cursedbelt-server 4.74.0 → 4.76.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/server/d1/plans.d.ts +12 -0
- package/dist/server/d1/plans.js +26 -7
- package/dist/server/presence/index.d.ts +95 -0
- package/dist/server/presence/index.js +123 -0
- package/package.json +8 -2
- package/src/server/d1/plans.spec.ts +39 -0
- package/src/server/d1/plans.ts +33 -7
- package/src/server/presence/index.ts +185 -0
- package/src/server/presence/presence.spec.ts +160 -0
|
@@ -10,6 +10,12 @@
|
|
|
10
10
|
* 963 photographs. A page is held too: one that reads its table whole and sorts it to hand back its
|
|
11
11
|
* LIMIT pays for the archive on every page (photos' `albums/assets`, 331,190 rows for one page).
|
|
12
12
|
*
|
|
13
|
+
* A search keyed by `col IS NULL` alone is held the same way, whatever the column: the plan prints it as
|
|
14
|
+
* `(col=?)`, a keyed search, but the key is every row that has no value yet — usually most of the table.
|
|
15
|
+
* Photos' art-face hides reached `faces` through `faces_entity (entity_id=?)` for `f.entity_id IS NULL`,
|
|
16
|
+
* 16,314 of 23,978 faces per statement, twice per described photograph: 1.78 M rows read by one sync
|
|
17
|
+
* (forge task 5517). The plan cannot tell `= ?` from `IS NULL`, so the check reads the statement too.
|
|
18
|
+
*
|
|
13
19
|
* ```ts
|
|
14
20
|
* const statements = await preparedBy(db, () => app.request('/api/heavy'));
|
|
15
21
|
* expect(await planOffenders(db, statements)).toEqual([]);
|
|
@@ -32,6 +38,12 @@ export declare const LOW_CARDINALITY_COLUMNS: readonly string[];
|
|
|
32
38
|
export interface PlanCheckOptions {
|
|
33
39
|
/** Replaces {@link LOW_CARDINALITY_COLUMNS}. */
|
|
34
40
|
lowCardinality?: readonly string[];
|
|
41
|
+
/**
|
|
42
|
+
* The statement the plan is of. Given, a search keyed by one column alone that the statement tests
|
|
43
|
+
* `IS NULL` (`f.entity_id IS NULL` → `SEARCH f USING INDEX faces_entity (entity_id=?)`) reads every
|
|
44
|
+
* row with no value, and counts as reading its table whole. {@link planOffenders} always passes it.
|
|
45
|
+
*/
|
|
46
|
+
sql?: string;
|
|
35
47
|
}
|
|
36
48
|
/** The steps of `plan` that run once per outer row: inside a correlated subquery, or an `EXISTS` semi-join. */
|
|
37
49
|
export declare function perRowSteps(plan: readonly PlanRow[]): PlanRow[];
|
package/dist/server/d1/plans.js
CHANGED
|
@@ -10,6 +10,12 @@
|
|
|
10
10
|
* 963 photographs. A page is held too: one that reads its table whole and sorts it to hand back its
|
|
11
11
|
* LIMIT pays for the archive on every page (photos' `albums/assets`, 331,190 rows for one page).
|
|
12
12
|
*
|
|
13
|
+
* A search keyed by `col IS NULL` alone is held the same way, whatever the column: the plan prints it as
|
|
14
|
+
* `(col=?)`, a keyed search, but the key is every row that has no value yet — usually most of the table.
|
|
15
|
+
* Photos' art-face hides reached `faces` through `faces_entity (entity_id=?)` for `f.entity_id IS NULL`,
|
|
16
|
+
* 16,314 of 23,978 faces per statement, twice per described photograph: 1.78 M rows read by one sync
|
|
17
|
+
* (forge task 5517). The plan cannot tell `= ?` from `IS NULL`, so the check reads the statement too.
|
|
18
|
+
*
|
|
13
19
|
* ```ts
|
|
14
20
|
* const statements = await preparedBy(db, () => app.request('/api/heavy'));
|
|
15
21
|
* expect(await planOffenders(db, statements)).toEqual([]);
|
|
@@ -24,13 +30,26 @@
|
|
|
24
30
|
export const LOW_CARDINALITY_COLUMNS = ['state', 'status', 'deleted_at', 'owner_id'];
|
|
25
31
|
const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
26
32
|
const lowCardinalityRule = (columns) => columns.length === 0 ? null : new RegExp(` USING (?:COVERING )?INDEX \\S+ \\((?:${columns.map(escapeRegExp).join('|')})=\\?\\)`);
|
|
27
|
-
/**
|
|
28
|
-
|
|
33
|
+
/** `SEARCH <alias> [EXISTS ]USING [COVERING ]INDEX <index> (<column>=?)` — a search keyed by one column alone. */
|
|
34
|
+
const ONE_KEY = /^SEARCH (\S+) (?:EXISTS )?USING (?:COVERING )?INDEX \S+ \((\w+)=\?\)$/;
|
|
35
|
+
/**
|
|
36
|
+
* Whether `sql` tests `alias.column IS NULL` (or a bare `column IS NULL`): the search {@link ONE_KEY} names is then
|
|
37
|
+
* keyed by NULL. A unary `+` (`+f.entity_id IS NULL`) is SQLite's way to keep a term off every index, so it is not one.
|
|
38
|
+
*/
|
|
39
|
+
function keyedByNull(detail, sql) {
|
|
40
|
+
const m = sql ? ONE_KEY.exec(detail) : null;
|
|
41
|
+
if (!m || !sql)
|
|
42
|
+
return false;
|
|
43
|
+
const [, alias, column] = m;
|
|
44
|
+
return new RegExp(`(?<![\\w.+])(?:${escapeRegExp(alias)}\\.)?${escapeRegExp(column)}\\s+IS\\s+NULL\\b`, 'i').test(sql);
|
|
45
|
+
}
|
|
46
|
+
/** A step that reads its table whole: a scan with no index, or a search by a low-cardinality column (or NULL) alone. */
|
|
47
|
+
function readsWhole(detail, derived, low, sql) {
|
|
29
48
|
const bareScan = /^SCAN (?!CONSTANT ROW)/.test(detail) &&
|
|
30
49
|
!detail.includes(' VIRTUAL TABLE ') &&
|
|
31
50
|
!derived.has(detail.split(' ')[1] ?? '') &&
|
|
32
51
|
!/ USING (?:COVERING )?INDEX /.test(detail);
|
|
33
|
-
return bareScan || (low?.test(detail) ?? false);
|
|
52
|
+
return bareScan || (low?.test(detail) ?? false) || keyedByNull(detail, sql);
|
|
34
53
|
}
|
|
35
54
|
/** What a subquery made (`MATERIALIZE hit`, `CO-ROUTINE (subquery-1)`): its rows were counted where they were made. */
|
|
36
55
|
const derivedOf = (plan) => new Set(plan.flatMap((r) => /^(?:MATERIALIZE|CO-ROUTINE) (\S+)/.exec(r.detail)?.[1] ?? []));
|
|
@@ -57,7 +76,7 @@ export function perRowSteps(plan) {
|
|
|
57
76
|
export function perRowReads(plan, opts = {}) {
|
|
58
77
|
const derived = derivedOf(plan);
|
|
59
78
|
const low = lowCardinalityRule(opts.lowCardinality ?? LOW_CARDINALITY_COLUMNS);
|
|
60
|
-
return (opts.perEvent ? plan : perRowSteps(plan)).filter((r) => readsWhole(r.detail, derived, low)).map((r) => r.detail);
|
|
79
|
+
return (opts.perEvent ? plan : perRowSteps(plan)).filter((r) => readsWhole(r.detail, derived, low, opts.sql)).map((r) => r.detail);
|
|
61
80
|
}
|
|
62
81
|
/**
|
|
63
82
|
* The outer steps of a paged read that reads its table whole and then sorts every row it kept (`USE
|
|
@@ -70,7 +89,7 @@ export function wholeTablePages(plan, opts = {}) {
|
|
|
70
89
|
return [];
|
|
71
90
|
const derived = derivedOf(plan);
|
|
72
91
|
const low = lowCardinalityRule(opts.lowCardinality ?? LOW_CARDINALITY_COLUMNS);
|
|
73
|
-
return outer.filter((r) => readsWhole(r.detail, derived, low)).map((r) => r.detail);
|
|
92
|
+
return outer.filter((r) => readsWhole(r.detail, derived, low, opts.sql)).map((r) => r.detail);
|
|
74
93
|
}
|
|
75
94
|
/**
|
|
76
95
|
* Every distinct statement `run` prepares on `db`, in first-prepared order. `db.prepare` is restored
|
|
@@ -117,10 +136,10 @@ export async function planOffenders(db, statements, opts = {}) {
|
|
|
117
136
|
continue;
|
|
118
137
|
const plan = await planOf(db, sql);
|
|
119
138
|
const where = sql.replace(/\s+/g, ' ').trim().slice(0, 160);
|
|
120
|
-
for (const step of perRowReads(plan, { ...opts, perEvent: write }))
|
|
139
|
+
for (const step of perRowReads(plan, { ...opts, perEvent: write, sql }))
|
|
121
140
|
offenders.push(`${step} ← ${where}`);
|
|
122
141
|
if (!write && /\bLIMIT\b/i.test(sql))
|
|
123
|
-
for (const step of wholeTablePages(plan, opts))
|
|
142
|
+
for (const step of wholeTablePages(plan, { ...opts, sql }))
|
|
124
143
|
offenders.push(`page: ${step} ← ${where}`);
|
|
125
144
|
}
|
|
126
145
|
return offenders;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `cursedbelt-server/presence` — 🔴 an app nobody is using costs (close to) nothing (forge task 5325).
|
|
3
|
+
*
|
|
4
|
+
* The owner, 2026-11-16: *"if no one uses apps like photos, roms, flix, vault, desk, etc all day I don't
|
|
5
|
+
* want thousands of requests […] back and forth with no benefit."* Measured that day: the
|
|
6
|
+
* fleet's Worker crons fired ~6,500 times and spent ~172k CPU-ms — about a sixth of the account's Workers
|
|
7
|
+
* CPU, which the month was already past — and nearly all of it ran with nobody there. A five-minute cron
|
|
8
|
+
* is a promise to someone looking at the page; at 4 a.m. it is a promise to no one.
|
|
9
|
+
*
|
|
10
|
+
* So scheduled work keys on PRESENCE, not the clock (night is just the common case of idle):
|
|
11
|
+
*
|
|
12
|
+
* - **{@link createUseTick}** — work that used to run every few minutes runs on USE instead: a signed-in
|
|
13
|
+
* request kicks it under `waitUntil` when it is due, at most once per `everyMs` across every isolate
|
|
14
|
+
* ({@link claimTick} in D1). The Worker's own cron drops to the lowest cadence that is still correct
|
|
15
|
+
* with nobody there (an hourly backstop for queued work, the day's purge), and a stage tier keeps no
|
|
16
|
+
* cron at all: its tests in flight are the use that ticks it.
|
|
17
|
+
* - **{@link notePresence} / {@link lastPresence}** — for a Worker with no sign-in of its own (the media
|
|
18
|
+
* edge): it notes "a reader of <name> was here", throttled per isolate, and its cron asks before it
|
|
19
|
+
* spends anything.
|
|
20
|
+
* - **{@link lastHumanUse}** — for an app behind cursedauth's door: `sessions.last_seen_at` is ALREADY
|
|
21
|
+
* the signal. The door moves it on every signed-in request (`userIdOf`, throttled to a minute), so
|
|
22
|
+
* `MAX(last_seen_at)` is the tier's last human use, with no write of ours at all.
|
|
23
|
+
*
|
|
24
|
+
* Everything is created on first use (`presence_marks`, like `events_days` and the engagement tables),
|
|
25
|
+
* so no app's schema has to learn it. A failed claim runs nothing and warns: a lost tick is the next
|
|
26
|
+
* request's or the backstop cron's, never a double.
|
|
27
|
+
*
|
|
28
|
+
* `tools/check-idle-cost.ts` in the generation holds the other half: a sub-hourly cron or a stage cron
|
|
29
|
+
* that does not go through here is red.
|
|
30
|
+
*
|
|
31
|
+
* 🔴 Worker-safe: nothing here imports `bun:*`.
|
|
32
|
+
*/
|
|
33
|
+
import type { D1LikeDatabase } from "../d1/types.js";
|
|
34
|
+
/** One row per name: a presence mark (`reader:<tenant>`) or a tick's last run (`tick:<name>`). */
|
|
35
|
+
export declare const PRESENCE_DDL: string[];
|
|
36
|
+
/** How often one isolate writes the same presence mark. Presence is an hours-scale question. */
|
|
37
|
+
export declare const PRESENCE_THROTTLE_MS: number;
|
|
38
|
+
/** The default "nobody is here" line: no use for this long and scheduled work stands down. */
|
|
39
|
+
export declare const IDLE_AFTER_MS: number;
|
|
40
|
+
/**
|
|
41
|
+
* Note that someone used `name` now. At most one D1 write per isolate per `throttleMs`, and the row only
|
|
42
|
+
* moves when it is older than that, so many isolates add up to a handful of writes an hour while anyone is
|
|
43
|
+
* there and none while no one is. Resolves `true` when it wrote; never throws (presence is advisory).
|
|
44
|
+
*/
|
|
45
|
+
export declare function notePresence(db: D1LikeDatabase, name: string, options?: {
|
|
46
|
+
now?: () => number;
|
|
47
|
+
throttleMs?: number;
|
|
48
|
+
}): Promise<boolean>;
|
|
49
|
+
/** When `name` was last noted (epoch ms), or null — never noted, or no table yet. Throws on any other error. */
|
|
50
|
+
export declare function lastPresence(db: D1LikeDatabase, name: string): Promise<number | null>;
|
|
51
|
+
/**
|
|
52
|
+
* The tier's last human use behind cursedauth's door: `MAX(sessions.last_seen_at)`, which the door's
|
|
53
|
+
* `userIdOf` moves on every signed-in request. Null when nobody has a session, or the app has no
|
|
54
|
+
* `sessions` table. A row read per live session — a household's handful.
|
|
55
|
+
*/
|
|
56
|
+
export declare function lastHumanUse(db: D1LikeDatabase): Promise<number | null>;
|
|
57
|
+
/** Whether a last use at `lastAt` still counts as someone being here. Null (never) is idle. Pure. */
|
|
58
|
+
export declare function isPresent(lastAt: number | null, now?: number, idleAfterMs?: number): boolean;
|
|
59
|
+
/**
|
|
60
|
+
* Claim tick `name` if its last run is at least `everyMs` old — one D1 statement, atomic, so of every
|
|
61
|
+
* isolate and cron that asks inside the window exactly one wins. `everyMs: 0` always wins: what a cron
|
|
62
|
+
* calls to record that it ran, so the next request does not run the same work again a minute later.
|
|
63
|
+
*/
|
|
64
|
+
export declare function claimTick(db: D1LikeDatabase, name: string, everyMs: number, now?: number): Promise<boolean>;
|
|
65
|
+
/** When tick `name` last ran (epoch ms), or null. */
|
|
66
|
+
export declare const lastTick: (db: D1LikeDatabase, name: string) => Promise<number | null>;
|
|
67
|
+
export interface UseTickKick {
|
|
68
|
+
db: D1LikeDatabase;
|
|
69
|
+
/** The work — the same function the cron runs. Its errors are logged, never thrown at the request. */
|
|
70
|
+
run: () => Promise<unknown>;
|
|
71
|
+
/** The request's `ctx.waitUntil`: the tick never holds the answer. */
|
|
72
|
+
waitUntil: (promise: Promise<unknown>) => void;
|
|
73
|
+
now?: () => number;
|
|
74
|
+
}
|
|
75
|
+
export interface UseTick {
|
|
76
|
+
/** Start the tick behind this request if it is due. True when it was started (and won its claim or is asking). */
|
|
77
|
+
kick(input: UseTickKick): boolean;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Work that runs because someone is USING the app (see the header): `kick` on a signed-in request.
|
|
81
|
+
* The isolate remembers its last attempt, so a page's burst of requests costs one claim, and the claim
|
|
82
|
+
* in D1 keeps every isolate together to one run per `everyMs`.
|
|
83
|
+
*/
|
|
84
|
+
export declare function createUseTick(options: {
|
|
85
|
+
name: string;
|
|
86
|
+
everyMs: number;
|
|
87
|
+
}): UseTick;
|
|
88
|
+
/**
|
|
89
|
+
* Whether a request is a person using the app — it carries the app's own session cookie. A stale cookie
|
|
90
|
+
* counts too: the price of a false yes is one tick, while a probe, a crawler, the Mac's bearer-token
|
|
91
|
+
* pipeline and `/healthz` carry no cookie and never tick anything.
|
|
92
|
+
*/
|
|
93
|
+
export declare function carriesSession(request: Request, cookieName: string): boolean;
|
|
94
|
+
/** Test seam: forget what this isolate noted. */
|
|
95
|
+
export declare function resetPresenceMemo(): void;
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/** One row per name: a presence mark (`reader:<tenant>`) or a tick's last run (`tick:<name>`). */
|
|
2
|
+
export const PRESENCE_DDL = ["CREATE TABLE IF NOT EXISTS presence_marks (name TEXT PRIMARY KEY, at INTEGER NOT NULL)"];
|
|
3
|
+
/** How often one isolate writes the same presence mark. Presence is an hours-scale question. */
|
|
4
|
+
export const PRESENCE_THROTTLE_MS = 5 * 60_000;
|
|
5
|
+
/** The default "nobody is here" line: no use for this long and scheduled work stands down. */
|
|
6
|
+
export const IDLE_AFTER_MS = 3 * 60 * 60_000;
|
|
7
|
+
const TICK_PREFIX = "tick:";
|
|
8
|
+
/** An upsert that only moves `at` when the row is older than `?3` — the claim and the throttled mark both. */
|
|
9
|
+
const UPSERT_IF_OLDER = "INSERT INTO presence_marks (name, at) VALUES (?1, ?2) ON CONFLICT(name) DO UPDATE SET at = excluded.at WHERE presence_marks.at <= ?3";
|
|
10
|
+
const isMissingTable = (error) => /no such table/i.test(String(error));
|
|
11
|
+
async function upsertIfOlder(db, name, at, olderThan) {
|
|
12
|
+
const run = () => db.prepare(UPSERT_IF_OLDER).bind(name, at, olderThan).run();
|
|
13
|
+
const result = await run().catch(async (error) => {
|
|
14
|
+
if (!isMissingTable(error))
|
|
15
|
+
throw error;
|
|
16
|
+
await db.batch(PRESENCE_DDL.map((ddl) => db.prepare(ddl)));
|
|
17
|
+
return run();
|
|
18
|
+
});
|
|
19
|
+
return (result.meta?.changes ?? 0) > 0;
|
|
20
|
+
}
|
|
21
|
+
/** What this isolate last wrote or attempted, per name — so a busy Worker asks D1 once per throttle. */
|
|
22
|
+
const noted = new Map();
|
|
23
|
+
/**
|
|
24
|
+
* Note that someone used `name` now. At most one D1 write per isolate per `throttleMs`, and the row only
|
|
25
|
+
* moves when it is older than that, so many isolates add up to a handful of writes an hour while anyone is
|
|
26
|
+
* there and none while no one is. Resolves `true` when it wrote; never throws (presence is advisory).
|
|
27
|
+
*/
|
|
28
|
+
export async function notePresence(db, name, options = {}) {
|
|
29
|
+
const now = (options.now ?? Date.now)();
|
|
30
|
+
const throttle = options.throttleMs ?? PRESENCE_THROTTLE_MS;
|
|
31
|
+
const last = noted.get(name);
|
|
32
|
+
if (last !== undefined && now - last < throttle)
|
|
33
|
+
return false;
|
|
34
|
+
noted.set(name, now);
|
|
35
|
+
try {
|
|
36
|
+
return await upsertIfOlder(db, name, now, now - throttle);
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
console.warn(`[presence] ${name} was not noted: ${String(error)}`);
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** When `name` was last noted (epoch ms), or null — never noted, or no table yet. Throws on any other error. */
|
|
44
|
+
export async function lastPresence(db, name) {
|
|
45
|
+
try {
|
|
46
|
+
const row = await db.prepare("SELECT at FROM presence_marks WHERE name = ?").bind(name).first();
|
|
47
|
+
return typeof row?.at === "number" ? row.at : null;
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
if (isMissingTable(error))
|
|
51
|
+
return null;
|
|
52
|
+
throw error;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The tier's last human use behind cursedauth's door: `MAX(sessions.last_seen_at)`, which the door's
|
|
57
|
+
* `userIdOf` moves on every signed-in request. Null when nobody has a session, or the app has no
|
|
58
|
+
* `sessions` table. A row read per live session — a household's handful.
|
|
59
|
+
*/
|
|
60
|
+
export async function lastHumanUse(db) {
|
|
61
|
+
try {
|
|
62
|
+
const row = await db.prepare("SELECT MAX(last_seen_at) AS at FROM sessions").first();
|
|
63
|
+
return typeof row?.at === "number" && row.at > 0 ? row.at : null;
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
if (isMissingTable(error))
|
|
67
|
+
return null;
|
|
68
|
+
throw error;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/** Whether a last use at `lastAt` still counts as someone being here. Null (never) is idle. Pure. */
|
|
72
|
+
export function isPresent(lastAt, now = Date.now(), idleAfterMs = IDLE_AFTER_MS) {
|
|
73
|
+
return lastAt !== null && now - lastAt < idleAfterMs;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Claim tick `name` if its last run is at least `everyMs` old — one D1 statement, atomic, so of every
|
|
77
|
+
* isolate and cron that asks inside the window exactly one wins. `everyMs: 0` always wins: what a cron
|
|
78
|
+
* calls to record that it ran, so the next request does not run the same work again a minute later.
|
|
79
|
+
*/
|
|
80
|
+
export async function claimTick(db, name, everyMs, now = Date.now()) {
|
|
81
|
+
return upsertIfOlder(db, TICK_PREFIX + name, now, now - everyMs);
|
|
82
|
+
}
|
|
83
|
+
/** When tick `name` last ran (epoch ms), or null. */
|
|
84
|
+
export const lastTick = (db, name) => lastPresence(db, TICK_PREFIX + name);
|
|
85
|
+
/**
|
|
86
|
+
* Work that runs because someone is USING the app (see the header): `kick` on a signed-in request.
|
|
87
|
+
* The isolate remembers its last attempt, so a page's burst of requests costs one claim, and the claim
|
|
88
|
+
* in D1 keeps every isolate together to one run per `everyMs`.
|
|
89
|
+
*/
|
|
90
|
+
export function createUseTick(options) {
|
|
91
|
+
let attempted = Number.NEGATIVE_INFINITY;
|
|
92
|
+
return {
|
|
93
|
+
kick({ db, run, waitUntil, now = Date.now }) {
|
|
94
|
+
const at = now();
|
|
95
|
+
if (at - attempted < options.everyMs)
|
|
96
|
+
return false;
|
|
97
|
+
attempted = at;
|
|
98
|
+
waitUntil(claimTick(db, options.name, options.everyMs, at)
|
|
99
|
+
.then((won) => (won ? run() : undefined))
|
|
100
|
+
.catch((error) => console.warn(`[presence] the ${options.name} tick failed: ${String(error)}`)));
|
|
101
|
+
return true;
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Whether a request is a person using the app — it carries the app's own session cookie. A stale cookie
|
|
107
|
+
* counts too: the price of a false yes is one tick, while a probe, a crawler, the Mac's bearer-token
|
|
108
|
+
* pipeline and `/healthz` carry no cookie and never tick anything.
|
|
109
|
+
*/
|
|
110
|
+
export function carriesSession(request, cookieName) {
|
|
111
|
+
const cookie = request.headers.get("cookie");
|
|
112
|
+
if (!cookie)
|
|
113
|
+
return false;
|
|
114
|
+
return cookie.split(";").some((part) => {
|
|
115
|
+
const name = part.trim().split("=", 1)[0];
|
|
116
|
+
// cursedauth's account slots: `<base>` is slot 0, `<base>__<n>` the others (`slotCookieName`).
|
|
117
|
+
return name === cookieName || name.startsWith(`${cookieName}__`);
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
/** Test seam: forget what this isolate noted. */
|
|
121
|
+
export function resetPresenceMemo() {
|
|
122
|
+
noted.clear();
|
|
123
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cursedbelt-server",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.76.0",
|
|
4
4
|
"license": "ISC",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "The app-facing Bun/Hono server tier of the cursedbelt split — storage, sharing, activity, guard, sync. React-free; cursedbelt-core below it.",
|
|
@@ -168,6 +168,12 @@
|
|
|
168
168
|
"source": "./src/server/events/index.ts",
|
|
169
169
|
"import": "./dist/server/events/index.js"
|
|
170
170
|
},
|
|
171
|
+
"./presence": {
|
|
172
|
+
"types": "./dist/server/presence/index.d.ts",
|
|
173
|
+
"bun": "./src/server/presence/index.ts",
|
|
174
|
+
"source": "./src/server/presence/index.ts",
|
|
175
|
+
"import": "./dist/server/presence/index.js"
|
|
176
|
+
},
|
|
171
177
|
"./errors": {
|
|
172
178
|
"types": "./dist/server/errors.d.ts",
|
|
173
179
|
"bun": "./src/server/errors.ts",
|
|
@@ -441,7 +447,7 @@
|
|
|
441
447
|
"@node-rs/argon2": "^2.0.2",
|
|
442
448
|
"@types/bun": "^1.3.14",
|
|
443
449
|
"@types/node": "^24",
|
|
444
|
-
"cursedbelt": "^6.
|
|
450
|
+
"cursedbelt": "^6.13.1",
|
|
445
451
|
"hono": "4.12.28",
|
|
446
452
|
"kysely": "^0.28.17",
|
|
447
453
|
"kysely-bun-sqlite": "^0.4.0",
|
|
@@ -55,6 +55,45 @@ describe('perRowReads', () => {
|
|
|
55
55
|
});
|
|
56
56
|
});
|
|
57
57
|
|
|
58
|
+
describe('a search keyed by NULL (forge task 5517)', () => {
|
|
59
|
+
const byEntity = 'SEARCH f USING INDEX faces_entity (entity_id=?)';
|
|
60
|
+
const outer: PlanRow[] = [{ id: 4, parent: 0, detail: byEntity }];
|
|
61
|
+
|
|
62
|
+
test("the statement's `IS NULL` makes a one-column key read the table whole; `= ?` on the same plan does not", () => {
|
|
63
|
+
const hide = "UPDATE faces SET dismissed_at = ? WHERE id IN (SELECT f.id FROM faces f WHERE f.asset_id IN (SELECT value FROM json_each(?)) AND f.entity_id IS NULL)";
|
|
64
|
+
expect(perRowReads(outer, { perEvent: true, sql: hide })).toEqual([byEntity]);
|
|
65
|
+
expect(perRowReads(outer, { perEvent: true, sql: 'UPDATE faces SET dismissed_at = ? WHERE id IN (SELECT f.id FROM faces f WHERE f.entity_id = ?)' })).toEqual([]);
|
|
66
|
+
// Without the statement the plan alone cannot tell, so it stays a keyed search.
|
|
67
|
+
expect(perRowReads(outer, { perEvent: true })).toEqual([]);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test('another alias, a compound key, IS NOT NULL and a unary + are not a NULL key', () => {
|
|
71
|
+
expect(perRowReads(outer, { perEvent: true, sql: 'SELECT 1 FROM faces f JOIN faces g ON g.entity_id IS NULL WHERE f.entity_id = ?' })).toEqual([]);
|
|
72
|
+
expect(perRowReads(outer, { perEvent: true, sql: 'SELECT 1 FROM faces f WHERE f.entity_id IS NOT NULL' })).toEqual([]);
|
|
73
|
+
expect(perRowReads(outer, { perEvent: true, sql: 'SELECT 1 FROM faces f WHERE +f.entity_id IS NULL' })).toEqual([]);
|
|
74
|
+
expect(perRowReads([{ id: 4, parent: 0, detail: 'SEARCH f USING INDEX faces_entity (entity_id=? AND kind=?)' }], { perEvent: true, sql: 'SELECT 1 FROM faces f WHERE f.entity_id IS NULL AND f.kind = ?' })).toEqual([]);
|
|
75
|
+
// A bare column, the table read under its own name.
|
|
76
|
+
expect(perRowReads([{ id: 4, parent: 0, detail: 'SEARCH faces USING INDEX faces_entity (entity_id=?)' }], { perEvent: true, sql: 'UPDATE faces SET x = 1 WHERE entity_id IS NULL' })).toEqual([
|
|
77
|
+
'SEARCH faces USING INDEX faces_entity (entity_id=?)',
|
|
78
|
+
]);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
test('planOffenders reads the statement itself: a write reaching its rows by NULL is named, by the asked-for key passes', async () => {
|
|
82
|
+
const db = createLocalD1(new Database(':memory:'));
|
|
83
|
+
await db.batch([
|
|
84
|
+
db.prepare('CREATE TABLE faces (id TEXT PRIMARY KEY, asset_id TEXT, entity_id TEXT)'),
|
|
85
|
+
db.prepare('CREATE INDEX faces_asset ON faces (asset_id)'),
|
|
86
|
+
db.prepare('CREATE INDEX faces_entity ON faces (entity_id)'),
|
|
87
|
+
]);
|
|
88
|
+
const where = 'f.asset_id IN (SELECT value FROM json_each(?)) AND f.entity_id IS NULL';
|
|
89
|
+
const byNull = `UPDATE faces SET entity_id = 'x' WHERE id IN (SELECT f.id FROM faces f WHERE ${where})`;
|
|
90
|
+
expect((await planOf(db, byNull)).some((r) => r.detail === 'SEARCH f USING INDEX faces_entity (entity_id=?)')).toBe(true);
|
|
91
|
+
expect(await planOffenders(db, [byNull], { writes: true })).toEqual([`SEARCH f USING INDEX faces_entity (entity_id=?) ← ${byNull}`]);
|
|
92
|
+
const byAsset = `UPDATE faces SET entity_id = 'x' WHERE id IN (SELECT f.id FROM faces f INDEXED BY faces_asset WHERE ${where})`;
|
|
93
|
+
expect(await planOffenders(db, [byAsset], { writes: true })).toEqual([]);
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
|
|
58
97
|
describe('wholeTablePages', () => {
|
|
59
98
|
const sorted = (outer: string): PlanRow[] => [
|
|
60
99
|
{ id: 7, parent: 0, detail: outer },
|
package/src/server/d1/plans.ts
CHANGED
|
@@ -10,6 +10,12 @@
|
|
|
10
10
|
* 963 photographs. A page is held too: one that reads its table whole and sorts it to hand back its
|
|
11
11
|
* LIMIT pays for the archive on every page (photos' `albums/assets`, 331,190 rows for one page).
|
|
12
12
|
*
|
|
13
|
+
* A search keyed by `col IS NULL` alone is held the same way, whatever the column: the plan prints it as
|
|
14
|
+
* `(col=?)`, a keyed search, but the key is every row that has no value yet — usually most of the table.
|
|
15
|
+
* Photos' art-face hides reached `faces` through `faces_entity (entity_id=?)` for `f.entity_id IS NULL`,
|
|
16
|
+
* 16,314 of 23,978 faces per statement, twice per described photograph: 1.78 M rows read by one sync
|
|
17
|
+
* (forge task 5517). The plan cannot tell `= ?` from `IS NULL`, so the check reads the statement too.
|
|
18
|
+
*
|
|
13
19
|
* ```ts
|
|
14
20
|
* const statements = await preparedBy(db, () => app.request('/api/heavy'));
|
|
15
21
|
* expect(await planOffenders(db, statements)).toEqual([]);
|
|
@@ -36,20 +42,40 @@ export const LOW_CARDINALITY_COLUMNS: readonly string[] = ['state', 'status', 'd
|
|
|
36
42
|
export interface PlanCheckOptions {
|
|
37
43
|
/** Replaces {@link LOW_CARDINALITY_COLUMNS}. */
|
|
38
44
|
lowCardinality?: readonly string[];
|
|
45
|
+
/**
|
|
46
|
+
* The statement the plan is of. Given, a search keyed by one column alone that the statement tests
|
|
47
|
+
* `IS NULL` (`f.entity_id IS NULL` → `SEARCH f USING INDEX faces_entity (entity_id=?)`) reads every
|
|
48
|
+
* row with no value, and counts as reading its table whole. {@link planOffenders} always passes it.
|
|
49
|
+
*/
|
|
50
|
+
sql?: string;
|
|
39
51
|
}
|
|
40
52
|
|
|
41
53
|
const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
42
54
|
const lowCardinalityRule = (columns: readonly string[]): RegExp | null =>
|
|
43
55
|
columns.length === 0 ? null : new RegExp(` USING (?:COVERING )?INDEX \\S+ \\((?:${columns.map(escapeRegExp).join('|')})=\\?\\)`);
|
|
44
56
|
|
|
45
|
-
/**
|
|
46
|
-
|
|
57
|
+
/** `SEARCH <alias> [EXISTS ]USING [COVERING ]INDEX <index> (<column>=?)` — a search keyed by one column alone. */
|
|
58
|
+
const ONE_KEY = /^SEARCH (\S+) (?:EXISTS )?USING (?:COVERING )?INDEX \S+ \((\w+)=\?\)$/;
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Whether `sql` tests `alias.column IS NULL` (or a bare `column IS NULL`): the search {@link ONE_KEY} names is then
|
|
62
|
+
* keyed by NULL. A unary `+` (`+f.entity_id IS NULL`) is SQLite's way to keep a term off every index, so it is not one.
|
|
63
|
+
*/
|
|
64
|
+
function keyedByNull(detail: string, sql: string | undefined): boolean {
|
|
65
|
+
const m = sql ? ONE_KEY.exec(detail) : null;
|
|
66
|
+
if (!m || !sql) return false;
|
|
67
|
+
const [, alias, column] = m as unknown as [string, string, string];
|
|
68
|
+
return new RegExp(`(?<![\\w.+])(?:${escapeRegExp(alias)}\\.)?${escapeRegExp(column)}\\s+IS\\s+NULL\\b`, 'i').test(sql);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** A step that reads its table whole: a scan with no index, or a search by a low-cardinality column (or NULL) alone. */
|
|
72
|
+
function readsWhole(detail: string, derived: ReadonlySet<string>, low: RegExp | null, sql?: string): boolean {
|
|
47
73
|
const bareScan =
|
|
48
74
|
/^SCAN (?!CONSTANT ROW)/.test(detail) &&
|
|
49
75
|
!detail.includes(' VIRTUAL TABLE ') &&
|
|
50
76
|
!derived.has(detail.split(' ')[1] ?? '') &&
|
|
51
77
|
!/ USING (?:COVERING )?INDEX /.test(detail);
|
|
52
|
-
return bareScan || (low?.test(detail) ?? false);
|
|
78
|
+
return bareScan || (low?.test(detail) ?? false) || keyedByNull(detail, sql);
|
|
53
79
|
}
|
|
54
80
|
|
|
55
81
|
/** What a subquery made (`MATERIALIZE hit`, `CO-ROUTINE (subquery-1)`): its rows were counted where they were made. */
|
|
@@ -78,7 +104,7 @@ export function perRowSteps(plan: readonly PlanRow[]): PlanRow[] {
|
|
|
78
104
|
export function perRowReads(plan: readonly PlanRow[], opts: PlanCheckOptions & { perEvent?: boolean } = {}): string[] {
|
|
79
105
|
const derived = derivedOf(plan);
|
|
80
106
|
const low = lowCardinalityRule(opts.lowCardinality ?? LOW_CARDINALITY_COLUMNS);
|
|
81
|
-
return (opts.perEvent ? plan : perRowSteps(plan)).filter((r) => readsWhole(r.detail, derived, low)).map((r) => r.detail);
|
|
107
|
+
return (opts.perEvent ? plan : perRowSteps(plan)).filter((r) => readsWhole(r.detail, derived, low, opts.sql)).map((r) => r.detail);
|
|
82
108
|
}
|
|
83
109
|
|
|
84
110
|
/**
|
|
@@ -91,7 +117,7 @@ export function wholeTablePages(plan: readonly PlanRow[], opts: PlanCheckOptions
|
|
|
91
117
|
if (!outer.some((r) => r.detail === 'USE TEMP B-TREE FOR ORDER BY')) return [];
|
|
92
118
|
const derived = derivedOf(plan);
|
|
93
119
|
const low = lowCardinalityRule(opts.lowCardinality ?? LOW_CARDINALITY_COLUMNS);
|
|
94
|
-
return outer.filter((r) => readsWhole(r.detail, derived, low)).map((r) => r.detail);
|
|
120
|
+
return outer.filter((r) => readsWhole(r.detail, derived, low, opts.sql)).map((r) => r.detail);
|
|
95
121
|
}
|
|
96
122
|
|
|
97
123
|
/**
|
|
@@ -141,8 +167,8 @@ export async function planOffenders(
|
|
|
141
167
|
if (write ? !opts.writes : !/^\s*(?:SELECT|WITH)\b/i.test(sql)) continue;
|
|
142
168
|
const plan = await planOf(db, sql);
|
|
143
169
|
const where = sql.replace(/\s+/g, ' ').trim().slice(0, 160);
|
|
144
|
-
for (const step of perRowReads(plan, { ...opts, perEvent: write })) offenders.push(`${step} ← ${where}`);
|
|
145
|
-
if (!write && /\bLIMIT\b/i.test(sql)) for (const step of wholeTablePages(plan, opts)) offenders.push(`page: ${step} ← ${where}`);
|
|
170
|
+
for (const step of perRowReads(plan, { ...opts, perEvent: write, sql })) offenders.push(`${step} ← ${where}`);
|
|
171
|
+
if (!write && /\bLIMIT\b/i.test(sql)) for (const step of wholeTablePages(plan, { ...opts, sql })) offenders.push(`page: ${step} ← ${where}`);
|
|
146
172
|
}
|
|
147
173
|
return offenders;
|
|
148
174
|
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `cursedbelt-server/presence` — 🔴 an app nobody is using costs (close to) nothing (forge task 5325).
|
|
3
|
+
*
|
|
4
|
+
* The owner, 2026-11-16: *"if no one uses apps like photos, roms, flix, vault, desk, etc all day I don't
|
|
5
|
+
* want thousands of requests […] back and forth with no benefit."* Measured that day: the
|
|
6
|
+
* fleet's Worker crons fired ~6,500 times and spent ~172k CPU-ms — about a sixth of the account's Workers
|
|
7
|
+
* CPU, which the month was already past — and nearly all of it ran with nobody there. A five-minute cron
|
|
8
|
+
* is a promise to someone looking at the page; at 4 a.m. it is a promise to no one.
|
|
9
|
+
*
|
|
10
|
+
* So scheduled work keys on PRESENCE, not the clock (night is just the common case of idle):
|
|
11
|
+
*
|
|
12
|
+
* - **{@link createUseTick}** — work that used to run every few minutes runs on USE instead: a signed-in
|
|
13
|
+
* request kicks it under `waitUntil` when it is due, at most once per `everyMs` across every isolate
|
|
14
|
+
* ({@link claimTick} in D1). The Worker's own cron drops to the lowest cadence that is still correct
|
|
15
|
+
* with nobody there (an hourly backstop for queued work, the day's purge), and a stage tier keeps no
|
|
16
|
+
* cron at all: its tests in flight are the use that ticks it.
|
|
17
|
+
* - **{@link notePresence} / {@link lastPresence}** — for a Worker with no sign-in of its own (the media
|
|
18
|
+
* edge): it notes "a reader of <name> was here", throttled per isolate, and its cron asks before it
|
|
19
|
+
* spends anything.
|
|
20
|
+
* - **{@link lastHumanUse}** — for an app behind cursedauth's door: `sessions.last_seen_at` is ALREADY
|
|
21
|
+
* the signal. The door moves it on every signed-in request (`userIdOf`, throttled to a minute), so
|
|
22
|
+
* `MAX(last_seen_at)` is the tier's last human use, with no write of ours at all.
|
|
23
|
+
*
|
|
24
|
+
* Everything is created on first use (`presence_marks`, like `events_days` and the engagement tables),
|
|
25
|
+
* so no app's schema has to learn it. A failed claim runs nothing and warns: a lost tick is the next
|
|
26
|
+
* request's or the backstop cron's, never a double.
|
|
27
|
+
*
|
|
28
|
+
* `tools/check-idle-cost.ts` in the generation holds the other half: a sub-hourly cron or a stage cron
|
|
29
|
+
* that does not go through here is red.
|
|
30
|
+
*
|
|
31
|
+
* 🔴 Worker-safe: nothing here imports `bun:*`.
|
|
32
|
+
*/
|
|
33
|
+
import type { D1LikeDatabase } from "../d1/types.js";
|
|
34
|
+
|
|
35
|
+
/** One row per name: a presence mark (`reader:<tenant>`) or a tick's last run (`tick:<name>`). */
|
|
36
|
+
export const PRESENCE_DDL = ["CREATE TABLE IF NOT EXISTS presence_marks (name TEXT PRIMARY KEY, at INTEGER NOT NULL)"];
|
|
37
|
+
|
|
38
|
+
/** How often one isolate writes the same presence mark. Presence is an hours-scale question. */
|
|
39
|
+
export const PRESENCE_THROTTLE_MS = 5 * 60_000;
|
|
40
|
+
|
|
41
|
+
/** The default "nobody is here" line: no use for this long and scheduled work stands down. */
|
|
42
|
+
export const IDLE_AFTER_MS = 3 * 60 * 60_000;
|
|
43
|
+
|
|
44
|
+
const TICK_PREFIX = "tick:";
|
|
45
|
+
|
|
46
|
+
/** An upsert that only moves `at` when the row is older than `?3` — the claim and the throttled mark both. */
|
|
47
|
+
const UPSERT_IF_OLDER =
|
|
48
|
+
"INSERT INTO presence_marks (name, at) VALUES (?1, ?2) ON CONFLICT(name) DO UPDATE SET at = excluded.at WHERE presence_marks.at <= ?3";
|
|
49
|
+
|
|
50
|
+
const isMissingTable = (error: unknown): boolean => /no such table/i.test(String(error));
|
|
51
|
+
|
|
52
|
+
async function upsertIfOlder(db: D1LikeDatabase, name: string, at: number, olderThan: number): Promise<boolean> {
|
|
53
|
+
const run = () => db.prepare(UPSERT_IF_OLDER).bind(name, at, olderThan).run();
|
|
54
|
+
const result = await run().catch(async (error: unknown) => {
|
|
55
|
+
if (!isMissingTable(error)) throw error;
|
|
56
|
+
await db.batch(PRESENCE_DDL.map((ddl) => db.prepare(ddl)));
|
|
57
|
+
return run();
|
|
58
|
+
});
|
|
59
|
+
return (result.meta?.changes ?? 0) > 0;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** What this isolate last wrote or attempted, per name — so a busy Worker asks D1 once per throttle. */
|
|
63
|
+
const noted = new Map<string, number>();
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Note that someone used `name` now. At most one D1 write per isolate per `throttleMs`, and the row only
|
|
67
|
+
* moves when it is older than that, so many isolates add up to a handful of writes an hour while anyone is
|
|
68
|
+
* there and none while no one is. Resolves `true` when it wrote; never throws (presence is advisory).
|
|
69
|
+
*/
|
|
70
|
+
export async function notePresence(
|
|
71
|
+
db: D1LikeDatabase,
|
|
72
|
+
name: string,
|
|
73
|
+
options: { now?: () => number; throttleMs?: number } = {},
|
|
74
|
+
): Promise<boolean> {
|
|
75
|
+
const now = (options.now ?? Date.now)();
|
|
76
|
+
const throttle = options.throttleMs ?? PRESENCE_THROTTLE_MS;
|
|
77
|
+
const last = noted.get(name);
|
|
78
|
+
if (last !== undefined && now - last < throttle) return false;
|
|
79
|
+
noted.set(name, now);
|
|
80
|
+
try {
|
|
81
|
+
return await upsertIfOlder(db, name, now, now - throttle);
|
|
82
|
+
} catch (error) {
|
|
83
|
+
console.warn(`[presence] ${name} was not noted: ${String(error)}`);
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** When `name` was last noted (epoch ms), or null — never noted, or no table yet. Throws on any other error. */
|
|
89
|
+
export async function lastPresence(db: D1LikeDatabase, name: string): Promise<number | null> {
|
|
90
|
+
try {
|
|
91
|
+
const row = await db.prepare("SELECT at FROM presence_marks WHERE name = ?").bind(name).first<{ at: number }>();
|
|
92
|
+
return typeof row?.at === "number" ? row.at : null;
|
|
93
|
+
} catch (error) {
|
|
94
|
+
if (isMissingTable(error)) return null;
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* The tier's last human use behind cursedauth's door: `MAX(sessions.last_seen_at)`, which the door's
|
|
101
|
+
* `userIdOf` moves on every signed-in request. Null when nobody has a session, or the app has no
|
|
102
|
+
* `sessions` table. A row read per live session — a household's handful.
|
|
103
|
+
*/
|
|
104
|
+
export async function lastHumanUse(db: D1LikeDatabase): Promise<number | null> {
|
|
105
|
+
try {
|
|
106
|
+
const row = await db.prepare("SELECT MAX(last_seen_at) AS at FROM sessions").first<{ at: number | null }>();
|
|
107
|
+
return typeof row?.at === "number" && row.at > 0 ? row.at : null;
|
|
108
|
+
} catch (error) {
|
|
109
|
+
if (isMissingTable(error)) return null;
|
|
110
|
+
throw error;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Whether a last use at `lastAt` still counts as someone being here. Null (never) is idle. Pure. */
|
|
115
|
+
export function isPresent(lastAt: number | null, now: number = Date.now(), idleAfterMs: number = IDLE_AFTER_MS): boolean {
|
|
116
|
+
return lastAt !== null && now - lastAt < idleAfterMs;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Claim tick `name` if its last run is at least `everyMs` old — one D1 statement, atomic, so of every
|
|
121
|
+
* isolate and cron that asks inside the window exactly one wins. `everyMs: 0` always wins: what a cron
|
|
122
|
+
* calls to record that it ran, so the next request does not run the same work again a minute later.
|
|
123
|
+
*/
|
|
124
|
+
export async function claimTick(db: D1LikeDatabase, name: string, everyMs: number, now: number = Date.now()): Promise<boolean> {
|
|
125
|
+
return upsertIfOlder(db, TICK_PREFIX + name, now, now - everyMs);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** When tick `name` last ran (epoch ms), or null. */
|
|
129
|
+
export const lastTick = (db: D1LikeDatabase, name: string): Promise<number | null> => lastPresence(db, TICK_PREFIX + name);
|
|
130
|
+
|
|
131
|
+
export interface UseTickKick {
|
|
132
|
+
db: D1LikeDatabase;
|
|
133
|
+
/** The work — the same function the cron runs. Its errors are logged, never thrown at the request. */
|
|
134
|
+
run: () => Promise<unknown>;
|
|
135
|
+
/** The request's `ctx.waitUntil`: the tick never holds the answer. */
|
|
136
|
+
waitUntil: (promise: Promise<unknown>) => void;
|
|
137
|
+
now?: () => number;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export interface UseTick {
|
|
141
|
+
/** Start the tick behind this request if it is due. True when it was started (and won its claim or is asking). */
|
|
142
|
+
kick(input: UseTickKick): boolean;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Work that runs because someone is USING the app (see the header): `kick` on a signed-in request.
|
|
147
|
+
* The isolate remembers its last attempt, so a page's burst of requests costs one claim, and the claim
|
|
148
|
+
* in D1 keeps every isolate together to one run per `everyMs`.
|
|
149
|
+
*/
|
|
150
|
+
export function createUseTick(options: { name: string; everyMs: number }): UseTick {
|
|
151
|
+
let attempted = Number.NEGATIVE_INFINITY;
|
|
152
|
+
return {
|
|
153
|
+
kick({ db, run, waitUntil, now = Date.now }) {
|
|
154
|
+
const at = now();
|
|
155
|
+
if (at - attempted < options.everyMs) return false;
|
|
156
|
+
attempted = at;
|
|
157
|
+
waitUntil(
|
|
158
|
+
claimTick(db, options.name, options.everyMs, at)
|
|
159
|
+
.then((won) => (won ? run() : undefined))
|
|
160
|
+
.catch((error: unknown) => console.warn(`[presence] the ${options.name} tick failed: ${String(error)}`)),
|
|
161
|
+
);
|
|
162
|
+
return true;
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Whether a request is a person using the app — it carries the app's own session cookie. A stale cookie
|
|
169
|
+
* counts too: the price of a false yes is one tick, while a probe, a crawler, the Mac's bearer-token
|
|
170
|
+
* pipeline and `/healthz` carry no cookie and never tick anything.
|
|
171
|
+
*/
|
|
172
|
+
export function carriesSession(request: Request, cookieName: string): boolean {
|
|
173
|
+
const cookie = request.headers.get("cookie");
|
|
174
|
+
if (!cookie) return false;
|
|
175
|
+
return cookie.split(";").some((part) => {
|
|
176
|
+
const name = part.trim().split("=", 1)[0];
|
|
177
|
+
// cursedauth's account slots: `<base>` is slot 0, `<base>__<n>` the others (`slotCookieName`).
|
|
178
|
+
return name === cookieName || name.startsWith(`${cookieName}__`);
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Test seam: forget what this isolate noted. */
|
|
183
|
+
export function resetPresenceMemo(): void {
|
|
184
|
+
noted.clear();
|
|
185
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { Database } from "bun:sqlite";
|
|
2
|
+
import { afterEach, describe, expect, test } from "bun:test";
|
|
3
|
+
import { createLocalD1 } from "../d1/local.js";
|
|
4
|
+
import type { D1LikeDatabase } from "../d1/types.js";
|
|
5
|
+
import {
|
|
6
|
+
carriesSession,
|
|
7
|
+
claimTick,
|
|
8
|
+
createUseTick,
|
|
9
|
+
IDLE_AFTER_MS,
|
|
10
|
+
isPresent,
|
|
11
|
+
lastHumanUse,
|
|
12
|
+
lastPresence,
|
|
13
|
+
lastTick,
|
|
14
|
+
notePresence,
|
|
15
|
+
PRESENCE_THROTTLE_MS,
|
|
16
|
+
resetPresenceMemo,
|
|
17
|
+
} from "./index.js";
|
|
18
|
+
|
|
19
|
+
const T0 = Date.UTC(2026, 10, 17, 4, 0);
|
|
20
|
+
const MIN = 60_000;
|
|
21
|
+
const fresh = (): D1LikeDatabase => createLocalD1(new Database(":memory:"));
|
|
22
|
+
|
|
23
|
+
afterEach(() => resetPresenceMemo());
|
|
24
|
+
|
|
25
|
+
describe("notePresence / lastPresence — a throttled mark, created on first use", () => {
|
|
26
|
+
test("no table yet reads as never; the first note creates it", async () => {
|
|
27
|
+
const db = fresh();
|
|
28
|
+
expect(await lastPresence(db, "reader:photos")).toBeNull();
|
|
29
|
+
expect(await notePresence(db, "reader:photos", { now: () => T0 })).toBe(true);
|
|
30
|
+
expect(await lastPresence(db, "reader:photos")).toBe(T0);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test("one isolate writes a name at most once per throttle; another isolate inside it moves nothing", async () => {
|
|
34
|
+
const db = fresh();
|
|
35
|
+
expect(await notePresence(db, "reader:photos", { now: () => T0 })).toBe(true);
|
|
36
|
+
expect(await notePresence(db, "reader:photos", { now: () => T0 + MIN })).toBe(false);
|
|
37
|
+
resetPresenceMemo(); // another isolate, same database
|
|
38
|
+
expect(await notePresence(db, "reader:photos", { now: () => T0 + MIN })).toBe(false);
|
|
39
|
+
expect(await lastPresence(db, "reader:photos")).toBe(T0);
|
|
40
|
+
resetPresenceMemo();
|
|
41
|
+
expect(await notePresence(db, "reader:photos", { now: () => T0 + PRESENCE_THROTTLE_MS })).toBe(true);
|
|
42
|
+
expect(await lastPresence(db, "reader:photos")).toBe(T0 + PRESENCE_THROTTLE_MS);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test("a database that refuses is a warning and false, never a throw at the request", async () => {
|
|
46
|
+
const broken = {
|
|
47
|
+
prepare: () => ({ bind: () => ({ run: () => Promise.reject(new Error("D1_ERROR: overloaded")) }) }),
|
|
48
|
+
} as unknown as D1LikeDatabase;
|
|
49
|
+
expect(await notePresence(broken, "reader:photos", { now: () => T0 })).toBe(false);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
test("lastPresence still throws on an error that is not a missing table", async () => {
|
|
53
|
+
const broken = {
|
|
54
|
+
prepare: () => ({ bind: () => ({ first: () => Promise.reject(new Error("D1_ERROR: overloaded")) }) }),
|
|
55
|
+
} as unknown as D1LikeDatabase;
|
|
56
|
+
await expect(lastPresence(broken, "reader:photos")).rejects.toThrow("overloaded");
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
describe("lastHumanUse — cursedauth's sessions.last_seen_at is the signal", () => {
|
|
61
|
+
test("no sessions table is null; an empty one is null; otherwise the newest last_seen_at", async () => {
|
|
62
|
+
const db = fresh();
|
|
63
|
+
expect(await lastHumanUse(db)).toBeNull();
|
|
64
|
+
await db.prepare("CREATE TABLE sessions (id TEXT PRIMARY KEY, last_seen_at INTEGER NOT NULL DEFAULT 0)").run();
|
|
65
|
+
expect(await lastHumanUse(db)).toBeNull();
|
|
66
|
+
await db.prepare("INSERT INTO sessions (id, last_seen_at) VALUES ('a', ?), ('b', ?), ('c', 0)").bind(T0 - 5 * MIN, T0).run();
|
|
67
|
+
expect(await lastHumanUse(db)).toBe(T0);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test("isPresent: never is idle; inside the line is present; at it is idle", () => {
|
|
71
|
+
expect(isPresent(null, T0)).toBe(false);
|
|
72
|
+
expect(isPresent(T0 - IDLE_AFTER_MS + 1, T0)).toBe(true);
|
|
73
|
+
expect(isPresent(T0 - IDLE_AFTER_MS, T0)).toBe(false);
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
describe("claimTick — one winner per window across every isolate", () => {
|
|
78
|
+
test("first claim wins, a second inside the window loses, the next window wins", async () => {
|
|
79
|
+
const db = fresh();
|
|
80
|
+
expect(await claimTick(db, "cron", 5 * MIN, T0)).toBe(true);
|
|
81
|
+
expect(await claimTick(db, "cron", 5 * MIN, T0 + 4 * MIN)).toBe(false);
|
|
82
|
+
expect(await claimTick(db, "cron", 5 * MIN, T0 + 5 * MIN)).toBe(true);
|
|
83
|
+
expect(await lastTick(db, "cron")).toBe(T0 + 5 * MIN);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
test("everyMs 0 always wins — the cron's own record that it ran", async () => {
|
|
87
|
+
const db = fresh();
|
|
88
|
+
expect(await claimTick(db, "cron", 5 * MIN, T0)).toBe(true);
|
|
89
|
+
expect(await claimTick(db, "cron", 0, T0 + MIN)).toBe(true);
|
|
90
|
+
expect(await claimTick(db, "cron", 5 * MIN, T0 + 3 * MIN)).toBe(false);
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
describe("createUseTick — work on use, not on the clock", () => {
|
|
95
|
+
const kicker = (db: D1LikeDatabase, runs: number[], pending: Promise<unknown>[]) => (tick: ReturnType<typeof createUseTick>, at: number) =>
|
|
96
|
+
tick.kick({ db, now: () => at, waitUntil: (p) => pending.push(p), run: async () => runs.push(at) });
|
|
97
|
+
|
|
98
|
+
test("a burst of requests runs the work once; the next window runs it again", async () => {
|
|
99
|
+
const db = fresh();
|
|
100
|
+
const runs: number[] = [];
|
|
101
|
+
const pending: Promise<unknown>[] = [];
|
|
102
|
+
const tick = createUseTick({ name: "cron", everyMs: 5 * MIN });
|
|
103
|
+
const kick = kicker(db, runs, pending);
|
|
104
|
+
expect(kick(tick, T0)).toBe(true);
|
|
105
|
+
expect(kick(tick, T0 + 1000)).toBe(false); // the isolate's memory: no D1 at all
|
|
106
|
+
await Promise.all(pending);
|
|
107
|
+
expect(kick(tick, T0 + 5 * MIN)).toBe(true);
|
|
108
|
+
await Promise.all(pending);
|
|
109
|
+
expect(runs).toEqual([T0, T0 + 5 * MIN]);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
test("two isolates inside one window: one runs, the other's claim loses", async () => {
|
|
113
|
+
const db = fresh();
|
|
114
|
+
const runs: number[] = [];
|
|
115
|
+
const pending: Promise<unknown>[] = [];
|
|
116
|
+
const kick = kicker(db, runs, pending);
|
|
117
|
+
kick(createUseTick({ name: "cron", everyMs: 5 * MIN }), T0);
|
|
118
|
+
await Promise.all(pending);
|
|
119
|
+
kick(createUseTick({ name: "cron", everyMs: 5 * MIN }), T0 + MIN);
|
|
120
|
+
await Promise.all(pending);
|
|
121
|
+
expect(runs).toEqual([T0]);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
test("a cron that just ran (claimTick everyMs 0) holds the next request off", async () => {
|
|
125
|
+
const db = fresh();
|
|
126
|
+
const runs: number[] = [];
|
|
127
|
+
const pending: Promise<unknown>[] = [];
|
|
128
|
+
await claimTick(db, "cron", 0, T0);
|
|
129
|
+
kicker(db, runs, pending)(createUseTick({ name: "cron", everyMs: 5 * MIN }), T0 + MIN);
|
|
130
|
+
await Promise.all(pending);
|
|
131
|
+
expect(runs).toEqual([]);
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
test("work that throws is logged under waitUntil, never thrown at the request", async () => {
|
|
135
|
+
const db = fresh();
|
|
136
|
+
const pending: Promise<unknown>[] = [];
|
|
137
|
+
const tick = createUseTick({ name: "cron", everyMs: 5 * MIN });
|
|
138
|
+
const started = tick.kick({
|
|
139
|
+
db,
|
|
140
|
+
now: () => T0,
|
|
141
|
+
waitUntil: (p) => pending.push(p),
|
|
142
|
+
run: () => Promise.reject(new Error("queue down")),
|
|
143
|
+
});
|
|
144
|
+
expect(started).toBe(true);
|
|
145
|
+
await expect(Promise.all(pending)).resolves.toBeDefined();
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
describe("carriesSession — a person, not a probe", () => {
|
|
150
|
+
const req = (cookie?: string) => new Request("https://photos.example/api/albums", cookie ? { headers: { cookie } } : {});
|
|
151
|
+
test("the app's cookie, and its account-slot cookies, count", () => {
|
|
152
|
+
expect(carriesSession(req("photos_session=abc"), "photos_session")).toBe(true);
|
|
153
|
+
expect(carriesSession(req("theme=dark; photos_session__2=abc"), "photos_session")).toBe(true);
|
|
154
|
+
});
|
|
155
|
+
test("no cookie, another app's cookie, or a name that only starts the same do not", () => {
|
|
156
|
+
expect(carriesSession(req(), "photos_session")).toBe(false);
|
|
157
|
+
expect(carriesSession(req("family_session=abc"), "photos_session")).toBe(false);
|
|
158
|
+
expect(carriesSession(req("photos_sessionx=abc"), "photos_session")).toBe(false);
|
|
159
|
+
});
|
|
160
|
+
});
|