@cloudhal/cloudflare 0.0.0-stage → 0.1.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/LICENSE +202 -0
- package/README.md +22 -2
- package/dist/src/admin-worker.d.ts +148 -0
- package/dist/src/admin-worker.js +569 -0
- package/dist/src/browser-render.d.ts +18 -0
- package/dist/src/browser-render.js +127 -0
- package/dist/src/build-rooms.d.ts +36 -0
- package/dist/src/build-rooms.js +135 -0
- package/dist/src/comments.d.ts +94 -0
- package/dist/src/comments.js +281 -0
- package/dist/src/features.d.ts +24 -0
- package/dist/src/features.js +59 -0
- package/dist/src/mail.d.ts +37 -0
- package/dist/src/mail.js +69 -0
- package/dist/src/purge.d.ts +58 -0
- package/dist/src/purge.js +109 -0
- package/dist/src/scheduler.d.ts +149 -0
- package/dist/src/scheduler.js +573 -0
- package/dist/src/site-routes.d.ts +23 -0
- package/dist/src/site-routes.js +61 -0
- package/dist/src/workerd-prelude.d.ts +1 -0
- package/dist/src/workerd-prelude.js +17 -0
- package/package.json +72 -3
|
@@ -0,0 +1,573 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The scheduler on Cloudflare (RFC-0008 §8.2–§8.7). One `runDue` per tick, whatever woke it:
|
|
3
|
+
*
|
|
4
|
+
* - **cron** (`* * * * *`, `CLOUDHAL_SCHEDULER=cron`, the default): the admin Worker's
|
|
5
|
+
* `scheduled` handler, `controller.scheduledTime` as the tick's `now`;
|
|
6
|
+
* - **alarm** (`CLOUDHAL_SCHEDULER=alarm`, when Cloudflare refused the cron trigger): the
|
|
7
|
+
* SQLite-backed `SchedulerClock` Durable Object. It holds no state: `alarm()` runs a tick, never
|
|
8
|
+
* throws, and re-arms at `min(nextWakeAt, now + 1 h)` (`now + 1 s` while there is more). Pokes
|
|
9
|
+
* (`POST /poke {at}`) move the alarm earlier when a release or an automation becomes due sooner;
|
|
10
|
+
* cron ignores them;
|
|
11
|
+
* - **request** (every mode): an admin request reads the heartbeat at most once a minute per
|
|
12
|
+
* isolate and, when it is more than two minutes behind, runs a tick in `waitUntil` (and re-arms
|
|
13
|
+
* the clock in alarm mode). A safety net, never the scheduler.
|
|
14
|
+
*
|
|
15
|
+
* The analytics rollup and the comments job are `SystemJobDefinition`s behind `system_jobs`
|
|
16
|
+
* watermarks (every hour at :17), with today's code and log lines; `schedules.retention` runs daily.
|
|
17
|
+
* Their statements count against the tick (`wrapCounting`) without being refused.
|
|
18
|
+
*
|
|
19
|
+
* A published release's purge plan goes through the site Worker like a publish's, logged in the
|
|
20
|
+
* shared purge budget (`cache_purge_log`, source `schedules`); when the bucket is empty the tags
|
|
21
|
+
* go into the comment purge queue (tag-generic) and the outcome records `deferred`.
|
|
22
|
+
*
|
|
23
|
+
* Legacy: a deployment configured before RFC-0008 without a cron slot carries
|
|
24
|
+
* `CLOUDHAL_ANALYTICS_CRON=off` / `CLOUDHAL_COMMENTS_CRON=off`; both read as `alarm` until the next
|
|
25
|
+
* `cloudhal deploy` removes them.
|
|
26
|
+
*/
|
|
27
|
+
import { releaseApprovalCheck } from "@cloudhal/api";
|
|
28
|
+
import { PURGE_LIMITS } from "@cloudhal/comments";
|
|
29
|
+
import { SqlCommentStore } from "@cloudhal/comments/sql";
|
|
30
|
+
import {
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
SiteGraphStore,
|
|
34
|
+
searchProviderFromEnv,
|
|
35
|
+
siteCacheTag,
|
|
36
|
+
} from "@cloudhal/core-ts";
|
|
37
|
+
import {
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
notFoundFromAnalytics,
|
|
41
|
+
} from "@cloudhal/core-ts/automations";
|
|
42
|
+
import {
|
|
43
|
+
CRON_RUNTIME,
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
runScheduledTick,
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
} from "@cloudhal/core-ts/releases";
|
|
50
|
+
import {
|
|
51
|
+
backstopDue,
|
|
52
|
+
dailyAt,
|
|
53
|
+
HOUR_MS,
|
|
54
|
+
hourlyAt,
|
|
55
|
+
|
|
56
|
+
TICK_BUDGETS,
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
} from "@cloudhal/schedules";
|
|
61
|
+
import { SqlScheduleStore } from "@cloudhal/schedules/sql";
|
|
62
|
+
|
|
63
|
+
import { D1Driver } from "@cloudhal/storage/d1";
|
|
64
|
+
import { R2BlobStore } from "@cloudhal/storage/r2";
|
|
65
|
+
import { flushCommentPurges, runCommentsHourly } from "./comments.js";
|
|
66
|
+
import { PURGE_MAX_REQUESTS, PURGE_TAGS_PER_REQUEST } from "./purge.js";
|
|
67
|
+
import { attachedSite, bindingFor, routedSite } from "./site-routes.js";
|
|
68
|
+
|
|
69
|
+
/** What the scheduler reads from the admin Worker's environment. */
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
/** The clock's one instance (`getByName("clock")`, §8.3). */
|
|
96
|
+
export const CLOCK_NAME = "clock";
|
|
97
|
+
const CLOCK_URL = "https://scheduler-clock.internal";
|
|
98
|
+
const PURGE_URL = "https://site.internal/__cloudhal/purge";
|
|
99
|
+
|
|
100
|
+
/** `CLOUDHAL_SCHEDULER`, else the legacy `*_CRON=off` vars as `alarm`, else `cron`. */
|
|
101
|
+
export function schedulerMode(env ) {
|
|
102
|
+
if (env.CLOUDHAL_SCHEDULER === "alarm" || env.CLOUDHAL_SCHEDULER === "cron")
|
|
103
|
+
return env.CLOUDHAL_SCHEDULER;
|
|
104
|
+
if (env.CLOUDHAL_ANALYTICS_CRON === "off" || env.CLOUDHAL_COMMENTS_CRON === "off") return "alarm";
|
|
105
|
+
return "cron";
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The per-tick budget: Workers Free unless the deployment says it is on Paid. */
|
|
109
|
+
export function tickBudget(env ) {
|
|
110
|
+
return env.CLOUDHAL_TICK_BUDGET === "paid" ? TICK_BUDGETS.paid : TICK_BUDGETS.free;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function clockStub(env ) {
|
|
114
|
+
const ns = env.SCHEDULER_CLOCK;
|
|
115
|
+
return ns ? ns.get(ns.idFromName(CLOCK_NAME)) : undefined;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Moves the clock's alarm to `at` when that is sooner (or arms a lost one). Never throws. */
|
|
119
|
+
export async function pokeClock(
|
|
120
|
+
env ,
|
|
121
|
+
at ,
|
|
122
|
+
log = () => {},
|
|
123
|
+
) {
|
|
124
|
+
const stub = clockStub(env);
|
|
125
|
+
if (!stub) return;
|
|
126
|
+
try {
|
|
127
|
+
const res = await stub.fetch(`${CLOCK_URL}/poke`, {
|
|
128
|
+
method: "POST",
|
|
129
|
+
headers: { "content-type": "application/json" },
|
|
130
|
+
body: JSON.stringify({ at: typeof at === "number" ? at : Date.parse(at) }),
|
|
131
|
+
});
|
|
132
|
+
await res.body?.cancel();
|
|
133
|
+
} catch (e) {
|
|
134
|
+
log(`scheduler clock poke failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** The ticker as the API sees it (`ApiDeps.scheduler`): alarm mode pokes the clock. */
|
|
139
|
+
export function schedulerRuntime(
|
|
140
|
+
env ,
|
|
141
|
+
log = () => {},
|
|
142
|
+
) {
|
|
143
|
+
const mode = schedulerMode(env);
|
|
144
|
+
if (mode !== "alarm") return CRON_RUNTIME;
|
|
145
|
+
return { mode, poke: (at) => pokeClock(env, at, log) };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// ───────────────────────────── purge ─────────────────────────────
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Sends a published release's stored purge plan through the site Worker (≤ 3 tag requests, else
|
|
152
|
+
* one "purge everything"), each request logged in `cache_purge_log` (source `schedules`). A failed
|
|
153
|
+
* request (`success: false` is a 502 from the site Worker: the bucket is empty) puts what is left
|
|
154
|
+
* into the purge queue and answers `deferred`; `wake` asks for a flush once the tags are ripe.
|
|
155
|
+
*/
|
|
156
|
+
export function releasePurger(
|
|
157
|
+
env ,
|
|
158
|
+
sql ,
|
|
159
|
+
o = {},
|
|
160
|
+
) {
|
|
161
|
+
const log = o.log ?? (() => {});
|
|
162
|
+
return async (siteId , plan ) => {
|
|
163
|
+
const site = routedSite(env);
|
|
164
|
+
const token = env.CLOUDHAL_PURGE_TOKEN;
|
|
165
|
+
if (!site || !token) return "none";
|
|
166
|
+
const queue = new SqlCommentStore(sql).purgeQueue;
|
|
167
|
+
const defer = async (tags , why ) => {
|
|
168
|
+
try {
|
|
169
|
+
await queue.enqueue(siteId, tags, "normal");
|
|
170
|
+
o.wake?.(siteId);
|
|
171
|
+
log(`schedules purge for ${siteId} deferred (${why}): ${tags.length} tag(s) queued`);
|
|
172
|
+
return "deferred";
|
|
173
|
+
} catch (e) {
|
|
174
|
+
log(`schedules purge for ${siteId} failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
175
|
+
return "failed";
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
const send = async (tags ) => {
|
|
179
|
+
let ok = false;
|
|
180
|
+
try {
|
|
181
|
+
const res = await site.fetch(PURGE_URL, {
|
|
182
|
+
method: "POST",
|
|
183
|
+
// RFC-0034 §4: the site is named, so a multi-site Worker purges only its tags.
|
|
184
|
+
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
|
|
185
|
+
body: JSON.stringify({ siteId, ...(tags ? { tags } : {}) }),
|
|
186
|
+
});
|
|
187
|
+
ok = res.ok;
|
|
188
|
+
await res.body?.cancel();
|
|
189
|
+
} finally {
|
|
190
|
+
try {
|
|
191
|
+
await queue.log("schedules");
|
|
192
|
+
} catch {
|
|
193
|
+
// the log is a budget hint: never fail a purge over it
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return ok;
|
|
197
|
+
};
|
|
198
|
+
const everything =
|
|
199
|
+
plan.mode === "everything" || plan.tags.length > PURGE_TAGS_PER_REQUEST * PURGE_MAX_REQUESTS;
|
|
200
|
+
if (everything) {
|
|
201
|
+
const ok = await send().catch(() => false);
|
|
202
|
+
return ok ? "everything" : defer([siteCacheTag(siteId)], "the purge budget is empty");
|
|
203
|
+
}
|
|
204
|
+
if (plan.tags.length === 0) return "none";
|
|
205
|
+
for (let i = 0; i < plan.tags.length; i += PURGE_TAGS_PER_REQUEST) {
|
|
206
|
+
const batch = plan.tags.slice(i, i + PURGE_TAGS_PER_REQUEST);
|
|
207
|
+
const ok = await send(batch).catch(() => false);
|
|
208
|
+
if (!ok) return defer(plan.tags.slice(i), "the purge budget is empty");
|
|
209
|
+
}
|
|
210
|
+
return "tags";
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// ───────────────────────────── system jobs ─────────────────────────────
|
|
215
|
+
|
|
216
|
+
/** What the analytics rollup needs (the admin Worker passes `adminAnalytics`). */
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* The deployment's periodic jobs (§8.2): today's hourly code behind watermarks, with today's log
|
|
235
|
+
* lines; `comments.hourly` only where comments are on.
|
|
236
|
+
*/
|
|
237
|
+
export function adminSystemJobs(
|
|
238
|
+
env ,
|
|
239
|
+
sql ,
|
|
240
|
+
o
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
,
|
|
245
|
+
) {
|
|
246
|
+
const { log } = o;
|
|
247
|
+
const graph = () => new SiteGraphStore({ sql, blobs: new R2BlobStore(env.BLOBS) });
|
|
248
|
+
const jobs = [
|
|
249
|
+
{
|
|
250
|
+
name: "analytics.rollup",
|
|
251
|
+
cost: 20,
|
|
252
|
+
next: hourlyAt(17),
|
|
253
|
+
async run({ now }) {
|
|
254
|
+
const analytics = o.analytics(sql, now);
|
|
255
|
+
const siteIds = (await graph().listSites()).map((s) => s.id);
|
|
256
|
+
const report = await analytics.rollup({ siteIds });
|
|
257
|
+
const failed = report.failed.map((f) => `${f.siteId} ${f.day}: ${f.error}`);
|
|
258
|
+
log(
|
|
259
|
+
`analytics rollup (${analytics.feature().reader}): ${report.done.length} site-day(s) done, ${report.pending} pending, ${report.saltsDeleted} salt(s) deleted, ${report.retained} row(s) past retention${failed.length ? `; failed: ${failed.join("; ")}` : ""}`,
|
|
260
|
+
);
|
|
261
|
+
},
|
|
262
|
+
},
|
|
263
|
+
{
|
|
264
|
+
name: "schedules.retention",
|
|
265
|
+
cost: 3,
|
|
266
|
+
next: dailyAt(3, 27),
|
|
267
|
+
async run({ now }) {
|
|
268
|
+
const r = await new SqlScheduleStore(sql).applyRetention(now.toISOString());
|
|
269
|
+
if (r.runs + r.releases > 0)
|
|
270
|
+
log(`schedules retention: ${r.runs} run(s), ${r.releases} release(s) deleted`);
|
|
271
|
+
},
|
|
272
|
+
},
|
|
273
|
+
];
|
|
274
|
+
if (o.commentsOn)
|
|
275
|
+
jobs.push({
|
|
276
|
+
name: "comments.hourly",
|
|
277
|
+
cost: 20,
|
|
278
|
+
next: hourlyAt(17),
|
|
279
|
+
async run({ now }) {
|
|
280
|
+
const comments = new SqlCommentStore(sql);
|
|
281
|
+
const c = await runCommentsHourly({ graph: graph(), store: comments, now });
|
|
282
|
+
log(
|
|
283
|
+
`comments hourly: ${c.sites} site(s), ${c.retained} row(s) past retention${c.more ? " (more next run)" : ""}, ${c.deletedEntries} of deleted entries, ${c.closed} thread(s) closed, ${c.salts} salt(s) deleted`,
|
|
284
|
+
);
|
|
285
|
+
const site = routedSite(env);
|
|
286
|
+
if (site && env.CLOUDHAL_PURGE_TOKEN) {
|
|
287
|
+
const f = await flushCommentPurges({
|
|
288
|
+
store: comments,
|
|
289
|
+
fetch: (u, init) => site.fetch(u, init ) ,
|
|
290
|
+
token: env.CLOUDHAL_PURGE_TOKEN,
|
|
291
|
+
now: () => now,
|
|
292
|
+
log,
|
|
293
|
+
});
|
|
294
|
+
log(
|
|
295
|
+
`comments purge backstop: ${f.sent.length} request(s), ${f.failed} failed${f.takedownWaiting ? ", a takedown is waiting" : ""}`,
|
|
296
|
+
);
|
|
297
|
+
}
|
|
298
|
+
},
|
|
299
|
+
});
|
|
300
|
+
return jobs;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// ───────────────────────────── built-in jobs ─────────────────────────────
|
|
304
|
+
|
|
305
|
+
const SITE_ORIGIN = "https://site.internal";
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Where the site Worker answers for `siteId`, or undefined when it does not serve it. A multi-site
|
|
309
|
+
* Worker picks the site by hostname (RFC-0034 §4), so the request carries the site's primary host
|
|
310
|
+
* (a service-binding request never leaves Cloudflare, whatever its host).
|
|
311
|
+
*/
|
|
312
|
+
async function siteOrigin(env , siteId ) {
|
|
313
|
+
const served = (env.CLOUDHAL_SITE_IDS ?? "").split(/[\s,]+/).filter(Boolean);
|
|
314
|
+
if (attachedSite(env, siteId)) served.push(siteId);
|
|
315
|
+
if (served.length === 0)
|
|
316
|
+
return !env.CLOUDHAL_SITE_ID || env.CLOUDHAL_SITE_ID === siteId ? SITE_ORIGIN : undefined;
|
|
317
|
+
if (!served.includes(siteId)) return undefined;
|
|
318
|
+
const row = await new D1Driver(env.DB).get (
|
|
319
|
+
"SELECT host FROM site_hosts WHERE site_id = ? AND locale IS NULL ORDER BY primary_host DESC, host LIMIT 1",
|
|
320
|
+
[siteId],
|
|
321
|
+
);
|
|
322
|
+
return row ? `https://${row.host}` : undefined;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* Fetches the site's own `/rss.xml` or `/sitemap.xml` through the `SITE` binding, as readers get
|
|
327
|
+
* them (RFC-0008 §11.1 `feed-check`). For a site the site Worker does not serve the answer is
|
|
328
|
+
* undefined (not served from here).
|
|
329
|
+
*/
|
|
330
|
+
export function siteDocumentFetcher(
|
|
331
|
+
env ,
|
|
332
|
+
) {
|
|
333
|
+
if (!env.SITE && !env.CLOUDHAL_SITE_ROUTES) return undefined;
|
|
334
|
+
return async ({ siteId, path }) => {
|
|
335
|
+
const origin = await siteOrigin(env, siteId);
|
|
336
|
+
const site = bindingFor(env, siteId);
|
|
337
|
+
if (!origin || !site) return undefined;
|
|
338
|
+
const res = await site.fetch(`${origin}${path}`, {
|
|
339
|
+
headers: { accept: "application/rss+xml, application/xml;q=0.9, */*;q=0.1" },
|
|
340
|
+
});
|
|
341
|
+
const contentType = res.headers.get("content-type");
|
|
342
|
+
return {
|
|
343
|
+
status: res.status,
|
|
344
|
+
...(contentType ? { contentType } : {}),
|
|
345
|
+
body: await res.text(),
|
|
346
|
+
};
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** What the admin Worker adds for the built-in jobs: analytics' 404 rows and the feed fetcher. */
|
|
351
|
+
export function adminBuiltinInputs(
|
|
352
|
+
env ,
|
|
353
|
+
analytics ,
|
|
354
|
+
) {
|
|
355
|
+
const query = analytics?.query;
|
|
356
|
+
const fetchDocument = siteDocumentFetcher(env);
|
|
357
|
+
return {
|
|
358
|
+
...(analytics && query
|
|
359
|
+
? {
|
|
360
|
+
notFound: notFoundFromAnalytics({
|
|
361
|
+
feature: () => ({ enabled: analytics.feature().enabled === true }),
|
|
362
|
+
query: (q) => query.call(analytics, q),
|
|
363
|
+
}),
|
|
364
|
+
}
|
|
365
|
+
: {}),
|
|
366
|
+
...(fetchDocument ? { fetchDocument } : {}),
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// ───────────────────────────── one tick ─────────────────────────────
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
const sleep = (ms ) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
383
|
+
|
|
384
|
+
/** One tick of the admin Worker (cron, alarm, request backstop or the operator's run-due). */
|
|
385
|
+
export function runAdminTick(env , o ) {
|
|
386
|
+
const sql = new D1Driver(env.DB);
|
|
387
|
+
const mode = schedulerMode(env);
|
|
388
|
+
const flush = (siteId ) => {
|
|
389
|
+
const site = routedSite(env);
|
|
390
|
+
const token = env.CLOUDHAL_PURGE_TOKEN;
|
|
391
|
+
if (!o.waitUntil || !site || !token) return;
|
|
392
|
+
o.waitUntil(
|
|
393
|
+
sleep(PURGE_LIMITS.normalDelayMs + 500)
|
|
394
|
+
.then(() =>
|
|
395
|
+
flushCommentPurges({
|
|
396
|
+
store: new SqlCommentStore(sql),
|
|
397
|
+
fetch: (u, init) => site.fetch(u, init ) ,
|
|
398
|
+
token,
|
|
399
|
+
siteId,
|
|
400
|
+
log: o.log,
|
|
401
|
+
}),
|
|
402
|
+
)
|
|
403
|
+
.catch((e) =>
|
|
404
|
+
o.log(`schedules purge flush failed: ${e instanceof Error ? e.message : String(e)}`),
|
|
405
|
+
),
|
|
406
|
+
);
|
|
407
|
+
};
|
|
408
|
+
const blobs = new R2BlobStore(env.BLOBS);
|
|
409
|
+
return runScheduledTick({
|
|
410
|
+
sql,
|
|
411
|
+
blobs,
|
|
412
|
+
now: o.now,
|
|
413
|
+
trigger: o.trigger,
|
|
414
|
+
// cron wakes every minute anyway; the clock and the backstop compute the next wake
|
|
415
|
+
wake: mode === "cron" ? "minute" : "computed",
|
|
416
|
+
budget: tickBudget(env),
|
|
417
|
+
log: o.log,
|
|
418
|
+
systemJobs: ({ counted }) =>
|
|
419
|
+
adminSystemJobs(env, counted, {
|
|
420
|
+
analytics: o.analytics,
|
|
421
|
+
commentsOn: o.commentsOn,
|
|
422
|
+
log: o.log,
|
|
423
|
+
}),
|
|
424
|
+
purge: ({ counted }) => releasePurger(env, counted, { log: o.log, wake: flush }),
|
|
425
|
+
automationsEnabled: env.CLOUDHAL_AUTOMATIONS !== "off",
|
|
426
|
+
// RFC-0008 §11.1: the built-in jobs read analytics' 404 rows and the site's own feed.
|
|
427
|
+
builtinInputs: ({ counted }) => adminBuiltinInputs(env, o.analytics(counted, o.now)),
|
|
428
|
+
// RFC-0008 §10.6: the approver may still approve it, an auto release's key still holds.
|
|
429
|
+
checkApproval: releaseApprovalCheck({ sql, graph: new SiteGraphStore({ sql, blobs }) }),
|
|
430
|
+
// RFC-0029 §3: releases mirror into the AI Search bucket too.
|
|
431
|
+
graph: searchGraph(env, sql, o.log),
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* A cron tick's follow-up (RFC-0008 §8.2): Cloudflare fires `* * * * *` at a fixed second of each
|
|
437
|
+
* minute for a Worker (measured live: :54), so work due a few seconds after a tick would wait for
|
|
438
|
+
* the next one, almost a minute late. When something is due within the next minute, the handler
|
|
439
|
+
* waits until then (no CPU is used while waiting) and runs one more tick, so releases go live at
|
|
440
|
+
* their minute. Returns the wait in ms, or undefined when nothing is due before the next tick.
|
|
441
|
+
*/
|
|
442
|
+
export function followUpDelay(report , now ) {
|
|
443
|
+
const due = report?.nextDueAt ? Date.parse(report.nextDueAt) : Number.NaN;
|
|
444
|
+
if (!Number.isFinite(due) || due <= now || due - now >= 60_000) return undefined;
|
|
445
|
+
return due - now;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/** Isolate-local state of the request backstop: plain numbers only (ADR-0012). */
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
/** How often an isolate reads the heartbeat, and runs at most one backstop tick (§8.6). */
|
|
455
|
+
export const BACKSTOP_EVERY_MS = 60_000;
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* The request backstop (§8.6): at most once a minute per isolate, read the heartbeat; if it is
|
|
459
|
+
* more than two minutes behind, run a tick (`request`) — and in alarm mode re-arm the clock.
|
|
460
|
+
* Returns the promise for `waitUntil`, or undefined when nothing is to be done.
|
|
461
|
+
*/
|
|
462
|
+
export function requestBackstop(
|
|
463
|
+
env ,
|
|
464
|
+
state ,
|
|
465
|
+
o ,
|
|
466
|
+
) {
|
|
467
|
+
const clock = o.now ?? (() => Date.now());
|
|
468
|
+
const t = clock();
|
|
469
|
+
if (t - state.lastCheck < BACKSTOP_EVERY_MS) return undefined;
|
|
470
|
+
state.lastCheck = t;
|
|
471
|
+
return (async () => {
|
|
472
|
+
const heartbeat = await new SqlScheduleStore(new D1Driver(env.DB)).heartbeat();
|
|
473
|
+
if (!backstopDue(heartbeat, clock())) return;
|
|
474
|
+
if (clock() - state.lastRun < BACKSTOP_EVERY_MS) return;
|
|
475
|
+
state.lastRun = clock();
|
|
476
|
+
if (schedulerMode(env) === "alarm") await pokeClock(env, clock(), o.log);
|
|
477
|
+
o.log(
|
|
478
|
+
`schedules backstop: the scheduler's last tick was ${heartbeat ? heartbeat.at : "never"}; running one on this request`,
|
|
479
|
+
);
|
|
480
|
+
await runAdminTick(env, { ...o, trigger: "request", now: new Date(clock()) });
|
|
481
|
+
})().catch((e) =>
|
|
482
|
+
o.log(`schedules backstop failed: ${e instanceof Error ? e.message : String(e)}`),
|
|
483
|
+
);
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
// ───────────────────────────── the clock ─────────────────────────────
|
|
487
|
+
|
|
488
|
+
/**
|
|
489
|
+
* How the clock re-arms after a tick (§8.3): `now + 1 s` while there is more, else the next wake,
|
|
490
|
+
* at most an hour away (a safety alarm), never in the past.
|
|
491
|
+
*/
|
|
492
|
+
export function nextAlarm(report , now ) {
|
|
493
|
+
if (!report) return now + 60_000; // a failed tick: try again in a minute
|
|
494
|
+
if (report.more) return now + 1_000;
|
|
495
|
+
const wake = report.nextWakeAt ? Date.parse(report.nextWakeAt) : Number.NaN;
|
|
496
|
+
const next = Number.isFinite(wake) ? Math.min(wake, now + HOUR_MS) : now + HOUR_MS;
|
|
497
|
+
return Math.max(next, now + 1_000);
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/**
|
|
501
|
+
* Builds the `SchedulerClock` Durable Object class (SQLite-backed, one instance named "clock").
|
|
502
|
+
* `tick` runs one admin tick; the admin Worker module passes its own (migrations, analytics,
|
|
503
|
+
* comments). Kept as a factory so the class needs no `cloudflare:workers` import and its logic is
|
|
504
|
+
* testable on Node.
|
|
505
|
+
*/
|
|
506
|
+
export function schedulerClockClass(
|
|
507
|
+
tick
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
,
|
|
511
|
+
log = (l) => console.log(l),
|
|
512
|
+
) {
|
|
513
|
+
return class SchedulerClock {
|
|
514
|
+
state ;
|
|
515
|
+
env ;
|
|
516
|
+
|
|
517
|
+
constructor(state , env ) {
|
|
518
|
+
this.state = state;
|
|
519
|
+
this.env = env;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/** `POST /poke {at}` moves the alarm earlier (or arms it); `GET /alarm` reads it. */
|
|
523
|
+
async fetch(request ) {
|
|
524
|
+
const url = new URL(request.url);
|
|
525
|
+
if (request.method === "POST" && url.pathname === "/poke") {
|
|
526
|
+
const body = (await request.json().catch(() => ({}))) ;
|
|
527
|
+
const at = typeof body.at === "number" && Number.isFinite(body.at) ? body.at : Date.now();
|
|
528
|
+
return Response.json({ alarm: await this.poke(at) });
|
|
529
|
+
}
|
|
530
|
+
if (request.method === "GET" && url.pathname === "/alarm")
|
|
531
|
+
return Response.json({ alarm: await this.state.storage.getAlarm() });
|
|
532
|
+
return new Response("not found", { status: 404 });
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/** Moves the alarm to `at` when that is sooner than the armed one (never into the past). */
|
|
536
|
+
async poke(at ) {
|
|
537
|
+
const t = Math.max(at, Date.now());
|
|
538
|
+
const current = await this.state.storage.getAlarm();
|
|
539
|
+
if (current === null || t < current) {
|
|
540
|
+
await this.state.storage.setAlarm(t);
|
|
541
|
+
return t;
|
|
542
|
+
}
|
|
543
|
+
return current;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/** Runs a tick and always re-arms; never throws (a thrown alarm is retried only six times). */
|
|
547
|
+
async alarm() {
|
|
548
|
+
const started = Date.now();
|
|
549
|
+
let report ;
|
|
550
|
+
try {
|
|
551
|
+
report = await tick(this.env, {
|
|
552
|
+
now: new Date(started),
|
|
553
|
+
waitUntil: (p) => this.state.waitUntil(p),
|
|
554
|
+
});
|
|
555
|
+
} catch (e) {
|
|
556
|
+
log(`scheduler clock tick failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
557
|
+
}
|
|
558
|
+
try {
|
|
559
|
+
await this.state.storage.setAlarm(nextAlarm(report, Date.now()));
|
|
560
|
+
} catch (e) {
|
|
561
|
+
log(`scheduler clock could not re-arm: ${e instanceof Error ? e.message : String(e)}`);
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/** The tick's store options: the deployment's search provider, when it has one (RFC-0029 §3). */
|
|
568
|
+
function searchGraph(env , sql , log ) {
|
|
569
|
+
const search = searchProviderFromEnv(env, sql, {
|
|
570
|
+
onError: (e) => log(`semantic search failed: ${e instanceof Error ? e.message : String(e)}`),
|
|
571
|
+
});
|
|
572
|
+
return search ? { search } : {};
|
|
573
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RFC-0034 §4: which site Worker serves a site. The installation's own site Worker is the `SITE`
|
|
3
|
+
* service binding; Workers attached later (another theme) are bound as `SITE_1`, `SITE_2`, … and
|
|
4
|
+
* `CLOUDHAL_SITE_ROUTES` (JSON `{siteId: binding}`, written by `cloudhal deploy`) says which site
|
|
5
|
+
* each one serves. A site with no route goes to `SITE`.
|
|
6
|
+
*
|
|
7
|
+
* Every purge the admin Worker sends names its site in the JSON body, so `routedSite` can wrap
|
|
8
|
+
* the whole purge path: it reads the body's `siteId` and forwards to that site's Worker.
|
|
9
|
+
*/
|
|
10
|
+
/** The bindings and the route table on the admin Worker's env. */
|
|
11
|
+
export interface SiteRoutesEnv {
|
|
12
|
+
SITE?: Fetcher;
|
|
13
|
+
CLOUDHAL_SITE_ROUTES?: string;
|
|
14
|
+
}
|
|
15
|
+
/** The Worker that serves `siteId`: its own binding when one is routed, else `SITE`. */
|
|
16
|
+
export declare function bindingFor(env: SiteRoutesEnv, siteId: string | undefined): Fetcher | undefined;
|
|
17
|
+
/** True when `siteId` is served by an attached Worker (not the installation's own). */
|
|
18
|
+
export declare function attachedSite(env: SiteRoutesEnv, siteId: string): boolean;
|
|
19
|
+
/**
|
|
20
|
+
* A `Fetcher` for purges: each request goes to the Worker of the `siteId` in its JSON body (`SITE`
|
|
21
|
+
* without one). Undefined when the admin Worker has no site Worker at all.
|
|
22
|
+
*/
|
|
23
|
+
export declare function routedSite(env: SiteRoutesEnv): Fetcher | undefined;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RFC-0034 §4: which site Worker serves a site. The installation's own site Worker is the `SITE`
|
|
3
|
+
* service binding; Workers attached later (another theme) are bound as `SITE_1`, `SITE_2`, … and
|
|
4
|
+
* `CLOUDHAL_SITE_ROUTES` (JSON `{siteId: binding}`, written by `cloudhal deploy`) says which site
|
|
5
|
+
* each one serves. A site with no route goes to `SITE`.
|
|
6
|
+
*
|
|
7
|
+
* Every purge the admin Worker sends names its site in the JSON body, so `routedSite` can wrap
|
|
8
|
+
* the whole purge path: it reads the body's `siteId` and forwards to that site's Worker.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** The bindings and the route table on the admin Worker's env. */
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
function routesOf(env ) {
|
|
18
|
+
try {
|
|
19
|
+
const parsed = JSON.parse(env.CLOUDHAL_SITE_ROUTES ?? "{}") ;
|
|
20
|
+
return parsed && typeof parsed === "object" ? (parsed ) : {};
|
|
21
|
+
} catch {
|
|
22
|
+
return {};
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const isFetcher = (v ) =>
|
|
27
|
+
typeof v === "object" && v !== null && typeof (v ).fetch === "function";
|
|
28
|
+
|
|
29
|
+
/** The Worker that serves `siteId`: its own binding when one is routed, else `SITE`. */
|
|
30
|
+
export function bindingFor(env , siteId ) {
|
|
31
|
+
const name = siteId ? routesOf(env)[siteId] : undefined;
|
|
32
|
+
const bound = name ? (env )[name] : undefined;
|
|
33
|
+
return isFetcher(bound) ? bound : env.SITE;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** True when `siteId` is served by an attached Worker (not the installation's own). */
|
|
37
|
+
export function attachedSite(env , siteId ) {
|
|
38
|
+
return routesOf(env)[siteId] !== undefined;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* A `Fetcher` for purges: each request goes to the Worker of the `siteId` in its JSON body (`SITE`
|
|
43
|
+
* without one). Undefined when the admin Worker has no site Worker at all.
|
|
44
|
+
*/
|
|
45
|
+
export function routedSite(env ) {
|
|
46
|
+
if (!env.SITE && Object.keys(routesOf(env)).length === 0) return undefined;
|
|
47
|
+
const fetch = async (input , init ) => {
|
|
48
|
+
let siteId ;
|
|
49
|
+
if (typeof init?.body === "string")
|
|
50
|
+
try {
|
|
51
|
+
const id = (JSON.parse(init.body) ).siteId;
|
|
52
|
+
siteId = typeof id === "string" ? id : undefined;
|
|
53
|
+
} catch {
|
|
54
|
+
// not JSON: the installation's own Worker
|
|
55
|
+
}
|
|
56
|
+
const target = bindingFor(env, siteId);
|
|
57
|
+
if (!target) return new Response("no site Worker for this site", { status: 503 });
|
|
58
|
+
return target.fetch(input , init ) ;
|
|
59
|
+
};
|
|
60
|
+
return { fetch } ;
|
|
61
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Import this module FIRST in a Worker entry (the generated `worker.ts` does).
|
|
3
|
+
*
|
|
4
|
+
* esbuild (wrangler's bundler) wraps zod in a lazy initializer because Better Auth reaches it
|
|
5
|
+
* through dynamic `import()`s, yet it does not call that initializer before modules that import
|
|
6
|
+
* zod statically — and `@modelcontextprotocol/core` builds zod schemas at module top level. The
|
|
7
|
+
* Worker then fails at startup with "ZodLazy is not a constructor". Awaiting a dynamic import here
|
|
8
|
+
* forces the initializer to run before any later module in the bundle evaluates.
|
|
9
|
+
* Remove once the bundler orders wrapped modules correctly (ADR-0012).
|
|
10
|
+
*/
|
|
11
|
+
const z = await import("zod/v4");
|
|
12
|
+
|
|
13
|
+
// A real side effect, so the bundler keeps this module (zod declares `sideEffects: false`).
|
|
14
|
+
(globalThis ).__cloudhalZodReady =
|
|
15
|
+
typeof z.lazy(() => z.string()).parse === "function";
|
|
16
|
+
|
|
17
|
+
export {};
|