actors

package
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2025 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DiagnosticsPatchesQuery is the reserved Temporal query name that returns actor patch metadata.
	DiagnosticsPatchesQuery = "actors_diag_patches"
	// DiagnosticsSnapshotQuery returns snapshot/Continue-As-New statistics for the workflow.
	DiagnosticsSnapshotQuery = "actors_diag_snapshot"
)
View Source
const DefaultVersion = -1

DefaultVersion mirrors Temporal's workflow.DefaultVersion for convenience.

Variables

View Source
var (
	// ErrStopLoop signals the workflow loop should terminate gracefully.
	ErrStopLoop = errors.New("actors: stop loop")
)
View Source
var ErrUnsupported = errors.New("actors: unsupported operation")

Functions

func AsBusinessError

func AsBusinessError(err error) (error, bool)

AsBusinessError reports whether err was created via BusinessError.

func Ask

func Ask[Req TypedCommandMessage[Resp], Resp any](ctx Ctx, ref Ref, req Req) (Resp, error)

Ask sends a typed command to another actor instance and waits for the response.

func BackgroundActivity

func BackgroundActivity(ctx Ctx, name string, payload any)

BackgroundActivity launches an activity asynchronously and logs errors via the runtime.

func BusinessError

func BusinessError(err error) error

BusinessError wraps err so runtimes can reply with application errors without treating them as fatal workflow failures.

func Cause

func Cause(err error) error

Cause extracts the underlying cause attached via WithCause.

func CompleteSession

func CompleteSession(session Session) error

CompleteSession releases the slot acquired via StartSession.

func ContinueAsNew

func ContinueAsNew(ctx Ctx, payload any) error

ContinueAsNew restarts the current actor workflow with a new init payload.

func Effect

func Effect[Resp any](ctx Ctx, key string, fn func(Ctx) (Resp, error), opts ...EffectOption) (Resp, error)

Effect executes fn with deduplication keyed by key and persists the result.

func InvokeAsk

func InvokeAsk[R any](ctx context.Context, ref Ref, payload any, opts ...AskOption) (R, error)

InvokeAsk executes a command and waits for the typed response.

func InvokeCommand

func InvokeCommand(ctx context.Context, ref Ref, payload any) error

InvokeCommand sends a fire-and-forget command to the target actor.

func InvokeQuery

func InvokeQuery[R any](ctx context.Context, ref Ref, payload any) (R, error)

InvokeQuery executes a read-only query against the actor workflow.

func IsNonRetryable

func IsNonRetryable(err error) bool

IsNonRetryable reports whether err was wrapped via NonRetryable.

func IsRetryAfter

func IsRetryAfter(err error) (time.Duration, bool)

IsRetryAfter extracts the requested retry delay.

func MarshalDescription

func MarshalDescription(desc *Description) ([]byte, error)

MarshalDescription produces the canonical manifest for the provided description.

func Memo

func Memo(ctx Ctx) map[string]any

Memo returns the workflow memo if the runtime exposes it.

func NonRetryable

func NonRetryable(err error) error

NonRetryable marks an error so runtimes treat it as non-retryable.

func Patch

func Patch(ctx Ctx, changeID string) bool

Patch reports whether the change identified by changeID is active.

func PatchDefaultOff

func PatchDefaultOff(ctx Ctx, changeID string) bool

PatchDefaultOff mirrors Patch but returns false when ctx is nil or the runtime reports DefaultVersion.

func QueryActor

func QueryActor[Req TypedQueryMessage[Resp], Resp any](ctx Ctx, ref Ref, req Req) (Resp, error)

QueryActor executes a typed query against another actor instance.

func RegisterActorDescription

func RegisterActorDescription(actor Actor)

RegisterActorDescription registers the provided actor with the default registry.

func RegisterClientInvoker

func RegisterClientInvoker(factory func(Ref) ClientInvoker)

RegisterClientInvoker installs the factory used by Invoke* helpers. The last registration wins.

func RegisterDescription

func RegisterDescription(desc *Description)

RegisterDescription stores a description in the default registry.

func RequestContinueAsNew

func RequestContinueAsNew(ctx Ctx, ref Ref, opts ...ContinueAsNewOption) error

RequestContinueAsNew asks another actor instance to snapshot and continue-as-new.

func RetryAfter

func RetryAfter(err error, delay time.Duration) error

RetryAfter requests the runtime to retry the message after delay.

func RunActivity

func RunActivity[Req TypedActivityMessage[Resp], Resp any](ctx Ctx, payload Req, opts ...ActivityCallOption) (Resp, error)

RunActivity executes an activity synchronously and decodes the typed result, routing by payload type.

func RunActivityBackground

func RunActivityBackground[Req TypedActivityMessage[Resp], Resp any](ctx Ctx, payload Req) error

RunActivityBackground launches a fire-and-forget activity based on the payload type.

func RunActivityNamed

func RunActivityNamed[Req TypedActivityMessage[Resp], Resp any](ctx Ctx, name string, payload Req, opts ...ActivityCallOption) (Resp, error)

RunActivityNamed executes an activity by explicit name and decodes the typed result.

func RunActivityNoResult

func RunActivityNoResult[Req TypedActivityMessage[struct{}]](ctx Ctx, payload Req, opts ...ActivityCallOption) error

RunActivityNoResult executes an activity that only returns an error, routing by payload type.

func RunActivityNoResultNamed

func RunActivityNoResultNamed[Req TypedActivityMessage[struct{}]](ctx Ctx, name string, payload Req, opts ...ActivityCallOption) error

RunActivityNoResultNamed executes a named activity that only returns an error.

func RunActivityTyped

func RunActivityTyped[Req TypedActivityMessage[Resp], Resp any](ctx Ctx, payload Req, opts ...ActivityCallOption) (Resp, error)

RunActivityTyped resolves the activity name from the payload type and executes it.

func RunSessionActivity

func RunSessionActivity[Req TypedActivityMessage[Resp], Resp any](session Session, payload Req, opts ...ActivityCallOption) (Resp, error)

RunSessionActivity executes an activity within the provided session context.

func RunSessionActivityNamed

func RunSessionActivityNamed[Req TypedActivityMessage[Resp], Resp any](session Session, name string, payload Req, opts ...ActivityCallOption) (Resp, error)

RunSessionActivityNamed executes an activity within the provided session context by explicit name.

func RunSessionActivityNoResult

func RunSessionActivityNoResult[Req TypedActivityMessage[struct{}]](session Session, payload Req, opts ...ActivityCallOption) error

RunSessionActivityNoResult executes an activity within the session and only returns an error.

func RunSessionActivityNoResultNamed

func RunSessionActivityNoResultNamed[Req TypedActivityMessage[struct{}]](session Session, name string, payload Req, opts ...ActivityCallOption) error

RunSessionActivityNoResultNamed executes a named session activity that only returns an error.

func SearchAttributes

func SearchAttributes(ctx Ctx) map[string]any

SearchAttributes returns the workflow search attributes if the runtime exposes them.

func SetCorrelation

func SetCorrelation(ctx Ctx, data CorrelationData)

SetCorrelation overrides the correlation annotations that downstream calls should inherit.

func SetDefaultRegistry

func SetDefaultRegistry(reg DescriptionRegistry)

SetDefaultRegistry replaces the process-wide registry reference.

func SpawnOneShot

func SpawnOneShot[Req TypedCommandMessage[Resp], Resp any](ctx Ctx, req Req, opts ...SpawnOption) (Resp, error)

SpawnOneShot launches a one-shot child workflow returning a typed response.

func Tell

func Tell[Req TypedCommandMessage[Resp], Resp any](ctx Ctx, ref Ref, req Req) error

Tell sends a typed command to another actor instance without waiting for a response.

func TypeKeyOf

func TypeKeyOf(value any) string

TypeKeyOf returns the type string used to map commands/queries to names.

func TypeName

func TypeName[T any]() string

TypeName returns the fully qualified name of the supplied type parameter.

func UnregisterKind

func UnregisterKind(kind string)

UnregisterKind removes a kind from the default registry.

func UpsertSearchAttributes

func UpsertSearchAttributes(ctx Ctx, attrs map[string]any) error

UpsertSearchAttributes updates the workflow search attributes.

func WithCause

func WithCause(err, cause error) error

WithCause attaches an explanatory cause to err for richer diagnostics.

Types

type ActivityAction

type ActivityAction[S any] struct {
	// contains filtered or unexported fields
}

func Activity

func Activity[P any, R any](fn func(context.Context, P) (R, error), opts ...ActivityOption[any]) ActivityAction[any]

Activity registers a typed activity using the payload type as the route name.

func ActivityAuto

func ActivityAuto[P any, R any](fn func(context.Context, P) (R, error)) ActivityAction[any]

ActivityAuto registers an activity using the payload type as the route name.

func ActivityNamed

func ActivityNamed[P any, R any](name string, fn func(context.Context, P) (R, error), opts ...ActivityOption[any]) ActivityAction[any]

ActivityNamed registers an activity with an explicit name.

func ActivityNoResult

func ActivityNoResult[P any](fn func(context.Context, P) error, opts ...ActivityOption[any]) ActivityAction[any]

ActivityNoResult registers an activity that only returns an error using the payload type as the route name.

func ActivityNoResultAuto

func ActivityNoResultAuto[P any](fn func(context.Context, P) error) ActivityAction[any]

ActivityNoResultAuto registers a no-result activity using the payload type as the route name.

func ActivityNoResultNamed

func ActivityNoResultNamed[P any](name string, fn func(context.Context, P) error, opts ...ActivityOption[any]) ActivityAction[any]

ActivityNoResultNamed registers a no-result activity with an explicit name.

type ActivityCallOption

type ActivityCallOption func(*ActivityCallOptions)

ActivityCallOption customizes ActivityCallOptions.

func WithActivityHeartbeat

func WithActivityHeartbeat(d time.Duration) ActivityCallOption

WithActivityHeartbeat sets the heartbeat timeout.

func WithActivityRetry

func WithActivityRetry(policy RetryPolicy) ActivityCallOption

WithActivityRetry sets the activity retry policy.

func WithActivityScheduleToClose

func WithActivityScheduleToClose(d time.Duration) ActivityCallOption

WithActivityScheduleToClose sets the schedule-to-close timeout.

func WithActivityScheduleToStart

func WithActivityScheduleToStart(d time.Duration) ActivityCallOption

WithActivityScheduleToStart sets the schedule-to-start timeout.

func WithActivityStartToClose

func WithActivityStartToClose(d time.Duration) ActivityCallOption

WithActivityStartToClose sets the start-to-close timeout.

func WithActivityTaskQueue

func WithActivityTaskQueue(name string) ActivityCallOption

WithActivityTaskQueue routes the activity to a specific task queue.

type ActivityCallOptions

type ActivityCallOptions struct {
	ScheduleToClose time.Duration
	ScheduleToStart time.Duration
	StartToClose    time.Duration
	Heartbeat       time.Duration
	Retry           RetryPolicy
	TaskQueue       string
}

ActivityCallOptions configures per-invocation activity behavior.

type ActivityFunc

type ActivityFunc func(context.Context, any) (any, error)

ActivityFunc adapts user functions into a runtime-callable activity.

type ActivityFuture

type ActivityFuture interface {
	Get() (any, error)
}

ActivityFuture is a placeholder for the runtime specific promise returned by Activity.

type ActivityMetadata

type ActivityMetadata struct {
	Name            string
	RequestType     string
	ResponseType    string
	ScheduleToClose time.Duration
	ScheduleToStart time.Duration
	StartToClose    time.Duration
	Heartbeat       time.Duration
	TaskQueue       string
	Retry           RetryPolicy
}

ActivityMetadata captures registered activity schemas.

type ActivityMsg

type ActivityMsg[Resp any] struct{}

ActivityMsg ties an activity request to its response type.

func (ActivityMsg[Resp]) ActivityResponsePrototype

func (ActivityMsg[Resp]) ActivityResponsePrototype() Resp

ActivityResponsePrototype satisfies the TypedActivityMessage interface.

type ActivityOption

type ActivityOption[S any] func(*ActivityAction[S])

func WithActivityDefaults

func WithActivityDefaults(opts ...ActivityCallOption) ActivityOption[any]

WithActivityDefaults sets default call options for the activity route.

type ActivitySpec

type ActivitySpec struct {
	Handler ActivityFunc
	Options ActivityCallOptions
}

ActivitySpec captures routing and defaults for an activity.

type Actor

type Actor interface {
	Kind() string
	Spec() *Description
}

Actor is the runtime-facing representation of an actor definition.

type ActorMetadata

type ActorMetadata struct {
	Kind           string
	VersionTag     string
	WorkflowQueue  string
	ActivityQueue  string
	DefaultTimeout time.Duration
	DefaultRetry   RetryPolicy
	SnapshotEvery  int
	Start          StartMetadata
	Commands       []CommandMetadata
	Queries        []QueryMetadata
	Activities     []ActivityMetadata
	Patches        []PatchMetadata
	CommandTypes   map[string]string
	QueryTypes     map[string]string
	ActivityTypes  map[string]string
}

ActorMetadata captures routing, schema, and option details for an actor description.

type AskOption

type AskOption func(*AskOptions)

AskOption customizes AskOptions.

func WithCorrelationID

func WithCorrelationID(id string) AskOption

WithCorrelationID overrides the correlation identifier attached to the ask.

type AskOptions

type AskOptions struct {
	CorrelationID string
}

AskOptions exposes optional metadata for ask calls.

type ClientInvoker

type ClientInvoker interface {
	InvokeCommand(ctx context.Context, ref Ref, method string, payload any) error
	InvokeAsk(ctx context.Context, ref Ref, method string, payload any, resp any, opts AskOptions) error
	InvokeQuery(ctx context.Context, ref Ref, method string, payload any, resp any) error
}

ClientInvoker drives ask/tell/query operations from non-actor processes (e.g., HTTP gateways).

type CommandAction

type CommandAction[S any] struct {
	// contains filtered or unexported fields
}

CommandAction is a typed adapter created via Command.

func Command

func Command[S any, Req any, Resp any](fn func(Ctx, *S, Req) (Resp, error), opts ...CommandOption) CommandAction[S]

Command lifts a typed command handler into an action the builder understands.

func CommandFunc

func CommandFunc[S any, Req TypedCommandMessage[Resp], Resp any](fn func(Ctx, *S, Req) (Resp, error), opts ...CommandOption) CommandAction[S]

CommandFunc infers the request/response types from the handler signature.

func StopCommandAction

func StopCommandAction[S any]() CommandAction[S]

StopCommandAction registers a handler that returns ErrStopLoop when StopCommand runs.

type CommandHandler

type CommandHandler struct {
	Name  string
	Input string
	// contains filtered or unexported fields
}

CommandHandler routes inbound commands to user code.

func (CommandHandler) Invoke

func (h CommandHandler) Invoke(ctx Ctx, state any, payload any) (any, error)

Invoke executes the user-supplied command handler.

type CommandMetadata

type CommandMetadata struct {
	Name          string
	RequestType   string
	ResponseType  string
	Timeout       time.Duration
	SignalTimeout time.Duration
	Retry         RetryPolicy
	HasValidator  bool
}

CommandMetadata captures per-command routing info.

type CommandMsg

type CommandMsg[Resp any] struct{}

CommandMsg is a helper embed that ties a request to its response type.

func (CommandMsg[Resp]) CommandResponsePrototype

func (CommandMsg[Resp]) CommandResponsePrototype() Resp

CommandResponsePrototype satisfies the TypedCommandMessage interface.

type CommandOption

type CommandOption func(*commandOptions)

func WithRetry

func WithRetry(policy RetryPolicy) CommandOption

WithRetry overrides the retry policy for this command.

func WithTimeout

func WithTimeout(timeout time.Duration) CommandOption

WithTimeout overrides the default timeout for this command.

func WithValidator

func WithValidator[Req any](fn func(Req) error) CommandOption

WithValidator attaches a validation hook executed before the handler runs.

type CommandSpec

type CommandSpec struct {
	Handler        CommandHandler
	Timeout        time.Duration
	Retry          RetryPolicy
	ResponseType   string
	PayloadFactory func() any
	DecodePayload  func(any) (any, error)
	Validator      func(any) error
}

CommandSpec captures metadata for a command route.

type ContinueAsNewOption

type ContinueAsNewOption func(*ContinueAsNewOptions)

ContinueAsNewOption customizes ContinueAsNewOptions.

func WithContinueInit

func WithContinueInit(payload any) ContinueAsNewOption

WithContinueInit overrides the init payload supplied to the next run.

type ContinueAsNewOptions

type ContinueAsNewOptions struct {
	Init any
}

ContinueAsNewOptions configure how a remote continue-as-new request behaves.

type CorrelationData

type CorrelationData struct {
	SagaID     string
	TraceID    string
	ParentID   string
	Attributes map[string]string
}

CorrelationData carries saga/trace identifiers and arbitrary annotations.

func Correlation

func Correlation(ctx Ctx) CorrelationData

Correlation returns the current saga/tracing annotations associated with the message.

func (CorrelationData) Clone

func (c CorrelationData) Clone() CorrelationData

Clone returns a deep copy of the correlation data.

func (CorrelationData) IsZero

func (c CorrelationData) IsZero() bool

IsZero reports whether the correlation payload is empty.

type Ctx

type Ctx interface {
	ActorID() string
	Now() time.Time
	Sleep(delay time.Duration) error
	Version(changeID string, defaultVersion, newVersion int) int
	Activity(name string, payload any) ActivityFuture
	ActivityWithOptions(name string, payload any, opts ActivityCallOptions) ActivityFuture
	BackgroundActivity(name string, payload any)
	Logger() Logger
	Self() Ref
	UpsertSearchAttributes(attrs map[string]any) error
	SearchAttributes() map[string]any
	MessageMetadata() MessageMetadata
	Effect(key string, fn EffectFunc, opts ...EffectOption) (any, error)
	Correlation() CorrelationData
	SetCorrelation(CorrelationData)
	SnapshotInfo() SnapshotInfo
}

Ctx is the execution context passed to every handler. It intentionally mirrors the subset of Temporal features most actors rely on so another runtime could be wired up later.

type Description

type Description struct {
	Kind           string
	VersionTag     string
	Timeout        time.Duration
	Retry          RetryPolicy
	SignalTimeouts map[string]time.Duration
	WorkflowQueue  string
	ActivityQueue  string
	StateFactory   func() any
	Start          StartHandler
	Commands       map[string]CommandSpec
	Queries        map[string]QuerySpec
	Activities     map[string]ActivitySpec

	ActivityTypes     map[string]string
	ActivityResults   map[string]string
	ActivityNames     map[string]string
	ActivityObservers []func(string, ActivityCallOptions)
	CommandTypes      map[string]string
	QueryTypes        map[string]string
	Patches           map[string]PatchSpec
	SnapshotEvery     int
	SnapshotArgs      func(any) (any, error)
	// contains filtered or unexported fields
}

Description is a runtime-agnostic schema the builder emits. It deliberately avoids reflection-friendly types so runtimes can stay in the typed world.

func LookupDescription

func LookupDescription(kind string) *Description

LookupDescription fetches a description by kind from the default registry.

func (*Description) ActivityDecoders

func (d *Description) ActivityDecoders() map[string]func(any) (any, error)

ActivityDecoders exposes the registered activity result decoders.

func (*Description) ActivityDefaults

func (d *Description) ActivityDefaults() map[string]ActivityCallOptions

ActivityDefaults exposes the registered per-activity default call options.

func (*Description) Clone

func (d *Description) Clone() *Description

Clone returns a deep copy of the description maps so runtimes can safely mutate them.

func (*Description) HasWorkflow added in v0.4.0

func (d *Description) HasWorkflow() bool

HasWorkflow reports whether the description includes any workflow handlers or state.

func (*Description) Metadata

func (d *Description) Metadata() ActorMetadata

Metadata generates a stable metadata summary for the description.

func (*Description) PatchSpecs

func (d *Description) PatchSpecs() []PatchSpec

PatchSpecs returns the declared patch metadata sorted by identifier.

type DescriptionManifest

type DescriptionManifest struct {
	Version int             `json:"version"`
	Hash    string          `json:"hash"`
	Actor   serializedActor `json:"actor"`
}

DescriptionManifest is the canonical serialized representation of an actor description.

func UnmarshalDescription

func UnmarshalDescription(data []byte) (DescriptionManifest, error)

UnmarshalDescription parses a manifest into its typed form.

func (DescriptionManifest) Metadata

func (m DescriptionManifest) Metadata() (ActorMetadata, error)

Metadata converts the manifest back into ActorMetadata.

func (DescriptionManifest) VerifyHash

func (m DescriptionManifest) VerifyHash() error

VerifyHash recomputes the schema hash and reports mismatches.

type DescriptionRegistry

type DescriptionRegistry interface {
	RegisterActor(actor Actor)
	RegisterDescription(desc *Description)
	Unregister(kind string)
	Lookup(kind string) *Description
	List() []RegisteredActor
}

DescriptionRegistry exposes thread-safe registration and lookup helpers for actor descriptions.

func DefaultRegistry

func DefaultRegistry() DescriptionRegistry

DefaultRegistry returns the process-wide registry used by runtime helpers.

func NewRegistry

func NewRegistry() DescriptionRegistry

NewRegistry returns an in-memory implementation of DescriptionRegistry.

type EffectFunc

type EffectFunc func(Ctx) (any, error)

EffectFunc encapsulates a side effect function invoked via ctx.Effect.

type EffectOption

type EffectOption func(*EffectOptions)

EffectOption customizes EffectOptions.

func WithEffectTTL

func WithEffectTTL(ttl time.Duration) EffectOption

WithEffectTTL controls how long effect results are retained for deduplication.

type EffectOptions

type EffectOptions struct {
	TTL time.Duration
}

EffectOptions configure effect persistence behavior.

type Logger

type Logger interface {
	Debug(msg string, kv ...any)
	Info(msg string, kv ...any)
	Warn(msg string, kv ...any)
	Error(msg string, kv ...any)
}

Logger is the minimal logging surface actors need. Runtimes can adapt their logger of choice.

type MessageMetadata

type MessageMetadata struct {
	// ID uniquely identifies the delivery attempt within the receiving workflow.
	ID string
	// CorrelationID links the delivery back to the caller; defaults to ID when unset.
	CorrelationID string
	// Correlation carries saga IDs or tracing spans that should propagate downstream.
	Correlation CorrelationData
	// Deadline is optional and represents the point after which the call is considered expired.
	Deadline time.Time
	// RetryBudget expresses how many retries remain from the caller's perspective.
	RetryBudget int
	// RetryBudgetSet reports whether RetryBudget should be enforced. When false, the
	// budget is treated as unlimited.
	RetryBudgetSet bool
	// Caller identifies who initiated the delivery if known.
	Caller Ref
}

MessageMetadata carries correlation data about the currently processed message.

func Message

func Message(ctx Ctx) MessageMetadata

Message returns metadata about the currently processed message.

func (MessageMetadata) HasDeadline

func (m MessageMetadata) HasDeadline() bool

HasDeadline reports whether a deadline is configured.

type PatchMetadata

type PatchMetadata struct {
	ID        string
	DefaultOn bool
	Note      string
}

PatchMetadata captures declared patch toggles.

type PatchReport

type PatchReport struct {
	Kind    string
	Patches []PatchStatus
}

PatchReport enumerates every patch declared on an actor kind.

func QueryPatchReport

func QueryPatchReport(ctx context.Context, ref Ref) (PatchReport, error)

QueryPatchReport asks the target actor for its patch metadata via the diagnostics query.

type PatchSpec

type PatchSpec struct {
	ID        string
	DefaultOn bool
	Note      string
}

PatchSpec declares a forward-compatible patch gate.

type PatchStatus

type PatchStatus struct {
	ID        string
	DefaultOn bool
	Note      string
}

PatchStatus captures the static metadata for a declared patch.

type QueryAction

type QueryAction[S any] struct {
	// contains filtered or unexported fields
}

QueryAction is a typed adapter created via Query.

func Query

func Query[S any, Req any, Resp any](fn func(Ctx, S, Req) (Resp, error), opts ...QueryOption) QueryAction[S]

Query lifts a typed query handler into an action the builder understands.

func QueryFunc

func QueryFunc[S any, Req TypedQueryMessage[Resp], Resp any](fn func(Ctx, S, Req) (Resp, error), opts ...QueryOption) QueryAction[S]

QueryFunc infers the request/response types from the handler signature.

type QueryHandler

type QueryHandler struct {
	Name  string
	Input string
	// contains filtered or unexported fields
}

QueryHandler routes read-only queries.

func (QueryHandler) Invoke

func (h QueryHandler) Invoke(ctx Ctx, state any, payload any) (any, error)

Invoke executes the user-supplied query handler.

type QueryMetadata

type QueryMetadata struct {
	Name         string
	RequestType  string
	ResponseType string
	CacheTTL     time.Duration
}

QueryMetadata captures per-query routing info.

type QueryMsg

type QueryMsg[Resp any] struct{}

QueryMsg is a helper embed that ties a query request to its response type.

func (QueryMsg[Resp]) QueryResponsePrototype

func (QueryMsg[Resp]) QueryResponsePrototype() Resp

QueryResponsePrototype satisfies the TypedQueryMessage interface.

type QueryOption

type QueryOption func(*queryOptions)

func WithCache

func WithCache(ttl time.Duration) QueryOption

WithCache sets the cache hint for this query.

type QuerySpec

type QuerySpec struct {
	Handler        QueryHandler
	CacheTTL       time.Duration
	ResponseType   string
	PayloadFactory func() any
	DecodePayload  func(any) (any, error)
}

QuerySpec captures metadata for a query route.

type Ref

type Ref struct {
	Workflow     string
	Kind         string
	ID           string
	Tenant       string
	WorkflowType string
	TaskQueue    string
	RunID        string
	StartArgs    []any
}

Ref uniquely identifies an actor instance.

func ARef

func ARef(kind, id string, opts ...RefOption) Ref

ARef constructs a Ref whose workflow type and task queue default to the actor kind.

func Parent

func Parent(ctx Ctx) Ref

Parent returns the parent reference if exposed by the runtime.

func Spawn

func Spawn(ctx Ctx, kind string, init any, opts ...SpawnOption) (Ref, error)

Spawn launches a long-lived child actor.

func TRef

func TRef(tenant, kind, id string, opts ...RefOption) Ref

TRef constructs a tenant-aware reference (workflow type equals kind).

func (Ref) Empty

func (r Ref) Empty() bool

Empty reports whether the reference is unset.

func (Ref) StartPayload

func (r Ref) StartPayload() []any

StartPayload returns the arguments that should be supplied if the workflow needs to be started.

type RefOption

type RefOption func(*Ref)

RefOption customizes a Ref while constructing helper references.

func WithRunID

func WithRunID(runID string) RefOption

WithRunID pins the reference to a specific workflow run.

func WithStartArgs

func WithStartArgs(args ...any) RefOption

WithStartArgs overrides the arguments used when starting actor workflows.

func WithTaskQueue

func WithTaskQueue(queue string) RefOption

WithTaskQueue overrides the task queue used when auto-starting actors.

func WithWorkflowType

func WithWorkflowType(name string) RefOption

WithWorkflowType overrides the workflow type used when auto-starting actors.

type RegisteredActor

type RegisteredActor struct {
	Kind        string
	Description *Description
	Metadata    ActorMetadata
}

RegisteredActor captures a point-in-time snapshot of a registered actor.

func RegisteredActors

func RegisteredActors() []RegisteredActor

RegisteredActors returns sorted snapshots of every registered kind.

type RetryPolicy

type RetryPolicy struct {
	MaxAttempts        int
	InitialInterval    time.Duration
	BackoffCoefficient float64
}

RetryPolicy captures a handful of knobs all runtimes typically expose.

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session represents a host-affine slot managed by the runtime.

func NewSessionHandle

func NewSessionHandle(id string, runtime SessionRuntime, handle any) Session

NewSessionHandle constructs a session backed by the provided runtime implementation.

func StartSession

func StartSession(ctx Ctx, opts SessionOptions) (Session, error)

StartSession requests a host-affine slot from the runtime.

func (Session) ID

func (s Session) ID() string

ID returns the underlying session identifier exposed by the runtime.

type SessionOptions

type SessionOptions struct {
	CreationTimeout  time.Duration
	ExecutionTimeout time.Duration
	HeartbeatTimeout time.Duration
}

SessionOptions mirror Temporal session configuration knobs.

type SessionRuntime

type SessionRuntime interface {
	InvokeSessionActivity(handle any, name string, payload any, opts ActivityCallOptions) (ActivityFuture, error)
	CompleteSessionHandle(handle any) error
}

type SnapshotConfig

type SnapshotConfig[S any] struct {
	Every        int
	ContinueArgs func(state S) (any, error)
}

SnapshotConfig configures automatic ContinueAsNew rotation with state snapshots.

type SnapshotInfo

type SnapshotInfo struct {
	Enabled               bool
	SnapshotEvery         int
	SnapshotsTaken        int
	ContinueAsNewCount    int
	CommandsSinceSnapshot int
	LastSnapshotTime      time.Time
}

SnapshotInfo exposes snapshot/continue statistics for diagnostics.

func Snapshot

func Snapshot(ctx Ctx) SnapshotInfo

Snapshot returns snapshot metadata from the current context.

type SnapshotReport

type SnapshotReport struct {
	Kind     string
	Snapshot SnapshotInfo
}

SnapshotReport returns snapshot rotation statistics for an actor workflow.

func QuerySnapshotReport

func QuerySnapshotReport(ctx context.Context, ref Ref) (SnapshotReport, error)

QuerySnapshotReport asks the target actor for its snapshot/rotation state via the diagnostics query.

type SpawnConfig

type SpawnConfig struct {
	Kind      string
	Name      string
	Timeout   time.Duration
	TaskQueue string
}

SpawnConfig captures optional settings for child workflows.

type SpawnOption

type SpawnOption func(*SpawnConfig)

SpawnOption customizes spawn behavior.

func WithChildKind

func WithChildKind(kind string) SpawnOption

WithChildKind specifies the actor kind to target when spawning children.

func WithChildName

func WithChildName(name string) SpawnOption

func WithChildTaskQueue

func WithChildTaskQueue(name string) SpawnOption

WithChildTaskQueue routes the child workflow to a specific task queue.

func WithChildTimeout

func WithChildTimeout(d time.Duration) SpawnOption

type StartAction

type StartAction[S any] struct {
	// contains filtered or unexported fields
}

StartAction is a typed adapter created via Start.

func Start

func Start[S any, P any](fn func(Ctx, P) (S, error)) StartAction[S]

Start lifts a typed init function into an action the builder understands.

type StartHandler

type StartHandler struct {
	Input string
	// contains filtered or unexported fields
}

StartHandler is invoked when a new actor instance spins up.

func (StartHandler) Invoke

func (h StartHandler) Invoke(ctx Ctx, payload any) (any, error)

Invoke executes the user-supplied logic.

type StartMetadata

type StartMetadata struct {
	InputType string
}

StartMetadata describes the init payload schema.

type StatefulBuilder

type StatefulBuilder[S any] struct {
	// contains filtered or unexported fields
}

StatefulBuilder wires up typed handlers for the provided state.

func NewStateful

func NewStateful[S any](kind string, factory func() S) StatefulBuilder[S]

NewStateful declares a new actor kind with a typed state factory.

func (StatefulBuilder[S]) Build

func (b StatefulBuilder[S]) Build() Actor

Build finalizes the actor and returns something the app can register.

func (StatefulBuilder[S]) DeclarePatch

func (b StatefulBuilder[S]) DeclarePatch(id string, defaultOn bool) StatefulBuilder[S]

DeclarePatch registers a patch identifier and its default activation state for metadata consumers.

func (StatefulBuilder[S]) OnStart

func (b StatefulBuilder[S]) OnStart(action StartAction[S]) StatefulBuilder[S]

OnStart registers the initialization logic for the actor.

func (StatefulBuilder[S]) With

func (b StatefulBuilder[S]) With(actions ...statefulAction[S]) StatefulBuilder[S]

With applies multiple actions such as commands, queries, or start hooks.

func (StatefulBuilder[S]) WithActivity

func (b StatefulBuilder[S]) WithActivity(name string, fn ActivityFunc) StatefulBuilder[S]

WithActivity registers a callable that handlers can trigger via ctx.Activity.

func (StatefulBuilder[S]) WithActivityQueue

func (b StatefulBuilder[S]) WithActivityQueue(name string) StatefulBuilder[S]

WithActivityQueue overrides the activity task queue for this actor.

func (StatefulBuilder[S]) WithRetry

func (b StatefulBuilder[S]) WithRetry(policy RetryPolicy) StatefulBuilder[S]

WithRetry sets the retry policy for this actor.

func (StatefulBuilder[S]) WithSignalTimeout

func (b StatefulBuilder[S]) WithSignalTimeout(name string, timeout time.Duration) StatefulBuilder[S]

WithSignalTimeout sets a per-command timeout for inbound signals.

func (StatefulBuilder[S]) WithSnapshot

func (b StatefulBuilder[S]) WithSnapshot(cfg SnapshotConfig[S]) StatefulBuilder[S]

WithSnapshot enables periodic snapshotting/ContinueAsNew for the actor state.

func (StatefulBuilder[S]) WithTimeout

func (b StatefulBuilder[S]) WithTimeout(timeout time.Duration) StatefulBuilder[S]

WithTimeout configures the workflow execution timeout.

func (StatefulBuilder[S]) WithVersionTag

func (b StatefulBuilder[S]) WithVersionTag(tag string) StatefulBuilder[S]

WithVersionTag annotates the actor description with a semantic version identifier.

func (StatefulBuilder[S]) WithWorkflowQueue

func (b StatefulBuilder[S]) WithWorkflowQueue(name string) StatefulBuilder[S]

WithWorkflowQueue overrides the workflow task queue for this actor.

type StatelessBuilder

type StatelessBuilder struct {
	// contains filtered or unexported fields
}

StatelessBuilder is the entry point - users can register timeouts/retries without committing to a stateful actor. Calling WithState transitions into a typed StatefulBuilder.

func New

func New(kind string) StatelessBuilder

New declares a new actor kind.

func (StatelessBuilder) Build

func (b StatelessBuilder) Build() Actor

Build finalizes the actor without any stateful behavior.

func (StatelessBuilder) WithActivity

func (b StatelessBuilder) WithActivity(name string, fn ActivityFunc) StatelessBuilder

WithActivity registers a callable that handlers can trigger via ctx.Activity.

func (StatelessBuilder) WithActivityQueue

func (b StatelessBuilder) WithActivityQueue(name string) StatelessBuilder

WithActivityQueue overrides the default activity task queue for this actor.

func (StatelessBuilder) WithRetry

func (b StatelessBuilder) WithRetry(policy RetryPolicy) StatelessBuilder

WithRetry sets the retry policy for this actor.

func (StatelessBuilder) WithSignalTimeout

func (b StatelessBuilder) WithSignalTimeout(name string, timeout time.Duration) StatelessBuilder

WithSignalTimeout sets a per-command timeout for inbound signals.

func (StatelessBuilder) WithTimeout

func (b StatelessBuilder) WithTimeout(timeout time.Duration) StatelessBuilder

WithTimeout configures the workflow execution timeout.

func (StatelessBuilder) WithWorkflowQueue

func (b StatelessBuilder) WithWorkflowQueue(name string) StatelessBuilder

WithWorkflowQueue overrides the default workflow task queue for this actor.

type StopCommand

type StopCommand struct {
	CommandMsg[struct{}]
}

StopCommand is a built-in command that stops the workflow loop gracefully.

type TypedActivityMessage

type TypedActivityMessage[Resp any] interface {
	ActivityResponsePrototype() Resp
}

TypedActivityMessage allows helpers to infer activity response types.

type TypedCommandMessage

type TypedCommandMessage[Resp any] interface {
	CommandResponsePrototype() Resp
}

TypedCommandMessage allows runtimes to infer a command's response type.

type TypedQueryMessage

type TypedQueryMessage[Resp any] interface {
	QueryResponsePrototype() Resp
}

TypedQueryMessage allows runtimes to infer a query's response type.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL