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

# Streaming

> Send streams in calls, read streams from results, and connect pipes.

A stream is a value in a call's payload or result. Use a stream for data that is larger than the
JSON message limit, or for data that the sender makes over time. For small JSON values, use a
regular `worker.call(...)`.

The function on the other side receives an `InputStream` to read or an `OutputStream` to write. The
two functions can run in different processes and languages.

> [!NOTE]
>
> The examples use the stream API of the 0.27 SDKs. To write the functions that receive and return
> streams, see [Creating workers / Streaming](https://iii.dev/docs/creating-workers/streaming.md). To move code from the
> channel API, see [Upgrading from 0.26.x](https://iii.dev/docs/upgrading/from-0-26-x.md). For how a stream works, see
> [Understanding iii / Streaming](https://iii.dev/docs/understanding-iii/streaming.md).

## Send a stream in a call

To send a stream, put it in the payload of the call. For the steps that the SDK and the engine do,
see [How a stream works](https://iii.dev/docs/understanding-iii/streaming.md#how-a-stream-works).

Each SDK sends only specific types of values as streams. The supported types are listed in the
comments on each language tab. Strings, buffers, plain objects, and arrays will not be sent as
streams by default. To send these types as streams first convert them with `InputStream.from()`.

> [tab] Node / TypeScript
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import { createReadStream } from "node:fs";
> import { InputStream, registerWorker } from "iii-sdk";
>
> const worker = registerWorker(process.env.III_URL ?? "ws://localhost:49134");
>
> // Streams: an InputStream, a Node Readable, a Web ReadableStream, a Blob or File, or an async
> // generator object.
> const result = await worker.call({
>   function_id: "files::process",
>   payload: { filename: "report.csv", body: createReadStream("report.csv") },
> });
>
> // The SDK sends other values as JSON. To send in-memory data as a stream, wrap it with
> // InputStream.from(...): a Uint8Array, an ArrayBuffer, a string, or an iterable or async
> // iterable of Uint8Array and strings.
> const textResult = await worker.call({
>   function_id: "files::process",
>   payload: { filename: "totals.csv", body: InputStream.from("id,total\nr-42,120\n") },
> });
> ```

> [tab] Python
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import os
>
> from iii import InputStream, register_worker
>
> worker = register_worker(os.environ.get("III_URL", "ws://localhost:49134"))
>
>
> # Streams: an InputStream, an async generator object, or a binary file object opened for reading.
> # InputStream.from_file(path), InputStream.from_iter(iterable) (sync or async, of bytes or str),
> # and InputStream.from_bytes(data) build one.
> async def upload() -> dict:
>     return await worker.call_async(
>         {
>             "function_id": "files::process",
>             "payload": {"filename": "report.csv", "body": InputStream.from_file("report.csv")},
>         }
>     )
> ```

> [tab] Rust
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> use iii_sdk::{CallRequest, InputStream};
> use serde_json::json;
> use tokio::fs::File;
>
> // Streams: an InputStream built with from_reader (an AsyncRead), from_stream (a Stream of
> // Result<Bytes, E>), or from_bytes. Other serde values stay JSON.
> let result = worker
>     .call(CallRequest::new(
>         "files::process",
>         json!({
>             "filename": "report.csv",
>             "body": InputStream::from_reader(File::open("report.csv").await?),
>         }),
>     ))
>     .await?;
> ```

> [tab] Go
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // Streams: an *iii.InputStream built with iii.InputStreamFromReader (an io.Reader, closed at the
> // end when it is an io.Closer) or iii.InputStreamFromBytes. Other values stay JSON.
> file, err := os.Open("report.csv")
> if err != nil {
> 	return err
> }
> payload, err := json.Marshal(map[string]any{
> 	"filename": "report.csv",
> 	"body":     iii.InputStreamFromReader(file),
> })
> if err != nil {
> 	return err
> }
> result, err := worker.Call(ctx, iii.CallRequest{FunctionID: "files::process", Payload: payload})
> ```

A payload can contain more than one stream. The SDK finds streams in plain objects and arrays, at
any depth. It creates one pipe for each stream, all at the same time, before it sends the call. If
the SDK cannot create a pipe, the call fails and the SDK does not send it.

Your worker owns the pipe of each stream that it sends. Keep the worker connected until the transfer
has completed. For what the engine does when the owner disconnects, see
[Pipe ownership](https://iii.dev/docs/understanding-iii/streaming.md#pipe-ownership).

The SDK writes the data of a source into the pipe for you. You write the data yourself when you have
an `OutputStream`: the `output` of [`worker.pipe()`](#create-a-pipe), or an `OutputStream` in the
result of a call. These are the operations of an `OutputStream`:

| To | Call |
| - | - |
| Write bytes | `await out.write(chunk)`, a `Uint8Array` or a string as UTF-8 bytes |
| Send a JSON message | `await out.send(value)` |
| Finish | `await out.close()` |
| Fail | `await out.abort(reason)` |
| Use a native API | `out.toWritable()` for a Node `Writable`, `out.toWebStream()` for the Web |

> [!NOTE]
>
> The operation tables on this page show the TypeScript API. The SDK reference gives the same
> operations for each SDK: [Node](https://iii.dev/docs/reference/sdk-node.md), [Python](https://iii.dev/docs/reference/sdk-python.md),
> [Rust](https://iii.dev/docs/reference/sdk-rust.md), [Go](https://iii.dev/docs/reference/sdk-go.md), and [Browser](https://iii.dev/docs/reference/sdk-browser.md).

## Read a stream from a result

A function can return a stream in its result. The result of `worker.call(...)` then contains an
`InputStream` in the field where the function put the stream.

> [tab] Node / TypeScript
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import type { InputStream } from "iii-sdk";
>
> const { csv }: { csv: InputStream } = await worker.call({
>   function_id: "reports::export",
>   payload: { report_id: "r-42" },
> });
> for await (const line of csv.lines()) console.log(line);
> ```

> [tab] Python
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> result = await worker.call_async(
>     {"function_id": "reports::export", "payload": {"report_id": "r-42"}}
> )
> async for line in result["csv"].lines():
>     print(line)
> ```

> [tab] Rust
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> use futures::TryStreamExt;
> use iii_sdk::{CallRequest, InputStream};
> use serde::Deserialize;
> use serde_json::json;
>
> #[derive(Deserialize)]
> struct Export {
>     csv: InputStream,
> }
>
> let export: Export = serde_json::from_value(
>     worker
>         .call(CallRequest::new("reports::export", json!({ "report_id": "r-42" })))
>         .await?,
> )?;
> // A decoded stream binds to the only client in the process.
> // With several clients in one process, call export.csv.bind(&worker) before reading.
> // To keep the result as a serde_json::Value, find its read refs with
> // iii_sdk::protocol::extract_channel_refs and open each with
> // InputStream::from_ref(channel, &worker), which also binds it.
> let mut lines = export.csv.lines();
> while let Some(line) = lines.try_next().await? {
>     println!("{line}");
> }
> ```

> [tab] Go
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> type export struct {
> 	ReportID string           `json:"report_id"`
> 	CSV      *iii.InputStream `json:"csv"`
> }
>
> out, err := worker.Call(ctx, iii.CallRequest{
> 	FunctionID: "reports::export",
> 	Payload:    json.RawMessage(`{"report_id":"r-42"}`),
> })
> if err != nil {
> 	return err
> }
> // A stream unmarshalled from a call's result binds to that client. A stream unmarshalled from
> // other JSON binds to the only client in the process; with several, call stream.Bind(worker).
> var res export
> if err := json.Unmarshal(out, &res); err != nil {
> 	return err
> }
> for line, err := range res.CSV.Lines(ctx) {
> 	if err != nil {
> 		return err
> 	}
> 	fmt.Println(line)
> }
> ```

An `InputStream` from a result and the `input` of a [pipe](#create-a-pipe) have the same read
operations. You can read an `InputStream` only once, so use the one operation that fits the data:

| To | Call |
| - | - |
| Read byte chunks | `for await (const chunk of s)` |
| Read all the data | `await s.bytes()`, `await s.text()` |
| Read lines, without the newline | `for await (const line of s.lines())` |
| Read JSON messages | `for await (const msg of s.messages<T>())` |
| Read bytes and messages, in order | `for await (const frame of s.frames())` |
| Stop reading | `await s.cancel()` |
| Make two copies | `s.tee()`, before the first read |
| Use a native API | `s.toReadable()` for a Node `Readable`, `s.toWebStream()` for the Web |

A stream can carry bytes and JSON messages. The operations that read bytes skip the messages, and
`messages()` skips the bytes. To read both types in the order in which the writer sent them, use
`frames()`. A frame is `{ type: "binary", value }` for bytes, or `{ type: "text", value }` for one
message as a string.

`messages()` parses each message as JSON. If a message is not valid JSON, `messages()` gives the
message as a string. For the two types of data, see
[Bytes and messages](https://iii.dev/docs/understanding-iii/streaming.md#bytes-and-messages).

### Read a stream more than once

A second read of the same `InputStream` fails with `STREAM_IN_USE`. To use the data in two places,
call `tee()` before the first read. `tee()` returns two copies of the stream, and each copy gives
all the data. The two copies are in the same process.

> [tab] Node / TypeScript
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import { createHash } from "node:crypto";
> import { createWriteStream } from "node:fs";
> import { pipeline } from "node:stream/promises";
>
> const [forHash, forFile] = body.tee();
> const hash = createHash("sha256");
> // Read both copies at the same time
> await Promise.all([
>   pipeline(forHash.toReadable(), hash),
>   pipeline(forFile.toReadable(), createWriteStream("report.csv")),
> ]);
> ```

> [tab] Python
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import asyncio
> import hashlib
>
> for_hash, for_file = body.tee()
>
>
> async def digest() -> str:
>     h = hashlib.sha256()
>     async for chunk in for_hash:
>         h.update(chunk)
>     return h.hexdigest()
>
>
> async def save() -> None:
>     with open("report.csv", "wb") as file:
>         async for chunk in for_file:
>             file.write(chunk)
>
>
> # Read both copies at the same time
> sha, _ = await asyncio.gather(digest(), save())
> ```

> [tab] Rust
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> use futures::TryStreamExt;
> use sha2::{Digest, Sha256};
> use tokio::{fs::File, io::AsyncWriteExt};
>
> // There is no tee(): read the stream once, and use each chunk twice
> let mut hasher = Sha256::new();
> let mut file = File::create("report.csv").await?;
> let mut chunks = body;
> while let Some(chunk) = chunks.try_next().await? {
>     hasher.update(&chunk);
>     file.write_all(&chunk).await?;
> }
> ```

> [tab] Go
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // There is no tee(): read the stream once, and copy it with io.TeeReader or io.MultiWriter
> file, err := os.Create("report.csv")
> if err != nil {
> 	return err
> }
> defer file.Close()
> hash := sha256.New()
> if _, err := io.Copy(io.MultiWriter(file, hash), body); err != nil {
> 	return err
> }
> ```

Read the two copies at the same time. `tee()` keeps at most 16 frames for the copy that is behind.
When one copy is 16 frames behind the other, the read of the faster copy waits. If you read one copy
to the end before you start the other, the first read waits after 16 frames and does not finish.

If you do not need one of the copies, call `cancel()` on it. The read of the other copy then does
not wait.

To send the data in another call, put one of the copies in the payload. The SDK refuses the stream
that you split with `tee()`, and the call fails with `STREAM_IN_USE`.

## Receive data into a sink

A sink is a destination that receives the data of a stream, for example a file that is open for
writing. Put the sink in the payload. The function receives it as an `OutputStream` and writes to
it, and the SDK copies the bytes into your destination. The call resolves after the sink has
received all the data, so the data is complete when the call returns.

> [tab] Node / TypeScript
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import { createWriteStream } from "node:fs";
>
> // Sinks: an OutputStream, a Node Writable (not a Duplex), or a Web WritableStream
> await worker.call({
>   function_id: "reports::render-pdf",
>   payload: { report_id: "r-42", out: createWriteStream("r-42.pdf") },
> });
> ```

> [tab] Python
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> from iii import OutputStream
>
> # Sinks: an OutputStream built with OutputStream.to_file(path), or with OutputStream.to(writer),
> # where writer is a binary file object, an asyncio StreamWriter, or an object with a write method
> await worker.call_async(
>     {
>         "function_id": "reports::render-pdf",
>         "payload": {"report_id": "r-42", "out": OutputStream.to_file("r-42.pdf")},
>     }
> )
> ```

> [tab] Rust
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> use iii_sdk::{CallRequest, OutputStream};
> use serde_json::json;
> use tokio::fs::File;
>
> // Sinks: an OutputStream built with to_writer (an AsyncWrite)
> worker
>     .call(CallRequest::new(
>         "reports::render-pdf",
>         json!({
>             "report_id": "r-42",
>             "out": OutputStream::to_writer(File::create("r-42.pdf").await?),
>         }),
>     ))
>     .await?;
> ```

> [tab] Go
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // Sinks: an *iii.OutputStream built with iii.OutputStreamToWriter (an io.Writer). When the stream
> // ends, the SDK calls the writer's Flush() error method if it has one, and closes an io.Closer.
> // When the stream aborts, the SDK closes only a writer with a CloseWithError method.
> file, err := os.Create("r-42.pdf")
> if err != nil {
> 	return err
> }
> defer file.Close() // covers a failed call
> payload, err := json.Marshal(map[string]any{"report_id": "r-42", "out": iii.OutputStreamToWriter(file)})
> if err != nil {
> 	return err
> }
> _, err = worker.Call(ctx, iii.CallRequest{FunctionID: "reports::render-pdf", Payload: payload})
> ```

A sink receives bytes only. If the function sends messages, the sink drops them. To receive
messages, give the function the `output` of a pipe. See [Create a pipe](#create-a-pipe).

### Sink errors

A call with a sink can fail in three ways:

* **The stream aborts.** The call fails immediately with `STREAM_ABORTED`. The call fails also when
  the function returned a result.
* **The sink fails.** For example, the disk is full. The SDK stops the copy, and the call fails
  immediately with `STREAM_ABORTED`. The `reason` of the error starts with `the sink failed:`, and
  the `cause` of the error is the error from the sink.
* **The call fails.** The SDK stops the copy and closes the sink with the error.

When a stream aborts or a sink fails, the SDK also aborts the other open sinks of the call.

After each of these failures, the sink may contain a partial copy of the data.

### Sink timeout

The `timeoutMs` of a call includes the time that its sinks take to receive the data. The time starts
when the SDK sends the call. If the time expires before all the sinks are complete, the SDK aborts
the sinks that are still open, and the call fails with `TIMEOUT`.

Set a longer `timeoutMs` when a sink fills slowly. For example, some functions continue to write
after they return.

A call does not wait for its sinks when its result contains an `OutputStream` for you to write to.
The data that the sinks receive can depend on the data that you write, so the call resolves when the
function returns. A call with `CallAction.Void` does not wait for its sinks either.

In these two cases, a sink that aborts or fails after the call resolved cannot fail the call. A sink
that has already failed when the function returns still fails a call whose result contains an
`OutputStream`.

## Create a pipe

When you put a stream or a sink in a payload, the SDK creates the pipe for you. `worker.pipe()` is
how you can create a pipe manually. It returns the two ends of the pipe: you write to `output`, and
you read the same data from `input`. Put one end in a payload, and use the other end in your code.

Use `worker.pipe()` in these cases:

* The function must receive a stream before you have its data.
* You make the call that uses the stream at a later time.
* You need the messages that the function sends. A sink keeps only the bytes and drops the messages.
* You need a two-way exchange. Use two pipes, one for each direction.

> [tab] Node / TypeScript
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // Give the function the output, and read the messages from the input
> const { input, output } = await worker.pipe();
> const done = worker.call({
>   function_id: "llm::complete",
>   payload: { prompt: "Summarize report r-42", tokens: output },
> });
> // A handler that fails before it writes leaves `output` open: stop reading when the call fails.
> done.catch(() => input.cancel());
> try {
>   for await (const { token } of input.messages<{ token: string }>()) process.stdout.write(token);
> } finally {
>   await done; // when the call failed, this throws its error instead of the read's
> }
> ```

> [tab] Python
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import asyncio
>
> # Give the function the output, and read the messages from the input
> pipe = await worker.pipe_async()
>
>
> async def complete() -> None:
>     try:
>         await worker.call_async(
>             {
>                 "function_id": "llm::complete",
>                 "payload": {"prompt": "Summarize report r-42", "tokens": pipe.output},
>             }
>         )
>     except Exception:
>         # A handler that fails before it writes leaves the output open: stop reading.
>         await pipe.input.cancel()
>         raise
>
>
> call = asyncio.create_task(complete())
> try:
>     async for message in pipe.input.messages():
>         print(message["token"], end="", flush=True)
> finally:
>     await call  # when the call failed, this raises its error instead of the read's
> ```

> [tab] Rust
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> use futures::TryStreamExt;
> use iii_sdk::{CallRequest, Error};
> use serde::Deserialize;
> use serde_json::json;
>
> #[derive(Deserialize)]
> struct Token {
>     token: String,
> }
>
> // Give the function the output, and read the messages from the input while the call runs
> let pipe = worker.pipe().await?;
> let call = worker.call(CallRequest::new(
>     "llm::complete",
>     json!({ "prompt": "Summarize report r-42", "tokens": pipe.output }),
> ));
> let read = async {
>     let mut messages = pipe.input.messages::<Token>();
>     while let Some(Token { token }) = messages.try_next().await? {
>         print!("{token}");
>     }
>     Ok::<_, Error>(())
> };
> let (result, ()) = tokio::try_join!(call, read)?;
> ```

> [tab] Go
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // Give the function the output, and read the messages from the input while the call runs.
> // Pipe uses the engine's default buffer size.
> input, output, err := worker.Pipe(ctx)
> if err != nil {
> 	return err
> }
> payload, err := json.Marshal(map[string]any{"prompt": "Summarize report r-42", "tokens": output})
> if err != nil {
> 	return err
> }
> readCtx, stopReading := context.WithCancel(ctx)
> defer stopReading()
> done := make(chan error, 1)
> go func() {
> 	_, err := worker.Call(ctx, iii.CallRequest{FunctionID: "llm::complete", Payload: payload})
> 	if err != nil {
> 		stopReading() // a handler that fails before it writes leaves the output open
> 	}
> 	done <- err
> }()
> for msg, err := range input.Messages(readCtx) {
> 	if err != nil {
> 		if callErr := <-done; callErr != nil {
> 			return callErr
> 		}
> 		return err
> 	}
> 	var m struct {
> 		Token string `json:"token"`
> 	}
> 	if json.Unmarshal(msg, &m) == nil {
> 		fmt.Print(m.Token)
> 	}
> }
> return <-done
> ```

The engine can hold a number of frames between the writer and the reader of a pipe. The default is
64 frames. To change the number, call `worker.pipe({ bufferSize })`. The maximum is 1024 frames.

Your worker owns each pipe that it creates with `pipe()`. See
[Pipe ownership](https://iii.dev/docs/understanding-iii/streaming.md#pipe-ownership).

A function can fail before it writes to the `output` that you gave it. The `output` then stays open,
and your read of `input` waits until the engine drops the `output` connection. The error of the call
arrives first, so monitor the call while you read. When the call fails, you can stop the read with
`input.cancel()`. The read then fails with `STREAM_CLOSED`.

> [!NOTE]
>
> A pipe end is different from a sink. A call with a sink resolves after the stream ends. A call
> with a pipe end resolves when the function returns.

## Handle aborts and errors

A read of a stream ends in one of two ways. If the read ends without an error, the stream closed
cleanly and you have all the data. If the stream aborts, the read gives you the data that the writer
sent before the abort, and then throws a `StreamAbortedError` with the code `STREAM_ABORTED`. When
you get this error, the data is incomplete. Do not use it as the full stream.

> [tab] Node / TypeScript
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import { StreamAbortedError } from "iii-sdk";
>
> // An abort is an error from the read, after the data already sent
> try {
>   for await (const chunk of body) await store.append(key, chunk);
> } catch (err) {
>   if (err instanceof StreamAbortedError) await store.remove(key); // the upload is incomplete
>   throw err;
> }
> ```

> [tab] Python
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> from iii import StreamAbortedError
>
> # An abort is an error from the read, after the data already sent
> try:
>     async for chunk in body:
>         await store.append(key, chunk)
> except StreamAbortedError:
>     await store.remove(key)  # the upload is incomplete
>     raise
> ```

> [tab] Rust
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> use iii_sdk::Error;
>
> // An abort is Error::StreamAborted, after the data already sent
> let data = match body.read_all().await {
>     Ok(data) => data,
>     Err(err @ Error::StreamAborted { .. }) => {
>         store.remove(&key).await; // the upload is incomplete
>         return Err(err);
>     }
>     Err(err) => return Err(err),
> };
> ```

> [tab] Go
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // An abort is an *iii.InvocationError with the code STREAM_ABORTED, after the data already sent
> if _, err := io.Copy(dst, body); err != nil {
> 	var streamErr *iii.InvocationError
> 	if errors.As(err, &streamErr) && streamErr.Code == iii.CodeStreamAborted {
> 		store.Remove(key) // the upload is incomplete
> 	}
> 	return err
> }
> ```

The `reason` of the error does not contain the root cause of the failure. The `reason` comes from
the engine, for example `channel writer aborted: closed with code 1011`. To get the cause, read the
error or the result of the call. For how the engine relays an abort, see
[Close and abort](https://iii.dev/docs/understanding-iii/streaming.md#close-and-abort).

### Error codes

The SDK reports each stream error as an `InvocationError` with one of these codes:

* `STREAM_ABORTED`: The stream aborted before its end.
* `STREAM_CLOSED`: A `write` or a `send` came after the stream closed, aborted, or lost its reader.
  A read also fails with this code when the `InputStream` was cancelled. A stream is cancelled by
  `cancel()`, by an early exit from a read loop, or when the handler that received it returns.
* `STREAM_IN_USE`: An `InputStream` was read a second time, the same stream is in one payload two
  times, or the stream was already read to the end or already sent.
* `STREAM_NOT_ALLOWED`: A queued call has a stream in its payload. See
  [Queue a call](#queue-a-call).

## Queue a call

A queued call cannot carry a stream. If the payload of a call with `CallAction.Enqueue` contains a
stream, the SDK does not send the call, and the call fails with `STREAM_NOT_ALLOWED`. There are two
reasons:

* The queue can run the call after the pipe of the stream expired.
* When the queue runs a failed call again, the function cannot read the stream a second time.

To queue work on such data, store the data first and put its key in the payload. For example, upload
a file to object storage and queue the key of the object.

> [!NOTE]
>
> `CallAction.Void` is different from `CallAction.Enqueue`. A call with `CallAction.Void` can carry
> a stream. The function runs immediately, and the SDK does not wait for the result or for the sinks
> of the call.

## Observe a stream

You can observe a function that receives or returns streams. The target of the observer does not
receive the streams. In the `input` or `output` that the observer captures, the target receives a
`StreamInfo` in place of each stream: `{ stream: true, direction, id }`. A `StreamInfo` shows that
the call carried a stream, with the direction of the stream and the id of its pipe. It has no access
key, so the target cannot read or write the stream.

The other fields arrive as usual, and filters operate as usual. For the reason that the target
receives a `StreamInfo`, see
[Streams and observers](https://iii.dev/docs/understanding-iii/streaming.md#streams-and-observers).

> [tab] Node / TypeScript
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import type { Observed, StreamInfo } from "iii-sdk";
>
> type UploadSeen = { filename: string; body: StreamInfo };
>
> worker.registerFunction("audit::uploads", async ({ input }: Observed<UploadSeen>) => {
>   // body says a stream was passed; it holds no bytes
>   console.log(`upload of ${input?.filename}`, { stream: input?.body.id });
>   return null;
> });
>
> worker.observe({ function_id: "files::process", capture: ["input"] }, "audit::uploads");
> ```

> [tab] Python
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> def audit_upload(observed: dict) -> None:
>     upload = observed["input"]
>     # body is a StreamInfo: it says a stream was passed, and holds no bytes
>     print(f"upload of {upload['filename']}", {"stream": upload["body"].id})
>
> worker.register_function("audit::uploads", audit_upload)
> worker.observe({"function_id": "files::process", "capture": ["input"]}, "audit::uploads")
> ```

> [tab] Rust
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> use iii_sdk::{Capture, Error, Observed, RegisterFunction, Source, StreamInfo};
> use schemars::JsonSchema;
> use serde::Deserialize;
>
> #[derive(Deserialize, JsonSchema)]
> struct UploadSeen {
>     filename: String,
>     body: StreamInfo,
> }
>
> worker.register_function(
>     "audit::uploads",
>     RegisterFunction::new(|event: Observed<UploadSeen>| {
>         // body is a StreamInfo: it says a stream was passed, and holds no bytes
>         if let Some(upload) = &event.input {
>             println!("upload of {} ({})", upload.filename, upload.body.id);
>         }
>         Ok::<_, Error>(())
>     }),
> );
>
> worker.observe(
>     Source::function("files::process").capture([Capture::Input]),
>     "audit::uploads",
> );
> ```

> [tab] Go
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> type uploadSeen struct {
> 	Filename string         `json:"filename"`
> 	Body     iii.StreamInfo `json:"body"`
> }
>
> worker.RegisterFunction("audit::uploads", func(ctx context.Context, data json.RawMessage) (any, error) {
> 	var event iii.Observed
> 	if err := json.Unmarshal(data, &event); err != nil {
> 		return nil, err
> 	}
> 	var upload uploadSeen
> 	if err := json.Unmarshal(event.Input, &upload); err != nil {
> 		return nil, err
> 	}
> 	// Body is a StreamInfo: it says a stream was passed, and holds no bytes
> 	log.Printf("upload of %s (stream %s)", upload.Filename, upload.Body.ID)
> 	return nil, nil
> })
>
> worker.Observe(iii.Source{FunctionID: "files::process", Capture: []iii.Capture{iii.CaptureInput}}, "audit::uploads")
> ```

> [!WARNING]
>
> The engine sends the ref of the stream, with its access key, and the SDK replaces it. A target on
> an SDK before 0.27 receives the ref. Do not open it. A stream has one reader, and the first socket
> that attaches takes the stream from the observed function.


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