Connect to an outside WebSocket
Open a WebSocket from a luna to another service, handle each message in a handler, and reopen it when it closes.
A luna’s memory does not survive sleep, so a WebSocket kept in a variable is gone once the luna sleeps. ctx.sockets opens a WebSocket that Luna holds for the luna: it stays open while the luna sleeps, and each message from the other end runs one of the luna’s handlers.
Open a socket
ctx.sockets.open takes a ws:// or wss:// URL and the name of the handler that receives messages. It returns the socket, whose id names it from then on.
import { defineLuna, t, table } from "luna";
const FEED_URL = "<FEED_URL>";
export const Room = defineLuna({
name: "Room",
key: { id: t.string() },
schema: {
messages: table({ id: t.id(), text: t.string() }),
},
handlers: (h) => ({
follow: h({}, (ctx) => ctx.sockets.open(FEED_URL, { handler: "heard" }).id),
heard: h({ args: { socket: t.string(), data: t.json() } }, (ctx, { data }) => {
if (typeof data === "string") ctx.db.messages.insert({ text: data });
}),
}),
});
The socket opens once follow ends well. A handler that fails opens no socket and sends nothing on one.
Handle each message
Each message from the other end is a call to the socket’s handler, with two args.
| Arg | Holds |
|---|---|
socket |
The socket’s id |
data |
A text message as a string, or a binary one as { base64 } |
Messages run one at a time, in the order they arrived. A message to a sleeping luna wakes it.
Send and close
ctx.sockets.get(id) returns an open socket, and ctx.sockets.list() returns them all. send sends a text message, and turns an object into JSON. close closes the socket.
post: h({ args: { socket: t.string(), text: t.string() } }, (ctx, { socket, text }) => {
return ctx.sockets.get(socket)?.send({ type: "post", text }) ?? false;
}),
stop: h({}, (ctx) => {
for (const socket of ctx.sockets.list()) socket.close(1000, "done");
}),
send and close return false when the socket has already closed. What they do leaves once the handler ends well, as an open does. A message is at most 1 MiB, and a larger one fails send with Invalid.
Reopen a socket that closed
onClose names a handler that runs once when the other end or the network closes the socket. It gets the socket’s id, the close code and the reason. It does not run when the luna closes the socket itself.
follow: h({}, (ctx) => ctx.sockets.open(FEED_URL, { handler: "heard", onClose: "closed" }).id),
closed: h({ args: { socket: t.string(), code: t.int(), reason: t.string() } }, (ctx, { code, reason }) => {
console.log(`the feed closed: ${code} ${reason}`);
ctx.schedule({ after: "10s", handler: "follow" });
}),
A socket that cannot connect also closes this way, with code 1006 and the reason in reason. Opening gives up after 10 seconds. Schedule a handler covers ctx.schedule.
Send headers when opening
headers adds headers to the request that opens the socket, such as a token kept in a secret. The Host header comes from the URL and cannot be set.
ctx.sockets.open(FEED_URL, {
handler: "heard",
headers: { authorization: `Bearer ${ctx.env.FEED_TOKEN}` },
});
Store secrets shows how to set FEED_TOKEN.
Know what a luna may reach
- A URL that is not
ws://orwss://, or is longer than 2,048 characters, failsopenwithInvalid. So does a handler name the luna type does not have. - A luna has at most 64 sockets open at once. Opening one more fails with
Invalid. - Addresses Luna never lets a luna reach, such as loopback addresses, close the socket at once with code 1006.
- When any luna type in the app sets
internet: false, every socket of the app closes at once with code 1006.
Reach the internet explains which addresses are refused and what internet: false turns off.
Next steps
- Reach the internet covers
fetchfrom a handler and outbound rules. - Call another luna sends slow work on with
ctx.send. - Open a connection covers WebSockets that apps open to a luna.