# Osy.Client — hold a live endpoint open from a .NET program

> `Osy.Client` is the .NET package (MIT-licensed, published by Osysharp with each platform release as an asset on the osysharp/cli GitHub release) a program uses to hold an app's live endpoint open with an API key and be told what changed, instead of asking every few seconds. `await foreach` over `app.Live<T>("route/path", args)` yields Added, Updated and Removed by id; the first answer arrives as Added. The package reconnects with backoff and full jitter, resumes with `Last-Event-ID` (nothing is repeated, and what changed while the stream was down arrives as changes), treats 50 s of silence as a dead connection, ends with `LiveRefusedException` on a refusal a retry would meet again, and measures itself on the meter `Osy.Client.Live`.

<!-- id: api-live-sdk · area: api · stability: preview · html: https://osysharp.com/reference/api/live-sdk/ -->

## Summary        {#summary}
A page's live query is pushed: each commit's changed rows are matched in memory and the page is sent its change, built
from the commit under the reader's own rules, with no query run. A **live endpoint** — a REST endpoint the app declares
`Live = true` — gives a program the same pushed changes over Server-Sent Events on the REST door, with an API key.
`Osy.Client` is the .NET side of it.

## Signature      {#signature}
```csharp
using Osy.Client.Live;

var app = new OsyApp(new Uri("https://shop.osyrin.app"), OsyCredential.ApiKey(hostKey));
await using LiveQuery<BuildTask> work = app.Live<BuildTask>("hosts/work", new { host = hostId });
await foreach (LiveChange<BuildTask> change in work.WithCancellation(stopping)) { … }
```

## Description    {#description}

### Holding an endpoint   {#holding}
`app.Live<T>(endpoint, args)` names the endpoint by its REST path under the app's API (its `RestApi.Route` and the
endpoint's `Path`: `hosts/work`) and binds its arguments once, as for a GET: an object whose properties are plain values
(text, numbers, true/false, ids, dates). Nothing is sent until the query is enumerated: the stream **is** the
subscription, so it opens when the enumeration starts and closes — the app's subscription with it — when the enumeration
ends. A query is enumerated once; call `Live` again for another stream. `app.Live(endpoint, args)` (no type) yields rows
as `JsonElement`, for tools and tests.

Each `LiveChange<T>` is `(Kind, Id, Item, Position, AfterReconnect)`:
- **`Added`** — the row is in the answer now. The first answer arrives as one Added per row.
- **`Updated`** — a row held changed. A row the app sends unchanged yields nothing.
- **`Removed`** — the row left the answer (deleted, filtered out, or no longer readable by the key's principal); `Item`
  is the row as last seen.
- **`Position`** is the app's own commit position the change was read at.

`Current` is the answer as it stands, by id, updated before each change is yielded and safe to read from any thread.
`Ready` completes when the first answer is applied. `State` is `Connecting`, `Live`, `Retrying` or `Ended`.

### Reconnect and resume   {#resume}
A dropped connection, a stopping server (`ended` with `unavailable`), a `503`, a `429` or a dead connection is retried:
exponential backoff with **full jitter** — a random wait up to `FirstRetry` × 2ⁿ (0.5 s), capped at `LongestRetry`
(30 s) — never sooner than the app asked by the stream's `retry:` or a refusal's `Retry-After`. The count starts again on
the first frame of a good connection.

The reconnect sends the last event id as `Last-Event-ID`. The app reads the query once, as the new server must hold its
subscription: if the answer is what was sent, it answers `same` and **nothing is yielded**; otherwise it sends a fresh
snapshot, which the SDK compares with `Current` and yields only the differences, each with `AfterReconnect = true`. App
code sees only changes either way.

### Silence, refusals and cancellation   {#ending}
The app sends a heartbeat (`: hb`) every 20 s, so **50 s of silence** (`SilenceIsDead`) is taken as a dead connection
and reopened.

A refusal a retry would meet again ends the enumeration with **`LiveRefusedException`** (`Code`, `Message`, `Status`),
and faults `Ready`: `denied` (`401`/`403` before the stream opens, or `ended {code: "denied"}` on an open stream — the
key was revoked or replaced, its holder switched off, or the organization's key rule shuts it out), `invalid` (not a
live endpoint, or it changed on a deploy) and `not-found`. It is never retried.

The cancellation token given to the enumeration (`WithCancellation`) ends the HTTP request, and `DisposeAsync` on the
query does the same. A row that does not fit `T` throws `JsonException`: the program's type and the endpoint disagree.

### Options   {#options}
`OsyAppOptions`: `FirstRetry` (0.5 s), `LongestRetry` (30 s), `SilenceIsDead` (50 s), `Handler` (default one
`SocketsHttpHandler` per `OsyApp`, so one HTTP/2 connection carries every stream; a handler given here is not disposed),
`Json` (how rows become `T`; default the web defaults: camelCase, case-insensitive).

### Metrics   {#metrics}
On the meter **`Osy.Client.Live`** (System.Diagnostics.Metrics; OpenTelemetry and `dotnet-counters` read it), each
tagged `osy.live.endpoint`:

| Instrument | What |
|---|---|
| `osy.live.open` | streams up now |
| `osy.live.frames` | frames received, by `osy.live.frame`: open, snapshot, delta, delta-fill, same, ended, hb |
| `osy.live.reconnects` | reconnects, by `osy.live.reason`: dropped, silence, protocol, unreachable, http-*status*, ended-*code* |
| `osy.live.resyncs` | snapshots after the first (a reconnect whose answer moved, a role grant, a reader that fell behind) |
| `osy.live.bytes` | bytes of the stream read |
| `osy.live.lag` | seconds from the commit (the frame's `at`) to the frame received |

### The wire protocol   {#wire}
Plain Server-Sent Events: `GET /api/rest/v1/<route>/<path>?<args>` with `Accept: text/event-stream` and `X-API-Key`
(and `Last-Event-ID` on a reconnect). A refusal before the stream opens is the ordinary REST answer with its error body.

```text
retry: 2000
event: open
data: {"heartbeat":20,"shape":"rows"}

id: 18234.71b0e2c94a5d3f18
event: snapshot
data: {"rows":[{"id":"…","kind":"build","priority":2}],"position":18234}

: hb

id: 18240.9f2c61d0b7e4a835
event: delta
data: {"upserts":[{"id":"…","kind":"build","priority":3}],"removed":["…"],"position":18240,"at":"2026-11-23T10:15:02Z"}

event: same
id: 18240.9f2c61d0b7e4a835

event: ended
data: {"code":"denied","message":"This key no longer opens this app."}
```

- **`snapshot`** — the whole answer, on every open and reopen, or when the app re-reads (a role grant of the key's
  principal, a reader that fell behind).
- **`delta`** — only the rows that moved, built from the commit. A row is flat, with its `id` (the REST row shape). A
  column the commit could not carry is named in the frame's `missing` map, `{"<id>": ["column", …]}` — never inside the
  row, so a column that is itself called `missing` is just a column — and keeps its held value until the `delta-fill`
  brings it. (The SDK also reads the page socket's row shape, `{id, entityType, values, missing}`; the live door does not
  send it.)
- **`delta-fill`** — `{rows, removed}`: flat rows with those columns, for rows already sent; a row the fill's read no
  longer returns is `removed`.
- **`same`** — a reconnect whose `Last-Event-ID` still holds: keep what you have.
- **`ended`** — `{code, message}`, then the server closes. `denied`, `invalid`, `not-found`: do not retry.
  `unavailable`, `fault`: retry with backoff.

The event id is `{position}.{hash}`: the app's own commit position and a hash of the answer sent (16 hex characters; an id
the app cannot read is answered with a snapshot). The door's side of it, its refusals and limits: [[api-live-endpoints#serving]].

## Examples       {#examples}
A host that holds its offered work open instead of polling, and takes a task with an ordinary call:

```csharp syntax
var app = new OsyApp(appUrl, OsyCredential.ApiKey(hostKey), new OsyAppOptions { SilenceIsDead = TimeSpan.FromSeconds(50) });
await using var work = app.Live<BuildTask>("hosts/work", new { host = hostId });

await foreach (var change in work.WithCancellation(stopping))
{
    switch (change.Kind)
    {
        case LiveChangeKind.Added:   tasks.Heard(change.Item!);  break;   // then POST hosts/poll to take one
        case LiveChangeKind.Updated: tasks.Update(change.Item!); break;
        case LiveChangeKind.Removed: tasks.Withdraw(change.Id);  break;
    }
}
```

Telling a refusal from a drop:

```csharp syntax
try { await foreach (var change in work.WithCancellation(stopping)) Handle(change); }
catch (LiveRefusedException refused) when (refused.Code == "denied")
{
    log.Warn($"the key no longer opens the app: {refused.Message}");   // a new key is needed; retrying is refused the same way
}
```

## See also       {#see-also}
- [Live endpoints — one query a program holds open (Live = true)](https://osysharp.com/reference/api/live-endpoints/) — declaring a live endpoint, and how the app serves it
- [publishing a REST API (app.Apis)](https://osysharp.com/reference/api/rest/) — REST endpoints, API keys, and `stream<T>` endpoints as server-sent events
- The package: `Osy.Client`, MIT-licensed, released with each platform version

## Getting the package today      {#getting-the-package}
nuget.org comes later: until Osysharp has an organization there, each platform release and preview carries
`Osy.Client.<version>.nupkg` as an asset on its GitHub release at `https://github.com/osysharp/cli/releases`. Download it
(its hash is in the release's `SHA256SUMS`) into a folder, make the folder a package source, and add the package:

```bash
mkdir -p ~/osy-packages && cd ~/osy-packages
gh release download v<version> --repo osysharp/cli --pattern 'Osy.Client.*.nupkg' --pattern SHA256SUMS
cd /path/to/your/project
dotnet nuget add source ~/osy-packages --name osy-local
dotnet add package Osy.Client --version <version>
```

The package carries its own MIT licence (`LICENSE.txt` inside it), separate from the Osy# tools' terms.
