@kelpie/server 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/boot.d.ts +9 -0
  2. package/dist/boot.d.ts.map +1 -1
  3. package/dist/boot.js +11 -2
  4. package/dist/boot.js.map +1 -1
  5. package/dist/index.d.ts +6 -1
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +3 -0
  8. package/dist/index.js.map +1 -1
  9. package/dist/lib/jobs.d.ts +110 -0
  10. package/dist/lib/jobs.d.ts.map +1 -0
  11. package/dist/lib/jobs.js +5 -0
  12. package/dist/lib/jobs.js.map +1 -0
  13. package/dist/runtime/jobs.d.ts +63 -0
  14. package/dist/runtime/jobs.d.ts.map +1 -0
  15. package/dist/runtime/jobs.js +231 -0
  16. package/dist/runtime/jobs.js.map +1 -0
  17. package/dist/runtime/module.d.ts +12 -0
  18. package/dist/runtime/module.d.ts.map +1 -1
  19. package/dist/runtime/registry.d.ts +8 -0
  20. package/dist/runtime/registry.d.ts.map +1 -1
  21. package/dist/runtime/registry.js +15 -0
  22. package/dist/runtime/registry.js.map +1 -1
  23. package/dist/runtime/transaction.d.ts +19 -0
  24. package/dist/runtime/transaction.d.ts.map +1 -1
  25. package/dist/runtime/transaction.js +7 -0
  26. package/dist/runtime/transaction.js.map +1 -1
  27. package/dist/testing/app.d.ts +7 -0
  28. package/dist/testing/app.d.ts.map +1 -1
  29. package/dist/testing/app.js +1 -0
  30. package/dist/testing/app.js.map +1 -1
  31. package/dist/testing/database.d.ts +7 -0
  32. package/dist/testing/database.d.ts.map +1 -1
  33. package/dist/testing/database.js +26 -2
  34. package/dist/testing/database.js.map +1 -1
  35. package/dist/testing/services.d.ts +7 -0
  36. package/dist/testing/services.d.ts.map +1 -1
  37. package/dist/testing/services.js +8 -1
  38. package/dist/testing/services.js.map +1 -1
  39. package/dist/worker.d.ts +15 -0
  40. package/dist/worker.d.ts.map +1 -0
  41. package/dist/worker.js +19 -0
  42. package/dist/worker.js.map +1 -0
  43. package/package.json +3 -2
  44. package/src/boot.ts +20 -2
  45. package/src/index.ts +17 -0
  46. package/src/lib/jobs.ts +126 -0
  47. package/src/runtime/jobs.ts +358 -0
  48. package/src/runtime/module.ts +12 -0
  49. package/src/runtime/registry.ts +24 -0
  50. package/src/runtime/transaction.ts +43 -0
  51. package/src/testing/app.ts +8 -0
  52. package/src/testing/database.ts +35 -2
  53. package/src/testing/services.ts +15 -1
  54. package/src/worker.ts +20 -0
package/src/index.ts CHANGED
@@ -9,6 +9,22 @@ export type { AppDependencies, AppBindings } from './app.ts'
9
9
  export { bootAssembly } from './boot.ts'
10
10
  export type { AssemblyBoot } from './boot.ts'
11
11
 
12
+ export { startWorker } from './worker.ts'
13
+
14
+ export { createJobsRuntime } from './runtime/jobs.ts'
15
+ export type { JobsRuntime, JobsRuntimeOptions } from './runtime/jobs.ts'
16
+ export { deadLetterQueueName } from './lib/jobs.ts'
17
+ export type {
18
+ EnqueueOptions,
19
+ JobContext,
20
+ JobDefaults,
21
+ JobDefinition,
22
+ JobHandle,
23
+ JobHandler,
24
+ JobRegistry,
25
+ TransactionJobs,
26
+ } from './lib/jobs.ts'
27
+
12
28
  export { WebBundleError, serveWebBundle } from './webBundle.ts'
13
29
  export type { WebBundleOptions } from './webBundle.ts'
14
30
 
@@ -143,6 +159,7 @@ export type { ModuleEventCatalog } from './runtime/module.ts'
143
159
  export { createTransactionScope } from './runtime/transaction.ts'
144
160
  export type {
145
161
  BufferedEvents,
162
+ EnqueueOnTransaction,
146
163
  Transaction,
147
164
  TransactionContext,
148
165
  TransactionOptions,
@@ -0,0 +1,126 @@
1
+ import type { ZodType } from 'zod'
2
+
3
+ import type { Logger } from './logger.ts'
4
+
5
+ /**
6
+ * The port core runs background work through.
7
+ *
8
+ * A module declares a handle at register time with `context.jobs.define(...)`
9
+ * and enqueues against it from a service. The insert lives inside the same
10
+ * Drizzle transaction as the write it belongs to, so a rolled-back write
11
+ * never leaves an orphan job behind. Handlers run out of process — on the
12
+ * worker entry point, or inline when the API runs its own worker — and see
13
+ * the same payload the caller passed, validated against the module's Zod
14
+ * schema before it reaches user code.
15
+ *
16
+ * The port itself knows nothing about pg-boss. `runtime/jobs.ts` binds it to
17
+ * a real provider at boot; tests bind it to a stub. Nothing outside the
18
+ * runtime imports the provider directly.
19
+ *
20
+ * Why a handle rather than a global name map: consumers of `@kelpie/server`
21
+ * installed from npm lost the `KelpieEventMap` augmentation until every
22
+ * catalog was pulled in from the entry point (see
23
+ * `modules/eventCatalogs.ts`). A handle keeps the payload type on the value
24
+ * the module exports, so `enqueue(handle, data)` typechecks without
25
+ * declaration merging across the package boundary.
26
+ */
27
+
28
+ /**
29
+ * Marker property carrying the handle's payload type. Never assigned at
30
+ * runtime; the `?` on the property makes an untagged plain object satisfy the
31
+ * shape at read time, so a stub handle in a test can be built without
32
+ * `unsafeCast`.
33
+ */
34
+ declare const JobHandleDataMarker: unique symbol
35
+
36
+ /** A typed reference a module exports after `define()`. */
37
+ export interface JobHandle<Data> {
38
+ readonly name: string
39
+ readonly [JobHandleDataMarker]?: Data
40
+ }
41
+
42
+ /**
43
+ * Defaults every enqueue on this queue inherits, unless the caller overrides
44
+ * on a per-`enqueue` basis. `localConcurrency` sizes the work loop on the
45
+ * worker; the rest match pg-boss's `QueueOptions` names.
46
+ *
47
+ * `retryDelay` is in seconds. pg-boss's default is 0 (immediate retry).
48
+ * `retryLimit` counts the retries pg-boss does after the first run; a job
49
+ * with `retryLimit: 2` runs at most three times.
50
+ */
51
+ export interface JobDefaults {
52
+ readonly retryLimit?: number
53
+ readonly retryDelay?: number
54
+ readonly retryBackoff?: boolean
55
+ readonly retryDelayMax?: number
56
+ readonly expireInSeconds?: number
57
+ readonly localConcurrency?: number
58
+ }
59
+
60
+ /** Passed to a job handler when a worker picks the job up. */
61
+ export interface JobContext<Data> {
62
+ readonly id: string
63
+ readonly data: Data
64
+ readonly log: Logger
65
+ /** Fires when pg-boss decides the job has expired. Long-running handlers should honour it. */
66
+ readonly signal: AbortSignal
67
+ }
68
+
69
+ export type JobHandler<Data> = (context: JobContext<Data>) => Promise<void>
70
+
71
+ export interface JobDefinition<Data> {
72
+ /**
73
+ * The queue name pg-boss stores against. Must be unique across the
74
+ * assembly; a second `define()` with the same name fails boot.
75
+ *
76
+ * Prefix with the module id — `webhooks.deliver`, `agent-tasks.dispatch` —
77
+ * so operators reading `pgboss.job` see who owns it.
78
+ */
79
+ readonly name: string
80
+ /**
81
+ * Parses the payload at handle time before it reaches user code. A job
82
+ * whose payload no longer matches fails, retries, and eventually
83
+ * dead-letters like any other failure.
84
+ */
85
+ readonly schema: ZodType<Data>
86
+ readonly handler: JobHandler<Data>
87
+ readonly defaults?: JobDefaults
88
+ }
89
+
90
+ /**
91
+ * The registration surface exposed to a module through `context.jobs`. Modules
92
+ * hand a definition in and receive a typed handle to enqueue against.
93
+ */
94
+ export interface JobRegistry {
95
+ define<Data>(definition: JobDefinition<Data>): JobHandle<Data>
96
+ }
97
+
98
+ /**
99
+ * Options a caller may override per `enqueue`. Deliberately narrow: features
100
+ * beyond retries, a singleton key, and a deferred start are out of scope until
101
+ * a consumer needs them (`crm-brief.md` cost/maintainability trade-offs).
102
+ */
103
+ export interface EnqueueOptions {
104
+ readonly retryLimit?: number
105
+ readonly retryBackoff?: boolean
106
+ readonly singletonKey?: string
107
+ readonly startAfter?: number | string | Date
108
+ }
109
+
110
+ /**
111
+ * Exposed on the transaction context next to `events`. `enqueue` runs its
112
+ * insert inside the caller's transaction via pg-boss's `fromDrizzle` adapter,
113
+ * so a rollback discards the job with the write.
114
+ */
115
+ export interface TransactionJobs {
116
+ enqueue<Data>(
117
+ handle: JobHandle<Data>,
118
+ data: Data,
119
+ options?: EnqueueOptions,
120
+ ): Promise<string | null>
121
+ }
122
+
123
+ /** The name pg-boss stores the dead-letter queue under, given a handle name. */
124
+ export function deadLetterQueueName(jobName: string): string {
125
+ return `${jobName}.dead`
126
+ }
@@ -0,0 +1,358 @@
1
+ import { sql } from 'drizzle-orm'
2
+ import { PgBoss, fromDrizzle } from 'pg-boss'
3
+ import type { Job } from 'pg-boss'
4
+
5
+ import { describeThrown } from '../lib/errors.ts'
6
+ import type { Logger } from '../lib/logger.ts'
7
+ import type {
8
+ EnqueueOptions,
9
+ JobContext,
10
+ JobDefinition,
11
+ JobHandle,
12
+ JobRegistry,
13
+ } from '../lib/jobs.ts'
14
+ import { deadLetterQueueName } from '../lib/jobs.ts'
15
+ import type { Transaction } from './transaction.ts'
16
+
17
+ /**
18
+ * The pg-boss provider that binds the job port defined in `lib/jobs.ts` to a
19
+ * real Postgres-backed queue.
20
+ *
21
+ * Two phases:
22
+ *
23
+ * 1. Registration, at boot. Modules call `context.jobs.define(...)` during
24
+ * `register`. The registry records the definition (fails boot on a
25
+ * duplicate name) and returns the handle. Nothing touches the database
26
+ * yet.
27
+ * 2. `start()`, from the entry point. Opens the pg-boss instance, primes the
28
+ * queue cache, and calls `createQueue` for every registered handle plus
29
+ * its dead-letter queue. Idempotent (`create_queue` upserts).
30
+ *
31
+ * The API and the worker both call `start()`: the API needs a boss instance
32
+ * to insert jobs on request-scoped transactions; the worker adds a
33
+ * `startWorking()` step that runs `work()` per handle.
34
+ *
35
+ * @see modules.md for how jobs sit next to the event bus.
36
+ */
37
+
38
+ /**
39
+ * The pg-boss schema name. Fixed here rather than configurable per assembly:
40
+ * self-hosters run one Postgres per Kelpie install and would gain nothing
41
+ * from renaming the schema.
42
+ */
43
+ const PGBOSS_SCHEMA = 'pgboss'
44
+
45
+ const DEFAULT_LOCAL_CONCURRENCY = 5
46
+
47
+ interface RegisteredJob<Data> {
48
+ readonly definition: JobDefinition<Data>
49
+ readonly handle: JobHandle<Data>
50
+ }
51
+
52
+ export interface JobsRuntimeOptions {
53
+ readonly connectionString: string
54
+ readonly logger: Logger
55
+ /**
56
+ * Polling floor. LISTEN/NOTIFY wakes a worker immediately when a job is
57
+ * inserted via `send()`, but pg-boss's own retry re-insert (inside
58
+ * `fail()`) never notifies, so a retried job is only ever picked up by
59
+ * this poll — as is a fresh job if the listener never opened. Also used
60
+ * as pg-boss's `notifyPollingIntervalSeconds`, so NOTIFY-active queues
61
+ * poll no slower than this either. Default 2s in production; tests pass
62
+ * a shorter value so a retry runs within the test's own budget.
63
+ */
64
+ readonly pollingIntervalSeconds?: number
65
+ /**
66
+ * How many workers the runtime spins up per handle when a definition does
67
+ * not override `defaults.localConcurrency`. Matches pg-boss's default.
68
+ */
69
+ readonly defaultLocalConcurrency?: number
70
+ }
71
+
72
+ export interface JobsRuntime {
73
+ /** The port modules bind to at register time. */
74
+ readonly registry: JobRegistry
75
+ /** True once `register` has been called with this name. Used by tests. */
76
+ hasHandle(name: string): boolean
77
+ /**
78
+ * Applies pg-boss's own schema migration. Idempotent: safe to run on every
79
+ * boot. Uses a throwaway `PgBoss` in `migrate: true, createSchema: true`
80
+ * mode, matching the release-command flow the cloud runs.
81
+ */
82
+ migrate(): Promise<void>
83
+ /**
84
+ * Opens the persistent pg-boss instance and declares every registered
85
+ * queue plus its dead-letter counterpart. Must run before `enqueueOnTx`
86
+ * or `startWorking`. `migrate: false` here: `migrate()` above owns that
87
+ * step, so instances never race the migration.
88
+ */
89
+ start(): Promise<void>
90
+ /**
91
+ * Starts the `work()` loop for every registered handle. The worker entry
92
+ * point calls this; the API calls it too unless `--no-worker` is set.
93
+ * Handler errors are logged and rethrown so pg-boss retries or
94
+ * dead-letters the job.
95
+ */
96
+ startWorking(): Promise<void>
97
+ /**
98
+ * Enqueues a job on the caller's transaction via `fromDrizzle(tx, sql)`.
99
+ * The insert commits with the surrounding write; a rollback discards it.
100
+ * Rejects when no `handle` was registered for `name` (this would be a
101
+ * boot-time bug, not a runtime one).
102
+ */
103
+ enqueueOnTx<Data>(
104
+ tx: Transaction,
105
+ handle: JobHandle<Data>,
106
+ data: Data,
107
+ options?: EnqueueOptions,
108
+ ): Promise<string | null>
109
+ /**
110
+ * Drains in-flight work and closes the pg-boss instance. `offWork({wait:
111
+ * true})` awaits every handler mid-flight; `boss.stop` then tears down
112
+ * the connection pool.
113
+ */
114
+ stop(): Promise<void>
115
+ }
116
+
117
+ export function createJobsRuntime(options: JobsRuntimeOptions): JobsRuntime {
118
+ const registered = new Map<string, RegisteredJob<unknown>>()
119
+ // Tracks which handles have had `createQueue` run and which have had
120
+ // `work()` called, so a runtime that registers a fresh handle after
121
+ // `start()` (a test that adds one mid-suite) still gets its queue built
122
+ // and its worker started without redoing the ones already up.
123
+ const queuesCreated = new Set<string>()
124
+ const workersStarted = new Set<string>()
125
+ let boss: PgBoss | undefined
126
+
127
+ function requireBoss(): PgBoss {
128
+ if (boss === undefined) {
129
+ throw new Error('jobs runtime used before start(): call jobs.start() at boot')
130
+ }
131
+ return boss
132
+ }
133
+
134
+ const registry: JobRegistry = {
135
+ define<Data>(definition: JobDefinition<Data>): JobHandle<Data> {
136
+ if (registered.has(definition.name)) {
137
+ throw new Error(`job "${definition.name}" is defined twice`)
138
+ }
139
+
140
+ const handle: JobHandle<Data> = { name: definition.name }
141
+ registered.set(definition.name, {
142
+ definition: definition as JobDefinition<unknown>,
143
+ handle: handle as JobHandle<unknown>,
144
+ })
145
+
146
+ return handle
147
+ },
148
+ }
149
+
150
+ async function migrate(): Promise<void> {
151
+ // A throwaway instance in migrate/createSchema mode. Cheaper than
152
+ // vendoring the SQL: pg-boss owns its schema, and `getConstructionPlans`
153
+ // / `getMigrationPlans` produce statements we would just execute in the
154
+ // same order the library does itself. `supervise: false, schedule: false`
155
+ // keeps the instance from spawning any background work while it lives.
156
+ const migrator = new PgBoss({
157
+ connectionString: options.connectionString,
158
+ schema: PGBOSS_SCHEMA,
159
+ migrate: true,
160
+ createSchema: true,
161
+ supervise: false,
162
+ schedule: false,
163
+ })
164
+
165
+ try {
166
+ await migrator.start()
167
+ } finally {
168
+ await migrator.stop({ graceful: false, close: true, timeout: 5_000 })
169
+ }
170
+ }
171
+
172
+ async function ensureQueuesFor(instance: PgBoss): Promise<void> {
173
+ for (const { definition } of registered.values()) {
174
+ if (queuesCreated.has(definition.name)) {
175
+ continue
176
+ }
177
+
178
+ const deadLetter = deadLetterQueueName(definition.name)
179
+
180
+ // Dead letter queue must exist before the main queue references it.
181
+ await instance.createQueue(deadLetter, {
182
+ policy: 'standard',
183
+ notify: false,
184
+ })
185
+
186
+ await instance.createQueue(definition.name, {
187
+ policy: 'standard',
188
+ deadLetter,
189
+ notify: true,
190
+ ...(definition.defaults?.retryLimit === undefined
191
+ ? {}
192
+ : { retryLimit: definition.defaults.retryLimit }),
193
+ ...(definition.defaults?.retryDelay === undefined
194
+ ? {}
195
+ : { retryDelay: definition.defaults.retryDelay }),
196
+ ...(definition.defaults?.retryBackoff === undefined
197
+ ? {}
198
+ : { retryBackoff: definition.defaults.retryBackoff }),
199
+ ...(definition.defaults?.retryDelayMax === undefined
200
+ ? {}
201
+ : { retryDelayMax: definition.defaults.retryDelayMax }),
202
+ ...(definition.defaults?.expireInSeconds === undefined
203
+ ? {}
204
+ : { expireInSeconds: definition.defaults.expireInSeconds }),
205
+ })
206
+
207
+ queuesCreated.add(definition.name)
208
+ }
209
+ }
210
+
211
+ async function start(): Promise<void> {
212
+ if (boss === undefined) {
213
+ const instance = new PgBoss({
214
+ connectionString: options.connectionString,
215
+ schema: PGBOSS_SCHEMA,
216
+ migrate: false,
217
+ createSchema: false,
218
+ supervise: false,
219
+ schedule: false,
220
+ useListenNotify: true,
221
+ })
222
+
223
+ instance.on('error', (error: unknown) => {
224
+ options.logger.error('pg-boss error', { error: describeThrown(error) })
225
+ })
226
+
227
+ await instance.start()
228
+ boss = instance
229
+ }
230
+
231
+ await ensureQueuesFor(boss)
232
+ }
233
+
234
+ async function startWorking(): Promise<void> {
235
+ const instance = requireBoss()
236
+ const pollingIntervalSeconds = options.pollingIntervalSeconds ?? 2
237
+ const defaultLocalConcurrency = options.defaultLocalConcurrency ?? DEFAULT_LOCAL_CONCURRENCY
238
+
239
+ for (const { definition } of registered.values()) {
240
+ if (workersStarted.has(definition.name)) {
241
+ continue
242
+ }
243
+
244
+ const localConcurrency = definition.defaults?.localConcurrency ?? defaultLocalConcurrency
245
+
246
+ await instance.work(
247
+ definition.name,
248
+ {
249
+ batchSize: 1,
250
+ localConcurrency,
251
+ pollingIntervalSeconds,
252
+ notifyPollingIntervalSeconds: pollingIntervalSeconds,
253
+ },
254
+ async (batch: Job<unknown>[]) => {
255
+ const job = batch[0]
256
+ if (job === undefined) {
257
+ return
258
+ }
259
+
260
+ const parsed = definition.schema.safeParse(job.data)
261
+
262
+ if (!parsed.success) {
263
+ options.logger.error('job payload rejected by schema', {
264
+ job: definition.name,
265
+ id: job.id,
266
+ issues: parsed.error.issues,
267
+ })
268
+ throw new Error(
269
+ `job "${definition.name}" payload does not match its schema: ${parsed.error.issues
270
+ .map((issue) => issue.message)
271
+ .join('; ')}`,
272
+ )
273
+ }
274
+
275
+ const jobLogger = options.logger.child({ job: definition.name, jobId: job.id })
276
+ const context: JobContext<unknown> = {
277
+ id: job.id,
278
+ data: parsed.data,
279
+ log: jobLogger,
280
+ signal: job.signal,
281
+ }
282
+
283
+ try {
284
+ await definition.handler(context)
285
+ } catch (error: unknown) {
286
+ jobLogger.error('job handler failed', { error: describeThrown(error) })
287
+ throw error
288
+ }
289
+ },
290
+ )
291
+
292
+ workersStarted.add(definition.name)
293
+ }
294
+ }
295
+
296
+ async function enqueueOnTx<Data>(
297
+ tx: Transaction,
298
+ handle: JobHandle<Data>,
299
+ data: Data,
300
+ enqueueOptions: EnqueueOptions = {},
301
+ ): Promise<string | null> {
302
+ const instance = requireBoss()
303
+ const entry = registered.get(handle.name)
304
+
305
+ if (entry === undefined) {
306
+ throw new Error(`enqueue for unregistered job "${handle.name}"`)
307
+ }
308
+
309
+ return instance.send(
310
+ handle.name,
311
+ data as object,
312
+ {
313
+ db: fromDrizzle(tx, sql),
314
+ ...(enqueueOptions.retryLimit === undefined ? {} : { retryLimit: enqueueOptions.retryLimit }),
315
+ ...(enqueueOptions.retryBackoff === undefined
316
+ ? {}
317
+ : { retryBackoff: enqueueOptions.retryBackoff }),
318
+ ...(enqueueOptions.singletonKey === undefined
319
+ ? {}
320
+ : { singletonKey: enqueueOptions.singletonKey }),
321
+ ...(enqueueOptions.startAfter === undefined ? {} : { startAfter: enqueueOptions.startAfter }),
322
+ },
323
+ )
324
+ }
325
+
326
+ async function stop(): Promise<void> {
327
+ const instance = boss
328
+ if (instance === undefined) {
329
+ return
330
+ }
331
+
332
+ for (const name of workersStarted) {
333
+ try {
334
+ await instance.offWork(name, { wait: true })
335
+ } catch (error: unknown) {
336
+ options.logger.error('offWork failed', {
337
+ job: name,
338
+ error: describeThrown(error),
339
+ })
340
+ }
341
+ }
342
+ workersStarted.clear()
343
+
344
+ await instance.stop({ graceful: true, close: true, timeout: 30_000 })
345
+ boss = undefined
346
+ queuesCreated.clear()
347
+ }
348
+
349
+ return {
350
+ registry,
351
+ hasHandle: (name) => registered.has(name),
352
+ migrate,
353
+ start,
354
+ startWorking,
355
+ enqueueOnTx,
356
+ stop,
357
+ }
358
+ }
@@ -5,6 +5,7 @@ import type { Actor } from '../lib/actor.ts'
5
5
  import type { Database } from '../lib/database.ts'
6
6
  import type { EmailSender } from '../lib/email.ts'
7
7
  import type { IdFactory } from '../lib/ids.ts'
8
+ import type { JobRegistry } from '../lib/jobs.ts'
8
9
  import type { Logger } from '../lib/logger.ts'
9
10
  import type { SecretEncryptionConfig } from '../lib/secrets.ts'
10
11
  import type { EntitlementRegistry } from './entitlements.ts'
@@ -240,6 +241,17 @@ export interface ModuleContext extends ModuleServices {
240
241
  * commits, and must be idempotent.
241
242
  */
242
243
  readonly events: EventBus
244
+ /**
245
+ * Declares a background job. Modules call `context.jobs.define(...)` at
246
+ * register time and receive a typed handle to enqueue against. The insert
247
+ * lives inside the caller's transaction (`services.transaction`) so a
248
+ * rollback discards the job.
249
+ *
250
+ * A second `define` with the same name fails boot. Handlers run out of
251
+ * process on the worker entry point, or inline when the API runs its own
252
+ * worker.
253
+ */
254
+ readonly jobs: JobRegistry
243
255
  /**
244
256
  * Declare capabilities and check grants. Every check is granted and unlimited
245
257
  * until a module registers a provider.
@@ -7,6 +7,7 @@ import type { Environment } from '../lib/config.ts'
7
7
  import { createLogEmailSender } from '../lib/email.ts'
8
8
  import type { EmailMessage, EmailSender } from '../lib/email.ts'
9
9
  import { AppError, describeThrown, describeValidationIssue, toErrorDetails } from '../lib/errors.ts'
10
+ import type { JobRegistry } from '../lib/jobs.ts'
10
11
  import type { Logger } from '../lib/logger.ts'
11
12
  import { createEntitlementRegistry, requireCapability } from './entitlements.ts'
12
13
  import type { EntitlementRegistry } from './entitlements.ts'
@@ -241,6 +242,13 @@ export interface ModuleRuntimeOptions {
241
242
  * two modules had registered it.
242
243
  */
243
244
  readonly additionalEmailProviders?: ReadonlyMap<string, EmailSender> | undefined
245
+ /**
246
+ * The job registry modules bind to at register time. Bound to the pg-boss
247
+ * runtime in production (`runtime/jobs.ts`) and to a stub in unit tests
248
+ * that never define a job. A module that calls `context.jobs.define` when
249
+ * this is absent gets a boot-time error naming the module.
250
+ */
251
+ readonly jobs?: JobRegistry | undefined
244
252
  /**
245
253
  * The deploy-time module override (`lib/moduleConfig.ts`), parsed. A locked
246
254
  * module id wins over whatever a workspace's own settings say.
@@ -349,6 +357,21 @@ interface RegisteredProvider {
349
357
  readonly registeredBy: string
350
358
  }
351
359
 
360
+ /**
361
+ * Refuses `define` for a module that reached `context.jobs` when the runtime
362
+ * booted without a jobs registry. Named so a boot log points at the module
363
+ * whose declaration cannot be honoured, rather than a bare stack trace.
364
+ */
365
+ function createMissingJobsRegistry(moduleId: string): JobRegistry {
366
+ return {
367
+ define() {
368
+ throw new ModuleBootError([
369
+ `module "${moduleId}" defines a job but the assembly booted without a jobs runtime`,
370
+ ])
371
+ },
372
+ }
373
+ }
374
+
352
375
  function createModuleContext(
353
376
  module: KelpieModule,
354
377
  accumulator: Accumulator,
@@ -363,6 +386,7 @@ function createModuleContext(
363
386
  return {
364
387
  ...options.services,
365
388
  email: emailProxy,
389
+ jobs: options.jobs ?? createMissingJobsRegistry(module.id),
366
390
 
367
391
  provideExternalSignIn(handler) {
368
392
  externalSignIn.install(module.id, handler)
@@ -2,6 +2,11 @@ import type { EventActor, EventTarget, KelpieEvent } from '@kelpie/schemas'
2
2
 
3
3
  import type { Database } from '../lib/database.ts'
4
4
  import type { IdFactory } from '../lib/ids.ts'
5
+ import type {
6
+ EnqueueOptions,
7
+ JobHandle,
8
+ TransactionJobs,
9
+ } from '../lib/jobs.ts'
5
10
  import type { Logger } from '../lib/logger.ts'
6
11
  import { checkEventCycle, currentEventChain } from './events.ts'
7
12
  import type { EventBus, EventName, KelpieEventMap } from './events.ts'
@@ -43,6 +48,13 @@ export interface BufferedEvents {
43
48
  export interface TransactionContext {
44
49
  readonly tx: Transaction
45
50
  readonly events: BufferedEvents
51
+ /**
52
+ * Enqueues background work on the caller's transaction. The insert runs
53
+ * inside `tx` via pg-boss's Drizzle adapter, so a rolled-back scope
54
+ * discards the job with the write. Unlike `events`, this is not buffered:
55
+ * the return value carries the pg-boss job id, awaited inside the scope.
56
+ */
57
+ readonly jobs: TransactionJobs
46
58
  }
47
59
 
48
60
  export interface TransactionOptions {
@@ -69,6 +81,17 @@ interface BufferedEvent {
69
81
 
70
82
  const SYSTEM_ACTOR: EventActor = { kind: 'system' }
71
83
 
84
+ /**
85
+ * Inserts a background job on `tx`. Bound to the pg-boss provider in
86
+ * production (`runtime/jobs.ts`) and to a stub in tests that never enqueue.
87
+ */
88
+ export type EnqueueOnTransaction = <Data>(
89
+ tx: Transaction,
90
+ handle: JobHandle<Data>,
91
+ data: Data,
92
+ options?: EnqueueOptions,
93
+ ) => Promise<string | null>
94
+
72
95
  export interface TransactionScopeDependencies {
73
96
  readonly db: Database
74
97
  readonly bus: EventBus
@@ -78,12 +101,27 @@ export interface TransactionScopeDependencies {
78
101
  readonly now?: () => Date
79
102
  /** Chain-depth cap. Reads `KELPIE_EVENT_MAX_DEPTH`; otherwise 8. */
80
103
  readonly maxDepth?: number
104
+ /**
105
+ * How `tx.jobs.enqueue(...)` reaches pg-boss. Optional so unit tests that
106
+ * never enqueue can build the scope without a runtime; a call from a
107
+ * scope built without one rejects with a boot-time bug message.
108
+ */
109
+ readonly enqueueOnTx?: EnqueueOnTransaction
81
110
  }
82
111
 
83
112
  export function createTransactionScope(dependencies: TransactionScopeDependencies): TransactionScope {
84
113
  const now = dependencies.now ?? ((): Date => new Date())
85
114
  const maxDepth = dependencies.maxDepth ?? readMaxDepthFromEnv() ?? 8
86
115
 
116
+ const enqueueOnTx: EnqueueOnTransaction =
117
+ dependencies.enqueueOnTx ??
118
+ (() =>
119
+ Promise.reject(
120
+ new Error(
121
+ 'jobs.enqueue used but no jobs runtime was wired into the transaction scope',
122
+ ),
123
+ ))
124
+
87
125
  return async function runInTransaction(work, options) {
88
126
  const actor = options?.actor ?? SYSTEM_ACTOR
89
127
  const workspaceId = options?.workspaceId
@@ -92,6 +130,11 @@ export function createTransactionScope(dependencies: TransactionScopeDependencie
92
130
  const result = await dependencies.db.transaction((tx) =>
93
131
  work({
94
132
  tx,
133
+ jobs: {
134
+ enqueue(handle, data, enqueueOptions) {
135
+ return enqueueOnTx(tx, handle, data, enqueueOptions)
136
+ },
137
+ },
95
138
  events: {
96
139
  emit(name, target, data) {
97
140
  if (workspaceId === undefined || workspaceId.length === 0) {