@plitzi/sdk-actions 0.0.0-stage → 0.39.2
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/CHANGELOG.md +11 -0
- package/README.md +54 -2
- package/dist/chunks/credentials-DwxZeAvH.mjs +27 -0
- package/dist/chunks/errors-bCBfIe7c.mjs +54 -0
- package/dist/chunks/grants-BsD-WlLE.mjs +168 -0
- package/dist/chunks/load-DBWRZn7G.mjs +48 -0
- package/dist/chunks/module-WdDzbjHy.mjs +7032 -0
- package/dist/chunks/queueDocument-xYz-KZ5V.mjs +21 -0
- package/dist/chunks/queueRules-BCCVgeUE.mjs +487 -0
- package/dist/chunks/remote-DopPgCMK.mjs +404 -0
- package/dist/chunks/storeClock-Btm7EaVm.mjs +31 -0
- package/dist/chunks/taskCatalog-S1IozUTD.mjs +201 -0
- package/dist/connectors/connectors.d.ts +7 -0
- package/dist/connectors/engine.d.ts +47 -0
- package/dist/connectors/getByPath.d.ts +8 -0
- package/dist/connectors/projection.d.ts +18 -0
- package/dist/connectors/resolver.d.ts +27 -0
- package/dist/connectors/types.d.ts +19 -0
- package/dist/engine/configSeam.d.ts +10 -0
- package/dist/engine/connectorWrite.d.ts +12 -0
- package/dist/engine/fileStore.d.ts +60 -0
- package/dist/engine/fleet.d.ts +20 -0
- package/dist/engine/jobs/calls.d.ts +49 -0
- package/dist/engine/jobs/claimSpaces.d.ts +10 -0
- package/dist/engine/jobs/codeMarks.d.ts +10 -0
- package/dist/engine/jobs/endings.d.ts +42 -0
- package/dist/engine/jobs/failureStreak.d.ts +15 -0
- package/dist/engine/jobs/fileQueue.d.ts +34 -0
- package/dist/engine/jobs/flow.d.ts +11 -0
- package/dist/engine/jobs/jobs.d.ts +36 -0
- package/dist/engine/jobs/later.d.ts +27 -0
- package/dist/engine/jobs/memoryNeeds.d.ts +24 -0
- package/dist/engine/jobs/memoryQueue.d.ts +33 -0
- package/dist/engine/jobs/memoryWatch.d.ts +21 -0
- package/dist/engine/jobs/notNow.d.ts +39 -0
- package/dist/engine/jobs/queueDocument.d.ts +15 -0
- package/dist/engine/jobs/queueRules.d.ts +64 -0
- package/dist/engine/jobs/scheduler.d.ts +70 -0
- package/dist/engine/jobs/schedules.d.ts +24 -0
- package/dist/engine/jobs/storeClock.d.ts +16 -0
- package/dist/engine/jobs/wake.d.ts +6 -0
- package/dist/engine/jobs/worker.d.ts +99 -0
- package/dist/engine/module.d.ts +96 -0
- package/dist/engine/moduleFor.d.ts +3 -0
- package/dist/engine/runtime/check.d.ts +24 -0
- package/dist/engine/runtime/credentials.d.ts +8 -0
- package/dist/engine/runtime/deadline.d.ts +19 -0
- package/dist/engine/runtime/email.d.ts +38 -0
- package/dist/engine/runtime/errors.d.ts +28 -0
- package/dist/engine/runtime/fileKv.d.ts +35 -0
- package/dist/engine/runtime/flags.d.ts +16 -0
- package/dist/engine/runtime/guards.d.ts +190 -0
- package/dist/engine/runtime/kvList.d.ts +28 -0
- package/dist/engine/runtime/kvStore.d.ts +36 -0
- package/dist/engine/runtime/limits.d.ts +12 -0
- package/dist/engine/runtime/memoryKv.d.ts +28 -0
- package/dist/engine/runtime/namespaceKv.d.ts +9 -0
- package/dist/engine/runtime/precheck.d.ts +28 -0
- package/dist/engine/runtime/rateLimit.d.ts +9 -0
- package/dist/engine/runtime/redisKv.d.ts +27 -0
- package/dist/engine/runtime/renderFailure.d.ts +24 -0
- package/dist/engine/runtime/renderResolver.d.ts +16 -0
- package/dist/engine/runtime/renderShare.d.ts +12 -0
- package/dist/engine/runtime/report.d.ts +15 -0
- package/dist/engine/runtime/runAction.d.ts +26 -0
- package/dist/engine/runtime/runLogger.d.ts +37 -0
- package/dist/engine/runtime/runStats.d.ts +8 -0
- package/dist/engine/runtime/scope.d.ts +40 -0
- package/dist/engine/runtime/signing.d.ts +27 -0
- package/dist/engine/runtime/taskContext.d.ts +54 -0
- package/dist/engine/runtime/triggers.d.ts +12 -0
- package/dist/engine/taskCatalog.d.ts +28 -0
- package/dist/engine/tasks/auth.d.ts +2 -0
- package/dist/engine/tasks/builtins.d.ts +10 -0
- package/dist/engine/tasks/connector.d.ts +2 -0
- package/dist/engine/tasks/db.d.ts +2 -0
- package/dist/engine/tasks/email.d.ts +2 -0
- package/dist/engine/tasks/flow.d.ts +3 -0
- package/dist/engine/tasks/helpers.d.ts +16 -0
- package/dist/engine/tasks/http.d.ts +2 -0
- package/dist/engine/tasks/kv.d.ts +2 -0
- package/dist/engine/tasks/list.d.ts +2 -0
- package/dist/engine/tasks/names.d.ts +8 -0
- package/dist/engine/tasks/realtime.d.ts +3 -0
- package/dist/engine/tasks/registry.d.ts +19 -0
- package/dist/engine/tasks/transform.d.ts +2 -0
- package/dist/engine/transport/callHandler.d.ts +34 -0
- package/dist/engine/transport/cancelHandler.d.ts +23 -0
- package/dist/engine/transport/catalogHandler.d.ts +22 -0
- package/dist/engine/transport/stream.d.ts +22 -0
- package/dist/engine/transport/verifySignature.d.ts +16 -0
- package/dist/engine/transport/webhookHandler.d.ts +26 -0
- package/dist/engine/types.d.ts +442 -0
- package/dist/functions/build.d.ts +27 -0
- package/dist/functions/capabilities.d.ts +11 -0
- package/dist/functions/config.d.ts +111 -0
- package/dist/functions/context.d.ts +15 -0
- package/dist/functions/index.d.ts +17 -0
- package/dist/functions/index.mjs +461 -0
- package/dist/functions/jobControl.d.ts +22 -0
- package/dist/functions/jobs.d.ts +104 -0
- package/dist/functions/load.d.ts +22 -0
- package/dist/functions/local.d.ts +36 -0
- package/dist/functions/manifest.d.ts +32 -0
- package/dist/functions/native.d.ts +13 -0
- package/dist/functions/oauth.d.ts +33 -0
- package/dist/functions/routes.d.ts +50 -0
- package/dist/functions/runner/remote.d.ts +26 -0
- package/dist/functions/scope.d.ts +28 -0
- package/dist/functions/space.d.ts +41 -0
- package/dist/functions/tryEntry.d.ts +9 -0
- package/dist/index.d.ts +47 -0
- package/dist/index.mjs +545 -0
- package/dist/mongo/claimable.d.ts +5 -0
- package/dist/mongo/index.d.ts +4 -0
- package/dist/mongo/index.mjs +779 -0
- package/dist/mongo/jobQueue.d.ts +38 -0
- package/dist/mongo/kv.d.ts +15 -0
- package/dist/mysql/index.d.ts +5 -0
- package/dist/mysql/index.mjs +808 -0
- package/dist/mysql/jobQueue.d.ts +40 -0
- package/dist/mysql/kv.d.ts +18 -0
- package/dist/mysql/rows.d.ts +64 -0
- package/dist/mysql/schema.d.ts +28 -0
- package/dist/mysql/summary.d.ts +7 -0
- package/dist/realtime/declarations.d.ts +11 -0
- package/dist/realtime/failure.d.ts +6 -0
- package/dist/realtime/grants.d.ts +22 -0
- package/dist/realtime/handlers.d.ts +86 -0
- package/dist/realtime/hub.d.ts +71 -0
- package/dist/realtime/index.d.ts +105 -0
- package/dist/realtime/index.mjs +824 -0
- package/dist/realtime/jobs.d.ts +18 -0
- package/dist/realtime/message.d.ts +3 -0
- package/dist/realtime/presence.d.ts +33 -0
- package/dist/realtime/retained.d.ts +21 -0
- package/dist/realtime/socket.d.ts +30 -0
- package/dist/render/index.d.ts +10 -0
- package/dist/render/index.mjs +1 -0
- package/dist/render/protocol.d.ts +47 -0
- package/dist/render/remote.d.ts +16 -0
- package/dist/runtimes/bundle.d.ts +29 -0
- package/dist/runtimes/index.d.ts +3 -0
- package/dist/runtimes/index.mjs +229 -0
- package/dist/runtimes/stages.d.ts +52 -0
- package/dist/sqlite/index.d.ts +4 -0
- package/dist/sqlite/index.mjs +160 -0
- package/dist/sqlite/jobQueue.d.ts +35 -0
- package/dist/sqlite/kv.d.ts +34 -0
- package/dist/sqlite/open.d.ts +3 -0
- package/dist/types/config.d.ts +293 -0
- package/dist/types/index.d.ts +2 -0
- package/dist/types/index.mjs +1 -0
- package/dist/types/jobs.d.ts +317 -0
- package/dist/worker/elsewhere.d.ts +16 -0
- package/dist/worker/index.d.ts +5 -0
- package/dist/worker/index.mjs +1703 -0
- package/dist/worker/origin.d.ts +12 -0
- package/dist/worker/pageEngine.d.ts +11 -0
- package/dist/worker/stages/action.d.ts +24 -0
- package/dist/worker/stages/cors.d.ts +9 -0
- package/dist/worker/stages/forward.d.ts +12 -0
- package/dist/worker/stages/functionRoutes.d.ts +10 -0
- package/dist/worker/stages/queuedCalls.d.ts +15 -0
- package/dist/worker/stages/realtime.d.ts +9 -0
- package/dist/worker/stages/render.d.ts +9 -0
- package/dist/worker/worker.d.ts +39 -0
- package/package.json +76 -3
|
@@ -0,0 +1,824 @@
|
|
|
1
|
+
import { i as KV_METHODS, o as createMemoryKv, r as createRealtimeGrants } from "../chunks/grants-BsD-WlLE.mjs";
|
|
2
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
3
|
+
import { isRecord } from "@plitzi/sdk-shared/helpers";
|
|
4
|
+
import { accessRefusal } from "@plitzi/sdk-shared/actions";
|
|
5
|
+
import { fleetStore, frameText, onAbort, openEventStream, requestOrigin } from "@plitzi/sdk-kernel/http";
|
|
6
|
+
import { readCookies } from "@plitzi/sdk-kernel/identity";
|
|
7
|
+
import { JOB_TYPE, JOIN_TYPE, LEAVE_TYPE, OBSERVER_COOKIE_NAME, PRESENCE_TYPE, REVOKED_TYPE, channelLimits, jobOfTopic, jobTopic, matchChannel } from "@plitzi/sdk-shared/realtime";
|
|
8
|
+
import { createMemoryPubSub } from "@plitzi/sdk-kernel/pubsub";
|
|
9
|
+
// src/realtime/failure.ts
|
|
10
|
+
/**
|
|
11
|
+
* What a realtime promise nobody waits on does when the pub/sub under it fails — Redis timing out under load: it says so
|
|
12
|
+
* and the server goes on. Left to reject, it reached the process's `unhandledRejection` handler, which shuts the whole
|
|
13
|
+
* server down over one undelivered cursor.
|
|
14
|
+
*/
|
|
15
|
+
var warnRealtime = (what) => (error) => {
|
|
16
|
+
console.warn(`[Realtime] ${what}:`, error instanceof Error ? error.message : error);
|
|
17
|
+
};
|
|
18
|
+
// src/realtime/message.ts
|
|
19
|
+
/** A message as a transport or a store carried it — written by this module, but read from something that is not. */
|
|
20
|
+
var isMessage = (value) => typeof value === "object" && value !== null && "topic" in value && typeof value.topic === "string" && "type" in value && typeof value.type === "string" && "from" in value && typeof value.from === "string" && "at" in value && typeof value.at === "number";
|
|
21
|
+
// src/realtime/presence.ts
|
|
22
|
+
/** How often a replica says its members are still there: a connection open for hours is seen every this often. */
|
|
23
|
+
var PRESENCE_HEARTBEAT_MS = 3e4;
|
|
24
|
+
/** A member not seen this long is gone — its replica went down without saying it: three heartbeats missed. */
|
|
25
|
+
var PRESENCE_STALE_MS = 3 * PRESENCE_HEARTBEAT_MS;
|
|
26
|
+
/** How many times a write is tried while other writes on the same topic keep landing first. */
|
|
27
|
+
var ATTEMPTS$1 = 8;
|
|
28
|
+
var isMember = (value) => isRecord(value) && typeof value.from === "string" && typeof value.since === "number" && typeof value.seenAt === "number" && (value.user === void 0 || isRecord(value.user));
|
|
29
|
+
/** A topic's members, as stored — read from a store something else could have written. */
|
|
30
|
+
var parseKept$1 = (raw) => {
|
|
31
|
+
try {
|
|
32
|
+
const value = JSON.parse(raw ?? "{}");
|
|
33
|
+
return isRecord(value) ? Object.fromEntries(Object.entries(value).filter((entry) => isMember(entry[1]))) : {};
|
|
34
|
+
} catch {
|
|
35
|
+
return {};
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
var fresh = (kept, now) => Object.fromEntries(Object.entries(kept).filter(([, member]) => now - member.seenAt < PRESENCE_STALE_MS));
|
|
39
|
+
/**
|
|
40
|
+
* Who is on each presence channel, kept where the actions keep their `kv` — beside the grants and what `retain` keeps —
|
|
41
|
+
* so a function on one replica counts the pages connected to all of them (`ctx.presence`). A page counted by its own
|
|
42
|
+
* replica alone answered a room of three as one (a run's listeners, counted by the pages' own heartbeats in kv).
|
|
43
|
+
*
|
|
44
|
+
* One value per topic, written by compare-and-swap; each member carries when its replica last saw it, so one that went
|
|
45
|
+
* down without a word stops counting within {@link PRESENCE_STALE_MS}, and is dropped at the next write.
|
|
46
|
+
*/
|
|
47
|
+
var createRealtimePresence = (store, now = Date.now) => {
|
|
48
|
+
const key = ({ spaceId, environment }, topic) => `realtime-presence:${String(spaceId)}:${environment}:${topic}`;
|
|
49
|
+
const change = async (space, topic, next) => {
|
|
50
|
+
const at = key(space, topic);
|
|
51
|
+
for (let attempt = 0; attempt < ATTEMPTS$1; attempt += 1) {
|
|
52
|
+
const raw = await store.get(at);
|
|
53
|
+
const written = JSON.stringify(next(fresh(parseKept$1(raw), now())));
|
|
54
|
+
if (await store.swap(at, raw, written, Math.ceil(90))) return;
|
|
55
|
+
}
|
|
56
|
+
throw new Error(`"${topic}" changed under ${String(ATTEMPTS$1)} writes in a row: its presence was not recorded`);
|
|
57
|
+
};
|
|
58
|
+
return {
|
|
59
|
+
touch: (space, topic, members) => change(space, topic, (kept) => ({
|
|
60
|
+
...kept,
|
|
61
|
+
...Object.fromEntries(members.map((member) => [member.from, {
|
|
62
|
+
...kept[member.from] ?? member,
|
|
63
|
+
seenAt: now()
|
|
64
|
+
}]))
|
|
65
|
+
})),
|
|
66
|
+
depart: (space, topic, from) => change(space, topic, (kept) => Object.fromEntries(Object.entries(kept).filter(([name]) => name !== from))),
|
|
67
|
+
of: async (space, topic) => Object.values(fresh(parseKept$1(await store.get(key(space, topic))), now())).map((member) => ({
|
|
68
|
+
from: member.from,
|
|
69
|
+
since: member.since,
|
|
70
|
+
...member.user ? { user: member.user } : {}
|
|
71
|
+
})).sort((a, b) => a.since - b.since)
|
|
72
|
+
};
|
|
73
|
+
};
|
|
74
|
+
// src/realtime/hub.ts
|
|
75
|
+
/** A space's topic, as the adapter knows it: namespaced, so two spaces never hear each other. */
|
|
76
|
+
var adapterTopic = ({ spaceId, environment }, topic) => `${spaceId}/${environment}/${topic}`;
|
|
77
|
+
/**
|
|
78
|
+
* Said between the servers, never to a page: every connection opened with the grant it names — or, naming none, with
|
|
79
|
+
* any grant for the topic — is let go of it. On the topic's own adapter channel, so it reaches every replica holding
|
|
80
|
+
* the topic, and only them. A page cannot send it: the types a page or a flow may use have no `$` but `$presence`.
|
|
81
|
+
*/
|
|
82
|
+
var REVOKE_TYPE = "$revoke";
|
|
83
|
+
var revokedGrant = (data) => typeof data === "object" && data !== null && "grant" in data && typeof data.grant === "string" ? data.grant : void 0;
|
|
84
|
+
var parse$1 = (raw) => {
|
|
85
|
+
try {
|
|
86
|
+
const value = JSON.parse(raw);
|
|
87
|
+
return isMessage(value) ? value : void 0;
|
|
88
|
+
} catch {
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
/**
|
|
93
|
+
* This process's connections, and the ONE adapter subscription per topic they share.
|
|
94
|
+
*
|
|
95
|
+
* A hundred pages on one board are a hundred connections here and a single subscription to the adapter: a message
|
|
96
|
+
* arrives once and is written to each of them. The last one to leave a topic unsubscribes it.
|
|
97
|
+
*/
|
|
98
|
+
var createRealtimeHub = (pubsub, retained, presence) => {
|
|
99
|
+
const byToken = /* @__PURE__ */ new Map();
|
|
100
|
+
/** The presence topics a connection is counted on: those of a `presence: true` channel, for a page that is not watching. */
|
|
101
|
+
const counted = (connection) => connection.observer ? [] : [...connection.topics].flatMap(([topic, declaration]) => declaration.presence ? [topic] : []);
|
|
102
|
+
const memberOf = (connection) => ({
|
|
103
|
+
from: connection.id,
|
|
104
|
+
...connection.user ? { user: connection.user } : {},
|
|
105
|
+
since: Date.now()
|
|
106
|
+
});
|
|
107
|
+
const heartbeat = presence ? setInterval(() => {
|
|
108
|
+
const byTopic = /* @__PURE__ */ new Map();
|
|
109
|
+
for (const connection of byToken.values()) for (const topic of counted(connection)) {
|
|
110
|
+
const key = adapterTopic(connection.space, topic);
|
|
111
|
+
const entry = byTopic.get(key) ?? {
|
|
112
|
+
space: connection.space,
|
|
113
|
+
topic,
|
|
114
|
+
members: []
|
|
115
|
+
};
|
|
116
|
+
entry.members.push(memberOf(connection));
|
|
117
|
+
byTopic.set(key, entry);
|
|
118
|
+
}
|
|
119
|
+
for (const { space, topic, members } of byTopic.values()) presence.touch(space, topic, members).catch(warnRealtime(`"${topic}"'s presence was not refreshed`));
|
|
120
|
+
}, PRESENCE_HEARTBEAT_MS) : void 0;
|
|
121
|
+
heartbeat?.unref();
|
|
122
|
+
const local = /* @__PURE__ */ new Map();
|
|
123
|
+
const publish = (space, message) => pubsub.publish(adapterTopic(space, message.topic), JSON.stringify(message));
|
|
124
|
+
const join = async (connection, topic) => {
|
|
125
|
+
const key = adapterTopic(connection.space, topic);
|
|
126
|
+
let entry = local.get(key);
|
|
127
|
+
if (!entry) {
|
|
128
|
+
const connections = /* @__PURE__ */ new Set();
|
|
129
|
+
entry = {
|
|
130
|
+
connections,
|
|
131
|
+
release: pubsub.subscribe(key, (raw) => {
|
|
132
|
+
const message = parse$1(raw);
|
|
133
|
+
if (message?.type === REVOKE_TYPE) {
|
|
134
|
+
const grant = revokedGrant(message.data);
|
|
135
|
+
[...connections].filter((member) => {
|
|
136
|
+
const opened = member.grants.get(message.topic);
|
|
137
|
+
return opened !== void 0 && (grant === void 0 || opened === grant);
|
|
138
|
+
}).forEach((member) => {
|
|
139
|
+
releaseTopic(member, message.topic).catch(warnRealtime(`"${message.topic}" was not let go`));
|
|
140
|
+
});
|
|
141
|
+
} else if (message) connections.forEach((member) => member.send("message", message));
|
|
142
|
+
})
|
|
143
|
+
};
|
|
144
|
+
local.set(key, entry);
|
|
145
|
+
}
|
|
146
|
+
entry.connections.add(connection);
|
|
147
|
+
await entry.release;
|
|
148
|
+
};
|
|
149
|
+
const leave = async (connection, topic) => {
|
|
150
|
+
const key = adapterTopic(connection.space, topic);
|
|
151
|
+
const entry = local.get(key);
|
|
152
|
+
if (!entry) return;
|
|
153
|
+
entry.connections.delete(connection);
|
|
154
|
+
if (entry.connections.size === 0) {
|
|
155
|
+
local.delete(key);
|
|
156
|
+
await (await entry.release)();
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
/**
|
|
160
|
+
* A stamped message from this connection: `from` and `user` are the server's, whatever was sent. `echo` carries the
|
|
161
|
+
* sender's asking to hear it too, which its page reads.
|
|
162
|
+
*/
|
|
163
|
+
const from = (connection, topic, type, data, echo = false) => ({
|
|
164
|
+
topic,
|
|
165
|
+
type,
|
|
166
|
+
data,
|
|
167
|
+
from: connection.id,
|
|
168
|
+
...connection.user ? { user: connection.user } : {},
|
|
169
|
+
at: Date.now(),
|
|
170
|
+
...echo ? { echo: true } : {}
|
|
171
|
+
});
|
|
172
|
+
/**
|
|
173
|
+
* Lets `connection` go of `topic`: it is told, the others on a presence channel hear it leave, and it no longer
|
|
174
|
+
* hears the topic or may send on it.
|
|
175
|
+
*/
|
|
176
|
+
const releaseTopic = async (connection, topic) => {
|
|
177
|
+
connection.send("message", {
|
|
178
|
+
topic,
|
|
179
|
+
type: REVOKED_TYPE,
|
|
180
|
+
data: null,
|
|
181
|
+
from: "server",
|
|
182
|
+
at: Date.now()
|
|
183
|
+
});
|
|
184
|
+
connection.topics.delete(topic);
|
|
185
|
+
connection.grants.delete(topic);
|
|
186
|
+
await leave(connection, topic);
|
|
187
|
+
if (connection.announced.delete(topic)) await publish(connection.space, from(connection, topic, LEAVE_TYPE, null));
|
|
188
|
+
};
|
|
189
|
+
return {
|
|
190
|
+
publish,
|
|
191
|
+
from,
|
|
192
|
+
find: (token) => byToken.get(token),
|
|
193
|
+
/**
|
|
194
|
+
* Lets go of `topic` every connection, on every replica, that opened it with `grant` — or with any grant, naming
|
|
195
|
+
* none. What stops a grant that is already in use; `grants.revoke` is what stops it being used again.
|
|
196
|
+
*/
|
|
197
|
+
revoke: (space, topic, grant) => publish(space, {
|
|
198
|
+
topic,
|
|
199
|
+
type: REVOKE_TYPE,
|
|
200
|
+
data: grant === void 0 ? null : { grant },
|
|
201
|
+
from: "server",
|
|
202
|
+
at: Date.now()
|
|
203
|
+
}),
|
|
204
|
+
/**
|
|
205
|
+
* Subscribes a new connection to its topics, hands it what each `retain: true` one keeps, and tells the members of
|
|
206
|
+
* each presence channel it arrived. What is kept is read AFTER joining, so nothing said in between is missed; a
|
|
207
|
+
* message heard live and then kept arrives twice, and the page keeps the newer of a type by its `at`. Each kept one
|
|
208
|
+
* is `replayed`: a page that joins tells it from what is said now.
|
|
209
|
+
*/
|
|
210
|
+
connect: async (connection) => {
|
|
211
|
+
byToken.set(connection.token, connection);
|
|
212
|
+
for (const [topic, declaration] of connection.topics) {
|
|
213
|
+
await join(connection, topic);
|
|
214
|
+
if (declaration.retain === true) (await retained.of(connection.space, topic)).forEach((message) => connection.send("message", {
|
|
215
|
+
...message,
|
|
216
|
+
replayed: true
|
|
217
|
+
}));
|
|
218
|
+
if (declaration.presence && !connection.observer) {
|
|
219
|
+
await publish(connection.space, from(connection, topic, JOIN_TYPE, null));
|
|
220
|
+
await presence?.touch(connection.space, topic, [memberOf(connection)]).catch(warnRealtime(`"${topic}"'s presence was not recorded`));
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
},
|
|
224
|
+
/** Unsubscribes a connection that went away, and tells the channels it announced itself on. */
|
|
225
|
+
disconnect: async (connection) => {
|
|
226
|
+
byToken.delete(connection.token);
|
|
227
|
+
for (const topic of counted(connection)) await presence?.depart(connection.space, topic, connection.id).catch(warnRealtime(`"${topic}"'s presence was not let go of`));
|
|
228
|
+
for (const topic of connection.topics.keys()) {
|
|
229
|
+
if (connection.announced.has(topic)) await publish(connection.space, from(connection, topic, LEAVE_TYPE, null));
|
|
230
|
+
await leave(connection, topic);
|
|
231
|
+
}
|
|
232
|
+
},
|
|
233
|
+
/**
|
|
234
|
+
* Every connection closed from here: the server is shutting down. An open socket or event stream is a request that
|
|
235
|
+
* never ends, so a server waiting for them to finish waited for ever — each is told to go, and goes the way it
|
|
236
|
+
* goes when its page leaves.
|
|
237
|
+
*/
|
|
238
|
+
closeAll: () => {
|
|
239
|
+
clearInterval(heartbeat);
|
|
240
|
+
[...byToken.values()].forEach((connection) => connection.end());
|
|
241
|
+
},
|
|
242
|
+
/** How many connections this process holds — for tests and for a health endpoint. */
|
|
243
|
+
get connectionCount() {
|
|
244
|
+
return byToken.size;
|
|
245
|
+
},
|
|
246
|
+
/** How many topics this process holds a subscription for — for tests and for a health endpoint. */
|
|
247
|
+
get topicCount() {
|
|
248
|
+
return local.size;
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
};
|
|
252
|
+
// src/realtime/jobs.ts
|
|
253
|
+
/** A job's topic, as a channel: the server alone says how the job goes, and a page that joins hears the latest. */
|
|
254
|
+
var JOB_CHANNEL = {
|
|
255
|
+
access: { mode: "session" },
|
|
256
|
+
publish: "server",
|
|
257
|
+
retain: true
|
|
258
|
+
};
|
|
259
|
+
/** How long a job's topic is kept after it last changed: as long as the queue keeps a finished job readable. */
|
|
260
|
+
var JOB_RETAINED_SECONDS = 2592e3;
|
|
261
|
+
/**
|
|
262
|
+
* Why a page may not watch a job, or nothing when it may: whoever started it always does, and anyone else as the
|
|
263
|
+
* job's `watch` says — a channel's access, read against the visitor's permissions in the space. A job of another space,
|
|
264
|
+
* or none by that id, is no topic at all.
|
|
265
|
+
*/
|
|
266
|
+
var jobRefusal = async (lookup, spaceId, jobId, user) => {
|
|
267
|
+
const target = (lookup ? await lookup(spaceId, jobId) : void 0)?.target;
|
|
268
|
+
if (target?.kind !== "function") return "undeclared";
|
|
269
|
+
if (user && target.user?.id === user.id) return;
|
|
270
|
+
if (!target.watch) return user ? "forbidden" : "unauthenticated";
|
|
271
|
+
return accessRefusal(target.watch, user);
|
|
272
|
+
};
|
|
273
|
+
/**
|
|
274
|
+
* Says a job as it is now on its topic, kept for a page that joins later — the one way it is said, by the page server's
|
|
275
|
+
* realtime and by an operator's panel in a process of its own alike.
|
|
276
|
+
*/
|
|
277
|
+
var publishJobView = async (hub, retained, space, jobId, view) => {
|
|
278
|
+
const message = {
|
|
279
|
+
topic: jobTopic(jobId),
|
|
280
|
+
type: JOB_TYPE,
|
|
281
|
+
data: view,
|
|
282
|
+
from: "server",
|
|
283
|
+
at: Date.now(),
|
|
284
|
+
retained: true
|
|
285
|
+
};
|
|
286
|
+
await retained.keep(space, message, JOB_RETAINED_SECONDS);
|
|
287
|
+
await hub.publish(space, message);
|
|
288
|
+
};
|
|
289
|
+
// src/realtime/retained.ts
|
|
290
|
+
/** The most types one topic keeps: state a page shows, never a log written one type per entry. */
|
|
291
|
+
var MAX_RETAINED_TYPES = 64;
|
|
292
|
+
/** The most one topic keeps, as JSON: every page that joins is sent all of it. */
|
|
293
|
+
var MAX_RETAINED_BYTES = 524288;
|
|
294
|
+
/** How many times a write is tried while other writes on the same topic keep landing first. */
|
|
295
|
+
var ATTEMPTS = 8;
|
|
296
|
+
/** A topic's kept messages, by type, as stored — read from a store something else could have written. */
|
|
297
|
+
var parseKept = (raw) => {
|
|
298
|
+
try {
|
|
299
|
+
const value = JSON.parse(raw ?? "{}");
|
|
300
|
+
if (typeof value !== "object" || value === null) return {};
|
|
301
|
+
return Object.fromEntries(Object.entries(value).filter((entry) => isMessage(entry[1])));
|
|
302
|
+
} catch {
|
|
303
|
+
return {};
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
/**
|
|
307
|
+
* The messages of `retain: true` channels, kept in the store the actions' `kv` uses — beside the grants, so one replica
|
|
308
|
+
* keeps what another hands a page that joins, and nothing new has to be configured for it.
|
|
309
|
+
*
|
|
310
|
+
* One value per topic, written by compare-and-swap: two types said at once on one topic are both kept, never one
|
|
311
|
+
* written over the other. Keyed under `realtime-retained:`, which no key a flow writes can reach.
|
|
312
|
+
*/
|
|
313
|
+
var createRealtimeRetained = (store) => {
|
|
314
|
+
const key = ({ spaceId, environment }, topic) => `realtime-retained:${String(spaceId)}:${environment}:${topic}`;
|
|
315
|
+
return {
|
|
316
|
+
keep: async (space, message, ttlSeconds) => {
|
|
317
|
+
const at = key(space, message.topic);
|
|
318
|
+
for (let attempt = 0; attempt < ATTEMPTS; attempt += 1) {
|
|
319
|
+
const raw = await store.get(at);
|
|
320
|
+
const kept = parseKept(raw);
|
|
321
|
+
const others = Object.fromEntries(Object.entries(kept).filter(([type]) => type !== message.type));
|
|
322
|
+
const next = message.data === null ? others : {
|
|
323
|
+
...others,
|
|
324
|
+
[message.type]: message
|
|
325
|
+
};
|
|
326
|
+
if (Object.keys(next).length > MAX_RETAINED_TYPES) throw new Error(`"${message.topic}" keeps at most ${String(MAX_RETAINED_TYPES)} types of message: keep fewer, larger ones (one \`lists\` holding every list), or forget one with null`);
|
|
327
|
+
const written = JSON.stringify(next);
|
|
328
|
+
if (Buffer.byteLength(written) > MAX_RETAINED_BYTES) throw new Error(`"${message.topic}" keeps at most ${String(MAX_RETAINED_BYTES / 1024)} KB, and "${message.type}" would take it past that: every page that joins is sent all of it — keep there what the screens show, the rest in kv`);
|
|
329
|
+
if (await store.swap(at, raw, written, ttlSeconds)) return;
|
|
330
|
+
}
|
|
331
|
+
throw new Error(`"${message.topic}" changed under ${String(ATTEMPTS)} writes in a row, so "${message.type}" was not kept: publish it again`);
|
|
332
|
+
},
|
|
333
|
+
of: async (space, topic) => Object.values(parseKept(await store.get(key(space, topic)))).sort((a, b) => a.at - b.at)
|
|
334
|
+
};
|
|
335
|
+
};
|
|
336
|
+
// src/realtime/declarations.ts
|
|
337
|
+
/** How long a space's channels are remembered: a publish is frequent, and a space's settings change rarely. */
|
|
338
|
+
var TTL_MS = 5e3;
|
|
339
|
+
/**
|
|
340
|
+
* The channels a space declares, read from its schema and remembered for a few seconds.
|
|
341
|
+
*
|
|
342
|
+
* A publish is checked against them on every message; reading the space's documents for each one would cost more
|
|
343
|
+
* than the message. A space that changes its channels is heard within the TTL.
|
|
344
|
+
*/
|
|
345
|
+
var createChannelResolver = (getOfflineData) => {
|
|
346
|
+
const cache = /* @__PURE__ */ new Map();
|
|
347
|
+
return (spaceId, environment, revision) => {
|
|
348
|
+
const key = `${spaceId}:${environment}:${revision ?? ""}`;
|
|
349
|
+
const hit = cache.get(key);
|
|
350
|
+
if (hit && Date.now() - hit.at < TTL_MS) return hit.channels;
|
|
351
|
+
const channels = getOfflineData(spaceId, environment, revision).then((data) => data?.schema.settings.channels);
|
|
352
|
+
cache.set(key, {
|
|
353
|
+
at: Date.now(),
|
|
354
|
+
channels
|
|
355
|
+
});
|
|
356
|
+
channels.catch(() => cache.delete(key));
|
|
357
|
+
return channels;
|
|
358
|
+
};
|
|
359
|
+
};
|
|
360
|
+
// src/realtime/handlers.ts
|
|
361
|
+
/** Topics one connection may hold. A page shows a handful; past this it is somebody enumerating. */
|
|
362
|
+
var MAX_TOPICS = 8;
|
|
363
|
+
/** A type a page may send: its own vocabulary, never one of the channel's `$` types but `$presence`. */
|
|
364
|
+
var TYPE = /^[A-Za-z0-9_.:-]{1,64}$/;
|
|
365
|
+
/** How long a disconnected client waits before trying again — ours reconnects itself; this is for anyone else's. */
|
|
366
|
+
var RETRY_MS = 3e3;
|
|
367
|
+
var answer = (res, { status, ...payload }) => {
|
|
368
|
+
res.setStatus(status);
|
|
369
|
+
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
370
|
+
res.setHeader("Cache-Control", "no-store");
|
|
371
|
+
res.send(JSON.stringify(payload));
|
|
372
|
+
};
|
|
373
|
+
var listOf = (query, name) => [...new Set((Object.hasOwn(query, name) ? query[name] : "").split(",").map((item) => item.trim()).filter(Boolean))];
|
|
374
|
+
/** The one of the grants the page sent (`?grants=g1,g2`) that opens `topic` — or none. */
|
|
375
|
+
var grantFor = async (grants, space, topic, offered) => {
|
|
376
|
+
for (const grant of offered) if (await grants.opens(space, topic, grant)) return grant;
|
|
377
|
+
};
|
|
378
|
+
/**
|
|
379
|
+
* Which of the topics a page asked for (`?topics=a,b`) it may open: each checked against the channels the space
|
|
380
|
+
* declares and against the visitor's access. One that fails is reported, not a reason to refuse the rest; all failing
|
|
381
|
+
* is a `403`.
|
|
382
|
+
*/
|
|
383
|
+
var admit = async (req, resolveChannels, grants, jobs, admitSpace) => {
|
|
384
|
+
const { environment = "main", spaceId, revision } = req.ctx.spaceDeployment ?? {};
|
|
385
|
+
if (typeof spaceId !== "number") return {
|
|
386
|
+
ok: false,
|
|
387
|
+
answer: {
|
|
388
|
+
status: 404,
|
|
389
|
+
error: "No space is served here",
|
|
390
|
+
reason: "not_found"
|
|
391
|
+
}
|
|
392
|
+
};
|
|
393
|
+
const requested = listOf(req.query, "topics");
|
|
394
|
+
const offered = listOf(req.query, "grants").slice(0, MAX_TOPICS);
|
|
395
|
+
if (requested.length === 0 || requested.length > MAX_TOPICS) return {
|
|
396
|
+
ok: false,
|
|
397
|
+
answer: {
|
|
398
|
+
status: 422,
|
|
399
|
+
error: `Name between 1 and ${MAX_TOPICS} topics: ?topics=a,b`,
|
|
400
|
+
reason: "invalid_input"
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
const channels = await resolveChannels(spaceId, environment, revision);
|
|
404
|
+
const spaceRefusal = await admitSpace?.(spaceId);
|
|
405
|
+
const accepted = /* @__PURE__ */ new Map();
|
|
406
|
+
const granted = /* @__PURE__ */ new Map();
|
|
407
|
+
const refused = [];
|
|
408
|
+
const space = {
|
|
409
|
+
spaceId,
|
|
410
|
+
environment
|
|
411
|
+
};
|
|
412
|
+
for (const topic of requested) {
|
|
413
|
+
const jobId = jobOfTopic(topic);
|
|
414
|
+
if (jobId !== void 0) {
|
|
415
|
+
const refusal = await jobRefusal(jobs, spaceId, jobId, req.ctx.user);
|
|
416
|
+
if (refusal) refused.push({
|
|
417
|
+
topic,
|
|
418
|
+
reason: refusal
|
|
419
|
+
});
|
|
420
|
+
else accepted.set(topic, JOB_CHANNEL);
|
|
421
|
+
continue;
|
|
422
|
+
}
|
|
423
|
+
if (spaceRefusal !== void 0) {
|
|
424
|
+
refused.push({
|
|
425
|
+
topic,
|
|
426
|
+
reason: "unavailable"
|
|
427
|
+
});
|
|
428
|
+
continue;
|
|
429
|
+
}
|
|
430
|
+
const match = matchChannel(topic, channels);
|
|
431
|
+
const refusal = match ? accessRefusal(match.declaration.access, req.ctx.user) : "undeclared";
|
|
432
|
+
const grant = match && !refusal && match.declaration.grant === true ? await grantFor(grants, space, topic, offered) : void 0;
|
|
433
|
+
if (!match || refusal) refused.push({
|
|
434
|
+
topic,
|
|
435
|
+
reason: refusal ?? "undeclared"
|
|
436
|
+
});
|
|
437
|
+
else if (match.declaration.grant === true && grant === void 0) refused.push({
|
|
438
|
+
topic,
|
|
439
|
+
reason: "ungranted"
|
|
440
|
+
});
|
|
441
|
+
else {
|
|
442
|
+
accepted.set(topic, match.declaration);
|
|
443
|
+
if (grant !== void 0) granted.set(topic, grant);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
if (accepted.size === 0 && spaceRefusal !== void 0) return {
|
|
447
|
+
ok: false,
|
|
448
|
+
answer: {
|
|
449
|
+
status: 402,
|
|
450
|
+
error: spaceRefusal,
|
|
451
|
+
reason: "unavailable",
|
|
452
|
+
refused
|
|
453
|
+
}
|
|
454
|
+
};
|
|
455
|
+
if (accepted.size === 0) return {
|
|
456
|
+
ok: false,
|
|
457
|
+
answer: {
|
|
458
|
+
status: 403,
|
|
459
|
+
error: "None of these topics may be opened here",
|
|
460
|
+
reason: "forbidden",
|
|
461
|
+
refused
|
|
462
|
+
}
|
|
463
|
+
};
|
|
464
|
+
const { user } = req.ctx;
|
|
465
|
+
return {
|
|
466
|
+
ok: true,
|
|
467
|
+
space,
|
|
468
|
+
...user ? { user: {
|
|
469
|
+
id: user.id,
|
|
470
|
+
name: user.username
|
|
471
|
+
} } : {},
|
|
472
|
+
accepted,
|
|
473
|
+
granted,
|
|
474
|
+
refused,
|
|
475
|
+
observer: Object.hasOwn(readCookies(req), OBSERVER_COOKIE_NAME)
|
|
476
|
+
};
|
|
477
|
+
};
|
|
478
|
+
/** A new connection for what was admitted, speaking through `send`. */
|
|
479
|
+
var connectionFor = (admission, send, end) => ({
|
|
480
|
+
id: randomUUID(),
|
|
481
|
+
token: randomBytes(24).toString("base64url"),
|
|
482
|
+
space: admission.space,
|
|
483
|
+
...admission.user ? { user: admission.user } : {},
|
|
484
|
+
topics: admission.accepted,
|
|
485
|
+
grants: admission.granted,
|
|
486
|
+
announced: /* @__PURE__ */ new Set(),
|
|
487
|
+
observer: admission.observer,
|
|
488
|
+
sent: /* @__PURE__ */ new Map(),
|
|
489
|
+
send,
|
|
490
|
+
end
|
|
491
|
+
});
|
|
492
|
+
/** Whether this connection may send one more message on `topic` this second. */
|
|
493
|
+
var withinRate = (connection, topic, perSecond) => {
|
|
494
|
+
const second = Math.floor(Date.now() / 1e3);
|
|
495
|
+
const sent = connection.sent.get(topic);
|
|
496
|
+
const count = sent?.second === second ? sent.count + 1 : 1;
|
|
497
|
+
connection.sent.set(topic, {
|
|
498
|
+
second,
|
|
499
|
+
count
|
|
500
|
+
});
|
|
501
|
+
return count <= perSecond;
|
|
502
|
+
};
|
|
503
|
+
/**
|
|
504
|
+
* A page publishing, whichever way it arrived: only on a topic its connection subscribed to, only on a channel pages
|
|
505
|
+
* may send on, within its size and its rate — and stamped by the server with who sent it and when, whatever the
|
|
506
|
+
* message said.
|
|
507
|
+
*/
|
|
508
|
+
var publishFrom = async (hub, connection, { topic, type, data, echo }) => {
|
|
509
|
+
const name = typeof topic === "string" ? topic : "";
|
|
510
|
+
const declaration = connection.topics.get(name);
|
|
511
|
+
if (!declaration) return {
|
|
512
|
+
status: 403,
|
|
513
|
+
error: `This connection did not subscribe to "${name}"`,
|
|
514
|
+
reason: "not_subscribed"
|
|
515
|
+
};
|
|
516
|
+
if (declaration.publish === "server") return {
|
|
517
|
+
status: 403,
|
|
518
|
+
error: `Only the server publishes on "${name}"`,
|
|
519
|
+
reason: "server_only"
|
|
520
|
+
};
|
|
521
|
+
if (connection.observer) return { status: 204 };
|
|
522
|
+
const kind = typeof type === "string" ? type : "";
|
|
523
|
+
const presence = kind === PRESENCE_TYPE && declaration.presence === true;
|
|
524
|
+
if (!presence && !TYPE.test(kind)) return {
|
|
525
|
+
status: 422,
|
|
526
|
+
error: "A message type is 1-64 of A-Z a-z 0-9 _ . : -",
|
|
527
|
+
reason: "invalid_input"
|
|
528
|
+
};
|
|
529
|
+
const limits = channelLimits(declaration);
|
|
530
|
+
const value = data ?? null;
|
|
531
|
+
if (Buffer.byteLength(JSON.stringify(value)) > limits.maxMessageBytes) return {
|
|
532
|
+
status: 413,
|
|
533
|
+
error: `A message on "${name}" is at most ${limits.maxMessageBytes} bytes`,
|
|
534
|
+
reason: "too_large"
|
|
535
|
+
};
|
|
536
|
+
if (!withinRate(connection, name, limits.messagesPerSecond)) return {
|
|
537
|
+
status: 429,
|
|
538
|
+
error: `At most ${limits.messagesPerSecond} messages a second`,
|
|
539
|
+
reason: "rate_limited"
|
|
540
|
+
};
|
|
541
|
+
if (presence) connection.announced.add(name);
|
|
542
|
+
try {
|
|
543
|
+
await hub.publish(connection.space, hub.from(connection, name, kind, value, echo === true && !presence));
|
|
544
|
+
} catch (error) {
|
|
545
|
+
warnRealtime("a message was not delivered")(error);
|
|
546
|
+
return {
|
|
547
|
+
status: 503,
|
|
548
|
+
error: "The message was not delivered: send it again",
|
|
549
|
+
reason: "unavailable"
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
return { status: 204 };
|
|
553
|
+
};
|
|
554
|
+
/**
|
|
555
|
+
* `GET /_realtime?topics=a,b` (and `&grants=g1,g2` for the topics of a `grant: true` channel) — one Server-Sent Events connection for every topic a page listens to.
|
|
556
|
+
*
|
|
557
|
+
* The first event, `ready`, tells the page its public name (`from`) and the secret its publishes carry. Resolves when
|
|
558
|
+
* the page goes.
|
|
559
|
+
*/
|
|
560
|
+
var handleRealtimeSubscribe = async ({ req, res, raw, signal, hub, resolveChannels, grants, jobs, admitSpace }) => {
|
|
561
|
+
const admission = await admit(req, resolveChannels, grants, jobs, admitSpace);
|
|
562
|
+
if (!admission.ok) {
|
|
563
|
+
answer(res, admission.answer);
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
566
|
+
let finish = () => void 0;
|
|
567
|
+
const gone = new Promise((resolve) => {
|
|
568
|
+
finish = resolve;
|
|
569
|
+
});
|
|
570
|
+
const stream = openEventStream(raw, {
|
|
571
|
+
onAbort: () => finish(),
|
|
572
|
+
retryMs: RETRY_MS
|
|
573
|
+
});
|
|
574
|
+
const connection = connectionFor(admission, stream.send, () => finish());
|
|
575
|
+
const release = onAbort(signal, () => finish());
|
|
576
|
+
stream.send("ready", {
|
|
577
|
+
connection: connection.id,
|
|
578
|
+
token: connection.token,
|
|
579
|
+
topics: [...admission.accepted.keys()],
|
|
580
|
+
refused: admission.refused
|
|
581
|
+
});
|
|
582
|
+
await hub.connect(connection).catch(warnRealtime("a connection was not announced"));
|
|
583
|
+
await gone;
|
|
584
|
+
release();
|
|
585
|
+
stream.close();
|
|
586
|
+
await hub.disconnect(connection).catch(warnRealtime("a connection was not let go"));
|
|
587
|
+
};
|
|
588
|
+
var parseBody = (body) => {
|
|
589
|
+
try {
|
|
590
|
+
const value = body ? JSON.parse(body) : void 0;
|
|
591
|
+
return typeof value === "object" && value !== null ? value : void 0;
|
|
592
|
+
} catch {
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
};
|
|
596
|
+
/** `POST /_realtime` `{ token, topic, type, data }` — a page on a Server-Sent Events connection, publishing. */
|
|
597
|
+
var handleRealtimePublish = async ({ req, res, hub }) => {
|
|
598
|
+
const body = parseBody(req.body);
|
|
599
|
+
const connection = typeof body?.token === "string" ? hub.find(body.token) : void 0;
|
|
600
|
+
if (!body || !connection) {
|
|
601
|
+
answer(res, {
|
|
602
|
+
status: 401,
|
|
603
|
+
error: "Not connected: open /_realtime first and publish with its token",
|
|
604
|
+
reason: "not_connected"
|
|
605
|
+
});
|
|
606
|
+
return;
|
|
607
|
+
}
|
|
608
|
+
const result = await publishFrom(hub, connection, body);
|
|
609
|
+
if (result.status === 204) {
|
|
610
|
+
res.setStatus(204);
|
|
611
|
+
res.send("");
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
answer(res, result);
|
|
615
|
+
};
|
|
616
|
+
// src/realtime/socket.ts
|
|
617
|
+
/** The largest frame a page may send: well above the largest message a channel may declare, and bounded. */
|
|
618
|
+
var MAX_FRAME_BYTES = 262144;
|
|
619
|
+
/**
|
|
620
|
+
* What may wait in a socket's buffer for a page that stopped reading. Past it the page is gone in all but name, and
|
|
621
|
+
* holding everything it has not read is how one stalled tab grows a process.
|
|
622
|
+
*/
|
|
623
|
+
var MAX_BUFFERED_BYTES = 1048576;
|
|
624
|
+
/** How often the server asks a socket whether the page behind it is still there — and gives up on one that did not answer the last time. */
|
|
625
|
+
var PING_MS = 25e3;
|
|
626
|
+
var server;
|
|
627
|
+
/**
|
|
628
|
+
* Loaded the first time a page asks for a socket: a server whose pages never do — or that runs behind HTTP/2, where
|
|
629
|
+
* none can — never pays for the module.
|
|
630
|
+
*/
|
|
631
|
+
var socketServer = () => server ??= import("ws").then(({ WebSocketServer: Server }) => new Server({
|
|
632
|
+
noServer: true,
|
|
633
|
+
maxPayload: MAX_FRAME_BYTES
|
|
634
|
+
}));
|
|
635
|
+
/**
|
|
636
|
+
* A browser opens a WebSocket to any address, carrying that address's cookies, from any page — CORS does not apply to
|
|
637
|
+
* it. So a socket is refused unless the page that opened it is on this origin, or on one the deployment lists: without
|
|
638
|
+
* this, another site could open a channel restricted to signed-in visitors with a visitor's session and read it.
|
|
639
|
+
* A client that is not a browser sends no `Origin`, and has no visitor's cookies to borrow.
|
|
640
|
+
*/
|
|
641
|
+
var originAllowed = (raw, req, allowed) => {
|
|
642
|
+
const origin = raw.headers.origin;
|
|
643
|
+
return origin === void 0 || origin === requestOrigin(req) || allowed.includes(origin);
|
|
644
|
+
};
|
|
645
|
+
/** A frame's text, whichever of the shapes `ws` hands a frame over in. */
|
|
646
|
+
var parse = (frame) => {
|
|
647
|
+
try {
|
|
648
|
+
const value = JSON.parse(frameText(frame));
|
|
649
|
+
return typeof value === "object" && value !== null ? value : void 0;
|
|
650
|
+
} catch {
|
|
651
|
+
return;
|
|
652
|
+
}
|
|
653
|
+
};
|
|
654
|
+
/** A publish's id, echoed on its `ack`: what the page matches the answer to. Short, and never anything else. */
|
|
655
|
+
var ackId = (id) => typeof id === "number" && Number.isInteger(id) || typeof id === "string" && id.length <= 64 ? id : void 0;
|
|
656
|
+
/**
|
|
657
|
+
* A page's realtime connection as a WebSocket: the same topics, rules and messages as the Server-Sent Events one, in
|
|
658
|
+
* both directions over one socket. A publish is a frame, not a request — no headers, no second connection, no token
|
|
659
|
+
* to present: the socket is the credential. Its answer arrives as an `ack` carrying the publish's `id`.
|
|
660
|
+
*
|
|
661
|
+
* Refused the way the stream is — a `403` or a `422`, in HTTP, before anything switches — so a page falls back or
|
|
662
|
+
* reports it exactly as it would there.
|
|
663
|
+
*/
|
|
664
|
+
var handleRealtimeSocket = async ({ req, res, raw, upgrade, hub, resolveChannels, grants, allowedOrigins, jobs, admitSpace }) => {
|
|
665
|
+
if (!originAllowed(raw, req, allowedOrigins)) {
|
|
666
|
+
answer(res, {
|
|
667
|
+
status: 403,
|
|
668
|
+
error: "A page of another origin may not open this",
|
|
669
|
+
reason: "foreign"
|
|
670
|
+
});
|
|
671
|
+
return;
|
|
672
|
+
}
|
|
673
|
+
const admission = await admit(req, resolveChannels, grants, jobs, admitSpace);
|
|
674
|
+
if (!admission.ok) {
|
|
675
|
+
answer(res, admission.answer);
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
const sockets = await socketServer();
|
|
679
|
+
upgrade.taken = true;
|
|
680
|
+
res.setStatus(101);
|
|
681
|
+
sockets.handleUpgrade(raw, upgrade.socket, upgrade.head, (socket) => {
|
|
682
|
+
const send = (event, data) => {
|
|
683
|
+
if (socket.readyState !== socket.OPEN) return;
|
|
684
|
+
if (socket.bufferedAmount > MAX_BUFFERED_BYTES) {
|
|
685
|
+
socket.terminate();
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
socket.send(JSON.stringify({
|
|
689
|
+
event,
|
|
690
|
+
data
|
|
691
|
+
}));
|
|
692
|
+
};
|
|
693
|
+
const connection = connectionFor(admission, send, () => socket.close(1001, "The server is going away"));
|
|
694
|
+
let alive = true;
|
|
695
|
+
const heartbeat = setInterval(() => {
|
|
696
|
+
if (!alive) {
|
|
697
|
+
socket.terminate();
|
|
698
|
+
return;
|
|
699
|
+
}
|
|
700
|
+
alive = false;
|
|
701
|
+
socket.ping();
|
|
702
|
+
}, PING_MS);
|
|
703
|
+
socket.on("pong", () => {
|
|
704
|
+
alive = true;
|
|
705
|
+
});
|
|
706
|
+
socket.on("message", (frame, binary) => {
|
|
707
|
+
alive = true;
|
|
708
|
+
const message = binary ? void 0 : parse(frame);
|
|
709
|
+
if (!message) return;
|
|
710
|
+
const id = ackId(message.id);
|
|
711
|
+
publishFrom(hub, connection, message).then((result) => {
|
|
712
|
+
if (id !== void 0) send("ack", {
|
|
713
|
+
id,
|
|
714
|
+
ok: result.status === 204,
|
|
715
|
+
status: result.status,
|
|
716
|
+
...result.reason ? { reason: result.reason } : {}
|
|
717
|
+
});
|
|
718
|
+
});
|
|
719
|
+
});
|
|
720
|
+
socket.on("close", () => {
|
|
721
|
+
clearInterval(heartbeat);
|
|
722
|
+
hub.disconnect(connection).catch(warnRealtime("a connection was not let go"));
|
|
723
|
+
});
|
|
724
|
+
socket.on("error", () => socket.terminate());
|
|
725
|
+
send("ready", {
|
|
726
|
+
connection: connection.id,
|
|
727
|
+
topics: [...admission.accepted.keys()],
|
|
728
|
+
refused: admission.refused
|
|
729
|
+
});
|
|
730
|
+
hub.connect(connection).catch(warnRealtime("a connection was not announced"));
|
|
731
|
+
});
|
|
732
|
+
};
|
|
733
|
+
// src/realtime/index.ts
|
|
734
|
+
/** A type a flow publishes: its own vocabulary — the `$` types are the channel's. */
|
|
735
|
+
/** Where a page's realtime channels are, and how it reaches them, when the deployment says nothing. */
|
|
736
|
+
var DEFAULT_REALTIME_PATH = "/_realtime";
|
|
737
|
+
var DEFAULT_REALTIME_TRANSPORT = "sse";
|
|
738
|
+
var SERVER_TYPE = /^[A-Za-z0-9_.:-]{1,64}$/;
|
|
739
|
+
var modules = /* @__PURE__ */ new WeakMap();
|
|
740
|
+
var createRealtimeModule = (options) => {
|
|
741
|
+
const kv = options.kv ?? createMemoryKv();
|
|
742
|
+
const retained = createRealtimeRetained(kv);
|
|
743
|
+
const presence = createRealtimePresence(kv);
|
|
744
|
+
const hub = createRealtimeHub(options.pubsub ?? createMemoryPubSub(), retained, presence);
|
|
745
|
+
const resolveChannels = createChannelResolver(options.getOfflineData);
|
|
746
|
+
const grants = createRealtimeGrants(kv);
|
|
747
|
+
let jobLookup;
|
|
748
|
+
return {
|
|
749
|
+
hub,
|
|
750
|
+
path: options.path ?? "/_realtime",
|
|
751
|
+
transport: options.transport ?? "sse",
|
|
752
|
+
allowedOrigins: options.allowedOrigins ?? [],
|
|
753
|
+
...options.admitSpace ? { admitSpace: options.admitSpace } : {},
|
|
754
|
+
resolveChannels,
|
|
755
|
+
grants,
|
|
756
|
+
close: () => hub.closeAll(),
|
|
757
|
+
publish: async (space, topic, type, data) => {
|
|
758
|
+
const match = matchChannel(topic, await resolveChannels(space.spaceId, space.environment));
|
|
759
|
+
if (!match) throw new Error(`No channel of this space matches "${topic}": declare it in the space's \`channels\``);
|
|
760
|
+
if (!SERVER_TYPE.test(type)) throw new Error("A message type is 1-64 of A-Z a-z 0-9 _ . : -");
|
|
761
|
+
const retain = match.declaration.retain === true;
|
|
762
|
+
const message = {
|
|
763
|
+
topic,
|
|
764
|
+
type,
|
|
765
|
+
data,
|
|
766
|
+
from: "server",
|
|
767
|
+
at: Date.now(),
|
|
768
|
+
...retain ? { retained: true } : {}
|
|
769
|
+
};
|
|
770
|
+
if (retain) await retained.keep(space, message);
|
|
771
|
+
await hub.publish(space, message);
|
|
772
|
+
},
|
|
773
|
+
presence: async (space, topic) => {
|
|
774
|
+
const match = matchChannel(topic, await resolveChannels(space.spaceId, space.environment));
|
|
775
|
+
if (!match) throw new Error(`No channel of this space matches "${topic}": declare it in the space's \`channels\``);
|
|
776
|
+
if (match.declaration.presence !== true) throw new Error(`"${match.pattern}" counts nobody: declare it \`presence: true\` for its pages to be counted, and read here`);
|
|
777
|
+
const members = await presence.of(space, topic);
|
|
778
|
+
return {
|
|
779
|
+
count: members.length,
|
|
780
|
+
members
|
|
781
|
+
};
|
|
782
|
+
},
|
|
783
|
+
grant: async (space, topic, ttlSeconds) => {
|
|
784
|
+
const match = matchChannel(topic, await resolveChannels(space.spaceId, space.environment));
|
|
785
|
+
if (!match) throw new Error(`No channel of this space matches "${topic}": declare it in the space's \`channels\``);
|
|
786
|
+
if (match.declaration.grant !== true) throw new Error(`"${match.pattern}" is open to anyone its access lets in, so it takes no grant: declare it \`grant: true\` to make its topics private`);
|
|
787
|
+
return grants.issue(space, topic, ttlSeconds);
|
|
788
|
+
},
|
|
789
|
+
revoke: async (space, topic, grant) => {
|
|
790
|
+
if (matchChannel(topic, await resolveChannels(space.spaceId, space.environment))?.declaration.grant !== true) throw new Error(`"${topic}" is not a topic of a private (\`grant: true\`) channel of this space: it has no grants to revoke`);
|
|
791
|
+
await grants.revoke(space, topic, grant);
|
|
792
|
+
await hub.revoke(space, topic, grant);
|
|
793
|
+
},
|
|
794
|
+
publishJob: (space, jobId, view) => publishJobView(hub, retained, space, jobId, view),
|
|
795
|
+
watchJobs: (lookup) => {
|
|
796
|
+
jobLookup = lookup;
|
|
797
|
+
},
|
|
798
|
+
jobs: () => jobLookup
|
|
799
|
+
};
|
|
800
|
+
};
|
|
801
|
+
/**
|
|
802
|
+
* The channels an actions runner that serves no pages publishes on (`createActionsModule({ realtime })`): a job's
|
|
803
|
+
* `ctx.publish`, a flow's `realtime.publish`, a function job's `$job:<id>`. Without them a job that publishes fails on
|
|
804
|
+
* that runner — handed the same `pubsub` and `kv` as the page servers, it reaches every page they hold open.
|
|
805
|
+
*/
|
|
806
|
+
var createActionRealtime = (options) => createRealtimeModule(options);
|
|
807
|
+
var realtimeModuleFor = (config) => {
|
|
808
|
+
const getOfflineData = config.adapters.getOfflineData;
|
|
809
|
+
if (config.realtime === false || !getOfflineData) return;
|
|
810
|
+
const existing = modules.get(config);
|
|
811
|
+
if (existing) return existing;
|
|
812
|
+
const module = createRealtimeModule({
|
|
813
|
+
getOfflineData,
|
|
814
|
+
...config.realtime?.pubsub ? { pubsub: config.realtime.pubsub } : {},
|
|
815
|
+
kv: config.action?.kv ?? fleetStore("realtime.kv", KV_METHODS) ?? createMemoryKv(),
|
|
816
|
+
...config.realtime?.path ? { path: config.realtime.path } : {},
|
|
817
|
+
...config.realtime?.transport ? { transport: config.realtime.transport } : {},
|
|
818
|
+
...config.realtime?.allowedOrigins ? { allowedOrigins: config.realtime.allowedOrigins } : {},
|
|
819
|
+
...config.realtime?.admitSpace ? { admitSpace: config.realtime.admitSpace } : {}
|
|
820
|
+
});
|
|
821
|
+
modules.set(config, module);
|
|
822
|
+
return module;
|
|
823
|
+
};
|
|
824
|
+
export { DEFAULT_REALTIME_PATH, DEFAULT_REALTIME_TRANSPORT, createActionRealtime, createRealtimeModule, handleRealtimePublish, handleRealtimeSocket, handleRealtimeSubscribe, publishJobView as n, createRealtimeHub as r, realtimeModuleFor, createRealtimeRetained as t };
|