Skip to main content

fedimint_client_module/
oplog.rs

1use std::fmt::Debug;
2use std::future;
3use std::time::SystemTime;
4
5use fedimint_core::core::{Account, OperationId};
6use fedimint_core::db::DatabaseTransaction;
7use fedimint_core::encoding::{
8    Decodable, DecodeError, Encodable, decode_field_from_finite_reader,
9    decode_legacy_system_time_from_finite_reader, encode_legacy_system_time, with_decoding_context,
10};
11use fedimint_core::module::registry::ModuleDecoderRegistry;
12use fedimint_core::task::{MaybeSend, MaybeSync};
13use fedimint_core::util::BoxStream;
14use fedimint_core::{apply, async_trait_maybe_send, maybe_add_send, maybe_add_send_sync};
15use futures::{StreamExt, stream};
16use serde::de::DeserializeOwned;
17use serde::{Deserialize, Serialize};
18
19/// Json value using string representation as db encoding.
20#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
21#[serde(transparent)]
22pub struct JsonStringed(pub serde_json::Value);
23
24impl Encodable for JsonStringed {
25    fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), std::io::Error> {
26        let json_str = serde_json::to_string(&self.0).expect("JSON serialization should not fail");
27        json_str.consensus_encode(writer)
28    }
29}
30
31impl Decodable for JsonStringed {
32    fn consensus_decode_partial<R: std::io::Read>(
33        r: &mut R,
34        modules: &ModuleDecoderRegistry,
35    ) -> Result<Self, DecodeError> {
36        let json_str = String::consensus_decode_partial(r, modules)?;
37        let value = serde_json::from_str(&json_str).map_err(DecodeError::from_err)?;
38        Ok(JsonStringed(value))
39    }
40}
41
42#[apply(async_trait_maybe_send!)]
43pub trait IOperationLog {
44    async fn get_operation(&self, operation_id: OperationId) -> Option<OperationLogEntry>;
45
46    async fn get_operation_dbtx(
47        &self,
48        dbtx: &mut DatabaseTransaction<'_>,
49        operation_id: OperationId,
50    ) -> Option<OperationLogEntry>;
51
52    async fn add_operation_log_entry_dbtx(
53        &self,
54        dbtx: &mut DatabaseTransaction<'_>,
55        operation_id: OperationId,
56        account: Account,
57        operation_type: &str,
58        operation_meta: serde_json::Value,
59    );
60
61    /// Wrap a module's operation update stream so that its last update is
62    /// cached as the operation's outcome — only when `is_terminal` reports
63    /// that update as a final state of the operation. Outcome resolution
64    /// (returning a cached outcome instead of a stream) happens in the typed
65    /// caller ([`crate::module::ClientContext::outcome_or_updates`]), which
66    /// can deserialize the cached value into the module's update type and
67    /// fall back to this stream when that fails.
68    fn caching_operation_update_stream(
69        &self,
70        operation_id: OperationId,
71        stream_gen: Box<maybe_add_send!(dyn FnOnce() -> BoxStream<'static, serde_json::Value>)>,
72        is_terminal: Box<maybe_add_send_sync!(dyn Fn(&serde_json::Value) -> bool)>,
73    ) -> BoxStream<'static, serde_json::Value>;
74}
75
76/// Represents the outcome of an operation, combining both the outcome value and
77/// its timestamp
78#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
79pub struct OperationOutcome {
80    pub time: SystemTime,
81    pub outcome: JsonStringed,
82}
83
84impl Encodable for OperationOutcome {
85    fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), std::io::Error> {
86        encode_legacy_system_time(&self.time, writer)?;
87        self.outcome.consensus_encode(writer)
88    }
89}
90
91impl Decodable for OperationOutcome {
92    fn consensus_decode_partial_from_finite_reader<R: std::io::Read>(
93        reader: &mut R,
94        modules: &ModuleDecoderRegistry,
95    ) -> Result<Self, DecodeError> {
96        Ok(Self {
97            time: with_decoding_context(
98                decode_legacy_system_time_from_finite_reader(reader, modules),
99                "Decoding named block field: OperationOutcome{ ... time ... }",
100            )?,
101            outcome: decode_field_from_finite_reader(
102                reader,
103                modules,
104                "Decoding named block field: OperationOutcome{ ... outcome ... }",
105            )?,
106        })
107    }
108}
109
110/// Represents an operation triggered by a user, typically related to sending or
111/// receiving money.
112///
113/// There are three levels of introspection possible for `OperationLogEntry`s:
114///   1. The [`OperationLogEntry::operation_module_kind`] function returns the
115///      kind of the module that created the operation.
116///   2. The [`OperationLogEntry::meta`] function returns static meta data that
117///      was associated with the operation when it was created. Modules define
118///      their own meta structures, so the module kind has to be used to
119///      determine the structure of the meta data.
120///   3. To find out the current state of the operation there is a two-step
121///      process:
122///      * First, the [`OperationLogEntry::outcome`] function returns the
123///        outcome if the operation finished **and** the update subscription
124///        stream has been processed till its end at least once.
125///      * If that isn't the case, the [`OperationLogEntry::outcome`] method
126///        will return `None` and the appropriate update subscription function
127///        has to be called. See the respective client extension trait for these
128///        functions.
129#[derive(Debug, Serialize, Deserialize, Encodable, Decodable)]
130pub struct OperationLogEntry {
131    pub(crate) operation_module_kind: String,
132    pub(crate) meta: JsonStringed,
133    // TODO: probably change all that JSON to Dyn-types
134    pub(crate) outcome: Option<OperationOutcome>,
135}
136
137impl OperationLogEntry {
138    pub fn new(
139        operation_module_kind: String,
140        meta: JsonStringed,
141        outcome: Option<OperationOutcome>,
142    ) -> Self {
143        Self {
144            operation_module_kind,
145            meta,
146            outcome,
147        }
148    }
149
150    /// Returns the kind of the module that generated the operation
151    pub fn operation_module_kind(&self) -> &str {
152        &self.operation_module_kind
153    }
154
155    /// Returns the meta data of the operation. This is a JSON value that can be
156    /// either returned as a [`serde_json::Value`] or deserialized into a
157    /// specific type. The specific type should be named `<Module>OperationMeta`
158    /// in the module's client crate. The module can be determined by calling
159    /// [`OperationLogEntry::operation_module_kind`].
160    pub fn meta<M: DeserializeOwned>(&self) -> M {
161        self.try_meta()
162            .expect("JSON deserialization should not fail")
163    }
164
165    /// Fallible version of [`OperationLogEntry::meta`]. Used to avoid panics in
166    /// the case of failed past migrations, resulting in invalid encodings in
167    /// the DB.
168    pub fn try_meta<M: DeserializeOwned>(&self) -> Result<M, serde_json::Error> {
169        serde_json::from_value(self.meta.0.clone())
170    }
171
172    /// Returns the last state update of the operation, if any was cached yet.
173    /// If this hasn't been the case yet and `None` is returned subscribe to the
174    /// appropriate update stream.
175    ///
176    /// ## Determining the return type
177    /// [`OperationLogEntry::meta`] should tell you the which operation type of
178    /// a given module the outcome belongs to. The operation type will have a
179    /// corresponding `async fn subscribe_type(&self, operation_id:
180    /// OperationId) -> Result<UpdateStreamOrOutcome<TypeState>, E>;`
181    /// function that returns a `UpdateStreamOrOutcome<S>` where `S` is the
182    /// high-level state the operation is in. If this state is terminal, i.e.
183    /// the stream closes after returning it, it will be cached as the `outcome`
184    /// of the operation.
185    ///
186    /// This means the type to be used for deserializing the outcome is `S`,
187    /// often called `<OperationType>State`. Alternatively one can also use
188    /// [`serde_json::Value`] to get the unstructured data.
189    pub fn outcome<D: DeserializeOwned>(&self) -> Option<D> {
190        self.try_outcome()
191            .expect("JSON deserialization should not fail")
192    }
193
194    /// Fallible version of [`OperationLogEntry::outcome`]. Used to avoid panics
195    /// in the case of failed past migrations, resulting in invalid encodings in
196    /// the DB.
197    pub fn try_outcome<D: DeserializeOwned>(&self) -> Result<Option<D>, serde_json::Error> {
198        self.outcome
199            .as_ref()
200            .map(|outcome| serde_json::from_value(outcome.outcome.0.clone()))
201            .transpose()
202    }
203
204    /// Returns the time when the outcome was cached.
205    pub fn outcome_time(&self) -> Option<SystemTime> {
206        self.outcome.as_ref().map(|o| o.time)
207    }
208
209    pub fn set_outcome(&mut self, outcome: impl Into<Option<OperationOutcome>>) {
210        self.outcome = outcome.into();
211    }
212}
213
214/// Either a stream of operation updates if the operation hasn't finished yet or
215/// its outcome otherwise.
216pub enum UpdateStreamOrOutcome<U> {
217    UpdateStream(BoxStream<'static, U>),
218    Outcome(U),
219}
220
221impl<U: Debug> Debug for UpdateStreamOrOutcome<U> {
222    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
223        match self {
224            UpdateStreamOrOutcome::UpdateStream(_) => write!(f, "UpdateStream"),
225            UpdateStreamOrOutcome::Outcome(o) => f.debug_tuple("Outcome").field(o).finish(),
226        }
227    }
228}
229
230impl<U> UpdateStreamOrOutcome<U>
231where
232    U: MaybeSend + MaybeSync + 'static,
233{
234    /// Returns a stream no matter if the operation is finished. If there
235    /// already is a cached outcome the stream will only return that, otherwise
236    /// all updates will be returned until the operation finishes.
237    pub fn into_stream(self) -> BoxStream<'static, U> {
238        match self {
239            UpdateStreamOrOutcome::UpdateStream(stream) => stream,
240            UpdateStreamOrOutcome::Outcome(outcome) => {
241                Box::pin(stream::once(future::ready(outcome)))
242            }
243        }
244    }
245
246    /// Awaits the outcome of the operation update stream, either by returning
247    /// the cached value or by consuming the entire stream and returning the
248    /// last update.
249    pub async fn await_outcome(self) -> Option<U> {
250        match self {
251            UpdateStreamOrOutcome::Outcome(outcome) => Some(outcome),
252            UpdateStreamOrOutcome::UpdateStream(mut stream) => {
253                let mut last_update = None;
254                while let Some(update) = stream.next().await {
255                    last_update = Some(update);
256                }
257                last_update
258            }
259        }
260    }
261}
262
263#[cfg(test)]
264mod tests;