Files
captoys/diigo-cache/src/api.ts
T
dckc 2a1942fc2a fixup! diigo-cache: invalidate the last N days of cached pages
Docs per the docs-files-api skill: a 1–2 line @file; what a declaration is or does in JSDoc on it, not in // comments or the file header.

Generated-by: Claude Opus 5.5
2026-10-07 09:34:06 -05:00

133 lines
4.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/** @file the Cap'n Web API at /api: trade a cache's webkey for a capability. */
import { RpcTarget } from "capnweb";
import type { DiigoCacheLogic, FillStatus, PublicCacheLogic } from "./cache.js";
import { idFromWebkey, isWebkey, shashKey } from "./webkeys.js";
/** the bindings the API reaches (structural) */
export type ApiEnv = {
CACHE_DO: DurableObjectNamespace<DiigoCacheLogic>;
PUBLIC_DO: DurableObjectNamespace<PublicCacheLogic>;
};
/** the fill-job surface of one cache (private or public) */
type Fillable = {
startFill(opts?: { pagesPerStep?: number }): Promise<FillStatus>;
fillStatus(): Promise<FillStatus | undefined>;
stopFill(): Promise<FillStatus>;
invalidateRecent(days: number): Promise<{ pages: number }>;
};
/** a cache's fill job and page invalidation, and nothing else */
export class FillCap extends RpcTarget {
#cache: Fillable;
constructor(cache: Fillable) {
super();
this.#cache = cache;
}
/** start (or rejoin) the job; `pagesPerStep` 1–50 */
async startFill(opts: unknown = {}): Promise<FillStatus> {
const step = (opts as { pagesPerStep?: unknown } | null)?.pagesPerStep;
if (step !== undefined && typeof step !== "number") throw new Error("pagesPerStep: expected a number");
return this.#cache.startFill(step === undefined ? {} : { pagesPerStep: step });
}
/** the job's progress, or undefined if none was started */
async fillStatus(): Promise<FillStatus | undefined> {
return this.#cache.fillStatus();
}
/** stop the job; cached pages stay */
async stopFill(): Promise<FillStatus> {
return this.#cache.stopFill();
}
/** drop the cached pages holding anything updated in the last `days`
* days (1–3650), so they refetch */
async invalidateRecent(days: unknown): Promise<{ pages: number }> {
if (typeof days !== "number") throw new Error("days: expected a number");
return this.#cache.invalidateRecent(days);
}
}
/** what the holder of a private cache's key may do */
export class CacheCap extends FillCap {
#key: string;
#publicId: string | undefined;
#env: ApiEnv;
constructor(env: ApiEnv, key: string, cache: Fillable, publicId: string | undefined) {
super(cache);
this.#env = env;
this.#key = key;
this.#publicId = publicId;
}
/** a prefix of the key's one-way hash: names it without granting it */
async fingerprint(): Promise<string> {
return (await shashKey(this.#key)).slice(0, 8);
}
/** whether a public companion exists (see {@link publicCache}) */
hasPublic(): boolean {
return this.#publicId !== undefined;
}
/** the public companion's fill job; refused if never published (a
* stub, not a maybe-null, so calls on it pipeline) */
publicCache(): FillCap {
if (!this.#publicId) throw new Error("no public cache: publish this cache first");
const ns = this.#env.PUBLIC_DO;
return new FillCap(ns.get(ns.idFromString(idFromWebkey(this.#publicId))));
}
}
/**
* the main interface at /api. The browser holds a cache's key in a URL
* fragment (`/cache/#<key>`, docs/webkeys.md), so it never reaches the
* server in a URL; the webkey page passes it *in-band* to {@link cache}
* and gets back a {@link CacheCap}. With authorization in-band,
* cross-origin calls are safe (capnweb's note on `newWorkersRpcResponse`);
* arguments are checked at runtime, since types are erased on the wire.
*
* @see https://github.com/cloudflare/capnweb
*/
export class CacheApi extends RpcTarget {
#env: ApiEnv;
constructor(env: ApiEnv) {
super();
this.#env = env;
}
/**
* trade a cache's webkey for its capability. Refused keys get one
* message for malformed and unknown alike, which never echoes the key.
*/
async cache(key: unknown): Promise<CacheCap> {
const refused = () => new Error("no such cache");
if (typeof key !== "string" || !isWebkey(key, 256)) {
console.log({ event: "api", refused: "cache", reason: "malformed key" });
throw refused();
}
const ns = this.#env.CACHE_DO;
let stub;
try {
// a well-formed id from another namespace throws here
stub = ns.get(ns.idFromString(idFromWebkey(key)));
} catch (err) {
// the key is never logged: it is the bearer secret
console.log({ event: "api", refused: "cache", reason: String(err) });
throw refused();
}
const wiring = await stub.wiring();
if (!wiring) {
console.log({ event: "api", refused: "cache", reason: "not wired" });
throw refused();
}
return new CacheCap(this.#env, key, stub, wiring.publicId);
}
}