-
Notifications
You must be signed in to change notification settings - Fork 2
/
examples_test.go
211 lines (192 loc) · 7.62 KB
/
examples_test.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
package maquina_test
import (
"bytes"
"context"
"errors"
"fmt"
"math/rand"
"time"
"github.com/soypat/go-maquina"
)
func ExampleStateMachine_tollBooth() {
rand.Seed(1)
const (
passageCost = 10.00
defaultPay = 0.0
payUp maquina.Trigger = "customer pays"
customerAdvances maquina.Trigger = "customer advances"
)
var (
tollClosed = maquina.NewState("toll barrier closed", defaultPay)
tollOpen = maquina.NewState("toll barrier open", defaultPay)
guardPay = maquina.NewGuard("payment check", func(ctx context.Context, pay float64) error {
if pay < passageCost {
// Barrier remains closed unless customer pays up
return fmt.Errorf("customer underpaid with $%.2f", pay)
}
return nil
})
)
tollClosed.Permit(payUp, tollOpen, guardPay)
tollOpen.Permit(customerAdvances, tollClosed)
SM := maquina.NewStateMachine(tollClosed)
for i := 0; i < 5; i++ {
pay := 2 * passageCost * rand.Float64()
err := SM.FireBg(payUp, pay)
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("customer paid $%.2f, let them pass!\n", pay)
SM.FireBg(customerAdvances, 0)
}
}
//Output:
// customer paid $12.09, let them pass!
// customer paid $18.81, let them pass!
// customer paid $13.29, let them pass!
// guard clause "payment check" failed: customer underpaid with $8.75
// guard clause "payment check" failed: customer underpaid with $8.49
}
func ExampleWriteDOT_threeDPrinter() {
type printerState struct {
x, y, z int
}
// Declaration of triggers. These are actions.
// In the example of a 3D printer one could think of them
// as buttons exposed to the end user.
const (
trigHome maquina.Trigger = "home"
trigCalibrate maquina.Trigger = "calibrate"
trigStop maquina.Trigger = "stop"
)
var (
// stateSingleton contains the state of the printer at all times.
// It is a singleton and is shared by all states.
stateSingleton = &printerState{}
stateIdleHome = maquina.NewState("idle at home", stateSingleton)
stateIdle = maquina.NewState("idle", stateSingleton)
stateCalibrating = maquina.NewState("calibrating", stateSingleton)
stateGoingHome = maquina.NewState("going home", stateSingleton)
// guardNotAtHome is a guard clause that checks if the printer is at home position.
guardNotAtHome = maquina.NewGuard("not at home", func(ctx context.Context, state *printerState) error {
if state.x != 0 || state.y != 0 || state.z != 0 {
return fmt.Errorf("not at home")
}
return nil
})
)
// Declare Calibration and Stop transitions. These would be the actions taken
// when user presses CALIBRATE or STOP button.
stateIdleHome.Permit(trigCalibrate, stateCalibrating)
stateIdle.Permit(trigCalibrate, stateCalibrating, guardNotAtHome)
// Special case of STOP while home: we stay at home.
stateIdleHome.Permit(trigStop, stateIdleHome)
// Declare home transitions. These would be the actions taken when a user presses
// the HOME button, as an example.
stateCalibrating.Permit(trigHome, stateGoingHome)
stateIdle.Permit(trigHome, stateGoingHome)
stateGoingHome.Permit(trigHome, stateIdleHome, guardNotAtHome)
sm := maquina.NewStateMachine(stateIdleHome)
// In the case of stopping we go to Idle state since we are not
// guaranteed to be at home position.
sm.AlwaysPermit(trigStop, stateIdle)
var buf bytes.Buffer
maquina.WriteDOT(&buf, sm)
fmt.Println(buf.String())
// With the code below one can also output a PNG file with the graph:
// One must have graphviz installed and in the path: `sudo apt install graphviz`
//
// cmd := exec.Command("dot", "-Tpng", "-o", "3dprinterNoBug.png")
// cmd.Stdin = &buf
// cmd.Run()
// Unordered output:
// digraph {
// rankdir=LR;
// node [shape = box];
// graph [ dpi = 300 ];
// "idle at home" -> "calibrating" [ label = "calibrate", style = "solid" ];
// "calibrating" -> "going home" [ label = "home", style = "solid" ];
// "going home" -> "idle at home" [ label = "home\n[not at home]", style = "dashed" ];
// "calibrating" -> "idle" [ label = "stop", style = "solid" ];
// "idle" -> "calibrating" [ label = "calibrate\n[not at home]", style = "dashed" ];
// "idle" -> "going home" [ label = "home", style = "solid" ];
// "idle at home" -> "idle at home" [ label = "stop", style = "solid" ];
// "going home" -> "idle" [ label = "stop", style = "solid" ];
// "idle" -> "idle" [ label = "stop", style = "solid" ];
// }
}
func ExampleWriteDOT_algorithmicTrading() {
getStock := func() string {
return string([]byte{byte(rand.Intn(26)) + 'A', byte(rand.Intn(26)) + 'A', byte(rand.Intn(26)) + 'A'})
}
type tradeState struct {
targetStock string
quoteReceived time.Time
}
type transition = maquina.Transition[*tradeState]
const (
trigRequestQuote = "request quote"
trigExecute = "execute"
trigExecuteFail = "execute failed"
trigCancel = "cancel"
trigQuoteReceived = "quote received"
trigExecuteConfirmed = "execute confirmed"
)
var (
stateWaitingOnQuote = maquina.NewState("waiting on quote", &tradeState{})
stateReadyToOperate = maquina.NewState("ready to operate", &tradeState{})
stateIdle = maquina.NewState("idle", &tradeState{})
stateExecuting = maquina.NewState("executing", &tradeState{})
stateCritical = maquina.NewState("critical section", &tradeState{})
fringeStockSelect = maquina.NewFringeCallback("stock select", func(_ context.Context, _ transition, state *tradeState) {
state.targetStock = getStock()
})
fringeStockClear = maquina.NewFringeCallback("stock clear", func(_ context.Context, _ transition, state *tradeState) {
state.targetStock = ""
})
guardQuoteStale = maquina.NewGuard("quote staleness", func(ctx context.Context, state *tradeState) error {
const staleQuoteTimeout = 10 * time.Minute
elapsed := time.Since(state.quoteReceived)
if elapsed > staleQuoteTimeout || elapsed < 1 { // Sanity check included.
return errors.New("quote is stale: " + elapsed.String() + " elapsed")
}
return nil
})
)
stateIdle.Permit(trigRequestQuote, stateWaitingOnQuote)
stateIdle.OnExitThrough(trigRequestQuote, fringeStockSelect)
stateIdle.OnEntry(fringeStockClear)
stateWaitingOnQuote.Permit(trigCancel, stateIdle)
stateWaitingOnQuote.Permit(trigQuoteReceived, stateReadyToOperate)
stateReadyToOperate.Permit(trigExecute, stateExecuting, guardQuoteStale)
stateReadyToOperate.Permit(trigCancel, stateIdle)
stateExecuting.Permit(trigExecuteConfirmed, stateIdle)
stateExecuting.Permit(trigExecuteFail, stateReadyToOperate)
// Mark critical section as a superstate.
stateCritical.LinkSubstates(stateReadyToOperate, stateExecuting)
sm := maquina.NewStateMachine(stateIdle)
var buf bytes.Buffer
maquina.WriteDOT(&buf, sm)
// cmd := exec.Command("dot", "-Tpng", "-o", "3dprinterNoBug.png")
// cmd.Stdin = &buf
// cmd.Run()
fmt.Println(buf.String())
//Unordered output:
// digraph {
// rankdir=LR;
// node [shape = box];
// graph [ dpi = 300 ];
// "idle" -> "waiting on quote" [ label = "request quote", style = "solid" ];
// "waiting on quote" -> "idle" [ label = "cancel", style = "solid" ];
// "waiting on quote" -> "ready to operate" [ label = "quote received", style = "solid" ];
// "ready to operate" -> "executing" [ label = "execute\n[quote staleness]", style = "dashed" ];
// "ready to operate" -> "idle" [ label = "cancel", style = "solid" ];
// "executing" -> "idle" [ label = "execute confirmed", style = "solid" ];
// "executing" -> "ready to operate" [ label = "execute failed", style = "solid" ];
// subgraph cluster_0 {
// label = "critical section";
// "ready to operate";
// "executing";
// }
// }
}