@plitzi/sdk-actions 0.0.0-stage → 0.39.3

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 +18 -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,64 @@
1
+ import { JobQueue, JobQueueSummary, JobTake, ActionSchedule, WaitingJobs } from '../../types';
2
+ import { Job, JobStatus } from '@plitzi/sdk-shared';
3
+ /** The kind of work a job is (`JobTake`): what a claim's `takes` picks by. */
4
+ export declare const takeOf: (target: Job["target"]) => JobTake;
5
+ /**
6
+ * The queue's rules — what `enqueue`, `claim`, `settle`… do to the jobs and schedules — over a state handed to them,
7
+ * kept apart from WHERE the state is: a process's Maps (`createMemoryJobQueue`), a JSON file (`createFileJobQueue`), a
8
+ * SQLite table (`createSqliteJobQueue`). One set of rules, so a store kept anywhere keeps the contract to the letter: a
9
+ * test that passes against one is testing all of them.
10
+ */
11
+ /** The jobs and the schedules, by id: what a queue keeps. */
12
+ export type QueueState = {
13
+ jobs: Map<string, Job>;
14
+ schedules: Map<string, ActionSchedule>;
15
+ };
16
+ /** The queue's methods, answering at once: what each store wraps in its own way of reading and keeping the state. */
17
+ export type QueueRules = {
18
+ [K in keyof JobQueue]: (...args: Parameters<JobQueue[K]>) => Awaited<ReturnType<JobQueue[K]>>;
19
+ };
20
+ /**
21
+ * Whether a call changed the state, by its method and what it answered — what a store keeping the state elsewhere writes
22
+ * back after. A worker claims every second: a claim that took nothing, a refused `write` or `cancel` change nothing, and
23
+ * are not written.
24
+ */
25
+ export declare const changedBy: <K extends keyof JobQueue>(method: K, answer: Awaited<ReturnType<JobQueue[K]>>) => boolean;
26
+ /** What a schedule is kept by: its space and its action. */
27
+ export declare const scheduleKey: (spaceId: number, actionId: string) => string;
28
+ export type QueueRulesOptions = {
29
+ /** How many finished jobs to keep before the oldest are dropped. */
30
+ retainFinished: number;
31
+ /** What the queue calls now, in epoch ms: the one clock everything here reads. */
32
+ clock: () => number;
33
+ /**
34
+ * Told when a rule changed the state though its answer does not say so (`changedBy`): a claim that reaped a job, or
35
+ * set one aside, and took nothing. A store that keeps the state elsewhere writes it back then too.
36
+ */
37
+ onUnansweredChange?: () => void;
38
+ };
39
+ export declare const queueRules: ({ jobs, schedules }: QueueState, { retainFinished, clock, onUnansweredChange }: QueueRulesOptions) => QueueRules;
40
+ /** A state with nothing in it. */
41
+ /** Which of {@link WaitingJobs} a job is, by its target's kind and trigger — as a store's own query reads them. */
42
+ export declare const waitingKindOf: (kind: string, trigger: string | null | undefined) => keyof WaitingJobs;
43
+ /** Every status at zero: what a summary counts up from, so a status nothing is in still says 0. */
44
+ export declare const noJobsByStatus: () => Record<JobStatus, number>;
45
+ /**
46
+ * The status a job waits for the queue in. One set aside (`paused`) waits for a person and is said apart
47
+ * (`byStatus.paused`): counted as waiting, 32 jobs set aside at their limits read as a queue falling behind for
48
+ * minutes, the oldest of them its wait, with nothing left to run.
49
+ */
50
+ export declare const WAITING_STATUSES: readonly JobStatus[];
51
+ /** The statuses a job a worker died running is in while it needs a larger worker: waiting for one, or set aside. */
52
+ export declare const NEEDING_STATUSES: readonly JobStatus[];
53
+ /**
54
+ * The queue at a glance, from its jobs: what `summarize` answers for a store that holds them all in hand — the database
55
+ * ones count the same in their own query.
56
+ */
57
+ export declare const summarizeJobs: (all: readonly Job[], spaces: number) => JobQueueSummary;
58
+ export declare const emptyState: () => QueueState;
59
+ /** How a store runs one method of the rules: reading its state, and keeping it after one that changes it. */
60
+ export type QueueAccess = <K extends keyof JobQueue>(method: K, args: Parameters<JobQueue[K]>) => Promise<Awaited<ReturnType<JobQueue[K]>>>;
61
+ /** One method of the rules, called with the arguments its contract types. */
62
+ export declare const applyRule: <K extends keyof JobQueue>(rules: QueueRules, method: K, args: Parameters<JobQueue[K]>) => Awaited<ReturnType<JobQueue[K]>>;
63
+ /** The contract, each method run through `access`: what every store answers with. */
64
+ export declare const queueOver: (access: QueueAccess) => JobQueue;
@@ -0,0 +1,70 @@
1
+ import { JobQueue } from '../../types';
2
+ import { ActionLookups } from '../types';
3
+ import { Environment } from '@plitzi/sdk-shared';
4
+ export type SchedulerOptions = {
5
+ queue: JobQueue;
6
+ lookups: ActionLookups;
7
+ /**
8
+ * Whether a space may have scheduled runs at all — its plan, say: why not, or nothing. A space refused has none:
9
+ * its schedules are taken off the queue, and a fire already due is not run. Absent, every space may.
10
+ */
11
+ admit?: (spaceId: number) => Promise<string | undefined>;
12
+ /** Which environment scheduled runs execute in. Defaults to `main`, the document the builder edits. */
13
+ environment?: Environment;
14
+ /** How often this replica looks for due schedules. Default 15s — the resolution of a cron is a minute. */
15
+ pollMs?: number;
16
+ /** Schedules swept per pass. */
17
+ batch?: number;
18
+ /** Attempts a job produced here is given. */
19
+ maxAttempts?: number;
20
+ /** How often a space's schedules are re-derived from its documents. Default 15 minutes. A deployment that
21
+ * reconciles on save needs this only as a safety net. */
22
+ reconcileMs?: number;
23
+ /** The spaces to reconcile, for a server that serves a known few. `listScheduledSpaces` wins over it. */
24
+ spaces?: number[];
25
+ /** Every failed pass, in place of the default report — a warning, then an error once a pass has kept failing for a
26
+ * minute (see `createFailureStreak`). */
27
+ onError?: (error: unknown) => void;
28
+ };
29
+ export type SweepResult = {
30
+ /** Fires this pass turned into jobs. */
31
+ enqueued: string[];
32
+ /** Fires another replica had already enqueued. Not a problem: it is the guarantee working. */
33
+ duplicates: string[];
34
+ /** Fires that went by while nothing was running, by schedule. */
35
+ missed: {
36
+ spaceId: number;
37
+ actionId: string;
38
+ count: number;
39
+ }[];
40
+ };
41
+ export type Scheduler = {
42
+ /** One pass. Exposed because a deployment driving this from its own cron — a k8s CronJob, a queue tick — needs
43
+ * a way in that is not a timer, and because a test must not have to wait for one. */
44
+ sweep: () => Promise<SweepResult>;
45
+ /** Re-derives one space's schedules from its action documents. Called by a deployment whenever they change. */
46
+ reconcile: (spaceId: number) => Promise<void>;
47
+ start: () => void;
48
+ stop: () => void;
49
+ };
50
+ /**
51
+ * Turns due schedules into jobs. Nothing else.
52
+ *
53
+ * **There is no leader.** Every replica sweeps, and that is safe because a fire's job id is derived from the fire's
54
+ * own stored instant: two replicas reaching the same fire write the same id, and the queue keeps the first. A
55
+ * leader lock would only add a way for the cluster to have no producer at all for a minute — which is exactly the
56
+ * failure a nightly digest cannot afford.
57
+ *
58
+ * **No clock is trusted but the queue's.** Which schedules are due is the queue's answer, the fire instant is the
59
+ * one the schedule row already held, and the next one is computed from that row. A replica in Santiago and a
60
+ * replica in Frankfurt produce the same fires, once each, however far apart their clocks have drifted.
61
+ *
62
+ * **A fire is enqueued BEFORE the schedule moves on.** If this process dies between the two, the schedule is still
63
+ * due, the next sweep enqueues the same id — a no-op — and advances. Nothing is produced twice and nothing is
64
+ * lost; the ordering is the whole of that guarantee.
65
+ *
66
+ * **An outage does not replay as a storm.** The overdue fire becomes one job, and the schedule then jumps to the
67
+ * first occurrence after now, recording how many went by. A digest missed for a day sends once and says it missed
68
+ * 23 — rather than sending 23 times, which is how a scheduler that "catches up" turns an outage into an incident.
69
+ */
70
+ export declare const createScheduler: ({ queue, lookups, environment, pollMs, batch, maxAttempts, reconcileMs, spaces, admit, onError }: SchedulerOptions) => Scheduler;
@@ -0,0 +1,24 @@
1
+ import { ActionScheduleInput } from '../../types';
2
+ import { ActionEntry, Environment } from '@plitzi/sdk-shared';
3
+ /** Attempts a scheduled job is given before it is left for an operator. Overridable per deployment. */
4
+ export declare const DEFAULT_MAX_ATTEMPTS = 3;
5
+ /**
6
+ * The schedule a document declares, or nothing.
7
+ *
8
+ * The cron and the zone are read through the same fields the runner used to read at every tick — but read ONCE,
9
+ * when the document is saved, and written to a row. What the tick then reads is a due time, not a JSON blob: the
10
+ * difference between one indexed query a minute and every action document in the deployment, parsed.
11
+ *
12
+ * A zone `Intl` does not know is dropped rather than silently treated as UTC. The validator already tells the
13
+ * author, and a schedule that fires at the wrong hour is worse than one that visibly never fires at all.
14
+ */
15
+ export declare const scheduleFor: (entry: ActionEntry, spaceId: number, environment: Environment, from: Date, maxAttempts?: number) => ActionScheduleInput | undefined;
16
+ /** Every schedule a space's actions declare, as of one instant. */
17
+ export declare const schedulesFor: (entries: ActionEntry[], spaceId: number, environment: Environment, from: Date, maxAttempts?: number) => ActionScheduleInput[];
18
+ /**
19
+ * The id a fire gets, and the whole of the exactly-once guarantee.
20
+ *
21
+ * Derived from the STORED fire instant rather than from any node's reading of the clock, so two replicas that
22
+ * disagree about what time it is still write the same id — and the second one's enqueue is a no-op.
23
+ */
24
+ export declare const scheduleJobId: (spaceId: number, actionId: string, fireAt: number) => string;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The clock of the store a queue lives in, read cheaply.
3
+ *
4
+ * Every comparison a queue makes — is this due, has this lease lapsed — is made against ONE clock, and a cluster whose
5
+ * replicas sit in different countries only agrees on the store's. Reading it on every call would put a round trip on
6
+ * the path of every claim and every heartbeat, so it is read once and then trusted for the ELAPSED time only: the one
7
+ * thing a wrong local clock still gets right is how long thirty seconds is.
8
+ */
9
+ export type StoreClock = {
10
+ /** The store's now, in epoch ms. */
11
+ now: () => Promise<number>;
12
+ /** Forgets the reading, so the next call takes it again — after a failover to another primary, or in a test. */
13
+ resync: () => void;
14
+ };
15
+ /** `read` answers the store's own time in epoch ms: `hello.localTime` on Mongo, `NOW(3)` on MySQL. */
16
+ export declare const createStoreClock: (read: () => Promise<number>, resyncMs?: number) => StoreClock;
@@ -0,0 +1,6 @@
1
+ import { JobQueue, JobWake } from '../../types';
2
+ /**
3
+ * The queue, telling the workers (`wake.notify`) as a job due now is enqueued or handed back due: a retry with no delay,
4
+ * a worker's shutdown giving its claims back. What a worker hears it looks at once, rather than on its next look.
5
+ */
6
+ export declare const wakingQueue: (queue: JobQueue, wake: JobWake | undefined) => JobQueue;
@@ -0,0 +1,99 @@
1
+ import { MemoryReading } from './memoryWatch';
2
+ import { FunctionJobsService } from '../../functions/jobs';
3
+ import { JobClaimMemory, JobQueue, JobSpaces, JobWake } from '../../types';
4
+ import { ActionsModule } from '../module';
5
+ import { ActionLookups } from '../types';
6
+ import { ProcessLoad } from '@plitzi/sdk-kernel/stats';
7
+ export type JobWorkerOptions = {
8
+ queue: JobQueue;
9
+ lookups: ActionLookups;
10
+ module: ActionsModule;
11
+ /** What runs a job of a space's functions (`function` on the job), slice by slice. Absent, such a job waits. */
12
+ functionJobs?: FunctionJobsService;
13
+ /**
14
+ * How many jobs this replica runs AT ONCE.
15
+ *
16
+ * The number that decides whether five hundred queued jobs take five minutes or an hour, and it is a deployment's
17
+ * to set because only it knows what its jobs do: flows that wait on somebody else's API are cheap to hold many of,
18
+ * flows that render or transform are not. Zero makes this replica a producer only — which is how a deployment
19
+ * dedicates a pod to running jobs and leaves the ones serving pages alone. With `memory`, it is the most: near its
20
+ * memory the replica takes no new job, whatever slots it has, and takes no more at once than its memory has room for.
21
+ * Near all of its CPU it takes none either. A slot is taken again as soon as its job ends.
22
+ *
23
+ * Past its share (`concurrency.perSpace`) a space's jobs take only the slots no other space's work waits for.
24
+ */
25
+ workers?: number;
26
+ /** How often a worker with a free slot looks for work. Default 1s. */
27
+ pollMs?: number;
28
+ /** Told a job is due now (`JobWake.listen`): it looks at once, rather than on its next look. */
29
+ wake?: JobWake;
30
+ /**
31
+ * Which spaces' jobs this replica takes, asked on every claim: a worker kept for some spaces takes theirs alone, the
32
+ * others every space but those. Absent, every space's.
33
+ */
34
+ spaces?: () => JobSpaces | undefined;
35
+ /**
36
+ * What this replica may hold and the most any of the deployment's may, asked on every claim (`JobClaimMemory`): a job
37
+ * a worker died running is then left to one that may hold more, or set aside when none may. Absent, as it always was.
38
+ */
39
+ memory?: () => JobClaimMemory | undefined;
40
+ /**
41
+ * Whose jobs this replica takes besides its own while it has more than one slot free, asked on every claim: a larger
42
+ * worker kept for the heavy jobs helps the others while it is idle, and keeps a slot for what only it may run.
43
+ * Absent, its own alone.
44
+ */
45
+ helps?: () => JobSpaces | undefined;
46
+ /**
47
+ * How often, while it holds jobs, this replica reads how near its memory it is (with `memory`): near it, it marks
48
+ * them (`heartbeat`'s `nearMemoryLimit`), so that should it die, they run next on a larger worker. Default 1s.
49
+ */
50
+ memoryWatchMs?: number;
51
+ /** This process's memory, as the watch reads it. Default `process.memoryUsage.rss()` and V8's heap. */
52
+ readMemory?: () => MemoryReading;
53
+ /** This process's CPU and event loop, as a claim reads them: past `LOAD_LIMITS` it takes nothing. Default `processLoad`. */
54
+ readLoad?: () => ProcessLoad;
55
+ /**
56
+ * How long a claim is held before another worker may take the job over.
57
+ *
58
+ * The failover window, in other words: a replica that is killed has its jobs picked up this long afterwards. It
59
+ * is renewed every third of its length while a job runs, so a long flow keeps its claim and a dead process does
60
+ * not. Shorter is a faster recovery and a higher chance of taking a job away from a worker that was merely
61
+ * stalled; the single-flight key is what makes that safe rather than doubled.
62
+ */
63
+ leaseMs?: number;
64
+ /** First retry delay, doubling per attempt, and the ceiling it doubles up to. */
65
+ backoff?: {
66
+ baseMs?: number;
67
+ maxMs?: number;
68
+ };
69
+ /** Names this replica in the job history, so a bad one is identifiable. Defaults to the process and a random id. */
70
+ workerId?: string;
71
+ /** Every failure, in place of the default report. By default a claim or a heartbeat that fails is a warning, and an
72
+ * error once it has kept failing for a minute (see `createFailureStreak`); anything else is an error at once. */
73
+ onError?: (error: unknown) => void;
74
+ };
75
+ export type JobWorker = {
76
+ /** One pass: claim what fits in the free slots and start it. Exposed for a deployment that drives its own loop. */
77
+ poll: () => Promise<number>;
78
+ /**
79
+ * Renews every claim this worker holds, and aborts the ones an operator asked to cancel.
80
+ *
81
+ * Exposed beside `poll` for the same reason: a deployment driving its own loop owns both halves, and a worker
82
+ * that polls without beating loses its jobs to the next replica halfway through them.
83
+ */
84
+ beat: () => Promise<void>;
85
+ /** Reads how near its memory this replica is, and marks the jobs it holds when near — `start` does it every second. */
86
+ watchMemory: () => Promise<void>;
87
+ start: () => void;
88
+ /**
89
+ * Stops claiming, then waits for every job this worker is running to FINISH — however long past its lease that is.
90
+ *
91
+ * The heartbeat keeps renewing their claims meanwhile, so no other replica takes a job over while this one is still
92
+ * running it, and an operator's cancel still reaches it. Each wait is bounded by the run's own timeout, which is
93
+ * the number an orchestrator's grace period has to cover: a pod killed before that loses the run to a lease that
94
+ * lapses, and another replica runs it again.
95
+ */
96
+ stop: () => Promise<void>;
97
+ inFlight: () => number;
98
+ };
99
+ export declare const createJobWorker: ({ queue, lookups, module, functionJobs, workers, pollMs, wake, spaces, memory, helps, memoryWatchMs, readMemory, readLoad, leaseMs, backoff, workerId, onError: customOnError }: JobWorkerOptions) => JobWorker;
@@ -0,0 +1,96 @@
1
+ import { ActionJobs } from './jobs/jobs';
2
+ import { RunGuards } from './runtime/guards';
3
+ import { ActionRunner } from './runtime/runAction';
4
+ import { ActionsConfig, ActionTaskRegistry, ResolvedActionLimits, SpaceRevision } from './types';
5
+ import { FunctionsSource } from '../functions/build';
6
+ import { ManifestReading } from '../functions/manifest';
7
+ import { RouteHandler, RouteVisit } from '../functions/routes';
8
+ import { FunctionScope } from '../functions/scope';
9
+ import { PreparedFunctions } from '../functions/space';
10
+ import { ActionDocument } from '@plitzi/sdk-shared';
11
+ import { FunctionsDefinition, ActionKvStore } from '@plitzi/sdk-shared/functions';
12
+ export type ActionsModule = ActionRunner & {
13
+ /** The deployment's own tasks: shipped, and its native functions. */
14
+ registry: ActionTaskRegistry;
15
+ /**
16
+ * What a space's actions can use as of that revision: the deployment's tasks and the space's own functions — what
17
+ * its catalog offers, what a check checks against and what its runs run.
18
+ */
19
+ registryFor: (spaceId: number, at?: SpaceRevision) => Promise<ActionTaskRegistry>;
20
+ /**
21
+ * Whether this action runs the space's own code and no runner for it answers now: a call to it waits in the queue
22
+ * rather than start and fail half-way, its earlier steps done and its later ones not.
23
+ */
24
+ codeAway: (spaceId: number, document: ActionDocument, at?: SpaceRevision) => Promise<boolean>;
25
+ /**
26
+ * How many of this process's invocations no functions runner has taken yet (`FunctionRunner.waitingForRoom`): what a
27
+ * job worker holds back by.
28
+ */
29
+ runnerWaiting: () => number;
30
+ /** Whether an action runs the space's own code: a task step this server's registry does not hold. */
31
+ runsCode: (document: ActionDocument) => boolean;
32
+ /**
33
+ * A space's functions source, built, read and checked — ready to store, or the problems to show where they are. The
34
+ * one way a space's functions become storable; refused when this server has no runner. With a `scope`, a plugin's
35
+ * server half: its tasks named after the plugin, its routes its own.
36
+ */
37
+ prepareFunctions: (source: FunctionsSource, scope?: FunctionScope) => Promise<PreparedFunctions>;
38
+ /**
39
+ * What a space's code declares, read by every rule a saved space's functions meet — for code that is not built here:
40
+ * a space runtime's, described by the runtime itself when it starts. The manifest, and the problems that refuse it.
41
+ */
42
+ readManifest: (declared: unknown) => ManifestReading;
43
+ /**
44
+ * The function that answers `method path` under `/api/` for this visit — the deployment's own routes, then the space's
45
+ * — or none, and the page server answers as it would have.
46
+ */
47
+ routeFor: (visit: RouteVisit, method: string, path: string) => Promise<RouteHandler | undefined>;
48
+ guards: RunGuards;
49
+ /** The key/value store, namespaced to one space — the same one the `kv` tasks write through, so a rate limit the
50
+ * transport keeps and a counter a flow keeps cannot end up in different places. */
51
+ kv: (spaceId: number) => ActionKvStore;
52
+ /**
53
+ * What this server will allow one run of that space's document to spend — the deployment's ceilings, tightened by the
54
+ * space's plan (`ActionsConfig.limitsFor`) and by the document.
55
+ */
56
+ limitsFor: (spaceId: number, document: ActionDocument) => Promise<ResolvedActionLimits>;
57
+ /**
58
+ * Puts the server half of a plugin this server ships in place — or takes it away, with none — while it runs: what a
59
+ * development server does when a plugin's `functions/` change, instead of restarting. Checked as at boot: a task not
60
+ * named after the plugin throws, and nothing changes.
61
+ */
62
+ setPluginFunctions: (plugin: string, definition: FunctionsDefinition | undefined) => void;
63
+ /**
64
+ * Scheduled runs: the queue, the sweep that fills it and the workers that drain it.
65
+ *
66
+ * Built but NOT started — whoever owns the process decides when background work begins, and a server nobody
67
+ * listened on must not be quietly claiming jobs. Absent when the deployment cannot list a space's actions, since
68
+ * there is then no way to know what is scheduled.
69
+ */
70
+ jobs?: ActionJobs;
71
+ };
72
+ export declare const createActionsModule: (given: ActionsConfig) => ActionsModule;
73
+ export { ActionRunError } from './runtime/errors';
74
+ export { ActionRefusal } from '@plitzi/sdk-shared/functions';
75
+ export { precheckRun } from './runtime/precheck';
76
+ export { spaceKvPatterns } from './runtime/namespaceKv';
77
+ export { checkAction } from './runtime/check';
78
+ export { DEFAULT_LIMITS, resolveLimits } from './runtime/limits';
79
+ export { createRunGuards, deriveRunKey } from './runtime/guards';
80
+ export { createActionJobs, createJobWorker, createMemoryJobQueue, createScheduler } from './jobs/jobs';
81
+ export { createMemoryKv } from './runtime/memoryKv';
82
+ export { createRunLogger, createRejectLogger } from './runtime/runLogger';
83
+ export { createTaskRegistry } from './tasks/registry';
84
+ export { taskName } from './tasks/names';
85
+ export { describeCatalog, describeTask } from './taskCatalog';
86
+ export { handleActionCall } from './transport/callHandler';
87
+ export { handleActionCatalog } from './transport/catalogHandler';
88
+ export { handleActionWebhook } from './transport/webhookHandler';
89
+ export { verifySignature } from './transport/verifySignature';
90
+ export { handleActionCancel } from './transport/cancelHandler';
91
+ export type { ActionJobs, JobWorker, JobWorkerOptions, Scheduler, SchedulerOptions, SweepResult } from './jobs/jobs';
92
+ export type { ActiveRun, RunGuards } from './runtime/guards';
93
+ export type { ActionTaskDescriptor } from './taskCatalog';
94
+ export type { TaskRegistryOptions } from './tasks/registry';
95
+ export type { ActionCredential, ActionDbDriver, ActionEmailConfig, ActionEmailDelivery, ActionEmailMessage, ActionEmailTransport, ActionJobsConfig, ActionLookups, ActionRejectRecord, ActionRunRecord, ActionRunRequest, ActionRunResult, ActionsConfig, ActionTask, ActionTaskContext, ActionTaskOrigin, ActionTaskRegistry, RegisteredTask, ResolvedConnector } from './types';
96
+ export type { ActionKvStore } from '@plitzi/sdk-shared/functions';
@@ -0,0 +1,3 @@
1
+ import { ActionsModule } from './module';
2
+ import { EngineConfig } from '../types';
3
+ export declare const actionsModuleFor: (config: EngineConfig) => ActionsModule | undefined;
@@ -0,0 +1,24 @@
1
+ import { ActionDbDriver, ActionLookups, ActionTaskRegistry } from '../types';
2
+ import { ActionCheckReport, ActionEntry } from '@plitzi/sdk-shared';
3
+ export type ActionCheckDeps = {
4
+ spaceId: number;
5
+ registry: ActionTaskRegistry;
6
+ lookups: ActionLookups;
7
+ dbDrivers?: ActionDbDriver[];
8
+ };
9
+ /**
10
+ * What only THIS deployment can answer about an action.
11
+ *
12
+ * `validateActionDocument` reads the document and nothing else, so it catches a flow that contradicts itself — a
13
+ * step with no task, an output that names a step that does not exist. It cannot catch the other half, which is
14
+ * every way a correct document meets a server that cannot run it: a task this deployment never registered, a
15
+ * credential the space does not have, a key that is not in the credential it does have, a connector that was
16
+ * deleted, a database engine with no driver, a cron that will never fire.
17
+ *
18
+ * Those are the failures that surface at 3am on the first real delivery, and an author has no way to see them
19
+ * from the editor — which is why this runs on the server and answers in the same shape the validator does.
20
+ *
21
+ * It reads credentials to ask WHETHER they exist and whether they carry the key a step names. It never reports a
22
+ * value, and nothing here runs a step.
23
+ */
24
+ export declare const checkAction: (entry: ActionEntry, deps: ActionCheckDeps) => Promise<ActionCheckReport>;
@@ -0,0 +1,8 @@
1
+ import { ActionCredential } from '../types';
2
+ /**
3
+ * The credentials a deployment with no credential store keeps in its environment: one JSON object, credential id → its
4
+ * keys, each a string — what `ctx.fetch({ credential })`, a connector and an `http.request` step name. Read whole or
5
+ * refused with why: a value that does not read would otherwise leave every credential missing, and the integration
6
+ * failing far from the cause.
7
+ */
8
+ export declare const credentialsFromEnv: (env?: NodeJS.ProcessEnv) => Record<string, ActionCredential>;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The run's deadline, as a promise that loses patience.
3
+ *
4
+ * Aborting the controller is the polite half: a task that watches its signal stops, and the loop refuses to start
5
+ * the next step. It is not enough on its own, because a step that ignores the signal — a driver that does not
6
+ * take one, a provider client that swallows it, a `while (true)` inside a task — leaves the run awaiting something
7
+ * that never returns. That is the stuck run this exists to end: nothing else in the process can tell the
8
+ * difference between a flow that is working hard and one that will never finish.
9
+ *
10
+ * Racing the flow against this means the RUN always ends, even when a step does not. What the step does after
11
+ * that is beyond anybody's reach in a single-threaded runtime — but it no longer holds a caller, a slot, or a
12
+ * connection while it does it.
13
+ */
14
+ export declare const createDeadline: (timeoutMs: number, controller: AbortController) => {
15
+ promise: Promise<never>;
16
+ clear: () => void;
17
+ /** A wait for a runner — its queue, a turn at its CPU — is the platform's time, not the run's: the limit moves. */
18
+ extend: (ms: number) => void;
19
+ };
@@ -0,0 +1,38 @@
1
+ import { HostLookup } from '@plitzi/sdk-kernel/outbound';
2
+ import { ActionEmailConfig, ActionEmailMessage } from '@plitzi/sdk-shared';
3
+ import { SmtpSettings } from '@plitzi/sdk-shared/actions';
4
+ import { ActionKvStore } from '@plitzi/sdk-shared/functions';
5
+ /** Hands one message to the SMTP server of a space, at an address this module already resolved and judged. */
6
+ export type SmtpDelivery = (delivery: {
7
+ /** The IP to connect to. The host name travels separately, as what the TLS certificate must be for. */
8
+ address: string;
9
+ smtp: SmtpSettings;
10
+ message: ActionEmailMessage;
11
+ signal: AbortSignal;
12
+ }) => Promise<void>;
13
+ /** What the `email.send` task sends through: the policy around a space's own SMTP server, and the connection. */
14
+ export type ActionEmailSender = {
15
+ send: (spaceId: number, smtp: SmtpSettings, message: ActionEmailMessage, signal: AbortSignal) => Promise<void>;
16
+ };
17
+ export type EmailSenderOptions = ActionEmailConfig & {
18
+ /** The server's own store, NOT a space's: a flow must not be able to reach the counter that limits it. */
19
+ kv: ActionKvStore;
20
+ lookup?: HostLookup;
21
+ deliver?: SmtpDelivery;
22
+ now?: () => Date;
23
+ };
24
+ /**
25
+ * Sends a flow's message under the deployment's rules, in this order:
26
+ *
27
+ * 1. **Where it goes is settled.** A deployment's own `transport` owns its connection and receives the message as it
28
+ * is. Without one, the message goes to the SMTP server the space's credential names, and the host is resolved and
29
+ * every address judged first: a credential is typed by a customer and the connection starts inside the
30
+ * deployment's network, so `localhost` or an address that resolves to `10.0.0.5` is refused unless the deployment
31
+ * allowed it. The connection then goes to the address that was judged, so a name that answers differently a second
32
+ * later cannot be how it gets in.
33
+ * 2. **The message is counted against the space's day.** Before it leaves, and never given back: a failing server
34
+ * still spends the allowance, or retrying against an outage would be how the limit is walked past. A host refused
35
+ * in step 1 spends nothing, because nothing was attempted.
36
+ * 3. **The message is delivered.**
37
+ */
38
+ export declare const createEmailSender: ({ kv, dailyLimitPerSpace, allowPrivateHosts, transport, lookup, deliver, now }: EmailSenderOptions) => ActionEmailSender;
@@ -0,0 +1,28 @@
1
+ import { ActionErrorReason, ActionRunLimit, ActionRunStep } from '@plitzi/sdk-shared';
2
+ /**
3
+ * A run that stopped for a reason the caller is entitled to know, as opposed to one whose step threw.
4
+ *
5
+ * Its own file so the precheck and the runner can both raise it without either importing the other — the
6
+ * precheck is called BY the runner and BEFORE it, and a shared error type is the only thing they have in common.
7
+ */
8
+ export declare class ActionRunError extends Error {
9
+ reason: ActionErrorReason;
10
+ /**
11
+ * The steps a run that STARTED took before it hit this — its deadline, a budget — set by the runner as it rethrows.
12
+ * A refusal before the run began has none. The same outline a completed run returns, and nothing more.
13
+ */
14
+ steps?: ActionRunStep[];
15
+ /** The limit it is, when it is one (its deadline, its step budget…): a ceiling reached, never a fault. */
16
+ limit?: ActionRunLimit;
17
+ constructor(reason: ActionErrorReason, message: string, limit?: ActionRunLimit);
18
+ }
19
+ /**
20
+ * A step stopped at a limit of what its run may spend — its account's CPU budget — failing that step as any error
21
+ * does, while saying it was a limit and not a fault.
22
+ */
23
+ export declare class RunLimitReached extends Error {
24
+ limit: ActionRunLimit;
25
+ constructor(limit: ActionRunLimit, message: string);
26
+ }
27
+ /** The limit an error that ended a run says it is: a ceiling of the run's, one of its step's, or its code's runner's. */
28
+ export declare const limitOf: (error: unknown) => ActionRunLimit | undefined;
@@ -0,0 +1,35 @@
1
+ import { ActionKvAdapter } from '../types';
2
+ export type FileKvOptions = {
3
+ /** The JSON file the store lives in — created, with its folder, on the first write. */
4
+ file: string;
5
+ /** Who holds it, said to a second process that tries: `this project's server, on port 8080`. */
6
+ owner?: string;
7
+ /** Where the process that holds it answers, for a second one to be pointed there: `http://localhost:8080`. */
8
+ serves?: string;
9
+ };
10
+ export type FileKv = ActionKvAdapter & {
11
+ /** Resolves once everything written so far is on disk: for a shutdown, or a test that reads the file. */
12
+ flush: () => Promise<void>;
13
+ /** Writes what is pending and lets go of the file, for the next process to take. */
14
+ close: () => Promise<void>;
15
+ };
16
+ /**
17
+ * A key/value store in one JSON file: the `kv` server actions keep — saved layouts, counters, a source's cached answer —
18
+ * surviving a restart, for a deployment with no database. Nothing to install, and a file anybody can read, back up or
19
+ * edit by hand while the server is stopped.
20
+ *
21
+ * ```ts
22
+ * createServer({ action: { kv: createFileKv({ file: 'state/kv.json' }) } });
23
+ * ```
24
+ *
25
+ * The rules are the in-process store's, to the letter (`createMapKv`): the file is only where the map is kept. Every
26
+ * change is written whole, through a temporary file renamed over the old one, as soon as the change is made — changes
27
+ * that arrive while a write is under way are written together right after it, so a crash loses at most the writes
28
+ * of that instant and never leaves half a file. Entries past their lifetime are not written.
29
+ *
30
+ * ONE process: it reads the file when it starts and holds it after (`<file>.lock`, with its pid) — a second process is
31
+ * refused, naming the first, because two would write over each other's changes. The workers of one server reach the
32
+ * primary's through the fleet (`fleetKv`); replicas use `createSqliteKv` (`@plitzi/sdk-actions/sqlite`) or a database.
33
+ * And a whole file per change: right for what a site keeps, not for a counter bumped thousands of times a second.
34
+ */
35
+ export declare const createFileKv: ({ file, owner, serves }: FileKvOptions) => FileKv;
@@ -0,0 +1,16 @@
1
+ import { ActionRunRequest, ActionsConfig } from '../types';
2
+ /**
3
+ * Whether a flow names `flags` anywhere — a template, a `when` rule's field. Only those are worth a lookup: most flows
4
+ * read no flag, and asking for the space's flags on every run of every one of them would be a read per click.
5
+ *
6
+ * Over the serialized document, so a template in any step's params counts without knowing every step's shape. A word
7
+ * `flags` that is not the source costs one lookup that was not needed, never a flow without its flags. Kept per
8
+ * document, which the lookups hand out once per version.
9
+ */
10
+ export declare const readsFlags: (document: object) => boolean;
11
+ /**
12
+ * The space's flags as this run sees them: what the space declares at the run's revision, matched against the run's
13
+ * environment and visitor, then the server's own layer and a tester's forced one — the same order a page resolves
14
+ * them in. A run has no URL, so a rule on the host or the route does not match here.
15
+ */
16
+ export declare const flagsForRun: (config: Pick<ActionsConfig, "lookups" | "flags">, request: Pick<ActionRunRequest, "entry" | "spaceId" | "environment" | "at" | "user" | "forcedFlags">) => Promise<Record<string, boolean>>;