import { createSignal, type Signal } from "solid-js"; import { DEV } from "solid-js"; import { getRequestEvent, getServerFunctionMetadata, isServer, isServerFunction } from "@solidjs/web"; import { live } from "@solidjs/web/server-functions"; import { getIntent } from "../routing.js"; import { hashKey, matchKey, registerFlightDataHook, registerRevalidateHook } from "./query.js"; // Matches query's preload lifetime: a channel warmed by preload intent // stays held this long waiting for its navigation. const PRELOAD_TIMEOUT = 5000; // The live-source brand (registered symbol — no transport import needed): // computations meeting a branded iterable apply live SSR policy (document // face takes the first value; hydration re-runs the compute after adoption // to reconnect). liveQuery writes it on both faces itself — the server-side // resolved iterable and the client-side multicast iterable. A server function // producer is declared live() by liveQuery (below); a plain producer needs no // declaration at all. const LIVE_SOURCE = Symbol.for("solid.LiveSource"); // Stamped by hydration's takeover on the iterable the compute returned (the // subscriber iterable below): the value the page was served with. Forwarded // onto the channel's first live() iterable, which yields it first and names // it as its position, so a takeover whose value is unchanged costs nothing // on the wire. const LIVE_RESUME_FROM = Symbol.for("solid.LiveResumeFrom"); export type LiveQueryStatus = "idle" | "connecting" | "connected" | "reconnecting" | "closed"; type Channel = { key: string; /** the keyed store this channel lives in (module map or a request's map) */ map: Map; /** live consumer iterators */ count: number; /** bumps once per delivered value — consumers diff against it */ version: number; latest: any; /** sticky terminal failure — consumers rethrow (transient deaths retry) */ error: any; done: boolean; waiters: Set<() => void>; /** reconnect generation — a superseded pump's late values are dropped */ gen: number; /** ends the current underlying iterator (transport return() aborts the call) */ close: () => void; /** the producer, held for reconnect */ call: () => any; /** report wire state to the keyed status signal (client channels only) */ report: boolean; /** keep the record (latest value) past teardown — request-scoped channels * replay it to later consumers of the same render for value consistency */ retain: boolean; /** the hydrated value the first connection resumes from (see LIVE_RESUME_FROM) */ resume?: any; }; const channelMap = new Map(); // Status outlives the channel (an "idle"/"closed" read after teardown is // meaningful), so signals live in their own keyed map. const statusMap = new Map>(); function statusSignal(key: string) { let s = statusMap.get(key); // ownedWrite: the first write happens synchronously inside whatever // computation pulled the channel open — this is channel-owned state, not // the computation's own. if (!s) statusMap.set( key, (s = createSignal("idle", { ownedWrite: true, ...(DEV && { name: `liveQuery.status:${key}` }) })) ); return s; } function wake(ch: Channel) { const waiters = [...ch.waiters]; ch.waiters.clear(); for (const w of waiters) w(); } const noStatus = () => {}; async function connect(ch: Channel) { const gen = ch.gen; const setStatus = ch.report ? statusSignal(ch.key)[1] : noStatus; let attempts = 0; setStatus(ch.version ? "reconnecting" : "connecting"); while (true) { try { const result = await ch.call(); if (gen !== ch.gen || ch.done) { // superseded (reconnect) or torn down while connecting: the arrived // stream must still be ended or its request leaks result?.[Symbol.asyncIterator] && result[Symbol.asyncIterator]().return?.(); return; } // A live()-declared producer's own retry loop erases deaths from the // value stream and reports them through onstatus — forward those into // the channel's status so both producer kinds read the same. Its // "closed" is redundant with our own done handling below. if (result !== null && typeof result === "object") { try { result.onstatus = (state: string) => { if (gen === ch.gen && state !== "closed") setStatus(state as LiveQueryStatus); }; } catch {} } if (ch.resume !== undefined && result !== null && typeof result === "object") { result[LIVE_RESUME_FROM] = ch.resume; ch.resume = undefined; } const it = result !== null && typeof result === "object" && result[Symbol.asyncIterator] ? result[Symbol.asyncIterator]() : (async function* () { yield result; })(); ch.close = () => { try { const r = it.return && it.return(); if (r && typeof (r as any).then === "function") (r as any).then(undefined, () => {}); } catch {} }; while (true) { const r = await it.next(); if (gen !== ch.gen || ch.done) return; if (r.done) break; ch.latest = r.value; ch.version++; attempts = 0; // healthy value: backoff resets setStatus("connected"); wake(ch); } ch.done = true; setStatus("closed"); wake(ch); return; } catch (error) { if (gen !== ch.gen || ch.done) return; const status = (error as any)?.status; if (!ch.version || (typeof status === "number" && status >= 400 && status < 500)) { // Terminal: never connected (fail like a normal call), or a // definite rejection — the transport stamps HTTP statuses onto // failures, and a 4xx means the server understood and refused; // retrying cannot change the answer. Consumers rethrow (after // draining the latest value), surfacing to error boundaries. ch.error = error; ch.done = true; setStatus("closed"); wake(ch); return; } // A stream that had delivered died transiently (network, 5xx, // severed stream): the channel IS the live layer — reconnect with // backoff, latest value keeps serving meanwhile. (A live()-declared // producer never reaches here; its transport retries.) setStatus("reconnecting"); let timer: any, wakeUp: () => void; await new Promise(resolve => { wakeUp = () => resolve(); timer = setTimeout(wakeUp, Math.min(500 * 2 ** attempts++, 10000)); // connectivity returning wakes the sleep early if (typeof addEventListener === "function") addEventListener("online", wakeUp, { once: true }); }); clearTimeout(timer); // a timer-woken sleep leaves its once-listener behind otherwise — // one leaked closure per backoff cycle until an online event fires if (typeof removeEventListener === "function") removeEventListener("online", wakeUp!); if (gen !== ch.gen || ch.done) return; } } } function teardown(ch: Channel) { // Deferred so a same-key resubscribe in the same tick (a memo re-running // its compute) reuses the connection instead of thrashing it. queueMicrotask(() => { if (ch.count > 0 || ch.map.get(ch.key) !== ch) return; const ended = ch.done; // completed/failed on its own — "closed" persists ch.done = true; ch.close(); wake(ch); if (ch.retain) return; // request-scoped: latest stays replayable ch.map.delete(ch.key); if (ch.report && !ended) statusSignal(ch.key)[1]("idle"); }); } function openChannel( map: Map, key: string, call: () => any, report: boolean, retain: boolean, resume?: any ): Channel { let ch = map.get(key); if (!ch) { ch = { key, map, count: 0, version: 0, latest: undefined, error: undefined, done: false, waiters: new Set(), gen: 0, close: () => {}, call, report, retain, resume }; map.set(key, ch); connect(ch); } return ch; } // The consumer half: a branded iterable whose iterators subscribe to the // channel lazily (first pull connects — a hydration trace or speculative // call opens nothing), replay the latest value immediately, then follow // with latest-wins delivery. function subscriberIterable(open: (resume?: any) => Channel) { const iterable: any = { [LIVE_SOURCE]: true, [Symbol.asyncIterator]() { const ch = open(iterable[LIVE_RESUME_FROM]); ch.count++; let seen = 0; let released = false; const release = () => { if (released) return; released = true; if (--ch.count === 0) teardown(ch); }; const pull = async (): Promise> => { while (true) { if (ch.error && seen >= ch.version) { release(); throw ch.error; } if (ch.version > seen) { seen = ch.version; return { done: false, value: ch.latest }; } if (ch.done) { release(); return { done: true, value: undefined }; } await new Promise(resolve => ch.waiters.add(resolve)); } }; return { next: () => released ? Promise.resolve({ done: true as const, value: undefined }) : pull(), return(value?: any) { release(); return Promise.resolve({ done: true as const, value }); } }; } }; return iterable; } function reconnectChannel(ch: Channel) { ch.gen++; ch.close(); ch.error = undefined; ch.done = false; connect(ch); } function push(ch: Channel, value: any) { ch.latest = value; ch.version++; wake(ch); } // Live channels participate in both data protocols. Registered on first // liveQuery() call, not at module scope: a side-effectful top level would // anchor this module into graphs that never use it. // // - Explicit revalidate(key) (force) reconnects — the producer re-yields // current state on invocation by contract. // - The post-mutation sweep (force=false) does NOT reconnect: the // connection is alive and is itself the freshness mechanism — a // push-driven producer yields the mutated state on its own, and tearing // down healthy connections on every mutation defeats the model. // - A single-flight payload carrying a live key delivers INTO the open // channel rather than reconnecting it. The router's own collector does not // produce live keys (the stream is the freshness mechanism; collection // for live server components is an open question — a mutation's region // would outrank the standing frame stream under the transport's version // policy), so this path serves an integration that collects them itself. let hooked = false; function hookRevalidate() { if (hooked) return; hooked = true; registerRevalidateHook((keys, force) => { if (!force) return; for (const [k, ch] of channelMap) { if (keys === undefined || matchKey(k, keys)) reconnectChannel(ch); } }); registerFlightDataHook(data => { for (const k in data) { const ch = channelMap.get(k); if (!ch || ch.done) continue; const v = data[k]; if (v !== null && typeof v === "object" && v[Symbol.asyncIterator]) { // a live key collected server-side arrives stream-shaped: adopt // its yields for as long as it runs (it ends with the response // body); the channel's own connection remains authoritative (async () => { try { for await (const value of v) { if (ch.done) return; push(ch, value); } } catch {} })(); } else push(ch, v); } }); } export type LiveFunction any> = T extends (...args: infer A) => infer R ? ((...args: A) => AsyncIterable extends AsyncIterable ? V : Awaited>) & { keyFor: (...args: A) => string; key: string; status: (...args: A) => LiveQueryStatus; } : never; /** * Declares a keyed live query over a value-shaped stream: an async-iterable * producer whose yields are successive VALUES of one logical query, with the * contract that the producer re-yields current state on every invocation. * liveQuery IS the live layer — no separate declaration needed: * * - One connection per (name + args) key, shared by every consumer. Late * subscribers receive the latest value immediately, delivery is * latest-wins, and the connection closes when the last consumer leaves. * - A connected stream that dies transiently (network, 5xx) reconnects with * exponential backoff — the latest value keeps serving meanwhile. A * definite rejection (4xx: the transport stamps HTTP statuses onto * failures) ends the channel and surfaces the error to consumers, as does * a first-connect failure. * - Server functions are declared `live()` (which implies GET) at creation, * so the connection gets the transport's live lifecycle. Live keys * are neither collected for single-flight nor swept after a mutation: the * stream is the freshness mechanism, and the mutation reaches a live * query through its producer. (The flight-data hook below still adopts a * live key an integration collects itself.) * - Calling under preload intent warms the channel (a temporary hold keeps * it open through the preload window), so navigation renders against an * already-connected stream instead of holding the transition on connect * plus first yield. Outside preload, calling remains free — only a real * pull connects. * - SSR: the document face renders the first value; hydration adopts it and * reconnects. Channels are request-scoped on the server, so every * consumer of a key in one render observes the same value. Explicit * `revalidate(key)` reconnects (the producer re-yields current state on * invocation), and `status(...args)` is a reactive read of the channel's * wire state. * * ```ts * const roomMessages = liveQuery(getMessages, "messages"); * // in a component — one connection, however many consumers: * const messages = createMemo(() => roomMessages(props.room)); * ``` */ export function liveQuery any>(fn: T, name: string): LiveFunction { hookRevalidate(); // liveQuery implies live (which implies GET): live() brings the wire // lifecycle — the live address, Last-Event-ID resume, response-lifetime // deaths, Retry-After — so the channel multicasts a live connection. An // explicit live() declaration passes through untouched. if (isServerFunction(fn) && !getServerFunctionMetadata(fn)?.live) fn = live(fn) as unknown as T; const liveFn = ((...args: Parameters) => { const key = name + hashKey(args); if (isServer) { const e = getRequestEvent(); if (!e) { // No request scope (static render, tests): hand the source through // whole, branded, so the signals layer applies live SSR policy // (first value, then client takeover). const result = fn(...(args as any)); const brand = (r: any) => { if (r !== null && typeof r === "object" && r[Symbol.asyncIterator]) r[LIVE_SOURCE] = true; return r; }; return result !== null && typeof result === "object" && typeof result.then === "function" ? result.then(brand) : brand(result); } // Request-scoped channels: two consumers of one key during one render // must observe the SAME first value (query's request cache gives its // reads the same guarantee). Channels live in the event, retained // past teardown so a later consumer replays the settled value instead // of reinvoking; the producer still closes with its last consumer. const router = (e as any).router || ((e as any).router = {}); const channels: Map = router.liveChannels || (router.liveChannels = new Map()); return subscriberIterable(() => openChannel(channels, key, () => fn(...(args as any)), false, true) ); } const open = (resume?: any) => openChannel(channelMap, key, () => fn(...(args as any)), true, false, resume); // Preload warms the channel, exactly as calling a query in a preload // function warms its cache: connect now, hold a temporary consumer slot // so refcounting doesn't close it before navigation renders. When the // real consumer arrives it inherits the live connection (first pull // replays the already-arrived value — the transition doesn't hold); // when navigation never comes, the hold lapses and teardown closes it. if (getIntent() === "preload") { const ch = open(); ch.count++; setTimeout(() => { if (--ch.count === 0) teardown(ch); }, PRELOAD_TIMEOUT); } return subscriberIterable(open); }) as unknown as LiveFunction; liveFn.keyFor = (...args: Parameters) => name + hashKey(args); liveFn.key = name; liveFn.status = (...args: Parameters) => statusSignal(name + hashKey(args))[0](); return liveFn; }