feat(catalog): make the live catalog self-correcting and honest about failure
Gitea Actions Runner Test / test-job (push) Successful in 0s
CI / check (push) Successful in 29s
CI / tests-unit (push) Successful in 1m34s
CI / tests-integration (push) Failing after 1m34s
CI / tests-ui (push) Successful in 2m19s
CI / preflight (push) Skipped
CI / deploy (push) Skipped
Gitea Actions Runner Test / test-job (push) Successful in 0s
CI / check (push) Successful in 29s
CI / tests-unit (push) Successful in 1m34s
CI / tests-integration (push) Failing after 1m34s
CI / tests-ui (push) Successful in 2m19s
CI / preflight (push) Skipped
CI / deploy (push) Skipped
The previous commit made imports update the Studio without a reload, but the guarantee only held inside the tab that started the import and only as long as every read succeeded. Four holes were left, and this closes them. A session that mounted the tree before an import kept the pre-import tree for the rest of its life, because ensureCatalogTreeLoaded() was a once-per-session no-op. It now asks the server whether what it holds is still current. The answer is a revision: sendCatalogUpdate() already runs after every catalog write, so it bumps one, and clients read it on mount, on focus, on a 20s poll and from other tabs over a BroadcastChannel. An import that finishes in another tab, another browser or the job worker now lands here too. A failed read used to be swallowed, which is the worst outcome available: the rail kept showing pre-import counts as if they were current and nothing said so. The snapshot now carries the error, the rail shows it with a retry, and the previous tree stays on screen because stale beats empty. Every settled import pulled the entire flat tree, which is the one payload that grows with the size of the catalog. The revision doubles as the ETag on mode=full, so an unchanged catalog answers 304 and the poll costs a file read. An import could also report success for an offer the hotel will never sell: a hidden or disabled page, an item_ids that misses the furni id, a zero amount. importSingleFurni reads its own row back and reports each of those as a warning, where the import report already is, instead of leaving it to surface as "the import did not work" in the client. Finally, the catalog items table no longer falls back to router.refresh() — onRefresh is now required, so every mutation ends in a refresh of the caller's own data instead of a route re-render that threw away editor state and scroll position. useServerAction keeps its default, because 47 callers across the app depend on it. The 750-line CatalogTree in catalog-tree.tsx was dead code that kept its own stale tree and three more router.refresh() calls; only CatalogIcon and LAYOUT_COLORS are still imported, so the rest is gone. Tests: the store now covers revisions, 304s, probe failures and error recovery; a jsdom test mounts a consumer and asserts the tree updates in place with no navigation; the old organize-imports e2e asserted nothing about the endpoints the code actually calls, and is replaced by one that asserts a cross-tab write lands in the mounted categories without a reload. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
This commit is contained in:
1 parent
28ce0f911c
commit
9550b3d66f
18 files changed
+1016
-973
No files matched your search
@@ -0,0 +1,166 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const adminFetch = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@/lib/admin-fetch", () => ({ adminFetch }));
|
||||
|
||||
import {
|
||||
checkCatalogRevision,
|
||||
resetLiveCatalogForTests,
|
||||
useCatalogSync,
|
||||
useLiveCatalog,
|
||||
} from "./use-live-catalog";
|
||||
|
||||
function page(id: number, caption = `page ${id}`) {
|
||||
return {
|
||||
id,
|
||||
caption,
|
||||
parentId: -1,
|
||||
depth: 0,
|
||||
orderNum: 0,
|
||||
enabled: "1",
|
||||
visible: "1",
|
||||
iconImage: 0,
|
||||
iconColor: 0,
|
||||
pageLayout: "default_3x3",
|
||||
childCount: 0,
|
||||
itemCount: 0,
|
||||
};
|
||||
}
|
||||
|
||||
/** What the server currently looks like, as the route would report it. */
|
||||
const server = {
|
||||
revision: "rev-1",
|
||||
pages: [page(1)],
|
||||
treeFails: false,
|
||||
};
|
||||
|
||||
function respond(body: unknown) {
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => body,
|
||||
headers: new Headers(),
|
||||
} as unknown as Response;
|
||||
}
|
||||
|
||||
function serve(): Response {
|
||||
const url = String(adminFetch.mock.calls.at(-1)?.[0] ?? "");
|
||||
if (url.includes("/catalog/revision"))
|
||||
return respond({ revision: server.revision });
|
||||
if (server.treeFails) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 500,
|
||||
json: async () => ({}),
|
||||
headers: new Headers(),
|
||||
} as unknown as Response;
|
||||
}
|
||||
return respond({
|
||||
pages: server.pages,
|
||||
totals: null,
|
||||
revision: server.revision,
|
||||
});
|
||||
}
|
||||
|
||||
function Probe() {
|
||||
// The real interval is long; each test drives the revision check itself.
|
||||
useCatalogSync(600_000);
|
||||
const { tree, refreshError } = useLiveCatalog();
|
||||
return (
|
||||
<div>
|
||||
<span data-testid="captions">
|
||||
{tree.map((node) => node.caption).join(",")}
|
||||
</span>
|
||||
{refreshError ? <span data-testid="stale">stale</span> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
const navigations: string[] = [];
|
||||
|
||||
async function render() {
|
||||
await act(async () => {
|
||||
root.render(<Probe />);
|
||||
await Promise.resolve();
|
||||
});
|
||||
}
|
||||
|
||||
function captions() {
|
||||
return container.querySelector('[data-testid="captions"]')?.textContent ?? "";
|
||||
}
|
||||
|
||||
async function flush() {
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
});
|
||||
}
|
||||
|
||||
describe("useCatalogSync", () => {
|
||||
beforeEach(async () => {
|
||||
resetLiveCatalogForTests();
|
||||
adminFetch.mockReset();
|
||||
server.revision = "rev-1";
|
||||
server.pages = [page(1)];
|
||||
server.treeFails = false;
|
||||
adminFetch.mockImplementation(serve);
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
navigations.length = 0;
|
||||
window.addEventListener("beforeunload", () => navigations.push("unload"));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await act(async () => root.unmount());
|
||||
container.remove();
|
||||
});
|
||||
|
||||
it("updates the mounted tree when an import finishes in another session", async () => {
|
||||
await render();
|
||||
expect(captions()).toBe("page 1");
|
||||
|
||||
// Another tab, browser or the job worker wrote the catalog.
|
||||
server.revision = "rev-2";
|
||||
server.pages = [page(1), page(2, "Imported Furniture")];
|
||||
await act(async () => {
|
||||
await checkCatalogRevision();
|
||||
});
|
||||
|
||||
expect(captions()).toBe("page 1,Imported Furniture");
|
||||
// Nothing about this update went through the router: the document was
|
||||
// never torn down and no navigation was triggered.
|
||||
expect(navigations).toEqual([]);
|
||||
expect(document.body.contains(container)).toBe(true);
|
||||
});
|
||||
|
||||
it("follows a catalog write announced by another tab", async () => {
|
||||
await render();
|
||||
const otherTab = new BroadcastChannel("atom-cms-catalog");
|
||||
|
||||
server.revision = "rev-3";
|
||||
server.pages = [page(1), page(7, "Chairs")];
|
||||
otherTab.postMessage({ revision: "rev-3" });
|
||||
await flush();
|
||||
|
||||
expect(captions()).toBe("page 1,Chairs");
|
||||
otherTab.close();
|
||||
});
|
||||
|
||||
it("keeps the previous tree and marks it stale when the read fails", async () => {
|
||||
await render();
|
||||
server.treeFails = true;
|
||||
server.revision = "rev-4";
|
||||
|
||||
await act(async () => {
|
||||
await checkCatalogRevision();
|
||||
});
|
||||
|
||||
expect(captions()).toBe("page 1");
|
||||
expect(container.querySelector('[data-testid="stale"]')).not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -5,14 +5,21 @@ vi.mock("@/lib/admin-fetch", () => ({ adminFetch }));
|
||||
|
||||
import {
|
||||
applyCatalogDelta,
|
||||
checkCatalogRevision,
|
||||
ensureCatalogTreeLoaded,
|
||||
getLiveCatalogSnapshot,
|
||||
refreshCatalogTree,
|
||||
resetLiveCatalogForTests,
|
||||
seedCatalogTotals,
|
||||
} from "./use-live-catalog";
|
||||
|
||||
function ok(body: unknown) {
|
||||
return { ok: true, json: async () => body } as unknown as Response;
|
||||
function ok(body: unknown, init: { etag?: string } = {}) {
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => body,
|
||||
headers: new Headers(init.etag ? { etag: init.etag } : {}),
|
||||
} as unknown as Response;
|
||||
}
|
||||
|
||||
function page(id: number, over: Record<string, unknown> = {}) {
|
||||
@@ -153,7 +160,7 @@ describe("refreshCatalogTree", () => {
|
||||
expect(getLiveCatalogSnapshot().tree.map((n) => n.id)).toEqual([1, 2]);
|
||||
});
|
||||
|
||||
it("leaves the previous snapshot alone when the read fails", async () => {
|
||||
it("keeps the tree it holds when the read fails, and says so", async () => {
|
||||
adminFetch.mockResolvedValueOnce(ok({ pages: [page(1)] }));
|
||||
await refreshCatalogTree();
|
||||
adminFetch.mockResolvedValueOnce({
|
||||
@@ -164,6 +171,159 @@ describe("refreshCatalogTree", () => {
|
||||
|
||||
await refreshCatalogTree();
|
||||
|
||||
const snapshot = getLiveCatalogSnapshot();
|
||||
expect(snapshot.tree.map((n) => n.id)).toEqual([1]);
|
||||
// A rail that cannot refresh must say so: showing the previous tree as if
|
||||
// it were current is the silent-staleness bug this error exists for.
|
||||
expect(snapshot.refreshError).toContain("500");
|
||||
expect(snapshot.refreshing).toBe(false);
|
||||
});
|
||||
|
||||
it("clears the error once a later read succeeds", async () => {
|
||||
adminFetch.mockResolvedValueOnce({
|
||||
ok: false,
|
||||
status: 503,
|
||||
json: async () => ({}),
|
||||
} as unknown as Response);
|
||||
await refreshCatalogTree();
|
||||
expect(getLiveCatalogSnapshot().refreshError).toContain("503");
|
||||
|
||||
adminFetch.mockResolvedValueOnce(ok({ pages: [page(1)] }));
|
||||
await refreshCatalogTree();
|
||||
|
||||
expect(getLiveCatalogSnapshot().refreshError).toBeNull();
|
||||
});
|
||||
|
||||
it("reports a read in flight while it runs", async () => {
|
||||
let release: (() => void) | undefined;
|
||||
const gate = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
adminFetch.mockImplementationOnce(async () => {
|
||||
expect(getLiveCatalogSnapshot().refreshing).toBe(true);
|
||||
await gate;
|
||||
return ok({ pages: [] });
|
||||
});
|
||||
|
||||
const read = refreshCatalogTree();
|
||||
release?.();
|
||||
await read;
|
||||
|
||||
expect(getLiveCatalogSnapshot().refreshing).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("catalog revision", () => {
|
||||
beforeEach(() => {
|
||||
resetLiveCatalogForTests();
|
||||
adminFetch.mockReset();
|
||||
});
|
||||
|
||||
it("adopts the revision the tree route reports", async () => {
|
||||
adminFetch.mockResolvedValueOnce(
|
||||
ok({ pages: [page(1)], revision: "rev-1" }, { etag: '"rev-1"' }),
|
||||
);
|
||||
|
||||
await refreshCatalogTree();
|
||||
|
||||
expect(getLiveCatalogSnapshot().revision).toBe("rev-1");
|
||||
});
|
||||
|
||||
it("does not re-read the tree when the revision is unchanged", async () => {
|
||||
adminFetch.mockResolvedValueOnce(
|
||||
ok({ pages: [page(1)], revision: "rev-1" }, { etag: '"rev-1"' }),
|
||||
);
|
||||
await refreshCatalogTree();
|
||||
adminFetch.mockResolvedValueOnce(ok({ revision: "rev-1" }));
|
||||
|
||||
await checkCatalogRevision();
|
||||
|
||||
expect(adminFetch).toHaveBeenCalledTimes(2);
|
||||
expect(adminFetch.mock.calls[1][0]).toContain("/catalog/revision");
|
||||
});
|
||||
|
||||
it("re-reads the tree when another session moved the revision on", async () => {
|
||||
adminFetch.mockResolvedValueOnce(
|
||||
ok({ pages: [page(1)], revision: "rev-1" }, { etag: '"rev-1"' }),
|
||||
);
|
||||
await refreshCatalogTree();
|
||||
|
||||
adminFetch.mockResolvedValueOnce(ok({ revision: "rev-2" }));
|
||||
adminFetch.mockResolvedValueOnce(
|
||||
ok({ pages: [page(1), page(2)], revision: "rev-2" }, { etag: '"rev-2"' }),
|
||||
);
|
||||
|
||||
await checkCatalogRevision();
|
||||
|
||||
expect(getLiveCatalogSnapshot().tree.map((n) => n.id)).toEqual([1, 2]);
|
||||
expect(getLiveCatalogSnapshot().revision).toBe("rev-2");
|
||||
});
|
||||
|
||||
it("probes the revision on every mount instead of trusting the session", async () => {
|
||||
adminFetch.mockResolvedValueOnce(
|
||||
ok({ pages: [page(1)], revision: "rev-1" }, { etag: '"rev-1"' }),
|
||||
);
|
||||
await refreshCatalogTree();
|
||||
|
||||
// A second mount of the tree in the same session used to be a no-op, which
|
||||
// is why a session that started before an import kept showing the old
|
||||
// catalog.
|
||||
adminFetch.mockResolvedValueOnce(ok({ revision: "rev-1" }));
|
||||
adminFetch.mockResolvedValueOnce(ok({ revision: "rev-2" }));
|
||||
adminFetch.mockResolvedValueOnce(
|
||||
ok({ pages: [page(1), page(9)], revision: "rev-2" }, { etag: '"rev-2"' }),
|
||||
);
|
||||
await ensureCatalogTreeLoaded();
|
||||
await ensureCatalogTreeLoaded();
|
||||
|
||||
expect(getLiveCatalogSnapshot().tree.map((n) => n.id)).toEqual([1, 9]);
|
||||
});
|
||||
|
||||
it("replays the ETag so an unchanged catalog answers 304", async () => {
|
||||
adminFetch.mockResolvedValueOnce(
|
||||
ok({ pages: [page(1)], revision: "rev-1" }, { etag: '"rev-1"' }),
|
||||
);
|
||||
await refreshCatalogTree();
|
||||
|
||||
adminFetch.mockResolvedValueOnce({
|
||||
ok: false,
|
||||
status: 304,
|
||||
json: async () => ({}),
|
||||
headers: new Headers({ etag: '"rev-1"' }),
|
||||
} as unknown as Response);
|
||||
adminFetch.mockResolvedValueOnce(ok({ revision: "rev-2" }));
|
||||
adminFetch.mockResolvedValueOnce(
|
||||
ok({ pages: [page(1), page(2)], revision: "rev-2" }, { etag: '"rev-2"' }),
|
||||
);
|
||||
|
||||
await refreshCatalogTree();
|
||||
// 304 means nothing changed: the tree stays, and no error is invented.
|
||||
expect(getLiveCatalogSnapshot().tree.map((n) => n.id)).toEqual([1]);
|
||||
expect(getLiveCatalogSnapshot().refreshError).toBeNull();
|
||||
|
||||
await checkCatalogRevision();
|
||||
|
||||
expect(getLiveCatalogSnapshot().tree.map((n) => n.id)).toEqual([1, 2]);
|
||||
expect(adminFetch.mock.calls[1][1]).toMatchObject({
|
||||
headers: { "if-none-match": '"rev-1"' },
|
||||
});
|
||||
});
|
||||
|
||||
it("stays quiet when the probe itself fails", async () => {
|
||||
adminFetch.mockResolvedValueOnce(
|
||||
ok({ pages: [page(1)], revision: "rev-1" }, { etag: '"rev-1"' }),
|
||||
);
|
||||
await refreshCatalogTree();
|
||||
adminFetch.mockResolvedValueOnce({
|
||||
ok: false,
|
||||
status: 500,
|
||||
json: async () => ({}),
|
||||
} as unknown as Response);
|
||||
|
||||
await checkCatalogRevision();
|
||||
|
||||
// The tree may be perfectly current; a failed probe is not a failed read.
|
||||
expect(getLiveCatalogSnapshot().refreshError).toBeNull();
|
||||
expect(getLiveCatalogSnapshot().revision).toBe("rev-1");
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { useEffect, useSyncExternalStore } from "react";
|
||||
import { adminFetch } from "@/lib/admin-fetch";
|
||||
import type { TreeNode } from "@/types/catalog";
|
||||
import {
|
||||
@@ -19,12 +19,21 @@ interface LiveCatalogSnapshot {
|
||||
tree: TreeNode[];
|
||||
totals: Record<CatalogMode, CatalogTotals | null>;
|
||||
treeLoaded: boolean;
|
||||
/** Catalog state the tree was read at, as bumped by `sendCatalogUpdate()`. */
|
||||
revision: string | null;
|
||||
/** A read is in flight; the rail shows this instead of pretending to be live. */
|
||||
refreshing: boolean;
|
||||
/** Last read failure. Never swallowed: a rail that cannot refresh must say so. */
|
||||
refreshError: string | null;
|
||||
}
|
||||
|
||||
const EMPTY_SNAPSHOT: LiveCatalogSnapshot = {
|
||||
tree: [],
|
||||
totals: { normal: null, bc: null },
|
||||
treeLoaded: false,
|
||||
revision: null,
|
||||
refreshing: false,
|
||||
refreshError: null,
|
||||
};
|
||||
|
||||
// A module-level external store keeps the catalog tree alive across client
|
||||
@@ -93,14 +102,38 @@ export function applyCatalogDelta(delta: CatalogTreeDelta): void {
|
||||
});
|
||||
}
|
||||
|
||||
const TREE_URL = "/api/admin/catalog/tree?mode=full";
|
||||
const REVISION_URL = "/api/admin/catalog/revision";
|
||||
const CHANNEL = "atom-cms-catalog";
|
||||
|
||||
/** Last ETag the server handed out, replayed as `If-None-Match` on the next read. */
|
||||
let treeEtag: string | null = null;
|
||||
let treeRequest: Promise<void> | null = null;
|
||||
let treeRequestQueued = false;
|
||||
|
||||
async function loadTree(): Promise<void> {
|
||||
const res = await adminFetch("/api/admin/catalog/tree?mode=full");
|
||||
const res = await adminFetch(
|
||||
TREE_URL,
|
||||
treeEtag
|
||||
? { cache: "no-store", headers: { "if-none-match": treeEtag } }
|
||||
: { cache: "no-store" },
|
||||
);
|
||||
// 304 means the catalog state this tree was read at is still current: nothing
|
||||
// changed, so nothing to re-render. This is what keeps the poll cheap on a
|
||||
// large catalog, where the flat tree is by far the biggest payload here.
|
||||
if (res.status === 304) {
|
||||
emit({ ...snapshot, refreshing: false, refreshError: null });
|
||||
return;
|
||||
}
|
||||
if (!res.ok) throw new Error(`Catalog tree refresh failed (${res.status})`);
|
||||
treeEtag = res.headers.get("etag") ?? treeEtag;
|
||||
const data = await res.json();
|
||||
// The route answers with live totals alongside the tree: importing writes
|
||||
// catalog rows server-side, so the numbers the store holds would otherwise
|
||||
// stay pre-import for the rest of the session.
|
||||
const totals = normalizeCatalogTotals(data?.totals);
|
||||
const revision =
|
||||
typeof data?.revision === "string" ? data.revision : snapshot.revision;
|
||||
emit({
|
||||
...snapshot,
|
||||
tree: normalizeTreePages(data?.pages),
|
||||
@@ -109,12 +142,13 @@ async function loadTree(): Promise<void> {
|
||||
normal: totals ?? snapshot.totals.normal,
|
||||
},
|
||||
treeLoaded: true,
|
||||
revision,
|
||||
refreshing: false,
|
||||
refreshError: null,
|
||||
});
|
||||
if (revision) broadcastRevision(revision);
|
||||
}
|
||||
|
||||
let treeRequest: Promise<void> | null = null;
|
||||
let treeRequestQueued = false;
|
||||
|
||||
/**
|
||||
* Reload the whole tree and totals over the API. Used where the server decides
|
||||
* the shape of the result — the furniture importers derive their category pages
|
||||
@@ -131,15 +165,24 @@ export function refreshCatalogTree(): Promise<void> {
|
||||
treeRequestQueued = true;
|
||||
return treeRequest;
|
||||
}
|
||||
if (!snapshot.refreshing) emit({ ...snapshot, refreshing: true });
|
||||
treeRequest = (async () => {
|
||||
try {
|
||||
do {
|
||||
treeRequestQueued = false;
|
||||
await loadTree();
|
||||
} while (treeRequestQueued);
|
||||
} catch {
|
||||
// A failed read keeps the previous snapshot; the next mount or
|
||||
// mutation tries again.
|
||||
} catch (error) {
|
||||
// Keep the previous tree — stale beats empty — but never silently:
|
||||
// without an error in the snapshot the rail would show pre-import
|
||||
// counts as if they were current.
|
||||
treeEtag = null;
|
||||
emit({
|
||||
...snapshot,
|
||||
refreshing: false,
|
||||
refreshError:
|
||||
error instanceof Error ? error.message : "Catalog refresh failed",
|
||||
});
|
||||
} finally {
|
||||
treeRequest = null;
|
||||
}
|
||||
@@ -147,14 +190,89 @@ export function refreshCatalogTree(): Promise<void> {
|
||||
return treeRequest;
|
||||
}
|
||||
|
||||
/** Load the tree once per session; later calls are no-ops. */
|
||||
/**
|
||||
* Compare the server's revision against the one this tree was read at and
|
||||
* refresh only when they differ. Cheap enough to run on every mount, on every
|
||||
* focus and on a slow poll, which is what closes the gaps a single-tab store
|
||||
* leaves: an import finished in another tab, another browser or the job worker
|
||||
* has to show up here too.
|
||||
*/
|
||||
export async function checkCatalogRevision(): Promise<void> {
|
||||
const res = await adminFetch(REVISION_URL, { cache: "no-store" });
|
||||
// A failed probe is not worth reporting: the tree itself may be perfectly
|
||||
// current, and the next poll tries again.
|
||||
if (!res.ok) return;
|
||||
let revision: unknown;
|
||||
try {
|
||||
revision = (await res.json())?.revision;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (typeof revision !== "string" || !revision) return;
|
||||
if (revision === snapshot.revision) return;
|
||||
await refreshCatalogTree();
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the tree when this session has none, otherwise ask the server whether
|
||||
* what we hold is still current. The tree used to be read once per session,
|
||||
* which is exactly why a session that started before an import could keep
|
||||
* showing the pre-import catalog.
|
||||
*/
|
||||
export function ensureCatalogTreeLoaded(): Promise<void> {
|
||||
return snapshot.treeLoaded ? Promise.resolve() : refreshCatalogTree();
|
||||
return snapshot.treeLoaded ? checkCatalogRevision() : refreshCatalogTree();
|
||||
}
|
||||
|
||||
// ── Cross-tab ────────────────────────────────────────────────────────────
|
||||
|
||||
let channel: BroadcastChannel | null = null;
|
||||
|
||||
function broadcastRevision(revision: string): void {
|
||||
// One tab's refresh tells the others; their own refresh then finds the
|
||||
// revision it already has and stops, so this cannot loop.
|
||||
channel?.postMessage({ revision });
|
||||
}
|
||||
|
||||
function getChannel(): BroadcastChannel | null {
|
||||
if (channel || typeof BroadcastChannel === "undefined") return channel;
|
||||
channel = new BroadcastChannel(CHANNEL);
|
||||
channel.addEventListener("message", (event) => {
|
||||
const revision = (event.data as { revision?: unknown } | null)?.revision;
|
||||
if (typeof revision !== "string" || revision === snapshot.revision) return;
|
||||
void refreshCatalogTree();
|
||||
});
|
||||
return channel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep a mounted admin view honest about catalog writes it did not make itself:
|
||||
* load once, then poll the server revision, re-check on focus, and follow
|
||||
* writes from other tabs. Mount it once per view that renders the tree.
|
||||
*/
|
||||
export function useCatalogSync(intervalMs = 20_000): void {
|
||||
useEffect(() => {
|
||||
void ensureCatalogTreeLoaded();
|
||||
getChannel();
|
||||
const recheck = () => {
|
||||
if (document.visibilityState === "visible") void checkCatalogRevision();
|
||||
};
|
||||
const interval = setInterval(recheck, intervalMs);
|
||||
document.addEventListener("visibilitychange", recheck);
|
||||
window.addEventListener("focus", recheck);
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
document.removeEventListener("visibilitychange", recheck);
|
||||
window.removeEventListener("focus", recheck);
|
||||
};
|
||||
}, [intervalMs]);
|
||||
}
|
||||
|
||||
/** Test seam: drop all live catalog state between cases. */
|
||||
export function resetLiveCatalogForTests(): void {
|
||||
treeRequest = null;
|
||||
treeRequestQueued = false;
|
||||
treeEtag = null;
|
||||
channel?.close();
|
||||
channel = null;
|
||||
emit(EMPTY_SNAPSHOT);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import "server-only";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { logger } from "@/lib/logger";
|
||||
import { catalogStateRoot } from "@/lib/services/catalog-git-config";
|
||||
|
||||
const FILE = "catalog-revision.json";
|
||||
|
||||
/**
|
||||
* A cheap "did the catalog change?" token for every open admin session.
|
||||
*
|
||||
* `sendCatalogUpdate()` runs after each catalog write, so bumping this there
|
||||
* covers every import, page edit, item edit and organize run without touching
|
||||
* each call site. Clients compare the revision they loaded against the current
|
||||
* one to decide whether their tree is stale: one tiny file read instead of
|
||||
* re-reading the whole tree every few seconds.
|
||||
*
|
||||
* The value is random rather than a counter. Two CMS processes writing at the
|
||||
* same moment must never hand out the same revision, and consumers only ever
|
||||
* compare for inequality, so a monotonic number would buy nothing.
|
||||
*
|
||||
* Like the totals cache this only tracks writes made through the CMS. A direct
|
||||
* database edit leaves the revision untouched, which is exactly when a reload
|
||||
* is warranted anyway.
|
||||
*/
|
||||
export async function bumpCatalogRevision(): Promise<string> {
|
||||
const revision = `${Date.now().toString(36)}-${randomUUID().slice(0, 8)}`;
|
||||
const root = catalogStateRoot();
|
||||
const temp = path.join(root, `revision-${randomUUID()}.tmp`);
|
||||
try {
|
||||
await fs.mkdir(root, { recursive: true });
|
||||
await fs.writeFile(temp, JSON.stringify({ revision }), { flag: "wx" });
|
||||
await fs.rename(temp, path.join(root, FILE));
|
||||
} catch (error) {
|
||||
logger.error("Cannot persist catalog revision", {
|
||||
module: "catalog",
|
||||
error,
|
||||
});
|
||||
} finally {
|
||||
await fs.rm(temp, { force: true }).catch(() => {});
|
||||
}
|
||||
return revision;
|
||||
}
|
||||
|
||||
export async function readCatalogRevision(): Promise<string | null> {
|
||||
try {
|
||||
const parsed = JSON.parse(
|
||||
await fs.readFile(path.join(catalogStateRoot(), FILE), "utf8"),
|
||||
) as { revision?: unknown };
|
||||
return typeof parsed.revision === "string" ? parsed.revision : null;
|
||||
} catch (error) {
|
||||
// A missing file means "no revision yet", which every client reads as
|
||||
// stale — the correct answer on a fresh install.
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
|
||||
logger.error("Cannot read catalog revision", {
|
||||
module: "catalog",
|
||||
error,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import path from "node:path";
|
||||
import { logger } from "@/lib/logger";
|
||||
import { catalogStateRoot } from "@/lib/services/catalog-git-config";
|
||||
import { rcon } from "@/lib/services/rcon";
|
||||
import { bumpCatalogRevision } from "./catalog-revision";
|
||||
import { invalidateCatalogTotals } from "./catalog-totals";
|
||||
export interface CatalogHotelStatus {
|
||||
sent: boolean;
|
||||
@@ -44,6 +45,10 @@ export async function sendCatalogUpdate(): Promise<CatalogHotelStatus> {
|
||||
// Callers reach here only after writing catalog rows, so the admin stats
|
||||
// totals must not keep serving the pre-write numbers from their 30s cache.
|
||||
invalidateCatalogTotals();
|
||||
// Every catalog write lands here, which makes this the one place that can
|
||||
// tell open admin sessions their tree is stale — including writes made by a
|
||||
// different tab, browser or process than the one watching.
|
||||
await bumpCatalogRevision();
|
||||
const status = { sent, checkedAt: new Date().toISOString(), reference };
|
||||
const root = catalogStateRoot();
|
||||
const temp = path.join(root, `hotel-${randomUUID()}.tmp`);
|
||||
|
||||
Reference in new issue
Block a user