mirror of
https://github.com/Moepchi/webspeak3.git
synced 2026-12-03 01:42:50 +08:00
gateway: serialize write-then-rename per file
Every JSON store (ping, store, news, sync, admin auth, config) wrote to one shared "<file>.tmp" and renamed it. Parallel requests raced on that path: one rename won, the others failed with ENOENT, and overlapping writes could leave a mangled file that reads as empty after a restart. Seen live from a parallel /api/ping probe. writeFileAtomic() in net.ts queues writes per file, so the last caller's data always lands last. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
This commit is contained in:
1 parent
54a580dc39
commit
f2d9115782
8 files changed
+55
-28
No files matched your search
+3
-5
@@ -4,8 +4,8 @@
|
||||
// row per instance id: version, first and last seen. No IP addresses, no
|
||||
// request log. The admin view returns counts only.
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { readFile, rename, writeFile } from "node:fs/promises";
|
||||
import { clientIp, createRateLimiter } from "./net.js";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { clientIp, createRateLimiter, writeFileAtomic } from "./net.js";
|
||||
import { isAdminRequest } from "./store.js";
|
||||
|
||||
const PING_DATA_FILE = process.env.PING_DATA_FILE;
|
||||
@@ -36,9 +36,7 @@ async function save(instances: Record<string, Instance>) {
|
||||
// Instances silent for 90 days are gone for good.
|
||||
const cutoff = Date.now() - 90 * DAY_MS;
|
||||
for (const [id, i] of Object.entries(instances)) if (Date.parse(i.lastSeen) < cutoff) delete instances[id];
|
||||
const tmp = `${PING_DATA_FILE}.tmp`;
|
||||
await writeFile(tmp, JSON.stringify(instances), "utf-8");
|
||||
await rename(tmp, PING_DATA_FILE!);
|
||||
await writeFileAtomic(PING_DATA_FILE!, JSON.stringify(instances));
|
||||
}
|
||||
|
||||
function json(res: ServerResponse, status: number, body: unknown) {
|
||||
|
||||
Reference in new issue
Block a user