Skip to main content

Installation

Initialization

register_worker

Register the worker with a iii instance, returns a connected worker client. Blocks up to 30 seconds for the WebSocket connection to be established. If the engine is not reachable in time, a warning is logged and the client is returned anyway; it keeps retrying in the background and flushes registrations once connected. Use add_connection_state_listener to observe the actual transition. Signature
str | None
WebSocket URL of the III engine (e.g. ws://localhost:49134). When omitted, resolves from III_URL and then DEFAULT_ENGINE_URL.
InitOptions | None
Optional configuration for worker name, timeouts, reconnection, and OTel.

Methods

register_trigger

Deprecated since 0.25.0. Use iii.observe(source, target) instead: iii.observe({"function_id": ..., "args": ..., "filters": ...}, target, {"metadata": ...}). Emits a DeprecationWarning and logs a warning once per process. The http, cron, queue, state, stream, pubsub and database workers still publish trigger types: keep using register_trigger for them until they ship source functions. Migration guide: https://iii.dev/docs/upgrading/from-0-24-x
Bind a trigger configuration to a registered function. Signature
RegisterTriggerInput | dict[str, Any]
required
A RegisterTriggerInput or dict with type, function_id, and optional config.

register_function

Register a function with the engine. Pass a handler for local execution, or an HttpInvocationConfig for HTTP-invoked functions (Lambda, Cloudflare Workers, etc.). Handlers can be synchronous or asynchronous. Sync handlers are automatically wrapped with run_in_executor so they do not block the event loop. Each handler receives a data argument containing the trigger payload, and may optionally accept a second metadata argument carrying per-invocation metadata (e.g. def handler(data, metadata=None) or def handler(data, *, metadata=None)). Metadata is only forwarded to handlers that declare a parameter literally named metadata, so existing handlers, including ones with unrelated extra parameters, *args, or **kwargs, keep working unchanged. request_format and response_format are auto-extracted from the handler’s type hints when omitted or passed as None (the default). To opt out of auto-extraction, pass an explicit schema (RegisterFunctionFormat or dict). This behavior is Python-specific; the Node SDK relies on explicit schemas because TypeScript types are erased at runtime. Signature
str
required
Unique string identifier for the function.
RemoteFunctionHandler | HttpInvocationConfig
required
A callable handler or HttpInvocationConfig. Callable handlers receive data (the trigger payload) as the first argument and may optionally accept metadata (per-invocation metadata) as a second argument; they may return a value.
str | None
Human-readable description of what the function does.
dict[str, Any] | None
Arbitrary metadata attached to the function.
RegisterFunctionFormat | dict[str, Any] | None
Schema describing expected input. When None (default), auto-extracted from the handler’s first-parameter type hint. Pass an explicit schema to override; there is no way to register with no schema when the handler is typed.
RegisterFunctionFormat | dict[str, Any] | None
Schema describing expected output. Same auto-extraction semantics as request_format.
ObserveHooks | dict[str, Any] | None
Makes the function observable on its own terms: owner delivery (delivery="owner", args_format), and callbacks when an observer is added or removed (an :class:ObserveHooks, a subclass of it, or a dict of its fields). Without it the function is still observable (auto delivery, no args).
bool
Calls this worker makes to its own function run in-process once the engine confirmed it (default True). Like a remote invocation, each local call to a sync handler runs on a thread of its own (one per call, not pooled), so the caller can stop waiting at its timeout. A sync handler that blocks for long should be async, or set False so its calls go through the engine (also for a handler that relies on engine-side effects).

trigger

Invoke a remote function. The routing behavior and return type depend on the action field:
  • No action: synchronous, waits for the function to return.
  • TriggerAction.Enqueue(...): async via named queue, returns a dict with messageReceiptId.
  • TriggerAction.Void(): fire-and-forget, returns None.
A function this worker registered with a handler, once the engine confirmed it, runs in-process (local dispatch, sdk.md §3): a sync handler on a thread of its own (the caller waits up to the timeout), an async one on the SDK loop. Its observers are still evaluated, and only matched calls reach the engine. dispatch="remote" (or action=Enqueue) always goes through the engine. Whatever a local handler raises, BaseExceptions such as KeyboardInterrupt and SystemExit included, reaches the caller as InvocationError("invocation_failed") with the original as its __cause__ (for a Void call nothing reaches the caller: the error is logged). Signature
dict[str, Any] | TriggerRequest
required
A TriggerRequest or dict with function_id, payload, and optional action / timeout_ms / metadata / namespace / dispatch ("auto", the default, or "remote").

register_trigger_type

Deprecated since 0.25.0. Register a function with an observe descriptor instead: register_function(id, handler, observe=ObserveHooks(delivery="owner", on_observer_added=..., on_observer_removed=...)). Emits a DeprecationWarning and logs a warning once per process. Migration guide: https://iii.dev/docs/upgrading/from-0-24-x
Register a custom trigger type with the engine. Returns a :class:TriggerTypeRef handle with register_trigger and register_function methods. Signature
RegisterTriggerTypeInput | dict[str, Any]
required
A RegisterTriggerTypeInput or dict with id, description, and optional trigger_request_format / call_request_format (Pydantic class or dict).
TriggerHandler[Any]
required
A TriggerHandler instance.

unregister_trigger_type

Deprecated since 0.25.0. Trigger types are replaced by functions with an observe descriptor; unregister the function instead. Migration guide: https://iii.dev/docs/upgrading/from-0-24-x
Unregister a previously registered trigger type. Signature
RegisterTriggerTypeInput | dict[str, Any]
required
A RegisterTriggerTypeInput or dict with id, an optional description, and (dict only) the namespace it was registered in.

add_connection_state_listener

Subscribe to connection-state transitions. The handler is fired immediately with the current state (on the caller’s thread), then once per transition. Transitions fire on the SDK’s background event-loop thread: keep handlers fast and do not call sync SDK methods from them (they would raise RuntimeError). Treat calls as state notifications, not edges. A state may rarely be observed twice around subscription. Registering the same handler twice fires it twice. Returns an idempotent unsubscribe function that removes only its own registration. Signature
ConnectionStateCallback
required

connect_async

Connect to the III Engine via WebSocket. Initializes OpenTelemetry (if configured), attaches the event loop, and establishes the WebSocket connection. This is called automatically during construction; use it only if you need to reconnect manually from an async context. Signature

current_invocation

The invocation the calling code runs in (in every handler, remote or local), or None outside any handler. Signature

Example


get_address

Return the engine address this worker resolved to. The explicit register_worker argument, else III_URL, else :data:DEFAULT_ENGINE_URL. Mirrors the Rust SDK’s address() and the Node SDK’s getAddress(). Signature

get_connection_state

Return the current WebSocket connection state. Signature

Example


observe

Observes a function: every event of source (an invocation of an auto function, or what its owner hands over) that passes source["filters"] invokes target, a registered function. Returns synchronously, also before the connection is up; the observer is replayed with the same id on every reconnect. Errors (INVALID_ARGS, INVALID_FILTER, FORBIDDEN, an owner’s rejection, UNSUPPORTED against an engine without observe) show up as state error and make ready() raise :class:ObserveRejection. Signature
ObserveSource | dict[str, Any]
required
What is observed: function_id, namespace, args (owner-delivered functions only), filters, and on / capture / deliver.
Target
required
The function to invoke: its id, or {"function_id": ..., "namespace": ...}. Register it first; until then the observer stays pending.
ObserverOptions | dict[str, Any] | None
id, max_fires, expires_in_ms, max_in_flight, metadata (the activation’s metadata sidecar).

shutdown

Gracefully shut down the client, releasing all resources. Cancels any pending reconnection attempts, rejects all in-flight invocations with an error, closes the WebSocket connection, and stops the background event-loop thread. After this call the instance must not be reused. Signature

Example


shutdown_async

Gracefully shut down the client, releasing all resources. Cancels any pending reconnection attempts, rejects all in-flight invocations with an error, closes the WebSocket connection, and stops the background event-loop thread. After this call the instance must not be reused. Signature

Example


trigger_async

Invoke a remote function. The routing behavior and return type depend on the action field:
  • No action: synchronous, waits for the function to return.
  • TriggerAction.Enqueue(...): async via named queue, returns a dict with messageReceiptId.
  • TriggerAction.Void(): fire-and-forget, returns None.
Works from any event loop. A function this worker registered with a handler, once the engine confirmed it, runs in-process on the calling loop (a sync handler on a thread of its own); dispatch="remote" (or action=Enqueue) always goes through the engine. Signature
dict[str, Any] | TriggerRequest
required
A TriggerRequest or dict with function_id, payload, and optional action / timeout_ms / metadata / namespace / dispatch ("auto" or "remote").

Types

iii

Caller · EnqueueResult · InitOptions · InvocationContext · MiddlewareFunctionInput · Observed · ObserveHooks · Observer · ObserverHandle · ObserverOptions · ObserveSource · StreamRequest · StreamResponse · TelemetryOptions · TriggerAction · TriggerActionEnqueue

Caller

Who started an invocation: the worker (worker_id / worker_name, stamped by the engine), and the function and invocation the call was made from (absent for top-level calls). parent is that handler’s own caller, one level only.

EnqueueResult

Result returned when a function is invoked with TriggerAction.Enqueue.

InitOptions

Configuration options passed to register_worker.

InvocationContext

The invocation the current code runs in, in every handler, remote or local. Returned by iii.current_invocation().

MiddlewareFunctionInput

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

Observed

What the target of an auto observer (or of obs.emit) receives with deliver: "envelope" (the default). Fields not in the observer’s capture are absent.

ObserveHooks

The observe option of register_function: how the function’s observers are delivered, and the callbacks that run when one is added or removed. Pass an instance, built with keyword arguments or from a subclass that sets the attributes and defines the callbacks as (sync or async) methods. Only delivery, args_format, legacy_trigger_type and allow travel to the engine; the callbacks stay in this process.

Observer

An observer as the function’s owner sees it (on_observer_added, FunctionRef.observers()): its args, filters, target, capture and on. Never its metadata, policy or the observing worker. The object stays the same for the observer’s whole lifetime, so owners keep it in their own index (expression → observers, route table, …).

ObserverHandle

What iii.observe returns, synchronously. The observer is replayed with the same id on every reconnect until it is disposed. State listeners are called in order, on a callback thread of the SDK (never on the event loop that reads the engine’s frames), so they may call the sync API.

ObserverOptions

The observer itself: its id, policy and metadata (the third argument of iii.observe).

ObserveSource

The left side of iii.observe: what is observed.

StreamRequest

Incoming streaming request received by a function registered with a stream trigger.

StreamResponse

Streaming response built on top of a ChannelWriter.

TelemetryOptions

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

TriggerAction

Factory for creating trigger actions used with trigger().

TriggerActionEnqueue

Routes the invocation through a named queue for async processing. Requires the queue worker in worker-compose.yaml and a matching entry under that worker’s queue_configs. Without it the trigger rejects with enqueue_error (no queue provider).

iii.channel

Channel · ChannelReader · ChannelWriter · StreamChannelRef

Channel

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

ChannelReader

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

ChannelWriter

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

StreamChannelRef

Reference to a streaming channel for worker-to-worker data transfer.

iii.engine

EngineFunctions · EngineTriggers

EngineFunctions

Engine function ids for internal operations (parity with the Node SDK).

EngineTriggers

Engine trigger ids (parity with the Node SDK).

iii.errors

InvocationError · ObserveRejection · RegistrationRejectedError

InvocationError

Raised when an invocation dispatched by the SDK fails. Inspect err.code to react to a specific category (e.g. 'FORBIDDEN' for RBAC denials, 'TIMEOUT' for timeouts). Catch this class to handle every rejection. except Exception continues to work because InvocationError inherits from Exception. Attributes are read-only after construction. stacktrace is the engine-side trace when the remote handler raised; it may include internal file paths and should not be surfaced to end users. str(err) intentionally never includes the stacktrace.

ObserveRejection

Rejects an observer with a code of its own. Raise it from an on_observer_added hook (HTTP_ROUTE_CONFLICT, INVALID_CRON_EXPRESSION, …); any other exception rejects the observer with OBSERVE_REJECTED. Also what ObserverHandle.ready() raises when the observer turns error or disposed, with the engine’s code (INVALID_ARGS, FORBIDDEN, UNSUPPORTED, …).

RegistrationRejectedError

Raised when the engine rejects this worker’s registration. The engine pushes a registrationrejected message and closes the connection on a registration collision (e.g. another live worker already owns (namespace, worker_name)). This is fatal: the SDK does not reconnect. Inspect the attributes to identify the conflict.

iii.protocol

MessageType · RegisterFunctionFormat · RegisterFunctionInput · RegisterFunctionMessage · RegisterTriggerInput · RegisterTriggerMessage · RegisterTriggerTypeInput · RegisterTriggerTypeMessage · SDK_FEATURES · TriggerRequest

MessageType

Message types for iii communication.

RegisterFunctionFormat

Format definition for function parameters.

RegisterFunctionInput

Input for registering a function, matches Node.js RegisterFunctionInput.

RegisterFunctionMessage


RegisterTriggerInput

Input for registering a trigger (matches Node SDK’s RegisterTriggerInput).

RegisterTriggerMessage


RegisterTriggerTypeInput

Input for registering a trigger type.

RegisterTriggerTypeMessage


SDK_FEATURES


TriggerRequest

Request object for trigger().

iii.runtime

FunctionRef · TriggerTypeRef

FunctionRef

Reference to a registered function, allowing programmatic unregistration.

TriggerTypeRef

Typed handle returned by :meth:iii.III.register_trigger_type. .. deprecated:: 0.25.0 Trigger types are replaced by functions with an observe descriptor, and these helpers by iii.observe. Migration guide: https://iii.dev/docs/upgrading/from-0-24-x Type parameters:
  • C: configuration type for :meth:register_trigger
  • R: call-request type for :meth:register_function

iii.state

IState · StateDeleteInput · StateDeleteResult · StateEventData · StateEventType · StateGetInput · StateListInput · StateSetInput · StateSetResult · StateUpdateInput · StateUpdateResult

IState

Abstract interface for state management operations.

StateDeleteInput

Input for deleting a state value.

StateDeleteResult

Result of a state delete operation.

StateEventData

Payload for state change events.

StateEventType

Types of state change events.

StateGetInput

Input for retrieving a state value.

StateListInput

Input for listing all values in a state scope.

StateSetInput

Input for setting a state value.

StateSetResult

Result of a state set operation.

StateUpdateInput

Input for atomically updating a state value.

StateUpdateResult

Result of a state update operation.

iii.stream

IStream · StreamDeleteInput · StreamDeleteResult · StreamGetInput · StreamListGroupsInput · StreamListInput · StreamSetInput · StreamSetResult · StreamUpdateInput · StreamUpdateResult

IStream

Abstract interface for stream operations.

StreamDeleteInput

Input for stream delete operation.

StreamDeleteResult

Result of stream delete operation.

StreamGetInput

Input for stream get operation.

StreamListGroupsInput

Input for stream list groups operation.

StreamListInput

Input for stream list operation.

StreamSetInput

Input for stream set operation.

StreamSetResult

Result of stream set operation.

StreamUpdateInput

Input for stream update operation.

StreamUpdateResult

Result of stream update operation.

iii.trigger

Trigger · TriggerActionVoid · TriggerConfig · TriggerHandler

Trigger

Represents a registered trigger. .. deprecated:: 0.25.0 register_trigger is replaced by iii.observe, which returns an :class:~iii.ObserverHandle.

TriggerActionVoid

Fire-and-forget routing. No response is returned.

TriggerConfig

Configuration passed to a trigger handler when a trigger instance is registered or unregistered. .. deprecated:: 0.25.0 Replaced by the :class:~iii.Observer an on_observer_added hook receives (id, args, filters, target).

TriggerHandler

Abstract base class for trigger handlers. .. deprecated:: 0.25.0 Replaced by :class:~iii.ObserveHooks (on_observer_added / on_observer_removed) on register_function. Migration guide: https://iii.dev/docs/upgrading/from-0-24-x