# Live endpoints — one query a program holds open (Live = true)

> `Live = true` on a REST endpoint is a program's `live var`. A program holds the endpoint open with its API key and is sent each change to the endpoint's rows, instead of asking again every few seconds. The function must be ONE query: a filtered, ordered, limited read of one entity, with no `Include`, answering that entity's rows or chosen columns of them (a `Select` into a class whose members are the row's own columns, `Id` among them). Then each change is built from the commit, as a page's live query is, with no query run, and carries only those columns. The compiler refuses anything else and says why. A live endpoint needs a GET and an `Auth` other than `Anonymous`, and its function may not be a `stream<T>`. `osy model` shows each live endpoint's entity and filter; `osy check` names any column or rule that will cost a statement on a change.

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

## Summary        {#summary}
A program that needs to know when rows change marks one REST endpoint live:

```osy syntax
new Endpoint(WorkFor) { Path = "/work", Live = true }
```

## Signature      {#signature}
```osy syntax
new RestApi("Hosts") {
  Route = "hosts",
  Auth  = new ApiAuth { ApiKey = true },        // not Anonymous: each change is built as the caller
  Endpoints = [
    new Endpoint(WorkFor) { Path = "/work", Live = true },   // a GET (the default Method)
  ],
}
```

## Description    {#description}
A page keeps a query live with `live var` ([The reactivity & lifecycle model](https://osysharp.com/reference/ui/reactivity/)): the commit carries each changed row to every server,
and the page is sent the change, built from those values under the reader's own rules, with no query run. A program
has no page to write `live var` in, so it declares the same thing on the endpoint it calls: `Live = true`.

### One query   {#one-query}
The function of a live endpoint is one read of one entity, `return`ed (or written with `=>`):

- filtered with `Where`, ordered with `OrderBy`, limited with `Take`;
- answering that entity's rows, or chosen columns of them ([below](#columns)): no `Include`, no join, no `Skip`, no
  `Distinct`, no count or sum;
- with no second read inside the filter.

Anything more is refused with `LIVE_ENDPOINT_NOT_ONE_QUERY`, the reason (for example "`Waiting` makes 2 reads in 4
statements") and the suggestion: *answer the rows of one query; each change is then built from the commit*. Logic that
is more than one query stays in an ordinary endpoint the program calls when a change arrives. Deciding which waiting parcel
a worker takes is such logic: the live endpoint tells the worker there is something to take, and an ordinary `POST`
takes it.

A function that writes is refused too: a live endpoint only reads. One whose answer depends on the clock or the network
is accepted with the warning `LIVE_CALL_UNANNOUNCED_DEPENDENCY`, the code a page's live call gets. No commit announces
time passing, so a row can enter or leave the answer with nothing sent.

### A `Select` answers chosen columns   {#columns}
A row often holds more than a program should be sent: a sealed copy, a long text, a note for people. End the query with
a `Select` into a class whose members are the row's own columns, and the stream answers those and nothing else:

```osy syntax
class WorkRow { public Guid Id; public string Title; public WorkState State; }

[Authorize(IsAHost)]
List<WorkRow> WorkFor(string host) =>
  Work.Where(w => w.Host == host && w.State != WorkState.Done).OrderBy(w => w.Rank).Take(200)
      .Select(w => new WorkRow { Id = w.Id, Title = w.Title, State = w.State }).ToList();
```

- Each member is one stored column of the row, written as it is (`State = w.State`). A computed value, a reference's
  column (`w.Host.Name`) or a classified column is refused with its reason.
- `Id = w.Id` is one of them: every change names the row it is of by its id. A `Select` without it is refused.
- The snapshot and every `delta` and `delta-fill` carry the row's `id` and the selected columns, named by their members
  as the GET's answer names them. A column only the filter or the order reads is not sent. The server does not read a
  column you leave out, does not fill it, and never sends it.
- The app's read rules apply to every selected column as they apply to the row: a column `deny read` hides from the
  caller is sent as its stand-in, never its value. Which rows the stream holds is decided exactly as without the `Select`.
- A cost `osy check` names is a cost of the selected columns only: a long text you leave out costs no fill.

### What it needs   {#needs}
- **A GET.** A live endpoint is read. `Method = HttpMethod.Post` beside `Live = true` is refused.
- **A caller it knows.** The API's `Auth` may not be `Anonymous`: each change is built as the caller, under the app's
  read rules for them. A program uses an API key ([publishing a REST API (app.Apis)](https://osysharp.com/reference/api/rest/)).
- **Rows, not a stream.** A `stream<T>` function yields items one by one; it is an ordinary event-stream endpoint, not
  a live one.

### What it costs   {#costs}
A change is built from the commit's row in memory when the row carries everything the answer shows. `osy check` lists
each live endpoint and names what costs more:

- **a fill**: a column a commit does not carry (a `Json` value, a text that may be longer than 256 characters) costs
  one read per commit for each group of readers bound to the same rules;
- **a row read**: a computed member, a classified column, a field rule decided per row, a read rule that reaches
  through a reference (`where Taker.Email == user.Email`), or a filter or order on a column a change cannot decide (a
  date) has the server read the changed row for each reader.

`osy model --json` gives each live endpoint `"live": true` and a `liveQuery` with its `entity`, `filter`, `orderBy`,
`limit` and these `costs`.

### Serving it   {#serving}
A program holds a live endpoint open with a GET that asks for an event stream, with its API key:
`GET /api/rest/v1/<route>/<path>?<args>` with `Accept: text/event-stream` and `X-API-Key`. The same GET without that
`Accept` header is an ordinary call, answered with the rows once, as any endpoint is.

The function's arguments travel in the path (`Path = "/work/{host}"`) or the query string (`/work?host=build-1`), which
binds a GET's parameters by name ([[api-rest#query-string]]). A query string name the function does not take is
refused with `400`, as an unknown body field is.

- [Osy.Client — hold a live endpoint open from a .NET program](https://osysharp.com/reference/api/live-sdk/) — how a .NET program holds one

**At open.** The stream opens for the caller the key belongs to, as any REST call does. The function's `[Authorize]`
and its arguments are checked and bound as a call's are. A refusal comes before the stream opens, as the ordinary REST
answer with its error body: `403` for a caller with no account of the app or one `[Authorize]` refuses, `400` or `404`
for an argument that does not bind, `429` with `Retry-After` past the limit below, and `503` with `Retry-After: 1` from a
server that is stopping.

**Where it reads.** The stream is held in the environment its GET was made in: on `<slug>--<env>` (and on a zone, where
every request names its environment) it hears only that environment's commits, and every read for it is made in that
environment's database under the caller's roles there. A preview key's stream never hears a production commit.

**The frames.** Server-Sent Events, each frame flushed as it is written. Rows are flat, with their `id` and their columns
named as the REST answer names them:

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

id: 0.3f9a1c07d2b84e61
event: snapshot
data: {"rows":[{"id":"7c1e…","label":"Box of tiles","priority":2,"delivered":false}],"position":0}

: hb

id: 41.9be04c2a1d7f3358
event: delta
data: {"upserts":[{"id":"7c1e…","label":"Box of tiles","priority":5,"delivered":false}],"removed":[],"position":41,"at":"2026-11-23T10:15:02Z"}

event: ended
data: {"code":"unavailable","message":"This server is stopping. Reconnect, and another server holds the stream."}
```

- **`open`**: the first frame, with the heartbeat period in seconds.
- **`snapshot`**: the whole answer, read as the caller. It is sent at open and whenever the server reads the query
  again: when a role grant of the caller is written or revoked (rows they may no longer read are gone from it), when a
  change could not be built from the commit or could bring in a row past the `Take` bound, and when the stream has fallen
  more than 256 commits behind. Before each read, the open's first read included, the function's `[Authorize]` is asked
  again for the caller as they are now; when a GET would now answer `403`, the stream ends `denied` instead. A change to
  a row the gate's policy reads wakes the stream too, as a role grant does: closing the caller's shift under
  `[Authorize(IsOnShift)]` ends it `denied` ([when is who, where is which rows](https://osysharp.com/reference/security/when-and-where/)).
- **`delta`**: the rows a commit changed, built from the commit. A column the commit could not carry is named in the
  frame's `missing` map (`{"<id>":["column",…]}`), never in the row; the `delta-fill` after it brings the value.
  `removed` names only rows the stream sent: a commit of rows the caller was never shown sends nothing.
- **`delta-fill`**: `{rows, removed}`, the missing columns of rows already sent.
- **`same`**: only an id (see resume below).
- **`ended`**: `{code, message}`, then the stream closes. `denied` means the key no longer holds the stream: it was
  revoked or replaced, or its holder was switched off, or the function's `[Authorize]` no longer lets its caller in. The
  stream is told as soon as that change is written, on whichever server holds it. Do not reconnect with the same key.
  `invalid` means the answer grew past what one stream may hold (below); `not-found` that an argument no longer binds.
  Neither is retried. `unavailable` means reconnect: the server is stopping, the app has
  a new version, or the sign-in could not be checked just now. `fault` means the stream failed on the server. If the
  `ended` frame cannot be written within a second or two, the server closes the stream without it.
- **`: hb`**: a comment line every 20 seconds, so a program can tell a quiet stream from a dead one.

Each `snapshot`, `delta` and `delta-fill` has an id, `{position}.{hash}`. The position is the app's own commit position (0
before the app's first counted commit). The hash is 16 hex characters over the answer sent; it is kept as rows change,
so a frame costs the rows it carries, not the whole answer.

**Resume.** A reconnect that sends `Last-Event-ID: {position}.{hash}` is read once, as an open is. If the answer has that
hash, the stream sends `same` (only an id) and no rows. Otherwise it sends a snapshot. An id the server cannot read counts
as no id.

**Limits.** One key's principal holds at most **4** live streams on one server; the fifth is answered `429` with
`Retry-After: 30`. A reconnect is the exception: when it resumes one of the key's own streams on that server (the same
endpoint and arguments, and a `Last-Event-ID` that stream sent), it takes that stream's place, and the old stream ends
with `unavailable`. A client whose connection dropped without closing (its network gone) never hangs up, so its old
stream would otherwise keep the place for minutes. One stream holds at most one answer: about 2 MB of rows, measured as the stream sends them (the REST
answer's form, where an enum is its member's name). An answer that is cut there at open, that is larger than that in the
stream's form, or that commits or their `delta-fill`s grow past it, ends the stream `invalid` with the reason; add a
`.Take(n)` to the query, or narrow its filter. An open stream holds no admission ticket or request slot while it is idle. Only its open read is
admitted, as a call is. Its work, the matching of each commit included, is metered under the endpoint's function. MCP hosts keep their own watch
([[config-mcp-server#watch]]).

## Examples       {#examples}

```osy title="A worker hears about waiting parcels instead of polling" test app=api-live-endpoints
[Role] enum AppRole { Authenticator }

[Principal] entity Worker {
  [Unique, MaxLength(200)] string Email;
  [MaxLength(200)] string PasswordHash;
  [MaxLength(255)] string? ApiKeyHash;
  [MaxLength(255)] string? ApiKeyHash2;
  security {
    allow read when IsAuthenticated;
    allow read, create when IsAuthenticator;
    deny read PasswordHash when !IsAuthenticator;
    deny read ApiKeyHash when !IsAuthenticator;
    deny read ApiKeyHash2 when !IsAuthenticator;
  }
}
[RoleGrant] entity RoleGrant { [Required] Worker Member; [Required] AppRole Role; }
policy IsAuthenticator => RoleGrant.Any(g => g.Member == user && g.Role == AppRole.Authenticator);
[AuthMethod] void SignIn(string email, string password) { }

entity Parcel {
  [MaxLength(200)] string Label = "";
  int Priority;
  bool Delivered;
  Worker? TakenBy;
  security { allow read when IsAuthenticated; }
}

/// The parcels no worker has taken yet, most urgent first: one query, so each change is built from the commit.
List<Parcel> Waiting() => Parcel.Where(p => !p.Delivered && p.TakenBy == null).OrderByDescending(p => p.Priority).Take(100).ToList();

app.Apis = [
  new RestApi("Workers") {
    Route = "workers",
    Auth  = new ApiAuth { ApiKey = true },
    Endpoints = [
      new Endpoint(Waiting) { Path = "/waiting", Live = true },
    ],
  },
];
app.AuthBootstrap = new AuthBootstrap { Role = AppRole.Authenticator, Login = SignIn };
```

## See also       {#see-also}
- [[testing-api-calls#live]] — `Api.Live`: holding a live endpoint from a test, and reading what it sent
- [publishing a REST API (app.Apis)](https://osysharp.com/reference/api/rest/) — publishing endpoints, API keys, who `user` is on a call
- [The reactivity & lifecycle model](https://osysharp.com/reference/ui/reactivity/) — `live var`, a page's live query, which a live endpoint gives a program
- [Osy.Client — hold a live endpoint open from a .NET program](https://osysharp.com/reference/api/live-sdk/) — how a .NET program holds one
- [MCP tool server (app.McpServer)](https://osysharp.com/reference/config/mcp-server/) — an agent's `watch` over MCP
