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

# Functions

> Register functions and call them from code, the CLI, or other functions.

## Register a function

Inside a worker, `worker.registerFunction(id, handler)` makes a function callable from anywhere in
the iii system. The `id` follows the `service::name` form; the handler receives the call's payload
and returns the result.

> [tab] Node / TypeScript
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import { registerWorker } from "iii-sdk";
>
> const url = process.env.III_URL;
> if (!url) throw new Error("III_URL must be set");
> const worker = registerWorker(url, { namespace: "orders" });
>
> worker.registerFunction("math::add", async (payload: { a: number; b: number }) => {
>   return { c: payload.a + payload.b };
> });
> ```

> [tab] Python
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import os
> from iii import register_worker, InitOptions
>
> worker = register_worker(
>     os.environ.get("III_URL"),
>     InitOptions(
>         worker_name="math-worker",
>         namespace="orders",
>     ),
> )
>
> def add_handler(payload: dict) -> dict:
>     return {"c": payload["a"] + payload["b"]}
>
> worker.register_function("math::add", add_handler)
> ```

> [tab] Rust
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> use iii_sdk::{InitOptions, RegisterFunction, register_worker};
>
> let url = std::env::var("III_URL").expect("III_URL must be set");
> let worker = register_worker(
>     &url,
>     InitOptions {
>         namespace: Some("orders".into()),
>         ..Default::default()
>     },
> );
>
> worker.register_function("math::add", RegisterFunction::new(|input: AddInput| {
>     Ok(serde_json::json!({ "c": input.a + input.b }))
> }));
> ```

> [tab] Go
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> client := iii.RegisterWorker(os.Getenv("III_URL"), iii.WithNamespace("orders"))
>
> client.RegisterFunction("math::add", func(ctx context.Context, data json.RawMessage) (any, error) {
>     var payload struct {
>         A float64 `json:"a"`
>         B float64 `json:"b"`
>     }
>     if err := json.Unmarshal(data, &payload); err != nil {
>         return nil, err
>     }
>     return map[string]float64{"c": payload.A + payload.B}, nil
> })
> ```

## Call a function

`call` runs a function and resolves to its result. The engine routes the call to the worker that
registered the function, wherever it runs. Call a function from the terminal with `iii call`, or
from worker code with `worker.call`. The `action` field sets how the call is delivered: by default
the call waits for the function to return its result, or for the configured timeout to fire.

> [tab] CLI
>
> ```bash theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> iii call math::add a=2 b=3
> ```

> [tab] Node / TypeScript
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import { CallAction } from "iii-sdk";
>
> const result = await worker.call({
>   function_id: "math::add",
>   payload: { a: 2, b: 3 },
>   // namespace: "default", // target a specific namespace
>   // action: CallAction.Void(), // fire-and-forget
>   // action: CallAction.Enqueue({ queue: "math" }), // route through queue
> });
> ```

> [tab] Python
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> from iii import CallAction
>
> result = worker.call({
>     "function_id": "math::add",
>     "payload": {"a": 2, "b": 3},
>     # "namespace": "default", # target a specific namespace
>     # "action": CallAction.Void(), # fire-and-forget
>     # "action": CallAction.Enqueue(queue="math"), # route through queue
> })
> # result = await worker.call_async({...}) # awaitable form for asyncio callers
> ```

> [tab] Rust
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> use iii_sdk::CallAction;
> use iii_sdk::protocol::CallRequest;
> use serde_json::json;
>
> let result = worker
>     .call(CallRequest {
>         function_id: "math::add".into(),
>         payload: json!({ "a": 2, "b": 3 }),
>         action: None,
>         // action: Some(CallAction::Void),                                  // fire-and-forget
>         // action: Some(CallAction::Enqueue { queue: "math".to_string() }), // route through queue
>         timeout_ms: None,
>     }
>     // .namespace("default"), // target a specific namespace
>     )
>     .await?;
> ```

> [tab] Go
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> result, err := client.Call(ctx, iii.CallRequest{
>     FunctionID: "math::add",
>     Payload:    json.RawMessage(`{"a":2,"b":3}`),
>     // Namespace:  "default", // target a specific namespace
>     // Action: iii.VoidAction(),          // fire-and-forget
>     // Action: iii.EnqueueAction("math"), // route through queue
> })
> if err != nil {
>     log.Fatal(err)
> }
> log.Printf("math::add returned %s", result)
> ```

The actions are:

* **Default (synchronous)**. No `action` set. The call waits for the function to return its result
  or for the configured timeout to fire.
* **`CallAction.Void()`**. Fire-and-forget. The call returns at once; the function still runs, and
  the caller does not see the result.
* **`CallAction.Enqueue({ queue })`**. Provided by [queue](https://workers.iii.dev/workers/queue).
  Routes the call through a named queue with retries; the call returns once the message is enqueued.

Workers can provide their own `CallAction`s. Check each
[worker's documentation](https://workers.iii.dev) for the actions it offers.

> [!NOTE]
>
> Refer to [Using iii / Namespaces](https://iii.dev/docs/0-26-0/using-iii/namespaces.md#call-a-function-in-a-namespace) for more
> information on namespaces and calling functions in a specific namespace.

> [!NOTE]
>
> A call to a function that the calling worker registered itself runs in-process once the engine
> confirmed the registration (local dispatch), with the same result, errors, and timeout as a call
> through the engine. Pass `dispatch: "remote"` (Python `"dispatch": "remote"`, Rust
> `.dispatch(Dispatch::Remote)`, Go `Dispatch: iii.DispatchRemote`) to send one call through the
> engine. See [Local dispatch](https://iii.dev/docs/0-26-0/using-iii/observers.md#local-dispatch).

> [!NOTE]
>
> In Python, every blocking method has an awaitable twin (`call_async`, `shutdown_async`,
> `create_channel_async`) for use inside `asyncio`. See the [Python SDK
> reference](https://iii.dev/docs/0-26-0/reference/sdk-python.md).

### Routing to a namespace

Workers and their associated functions can be namespaced. A function id is unique per namespace, not
globally: `state::get` can be registered once in `default`, once in `orders`, and once in
`analytics`. Set `namespace` on the call to pick one.

Resolution is strict. A call that names `orders` resolves there and nowhere else, and a call that
names none resolves in the namespace of the calling worker. A miss returns `function_not_found`
naming the namespaces where the id does exist.

> [!NOTE]
>
> `iii call` reaches `default` unless you pass `--namespace <NS>`. For calling across namespaces
> from worker code, see [Use namespaces](https://iii.dev/docs/0-26-0/using-iii/namespaces.md#call-a-function-in-a-namespace).

## Run a function when something happens

A call runs a function once, when you make it. To run a function each time something happens
(another function runs, an HTTP request arrives, a row changes), observe the function that
represents it:

> [tab] Node / TypeScript
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // When math::add runs, run audit::record.
> worker.observe("math::add", "audit::record");
>
> // Every day at 09:00, run reports::daily-summary.
> worker.observe(
>   { function_id: "cron::on-tick", args: { expression: "0 0 9 * * * *" } },
>   "reports::daily-summary",
> );
> ```

> [tab] Python
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> # When math::add runs, run audit::record.
> worker.observe("math::add", "audit::record")
>
> # Every day at 09:00, run reports::daily-summary.
> worker.observe(
>     {"function_id": "cron::on-tick", "args": {"expression": "0 0 9 * * * *"}},
>     "reports::daily-summary",
> )
> ```

> [tab] Rust
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> use iii_sdk::Source;
> use serde_json::json;
>
> // When math::add runs, run audit::record.
> worker.observe("math::add", "audit::record");
>
> // Every day at 09:00, run reports::daily-summary.
> worker.observe(
>     Source::function("cron::on-tick").args(json!({ "expression": "0 0 9 * * * *" })),
>     "reports::daily-summary",
> );
> ```

> [tab] Go
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // When math::add runs, run audit::record.
> client.ObserveFunction("math::add", "audit::record")
>
> // Every day at 09:00, run reports::daily-summary.
> client.Observe(iii.Source{
>     FunctionID: "cron::on-tick",
>     Args:       iii.Args{"expression": "0 0 9 * * * *"},
> }, "reports::daily-summary")
> ```

See [Observers](https://iii.dev/docs/0-26-0/using-iii/observers.md).

### Every function is observable

Any worker can observe any function, private ones included, unless the function is registered with
`observable: false` or RBAC restricts it.

The worker that registers a function can make it private or unobservable, and can override what iii
does by default when it is observed; see
[Observable functions](https://iii.dev/docs/0-26-0/creating-workers/observable-functions.md).

## Call functions from the CLI

`iii call` is a useful development tool. Pass `--help` to any function to see its arguments and a
description of what it does:

```bash theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
iii call function::id --help
```

Because `iii call` runs through the exact same code paths as the rest of the system, you can do real
work straight from the terminal: figure out what a function does, apply database modifications, make
state changes, or try any other manipulation or new code interactively. That makes it a useful tool
for development and debugging.

> [!NOTE]
>
> Request and response formats are what make `iii call <function> --help` work. Functions can carry
> JSON Schemas for their request payload and response shape. For how to create these schemas when
> registering a function, see
> [Creating Workers / Functions](https://iii.dev/docs/0-26-0/creating-workers/functions.md#attach-request-and-response-schemas).

## Common functions

A handful of functions ship with the iii engine and the standard workers. You'll likely call them
from almost every iii project. They look like any function you'd register yourself and are called
the same way (with [`iii call`](./cli) or [`worker.call`](#call-a-function)). The only thing special
about them is that you didn't have to register them.

### Engine functions (`engine::*`)

The engine itself registers a small set of introspection and lifecycle functions. Full request and
response schemas are in the
[engine protocol reference](https://iii.dev/docs/0-26-0/reference/engine-protocol.md#engine-discovery-functions).

| Function | What it does |
| - | - |
| `engine::functions::list` | List every registered function with its `args_format`, `private`, `observable`, and observer count. Pass `{ include_internal: true }` to include engine internals. |
| `engine::workers::list` | List every connected worker with its metrics. Pass `{ worker_id: "<uuid>" }` to look one up. |
| `engine::channels::create` | Allocate a streaming channel reader / writer pair. The SDK wraps this as the `createChannel` helper in `iii-sdk/helpers`; rarely called directly. |
| `engine::workers::register` | Publish the calling worker's metadata (runtime, version, OS, PID, optional `namespace`, optional `description`). The SDK calls this automatically on connect. |
| `engine::observers::list` | List observers. Pass `{ function_id, namespace, worker }` to narrow the list. See [Inspect observers](https://iii.dev/docs/0-26-0/using-iii/observers.md#inspect-observers). |
| `engine::observers::get` | Read one observer by `{ id }`. |
| `engine::observers::dispose` | Remove an observer by `{ id }`. Only its observing worker, or a caller without RBAC restrictions, may do it. |

The engine also hosts event sources for its registry. Observe them to react when it changes:

| Function | Runs when |
| - | - |
| `engine::on-functions-changed` | A function is registered or unregistered. |
| `engine::on-workers-changed` | A worker connects, disconnects, or updates its metadata. |
| `engine::on-observers-changed` | An observer changes state. |

See [Engine-hosted event sources](https://iii.dev/docs/0-26-0/using-iii/observers.md#engine-hosted-event-sources) for their events.

### Common workers

Each of these is published by a separate worker. Function ids, payload shapes, and per-function
behaviour are in the worker's own docs at [workers.iii.dev](https://workers.iii.dev):

> [!WARNING]
>
> `iii-stream` is deprecated (iii-stream) and will be removed in an upcoming release. `pubsub` is
> deprecated (pubsub) and will be removed in an upcoming release. Behavior is unchanged for now. See
> [Migrate from iii-stream and pubsub](https://iii.dev/docs/0-26-0/upgrading/migrate-from-streams.md).

* **HTTP**: Serves HTTP routes. Observe `http::on-request` with a method and a path to add a route.
  See [http](https://workers.iii.dev/workers/http).
* **Cron**: Runs functions on a schedule. Observe `cron::on-tick` with an expression. See
  [cron](https://workers.iii.dev/workers/cron).
* **State**: KV-style state with scoped key namespaces (distinct from
  [routing namespaces](https://iii.dev/docs/0-26-0/understanding-iii/namespaces.md)). Each create, update, and delete runs
  `state::on-changed`, which you observe. See [state](https://workers.iii.dev/workers/state).
* **Stream** (deprecated): Real-time push to connected clients over WebSocket. See
  [iii-stream](https://workers.iii.dev/workers/iii-stream). Use
  [observable functions](https://iii.dev/docs/0-26-0/creating-workers/observable-functions.md) or
  [channels](https://iii.dev/docs/0-26-0/creating-workers/channels.md) for new work.
* **Queue**: Durable, ordered job processing with retries, concurrency limits, and a dead-letter
  queue. Observe `queue::on-message` to consume a topic. See
  [queue](https://workers.iii.dev/workers/queue).
* **Pub/Sub** (deprecated): Lightweight in-engine topic subscription for fan-out without durability
  guarantees. See [pubsub](https://workers.iii.dev/workers/pubsub). Use observable functions or
  durable queue topics for new work.
* **Observability**: Traces, logs, metrics, alerts, sampling rules, and rollups. See
  [iii-observability](https://workers.iii.dev/workers/iii-observability).


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