> ## Documentation Index
> Fetch the complete documentation index at: https://iii.dev/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Rust SDK

> API reference for the iii SDK for Rust.

## Installation

```bash theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
cargo add iii-sdk
```

## Initialization

### register\_worker

**Signature**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
register_worker(address: &str, options: InitOptions) -> IIIClient
```

#### Parameters

**address** `&str` *required*

**options** `InitOptions` *required*

**`InitOptions` fields**

**metadata** `Option\<iii::WorkerMetadata\>`

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

**headers** `Option\<HashMap\<String, String\>\>`

Custom HTTP headers sent during the WebSocket handshake, on the main connection and on channels from `create_channel`. `Authorization: Bearer $III_TOKEN` is added unless you set `Authorization` here.

**otel** `Option\<iii_helpers::observability::OtelConfig\>`

OpenTelemetry configuration.

**namespace** `Option\<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.

**identity** `WorkerIdentityMode` *required*

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

## Methods

### register\_function

Register a function with the engine.

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

**Signature**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
register_function(id: impl Into<String>, registration: RegisterFunction) -> FunctionRef
```

> [tab] Parameters
>
> **id** `impl Into\<String\>` *required*
>
> Unique identifier for the function.
>
> **registration** `RegisterFunction` *required*
>
> Built via \[`RegisterFunction::new`], \[`RegisterFunction::new_async`], or \[`RegisterFunction::http`]. Chain `.description(...)`, `.metadata(...)`, `.request_format(...)`, `.response_format(...)` as needed.
>
> **`RegisterFunction` fields**
>
> **args\_format** `fn() -\> Self` *required*
>
> 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\_value** `fn(schema: Value) -\> Self` *required*
>
> `args_format` from a JSON Schema value.
>
> **description** `fn(desc: impl Into\<String\>) -\> Self` *required*
>
> Set the function description.
>
> **http** `fn(config: HttpInvocationConfig) -\> Self` *required*
>
> Create a registration for an **HTTP-invoked** function (Lambda, Cloudflare Workers, etc.). No local handler runs.
>
> **local\_dispatch** `fn(enabled: bool) -\> Self` *required*
>
> Whether calls to this function from this same worker may run in-process once the engine allows it. Default `true`.
>
> **metadata** `fn(meta: Value) -\> Self` *required*
>
> Set function metadata.
>
> **new** `fn(f: F) -\> Self` *required*
>
> Create a registration for a **sync** typed function.
>
> **new\_async** `fn(f: F) -\> Self` *required*
>
> Create a registration for an **async** typed function.
>
> **observable** `fn(observable: bool) -\> Self` *required*
>
> `false`: nobody may observe the function (`NOT_OBSERVABLE`), for one whose payloads carry credentials. Default `true`.
>
> **private** `fn() -\> Self` *required*
>
> 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\_format** `fn(schema: Value) -\> Self` *required*
>
> Set the request format schema. Overrides any auto-extracted schema.
>
> **response\_format** `fn(schema: Value) -\> Self` *required*
>
> Set the response format schema. Overrides any auto-extracted schema.

> [tab] Example
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> use iii_sdk::{register_worker, InitOptions, Error, RegisterFunction};
> use serde::{Deserialize, Serialize};
> use schemars::JsonSchema;
>
> #[derive(Deserialize, JsonSchema)]
> struct Input { name: String }
> #[derive(Serialize, JsonSchema)]
> struct Output { message: String }
>
> async fn greet(input: Input) -> Result<Output, Error> {
>     Ok(Output { message: format!("Hello, {}!", input.name) })
> }
>
> let worker = register_worker("ws://localhost:49134", InitOptions::default());
> worker.register_function(
>     "greetings::greet",
>     RegisterFunction::new_async(greet).description("Greets a user"),
> );
> ```

***

### call

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**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
async call(request: impl Into<CallRequestWithMetadata>) -> Result<Value, Error>
```

> [tab] Parameters
>
> **request** `impl Into\<CallRequestWithMetadata\>` *required*
>
> **`CallRequestWithMetadata` fields**
>
> **action** `fn(action: CallAction) -\> Self` *required*
>
> How the call is routed; see `CallRequest::action`.
>
> **dispatch** `fn(dispatch: Dispatch) -\> Self` *required*
>
> Choose the path this call takes; see `Dispatch`.
>
> **metadata** `fn(metadata: Value) -\> Self` *required*
>
> 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.
>
> **namespace** `fn(namespace: impl Into\<String\>) -\> Self` *required*
>
> Target a specific namespace for this invocation.
>
> **timeout** `fn(timeout: Duration) -\> Self` *required*
>
> Override the default invocation timeout.
>
> **`CallRequest` fields**
>
> **function\_id** `String` *required*
>
> ID of the function to invoke.
>
> **payload** `Value` *required*
>
> Input data passed to the function.
>
> **action** `Option\<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\_ms** `Option\<u64\>`
>
> Override the default invocation timeout, in milliseconds.
>
> **dispatch** `fn(dispatch: Dispatch) -\> CallRequestWithMetadata` *required*
>
> 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.
>
> **metadata** `fn(metadata: Value) -\> CallRequestWithMetadata` *required*
>
> Attach per-invocation metadata without adding a required field to `CallRequest` struct literals.
>
> **namespace** `fn(namespace: impl Into\<String\>) -\> CallRequestWithMetadata` *required*
>
> Target a specific namespace for this invocation without adding a required field to `CallRequest` struct literals. Serializes into `Message::InvokeFunction`'s `namespace`.
>
> **new** `fn(function_id: impl Into\<String\>, payload: Value) -\> Self` *required*
>
> A synchronous request/response call of `function_id` with `payload`, the default timeout and no routing action.
>
> **observer** `fn(observer: &Observer, payload: Value) -\> CallRequestWithMetadata` *required*
>
> 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`).

> [tab] Example
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // Synchronous
> let result = worker
>     .call(CallRequest::new("greet", json!({"name": "World"})))
>     .await?;
>
> // Fire-and-forget
> worker
>     .call(CallRequest {
>         function_id: "notify".to_string(),
>         payload: json!({}),
>         action: Some(CallAction::Void),
>         timeout_ms: None,
>     })
>     .await?;
>
> // Enqueue (the queue must be declared in the queue worker's
> // queue_configs)
> let receipt = worker
>     .call(CallRequest {
>         function_id: "iii::durable::publish".to_string(),
>         payload: json!({"topic": "test"}),
>         action: Some(CallAction::Enqueue { queue: "test".to_string() }),
>         timeout_ms: None,
>     })
>     .await?;
>
> // Metadata
> worker
>     .call(
>         CallRequest::new("audit::write", json!({"event": "checkout"}))
>             .metadata(json!({"tenant": "acme"}))
>             .action(CallAction::Void),
>     )
>     .await?;
> ```

***

### observe

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**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
observe(source: impl Into<Source>, target: impl Into<Target>) -> ObserverHandle
```

#### Parameters

**source** `impl Into\<Source\>` *required*

**`Source` fields**

**args** `fn(args: Value) -\> Self` *required*

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.

**capture** `fn(capture: impl IntoIterator\<Item = Capture\>) -\> Self` *required*

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

**filters** `fn(filters: Value) -\> Self` *required*

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.

**function** `fn(function_id: impl Into\<String\>) -\> Self` *required*

Observe `function_id`. Every function is observable.

**function\_id** `fn() -\> &str` *required*

The observed function id.

**namespace** `fn(namespace: impl Into\<String\>) -\> Self` *required*

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

**target** `impl Into\<Target\>` *required*

**`Target` fields**

**function** `fn(function_id: impl Into\<String\>) -\> Self` *required*

**namespace** `fn(namespace: impl Into\<String\>) -\> Self` *required*

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

***

### trigger

> [!WARNING]
>
> **Deprecated since 0.26.0.** Use call.

`call` under its 0.25 name.

**Signature**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
async trigger(request: impl Into<CallRequestWithMetadata>) -> Result<Value, Error>
```

#### Parameters

**request** `impl Into\<CallRequestWithMetadata\>` *required*

**`CallRequestWithMetadata` fields**

**action** `fn(action: CallAction) -\> Self` *required*

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

**dispatch** `fn(dispatch: Dispatch) -\> Self` *required*

Choose the path this call takes; see `Dispatch`.

**metadata** `fn(metadata: Value) -\> Self` *required*

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.

**namespace** `fn(namespace: impl Into\<String\>) -\> Self` *required*

Target a specific namespace for this invocation.

**timeout** `fn(timeout: Duration) -\> Self` *required*

Override the default invocation timeout.

***

### clear\_observation\_deliver\_for

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

**Signature**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
clear_observation_deliver_for(function_id: &str) -> &Self
```

#### Parameters

**function\_id** `&str` *required*

***

### clear\_observation\_match\_for

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

**Signature**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
clear_observation_match_for(function_id: &str) -> &Self
```

#### Parameters

**function\_id** `&str` *required*

***

### clear\_observer\_added

Removes the added hook set with `on_observer_added`.

**Signature**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
clear_observer_added() -> &Self
```

***

### clear\_observer\_added\_for

Removes the added hook of `function_id`.

**Signature**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
clear_observer_added_for(function_id: &str) -> &Self
```

#### Parameters

**function\_id** `&str` *required*

***

### clear\_observer\_removed

Removes the removed hook set with `on_observer_removed`.

**Signature**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
clear_observer_removed() -> &Self
```

***

### clear\_observer\_removed\_for

Removes the removed hook of `function_id`.

**Signature**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
clear_observer_removed_for(function_id: &str) -> &Self
```

#### Parameters

**function\_id** `&str` *required*

***

### engine\_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**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
engine_supports_observe() -> Option<bool>
```

#### Example

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
if worker.engine_supports_observe() == Some(false) {
    eprintln!("engine without observe: keeping the fallback");
}
```

***

### fatal\_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**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
fatal_error() -> Option<Error>
```

***

### get\_connection\_state

Get the current connection state.

**Signature**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
get_connection_state() -> IIIConnectionState
```

#### Example

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
if worker.get_connection_state() != IIIConnectionState::Connected {
    eprintln!("engine not reachable yet");
}
```

***

### is\_observed

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

**Signature**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
is_observed(function_id: &str) -> bool
```

#### Parameters

**function\_id** `&str` *required*

***

### is\_observed\_for

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

**Signature**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
is_observed_for(function_id: &str, call: &Call) -> bool
```

#### Parameters

**function\_id** `&str` *required*

**call** `&Call` *required*

**`Call` fields**

**function\_id** `String` *required*

**invocation\_id** `String` *required*

**status** `InvocationStatus` *required*

**input** `Value` *required*

**output** `Option\<Value\>`

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

**error** `Option\<ObservedError\>`

What the handler failed with.

**caller** `Option\<Caller\>`

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

**metadata** `Option\<Value\>`

The call's metadata sidecar.

***

### namespace

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

**Signature**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
namespace() -> Option<String>
```

***

### observe\_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**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
observe_with(source: impl Into<Source>, target: impl Into<Target>, options: ObserverOptions) -> ObserverHandle
```

#### Parameters

**source** `impl Into\<Source\>` *required*

**`Source` fields**

**args** `fn(args: Value) -\> Self` *required*

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.

**capture** `fn(capture: impl IntoIterator\<Item = Capture\>) -\> Self` *required*

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

**filters** `fn(filters: Value) -\> Self` *required*

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.

**function** `fn(function_id: impl Into\<String\>) -\> Self` *required*

Observe `function_id`. Every function is observable.

**function\_id** `fn() -\> &str` *required*

The observed function id.

**namespace** `fn(namespace: impl Into\<String\>) -\> Self` *required*

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

**target** `impl Into\<Target\>` *required*

**`Target` fields**

**function** `fn(function_id: impl Into\<String\>) -\> Self` *required*

**namespace** `fn(namespace: impl Into\<String\>) -\> Self` *required*

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

**options** `ObserverOptions` *required*

**`ObserverOptions` fields**

**expires\_in** `fn(expires_in: Duration) -\> Self` *required*

Dispose of the observer after this long.

**id** `fn(id: impl Into\<String\>) -\> Self` *required*

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

**max\_fires** `fn(max_fires: u64) -\> Self` *required*

Dispose of the observer after this many activations.

**max\_in\_flight** `fn(max_in_flight: u32) -\> Self` *required*

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

**metadata** `fn(metadata: Value) -\> Self` *required*

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

***

### observers

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

**Signature**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
observers(function_id: &str) -> Vec<Observer>
```

#### Parameters

**function\_id** `&str` *required*

***

### on\_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**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
on_engine_supports_observe(listener: F) -> ObserveSupportListener
```

> [tab] Parameters
>
> **listener** `F` *required*

> [tab] Example
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> let listener = worker.on_engine_supports_observe(|observe| {
>     if !observe {
>         eprintln!("engine without observe: registering the fallback");
>     }
> });
> // later
> listener.unsubscribe();
> ```

***

### on\_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**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
on_observation_deliver_for(function_id: &str, hook: impl DeliverHook) -> &Self
```

#### Parameters

**function\_id** `&str` *required*

**hook** `impl DeliverHook` *required*

**`DeliverHook` fields**

**on\_deliver** `fn(call: Call, observers: Vec\<Observer\>) -\> impl Future\<Output = Result\<Value, Error\>\> + Send + '_` *required*

***

### on\_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**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
on_observation_match_for(function_id: &str, rule: Match) -> &Self
```

#### Parameters

**function\_id** `&str` *required*

**rule** `Match` *required*

**`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.

**keys** `fn(observer: O, call: C) -\> Self` *required*

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.

**predicate** `fn(f: impl Fn(&Observer, &Call) -\> bool + Send + Sync + 'static) -\> Self` *required*

Does `obs` want `call`?

***

### on\_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**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
on_observer_added(hook: impl AddedHook) -> &Self
```

#### Parameters

**hook** `impl AddedHook` *required*

**`AddedHook` fields**

**on\_added** `fn(obs: Observer) -\> impl Future\<Output = Result\<(), ObserveRejection\>\> + Send + '_` *required*

***

### on\_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**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
on_observer_added_for(function_id: &str, hook: impl AddedHook) -> &Self
```

#### Parameters

**function\_id** `&str` *required*

**hook** `impl AddedHook` *required*

**`AddedHook` fields**

**on\_added** `fn(obs: Observer) -\> impl Future\<Output = Result\<(), ObserveRejection\>\> + Send + '_` *required*

***

### on\_observer\_removed

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

**Signature**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
on_observer_removed(hook: impl RemovedHook) -> &Self
```

#### Parameters

**hook** `impl RemovedHook` *required*

**`RemovedHook` fields**

**on\_removed** `fn(obs: Observer) -\> impl Future\<Output = ()\> + Send + '_` *required*

***

### on\_observer\_removed\_for

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

**Signature**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
on_observer_removed_for(function_id: &str, hook: impl RemovedHook) -> &Self
```

#### Parameters

**function\_id** `&str` *required*

**hook** `impl RemovedHook` *required*

**`RemovedHook` fields**

**on\_removed** `fn(obs: Observer) -\> impl Future\<Output = ()\> + Send + '_` *required*

***

### set\_namespace

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

**Signature**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
set_namespace(namespace: impl Into<String>)
```

#### Parameters

**namespace** `impl Into\<String\>` *required*

***

### shutdown

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**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
shutdown()
```

#### Example

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
worker.shutdown();
```

***

### shutdown\_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**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
async shutdown_async()
```

#### Example

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
worker.shutdown_async().await;
```

***

### wait\_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**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
async wait_until_registered(timeout: Duration) -> Result<(), Error>
```

#### Parameters

**timeout** `Duration` *required*

## Functions

### capture\_fires

**Signature**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
capture_fires(capture: &[Capture], success: bool) -> bool
```

#### Parameters

**capture** `&[Capture]` *required*

**`Capture` fields**

**Input** `unit` *required*

**Output** `unit` *required*

**Error** `unit` *required*

**Caller** `unit` *required*

**Metadata** `unit` *required*

**Unknown** `(String)` *required*

A value this SDK does not know, kept verbatim.

**as\_str** `fn() -\> &str` *required*

The wire spelling.

**success** `bool` *required*

***

### current\_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**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
current_invocation() -> Option<InvocationCtx>
```

***

### scope

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.

**Signature**

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
scope(ctx: impl Into<Option<InvocationCtx>>, fut: F) -> impl Future<Output = Output>
```

#### Parameters

**ctx** `impl Into\<Option\<InvocationCtx\>\>` *required*

**`InvocationCtx` fields**

**function\_id** `String` *required*

The function being invoked.

**invocation\_id** `String` *required*

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

**caller** `Option\<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).

**activation** `Option\<Activation\>`

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

**observe\_depth** `u32` *required*

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

**metadata** `Option\<Value\>`

The invocation's metadata sidecar.

**traceparent** `Option\<String\>`

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

**baggage** `Option\<String\>`

W3C baggage of the invocation.

**fut** `F` *required*

## Types

### iii\_sdk

[`EnqueueResult`](#enqueueresult) · [`InitOptions`](#initoptions) · [`ObserveSupportListener`](#observesupportlistener) · [`RegisterFunction`](#registerfunction) · [`TelemetryOptions`](#telemetryoptions)

#### EnqueueResult

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

| Name | Type | Required | Description |
| - | - | - | - |
| `message_receipt_id` | `String` | Yes | Unique receipt ID for the enqueued message. |

***

#### InitOptions

Configuration options passed to `register_worker`.

| Name | Type | Required | Description |
| - | - | - | - |
| `metadata` | Option\<iii::[`WorkerMetadata`](#workermetadata)> | No | Custom worker metadata. Auto-detected if `None`. In managed identity mode, process-wide identity variables override matching fields. |
| `headers` | `Option<HashMap<String, String>>` | No | Custom HTTP headers sent during the WebSocket handshake, on the main connection and on channels from `create_channel`. `Authorization: Bearer<br />$III_TOKEN` is added unless you set `Authorization` here. |
| `otel` | `Option<iii_helpers::observability::OtelConfig>` | No | OpenTelemetry configuration. |
| `namespace` | `Option<String>` | No | 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. |
| `identity` | [`WorkerIdentityMode`](#workeridentitymode) | Yes | Selects whether process-wide managed identity variables can override this connection's metadata. Auxiliary connections should use `WorkerIdentityMode::Explicit`. |

***

#### ObserveSupportListener

A listener added with `IIIClient::on_engine_supports_observe`.

| Name | Type | Required | Description |
| - | - | - | - |
| `unsubscribe` | `fn()` | Yes | Stops calling the listener: once this returns no call starts, queued ones included (a call already running finishes). |

***

#### RegisterFunction

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`.

| Name | Type | Required | Description |
| - | - | - | - |
| `args_format` | `fn() -> Self` | Yes | 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_value` | `fn(schema: Value) -> Self` | Yes | `args_format` from a JSON Schema value. |
| `description` | `fn(desc: impl Into<String>) -> Self` | Yes | Set the function description. |
| `http` | `fn(config: HttpInvocationConfig) -> Self` | Yes | Create a registration for an **HTTP-invoked** function (Lambda, Cloudflare Workers, etc.). No local handler runs. |
| `local_dispatch` | `fn(enabled: bool) -> Self` | Yes | Whether calls to this function from this same worker may run in-process once the engine allows it. Default `true`. |
| `metadata` | `fn(meta: Value) -> Self` | Yes | Set function metadata. |
| `new` | `fn(f: F) -> Self` | Yes | Create a registration for a **sync** typed function. |
| `new_async` | `fn(f: F) -> Self` | Yes | Create a registration for an **async** typed function. |
| `observable` | `fn(observable: bool) -> Self` | Yes | `false`: nobody may observe the function (`NOT_OBSERVABLE`), for one whose payloads carry credentials. Default `true`. |
| `private` | `fn() -> Self` | Yes | 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_format` | `fn(schema: Value) -> Self` | Yes | Set the request format schema. Overrides any auto-extracted schema. |
| `response_format` | `fn(schema: Value) -> Self` | Yes | Set the response format schema. Overrides any auto-extracted schema. |

***

#### TelemetryOptions

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

| Name | Type | Required | Description |
| - | - | - | - |
| `language` | `Option<String>` | No | Programming language of the worker. |
| `project_name` | `Option<String>` | No | Name of the project this worker belongs to. |
| `framework` | `Option<String>` | No | Framework name, if applicable. |

### iii\_sdk::channel

[`Channel`](#channel) · [`ChannelReader`](#channelreader) · [`ChannelWriter`](#channelwriter) · [`StreamChannelRef`](#streamchannelref)

#### Channel

A streaming channel pair for worker-to-worker data transfer.

| Name | Type | Required | Description |
| - | - | - | - |
| `writer` | [`ChannelWriter`](#channelwriter) | Yes | - |
| `reader` | [`ChannelReader`](#channelreader) | Yes | - |
| `writer_ref` | [`StreamChannelRef`](#streamchannelref) | Yes | - |
| `reader_ref` | [`StreamChannelRef`](#streamchannelref) | Yes | - |

***

#### ChannelReader

WebSocket-backed reader for streaming binary data and text messages.

| Name | Type | Required | Description |
| - | - | - | - |
| `close` | async fn() -> Result\<(), [`Error`](#error)> | Yes | - |
| `new` | fn(engine\_ws\_base: \&str, channel\_ref: &[`StreamChannelRef`](#streamchannelref)) -> Self | Yes | Authenticates with `III_TOKEN` as a bearer token when it is set. |
| `next_binary` | async fn() -> Result\<Option\<Vec\<u8>>, [`Error`](#error)> | Yes | Read the next binary chunk from the channel. Text messages are dispatched to registered callbacks. Returns `None` when the writer ended the stream cleanly (a close with no code or code 1000). Any other close code, or the connection ending without a close, is an `Err` carrying the code and reason: the data read so far is incomplete. Once a read failed, later reads fail too. After `close()`, reads (and one in flight) return `None`. |
| `on_message` | `async fn(callback: F)` | Yes | Register a callback for text messages received on this channel. |
| `read_all` | async fn() -> Result\<Vec\<u8>, [`Error`](#error)> | Yes | Read the entire stream into a single `Vec<u8>`. |

***

#### ChannelWriter

WebSocket-backed writer for streaming binary data and text messages.

| Name | Type | Required | Description |
| - | - | - | - |
| `close` | async fn() -> Result\<(), [`Error`](#error)> | Yes | End the stream cleanly. Dropping a writer that has written, without calling `close()`, ends the socket with no close frame; the reader gets that as an error. |
| `new` | fn(engine\_ws\_base: \&str, channel\_ref: &[`StreamChannelRef`](#streamchannelref)) -> Self | Yes | Authenticates with `III_TOKEN` as a bearer token when it is set. |
| `send_message` | async fn(msg: \&str) -> Result\<(), [`Error`](#error)> | Yes | - |
| `write` | async fn(data: &\[u8]) -> Result\<(), [`Error`](#error)> | Yes | - |

***

#### StreamChannelRef

| Name | Type | Required | Description |
| - | - | - | - |
| `channel_id` | `String` | Yes | - |
| `access_key` | `String` | Yes | - |
| `direction` | [`ChannelDirection`](#channeldirection) | Yes | - |

### iii\_sdk::channels

[`ChannelDirection`](#channeldirection) · [`ChannelItem`](#channelitem)

#### ChannelDirection

| Name | Type | Required | Description |
| - | - | - | - |
| `Read` | `unit` | Yes | - |
| `Write` | `unit` | Yes | - |

***

#### ChannelItem

| Name | Type | Required | Description |
| - | - | - | - |
| `Text` | `(String)` | Yes | - |
| `Binary` | `(Vec<u8>)` | Yes | - |

### iii\_sdk::context

[`InvocationCtx`](#invocationctx)

#### InvocationCtx

The invocation a handler is running for.

| Name | Type | Required | Description |
| - | - | - | - |
| `function_id` | `String` | Yes | The function being invoked. |
| `invocation_id` | `String` | Yes | This invocation's id (generated by the SDK for a local call). |
| `caller` | Option\<[`Caller`](#caller)> | No | 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). |
| `activation` | Option\<[`Activation`](#activation)> | No | Set when this invocation is an observer activation, or the target's call of a call through an observer. |
| `observe_depth` | `u32` | Yes | Depth of the causal chain in observe hops; 0 outside observers. |
| `metadata` | `Option<Value>` | No | The invocation's metadata sidecar. |
| `traceparent` | `Option<String>` | No | W3C trace context of the invocation's `execute` span, when tracing is on: the deliveries of its call join its trace. |
| `baggage` | `Option<String>` | No | W3C baggage of the invocation. |

### iii\_sdk::engine

[`EngineFunctions`](#enginefunctions) · [`EngineSources`](#enginesources)

#### EngineFunctions

Engine function ids for internal operations.

***

#### EngineSources

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`:

```rust,no_run theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
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",
);
```

### iii\_sdk::errors

[`Error`](#error) · [`InvocationError`](#invocationerror)

#### Error

Errors returned by the III SDK.

| Name | Type | Required | Description |
| - | - | - | - |
| `NotConnected` | `unit` | Yes | - |
| `Timeout` | `unit` | Yes | - |
| `Runtime` | `(String)` | Yes | - |
| `Remote` | `{ code: String, message: String, stacktrace: Option<String> }` | Yes | - |
| `Handler` | `(String)` | Yes | - |
| `Serde` | `(String)` | Yes | - |
| `WebSocket` | `(String)` | Yes | - |
| `RegistrationRejected` | `{ code: String, namespace: String, worker_name: Option<String>, function_id: Option<String>, owner_worker_id: String }` | Yes | Fatal 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. |
| `invocation_error` | fn() -> Option\<[`InvocationError`](#invocationerror)> | Yes | If this is a remote invocation failure (`Error::Remote`), return its structured form. Returns `None` for transport/serde/handler errors. |

***

#### InvocationError

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.

| Name | Type | Required | Description |
| - | - | - | - |
| `code` | `String` | Yes | - |
| `message` | `String` | Yes | - |
| `function_id` | `Option<String>` | No | - |
| `stacktrace` | `Option<String>` | No | - |

### iii\_sdk::hooks

[`AddedHook`](#addedhook) · [`Call`](#call) · [`DeliverHook`](#deliverhook) · [`Keys`](#keys) · [`Match`](#match) · [`RemovedHook`](#removedhook)

#### AddedHook

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`.

| Name | Type | Required | Description |
| - | - | - | - |
| `on_added` | fn(obs: [`Observer`](#observer)) -> impl Future\<Output = Result\<(), [`ObserveRejection`](#observerejection)>> + Send + '\_ | Yes | - |

***

#### Call

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:

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
let call = Call { input: json!({ "expression": "0 * * * * * *" }), ..Call::default() };
```

| Name | Type | Required | Description |
| - | - | - | - |
| `function_id` | `String` | Yes | - |
| `invocation_id` | `String` | Yes | - |
| `status` | [`InvocationStatus`](#invocationstatus) | Yes | - |
| `input` | `Value` | Yes | - |
| `output` | `Option<Value>` | No | The handler's return value; `None` when it failed. |
| `error` | Option\<[`ObservedError`](#observederror)> | No | What the handler failed with. |
| `caller` | Option\<[`Caller`](#caller)> | No | Who made the call; `None` for a call made outside any handler of a worker, or from an engine older than 0.25. |
| `metadata` | `Option<Value>` | No | The call's metadata sidecar. |

***

#### DeliverHook

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`.

| Name | Type | Required | Description |
| - | - | - | - |
| `on_deliver` | fn(call: [`Call`](#call), observers: Vec\<[`Observer`](#observer)>) -> impl Future\<Output = Result\<Value, [`Error`](#error)>> + Send + '\_ | Yes | - |

***

#### Keys

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

| Name | Type | Required | Description |
| - | - | - | - |
| `none` | `fn() -> Self` | Yes | No key: an observer filed nowhere, a call that matches nobody. |

***

#### Match

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.

| Name | Type | Required | Description | | | | | | | | | | |
| - | - | - | - | - | - | - | - | - | - | - | - | - | - |
| `Predicate` | (Arc\<dyn Fn(&[`Observer`](#observer), &[`Call`](#call)) -> bool + Send + Sync>) | Yes | 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`](#observer)) -> [`Keys`](#keys)\<'a> + Send + Sync>, call: Arc\<dyn Fn(&'a [`Call`](#call)) -> [`Keys`](#keys)\<'a> + Send + Sync> } | Yes | 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"`,<br />`"primary | orders | \*"`, `"primary | \* | insert"`and`"primary | \* | \*"\`: four lookups, whatever the number of observers. |
| `keys` | `fn(observer: O, call: C) -> Self` | Yes | 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. | | | | | | | | | | |
| `predicate` | fn(f: impl Fn(&[`Observer`](#observer), &[`Call`](#call)) -> bool + Send + Sync + 'static) -> Self | Yes | Does `obs` want `call`? | | | | | | | | | | |

***

#### RemovedHook

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`.

| Name | Type | Required | Description |
| - | - | - | - |
| `on_removed` | fn(obs: [`Observer`](#observer)) -> impl Future\<Output = ()> + Send + '\_ | Yes | - |

### iii\_sdk::observable

[`Observer`](#observer) · [`ObserveRejection`](#observerejection)

#### Observer

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 `Observer`s 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.

| Name | Type | Required | Description |
| - | - | - | - |
| `accepted` | async fn() -> Result\<(), [`Error`](#error)> | Yes | Resolves 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. |
| `args` | fn() -> Result\<T, [`ObserveRejection`](#observerejection)> | Yes | The observer's args as `T`. The engine validated them against the function's `args_format`; a mismatch with `T` is `INVALID_ARGS`. |
| `args_value` | `fn() -> &Value` | Yes | The observer's args as JSON (`{}` when it has none). |
| `capture` | fn() -> &\[[`Capture`](#capture)] | Yes | What deliveries ship to the target. |
| `filters` | `fn() -> &Value` | Yes | The observer's filters in normal form (`{}` matches every call). iii's delivery and `matches` apply them. |
| `function_id` | `fn() -> &str` | Yes | The observed function: the one this worker registered. |
| `id` | `fn() -> &str` | Yes | The observer's id (client-generated, stable across replays). |
| `is_active` | `fn() -> bool` | Yes | Whether it is still delivered to: accepted, and neither removed nor rejected since. |
| `matches` | fn(call: &[`Call`](#call)) -> bool | Yes | Whether `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. |
| `namespace` | `fn() -> &str` | Yes | The observed function's namespace. |
| `reject` | `fn(code: impl Into<String>, message: impl Into<String>)` | Yes | Rejects 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. |
| `target` | `fn() -> &str` | Yes | The function each delivery invokes. |

***

#### ObserveRejection

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

| Name | Type | Required | Description |
| - | - | - | - |
| `code` | `String` | Yes | - |
| `message` | `String` | Yes | - |
| `new` | `fn(code: impl Into<String>, message: impl Into<String>) -> Self` | Yes | A rejection with a code of the hook's own (`HTTP_ROUTE_CONFLICT`, `INVALID_CRON_EXPRESSION`, ...) and a message. |

### iii\_sdk::observe

[`Observed`](#observed) · [`ObservedError`](#observederror) · [`ObserverHandle`](#observerhandle) · [`ObserverOptions`](#observeroptions) · [`ObserverReason`](#observerreason) · [`ObserverStatus`](#observerstatus) · [`Source`](#source) · [`StateListener`](#statelistener) · [`Target`](#target)

#### Observed

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

```rust,no_run theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
iii.register_function(
    "alerts::payment-failed",
    RegisterFunction::new(|event: Observed<Value>| {
        println!("{} failed: {:?}", event.function_id, event.error);
        Ok::<_, Error>(())
    }),
);
```

| Name | Type | Required | Description |
| - | - | - | - |
| `observer_id` | `String` | Yes | - |
| `activation_id` | `String` | Yes | - |
| `function_id` | `String` | Yes | - |
| `namespace` | `Option<String>` | No | - |
| `invocation_id` | `String` | Yes | - |
| `status` | [`InvocationStatus`](#invocationstatus) | Yes | - |
| `input` | `Option<I>` | No | - |
| `output` | `Option<O>` | No | - |
| `error` | Option\<[`ObservedError`](#observederror)> | No | - |
| `caller` | Option\<[`Caller`](#caller)> | No | - |
| `metadata` | `Option<Value>` | No | - |
| `started_at_ms` | `u64` | Yes | - |
| `duration_ms` | `f64` | Yes | - |

***

#### ObservedError

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

| Name | Type | Required | Description |
| - | - | - | - |
| `code` | `String` | Yes | - |
| `message` | `String` | Yes | - |

***

#### ObserverHandle

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.

| Name | Type | Required | Description |
| - | - | - | - |
| `dispose` | async fn() -> Result\<(), [`Error`](#error)> | Yes | Removes 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`. |
| `fires` | `fn() -> u64` | Yes | Activations so far, as last reported by the engine. |
| `id` | `fn() -> &str` | Yes | The observer's id. |
| `on_state_change` | fn(listener: F) -> [`StateListener`](#statelistener) | Yes | Calls `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. |
| `ready` | async fn() -> Result\<(), [`Error`](#error)> | Yes | Resolves 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`. |
| `reason` | fn() -> Option\<[`ObserverReason`](#observerreason)> | Yes | Why 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. |
| `state` | fn() -> [`ObserverState`](#observerstate) | Yes | The current state. |
| `warnings` | `fn() -> Vec<String>` | Yes | The engine's warnings about the filters (paths it could not verify against an open schema). |

***

#### ObserverOptions

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

| Name | Type | Required | Description |
| - | - | - | - |
| `expires_in` | `fn(expires_in: Duration) -> Self` | Yes | Dispose of the observer after this long. |
| `id` | `fn(id: impl Into<String>) -> Self` | Yes | The observer's id. Default: a random UUID v4, kept across replays. |
| `max_fires` | `fn(max_fires: u64) -> Self` | Yes | Dispose of the observer after this many activations. |
| `max_in_flight` | `fn(max_in_flight: u32) -> Self` | Yes | At most this many activations running at once; more queue in the engine, and a call through the observer fails with `OVERFLOW`. |
| `metadata` | `fn(metadata: Value) -> Self` | Yes | Delivered as the metadata sidecar of every activation. The worker that hosts the function never sees it. |

***

#### ObserverReason

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

| Name | Type | Required | Description |
| - | - | - | - |
| `code` | `String` | Yes | - |
| `message` | `String` | Yes | - |

***

#### ObserverStatus

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

| Name | Type | Required | Description |
| - | - | - | - |
| `state` | [`ObserverState`](#observerstate) | Yes | - |
| `reason` | Option\<[`ObserverReason`](#observerreason)> | No | - |
| `fires` | `u64` | Yes | - |

***

#### Source

The left side of an observer: what is observed.

| Name | Type | Required | Description |
| - | - | - | - |
| `args` | `fn(args: Value) -> Self` | Yes | 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. |
| `capture` | fn(capture: impl IntoIterator\<Item = [`Capture`](#capture)>) -> Self | Yes | What the target's payload carries, and with it which outcomes fire the target. Default `[input, output, caller]`. |
| `filters` | `fn(filters: Value) -> Self` | Yes | 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. |
| `function` | `fn(function_id: impl Into<String>) -> Self` | Yes | Observe `function_id`. Every function is observable. |
| `function_id` | `fn() -> &str` | Yes | The observed function id. |
| `namespace` | `fn(namespace: impl Into<String>) -> Self` | Yes | The namespace the function is in. Unset, it resolves like a `call`: this worker's namespace (`default` for `engine::*` and `configuration::*`). |

***

#### StateListener

A listener added with `ObserverHandle::on_state_change`.

| Name | Type | Required | Description |
| - | - | - | - |
| `unsubscribe` | `fn()` | Yes | Stops calling the listener. |

***

#### Target

The right side of an observer: a registered function.

| Name | Type | Required | Description |
| - | - | - | - |
| `function` | `fn(function_id: impl Into<String>) -> Self` | Yes | - |
| `namespace` | `fn(namespace: impl Into<String>) -> Self` | Yes | The target's namespace. Unset, it resolves like a `call`. |

### iii\_sdk::protocol

[`Activation`](#activation) · [`CallAction`](#callaction) · [`Caller`](#caller) · [`CallRequest`](#callrequest) · [`CallRequestWithMetadata`](#callrequestwithmetadata) · [`Capture`](#capture) · [`Dispatch`](#dispatch) · [`DroppedReportStats`](#droppedreportstats) · [`ErrorBody`](#errorbody) · [`FunctionMessage`](#functionmessage) · [`InvocationStatus`](#invocationstatus) · [`LocalFunctionStats`](#localfunctionstats) · [`Message`](#message) · [`ObservedItem`](#observeditem) · [`ObserverState`](#observerstate) · [`ObserverView`](#observerview) · [`ObserveSource`](#observesource) · [`ObserveTarget`](#observetarget) · [`ParentCaller`](#parentcaller) · [`RegisterFunctionMessage`](#registerfunctionmessage)

#### Activation

`invokefunction.activation`.

| Name | Type | Required | Description |
| - | - | - | - |
| `observer_id` | `String` | Yes | - |
| `activation_id` | `Option<String>` | No | Engine → worker: unique per activation. Absent on a call through an observer as its host sends it. |

***

#### CallAction

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.

| Name | Type | Required | Description |
| - | - | - | - |
| `Enqueue` | `{ queue: String }` | Yes | Routes the invocation through a named queue. |
| `Void` | `unit` | Yes | Fire-and-forget routing. |

***

#### Caller

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.

| Name | Type | Required | Description |
| - | - | - | - |
| `worker_id` | `Option<String>` | No | - |
| `worker_name` | `Option<String>` | No | - |
| `function_id` | `Option<String>` | No | The handler the call was made from; absent for a top-level call. |
| `invocation_id` | `Option<String>` | No | - |
| `parent` | Option\<[`ParentCaller`](#parentcaller)> | No | The caller of that handler, one level only. |
| `strip` | fn() -> [`ParentCaller`](#parentcaller) | Yes | This caller without its own `parent`, as the `parent` of a call made from the handler it invoked. |

***

#### CallRequest

Request object for `IIIClient::call`.

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
// 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" }));
```

| Name | Type | Required | Description |
| - | - | - | - |
| `function_id` | `String` | Yes | ID of the function to invoke. |
| `payload` | `Value` | Yes | Input data passed to the function. |
| `action` | Option\<[`CallAction`](#callaction)> | No | Sets how the call is routed. `None` for a synchronous request/response. Set a routing scheme otherwise (e.g. `CallAction::Enqueue { .. }`, `CallAction::Void`). |
| `timeout_ms` | `Option<u64>` | No | Override the default invocation timeout, in milliseconds. |
| `dispatch` | fn(dispatch: [`Dispatch`](#dispatch)) -> [`CallRequestWithMetadata`](#callrequestwithmetadata) | Yes | 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. |
| `metadata` | fn(metadata: Value) -> [`CallRequestWithMetadata`](#callrequestwithmetadata) | Yes | Attach per-invocation metadata without adding a required field to `CallRequest` struct literals. |
| `namespace` | fn(namespace: impl Into\<String>) -> [`CallRequestWithMetadata`](#callrequestwithmetadata) | Yes | Target a specific namespace for this invocation without adding a required field to `CallRequest` struct literals. Serializes into `Message::InvokeFunction`'s `namespace`. |
| `new` | `fn(function_id: impl Into<String>, payload: Value) -> Self` | Yes | A synchronous request/response call of `function_id` with `payload`, the default timeout and no routing action. |
| `observer` | fn(observer: &[`Observer`](#observer), payload: Value) -> [`CallRequestWithMetadata`](#callrequestwithmetadata) | Yes | 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`). |

***

#### CallRequestWithMetadata

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

| Name | Type | Required | Description |
| - | - | - | - |
| `action` | fn(action: [`CallAction`](#callaction)) -> Self | Yes | How the call is routed; see `CallRequest::action`. |
| `dispatch` | fn(dispatch: [`Dispatch`](#dispatch)) -> Self | Yes | Choose the path this call takes; see `Dispatch`. |
| `metadata` | `fn(metadata: Value) -> Self` | Yes | 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. |
| `namespace` | `fn(namespace: impl Into<String>) -> Self` | Yes | Target a specific namespace for this invocation. |
| `timeout` | `fn(timeout: Duration) -> Self` | Yes | Override the default invocation timeout. |

***

#### Capture

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

| Name | Type | Required | Description |
| - | - | - | - |
| `Input` | `unit` | Yes | - |
| `Output` | `unit` | Yes | - |
| `Error` | `unit` | Yes | - |
| `Caller` | `unit` | Yes | - |
| `Metadata` | `unit` | Yes | - |
| `Unknown` | `(String)` | Yes | A value this SDK does not know, kept verbatim. |
| `as_str` | `fn() -> &str` | Yes | The wire spelling. |

***

#### Dispatch

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.

| Name | Type | Required | Description |
| - | - | - | - |
| `Auto` | `unit` | Yes | Run in-process when the five conditions above hold, else remote. |
| `Remote` | `unit` | Yes | Always route through the engine (engine-side effects, tests). |

***

#### DroppedReportStats

SDK-side report drops in `localinvocationstats`.

| Name | Type | Required | Description |
| - | - | - | - |
| `function_id` | `String` | Yes | - |
| `reason` | `String` | Yes | `observe_codes::BUFFER_FULL`, `observe_codes::TOO_LARGE` or `observe_codes::INACTIVE`. |
| `count` | `u64` | Yes | - |

***

#### ErrorBody

| Name | Type | Required | Description |
| - | - | - | - |
| `code` | `String` | Yes | - |
| `message` | `String` | Yes | - |
| `stacktrace` | `Option<String>` | No | - |
| `new` | `fn(code: impl Into<String>, message: impl Into<String>) -> Self` | Yes | An error body without a stacktrace. |

***

#### FunctionMessage

| Name | Type | Required | Description |
| - | - | - | - |
| `function_id` | `String` | Yes | - |
| `description` | `Option<String>` | No | - |
| `request_format` | `Option<Value>` | No | - |
| `response_format` | `Option<Value>` | No | - |
| `metadata` | `Option<Value>` | No | - |

***

#### InvocationStatus

Outcome of an observed call.

| Name | Type | Required | Description |
| - | - | - | - |
| `Success` | `unit` | Yes | - |
| `Error` | `unit` | Yes | - |
| `Unknown` | `(String)` | Yes | A value this SDK does not know, kept verbatim. |
| `as_str` | `fn() -> &str` | Yes | The wire spelling. |

***

#### LocalFunctionStats

Per-function counts in `localinvocationstats`.

| Name | Type | Required | Description |
| - | - | - | - |
| `function_id` | `String` | Yes | - |
| `count` | `u64` | Yes | - |
| `errors` | `u64` | Yes | - |
| `duration_ms_sum` | `f64` | Yes | - |

***

#### Message

| Name | Type | Required | Description |
| - | - | - | - |
| `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`](#callaction)>, metadata: Option\<Value>, namespace: Option\<String>, caller: Option\<Box\<[`Caller`](#caller)>>, observe\_depth: Option\<u32>, activation: Option\<[`Activation`](#activation)> } | Yes | - |
| `InvocationResult` | \{ invocation\_id: uuid::Uuid, function\_id: String, result: Option\<Value>, error: Option\<[`ErrorBody`](#errorbody)>, traceparent: Option\<String>, baggage: Option\<String>, matched: Option\<Vec\<String>>, delivered: bool } | Yes | - |
| `Ping` | `unit` | Yes | - |
| `Pong` | `unit` | Yes | - |
| `Reattach` | `{ previous_worker_id: String, reattach_token: Option<String> }` | Yes | Sent 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 }` | Yes | Pushed 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`](#observesource)>, target: [`ObserveTarget`](#observetarget), metadata: Option\<Value>, max\_fires: Option\<u64>, expires\_in\_ms: Option\<u64>, max\_in\_flight: Option\<u32> } | Yes | Observing worker → engine: create, or idempotently replay, an observer owned by this connection. |
| `Unobserve` | `{ id: String }` | Yes | Observing worker → engine: dispose an observer this connection owns. |
| `ObserveResult` | \{ id: String, state: [`ObserverState`](#observerstate), error: Option\<[`ErrorBody`](#errorbody)>, warnings: Vec\<String> } | Yes | Engine → observing worker: the reply to `observe` (also on replay). |
| `ObserverStateChanged` | \{ id: String, state: [`ObserverState`](#observerstate), reason: Option\<[`ErrorBody`](#errorbody)>, fires: u64 } | Yes | Engine → observing worker: every lifecycle transition. |
| `FunctionRegistered` | \{ id: String, namespace: String, revision: u64, local\_dispatch: bool, observers: Vec\<[`ObserverView`](#observerview)> } | Yes | Engine → 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`](#observerview) } | Yes | Engine → host: one observer attached to a function this connection hosts. Awaits `observerack`. |
| `ObserverRemoved` | `{ function_id: String, namespace: String, revision: u64, id: String }` | Yes | Engine → host: one observer detached. |
| `ObserverAck` | \{ function\_id: String, namespace: Option\<String>, id: String, revision: u64, error: Option\<[`ErrorBody`](#errorbody)> } | Yes | Host → engine: accepts one added observer, or rejects it with `error` (also later, for an active observer: a late rejection). |
| `InvocationsObserved` | \{ items: Vec\<[`ObservedItem`](#observeditem)> } | Yes | Host → 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`](#localfunctionstats)>, dropped\_reports: Vec\<[`DroppedReportStats`](#droppedreportstats)> } | Yes | Host → engine: local invocation counts and SDK-side report drops, every 10 s and only when non-zero. |
| `Unknown` | `unit` | Yes | Any message type this SDK does not know, sent by a newer engine. It is ignored (logged at debug level), never sent. |

***

#### ObservedItem

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.

| Name | Type | Required | Description |
| - | - | - | - |
| `function_id` | `String` | Yes | - |
| `namespace` | `Option<String>` | No | - |
| `invocation_id` | `String` | Yes | - |
| `matched` | `Vec<String>` | Yes | - |
| `status` | [`InvocationStatus`](#invocationstatus) | Yes | - |
| `input` | `Option<Value>` | No | - |
| `output` | `Option<Value>` | No | - |
| `error` | `Option<Value>` | No | - |
| `caller` | Option\<[`Caller`](#caller)> | No | - |
| `metadata` | `Option<Value>` | No | - |
| `started_at_ms` | `u64` | Yes | - |
| `duration_ms` | `f64` | Yes | - |
| `observe_depth` | `u32` | Yes | - |
| `traceparent` | `Option<String>` | No | - |
| `baggage` | `Option<String>` | No | - |
| `output_is_input` | `bool` | Yes | The handler returned its input: the item carries it once, as `input`, and the engine fills `output` from it. |

***

#### ObserverState

Observer lifecycle states.

| Name | Type | Required | Description |
| - | - | - | - |
| `Pending` | `unit` | Yes | Waiting for its function's host (and its ack) or its target. |
| `Active` | `unit` | Yes | Delivering. |
| `Suspended` | `unit` | Yes | Its observing worker or its target is gone for now. |
| `Error` | `unit` | Yes | Rejected; see the reason. |
| `Disposed` | `unit` | Yes | Gone for good. |
| `Unknown` | `(String)` | Yes | A value this SDK does not know, kept verbatim. |
| `as_str` | `fn() -> &str` | Yes | The wire spelling. |

***

#### ObserverView

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

| Name | Type | Required | Description |
| - | - | - | - |
| `id` | `String` | Yes | - |
| `args` | `Value` | Yes | `{}` for an observer without args. |
| `filters` | `Value` | Yes | The observer's filters in normal form; `{}` matches every call. |
| `target` | `String` | Yes | Target function id (its namespace is not disclosed). |
| `capture` | Vec\<[`Capture`](#capture)> | Yes | - |
| `fires_on` | Option\<Vec\<[`InvocationStatus`](#invocationstatus)>> | No | The outcomes that fire it, from an engine with `FEATURE_OBSERVE_CAPTURE`; absent from an older engine, whose observers fire as their legacy `on` says. |
| `on` | `Option<Value>` | No | The legacy `on` of an engine without `FEATURE_OBSERVE_CAPTURE` (absent: success; `error`; `complete`). Read only when `fires_on` is absent; deprecated. |
| `fires_on` | `fn(success: bool) -> bool` | Yes | Whether a call that ended in success (or not) fires this observer: from `fires_on`, or else from the legacy `on`, never from `capture`. |

***

#### ObserveSource

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

| Name | Type | Required | Description |
| - | - | - | - |
| `function_id` | `String` | Yes | - |
| `namespace` | `Option<String>` | No | - |
| `args` | `Option<Value>` | No | - |
| `filters` | `Option<Value>` | No | - |
| `capture` | Option\<Vec\<[`Capture`](#capture)>> | No | - |

***

#### ObserveTarget

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

| Name | Type | Required | Description |
| - | - | - | - |
| `function_id` | `String` | Yes | - |
| `namespace` | `Option<String>` | No | - |

***

#### ParentCaller

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

| Name | Type | Required | Description |
| - | - | - | - |
| `worker_id` | `Option<String>` | No | - |
| `worker_name` | `Option<String>` | No | - |
| `function_id` | `Option<String>` | No | - |
| `invocation_id` | `Option<String>` | No | - |

***

#### RegisterFunctionMessage

| Name | Type | Required | Description |
| - | - | - | - |
| `id` | `String` | Yes | - |
| `description` | `Option<String>` | No | - |
| `request_format` | `Option<Value>` | No | - |
| `response_format` | `Option<Value>` | No | - |
| `metadata` | `Option<Value>` | No | - |
| `invocation` | `Option<iii_helpers::http::HttpInvocationConfig>` | No | - |
| `args_format` | `Option<Value>` | No | See `RegisterFunction::args_format`. |
| `private` | `bool` | Yes | See `RegisterFunction::private`. |
| `observable` | `bool` | Yes | See `RegisterFunction::observable`. |
| `to_message` | fn() -> [`Message`](#message) | Yes | - |
| `with_description` | `fn(description: String) -> Self` | Yes | - |
| `with_id` | `fn(name: String) -> Self` | Yes | - |

### iii\_sdk::runtime

[`FunctionInfo`](#functioninfo) · [`FunctionRef`](#functionref) · [`IIIConnectionState`](#iiiconnectionstate) · [`WorkerIdentityMode`](#workeridentitymode) · [`WorkerInfo`](#workerinfo) · [`WorkerMetadata`](#workermetadata)

#### FunctionInfo

Function information returned by `engine::functions::list`

| Name | Type | Required | Description |
| - | - | - | - |
| `function_id` | `String` | Yes | - |
| `description` | `Option<String>` | No | - |
| `request_format` | `Option<Value>` | No | - |
| `response_format` | `Option<Value>` | No | - |
| `metadata` | `Option<Value>` | No | - |
| `namespace` | `Option<String>` | No | - |
| `args_format` | `Option<Value>` | No | JSON Schema of the function's observer args, when it takes any. |
| `private` | `bool` | Yes | Only its host may call it. |
| `observable` | `bool` | Yes | `false`: nobody may observe it. |
| `observer_count` | `u64` | Yes | Observers of the function. |

***

#### FunctionRef

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.

```rust,no_run theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
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());
});
```

| Name | Type | Required | Description |
| - | - | - | - |
| `id` | `String` | Yes | - |
| `clear_observation_deliver` | `fn() -> &Self` | Yes | `IIIClient::clear_observation_deliver_for` this function. |
| `clear_observation_match` | `fn() -> &Self` | Yes | `IIIClient::clear_observation_match_for` this function. |
| `clear_observer_added` | `fn() -> &Self` | Yes | `IIIClient::clear_observer_added_for` this function. |
| `clear_observer_removed` | `fn() -> &Self` | Yes | `IIIClient::clear_observer_removed_for` this function. |
| `is_observed` | `fn() -> bool` | Yes | Whether 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_for` | fn(call: &[`Call`](#call)) -> bool | Yes | Whether `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_active` | `fn() -> bool` | Yes | Whether calls to this function from this worker currently run in-process (the engine confirmed it with `local_dispatch: true`). |
| `observers` | fn() -> Vec\<[`Observer`](#observer)> | Yes | The active observers, as the host sees them. |
| `on_observation_deliver` | fn(hook: impl [`DeliverHook`](#deliverhook)) -> \&Self | Yes | `IIIClient::on_observation_deliver_for` this function. |
| `on_observation_match` | fn(rule: [`Match`](#match)) -> \&Self | Yes | `IIIClient::on_observation_match_for` this function. |
| `on_observer_added` | fn(hook: impl [`AddedHook`](#addedhook)) -> \&Self | Yes | `IIIClient::on_observer_added_for` this function. |
| `on_observer_removed` | fn(hook: impl [`RemovedHook`](#removedhook)) -> \&Self | Yes | `IIIClient::on_observer_removed_for` this function. |
| `unregister` | `fn()` | Yes | Unregisters the function. Its hooks stay set, for a later registration of the same id. |

***

#### IIIConnectionState

Connection state for the III WebSocket client

| Name | Type | Required | Description |
| - | - | - | - |
| `Disconnected` | `unit` | Yes | - |
| `Connecting` | `unit` | Yes | - |
| `Connected` | `unit` | Yes | - |
| `Reconnecting` | `unit` | Yes | - |
| `Failed` | `unit` | Yes | - |

***

#### WorkerIdentityMode

Selects where a worker connection gets its engine identity.

| Name | Type | Required | Description |
| - | - | - | - |
| `Managed` | `unit` | Yes | Use the supervisor-managed `III_WORKER_NAME` and `III_NAMESPACE` values when present. This is the default for normal worker connections. |
| `Explicit` | `unit` | Yes | Keep 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. |

***

#### WorkerInfo

Worker information returned by `engine::workers::list`

| Name | Type | Required | Description |
| - | - | - | - |
| `id` | `String` | Yes | - |
| `name` | `Option<String>` | No | - |
| `runtime` | `Option<String>` | No | - |
| `version` | `Option<String>` | No | - |
| `os` | `Option<String>` | No | - |
| `ip_address` | `Option<String>` | No | - |
| `status` | `String` | Yes | - |
| `connected_at_ms` | `u64` | Yes | - |
| `function_count` | `usize` | Yes | - |
| `functions` | `Vec<String>` | Yes | - |
| `active_invocations` | `usize` | Yes | - |
| `isolation` | `Option<String>` | No | - |
| `namespace` | `Option<String>` | No | - |

***

#### WorkerMetadata

Worker metadata for auto-registration

| Name | Type | Required | Description |
| - | - | - | - |
| `runtime` | `String` | Yes | - |
| `version` | `String` | Yes | Version 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. |
| `name` | `String` | Yes | Worker name reported to the engine. In managed identity mode, a non-empty `III_WORKER_NAME` overrides this value when the client is created. |
| `os` | `String` | Yes | - |
| `description` | `Option<String>` | No | One-line, human/LLM-readable summary of what this worker does. Surfaces in `engine::workers::list` / `engine::workers::info`. |
| `pid` | `Option<u32>` | No | - |
| `telemetry` | Option\<[`TelemetryOptions`](#telemetryoptions)> | No | - |
| `isolation` | `Option<String>` | No | - |
| `namespace` | `Option<String>` | No | Namespace 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. |

### iii\_sdk::structs

[`MiddlewareFunctionInput`](#middlewarefunctioninput)

#### MiddlewareFunctionInput

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.

| Name | Type | Required | Description |
| - | - | - | - |
| `function_id` | `String` | Yes | ID of the function being invoked. |
| `payload` | `Value` | Yes | Payload sent by the caller. |
| `action` | Option\<[`CallAction`](#callaction)> | No | Routing action, if any. |
| `context` | `Value` | Yes | Auth context returned by the auth function for this session. |
| `namespace` | `Option<String>` | No | Target namespace the invoke addressed; forward the call here to stay in the caller's namespace. Absent → the engine's default namespace. |

### iii\_sdk::types

[`RemoteFunctionData`](#remotefunctiondata) · [`RemoteFunctionHandler`](#remotefunctionhandler) · [`StreamRequest`](#streamrequest) · [`StreamResponse`](#streamresponse)

#### RemoteFunctionData

| Name | Type | Required | Description |
| - | - | - | - |
| `message` | [`RegisterFunctionMessage`](#registerfunctionmessage) | Yes | - |
| `handler` | `Option<RemoteFunctionHandlerWithMetadata>` | No | - |

***

#### RemoteFunctionHandler

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.

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
type RemoteFunctionHandler = Arc<dyn Fn(Value) -> futures_util::future::BoxFuture<'static, Result<Value, Error>> + Send + Sync>
```

***

#### StreamRequest

Incoming streaming request received by a function that serves HTTP.

Alias of `iii_helpers::http::HttpRequest`.

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
type StreamRequest = iii_helpers::http::HttpRequest<T>
```

***

#### StreamResponse

Streaming response type, mirroring the Node and Python `StreamResponse`.

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

```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
type StreamResponse = iii_helpers::http::HttpResponse<T>
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.