Rust SDK

API reference for the iii SDK for Rust.

Link to this sectionInstallation

Terminal
cargo add iii-sdk

Link to this sectionInitialization

Link to this sectionregister_worker

Signature

register_worker(address: &str, options: InitOptions) -> IIIClient

Link to this sectionParameters

address&strrequired
optionsInitOptionsrequired
Show `InitOptions` fields
metadataOption<iii::WorkerMetadata>

Custom worker metadata. Auto-detected if None. In managed identity mode, process-wide identity variables override matching fields.

headersOption<HashMap<String, String>>

Custom HTTP headers sent during the WebSocket handshake, on the main connection and on the sockets of the streams bound to this client. Authorization: Bearer $III_TOKEN is added unless you set Authorization here.

otelOption<iii_helpers::observability::OtelConfig>

OpenTelemetry configuration.

namespaceOption<String>

Namespace this worker belongs to. In managed mode, resolution order is namespace > env III_NAMESPACE > None. In explicit mode, the environment is not used. It scopes more than the registration. The worker and its functions register here, and everything the worker does afterwards follows it: a IIIClient::call resolves its target here and an IIIClient::observe its source and target, unless they name another namespace.

identityWorkerIdentityModerequired

Selects whether process-wide managed identity variables can override this connection's metadata. Auxiliary connections should use WorkerIdentityMode::Explicit.

Link to this sectionMethods

Link to this sectionregister_function

Register a function with the engine.

Argument order matches the Node and Python SDKs: (id, registration).

Signature

register_function(id: impl Into<String>, registration: RegisterFunction) -> FunctionRef
idimpl Into<String>required

Unique identifier for the function.

registrationRegisterFunctionrequired

Built via [RegisterFunction::new], [RegisterFunction::new_async], or [RegisterFunction::http]. Chain .description(...), .metadata(...), .request_format(...), .response_format(...) as needed.

Show `RegisterFunction` fields
args_formatfn() -> Selfrequired

The JSON Schema of the observers' args, generated from T. The engine validates every observe against it (INVALID_ARGS) before the added hooks run, and they read the args with Observer::args. #[serde(deny_unknown_fields)] on T rejects argument typos. A function without it takes no args.

args_format_valuefn(schema: Value) -> Selfrequired

args_format from a JSON Schema value.

descriptionfn(desc: impl Into<String>) -> Selfrequired

Set the function description.

httpfn(config: HttpInvocationConfig) -> Selfrequired

Deprecated. HttpInvocationConfig is deprecated (iii-http-functions) and will be removed in an upcoming release. Behavior is unchanged for now. Migration guide: https://iii.dev/docs/upgrading/migrate-from-http-functions. Create a registration for an HTTP-invoked function (Lambda, Cloudflare Workers, etc.). No local handler runs.

local_dispatchfn(enabled: bool) -> Selfrequired

Whether calls to this function from this same worker may run in-process once the engine allows it. Default true.

metadatafn(meta: Value) -> Selfrequired

Set function metadata.

newfn(f: F) -> Selfrequired

Create a registration for a sync typed function.

new_asyncfn(f: F) -> Selfrequired

Create a registration for an async typed function.

observablefn(observable: bool) -> Selfrequired

false: nobody may observe the function (NOT_OBSERVABLE), for one whose payloads carry credentials. Default true.

privatefn() -> Selfrequired

Only this worker may call the function; any worker may observe it, and its observers receive every call this worker makes. The engine refuses a call from another connection (FORBIDDEN), and the function as an observer's target. For event sources, whose calls from anywhere else would be forged events.

request_formatfn(schema: Value) -> Selfrequired

Set the request format schema. Overrides any auto-extracted schema.

response_formatfn(schema: Value) -> Selfrequired

Set the response format schema. Overrides any auto-extracted schema.


Link to this sectioncall

Call a function: resolves to its result.

The routing behavior depends on the action field of the request:

  • No action: synchronous, waits for the function to return.
  • CallAction::Enqueue: async via named queue.
  • CallAction::Void: fire-and-forget.

A function this worker registered itself runs in-process once the engine allowed it ("local dispatch", see Dispatch): same result, error shape and timeout, and nothing on the wire unless an observer's filters match the call. A sync handler then runs inline on the caller's task, where the timeout cannot interrupt it: a sync handler that can block should be async, or registered with RegisterFunction::local_dispatch(false). CallRequest::dispatch with Dispatch::Remote forces the engine path. Calls made from inside a handler (or a deliver hook) carry that handler's invocation as their caller.

A request built with CallRequest::observer calls through that observer: the engine runs its target with the payload, as given.

Signature

async call(request: impl Into<CallRequestWithMetadata>) -> Result<Value, Error>
requestimpl Into<CallRequestWithMetadata>required
Show `CallRequestWithMetadata` fields
actionfn(action: CallAction) -> Selfrequired

How the call is routed; see CallRequest::action.

dispatchfn(dispatch: Dispatch) -> Selfrequired

Choose the path this call takes; see Dispatch.

metadatafn(metadata: Value) -> Selfrequired

Attach per-invocation metadata: any JSON value, which the handler receives as its metadata argument. Value::Null is the same as no metadata. A call through an observer (CallRequest::observer) takes none.

namespacefn(namespace: impl Into<String>) -> Selfrequired

Target a specific namespace for this invocation.

timeoutfn(timeout: Duration) -> Selfrequired

Override the default invocation timeout.

Show `CallRequest` fields
function_idStringrequired

ID of the function to invoke.

payloadValuerequired

Input data passed to the function.

actionOption<CallAction>

Sets how the call is routed. None for a synchronous request/response. Set a routing scheme otherwise (e.g. CallAction::Enqueue { .. }, CallAction::Void).

timeout_msOption<u64>

Override the default invocation timeout, in milliseconds.

dispatchfn(dispatch: Dispatch) -> CallRequestWithMetadatarequired

Choose the path this call takes: Dispatch::Auto (the default) runs a function this worker hosts in-process when the engine allows it; Dispatch::Remote always goes through the engine.

metadatafn(metadata: Value) -> CallRequestWithMetadatarequired

Attach per-invocation metadata without adding a required field to CallRequest struct literals.

namespacefn(namespace: impl Into<String>) -> CallRequestWithMetadatarequired

Target a specific namespace for this invocation without adding a required field to CallRequest struct literals. Serializes into Message::InvokeFunction's namespace.

newfn(function_id: impl Into<String>, payload: Value) -> Selfrequired

A synchronous request/response call of function_id with payload, the default timeout and no routing action.

observerfn(observer: &Observer, payload: Value) -> CallRequestWithMetadatarequired

A call through observer: the engine runs the observer's target with payload, as given, and applies the observer's policy, metadata sidecar and loop guard. Only the worker that hosts the observer's function may make it (NOT_FUNCTION_OWNER); it never runs in-process. It takes no metadata: the target's metadata argument is the observer's registration metadata, and IIIClient::call refuses a request given metadata before anything is sent. A host makes it in the function's deliver hook, or to send one observer something of its own, such as its initial state once it is accepted (see Observer::accepted).


Link to this sectionobserve

Observes source and calls target once per matching call.

source is a Source, or a function id for every successful call with the defaults. Returns at once, before the engine answered: the handle starts pending; ObserverHandle::ready resolves on active and fails on error (INVALID_ARGS, INVALID_FILTER, FORBIDDEN, NOT_OBSERVABLE, an added hook's rejection, UNSUPPORTED against an engine without observe). There is no inline handler: target is a registered function, and the observer stays pending until it is registered.

Signature

observe(source: impl Into<Source>, target: impl Into<Target>) -> ObserverHandle

Link to this sectionParameters

sourceimpl Into<Source>required
Show `Source` fields
argsfn(args: Value) -> Selfrequired

Args for the worker that hosts the function: what to set up for this observer and which calls it wants, validated against the function's args_format (INVALID_ARGS). The function's description says what they mean.

capturefn(capture: impl IntoIterator<Item = Capture>) -> Selfrequired

What the target's payload carries, and with it which outcomes fire the target. Default [input, output, caller].

filtersfn(filters: Value) -> Selfrequired

Which calls reach the target: a filter over input, output, error, caller and metadata, with explicit operators ({ "input.amount": { "$gte": 500 } }). Unset matches every call.

functionfn(function_id: impl Into<String>) -> Selfrequired

Observe function_id. Every function is observable.

function_idfn() -> &strrequired

The observed function id.

namespacefn(namespace: impl Into<String>) -> Selfrequired

The namespace the function is in. Unset, it resolves like a call: this worker's namespace (default for engine::* and configuration::*).

targetimpl Into<Target>required
Show `Target` fields
functionfn(function_id: impl Into<String>) -> Selfrequired
namespacefn(namespace: impl Into<String>) -> Selfrequired

The target's namespace. Unset, it resolves like a call.


Link to this sectiontrigger

call under its 0.25 name.

Signature

async trigger(request: impl Into<CallRequestWithMetadata>) -> Result<Value, Error>

Link to this sectionParameters

requestimpl Into<CallRequestWithMetadata>required
Show `CallRequestWithMetadata` fields
actionfn(action: CallAction) -> Selfrequired

How the call is routed; see CallRequest::action.

dispatchfn(dispatch: Dispatch) -> Selfrequired

Choose the path this call takes; see Dispatch.

metadatafn(metadata: Value) -> Selfrequired

Attach per-invocation metadata: any JSON value, which the handler receives as its metadata argument. Value::Null is the same as no metadata. A call through an observer (CallRequest::observer) takes none.

namespacefn(namespace: impl Into<String>) -> Selfrequired

Target a specific namespace for this invocation.

timeoutfn(timeout: Duration) -> Selfrequired

Override the default invocation timeout.


Link to this sectionclear_observation_deliver_for

Removes the deliver hook of function_id: iii delivers its calls.

Signature

clear_observation_deliver_for(function_id: &str) -> &Self

Link to this sectionParameters

function_id&strrequired

Link to this sectionclear_observation_match_for

Removes the match hook of function_id: every observer wants every call.

Signature

clear_observation_match_for(function_id: &str) -> &Self

Link to this sectionParameters

function_id&strrequired

Link to this sectionclear_observer_added

Removes the added hook set with on_observer_added.

Signature

clear_observer_added() -> &Self

Link to this sectionclear_observer_added_for

Removes the added hook of function_id.

Signature

clear_observer_added_for(function_id: &str) -> &Self

Link to this sectionParameters

function_id&strrequired

Link to this sectionclear_observer_removed

Removes the removed hook set with on_observer_removed.

Signature

clear_observer_removed() -> &Self

Link to this sectionclear_observer_removed_for

Removes the removed hook of function_id.

Signature

clear_observer_removed_for(function_id: &str) -> &Self

Link to this sectionParameters

function_id&strrequired

Link to this sectionengine_supports_observe

Whether the engine on the current connection supports observe: it advertised observe.v1 in its WorkerRegistered. None until that arrives, before the first connection and again while reconnecting.

Without it, observe() fails with UNSUPPORTED and the hooks of this worker's functions never run; a worker can keep a fallback for older engines when this is Some(false). Pair it with on_engine_supports_observe to follow changes across reconnects.

Signature

engine_supports_observe() -> Option<bool>

Link to this sectionExample

if worker.engine_supports_observe() == Some(false) {
    eprintln!("engine without observe: keeping the fallback");
}

Link to this sectionfatal_error

Fatal error that stopped the worker, if any. Set when the engine rejects registration (see Error::RegistrationRejected); the worker does not reconnect once this is populated.

Signature

fatal_error() -> Option<Error>

Link to this sectionget_connection_state

Get the current connection state.

Signature

get_connection_state() -> IIIConnectionState

Link to this sectionExample

if worker.get_connection_state() != IIIConnectionState::Connected {
    eprintln!("engine not reachable yet");
}

Link to this sectionis_observed

Whether function_id, a function this worker hosts, has any active observer.

Signature

is_observed(function_id: &str) -> bool

Link to this sectionParameters

function_id&strrequired

Link to this sectionis_observed_for

Whether call of function_id would reach any observer; see FunctionRef::is_observed_for.

Signature

is_observed_for(function_id: &str, call: &Call) -> bool

Link to this sectionParameters

function_id&strrequired
call&Callrequired
Show `Call` fields
function_idStringrequired
invocation_idStringrequired
statusInvocationStatusrequired
inputValuerequired
outputOption<Value>

The handler's return value; None when it failed.

errorOption<ObservedError>

What the handler failed with.

callerOption<Caller>

Who made the call; None for a call made outside any handler of a worker, or from an engine older than 0.25.

metadataOption<Value>

The call's metadata sidecar.


Link to this sectionnamespace

The effective worker namespace (resolved from InitOptions.namespace / III_NAMESPACE), or None for the engine's default.

Signature

namespace() -> Option<String>

Link to this sectionobserve_with

observe with the observer's id, policy and metadata.

An id (ObserverOptions::id) that a handle of this client holds, in any state, is refused at the call: nothing is sent, the holding handle and its observer are untouched, and the handle returned is in state error with the reason OBSERVER_ID_CONFLICT, observer id already in use: <id>. Its ready fails with that code, and its dispose sends nothing.

The id is free again as soon as dispose() is called on the handle that held it, before the engine confirms the disposal. The engine answers a connection's observes in the order it reads them, so each handle of the id gets the answers to its own observe and unobserve: a late disposed for the earlier observer never disposes the new one.

Signature

observe_with(source: impl Into<Source>, target: impl Into<Target>, options: ObserverOptions) -> ObserverHandle

Link to this sectionParameters

sourceimpl Into<Source>required
Show `Source` fields
argsfn(args: Value) -> Selfrequired

Args for the worker that hosts the function: what to set up for this observer and which calls it wants, validated against the function's args_format (INVALID_ARGS). The function's description says what they mean.

capturefn(capture: impl IntoIterator<Item = Capture>) -> Selfrequired

What the target's payload carries, and with it which outcomes fire the target. Default [input, output, caller].

filtersfn(filters: Value) -> Selfrequired

Which calls reach the target: a filter over input, output, error, caller and metadata, with explicit operators ({ "input.amount": { "$gte": 500 } }). Unset matches every call.

functionfn(function_id: impl Into<String>) -> Selfrequired

Observe function_id. Every function is observable.

function_idfn() -> &strrequired

The observed function id.

namespacefn(namespace: impl Into<String>) -> Selfrequired

The namespace the function is in. Unset, it resolves like a call: this worker's namespace (default for engine::* and configuration::*).

targetimpl Into<Target>required
Show `Target` fields
functionfn(function_id: impl Into<String>) -> Selfrequired
namespacefn(namespace: impl Into<String>) -> Selfrequired

The target's namespace. Unset, it resolves like a call.

optionsObserverOptionsrequired
Show `ObserverOptions` fields
expires_infn(expires_in: Duration) -> Selfrequired

Dispose of the observer after this long.

idfn(id: impl Into<String>) -> Selfrequired

The observer's id. Default: a random UUID v4, kept across replays.

max_firesfn(max_fires: u64) -> Selfrequired

Dispose of the observer after this many activations.

max_in_flightfn(max_in_flight: u32) -> Selfrequired

At most this many activations running at once; more queue in the engine, and a call through the observer fails with OVERFLOW.

metadatafn(metadata: Value) -> Selfrequired

Delivered as the metadata sidecar of every activation. The worker that hosts the function never sees it.


Link to this sectionobservers

The active observers of function_id, a function this worker hosts.

Signature

observers(function_id: &str) -> Vec<Observer>

Link to this sectionParameters

function_id&strrequired

Link to this sectionon_engine_supports_observe

Calls listener with the engine's observe support (see engine_supports_observe) when it becomes known and whenever a later connection's WorkerRegistered changes it (an engine upgraded or rolled back between reconnects). Not called for a reconnect to an engine that says the same, nor while reconnecting (the value is unknown then, not changed).

A listener is called with the current value right away when it is known; one added while it is not (before the first connection, while reconnecting) hears it from the next WorkerRegistered, the same value or not. Either way it sees every value from the current one on, in order. Listeners run on the same thread as ObserverHandle::on_state_change listeners, never on the connection's read loop: one may call the client.

Signature

on_engine_supports_observe(listener: F) -> ObserveSupportListener
listenerFrequired

Link to this sectionon_observation_deliver_for

Delivers each call of function_id with hook, which decides which observers get it and what its caller gets back; iii delivers nothing for the function. See DeliverHook.

A function with a deliver hook needs an engine that advertised observe.v2: against an older one it stays unregistered, and the SDK logs UNSUPPORTED once.

Signature

on_observation_deliver_for(function_id: &str, hook: impl DeliverHook) -> &Self

Link to this sectionParameters

function_id&strrequired
hookimpl DeliverHookrequired
Show `DeliverHook` fields
on_deliverfn(call: Call, observers: Vec<Observer>) -> impl Future<Output = Result<Value, Error>> + Send + '_required

Link to this sectionon_observation_match_for

Says which calls of function_id each observer wants; see Match. Set while observers are active, a key index is rebuilt from them.

A function with a match hook needs an engine that advertised observe.v2: against an older one it stays unregistered, and the SDK logs UNSUPPORTED once.

Signature

on_observation_match_for(function_id: &str, rule: Match) -> &Self

Link to this sectionParameters

function_id&strrequired
ruleMatchrequired
Show `Match` fields
Predicate(Arc<dyn Fn(&Observer, &Call) -> bool + Send + Sync>)required

Asked once per observation: for every call, once for each active observer, before its filters. A predicate that panics counts as no match for that observer, logged once per function.

Keys{ observer: Arc<dyn Fn(&'a Observer) -> Keys<'a> + Send + Sync>, call: Arc<dyn Fn(&'a Call) -> Keys<'a> + Send + Sync> }required

An observer wants a call when they share a key. The SDK computes an observer's keys once, when it is accepted, and files it under each (an observer whose key function panics is rejected with OBSERVE_REJECTED); a call's keys once per call. A call matches the observers filed under any of its keys, each once. Keys express wildcards by listing them: an observer of every table filed under "primary|*|insert", and a change matching "primary|orders|insert", "primary|orders|*", "primary|*|insert" and "primary|*|*": four lookups, whatever the number of observers.

keysfn(observer: O, call: C) -> Selfrequired

The keys an observer is filed under, and the keys a call matches. With them, FunctionRef::is_observed_for answers with one hash lookup per call key.

predicatefn(f: impl Fn(&Observer, &Call) -> bool + Send + Sync + 'static) -> Selfrequired

Does obs want call?


Link to this sectionon_observer_added

Runs hook when an observer is added to any function this worker hosts, before the function's own added hook. Returns the client, for chaining.

Signature

on_observer_added(hook: impl AddedHook) -> &Self

Link to this sectionParameters

hookimpl AddedHookrequired
Show `AddedHook` fields
on_addedfn(obs: Observer) -> impl Future<Output = Result<(), ObserveRejection>> + Send + '_required

Link to this sectionon_observer_added_for

Runs hook when an observer is added to function_id, after the worker's added hook. Set it before registering the function: then it runs for every observer.

Signature

on_observer_added_for(function_id: &str, hook: impl AddedHook) -> &Self

Link to this sectionParameters

function_id&strrequired
hookimpl AddedHookrequired
Show `AddedHook` fields
on_addedfn(obs: Observer) -> impl Future<Output = Result<(), ObserveRejection>> + Send + '_required

Link to this sectionon_observer_removed

Runs hook when an observer of any function this worker hosts is removed, after the function's own removed hook.

Signature

on_observer_removed(hook: impl RemovedHook) -> &Self

Link to this sectionParameters

hookimpl RemovedHookrequired
Show `RemovedHook` fields
on_removedfn(obs: Observer) -> impl Future<Output = ()> + Send + '_required

Link to this sectionon_observer_removed_for

Runs hook when an observer of function_id is removed, before the worker's removed hook.

Signature

on_observer_removed_for(function_id: &str, hook: impl RemovedHook) -> &Self

Link to this sectionParameters

function_id&strrequired
hookimpl RemovedHookrequired
Show `RemovedHook` fields
on_removedfn(obs: Observer) -> impl Future<Output = ()> + Send + '_required

Link to this sectionpipe

Creates a pipe on the engine and returns both ends: send 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, or the engine aborts it.

Most code does not need it: an InputStream built with from_reader/from_stream/from_bytes, or an OutputStream built with to_writer, put in a payload gets its pipe from the SDK.

Signature

async pipe() -> Result<Pipe, Error>

Link to this sectionset_namespace

Override the worker's target namespace (call before connect). Applied by register_worker after resolving InitOptions.namespace and III_NAMESPACE.

Signature

set_namespace(namespace: impl Into<String>)

Link to this sectionParameters

namespaceimpl Into<String>required

Link to this sectionshutdown

Shutdown the III client and wait for the connection thread to finish.

This stops the connection loop, sends a shutdown signal, and joins the background connection thread. OpenTelemetry is flushed inside the connection thread before it exits.

Signature

shutdown()

Link to this sectionExample

worker.shutdown();

Link to this sectionshutdown_async

Shutdown the III client.

This stops the connection loop and sends a shutdown signal, but it does not join connection_thread.

This method returns without waiting for run_connection() to finish, making it safe to call from an async context without stalling the executor; shutdown blocks and joins the thread. The OpenTelemetry flush (telemetry::shutdown_otel()) still runs inside the connection thread after run_connection() returns, so it may not complete unless shutdown is used to join the thread.

Signature

async shutdown_async()

Link to this sectionExample

worker.shutdown_async().await;

Link to this sectionwait_until_registered

Wait until the engine accepts this worker's initial registration.

Returns Error::RegistrationRejected for a fatal identity conflict, Error::Timeout when the deadline expires, and Error::NotConnected when called before the client starts or after it stops.

Signature

async wait_until_registered(timeout: Duration) -> Result<(), Error>

Link to this sectionParameters

timeoutDurationrequired

Link to this sectionFunctions

Link to this sectioncapture_fires

Signature

capture_fires(capture: &[Capture], success: bool) -> bool

Link to this sectionParameters

capture&[Capture]required
Show `Capture` fields
Inputunitrequired
Outputunitrequired
Errorunitrequired
Callerunitrequired
Metadataunitrequired
Unknown(String)required

A value this SDK does not know, kept verbatim.

as_strfn() -> &strrequired

The wire spelling.

successboolrequired

Link to this sectioncurrent_invocation

The invocation the calling task is running for, or None outside any handler (and in a task spawned from a handler without scope).

Signature

current_invocation() -> Option<InvocationCtx>

Link to this sectionscope

Runs fut with ctx as its current invocation. Use it to keep the handler's context in a task it spawns; None runs fut outside any invocation. The local-call nesting of the calling task is carried too, so recursing through spawned tasks stays bounded.

With an invocation, the calling handler's client and its stream guard are carried as well: a stream deserialized in the task binds to that client, and the handler's return settles it like the handler's own streams (see InputStream). Call OutputStream::keep_open on one the task keeps writing after the handler returned.

Signature

scope(ctx: impl Into<Option<InvocationCtx>>, fut: F) -> impl Future<Output = Output>

Link to this sectionParameters

ctximpl Into<Option<InvocationCtx>>required
Show `InvocationCtx` fields
function_idStringrequired

The function being invoked.

invocation_idStringrequired

This invocation's id (generated by the SDK for a local call).

callerOption<Caller>

Who made the call: the engine-stamped caller of a remote invocation, or this worker (with the calling handler) for a local one. None when the engine did not say (an engine older than 0.25).

activationOption<Activation>

Set when this invocation is an observer activation, or the target's call of a call through an observer.

observe_depthu32required

Depth of the causal chain in observe hops; 0 outside observers.

metadataOption<Value>

The invocation's metadata sidecar.

traceparentOption<String>

W3C trace context of the invocation's execute span, when tracing is on: the deliveries of its call join its trace.

baggageOption<String>

W3C baggage of the invocation.

futFrequired

Link to this sectionTypes

Link to this sectioniii_sdk

EnqueueResult · InitOptions · ObserveSupportListener · RegisterFunction · TelemetryOptions

Link to this sectionEnqueueResult

Result returned when a function is called with CallAction::Enqueue.

NameTypeRequiredDescription
message_receipt_idStringYesUnique receipt ID for the enqueued message.

Link to this sectionInitOptions

Configuration options passed to register_worker.

NameTypeRequiredDescription
metadataOption<iii::WorkerMetadata>NoCustom worker metadata. Auto-detected if None. In managed identity
mode, process-wide identity variables override matching fields.
headersOption<HashMap<String, String>>NoCustom HTTP headers sent during the WebSocket handshake, on the main
connection and on the sockets of the streams bound to this client.
Authorization: Bearer $III_TOKEN is added unless you set
Authorization here.
otelOption<iii_helpers::observability::OtelConfig>NoOpenTelemetry configuration.
namespaceOption<String>NoNamespace this worker belongs to. In managed mode, resolution order is
namespace > env III_NAMESPACE > None. In explicit mode, the
environment is not used.

It scopes more than the registration. The worker and its functions
register here, and everything the worker does afterwards follows it: a
IIIClient::call resolves its target here and an
IIIClient::observe its source and target, unless they name
another namespace.
identityWorkerIdentityModeYesSelects whether process-wide managed identity variables can override
this connection's metadata. Auxiliary connections should use
WorkerIdentityMode::Explicit.

Link to this sectionObserveSupportListener

A listener added with IIIClient::on_engine_supports_observe.

NameTypeRequiredDescription
unsubscribefn()YesStops calling the listener: once this returns no call starts, queued ones included (a call already running finishes).

Link to this sectionRegisterFunction

Function registration builder.

The function ID is supplied separately at registration time via IIIClient::register_function, RegisterFunction only carries the handler and optional metadata.

Constructors:

  • RegisterFunction::new: sync function. Accepts both typed handlers (schemas auto-extracted via schemars) and Fn(Value, Option<Value>) -> Result<Value, Error> closures. The second argument is the per-invocation metadata sidecar and is None when absent. A Value input or result passes as is; other types go through serde.
  • RegisterFunction::new_async: async equivalent of new.
  • RegisterFunction::http: function invoked over HTTP (Lambda, Cloudflare Workers, etc.).

Builder methods (all consume self):

  • description
  • metadata
  • request_format: overrides any auto-extracted schema.
  • response_format: overrides any auto-extracted schema; it describes what observers observe.
  • args_format: the observers' args.
  • private: only this worker calls it.
  • observable: false refuses every observer.
  • local_dispatch: opt out of in-process calls.

The handler's return value is what observers observe. An event source's handler returns the event it is called with. What the worker does when the function is observed is set with hooks: see hooks.

NameTypeRequiredDescription
args_formatfn() -> SelfYesThe JSON Schema of the observers' args, generated from T. The engine validates every observe against it (INVALID_ARGS) before the added hooks run, and they read the args with Observer::args. #[serde(deny_unknown_fields)] on T rejects argument typos. A function without it takes no args.
args_format_valuefn(schema: Value) -> SelfYesargs_format from a JSON Schema value.
descriptionfn(desc: impl Into<String>) -> SelfYesSet the function description.
httpfn(config: HttpInvocationConfig) -> SelfYesDeprecated. HttpInvocationConfig is deprecated (iii-http-functions) and will be removed in an upcoming release. Behavior is unchanged for now. Migration guide: https://iii.dev/docs/upgrading/migrate-from-http-functions. Create a registration for an HTTP-invoked function (Lambda, Cloudflare Workers, etc.). No local handler runs.
local_dispatchfn(enabled: bool) -> SelfYesWhether calls to this function from this same worker may run in-process once the engine allows it. Default true.
metadatafn(meta: Value) -> SelfYesSet function metadata.
newfn(f: F) -> SelfYesCreate a registration for a sync typed function.
new_asyncfn(f: F) -> SelfYesCreate a registration for an async typed function.
observablefn(observable: bool) -> SelfYesfalse: nobody may observe the function (NOT_OBSERVABLE), for one whose payloads carry credentials. Default true.
privatefn() -> SelfYesOnly this worker may call the function; any worker may observe it, and its observers receive every call this worker makes. The engine refuses a call from another connection (FORBIDDEN), and the function as an observer's target. For event sources, whose calls from anywhere else would be forged events.
request_formatfn(schema: Value) -> SelfYesSet the request format schema. Overrides any auto-extracted schema.
response_formatfn(schema: Value) -> SelfYesSet the response format schema. Overrides any auto-extracted schema.

Link to this sectionTelemetryOptions

Worker metadata reported to the engine (language, framework, project).

NameTypeRequiredDescription
languageOption<String>NoProgramming language of the worker.
project_nameOption<String>NoName of the project this worker belongs to.
frameworkOption<String>NoFramework name, if applicable.

Link to this sectioniii_sdk::channels

ChannelDirection · ChannelItem · StreamChannelRef

Link to this sectionChannelDirection

Which end of a pipe a StreamChannelRef opens: read is received as an InputStream, write as an OutputStream.

NameTypeRequiredDescription
ReadunitYes-
WriteunitYes-

Link to this sectionChannelItem

One frame of a stream: a text frame carries a message, a binary frame bytes.

NameTypeRequiredDescription
Text(String)Yes-
Binary(Vec<u8>)Yes-

Link to this sectionStreamChannelRef

One end of an engine pipe as a payload carries it: { channel_id, access_key, direction }. The JSON is the same in every SDK and release, so new and old SDKs read each other's refs.

NameTypeRequiredDescription
channel_idStringYes-
access_keyStringYes-
directionChannelDirectionYes-

Link to this sectioniii_sdk::context

InvocationCtx

Link to this sectionInvocationCtx

The invocation a handler is running for.

NameTypeRequiredDescription
function_idStringYesThe function being invoked.
invocation_idStringYesThis invocation's id (generated by the SDK for a local call).
callerOption<Caller>NoWho made the call: the engine-stamped caller of a remote invocation,
or this worker (with the calling handler) for a local one. None when
the engine did not say (an engine older than 0.25).
activationOption<Activation>NoSet when this invocation is an observer activation, or the target's
call of a call through an observer.
observe_depthu32YesDepth of the causal chain in observe hops; 0 outside observers.
metadataOption<Value>NoThe invocation's metadata sidecar.
traceparentOption<String>NoW3C trace context of the invocation's execute span, when tracing is
on: the deliveries of its call join its trace.
baggageOption<String>NoW3C baggage of the invocation.

Link to this sectioniii_sdk::engine

EngineFunctions · EngineSources

Link to this sectionEngineFunctions

Engine function ids for internal operations.


Link to this sectionEngineSources

The ids of the engine-hosted sources: private functions the engine calls once per event, whose handler returns the event. Observe them with filters on their input:

iii.observe(
    Source::function(EngineSources::FUNCTIONS_CHANGED),
    "catalog::refresh",
);
iii.observe(
    Source::function(EngineSources::LOG).filters(json!({ "input.level": { "$eq": "error" } })),
    "alerts::on-error-log",
);

Link to this sectioniii_sdk::errors

Error · InvocationError

Link to this sectionError

Errors returned by the III SDK.

NameTypeRequiredDescription
NotConnectedunitYes-
TimeoutunitYes-
Runtime(String)Yes-
Remote{ code: String, message: String, stacktrace: Option<String> }Yes-
Handler(String)Yes-
Serde(String)Yes-
WebSocket(String)Yes-
StreamAborted{ reason: String }YesA stream ended with an abort, code STREAM_ABORTED
(protocol::STREAM_ABORTED): its
writer called OutputStream::abort,
failed or went away before it closed. 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 reason is the engine's (channel writer<br />aborted: ...); in-process it is the writer's own.
StreamNotAllowed(String)YesA call that cannot carry a stream, code STREAM_NOT_ALLOWED
(protocol::STREAM_NOT_ALLOWED):
a payload holding a stream sent with
CallAction::Enqueue. Nothing was sent.
StreamClosed(String)YesA stream used after it ended, code STREAM_CLOSED
(protocol::STREAM_CLOSED): a
write or send on a stream already closed or aborted, or after its
reader left, and a read of an InputStream
that was cancelled (by
InputStream::cancel, or when its
handler returned before reading it to the end). A cancelled stream
never ends as if it were complete.
StreamInUse(String)YesA stream already in use, code STREAM_IN_USE
(protocol::STREAM_IN_USE): a
second reader (a clone included), the same stream twice in one
payload, or a stream sent on after it was read to the end or already
sent.
RegistrationRejected{ code: String, namespace: String, worker_name: Option<String>, function_id: Option<String>, owner_worker_id: String }YesFatal registration rejection: another live worker already holds this
worker name in the namespace, or the engine sent a rejection that
names no function with a code this SDK does not know. The SDK stops
and does not reconnect. A rejection that names a function
(FUNCTION_NAMESPACE_CONFLICT, INVALID_ARGS_FORMAT, UNSUPPORTED)
refuses only that function, is logged, and does not produce this
error.
codefn() -> Option<&str>YesThe wire code of this error, when it has one: the code of a remote failure or a registration rejection, TIMEOUT for Error::Timeout, and the stream codes: STREAM_ABORTED, STREAM_NOT_ALLOWED, STREAM_CLOSED, STREAM_IN_USE.
invocation_errorfn() -> Option<InvocationError>YesIf this is a remote invocation failure (Error::Remote), return its structured form. Returns None for transport/serde/handler errors.

Link to this sectionInvocationError

Structured invocation failure, mirroring the Node and Python InvocationError.

Produced from the Error::Remote variant via Error::invocation_error. function_id is None from that accessor because the wire Remote payload does not carry it.

NameTypeRequiredDescription
codeStringYes-
messageStringYes-
function_idOption<String>No-
stacktraceOption<String>No-

Link to this sectioniii_sdk::hooks

AddedHook · Call · DeliverHook · Keys · Match · RemovedHook

Link to this sectionAddedHook

Runs when an observer is added to a function this worker hosts, before the SDK accepts it: what it sets up is in place before the observer's first call. Returning an error rejects the observer: an ObserveRejection sets the code, any other error (? on an Error, a failed call's included) is OBSERVE_REJECTED, and a hook still running after 30 s is OWNER_TIMEOUT.

Implemented for async closures taking the Observer by value. Implement with plain async fn, without #[async_trait]. The returned future is Send and may borrow self across .await. This trait is not dyn-compatible; pass a concrete hook to IIIClient::on_observer_added.

NameTypeRequiredDescription
on_addedfn(obs: Observer) -> impl Future<Output = Result<(), ObserveRejection>> + Send + '_Yes-

Link to this sectionCall

One call of a function this worker hosts, as its observers observe it.

output is the handler's return value: what observers observe. A source that asks FunctionRef::is_observed_for before calling fills in only what its Match::keys read:

let call = Call { input: json!({ "expression": "0 * * * * * *" }), ..Call::default() };
NameTypeRequiredDescription
function_idStringYes-
invocation_idStringYes-
statusInvocationStatusYes-
inputValueYes-
outputOption<Value>NoThe handler's return value; None when it failed.
errorOption<ObservedError>NoWhat the handler failed with.
callerOption<Caller>NoWho made the call; None for a call made outside any handler of a
worker, or from an engine older than 0.25.
metadataOption<Value>NoThe call's metadata sidecar.

Link to this sectionDeliverHook

Delivers each call of one function itself, in place of iii's delivery: what it returns (or fails with) is the call's result, and iii delivers nothing for the function. For a function whose observers' answers matter (an HTTP route's response, a queue subscriber's ack) or whose calls each go to one observer, called through with CallRequest::observer.

It runs after the handler, inside the function's invocation context and span, so calls it makes have the function's invocation as their caller. It receives the call and the observers that matched it (Match, or all of them), a snapshot taken when the call started. It applies their filters with Observer::matches.

Implemented for async closures taking (Call, Vec<Observer>). Implement with plain async fn, without #[async_trait]. The returned future is Send and may borrow self across .await. This trait is not dyn-compatible; pass a concrete hook to IIIClient::on_observation_deliver_for.

NameTypeRequiredDescription
on_deliverfn(call: Call, observers: Vec<Observer>) -> impl Future<Output = Result<Value, Error>> + Send + '_Yes-

Link to this sectionKeys

The keys an observer is filed under, or a call matches, for Match::keys: none, one or several. Converts from &str, String, their Options and Vecs. Keys borrowed from the observer or the call cost no allocation.

NameTypeRequiredDescription
nonefn() -> SelfYesNo key: an observer filed nowhere, a call that matches nobody.

Link to this sectionMatch

Which calls of a function each observer wants: the function's match hook (IIIClient::on_observation_match_for). A worker sets it when its observers' args say which calls they want; iii does everything else as usual: the observers' capture, filters and policy still apply. IIIClient::clear_observation_match_for removes it: every observer wants every call again.

NameTypeRequiredDescription
Predicate(Arc<dyn Fn(&Observer, &Call) -> bool + Send + Sync>)YesAsked once per observation: for every call, once for each active
observer, before its filters. A predicate that panics counts as no
match for that observer, logged once per function.
Keys{ observer: Arc<dyn Fn(&'a Observer) -> Keys<'a> + Send + Sync>, call: Arc<dyn Fn(&'a Call) -> Keys<'a> + Send + Sync> }YesAn observer wants a call when they share a key. The SDK computes an
observer's keys once, when it is accepted, and files it under each
(an observer whose key function panics is rejected with
OBSERVE_REJECTED); a call's keys once per call. A call matches the
observers filed under any of its keys, each once. Keys express
wildcards by listing them: an observer of every table filed under
`"primary
keysfn(observer: O, call: C) -> SelfYesThe keys an observer is filed under, and the keys a call matches. With them, FunctionRef::is_observed_for answers with one hash lookup per call key.
predicatefn(f: impl Fn(&Observer, &Call) -> bool + Send + Sync + 'static) -> SelfYesDoes obs want call?

Link to this sectionRemovedHook

Runs once for every accepted observer when it is removed (unobserved, disposed, rejected late), to tear down what AddedHook set up. It never runs for an observer that was not accepted. A panic is logged; the observer is removed either way.

Implemented for async closures taking the Observer by value. Implement with plain async fn, without #[async_trait]. The returned future is Send and may borrow self across .await. This trait is not dyn-compatible; pass a concrete hook to IIIClient::on_observer_removed.

NameTypeRequiredDescription
on_removedfn(obs: Observer) -> impl Future<Output = ()> + Send + '_Yes-

Link to this sectioniii_sdk::observable

Observer · ObserveRejection

Link to this sectionObserver

One observer of a function this worker hosts, as its host sees it: its id, args, filters, target and capture. Never its metadata, policy or observing worker.

Cheap to clone (an Arc), so hooks take it by value and a worker keeps it in its own index. Two Observers are equal when their ids are.

The engine may announce an observer again with the same args and other filters, target or capture: it stays the same observer and no hook runs. Handles given out earlier keep the view they were made with, and IIIClient::observers returns the announced one.

NameTypeRequiredDescription
acceptedasync fn() -> Result<(), Error>YesResolves once the SDK has acked the observer, which makes it active: a call made after this resolves reaches an active observer, since the engine handles a connection's frames in order. A provider sends an observer its initial state this way: a call through it (CallRequest::observer), which runs its target alone with the payload as given. Fails with the rejection's code when the observer is rejected first.
argsfn() -> Result<T, ObserveRejection>YesThe observer's args as T. The engine validated them against the function's args_format; a mismatch with T is INVALID_ARGS.
args_valuefn() -> &ValueYesThe observer's args as JSON ({} when it has none).
capturefn() -> &[Capture]YesWhat deliveries ship to the target.
filtersfn() -> &ValueYesThe observer's filters in normal form ({} matches every call). iii's delivery and matches apply them.
function_idfn() -> &strYesThe observed function: the one this worker registered.
idfn() -> &strYesThe observer's id (client-generated, stable across replays).
is_activefn() -> boolYesWhether it is still delivered to: accepted, and neither removed nor rejected since.
matchesfn(call: &Call) -> boolYesWhether call reaches this observer: its capture fires on the call's status and its filters match the call. A deliver hook that calls targets itself applies them with this.
namespacefn() -> &strYesThe observed function's namespace.
rejectfn(code: impl Into<String>, message: impl Into<String>)YesRejects this observer after it was accepted (a config reload removed what it needs). It stops receiving calls now, and its removed hooks run next on the function's hook task, connected or not; the engine moves it to error with this code, and its observerremoved that follows runs none again. The rejection holds across a reconnect: the SDK sends it again whenever the engine lists the observer, until a fresh observeradded brings it back. 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.
targetfn() -> &strYesThe function each delivery invokes.

Link to this sectionObserveRejection

An AddedHook's refusal of an observer, with the code the observer's ready() fails with. Any other error is OBSERVE_REJECTED.

NameTypeRequiredDescription
codeStringYes-
messageStringYes-
newfn(code: impl Into<String>, message: impl Into<String>) -> SelfYesA rejection with a code of the hook's own (HTTP_ROUTE_CONFLICT, INVALID_CRON_EXPRESSION, ...) and a message.

Link to this sectioniii_sdk::observe

Observed · ObservedError · ObserverHandle · ObserverOptions · ObserverReason · ObserverStatus · Source · StateListener · Target

Link to this sectionObserved

What an observer's target receives when iii delivers: the observed call, per the observer's capture.

iii.register_function(
    "alerts::payment-failed",
    RegisterFunction::new(|event: Observed<Value>| {
        println!("{} failed: {:?}", event.function_id, event.error);
        Ok::<_, Error>(())
    }),
);
NameTypeRequiredDescription
observer_idStringYes-
activation_idStringYes-
function_idStringYes-
namespaceOption<String>No-
invocation_idStringYes-
statusInvocationStatusYes-
inputOption<I>No-
outputOption<O>No-
errorOption<ObservedError>No-
callerOption<Caller>No-
metadataOption<Value>No-
started_at_msu64Yes-
duration_msf64Yes-

Link to this sectionObservedError

What a call failed with: Observed::error, Call::error.

NameTypeRequiredDescription
codeStringYes-
messageStringYes-

Link to this sectionObserverHandle

Handle to an observer created by IIIClient::observe. Cheap to clone.

The observer exists until dispose (or its policy runs out); dropping the handle does not remove it. It works before the connection is up and is replayed with the same id after a reconnect.

NameTypeRequiredDescription
disposeasync fn() -> Result<(), Error>YesRemoves the observer, and frees its id at once: an observe_with under the same id makes a new observer while this one is still being disposed, and each handle hears the engine's answers to its own messages only. Once it resolves (the engine confirmed it, or after 5 s without an answer), no new activation starts and a call through it fails with OBSERVER_NOT_ACTIVE. A handle observe_with refused (state error, with no observer of its own) sends nothing and leaves the handle that holds the id alone. The engine's refusal of an observe (its answer in state error, to the first observe or to a replay) is the handle's final answer: the engine holds no observer for it and the handle is not sent again, so dispose() sends nothing and resolves at once, or, called before the refusal arrives, when it arrives. An observer that reaches error by a state change stays held, and dispose() sends unobserve.
firesfn() -> u64YesActivations so far, as last reported by the engine.
idfn() -> &strYesThe observer's id.
on_state_changefn(listener: F) -> StateListenerYesCalls listener on every state change. Listeners run on one process-wide thread, one call at a time and in the order the changes happened, never on the connection's read loop: a listener may call the client. A listener that blocks delays every client's listeners in the process; hand slow work to a task of its own.
readyasync fn() -> Result<(), Error>YesResolves once the observer is active. Fails with the reason's code (Error::Remote) when it ends in error or disposed; waits through pending and suspended.
reasonfn() -> Option<ObserverReason>YesWhy it is in error (or suspended, disposed): an engine code such as INVALID_ARGS, FORBIDDEN, UNSUPPORTED, or the rejection code of an added hook of the worker that hosts the function.
statefn() -> ObserverStateYesThe current state.
warningsfn() -> Vec<String>YesThe engine's warnings about the filters (paths it could not verify against an open schema).

Link to this sectionObserverOptions

The observer itself: its id, policy and metadata sidecar.

NameTypeRequiredDescription
expires_infn(expires_in: Duration) -> SelfYesDispose of the observer after this long.
idfn(id: impl Into<String>) -> SelfYesThe observer's id. Default: a random UUID v4, kept across replays.
max_firesfn(max_fires: u64) -> SelfYesDispose of the observer after this many activations.
max_in_flightfn(max_in_flight: u32) -> SelfYesAt most this many activations running at once; more queue in the engine, and a call through the observer fails with OVERFLOW.
metadatafn(metadata: Value) -> SelfYesDelivered as the metadata sidecar of every activation. The worker that hosts the function never sees it.

Link to this sectionObserverReason

Why an observer is in its state: { code, message }.

NameTypeRequiredDescription
codeStringYes-
messageStringYes-

Link to this sectionObserverStatus

An observer's state, why, and how often it fired.

NameTypeRequiredDescription
stateObserverStateYes-
reasonOption<ObserverReason>No-
firesu64Yes-

Link to this sectionSource

The left side of an observer: what is observed.

NameTypeRequiredDescription
argsfn(args: Value) -> SelfYesArgs for the worker that hosts the function: what to set up for this observer and which calls it wants, validated against the function's args_format (INVALID_ARGS). The function's description says what they mean.
capturefn(capture: impl IntoIterator<Item = Capture>) -> SelfYesWhat the target's payload carries, and with it which outcomes fire the target. Default [input, output, caller].
filtersfn(filters: Value) -> SelfYesWhich calls reach the target: a filter over input, output, error, caller and metadata, with explicit operators ({ "input.amount": { "$gte": 500 } }). Unset matches every call.
functionfn(function_id: impl Into<String>) -> SelfYesObserve function_id. Every function is observable.
function_idfn() -> &strYesThe observed function id.
namespacefn(namespace: impl Into<String>) -> SelfYesThe namespace the function is in. Unset, it resolves like a call: this worker's namespace (default for engine::* and configuration::*).

Link to this sectionStateListener

A listener added with ObserverHandle::on_state_change.

NameTypeRequiredDescription
unsubscribefn()YesStops calling the listener.

Link to this sectionTarget

The right side of an observer: a registered function.

NameTypeRequiredDescription
functionfn(function_id: impl Into<String>) -> SelfYes-
namespacefn(namespace: impl Into<String>) -> SelfYesThe target's namespace. Unset, it resolves like a call.

Link to this sectioniii_sdk::protocol

Activation · CallAction · Caller · CallRequest · CallRequestWithMetadata · Capture · Dispatch · DroppedReportStats · ErrorBody · FunctionMessage · InvocationStatus · LocalFunctionStats · Message · ObservedItem · ObserverState · ObserverView · ObserveSource · ObserveTarget · ParentCaller · RegisterFunctionMessage

Link to this sectionActivation

invokefunction.activation.

NameTypeRequiredDescription
observer_idStringYes-
activation_idOption<String>NoEngine → worker: unique per activation. Absent on a call through an
observer as its host sends it.

Link to this sectionCallAction

Routing action for CallRequest. Determines how the engine handles the invocation.

  • Enqueue: Routes through a named queue for async processing.
  • Void: Fire-and-forget, no response.
NameTypeRequiredDescription
Enqueue{ queue: String }YesRoutes the invocation through a named queue.
VoidunitYesFire-and-forget routing.

Link to this sectionCaller

Who made an invocation. worker_id / worker_name are stamped by the engine from the calling connection; function_id, invocation_id and parent are asserted by the calling SDK.

NameTypeRequiredDescription
worker_idOption<String>No-
worker_nameOption<String>No-
function_idOption<String>NoThe handler the call was made from; absent for a top-level call.
invocation_idOption<String>No-
parentOption<ParentCaller>NoThe caller of that handler, one level only.
stripfn() -> ParentCallerYesThis caller without its own parent, as the parent of a call made from the handler it invoked.

Link to this sectionCallRequest

Request object for IIIClient::call.

// Simple call
CallRequest {
    function_id: "my::function".to_string(),
    payload: json!({ "key": "value" }),
    action: None,
    timeout_ms: None,
};

// With action
CallRequest {
    function_id: "my::function".to_string(),
    payload: json!({}),
    action: Some(CallAction::Enqueue { queue: "payments".to_string() }),
    timeout_ms: None,
};

// With metadata
CallRequest::new("my::function", json!({})).metadata(json!({ "tenant": "acme" }));
NameTypeRequiredDescription
function_idStringYesID of the function to invoke.
payloadValueYesInput data passed to the function.
actionOption<CallAction>NoSets how the call is routed. None for a synchronous request/response.
Set a routing scheme otherwise (e.g. CallAction::Enqueue { .. }, CallAction::Void).
timeout_msOption<u64>NoOverride the default invocation timeout, in milliseconds.
dispatchfn(dispatch: Dispatch) -> CallRequestWithMetadataYesChoose the path this call takes: Dispatch::Auto (the default) runs a function this worker hosts in-process when the engine allows it; Dispatch::Remote always goes through the engine.
metadatafn(metadata: Value) -> CallRequestWithMetadataYesAttach per-invocation metadata without adding a required field to CallRequest struct literals.
namespacefn(namespace: impl Into<String>) -> CallRequestWithMetadataYesTarget a specific namespace for this invocation without adding a required field to CallRequest struct literals. Serializes into Message::InvokeFunction's namespace.
newfn(function_id: impl Into<String>, payload: Value) -> SelfYesA synchronous request/response call of function_id with payload, the default timeout and no routing action.
observerfn(observer: &Observer, payload: Value) -> CallRequestWithMetadataYesA call through observer: the engine runs the observer's target with payload, as given, and applies the observer's policy, metadata sidecar and loop guard. Only the worker that hosts the observer's function may make it (NOT_FUNCTION_OWNER); it never runs in-process. It takes no metadata: the target's metadata argument is the observer's registration metadata, and IIIClient::call refuses a request given metadata before anything is sent. A host makes it in the function's deliver hook, or to send one observer something of its own, such as its initial state once it is accepted (see Observer::accepted).

Link to this sectionCallRequestWithMetadata

A CallRequest plus optional per-invocation metadata, target namespace, dispatch and the observer it is made through.

NameTypeRequiredDescription
actionfn(action: CallAction) -> SelfYesHow the call is routed; see CallRequest::action.
dispatchfn(dispatch: Dispatch) -> SelfYesChoose the path this call takes; see Dispatch.
metadatafn(metadata: Value) -> SelfYesAttach per-invocation metadata: any JSON value, which the handler receives as its metadata argument. Value::Null is the same as no metadata. A call through an observer (CallRequest::observer) takes none.
namespacefn(namespace: impl Into<String>) -> SelfYesTarget a specific namespace for this invocation.
timeoutfn(timeout: Duration) -> SelfYesOverride the default invocation timeout.

Link to this sectionCapture

What an activation ships to the target. A filter may read any root, whatever is captured.

NameTypeRequiredDescription
InputunitYes-
OutputunitYes-
ErrorunitYes-
CallerunitYes-
MetadataunitYes-
Unknown(String)YesA value this SDK does not know, kept verbatim.
as_strfn() -> &strYesThe wire spelling.

Link to this sectionDispatch

Which path IIIClient::call takes.

A call to a function registered by this same worker runs in-process ("local dispatch") when all of these hold:

  1. the function has a handler here (not RegisterFunction::http) and was not registered with RegisterFunction::local_dispatch(false);
  2. the engine confirmed it with functionregistered { local_dispatch: true };
  3. the call resolves to the namespace the function is registered in;
  4. the action is not CallAction::Enqueue (a Void call runs locally, fire-and-forget);
  5. the dispatch is not Dispatch::Remote, and the call is not made through an observer (CallRequest::observer).

Otherwise the call goes through the engine. A local call returns the same result, error shape and timeout as a remote one, and is reported to the engine only when an observer's filters match it.

NameTypeRequiredDescription
AutounitYesRun in-process when the five conditions above hold, else remote.
RemoteunitYesAlways route through the engine (engine-side effects, tests).

Link to this sectionDroppedReportStats

SDK-side report drops in localinvocationstats.

NameTypeRequiredDescription
function_idStringYes-
reasonStringYesobserve_codes::BUFFER_FULL, observe_codes::TOO_LARGE or
observe_codes::INACTIVE.
countu64Yes-

Link to this sectionErrorBody

NameTypeRequiredDescription
codeStringYes-
messageStringYes-
stacktraceOption<String>No-
newfn(code: impl Into<String>, message: impl Into<String>) -> SelfYesAn error body without a stacktrace.

Link to this sectionFunctionMessage

NameTypeRequiredDescription
function_idStringYes-
descriptionOption<String>No-
request_formatOption<Value>No-
response_formatOption<Value>No-
metadataOption<Value>No-

Link to this sectionInvocationStatus

Outcome of an observed call.

NameTypeRequiredDescription
SuccessunitYes-
ErrorunitYes-
Unknown(String)YesA value this SDK does not know, kept verbatim.
as_strfn() -> &strYesThe wire spelling.

Link to this sectionLocalFunctionStats

Per-function counts in localinvocationstats.

NameTypeRequiredDescription
function_idStringYes-
countu64Yes-
errorsu64Yes-
duration_ms_sumf64Yes-

Link to this sectionMessage

NameTypeRequiredDescription
RegisterFunction{ id: String, description: Option<String>, request_format: Option<Value>, response_format: Option<Value>, metadata: Option<Value>, invocation: Option<iii_helpers::http::HttpInvocationConfig>, args_format: Option<Value>, private: bool, observable: bool }Yes-
UnregisterFunction{ id: String }Yes-
InvokeFunction{ invocation_id: Option<uuid::Uuid>, function_id: String, data: Value, traceparent: Option<String>, baggage: Option<String>, action: Option<CallAction>, metadata: Option<Value>, namespace: Option<String>, caller: Option<Box<Caller>>, observe_depth: Option<u32>, activation: Option<Activation> }Yes-
InvocationResult{ invocation_id: uuid::Uuid, function_id: String, result: Option<Value>, error: Option<ErrorBody>, traceparent: Option<String>, baggage: Option<String>, matched: Option<Vec<String>>, delivered: bool }Yes-
PingunitYes-
PongunitYes-
Reattach{ previous_worker_id: String, reattach_token: Option<String> }YesSent to the engine as the first message of a reconnect, before the
registration replay: previous_worker_id and reattach_token are
the values the engine assigned via WorkerRegistered on the previous
connection. The engine retires that connection so the replay lands on
a clean slate; the token is required because worker ids alone are
publicly discoverable.
WorkerRegistered{ worker_id: String, reattach_token: Option<String>, features: Vec<String> }Yes-
RegistrationRejected{ code: String, namespace: String, worker_name: Option<String>, function_id: Option<String>, owner_worker_id: String }YesPushed by the engine when it refuses a registration.
WORKER_NAMESPACE_CONFLICT is fatal (the engine closes the connection;
the SDK stops and does not reconnect). A rejection that names a
function_id (FUNCTION_NAMESPACE_CONFLICT,
observe_codes::INVALID_ARGS_FORMAT, observe_codes::UNSUPPORTED)
refuses that one function and keeps the connection open.
Observe{ id: String, source: Box<ObserveSource>, target: ObserveTarget, metadata: Option<Value>, max_fires: Option<u64>, expires_in_ms: Option<u64>, max_in_flight: Option<u32> }YesObserving worker → engine: create, or idempotently replay, an observer
owned by this connection.
Unobserve{ id: String }YesObserving worker → engine: dispose an observer this connection owns.
ObserveResult{ id: String, state: ObserverState, error: Option<ErrorBody>, warnings: Vec<String> }YesEngine → observing worker: the reply to observe (also on replay).
ObserverStateChanged{ id: String, state: ObserverState, reason: Option<ErrorBody>, fires: u64 }YesEngine → observing worker: every lifecycle transition.
FunctionRegistered{ id: String, namespace: String, revision: u64, local_dispatch: bool, observers: Vec<ObserverView> }YesEngine → host: the registerfunction success ack, with the full
current observer set. Enables local dispatch for this function.
ObserverAdded{ function_id: String, namespace: String, revision: u64, observer: ObserverView }YesEngine → host: one observer attached to a function this connection
hosts. Awaits observerack.
ObserverRemoved{ function_id: String, namespace: String, revision: u64, id: String }YesEngine → host: one observer detached.
ObserverAck{ function_id: String, namespace: Option<String>, id: String, revision: u64, error: Option<ErrorBody> }YesHost → engine: accepts one added observer, or rejects it with error
(also later, for an active observer: a late rejection).
InvocationsObserved{ items: Vec<ObservedItem> }YesHost → engine: what the host's delivery matched in local calls,
batched. The engine evaluates the observers of the calls it routes.
LocalInvocationStats{ window_ms: u64, functions: Vec<LocalFunctionStats>, dropped_reports: Vec<DroppedReportStats> }YesHost → engine: local invocation counts and SDK-side report drops,
every 10 s and only when non-zero.
UnknownunitYesAny message type this SDK does not know, sent by a newer engine. It is
ignored (logged at debug level), never sent.

Link to this sectionObservedItem

One item of invocationsobserved: one local call and the observers iii's delivery selected for it.

input / output / error / metadata keep null apart from absent.

NameTypeRequiredDescription
function_idStringYes-
namespaceOption<String>No-
invocation_idStringYes-
matchedVec<String>Yes-
statusInvocationStatusYes-
inputOption<Value>No-
outputOption<Value>No-
errorOption<Value>No-
callerOption<Caller>No-
metadataOption<Value>No-
started_at_msu64Yes-
duration_msf64Yes-
observe_depthu32Yes-
traceparentOption<String>No-
baggageOption<String>No-
output_is_inputboolYesThe handler returned its input: the item carries it once, as input,
and the engine fills output from it.

Link to this sectionObserverState

Observer lifecycle states.

NameTypeRequiredDescription
PendingunitYesWaiting for its function's host (and its ack) or its target.
ActiveunitYesDelivering.
SuspendedunitYesIts observing worker or its target is gone for now.
ErrorunitYesRejected; see the reason.
DisposedunitYesGone for good.
Unknown(String)YesA value this SDK does not know, kept verbatim.
as_strfn() -> &strYesThe wire spelling.

Link to this sectionObserverView

An observer as its function's host sees it (functionregistered, observeradded): never the observer's metadata, policy or observing worker.

NameTypeRequiredDescription
idStringYes-
argsValueYes{} for an observer without args.
filtersValueYesThe observer's filters in normal form; {} matches every call.
targetStringYesTarget function id (its namespace is not disclosed).
captureVec<Capture>Yes-
fires_onOption<Vec<InvocationStatus>>NoThe outcomes that fire it, from an engine with
FEATURE_OBSERVE_CAPTURE; absent from an older engine, whose
observers fire as their legacy on says.
onOption<Value>NoThe legacy on of an engine without FEATURE_OBSERVE_CAPTURE
(absent: success; error; complete). Read only when fires_on is
absent; deprecated.
fires_onfn(success: bool) -> boolYesWhether a call that ended in success (or not) fires this observer: from fires_on, or else from the legacy on, never from capture.

Link to this sectionObserveSource

The left side of iii.observe on the wire. Absent fields stay absent; the engine applies the defaults.

NameTypeRequiredDescription
function_idStringYes-
namespaceOption<String>No-
argsOption<Value>No-
filtersOption<Value>No-
captureOption<Vec<Capture>>No-

Link to this sectionObserveTarget

The right side of iii.observe on the wire: a registered function.

NameTypeRequiredDescription
function_idStringYes-
namespaceOption<String>No-

Link to this sectionParentCaller

Caller::parent: a caller without a parent of its own.

NameTypeRequiredDescription
worker_idOption<String>No-
worker_nameOption<String>No-
function_idOption<String>No-
invocation_idOption<String>No-

Link to this sectionRegisterFunctionMessage

NameTypeRequiredDescription
idStringYes-
descriptionOption<String>No-
request_formatOption<Value>No-
response_formatOption<Value>No-
metadataOption<Value>No-
invocationOption<iii_helpers::http::HttpInvocationConfig>No-
args_formatOption<Value>NoSee RegisterFunction::args_format.
privateboolYesSee RegisterFunction::private.
observableboolYesSee RegisterFunction::observable.
to_messagefn() -> MessageYes-
with_descriptionfn(description: String) -> SelfYes-
with_idfn(name: String) -> SelfYes-

Link to this sectioniii_sdk::runtime

FunctionInfo · FunctionRef · IIIConnectionState · WorkerIdentityMode · WorkerInfo · WorkerMetadata

Link to this sectionFunctionInfo

Function information returned by engine::functions::list

NameTypeRequiredDescription
function_idStringYes-
descriptionOption<String>No-
request_formatOption<Value>No-
response_formatOption<Value>No-
metadataOption<Value>No-
namespaceOption<String>No-
args_formatOption<Value>NoJSON Schema of the function's observer args, when it takes any.
privateboolYesOnly its host may call it.
observableboolYesfalse: nobody may observe it.
observer_countu64YesObservers of the function.

Link to this sectionFunctionRef

A function this worker registered, returned by IIIClient::register_function. Its hook methods are the client's, with the function id filled in; each returns the receiver, for chaining.

iii.register_function(
    "orders::on-placed",
    RegisterFunction::new(|order: Value| Ok::<_, Error>(order)).private(),
)
.on_observer_removed(|obs: Observer| async move {
    println!("{} stopped observing", obs.id());
});
NameTypeRequiredDescription
idStringYes-
clear_observation_deliverfn() -> &SelfYesIIIClient::clear_observation_deliver_for this function.
clear_observation_matchfn() -> &SelfYesIIIClient::clear_observation_match_for this function.
clear_observer_addedfn() -> &SelfYesIIIClient::clear_observer_added_for this function.
clear_observer_removedfn() -> &SelfYesIIIClient::clear_observer_removed_for this function.
is_observedfn() -> boolYesWhether any observer is active on this function, in one atomic load and without allocating. Check it before building an event nobody would receive.
is_observed_forfn(call: &Call) -> boolYesWhether call would reach anyone. Matched by Match::keys: an observer is filed under one of the call's keys, one hash lookup per key and no allocation for keys borrowed from the call. Otherwise the call is not looked at: as is_observed.
local_dispatch_activefn() -> boolYesWhether calls to this function from this worker currently run in-process (the engine confirmed it with local_dispatch: true).
observersfn() -> Vec<Observer>YesThe active observers, as the host sees them.
on_observation_deliverfn(hook: impl DeliverHook) -> &SelfYesIIIClient::on_observation_deliver_for this function.
on_observation_matchfn(rule: Match) -> &SelfYesIIIClient::on_observation_match_for this function.
on_observer_addedfn(hook: impl AddedHook) -> &SelfYesIIIClient::on_observer_added_for this function.
on_observer_removedfn(hook: impl RemovedHook) -> &SelfYesIIIClient::on_observer_removed_for this function.
unregisterfn()YesUnregisters the function. Its hooks stay set, for a later registration of the same id.

Link to this sectionIIIConnectionState

Connection state for the III WebSocket client

NameTypeRequiredDescription
DisconnectedunitYes-
ConnectingunitYes-
ConnectedunitYes-
ReconnectingunitYes-
FailedunitYes-

Link to this sectionWorkerIdentityMode

Selects where a worker connection gets its engine identity.

NameTypeRequiredDescription
ManagedunitYesUse the supervisor-managed III_WORKER_NAME and III_NAMESPACE values
when present. This is the default for normal worker connections.
ExplicitunitYesKeep the name from WorkerMetadata and the namespace from explicit
options or metadata. Process-wide identity environment variables are
ignored. Use this for auxiliary connections created by one worker.

Link to this sectionWorkerInfo

Worker information returned by engine::workers::list

NameTypeRequiredDescription
idStringYes-
nameOption<String>No-
runtimeOption<String>No-
versionOption<String>No-
osOption<String>No-
ip_addressOption<String>No-
statusStringYes-
connected_at_msu64Yes-
function_countusizeYes-
functionsVec<String>Yes-
active_invocationsusizeYes-
isolationOption<String>No-
namespaceOption<String>No-

Link to this sectionWorkerMetadata

Worker metadata for auto-registration

NameTypeRequiredDescription
runtimeStringYes-
versionStringYesVersion reported to the engine and shown by engine::workers::list.
Defaults to this SDK's version and may be set to the worker's own: the
engine sizes the messages it sends this worker by the
large-messages.v1 feature the SDK declares, not by this field.
nameStringYesWorker name reported to the engine. In managed identity mode, a
non-empty III_WORKER_NAME overrides this value when the client is
created.
osStringYes-
descriptionOption<String>NoOne-line, human/LLM-readable summary of what this worker does.
Surfaces in engine::workers::list / engine::workers::info.
pidOption<u32>No-
telemetryOption<TelemetryOptions>No-
isolationOption<String>No-
namespaceOption<String>NoNamespace this worker belongs to, and therefore the one its calls and
its observers resolve in unless they name another. Absent means
the engine applies its default namespace. Managed clients also use
III_NAMESPACE when no explicit namespace is present.

Link to this sectioniii_sdk::streams

InputStream · OutputStream · Pipe · StreamInfo

Link to this sectionInputStream

The read side of a stream: 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 deserializes to it), or is built to be sent: from_reader, from_stream, from_bytes. Put it in a call payload or a handler result and the SDK streams it to the other side. A read ref found in a raw value opens with from_ref.

Read it once, one way: as a Stream of byte chunks, an AsyncRead, read_all, text, lines, messages (text frames, JSON decoded) or frames (both, in order). Byte reads skip text frames. A second reader gets Error::StreamInUse. The socket opens on the first read.

An abort (its writer failed or called OutputStream::abort) ends a read with Error::StreamAborted, 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; one never read is left alone. One sent on unread (in a call payload or the result) is forwarded: its ref goes, 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 Error::StreamInUse.

A received stream binds to the client of the handler it was received in, or else to the only IIIClient alive; with several, call bind. A clone is a handle to the same stream, and another reader: only one of them can read it.

NameTypeRequiredDescription
bindfn(iii: &IIIClient) -> &SelfYesBinds a received stream to iii: its socket opens on that client's engine, with its handshake headers. Needed only outside a handler while several clients are alive.
cancelasync fn()YesStops 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, fails with Error::StreamClosed: what was read is not the whole stream. A stream read to its end stays ended.
framesfn() -> impl Stream<Item = Result<ChannelItem, Error>> + Send + Unpin + 'staticYesEvery frame, in order: text frames (messages) and binary frames (bytes). The stream is Unpin.
from_bytesfn(bytes: impl Into<Bytes>) -> SelfYesA stream of bytes.
from_readerfn(reader: R) -> SelfYesA stream of what reader yields, read in chunks of up to 64 KiB. A read error aborts the stream with its message.
from_reffn(channel: StreamChannelRef, iii: &IIIClient) -> Result<InputStream, Error>YesOpens a read ref (one extract_channel_refs found in a call's result read as a Value, say) as a stream bound to iii. It is what deserializing the ref into an InputStream gives: a received stream its invocation tracks is that stream, a stream of this process passed as a placeholder is that stream, and in a handler the guard settles it. A write ref, or a placeholder already received, fails with Error::Runtime.
from_streamfn(stream: S) -> SelfYesA stream of the chunks stream yields. An Err aborts the stream with its message: the reader gets Error::StreamAborted, not a short stream that looks complete.
linesfn() -> impl Stream<Item = Result<String, Error>> + Send + Unpin + 'staticYesThe stream's lines, without their \n (or \r\n); the last one may have no newline. Invalid UTF-8 becomes U+FFFD. The stream is Unpin, so next() and try_next() work on it without pinning.
messagesfn() -> impl Stream<Item = Result<T, Error>> + Send + Unpin + 'staticYesThe stream's messages: its text frames, each decoded as JSON into T. A frame that is not JSON is decoded from the raw string (so a T of String or Value takes it). Binary frames are skipped. The stream is Unpin, so next() and try_next() work on it without pinning.
read_allasync fn() -> Result<Vec<u8>, Error>YesReads the whole stream (its binary frames).
textasync fn() -> Result<String, Error>YesReads the whole stream as UTF-8 text; invalid sequences become U+FFFD.

Link to this sectionOutputStream

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 deserializes to it), or is built around a local sink with to_writer: put it in a call payload and the function writes into the sink; the call resolves once the sink got the whole stream (and fails with Error::StreamAborted if the writer aborted it), within the call's timeout. A call whose result holds a stream to write (the function returned a sink) resolves without waiting: the caller writes it.

write sends bytes (in binary frames of up to 64 KiB), send a message (a JSON text frame), and each resolves once the chunk was taken. End it with close, or fail it with abort: the reader then gets an error, not a short stream. A write after either fails with Error::StreamClosed. It is also an AsyncWrite. A byte sink made with to_writer takes the bytes only: messages are not written to it.

In a handler, the stream is ended when the handler returns: one it used is closed when it succeeded and aborted when it failed. One it never used is closed when it succeeded and left as is when it failed; in an observer activation (an HTTP route target, say) it is closed only when the handler returned 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 keep_open to keep writing after the handler returned. Dropped while used and not ended, it aborts.

NameTypeRequiredDescription
abortasync fn(reason: impl Into<String>) -> Result<(), Error>YesFails the stream with reason: the reader's read ends with Error::StreamAborted (through an engine pipe the reason is the engine's). A stream never written is opened first, so its reader always learns of it. Aborting a stream already ended does nothing.
bindfn(iii: &IIIClient) -> &SelfYesBinds a received stream to iii: its socket opens on that client's engine, with its handshake headers. Needed only outside a handler while several clients are alive.
closeasync fn() -> Result<(), Error>YesEnds the stream: the reader reads to the end. A stream never written is opened and closed, so the reader sees an empty stream. Closing a stream already ended does nothing.
keep_openfn() -> &SelfYesKeeps the stream open after the handler that received it returns: it is then this code's to close or abort.
sendasync fn(message: &T) -> Result<(), Error>YesSends message as a JSON text frame.
send_textasync fn(text: &str) -> Result<(), Error>YesSends text as a text frame, as is.
to_writerfn(writer: W) -> SelfYesA stream whose bytes go to writer: closing it flushes and shuts the writer down; an abort drops it as is.
writeasync fn(data: &[u8]) -> Result<(), Error>YesWrites data, in binary frames of up to 64 KiB. Resolves once taken.

Link to this sectionPipe

The two ends of a pipe made with IIIClient::pipe: put one in a call payload and use the other here.

NameTypeRequiredDescription
inputInputStreamYesThe read end.
outputOutputStreamYesThe write end.

Link to this sectionStreamInfo

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.

An observer's target receives it in place of each stream ref under the input and output of an Observed envelope. 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.

NameTypeRequiredDescription
streamboolYesAlways true: marks the value as a stream.
directionChannelDirectionYesread for a stream the function read, write for one it wrote.
idStringYesThe channel id (a local stream's placeholder id for a call this
worker dispatched in-process).

Link to this sectioniii_sdk::structs

MiddlewareFunctionInput

Link to this sectionMiddlewareFunctionInput

Input passed to the RBAC middleware function on every function invocation through the RBAC port.

The middleware can inspect, modify, or reject the call before it reaches the target function.

NameTypeRequiredDescription
function_idStringYesID of the function being invoked.
payloadValueYesPayload sent by the caller.
actionOption<CallAction>NoRouting action, if any.
contextValueYesAuth context returned by the auth function for this session.
namespaceOption<String>NoTarget namespace the invoke addressed; forward the call here to stay in
the caller's namespace. Absent → the engine's default namespace.

Link to this sectioniii_sdk::types

RemoteFunctionData · RemoteFunctionHandler · StreamRequest · StreamResponse

Link to this sectionRemoteFunctionData

NameTypeRequiredDescription
messageRegisterFunctionMessageYes-
handlerOption<RemoteFunctionHandlerWithMetadata>No-

Link to this sectionRemoteFunctionHandler

A dispatchable function handler. Receives the invocation payload.

Handlers that also want the optional per-invocation metadata sidecar use RemoteFunctionHandlerWithMetadata; this single-argument shape is kept for backward compatibility.

type RemoteFunctionHandler = Arc<dyn Fn(Value) -> futures_util::future::BoxFuture<'static, Result<Value, Error>> + Send + Sync>

Link to this sectionStreamRequest

Incoming streaming request received by a function that serves HTTP.

Alias of iii_helpers::http::HttpRequest.

type StreamRequest = iii_helpers::http::HttpRequest<T>

Link to this sectionStreamResponse

Streaming response type, mirroring the Node and Python StreamResponse.

Alias of iii_helpers::http::HttpResponse; added for cross-language parity.

type StreamResponse = iii_helpers::http::HttpResponse<T>