Overview
Tablebox is a base on which the people in one room exchange values, records, files, and camera, microphone and screen, in real time. A Tablebox Relay carries what they exchange: a server that relays it with MoQ (Media over QUIC). Apps connect to it from browsers and Node with the SDK, the npm package tablebox.io.
Tablebox's servers keep no data. What someone publishes reaches the others while they are connected, and it is gone once they leave.
Follow Get started: install the CLI and run tablebox init in your app's folder, which needs no account. Console shows the projects you own once you sign in with GitHub.
This page says how Tablebox behaves. Get started gives the steps, and Reference the calls, commands, codes and values. Every page is also plain Markdown at its address with .md appended, such as start.md, and index.md for this one, and llms.txt lists the pages, with how to start, for AI.
Words
| Word | Meaning |
|---|---|
| Room | A path such as boards/42. Nobody creates or deletes it: those who connect at the same path are together |
| ID | Who someone is in the room, connection.id: each tab's own, after the user and ~ when a backend signed the token |
| Name | What each person publishes under in a room, such as pointer or call |
| Project | What your app's keys, tokens, limits and usage belong to. tablebox init makes a temporary one with no account, which is deleted 72 hours later unless a person claims it (Projects, owners and keys) |
| Token | A pass signed with a key of the project: the rooms it lets in, whether it may publish there, and the user when a backend signed it. A token with no user may sit in a page |
| Key | A key pair whose private key signs tokens. It is made where it is used, by the CLI in your app's folder, and the Relays keep only its public key. The folder's key, TABLEBOX_KEY in .env.local, is the only secret your app holds, and goes in no page |
Connecting
A connection is in one room. connect(token, { room }) connects to room, which the token must let in; a token a backend signs names its room already. Moving to another room is connecting there and then closing the old connection, and being in two rooms at once is two connections. A connection reads its own room only: nothing published in a room above or below it reaches it, and it is told of nothing outside it. So a room whose name nobody can guess, such as one named after a random UUID, is open only to those who have its link. A room lives on no one server: its people may be on any Relays and read each other as on one, and Relays are added and removed with no change to your app.
connect() resolves without waiting for the connection, with connection.id set. Status changes come through onStatus. When the connection drops, the SDK connects again by itself, publishes again what was published and reads again what was read (Disconnects and departures). close() leaves the room.
With a token for pages. The token tablebox init prints, and those tablebox token prints, carry no user, so they may sit in a page. Whoever loads the page has the token and enters the rooms it lets in, up to the project's limits, each tab with an ID of its own. The SDK keeps a random secret for each tab in its sessionStorage, from which the Relay makes the tab's ID: a reload keeps the ID, another tab gets another, and nobody can take someone else's. A duplicated tab copies sessionStorage, so the two tabs share one ID. In Node, each connect() gets a new ID. The ID tells nothing of who entered: to know that, use a backend.
The secret the SDK sends, made from the tab's, goes in the connection's URL with the token, and a browser's developer tools show the URL when a connection fails. Whoever has both connects as that ID, so keep them out of what you share, such as bug reports.
The token tablebox init prints enters any room a page names, and publishes there. Use it for trying. Whoever loads a page has its token, so a room a backend guards must lie outside the rooms of every token for pages: an app with such rooms runs tablebox key, which replaces the folder's key and so stops init's token with every other token of the old key, and gives its pages narrower tokens made after it with tablebox token --room (Reference), or none.
With a backend, the page passes connect a function in place of the token. The SDK calls it before every connection attempt, reconnecting too, so each attempt has a fresh token. If its first call throws, connect() fails; if a later call throws, the SDK tries again after a wait. The backend signs a token for one user and one room with the folder's key, and each tab's ID begins with that user (Tokens and rights). Get started has a backend and a page that asks it.
Publishing and reading
In a room, each person publishes under names. Reading a name gives everyone's, one's own too, each with the ID of who published it, which nobody can fake: the Relay lets each connection publish only at its own ID. To read one person alone, pass { from: their ID } last to subscribe: nobody else's is received or counted. One's own arrives where it is, without the network, and is not counted in the transfer. A subscribe never calls its callback before it has returned. The name and the content are the publisher's: anyone may publish the same name.
Who is here is who publishes: what State.subscribe and Media.subscribe return map each of them to what they publish, and someone who only reads is not in it.
There are four kinds. Someone who comes later gets each person's value now (State), each person's newest records (Log), each person's picture and sound now (Media), and the files that someone still shares (Files).
This page, on which everyone sees each other's pointer and adds lines to a chat, uses the first two. It connects as the page of Get started does:
// Shows a board where everyone who opens the page sees the others: each person's pointer, a value
// they replace (State), and the lines they add to a chat (Log), each with the ID of who sent it.
//
// The board is named after `#` in the address, a new one when there is none, and the page connects
// with the token `tablebox init` printed, as page.ts does. A person's dot goes once they leave, and
// someone who comes later gets each person's newest lines.
import { connect, Log, State } from 'tablebox.io';
if (!location.hash) location.hash = crypto.randomUUID();
const connection = await connect('…the token init printed…', { room: `boards/${location.hash.slice(1)}` });
const pointer = State.publish(connection, 'pointer', { x: 0, y: 0 });
addEventListener('pointermove', event => pointer.set({ x: event.clientX, y: event.clientY }));
const dots = new Map<string, HTMLElement>();
State.subscribe<{ x: number; y: number }>(connection, 'pointer', (id, at) => {
let dot = dots.get(id);
if (!at) return void (dot?.remove(), dots.delete(id));
if (!dot) {
dot = document.body.appendChild(document.createElement('b'));
dot.textContent = '•';
dot.dataset.id = id;
dots.set(id, dot);
}
dot.style.cssText = `position: fixed; left: ${at.x}px; top: ${at.y}px`;
});
const chat = Log.publish<string>(connection, 'chat');
const input = document.body.appendChild(document.createElement('input'));
input.addEventListener('change', () => {
chat.append(input.value);
input.value = '';
});
Log.subscribe<string>(connection, 'chat', ({ id, value }) => {
document.body.appendChild(document.createElement('p')).textContent = `${id}: ${value}`;
});The Node samples below run in the room rooms/lobby, as Running the samples says.
State
State.publish(connection, name, value) publishes a value. set on what it returns replaces it, and close() withdraws it. State.subscribe(connection, name, (id, value) => …) reads everyone's values: what it returns is a Map from ID to value. Once a person leaves or withdraws theirs, their value turns undefined. Call its close() to stop reading.
// Shows how a program takes part in a room: it publishes its status there every second, for
// everyone in the room to read.
//
// Publishes the state `status` in the room rooms/lobby, as the user named on the command line.
import { connect, State } from 'tablebox.io';
import { sign } from 'tablebox.io/server';
const user = process.argv[2] ?? 'alice';
const connection = await connect(() => sign(process.env.TABLEBOX_KEY!, { user, room: 'rooms/lobby' }));
let count = 0;
const status = State.publish(connection, 'status', { online: true, count });
setInterval(() => status.set({ online: true, count: ++count }), 1_000);This sample reads everyone's status, or one person's with { from }. It publishes nothing, so it is in no one's list:
// Shows how a program follows a room: everyone who publishes a status there, and each status as it
// changes; or, given an ID, that person's alone.
//
// Reads the state `status` in rooms/lobby, as status.ts publishes it, as the user `watcher`, who
// publishes nothing.
import { connect, State } from 'tablebox.io';
import { sign } from 'tablebox.io/server';
const from = process.argv[2];
const connection = await connect(() => sign(process.env.TABLEBOX_KEY!, { user: 'watcher', room: 'rooms/lobby' }));
const statuses = State.subscribe<{ online: boolean; count: number }>(connection, 'status', (id, status) => {
console.log(`${id}: ${JSON.stringify(status) ?? 'gone'}`);
console.log(`here: ${[...statuses.keys()].join(', ')}`);
}, from ? { from } : undefined);Log
Log.publish(connection, name) returns something whose append adds a record. Log.subscribe(connection, name, record => …) gets each record that arrives once: { id, at, value }, where id is who added it and at is when, by their clock, in ms since the epoch. The records of what it returns hold each person's newest records, in the order of at (how many). An older record leaves records once its writer's window moves past it, so to keep everything, keep each record as it arrives. What a person had when they left stays. Call close() to stop reading. What a log keeps goes again to everyone reading it when its writer adds a record after a pause, so keep records small.
// Shows how a program chats in a room: each line typed is added to its log, and everyone's lines
// are printed as they come, with who added them.
//
// Chats in rooms/lobby with the log `chat`, as the user named on the command line.
import { createInterface } from 'node:readline';
import { connect, Log } from 'tablebox.io';
import { sign } from 'tablebox.io/server';
const user = process.argv[2] ?? 'alice';
const connection = await connect(() => sign(process.env.TABLEBOX_KEY!, { user, room: 'rooms/lobby' }));
const chat = Log.publish<string>(connection, 'chat');
Log.subscribe<string>(connection, 'chat', record => console.log(`${record.id}: ${record.value}`));
for await (const line of createInterface({ input: process.stdin })) chat.append(line);Media
Media has the same form as State. Media.publish(connection, name, stream) sends a MediaStream the app opened, as getUserMedia or getDisplayMedia gives it: its first live video track and its first live audio track, either of which may be missing, so getUserMedia({ audio: true }) sends a microphone alone. set(stream) sends another in its place at once, and close() stops sending.
The SDK sends a copy of each track and never stops the app's own, and it follows the stream within a second: a track the app adds with addTrack is sent, one it takes out with removeTrack is not, and track.stop() turns a camera or microphone off and stops sending it. A microphone's enabled = false sends silence in its place, and true brings its sound back, within a second too. To turn a camera or screen off, stop its track or take it out of the stream: in Safari and Firefox a picture does not follow enabled. applyConstraints on the app's track does not reach the copy. A track the browser ends on its own, such as when the person stops sharing their screen from the browser, stops at once. When a track sent stops, the stream's next live track of its kind is sent in its place.
Media.subscribe(connection, name, (id, stream) => …) gets everyone's MediaStream, one's own too (the tracks one sends). Each person's stream holds the tracks they send now, and a new MediaStream comes each time those change. When a sender stops one track, with track.stop() or from the browser, or takes it out of the stream, the callback gets a new stream without it; when they stop the last one, call close() or leave, it gets undefined. So a screen shared alone gives undefined once its sharing stops, and a camera and microphone whose video track is stopped give a stream with the sound alone. close() on what subscribe returns stops reading and calls back nothing, so remove the elements of those it read yourself, and their sound stops.
Media.show(element, stream, { muted }) shows a stream in a <video> or <audio>: the element plays its picture, muted, at once, and the page plays someone else's sound through an AudioContext of its own, at once where the page may play sound, else from the person's first click, tap or key press in the page. One's own stream, and any stream the app made itself, plays without sound. muted: true keeps someone silent while they are shown, and undefined empties the element and stops the sound it played. A person sounds while any element shows their stream without muted, so mute them, or show undefined, in each element that shows them. A person's sound stops by itself when their stream ends, so removing their element is all a page does. Taking an element off the page while its stream goes on does not stop the sound: show it undefined first. An element's own volume and muted change nothing, since it plays no sound. A click inside an iframe does not count for the page around it, and a page inside an iframe gets sound only from a click inside it. A page that asks the person to click for sound can tell whether they have: navigator.userActivation.hasBeenActive stays false until then.
In most browsers a person's own page needs that click too before they are heard, since they run a page's microphone only then; Chrome runs it, and plays the page's sound, at once on a page that captures the camera or microphone (getUserMedia). In both, the audio track enters the stream the others get once it runs. It is silent for a moment after it enters, and nothing marks the first sound. A person newly heard sounds about 0.1 s after the subscription on a page that sends its microphone or is cross-origin isolated, and about 0.2 s on other pages, where the browser's console says so once ([audio] SharedArrayBuffer unavailable, …).
Media that nobody subscribes to is neither delivered nor counted in usage. So to hear only the people near you, subscribe to each of them with { from: their ID } and close it when they go: subscribing to everyone and showing them with muted, or removing their element, still receives and decodes everyone. A voice subscribed again takes 0.1 to 0.2 s to sound, so on this floor, where each person sends their microphone alone, the page reads each person within 200 of it and plays those within 150:
// Shows how a web page hears only the people near it on a floor: each person sends their
// microphone alone and publishes where they are, and the page reads the voice of each person within
// 200 of it, one subscription per person, and nobody else's.
//
// Within 150 a voice plays; between 150 and 200 it stays read but shown with `muted`, so that
// someone who comes within 150 sounds at once (a voice read again takes 0.1 to 0.2 s to sound). A
// voice is closed once its person goes beyond 200 or leaves, which stops its sound, and its <audio>
// goes.
import { Media, State, type Connection } from 'tablebox.io';
/** A place on the floor. */
export type Place = { x: number; y: number };
const HEARD = 150;
const READ = 200;
export async function hearNearby(connection: Connection, start: Place) {
Media.publish(connection, 'voice', await navigator.mediaDevices.getUserMedia({ audio: true }));
let here = start;
const place = State.publish(connection, 'place', here);
/** The voices read: each person's subscription, its <audio> and their latest stream. */
type Voice = { streams: Media.Streams; audio: HTMLAudioElement; stream?: MediaStream };
const voices = new Map<string, Voice>();
const close = (id: string) => {
const voice = voices.get(id);
if (!voice) return;
// Closing calls back nothing and stops the voice's sound, so the page removes the <audio> itself.
voice.streams.close();
voice.audio.remove();
voices.delete(id);
};
const places = State.subscribe<Place>(connection, 'place', () => hear());
function hear() {
for (const [id, at] of places) {
if (id === connection.id) continue;
const away = Math.hypot(at.x - here.x, at.y - here.y);
if (away > READ) {
close(id);
continue;
}
let voice = voices.get(id);
if (!voice) {
const audio = document.body.appendChild(document.createElement('audio'));
audio.dataset.id = id;
const one: Voice = {
audio,
streams: Media.subscribe(connection, 'voice', (_, stream) => {
one.stream = stream;
hear();
}, { from: id }),
};
voices.set(id, (voice = one));
}
Media.show(voice.audio, voice.stream, { muted: away > HEARD });
}
// Those who left, or withdrew their place.
for (const id of voices.keys()) if (!places.has(id)) close(id);
}
return {
/** Moves this person on the floor. */
move(to: Place) {
here = to;
place.set(here);
hear();
},
};
}Browsers sound a limited number of AudioContexts at once: Chrome 50, across all the tabs of the browser. A page that hears anyone uses one, however many it hears, and one more while it sends its microphone; its elements play no sound.
Media works in browsers only, and in Node the calls throw. Media counts in the project's transfer too, and far more than data (Reference). Browsers without WebCodecs audio use three more files, which the SDK's package carries (Reference).
Files
await Files.publish(connection, file) returns ref and close(). Pass ref along, in a record or a value, and whoever gets it fetches the file with Files.fetch(connection, ref). It comes from anyone who shares the same content, and only while someone does (how long it waits). The SDK checks the content against its hash. The name and type in ref are what the sharer said, so do not open HTML or SVG inside your page.
// Shows how a program shares a file in a room and fetches the files the others share there: it
// shares its file and adds the file's reference to the log `files`, and fetches each reference the
// others add, from whoever shares that file.
//
// Shares the file named on the command line in rooms/lobby, as the user named before it.
import { openAsBlob } from 'node:fs';
import { basename } from 'node:path';
import { connect, Files, Log } from 'tablebox.io';
import { sign } from 'tablebox.io/server';
const [user = 'alice', path = 'notes.txt'] = process.argv.slice(2);
const connection = await connect(() => sign(process.env.TABLEBOX_KEY!, { user, room: 'rooms/lobby' }));
const shared = await Files.publish(connection, new File([await openAsBlob(path)], basename(path)));
const refs = Log.publish<Files.FileRef>(connection, 'files');
refs.append(shared.ref);
Log.subscribe<Files.FileRef>(connection, 'files', async ({ id, value: ref }) => {
if (id === connection.id) return;
try {
const blob = await Files.fetch(connection, ref);
console.log(`fetched ${ref.name}: ${blob.size} bytes`);
} catch (error) {
console.log(`${ref.name}: ${(error as Error).message}`);
}
});Sizes and names
A value or a record is JSON, up to a size (Reference). Over it, set and append throw, and what is published stays as it was. One connection publishes a name of a kind once at a time: close it before publishing it again. What a name and a room may be is in Reference.
Large rooms
Where everyone reads everyone, each person receives what everyone sends, so a room holds hundreds. Past that, a room is read by area: each person publishes under the name of the area they are in and reads the areas near them, and of each area farther off a summary that someone present there publishes. What a person receives then follows what is around them, not how many are in the room. The areas are names in one room, so moving between them changes only what is read. The service does not merge or thin what it carries: the people present sum each area up.
In this hall, each area is a square of 400 px:
// Shows a hall of thousands read by area: each person publishes where they are under the name of the
// 400 px square they stand in, and reads everyone in the nine squares around them. Of each square
// farther off, up to three away, they read only a summary, which the person with the lowest ID in
// that square publishes; when that person leaves, the next lowest takes it on. What a person receives
// follows what is around them, not how many are in the hall.
//
// The hall is named after `#` in the address, hall 1 when there is none, and is larger than the
// window. The page shows each person it reads as a dot, and each summary as the number of people in
// its square, at their average place.
import { connect, State } from 'tablebox.io';
type At = { x: number; y: number };
type Summary = At & { count: number };
const connection = await connect('…the token init printed…', { room: `halls/${location.hash.slice(1) || '1'}` });
document.body.style.cssText = 'width: 8000px; height: 8000px';
const square = (at: At, dx = 0, dy = 0) => `${Math.floor(at.x / 400) + dx}_${Math.floor(at.y / 400) + dy}`;
/** The squares up to `r` away, its own too. */
const around = (at: At, r: number) =>
Array.from({ length: (2 * r + 1) ** 2 }, (_, k) => square(at, (k % (2 * r + 1)) - r, Math.floor(k / (2 * r + 1)) - r));
/** What the page shows of each name it reads: an element for each person or summary. */
const shown = new Map<string, Map<string, HTMLElement>>();
function draw(name: string, id: string, value: At | Summary | undefined) {
let elements = shown.get(name);
if (!elements) shown.set(name, (elements = new Map()));
let element = elements.get(id);
if (!value) return void (element?.remove(), elements.delete(id));
if (!element) {
element = document.body.appendChild(document.createElement('b'));
Object.assign(element.dataset, { name, id });
elements.set(id, element);
}
element.textContent = 'count' in value ? String(value.count) : '•';
element.style.cssText = `position: absolute; left: ${value.x}px; top: ${value.y}px`;
}
let me: At = { x: 0, y: 0 }, sent: At | undefined, mySquare = square(me);
let mine = State.publish(connection, `area_${mySquare}`, me);
let summary: State.Published<Summary> | undefined; // my square's, while I sum it up
const reading = new Map<string, State.Values<At | Summary>>();
addEventListener('pointermove', event => (me = { x: event.pageX, y: event.pageY }));
setInterval(() => { // at most five times a second
if (me === sent) return;
sent = me;
if (square(me) === mySquare) mine.set(me);
else { // into another square
mine.close(); summary?.close(); summary = undefined;
mySquare = square(me); mine = State.publish(connection, `area_${mySquare}`, me);
}
const near = around(me, 1);
const wanted = new Set([...near.map(s => `area_${s}`), ...around(me, 3).filter(s => !near.includes(s)).map(s => `summary_${s}`)]);
for (const [name, values] of reading) {
if (wanted.has(name)) continue;
// Closing calls back nothing, so the page takes away what it showed of that name itself.
values.close();
reading.delete(name);
for (const element of shown.get(name)?.values() ?? []) element.remove();
shown.delete(name);
}
for (const name of wanted) if (!reading.has(name)) reading.set(name, State.subscribe<At | Summary>(connection, name, (id, value) => draw(name, id, value)));
}, 200);
setInterval(() => { // once a second, the lowest ID here sums the square up
const here = [...(reading.get(`area_${mySquare}`) ?? [])] as [string, At][];
if (here.map(([id]) => id).sort()[0] !== connection.id) return void (summary?.close(), (summary = undefined));
const value = { count: here.length, x: here.reduce((s, [, at]) => s + at.x, 0) / here.length, y: here.reduce((s, [, at]) => s + at.y, 0) / here.length };
if (summary) summary.set(value); else summary = State.publish(connection, `summary_${mySquare}`, value);
}, 1000);Keeping what someone left, editing one thing together
To keep what someone who left published, or to edit one thing together, such as a whiteboard, those present read it and publish it again as their own. How it merges is up to the app, or a library above it. In this sample Yjs merges it, and each person publishes the document they hold as State:
// Shows how the people of a room edit one document together, with Yjs merging it: each publishes the
// document they hold as State, again whenever it changes, and merges in everyone else's. It prints
// the text whenever it changes.
//
// Edits the text of the document `doc` in rooms/lobby as the user named on the command line, putting
// the words after the name at its start. Needs the yjs and lib0 packages (npm install yjs lib0).
import { fromBase64, toBase64 } from 'lib0/buffer';
import { connect, State } from 'tablebox.io';
import { sign } from 'tablebox.io/server';
import * as Y from 'yjs';
const [user = 'alice', ...words] = process.argv.slice(2);
const connection = await connect(() => sign(process.env.TABLEBOX_KEY!, { user, room: 'rooms/lobby' }));
const doc = new Y.Doc(); // what everyone edits; Yjs holds how it merges
const encode = () => toBase64(Y.encodeStateAsUpdate(doc));
const mine = State.publish(connection, 'doc', encode());
// What this person holds (what it merged from the others too), published again on each change.
doc.on('update', () => mine.set(encode()));
// The others' documents, merged into this one.
State.subscribe<string>(connection, 'doc', (id, state) => {
if (id !== connection.id && state) Y.applyUpdate(doc, fromBase64(state));
});
const text = doc.getText('text');
text.observe(() => console.log(`text: ${text.toString()}`));
if (words.length > 0) text.insert(0, `${words.join(' ')} `);When you write the merge yourself, make it give the same result whoever's is merged, however many times and in whatever order. Everyone reads everyone's and publishes the whole again each time, so the transfer grows with the number of people and the size of the document. To keep it after everyone has left, run your app's server as a participant and let it save.
For what must be right, such as a game's result, let your app's server publish it as a participant, and let everyone read it with { from: the server's ID }.
Tokens and rights
Every token reads its room. A token with publish also publishes there, each name at {kind}/{name}/{the connection's ID} and nowhere else. Publishing with a token that only reads is not an error, and reaches no one. Everyone in the room sees each person's ID. A token carries only the claims Reference lists.
A token for pages has no user and needs no end, and the CLI's have none. tablebox token --room 'shows/*' prints one for the rooms one segment below shows/, reading only, and --publish adds publishing. It admits until its key is deleted or its room is closed. tablebox init and tablebox token sign with the folder's key, and nothing keeps a list of tokens, so one token cannot be stopped alone: tablebox key replaces the folder's key and deletes the old, which stops every token the old key signed and closes the connections they admitted.
A backend's token has a user, whom your backend checked (Get started). sign of tablebox.io/server signs one for one user and one room, publishing there, for 10 minutes. Its end is checked only when a connection is admitted, so a connection carries on past it, and the function connect takes gives the next attempt a fresh token. It cannot be stopped alone either: it ends at its exp, and remove turns its user out (Removals and closings).
Removals and closings compare when a token was issued (Removals and closings).
One to many
One person broadcasts and everyone else watches, with two tokens and no backend. Each viewer is one of the project's connections, and what each receives counts in its bytes (Limits and usage). The viewers' token only reads, so a viewer cannot pose as the broadcaster once no page carries a token that publishes in shows/, such as init's (Connecting). It lets in every show, shows/1, shows/2 and on: the page carries it in place of …the token that only reads…. The broadcaster's token may publish in one show, and goes in no page. In the app's folder, the first prints the viewers' token and the second the broadcaster's of show 1:
tablebox token --room 'shows/*'
tablebox token --room shows/1 --publishBundle stage.ts as Running the samples says. Viewers open stage.html#1, or stage.html#2 for show 2. The broadcaster opens stage.html#1:{token} with their token, and keeps that address to themselves, since whoever opens it may broadcast: the page publishes only when it was given a token after the show, which it takes out of the address bar. A reload therefore opens it as a viewer, and the broadcaster opens the link again.
// Shows one-to-many with no backend: the broadcaster sends their camera and microphone, and everyone
// else watches and listens, each person shown in a video of their own.
//
// The show is named after `#` in the address, show 1 when there is none. The page carries the token
// `tablebox token --room 'shows/*'` printed, which only reads, so a viewer sends nothing anyone
// gets. The broadcaster opens the page with a token that may publish after the show and `:`, as
// `stage.html#1:{token}`: it is in no page, so no viewer carries it. The page takes it out of the
// address bar once it has read it.
import { connect, Media } from 'tablebox.io';
const [show, broadcaster] = (location.hash.slice(1) || '1').split(':');
if (broadcaster) history.replaceState(null, '', `#${show}`);
const connection = await connect(broadcaster || '…the token that only reads…', { room: `shows/${show}` });
if (broadcaster) Media.publish(connection, 'stage', await navigator.mediaDevices.getUserMedia({ video: true, audio: true }));
const videos = new Map<string, HTMLVideoElement>();
Media.subscribe(connection, 'stage', (id, stream) => {
let video = videos.get(id);
if (!stream) return void (video?.remove(), videos.delete(id));
if (!video) {
video = document.body.appendChild(document.createElement('video'));
video.dataset.id = id;
videos.set(id, video);
}
Media.show(video, stream);
});A page that takes a token from its address trusts whoever made that link: it connects, and here sends the camera and microphone, wherever that token is for, another project or another service included. So the broadcaster opens only a link they made, or got from someone they trust.
Disconnects and departures
A person who closes the page leaves at once. One whose connection drops leaves once the connection has gone silent for a while (Reference). When someone leaves, the records already received stay. A person who connects again looks as if they left and came back, and when you connect again yourself, everyone else does. So does a reload, though the tab keeps its ID.
When the browser says it is back online, the SDK opens a new session while the old one still works, and moves to it once it is open, so others see nothing while the old path lasts.
The SDK connects again on its own, with waits that grow, and a refusal because the project is full or stopped is tried again after a wait. It stays closed, and does not connect again, only when the token is not valid, a token given in place of a function expired, the person was removed, the room was closed, or the project was stopped while they were connected. connection.reason says which (Close codes).
Other kinds of data
What State, Log, Media and Files do not cover, you can write yourself with connection.origin: the Origin of @moq/net, the official MoQ package Tablebox uses. Use the same @moq/net as the SDK's, with import { moq } from 'tablebox.io'. What you publish there is held to the same rights: broadcasts at {kind}/{name}/{your ID} in the room, with tracks of your own (Reference). A program in another language takes part the same way, with the official moq crates and the same tokens (Reference).
Management
Every Relay holds what a room needs: each project's name, limits and ceilings, the public keys of its keys, removals and closings, its usage this month and last, a temporary project's deletion time, and the list of Relays. Each Relay admits and delivers from what it holds, and asks no other server. Manager is the one way to change a project: every change, from the CLI, your backend, Console or the operator, is a call to Manager, which writes it to the Relays at that moment; a Relay's refusal, or no Relay answering, is that call's answer. Manager reads the projects and their usage from the Relays every 10 s. It keeps people and their GitHub sign-in, who owns which project, the operator's ceilings and suspensions, and usage per day. Manager is never on the path of what people exchange.
A call to Manager is made as a key of the project, with a management token that key signs (Reference), as tablebox claim, tablebox key, tablebox api and remove of tablebox.io/server do with the folder's key; or as a person, signed in to Console with GitHub, on a project they own.
Projects, owners and keys
tablebox init makes a temporary project, with no account: nobody owns it, its ceilings are small, and every Relay deletes it 72 hours after init, by itself, at that time: its connections close with path-closed, its tokens are refused with invalid-token, and its keys go. While Tablebox holds as many temporary projects as it takes, init answers that it is busy, and makes nothing.
A person keeps a temporary project by claiming it: tablebox claim in its folder prints an address on Console and a code that works for 15 minutes, or until Manager restarts, and the person opens it, signs in with GitHub and accepts (Get started). They become its owner, its deletion time is cleared, it gets an owned project's ceilings, and it counts against their ceiling of projects. The folder's key stays.
A project's owners are people, and every owner has the same rights: managing its keys, limits, removals and closings, its owners, and deleting it. An owner adds a person who has signed in to Console once, by their GitHub login or user ID, and removes an owner, with tablebox api (Get started). A project keeps at least one owner.
A key is an EdDSA (Ed25519) key pair, made in your app's folder by the CLI; Manager and the Relays get only its public key, and the Relay that takes it gives it its ID. A folder holds the project's key as TABLEBOX_KEY: tablebox init writes it, tablebox key replaces it. Deleting a key closes the connections its tokens admitted and stops every token it signed. A deleted key, like a deleted project, stays deleted.
Limits and usage
The operator sets ceilings: how many projects a person may own, and each project's monthly bytes and connections, small for a temporary project (Reference). Under them, you set a monthly byte limit (bytes in and out, over the UTC calendar month) and a connection limit, each at most the ceiling. A limit not set is the ceiling.
- Reaching the byte limit makes the project
stoppeduntil the month ends or the limit rises: every connection closes, and new ones are refused. - Reaching the connection limit makes it
fullwhile the count stays there: new connections are refused, and open ones continue. - A limit can be passed by what Relays carry in one 10-s count, plus the time a change takes to reach them.
Each Relay counts its usage per project and passes it on every 10 s, and a project's usage this month, which the byte limit is checked against, is the sum over every Relay (when it shows). Manager records it per project and UTC day: bytes into and out of Relays, and peak connections.
The operator can suspend a person. A suspended person's Console sessions end and signing in is refused. A project whose every owner is suspended is stopped; one with an owner who is not goes on as before. Once the operator lifts the suspension, the projects follow their limits again.
Removals and closings
Removing a user in a room turns out every tab of theirs in that room or a room below it, and from then on refuses there their tokens issued at or before the removal's second (iat is in seconds). Tokens issued in a later second are admitted, so your backend also stops signing for them. Removing a tab's ID does the same for that tab, and removing again moves the time forward. remove(key, { user, room }) of tablebox.io/server removes a user, with one call to Manager.
Closing a room does the same for everyone: every connection in it or in a room below it closes, and tokens issued at or before the closing's second are refused there. A connection in a room above it stays, so a lobby keeps running when one of its rooms closes. remove(key, { room }), with no user, closes a room. Deleting a project closes all its connections.
A token for pages was issued when it was made, so a tab removed, or everyone in a room closed, stays out with that token for good; a token made later lets them back in, since a reloaded tab keeps its ID. Removing cannot keep out someone with a page's token: they get a new ID by opening the page in another tab.
Removals, closings and other changes reach every Relay within a second, and take effect within 5 s.
While Manager is down
Rooms run: connections carry on, new ones are admitted, a backend's sign goes on, since it calls nothing, and the Relays delete temporary projects at their deletion time. Every change waits for Manager: tablebox init, claim, key and api, remove, so a removal waits too, and Console, owners, the operator's ceilings and suspensions, and the record of usage per day. Each such call fails while Manager is down (503 unavailable: Manager is not answering), and works when made again once it is back. tablebox token, ls, read and status need no Manager. Nothing the Relays hold is lost. Once Manager is back, it records what the Relays counted meanwhile, this month's on the day it reads it and last month's on that month's last day, none of it twice; the Relays keep last month's usage too, so a Manager down across the turn of a month loses none.