-
Notifications
You must be signed in to change notification settings - Fork 0
/
workdata.go
115 lines (96 loc) · 2.28 KB
/
workdata.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
package workflow
import (
"context"
"fmt"
"sync"
"github.com/sirupsen/logrus"
)
type WorkData struct {
workBegin *funcs
workBeforeCommit *funcs
workCommit *funcs
workFinish *funcs
workRollback *funcs
currentState *funcs
ctx map[string]interface{}
ctxLocker sync.RWMutex
isAborted bool
Logger *logrus.Entry
}
func NewWorkData() *WorkData {
d := &WorkData{
workBegin: NewFuncs(),
workBeforeCommit: NewFuncs(),
workCommit: NewFuncs(),
workFinish: NewFuncs(),
workRollback: NewFuncs(),
ctx: make(map[string]interface{}),
Logger: logrus.StandardLogger().WithField("from", "workflow"),
}
d.ResetProgress()
return d
}
func (d *WorkData) Get(key string) (interface{}, bool) {
d.ctxLocker.RLock()
defer d.ctxLocker.RUnlock()
data, ok := d.ctx[key]
return data, ok
}
func (d *WorkData) MustGet(key string) interface{} {
if data, ok := d.Get(key); !ok {
panic(fmt.Sprintf("key: %v is not exists", key))
} else {
return data
}
}
func (d *WorkData) Set(key string, value interface{}) {
d.ctxLocker.Lock()
defer d.ctxLocker.Unlock()
d.ctx[key] = value
}
func (d *WorkData) Next(ctx context.Context) error {
if d.currentState == nil {
return nil
}
defer func() {
d.currentState = nil
}()
return d.currentState.next(ctx, d)
}
func (d *WorkData) Abort() {
d.isAborted = true
if d.currentState == nil {
return
}
d.currentState.abort()
}
func (d *WorkData) IsAborted() bool {
return (d.currentState != nil && d.currentState.isAborted()) || d.isAborted
}
func (d *WorkData) ResetProgress() {
d.workBegin.reset()
d.workBeforeCommit.reset()
d.workCommit.reset()
d.workRollback.reset()
d.workFinish.reset()
}
func (d *WorkData) Begin(ctx context.Context) error {
d.currentState = d.workBegin
return d.Next(ctx)
}
func (d *WorkData) BeforeCommit(ctx context.Context) error {
d.currentState = d.workBeforeCommit
return d.Next(ctx)
}
func (d *WorkData) Commit(ctx context.Context) error {
d.currentState = d.workCommit
return d.Next(ctx)
}
func (d *WorkData) Rollback(ctx context.Context) error {
d.currentState = d.workRollback
return d.Next(ctx)
}
func (d *WorkData) Finish(ctx context.Context) error {
d.currentState = d.workFinish
return d.Next(ctx)
}