-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
7 changed files
with
283 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
# Binaries for programs and plugins | ||
*.exe | ||
*.exe~ | ||
*.dll | ||
*.so | ||
*.dylib | ||
# Test binary, built with `go test -c` | ||
*.test | ||
# Output of the go coverage tool, specifically when used with LiteIDE | ||
*.out | ||
# Dependency directories (remove the comment below to include it) | ||
# vendor/ | ||
# goland | ||
.idea |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2023 Necrobits | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,5 @@ | ||
# A collection of common libs in Golang | ||
|
||
## List of packages | ||
|
||
- `flow`: A library for finite state machine (FSM). A flow can have internal data and can be serialized to JSON. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
# Flow - Finite State Machine in Golang |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
package main | ||
|
||
import ( | ||
"encoding/json" | ||
"fmt" | ||
|
||
"github.com/necrobits/golib/flow" | ||
) | ||
|
||
const ( | ||
AwaitingPayment flow.State = "AwaitingPayment" | ||
AwaitingShipping flow.State = "AwaitingShipping" | ||
OrderFulfilled flow.State = "OrderFulfilled" | ||
|
||
PayForOrder flow.ActionType = "PayForOrder" | ||
) | ||
|
||
type OrderInternalState struct { | ||
OrderID string | ||
TotalAmount int | ||
Paid bool | ||
} | ||
|
||
type PaymentAction struct { | ||
Amount int | ||
} | ||
|
||
func (p PaymentAction) Type() flow.ActionType { | ||
return PayForOrder | ||
} | ||
|
||
type OrderFlowCreator struct { | ||
transTable flow.TransitionTable | ||
} | ||
|
||
func NewOrderFlowCreator() *OrderFlowCreator { | ||
f := &OrderFlowCreator{} | ||
f.transTable = flow.TransitionTable{ | ||
AwaitingPayment: flow.StateConfig{ | ||
Handler: f.HandlePayment, | ||
Transitions: flow.Transitions{ | ||
PayForOrder: AwaitingShipping, | ||
}, | ||
}, | ||
} | ||
return f | ||
} | ||
|
||
func (f *OrderFlowCreator) NewFlow(orderId string, amount int) *flow.Flow { | ||
return flow.New(flow.CreateFlowOpts{ | ||
ID: "flowID123", | ||
Type: "OrderFlow", | ||
Data: OrderInternalState{OrderID: orderId, TotalAmount: amount}, | ||
InitialState: AwaitingPayment, | ||
TransitionTable: f.transTable, | ||
}) | ||
} | ||
|
||
func (f *OrderFlowCreator) NewFlowFromSnapshot(s *flow.Snapshot) *flow.Flow { | ||
return flow.FromSnapshot(s, f.transTable) | ||
} | ||
|
||
func (f *OrderFlowCreator) HandlePayment(state flow.FlowData, a flow.Action) (flow.FlowData, error) { | ||
state = state.(OrderInternalState) | ||
payment := a.(PaymentAction) | ||
if payment.Amount != state.(OrderInternalState).TotalAmount { | ||
return nil, fmt.Errorf("payment amount does not match order total") | ||
} | ||
newState := state.(OrderInternalState) | ||
newState.Paid = true | ||
return newState, nil | ||
} | ||
|
||
func main() { | ||
orderFlowCreator := NewOrderFlowCreator() | ||
|
||
orderFlow := orderFlowCreator.NewFlow("123", 100) | ||
|
||
fmt.Printf("Current State: %s\n", orderFlow.CurrentState()) | ||
|
||
err := orderFlow.HandleAction(PaymentAction{Amount: 100}) | ||
if err != nil { | ||
fmt.Printf("Error: %s\n", err) | ||
} | ||
fmt.Printf("Current State: %s\n", orderFlow.CurrentState()) | ||
b, err := json.Marshal(orderFlow.ToSnapshot()) | ||
if err != nil { | ||
fmt.Printf("Error: %s\n", err) | ||
} | ||
fmt.Printf("Snapshot: %s\n", string(b)) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,149 @@ | ||
package flow | ||
|
||
import ( | ||
"fmt" | ||
) | ||
|
||
type Flow struct { | ||
id string | ||
flowType string | ||
data FlowData | ||
currentState State | ||
states TransitionTable | ||
} | ||
|
||
// FlowData is the internal data of the flow. This can be anything. | ||
type FlowData interface{} | ||
|
||
type TransitionTable map[State]StateConfig | ||
|
||
// Action is the interface that all actions must implement. | ||
type Action interface { | ||
Type() ActionType | ||
} | ||
|
||
// ActionType is the type of the action. It is used to identify the action in the FSMMap. | ||
type ActionType string | ||
|
||
// CreateFlowOpts is used to create a new Flow | ||
// ID is the unique identifier for the flow. | ||
// Type is the type of the flow. | ||
// Both ID and Type are used to identify the flow and restore it from a snapshot. | ||
// | ||
// Data is the initial internal data for the flow. | ||
// InitialState is the initial state for the flow. It must be one of the states in FSMMap. | ||
// FSMMap contains the description of the state machine for the flow. | ||
type CreateFlowOpts struct { | ||
ID string | ||
Type string | ||
Data FlowData | ||
InitialState State | ||
TransitionTable TransitionTable | ||
} | ||
|
||
// Snapshot is used to persist the flow, and restore it later. | ||
type Snapshot struct { | ||
ID string `json:"id"` | ||
Type string `json:"type"` | ||
Data FlowData `json:"data"` | ||
CurrentState State `json:"current_state"` | ||
} | ||
|
||
// ActionHandler is the function that handles an action. It can modify the internal data of the flow. | ||
// It returns the new internal data, and an error if any. | ||
// If the error is not nil, the flow will not change its state. | ||
// If the error is nil, the flow will change its state according to the transitions in FSMMap. | ||
type ActionHandler func(data FlowData, a Action) (FlowData, error) | ||
|
||
// State is just a name for a state in the state machine. | ||
type State string | ||
|
||
// Transitions is a map, describing the transition from a state to the next state. | ||
type Transitions map[ActionType]State | ||
|
||
// StateConfig is the configuration for a state in the state machine. | ||
// In addition to just a name, a State contains a handler function, and a map of transitions. | ||
// When the flow is in a state, and an action is received, the handler function of that state is called. | ||
type StateConfig struct { | ||
Handler ActionHandler | ||
Transitions Transitions | ||
} | ||
|
||
// HandleAction handles an action for the flow. | ||
// Everytime an action is handled, the flow may change its state. | ||
// This function is the only way to change the state of the flow. | ||
func (f *Flow) HandleAction(a Action) error { | ||
actionType := a.Type() | ||
stateConfig, ok := f.states[f.currentState] | ||
if !ok { | ||
return fmt.Errorf("illegal state: %s", f.currentState) | ||
} | ||
actionHandler := stateConfig.Handler | ||
nextState, ok := stateConfig.Transitions[actionType] | ||
if !ok { | ||
return fmt.Errorf("no transition found for event: %s", actionType) | ||
} | ||
if actionHandler != nil { | ||
newData, err := actionHandler(f.data, a) | ||
if err != nil { | ||
return err | ||
} | ||
f.data = newData | ||
} | ||
f.currentState = nextState | ||
return nil | ||
} | ||
|
||
// New creates a new Flow. | ||
func New(opts CreateFlowOpts) *Flow { | ||
if opts.TransitionTable == nil { | ||
panic("FSMMap cannot be nil") | ||
} | ||
if opts.InitialState == "" { | ||
panic("InitialState cannot be empty") | ||
} | ||
return &Flow{ | ||
id: opts.ID, | ||
flowType: opts.Type, | ||
data: opts.Data, | ||
currentState: opts.InitialState, | ||
states: opts.TransitionTable, | ||
} | ||
} | ||
|
||
// ToSnapshot converts the flow to a Snapshot to be persisted. | ||
func (f *Flow) ToSnapshot() Snapshot { | ||
return Snapshot{ | ||
ID: f.id, | ||
Type: f.flowType, | ||
Data: f.data, | ||
CurrentState: f.currentState, | ||
} | ||
} | ||
|
||
// FromSnapshot restores a flow from a Snapshot. | ||
func FromSnapshot(s *Snapshot, stateMap TransitionTable) *Flow { | ||
return &Flow{ | ||
id: s.ID, | ||
flowType: s.Type, | ||
data: s.Data, | ||
currentState: s.CurrentState, | ||
states: stateMap, | ||
} | ||
} | ||
|
||
func (f *Flow) ID() string { | ||
return f.id | ||
} | ||
|
||
func (f *Flow) Type() string { | ||
return f.flowType | ||
} | ||
|
||
func (f *Flow) CurrentState() State { | ||
return f.currentState | ||
} | ||
|
||
func (f *Flow) Data() FlowData { | ||
return f.data | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
module github.com/necrobits/golib | ||
|
||
go 1.19 |