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

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:
openhandsandClaude Opus 4.8 committed 2026-09-30 15:15:34 +02:00
1 parent 28ce0f911c
commit 9550b3d66f
18 files changed
+1016 -973

No files matched your search

@@ -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`);