forked from temporalio/temporal
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuffer.go
More file actions
52 lines (46 loc) · 1.53 KB
/
buffer.go
File metadata and controls
52 lines (46 loc) · 1.53 KB
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
package effect
import "context"
// Buffer holds a set of effect and rollback functions that can be invoked as a
// batch with a defined order. Once either Apply or Cancel is called, all
// buffered effects are cleared. This type is not threadsafe. The zero-value of
// a Buffer is a valid state.
type Buffer struct {
effects []func(context.Context)
cancels []func(context.Context)
}
// OnAfterCommit adds the provided effect function to set of such functions to
// be invoked when Buffer.Apply is called.
func (b *Buffer) OnAfterCommit(effect func(context.Context)) {
b.effects = append(b.effects, effect)
}
// OnAfterRollback adds the provided effect function to set of such functions to
// be invoked when Buffer.Cancel is called.
func (b *Buffer) OnAfterRollback(effect func(context.Context)) {
b.cancels = append(b.cancels, effect)
}
// Apply invokes the buffered effect functions in the order that they were added
// to this Buffer.
// It returns true if any effects were applied.
func (b *Buffer) Apply(ctx context.Context) bool {
applied := false
b.cancels = nil
for _, effect := range b.effects {
effect(ctx)
applied = true
}
b.effects = nil
return applied
}
// Cancel invokes the buffered rollback functions in the reverse of the order
// that they were added to this Buffer.
// It returns true if any effects were canceled.
func (b *Buffer) Cancel(ctx context.Context) bool {
canceled := false
b.effects = nil
for i := len(b.cancels) - 1; i >= 0; i-- {
b.cancels[i](ctx)
canceled = true
}
b.cancels = nil
return canceled
}