package helpers

Import Path
	/pkg/helpers (on go.dev)

Dependency Relation
	imports 22 packages, and imported by 34 packages

Involved Source Files Package helpers is a set of useful functions when working with async state machines.
Package-Level Type Names (total 8)
/* sort by: | */
type A = am.A (map)
Cond is a set of state conditions, which when all met make the condition true. TODO implement Only if any of these groups of states are active. Only if any of these states is active. Only if the clock is equal or higher then. Only if all these states are active. Only if none of these states are active. Check compares the specified conditions against the passed machine. When mach is nil, Check returns false. IsEmpty returns false if no condition is defined. ( Cond) String() string Cond : expvar.Var Cond : fmt.Stringer
(*MachGroup) Is1(state string) bool
MutRequest is a failsafe request for a machine mutation. It supports retries, backoff, max duration, delay, and timeout policies. It will try to mutate the machine until the context is done, or the max duration is reached. Queued mutations are considered supported a success. Args am.A Mach am.Api MutType am.MutationType PolicyBackoff is the max time to wait between retries. PolicyDelay is the delay before the first retry, then doubles. PolicyMaxDuration is the max time to wait for the mutation to be accepted. PolicyRetries is the max number of retries. States am.S (*MutRequest) Backoff(backoff time.Duration) *MutRequest (*MutRequest) Clone(mach am.Api, mutType am.MutationType, states am.S, args am.A) *MutRequest (*MutRequest) Delay(delay time.Duration) *MutRequest (*MutRequest) MaxDuration(maxDuration time.Duration) *MutRequest (*MutRequest) Retries(retries int) *MutRequest (*MutRequest) Run(ctx context.Context) (am.Result, error) func NewMutRequest(mach am.Api, mutType am.MutationType, states am.S, args am.A) *MutRequest func NewReqAdd(mach am.Api, states am.S, args am.A) *MutRequest func NewReqAdd1(mach am.Api, state string, args am.A) *MutRequest func NewReqRemove(mach am.Api, states am.S, args am.A) *MutRequest func NewReqRemove1(mach am.Api, state string, args am.A) *MutRequest func (*MutRequest).Backoff(backoff time.Duration) *MutRequest func (*MutRequest).Clone(mach am.Api, mutType am.MutationType, states am.S, args am.A) *MutRequest func (*MutRequest).Delay(delay time.Duration) *MutRequest func (*MutRequest).MaxDuration(maxDuration time.Duration) *MutRequest func (*MutRequest).Retries(retries int) *MutRequest
type S = am.S ([])
type Schema = am.Schema (map)
SlogToMachLog allows to use the machine logger as a slog sink. a.loggerMach = slog.New(slog.NewTextHandler( amhelp.SlogToMachLog{Mach: mach}, amhelp.SlogToMachLogOpts)) Mach am.Api ( SlogToMachLog) Write(p []byte) (n int, err error) SlogToMachLog : github.com/miekg/dns.Writer SlogToMachLog : internal/bisect.Writer SlogToMachLog : io.Writer
TODO thread safety via atomics ResetInterval time.Duration Threshold int Break breaks the loop. Ended returns the ended flag, but does not any context. Useful for negotiation handles which don't have state context yet. Ok returns true if the loop should continue. (*StateLoop) String() string Sum returns a sum of state time from all context states. *StateLoop : expvar.Var *StateLoop : fmt.Stringer func NewStateLoop(mach *am.Machine, loopState string, optCheck func() bool) *StateLoop
Package-Level Functions (total 63)
Activations return the number of state activations from the number of ticks passed.
Add1Async adds a state from an async op and waits for another one from the op to become active. Theoretically, it should work with any state pair, including Multi states (assuming they remove themselves). Not compatible with queued negotiation at the moment.
Add1Block activates a state and waits until it becomes active. If it's a multi-state, it also waits for it to deactivate. Returns early if a non-multi state is already active. Useful to avoid the queue but can't handle a rejected negotiation. Deprecated: use Add1Sync instead.
Add1Sync activates a state and waits until it becomes activate, or canceled. Add1Sync is a newer version of Add1Block that supports queued rejections, but at the moment it is not compatible with RPC. This method checks expiration ctx and returns as [am.Canceled].
Type Parameters: T: any ArgsFromMap takes an arguments map [am.A] and copies the fields into a typed argument struct value. Useful for typed args via RPC.
Type Parameters: T: any ArgsToArgs converts a typed arguments struct into an overlapping typed arguments struct. Useful for removing fields which can't be passed over RPC, and back. Both params should be pointers to a struct and share at least one field.
ArgsToLogMap converts an [A] (arguments) struct to a map of strings using `log` tags as keys, and their cased string values.
AskAdd will first check if a mutation isn't impossible and only then try to mutate the state machine. Causes the negotiation phase to execute twice. AskAdd BLOCKS. Useful to avoid canceled transitions. See also [am.Machine.CanAdd] and [CantAdd].
AskAdd1 is a single-state version of [AskAdd].
AskEvAdd is a traced version of [AskAdd].
AskEvAdd1 is a traced version of [AskAdd] for a single state.
AskEvRemove is a traced version of [AskRemove].
AskEvRemove1 is a traced version of [AskRemove] for a single state.
AskRemove will first check if a mutation isn't impossible and only then try to mutate the state machine. Causes the negotiation phase to execute twice. AskRemove BLOCKS. Useful to avoid canceled transitions. See also [am.Machine.CanRemove] and [CantRemove].
AskRemove1 is a single-state version of [AskRemove].
CantAdd will confirm that the mutation is impossible. Blocks.
CantAdd1 is a single-state version of [CantAdd].
CantRemove will confirm that the mutation is impossible. Blocks.
CantRemove1 is a single-state version of [CantRemove].
CopySchema copies states from the source to target schema, from the passed list of states. Returns a list of copied states, and an error. CopySchema verifies states.
CountRelations will count all referenced states in all relations of the given state.
Dispose triggers a machine disposal, using either the dedicated state set or the machine directly.
DisposeBind registers a disposal handler, using either the dedicated state set or the machine directly.
EnableDebugging sets env vars for debugging tested machines with am-dbg on port 6831.
Type Parameters: T: any EvalGetter is a syntax sugar for creating getters via Eval functions. Like any eval, it can end with ErrEvalTimeout. Getting values via channels passed to mutations is recommended and allows for a custom timeout.
ExecAndClose closes the chan when the function ends.
GetTransitionStates will extract added, removed, and touched states from transition's clock values and steps. Requires a state names index. Collecting touched states requires transition steps.
GroupWhen1 will create wait channels for the same state in a group of machines, or return a [am.ErrStateMissing].
Hash is a general hashing function. TODO move to pkg/machine
Healthcheck adds a state to a machine every 5 seconds, until the context is done. This makes sure all the logs are pushed to the telemetry server. TODO use machine scheduler when ready
Implements checks is statesChecked implement statesNeeded. It's an equivalent of Machine.Has(), but for slices of state names, and with better error msgs.
IndexesToStates converts a list of state indexes to a list of state names, for a given machine.
Interval runs a function at a given interval, for a given duration, or until the context is done. Returns nil if the duration has passed, or err is ctx is done. The function should return false to stop the interval.
IsDebug returns true if the process is in a "simple debug mode" via AM_DEBUG.
IsMulti returns true if a state is a multi state.
IsTelemetry returns true if the process is in telemetry debug mode.
MachDebug exports transition telemetry to an am-dbg instance listening at [amDbgAddr].
MachDebugEnv sets up a machine for debugging, based on env vars only: AM_DBG_ADDR, AM_LOG, AM_LOG_*, and AM_DEBUG. This function should be called right after the machine is created (to catch all the log entries).
NewMirror creates a submachine which mirrors the given source machine. If [flat] is true, only mutations changing the state will be propagated, along with the currently active states. At this point, the handlers' struct needs to be defined manually with fields of type `am.HandlerFinal`. [id] is optional.
NewMutRequest creates a new MutRequest with defaults - 10 retries, 100ms delay, 5s backoff, and 5s max duration.
NewReqAdd creates a new failsafe request to add states to a machine. See See MutRequest for more info and NewMutRequest for the defaults.
NewReqAdd1 creates a new failsafe request to add a single state to a machine. See MutRequest for more info and NewMutRequest for the defaults.
NewReqRemove creates a new failsafe request to remove states from a machine. See MutRequest for more info and NewMutRequest for the defaults.
NewReqRemove1 creates a new failsafe request to remove a single state from a machine. See MutRequest for more info and NewMutRequest for the defaults.
NewStateLoop helper creates a state loop guard bound to a specific state (eg Heartbeat), preventing infinite loops. It monitors context, off states, ticks of related "context states", and an optional check function. We can adjust Threshold and ResetInterval. Not thread safe ATM.
func Pool(limit int) *errgroup.Group
PrefixStates will prefix all state names with [prefix]. removeDups will skip overlaps eg "FooFooName" will be "Foo".
RemoveMulti creates a final handler which removes a multi state from a machine. Useful to avoid FooState-Remove1-Foo repetition.
func ResultToErr(result am.Result) error
SchemaHash computes an MD5 hash of the passed schema. The order of states is not important.
SchemaImplements checks if a given schema implements a certain set of states.
SchemaStates returns state names from a schema struct in a random order.
SemConfigEnv returns a SemConfigEnv based on env vars, or the [forceFull] flag.
SetEnvLogLevel sets AM_LOG env var to the passed log level. It will affect all future state machines using MachDebugEnv.
StatesToIndexes converts a list of state names to a list of state indexes, for the given machine. It returns -1 for unknown states.
TagValue returns the value part from a text tag "key:value". For tag without value, it returns the tag name.
TagValueInt is like TagValue, but returns a formatted int.
Wait waits for a duration, or until the context is done. Returns true if the duration has passed, or false if ctx is done.
WaitForAll waits for a list of channels to close, or until the context is done, or until the timeout is reached. Returns nil if all channels are closed, or ErrTimeout, or ctx.Err(). It's advised to check the state ctx after this call, as it usually means expiration and not a timeout.
WaitForAny waits for any of the channels to close, or until the context is done, or until the timeout is reached. Returns nil if any channel is closed, or ErrTimeout, or ctx.Err(). It's advised to check the state ctx after this call, as it usually means expiration and not a timeout. This function uses reflection to wait for multiple channels at once.
WaitForErrAll is like WaitForAll, but also waits on WhenErr of a passed machine. For state machines with error handling (like retry) it's recommended to measure machine time of [am.StateException] instead.
WaitForErrAny is like WaitForAny, but also waits on WhenErr of a passed machine. For state machines with error handling (like retry) it's recommended to measure machine time of [am.StateException] instead.
Package-Level Variables (total 2)
SlogToMachLogOpts complements SlogToMachLog.
Package-Level Constants (total 12)
EnvAmHealthcheck enables a healthcheck ticker for every debugged machine.
EnvAmLogArgs logs mutation args. See [am.SemLogger.EnableArgs]. "1" | "" (default)
EnvAmLogChecks logs Can methods. See [am.SemLogger.EnableCan]. "1" | "" (default)
EnvAmLogFile enables file logging (using machine ID as the name). "1" | "" (default)
EnvAmLogFull enables all the features of [am.SemLogger].
EnvAmLogGraph logs the graph structure (mutation traces, pipes, RPC, etc). See [am.SemLogger.EnableGraph]. "1" | "" (default)
EnvAmLogPrint prints machine log to stdout.
EnvAmLogQueued logs queued mutations. See [am.SemLogger.EnableQueued]. "1" | "" (default)
EnvAmLogStateCtx logs state ctxs. See [am.SemLogger.EnableStateCtx]. "1" | "" (default)
EnvAmLogSteps logs transition steps. See [am.SemLogger.EnableSteps]. "1" | "" (default)
EnvAmLogWhen logs When methods. See [am.SemLogger.EnableWhen]. "1" | "" (default)
EnvAmTestRunner indicates the main test tunner, disables any telemetry.