mirror of
https://github.com/Moepchi/webspeak3.git
synced 2026-12-03 09:52: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
@@ -11,11 +11,10 @@ import type { IncomingMessage, ServerResponse } from "node:http";
|
|||||||
import type { TLSSocket } from "node:tls";
|
import type { TLSSocket } from "node:tls";
|
||||||
import { createHash, createHmac, randomBytes, scrypt, timingSafeEqual } from "node:crypto";
|
import { createHash, createHmac, randomBytes, scrypt, timingSafeEqual } from "node:crypto";
|
||||||
import { readFileSync } from "node:fs";
|
import { readFileSync } from "node:fs";
|
||||||
import { rename, writeFile } from "node:fs/promises";
|
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { promisify } from "node:util";
|
import { promisify } from "node:util";
|
||||||
import qrcode from "qrcode-generator";
|
import qrcode from "qrcode-generator";
|
||||||
import { clientIp, createRateLimiter } from "./net.js";
|
import { clientIp, createRateLimiter, writeFileAtomic } from "./net.js";
|
||||||
import { describeSettings, updateSettings, validate } from "./config.js";
|
import { describeSettings, updateSettings, validate } from "./config.js";
|
||||||
|
|
||||||
const ADMIN_USER = process.env.ADMIN_USER ?? "";
|
const ADMIN_USER = process.env.ADMIN_USER ?? "";
|
||||||
@@ -36,9 +35,7 @@ try {
|
|||||||
}
|
}
|
||||||
const totpSecret = () => auth.totpSecret ?? ENV_TOTP;
|
const totpSecret = () => auth.totpSecret ?? ENV_TOTP;
|
||||||
async function saveAuth(next: typeof auth) {
|
async function saveAuth(next: typeof auth) {
|
||||||
const tmp = `${AUTH_FILE}.${process.pid}.tmp`;
|
await writeFileAtomic(AUTH_FILE, JSON.stringify(next, null, 2), 0o600);
|
||||||
await writeFile(tmp, JSON.stringify(next, null, 2), { mode: 0o600 });
|
|
||||||
await rename(tmp, AUTH_FILE);
|
|
||||||
auth = next;
|
auth = next;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
// Deliberately absent: CONNECTOR_BIN (would be code execution), ALLOW_PRIVATE_TARGETS (opens the
|
// Deliberately absent: CONNECTOR_BIN (would be code execution), ALLOW_PRIVATE_TARGETS (opens the
|
||||||
// operator's LAN), and the admin credentials themselves.
|
// operator's LAN), and the admin credentials themselves.
|
||||||
import { readFileSync } from "node:fs";
|
import { readFileSync } from "node:fs";
|
||||||
import { rename, writeFile } from "node:fs/promises";
|
import { writeFileAtomic } from "./net.js";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
|
|
||||||
export type SettingKind = "number" | "bool" | "list" | "text" | "secret";
|
export type SettingKind = "number" | "bool" | "list" | "text" | "secret";
|
||||||
@@ -116,9 +116,7 @@ export async function updateSettings(changes: Record<string, string | null>): Pr
|
|||||||
if (value === null) delete next[key];
|
if (value === null) delete next[key];
|
||||||
else next[key] = value;
|
else next[key] = value;
|
||||||
}
|
}
|
||||||
const tmp = `${CONFIG_FILE}.${process.pid}.tmp`;
|
await writeFileAtomic(CONFIG_FILE, JSON.stringify(next, null, 2), 0o600);
|
||||||
await writeFile(tmp, JSON.stringify(next, null, 2), { mode: 0o600 });
|
|
||||||
await rename(tmp, CONFIG_FILE);
|
|
||||||
overrides = next;
|
overrides = next;
|
||||||
apply();
|
apply();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { IncomingMessage } from "node:http";
|
import type { IncomingMessage } from "node:http";
|
||||||
|
import { rename, writeFile } from "node:fs/promises";
|
||||||
|
|
||||||
// Behind a reverse proxy / tunnel every request arrives from the proxy's own
|
// Behind a reverse proxy / tunnel every request arrives from the proxy's own
|
||||||
// address, so per-IP limits would lump all users into one bucket. Only set
|
// address, so per-IP limits would lump all users into one bucket. Only set
|
||||||
@@ -38,3 +39,21 @@ export function createRateLimiter(limit: number | (() => number), windowMs: numb
|
|||||||
return recent.length > (typeof limit === "function" ? limit() : limit);
|
return recent.length > (typeof limit === "function" ? limit() : limit);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Write-then-rename, one write at a time per file. Concurrent requests used
|
||||||
|
* to share one `.tmp` path: one rename won, the others failed with ENOENT,
|
||||||
|
* and overlapping writes could leave a mangled file. Queued, the last caller's
|
||||||
|
* data always lands last. */
|
||||||
|
const writeQueues = new Map<string, Promise<void>>();
|
||||||
|
export function writeFileAtomic(file: string, data: string, mode?: number): Promise<void> {
|
||||||
|
const run = async () => {
|
||||||
|
const tmp = `${file}.tmp`;
|
||||||
|
await writeFile(tmp, data, { encoding: "utf-8", mode });
|
||||||
|
await rename(tmp, file);
|
||||||
|
};
|
||||||
|
const done = (writeQueues.get(file) ?? Promise.resolve()).then(run);
|
||||||
|
const tail = done.catch(() => {});
|
||||||
|
writeQueues.set(file, tail);
|
||||||
|
void tail.then(() => { if (writeQueues.get(file) === tail) writeQueues.delete(file); });
|
||||||
|
return done;
|
||||||
|
}
|
||||||
+3
-4
@@ -13,7 +13,8 @@
|
|||||||
//
|
//
|
||||||
// Like store.ts, this file has zero private modifications.
|
// Like store.ts, this file has zero private modifications.
|
||||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||||
import { readFile, rename, writeFile } from "node:fs/promises";
|
import { readFile } from "node:fs/promises";
|
||||||
|
import { writeFileAtomic } from "./net.js";
|
||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
import { isAdminRequest, latestPublicTheme } from "./store.js";
|
import { isAdminRequest, latestPublicTheme } from "./store.js";
|
||||||
|
|
||||||
@@ -43,9 +44,7 @@ async function load(): Promise<TextItem[]> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function save(items: TextItem[]) {
|
async function save(items: TextItem[]) {
|
||||||
const tmp = `${NEWS_DATA_FILE}.tmp`;
|
await writeFileAtomic(NEWS_DATA_FILE!, JSON.stringify(items));
|
||||||
await writeFile(tmp, JSON.stringify(items), "utf-8");
|
|
||||||
await rename(tmp, NEWS_DATA_FILE!);
|
|
||||||
cache = items;
|
cache = items;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+3
-5
@@ -4,8 +4,8 @@
|
|||||||
// row per instance id: version, first and last seen. No IP addresses, no
|
// row per instance id: version, first and last seen. No IP addresses, no
|
||||||
// request log. The admin view returns counts only.
|
// request log. The admin view returns counts only.
|
||||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||||
import { readFile, rename, writeFile } from "node:fs/promises";
|
import { readFile } from "node:fs/promises";
|
||||||
import { clientIp, createRateLimiter } from "./net.js";
|
import { clientIp, createRateLimiter, writeFileAtomic } from "./net.js";
|
||||||
import { isAdminRequest } from "./store.js";
|
import { isAdminRequest } from "./store.js";
|
||||||
|
|
||||||
const PING_DATA_FILE = process.env.PING_DATA_FILE;
|
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.
|
// Instances silent for 90 days are gone for good.
|
||||||
const cutoff = Date.now() - 90 * DAY_MS;
|
const cutoff = Date.now() - 90 * DAY_MS;
|
||||||
for (const [id, i] of Object.entries(instances)) if (Date.parse(i.lastSeen) < cutoff) delete instances[id];
|
for (const [id, i] of Object.entries(instances)) if (Date.parse(i.lastSeen) < cutoff) delete instances[id];
|
||||||
const tmp = `${PING_DATA_FILE}.tmp`;
|
await writeFileAtomic(PING_DATA_FILE!, JSON.stringify(instances));
|
||||||
await writeFile(tmp, JSON.stringify(instances), "utf-8");
|
|
||||||
await rename(tmp, PING_DATA_FILE!);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function json(res: ServerResponse, status: number, body: unknown) {
|
function json(res: ServerResponse, status: number, body: unknown) {
|
||||||
|
|||||||
@@ -11,10 +11,10 @@
|
|||||||
// touched. It has zero private modifications, so the overlay just copies it
|
// touched. It has zero private modifications, so the overlay just copies it
|
||||||
// verbatim; only index.ts's small SQLite-persistence sections need patching.
|
// verbatim; only index.ts's small SQLite-persistence sections need patching.
|
||||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||||
import { readFile, rename, writeFile } from "node:fs/promises";
|
import { readFile } from "node:fs/promises";
|
||||||
import { timingSafeEqual, randomUUID } from "node:crypto";
|
import { timingSafeEqual, randomUUID } from "node:crypto";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { clientIp, createRateLimiter } from "./net.js";
|
import { clientIp, createRateLimiter, writeFileAtomic } from "./net.js";
|
||||||
|
|
||||||
const storeAllowedOrigin = () => process.env.STORE_ALLOWED_ORIGIN || "*";
|
const storeAllowedOrigin = () => process.env.STORE_ALLOWED_ORIGIN || "*";
|
||||||
// Plain JSON file (whole-array read-modify-write, not JSON-lines like
|
// Plain JSON file (whole-array read-modify-write, not JSON-lines like
|
||||||
@@ -134,9 +134,7 @@ async function saveStoreThemes(themes: StoreTheme[]): Promise<void> {
|
|||||||
storeCache = themes;
|
storeCache = themes;
|
||||||
// Write-then-rename: a crash mid-write must not leave a truncated file,
|
// Write-then-rename: a crash mid-write must not leave a truncated file,
|
||||||
// which loadStoreThemes() would read as "no themes" and then overwrite.
|
// which loadStoreThemes() would read as "no themes" and then overwrite.
|
||||||
const tmp = `${STORE_DATA_FILE}.tmp`;
|
await writeFileAtomic(STORE_DATA_FILE, JSON.stringify(themes));
|
||||||
await writeFile(tmp, JSON.stringify(themes), "utf-8");
|
|
||||||
await rename(tmp, STORE_DATA_FILE);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isAdminRequest(req: IncomingMessage): boolean {
|
export function isAdminRequest(req: IncomingMessage): boolean {
|
||||||
|
|||||||
+3
-5
@@ -8,9 +8,9 @@
|
|||||||
// One JSON file per account in SYNC_DATA_DIR. Only served by sync-server.ts.
|
// One JSON file per account in SYNC_DATA_DIR. Only served by sync-server.ts.
|
||||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||||
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||||
import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
import { mkdir, readdir, readFile, rm } from "node:fs/promises";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { clientIp, createRateLimiter } from "./net.js";
|
import { clientIp, createRateLimiter, writeFileAtomic } from "./net.js";
|
||||||
|
|
||||||
const SYNC_DATA_DIR = process.env.SYNC_DATA_DIR;
|
const SYNC_DATA_DIR = process.env.SYNC_DATA_DIR;
|
||||||
const SYNC_ALLOWED_ORIGIN = process.env.SYNC_ALLOWED_ORIGIN ?? "*";
|
const SYNC_ALLOWED_ORIGIN = process.env.SYNC_ALLOWED_ORIGIN ?? "*";
|
||||||
@@ -76,9 +76,7 @@ async function load(id: string): Promise<Account | null> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function save(id: string, account: Account) {
|
async function save(id: string, account: Account) {
|
||||||
const tmp = `${file(id)}.tmp`;
|
await writeFileAtomic(file(id), JSON.stringify(account));
|
||||||
await writeFile(tmp, JSON.stringify(account), "utf-8");
|
|
||||||
await rename(tmp, file(id));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Writes to one account run one after another, so the version check can't race.
|
// Writes to one account run one after another, so the version check can't race.
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
// Concurrent saves to one file used to share a .tmp path: all but one rename
|
||||||
|
// failed with ENOENT (seen live from a parallel /api/ping probe).
|
||||||
|
import { test } from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
|
import { writeFileAtomic } from "../dist/net.js";
|
||||||
|
|
||||||
|
test("parallel writes to one file all succeed, last one wins", async () => {
|
||||||
|
const dir = mkdtempSync(path.join(tmpdir(), "ws3-atomic-"));
|
||||||
|
try {
|
||||||
|
const file = path.join(dir, "data.json");
|
||||||
|
await Promise.all(Array.from({ length: 50 }, (_, i) => writeFileAtomic(file, JSON.stringify({ i, pad: "x".repeat(i * 500) }))));
|
||||||
|
assert.equal(JSON.parse(readFileSync(file, "utf-8")).i, 49);
|
||||||
|
assert.deepEqual(readdirSync(dir), ["data.json"]);
|
||||||
|
} finally {
|
||||||
|
rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
Reference in new issue
Block a user