@plitzi/sdk-server 0.38.24 → 0.39.1
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 +162 -1
- package/README.md +55 -9
- package/dist/actions.d.ts +4 -1
- package/dist/actions.js +3 -2
- package/dist/auth.d.ts +2 -2
- package/dist/auth.js +5 -4
- package/dist/core/auth/api/accounts.d.ts +11 -0
- package/dist/core/auth/api/accounts.js +175 -0
- package/dist/core/auth/api/admin.d.ts +41 -0
- package/dist/core/auth/api/admin.js +146 -0
- package/dist/core/auth/api/context.d.ts +119 -0
- package/dist/core/auth/api/context.js +262 -0
- package/dist/core/auth/api/factors.d.ts +31 -0
- package/dist/core/auth/api/factors.js +209 -0
- package/dist/core/auth/api/index.d.ts +94 -0
- package/dist/core/auth/api/index.js +43 -0
- package/dist/core/auth/api/profile.d.ts +43 -0
- package/dist/core/auth/api/profile.js +243 -0
- package/dist/core/auth/api/session.d.ts +62 -0
- package/dist/core/auth/api/session.js +312 -0
- package/dist/core/auth/{api.d.ts → api/types.d.ts} +41 -195
- package/dist/core/auth/api/values.d.ts +67 -0
- package/dist/core/auth/api/values.js +90 -0
- package/dist/core/auth/createAuth.d.ts +49 -39
- package/dist/core/auth/createAuth.js +21 -1
- package/dist/core/auth/oauth/client.d.ts +2 -2
- package/dist/core/auth/oauth/client.js +6 -1
- package/dist/core/auth/oauth/index.d.ts +30 -7
- package/dist/core/auth/oauth/index.js +33 -14
- package/dist/core/auth/oauth/providers/github.js +1 -1
- package/dist/core/auth/oauth/providers/google.js +1 -1
- package/dist/core/auth/oauth/providers/oidc.d.ts +40 -0
- package/dist/core/auth/oauth/providers/oidc.js +197 -0
- package/dist/core/auth/oauth/state.d.ts +2 -0
- package/dist/core/auth/oauth/state.js +2 -0
- package/dist/core/auth/oauth/types.d.ts +21 -3
- package/dist/core/auth/oauth/types.js +4 -1
- package/dist/core/auth/routes.js +1 -1
- package/dist/core/auth/tokens.d.ts +3 -1
- package/dist/core/auth/tokens.js +2 -1
- package/dist/core/configSeam.d.ts +0 -4
- package/dist/core/configSeam.js +12 -1
- package/dist/core/createServer.js +16 -4
- package/dist/core/freePort.d.ts +10 -0
- package/dist/core/freePort.js +39 -1
- package/dist/core/handlers/socialRouteHandlers.d.ts +9 -1
- package/dist/core/handlers/socialRouteHandlers.js +46 -12
- package/dist/core/health.d.ts +1 -0
- package/dist/core/health.js +2 -1
- package/dist/core/http/stages/authRoutes.d.ts +6 -0
- package/dist/core/http/stages/authRoutes.js +42 -1
- package/dist/core/http/stages/images.js +5 -3
- package/dist/core/http/stages/livePages.js +1 -1
- package/dist/core/server/fleet/relay.js +9 -1
- package/dist/core/server/fleet/stores.d.ts +7 -0
- package/dist/core/server/fleet/stores.js +15 -2
- package/dist/core/server/pageServer.js +5 -1
- package/dist/core/services/realtime.js +4 -2
- package/dist/core/services/registry.js +7 -1
- package/dist/core/services/robotsTxt.d.ts +16 -0
- package/dist/core/services/robotsTxt.js +50 -0
- package/dist/core/services/servedSpace.d.ts +8 -0
- package/dist/core/services/servedSpace.js +16 -0
- package/dist/core/services/sitemapXml.d.ts +7 -0
- package/dist/core/services/sitemapXml.js +37 -0
- package/dist/functions-api.d.ts +69 -2
- package/dist/helpers/fileStore.d.ts +60 -0
- package/dist/helpers/fileStore.js +127 -0
- package/dist/helpers/outboundGuard.d.ts +32 -3
- package/dist/helpers/outboundGuard.js +50 -5
- package/dist/hosts/project/agentRuns.d.ts +24 -0
- package/dist/hosts/project/agentRuns.js +107 -0
- package/dist/hosts/project/laterAsks.d.ts +41 -0
- package/dist/hosts/project/laterAsks.js +117 -0
- package/dist/hosts/project/plugins.js +11 -4
- package/dist/hosts/project/serveProject.d.ts +18 -1
- package/dist/hosts/project/serveProject.js +89 -25
- package/dist/hosts/project/spaceFailure.d.ts +4 -0
- package/dist/hosts/project/spaceFailure.js +10 -0
- package/dist/hosts/project/watchSpace.d.ts +5 -5
- package/dist/hosts/project/watchSpace.js +15 -6
- package/dist/index.js +2 -2
- package/dist/kernel.js +1 -1
- package/dist/modules/actions/connectorWrite.js +3 -1
- package/dist/modules/actions/index.js +1 -1
- package/dist/modules/actions/jobs/fileQueue.d.ts +34 -0
- package/dist/modules/actions/jobs/fileQueue.js +72 -0
- package/dist/modules/actions/jobs/index.js +3 -3
- package/dist/modules/actions/jobs/memoryQueue.js +6 -215
- package/dist/modules/actions/jobs/queueDocument.d.ts +14 -0
- package/dist/modules/actions/jobs/queueDocument.js +22 -0
- package/dist/modules/actions/jobs/queueRules.d.ts +39 -0
- package/dist/modules/actions/jobs/queueRules.js +270 -0
- package/dist/modules/actions/moduleFor.js +2 -0
- package/dist/modules/actions/runtime/fileKv.d.ts +3 -1
- package/dist/modules/actions/runtime/fileKv.js +12 -98
- package/dist/modules/actions/runtime/guards.d.ts +19 -1
- package/dist/modules/actions/runtime/guards.js +10 -1
- package/dist/modules/actions/runtime/kvChange.d.ts +40 -0
- package/dist/modules/actions/runtime/kvChange.js +23 -1
- package/dist/modules/actions/runtime/kvList.d.ts +4 -0
- package/dist/modules/actions/runtime/kvList.js +5 -1
- package/dist/modules/actions/runtime/kvStore.js +15 -1
- package/dist/modules/actions/runtime/namespaceKv.js +2 -0
- package/dist/modules/actions/runtime/renderResolver.js +31 -5
- package/dist/modules/actions/runtime/runAction.js +16 -6
- package/dist/modules/actions/runtime/scope.js +11 -0
- package/dist/modules/actions/runtime/taskContext.js +11 -32
- package/dist/modules/actions/tasks/auth.js +2 -0
- package/dist/modules/actions/tasks/connector.js +6 -2
- package/dist/modules/actions/tasks/flow.js +5 -0
- package/dist/modules/actions/tasks/http.js +2 -1
- package/dist/modules/actions/tasks/kv.js +5 -0
- package/dist/modules/actions/tasks/list.js +11 -2
- package/dist/modules/actions/tasks/transform.js +2 -0
- package/dist/modules/actions/transport/callHandler.js +25 -4
- package/dist/modules/actions/types.d.ts +46 -1
- package/dist/modules/connectors/engine.d.ts +7 -2
- package/dist/modules/connectors/engine.js +4 -4
- package/dist/modules/connectors/resolver.d.ts +2 -1
- package/dist/modules/connectors/resolver.js +3 -2
- package/dist/modules/functions/build.d.ts +7 -2
- package/dist/modules/functions/build.js +90 -6
- package/dist/modules/functions/capabilities.js +16 -0
- package/dist/modules/functions/context.js +6 -2
- package/dist/modules/functions/contract.d.ts +39 -1
- package/dist/modules/functions/driver.d.ts +2 -1
- package/dist/modules/functions/driver.js +35 -0
- package/dist/modules/functions/load.d.ts +1 -1
- package/dist/modules/functions/load.js +2 -2
- package/dist/modules/functions/manifest.js +7 -1
- package/dist/modules/functions/oauth.d.ts +1 -1
- package/dist/modules/functions/oauth.js +4 -4
- package/dist/modules/functions/protocol.d.ts +6 -0
- package/dist/modules/functions/sandbox/guest/bytes.d.ts +27 -0
- package/dist/modules/functions/sandbox/guest/bytes.js +108 -0
- package/dist/modules/functions/sandbox/guest/crypto.d.ts +47 -0
- package/dist/modules/functions/sandbox/guest/crypto.js +144 -0
- package/dist/modules/functions/sandbox/guest/events.d.ts +152 -0
- package/dist/modules/functions/sandbox/guest/events.js +143 -0
- package/dist/modules/functions/sandbox/guest/fetch.d.ts +305 -0
- package/dist/modules/functions/sandbox/guest/fetch.js +237 -0
- package/dist/modules/functions/sandbox/guest/index.d.ts +28 -0
- package/dist/modules/functions/sandbox/guest/index.js +130 -0
- package/dist/modules/functions/sandbox/{guest.d.ts → guest/types.d.ts} +5 -12
- package/dist/modules/functions/sandbox/isolate.js +20 -6
- package/dist/modules/functions/space.js +2 -8
- package/dist/modules/images/imageProxy.d.ts +3 -2
- package/dist/modules/images/imageProxy.js +2 -2
- package/dist/modules/mongo/jobQueue.js +0 -19
- package/dist/modules/mysql/accounts.js +12 -5
- package/dist/modules/mysql/jobs/index.d.ts +1 -1
- package/dist/modules/mysql/jobs/schema.d.ts +0 -6
- package/dist/modules/mysql/jobs/schema.js +2 -46
- package/dist/modules/mysql/schema.js +26 -1
- package/dist/modules/mysql/sessions.js +2 -1
- package/dist/modules/realtime/handlers.d.ts +9 -4
- package/dist/modules/realtime/handlers.js +20 -3
- package/dist/modules/realtime/hub.d.ts +4 -2
- package/dist/modules/realtime/hub.js +36 -4
- package/dist/modules/realtime/index.d.ts +14 -0
- package/dist/modules/realtime/index.js +14 -1
- package/dist/modules/realtime/presence.d.ts +33 -0
- package/dist/modules/realtime/presence.js +56 -0
- package/dist/modules/realtime/socket.d.ts +3 -1
- package/dist/modules/realtime/socket.js +2 -2
- package/dist/modules/rsc/connectorRscData.d.ts +6 -1
- package/dist/modules/rsc/connectorRscData.js +27 -6
- package/dist/modules/rsc/externalQueryReader.d.ts +28 -0
- package/dist/modules/rsc/externalQueryReader.js +43 -0
- package/dist/modules/rsc/handler.js +1 -1
- package/dist/modules/rsc/resolveRscData.d.ts +11 -1
- package/dist/modules/rsc/resolveRscData.js +86 -16
- package/dist/modules/runtime/inside.js +1 -1
- package/dist/modules/runtime/runner.js +2 -1
- package/dist/modules/sqlite/jobQueue.d.ts +35 -0
- package/dist/modules/sqlite/jobQueue.js +56 -0
- package/dist/modules/sqlite/kv.d.ts +1 -1
- package/dist/modules/sqlite/kv.js +2 -10
- package/dist/modules/sqlite/open.d.ts +3 -0
- package/dist/modules/sqlite/open.js +13 -0
- package/dist/modules/ssr/Component.d.ts +5 -1
- package/dist/modules/ssr/Component.js +3 -1
- package/dist/modules/ssr/applySSRResult.d.ts +8 -1
- package/dist/modules/ssr/applySSRResult.js +23 -3
- package/dist/modules/ssr/handler.js +30 -5
- package/dist/modules/ssr/prepareRender.js +31 -8
- package/dist/modules/ssr/preview.d.ts +2 -0
- package/dist/modules/ssr/preview.js +6 -3
- package/dist/modules/ssr/registerExternalPlugins.d.ts +2 -6
- package/dist/modules/ssr/registerExternalPlugins.js +2 -2
- package/dist/modules/ssr/resolvePageSeo.d.ts +11 -0
- package/dist/modules/ssr/resolvePageSeo.js +13 -2
- package/dist/modules/ssr/streamBody.js +2 -2
- package/dist/modules/ssr/views/template.ejs +21 -17
- package/dist/mysql.d.ts +1 -1
- package/dist/mysql.js +2 -2
- package/dist/plugins/manager.d.ts +5 -0
- package/dist/plugins/manager.js +9 -0
- package/dist/sqlite.d.ts +8 -1
- package/dist/sqlite.js +3 -1
- package/package.json +5 -5
- package/skills/plitzi-authoring/CHEATSHEET.md +6 -6
- package/skills/plitzi-authoring/SKILL.md +4 -2
- package/skills/plitzi-authoring/recipes/accordion.ts +2 -1
- package/skills/plitzi-authoring/recipes/carousel.ts +24 -3
- package/skills/plitzi-authoring/recipes/detail-page.ts +0 -1
- package/skills/plitzi-authoring/recipes/embed-and-svg.ts +3 -1
- package/skills/plitzi-authoring/recipes/filter-a-list.ts +0 -1
- package/skills/plitzi-authoring/recipes/show-data.ts +0 -1
- package/skills/plitzi-authoring/recipes/typed-data.ts +0 -1
- package/skills/plitzi-authoring/reference/accessibility.md +10 -2
- package/skills/plitzi-authoring/reference/auth.md +15 -4
- package/skills/plitzi-authoring/reference/authoring-errors.md +55 -12
- package/skills/plitzi-authoring/reference/colours-and-motion.md +7 -1
- package/skills/plitzi-authoring/reference/components.md +4 -1
- package/skills/plitzi-authoring/reference/data-and-visibility.md +31 -22
- package/skills/plitzi-authoring/reference/efficiency.md +2 -1
- package/skills/plitzi-authoring/reference/elements-and-styles.md +16 -15
- package/skills/plitzi-authoring/reference/flows.md +29 -17
- package/skills/plitzi-authoring/reference/kept-state.md +20 -0
- package/skills/plitzi-authoring/reference/layouts.md +18 -2
- package/skills/plitzi-authoring/reference/lists.md +20 -4
- package/skills/plitzi-authoring/reference/plugin-reach.md +12 -0
- package/skills/plitzi-authoring/reference/plugins.md +17 -3
- package/skills/plitzi-authoring/reference/realtime.md +8 -5
- package/skills/plitzi-authoring/reference/structure.md +17 -1
- package/skills/plitzi-authoring/reference/templates.md +11 -3
- package/skills/plitzi-authoring/reference/testing.md +82 -5
- package/skills/plitzi-authoring/reference/typed-sources.md +6 -0
- package/skills/plitzi-authoring/reference/validation.md +1 -1
- package/dist/core/auth/api.js +0 -1323
- package/dist/modules/functions/sandbox/guest.js +0 -662
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { execute
|
|
1
|
+
import { execute } from "../query.js";
|
|
2
2
|
//#region src/modules/mysql/jobs/schema.ts
|
|
3
3
|
var PREFIX = /^[A-Za-z0-9_]*$/;
|
|
4
4
|
/**
|
|
@@ -89,49 +89,6 @@ var mysqlJobSchemaStatements = (prefix = "") => {
|
|
|
89
89
|
) ${CHARSET}`
|
|
90
90
|
];
|
|
91
91
|
};
|
|
92
|
-
/** The columns a table of this database has, by name, with their types. */
|
|
93
|
-
var columnsOf = async (db, table) => {
|
|
94
|
-
const columns = await selectRows(db, `SELECT COLUMN_NAME AS name, DATA_TYPE AS type FROM INFORMATION_SCHEMA.COLUMNS
|
|
95
|
-
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?`, [table]);
|
|
96
|
-
return new Map(columns.map((column) => [column.name, column.type.toLowerCase()]));
|
|
97
|
-
};
|
|
98
|
-
var UPGRADES = [
|
|
99
|
-
{
|
|
100
|
-
needed: async (db, prefix) => {
|
|
101
|
-
const columns = await columnsOf(db, `${prefix}action_kv`);
|
|
102
|
-
return columns.get("k") !== "varbinary" || columns.get("v") !== "mediumtext";
|
|
103
|
-
},
|
|
104
|
-
statements: (prefix) => [`ALTER TABLE ${jobTables(prefix).kv} MODIFY k VARBINARY(764) NOT NULL, MODIFY v MEDIUMTEXT NOT NULL`]
|
|
105
|
-
},
|
|
106
|
-
{
|
|
107
|
-
needed: async (db, prefix) => !(await columnsOf(db, `${prefix}action_jobs`)).has("job_key"),
|
|
108
|
-
statements: (prefix) => [`ALTER TABLE ${jobTables(prefix).jobs} ADD COLUMN job_key VARCHAR(191) NULL AFTER missed,
|
|
109
|
-
ADD KEY action_jobs_key (space_id, job_key, status)`]
|
|
110
|
-
},
|
|
111
|
-
{
|
|
112
|
-
needed: async (db, prefix) => !(await columnsOf(db, `${prefix}action_jobs`)).has("target_kind"),
|
|
113
|
-
statements: (prefix) => {
|
|
114
|
-
const { jobs } = jobTables(prefix);
|
|
115
|
-
return [
|
|
116
|
-
`ALTER TABLE ${jobs} ADD COLUMN target_kind VARCHAR(16) NULL AFTER space_id,
|
|
117
|
-
ADD COLUMN target_name VARCHAR(191) NULL AFTER target_kind, ADD COLUMN target MEDIUMTEXT NULL AFTER target_name,
|
|
118
|
-
ADD COLUMN state MEDIUMTEXT NULL, ADD COLUMN progress TEXT NULL, ADD COLUMN result MEDIUMTEXT NULL,
|
|
119
|
-
ADD COLUMN pause_requested TINYINT(1) NOT NULL DEFAULT 0, ADD COLUMN active_ms BIGINT NOT NULL DEFAULT 0`,
|
|
120
|
-
`UPDATE ${jobs} SET target_kind = 'action', target_name = action_id,
|
|
121
|
-
target = JSON_OBJECT('kind', 'action', 'name', action_id, 'trigger', trigger_type)`,
|
|
122
|
-
`ALTER TABLE ${jobs} MODIFY target_kind VARCHAR(16) NOT NULL, MODIFY target_name VARCHAR(191) NOT NULL,
|
|
123
|
-
MODIFY target MEDIUMTEXT NOT NULL, DROP COLUMN action_id, DROP COLUMN trigger_type,
|
|
124
|
-
ADD KEY action_jobs_target (space_id, target_name, updated_at)`
|
|
125
|
-
];
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
];
|
|
129
|
-
/**
|
|
130
|
-
* What brings tables made before the columns above up to them — for a deployment that runs its own migrations: each
|
|
131
|
-
* statement once, the ones its tables still lack. `ensureJobTables` does it by itself, and only where a table needs
|
|
132
|
-
* it: an `ALTER` copies the table.
|
|
133
|
-
*/
|
|
134
|
-
var mysqlJobSchemaUpgrades = (prefix = "") => UPGRADES.flatMap((upgrade) => upgrade.statements(prefix));
|
|
135
92
|
/** The server's now, in epoch ms, as an SQL expression — what every comparison reads instead of a caller's clock. */
|
|
136
93
|
var NOW_MS = "CAST(ROUND(UNIX_TIMESTAMP(NOW(3)) * 1000) AS SIGNED)";
|
|
137
94
|
/** Creates the tables once per process, on first use; a failure is retried by the next call rather than remembered. */
|
|
@@ -141,7 +98,6 @@ var ensureJobTables = (db, prefix, create) => {
|
|
|
141
98
|
if (!create) return;
|
|
142
99
|
ready ??= (async () => {
|
|
143
100
|
for (const statement of mysqlJobSchemaStatements(prefix)) await execute(db, statement);
|
|
144
|
-
for (const upgrade of UPGRADES) if (await upgrade.needed(db, prefix)) for (const statement of upgrade.statements(prefix)) await execute(db, statement);
|
|
145
101
|
})().catch((error) => {
|
|
146
102
|
ready = void 0;
|
|
147
103
|
throw error;
|
|
@@ -150,4 +106,4 @@ var ensureJobTables = (db, prefix, create) => {
|
|
|
150
106
|
};
|
|
151
107
|
};
|
|
152
108
|
//#endregion
|
|
153
|
-
export { NOW_MS, ensureJobTables, jobTables, mysqlJobSchemaStatements
|
|
109
|
+
export { NOW_MS, ensureJobTables, jobTables, mysqlJobSchemaStatements };
|
|
@@ -198,7 +198,7 @@ var step3 = (t) => {
|
|
|
198
198
|
};
|
|
199
199
|
/**
|
|
200
200
|
* What tells one device from another in the account's session list: the application holding it, when it is not a
|
|
201
|
-
* browser (`Plitzi CLI on
|
|
201
|
+
* browser (`Plitzi CLI on dev-laptop`, software `plitzi-cli`), and when it was last used — see `sessionActivity`.
|
|
202
202
|
*/
|
|
203
203
|
var step4 = (t) => {
|
|
204
204
|
const session = unquote(t.session);
|
|
@@ -213,6 +213,23 @@ var step4 = (t) => {
|
|
|
213
213
|
* stays valid for (RFC 6238 §5.2) — see `MfaRecord.lastUsedStep`.
|
|
214
214
|
*/
|
|
215
215
|
var step5 = (t) => [...addColumn(unquote(t.mfa), "last_used_step", "BIGINT NULL AFTER recovery_codes")];
|
|
216
|
+
/**
|
|
217
|
+
* The host a session was signed in on (`SessionClient.host`), and an index to end a site's sessions by: a space's
|
|
218
|
+
* visitors sign in on its own host, and "sign out of this site everywhere" is every session of the account there.
|
|
219
|
+
*/
|
|
220
|
+
var step6 = (t) => {
|
|
221
|
+
const session = unquote(t.session);
|
|
222
|
+
return [...addColumn(session, "host", "VARCHAR(255) NULL AFTER app_id"), ...addIndex(session, "session_account_host", "(account_id, host(191))")];
|
|
223
|
+
};
|
|
224
|
+
/**
|
|
225
|
+
* The terms an account was opened under, and when they were accepted (`AuthApiConfig.terms`, `termsAccepted` on
|
|
226
|
+
* `createAccount`): the record of what each person agreed to. Null for an account opened before a deployment named
|
|
227
|
+
* terms, or through another provider.
|
|
228
|
+
*/
|
|
229
|
+
var step7 = (t) => {
|
|
230
|
+
const account = unquote(t.account);
|
|
231
|
+
return [...addColumn(account, "terms_version", "VARCHAR(32) NULL AFTER verified"), ...addColumn(account, "terms_accepted_at", "DATETIME NULL AFTER terms_version")];
|
|
232
|
+
};
|
|
216
233
|
/** Append only. A released version is never edited — the deployments that already ran it would never see the change. */
|
|
217
234
|
var STEPS = [
|
|
218
235
|
{
|
|
@@ -234,6 +251,14 @@ var STEPS = [
|
|
|
234
251
|
{
|
|
235
252
|
version: 5,
|
|
236
253
|
statements: step5
|
|
254
|
+
},
|
|
255
|
+
{
|
|
256
|
+
version: 6,
|
|
257
|
+
statements: step6
|
|
258
|
+
},
|
|
259
|
+
{
|
|
260
|
+
version: 7,
|
|
261
|
+
statements: step7
|
|
237
262
|
}
|
|
238
263
|
];
|
|
239
264
|
var SCHEMA_VERSION = STEPS[STEPS.length - 1].version;
|
|
@@ -9,7 +9,7 @@ import { execute, selectRows } from "./query.js";
|
|
|
9
9
|
*/
|
|
10
10
|
var createSessionStore = (db, t) => {
|
|
11
11
|
const list = async (accountId, currentToken) => {
|
|
12
|
-
return (await selectRows(db, `SELECT id, token, user_agent, ip, app_name, app_id, created_at, last_active_at, expires_at
|
|
12
|
+
return (await selectRows(db, `SELECT id, token, user_agent, ip, app_name, app_id, host, created_at, last_active_at, expires_at
|
|
13
13
|
FROM ${t.session}
|
|
14
14
|
WHERE account_id = ?
|
|
15
15
|
ORDER BY created_at DESC`, [accountId])).map((row) => ({
|
|
@@ -20,6 +20,7 @@ var createSessionStore = (db, t) => {
|
|
|
20
20
|
name: row.app_name,
|
|
21
21
|
...row.app_id ? { softwareId: row.app_id } : {}
|
|
22
22
|
} } : {},
|
|
23
|
+
...row.host ? { host: row.host } : {},
|
|
23
24
|
createdAt: Math.floor(row.created_at.getTime() / 1e3),
|
|
24
25
|
...row.last_active_at ? { lastActiveAt: row.last_active_at } : {},
|
|
25
26
|
expiresAt: row.expires_at,
|
|
@@ -6,8 +6,11 @@ import { RawResponse } from '../../helpers/buildResponseHelpers';
|
|
|
6
6
|
import { ChannelDeclaration, RealtimeSender, SSRRequest, SSRResponseHelpers } from '@plitzi/sdk-shared';
|
|
7
7
|
export type RealtimeRefusal = {
|
|
8
8
|
topic: string;
|
|
9
|
-
/**
|
|
10
|
-
|
|
9
|
+
/**
|
|
10
|
+
* `ungranted`: the channel is declared `grant: true`, and no grant the page sent opens this topic. `unavailable`: the
|
|
11
|
+
* deployment does not open this space's channels (`realtime.admitSpace`).
|
|
12
|
+
*/
|
|
13
|
+
reason: 'undeclared' | 'unauthenticated' | 'forbidden' | 'ungranted' | 'unavailable';
|
|
11
14
|
};
|
|
12
15
|
/** An answer in HTTP terms, whichever transport carries it: a status, and what went wrong when something did. */
|
|
13
16
|
export type RealtimeAnswer = {
|
|
@@ -37,7 +40,7 @@ export type Admission = {
|
|
|
37
40
|
* declares and against the visitor's access. One that fails is reported, not a reason to refuse the rest; all failing
|
|
38
41
|
* is a `403`.
|
|
39
42
|
*/
|
|
40
|
-
export declare const admit: (req: SSRRequest, resolveChannels: ChannelResolver, grants: RealtimeGrants, jobs?: JobLookup) => Promise<Admission>;
|
|
43
|
+
export declare const admit: (req: SSRRequest, resolveChannels: ChannelResolver, grants: RealtimeGrants, jobs?: JobLookup, admitSpace?: (spaceId: number) => Promise<string | undefined>) => Promise<Admission>;
|
|
41
44
|
/** A new connection for what was admitted, speaking through `send`. */
|
|
42
45
|
export declare const connectionFor: (admission: Extract<Admission, {
|
|
43
46
|
ok: true;
|
|
@@ -63,6 +66,8 @@ export type SubscribeDeps = {
|
|
|
63
66
|
grants: RealtimeGrants;
|
|
64
67
|
/** The way to the jobs `$job:<id>` is about — absent where the server runs none. */
|
|
65
68
|
jobs?: JobLookup;
|
|
69
|
+
/** The deployment's say on whether a space opens its channels (`realtime.admitSpace`). */
|
|
70
|
+
admitSpace?: (spaceId: number) => Promise<string | undefined>;
|
|
66
71
|
};
|
|
67
72
|
/**
|
|
68
73
|
* `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.
|
|
@@ -70,7 +75,7 @@ export type SubscribeDeps = {
|
|
|
70
75
|
* The first event, `ready`, tells the page its public name (`from`) and the secret its publishes carry. Resolves when
|
|
71
76
|
* the page goes.
|
|
72
77
|
*/
|
|
73
|
-
export declare const handleRealtimeSubscribe: ({ req, res, raw, signal, hub, resolveChannels, grants, jobs }: SubscribeDeps) => Promise<void>;
|
|
78
|
+
export declare const handleRealtimeSubscribe: ({ req, res, raw, signal, hub, resolveChannels, grants, jobs, admitSpace }: SubscribeDeps) => Promise<void>;
|
|
74
79
|
export type PublishDeps = {
|
|
75
80
|
req: SSRRequest;
|
|
76
81
|
res: SSRResponseHelpers;
|
|
@@ -29,7 +29,7 @@ var grantFor = async (grants, space, topic, offered) => {
|
|
|
29
29
|
* declares and against the visitor's access. One that fails is reported, not a reason to refuse the rest; all failing
|
|
30
30
|
* is a `403`.
|
|
31
31
|
*/
|
|
32
|
-
var admit = async (req, resolveChannels, grants, jobs) => {
|
|
32
|
+
var admit = async (req, resolveChannels, grants, jobs, admitSpace) => {
|
|
33
33
|
const { environment = "main", spaceId, revision } = req.ctx.spaceDeployment ?? {};
|
|
34
34
|
if (typeof spaceId !== "number") return {
|
|
35
35
|
ok: false,
|
|
@@ -50,6 +50,7 @@ var admit = async (req, resolveChannels, grants, jobs) => {
|
|
|
50
50
|
}
|
|
51
51
|
};
|
|
52
52
|
const channels = await resolveChannels(spaceId, environment, revision);
|
|
53
|
+
const spaceRefusal = await admitSpace?.(spaceId);
|
|
53
54
|
const accepted = /* @__PURE__ */ new Map();
|
|
54
55
|
const granted = /* @__PURE__ */ new Map();
|
|
55
56
|
const refused = [];
|
|
@@ -68,6 +69,13 @@ var admit = async (req, resolveChannels, grants, jobs) => {
|
|
|
68
69
|
else accepted.set(topic, JOB_CHANNEL);
|
|
69
70
|
continue;
|
|
70
71
|
}
|
|
72
|
+
if (spaceRefusal !== void 0) {
|
|
73
|
+
refused.push({
|
|
74
|
+
topic,
|
|
75
|
+
reason: "unavailable"
|
|
76
|
+
});
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
71
79
|
const match = matchChannel(topic, channels);
|
|
72
80
|
const refusal = match ? accessRefusal(match.declaration.access, req.ctx.user) : "undeclared";
|
|
73
81
|
const grant = match && !refusal && match.declaration.grant === true ? await grantFor(grants, space, topic, offered) : void 0;
|
|
@@ -84,6 +92,15 @@ var admit = async (req, resolveChannels, grants, jobs) => {
|
|
|
84
92
|
if (grant !== void 0) granted.set(topic, grant);
|
|
85
93
|
}
|
|
86
94
|
}
|
|
95
|
+
if (accepted.size === 0 && spaceRefusal !== void 0) return {
|
|
96
|
+
ok: false,
|
|
97
|
+
answer: {
|
|
98
|
+
status: 402,
|
|
99
|
+
error: spaceRefusal,
|
|
100
|
+
reason: "unavailable",
|
|
101
|
+
refused
|
|
102
|
+
}
|
|
103
|
+
};
|
|
87
104
|
if (accepted.size === 0) return {
|
|
88
105
|
ok: false,
|
|
89
106
|
answer: {
|
|
@@ -189,8 +206,8 @@ var publishFrom = async (hub, connection, { topic, type, data, echo }) => {
|
|
|
189
206
|
* The first event, `ready`, tells the page its public name (`from`) and the secret its publishes carry. Resolves when
|
|
190
207
|
* the page goes.
|
|
191
208
|
*/
|
|
192
|
-
var handleRealtimeSubscribe = async ({ req, res, raw, signal, hub, resolveChannels, grants, jobs }) => {
|
|
193
|
-
const admission = await admit(req, resolveChannels, grants, jobs);
|
|
209
|
+
var handleRealtimeSubscribe = async ({ req, res, raw, signal, hub, resolveChannels, grants, jobs, admitSpace }) => {
|
|
210
|
+
const admission = await admit(req, resolveChannels, grants, jobs, admitSpace);
|
|
194
211
|
if (!admission.ok) {
|
|
195
212
|
answer(res, admission.answer);
|
|
196
213
|
return;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { RealtimePresence } from './presence';
|
|
1
2
|
import { RealtimeRetained } from './retained';
|
|
2
3
|
import { ChannelDeclaration, PubSubAdapter, RealtimeMessage, RealtimeSender } from '@plitzi/sdk-shared';
|
|
3
4
|
/** The space a connection belongs to: its topics are that space's and no other's. */
|
|
@@ -39,7 +40,7 @@ export type RealtimeHub = ReturnType<typeof createRealtimeHub>;
|
|
|
39
40
|
* A hundred pages on one board are a hundred connections here and a single subscription to the adapter: a message
|
|
40
41
|
* arrives once and is written to each of them. The last one to leave a topic unsubscribes it.
|
|
41
42
|
*/
|
|
42
|
-
export declare const createRealtimeHub: (pubsub: PubSubAdapter, retained: RealtimeRetained) => {
|
|
43
|
+
export declare const createRealtimeHub: (pubsub: PubSubAdapter, retained: RealtimeRetained, presence?: RealtimePresence) => {
|
|
43
44
|
publish: (space: RealtimeSpace, message: RealtimeMessage) => Promise<void>;
|
|
44
45
|
from: (connection: RealtimeConnection, topic: string, type: string, data: unknown, echo?: boolean) => RealtimeMessage;
|
|
45
46
|
find: (token: string) => RealtimeConnection | undefined;
|
|
@@ -51,7 +52,8 @@ export declare const createRealtimeHub: (pubsub: PubSubAdapter, retained: Realti
|
|
|
51
52
|
/**
|
|
52
53
|
* Subscribes a new connection to its topics, hands it what each `retain: true` one keeps, and tells the members of
|
|
53
54
|
* each presence channel it arrived. What is kept is read AFTER joining, so nothing said in between is missed; a
|
|
54
|
-
* message heard live and then kept arrives twice, and the page keeps the newer of a type by its `at`.
|
|
55
|
+
* message heard live and then kept arrives twice, and the page keeps the newer of a type by its `at`. Each kept one
|
|
56
|
+
* is `replayed`: a page that joins tells it from what is said now.
|
|
55
57
|
*/
|
|
56
58
|
connect: (connection: RealtimeConnection) => Promise<void>;
|
|
57
59
|
/** Unsubscribes a connection that went away, and tells the channels it announced itself on. */
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { warnRealtime } from "./failure.js";
|
|
2
2
|
import { isMessage } from "./message.js";
|
|
3
|
+
import { PRESENCE_HEARTBEAT_MS } from "./presence.js";
|
|
3
4
|
import { JOIN_TYPE, LEAVE_TYPE, REVOKED_TYPE } from "@plitzi/sdk-shared/realtime";
|
|
4
5
|
//#region src/modules/realtime/hub.ts
|
|
5
6
|
/** A space's topic, as the adapter knows it: namespaced, so two spaces never hear each other. */
|
|
@@ -25,8 +26,30 @@ var parse = (raw) => {
|
|
|
25
26
|
* A hundred pages on one board are a hundred connections here and a single subscription to the adapter: a message
|
|
26
27
|
* arrives once and is written to each of them. The last one to leave a topic unsubscribes it.
|
|
27
28
|
*/
|
|
28
|
-
var createRealtimeHub = (pubsub, retained) => {
|
|
29
|
+
var createRealtimeHub = (pubsub, retained, presence) => {
|
|
29
30
|
const byToken = /* @__PURE__ */ new Map();
|
|
31
|
+
/** The presence topics a connection is counted on: those of a `presence: true` channel, for a page that is not watching. */
|
|
32
|
+
const counted = (connection) => connection.observer ? [] : [...connection.topics].flatMap(([topic, declaration]) => declaration.presence ? [topic] : []);
|
|
33
|
+
const memberOf = (connection) => ({
|
|
34
|
+
from: connection.id,
|
|
35
|
+
...connection.user ? { user: connection.user } : {},
|
|
36
|
+
since: Date.now()
|
|
37
|
+
});
|
|
38
|
+
const heartbeat = presence ? setInterval(() => {
|
|
39
|
+
const byTopic = /* @__PURE__ */ new Map();
|
|
40
|
+
for (const connection of byToken.values()) for (const topic of counted(connection)) {
|
|
41
|
+
const key = adapterTopic(connection.space, topic);
|
|
42
|
+
const entry = byTopic.get(key) ?? {
|
|
43
|
+
space: connection.space,
|
|
44
|
+
topic,
|
|
45
|
+
members: []
|
|
46
|
+
};
|
|
47
|
+
entry.members.push(memberOf(connection));
|
|
48
|
+
byTopic.set(key, entry);
|
|
49
|
+
}
|
|
50
|
+
for (const { space, topic, members } of byTopic.values()) presence.touch(space, topic, members).catch(warnRealtime(`"${topic}"'s presence was not refreshed`));
|
|
51
|
+
}, PRESENCE_HEARTBEAT_MS) : void 0;
|
|
52
|
+
heartbeat?.unref();
|
|
30
53
|
const local = /* @__PURE__ */ new Map();
|
|
31
54
|
const publish = (space, message) => pubsub.publish(adapterTopic(space, message.topic), JSON.stringify(message));
|
|
32
55
|
const join = async (connection, topic) => {
|
|
@@ -112,19 +135,27 @@ var createRealtimeHub = (pubsub, retained) => {
|
|
|
112
135
|
/**
|
|
113
136
|
* Subscribes a new connection to its topics, hands it what each `retain: true` one keeps, and tells the members of
|
|
114
137
|
* each presence channel it arrived. What is kept is read AFTER joining, so nothing said in between is missed; a
|
|
115
|
-
* message heard live and then kept arrives twice, and the page keeps the newer of a type by its `at`.
|
|
138
|
+
* message heard live and then kept arrives twice, and the page keeps the newer of a type by its `at`. Each kept one
|
|
139
|
+
* is `replayed`: a page that joins tells it from what is said now.
|
|
116
140
|
*/
|
|
117
141
|
connect: async (connection) => {
|
|
118
142
|
byToken.set(connection.token, connection);
|
|
119
143
|
for (const [topic, declaration] of connection.topics) {
|
|
120
144
|
await join(connection, topic);
|
|
121
|
-
if (declaration.retain === true) (await retained.of(connection.space, topic)).forEach((message) => connection.send("message",
|
|
122
|
-
|
|
145
|
+
if (declaration.retain === true) (await retained.of(connection.space, topic)).forEach((message) => connection.send("message", {
|
|
146
|
+
...message,
|
|
147
|
+
replayed: true
|
|
148
|
+
}));
|
|
149
|
+
if (declaration.presence && !connection.observer) {
|
|
150
|
+
await publish(connection.space, from(connection, topic, JOIN_TYPE, null));
|
|
151
|
+
await presence?.touch(connection.space, topic, [memberOf(connection)]).catch(warnRealtime(`"${topic}"'s presence was not recorded`));
|
|
152
|
+
}
|
|
123
153
|
}
|
|
124
154
|
},
|
|
125
155
|
/** Unsubscribes a connection that went away, and tells the channels it announced itself on. */
|
|
126
156
|
disconnect: async (connection) => {
|
|
127
157
|
byToken.delete(connection.token);
|
|
158
|
+
for (const topic of counted(connection)) await presence?.depart(connection.space, topic, connection.id).catch(warnRealtime(`"${topic}"'s presence was not let go of`));
|
|
128
159
|
for (const topic of connection.topics.keys()) {
|
|
129
160
|
if (connection.announced.has(topic)) await publish(connection.space, from(connection, topic, LEAVE_TYPE, null));
|
|
130
161
|
await leave(connection, topic);
|
|
@@ -136,6 +167,7 @@ var createRealtimeHub = (pubsub, retained) => {
|
|
|
136
167
|
* goes when its page leaves.
|
|
137
168
|
*/
|
|
138
169
|
closeAll: () => {
|
|
170
|
+
clearInterval(heartbeat);
|
|
139
171
|
[...byToken.values()].forEach((connection) => connection.end());
|
|
140
172
|
},
|
|
141
173
|
/** How many connections this process holds — for tests and for a health endpoint. */
|
|
@@ -2,6 +2,7 @@ import { ChannelResolver } from './declarations';
|
|
|
2
2
|
import { RealtimeGrants } from './grants';
|
|
3
3
|
import { RealtimeHub } from './hub';
|
|
4
4
|
import { JobLookup } from './jobs';
|
|
5
|
+
import { RealtimePresenceMember } from './presence';
|
|
5
6
|
import { FunctionJobView, RealtimeTransport, SSRServerConfig } from '@plitzi/sdk-shared';
|
|
6
7
|
export { createMemoryPubSub } from './memoryPubSub';
|
|
7
8
|
export { handleRealtimePublish, handleRealtimeSubscribe } from './handlers';
|
|
@@ -13,6 +14,8 @@ export type RealtimeModule = {
|
|
|
13
14
|
transport: RealtimeTransport;
|
|
14
15
|
/** Origins besides the server's own whose pages may open a socket. */
|
|
15
16
|
allowedOrigins: readonly string[];
|
|
17
|
+
/** The deployment's say on whether a space opens its channels (`realtime.admitSpace`). */
|
|
18
|
+
admitSpace?: (spaceId: number) => Promise<string | undefined>;
|
|
16
19
|
resolveChannels: ChannelResolver;
|
|
17
20
|
/** The grants issued for topics of channels declared `grant: true`, and the check a subscription makes. */
|
|
18
21
|
grants: RealtimeGrants;
|
|
@@ -44,6 +47,17 @@ export type RealtimeModule = {
|
|
|
44
47
|
spaceId: number;
|
|
45
48
|
environment: string;
|
|
46
49
|
}, topic: string, grant?: string) => Promise<void>;
|
|
50
|
+
/**
|
|
51
|
+
* Who is on a topic of a `presence: true` channel now, on every replica — what a function's `ctx.presence` reads. A
|
|
52
|
+
* topic of any other channel is refused: nobody is counted there, and an empty answer would read as an empty room.
|
|
53
|
+
*/
|
|
54
|
+
presence: (space: {
|
|
55
|
+
spaceId: number;
|
|
56
|
+
environment: string;
|
|
57
|
+
}, topic: string) => Promise<{
|
|
58
|
+
count: number;
|
|
59
|
+
members: RealtimePresenceMember[];
|
|
60
|
+
}>;
|
|
47
61
|
/** Says a job of the space's functions as it is now on its topic (`$job:<id>`), kept for a page that joins later. */
|
|
48
62
|
publishJob: (space: {
|
|
49
63
|
spaceId: number;
|
|
@@ -2,6 +2,7 @@ import { fleetStore } from "../../core/server/fleet/link.js";
|
|
|
2
2
|
import { KV_METHODS, createMemoryKv } from "../actions/runtime/memoryKv.js";
|
|
3
3
|
import { createRealtimeGrants } from "./grants.js";
|
|
4
4
|
import { createChannelResolver } from "./declarations.js";
|
|
5
|
+
import { createRealtimePresence } from "./presence.js";
|
|
5
6
|
import { createRealtimeHub } from "./hub.js";
|
|
6
7
|
import { publishJobView } from "./jobs.js";
|
|
7
8
|
import { createMemoryPubSub } from "./memoryPubSub.js";
|
|
@@ -24,7 +25,8 @@ var realtimeModuleFor = (config) => {
|
|
|
24
25
|
if (existing) return existing;
|
|
25
26
|
const kv = config.action?.kv ?? fleetStore("realtime.kv", KV_METHODS) ?? createMemoryKv();
|
|
26
27
|
const retained = createRealtimeRetained(kv);
|
|
27
|
-
const
|
|
28
|
+
const presence = createRealtimePresence(kv);
|
|
29
|
+
const hub = createRealtimeHub(config.realtime?.pubsub ?? createMemoryPubSub(), retained, presence);
|
|
28
30
|
const resolveChannels = createChannelResolver(getOfflineData);
|
|
29
31
|
const grants = createRealtimeGrants(kv);
|
|
30
32
|
let jobLookup;
|
|
@@ -33,6 +35,7 @@ var realtimeModuleFor = (config) => {
|
|
|
33
35
|
path: config.realtime?.path ?? "/_realtime",
|
|
34
36
|
transport: config.realtime?.transport ?? "sse",
|
|
35
37
|
allowedOrigins: config.realtime?.allowedOrigins ?? [],
|
|
38
|
+
...config.realtime?.admitSpace ? { admitSpace: config.realtime.admitSpace } : {},
|
|
36
39
|
resolveChannels,
|
|
37
40
|
grants,
|
|
38
41
|
close: () => hub.closeAll(),
|
|
@@ -52,6 +55,16 @@ var realtimeModuleFor = (config) => {
|
|
|
52
55
|
if (retain) await retained.keep(space, message);
|
|
53
56
|
await hub.publish(space, message);
|
|
54
57
|
},
|
|
58
|
+
presence: async (space, topic) => {
|
|
59
|
+
const match = matchChannel(topic, await resolveChannels(space.spaceId, space.environment));
|
|
60
|
+
if (!match) throw new Error(`No channel of this space matches "${topic}": declare it in the space's \`channels\``);
|
|
61
|
+
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`);
|
|
62
|
+
const members = await presence.of(space, topic);
|
|
63
|
+
return {
|
|
64
|
+
count: members.length,
|
|
65
|
+
members
|
|
66
|
+
};
|
|
67
|
+
},
|
|
55
68
|
grant: async (space, topic, ttlSeconds) => {
|
|
56
69
|
const match = matchChannel(topic, await resolveChannels(space.spaceId, space.environment));
|
|
57
70
|
if (!match) throw new Error(`No channel of this space matches "${topic}": declare it in the space's \`channels\``);
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { RealtimeSpace } from './hub';
|
|
2
|
+
import { ActionKvAdapter } from '../actions/types';
|
|
3
|
+
import { RealtimeSender } from '@plitzi/sdk-shared';
|
|
4
|
+
/** How often a replica says its members are still there: a connection open for hours is seen every this often. */
|
|
5
|
+
export declare const PRESENCE_HEARTBEAT_MS = 30000;
|
|
6
|
+
/** A member not seen this long is gone — its replica went down without saying it: three heartbeats missed. */
|
|
7
|
+
export declare const PRESENCE_STALE_MS: number;
|
|
8
|
+
/** One page on a presence channel, as every replica sees it. */
|
|
9
|
+
export type RealtimePresenceMember = {
|
|
10
|
+
/** Its public name on the channel — the `from` of what it says. */
|
|
11
|
+
from: string;
|
|
12
|
+
/** Who is signed in on it, when someone is. */
|
|
13
|
+
user?: RealtimeSender['user'];
|
|
14
|
+
/** When it arrived, ms. */
|
|
15
|
+
since: number;
|
|
16
|
+
};
|
|
17
|
+
export type RealtimePresence = {
|
|
18
|
+
/** Records the pages that arrived on `topic` here — or are still on it, at a heartbeat: their `seenAt` moves on. */
|
|
19
|
+
touch: (space: RealtimeSpace, topic: string, members: readonly RealtimePresenceMember[]) => Promise<void>;
|
|
20
|
+
/** The page left `topic`. */
|
|
21
|
+
depart: (space: RealtimeSpace, topic: string, from: string) => Promise<void>;
|
|
22
|
+
/** Who is on `topic` now, on every replica, the earliest first — those not seen within {@link PRESENCE_STALE_MS} not. */
|
|
23
|
+
of: (space: RealtimeSpace, topic: string) => Promise<RealtimePresenceMember[]>;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Who is on each presence channel, kept where the actions keep their `kv` — beside the grants and what `retain` keeps —
|
|
27
|
+
* so a function on one replica counts the pages connected to all of them (`ctx.presence`). A page counted by its own
|
|
28
|
+
* replica alone answered a room of three as one (a run's listeners, counted by the pages' own heartbeats in kv).
|
|
29
|
+
*
|
|
30
|
+
* One value per topic, written by compare-and-swap; each member carries when its replica last saw it, so one that went
|
|
31
|
+
* down without a word stops counting within {@link PRESENCE_STALE_MS}, and is dropped at the next write.
|
|
32
|
+
*/
|
|
33
|
+
export declare const createRealtimePresence: (store: ActionKvAdapter, now?: () => number) => RealtimePresence;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { isRecord } from "@plitzi/sdk-shared/helpers";
|
|
2
|
+
//#region src/modules/realtime/presence.ts
|
|
3
|
+
/** How often a replica says its members are still there: a connection open for hours is seen every this often. */
|
|
4
|
+
var PRESENCE_HEARTBEAT_MS = 3e4;
|
|
5
|
+
/** A member not seen this long is gone — its replica went down without saying it: three heartbeats missed. */
|
|
6
|
+
var PRESENCE_STALE_MS = 3 * PRESENCE_HEARTBEAT_MS;
|
|
7
|
+
/** How many times a write is tried while other writes on the same topic keep landing first. */
|
|
8
|
+
var ATTEMPTS = 8;
|
|
9
|
+
var isMember = (value) => isRecord(value) && typeof value.from === "string" && typeof value.since === "number" && typeof value.seenAt === "number" && (value.user === void 0 || isRecord(value.user));
|
|
10
|
+
/** A topic's members, as stored — read from a store something else could have written. */
|
|
11
|
+
var parseKept = (raw) => {
|
|
12
|
+
try {
|
|
13
|
+
const value = JSON.parse(raw ?? "{}");
|
|
14
|
+
return isRecord(value) ? Object.fromEntries(Object.entries(value).filter((entry) => isMember(entry[1]))) : {};
|
|
15
|
+
} catch {
|
|
16
|
+
return {};
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
var fresh = (kept, now) => Object.fromEntries(Object.entries(kept).filter(([, member]) => now - member.seenAt < PRESENCE_STALE_MS));
|
|
20
|
+
/**
|
|
21
|
+
* Who is on each presence channel, kept where the actions keep their `kv` — beside the grants and what `retain` keeps —
|
|
22
|
+
* so a function on one replica counts the pages connected to all of them (`ctx.presence`). A page counted by its own
|
|
23
|
+
* replica alone answered a room of three as one (a run's listeners, counted by the pages' own heartbeats in kv).
|
|
24
|
+
*
|
|
25
|
+
* One value per topic, written by compare-and-swap; each member carries when its replica last saw it, so one that went
|
|
26
|
+
* down without a word stops counting within {@link PRESENCE_STALE_MS}, and is dropped at the next write.
|
|
27
|
+
*/
|
|
28
|
+
var createRealtimePresence = (store, now = Date.now) => {
|
|
29
|
+
const key = ({ spaceId, environment }, topic) => `realtime-presence:${String(spaceId)}:${environment}:${topic}`;
|
|
30
|
+
const change = async (space, topic, next) => {
|
|
31
|
+
const at = key(space, topic);
|
|
32
|
+
for (let attempt = 0; attempt < ATTEMPTS; attempt += 1) {
|
|
33
|
+
const raw = await store.get(at);
|
|
34
|
+
const written = JSON.stringify(next(fresh(parseKept(raw), now())));
|
|
35
|
+
if (await store.swap(at, raw, written, Math.ceil(90))) return;
|
|
36
|
+
}
|
|
37
|
+
throw new Error(`"${topic}" changed under ${String(ATTEMPTS)} writes in a row: its presence was not recorded`);
|
|
38
|
+
};
|
|
39
|
+
return {
|
|
40
|
+
touch: (space, topic, members) => change(space, topic, (kept) => ({
|
|
41
|
+
...kept,
|
|
42
|
+
...Object.fromEntries(members.map((member) => [member.from, {
|
|
43
|
+
...kept[member.from] ?? member,
|
|
44
|
+
seenAt: now()
|
|
45
|
+
}]))
|
|
46
|
+
})),
|
|
47
|
+
depart: (space, topic, from) => change(space, topic, (kept) => Object.fromEntries(Object.entries(kept).filter(([name]) => name !== from))),
|
|
48
|
+
of: async (space, topic) => Object.values(fresh(parseKept(await store.get(key(space, topic))), now())).map((member) => ({
|
|
49
|
+
from: member.from,
|
|
50
|
+
since: member.since,
|
|
51
|
+
...member.user ? { user: member.user } : {}
|
|
52
|
+
})).sort((a, b) => a.since - b.since)
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
//#endregion
|
|
56
|
+
export { PRESENCE_HEARTBEAT_MS, PRESENCE_STALE_MS, createRealtimePresence };
|
|
@@ -16,6 +16,8 @@ export type SocketDeps = {
|
|
|
16
16
|
allowedOrigins: readonly string[];
|
|
17
17
|
/** The way to the jobs `$job:<id>` is about — absent where the server runs none. */
|
|
18
18
|
jobs?: JobLookup;
|
|
19
|
+
/** The deployment's say on whether a space opens its channels (`realtime.admitSpace`). */
|
|
20
|
+
admitSpace?: (spaceId: number) => Promise<string | undefined>;
|
|
19
21
|
};
|
|
20
22
|
/**
|
|
21
23
|
* A page's realtime connection as a WebSocket: the same topics, rules and messages as the Server-Sent Events one, in
|
|
@@ -25,4 +27,4 @@ export type SocketDeps = {
|
|
|
25
27
|
* Refused the way the stream is — a `403` or a `422`, in HTTP, before anything switches — so a page falls back or
|
|
26
28
|
* reports it exactly as it would there.
|
|
27
29
|
*/
|
|
28
|
-
export declare const handleRealtimeSocket: ({ req, res, raw, upgrade, hub, resolveChannels, grants, allowedOrigins, jobs }: SocketDeps) => Promise<void>;
|
|
30
|
+
export declare const handleRealtimeSocket: ({ req, res, raw, upgrade, hub, resolveChannels, grants, allowedOrigins, jobs, admitSpace }: SocketDeps) => Promise<void>;
|
|
@@ -50,7 +50,7 @@ var ackId = (id) => typeof id === "number" && Number.isInteger(id) || typeof id
|
|
|
50
50
|
* Refused the way the stream is — a `403` or a `422`, in HTTP, before anything switches — so a page falls back or
|
|
51
51
|
* reports it exactly as it would there.
|
|
52
52
|
*/
|
|
53
|
-
var handleRealtimeSocket = async ({ req, res, raw, upgrade, hub, resolveChannels, grants, allowedOrigins, jobs }) => {
|
|
53
|
+
var handleRealtimeSocket = async ({ req, res, raw, upgrade, hub, resolveChannels, grants, allowedOrigins, jobs, admitSpace }) => {
|
|
54
54
|
if (!originAllowed(raw, req, allowedOrigins)) {
|
|
55
55
|
answer(res, {
|
|
56
56
|
status: 403,
|
|
@@ -59,7 +59,7 @@ var handleRealtimeSocket = async ({ req, res, raw, upgrade, hub, resolveChannels
|
|
|
59
59
|
});
|
|
60
60
|
return;
|
|
61
61
|
}
|
|
62
|
-
const admission = await admit(req, resolveChannels, grants, jobs);
|
|
62
|
+
const admission = await admit(req, resolveChannels, grants, jobs, admitSpace);
|
|
63
63
|
if (!admission.ok) {
|
|
64
64
|
answer(res, admission.answer);
|
|
65
65
|
return;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { OutboundOptions } from '../../helpers/outboundGuard';
|
|
1
2
|
import { ActionsModule } from '../actions';
|
|
2
3
|
import { ProjectDataLookup } from '../actions/runtime/projectData';
|
|
3
4
|
import { ActionLookups } from '../actions/types';
|
|
@@ -18,7 +19,7 @@ import { SSRAdapters } from '@plitzi/sdk-shared';
|
|
|
18
19
|
*
|
|
19
20
|
* A deployment that resolves server elements some other way still supplies its own `getRscData`, and that one wins.
|
|
20
21
|
*/
|
|
21
|
-
export declare const connectorRscData: ({ connectors, actions, publicDir, data, elementTimeoutMs }: {
|
|
22
|
+
export declare const connectorRscData: ({ connectors, actions, publicDir, data, elementTimeoutMs, sayFailures, outbound }: {
|
|
22
23
|
connectors?: ConnectorLookups;
|
|
23
24
|
actions?: {
|
|
24
25
|
lookups: ActionLookups;
|
|
@@ -33,4 +34,8 @@ export declare const connectorRscData: ({ connectors, actions, publicDir, data,
|
|
|
33
34
|
data?: ProjectDataLookup;
|
|
34
35
|
/** The deployment's per-element ceiling, when it set one. `resolveRscData` decides the default. */
|
|
35
36
|
elementTimeoutMs?: number;
|
|
37
|
+
/** While developing: a failed element says why where the page reads it. */
|
|
38
|
+
sayFailures?: boolean;
|
|
39
|
+
/** The deployment's own origins a connector or a query may reach on its network (`outbound.privateOrigins`). */
|
|
40
|
+
outbound?: OutboundOptions;
|
|
36
41
|
}) => NonNullable<SSRAdapters["getRscData"]>;
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { createActionResolver } from "../actions/runtime/renderResolver.js";
|
|
2
2
|
import { createConnectorResolver } from "../connectors/resolver.js";
|
|
3
|
+
import { externalQueryReader } from "./externalQueryReader.js";
|
|
3
4
|
import { dataLookupResolver, publicFileResolver } from "./publicFileResolver.js";
|
|
4
5
|
import { resolveRscData } from "./resolveRscData.js";
|
|
6
|
+
import { serverQueryOf } from "@plitzi/sdk-shared/schema";
|
|
5
7
|
//#region src/modules/rsc/connectorRscData.ts
|
|
6
8
|
/**
|
|
7
9
|
* `getRscData`, built from the producers the server was already given — connectors, actions, its own static files.
|
|
@@ -18,24 +20,42 @@ import { resolveRscData } from "./resolveRscData.js";
|
|
|
18
20
|
*
|
|
19
21
|
* A deployment that resolves server elements some other way still supplies its own `getRscData`, and that one wins.
|
|
20
22
|
*/
|
|
21
|
-
var connectorRscData = ({ connectors, actions, publicDir, data, elementTimeoutMs }) => {
|
|
22
|
-
const resolveConnector = connectors ? createConnectorResolver(connectors) : void 0;
|
|
23
|
+
var connectorRscData = ({ connectors, actions, publicDir, data, elementTimeoutMs, sayFailures = false, outbound }) => {
|
|
24
|
+
const resolveConnector = connectors ? createConnectorResolver(connectors, outbound) : void 0;
|
|
23
25
|
const resolveAction = actions ? createActionResolver(actions.lookups, actions.module) : void 0;
|
|
24
26
|
const resolvePublicFile = publicDir ? publicFileResolver(publicDir) : void 0;
|
|
25
27
|
const resolveDataFile = data ? dataLookupResolver(data) : void 0;
|
|
28
|
+
const readExternal = externalQueryReader({ outbound });
|
|
26
29
|
/**
|
|
27
30
|
* An element names ONE producer, and which one decides how its data is fetched.
|
|
28
31
|
*
|
|
29
32
|
* A connector is the declarative read and stays the default; an action is the read a manifest cannot express; a
|
|
30
|
-
* file of the server's own is the read with no backend at all
|
|
33
|
+
* file of the server's own is the read with no backend at all, and another site's address is asked as the browser
|
|
34
|
+
* would have asked it (`externalQueryResolver`). Checked in that order so an element carrying more
|
|
31
35
|
* than one keeps resolving the way its page already renders, instead of silently changing under them.
|
|
32
36
|
*/
|
|
33
37
|
const resolveElement = async (context) => {
|
|
34
38
|
const attributes = context.element.attributes;
|
|
35
39
|
if (attributes.connector) return resolveConnector ? resolveConnector(context) : void 0;
|
|
36
40
|
if (attributes.action) return resolveAction ? resolveAction(context) : void 0;
|
|
37
|
-
const
|
|
38
|
-
|
|
41
|
+
const query = serverQueryOf(context.element, context.templateData);
|
|
42
|
+
if (query === void 0) return;
|
|
43
|
+
if (query.kind === "unresolved") throw new Error(`the page server cannot read its query: ${query.why}`);
|
|
44
|
+
if (query.kind === "url") return readExternal(query, context.signal);
|
|
45
|
+
const atPath = {
|
|
46
|
+
...context,
|
|
47
|
+
element: {
|
|
48
|
+
...context.element,
|
|
49
|
+
attributes: {
|
|
50
|
+
...context.element.attributes,
|
|
51
|
+
query: query.path
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
const fromData = resolveDataFile ? await resolveDataFile(atPath) : void 0;
|
|
56
|
+
const fromFile = fromData !== void 0 ? fromData : resolvePublicFile ? await resolvePublicFile(atPath) : void 0;
|
|
57
|
+
if (fromFile === void 0) throw new Error(`no file of this server's answers ${query.path}`);
|
|
58
|
+
return fromFile;
|
|
39
59
|
};
|
|
40
60
|
return async ({ req, spaceId, environment, user, ids, loadOfflineData, flagOverrides, signal }) => {
|
|
41
61
|
const offlineData = await loadOfflineData();
|
|
@@ -50,7 +70,8 @@ var connectorRscData = ({ connectors, actions, publicDir, data, elementTimeoutMs
|
|
|
50
70
|
resolveElement,
|
|
51
71
|
...flagOverrides ? { flagOverrides } : {},
|
|
52
72
|
...signal ? { signal } : {},
|
|
53
|
-
...elementTimeoutMs === void 0 ? {} : { timeoutMs: elementTimeoutMs }
|
|
73
|
+
...elementTimeoutMs === void 0 ? {} : { timeoutMs: elementTimeoutMs },
|
|
74
|
+
sayFailures
|
|
54
75
|
});
|
|
55
76
|
};
|
|
56
77
|
};
|