-
Notifications
You must be signed in to change notification settings - Fork 10
/
saga_exec.rs
2670 lines (2445 loc) · 103 KB
/
saga_exec.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Manages execution of a saga
use crate::dag::InternalNode;
use crate::dag::NodeName;
use crate::rust_features::ExpectNone;
use crate::saga_action_error::ActionError;
use crate::saga_action_generic::Action;
use crate::saga_action_generic::ActionConstant;
use crate::saga_action_generic::ActionData;
use crate::saga_action_generic::ActionInjectError;
use crate::saga_log::SagaNodeEventType;
use crate::saga_log::SagaNodeLoadStatus;
use crate::sec::SecExecClient;
use crate::ActionRegistry;
use crate::SagaCachedState;
use crate::SagaDag;
use crate::SagaId;
use crate::SagaLog;
use crate::SagaNodeEvent;
use crate::SagaNodeId;
use crate::SagaType;
use anyhow::anyhow;
use anyhow::ensure;
use anyhow::Context;
use futures::channel::mpsc;
use futures::future::BoxFuture;
use futures::lock::Mutex;
use futures::FutureExt;
use futures::StreamExt;
use petgraph::algo::toposort;
use petgraph::graph::NodeIndex;
use petgraph::visit::Topo;
use petgraph::visit::Walker;
use petgraph::Direction;
use petgraph::Graph;
use petgraph::Incoming;
use petgraph::Outgoing;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::convert::TryFrom;
use std::fmt;
use std::future::Future;
use std::sync::Arc;
use tokio::sync::broadcast;
use tokio::task::JoinHandle;
// TODO-design Should we go even further and say that each node is its own
// struct with incoming channels from parents (to notify when done), from
// children (to notify when undone), and to each direction as well? Then the
// whole thing is a message passing exercise?
struct SgnsDone(Arc<serde_json::Value>);
struct SgnsFailed(ActionError);
struct SgnsUndone(UndoMode);
struct SagaNode<S: SagaNodeStateType> {
node_id: NodeIndex,
state: S,
}
trait SagaNodeStateType {}
impl SagaNodeStateType for SgnsDone {}
impl SagaNodeStateType for SgnsFailed {}
impl SagaNodeStateType for SgnsUndone {}
// TODO-design Is this right? Is the trait supposed to be empty?
trait SagaNodeRest<UserType: SagaType>: Send + Sync {
fn propagate(
&self,
exec: &SagaExecutor<UserType>,
live_state: &mut SagaExecLiveState,
);
fn log_event(&self) -> SagaNodeEventType;
}
impl<UserType: SagaType> SagaNodeRest<UserType> for SagaNode<SgnsDone> {
fn log_event(&self) -> SagaNodeEventType {
SagaNodeEventType::Succeeded(Arc::clone(&self.state.0))
}
fn propagate(
&self,
exec: &SagaExecutor<UserType>,
live_state: &mut SagaExecLiveState,
) {
let graph = &exec.dag.graph;
assert!(!live_state.node_errors.contains_key(&self.node_id));
live_state
.node_outputs
.insert(self.node_id, Arc::clone(&self.state.0))
.expect_none("node finished twice (storing output)");
if self.node_id == exec.dag.end_node {
// If we've completed the last node, the saga is done.
assert_eq!(live_state.exec_state, SagaCachedState::Running);
assert_eq!(graph.node_count(), live_state.node_outputs.len());
live_state.mark_saga_done();
return;
}
if live_state.exec_state == SagaCachedState::Unwinding {
// If the saga is currently unwinding, then this node finishing
// doesn't unblock any other nodes. However, it potentially
// unblocks undoing itself. We'll only proceed if all of our child
// nodes are "undone" already.
if neighbors_all(graph, &self.node_id, Outgoing, |child| {
live_state.nodes_undone.contains_key(child)
}) {
live_state.queue_undo.push(self.node_id);
}
return;
}
// Under normal execution, this node's completion means it's time to
// check dependent nodes to see if they're now runnable.
for child in graph.neighbors_directed(self.node_id, Outgoing) {
if neighbors_all(graph, &child, Incoming, |parent| {
live_state.node_outputs.contains_key(parent)
}) {
live_state.queue_todo.push(child);
}
}
}
}
impl<UserType: SagaType> SagaNodeRest<UserType> for SagaNode<SgnsFailed> {
fn log_event(&self) -> SagaNodeEventType {
SagaNodeEventType::Failed(self.state.0.clone())
}
fn propagate(
&self,
exec: &SagaExecutor<UserType>,
live_state: &mut SagaExecLiveState,
) {
let graph = &exec.dag.graph;
assert!(!live_state.node_outputs.contains_key(&self.node_id));
live_state
.node_errors
.insert(self.node_id, self.state.0.clone())
.expect_none("node finished twice (storing error)");
if live_state.exec_state == SagaCachedState::Unwinding {
// This node failed while we're already unwinding. We don't
// need to kick off unwinding again. We could in theory
// immediately move this node to "undone" and unblock its
// dependents, but for consistency with a simpler algorithm,
// we'll wait for unwinding to propagate from the end node.
// If all of our children are already undone, however, we
// must go ahead and mark ourselves undone and propagate
// that.
if neighbors_all(graph, &self.node_id, Outgoing, |child| {
live_state.nodes_undone.contains_key(child)
}) {
let new_node = SagaNode {
node_id: self.node_id,
state: SgnsUndone(UndoMode::ActionFailed),
};
new_node.propagate(exec, live_state);
}
} else {
// Begin the unwinding process. Start with the end node: mark
// it trivially "undone" and propagate that.
live_state.exec_state = SagaCachedState::Unwinding;
assert_ne!(self.node_id, exec.dag.end_node);
let new_node = SagaNode {
node_id: exec.dag.end_node,
state: SgnsUndone(UndoMode::ActionNeverRan),
};
new_node.propagate(exec, live_state);
}
}
}
impl<UserType: SagaType> SagaNodeRest<UserType> for SagaNode<SgnsUndone> {
fn log_event(&self) -> SagaNodeEventType {
SagaNodeEventType::UndoFinished
}
fn propagate(
&self,
exec: &SagaExecutor<UserType>,
live_state: &mut SagaExecLiveState,
) {
let graph = &exec.dag.graph;
assert_eq!(live_state.exec_state, SagaCachedState::Unwinding);
live_state
.nodes_undone
.insert(self.node_id, self.state.0)
.expect_none("node already undone");
if self.node_id == exec.dag.start_node {
// If we've undone the start node, the saga is done.
live_state.mark_saga_done();
return;
}
// During unwinding, a node's becoming undone means it's time to check
// ancestor nodes to see if they're now undoable.
for parent in graph.neighbors_directed(self.node_id, Incoming) {
if neighbors_all(graph, &parent, Outgoing, |child| {
live_state.nodes_undone.contains_key(child)
}) {
// We're ready to undo "parent". We don't know whether it's
// finished running, on the todo queue, or currenting
// outstanding. (It should not be on the undo queue!)
// TODO-design Here's an awful approach just intended to let us
// flesh out more of the rest of this to better understand how
// to manage state.
match live_state.node_exec_state(parent) {
// If the node never started or if it failed, we can
// just mark it undone without doing anything else.
NodeExecState::Blocked => {
let new_node = SagaNode {
node_id: parent,
state: SgnsUndone(UndoMode::ActionNeverRan),
};
new_node.propagate(exec, live_state);
continue;
}
NodeExecState::Failed => {
let new_node = SagaNode {
node_id: parent,
state: SgnsUndone(UndoMode::ActionFailed),
};
new_node.propagate(exec, live_state);
continue;
}
NodeExecState::QueuedToRun
| NodeExecState::TaskInProgress => {
// If we're running an action for this task, there's
// nothing we can do right now, but we'll handle it when
// it finishes. We could do better with queued (and
// there's a TODO-design in kick_off_ready() to do so),
// but this isn't wrong as-is.
continue;
}
NodeExecState::Done => {
// We have to actually run the undo action.
live_state.queue_undo.push(parent);
}
NodeExecState::QueuedToUndo
| NodeExecState::UndoInProgress
| NodeExecState::Undone(_) => {
panic!(
"already undoing or undone node whose child was \
just now undone"
);
}
}
}
}
}
}
/// Message sent from (tokio) task that executes an action to the executor
/// indicating that the action has completed
struct TaskCompletion<UserType: SagaType> {
// TODO-cleanup can this be removed? The node field is a SagaNode, which
// has a node_id.
node_id: NodeIndex,
node: Box<dyn SagaNodeRest<UserType>>,
}
/// Context provided to the (tokio) task that executes an action
struct TaskParams<UserType: SagaType> {
dag: Arc<SagaDag>,
user_context: Arc<UserType::ExecContextType>,
/// Handle to the saga's live state
///
/// This is used only to update state for status purposes. We want to
/// avoid any tight coupling between this task and the internal state.
live_state: Arc<Mutex<SagaExecLiveState>>,
/// id of the graph node whose action we're running
node_id: NodeIndex,
/// channel over which to send completion message
done_tx: mpsc::Sender<TaskCompletion<UserType>>,
/// Ancestor tree for this node. See [`ActionContext`].
// TODO-cleanup there's no reason this should be an Arc.
ancestor_tree: Arc<BTreeMap<NodeName, Arc<serde_json::Value>>>,
/// Saga parameters for the closest enclosing saga
saga_params: Arc<serde_json::Value>,
/// The action itself that we're executing.
action: Arc<dyn Action<UserType>>,
}
/// Executes a saga
///
/// Call `SagaExecutor.run()` to get a Future. You must `await` this Future to
/// actually execute the saga.
// TODO Lots more could be said here, but the basic idea matches distributed
// sagas.
// This will be a good place to put things like concurrency limits, canarying,
// etc.
//
// TODO Design note: SagaExecutor's constructors consume Arc<E> and store Arc<E>
// to reference the user-provided context "E". This makes it easy for us to
// pass references to the various places that need it. It would seem nice if
// the constructor accepted "E" and stored that, since "E" is already Send +
// Sync + 'static. There are two challenges here: (1) There are a bunch of
// other types that store a reference to E, including TaskParams and
// ActionContext, the latter of which is exposed to the user. These would have
// to store &E, which would be okay, but they'd need to have annoying lifetime
// parameters. (2) child sagas (and so child saga executors) are a thing.
// Since there's only one "E", the child would have to reference &E, which means
// it would need a lifetime parameter on it _and_ that might mean it would have
// to be a different type than SagaExecutor, even though they're otherwise the
// same.
#[derive(Debug)]
pub struct SagaExecutor<UserType: SagaType> {
#[allow(dead_code)]
log: slog::Logger,
dag: Arc<SagaDag>,
action_registry: Arc<ActionRegistry<UserType>>,
/// Channel for monitoring execution completion
finish_tx: broadcast::Sender<()>,
/// Unique identifier for this saga (an execution of a saga template)
saga_id: SagaId,
/// For each node, the NodeIndex of the start of its saga or subsaga
node_saga_start: BTreeMap<NodeIndex, NodeIndex>,
live_state: Arc<Mutex<SagaExecLiveState>>,
user_context: Arc<UserType::ExecContextType>,
}
#[derive(Debug)]
enum RecoveryDirection {
Forward(bool),
Unwind(bool),
}
impl<UserType: SagaType> SagaExecutor<UserType> {
/// Create an executor to run the given saga.
pub fn new(
log: slog::Logger,
saga_id: SagaId,
dag: Arc<SagaDag>,
registry: Arc<ActionRegistry<UserType>>,
user_context: Arc<UserType::ExecContextType>,
sec_hdl: SecExecClient,
) -> Result<SagaExecutor<UserType>, anyhow::Error> {
let sglog = SagaLog::new_empty(saga_id);
SagaExecutor::new_recover(
log,
saga_id,
dag,
registry,
user_context,
sec_hdl,
sglog,
)
}
/// Create an executor to run the given saga that may have already
/// started, using the given log events.
pub fn new_recover(
log: slog::Logger,
saga_id: SagaId,
dag: Arc<SagaDag>,
registry: Arc<ActionRegistry<UserType>>,
user_context: Arc<UserType::ExecContextType>,
sec_hdl: SecExecClient,
sglog: SagaLog,
) -> Result<SagaExecutor<UserType>, anyhow::Error> {
// Before anything else, do some basic checks on the DAG.
Self::validate_saga(&dag, ®istry).with_context(|| {
format!("validating saga {:?}", dag.saga_name())
})?;
// During recovery, there's a fine line between operational errors and
// programmer errors. If we discover semantically invalid saga state,
// that's an operational error that we must handle gracefully. We use
// lots of assertions to check invariants about our own process for
// loading the state. We panic if those are violated. For example, if
// we find that we've loaded the same node twice, that's a bug in this
// code right here (which walks each node of the graph exactly once),
// not a result of corrupted database state.
let forward = !sglog.unwinding();
let mut live_state = SagaExecLiveState {
exec_state: if forward {
SagaCachedState::Running
} else {
SagaCachedState::Unwinding
},
queue_todo: Vec::new(),
queue_undo: Vec::new(),
node_tasks: BTreeMap::new(),
node_outputs: BTreeMap::new(),
nodes_undone: BTreeMap::new(),
node_errors: BTreeMap::new(),
sglog,
injected_errors: BTreeSet::new(),
sec_hdl,
saga_id,
};
let mut loaded = BTreeSet::new();
let graph = &dag.graph;
// Precompute a mapping from each node to the start of its containing
// saga or subsaga. This is used for quickly finding each node's saga
// parameters and also when building ancestor trees for skipping over
// entire subsagas.
let nodes_sorted = toposort(&graph, None).expect("saga DAG had cycles");
let node_saga_start = {
let mut node_saga_start = BTreeMap::new();
for node_index in &nodes_sorted {
let node = graph.node_weight(*node_index).unwrap();
let subsaga_start_index = match node {
InternalNode::Start { .. }
| InternalNode::SubsagaStart { .. } => {
// For a top-level start node or subsaga start node, the
// containing saga start node is itself.
*node_index
}
InternalNode::End
| InternalNode::Action { .. }
| InternalNode::Constant { .. }
| InternalNode::SubsagaEnd { .. } => {
// For every other kind of node, first, there must be at
// least one ancestor. And we must have already visited
// because we're iterating in topological order. In
// most cases, this node's saga starts at the same node
// as its ancestor. However, if the ancestor is a
// SubsagaEnd, then we need to skip over the whole
// subsaga.
let immed_ancestor = graph
.neighbors_directed(*node_index, petgraph::Incoming)
.next()
.unwrap();
let immed_ancestor_node =
dag.get(immed_ancestor).unwrap();
let ancestor = match immed_ancestor_node {
InternalNode::SubsagaEnd { .. } => {
let subsaga_start = *node_saga_start
.get(&immed_ancestor)
.unwrap();
graph
.neighbors_directed(
subsaga_start,
petgraph::Incoming,
)
.next()
.unwrap()
}
_ => immed_ancestor,
};
*node_saga_start.get(&ancestor).expect(
"expected to compute ancestor's subsaga start \
node first",
)
}
};
node_saga_start.insert(*node_index, subsaga_start_index);
}
node_saga_start
};
// Iterate in the direction of current execution: for normal execution,
// a standard topological sort. For unwinding, reverse that.
let graph_nodes = {
let mut nodes = nodes_sorted;
if !forward {
nodes.reverse();
}
nodes
};
for node_id in graph_nodes {
let node_status =
live_state.sglog.load_status_for_node(node_id.into());
// Validate this node's state against its parent nodes' states. By
// induction, this validates everything in the graph from the start
// or end node to the current node.
for parent in graph.neighbors_directed(node_id, Incoming) {
let parent_status =
live_state.sglog.load_status_for_node(parent.into());
if !recovery_validate_parent(parent_status, node_status) {
return Err(anyhow!(
"recovery for saga {}: node {:?}: load status is \
\"{:?}\", which is illegal for parent load status \
\"{:?}\"",
saga_id,
node_id,
node_status,
parent_status,
));
}
}
let direction = if forward {
RecoveryDirection::Forward(neighbors_all(
graph,
&node_id,
Incoming,
|p| {
assert!(loaded.contains(p));
live_state.node_outputs.contains_key(p)
},
))
} else {
RecoveryDirection::Unwind(neighbors_all(
graph,
&node_id,
Outgoing,
|c| {
assert!(loaded.contains(c));
live_state.nodes_undone.contains_key(c)
},
))
};
match node_status {
SagaNodeLoadStatus::NeverStarted => {
match direction {
RecoveryDirection::Forward(true) => {
// We're recovering a node in the forward direction
// where all parents completed successfully. Add it
// to the ready queue.
live_state.queue_todo.push(node_id);
}
RecoveryDirection::Unwind(true) => {
// We're recovering a node in the reverse direction
// (unwinding) whose children have all been
// undone and which has never started. Just mark
// it undone.
// TODO-design Does this suggest a better way to do
// this might be to simply load all the state that
// we have into the SagaExecLiveState and execute
// the saga as normal, but have normal execution
// check for cached values instead of running
// actions? In a sense, this makes the recovery
// path look like the normal path rather than having
// the normal path look like the recovery path. On
// the other hand, it seems kind of nasty to have to
// hold onto the recovery state for the duration.
// It doesn't make it a whole lot easier to test or
// have fewer code paths, in a real sense. It moves
// those code paths to normal execution, but they're
// still bifurcated from the case where we didn't
// recover the saga.
live_state
.nodes_undone
.insert(node_id, UndoMode::ActionNeverRan);
}
_ => (),
}
}
SagaNodeLoadStatus::Started => {
// Whether we're unwinding or not, we have to finish
// execution of this action.
live_state.queue_todo.push(node_id);
}
SagaNodeLoadStatus::Succeeded(output) => {
// If the node has finished executing and not started
// undoing, and if we're unwinding and the children have
// all finished undoing, then it's time to undo this
// one.
assert!(!live_state.node_errors.contains_key(&node_id));
live_state
.node_outputs
.insert(node_id, Arc::clone(output))
.expect_none("recovered node twice (success case)");
if let RecoveryDirection::Unwind(true) = direction {
live_state.queue_undo.push(node_id);
}
}
SagaNodeLoadStatus::Failed(error) => {
assert!(!live_state.node_outputs.contains_key(&node_id));
live_state
.node_errors
.insert(node_id, error.clone())
.expect_none("recovered node twice (failure case)");
// If the node failed, and we're unwinding, and the children
// have all been undone, it's time to undo this one.
// But we just mark it undone -- we don't execute the
// undo action.
if let RecoveryDirection::Unwind(true) = direction {
live_state
.nodes_undone
.insert(node_id, UndoMode::ActionFailed);
}
}
SagaNodeLoadStatus::UndoStarted(output) => {
// We know we're unwinding. (Otherwise, we should have
// failed validation earlier.) Execute the undo action.
assert!(!forward);
live_state.queue_undo.push(node_id);
// We still need to record the output because it's available
// to the undo action.
live_state
.node_outputs
.insert(node_id, Arc::clone(output))
.expect_none("recovered node twice (undo case)");
}
SagaNodeLoadStatus::UndoFinished => {
// Again, we know we're unwinding. We've also finished
// undoing this node.
assert!(!forward);
live_state
.nodes_undone
.insert(node_id, UndoMode::ActionUndone);
}
}
// TODO-correctness is it appropriate to have side effects in an
// assertion here?
assert!(loaded.insert(node_id));
}
// Check our done conditions.
if live_state.node_outputs.contains_key(&dag.end_node)
|| live_state.nodes_undone.contains_key(&dag.start_node)
{
live_state.mark_saga_done();
}
let (finish_tx, _) = broadcast::channel(1);
Ok(SagaExecutor {
log,
dag,
finish_tx,
saga_id,
user_context,
live_state: Arc::new(Mutex::new(live_state)),
action_registry: Arc::clone(®istry),
node_saga_start,
})
}
/// Validates some basic properties of the saga
// Many of these properties may be validated when we construct the saga DAG.
// Checking them again here makes sure that we gracefully handle a case
// where we got an invalid DAG in some other way (e.g., bad database state).
// See `DagBuilderError` for more information about these conditions.
fn validate_saga(
saga: &SagaDag,
registry: &ActionRegistry<UserType>,
) -> Result<(), anyhow::Error> {
let mut nsubsaga_start = 0;
let mut nsubsaga_end = 0;
for node_index in saga.graph.node_indices() {
let node = &saga.graph[node_index];
match node {
InternalNode::Start { .. } => {
ensure!(
node_index == saga.start_node,
"found start node at unexpected index {:?}",
node_index
);
}
InternalNode::End => {
ensure!(
node_index == saga.end_node,
"found end node at unexpected index {:?}",
node_index
);
}
InternalNode::Action { name, action_name, .. } => {
let action = registry.get(&action_name);
ensure!(
action.is_ok(),
"action for node {:?} not registered: {:?}",
name,
action_name
);
}
InternalNode::Constant { .. } => (),
InternalNode::SubsagaStart { .. } => {
nsubsaga_start += 1;
}
InternalNode::SubsagaEnd { .. } => {
nsubsaga_end += 1;
}
}
}
ensure!(
saga.start_node.index() < saga.graph.node_count(),
"bad saga graph (missing start node)",
);
ensure!(
saga.end_node.index() < saga.graph.node_count(),
"bad saga graph (missing end node)",
);
ensure!(
nsubsaga_start == nsubsaga_end,
"bad saga graph (found {} subsaga start nodes but {} subsaga end \
nodes)",
nsubsaga_start,
nsubsaga_end
);
let nend_ancestors =
saga.graph.neighbors_directed(saga.end_node, Incoming).count();
ensure!(
nend_ancestors == 1,
"expected saga to end with exactly one node"
);
Ok(())
}
/// Builds the "ancestor tree" for a node whose dependencies have all
/// completed
///
/// The ancestor tree for a node is a map whose keys are strings that
/// identify ancestor nodes in the graph and whose values represent the
/// outputs from those nodes. This is used by [`ActionContext::lookup`].
/// See where we use this function in poll() for more details.
fn make_ancestor_tree(
&self,
tree: &mut BTreeMap<NodeName, Arc<serde_json::Value>>,
live_state: &SagaExecLiveState,
node_index: NodeIndex,
include_self: bool,
) {
if include_self {
self.make_ancestor_tree_node(tree, live_state, node_index);
return;
}
let ancestors = self.dag.graph.neighbors_directed(node_index, Incoming);
for ancestor in ancestors {
self.make_ancestor_tree_node(tree, live_state, ancestor);
}
}
fn make_ancestor_tree_node(
&self,
tree: &mut BTreeMap<NodeName, Arc<serde_json::Value>>,
live_state: &SagaExecLiveState,
node_index: NodeIndex,
) {
let dag_node = self.dag.get(node_index).unwrap();
// Record any output from the current node.
match dag_node {
InternalNode::Constant { name, .. }
| InternalNode::Action { name, .. }
| InternalNode::SubsagaEnd { name, .. } => {
// TODO-cleanup This implementation may encounter the same node
// twice. This feels a little sloppy and inefficient.
let output = live_state.node_output(node_index);
tree.insert(name.clone(), output);
}
InternalNode::Start { .. }
| InternalNode::End
| InternalNode::SubsagaStart { .. } => (),
}
// Figure out where to resume the traversal.
let resume_node = match dag_node {
InternalNode::SubsagaStart { .. } => {
// We were traversing nodes in a subsaga and we're now done.
None
}
InternalNode::SubsagaEnd { .. } => {
// We're traversing nodes in a saga that contains a subsaga.
// Skip over the subsaga.
Some(*self.node_saga_start.get(&node_index).unwrap())
}
InternalNode::Constant { .. }
| InternalNode::Action { .. }
| InternalNode::Start { .. }
| InternalNode::End => {
// Ordinary traversal -- keep going from where we are.
Some(node_index)
}
};
if let Some(resume_node) = resume_node {
self.make_ancestor_tree(tree, live_state, resume_node, false);
}
}
/// Returns the saga parameters for the current node
// If this node is not within a subsaga, then these will be the top-level
// saga parameters. If this node is contained within a subsaga, then these
// will be the parameters of the _subsaga_.
fn saga_params_for(
&self,
live_state: &SagaExecLiveState,
node_index: NodeIndex,
) -> Arc<serde_json::Value> {
let subsaga_start_index = self.node_saga_start[&node_index];
let subsaga_start_node = self.dag.get(subsaga_start_index).unwrap();
match subsaga_start_node {
InternalNode::Start { params } => params.clone(),
InternalNode::SubsagaStart { params_node_name, .. } => {
// TODO-performance We're going to repeat this for every node in
// the subsaga. We may as well cache it somewhere. The tricky
// part is figuring out when to generate the value that accounts
// for all the cases where we may land here, including recovery
// (in which case we may not have executed the SubsagaStart
// node since crashing) and for undo actions in the subsaga.
let mut tree = BTreeMap::new();
self.make_ancestor_tree(
&mut tree,
live_state,
subsaga_start_index,
false,
);
Arc::clone(tree.get(params_node_name).unwrap())
}
InternalNode::SubsagaEnd { .. }
| InternalNode::End
| InternalNode::Action { .. }
| InternalNode::Constant { .. } => {
panic!(
"containing saga cannot have started with {:?}",
subsaga_start_node
);
}
}
}
/// Simulates an error at a given node in the saga graph
///
/// When execution reaches this node, instead of running the normal action
/// for this node, an error will be generated and processed as though the
/// action itself had produced the error.
pub async fn inject_error(&self, node_id: NodeIndex) {
let mut live_state = self.live_state.lock().await;
live_state.injected_errors.insert(node_id);
}
/// Runs the saga
///
/// This might be running a saga that has never been started before or
/// one that has been recovered from persistent state.
async fn run_saga(&self) {
{
// TODO-design Every SagaExec should be able to run_saga() exactly
// once. We don't really want to let you re-run it and get a new
// message on finish_tx. However, we _do_ want to handle this
// particular case when we've recovered a "done" saga and the
// consumer has run() it (once).
let live_state = self.live_state.lock().await;
if live_state.exec_state == SagaCachedState::Done {
self.finish_tx.send(()).expect("failed to send finish message");
live_state.sec_hdl.saga_update(SagaCachedState::Done).await;
return;
}
}
// Allocate the channel used for node tasks to tell us when they've
// completed. In practice, each node can enqueue only two messages in
// its lifetime: one for completion of the action, and one for
// completion of the compensating action. We bound this channel's size
// at twice the graph node count for this worst case.
let (tx, mut rx) = mpsc::channel(2 * self.dag.graph.node_count());
loop {
self.kick_off_ready(&tx).await;
// Process any messages available on our channel.
// It shouldn't be possible to get None back here. That would mean
// that all of the consumers have closed their ends, but we still
// have a consumer of our own in "tx".
// TODO-robustness Can we assert that there are outstanding tasks
// when we block on this channel?
let message = rx.next().await.expect("broken tx");
let task = {
let mut live_state = self.live_state.lock().await;
live_state.node_task_done(message.node_id)
};
// This should really not take long, as there's nothing else this
// task does after sending the message that we just received. It's
// good to wait here to make sure things are cleaned up.
// TODO-robustness can we enforce that this won't take long?
task.await.expect("node task failed unexpectedly");
let mut live_state = self.live_state.lock().await;
let prev_state = live_state.exec_state;
message.node.propagate(&self, &mut live_state);
// TODO-cleanup This condition ought to be simplified. We want to
// update the saga state when we become Unwinding (which we do here)
// and when we become Done (which we do below). There may be a
// better place to put this logic that's less ad hoc.
if live_state.exec_state == SagaCachedState::Unwinding
&& prev_state != SagaCachedState::Unwinding
{
live_state
.sec_hdl
.saga_update(SagaCachedState::Unwinding)
.await;
}
if live_state.exec_state == SagaCachedState::Done {
break;
}
}
let live_state = self.live_state.try_lock().unwrap();
assert_eq!(live_state.exec_state, SagaCachedState::Done);
self.finish_tx.send(()).expect("failed to send finish message");
live_state.sec_hdl.saga_update(SagaCachedState::Done).await;
}
// Kick off any nodes that are ready to run. (Right now, we kick off
// everything, so it might seem unnecessary to store this vector in
// "self" to begin with. However, the intent is to add capacity limits,
// in which case we may return without having scheduled everything, and
// we want to track whatever's still ready to go.)
// TODO revisit dance with the vec to satisfy borrow rules
// TODO implement unwinding
async fn kick_off_ready(
&self,
tx: &mpsc::Sender<TaskCompletion<UserType>>,
) {
let mut live_state = self.live_state.lock().await;
// TODO is it possible to deadlock with a concurrency limit given that
// we always do "todo" before "undo"?
let todo_queue = live_state.queue_todo.clone();
live_state.queue_todo = Vec::new();
for node_id in todo_queue {
// TODO-design It would be good to check whether the saga is
// unwinding, and if so, whether this action has ever started
// running before. If not, then we can send this straight to
// undoing without doing any more work here. What we're
// doing here should also be safe, though. We run the action
// regardless, and when we complete it, we'll undo it.
// TODO we could be much more efficient without copying this tree
// each time.
let mut ancestor_tree = BTreeMap::new();
self.make_ancestor_tree(
&mut ancestor_tree,
&live_state,
node_id,
false,
);
let saga_params = self.saga_params_for(&live_state, node_id);
let sgaction = if live_state.injected_errors.contains(&node_id) {
Arc::new(ActionInjectError {}) as Arc<dyn Action<UserType>>
} else {
self.node_action(&live_state, node_id)
};
let task_params = TaskParams {
dag: Arc::clone(&self.dag),
live_state: Arc::clone(&self.live_state),
node_id,
done_tx: tx.clone(),
ancestor_tree: Arc::new(ancestor_tree),
saga_params,
action: sgaction,
user_context: Arc::clone(&self.user_context),
};
let task = tokio::spawn(SagaExecutor::exec_node(task_params));
live_state.node_task(node_id, task);
}
if live_state.exec_state == SagaCachedState::Running {
assert!(live_state.queue_undo.is_empty());
return;
}
let undo_queue = live_state.queue_undo.clone();
live_state.queue_undo = Vec::new();
for node_id in undo_queue {
// TODO commonize with code above
// TODO we could be much more efficient without copying this tree
// each time.
let mut ancestor_tree = BTreeMap::new();
self.make_ancestor_tree(
&mut ancestor_tree,
&live_state,
node_id,
true,
);
let saga_params = self.saga_params_for(&live_state, node_id);
let sgaction = self.node_action(&live_state, node_id);
let task_params = TaskParams {
dag: Arc::clone(&self.dag),
live_state: Arc::clone(&self.live_state),
node_id,
done_tx: tx.clone(),
ancestor_tree: Arc::new(ancestor_tree),