# Loro Streams Agent Guide

Use this guide to operate Loro Streams with the `loro` CLI.
Loro Streams is designed for real-time collaboration: CRDT sync, event/log replication, and multi-agent chat/state synchronization.

## What Problems This Solves

- Build real-time collaborative applications.
- Synchronize Loro CRDT documents across clients and services.
- Replicate logs/events with durable history and replay.
- Share chat messages and state between multiple AI agents.
- Operate platform resources from CLI without relying on dashboard UI flows.

## Core Mental Model

- You work inside an organization context.
- Data model is `bucket -> stream`.
- A stream is append-only and durable.
- Typical loop: create stream -> append messages -> read/watch -> recover with bootstrap/snapshot when needed.

## Important Stream Content-Type Rule

Always set stream content type explicitly at stream creation time.

- Recommended default for most users: `application/json`
  - Reason: easiest to inspect, parse, and debug.
  - This avoids binary decoding in everyday workflows.
- Use `application/octet-stream` when you intentionally need binary framing.

Recommended commands:

```bash
# Intuitive default for app/event workflows
loro stream create <bucket> <stream> --content-type application/json

# Binary framing for CRDT/binary payload workloads
loro stream create <bucket> <stream> --content-type application/octet-stream
```

## Quick Start (First 5 Minutes)

1. Log in:
   - `loro auth login --host https://streams.loro.dev`
2. Verify identity and org context:
   - `loro auth whoami`
   - `loro auth use-org <org-id>` (if needed)
3. Create resources:
   - `loro bucket create <bucket>`
   - `loro stream create <bucket> <stream> --content-type application/json`
4. Write and read:
   - `loro stream append <bucket> <stream> --data '{"type":"hello","text":"world"}'`
   - `loro stream read <bucket> <stream> --format jsonl`
5. Watch live updates:
   - `loro stream watch <bucket> <stream> --from now --format jsonl`

## Common Workflows

### 1) Real-Time CRDT Collaboration

- Store CRDT updates in durable streams.
- Readers continuously apply updates from `read/watch`.
- For application integration, use `@loro-dev/streams-crdt`.
- If you need to integrate CRDT sync into your app, install it first: `npm install @loro-dev/streams-crdt`.

### 2) Multi-Agent Chat And Multiplayer State

- Use one stream per room/session/team.
- Agents append messages/events to the stream.
- Other agents consume via `watch` for real-time multiplayer behavior.

### 3) Durable Log/Event Sync

- Append structured logs/events to streams.
- Consumers read from offsets for replay/resume.
- Prefer `--format jsonl` for machine parsing.

### 4) API Token Distribution For Apps

- Create and manage API keys:
  - `loro dashboard api-key create|list|revoke`
- Verify and exchange for JWT:
  - `loro dashboard api-key verify --key <api-key>`
  - `loro dashboard api-key token --key <api-key>`

## Streams CRDT Package (`@loro-dev/streams-crdt`)

This package can synchronize:

- `@loro-dev/streams-crdt` / `@loro-dev/streams-crdt/flock`
  - `flock` state (`syncMeta`, `joinMetaRoom`, `syncFlock`, `joinFlockRoom`)
- `@loro-dev/streams-crdt/loro`
  - `Loro CRDT documents` (`syncDoc`, `joinDocRoom`)
  - `ephemeral store` data (`joinEphemeralRoom`)

Minimal adapter setup:

```ts
import { LoroDoc } from "loro-crdt";
import {
  createLoroDocAdapter,
  StreamsCrdt,
} from "@loro-dev/streams-crdt/loro";

const loroDoc = new LoroDoc();
const transport = new StreamsCrdt({
  streamUrl: "https://streams-api.loro.dev/ds/my_bucket/doc-1",
  auth: async () => "<gateway-jwt>",
  adapter: createLoroDocAdapter(loroDoc),
});

await transport.sync();
transport.join();
```

Typical usage shape:

```ts
const metaTransport = new StreamsCrdt({
  streamUrl: "https://streams-api.loro.dev/ds/my_bucket/repo%3Ameta",
  auth: async () => "<gateway-jwt>",
  adapter: createFlockAdapter(flock),
});
await metaTransport.sync();
const metaSub = metaTransport.join();

const docTransport = new StreamsCrdt({
  streamUrl: "https://streams-api.loro.dev/ds/my_bucket/doc-1",
  auth: async () => "<gateway-jwt>",
  adapter: createLoroDocAdapter(loroDoc),
});
await docTransport.sync();
const docSub = docTransport.join();
```

## Recovery And Reliability

- If stream read returns `410 Gone`, rebuild from bootstrap:
  - `loro stream bootstrap <bucket> <stream>`
- Use snapshots to speed up recovery of large streams:
  - `loro stream snapshot read <bucket> <stream> --latest`
  - `loro stream snapshot write <bucket> <stream> --at <offset> --data-file <path>`

## Permissions (User-Facing)

- `401` means authentication failed or token expired: run `loro auth login` again.
- `403` means permission denied: check org context and token scope.
- Access is scoped by organization and resource permissions on buckets/streams.
- API key creation is bucket-scoped: `loro dashboard api-key create --name <name> --bucket <bucket>`.
- The dashboard checks that the bucket belongs to the active org before creating the key.
- The generated key scope is exact to that bucket and allows normal stream read/create/append/snapshot-write.
- Destructive operations such as bucket delete, stream delete, stream close, and snapshot delete are not granted.
- Old arbitrary `--permissions` / `buckets` JSON key creation is deprecated and rejected.

## Output Modes

- Default output: human-readable.
- Non-stream commands: use `--json` for machine-readable output.
- Stream commands: use `--format jsonl` for one-message-per-line output.

## Safe Agent Behavior

- Prefer idempotent operations.
- Read current state before write/delete actions.
- Verify target identifiers before `delete`, `remove`, `revoke`.
- Never print refresh tokens or raw secrets.

## Command Cheat Sheet

- Auth:
  - `loro auth login|whoami|use-org|token`
- Dashboard:
  - `loro dashboard organizations ...`
  - `loro dashboard members ...`
  - `loro dashboard buckets|usage|quota|storage ...`
  - `loro dashboard api-key ...`
- Stream:
  - `loro stream create|append|read|watch|inspect|head|close|delete ...`
  - `loro stream snapshot read|write ...`
  - `loro stream bootstrap ...`
- Bucket:
  - `loro bucket create|get|delete ...`

## Full Durable Streams Protocol Reference (Interface-Level)

The following section includes the complete Durable Streams Protocol reference.

# DRAFT: The Durable Streams Protocol

**Document:** Durable Streams Protocol  
**Version:** 1.0  
**Date:** 2025-01-XX  
**Author:** ElectricSQL

---

## Abstract

This document specifies the Durable Streams Protocol, an HTTP-based protocol for creating, appending to, and reading from durable, append-only byte streams. The protocol provides a simple, web-native primitive for applications requiring ordered, replayable data streams with support for catch-up reads and live tailing. It is designed to be a foundation for higher-level abstractions such as event sourcing, database synchronization, collaborative editing, and AI conversation histories.

## Copyright Notice

Copyright (c) 2025 ElectricSQL

## Table of Contents

1. [Introduction](#1-introduction)
2. [Terminology](#2-terminology)
3. [Protocol Overview](#3-protocol-overview)
4. [Stream Model](#4-stream-model)
5. [HTTP Operations](#5-http-operations)
   - 5.1. [Create Stream](#51-create-stream)
   - 5.2. [Append to Stream](#52-append-to-stream)
   - 5.3. [Delete Stream](#53-delete-stream)
   - 5.3.1. [Close Stream (Extension)](#531-close-stream-extension)
   - 5.4. [Stream Metadata](#54-stream-metadata)
   - 5.5. [Read Stream - Catch-up](#55-read-stream---catch-up)
   - 5.6. [Read Stream - Live (Long-poll)](#56-read-stream---live-long-poll)
   - 5.7. [Read Stream - Live (SSE)](#57-read-stream---live-sse)
6. [Offsets](#6-offsets)
7. [Content Types](#7-content-types)
8. [Caching and Collapsing](#8-caching-and-collapsing)
9. [Extensibility](#9-extensibility)
10. [Security Considerations](#10-security-considerations)
11. [IANA Considerations](#11-iana-considerations)
12. [References](#12-references)

---

## 1. Introduction

Modern web and cloud applications frequently require ordered, durable sequences of data that can be replayed from arbitrary points and tailed in real time. Common use cases include:

- Database synchronization and change feeds
- Event-sourced architectures
- Collaborative editing and CRDTs
- AI conversation histories and token streaming
- Workflow execution histories
- Real-time application state updates

While these patterns are widespread, the web platform lacks a simple, first-class primitive for durable streams. Applications typically implement ad-hoc solutions using combinations of databases, queues, and polling mechanisms, each reinventing similar offset-based replay semantics.

The Durable Streams Protocol provides a minimal HTTP-based interface for durable, append-only byte streams. It is intentionally low-level and byte-oriented, allowing higher-level abstractions to be built on top without protocol changes.

## 2. Terminology

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 [RFC2119] [RFC8174] when, and only when, they appear in all capitals, as shown here.

**Stream**: A URL-addressable, append-only byte stream that can be read and written to. A stream is simply a URL; the protocol defines how to interact with that URL using HTTP methods, query parameters, and headers. Streams are durable and immutable by position; new data can only be appended.

**Offset**: An opaque, lexicographically sortable token that identifies a position within a stream. Clients use offsets to resume reading from a specific previously reached point.

**Content Type**: A MIME type set on stream creation that describes the format of the stream's bytes. The content type is returned on reads and may be used by clients to interpret message boundaries.

**Tail Offset**: The offset immediately after the last byte in the stream. This is the position where new appends will be written.

## 3. Protocol Overview

The Durable Streams Protocol is an HTTP-based protocol that operates on URLs. A stream is simply a URL; the protocol defines how to interact with that URL using standard HTTP methods, query parameters, and custom headers.

The protocol defines operations to create, append to, read, delete, and query metadata for streams. Reads have three modes: catch-up, long-poll, and Server-Sent Events (SSE). The primary operations are:

1. **Create**: Establish a new stream at a URL with optional initial content (PUT)
2. **Append**: Add bytes to the end of an existing stream (POST)
3. **Read**: Retrieve bytes starting from a given offset, with support for catch-up and live modes (GET)
4. **Delete**: Remove a stream (DELETE)
5. **Head**: Query stream metadata without transferring data (HEAD)

The protocol does not prescribe a specific URL structure. Servers may organize streams using any URL scheme they choose (e.g., `/v1/stream/{path}`, `/streams/{id}`, or domain-specific paths). The protocol is defined by the HTTP methods, query parameters, and headers applied to any stream URL.

Streams support arbitrary content types. The protocol operates at the byte level, leaving message framing and schema interpretation to clients.

**Independent Read/Write Implementation**: Servers **MAY** implement the read and write paths independently. For example, a database synchronization server may only implement the read path and use its own injection system for writes, while a collaborative editing service might implement both paths.

## 4. Stream Model

A stream is an append-only sequence of bytes with the following properties:

- **Durability**: Once written and acknowledged, bytes persist until the stream is deleted or expired
- **Immutability by Position**: Bytes at a given offset never change; new data is only appended
- **Ordering**: Bytes are strictly ordered by offset
- **Content Type**: Each stream has a MIME content type set at creation
- **TTL/Expiry**: Streams may have optional time-to-live or absolute expiry times
- **Retention**: Servers **MAY** implement retention policies that drop data older than a certain age while the stream continues. If a stream is deleted a new stream **SHOULD NOT** be created at the same URL.

Clients track their position in a stream using offsets. Offsets are opaque to clients but are lexicographically sortable, allowing clients to determine ordering and resume from any point.

## 5. HTTP Operations

The protocol defines operations that are applied to a stream URL. The examples in this section use `{stream-url}` to represent any stream URL. Servers may implement any URL structure they choose; the protocol is defined by the HTTP methods, query parameters, and headers.

### 5.1. Create Stream

#### Request

```
PUT {stream-url}
```

Where `{stream-url}` is any URL that identifies the stream to be created.

Creates a new stream. If the stream already exists at `{stream-url}`, the server **MUST** either:

- return `200 OK` if the existing stream's configuration (content type, TTL/expiry) matches the request, or
- return `409 Conflict` if it does not.

This provides idempotent "create or ensure exists" semantics aligned with HTTP PUT expectations.

#### Request Headers (Optional)

- `Content-Type: <stream-content-type>`
  - Sets the stream's content type. If omitted, the server **MAY** default to `application/octet-stream`.

- `Stream-TTL: <seconds>`
  - Sets a relative time-to-live in seconds from creation. The value **MUST** be a non-negative integer in decimal notation without leading zeros, plus signs, decimal points, or scientific notation (e.g., `3600` is valid; `+3600`, `03600`, `3600.0`, and `3.6e3` are not).

- `Stream-Expires-At: <rfc3339>`
  - Sets an absolute expiry time as an RFC 3339 timestamp.
  - If both `Stream-TTL` and `Stream-Expires-At` are supplied, servers **SHOULD** reject the request with `400 Bad Request`. Implementations **MAY** define a deterministic precedence rule, but **MUST** document it.

#### Request Body (Optional)

- Initial stream bytes. If provided, these bytes form the first content of the stream.

#### Response Codes

- `201 Created`: Stream created successfully
- `200 OK`: Stream already exists with matching configuration (idempotent success)
- `409 Conflict`: Stream already exists with different configuration
- `400 Bad Request`: Invalid headers or parameters (including conflicting TTL/expiry)
- `429 Too Many Requests`: Rate limit exceeded

#### Response Headers (on 201 or 200)

- `Location: {stream-url}` (on 201): Servers **SHOULD** include a `Location` header equal to `{stream-url}` in `201 Created` responses.
- `Content-Type: <stream-content-type>`: The stream's content type
- `Stream-Next-Offset: <offset>`: The tail offset after any initial content

### 5.2. Append to Stream

#### Request

```
POST {stream-url}
```

Where `{stream-url}` is the URL of an existing stream.

Appends bytes to the end of an existing stream. Supports both full-body and streaming (chunked) append operations.

Servers that do not support appends for a given stream **SHOULD** return `405 Method Not Allowed` or `501 Not Implemented` to `POST` requests on that URL.

#### Request Headers

- `Content-Type: <stream-content-type>`
  - **MUST** match the stream's existing content type. Servers **MUST** return `409 Conflict` when the content type is valid but does not match the stream's configured type.

- `Transfer-Encoding: chunked` (optional)
  - Indicates a streaming body. Servers **SHOULD** support HTTP/1.1 chunked encoding and HTTP/2 streaming semantics.

- `Stream-Seq: <string>` (optional)
  - A monotonic, lexicographic writer sequence number for coordination.
  - `Stream-Seq` values are opaque strings that **MUST** compare using simple byte-wise lexicographic ordering. Sequence numbers are scoped per authenticated writer identity (or per stream, depending on implementation). Servers **MUST** document the scope they enforce.
  - If provided and less than or equal to the last appended sequence (as determined by lexicographic comparison), the server **MUST** return `409 Conflict`. Sequence numbers **MUST** be strictly increasing.

#### Request Body

- Bytes to append to the stream. Servers **MUST** reject POST requests with an empty body (Content-Length: 0 or no body) with `400 Bad Request`. Empty appends have no semantic meaning and are likely client errors.

#### Response Codes

- `204 No Content`: Append successful
- `400 Bad Request`: Malformed request (invalid header syntax, missing Content-Type, empty body)
- `404 Not Found`: Stream does not exist
- `405 Method Not Allowed` or `501 Not Implemented`: Append not supported for this stream
- `409 Conflict`: Content type mismatch with stream's configured type, or sequence regression (if `Stream-Seq` provided)
- `413 Payload Too Large`: Request body exceeds server limits
- `429 Too Many Requests`: Rate limit exceeded

#### Response Headers (on success)

- `Stream-Next-Offset: <offset>`: The new tail offset after the append
  - Under concurrent writers, this value MAY be greater than the end position of only this request, because it represents the published tail at response time.

#### Acknowledgement Durability

Servers **MUST** document the durability boundary associated with successful append responses.

- A server **MUST NOT** return append success (`200 OK` or `204 No Content`) for an offset that can be silently lost without a documented recovery mechanism.
- Implementations that claim strict durability **MUST** return success only after the appended data is durably published/committed in their control-plane durability model.
- The `Stream-Next-Offset` returned on success **MUST** correspond to that documented durability boundary.

### 5.2.1. Idempotent Producers

Durable Streams supports Kafka-style idempotent producers for exactly-once write semantics. This enables fire-and-forget writes with server-side deduplication, eliminating duplicates from client retries.

#### Design

- **Client-provided producer IDs**: Zero RTT overhead, no handshake required
- **Client-declared epochs, server-validated fencing**: Client increments epoch on restart; server validates monotonicity and fences stale epochs
- **Per-batch sequence numbers**: Separate from `Stream-Seq`, used for retry safety
- **Two-layer sequence design**:
  - Transport layer: `Producer-Id` + `Producer-Epoch` + `Producer-Seq` (retry safety)
  - Application layer: `Stream-Seq` (cross-restart ordering, lexicographic)

#### Request Headers

All three producer headers **MUST** be provided together or none at all. If only some headers are provided, servers **MUST** return `400 Bad Request`.

- `Producer-Id: <string>`
  - Client-supplied stable identifier (e.g., "order-service-1", UUID)
  - **MUST** be a non-empty string; empty values result in `400 Bad Request`
  - Identifies the logical producer across restarts

- `Producer-Epoch: <integer>`
  - Client-declared epoch, starting at 0
  - Increment on producer restart to establish a new session
  - Server validates that epoch is monotonically non-decreasing
  - **MUST** be a non-negative integer ≤ 2^53-1 (for JavaScript interoperability)

- `Producer-Seq: <integer>`
  - Monotonically increasing sequence number per epoch
  - Starts at 0 for each new epoch
  - Applies per-batch (per HTTP request), not per-message
  - **MUST** be a non-negative integer ≤ 2^53-1 (for JavaScript interoperability)

#### Response Headers

- `Producer-Epoch: <integer>`: Echoed back on success (200/204), or current server epoch on stale epoch (403)
- `Producer-Seq: <integer>`: On success (200/204), the highest accepted sequence number for this `(stream, producerId, epoch)` tuple. Enables clients to confirm pipelined requests and recover state after crashes.
- `Producer-Expected-Seq: <integer>`: On 409 Conflict (sequence gap), the expected sequence
- `Producer-Received-Seq: <integer>`: On 409 Conflict (sequence gap), the received sequence

#### Validation Logic

```
# Epoch validation (client-declared, server-validated)
if epoch < state.epoch:
  → 403 Forbidden
  → Headers: Producer-Epoch: <current epoch>

if epoch > state.epoch:
  if seq != 0:
    → 400 Bad Request (new epoch must start at seq=0)
  → Accept: update state.epoch = epoch, state.lastSeq = 0
  → 200 OK (new epoch established)

# Same epoch: sequence validation
if seq <= state.lastSeq:
  → 204 No Content (duplicate, idempotent success)

if seq == state.lastSeq + 1:
  → Accept, update state.lastSeq = seq
  → 200 OK

if seq > state.lastSeq + 1:
  → 409 Conflict
  → Headers: Producer-Expected-Seq: <lastSeq + 1>, Producer-Received-Seq: <seq>
```

#### Response Codes (with Producer Headers)

- `200 OK`: Append successful (new data)
- `204 No Content`: Duplicate append (idempotent success, data already exists)
- `400 Bad Request`: Invalid producer headers (e.g., non-integer values, epoch increase with seq != 0)
- `403 Forbidden`: Stale producer epoch (zombie fencing). Response includes `Producer-Epoch` header with current server epoch.
- `409 Conflict`: Sequence gap detected. Response includes `Producer-Expected-Seq` and `Producer-Received-Seq` headers.

#### Bootstrap and Restart Flow

1. **Initial start (epoch=0)**:
   - Producer sends `(epoch=0, seq=0)`
   - Server accepts, establishes producer state

2. **Producer restart**:
   - Producer increments local epoch (0 → 1), resets seq to 0
   - Sends `(epoch=1, seq=0)`
   - Server sees epoch > state.epoch, accepts, updates state

3. **Zombie fencing**:
   - Old producer (zombie) still sending `(epoch=0, seq=N)` gets 403 Forbidden
   - Response includes `Producer-Epoch: 1` header

#### Auto-claim Flow (for ephemeral producers)

For serverless or ephemeral producers without persisted epoch:

1. Producer starts fresh with `(epoch=0, seq=0)`
2. If server has `state.epoch=5`, returns 403 with `Producer-Epoch: 5`
3. Client can retry with `(epoch=6, seq=0)` to claim the producer ID

This is opt-in client behavior and should be used with caution.

#### Concurrency Requirements

Servers **MUST** serialize validation + append operations per `(stream, producerId)` pair. HTTP requests can arrive out-of-order; without serialization, seq=1 arriving before seq=0 would cause false sequence gaps.

#### Atomicity Requirements

For persistent storage, servers **SHOULD** commit producer state updates and log appends atomically (e.g., in a single database transaction). Non-atomic implementations have a crash window where:

1. Data is appended to the log
2. Crash occurs before producer state is updated
3. On recovery, a retry may be re-accepted, causing duplicate data

**Recovery for non-atomic stores**: Clients can bump their epoch after a crash to establish a clean session. This trades "exactly once within epoch" for "at least once across crashes" which is acceptable for many use cases. Stores **SHOULD** document their atomicity guarantees clearly.

#### Producer State Cleanup

Servers **MAY** implement TTL-based cleanup for producer state:

- **In-memory stores**: 7 days TTL recommended, clean up on stream access
- **Persistent stores**: Retain as long as stream data exists (stronger guarantee)

After state expiry, the producer is treated as new. A zombie alive past TTL expiry can write again, which is acceptable for testing but persistent stores should use longer retention.

### 5.3. Delete Stream

#### Request

```
DELETE {stream-url}
```

Where `{stream-url}` is the URL of the stream to delete.

Deletes the stream and all its data. In-flight reads may terminate with a `404 Not Found` on subsequent requests after deletion.

#### Response Codes

- `204 No Content`: Stream deleted successfully
- `404 Not Found`: Stream does not exist
- `405 Method Not Allowed` or `501 Not Implemented`: Delete not supported for this stream

### 5.3.1. Close Stream

#### Request

```
POST {stream-url}
Stream-Closed: true
```

Where `{stream-url}` is the URL of an existing stream.

Transitions the stream from `open` to `closed` without deleting historical data. This is the canonical close-only form: empty body plus `Stream-Closed: true`.

#### Response Codes

- `204 No Content`: Stream is now closed, or was already closed (idempotent success)
- `404 Not Found`: Stream does not exist
- `405 Method Not Allowed` or `501 Not Implemented`: Close not supported by this implementation

#### Behavior

- Closing is a state transition, not deletion.
- Closing is not reversible unless an implementation defines a separate extension for reopening.
- Implementations that support close **SHOULD** reject appends to closed streams with `409 Conflict`.
- Delete remains terminal and **MAY** be allowed from both `open` and `closed` states.

### 5.4. Stream Metadata

#### Request

```
HEAD {stream-url}
```

Where `{stream-url}` is the URL of the stream. Checks stream existence and returns metadata without transferring a body. This is the canonical way to find the tail offset, TTL, and expiry information.

#### Response Codes

- `200 OK`: Stream exists
- `404 Not Found`: Stream does not exist
- `429 Too Many Requests`: Rate limit exceeded

#### Response Headers (on 200)

- `Content-Type: <stream-content-type>`: The stream's content type
- `Stream-Next-Offset: <offset>`: The tail offset (next offset after the current end)
- `Stream-TTL: <seconds>` (optional): Remaining time-to-live, if applicable
- `Stream-Expires-At: <rfc3339>` (optional): Absolute expiry time, if applicable
- `Cache-Control`: See Section 8

#### Caching Guidance

Servers **SHOULD** make `HEAD` responses effectively non-cacheable, for example by returning `Cache-Control: no-store`. Servers **MAY** use `Cache-Control: private, max-age=0, must-revalidate` as an alternative, but `no-store` is recommended to avoid stale tail offsets.

### 5.5. Read Stream - Catch-up

#### Request

```
GET {stream-url}?offset=<offset>
```

Where `{stream-url}` is the URL of the stream. Returns bytes starting from the specified offset. This is used for catch-up reads when a client needs to replay stream content from a known position.

Unless an extension explicitly defines speculative visibility, servers **MUST** expose only published/committed data in catch-up and live reads.

#### Query Parameters

- `offset` (optional)
  - Start offset token. If omitted, defaults to the stream start (offset -1).

#### Response Codes

- `200 OK`: Data available (or empty body if offset equals tail)
- `400 Bad Request`: Malformed offset or invalid parameters
- `404 Not Found`: Stream does not exist
- `410 Gone`: Offset is outside the readable retained range (before earliest retained position, or beyond current published tail)
- `429 Too Many Requests`: Rate limit exceeded

For non-live reads without data beyond the requested offset, servers **SHOULD** return `200 OK` with an empty body and `Stream-Next-Offset` equal to the requested offset.

#### Response Headers (on 200)

- `Cache-Control`: Derived from TTL/expiry (see Section 8)
- `ETag: {internal_stream_id}:{start_offset}:{end_offset}`
  - Entity tag for cache validation
- `Stream-Cursor: <cursor>`
  - Cursor to echo on subsequent long-poll requests to improve CDN collapsing
- `Stream-Next-Offset: <offset>`
  - The next offset to read from (for subsequent requests)
- `Stream-Up-To-Date: true`
  - **MUST** be present and set to `true` when the response includes all data available in the stream at the time the response was generated (i.e., when the requested offset has reached the tail and no more data exists).
  - **SHOULD NOT** be present when returning partial data due to server-defined chunk size limits (when more data exists beyond what was returned).
  - Clients **MAY** use this header to determine when they have caught up and can transition to live tailing mode.

#### Response Body

- Bytes from the stream starting at the specified offset, up to a server-defined maximum chunk size.

### 5.6. Read Stream - Live (Long-poll)

#### Request

```
GET {stream-url}?offset=<offset>&live=long-poll[&cursor=<cursor>]
```

Where `{stream-url}` is the URL of the stream. If no data is available at the specified offset, the server waits up to a timeout for new data to arrive. This enables efficient live tailing without constant polling.

#### Query Parameters

- `offset` (required)
  - The offset to read from. **MUST** be provided.

- `live=long-poll` (required)
  - Indicates long-polling mode.

- `cursor` (optional)
  - Echo of the last `Stream-Cursor` header value from a previous response.
  - Used for collapsing keys in CDN/proxy configurations.

#### Response Codes

- `200 OK`: Data became available within the timeout
- `204 No Content`: Timeout expired with no new data
- `400 Bad Request`: Invalid parameters
- `404 Not Found`: Stream does not exist
- `410 Gone`: Offset is outside the readable retained range
- `429 Too Many Requests`: Rate limit exceeded

#### Response Headers (on 200)

- Same as catch-up reads (Section 5.5), except:
- `Stream-Cursor: <cursor>`: Servers **MUST** include this header. See Section 8.1.

#### Response Headers (on 204)

- `Stream-Next-Offset: <offset>`: Servers **MUST** include a `Stream-Next-Offset` header indicating the current tail offset.
- `Stream-Up-To-Date: true`: Servers **MUST** include this header to indicate the client is caught up with all available data.
- `Stream-Cursor: <cursor>`: Servers **MUST** include this header. See Section 8.1.

#### Response Body (on 200)

- New bytes that arrived during the long-poll period.
- For non-`application/json` streams, servers **MUST** preserve stored payload boundaries in live responses. A single appended payload **MUST NOT** be split across multiple long-poll responses, even if it exceeds an advisory read window used by catch-up mode.

#### Timeout Behavior

The timeout for long-polling is implementation-defined. Servers **MAY** accept a `timeout` query parameter (in seconds) as a future extension, but this is not required by the base protocol.

### 5.7. Read Stream - Live (SSE)

#### Request

```
GET {stream-url}?offset=<offset>&live=sse
```

Where `{stream-url}` is the URL of the stream. Returns data as a Server-Sent Events (SSE) stream. **ONLY** valid for streams with `content-type: text/*` or `application/json` (the stream's configured content type). SSE responses **MUST** use `Content-Type: text/event-stream` in the HTTP response headers.

#### Query Parameters

- `offset` (required)
  - The offset to start reading from.

- `live=sse` (required)
  - Indicates SSE streaming mode.

#### Response Codes

- `200 OK`: Streaming body (SSE format)
- `400 Bad Request`: Content type incompatible with SSE or invalid parameters
- `404 Not Found`: Stream does not exist
- `410 Gone`: Offset is outside the readable retained range
- `429 Too Many Requests`: Rate limit exceeded

#### Response Format

Data is emitted in [Server-Sent Events format](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format).

**Events:**

- `data`: Emitted for each batch of data
  - Each line prefixed with `data:`
  - When the stream content type is `application/json`, implementations **MAY** batch multiple logical messages into a single SSE `data` event by streaming a JSON array across multiple `data:` lines, as in the example below.
  - For non-`application/json` streams, servers **MUST** preserve stored payload boundaries. A single appended payload **MUST NOT** be split across multiple SSE `data` events, even if it exceeds an advisory read window used by catch-up mode.
- `control`: Emitted after every data event
  - **MUST** include `streamNextOffset` and `streamCursor`. See Section 8.1.
  - Format: JSON object with offset and cursor. Field names use camelCase: `streamNextOffset` and `streamCursor`.

**Example:**

```
event: data
data: [
data: {"k":"v"},
data: {"k":"w"},
data: ]

event: control
data: {"streamNextOffset":"123456_789","streamCursor":"abc"}
```

#### Connection Lifecycle

- Server **SHOULD** close connections roughly every ~60 seconds to enable CDN collapsing
- Client **MUST** reconnect using the last received `streamNextOffset` value from the control event

## 6. Offsets

Offsets are opaque tokens that identify positions within a stream. They have the following properties:

1. **Opaque**: Clients **MUST NOT** interpret offset structure or meaning
2. **Lexicographically Sortable**: For any two valid offsets for the same stream, a lexicographic comparison determines their relative position in the stream. Clients **MAY** compare offsets lexicographically to determine ordering.
3. **Persistent**: Offsets remain valid for the lifetime of the stream (until deletion or expiration)
4. **Strictly Increasing**: Offsets assigned to appended data **MUST** be lexicographically greater than all previously assigned offsets. Server implementations **MUST NOT** use schemes (such as raw UTC timestamps) that can produce duplicate or non-monotonic offsets. Time-based identifiers like ULIDs, which combine timestamps with random components to guarantee monotonicity, are acceptable.

**Format**: Offset tokens are opaque, case-sensitive strings. Their internal structure is implementation-defined. Offsets are single tokens and **MUST NOT** contain commas, ampersands, equals signs, or question marks (to avoid conflict with URL query parameter syntax). Servers **SHOULD** use URL-safe characters to avoid encoding issues, but clients **MUST** properly URL-encode offset values when including them in query parameters. Servers **SHOULD** keep offsets reasonably short (under 256 characters) since they appear in every request URL.

**Sentinel Values**: The protocol defines two special offset sentinel values:

- **`-1` (Stream Beginning)**: The special offset value `-1` represents the beginning of the stream. Clients **MAY** use `offset=-1` as an explicit way to request data from the start. This is semantically equivalent to omitting the offset parameter. Servers **MUST** recognize `-1` as a valid offset that returns data from the beginning of the stream.

- **`now` (Current Tail Position)**: The special offset value `now` allows clients to skip all existing data and begin reading from the current tail position. This is useful for applications that only care about future data (e.g., presence tracking, live monitoring, late joiners to a conversation). The behavior varies by read mode:

  **Catch-up mode** (`offset=now` without `live` parameter):
  - Servers **MUST** return `200 OK` with an empty response body appropriate to the stream's content type:
    - For `application/json` streams: the body **MUST** be `[]` (empty JSON array), consistent with Section 7.1
    - For all other content types: the body **MUST** be 0 bytes (empty)
  - Servers **MUST** include a `Stream-Next-Offset` header set to the current tail position
  - Servers **MUST** include `Stream-Up-To-Date: true` header
  - Servers **SHOULD** return `Cache-Control: no-store` to prevent caching of the tail offset
  - The response **MUST** contain no data messages, regardless of stream content

  **Long-poll mode** (`offset=now&live=long-poll`):
  - Servers **MUST** immediately begin waiting for new data (no initial empty response)
  - This eliminates a round-trip: clients can subscribe to future data in a single request
  - If new data arrives during the wait, servers return `200 OK` with the new data
  - If the timeout expires, servers return `204 No Content` with `Stream-Up-To-Date: true`
  - The `Stream-Next-Offset` header **MUST** be set to the tail position

  **SSE mode** (`offset=now&live=sse`):
  - Servers **MUST** immediately begin the SSE stream from the tail position
  - The first control event **MUST** include the tail offset in `streamNextOffset`
  - If no data has arrived, the first control event **MUST** include `upToDate: true`
  - If data arrives before the first control event, `upToDate` reflects the current state
  - No historical data is sent; only future data events are streamed

**Reserved Values**: The sentinel values `-1` and `now` are reserved by the protocol. Server implementations **MUST NOT** generate these strings as actual stream offsets (in `Stream-Next-Offset` headers or SSE control events). This ensures clients can always distinguish between sentinel requests and real offset values.

The opaque nature of offsets enables important server-side optimizations. For example, offsets may encode chunk file identifiers, allowing catch-up requests to be served directly from object storage without touching the main database.

Clients **MUST** use the `Stream-Next-Offset` value returned in responses for subsequent read requests. They **SHOULD** persist offsets locally (e.g., in browser local storage or a database) to enable resumability after disconnection or restart.

## 7. Content Types

The protocol supports arbitrary MIME content types. Most content types operate at the byte level, leaving message framing and interpretation to clients. The `application/json` content type has special semantics defined below.

**Restriction:**

- SSE mode (Section 5.7) **REQUIRES** `content-type: text/*` or `application/json`

Clients **MAY** use any content type for their streams, including:

- `application/json` for JSON mode with message boundary preservation
- `application/ndjson` for newline-delimited JSON
- `application/x-protobuf` for Protocol Buffer messages
- `text/plain` for plain text
- Custom types for application-specific formats

### 7.1. JSON Mode

Streams created with `Content-Type: application/json` have special semantics for message boundaries and batch operations.

#### Message Boundaries

For `application/json` streams, servers **MUST** preserve message boundaries. Each POST request stores messages as a distinct unit, and GET responses **MUST** return data as a JSON array containing all messages from the requested offset range.

#### Array Flattening for Batch Operations

When a POST request body contains a JSON array, servers **MUST** flatten exactly one level of the array, treating each element as a separate message. This enables clients to batch multiple messages in a single HTTP request while preserving individual message semantics.

**Examples (direct POST to server):**

- POST body `{"event": "created"}` stores one message: `{"event": "created"}`
- POST body `[{"event": "a"}, {"event": "b"}]` stores two messages: `{"event": "a"}`, `{"event": "b"}`
- POST body `[[1,2], [3,4]]` stores two messages: `[1,2]`, `[3,4]`
- POST body `[[[1,2,3]]]` stores one message: `[[1,2,3]]`

**Note:** Client libraries **MAY** automatically wrap individual values in arrays for batching. For example, a client calling `append({"x": 1})` might send POST body `[{"x": 1}]` to the server, which flattens it to store one message: `{"x": 1}`.

#### Empty Arrays

Servers **MUST** reject POST requests containing empty JSON arrays (`[]`) with `400 Bad Request`. Empty arrays in append operations represent no-op operations with no semantic meaning and likely indicate a client bug.

PUT requests with an empty array body (`[]`) are valid and create an empty stream. The empty array simply means no initial messages are being written.

#### JSON Validation

Servers **MUST** validate that appended data is valid JSON. If validation fails, servers **MUST** return `400 Bad Request` with an appropriate error message.

#### Response Format

GET responses for `application/json` streams **MUST** return `Content-Type: application/json` with a body containing a JSON array of all messages in the requested range:

```http
HTTP/1.1 200 OK
Content-Type: application/json

[{"event":"created"},{"event":"updated"}]
```

If no messages exist in the range, servers **MUST** return an empty JSON array `[]`.

## 8. Caching and Collapsing

### 8.1. Catch-up and Long-poll Reads

For **shared, non-user-specific streams**, servers **SHOULD** return:

```
Cache-Control: public, max-age=60, stale-while-revalidate=300
```

For **streams that may contain user-specific or confidential data**, servers **SHOULD** use `private` instead of `public` and rely on CDN configurations that respect `Authorization` or other cache keys:

```
Cache-Control: private, max-age=60, stale-while-revalidate=300
```

This enables CDN/proxy caching while allowing stale content to be served during revalidation.

**ETag Usage:**

Servers **MUST** generate `ETag` headers for GET responses, except for `offset=now` responses. Clients **MAY** use `If-None-Match` with the `ETag` value on repeat catch-up requests. When a client provides a valid `If-None-Match` header that matches the current ETag, servers **MUST** respond with `304 Not Modified` (with no body) instead of re-sending the same data. This is essential for fast loading and efficient bandwidth usage.

**Query Parameter Ordering:**

For optimal cache behavior, clients **SHOULD** order query parameters lexicographically by key name. This ensures consistent URL serialization across implementations and improves CDN cache hit rates.

**Collapsing:**

Clients **SHOULD** echo the `Stream-Cursor` value as `cursor=<cursor>` in subsequent long-poll requests. This, along with the appropriate `Cache-Control` header, enables CDNs and proxies to collapse multiple clients waiting for the same data into a single upstream request.

**Server-Generated Cursors:**

To prevent infinite CDN cache loops (where clients receive the same cached empty response indefinitely), servers **MUST** generate cursors on all live mode responses:

- **Long-poll**: `Stream-Cursor` response header
- **SSE**: `streamCursor` field in `control` events

The cursor mechanism works as follows:

1. **Interval-based Calculation**: Servers divide time into fixed intervals (default: 20 seconds) counted from an epoch (default: October 9, 2024 00:00:00 UTC). The cursor value is the interval number as a decimal string.

2. **Cursor Generation**: For each live response, the server calculates the current interval number and returns it as the cursor value.

3. **Monotonic Progression**: Servers **MUST** ensure cursors never go backwards. When a client provides a `cursor` query parameter that is greater than or equal to the current interval number, the server **MUST** return a cursor strictly greater than the client's cursor (by adding random jitter of 1-3600 seconds). This guarantees monotonic progression and prevents cache cycles.

4. **Client Behavior**: Clients **MUST** include the received cursor value as the `cursor` query parameter in subsequent requests. This creates different cache keys as time progresses, ensuring CDN caches eventually expire.

**Example Cursor Flow:**

```
# Client makes initial long-poll request
GET /stream?offset=123&live=long-poll

# Server returns cursor based on current interval (e.g., interval 1000)
< Stream-Cursor: 1000

# Client echoes cursor on next request
GET /stream?offset=123&live=long-poll&cursor=1000

# If still in same interval, server adds jitter and returns advanced cursor
< Stream-Cursor: 1050
```

**Long-poll Caching:**

CDNs and proxies **SHOULD NOT** cache `204 No Content` responses from long-poll requests in most cases. Long-poll `200 OK` responses are safe to cache when keyed by `offset`, `cursor`, and authentication credentials.

### 8.2. SSE

SSE connections **SHOULD** be closed by the server approximately every 60 seconds. This enables new clients to collapse onto edge requests rather than maintaining long-lived connections to origin servers.

## 9. Extensibility

The Durable Streams Protocol is designed to be extended for specific use cases and implementations. Extensions **SHOULD** be pure supersets of the base protocol, ensuring compatibility with any client that implements the base protocol.

### 9.1. Protocol Extensions

Implementations **MAY** extend the protocol with additional query parameters, headers, or response fields to support domain-specific semantics. For example, a database synchronization implementation might add query parameters to filter by table or schema, or include additional metadata in response headers.

Extensions **SHOULD** follow these principles:

- **Backward Compatibility**: Extensions **MUST NOT** break base protocol semantics. Clients that do not understand extension parameters or headers **MUST** be able to operate using only base protocol features.

- **Pure Superset**: Extensions **SHOULD** be additive only. New parameters and headers **SHOULD** be optional, and servers **SHOULD** provide sensible defaults or fallback behavior when extensions are not used.

- **Version Independence**: Extensions **SHOULD** work with any version of a client that implements the base protocol. Extension negotiation **MAY** be handled through headers or query parameters, but base protocol operations **MUST** remain functional without extension support.

### 9.2. Authentication Extensions

See Section 10.1 for authentication and authorization details. Implementations **MAY** extend the protocol with authentication-related query parameters or headers (e.g., API keys, OAuth tokens, custom authentication headers).

### 9.3. Correctness Profiles (Example)

Implementations **MAY** publish named correctness profiles that tighten behavior beyond base requirements.

Example profile (`riverrun-correctness-v1`):

1. Strict durable ACK: append success is returned only after durable publish/commit.
2. Published-only reads: public read APIs never expose unpublished/uncommitted data.
3. Close-only uses `POST {stream-url}` with `Stream-Closed: true` and an empty body.

## 10. Security Considerations

### 10.1. Authentication and Authorization

Authentication and authorization are explicitly out of scope for this protocol specification. Clients **SHOULD** implement all standard HTTP authentication primitives (e.g., Basic Authentication [RFC7617], Bearer tokens [RFC6750], Digest Authentication [RFC7616]). Implementations **MUST** provide appropriate access controls to prevent unauthorized stream creation, modification, or deletion, but may do so using any mechanism they choose, including extending the protocol with authentication-related parameters or headers as described in Section 9.2.

### 10.2. Multi-tenant Safety

If stream URLs are guessable, servers **MUST** enforce access controls even when using shared caches. Servers **SHOULD** validate and sanitize stream URLs to prevent path traversal attacks and ensure URL components are within acceptable limits.

### 10.3. Untrusted Content

Clients **MUST** treat stream contents as untrusted input and **MUST NOT** evaluate or execute stream data without appropriate validation. This is particularly important for append-only streams used as logs, where log injection attacks are a concern.

### 10.4. Content Type Validation

Servers **MUST** validate that appended content types match the stream's declared content type to prevent type confusion attacks.

### 10.5. Rate Limiting

Servers **SHOULD** implement rate limiting to prevent abuse. The `429 Too Many Requests` response code indicates rate limit exhaustion.

### 10.6. Sequence Validation

The optional `Stream-Seq` header provides protection against out-of-order writes in multi-writer scenarios. Servers **MUST** reject sequence regressions to maintain stream integrity.

### 10.7. Browser Security Headers

When serving streams to browser clients, servers **SHOULD** include the following headers to prevent MIME-sniffing attacks, cross-origin embedding exploits, and cache-related vulnerabilities:

- `X-Content-Type-Options: nosniff`
  - Servers **SHOULD** include this header on all responses. This prevents browsers from MIME-sniffing the response content and potentially executing it as a different content type (e.g., interpreting binary data as HTML/JavaScript).

- `Cross-Origin-Resource-Policy: cross-origin` (or `same-origin`/`same-site`)
  - Servers **SHOULD** include this header to explicitly control cross-origin embedding. Use `cross-origin` to allow cross-origin access via `fetch()`, `same-site` to restrict to the same registrable domain, or `same-origin` for strict same-origin only. This prevents Cross-Origin Read Blocking (CORB) issues and protects against Spectre-like side-channel attacks.

- `Cache-Control: no-store`
  - Servers **SHOULD** include this header on HEAD responses and on responses containing sensitive or user-specific stream data. This prevents intermediate proxies and CDNs from caching potentially sensitive content. For public, non-sensitive historical reads, servers **MAY** use `Cache-Control: public, max-age=60, stale-while-revalidate=300` as described in Section 8.

- `Content-Disposition: attachment` (optional)
  - Servers **MAY** include this header for `application/octet-stream` responses to prevent inline rendering if a user navigates directly to the stream URL.

These headers provide defense-in-depth for scenarios where stream URLs might be accessed outside the intended programmatic fetch context (e.g., direct navigation, malicious cross-origin embedding via `<script>` or `<img>` tags).

### 10.8. TLS

All protocol operations **MUST** be performed over HTTPS (TLS) in production environments to protect data in transit.

## 11. IANA Considerations

### 11.1. Default Port

The default port for standalone Durable Streams servers is **4437/tcp** (with 4437/udp reserved for future use).

This port was selected from the IANA unassigned range 4434-4440. Standalone server implementations **SHOULD** use port 4437 as the default when no explicit port is configured. When Durable Streams is integrated into an existing web server or application framework, it **SHOULD** use the host server's port instead.

### 11.2. HTTP Headers

This document requests registration of the following HTTP headers in the "Permanent Message Header Field Names" registry:

| Field Name           | Status    | Reference     |
| -------------------- | --------- | ------------- |
| `Stream-TTL`         | permanent | This document |
| `Stream-Expires-At`  | permanent | This document |
| `Stream-Seq`         | permanent | This document |
| `Stream-Cursor`      | permanent | This document |
| `Stream-Next-Offset` | permanent | This document |
| `Stream-Up-To-Date`  | permanent | This document |

**Descriptions:**

- `Stream-TTL`: Relative time-to-live for streams (seconds)
- `Stream-Expires-At`: Absolute expiry time for streams (RFC 3339 timestamp)
- `Stream-Seq`: Writer sequence number for coordination (opaque string)
- `Stream-Cursor`: Cursor for CDN collapsing (opaque string)
- `Stream-Next-Offset`: Next offset for subsequent reads (opaque string)
- `Stream-Up-To-Date`: Indicates up-to-date response (presence header)

## 12. References

### 12.1. Normative References

[RFC2119] Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", BCP 14, RFC 2119, DOI 10.17487/RFC2119, March 1997, <https://www.rfc-editor.org/info/rfc2119>.

[RFC3339] Klyne, G. and C. Newman, "Date and Time on the Internet: Timestamps", RFC 3339, DOI 10.17487/RFC3339, July 2002, <https://www.rfc-editor.org/info/rfc3339>.

[RFC8174] Leiba, B., "Ambiguity of Uppercase vs Lowercase in RFC 2119 Key Words", BCP 14, RFC 8174, DOI 10.17487/RFC8174, May 2017, <https://www.rfc-editor.org/info/rfc8174>.

[RFC9110] Fielding, R., Ed., Nottingham, M., Ed., and J. Reschke, Ed., "HTTP Semantics", STD 97, RFC 9110, DOI 10.17487/RFC9110, June 2022, <https://www.rfc-editor.org/info/rfc9110>.

[RFC9113] Thomson, M., Ed. and C. Benfield, Ed., "HTTP/2", RFC 9113, DOI 10.17487/RFC9113, June 2022, <https://www.rfc-editor.org/info/rfc9113>.

[RFC7617] Reschke, J., "The 'Basic' HTTP Authentication Scheme", RFC 7617, DOI 10.17487/RFC7617, September 2015, <https://www.rfc-editor.org/info/rfc7617>.

[RFC6750] Jones, M. and D. Hardt, "The OAuth 2.0 Authorization Framework: Bearer Token Usage", RFC 6750, DOI 10.17487/RFC6750, October 2012, <https://www.rfc-editor.org/info/rfc6750>.

[RFC7616] Shekh-Yusef, R., Ed., Ahrens, D., and S. Bremer, "HTTP Digest Access Authentication", RFC 7616, DOI 10.17487/RFC7616, September 2015, <https://www.rfc-editor.org/info/rfc7616>.

### 12.2. Informative References

[SSE] Hickson, I., "Server-Sent Events", W3C Recommendation, February 2015, <https://www.w3.org/TR/eventsource/>.

---

**Full Copyright Statement**

Copyright (c) 2025 ElectricSQL

This document and the information contained herein are provided on an "AS IS" basis. ElectricSQL disclaims all warranties, express or implied, including but not limited to any warranty that the use of the information herein will not infringe any rights or any implied warranties of merchantability or fitness for a particular purpose.

## Full DS-CRDT Extension Reference (Interface-Level)

This section defines DS-CRDT protocol extensions on top of the Durable Streams Protocol.
This is an interface-level reference only.

## 1. Bucket Model

Each stream belongs to a bucket, and the URL shape is:

`<baseUrl>/ds/<bucketId>/<streamId>`

Identifier constraints:

- `bucketId`: `^[a-z0-9_-]{4,64}$`, globally unique in the deployment scope.
- `streamId`: UTF-8 string, `len(bytes) <= 512`, must not contain `/`, `\0`, or `..`.

### 1.1 Bucket Creation Semantics

Bucket creation is explicit. `PUT /ds/:bucket/:stream` MUST NOT implicitly create a missing bucket.

- `PUT /ds/:bucket`
  - `201 Created`: bucket created
  - `409 Conflict`: bucket already exists
  - `400 Bad Request`: invalid `bucketId`
- `PUT /ds/:bucket/:stream`
  - `404 Not Found` when bucket does not exist

Recommended call order:

1. `PUT /ds/:bucket`
2. `PUT /ds/:bucket/:stream`
3. `POST /ds/:bucket/:stream`

Example:

```bash
# 1) Create bucket
curl -i -X PUT http://127.0.0.1:8787/ds/buck1

# 2) Create stream in existing bucket
curl -i -X PUT http://127.0.0.1:8787/ds/buck1/doc1 \
  -H "Content-Type: application/json"

# 3) Create stream in missing bucket -> 404
curl -i -X PUT http://127.0.0.1:8787/ds/buck2/doc1 \
  -H "Content-Type: application/json"
```

## 2. Snapshot

This section defines snapshot create, resolve, and read APIs, and bootstrap for low-latency initialization.

### 2.1 Terms And Constraints

- **Offset is opaque**: client MUST treat offsets as opaque tokens and always continue from server-returned `Stream-Next-Offset`.
- **Snapshot offset**: `snapshot_offset` is the stream position covered by the snapshot. Semantically, snapshot materializes `[-1, snapshot_offset)`.
- **Compatibility mode**: `GET {stream_url}?offset=...` MUST preserve stream native content type and raw stream bytes only.
- **JSON mode**: if stream content type is `application/json`, JSON message boundary rules still apply. Snapshot APIs are orthogonal to JSON mode.

### 2.2 Create Snapshot

```
PUT {stream_url}/snapshot/<snapshot_offset>

<snapshot-binary>
```

Semantics:

- Creates snapshot at `snapshot_offset`, covering updates before that offset.
- Snapshot compacts historical updates for faster rehydration.
- After successful snapshot write, server MUST treat `snapshot_offset` as earliest retained offset.
- Reads targeting offsets `< snapshot_offset` (including `-1`) MUST return `410 Gone`.

Request headers:

- `Content-Type: <snapshot-content-type>`
  - Server MUST persist and return this content type on snapshot read.
  - Recommended default: `application/octet-stream`.

Response codes:

- `204 No Content`: snapshot write succeeded
- `400 Bad Request`: invalid offset format or non-boundary offset
- `404 Not Found`: stream does not exist
- `409 Conflict`: offset is beyond tail or cannot produce consistent view
- `413 Payload Too Large`: snapshot payload too large

Consistency:

- Consistency boundary is exactly `snapshot_offset`.
- Concurrent appends are allowed, but snapshot MUST NOT include updates at or after `snapshot_offset`.

### 2.3 Resolve Latest Snapshot

```
GET {stream_url}/snapshot
```

With snapshot:

```
HTTP/1.1 307 Temporary Redirect
Location: {stream_url}/snapshot/<snapshot_offset>
Cache-Control: private, max-age=5
```

Without snapshot:

```
HTTP/1.1 404 Not Found
```

### 2.4 Read Snapshot

```
GET {stream_url}/snapshot/<snapshot_offset>
```

Response body is snapshot bytes (no framing).

Response headers:

- `Content-Type: <snapshot-content-type>`
- `Stream-Snapshot-Offset: <snapshot_offset>`
- `Stream-Next-Offset: <next-offset>`
- `Stream-Up-To-Date: boolean`

Response codes:

- `200 OK`: snapshot exists
- `404 Not Found`: snapshot does not exist

## 3. Binary Framing: Length-Prefixed Messages

To preserve boundaries for concatenated binary payloads and support single-request bootstrap, DS-CRDT defines a common framing format.

Content type:

- `application/octet-stream`

Item format:

```
item := len:u32be + payload:byte[len]
```

Constraints:

- `len` is payload byte length only.
- Max item size is implementation-defined; oversized writes SHOULD return `413`.
- Decoders MUST support streaming parse across partial chunks.

Payload semantics:

- Payload meaning is application-defined.
- Protocol only defines boundary/framing semantics.

## 4. CRDT Update Stream (Optional)

CRDT update streams may use any content type.

- For binary updates with boundaries, use `application/octet-stream` and encode each update as one framed message.
- For JSON updates, `application/json` mode already preserves boundaries.

## 5. Bootstrap (Single-Request Initialization)

To avoid extra RTT (`snapshot` then `updates`), DS-CRDT adds bootstrap:

```
GET {stream_url}/bootstrap
```

Query params:

- `/bootstrap` is one-shot only.
- Servers SHOULD reject any `live` query parameter on `/bootstrap` with `400 Bad Request`.

Response codes:

- `200 OK`: bootstrap data
- `404 Not Found`: stream not found

Response headers:

- `Content-Type: multipart/mixed; boundary=<token>`
- `Stream-Snapshot-Offset: <snapshot_offset_or_-1>`
- `Stream-Next-Offset: <next-offset>`
- `Stream-Up-To-Date: boolean`

Response body (`multipart/mixed`):

1. First part: snapshot bytes (empty part when no snapshot, and header offset MUST be `-1`).
2. Remaining parts: update bytes from snapshot offset to tail (or from `-1` when no snapshot).

## 6. Bootstrap Follow-Up

- `/bootstrap` returns snapshot + retained updates once.
- To keep tailing, client MUST continue with ordinary reads from the returned `Stream-Next-Offset`.
- Normal `GET {stream_url}?offset=...` MUST NOT return snapshot bytes.
- If read returns `410 Gone`, client SHOULD bootstrap and then resume from returned `Stream-Next-Offset`.
- If retention has advanced (earliest retained offset > `-1`), bootstrap MUST remain available.

## 7. URL Encoding Constraint

`snapshot_offset` may contain characters that require encoding.
Clients and servers MUST use standard URL encoding/decoding for path segment handling.

## 8. Binary SSE

Ordinary SSE behavior comes from the base DS protocol.

- For binary streams, servers MUST send raw base64 `event: data` payloads.
- For binary streams, responses MUST include `stream-sse-data-encoding: base64`.
- `event: control` semantics remain unchanged.
- Client compatibility strategy:
  - Try ordinary `live=sse` first.
  - If server returns `400` for unsupported SSE, fallback to `live=long-poll`.
  - On fallback/reconnect, always use latest applied offset.

## 9. Ephemeral Stream Retention Extension

This extension defines explicit retention for ephemeral workloads (presence, cursors, selections):

- Request header on `PUT {stream_url}`:
  - `Ephemeral-Stream-Retention-Seconds: <seconds>`

Value constraints:

- Decimal non-negative integer.
- No leading zeros (except literal `0`).
- No plus sign, decimal point, or scientific notation.
- Header omitted means unlimited retention behavior.

Protocol-visible behavior:

- Server MAY drop data older than retention window.
- If read targets `offset < earliest_retained`, server MUST return `410 Gone`.
- Offsets MUST remain monotonic and stable (no renumbering).
- Retention value is part of stream create/ensure idempotency.
  - Existing stream with different retention value -> `409 Conflict`.
- Snapshot APIs are not supported for streams created with this header:
  - `GET {stream_url}/snapshot`
  - `GET {stream_url}/snapshot/<offset>`
  - `PUT {stream_url}/snapshot/<offset>`
  - These MUST return `400 Bad Request`.

Example:

```bash
# Create bucket
curl -i -X PUT http://127.0.0.1:8080/ds/buck1

# Create/ensure ephemeral stream with retention
curl -i -X PUT http://127.0.0.1:8080/ds/buck1/presence-room-1 \
  -H "Content-Type: application/octet-stream" \
  -H "Ephemeral-Stream-Retention-Seconds: 120"

# Append
curl -i -X POST http://127.0.0.1:8080/ds/buck1/presence-room-1 \
  -H "Content-Type: application/octet-stream" \
  --data-binary "hello"

# Read from beginning
curl -i "http://127.0.0.1:8080/ds/buck1/presence-room-1?offset=-1"

# Read from tail
curl -i "http://127.0.0.1:8080/ds/buck1/presence-room-1?offset=now"
```

## 10. Client Interoperability Constraints

The following constraints must hold for interoperable clients:

- `joined` means client is in sustainable sync state, not that SSE transport is always open.
- On auth failures (`401`/`403`), client should enter terminal error state and stop automatic retries until explicit rejoin.
- Ephemeral lane still requires durable send semantics at client side:
  - failed send must not be dropped before ack
  - dequeue only after successful ack
- Reconnect requests MUST use latest applied offset.
- On `410 Gone`, read path MUST switch to bootstrap rebuild and then continue tailing.
