Documentation
¶
Overview ¶
Package gor provides the application-facing API for defining, registering, invoking, and persisting virtual actors.
Index ¶
- Variables
- func InstallType[T any](rt *Runtime, dispatch func(context.Context, T, string, any, any) error, ...) error
- func Now(b *Binder) time.Time
- func Ref[T any](scope Scope, key string) T
- func Register[T any](rt *Runtime, factory func(*Binder) T) error
- func TypeName[T any]() string
- type Activatable
- type Activation
- type BackgroundError
- type Binder
- type CallObservation
- type Code
- type Coded
- type Config
- type Deactivatable
- type Deactivation
- type DeactivationReason
- type ErrorSource
- type Identity
- type Invoker
- type MethodHandle
- type Option
- func OnCall(f func(CallObservation)) Option
- func OnError(f func(BackgroundError)) Option
- func WithClock(value clock.Clock) Option
- func WithEvictionInterval(value time.Duration) Option
- func WithGeneration(value string) Option
- func WithHeartbeatInterval(value time.Duration) Option
- func WithIdleTimeout(value time.Duration) Option
- func WithMailboxCapacity(value int) Option
- func WithMaxTableLatency(value time.Duration) Option
- func WithMaxTickGap(value time.Duration) Option
- func WithMemberStore(value store.MemberStore) Option
- func WithNodeAddr(value string) Option
- func WithProbeFailures(value int) Option
- func WithProbeInterval(value time.Duration) Option
- func WithProbeTimeout(value time.Duration) Option
- func WithScheduleInterval(value time.Duration) Option
- func WithScheduleStore(value store.ScheduleStore) Option
- func WithStore(value store.Store) Option
- func WithTransport(value transport.Transport) Option
- func WithViewInterval(value time.Duration) Option
- func WithVoteTTL(value time.Duration) Option
- type Runtime
- type Schedule
- type ScheduleTime
- type ScheduledInvocation
- type Scope
- type State
Constants ¶
This section is empty.
Variables ¶
ErrScheduleStoreUnavailable is returned by Schedule.Set and Schedule.Cancel when no schedule store is configured. It is a sentinel suitable for errors.Is.
Functions ¶
func InstallType ¶
func InstallType[T any](rt *Runtime, dispatch func(context.Context, T, string, any, any) error, newProxy func(Invoker, Identity) T, newCall func(string) (any, any)) error
InstallType installs the dispatch and proxy factories required for T in rt. Generated Install code calls it; application code should use the generated installer rather than hand-writing this integration seam. It returns an error when T is already installed in rt.
func Ref ¶
Ref returns a typed reference to entity T identified by key. The type must already be installed in the runtime represented by scope; otherwise Ref panics with an ErrTypeNotInstalled message. Creating a reference does not activate the entity; activation begins when a method is invoked on it.
func Register ¶
Register associates T with factory in rt. T must already be installed by generated code or InstallType; otherwise the returned error wraps ErrTypeNotInstalled. Register rejects a second registration of the same type in one runtime.
factory is called to create each activation and receives a Binder for that activation's identity. Register itself does not create an activation.
Types ¶
type Activatable ¶
Activatable is implemented by an entity that needs a hook after its state is loaded and before its first method call. An OnActivate error prevents that activation from being established and is returned by the triggering call.
type Activation ¶
type Activation = runtimepkg.Activation
type BackgroundError ¶
type BackgroundError struct {
Identity Identity
Err error
Source ErrorSource
}
BackgroundError reports a failure of an application callback that has no caller waiting for its result: a claimed scheduled invocation, or a normal deactivation hook. Identity is the affected entity, Err is the callback's error, and Source identifies which kind of callback failed.
type Binder ¶
type Binder struct {
// contains filtered or unexported fields
}
Binder is the runtime-bound context passed to an entity factory. Entity code uses the Binder to create state, schedules, and references; application code should use the supplied Binder rather than construct one.
type CallObservation ¶
CallObservation describes one invocation observed by an OnCall callback. EntityType and Method identify the call, Duration is measured with the observing Runtime's configured clock, and Err is the error returned to the caller.
For a forwarded call, the initiating Runtime reports one observation whose duration includes forwarding; the owning Runtime does not report a second observation. A remote coded error is reconstructed so errors.Is matches its Code; an opaque remote error retains only its diagnostic text.
type Code ¶
type Code string
Code is the stable identity of an application or gor framework error. A Code is also an error and can be matched with errors.Is.
const ( ErrNoOwner Code = "gor.no_owner" ErrNodeDead Code = "gor.node_dead" ErrRuntimeClosed Code = "gor.runtime_closed" ErrOverloaded Code = "gor.overloaded" ErrTypeNotInstalled Code = "gor.type_not_installed" ErrUnknownMethod Code = "gor.unknown_method" ErrInvalidRequest Code = "gor.invalid_request" ErrPersistenceConflict Code = "gor.persistence_conflict" ErrPersistenceFailed Code = "gor.persistence_failed" ErrPanic Code = "gor.panic" ErrRequestEncodeFailed Code = "gor.request_encode_failed" ErrReplyEncodeFailed Code = "gor.reply_encode_failed" ErrTransportFailed Code = "gor.transport_failed" // ErrCallCycle reports that a call targeted an entity that the same call // chain already occupies, so the call could never start. The error text // names the entities in the cycle. The cycle is detected at delivery, not // inferred from elapsed time: a slow call that is not a cycle still times // out as a plain timeout. ErrCallCycle Code = "gor.call_cycle" )
The framework Code values are a closed set. Applications must declare codes under an owner other than gor.
func CodeOf ¶
CodeOf reports the single Code reachable from err. It traverses err the way errors.Is does—the error itself, the single-value Unwrap chain, and every branch of a multi-value Unwrap—collecting every reachable Code. Exactly one reachable Code is the error's determined Code; none, or more than one, means the error has no determined Code and crosses the network as opaque text. As with errors.Is, a cyclic Unwrap is not handled.
type Coded ¶
type Coded interface {
Code() Code
}
Coded exposes the stable Code carried by an error.
type Config ¶
type Config struct {
runtimepkg.Config
Store store.Store
ScheduleStore store.ScheduleStore
ScheduleInterval time.Duration
Transport transport.Transport
OnError func(BackgroundError)
OnCall func(CallObservation)
MemberStore store.MemberStore
NodeAddr string
Generation string
HeartbeatInterval time.Duration
ViewInterval time.Duration
ProbeInterval time.Duration
ProbeTimeout time.Duration
ProbeFailures int
VoteTTL time.Duration
MaxTickGap time.Duration
MaxTableLatency time.Duration
}
Config contains the settings assembled by New from Option values. Use the provided option functions for normal configuration; custom options may inspect or modify Config directly. Omitted fields receive the defaults described by their corresponding option.
type Deactivatable ¶
type Deactivatable interface {
OnDeactivate(context.Context, DeactivationReason) error
}
Deactivatable is implemented by an entity that needs a hook when its activation leaves the active state. reason is fixed when the deactivation begins and is never rewritten. The hook receives a fresh context with no deadline that is never canceled, independent of any caller's context; a normal shutdown waits for the hook, so it must finish promptly. The hook cannot prevent deactivation. Its error is reported through OnError when configured; Kill skips this hook.
type Deactivation ¶
type Deactivation struct {
Reason DeactivationReason
}
Deactivation is the source of a failure from a normal deactivation hook. Reason is the reason of that deactivation.
type DeactivationReason ¶
type DeactivationReason = runtimepkg.DeactivationReason
DeactivationReason describes why an activation left the active state. The reason is fixed at the first transition out of active and is never rewritten by later events.
const ( // Idle reports that the activation was evicted for idleness. Idle DeactivationReason = runtimepkg.Idle // OwnershipLost reports that this node no longer owns the identity, or // the view has no active owner. OwnershipLost DeactivationReason = runtimepkg.OwnershipLost // RuntimeClosed reports that the root runtime began a normal shutdown. RuntimeClosed DeactivationReason = runtimepkg.RuntimeClosed // Faulted reports that the instance is no longer trusted: a method // panicked, or the entity requested discarding the current instance. Faulted DeactivationReason = runtimepkg.Faulted )
type ErrorSource ¶
type ErrorSource interface {
// contains filtered or unexported methods
}
ErrorSource identifies the kind of callback that produced a BackgroundError. Its unexported method seals the set: only the gor package can add sources, so application code can branch on the concrete type without a fallback.
type Identity ¶
type Identity = runtimepkg.Identity
Identity identifies an entity by its registered type name and key.
type Invoker ¶
type Invoker interface {
// Invoke invokes method for id, using the generated request in args and
// writing the generated response to reply. For a local call, ctx bounds
// activation and delivery; for a forwarded call, it bounds forwarding at
// the initiating Runtime. A forwarded call may continue on the owning
// Runtime after ctx is canceled, and errors returned from that Runtime do
// not preserve the original errors.Is or errors.As identity.
Invoke(context.Context, Identity, string, any, any) error
}
Invoker is the generated proxy call boundary. Generated code receives an Invoker from the runtime; application code normally consumes generated proxies instead of implementing Invoker.
type MethodHandle ¶ added in v0.0.2
type MethodHandle[T any] struct { // contains filtered or unexported fields }
MethodHandle names one method of T for a schedule. Build one with Handle from a method expression on T's interface; the type parameter ties the handle to the entity interface, so a handle built from another interface does not assign and cannot reach this schedule.
func Handle ¶ added in v0.0.2
func Handle[T any](m func(T, context.Context) error) MethodHandle[T]
Handle builds a MethodHandle from a method expression on T's interface, such as gor.Handle(Account.ApplyInterest). The method name is read off the expression once, at this call: reflect and runtime.FuncForPC yield the full function name, and its trailing segment is the method name. The expression must be a method expression on the interface — a hand-written closure of the same function type also compiles, but the name read off it is not a method name and delivery fails with "unknown method".
type Option ¶
type Option func(*Config)
Option configures a Runtime created by New. New applies options in argument order, then derives a schedule store when none was supplied.
func OnCall ¶
func OnCall(f func(CallObservation)) Option
OnCall sets the callback invoked after each call initiated through this Runtime, including calls that return an error and calls started by the scheduler. If omitted, no observations are produced.
The callback runs synchronously on the invoking goroutine and may be called concurrently for different calls. A forwarded call produces one observation on the initiating Runtime; the target Runtime does not produce a second observation, and the duration includes forwarding.
func OnError ¶
func OnError(f func(BackgroundError)) Option
OnError sets the callback for failures of background application callbacks: claimed scheduled invocations and normal OnDeactivate hooks. If omitted, those errors are not reported. The callback may run asynchronously and concurrently with application code; it is not called for ordinary foreground Invoke errors. A scheduled invocation whose delivery is canceled because the poller's context was canceled during shutdown is not reported. ListDue and Claim failures are not reported either. Event sources are sealed: branch on the concrete type of Source, never on method-name strings.
func WithClock ¶
WithClock sets the clock used by runtime and cluster timers. If omitted, New uses clock.Real{}.
func WithEvictionInterval ¶
WithEvictionInterval sets how often idle activations are checked. If omitted, New checks once per second. A non-positive value disables idle eviction.
func WithGeneration ¶
WithGeneration sets this node's membership generation. If omitted, the generation is the empty string; the option has no effect when clustering is disabled.
func WithHeartbeatInterval ¶
WithHeartbeatInterval sets the cluster heartbeat interval. If omitted, New uses one second; the option has no effect when clustering is disabled. When clustering is enabled, the value must be positive; a non-positive value makes New panic while creating the cluster ticker.
func WithIdleTimeout ¶
WithIdleTimeout sets how long an unused activation may remain before idle eviction. If omitted, New uses one minute. A non-positive value disables idle eviction.
func WithMailboxCapacity ¶
WithMailboxCapacity sets the number of calls that may wait in one entity's mailbox. If omitted, New allows 16 queued calls per entity; calls that cannot be queued are rejected. The value must not be negative; New panics when it creates a mailbox with a negative capacity.
func WithMaxTableLatency ¶
WithMaxTableLatency sets the maximum acceptable membership-store latency. If omitted, New uses 500 ms. A negative value makes a clustered New return an error matching cluster.ErrInvalidConfig. It has no effect when clustering is disabled.
func WithMaxTickGap ¶
WithMaxTickGap sets the maximum allowed gap between healthy cluster ticks. If omitted, New uses two seconds. A negative value makes a clustered New return an error matching cluster.ErrInvalidConfig. It has no effect when clustering is disabled.
func WithMemberStore ¶
func WithMemberStore(value store.MemberStore) Option
WithMemberStore sets the membership store used to enable clustering. If omitted, the runtime operates without cluster membership; a MemberStore must be configured together with a Transport.
func WithNodeAddr ¶
WithNodeAddr sets this node's address in cluster membership and ownership decisions. If omitted, the address is the empty string; the option has no effect when clustering is disabled.
func WithProbeFailures ¶
WithProbeFailures sets the number of failed probes required before a member is considered for a death vote. If omitted, New uses three failures. A negative value makes a clustered New return an error matching cluster.ErrInvalidConfig. It has no effect when clustering is disabled.
func WithProbeInterval ¶
WithProbeInterval sets the cluster probe interval. If omitted, New uses one second. A negative value makes a clustered New return an error matching cluster.ErrInvalidConfig. It has no effect when clustering is disabled.
func WithProbeTimeout ¶
WithProbeTimeout sets the deadline for a cluster probe. If omitted, New uses 500 ms. A negative value makes a clustered New return an error matching cluster.ErrInvalidConfig. It has no effect when clustering is disabled.
func WithScheduleInterval ¶
WithScheduleInterval sets the interval for background schedule polling. If omitted, New polls once per second. A non-positive value keeps schedules persisted but disables automatic polling.
func WithScheduleStore ¶
func WithScheduleStore(value store.ScheduleStore) Option
WithScheduleStore sets the store used for entity schedules. If omitted, New derives it from Store when Store implements ScheduleStore; otherwise schedule operations return ErrScheduleStoreUnavailable.
func WithStore ¶
WithStore sets the store used for entity state. If omitted, New uses an in-memory store; when the selected store also implements ScheduleStore and no schedule store is supplied, New uses it for schedules too.
func WithTransport ¶
WithTransport sets the transport used by a clustered runtime for serving and forwarding calls. If omitted, no transport is started; a transport must be configured together with a MemberStore.
func WithViewInterval ¶
WithViewInterval sets how often the cluster membership view is refreshed. If omitted, New uses one second; the option has no effect when clustering is disabled. When clustering is enabled, the value must be positive; a non-positive value makes New panic while creating the cluster ticker.
func WithVoteTTL ¶
WithVoteTTL sets how long a cluster suspect vote remains valid. If omitted, New uses six seconds. A negative value makes a clustered New return an error matching cluster.ErrInvalidConfig. It has no effect when clustering is disabled.
type Runtime ¶
type Runtime struct {
// contains filtered or unexported fields
}
Runtime coordinates entity registration, activation, invocation, state, and schedules. Invocations for the same identity are serialized, and a runtime configured for a cluster can route an invocation to its current owner. Create a Runtime with New and stop it with Close or Kill.
func New ¶
New creates and starts a Runtime.
By default, New uses clock.Real{}, store.NewMemory for entity state and schedules, a mailbox capacity of 16, a one-minute idle timeout, one-second eviction and schedule intervals, and one-second heartbeat and view intervals. A MemberStore and Transport must be configured together. In clustered mode, ProbeInterval, ProbeTimeout, ProbeFailures, VoteTTL, MaxTickGap, and MaxTableLatency default to one second, 500 ms, three, six seconds, two seconds, and 500 ms; a negative value returns an error matching cluster.ErrInvalidConfig.
New returns an error if cluster initialization fails. The returned Runtime is ready for entity installation and registration.
func (*Runtime) Activations ¶
func (rt *Runtime) Activations() []Activation
Activations returns a sorted snapshot of this runtime's active entities.
func (*Runtime) Close ¶
func (rt *Runtime) Close()
Close begins an orderly shutdown. It stops admitting new entity calls, lets calls already admitted finish, rejects queued calls without entering their method bodies, and then waits for in-flight methods, normal deactivation callbacks, and the runtime's own infrastructure goroutines before closing configured cluster and transport resources.
Scheduled delivery, direct Invoke, and inbound forwarded invokes all pass through the same admission gate, so all three are rejected once Close has begun. Repeated Close or Kill calls are safe and do not start another shutdown; a Kill during Close escalates to immediate shutdown semantics.
func (*Runtime) Done ¶
func (rt *Runtime) Done() <-chan struct{}
Done returns a channel that is closed when shutdown begins and the runtime stops accepting forwarded requests. It may close before Close or Kill has finished waiting for invocations, deactivation callbacks, or resources. It also closes when a clustered runtime's node is declared dead.
func (*Runtime) Invoke ¶
func (rt *Runtime) Invoke(ctx context.Context, id Identity, method string, args any, reply any) error
Invoke calls method for id, passing args and reply to the registered entity dispatch. Calls for the same identity are serialized; calls for different identities may run concurrently.
For a local call, ctx limits waiting for activation and delivery and is passed to the entity method. For a remote owner, ctx limits the forwarding operation at the initiating Runtime; canceling it does not cancel the already forwarded entity call, which may continue on the remote Runtime. An identity with no current owner returns an error matching ErrNoOwner without being forwarded. A forwarded error with a Code is reconstructed so errors.Is can match that Code; errors from an opaque error retain only text. Caller cancellation and deadline errors are returned unchanged. Once the Runtime has begun stopping, new calls are rejected at the root admission gate with a stable stop error before ownership is decided or a call is forwarded: gor.runtime_closed after Close or Kill, and gor.node_dead once the cluster has declared this node dead.
func (*Runtime) Kill ¶
func (rt *Runtime) Kill()
Kill begins an immediate shutdown. It stops admitting new entity calls, cancels the contexts of calls already running, rejects queued work, and skips deactivation callbacks. Unlike Close, Kill does not wait for user methods to return: Go cannot forcibly stop code that ignores cancellation. It is safe to call repeatedly; a Kill during Close escalates immediately.
type Schedule ¶
type Schedule[T any] struct { // contains filtered or unexported fields }
Schedule manages schedules for the entity bound to a Binder, typed to the entity's interface T. Obtain one with NewSchedule[T]; the zero value has no schedule store and its operations return ErrScheduleStoreUnavailable.
func NewSchedule ¶
NewSchedule returns a schedule manager bound to the entity represented by b and typed to its interface T.
func (Schedule[T]) Cancel ¶
Cancel asks the schedule store to delete the named schedule for the bound entity. Canceling a name that does not exist succeeds as a no-op. It returns ErrScheduleStoreUnavailable when no schedule store is configured, or the error returned by the store.
func (Schedule[T]) Set ¶
func (s Schedule[T]) Set(ctx context.Context, name string, when ScheduleTime, m MethodHandle[T]) error
Set creates or replaces the named schedule for the bound entity. m must be a Handle built from a method expression on the entity's interface; the method name is read off the handle once, here, and stored. Set does not validate that the name has a dispatch case, so a handle built from a closure rather than a method expression is stored and fails with "unknown method" when the scheduler invokes it. A successful Set persists the schedule. Each due occurrence is delivered at most once, and an invocation that returns an error is not automatically retried. Setting the same name again replaces its method and timing. Set returns ErrScheduleStoreUnavailable when no schedule store is configured, or the error returned by the store.
type ScheduleTime ¶
type ScheduleTime struct {
// contains filtered or unexported fields
}
ScheduleTime describes when a schedule first runs and whether it repeats. Its zero value is valid and is equivalent to After(0): a one-shot schedule due at the clock time used by Set.
func After ¶
func After(delay time.Duration) ScheduleTime
After returns a one-shot schedule due delay after Set uses its clock. A zero delay is due immediately; a negative delay is due in the past and is eligible on the next scheduler poll.
func Every ¶
func Every(interval time.Duration) ScheduleTime
Every returns a schedule whose first due time is interval after Set uses its clock and whose subsequent due times use the same interval when interval is positive. Every(0) is accepted and produces a one-shot schedule, just like After(0). A negative interval is also accepted and stored; it places the schedule in the past so it remains due instead of producing a future recurring deadline.
type ScheduledInvocation ¶
type ScheduledInvocation struct {
Method string
}
ScheduledInvocation is the source of a failure from a claimed scheduled invocation. Method is the entity method that was invoked.
type Scope ¶
type Scope interface {
// contains filtered or unexported methods
}
Scope is the generated-reference scope accepted by Ref. Runtime and Binder implement it; application code should pass those values rather than implement Scope.
type State ¶
type State[T any] struct { // contains filtered or unexported fields }
State is a handle to one named JSON-encoded value in an entity's persistent state record. All State handles for one entity share one JSON object, one store record, and one ETag; setting one handle rewrites the complete record. Obtain a State with NewState; the zero value is not usable.
func NewState ¶
NewState registers a named persistent value for the entity bound to b and returns its handle. The name must be unique within that entity; registering the same name twice panics. A newly registered state has its type's zero value until activation data is loaded or Set succeeds.
func (State[T]) Get ¶
func (s State[T]) Get() T
Get returns the current in-memory value without reading from the store or making a copy. If T is a map or slice, the returned value aliases the state; mutating it changes in-memory state but does not persist the change. Call Set to encode and persist a mutated value.
func (State[T]) Set ¶
Set JSON-encodes value and persists the entity's complete state record using ctx. A JSON encoding error for value or another registered state leaves the current value unchanged and is returned without a store write. Store errors leave the current in-memory value unchanged, but do not establish whether the store wrote the record; callers must not assume the write failed or retry unconditionally. Store errors are returned as well; in particular, errors.Is(err, store.ErrConflict) and errors.Is(err, ErrPersistenceConflict) report an ETag conflict. A store write failure also discards the current entity activation after the containing call completes, so the next call creates a fresh activation. On success, subsequent Get calls return value.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package clock provides injectable time sources for gor.
|
Package clock provides injectable time sources for gor. |
|
Package cluster implements gor's membership, failure detection, and ownership view for clustered runtimes.
|
Package cluster implements gor's membership, failure detection, and ownership view for clustered runtimes. |
|
cmd
|
|
|
gorgen
command
Command gorgen generates Go support code for gor entity interfaces.
|
Command gorgen generates Go support code for gor entity interfaces. |
|
gorgen/testfixture/reserved/context
Package context is a fixture whose package name collides with one of the names the generated file always imports itself.
|
Package context is a fixture whose package name collides with one of the names the generated file always imports itself. |
|
examples
|
|
|
shadow/cmd/load
command
|
|
|
shadow/cmd/shadow
command
|
|
|
internal
|
|
|
constraintcheck
command
|
|
|
Package mail provides the per-entity mailboxes gor uses to serialize calls.
|
Package mail provides the per-entity mailboxes gor uses to serialize calls. |
|
Package runtime is gor's local actor engine: it manages entity activation, lifecycle, mailboxes, and dispatch within one process.
|
Package runtime is gor's local actor engine: it manages entity activation, lifecycle, mailboxes, and dispatch within one process. |
|
Package store defines the persistence interfaces used by gor and provides in-memory and SQLite implementations.
|
Package store defines the persistence interfaces used by gor and provides in-memory and SQLite implementations. |
|
Package timer polls persisted schedules and delivers due entity calls for gor.
|
Package timer polls persisted schedules and delivers due entity calls for gor. |
|
Package transport moves opaque request and response payloads between gor runtimes.
|
Package transport moves opaque request and response payloads between gor runtimes. |