diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index ed07a01..a7bde86 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -305,9 +305,11 @@ text rules below are enforced by endpoints. gateway; nothing else about the conversation is exposed. - **Buyer UI:** a contact form on every verified listing; a private link `#/c///` (the secret stays in the URL fragment, - which is never sent to a server) that polls every 20 s, shows only verified - owner replies and counts the rest as rejected; `#/messages` lists the - conversations stored in this browser. + which is never sent to a server) that polls every 8 s while the tab is + visible (paused in a background tab, resumed at once when it returns; there is + no push channel), shows only verified owner replies and counts the rest as + rejected; `#/messages` lists the conversations stored in this browser. The + owner's "My listings" screen refreshes the same way. - **Owner UI** (`#/mine`): your listings (requests needing a reply, whether an address is saved), the requests of one listing (status, preview, effort, filters), a conversation, and a sheet to **release the address** (prefilled diff --git a/web/dist/app.js b/web/dist/app.js index df3c6b0..9b8c567 100644 --- a/web/dist/app.js +++ b/web/dist/app.js @@ -671,6 +671,46 @@ function cellMetres(hash) { }; } +// src/fresh.ts +var FOREGROUND_MS = 8e3; +function keepFresh(alive, run, ms = FOREGROUND_MS, doc = document) { + let timer; + let running = false; + const stop = () => { + clearTimeout(timer); + doc.removeEventListener("visibilitychange", onVisible); + }; + const schedule = () => { + clearTimeout(timer); + timer = setTimeout(() => void fire(), ms); + }; + const fire = async () => { + if (!alive()) return stop(); + if (doc.hidden) return; + if (running) return schedule(); + running = true; + try { + await run(); + } catch { + } finally { + running = false; + } + if (!alive()) return stop(); + schedule(); + }; + const onVisible = () => { + if (!alive()) return stop(); + if (doc.hidden) { + clearTimeout(timer); + return; + } + clearTimeout(timer); + void fire(); + }; + doc.addEventListener("visibilitychange", onVisible); + schedule(); +} + // node_modules/@noble/ciphers/utils.js /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */ function isBytes(a) { @@ -4317,7 +4357,6 @@ function conversationHash(author, id, secret) { } // src/chat.ts -var POLL_MS = 2e4; var OVERLAP = 3600; var app = () => document.getElementById("app"); var fromHex = (s) => Uint8Array.from(s.match(/../g) ?? [], (b) => parseInt(b, 16)); @@ -4625,9 +4664,9 @@ async function showConversation(author, id, secret) { } if (gen !== state.generation) return; render(rejected, failed); - setTimeout(() => void cycle(), POLL_MS); }; await cycle(); + keepFresh(() => gen === state.generation, cycle); } function deleteControl(c) { const slot = h("p", null); @@ -4795,7 +4834,6 @@ async function renewListing(author, id, days = MAX_LIFETIME_DAYS) { } // src/owner.ts -var REFRESH_MS = 3e4; var VALID_DAYS = [1, 3, 7, 14, 30]; var DEFAULT_DAYS = 7; var app2 = () => document.getElementById("app"); @@ -5014,13 +5052,7 @@ async function showOwner(listingId, thread) { } renderListings(); await refresh(); - const tick2 = () => { - setTimeout(() => { - if (gen !== state.generation) return; - void refresh().then(tick2); - }, REFRESH_MS); - }; - tick2(); + keepFresh(() => gen === state.generation && getToken() !== null, refresh); } var DAY2 = 86400; var SOON_DAYS = 5; diff --git a/web/src/chat.ts b/web/src/chat.ts index 8ae8d29..17f589d 100644 --- a/web/src/chat.ts +++ b/web/src/chat.ts @@ -4,6 +4,7 @@ import { HttpError, getListing, pollMailbox, postMessage } from "./api.ts"; import { append, clear, h, sendOnCtrlEnter } from "./dom.ts"; +import { keepFresh } from "./fresh.ts"; import { date } from "./format.ts"; import { t, type Key } from "./i18n.ts"; import { @@ -33,7 +34,6 @@ import { } from "./threads.ts"; import { verifyListing, type Listing } from "./verify.ts"; -const POLL_MS = 20_000; /** Re-read this much of the mailbox each time, so a clock that is a little off loses nothing. */ const OVERLAP = 3600; const app = () => document.getElementById("app")!; @@ -375,9 +375,9 @@ export async function showConversation(author: string, id: string, secret: strin } if (gen !== state.generation) return; render(rejected, failed); - setTimeout(() => void cycle(), POLL_MS); }; await cycle(); + keepFresh(() => gen === state.generation, cycle); } function deleteControl(c: Conversation): HTMLElement { diff --git a/web/src/fresh.ts b/web/src/fresh.ts new file mode 100644 index 0000000..7aa1b70 --- /dev/null +++ b/web/src/fresh.ts @@ -0,0 +1,53 @@ +// Keeps a screen up to date without a live connection: runs `run` every `ms` +// while the page is visible, pauses while it is in a background tab, and runs +// at once when the tab comes back. There is no push channel (messages are +// relayed through the network and fetched), so this is as live as it gets. + +/** How often an open screen checks for news, in milliseconds. */ +export const FOREGROUND_MS = 8_000; + +/** + * Calls `run` every `ms` while `alive()` is true and `doc` is visible. The first + * call is the caller's job (do it before calling this); the next one happens + * after `ms`. Runs never overlap. Stops for good once `alive()` is false. + */ +export function keepFresh(alive: () => boolean, run: () => Promise, ms = FOREGROUND_MS, doc: Document = document): void { + let timer: ReturnType | undefined; + let running = false; + + const stop = () => { + clearTimeout(timer); + doc.removeEventListener("visibilitychange", onVisible); + }; + const schedule = () => { + clearTimeout(timer); + timer = setTimeout(() => void fire(), ms); + }; + const fire = async () => { + if (!alive()) return stop(); + if (doc.hidden) return; // paused: becoming visible resumes it + if (running) return schedule(); + running = true; + try { + await run(); + } catch { + // A failed check is the caller's to show; the next one still happens. + } finally { + running = false; + } + if (!alive()) return stop(); + schedule(); + }; + const onVisible = () => { + if (!alive()) return stop(); + if (doc.hidden) { + clearTimeout(timer); + return; + } + clearTimeout(timer); + void fire(); + }; + + doc.addEventListener("visibilitychange", onVisible); + schedule(); +} diff --git a/web/src/owner.ts b/web/src/owner.ts index 8ca1e10..2742c7a 100644 --- a/web/src/owner.ts +++ b/web/src/owner.ts @@ -8,13 +8,13 @@ import { HttpError } from "./api.ts"; import { append, clear, h, sendOnCtrlEnter } from "./dom.ts"; +import { keepFresh } from "./fresh.ts"; import { date, price, when } from "./format.ts"; import { t, type Key } from "./i18n.ts"; import * as o from "./ownerApi.ts"; import { nowSeconds, state } from "./state.ts"; import type { Listing } from "./verify.ts"; -const REFRESH_MS = 30_000; const VALID_DAYS = [1, 3, 7, 14, 30]; const DEFAULT_DAYS = 7; const app = () => document.getElementById("app")!; @@ -274,13 +274,8 @@ export async function showOwner(listingId?: string, thread?: string): Promise { - setTimeout(() => { - if (gen !== state.generation) return; - void refresh().then(tick); - }, REFRESH_MS); - }; - tick(); + // Signed out (or a rejected token) ends the checks, so the sign-in form is not redrawn under the user. + keepFresh(() => gen === state.generation && o.getToken() !== null, refresh); } // --- pieces ------------------------------------------------------------------------------ diff --git a/web/test/fresh.test.ts b/web/test/fresh.test.ts new file mode 100644 index 0000000..2bd32bc --- /dev/null +++ b/web/test/fresh.test.ts @@ -0,0 +1,96 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { JSDOM } from "jsdom"; + +import { FOREGROUND_MS, keepFresh } from "../src/fresh.ts"; + +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +/** A document whose visibility the test controls. */ +function page() { + const doc = new JSDOM("").window.document; + let hidden = false; + Object.defineProperty(doc, "hidden", { get: () => hidden }); + return { + doc, + setHidden(h: boolean) { + hidden = h; + doc.dispatchEvent(new doc.defaultView!.Event("visibilitychange")); + }, + }; +} + +test("it checks again and again while the page is visible", async () => { + const p = page(); + let runs = 0; + let alive = true; + keepFresh(() => alive, async () => void runs++, 20, p.doc); + await sleep(110); + alive = false; + assert.ok(runs >= 3, `ran ${runs} times`); +}); + +test("it pauses in a background tab and catches up at once when the tab returns", async () => { + const p = page(); + let runs = 0; + let alive = true; + keepFresh(() => alive, async () => void runs++, 20, p.doc); + await sleep(50); + p.setHidden(true); + await sleep(30); // let any run that was already due finish + const paused = runs; + await sleep(120); + assert.equal(runs, paused, "nothing runs while hidden"); + + p.setHidden(false); + await sleep(5); // far less than the interval: the catch-up is immediate + assert.equal(runs, paused + 1, "one check right away"); + await sleep(60); + assert.ok(runs > paused + 1, "and it keeps going"); + alive = false; +}); + +test("it stops for good once the screen is gone", async () => { + const p = page(); + let runs = 0; + let alive = true; + keepFresh(() => alive, async () => void runs++, 20, p.doc); + await sleep(50); + alive = false; + await sleep(40); + const stopped = runs; + p.setHidden(true); + p.setHidden(false); // coming back does not revive it + await sleep(80); + assert.equal(runs, stopped); +}); + +test("a slow or failing check never overlaps itself and does not end the loop", async () => { + const p = page(); + let active = 0; + let peak = 0; + let runs = 0; + let alive = true; + keepFresh( + () => alive, + async () => { + runs++; + active++; + peak = Math.max(peak, active); + await sleep(35); // slower than the interval + active--; + if (runs === 2) throw new Error("network down"); + }, + 10, + p.doc, + ); + await sleep(300); + alive = false; + assert.equal(peak, 1, "runs do not overlap"); + assert.ok(runs >= 4, `kept going after a failure (${runs} runs)`); +}); + +test("the default is a few seconds, not half a minute", () => { + assert.ok(FOREGROUND_MS >= 5_000 && FOREGROUND_MS <= 10_000); +});