Open a connection
Keep a WebSocket open between an app and a luna, know who is connected, and run code as apps arrive and leave.
A call ends with its answer, so a luna cannot reach an app between calls or know who is still there. A connection keeps a WebSocket open between an app and one luna: calls and live queries travel over it, and the luna sees every app connected to it.
Open a connection
The luna type must be public, because apps connect with the publishable key. Hooks run as each app arrives and leaves.
import { defineLuna, t } from "luna";
export const Room = defineLuna({
name: "Room",
visibility: "public",
key: { id: t.string() },
hooks: {
onConnect(ctx, conn) {
console.log(`${conn.id} joined`);
},
onDisconnect(ctx, conn) {
console.log(`${conn.id} left`);
},
},
handlers: () => ({}),
});
In the app, connection() on a LunaHandle gives the connection to that luna. Subscribing to it opens the connection and keeps it open.
import { createClient } from "luna/client";
const client = createClient({ url: "<LUNA_URL>", key: "<LUNA_KEY>" });
const connection = client.luna("Room", "lobby").connection();
connection.subscribe(() => console.log(connection.status()));
A live query, a push listener or a call to the luna opens the same connection. The client carries every luna it uses over one WebSocket, which holds at most 256 lunas. Pass multiplex: false to createClient to give each luna a WebSocket of its own.
Follow the status in the app
status() returns a ConnectionStatus.
| Status | Means |
|---|---|
connecting |
The first attempt is under way |
open |
The luna accepted the connection |
reconnecting |
The connection dropped, and the client is trying again |
closed |
The luna refused it or closed it on purpose, or the client was closed |
The client reconnects by itself, waiting longer after each failure, up to 15 seconds. It subscribes its live queries again and keeps its push listeners. Each reconnect is a new connection to the luna, with a new id.
Say who is connecting
onBeforeConnect runs before a connection opens. It returns the caller’s identity, or refuses with ctx.fail.
onBeforeConnect(ctx, request) {
const name = request.query.name;
if (!name) ctx.fail("NoName");
return { name };
},
The client’s params adds query parameters to each new connection. It is asked again on every reconnect, so a token you refresh reaches the luna.
const client = createClient({
url: "<LUNA_URL>",
key: "<LUNA_KEY>",
params: () => ({ name: "ann" }),
});
The identity is conn.auth in the connection hooks, and ctx.caller.external in each call over the connection. The hook runs once per connection, not once per call over it. It also runs before every plain HTTP call to the luna type. A refused app’s calls and queries fail with the code given to ctx.fail, and the error’s status is 403.
Without the hook, every app with the key connects, and its identity is null. A name in the query proves nothing. Check who is calling verifies a token instead.
Run code as apps arrive and leave
onConnect runs after onBeforeConnect, with the new Connection. If it throws, the connection is refused.
onDisconnect runs when the app closes the connection or disappears. It runs at least once for each connection, so make it safe to run twice. An app that vanishes without closing, such as a phone that lost its network, is noticed within 45 seconds.
Tag connections and keep state
Tags group connections, so a push can reach some of them. State holds a little JSON with the connection.
onConnect(ctx, conn) {
const { name } = conn.auth as { name: string };
conn.tag("lobby", `user:${name}`);
conn.setState({ typing: false });
},
tag and untag return the connection’s tags, and conn.tags holds them. setState replaces the whole state, and conn.state reads it. A connection has at most 16 tags of 1 to 128 bytes each, and state of at most 64 KiB as JSON.
Find the luna’s connections
ctx.connections.list() returns every open connection, and { tag } keeps those with that tag. ctx.connections.get(id) returns one, and ctx.connection is the one the current call came over.
here: h({}, (ctx) => ctx.connections.list({ tag: "lobby" }).map((conn) => (conn.auth as { name: string }).name)),
Close a connection
conn.close(code, reason) closes a connection from the luna.
kick: h({ args: { name: t.string() } }, (ctx, { name }) => {
for (const conn of ctx.connections.list({ tag: `user:${name}` })) conn.close(4001, "removed");
}),
With code 1000, or 4000 to 4999, the app’s client does not reconnect. Its status becomes closed, and its live queries show the reason as their error. onDisconnect does not run for a connection the luna closed. A call still waiting on that connection gets its answer before the close.
Keep connections while the luna sleeps
Open connections do not keep a luna awake. When it sleeps, the connections stay open, and Luna keeps each one’s identity, tags and state. The next call, over a connection or not, wakes the luna, and ctx.connections lists them all again.
Send raw messages
connect from luna opens one connection without the client around it, for scripts and servers. It never reconnects. Its send delivers a raw message to the luna’s onMessage hook, which the client from createClient cannot do.
import { connect } from "luna";
const socket = connect("<LUNA_URL>", "/Room/lobby", { key: "<LUNA_KEY>", params: { name: "ann" } });
await socket.opened;
socket.send({ typing: true });
onMessage(ctx, conn, data) {
conn.setState(data);
},
Next steps
- Push to connected apps sends messages to the apps connected.
- Subscribe to a query keeps a result current over the connection.
- The life of a luna explains sleeping and waking.