@owlmeans/queue 0.1.18-rc.7 → 0.1.18-rc.8

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 (47) hide show
  1. package/README.md +111 -3
  2. package/agent-meta/manifest.json +2 -2
  3. package/agent-meta/skills/queue/SKILL.md +125 -12
  4. package/build/bridge.d.ts +27 -0
  5. package/build/bridge.d.ts.map +1 -0
  6. package/build/bridge.js +93 -0
  7. package/build/bridge.js.map +1 -0
  8. package/build/config.d.ts +22 -0
  9. package/build/config.d.ts.map +1 -0
  10. package/build/config.js +41 -0
  11. package/build/config.js.map +1 -0
  12. package/build/consts.d.ts +33 -0
  13. package/build/consts.d.ts.map +1 -0
  14. package/build/consts.js +35 -0
  15. package/build/consts.js.map +1 -0
  16. package/build/errors.d.ts +59 -0
  17. package/build/errors.d.ts.map +1 -0
  18. package/build/errors.js +90 -0
  19. package/build/errors.js.map +1 -0
  20. package/build/index.d.ts +7 -0
  21. package/build/index.d.ts.map +1 -1
  22. package/build/index.js +7 -1
  23. package/build/index.js.map +1 -1
  24. package/build/transport.d.ts +15 -0
  25. package/build/transport.d.ts.map +1 -0
  26. package/build/transport.js +62 -0
  27. package/build/transport.js.map +1 -0
  28. package/build/types.d.ts +240 -0
  29. package/build/types.d.ts.map +1 -0
  30. package/build/types.js +2 -0
  31. package/build/types.js.map +1 -0
  32. package/build/worker.d.ts +27 -0
  33. package/build/worker.d.ts.map +1 -0
  34. package/build/worker.js +58 -0
  35. package/build/worker.js.map +1 -0
  36. package/package.json +10 -1
  37. package/src/bridge.ts +109 -0
  38. package/src/config.ts +56 -0
  39. package/src/consts.ts +39 -0
  40. package/src/errors.ts +106 -0
  41. package/src/index.ts +7 -0
  42. package/src/transport.ts +82 -0
  43. package/src/types.ts +251 -0
  44. package/src/worker.ts +72 -0
  45. package/tests/bridge.spec.ts +64 -0
  46. package/tests/config.spec.ts +66 -0
  47. package/tsconfig.json +1 -0
package/src/bridge.ts ADDED
@@ -0,0 +1,109 @@
1
+ import type { AbstractRequest, CommonEntrypoint, GuardService } from '@owlmeans/entrypoint'
2
+ import { EntrypointOutcome, provideResponse } from '@owlmeans/entrypoint'
3
+ import type { Auth } from '@owlmeans/auth'
4
+ import { AuthorizationError } from '@owlmeans/auth'
5
+ import { attachEntity } from '@owlmeans/auth-common'
6
+ import { ResilientError } from '@owlmeans/error'
7
+ import type { Config, Context, JobContext, JobEnvelope, JobReply } from './types.js'
8
+ import { EnvelopeExpired, JobNotServed } from './errors.js'
9
+
10
+ /**
11
+ * Rebuild the request the producer described. A queued call is still a call: the same guards, the
12
+ * same filter, the same handler run against it — only the wire is different.
13
+ */
14
+ export const requestOf = (envelope: JobEnvelope, path: string): AbstractRequest => ({
15
+ alias: envelope.alias,
16
+ params: (envelope.params ?? {}) as AbstractRequest['params'],
17
+ body: envelope.body as AbstractRequest['body'],
18
+ headers: (envelope.headers ?? {}) as AbstractRequest['headers'],
19
+ query: (envelope.query ?? {}) as AbstractRequest['query'],
20
+ path,
21
+ })
22
+
23
+ /**
24
+ * Freshness is judged from when the job was ENQUEUED, not from now.
25
+ *
26
+ * A signed envelope proves who produced it, and a replay window keeps a captured one from being
27
+ * useful forever. But a job can legitimately sit behind a long backlog, and judging it on pickup
28
+ * would reject exactly the work that a busy queue delayed — so the producer's timestamp is what
29
+ * the window applies to.
30
+ *
31
+ * @throws {EnvelopeExpired}
32
+ */
33
+ export const assertFresh = (envelope: JobEnvelope, ttl?: number): void => {
34
+ if (ttl == null || envelope.enqueuedAt == null) {
35
+ return
36
+ }
37
+ const age = (Date.now() - new Date(envelope.enqueuedAt).getTime()) / 1000
38
+ if (age > ttl) {
39
+ throw new EnvelopeExpired(`${envelope.alias}: ${Math.round(age)}s > ${ttl}s`)
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Run one queued entrypoint call and describe the outcome.
45
+ *
46
+ * It never throws for a DOMAIN failure — the error is marshalled into the returned reply so the
47
+ * producer can rebuild it as its own class, and so the broker does not count a legitimate refusal
48
+ * as a job to retry. Infrastructure failures are left to propagate: those are what retries are for.
49
+ */
50
+ export const handleJob = async <C extends Config, T extends Context<C>>(
51
+ context: T, job: JobContext<JobEnvelope>
52
+ ): Promise<JobReply> => {
53
+ const envelope = job.data
54
+
55
+ try {
56
+ assertFresh(envelope, context.cfg.queue?.envelopeTtl)
57
+
58
+ const entrypoint = context.entrypoint<CommonEntrypoint>(envelope.alias)
59
+ if (entrypoint.handle == null) {
60
+ throw new JobNotServed(envelope.alias)
61
+ }
62
+
63
+ const request = requestOf(envelope, entrypoint.path())
64
+ const response = provideResponse<unknown>()
65
+
66
+ const guards = entrypoint.getGuards()
67
+ if (guards.length > 0) {
68
+ let matched: GuardService | undefined
69
+ for (const alias of guards) {
70
+ const guard: GuardService = context.service(alias)
71
+ if (await guard.match(request, response)) {
72
+ matched = guard
73
+ break
74
+ }
75
+ }
76
+ if (matched == null) {
77
+ throw new AuthorizationError(`queue:${envelope.alias}`)
78
+ }
79
+
80
+ const auth = provideResponse<Auth>()
81
+ if (!await matched.handle<boolean>(request, auth)) {
82
+ throw new AuthorizationError(`queue:${envelope.alias}:${matched.alias}`)
83
+ }
84
+ request.auth = auth.value
85
+
86
+ const entity = await attachEntity(context, request)
87
+ if (entity != null) {
88
+ request.entity = entity
89
+ }
90
+ }
91
+
92
+ await entrypoint.handle(request, response)
93
+
94
+ if (response.error != null) {
95
+ return { error: ResilientError.marshal(response.error).message }
96
+ }
97
+
98
+ return { value: response.value, outcome: response.outcome ?? EntrypointOutcome.Ok }
99
+ } catch (e) {
100
+ // A refusal the caller must see as its own class — `ContentRefused`, `AgentLocked` — travels
101
+ // in the reply. Only a broker- or connection-level fault should ever reach the retry logic:
102
+ // retrying a refusal just spends the work again to be refused identically.
103
+ if (e instanceof ResilientError) {
104
+ return { error: ResilientError.marshal(e).message }
105
+ }
106
+
107
+ throw e
108
+ }
109
+ }
package/src/config.ts ADDED
@@ -0,0 +1,56 @@
1
+ import type { Config, JobOptions, QueueDeclaration, QueueWorkerOptions } from './types.js'
2
+ import { UnknownQueue } from './errors.js'
3
+
4
+ /**
5
+ * Add a queue to the shared configuration. Every process in the monorepo loads the same
6
+ * declarations — a producer needs them to know a queue exists and what it accepts, a worker needs
7
+ * them to bind. Declaring twice replaces, so a helper that runs per app is safe to call.
8
+ */
9
+ export const declareQueue = <C extends Config>(
10
+ cfg: C, name: string, jobs: string[], opts?: { worker?: QueueWorkerOptions, defaults?: JobOptions }
11
+ ): C => {
12
+ const queue: QueueDeclaration = { name, jobs, ...opts }
13
+ const queues = cfg.queue?.queues ?? []
14
+ const existing = queues.findIndex(declared => declared.name === name)
15
+
16
+ if (existing < 0) {
17
+ queues.push(queue)
18
+ } else {
19
+ queues[existing] = queue
20
+ }
21
+
22
+ cfg.queue = { ...cfg.queue, queues }
23
+
24
+ return cfg
25
+ }
26
+
27
+ /**
28
+ * Name the queues this process consumes. It is what turns an otherwise identical binary into a
29
+ * worker, which is why it lives in the process's own config and never in a declaration.
30
+ */
31
+ export const listenQueues = <C extends Config>(cfg: C, ...names: string[]): C => {
32
+ const listen = new Set([...(cfg.queue?.listen ?? []), ...names])
33
+
34
+ cfg.queue = { ...cfg.queue, listen: [...listen] }
35
+
36
+ return cfg
37
+ }
38
+
39
+ /**
40
+ * @throws {UnknownQueue}
41
+ */
42
+ export const queueOf = <C extends Config>(cfg: C, name: string): QueueDeclaration => {
43
+ const queue = cfg.queue?.queues?.find(declared => declared.name === name)
44
+
45
+ if (queue == null) {
46
+ throw new UnknownQueue(name)
47
+ }
48
+
49
+ return queue
50
+ }
51
+
52
+ export const queueOfJob = <C extends Config>(cfg: C, job: string): QueueDeclaration | undefined =>
53
+ cfg.queue?.queues?.find(declared => declared.jobs.includes(job))
54
+
55
+ export const isListening = <C extends Config>(cfg: C, name: string): boolean =>
56
+ cfg.queue?.listen?.includes(name) === true
package/src/consts.ts ADDED
@@ -0,0 +1,39 @@
1
+
2
+ export const DEFAULT_ALIAS = 'queue'
3
+
4
+ /**
5
+ * The state a job is in, as the broker reports it. `Waiting` covers both a job queued normally
6
+ * and one held by an unfinished parent — the difference matters to the broker, never to a caller
7
+ * asking whether an answer has arrived.
8
+ */
9
+ export enum JobState {
10
+ Waiting = 'waiting',
11
+ Delayed = 'delayed',
12
+ Active = 'active',
13
+ Completed = 'completed',
14
+ Failed = 'failed',
15
+ Unknown = 'unknown',
16
+ }
17
+
18
+ /** A job has reached a state it will not leave on its own. */
19
+ export const isSettled = (state?: JobState): boolean =>
20
+ state === JobState.Completed || state === JobState.Failed
21
+
22
+ export enum JobEventType {
23
+ Completed = 'completed',
24
+ Failed = 'failed',
25
+ Progress = 'progress',
26
+ }
27
+
28
+ /**
29
+ * How long a caller waits for a reply when neither the route nor the request says. Long enough
30
+ * for work that talks to a model, short enough that a lost job surfaces as an error rather than a
31
+ * hung request.
32
+ */
33
+ export const DEFAULT_JOB_TIMEOUT = 60_000
34
+
35
+ /**
36
+ * Retries default to one attempt: the jobs here are mostly LLM work, and a blind retry re-spends
37
+ * the tokens that just failed. A queue whose jobs are cheap and idempotent raises it per queue.
38
+ */
39
+ export const DEFAULT_ATTEMPTS = 1
package/src/errors.ts ADDED
@@ -0,0 +1,106 @@
1
+ import { ResilientError } from '@owlmeans/error'
2
+
3
+ export class QueueError extends ResilientError {
4
+ public static override typeName = 'QueueError'
5
+
6
+ constructor(message: string = 'error') {
7
+ super(QueueError.typeName, `queue:${message}`)
8
+ }
9
+ }
10
+
11
+ /**
12
+ * The caller stopped waiting. The job is untouched — it may still be queued, running, or already
13
+ * finished; only the wait ended. Read the job back to learn which.
14
+ */
15
+ export class QueueTimeout extends QueueError {
16
+ public static override typeName = `${QueueError.typeName}Timeout`
17
+
18
+ constructor(msg: string) {
19
+ super(`timeout:${msg}`)
20
+ this.type = QueueTimeout.typeName
21
+ }
22
+ }
23
+
24
+ /** No job with that id in this queue — it never existed, or it was removed after completing. */
25
+ export class UnknownJob extends QueueError {
26
+ public static override typeName = `${QueueError.typeName}UnknownJob`
27
+
28
+ constructor(msg: string) {
29
+ super(`unknown-job:${msg}`)
30
+ this.type = UnknownJob.typeName
31
+ }
32
+ }
33
+
34
+ /**
35
+ * A job name the queue does not declare. Declaring every job a queue accepts is what keeps an
36
+ * enqueue from succeeding into a queue where nothing can ever process it.
37
+ */
38
+ export class UnknownJobName extends QueueError {
39
+ public static override typeName = `${QueueError.typeName}UnknownJobName`
40
+
41
+ constructor(msg: string) {
42
+ super(`unknown-job-name:${msg}`)
43
+ this.type = UnknownJobName.typeName
44
+ }
45
+ }
46
+
47
+ /** A queue asked for that no declaration names. */
48
+ export class UnknownQueue extends QueueError {
49
+ public static override typeName = `${QueueError.typeName}UnknownQueue`
50
+
51
+ constructor(msg: string) {
52
+ super(`unknown-queue:${msg}`)
53
+ this.type = UnknownQueue.typeName
54
+ }
55
+ }
56
+
57
+ /**
58
+ * This process was asked to consume a queue it does not listen to. Which queues a process
59
+ * consumes is configuration (`cfg.queue.listen`), so this is a deployment question, not a code
60
+ * one — the same binary is a producer or a worker depending on it.
61
+ */
62
+ export class QueueNotListening extends QueueError {
63
+ public static override typeName = `${QueueError.typeName}NotListening`
64
+
65
+ constructor(msg: string) {
66
+ super(`not-listening:${msg}`)
67
+ this.type = QueueNotListening.typeName
68
+ }
69
+ }
70
+
71
+ /**
72
+ * The job named an entrypoint this process does not serve. Unlike a missing queue this is not a
73
+ * declaration problem: the alias exists, but nothing here elevated it, so the job was taken by a
74
+ * worker that cannot run it.
75
+ */
76
+ export class JobNotServed extends QueueError {
77
+ public static override typeName = `${QueueError.typeName}JobNotServed`
78
+
79
+ constructor(msg: string) {
80
+ super(`job-not-served:${msg}`)
81
+ this.type = JobNotServed.typeName
82
+ }
83
+ }
84
+
85
+ /**
86
+ * The signed envelope is older than the configured lifetime. Freshness is judged from when the
87
+ * producer enqueued the job, not from when a worker picked it up, so a long backlog does not
88
+ * invalidate work that was legitimate when it was submitted.
89
+ */
90
+ export class EnvelopeExpired extends QueueError {
91
+ public static override typeName = `${QueueError.typeName}EnvelopeExpired`
92
+
93
+ constructor(msg: string) {
94
+ super(`envelope-expired:${msg}`)
95
+ this.type = EnvelopeExpired.typeName
96
+ }
97
+ }
98
+
99
+ ResilientError.registerErrorClass(QueueError)
100
+ ResilientError.registerErrorClass(QueueTimeout)
101
+ ResilientError.registerErrorClass(UnknownJob)
102
+ ResilientError.registerErrorClass(UnknownJobName)
103
+ ResilientError.registerErrorClass(UnknownQueue)
104
+ ResilientError.registerErrorClass(QueueNotListening)
105
+ ResilientError.registerErrorClass(JobNotServed)
106
+ ResilientError.registerErrorClass(EnvelopeExpired)
package/src/index.ts CHANGED
@@ -0,0 +1,7 @@
1
+ export * from './types.js'
2
+ export * from './consts.js'
3
+ export * from './errors.js'
4
+ export * from './config.js'
5
+ export * from './transport.js'
6
+ export * from './bridge.js'
7
+ export * from './worker.js'
@@ -0,0 +1,82 @@
1
+ import { assertContext, createService } from '@owlmeans/context'
2
+ import type { AbstractRequest, AbstractResponse, EntrypointTransport } from '@owlmeans/entrypoint'
3
+ import { EntrypointOutcome, transportAlias } from '@owlmeans/entrypoint'
4
+ import { RouteProtocols } from '@owlmeans/route'
5
+ import { ResilientError } from '@owlmeans/error'
6
+ import type { CommonEntrypoint } from '@owlmeans/entrypoint'
7
+ import type { Config, Context, JobEnvelope, JobReply, QueueAppend } from './types.js'
8
+ import { DEFAULT_JOB_TIMEOUT } from './consts.js'
9
+ import { UnknownQueue } from './errors.js'
10
+
11
+ /**
12
+ * The producing half of the bridge: it turns a call on a QUEUE entrypoint into a job, and the
13
+ * job's outcome back into a reply.
14
+ *
15
+ * Registering it is the whole opt-in. `apiHandler` looks up a transport by the route's protocol,
16
+ * so a consumer writes `ep.call(...)` against a declaration it shares with every other kind of
17
+ * entrypoint and never learns which one carried it. That is also why the envelope is built from
18
+ * the request rather than from the entrypoint: the far side rebuilds a request, and anything only
19
+ * HTTP understands would not survive the trip anyway.
20
+ */
21
+ export const makeQueueTransport = (alias: string = transportAlias(RouteProtocols.QUEUE)) => {
22
+ const location = `queue-transport:${alias}`
23
+
24
+ const service = createService<EntrypointTransport>(alias, {
25
+ protocol: RouteProtocols.QUEUE,
26
+
27
+ handle: (async <T>(req: AbstractRequest, res: AbstractResponse<T>) => {
28
+ const context = assertContext<Config, Context<Config>>(service.ctx as Context<Config>, location)
29
+ const entrypoint = context.entrypoint<CommonEntrypoint>(req.alias)
30
+ const route = entrypoint.route.route
31
+
32
+ if (route.queue == null) {
33
+ throw new UnknownQueue(`${req.alias}: route declares no queue`)
34
+ }
35
+
36
+ const jobs = (context as unknown as QueueAppend).jobs<JobEnvelope, JobReply<T>>(route.queue)
37
+
38
+ const envelope: JobEnvelope = {
39
+ alias: req.alias,
40
+ params: req.params as Record<string, unknown>,
41
+ body: req.body,
42
+ query: req.query as Record<string, unknown>,
43
+ headers: req.headers as Record<string, string | undefined>,
44
+ enqueuedAt: new Date().toISOString(),
45
+ }
46
+
47
+ const job = await jobs.create({ queue: route.queue, name: req.alias, data: envelope })
48
+
49
+ // `reply: false` says the caller is not waiting for the work, only for the promise that it
50
+ // was taken. `Accepted` plus the job's identity is the whole answer — enough to watch it.
51
+ if (route.reply === false) {
52
+ res.resolve({ id: job.id, queue: route.queue } as T, EntrypointOutcome.Accepted)
53
+
54
+ return
55
+ }
56
+
57
+ const reply = await jobs.wait(job.id as string, {
58
+ timeout: req.timeout ?? route.timeout ?? DEFAULT_JOB_TIMEOUT
59
+ })
60
+
61
+ // A processor reports a domain failure by returning it, so it crosses the hop as the class
62
+ // it was thrown as rather than as a string a caller would have to parse.
63
+ if (reply?.error != null) {
64
+ throw ResilientError.ensure(reply.error as Error | string)
65
+ }
66
+
67
+ res.resolve(reply?.value as T, (reply?.outcome as EntrypointOutcome) ?? EntrypointOutcome.Ok)
68
+ }) as EntrypointTransport['handle']
69
+ })
70
+
71
+ return service
72
+ }
73
+
74
+ export const appendQueueTransport = <C extends Config, T extends Context<C> = Context<C>>(
75
+ context: T, alias?: string
76
+ ): T => {
77
+ const service = makeQueueTransport(alias)
78
+
79
+ context.registerService(service)
80
+
81
+ return context
82
+ }
package/src/types.ts ADDED
@@ -0,0 +1,251 @@
1
+ import type { BasicConfig, BasicContext, InitializedService } from '@owlmeans/context'
2
+ import type { PubSubResource, Resource, ResourceRecord } from '@owlmeans/resource'
3
+ import type { AbstractRequest, AbstractResponse } from '@owlmeans/entrypoint'
4
+ import type { JobEventType, JobState } from './consts.js'
5
+
6
+ /**
7
+ * Everything the monorepo knows about its queues, declared in the shared backend package so that
8
+ * producer and consumer read the same list. A process becomes a worker by naming queues in
9
+ * `listen` — nothing in a declaration decides where it runs.
10
+ */
11
+ export interface QueueConfig {
12
+ queues?: QueueDeclaration[]
13
+ /** The queues THIS process consumes. Absent or empty means producer only. */
14
+ listen?: string[]
15
+ /** Which db service carries the queues. Defaults to the queue service's own alias. */
16
+ db?: string
17
+ defaults?: JobOptions
18
+ /**
19
+ * How long a signed job envelope stays acceptable, in seconds. It bounds both the freshness
20
+ * check and the nonce cache, so a job delayed behind a long backlog is still admitted.
21
+ */
22
+ envelopeTtl?: number
23
+ }
24
+
25
+ export interface QueueDeclaration {
26
+ name: string
27
+ /**
28
+ * The job names this queue accepts. A job the queue does not declare is refused at enqueue
29
+ * time rather than becoming a job nothing can process.
30
+ */
31
+ jobs: string[]
32
+ worker?: QueueWorkerOptions
33
+ defaults?: JobOptions
34
+ }
35
+
36
+ export interface QueueWorkerOptions {
37
+ concurrency?: number
38
+ /**
39
+ * How long a job may hold its lock without reporting progress. A processor that runs longer
40
+ * than this between `touch()` calls is treated as stalled and its job is handed to someone else.
41
+ */
42
+ lockDuration?: number
43
+ stalledInterval?: number
44
+ maxStalledCount?: number
45
+ }
46
+
47
+ export interface JobOptions {
48
+ attempts?: number
49
+ backoff?: { type: 'fixed' | 'exponential', delay: number }
50
+ delay?: number
51
+ priority?: number
52
+ /**
53
+ * A caller-chosen identity for the job. Enqueueing the same id twice while the first is still
54
+ * around is a no-op, which is what makes an admission step safe to retry.
55
+ */
56
+ id?: string
57
+ removeOnComplete?: boolean | number
58
+ removeOnFail?: boolean | number
59
+ }
60
+
61
+ /**
62
+ * A job as a RECORD — the same shape the resource contract reads and writes, so inspecting a
63
+ * queue is `list`/`get`/`count` rather than a broker-specific API.
64
+ */
65
+ export interface JobRecord<D = unknown, R = unknown> extends ResourceRecord {
66
+ queue: string
67
+ name: string
68
+ data: D
69
+ state?: JobState
70
+ result?: R
71
+ error?: string
72
+ attempts?: number
73
+ progress?: unknown
74
+ parentId?: string
75
+ createdAt?: string
76
+ startedAt?: string
77
+ finishedAt?: string
78
+ opts?: JobOptions
79
+ }
80
+
81
+ export interface JobEvent<R = unknown> {
82
+ type: JobEventType
83
+ id: string
84
+ queue: string
85
+ /**
86
+ * Empty when the job is already gone. A broker's completion event carries only an id, so the
87
+ * name is read back from the job — and a queue that removes jobs on completion has nothing left
88
+ * to read. Subscribe for the id and the outcome; do not branch on the name.
89
+ */
90
+ name: string
91
+ result?: R
92
+ error?: string
93
+ progress?: unknown
94
+ }
95
+
96
+ /** A node of a job graph: children run first, siblings run together. */
97
+ export interface FlowSpec<D = unknown> {
98
+ name: string
99
+ queue?: string
100
+ data: D
101
+ opts?: JobOptions
102
+ children?: FlowSpec[]
103
+ }
104
+
105
+ /**
106
+ * One queue, addressed as a resource.
107
+ *
108
+ * `create` enqueues, `get`/`load`/`list`/`count` inspect, `delete`/`take` cancel. What the base
109
+ * contract cannot express — waiting for an answer, submitting a graph, releasing the connection —
110
+ * is added here.
111
+ *
112
+ * Three places where the base `Resource` contract reads differently against a broker, because a
113
+ * job is not a row:
114
+ * - `create` does NOT throw `RecordExists` for a repeated `opts.id`. Re-enqueueing an id that is
115
+ * still around returns the existing job, which is the idempotency that makes an admission step
116
+ * safe to retry.
117
+ * - `WriteOptions.ttl` is refused. A job's lifetime is `removeOnComplete`/`removeOnFail` —
118
+ * explicit deletion once it has finished, not expiry while it waits.
119
+ * - `update`/`save` reach only the job's `data`. Everything else about a job belongs to the
120
+ * broker, and an implementation refuses rather than pretending to write it.
121
+ */
122
+ export interface QueueResource<D = unknown, R = unknown>
123
+ extends Resource<JobRecord<D, R>>, PubSubResource<JobEvent<R>> {
124
+ queue: string
125
+ /**
126
+ * Release the connections this queue holds.
127
+ *
128
+ * Watching for completions means a blocking connection, and a process that never releases it
129
+ * does not exit. Nothing else in the resource contract can express that, so it lives here and a
130
+ * producer calls it on shutdown.
131
+ */
132
+ close: () => Promise<void>
133
+ /**
134
+ * Wait for a job's return value.
135
+ * @throws {QueueTimeout} when the wait elapses — the job itself is left alone.
136
+ * @throws the processor's own error, rebuilt as its original class.
137
+ */
138
+ wait: (id: string, opts?: { timeout?: number }) => Promise<R>
139
+ /** Submit a graph and get its root back. Children complete before their parent starts. */
140
+ flow: (root: FlowSpec<D>) => Promise<JobRecord<D, R>>
141
+ counts: () => Promise<Record<JobState, number>>
142
+ }
143
+
144
+ /**
145
+ * What a processor is handed. `data` is the job's payload; everything else is the means to stay
146
+ * alive and to read what the children reported.
147
+ */
148
+ export interface JobContext<D = unknown> {
149
+ id: string
150
+ name: string
151
+ queue: string
152
+ attempt: number
153
+ data: D
154
+ signal: AbortSignal
155
+ /**
156
+ * Renew the lock. A processor that runs a long loop MUST call it as it goes: the broker judges
157
+ * liveness by the lock, so silence for longer than `lockDuration` is indistinguishable from a
158
+ * dead worker, and the job is re-run somewhere else while this one is still working on it.
159
+ */
160
+ touch: () => Promise<void>
161
+ progress: (value: unknown) => Promise<void>
162
+ /**
163
+ * What the children returned, keyed by child job id.
164
+ *
165
+ * A broker keys them by its own fully qualified job key; an implementation re-keys to the bare
166
+ * id, so two children of one parent that live in DIFFERENT queues and happen to share an id
167
+ * collide here. Give the children of a cross-queue flow distinct ids.
168
+ */
169
+ children: <T = unknown>() => Promise<Record<string, T>>
170
+ failedChildren: () => Promise<Record<string, string>>
171
+ }
172
+
173
+ export interface JobProcessor<D = unknown, R = unknown> {
174
+ (job: JobContext<D>): Promise<R>
175
+ }
176
+
177
+ /**
178
+ * The consuming half. It is registered only in processes that consume: `start()` binds the
179
+ * queues named in `cfg.listen` and dispatches by job name, to a processor registered here or to
180
+ * an entrypoint served in this process.
181
+ */
182
+ export interface QueueWorkerService extends InitializedService {
183
+ process: <D, R>(queue: string, name: string, processor: JobProcessor<D, R>) => void
184
+ start: () => Promise<void>
185
+ stop: () => Promise<void>
186
+ /** The queues this process actually consumes. Empty in a producer. */
187
+ listening: () => string[]
188
+ /**
189
+ * Bind the application's reactions to job lifecycle events. Registering more than once merges,
190
+ * so an application composed of several parts can each contribute what it cares about.
191
+ *
192
+ * It belongs on the contract rather than on a driver because `onJobDead` is where an
193
+ * application COMPENSATES — releases the lock the admission step took, marks the record failed —
194
+ * and that behaviour must not have to be rewritten when the broker changes.
195
+ */
196
+ hooks: (hooks: QueueHooks) => void
197
+ }
198
+
199
+ /**
200
+ * The envelope a queued entrypoint call travels in. It is the request, minus everything that only
201
+ * means something to HTTP — the transport rebuilds a request from it on the far side.
202
+ */
203
+ export interface JobEnvelope {
204
+ alias: string
205
+ params?: Record<string, unknown>
206
+ body?: unknown
207
+ query?: Record<string, unknown>
208
+ headers?: Record<string, string | undefined>
209
+ /** When the producer enqueued it — freshness is judged here, not at processing time. */
210
+ enqueuedAt?: string
211
+ }
212
+
213
+ /** What a processor returns for an entrypoint job, so the caller can rebuild the reply. */
214
+ export interface JobReply<T = unknown> {
215
+ value?: T
216
+ outcome?: string
217
+ error?: unknown
218
+ }
219
+
220
+ export interface QueueHooks {
221
+ wrapHandler?: (job: JobContext, next: () => Promise<unknown>) => Promise<unknown>
222
+ onJobResult?: (event: JobEvent) => void | Promise<void>
223
+ onJobStalled?: (meta: { id: string, queue: string, name: string }, phase: 'stalled' | 'failed') => void | Promise<void>
224
+ /**
225
+ * The job is finished for good — retries exhausted, or it was dropped. This is where an
226
+ * application compensates: release the lock the admission step took, mark the record failed.
227
+ */
228
+ onJobDead?: (job: JobRecord, reason: string) => void | Promise<void>
229
+ }
230
+
231
+ export interface QueueDriver {
232
+ resource: <D, R>(queue: string) => QueueResource<D, R>
233
+ worker: () => QueueWorkerService
234
+ }
235
+
236
+ export interface Config extends BasicConfig {
237
+ queue?: QueueConfig
238
+ }
239
+
240
+ export interface Context<C extends Config = Config> extends BasicContext<C> {
241
+ }
242
+
243
+ export interface QueueAppend {
244
+ jobs: <D = unknown, R = unknown>(queue?: string) => QueueResource<D, R>
245
+ }
246
+
247
+ export interface QueueTransportRequest extends AbstractRequest {
248
+ }
249
+
250
+ export interface QueueTransportResponse extends AbstractResponse<unknown> {
251
+ }