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

LunaHandle

One luna as an app sees it, with its live queries, writes, pushes, streams and queued writes.

A LunaHandle is one luna, from client.luna(type, ...key). Pass the luna type as a type argument to check handler names, arguments and results.

import { createClient } from "luna/client";
import type { List } from "../luna/lunas/list.ts";

const client = createClient({ url: "<LUNA_URL>", key: "<LUNA_KEY>" });
const list = client.luna<typeof List>("List", "groceries");

const items = list.query("all");
items.subscribe(() => console.log(items.get().data));
await list.mutate("add", { text: "milk" });

Reference

Methods

PropType
query(handler, args)?LiveQuery<R>

A live query of a query handler. Each new result reaches its subscribers.

TypeLiveQuery<R>
mutate(handler, args, opts)?Promise<R>

Calls a handler and resolves with its result. opts is MutateOptions.

TypePromise<R>
read(handler, args, opts)?Promise<R>

Calls a handler once, without following it. opts takes timeoutMs.

TypePromise<R>
response(handler, args, opts)?Promise<HttpResult>

Calls a handler that answers with a Response, and resolves with its status, headers and body. opts takes timeoutMs.

TypePromise<HttpResult>
iterate(handler, args, opts)?AsyncGenerator<T>

Yields what a streaming handler yields, as it yields it. opts takes an AbortSignal as signal.

TypeAsyncGenerator<T>
connection()?ConnectionHandle

The state of the connection to this luna.

TypeConnectionHandle
enqueue(handler, args, opts)?{ id: string; done: Promise<R> }

Queues a write that survives restarts. opts.optimistic names an update given to createClient.

Type{ id: string; done: Promise<R> }
on(push, fn)?() => void

Hears a push the luna sends its connected apps. Returns a function that stops it.

Type() => void
stream(name, opts)?StreamHandle<T>

Reads one of the luna's streams as it grows. opts is StreamOptions.

TypeStreamHandle<T>

LiveQuery

PropType
get()() => QueryState<R>

The latest state. The same object until something changes.

Type() => QueryState<R>
subscribe(fn)(fn: () => void) => () => void

Hears every change and keeps the query live. Returns a function that stops it.

Type(fn: () => void) => () => void

QueryState

PropType
status"loading" | "ready" | "error"

ready once there is data. error when the first run failed.

Type"loading" | "ready" | "error"
dataR | undefined

The confirmed result, with pending writes laid over it.

TypeR | undefined
errorConnectionError | undefined

The latest run's failure. data stays as it was.

TypeConnectionError | undefined
staleboolean

The connection dropped, or the result is one saved in the store, so data may be behind.

Typeboolean

MutateOptions

PropType
optimistic?(local: LocalStore) => void

Changes what queries show until the write is in. It must read and write only through local.

Type(local: LocalStore) => void
timeoutMs?number

How long to wait, including the wait to connect.

Typenumber
DefaultcallTimeoutMs

LocalStore

PropType
get(query)(query: LiveQuery<R>) => R | undefined

A query's value as of the writes before this one. undefined when it is not loaded.

Type(query: LiveQuery<R>) => R | undefined
set(query, value)(query: LiveQuery<R>, value: R) => void

Replaces what a query shows while this write is pending.

Type(query: LiveQuery<R>, value: R) => void
update(query, fn)(query: LiveQuery<R>, fn: (current: R) => R) => void

set from the current value. Does nothing when the query is not loaded.

Type(query: LiveQuery<R>, fn: (current: R) => R) => void

ConnectionHandle and ConnectionStatus

PropType
status()() => "connecting" | "open" | "reconnecting" | "closed"

The connection's state now.

Type() => "connecting" | "open" | "reconnecting" | "closed"
subscribe(fn)(fn: () => void) => () => void

Hears each change of state and keeps the connection open.

Type(fn: () => void) => () => void

StreamOptions

PropType
offset?string

"-1" reads from the start, "now" from the end, or an offset a read gave.

Typestring
Default"-1"
limit?number

The most entries to keep. The oldest go first.

Typenumber
Default1000

StreamHandle and StreamState

stream.get() returns a StreamState, and stream.subscribe(fn) hears new entries and keeps reading.

PropType
entriesreadonly T[]

What has been read, oldest first, at most limit of them.

Typereadonly T[]
offsetstring

Where reading goes on from.

Typestring
upToDateboolean

The last read reached the end of the stream.

Typeboolean
errorConnectionError | undefined

The last read's failure.

TypeConnectionError | undefined

Good to know

  • Without a type argument, any handler name and arguments are accepted, and results are any.
  • Everyone asking the same handler with the same arguments shares one live query, whatever order the arguments’ keys are in. A result equal to the last one does not reach subscribers.
  • A query nobody subscribes to stays live and cached for keepAliveMs, then ends.
  • A live query that a busy luna refuses with Unavailable, Overloaded, Timeout or OutcomeUnknown is asked again after 500 ms.
  • The writes of one connection run one at a time, in the order they were sent. A write whose connection drops fails with Closed, and may or may not have happened.
  • An optimistic update stays laid over until a live result that includes the write arrives, or until settleMs runs out after the write is answered. If the write fails, the update is removed and mutate rejects. An update that throws is dropped on its own.
  • read goes over the connection after the writes before it, so it sees every write this client already had answered.
  • A handler that answers with a Response gives its body to mutate and read. A status of 400 or above throws HttpError.
  • iterate sends one HTTP request. Breaking out of the loop stops the handler, and an error the handler raises after it started throws a ConnectionError.
  • stream reads over HTTP and never keeps the luna awake. A read refused with a status below 500, other than 429, stops reading and sets error.
  • enqueue needs a store. Each write goes once, with its id as its idempotency key, after the luna’s earlier queued writes. A lost connection or a busy luna sends it again with the same key, and a handler’s failure marks it failed.
  • A queued write refused for its sign-in, with Unauthorized, Unauthenticated, Forbidden, Denied, or a refusal with status 401 or 403, stops the queue until client.resumeWrites().
  • The done promise of a queued write already has a rejection handler, so leaving it unawaited is safe. client.writes() shows failures.

Examples

Follow a query without a framework

const items = list.query("all");
const stop = items.subscribe(() => {
  const { status, data, stale } = items.get();
  if (status === "ready") render(data ?? [], stale);
});

Call stop() when the view goes away.

Show a write at once

await list.mutate(
  "add",
  { text: "milk" },
  {
    optimistic: (local) =>
      local.update(items, (old) => [...old, { id: -1, text: "milk" }]),
  },
);

Read once without following

const now = await list.read("all", {}, { timeoutMs: 5000 });

Watch the connection

const conn = list.connection();
conn.subscribe(() => showOffline(conn.status() !== "open"));

Hear a push

The luna sends pushes with ctx.broadcast or conn.push. See Push to connected apps.

const room = client.luna("Room", "lobby");
const stop = room.on<{ text: string }>("said", (m) => console.log(m.text));

Read a stream as it grows

const said = room.stream<{ text: string }>("said", { offset: "now", limit: 100 });
said.subscribe(() => console.log(said.get().entries));

Queue a write that survives a restart

const { id, done } = list.enqueue("add", { text: "eggs" });

Read a handler’s Response

const board = client.luna("Board", "b1");
const res = await board.response("export", {});
console.log(res.status, res.headers.get("content-type"), res.body);

Read what a streaming handler yields

for await (const n of room.iterate<number>("count", { to: 3 })) {
  console.log(n);
}

Was this page helpful?