DefaultRelationsResolver is the default implementation of the
RelationsResolver with Add, Remove, Require and After. It can be overridden
using Opts.Resolver.
TODO refac RelationsDefaultIndexS TODO replace with TimeIndex, log(), Schema
- for netmach mut filtering
- for alternative implsTransition*Transition InboundRelationsOf returns a list of states pointing to [toState].
Not thread safe. NewAutoMutation implements RelationsResolver.GetAutoMutation.(*DefaultRelationsResolver) NewSchema(schema Schema, states S) RelationsBetween returns a list of outbound relations between
fromState -> toState. Not thread safe. RelationsOf returns a list of relation types of the given state.
Not thread safe. SortStates implements RelationsResolver.SortStates. TargetStates implements RelationsResolver.TargetStates.
*DefaultRelationsResolver : RelationsResolver
ExceptionHandler provide a basic StateException state support, as should be
embedded into handler structs in most of the cases. Because ExceptionState
will be called after [Machine.HandlerDeadline], it should handle locks
on its own (to not race with itself). ExceptionState is a final entry handler for the StateException state.
Args:
- err error: The error that caused the StateException state.
- panic *ExceptionArgsPanic: Optional details about the panic.
Machine provides a state machine API with mutations, state schema, handlers,
subscriptions, tracers, and helpers methods. It also holds a queue of
mutations to execute. DisposeTimeout specifies the duration to wait for the queue to drain during
disposal. Default 1s. EvalTimeout is the time the machine will try to execute an eval func.
Like any other handler, eval func also has [HandlerTimeout]. Default: 1s. HandlerBackoff is the time after a [HandlerDeadline], during which the
machine will return [Canceled] to any mutation. HandlerDeadline is a grace period after a handler timeout, before the
machine moves on. HandlerTimeout defined the time for a handler to execute before it causes
StateException. Default: 1s. See also [Opts.HandlerTimeout].
Using HandlerTimeout can cause race conditions, unless paired with
[Event.IsValid]. LastHandlerDeadline stores when the last HandlerDeadline was hit. If true, the machine will log stack traces of errors. Default: true.
Requires an ExceptionHandler binding and [Machine.PanicToException] set. If true, the machine will catch panic and trigger the [StateException]
state. Default: true. Can be disabled via AM_DEBUG=1. Maximum number of mutations that can be queued. Default: 1000. ActiveStates returns a copy of the currently active states when states is
nil, optionally limiting the results to a subset of states. Add activates a list of states in the machine, returning the result of the
transition (Executed, Queued, Canceled).
Like every mutation method, it will resolve relations and trigger handlers. Add1 is a shorthand method to add a single state with the passed args.
See Add(). AddBreakpoint adds a breakpoint for an outcome of mutation (added and
removed states) checked by mutation equality. Once such a mutation happens,
a log message will be printed out. We can set an IDE's breakpoint on this
line and see the mutation's sync stack trace. If [Machine.LogStackTrace] is
set, the stack trace will be printed out as well. Many breakpoints can be
added, but none removed.
Breakpoints are useful to find the caller of a mutation, but don't work with
[Machine.Set].
strict: strict skips already active / inactive (for strict of diff equality).(*Machine) AddBreakpoint1(added string, removed string, strict bool) AddErr is a dedicated method to add the StateException state with the passed
error and optional arguments.
Like every mutation method, it will resolve relations and trigger handlers.
AddErr produces a stack trace of the error, if LogStackTrace is enabled. AddErrState adds a dedicated error state, along with the build in
StateException state. Like every mutation method, it will resolve relations
and trigger handlers. AddErrState produces a stack trace of the error, if
LogStackTrace is enabled. Any is a group call to Is, returns true if any of the params return true
from Is.
machine.StringAll() // ()[Foo:0 Bar:0 Baz:0]
machine.Add(S{"Foo"})
// is(Foo, Bar) or is(Bar)
machine.Any(S{"Foo", "Bar"}, S{"Bar"}) // false
// is(Foo) or is(Bar)
machine.Any(S{"Foo"}, S{"Bar"}) // true Any1 is group call to [Machine.Is1], returns true if any of the params return
true from [Machine.Is1]. Backoff is true in case the machine had a recent HandlerDeadline. During a
backoff, all mutations will be [Canceled]. BindHandlers binds a struct of handler methods to machine's states, based on
the naming convention, eg `FooState(e *Event)`. Negotiation handlers can
optionally return bool. BindTracer binds a Tracer to the machine. Tracers can cause StateException in
submachines, before any handlers are bound. Use the Err() getter to examine
such errors. CanAdd checks if [states] can be added and returns Executed or
[AT.CheckDone] if a dry run mutation passes. Useful for reducing failed
negotiations. CanAdd1 is [Machine.CanAdd] for a single state. CanRemove checks if [states] can be removed and returns Executed or
[AT.CheckDone] if a dry run mutation passes. Useful for reducing failed
negotiations. CanRemove1 is [Machine.CanRemove] for a single state. Clock returns current machine's clock, a state-keyed map of ticks. If states
are passed, only the ticks of the passed states are returned. Ctx return machine's root context. DetachHandlers detaches previously bound machine handlers. DetachTracer tries to remove a tracer from the machine. Returns an error in
case the tracer wasn't bound. Dispose disposes the machine and all its emitters. You can wait for the
completion of the disposal with `<-mach.WhenDisposed`. DisposeForce disposes the machine and all its emitters, without waiting for
the queue to drain. Will cause panics. Err returns the last error. EvAdd is like Add, but passed the source event as the 1st param, which
results in traceable transitions. EvAdd1 is like Add1 but passed the source event as the 1st param, which
results in traceable transitions. EvAddErr is like AddErr, but passed the source event as the 1st param, which
results in traceable transitions. EvAddErrState is like AddErrState, but passed the source event as the 1st
param, which results in traceable transitions. EvRemove is like Remove but passed the source event as the 1st param, which
results in traceable transitions. EvRemove1 is like Remove1, but passed the source event as the 1st param,
which results in traceable transitions. EvToggle is a traced version of [Machine.Toggle]. EvToggle1 is a traced version of [Machine.Toggle1]. Eval executes a function on the machine's queue, allowing to avoid using
locks for non-handler code. Blocking code should NOT be scheduled here.
Eval cannot be called within a handler's critical zone, as both are using
the same serial queue and will deadlock. Eval has a timeout of
HandlerTimeout/2 and will return false in case it happens. Evals do not
trigger consensus, thus are much faster than state mutations.
ctx: nil context defaults to machine's context.
Note: usage of Eval is discouraged. But if you have to, use AM_DETECT_EVAL in
tests for deadlock detection. Most usages of eval can be replaced with
atomics or returning from mutation via channels. Export exports the machine state as Serialized: ID, machine time, and
state names.(*Machine) Groups() (map[string][]int, []string) Has return true is passed states are registered in the machine. Useful for
checking if a machine implements a specific state set. Has1 is shorthand for Has. It returns true if the passed state is
registered in the machine. HasHandlers returns true if this machine has bound handlers, and thus an
allocated goroutine. It also makes it nondeterministic. Id returns the machine's id. Import imports the machine state from Serialized. It's not safe to import
into a machine which has already produces transitions and/or
has telemetry connected (use [Machine.SetSchema] instead). Index returns a list of state indexes in the machine's StateNames() list,
with -1s for missing ones. Index1 returns the index of a state in the machine's StateNames() list, or -1
when not found or machine has been disposed. Inspect returns a multi-line string representation of the machine (states,
relations, clocks).
states: param for ordered or partial results. Is checks if all the passed states are currently active.
machine.StringAll() // ()[Foo:0 Bar:0 Baz:0]
machine.Add(S{"Foo"})
machine.Is(S{"Foo"}) // true
machine.Is(S{"Foo", "Bar"}) // false Is1 is [Machine.Is] for a single state. IsClock checks if the machine has changed since the passed
clock. Returns true if at least one state has changed. IsDisposed returns true if the machine has been disposed. IsErr checks if the machine has the StateException state currently active. IsQueued checks if a particular mutation has been queued. Returns
an index (idx, true), or (0, false), if not found.
mutType: add, remove, set
states: list of states used in the mutation
withoutArgsOnly: matches only mutation without the arguments object
statesStrictEqual: states of the mutation have to be exactly like `states`
and not a superset.
minQueueTick: minimal queue tick assigned to the matched mutation
isCheck: the mutation has to be a [Mutation.IsCheck]
position: position in the queue, after applying the [startIndex] IsQueuedAbove ... N times. This method allows for rate-limiting of
mutations for specific states and a threshold. IsTime checks if the machine has changed since the passed
time (list of ticks). Returns true if at least one state has changed. The
states param is optional and can be used to check only a subset of states. Log logs an [extern] message unless LogNothing is set.
Optionally redirects to a custom logger from SemLogger().SetLogger. MachineTick is the number of times the machine has been started. Each start
means an empty queue. Only set by [Machine.Import]. MustBindHandlers is a panicking version of BindHandlers, useful in tests. NewStateCtx returns a new sub-context, bound to the current clock's tick of
the passed state.
Context cancels when the state has been deactivated, or right away,
if it isn't currently active.
State contexts are used to check state expirations and should be checked
often inside goroutines. Not checks if **none** of the passed states are currently active.
machine.StringAll()
// -> ()[A:0 B:0 C:0 D:0]
machine.Add(S{"A", "B"})
// not(A) and not(C)
machine.Not(S{"A", "C"})
// -> false
// not(C) and not(D)
machine.Not(S{"C", "D"})
// -> true Not1 is [Machine.Not] for a single state. OnChange is the most basic state-change handler, useful for machines without
any handlers. OnDispose adds a function to be called after the machine gets disposed.
These functions will run synchronously just before WhenDisposed() channel
gets closed. Considering it's a low-level feature, it's advised to handle
disposal via dedicated states. OnError is the most basic error handler, useful for machines without any
handlers. PanicToErr will catch a panic and add the StateException state. Needs to
be called in a defer statement, just like a recover() call. PanicToErrState will catch a panic and add the StateException state, along
with the passed state. Needs to be called in a defer statement, just like a
recover() call. ParentId returns the ID of the parent machine (if any). ParseStates parses a list of states, removing unknown ones and duplicates.
Use [Machine.Has] and [Machine.Has1] to check if a state is defined for the
machine. PrependMut prepends the mutation to the front of the queue. This is a special
cases only method and should be used with caution, as it can create an
infinite loop. It's useful for postponing mutations inside a negotiation
handler. The returned Result can't be waited on, as prepended mutations don't
create a queue tick. Queue returns a copy of the currently active states.(*Machine) QueueLen() uint16 QueueTick is the number of times the queue has processed a mutation. Starts
from [1], for easy comparison with [Result]. Remove deactivates a list of states in the machine, returning the result of
the transition (Executed, Queued, Canceled).
Like every mutation method, it will resolve relations and trigger handlers. Remove1 is [Machine.Remove1] for a single state. Resolver returns the relation resolver, used to produce target states of
transitions. Schema returns a copy of machine's schema. SchemaVer return the current version of the schema. SemLogger returns the semantic logger of the machine Set deactivates a list of states in the machine, returning the result of
the transition (Executed, Canceled, Queued).
Like every mutation method, it will resolve relations and trigger handlers. SetGroups organizes the schema into a tree using schema-v2 structs. SetGroupsString is like SetGroups, but work with the schema-v1 format. SetSchema sets the machine's schema. It will automatically call
VerifyStates with the names param and handle EventSchemaChange if successful.
The new schema has to be longer than the previous one (no relations-only
changes). The length of the schema is also the version of the schema. SetTags updates the machine's tags with the provided slice of strings. StateNames returns a SHARED copy of all the state names. TODO docs StatesVerified returns true if the state names have been ordered
using VerifyStates. String returns a one line representation of the currently active states,
with their clock values. Inactive states are omitted.
Eg: (Foo:1 Bar:3) StringAll returns a one line representation of all the states, with their
clock values. Inactive states are in square brackets.
(Foo:1 Bar:3) [Baz:2] Switch returns the first state from the passed list that is currently active,
making it handy for switch statements. Useful for state groups.
switch mach.Switch(ss.GroupPlaying) {
case "Playing":
case "Paused":
case "Stopped":
} Tags returns machine's tags, a list of unstructured strings without spaces. Tick return the current tick for a given state. Time returns machine's time, a list of ticks per state. Returned value
includes the specified states, or all the states if nil. Toggle deactivates a list of states in case all are active, or activates
them otherwise. Returns the result of the transition (Executed, Queued,
Canceled). Toggle1 activates or deactivates a single state, depending on its current
state. Returns the result of the transition (Executed, Queued, Canceled). Tracers return a copy of currenty attached tracers. Transition returns the current transition, if any. VerifyStates verifies an array of state names and returns an error in case
at least one isn't defined. It also retains the order and uses it for
StateNames. Verification can be checked via Machine.StatesVerified. WasClock checks if the passed time has happened (or happening right now).
Returns false if at least one state is too early. WasTime checks if the passed time has happened (or happening right now).
Returns false if at least one state is too early. The
states param is optional and can be used to check only a subset of states. When returns a channel that will be closed when all the passed states
become active or the machine gets disposed.
ctx: optional context that will close the channel early. When1 is an alias to When() for a single state.
See When. WhenArgs returns a channel that will be closed when the passed state
becomes active with all the passed args. Args are compared using the native
'=='. It's meant to be used with async Multi states, to filter out
a specific call.
ctx: optional context that will close the channel when handler loop ends. WhenDisposed returns a channel that will be closed when the machine is
disposed. Requires bound handlers. Use Machine.disposed in case no handlers
have been bound. WhenErr returns a channel that will be closed when the machine is in the
StateException state.
ctx: optional context that will close the channel early. WhenNot returns a channel that will be closed when all the passed states
become inactive or the machine gets disposed.
ctx: optional context that will close the channel early. WhenNot1 is an alias to WhenNot() for a single state.
See WhenNot. WhenQuery returns a channel that will be closed when the passed [clockCheck]
function returns true. [clockCheck] should be a pure function and
non-blocking.`
ctx: optional context that will close the channel early. WhenQueue waits until the passed queueTick gets processed.
TODO example WhenQueueEnds closes every time the queue ends, or the optional ctx expires.
ctx: optional context that will close the channel early. WhenTicks waits N ticks of a single state (relative to now). Uses WhenTime
underneath.
ctx: optional context that will close the channel early. WhenTime returns a channel that will be closed when all the passed states
have passed the specified time. The time is a logical clock of the state.
Machine time can be sourced from [Machine.Time](), or [Machine.Clock]().
ctx: optional context that will close the channel early. WhenTime1 waits till ticks for a single state equal the given value (or
more).
ctx: optional context that will close the channel early. WillBe returns true if the passed states are scheduled to be activated.
Does not cover implied states, only called ones.
See [Machine.IsQueued] to perform more detailed queries.
position: optional position assertion WillBe1 returns true if the passed state is scheduled to be activated.
See IsQueued to perform more detailed queries. WillBeRemoved returns true if the passed states are scheduled to be
deactivated. Does not cover implied states, only called ones. See
[Machine.IsQueued] to perform more detailed queries.
position: optional position assertion WillBeRemoved1 returns true if the passed state is scheduled to be
deactivated. See IsQueued to perform more detailed queries.
*Machine : Api
*Machine : expvar.Var
*Machine : fmt.Stringer
func New(ctx context.Context, schema Schema, opts *Opts) *Machine
func NewCommon(ctx context.Context, id string, stateSchema Schema, stateNames S, handlers any, parent Api, opts *Opts) (*Machine, error)
func (*Event).Machine() *Machine
func github.com/pancsta/asyncmachine-go/pkg/helpers.NewMirror(id string, flat bool, source *Machine, handlers any, states S) (*Machine, error)
func github.com/pancsta/asyncmachine-go/examples/mach_template.NewTemplate(ctx context.Context, num int) (*Machine, error)
func github.com/pancsta/asyncmachine-go/examples/temporal_fileprocessing.FileProcessingFlow(ctx context.Context, log temporal_fileprocessing.Logger, filename string) (*Machine, error)
func github.com/pancsta/asyncmachine-go/examples/tui/states.NewTui(ctx context.Context) *Machine
func github.com/pancsta/asyncmachine-go/internal/testing.NewRpcTest(t *testing.T, ctx context.Context, netSrc *Machine, consumer *Machine) (*Machine, *rpc.Server, *rpc.Client)
func github.com/pancsta/asyncmachine-go/internal/testing/states.NewRel(ctx context.Context) *Machine
func github.com/pancsta/asyncmachine-go/internal/testing/utils.NewCustom(t *testing.T, states Schema) *Machine
func github.com/pancsta/asyncmachine-go/internal/testing/utils.NewCustomNetSrc(t *testing.T, states Schema) *Machine
func github.com/pancsta/asyncmachine-go/internal/testing/utils.NewNoRels(t *testing.T, initialState S, suffix string) *Machine
func github.com/pancsta/asyncmachine-go/internal/testing/utils.NewNoRelsNetSrc(t *testing.T, initialState S) *Machine
func github.com/pancsta/asyncmachine-go/internal/testing/utils.NewNoRelsNetSrcSchema(t *testing.T, initialState S, overlay Schema) *Machine
func github.com/pancsta/asyncmachine-go/internal/testing/utils.NewRels(t *testing.T, initialState S) *Machine
func github.com/pancsta/asyncmachine-go/internal/testing/utils.NewRelsNetSrc(t *testing.T, initialState S) *Machine
func github.com/pancsta/asyncmachine-go/internal/testing/utils.NewRelsNodeWorker(t *testing.T, initialState S) *Machine
func MockClock(mach *Machine, clock Clock)
func NewEvent(mach *Machine, machApi Api) *Event
func github.com/pancsta/asyncmachine-go/pkg/graph.New(server *Machine) (*graph.Graph, error)
func github.com/pancsta/asyncmachine-go/pkg/helpers.CopySchema(source Schema, target *Machine, states S) error
func github.com/pancsta/asyncmachine-go/pkg/helpers.EvalGetter[T](ctx context.Context, source string, maxTries int, mach *Machine, eval func() (T, error)) (T, error)
func github.com/pancsta/asyncmachine-go/pkg/helpers.NewMirror(id string, flat bool, source *Machine, handlers any, states S) (*Machine, error)
func github.com/pancsta/asyncmachine-go/pkg/helpers.NewStateLoop(mach *Machine, loopState string, optCheck func() bool) *helpers.StateLoop
func github.com/pancsta/asyncmachine-go/pkg/helpers.WaitForErrAny(ctx context.Context, timeout time.Duration, mach *Machine, chans ...<-chan struct{}) error
func github.com/pancsta/asyncmachine-go/pkg/node.AddErrPool(mach *Machine, err error, args A) error
func github.com/pancsta/asyncmachine-go/pkg/node.AddErrPoolStr(mach *Machine, msg string, args A) error
func github.com/pancsta/asyncmachine-go/pkg/node.AddErrRpc(mach *Machine, err error, args A) error
func github.com/pancsta/asyncmachine-go/pkg/node.AddErrWorker(event *Event, mach *Machine, err error, args A) error
func github.com/pancsta/asyncmachine-go/pkg/node.AddErrWorkerStr(mach *Machine, msg string, args A) error
func github.com/pancsta/asyncmachine-go/pkg/pubsub.AddErrJoining(event *Event, mach *Machine, err error, args A) error
func github.com/pancsta/asyncmachine-go/pkg/pubsub.AddErrListening(event *Event, mach *Machine, err error, args A) error
func github.com/pancsta/asyncmachine-go/pkg/pubsub.NewTopic(ctx context.Context, name, suffix string, exposedMachs []*Machine, opts *pubsub.TopicOpts) (*pubsub.Topic, error)
func github.com/pancsta/asyncmachine-go/pkg/rpc.AddErr(e *Event, mach *Machine, msg string, err error)
func github.com/pancsta/asyncmachine-go/pkg/rpc.AddErrNetwork(e *Event, mach *Machine, err error)
func github.com/pancsta/asyncmachine-go/pkg/rpc.AddErrNoConn(e *Event, mach *Machine, err error)
func github.com/pancsta/asyncmachine-go/pkg/rpc.AddErrParams(e *Event, mach *Machine, err error)
func github.com/pancsta/asyncmachine-go/pkg/rpc.AddErrResp(e *Event, mach *Machine, err error)
func github.com/pancsta/asyncmachine-go/pkg/rpc.AddErrRpcStr(e *Event, mach *Machine, msg string)
func github.com/pancsta/asyncmachine-go/pkg/rpc.BindServer(source, target *Machine, rpcReady, clientConn string) error
func github.com/pancsta/asyncmachine-go/pkg/rpc.BindServerMulti(source, target *Machine, rpcReady, clientConn, clientDisconn string) error
func github.com/pancsta/asyncmachine-go/pkg/rpc.BindServerRpcReady(source, target *Machine, rpcReady string) error
func github.com/pancsta/asyncmachine-go/pkg/rpc.NewNetworkMachine(ctx context.Context, id string, conn rpc.NetMachConn, schema Schema, stateNames S, parent *Machine, tags []string, filterMutations bool) (*rpc.NetworkMachine, *rpc.NetMachInternal, error)
func github.com/pancsta/asyncmachine-go/pkg/states.AddErrConnecting(event *Event, mach *Machine, err error, args A) error
func github.com/pancsta/asyncmachine-go/pkg/x/helpers.FanOutIn(mach *Machine, name string, total, concurrency int, fn helpers.FanFn) (any, error)
func github.com/pancsta/asyncmachine-go/pkg/x/helpers.RelationsMatrix(mach *Machine) ([][]int, error)
func github.com/pancsta/asyncmachine-go/pkg/x/helpers.TimeMatrix(machines []*Machine) ([]Time, error)
func github.com/pancsta/asyncmachine-go/pkg/x/history/frostdb.(*Memory).Track(onErr func(err error), mach *Machine, calledAllowlist, changedAllowlist S, maxEntries int) (*frostdb.Tracer, error)
func github.com/pancsta/asyncmachine-go/examples/mach_template.AddErrExample(event *Event, mach *Machine, err error, args A) error
func github.com/pancsta/asyncmachine-go/internal/testing.NewRpcClient(t *testing.T, ctx context.Context, addr string, netSrcSchema Schema, consumer *Machine) *rpc.Client
func github.com/pancsta/asyncmachine-go/internal/testing.NewRpcTest(t *testing.T, ctx context.Context, netSrc *Machine, consumer *Machine) (*Machine, *rpc.Server, *rpc.Client)
func github.com/pancsta/asyncmachine-go/internal/testing.NewRpcTest(t *testing.T, ctx context.Context, netSrc *Machine, consumer *Machine) (*Machine, *rpc.Server, *rpc.Client)
func github.com/pancsta/asyncmachine-go/tools/debugger/server.StartRpc(mach *Machine, addr string, mux chan<- cmux.CMux, fwdAdds []string, enableHttp bool)
func github.com/pancsta/asyncmachine-go/tools/generator.MachDashboardEnv(mach *Machine) error
func github.com/pancsta/asyncmachine-go/tools/repl.AddErrSyntax(event *Event, mach *Machine, err error, args A) error
Mutation represents an atomic change (or an attempt) of machine's active
states. Mutation causes a Transition. argument map passed to the mutation method (if any). States explicitly passed to the mutation method, as their indexes. Use
Transition.CalledStates or IndexToStates to get the actual state names. this mutation has been triggered by an auto state
TODO rename to IsAuto IsCheck indicates that this mutation is a check, see [Machine.CanAdd]. QueueLen is the length of the queue at the time when the mutation was
queued. QueueTick is the assigned queue tick at the time when the mutation was
queued. 0 for prepended mutations. QueueTickNow is the queue tick during which this mutation was scheduled. QueueToken is a unique ID, which is given to prepended mutations.
Tokens are assigned in a series but executed in random order. QueueTokensLen is the amount of unexecuted queue tokens (priority queue).
TODO impl Source is the source event for this mutation. add, set, remove(*Mutation) CalledIndex(index S) *TimeIndex(*Mutation) IsCalled(idx int) bool LogArgs returns a text snippet with arguments which should be logged for this
Mutation. MapArgs returns arguments of this Mutation which match the passed [mapper].
The returned map is never nil.(*Mutation) String() string(*Mutation) StringFromIndex(index S) string
*Mutation : expvar.Var
*Mutation : fmt.Stringer
func (*DefaultRelationsResolver).NewAutoMutation() (*Mutation, S)
func (*Event).Mutation() *Mutation
func (*Machine).Queue() []*Mutation
func RelationsResolver.NewAutoMutation() (*Mutation, S)
func (*Machine).PrependMut(mut *Mutation) Result
func Tracer.MutationQueued(machine Api, mutation *Mutation)
func (*TracerNoOp).MutationQueued(machine Api, mutation *Mutation)
func github.com/pancsta/asyncmachine-go/pkg/telemetry.(*DbgTracer).MutationQueued(mach Api, mut *Mutation)
Opts struct is used to configure a new [Machine]. DetectEval will detect Eval calls directly in handlers, which causes a
deadlock. It works in similar way as -race flag in Go and can also be
triggered by setting either env var: AM_DEBUG=1 or AM_DETECT_EVAL=1.
Default: false. If true, the machine will NOT prefix its logs with its ID. If true, the machine will NOT print all exceptions to stdout. If true, the machine will die on panics.HandlerBackofftime.Duration TODO docs Time for a handler to execute. Default: time.Second Unique ID of this machine. Default: random ID. LogArgs matching function for the machine. Default: nil. Log level of the machine. Default: [LogNothing]. Parent machine, used to inherit certain properties, e.g. tracers.
Overrides ParentID. Default: nil. ParentID is the ID of the parent machine. Default: "". QueueLimit is the maximum number of mutations that can be queued.
Default: 1000. Custom relations resolver. Default: *[DefaultRelationsResolver]. Tags is a list of tags for the machine. Default: nil. Tracer for the machine. Default: nil.
func OptsWithDebug(opts *Opts) *Opts
func OptsWithTracers(opts *Opts, tracers ...Tracer) *Opts
func New(ctx context.Context, schema Schema, opts *Opts) *Machine
func NewCommon(ctx context.Context, id string, stateSchema Schema, stateNames S, handlers any, parent Api, opts *Opts) (*Machine, error)
func OptsWithDebug(opts *Opts) *Opts
func OptsWithTracers(opts *Opts, tracers ...Tracer) *Opts
RelationsResolver is an interface for parsing relations between states.
Not thread-safe.
TODO support custom relation types and additional state properties.
TODO refac Relations( RelationsResolver) InboundRelationsOf(toState string) (S, error) NewAutoMutation returns an (optional) auto mutation which is appended to
the queue after the transition is executed. It also returns the names of
the called states. NewSchema runs when Machine receives a new struct. RelationsBetween returns a list of relation types between the given
states. RelationsOf returns a list of relation types of the given state. SortStates sorts the states in the order their handlers should be
executed. TargetStates returns the target states after parsing the relations.
*DefaultRelationsResolver
func (*Machine).Resolver() RelationsResolver
SemLogger is a semantic logger for structured events. It's consist of:
- enable / enabled methods
- text logger utils
- setters for external semantics (eg pipes)
It's WIP, and eventually it will replace (but not remove) the text logger. AddPipeIn informs that [targetState] has been piped into this machine from
[sourceMach]. The name of the source state is unknown. AddPipeOut informs that [sourceState] has been piped out into [targetMach].
The name of the target state is unknown. ArgsMapper returns the current log args mapper function. EnableArgs enables or disables the logging known args. EnableCan enables / disables logging of Can* methods. EnableGraph enables / disables logging of graph structures. EnableId enables or disables the logging of the machine's ID in log
messages. EnableQueued enables or disables the logging of queued mutations. EnableStateCtx enables or disables the logging of active state contexts. EnableSteps enables / disables logging of transition steps. EnableWhen enables or disables the logging of "when" methods. IsArgs returns true when the machine is logging known args. IsCan return true when the machine is logging Can* methods. IsGraph returns true when the machine is logging graph structures. IsId returns true when the machine is logging the machine's ID in log
messages. IsQueued returns true when the machine is logging queued mutations. IsStateCtx returns true when the machine is logging active state contexts. IsSteps return true when the machine is logging transition steps. IsWhen returns true when the machine is logging "when" methods. Level returns the log level of the machine. Logger returns the current custom logger function or nil. RemovePipes removes all pipes for the passed machine ID. SetArgsMapper accepts a function which decides which mutation arguments
to log. See NewArgsMapper or create your own manually. SetEmpty creates an empty logger that does nothing and sets the log
level in one call. Useful when combined with am-dbg. Requires LogChanges
log level to produce any output. SetLevel sets the log level of the machine. SetLogger sets a custom logger function. SetSimple takes log.Printf and sets the log level in one
call. Useful for testing. Requires LogChanges log level to produce any
output.
func Api.SemLogger() SemLogger
func (*Machine).SemLogger() SemLogger
func github.com/pancsta/asyncmachine-go/pkg/rpc.(*NetworkMachine).SemLogger() SemLogger
Serialized is a machine state serialized to a JSON/YAML/TOML compatible
struct. One also needs the state Struct to re-create a state machine. ID is the ID of a state machine.
TODO refac to Id with the new dbg telemetry protocol MachineTick is a value of [Machine.MachineTick].
nolint:lll QueueTick is a value of [Machine.QueueTick]. StateNames is an ordered list of state names. Time is the [Machine.Time] value.
func Api.Export() (*Serialized, Schema, error)
func (*Machine).Export() (*Serialized, Schema, error)
func github.com/pancsta/asyncmachine-go/pkg/rpc.(*NetworkMachine).Export() (*Serialized, Schema, error)
func (*Machine).Import(data *Serialized) error
State defines a single state of a machine, its properties and relations.AddSAfterSAutoboolMultiboolRemoveSRequireSTags[]string
func StateAdd(source State, overlay State) State
func StateSet(source State, auto, multi bool, overlay State) State
func StateAdd(source State, overlay State) State
func StateAdd(source State, overlay State) State
func StateSet(source State, auto, multi bool, overlay State) State
func StateSet(source State, auto, multi bool, overlay State) State
func github.com/pancsta/asyncmachine-go/pkg/helpers.CountRelations(state *State) int
TODO optimize with indexes
Names returns the state names of the state machine.( States) SetNames(S)( States) SetStateGroups(map[string][]int, []string) TODO
*StatesBase
github.com/pancsta/asyncmachine-go/pkg/node/states.BootstrapStatesDef
github.com/pancsta/asyncmachine-go/pkg/node/states.ClientStatesDef
github.com/pancsta/asyncmachine-go/pkg/node/states.SupervisorStatesDef
github.com/pancsta/asyncmachine-go/pkg/node/states.WorkerStatesDef
github.com/pancsta/asyncmachine-go/pkg/pubsub/states.TopicStatesDef
github.com/pancsta/asyncmachine-go/pkg/rpc/states.ClientStatesDef
github.com/pancsta/asyncmachine-go/pkg/rpc/states.ConsumerStatesDef
github.com/pancsta/asyncmachine-go/pkg/rpc/states.MuxStatesDef
github.com/pancsta/asyncmachine-go/pkg/rpc/states.NetSourceStatesDef
github.com/pancsta/asyncmachine-go/pkg/rpc/states.ServerStatesDef
github.com/pancsta/asyncmachine-go/pkg/rpc/states.SharedStatesDef
github.com/pancsta/asyncmachine-go/pkg/states.BasicStatesDef
github.com/pancsta/asyncmachine-go/pkg/states.ConnectedStatesDef
github.com/pancsta/asyncmachine-go/pkg/states.ConnPoolStatesDef
github.com/pancsta/asyncmachine-go/pkg/states.DisposedStatesDef
github.com/pancsta/asyncmachine-go/pkg/x/history/frostdb.BasicStatesDef
github.com/pancsta/asyncmachine-go/examples/arpc/states.ExampleStatesDef
github.com/pancsta/asyncmachine-go/examples/benchmark_grpc/states.WorkerStatesDef
github.com/pancsta/asyncmachine-go/examples/cli/states.CliStatesDef
github.com/pancsta/asyncmachine-go/examples/cli_daemon/states.DaemonStatesDef
github.com/pancsta/asyncmachine-go/examples/mach_template/states.MachTemplateStatesDef
github.com/pancsta/asyncmachine-go/examples/nfa/states.NfaStatesDef
github.com/pancsta/asyncmachine-go/examples/repl/states.ExampleStatesDef
github.com/pancsta/asyncmachine-go/examples/tree_state_source/states.FlightsStatesDef
github.com/pancsta/asyncmachine-go/examples/tui/states.TuiStatesDef
github.com/pancsta/asyncmachine-go/tools/debugger/states.ServerStatesDef
github.com/pancsta/asyncmachine-go/tools/generator/states.GeneratorStatesDef
github.com/pancsta/asyncmachine-go/tools/relay/states.RelayStatesDef
github.com/pancsta/asyncmachine-go/tools/repl/states.ReplStatesDef
github.com/pancsta/asyncmachine-go/tools/visualizer/states.VisualizerStatesDef
func (*Machine).SetGroups(groups any, optStates States)
Step struct represents a single step within a Transition, either a relation
resolving step or a handler call. Deprecated, use RelType. TODO remove Deprecated, use GetFromState(). TODO remove TODO implement marks an enter handler (FooState, but not FooEnd). Requires IsFinal. marks a final handler (FooState, FooEnd) marks a self handler (FooFoo) Only for Type == StepRelation. Deprecated, use GetToState(). TODO remove TODO implementTypeStepType GetFromState returns the source state of a step. Optional, unless no
GetToState(). GetToState returns the target state of a step. Optional, unless no
GetFromState().(*Step) StringFromIndex(idx S) string
Subscriptions is an embed responsible for binding subscriptions,
managing their indexes, processing triggers, and garbage collection. Mx locks the subscription manager. TODO optimize?(*Subscriptions) HasWhenArgs() bool NewStateCtx returns a new sub-context, bound to the current clock's tick of
the passed state.
Context cancels when the state has been deactivated, or right away,
if it isn't currently active.
State contexts are used to check state expirations and should be checked
often inside goroutines. ProcessStateCtx collects all deactivated state contexts, and returns theirs
cancel funcs. Uses transition caches. ProcessWhen collects all the matched active state subscriptions, and
returns theirs channels. ProcessWhenArgs collects all the args-matching subscriptions, and
returns theirs channels.(*Subscriptions) ProcessWhenQuery() []chan struct{}(*Subscriptions) ProcessWhenQueue(queueTick uint64) []chan struct{} ProcessWhenQueueEnds collects all queue-end subscriptions, and
returns theirs channels. ProcessWhenTime collects all the time-based subscriptions, and
returns theirs channels. QueueFlush means a new queue, and all the queue-related subs are expired and
have to be closed. SetClock sets a longer clock from an expanded schema.(*Subscriptions) When(states S, ctx context.Context) <-chan struct{} WhenArgs returns a channel that will be closed when the passed state
becomes active with all the passed args. Args are compared using the native
'=='. It's meant to be used with async Multi states, to filter out
a specific call.
ctx: optional context that will close the channel when handler loop ends. WhenNot returns a channel that will be closed when all the passed states
become inactive or the machine gets disposed.
ctx: optional context that will close the channel early.(*Subscriptions) WhenQuery(fn func(clock Clock) bool, ctx context.Context) <-chan struct{} WhenQueue waits until the passed queueTick gets processed. WhenQueueEnds closes every time the queue ends, or the optional ctx expires.
This function assumes the queue is running, and wont close early.
ctx: optional context that will close the channel early. WhenTime returns a channel that will be closed when all the passed states
have passed the specified time. The time is a logical clock of the state.
Machine time can be sourced from [Machine.Time](), or [Machine.Clock]().
ctx: optional context that will close the channel early.
func NewSubscriptionManager(mach Api, clock Clock, is, not InternalCheckFunc, log InternalLogFunc) *Subscriptions
Time is machine time, an ordered list of state ticks. It's like Clock, but
indexed by int, instead of string.
TODO use math/big? ActiveStates returns a list of active state indexes in this machine time
slice. When idxs isn't nil, only the passed indexes are considered. Add sums 2 instances of Time and returns a new one. After returns true if at least 1 tick in time1 is after time2, optionally
accepting equal values for true. Requires a deterministic states
order, eg by using [Machine.VerifyStates]. Any is [Machine.Any] but for an int-based time slice. Any1 is [Machine.Any1] but for an int-based time slice. Before returns true if at least 1 tick in time1 is before time2, optionally
accepting equal values for true. Requires a deterministic states
order, eg by using [Machine.VerifyStates]. DiffSince returns the number of ticks for each state in Time since the
passed machine time. Equal checks if time1 is equal to time2. Requires a deterministic states
order, eg by using [Machine.VerifyStates]. Filter returns a subset of the Time slice for the given state indexes.
It's not advised to slice an already sliced time slice. Increment adds 1 to a state's tick value Is is [Machine.Is] but for an int-based time slice. Is1 is [Machine.Is1] but for an int-based time slice. NonZeroStates returns a list of state indexes with non-zero ticks in this
machine time slice. Not is [Machine.Not] but for an int-based time slice. Not1 is [Machine.Not1] but for an int-based time slice. String returns an integer representation of the time slice. Sum returns a sum of ticks for each state in Time, or narrowed down to
[idxs]. Tick is [Machine.Tick] but for an int-based time slice. ToIndex returns a string-indexed version of Time.
Time : expvar.Var
Time : fmt.Stringer
func IndexToTime(index S, active []int) Time
func NewTime(index Time, activeStates []int) Time
func Api.Time(states S) Time
func (*Machine).Time(states S) Time
func Time.Add(t2 Time) Time
func Time.DiffSince(before Time) Time
func Time.Filter(idxs []int) Time
func Time.Increment(idx int) Time
func github.com/pancsta/asyncmachine-go/pkg/rpc.(*Client).Sync() Time
func github.com/pancsta/asyncmachine-go/pkg/rpc.(*NetworkMachine).Time(states S) Time
func github.com/pancsta/asyncmachine-go/pkg/x/helpers.TimeMatrix(machines []*Machine) ([]Time, error)
func NewTime(index Time, activeStates []int) Time
func Api.IsTime(time Time, states S) bool
func Api.WasTime(time Time, states S) bool
func Api.WhenTime(states S, times Time, ctx context.Context) <-chan struct{}
func (*Machine).IsTime(t Time, states S) bool
func (*Machine).WasTime(t Time, states S) bool
func (*Machine).WhenTime(states S, times Time, ctx context.Context) <-chan struct{}
func (*Subscriptions).WhenTime(states S, times Time, ctx context.Context) <-chan struct{}
func Time.Add(t2 Time) Time
func Time.After(orEqual bool, time2 Time) bool
func Time.Before(orEqual bool, time2 Time) bool
func Time.DiffSince(before Time) Time
func Time.Equal(strict bool, time2 Time) bool
func github.com/pancsta/asyncmachine-go/pkg/rpc.(*NetMachInternal).UpdateClock(now Time, qTick uint64, machTick uint32)
func github.com/pancsta/asyncmachine-go/pkg/rpc.(*NetworkMachine).IsTime(t Time, states S) bool
func github.com/pancsta/asyncmachine-go/pkg/rpc.(*NetworkMachine).WasTime(t Time, states S) bool
func github.com/pancsta/asyncmachine-go/pkg/rpc.(*NetworkMachine).WhenTime(states S, times Time, ctx context.Context) <-chan struct{}
TimeIndex is [Time] with a bound state index (list of state names). It's not
suitable for storage, use [Time] instead. See [Clock] for a simpler type with
ticks indexes by state names.IndexSTimeTime ActiveStates is [Machine.ActiveStates] but for a string-based time slice. Add sums 2 instances of Time and returns a new one. After returns true if at least 1 tick in time1 is after time2, optionally
accepting equal values for true. Requires a deterministic states
order, eg by using [Machine.VerifyStates]. Any is [Machine.Any] but for a string-based time slice. Any1 is [Machine.Any1] but for a string-based time slice. Before returns true if at least 1 tick in time1 is before time2, optionally
accepting equal values for true. Requires a deterministic states
order, eg by using [Machine.VerifyStates]. DiffSince returns the number of ticks for each state in Time since the
passed machine time. Equal checks if time1 is equal to time2. Requires a deterministic states
order, eg by using [Machine.VerifyStates]. Filter is [Time.Filter] but for a string-based time slice. Increment adds 1 to a state's tick value Is is [Machine.Is] but for a string-based time slice. Is1 is [Machine.Is1] but for a string-based time slice. NonZeroStates is [Time.NonZeroStates] but for a string-based time slice. Not is [Machine.Not] but for a string-based time slice. Not1 is [Machine.Not1] but for a string-based time slice. StateName returns the name of the state at the given index. String returns a string representation of the time slice. Sum is [Time.Sum] but for a string-based time slice. Tick is [Machine.Tick] but for an int-based time slice. ToIndex returns a string-indexed version of Time.
TimeIndex : expvar.Var
TimeIndex : fmt.Stringer
func NewTimeIndex(index S, activeStates []int) *TimeIndex
func (*Mutation).CalledIndex(index S) *TimeIndex
func Time.ToIndex(index S) *TimeIndex
func TimeIndex.Filter(states S) *TimeIndex
func (*Transition).TimeIndexAfter() TimeIndex
Transition represents processing of a single mutation within a machine. Enters is a list of states activated in this transition. Enters is a list of states deactivated in this transition. Id is a unique identifier of the transition. InternalLogEntriesLock is used to lock the logs to be collected by Tracers.
TODO getter? IsAccepted returns true if the transition has been accepted, which can
change during the transition's negotiation phase and while resolving
relations. TODO true for panic and timeouts IsCompleted returns true when the execution of the transition has been
fully completed. TODO confirms relations resolved and negotiation ended LogEntries are log msgs produced during the transition. MachApi is a subset of Machine.
TODO call when applicable instead of calling Machine
TODO rename to MachApi Machine is the parent machine of this transition. Mutation call which caused this transition PreLogEntries are log msgs produced before during the transition. QueueLen is the length of the queue after the transition. Steps is a list of steps taken by this transition (so far). TargetIndexes is a list of indexes of the target states. TimeAfter is the machine time from after the transition. If the transition
has been canceled, this will be the same as TimeBefore. This field is the
same as TimeBefore, until the negotiation phase finishes. HasStateChanged is true if the transition has changed the state of the
machine. TODO useful?
HasStateChanged bool
TimeBefore is the machine time from before the transition. Args returns the argument map passed to the mutation method
(or an empty one). CalledStates return explicitly called / requested states of the transition.(*Transition) CleanCache() ClockAfter return the Clock from before the transition. ClockBefore return the Clock from before the transition. IsAuto returns true if the transition was triggered by an auto state.
Thus, it cant trigger any other auto state mutations. IsHealth returns true if the transition was health-related (StateHealthcheck,
StateHeartbeat). StatesBefore is a list of states before the transition. String representation of the transition and the steps taken so far. TargetStates is a list of states after parsing the relations. TimeIndexAfter return TimeAfter bound to an index, for easy quering. Type returns the type of the mutation (add, remove, set).
*Transition : expvar.Var
*Transition : fmt.Stringer
func Api.Transition() *Transition
func (*Event).Transition() *Transition
func (*LastTxTracer).Load() *Transition
func (*Machine).Transition() *Transition
func github.com/pancsta/asyncmachine-go/pkg/rpc.(*NetworkMachine).Transition() *Transition
func (*DefaultRelationsResolver).TargetStates(t *Transition, statesToSet, index S) S
func (*LastTxTracer).TransitionEnd(transition *Transition)
func RelationsResolver.TargetStates(t *Transition, calledStates, index S) S
func Tracer.HandlerEnd(transition *Transition, emitter string, handler string)
func Tracer.HandlerStart(transition *Transition, emitter string, handler string)
func Tracer.TransitionEnd(transition *Transition)
func Tracer.TransitionInit(transition *Transition)
func Tracer.TransitionStart(transition *Transition)
func (*TracerNoOp).HandlerEnd(transition *Transition, emitter string, handler string)
func (*TracerNoOp).HandlerStart(transition *Transition, emitter string, handler string)
func (*TracerNoOp).TransitionEnd(transition *Transition)
func (*TracerNoOp).TransitionInit(transition *Transition)
func (*TracerNoOp).TransitionStart(transition *Transition)
func github.com/pancsta/asyncmachine-go/pkg/helpers.GetTransitionStates(tx *Transition, index S) (added S, removed S, touched S)
func github.com/pancsta/asyncmachine-go/pkg/pubsub.(*Tracer).TransitionEnd(transition *Transition)
func github.com/pancsta/asyncmachine-go/pkg/telemetry.(*DbgTracer).TransitionEnd(tx *Transition)
func github.com/pancsta/asyncmachine-go/pkg/telemetry.(*OtelMachTracer).HandlerEnd(tx *Transition, emitter string, handler string)
func github.com/pancsta/asyncmachine-go/pkg/telemetry.(*OtelMachTracer).TransitionEnd(tx *Transition)
func github.com/pancsta/asyncmachine-go/pkg/telemetry.(*OtelMachTracer).TransitionInit(tx *Transition)
func github.com/pancsta/asyncmachine-go/pkg/telemetry/prometheus.(*PromTracer).TransitionEnd(tx *Transition)
func github.com/pancsta/asyncmachine-go/pkg/telemetry/prometheus.(*PromTracer).TransitionInit(tx *Transition)
func github.com/pancsta/asyncmachine-go/pkg/x/helpers.TransitionMatrix(tx, prevTx *Transition, index S) ([][]int, error)
func github.com/pancsta/asyncmachine-go/pkg/x/history/frostdb.(*Tracer).TransitionEnd(tx *Transition)
func github.com/pancsta/asyncmachine-go/examples/mach_template.(*Tracer).TransitionEnd(transition *Transition)
func github.com/pancsta/asyncmachine-go/examples/relations_playground.(*Tracer).TransitionEnd(tx *Transition)
Chchan struct{}CompletedStateIsActiveCtxcontext.Context map of matched to their index positions
TODO optimize indexes number of matches so far TODO len(Index) ? optional Time to match for completed from Index number of total matches needed // TODO len(Times) ?
Package-Level Functions (total 36)
Type Parameters:
K: comparable
V: any AMerge merges 2 or more maps into 1. Useful for passing args from many
packages.
CloneSchema deep clones the states struct and returns a copy.
EnvLogLevel returns a log level from an environment variable, AM_LOG by
default.
IndexToStates decodes state indexes based on the provided index.
IndexToTime returns "virtual time" with selected states active. It's useful
to use time methods on a list of states, eg the called ones.
IsActiveTick returns true if the tick represents an active state
(odd number).
IsHandler checks if a method name is a handler method, by returning a state
name.
IsQueued returns true if the mutation has been queued, and the result
represents the queue time it will be processed.
ListHandlers returns a list of handler method names from a handler struct,
limited to [states].
MockClock mocks the internal clock of the machine. Only for testing.
New creates a new Machine instance, bound to context and modified with
optional Opts.
NewArgsMapper returns a matcher function for [Opts.LogArgs]. Useful for
debugging untyped argument maps. Usually [names] extend defaults from
[LogArgs].
maxLen: maximum length of the arg's string representation). Defaults to
LogArgsMaxLen,
NewCommon creates a new Machine instance with all the common options set.
NewEvent creates a new Event struct with private fields initialized.
NewLastTxTracer returns a Tracer that logs the last transition.
Pass prepares A from AT, to pass to further mutations.
PassMerge prepares A from AT and existing A, to pass to further
mutations.
SAdd 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.
SchemaMerge merges multiple state structs into one, overriding the previous
state definitions. No relation-level merging takes place.
SRem removes groups > 1 from nr 1.
StateAdd 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].
StatesDiff returns the states that are in states1 but not in states2.
StatesEqual returns true if states1 and states2 are equal, regardless of
order.
StateSet 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.
StatesShared return states present in both states1 and states2.
StatesToIndex returns a subset of [index] that matches [states]. Unknown
states are represented by -1.
Queued means that the transition was queued for later execution. Everything
above 2 also means Queued. The following methods can be used to wait for
the results:
- Machine.When
- Machine.WhenNot
- Machine.WhenArgs
- Machine.WhenTime
- Machine.WhenTime1
- Machine.WhenTicks
- Machine.WhenQueue
- Machine.WhenQueueEnds
See [Machine.QueueTick].
The pages are generated with Goldsv0.8.2. (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.