package machineimport ()// ///// ///// /////// ///// PUB UTILS// ///// ///// /////// IsActiveTick returns true if the tick represents an active state// (odd number).func ( uint64) bool {return %2 == 1}// NextActive returns the absolute tick when the state will be active again// (excluding the currently active tick).func ( uint64) uint64 {ifIsActiveTick() {return + 2 }return + 1}// NextInactive returns the absolute tick when the state will be inactive again// (excluding the currently inactive tick).func ( uint64) uint64 {if !IsActiveTick() {return + 2 }return + 1}// NextActiveIn returns the number of ticks until the state will be active again// (excluding the currently active tick).func ( uint64) int {ifIsActiveTick() {return2 }return1}// NextInactiveIn returns the number of ticks until the state will be inactive// again (excluding the currently inactive tick).func ( uint64) int {if !IsActiveTick() {return2 }return1}// IsQueued returns true if the mutation has been queued, and the result// represents the queue time it will be processed.func ( Result) bool {return > Canceled}// EnvLogLevel returns a log level from an environment variable, AM_LOG by// default.func ( string) LogLevel {if == "" { = EnvAmLog } , := strconv.Atoi(os.Getenv())returnLogLevel()}// TODO prevent using these names as state namesvar handlerSuffixes = []string{SuffixEnter, SuffixExit, SuffixState, SuffixEnd, StateAny,}// IsHandler checks if a method name is a handler method, by returning a state// name.func ( S, string) (string, string) {if == StateAny+SuffixEnter || == StateAny+SuffixState {return"", "" }// suffixesfor , := rangehandlerSuffixes {ifstrings.HasSuffix(, ) && len() != len() && != StateAny+ {return [0 : len()-len()], "" } }// AnyFooifstrings.HasPrefix(, StateAny) && len() != len(StateAny) && != StateAny+SuffixState {return [len(StateAny):], "" }// FooBarfor , := range {if !strings.HasPrefix(, ) {continue }for , := range {if + == {return , } } }return"", ""}// TestMockClock mocks the internal clock of the machine. Only for testing.func ( *Machine, Clock) { .clock = }// AMerge merges 2 or more maps into 1. Useful for passing args from many// packages.func [ comparable, any]( ...map[]) map[] { := map[]{}for , := range {for , := range { [] = } }return}// ///// ///// /////// ///// STATE LIST// ///// ///// /////// S (state names) is a string list of state names.typeS []string// TODO NewS([]string, stateLists ... string) S// - should filter newlines// FilterIndex returns a subset of S from specified indexes.func ( S) ( []int) S {returnIndexToStates(, )}// Unique returns a new slice with unique state names.func ( S) () S {returnslicesUniq()}// FilterPrefix returns all the states with a prefix.func ( S) ( ...string) S { := S{}for , := range { = .Add(StatesWithPrefix(, )) }return}// FilterMatch returns all the states matching a regexp.func ( S) ( *regexp.Regexp) S { := S{}for , := range {if .MatchString() { = append(, ) } }return}// Prefix prefixes all state names with [prefix].func ( S) ( string) S {returnStatesPrefix(, )}// Add concatenates multiple state lists into one, removing duplicates.// Useful for merging lists of states, eg a state group with other states// involved in a relation.func ( S) ( ...S) S {iflen() == 0 {return } = append([]S{}, ...)returnslicesUniq(slices.Concat(...))}// Add1 is like [S.Add], but for single state names.func ( S) ( ...string) S { := slices.Clone() := append(, ...)returnslicesUniq()}// Delete removes states from all passed state groups.func ( S) ( ...S) S {returnSRem(, ...)}// Delete1 is like [S.Delete], but for single state names.func ( S) ( ...string) S {returnSRem(, )}// Sub returns the states from [s] that are missing in [other] (subtract).// Deprecated, [S.Delete].func ( S) ( S) S {returnStatesDiff(, )}// Sub1 returns the states from [s] without [state] (subtract).// Deprecated, use [S.Delete1].func ( S) ( string) S {returnStatesDiff(, S{})}// Shared returns states present in both S and other (overlap).func ( S) ( S) S {returnStatesShared(, )}// Equal returns true if states1 and states2 are equal, regardless of// order.func ( S) ( S) bool {returnStatesEqual(, )}// EqualOrder is like [S.Equal], but also checks the order of states.func ( S) ( S) bool {iflen() != len() {returnfalse }for := range {if [] != strings.TrimSpace([]) {returnfalse } }returntrue}// EqualIndex is like [S.EqualOrder], but for state indexes instead of names.func ( S) ( []int) bool { := .Index(nil)returnslices.Equal(, )}// Index returns an index of passed [states]. Unknown states are// represented by -1.func ( S) ( S) []int {returnStatesToIndex(, )}// Index1 is [S.Index] for a single state.func ( S) ( string) int {returnslices.Index(, )}// Hash returns a short hash of this state set.func ( S) () string {returnHash(strings.Join(, ","), 4)}// Has returns true is [state] is in this state set.// TODO v0.20 Has1(string), Is1(S), like amhelp.Implementsfunc ( S) ( string) bool {returnslices.Contains(, )}// TODO v0.20 Has1(string), Is(S), like amhelp.Implementsfunc ( S) ( S) bool {for , := range {if !slices.Contains(, ) {returnfalse } }returntrue}// TODO Not(), Not1()func ( S) ( string) S {returnslices.DeleteFunc(, func( string) bool {return == })}func ( S) ( S) S {returnslices.DeleteFunc(, func( string) bool {returnslices.Contains(, ) })}// ----- old// IndexToStates is deprecated, use [S.FilterIndex].// Deprecated.func ( S, []int) S { := make(S, len())for := range { := "unknown" + strconv.Itoa([])iflen() > [] && [] != -1 { = [[]] } [] = }return}// StatesToIndex is deprecated, use [S.Index].// Deprecated.func ( S, S) []int { := make([]int, len())for := range { [] = slices.Index(, strings.TrimSpace([])) }return}// StatesDiff is deprecated, use [S.Delete].// Deprecated.func ( S, S) S {// TODO optimizereturnslicesFilter(, func( string, int) bool {return !slices.Contains(, ) })}// StatesShared is deprecated, use [S.Shared].// Deprecated.func ( S, S) S {returnslicesFilter(, func( string, int) bool {returnslices.Contains(, ) })}// StatesEqual is deprecated, use [S.Equal].// Deprecated.func ( S, S) bool {returnslicesEvery(, ) && slicesEvery(, )}// StatesPrefix is deprecated, use [S.Prefix].// Deprecated.func ( string, S) S { := make(S, len())for , := range { [] = + }return}// StatesWithPrefix is deprecated, use [S.FilterPrefix].// Deprecated.func ( string, S) S { := S{}for , := range {ifstrings.HasPrefix(, ) { = append(, ) } }return}// SAdd is deprecated, use [S.Add].// Deprecated.func ( ...S) S {// TODO testiflen() == 0 {returnS{} } := slices.Clone([0])for := 1; < len(); ++ { = append(, []...) }returnslicesUniq()}// SRem is deprecated, use [S.Delete].// Deprecated.func ( S, ...S) S {// TODO test := slices.Clone()iflen() == 0 {return }for := range {for := 0; < len([]); ++ { = slicesWithout(, [][]) } }return}// ///// ///// /////n// ///// SCHEMA// ///// ///// /////// ----- STATE// State defines a single state of a machine, its properties, relations, and tags.// nolint:llltypeStatestruct { Auto bool`json:"auto,omitempty" yaml:"auto,omitempty" toml:"auto,omitempty"` Multi bool`json:"multi,omitempty" yaml:"multi,omitempty" toml:"multi,omitempty"` Require S`json:"require,omitempty" yaml:"require,omitempty" toml:"require,omitempty"` Add S`json:"add,omitempty" yaml:"add,omitempty" toml:"add,omitempty"` Remove S`json:"remove,omitempty" yaml:"remove,omitempty" toml:"remove,omitempty"` After S`json:"after,omitempty" yaml:"after,omitempty" toml:"after,omitempty"` Tags []string`json:"tags,omitempty" yaml:"tags,omitempty" toml:"tags,omitempty"`}// Extend adds new states to relations of the source state, without// removing existing ones. Useful for adjusting shared stated to a specific// machine. Only "true" values for Auto and Multi are applied from [overlay].//// ssS.HandshakeDone: SharedSchema[ssS.HandshakeDone].Extend(// am.State{// Require: S{ssS.ClientConnected},// Remove: S{Exception},// }),func ( State) ( State) State {returnStateAdd(, )}// Set replaces passed relations and properties of the source state.// Only relations in the overlay state are replaced, the rest is preserved.// If [overlay] has all fields `nil`, then only [auto] and [multi] get applied.//// ssS.HandshakeDone: s.Set(false, true, State{// Remove: S{"C"},// })func ( State) (, bool, State) State {returnStateSet(, , , )}// SetRels is like [State.Set], but inherits properties (Auto, Multi).func ( State) ( State) State {returnStateSet(, .Auto, .Multi, )}func ( State) () State { := State{Auto: .Auto,Multi: .Multi, }if .Require != nil { .Require = slices.Clone(.Require) }if .Add != nil { .Add = slices.Clone(.Add) }if .Remove != nil { .Remove = slices.Clone(.Remove) }if .After != nil { .After = slices.Clone(.After) }if .Tags != nil { .Tags = slices.Clone(.Tags) }return}func ( State) ( string) bool {returnslices.Contains(.Tags, )}// ----- old// StateAdd is deprecated, use [State.Extend].// Deprecated.func ( State, State) State {// TODO example // TODO test := .Clone() := .Clone()if .Auto { .Auto = true }if .Multi { .Multi = true }// relationsif .Add != nil { .Add = SAdd(.Add, .Add) }if .Remove != nil { .Remove = SAdd(.Remove, .Remove) }if .Require != nil { .Require = SAdd(.Require, .Require) }if .After != nil { .After = SAdd(.After, .After) }return}// StateSet is deprecated, use [State.Set].// Deprecated.func ( State, , bool, State) State {// TODO example // TODO test := .Clone() := .Clone()// properties .Auto = .Multi = // relationsif .Add != nil { .Add = .Add }if .Remove != nil { .Remove = .Remove }if .Require != nil { .Require = .Require }if .After != nil { .After = .After }return}// ///// ///// /////// ///// HANDLERS// ///// ///// /////// handler represents a list of transition handler methods.type handler struct { id string num int// map-based handler isMap bool mx sync.Mutex opts *BindOpts// maps negotiations map[string]HandlerNegotiation partials map[string]HandlerNegotiationPartial finals map[string]HandlerFinal// reflect refl handlerReflect}// BindOpts define how the methods are bound to the state machine. Optional.typeBindOptsstruct {// Id of this binding, optional. Id string// Method names will have this prefix removed MethodPrefixTrim string// Bind only the states with this prefix StatePrefix string// TODO ExecOnActive to run handlers of active states // in order they depend on each other and order of activation // (save activation tick)}// handlerReturn is a return of a single handlerCall.type handlerReturn struct {// was the handler called? called bool// did the handler time out? timeout bool// hard cancel, full tx rejection canceled bool// binary negotiation return retBool bool// partial negotiation return of called states retStates S// partial negotiation return marker partialNeg bool// only for partialNeg true partiallyAccepted bool// implied states rejected via Event.AcceptWithout in the current handler rejectedImplied S// states rejected in this partial acceptance (called and implied), // used for logging rejected S}type handlerCall struct { refl handlerCallReflect// TODO debug only name string negotiation HandlerNegotiation negotiationPartial HandlerNegotiationPartial final HandlerFinal event *Event timeout bool debug string}func newHandlerCallMap( *Event, *handler, string, *Machine,) *handlerCall {// := strings.HasSuffix(, SuffixState) ||strings.HasSuffix(, SuffixEnd)if {if , := .finals[]; ! { .mx.Unlock()returnnil } } else { , := .negotiations[] , := .partials[]if ! && ! { .mx.Unlock()returnnil } } .mx.Unlock()// call the handler .log(LogOps, "[handler:%d] %s", .num, ) .currentHandler.Store()// tracers .tracersMx.RLock()for := range .tracers { .tracers[].HandlerStart(.t.Load(), .id, ) } .tracersMx.RUnlock() := &handlerCall{name: ,event: ,timeout: false, }if { .final = .finals[] } elseif , := .negotiations[]; { .negotiation = } else { .negotiationPartial = .partials[] }return}// ///// ///// /////// ///// UTILS// ///// ///// /////// truncateStr with shorten the string and leave a tripedot suffix.func truncateStr( string, int) string {iflen() <= {return }if < 5 {return [:] } else {return [:-3] + "..." }}// j joins state names into a single stringfunc j( []string) string {returnstrings.Join(, " ")}// jw joins state names into a single string with a separator.func jw( []string, string) string {returnstrings.Join(, )}func closeSafe[ any]( chan ) {select {case<-:default:close() }}// compareArgs return true if args2 is a subset of args1.func compareArgs(, A) bool { := truefor , := range {// TODO better comparisonsif [] != { = falsebreak } }return}// RandId generates a random ID of the given length (defaults to 8).func randId( int) string {if == 0 { = 16 } ++ = / 2 := make([]byte, ) , := rand.Read()if != nil {return"error" }returnhex.EncodeToString()}func slicesWithout[ ~[], comparable]( , ) { := slices.Index(, ) := slices.Clone()if == -1 {return }returnslices.Delete(, , +1)}// slicesNone returns true if none of the elements of coll2 are in coll1.func slicesNone[ ~[], ~[], comparable]( , ) bool {for , := range {ifslices.Contains(, ) {returnfalse } }returntrue}// slicesEvery returns true if all elements of coll2 are in coll1.func slicesEvery[ ~[], ~[], comparable]( , ) bool {for , := range {if !slices.Contains(, ) {returnfalse } }returntrue}// TODO replace with slices.DeleteFuncfunc slicesFilter[ ~[], any]( , func( , int) bool) { := make(, 0, len())for , := range {if (, ) { = append(, ) } }return}func slicesReverse[ ~[], any]( ) { := make(, len())for := range { [] = [len()-1-] }return}func slicesUniq[ comparable]( []) [] {iflen() == 0 {return []{} } := make(map[]struct{}, len()) := make([], 0, len())for , := range {if , := []; ! { [] = struct{}{} = append(, ) } }return}func cloneOptions( *Opts) *Opts {if == nil {return &Opts{} }return &Opts{Id: .Id,HandlerTimeout: .HandlerTimeout,DontPanicToException: .DontPanicToException,DontLogStackTrace: .DontLogStackTrace,DontLogId: .DontLogId,Resolver: .Resolver,LogLevel: .LogLevel,Tracers: .Tracers,LogArgs: .LogArgs,QueueLimit: .QueueLimit,Parent: .Parent,ParentId: .ParentId,Tags: .Tags,DetectEval: .DetectEval, }}func ( string) string {if == "" {return"" }// Decode the first character to find out exactly how many bytes it uses , := utf8.DecodeRuneInString()// Uppercase the first character, then append the rest of the original stringreturnstrings.ToUpper(string()) + [:]}// OptArgs will return the first [A] from a list.func ( []A) A {iflen() > 0 {return [0] }returnnil}// OptCtx will return the first [context.Context] from a list.func ( []context.Context) context.Context {iflen() > 0 {return [0] }returnnil}// OptEv will return the first [*Event] from a list.func ( []*Event) *Event {iflen() > 0 {return [0] }returnnil}// optBindOpts will return the first [BindOpts] from a list.func optBindOpts( []BindOpts) BindOpts {iflen() > 0 {return [0] }returnBindOpts{}}// goroutineNum returns the ID of the current goroutine, or 0 if err.// Numbers are re-assigned, so this is not a bulletproof way of IDing threads.func goroutineNum() int64 { := make([]byte, 4024) := runtime.Stack(, false) := string([:]) := strings.Split(, "\n") := strings.Split([0], " ") , := strconv.Atoi([1])returnint64()}func captureStackTrace() string { := make([]byte, 4024) := runtime.Stack(, false) := string([:]) := strings.Split(, "\n") := strings.Contains(, "panic")slices.Reverse() := []string{"AddErr", "AddErrState", "Remove", "Remove1", "Add", "Add1", "Set", }// TODO trim tails start at reflect.Value.Call({ // with asyncmachine 2 frames down// trim the head, remove junk := falsefor , := range {if && strings.HasPrefix(, "panic(") { = [:-1]break }for , := range {ifstrings.Contains("machine.(*Machine)."++"(", ) { = [:-1] = truebreak } }if {break } }slices.Reverse() := strings.Join(, "\n")if := os.Getenv(EnvAmTraceFilter); != "" { = strings.ReplaceAll(, , "") }return}// Hash is a general hashing function.func ( string, int) string { := md5.New() .Write([]byte())if == 0 { = 6 } := hex.EncodeToString(.Sum(nil))// short hashreturn [:]}
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.