-
Notifications
You must be signed in to change notification settings - Fork 5
/
status.go
118 lines (90 loc) · 2.01 KB
/
status.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
package block_stm
import "sync"
type Status uint
const (
StatusReadyToExecute Status = iota
StatusExecuting
StatusExecuted
StatusAborting
StatusSuspended
)
// StatusEntry is a state machine for the status of a transaction, all the transitions are atomic protected by a mutex.
//
// ```mermaid
// stateDiagram-v2
//
// [*] --> ReadyToExecute
// ReadyToExecute --> Executing: TrySetExecuting()
// Executing --> Executed: SetExecuted()
// Executing --> Suspended: Suspend(cond)\nset cond
// Executed --> Aborting: TryValidationAbort(incarnation)
// Aborting --> ReadyToExecute: SetReadyStatus()\nincarnation++
// Suspended --> Executing: Resume()
//
// ```
type StatusEntry struct {
sync.Mutex
incarnation Incarnation
status Status
cond *Condvar
}
func (s *StatusEntry) IsExecuted() (ok bool, incarnation Incarnation) {
s.Lock()
if s.status == StatusExecuted {
ok = true
incarnation = s.incarnation
}
s.Unlock()
return
}
func (s *StatusEntry) TrySetExecuting() (Incarnation, bool) {
s.Lock()
if s.status == StatusReadyToExecute {
s.status = StatusExecuting
incarnation := s.incarnation
s.Unlock()
return incarnation, true
}
s.Unlock()
return 0, false
}
func (s *StatusEntry) setStatus(status Status) {
s.Lock()
s.status = status
s.Unlock()
}
func (s *StatusEntry) Resume() {
// status must be SUSPENDED and cond != nil
s.Lock()
s.status = StatusExecuting
s.cond.Notify()
s.cond = nil
s.Unlock()
}
func (s *StatusEntry) SetExecuted() {
// status must have been EXECUTING
s.setStatus(StatusExecuted)
}
func (s *StatusEntry) TryValidationAbort(incarnation Incarnation) bool {
s.Lock()
if s.incarnation == incarnation && s.status == StatusExecuted {
s.status = StatusAborting
s.Unlock()
return true
}
s.Unlock()
return false
}
func (s *StatusEntry) SetReadyStatus() {
s.Lock()
s.incarnation++
// status must be ABORTING
s.status = StatusReadyToExecute
s.Unlock()
}
func (s *StatusEntry) Suspend(cond *Condvar) {
s.Lock()
s.cond = cond
s.status = StatusSuspended
s.Unlock()
}