fix(storage): repair orphaned KV routes

Repair orphaned KV routes before serving KV-only configuration.
This commit is contained in:
RhenCloud committed 2026-10-24 15:47:39 +08:00
1 parent 5fcb129170
commit 714953bb76
2 files changed
+32 -1

No files matched your search

+16 -1
View File
@@ -1147,7 +1147,22 @@ export function kvConfigStore(kv: KVNamespace): ConfigStore {
const raw = await kv.get<T[]>(key, "json");
return Array.isArray(raw) ? raw : [];
}
const loadRoutes = async (): Promise<Route[]> => migrateRoutes(await readList(KV_ROUTES_KEY));
/**
* KV has no transaction spanning the group and route lists. A rename can
* therefore be interrupted between its writes, leaving routes under an id
* that is no longer a group (or under the new id before that group exists).
* Never serve those orphaned routes: they could otherwise be inherited by a
* later group that reuses the id. Repair the permanent route list while it
* is read so every public load path gets the same safety boundary.
*/
const loadRoutes = async (): Promise<Route[]> => {
const routes = migrateRoutes(await readList<Route>(KV_ROUTES_KEY));
const groups = migrateGroups(await readList<Group>(KV_GROUPS_KEY));
const groupIds = new Set(groups.map((g) => g.id));
const kept = routes.filter((route) => !route.groupId || groupIds.has(route.groupId));
if (kept.length !== routes.length) await kv.put(KV_ROUTES_KEY, JSON.stringify(kept));
return kept;
};
let identitiesMigrated = false;
const loadGroups = async (): Promise<Group[]> => {
let groups = migrateGroups(await readList<Group>(KV_GROUPS_KEY));
+16
View File
@@ -380,6 +380,22 @@ describe("kvConfigStore", () => {
expect(JSON.parse(store.get("config:routes")!)).toEqual([]);
});
it("repairs orphaned routes before a reused group id can inherit them", async () => {
const { kv, store } = createMemoryKV();
store.set("config:groups", JSON.stringify([group("current")]));
store.set(
"config:routes",
JSON.stringify([route("orphan", "reused"), route("live", "current")]),
);
const cfg = kvConfigStore(kv);
expect((await cfg.loadRoutes()).map((r) => r.id)).toEqual(["live"]);
expect(JSON.parse(store.get("config:routes")!)).toEqual([route("live", "current")]);
await expect(cfg.createGroup(group("reused"))).resolves.toBe(true);
expect((await cfg.loadRoutes()).map((r) => r.id)).toEqual(["live"]);
});
it("backfills the same instance whichever cold start wins the race", async () => {
const { kv, store } = createMemoryKV();
store.set("config:groups", JSON.stringify([group("legacy")]));