Skip to main content

fedimint_client/sm/
executor.rs

1use std::collections::{BTreeMap, BTreeSet, HashSet};
2use std::convert::Infallible;
3use std::fmt::{Debug, Formatter};
4use std::io::{Error, Write};
5use std::mem;
6use std::sync::Arc;
7use std::time::Duration;
8
9use fedimint_client_module::sm::executor::{
10    ActiveStateKey, ContextGen, IExecutor, InactiveStateKey,
11};
12use fedimint_client_module::sm::{
13    ActiveStateMeta, ClientSMDatabaseTransaction, DynContext, DynState, InactiveStateMeta, State,
14    StateTransition, StateTransitionFunction,
15};
16use fedimint_core::core::{IntoDynInstance, ModuleInstanceId, OperationId};
17use fedimint_core::db::{
18    AutocommitError, Database, DatabaseKeyWithNotify, DatabaseTransaction,
19    IDatabaseTransactionOpsCoreTyped,
20};
21use fedimint_core::encoding::{Decodable, DecodeError, Encodable};
22use fedimint_core::fmt_utils::AbbreviateJson;
23use fedimint_core::module::registry::ModuleDecoderRegistry;
24use fedimint_core::task::TaskGroup;
25use fedimint_core::util::BoxFuture;
26use fedimint_core::{apply, async_trait_maybe_send};
27use fedimint_eventlog::{DBTransactionEventLogExt as _, Event, EventKind, EventPersistence};
28use fedimint_logging::LOG_CLIENT_REACTOR;
29use futures::future::{self, select_all};
30use futures::stream::{FuturesUnordered, StreamExt};
31use serde::{Deserialize, Serialize};
32use tokio::select;
33use tokio::sync::{mpsc, oneshot, watch};
34use tracing::{Instrument, debug, error, info, trace, warn};
35
36use crate::sm::notifier::Notifier;
37use crate::{AddStateMachinesError, AddStateMachinesResult, DynGlobalClientContext};
38
39/// After how many attempts a DB transaction is aborted with an error
40const MAX_DB_ATTEMPTS: Option<usize> = Some(100);
41
42/// Prefixes for executor DB entries
43pub(crate) enum ExecutorDbPrefixes {
44    /// See [`ActiveStateKey`]
45    ActiveStates = 0xa1,
46    /// See [`InactiveStateKey`]
47    InactiveStates = 0xa2,
48}
49
50#[derive(Serialize, Deserialize)]
51pub struct StateMachineUpdated {
52    operation_id: OperationId,
53    started: bool,
54    terminal: bool,
55    module_id: ModuleInstanceId,
56}
57
58impl Event for StateMachineUpdated {
59    const MODULE: Option<fedimint_core::core::ModuleKind> = None;
60    const KIND: EventKind = EventKind::from_static("sm-updated");
61    const PERSISTENCE: EventPersistence = EventPersistence::Trimable;
62}
63
64/// Executor that drives forward state machines under its management.
65///
66/// Each state transition is atomic and supposed to be idempotent such that a
67/// stop/crash of the executor at any point can be recovered from on restart.
68/// The executor is aware of the concept of Fedimint modules and can give state
69/// machines a different [execution context](crate::module::sm::Context)
70/// depending on the owning module, making it very flexible.
71#[derive(Clone, Debug)]
72pub struct Executor {
73    inner: Arc<ExecutorInner>,
74}
75
76struct ExecutorInner {
77    db: Database,
78    state: std::sync::RwLock<ExecutorState>,
79    module_contexts: BTreeMap<ModuleInstanceId, DynContext>,
80    valid_module_ids: BTreeSet<ModuleInstanceId>,
81    notifier: Notifier,
82    /// Any time executor should notice state machine update (e.g. because it
83    /// was created), it's must be sent through this channel for it to notice.
84    sm_update_tx: mpsc::UnboundedSender<DynState>,
85    client_task_group: TaskGroup,
86    log_ordering_wakeup_tx: watch::Sender<()>,
87}
88
89enum ExecutorState {
90    Unstarted {
91        sm_update_rx: mpsc::UnboundedReceiver<DynState>,
92    },
93    Running {
94        context_gen: ContextGen,
95        shutdown_sender: oneshot::Sender<()>,
96    },
97    Stopped,
98}
99
100impl ExecutorState {
101    /// Starts the executor, returning a receiver that will be signalled when
102    /// the executor is stopped and a receiver for state machine updates.
103    /// Returns `None` if the executor has already been started and/or stopped.
104    fn start(
105        &mut self,
106        context: ContextGen,
107    ) -> Option<(oneshot::Receiver<()>, mpsc::UnboundedReceiver<DynState>)> {
108        let (shutdown_sender, shutdown_receiver) = tokio::sync::oneshot::channel::<()>();
109
110        let previous_state = mem::replace(
111            self,
112            ExecutorState::Running {
113                context_gen: context,
114                shutdown_sender,
115            },
116        );
117
118        match previous_state {
119            ExecutorState::Unstarted { sm_update_rx } => Some((shutdown_receiver, sm_update_rx)),
120            _ => {
121                // Replace the previous state, undoing the `mem::replace` above.
122                *self = previous_state;
123
124                debug!(target: LOG_CLIENT_REACTOR, "Executor already started, ignoring start request");
125                None
126            }
127        }
128    }
129
130    /// Stops the executor, returning `Some(())` if the executor was running and
131    /// `None` if it was in any other state.
132    fn stop(&mut self) -> Option<()> {
133        let previous_state = mem::replace(self, ExecutorState::Stopped);
134
135        match previous_state {
136            ExecutorState::Running {
137                shutdown_sender, ..
138            } => {
139                if shutdown_sender.send(()).is_err() {
140                    warn!(target: LOG_CLIENT_REACTOR, "Failed to send shutdown signal to executor, already dead?");
141                }
142                Some(())
143            }
144            _ => {
145                // Replace the previous state, undoing the `mem::replace` above.
146                *self = previous_state;
147
148                debug!(target: LOG_CLIENT_REACTOR, "Executor not running, ignoring stop request");
149                None
150            }
151        }
152    }
153
154    fn gen_context(&self, state: &DynState) -> Option<DynGlobalClientContext> {
155        let ExecutorState::Running { context_gen, .. } = self else {
156            return None;
157        };
158        Some(context_gen(
159            state.module_instance_id(),
160            state.operation_id(),
161        ))
162    }
163}
164
165/// Builder to which module clients can be attached and used to build an
166/// [`Executor`] supporting these.
167#[derive(Debug, Default)]
168pub struct ExecutorBuilder {
169    module_contexts: BTreeMap<ModuleInstanceId, DynContext>,
170    valid_module_ids: BTreeSet<ModuleInstanceId>,
171}
172
173impl Executor {
174    /// Creates an [`ExecutorBuilder`]
175    pub fn builder() -> ExecutorBuilder {
176        ExecutorBuilder::default()
177    }
178
179    pub async fn get_active_states(&self) -> Vec<(DynState, ActiveStateMeta)> {
180        self.inner.get_active_states().await
181    }
182
183    /// Adds a number of state machines to the executor atomically. They will be
184    /// driven to completion automatically in the background.
185    ///
186    /// **Attention**: do not use before background task is started!
187    // TODO: remove warning once finality is an inherent state attribute
188    pub async fn add_state_machines(
189        &self,
190        states: Vec<DynState>,
191    ) -> Result<(), AddStateMachinesError> {
192        self.inner
193            .db
194            .autocommit(
195                |dbtx, _| Box::pin(self.add_state_machines_dbtx(dbtx, states.clone())),
196                MAX_DB_ATTEMPTS,
197            )
198            .await
199            .map_err(|e| match e {
200                AutocommitError::CommitFailed { last_error, .. } => {
201                    AddStateMachinesError::Database(last_error)
202                }
203                AutocommitError::ClosureError { error, .. } => error,
204            })?;
205
206        // TODO: notify subscribers to state changes?
207
208        Ok(())
209    }
210
211    /// Adds a number of state machines to the executor atomically with other DB
212    /// changes is `dbtx`. See [`Executor::add_state_machines`] for more
213    /// details.
214    ///
215    /// ## Panics
216    /// If called before background task is started using
217    /// [`Executor::start_executor`]!
218    // TODO: remove warning once finality is an inherent state attribute
219    pub async fn add_state_machines_dbtx(
220        &self,
221        dbtx: &mut DatabaseTransaction<'_>,
222        states: Vec<DynState>,
223    ) -> AddStateMachinesResult {
224        for state in states {
225            if !self
226                .inner
227                .valid_module_ids
228                .contains(&state.module_instance_id())
229            {
230                return Err(AddStateMachinesError::UnknownModule {
231                    module_instance_id: state.module_instance_id(),
232                });
233            }
234
235            let is_active_state = dbtx
236                .get_value(&ActiveStateKeyDb(ActiveStateKey::from_state(state.clone())))
237                .await
238                .is_some();
239            let is_inactive_state = dbtx
240                .get_value(&InactiveStateKeyDb(InactiveStateKey::from_state(
241                    state.clone(),
242                )))
243                .await
244                .is_some();
245
246            if is_active_state || is_inactive_state {
247                return Err(AddStateMachinesError::StateAlreadyExists);
248            }
249
250            // In case of recovery functions, the module itself is not yet initialized,
251            // so we can't check if the state is terminal. However the
252            // [`Self::get_transitions_for`] function will double check and
253            // deactivate any terminal states that would slip past this check.
254            if let Some(module_context) =
255                self.inner.module_contexts.get(&state.module_instance_id())
256            {
257                match self
258                    .inner
259                    .state
260                    .read()
261                    .expect("locking failed")
262                    .gen_context(&state)
263                {
264                    Some(context) => {
265                        if state.is_terminal(module_context, &context) {
266                            return Err(AddStateMachinesError::StateAlreadyTerminal);
267                        }
268                    }
269                    _ => {
270                        warn!(target: LOG_CLIENT_REACTOR, "Executor should be running at this point");
271                    }
272                }
273            }
274
275            dbtx.insert_new_entry(
276                &ActiveStateKeyDb(ActiveStateKey::from_state(state.clone())),
277                &ActiveStateMeta::default(),
278            )
279            .await;
280
281            let operation_id = state.operation_id();
282            self.inner
283                .log_event_dbtx(
284                    dbtx,
285                    StateMachineUpdated {
286                        operation_id,
287                        started: true,
288                        terminal: false,
289                        module_id: state.module_instance_id(),
290                    },
291                )
292                .await;
293
294            let notify_sender = self.inner.notifier.sender();
295            let sm_updates_tx = self.inner.sm_update_tx.clone();
296            dbtx.on_commit(move || {
297                notify_sender.notify(state.clone());
298                let _ = sm_updates_tx.send(state);
299            });
300        }
301
302        Ok(())
303    }
304
305    /// **Mostly used for testing**
306    ///
307    /// Check if state exists in the database as part of an actively running
308    /// state machine.
309    pub async fn contains_active_state<S: State>(
310        &self,
311        instance: ModuleInstanceId,
312        state: S,
313    ) -> bool {
314        let state = DynState::from_typed(instance, state);
315        self.inner
316            .get_active_states()
317            .await
318            .into_iter()
319            .any(|(s, _)| s == state)
320    }
321
322    // TODO: unify querying fns
323    /// **Mostly used for testing**
324    ///
325    /// Check if state exists in the database as inactive. If the state is
326    /// terminal it means the corresponding state machine finished its
327    /// execution. If the state is non-terminal it means the state machine was
328    /// in that state at some point but moved on since then.
329    pub async fn contains_inactive_state<S: State>(
330        &self,
331        instance: ModuleInstanceId,
332        state: S,
333    ) -> bool {
334        let state = DynState::from_typed(instance, state);
335        self.inner
336            .get_inactive_states()
337            .await
338            .into_iter()
339            .any(|(s, _)| s == state)
340    }
341
342    pub async fn await_inactive_state(&self, state: DynState) -> InactiveStateMeta {
343        self.inner
344            .db
345            .wait_key_exists(&InactiveStateKeyDb(InactiveStateKey::from_state(state)))
346            .await
347    }
348
349    pub async fn await_active_state(&self, state: DynState) -> ActiveStateMeta {
350        self.inner
351            .db
352            .wait_key_exists(&ActiveStateKeyDb(ActiveStateKey::from_state(state)))
353            .await
354    }
355
356    /// Only meant for debug tooling
357    pub async fn get_operation_states(
358        &self,
359        operation_id: OperationId,
360    ) -> (
361        Vec<(DynState, ActiveStateMeta)>,
362        Vec<(DynState, InactiveStateMeta)>,
363    ) {
364        let mut dbtx = self.inner.db.begin_transaction_nc().await;
365        let active_states: Vec<_> = dbtx
366            .find_by_prefix(&ActiveOperationStateKeyPrefix { operation_id })
367            .await
368            .map(|(active_key, active_meta)| (active_key.0.state, active_meta))
369            .collect()
370            .await;
371        let inactive_states: Vec<_> = dbtx
372            .find_by_prefix(&InactiveOperationStateKeyPrefix { operation_id })
373            .await
374            .map(|(active_key, inactive_meta)| (active_key.0.state, inactive_meta))
375            .collect()
376            .await;
377
378        (active_states, inactive_states)
379    }
380
381    /// Starts the background thread that runs the state machines. This cannot
382    /// be done when building the executor since some global contexts in turn
383    /// may depend on the executor, forming a cyclic dependency.
384    ///
385    /// ## Panics
386    /// If called more than once.
387    pub fn start_executor(&self, context_gen: ContextGen, client_span: tracing::Span) {
388        let Some((shutdown_receiver, sm_update_rx)) = self
389            .inner
390            .state
391            .write()
392            .expect("locking can't fail")
393            .start(context_gen.clone())
394        else {
395            panic!("start_executor was called previously");
396        };
397
398        let task_runner_inner = self.inner.clone();
399        let _handle = self.inner.client_task_group.spawn_with_span(
400            client_span,
401            "sm-executor",
402            |task_handle| async move {
403                let executor_runner = task_runner_inner.run(context_gen, sm_update_rx);
404                let task_group_shutdown_rx = task_handle.make_shutdown_rx();
405                select! {
406                    () = task_group_shutdown_rx => {
407                        debug!(
408                            target: LOG_CLIENT_REACTOR,
409                            "Shutting down state machine executor runner due to task group shutdown signal"
410                        );
411                    },
412                    shutdown_happened_sender = shutdown_receiver => {
413                        match shutdown_happened_sender {
414                            Ok(()) => {
415                                debug!(
416                                    target: LOG_CLIENT_REACTOR,
417                                    "Shutting down state machine executor runner due to explicit shutdown signal"
418                                );
419                            },
420                            Err(_) => {
421                                warn!(
422                                    target: LOG_CLIENT_REACTOR,
423                                    "Shutting down state machine executor runner because the shutdown signal channel was closed (the executor object was dropped)"
424                                );
425                            }
426                        }
427                    },
428                    () = executor_runner => {
429                        error!(target: LOG_CLIENT_REACTOR, "State machine executor runner exited unexpectedly!");
430                    },
431                };
432            },
433        );
434    }
435
436    /// Stops the background task that runs the state machines.
437    ///
438    /// If a shutdown signal was sent it returns a [`oneshot::Receiver`] that
439    /// will be signalled when the main loop of the background task has
440    /// exited. This can be useful to block until the executor has stopped
441    /// to avoid errors due to the async runtime shutting down while the
442    /// task is still running.
443    ///
444    /// If no shutdown signal was sent it returns `None`. This can happen if
445    /// `stop_executor` is called multiple times.
446    ///
447    /// ## Panics
448    /// If called in parallel with [`start_executor`](Self::start_executor).
449    pub fn stop_executor(&self) -> Option<()> {
450        self.inner.stop_executor()
451    }
452
453    /// Returns a reference to the [`Notifier`] that can be used to subscribe to
454    /// state transitions
455    pub fn notifier(&self) -> &Notifier {
456        &self.inner.notifier
457    }
458}
459
460impl Drop for ExecutorInner {
461    fn drop(&mut self) {
462        self.stop_executor();
463    }
464}
465
466struct TransitionForActiveState {
467    outcome: serde_json::Value,
468    state: DynState,
469    meta: ActiveStateMeta,
470    transition_fn: StateTransitionFunction<DynState>,
471}
472
473impl ExecutorInner {
474    async fn run(
475        &self,
476        global_context_gen: ContextGen,
477        sm_update_rx: tokio::sync::mpsc::UnboundedReceiver<DynState>,
478    ) {
479        debug!(target: LOG_CLIENT_REACTOR, "Starting state machine executor task");
480        self.run_state_machines_executor_inner(global_context_gen, sm_update_rx)
481            .await;
482    }
483
484    async fn get_transition_for(
485        &self,
486        state: &DynState,
487        meta: ActiveStateMeta,
488        global_context_gen: &ContextGen,
489    ) -> Vec<BoxFuture<'static, TransitionForActiveState>> {
490        let module_instance = state.module_instance_id();
491        let context = &self
492            .module_contexts
493            .get(&module_instance)
494            .expect("Unknown module");
495        let transitions = state
496            .transitions(
497                context,
498                &global_context_gen(module_instance, state.operation_id()),
499            )
500            .into_iter()
501            .map(|transition| {
502                let state = state.clone();
503                let f: BoxFuture<TransitionForActiveState> = Box::pin(async move {
504                    let StateTransition {
505                        trigger,
506                        transition,
507                    } = transition;
508                    TransitionForActiveState {
509                        outcome: trigger.await,
510                        state,
511                        transition_fn: transition,
512                        meta,
513                    }
514                });
515                f
516            })
517            .collect::<Vec<_>>();
518        if transitions.is_empty() {
519            // In certain cases a terminal (no transitions) state could get here due to
520            // module bug. Inactivate it to prevent accumulation of such states.
521            // See [`Self::add_state_machines_dbtx`].
522            warn!(
523                target: LOG_CLIENT_REACTOR,
524                module_id = module_instance, "A terminal state where only active states are expected. Please report this bug upstream."
525            );
526            self.db
527                .autocommit::<_, _, Infallible>(
528                    |dbtx, _| {
529                        Box::pin(async {
530                            let k = InactiveStateKey::from_state(state.clone());
531                            let v = ActiveStateMeta::default().into_inactive();
532                            dbtx.remove_entry(&ActiveStateKeyDb(ActiveStateKey::from_state(
533                                state.clone(),
534                            )))
535                            .await;
536                            dbtx.insert_entry(&InactiveStateKeyDb(k), &v).await;
537                            Ok(())
538                        })
539                    },
540                    None,
541                )
542                .await
543                .expect("Autocommit here can't fail");
544        }
545
546        transitions
547    }
548
549    async fn run_state_machines_executor_inner(
550        &self,
551        global_context_gen: ContextGen,
552        mut sm_update_rx: tokio::sync::mpsc::UnboundedReceiver<DynState>,
553    ) {
554        /// All futures in the executor resolve to this type, so the handling
555        /// code can tell them apart.
556        enum ExecutorLoopEvent {
557            /// Notification about `DynState` arrived and should be handled,
558            /// usually added to the list of pending futures.
559            New { state: DynState },
560            /// One of trigger futures of a state machine finished and
561            /// returned transition function to run
562            Triggered(TransitionForActiveState),
563            /// The state machine did not need to run, so it was canceled
564            Invalid { state: DynState },
565            /// Transition function and all the accounting around it are done
566            Completed {
567                state: DynState,
568                outcome: ActiveOrInactiveState,
569            },
570            /// New job receiver disconnected, that can only mean termination
571            Disconnected,
572        }
573
574        let active_states = self.get_active_states().await;
575        debug!(
576            target: LOG_CLIENT_REACTOR,
577            total = active_states.len(),
578            "Starting active state machines",
579        );
580        for (state, meta) in active_states {
581            trace!(target: LOG_CLIENT_REACTOR, ?state, ?meta, "Starting active state");
582
583            let age = fedimint_core::time::now()
584                .duration_since(meta.created_at)
585                .unwrap_or_default();
586            if age > Duration::from_secs(7 * 24 * 3600) {
587                warn!(
588                    target: LOG_CLIENT_REACTOR,
589                    operation_id = %state.operation_id().fmt_short(),
590                    module_instance = %state.module_instance_id(),
591                    age_days = age.as_secs() / 86400,
592                    "Active state machine has been running for over a week, possibly stuck",
593                );
594            }
595            self.sm_update_tx
596                .send(state)
597                .expect("Must be able to send state machine to own opened channel");
598        }
599
600        // Keeps track of things already running, so we can deduplicate, just
601        // in case.
602        let mut currently_running_sms = HashSet::<DynState>::new();
603        // All things happening in parallel go into here
604        // NOTE: `FuturesUnordered` is a footgun: when it's not being polled
605        // (e.g. we picked an event and are awaiting on something to process it),
606        // nothing inside `futures` will be making progress, which in extreme cases
607        // could lead to hangs. For this reason we try really hard in the code here,
608        // to pick an event from `futures` and spawn a new task, avoiding any `await`,
609        // just so we can get back to `futures.next()` ASAP.
610        let mut futures: FuturesUnordered<BoxFuture<'_, ExecutorLoopEvent>> =
611            FuturesUnordered::new();
612
613        loop {
614            let event = tokio::select! {
615                new = sm_update_rx.recv() => {
616                    match new { Some(new) => {
617                        ExecutorLoopEvent::New {
618                            state: new,
619                        }
620                    } _ => {
621                        ExecutorLoopEvent::Disconnected
622                    }}
623                },
624
625                event = futures.next(), if !futures.is_empty() => event.expect("we only .next() if there are pending futures"),
626            };
627
628            // main reactor loop: wait for next thing that completed, react (possibly adding
629            // more things to `futures`)
630            match event {
631                ExecutorLoopEvent::New { state } => {
632                    if currently_running_sms.contains(&state) {
633                        warn!(target: LOG_CLIENT_REACTOR, operation_id = %state.operation_id().fmt_short(), "Received a state machine that is already running. Ignoring");
634                        continue;
635                    }
636                    currently_running_sms.insert(state.clone());
637                    let futures_len = futures.len();
638                    let global_context_gen = &global_context_gen;
639                    trace!(target: LOG_CLIENT_REACTOR, state = ?state, "Started new active state machine, details.");
640                    futures.push(Box::pin(async move {
641                        let Some(meta) = self.get_active_state(&state).await else {
642                            warn!(target: LOG_CLIENT_REACTOR, operation_id = %state.operation_id().fmt_short(), "Couldn't look up received state machine. Ignoring.");
643                            return ExecutorLoopEvent::Invalid { state: state.clone() };
644                        };
645
646                        let transitions = self
647                            .get_transition_for(&state, meta, global_context_gen)
648                            .await;
649                        if transitions.is_empty() {
650                            warn!(target: LOG_CLIENT_REACTOR, operation_id = %state.operation_id().fmt_short(), "Received an active state that doesn't produce any transitions. Ignoring.");
651                            return ExecutorLoopEvent::Invalid { state: state.clone() };
652                        }
653                        let transitions_num = transitions.len();
654
655                        debug!(target: LOG_CLIENT_REACTOR, operation_id = %state.operation_id().fmt_short(), total = futures_len + 1, transitions_num, "New active state machine.");
656
657                        let (first_completed_result, _index, _unused_transitions) =
658                            select_all(transitions).await;
659                        ExecutorLoopEvent::Triggered(first_completed_result)
660                    }));
661                }
662                ExecutorLoopEvent::Triggered(TransitionForActiveState {
663                    outcome,
664                    state,
665                    meta,
666                    transition_fn,
667                }) => {
668                    debug!(
669                        target: LOG_CLIENT_REACTOR,
670                        operation_id = %state.operation_id().fmt_short(),
671                        "Triggered state transition",
672                    );
673                    let span = tracing::debug_span!(
674                        target: LOG_CLIENT_REACTOR,
675                        "sm_transition",
676                        operation_id = %state.operation_id().fmt_short()
677                    );
678                    // Perform the transition as another future, so transitions can happen in
679                    // parallel.
680                    // Database write conflicts might be happening quite often here,
681                    // but transaction functions are supposed to be idempotent anyway,
682                    // so it seems like a good stress-test in the worst case.
683                    futures.push({
684                        let sm_update_tx = self.sm_update_tx.clone();
685                        let db = self.db.clone();
686                        let notifier = self.notifier.clone();
687                        let module_contexts = self.module_contexts.clone();
688                        let global_context_gen = global_context_gen.clone();
689                        Box::pin(
690                            async move {
691                                debug!(
692                                    target: LOG_CLIENT_REACTOR,
693                                    "Executing state transition",
694                                );
695                                trace!(
696                                    target: LOG_CLIENT_REACTOR,
697                                    ?state,
698                                    outcome = ?AbbreviateJson(&outcome),
699                                    "Executing state transition (details)",
700                                );
701
702                                let module_contexts = &module_contexts;
703                                let global_context_gen = &global_context_gen;
704
705                                let outcome = db
706                                    .autocommit::<'_, '_, _, _, Infallible>(
707                                        |dbtx, _| {
708                                            let state = state.clone();
709                                            let state_module_instance_id = state.module_instance_id();
710                                            let transition_fn = transition_fn.clone();
711                                            let transition_outcome = outcome.clone();
712                                            Box::pin(async move {
713                                                let new_state = transition_fn(
714                                                    &mut ClientSMDatabaseTransaction::new(
715                                                        &mut dbtx.to_ref(),
716                                                        state.module_instance_id(),
717                                                    ),
718                                                    transition_outcome.clone(),
719                                                    state.clone(),
720                                                )
721                                                .await;
722                                                dbtx.remove_entry(&ActiveStateKeyDb(ActiveStateKey::from_state(
723                                                    state.clone(),
724                                                )))
725                                                .await;
726                                                dbtx.insert_entry(
727                                                    &InactiveStateKeyDb(InactiveStateKey::from_state(state.clone())),
728                                                    &meta.into_inactive(),
729                                                )
730                                                .await;
731
732                                                let context = &module_contexts
733                                                    .get(&state.module_instance_id())
734                                                    .expect("Unknown module");
735
736                                                let operation_id = state.operation_id();
737                                                let global_context = global_context_gen(
738                                                    state.module_instance_id(),
739                                                    operation_id,
740                                                );
741
742                                                let is_terminal = new_state.is_terminal(context, &global_context);
743
744                                                self.log_event_dbtx(dbtx,
745                                                    StateMachineUpdated{
746                                                        started: false,
747                                                        operation_id,
748                                                        module_id: state_module_instance_id,
749                                                        terminal: is_terminal,
750                                                    }
751                                                ).await;
752
753                                                if is_terminal {
754                                                    let k = InactiveStateKey::from_state(
755                                                        new_state.clone(),
756                                                    );
757                                                    let v = ActiveStateMeta::default().into_inactive();
758                                                    dbtx.insert_entry(&InactiveStateKeyDb(k), &v).await;
759                                                    Ok(ActiveOrInactiveState::Inactive {
760                                                        dyn_state: new_state,
761                                                    })
762                                                } else {
763                                                    let k = ActiveStateKey::from_state(
764                                                        new_state.clone(),
765                                                    );
766                                                    let v = ActiveStateMeta::default();
767                                                    dbtx.insert_entry(&ActiveStateKeyDb(k), &v).await;
768                                                    Ok(ActiveOrInactiveState::Active {
769                                                        dyn_state: new_state,
770                                                        meta: v,
771                                                    })
772                                                }
773                                            })
774                                        },
775                                        None,
776                                    )
777                                    .await
778                                    .expect("autocommit should keep trying to commit (max_attempt: None) and body doesn't return errors");
779
780                                debug!(
781                                    target: LOG_CLIENT_REACTOR,
782                                    terminal = !outcome.is_active(),
783                                    ?outcome,
784                                    "State transition complete",
785                                );
786
787                                match &outcome {
788                                    ActiveOrInactiveState::Active { dyn_state, meta: _ } => {
789                                        sm_update_tx
790                                            .send(dyn_state.clone())
791                                            .expect("can't fail: we are the receiving end");
792                                        notifier.notify(dyn_state.clone());
793                                    }
794                                    ActiveOrInactiveState::Inactive { dyn_state } => {
795                                        notifier.notify(dyn_state.clone());
796                                    }
797                                }
798                                ExecutorLoopEvent::Completed { state, outcome }
799                            }
800                            .instrument(span),
801                        )
802                    });
803                }
804                ExecutorLoopEvent::Invalid { state } => {
805                    trace!(
806                        target: LOG_CLIENT_REACTOR,
807                        operation_id = %state.operation_id().fmt_short(), total = futures.len(),
808                        "State invalid"
809                    );
810                    assert!(
811                        currently_running_sms.remove(&state),
812                        "State must have been recorded"
813                    );
814                }
815
816                ExecutorLoopEvent::Completed { state, outcome } => {
817                    assert!(
818                        currently_running_sms.remove(&state),
819                        "State must have been recorded"
820                    );
821                    debug!(
822                        target: LOG_CLIENT_REACTOR,
823                        operation_id = %state.operation_id().fmt_short(),
824                        outcome_active = outcome.is_active(),
825                        total = futures.len(),
826                        "State transition complete"
827                    );
828                    trace!(
829                        target: LOG_CLIENT_REACTOR,
830                        ?outcome,
831                        operation_id = %state.operation_id().fmt_short(), total = futures.len(),
832                        "State transition complete"
833                    );
834                }
835                ExecutorLoopEvent::Disconnected => {
836                    break;
837                }
838            }
839        }
840
841        info!(target: LOG_CLIENT_REACTOR, "Terminated.");
842    }
843
844    async fn get_active_states(&self) -> Vec<(DynState, ActiveStateMeta)> {
845        self.db
846            .begin_transaction_nc()
847            .await
848            .find_by_prefix(&ActiveStateKeyPrefix)
849            .await
850            // ignore states from modules that are not initialized yet
851            .filter(|(state, _)| {
852                future::ready(
853                    self.module_contexts
854                        .contains_key(&state.0.state.module_instance_id()),
855                )
856            })
857            .map(|(state, meta)| (state.0.state, meta))
858            .collect::<Vec<_>>()
859            .await
860    }
861
862    async fn get_active_state(&self, state: &DynState) -> Option<ActiveStateMeta> {
863        // ignore states from modules that are not initialized yet
864        if !self
865            .module_contexts
866            .contains_key(&state.module_instance_id())
867        {
868            return None;
869        }
870        self.db
871            .begin_transaction_nc()
872            .await
873            .get_value(&ActiveStateKeyDb(ActiveStateKey::from_state(state.clone())))
874            .await
875    }
876
877    async fn get_inactive_states(&self) -> Vec<(DynState, InactiveStateMeta)> {
878        self.db
879            .begin_transaction_nc()
880            .await
881            .find_by_prefix(&InactiveStateKeyPrefix)
882            .await
883            // ignore states from modules that are not initialized yet
884            .filter(|(state, _)| {
885                future::ready(
886                    self.module_contexts
887                        .contains_key(&state.0.state.module_instance_id()),
888                )
889            })
890            .map(|(state, meta)| (state.0.state, meta))
891            .collect::<Vec<_>>()
892            .await
893    }
894
895    pub async fn log_event_dbtx<E, Cap>(&self, dbtx: &mut DatabaseTransaction<'_, Cap>, event: E)
896    where
897        E: Event + Send,
898        Cap: Send,
899    {
900        dbtx.log_event(self.log_ordering_wakeup_tx.clone(), None, event)
901            .await;
902    }
903}
904
905impl ExecutorInner {
906    /// See [`Executor::stop_executor`].
907    fn stop_executor(&self) -> Option<()> {
908        // This runs from destructors, which must never panic, so recover from a lock
909        // poisoned by a panic elsewhere. `ExecutorState` is always left in a coherent
910        // variant, so the poison can be ignored safely.
911        let mut state = self
912            .state
913            .write()
914            .unwrap_or_else(std::sync::PoisonError::into_inner);
915
916        state.stop()
917    }
918}
919
920impl Debug for ExecutorInner {
921    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
922        writeln!(f, "ExecutorInner {{}}")
923    }
924}
925
926impl ExecutorBuilder {
927    /// Allow executor being built to run state machines associated with the
928    /// supplied module
929    pub fn with_module<C>(&mut self, instance_id: ModuleInstanceId, context: C)
930    where
931        C: IntoDynInstance<DynType = DynContext>,
932    {
933        self.with_module_dyn(context.into_dyn(instance_id));
934    }
935
936    /// Allow executor being built to run state machines associated with the
937    /// supplied module
938    pub fn with_module_dyn(&mut self, context: DynContext) {
939        self.valid_module_ids.insert(context.module_instance_id());
940
941        if self
942            .module_contexts
943            .insert(context.module_instance_id(), context)
944            .is_some()
945        {
946            panic!("Tried to add two modules with the same instance id!");
947        }
948    }
949
950    /// Allow executor to build state machines associated with the module id,
951    /// for which the module itself might not be available yet (otherwise it
952    /// would be registered with `[Self::with_module_dyn]`).
953    pub fn with_valid_module_id(&mut self, module_id: ModuleInstanceId) {
954        self.valid_module_ids.insert(module_id);
955    }
956
957    /// Build [`Executor`] and spawn background task in `tasks` executing active
958    /// state machines. The supplied database `db` must support isolation, so
959    /// cannot be an isolated DB instance itself.
960    pub fn build(
961        self,
962        db: Database,
963        notifier: Notifier,
964        client_task_group: TaskGroup,
965        log_ordering_wakeup_tx: watch::Sender<()>,
966    ) -> Executor {
967        let (sm_update_tx, sm_update_rx) = tokio::sync::mpsc::unbounded_channel();
968
969        let inner = Arc::new(ExecutorInner {
970            db,
971            log_ordering_wakeup_tx,
972            state: std::sync::RwLock::new(ExecutorState::Unstarted { sm_update_rx }),
973            module_contexts: self.module_contexts,
974            valid_module_ids: self.valid_module_ids,
975            notifier,
976            sm_update_tx,
977            client_task_group,
978        });
979
980        debug!(
981            target: LOG_CLIENT_REACTOR,
982            instances = ?inner.module_contexts.keys().copied().collect::<Vec<_>>(),
983            "Initialized state machine executor with module instances"
984        );
985        Executor { inner }
986    }
987}
988#[derive(Debug)]
989pub struct ActiveOperationStateKeyPrefix {
990    pub operation_id: OperationId,
991}
992
993impl Encodable for ActiveOperationStateKeyPrefix {
994    fn consensus_encode<W: Write>(&self, writer: &mut W) -> Result<(), Error> {
995        self.operation_id.consensus_encode(writer)
996    }
997}
998
999impl ::fedimint_core::db::DatabaseLookup for ActiveOperationStateKeyPrefix {
1000    type Record = ActiveStateKeyDb;
1001}
1002
1003#[derive(Debug)]
1004pub(crate) struct ActiveModuleOperationStateKeyPrefix {
1005    pub operation_id: OperationId,
1006    pub module_instance: ModuleInstanceId,
1007}
1008
1009impl Encodable for ActiveModuleOperationStateKeyPrefix {
1010    fn consensus_encode<W: Write>(&self, writer: &mut W) -> Result<(), Error> {
1011        self.operation_id.consensus_encode(writer)?;
1012        self.module_instance.consensus_encode(writer)?;
1013        Ok(())
1014    }
1015}
1016
1017impl ::fedimint_core::db::DatabaseLookup for ActiveModuleOperationStateKeyPrefix {
1018    type Record = ActiveStateKeyDb;
1019}
1020
1021#[derive(Debug)]
1022pub struct ActiveStateKeyPrefix;
1023
1024impl Encodable for ActiveStateKeyPrefix {
1025    fn consensus_encode<W: Write>(&self, _writer: &mut W) -> Result<(), Error> {
1026        Ok(())
1027    }
1028}
1029
1030#[derive(Encodable, Decodable, Debug)]
1031pub struct ActiveStateKeyDb(pub fedimint_client_module::sm::executor::ActiveStateKey);
1032
1033impl ::fedimint_core::db::DatabaseRecord for ActiveStateKeyDb {
1034    const DB_PREFIX: u8 = ExecutorDbPrefixes::ActiveStates as u8;
1035    const NOTIFY_ON_MODIFY: bool = true;
1036    type Key = Self;
1037    type Value = ActiveStateMeta;
1038}
1039
1040impl DatabaseKeyWithNotify for ActiveStateKeyDb {}
1041
1042impl ::fedimint_core::db::DatabaseLookup for ActiveStateKeyPrefix {
1043    type Record = ActiveStateKeyDb;
1044}
1045
1046#[derive(Debug, Encodable, Decodable)]
1047pub struct ActiveStateKeyPrefixBytes;
1048
1049impl ::fedimint_core::db::DatabaseRecord for ActiveStateKeyBytes {
1050    const DB_PREFIX: u8 = ExecutorDbPrefixes::ActiveStates as u8;
1051    const NOTIFY_ON_MODIFY: bool = false;
1052    type Key = Self;
1053    type Value = ActiveStateMeta;
1054}
1055
1056impl ::fedimint_core::db::DatabaseLookup for ActiveStateKeyPrefixBytes {
1057    type Record = ActiveStateKeyBytes;
1058}
1059
1060#[derive(Encodable, Decodable, Debug)]
1061pub struct InactiveStateKeyDb(pub fedimint_client_module::sm::executor::InactiveStateKey);
1062
1063#[derive(Debug)]
1064pub struct InactiveStateKeyBytes {
1065    pub operation_id: OperationId,
1066    pub module_instance_id: ModuleInstanceId,
1067    pub state: Vec<u8>,
1068}
1069
1070impl Encodable for InactiveStateKeyBytes {
1071    fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), std::io::Error> {
1072        self.operation_id.consensus_encode(writer)?;
1073        writer.write_all(self.state.as_slice())?;
1074        Ok(())
1075    }
1076}
1077
1078impl Decodable for InactiveStateKeyBytes {
1079    fn consensus_decode_partial<R: std::io::Read>(
1080        reader: &mut R,
1081        modules: &ModuleDecoderRegistry,
1082    ) -> Result<Self, DecodeError> {
1083        let operation_id = OperationId::consensus_decode_partial(reader, modules)?;
1084        let module_instance_id = ModuleInstanceId::consensus_decode_partial(reader, modules)?;
1085        let mut bytes = Vec::new();
1086        reader.read_to_end(&mut bytes)?;
1087
1088        let mut instance_bytes = ModuleInstanceId::consensus_encode_to_vec(&module_instance_id);
1089        instance_bytes.append(&mut bytes);
1090
1091        Ok(InactiveStateKeyBytes {
1092            operation_id,
1093            module_instance_id,
1094            state: instance_bytes,
1095        })
1096    }
1097}
1098
1099#[derive(Debug)]
1100pub struct InactiveOperationStateKeyPrefix {
1101    pub operation_id: OperationId,
1102}
1103
1104impl Encodable for InactiveOperationStateKeyPrefix {
1105    fn consensus_encode<W: Write>(&self, writer: &mut W) -> Result<(), Error> {
1106        self.operation_id.consensus_encode(writer)
1107    }
1108}
1109
1110impl ::fedimint_core::db::DatabaseLookup for InactiveOperationStateKeyPrefix {
1111    type Record = InactiveStateKeyDb;
1112}
1113
1114#[derive(Debug)]
1115pub(crate) struct InactiveModuleOperationStateKeyPrefix {
1116    pub operation_id: OperationId,
1117    pub module_instance: ModuleInstanceId,
1118}
1119
1120impl Encodable for InactiveModuleOperationStateKeyPrefix {
1121    fn consensus_encode<W: Write>(&self, writer: &mut W) -> Result<(), Error> {
1122        self.operation_id.consensus_encode(writer)?;
1123        self.module_instance.consensus_encode(writer)?;
1124        Ok(())
1125    }
1126}
1127
1128impl ::fedimint_core::db::DatabaseLookup for InactiveModuleOperationStateKeyPrefix {
1129    type Record = InactiveStateKeyDb;
1130}
1131
1132#[derive(Debug, Clone)]
1133pub struct InactiveStateKeyPrefix;
1134
1135impl Encodable for InactiveStateKeyPrefix {
1136    fn consensus_encode<W: Write>(&self, _writer: &mut W) -> Result<(), Error> {
1137        Ok(())
1138    }
1139}
1140
1141#[derive(Debug, Encodable, Decodable)]
1142pub struct InactiveStateKeyPrefixBytes;
1143
1144impl ::fedimint_core::db::DatabaseRecord for InactiveStateKeyBytes {
1145    const DB_PREFIX: u8 = ExecutorDbPrefixes::InactiveStates as u8;
1146    const NOTIFY_ON_MODIFY: bool = false;
1147    type Key = Self;
1148    type Value = InactiveStateMeta;
1149}
1150
1151impl ::fedimint_core::db::DatabaseLookup for InactiveStateKeyPrefixBytes {
1152    type Record = InactiveStateKeyBytes;
1153}
1154
1155#[derive(Debug)]
1156pub struct ActiveStateKeyBytes {
1157    pub operation_id: OperationId,
1158    pub module_instance_id: ModuleInstanceId,
1159    pub state: Vec<u8>,
1160}
1161
1162impl Encodable for ActiveStateKeyBytes {
1163    fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), std::io::Error> {
1164        self.operation_id.consensus_encode(writer)?;
1165        writer.write_all(self.state.as_slice())?;
1166        Ok(())
1167    }
1168}
1169
1170impl Decodable for ActiveStateKeyBytes {
1171    fn consensus_decode_partial<R: std::io::Read>(
1172        reader: &mut R,
1173        modules: &ModuleDecoderRegistry,
1174    ) -> Result<Self, DecodeError> {
1175        let operation_id = OperationId::consensus_decode_partial(reader, modules)?;
1176        let module_instance_id = ModuleInstanceId::consensus_decode_partial(reader, modules)?;
1177        let mut bytes = Vec::new();
1178        reader.read_to_end(&mut bytes)?;
1179
1180        let mut instance_bytes = ModuleInstanceId::consensus_encode_to_vec(&module_instance_id);
1181        instance_bytes.append(&mut bytes);
1182
1183        Ok(ActiveStateKeyBytes {
1184            operation_id,
1185            module_instance_id,
1186            state: instance_bytes,
1187        })
1188    }
1189}
1190impl ::fedimint_core::db::DatabaseRecord for InactiveStateKeyDb {
1191    const DB_PREFIX: u8 = ExecutorDbPrefixes::InactiveStates as u8;
1192    const NOTIFY_ON_MODIFY: bool = true;
1193    type Key = Self;
1194    type Value = InactiveStateMeta;
1195}
1196
1197impl DatabaseKeyWithNotify for InactiveStateKeyDb {}
1198
1199impl ::fedimint_core::db::DatabaseLookup for InactiveStateKeyPrefix {
1200    type Record = InactiveStateKeyDb;
1201}
1202
1203#[derive(Debug)]
1204enum ActiveOrInactiveState {
1205    Active {
1206        dyn_state: DynState,
1207        #[allow(dead_code)] // currently not printed anywhere, but useful in the db
1208        meta: ActiveStateMeta,
1209    },
1210    Inactive {
1211        dyn_state: DynState,
1212    },
1213}
1214
1215impl ActiveOrInactiveState {
1216    fn is_active(&self) -> bool {
1217        match self {
1218            ActiveOrInactiveState::Active { .. } => true,
1219            ActiveOrInactiveState::Inactive { .. } => false,
1220        }
1221    }
1222}
1223
1224#[apply(async_trait_maybe_send!)]
1225impl IExecutor for Executor {
1226    async fn get_active_states(&self) -> Vec<(DynState, ActiveStateMeta)> {
1227        Self::get_active_states(self).await
1228    }
1229
1230    async fn add_state_machines_dbtx(
1231        &self,
1232        dbtx: &mut DatabaseTransaction<'_>,
1233        states: Vec<DynState>,
1234    ) -> AddStateMachinesResult {
1235        Self::add_state_machines_dbtx(self, dbtx, states).await
1236    }
1237}
1238
1239#[cfg(test)]
1240mod tests;