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:
1 parent
9cfc150f2c
commit
992e871c56
5 files changed
+132
-13
No files matched your search
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user