october

@october1/client

A small client for one october tenant: GraphQL reads and writes, live queries, and sign-in by email code. No runtime dependencies; about 7 KB gzipped.

import { init } from "@october1/client";

const db = init({ url: "https://october.sombra.so", tenant: "shop" });
// same origin as the page: init({ tenant: "shop" })

// sign in
const { demoCode } = await db.auth.sendMagicCode({ email });
await db.auth.signInWithMagicCode({ email, code });

// read
const { products } = await db.query(`{ products(first: 20) { items { id name } } }`);

// write: every call carries an Idempotency-Key, so retries never write twice
await db.mutate(`mutation ($input: ProductCreateInput!) { createProduct(input: $input) { id } }`,
  { input: { name: "Lamp" } });

// live: the first result, then every change
const stop = db.subscribe(`{ products(first: 20) { items { id name } } }`, {}, ({ data, mine }) => render(data));

Without a bundler

A static page can load the copy your october server serves, which moves with that server:

<script type="module">
  import { init } from "https://october.sombra.so/october-client.js";
  const db = init({ url: "https://october.sombra.so", tenant: "shop" });
</script>

The page's origin must be allowed on the tenant (october origins) for its API calls, but the script itself loads from any origin. To pin a version, use npm, or an npm CDN such as https://esm.sh/@october1/client@1.1.0.

React

import { init } from "@october1/client/react";

const db = init({ tenant: "chat" });
const MESSAGES = `{ messages(first: 50) { items { id text createdAt } } }`;
const SEND = `mutation ($input: MessageCreateInput!) { createMessage(input: $input) { id } }`;

function Chat() {
  const { isLoading, error, data } = db.useQuery(MESSAGES);   // live: re-renders on every change
  const { user } = db.useAuth();
  const send = (text) => db.mutate(SEND, { input: { text } });
  if (isLoading) return <p>Loading…</p>;
  if (error) return <p>{error.message}</p>;
  return <UI messages={data.messages.items} canSend={!!user} onSend={send} />;
}
  • db.useQuery(doc, variables, { skip }) answers {isLoading, data, error, mine, basisT}. A null doc runs nothing. Components asking for the same query and variables share one live stream (the server allows a user 8), whatever the order of the variables' keys, and the stream closes when the last of them unmounts.
  • db.useAuth() answers {isLoading, user, token} and follows sign-in, sign-out and other tabs (a token's refresh renders nothing).
  • id() is optional: the server makes an entity's id. Use it to name what you create and show it before the server answers (input: { id: id(), ... }).

React is an optional peer dependency. The core (@october1/client) needs nothing.

Writes are retried safely

mutate sends an Idempotency-Key header (a random one per call, or { idempotencyKey }). If the request times out, the network fails, or the server answers UNAVAILABLE, CONFLICT or RATE_LIMITED, the client sends the same request again with the same key. If the write committed the first time, the server answers with that commit and does not write again. Reads are retried the same way, without a key.

Retries wait for the server's retryAfterMs, else a short backoff. They give up after attempts tries (4), or when the server asks for a wait longer than maxRetryWaitMs (10 s).

Read your own writes

mutate resolves once this client's live queries show the write, so a list you subscribe to has the new post when await db.mutate(...) returns. The server answers every write with the basis it committed at (extensions.basisT), and the client waits until each of its live streams has shown that basis, either as a new result or as a small ack the server sends when the write didn't change that query's result.

  • It waits at most liveWaitMs (2 s), then resolves anyway: it never hangs. { waitForLive: false } doesn't wait at all; liveWaitMs: 0 turns waiting off for the client.
  • It waits only for this client's streams that are open as the signed-in user and have had their first result. Other tabs, anonymous streams, and streams that are reconnecting aren't waited for.
  • Two live queries can still be at different bases for a moment (a list and its count): after mutate both show the write, but they don't update at one basis together.
  • db.awaitBasis(basisT, timeoutMs?) waits for any basis, and answers true when every stream got there in time. db.request(doc, vars, { write: true }) answers extensions.basisT and doesn't wait.

Errors

Every failure is an OctoberError:

  • code: the GraphQL extensions.code (VALIDATION_FAILED, FORBIDDEN, NOT_FOUND, UNAUTHENTICATED, CONFLICT, UNAVAILABLE, RATE_LIMITED, ...). For a REST refusal, its type in upper snake case (INVALID_CODE, RATE_LIMITED, UNKNOWN_TENANT). Else NETWORK or TIMEOUT.
  • fields: for VALIDATION_FAILED, {field: [message]}.
  • retryAfterMs, status, details (the rest of the error).
  • data: what did commit. Each mutation field in a request is its own transaction.
  • retryable.

db.request(doc, vars) returns the whole response (data, errors, extensions.cost) instead of throwing on GraphQL errors.

Live queries

db.subscribe(doc, variables, callback, { onStatus, onError }) calls callback with {data, errors, basisT, mine, cost}. mine is true when every write in the push was the signed-in user's own. The client:

  • opens each stream with POST /live, as the signed-in user (its access token refreshed when due) or anonymous; the query and variables go in the body, never in the URL;
  • reconnects with backoff, and when the stream goes quiet (no heartbeat for liveIdleMs, 45 s). The backoff starts over only once a stream has stayed up for 30 s, so a server that keeps closing streams isn't hammered;
  • reopens every stream as the new caller when the sign-in changes, and holds a stream opened while signInWithMagicCode is under way until it settles, so no signed-out result shows first;
  • reconnects at once when the browser comes back online, or the page becomes visible again, instead of waiting out a backoff or a quiet stream;
  • closes a page's streams once it has been hidden for hiddenCloseMs (5 minutes), and opens them again when it is visible (status paused), so background tabs give their connections and slots back.

A query the server refuses (a parse error, a mutation, over the cost limits, any other 4xx but 401 and 429) calls onError and the subscription stops. A callback that throws is your bug, not the stream's: onError gets it with code CALLBACK_FAILED (or, without onError, console.error), and the subscription goes on. It runs over fetch, so it works in Node too.

Each live query is one HTTP stream. The server allows a user 8 open at once, counting every tab and device; past that, onError gets TOO_MANY_SUBSCRIPTIONS once, and the subscription keeps trying every few seconds until a slot frees (another stream closes). useQuery shares one stream between components asking for the same query and variables. A server you run yourself needs HTTP/2 in front of it (nginx, Caddy): over HTTP/1.1, browsers open at most 6 connections to an origin, across all its tabs, so six live queries would leave no connection for anything else and the page would seem to hang.

Sign-in

sendMagicCode answers {sent, demoCode, delivered, message}. demoCode is there only in demo mode; otherwise the user types the code from their email. On a tenant without email, delivered is false: the code wasn't emailed, and message says so.

Unlike reads and writes, sendMagicCode isn't retried: a second code for an address within 30 seconds is an OctoberError with code RATE_LIMITED and retryAfterMs, for your page to wait out or show.

A sign-in is a session: an access token that lasts about 15 minutes, sent with every request and live query, and a refresh token that trades for the next pair. The client keeps the pair in localStorage under october:<tenant>:token (tokenKey, storage) and refreshes on its own:

  • before a request whose access token is about to expire, and on a 401 that says it has (the request is then sent once more);
  • once, however many requests ask at the same time, and once across tabs (a lock, where the browser has the Web Locks API; another tab's new pair is picked up from storage);
  • without touching live queries: a stream stays open across a refresh, and a reconnect opens with the new access token. There is no timer: an idle page refreshes when it next sends something.

A session lasts 30 days at most, however often it is refreshed. A refresh token works once: presented a second time (after 30 seconds, or after the pair it got has itself been used), the server takes it as stolen and ends the whole session. When the server refuses a refresh, the client signs out and tells you why:

db.auth.onSignOut(({ reason }) => {
  // "signed-out" (here or in another tab), "expired", "revoked", "reused"
  if (reason !== "signed-out") showSignIn("Your sign-in has ended.");
});

In Node there is no localStorage, so scripts pass storage: null, which keeps the session in memory. On a server, see On a server: one client per user or request.

  • await db.auth.getToken() is the access token to send with your own requests (to your server, say): refreshed first when it is about to expire, null when signed out. db.auth.token is the token as it is now, which may have expired.
  • db.auth.signedIn, db.auth.user ({id, email} once known), db.auth.session (the pair).
  • db.auth.onChange(fn) is called when who is signed in changes (sign-in, sign-out, another tab), never on a refresh. db.auth.onSignOut(fn).
  • db.auth.setToken(t) adopts a refresh token got elsewhere; null signs out here only.
  • db.auth.me() answers {id, email} or null. A session the server no longer knows is signed out.
  • db.auth.signOut() ends the session on the server (every token of this sign-in) and its live streams.
  • A token stored by a 0.1 client is no session: its user signs in again.
  • db.config() answers {demo}.

On a server

On a server, make one client per user or per request. Never keep a signed-in client at module level. A client holds one session. A server that calls init() once at module level and signs it in shares that one session with every request it serves, so one user's token answers another user's requests.

  • A module-level client is fine only if it never signs in: it reads what anonymous callers may see, for every request alike. Never call db.auth.* on it.
  • For a signed-in user, the browser keeps the session and sends its access token with each call to your server. Make a client for that request that carries the token, and let it go when the request ends. Pass storage: null, so nothing is kept in memory or on disk between requests:
import { init } from "@october1/client";

const ORDERS = `{ orders(first: 20) { items { id total } } }`;

/** A client for one request, as the user whose access token it carries (or anonymous). */
function octoberFor(token) {
  return init({
    url: "https://october.sombra.so",
    tenant: "shop",
    storage: null,
    fetch: (url, opts = {}) =>
      fetch(url, { ...opts, headers: { ...opts.headers, ...(token ? { Authorization: "Bearer " + token } : {}) } }),
  });
}

const bearerOf = (header) => header?.replace(/^Bearer /, "") || null;

Express:

app.get("/api/orders", async (req, res) => {
  const db = octoberFor(bearerOf(req.get("authorization")));   // this request's user
  try {
    res.json(await db.query(ORDERS));
  } catch (e) {
    // UNAUTHENTICATED: the token expired or the session ended; the page gets a new one
    res.status(e.code === "UNAUTHENTICATED" ? 401 : 502).json({ error: e.code });
  }
});

Next.js (a route handler, app/api/orders/route.js):

export async function GET(request) {
  const db = octoberFor(bearerOf(request.headers.get("authorization")));
  try {
    return Response.json(await db.query(ORDERS));
  } catch (e) {
    return Response.json({ error: e.code }, { status: e.code === "UNAUTHENTICATED" ? 401 : 502 });
  }
}

A server component or server action has no Authorization header: read the token from wherever your app hands it to the server (a cookie it sets, for example) inside the component or action, and make the client there. Never put the token or the client in a module variable.

In the browser, send your server the access token from db.auth.getToken(), which refreshes it first when it is about to expire:

const res = await fetch("/api/orders", { headers: { Authorization: "Bearer " + await db.auth.getToken() } });

The server never refreshes the user's token: on a 401 it passes the refusal back, and the page gets a fresh token and calls again. Scripts that act as themselves, not as an app user, use a service token, not an app user's session.

What may I do?

Every type has a can field, and the root has viewer, so a page can leave out what the server would refuse:

const { viewer, card } = await db.query(
  `query ($id: UUID!) { viewer { can { createCard } } card(id: $id) { can { update delete } } }`,
  { id });

A flag has three values. true and false are decided. null means it depends on the write, as with a rule on the new value of a field or an enum's :transitions: show the control, and handle the refusal.

Types (gql.tada)

Documents are strings or typed documents: gql.tada's, or any TypedDocumentNode. Results and variables are then typed from the tenant's SDL:

curl -fsS https://october.sombra.so/t/shop/schema.graphql -o schema.graphql
import { initGraphQLTada } from "gql.tada";
import type { introspection } from "./graphql-env.d.ts";
import { init, type Scalars } from "@october1/client";

const graphql = initGraphQLTada<{ introspection: introspection; scalars: Scalars }>();
const PRODUCT = graphql(`query ($id: UUID!) { product(id: $id) { id name } }`);
const { product } = await db.query(PRODUCT, { id }); // typed

Scalars maps october's scalars: UUID and Instant are strings, Long is a number or a decimal string, JSON is unknown.