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#[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 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#[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#[derive(Debug, Serialize, Deserialize, Encodable, Decodable)]
130pub struct OperationLogEntry {
131 pub(crate) operation_module_kind: String,
132 pub(crate) meta: JsonStringed,
133 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 pub fn operation_module_kind(&self) -> &str {
152 &self.operation_module_kind
153 }
154
155 pub fn meta<M: DeserializeOwned>(&self) -> M {
161 self.try_meta()
162 .expect("JSON deserialization should not fail")
163 }
164
165 pub fn try_meta<M: DeserializeOwned>(&self) -> Result<M, serde_json::Error> {
169 serde_json::from_value(self.meta.0.clone())
170 }
171
172 pub fn outcome<D: DeserializeOwned>(&self) -> Option<D> {
190 self.try_outcome()
191 .expect("JSON deserialization should not fail")
192 }
193
194 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 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
214pub 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 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 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;