feat(diigo-cache): refresh each cache every 3 hours

workerd has no cron triggers, but it runs Durable Object alarms, and
the cache DOs already hold their wiring to the webapp: a refresh
scheduled from inside the DO needs no credential outside it (a systemd
timer would need a cache id to call /api with).

A fill that ends (done or failed) sets an alarm 3 hours out; it starts
a fill that refetches every page through the deepest one holding an
item updated in the last 2 days (page 1 at least, where new bookmarks
land). Refetching overwrites pages in place rather than dropping them
first, so a refresh that fails leaves the cache as it was. stopFill now
also stops a finished job's refreshes.

FillStatus gains refetchThrough (optional; additive). Caches whose fill
ended before this get their first refresh alarm when they next wake.

The service starts at boot as well as on the socket: alarms fire only
while workerd runs.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
dckcandClaude Opus 5.5 committed 2026-10-14 23:31:48 -05:00
1 parent 9cfc150f2c
commit 992e871c56
5 files changed
+132 -13

No files matched your search

+1 -1
View File
@@ -26,7 +26,7 @@ nix-env is spelled out in full because sudo's `secure_path` leaves out nix's pro
```sh
sudo /nix/var/nix/profiles/default/bin/nix-env -p /nix/var/nix/profiles/diigo-cache --set "$out"
sudo systemctl link /nix/var/nix/profiles/diigo-cache/lib/systemd/system/diigo-cache.{socket,service}
sudo systemctl enable --now diigo-cache.socket
sudo systemctl enable --now diigo-cache.socket diigo-cache.service
sudo tailscale serve --bg --https=443 http://127.0.0.1:8790
```
+1 -1
View File
@@ -17,7 +17,7 @@ journalctl -u diigo-cache.service -f -o cat |
workerd runs with `structuredLogging`: each entry is one line of JSON, `{timestamp, level, message}`. `message` is the logged object as `console.log` prints it, not JSON: on Cloudflare, Workers Logs indexes the fields of a logged object, so the workers log objects rather than strings.
workerd logs the workers' `console.*` output: `{event: "cache", kind, page, outcome}` per page read, `{event: "fill", state, …}` per fill step, `{event: "mint"}`. Ids show only as fingerprints; the cookie never appears.
workerd logs the workers' `console.*` output: `{event: "cache", kind, page, outcome}` per page read, `{event: "fill", state, …}` per fill step (a refresh logs `refetchThrough`), `{event: "mint"}`. Ids show only as fingerprints; the cookie never appears.
## State
+5
View File
@@ -24,3 +24,8 @@ SystemCallFilter=@system-service
# V8 uses memory protection keys; without these, SIGSYS at startup
SystemCallFilter=pkey_alloc pkey_mprotect pkey_free
# not MemoryDenyWriteExecute: V8's JIT needs W+X
[Install]
# started at boot, not only on the first request: workerd runs the
# caches' refresh alarms only while it is up
WantedBy=multi-user.target
+55 -8
View File
@@ -44,6 +44,14 @@ const LEGACY_FILL_PAGE_SIZE = 24;
* pages at MS_PER_CALL; this keeps steps from running back to back */
const FILL_STEP_DELAY_MS = 1000;
/** how long after a fill ends (done or failed) a refresh starts: a fill
* that refetches the recent pages, then ends and schedules the next */
const REFRESH_INTERVAL_MS = 3 * 60 * 60 * 1000;
/** a refresh refetches the pages holding anything updated this recently
* (and every page before them; page 1 at least, for new bookmarks) */
const REFRESH_DAYS = 2;
/**
* a fill job's progress (goal 1e; tests/fill.test.ts). Stored in the DO
* (new state, additive), so it survives eviction; advanced by alarms.
@@ -66,6 +74,9 @@ export type FillStatus = {
updatedAt: string;
/** why it failed: safe to show and log (no ids, no header values) */
error?: string;
/** pages numbered this or lower are fetched even when cached (a
* refresh); absent on plain fills */
refetchThrough?: number;
};
/** the page size a fill job counts in (old jobs didn't record it) */
@@ -139,6 +150,11 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
await null; // let the subclass constructor finish: `kind` is its field
const from = this.#writer.migrate();
if (from < SCHEMA_VERSION) console.log({ event: "schema", kind: this.kind, from, to: SCHEMA_VERSION });
// a fill that ended before refreshes existed has no alarm yet
const fill = await ctx.storage.get<FillStatus>("fill");
if (fill && fill.state !== "running" && fill.state !== "stopped" && (await ctx.storage.getAlarm()) === null) {
await ctx.storage.setAlarm(this.#clock.now() + REFRESH_INTERVAL_MS);
}
});
}
@@ -176,12 +192,20 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
* cache, `pagesPerStep` per alarm (default 20, 1–50). Starting while a
* job runs returns that job unchanged; a finished, stopped, or failed
* job is replaced by a fresh one (cached pages are skipped anyway).
* Once the job ends, a refresh follows every REFRESH_INTERVAL_MS until
* stopped.
*/
async startFill(opts: { pagesPerStep?: number } = {}): Promise<FillStatus> {
const current = await this.fillStatus();
if (current?.state === "running" && fillCountsAsNow(current)) return current;
const step = Math.trunc(opts.pagesPerStep ?? 20);
if (!(step >= 1 && step <= 50)) throw new Error("pagesPerStep: expected 1–50");
return this.#startJob(step);
}
/** a fresh fill job, first step in FILL_STEP_DELAY_MS; `refetchThrough`
* makes it a refresh */
async #startJob(step: number, refetchThrough?: number): Promise<FillStatus> {
const now = this.#iso();
const status: FillStatus = {
state: "running",
@@ -192,13 +216,22 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
fetched: 0,
startedAt: now,
updatedAt: now,
...(refetchThrough === undefined ? {} : { refetchThrough }),
};
await this.ctx.storage.put({ fill: status, fillStep: step });
await this.ctx.storage.setAlarm(this.#clock.now() + FILL_STEP_DELAY_MS);
console.log({ event: "fill", kind: this.kind, state: status.state, pagesPerStep: step });
console.log({ event: "fill", kind: this.kind, state: status.state, pagesPerStep: step, refetchThrough });
return status;
}
/** start a refresh: a fill that refetches the pages holding anything
* updated in the last REFRESH_DAYS days. Fetching overwrites a page in
* place, so a refresh that fails leaves the cache as it was. */
async #refresh(step: number): Promise<void> {
const cutoff = Math.floor(this.#clock.now() / 1000) - REFRESH_DAYS * 24 * 60 * 60;
await this.#startJob(step, Math.max(1, this.#reader.deepestPageSince(cutoff) ?? 1));
}
/** the fill job's progress, or undefined if none was ever started;
* the page count comes from any cached page until the job learns it */
async fillStatus(): Promise<FillStatus | undefined> {
@@ -206,11 +239,12 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
return fill && fill.pages === null ? { ...fill, pages: this.#knownPages() } : fill;
}
/** stop the fill job after its current step; cached pages stay */
/** stop the fill job after its current step, and its refreshes;
* cached pages stay */
async stopFill(): Promise<FillStatus> {
const current = await this.fillStatus();
if (!current) throw new Error("no fill job to stop");
if (current.state !== "running") return current;
if (current.state === "stopped") return current;
const stopped: FillStatus = { ...current, state: "stopped", updatedAt: this.#iso() };
await this.ctx.storage.put("fill", stopped);
await this.ctx.storage.deleteAlarm();
@@ -239,10 +273,15 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
}
/** one fill step: up to `fillStep` pages, progress saved after each,
* then the next step is scheduled (or the job ends) */
* then the next step is scheduled (or the job ends, and the next
* refresh is). On a job that has ended, the refresh starts. */
async alarm(): Promise<void> {
const step = (await this.ctx.storage.get<number>("fillStep")) ?? 20;
let status = await this.fillStatus();
if (status?.state === "done" || status?.state === "failed") {
await this.#refresh(step);
return;
}
// a job saved under another page size or numbering counts its pages
// differently: resuming it would skip or repeat items, so it fails
if (status?.state === "running" && !fillCountsAsNow(status)) {
@@ -253,6 +292,7 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
status = { ...status, state: "failed", error, updatedAt: this.#iso() };
console.error({ event: "fill", kind: this.kind, state: "failed", error });
await this.ctx.storage.put("fill", status);
await this.ctx.storage.setAlarm(this.#clock.now() + REFRESH_INTERVAL_MS);
return;
}
for (let i = 0; i < step && status?.state === "running"; i += 1) {
@@ -261,7 +301,7 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
break;
}
try {
const page = await this.page(status.nextPage, PAGE_SIZE);
const page = await this.#load(status.nextPage, PAGE_SIZE, status.nextPage <= (status.refetchThrough ?? 0));
const fetched = status.fetched + (page.cached ? 0 : 1);
// a page whose own total says the data ended before it (diigo
// answers total 0 past the end) ends the walk; the count is the
@@ -293,6 +333,7 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
await this.ctx.storage.put("fill", status);
console.log({ event: "fill", kind: this.kind, state: status.state, nextPage: status.nextPage, pages: status.pages, fetched: status.fetched });
if (status.state === "running") await this.ctx.storage.setAlarm(this.#clock.now() + FILL_STEP_DELAY_MS);
else await this.ctx.storage.setAlarm(this.#clock.now() + REFRESH_INTERVAL_MS);
}
/** diigo's page count, if any cached page recorded `total` (pages past
@@ -309,10 +350,16 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
* rides in the result (`cached`).
*/
async page(pageNum: number, count: number): Promise<CachePage> {
return this.#load(pageNum, count, false);
}
/** {@link page}, or with `fresh`, fetch even if cached (overwriting
* the stored page) */
async #load(pageNum: number, count: number, fresh: boolean): Promise<CachePage> {
const init = await this.wiring();
if (!init) throw new Error("not wired: this cache id was never set up");
const hit = await this.#pageFromStorage(pageNum, count);
const hit = fresh ? null : await this.#pageFromStorage(pageNum, count);
if (hit) {
console.log({ event: "cache", kind: this.kind, page: pageNum, outcome: "hit", items: hit.items.length });
return hit;
@@ -329,7 +376,7 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
this.#step += 1;
this.#pause = this.#clock.sleep(MS_PER_CALL);
// a request ahead of us at the gate may have etched this page
const late = await this.#pageFromStorage(pageNum, count);
const late = fresh ? null : await this.#pageFromStorage(pageNum, count);
if (late) {
console.log({ event: "cache", kind: this.kind, page: pageNum, outcome: "hit", items: late.items.length });
return late;
@@ -357,7 +404,7 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
}
const kept = this.keep(toRows(data.items, console));
// fetched vs kept: the public cache's drop of private rows shows here
console.log({ event: "cache", kind: this.kind, page: pageNum, outcome: "miss", fetched: data.items.length, kept: kept.length });
console.log({ event: "cache", kind: this.kind, page: pageNum, outcome: fresh ? "refetch" : "miss", fetched: data.items.length, kept: kept.length });
return this.#etch(pageNum, count, data.total, kept);
}
+70 -3
View File
@@ -26,10 +26,14 @@ const wired = async (webappId = "fake-webapp-id") => {
return stub;
};
/** run alarms until none is scheduled (bounded, so a runaway job fails) */
const drain = async (stub: DurableObjectStub, max = 20) => {
const HOUR = 60 * 60 * 1000;
/** run alarms until the job ends (bounded, so a runaway job fails); the
* refresh alarm an ended job leaves is not run */
const drain = async (stub: DurableObjectStub & { fillStatus(): Promise<{ state: string } | undefined> }, max = 20) => {
let ran = 0;
while (ran < max && (await runDurableObjectAlarm(stub))) ran += 1;
const running = async () => (await stub.fillStatus())?.state === "running";
while (ran < max && (await running()) && (await runDurableObjectAlarm(stub))) ran += 1;
expect(ran).toBeLessThan(max);
return ran;
};
@@ -120,6 +124,9 @@ describe("fill job (goal 1e)", () => {
});
await drain(stub);
expect(await stub.fillStatus()).toMatchObject({ state: "done", updatedAt: at });
await runInDurableObject(stub, async (_obj, state) => {
expect(await state.storage.getAlarm()).toBe(FIXED_NOW + 3 * HOUR);
});
});
it("a capped page size fails the fill with the reason, instead of skipping items", async () => {
@@ -170,6 +177,66 @@ describe("fill job (goal 1e)", () => {
expect(await stub.startFill()).toMatchObject({ state: "running", nextPage: 1, pageSize: PAGE_SIZE });
});
it("refreshes 3 hours after a fill: refetches the pages updated in the last 2 days, skips the rest, then waits again", async () => {
// deep account: item n updated n-1 days + 1 hour ago, so items 1–2
// (both on page 1) are within 2 days
const stub = await wired("fake-deep-webapp");
await stub.startFill();
await drain(stub);
await runInDurableObject(stub, async (_obj, state) => {
const alarm = (await state.storage.getAlarm()) ?? 0;
expect(alarm - Date.now()).toBeGreaterThan(2.9 * HOUR);
expect(alarm - Date.now()).toBeLessThanOrEqual(3 * HOUR);
});
expect(await runDurableObjectAlarm(stub)).toBe(true);
expect(await stub.fillStatus()).toMatchObject({ state: "running", nextPage: 1, refetchThrough: 1 });
await drain(stub);
// fetched counts diigo calls; pages 2–3 were hits
expect(await stub.fillStatus()).toMatchObject({ state: "done", pages: 3, fetched: 1 });
await runInDurableObject(stub, async (_obj, state) => {
expect(await state.storage.getAlarm()).not.toBeNull();
});
});
it("a refresh refetches page 1 even when nothing cached is recent: new bookmarks land there", async () => {
const stub = await wired();
await stub.startFill();
await drain(stub);
await runDurableObjectAlarm(stub);
expect(await stub.fillStatus()).toMatchObject({ refetchThrough: 1 });
await drain(stub);
expect(await stub.fillStatus()).toMatchObject({ state: "done", fetched: 1 });
});
it("a failed fill is retried by the next refresh; a stopped one is not", async () => {
const failing = await wired("no-such-webapp");
await failing.startFill();
await drain(failing);
expect((await failing.fillStatus())?.state).toBe("failed");
expect(await runDurableObjectAlarm(failing)).toBe(true);
expect((await failing.fillStatus())?.state).toBe("running");
const stopped = await wired();
await stopped.startFill();
await drain(stopped);
expect((await stopped.stopFill()).state).toBe("stopped");
expect(await runDurableObjectAlarm(stopped)).toBe(false);
});
it("a fill that ended before refreshes existed gets one when the cache next wakes", async () => {
const stub = await wired();
await stub.startFill();
await drain(stub);
await runInDurableObject(stub, async (_obj, state) => {
await state.storage.deleteAlarm();
});
await evictDurableObject(stub);
await stub.fillStatus();
await runInDurableObject(stub, async (_obj, state) => {
expect(await state.storage.getAlarm()).not.toBeNull();
});
});
it("a public cache's fill stores no private rows", async () => {
const stub = testEnv.PUBLIC_DO.get(testEnv.PUBLIC_DO.newUniqueId());
await stub.setup({ webappId: "fake-webapp-id" });