|
| 1 | +package myapp |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "time" |
| 6 | + |
| 7 | + "ergo.services/ergo/act" |
| 8 | + "ergo.services/ergo/gen" |
| 9 | +) |
| 10 | + |
| 11 | +// Order with the states: new, processing, shipped, delivered, canceled |
| 12 | + |
| 13 | +type OrderData struct { |
| 14 | + items []string |
| 15 | + processed time.Time |
| 16 | + shipped time.Time |
| 17 | + delivered time.Time |
| 18 | + canceled time.Time |
| 19 | +} |
| 20 | + |
| 21 | +type Order struct { |
| 22 | + act.StateMachine[OrderData] |
| 23 | +} |
| 24 | + |
| 25 | +func factoryOrder() gen.ProcessBehavior { |
| 26 | + return &Order{} |
| 27 | +} |
| 28 | + |
| 29 | +func (order *Order) Init(args ...any) (act.StateMachineSpec[OrderData], error) { |
| 30 | + spec := act.NewStateMachineSpec(gen.Atom("new"), |
| 31 | + // new |
| 32 | + act.WithStateCallback(gen.Atom("new"), process), |
| 33 | + act.WithStateCallback(gen.Atom("new"), cancel), |
| 34 | + // processing |
| 35 | + act.WithStateCallback(gen.Atom("processing"), ship), |
| 36 | + act.WithStateCallback(gen.Atom("processing"), cancel), |
| 37 | + // shipped |
| 38 | + act.WithStateCallback(gen.Atom("shipped"), deliver), |
| 39 | + ) |
| 40 | + |
| 41 | + return spec, nil |
| 42 | +} |
| 43 | + |
| 44 | +type Process struct{} |
| 45 | + |
| 46 | +type Ship struct { |
| 47 | + priority bool |
| 48 | +} |
| 49 | + |
| 50 | +type Deliver struct{} |
| 51 | + |
| 52 | +type Cancel struct { |
| 53 | + reason string |
| 54 | +} |
| 55 | + |
| 56 | +func process(sm *act.StateMachine[OrderData], message Process) error { |
| 57 | + data := sm.Data() |
| 58 | + if len(data.items) < 1 { |
| 59 | + return fmt.Errorf("can't process order as there are no items added yet") |
| 60 | + } |
| 61 | + sm.Log().Info("processing order...") |
| 62 | + data.processed = time.Now() |
| 63 | + sm.SetData(data) |
| 64 | + sm.SetCurrentState(gen.Atom("processing")) |
| 65 | + return nil |
| 66 | +} |
| 67 | + |
| 68 | +func ship(sm *act.StateMachine[OrderData], message Ship) error { |
| 69 | + data := sm.Data() |
| 70 | + sm.Log().Info("shiping order...") |
| 71 | + data.shipped = time.Now() |
| 72 | + sm.SetData(data) |
| 73 | + sm.SetCurrentState(gen.Atom("shipped")) |
| 74 | + return nil |
| 75 | +} |
| 76 | + |
| 77 | +func deliver(sm *act.StateMachine[OrderData], message Deliver) error { |
| 78 | + data := sm.Data() |
| 79 | + sm.Log().Info("delivering order...") |
| 80 | + data.delivered = time.Now() |
| 81 | + sm.SetData(data) |
| 82 | + sm.SetCurrentState(gen.Atom("delivered")) |
| 83 | + return nil |
| 84 | +} |
| 85 | + |
| 86 | +func cancel(sm *act.StateMachine[OrderData], message Cancel) error { |
| 87 | + data := sm.Data() |
| 88 | + sm.Log().Info("canceling order...") |
| 89 | + data.canceled = time.Now() |
| 90 | + sm.SetData(data) |
| 91 | + sm.SetCurrentState(gen.Atom("canceled")) |
| 92 | + return nil |
| 93 | +} |
0 commit comments