@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,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `render_page` on Workers (RFC-0021 §4): Cloudflare Browser Rendering through the admin Worker's
|
|
3
|
+
* `BROWSER` binding. One browser per call: acquired, driven over its DevTools socket and closed.
|
|
4
|
+
* The binding's socket carries messages in chunks (Workers caps a WebSocket message at 1 MiB and
|
|
5
|
+
* screenshots are larger): a 4-byte little-endian length, then the UTF-8 message, in pieces.
|
|
6
|
+
*/
|
|
7
|
+
import {
|
|
8
|
+
|
|
9
|
+
cdpSession,
|
|
10
|
+
|
|
11
|
+
RenderError,
|
|
12
|
+
} from "@cloudhal/mcp-server/render";
|
|
13
|
+
|
|
14
|
+
/** The Browser Rendering binding (`browser = { binding = "BROWSER" }`). */
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
const HOST = "https://fake.host";
|
|
20
|
+
const HEADER = 4;
|
|
21
|
+
const MAX_MESSAGE = 1_048_575;
|
|
22
|
+
|
|
23
|
+
/** Splits one DevTools message into the binding's chunks. */
|
|
24
|
+
export function messageToChunks(message ) {
|
|
25
|
+
const data = new TextEncoder().encode(message);
|
|
26
|
+
const first = new Uint8Array(Math.min(MAX_MESSAGE, HEADER + data.length));
|
|
27
|
+
new DataView(first.buffer).setUint32(0, data.length, true);
|
|
28
|
+
first.set(data.subarray(0, MAX_MESSAGE - HEADER), HEADER);
|
|
29
|
+
const chunks = [first];
|
|
30
|
+
for (let i = MAX_MESSAGE - HEADER; i < data.length; i += MAX_MESSAGE)
|
|
31
|
+
chunks.push(data.subarray(i, i + MAX_MESSAGE));
|
|
32
|
+
return chunks;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Collects chunks until a whole message has arrived; returns it and drops its chunks. */
|
|
36
|
+
export function chunksToMessage(chunks ) {
|
|
37
|
+
const first = chunks[0];
|
|
38
|
+
if (!first || first.length < HEADER) return undefined;
|
|
39
|
+
const expected = new DataView(first.buffer, first.byteOffset, first.byteLength).getUint32(
|
|
40
|
+
0,
|
|
41
|
+
true,
|
|
42
|
+
);
|
|
43
|
+
let total = -HEADER;
|
|
44
|
+
for (let i = 0; i < chunks.length; i++) {
|
|
45
|
+
total += (chunks[i] ).length;
|
|
46
|
+
if (total > expected) throw new RenderError("Browser Rendering sent a malformed message");
|
|
47
|
+
if (total === expected) {
|
|
48
|
+
const parts = chunks.splice(0, i + 1);
|
|
49
|
+
parts[0] = first.subarray(HEADER);
|
|
50
|
+
const out = new Uint8Array(expected);
|
|
51
|
+
let offset = 0;
|
|
52
|
+
for (const p of parts) {
|
|
53
|
+
out.set(p, offset);
|
|
54
|
+
offset += p.length;
|
|
55
|
+
}
|
|
56
|
+
return new TextDecoder().decode(out);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The binding's DevTools socket as a `CdpSocket` (exported for tests). */
|
|
63
|
+
export function bindingSocket(ws ) {
|
|
64
|
+
const chunks = [];
|
|
65
|
+
const messageListeners = [];
|
|
66
|
+
// Browser Rendering closes a socket that stays quiet; keep it talking while we work.
|
|
67
|
+
const ping = setInterval(() => {
|
|
68
|
+
try {
|
|
69
|
+
ws.send("ping");
|
|
70
|
+
} catch {
|
|
71
|
+
clearInterval(ping);
|
|
72
|
+
}
|
|
73
|
+
}, 1000);
|
|
74
|
+
// Recent compatibility dates deliver binary messages as Blobs (the web default); ask for
|
|
75
|
+
// ArrayBuffers, and keep any Blob in order while it is read.
|
|
76
|
+
(ws ).binaryType = "arraybuffer";
|
|
77
|
+
let queue = Promise.resolve();
|
|
78
|
+
const take = (bytes ) => {
|
|
79
|
+
chunks.push(bytes);
|
|
80
|
+
for (let m = chunksToMessage(chunks); m !== undefined; m = chunksToMessage(chunks))
|
|
81
|
+
for (const l of messageListeners) l(m);
|
|
82
|
+
};
|
|
83
|
+
ws.addEventListener("message", (event) => {
|
|
84
|
+
const data = event.data ;
|
|
85
|
+
queue = queue.then(async () => {
|
|
86
|
+
if (typeof data === "string") for (const l of messageListeners) l(data);
|
|
87
|
+
else take(new Uint8Array(data instanceof Blob ? await data.arrayBuffer() : data));
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
ws.addEventListener("close", () => clearInterval(ping));
|
|
91
|
+
return {
|
|
92
|
+
send: (m) => {
|
|
93
|
+
for (const c of messageToChunks(m)) ws.send(c);
|
|
94
|
+
},
|
|
95
|
+
onMessage: (l) => {
|
|
96
|
+
messageListeners.push(l);
|
|
97
|
+
},
|
|
98
|
+
onClose: (l) => ws.addEventListener("close", () => l()),
|
|
99
|
+
close: () => {
|
|
100
|
+
clearInterval(ping);
|
|
101
|
+
ws.close();
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function browserRenderingRenderer(binding ) {
|
|
107
|
+
return {
|
|
108
|
+
async session() {
|
|
109
|
+
const acquired = await binding.fetch(`${HOST}/v1/acquire?keep_alive=60000`);
|
|
110
|
+
if (acquired.status !== 200)
|
|
111
|
+
throw new RenderError(
|
|
112
|
+
`Browser Rendering refused a browser (${acquired.status}): ${(await acquired.text()).slice(0, 200)}`,
|
|
113
|
+
);
|
|
114
|
+
const { sessionId } = (await acquired.json()) ;
|
|
115
|
+
if (!sessionId) throw new RenderError("Browser Rendering gave no session");
|
|
116
|
+
const upgraded = await binding.fetch(
|
|
117
|
+
`${HOST}/v1/connectDevtools?browser_session=${encodeURIComponent(sessionId)}`,
|
|
118
|
+
{ headers: { Upgrade: "websocket" } },
|
|
119
|
+
);
|
|
120
|
+
const ws = (upgraded ).webSocket;
|
|
121
|
+
if (!ws)
|
|
122
|
+
throw new RenderError(`Browser Rendering did not open a socket (${upgraded.status})`);
|
|
123
|
+
(ws ).accept();
|
|
124
|
+
return cdpSession(bindingSocket(ws), { closeBrowser: true });
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Build rooms (RFC-0020 §6, phase 20b part 2): one Durable Object per page carries build events
|
|
3
|
+
* between the admin Worker's isolates. A write on any isolate posts its change to the page's room
|
|
4
|
+
* (`POST /publish`); each Build view stream holds a hibernatable WebSocket to it
|
|
5
|
+
* (`/subscribe`), so an idle room costs nothing while Studio watches. The room keeps no state of
|
|
6
|
+
* its own: changes pass through, viewers are its WebSockets.
|
|
7
|
+
*
|
|
8
|
+
* `createDurableBuildHub` is `@cloudhal/api`'s `BuildHub` over those rooms, so the API's
|
|
9
|
+
* server-sent events route stays the same on Node and on Cloudflare.
|
|
10
|
+
*/
|
|
11
|
+
import { type BuildHub } from "@cloudhal/api";
|
|
12
|
+
export interface BuildRoomsEnv {
|
|
13
|
+
/** One room per page, `idFromName(pageId)`; declared by every deploy (SQLite-backed). */
|
|
14
|
+
BUILD_ROOMS?: DurableObjectNamespace;
|
|
15
|
+
}
|
|
16
|
+
/** What the room needs from the runtime; workerd's globals by default, fakes in tests. */
|
|
17
|
+
export interface BuildRoomRuntime {
|
|
18
|
+
pair(): [WebSocket, WebSocket];
|
|
19
|
+
/** The 101 answer handing the client end to the caller (Node's `Response` cannot say 101). */
|
|
20
|
+
upgrade(client: WebSocket): Response;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Builds the `BuildRoom` Durable Object class. A factory, like `schedulerClockClass`, so it needs
|
|
24
|
+
* no `cloudflare:workers` import and its logic runs on Node with a fake state.
|
|
25
|
+
*/
|
|
26
|
+
export declare function buildRoomClass(runtime?: BuildRoomRuntime): {
|
|
27
|
+
new (state: DurableObjectState, _env: unknown): {
|
|
28
|
+
readonly state: DurableObjectState;
|
|
29
|
+
fetch(request: Request): Promise<Response>;
|
|
30
|
+
/** Viewers only listen; anything they send is ignored. */
|
|
31
|
+
webSocketMessage(): void;
|
|
32
|
+
webSocketClose(ws: WebSocket, code: number): void;
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
/** `BuildHub` over the rooms: publish posts to the page's room, subscribe opens a WebSocket. */
|
|
36
|
+
export declare function createDurableBuildHub(rooms: DurableObjectNamespace, now?: () => Date): BuildHub;
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Build rooms (RFC-0020 §6, phase 20b part 2): one Durable Object per page carries build events
|
|
3
|
+
* between the admin Worker's isolates. A write on any isolate posts its change to the page's room
|
|
4
|
+
* (`POST /publish`); each Build view stream holds a hibernatable WebSocket to it
|
|
5
|
+
* (`/subscribe`), so an idle room costs nothing while Studio watches. The room keeps no state of
|
|
6
|
+
* its own: changes pass through, viewers are its WebSockets.
|
|
7
|
+
*
|
|
8
|
+
* `createDurableBuildHub` is `@cloudhal/api`'s `BuildHub` over those rooms, so the API's
|
|
9
|
+
* server-sent events route stays the same on Node and on Cloudflare.
|
|
10
|
+
*/
|
|
11
|
+
import {
|
|
12
|
+
BUILD_VIEWER_LIMIT,
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
BuildViewerLimitError,
|
|
16
|
+
buildChange,
|
|
17
|
+
} from "@cloudhal/api";
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
/** The room's origin in requests from the Worker (a Durable Object ignores the host). */
|
|
25
|
+
const ROOM = "https://build-room";
|
|
26
|
+
|
|
27
|
+
/** What the room needs from the runtime; workerd's globals by default, fakes in tests. */
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
const workerdRuntime = {
|
|
35
|
+
pair: () => {
|
|
36
|
+
const p = new WebSocketPair();
|
|
37
|
+
return [p[0], p[1]];
|
|
38
|
+
},
|
|
39
|
+
upgrade: (client) => new Response(null, { status: 101, webSocket: client }),
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Builds the `BuildRoom` Durable Object class. A factory, like `schedulerClockClass`, so it needs
|
|
44
|
+
* no `cloudflare:workers` import and its logic runs on Node with a fake state.
|
|
45
|
+
*/
|
|
46
|
+
export function buildRoomClass(runtime = workerdRuntime) {
|
|
47
|
+
return class BuildRoom {
|
|
48
|
+
state ;
|
|
49
|
+
|
|
50
|
+
constructor(state , _env ) {
|
|
51
|
+
this.state = state;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async fetch(request ) {
|
|
55
|
+
const { pathname } = new URL(request.url);
|
|
56
|
+
if (request.method === "POST" && pathname === "/publish") {
|
|
57
|
+
const text = await request.text();
|
|
58
|
+
for (const ws of this.state.getWebSockets()) {
|
|
59
|
+
try {
|
|
60
|
+
ws.send(text);
|
|
61
|
+
} catch {
|
|
62
|
+
// A socket closing as we send: the runtime drops it from the room.
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return new Response(null, { status: 204 });
|
|
66
|
+
}
|
|
67
|
+
if (pathname === "/subscribe") {
|
|
68
|
+
if (request.headers.get("upgrade")?.toLowerCase() !== "websocket")
|
|
69
|
+
return new Response("expected a WebSocket upgrade", { status: 426 });
|
|
70
|
+
if (this.state.getWebSockets().length >= BUILD_VIEWER_LIMIT)
|
|
71
|
+
return new Response("too many viewers", { status: 429 });
|
|
72
|
+
const [client, server] = runtime.pair();
|
|
73
|
+
// Hibernatable: the room may sleep between changes without dropping its viewers.
|
|
74
|
+
this.state.acceptWebSocket(server);
|
|
75
|
+
return runtime.upgrade(client);
|
|
76
|
+
}
|
|
77
|
+
return new Response("not found", { status: 404 });
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Viewers only listen; anything they send is ignored. */
|
|
81
|
+
webSocketMessage() {}
|
|
82
|
+
|
|
83
|
+
webSocketClose(ws , code ) {
|
|
84
|
+
try {
|
|
85
|
+
ws.close(code === 1005 ? 1000 : code);
|
|
86
|
+
} catch {
|
|
87
|
+
// Already closed.
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** `BuildHub` over the rooms: publish posts to the page's room, subscribe opens a WebSocket. */
|
|
94
|
+
export function createDurableBuildHub(
|
|
95
|
+
rooms ,
|
|
96
|
+
now = () => new Date(),
|
|
97
|
+
) {
|
|
98
|
+
const room = (pageId ) => rooms.get(rooms.idFromName(pageId));
|
|
99
|
+
const publish = async (pageId , change ) => {
|
|
100
|
+
const res = await room(pageId).fetch(`${ROOM}/publish`, {
|
|
101
|
+
method: "POST",
|
|
102
|
+
body: JSON.stringify(change),
|
|
103
|
+
});
|
|
104
|
+
if (!res.ok && res.status !== 204) throw new Error(`build room answered ${res.status}`);
|
|
105
|
+
};
|
|
106
|
+
return {
|
|
107
|
+
pageChanged: (change) =>
|
|
108
|
+
publish(change.page.id, buildChange({ kind: "changed", ...change }, now())),
|
|
109
|
+
patchRejected: (rejection) =>
|
|
110
|
+
publish(rejection.pageId, buildChange({ kind: "rejected", ...rejection }, now())),
|
|
111
|
+
async subscribe(pageId, listener) {
|
|
112
|
+
const res = await room(pageId).fetch(`${ROOM}/subscribe`, {
|
|
113
|
+
headers: { upgrade: "websocket" },
|
|
114
|
+
});
|
|
115
|
+
if (res.status === 429) throw new BuildViewerLimitError();
|
|
116
|
+
const ws = res.webSocket;
|
|
117
|
+
if (!ws) throw new Error(`build room did not open a WebSocket (${res.status})`);
|
|
118
|
+
ws.accept();
|
|
119
|
+
ws.addEventListener("message", (event) => {
|
|
120
|
+
try {
|
|
121
|
+
listener(JSON.parse(String(event.data)) );
|
|
122
|
+
} catch {
|
|
123
|
+
// A malformed message is skipped; the viewer's next snapshot puts it right.
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
return () => {
|
|
127
|
+
try {
|
|
128
|
+
ws.close(1000, "viewer left");
|
|
129
|
+
} catch {
|
|
130
|
+
// Already closed.
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reader comments on the admin Worker (RFC-0007 rollout step 5):
|
|
3
|
+
*
|
|
4
|
+
* - **The purge flusher** (§8.4, invariant C6). Moderation never purges directly: the store queues
|
|
5
|
+
* `cloudhal-comments-<nodeId>` in the same batch as the change, and `flushCommentPurges` sends
|
|
6
|
+
* what `planPurge` allows through the `SITE` binding to `/__cloudhal/purge` — takedowns at once
|
|
7
|
+
* (after a 2 s micro-batch), normal tags once 20 s old and only while the last minute shows fewer
|
|
8
|
+
* than 3 purge requests in total. The budget is shared: publishes, media takedowns and analytics
|
|
9
|
+
* settings log their requests in `cache_purge_log` too. A failed request (`success: false` is a
|
|
10
|
+
* 502 from the site Worker) keeps the rows and backs off 30 s × 2^attempts, at most 5 minutes.
|
|
11
|
+
* - **The hourly job** (§8.5, §9.2, §9.3): retention per site in bounded runs, comments of
|
|
12
|
+
* entries deleted 30 days ago, purges for threads that closed by time in the last hour, salts
|
|
13
|
+
* older than the previous month, then a flush as the backstop. Since RFC-0008 it is the
|
|
14
|
+
* `comments.hourly` system job of the minute tick (`scheduler.ts`), behind a watermark.
|
|
15
|
+
* - **`adminComments`**: the deployment's `CommentsDeps` from its secrets. Without a valid
|
|
16
|
+
* `CLOUDHAL_COMMENTS_KEY` (the same secret the site Worker uses) comments are unavailable, never
|
|
17
|
+
* a crash; `CLOUDHAL_COMMENTS_AVAILABLE=false` turns them off for the deployment.
|
|
18
|
+
*/
|
|
19
|
+
import type { ApiDeps } from "@cloudhal/api";
|
|
20
|
+
import { type PurgePriority } from "@cloudhal/comments";
|
|
21
|
+
import { SqlCommentStore } from "@cloudhal/comments/sql";
|
|
22
|
+
import type { SiteGraphStore } from "@cloudhal/core-ts";
|
|
23
|
+
import type { SqlDriver } from "@cloudhal/storage";
|
|
24
|
+
import type { SiteFetch } from "./purge.js";
|
|
25
|
+
type CommentsDeps = NonNullable<ApiDeps["comments"]>;
|
|
26
|
+
export interface FlushOptions {
|
|
27
|
+
readonly store: SqlCommentStore;
|
|
28
|
+
/** `fetch` of the site Worker (the `SITE` binding). */
|
|
29
|
+
readonly fetch: SiteFetch;
|
|
30
|
+
/** The shared `CLOUDHAL_PURGE_TOKEN`. */
|
|
31
|
+
readonly token: string;
|
|
32
|
+
readonly now?: (() => Date) | undefined;
|
|
33
|
+
/** Only this site's queue (default: every site with queued tags). */
|
|
34
|
+
readonly siteId?: string | undefined;
|
|
35
|
+
readonly log?: ((line: string) => void) | undefined;
|
|
36
|
+
}
|
|
37
|
+
export interface FlushReport {
|
|
38
|
+
/** Requests sent, with their tags. */
|
|
39
|
+
readonly sent: readonly {
|
|
40
|
+
siteId: string;
|
|
41
|
+
priority: PurgePriority;
|
|
42
|
+
tags: readonly string[];
|
|
43
|
+
}[];
|
|
44
|
+
/** Requests that failed (rows backed off). */
|
|
45
|
+
readonly failed: number;
|
|
46
|
+
/** A takedown has waited longer than 2 minutes (the bell's `comments-purge-waiting`). */
|
|
47
|
+
readonly takedownWaiting: boolean;
|
|
48
|
+
/** When the queue should be looked at again (`null`: empty). */
|
|
49
|
+
readonly nextCheckAt: string | null;
|
|
50
|
+
}
|
|
51
|
+
/** Plans and sends one flush of the comment purge queue (§8.4). */
|
|
52
|
+
export declare function flushCommentPurges(o: FlushOptions): Promise<FlushReport>;
|
|
53
|
+
export interface HourlyReport {
|
|
54
|
+
readonly sites: number;
|
|
55
|
+
/** Rows deleted or cleared by retention, across sites. */
|
|
56
|
+
readonly retained: number;
|
|
57
|
+
/** Comments and reports of entries deleted ≥ 30 days ago. */
|
|
58
|
+
readonly deletedEntries: number;
|
|
59
|
+
/** Comment tags queued because a thread closed by time in the last hour. */
|
|
60
|
+
readonly closed: number;
|
|
61
|
+
readonly salts: number;
|
|
62
|
+
readonly purgeLog: number;
|
|
63
|
+
/** A retention run hit its row budget; the next run continues. */
|
|
64
|
+
readonly more: boolean;
|
|
65
|
+
}
|
|
66
|
+
/** The hourly comments job (§8.5, §9.3): bounded work per site; a missed run is caught up later. */
|
|
67
|
+
export declare function runCommentsHourly(o: {
|
|
68
|
+
readonly graph: SiteGraphStore;
|
|
69
|
+
readonly store: SqlCommentStore;
|
|
70
|
+
readonly now: Date;
|
|
71
|
+
}): Promise<HourlyReport>;
|
|
72
|
+
/** The comment secrets and switches of a deployment (both Workers read the same key). */
|
|
73
|
+
export interface CommentsEnv {
|
|
74
|
+
CLOUDHAL_COMMENTS_KEY?: string;
|
|
75
|
+
/** `false` turns comments off for the deployment (`cloudhal.json` `comments.available`). */
|
|
76
|
+
CLOUDHAL_COMMENTS_AVAILABLE?: string;
|
|
77
|
+
/**
|
|
78
|
+
* Legacy (before RFC-0008): `off` meant the deploy went without the hourly cron trigger. It now
|
|
79
|
+
* reads as `CLOUDHAL_SCHEDULER=alarm` (`scheduler.ts`) until the next deploy removes it.
|
|
80
|
+
*/
|
|
81
|
+
CLOUDHAL_COMMENTS_CRON?: string;
|
|
82
|
+
}
|
|
83
|
+
/** True when the deployment serves comments: a valid key and not switched off. */
|
|
84
|
+
export declare function commentsOn(env: CommentsEnv): boolean;
|
|
85
|
+
/**
|
|
86
|
+
* The admin Worker's `CommentsDeps`, or `undefined` when comments are unavailable. `wake` is
|
|
87
|
+
* called after a write queued purge rows (the Worker flushes in `waitUntil`); `purgeSite` purges
|
|
88
|
+
* the whole site cache (the last resort).
|
|
89
|
+
*/
|
|
90
|
+
export declare function adminComments(env: CommentsEnv, sql: SqlDriver, o?: {
|
|
91
|
+
readonly wake?: ((siteId: string, priority: PurgePriority) => void) | undefined;
|
|
92
|
+
readonly purgeSite?: ((siteId: string) => Promise<void>) | undefined;
|
|
93
|
+
}): Promise<CommentsDeps | undefined>;
|
|
94
|
+
export {};
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reader comments on the admin Worker (RFC-0007 rollout step 5):
|
|
3
|
+
*
|
|
4
|
+
* - **The purge flusher** (§8.4, invariant C6). Moderation never purges directly: the store queues
|
|
5
|
+
* `cloudhal-comments-<nodeId>` in the same batch as the change, and `flushCommentPurges` sends
|
|
6
|
+
* what `planPurge` allows through the `SITE` binding to `/__cloudhal/purge` — takedowns at once
|
|
7
|
+
* (after a 2 s micro-batch), normal tags once 20 s old and only while the last minute shows fewer
|
|
8
|
+
* than 3 purge requests in total. The budget is shared: publishes, media takedowns and analytics
|
|
9
|
+
* settings log their requests in `cache_purge_log` too. A failed request (`success: false` is a
|
|
10
|
+
* 502 from the site Worker) keeps the rows and backs off 30 s × 2^attempts, at most 5 minutes.
|
|
11
|
+
* - **The hourly job** (§8.5, §9.2, §9.3): retention per site in bounded runs, comments of
|
|
12
|
+
* entries deleted 30 days ago, purges for threads that closed by time in the last hour, salts
|
|
13
|
+
* older than the previous month, then a flush as the backstop. Since RFC-0008 it is the
|
|
14
|
+
* `comments.hourly` system job of the minute tick (`scheduler.ts`), behind a watermark.
|
|
15
|
+
* - **`adminComments`**: the deployment's `CommentsDeps` from its secrets. Without a valid
|
|
16
|
+
* `CLOUDHAL_COMMENTS_KEY` (the same secret the site Worker uses) comments are unavailable, never
|
|
17
|
+
* a crash; `CLOUDHAL_COMMENTS_AVAILABLE=false` turns them off for the deployment.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
import {
|
|
22
|
+
closeAfterDaysFor,
|
|
23
|
+
collectionEnabled,
|
|
24
|
+
deletedEntriesDue,
|
|
25
|
+
deriveCommentKeys,
|
|
26
|
+
MIN_SECRET_LENGTH,
|
|
27
|
+
oldestSaltMonthToKeep,
|
|
28
|
+
PURGE_LIMITS,
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
planPurge,
|
|
32
|
+
retentionPlan,
|
|
33
|
+
threadClosesAt,
|
|
34
|
+
} from "@cloudhal/comments";
|
|
35
|
+
import { SqlCommentStore } from "@cloudhal/comments/sql";
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
const PURGE_URL = "https://site.internal/__cloudhal/purge";
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
/** Plans and sends one flush of the comment purge queue (§8.4). */
|
|
68
|
+
export async function flushCommentPurges(o ) {
|
|
69
|
+
const clock = o.now ?? (() => new Date());
|
|
70
|
+
const log = o.log ?? (() => {});
|
|
71
|
+
const sent = [];
|
|
72
|
+
let failed = 0;
|
|
73
|
+
let takedownWaiting = false;
|
|
74
|
+
let next ;
|
|
75
|
+
const sites = o.siteId ? [o.siteId] : await o.store.purgeQueue.sites();
|
|
76
|
+
for (const siteId of sites) {
|
|
77
|
+
const rows = await o.store.purgeQueue.queued(siteId);
|
|
78
|
+
if (rows.length === 0) continue;
|
|
79
|
+
const now = clock();
|
|
80
|
+
const plan = planPurge({ rows, recent: await o.store.purgeQueue.recent(now), now });
|
|
81
|
+
takedownWaiting ||= plan.takedownWaiting;
|
|
82
|
+
if (plan.nextCheckAt) next = Math.min(next ?? Infinity, Date.parse(plan.nextCheckAt));
|
|
83
|
+
for (const request of plan.requests) {
|
|
84
|
+
const at = clock();
|
|
85
|
+
let ok = false;
|
|
86
|
+
let status = "error";
|
|
87
|
+
try {
|
|
88
|
+
const res = await o.fetch(PURGE_URL, {
|
|
89
|
+
method: "POST",
|
|
90
|
+
headers: { authorization: `Bearer ${o.token}`, "content-type": "application/json" },
|
|
91
|
+
body: JSON.stringify({ tags: request.tags, siteId }),
|
|
92
|
+
});
|
|
93
|
+
status = String(res.status);
|
|
94
|
+
// the site Worker answers 502 when Cloudflare said `success: false` (bucket empty)
|
|
95
|
+
ok = res.ok;
|
|
96
|
+
await res.body?.cancel();
|
|
97
|
+
} catch (e) {
|
|
98
|
+
status = e instanceof Error ? e.message : String(e);
|
|
99
|
+
}
|
|
100
|
+
if (ok) {
|
|
101
|
+
await o.store.purgeQueue.sent(siteId, request.tags, at);
|
|
102
|
+
sent.push({ siteId, priority: request.priority, tags: request.tags });
|
|
103
|
+
log(
|
|
104
|
+
`comments purge ${siteId}: ${request.priority}, ${request.tags.length} tag(s): ${status}`,
|
|
105
|
+
);
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
const tags = new Set(request.tags);
|
|
109
|
+
const back = rows.filter((r) => tags.has(r.tag));
|
|
110
|
+
await o.store.purgeQueue.failed(siteId, back, at);
|
|
111
|
+
failed++;
|
|
112
|
+
log(`comments purge ${siteId} failed (${status}); ${back.length} tag(s) back off`);
|
|
113
|
+
// an empty bucket stays empty for a while: stop here, the next flush retries
|
|
114
|
+
return {
|
|
115
|
+
sent,
|
|
116
|
+
failed,
|
|
117
|
+
takedownWaiting,
|
|
118
|
+
nextCheckAt: new Date(at.getTime() + PURGE_LIMITS.backoffBaseMs).toISOString(),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return {
|
|
123
|
+
sent,
|
|
124
|
+
failed,
|
|
125
|
+
takedownWaiting,
|
|
126
|
+
nextCheckAt: next === undefined ? null : new Date(next).toISOString(),
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
/** How far back "closed in the last hour" looks: an hour and a bit, duplicates coalesce. */
|
|
145
|
+
const CLOSING_WINDOW_MS = 65 * 60_000;
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* When missing entries were deleted, from the site's snapshots (the graph keeps no deletion time):
|
|
149
|
+
* the first snapshot after the newest one that still had the entry; when none of the recent
|
|
150
|
+
* snapshots has it, the oldest of them (a later time than the real one, so never too early).
|
|
151
|
+
*/
|
|
152
|
+
async function deletionTimes(
|
|
153
|
+
graph ,
|
|
154
|
+
siteId ,
|
|
155
|
+
missing ,
|
|
156
|
+
now ,
|
|
157
|
+
) {
|
|
158
|
+
const snaps = await graph.listSnapshots(siteId, 200); // newest first
|
|
159
|
+
if (snaps.length === 0) return [];
|
|
160
|
+
return missing.map((nodeId) => {
|
|
161
|
+
const i = snaps.findIndex((s) => s.nodes.some((n) => n.id === nodeId));
|
|
162
|
+
const deletedAt =
|
|
163
|
+
i < 0
|
|
164
|
+
? (snaps.at(-1)?.createdAt ?? now.toISOString())
|
|
165
|
+
: i === 0
|
|
166
|
+
? now.toISOString()
|
|
167
|
+
: (snaps[i - 1]?.createdAt ?? now.toISOString());
|
|
168
|
+
return { nodeId, deletedAt };
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** The hourly comments job (§8.5, §9.3): bounded work per site; a missed run is caught up later. */
|
|
173
|
+
export async function runCommentsHourly(o
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
) {
|
|
178
|
+
const { graph, store, now } = o;
|
|
179
|
+
let retained = 0;
|
|
180
|
+
let deletedEntries = 0;
|
|
181
|
+
let closed = 0;
|
|
182
|
+
let more = false;
|
|
183
|
+
const sites = await graph.listSites();
|
|
184
|
+
for (const site of sites) {
|
|
185
|
+
const settings = await store.settings(site.id);
|
|
186
|
+
const run = await store.retention.run(site.id, retentionPlan(settings.retention, now));
|
|
187
|
+
retained += Object.values(run.counts).reduce((a, b) => a + (b ?? 0), 0);
|
|
188
|
+
more ||= run.more;
|
|
189
|
+
|
|
190
|
+
const commented = await store.nodeIds(site.id);
|
|
191
|
+
const entries = await graph.listContentEntries(site.id);
|
|
192
|
+
if (commented.length > 0) {
|
|
193
|
+
const live = new Set(entries.map((e) => e.id));
|
|
194
|
+
const missing = commented.filter((id) => !live.has(id));
|
|
195
|
+
if (missing.length > 0) {
|
|
196
|
+
const due = deletedEntriesDue(await deletionTimes(graph, site.id, missing, now), now);
|
|
197
|
+
if (due.length > 0) deletedEntries += await store.retention.deleteEntries(site.id, due);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// Threads that closed by time in the last hour: the cached page still shows the form.
|
|
202
|
+
if (settings.enabled) {
|
|
203
|
+
const threads = new Map((await store.threads(site.id)).map((t) => [t.nodeId, t]));
|
|
204
|
+
const tags = [];
|
|
205
|
+
for (const e of entries) {
|
|
206
|
+
if (e.status !== "published" || !collectionEnabled(settings, e.collection)) continue;
|
|
207
|
+
if (closeAfterDaysFor(settings, e.collection) === null && !threads.get(e.id)?.closesAt)
|
|
208
|
+
continue;
|
|
209
|
+
const thread = threads.get(e.id);
|
|
210
|
+
if (thread?.mode === "closed" || thread?.mode === "hidden") continue;
|
|
211
|
+
const at = threadClosesAt(
|
|
212
|
+
settings,
|
|
213
|
+
{ nodeId: e.id, collection: e.collection, publishedAt: e.publishedAt ?? null },
|
|
214
|
+
thread,
|
|
215
|
+
);
|
|
216
|
+
if (at === null) continue;
|
|
217
|
+
const t = Date.parse(at);
|
|
218
|
+
if (t <= now.getTime() && t > now.getTime() - CLOSING_WINDOW_MS)
|
|
219
|
+
tags.push(`cloudhal-comments-${e.id}`);
|
|
220
|
+
}
|
|
221
|
+
if (tags.length > 0) {
|
|
222
|
+
await store.purgeQueue.enqueue(site.id, tags, "normal");
|
|
223
|
+
closed += tags.length;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
const deployment = await store.retention.runDeployment(now, oldestSaltMonthToKeep(now));
|
|
228
|
+
return {
|
|
229
|
+
sites: sites.length,
|
|
230
|
+
retained,
|
|
231
|
+
deletedEntries,
|
|
232
|
+
closed,
|
|
233
|
+
salts: deployment.salts,
|
|
234
|
+
purgeLog: deployment.purgeLog,
|
|
235
|
+
more,
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** The comment secrets and switches of a deployment (both Workers read the same key). */
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
/** True when the deployment serves comments: a valid key and not switched off. */
|
|
252
|
+
export function commentsOn(env ) {
|
|
253
|
+
const key = env.CLOUDHAL_COMMENTS_KEY;
|
|
254
|
+
return (
|
|
255
|
+
typeof key === "string" &&
|
|
256
|
+
key.length >= MIN_SECRET_LENGTH &&
|
|
257
|
+
env.CLOUDHAL_COMMENTS_AVAILABLE !== "false"
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* The admin Worker's `CommentsDeps`, or `undefined` when comments are unavailable. `wake` is
|
|
263
|
+
* called after a write queued purge rows (the Worker flushes in `waitUntil`); `purgeSite` purges
|
|
264
|
+
* the whole site cache (the last resort).
|
|
265
|
+
*/
|
|
266
|
+
export async function adminComments(
|
|
267
|
+
env ,
|
|
268
|
+
sql ,
|
|
269
|
+
o
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
= {},
|
|
273
|
+
) {
|
|
274
|
+
if (!commentsOn(env)) return undefined;
|
|
275
|
+
return {
|
|
276
|
+
store: new SqlCommentStore(sql),
|
|
277
|
+
keys: await deriveCommentKeys(env.CLOUDHAL_COMMENTS_KEY ),
|
|
278
|
+
...(o.wake ? { onQueued: o.wake } : {}),
|
|
279
|
+
...(o.purgeSite ? { purgeSite: o.purgeSite } : {}),
|
|
280
|
+
};
|
|
281
|
+
}
|