-
-
Notifications
You must be signed in to change notification settings - Fork 145
/
saga.go
1300 lines (1114 loc) · 32.1 KB
/
saga.go
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
package gen
import (
"context"
"fmt"
"math"
"sync"
"time"
"github.com/ergo-services/ergo/etf"
)
// SagaBehavior interface
type SagaBehavior interface {
//
// Mandatory callbacks
//
// InitSaga
InitSaga(process *SagaProcess, args ...etf.Term) (SagaOptions, error)
// HandleTxNew invokes on a new TX receiving by this saga.
HandleTxNew(process *SagaProcess, id SagaTransactionID, value interface{}) SagaStatus
// HandleTxResult invoked on a receiving result from the next saga
HandleTxResult(process *SagaProcess, id SagaTransactionID, from SagaNextID, result interface{}) SagaStatus
// HandleTxCancel invoked on a request of transaction cancelation.
HandleTxCancel(process *SagaProcess, id SagaTransactionID, reason string) SagaStatus
//
// Optional callbacks
//
// HandleTxDone invoked when the transaction is done on a saga where it was created.
// It returns the final result and SagaStatus. The commit message will deliver the final
// result to all participants of this transaction (if it has enabled the TwoPhaseCommit option).
// Otherwise the final result will be ignored.
HandleTxDone(process *SagaProcess, id SagaTransactionID, result interface{}) (interface{}, SagaStatus)
// HandleTxInterim invoked if received interim result from the next hop
HandleTxInterim(process *SagaProcess, id SagaTransactionID, from SagaNextID, interim interface{}) SagaStatus
// HandleTxCommit invoked if TwoPhaseCommit option is enabled for the given TX.
// All sagas involved in this TX receive a commit message with final value and invoke this callback.
// The final result has a value returned by HandleTxDone on a Saga created this TX.
HandleTxCommit(process *SagaProcess, id SagaTransactionID, final interface{}) SagaStatus
//
// Callbacks to handle result/interim from the worker(s)
//
// HandleJobResult
HandleJobResult(process *SagaProcess, id SagaTransactionID, from SagaJobID, result interface{}) SagaStatus
// HandleJobInterim
HandleJobInterim(process *SagaProcess, id SagaTransactionID, from SagaJobID, interim interface{}) SagaStatus
// HandleJobFailed
HandleJobFailed(process *SagaProcess, id SagaTransactionID, from SagaJobID, reason string) SagaStatus
//
// Server's callbacks
//
// HandleStageCall this callback is invoked on ServerProcess.Call. This method is optional
// for the implementation
HandleSagaCall(process *SagaProcess, from ServerFrom, message etf.Term) (etf.Term, ServerStatus)
// HandleStageCast this callback is invoked on ServerProcess.Cast. This method is optional
// for the implementation
HandleSagaCast(process *SagaProcess, message etf.Term) ServerStatus
// HandleStageInfo this callback is invoked on Process.Send. This method is optional
// for the implementation
HandleSagaInfo(process *SagaProcess, message etf.Term) ServerStatus
// HandleSagaDirect this callback is invoked on Process.Direct. This method is optional
// for the implementation
HandleSagaDirect(process *SagaProcess, message interface{}) (interface{}, error)
}
const (
defaultHopLimit = math.MaxUint16
defaultLifespan = 60
)
type SagaStatus error
var (
SagaStatusOK SagaStatus // nil
SagaStatusStop SagaStatus = fmt.Errorf("stop")
// internal
sagaStatusUnsupported SagaStatus = fmt.Errorf("unsupported")
ErrSagaTxEndOfLifespan = fmt.Errorf("End of TX lifespan")
ErrSagaTxNextTimeout = fmt.Errorf("Next saga timeout")
ErrSagaUnknown = fmt.Errorf("Unknown saga")
ErrSagaJobUnknown = fmt.Errorf("Unknown job")
ErrSagaTxUnknown = fmt.Errorf("Unknown TX")
ErrSagaTxCanceled = fmt.Errorf("Tx is canceled")
ErrSagaTxInProgress = fmt.Errorf("Tx is still in progress")
ErrSagaResultAlreadySent = fmt.Errorf("Result is already sent")
ErrSagaNotAllowed = fmt.Errorf("Operation is not allowed")
)
type Saga struct {
Server
}
type SagaTransactionOptions struct {
// HopLimit defines a number of hop within the transaction. Default limit
// is 0 (no limit).
HopLimit uint
// Lifespan defines a lifespan for the transaction in seconds. Default is 60.
Lifespan uint
// TwoPhaseCommit enables 2PC for the transaction. This option makes all
// Sagas involved in this transaction invoke HandleCommit callback on them and
// invoke HandleCommitJob callback on Worker processes once the transaction is finished.
TwoPhaseCommit bool
}
type SagaOptions struct {
// MaxTransactions defines the limit for the number of active transactions. Default: 0 (unlimited)
MaxTransactions uint
// Worker
Worker SagaWorkerBehavior
}
type SagaProcess struct {
ServerProcess
options SagaOptions
behavior SagaBehavior
// running transactions
txs map[SagaTransactionID]*SagaTransaction
mutexTXS sync.Mutex
// next sagas where txs were sent
next map[SagaNextID]*SagaTransaction
mutexNext sync.Mutex
// running jobs
jobs map[etf.Pid]*SagaJob
mutexJobs sync.Mutex
}
type SagaTransactionID etf.Ref
func (id SagaTransactionID) String() string {
r := etf.Ref(id)
return fmt.Sprintf("TX#%d.%d.%d", r.ID[0], r.ID[1], r.ID[2])
}
type SagaTransaction struct {
sync.Mutex
id SagaTransactionID
options SagaTransactionOptions
origin SagaNextID // next id on a saga it came from
monitor etf.Ref // monitor parent saga
next map[SagaNextID]*SagaNext // where were sent
jobs map[SagaJobID]etf.Pid
arrival int64 // when it arrived on this saga
parents []etf.Pid // sagas trace
done bool // do not allow send result more than once if 2PC is set
cancelTimer context.CancelFunc
}
type SagaNextID etf.Ref
func (id SagaNextID) String() string {
r := etf.Ref(id)
return fmt.Sprintf("Next#%d.%d.%d", r.ID[0], r.ID[1], r.ID[2])
}
type SagaNext struct {
// Saga etf.Pid, string (for the locally registered process), gen.ProcessID{process, node} (for the remote process)
Saga interface{}
// Value a value for the invoking HandleTxNew on a next hop.
Value interface{}
// Timeout how long this Saga will be waiting for the result from the next hop. Default - 10 seconds
Timeout uint
// TrapCancel if the next saga fails, it will transform the cancel signal into the regular message gen.MessageSagaCancel, and HandleSagaInfo callback will be invoked.
TrapCancel bool
// internal
done bool // for 2PC case
cancelTimer context.CancelFunc
}
type SagaJobID etf.Ref
func (id SagaJobID) String() string {
r := etf.Ref(id)
return fmt.Sprintf("Job#%d.%d.%d", r.ID[0], r.ID[1], r.ID[2])
}
type SagaJob struct {
ID SagaJobID
TransactionID SagaTransactionID
Value interface{}
// internal
options SagaJobOptions
saga etf.Pid
commit bool
worker Process
done bool
cancelTimer context.CancelFunc
}
type SagaJobOptions struct {
Timeout uint
}
type messageSaga struct {
Request etf.Atom
Pid etf.Pid
Command interface{}
}
type messageSagaNext struct {
TransactionID etf.Ref
Origin etf.Ref
Value interface{}
Parents []etf.Pid
Options map[string]interface{}
}
type messageSagaResult struct {
TransactionID etf.Ref
Origin etf.Ref
Result interface{}
}
type messageSagaCancel struct {
TransactionID etf.Ref
Origin etf.Ref
Reason string
}
type messageSagaCommit struct {
TransactionID etf.Ref
Origin etf.Ref
Final interface{}
}
type MessageSagaCancel struct {
TransactionID SagaTransactionID
NextID SagaNextID
Reason string
}
type MessageSagaError struct {
TransactionID SagaTransactionID
NextID SagaNextID
Error string
Details string
}
//
// Saga API
//
type sagaSetMaxTransactions struct {
max uint
}
// SetMaxTransactions set maximum transactions fo the saga
func (gs *Saga) SetMaxTransactions(process Process, max uint) error {
if !process.IsAlive() {
return ErrServerTerminated
}
message := sagaSetMaxTransactions{
max: max,
}
_, err := process.Direct(message)
return err
}
//
// SagaProcess methods
//
func (sp *SagaProcess) StartTransaction(options SagaTransactionOptions, value interface{}) SagaTransactionID {
id := sp.MakeRef()
if options.HopLimit == 0 {
options.HopLimit = defaultHopLimit
}
if options.Lifespan == 0 {
options.Lifespan = defaultLifespan
}
message := etf.Tuple{
etf.Atom("$saga_next"),
sp.Self(),
etf.Tuple{
id, // tx id
etf.Ref{}, // origin. empty value. (parent's next id)
value, // tx value
[]etf.Pid{}, // parents
etf.Map{ // tx options
"HopLimit": options.HopLimit,
"Lifespan": options.Lifespan,
"TwoPhaseCommit": options.TwoPhaseCommit,
},
},
}
sp.Send(sp.Self(), message)
return SagaTransactionID(id)
}
func (sp *SagaProcess) Next(id SagaTransactionID, next SagaNext) (SagaNextID, error) {
sp.mutexTXS.Lock()
tx, ok := sp.txs[id]
sp.mutexTXS.Unlock()
if !ok {
return SagaNextID{}, ErrSagaTxUnknown
}
if len(tx.next) > int(tx.options.HopLimit) {
return SagaNextID{}, fmt.Errorf("exceeded hop limit")
}
nextLifespan := int64(tx.options.Lifespan) - (time.Now().Unix() - tx.arrival)
if nextLifespan < 1 {
sp.CancelTransaction(id, "exceeded lifespan")
return SagaNextID{}, fmt.Errorf("exceeded lifespan. transaction canceled")
}
if next.Timeout > 0 && int64(next.Timeout) > nextLifespan {
return SagaNextID{}, fmt.Errorf("requested timeout exceed lifespan")
}
if next.Timeout > 0 {
nextLifespan = int64(next.Timeout)
}
ref := sp.MonitorProcess(next.Saga)
next_id := SagaNextID(ref)
message := etf.Tuple{
etf.Atom("$saga_next"),
sp.Self(),
etf.Tuple{
etf.Ref(tx.id), // tx id
ref, // next id (tx origin on the next saga)
next.Value,
tx.parents,
etf.Map{
"HopLimit": tx.options.HopLimit,
"Lifespan": nextLifespan,
"TwoPhaseCommit": tx.options.TwoPhaseCommit,
},
},
}
sp.Send(next.Saga, message)
cancelMessage := etf.Tuple{
etf.Atom("$saga_cancel"),
etf.Pid{}, // do not send sp.Self() to be able TrapCancel work
etf.Tuple{
etf.Ref(tx.id), // tx id
ref,
"lifespan",
},
}
timeout := time.Duration(nextLifespan) * time.Second
next.cancelTimer = sp.SendAfter(sp.Self(), cancelMessage, timeout)
tx.Lock()
tx.next[next_id] = &next
tx.Unlock()
sp.mutexNext.Lock()
sp.next[next_id] = tx
sp.mutexNext.Unlock()
return next_id, nil
}
func (sp *SagaProcess) StartJob(id SagaTransactionID, options SagaJobOptions, value interface{}) (SagaJobID, error) {
if sp.options.Worker == nil {
return SagaJobID{}, fmt.Errorf("This saga has no worker")
}
sp.mutexTXS.Lock()
tx, ok := sp.txs[id]
sp.mutexTXS.Unlock()
if !ok {
return SagaJobID{}, ErrSagaTxUnknown
}
jobLifespan := int64(tx.options.Lifespan) - (time.Now().Unix() - tx.arrival)
if options.Timeout > 0 && int64(options.Timeout) > jobLifespan {
return SagaJobID{}, fmt.Errorf("requested timeout exceed lifespan")
}
if options.Timeout > 0 {
jobLifespan = int64(options.Timeout)
}
workerOptions := ProcessOptions{}
worker, err := sp.Spawn("", workerOptions, sp.options.Worker)
if err != nil {
return SagaJobID{}, err
}
sp.Link(worker.Self())
job := SagaJob{
ID: SagaJobID(sp.MakeRef()),
TransactionID: id,
Value: value,
commit: tx.options.TwoPhaseCommit,
saga: sp.Self(),
worker: worker,
}
sp.mutexJobs.Lock()
sp.jobs[worker.Self()] = &job
sp.mutexJobs.Unlock()
m := messageSagaJobStart{
job: job,
}
tx.Lock()
tx.jobs[job.ID] = worker.Self()
tx.Unlock()
sp.Cast(worker.Self(), m)
// terminate worker process via handleSagaExit
exitMessage := MessageExit{
Pid: worker.Self(),
Reason: "lifespan",
}
timeout := time.Duration(jobLifespan) * time.Second
job.cancelTimer = sp.SendAfter(sp.Self(), exitMessage, timeout)
return job.ID, nil
}
func (sp *SagaProcess) SendResult(id SagaTransactionID, result interface{}) error {
sp.mutexTXS.Lock()
tx, ok := sp.txs[id]
sp.mutexTXS.Unlock()
if !ok {
return ErrSagaTxUnknown
}
if len(tx.parents) == 0 {
// SendResult was called right after CreateTransaction call.
return ErrSagaNotAllowed
}
if tx.done {
return ErrSagaResultAlreadySent
}
if sp.checkTxDone(tx) == false {
return ErrSagaTxInProgress
}
message := etf.Tuple{
etf.Atom("$saga_result"),
sp.Self(),
etf.Tuple{
etf.Ref(tx.id),
etf.Ref(tx.origin),
result,
},
}
// send message to the parent saga
if err := sp.Send(tx.parents[0], message); err != nil {
return err
}
// tx handling is done on this saga
tx.done = true
// do not remove TX if we send result to itself
if tx.parents[0] == sp.Self() {
return nil
}
// do not remove TX if 2PC is enabled
if tx.options.TwoPhaseCommit {
return nil
}
sp.mutexTXS.Lock()
delete(sp.txs, id)
sp.mutexTXS.Unlock()
return nil
}
func (sp *SagaProcess) SendInterim(id SagaTransactionID, interim interface{}) error {
sp.mutexTXS.Lock()
tx, ok := sp.txs[id]
sp.mutexTXS.Unlock()
if !ok {
return ErrSagaTxUnknown
}
message := etf.Tuple{
etf.Atom("$saga_interim"),
sp.Self(),
etf.Tuple{
etf.Ref(tx.id),
etf.Ref(tx.origin),
interim,
},
}
// send message to the parent saga
if err := sp.Send(tx.parents[0], message); err != nil {
return err
}
return nil
}
func (sp *SagaProcess) CancelTransaction(id SagaTransactionID, reason string) error {
sp.mutexTXS.Lock()
tx, ok := sp.txs[id]
sp.mutexTXS.Unlock()
if !ok {
return ErrSagaTxUnknown
}
message := etf.Tuple{
etf.Atom("$saga_cancel"),
sp.Self(),
etf.Tuple{etf.Ref(tx.id), etf.Ref(tx.origin), reason},
}
sp.Send(sp.Self(), message)
return nil
}
func (sp *SagaProcess) CancelJob(id SagaTransactionID, job SagaJobID, reason string) error {
sp.mutexTXS.Lock()
tx, ok := sp.txs[id]
sp.mutexTXS.Unlock()
if !ok {
return ErrSagaTxUnknown
}
tx.Lock()
defer tx.Unlock()
return nil
}
func (sp *SagaProcess) checkTxDone(tx *SagaTransaction) bool {
if tx.options.TwoPhaseCommit == false { // 2PC is disabled
if len(tx.next) > 0 { // haven't received all results from the "next" sagas
return false
}
if len(tx.jobs) > 0 { // tx has running jobs
return false
}
return true
}
// 2PC is enabled. check whether received all results from sagas
// and workers have finished their jobs
tx.Lock()
// check results from sagas
for _, next := range tx.next {
if next.done == false {
tx.Unlock()
return false
}
}
if len(tx.jobs) == 0 {
tx.Unlock()
return true
}
// gen list of running workers
jobs := []etf.Pid{}
for _, pid := range tx.jobs {
jobs = append(jobs, pid)
}
tx.Unlock()
// check the job states of them
sp.mutexJobs.Lock()
for _, pid := range jobs {
job := sp.jobs[pid]
if job.done == false {
sp.mutexJobs.Unlock()
return false
}
}
sp.mutexJobs.Unlock()
return true
}
func (sp *SagaProcess) handleSagaRequest(m messageSaga) error {
switch m.Request {
case etf.Atom("$saga_next"):
nextMessage := messageSagaNext{}
if err := etf.TermIntoStruct(m.Command, &nextMessage); err != nil {
return ErrUnsupportedRequest
}
// Check if exceed the number of transaction on this saga
if sp.options.MaxTransactions > 0 && len(sp.txs)+1 > int(sp.options.MaxTransactions) {
cancel := etf.Tuple{
etf.Atom("$saga_cancel"),
sp.Self(),
etf.Tuple{
nextMessage.TransactionID,
nextMessage.Origin,
"exceed_tx_limit",
},
}
sp.Send(m.Pid, cancel)
return nil
}
// Check for the loop
transactionID := SagaTransactionID(nextMessage.TransactionID)
sp.mutexTXS.Lock()
tx, ok := sp.txs[transactionID]
sp.mutexTXS.Unlock()
if ok {
// loop detected. send cancel message
cancel := etf.Tuple{
etf.Atom("$saga_cancel"),
sp.Self(),
etf.Tuple{
nextMessage.TransactionID,
nextMessage.Origin,
"loop_detected",
},
}
sp.Send(m.Pid, cancel)
return nil
}
txOptions := SagaTransactionOptions{
HopLimit: defaultHopLimit,
Lifespan: defaultLifespan,
}
if value, ok := nextMessage.Options["HopLimit"]; ok {
if hoplimit, ok := value.(int64); ok {
txOptions.HopLimit = uint(hoplimit)
}
}
if value, ok := nextMessage.Options["Lifespan"]; ok {
if lifespan, ok := value.(int64); ok && lifespan > 0 {
txOptions.Lifespan = uint(lifespan)
}
}
if value, ok := nextMessage.Options["TwoPhaseCommit"]; ok {
txOptions.TwoPhaseCommit, _ = value.(bool)
}
tx = &SagaTransaction{
id: transactionID,
options: txOptions,
origin: SagaNextID(nextMessage.Origin),
next: make(map[SagaNextID]*SagaNext),
jobs: make(map[SagaJobID]etf.Pid),
arrival: time.Now().Unix(),
parents: append([]etf.Pid{m.Pid}, nextMessage.Parents...),
}
sp.mutexTXS.Lock()
sp.txs[transactionID] = tx
sp.mutexTXS.Unlock()
// do not monitor itself (they are equal if its came from the StartTransaction call)
if m.Pid != sp.Self() {
tx.monitor = sp.MonitorProcess(m.Pid)
}
// tx lifespan timer
cancelMessage := etf.Tuple{
etf.Atom("$saga_cancel"),
sp.Self(), // can't be trapped (ignored)
etf.Tuple{
nextMessage.TransactionID,
nextMessage.Origin,
"lifespan",
},
}
timeout := time.Duration(txOptions.Lifespan) * time.Second
tx.cancelTimer = sp.SendAfter(sp.Self(), cancelMessage, timeout)
return sp.behavior.HandleTxNew(sp, transactionID, nextMessage.Value)
case "$saga_cancel":
cancel := messageSagaCancel{}
if err := etf.TermIntoStruct(m.Command, &cancel); err != nil {
return ErrUnsupportedRequest
}
tx, exist := sp.txs[SagaTransactionID(cancel.TransactionID)]
if !exist {
// unknown tx, just ignore it
return nil
}
// check where it came from.
if tx.parents[0] == m.Pid {
// came from parent saga or from itself via CancelTransaction
// can't be ignored
sp.cancelTX(m.Pid, cancel, tx)
return sp.behavior.HandleTxCancel(sp, tx.id, cancel.Reason)
}
// this cancel came from one of the next sagas
// or from itself (being in the middle of transaction graph)
next_id := SagaNextID(cancel.Origin)
tx.Lock()
next, ok := tx.next[next_id]
tx.Unlock()
if ok && next.TrapCancel {
// clean the next saga stuff
next.cancelTimer()
sp.DemonitorProcess(cancel.Origin)
tx.Lock()
delete(tx.next, next_id)
tx.Unlock()
sp.mutexNext.Lock()
delete(sp.next, next_id)
sp.mutexNext.Unlock()
// came from the next saga and TrapCancel was enabled
cm := MessageSagaCancel{
TransactionID: tx.id,
NextID: next_id,
Reason: cancel.Reason,
}
sp.Send(sp.Self(), cm)
return SagaStatusOK
}
sp.cancelTX(m.Pid, cancel, tx)
return sp.behavior.HandleTxCancel(sp, tx.id, cancel.Reason)
case etf.Atom("$saga_result"):
result := messageSagaResult{}
if err := etf.TermIntoStruct(m.Command, &result); err != nil {
return ErrUnsupportedRequest
}
transactionID := SagaTransactionID(result.TransactionID)
sp.mutexTXS.Lock()
tx, ok := sp.txs[transactionID]
sp.mutexTXS.Unlock()
if !ok {
// ignore unknown TX
return nil
}
next_id := SagaNextID(result.Origin)
empty_next_id := SagaNextID{}
// next id is empty if we got result on a saga created this TX
if next_id != empty_next_id {
sp.mutexNext.Lock()
_, ok := sp.next[next_id]
sp.mutexNext.Unlock()
if !ok {
// ignore unknown result
return nil
}
sp.mutexNext.Lock()
delete(sp.next, next_id)
sp.mutexNext.Unlock()
tx.Lock()
next := tx.next[next_id]
if tx.options.TwoPhaseCommit == false {
next.cancelTimer()
sp.DemonitorProcess(result.Origin)
delete(tx.next, next_id)
} else {
next.done = true
}
tx.Unlock()
return sp.behavior.HandleTxResult(sp, tx.id, next_id, result.Result)
}
final, status := sp.behavior.HandleTxDone(sp, tx.id, result.Result)
if status == SagaStatusOK {
sp.commitTX(tx, final)
}
return status
case etf.Atom("$saga_interim"):
interim := messageSagaResult{}
if err := etf.TermIntoStruct(m.Command, &interim); err != nil {
return ErrUnsupportedRequest
}
next_id := SagaNextID(interim.Origin)
sp.mutexNext.Lock()
tx, ok := sp.next[next_id]
sp.mutexNext.Unlock()
if !ok {
// ignore unknown interim result and send cancel message to the sender
message := etf.Tuple{
etf.Atom("$saga_cancel"),
sp.Self(),
etf.Tuple{
interim.TransactionID,
interim.Origin,
"unknown or canceled tx",
},
}
sp.Send(m.Pid, message)
return nil
}
return sp.behavior.HandleTxInterim(sp, tx.id, next_id, interim.Result)
case etf.Atom("$saga_commit"):
// propagate Commit signal if 2PC is enabled
commit := messageSagaCommit{}
if err := etf.TermIntoStruct(m.Command, &commit); err != nil {
return ErrUnsupportedRequest
}
transactionID := SagaTransactionID(commit.TransactionID)
sp.mutexTXS.Lock()
tx, ok := sp.txs[transactionID]
sp.mutexTXS.Unlock()
if !ok {
// ignore unknown TX
return nil
}
// clean up and send commit message before we invoke callback
sp.commitTX(tx, commit.Final)
// make sure if 2PC was enabled on this TX
if tx.options.TwoPhaseCommit {
return sp.behavior.HandleTxCommit(sp, tx.id, commit.Final)
}
return SagaStatusOK
}
return sagaStatusUnsupported
}
func (sp *SagaProcess) cancelTX(from etf.Pid, cancel messageSagaCancel, tx *SagaTransaction) {
tx.cancelTimer()
// stop workers
tx.Lock()
cancelJobs := []etf.Pid{}
for _, pid := range tx.jobs {
sp.Unlink(pid)
sp.Cast(pid, messageSagaJobCancel{reason: cancel.Reason})
cancelJobs = append(cancelJobs, pid)
}
tx.Unlock()
sp.mutexJobs.Lock()
for i := range cancelJobs {
job, ok := sp.jobs[cancelJobs[i]]
if ok {
delete(sp.jobs, cancelJobs[i])
job.cancelTimer()
}
}
sp.mutexJobs.Unlock()
// remove monitor from parent saga
if tx.parents[0] != sp.Self() {
sp.DemonitorProcess(tx.monitor)
// do not send to the parent saga if it came from there
// and cancelation reason caused by lifespan timer
if tx.parents[0] != from && cancel.Reason != "lifespan" {
cm := etf.Tuple{
etf.Atom("$saga_cancel"),
sp.Self(),
etf.Tuple{
cancel.TransactionID,
etf.Ref(tx.origin),
cancel.Reason,
},
}
sp.Send(tx.parents[0], cm)
}
}
// send cancel to all next sagas except the saga this cancel came from
sp.mutexNext.Lock()
for nxtid, nxt := range tx.next {
ref := etf.Ref(nxtid)
// remove monitor from the next saga
sp.DemonitorProcess(ref)
delete(sp.next, nxtid)
nxt.cancelTimer()
if cancel.Reason == "lifespan" {
// do not send if the cancelation caused by lifespan timer
continue
}
if ref == cancel.Origin {
// do not send to the parent if it came from there
continue
}
cm := etf.Tuple{
etf.Atom("$saga_cancel"),
sp.Self(),
etf.Tuple{
cancel.TransactionID,
ref,
cancel.Reason,
},
}
if err := sp.Send(nxt.Saga, cm); err != nil {
errmessage := MessageSagaError{
TransactionID: tx.id,
NextID: nxtid,
Error: "can't send cancel message",
Details: err.Error(),
}
sp.Send(sp.Self(), errmessage)
}
}
sp.mutexNext.Unlock()
// remove tx from this saga
sp.mutexTXS.Lock()
delete(sp.txs, tx.id)
sp.mutexTXS.Unlock()
}
func (sp *SagaProcess) commitTX(tx *SagaTransaction, final interface{}) {
tx.cancelTimer()
// remove tx from this saga
sp.mutexTXS.Lock()
delete(sp.txs, tx.id)
sp.mutexTXS.Unlock()
// send commit message to all workers
for _, pid := range tx.jobs {
// unlink before this worker stopped
sp.Unlink(pid)
// do nothing if 2PC option is disabled
if tx.options.TwoPhaseCommit == false {
continue
}
// send commit message
sp.Cast(pid, messageSagaJobCommit{final: final})
}
// remove monitor from parent saga
sp.DemonitorProcess(tx.monitor)
sp.mutexNext.Lock()
for nxtid, nxt := range tx.next {
ref := etf.Ref(nxtid)
// remove monitor from the next saga
sp.DemonitorProcess(ref)
delete(sp.next, nxtid)
nxt.cancelTimer()
// send commit message
if tx.options.TwoPhaseCommit == false {
continue
}
cm := etf.Tuple{
etf.Atom("$saga_commit"),
sp.Self(),
etf.Tuple{
etf.Ref(tx.id), // tx id
ref, // origin (next_id)
final, // final result
},
}
if err := sp.Send(nxt.Saga, cm); err != nil {
errmessage := MessageSagaError{
TransactionID: tx.id,
NextID: nxtid,
Error: "can't send commit message",
Details: err.Error(),
}
sp.Send(sp.Self(), errmessage)
}
}
sp.mutexNext.Unlock()
}
func (sp *SagaProcess) handleSagaExit(exit MessageExit) error {
sp.mutexJobs.Lock()
job, ok := sp.jobs[exit.Pid]
sp.mutexJobs.Unlock()
if !ok {
// passthrough this message to HandleSagaInfo callback