Public: anyone can read this; the crew can change it.

The access log's rotate and prune leave the serving thread #17901

opened this

Merged 25h 23m ago, live in production

torque/forge:torque/17884-the-access-log-s-rotate-and-prune-leave → main 0 commits fork

  • Merged. torque/17884-the-access-log-s-rotate-and-prune-leave was merged into main as ff13e06.

Review

Sign in to review this change.
4 files changed +270 −40
src/http/access_log.ts +151 −32
@@ -12,7 +12,9 @@
1212 * other than the user agent, cookies, bodies and queries are never read.
1313 *
1414 * Files older than 14 days go, and the directory is capped in total, oldest
15 * first; one day's file sheds its older half at its own cap, so it never stops. Nothing here is served
15 * first; one day's file sheds its older half at its own cap, so it never stops. Pruning and
16 * shedding run as a background pass a file call a tick (#17884); the append never waits on them.
17 * Nothing here is served
1618 * by any route; the owner reads it through `readAccess` (a settings page and
1719 * the `access` MCP tool).
1820 */
@@ -28,11 +30,12 @@ import {
2830 readSync,
2931 statSync,
3032 unlinkSync,
31 writeFileSync,
33 writeSync,
3234 } from "node:fs";
3335 import { createHmac } from "node:crypto";
3436 import { join } from "node:path";
3537 import { loadKey } from "../kernel/secret.ts";
38 import { breathe } from "../kernel/breathe.ts";
3639
3740 export const KEEP_DAYS = 14;
3841 export const DAY_BYTES = 16 * 1024 * 1024;
@@ -156,39 +159,131 @@ export function lineFor(
156159
157160 let pruned = "";
158161
159 /** Drop files past their days, then the oldest until the directory fits. */
160 export function prune(dataDir: string, at: Date, cap: number = TOTAL_BYTES): void {
161 const dir = accessDir(dataDir);
162 const oldest = dayOf(new Date(at.getTime() - (KEEP_DAYS - 1) * DAY_MS));
163 const files = readdirSync(dir)
164 .filter((f) => /^access-\d{4}-\d{2}-\d{2}\.log$/.test(f))
165 .sort();
166 const kept: string[] = [];
167 for (const f of files) {
168 if (f.slice(7, 17) < oldest) unlinkSync(join(dir, f));
169 else kept.push(f);
170 }
171 let total = kept.reduce((n, f) => n + statSync(join(dir, f)).size, 0);
172 for (const f of kept) {
173 if (total <= cap || f === kept[kept.length - 1]) break;
174 total -= statSync(join(dir, f)).size;
175 unlinkSync(join(dir, f));
162 /**
163 * The file calls keeping makes, and how it hands the thread back between them. A test swaps in
164 * counting ones to show no tick holds more than a few calls (#17884).
165 */
166 const DISK = {
167 readdirSync,
168 statSync,
169 unlinkSync,
170 openSync,
171 readSync,
172 writeSync,
173 closeSync,
174 renameSync,
175 };
176 type Keeping = { readonly disk: typeof DISK; readonly pause: () => Promise<void> };
177 const KEEPING: Keeping = { disk: DISK, pause: breathe };
178 /** One shed slice: a read and a write this size hold the thread well under a millisecond. */
179 const CHUNK = 1024 * 1024;
180 /** The last keeping pass queued: each waits for the one before, so two never cut one file. */
181 let keeping: Promise<void> = Promise.resolve();
182
183 /** `fn`, with a file another pod already removed read as done. */
184 function unlessGone(fn: () => void): void {
185 try {
186 fn();
187 } catch (error) {
188 if ((error as { code?: string }).code !== "ENOENT") throw error;
176189 }
177190 }
178191
179192 /**
180 * Keep the newest half of a file, from a whole line: written beside it and
181 * renamed over it, so a crash never leaves an empty day. A line another pod
182 * appends to the old file between the read and the rename can still be lost.
183 * Never throws.
193 * Drop files past their days, then the oldest until the directory fits. One file call a tick
194 * (#17884): forty day files are forty short turns, never one long one.
184195 */
185 function shedOlder(file: string): void {
196 export async function prune(
197 dataDir: string,
198 at: Date,
199 cap: number = TOTAL_BYTES,
200 k: Keeping = KEEPING,
201 ): Promise<void> {
202 const dir = accessDir(dataDir);
203 const oldest = dayOf(new Date(at.getTime() - (KEEP_DAYS - 1) * DAY_MS));
204 const files = k.disk.readdirSync(dir)
205 .filter((f) => /^access-\d{4}-\d{2}-\d{2}\.log$/.test(f))
206 .sort();
207 const kept: string[] = [];
208 for (const f of files) {
209 if (f.slice(7, 17) >= oldest) {
210 kept.push(f);
211 continue;
212 }
213 await k.pause();
214 unlessGone(() => k.disk.unlinkSync(join(dir, f)));
215 }
216 const sizes: number[] = [];
217 for (const f of kept) {
218 await k.pause();
219 let size = 0;
220 unlessGone(() => (size = k.disk.statSync(join(dir, f)).size));
221 sizes.push(size);
222 }
223 let total = sizes.reduce((n, s) => n + s, 0);
224 for (const [i, f] of kept.entries()) {
225 if (total <= cap || i === kept.length - 1) break;
226 total -= sizes[i]!;
227 await k.pause();
228 unlessGone(() => k.disk.unlinkSync(join(dir, f)));
229 }
230 }
231
232 /**
233 * Keep the newest half of a file, from a whole line: copied beside it a chunk a tick and renamed
234 * over it, so a crash never leaves an empty day. Lines this process appends meanwhile land on the
235 * old file and are copied too: the last tick reads the size and renames in one synchronous step,
236 * so no append comes between them and none is lost or doubled (#17884). A line another pod
237 * appends between that step's read and its rename can still be lost.
238 */
239 async function shedOlder(file: string, k: Keeping): Promise<void> {
240 const { disk } = k;
186241 const tmp = `${file}.tmp`;
242 const from = disk.openSync(file, "r");
243 let to: number | undefined;
187244 try {
188 writeFileSync(tmp, tailOf(file, DAY_BYTES / 2).join("\n"), { mode: 0o600 });
189 renameSync(tmp, file);
190 } catch {
191 // appending still works on the long file
245 const buffer = Buffer.alloc(CHUNK);
246 let pos = -1;
247 let first = false;
248 for (;;) {
249 if (pos >= 0) await k.pause();
250 const end = disk.statSync(file).size;
251 let w = 0;
252 if (pos < 0) {
253 // A shed queued behind one that already cut this file has nothing to do.
254 if (end < DAY_BYTES) return;
255 pos = end - DAY_BYTES / 2;
256 first = true;
257 to = disk.openSync(tmp, "w", 0o600);
258 }
259 const n = end > pos ? disk.readSync(from, buffer, 0, Math.min(CHUNK, end - pos), pos) : 0;
260 if (n === 0 && end > pos) throw new Error("the access log was cut under its shed");
261 // A cut file begins part-way through a line: drop that line.
262 if (first && n > 0) {
263 first = false;
264 const nl = buffer.indexOf(10);
265 w = nl >= 0 && nl < n ? nl + 1 : 0;
266 }
267 while (w < n) w += disk.writeSync(to!, buffer, w, n - w);
268 pos += n;
269 // The last chunk and the rename share a tick: lines keep landing, and the copy still ends.
270 if (pos >= end) {
271 disk.closeSync(to!);
272 to = undefined;
273 disk.renameSync(tmp, file);
274 return;
275 }
276 }
277 } finally {
278 if (to !== undefined) {
279 disk.closeSync(to);
280 try {
281 disk.unlinkSync(tmp);
282 } catch {
283 // nothing was left behind
284 }
285 }
286 disk.closeSync(from);
192287 }
193288 }
194289
@@ -216,13 +311,22 @@ let timer: ReturnType<typeof setTimeout> | undefined;
216311 const FLUSH_MS = 1000;
217312 const FLUSH_LINES = 200;
218313
219 /** Write everything that waits, one append per file. Never throws. */
220 export function flushAccess(at: Date = new Date()): void {
314 /**
315 * Write everything that waits, one append per file, now. Pruning a new day and shedding a full
316 * file run after it as a background pass that hands the thread back between file calls (#17884),
317 * queued behind any pass still running; the promise settles when this flush's pass is done, and
318 * never rejects.
319 */
320 export function flushAccess(
321 at: Date = new Date(),
322 k: Keeping = KEEPING,
323 ): Promise<void> {
221324 clearTimeout(timer);
222325 timer = undefined;
223326 const batches = [...pending];
224327 pending.clear();
225328 let failed = false;
329 const jobs: (() => Promise<void>)[] = [];
226330 for (const [file, { dataDir, lines }] of batches) {
227331 try {
228332 const dir = accessDir(dataDir);
@@ -230,7 +334,7 @@ export function flushAccess(at: Date = new Date()): void {
230334 const day = dayOf(at);
231335 if (pruned !== `${dir}:${day}`) {
232336 pruned = `${dir}:${day}`;
233 prune(dataDir, at);
337 jobs.push(() => prune(dataDir, at, TOTAL_BYTES, k));
234338 }
235339 let size = 0;
236340 try {
@@ -239,7 +343,8 @@ export function flushAccess(at: Date = new Date()): void {
239343 // no file yet
240344 }
241345 // A full day's file sheds its older half: the trail never goes silent.
242 if (size >= DAY_BYTES) shedOlder(file);
346 // Passes run one after another, and a shed finds a file already cut and stops there.
347 if (size >= DAY_BYTES) jobs.push(() => shedOlder(file, k));
243348 appendFileSync(file, lines.join(""), { mode: 0o600 });
244349 } catch {
245350 // the log is a convenience; the request is the work
@@ -248,6 +353,20 @@ export function flushAccess(at: Date = new Date()): void {
248353 }
249354 // The mark clears only when every line landed and none wait.
250355 if (!failed && pending.size === 0) unwritten = undefined;
356 if (jobs.length > 0) {
357 keeping = keeping.then(() =>
358 background("access-keep", async () => {
359 for (const job of jobs) {
360 try {
361 await job();
362 } catch {
363 // appending still works on the long file; the next day prunes again
364 }
365 }
366 }),
367 );
368 }
369 return keeping;
251370 }
252371
253372 /**
test/access-log.test.ts +116 −5
@@ -6,11 +6,25 @@
66 */
77
88 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
9 import {
10 closeSync,
11 mkdirSync,
12 openSync,
13 readdirSync,
14 readFileSync,
15 readSync,
16 renameSync,
17 statSync,
18 unlinkSync,
19 writeFileSync,
20 writeSync,
21 type Stats,
22 } from "node:fs";
1023 import { mkdtemp, rm } from "node:fs/promises";
1124 import { tmpdir } from "node:os";
1225 import { join } from "node:path";
1326 import { createApp, type App } from "../src/app.ts";
27 import { breathe } from "../src/kernel/breathe.ts";
1428 import { createToken } from "../src/core/tokens.ts";
1529 import { createUser } from "../src/core/users.ts";
1630 import {
@@ -195,7 +209,7 @@ describe("the access log's keeping", () => {
195209 writeFileSync(join(keep, "access-2026-09-01.log"), "old\n");
196210 writeFileSync(join(keep, "access-2026-09-30.log"), "recent\n");
197211 const now = new Date("2026-10-13T12:00:00Z");
198 prune(dir, now);
212 await prune(dir, now);
199213 expect(readdirSync(keep)).toEqual(["access-2026-09-30.log"]);
200214 // Over the cap: the oldest goes first, today's file always stays.
201215 const cap = 1024;
@@ -203,7 +217,7 @@ describe("the access log's keeping", () => {
203217 writeFileSync(join(keep, "access-2026-10-10.log"), big);
204218 writeFileSync(join(keep, "access-2026-10-11.log"), big);
205219 writeFileSync(join(keep, "access-2026-10-13.log"), "today\n");
206 prune(dir, now, cap);
220 await prune(dir, now, cap);
207221 expect(readdirSync(keep).sort()).toEqual([
208222 "access-2026-10-11.log",
209223 "access-2026-10-13.log",
@@ -230,7 +244,7 @@ describe("the access log's keeping", () => {
230244 recordAccess(dir, seen("/llms.txt"), new Date("2026-10-14T01:00:00Z"));
231245 // Batched: a request has only queued its line.
232246 expect(readdirSync(accessDir(dir))).toEqual(["access-2026-09-01.log"]);
233 flushAccess(new Date("2026-10-14T01:00:00Z"));
247 await flushAccess(new Date("2026-10-14T01:00:00Z"));
234248 expect(readdirSync(accessDir(dir)).sort()).toEqual([
235249 "access-2026-10-13.log",
236250 "access-2026-10-14.log",
@@ -338,7 +352,7 @@ describe("the access log never goes silent (#6841)", () => {
338352 const filler = `${JSON.stringify({ t: "x", path: "/old" })}\n`;
339353 writeFileSync(file, filler.repeat(Math.ceil(DAY_BYTES / filler.length) + 1));
340354 recordAccess(dir, seen("/issues/new"), at);
341 flushAccess(at);
355 await flushAccess(at);
342356 const text = readFileSync(file, "utf8");
343357 expect(text).toContain("/issues/new");
344358 expect(text.length).toBeLessThan(DAY_BYTES);
@@ -367,3 +381,100 @@ describe("the access log never goes silent (#6841)", () => {
367381 }
368382 });
369383 });
384
385 describe("the access log's keeping hands the thread back (#17884)", () => {
386 const seen = (path: string) => ({
387 request: new Request(`http://forge.test${path}`),
388 status: 200,
389 ms: 1,
390 client: "1.2.3.4",
391 });
392
393 /** The real file calls, counted between two pauses; `between` runs at each pause. */
394 const counting = (between: () => void = () => {}) => {
395 const ticks: number[] = [0];
396 const tally = <A extends unknown[], R>(fn: (...a: A) => R) => (...a: A): R => {
397 ticks[ticks.length - 1]! += 1;
398 return fn(...a);
399 };
400 const disk = {
401 readdirSync: tally(readdirSync as (p: string) => string[]),
402 statSync: tally(statSync as (p: string) => Stats),
403 unlinkSync: tally(unlinkSync),
404 openSync: tally(openSync),
405 readSync: tally(readSync as (fd: number, b: Buffer, o: number, l: number, p: number) => number),
406 writeSync: tally(writeSync as (fd: number, b: Buffer, o: number, l: number) => number),
407 closeSync: tally(closeSync),
408 renameSync: tally(renameSync),
409 };
410 const pause = async () => {
411 between();
412 ticks.push(0);
413 await breathe();
414 };
415 return { ticks, keeping: { disk, pause } as Parameters<typeof flushAccess>[1] };
416 };
417
418 test("forty day files and a full current file are kept a few calls a tick", async () => {
419 const dir = await mkdtemp(join(tmpdir(), "access-slices-"));
420 try {
421 const keep = accessDir(dir);
422 mkdirSync(keep, { recursive: true });
423 const at = new Date("2026-11-30T10:00:00Z");
424 for (let i = 1; i <= 40; i++) {
425 const day = new Date(at.getTime() - i * 86_400_000).toISOString().slice(0, 10);
426 writeFileSync(join(keep, `access-${day}.log`), "old\n");
427 }
428 const file = join(keep, "access-2026-11-30.log");
429 const filler = `${JSON.stringify({ t: "x", path: "/old" })}\n`;
430 writeFileSync(file, filler.repeat(Math.ceil(DAY_BYTES / filler.length) + 1));
431 const { ticks, keeping } = counting();
432 recordAccess(dir, seen("/issues/new"), at);
433 await flushAccess(at, keeping);
434 // Before: one tick made ~60 calls (40 unlinks, 14 stats, a 16 MB read and an 8 MB write).
435 // After: dozens of ticks, none over six calls, the biggest a 1 MB read and its write.
436 expect(ticks.length).toBeGreaterThan(40);
437 expect(Math.max(...ticks)).toBeLessThanOrEqual(6);
438 const left = readdirSync(keep).sort();
439 expect(left).toHaveLength(14);
440 expect(left.at(-1)).toBe("access-2026-11-30.log");
441 const text = readFileSync(file, "utf8");
442 expect(text.length).toBeLessThanOrEqual(DAY_BYTES / 2 + 1024);
443 expect(text.startsWith(filler)).toBe(true);
444 expect(text).toContain("/issues/new");
445 } finally {
446 await rm(dir, { recursive: true, force: true });
447 }
448 });
449
450 test("lines recorded while a full file sheds land once each, none lost", async () => {
451 const dir = await mkdtemp(join(tmpdir(), "access-shed-lines-"));
452 try {
453 const at = new Date("2026-11-30T10:00:00Z");
454 mkdirSync(accessDir(dir), { recursive: true });
455 const file = join(accessDir(dir), "access-2026-11-30.log");
456 const filler = `${JSON.stringify({ t: "x", path: "/old" })}\n`;
457 writeFileSync(file, filler.repeat(Math.ceil(DAY_BYTES / filler.length) + 1));
458 // Each tick of the shed, a request lands and is flushed onto the file being copied.
459 let n = 0;
460 const { ticks, keeping } = counting(() => {
461 recordAccess(dir, seen(`/issues/during-${n++}`), at);
462 void flushAccess(at, keeping);
463 });
464 recordAccess(dir, seen("/issues/first"), at);
465 await flushAccess(at, keeping);
466 expect(ticks.length).toBeGreaterThan(4);
467 recordAccess(dir, seen("/issues/after"), at);
468 await flushAccess(at);
469 const paths = readFileSync(file, "utf8")
470 .trim()
471 .split("\n")
472 .map((l) => JSON.parse(l).path as string)
473 .filter((p) => p !== "/old");
474 const want = ["/issues/first", ...Array.from({ length: n }, (_, i) => `/issues/during-${i}`), "/issues/after"];
475 expect(paths).toEqual(want);
476 } finally {
477 await rm(dir, { recursive: true, force: true });
478 }
479 });
480 });
test/job-slices.test.ts +1
@@ -385,6 +385,7 @@ const UNTIMED: Record<string, string> = {
385385 "route-timing-flush": "a debounced write of route timings: runs after requests, the jobs here make none",
386386 "usage-count-flush": "a debounced write of usage counts: runs after requests, the jobs here make none",
387387 "access-flush": "a debounced write of the access log: runs after requests, the jobs here make none",
388 "access-keep": "the access log's prune and shed after a day change or a full file: a few file calls a tick between breaths, counted per tick in access-log.test.ts (#17884); the jobs here make no requests",
388389 "egress-refused-flush": "a debounced write of an app's refused hosts; needs the egress proxy and apps",
389390 "nightly-output-flush": "a debounced write of a nightly job's output: inside a nightly run",
390391 "home-refresh": "redraws a stale home panel after a request; the jobs here make no requests",
test/request-path-sync.test.ts +2 −3
@@ -36,13 +36,12 @@ const ALLOWED: Record<string, Partial<Record<SyncCall, Allowed>>> = {
3636 "src/http/access_log.ts": {
3737 readdirSync: {
3838 count: 2,
39 reason: "prune runs once a day per directory inside the batched flush; readAccess lists at most 14 day files for an owner's settings page",
39 reason: "prune runs once a day per directory as a background pass, one file call a tick (#17884); readAccess lists at most 14 day files for an owner's settings page",
4040 },
4141 statSync: {
4242 count: 4,
43 reason: "batched: flushAccess runs once a second on a timer (or on the 200th waiting line), once per day file, and prune at most once a day",
43 reason: "batched: flushAccess runs once a second on a timer (or on the 200th waiting line), once per day file; prune and the shed stat one file a tick in a background pass (#17884)",
4444 },
45 writeFileSync: { count: 1, reason: "rare: shedOlder runs only when a day's file reaches its cap, writing half of it once" },
4645 appendFileSync: { count: 1, reason: "batched: one append per day file a flush, once a second on a timer, never one per request" },
4746 },
4847 "src/web/pages/security.ts": {

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs