Skip to content
Luna
Esc
↑↓navigate↵open⌘Jpreview
On this page

Follow a stream from an app

Read a luna's stream in an app from any offset, and follow new entries as they are appended.

A push reaches only the apps connected when it is sent, and a live query shows the current state, not what happened along the way. A stream keeps every entry at an offset, so an app can read the history and follow what comes next, from wherever it left off.

Read a stream in an app

The luna declares a stream and appends to it. Keep a stream covers streams and their retention.

import { defineLuna, stream, t } from "luna";

export const Room = defineLuna({
  name: "Room",
  visibility: "public",
  key: { id: t.string() },
  streams: {
    history: stream(t.object({ from: t.string(), text: t.string() }), { retention: { maxCount: 1000 } }),
  },
  handlers: (h) => ({
    say: h({ args: { from: t.string(), text: t.string() } }, (ctx, { from, text }) => {
      ctx.streams.history.append({ from, text });
    }),
  }),
});

In the app, stream on a LunaHandle names the stream. Subscribing reads it from the start, then follows new entries.

import { createClient } from "luna/client";

type Said = { from: string; text: string };

const client = createClient({ url: "<LUNA_URL>", key: "<LUNA_KEY>" });
const history = client.luna("Room", "lobby").stream<Said>("history");

const stop = history.subscribe(() => {
  const { entries, upToDate } = history.get();
  if (upToDate) console.log(entries.map((said) => `${said.from}: ${said.text}`));
});

Reading a stream neither wakes the luna nor keeps it awake, except to run onBeforeConnect, as Know who may read explains. Reading stops when the last subscriber calls the function subscribe returned.

Read the state

get returns a StreamState.

Field Holds
entries The data of the entries read, oldest first
offset Where reading continues from
upToDate true when the last read reached the end of the stream
error A ConnectionError when a read failed

Choose where to start

stream takes options as its second argument.

Option Does
offset "-1" from the start, the default. "now" from the next append. Or an offset that get().offset gave
limit The most entries to hold in entries, the newest ones. 1,000 by default

Save offset as the app reads, and pass it back later to carry on without reading anything twice.

const room = client.luna("Room", "lobby");
const fromNow = room.stream<Said>("history", { offset: "now" });
const resumed = room.stream<Said>("history", { offset: savedOffset });

limit only bounds what the app holds. The stream itself keeps entries as its retention says.

Show progress while a handler runs

An append to a stream is readable once the handler that made it ends well, and it goes if the handler fails. Declare the stream with live: true to make each append readable at once, while the handler still runs. A live append stays even if the handler fails later.

streams: {
  progress: stream(t.object({ done: t.int(), total: t.int() }), { live: true }),
},
moderate: h({ args: { texts: t.array(t.string()) } }, async (ctx, { texts }) => {
  for (const [i, text] of texts.entries()) {
    await fetch("<MODERATION_URL>", { method: "POST", body: text });
    ctx.streams.progress.append({ done: i + 1, total: texts.length });
  }
}),

The app follows progress from "now" and shows each entry as the handler goes. A deploy refuses to change a stream between live and not. Declare a new stream under another name instead.

Know who may read

An app reads with the publishable key, so the luna type must be public. If the type has an onBeforeConnect hook, the first read runs it, which wakes the luna that one time. The client then reads for an hour without running the hook again, and runs it once more after that.

A refused read sets error, and the client stops reading. Other failures, such as a luna that is busy, are retried, waiting longer after each one.

Read a stream over HTTP

Any HTTP client can read a stream with a GET to its path. The publishable key goes in luna-key or ?key=.

curl "$LUNA_URL/Room/lobby/streams/history?offset=-1&key=$LUNA_KEY"

The body is a JSON array of the entries’ data, at most 1,000 at a time. The stream-next-offset header says where to read next, and stream-up-to-date: true says the read reached the end.

Parameter Does
offset -1, now, or a stream-next-offset a response gave
limit The most entries to return, up to 1,000
live long-poll waits up to 20 seconds for an append, and answers 204 if none comes. sse keeps the response open as server-sent events

Next steps

Was this page helpful?