@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.
Files changed (168) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +54 -2
  3. package/dist/chunks/credentials-DwxZeAvH.mjs +27 -0
  4. package/dist/chunks/errors-bCBfIe7c.mjs +54 -0
  5. package/dist/chunks/grants-BsD-WlLE.mjs +168 -0
  6. package/dist/chunks/load-DBWRZn7G.mjs +48 -0
  7. package/dist/chunks/module-WdDzbjHy.mjs +7032 -0
  8. package/dist/chunks/queueDocument-xYz-KZ5V.mjs +21 -0
  9. package/dist/chunks/queueRules-BCCVgeUE.mjs +487 -0
  10. package/dist/chunks/remote-DopPgCMK.mjs +404 -0
  11. package/dist/chunks/storeClock-Btm7EaVm.mjs +31 -0
  12. package/dist/chunks/taskCatalog-S1IozUTD.mjs +201 -0
  13. package/dist/connectors/connectors.d.ts +7 -0
  14. package/dist/connectors/engine.d.ts +47 -0
  15. package/dist/connectors/getByPath.d.ts +8 -0
  16. package/dist/connectors/projection.d.ts +18 -0
  17. package/dist/connectors/resolver.d.ts +27 -0
  18. package/dist/connectors/types.d.ts +19 -0
  19. package/dist/engine/configSeam.d.ts +10 -0
  20. package/dist/engine/connectorWrite.d.ts +12 -0
  21. package/dist/engine/fileStore.d.ts +60 -0
  22. package/dist/engine/fleet.d.ts +20 -0
  23. package/dist/engine/jobs/calls.d.ts +49 -0
  24. package/dist/engine/jobs/claimSpaces.d.ts +10 -0
  25. package/dist/engine/jobs/codeMarks.d.ts +10 -0
  26. package/dist/engine/jobs/endings.d.ts +42 -0
  27. package/dist/engine/jobs/failureStreak.d.ts +15 -0
  28. package/dist/engine/jobs/fileQueue.d.ts +34 -0
  29. package/dist/engine/jobs/flow.d.ts +11 -0
  30. package/dist/engine/jobs/jobs.d.ts +36 -0
  31. package/dist/engine/jobs/later.d.ts +27 -0
  32. package/dist/engine/jobs/memoryNeeds.d.ts +24 -0
  33. package/dist/engine/jobs/memoryQueue.d.ts +33 -0
  34. package/dist/engine/jobs/memoryWatch.d.ts +21 -0
  35. package/dist/engine/jobs/notNow.d.ts +39 -0
  36. package/dist/engine/jobs/queueDocument.d.ts +15 -0
  37. package/dist/engine/jobs/queueRules.d.ts +64 -0
  38. package/dist/engine/jobs/scheduler.d.ts +70 -0
  39. package/dist/engine/jobs/schedules.d.ts +24 -0
  40. package/dist/engine/jobs/storeClock.d.ts +16 -0
  41. package/dist/engine/jobs/wake.d.ts +6 -0
  42. package/dist/engine/jobs/worker.d.ts +99 -0
  43. package/dist/engine/module.d.ts +96 -0
  44. package/dist/engine/moduleFor.d.ts +3 -0
  45. package/dist/engine/runtime/check.d.ts +24 -0
  46. package/dist/engine/runtime/credentials.d.ts +8 -0
  47. package/dist/engine/runtime/deadline.d.ts +19 -0
  48. package/dist/engine/runtime/email.d.ts +38 -0
  49. package/dist/engine/runtime/errors.d.ts +28 -0
  50. package/dist/engine/runtime/fileKv.d.ts +35 -0
  51. package/dist/engine/runtime/flags.d.ts +16 -0
  52. package/dist/engine/runtime/guards.d.ts +190 -0
  53. package/dist/engine/runtime/kvList.d.ts +28 -0
  54. package/dist/engine/runtime/kvStore.d.ts +36 -0
  55. package/dist/engine/runtime/limits.d.ts +12 -0
  56. package/dist/engine/runtime/memoryKv.d.ts +28 -0
  57. package/dist/engine/runtime/namespaceKv.d.ts +9 -0
  58. package/dist/engine/runtime/precheck.d.ts +28 -0
  59. package/dist/engine/runtime/rateLimit.d.ts +9 -0
  60. package/dist/engine/runtime/redisKv.d.ts +27 -0
  61. package/dist/engine/runtime/renderFailure.d.ts +24 -0
  62. package/dist/engine/runtime/renderResolver.d.ts +16 -0
  63. package/dist/engine/runtime/renderShare.d.ts +12 -0
  64. package/dist/engine/runtime/report.d.ts +15 -0
  65. package/dist/engine/runtime/runAction.d.ts +26 -0
  66. package/dist/engine/runtime/runLogger.d.ts +37 -0
  67. package/dist/engine/runtime/runStats.d.ts +8 -0
  68. package/dist/engine/runtime/scope.d.ts +40 -0
  69. package/dist/engine/runtime/signing.d.ts +27 -0
  70. package/dist/engine/runtime/taskContext.d.ts +54 -0
  71. package/dist/engine/runtime/triggers.d.ts +12 -0
  72. package/dist/engine/taskCatalog.d.ts +28 -0
  73. package/dist/engine/tasks/auth.d.ts +2 -0
  74. package/dist/engine/tasks/builtins.d.ts +10 -0
  75. package/dist/engine/tasks/connector.d.ts +2 -0
  76. package/dist/engine/tasks/db.d.ts +2 -0
  77. package/dist/engine/tasks/email.d.ts +2 -0
  78. package/dist/engine/tasks/flow.d.ts +3 -0
  79. package/dist/engine/tasks/helpers.d.ts +16 -0
  80. package/dist/engine/tasks/http.d.ts +2 -0
  81. package/dist/engine/tasks/kv.d.ts +2 -0
  82. package/dist/engine/tasks/list.d.ts +2 -0
  83. package/dist/engine/tasks/names.d.ts +8 -0
  84. package/dist/engine/tasks/realtime.d.ts +3 -0
  85. package/dist/engine/tasks/registry.d.ts +19 -0
  86. package/dist/engine/tasks/transform.d.ts +2 -0
  87. package/dist/engine/transport/callHandler.d.ts +34 -0
  88. package/dist/engine/transport/cancelHandler.d.ts +23 -0
  89. package/dist/engine/transport/catalogHandler.d.ts +22 -0
  90. package/dist/engine/transport/stream.d.ts +22 -0
  91. package/dist/engine/transport/verifySignature.d.ts +16 -0
  92. package/dist/engine/transport/webhookHandler.d.ts +26 -0
  93. package/dist/engine/types.d.ts +442 -0
  94. package/dist/functions/build.d.ts +27 -0
  95. package/dist/functions/capabilities.d.ts +11 -0
  96. package/dist/functions/config.d.ts +111 -0
  97. package/dist/functions/context.d.ts +15 -0
  98. package/dist/functions/index.d.ts +17 -0
  99. package/dist/functions/index.mjs +461 -0
  100. package/dist/functions/jobControl.d.ts +22 -0
  101. package/dist/functions/jobs.d.ts +104 -0
  102. package/dist/functions/load.d.ts +22 -0
  103. package/dist/functions/local.d.ts +36 -0
  104. package/dist/functions/manifest.d.ts +32 -0
  105. package/dist/functions/native.d.ts +13 -0
  106. package/dist/functions/oauth.d.ts +33 -0
  107. package/dist/functions/routes.d.ts +50 -0
  108. package/dist/functions/runner/remote.d.ts +26 -0
  109. package/dist/functions/scope.d.ts +28 -0
  110. package/dist/functions/space.d.ts +41 -0
  111. package/dist/functions/tryEntry.d.ts +9 -0
  112. package/dist/index.d.ts +47 -0
  113. package/dist/index.mjs +545 -0
  114. package/dist/mongo/claimable.d.ts +5 -0
  115. package/dist/mongo/index.d.ts +4 -0
  116. package/dist/mongo/index.mjs +779 -0
  117. package/dist/mongo/jobQueue.d.ts +38 -0
  118. package/dist/mongo/kv.d.ts +15 -0
  119. package/dist/mysql/index.d.ts +5 -0
  120. package/dist/mysql/index.mjs +808 -0
  121. package/dist/mysql/jobQueue.d.ts +40 -0
  122. package/dist/mysql/kv.d.ts +18 -0
  123. package/dist/mysql/rows.d.ts +64 -0
  124. package/dist/mysql/schema.d.ts +28 -0
  125. package/dist/mysql/summary.d.ts +7 -0
  126. package/dist/realtime/declarations.d.ts +11 -0
  127. package/dist/realtime/failure.d.ts +6 -0
  128. package/dist/realtime/grants.d.ts +22 -0
  129. package/dist/realtime/handlers.d.ts +86 -0
  130. package/dist/realtime/hub.d.ts +71 -0
  131. package/dist/realtime/index.d.ts +105 -0
  132. package/dist/realtime/index.mjs +824 -0
  133. package/dist/realtime/jobs.d.ts +18 -0
  134. package/dist/realtime/message.d.ts +3 -0
  135. package/dist/realtime/presence.d.ts +33 -0
  136. package/dist/realtime/retained.d.ts +21 -0
  137. package/dist/realtime/socket.d.ts +30 -0
  138. package/dist/render/index.d.ts +10 -0
  139. package/dist/render/index.mjs +1 -0
  140. package/dist/render/protocol.d.ts +47 -0
  141. package/dist/render/remote.d.ts +16 -0
  142. package/dist/runtimes/bundle.d.ts +29 -0
  143. package/dist/runtimes/index.d.ts +3 -0
  144. package/dist/runtimes/index.mjs +229 -0
  145. package/dist/runtimes/stages.d.ts +52 -0
  146. package/dist/sqlite/index.d.ts +4 -0
  147. package/dist/sqlite/index.mjs +160 -0
  148. package/dist/sqlite/jobQueue.d.ts +35 -0
  149. package/dist/sqlite/kv.d.ts +34 -0
  150. package/dist/sqlite/open.d.ts +3 -0
  151. package/dist/types/config.d.ts +293 -0
  152. package/dist/types/index.d.ts +2 -0
  153. package/dist/types/index.mjs +1 -0
  154. package/dist/types/jobs.d.ts +317 -0
  155. package/dist/worker/elsewhere.d.ts +16 -0
  156. package/dist/worker/index.d.ts +5 -0
  157. package/dist/worker/index.mjs +1703 -0
  158. package/dist/worker/origin.d.ts +12 -0
  159. package/dist/worker/pageEngine.d.ts +11 -0
  160. package/dist/worker/stages/action.d.ts +24 -0
  161. package/dist/worker/stages/cors.d.ts +9 -0
  162. package/dist/worker/stages/forward.d.ts +12 -0
  163. package/dist/worker/stages/functionRoutes.d.ts +10 -0
  164. package/dist/worker/stages/queuedCalls.d.ts +15 -0
  165. package/dist/worker/stages/realtime.d.ts +9 -0
  166. package/dist/worker/stages/render.d.ts +9 -0
  167. package/dist/worker/worker.d.ts +39 -0
  168. package/package.json +76 -3
@@ -0,0 +1,40 @@
1
+ import { JobQueue } from '../types';
2
+ import { Pool } from 'mysql2/promise';
3
+ export type MysqlJobQueueOptions = {
4
+ /** A pool the deployment opened. The helper borrows connections from it and never ends it. */
5
+ pool: Pool;
6
+ /** Prefix for the three tables — `action_jobs`, `action_schedules`, `action_kv`. Default none. */
7
+ tablePrefix?: string;
8
+ /**
9
+ * Create the tables on first use (`CREATE TABLE IF NOT EXISTS`). Default true; false for a deployment that runs
10
+ * {@link mysqlJobSchemaStatements} through its own migrations.
11
+ */
12
+ createTables?: boolean;
13
+ /** How long a finished job stays readable. A waiting or running one never expires. Default 90 days. */
14
+ retentionDays?: number;
15
+ };
16
+ export type MysqlJobQueue = JobQueue & {
17
+ /** Takes the store's clock again on the next call — after a failover to another primary. */
18
+ resyncClock: () => void;
19
+ };
20
+ /**
21
+ * An {@link JobQueue} over tables in a MySQL database the deployment owns. Tested on MySQL 8; nothing in it
22
+ * needs more than 5.7.
23
+ *
24
+ * The helper for a deployment that already runs MySQL: it borrows connections from the pool it is handed, and creates
25
+ * its three tables on first use unless told not to. Every replica pointed at the same database shares the jobs and the
26
+ * schedules.
27
+ *
28
+ * ```ts
29
+ * import mysql from 'mysql2/promise';
30
+ * import { createMysqlJobQueue, createMysqlKv } from '@plitzi/sdk-actions/mysql';
31
+ *
32
+ * const pool = mysql.createPool(process.env.DATABASE_URL);
33
+ * createServer({ action: { lookups, kv: createMysqlKv({ pool }), jobs: { queue: createMysqlJobQueue({ pool }) } } });
34
+ * ```
35
+ *
36
+ * The contract's rules, as MySQL keeps them: every instant is the SERVER's (`NOW(3)`), `enqueue` is idempotent by the
37
+ * primary key, `claim` takes each job with a single-row compare-and-set — so two workers never take the same one —
38
+ * and reaps a lapsed lease in the same write, and a schedule advances by compare-and-set too.
39
+ */
40
+ export declare const createMysqlJobQueue: ({ pool, tablePrefix, createTables, retentionDays }: MysqlJobQueueOptions) => MysqlJobQueue;
@@ -0,0 +1,18 @@
1
+ import { ActionKvAdapter } from '../engine/types';
2
+ import { Pool } from 'mysql2/promise';
3
+ export type MysqlKvOptions = {
4
+ /** A pool the deployment opened. Never ended here. */
5
+ pool: Pool;
6
+ /** Same prefix as the job queue's, when both are used: the three tables are created together. */
7
+ tablePrefix?: string;
8
+ /** Create the tables on first use. Default true. */
9
+ createTables?: boolean;
10
+ };
11
+ /**
12
+ * An {@link ActionKvAdapter} over a table in a MySQL database the deployment owns.
13
+ *
14
+ * What the run guards' single-flight keys and the `kv` tasks' counters need from a store the replicas share: a TTL the
15
+ * store enforces and an increment nobody can race. The increment is one `INSERT … ON DUPLICATE KEY UPDATE`, which
16
+ * MySQL applies to the row under its lock — so two replicas counting at once both count.
17
+ */
18
+ export declare const createMysqlKv: ({ pool, tablePrefix, createTables }: MysqlKvOptions) => ActionKvAdapter;
@@ -0,0 +1,64 @@
1
+ import { ActionSchedule, JobSpaces, JobTake } from '../types';
2
+ import { Job } from '@plitzi/sdk-shared';
3
+ /** The MySQL job queue's rows, as they are read and written, and what a claim takes (`jobQueue.ts`). */
4
+ export type Numeric = number | string;
5
+ export type JobRow = {
6
+ id: string;
7
+ space_id: Numeric;
8
+ target_kind: string;
9
+ target_name: string;
10
+ target: string;
11
+ environment: string;
12
+ input: string;
13
+ due_at: Numeric;
14
+ max_attempts: Numeric;
15
+ missed: Numeric | null;
16
+ job_key: string | null;
17
+ status: string;
18
+ run_at: Numeric;
19
+ attempts: Numeric;
20
+ lease_until: Numeric | null;
21
+ worker_id: string | null;
22
+ run_id: string | null;
23
+ cancel_requested: Numeric;
24
+ created_at: Numeric;
25
+ updated_at: Numeric;
26
+ error: string | null;
27
+ history: string;
28
+ state: string | null;
29
+ progress: string | null;
30
+ result: string | null;
31
+ pause_requested: Numeric;
32
+ active_ms: Numeric;
33
+ holder_memory_mb: Numeric | null;
34
+ needs_memory_mb: Numeric | null;
35
+ near_memory_limit: Numeric;
36
+ };
37
+ export type ScheduleRow = {
38
+ space_id: Numeric;
39
+ action_id: string;
40
+ cron: string;
41
+ timezone: string | null;
42
+ environment: string;
43
+ enabled: Numeric;
44
+ next_run_at: Numeric;
45
+ last_fire_at: Numeric | null;
46
+ missed: Numeric;
47
+ max_attempts: Numeric;
48
+ updated_at: Numeric;
49
+ };
50
+ /**
51
+ * A row as the contract shapes it.
52
+ *
53
+ * `BIGINT` arrives as a number or as a string depending on how the deployment configured its pool
54
+ * (`bigNumberStrings`), so every numeric column goes through `Number`. The text columns hold only what this queue
55
+ * wrote into them — a status, an environment, a trigger — which is why they can be read back as those types.
56
+ */
57
+ export declare const toJob: (row: JobRow) => Job;
58
+ /** A value of a JSON column, or SQL's NULL for none. */
59
+ export declare const jsonOrNull: (value: unknown) => string | null;
60
+ export declare const toSchedule: (row: ScheduleRow) => ActionSchedule;
61
+ export declare const claimable: (at: number, spaces: JobSpaces | undefined, memoryMb: number | undefined, takes?: JobTake) => {
62
+ sql: string;
63
+ params: (number | string)[];
64
+ };
@@ -0,0 +1,28 @@
1
+ import { Queryable } from '@plitzi/sdk-kernel/mysql';
2
+ /** The tables the job queue and the key/value store keep, backticked and prefixed. */
3
+ export type JobTables = {
4
+ jobs: string;
5
+ schedules: string;
6
+ kv: string;
7
+ };
8
+ /**
9
+ * Table names under a prefix. A prefix is part of an identifier, which no driver can bind as a parameter — so it is
10
+ * held to the characters an unquoted identifier may use, and refused otherwise, rather than escaped and hoped for.
11
+ */
12
+ export declare const jobTables: (prefix?: string) => JobTables;
13
+ /**
14
+ * The tables, as SQL — for a deployment that runs its own migrations rather than letting the helpers create them.
15
+ *
16
+ * Instants are epoch milliseconds in `BIGINT`, read from the SERVER's clock; `history` and `input` are JSON kept as
17
+ * text, because they are only ever read whole. Separate from the account store's schema and its version: a deployment
18
+ * can use either without the other.
19
+ *
20
+ * A `kv` key is BYTES, as it is in Redis and in memory: under a collation `Board` and `board` — and `a` and `a ` — were
21
+ * one key here and two everywhere else. A value is a `MEDIUMTEXT`: a `TEXT` stops at 64 KB, and past it MySQL
22
+ * refuses the write, or cuts it short where it is not strict.
23
+ */
24
+ export declare const mysqlJobSchemaStatements: (prefix?: string) => string[];
25
+ /** The server's now, in epoch ms, as an SQL expression — what every comparison reads instead of a caller's clock. */
26
+ export declare const NOW_MS = "CAST(ROUND(UNIX_TIMESTAMP(NOW(3)) * 1000) AS SIGNED)";
27
+ /** Creates the tables once per process, on first use; a failure is retried by the next call rather than remembered. */
28
+ export declare const ensureJobTables: (db: Queryable, prefix: string, create: boolean) => (() => Promise<void>);
@@ -0,0 +1,7 @@
1
+ import { JobQueueSummary } from '../types';
2
+ import { Pool } from 'mysql2/promise';
3
+ /**
4
+ * The jobs table at a glance (`JobQueue.summarize`), counted by MySQL: every status, what waits by what it is, and the
5
+ * spaces with the most waiting — with what the job of each touched last said.
6
+ */
7
+ export declare const summarizeJobsTable: (conn: Pool, table: string, spaces: number) => Promise<JobQueueSummary>;
@@ -0,0 +1,11 @@
1
+ import { ChannelDeclarations, OfflineDataRaw } from '@plitzi/sdk-shared';
2
+ type GetOfflineData = (spaceId: number, environment: string, revision?: number) => Promise<OfflineDataRaw | undefined>;
3
+ /**
4
+ * The channels a space declares, read from its schema and remembered for a few seconds.
5
+ *
6
+ * A publish is checked against them on every message; reading the space's documents for each one would cost more
7
+ * than the message. A space that changes its channels is heard within the TTL.
8
+ */
9
+ export declare const createChannelResolver: (getOfflineData: GetOfflineData) => (spaceId: number, environment: string, revision?: number) => Promise<ChannelDeclarations | undefined>;
10
+ export type ChannelResolver = ReturnType<typeof createChannelResolver>;
11
+ export {};
@@ -0,0 +1,6 @@
1
+ /**
2
+ * What a realtime promise nobody waits on does when the pub/sub under it fails — Redis timing out under load: it says so
3
+ * and the server goes on. Left to reject, it reached the process's `unhandledRejection` handler, which shuts the whole
4
+ * server down over one undelivered cursor.
5
+ */
6
+ export declare const warnRealtime: (what: string) => (error: unknown) => void;
@@ -0,0 +1,22 @@
1
+ import { RealtimeSpace } from './hub';
2
+ import { ActionKvAdapter } from '../engine/types';
3
+ /** How long a grant opens its topic when the flow does not say: a day, which outlives any one visit. */
4
+ export declare const DEFAULT_GRANT_SECONDS = 86400;
5
+ /** The longest a grant may last: thirty days. A page that stays open longer asks its action for a new one. */
6
+ export declare const MAX_GRANT_SECONDS: number;
7
+ export type RealtimeGrants = {
8
+ /** A grant for `topic`, good for `ttlSeconds` — what `realtime.grant` hands the page. */
9
+ issue: (space: RealtimeSpace, topic: string, ttlSeconds?: number) => Promise<string>;
10
+ /** Whether `grant` was issued for exactly `topic` of this space, and has neither run out nor been revoked. */
11
+ opens: (space: RealtimeSpace, topic: string, grant: string) => Promise<boolean>;
12
+ /** `grant` no longer opens `topic` — or, with none named, no grant issued for it until now does. */
13
+ revoke: (space: RealtimeSpace, topic: string, grant?: string) => Promise<void>;
14
+ };
15
+ /**
16
+ * The grants a server has issued, kept in the store its actions' `kv` uses — so a grant one replica issued opens the
17
+ * topic on whichever replica the page connects to, and nothing new has to be configured for it. A random token rather
18
+ * than a signature: there is no secret to share between replicas, and a grant is only ever as old as its lifetime.
19
+ *
20
+ * Keyed under `realtime-grant:`, a prefix no key a flow writes can reach (theirs are `kv:action:<space>:…`).
21
+ */
22
+ export declare const createRealtimeGrants: (store: ActionKvAdapter) => RealtimeGrants;
@@ -0,0 +1,86 @@
1
+ import { ChannelResolver } from './declarations';
2
+ import { RealtimeGrants } from './grants';
3
+ import { RealtimeConnection, RealtimeHub, RealtimeSpace } from './hub';
4
+ import { JobLookup } from './jobs';
5
+ import { RawResponse } from '@plitzi/sdk-kernel/http';
6
+ import { SSRRequest, SSRResponseHelpers } from '@plitzi/sdk-kernel/types';
7
+ import { ChannelDeclaration, RealtimeSender } from '@plitzi/sdk-shared';
8
+ export type RealtimeRefusal = {
9
+ topic: string;
10
+ /**
11
+ * `ungranted`: the channel is declared `grant: true`, and no grant the page sent opens this topic. `unavailable`: the
12
+ * deployment does not open this space's channels (`realtime.admitSpace`).
13
+ */
14
+ reason: 'undeclared' | 'unauthenticated' | 'forbidden' | 'ungranted' | 'unavailable';
15
+ };
16
+ /** An answer in HTTP terms, whichever transport carries it: a status, and what went wrong when something did. */
17
+ export type RealtimeAnswer = {
18
+ status: number;
19
+ error?: string;
20
+ reason?: string;
21
+ refused?: RealtimeRefusal[];
22
+ };
23
+ export declare const answer: (res: SSRResponseHelpers, { status, ...payload }: RealtimeAnswer) => void;
24
+ /** What a page may open, decided once for either transport. */
25
+ export type Admission = {
26
+ ok: false;
27
+ answer: RealtimeAnswer;
28
+ } | {
29
+ ok: true;
30
+ space: RealtimeSpace;
31
+ user?: RealtimeSender['user'];
32
+ accepted: Map<string, ChannelDeclaration>;
33
+ /** The grant each accepted topic of a `grant: true` channel was opened with. */
34
+ granted: Map<string, string>;
35
+ refused: RealtimeRefusal[];
36
+ /** It hears and never speaks: the page asked to watch (`OBSERVER_COOKIE_NAME`). */
37
+ observer: boolean;
38
+ };
39
+ /**
40
+ * Which of the topics a page asked for (`?topics=a,b`) it may open: each checked against the channels the space
41
+ * declares and against the visitor's access. One that fails is reported, not a reason to refuse the rest; all failing
42
+ * is a `403`.
43
+ */
44
+ export declare const admit: (req: SSRRequest, resolveChannels: ChannelResolver, grants: RealtimeGrants, jobs?: JobLookup, admitSpace?: (spaceId: number) => Promise<string | undefined>) => Promise<Admission>;
45
+ /** A new connection for what was admitted, speaking through `send`. */
46
+ export declare const connectionFor: (admission: Extract<Admission, {
47
+ ok: true;
48
+ }>, send: RealtimeConnection["send"], end: RealtimeConnection["end"]) => RealtimeConnection;
49
+ /**
50
+ * A page publishing, whichever way it arrived: only on a topic its connection subscribed to, only on a channel pages
51
+ * may send on, within its size and its rate — and stamped by the server with who sent it and when, whatever the
52
+ * message said.
53
+ */
54
+ export declare const publishFrom: (hub: RealtimeHub, connection: RealtimeConnection, { topic, type, data, echo }: {
55
+ topic?: unknown;
56
+ type?: unknown;
57
+ data?: unknown;
58
+ echo?: unknown;
59
+ }) => Promise<RealtimeAnswer>;
60
+ export type SubscribeDeps = {
61
+ req: SSRRequest;
62
+ res: SSRResponseHelpers;
63
+ raw: RawResponse;
64
+ signal: AbortSignal;
65
+ hub: RealtimeHub;
66
+ resolveChannels: ChannelResolver;
67
+ grants: RealtimeGrants;
68
+ /** The way to the jobs `$job:<id>` is about — absent where the server runs none. */
69
+ jobs?: JobLookup;
70
+ /** The deployment's say on whether a space opens its channels (`realtime.admitSpace`). */
71
+ admitSpace?: (spaceId: number) => Promise<string | undefined>;
72
+ };
73
+ /**
74
+ * `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.
75
+ *
76
+ * The first event, `ready`, tells the page its public name (`from`) and the secret its publishes carry. Resolves when
77
+ * the page goes.
78
+ */
79
+ export declare const handleRealtimeSubscribe: ({ req, res, raw, signal, hub, resolveChannels, grants, jobs, admitSpace }: SubscribeDeps) => Promise<void>;
80
+ export type PublishDeps = {
81
+ req: SSRRequest;
82
+ res: SSRResponseHelpers;
83
+ hub: RealtimeHub;
84
+ };
85
+ /** `POST /_realtime` `{ token, topic, type, data }` — a page on a Server-Sent Events connection, publishing. */
86
+ export declare const handleRealtimePublish: ({ req, res, hub }: PublishDeps) => Promise<void>;
@@ -0,0 +1,71 @@
1
+ import { RealtimePresence } from './presence';
2
+ import { RealtimeRetained } from './retained';
3
+ import { ChannelDeclaration, PubSubAdapter, RealtimeMessage, RealtimeSender } from '@plitzi/sdk-shared';
4
+ /** The space a connection belongs to: its topics are that space's and no other's. */
5
+ export type RealtimeSpace = {
6
+ spaceId: number;
7
+ environment: string;
8
+ };
9
+ /** One page, connected. */
10
+ export type RealtimeConnection = {
11
+ /** Its public name — the `from` of everything it sends. */
12
+ id: string;
13
+ /** Its secret: what a publish proves it comes from this connection with. Never sent to anyone else. */
14
+ token: string;
15
+ space: RealtimeSpace;
16
+ user?: RealtimeSender['user'];
17
+ /** The topics it subscribed to, with the channel each falls under. */
18
+ topics: Map<string, ChannelDeclaration>;
19
+ /** The grant each topic of a `grant: true` channel was opened with — what a revoke names. */
20
+ grants: Map<string, string>;
21
+ /** The topics it announced itself on, which hear `$leave` when it goes. */
22
+ announced: Set<string>;
23
+ /** A page that watches (`page check`, `page shot`): it hears its topics, arrives on none and says nothing on any. */
24
+ observer: boolean;
25
+ /** Messages sent this second, by topic — the rate a channel allows is per connection, and a connection is here. */
26
+ sent: Map<string, {
27
+ second: number;
28
+ count: number;
29
+ }>;
30
+ send: (event: string, data: unknown) => void;
31
+ /** Closes it from the server's side — the server is going away. Its own `close` then lets it go as any other. */
32
+ end: () => void;
33
+ };
34
+ /** A space's topic, as the adapter knows it: namespaced, so two spaces never hear each other. */
35
+ export declare const adapterTopic: ({ spaceId, environment }: RealtimeSpace, topic: string) => string;
36
+ export type RealtimeHub = ReturnType<typeof createRealtimeHub>;
37
+ /**
38
+ * This process's connections, and the ONE adapter subscription per topic they share.
39
+ *
40
+ * A hundred pages on one board are a hundred connections here and a single subscription to the adapter: a message
41
+ * arrives once and is written to each of them. The last one to leave a topic unsubscribes it.
42
+ */
43
+ export declare const createRealtimeHub: (pubsub: PubSubAdapter, retained: RealtimeRetained, presence?: RealtimePresence) => {
44
+ publish: (space: RealtimeSpace, message: RealtimeMessage) => Promise<void>;
45
+ from: (connection: RealtimeConnection, topic: string, type: string, data: unknown, echo?: boolean) => RealtimeMessage;
46
+ find: (token: string) => RealtimeConnection | undefined;
47
+ /**
48
+ * Lets go of `topic` every connection, on every replica, that opened it with `grant` — or with any grant, naming
49
+ * none. What stops a grant that is already in use; `grants.revoke` is what stops it being used again.
50
+ */
51
+ revoke: (space: RealtimeSpace, topic: string, grant?: string) => Promise<void>;
52
+ /**
53
+ * Subscribes a new connection to its topics, hands it what each `retain: true` one keeps, and tells the members of
54
+ * each presence channel it arrived. What is kept is read AFTER joining, so nothing said in between is missed; a
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.
57
+ */
58
+ connect: (connection: RealtimeConnection) => Promise<void>;
59
+ /** Unsubscribes a connection that went away, and tells the channels it announced itself on. */
60
+ disconnect: (connection: RealtimeConnection) => Promise<void>;
61
+ /**
62
+ * Every connection closed from here: the server is shutting down. An open socket or event stream is a request that
63
+ * never ends, so a server waiting for them to finish waited for ever — each is told to go, and goes the way it
64
+ * goes when its page leaves.
65
+ */
66
+ closeAll: () => void;
67
+ /** How many connections this process holds — for tests and for a health endpoint. */
68
+ readonly connectionCount: number;
69
+ /** How many topics this process holds a subscription for — for tests and for a health endpoint. */
70
+ readonly topicCount: number;
71
+ };
@@ -0,0 +1,105 @@
1
+ import { ChannelResolver } from './declarations';
2
+ import { RealtimeGrants } from './grants';
3
+ import { RealtimeHub } from './hub';
4
+ import { JobLookup } from './jobs';
5
+ import { RealtimePresenceMember } from './presence';
6
+ import { ActionKvAdapter, ActionRealtime } from '../engine/types';
7
+ import { EngineConfig } from '../types';
8
+ import { FunctionJobView, PubSubAdapter, RealtimeTransport } from '@plitzi/sdk-shared';
9
+ export { handleRealtimePublish, handleRealtimeSubscribe } from './handlers';
10
+ export { handleRealtimeSocket } from './socket';
11
+ /** A type a flow publishes: its own vocabulary — the `$` types are the channel's. */
12
+ /** Where a page's realtime channels are, and how it reaches them, when the deployment says nothing. */
13
+ export declare const DEFAULT_REALTIME_PATH = "/_realtime";
14
+ export declare const DEFAULT_REALTIME_TRANSPORT: RealtimeTransport;
15
+ export type RealtimeModule = {
16
+ hub: RealtimeHub;
17
+ path: string;
18
+ /** What pages are told to connect with. Both are served whatever this says. */
19
+ transport: RealtimeTransport;
20
+ /** Origins besides the server's own whose pages may open a socket. */
21
+ allowedOrigins: readonly string[];
22
+ /** The deployment's say on whether a space opens its channels (`realtime.admitSpace`). */
23
+ admitSpace?: (spaceId: number) => Promise<string | undefined>;
24
+ resolveChannels: ChannelResolver;
25
+ /** The grants issued for topics of channels declared `grant: true`, and the check a subscription makes. */
26
+ grants: RealtimeGrants;
27
+ /** Closes every connection this process holds: the server is shutting down (`HttpServerParts.onClosing`). */
28
+ close: () => void;
29
+ /**
30
+ * Publishes from the server — what a flow's `realtime.publish` does. Checked against the space's channels like a
31
+ * page's publish, and sent `from: 'server'`: the one sender a page cannot be.
32
+ */
33
+ publish: (space: {
34
+ spaceId: number;
35
+ environment: string;
36
+ }, topic: string, type: string, data: unknown) => Promise<void>;
37
+ /**
38
+ * A grant for one topic of a channel declared `grant: true` — what a flow's `realtime.grant` hands a page, once it
39
+ * has decided the visitor may be there. Refused for a topic of any other channel: a grant it would never ask for
40
+ * is a mistake in the flow, not a key to hand out.
41
+ */
42
+ grant: (space: {
43
+ spaceId: number;
44
+ environment: string;
45
+ }, topic: string, ttlSeconds?: number) => Promise<string>;
46
+ /**
47
+ * `grant` no longer opens `topic` — or, naming none, no grant issued for it until now does: nobody who holds one gets
48
+ * in again, and whoever is on the topic with one, on any replica, is let go of it (`$revoked`). A page kept out asks
49
+ * the action that lets it in for a new grant, if it still may.
50
+ */
51
+ revoke: (space: {
52
+ spaceId: number;
53
+ environment: string;
54
+ }, topic: string, grant?: string) => Promise<void>;
55
+ /**
56
+ * Who is on a topic of a `presence: true` channel now, on every replica — what a function's `ctx.presence` reads. A
57
+ * topic of any other channel is refused: nobody is counted there, and an empty answer would read as an empty room.
58
+ */
59
+ presence: (space: {
60
+ spaceId: number;
61
+ environment: string;
62
+ }, topic: string) => Promise<{
63
+ count: number;
64
+ members: RealtimePresenceMember[];
65
+ }>;
66
+ /** Says a job of the space's functions as it is now on its topic (`$job:<id>`), kept for a page that joins later. */
67
+ publishJob: (space: {
68
+ spaceId: number;
69
+ environment: string;
70
+ }, jobId: string, view: FunctionJobView) => Promise<void>;
71
+ /** Hands the realtime the way to a job, which the actions module holds: what the door of `$job:<id>` reads. */
72
+ watchJobs: (lookup: JobLookup) => void;
73
+ /** The way to a job, once the actions module handed it — what a subscription to `$job:<id>` is decided by. */
74
+ jobs: () => JobLookup | undefined;
75
+ };
76
+ /**
77
+ * The server's realtime channels, built once per config — or `undefined` when they are off or cannot be: without the
78
+ * space's documents (`getOfflineData`) there is nothing to say which channels a space declares, so none is opened.
79
+ */
80
+ /**
81
+ * What a server's realtime channels are made of — the hub over `pubsub`, the grants, presence and what a `retain`
82
+ * channel keeps in `kv` — given what it needs alone, so a process that is no page server (a deployment's own actions
83
+ * runner, `createActionsModule`) publishes on the same channels as the pages: hand it the same `pubsub` and `kv` the
84
+ * page servers have, or what it says is heard by nobody. `realtimeModuleFor` makes a page server's with this.
85
+ */
86
+ export type RealtimeModuleOptions = {
87
+ /** The space's documents, where its `channels` are declared. */
88
+ getOfflineData: NonNullable<EngineConfig['adapters']['getOfflineData']>;
89
+ /** What carries a message to every replica (`createRedisPubSub`). Absent, this process alone. */
90
+ pubsub?: PubSubAdapter;
91
+ /** Where grants, presence and retained messages are kept, shared by every replica. Absent, this process alone. */
92
+ kv?: ActionKvAdapter;
93
+ path?: string;
94
+ transport?: RealtimeTransport;
95
+ allowedOrigins?: readonly string[];
96
+ admitSpace?: (spaceId: number) => Promise<string | undefined>;
97
+ };
98
+ export declare const createRealtimeModule: (options: RealtimeModuleOptions) => RealtimeModule;
99
+ /**
100
+ * The channels an actions runner that serves no pages publishes on (`createActionsModule({ realtime })`): a job's
101
+ * `ctx.publish`, a flow's `realtime.publish`, a function job's `$job:<id>`. Without them a job that publishes fails on
102
+ * that runner — handed the same `pubsub` and `kv` as the page servers, it reaches every page they hold open.
103
+ */
104
+ export declare const createActionRealtime: (options: RealtimeModuleOptions) => ActionRealtime;
105
+ export declare const realtimeModuleFor: (config: EngineConfig) => RealtimeModule | undefined;