{/* AUTO-GENERATED FILE. Do not edit. Regenerate with docs/next/scripts/generate-api-docs.mts. */} {/* AI: any skill-check (vale/AI) text fixes belong in the source doc-comments under sdk/packages/go/iii (prose) or docs/next/scripts/ (structure/formatting), then regenerate. Never edit this file directly. */}
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Reference?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/iii-hq-reference-1de4f122)
<!-- generated by iii-skill-render. DO NOT EDIT (changes here are overwritten on the next render). Edit docs/next/reference/sdk-go.mdx. -->
# Go SDK
{/* AUTO-GENERATED FILE. Do not edit. Regenerate with docs/next/scripts/generate-api-docs.mts. */}
{/* AI: any skill-check (vale/AI) text fixes belong in the source doc-comments under sdk/packages/go/iii (prose) or docs/next/scripts/ (structure/formatting), then regenerate. Never edit this file directly. */}
## Installation
```bash
go get github.com/iii-hq/iii/sdk/packages/go/iii@latest
```
## Initialization
### RegisterWorker
RegisterWorker creates a `Client` for the engine at url and starts the connection lifecycle in the background, returning immediately. An empty url means `EngineURLFromEnv`, as with `New`. It is the idiomatic entry point, matching registerWorker in the Node SDK and register_worker in the Rust SDK. Register functions and observers on the returned client; they are (re)sent on each connection. Call `Client.Close` to stop.
To wait for the first connection (or fail fast on a bad URL), call `Client.Connect` instead of (or after) RegisterWorker; it blocks until connected, ctx is done, or the reconnect budget is exhausted. Use `New` if you want to build a client without starting the connection.
**Signature**
```go
func RegisterWorker(url string, opts ...Option) *Client
```
<Tabs>
<Tab title="Parameters">
<ParamField body="url" type="string" required>
</ParamField>
<ParamField body="opts" type="...Option">
<Expandable title="`Option` fields">
<ParamField body="WithDescription" type="func(description string) Option" required>
WithDescription sets a one-line, human/LLM-readable summary of what this worker does. Surfaces in engine::workers::list / engine::workers::info.
</ParamField>
<ParamField body="WithHeaders" type="func(h http.Header) Option" required>
WithHeaders sets HTTP headers sent on the WebSocket handshake of the main connection and of the stream sockets of this client (see `InputStream` and `OutputStream`). The III_TOKEN environment variable, when set and not blank, adds "Authorization: Bearer <token>" unless h already carries an Authorization header.
</ParamField>
<ParamField body="WithInvocationTimeout" type="func(d time.Duration) Option" required>
WithInvocationTimeout sets how long `Client.Call` waits for a result when `CallRequest`.Timeout is zero, in place of `DefaultInvocationTimeout`. It is the invocationTimeoutMs option of the Node SDK's registerWorker. A d of zero or less keeps the default.
</ParamField>
<ParamField body="WithMetricsReporting" type="func(enabled bool) Option" required>
WithMetricsReporting turns the worker resource gauges on or off (Node enableMetricsReporting): the iii.worker.memory.\*, iii.worker.cpu.\*, iii.worker.event_loop.lag_ms and iii.worker.uptime_seconds metrics, tagged with worker.id and worker.name. The default is true. The gauges start when the engine acknowledges the worker and stop when the connection drops; they need telemetry and its metrics to be enabled (see `OtelConfig`).
</ParamField>
<ParamField body="WithName" type="func(name string) Option" required>
WithName sets the worker name reported to the engine. A non-empty III_WORKER_NAME takes precedence. The default is "hostname:pid".
</ParamField>
<ParamField body="WithNamespace" type="func(namespace string) Option" required>
WithNamespace sets the namespace this worker registers into. Takes precedence over the III_NAMESPACE environment variable.
</ParamField>
<ParamField body="WithOtel" type="func(cfg OtelConfig) Option" required>
WithOtel configures the client's OpenTelemetry pipeline (the otel option of Node registerWorker). Telemetry starts with the connection lifecycle (`RegisterWorker` or `Client.Connect`) and `Client.Close` flushes and stops it. Without this option the defaults documented on `OtelConfig` apply, and they enable telemetry.
</ParamField>
<ParamField body="WithReconnectConfig" type="func(c ReconnectConfig) Option" required>
WithReconnectConfig overrides the default reconnect schedule.
</ParamField>
<ParamField body="WithTelemetry" type="func(t TelemetryOptions) Option" required>
WithTelemetry sets what the worker reports about its language, project and framework on every connection. Blank fields keep their defaults (see `TelemetryOptions`).
</ParamField>
</Expandable>
</ParamField>
</Tab>
<Tab title="Example">
```go
client := iii.RegisterWorker(iii.DefaultEngineURL) // ws://127.0.0.1:49134
greet, err := client.RegisterFunction("hello::greet", func(ctx context.Context, data json.RawMessage) (any, error) {
var req struct {
Body struct {
Name string `json:"name"`
} `json:"body"`
}
if err := json.Unmarshal(data, &req); err != nil {
return nil, err
}
return map[string]any{
"status_code": 200,
"body": map[string]string{"message": "Hello, " + req.Body.Name + "!"},
}, nil
})
if err != nil {
log.Fatal(err)
}
if _, err := client.Observe(iii.Source{
FunctionID: "http::on-request",
Args: iii.Args{"method": "POST", "path": "/greet"},
}, greet.ID); err != nil {
log.Fatal(err)
}
if err := client.Connect(context.Background()); err != nil {
log.Fatal(err)
}
defer client.Close()
```
</Tab>
</Tabs>
## Methods
### Client.RegisterFunction
RegisterFunction registers a function this worker can handle and returns its handle; `FunctionRef.Unregister` removes it. It may be called before or after Connect; the registration is sent on the next (re)connect. As in the Node, Python and Rust SDKs, an empty id is refused ("id is required") and so is an id this client already registered ("function id already registered"): to replace a function, unregister it first. Pass a single `RegisterFunctionOptions` value for a description, request and response formats, metadata, args_format, private, observable or the local dispatch setting.
The handler's return value is what observers observe. Every call of the function, local or routed, runs the handler and is then delivered to the observers that want it (`Client.OnObservationMatchFor`; by default all of them): by the function's deliver hook (`Client.OnObservationDeliverFor`), or by iii, to those whose capture and filters match. Set hooks by id before registering: the SDK acks no observer before RegisterFunction returns, but a hook set on the returned handle can miss observers already accepted, and is caught up for them.
Handlers read the optional per-invocation metadata sidecar from their ctx with `MetadataFromContext`.
**Signature**
```go
func (c *Client) RegisterFunction(id string, handler Handler, opts ...RegisterFunctionOptions) (*FunctionRef, error)
```
<Tabs>
<Tab title="Parameters">
<ParamField body="id" type="string" required>
</ParamField>
<ParamField body="handler" type="Handler" required>
</ParamField>
<ParamField body="opts" type="...RegisterFunctionOptions">
<Expandable title="`RegisterFunctionOptions` fields">
<ParamField body="Metadata" type="json.RawMessage">
Metadata is arbitrary JSON attached to the function registration. It is stored with the function and is distinct from the per-invocation metadata passed to handlers.
</ParamField>
<ParamField body="LocalDispatch" type="*bool">
LocalDispatch false keeps every Call of this function on the engine path; nil or true lets Call run it in-process once the engine confirms it (see `Client.Call`: observers see snapshots of the payload and metadata taken at call start, and a handler may outlive a caller whose deadline passed).
</ParamField>
<ParamField body="Description" type="string">
Description is a human/LLM-readable summary of the function, sent as "description" and surfaced by engine::functions::list and engine::functions::info. Empty omits it.
</ParamField>
<ParamField body="RequestFormat" type="json.RawMessage">
RequestFormat is the JSON Schema of the function's request, sent as "request_format". It must be valid JSON; nil omits it. With `RegisterFunctionTyped` it replaces the schema inferred from Req.
</ParamField>
<ParamField body="ResponseFormat" type="json.RawMessage">
ResponseFormat is the JSON Schema of the function's response, sent as "response_format": the handler's return value, which is what observers observe. It must be valid JSON; nil omits it. With `RegisterFunctionTyped` it replaces the schema inferred from Resp.
</ParamField>
<ParamField body="ArgsFormat" type="json.RawMessage">
ArgsFormat is the JSON Schema of the observers' args, sent as "args_format": the engine validates every observer's args against it (INVALID_ARGS), and refuses a schema that is not valid (INVALID_ARGS_FORMAT). It must be valid JSON; nil means the function takes no args.
</ParamField>
<ParamField body="Private" type="bool">
Private lets only this worker call the function (the engine answers anyone else with FORBIDDEN); other workers may observe it, and it cannot be an observer's target. A call this worker makes to it passes the input and the result by reference: the handler and the hooks treat both as read-only.
</ParamField>
<ParamField body="Observable" type="*bool">
Observable false refuses every observer of the function (NOT_OBSERVABLE), for a function whose payloads carry credentials. nil means true.
</ParamField>
</Expandable>
</ParamField>
</Tab>
<Tab title="Example">
```go
client := iii.New(iii.DefaultEngineURL)
handler := func(ctx context.Context, data json.RawMessage) (any, error) {
return map[string]any{"ok": true}, nil
}
client.RegisterFunction("orders::create", handler, iii.RegisterFunctionOptions{
Metadata: json.RawMessage(`{"owner":"billing-team","priority":"high"}`),
})
```
</Tab>
</Tabs>
---
### Client.Call
Call invokes a function. With the default (nil) or an enqueue action it waits for the matching invocation result and returns it, mapping a remote error to `InvocationError` and a missed deadline to `ErrTimeout`. With a `VoidAction` it is fire-and-forget and returns immediately with a nil result. With `CallRequest`.Observer it calls through that observer.
ctx bounds the wait independently of `CallRequest.Timeout`: if ctx is cancelled first, its error is returned and the pending entry is reclaimed. Inside a handler or a deliver hook, pass its ctx: the call then carries that invocation as its caller (and the observe depth), which observers' filters and the engine's loop guard read.
A function this worker hosts runs in-process, without touching the wire, once the engine confirmed it for local dispatch, unless the action is enqueue or Dispatch is `DispatchRemote`. The handler gets its own copy of the payload and the caller its own encoding of the result, except for a `RegisterFunctionOptions`.Private function, whose input and result pass by reference; errors and timeouts look as on the remote path. The call is delivered to the function's observers as a routed one is, from snapshots of the payload and metadata taken when it started. The handler runs on a goroutine of its own, so the caller always returns on its Timeout or ctx deadline, even when the handler blocks and ignores its ctx; the handler then runs to completion (as a remote one would on its worker), its result is discarded, and the call is still counted and delivered. A handler that can block for long should honor its ctx (cancelled on Close), or opt out with `RegisterFunctionOptions`.LocalDispatch.
**Signature**
```go
func (c *Client) Call(ctx context.Context, req CallRequest) (json.RawMessage, error)
```
<Tabs>
<Tab title="Parameters">
<ParamField body="ctx" type="context.Context" required>
</ParamField>
<ParamField body="req" type="CallRequest" required>
<Expandable title="`CallRequest` fields">
<ParamField body="FunctionID" type="string">
FunctionID is the function to invoke (e.g. an EngineFunctions constant). Empty with Observer.
</ParamField>
<ParamField body="Observer" type="*Observer">
Observer calls through an observer of a function this worker hosts: the engine runs the observer's target with Payload as given, after checking that this worker hosts the observer's function (NOT_FUNCTION_OWNER) and that the observer exists and is active (OBSERVER_NOT_FOUND, OBSERVER_NOT_ACTIVE), and applies its policy (max_fires, expiry, max_in_flight: OVERFLOW), metadata sidecar and loop guard. The call goes out on the current connection, after the acks already sent on it; FunctionID, Namespace and an enqueue action do not apply. It takes no Metadata: the target's metadata is the observer's registration metadata, and Call refuses a request with Metadata before anything is sent. A call through an observer belongs in the function's `DeliverHook`, which applies the observer's filters with `Observer.Matches`; to send one observer something outside delivery (its initial state), call the function with metadata \{"for_observer": <obs.ID>\} (see `Observer.Accepted`).
</ParamField>
<ParamField body="Payload" type="json.RawMessage">
Payload is the JSON input of the function (payload in the Node, Python and Rust SDKs). Nil is sent as \{\}.
</ParamField>
<ParamField body="Data" type="json.RawMessage">
**Deprecated.** Use Payload. Data is the JSON input of the function, used only when Payload is nil.
</ParamField>
<ParamField body="Metadata" type="json.RawMessage">
Metadata is optional per-invocation metadata (any JSON value) sent alongside the payload on the wire's metadata channel, not folded into it. nil and JSON null are no metadata: omitted, and the handler's MetadataFromContext reports none.
</ParamField>
<ParamField body="Action" type="*CallAction">
Action selects void/enqueue semantics; nil means the default await path.
</ParamField>
<ParamField body="Timeout" type="time.Duration">
Timeout bounds an await/enqueue call. Zero means the client's invocation timeout: `WithInvocationTimeout`, else `DefaultInvocationTimeout`.
</ParamField>
<ParamField body="Namespace" type="string">
Namespace routes the invocation to a specific namespace. Empty means this worker's namespace, except engine::\* and configuration::\* builtins, which resolve in the engine's default namespace.
</ParamField>
<ParamField body="Dispatch" type="Dispatch">
Dispatch selects the path to a function this worker hosts: the zero value (or `DispatchAuto`) runs it in-process once the engine confirmed it for local dispatch; `DispatchRemote` always goes through the engine.
</ParamField>
</Expandable>
</ParamField>
</Tab>
<Tab title="Example">
```go
client := iii.RegisterWorker(iii.DefaultEngineURL)
defer client.Close()
res, err := client.Call(context.Background(), iii.CallRequest{
FunctionID: "orders::create",
Payload: json.RawMessage(`{"item":"widget"}`),
})
switch {
case errors.Is(err, iii.ErrTimeout):
fmt.Println("timed out")
case err != nil:
var ie *iii.InvocationError
if errors.As(err, &ie) {
fmt.Println("remote error:", ie.Code)
}
default:
fmt.Printf("result: %s\n", res)
}
```
</Tab>
</Tabs>
---
### Client.Observe
Observe observes a function: when source.FunctionID runs, target runs, for every call that the function's worker delivers to the observer and that passes source.Filters. target is a function registered by some worker (until it is, the observer stays pending). source.Args go to the worker that hosts the function, which reads them in its hooks (a route, a table).
It returns the handle immediately, even before the connection is up; the observer is replayed with the same id on every reconnect. Errors from the engine (INVALID_ARGS, INVALID_FILTER, FORBIDDEN, NOT_OBSERVABLE, SELF_TARGET, the host's rejection, and UNSUPPORTED against an engine without observe) show up as state error and fail `ObserverHandle.Ready`. An observeresult in state error is the engine's refusal of that observe and the handle's final answer: the engine holds no observer for it (it stores nothing for a refused observe, and disposes an observer it holds in error as it answers that observer's replay), the handle is not sent again on a later connection, and its Dispose sends nothing. An observer that turns error after its observe was answered (the host's rejection, OWNER_TIMEOUT) is held by the engine: the handle is replayed, and its Dispose unobserves it. The returned error is for a request that cannot be sent at all: a missing function or target, a blank namespace, args or filters that are not JSON, and an id a handle of this client holds. A handle holds its id until it is disposed (by `ObserverHandle.Dispose` or by the engine); an Observe of a held id sends nothing, leaves the holder alone and returns an \*ObserveRejectionError with code OBSERVER_ID_CONFLICT. Once the holder is disposed the id is free at once. An observer without MaxFires or ExpiresIn that the engine disposed while this worker was away past its grace period (OBSERVER_DISCONNECTED) is not reported disposed: the handle observes again, with the same id, as a new observer (pending, then the engine's answer).
**Signature**
```go
func (c *Client) Observe(source Source, target string, opts ...ObserverOptions) (*ObserverHandle, error)
```
<Tabs>
<Tab title="Parameters">
<ParamField body="source" type="Source" required>
<Expandable title="`Source` fields">
<ParamField body="FunctionID" type="string" required>
FunctionID is the observed function.
</ParamField>
<ParamField body="Namespace" type="string">
Namespace defaults to this worker's (engine::\* and configuration::\* resolve to the engine's default namespace).
</ParamField>
<ParamField body="Args" type="Args" required>
Args go to the worker that hosts the function, which reads them in its hooks (a cron expression, a route, a table). A function without args_format takes none.
</ParamField>
<ParamField body="Filters" type="Filters">
Filters decide which calls reach the target; nil matches every call.
</ParamField>
<ParamField body="Capture" type="[]Capture">
Capture is what the target's payload carries, and with it which outcomes fire the target. nil means the default (input, output, caller), which fires on success. Input and output fire on success, error fires on error; caller and metadata only add to the payload, so a non-empty Capture must name at least one of input, output, error (INVALID_ARGS otherwise). An empty, non-nil slice fires on success with the top-level fields only. \{error, caller\} fires on errors, \{input, error\} on both.
</ParamField>
</Expandable>
</ParamField>
<ParamField body="target" type="string" required>
</ParamField>
<ParamField body="opts" type="...ObserverOptions">
<Expandable title="`ObserverOptions` fields">
<ParamField body="ID" type="string">
ID defaults to a random UUID, stable across replays.
</ParamField>
<ParamField body="MaxFires" type="uint64" required>
MaxFires disposes the observer after this many activations.
</ParamField>
<ParamField body="ExpiresIn" type="time.Duration" required>
ExpiresIn disposes the observer after this long (millisecond precision).
</ParamField>
<ParamField body="MaxInFlight" type="uint64" required>
MaxInFlight bounds the observer's concurrent activations.
</ParamField>
<ParamField body="Metadata" type="json.RawMessage">
Metadata is delivered as the metadata sidecar of every activation (a JSON object).
</ParamField>
<ParamField body="TargetNamespace" type="string">
TargetNamespace is the namespace of the target function; it defaults to this worker's.
</ParamField>
</Expandable>
</ParamField>
</Tab>
<Tab title="Example">
```go
client.RegisterFunction("alerts::payment-failed", notify)
failures, err := client.Observe(iii.Source{
FunctionID: "payments::charge",
Capture: []iii.Capture{iii.CaptureError, iii.CaptureCaller}, // fires on errors only
Filters: iii.Filters{"input.amount": iii.Op{"$gte": 500}},
}, "alerts::payment-failed")
if err == nil {
err = failures.Ready(ctx)
}
```
</Tab>
</Tabs>
---
### Client.Trigger
<Warning>
**Deprecated.** Use `Client.Call`.
</Warning>
Trigger is `Client.Call` under its 0.25 name.
**Signature**
```go
func (c *Client) Trigger(ctx context.Context, req TriggerRequest) (json.RawMessage, error)
```
#### Parameters
<ParamField body="ctx" type="context.Context" required>
</ParamField>
<ParamField body="req" type="TriggerRequest" required>
</ParamField>
---
### Client.AddConnectionStateListener
AddConnectionStateListener calls listener with the current `ConnectionState`, then with every later change of state (`StateConnecting`, `StateConnected`, `StateReconnecting`, `StateDisconnected`, `StateFailed`), in the order the changes happen. Calls are made one at a time on a goroutine of the client's own, never on the subscribing goroutine or on the SDK's read loop, so a listener may call any Client method; it should return promptly, since later changes wait for it. A state is reported once per change: the same state is never delivered twice in a row. A listener that panics is logged and keeps its subscription.
It returns the function that unsubscribes listener: changes not yet delivered when it returns are dropped for this listener (a call already under way completes). Calling it more than once does nothing. It mirrors addConnectionStateListener in the browser SDK and add_connection_state_listener in the Python SDK.
**Signature**
```go
func (c *Client) AddConnectionStateListener(listener func(ConnectionState)) (unsubscribe func())
```
#### Parameters
<ParamField body="listener" type="func(ConnectionState)" required>
<Expandable title="`ConnectionState` fields">
<ParamField body="StateDisconnected" type="'disconnected'" required>
</ParamField>
<ParamField body="StateConnecting" type="'connecting'" required>
</ParamField>
<ParamField body="StateConnected" type="'connected'" required>
</ParamField>
<ParamField body="StateReconnecting" type="'reconnecting'" required>
</ParamField>
<ParamField body="StateFailed" type="'failed'" required>
</ParamField>
</Expandable>
</ParamField>
---
### Client.Address
Address returns the engine WebSocket base URL this client dials (e.g. "ws://127.0.0.1:49134"): the url given to `New` or `RegisterWorker`, else `EngineURLFromEnv`. Channel readers/writers build their own URLs from it.
**Signature**
```go
func (c *Client) Address() string
```
---
### Client.Close
Close shuts the client down at once: it stops the reconnect loop, gives buffered observe reports and telemetry a short, fixed time to go out (250ms for the reports, at most 10s for the telemetry flush), cancels all pending calls with ErrNotConnected, and drops the socket without a closing handshake. It does not send unregister frames (matching the reference SDKs). Use `Client.Shutdown` to wait for the flushes under a deadline of your own and close the socket gracefully.
Close is idempotent and implements io.Closer; it always returns nil. Called while a Shutdown runs, it cuts that Shutdown short (as http.Server.Close does) and returns once it has finished.
**Signature**
```go
func (c *Client) Close() error
```
---
### Client.Connect
Connect starts the connection lifecycle (if not already started) and blocks until the first connection is established, ctx is cancelled, or the reconnect budget is exhausted. The supervisor goroutine then keeps the connection alive (reconnecting with backoff) until Close. Connect is safe to call multiple times and from multiple goroutines; only one supervisor ever runs.
**Signature**
```go
func (c *Client) Connect(ctx context.Context) error
```
#### Parameters
<ParamField body="ctx" type="context.Context" required>
</ParamField>
---
### Client.ConnectionState
ConnectionState returns the current state of the connection to the engine. It mirrors getConnectionState in the Node SDK; `Client.AddConnectionStateListener` reports every change.
**Signature**
```go
func (c *Client) ConnectionState() ConnectionState
```
---
### Client.FatalError
FatalError returns the terminal registration rejection that stopped this worker, or nil while healthy. Mirrors the Node/Python/Rust SDKs' fatal-error accessors.
**Signature**
```go
func (c *Client) FatalError() error
```
---
### Client.IsObserved
IsObserved reports whether functionID, registered by this worker, has active observers, so a source can skip building an event nobody wants. It takes no lock: a lookup of functionID and one atomic load. `FunctionRef.IsObserved` is the load alone.
**Signature**
```go
func (c *Client) IsObserved(functionID string) bool
```
#### Parameters
<ParamField body="functionID" type="string" required>
</ParamField>
---
### Client.IsObservedFor
IsObservedFor reports whether call of functionID, registered by this worker, would reach an observer. On a function matched by keys (`MatchKeys`) it is true when an observer is filed under one of the call's keys (one lookup per key); on any other function call is ignored, and it is `Client.IsObserved`. Set what the keys read (Input, Metadata).
**Signature**
```go
func (c *Client) IsObservedFor(functionID string, call *Call) bool
```
#### Parameters
<ParamField body="functionID" type="string" required>
</ParamField>
<ParamField body="call" type="*Call" required>
<Expandable title="`Call` fields">
<ParamField body="FunctionID" type="string" required>
</ParamField>
<ParamField body="InvocationID" type="string" required>
</ParamField>
<ParamField body="Status" type="string">
Status is "success" or "error". Empty reads as "error" when Error is set, and "success" otherwise.
</ParamField>
<ParamField body="Input" type="json.RawMessage">
Input is the call's input, as the handler received it.
</ParamField>
<ParamField body="Output" type="json.RawMessage">
Output is the handler's return value as JSON: what observers observe. Nil on an error.
</ParamField>
<ParamField body="Error" type="*ErrorBody">
Error is the error the handler returned. Nil on success.
</ParamField>
<ParamField body="Caller" type="*Caller">
Caller is who made the call; nil for a call made outside any handler.
</ParamField>
<ParamField body="Metadata" type="json.RawMessage">
Metadata is the call's metadata sidecar; nil when it carries none.
</ParamField>
</Expandable>
</ParamField>
---
### Client.LocalDispatchActive
LocalDispatchActive reports whether Call runs functionID in-process: it is registered here, the engine confirmed it with local_dispatch, and RegisterFunctionOptions.LocalDispatch did not opt out.
**Signature**
```go
func (c *Client) LocalDispatchActive(functionID string) bool
```
#### Parameters
<ParamField body="functionID" type="string" required>
</ParamField>
---
### Client.ObserveFunction
ObserveFunction observes functionID with target, every call and the observer defaults: `Client.Observe` with Source\{FunctionID: functionID\}.
**Signature**
```go
func (c *Client) ObserveFunction(functionID, target string, opts ...ObserverOptions) (*ObserverHandle, error)
```
<Tabs>
<Tab title="Parameters">
<ParamField body="functionID" type="string" required>
</ParamField>
<ParamField body="target" type="string" required>
</ParamField>
<ParamField body="opts" type="...ObserverOptions">
<Expandable title="`ObserverOptions` fields">
<ParamField body="ID" type="string">
ID defaults to a random UUID, stable across replays.
</ParamField>
<ParamField body="MaxFires" type="uint64" required>
MaxFires disposes the observer after this many activations.
</ParamField>
<ParamField body="ExpiresIn" type="time.Duration" required>
ExpiresIn disposes the observer after this long (millisecond precision).
</ParamField>
<ParamField body="MaxInFlight" type="uint64" required>
MaxInFlight bounds the observer's concurrent activations.
</ParamField>
<ParamField body="Metadata" type="json.RawMessage">
Metadata is delivered as the metadata sidecar of every activation (a JSON object).
</ParamField>
<ParamField body="TargetNamespace" type="string">
TargetNamespace is the namespace of the target function; it defaults to this worker's.
</ParamField>
</Expandable>
</ParamField>
</Tab>
<Tab title="Example">
```go
client := iii.RegisterWorker(iii.DefaultEngineURL)
defer client.Close()
client.RegisterFunction("alerts::new-order", func(ctx context.Context, data json.RawMessage) (any, error) {
var event iii.Observed
if err := json.Unmarshal(data, &event); err != nil {
return nil, err
}
log.Printf("order created: %s", event.Output)
return nil, nil
})
if _, err := client.ObserveFunction("orders::create", "alerts::new-order"); err != nil {
log.Fatal(err)
}
```
</Tab>
</Tabs>
---
### Client.Observers
Observers returns the active observers of functionID, registered by this worker, as its host sees them.
**Signature**
```go
func (c *Client) Observers(functionID string) []*Observer
```
#### Parameters
<ParamField body="functionID" type="string" required>
</ParamField>
---
### Client.OnObservationDeliverFor
OnObservationDeliverFor sets the hook that delivers each call of functionID itself; nil restores iii's delivery, which delivers each call to every matched observer whose capture and filters accept it, and gives the caller the handler's result. It is stored by id, as `Client.OnObserverAddedFor` is. A function with a deliver hook needs an engine with observe.v2: against an older one it stays unregistered, and the SDK logs UNSUPPORTED once. A deliver hook does not run for a function registered with `Client.RegisterHTTPFunction`: the engine delivers its calls. It returns the client, for chaining.
**Signature**
```go
func (c *Client) OnObservationDeliverFor(functionID string, hook DeliverHook) *Client
```
<Tabs>
<Tab title="Parameters">
<ParamField body="functionID" type="string" required>
</ParamField>
<ParamField body="hook" type="DeliverHook" required>
</ParamField>
</Tab>
<Tab title="Example">
```go
client := iii.RegisterWorker(iii.DefaultEngineURL)
defer client.Close()
commandOf := func(call *iii.Call) string {
var req struct {
Command string `json:"command"`
}
_ = json.Unmarshal(call.Input, &req)
return req.Command
}
client.OnObservationMatchFor("chat::on-command", iii.MatchFunc(func(obs *iii.Observer, call *iii.Call) bool {
return obs.Args["command"] == commandOf(call)
}))
client.OnObservationDeliverFor("chat::on-command", func(ctx context.Context, call *iii.Call, observers []*iii.Observer) (any, error) {
if len(observers) == 0 {
return map[string]string{"reply": "unknown command /" + commandOf(call)}, nil
}
obs := observers[0]
if !obs.Matches(call) {
return map[string]string{"reply": "/" + commandOf(call) + " is not available"}, nil
}
// what this hook returns is what the caller gets back
return client.Call(ctx, iii.CallRequest{Observer: obs, Payload: call.Input})
})
if _, err := client.RegisterFunction("chat::on-command", iii.Identity, iii.FunctionOptions{
ArgsFormat: json.RawMessage(`{"type":"object","required":["command"],"properties":{"command":{"type":"string"}}}`),
Private: true,
}); err != nil {
log.Fatal(err)
}
```
</Tab>
</Tabs>
---
### Client.OnObservationMatchFor
OnObservationMatchFor sets which observers want each call of functionID: `MatchFunc` or `MatchKeys`; nil restores the default, where every observer wants every call. It is stored by id, as `Client.OnObserverAddedFor` is. A match hook set on a registered function takes effect on the function's hook queue, after the hooks queued before it, and calls use the previous one until then. A hook by keys set while the function has active observers rebuilds the index from them; an observer whose keys panic is late-rejected with OBSERVE_REJECTED. A function with a match hook needs an engine with observe.v2: against an older one it stays unregistered, and the SDK logs UNSUPPORTED once. It returns the client, for chaining.
**Signature**
```go
func (c *Client) OnObservationMatchFor(functionID string, m *MatchHook) *Client
```
#### Parameters
<ParamField body="functionID" type="string" required>
</ParamField>
<ParamField body="m" type="*MatchHook" required>
<Expandable title="`MatchHook` fields">
<ParamField body="MatchFunc" type="func(predicate func(obs *Observer, call *Call) bool) *MatchHook" required>
MatchFunc is a match hook that asks predicate, once per active observer per call, whether the observer wants the call. A predicate that panics counts as no match, and the SDK logs it once per function. A nil predicate gives a nil MatchHook.
</ParamField>
<ParamField body="MatchKeys" type="func(observerKeys func(obs *Observer) []string, callKeys func(call *Call) []string) *MatchHook" required>
MatchKeys is a match hook by keys: an observer wants a call when they share a key, and the SDK keeps an index of the active observers by key instead of asking each of them. observerKeys says what an observer listens for: the SDK computes it once, when the observer is accepted, files the observer under each key and unfiles it when it is removed. An observer whose observerKeys panics is rejected with OBSERVE_REJECTED. callKeys says what a call is: the call matches the observers filed under any of its keys, each once; a callKeys that panics matches nothing, and the SDK logs it once per function. Keys express wildcards by listing them: an observer of every table is filed under "primary|\*|insert", and a change matches "primary|orders|insert", "primary|orders|\*", "primary|\*|insert" and "primary|\*|\*". A nil function gives a nil MatchHook.
</ParamField>
</Expandable>
</ParamField>
---
### Client.OnObserverAdded
OnObserverAdded sets the hook that runs when an observer is added to any function this worker hosts, before the function's own; nil removes it. A hook set while functions have active observers runs for each of them at once (see `Client.OnObserverAddedFor`). It returns the client, for chaining.
**Signature**
```go
func (c *Client) OnObserverAdded(hook AddedHook) *Client
```
#### Parameters
<ParamField body="hook" type="AddedHook" required>
</ParamField>
---
### Client.OnObserverAddedFor
OnObserverAddedFor sets the hook that runs when an observer is added to functionID, after the worker's; nil removes it. Hooks are stored by function id: set them before RegisterFunction, so they run for every observer, and they stay across `FunctionRef.Unregister` and a later registration of the id.
A hook set once the function already has active observers is caught up: it runs for each of them at once, an error late-rejects that observer, and the SDK logs one warning naming the function and how many observers were active without it. It returns the client, for chaining.
**Signature**
```go
func (c *Client) OnObserverAddedFor(functionID string, hook AddedHook) *Client
```
#### Parameters
<ParamField body="functionID" type="string" required>
</ParamField>
<ParamField body="hook" type="AddedHook" required>
</ParamField>
---
### Client.OnObserverRemoved
OnObserverRemoved sets the hook that runs when an observer is removed from any function this worker hosts, after the function's own; nil removes it. It returns the client, for chaining.
**Signature**
```go
func (c *Client) OnObserverRemoved(hook RemovedHook) *Client
```
#### Parameters
<ParamField body="hook" type="RemovedHook" required>
</ParamField>
---
### Client.OnObserverRemovedFor
OnObserverRemovedFor sets the hook that runs when an observer is removed from functionID, before the worker's; nil removes it. It is stored by function id, as `Client.OnObserverAddedFor` is. It returns the client, for chaining.
**Signature**
```go
func (c *Client) OnObserverRemovedFor(functionID string, hook RemovedHook) *Client
```
#### Parameters
<ParamField body="functionID" type="string" required>
</ParamField>
<ParamField body="hook" type="RemovedHook" required>
</ParamField>
---
### Client.Pipe
Pipe creates a pipe on the engine and returns its two ends: put one in a call payload (or a handler result) and use the other here. This worker owns the pipe: it must stay connected until the other side attached to its end, or the engine drops it.
Most code does not need it: a stream built with `InputStreamFromReader`, `InputStreamFromBytes` or `OutputStreamToWriter` gets its pipe from the SDK. Use a pipe for a stream handed out before its data exists, a stream given to a call made later, a two-way session (two pipes), or a reader that needs the messages too (a sink takes bytes only).
**Signature**
```go
func (c *Client) Pipe(ctx context.Context) (*InputStream, *OutputStream, error)
```
<Tabs>
<Tab title="Parameters">
<ParamField body="ctx" type="context.Context" required>
</ParamField>
</Tab>
<Tab title="Example">
```go
input, output, err := worker.Pipe(ctx)
if err != nil { return err }
payload, _ := json.Marshal(map[string]any{"prompt": "Summarize report r-42", "tokens": output})
done := make(chan error, 1)
go func() {
_, err := worker.Call(ctx, iii.CallRequest{FunctionID: "llm::complete", Payload: payload})
done <- err
}()
for msg, err := range input.Messages(ctx) { ... }
return <-done
```
</Tab>
</Tabs>
---
### Client.RegisterHTTPFunction
<Warning>
**Deprecated.** HTTP-invoked functions (iii-http-functions) will be removed in an upcoming release; behavior is unchanged for now. Register a handler that makes the HTTP call instead. Migration guide: [https://iii.dev/docs/upgrading/migrate-from-http-functions](https://iii.dev/docs/upgrading/migrate-from-http-functions).
</Warning>
RegisterHTTPFunction registers a function that has no handler in this process: the engine invokes it by sending an HTTP request as described by invocation, which travels as the registration's "invocation" field. invocation.URL is required; an empty Method means POST, as in the Node SDK. invocation.Auth, when set, must be valid JSON; build it with `HMACAuth`, `BearerAuth` or `APIKeyAuth`. Pass at most one `RegisterFunctionOptions` for the description, formats, metadata, args_format, private or observable; LocalDispatch does not apply, since there is nothing to run in-process. The engine delivers the function's calls itself, so a deliver hook does not run for it; the added and removed hooks do.
Like every registration it is kept in memory and sent again on each reconnect. An empty id, or one this client already registered, is refused as in `Client.RegisterFunction`; `FunctionRef.Unregister` on the returned handle removes it.
**Signature**
```go
func (c *Client) RegisterHTTPFunction(id string, invocation HTTPInvocationRef, opts ...RegisterFunctionOptions) (*FunctionRef, error)
```
#### Parameters
<ParamField body="id" type="string" required>
</ParamField>
<ParamField body="invocation" type="HTTPInvocationRef" required>
<Expandable title="`HTTPInvocationRef` fields">
<ParamField body="URL" type="string" required>
URL is the endpoint the engine calls. Required.
</ParamField>
<ParamField body="Method" type="string">
Method is the HTTP method (GET, POST, PUT, PATCH or DELETE). RegisterHTTPFunction sends POST when it is empty.
</ParamField>
<ParamField body="TimeoutMs" type="*uint64">
TimeoutMs bounds each request, in milliseconds; nil uses the engine default.
</ParamField>
<ParamField body="Headers" type="map[string]string">
Headers are sent with every request.
</ParamField>
<ParamField body="Auth" type="json.RawMessage">
Auth is how the engine authenticates its requests; nil sends none.
</ParamField>
</Expandable>
</ParamField>
<ParamField body="opts" type="...RegisterFunctionOptions">
<Expandable title="`RegisterFunctionOptions` fields">
<ParamField body="Metadata" type="json.RawMessage">
Metadata is arbitrary JSON attached to the function registration. It is stored with the function and is distinct from the per-invocation metadata passed to handlers.
</ParamField>
<ParamField body="LocalDispatch" type="*bool">
LocalDispatch false keeps every Call of this function on the engine path; nil or true lets Call run it in-process once the engine confirms it (see `Client.Call`: observers see snapshots of the payload and metadata taken at call start, and a handler may outlive a caller whose deadline passed).
</ParamField>
<ParamField body="Description" type="string">
Description is a human/LLM-readable summary of the function, sent as "description" and surfaced by engine::functions::list and engine::functions::info. Empty omits it.
</ParamField>
<ParamField body="RequestFormat" type="json.RawMessage">
RequestFormat is the JSON Schema of the function's request, sent as "request_format". It must be valid JSON; nil omits it. With `RegisterFunctionTyped` it replaces the schema inferred from Req.
</ParamField>
<ParamField body="ResponseFormat" type="json.RawMessage">
ResponseFormat is the JSON Schema of the function's response, sent as "response_format": the handler's return value, which is what observers observe. It must be valid JSON; nil omits it. With `RegisterFunctionTyped` it replaces the schema inferred from Resp.
</ParamField>
<ParamField body="ArgsFormat" type="json.RawMessage">
ArgsFormat is the JSON Schema of the observers' args, sent as "args_format": the engine validates every observer's args against it (INVALID_ARGS), and refuses a schema that is not valid (INVALID_ARGS_FORMAT). It must be valid JSON; nil means the function takes no args.
</ParamField>
<ParamField body="Private" type="bool">
Private lets only this worker call the function (the engine answers anyone else with FORBIDDEN); other workers may observe it, and it cannot be an observer's target. A call this worker makes to it passes the input and the result by reference: the handler and the hooks treat both as read-only.
</ParamField>
<ParamField body="Observable" type="*bool">
Observable false refuses every observer of the function (NOT_OBSERVABLE), for a function whose payloads carry credentials. nil means true.
</ParamField>
</Expandable>
</ParamField>
---
### Client.Shutdown
Shutdown shuts the client down gracefully, as the Node SDK's shutdown does, bounded by ctx like http.Server.Shutdown: it stops the reconnect loop, waits until the buffered observe reports and counters are written, stops the worker gauges, flushes and stops the telemetry exporters, cancels all pending calls with ErrNotConnected, and closes the socket with a normal-closure handshake.
When ctx is done before those steps finish, the remaining work is cut short (the socket is closed at once, also when the engine never answers the close handshake) and ctx.Err() is returned; the client is shut down either way and nil means everything was delivered. A `Client.Close` called meanwhile cuts it short the same way, and Shutdown then returns context.Canceled. Like Close it does not send unregister frames. Shutdown is idempotent: a later Shutdown returns once the first shutdown has finished, or ctx.Err() if its own ctx ends first.
**Signature**
```go
func (c *Client) Shutdown(ctx context.Context) error
```
<Tabs>
<Tab title="Parameters">
<ParamField body="ctx" type="context.Context" required>
</ParamField>
</Tab>
<Tab title="Example">
```go
client := iii.RegisterWorker(iii.DefaultEngineURL)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := client.Shutdown(ctx); err != nil {
log.Printf("shutdown cut short: %v", err)
}
```
</Tab>
</Tabs>
---
### Client.State
<Warning>
**Deprecated.** Use `Client.ConnectionState`.
</Warning>
State returns the current connection state.
**Signature**
```go
func (c *Client) State() ConnectionState
```
---
### Client.WaitUntilRegistered
WaitUntilRegistered blocks until the engine has acknowledged this worker on the current connection, with the WorkerRegistered frame it sends on each connection, and then returns nil. While the client is disconnected it waits for the next connection's acknowledgement.
It returns the error of `Client.FatalError` when the worker was terminally rejected (for example a WORKER_NAMESPACE_CONFLICT, or a blank `WithNamespace`), and ctx.Err() when ctx is done first. Like the Rust SDK's wait_until_registered, which it mirrors with ctx in place of a timeout, it returns `ErrNotConnected` when the client was never started (call it after `Client.Connect` or `RegisterWorker`), has been closed, or gave up reconnecting (`ReconnectConfig`.MaxRetries).
**Signature**
```go
func (c *Client) WaitUntilRegistered(ctx context.Context) error
```
#### Parameters
<ParamField body="ctx" type="context.Context" required>
</ParamField>
---
### Client.WorkerID
WorkerID returns the worker id the engine assigned with its last WorkerRegistered, or "" before the first one. The id is kept across a disconnect (the next connection presents it to reattach) until the engine assigns the next one. It mirrors worker_id in the Python SDK.
**Signature**
```go
func (c *Client) WorkerID() string
```
## Functions
### APIKeyAuth
APIKeyAuth returns the `HTTPInvocationRef`.Auth that has the engine send an API key in the request header named header, the key being held in the engine's environment variable valueKey: \{"type":"api_key","header":header,"value_key":valueKey\}. Same shape as the api_key variant of the Node SDK's HttpAuthConfig.
**Signature**
```go
func APIKeyAuth(header, valueKey string) json.RawMessage
```
#### Parameters
<ParamField body="header" type="string" required>
</ParamField>
<ParamField body="valueKey" type="string" required>
</ParamField>
---
### BearerAuth
BearerAuth returns the `HTTPInvocationRef`.Auth that has the engine send "Authorization: Bearer <token>", the token being held in the engine's environment variable tokenKey: \{"type":"bearer","token_key":tokenKey\}. Same shape as the bearer variant of the Node SDK's HttpAuthConfig.
**Signature**
```go
func BearerAuth(tokenKey string) json.RawMessage
```
#### Parameters
<ParamField body="tokenKey" type="string" required>
</ParamField>
---
### DefaultReconnectConfig
DefaultReconnectConfig is the reconnect schedule shared with the Node SDK: start at 1s, double each time, cap at 30s, ±30% jitter, retry forever.
**Signature**
```go
func DefaultReconnectConfig() ReconnectConfig
```
---
### EngineURLFromEnv
EngineURLFromEnv returns the engine address a worker connects to when its code names none: the III_URL environment variable, trimmed, when it is not blank, else `DefaultEngineURL`. The supervisor that spawned the process (iii compose, a container runtime, systemd) sets III_URL the same way it sets III_NAMESPACE and III_WORKER_NAME. `New` and `RegisterWorker` call it when their url argument is empty, so an explicit address wins, then III_URL, then the default, as in the Node SDK.
**Signature**
```go
func EngineURLFromEnv() string
```
---
### EnqueueAction
EnqueueAction routes an invocation through a named queue; the engine acknowledges with an enqueue receipt rather than the function's result.
**Signature**
```go
func EnqueueAction(queue string) *CallAction
```
#### Parameters
<ParamField body="queue" type="string" required>
</ParamField>
---
### HMACAuth
HMACAuth returns the `HTTPInvocationRef`.Auth that has the engine sign each request with HMAC, using the secret held in the engine's environment variable secretKey: \{"type":"hmac","secret_key":secretKey\}. Same shape as the hmac variant of the Node SDK's HttpAuthConfig.
**Signature**
```go
func HMACAuth(secretKey string) json.RawMessage
```
#### Parameters
<ParamField body="secretKey" type="string" required>
</ParamField>
---
### Identity
Identity is a handler that returns the input it is called with. An event source registers it: its observers observe each event as both input and output.
**Signature**
```go
func Identity(_ context.Context, data json.RawMessage) (any, error)
```
#### Parameters
<ParamField body="_" type="context.Context" required>
</ParamField>
<ParamField body="data" type="json.RawMessage" required>
</ParamField>
---
### InferSchema
InferSchema reflects a JSON Schema for T, exposed for callers that want to build a registration manually or inspect the schema the typed API would send.
Nested types are written out where they appear. A type that contains itself (a tree node with Children []Node, a struct with a pointer to its own type, two structs that point at each other) is described once under "$defs" and referenced with "$ref": "#/$defs/<Name>". An interface type, such as any, accepts any JSON value. A type with no JSON Schema, such as a chan or func field, is an error.
**Signature**
```go
func InferSchema[T any]() (json.RawMessage, error)
```
---
### InputStreamFromBytes
InputStreamFromBytes returns a stream of data. The stream keeps data: do not change it until the stream was read or sent.
**Signature**
```go
func InputStreamFromBytes(data []byte) *InputStream
```
#### Parameters
<ParamField body="data" type="[]byte" required>
</ParamField>
---
### InputStreamFromReader
InputStreamFromReader returns a stream of what r yields, read in chunks of up to 64 KiB when the stream is read or sent. A read error aborts the stream with its message: the reader gets STREAM_ABORTED, not a short stream that looks complete. When r is an `io.Closer`, the stream closes it once it ends, fails or is cancelled (it owns r, as an http.Request owns its Body).
Closing r is also how a cancel, or the end of the ctx of a read, stops a r.Read that blocks. A blocked Read of an r that is not an io.Closer cannot be cut short: the read of the stream in flight (a ReadAll whose ctx ended, or one at a Cancel), and the reads after it, return only once that Read does. Pass an io.Closer (an \*io.PipeReader, a net.Conn) when r.Read can block.
**Signature**
```go
func InputStreamFromReader(r io.Reader) *InputStream
```
<Tabs>
<Tab title="Parameters">
<ParamField body="r" type="io.Reader" required>
</ParamField>
</Tab>
<Tab title="Example">
```go
f, err := os.Open("report.csv")
if err != nil { ... }
payload, _ := json.Marshal(map[string]any{"filename": "report.csv", "body": iii.InputStreamFromReader(f)})
result, err := worker.Call(ctx, iii.CallRequest{FunctionID: "files::process", Payload: payload})
```
</Tab>
</Tabs>
---
### InvocationFromContext
InvocationFromContext returns the invocation a handler's ctx belongs to, remote or local. ok is false outside any handler.
**Signature**
```go
func InvocationFromContext(ctx context.Context) (Invocation, bool)
```
<Tabs>
<Tab title="Parameters">
<ParamField body="ctx" type="context.Context" required>
</ParamField>
</Tab>
<Tab title="Example">
```go
func handler(ctx context.Context, data json.RawMessage) (any, error) {
if inv, ok := iii.InvocationFromContext(ctx); ok {
log.Printf("%s called by %+v", inv.InvocationID, inv.Caller)
}
...
}
```
</Tab>
</Tabs>
---
### MarshalMessage
MarshalMessage encodes a variant struct as a wire frame, injecting the "type" tag. Pass one of the \*Message structs (by pointer or value) from this file.
**Signature**
```go
func MarshalMessage(msg any) ([]byte, error)
```
#### Parameters
<ParamField body="msg" type="any" required>
</ParamField>
---
### MatchFunc
MatchFunc is a match hook that asks predicate, once per active observer per call, whether the observer wants the call. A predicate that panics counts as no match, and the SDK logs it once per function. A nil predicate gives a nil MatchHook.
**Signature**
```go
func MatchFunc(predicate func(obs *Observer, call *Call) bool) *MatchHook
```
<Tabs>
<Tab title="Parameters">
<ParamField body="predicate" type="func(obs *Observer, call *Call) bool" required>
<Expandable title="`Call` fields">
<ParamField body="FunctionID" type="string" required>
</ParamField>
<ParamField body="InvocationID" type="string" required>
</ParamField>
<ParamField body="Status" type="string">
Status is "success" or "error". Empty reads as "error" when Error is set, and "success" otherwise.
</ParamField>
<ParamField body="Input" type="json.RawMessage">
Input is the call's input, as the handler received it.
</ParamField>
<ParamField body="Output" type="json.RawMessage">
Output is the handler's return value as JSON: what observers observe. Nil on an error.
</ParamField>
<ParamField body="Error" type="*ErrorBody">
Error is the error the handler returned. Nil on success.
</ParamField>
<ParamField body="Caller" type="*Caller">
Caller is who made the call; nil for a call made outside any handler.
</ParamField>
<ParamField body="Metadata" type="json.RawMessage">
Metadata is the call's metadata sidecar; nil when it carries none.
</ParamField>
</Expandable>
<Expandable title="`Observer` fields">
<ParamField body="ID" type="string" required>
</ParamField>
<ParamField body="FunctionID" type="string" required>
FunctionID is the observed function (the one this worker hosts).
</ParamField>
<ParamField body="Args" type="map[string]any">
Args are the observer's args, validated against args_format by the engine (numbers decode as float64; see DecodeArgs).
</ParamField>
<ParamField body="Filters" type="map[string]any">
Filters are the observer's filters in normal form; iii's delivery and Matches apply them.
</ParamField>
<ParamField body="Target" type="string" required>
Target is the target function id.
</ParamField>
<ParamField body="Capture" type="[]Capture">
Capture is what the target's payload carries, and the outcomes that fire it.
</ParamField>
<ParamField body="Accepted" type="func(ctx context.Context) error" required>
Accepted waits until the SDK has acked the observer as accepted, and returns nil. A call made after that reaches an active observer, since the engine handles a connection's frames in order: a host sends a new observer its initial state this way, with a call of its own function whose metadata is \{"for_observer": <obs.ID>\}. The function's `MatchHook` gives that call to this observer alone, and iii delivers it like every call. It returns an \*`ObserveRejectionError` when the observer is rejected first (code OBSERVER_NOT_ACTIVE when it is removed, or its function released, first), and ctx's error when ctx is done first. Once accepted, it returns nil at once.
</ParamField>
<ParamField body="DecodeArgs" type="func(v any) error" required>
DecodeArgs unmarshals the observer's args into v (a struct, typically).
</ParamField>
<ParamField body="Matches" type="func(call *Call) bool" required>
Matches reports whether call reaches the observer: it fires on the call's status (its view's fires_on) and its filters match the call. A deliver hook that calls targets itself checks it before calling through the observer; iii's delivery applies it on its own. On a call the SDK hands a hook, the observers share the call's decoded document and its values at the paths of the function's filter index, so each costs its own filter, and an observer costs a comparison when the call fails the condition it is filed under.
</ParamField>
<ParamField body="Reject" type="func(code, message string)" required>
Reject sends a late rejection for this observer (e.g. after a config reload removed what it needs). It leaves the compiled set at once, so calls stop reaching it, and its removed hooks run next on the function's hook queue, connected or not; the engine's observerremoved that follows runs none again. The rejection is sent again when the engine replays the observer after a reconnect. Called while the observer's added hooks run, it rejects the observer once they return, and the removed hook of each level whose added hook resolved runs.
</ParamField>
</Expandable>
</ParamField>
</Tab>
<Tab title="Example">
```go
// an observer of expression X gets the ticks of expression X
client.OnObservationMatchFor("cron::on-tick", iii.MatchFunc(func(obs *iii.Observer, call *iii.Call) bool {
var tick struct{ Expression string `json:"expression"` }
_ = json.Unmarshal(call.Input, &tick)
return obs.Args["expression"] == tick.Expression
}))
```
</Tab>
</Tabs>
---
### MatchKeys
MatchKeys is a match hook by keys: an observer wants a call when they share a key, and the SDK keeps an index of the active observers by key instead of asking each of them. observerKeys says what an observer listens for: the SDK computes it once, when the observer is accepted, files the observer under each key and unfiles it when it is removed. An observer whose observerKeys panics is rejected with OBSERVE_REJECTED. callKeys says what a call is: the call matches the observers filed under any of its keys, each once; a callKeys that panics matches nothing, and the SDK logs it once per function. Keys express wildcards by listing them: an observer of every table is filed under "primary|\*|insert", and a change matches "primary|orders|insert", "primary|orders|\*", "primary|\*|insert" and "primary|\*|\*". A nil function gives a nil MatchHook.
On a function matched by keys, `Client.IsObservedFor` answers with one lookup per call key.
**Signature**
```go
func MatchKeys(observerKeys func(obs *Observer) []string, callKeys func(call *Call) []string) *MatchHook
```
<Tabs>
<Tab title="Parameters">
<ParamField body="observerKeys" type="func(obs *Observer) []string" required>
<Expandable title="`Observer` fields">
<ParamField body="ID" type="string" required>
</ParamField>
<ParamField body="FunctionID" type="string" required>
FunctionID is the observed function (the one this worker hosts).
</ParamField>
<ParamField body="Args" type="map[string]any">
Args are the observer's args, validated against args_format by the engine (numbers decode as float64; see DecodeArgs).
</ParamField>
<ParamField body="Filters" type="map[string]any">
Filters are the observer's filters in normal form; iii's delivery and Matches apply them.
</ParamField>
<ParamField body="Target" type="string" required>
Target is the target function id.
</ParamField>
<ParamField body="Capture" type="[]Capture">
Capture is what the target's payload carries, and the outcomes that fire it.
</ParamField>
<ParamField body="Accepted" type="func(ctx context.Context) error" required>
Accepted waits until the SDK has acked the observer as accepted, and returns nil. A call made after that reaches an active observer, since the engine handles a connection's frames in order: a host sends a new observer its initial state this way, with a call of its own function whose metadata is \{"for_observer": <obs.ID>\}. The function's `MatchHook` gives that call to this observer alone, and iii delivers it like every call. It returns an \*`ObserveRejectionError` when the observer is rejected first (code OBSERVER_NOT_ACTIVE when it is removed, or its function released, first), and ctx's error when ctx is done first. Once accepted, it returns nil at once.
</ParamField>
<ParamField body="DecodeArgs" type="func(v any) error" required>
DecodeArgs unmarshals the observer's args into v (a struct, typically).
</ParamField>
<ParamField body="Matches" type="func(call *Call) bool" required>
Matches reports whether call reaches the observer: it fires on the call's status (its view's fires_on) and its filters match the call. A deliver hook that calls targets itself checks it before calling through the observer; iii's delivery applies it on its own. On a call the SDK hands a hook, the observers share the call's decoded document and its values at the paths of the function's filter index, so each costs its own filter, and an observer costs a comparison when the call fails the condition it is filed under.
</ParamField>
<ParamField body="Reject" type="func(code, message string)" required>
Reject sends a late rejection for this observer (e.g. after a config reload removed what it needs). It leaves the compiled set at once, so calls stop reaching it, and its removed hooks run next on the function's hook queue, connected or not; the engine's observerremoved that follows runs none again. The rejection is sent again when the engine replays the observer after a reconnect. Called while the observer's added hooks run, it rejects the observer once they return, and the removed hook of each level whose added hook resolved runs.
</ParamField>
</Expandable>
</ParamField>
<ParamField body="callKeys" type="func(call *Call) []string" required>
<Expandable title="`Call` fields">
<ParamField body="FunctionID" type="string" required>
</ParamField>
<ParamField body="InvocationID" type="string" required>
</ParamField>
<ParamField body="Status" type="string">
Status is "success" or "error". Empty reads as "error" when Error is set, and "success" otherwise.
</ParamField>
<ParamField body="Input" type="json.RawMessage">
Input is the call's input, as the handler received it.
</ParamField>
<ParamField body="Output" type="json.RawMessage">
Output is the handler's return value as JSON: what observers observe. Nil on an error.
</ParamField>
<ParamField body="Error" type="*ErrorBody">
Error is the error the handler returned. Nil on success.
</ParamField>
<ParamField body="Caller" type="*Caller">
Caller is who made the call; nil for a call made outside any handler.
</ParamField>
<ParamField body="Metadata" type="json.RawMessage">
Metadata is the call's metadata sidecar; nil when it carries none.
</ParamField>
</Expandable>
</ParamField>
</Tab>
<Tab title="Example">
```go
client := iii.RegisterWorker(iii.DefaultEngineURL)
defer client.Close()
type timerArgs struct {
EveryMs int64 `json:"every_ms"`
}
keyOf := func(everyMs int64) string { return fmt.Sprint(everyMs) }
stops := map[string]chan struct{}{} // one ticker per interval, used on the hook queue only
client.OnObserverAddedFor("timer::on-tick", func(ctx context.Context, obs *iii.Observer) error {
var args timerArgs
if err := obs.DecodeArgs(&args); err != nil || args.EveryMs <= 0 {
return iii.ObserveRejection("INVALID_ARGS", "every_ms must be a positive integer")
}
if _, running := stops[keyOf(args.EveryMs)]; running {
return nil
}
stop := make(chan struct{})
stops[keyOf(args.EveryMs)] = stop
go func() {
ticker := time.NewTicker(time.Duration(args.EveryMs) * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-stop:
return
case now := <-ticker.C:
tick, _ := json.Marshal(map[string]int64{"every_ms": args.EveryMs, "fired_at_ms": now.UnixMilli()})
if !client.IsObservedFor("timer::on-tick", &iii.Call{Input: tick}) {
continue
}
client.Call(context.Background(), iii.CallRequest{FunctionID: "timer::on-tick", Payload: tick, Action: iii.VoidAction()})
}
}
}()
return nil
})
client.OnObserverRemovedFor("timer::on-tick", func(ctx context.Context, obs *iii.Observer) {
var args timerArgs
_ = obs.DecodeArgs(&args)
for _, other := range client.Observers("timer::on-tick") {
var o timerArgs
if other != obs && other.DecodeArgs(&o) == nil && o.EveryMs == args.EveryMs {
return // the interval is still observed
}
}
if stop, ok := stops[keyOf(args.EveryMs)]; ok {
close(stop)
delete(stops, keyOf(args.EveryMs))
}
})
client.OnObservationMatchFor("timer::on-tick", iii.MatchKeys(
func(obs *iii.Observer) []string { // what the observer listens for
var args timerArgs
_ = obs.DecodeArgs(&args)
return []string{keyOf(args.EveryMs)}
},
func(call *iii.Call) []string { // what the call is: the tick carries every_ms too
var tick timerArgs
_ = json.Unmarshal(call.Input, &tick)
return []string{keyOf(tick.EveryMs)}
},
))
if _, err := client.RegisterFunction("timer::on-tick", iii.Identity, iii.FunctionOptions{
Description: "One call per tick. Observe it with args { every_ms }.",
ArgsFormat: json.RawMessage(`{"type":"object","required":["every_ms"],"properties":{"every_ms":{"type":"integer","minimum":1}}}`),
Private: true,
}); err != nil {
log.Fatal(err)
}
```
</Tab>
</Tabs>
---
### MetadataFromContext
MetadataFromContext returns the per-invocation metadata attached to a handler's ctx. The bool is false (and the value nil) when the invocation carried no metadata, letting a handler distinguish "no metadata" from a present-but-empty value. Metadata is any JSON value; JSON null is no metadata.
**Signature**
```go
func MetadataFromContext(ctx context.Context) (json.RawMessage, bool)
```
<Tabs>
<Tab title="Parameters">
<ParamField body="ctx" type="context.Context" required>
</ParamField>
</Tab>
<Tab title="Examples">
```go
func handler(ctx context.Context, data json.RawMessage) (any, error) {
if md, ok := iii.MetadataFromContext(ctx); ok {
// ... use md (raw JSON) ...
}
...
}
```
```go
client := iii.New(iii.DefaultEngineURL)
client.RegisterFunction("orders::create",
func(ctx context.Context, data json.RawMessage) (any, error) {
metadata, ok := iii.MetadataFromContext(ctx)
return map[string]any{"ok": true, "has_metadata": ok, "metadata": metadata}, nil
})
```
</Tab>
</Tabs>
---
### New
New creates a `Client` for the engine at url (e.g. `DefaultEngineURL`). An empty url means `EngineURLFromEnv`: III_URL when set, else DefaultEngineURL. It does not connect; call `Client.Connect` to start the connection lifecycle, or use `RegisterWorker` to create and connect in one step.
**Signature**
```go
func New(url string, opts ...Option) *Client
```
#### Parameters
<ParamField body="url" type="string" required>
</ParamField>
<ParamField body="opts" type="...Option">
<Expandable title="`Option` fields">
<ParamField body="WithDescription" type="func(description string) Option" required>
WithDescription sets a one-line, human/LLM-readable summary of what this worker does. Surfaces in engine::workers::list / engine::workers::info.
</ParamField>
<ParamField body="WithHeaders" type="func(h http.Header) Option" required>
WithHeaders sets HTTP headers sent on the WebSocket handshake of the main connection and of the stream sockets of this client (see `InputStream` and `OutputStream`). The III_TOKEN environment variable, when set and not blank, adds "Authorization: Bearer <token>" unless h already carries an Authorization header.
</ParamField>
<ParamField body="WithInvocationTimeout" type="func(d time.Duration) Option" required>
WithInvocationTimeout sets how long `Client.Call` waits for a result when `CallRequest`.Timeout is zero, in place of `DefaultInvocationTimeout`. It is the invocationTimeoutMs option of the Node SDK's registerWorker. A d of zero or less keeps the default.
</ParamField>
<ParamField body="WithMetricsReporting" type="func(enabled bool) Option" required>
WithMetricsReporting turns the worker resource gauges on or off (Node enableMetricsReporting): the iii.worker.memory.\*, iii.worker.cpu.\*, iii.worker.event_loop.lag_ms and iii.worker.uptime_seconds metrics, tagged with worker.id and worker.name. The default is true. The gauges start when the engine acknowledges the worker and stop when the connection drops; they need telemetry and its metrics to be enabled (see `OtelConfig`).
</ParamField>
<ParamField body="WithName" type="func(name string) Option" required>
WithName sets the worker name reported to the engine. A non-empty III_WORKER_NAME takes precedence. The default is "hostname:pid".
</ParamField>
<ParamField body="WithNamespace" type="func(namespace string) Option" required>
WithNamespace sets the namespace this worker registers into. Takes precedence over the III_NAMESPACE environment variable.
</ParamField>
<ParamField body="WithOtel" type="func(cfg OtelConfig) Option" required>
WithOtel configures the client's OpenTelemetry pipeline (the otel option of Node registerWorker). Telemetry starts with the connection lifecycle (`RegisterWorker` or `Client.Connect`) and `Client.Close` flushes and stops it. Without this option the defaults documented on `OtelConfig` apply, and they enable telemetry.
</ParamField>
<ParamField body="WithReconnectConfig" type="func(c ReconnectConfig) Option" required>
WithReconnectConfig overrides the default reconnect schedule.
</ParamField>
<ParamField body="WithTelemetry" type="func(t TelemetryOptions) Option" required>
WithTelemetry sets what the worker reports about its language, project and framework on every connection. Blank fields keep their defaults (see `TelemetryOptions`).
</ParamField>
</Expandable>
</ParamField>
---
### ObserveRejection
ObserveRejection builds the error an `AddedHook` returns to reject an observer with code (any other error rejects it with OBSERVE_REJECTED).
**Signature**
```go
func ObserveRejection(code, message string) error
```
#### Parameters
<ParamField body="code" type="string" required>
</ParamField>
<ParamField body="message" type="string" required>
</ParamField>
---
### OutputStreamToWriter
OutputStreamToWriter returns a stream whose bytes go to w. Closing the stream flushes w (when it has a Flush() error method) and closes it (when it is an `io.Closer`); an abort closes w with the error when it has CloseWithError (an `*io.PipeWriter`) and otherwise leaves it as is, so a truncated stream is never finished as if whole: close it yourself, and remove a partly written file.
When w fails (its Write, Flush or Close returns an error), the stream aborts: nothing more is written to w, the function's next write fails with STREAM_CLOSED, and the call that passed the stream fails with STREAM_ABORTED, "the sink failed: <w's error>", wrapping w's error (errors.Is and errors.As reach it), whatever the function returned.
A call does not wait behind a w.Write that blocks: at the call's timeout, or when its ctx ends, the call returns and the stream is aborted. A Write that never returns (and ignores CloseWithError) keeps the goroutine that called it until it returns.
**Signature**
```go
func OutputStreamToWriter(w io.Writer) *OutputStream
```
<Tabs>
<Tab title="Parameters">
<ParamField body="w" type="io.Writer" required>
</ParamField>
</Tab>
<Tab title="Example">
```go
f, err := os.Create("r-42.pdf")
if err != nil { ... }
payload, _ := json.Marshal(map[string]any{"report_id": "r-42", "out": iii.OutputStreamToWriter(f)})
// Returns once the file holds the whole PDF.
_, err = worker.Call(ctx, iii.CallRequest{FunctionID: "reports::render-pdf", Payload: payload})
```
</Tab>
</Tabs>
---
### RegisterFunctionTyped
RegisterFunctionTyped registers a function whose request and response schemas are inferred from the Req and Resp type parameters and advertised to the engine. It is the schema-aware counterpart of `Client.RegisterFunction`; reach for it when you want the engine (and its dashboard / typed callers) to know the function's contract.
It returns the function's handle, as `Client.RegisterFunction` does.
Use `Client.RegisterFunction` directly for schemaless functions. See `InferSchema` to obtain a type's schema on its own. Pass a single `RegisterFunctionOptions` value to attach a description, registration metadata, args_format, private or observable; its RequestFormat and ResponseFormat, when set, replace the inferred schemas (that type is then not reflected). Its handle sets the function's hooks, as `Client.RegisterFunction`'s does.
**Signature**
```go
func RegisterFunctionTyped[Req any, Resp any](c *Client, id string, handler TypedHandler[Req, Resp], opts ...RegisterFunctionOptions) (*FunctionRef, error)
```
<Tabs>
<Tab title="Parameters">
<ParamField body="c" type="*Client" required>
</ParamField>
<ParamField body="id" type="string" required>
</ParamField>
<ParamField body="handler" type="TypedHandler[Req, Resp]" required>
</ParamField>
<ParamField body="opts" type="...RegisterFunctionOptions">
<Expandable title="`RegisterFunctionOptions` fields">
<ParamField body="Metadata" type="json.RawMessage">
Metadata is arbitrary JSON attached to the function registration. It is stored with the function and is distinct from the per-invocation metadata passed to handlers.
</ParamField>
<ParamField body="LocalDispatch" type="*bool">
LocalDispatch false keeps every Call of this function on the engine path; nil or true lets Call run it in-process once the engine confirms it (see `Client.Call`: observers see snapshots of the payload and metadata taken at call start, and a handler may outlive a caller whose deadline passed).
</ParamField>
<ParamField body="Description" type="string">
Description is a human/LLM-readable summary of the function, sent as "description" and surfaced by engine::functions::list and engine::functions::info. Empty omits it.
</ParamField>
<ParamField body="RequestFormat" type="json.RawMessage">
RequestFormat is the JSON Schema of the function's request, sent as "request_format". It must be valid JSON; nil omits it. With `RegisterFunctionTyped` it replaces the schema inferred from Req.
</ParamField>
<ParamField body="ResponseFormat" type="json.RawMessage">
ResponseFormat is the JSON Schema of the function's response, sent as "response_format": the handler's return value, which is what observers observe. It must be valid JSON; nil omits it. With `RegisterFunctionTyped` it replaces the schema inferred from Resp.
</ParamField>
<ParamField body="ArgsFormat" type="json.RawMessage">
ArgsFormat is the JSON Schema of the observers' args, sent as "args_format": the engine validates every observer's args against it (INVALID_ARGS), and refuses a schema that is not valid (INVALID_ARGS_FORMAT). It must be valid JSON; nil means the function takes no args.
</ParamField>
<ParamField body="Private" type="bool">
Private lets only this worker call the function (the engine answers anyone else with FORBIDDEN); other workers may observe it, and it cannot be an observer's target. A call this worker makes to it passes the input and the result by reference: the handler and the hooks treat both as read-only.
</ParamField>
<ParamField body="Observable" type="*bool">
Observable false refuses every observer of the function (NOT_OBSERVABLE), for a function whose payloads carry credentials. nil means true.
</ParamField>
</Expandable>
</ParamField>
</Tab>
<Tab title="Examples">
```go
iii.RegisterFunctionTyped[CreateOrderRequest, OrderResult](client, "orders::create",
func(ctx context.Context, req CreateOrderRequest) (OrderResult, error) { ... })
```
```go
client := iii.RegisterWorker(iii.DefaultEngineURL)
defer client.Close()
iii.RegisterFunctionTyped(client, "hello::greet",
func(ctx context.Context, req greetRequest) (greetResponse, error) {
return greetResponse{Message: "Hello, " + req.Name + "!"}, nil
})
```
</Tab>
</Tabs>
---
### UnmarshalMessage
UnmarshalMessage decodes a wire frame by peeking at "type" and then decoding into the matching variant struct. It is the Go counterpart of serde's tag dispatch.
**Signature**
```go
func UnmarshalMessage(data []byte) (*DecodedMessage, error)
```
#### Parameters
<ParamField body="data" type="[]byte" required>
</ParamField>
---
### VoidAction
VoidAction returns the fire-and-forget action. A call with this action carries no invocation_id, so the engine sends no reply (see `Client.Call`).
**Signature**
```go
func VoidAction() *CallAction
```
---
### WithDescription
WithDescription sets a one-line, human/LLM-readable summary of what this worker does. Surfaces in engine::workers::list / engine::workers::info.
**Signature**
```go
func WithDescription(description string) Option
```
#### Parameters
<ParamField body="description" type="string" required>
</ParamField>
---
### WithHeaders
WithHeaders sets HTTP headers sent on the WebSocket handshake of the main connection and of the stream sockets of this client (see `InputStream` and `OutputStream`). The III_TOKEN environment variable, when set and not blank, adds "Authorization: Bearer <token>" unless h already carries an Authorization header.
**Signature**
```go
func WithHeaders(h http.Header) Option
```
#### Parameters
<ParamField body="h" type="http.Header" required>
</ParamField>
---
### WithInvocationTimeout
WithInvocationTimeout sets how long `Client.Call` waits for a result when `CallRequest`.Timeout is zero, in place of `DefaultInvocationTimeout`. It is the invocationTimeoutMs option of the Node SDK's registerWorker. A d of zero or less keeps the default.
**Signature**
```go
func WithInvocationTimeout(d time.Duration) Option
```
#### Parameters
<ParamField body="d" type="time.Duration" required>
</ParamField>
---
### WithMetricsReporting
WithMetricsReporting turns the worker resource gauges on or off (Node enableMetricsReporting): the iii.worker.memory.\*, iii.worker.cpu.\*, iii.worker.event_loop.lag_ms and iii.worker.uptime_seconds metrics, tagged with worker.id and worker.name. The default is true. The gauges start when the engine acknowledges the worker and stop when the connection drops; they need telemetry and its metrics to be enabled (see `OtelConfig`).
**Signature**
```go
func WithMetricsReporting(enabled bool) Option
```
#### Parameters
<ParamField body="enabled" type="bool" required>
</ParamField>
---
### WithName
WithName sets the worker name reported to the engine. A non-empty III_WORKER_NAME takes precedence. The default is "hostname:pid".
**Signature**
```go
func WithName(name string) Option
```
#### Parameters
<ParamField body="name" type="string" required>
</ParamField>
---
### WithNamespace
WithNamespace sets the namespace this worker registers into. Takes precedence over the III_NAMESPACE environment variable.
A namespace named and left blank is refused, not read as "no namespace": the client is put in a terminal failed state, so `Client.Connect` returns the reason and `Client.FatalError` reports it. Absent and blank ask for opposite things: absent asks for the engine's `default`, blank names a namespace and gives nothing to name it with. Read as absent, the worker registers in `default`, and since a worker's calls and observers follow its namespace, the whole project quietly serves from a place its declaration never named.
To register in the engine's default namespace, do not call this.
**Signature**
```go
func WithNamespace(namespace string) Option
```
#### Parameters
<ParamField body="namespace" type="string" required>
</ParamField>
---
### WithOtel
WithOtel configures the client's OpenTelemetry pipeline (the otel option of Node registerWorker). Telemetry starts with the connection lifecycle (`RegisterWorker` or `Client.Connect`) and `Client.Close` flushes and stops it. Without this option the defaults documented on `OtelConfig` apply, and they enable telemetry.
**Signature**
```go
func WithOtel(cfg OtelConfig) Option
```
<Tabs>
<Tab title="Parameters">
<ParamField body="cfg" type="OtelConfig" required>
<Expandable title="`OtelConfig` fields">
<ParamField body="Enabled" type="*bool">
Enabled turns telemetry export on or off. Nil reads OTEL_ENABLED ("false", "0", "no" or "off" disable it); the default is true.
</ParamField>
<ParamField body="ServiceName" type="string">
ServiceName is the service.name resource attribute and the instrumentation scope of the SDK's tracer, meter and logger. Empty reads OTEL_SERVICE_NAME; the default is "iii-go".
</ParamField>
<ParamField body="ServiceVersion" type="string">
ServiceVersion is the service.version resource attribute. Empty reads SERVICE_VERSION; the default is "unknown".
</ParamField>
<ParamField body="ServiceNamespace" type="string">
ServiceNamespace is the service.namespace resource attribute, omitted when empty. Empty reads SERVICE_NAMESPACE.
</ParamField>
<ParamField body="ServiceInstanceID" type="string">
ServiceInstanceID is the service.instance.id resource attribute. Empty reads SERVICE_INSTANCE_ID; the default is a random UUID.
</ParamField>
<ParamField body="MetricsEnabled" type="*bool">
MetricsEnabled turns metrics export on or off. Nil reads OTEL_METRICS_ENABLED ("false", "0", "no" or "off" disable it); the default is true.
</ParamField>
<ParamField body="MetricsExportInterval" type="time.Duration">
MetricsExportInterval is the period of the metrics export. Zero means 60 seconds.
</ParamField>
<ParamField body="SpansFlushInterval" type="time.Duration">
SpansFlushInterval is how long an ended span waits in the batch before it is sent. Zero reads OTEL_SPANS_FLUSH_INTERVAL_MS (milliseconds); the default is 100ms.
</ParamField>
<ParamField body="LogsFlushInterval" type="time.Duration">
LogsFlushInterval is how long a log record waits in the batch before it is sent. Zero reads OTEL_LOGS_FLUSH_INTERVAL_MS (milliseconds); the default is 100ms.
</ParamField>
<ParamField body="LogsBatchSize" type="int">
LogsBatchSize is the maximum number of log records per export. Zero reads OTEL_LOGS_BATCH_SIZE; the default is 1.
</ParamField>
<ParamField body="FetchInstrumentationEnabled" type="*bool">
FetchInstrumentationEnabled turns the HTTP client spans of observability.NewTransport and observability.NewHTTPClient on or off (the Go counterpart of Node's fetch instrumentation). Nil means true.
</ParamField>
<ParamField body="ReconnectionConfig" type="*ReconnectConfig">
ReconnectionConfig is the reconnect schedule of the telemetry WebSocket. Nil means `DefaultReconnectConfig`; a non-nil value is used as given.
</ParamField>
</Expandable>
</ParamField>
</Tab>
<Tab title="Examples">
```go
c := iii.RegisterWorker(url, iii.WithOtel(iii.OtelConfig{ServiceName: "orders"}))
```
```go
// To turn telemetry off:
off := false
c := iii.RegisterWorker(url, iii.WithOtel(iii.OtelConfig{Enabled: &off}))
```
</Tab>
</Tabs>
---
### WithReconnectConfig
WithReconnectConfig overrides the default reconnect schedule.
**Signature**
```go
func WithReconnectConfig(c ReconnectConfig) Option
```
#### Parameters
<ParamField body="c" type="ReconnectConfig" required>
<Expandable title="`ReconnectConfig` fields">
<ParamField body="InitialDelay" type="time.Duration" required>
InitialDelay is the delay before the first reconnect attempt.
</ParamField>
<ParamField body="MaxDelay" type="time.Duration" required>
MaxDelay caps the backoff.
</ParamField>
<ParamField body="BackoffMultiplier" type="float64" required>
BackoffMultiplier scales the delay after each failed attempt.
</ParamField>
<ParamField body="JitterFactor" type="float64" required>
JitterFactor (0..1) randomizes each delay by up to ±JitterFactor to avoid a thundering herd of workers reconnecting in lockstep.
</ParamField>
<ParamField body="MaxRetries" type="int">
MaxRetries caps reconnect attempts; -1 means retry forever (the default).
</ParamField>
<ParamField body="DefaultReconnectConfig" type="func() ReconnectConfig" required>
DefaultReconnectConfig is the reconnect schedule shared with the Node SDK: start at 1s, double each time, cap at 30s, ±30% jitter, retry forever.
</ParamField>
</Expandable>
</ParamField>
---
### WithTelemetry
WithTelemetry sets what the worker reports about its language, project and framework on every connection. Blank fields keep their defaults (see `TelemetryOptions`).
**Signature**
```go
func WithTelemetry(t TelemetryOptions) Option
```
#### Parameters
<ParamField body="t" type="TelemetryOptions" required>
<Expandable title="`TelemetryOptions` fields">
<ParamField body="Language" type="string">
Language reported for the worker. Default: the locale of LANG (else LC_ALL) without its encoding, for example "en_US" for LANG=en_US.UTF-8, which is the Node SDK's fallback; omitted when neither variable is set.
</ParamField>
<ParamField body="ProjectName" type="string">
ProjectName is the project the worker belongs to. Default: the last element of the module path in the nearest go.mod, searched from the working directory upwards, skipping a major-version suffix such as /v2; omitted when there is no go.mod.
</ParamField>
<ParamField body="Framework" type="string">
Framework the worker is built with. Default: "iii-go". Surrounding spaces are trimmed.
</ParamField>
</Expandable>
</ParamField>
---
### filter.Compile
Compile validates and compiles a filter given as a Go value. A json.RawMessage or []byte is read as JSON text; any other value is read through encoding/json, so what is validated is exactly what travels on the wire. It returns an \*Error with code INVALID_FILTER when the filter is not valid.
**Signature**
```go
func Compile(src any) (*Filter, error)
```
#### Parameters
<ParamField body="src" type="any" required>
</ParamField>
---
### filter.MatchAll
MatchAll returns the filter that matches every document (\{\}).
**Signature**
```go
func MatchAll() *Filter
```
---
### filter.Parse
Parse validates and compiles a filter given as JSON text. It returns an \*Error with code INVALID_FILTER when the filter is not valid.
**Signature**
```go
func Parse(data []byte) (*Filter, error)
```
#### Parameters
<ParamField body="data" type="[]byte" required>
</ParamField>
---
### filter.ParseNormalized
ParseNormalized compiles a filter in the normal form the engine pushes (functionregistered, observeradded). Every rule applies except the encoded size limit, which the engine checked on the filter as written (a normal form can be longer).
**Signature**
```go
func ParseNormalized(data []byte) (*Filter, error)
```
#### Parameters
<ParamField body="data" type="[]byte" required>
</ParamField>
## Constants
### iii
EngineFunctions are the engine's built-in function paths a worker can invoke with `Client.Call`. Mirrors EngineFunctions in the Node SDK. A function row of engine::functions::list and engine::functions::info carries observer_count, and args_format, private and observable when set.
| Name | Value | Description |
| --- | --- | --- |
| `FnListFunctions` | `"engine::functions::list"` | - |
| `FnInfoFunctions` | `"engine::functions::info"` | - |
| `FnListWorkers` | `"engine::workers::list"` | - |
| `FnInfoWorkers` | `"engine::workers::info"` | - |
| `FnRegisterWorker` | `"engine::workers::register"` | - |
| `FnCreateChannel` | `"engine::channels::create"` | - |
Engine-hosted sources: private functions of the engine whose handler returns the event, so input and output are both the event. Observe them with `Client.Observe` and filters on input; only the engine calls them. `EngineSources` names them as the other SDKs do.
| Name | Value | Description |
| --- | --- | --- |
| `FnOnFunctionsChanged` | `"engine::on-functions-changed"` | FnOnFunctionsChanged is called when the function set changes: \{ event: "functions_changed", functions: [...] \}. |
| `FnOnWorkersChanged` | `"engine::on-workers-changed"` | FnOnWorkersChanged is called when a worker connects, disconnects or updates its metadata: \{ event, worker_id \}. |
| `FnOnObserversChanged` | `"engine::on-observers-changed"` | FnOnObserversChanged is called once per observer state change: \{ observer_id, function_id, target, state, reason? \}. |
| `FnOnLog` | `"observability::on-log"` | FnOnLog is called once per log record. |
| `FnOnSpan` | `"observability::on-span"` | FnOnSpan is called once per window of recorded spans: \{ trace_ids \}. |
| `FnOnConfigurationUpdate` | `"configuration::on-updated"` | FnOnConfigurationUpdate is called when a configuration entry is registered, updated or deleted. |
Log function paths. Mirrors LogFunctions in the Node SDK. Call these with `VoidAction` (fire-and-forget) to write to the engine log.
| Name | Value | Description |
| --- | --- | --- |
| `LogInfo` | `"engine::log::info"` | - |
| `LogWarn` | `"engine::log::warn"` | - |
| `LogError` | `"engine::log::error"` | - |
| `LogDebug` | `"engine::log::debug"` | - |
The codes of the stream errors: an `*InvocationError` with one of these Code values, returned by stream operations and by a call whose streams failed. Recover the code with errors.As:
```go
var ie *iii.InvocationError
if errors.As(err, &ie) && ie.Code == iii.CodeStreamAborted {
// the writer aborted: the data read so far is incomplete
}
```
| Name | Value | Description |
| --- | --- | --- |
| `CodeStreamAborted` | `"STREAM_ABORTED"` | CodeStreamAborted: the stream ended with an abort (its writer called `OutputStream.Abort`, failed, or went away before it closed), or could not be opened. The data read before it is not the whole stream. A call whose sink received an aborted stream fails with it too, even when the function succeeded. Through an engine pipe the Message is the engine's reason (channel writer aborted: closed with code 1011); in-process it is the writer's own. A call whose own sink failed (its Write, Flush or Close returned an error) fails with Message "the sink failed: <its error>", wrapping it (errors.Is and errors.As reach it), whatever the function returned. |
| `CodeStreamNotAllowed` | `"STREAM_NOT_ALLOWED"` | CodeStreamNotAllowed: a payload holding a stream sent with `EnqueueAction`. A queued job can run after the pipe expired, and a retry cannot read the stream again. Nothing was sent. |
| `CodeStreamClosed` | `"STREAM_CLOSED"` | CodeStreamClosed: a write or a send on a stream already closed or aborted, or after its reader left. |
| `CodeStreamInUse` | `"STREAM_IN_USE"` | CodeStreamInUse: a stream already in use: a second read of an `InputStream`, the same stream twice in one payload, or a stream sent on after it was read to the end or already sent. |
Features this SDK declares in its engine::workers::register payload. The engine advertises the first three in WorkerRegistered: observe.v2 includes observe.v1, and with it this worker runs the match and deliver hooks of the functions it hosts for their routed calls, whose observers' capture and filters the engine evaluates. FeatureLargeMessagesV1 is declared by the SDK only: it receives JSON messages up to 64 MiB, so the engine sends it messages of that size whatever version it reports.
| Name | Value | Description |
| --- | --- | --- |
| `FeatureObserveV1` | `"observe.v1"` | - |
| `FeatureObserveV2` | `"observe.v2"` | - |
| `FeatureObserveCapture` | `"observe.capture"` | FeatureObserveCapture: the host reads the outcomes that fire an observer from the fires_on of its observer views, never from capture, and sends no source.on. An engine with it announces fires_on on every view. |
| `FeatureLocalDispatchV1` | `"local-dispatch.v1"` | - |
| `FeatureLargeMessagesV1` | `"large-messages.v1"` | - |
Engine functions of the observer registry.
| Name | Value | Description |
| --- | --- | --- |
| `FnListObservers` | `"engine::observers::list"` | - |
| `FnGetObserver` | `"engine::observers::get"` | - |
| `FnDisposeObserver` | `"engine::observers::dispose"` | - |
| Name | Value | Description |
| --- | --- | --- |
| `DefaultEngineURL` | `"ws://127.0.0.1:49134"` | DefaultEngineURL is the worker WebSocket endpoint of a locally-running engine, used when neither an explicit address nor III_URL is set (see `EngineURLFromEnv`). The engine listens for workers here by default; its HTTP API is on :3111. The IPv4 loopback is spelled out on purpose: "localhost" can resolve to ::1 on a host whose engine only listens on IPv4. Same value as DEFAULT_ENGINE_URL in the Node, Python and Rust SDKs. |
| `DefaultInvocationTimeout` | `30 * time.Second` | DefaultInvocationTimeout bounds how long Call waits for an InvocationResult before failing with ErrTimeout, unless `WithInvocationTimeout` or `CallRequest`.Timeout says otherwise. Same default (30000 ms) as DEFAULT_INVOCATION_TIMEOUT_MS in the Node SDK. |
### iii/filter
Structural limits of a filter (the conformance vectors define how they count).
| Name | Value | Description |
| --- | --- | --- |
| `MaxDepth` | `8` | MaxDepth is the deepest a filter may nest; the top-level filter is at depth 1. |
| `MaxNodes` | `64` | MaxNodes bounds the operator and $or / $not nodes of one filter. |
| `MaxSetItems` | `256` | MaxSetItems bounds the items of one $in / $nin array. |
| `MaxPathSegments` | `16` | MaxPathSegments bounds the segments after a path's root. |
| `MaxEncodedBytes` | `8192` | MaxEncodedBytes bounds the UTF-8 size of the filter's compact JSON encoding. |
| `MaxSafeLiteral` | `1 << 53` | MaxSafeLiteral bounds numeric literals: \|n\| <= 2^53. |
| `MaxLiteralDepth` | `32` | MaxLiteralDepth bounds the arrays / objects nested in one $eq / $ne operand or one $in / $nin item (a scalar is 0, [] is 1). |
| `MaxJSONDepth` | `120` | MaxJSONDepth bounds the arrays / objects nested in the whole filter value, $and wrappers and literals included (\{\} is 1). |
## Variables
### iii
Sentinel errors for the two failure modes that carry no payload. Compare with errors.Is. These line up with the Rust IIIError::NotConnected / ::Timeout variants.
| Name | Value | Description |
| --- | --- | --- |
| `ErrNotConnected` | `errors.New("iii: not connected")` | ErrNotConnected is returned by Call when the client has no live connection and the call cannot be buffered (a call through an observer, or one cancelled by shutdown). |
| `ErrTimeout` | `errors.New("iii: invocation timed out")` | ErrTimeout is returned when no InvocationResult arrives within the call's timeout (DefaultInvocationTimeout unless overridden). |
| Name | Value | Description |
| --- | --- | --- |
| `EngineSources` | `struct { FunctionsChanged string; WorkersChanged string; ObserversChanged string; Log string; Span string; ConfigurationUpdated string }{FunctionsChanged: FnOnFunctionsChanged, WorkersChanged: FnOnWorkersChanged, ObserversChanged: FnOnObserversChanged, Log: FnOnLog, Span: FnOnSpan, ConfigurationUpdated: FnOnConfigurationUpdate}` | EngineSources are the ids of the engine-hosted sources under the names every SDK gives them (EngineSources in the Node, browser, Python and Rust SDKs): EngineSources.FunctionsChanged is `FnOnFunctionsChanged`, and so on.<br /><br />`client.ObserveFunction(iii.EngineSources.FunctionsChanged, "catalog::refresh")` |
## Types
### iii
Package iii is a Go SDK for the iii worker protocol.
[`Activation`](#activation) · [`AddedHook`](#addedhook) · [`Args`](#args) · [`Call`](#call) · [`CallAction`](#callaction) · [`CallRequest`](#callrequest) · [`Caller`](#caller) · [`Capture`](#capture) · [`ChannelDirection`](#channeldirection) · [`ConnectionState`](#connectionstate) · [`DecodedMessage`](#decodedmessage) · [`DeliverHook`](#deliverhook) · [`Dispatch`](#dispatch) · [`DroppedReports`](#droppedreports) · [`ErrorBody`](#errorbody) · [`Filters`](#filters) · [`FrameType`](#frametype) · [`FunctionOptions`](#functionoptions) · [`FunctionRef`](#functionref) · [`FunctionRegisteredMessage`](#functionregisteredmessage) · [`Handler`](#handler) · [`InputStream`](#inputstream) · [`Invocation`](#invocation) · [`InvocationError`](#invocationerror) · [`InvocationResultMessage`](#invocationresultmessage) · [`InvocationsObservedMessage`](#invocationsobservedmessage) · [`InvokeFunctionMessage`](#invokefunctionmessage) · [`LocalFunctionStats`](#localfunctionstats) · [`LocalInvocationStatsMessage`](#localinvocationstatsmessage) · [`MatchHook`](#matchhook) · [`MessageType`](#messagetype) · [`MiddlewareFunctionInput`](#middlewarefunctioninput) · [`ObserveMessage`](#observemessage) · [`ObserveMessageSource`](#observemessagesource) · [`ObserveMessageTarget`](#observemessagetarget) · [`ObserveReason`](#observereason) · [`ObserveRejectionError`](#observerejectionerror) · [`ObserveResultMessage`](#observeresultmessage) · [`Observed`](#observed) · [`ObservedItem`](#observeditem) · [`Observer`](#observer) · [`ObserverAckMessage`](#observerackmessage) · [`ObserverAddedMessage`](#observeraddedmessage) · [`ObserverHandle`](#observerhandle) · [`ObserverInfo`](#observerinfo) · [`ObserverOptions`](#observeroptions) · [`ObserverRemovedMessage`](#observerremovedmessage) · [`ObserverState`](#observerstate) · [`ObserverStateChangedMessage`](#observerstatechangedmessage) · [`Op`](#op) · [`Option`](#option) · [`OtelConfig`](#otelconfig) · [`OutputStream`](#outputstream) · [`PingMessage`](#pingmessage) · [`PongMessage`](#pongmessage) · [`ReattachMessage`](#reattachmessage) · [`ReconnectConfig`](#reconnectconfig) · [`RegisterFunctionMessage`](#registerfunctionmessage) · [`RegisterFunctionOptions`](#registerfunctionoptions) · [`RegisterServiceMessage`](#registerservicemessage) · [`RegistrationRejectedError`](#registrationrejectederror) · [`RegistrationRejectedMessage`](#registrationrejectedmessage) · [`RemovedHook`](#removedhook) · [`Source`](#source) · [`StreamChannelRef`](#streamchannelref) · [`StreamFrame`](#streamframe) · [`StreamInfo`](#streaminfo) · [`TelemetryOptions`](#telemetryoptions) · [`TypedHandler`](#typedhandler) · [`UnobserveMessage`](#unobservemessage) · [`UnregisterFunctionMessage`](#unregisterfunctionmessage) · [`WorkerRegisteredMessage`](#workerregisteredmessage)
#### Activation
Activation marks the invocation of an observer's target.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `ObserverID` | `string` | Yes | - |
| `ActivationID` | `string` | No | - |
---
#### AddedHook
AddedHook runs when an observer is added to a function this worker hosts, before the SDK acks it. Returning nil accepts the observer; an error built with `ObserveRejection` rejects it with that code, any other error with OBSERVE_REJECTED. ctx is cancelled after 30 s, when the observer fails with OWNER_TIMEOUT.
```go
type AddedHook func(ctx context.Context, obs *Observer) error
```
---
#### Args
Args are an observer's arguments, for the worker that hosts the observed function: validated against the function's args_format by the engine, and read by its hooks.
```go
type Args map[string]any
```
---
#### Call
Call is one call of a function, as its host sees it in a `MatchHook`, a `DeliverHook` and `Observer.Matches`. The fields of a call the SDK hands over are read-only.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `FunctionID` | `string` | Yes | - |
| `InvocationID` | `string` | Yes | - |
| `Status` | `string` | No | Status is "success" or "error". Empty reads as "error" when Error is set, and "success" otherwise. |
| `Input` | `json.RawMessage` | No | Input is the call's input, as the handler received it. |
| `Output` | `json.RawMessage` | No | Output is the handler's return value as JSON: what observers observe. Nil on an error. |
| `Error` | *[`ErrorBody`](#errorbody) | No | Error is the error the handler returned. Nil on success. |
| `Caller` | *[`Caller`](#caller) | No | Caller is who made the call; nil for a call made outside any handler. |
| `Metadata` | `json.RawMessage` | No | Metadata is the call's metadata sidecar; nil when it carries none. |
---
#### CallAction
CallAction mirrors the engine's CallAction enum, a "type"-tagged lowercase union: \{"type":"void"\} or \{"type":"enqueue","queue":"..."\}. It rides on InvokeFunction.Action (the wire field "action") and selects the delivery semantics of a `Client.Call`.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `Type` | `string` | Yes | Type is "void" (fire-and-forget) or "enqueue" (route via a named queue). |
| `Queue` | `string` | No | Queue is set only when Type == "enqueue". |
| `EnqueueAction` | func(queue string) *[`CallAction`](#callaction) | Yes | EnqueueAction routes an invocation through a named queue; the engine acknowledges with an enqueue receipt rather than the function's result. |
| `VoidAction` | func() *[`CallAction`](#callaction) | Yes | VoidAction returns the fire-and-forget action. A call with this action carries no invocation_id, so the engine sends no reply (see `Client.Call`). |
---
#### CallRequest
CallRequest is the input to `Client.Call`. The Action field selects the delivery semantics: nil/await (default) waits for the result; `VoidAction` is fire-and-forget; `EnqueueAction` routes through a named queue and awaits its receipt.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `FunctionID` | `string` | No | FunctionID is the function to invoke (e.g. an EngineFunctions constant). Empty with Observer. |
| `Observer` | *[`Observer`](#observer) | No | Observer calls through an observer of a function this worker hosts: the engine runs the observer's target with Payload as given, after checking that this worker hosts the observer's function (NOT_FUNCTION_OWNER) and that the observer exists and is active (OBSERVER_NOT_FOUND, OBSERVER_NOT_ACTIVE), and applies its policy (max_fires, expiry, max_in_flight: OVERFLOW), metadata sidecar and loop guard. The call goes out on the current connection, after the acks already sent on it; FunctionID, Namespace and an enqueue action do not apply. It takes no Metadata: the target's metadata is the observer's registration metadata, and Call refuses a request with Metadata before anything is sent. A call through an observer belongs in the function's `DeliverHook`, which applies the observer's filters with `Observer.Matches`; to send one observer something outside delivery (its initial state), call the function with metadata \{"for_observer": <obs.ID>\} (see `Observer.Accepted`). |
| `Payload` | `json.RawMessage` | No | Payload is the JSON input of the function (payload in the Node, Python and Rust SDKs). Nil is sent as \{\}. |
| `Data` | `json.RawMessage` | No | **Deprecated.** Use Payload. Data is the JSON input of the function, used only when Payload is nil. |
| `Metadata` | `json.RawMessage` | No | Metadata is optional per-invocation metadata (any JSON value) sent alongside the payload on the wire's metadata channel, not folded into it. nil and JSON null are no metadata: omitted, and the handler's MetadataFromContext reports none. |
| `Action` | *[`CallAction`](#callaction) | No | Action selects void/enqueue semantics; nil means the default await path. |
| `Timeout` | `time.Duration` | No | Timeout bounds an await/enqueue call. Zero means the client's invocation timeout: `WithInvocationTimeout`, else `DefaultInvocationTimeout`. |
| `Namespace` | `string` | No | Namespace routes the invocation to a specific namespace. Empty means this worker's namespace, except engine::\* and configuration::\* builtins, which resolve in the engine's default namespace. |
| `Dispatch` | [`Dispatch`](#dispatch) | No | Dispatch selects the path to a function this worker hosts: the zero value (or `DispatchAuto`) runs it in-process once the engine confirmed it for local dispatch; `DispatchRemote` always goes through the engine. |
---
#### Caller
Caller is who started an invocation: the worker (WorkerID / WorkerName, stamped by the engine and never forgeable), and the function and invocation the call was made from. Parent is the caller of that handler, one level only. Every field may be empty: a top-level call has no function.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `WorkerID` | `string` | No | - |
| `WorkerName` | `string` | No | - |
| `FunctionID` | `string` | No | - |
| `InvocationID` | `string` | No | - |
| `Parent` | *[`Caller`](#caller) | No | - |
---
#### Capture
Capture names a part of an observed invocation shipped to an observer's target. The default is input, output and caller. Capture also decides which outcomes fire the target: input and output fire on success, error on error; caller and metadata only add to the payload.
```go
type Capture string
```
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `CaptureInput` | `"input"` | Yes | - |
| `CaptureOutput` | `"output"` | Yes | - |
| `CaptureError` | `"error"` | Yes | - |
| `CaptureCaller` | `"caller"` | Yes | - |
| `CaptureMetadata` | `"metadata"` | Yes | - |
---
#### ChannelDirection
ChannelDirection is the end of an engine pipe a StreamChannelRef refers to. On the wire it is lowercase: "read" or "write".
```go
type ChannelDirection string
```
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `ChannelRead` | `"read"` | Yes | - |
| `ChannelWrite` | `"write"` | Yes | - |
---
#### ConnectionState
ConnectionState is the lifecycle state of a Client's WebSocket. Mirrors IIIConnectionState in the Node SDK.
```go
type ConnectionState string
```
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `StateDisconnected` | `"disconnected"` | Yes | - |
| `StateConnecting` | `"connecting"` | Yes | - |
| `StateConnected` | `"connected"` | Yes | - |
| `StateReconnecting` | `"reconnecting"` | Yes | - |
| `StateFailed` | `"failed"` | Yes | - |
---
#### DecodedMessage
DecodedMessage is the result of UnmarshalMessage: the decoded "type" plus exactly one populated variant pointer (the rest are nil). Callers switch on Type, or check which pointer is non-nil.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `Type` | [`MessageType`](#messagetype) | Yes | - |
| `RegisterFunction` | *[`RegisterFunctionMessage`](#registerfunctionmessage) | No | - |
| `UnregisterFunction` | *[`UnregisterFunctionMessage`](#unregisterfunctionmessage) | No | - |
| `InvokeFunction` | *[`InvokeFunctionMessage`](#invokefunctionmessage) | No | - |
| `InvocationResult` | *[`InvocationResultMessage`](#invocationresultmessage) | No | - |
| `RegisterService` | *[`RegisterServiceMessage`](#registerservicemessage) | No | - |
| `WorkerRegistered` | *[`WorkerRegisteredMessage`](#workerregisteredmessage) | No | - |
| `RegistrationRejected` | *[`RegistrationRejectedMessage`](#registrationrejectedmessage) | No | - |
| `Ping` | *[`PingMessage`](#pingmessage) | No | - |
| `Pong` | *[`PongMessage`](#pongmessage) | No | - |
| `Observe` | *[`ObserveMessage`](#observemessage) | No | - |
| `Unobserve` | *[`UnobserveMessage`](#unobservemessage) | No | - |
| `ObserverAck` | *[`ObserverAckMessage`](#observerackmessage) | No | - |
| `InvocationsObserved` | *[`InvocationsObservedMessage`](#invocationsobservedmessage) | No | - |
| `LocalInvocationStats` | *[`LocalInvocationStatsMessage`](#localinvocationstatsmessage) | No | - |
| `FunctionRegistered` | *[`FunctionRegisteredMessage`](#functionregisteredmessage) | No | - |
| `ObserverAdded` | *[`ObserverAddedMessage`](#observeraddedmessage) | No | - |
| `ObserverRemoved` | *[`ObserverRemovedMessage`](#observerremovedmessage) | No | - |
| `ObserveResult` | *[`ObserveResultMessage`](#observeresultmessage) | No | - |
| `ObserverStateChanged` | *[`ObserverStateChangedMessage`](#observerstatechangedmessage) | No | - |
| `UnmarshalMessage` | func(data []byte) (*[`DecodedMessage`](#decodedmessage), error) | Yes | UnmarshalMessage decodes a wire frame by peeking at "type" and then decoding into the matching variant struct. It is the Go counterpart of serde's tag dispatch. |
---
#### DeliverHook
DeliverHook delivers each call of one function itself. It receives the call and the observers that matched it (`MatchHook`, or every active observer), as they were when the call started. What it returns is the caller's result, encoded as a handler's is; the error it returns is the caller's error. iii delivers nothing for the function: the hook calls a target through its observer (`CallRequest`.Observer) and applies the observer's capture and filters with `Observer.Matches`. It runs inside the function's invocation, so calls made with ctx have that invocation as their caller.
```go
type DeliverHook func(ctx context.Context, call *Call, observers []*Observer) (any, error)
```
---
#### Dispatch
Dispatch selects how `Client.Call` reaches a function this worker hosts.
```go
type Dispatch string
```
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `DispatchAuto` | `"auto"` | Yes | DispatchAuto (the default, also the zero value) runs a function this worker hosts in-process once the engine confirmed it for local dispatch. |
| `DispatchRemote` | `"remote"` | Yes | DispatchRemote always goes through the engine. |
---
#### DroppedReports
DroppedReports counts report items the SDK dropped (BUFFER_FULL, TOO_LARGE, DISCONNECTED, INACTIVE).
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `FunctionID` | `string` | Yes | - |
| `Reason` | `string` | Yes | - |
| `Count` | `uint64` | Yes | - |
---
#### ErrorBody
ErrorBody is the wire representation of a remote error: a code, a message and an optional stack trace. It is intentionally minimal; a `Client.Call` caller receives it as an `InvocationError` (read it with errors.As).
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `Code` | `string` | Yes | - |
| `Message` | `string` | Yes | - |
| `Stacktrace` | `*string` | No | - |
| `Error` | `func() string` | Yes | - |
---
#### Filters
Filters is a declarative filter over input, output, error, caller and metadata, with explicit operators only (the language of the filter subpackage):
```go
iii.Filters{"input.amount": iii.Op{"$gte": 500}}
```
The engine evaluates them for the calls it routes, and the worker that hosts the function for the calls it makes to it in-process. Both match through an index of the observers' equality conditions: each observer is filed under one $eq of a scalar, or one $in of scalars, on a path of its filter's top-level $and, and costs a call nothing when the call's value at that path is none of that condition's values. A call evaluates the whole filter of the observers filed under its value and of those with no such condition.
```go
type Filters map[string]any
```
---
#### FrameType
FrameType tells the two kinds of frame a stream carries apart.
```go
type FrameType string
```
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `FrameBinary` | `"binary"` | Yes | FrameBinary is bytes: written with `OutputStream.Write`, read by `InputStream.Read` and the other byte reads. |
| `FrameText` | `"text"` | Yes | FrameText is a message: sent with `OutputStream.Send`, read by `InputStream.Messages`. |
---
#### FunctionOptions
FunctionOptions is another name for `RegisterFunctionOptions`, the one the cross-SDK specification uses.
```go
type FunctionOptions = RegisterFunctionOptions
```
---
#### FunctionRef
FunctionRef is the handle of a registered function, returned by `Client.RegisterFunction`, `Client.RegisterHTTPFunction` and `RegisterFunctionTyped`. It mirrors the FunctionRef of the Node SDK: its hook methods set the function's hooks by its id, and return the handle for chaining.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `ID` | `string` | Yes | ID is the function id given at registration. |
| `IsObserved` | `func() bool` | Yes | IsObserved reports whether any observer is active on the function: one atomic load, so a source checks it before building an event nobody would receive. False for a handle that does not control the function's current registration. |
| `IsObservedFor` | func(call *[`Call`](#call)) bool | Yes | IsObservedFor reports whether call would reach an observer, as `Client.IsObservedFor` does: on a function matched by keys (`MatchKeys`), whether an observer is filed under one of the call's keys; otherwise `FunctionRef.IsObserved`. False for a handle that does not control the function's current registration. |
| `Observers` | func() []*[`Observer`](#observer) | Yes | Observers returns the active observers of the function, as its host sees them. Empty for a handle that does not control the function's current registration. |
| `OnObservationDeliver` | func(hook [`DeliverHook`](#deliverhook)) *[`FunctionRef`](#functionref) | Yes | OnObservationDeliver sets the function's deliver hook, as `Client.OnObservationDeliverFor` does for its id, and returns the handle, for chaining. |
| `OnObservationMatch` | func(m *[`MatchHook`](#matchhook)) *[`FunctionRef`](#functionref) | Yes | OnObservationMatch sets the function's match hook, as `Client.OnObservationMatchFor` does for its id, and returns the handle, for chaining. |
| `OnObserverAdded` | func(hook [`AddedHook`](#addedhook)) *[`FunctionRef`](#functionref) | Yes | OnObserverAdded sets the function's added hook, as `Client.OnObserverAddedFor` does for its id, and returns the handle, for chaining. |
| `OnObserverRemoved` | func(hook [`RemovedHook`](#removedhook)) *[`FunctionRef`](#functionref) | Yes | OnObserverRemoved sets the function's removed hook, as `Client.OnObserverRemovedFor` does for its id, and returns the handle, for chaining. |
| `Unregister` | `func() error` | Yes | Unregister removes the function: the engine stops routing invocations to it, and a reconnect does not register it again. Its observe state is cleared as well: its observers are released (through the removed hooks), calls stop running in-process, and reports it still buffered are dropped. The hooks set for its id stay, for a later registration of the id. |
---
#### FunctionRegisteredMessage
FunctionRegisteredMessage is the RegisterFunction success ack, with the full current observer set. Always accepted: it replaces the set the SDK holds.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `ID` | `string` | Yes | - |
| `Namespace` | `string` | Yes | - |
| `Revision` | `uint64` | Yes | - |
| `LocalDispatch` | `bool` | Yes | - |
| `Observers` | [][`ObserverInfo`](#observerinfo) | Yes | - |
---
#### Handler
Handler is a registered function's implementation. data is the raw JSON the engine sent. The returned value is marshaled into the InvocationResult.result. Returning an error produces an InvocationResult.error; if the error is an \*InvocationError its code and stacktrace are preserved, otherwise it is reported with code "invocation_failed" (matching the Rust and Node SDKs).
Per-invocation metadata, when the call carries any, rides on ctx rather than the signature (so adding it is non-breaking): read it with `MetadataFromContext`.
```go
type Handler func(ctx context.Context, data json.RawMessage) (any, error)
```
---
#### InputStream
InputStream is the read side of a stream: the bytes (and messages) a function receives.
An InputStream arrives as a field of a handler's input or of a call's result (a "read" ref unmarshals to it), or is built to be sent: `InputStreamFromReader`, `InputStreamFromBytes`, or the input end of `Client.Pipe`. Put it in a call payload or a handler result (as a \*InputStream field, or in a map) and the SDK streams it to the other side.
Read it once, one way: as an `io.Reader` (Read), with `InputStream.ReadAll`, `InputStream.Text`, `InputStream.Lines`, `InputStream.Messages` (text frames) or `InputStream.Frames` (both kinds, in order). Byte reads skip messages. A second reader gets STREAM_IN_USE (`CodeStreamInUse`): Read is one reader across calls, and each of the other methods is a reader of its own. The socket opens on the first read. A stream read to the end returns io.EOF on further reads; one cancelled before its end (`InputStream.Cancel`, `InputStream.Close`, a break out of Lines, Messages or Frames, or the guard below) fails every later read, and a read in flight, with STREAM_CLOSED (`CodeStreamClosed`), never io.EOF.
An abort (its writer failed or called `OutputStream.Abort`) ends a read with an `*InvocationError` of code `CodeStreamAborted`, after the data sent before it.
In a handler, a stream the handler started reading and did not finish is cancelled when the handler returns (a goroutine still reading it gets STREAM_CLOSED: read it before returning); one never read is left alone. One sent on unread (in a call payload or the result) is forwarded: its ref goes, and no byte passes through this worker. One sent on after reading is pumped from where it is. A stream is sent once: sending it twice, or after it was read to the end, fails with STREAM_IN_USE.
A received stream binds to the client that received it (in a handler's input or a call's result); one unmarshalled from JSON that no client received binds to the only `Client` not yet closed, or call `InputStream.Bind`. An InputStream is a handle: copies of it are the same stream. Its methods are safe for concurrent use, but reads are not meant to be shared.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `InputStreamFromBytes` | func(data []byte) *[`InputStream`](#inputstream) | Yes | InputStreamFromBytes returns a stream of data. The stream keeps data: do not change it until the stream was read or sent. |
| `InputStreamFromReader` | func(r io.Reader) *[`InputStream`](#inputstream) | Yes | InputStreamFromReader returns a stream of what r yields, read in chunks of up to 64 KiB when the stream is read or sent. A read error aborts the stream with its message: the reader gets STREAM_ABORTED, not a short stream that looks complete. When r is an `io.Closer`, the stream closes it once it ends, fails or is cancelled (it owns r, as an http.Request owns its Body). |
| `Bind` | func(c *Client) *[`InputStream`](#inputstream) | Yes | Bind binds a received stream to c: its socket opens on c's engine, with c's handshake headers. Needed only for a stream unmarshalled from JSON that no client received, while several clients are alive. It returns s. |
| `Cancel` | `func()` | Yes | Cancel stops reading: the socket, if open, closes, and the engine then closes the writer, as it does when a reader leaves. A read in flight and every later read fail with STREAM_CLOSED (`CodeStreamClosed`): what was read is not the whole stream. A stream never read opens no socket; a local source is released (an io.Closer is closed). Of a reader that is not an io.Closer, a blocked Read is not cut short: the reads fail once it returns (`InputStreamFromReader`). Cancel does nothing to a stream read to the end, which keeps returning io.EOF. |
| `Close` | `func() error` | Yes | Close cancels the stream (see `InputStream.Cancel`) and returns nil, so an InputStream is an `io.ReadCloser`. After a Close before the end, reads fail with STREAM_CLOSED. |
| `Frames` | func(ctx context.Context) iter.Seq2[[`StreamFrame`](#streamframe), error] | Yes | Frames yields every frame of the stream in order: bytes (`FrameBinary`) and messages (`FrameText`). After an error it yields it and stops. Breaking out of the loop cancels the stream. |
| `JSONSchema` | `func() *jsonschema.Schema` | Yes | JSONSchema is the schema of a stream to read, for `RegisterFunctionTyped` and `InferSchema`: the ref object, marked with "x-iii-stream": "read". |
| `Lines` | `func(ctx context.Context) iter.Seq2[string, error]` | Yes | Lines yields the stream's lines, without their "\n" (or "\r\n"); the last one may have no newline. After an error it yields ("", err) and stops. Breaking out of the loop cancels the stream. |
| `MarshalJSON` | `func() ([]byte, error)` | Yes | MarshalJSON writes the stream as the ref that takes its place in a payload or a result: its own ref when it was received and not yet read (it is forwarded), else a placeholder the SDK replaces with the ref of a new pipe when the call or the answer is sent. Marshal a stream only to send it: a marshalled stream counts as sent. |
| `Messages` | `func(ctx context.Context) iter.Seq2[json.RawMessage, error]` | Yes | Messages yields the stream's messages (its text frames), each as JSON. A text frame that is not JSON yields its text as a JSON string. Bytes are skipped. After an error it yields (nil, err) and stops. Breaking out of the loop cancels the stream. |
| `Read` | `func(p []byte) (int, error)` | Yes | Read reads the stream's bytes (its binary frames) and implements `io.Reader`. It returns io.EOF once the writer closed the stream and everything was read. An abort is an error, never io.EOF: the bytes read so far are incomplete. Read is one reader: calls of Read continue each other, and another read method fails after it. |
| `ReadAll` | `func(ctx context.Context) ([]byte, error)` | Yes | ReadAll reads the whole stream (its binary frames) and returns its bytes. On an error, an abort included, it returns the bytes read so far with the error. ctx bounds the reads: when it ends, the stream is cancelled, and a read in flight returns, except a blocked Read of a reader that is not an io.Closer (`InputStreamFromReader`). |
| `Text` | `func(ctx context.Context) (string, error)` | Yes | Text reads the whole stream as text (its bytes, as a string). |
| `UnmarshalJSON` | `func(data []byte) error` | Yes | UnmarshalJSON reads a "read" ref as the stream it stands for: the one the invocation or the call result that received it tracks, the stream itself for a placeholder of this process, else a new stream of that ref. A "write" ref is an error: it is an `OutputStream`. |
---
#### Invocation
Invocation is the invocation a handler runs in, remote or local (`InvocationFromContext`).
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `FunctionID` | `string` | Yes | - |
| `InvocationID` | `string` | Yes | - |
| `Caller` | *[`Caller`](#caller) | No | Caller is who made the call; nil when the engine sent none (before 0.25). |
| `Activation` | *[`Activation`](#activation) | No | Activation is set when this invocation is the activation of an observer's target. |
| `ObserveDepth` | `uint32` | Yes | ObserveDepth is the depth of the causal chain in observe hops. |
| `InvocationFromContext` | func(ctx context.Context) ([`Invocation`](#invocation), bool) | Yes | InvocationFromContext returns the invocation a handler's ctx belongs to, remote or local. ok is false outside any handler. |
---
#### InvocationError
InvocationError wraps a remote ErrorBody returned by the engine in InvocationResult.error, annotated with the function that was invoked. It is the Go counterpart of Node's IIIInvocationError: one error type across all remote failure modes (RBAC FORBIDDEN, handler error, …), disambiguated by Code.
Recover the details with errors.As:
```go
var ie *iii.InvocationError
if errors.As(err, &ie) && ie.Code == "FORBIDDEN" { ... }
```
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `Code` | `string` | Yes | Code is the engine's machine-readable error code (e.g. "FORBIDDEN"). |
| `Message` | `string` | Yes | Message is the human-readable description. |
| `FunctionID` | `string` | No | FunctionID is the function whose invocation failed; empty if not known. |
| `Stacktrace` | `string` | Yes | Stacktrace is the remote stack trace, when the engine provides one. |
| `Error` | `func() string` | Yes | - |
| `Unwrap` | `func() error` | Yes | Unwrap is the local error behind e, nil for an error from the engine: for a call whose sink failed (STREAM_ABORTED, "the sink failed: ..."), the sink's own error, so errors.Is and errors.As reach it. |
---
#### InvocationResultMessage
InvocationResult is the worker's reply to a non-fire-and-forget InvokeFunction. InvocationID is REQUIRED (a value, not a pointer): a result with no id cannot be routed back to its caller. At most one of Result/Error is set.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `InvocationID` | `uuid.UUID` | Yes | - |
| `FunctionID` | `string` | Yes | - |
| `Result` | `json.RawMessage` | No | - |
| `Error` | *[`ErrorBody`](#errorbody) | No | - |
| `Traceparent` | `*string` | No | - |
| `Baggage` | `*string` | No | - |
| `Matched` | `[]string` | No | Matched lists, on an observe.v2 host's answer to a routed call of a function with a match hook, the observers the hook matched, each once ([] when it matched none): the engine evaluates the capture and filters of those that are active observers of the function, with the call's input, caller and metadata and this answer. Absent (nil) when the host did not narrow the call's observers: the engine then evaluates every active observer of the function. Decoded leniently, as the engine reads it: null is absent, a value that is not an array is [], and an id that is not a string is skipped. |
| `Delivered` | `bool` | No | Delivered is set on an observe.v2 host's answer to a routed call of a function whose deliver hook delivered the call: the engine activates no observer for it. It outweighs Matched. Only true sets it on decode. The engine strips both before forwarding a result to the caller. |
| `UnmarshalJSON` | `func(data []byte) error` | Yes | UnmarshalJSON decodes an InvocationResult, reading matched and delivered leniently, as the engine does: a malformed value never costs the result. |
---
#### InvocationsObservedMessage
InvocationsObservedMessage carries the matches of the local calls this worker delivered, batched. The engine delivers routed calls itself (InvocationResultMessage says which observers it evaluates).
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `Items` | [][`ObservedItem`](#observeditem) | Yes | - |
---
#### InvokeFunctionMessage
InvokeFunction is the engine->worker (and worker->engine, via Call) call.
InvocationID is a POINTER and omitempty: when absent, the call is fire-and-forget and no InvocationResult is expected. Traceparent/Baggage carry W3C trace context across the hop. Action selects void/enqueue semantics.
Metadata is OPTIONAL per-invocation metadata (arbitrary JSON) that travels as its own channel alongside Data, NOT folded into the payload. Like the engine's skip_serializing_if optional fields it is omitted when nil; an inbound frame without a metadata key decodes to nil ("no metadata"), so older engines that never send it stay backward compatible. Distinct from RegisterFunction's registration-level Metadata: this one is scoped to a single call.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `InvocationID` | `*uuid.UUID` | No | - |
| `FunctionID` | `string` | Yes | - |
| `Data` | `json.RawMessage` | Yes | - |
| `Metadata` | `json.RawMessage` | No | - |
| `Traceparent` | `*string` | No | - |
| `Baggage` | `*string` | No | - |
| `Action` | *[`CallAction`](#callaction) | No | - |
| `Namespace` | `string` | No | Namespace routes this invocation to a specific namespace. Absent means the engine's default namespace, independent of the caller's own namespace. |
| `Caller` | *[`Caller`](#caller) | No | Caller is who made the call. Worker -> engine: the handler the call was made from and its own caller; engine -> worker: also the calling worker, stamped by the engine. Sent and received only with observe.v1. |
| `ObserveDepth` | `uint32` | No | ObserveDepth is the depth of the causal chain in observe hops; 0 is omitted. |
| `Activation` | *[`Activation`](#activation) | No | Activation marks an observer activation (engine -> worker) or a call through an observer (worker -> engine, ObserverID only). |
| `UnmarshalJSON` | `func(data []byte) error` | Yes | UnmarshalJSON decodes an InvokeFunction, reading the observe fields (caller, observe_depth, activation) leniently: a malformed value is treated as absent rather than failing the frame, so the invocation is still answered. |
---
#### LocalFunctionStats
LocalFunctionStats counts one function's local invocations in a stats window.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `FunctionID` | `string` | Yes | - |
| `Count` | `uint64` | Yes | - |
| `Errors` | `uint64` | Yes | - |
| `DurationMsSum` | `float64` | Yes | - |
---
#### LocalInvocationStatsMessage
LocalInvocationStatsMessage reports local invocations and SDK-side report drops, periodically and only when non-zero.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `WindowMs` | `uint64` | Yes | - |
| `Functions` | [][`LocalFunctionStats`](#localfunctionstats) | No | - |
| `DroppedReports` | [][`DroppedReports`](#droppedreports) | No | - |
---
#### MatchHook
MatchHook says which observers want each call of one function; without one, every observer wants every call. Build it with `MatchFunc` (a predicate) or `MatchKeys` (keys the SDK indexes). The observers it matches are what iii delivers the call to, after their capture and filters, or what the function's `DeliverHook` receives. A nil MatchHook, and the zero one, match every observer.
A host that sends one observer something of its own (its initial state) calls the function with metadata \{"for_observer": <observer id>\}, and the hook gives such a call to that observer alone: a predicate compares the ids, and observerKeys also files each observer under "for_observer:<id>", the one key callKeys gives such a call.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `MatchFunc` | func(predicate func(obs *[`Observer`](#observer), call *[`Call`](#call)) bool) *[`MatchHook`](#matchhook) | Yes | MatchFunc is a match hook that asks predicate, once per active observer per call, whether the observer wants the call. A predicate that panics counts as no match, and the SDK logs it once per function. A nil predicate gives a nil MatchHook. |
| `MatchKeys` | func(observerKeys func(obs *[`Observer`](#observer)) []string, callKeys func(call *[`Call`](#call)) []string) *[`MatchHook`](#matchhook) | Yes | MatchKeys is a match hook by keys: an observer wants a call when they share a key, and the SDK keeps an index of the active observers by key instead of asking each of them. observerKeys says what an observer listens for: the SDK computes it once, when the observer is accepted, files the observer under each key and unfiles it when it is removed. An observer whose observerKeys panics is rejected with OBSERVE_REJECTED. callKeys says what a call is: the call matches the observers filed under any of its keys, each once; a callKeys that panics matches nothing, and the SDK logs it once per function. Keys express wildcards by listing them: an observer of every table is filed under "primary\|\*\|insert", and a change matches "primary\|orders\|insert", "primary\|orders\|\*", "primary\|\*\|insert" and "primary\|\*\|\*". A nil function gives a nil MatchHook. |
---
#### MessageType
MessageType is the value of the envelope "type" field: the lowercase name of the message variant, as the engine expects it.
```go
type MessageType string
```
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `MsgRegisterFunction` | `"registerfunction"` | Yes | - |
| `MsgUnregisterFunction` | `"unregisterfunction"` | Yes | - |
| `MsgInvokeFunction` | `"invokefunction"` | Yes | - |
| `MsgInvocationResult` | `"invocationresult"` | Yes | - |
| `MsgRegisterService` | `"registerservice"` | Yes | - |
| `MsgPing` | `"ping"` | Yes | - |
| `MsgPong` | `"pong"` | Yes | - |
| `MsgWorkerRegistered` | `"workerregistered"` | Yes | - |
| `MsgReattach` | `"reattach"` | Yes | - |
| `MsgRegistrationRejected` | `"registrationrejected"` | Yes | - |
| `MsgObserve` | `"observe"` | Yes | observe messages. The engine pushes functionregistered, observeradded and observerremoved only to connections that declared observe.v1. |
| `MsgUnobserve` | `"unobserve"` | Yes | - |
| `MsgObserveResult` | `"observeresult"` | Yes | - |
| `MsgObserverStateChanged` | `"observerstatechanged"` | Yes | - |
| `MsgFunctionRegistered` | `"functionregistered"` | Yes | - |
| `MsgObserverAdded` | `"observeradded"` | Yes | - |
| `MsgObserverRemoved` | `"observerremoved"` | Yes | - |
| `MsgObserverAck` | `"observerack"` | Yes | - |
| `MsgInvocationsObserved` | `"invocationsobserved"` | Yes | - |
| `MsgLocalInvocationStats` | `"localinvocationstats"` | Yes | - |
---
#### MiddlewareFunctionInput
MiddlewareFunctionInput is the payload the engine sends to the RBAC middleware function (the worker-manager rbac.middleware_function_id) on every function invocation that arrives through the RBAC port. The middleware can inspect, modify or reject the call before it reaches the target function: forward it with `Client.Call`, or return an error to reject it.
It mirrors MiddlewareFunctionInput in the Node and Rust SDKs field for field; the JSON names are the wire contract. Register the middleware with `RegisterFunctionTyped` to receive it decoded, or unmarshal the raw handler payload into it.
When forwarding, note that an empty Namespace means the engine's default namespace, whereas an empty `CallRequest.Namespace` means this worker's own namespace: pass "default" explicitly when Namespace is empty and the worker is namespaced.
```go
raw := []byte(`{"function_id":"orders::create","payload":{"item":"book"},"action":null,"context":{"source":"browser"},"namespace":"default"}`)
var in iii.MiddlewareFunctionInput
if err := json.Unmarshal(raw, &in); err != nil {
panic(err)
}
fmt.Println(in.FunctionID, in.Namespace, in.Action == nil)
fmt.Println(string(in.Payload), string(in.Context))
```
```go
client := iii.RegisterWorker(iii.DefaultEngineURL)
defer client.Close()
_, _ = iii.RegisterFunctionTyped(client, "auth::middleware",
func(ctx context.Context, in iii.MiddlewareFunctionInput) (json.RawMessage, error) {
var payload map[string]any
if err := json.Unmarshal(in.Payload, &payload); err != nil {
return nil, err
}
payload["_auth"] = in.Context
data, err := json.Marshal(payload)
if err != nil {
return nil, err
}
namespace := in.Namespace
if namespace == "" {
namespace = "default" // absent means the engine's default namespace
}
return client.Call(ctx, iii.CallRequest{
FunctionID: in.FunctionID,
Payload: data,
Action: in.Action,
Namespace: namespace,
})
})
```
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `FunctionID` | `string` | Yes | FunctionID is the ID of the function being invoked. |
| `Payload` | `json.RawMessage` | Yes | Payload is the payload sent by the caller, verbatim. Forward it as `CallRequest.Payload` or decode it to inspect the call. |
| `Action` | *[`CallAction`](#callaction) | No | Action is the routing action of the call, if any (nil for a synchronous request/response). Forward it as `CallRequest.Action` to keep enqueue/void semantics. |
| `Context` | `json.RawMessage` | Yes | Context is the auth context the RBAC auth function returned for this session (AuthResult.context in package helpers/workerconnection), as raw JSON. |
| `Namespace` | `string` | No | Namespace is the target namespace the invocation addressed; forward the call there to stay in the caller's namespace. Empty means the engine's default namespace. |
---
#### ObserveMessage
ObserveMessage creates, or idempotently replays, an observer owned by this connection: Source is the left side of `Client.Observe`, Target the right side.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `ID` | `string` | Yes | - |
| `Source` | [`ObserveMessageSource`](#observemessagesource) | Yes | - |
| `Target` | [`ObserveMessageTarget`](#observemessagetarget) | Yes | - |
| `Metadata` | `json.RawMessage` | No | - |
| `MaxFires` | `*uint64` | No | - |
| `ExpiresInMs` | `*uint64` | No | - |
| `MaxInFlight` | `*uint64` | No | - |
---
#### ObserveMessageSource
ObserveMessageSource is what an observer observes. Capture is omitted when nil and sent when empty (capture: [] is valid: a success with ids, status and timings only).
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `FunctionID` | `string` | Yes | - |
| `Namespace` | `string` | No | - |
| `Args` | `json.RawMessage` | No | - |
| `Filters` | `json.RawMessage` | No | - |
| `Capture` | [][`Capture`](#capture) | No | - |
---
#### ObserveMessageTarget
ObserveMessageTarget is the function an observer invokes.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `FunctionID` | `string` | Yes | - |
| `Namespace` | `string` | No | - |
---
#### ObserveReason
ObserveReason is why an observer is in its state: a machine-readable code and a message.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `Code` | `string` | Yes | - |
| `Message` | `string` | Yes | - |
---
#### ObserveRejectionError
ObserveRejectionError is an observe error carrying its code: what `ObserverHandle.Ready` returns when the observer turns error or disposed, what `Client.Observe` returns for an id a handle of the client holds (OBSERVER_ID_CONFLICT), and what an `AddedHook` returns (built with `ObserveRejection`) to reject an observer with a code of its own. Recover it with errors.As.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `Code` | `string` | Yes | - |
| `Message` | `string` | Yes | - |
| `Error` | `func() string` | Yes | - |
---
#### ObserveResultMessage
ObserveResultMessage is the engine's reply to an observe (also on a replay).
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `ID` | `string` | Yes | - |
| `State` | `string` | Yes | - |
| `Error` | *[`ErrorBody`](#errorbody) | No | - |
| `Warnings` | `[]string` | No | - |
---
#### Observed
Observed is what an observer's target receives when iii delivers: the top-level fields, plus whichever of the observer's capture apply to the outcome. Fields not captured, or that do not apply, are absent. Decode a target's payload into it:
```go
var ev iii.Observed
_ = json.Unmarshal(data, &ev)
```
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `ObserverID` | `string` | Yes | - |
| `ActivationID` | `string` | Yes | - |
| `FunctionID` | `string` | Yes | - |
| `Namespace` | `string` | Yes | - |
| `InvocationID` | `string` | Yes | - |
| `Status` | `string` | Yes | - |
| `Input` | `json.RawMessage` | No | - |
| `Output` | `json.RawMessage` | No | - |
| `Error` | *[`ErrorBody`](#errorbody) | No | - |
| `Caller` | *[`Caller`](#caller) | No | - |
| `Metadata` | `json.RawMessage` | No | - |
| `StartedAtMs` | `int64` | Yes | - |
| `DurationMs` | `float64` | Yes | - |
---
#### ObservedItem
ObservedItem is one reported call. Input, Output, Error and Metadata keep JSON null apart from absent: "output": null is a function that returned null, a nil Output was not captured or equals Input (OutputIsInput).
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `FunctionID` | `string` | Yes | - |
| `Namespace` | `string` | No | - |
| `InvocationID` | `string` | Yes | - |
| `Matched` | `[]string` | Yes | - |
| `Status` | `string` | Yes | - |
| `Input` | `json.RawMessage` | No | - |
| `Output` | `json.RawMessage` | No | - |
| `Error` | `json.RawMessage` | No | - |
| `Caller` | *[`Caller`](#caller) | No | - |
| `Metadata` | `json.RawMessage` | No | - |
| `StartedAtMs` | `int64` | Yes | - |
| `DurationMs` | `float64` | Yes | - |
| `ObserveDepth` | `uint32` | Yes | - |
| `Traceparent` | `*string` | No | - |
| `Baggage` | `*string` | No | - |
| `OutputIsInput` | `bool` | No | OutputIsInput: the handler returned its input, so the item carries Input once and the engine fills output from it. Sent only to engines with observe.v2. |
---
#### Observer
Observer is an observer as the worker that hosts the observed function sees it (in its hooks and in `Client.Observers`): its args, filters, target and capture. Never its metadata, policy or the observing worker. Its fields are set when it is added; the SDK keeps its own copy of what it reads, so changing them changes nothing but the host's view. The pointer is stable while the engine announces the same view of the observer, so hosts keep it in their own index (expression -> observers, route table).
The engine may announce an observer again with the same args and other filters, target or capture (a replay): it stays the same observer and no hook runs. From then on it is served, and listed by `Client.Observers`, as a new \*Observer with that view; Reject and Accepted act on the observer through either pointer, and pointers handed out earlier keep the view they were made with.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `ID` | `string` | Yes | - |
| `FunctionID` | `string` | Yes | FunctionID is the observed function (the one this worker hosts). |
| `Args` | `map[string]any` | No | Args are the observer's args, validated against args_format by the engine (numbers decode as float64; see DecodeArgs). |
| `Filters` | `map[string]any` | No | Filters are the observer's filters in normal form; iii's delivery and Matches apply them. |
| `Target` | `string` | Yes | Target is the target function id. |
| `Capture` | [][`Capture`](#capture) | No | Capture is what the target's payload carries, and the outcomes that fire it. |
| `Accepted` | `func(ctx context.Context) error` | Yes | Accepted waits until the SDK has acked the observer as accepted, and returns nil. A call made after that reaches an active observer, since the engine handles a connection's frames in order: a host sends a new observer its initial state this way, with a call of its own function whose metadata is \{"for_observer": <obs.ID>\}. The function's `MatchHook` gives that call to this observer alone, and iii delivers it like every call. It returns an \*`ObserveRejectionError` when the observer is rejected first (code OBSERVER_NOT_ACTIVE when it is removed, or its function released, first), and ctx's error when ctx is done first. Once accepted, it returns nil at once. |
| `DecodeArgs` | `func(v any) error` | Yes | DecodeArgs unmarshals the observer's args into v (a struct, typically). |
| `Matches` | func(call *[`Call`](#call)) bool | Yes | Matches reports whether call reaches the observer: it fires on the call's status (its view's fires_on) and its filters match the call. A deliver hook that calls targets itself checks it before calling through the observer; iii's delivery applies it on its own. On a call the SDK hands a hook, the observers share the call's decoded document and its values at the paths of the function's filter index, so each costs its own filter, and an observer costs a comparison when the call fails the condition it is filed under. |
| `Reject` | `func(code, message string)` | Yes | Reject sends a late rejection for this observer (e.g. after a config reload removed what it needs). It leaves the compiled set at once, so calls stop reaching it, and its removed hooks run next on the function's hook queue, connected or not; the engine's observerremoved that follows runs none again. The rejection is sent again when the engine replays the observer after a reconnect. Called while the observer's added hooks run, it rejects the observer once they return, and the removed hook of each level whose added hook resolved runs. |
---
#### ObserverAckMessage
ObserverAckMessage is the host's answer to one added observer, sent once every OnObserverAdded hook that applies to it has returned. Error rejects it; a host may re-send it with an error for an active observer (a late rejection).
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `FunctionID` | `string` | Yes | - |
| `Namespace` | `string` | No | - |
| `ID` | `string` | Yes | - |
| `Revision` | `uint64` | Yes | - |
| `Error` | *[`ErrorBody`](#errorbody) | No | - |
---
#### ObserverAddedMessage
ObserverAddedMessage attaches one observer to a function this connection hosts.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `FunctionID` | `string` | Yes | - |
| `Namespace` | `string` | Yes | - |
| `Revision` | `uint64` | Yes | - |
| `Observer` | [`ObserverInfo`](#observerinfo) | Yes | - |
---
#### ObserverHandle
ObserverHandle is what `Client.Observe` returns: the observing side of one observer. It is kept for replay, with the same id, on every connection until it is disposed. Safe for concurrent use.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `Dispose` | `func(ctx context.Context) error` | Yes | Dispose removes the observer (unobserve). It is not replayed on reconnect. An observer disposed while disconnected is unobserved on the next connection, before any observe is replayed, so a Reattach does not keep it alive. When the engine refused its observe (see `Client.Observe`), Dispose sends nothing. Its id is free at once: an Observe under it gets a new handle, which hears the engine's answers to its own observe only. ctx is reserved; Dispose does not wait for the engine. |
| `ID` | `func() string` | Yes | ID is the observer's id, stable across replays. |
| `OnStateChange` | func(listener func(state [`ObserverState`](#observerstate), reason *[`ObserveReason`](#observereason))) (unsubscribe func()) | Yes | OnStateChange calls listener on every state change, in order of the changes and of registration, on a goroutine of the handle's own (one change at a time; never on the SDK's read loop, so a listener may call the client). It returns the function that unsubscribes it; a change already queued is not delivered to it afterwards. |
| `Ready` | `func(ctx context.Context) error` | Yes | Ready waits until the observer is active. It returns an \*ObserveRejectionError carrying the code when the observer turns error or disposed first (INVALID_ARGS, INVALID_FILTER, FORBIDDEN, SELF_TARGET, an owner rejection, UNSUPPORTED against an engine without observe), and ctx's error when ctx is done first. |
| `Reason` | func() *[`ObserveReason`](#observereason) | Yes | Reason is why the observer is in its state (error, suspended, disposed), or nil. |
| `State` | func() [`ObserverState`](#observerstate) | Yes | State is the observer's current state. |
---
#### ObserverInfo
ObserverInfo is an observer as the host sees it: never its metadata, policy or the observing worker. Filters are in normal form.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `ID` | `string` | Yes | - |
| `Args` | `json.RawMessage` | No | - |
| `Filters` | `json.RawMessage` | No | - |
| `Target` | `string` | Yes | - |
| `Capture` | [][`Capture`](#capture) | No | - |
| `FiresOn` | `[]string` | No | FiresOn is the outcomes that fire it ("success", "error"), from an engine with observe.capture; nil from an older one, whose observers fire as On says. |
| `On` | `json.RawMessage` | No | On is the legacy on of an engine without observe.capture (absent: success; "error"; "complete"), read only when FiresOn is nil. Deprecated. |
---
#### ObserverOptions
ObserverOptions are the observer's own settings: its id, policy and metadata. A zero field is unset.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `ID` | `string` | No | ID defaults to a random UUID, stable across replays. |
| `MaxFires` | `uint64` | Yes | MaxFires disposes the observer after this many activations. |
| `ExpiresIn` | `time.Duration` | Yes | ExpiresIn disposes the observer after this long (millisecond precision). |
| `MaxInFlight` | `uint64` | Yes | MaxInFlight bounds the observer's concurrent activations. |
| `Metadata` | `json.RawMessage` | No | Metadata is delivered as the metadata sidecar of every activation (a JSON object). |
| `TargetNamespace` | `string` | No | TargetNamespace is the namespace of the target function; it defaults to this worker's. |
---
#### ObserverRemovedMessage
ObserverRemovedMessage detaches one observer.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `FunctionID` | `string` | Yes | - |
| `Namespace` | `string` | Yes | - |
| `Revision` | `uint64` | Yes | - |
| `ID` | `string` | Yes | - |
---
#### ObserverState
ObserverState is an observer's lifecycle: pending (no host yet, waiting for the host's ack, or no target yet) -> active or error; suspended while its worker or target is away; disposed at the end.
```go
type ObserverState string
```
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `ObserverPending` | `"pending"` | Yes | - |
| `ObserverActive` | `"active"` | Yes | - |
| `ObserverSuspended` | `"suspended"` | Yes | - |
| `ObserverError` | `"error"` | Yes | - |
| `ObserverDisposed` | `"disposed"` | Yes | - |
---
#### ObserverStateChangedMessage
ObserverStateChangedMessage is a lifecycle transition of an observer this connection owns.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `ID` | `string` | Yes | - |
| `State` | `string` | Yes | - |
| `Reason` | *[`ErrorBody`](#errorbody) | No | - |
| `Fires` | `uint64` | Yes | - |
---
#### Op
Op is the operator object of one filter path: iii.Op\{"$eq": "insert"\}.
```go
type Op map[string]any
```
---
#### Option
Option configures a Client. Pass options to New.
```go
type Option func(*Client)
```
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `WithDescription` | func(description string) [`Option`](#option) | Yes | WithDescription sets a one-line, human/LLM-readable summary of what this worker does. Surfaces in engine::workers::list / engine::workers::info. |
| `WithHeaders` | func(h http.Header) [`Option`](#option) | Yes | WithHeaders sets HTTP headers sent on the WebSocket handshake of the main connection and of the stream sockets of this client (see `InputStream` and `OutputStream`). The III_TOKEN environment variable, when set and not blank, adds "Authorization: Bearer <token>" unless h already carries an Authorization header. |
| `WithInvocationTimeout` | func(d time.Duration) [`Option`](#option) | Yes | WithInvocationTimeout sets how long `Client.Call` waits for a result when `CallRequest`.Timeout is zero, in place of `DefaultInvocationTimeout`. It is the invocationTimeoutMs option of the Node SDK's registerWorker. A d of zero or less keeps the default. |
| `WithMetricsReporting` | func(enabled bool) [`Option`](#option) | Yes | WithMetricsReporting turns the worker resource gauges on or off (Node enableMetricsReporting): the iii.worker.memory.\*, iii.worker.cpu.\*, iii.worker.event_loop.lag_ms and iii.worker.uptime_seconds metrics, tagged with worker.id and worker.name. The default is true. The gauges start when the engine acknowledges the worker and stop when the connection drops; they need telemetry and its metrics to be enabled (see `OtelConfig`). |
| `WithName` | func(name string) [`Option`](#option) | Yes | WithName sets the worker name reported to the engine. A non-empty III_WORKER_NAME takes precedence. The default is "hostname:pid". |
| `WithNamespace` | func(namespace string) [`Option`](#option) | Yes | WithNamespace sets the namespace this worker registers into. Takes precedence over the III_NAMESPACE environment variable. |
| `WithOtel` | func(cfg [`OtelConfig`](#otelconfig)) [`Option`](#option) | Yes | WithOtel configures the client's OpenTelemetry pipeline (the otel option of Node registerWorker). Telemetry starts with the connection lifecycle (`RegisterWorker` or `Client.Connect`) and `Client.Close` flushes and stops it. Without this option the defaults documented on `OtelConfig` apply, and they enable telemetry. |
| `WithReconnectConfig` | func(c [`ReconnectConfig`](#reconnectconfig)) [`Option`](#option) | Yes | WithReconnectConfig overrides the default reconnect schedule. |
| `WithTelemetry` | func(t [`TelemetryOptions`](#telemetryoptions)) [`Option`](#option) | Yes | WithTelemetry sets what the worker reports about its language, project and framework on every connection. Blank fields keep their defaults (see `TelemetryOptions`). |
---
#### OtelConfig
OtelConfig configures the OpenTelemetry pipeline a `Client` runs: spans, metrics and logs exported to the engine over a dedicated WebSocket at <engine address>/otel, the "execute <function id>" span around every handler, and the worker resource gauges. It mirrors the Node SDK's OtelConfig (the otel option of registerWorker) field for field. The engine URL and the handshake headers are not part of it: the client uses its own address and its `WithHeaders` headers (plus the III_TOKEN bearer), as Node does for engineWsUrl and engineWsHeaders.
Telemetry is enabled by default, as in the Node SDK: a client started without `WithOtel` exports unless OTEL_ENABLED is "false", "0", "no" or "off". A zero field means "not set": the environment variable named on the field, then the default, fills it in.
OpenTelemetry globals: when telemetry starts, the client installs its tracer provider, its meter provider and the W3C Trace Context + Baggage propagator as the OpenTelemetry globals (otel.Tracer, otel.Meter, otel.GetTextMapPropagator), each only while that global is still the otel default. A provider or propagator the application installed earlier, or another client installed first, is never replaced: first registration wins, as in the Node SDK. `Client.Close` puts the default back into every global that still holds this client's. The client's invocation spans and worker gauges, and the observability helpers (which use the client started last), always use the client's own providers, so they reach the engine either way. Spans the application creates with its own provider are parented to the invocation span through ctx and exported wherever that provider exports. Call and inbound invocations always propagate W3C Trace Context and Baggage, whatever the global propagator.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `Enabled` | `*bool` | No | Enabled turns telemetry export on or off. Nil reads OTEL_ENABLED ("false", "0", "no" or "off" disable it); the default is true. |
| `ServiceName` | `string` | No | ServiceName is the service.name resource attribute and the instrumentation scope of the SDK's tracer, meter and logger. Empty reads OTEL_SERVICE_NAME; the default is "iii-go". |
| `ServiceVersion` | `string` | No | ServiceVersion is the service.version resource attribute. Empty reads SERVICE_VERSION; the default is "unknown". |
| `ServiceNamespace` | `string` | No | ServiceNamespace is the service.namespace resource attribute, omitted when empty. Empty reads SERVICE_NAMESPACE. |
| `ServiceInstanceID` | `string` | No | ServiceInstanceID is the service.instance.id resource attribute. Empty reads SERVICE_INSTANCE_ID; the default is a random UUID. |
| `MetricsEnabled` | `*bool` | No | MetricsEnabled turns metrics export on or off. Nil reads OTEL_METRICS_ENABLED ("false", "0", "no" or "off" disable it); the default is true. |
| `MetricsExportInterval` | `time.Duration` | No | MetricsExportInterval is the period of the metrics export. Zero means 60 seconds. |
| `SpansFlushInterval` | `time.Duration` | No | SpansFlushInterval is how long an ended span waits in the batch before it is sent. Zero reads OTEL_SPANS_FLUSH_INTERVAL_MS (milliseconds); the default is 100ms. |
| `LogsFlushInterval` | `time.Duration` | No | LogsFlushInterval is how long a log record waits in the batch before it is sent. Zero reads OTEL_LOGS_FLUSH_INTERVAL_MS (milliseconds); the default is 100ms. |
| `LogsBatchSize` | `int` | No | LogsBatchSize is the maximum number of log records per export. Zero reads OTEL_LOGS_BATCH_SIZE; the default is 1. |
| `FetchInstrumentationEnabled` | `*bool` | No | FetchInstrumentationEnabled turns the HTTP client spans of observability.NewTransport and observability.NewHTTPClient on or off (the Go counterpart of Node's fetch instrumentation). Nil means true. |
| `ReconnectionConfig` | *[`ReconnectConfig`](#reconnectconfig) | No | ReconnectionConfig is the reconnect schedule of the telemetry WebSocket. Nil means `DefaultReconnectConfig`; a non-nil value is used as given. |
---
#### OutputStream
OutputStream is the write side of a stream: where a function writes bytes and messages.
An OutputStream arrives as a field of a handler's input or of a call's result (a "write" ref unmarshals to it), or is built around a local sink with `OutputStreamToWriter`: put it in a call payload and the function writes into the sink. The call returns once the sink got the whole stream (and fails with STREAM_ABORTED if the writer aborted it), within the call's timeout. A call whose result holds a stream to write (the function returned a write end) returns without waiting: the caller writes it.
`OutputStream.Write` sends bytes (in binary frames of up to 64 KiB) and `OutputStream.Send` a message (a JSON text frame); each returns once the frame was taken, so a loop of writes follows the reader's pace. End the stream with `OutputStream.Close`, or fail it with `OutputStream.Abort`: the reader then gets an error, not a short stream. A write after either fails with STREAM_CLOSED (`CodeStreamClosed`). `OutputStream.Writer` adapts it to an `io.Writer`. A byte sink made with OutputStreamToWriter takes the bytes only: messages are dropped.
In a handler, the stream is ended when the handler returns: one it used (wrote, sent on, or took a Writer of) is closed when the handler succeeded and aborted when it failed. One it never used is closed when it succeeded and left as is when it failed; in a call through an observer (an HTTP route, say) it is closed only when the handler returned nil (JSON null) and left as is with any other result, as the HTTP worker reads an untouched response with a value as a buffered response. Call `OutputStream.KeepOpen` to keep writing after the handler returned, and then close or abort it yourself.
A received stream binds to the client that received it; see `InputStream` for the rules and `OutputStream.Bind`. An OutputStream is a handle: copies of it are the same stream. Its methods are safe for concurrent use.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `OutputStreamToWriter` | func(w io.Writer) *[`OutputStream`](#outputstream) | Yes | OutputStreamToWriter returns a stream whose bytes go to w. Closing the stream flushes w (when it has a Flush() error method) and closes it (when it is an `io.Closer`); an abort closes w with the error when it has CloseWithError (an `*io.PipeWriter`) and otherwise leaves it as is, so a truncated stream is never finished as if whole: close it yourself, and remove a partly written file. |
| `Abort` | `func(reason string) error` | Yes | Abort fails the stream with reason: the reader's read ends with STREAM_ABORTED (through an engine pipe the reason the reader sees is the engine's). A stream never written is opened first, so its reader always learns of it. Aborting a stream already ended, or being closed, does nothing. Abort does not wait behind a Write or a Send in flight (one blocked by a reader that does not read): that write returns STREAM_CLOSED, and the stream ends at once. |
| `Bind` | func(c *Client) *[`OutputStream`](#outputstream) | Yes | Bind binds a received stream to c: its socket opens on c's engine, with c's handshake headers. Needed only for a stream unmarshalled from JSON that no client received, while several clients are alive. It returns s. |
| `Close` | `func() error` | Yes | Close ends the stream: the reader reads to the end. A stream never written is opened and closed, so its reader sees an empty stream. Closing a stream already ended, or sent on, does nothing. It implements `io.Closer`. |
| `JSONSchema` | `func() *jsonschema.Schema` | Yes | JSONSchema is the schema of a stream to write, for `RegisterFunctionTyped` and `InferSchema`: the ref object, marked with "x-iii-stream": "write". |
| `KeepOpen` | func() *[`OutputStream`](#outputstream) | Yes | KeepOpen keeps the stream open after the handler that received it returns: it is then this code's to close or abort. It returns s. |
| `MarshalJSON` | `func() ([]byte, error)` | Yes | MarshalJSON writes the stream as the ref that takes its place in a payload or a result: its own ref when it was received and not yet used (it is forwarded), else a placeholder the SDK replaces with the ref of a new pipe. Marshal a stream only to send it: a marshalled stream counts as sent. |
| `Send` | `func(ctx context.Context, message any) error` | Yes | Send sends message as a JSON text frame. A json.RawMessage is sent as it is. |
| `UnmarshalJSON` | `func(data []byte) error` | Yes | UnmarshalJSON reads a "write" ref as the stream it stands for (see `InputStream.UnmarshalJSON`). A "read" ref is an error: it is an `InputStream`. |
| `Write` | `func(ctx context.Context, data []byte) error` | Yes | Write writes data, in binary frames of up to 64 KiB, and returns once the socket took them. ctx bounds the write: when it ends mid-write, the socket closes without a close frame and the reader gets an abort. |
| `Writer` | `func(ctx context.Context) io.Writer` | Yes | Writer returns an `io.Writer` that writes to the stream with ctx. Taking it counts as using the stream. Close or abort the stream itself when done. |
---
#### PingMessage
PingMessage is the payloadless keepalive the engine sends; it serializes to \{"type":"ping"\}. The client replies with a PongMessage.
---
#### PongMessage
PongMessage is the payloadless reply to a PingMessage; it serializes to \{"type":"pong"\}.
---
#### ReattachMessage
Reattach is sent worker->engine as the first message of a reconnect, before the registration replay: PreviousWorkerID is the id the engine assigned via WorkerRegistered on the previous connection. The engine retires that connection so the replay lands on a clean slate instead of racing its cleanup.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `PreviousWorkerID` | `string` | Yes | - |
| `ReattachToken` | `string` | No | ReattachToken authorizes retiring the previous connection: worker ids are publicly listable, the token was only ever sent over that connection's own socket. |
---
#### ReconnectConfig
ReconnectConfig controls the exponential-backoff-with-jitter reconnect loop. The defaults below match the Node SDK's DEFAULT_BRIDGE_RECONNECTION_CONFIG exactly, so a Go worker reconnects on the same schedule as a Node one.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `InitialDelay` | `time.Duration` | Yes | InitialDelay is the delay before the first reconnect attempt. |
| `MaxDelay` | `time.Duration` | Yes | MaxDelay caps the backoff. |
| `BackoffMultiplier` | `float64` | Yes | BackoffMultiplier scales the delay after each failed attempt. |
| `JitterFactor` | `float64` | Yes | JitterFactor (0..1) randomizes each delay by up to ±JitterFactor to avoid a thundering herd of workers reconnecting in lockstep. |
| `MaxRetries` | `int` | No | MaxRetries caps reconnect attempts; -1 means retry forever (the default). |
| `DefaultReconnectConfig` | func() [`ReconnectConfig`](#reconnectconfig) | Yes | DefaultReconnectConfig is the reconnect schedule shared with the Node SDK: start at 1s, double each time, cap at 30s, ±30% jitter, retry forever. |
---
#### RegisterFunctionMessage
RegisterFunction announces a function this worker can handle. RequestFormat and ResponseFormat are optional JSON Schemas; Invocation is set only for externally HTTP-hosted functions (`Client.RegisterHTTPFunction`).
Optional fields are omitted when unset, as the engine writes them (skip_serializing_if); the engine reads an absent format and a JSON null alike. ArgsFormat, Private and Observable describe the function to the engine's observer registry; private: false and observable: true are the defaults and are omitted.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `ID` | `string` | Yes | - |
| `Description` | `*string` | No | - |
| `RequestFormat` | `json.RawMessage` | No | - |
| `ResponseFormat` | `json.RawMessage` | No | - |
| `Metadata` | `json.RawMessage` | No | - |
| `Invocation` | `*HTTPInvocationRef` | No | - |
| `ArgsFormat` | `json.RawMessage` | No | ArgsFormat is the JSON Schema of the observers' args; the engine validates them (INVALID_ARGS). Absent: the function takes no args. |
| `Private` | `bool` | No | Private: only the connection that hosts the function may call it (FORBIDDEN for anyone else); other workers may observe it. |
| `Observable` | `*bool` | No | Observable false refuses every observer (NOT_OBSERVABLE); absent means true. |
---
#### RegisterFunctionOptions
RegisterFunctionOptions configures a function registration. The zero value preserves the default registration shape. `FunctionOptions` is the same type.
ArgsFormat, Private and Observable false need an engine with observe.v2, as a match or deliver hook does: against an older one the function stays unregistered, and the SDK logs UNSUPPORTED once. What the worker does when the function is observed is set with hooks (`FunctionRef.OnObserverAdded` and its siblings).
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `Metadata` | `json.RawMessage` | No | Metadata is arbitrary JSON attached to the function registration. It is stored with the function and is distinct from the per-invocation metadata passed to handlers. |
| `LocalDispatch` | `*bool` | No | LocalDispatch false keeps every Call of this function on the engine path; nil or true lets Call run it in-process once the engine confirms it (see `Client.Call`: observers see snapshots of the payload and metadata taken at call start, and a handler may outlive a caller whose deadline passed). |
| `Description` | `string` | No | Description is a human/LLM-readable summary of the function, sent as "description" and surfaced by engine::functions::list and engine::functions::info. Empty omits it. |
| `RequestFormat` | `json.RawMessage` | No | RequestFormat is the JSON Schema of the function's request, sent as "request_format". It must be valid JSON; nil omits it. With `RegisterFunctionTyped` it replaces the schema inferred from Req. |
| `ResponseFormat` | `json.RawMessage` | No | ResponseFormat is the JSON Schema of the function's response, sent as "response_format": the handler's return value, which is what observers observe. It must be valid JSON; nil omits it. With `RegisterFunctionTyped` it replaces the schema inferred from Resp. |
| `ArgsFormat` | `json.RawMessage` | No | ArgsFormat is the JSON Schema of the observers' args, sent as "args_format": the engine validates every observer's args against it (INVALID_ARGS), and refuses a schema that is not valid (INVALID_ARGS_FORMAT). It must be valid JSON; nil means the function takes no args. |
| `Private` | `bool` | No | Private lets only this worker call the function (the engine answers anyone else with FORBIDDEN); other workers may observe it, and it cannot be an observer's target. A call this worker makes to it passes the input and the result by reference: the handler and the hooks treat both as read-only. |
| `Observable` | `*bool` | No | Observable false refuses every observer of the function (NOT_OBSERVABLE), for a function whose payloads carry credentials. nil means true. |
---
#### RegisterServiceMessage
RegisterService groups functions under a service for the dashboard.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `ID` | `string` | Yes | - |
| `Name` | `string` | Yes | - |
| `Description` | `*string` | No | - |
| `ParentServiceID` | `*string` | No | - |
---
#### RegistrationRejectedError
RegistrationRejectedError is the terminal error the engine returns when a worker's registration is refused for good, typically a WORKER_NAMESPACE_CONFLICT, where another live worker already owns this name in the namespace. It is delivered to every pending invocation and reported by `Client.FatalError`; the worker stops and does not reconnect. Mirrors the Node/Python/Rust SDKs.
Recover the details with errors.As:
```go
var re *iii.RegistrationRejectedError
if errors.As(err, &re) { ... re.Code, re.Namespace ... }
```
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `Code` | `string` | Yes | Code is the rejection code, e.g. "WORKER_NAMESPACE_CONFLICT". |
| `Namespace` | `string` | Yes | Namespace is the namespace the conflict occurred in. |
| `WorkerName` | `string` | Yes | WorkerName is the rejected worker name for a worker conflict. |
| `FunctionID` | `string` | Yes | FunctionID is the rejected function id for a function conflict. |
| `OwnerWorkerID` | `string` | Yes | OwnerWorkerID is the id of the worker that already owns the name. |
| `Error` | `func() string` | Yes | - |
---
#### RegistrationRejectedMessage
RegistrationRejectedMessage is the engine's refusal of a registration. A FUNCTION_NAMESPACE_CONFLICT costs one function and leaves the connection open; a WORKER_NAMESPACE_CONFLICT is terminal: another live worker owns this name in the namespace.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `Code` | `string` | Yes | - |
| `Namespace` | `string` | Yes | - |
| `WorkerName` | `string` | No | - |
| `FunctionID` | `string` | No | - |
| `OwnerWorkerID` | `string` | Yes | - |
---
#### RemovedHook
RemovedHook runs once for every accepted observer when it is removed (unobserve, disposal, late rejection with `Observer.Reject`). For an observer rejected before it is accepted (by another level's `AddedHook`, or by `Observer.Reject` while the added hooks run), it runs for each level whose `AddedHook` resolved. A panic is logged; the observer is removed either way.
```go
type RemovedHook func(ctx context.Context, obs *Observer)
```
---
#### Source
Source is the left side of `Client.Observe`: what is observed.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `FunctionID` | `string` | Yes | FunctionID is the observed function. |
| `Namespace` | `string` | No | Namespace defaults to this worker's (engine::\* and configuration::\* resolve to the engine's default namespace). |
| `Args` | [`Args`](#args) | Yes | Args go to the worker that hosts the function, which reads them in its hooks (a cron expression, a route, a table). A function without args_format takes none. |
| `Filters` | [`Filters`](#filters) | No | Filters decide which calls reach the target; nil matches every call. |
| `Capture` | [][`Capture`](#capture) | No | Capture is what the target's payload carries, and with it which outcomes fire the target. nil means the default (input, output, caller), which fires on success. Input and output fire on success, error fires on error; caller and metadata only add to the payload, so a non-empty Capture must name at least one of input, output, error (INVALID_ARGS otherwise). An empty, non-nil slice fires on success with the top-level fields only. \{error, caller\} fires on errors, \{input, error\} on both. |
---
#### StreamChannelRef
StreamChannelRef is the wire form of a stream: a capability handle to one end of an engine pipe. The engine's engine::channels::create returns a writer ref and a reader ref that share a channel_id; a ref travels as plain JSON inside a call payload or result, and the holder opens its own WebSocket to the pipe with it. In Go code a "read" ref is an `InputStream` and a "write" ref an `OutputStream`: unmarshal it into one, and the SDK makes and opens the pipes.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `ChannelID` | `string` | Yes | - |
| `AccessKey` | `string` | Yes | - |
| `Direction` | [`ChannelDirection`](#channeldirection) | Yes | - |
---
#### StreamFrame
StreamFrame is one frame of a stream, as `InputStream.Frames` yields it: bytes (Type `FrameBinary`) or a message (Type `FrameText`, Data holding the frame's text).
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `Type` | [`FrameType`](#frametype) | Yes | - |
| `Data` | `[]byte` | No | - |
---
#### StreamInfo
StreamInfo is a stream an observed call carried, as its observers see it: that a stream was passed, which way, and its channel id. It holds no bytes, and no access key.
An observer's target receives it in place of each stream ref under the Input and Output of an `Observed` payload. The engine still sends the ref (access key included) to the observer's worker: the SDK hides it, it does not keep it off the wire.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `Stream` | `bool` | Yes | Stream is always true: it marks the value as a stream. |
| `Direction` | [`ChannelDirection`](#channeldirection) | Yes | Direction is "read" for a stream the function read, "write" for one it wrote. |
| `ID` | `string` | Yes | ID is the channel id (a local stream's placeholder id for a call this worker dispatched in-process). |
---
#### TelemetryOptions
TelemetryOptions is what the worker reports about its language, project and framework in the telemetry object of engine::workers::register, shown by engine::workers::list and engine::workers::info. A blank field takes its default. Mirrors TelemetryOptions in the Node and Rust SDKs.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `Language` | `string` | No | Language reported for the worker. Default: the locale of LANG (else LC_ALL) without its encoding, for example "en_US" for LANG=en_US.UTF-8, which is the Node SDK's fallback; omitted when neither variable is set. |
| `ProjectName` | `string` | No | ProjectName is the project the worker belongs to. Default: the last element of the module path in the nearest go.mod, searched from the working directory upwards, skipping a major-version suffix such as /v2; omitted when there is no go.mod. |
| `Framework` | `string` | No | Framework the worker is built with. Default: "iii-go". Surrounding spaces are trimmed. |
---
#### TypedHandler
TypedHandler is a function handler with a typed request and response. The SDK unmarshals the invocation payload into Req before calling it and marshals the returned Resp into the result, so handlers work with concrete types instead of json.RawMessage.
Per-invocation metadata, when the call carries any, rides on ctx rather than the signature (so adding it is non-breaking): read it with `MetadataFromContext`.
```go
type TypedHandler[Req any, Resp any] func(ctx context.Context, req Req) (Resp, error)
```
---
#### UnobserveMessage
UnobserveMessage removes an observer this connection owns.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `ID` | `string` | Yes | - |
---
#### UnregisterFunctionMessage
UnregisterFunction removes a previously registered function.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `ID` | `string` | Yes | - |
---
#### WorkerRegisteredMessage
WorkerRegistered is sent engine->worker on connect to announce the worker's id. The worker treats it as informational.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `WorkerID` | `string` | Yes | - |
| `ReattachToken` | `string` | No | ReattachToken is the secret to present in a ReattachMessage on reconnect; empty on older engines. |
| `Features` | `[]string` | No | Features the engine supports, e.g. "observe.v1" and "local-dispatch.v1". Absent on engines before 0.25: observe is then unsupported. |
### iii/filter
Package filter is the observer filter language (iii-filter v1): validation and evaluation with the same semantics as the engine's evaluator and the other SDKs, pinned down by the conformance vectors all of them share.
[`Doc`](#doc) · [`Error`](#error) · [`ErrorCode`](#errorcode) · [`Filter`](#filter) · [`Map`](#map) · [`Root`](#root) · [`Roots`](#roots)
#### Doc
Doc is the document a filter reads: the value of each root, and whether it is present. A missing root is absent; a present nil is JSON null.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `Root` | func(root [`Root`](#root)) (value any, present bool) | Yes | - |
---
#### Error
Error is a filter the language rejects. Recover it with errors.As.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `Code` | [`ErrorCode`](#errorcode) | Yes | - |
| `Message` | `string` | Yes | - |
| `Error` | `func() string` | Yes | - |
---
#### ErrorCode
ErrorCode is the protocol error code of a rejected filter.
```go
type ErrorCode string
```
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `CodeInvalidFilter` | `"INVALID_FILTER"` | Yes | CodeInvalidFilter is a filter the language rejects. |
| `CodeInvalidFilterPath` | `"INVALID_FILTER_PATH"` | Yes | CodeInvalidFilterPath is a path a closed schema does not have. Only the engine checks schemas; this package never returns it. |
---
#### Filter
Filter is a validated filter, compiled once into a closure tree. It is immutable and safe for concurrent use.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `Compile` | func(src any) (*[`Filter`](#filter), error) | Yes | Compile validates and compiles a filter given as a Go value. A json.RawMessage or []byte is read as JSON text; any other value is read through encoding/json, so what is validated is exactly what travels on the wire. It returns an \*Error with code INVALID_FILTER when the filter is not valid. |
| `MatchAll` | func() *[`Filter`](#filter) | Yes | MatchAll returns the filter that matches every document (\{\}). |
| `Parse` | func(data []byte) (*[`Filter`](#filter), error) | Yes | Parse validates and compiles a filter given as JSON text. It returns an \*Error with code INVALID_FILTER when the filter is not valid. |
| `ParseNormalized` | func(data []byte) (*[`Filter`](#filter), error) | Yes | ParseNormalized compiles a filter in the normal form the engine pushes (functionregistered, observeradded). Every rule applies except the encoded size limit, which the engine checked on the filter as written (a normal form can be longer). |
| `IsMatchAll` | `func() bool` | Yes | IsMatchAll reports whether the filter matches every document. |
| `Matches` | func(doc [`Doc`](#doc)) (matched bool) | Yes | Matches evaluates the filter on doc. A nil doc has every root absent. It is total: a host value whose JSON encoding panics reads as no match. |
| `Roots` | func() [`Roots`](#roots) | Yes | Roots reports which roots the filter's clauses read. |
| `Source` | `func() map[string]any` | Yes | Source returns a copy of the filter as decoded JSON (numbers as json.Number). |
---
#### Map
Map is a Doc backed by a map keyed by root name: a missing key is an absent root, a nil value is JSON null. Keys other than the five roots are ignored.
```go
type Map map[string]any
```
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `Root` | func(root [`Root`](#root)) (any, bool) | Yes | Root implements Doc. |
---
#### Root
Root is a path's first segment: the part of the document it reads.
```go
type Root string
```
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `RootInput` | `"input"` | Yes | - |
| `RootOutput` | `"output"` | Yes | - |
| `RootError` | `"error"` | Yes | - |
| `RootCaller` | `"caller"` | Yes | - |
| `RootMetadata` | `"metadata"` | Yes | - |
---
#### Roots
Roots tells which document roots a filter's clauses read.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `Input` | `bool` | Yes | - |
| `Output` | `bool` | Yes | - |
| `Error` | `bool` | Yes | - |
| `Caller` | `bool` | Yes | - |
| `Metadata` | `bool` | Yes | - |
| `Has` | func(root [`Root`](#root)) bool | Yes | Has reports whether the filter reads root. |