@vercel/board 0.32.0 → 0.33.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/README.md +25 -20
- package/dist/{access-CY5xVMIK.mjs → access-N3XmkKXg.mjs} +3 -3
- package/dist/access.d.mts +4 -5
- package/dist/access.mjs +5 -5
- package/dist/{actors-Bm-ojWWT.mjs → actors-ihyN47OV.mjs} +3 -3
- package/dist/{auth-K8dY1nBY.d.mts → auth-D6z3rMNj.d.mts} +7 -93
- package/dist/{auth-8pRZnF1M.mjs → auth-r-_PeZyw.mjs} +32 -148
- package/dist/{backend-DxE9wGKm.d.mts → backend-CWpyR1A7.d.mts} +81 -51
- package/dist/backend-local.d.mts +28 -0
- package/dist/backend-local.mjs +2 -0
- package/dist/{chat-provider-DkFp2hrh.mjs → chat-provider-9hCT654s.mjs} +2 -2
- package/dist/{chat-provider-BChYrrA7.d.mts → chat-provider-DJpFUaFv.d.mts} +2 -3
- package/dist/cli-commands.d.mts +1 -1
- package/dist/cli-commands.mjs +1 -1
- package/dist/cli-embedded.d.mts +2 -2
- package/dist/cli-embedded.mjs +1 -1
- package/dist/cli.mjs +6 -6
- package/dist/{commands-CpyPV_tk.d.mts → commands-BOBQHVqM.d.mts} +9 -0
- package/dist/{commands-DsnQKTdB.mjs → commands-CHoMl06v.mjs} +12 -1
- package/dist/{conformance-3RBKxwbp.mjs → conformance-qKmGLTAT.mjs} +5 -5
- package/dist/conformance.d.mts +1 -1
- package/dist/conformance.mjs +1 -1
- package/dist/{engine-DurYIRt8.mjs → engine-JxgZiikU.mjs} +6 -8
- package/dist/{errors-CJXhhzvT.mjs → errors-Pk0XV1hK.mjs} +56 -2
- package/dist/{events-lujPA3gQ.mjs → events-IQg0k281.mjs} +2 -2
- package/dist/exports-BuKjVq2t.d.mts +4 -0
- package/dist/exports-gHDHlg0i.mjs +3207 -0
- package/dist/{external-D3p5T57R.mjs → external-CYe424fO.mjs} +1 -1
- package/dist/{folds-DLUzfibJ.d.mts → folds-DjFTiqIM.d.mts} +38 -44
- package/dist/index-CXvvYNYj.d.mts +11 -0
- package/dist/index.d.mts +9 -8
- package/dist/index.mjs +21 -8
- package/dist/index.node.d.mts +5 -6
- package/dist/index.node.mjs +3 -3
- package/dist/inspect/app.js +95 -95
- package/dist/{internal-CvsrprnU-zZMpDiRY.mjs → internal-CvsrprnU-CEPOUpAv.mjs} +63 -43
- package/dist/local-BbLjA5vI.mjs +8818 -0
- package/dist/{main-CcYDo9Hb.mjs → main-CQpCZJFw.mjs} +91 -23
- package/dist/{backend-a2/store-memory.mjs → memory-7RRnLa4X.mjs} +3 -3
- package/dist/middleware-BU7rVi9F.mjs +103 -0
- package/dist/{client-COfYrgfV.d.mts → provider-BlzUvcM9.d.mts} +665 -5
- package/dist/{schemas-DBmUO6pr.mjs → schemas-BG205xds.mjs} +2 -5
- package/dist/{serve-Bplieh0C.mjs → serve-D8_W4UN6.mjs} +33 -24
- package/dist/{node-BgeGcwX0.mjs → server-BiIUXWbU.mjs} +419 -6
- package/dist/{serving-Y7s7VDjB.mjs → serving-D7rcUtSC.mjs} +1 -1
- package/dist/{sql-E1K5g_ih.mjs → sql-BQzKUqQt.mjs} +349 -114
- package/dist/sqlite-DCtZFEVm.mjs +30 -0
- package/dist/{sqlite-db-CzcD_FW8.mjs → sqlite-db-qLTs52Ny.mjs} +2 -3
- package/dist/{store-codec-pAG2oPgQ-SqDXlPBR.mjs → store-N8PXxDAS-BdL4Sq-f.mjs} +6 -2
- package/dist/{store-memory-B0PkVSuQ.mjs → store-memory-CKQVEzXN.mjs} +2 -4
- package/dist/store-memory-OdGsc-t_.mjs +2 -0
- package/dist/{store-polling-BZt2Rf3D-Div-bJ_D.mjs → store-polling-BZt2Rf3D-oh3aU_An.mjs} +1 -1
- package/dist/store-sqlite-CTxAVCcz.mjs +2 -0
- package/dist/{store-sqlite-D85t3tE7.mjs → store-sqlite-D6fIszST.mjs} +3 -4
- package/dist/sync-chat-sdk.d.mts +2 -2
- package/dist/sync-chat-sdk.mjs +2 -2
- package/dist/sync-github.d.mts +2 -2
- package/dist/sync-github.mjs +2 -2
- package/dist/sync-linear.d.mts +2 -3
- package/dist/sync-linear.mjs +2 -2
- package/dist/sync-slack.d.mts +3 -3
- package/dist/sync-slack.mjs +4 -4
- package/dist/sync.d.mts +2 -2
- package/dist/sync.mjs +2 -2
- package/dist/{watchers-hash-CurCzwhe.mjs → targets-CknPGGVi.mjs} +40 -10
- package/dist/{tokens-C7kYyrAG.mjs → tokens-DPKjl3jf.mjs} +15 -43
- package/docs/01-board/01-mounting.md +243 -288
- package/docs/01-board/03-identity.md +41 -50
- package/docs/01-board/04-messages.md +15 -14
- package/docs/01-board/05-reading.md +3 -3
- package/docs/01-board/06-watchers.md +58 -105
- package/docs/01-board/07-schedules.md +21 -41
- package/docs/01-board/08-middleware.md +11 -17
- package/docs/01-board/09-access.md +76 -313
- package/docs/01-board/10-local.md +81 -0
- package/docs/01-quickstart.md +49 -126
- package/docs/02-sync/01-overview.md +25 -80
- package/docs/02-sync/02-functions.md +10 -16
- package/docs/02-sync/03-slack.md +13 -26
- package/docs/02-sync/04-github.md +8 -20
- package/docs/02-sync/07-linear.md +6 -10
- package/docs/03-guides/02-inspector.md +3 -3
- package/docs/03-guides/03-ci.md +88 -128
- package/docs/03-guides/04-triage.md +7 -15
- package/docs/03-guides/05-agent-factory.md +30 -36
- package/docs/04-reference/01-cli.md +104 -22
- package/docs/04-reference/02-board.md +60 -74
- package/docs/04-reference/03-http.md +119 -57
- package/docs/04-reference/05-conformance.md +31 -45
- package/docs/index.md +41 -65
- package/package.json +12 -83
- package/dist/a2-DiDc77Uf.mjs +0 -4238
- package/dist/access-DPcrKIH_.d.mts +0 -37
- package/dist/backend-a2/blob-vercel.d.mts +0 -8
- package/dist/backend-a2/blob-vercel.mjs +0 -81
- package/dist/backend-a2/contract.d.mts +0 -828
- package/dist/backend-a2/contract.mjs +0 -5
- package/dist/backend-a2/scheduler-local.d.mts +0 -11
- package/dist/backend-a2/scheduler-local.mjs +0 -2
- package/dist/backend-a2/scheduler-qstash.d.mts +0 -79
- package/dist/backend-a2/scheduler-qstash.mjs +0 -522
- package/dist/backend-a2/scheduler-vercel.d.mts +0 -38
- package/dist/backend-a2/scheduler-vercel.mjs +0 -204
- package/dist/backend-a2/store-memory.d.mts +0 -11
- package/dist/backend-a2/store-postgres.d.mts +0 -38
- package/dist/backend-a2/store-postgres.mjs +0 -2977
- package/dist/backend-a2/store-redis-http.d.mts +0 -17
- package/dist/backend-a2/store-redis-http.mjs +0 -520
- package/dist/backend-a2/store-redis.d.mts +0 -31
- package/dist/backend-a2/store-redis.mjs +0 -88
- package/dist/backend-a2/store-sqlite.d.mts +0 -12
- package/dist/backend-a2/store-sqlite.mjs +0 -31
- package/dist/backend-a2.d.mts +0 -2633
- package/dist/backend-a2.mjs +0 -3
- package/dist/backend-http-CaN06CaD.d.mts +0 -672
- package/dist/backend-http-CoaCghuJ.mjs +0 -18
- package/dist/backend-http-l5A8UmL-.mjs +0 -585
- package/dist/backend-http.d.mts +0 -10
- package/dist/backend-http.mjs +0 -2
- package/dist/backend-http.node.d.mts +0 -10
- package/dist/backend-http.node.mjs +0 -2
- package/dist/backend-vercel-BE65okBC.mjs +0 -86
- package/dist/backend-vercel-CVxoTNF2.mjs +0 -1744
- package/dist/backend-vercel-jg-6PAgD.d.mts +0 -674
- package/dist/backend-vercel.d.mts +0 -9
- package/dist/backend-vercel.mjs +0 -11
- package/dist/backend-vercel.node.d.mts +0 -17
- package/dist/backend-vercel.node.mjs +0 -2
- package/dist/blob-Bx8QPWEd.d.mts +0 -40
- package/dist/blob-WbB2DJKn.mjs +0 -201
- package/dist/errors-2vGs49Db.d.mts +0 -16
- package/dist/exports-BnUZuRm9.mjs +0 -1389
- package/dist/exports-u5mApVvn.d.mts +0 -5
- package/dist/files-SniSmeEr.mjs +0 -47
- package/dist/folds-DsWfIftc.mjs +0 -208
- package/dist/index-UXpTPWNc.d.mts +0 -11
- package/dist/index.default-Dp8gexln.mjs +0 -12
- package/dist/local-C76Fy5ad.mjs +0 -44
- package/dist/middleware-BavYSDUa.mjs +0 -62
- package/dist/platform-B4TnJtWu-Do3agKr5.mjs +0 -32
- package/dist/project-4Vl7_uy5.mjs +0 -124
- package/dist/provider-gynDUoyW.d.mts +0 -665
- package/dist/redis-tables-BFRj_SEJ.mjs +0 -3895
- package/dist/reducer-Bswr11ar-P324o9vn.mjs +0 -74
- package/dist/reducer-CYPHsSmd-BXjGiptm.d.mts +0 -170
- package/dist/reducers-DQVSP3kk.mjs +0 -538
- package/dist/retryable-lazy-DZWmHpii-DpTc5PIP.mjs +0 -19
- package/dist/scheduler-task-X1SToDjP-D2Il2rln.mjs +0 -69
- package/dist/server-B9gu0qi1-DI1WvcVK.d.mts +0 -391
- package/dist/server-DX7mM6nm-D7N_7bug.mjs +0 -3611
- package/dist/server-wIpAEjpX.mjs +0 -17
- package/dist/session-clear-XJYpmUpg-2q8l_FJR.mjs +0 -63
- package/dist/store-DEzcHZOA-B-5vhxef.d.mts +0 -540
- package/dist/store-N8PXxDAS-DWWgv-Vz.mjs +0 -5
- package/dist/store-memory-4IBl0Ztu.mjs +0 -2
- package/dist/store-presence-polling-JuAy2Ck2-Dh-g_KYM.mjs +0 -109
- package/dist/store-sqlite-iBTYYKBj.mjs +0 -2
- package/dist/stream-buffer-DrTyiIuo-Be10yOBR.mjs +0 -53
- package/dist/targets-Cgjs29T0.mjs +0 -33
- package/dist/types-CmrFjpml.d.mts +0 -102
- package/dist/wait-until-Dw4XrIDQ.mjs +0 -42
- package/docs/01-board/02-database.md +0 -258
- package/docs/04-reference/04-log.md +0 -247
- package/sql/postgres/board.sql +0 -145
- package/sql/postgres/notifications.sql +0 -24
- package/sql/postgres/schema.sql +0 -451
package/dist/a2-DiDc77Uf.mjs
DELETED
|
@@ -1,4238 +0,0 @@
|
|
|
1
|
-
import { r as IMPORT_BYTES_MAX, t as ATTACHMENT_BYTES_MAX } from "./files-SniSmeEr.mjs";
|
|
2
|
-
import { _ as RemoteWatcherId, b as actorKind, v as SCOPE_MAX, x as platformAvatar } from "./schemas-DBmUO6pr.mjs";
|
|
3
|
-
import "./external-D3p5T57R.mjs";
|
|
4
|
-
import { a as METHODS, d as VERSION, f as SYNC, n as compileWatcher, r as hasCriteria, t as canonicalWatchers } from "./watchers-hash-CurCzwhe.mjs";
|
|
5
|
-
import { a as forbidden, c as toErrorResponse, f as duration, i as duplicateId, l as unauthorized, r as badRequest, s as notFound, t as HttpError, u as BoardError } from "./errors-CJXhhzvT.mjs";
|
|
6
|
-
import { i as isKeyIdOf, r as derivedId, t as waitUntil } from "./wait-until-Dw4XrIDQ.mjs";
|
|
7
|
-
import { a as scopeOf, i as parseScope, n as authorize, r as compileAccess, t as FULL_ACCESS } from "./access-CY5xVMIK.mjs";
|
|
8
|
-
import { t as own } from "./own-OwgPWdmh.mjs";
|
|
9
|
-
import { n as replaceMentions } from "./mentions-CB6ShY4R.mjs";
|
|
10
|
-
import { a as resolveMentions, n as actorSeen } from "./actors-Bm-ojWWT.mjs";
|
|
11
|
-
import { C as wroteAs, f as grantIssuers, n as DEFAULT_CAN, o as authenticates, s as checkGrant, t as BOARD_TOKEN_PREFIX, y as tokenHash } from "./auth-8pRZnF1M.mjs";
|
|
12
|
-
import { n as MIDDLEWARE_ACTOR, t as DroppedError } from "./middleware-BavYSDUa.mjs";
|
|
13
|
-
import { n as syncTarget, r as withEmailMentions } from "./targets-Cgjs29T0.mjs";
|
|
14
|
-
import { t as A2Error } from "./session-clear-XJYpmUpg-2q8l_FJR.mjs";
|
|
15
|
-
import { a as reducer } from "./reducer-Bswr11ar-P324o9vn.mjs";
|
|
16
|
-
import { a as INBOXES_SESSION, c as accessContract, d as inboxSession, f as registryContract, g as BOARD_SESSION, h as watchSession, i as ACCESS_SESSION, l as boardContract, m as watchContract, n as channelsReducer, o as REGISTRY_SESSION, p as schedulesContract, s as SCHEDULES_SESSION, t as actorsReducer, u as inboxContract } from "./reducers-DQVSP3kk.mjs";
|
|
17
|
-
import { n as createServer, t as consumer } from "./server-DX7mM6nm-D7N_7bug.mjs";
|
|
18
|
-
import { i as iso, n as foldMessages, t as foldActors } from "./folds-DsWfIftc.mjs";
|
|
19
|
-
import { c as ownUpload, d as writeUpload, i as finishUpload, l as readUpload, n as attachmentNotFound, t as attachmentBody, u as startUpload } from "./blob-WbB2DJKn.mjs";
|
|
20
|
-
import { t as concernedMessageId } from "./project-4Vl7_uy5.mjs";
|
|
21
|
-
import { t as TABLES_CONSUMER } from "./sql-E1K5g_ih.mjs";
|
|
22
|
-
import { t as afterRetry } from "./attempts-HXcskN1w.mjs";
|
|
23
|
-
import { createHash, randomBytes } from "node:crypto";
|
|
24
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
25
|
-
import { lookup } from "node:dns";
|
|
26
|
-
import { request } from "node:https";
|
|
27
|
-
import { BlockList, isIP } from "node:net";
|
|
28
|
-
//#region ../../node_modules/.pnpm/experimental-a2@0.24.0_@upstash+qstash@2.12.0_@vercel+queue@0.7.0_ai@7.0.130_zod@4.6.5__b1e2c243a963f2620a5d202817417c26/node_modules/experimental-a2/dist/idempotent-id-BRJVeylj.js
|
|
29
|
-
async function idempotentId(...parts) {
|
|
30
|
-
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(parts)));
|
|
31
|
-
const bytes = new Uint8Array(digest).slice(0, 16);
|
|
32
|
-
bytes[6] = bytes[6] & 15 | 128;
|
|
33
|
-
bytes[8] = bytes[8] & 63 | 128;
|
|
34
|
-
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
35
|
-
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
|
|
36
|
-
}
|
|
37
|
-
//#endregion
|
|
38
|
-
//#region src/server/trust.ts
|
|
39
|
-
/** How long a token lives when its minter doesn't say, and at most: npm caps its write tokens at 90 days. */
|
|
40
|
-
const TOKEN_DEFAULT_MS = 2592e6;
|
|
41
|
-
/** How deep tokens minted with tokens go: each request walks the chain to its root. */
|
|
42
|
-
const TOKEN_DEPTH_MAX = 8;
|
|
43
|
-
const DAY_MS = 864e5;
|
|
44
|
-
/** What makes two grants one: the issuer, and the claims with their names sorted. */
|
|
45
|
-
const grantKey = (issuer, claims) => JSON.stringify([issuer, Object.keys(claims).sort().map((name) => [name, claims[name]])]);
|
|
46
|
-
function dropToken(state, id) {
|
|
47
|
-
const row = state.tokens[id];
|
|
48
|
-
if (!row) return;
|
|
49
|
-
delete state.hashes[row.hash];
|
|
50
|
-
delete state.tokens[id];
|
|
51
|
-
}
|
|
52
|
-
/** Whether token `id` is token `ancestor`, or was minted with it at any depth. */
|
|
53
|
-
function mintedWith(state, id, ancestor) {
|
|
54
|
-
let at = id;
|
|
55
|
-
for (let depth = 0; at !== null && depth <= TOKEN_DEPTH_MAX; depth++) {
|
|
56
|
-
if (at === ancestor) return true;
|
|
57
|
-
at = state.tokens[at]?.parent ?? null;
|
|
58
|
-
}
|
|
59
|
-
return false;
|
|
60
|
-
}
|
|
61
|
-
/**
|
|
62
|
-
* Whether `identity` may see and revoke token `row`: anyone's with `manage` in every channel. A
|
|
63
|
-
* token acts as its minter, so its principal alone would hand it every token its minter has: with
|
|
64
|
-
* a token, it's that token and those minted with it; without one, those its principal minted.
|
|
65
|
-
*/
|
|
66
|
-
function manages(state, { principal }, row) {
|
|
67
|
-
if (principal.access.everywhere("manage")) return true;
|
|
68
|
-
if (row.minter.id !== principal.id) return false;
|
|
69
|
-
if (principal.token === void 0) return true;
|
|
70
|
-
const held = indexOf$1(principal.token, "t");
|
|
71
|
-
return held !== null && mintedWith(state, row.id, held);
|
|
72
|
-
}
|
|
73
|
-
/**
|
|
74
|
-
* The access session's fold. It prunes by the events' own times, so every instance folds the same
|
|
75
|
-
* state, and each event costs a day's expired tokens at most. A child whose parent is gone counts
|
|
76
|
-
* as dead (`liveIn`), and lives no longer than its parent, so pruning never brings one back.
|
|
77
|
-
*/
|
|
78
|
-
function foldAccess(state, event) {
|
|
79
|
-
const at = new Date(event.createdAt).getTime();
|
|
80
|
-
const day = Math.floor(at / DAY_MS);
|
|
81
|
-
if (state.pruned === null) state.pruned = day;
|
|
82
|
-
for (; state.pruned < day; state.pruned++) {
|
|
83
|
-
for (const id of state.expiring[state.pruned] ?? []) dropToken(state, id);
|
|
84
|
-
delete state.expiring[state.pruned];
|
|
85
|
-
}
|
|
86
|
-
switch (event.type) {
|
|
87
|
-
case "grant.set": {
|
|
88
|
-
const { issuer, claims, can, by } = event.payload;
|
|
89
|
-
const key = grantKey(issuer, claims);
|
|
90
|
-
const existing = state.grants[key];
|
|
91
|
-
if (existing) Object.assign(existing, {
|
|
92
|
-
can,
|
|
93
|
-
by,
|
|
94
|
-
at
|
|
95
|
-
});
|
|
96
|
-
else {
|
|
97
|
-
state.grants[key] = {
|
|
98
|
-
id: event.index,
|
|
99
|
-
issuer,
|
|
100
|
-
claims,
|
|
101
|
-
can,
|
|
102
|
-
by,
|
|
103
|
-
at
|
|
104
|
-
};
|
|
105
|
-
state.grantKeys[event.index] = key;
|
|
106
|
-
}
|
|
107
|
-
break;
|
|
108
|
-
}
|
|
109
|
-
case "grant.revoked": {
|
|
110
|
-
const key = state.grantKeys[event.payload.id];
|
|
111
|
-
if (key !== void 0) {
|
|
112
|
-
delete state.grants[key];
|
|
113
|
-
delete state.grantKeys[event.payload.id];
|
|
114
|
-
}
|
|
115
|
-
break;
|
|
116
|
-
}
|
|
117
|
-
case "token.minted": {
|
|
118
|
-
const { payload } = event;
|
|
119
|
-
if (state.hashes[payload.hash] !== void 0) break;
|
|
120
|
-
state.tokens[event.index] = {
|
|
121
|
-
id: event.index,
|
|
122
|
-
...payload,
|
|
123
|
-
minter: payload.minter,
|
|
124
|
-
at
|
|
125
|
-
};
|
|
126
|
-
state.hashes[payload.hash] = event.index;
|
|
127
|
-
(state.expiring[Math.floor(payload.expiresAt / DAY_MS)] ??= []).push(event.index);
|
|
128
|
-
break;
|
|
129
|
-
}
|
|
130
|
-
case "token.revoked": dropToken(state, event.payload.id);
|
|
131
|
-
}
|
|
132
|
-
return state;
|
|
133
|
-
}
|
|
134
|
-
const accessReducer = reducer({
|
|
135
|
-
contract: accessContract,
|
|
136
|
-
name: "board.access.v1",
|
|
137
|
-
initialState: {
|
|
138
|
-
grants: {},
|
|
139
|
-
grantKeys: {},
|
|
140
|
-
tokens: {},
|
|
141
|
-
hashes: {},
|
|
142
|
-
expiring: {},
|
|
143
|
-
pruned: null
|
|
144
|
-
}
|
|
145
|
-
}).fold(foldAccess);
|
|
146
|
-
const grantId = (id) => `g${id}`;
|
|
147
|
-
const tokenId = (id) => `t${id}`;
|
|
148
|
-
/** The index an ID names: `g12` or `t12` for 12. Null for one that names none. */
|
|
149
|
-
function indexOf$1(id, prefix) {
|
|
150
|
-
const found = new RegExp(`^${prefix}([1-9]\\d{0,15})$`).exec(id);
|
|
151
|
-
return found ? Number(found[1]) : null;
|
|
152
|
-
}
|
|
153
|
-
const grantView = (row) => ({
|
|
154
|
-
id: grantId(row.id),
|
|
155
|
-
issuer: row.issuer,
|
|
156
|
-
claims: row.claims,
|
|
157
|
-
can: compileAccess(row.can).summary(),
|
|
158
|
-
by: row.by,
|
|
159
|
-
at: new Date(row.at).toISOString()
|
|
160
|
-
});
|
|
161
|
-
/** A token as the protocol shows it, with `can` what it may do now (`accessNow`'s, for its minter). */
|
|
162
|
-
const tokenView = (row, can) => ({
|
|
163
|
-
id: tokenId(row.id),
|
|
164
|
-
name: row.name,
|
|
165
|
-
can: can === null ? {} : can.summary(),
|
|
166
|
-
profile: row.profile,
|
|
167
|
-
session: row.session,
|
|
168
|
-
by: row.by,
|
|
169
|
-
at: new Date(row.at).toISOString(),
|
|
170
|
-
expiresAt: new Date(row.expiresAt).toISOString(),
|
|
171
|
-
parent: row.parent === null ? null : tokenId(row.parent)
|
|
172
|
-
});
|
|
173
|
-
/** A new token's secret: the prefix and 32 random bytes, base64url. */
|
|
174
|
-
function newSecret() {
|
|
175
|
-
const bytes = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32));
|
|
176
|
-
return `${BOARD_TOKEN_PREFIX}${btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")}`;
|
|
177
|
-
}
|
|
178
|
-
const needsManage = (identity, what) => {
|
|
179
|
-
if (!identity.principal.access.everywhere("manage")) throw forbidden(`this token can't ${what}: it needs manage in every channel`);
|
|
180
|
-
};
|
|
181
|
-
/**
|
|
182
|
-
* The board's grants and tokens, in session `access` of its log: what `a2()` answers for them, and
|
|
183
|
-
* what board() checks requests against. `issuers`: the OIDC issuers the board's rules name, which no
|
|
184
|
-
* grant's may share principals with. `accessNow`: what a principal may do now, under board()'s
|
|
185
|
-
* rules and grants, which a token's listing shows.
|
|
186
|
-
*/
|
|
187
|
-
function createTrust(options) {
|
|
188
|
-
const session = createServer({
|
|
189
|
-
contract: accessContract,
|
|
190
|
-
store: options.store
|
|
191
|
-
}).session(ACCESS_SESSION);
|
|
192
|
-
const read = async () => (await session.state(accessReducer)).state;
|
|
193
|
-
/**
|
|
194
|
-
* What each of `rows` may do now: its minter's access, narrowed by its scope. A minter's is worked
|
|
195
|
-
* out once, however many tokens it has.
|
|
196
|
-
*/
|
|
197
|
-
async function viewsOf(rows) {
|
|
198
|
-
const minters = /* @__PURE__ */ new Map();
|
|
199
|
-
return Promise.all(rows.map(async (row) => {
|
|
200
|
-
const { scope, ...minter } = row.minter;
|
|
201
|
-
const key = JSON.stringify(minter);
|
|
202
|
-
let access = minters.get(key);
|
|
203
|
-
if (!access) minters.set(key, access = options.accessNow(minter));
|
|
204
|
-
const now = await access;
|
|
205
|
-
return tokenView(row, now === null || scope === void 0 ? now : now.narrow(parseScope(scope)));
|
|
206
|
-
}));
|
|
207
|
-
}
|
|
208
|
-
/** Whether token `id` and every token it was minted with are live now. */
|
|
209
|
-
function liveIn(state, id) {
|
|
210
|
-
let at = id;
|
|
211
|
-
for (let depth = 0; at !== null; depth++) {
|
|
212
|
-
const row = state.tokens[at];
|
|
213
|
-
if (!row || row.expiresAt <= Date.now() || depth > TOKEN_DEPTH_MAX) return false;
|
|
214
|
-
at = row.parent;
|
|
215
|
-
}
|
|
216
|
-
return true;
|
|
217
|
-
}
|
|
218
|
-
return {
|
|
219
|
-
trust: {
|
|
220
|
-
async grants() {
|
|
221
|
-
return Object.values((await read()).grants).map((row) => ({
|
|
222
|
-
...grantView(row),
|
|
223
|
-
can: row.can
|
|
224
|
-
}));
|
|
225
|
-
},
|
|
226
|
-
async token(hash) {
|
|
227
|
-
const state = await read();
|
|
228
|
-
const id = state.hashes[hash];
|
|
229
|
-
if (id === void 0 || !liveIn(state, id)) return null;
|
|
230
|
-
const row = state.tokens[id];
|
|
231
|
-
return {
|
|
232
|
-
id: tokenId(row.id),
|
|
233
|
-
name: row.name,
|
|
234
|
-
minter: row.minter,
|
|
235
|
-
pinned: {
|
|
236
|
-
profile: row.profile,
|
|
237
|
-
avatar: row.avatar,
|
|
238
|
-
session: row.session,
|
|
239
|
-
handle: row.handle,
|
|
240
|
-
name: row.personName
|
|
241
|
-
},
|
|
242
|
-
expiresAt: new Date(row.expiresAt)
|
|
243
|
-
};
|
|
244
|
-
},
|
|
245
|
-
async live(id) {
|
|
246
|
-
const index = indexOf$1(id, "t");
|
|
247
|
-
return index !== null && liveIn(await read(), index);
|
|
248
|
-
}
|
|
249
|
-
},
|
|
250
|
-
async grants(identity) {
|
|
251
|
-
needsManage(identity, "list grants");
|
|
252
|
-
return { grants: Object.values((await read()).grants).sort((a, b) => a.id - b.id).map(grantView) };
|
|
253
|
-
},
|
|
254
|
-
async createGrant(identity, body) {
|
|
255
|
-
needsManage(identity, "set grants");
|
|
256
|
-
const before = await read();
|
|
257
|
-
const checked = checkGrant(body, [...options.issuers(), ...grantIssuers(Object.values(before.grants))]);
|
|
258
|
-
const key = grantKey(checked.issuer, checked.claims);
|
|
259
|
-
const created = before.grants[key] === void 0;
|
|
260
|
-
await session.append({
|
|
261
|
-
type: "grant.set",
|
|
262
|
-
payload: {
|
|
263
|
-
issuer: checked.issuer,
|
|
264
|
-
claims: checked.claims,
|
|
265
|
-
can: checked.can,
|
|
266
|
-
by: identity.actor.id
|
|
267
|
-
}
|
|
268
|
-
});
|
|
269
|
-
const row = (await read()).grants[key];
|
|
270
|
-
return {
|
|
271
|
-
grant: grantView(row),
|
|
272
|
-
created
|
|
273
|
-
};
|
|
274
|
-
},
|
|
275
|
-
async revokeGrant(identity, { id }) {
|
|
276
|
-
needsManage(identity, "revoke grants");
|
|
277
|
-
const index = indexOf$1(id, "g");
|
|
278
|
-
if (index === null || (await read()).grantKeys[index] === void 0) return { revoked: false };
|
|
279
|
-
await session.append({
|
|
280
|
-
type: "grant.revoked",
|
|
281
|
-
payload: {
|
|
282
|
-
id: index,
|
|
283
|
-
by: identity.actor.id
|
|
284
|
-
}
|
|
285
|
-
});
|
|
286
|
-
return { revoked: true };
|
|
287
|
-
},
|
|
288
|
-
async tokens(identity) {
|
|
289
|
-
const state = await read();
|
|
290
|
-
return { tokens: await viewsOf(Object.values(state.tokens).filter((row) => liveIn(state, row.id) && manages(state, identity, row)).sort((a, b) => a.id - b.id)) };
|
|
291
|
-
},
|
|
292
|
-
/** The board tokens `principal` came with: its own, then each it was minted with. Undefined with none. */
|
|
293
|
-
async chain(principal) {
|
|
294
|
-
if (principal.token === void 0) return void 0;
|
|
295
|
-
const state = await read();
|
|
296
|
-
const chain = [];
|
|
297
|
-
for (let at = indexOf$1(principal.token, "t"); at !== null && chain.length <= TOKEN_DEPTH_MAX; at = state.tokens[at]?.parent ?? null) chain.push(tokenId(at));
|
|
298
|
-
return chain;
|
|
299
|
-
},
|
|
300
|
-
async createToken(identity, body) {
|
|
301
|
-
const { principal, author, actor } = identity;
|
|
302
|
-
const state = await read();
|
|
303
|
-
const now = Date.now();
|
|
304
|
-
const asked = body.expires === void 0 ? TOKEN_DEFAULT_MS : duration(body.expires);
|
|
305
|
-
if (asked <= 0 || asked > 7776e6) throw badRequest("a token lives up to 90 days: pass expires as 90d or less", "invalid_expires");
|
|
306
|
-
let expiresAt = now + asked;
|
|
307
|
-
let parent = null;
|
|
308
|
-
if (principal.token !== void 0) {
|
|
309
|
-
const index = indexOf$1(principal.token, "t");
|
|
310
|
-
parent = index === null ? null : state.tokens[index] ?? null;
|
|
311
|
-
if (!parent || !liveIn(state, parent.id)) throw unauthorized("invalid token: revoked, expired, or not this board's");
|
|
312
|
-
let depth = 0;
|
|
313
|
-
for (let at = parent; at; at = at.parent === null ? void 0 : state.tokens[at.parent]) depth++;
|
|
314
|
-
if (depth >= TOKEN_DEPTH_MAX) throw badRequest(`tokens minted with tokens go ${TOKEN_DEPTH_MAX} deep at most`, "invalid_token");
|
|
315
|
-
expiresAt = Math.min(expiresAt, parent.expiresAt);
|
|
316
|
-
}
|
|
317
|
-
let can;
|
|
318
|
-
try {
|
|
319
|
-
can = compileAccess(body.can ?? DEFAULT_CAN);
|
|
320
|
-
} catch (error) {
|
|
321
|
-
throw badRequest(error.message, "invalid_scope");
|
|
322
|
-
}
|
|
323
|
-
const scope = scopeOf((principal.scope === void 0 ? FULL_ACCESS : compileAccess(parseScope(principal.scope))).narrow(can));
|
|
324
|
-
if (scope.length > 4e3) throw badRequest(`a token's can is ${SCOPE_MAX} characters at most as a scope: name fewer channels`, "invalid_scope");
|
|
325
|
-
const minter = {
|
|
326
|
-
id: principal.id,
|
|
327
|
-
kind: principal.kind,
|
|
328
|
-
handle: principal.handle,
|
|
329
|
-
...principal.facts ? { facts: principal.facts } : {},
|
|
330
|
-
scope
|
|
331
|
-
};
|
|
332
|
-
const pinned = principal.pinned;
|
|
333
|
-
const profile = pinned?.profile ?? body.profile ?? null;
|
|
334
|
-
const avatar = pinned?.profile ? pinned.avatar : profile !== null ? body.avatar ?? null : null;
|
|
335
|
-
const pinnedSession = pinned?.session ?? body.session ?? null;
|
|
336
|
-
const person = principal.kind === "person";
|
|
337
|
-
const base = author.profile === null ? actor.handle : actor.handle.slice(0, Math.max(0, actor.handle.length - author.profile.length - 1)) || principal.handle;
|
|
338
|
-
const handle = pinned?.handle ?? (person ? base : null);
|
|
339
|
-
const personName = pinned?.name ?? (person && author.profile === null ? actor.name : null);
|
|
340
|
-
const secret = newSecret();
|
|
341
|
-
const [row] = await session.append({
|
|
342
|
-
type: "token.minted",
|
|
343
|
-
payload: {
|
|
344
|
-
hash: await tokenHash(secret),
|
|
345
|
-
name: body.name,
|
|
346
|
-
minter,
|
|
347
|
-
profile,
|
|
348
|
-
avatar,
|
|
349
|
-
session: pinnedSession,
|
|
350
|
-
handle,
|
|
351
|
-
personName,
|
|
352
|
-
expiresAt,
|
|
353
|
-
parent: parent?.id ?? null,
|
|
354
|
-
by: actor.id
|
|
355
|
-
}
|
|
356
|
-
});
|
|
357
|
-
const minted = row && (await read()).tokens[row.index];
|
|
358
|
-
if (!minted) throw new Error("a token was minted but its log has no record of it");
|
|
359
|
-
const [view] = await viewsOf([minted]);
|
|
360
|
-
return {
|
|
361
|
-
token: view,
|
|
362
|
-
secret
|
|
363
|
-
};
|
|
364
|
-
},
|
|
365
|
-
async revokeToken(identity, { id }) {
|
|
366
|
-
const state = await read();
|
|
367
|
-
const index = indexOf$1(id, "t");
|
|
368
|
-
const row = index === null ? void 0 : state.tokens[index];
|
|
369
|
-
if (!row || !liveIn(state, row.id) || !manages(state, identity, row)) return { revoked: false };
|
|
370
|
-
await session.append({
|
|
371
|
-
type: "token.revoked",
|
|
372
|
-
payload: {
|
|
373
|
-
id: row.id,
|
|
374
|
-
by: identity.actor.id
|
|
375
|
-
}
|
|
376
|
-
});
|
|
377
|
-
return { revoked: true };
|
|
378
|
-
}
|
|
379
|
-
};
|
|
380
|
-
}
|
|
381
|
-
//#endregion
|
|
382
|
-
//#region src/server/feed.ts
|
|
383
|
-
/** Bookkeeping events, shown only with `all`: who's who, and delivery receipts. */
|
|
384
|
-
const HIDDEN = /* @__PURE__ */ new Set([
|
|
385
|
-
"actor.seen",
|
|
386
|
-
"message.synced",
|
|
387
|
-
"message.files_synced"
|
|
388
|
-
]);
|
|
389
|
-
function actorView(actors, id) {
|
|
390
|
-
const author = own(actors.byId, id);
|
|
391
|
-
if (!author) return null;
|
|
392
|
-
return {
|
|
393
|
-
kind: author.kind,
|
|
394
|
-
handle: author.handle,
|
|
395
|
-
name: author.name,
|
|
396
|
-
avatar: author.avatar
|
|
397
|
-
};
|
|
398
|
-
}
|
|
399
|
-
/** The board's own code, which reads every channel: it needs no messages to say so. */
|
|
400
|
-
const OWN_CODE = {
|
|
401
|
-
access: FULL_ACCESS,
|
|
402
|
-
channelOf: () => void 0
|
|
403
|
-
};
|
|
404
|
-
/** The board messages `links` point to, for `Reader.channelOf`. */
|
|
405
|
-
const linkedIds = (links) => links.flatMap((link) => link.message === null ? [] : [link.message]);
|
|
406
|
-
/**
|
|
407
|
-
* Links as `reader` may see them. The log keeps each snapshot; it's hidden when
|
|
408
|
-
* it's read. A linked message the reader's lookup doesn't have hides too: its
|
|
409
|
-
* snapshot shows only where it's known to be readable.
|
|
410
|
-
*/
|
|
411
|
-
function readableLinks(links, reader) {
|
|
412
|
-
return links.map((link) => {
|
|
413
|
-
if (link.message === null) return {
|
|
414
|
-
...link,
|
|
415
|
-
message: null
|
|
416
|
-
};
|
|
417
|
-
const channel = reader.access.readsAll ? void 0 : reader.channelOf(link.message);
|
|
418
|
-
return reader.access.readsAll || channel !== void 0 && reader.access.readable(channel) ? {
|
|
419
|
-
...link,
|
|
420
|
-
message: ref(link.message)
|
|
421
|
-
} : {
|
|
422
|
-
url: link.url,
|
|
423
|
-
message: null,
|
|
424
|
-
snapshot: null,
|
|
425
|
-
unavailable: "not_readable"
|
|
426
|
-
};
|
|
427
|
-
});
|
|
428
|
-
}
|
|
429
|
-
/** The links in an event view: its payload's, its message's, and the message before a label change. */
|
|
430
|
-
const viewLinks = (view) => {
|
|
431
|
-
const { payload, message, before } = view;
|
|
432
|
-
return [
|
|
433
|
-
payload?.links,
|
|
434
|
-
message?.links,
|
|
435
|
-
before?.links
|
|
436
|
-
].filter((links) => links !== void 0);
|
|
437
|
-
};
|
|
438
|
-
/** The board messages an event view's links point to, for a reader of them. */
|
|
439
|
-
const viewLinkedIds = (view) => viewLinks(view).flatMap((links) => links.flatMap((link) => link.message === null ? [] : [indexOf(link.message) ?? 0]));
|
|
440
|
-
/**
|
|
441
|
-
* An event view made for one reader, as `reader` sees it: a link to a message it can't read shows
|
|
442
|
-
* nothing of it. A watcher's match is made when its event lands and pulled later, by whatever its
|
|
443
|
-
* registrant may read then.
|
|
444
|
-
*/
|
|
445
|
-
function viewedBy(view, reader) {
|
|
446
|
-
if (reader.access.readsAll) return view;
|
|
447
|
-
const shown = structuredClone(view);
|
|
448
|
-
const reread = (links) => readableLinks(links.map((link) => ({
|
|
449
|
-
...link,
|
|
450
|
-
message: link.message === null ? null : indexOf(link.message) ?? 0
|
|
451
|
-
})), reader);
|
|
452
|
-
if (shown.payload?.links) shown.payload.links = reread(shown.payload.links);
|
|
453
|
-
if (shown.message) shown.message.links = reread(shown.message.links);
|
|
454
|
-
if (shown.before) shown.before.links = reread(shown.before.links);
|
|
455
|
-
return shown;
|
|
456
|
-
}
|
|
457
|
-
/** A message's or a cursor's ID as clients see it. On this board it's the log index, in decimal. */
|
|
458
|
-
const ref = (index) => String(index);
|
|
459
|
-
/** A schedule's ID as clients see it: its index in session `schedules`, as `s12`, so it reads apart from message `12`. */
|
|
460
|
-
const scheduleRef = (index) => `s${index}`;
|
|
461
|
-
/** The log index a ref names on this board, or null for a string that names nothing here. */
|
|
462
|
-
const indexOf = (value) => /^(0|[1-9]\d{0,15})$/.test(value) ? Number(value) : null;
|
|
463
|
-
/** A message as `reader` sees it. Every view names its reader, so none shows a link's snapshot by default. */
|
|
464
|
-
function view(message, actors, reader) {
|
|
465
|
-
const { blind, version, revision, schedule, ...shown } = message;
|
|
466
|
-
return {
|
|
467
|
-
...shown,
|
|
468
|
-
...blind ? { blind } : {},
|
|
469
|
-
id: ref(message.id),
|
|
470
|
-
re: message.re === null ? null : ref(message.re),
|
|
471
|
-
replyTo: message.replyTo === null ? null : ref(message.replyTo),
|
|
472
|
-
version: version ?? message.id,
|
|
473
|
-
revision: revision ?? message.id,
|
|
474
|
-
...schedule ? { schedule: {
|
|
475
|
-
id: scheduleRef(schedule.id),
|
|
476
|
-
n: schedule.n
|
|
477
|
-
} } : {},
|
|
478
|
-
links: readableLinks(message.links, reader),
|
|
479
|
-
labels: { ...message.labels },
|
|
480
|
-
reactions: Object.fromEntries(Object.entries(message.reactions).map(([emoji, ids]) => [emoji, [...ids]])),
|
|
481
|
-
author: actorView(actors, message.by.actor)
|
|
482
|
-
};
|
|
483
|
-
}
|
|
484
|
-
const actorSet = (value, actors) => own(actors.byId, value) ? /* @__PURE__ */ new Set([value]) : new Set(own(actors.byHandle, value.toLowerCase()) ?? []);
|
|
485
|
-
/**
|
|
486
|
-
* Who a `--by` or `--mentions` value covers. A person (`julian`) is everyone they
|
|
487
|
-
* are: their own actor, and their agents (`julian/claude`). An agent or a platform
|
|
488
|
-
* actor is just itself.
|
|
489
|
-
*/
|
|
490
|
-
function whoIs(value, actors) {
|
|
491
|
-
const ids = actorSet(value, actors);
|
|
492
|
-
return {
|
|
493
|
-
actors: ids,
|
|
494
|
-
principals: new Set([...ids].filter((id) => own(actors.byId, id)?.kind === "person"))
|
|
495
|
-
};
|
|
496
|
-
}
|
|
497
|
-
/** Whether `author` is one of `who`: its actor, or an agent of one of its people. */
|
|
498
|
-
const covers = (who, actor, principal) => who.actors.has(actor) || principal !== void 0 && who.principals.has(principal);
|
|
499
|
-
const hasLabel = (labels, [key, values]) => Object.hasOwn(labels, key) && (values === null || values.includes(labels[key]));
|
|
500
|
-
/**
|
|
501
|
-
* Compiles filters once; handles resolve against the actors known at that
|
|
502
|
-
* moment. A label matches on the message or its thread's root, where sync puts
|
|
503
|
-
* labels, so `pr=…` means the PR's whole conversation. `messages` is the live
|
|
504
|
-
* state for that lookup. A message in a channel `access` can't read never
|
|
505
|
-
* matches, whatever the filters say.
|
|
506
|
-
*/
|
|
507
|
-
function compileFilter(filters, context) {
|
|
508
|
-
const { access } = context;
|
|
509
|
-
const text = filters.text?.toLowerCase();
|
|
510
|
-
const labels = filters.label ?? [];
|
|
511
|
-
const channel = filters.channel;
|
|
512
|
-
const subtree = channel?.endsWith("/") ? channel.slice(0, -1) : null;
|
|
513
|
-
const by = filters.by === void 0 ? null : whoIs(filters.by, context.actors);
|
|
514
|
-
const re = filters.re === void 0 ? void 0 : indexOf(filters.re) ?? -1;
|
|
515
|
-
const mentions = filters.mentions === void 0 ? null : filters.mentions === "me" ? new Set(context.me === null ? [] : [context.me]) : whoIs(filters.mentions, context.actors).actors;
|
|
516
|
-
return (message) => {
|
|
517
|
-
if (!message || !access.readable(message.channel)) return false;
|
|
518
|
-
if (channel !== void 0) {
|
|
519
|
-
if (subtree !== null) {
|
|
520
|
-
if (message.channel !== subtree && !message.channel.startsWith(`${subtree}/`)) return false;
|
|
521
|
-
} else if (message.channel !== channel) return false;
|
|
522
|
-
}
|
|
523
|
-
if (re !== void 0 && message.id !== re && message.re !== re) return false;
|
|
524
|
-
if (by !== null && !covers(by, message.by.actor, message.by.principal)) return false;
|
|
525
|
-
if (mentions !== null && !message.mentions.some((id) => mentions.has(id))) return false;
|
|
526
|
-
if (filters.from !== void 0 && (message.from ?? "board") !== filters.from) return false;
|
|
527
|
-
if (text !== void 0 && !message.text.toLowerCase().includes(text)) return false;
|
|
528
|
-
if (labels.length > 0) {
|
|
529
|
-
const root = message.re === null ? void 0 : context.messages?.byId[message.re];
|
|
530
|
-
for (const label of labels) if (!hasLabel(message.labels, label) && !(root && hasLabel(root.labels, label))) return false;
|
|
531
|
-
}
|
|
532
|
-
return true;
|
|
533
|
-
};
|
|
534
|
-
}
|
|
535
|
-
/**
|
|
536
|
-
* `filter`, narrowed to the channels `access` reads among `known`, as the tables
|
|
537
|
-
* take it: a reader of every channel needs nothing more. A channel the caller
|
|
538
|
-
* didn't know of is left out, never let in.
|
|
539
|
-
*/
|
|
540
|
-
function readableFilter(filter, known, access) {
|
|
541
|
-
if (access.readsAll) return filter;
|
|
542
|
-
const { channel, ...rest } = filter;
|
|
543
|
-
const within = (path) => !channel || path === channel.path || channel.subtree && path.startsWith(`${channel.path}/`);
|
|
544
|
-
return {
|
|
545
|
-
...rest,
|
|
546
|
-
channels: [...known].filter((path) => within(path) && access.readable(path))
|
|
547
|
-
};
|
|
548
|
-
}
|
|
549
|
-
/** The filters as the tables take them: handles resolved to who they cover, `me` to the caller. */
|
|
550
|
-
function toMessageFilter(filters, context) {
|
|
551
|
-
const out = {};
|
|
552
|
-
const channel = filters.channel;
|
|
553
|
-
if (channel !== void 0) out.channel = channel.endsWith("/") ? {
|
|
554
|
-
path: channel.slice(0, -1),
|
|
555
|
-
subtree: true
|
|
556
|
-
} : {
|
|
557
|
-
path: channel,
|
|
558
|
-
subtree: false
|
|
559
|
-
};
|
|
560
|
-
if (filters.re !== void 0) out.re = indexOf(filters.re) ?? -1;
|
|
561
|
-
if (filters.by !== void 0) {
|
|
562
|
-
const who = whoIs(filters.by, context.actors);
|
|
563
|
-
out.by = {
|
|
564
|
-
actors: [...who.actors],
|
|
565
|
-
principals: [...who.principals]
|
|
566
|
-
};
|
|
567
|
-
}
|
|
568
|
-
if (filters.mentions !== void 0) out.mentions = filters.mentions === "me" ? context.me === null ? [] : [context.me] : [...whoIs(filters.mentions, context.actors).actors];
|
|
569
|
-
if (filters.from !== void 0) out.from = filters.from;
|
|
570
|
-
if (filters.text !== void 0) out.text = filters.text.toLowerCase();
|
|
571
|
-
if (filters.label?.length) out.labels = filters.label.map(([key, values]) => ({
|
|
572
|
-
key,
|
|
573
|
-
values
|
|
574
|
-
}));
|
|
575
|
-
return out;
|
|
576
|
-
}
|
|
577
|
-
/**
|
|
578
|
-
* Loads into `messages`, as they were just before `event`, the message it
|
|
579
|
-
* concerns and that message's root: what folding it and matching filters need.
|
|
580
|
-
* `loaded` remembers what was asked for already, found or not.
|
|
581
|
-
*/
|
|
582
|
-
async function loadInto(reads, messages, loaded, event, signal) {
|
|
583
|
-
const id = concernedMessageId(event);
|
|
584
|
-
if (id === null) return;
|
|
585
|
-
const through = event.index - 1;
|
|
586
|
-
const load = async (ids) => {
|
|
587
|
-
const wanted = ids.filter((want) => !loaded.has(want));
|
|
588
|
-
if (wanted.length === 0) return;
|
|
589
|
-
const found = await reads.messagesAt(wanted, through, signal);
|
|
590
|
-
for (const want of wanted) {
|
|
591
|
-
loaded.add(want);
|
|
592
|
-
const message = found.get(want);
|
|
593
|
-
if (message) messages.byId[want] = message;
|
|
594
|
-
}
|
|
595
|
-
};
|
|
596
|
-
if (event.type === "message.posted") loaded.add(id);
|
|
597
|
-
else await load([id]);
|
|
598
|
-
const re = event.type === "message.posted" ? event.payload.re : messages.byId[id]?.re ?? null;
|
|
599
|
-
if (re !== null) await load([re]);
|
|
600
|
-
}
|
|
601
|
-
/** The message `event` concerns and its root, as they were just before it. */
|
|
602
|
-
async function loadBefore(reads, event, signal) {
|
|
603
|
-
const messages = {
|
|
604
|
-
byId: {},
|
|
605
|
-
replies: {}
|
|
606
|
-
};
|
|
607
|
-
await loadInto(reads, messages, /* @__PURE__ */ new Set(), event, signal);
|
|
608
|
-
return messages;
|
|
609
|
-
}
|
|
610
|
-
/** Folds one event into `messages` and `actors`, and returns the message it concerns before and after. */
|
|
611
|
-
function foldEvent(messages, actors, event) {
|
|
612
|
-
const id = concernedMessageId(event);
|
|
613
|
-
const before = id === null ? void 0 : structuredClone(messages.byId[id]);
|
|
614
|
-
foldMessages(messages, event);
|
|
615
|
-
foldActors(actors, event);
|
|
616
|
-
return {
|
|
617
|
-
id,
|
|
618
|
-
before,
|
|
619
|
-
after: id === null ? void 0 : messages.byId[id]
|
|
620
|
-
};
|
|
621
|
-
}
|
|
622
|
-
/** An event as subscribers receive it, with its message as it is afterwards. */
|
|
623
|
-
function eventView(event, after, actors, reader) {
|
|
624
|
-
const by = event.payload.by?.actor;
|
|
625
|
-
const actor = by ? own(actors.byId, by) : void 0;
|
|
626
|
-
const { links } = event.payload;
|
|
627
|
-
return {
|
|
628
|
-
cursor: ref(event.index),
|
|
629
|
-
type: event.type,
|
|
630
|
-
createdAt: iso(event.createdAt),
|
|
631
|
-
payload: payloadView(event.payload, links ? readableLinks(links, reader) : void 0),
|
|
632
|
-
...after ? { message: view(after, actors, reader) } : {},
|
|
633
|
-
...actor ? { actor: {
|
|
634
|
-
id: actor.id,
|
|
635
|
-
...actorView(actors, actor.id)
|
|
636
|
-
} } : {}
|
|
637
|
-
};
|
|
638
|
-
}
|
|
639
|
-
/** An event's payload as clients see it: the message IDs in it are refs. */
|
|
640
|
-
function payloadView(payload, links) {
|
|
641
|
-
const shown = { ...payload };
|
|
642
|
-
for (const key of [
|
|
643
|
-
"id",
|
|
644
|
-
"re",
|
|
645
|
-
"replyTo"
|
|
646
|
-
]) if (typeof shown[key] === "number") shown[key] = ref(shown[key]);
|
|
647
|
-
const schedule = shown.schedule;
|
|
648
|
-
if (schedule) shown.schedule = {
|
|
649
|
-
id: scheduleRef(schedule.id),
|
|
650
|
-
n: schedule.n
|
|
651
|
-
};
|
|
652
|
-
if (links) shown.links = links;
|
|
653
|
-
return shown;
|
|
654
|
-
}
|
|
655
|
-
/**
|
|
656
|
-
* Folds events one at a time and decides what a subscriber sees. It holds only
|
|
657
|
-
* the messages events have touched, each loaded from the tables as it was just
|
|
658
|
-
* before the first event that touched it. A label or reaction change is
|
|
659
|
-
* delivered when its message matched the filter before *or* after it, so
|
|
660
|
-
* subscribers see messages leave a view too.
|
|
661
|
-
*
|
|
662
|
-
* It's the one choke point for `/events` (tail, wait, and poll): an event about
|
|
663
|
-
* a message shows only where `access` reads its channel, and one about no
|
|
664
|
-
* message (who's who, a thread's sync) only to a reader of every channel.
|
|
665
|
-
*/
|
|
666
|
-
var FeedProjection = class {
|
|
667
|
-
messages = {
|
|
668
|
-
byId: {},
|
|
669
|
-
replies: {}
|
|
670
|
-
};
|
|
671
|
-
loaded = /* @__PURE__ */ new Set();
|
|
672
|
-
reads;
|
|
673
|
-
actors;
|
|
674
|
-
match;
|
|
675
|
-
criteria;
|
|
676
|
-
all;
|
|
677
|
-
access;
|
|
678
|
-
/** Where each board message a view links to lives, for a reader that can't read every channel. */
|
|
679
|
-
linked = /* @__PURE__ */ new Map();
|
|
680
|
-
constructor(options) {
|
|
681
|
-
this.reads = options.reads;
|
|
682
|
-
this.actors = options.actors;
|
|
683
|
-
this.access = options.access;
|
|
684
|
-
this.match = compileFilter(options.filters, {
|
|
685
|
-
me: options.me,
|
|
686
|
-
actors: options.actors,
|
|
687
|
-
messages: this.messages,
|
|
688
|
-
access: options.access
|
|
689
|
-
});
|
|
690
|
-
this.criteria = hasCriteria(options.filters);
|
|
691
|
-
this.all = options.all;
|
|
692
|
-
}
|
|
693
|
-
/** Loads what `events` touch, all as of `index`, in two queries rather than two per event. */
|
|
694
|
-
async preload(events, index) {
|
|
695
|
-
const ids = /* @__PURE__ */ new Set();
|
|
696
|
-
for (const event of events) {
|
|
697
|
-
const id = concernedMessageId(event);
|
|
698
|
-
if (id === null) continue;
|
|
699
|
-
if (event.type !== "message.posted") ids.add(id);
|
|
700
|
-
else if (event.payload.re !== null) ids.add(event.payload.re);
|
|
701
|
-
}
|
|
702
|
-
const load = async (wanted) => {
|
|
703
|
-
if (wanted.length === 0) return;
|
|
704
|
-
const found = await this.reads.messagesAt(wanted, index);
|
|
705
|
-
for (const id of wanted) {
|
|
706
|
-
this.loaded.add(id);
|
|
707
|
-
const message = found.get(id);
|
|
708
|
-
if (message) this.messages.byId[id] = message;
|
|
709
|
-
}
|
|
710
|
-
};
|
|
711
|
-
await load([...ids].filter((id) => !this.loaded.has(id) && id <= index));
|
|
712
|
-
const roots = Object.values(this.messages.byId).flatMap((message) => message.re === null ? [] : [message.re]);
|
|
713
|
-
await load([...new Set(roots)].filter((id) => !this.loaded.has(id)));
|
|
714
|
-
}
|
|
715
|
-
async step(event, signal) {
|
|
716
|
-
await loadInto(this.reads, this.messages, this.loaded, event, signal);
|
|
717
|
-
const { id, before, after } = foldEvent(this.messages, this.actors, event);
|
|
718
|
-
const message = after ?? before;
|
|
719
|
-
const readable = id === null ? this.access.readsAll : message !== void 0 && this.access.readable(message.channel);
|
|
720
|
-
const hidden = HIDDEN.has(event.type) && !this.all;
|
|
721
|
-
if (!(readable && !hidden && (this.criteria ? this.match(before) || this.match(after) : id !== null || this.all))) return {
|
|
722
|
-
index: event.index,
|
|
723
|
-
view: null
|
|
724
|
-
};
|
|
725
|
-
await this.loadLinked([...after?.links ?? [], ...event.payload.links ?? []], event.index, signal);
|
|
726
|
-
const reader = {
|
|
727
|
-
access: this.access,
|
|
728
|
-
channelOf: (message) => this.messages.byId[message]?.channel ?? this.linked.get(message)
|
|
729
|
-
};
|
|
730
|
-
return {
|
|
731
|
-
index: event.index,
|
|
732
|
-
view: eventView(event, after, this.actors, reader)
|
|
733
|
-
};
|
|
734
|
-
}
|
|
735
|
-
/** Where the messages `links` point to live; a message never moves, so any version says. */
|
|
736
|
-
async loadLinked(links, index, signal) {
|
|
737
|
-
if (this.access.readsAll) return;
|
|
738
|
-
const wanted = [...new Set(linkedIds(links))].filter((id) => !this.messages.byId[id] && !this.linked.has(id));
|
|
739
|
-
if (wanted.length === 0) return;
|
|
740
|
-
const found = await this.reads.messagesAt(wanted, index, signal);
|
|
741
|
-
for (const id of wanted) this.linked.set(id, found.get(id)?.channel);
|
|
742
|
-
}
|
|
743
|
-
};
|
|
744
|
-
/** Resolves when the iterator yields, or with null once the signal aborts. */
|
|
745
|
-
function nextOrAbort(iterator, signal) {
|
|
746
|
-
if (signal.aborted) return Promise.resolve(null);
|
|
747
|
-
return new Promise((resolve, reject) => {
|
|
748
|
-
const onAbort = () => resolve(null);
|
|
749
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
750
|
-
iterator.next().then((result) => {
|
|
751
|
-
signal.removeEventListener("abort", onAbort);
|
|
752
|
-
resolve(result);
|
|
753
|
-
}, (error) => {
|
|
754
|
-
signal.removeEventListener("abort", onAbort);
|
|
755
|
-
reject(error);
|
|
756
|
-
});
|
|
757
|
-
});
|
|
758
|
-
}
|
|
759
|
-
/** Where a feed starts: `after`, or the head when it's omitted or past it. */
|
|
760
|
-
async function start(options) {
|
|
761
|
-
const { index: head } = await options.session.state(channelsReducer);
|
|
762
|
-
return options.after === void 0 || options.after >= head ? head : options.after;
|
|
763
|
-
}
|
|
764
|
-
const PAGE = 200;
|
|
765
|
-
/**
|
|
766
|
-
* One long-poll: matching events already in the log return at once; otherwise
|
|
767
|
-
* it waits up to `waitMs` for the first new match. The cursor is the last
|
|
768
|
-
* event examined, matched or not, so the next poll never rescans.
|
|
769
|
-
*/
|
|
770
|
-
async function pollFeed(options, waitMs, signal) {
|
|
771
|
-
const index = await start(options);
|
|
772
|
-
const feed = new FeedProjection(options);
|
|
773
|
-
const events = [];
|
|
774
|
-
let cursor = index;
|
|
775
|
-
const backlog = await options.session.history({
|
|
776
|
-
gte: index + 1,
|
|
777
|
-
lte: index + PAGE
|
|
778
|
-
});
|
|
779
|
-
await feed.preload(backlog, index);
|
|
780
|
-
for (const event of backlog) {
|
|
781
|
-
const item = await feed.step(event, signal);
|
|
782
|
-
cursor = item.index;
|
|
783
|
-
if (item.view) events.push(item.view);
|
|
784
|
-
}
|
|
785
|
-
if (events.length > 0 || backlog.length === PAGE || waitMs <= 0) return {
|
|
786
|
-
events,
|
|
787
|
-
cursor
|
|
788
|
-
};
|
|
789
|
-
const timeout = AbortSignal.timeout(waitMs);
|
|
790
|
-
const until = AbortSignal.any([signal, timeout]);
|
|
791
|
-
const iterator = options.session.stream({ startAfter: cursor })[Symbol.asyncIterator]();
|
|
792
|
-
try {
|
|
793
|
-
while (true) {
|
|
794
|
-
const next = await nextOrAbort(iterator, until);
|
|
795
|
-
if (next === null || next.done) return {
|
|
796
|
-
events,
|
|
797
|
-
cursor
|
|
798
|
-
};
|
|
799
|
-
const item = await feed.step(next.value, until);
|
|
800
|
-
cursor = item.index;
|
|
801
|
-
if (item.view) {
|
|
802
|
-
events.push(item.view);
|
|
803
|
-
return {
|
|
804
|
-
events,
|
|
805
|
-
cursor
|
|
806
|
-
};
|
|
807
|
-
}
|
|
808
|
-
}
|
|
809
|
-
} finally {
|
|
810
|
-
iterator.return?.();
|
|
811
|
-
}
|
|
812
|
-
}
|
|
813
|
-
//#endregion
|
|
814
|
-
//#region src/server/reads.ts
|
|
815
|
-
/** Keeps the tables from the board's log, one event at a time, from the first. */
|
|
816
|
-
function tablesConsumer(tables) {
|
|
817
|
-
return consumer({
|
|
818
|
-
contract: boardContract,
|
|
819
|
-
name: TABLES_CONSUMER,
|
|
820
|
-
lane: "tables",
|
|
821
|
-
backfill: true
|
|
822
|
-
}).run(async (ctx) => {
|
|
823
|
-
if (ctx.session.id !== "board") return;
|
|
824
|
-
await tables.apply(ctx.event);
|
|
825
|
-
});
|
|
826
|
-
}
|
|
827
|
-
/**
|
|
828
|
-
* The board's reads from its tables. A read that names a log index (a message
|
|
829
|
-
* ID is one) waits until the tables have applied it; list reads don't wait, and
|
|
830
|
-
* say which index they reflect.
|
|
831
|
-
*/
|
|
832
|
-
function createReads(tables, session, projection) {
|
|
833
|
-
/**
|
|
834
|
-
* The first list read on an instance starts the tables catching up, and doesn't wait: after a deploy
|
|
835
|
-
* that adds them, or on a quiet board, nothing else may have yet.
|
|
836
|
-
*/
|
|
837
|
-
let catching = null;
|
|
838
|
-
/**
|
|
839
|
-
* The reader of views whose links point to the board messages `linked`, looked up only for a
|
|
840
|
-
* reader that can't read every channel. A linked message is older than the one linking it, so
|
|
841
|
-
* the tables have it.
|
|
842
|
-
*/
|
|
843
|
-
async function readerOf(access, linked) {
|
|
844
|
-
if (access.readsAll) return {
|
|
845
|
-
access,
|
|
846
|
-
channelOf: () => void 0
|
|
847
|
-
};
|
|
848
|
-
const ids = [...new Set(linked)].filter((id) => id > 0);
|
|
849
|
-
const found = ids.length === 0 ? /* @__PURE__ */ new Map() : await tables.messagesAt(ids, await tables.position());
|
|
850
|
-
return {
|
|
851
|
-
access,
|
|
852
|
-
channelOf: (id) => found.get(id)?.channel
|
|
853
|
-
};
|
|
854
|
-
}
|
|
855
|
-
function catchUp() {
|
|
856
|
-
if (catching) return;
|
|
857
|
-
catching = session.consume(projection).catch(() => {
|
|
858
|
-
catching = null;
|
|
859
|
-
});
|
|
860
|
-
waitUntil(catching);
|
|
861
|
-
}
|
|
862
|
-
/**
|
|
863
|
-
* The tables caught up with the whole log once on this instance. Until then, a read by index waits
|
|
864
|
-
* for all of it: tables rebuilt from the log can be far behind, and a message's later events (an
|
|
865
|
-
* edit, a reaction, a reply) come after its own index. Once caught up, each write applies as it lands.
|
|
866
|
-
*/
|
|
867
|
-
let whole = null;
|
|
868
|
-
function caughtUp() {
|
|
869
|
-
whole ??= session.consume(projection).then(() => void 0, (error) => {
|
|
870
|
-
whole = null;
|
|
871
|
-
throw error;
|
|
872
|
-
});
|
|
873
|
-
return whole;
|
|
874
|
-
}
|
|
875
|
-
/** `promise`, unless `signal` aborts first: the caller stops waiting, and what it waits for keeps going. */
|
|
876
|
-
function untilAborted(promise, signal) {
|
|
877
|
-
if (!signal) return promise;
|
|
878
|
-
if (signal.aborted) return Promise.reject(signal.reason);
|
|
879
|
-
return new Promise((resolve, reject) => {
|
|
880
|
-
const abort = () => reject(signal.reason);
|
|
881
|
-
signal.addEventListener("abort", abort, { once: true });
|
|
882
|
-
promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
883
|
-
});
|
|
884
|
-
}
|
|
885
|
-
/** Waits until the tables have applied `index`, or the whole log when it's omitted. */
|
|
886
|
-
async function ensure(index, signal) {
|
|
887
|
-
if (index !== void 0) await untilAborted(caughtUp(), signal);
|
|
888
|
-
if (index !== void 0 && await tables.position() >= index) return;
|
|
889
|
-
await session.consume(projection, {
|
|
890
|
-
...index !== void 0 ? { through: index } : {},
|
|
891
|
-
...signal ? { signal } : {}
|
|
892
|
-
});
|
|
893
|
-
}
|
|
894
|
-
return {
|
|
895
|
-
tables,
|
|
896
|
-
ensure,
|
|
897
|
-
position: () => tables.position(),
|
|
898
|
-
async message(id, signal) {
|
|
899
|
-
await ensure(id, signal);
|
|
900
|
-
return tables.message(id);
|
|
901
|
-
},
|
|
902
|
-
/** A thread's root and replies; `cursor` is the index the tables had applied before reading it. */
|
|
903
|
-
async thread(root, signal) {
|
|
904
|
-
await ensure(root, signal);
|
|
905
|
-
const cursor = await tables.position();
|
|
906
|
-
return {
|
|
907
|
-
messages: await tables.thread(root),
|
|
908
|
-
cursor
|
|
909
|
-
};
|
|
910
|
-
},
|
|
911
|
-
async messagesAt(ids, index, signal) {
|
|
912
|
-
await ensure(index, signal);
|
|
913
|
-
return tables.messagesAt(ids, index);
|
|
914
|
-
},
|
|
915
|
-
/** By event ID, as of the whole log: an ID doesn't say how far to wait. */
|
|
916
|
-
async byEventId(eventId, signal) {
|
|
917
|
-
await ensure(void 0, signal);
|
|
918
|
-
return tables.byEventId(eventId);
|
|
919
|
-
},
|
|
920
|
-
/** The reader of views of `messages`: what a link shows depends on where the message it points to lives. */
|
|
921
|
-
reader: (access, messages) => readerOf(access, [...messages].flatMap((message) => linkedIds(message.links))),
|
|
922
|
-
readerOf,
|
|
923
|
-
async messages(filter, page) {
|
|
924
|
-
catchUp();
|
|
925
|
-
if (filter.channels?.length === 0) return {
|
|
926
|
-
messages: [],
|
|
927
|
-
position: await tables.position()
|
|
928
|
-
};
|
|
929
|
-
return tables.messages(filter, page);
|
|
930
|
-
},
|
|
931
|
-
async threads(filter, page) {
|
|
932
|
-
catchUp();
|
|
933
|
-
if (filter.channels?.length === 0) return {
|
|
934
|
-
threads: [],
|
|
935
|
-
position: await tables.position()
|
|
936
|
-
};
|
|
937
|
-
return tables.threads(filter, page);
|
|
938
|
-
}
|
|
939
|
-
};
|
|
940
|
-
}
|
|
941
|
-
//#endregion
|
|
942
|
-
//#region src/server/writes.ts
|
|
943
|
-
/** A piece of the board's own deployment, writing as `actor` with full access. */
|
|
944
|
-
function deploymentIdentity(actor, handle) {
|
|
945
|
-
return {
|
|
946
|
-
principal: {
|
|
947
|
-
id: actor,
|
|
948
|
-
kind: "deployment",
|
|
949
|
-
handle,
|
|
950
|
-
access: FULL_ACCESS,
|
|
951
|
-
expiresAt: null
|
|
952
|
-
},
|
|
953
|
-
author: {
|
|
954
|
-
actor,
|
|
955
|
-
principal: actor,
|
|
956
|
-
profile: null,
|
|
957
|
-
session: null
|
|
958
|
-
},
|
|
959
|
-
actor: {
|
|
960
|
-
id: actor,
|
|
961
|
-
kind: "deployment",
|
|
962
|
-
handle,
|
|
963
|
-
name: handle,
|
|
964
|
-
avatar: null
|
|
965
|
-
}
|
|
966
|
-
};
|
|
967
|
-
}
|
|
968
|
-
/**
|
|
969
|
-
* The `actor.seen` a write carries, or null: who its author is, as the board's record of them
|
|
970
|
-
* says, unless the board knows that already. A platform user's record is board-wide, so a write
|
|
971
|
-
* whose identity doesn't keep it (`records: false`) leaves it as it is. A host's principal and its
|
|
972
|
-
* profiles are recorded as the host's, which sync never writes as.
|
|
973
|
-
*/
|
|
974
|
-
function seenFor(identity, actors) {
|
|
975
|
-
if (identity.records === false) return null;
|
|
976
|
-
return actorSeen(identity.actor, actors, identity.principal.facts?.issuer === "host");
|
|
977
|
-
}
|
|
978
|
-
/** The actors a write can mention: the ones the board knows, plus the ones an email named. */
|
|
979
|
-
const knownWith = (actors, found) => found.length === 0 ? actors : {
|
|
980
|
-
...actors,
|
|
981
|
-
byId: {
|
|
982
|
-
...actors.byId,
|
|
983
|
-
...Object.fromEntries(found.map((a) => [a.id, a]))
|
|
984
|
-
}
|
|
985
|
-
};
|
|
986
|
-
const messageNotFound = (id) => () => notFound(`message not found: #${id}`, "message_not_found");
|
|
987
|
-
/**
|
|
988
|
-
* A message the board looked up and the caller may act on with `permission`,
|
|
989
|
-
* proved against its own channel. A message they can't read answers 404, as if
|
|
990
|
-
* it didn't exist: IDs are sequential, so a 403 would confirm it does.
|
|
991
|
-
*/
|
|
992
|
-
async function authorizeMessage(ctx, access, permission, id) {
|
|
993
|
-
const message = await ctx.reads.message(id);
|
|
994
|
-
if (!message) throw messageNotFound(id)();
|
|
995
|
-
return {
|
|
996
|
-
message,
|
|
997
|
-
proof: authorize(access, permission, message.channel, messageNotFound(id))
|
|
998
|
-
};
|
|
999
|
-
}
|
|
1000
|
-
/**
|
|
1001
|
-
* Your own message, to edit or delete: `post` in its channel. Where you can't
|
|
1002
|
-
* read, it's yours only if it was posted without reading too: a write-only
|
|
1003
|
-
* source fixes what it wrote, but a principal ID it shares with a caller that
|
|
1004
|
-
* reads (a repo's workflows share one) doesn't reach that caller's messages.
|
|
1005
|
-
* A board token that pins a profile owns only what was written as it (`wroteAs`).
|
|
1006
|
-
* Someone else's answers 404 where you can't read it, and 403 where you can.
|
|
1007
|
-
*/
|
|
1008
|
-
async function authorizeOwn(ctx, identity, id, verb) {
|
|
1009
|
-
const { principal } = identity;
|
|
1010
|
-
const message = await ctx.reads.message(id);
|
|
1011
|
-
if (!message) throw messageNotFound(id)();
|
|
1012
|
-
const readable = principal.access.readable(message.channel);
|
|
1013
|
-
if (!wroteAs(identity, message.by) || !readable && !message.blind) {
|
|
1014
|
-
if (!readable) throw messageNotFound(id)();
|
|
1015
|
-
throw forbidden(`only the author can ${verb} a message`);
|
|
1016
|
-
}
|
|
1017
|
-
return {
|
|
1018
|
-
message,
|
|
1019
|
-
proof: authorize(principal.access, "post", message.channel)
|
|
1020
|
-
};
|
|
1021
|
-
}
|
|
1022
|
-
const hasLabels = (labels) => Object.keys(labels ?? {}).length > 0;
|
|
1023
|
-
/**
|
|
1024
|
-
* Proofs for a post. A root lands in the channel it names, which the caller
|
|
1025
|
-
* needn't read: write-only is `['post']`. A reply lands in its root's channel,
|
|
1026
|
-
* looked up here and never taken from the request, and needs `read` there too,
|
|
1027
|
-
* since addressing a thread you can't see would confirm it exists.
|
|
1028
|
-
*/
|
|
1029
|
-
async function authorizePost(ctx, access, input) {
|
|
1030
|
-
let channel;
|
|
1031
|
-
let re;
|
|
1032
|
-
if (input.re !== void 0) {
|
|
1033
|
-
re = (await authorizeMessage(ctx, access, "read", input.re)).message;
|
|
1034
|
-
channel = re.channel;
|
|
1035
|
-
} else {
|
|
1036
|
-
if (!input.channel) throw badRequest("a post needs a channel");
|
|
1037
|
-
channel = input.channel;
|
|
1038
|
-
}
|
|
1039
|
-
return {
|
|
1040
|
-
post: authorize(access, "post", channel),
|
|
1041
|
-
...re ? { re } : {},
|
|
1042
|
-
...hasLabels(input.labels) ? { label: authorize(access, "label", channel) } : {},
|
|
1043
|
-
...input.sync?.length ? { sync: authorize(access, "sync", channel) } : {}
|
|
1044
|
-
};
|
|
1045
|
-
}
|
|
1046
|
-
/**
|
|
1047
|
-
* Spends a proof on its target: a write checked against one channel can't land
|
|
1048
|
-
* in another. A mismatch is the board's own bug, never the caller's.
|
|
1049
|
-
*/
|
|
1050
|
-
function spend(proof, permission, target) {
|
|
1051
|
-
if (!proof || proof.permission !== permission || proof.channel !== target.channel) throw new Error(`a ${permission} write in ${target.channel} needs a proof for that channel`);
|
|
1052
|
-
}
|
|
1053
|
-
/** Full-access proofs for the board's own code (sync), still checked against the channel each write lands in. */
|
|
1054
|
-
const trusted = {
|
|
1055
|
-
message: (ctx, permission, id) => authorizeMessage(ctx, FULL_ACCESS, permission, id),
|
|
1056
|
-
post: (ctx, input) => authorizePost(ctx, FULL_ACCESS, input)
|
|
1057
|
-
};
|
|
1058
|
-
async function writePost(ctx, input) {
|
|
1059
|
-
const { identity } = input;
|
|
1060
|
-
const sent = input.text;
|
|
1061
|
-
let channel = input.channel;
|
|
1062
|
-
let re = null;
|
|
1063
|
-
let replyTo = null;
|
|
1064
|
-
let thread;
|
|
1065
|
-
const id = input.id ?? (input.re === void 0 ? crypto.randomUUID() : void 0);
|
|
1066
|
-
if (input.re !== void 0) {
|
|
1067
|
-
const target = input.proofs.re;
|
|
1068
|
-
if (target?.id !== input.re) throw new Error(`a reply to #${input.re} needs proofs for that message`);
|
|
1069
|
-
re = target.re ?? target.id;
|
|
1070
|
-
replyTo = target.id === re ? null : target.id;
|
|
1071
|
-
channel = target.channel;
|
|
1072
|
-
thread = target.thread;
|
|
1073
|
-
if (input.sync?.length) throw badRequest("sync attaches whole threads: use `board sync <id> <target>`");
|
|
1074
|
-
} else {
|
|
1075
|
-
if (!channel) throw badRequest("a post needs a channel");
|
|
1076
|
-
if (input.after !== void 0) throw badRequest("`after` is for replies", "invalid_after");
|
|
1077
|
-
thread = id;
|
|
1078
|
-
}
|
|
1079
|
-
spend(input.proofs.post, "post", { channel });
|
|
1080
|
-
if (hasLabels(input.labels)) spend(input.proofs.label, "label", { channel });
|
|
1081
|
-
if (input.sync?.length) spend(input.proofs.sync, "sync", { channel });
|
|
1082
|
-
const replayed = await replayOf(ctx, input, {
|
|
1083
|
-
channel,
|
|
1084
|
-
re,
|
|
1085
|
-
replyTo
|
|
1086
|
-
}, sent);
|
|
1087
|
-
if (replayed) return replayed;
|
|
1088
|
-
if (input.after !== void 0) {
|
|
1089
|
-
if ((await ctx.reads.message(input.after))?.thread !== thread) throw badRequest(`after names no message in #${re}'s thread`, "invalid_after");
|
|
1090
|
-
}
|
|
1091
|
-
return commitPost(ctx, input, {
|
|
1092
|
-
channel,
|
|
1093
|
-
re,
|
|
1094
|
-
replyTo,
|
|
1095
|
-
thread,
|
|
1096
|
-
id,
|
|
1097
|
-
sent
|
|
1098
|
-
});
|
|
1099
|
-
}
|
|
1100
|
-
/** The post a caller's own ID already landed, as its retry gets it back: null when there's none. */
|
|
1101
|
-
async function replayOf(ctx, input, place, sent) {
|
|
1102
|
-
if (input.id === void 0) return null;
|
|
1103
|
-
const landed = await ctx.reads.byEventId(input.id);
|
|
1104
|
-
if (!landed) return null;
|
|
1105
|
-
if (landed.channel !== place.channel || landed.re !== place.re || landed.replyTo !== place.replyTo) throw duplicateId();
|
|
1106
|
-
const shown = await landedFor(ctx, input.identity, landed);
|
|
1107
|
-
if (!shown) throw duplicateId();
|
|
1108
|
-
return shownTo(shown, input.identity.principal.access, sent);
|
|
1109
|
-
}
|
|
1110
|
-
/**
|
|
1111
|
-
* A post that landed, as its author may have it back: only the same author's, and one in a
|
|
1112
|
-
* channel it can't read only if it posted without reading too. A caller that can't read gets back
|
|
1113
|
-
* what it sent, as it landed: never what others have added since. Null for anyone else.
|
|
1114
|
-
*/
|
|
1115
|
-
async function landedFor(ctx, identity, landed) {
|
|
1116
|
-
if (!sameAuthor(landed.by, identity.author)) return null;
|
|
1117
|
-
const { access } = identity.principal;
|
|
1118
|
-
const { state: actors } = await ctx.session.state(actorsReducer);
|
|
1119
|
-
if (access.readable(landed.channel)) return view(landed, actors, await readerFor(ctx, access, landed));
|
|
1120
|
-
if (!landed.blind) return null;
|
|
1121
|
-
const [event] = await ctx.session.history({
|
|
1122
|
-
gte: landed.id,
|
|
1123
|
-
lte: landed.id
|
|
1124
|
-
});
|
|
1125
|
-
const posted = foldMessages({
|
|
1126
|
-
byId: {},
|
|
1127
|
-
replies: {}
|
|
1128
|
-
}, event).byId[landed.id];
|
|
1129
|
-
return {
|
|
1130
|
-
...view(posted, actors, await readerFor(ctx, access, posted)),
|
|
1131
|
-
text: blindText(posted.text, identity.actor.id),
|
|
1132
|
-
mentions: []
|
|
1133
|
-
};
|
|
1134
|
-
}
|
|
1135
|
-
/**
|
|
1136
|
-
* A message's text for its writer where it can't read: each exact mention but of itself shows as
|
|
1137
|
-
* `@…`. The board may have turned an email it wrote into an actor ID, and who that is, `/actors`
|
|
1138
|
-
* doesn't show it either.
|
|
1139
|
-
*/
|
|
1140
|
-
const blindText = (text, own) => replaceMentions(text, (token) => token.kind === "actor" && token.actor !== own ? "@…" : null);
|
|
1141
|
-
const sameAuthor = (a, b) => a.actor === b.actor && a.principal === b.principal && a.profile === b.profile && a.session === b.session;
|
|
1142
|
-
async function commitPost(ctx, input, placed) {
|
|
1143
|
-
const { identity } = input;
|
|
1144
|
-
const { channel, re, replyTo, thread, id, sent } = placed;
|
|
1145
|
-
const { state: actors } = await ctx.session.state(actorsReducer);
|
|
1146
|
-
const targets = [];
|
|
1147
|
-
if (re === null) for (const requested of input.sync ?? []) {
|
|
1148
|
-
const target = syncTarget(requested);
|
|
1149
|
-
await unclaimed(ctx, target, thread, identity.principal.access);
|
|
1150
|
-
if (!targets.some((t) => t.target === target.target)) targets.push({
|
|
1151
|
-
...target,
|
|
1152
|
-
cause: "request"
|
|
1153
|
-
});
|
|
1154
|
-
}
|
|
1155
|
-
const seen = seenFor(identity, actors);
|
|
1156
|
-
const { text, found } = await withEmailMentions(input.text);
|
|
1157
|
-
const named = found.map((actor) => actorSeen(actor, actors)).filter((event) => event !== null);
|
|
1158
|
-
const { mentions, unknown } = resolveMentions(text, knownWith(actors, found), seen ? identity.actor : void 0, input.lenientMentions ?? false, identity.principal.access.readsAll);
|
|
1159
|
-
const synced = await Promise.all(targets.map(async ({ target, kind, cause }) => ({
|
|
1160
|
-
type: "thread.synced",
|
|
1161
|
-
id: await derivedId("board", thread, "sync", target),
|
|
1162
|
-
payload: {
|
|
1163
|
-
thread,
|
|
1164
|
-
target,
|
|
1165
|
-
kind,
|
|
1166
|
-
cause,
|
|
1167
|
-
by: identity.author
|
|
1168
|
-
}
|
|
1169
|
-
})));
|
|
1170
|
-
const events = [
|
|
1171
|
-
...seen ? [seen] : [],
|
|
1172
|
-
...named,
|
|
1173
|
-
{
|
|
1174
|
-
type: "message.posted",
|
|
1175
|
-
...id ? { id } : {},
|
|
1176
|
-
payload: {
|
|
1177
|
-
channel,
|
|
1178
|
-
text,
|
|
1179
|
-
re,
|
|
1180
|
-
replyTo,
|
|
1181
|
-
thread,
|
|
1182
|
-
labels: input.labels ?? {},
|
|
1183
|
-
noSync: input.noSync ?? false,
|
|
1184
|
-
mentions,
|
|
1185
|
-
by: identity.author,
|
|
1186
|
-
origin: input.origin ?? null,
|
|
1187
|
-
from: input.from ?? null,
|
|
1188
|
-
...input.attachments?.length ? { attachments: input.attachments } : {},
|
|
1189
|
-
...input.links?.length ? { links: input.links } : {},
|
|
1190
|
-
...input.schedule ? { schedule: input.schedule } : {},
|
|
1191
|
-
...identity.principal.access.readable(channel) ? {} : { blind: true },
|
|
1192
|
-
...input.importedBy !== void 0 ? { importedBy: input.importedBy } : {}
|
|
1193
|
-
}
|
|
1194
|
-
},
|
|
1195
|
-
...synced
|
|
1196
|
-
];
|
|
1197
|
-
let rows;
|
|
1198
|
-
try {
|
|
1199
|
-
rows = input.after === void 0 || re === null ? await ctx.session.append(...events) : await appendWhile(ctx, nothingAfter(ctx, re, input.after), events);
|
|
1200
|
-
} catch (error) {
|
|
1201
|
-
const replayed = error instanceof HttpError && error.code === "newer_message" ? await replayOf(ctx, input, {
|
|
1202
|
-
channel,
|
|
1203
|
-
re,
|
|
1204
|
-
replyTo
|
|
1205
|
-
}, sent) : null;
|
|
1206
|
-
if (replayed) return replayed;
|
|
1207
|
-
throw error;
|
|
1208
|
-
}
|
|
1209
|
-
const posted = rows.find((row) => row.type === "message.posted");
|
|
1210
|
-
await untilApplied(ctx, rows);
|
|
1211
|
-
const message = foldMessages({
|
|
1212
|
-
byId: {},
|
|
1213
|
-
replies: {}
|
|
1214
|
-
}, posted).byId[posted.index];
|
|
1215
|
-
const known = seen ? {
|
|
1216
|
-
...actors,
|
|
1217
|
-
byId: {
|
|
1218
|
-
...actors.byId,
|
|
1219
|
-
[identity.actor.id]: identity.actor
|
|
1220
|
-
}
|
|
1221
|
-
} : actors;
|
|
1222
|
-
return shownTo(view(message, known, await readerFor(ctx, identity.principal.access, message)), identity.principal.access, sent, unknown);
|
|
1223
|
-
}
|
|
1224
|
-
/**
|
|
1225
|
-
* A post's view for its writer. One that can't read the channel gets back the
|
|
1226
|
-
* text it sent, no mentions, and no `unknownMentions`: the board resolved its
|
|
1227
|
-
* handles and emails to actor IDs, which `/actors` doesn't show it, and which
|
|
1228
|
-
* handles matched no one would say which ones exist. The board keeps the
|
|
1229
|
-
* mentions, so they still notify.
|
|
1230
|
-
*/
|
|
1231
|
-
const shownTo = (shown, access, sent, unknown = []) => !access.readable(shown.channel) ? {
|
|
1232
|
-
...shown,
|
|
1233
|
-
text: sent,
|
|
1234
|
-
mentions: []
|
|
1235
|
-
} : unknown.length ? {
|
|
1236
|
-
...shown,
|
|
1237
|
-
unknownMentions: unknown
|
|
1238
|
-
} : shown;
|
|
1239
|
-
/** The writer, as the reader of the view its write returns. Only a link to a board message needs a lookup. */
|
|
1240
|
-
const readerFor = (ctx, access, message) => ctx.reads.reader(access, [message]);
|
|
1241
|
-
/**
|
|
1242
|
-
* Refuses an external thread another board thread is synced with: taking it
|
|
1243
|
-
* over would send its replies away from that thread, to a caller who may not
|
|
1244
|
-
* read it. A reader of that thread's channel learns which thread it is. It
|
|
1245
|
-
* reads the tables once they've applied the whole log, so a sync just made
|
|
1246
|
-
* counts.
|
|
1247
|
-
*/
|
|
1248
|
-
async function unclaimed(ctx, target, thread, access) {
|
|
1249
|
-
if (target.kind !== "thread") return;
|
|
1250
|
-
await ctx.reads.ensure();
|
|
1251
|
-
const owner = await ctx.reads.tables.threadOf(target.target);
|
|
1252
|
-
if (owner === null || owner === thread) return;
|
|
1253
|
-
const synced = await ctx.reads.tables.syncOf(owner);
|
|
1254
|
-
const which = synced && access.readable(synced.channel) ? `#${synced.root}` : "another thread";
|
|
1255
|
-
throw new HttpError(409, "already_synced", `${target.target} is already synced with ${which}`);
|
|
1256
|
-
}
|
|
1257
|
-
/**
|
|
1258
|
-
* Waits until the tables hold a write, so any read after it includes it. Most often
|
|
1259
|
-
* nothing was written in between, and the writer applies its own events itself; else
|
|
1260
|
-
* it waits for the tables' consumer. The write landed either way: if the tables are
|
|
1261
|
-
* slow or stuck, it still succeeds.
|
|
1262
|
-
*/
|
|
1263
|
-
async function untilApplied(ctx, rows) {
|
|
1264
|
-
const events = [...rows].sort((a, b) => a.index - b.index);
|
|
1265
|
-
const last = events.at(-1).index;
|
|
1266
|
-
try {
|
|
1267
|
-
let caughtUp = true;
|
|
1268
|
-
for (const event of events) if (!(caughtUp = await ctx.reads.tables.applyNext(event))) break;
|
|
1269
|
-
if (caughtUp) return;
|
|
1270
|
-
} catch {}
|
|
1271
|
-
await ctx.reads.ensure(last, AbortSignal.timeout(LANDED_WAIT_MS)).catch((error) => {
|
|
1272
|
-
console.warn(`[board] the tables haven't applied #${last} yet:`, error.message);
|
|
1273
|
-
});
|
|
1274
|
-
}
|
|
1275
|
-
/** How long a write waits for the tables before it answers anyway. */
|
|
1276
|
-
const LANDED_WAIT_MS = 1e4;
|
|
1277
|
-
/**
|
|
1278
|
-
* Appends `events` only while the board, as `holds` reads it, still allows them: `holds` checks
|
|
1279
|
-
* the tables, throws what refuses the write, and returns the index its reads reflect. The append
|
|
1280
|
-
* holds only while that index is still the log's last, so anything that lands in between,
|
|
1281
|
-
* anywhere on the board, moves it, and it looks again from there.
|
|
1282
|
-
*/
|
|
1283
|
-
async function appendWhile(ctx, holds, events) {
|
|
1284
|
-
return whileHeadMoves(async () => {
|
|
1285
|
-
await ctx.reads.ensure();
|
|
1286
|
-
return appendIfLast(ctx.session, await holds(), events);
|
|
1287
|
-
});
|
|
1288
|
-
}
|
|
1289
|
-
/**
|
|
1290
|
-
* Runs `attempt`, a look and a conditional append, again each time the board moves on in
|
|
1291
|
-
* between, up to `CONDITIONAL_TRIES` times: how every conditional write here looks again.
|
|
1292
|
-
*/
|
|
1293
|
-
async function whileHeadMoves(attempt) {
|
|
1294
|
-
for (let tries = 1;; tries++) try {
|
|
1295
|
-
return await attempt();
|
|
1296
|
-
} catch (error) {
|
|
1297
|
-
if (!headMoved(error)) throw error;
|
|
1298
|
-
if (tries === CONDITIONAL_TRIES) throw new HttpError(503, "unavailable", "the board kept changing while it checked: try again");
|
|
1299
|
-
await new Promise((resolve) => setTimeout(resolve, Math.random() * 5 * tries));
|
|
1300
|
-
}
|
|
1301
|
-
}
|
|
1302
|
-
/** How many times a conditional write looks again, as the board moves on, before it gives up. */
|
|
1303
|
-
const CONDITIONAL_TRIES = 10;
|
|
1304
|
-
/** A reply's `after`: nothing came after it in the thread, as of the index the read reflects. */
|
|
1305
|
-
const nothingAfter = (ctx, root, after) => async () => {
|
|
1306
|
-
const { messages: [newer], position } = await ctx.reads.tables.messages({ re: root }, {
|
|
1307
|
-
after,
|
|
1308
|
-
limit: 1
|
|
1309
|
-
});
|
|
1310
|
-
if (newer) throw new HttpError(409, "newer_message", `#${newer.id} came after #${after}`);
|
|
1311
|
-
return position;
|
|
1312
|
-
};
|
|
1313
|
-
/** The message a by-ID write targets, as the board looked it up, once its proof is spent on the message's channel. */
|
|
1314
|
-
function spent(authorized, permission) {
|
|
1315
|
-
spend(authorized.proof, permission, authorized.message);
|
|
1316
|
-
return authorized.message;
|
|
1317
|
-
}
|
|
1318
|
-
async function writeEdit(ctx, input) {
|
|
1319
|
-
const message = spent(input.authorized, "post");
|
|
1320
|
-
if (input.asAuthor !== false && message.by.principal !== input.identity.principal.id) throw forbidden("only the author can edit a message");
|
|
1321
|
-
if (message.deleted) {
|
|
1322
|
-
if (input.revision !== void 0 && input.revision !== (message.revision ?? message.id)) throw new HttpError(409, "revision_conflict", `#${message.id} was deleted since revision ${input.revision}`);
|
|
1323
|
-
throw badRequest("message was deleted", "message_deleted");
|
|
1324
|
-
}
|
|
1325
|
-
return commitEdit(ctx, input, message);
|
|
1326
|
-
}
|
|
1327
|
-
async function commitEdit(ctx, input, message) {
|
|
1328
|
-
const { state: actors } = await ctx.session.state(actorsReducer);
|
|
1329
|
-
const seen = seenFor(input.identity, actors);
|
|
1330
|
-
const { text, found } = await withEmailMentions(input.text);
|
|
1331
|
-
const named = found.map((actor) => actorSeen(actor, actors)).filter((event) => event !== null);
|
|
1332
|
-
const { mentions, unknown } = resolveMentions(text, knownWith(actors, found), seen ? input.identity.actor : void 0, input.from != null, input.identity.principal.access.readsAll);
|
|
1333
|
-
const events = [
|
|
1334
|
-
...seen ? [seen] : [],
|
|
1335
|
-
...named,
|
|
1336
|
-
{
|
|
1337
|
-
type: "message.edited",
|
|
1338
|
-
payload: {
|
|
1339
|
-
id: message.id,
|
|
1340
|
-
thread: message.thread,
|
|
1341
|
-
text,
|
|
1342
|
-
mentions,
|
|
1343
|
-
by: input.identity.author,
|
|
1344
|
-
from: input.from ?? null
|
|
1345
|
-
}
|
|
1346
|
-
}
|
|
1347
|
-
];
|
|
1348
|
-
await untilApplied(ctx, input.revision === void 0 ? await ctx.session.append(...events) : await appendWhile(ctx, revisionIs(ctx, message.id, input.revision), events));
|
|
1349
|
-
return unknown.length && input.identity.principal.access.readable(message.channel) ? { unknownMentions: unknown } : {};
|
|
1350
|
-
}
|
|
1351
|
-
/** A message's links, replaced: a platform edit or unfurl changed what it links to. */
|
|
1352
|
-
async function writeLinks(ctx, input) {
|
|
1353
|
-
const message = spent(input.authorized, "post");
|
|
1354
|
-
if (message.deleted) return;
|
|
1355
|
-
await untilApplied(ctx, await ctx.session.append({
|
|
1356
|
-
type: "message.linked",
|
|
1357
|
-
payload: {
|
|
1358
|
-
id: message.id,
|
|
1359
|
-
thread: message.thread,
|
|
1360
|
-
links: input.links,
|
|
1361
|
-
by: input.identity.author,
|
|
1362
|
-
from: input.from
|
|
1363
|
-
}
|
|
1364
|
-
}));
|
|
1365
|
-
}
|
|
1366
|
-
async function writeDelete(ctx, input) {
|
|
1367
|
-
const message = spent(input.authorized, "post");
|
|
1368
|
-
if (input.asAuthor !== false && message.by.principal !== input.identity.principal.id) throw forbidden("only the author can delete a message");
|
|
1369
|
-
if (message.deleted) {
|
|
1370
|
-
if (input.revision !== void 0 && input.revision !== (message.revision ?? message.id)) throw new HttpError(409, "revision_conflict", `#${message.id} was deleted since revision ${input.revision}`);
|
|
1371
|
-
return;
|
|
1372
|
-
}
|
|
1373
|
-
const deleted = [{
|
|
1374
|
-
type: "message.deleted",
|
|
1375
|
-
payload: {
|
|
1376
|
-
id: message.id,
|
|
1377
|
-
thread: message.thread,
|
|
1378
|
-
by: input.identity.author,
|
|
1379
|
-
from: input.from ?? null
|
|
1380
|
-
}
|
|
1381
|
-
}];
|
|
1382
|
-
await untilApplied(ctx, input.revision === void 0 ? await ctx.session.append(...deleted) : await appendWhile(ctx, revisionIs(ctx, message.id, input.revision), deleted));
|
|
1383
|
-
}
|
|
1384
|
-
/** An edit's or a delete's `revision`: no edit or delete since, as of the index the read reflects. */
|
|
1385
|
-
const revisionIs = (ctx, id, revision) => async () => {
|
|
1386
|
-
const position = await ctx.reads.tables.position();
|
|
1387
|
-
const message = (await ctx.reads.tables.messagesAt([id], position)).get(id);
|
|
1388
|
-
const now = message ? message.revision ?? message.id : null;
|
|
1389
|
-
if (now !== revision) throw new HttpError(409, "revision_conflict", message?.deleted ? `#${id} was deleted since revision ${revision}` : `#${id} was edited since revision ${revision}: it's at ${now}`);
|
|
1390
|
-
return position;
|
|
1391
|
-
};
|
|
1392
|
-
async function writeReaction(ctx, input) {
|
|
1393
|
-
const message = spent(input.authorized, "react");
|
|
1394
|
-
if (message.deleted) throw badRequest("message was deleted", "message_deleted");
|
|
1395
|
-
const { state: actors } = await ctx.session.state(actorsReducer);
|
|
1396
|
-
const seen = seenFor(input.identity, actors);
|
|
1397
|
-
await untilApplied(ctx, await ctx.session.append(...seen ? [seen] : [], {
|
|
1398
|
-
type: input.remove ? "reaction.removed" : "reaction.added",
|
|
1399
|
-
payload: {
|
|
1400
|
-
id: message.id,
|
|
1401
|
-
thread: message.thread,
|
|
1402
|
-
emoji: input.emoji,
|
|
1403
|
-
by: input.identity.author,
|
|
1404
|
-
from: input.from ?? null
|
|
1405
|
-
}
|
|
1406
|
-
}));
|
|
1407
|
-
}
|
|
1408
|
-
async function writeLabels(ctx, input) {
|
|
1409
|
-
const message = spent(input.authorized, "label");
|
|
1410
|
-
if (message.deleted) throw badRequest("message was deleted", "message_deleted");
|
|
1411
|
-
const { state: actors } = await ctx.session.state(actorsReducer);
|
|
1412
|
-
const seen = seenFor(input.identity, actors);
|
|
1413
|
-
const events = [...seen ? [seen] : [], {
|
|
1414
|
-
type: "labels.changed",
|
|
1415
|
-
payload: {
|
|
1416
|
-
id: message.id,
|
|
1417
|
-
thread: message.thread,
|
|
1418
|
-
set: input.set ?? {},
|
|
1419
|
-
unset: input.unset ?? [],
|
|
1420
|
-
by: input.identity.author
|
|
1421
|
-
}
|
|
1422
|
-
}];
|
|
1423
|
-
await untilApplied(ctx, input.if !== void 0 && Object.keys(input.if).length > 0 ? await appendWhile(ctx, labelsAre(ctx, message.id, input.if), events) : await ctx.session.append(...events));
|
|
1424
|
-
}
|
|
1425
|
-
/** A label write's `if`: each label is as it says, as of the index the read reflects. */
|
|
1426
|
-
const labelsAre = (ctx, id, expected) => async () => {
|
|
1427
|
-
const position = await ctx.reads.tables.position();
|
|
1428
|
-
const labels = (await ctx.reads.tables.messagesAt([id], position)).get(id)?.labels ?? {};
|
|
1429
|
-
for (const key of Object.keys(expected).sort()) {
|
|
1430
|
-
const now = own(labels, key);
|
|
1431
|
-
if (now === expected[key] || now === void 0 && expected[key] === null) continue;
|
|
1432
|
-
const wanted = expected[key];
|
|
1433
|
-
throw new HttpError(409, "label_conflict", wanted === null ? `${key} is set` : now === void 0 ? `${key} isn't set` : `${key} isn't ${wanted}`);
|
|
1434
|
-
}
|
|
1435
|
-
return position;
|
|
1436
|
-
};
|
|
1437
|
-
/**
|
|
1438
|
-
* Syncs a message's thread with a target, resolved by the sync that delivers it. Attaching twice
|
|
1439
|
-
* is a no-op; a platform thread another board thread is synced with is a 409.
|
|
1440
|
-
*/
|
|
1441
|
-
async function writeAttach(ctx, input) {
|
|
1442
|
-
const message = spent(input.authorized, "sync");
|
|
1443
|
-
const { target, kind } = input.target;
|
|
1444
|
-
await ctx.reads.ensure();
|
|
1445
|
-
if ((await ctx.reads.tables.syncOf(message.thread))?.targets.includes(target)) return { attached: false };
|
|
1446
|
-
await unclaimed(ctx, input.target, message.thread, input.identity.principal.access);
|
|
1447
|
-
await untilApplied(ctx, await ctx.session.append({
|
|
1448
|
-
type: "thread.synced",
|
|
1449
|
-
id: await derivedId("board", message.thread, "sync", target),
|
|
1450
|
-
payload: {
|
|
1451
|
-
thread: message.thread,
|
|
1452
|
-
target,
|
|
1453
|
-
kind,
|
|
1454
|
-
cause: input.cause,
|
|
1455
|
-
by: input.identity.author
|
|
1456
|
-
}
|
|
1457
|
-
}));
|
|
1458
|
-
return { attached: true };
|
|
1459
|
-
}
|
|
1460
|
-
/**
|
|
1461
|
-
* A channel made before anything posts to it, or the one that's there, made by a post or another
|
|
1462
|
-
* create, which `created: false` says. It needs `read` and `post` there, refused alike whether it's
|
|
1463
|
-
* there or not: the answer says whether it was, and shows what it holds.
|
|
1464
|
-
*/
|
|
1465
|
-
async function writeChannel(ctx, input) {
|
|
1466
|
-
const { access } = input.identity.principal;
|
|
1467
|
-
authorize(access, "read", input.path);
|
|
1468
|
-
authorize(access, "post", input.path);
|
|
1469
|
-
const seen = seenFor(input.identity, (await ctx.session.state(actorsReducer)).state);
|
|
1470
|
-
const events = [...seen ? [seen] : [], {
|
|
1471
|
-
type: "channel.created",
|
|
1472
|
-
payload: {
|
|
1473
|
-
channel: input.path,
|
|
1474
|
-
by: input.identity.author
|
|
1475
|
-
}
|
|
1476
|
-
}];
|
|
1477
|
-
const made = await whileHeadMoves(async () => {
|
|
1478
|
-
const { state, index } = await ctx.session.state(channelsReducer, { through: "latest" });
|
|
1479
|
-
const found = own(state, input.path);
|
|
1480
|
-
return found ? { found } : { rows: await appendIfLast(ctx.session, index, events) };
|
|
1481
|
-
});
|
|
1482
|
-
if ("found" in made) return {
|
|
1483
|
-
channel: made.found,
|
|
1484
|
-
created: false
|
|
1485
|
-
};
|
|
1486
|
-
await untilApplied(ctx, made.rows);
|
|
1487
|
-
return {
|
|
1488
|
-
channel: {
|
|
1489
|
-
path: input.path,
|
|
1490
|
-
lastIndex: 0,
|
|
1491
|
-
messages: 0,
|
|
1492
|
-
threads: 0
|
|
1493
|
-
},
|
|
1494
|
-
created: true
|
|
1495
|
-
};
|
|
1496
|
-
}
|
|
1497
|
-
/** The batch, only while `index` is still the session's last: A2's conditional append. */
|
|
1498
|
-
const appendIfLast = (session, index, events) => session.append.ifLastIndex(index, ...events);
|
|
1499
|
-
/** What A2 throws when the session's last index isn't the one a conditional append named. */
|
|
1500
|
-
const headMoved = (error) => error?.code === "LAST_INDEX_MISMATCH";
|
|
1501
|
-
//#endregion
|
|
1502
|
-
//#region src/server/registry.ts
|
|
1503
|
-
/** A principal as a registration keeps it: enough to work out its access again at each match. */
|
|
1504
|
-
const storedPrincipal = (principal) => ({
|
|
1505
|
-
id: principal.id,
|
|
1506
|
-
kind: principal.kind,
|
|
1507
|
-
handle: principal.handle,
|
|
1508
|
-
...principal.facts ? { facts: principal.facts } : {},
|
|
1509
|
-
...principal.scope !== void 0 ? { scope: principal.scope } : {},
|
|
1510
|
-
...principal.token !== void 0 ? { token: principal.token } : {}
|
|
1511
|
-
});
|
|
1512
|
-
/** What a registration shows: the principal's token facts stay on the board. */
|
|
1513
|
-
const viewOf = ({ principal: _principal, ...view }) => view;
|
|
1514
|
-
/**
|
|
1515
|
-
* The same on both ends: a board on `http()` hashes its watchers, and whether its sync subscribes,
|
|
1516
|
-
* and the board it uses hashes what it holds.
|
|
1517
|
-
*/
|
|
1518
|
-
function watchersHash(watch, sync = []) {
|
|
1519
|
-
return createHash("sha256").update(canonicalWatchers(watch, sync)).digest("hex").slice(0, 32);
|
|
1520
|
-
}
|
|
1521
|
-
function foldRegistry(state, event) {
|
|
1522
|
-
if (event.type === "watchers.registered") {
|
|
1523
|
-
const { owner, principal, url, watch, sync, hash } = event.payload;
|
|
1524
|
-
const copied = Object.fromEntries(Object.entries(watch).map(([id, spec]) => [id, {
|
|
1525
|
-
tail: spec.tail,
|
|
1526
|
-
when: spec.when
|
|
1527
|
-
}]));
|
|
1528
|
-
state.byOwner[owner] = {
|
|
1529
|
-
owner,
|
|
1530
|
-
principal: structuredClone(principal),
|
|
1531
|
-
url,
|
|
1532
|
-
watch: copied,
|
|
1533
|
-
sync: (sync ?? []).map((entry) => ({ ...entry })),
|
|
1534
|
-
hash
|
|
1535
|
-
};
|
|
1536
|
-
}
|
|
1537
|
-
return state;
|
|
1538
|
-
}
|
|
1539
|
-
const registryReducer = reducer({
|
|
1540
|
-
contract: registryContract,
|
|
1541
|
-
name: "board.registry.v1",
|
|
1542
|
-
initialState: { byOwner: {} }
|
|
1543
|
-
}).fold(foldRegistry);
|
|
1544
|
-
/** Watchers registered with this board by boards on `http()`. */
|
|
1545
|
-
function createRegistry(options) {
|
|
1546
|
-
const server = createServer({
|
|
1547
|
-
contract: registryContract,
|
|
1548
|
-
...options.store ? { store: options.store } : {},
|
|
1549
|
-
...options.scheduler ? { scheduler: options.scheduler } : {}
|
|
1550
|
-
});
|
|
1551
|
-
const session = server.session(REGISTRY_SESSION);
|
|
1552
|
-
const state = async () => (await session.state(registryReducer)).state;
|
|
1553
|
-
return {
|
|
1554
|
-
server,
|
|
1555
|
-
state,
|
|
1556
|
-
/**
|
|
1557
|
-
* Replaces `principal`'s registration. One that changes nothing writes nothing, so asking
|
|
1558
|
-
* again is free, unless the principal's token facts changed: those decide what it may read.
|
|
1559
|
-
*/
|
|
1560
|
-
async register(principal, input) {
|
|
1561
|
-
const owner = principal.id;
|
|
1562
|
-
const hash = watchersHash(input.watch, input.sync);
|
|
1563
|
-
const current = (await state()).byOwner[owner];
|
|
1564
|
-
if (current && current.url === input.url && current.hash === hash && JSON.stringify(current.principal) === JSON.stringify(principal)) return viewOf(current);
|
|
1565
|
-
await session.append({
|
|
1566
|
-
type: "watchers.registered",
|
|
1567
|
-
payload: {
|
|
1568
|
-
owner,
|
|
1569
|
-
principal,
|
|
1570
|
-
url: input.url,
|
|
1571
|
-
watch: input.watch,
|
|
1572
|
-
...input.sync.length > 0 ? { sync: input.sync } : {},
|
|
1573
|
-
hash
|
|
1574
|
-
}
|
|
1575
|
-
});
|
|
1576
|
-
return {
|
|
1577
|
-
owner,
|
|
1578
|
-
url: input.url,
|
|
1579
|
-
watch: input.watch,
|
|
1580
|
-
sync: input.sync,
|
|
1581
|
-
hash
|
|
1582
|
-
};
|
|
1583
|
-
},
|
|
1584
|
-
async list() {
|
|
1585
|
-
return Object.values((await state()).byOwner).sort((a, b) => a.owner.localeCompare(b.owner)).map(viewOf);
|
|
1586
|
-
}
|
|
1587
|
-
};
|
|
1588
|
-
}
|
|
1589
|
-
//#endregion
|
|
1590
|
-
//#region src/server/schedules.ts
|
|
1591
|
-
/** Vercel Queues delays at most 6 days: a send further out than this goes in hops. */
|
|
1592
|
-
const MAX_HOP_MS = 432e6;
|
|
1593
|
-
/** A timer that fires this early just waits again; any closer counts as on time. */
|
|
1594
|
-
const EARLY_MS = 1e3;
|
|
1595
|
-
const identityOf = (as) => {
|
|
1596
|
-
const { author, principal, actor } = as.payload.as;
|
|
1597
|
-
return {
|
|
1598
|
-
author,
|
|
1599
|
-
principal: {
|
|
1600
|
-
...principal,
|
|
1601
|
-
expiresAt: null
|
|
1602
|
-
},
|
|
1603
|
-
actor: {
|
|
1604
|
-
...actor,
|
|
1605
|
-
kind: actorKind(actor.kind)
|
|
1606
|
-
}
|
|
1607
|
-
};
|
|
1608
|
-
};
|
|
1609
|
-
function foldSchedules(state, event) {
|
|
1610
|
-
switch (event.type) {
|
|
1611
|
-
case "schedule.created": {
|
|
1612
|
-
const { payload } = event;
|
|
1613
|
-
state.byId[event.index] = {
|
|
1614
|
-
id: event.index,
|
|
1615
|
-
channel: payload.channel,
|
|
1616
|
-
re: payload.re,
|
|
1617
|
-
text: payload.text,
|
|
1618
|
-
labels: { ...payload.labels },
|
|
1619
|
-
noSync: payload.noSync,
|
|
1620
|
-
attachments: payload.attachments ?? [],
|
|
1621
|
-
first: payload.first,
|
|
1622
|
-
every: payload.every,
|
|
1623
|
-
until: payload.until,
|
|
1624
|
-
times: payload.times,
|
|
1625
|
-
as: identityOf(event),
|
|
1626
|
-
createdAt: new Date(event.createdAt).toISOString(),
|
|
1627
|
-
blind: payload.blind ?? false,
|
|
1628
|
-
sent: 0,
|
|
1629
|
-
next: payload.first,
|
|
1630
|
-
last: null,
|
|
1631
|
-
canceled: null
|
|
1632
|
-
};
|
|
1633
|
-
return state;
|
|
1634
|
-
}
|
|
1635
|
-
case "schedule.canceled": {
|
|
1636
|
-
const schedule = state.byId[event.payload.id];
|
|
1637
|
-
if (!schedule || schedule.next === null) return state;
|
|
1638
|
-
schedule.next = null;
|
|
1639
|
-
schedule.canceled = {
|
|
1640
|
-
by: event.payload.by,
|
|
1641
|
-
reason: event.payload.reason
|
|
1642
|
-
};
|
|
1643
|
-
return state;
|
|
1644
|
-
}
|
|
1645
|
-
case "schedule.fired": {
|
|
1646
|
-
const schedule = state.byId[event.payload.id];
|
|
1647
|
-
if (!schedule || schedule.next === null || schedule.sent !== event.payload.n) return state;
|
|
1648
|
-
schedule.sent++;
|
|
1649
|
-
schedule.last = event.payload.message;
|
|
1650
|
-
schedule.next = event.payload.next;
|
|
1651
|
-
return state;
|
|
1652
|
-
}
|
|
1653
|
-
case "schedule.takeover":
|
|
1654
|
-
state.takeover = {
|
|
1655
|
-
deployment: event.payload.deployment,
|
|
1656
|
-
index: event.index
|
|
1657
|
-
};
|
|
1658
|
-
return state;
|
|
1659
|
-
default: return state;
|
|
1660
|
-
}
|
|
1661
|
-
}
|
|
1662
|
-
const schedulesReducer = reducer({
|
|
1663
|
-
contract: schedulesContract,
|
|
1664
|
-
name: "board.schedules.v2",
|
|
1665
|
-
initialState: {
|
|
1666
|
-
byId: {},
|
|
1667
|
-
takeover: null
|
|
1668
|
-
}
|
|
1669
|
-
}).fold(foldSchedules);
|
|
1670
|
-
/** The send after one due at `at`: the next slot after now, so downtime skips missed slots instead of replaying them. */
|
|
1671
|
-
function nextSend(schedule, n, at, now) {
|
|
1672
|
-
if (schedule.every === null) return null;
|
|
1673
|
-
if (schedule.times !== null && n + 1 >= schedule.times) return null;
|
|
1674
|
-
const next = at + schedule.every * Math.max(1, Math.floor((now - at) / schedule.every) + 1);
|
|
1675
|
-
return schedule.until !== null && next > schedule.until ? null : next;
|
|
1676
|
-
}
|
|
1677
|
-
/**
|
|
1678
|
-
* Whether `principal` is the schedule's creator, as far as seeing and canceling
|
|
1679
|
-
* it goes. A principal ID is coarser than access (a repo's workflows share one,
|
|
1680
|
-
* and so do the proxies narrowing one token with `x-board-scope`), so it also
|
|
1681
|
-
* needs `post` there now, as it would to create it. Where it can't read, the
|
|
1682
|
-
* schedule is its own only if it was created without reading too, so a
|
|
1683
|
-
* principal ID shared with a caller that reads doesn't reach that caller's.
|
|
1684
|
-
* A board token that pins a profile owns only what was scheduled as it (`wroteAs`).
|
|
1685
|
-
*/
|
|
1686
|
-
const createdBy = (schedule, identity) => wroteAs(identity, {
|
|
1687
|
-
principal: schedule.as.principal.id,
|
|
1688
|
-
actor: schedule.as.actor.id
|
|
1689
|
-
}) && identity.principal.access.can("post", schedule.channel) && (schedule.blind || identity.principal.access.readable(schedule.channel));
|
|
1690
|
-
const scheduleView = (schedule, actors) => {
|
|
1691
|
-
const author = actors.byId[schedule.as.actor.id] ?? schedule.as.actor;
|
|
1692
|
-
return {
|
|
1693
|
-
id: scheduleRef(schedule.id),
|
|
1694
|
-
channel: schedule.channel,
|
|
1695
|
-
re: schedule.re === null ? null : ref(schedule.re),
|
|
1696
|
-
text: schedule.text,
|
|
1697
|
-
labels: { ...schedule.labels },
|
|
1698
|
-
noSync: schedule.noSync,
|
|
1699
|
-
attachments: schedule.attachments,
|
|
1700
|
-
first: new Date(schedule.first).toISOString(),
|
|
1701
|
-
every: schedule.every,
|
|
1702
|
-
until: schedule.until === null ? null : new Date(schedule.until).toISOString(),
|
|
1703
|
-
times: schedule.times,
|
|
1704
|
-
sent: schedule.sent,
|
|
1705
|
-
next: schedule.next === null ? null : new Date(schedule.next).toISOString(),
|
|
1706
|
-
last: schedule.last === null ? null : ref(schedule.last),
|
|
1707
|
-
state: schedule.canceled ? "canceled" : schedule.next === null ? "done" : "pending",
|
|
1708
|
-
canceled: schedule.canceled,
|
|
1709
|
-
by: schedule.as.author,
|
|
1710
|
-
author: {
|
|
1711
|
-
kind: author.kind,
|
|
1712
|
-
handle: author.handle,
|
|
1713
|
-
name: author.name,
|
|
1714
|
-
avatar: author.avatar
|
|
1715
|
-
},
|
|
1716
|
-
createdAt: schedule.createdAt
|
|
1717
|
-
};
|
|
1718
|
-
};
|
|
1719
|
-
const SYSTEM = deploymentIdentity("board:schedule", "schedule");
|
|
1720
|
-
/** A refusal (a 403, or a 404 for a thread the creator can no longer read) as null; anything else still throws. */
|
|
1721
|
-
const refused = (error) => {
|
|
1722
|
-
if (error instanceof HttpError && (error.status === 403 || error.status === 404)) return null;
|
|
1723
|
-
throw error;
|
|
1724
|
-
};
|
|
1725
|
-
/**
|
|
1726
|
-
* Scheduled messages: `schedule.created` arms the first send as an A2 timer, and
|
|
1727
|
-
* each `schedule.due` posts as the schedule's creator, then arms the next.
|
|
1728
|
-
*/
|
|
1729
|
-
function createSchedules(options) {
|
|
1730
|
-
let writes = null;
|
|
1731
|
-
let accessNow = null;
|
|
1732
|
-
/** Posts as `identity`, through what every post does: the middleware too. */
|
|
1733
|
-
let send = null;
|
|
1734
|
-
/** Vercel Queues delivers a timer only to the deployment that armed it, which runs its own code and access rules. */
|
|
1735
|
-
const deployment = process.env.VERCEL_DEPLOYMENT_ID || null;
|
|
1736
|
-
/**
|
|
1737
|
-
* Where this deployment's timers land: a session of its own on Vercel. A queue drains one session
|
|
1738
|
-
* at a time, and Vercel Queues drains it on the deployment that appended to it, so an earlier
|
|
1739
|
-
* deployment never drains the one that sends' timers, and can't drop them there.
|
|
1740
|
-
*/
|
|
1741
|
-
const sends = deployment === null ? SCHEDULES_SESSION : `${SCHEDULES_SESSION}:${deployment}`;
|
|
1742
|
-
/**
|
|
1743
|
-
* Arms send `n`, due at `at`: the whole way, or one hop toward it. A timer's name is its identity
|
|
1744
|
-
* in the queue, so arming the same send under the same name again adds nothing; only a hop's names
|
|
1745
|
-
* the hop, since a send waits through several.
|
|
1746
|
-
*/
|
|
1747
|
-
async function arm(name, id, n, at) {
|
|
1748
|
-
const hop = Math.max(Math.min(at, Date.now() + MAX_HOP_MS), Date.now());
|
|
1749
|
-
const named = name === "hop" ? `hop-${id}-${n}-${hop}` : `${name}-${id}-${n}`;
|
|
1750
|
-
await session.forSends.schedule(named, { at: new Date(hop) }, {
|
|
1751
|
-
type: "schedule.due",
|
|
1752
|
-
payload: {
|
|
1753
|
-
id,
|
|
1754
|
-
n,
|
|
1755
|
-
at
|
|
1756
|
-
}
|
|
1757
|
-
});
|
|
1758
|
-
}
|
|
1759
|
-
/** Appends to the schedules, once for each `key`, from a send in any session. */
|
|
1760
|
-
async function record(event, ...key) {
|
|
1761
|
-
await session.append({
|
|
1762
|
-
...event,
|
|
1763
|
-
id: await idempotentId("board-schedule-record", ...key)
|
|
1764
|
-
});
|
|
1765
|
-
}
|
|
1766
|
-
async function due(ctx) {
|
|
1767
|
-
if (!writes || !accessNow || !send) throw new Error("schedules used before the board bound them");
|
|
1768
|
-
const { id, n, at } = ctx.event.payload;
|
|
1769
|
-
const { state } = await session.state(schedulesReducer, { through: "latest" });
|
|
1770
|
-
const schedule = state.byId[id];
|
|
1771
|
-
if (deployment !== null && state.takeover !== null && state.takeover.deployment !== deployment) return;
|
|
1772
|
-
if (schedule && ctx.attempt > 1 && schedule.sent === n + 1 && schedule.next !== null) return arm("next", id, n + 1, schedule.next);
|
|
1773
|
-
if (!schedule || schedule.next !== at || schedule.sent !== n) return;
|
|
1774
|
-
if (Date.now() < at - EARLY_MS) return arm("hop", id, n, at);
|
|
1775
|
-
if (schedule.re !== null) {
|
|
1776
|
-
const root = await writes.reads.message(schedule.re, ctx.signal);
|
|
1777
|
-
if (!root || root.deleted) {
|
|
1778
|
-
await record({
|
|
1779
|
-
type: "schedule.canceled",
|
|
1780
|
-
payload: {
|
|
1781
|
-
id,
|
|
1782
|
-
by: SYSTEM.author,
|
|
1783
|
-
reason: "thread_deleted"
|
|
1784
|
-
}
|
|
1785
|
-
}, "ended", String(id));
|
|
1786
|
-
return;
|
|
1787
|
-
}
|
|
1788
|
-
}
|
|
1789
|
-
const access = await accessNow(schedule.as.principal);
|
|
1790
|
-
const target = schedule.re === null ? { channel: schedule.channel } : { re: schedule.re };
|
|
1791
|
-
const proofs = access && await authorizePost(writes, access, {
|
|
1792
|
-
...target,
|
|
1793
|
-
labels: schedule.labels
|
|
1794
|
-
}).catch(refused);
|
|
1795
|
-
if (!access || !proofs) {
|
|
1796
|
-
console.info(`[board] schedule s${id}'s creator can no longer post it in ${schedule.channel}`);
|
|
1797
|
-
await record({
|
|
1798
|
-
type: "schedule.canceled",
|
|
1799
|
-
payload: {
|
|
1800
|
-
id,
|
|
1801
|
-
by: SYSTEM.author,
|
|
1802
|
-
reason: "revoked"
|
|
1803
|
-
}
|
|
1804
|
-
}, "ended", String(id));
|
|
1805
|
-
return;
|
|
1806
|
-
}
|
|
1807
|
-
const input = {
|
|
1808
|
-
...schedule.re === null ? { channel: schedule.channel } : { re: ref(schedule.re) },
|
|
1809
|
-
id: await idempotentId("board-schedule", String(id), String(n)),
|
|
1810
|
-
text: schedule.text,
|
|
1811
|
-
labels: schedule.labels,
|
|
1812
|
-
noSync: schedule.noSync,
|
|
1813
|
-
...schedule.attachments.length ? { attachments: schedule.attachments.map((file) => file.id) } : {}
|
|
1814
|
-
};
|
|
1815
|
-
let posted;
|
|
1816
|
-
try {
|
|
1817
|
-
const sent = await send({
|
|
1818
|
-
...schedule.as,
|
|
1819
|
-
principal: {
|
|
1820
|
-
...schedule.as.principal,
|
|
1821
|
-
access
|
|
1822
|
-
}
|
|
1823
|
-
}, {
|
|
1824
|
-
via: {
|
|
1825
|
-
kind: "schedule",
|
|
1826
|
-
id
|
|
1827
|
-
},
|
|
1828
|
-
schedule: {
|
|
1829
|
-
id,
|
|
1830
|
-
n
|
|
1831
|
-
}
|
|
1832
|
-
}, input);
|
|
1833
|
-
posted = indexOf(sent.id);
|
|
1834
|
-
} catch (error) {
|
|
1835
|
-
if (!(error instanceof DroppedError)) throw error;
|
|
1836
|
-
console.info(`[board] the middleware dropped schedule s${id}: ${error.message}`);
|
|
1837
|
-
await record({
|
|
1838
|
-
type: "schedule.canceled",
|
|
1839
|
-
payload: {
|
|
1840
|
-
id,
|
|
1841
|
-
by: SYSTEM.author,
|
|
1842
|
-
reason: "dropped"
|
|
1843
|
-
}
|
|
1844
|
-
}, "ended", String(id));
|
|
1845
|
-
return;
|
|
1846
|
-
}
|
|
1847
|
-
const next = nextSend(schedule, n, at, Date.now());
|
|
1848
|
-
await record({
|
|
1849
|
-
type: "schedule.fired",
|
|
1850
|
-
payload: {
|
|
1851
|
-
id,
|
|
1852
|
-
n,
|
|
1853
|
-
message: posted,
|
|
1854
|
-
next
|
|
1855
|
-
}
|
|
1856
|
-
}, "fired", String(id), String(n));
|
|
1857
|
-
if (next !== null) await arm("next", id, n + 1, next);
|
|
1858
|
-
}
|
|
1859
|
-
/**
|
|
1860
|
-
* Arms each schedule's next send, as the schedule stands now, from the first schedule on: the
|
|
1861
|
-
* first deploy with this consumer arms every schedule from before it.
|
|
1862
|
-
*/
|
|
1863
|
-
const arming = consumer({
|
|
1864
|
-
contract: schedulesContract,
|
|
1865
|
-
name: "board-schedules",
|
|
1866
|
-
types: ["schedule.created"],
|
|
1867
|
-
lane: "schedules",
|
|
1868
|
-
backfill: true
|
|
1869
|
-
}).run(async (ctx) => {
|
|
1870
|
-
if (!options.scheduler) return;
|
|
1871
|
-
const { state } = await ctx.session.state(schedulesReducer, { through: "latest" });
|
|
1872
|
-
const schedule = state.byId[ctx.event.index];
|
|
1873
|
-
if (!schedule || schedule.next === null) return;
|
|
1874
|
-
await arm("first", schedule.id, schedule.sent, schedule.next);
|
|
1875
|
-
});
|
|
1876
|
-
/** Makes each due send, one schedule at a time. */
|
|
1877
|
-
const sending = consumer({
|
|
1878
|
-
contract: schedulesContract,
|
|
1879
|
-
name: "board-schedule-sends",
|
|
1880
|
-
types: ["schedule.due"],
|
|
1881
|
-
lane: ({ event }) => `schedule:${event.payload.id}`
|
|
1882
|
-
}).run(due);
|
|
1883
|
-
const server = createServer({
|
|
1884
|
-
contract: schedulesContract,
|
|
1885
|
-
...options.store ? { store: options.store } : {},
|
|
1886
|
-
...options.scheduler ? { scheduler: options.scheduler } : {},
|
|
1887
|
-
consumers: [arming, sending]
|
|
1888
|
-
});
|
|
1889
|
-
const session = Object.assign(server.session(SCHEDULES_SESSION), { forSends: server.session(sends) });
|
|
1890
|
-
const scheduled = options.scheduler !== void 0;
|
|
1891
|
-
/**
|
|
1892
|
-
* Makes this deployment the one that sends, unless it already is, and arms every pending
|
|
1893
|
-
* schedule's next send here, since the timers an earlier deployment armed only reach it. Each
|
|
1894
|
-
* instance arms them again, under the same names, so one created on an earlier deployment
|
|
1895
|
-
* after the takeover, or missed by a takeover that failed partway, still gets a timer here.
|
|
1896
|
-
*/
|
|
1897
|
-
async function takeOver() {
|
|
1898
|
-
if (deployment === null) return;
|
|
1899
|
-
const read = await session.state(schedulesReducer);
|
|
1900
|
-
let { state } = read;
|
|
1901
|
-
if (state.takeover?.deployment !== deployment) {
|
|
1902
|
-
await session.append({
|
|
1903
|
-
type: "schedule.takeover",
|
|
1904
|
-
payload: { deployment },
|
|
1905
|
-
id: await idempotentId("board-schedule-takeover", deployment, String(read.index))
|
|
1906
|
-
});
|
|
1907
|
-
state = (await session.state(schedulesReducer)).state;
|
|
1908
|
-
}
|
|
1909
|
-
const since = state.takeover.index;
|
|
1910
|
-
for (const schedule of Object.values(state.byId)) if (schedule.next !== null) await arm(`takeover-${since}`, schedule.id, schedule.sent, schedule.next);
|
|
1911
|
-
}
|
|
1912
|
-
/**
|
|
1913
|
-
* The first call on an instance starts the arming catching up, and doesn't wait: on the first
|
|
1914
|
-
* deploy with it, every schedule from before gets its next send armed here. The first call that
|
|
1915
|
-
* isn't a queue's delivery takes schedules over too: a deployment nobody visits any more still
|
|
1916
|
-
* gets its own timers, and those mustn't take schedules back from the one people reach.
|
|
1917
|
-
*/
|
|
1918
|
-
let catching = null;
|
|
1919
|
-
let taking = null;
|
|
1920
|
-
function catchUp(options) {
|
|
1921
|
-
if (!scheduled) return;
|
|
1922
|
-
if (!catching) {
|
|
1923
|
-
catching = session.consume(arming).catch((error) => {
|
|
1924
|
-
console.warn("[board] schedules are not caught up:", error.message);
|
|
1925
|
-
catching = null;
|
|
1926
|
-
});
|
|
1927
|
-
waitUntil(catching);
|
|
1928
|
-
}
|
|
1929
|
-
if (options.takeOver && !taking) {
|
|
1930
|
-
taking = takeOver().catch((error) => {
|
|
1931
|
-
console.warn("[board] schedules are not taken over:", error.message);
|
|
1932
|
-
taking = null;
|
|
1933
|
-
});
|
|
1934
|
-
waitUntil(taking);
|
|
1935
|
-
}
|
|
1936
|
-
}
|
|
1937
|
-
/** `visible`: which schedules the caller may see. */
|
|
1938
|
-
async function list(query, visible = () => true) {
|
|
1939
|
-
if (!writes) throw new Error("schedules used before the board bound them");
|
|
1940
|
-
const [{ state }, { state: actors }] = await Promise.all([session.state(schedulesReducer), writes.session.state(actorsReducer)]);
|
|
1941
|
-
return Object.values(state.byId).filter(visible).filter((s) => query.all ? true : s.next !== null).filter((s) => query.root === void 0 ? true : s.re === query.root).filter((s) => query.channel === void 0 ? true : s.channel === query.channel).filter((s) => query.by === void 0 ? true : s.as.actor.id === query.by || s.as.actor.handle.toLowerCase() === query.by.toLowerCase()).sort((a, b) => a.id - b.id).map((s) => scheduleView(s, actors));
|
|
1942
|
-
}
|
|
1943
|
-
return {
|
|
1944
|
-
server,
|
|
1945
|
-
session,
|
|
1946
|
-
catchUp,
|
|
1947
|
-
bind: (binding) => {
|
|
1948
|
-
writes = binding.writes;
|
|
1949
|
-
accessNow = binding.accessNow;
|
|
1950
|
-
send = binding.send;
|
|
1951
|
-
},
|
|
1952
|
-
list,
|
|
1953
|
-
/** The pending schedules that reply in the thread rooted at `root`. */
|
|
1954
|
-
forThread: (root) => list({ root }),
|
|
1955
|
-
async create(identity, body, attachments) {
|
|
1956
|
-
if (!writes) throw new Error("schedules used before the board bound them");
|
|
1957
|
-
if (!options.scheduler) throw new HttpError(501, "no_scheduler", "this board has no scheduler: pass `scheduler` to `a2()` to send later");
|
|
1958
|
-
const now = Date.now();
|
|
1959
|
-
const every = body.every === void 0 ? null : duration(body.every);
|
|
1960
|
-
if (every !== null && every < 6e4) throw badRequest("`every` is at least 1m");
|
|
1961
|
-
if (every !== null && every > 316224e5) throw badRequest("`every` is at most a year");
|
|
1962
|
-
const first = body.at !== void 0 ? Date.parse(body.at) : now + duration(body.in ?? body.every);
|
|
1963
|
-
if (first < now - 6e4) throw badRequest("`at` is in the past");
|
|
1964
|
-
const asked = body.until !== void 0 ? Date.parse(body.until) : body.for !== void 0 ? first + duration(body.for) : null;
|
|
1965
|
-
const expires = identity.principal.token !== void 0 ? identity.principal.expiresAt?.getTime() ?? null : null;
|
|
1966
|
-
if (expires !== null && first > expires) throw badRequest(`this token expires ${new Date(expires).toISOString()}, before the schedule's first send: schedule it with a credential that lasts`, "token_expires_first");
|
|
1967
|
-
const until = expires !== null && (asked === null || asked > expires) ? expires : asked;
|
|
1968
|
-
if (until !== null && until < first) throw badRequest("the schedule stops before its first send");
|
|
1969
|
-
if (first > now + 316224e5 || until !== null && until > now + 316224e5) throw badRequest("a schedule reaches at most a year out: its first send and its stop");
|
|
1970
|
-
const { state: known } = await writes.session.state(actorsReducer);
|
|
1971
|
-
const withoutEmails = replaceMentions(body.text, (t) => t.kind === "actor" && t.actor.includes("@") ? t.actor : null);
|
|
1972
|
-
const { unknown } = resolveMentions(withoutEmails, known, identity.actor, false, identity.principal.access.readsAll);
|
|
1973
|
-
let channel = body.channel;
|
|
1974
|
-
let re = null;
|
|
1975
|
-
if (body.re !== void 0) {
|
|
1976
|
-
const target = await writes.reads.message(body.re);
|
|
1977
|
-
if (!target || target.deleted) throw notFound(`message not found: #${body.re}`, "message_not_found");
|
|
1978
|
-
re = target.re ?? target.id;
|
|
1979
|
-
channel = target.channel;
|
|
1980
|
-
}
|
|
1981
|
-
const [row] = await session.append({
|
|
1982
|
-
type: "schedule.created",
|
|
1983
|
-
payload: {
|
|
1984
|
-
channel,
|
|
1985
|
-
re,
|
|
1986
|
-
text: body.text,
|
|
1987
|
-
labels: body.labels ?? {},
|
|
1988
|
-
noSync: body.noSync ?? false,
|
|
1989
|
-
...attachments.length ? { attachments } : {},
|
|
1990
|
-
first,
|
|
1991
|
-
every,
|
|
1992
|
-
until,
|
|
1993
|
-
times: body.times ?? null,
|
|
1994
|
-
as: {
|
|
1995
|
-
author: identity.author,
|
|
1996
|
-
principal: storedPrincipal(identity.principal),
|
|
1997
|
-
actor: identity.actor
|
|
1998
|
-
},
|
|
1999
|
-
...identity.principal.access.readable(channel) ? {} : { blind: true }
|
|
2000
|
-
}
|
|
2001
|
-
});
|
|
2002
|
-
const { state } = await session.state(schedulesReducer);
|
|
2003
|
-
const created = state.byId[row.index];
|
|
2004
|
-
if (created.next !== null) await arm("first", created.id, created.sent, created.next);
|
|
2005
|
-
const { state: actors } = await writes.session.state(actorsReducer);
|
|
2006
|
-
const schedule = scheduleView(created, actors);
|
|
2007
|
-
return unknown.length && identity.principal.access.readable(channel) ? {
|
|
2008
|
-
schedule,
|
|
2009
|
-
unknownMentions: unknown
|
|
2010
|
-
} : { schedule };
|
|
2011
|
-
},
|
|
2012
|
-
/**
|
|
2013
|
-
* Its creator may cancel it while they can post there, and so may `manage`
|
|
2014
|
-
* in its channel. Anyone else gets 403 where they can read it, and 404
|
|
2015
|
-
* where they can't. Canceling twice is a no-op.
|
|
2016
|
-
*/
|
|
2017
|
-
async cancel(identity, id) {
|
|
2018
|
-
if (!writes) throw new Error("schedules used before the board bound them");
|
|
2019
|
-
const { state } = await session.state(schedulesReducer);
|
|
2020
|
-
const schedule = state.byId[id];
|
|
2021
|
-
const missing = () => notFound(`schedule not found: s${id}`, "schedule_not_found");
|
|
2022
|
-
if (!schedule) throw missing();
|
|
2023
|
-
if (!createdBy(schedule, identity)) authorize(identity.principal.access, "manage", schedule.channel, missing);
|
|
2024
|
-
const canceled = schedule.next !== null;
|
|
2025
|
-
if (canceled) await session.append({
|
|
2026
|
-
type: "schedule.canceled",
|
|
2027
|
-
payload: {
|
|
2028
|
-
id,
|
|
2029
|
-
by: identity.author,
|
|
2030
|
-
reason: "canceled"
|
|
2031
|
-
}
|
|
2032
|
-
});
|
|
2033
|
-
const { state: after } = await session.state(schedulesReducer);
|
|
2034
|
-
const { state: actors } = await writes.session.state(actorsReducer);
|
|
2035
|
-
return {
|
|
2036
|
-
schedule: scheduleView(after.byId[id], actors),
|
|
2037
|
-
canceled
|
|
2038
|
-
};
|
|
2039
|
-
}
|
|
2040
|
-
};
|
|
2041
|
-
}
|
|
2042
|
-
/** How long a pulled match is its puller's before someone may pull it again. */
|
|
2043
|
-
const LEASE_MS = 3e5;
|
|
2044
|
-
/** After an error, a match waits 1 second, doubling to 30. */
|
|
2045
|
-
const retryDelay = (attempts) => Math.min(3e4, 1e3 * 2 ** (attempts - 1));
|
|
2046
|
-
/**
|
|
2047
|
-
* Sweeps fall on the minute: a registrant has at most one timer a minute, however many matches it
|
|
2048
|
-
* pulls. A sweep wakes it for leases that ran out, and for a wake-up that didn't arrive.
|
|
2049
|
-
*/
|
|
2050
|
-
const SWEEP_MS = 6e4;
|
|
2051
|
-
/** The sweep that covers `at`: the next minute at least a second after it, since a timer may land up to a second early. */
|
|
2052
|
-
const sweepFor = (at) => Math.ceil((at + 1e3) / SWEEP_MS) * SWEEP_MS;
|
|
2053
|
-
/** The longest a registrant whose wake-ups don't get there waits for the next one. */
|
|
2054
|
-
const WAKE_BACKOFF_MAX_MS = 36e5;
|
|
2055
|
-
/**
|
|
2056
|
-
* After `failures` wake-ups in a row that didn't get there, how long until the next: a minute,
|
|
2057
|
-
* doubling to an hour. Until then a match only queues.
|
|
2058
|
-
*/
|
|
2059
|
-
const wakeBackoff = (failures) => Math.min(WAKE_BACKOFF_MAX_MS, SWEEP_MS * 2 ** (failures - 1));
|
|
2060
|
-
/** The queue of platform events a registrant pushed for sync key `key`. */
|
|
2061
|
-
const inboxQueue = (key) => `@inbox:${key}`;
|
|
2062
|
-
const queueKey = (queue, thread) => `${queue}\u001f${thread}`;
|
|
2063
|
-
function remove(state, id) {
|
|
2064
|
-
const found = state.pending[id];
|
|
2065
|
-
if (!found) return;
|
|
2066
|
-
delete state.pending[id];
|
|
2067
|
-
const key = queueKey(found.queue, found.thread);
|
|
2068
|
-
const rest = (state.queues[key] ?? []).filter((queued) => queued !== id);
|
|
2069
|
-
if (rest.length > 0) state.queues[key] = rest;
|
|
2070
|
-
else delete state.queues[key];
|
|
2071
|
-
}
|
|
2072
|
-
function foldQueue(state, event) {
|
|
2073
|
-
switch (event.type) {
|
|
2074
|
-
case "watch.matched": {
|
|
2075
|
-
const { watcher, sync, inbox, thread } = event.payload;
|
|
2076
|
-
const queue = watcher ?? (sync ? "@sync" : inbox !== void 0 ? inboxQueue(inbox) : void 0);
|
|
2077
|
-
if (queue === void 0 || state.pending[event.id]) return state;
|
|
2078
|
-
state.pending[event.id] = {
|
|
2079
|
-
id: event.id,
|
|
2080
|
-
queue,
|
|
2081
|
-
thread,
|
|
2082
|
-
event: event.payload.event,
|
|
2083
|
-
attempts: 0,
|
|
2084
|
-
lease: null,
|
|
2085
|
-
retryAt: null
|
|
2086
|
-
};
|
|
2087
|
-
(state.queues[queueKey(queue, thread)] ??= []).push(event.id);
|
|
2088
|
-
return state;
|
|
2089
|
-
}
|
|
2090
|
-
case "watch.leased": {
|
|
2091
|
-
const found = state.pending[event.payload.matched];
|
|
2092
|
-
if (found && !found.lease) found.lease = {
|
|
2093
|
-
id: event.payload.lease,
|
|
2094
|
-
until: event.payload.until
|
|
2095
|
-
};
|
|
2096
|
-
return state;
|
|
2097
|
-
}
|
|
2098
|
-
case "watch.acked": {
|
|
2099
|
-
const found = state.pending[event.payload.matched];
|
|
2100
|
-
if (!found || found.lease?.id !== event.payload.lease) return state;
|
|
2101
|
-
if (event.payload.error === void 0) {
|
|
2102
|
-
remove(state, found.id);
|
|
2103
|
-
return state;
|
|
2104
|
-
}
|
|
2105
|
-
found.attempts += 1;
|
|
2106
|
-
found.lease = null;
|
|
2107
|
-
found.retryAt = event.payload.retryAt ?? null;
|
|
2108
|
-
return state;
|
|
2109
|
-
}
|
|
2110
|
-
case "watch.expired": {
|
|
2111
|
-
const found = state.pending[event.payload.matched];
|
|
2112
|
-
if (!found || found.lease?.id !== event.payload.lease) return state;
|
|
2113
|
-
found.attempts += 1;
|
|
2114
|
-
found.lease = null;
|
|
2115
|
-
return state;
|
|
2116
|
-
}
|
|
2117
|
-
case "watch.retry": {
|
|
2118
|
-
const found = state.pending[event.payload.matched];
|
|
2119
|
-
if (found) found.retryAt = null;
|
|
2120
|
-
return state;
|
|
2121
|
-
}
|
|
2122
|
-
case "watch.armed":
|
|
2123
|
-
if (!state.sweeps.includes(event.payload.at)) state.sweeps.push(event.payload.at);
|
|
2124
|
-
return state;
|
|
2125
|
-
case "watch.due": {
|
|
2126
|
-
const { sweep } = event.payload;
|
|
2127
|
-
if (sweep !== void 0) state.sweeps = state.sweeps.filter((at) => at !== sweep);
|
|
2128
|
-
return state;
|
|
2129
|
-
}
|
|
2130
|
-
case "watch.failed":
|
|
2131
|
-
case "watch.skipped":
|
|
2132
|
-
remove(state, event.payload.matched);
|
|
2133
|
-
return state;
|
|
2134
|
-
case "watch.unreachable":
|
|
2135
|
-
state.unreachable = {
|
|
2136
|
-
failures: event.payload.failures,
|
|
2137
|
-
until: event.payload.until
|
|
2138
|
-
};
|
|
2139
|
-
return state;
|
|
2140
|
-
case "watch.reachable":
|
|
2141
|
-
state.unreachable = null;
|
|
2142
|
-
return state;
|
|
2143
|
-
default: return state;
|
|
2144
|
-
}
|
|
2145
|
-
}
|
|
2146
|
-
const queueReducer = reducer({
|
|
2147
|
-
contract: watchContract,
|
|
2148
|
-
name: "board.watch-queue.v4",
|
|
2149
|
-
initialState: {
|
|
2150
|
-
queues: {},
|
|
2151
|
-
pending: {},
|
|
2152
|
-
sweeps: [],
|
|
2153
|
-
unreachable: null
|
|
2154
|
-
}
|
|
2155
|
-
}).fold(foldQueue);
|
|
2156
|
-
const describe$1 = (error) => ((error instanceof Error ? error.message : String(error)) || "unknown error").slice(0, 500);
|
|
2157
|
-
/**
|
|
2158
|
-
* Whether `access` may see `event` now, as it was matched: a message's channel, or every channel for
|
|
2159
|
-
* none. Sync's queue gets what its registrant may sync, since it speaks for platform users there.
|
|
2160
|
-
*/
|
|
2161
|
-
function readable(access, event, queue) {
|
|
2162
|
-
const channel = event.message?.channel;
|
|
2163
|
-
if (queue === "@sync") return channel === void 0 ? access.everywhere("sync") : access.can("sync", channel);
|
|
2164
|
-
return channel === void 0 ? access.readsAll : access.readable(channel);
|
|
2165
|
-
}
|
|
2166
|
-
/** An append that holds an event ID already in the log: another pull's lease. */
|
|
2167
|
-
const taken = (error) => error instanceof A2Error && error.code === "PARTIAL_DUPLICATE_BATCH";
|
|
2168
|
-
/** Whether a match is free to pull now: no one holds it, and its wait after an error is over. A lease or wait whose time has passed counts as over. */
|
|
2169
|
-
const free = (found, now) => !(found.lease && found.lease.until > now) && !(found.retryAt !== null && found.retryAt > now);
|
|
2170
|
-
/** Whether the registrant has anything to pull now. */
|
|
2171
|
-
const hasWork = (state, now) => Object.values(state.queues).some((ids) => free(state.pending[ids[0]], now));
|
|
2172
|
-
/**
|
|
2173
|
-
* Hands out what the registrant's watchers and sync may run now: each queue's oldest match, if it's
|
|
2174
|
-
* free, leased to this pull. The inbox's queues are `pullInbox`'s.
|
|
2175
|
-
*/
|
|
2176
|
-
async function pull(session, options) {
|
|
2177
|
-
return (await lease(session, {
|
|
2178
|
-
...options,
|
|
2179
|
-
queues: (queue) => !queue.startsWith("@inbox:"),
|
|
2180
|
-
visible: (event, queue) => readable(options.access, event, queue)
|
|
2181
|
-
})).map(({ id, queue, thread, lease, attempt, event }) => ({
|
|
2182
|
-
id,
|
|
2183
|
-
watcher: queue,
|
|
2184
|
-
thread,
|
|
2185
|
-
lease,
|
|
2186
|
-
attempt,
|
|
2187
|
-
event
|
|
2188
|
-
}));
|
|
2189
|
-
}
|
|
2190
|
-
/**
|
|
2191
|
-
* Hands out the platform events the registrant pushed for sync key `key`: each platform thread's
|
|
2192
|
-
* oldest, if it's free, while the registrant may still sync somewhere.
|
|
2193
|
-
*/
|
|
2194
|
-
function pullInbox(session, key, options) {
|
|
2195
|
-
const queue = inboxQueue(key);
|
|
2196
|
-
return lease(session, {
|
|
2197
|
-
...options,
|
|
2198
|
-
queues: (name) => name === queue,
|
|
2199
|
-
visible: () => options.access.anywhere("sync")
|
|
2200
|
-
});
|
|
2201
|
-
}
|
|
2202
|
-
/**
|
|
2203
|
-
* Leases what's free in the queues `queues` picks: each one's oldest item, which `visible` says
|
|
2204
|
-
* its registrant may still have. What the pull changes goes in one append, and one read after
|
|
2205
|
-
* tells which leases are this pull's: two pulls at once derive the same lease ID for a try, and
|
|
2206
|
-
* only one lands.
|
|
2207
|
-
*/
|
|
2208
|
-
async function lease(session, options) {
|
|
2209
|
-
const { state } = await session.state(queueReducer);
|
|
2210
|
-
const events = state.unreachable ? [{
|
|
2211
|
-
type: "watch.reachable",
|
|
2212
|
-
payload: { by: "pull" }
|
|
2213
|
-
}] : [];
|
|
2214
|
-
const offered = [];
|
|
2215
|
-
for (const ids of Object.values(state.queues)) {
|
|
2216
|
-
if (offered.length >= options.limit) break;
|
|
2217
|
-
const head = state.pending[ids[0]];
|
|
2218
|
-
if (!options.queues(head.queue) || !free(head, options.now)) continue;
|
|
2219
|
-
let attempts = head.attempts;
|
|
2220
|
-
if (head.lease) {
|
|
2221
|
-
events.push({
|
|
2222
|
-
type: "watch.expired",
|
|
2223
|
-
payload: {
|
|
2224
|
-
matched: head.id,
|
|
2225
|
-
lease: head.lease.id
|
|
2226
|
-
}
|
|
2227
|
-
});
|
|
2228
|
-
attempts += 1;
|
|
2229
|
-
if (attempts >= 5) {
|
|
2230
|
-
events.push(failure(head, `its lease ran out ${attempts} times`));
|
|
2231
|
-
continue;
|
|
2232
|
-
}
|
|
2233
|
-
}
|
|
2234
|
-
if (!options.visible(head.event, head.queue)) {
|
|
2235
|
-
events.push({
|
|
2236
|
-
type: "watch.skipped",
|
|
2237
|
-
payload: {
|
|
2238
|
-
matched: head.id,
|
|
2239
|
-
reason: "its registrant can't have it anymore"
|
|
2240
|
-
}
|
|
2241
|
-
});
|
|
2242
|
-
continue;
|
|
2243
|
-
}
|
|
2244
|
-
const lease = randomBytes(16).toString("hex");
|
|
2245
|
-
events.push({
|
|
2246
|
-
type: "watch.leased",
|
|
2247
|
-
id: await idempotentId("board-lease", head.id, String(attempts)),
|
|
2248
|
-
payload: {
|
|
2249
|
-
matched: head.id,
|
|
2250
|
-
lease,
|
|
2251
|
-
until: options.now + LEASE_MS
|
|
2252
|
-
}
|
|
2253
|
-
});
|
|
2254
|
-
offered.push({
|
|
2255
|
-
head,
|
|
2256
|
-
lease,
|
|
2257
|
-
attempt: attempts
|
|
2258
|
-
});
|
|
2259
|
-
}
|
|
2260
|
-
if (events.length === 0) return [];
|
|
2261
|
-
await session.append(...events).catch(async (error) => {
|
|
2262
|
-
if (!taken(error)) throw error;
|
|
2263
|
-
for (const event of events) await session.append(event).catch((one) => {
|
|
2264
|
-
if (!taken(one)) throw one;
|
|
2265
|
-
});
|
|
2266
|
-
});
|
|
2267
|
-
if (offered.length === 0) return [];
|
|
2268
|
-
const { state: after } = await session.state(queueReducer);
|
|
2269
|
-
const handed = offered.filter(({ head, lease }) => after.pending[head.id]?.lease?.id === lease);
|
|
2270
|
-
if (handed.length > 0 && options.timers) await arm(session, after, options.now + LEASE_MS);
|
|
2271
|
-
return handed.map(({ head, lease, attempt }) => ({
|
|
2272
|
-
id: head.id,
|
|
2273
|
-
queue: head.queue,
|
|
2274
|
-
thread: head.thread,
|
|
2275
|
-
lease,
|
|
2276
|
-
attempt,
|
|
2277
|
-
event: head.event
|
|
2278
|
-
}));
|
|
2279
|
-
}
|
|
2280
|
-
/** Records how a pulled match went: done, skipped, or an error that waits, then tries again. */
|
|
2281
|
-
async function ack(session, id, body, options) {
|
|
2282
|
-
const { state } = await session.state(queueReducer);
|
|
2283
|
-
const found = state.pending[id];
|
|
2284
|
-
if (!found) return "gone";
|
|
2285
|
-
if (found.lease?.id !== body.lease) return "stale";
|
|
2286
|
-
if (body.skip) {
|
|
2287
|
-
await session.append({
|
|
2288
|
-
type: "watch.skipped",
|
|
2289
|
-
payload: {
|
|
2290
|
-
matched: id,
|
|
2291
|
-
reason: "its board skipped it"
|
|
2292
|
-
}
|
|
2293
|
-
});
|
|
2294
|
-
return "acked";
|
|
2295
|
-
}
|
|
2296
|
-
if (body.error === void 0) {
|
|
2297
|
-
await session.append({
|
|
2298
|
-
type: "watch.acked",
|
|
2299
|
-
payload: {
|
|
2300
|
-
matched: id,
|
|
2301
|
-
lease: body.lease
|
|
2302
|
-
}
|
|
2303
|
-
});
|
|
2304
|
-
return "acked";
|
|
2305
|
-
}
|
|
2306
|
-
const attempts = found.attempts + 1;
|
|
2307
|
-
if (attempts >= 5) {
|
|
2308
|
-
await session.append({
|
|
2309
|
-
type: "watch.acked",
|
|
2310
|
-
payload: {
|
|
2311
|
-
matched: id,
|
|
2312
|
-
lease: body.lease,
|
|
2313
|
-
error: body.error
|
|
2314
|
-
}
|
|
2315
|
-
}, failure(found, body.error));
|
|
2316
|
-
return "acked";
|
|
2317
|
-
}
|
|
2318
|
-
const retryAt = options.now + retryDelay(attempts);
|
|
2319
|
-
await session.append({
|
|
2320
|
-
type: "watch.acked",
|
|
2321
|
-
payload: {
|
|
2322
|
-
matched: id,
|
|
2323
|
-
lease: body.lease,
|
|
2324
|
-
error: body.error,
|
|
2325
|
-
retryAt
|
|
2326
|
-
}
|
|
2327
|
-
});
|
|
2328
|
-
if (options.timers) await session.schedule(`retry:${id}:${attempts}`, { at: new Date(retryAt) }, {
|
|
2329
|
-
type: "watch.due",
|
|
2330
|
-
payload: {
|
|
2331
|
-
matched: id,
|
|
2332
|
-
retry: true
|
|
2333
|
-
}
|
|
2334
|
-
});
|
|
2335
|
-
return "acked";
|
|
2336
|
-
}
|
|
2337
|
-
/**
|
|
2338
|
-
* Sets a sweep for `at`, unless one is set already. The sweep runs on the minute after it, so the
|
|
2339
|
-
* leases of a minute share one timer. Its timer goes first: a sweep recorded without one would
|
|
2340
|
-
* never run, and a timer set twice under one name lands once.
|
|
2341
|
-
*/
|
|
2342
|
-
async function arm(session, state, at) {
|
|
2343
|
-
const sweep = sweepFor(at);
|
|
2344
|
-
if (state.sweeps.includes(sweep)) return;
|
|
2345
|
-
await session.schedule(`sweep:${sweep}`, { at: new Date(sweep) }, {
|
|
2346
|
-
type: "watch.due",
|
|
2347
|
-
payload: { sweep }
|
|
2348
|
-
});
|
|
2349
|
-
await session.append({
|
|
2350
|
-
type: "watch.armed",
|
|
2351
|
-
id: await idempotentId("board-sweep", String(sweep)),
|
|
2352
|
-
payload: { at: sweep }
|
|
2353
|
-
});
|
|
2354
|
-
}
|
|
2355
|
-
/**
|
|
2356
|
-
* A timer came due: an error's wait is over, or a sweep. Returns the queue after it, for its
|
|
2357
|
-
* consumer to tell whether the registrant has something to pull.
|
|
2358
|
-
*/
|
|
2359
|
-
async function due(session, payload) {
|
|
2360
|
-
const { state } = await session.state(queueReducer);
|
|
2361
|
-
const found = payload.matched === void 0 ? void 0 : state.pending[payload.matched];
|
|
2362
|
-
if (!payload.retry || !found || found.retryAt === null) return state;
|
|
2363
|
-
await session.append({
|
|
2364
|
-
type: "watch.retry",
|
|
2365
|
-
payload: { matched: found.id }
|
|
2366
|
-
});
|
|
2367
|
-
return (await session.state(queueReducer)).state;
|
|
2368
|
-
}
|
|
2369
|
-
/** Gives up on a match: `watch.failed`, said in the logs too. */
|
|
2370
|
-
function failure(found, error) {
|
|
2371
|
-
console.error(`[board] a registrant's ${found.queue} gave up on an item after 5 tries:`, error);
|
|
2372
|
-
return {
|
|
2373
|
-
type: "watch.failed",
|
|
2374
|
-
payload: {
|
|
2375
|
-
matched: found.id,
|
|
2376
|
-
thread: found.thread,
|
|
2377
|
-
error: describe$1(error)
|
|
2378
|
-
}
|
|
2379
|
-
};
|
|
2380
|
-
}
|
|
2381
|
-
//#endregion
|
|
2382
|
-
//#region src/server/watch.ts
|
|
2383
|
-
const ID = /^[a-z0-9][a-z0-9_-]{0,63}$/;
|
|
2384
|
-
/** The events a tail shows, receipts included for `--all`: each concerns a message, and carries its thread for the lane. */
|
|
2385
|
-
const WATCHED = [
|
|
2386
|
-
"message.posted",
|
|
2387
|
-
"message.edited",
|
|
2388
|
-
"message.deleted",
|
|
2389
|
-
"reaction.added",
|
|
2390
|
-
"reaction.removed",
|
|
2391
|
-
"labels.changed",
|
|
2392
|
-
"message.sync_failed",
|
|
2393
|
-
"message.synced",
|
|
2394
|
-
"message.files_synced",
|
|
2395
|
-
"thread.synced"
|
|
2396
|
-
];
|
|
2397
|
-
/** Receipts: only a `--all` tail shows them. */
|
|
2398
|
-
const RECEIPTS = /* @__PURE__ */ new Set(["message.synced", "message.files_synced"]);
|
|
2399
|
-
/**
|
|
2400
|
-
* What a registrant's sync gets, in every channel where it may sync: what it delivers to platforms,
|
|
2401
|
-
* and a thread's new targets. A tail never shows `thread.synced`, so no watcher gets it.
|
|
2402
|
-
*/
|
|
2403
|
-
const SYNCED = /* @__PURE__ */ new Set([
|
|
2404
|
-
"message.posted",
|
|
2405
|
-
"message.edited",
|
|
2406
|
-
"message.deleted",
|
|
2407
|
-
"reaction.added",
|
|
2408
|
-
"reaction.removed",
|
|
2409
|
-
"labels.changed",
|
|
2410
|
-
"thread.synced"
|
|
2411
|
-
]);
|
|
2412
|
-
/** Whether a match waits in a registrant's queue for it to pull, as opposed to a config watcher's, which runs here. */
|
|
2413
|
-
const queued = (payload) => payload.watcher !== void 0 || payload.sync === true || payload.inbox !== void 0;
|
|
2414
|
-
/**
|
|
2415
|
-
* A2 dead-letters an event after 10 failures, and a dead letter stops its
|
|
2416
|
-
* lane, which is the thread's: the watcher would never run on that thread
|
|
2417
|
-
* again. So `run` gets a few tries, then the failure is recorded and the
|
|
2418
|
-
* thread moves on.
|
|
2419
|
-
*/
|
|
2420
|
-
const RUN_ATTEMPTS = 5;
|
|
2421
|
-
/**
|
|
2422
|
-
* A run that's killed (a timeout, out of memory) never throws. A2 counts it
|
|
2423
|
-
* toward the 10 failures when the next attempt takes over, and dead-letters
|
|
2424
|
-
* the event at that takeover instead of running it: the 10th attempt is the
|
|
2425
|
-
* last one a watcher sees. Throws give up at RUN_ATTEMPTS, so getting this far
|
|
2426
|
-
* means runs keep dying, and the 10th records the failure without running.
|
|
2427
|
-
*/
|
|
2428
|
-
const KILLED_ATTEMPTS = 10;
|
|
2429
|
-
/** Tries at a wake-up before it's left to the next match or sweep, well short of A2's dead letter. */
|
|
2430
|
-
const WAKE_TRIES = 3;
|
|
2431
|
-
const describe = (error) => ((error instanceof Error ? error.message : String(error)) || "unknown error").slice(0, 500);
|
|
2432
|
-
/**
|
|
2433
|
-
* One match, on its thread's lane: `run`, retried by A2 while it fails, then
|
|
2434
|
-
* given up on (recorded as `watch.failed`) so the thread's next event runs.
|
|
2435
|
-
*/
|
|
2436
|
-
async function runMatch(input) {
|
|
2437
|
-
const { watcher, match, attempt } = input;
|
|
2438
|
-
const event = match.payload.event;
|
|
2439
|
-
const giveUp = async (error) => {
|
|
2440
|
-
console.error(`[board] watcher ${watcher.id} gave up on event #${event.cursor} after ${attempt} tries:`, error);
|
|
2441
|
-
await input.record({
|
|
2442
|
-
matched: match.id,
|
|
2443
|
-
thread: match.payload.thread,
|
|
2444
|
-
error
|
|
2445
|
-
});
|
|
2446
|
-
};
|
|
2447
|
-
const early = !afterRetry(attempt);
|
|
2448
|
-
if (early && attempt >= KILLED_ATTEMPTS) return giveUp(`its run was cut short ${attempt - 1} times (a timeout, or out of memory)`);
|
|
2449
|
-
try {
|
|
2450
|
-
await watcher.run(event);
|
|
2451
|
-
} catch (error) {
|
|
2452
|
-
if (!early || attempt < RUN_ATTEMPTS) throw error;
|
|
2453
|
-
await giveUp(describe(error));
|
|
2454
|
-
}
|
|
2455
|
-
}
|
|
2456
|
-
/** A watcher writes as `board:watch:<id>`, and its own writes never wake it. */
|
|
2457
|
-
const actorOf = (id) => `board:watch:${id}`;
|
|
2458
|
-
/** `watch:@<principal>`: everything one registrant's watchers matched, queued for it to pull. */
|
|
2459
|
-
const registrantSession = (owner) => watchSession(`@${owner}`);
|
|
2460
|
-
/**
|
|
2461
|
-
* Watchers: a board-contract consumer matches each event against every
|
|
2462
|
-
* watcher's filters, the way a tail does, and appends what matched to that
|
|
2463
|
-
* watcher's session, where `run` happens on the thread's lane.
|
|
2464
|
-
*/
|
|
2465
|
-
function createWatchers(options) {
|
|
2466
|
-
const watchers = Object.entries(options.watch).map(([id, watcher]) => {
|
|
2467
|
-
if (!ID.test(id)) throw new Error(`watch: ids use lowercase letters, numbers, - and _, got: ${id}`);
|
|
2468
|
-
return {
|
|
2469
|
-
id,
|
|
2470
|
-
...compileWatcher(id, watcher)
|
|
2471
|
-
};
|
|
2472
|
-
});
|
|
2473
|
-
const byId = new Map(watchers.map((watcher) => [watcher.id, watcher]));
|
|
2474
|
-
let reads = null;
|
|
2475
|
-
/** Runs a watcher on a board event it matched, one thread at a time. */
|
|
2476
|
-
const runner = consumer({
|
|
2477
|
-
contract: watchContract,
|
|
2478
|
-
name: "board-watch",
|
|
2479
|
-
types: ["watch.matched"],
|
|
2480
|
-
lane: ({ event }) => `thread:${event.payload.thread}`
|
|
2481
|
-
}).run(async (ctx) => {
|
|
2482
|
-
const watcher = byId.get(ctx.session.id.slice(6));
|
|
2483
|
-
if (!watcher) return;
|
|
2484
|
-
await runMatch({
|
|
2485
|
-
watcher: {
|
|
2486
|
-
id: watcher.id,
|
|
2487
|
-
run: (event) => options.run(watcher.id, event, ctx.event.id, ctx.attempt)
|
|
2488
|
-
},
|
|
2489
|
-
match: ctx.event,
|
|
2490
|
-
attempt: ctx.attempt,
|
|
2491
|
-
record: (payload) => ctx.session.append(`failed:${ctx.event.id}`, {
|
|
2492
|
-
type: "watch.failed",
|
|
2493
|
-
payload
|
|
2494
|
-
})
|
|
2495
|
-
});
|
|
2496
|
-
});
|
|
2497
|
-
/**
|
|
2498
|
-
* Wakes a registrant's board when it has something to pull: a new match, a wait after an error
|
|
2499
|
-
* that's over, or a sweep that finds a lease ran out. A registrant's wake-ups go one at a time,
|
|
2500
|
-
* and only when there's something to pull: its board pulls until nothing's left, so a burst of
|
|
2501
|
-
* matches wakes it once. One that doesn't get there waits a minute for the next, doubling to an
|
|
2502
|
-
* hour while they keep failing, until its board answers one, pulls, or registers.
|
|
2503
|
-
*/
|
|
2504
|
-
const waker = consumer({
|
|
2505
|
-
contract: watchContract,
|
|
2506
|
-
name: "board-wake",
|
|
2507
|
-
types: ["watch.matched", "watch.due"],
|
|
2508
|
-
lane: ({ event }) => "thread" in event.payload && (!queued(event.payload) || event.payload.inbox !== void 0) ? null : "wake"
|
|
2509
|
-
}).run(async (ctx) => {
|
|
2510
|
-
const key = ctx.session.id.slice(6);
|
|
2511
|
-
const registered = options.registered;
|
|
2512
|
-
if (!key.startsWith("@") || !registered) return;
|
|
2513
|
-
if (ctx.event.type === "watch.matched" && (!queued(ctx.event.payload) || ctx.event.payload.inbox !== void 0)) return;
|
|
2514
|
-
const queue = server.session(ctx.session.id);
|
|
2515
|
-
try {
|
|
2516
|
-
const state = ctx.event.type === "watch.due" ? await due(queue, ctx.event.payload) : (await queue.state(queueReducer)).state;
|
|
2517
|
-
if (!hasWork(state, Date.now())) return;
|
|
2518
|
-
const registration = (await registered.state()).byOwner[key.slice(1)];
|
|
2519
|
-
if (!registration || registration.url === null) return;
|
|
2520
|
-
const { url } = registration;
|
|
2521
|
-
const now = Date.now();
|
|
2522
|
-
if (state.unreachable && state.unreachable.until > now) return;
|
|
2523
|
-
const woken = await registered.wake({
|
|
2524
|
-
...registration,
|
|
2525
|
-
url
|
|
2526
|
-
});
|
|
2527
|
-
if (woken.reached) {
|
|
2528
|
-
if (state.unreachable) await queue.append({
|
|
2529
|
-
type: "watch.reachable",
|
|
2530
|
-
payload: { by: "wake" }
|
|
2531
|
-
});
|
|
2532
|
-
return;
|
|
2533
|
-
}
|
|
2534
|
-
const failures = (state.unreachable?.failures ?? 0) + 1;
|
|
2535
|
-
const until = now + wakeBackoff(failures);
|
|
2536
|
-
if (failures === 1) console.error(`[board] couldn't wake ${url}: ${woken.why}`);
|
|
2537
|
-
if (failures === 2) console.error(`[board] couldn't wake ${url} again (${woken.why}): trying less often, up to once an hour, until it answers, pulls, or registers`);
|
|
2538
|
-
if (options.scheduler) await arm(queue, state, until);
|
|
2539
|
-
await queue.append({
|
|
2540
|
-
type: "watch.unreachable",
|
|
2541
|
-
payload: {
|
|
2542
|
-
failures,
|
|
2543
|
-
until,
|
|
2544
|
-
why: woken.why.slice(0, 200) || "unknown error"
|
|
2545
|
-
}
|
|
2546
|
-
});
|
|
2547
|
-
} catch (error) {
|
|
2548
|
-
if (ctx.attempt < WAKE_TRIES) throw error;
|
|
2549
|
-
console.error(`[board] couldn't wake the board of ${key.slice(1)}:`, error.message);
|
|
2550
|
-
}
|
|
2551
|
-
});
|
|
2552
|
-
const server = createServer({
|
|
2553
|
-
contract: watchContract,
|
|
2554
|
-
...options.store ? { store: options.store } : {},
|
|
2555
|
-
...options.scheduler ? { scheduler: options.scheduler } : {},
|
|
2556
|
-
consumers: [runner, waker]
|
|
2557
|
-
});
|
|
2558
|
-
const configured = watchers.map((watcher) => ({
|
|
2559
|
-
...watcher,
|
|
2560
|
-
actor: actorOf(watcher.id)
|
|
2561
|
-
}));
|
|
2562
|
-
const compiled = /* @__PURE__ */ new Map();
|
|
2563
|
-
function compiledFor(registration) {
|
|
2564
|
-
const version = `${registration.hash}\u001f${JSON.stringify(registration.principal)}`;
|
|
2565
|
-
const hit = compiled.get(registration.owner);
|
|
2566
|
-
if (hit?.version === version) return hit.candidates;
|
|
2567
|
-
const candidates = [];
|
|
2568
|
-
for (const [id, spec] of Object.entries(registration.watch)) try {
|
|
2569
|
-
candidates.push({
|
|
2570
|
-
...compileWatcher(id, spec),
|
|
2571
|
-
id,
|
|
2572
|
-
actor: `${registration.owner}+${id.toLowerCase()}`,
|
|
2573
|
-
registration
|
|
2574
|
-
});
|
|
2575
|
-
} catch (error) {
|
|
2576
|
-
console.error(`[board] skipping a watcher ${registration.owner} registered:`, error.message);
|
|
2577
|
-
}
|
|
2578
|
-
compiled.set(registration.owner, {
|
|
2579
|
-
version,
|
|
2580
|
-
candidates
|
|
2581
|
-
});
|
|
2582
|
-
return candidates;
|
|
2583
|
-
}
|
|
2584
|
-
async function registrations() {
|
|
2585
|
-
return options.registered ? Object.values((await options.registered.state()).byOwner) : [];
|
|
2586
|
-
}
|
|
2587
|
-
/** Matches one board event; the message before or after it must match, as in a tail. */
|
|
2588
|
-
async function dispatch(ctx) {
|
|
2589
|
-
const event = ctx.event;
|
|
2590
|
-
const through = event.index - 1;
|
|
2591
|
-
const [messages, { state: actors }] = await Promise.all([messagesBefore(event, ctx.signal), ctx.session.state(actorsReducer, { through })]);
|
|
2592
|
-
const { id, before, after } = foldEvent(messages, actors, event);
|
|
2593
|
-
const by = event.payload.by?.actor;
|
|
2594
|
-
const message = after ?? before;
|
|
2595
|
-
const thread = event.payload.thread;
|
|
2596
|
-
let view$1;
|
|
2597
|
-
/** Each session's matches, appended together: one append per watcher in config, one per registrant. */
|
|
2598
|
-
const appends = /* @__PURE__ */ new Map();
|
|
2599
|
-
const add = (session, matched) => (appends.get(session) ?? appends.set(session, []).get(session)).push(matched);
|
|
2600
|
-
const registered = await registrations();
|
|
2601
|
-
const targets = [...configured, ...registered.flatMap(compiledFor)];
|
|
2602
|
-
const registrants = /* @__PURE__ */ new Map();
|
|
2603
|
-
const accessOf = (registration) => {
|
|
2604
|
-
let found = registrants.get(registration.owner);
|
|
2605
|
-
if (!found) registrants.set(registration.owner, found = options.registered.accessNow(registration.principal));
|
|
2606
|
-
return found;
|
|
2607
|
-
};
|
|
2608
|
-
for (const watcher of targets) {
|
|
2609
|
-
if (event.type === "thread.synced") break;
|
|
2610
|
-
if (by === watcher.actor) continue;
|
|
2611
|
-
if (RECEIPTS.has(event.type) && !watcher.all) continue;
|
|
2612
|
-
const { registration } = watcher;
|
|
2613
|
-
let access = FULL_ACCESS;
|
|
2614
|
-
if (registration) {
|
|
2615
|
-
const now = await accessOf(registration);
|
|
2616
|
-
if (!now || (id === null ? !now.readsAll : !message || !now.readable(message.channel))) continue;
|
|
2617
|
-
access = now;
|
|
2618
|
-
}
|
|
2619
|
-
const match = compileFilter(watcher.filters, {
|
|
2620
|
-
me: null,
|
|
2621
|
-
actors,
|
|
2622
|
-
messages,
|
|
2623
|
-
access
|
|
2624
|
-
});
|
|
2625
|
-
if (watcher.enters ? !entered(match, before, after, messages) : !(watcher.criteria ? match(before) || match(after) : id !== null)) continue;
|
|
2626
|
-
const key = registration ? `@${registration.owner}/${watcher.id}` : watcher.id;
|
|
2627
|
-
const shown = registration ? eventView(event, after, actors, await reads.reader(access, after ? [after] : [])) : view$1 ??= eventView(event, after, actors, OWN_CODE);
|
|
2628
|
-
add(registration ? registrantSession(registration.owner) : watchSession(watcher.id), {
|
|
2629
|
-
type: "watch.matched",
|
|
2630
|
-
id: await idempotentId("board-watch", key, event.id),
|
|
2631
|
-
payload: {
|
|
2632
|
-
thread,
|
|
2633
|
-
event: shown,
|
|
2634
|
-
...registration ? { watcher: watcher.id } : {}
|
|
2635
|
-
}
|
|
2636
|
-
});
|
|
2637
|
-
}
|
|
2638
|
-
const syncing = SYNCED.has(event.type) ? registered.filter((registration) => registration.sync.length > 0) : [];
|
|
2639
|
-
if (syncing.length > 0) {
|
|
2640
|
-
const about = event.type === "thread.synced" ? await rootOf(event.payload.thread, event.index, ctx.signal) : message;
|
|
2641
|
-
for (const registration of syncing) {
|
|
2642
|
-
const now = await accessOf(registration);
|
|
2643
|
-
if (!now || !about || !now.can("sync", about.channel)) continue;
|
|
2644
|
-
const reader = await reads.reader(now, [about, ...before ? [before] : []]);
|
|
2645
|
-
const shown = {
|
|
2646
|
-
...eventView(event, about, actors, reader),
|
|
2647
|
-
...event.type === "labels.changed" && before ? { before: view(before, actors, reader) } : {}
|
|
2648
|
-
};
|
|
2649
|
-
add(registrantSession(registration.owner), {
|
|
2650
|
-
type: "watch.matched",
|
|
2651
|
-
id: await idempotentId("board-watch", `@${registration.owner}/@sync`, event.id),
|
|
2652
|
-
payload: {
|
|
2653
|
-
thread,
|
|
2654
|
-
event: shown,
|
|
2655
|
-
sync: true
|
|
2656
|
-
}
|
|
2657
|
-
});
|
|
2658
|
-
}
|
|
2659
|
-
}
|
|
2660
|
-
await Promise.all([...appends].map(async ([session, events]) => {
|
|
2661
|
-
try {
|
|
2662
|
-
await server.session(session).append(...events);
|
|
2663
|
-
} catch (error) {
|
|
2664
|
-
if (!(error instanceof A2Error && error.code === "PARTIAL_DUPLICATE_BATCH")) throw error;
|
|
2665
|
-
for (const matched of events) await server.session(session).append(matched);
|
|
2666
|
-
}
|
|
2667
|
-
}));
|
|
2668
|
-
}
|
|
2669
|
-
/** A thread's root, as the board has it once the tables reach `index`: the event that synced it comes after it. */
|
|
2670
|
-
async function rootOf(thread, index, signal) {
|
|
2671
|
-
if (!reads) throw new Error("watchers used before the board bound them");
|
|
2672
|
-
await reads.ensure(index - 1, signal);
|
|
2673
|
-
return await reads.tables.byEventId(thread) ?? void 0;
|
|
2674
|
-
}
|
|
2675
|
-
/** The message `event` concerns, and its thread's root, as they were just before it. */
|
|
2676
|
-
async function messagesBefore(event, signal) {
|
|
2677
|
-
if (!reads) throw new Error("watchers used before the board bound them");
|
|
2678
|
-
return loadBefore(reads, event, signal);
|
|
2679
|
-
}
|
|
2680
|
-
/** Didn't match before and does now; a new reply only counts if its thread wasn't already in view. */
|
|
2681
|
-
function entered(match, before, after, messages) {
|
|
2682
|
-
if (match(before) || !match(after)) return false;
|
|
2683
|
-
return !match(before === void 0 && after.re !== null ? messages.byId[after.re] : void 0);
|
|
2684
|
-
}
|
|
2685
|
-
return {
|
|
2686
|
-
server,
|
|
2687
|
-
boardConsumer: consumer({
|
|
2688
|
-
contract: boardContract,
|
|
2689
|
-
name: "board-watchers",
|
|
2690
|
-
types: WATCHED,
|
|
2691
|
-
lane: ({ event }) => `thread:${event.payload.thread}`
|
|
2692
|
-
}).run(dispatch),
|
|
2693
|
-
bind: (binding) => {
|
|
2694
|
-
reads = binding.reads;
|
|
2695
|
-
}
|
|
2696
|
-
};
|
|
2697
|
-
}
|
|
2698
|
-
//#endregion
|
|
2699
|
-
//#region src/server/transport.ts
|
|
2700
|
-
/** Addresses a wake-up never reaches: this machine, private networks, link-local, and the rest that aren't the internet. */
|
|
2701
|
-
const NOT_PUBLIC = new BlockList();
|
|
2702
|
-
for (const [network, prefix] of [
|
|
2703
|
-
["0.0.0.0", 8],
|
|
2704
|
-
["10.0.0.0", 8],
|
|
2705
|
-
["100.64.0.0", 10],
|
|
2706
|
-
["127.0.0.0", 8],
|
|
2707
|
-
["169.254.0.0", 16],
|
|
2708
|
-
["172.16.0.0", 12],
|
|
2709
|
-
["192.0.0.0", 24],
|
|
2710
|
-
["192.168.0.0", 16],
|
|
2711
|
-
["198.18.0.0", 15],
|
|
2712
|
-
["224.0.0.0", 4],
|
|
2713
|
-
["240.0.0.0", 4]
|
|
2714
|
-
]) NOT_PUBLIC.addSubnet(network, prefix, "ipv4");
|
|
2715
|
-
for (const [network, prefix] of [
|
|
2716
|
-
["::", 127],
|
|
2717
|
-
["64:ff9b::", 96],
|
|
2718
|
-
["64:ff9b:1::", 48],
|
|
2719
|
-
["100::", 64],
|
|
2720
|
-
["2001::", 32],
|
|
2721
|
-
["2002::", 16],
|
|
2722
|
-
["fc00::", 7],
|
|
2723
|
-
["fe80::", 10],
|
|
2724
|
-
["fec0::", 10],
|
|
2725
|
-
["ff00::", 8]
|
|
2726
|
-
]) NOT_PUBLIC.addSubnet(network, prefix, "ipv6");
|
|
2727
|
-
/** Whether `address` is one a wake-up may connect to. */
|
|
2728
|
-
const isPublicAddress = (address) => {
|
|
2729
|
-
const family = isIP(address);
|
|
2730
|
-
return family !== 0 && !NOT_PUBLIC.check(address, family === 4 ? "ipv4" : "ipv6");
|
|
2731
|
-
};
|
|
2732
|
-
/** Resolves as the system does, and refuses a name that resolves to any address that isn't public. */
|
|
2733
|
-
const publicLookup = (hostname, options, callback) => {
|
|
2734
|
-
lookup(hostname, {
|
|
2735
|
-
...options,
|
|
2736
|
-
all: true
|
|
2737
|
-
}, (error, found) => {
|
|
2738
|
-
if (error) return callback(error, "", 0);
|
|
2739
|
-
const addresses = found;
|
|
2740
|
-
const bad = addresses.find((entry) => !isPublicAddress(entry.address));
|
|
2741
|
-
if (bad || addresses.length === 0) return callback(Object.assign(/* @__PURE__ */ new Error(`${hostname} resolves to ${bad?.address ?? "nothing"}, which isn't a public address`), { code: "ENOTPUBLIC" }), "", 0);
|
|
2742
|
-
if (options.all) return callback(null, addresses);
|
|
2743
|
-
callback(null, addresses[0].address, addresses[0].family);
|
|
2744
|
-
});
|
|
2745
|
-
};
|
|
2746
|
-
/** A response body is read only as far as an error message needs. */
|
|
2747
|
-
const ERROR_BYTES = 4096;
|
|
2748
|
-
/** Statuses a `Response` has no body with. */
|
|
2749
|
-
const NULL_BODY = /* @__PURE__ */ new Set([
|
|
2750
|
-
204,
|
|
2751
|
-
205,
|
|
2752
|
-
304
|
|
2753
|
-
]);
|
|
2754
|
-
/**
|
|
2755
|
-
* A wake-up's answer as a `Response`, whatever status the other end chose: one with no body has
|
|
2756
|
-
* none, and one a `Response` can't have (outside 200 to 599) is a 502.
|
|
2757
|
-
*/
|
|
2758
|
-
function responseOf(status, body) {
|
|
2759
|
-
if (status === void 0 || !Number.isInteger(status) || status < 200 || status > 599) return new Response(null, { status: 502 });
|
|
2760
|
-
return new Response(NULL_BODY.has(status) ? null : body, { status });
|
|
2761
|
-
}
|
|
2762
|
-
/** POSTs to a public `https` URL: the default `Post`. */
|
|
2763
|
-
async function publicPost(url, init) {
|
|
2764
|
-
const target = new URL(url);
|
|
2765
|
-
if (target.protocol !== "https:") throw new Error(`wake-ups go over https, not to ${url}`);
|
|
2766
|
-
const host = target.hostname.replace(/^\[|\]$/g, "");
|
|
2767
|
-
if (isIP(host) && !isPublicAddress(host)) throw new Error(`${host} isn't a public address`);
|
|
2768
|
-
return new Promise((resolve, reject) => {
|
|
2769
|
-
const sent = request(target, {
|
|
2770
|
-
method: "POST",
|
|
2771
|
-
headers: {
|
|
2772
|
-
...init.headers,
|
|
2773
|
-
"content-length": String(Buffer.byteLength(init.body))
|
|
2774
|
-
},
|
|
2775
|
-
lookup: publicLookup,
|
|
2776
|
-
signal: init.signal
|
|
2777
|
-
}, (response) => {
|
|
2778
|
-
const chunks = [];
|
|
2779
|
-
let size = 0;
|
|
2780
|
-
response.on("data", (chunk) => {
|
|
2781
|
-
if (size < ERROR_BYTES) chunks.push(chunk);
|
|
2782
|
-
size += chunk.length;
|
|
2783
|
-
});
|
|
2784
|
-
response.on("end", () => {
|
|
2785
|
-
try {
|
|
2786
|
-
resolve(responseOf(response.statusCode, Buffer.concat(chunks).subarray(0, ERROR_BYTES)));
|
|
2787
|
-
} catch (error) {
|
|
2788
|
-
reject(error);
|
|
2789
|
-
}
|
|
2790
|
-
});
|
|
2791
|
-
response.on("error", reject);
|
|
2792
|
-
});
|
|
2793
|
-
sent.on("error", reject);
|
|
2794
|
-
sent.end(init.body);
|
|
2795
|
-
});
|
|
2796
|
-
}
|
|
2797
|
-
//#endregion
|
|
2798
|
-
//#region src/server/a2.ts
|
|
2799
|
-
/** Sync's own lookups and receipts, from board() in this deployment. */
|
|
2800
|
-
const SYNC_ACTOR = "board:sync";
|
|
2801
|
-
/** The board's own code, through its handle: `team.post(…)`. With `as(profile)`, `board:client:<profile>`. */
|
|
2802
|
-
const CLIENT_ACTOR = "board:client";
|
|
2803
|
-
/** A cursor or message ref in a request, as this board's log index: decimals, from 0. */
|
|
2804
|
-
function cursorAt(value) {
|
|
2805
|
-
const index = indexOf(value);
|
|
2806
|
-
if (index === null) throw badRequest(`${value} isn't a cursor or a message ID on this board`, "invalid_cursor");
|
|
2807
|
-
return index;
|
|
2808
|
-
}
|
|
2809
|
-
/** The message a ref in a request names, as its log index, or a 404 for one that names nothing here. */
|
|
2810
|
-
function messageAt(value) {
|
|
2811
|
-
const index = indexOf(value);
|
|
2812
|
-
if (index === null || index === 0) throw notFound(`message not found: #${value}`, "message_not_found");
|
|
2813
|
-
return index;
|
|
2814
|
-
}
|
|
2815
|
-
/**
|
|
2816
|
-
* A reply's `after`, as the index of a message. One that isn't one is 0, which names no message:
|
|
2817
|
-
* the post refuses it, after a retry that landed gets its reply back.
|
|
2818
|
-
*/
|
|
2819
|
-
const afterAt = (value) => value === void 0 ? void 0 : indexOf(value) ?? 0;
|
|
2820
|
-
/**
|
|
2821
|
-
* A schedule's ID, `s12`, as its index in session `schedules`. `12` from a client that strips the
|
|
2822
|
-
* `s`, and `ss12` from an older CLI that adds one to what this board hands out, name it too.
|
|
2823
|
-
*/
|
|
2824
|
-
function scheduleAt(value) {
|
|
2825
|
-
const bare = value.replace(/^s{1,2}/, "");
|
|
2826
|
-
const index = indexOf(bare);
|
|
2827
|
-
if (index === null || index === 0) throw notFound(`schedule not found: s${bare}`, "schedule_not_found");
|
|
2828
|
-
return index;
|
|
2829
|
-
}
|
|
2830
|
-
new AbortController().signal;
|
|
2831
|
-
/** A wake-up only has to arrive: the board it wakes answers once what it pulls has run, or after 2 seconds while it keeps going. */
|
|
2832
|
-
const WAKE_TIMEOUT_MS = 5e3;
|
|
2833
|
-
/**
|
|
2834
|
-
* `idempotentId`'s shape, a UUIDv8: the IDs the board derives for its own writes (schedule
|
|
2835
|
-
* sends, watchers, sync). They're guessable, so an API caller can't post with one and take it first.
|
|
2836
|
-
*/
|
|
2837
|
-
const DERIVED_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-8[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
2838
|
-
/** A request to the board, as board() verified it, as opposed to a write the board's own code makes in-process. */
|
|
2839
|
-
const fromRequest = (caller) => "identity" in caller && (caller.origin.via?.kind ?? "api") === "api";
|
|
2840
|
-
/** Sync in board() in this deployment, as opposed to a sync elsewhere that uses this board. */
|
|
2841
|
-
const ownSync = (caller) => "self" in caller && caller.origin.via?.kind === "engine";
|
|
2842
|
-
/** board()'s own code, as the backend's discovery is asked for it. */
|
|
2843
|
-
const OWN = {
|
|
2844
|
-
self: null,
|
|
2845
|
-
origin: { via: {
|
|
2846
|
-
kind: "client",
|
|
2847
|
-
name: null
|
|
2848
|
-
} }
|
|
2849
|
-
};
|
|
2850
|
-
/**
|
|
2851
|
-
* Who a caller writes as. This deployment's own code writes as `board:client` from a handle,
|
|
2852
|
-
* `board:client:<profile>` from `as(profile)`, as `board:watch:<id>` from a watcher, which its
|
|
2853
|
-
* own writes never wake, and as `board:middleware` and `board:sync` from board()'s middleware
|
|
2854
|
-
* and sync.
|
|
2855
|
-
*/
|
|
2856
|
-
function selfIdentity(caller) {
|
|
2857
|
-
const { self, origin } = caller;
|
|
2858
|
-
if (origin.via?.kind === "watcher") return deploymentIdentity(`board:watch:${self}`, self ?? "watch");
|
|
2859
|
-
if (origin.via?.kind === "middleware") return deploymentIdentity(MIDDLEWARE_ACTOR, "middleware");
|
|
2860
|
-
if (origin.via?.kind === "engine") return deploymentIdentity(SYNC_ACTOR, "sync");
|
|
2861
|
-
if (self === null) return deploymentIdentity(CLIENT_ACTOR, "client");
|
|
2862
|
-
if (!ID.test(self)) throw badRequest(`as: profiles use lowercase letters, numbers, - and _, got: ${self}`);
|
|
2863
|
-
return deploymentIdentity(`${CLIENT_ACTOR}:${self}`, self);
|
|
2864
|
-
}
|
|
2865
|
-
/** A schedule as its creator sees it where it can't read: its text as a blind writer's message's is. */
|
|
2866
|
-
const blindSchedule = (schedule, access, own) => access.readable(schedule.channel) ? schedule : {
|
|
2867
|
-
...schedule,
|
|
2868
|
-
text: blindText(schedule.text, own)
|
|
2869
|
-
};
|
|
2870
|
-
/**
|
|
2871
|
-
* A platform user, writing through sync: full access, and each write still proved against the
|
|
2872
|
-
* channel it lands in. Their avatar is an https URL or none. `records`: the write keeps the
|
|
2873
|
-
* board's record of who they are, which only a sync that may sync everywhere does.
|
|
2874
|
-
*/
|
|
2875
|
-
function externalIdentity(author, records) {
|
|
2876
|
-
return {
|
|
2877
|
-
principal: {
|
|
2878
|
-
id: author.id,
|
|
2879
|
-
kind: "external",
|
|
2880
|
-
handle: author.handle,
|
|
2881
|
-
access: FULL_ACCESS,
|
|
2882
|
-
expiresAt: null
|
|
2883
|
-
},
|
|
2884
|
-
author: {
|
|
2885
|
-
actor: author.id,
|
|
2886
|
-
principal: author.id,
|
|
2887
|
-
profile: null,
|
|
2888
|
-
session: null
|
|
2889
|
-
},
|
|
2890
|
-
actor: {
|
|
2891
|
-
id: author.id,
|
|
2892
|
-
kind: "external",
|
|
2893
|
-
handle: author.handle,
|
|
2894
|
-
name: author.name,
|
|
2895
|
-
avatar: platformAvatar(author.avatar)
|
|
2896
|
-
},
|
|
2897
|
-
...records ? {} : { records: false }
|
|
2898
|
-
};
|
|
2899
|
-
}
|
|
2900
|
-
/** The board events sync delivers: what a platform shows, and a thread's new targets. */
|
|
2901
|
-
const DELIVERED = [
|
|
2902
|
-
"thread.synced",
|
|
2903
|
-
"message.posted",
|
|
2904
|
-
"message.edited",
|
|
2905
|
-
"message.deleted",
|
|
2906
|
-
"reaction.added",
|
|
2907
|
-
"reaction.removed",
|
|
2908
|
-
"labels.changed"
|
|
2909
|
-
];
|
|
2910
|
-
/** The inboxes that have had an event, so a sync key's inbox lists every channel's. */
|
|
2911
|
-
const inboxesReducer = reducer({
|
|
2912
|
-
contract: inboxContract,
|
|
2913
|
-
name: "board.inboxes.v1",
|
|
2914
|
-
initialState: {}
|
|
2915
|
-
}).fold((state, event) => {
|
|
2916
|
-
if (event.type === "inbox.opened") state[event.payload.channel] = true;
|
|
2917
|
-
return state;
|
|
2918
|
-
});
|
|
2919
|
-
/** An append that holds an event ID already in the log. */
|
|
2920
|
-
const duplicate = (error) => error instanceof A2Error && error.code === "PARTIAL_DUPLICATE_BATCH";
|
|
2921
|
-
/**
|
|
2922
|
-
* A platform event whose ID is already in an inbox: the platform's retry, which can read differently
|
|
2923
|
-
* (another instance, a name changed since), so the copy already there stands.
|
|
2924
|
-
*/
|
|
2925
|
-
const alreadyReceived = (error) => {
|
|
2926
|
-
if (!duplicate(error)) throw error;
|
|
2927
|
-
};
|
|
2928
|
-
/** Where a board given no store keeps it, in the working directory, in every environment. */
|
|
2929
|
-
const DEFAULT_STORE_PATH = ".a2/dev.db";
|
|
2930
|
-
/** Why a file couldn't be opened, in a few words: a read-only filesystem, a serverless function's say. */
|
|
2931
|
-
function unwritable(error) {
|
|
2932
|
-
const { code, message } = error;
|
|
2933
|
-
if (code === "EROFS" || code === "EACCES" || code === "EPERM" || /unable to open database|readonly database/i.test(String(message))) return "this filesystem isn't writable here";
|
|
2934
|
-
return String(message ?? error).split("\n")[0];
|
|
2935
|
-
}
|
|
2936
|
-
/**
|
|
2937
|
-
* The store of a board given none: SQLite at `.a2/dev.db`, opened on its first use (so nothing loads
|
|
2938
|
-
* SQLite for a board that's given a store). Where it can't open, each request says why and what to
|
|
2939
|
-
* pass: never a store in memory, which would lose the board without a word.
|
|
2940
|
-
*/
|
|
2941
|
-
async function defaultStore() {
|
|
2942
|
-
const { sqlite } = await import("./backend-a2/store-sqlite.mjs");
|
|
2943
|
-
try {
|
|
2944
|
-
return sqlite({ path: DEFAULT_STORE_PATH });
|
|
2945
|
-
} catch (error) {
|
|
2946
|
-
throw new HttpError(500, "no_store", `can't open SQLite at ${DEFAULT_STORE_PATH}: ${unwritable(error)}, so pass a store to a2()`);
|
|
2947
|
-
}
|
|
2948
|
-
}
|
|
2949
|
-
/** Everything behind a board on `a2()`, built once board() binds it. Nothing in it connects until it's used. */
|
|
2950
|
-
function build(options, binding) {
|
|
2951
|
-
const blob = options.blob ?? null;
|
|
2952
|
-
const { store } = options;
|
|
2953
|
-
const log = store.log;
|
|
2954
|
-
const registry = createRegistry({
|
|
2955
|
-
store: log,
|
|
2956
|
-
scheduler: options.scheduler
|
|
2957
|
-
});
|
|
2958
|
-
/**
|
|
2959
|
-
* Who a caller is, and what it may do now: one board() verified, as it said, its access
|
|
2960
|
-
* included; this deployment's own code everything.
|
|
2961
|
-
*/
|
|
2962
|
-
const identityOf = async (caller) => "identity" in caller ? caller.identity : selfIdentity(caller);
|
|
2963
|
-
/** Its own code's handle, which reaches it in process. */
|
|
2964
|
-
let ownHandle = null;
|
|
2965
|
-
const post = options.transport?.post ?? publicPost;
|
|
2966
|
-
const watchers = createWatchers({
|
|
2967
|
-
watch: Object.fromEntries(Object.entries(binding.subscriptions).flatMap(([id, subscription]) => subscription.kind === "tail" ? [[id, {
|
|
2968
|
-
tail: subscription.tail,
|
|
2969
|
-
when: subscription.when
|
|
2970
|
-
}]] : [])),
|
|
2971
|
-
run: (id, event, trigger, attempt) => binding.run(id, event, {
|
|
2972
|
-
trigger,
|
|
2973
|
-
attempt
|
|
2974
|
-
}),
|
|
2975
|
-
store: log,
|
|
2976
|
-
scheduler: options.scheduler,
|
|
2977
|
-
registered: {
|
|
2978
|
-
state: registry.state,
|
|
2979
|
-
accessNow: (principal) => binding.accessNow(principal),
|
|
2980
|
-
wake
|
|
2981
|
-
}
|
|
2982
|
-
});
|
|
2983
|
-
const schedules = createSchedules({
|
|
2984
|
-
store: log,
|
|
2985
|
-
scheduler: options.scheduler
|
|
2986
|
-
});
|
|
2987
|
-
const projection = tablesConsumer(store.tables);
|
|
2988
|
-
/** Sync's delivery in progress here: its receipts are its consumer's appends, fenced by its attempt. */
|
|
2989
|
-
const delivering = new AsyncLocalStorage();
|
|
2990
|
-
/**
|
|
2991
|
-
* Sync's outbound, when board() syncs: each event it delivers, on its thread's lane, with its own
|
|
2992
|
-
* place in the log, so no watcher holds it up. A2 retries what throws, and dead-letters it after 10.
|
|
2993
|
-
*/
|
|
2994
|
-
const outbound = binding.subscriptions["@sync"] ? consumer({
|
|
2995
|
-
contract: boardContract,
|
|
2996
|
-
name: "board-sync",
|
|
2997
|
-
types: DELIVERED,
|
|
2998
|
-
lane: ({ event }) => `thread:${event.payload.thread}`
|
|
2999
|
-
}).run(async (ctx) => {
|
|
3000
|
-
const event = ctx.event;
|
|
3001
|
-
const [messages, { state: actors }] = await Promise.all([loadBefore(reads, event, ctx.signal), ctx.session.state(actorsReducer, { through: event.index - 1 })]);
|
|
3002
|
-
const { before, after } = foldEvent(messages, actors, event);
|
|
3003
|
-
const shown = {
|
|
3004
|
-
...eventView(event, event.type === "thread.synced" ? (await reads.ensure(event.index - 1, ctx.signal), await store.tables.byEventId(event.payload.thread)) ?? void 0 : after, actors, OWN_CODE),
|
|
3005
|
-
...event.type === "labels.changed" && before ? { before: view(before, actors, OWN_CODE) } : {}
|
|
3006
|
-
};
|
|
3007
|
-
await delivering.run(ctx, () => binding.run(SYNC, shown, {
|
|
3008
|
-
trigger: ctx.event.id,
|
|
3009
|
-
attempt: ctx.attempt
|
|
3010
|
-
}));
|
|
3011
|
-
}) : void 0;
|
|
3012
|
-
const consumers = [
|
|
3013
|
-
projection,
|
|
3014
|
-
watchers.boardConsumer,
|
|
3015
|
-
outbound
|
|
3016
|
-
].filter((consumer) => consumer !== void 0);
|
|
3017
|
-
const server = createServer({
|
|
3018
|
-
contract: boardContract,
|
|
3019
|
-
store: log,
|
|
3020
|
-
...options.scheduler ? { scheduler: options.scheduler } : {},
|
|
3021
|
-
consumers
|
|
3022
|
-
});
|
|
3023
|
-
const session = server.session(BOARD_SESSION);
|
|
3024
|
-
const reads = createReads(store.tables, session, projection);
|
|
3025
|
-
const writes = {
|
|
3026
|
-
session,
|
|
3027
|
-
reads
|
|
3028
|
-
};
|
|
3029
|
-
/** Sync's inbound: each platform event board()'s sync pushed here, one platform thread at a time. */
|
|
3030
|
-
const inbound = consumer({
|
|
3031
|
-
contract: inboxContract,
|
|
3032
|
-
name: "board-inbox",
|
|
3033
|
-
types: ["external.received"],
|
|
3034
|
-
lane: ({ event }) => `thread:${event.payload.event.thread}`
|
|
3035
|
-
}).run(async (ctx) => {
|
|
3036
|
-
const { payload } = ctx.event;
|
|
3037
|
-
await binding.receive(payload.sync, {
|
|
3038
|
-
event: payload.event,
|
|
3039
|
-
raw: payload.raw
|
|
3040
|
-
}, {
|
|
3041
|
-
id: ctx.event.id,
|
|
3042
|
-
attempt: ctx.attempt,
|
|
3043
|
-
signal: ctx.signal
|
|
3044
|
-
});
|
|
3045
|
-
});
|
|
3046
|
-
const inboxServer = createServer({
|
|
3047
|
-
contract: inboxContract,
|
|
3048
|
-
store: log,
|
|
3049
|
-
...options.scheduler ? { scheduler: options.scheduler } : {},
|
|
3050
|
-
consumers: [inbound]
|
|
3051
|
-
});
|
|
3052
|
-
const access = createTrust({
|
|
3053
|
-
store: log,
|
|
3054
|
-
issuers: () => binding.issuers(),
|
|
3055
|
-
accessNow: (principal) => binding.accessNow(principal)
|
|
3056
|
-
});
|
|
3057
|
-
const inboxes = inboxServer.session(INBOXES_SESSION);
|
|
3058
|
-
/** The inboxes this instance knows have an `inbox.opened`, so most pushes write nothing more. */
|
|
3059
|
-
const opened = /* @__PURE__ */ new Set();
|
|
3060
|
-
schedules.bind({
|
|
3061
|
-
writes,
|
|
3062
|
-
accessNow: binding.accessNow,
|
|
3063
|
-
send: async (identity, origin, input) => sendAs(identity, origin, input)
|
|
3064
|
-
});
|
|
3065
|
-
watchers.bind({ reads });
|
|
3066
|
-
/**
|
|
3067
|
-
* Whether `principal` may have a file: one it uploaded, or one a message it
|
|
3068
|
-
* can read carries. A deleted message drops its files, so it no longer counts.
|
|
3069
|
-
*/
|
|
3070
|
-
async function attachmentReadable(principal, id, uploader) {
|
|
3071
|
-
if (principal.access.readsAll || ownUpload(uploader, principal)) return true;
|
|
3072
|
-
await reads.ensure();
|
|
3073
|
-
return (await reads.tables.withAttachment(id)).some((message) => principal.access.readable(message.channel));
|
|
3074
|
-
}
|
|
3075
|
-
/**
|
|
3076
|
-
* `filter`, narrowed to the channels `access` reads among those the log has,
|
|
3077
|
-
* and the index that list reflects: a read's cursor goes no further, or the
|
|
3078
|
-
* first post in a channel newer than the list would be in neither the page
|
|
3079
|
-
* nor the feed after it.
|
|
3080
|
-
*/
|
|
3081
|
-
async function readable(filter, access) {
|
|
3082
|
-
if (access.readsAll) return {
|
|
3083
|
-
filter,
|
|
3084
|
-
through: Number.POSITIVE_INFINITY
|
|
3085
|
-
};
|
|
3086
|
-
const { state, index } = await session.state(channelsReducer);
|
|
3087
|
-
return {
|
|
3088
|
-
filter: readableFilter(filter, Object.keys(state), access),
|
|
3089
|
-
through: index
|
|
3090
|
-
};
|
|
3091
|
-
}
|
|
3092
|
-
/** Who wrote, was mentioned, or reacted in the channels `access` reads, a page at a time. */
|
|
3093
|
-
async function actorsIn(access) {
|
|
3094
|
-
const ids = /* @__PURE__ */ new Set();
|
|
3095
|
-
const { filter } = await readable({}, access);
|
|
3096
|
-
for (let before;;) {
|
|
3097
|
-
const { messages } = await reads.messages(filter, {
|
|
3098
|
-
limit: 500,
|
|
3099
|
-
...before !== void 0 ? { before } : {}
|
|
3100
|
-
});
|
|
3101
|
-
for (const message of messages) {
|
|
3102
|
-
ids.add(message.by.actor);
|
|
3103
|
-
for (const id of message.mentions) ids.add(id);
|
|
3104
|
-
for (const reactors of Object.values(message.reactions)) for (const id of reactors) ids.add(id);
|
|
3105
|
-
}
|
|
3106
|
-
if (messages.length < 500) return ids;
|
|
3107
|
-
before = messages[0].id;
|
|
3108
|
-
}
|
|
3109
|
-
}
|
|
3110
|
-
/** Files a write carries, as the board stored them: each one the caller may have, or 404 as if it didn't exist. */
|
|
3111
|
-
const attachmentsFor = (principal, ids) => Promise.all([...new Set(ids ?? [])].map(async (id) => {
|
|
3112
|
-
const { attachment, ...uploader } = await readUpload(blob, id);
|
|
3113
|
-
if (!await attachmentReadable(principal, id, uploader)) throw attachmentNotFound(id);
|
|
3114
|
-
return attachment;
|
|
3115
|
-
}));
|
|
3116
|
-
/**
|
|
3117
|
-
* Tells a registrant's board it has matches to pull, with no event and no credential in it: its
|
|
3118
|
-
* board pulls them with its own credentials, and lets this POST through its own protection. The hash says whether its registration is stale. Says whether the
|
|
3119
|
-
* wake-up got there: an answer, or still pulling when the wait ran out.
|
|
3120
|
-
*/
|
|
3121
|
-
async function wake(registration) {
|
|
3122
|
-
try {
|
|
3123
|
-
const response = await post(`${registration.url}/wake`, {
|
|
3124
|
-
headers: {
|
|
3125
|
-
"content-type": "application/json",
|
|
3126
|
-
"x-board-watchers": registration.hash
|
|
3127
|
-
},
|
|
3128
|
-
body: "{}",
|
|
3129
|
-
signal: AbortSignal.timeout(WAKE_TIMEOUT_MS)
|
|
3130
|
-
});
|
|
3131
|
-
return response.ok ? { reached: true } : {
|
|
3132
|
-
reached: false,
|
|
3133
|
-
why: String(response.status)
|
|
3134
|
-
};
|
|
3135
|
-
} catch (error) {
|
|
3136
|
-
if (error.name === "TimeoutError") return { reached: true };
|
|
3137
|
-
return {
|
|
3138
|
-
reached: false,
|
|
3139
|
-
why: error.message
|
|
3140
|
-
};
|
|
3141
|
-
}
|
|
3142
|
-
}
|
|
3143
|
-
/** A registrant's queue, in the watch contract: its watchers' and sync's matches, and its inbox. */
|
|
3144
|
-
const queueOf = (owner) => watchers.server.session(registrantSession(owner));
|
|
3145
|
-
/**
|
|
3146
|
-
* A schedule's send, as its creator, through board(): its middleware sees it as any post. One the
|
|
3147
|
-
* middleware drops is a `DroppedError`, as the schedule takes it.
|
|
3148
|
-
*/
|
|
3149
|
-
async function sendAs(identity, origin, input) {
|
|
3150
|
-
const { channel, re, ...rest } = input;
|
|
3151
|
-
const handle = binding.handle({
|
|
3152
|
-
identity,
|
|
3153
|
-
origin
|
|
3154
|
-
});
|
|
3155
|
-
try {
|
|
3156
|
-
return channel !== void 0 ? await handle.post(channel, rest) : await handle.reply(re, rest);
|
|
3157
|
-
} catch (error) {
|
|
3158
|
-
if (error instanceof BoardError && error.code === "dropped") throw new DroppedError(error.message === "the board dropped this message" ? [] : error.message.split("\n"));
|
|
3159
|
-
throw error;
|
|
3160
|
-
}
|
|
3161
|
-
}
|
|
3162
|
-
/** A post as it lands: what the caller may post, with the files it may have. */
|
|
3163
|
-
async function postNow(caller, identity, parsed) {
|
|
3164
|
-
const { principal } = identity;
|
|
3165
|
-
const body = {
|
|
3166
|
-
...parsed,
|
|
3167
|
-
re: parsed.re === void 0 ? void 0 : messageAt(parsed.re)
|
|
3168
|
-
};
|
|
3169
|
-
const proofs = await authorizePost(writes, principal.access, body);
|
|
3170
|
-
if (fromRequest(caller) && body.id !== void 0 && DERIVED_ID.test(body.id)) throw badRequest("id: UUIDv8s are the board's own, for the writes it makes itself");
|
|
3171
|
-
if (fromRequest(caller) && body.id?.startsWith("key:") && !isKeyIdOf(body.id, principal.id)) throw badRequest(`id: key:… IDs derive from a client's key, and this token's are key:${principal.id}:…`);
|
|
3172
|
-
if (fromRequest(caller) && body.id?.startsWith("sync:")) throw badRequest("id: sync:… IDs are what sync imports, under the principal that imports them");
|
|
3173
|
-
const attachments = await attachmentsFor(principal, body.attachments);
|
|
3174
|
-
const { schedule } = caller.origin;
|
|
3175
|
-
const { unknownMentions, ...message } = await writePost(writes, {
|
|
3176
|
-
attachments,
|
|
3177
|
-
identity,
|
|
3178
|
-
proofs,
|
|
3179
|
-
channel: body.channel,
|
|
3180
|
-
re: body.re,
|
|
3181
|
-
text: body.text,
|
|
3182
|
-
labels: body.labels,
|
|
3183
|
-
noSync: body.noSync,
|
|
3184
|
-
id: body.id,
|
|
3185
|
-
sync: body.sync,
|
|
3186
|
-
after: afterAt(body.after),
|
|
3187
|
-
...schedule && !fromRequest(caller) ? {
|
|
3188
|
-
schedule,
|
|
3189
|
-
lenientMentions: true
|
|
3190
|
-
} : {}
|
|
3191
|
-
});
|
|
3192
|
-
return {
|
|
3193
|
-
message,
|
|
3194
|
-
...unknownMentions ? { unknownMentions } : {}
|
|
3195
|
-
};
|
|
3196
|
-
}
|
|
3197
|
-
/**
|
|
3198
|
-
* The sync entry an import says it came through, when it names one: one its caller syncs, or a
|
|
3199
|
-
* 403. This board's own sync's, or what a sync elsewhere registered.
|
|
3200
|
-
*/
|
|
3201
|
-
async function checkSource(caller, principal, source) {
|
|
3202
|
-
if (source && !(await entriesOf(caller, principal)).some((entry) => entry.key === source.key)) throw forbidden(`this token doesn't sync ${source.key} here: its board registers its sync entries`);
|
|
3203
|
-
}
|
|
3204
|
-
const methods = {
|
|
3205
|
-
async discovery() {
|
|
3206
|
-
const url = binding.url() ?? (ownHandle ??= binding.handle(OWN)).url;
|
|
3207
|
-
const { id, teamId } = await binding.project();
|
|
3208
|
-
return {
|
|
3209
|
-
version: VERSION,
|
|
3210
|
-
url,
|
|
3211
|
-
audience: url,
|
|
3212
|
-
team_id: teamId,
|
|
3213
|
-
project_id: id,
|
|
3214
|
-
sync: await syncEntries()
|
|
3215
|
-
};
|
|
3216
|
-
},
|
|
3217
|
-
async me(caller) {
|
|
3218
|
-
const { principal, author, actor } = await identityOf(caller);
|
|
3219
|
-
return {
|
|
3220
|
-
actor: actor.id,
|
|
3221
|
-
principal: principal.id,
|
|
3222
|
-
kind: actor.kind,
|
|
3223
|
-
handle: actor.handle,
|
|
3224
|
-
name: actor.name,
|
|
3225
|
-
avatar: actor.avatar,
|
|
3226
|
-
profile: author.profile,
|
|
3227
|
-
session: author.session,
|
|
3228
|
-
expiresAt: principal.expiresAt?.toISOString() ?? null,
|
|
3229
|
-
can: principal.access.summary()
|
|
3230
|
-
};
|
|
3231
|
-
},
|
|
3232
|
-
async channels(caller) {
|
|
3233
|
-
const { principal } = await identityOf(caller);
|
|
3234
|
-
const { state, index } = await session.state(channelsReducer);
|
|
3235
|
-
return {
|
|
3236
|
-
channels: Object.values(state).filter((channel) => principal.access.readable(channel.path)).sort((a, b) => a.path.localeCompare(b.path)),
|
|
3237
|
-
cursor: ref(index)
|
|
3238
|
-
};
|
|
3239
|
-
},
|
|
3240
|
-
async createChannel(caller, { path }) {
|
|
3241
|
-
return writeChannel(writes, {
|
|
3242
|
-
identity: await identityOf(caller),
|
|
3243
|
-
path
|
|
3244
|
-
});
|
|
3245
|
-
},
|
|
3246
|
-
async actors(caller) {
|
|
3247
|
-
const { principal, actor } = await identityOf(caller);
|
|
3248
|
-
const { state, index } = await session.state(actorsReducer);
|
|
3249
|
-
let seen = null;
|
|
3250
|
-
if (!principal.access.readsAll) {
|
|
3251
|
-
const ids = await actorsIn(principal.access);
|
|
3252
|
-
ids.add(actor.id);
|
|
3253
|
-
seen = (id) => ids.has(id);
|
|
3254
|
-
}
|
|
3255
|
-
return {
|
|
3256
|
-
actors: Object.values(state.byId).filter((a) => seen === null || seen(a.id)).sort((a, b) => a.handle.localeCompare(b.handle)).map(({ host: _host, ...a }) => a),
|
|
3257
|
-
cursor: ref(index)
|
|
3258
|
-
};
|
|
3259
|
-
},
|
|
3260
|
-
async messages(caller, query) {
|
|
3261
|
-
const { principal, actor } = await identityOf(caller);
|
|
3262
|
-
const { state: actors } = await session.state(actorsReducer);
|
|
3263
|
-
const { filter, through } = await readable(toMessageFilter(query, {
|
|
3264
|
-
me: actor.id,
|
|
3265
|
-
actors
|
|
3266
|
-
}), principal.access);
|
|
3267
|
-
const { messages, position } = await reads.messages(filter, {
|
|
3268
|
-
...query.before !== void 0 ? { before: cursorAt(query.before) } : {},
|
|
3269
|
-
...query.after !== void 0 ? { after: cursorAt(query.after) } : {},
|
|
3270
|
-
limit: query.limit ?? 50
|
|
3271
|
-
});
|
|
3272
|
-
const reader = await reads.reader(principal.access, messages);
|
|
3273
|
-
return {
|
|
3274
|
-
messages: messages.map((m) => view(m, actors, reader)),
|
|
3275
|
-
cursor: ref(Math.min(position, through))
|
|
3276
|
-
};
|
|
3277
|
-
},
|
|
3278
|
-
async threads(caller, query) {
|
|
3279
|
-
const { principal, actor } = await identityOf(caller);
|
|
3280
|
-
const { state: actors } = await session.state(actorsReducer);
|
|
3281
|
-
const { filter, through } = await readable(toMessageFilter(query, {
|
|
3282
|
-
me: actor.id,
|
|
3283
|
-
actors
|
|
3284
|
-
}), principal.access);
|
|
3285
|
-
const { threads, position } = await reads.threads(filter, {
|
|
3286
|
-
...query.after !== void 0 ? { after: cursorAt(query.after) } : {},
|
|
3287
|
-
limit: query.limit ?? 50
|
|
3288
|
-
});
|
|
3289
|
-
const reader = await reads.reader(principal.access, threads.flatMap((t) => t.last ? [t.root, t.last] : [t.root]));
|
|
3290
|
-
return {
|
|
3291
|
-
threads: threads.map((t) => ({
|
|
3292
|
-
message: view(t.root, actors, reader),
|
|
3293
|
-
replies: t.replies,
|
|
3294
|
-
last: t.last && view(t.last, actors, reader)
|
|
3295
|
-
})),
|
|
3296
|
-
cursor: ref(Math.min(position, through))
|
|
3297
|
-
};
|
|
3298
|
-
},
|
|
3299
|
-
async message(caller, { id }, signal) {
|
|
3300
|
-
const { principal } = await identityOf(caller);
|
|
3301
|
-
const at = messageAt(id);
|
|
3302
|
-
const message = await reads.message(at, signal);
|
|
3303
|
-
if (!message || !principal.access.readable(message.channel)) throw notFound(`message not found: #${at}`, "message_not_found");
|
|
3304
|
-
const [{ messages, cursor }, { state: actors }] = await Promise.all([reads.thread(message.re ?? message.id, signal), session.state(actorsReducer)]);
|
|
3305
|
-
const [root, ...replies] = messages;
|
|
3306
|
-
const reader = await reads.reader(principal.access, messages);
|
|
3307
|
-
return {
|
|
3308
|
-
message: view(root, actors, reader),
|
|
3309
|
-
replies: replies.map((reply) => view(reply, actors, reader)),
|
|
3310
|
-
cursor: ref(cursor),
|
|
3311
|
-
schedules: await schedules.forThread(root.id)
|
|
3312
|
-
};
|
|
3313
|
-
},
|
|
3314
|
-
async posted(caller, { id }, signal) {
|
|
3315
|
-
const identity = await identityOf(caller);
|
|
3316
|
-
const landed = await reads.byEventId(id, signal);
|
|
3317
|
-
const shown = landed ? await landedFor(writes, identity, landed) : null;
|
|
3318
|
-
if (!shown) throw notFound(`no post of yours has id ${id}`, "post_not_found");
|
|
3319
|
-
return { message: shown };
|
|
3320
|
-
},
|
|
3321
|
-
async post(caller, parsed) {
|
|
3322
|
-
return postNow(caller, await identityOf(caller), parsed);
|
|
3323
|
-
},
|
|
3324
|
-
async edit(caller, { id, text, revision }) {
|
|
3325
|
-
const identity = await identityOf(caller);
|
|
3326
|
-
const authorized = await authorizeOwn(writes, identity, messageAt(id), "edit");
|
|
3327
|
-
const { unknownMentions } = await writeEdit(writes, {
|
|
3328
|
-
identity,
|
|
3329
|
-
authorized,
|
|
3330
|
-
text,
|
|
3331
|
-
revision
|
|
3332
|
-
});
|
|
3333
|
-
return {
|
|
3334
|
-
ok: true,
|
|
3335
|
-
...unknownMentions ? { unknownMentions } : {}
|
|
3336
|
-
};
|
|
3337
|
-
},
|
|
3338
|
-
async delete(caller, { id, revision }) {
|
|
3339
|
-
const identity = await identityOf(caller);
|
|
3340
|
-
const authorized = await authorizeOwn(writes, identity, messageAt(id), "delete");
|
|
3341
|
-
await writeDelete(writes, {
|
|
3342
|
-
identity,
|
|
3343
|
-
authorized,
|
|
3344
|
-
revision
|
|
3345
|
-
});
|
|
3346
|
-
return { ok: true };
|
|
3347
|
-
},
|
|
3348
|
-
async react(caller, { id, emoji, remove }) {
|
|
3349
|
-
const identity = await identityOf(caller);
|
|
3350
|
-
const authorized = await authorizeMessage(writes, identity.principal.access, "react", messageAt(id));
|
|
3351
|
-
await writeReaction(writes, {
|
|
3352
|
-
identity,
|
|
3353
|
-
authorized,
|
|
3354
|
-
emoji,
|
|
3355
|
-
remove
|
|
3356
|
-
});
|
|
3357
|
-
return { ok: true };
|
|
3358
|
-
},
|
|
3359
|
-
async label(caller, { id, set, unset, if: expected }) {
|
|
3360
|
-
const identity = await identityOf(caller);
|
|
3361
|
-
const authorized = await authorizeMessage(writes, identity.principal.access, "label", messageAt(id));
|
|
3362
|
-
await writeLabels(writes, {
|
|
3363
|
-
identity,
|
|
3364
|
-
authorized,
|
|
3365
|
-
set,
|
|
3366
|
-
unset,
|
|
3367
|
-
if: expected
|
|
3368
|
-
});
|
|
3369
|
-
return { ok: true };
|
|
3370
|
-
},
|
|
3371
|
-
async schedule(caller, parsed) {
|
|
3372
|
-
const identity = await identityOf(caller);
|
|
3373
|
-
const body = {
|
|
3374
|
-
...parsed,
|
|
3375
|
-
re: parsed.re === void 0 ? void 0 : messageAt(parsed.re)
|
|
3376
|
-
};
|
|
3377
|
-
await authorizePost(writes, identity.principal.access, body);
|
|
3378
|
-
const attachments = await attachmentsFor(identity.principal, body.attachments);
|
|
3379
|
-
return schedules.create(identity, body, attachments);
|
|
3380
|
-
},
|
|
3381
|
-
async schedules(caller, query) {
|
|
3382
|
-
const { principal, actor } = await identityOf(caller);
|
|
3383
|
-
let root;
|
|
3384
|
-
if (query.re !== void 0) {
|
|
3385
|
-
const at = messageAt(query.re);
|
|
3386
|
-
root = (await authorizeMessage(writes, principal.access, "read", at)).message.re ?? at;
|
|
3387
|
-
}
|
|
3388
|
-
const visible = (schedule) => principal.access.readable(schedule.channel) || createdBy(schedule, {
|
|
3389
|
-
principal,
|
|
3390
|
-
actor
|
|
3391
|
-
});
|
|
3392
|
-
return { schedules: (await schedules.list({
|
|
3393
|
-
...query,
|
|
3394
|
-
...root !== void 0 ? { root } : {}
|
|
3395
|
-
}, visible)).map((schedule) => blindSchedule(schedule, principal.access, actor.id)) };
|
|
3396
|
-
},
|
|
3397
|
-
async cancelSchedule(caller, { id }) {
|
|
3398
|
-
const identity = await identityOf(caller);
|
|
3399
|
-
const answer = await schedules.cancel(identity, scheduleAt(id));
|
|
3400
|
-
return {
|
|
3401
|
-
...answer,
|
|
3402
|
-
schedule: blindSchedule(answer.schedule, identity.principal.access, identity.actor.id)
|
|
3403
|
-
};
|
|
3404
|
-
},
|
|
3405
|
-
grants: async (caller) => access.grants(await identityOf(caller)),
|
|
3406
|
-
createGrant: async (caller, body) => access.createGrant(await identityOf(caller), body),
|
|
3407
|
-
revokeGrant: async (caller, input) => access.revokeGrant(await identityOf(caller), input),
|
|
3408
|
-
tokens: async (caller) => access.tokens(await identityOf(caller)),
|
|
3409
|
-
createToken: async (caller, body) => access.createToken(await identityOf(caller), body),
|
|
3410
|
-
revokeToken: async (caller, input) => access.revokeToken(await identityOf(caller), input),
|
|
3411
|
-
async upload(caller, { data, name, type }) {
|
|
3412
|
-
const { principal } = await identityOf(caller);
|
|
3413
|
-
if (!principal.access.anywhere("post") && !principal.access.anywhere("sync")) throw forbidden("this token can't post anywhere, so it can't upload");
|
|
3414
|
-
const max = ownSync(caller) ? IMPORT_BYTES_MAX : ATTACHMENT_BYTES_MAX;
|
|
3415
|
-
return { attachment: await writeUpload(blob, {
|
|
3416
|
-
data,
|
|
3417
|
-
name,
|
|
3418
|
-
type,
|
|
3419
|
-
uploadedBy: principal.id,
|
|
3420
|
-
uploadedWith: await access.chain(principal)
|
|
3421
|
-
}, max) };
|
|
3422
|
-
},
|
|
3423
|
-
async uploadStart(caller, { name, type, size }) {
|
|
3424
|
-
const { principal } = await identityOf(caller);
|
|
3425
|
-
if (!principal.access.anywhere("post") && !principal.access.anywhere("sync")) throw forbidden("this token can't post anywhere, so it can't upload");
|
|
3426
|
-
return startUpload(blob, {
|
|
3427
|
-
name: name ?? null,
|
|
3428
|
-
type: type ?? null,
|
|
3429
|
-
size,
|
|
3430
|
-
uploadedBy: principal.id,
|
|
3431
|
-
uploadedWith: await access.chain(principal)
|
|
3432
|
-
});
|
|
3433
|
-
},
|
|
3434
|
-
async uploadFinish(caller, { id }) {
|
|
3435
|
-
const { principal } = await identityOf(caller);
|
|
3436
|
-
return { attachment: await finishUpload(blob, id, principal) };
|
|
3437
|
-
},
|
|
3438
|
-
async attachment(caller, { id }) {
|
|
3439
|
-
const { principal } = await identityOf(caller);
|
|
3440
|
-
const { attachment, ...uploader } = await readUpload(blob, id);
|
|
3441
|
-
if (!await attachmentReadable(principal, attachment.id, uploader)) throw attachmentNotFound(attachment.id);
|
|
3442
|
-
return {
|
|
3443
|
-
attachment,
|
|
3444
|
-
data: await attachmentBody(blob, attachment.id)
|
|
3445
|
-
};
|
|
3446
|
-
},
|
|
3447
|
-
async watchers(caller) {
|
|
3448
|
-
const { principal } = await identityOf(caller);
|
|
3449
|
-
const all = await registry.list();
|
|
3450
|
-
return { watchers: principal.access.everywhere("manage") ? all : all.filter((found) => found.owner === principal.id) };
|
|
3451
|
-
},
|
|
3452
|
-
async register(caller, body) {
|
|
3453
|
-
if (body.path) throw new HttpError(501, "no_wake_by_path", "this board wakes a url, not a path: register `url` instead");
|
|
3454
|
-
const { principal } = await identityOf(caller);
|
|
3455
|
-
ownWatchers(principal);
|
|
3456
|
-
if (!principal.access.anywhere("read")) throw forbidden("this token can't read anywhere, so a watcher it registers would see nothing");
|
|
3457
|
-
if ((body.sync?.length ?? 0) > 0 && !principal.access.anywhere("sync")) throw forbidden("this token can't register a sync: it needs sync somewhere");
|
|
3458
|
-
const taken = body.sync?.find((entry) => binding.sync.some((own) => own.key === entry.key));
|
|
3459
|
-
if (taken) throw new HttpError(409, "sync_key_taken", `this board's own sync has sync entry ${taken.key}: give yours another key`);
|
|
3460
|
-
for (const [id, spec] of Object.entries(body.watch)) {
|
|
3461
|
-
const name = RemoteWatcherId.safeParse(id);
|
|
3462
|
-
if (!name.success) throw badRequest(`watch ${id}: ${name.error.issues[0].message}`, "bad_watcher");
|
|
3463
|
-
try {
|
|
3464
|
-
compileWatcher(id, spec);
|
|
3465
|
-
} catch (error) {
|
|
3466
|
-
throw badRequest(error.message, "bad_watcher");
|
|
3467
|
-
}
|
|
3468
|
-
}
|
|
3469
|
-
const registered = await registry.register(storedPrincipal(principal), {
|
|
3470
|
-
url: body.url ?? null,
|
|
3471
|
-
watch: body.watch,
|
|
3472
|
-
sync: body.sync ?? []
|
|
3473
|
-
});
|
|
3474
|
-
const queue = queueOf(principal.id);
|
|
3475
|
-
if ((await queue.state(queueReducer)).state.unreachable) await queue.append({
|
|
3476
|
-
type: "watch.reachable",
|
|
3477
|
-
payload: { by: "registration" }
|
|
3478
|
-
});
|
|
3479
|
-
return registered;
|
|
3480
|
-
},
|
|
3481
|
-
async matches(caller, query, signal) {
|
|
3482
|
-
const { principal } = await identityOf(caller);
|
|
3483
|
-
ownWatchers(principal);
|
|
3484
|
-
if (!(await registry.state()).byOwner[principal.id]) throw notFound("this token has no watchers registered here", "no_registration");
|
|
3485
|
-
const queue = queueOf(principal.id);
|
|
3486
|
-
const pulling = {
|
|
3487
|
-
access: principal.access,
|
|
3488
|
-
limit: query.limit ?? 10,
|
|
3489
|
-
timers: options.scheduler !== void 0
|
|
3490
|
-
};
|
|
3491
|
-
const deadline = Date.now() + (query.wait ?? 0) * 1e3;
|
|
3492
|
-
for (let pause = 100;; pause = Math.min(pause * 2, 1e3)) {
|
|
3493
|
-
const matches = await pull(queue, {
|
|
3494
|
-
...pulling,
|
|
3495
|
-
now: Date.now()
|
|
3496
|
-
});
|
|
3497
|
-
if (matches.length > 0) {
|
|
3498
|
-
const reader = await reads.readerOf(principal.access, matches.flatMap((match) => viewLinkedIds(match.event)));
|
|
3499
|
-
return { matches: matches.map((match) => ({
|
|
3500
|
-
...match,
|
|
3501
|
-
event: viewedBy(match.event, reader)
|
|
3502
|
-
})) };
|
|
3503
|
-
}
|
|
3504
|
-
if (Date.now() >= deadline || signal.aborted) return { matches };
|
|
3505
|
-
await new Promise((resolve) => setTimeout(resolve, Math.min(pause, Math.max(0, deadline - Date.now()))));
|
|
3506
|
-
}
|
|
3507
|
-
},
|
|
3508
|
-
async ack(caller, { id, ...body }) {
|
|
3509
|
-
const { principal } = await identityOf(caller);
|
|
3510
|
-
ownWatchers(principal);
|
|
3511
|
-
const result = await ack(queueOf(principal.id), id, body, {
|
|
3512
|
-
now: Date.now(),
|
|
3513
|
-
timers: options.scheduler !== void 0
|
|
3514
|
-
});
|
|
3515
|
-
if (result === "gone") throw notFound(`no match ${id} is waiting for this token`, "no_match");
|
|
3516
|
-
if (result === "stale") throw new HttpError(409, "stale_lease", "that lease ran out, and the match was pulled again");
|
|
3517
|
-
return { ok: true };
|
|
3518
|
-
},
|
|
3519
|
-
async events(caller, query, signal) {
|
|
3520
|
-
const { principal, actor } = await identityOf(caller);
|
|
3521
|
-
const after = query.after !== void 0 ? cursorAt(query.after) : void 0;
|
|
3522
|
-
const { state: actors } = await session.state(actorsReducer);
|
|
3523
|
-
const { events, cursor } = await pollFeed({
|
|
3524
|
-
session,
|
|
3525
|
-
reads,
|
|
3526
|
-
after,
|
|
3527
|
-
filters: query,
|
|
3528
|
-
all: query.all ?? false,
|
|
3529
|
-
me: actor.id,
|
|
3530
|
-
actors,
|
|
3531
|
-
access: principal.access
|
|
3532
|
-
}, (query.wait ?? 0) * 1e3, signal);
|
|
3533
|
-
return {
|
|
3534
|
-
events,
|
|
3535
|
-
cursor: ref(cursor)
|
|
3536
|
-
};
|
|
3537
|
-
},
|
|
3538
|
-
async typing(caller, { id, status }, signal) {
|
|
3539
|
-
const { principal } = await identityOf(caller);
|
|
3540
|
-
const found = await reads.message(messageAt(id), signal);
|
|
3541
|
-
if (!found || found.deleted || !principal.access.readable(found.channel)) throw notFound(`message not found: #${id}`, "message_not_found");
|
|
3542
|
-
if (!principal.access.can("post", found.channel)) throw forbidden(`this token can't post in ${found.channel}`);
|
|
3543
|
-
const { message, replies } = await methods.message(caller, { id }, signal);
|
|
3544
|
-
return { targets: await binding.typing([message, ...replies], status) };
|
|
3545
|
-
},
|
|
3546
|
-
async readSource(caller, { key, target, limit, after }) {
|
|
3547
|
-
if (!binding.sync.some((entry) => entry.key === key)) throw notFound(`this board doesn't run sync entry ${key}: read it where its sync runs`, "not_synced_here");
|
|
3548
|
-
const { principal } = await identityOf(caller);
|
|
3549
|
-
if (!principal.access.everywhere("manage")) throw forbidden("this token can't read a source: it needs manage in every channel");
|
|
3550
|
-
return binding.readSource(key, target, limit ?? 50, after ?? null);
|
|
3551
|
-
},
|
|
3552
|
-
async joinSource(caller, { key, target }) {
|
|
3553
|
-
if (!binding.sync.some((entry) => entry.key === key)) throw notFound(`this board doesn't run sync entry ${key}: join it where its sync runs`, "not_synced_here");
|
|
3554
|
-
const { principal } = await identityOf(caller);
|
|
3555
|
-
if (!principal.access.everywhere("manage")) throw forbidden("this token can't join a source: it needs manage in every channel");
|
|
3556
|
-
return binding.joinSource(key, target);
|
|
3557
|
-
},
|
|
3558
|
-
async synced(caller, { id }, signal) {
|
|
3559
|
-
const { principal } = await identityOf(caller);
|
|
3560
|
-
const message = await reads.message(messageAt(id), signal);
|
|
3561
|
-
if (!message || !principal.access.readable(message.channel)) throw notFound(`message not found: #${id}`, "message_not_found");
|
|
3562
|
-
await reads.ensure(void 0, signal);
|
|
3563
|
-
const { tables } = store;
|
|
3564
|
-
const [thread, copies] = await Promise.all([tables.syncOf(message.thread), tables.copiesOf([message.id])]);
|
|
3565
|
-
const mine = copies.get(message.id) ?? {};
|
|
3566
|
-
return { targets: await Promise.all((thread?.targets ?? []).map(async (target) => {
|
|
3567
|
-
const key = target.slice(0, target.indexOf(":"));
|
|
3568
|
-
const external = (thread && Object.hasOwn(thread.external, target) ? thread.external[target] : void 0) ?? null;
|
|
3569
|
-
const copy = (Object.hasOwn(mine, target) ? mine[target] : external !== null && Object.hasOwn(mine, external) ? mine[external] : void 0) ?? null;
|
|
3570
|
-
return {
|
|
3571
|
-
target,
|
|
3572
|
-
key,
|
|
3573
|
-
thread: copy?.thread ?? external,
|
|
3574
|
-
message: copy?.message ?? null,
|
|
3575
|
-
url: copy ? await binding.linkOf(key, copy.thread, copy.message) : null,
|
|
3576
|
-
undelivered: Object.hasOwn(message.undelivered, target) ? message.undelivered[target] : null
|
|
3577
|
-
};
|
|
3578
|
-
})) };
|
|
3579
|
-
},
|
|
3580
|
-
async linked(caller, { url }, signal) {
|
|
3581
|
-
const missing = () => notFound("no message on this board for that link", "message_not_found");
|
|
3582
|
-
const read = binding.locate(url);
|
|
3583
|
-
if (read.length === 0) throw missing();
|
|
3584
|
-
await reads.ensure(void 0, signal);
|
|
3585
|
-
const { tables } = store;
|
|
3586
|
-
const registered = Object.values((await registry.state()).byOwner).flatMap((registration) => registration.sync);
|
|
3587
|
-
const keysOf = (platform) => new Set([...binding.sync, ...registered].filter((entry) => entry.platform === platform).map((entry) => entry.key));
|
|
3588
|
-
const first = async () => {
|
|
3589
|
-
for (const { platform, thread, message } of read) for (const key of keysOf(platform)) {
|
|
3590
|
-
let found;
|
|
3591
|
-
if (message !== null) found = await tables.messageOf(`${key}:${thread}`, message);
|
|
3592
|
-
else {
|
|
3593
|
-
const at = await tables.threadOf(`${key}:${thread}`);
|
|
3594
|
-
found = at === null ? null : (await tables.syncOf(at))?.root ?? null;
|
|
3595
|
-
}
|
|
3596
|
-
if (found) return found;
|
|
3597
|
-
}
|
|
3598
|
-
return null;
|
|
3599
|
-
};
|
|
3600
|
-
const id = await first();
|
|
3601
|
-
if (id === null) throw missing();
|
|
3602
|
-
try {
|
|
3603
|
-
return await methods.message(caller, { id: ref(id) }, signal);
|
|
3604
|
-
} catch (error) {
|
|
3605
|
-
if (error instanceof HttpError && error.status === 404) throw missing();
|
|
3606
|
-
throw error;
|
|
3607
|
-
}
|
|
3608
|
-
},
|
|
3609
|
-
async syncImport(caller, body, signal) {
|
|
3610
|
-
const { principal } = await needSync(caller, "import", true);
|
|
3611
|
-
await speaksFor(caller, principal.id, body.author, body.op === "seen" ? null : body.from);
|
|
3612
|
-
const author = externalIdentity(body.author, recordsActors(caller, principal));
|
|
3613
|
-
if (body.op === "seen") {
|
|
3614
|
-
const { state: actors } = await session.state(actorsReducer);
|
|
3615
|
-
const seen = author.records === false ? null : actorSeen(author.actor, actors);
|
|
3616
|
-
if (seen) await session.append(seen);
|
|
3617
|
-
return { message: null };
|
|
3618
|
-
}
|
|
3619
|
-
const may = (channel) => principal.access.can("sync", channel);
|
|
3620
|
-
if (body.op === "post") {
|
|
3621
|
-
if (body.channel === void 0 === (body.re === void 0)) throw badRequest("an import needs `channel`; a reply needs `re`");
|
|
3622
|
-
let re;
|
|
3623
|
-
let root = null;
|
|
3624
|
-
let channel = body.channel;
|
|
3625
|
-
if (body.re !== void 0) {
|
|
3626
|
-
re = messageAt(body.re);
|
|
3627
|
-
root = await reads.message(re);
|
|
3628
|
-
if (!root || !principal.access.readable(root.channel)) throw notFound(`message not found: #${body.re}`, "message_not_found");
|
|
3629
|
-
channel = root.channel;
|
|
3630
|
-
}
|
|
3631
|
-
if (!may(channel)) throw forbidden(`this token can't sync in ${channel}, so it can't import there`);
|
|
3632
|
-
const id = body.id === void 0 ? void 0 : importId(caller, principal.id, body.id);
|
|
3633
|
-
const attachments = await attachmentsFor(principal, body.attachments);
|
|
3634
|
-
const commit = async ({ text, labels }) => {
|
|
3635
|
-
const proofs = await trusted.post(writes, {
|
|
3636
|
-
channel: body.channel,
|
|
3637
|
-
re,
|
|
3638
|
-
labels
|
|
3639
|
-
});
|
|
3640
|
-
return (await writePost(writes, {
|
|
3641
|
-
identity: author,
|
|
3642
|
-
proofs,
|
|
3643
|
-
channel: body.channel,
|
|
3644
|
-
re,
|
|
3645
|
-
text,
|
|
3646
|
-
labels,
|
|
3647
|
-
noSync: body.noSync,
|
|
3648
|
-
id,
|
|
3649
|
-
origin: body.origin,
|
|
3650
|
-
from: body.from,
|
|
3651
|
-
...body.origin && !ownSync(caller) ? { importedBy: principal.id } : {},
|
|
3652
|
-
after: afterAt(body.after),
|
|
3653
|
-
lenientMentions: true,
|
|
3654
|
-
attachments,
|
|
3655
|
-
links: await linksOf(principal, body.links)
|
|
3656
|
-
})).id;
|
|
3657
|
-
};
|
|
3658
|
-
const write = {
|
|
3659
|
-
text: body.text,
|
|
3660
|
-
labels: body.labels ?? {}
|
|
3661
|
-
};
|
|
3662
|
-
if (id !== void 0 && await reads.byEventId(id, signal)) return { message: await commit(write) };
|
|
3663
|
-
if (body.origin) await claimable(body.origin, body.from, root?.thread ?? null);
|
|
3664
|
-
await checkSource(caller, principal.id, body.source);
|
|
3665
|
-
return { message: await commit(write) };
|
|
3666
|
-
}
|
|
3667
|
-
if (body.origin === void 0 === (body.message === void 0)) throw badRequest("a change names its message by `origin` or by `message`, one or the other");
|
|
3668
|
-
const id = body.origin !== void 0 ? await locate(body.origin) : indexOf(body.message);
|
|
3669
|
-
const found = id === null || id === 0 ? null : await reads.message(id);
|
|
3670
|
-
if (!found || !may(found.channel)) return { message: null };
|
|
3671
|
-
const authorized = (permission) => trusted.message(writes, permission, found.id);
|
|
3672
|
-
const asAuthor = body.origin === void 0;
|
|
3673
|
-
if (body.op === "edit") {
|
|
3674
|
-
const proof = await authorized("post");
|
|
3675
|
-
const commit = async ({ text }) => {
|
|
3676
|
-
await writeEdit(writes, {
|
|
3677
|
-
identity: author,
|
|
3678
|
-
authorized: proof,
|
|
3679
|
-
text,
|
|
3680
|
-
from: body.from,
|
|
3681
|
-
asAuthor,
|
|
3682
|
-
revision: body.revision
|
|
3683
|
-
});
|
|
3684
|
-
return ref(found.id);
|
|
3685
|
-
};
|
|
3686
|
-
const write = {
|
|
3687
|
-
kind: "edit",
|
|
3688
|
-
id: ref(found.id),
|
|
3689
|
-
channel: found.channel,
|
|
3690
|
-
re: found.re === null ? null : ref(found.re),
|
|
3691
|
-
text: body.text
|
|
3692
|
-
};
|
|
3693
|
-
if (!found.deleted && !(asAuthor && found.by.principal !== body.author.id)) await checkSource(caller, principal.id, body.source);
|
|
3694
|
-
return { message: await commit(write) };
|
|
3695
|
-
}
|
|
3696
|
-
if (body.op === "delete") await writeDelete(writes, {
|
|
3697
|
-
identity: author,
|
|
3698
|
-
authorized: await authorized("post"),
|
|
3699
|
-
from: body.from,
|
|
3700
|
-
asAuthor,
|
|
3701
|
-
revision: body.revision
|
|
3702
|
-
});
|
|
3703
|
-
else if (body.op === "react") await writeReaction(writes, {
|
|
3704
|
-
identity: author,
|
|
3705
|
-
authorized: await authorized("react"),
|
|
3706
|
-
emoji: body.emoji,
|
|
3707
|
-
remove: body.remove ?? false,
|
|
3708
|
-
from: body.from
|
|
3709
|
-
});
|
|
3710
|
-
else if (body.op === "labels") await writeLabels(writes, {
|
|
3711
|
-
identity: author,
|
|
3712
|
-
authorized: await authorized("label"),
|
|
3713
|
-
set: body.set,
|
|
3714
|
-
unset: body.unset,
|
|
3715
|
-
if: body.if
|
|
3716
|
-
});
|
|
3717
|
-
else await writeLinks(writes, {
|
|
3718
|
-
identity: author,
|
|
3719
|
-
authorized: await authorized("post"),
|
|
3720
|
-
links: await linksOf(principal, body.links) ?? [],
|
|
3721
|
-
from: body.from
|
|
3722
|
-
});
|
|
3723
|
-
return { message: ref(found.id) };
|
|
3724
|
-
},
|
|
3725
|
-
async syncReceipt(caller, body) {
|
|
3726
|
-
const identity = await identityOf(caller);
|
|
3727
|
-
unnarrowed(identity.principal, "record what it synced");
|
|
3728
|
-
const authorized = await authorizeMessage(writes, identity.principal.access, "sync", messageAt(body.message));
|
|
3729
|
-
const { message } = authorized;
|
|
3730
|
-
if (body.kind === "thread") return {
|
|
3731
|
-
ok: true,
|
|
3732
|
-
...await writeAttach(writes, {
|
|
3733
|
-
identity,
|
|
3734
|
-
authorized,
|
|
3735
|
-
target: {
|
|
3736
|
-
target: body.target,
|
|
3737
|
-
kind: body.targetKind
|
|
3738
|
-
},
|
|
3739
|
-
cause: body.cause
|
|
3740
|
-
})
|
|
3741
|
-
};
|
|
3742
|
-
await deliverable(caller, identity.principal.id, message, body.target, body.kind === "message" ? body.external : void 0);
|
|
3743
|
-
const about = {
|
|
3744
|
-
id: message.id,
|
|
3745
|
-
thread: message.thread,
|
|
3746
|
-
target: body.target
|
|
3747
|
-
};
|
|
3748
|
-
const by = ownSync(caller) ? {} : { syncedBy: identity.principal.id };
|
|
3749
|
-
if (body.kind === "message") await receipt(caller, `receipt:${message.id}:${body.target}`, [{
|
|
3750
|
-
type: "message.synced",
|
|
3751
|
-
payload: {
|
|
3752
|
-
...about,
|
|
3753
|
-
external: body.external,
|
|
3754
|
-
...by
|
|
3755
|
-
}
|
|
3756
|
-
}, ...body.files !== void 0 ? [{
|
|
3757
|
-
type: "message.files_synced",
|
|
3758
|
-
payload: {
|
|
3759
|
-
...about,
|
|
3760
|
-
files: body.files,
|
|
3761
|
-
...by
|
|
3762
|
-
}
|
|
3763
|
-
}] : []]);
|
|
3764
|
-
else if (body.kind === "files") await receipt(caller, `files:${message.id}:${body.target}`, [{
|
|
3765
|
-
type: "message.files_synced",
|
|
3766
|
-
payload: {
|
|
3767
|
-
...about,
|
|
3768
|
-
files: body.files,
|
|
3769
|
-
...by
|
|
3770
|
-
}
|
|
3771
|
-
}]);
|
|
3772
|
-
else await receipt(caller, `failed:${message.id}:${body.target}`, [{
|
|
3773
|
-
type: "message.sync_failed",
|
|
3774
|
-
payload: {
|
|
3775
|
-
...about,
|
|
3776
|
-
error: body.error
|
|
3777
|
-
}
|
|
3778
|
-
}]);
|
|
3779
|
-
return { ok: true };
|
|
3780
|
-
},
|
|
3781
|
-
async syncThread(caller, { thread }) {
|
|
3782
|
-
const { principal } = await needSync(caller, "look up a sync");
|
|
3783
|
-
await reads.ensure();
|
|
3784
|
-
const synced = await store.tables.syncOf(thread);
|
|
3785
|
-
if (!synced || !principal.access.can("sync", synced.channel)) throw notFound(`no thread ${thread} on this board`, "thread_not_found");
|
|
3786
|
-
return {
|
|
3787
|
-
thread,
|
|
3788
|
-
root: ref(synced.root),
|
|
3789
|
-
channel: synced.channel,
|
|
3790
|
-
targets: [...synced.targets],
|
|
3791
|
-
external: { ...synced.external }
|
|
3792
|
-
};
|
|
3793
|
-
},
|
|
3794
|
-
async syncFind(caller, query, signal) {
|
|
3795
|
-
const { principal } = await needSync(caller, "look up a sync");
|
|
3796
|
-
const { tables } = store;
|
|
3797
|
-
let thread = null;
|
|
3798
|
-
let message = null;
|
|
3799
|
-
if (query.post !== void 0) {
|
|
3800
|
-
const landed = await reads.byEventId(importId(caller, principal.id, query.post), signal);
|
|
3801
|
-
if (landed && principal.access.can("sync", landed.channel)) message = ref(landed.id);
|
|
3802
|
-
}
|
|
3803
|
-
if (query.thread !== void 0) {
|
|
3804
|
-
let key = query.message === void 0 ? await tables.threadOf(query.thread) : null;
|
|
3805
|
-
if (key === null) {
|
|
3806
|
-
await reads.ensure(void 0, signal);
|
|
3807
|
-
key = await tables.threadOf(query.thread);
|
|
3808
|
-
}
|
|
3809
|
-
const synced = key === null ? null : await tables.syncOf(key);
|
|
3810
|
-
if (synced && principal.access.can("sync", synced.channel)) thread = key;
|
|
3811
|
-
if (query.message !== void 0) {
|
|
3812
|
-
const id = await tables.messageOf(query.thread, query.message);
|
|
3813
|
-
const found = id === null ? null : await tables.message(id);
|
|
3814
|
-
if (found && principal.access.can("sync", found.channel)) message = ref(found.id);
|
|
3815
|
-
}
|
|
3816
|
-
}
|
|
3817
|
-
return {
|
|
3818
|
-
thread,
|
|
3819
|
-
message
|
|
3820
|
-
};
|
|
3821
|
-
},
|
|
3822
|
-
async syncCopies(caller, query) {
|
|
3823
|
-
const { principal } = await needSync(caller, "look up a sync");
|
|
3824
|
-
await reads.ensure();
|
|
3825
|
-
const ids = [...new Set(query.message.map(indexOf).filter((id) => id !== null && id > 0))];
|
|
3826
|
-
const everywhere = principal.access.everywhere("sync");
|
|
3827
|
-
const [copies, messages] = await Promise.all([store.tables.copiesOf(ids), everywhere ? null : store.tables.messagesAt(ids, await store.tables.position())]);
|
|
3828
|
-
const own = ownSync(caller);
|
|
3829
|
-
const mine = (copy) => own ? copy.by === void 0 : copy.by === principal.id;
|
|
3830
|
-
const out = {};
|
|
3831
|
-
for (const id of ids) {
|
|
3832
|
-
const found = messages?.get(id);
|
|
3833
|
-
if (everywhere || found && principal.access.can("sync", found.channel)) out[ref(id)] = Object.fromEntries(Object.entries(copies.get(id) ?? {}).filter(([, copy]) => mine(copy)).map(([target, { by: _by, ...copy }]) => [target, copy]));
|
|
3834
|
-
}
|
|
3835
|
-
return { copies: out };
|
|
3836
|
-
},
|
|
3837
|
-
async inboxPush(caller, { key, events }) {
|
|
3838
|
-
const { principal } = await needSync(caller, "push to an inbox", true);
|
|
3839
|
-
for (const { event } of events) for (const location of [
|
|
3840
|
-
event.channel,
|
|
3841
|
-
event.thread,
|
|
3842
|
-
"subthread" in event ? event.subthread : null
|
|
3843
|
-
]) if (location !== null && !location.startsWith(`${key}:`)) throw badRequest(`an inbox's platform locations belong to its sync key: ${location} isn't ${key}'s`);
|
|
3844
|
-
if (ownSync(caller)) {
|
|
3845
|
-
for (const { id, event, raw } of events) {
|
|
3846
|
-
await openInbox(event.channel);
|
|
3847
|
-
await inboxServer.session(inboxSession(event.channel)).append({
|
|
3848
|
-
type: "external.received",
|
|
3849
|
-
id: await idempotentId("board-inbox", key, id),
|
|
3850
|
-
payload: {
|
|
3851
|
-
sync: key,
|
|
3852
|
-
event,
|
|
3853
|
-
raw
|
|
3854
|
-
}
|
|
3855
|
-
}).catch(alreadyReceived);
|
|
3856
|
-
}
|
|
3857
|
-
return { ok: true };
|
|
3858
|
-
}
|
|
3859
|
-
const queue = queueOf(principal.id);
|
|
3860
|
-
const matched = await Promise.all(events.map(async ({ id, event, raw }) => ({
|
|
3861
|
-
type: "watch.matched",
|
|
3862
|
-
id: await idempotentId("board-inbox", key, id),
|
|
3863
|
-
payload: {
|
|
3864
|
-
thread: event.thread,
|
|
3865
|
-
inbox: key,
|
|
3866
|
-
event: {
|
|
3867
|
-
sync: key,
|
|
3868
|
-
event,
|
|
3869
|
-
raw
|
|
3870
|
-
}
|
|
3871
|
-
}
|
|
3872
|
-
})));
|
|
3873
|
-
await queue.append(...matched).catch(async (error) => {
|
|
3874
|
-
if (!duplicate(error)) throw error;
|
|
3875
|
-
for (const one of matched) await queue.append(one).catch(alreadyReceived);
|
|
3876
|
-
});
|
|
3877
|
-
return { ok: true };
|
|
3878
|
-
},
|
|
3879
|
-
async inboxNext(caller, { key, limit }) {
|
|
3880
|
-
if (ownSync(caller)) return { items: [] };
|
|
3881
|
-
const { principal } = await needSync(caller, "pull from an inbox", true);
|
|
3882
|
-
return { items: (await pullInbox(queueOf(principal.id), key, {
|
|
3883
|
-
access: principal.access,
|
|
3884
|
-
limit: limit ?? 10,
|
|
3885
|
-
now: Date.now(),
|
|
3886
|
-
timers: options.scheduler !== void 0
|
|
3887
|
-
})).map(({ id, thread, lease, attempt, event }) => {
|
|
3888
|
-
const item = event;
|
|
3889
|
-
return {
|
|
3890
|
-
id,
|
|
3891
|
-
key,
|
|
3892
|
-
thread,
|
|
3893
|
-
lease,
|
|
3894
|
-
attempt,
|
|
3895
|
-
event: item.event,
|
|
3896
|
-
raw: item.raw
|
|
3897
|
-
};
|
|
3898
|
-
}) };
|
|
3899
|
-
},
|
|
3900
|
-
async inboxAck(caller, { id, lease, error }) {
|
|
3901
|
-
const { principal } = await needSync(caller, "ack an inbox event", true);
|
|
3902
|
-
const result = await ack(queueOf(principal.id), id, {
|
|
3903
|
-
lease,
|
|
3904
|
-
error
|
|
3905
|
-
}, {
|
|
3906
|
-
now: Date.now(),
|
|
3907
|
-
timers: options.scheduler !== void 0
|
|
3908
|
-
});
|
|
3909
|
-
if (result === "gone") throw notFound(`no inbox event ${id} is waiting for this token`, "no_item");
|
|
3910
|
-
if (result === "stale") throw new HttpError(409, "stale_lease", "that lease ran out, and the event was pulled again");
|
|
3911
|
-
return { ok: true };
|
|
3912
|
-
},
|
|
3913
|
-
async inbox(caller, { key, channel, limit }) {
|
|
3914
|
-
const { principal } = await needSync(caller, "read an inbox");
|
|
3915
|
-
const everywhere = principal.access.everywhere("sync");
|
|
3916
|
-
const entries = [];
|
|
3917
|
-
if (everywhere) {
|
|
3918
|
-
const channels = channel !== void 0 ? [channel] : Object.keys((await inboxes.state(inboxesReducer)).state).filter((found) => found.startsWith(`${key}:`));
|
|
3919
|
-
for (const found of channels) for (const event of await inboxServer.session(inboxSession(found)).history()) if (event.type === "external.received" && event.payload.sync === key) entries.push({
|
|
3920
|
-
id: event.id,
|
|
3921
|
-
channel: found,
|
|
3922
|
-
createdAt: new Date(event.createdAt).toISOString(),
|
|
3923
|
-
...event.payload
|
|
3924
|
-
});
|
|
3925
|
-
}
|
|
3926
|
-
const pushers = /* @__PURE__ */ new Set([principal.id, ...everywhere ? Object.keys((await registry.state()).byOwner) : []]);
|
|
3927
|
-
for (const pusher of pushers) for (const event of await queueOf(pusher).history()) {
|
|
3928
|
-
const pushed = event.payload;
|
|
3929
|
-
if (event.type !== "watch.matched" || pushed.inbox !== key || !pushed.event) continue;
|
|
3930
|
-
if (channel !== void 0 && pushed.event.event.channel !== channel) continue;
|
|
3931
|
-
entries.push({
|
|
3932
|
-
id: event.id,
|
|
3933
|
-
channel: pushed.event.event.channel,
|
|
3934
|
-
createdAt: new Date(event.createdAt).toISOString(),
|
|
3935
|
-
...pushed.event
|
|
3936
|
-
});
|
|
3937
|
-
}
|
|
3938
|
-
return { events: entries.sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt)).slice(0, limit ?? 50) };
|
|
3939
|
-
}
|
|
3940
|
-
};
|
|
3941
|
-
/**
|
|
3942
|
-
* An import's client ID as the board keeps it. A sync elsewhere names its posts under its own
|
|
3943
|
-
* principal, so it can't take an ID anyone else would use.
|
|
3944
|
-
*/
|
|
3945
|
-
function importId(caller, principal, id) {
|
|
3946
|
-
return ownSync(caller) ? id : `sync:${principal}:${createHash("sha256").update(`board-sync\u001f${id}`).digest("hex").slice(0, 32)}`;
|
|
3947
|
-
}
|
|
3948
|
-
/**
|
|
3949
|
-
* The sync entries a caller imports through: this board's own sync's, or what a sync elsewhere
|
|
3950
|
-
* registered, but for a key this board's own sync has since taken: its platform locations are
|
|
3951
|
-
* that sync's alone.
|
|
3952
|
-
*/
|
|
3953
|
-
async function entriesOf(caller, principal) {
|
|
3954
|
-
if (ownSync(caller)) return binding.sync;
|
|
3955
|
-
return ((await registry.state()).byOwner[principal]?.sync ?? []).filter((entry) => !binding.sync.some((own) => own.key === entry.key));
|
|
3956
|
-
}
|
|
3957
|
-
/**
|
|
3958
|
-
* The sync entries this board lists in its discovery: its own sync's, then those of the syncs
|
|
3959
|
-
* registered here that may still sync. A key its own sync has is its own.
|
|
3960
|
-
*/
|
|
3961
|
-
async function syncEntries() {
|
|
3962
|
-
const found = /* @__PURE__ */ new Map();
|
|
3963
|
-
for (const { key, platform } of binding.sync) found.set(key, {
|
|
3964
|
-
key,
|
|
3965
|
-
platform
|
|
3966
|
-
});
|
|
3967
|
-
for (const registration of Object.values((await registry.state()).byOwner)) {
|
|
3968
|
-
if (registration.sync.length === 0) continue;
|
|
3969
|
-
if (!(await binding.accessNow(registration.principal))?.anywhere("sync")) continue;
|
|
3970
|
-
for (const { key, platform } of registration.sync) if (!found.has(key)) found.set(key, {
|
|
3971
|
-
key,
|
|
3972
|
-
platform
|
|
3973
|
-
});
|
|
3974
|
-
}
|
|
3975
|
-
return [...found.values()];
|
|
3976
|
-
}
|
|
3977
|
-
/**
|
|
3978
|
-
* Whether a caller may write as `author`: a platform user, never anyone this board
|
|
3979
|
-
* signs in, on a platform it syncs: the one of entry `from`, when it names one.
|
|
3980
|
-
*/
|
|
3981
|
-
async function speaksFor(caller, principal, author, from) {
|
|
3982
|
-
if (authenticates(author.id) || await signedIn(author.id)) throw forbidden(`${author.id} is someone this board signs in, not a platform user: sync can't write as them`);
|
|
3983
|
-
const entries = await entriesOf(caller, principal);
|
|
3984
|
-
const platforms = (from === null ? entries : entries.filter((entry) => entry.key === from)).map((entry) => entry.platform);
|
|
3985
|
-
if (from !== null && platforms.length === 0) throw forbidden(`this token doesn't sync ${from} here: its board registers its sync entries`);
|
|
3986
|
-
if (!platforms.some((platform) => author.id.startsWith(`${platform}:`))) throw forbidden(`${author.id} isn't a user of ${platforms.length ? platforms.join(" or ") : "a platform this token syncs"}`);
|
|
3987
|
-
}
|
|
3988
|
-
/**
|
|
3989
|
-
* Whether `id` is someone this board signs in that `authenticates` can't tell by its shape: a
|
|
3990
|
-
* host's principal, which may take any ID and kind, and their agents (`<principal>+<profile>`).
|
|
3991
|
-
* It is once it has registered (its watchers write as `<principal>+<id>`, which never wakes
|
|
3992
|
-
* them), or written: the board records a host's principals and their profiles as the host's,
|
|
3993
|
-
* whatever their kind, and anything else that writes as other than a platform user.
|
|
3994
|
-
*/
|
|
3995
|
-
async function signedIn(id) {
|
|
3996
|
-
const plus = id.indexOf("+");
|
|
3997
|
-
const owners = (await registry.state()).byOwner;
|
|
3998
|
-
if (owners[id] || plus > 0 && owners[id.slice(0, plus)]) return true;
|
|
3999
|
-
const { state: actors } = await session.state(actorsReducer);
|
|
4000
|
-
return [id, plus > 0 ? id.slice(0, plus) : null].some((known) => {
|
|
4001
|
-
const actor = known === null ? void 0 : actors.byId[known];
|
|
4002
|
-
return actor !== void 0 && (actor.kind !== "external" || actor.host === true);
|
|
4003
|
-
});
|
|
4004
|
-
}
|
|
4005
|
-
/**
|
|
4006
|
-
* Refuses a caller narrowed with `x-board-scope` (a sandboxed agent, say): its principal's
|
|
4007
|
-
* watchers are one registration, which its project registers and runs with the token it
|
|
4008
|
-
* narrowed. A narrowed pull would take matches from it, and a narrowed register replace it.
|
|
4009
|
-
*/
|
|
4010
|
-
function ownWatchers(principal) {
|
|
4011
|
-
if (principal.scope !== void 0) throw forbidden("this token is narrowed with x-board-scope: registering and running watchers is its project's job");
|
|
4012
|
-
}
|
|
4013
|
-
/**
|
|
4014
|
-
* Whether a sync's writes keep the board's record of the platform users they're by (name and
|
|
4015
|
-
* avatar), which every channel shows: this board's own sync's, and those of one that may sync in every
|
|
4016
|
-
* channel. Anyone else's still carry their author, and leave the record as it is.
|
|
4017
|
-
*/
|
|
4018
|
-
function recordsActors(caller, principal) {
|
|
4019
|
-
return ownSync(caller) || principal.access.everywhere("sync");
|
|
4020
|
-
}
|
|
4021
|
-
/**
|
|
4022
|
-
* The caller, when it may sync somewhere: what every sync route needs. `records`: what it does
|
|
4023
|
-
* keeps sync's records (imports, receipts, its inbox, links), which only an integration does,
|
|
4024
|
-
* never a caller narrowed with `x-board-scope`.
|
|
4025
|
-
*/
|
|
4026
|
-
async function needSync(caller, what, records = false) {
|
|
4027
|
-
const identity = await identityOf(caller);
|
|
4028
|
-
if (!identity.principal.access.anywhere("sync")) throw forbidden(`this token can't ${what}: it needs sync`);
|
|
4029
|
-
if (records) unnarrowed(identity.principal, what);
|
|
4030
|
-
return identity;
|
|
4031
|
-
}
|
|
4032
|
-
/**
|
|
4033
|
-
* Refuses a caller narrowed with `x-board-scope` what its principal's sync does: a platform
|
|
4034
|
-
* thread or message it claimed for a channel in its scope would bring that sync's later events
|
|
4035
|
-
* there, from wherever on the platform they are.
|
|
4036
|
-
*/
|
|
4037
|
-
function unnarrowed(principal, what) {
|
|
4038
|
-
if (principal.scope !== void 0) throw forbidden(`this token is narrowed with x-board-scope, so it can't ${what}: that's its project's sync's job`);
|
|
4039
|
-
}
|
|
4040
|
-
/**
|
|
4041
|
-
* Refuses a platform origin an import can't have. Sync's records map each platform thread and
|
|
4042
|
-
* message to one board thread and message, board-wide, so taking one over would send what the
|
|
4043
|
-
* platform says there to another channel: a new root's platform thread must be no board
|
|
4044
|
-
* thread's yet, a reply's must be its own thread's, and its platform message no board message's.
|
|
4045
|
-
* Its platform locations are under the sync key it came through.
|
|
4046
|
-
*/
|
|
4047
|
-
async function claimable(origin, from, thread) {
|
|
4048
|
-
if (from === null) throw badRequest("an import with an origin names the sync key it came through: pass `from`");
|
|
4049
|
-
for (const location of [
|
|
4050
|
-
origin.channel,
|
|
4051
|
-
origin.thread,
|
|
4052
|
-
origin.subthread
|
|
4053
|
-
]) if (location !== void 0 && location !== null && !location.startsWith(`${from}:`)) throw badRequest(`an import's platform locations belong to its sync key: ${location} isn't ${from}'s`);
|
|
4054
|
-
if (origin.subthread != null && !origin.subthread.startsWith(`${origin.thread}:`)) throw badRequest(`an import's subthread is in its thread: ${origin.subthread} isn't in ${origin.thread}`);
|
|
4055
|
-
await reads.ensure();
|
|
4056
|
-
const owner = await store.tables.threadOf(origin.thread);
|
|
4057
|
-
if (owner !== null && owner !== thread) throw new HttpError(409, "already_synced", `${origin.thread} is already synced with another thread`);
|
|
4058
|
-
if (owner === null && thread !== null) throw new HttpError(409, "not_synced", `${origin.thread} isn't synced with this thread`);
|
|
4059
|
-
const exact = origin.subthread ?? origin.thread;
|
|
4060
|
-
if (await store.tables.messageOf(exact, origin.message) !== null) throw new HttpError(409, "already_synced", `${origin.message} in ${exact} is already on the board`);
|
|
4061
|
-
}
|
|
4062
|
-
/**
|
|
4063
|
-
* Refuses a delivery receipt a caller's sync can't have made: one for a target of another sync's,
|
|
4064
|
-
* or of none of its message's thread's, or one that says its message landed as a platform thread
|
|
4065
|
-
* or message another board thread or message syncs with. Receipts map those board-wide.
|
|
4066
|
-
*/
|
|
4067
|
-
async function deliverable(caller, principal, message, target, external) {
|
|
4068
|
-
const key = target.slice(0, target.indexOf(":"));
|
|
4069
|
-
if (!(await entriesOf(caller, principal)).some((entry) => entry.key === key)) throw forbidden(`this token doesn't sync ${key} here: its board registers its sync entries`);
|
|
4070
|
-
await reads.ensure();
|
|
4071
|
-
if (!(await store.tables.syncOf(message.thread))?.targets.includes(target)) throw badRequest(`#${message.id}'s thread doesn't sync with ${target}`, "not_a_target");
|
|
4072
|
-
if (!external) return;
|
|
4073
|
-
if (!external.thread.startsWith(`${key}:`)) throw badRequest(`a delivery to ${target} lands under ${key}, not in ${external.thread}`);
|
|
4074
|
-
const owner = await store.tables.threadOf(external.thread);
|
|
4075
|
-
if (owner !== null && owner !== message.thread) throw new HttpError(409, "already_synced", `${external.thread} is already synced with another thread`);
|
|
4076
|
-
const copy = await store.tables.messageOf(external.thread, external.message);
|
|
4077
|
-
if (copy !== null && copy !== message.id) throw new HttpError(409, "already_synced", `${external.message} in ${external.thread} is another board message's`);
|
|
4078
|
-
}
|
|
4079
|
-
/** The board message an import changes: a platform message, or the root of the thread a platform thread belongs to. */
|
|
4080
|
-
async function locate(origin) {
|
|
4081
|
-
await reads.ensure();
|
|
4082
|
-
if (origin.message !== void 0) return store.tables.messageOf(origin.thread, origin.message);
|
|
4083
|
-
const thread = await store.tables.threadOf(origin.thread);
|
|
4084
|
-
return thread === null ? null : (await store.tables.syncOf(thread))?.root ?? null;
|
|
4085
|
-
}
|
|
4086
|
-
/**
|
|
4087
|
-
* An import's links, as the board keeps them. One names a board message only if the importer
|
|
4088
|
-
* may read it, and then says what the board's own copy says, never what the import does: its
|
|
4089
|
-
* readers see that snapshot as the message's. Any other keeps its URL, and the platform's
|
|
4090
|
-
* snapshot if it came with one.
|
|
4091
|
-
*/
|
|
4092
|
-
async function linksOf(principal, links) {
|
|
4093
|
-
if (!links) return void 0;
|
|
4094
|
-
const { state: actors } = await session.state(actorsReducer);
|
|
4095
|
-
return Promise.all(links.map(async ({ message: ref, ...link }) => {
|
|
4096
|
-
const id = ref === null ? null : indexOf(ref);
|
|
4097
|
-
const found = id === null || id === 0 ? null : await reads.message(id);
|
|
4098
|
-
if (!found || found.deleted || !principal.access.readable(found.channel)) return {
|
|
4099
|
-
...link,
|
|
4100
|
-
message: null
|
|
4101
|
-
};
|
|
4102
|
-
const snapshot = {
|
|
4103
|
-
author: actors.byId[found.by.actor]?.name ?? found.by.actor,
|
|
4104
|
-
text: found.text,
|
|
4105
|
-
createdAt: found.createdAt,
|
|
4106
|
-
files: found.attachments.map((file) => ({
|
|
4107
|
-
name: file.name,
|
|
4108
|
-
url: null
|
|
4109
|
-
}))
|
|
4110
|
-
};
|
|
4111
|
-
return {
|
|
4112
|
-
url: link.url,
|
|
4113
|
-
message: found.id,
|
|
4114
|
-
snapshot,
|
|
4115
|
-
unavailable: null
|
|
4116
|
-
};
|
|
4117
|
-
}));
|
|
4118
|
-
}
|
|
4119
|
-
/**
|
|
4120
|
-
* A receipt. This board's own sync, while it delivers here, appends it as its consumer, keyed by
|
|
4121
|
-
* `key`: a retry after a crash lands it once, and an attempt that was taken over can't. Anyone
|
|
4122
|
-
* else's lands once by `key`.
|
|
4123
|
-
*/
|
|
4124
|
-
async function receipt(caller, key, events) {
|
|
4125
|
-
const ctx = delivering.getStore();
|
|
4126
|
-
if (ctx && ownSync(caller)) {
|
|
4127
|
-
await ctx.session.append(key, ...events);
|
|
4128
|
-
return;
|
|
4129
|
-
}
|
|
4130
|
-
for (const [i, event] of events.entries()) await session.append({
|
|
4131
|
-
...event,
|
|
4132
|
-
id: await idempotentId("board-receipt", key, String(i))
|
|
4133
|
-
}).catch((error) => {
|
|
4134
|
-
if (!duplicate(error)) throw error;
|
|
4135
|
-
});
|
|
4136
|
-
}
|
|
4137
|
-
/** Records that the inbox for `channel` exists, the first time anything lands in it. */
|
|
4138
|
-
async function openInbox(channel) {
|
|
4139
|
-
if (opened.has(channel)) return;
|
|
4140
|
-
if (!(await inboxes.state(inboxesReducer)).state[channel]) await inboxes.append({
|
|
4141
|
-
type: "inbox.opened",
|
|
4142
|
-
id: await idempotentId("board-inbox", "opened", channel),
|
|
4143
|
-
payload: { channel }
|
|
4144
|
-
});
|
|
4145
|
-
opened.add(channel);
|
|
4146
|
-
}
|
|
4147
|
-
const servers = [
|
|
4148
|
-
server,
|
|
4149
|
-
inboxServer,
|
|
4150
|
-
schedules.server,
|
|
4151
|
-
registry.server,
|
|
4152
|
-
watchers.server
|
|
4153
|
-
];
|
|
4154
|
-
return {
|
|
4155
|
-
methods,
|
|
4156
|
-
schedules,
|
|
4157
|
-
trust: access.trust,
|
|
4158
|
-
/** The scheduler's callback, for every A2 server behind the board. */
|
|
4159
|
-
scheduler: options.scheduler ? options.scheduler.handler(...servers) : async (_request) => toErrorResponse(notFound("this board has no scheduler")),
|
|
4160
|
-
servers,
|
|
4161
|
-
session,
|
|
4162
|
-
store
|
|
4163
|
-
};
|
|
4164
|
-
}
|
|
4165
|
-
/**
|
|
4166
|
-
* The board in this deployment, on A2's log: its store (SQLite at `.a2/dev.db` by default), and
|
|
4167
|
-
* optionally a scheduler and somewhere for files. It's the backend itself: pass it to
|
|
4168
|
-
* `board({ backend })`, and mount its `scheduler` in a route of its own. It trusts the callers
|
|
4169
|
-
* board() verified; what it does outside requests, it asks board()'s policy about and writes
|
|
4170
|
-
* through board(). Nothing is built or connected until board() binds it, and the default store
|
|
4171
|
-
* opens on the first call.
|
|
4172
|
-
*/
|
|
4173
|
-
function a2(options = {}) {
|
|
4174
|
-
let binding = null;
|
|
4175
|
-
let built = null;
|
|
4176
|
-
let opening = null;
|
|
4177
|
-
/** What's built, for what can't wait for the default store to open. */
|
|
4178
|
-
const now = () => {
|
|
4179
|
-
if (built) return built;
|
|
4180
|
-
if (!binding) throw new Error("a2: this backend isn't serving a board yet: pass it to board({ backend })");
|
|
4181
|
-
throw new Error("a2: its default store opens on the board's first request: pass a store to reach it before that");
|
|
4182
|
-
};
|
|
4183
|
-
/** A queue's delivery, through the scheduler callback, and everything it runs: watchers' writes too. */
|
|
4184
|
-
const delivery = new AsyncLocalStorage();
|
|
4185
|
-
const ready = async () => {
|
|
4186
|
-
if (!built) {
|
|
4187
|
-
if (!binding) throw new Error("a2: this backend isn't serving a board yet: pass it to board({ backend })");
|
|
4188
|
-
const bound = binding;
|
|
4189
|
-
opening ??= defaultStore().then((store) => built ??= build({
|
|
4190
|
-
...options,
|
|
4191
|
-
store
|
|
4192
|
-
}, bound));
|
|
4193
|
-
opening.catch(() => opening = null);
|
|
4194
|
-
await opening;
|
|
4195
|
-
}
|
|
4196
|
-
built.schedules.catchUp({ takeOver: !delivery.getStore() });
|
|
4197
|
-
return built;
|
|
4198
|
-
};
|
|
4199
|
-
const backend = {
|
|
4200
|
-
...Object.fromEntries(METHODS.map((name) => [name, async (caller, input, signal) => (await ready()).methods[name](caller, input, signal)])),
|
|
4201
|
-
routes: [],
|
|
4202
|
-
keeps: true,
|
|
4203
|
-
trust: {
|
|
4204
|
-
grants: async () => (await ready()).trust.grants(),
|
|
4205
|
-
token: async (hash) => (await ready()).trust.token(hash),
|
|
4206
|
-
live: async (id) => (await ready()).trust.live(id)
|
|
4207
|
-
},
|
|
4208
|
-
bind(given) {
|
|
4209
|
-
if (binding) throw new Error("a2: this backend already serves a board: create one a2() per board()");
|
|
4210
|
-
binding = given;
|
|
4211
|
-
if (options.store) built = build({
|
|
4212
|
-
...options,
|
|
4213
|
-
store: options.store
|
|
4214
|
-
}, given);
|
|
4215
|
-
},
|
|
4216
|
-
/** The scheduler's callback: `export { scheduler as POST }` from a route of its own. A board without a scheduler answers 404. */
|
|
4217
|
-
scheduler: (request) => delivery.run(true, async () => (await ready()).scheduler(request)),
|
|
4218
|
-
/** The A2 servers behind this board, to share one scheduler with other A2 servers. */
|
|
4219
|
-
get servers() {
|
|
4220
|
-
return now().servers;
|
|
4221
|
-
},
|
|
4222
|
-
/** For tests and tools. */
|
|
4223
|
-
get session() {
|
|
4224
|
-
return now().session;
|
|
4225
|
-
},
|
|
4226
|
-
get store() {
|
|
4227
|
-
return now().store;
|
|
4228
|
-
}
|
|
4229
|
-
};
|
|
4230
|
-
for (const key of [
|
|
4231
|
-
"servers",
|
|
4232
|
-
"session",
|
|
4233
|
-
"store"
|
|
4234
|
-
]) Object.defineProperty(backend, key, { enumerable: false });
|
|
4235
|
-
return backend;
|
|
4236
|
-
}
|
|
4237
|
-
//#endregion
|
|
4238
|
-
export { a2 as t };
|