@oatscenter/trellis 0.100.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (264) hide show
  1. package/README.md +59 -0
  2. package/auth/authorization/client_context.d.ts +61 -0
  3. package/auth/authorization/client_context.js +266 -0
  4. package/auth/authorization/nats_registry.d.ts +41 -0
  5. package/auth/authorization/nats_registry.js +283 -0
  6. package/auth/authorization/provider_cache.d.ts +90 -0
  7. package/auth/authorization/provider_cache.js +783 -0
  8. package/auth/authorization/refresh.d.ts +46 -0
  9. package/auth/authorization/refresh.js +246 -0
  10. package/auth/authorization/types.d.ts +207 -0
  11. package/auth/authorization/types.js +60 -0
  12. package/auth/authorization_context.d.ts +11 -0
  13. package/auth/authorization_context.js +10 -0
  14. package/auth/browser/flow_types.d.ts +84 -0
  15. package/auth/browser/flow_types.js +70 -0
  16. package/auth/browser/portal.d.ts +21 -0
  17. package/auth/browser/portal.js +307 -0
  18. package/auth/browser/storage.d.ts +26 -0
  19. package/auth/browser/storage.js +224 -0
  20. package/auth/browser.d.ts +11 -0
  21. package/auth/browser.js +10 -0
  22. package/auth/browser_recovery.d.ts +13 -0
  23. package/auth/browser_recovery.js +38 -0
  24. package/auth/device_activation.d.ts +134 -0
  25. package/auth/device_activation.js +376 -0
  26. package/auth/http_error.d.ts +12 -0
  27. package/auth/http_error.js +32 -0
  28. package/auth/keys.d.ts +5 -0
  29. package/auth/keys.js +63 -0
  30. package/auth/mod.d.ts +16 -0
  31. package/auth/mod.js +16 -0
  32. package/auth/proof.d.ts +31 -0
  33. package/auth/proof.js +95 -0
  34. package/auth/protocol_wasm/trellis_protocol_wasm.d.ts +138 -0
  35. package/auth/protocol_wasm/trellis_protocol_wasm.js +605 -0
  36. package/auth/protocol_wasm/trellis_protocol_wasm_bg.wasm +0 -0
  37. package/auth/protocol_wasm/trellis_protocol_wasm_bytes.d.ts +1 -0
  38. package/auth/protocol_wasm/trellis_protocol_wasm_bytes.js +2 -0
  39. package/auth/protocol_wasm.d.ts +179 -0
  40. package/auth/protocol_wasm.js +133 -0
  41. package/auth/session_auth.d.ts +30 -0
  42. package/auth/session_auth.js +77 -0
  43. package/auth/session_proof.d.ts +53 -0
  44. package/auth/session_proof.js +43 -0
  45. package/auth/time.d.ts +6 -0
  46. package/auth/time.js +7 -0
  47. package/auth/trellis_id.d.ts +1 -0
  48. package/auth/trellis_id.js +5 -0
  49. package/auth/utils.d.ts +10 -0
  50. package/auth/utils.js +69 -0
  51. package/auth.d.ts +1 -0
  52. package/auth.js +1 -0
  53. package/caller.d.ts +111 -0
  54. package/caller.js +85 -0
  55. package/client.d.ts +14 -0
  56. package/client.js +1 -0
  57. package/client_connect.d.ts +143 -0
  58. package/client_connect.js +1097 -0
  59. package/codec.d.ts +13 -0
  60. package/codec.js +192 -0
  61. package/connection.d.ts +107 -0
  62. package/connection.js +396 -0
  63. package/device/activation.d.ts +42 -0
  64. package/device/activation.js +319 -0
  65. package/device.d.ts +80 -0
  66. package/device.js +687 -0
  67. package/env.d.ts +2 -0
  68. package/env.js +10 -0
  69. package/errors/AuthError.d.ts +30 -0
  70. package/errors/AuthError.js +34 -0
  71. package/errors/KVError.d.ts +30 -0
  72. package/errors/KVError.js +36 -0
  73. package/errors/OperationLifecycleError.d.ts +110 -0
  74. package/errors/OperationLifecycleError.js +142 -0
  75. package/errors/RemoteError.d.ts +61 -0
  76. package/errors/RemoteError.js +72 -0
  77. package/errors/SchemaValidationError.d.ts +48 -0
  78. package/errors/SchemaValidationError.js +49 -0
  79. package/errors/StoreError.d.ts +21 -0
  80. package/errors/StoreError.js +31 -0
  81. package/errors/TransferError.d.ts +21 -0
  82. package/errors/TransferError.js +31 -0
  83. package/errors/TransportError.d.ts +29 -0
  84. package/errors/TransportError.js +33 -0
  85. package/errors/TrellisError.d.ts +15 -0
  86. package/errors/TrellisError.js +15 -0
  87. package/errors/ValidationError.d.ts +50 -0
  88. package/errors/ValidationError.js +59 -0
  89. package/errors/index.d.ts +254 -0
  90. package/errors/index.js +238 -0
  91. package/generated.d.ts +4 -0
  92. package/generated.js +3 -0
  93. package/generated_support.d.ts +120 -0
  94. package/generated_support.js +359 -0
  95. package/globals.d.ts +9 -0
  96. package/globals.js +16 -0
  97. package/health_transport.d.ts +18 -0
  98. package/health_transport.js +32 -0
  99. package/helpers.d.ts +11 -0
  100. package/helpers.js +53 -0
  101. package/index.d.ts +2 -0
  102. package/index.js +2 -0
  103. package/internal_sdk/generated/apis/auth/mod.d.ts +805 -0
  104. package/internal_sdk/generated/apis/auth/mod.js +958 -0
  105. package/internal_sdk/generated/apis/core/mod.d.ts +79 -0
  106. package/internal_sdk/generated/apis/core/mod.js +93 -0
  107. package/internal_sdk/generated/apis/events/mod.d.ts +224 -0
  108. package/internal_sdk/generated/apis/events/mod.js +313 -0
  109. package/internal_sdk/generated/apis/health/mod.d.ts +106 -0
  110. package/internal_sdk/generated/apis/health/mod.js +132 -0
  111. package/internal_sdk/generated/apis/index.d.ts +7 -0
  112. package/internal_sdk/generated/apis/index.js +8 -0
  113. package/internal_sdk/generated/apis/jobs/mod.d.ts +176 -0
  114. package/internal_sdk/generated/apis/jobs/mod.js +209 -0
  115. package/internal_sdk/generated/apis/state/mod.d.ts +104 -0
  116. package/internal_sdk/generated/apis/state/mod.js +139 -0
  117. package/internal_sdk/generated/index.d.ts +4 -0
  118. package/internal_sdk/generated/index.js +5 -0
  119. package/internal_sdk/generated/package.json +18 -0
  120. package/internal_sdk/generated/participants/cli/mod.d.ts +402 -0
  121. package/internal_sdk/generated/participants/cli/mod.js +460 -0
  122. package/internal_sdk/generated/participants/cli/types.d.ts +2 -0
  123. package/internal_sdk/generated/participants/cli/types.js +3 -0
  124. package/internal_sdk/generated/participants/console/mod.d.ts +489 -0
  125. package/internal_sdk/generated/participants/console/mod.js +579 -0
  126. package/internal_sdk/generated/participants/console/types.d.ts +2 -0
  127. package/internal_sdk/generated/participants/console/types.js +3 -0
  128. package/internal_sdk/generated/participants/eventsRuntime/mod.d.ts +64 -0
  129. package/internal_sdk/generated/participants/eventsRuntime/mod.js +42 -0
  130. package/internal_sdk/generated/participants/eventsRuntime/types.d.ts +2 -0
  131. package/internal_sdk/generated/participants/eventsRuntime/types.js +3 -0
  132. package/internal_sdk/generated/participants/healthRuntime/mod.d.ts +58 -0
  133. package/internal_sdk/generated/participants/healthRuntime/mod.js +36 -0
  134. package/internal_sdk/generated/participants/healthRuntime/types.d.ts +2 -0
  135. package/internal_sdk/generated/participants/healthRuntime/types.js +3 -0
  136. package/internal_sdk/generated/participants/index.d.ts +8 -0
  137. package/internal_sdk/generated/participants/index.js +9 -0
  138. package/internal_sdk/generated/participants/jobsRuntime/mod.d.ts +64 -0
  139. package/internal_sdk/generated/participants/jobsRuntime/mod.js +42 -0
  140. package/internal_sdk/generated/participants/jobsRuntime/types.d.ts +2 -0
  141. package/internal_sdk/generated/participants/jobsRuntime/types.js +3 -0
  142. package/internal_sdk/generated/participants/platform/mod.d.ts +164 -0
  143. package/internal_sdk/generated/participants/platform/mod.js +149 -0
  144. package/internal_sdk/generated/participants/platform/types.d.ts +7 -0
  145. package/internal_sdk/generated/participants/platform/types.js +5 -0
  146. package/internal_sdk/generated/participants/portal/mod.d.ts +131 -0
  147. package/internal_sdk/generated/participants/portal/mod.js +109 -0
  148. package/internal_sdk/generated/participants/portal/types.d.ts +2 -0
  149. package/internal_sdk/generated/participants/portal/types.js +3 -0
  150. package/internal_sdk/generated/types/_internal/p0.d.ts +13511 -0
  151. package/internal_sdk/generated/types/_internal/p0.js +6105 -0
  152. package/internal_sdk/generated/types/index.d.ts +2951 -0
  153. package/internal_sdk/generated/types/index.js +1477 -0
  154. package/jobs.d.ts +309 -0
  155. package/jobs.js +389 -0
  156. package/kv.d.ts +85 -0
  157. package/kv.js +330 -0
  158. package/operations.d.ts +189 -0
  159. package/operations.js +847 -0
  160. package/package.json +73 -0
  161. package/pagination.d.ts +25 -0
  162. package/pagination.js +117 -0
  163. package/participant.d.ts +6 -0
  164. package/participant.js +6 -0
  165. package/participant_runtime/api.d.ts +131 -0
  166. package/participant_runtime/api.js +42 -0
  167. package/participant_runtime/json.d.ts +16 -0
  168. package/participant_runtime/json.js +193 -0
  169. package/participant_runtime/metadata.d.ts +34 -0
  170. package/participant_runtime/metadata.js +4 -0
  171. package/participant_runtime/participant.d.ts +200 -0
  172. package/participant_runtime/participant.js +330 -0
  173. package/participant_runtime/schemas.d.ts +347 -0
  174. package/participant_runtime/schemas.js +211 -0
  175. package/participant_runtime/surface_names.d.ts +16 -0
  176. package/participant_runtime/surface_names.js +34 -0
  177. package/portable.d.ts +30 -0
  178. package/portable.js +14 -0
  179. package/provider.d.ts +69 -0
  180. package/provider.js +68 -0
  181. package/runtime_transport.d.ts +25 -0
  182. package/runtime_transport.js +48 -0
  183. package/service/mod.d.ts +14 -0
  184. package/service/mod.js +13 -0
  185. package/service/outbox_inbox.d.ts +259 -0
  186. package/service/outbox_inbox.js +908 -0
  187. package/service/runtime/bootstrap.d.ts +56 -0
  188. package/service/runtime/bootstrap.js +226 -0
  189. package/service/runtime/core.d.ts +46 -0
  190. package/service/runtime/core.js +1747 -0
  191. package/service/runtime/health.d.ts +97 -0
  192. package/service/runtime/health.js +153 -0
  193. package/service/runtime/health_schemas.d.ts +23 -0
  194. package/service/runtime/health_schemas.js +20 -0
  195. package/service/runtime/internal_jobs/active-job.d.ts +40 -0
  196. package/service/runtime/internal_jobs/active-job.js +91 -0
  197. package/service/runtime/internal_jobs/bindings.d.ts +40 -0
  198. package/service/runtime/internal_jobs/bindings.js +1 -0
  199. package/service/runtime/internal_jobs/cancellation-registry.d.ts +13 -0
  200. package/service/runtime/internal_jobs/cancellation-registry.js +55 -0
  201. package/service/runtime/internal_jobs/heartbeat.d.ts +33 -0
  202. package/service/runtime/internal_jobs/heartbeat.js +65 -0
  203. package/service/runtime/internal_jobs/job-manager.d.ts +126 -0
  204. package/service/runtime/internal_jobs/job-manager.js +821 -0
  205. package/service/runtime/internal_jobs/key-coordinator.d.ts +280 -0
  206. package/service/runtime/internal_jobs/key-coordinator.js +747 -0
  207. package/service/runtime/internal_jobs/projection.d.ts +3 -0
  208. package/service/runtime/internal_jobs/projection.js +42 -0
  209. package/service/runtime/internal_jobs/runtime-worker.d.ts +126 -0
  210. package/service/runtime/internal_jobs/runtime-worker.js +454 -0
  211. package/service/runtime/internal_jobs/types.d.ts +246 -0
  212. package/service/runtime/internal_jobs/types.js +163 -0
  213. package/service/runtime/logger.d.ts +2 -0
  214. package/service/runtime/logger.js +7 -0
  215. package/service/runtime/runtime.d.ts +16 -0
  216. package/service/runtime/runtime.js +1 -0
  217. package/service/runtime/service.d.ts +372 -0
  218. package/service/runtime/service.js +1896 -0
  219. package/service/runtime/transfer/download.d.ts +27 -0
  220. package/service/runtime/transfer/download.js +1 -0
  221. package/service/runtime/transfer/protocol.d.ts +15 -0
  222. package/service/runtime/transfer/protocol.js +46 -0
  223. package/service/runtime/transfer/queue.d.ts +18 -0
  224. package/service/runtime/transfer/queue.js +136 -0
  225. package/service/runtime/transfer/upload.d.ts +40 -0
  226. package/service/runtime/transfer/upload.js +27 -0
  227. package/service/runtime/transfer.d.ts +62 -0
  228. package/service/runtime/transfer.js +763 -0
  229. package/session.d.ts +862 -0
  230. package/session.js +3407 -0
  231. package/store.d.ts +71 -0
  232. package/store.js +412 -0
  233. package/store_entry.d.ts +20 -0
  234. package/store_entry.js +75 -0
  235. package/tasks.d.ts +10 -0
  236. package/tasks.js +28 -0
  237. package/telemetry/carrier.d.ts +8 -0
  238. package/telemetry/carrier.js +20 -0
  239. package/telemetry/core.d.ts +7 -0
  240. package/telemetry/core.js +14 -0
  241. package/telemetry/env.d.ts +2 -0
  242. package/telemetry/env.js +10 -0
  243. package/telemetry/init.d.ts +2 -0
  244. package/telemetry/init.js +7 -0
  245. package/telemetry/metrics.d.ts +81 -0
  246. package/telemetry/metrics.js +267 -0
  247. package/telemetry/mod.d.ts +13 -0
  248. package/telemetry/mod.js +8 -0
  249. package/telemetry/nats.d.ts +6 -0
  250. package/telemetry/nats.js +6 -0
  251. package/telemetry/result.d.ts +1 -0
  252. package/telemetry/result.js +18 -0
  253. package/telemetry/runtime.d.ts +1 -0
  254. package/telemetry/runtime.js +141 -0
  255. package/telemetry/trace.d.ts +4 -0
  256. package/telemetry/trace.js +26 -0
  257. package/telemetry/trellis.d.ts +1 -0
  258. package/telemetry/trellis.js +1 -0
  259. package/telemetry.d.ts +1 -0
  260. package/telemetry.js +1 -0
  261. package/transfer.d.ts +112 -0
  262. package/transfer.js +525 -0
  263. package/transfer_protocol.d.ts +1 -0
  264. package/transfer_protocol.js +13 -0
@@ -0,0 +1,3 @@
1
+ import type { Job, JobEvent, JobState } from "./types.ts";
2
+ export declare function isTerminal(state: JobState): boolean;
3
+ export declare function jobFromWorkEvent<TPayload = unknown, TResult = unknown>(event: JobEvent<TPayload, TResult>): Job<TPayload, TResult> | undefined;
@@ -0,0 +1,42 @@
1
+ const TERMINAL_STATES = new Set([
2
+ "completed",
3
+ "failed",
4
+ "cancelled",
5
+ "expired",
6
+ "skipped",
7
+ "stale",
8
+ "dead",
9
+ "dismissed",
10
+ ]);
11
+ export function isTerminal(state) {
12
+ return TERMINAL_STATES.has(state);
13
+ }
14
+ export function jobFromWorkEvent(event) {
15
+ switch (event.eventType) {
16
+ case "created":
17
+ case "retried":
18
+ return seedJobFromEvent(event);
19
+ default:
20
+ return undefined;
21
+ }
22
+ }
23
+ function seedJobFromEvent(event) {
24
+ if (event.payload === undefined) {
25
+ return undefined;
26
+ }
27
+ return {
28
+ id: event.jobId,
29
+ service: event.service,
30
+ type: event.jobType,
31
+ state: event.state,
32
+ context: event.context,
33
+ payload: event.payload,
34
+ createdAt: event.timestamp,
35
+ updatedAt: event.timestamp,
36
+ tries: event.tries,
37
+ maxTries: event.maxTries ?? 1,
38
+ ...(event.deadline !== undefined ? { deadline: event.deadline } : {}),
39
+ ...(event.trigger !== undefined ? { trigger: event.trigger } : {}),
40
+ ...(event.lineage !== undefined ? { lineage: event.lineage } : {}),
41
+ };
42
+ }
@@ -0,0 +1,126 @@
1
+ import type { NatsConnection } from "@nats-io/nats-core";
2
+ import type { JobsQueueBinding, JobsRuntimeBinding } from "./bindings.ts";
3
+ import type { ActiveJob, JobProcessOutcome } from "./job-manager.ts";
4
+ import { JobCancellationToken, type JobManager } from "./job-manager.ts";
5
+ import type { Job, JobEvent } from "./types.ts";
6
+ export type WorkerAckAction = "ack" | "nak" | "await-max-deliver";
7
+ export type ProjectedWorkDecision = "process" | "skip-ack";
8
+ export type SchemaRef = {
9
+ schema: string;
10
+ };
11
+ export type PayloadValidationArgs<TResult> = {
12
+ schema?: SchemaRef;
13
+ job: Job<unknown, TResult>;
14
+ };
15
+ export type ResultValidationArgs<TResult> = {
16
+ schema?: SchemaRef;
17
+ job: Job<unknown, TResult>;
18
+ result: TResult;
19
+ };
20
+ export declare class WorkerLoopStopError extends AggregateError {
21
+ constructor(errors: unknown[]);
22
+ }
23
+ export declare class WorkerHostStopError extends AggregateError {
24
+ constructor(errors: unknown[]);
25
+ }
26
+ export declare class JobsInfrastructureMissingError extends Error {
27
+ constructor(stream: string, queueType: string);
28
+ }
29
+ type WorkMessageLike = {
30
+ data: Uint8Array;
31
+ subject: string;
32
+ info?: {
33
+ redeliveryCount?: number;
34
+ };
35
+ ack(): void | Promise<void>;
36
+ nak(delay?: number): void | Promise<void>;
37
+ inProgress(): void | Promise<void>;
38
+ };
39
+ type ConsumerMessagesLike = AsyncIterable<WorkMessageLike> & {
40
+ stop?: () => void;
41
+ close?: () => Promise<void | Error> | void;
42
+ };
43
+ type WorkerConsumerLike = {
44
+ consume(): Promise<ConsumerMessagesLike>;
45
+ };
46
+ type CancelMessageLike = {
47
+ subject: string;
48
+ data: Uint8Array;
49
+ };
50
+ type CancelSubscriptionLike = AsyncIterable<CancelMessageLike> & {
51
+ unsubscribe(): void;
52
+ };
53
+ type ConsumerInfoLike = unknown;
54
+ type StartNatsConsumerDeps = {
55
+ nats: Pick<NatsConnection, "subscribe">;
56
+ jsm: {
57
+ consumers: {
58
+ info(stream: string, consumer: string): Promise<ConsumerInfoLike>;
59
+ };
60
+ direct?: DirectMessageReader;
61
+ };
62
+ js: {
63
+ consumers: {
64
+ getConsumerFromInfo(info: ConsumerInfoLike): WorkerConsumerLike;
65
+ };
66
+ };
67
+ };
68
+ type DirectMessageReader = {
69
+ getMessage(stream: string, query: {
70
+ last_by_subj: string;
71
+ }): Promise<{
72
+ data: Uint8Array;
73
+ } | null>;
74
+ };
75
+ type StartNatsConnectionDeps = {
76
+ nats: NatsConnection;
77
+ jsm?: undefined;
78
+ js?: undefined;
79
+ };
80
+ type StartNatsRuntimeDeps = StartNatsConsumerDeps | StartNatsConnectionDeps;
81
+ type StartNatsWorkerHostOptions<TResult> = StartNatsRuntimeDeps & {
82
+ instanceId: string;
83
+ queueTypes?: string[];
84
+ queueConcurrency?: Record<string, number>;
85
+ heartbeatPublisher?: {
86
+ publish(subject: string, payload: Uint8Array): void | Promise<void>;
87
+ };
88
+ heartbeatIntervalMs?: number;
89
+ version?: string;
90
+ nowIso?: () => string;
91
+ manager: JobManager<unknown, TResult>;
92
+ getProjectedJob?: (job: Job<unknown, TResult>) => Promise<Job<unknown, TResult> | undefined>;
93
+ getLatestLifecycleEvent?: (job: Job<unknown, TResult>) => Promise<JobEvent | undefined>;
94
+ validatePayload?: (args: PayloadValidationArgs<TResult>) => Promise<void> | void;
95
+ validateResult?: (args: ResultValidationArgs<TResult>) => Promise<void> | void;
96
+ handler: (job: ActiveJob<unknown, TResult>) => Promise<TResult>;
97
+ };
98
+ type StartQueueWorkerLoopOptions<TResult> = {
99
+ manager: JobManager<unknown, TResult>;
100
+ consumer: WorkerConsumerLike;
101
+ cancelSubscription: CancelSubscriptionLike;
102
+ hostCancellation?: JobCancellationToken;
103
+ getProjectedJob?: (job: Job<unknown, TResult>) => Promise<Job<unknown, TResult> | undefined>;
104
+ getLatestLifecycleEvent?: (job: Job<unknown, TResult>) => Promise<JobEvent | undefined>;
105
+ payloadSchema?: SchemaRef;
106
+ validatePayload?: (args: PayloadValidationArgs<TResult>) => Promise<void> | void;
107
+ resultSchema?: SchemaRef;
108
+ validateResult?: (args: ResultValidationArgs<TResult>) => Promise<void> | void;
109
+ handler: (job: ActiveJob<unknown, TResult>) => Promise<TResult>;
110
+ instanceId?: string;
111
+ deferralBackoffMs?: number;
112
+ backoffMs?: number[];
113
+ progressAckIntervalMs?: number;
114
+ };
115
+ export declare function projectedWorkDecision(projected: Job | undefined, _work: Job): ProjectedWorkDecision;
116
+ export declare function lifecycleWorkDecision(latest: JobEvent | undefined): ProjectedWorkDecision;
117
+ export declare function ackActionForOutcome(outcome: JobProcessOutcome<unknown> | undefined, maxDeliver?: number): WorkerAckAction;
118
+ export declare function startQueueWorkerLoop<TResult>(options: StartQueueWorkerLoopOptions<TResult>): Promise<{
119
+ stop(): Promise<void>;
120
+ }>;
121
+ export declare function startNatsWorkerHostFromBinding<TResult>(binding: JobsRuntimeBinding, options: StartNatsWorkerHostOptions<TResult>): Promise<{
122
+ workerCount(): number;
123
+ stop(): Promise<void>;
124
+ }>;
125
+ export declare function progressAckIntervalMs(queue: JobsQueueBinding): number;
126
+ export {};
@@ -0,0 +1,454 @@
1
+ import { jetstream, jetstreamManager } from "@nats-io/jetstream";
2
+ import { recordTrellisError } from "../../../telemetry/mod.js";
3
+ import { ActiveJobCancellationRegistry } from "./cancellation-registry.js";
4
+ import { startWorkerHeartbeatLoop } from "./heartbeat.js";
5
+ import { JobCancellationToken, JobProcessError, } from "./job-manager.js";
6
+ import { isTerminal, jobFromWorkEvent } from "./projection.js";
7
+ export class WorkerLoopStopError extends AggregateError {
8
+ constructor(errors) {
9
+ super(errors, "queue worker loop failed");
10
+ this.name = "WorkerLoopStopError";
11
+ }
12
+ }
13
+ export class WorkerHostStopError extends AggregateError {
14
+ constructor(errors) {
15
+ super(errors, "worker host stop failed");
16
+ this.name = "WorkerHostStopError";
17
+ }
18
+ }
19
+ export class JobsInfrastructureMissingError extends Error {
20
+ constructor(stream, queueType) {
21
+ super(`Jobs work stream '${stream}' was not found while starting queue '${queueType}'. ` +
22
+ "The built-in Trellis jobs infrastructure is missing or not provisioned for this environment. " +
23
+ `Start Trellis and bootstrap the service again so '${stream}' exists before workers start.`);
24
+ this.name = "JobsInfrastructureMissingError";
25
+ }
26
+ }
27
+ function isCustomNatsRuntimeDeps(args) {
28
+ return args.jsm !== undefined && args.js !== undefined;
29
+ }
30
+ function toWorkerConsumer(consumer) {
31
+ return {
32
+ async consume() {
33
+ const messages = await consumer.consume();
34
+ return {
35
+ stop: messages.stop?.bind(messages),
36
+ close: messages.close?.bind(messages),
37
+ async *[Symbol.asyncIterator]() {
38
+ for await (const msg of messages) {
39
+ yield {
40
+ data: msg.data,
41
+ subject: msg.subject,
42
+ info: {
43
+ redeliveryCount: Math.max(0, msg.info.deliveryCount - 1),
44
+ },
45
+ ack: msg.ack.bind(msg),
46
+ nak: msg.nak.bind(msg),
47
+ inProgress: msg.working.bind(msg),
48
+ };
49
+ }
50
+ },
51
+ };
52
+ },
53
+ };
54
+ }
55
+ export function projectedWorkDecision(projected, _work) {
56
+ if (!projected) {
57
+ return "process";
58
+ }
59
+ return isTerminal(projected.state) ? "skip-ack" : "process";
60
+ }
61
+ export function lifecycleWorkDecision(latest) {
62
+ if (!latest) {
63
+ return "process";
64
+ }
65
+ return isTerminal(latest.state) ? "skip-ack" : "process";
66
+ }
67
+ export function ackActionForOutcome(outcome, maxDeliver = Number.MAX_SAFE_INTEGER) {
68
+ if (!outcome) {
69
+ return "ack";
70
+ }
71
+ switch (outcome.outcome) {
72
+ case "retry":
73
+ return outcome.tries >= maxDeliver ? "await-max-deliver" : "nak";
74
+ case "interrupted":
75
+ case "deferred":
76
+ return "nak";
77
+ default:
78
+ return "ack";
79
+ }
80
+ }
81
+ async function cleanupTerminalKeyState(manager, job) {
82
+ try {
83
+ await manager.cleanupQueuedKeyedJob(job);
84
+ }
85
+ catch (error) {
86
+ recordTrellisError(error, {
87
+ surface: "job",
88
+ direction: "worker",
89
+ phase: "terminal_key_cleanup",
90
+ messagingSystem: "nats",
91
+ });
92
+ }
93
+ }
94
+ export async function startQueueWorkerLoop(options) {
95
+ const registry = new ActiveJobCancellationRegistry();
96
+ const activeTokens = new Set();
97
+ const messages = await options.consumer.consume();
98
+ const hostCancellation = options.hostCancellation;
99
+ const stopConsuming = () => {
100
+ if (typeof messages.stop === "function") {
101
+ messages.stop();
102
+ }
103
+ if (typeof messages.close === "function") {
104
+ void messages.close();
105
+ }
106
+ };
107
+ const cancelActiveForShutdown = () => {
108
+ for (const token of activeTokens) {
109
+ token.cancelForShutdown();
110
+ }
111
+ };
112
+ const hostAbortHandler = () => {
113
+ cancelActiveForShutdown();
114
+ stopConsuming();
115
+ };
116
+ hostCancellation?.signal.addEventListener("abort", hostAbortHandler);
117
+ if (hostCancellation?.signal.aborted) {
118
+ hostAbortHandler();
119
+ }
120
+ const workTask = (async () => {
121
+ for await (const msg of messages) {
122
+ try {
123
+ const event = parseWorkPayloadEvent(msg.data);
124
+ if (!event) {
125
+ await msg.ack();
126
+ continue;
127
+ }
128
+ const job = jobFromWorkEvent(event);
129
+ if (!job) {
130
+ await msg.ack();
131
+ continue;
132
+ }
133
+ const key = `${job.service}.${job.type}.${job.id}`;
134
+ if (hostCancellation?.isHostShutdown()) {
135
+ await msg.nak();
136
+ continue;
137
+ }
138
+ const latestLifecycle = options.getLatestLifecycleEvent
139
+ ? await options.getLatestLifecycleEvent(job)
140
+ : undefined;
141
+ if (hostCancellation?.isHostShutdown()) {
142
+ await msg.nak();
143
+ continue;
144
+ }
145
+ if (lifecycleWorkDecision(latestLifecycle) === "skip-ack") {
146
+ await cleanupTerminalKeyState(options.manager, job);
147
+ registry.clearPending(key);
148
+ await msg.ack();
149
+ continue;
150
+ }
151
+ if (!latestLifecycle) {
152
+ const projected = options.getProjectedJob
153
+ ? await options.getProjectedJob(job)
154
+ : undefined;
155
+ if (hostCancellation?.isHostShutdown()) {
156
+ await msg.nak();
157
+ continue;
158
+ }
159
+ if (projectedWorkDecision(projected, job) === "skip-ack") {
160
+ await cleanupTerminalKeyState(options.manager, job);
161
+ registry.clearPending(key);
162
+ await msg.ack();
163
+ continue;
164
+ }
165
+ }
166
+ const token = new JobCancellationToken();
167
+ if (hostCancellation?.isHostShutdown()) {
168
+ token.cancelForShutdown();
169
+ }
170
+ activeTokens.add(token);
171
+ const guard = registry.register(key, token);
172
+ try {
173
+ const currentJob = latestLifecycle
174
+ ? {
175
+ ...job,
176
+ state: latestLifecycle.state,
177
+ tries: latestLifecycle.tries,
178
+ }
179
+ : job;
180
+ let outcome;
181
+ do {
182
+ outcome = await options.manager.processWithHeartbeat(currentJob, token, async () => {
183
+ await msg.inProgress();
184
+ }, async (activeJob) => {
185
+ try {
186
+ await options.validatePayload?.({
187
+ schema: options.payloadSchema,
188
+ job: activeJob.job(),
189
+ });
190
+ }
191
+ catch (error) {
192
+ throw JobProcessError.failed(error instanceof Error ? error.message : String(error));
193
+ }
194
+ return await options.handler(activeJob);
195
+ }, {
196
+ latestState: latestLifecycle?.state,
197
+ workEventType: event.eventType,
198
+ redeliveryCount: msg.info?.redeliveryCount,
199
+ instanceId: options.instanceId,
200
+ progressAckIntervalMs: options.progressAckIntervalMs,
201
+ }, {
202
+ validateResult: options.validateResult
203
+ ? (result, resultJob) => options.validateResult({
204
+ schema: options.resultSchema,
205
+ result,
206
+ job: resultJob,
207
+ })
208
+ : undefined,
209
+ });
210
+ if (outcome.outcome === "deferred") {
211
+ await msg.inProgress();
212
+ await new Promise((resolve) => setTimeout(resolve, options.progressAckIntervalMs ?? 1_000));
213
+ }
214
+ } while (outcome.outcome === "deferred" && !token.isCancelled());
215
+ const ackAction = ackActionForOutcome(outcome, job.maxTries);
216
+ if (ackAction === "ack") {
217
+ await msg.ack();
218
+ }
219
+ else if (ackAction === "await-max-deliver") {
220
+ continue;
221
+ }
222
+ else if (outcome?.outcome === "deferred") {
223
+ await msg.nak(options.deferralBackoffMs ?? 1_000);
224
+ }
225
+ else {
226
+ await msg.nak(retryDelayMs(outcome?.tries ?? 1, options.backoffMs));
227
+ }
228
+ }
229
+ finally {
230
+ guard.dispose();
231
+ activeTokens.delete(token);
232
+ }
233
+ }
234
+ catch (error) {
235
+ recordTrellisError(error, {
236
+ surface: "job",
237
+ direction: "worker",
238
+ phase: "queue_loop",
239
+ messagingSystem: "nats",
240
+ });
241
+ try {
242
+ await msg.nak(options.deferralBackoffMs ?? 1_000);
243
+ }
244
+ catch (nakError) {
245
+ recordTrellisError(nakError, {
246
+ surface: "job",
247
+ direction: "worker",
248
+ phase: "queue_loop_nak",
249
+ messagingSystem: "nats",
250
+ });
251
+ }
252
+ }
253
+ }
254
+ })();
255
+ let workFailure;
256
+ const observedWorkTask = workTask.catch((error) => {
257
+ workFailure = error;
258
+ });
259
+ const cancelTask = (async () => {
260
+ for await (const msg of options.cancelSubscription) {
261
+ const event = parseWorkPayloadEvent(msg.data);
262
+ if (!event || event.eventType !== "cancelled") {
263
+ continue;
264
+ }
265
+ registry.cancel(`${event.service}.${event.jobType}.${event.jobId}`);
266
+ }
267
+ })();
268
+ let cancelFailure;
269
+ const observedCancelTask = cancelTask.catch((error) => {
270
+ cancelFailure = error;
271
+ });
272
+ return {
273
+ async stop() {
274
+ options.cancelSubscription.unsubscribe();
275
+ cancelActiveForShutdown();
276
+ stopConsuming();
277
+ await Promise.all([observedWorkTask, observedCancelTask]);
278
+ hostCancellation?.signal.removeEventListener("abort", hostAbortHandler);
279
+ const failures = [workFailure, cancelFailure].filter((error) => error !== undefined);
280
+ if (failures.length > 0) {
281
+ throw new WorkerLoopStopError(failures);
282
+ }
283
+ },
284
+ };
285
+ }
286
+ export async function startNatsWorkerHostFromBinding(binding, options) {
287
+ const queueTypes = options.queueTypes ??
288
+ Object.keys(binding.jobs.queues).sort();
289
+ const queueConcurrency = {};
290
+ for (const queueType of queueTypes) {
291
+ const queue = binding.jobs.queues[queueType];
292
+ if (!queue) {
293
+ throw new Error(`Requested worker queue binding '${queueType}' is missing`);
294
+ }
295
+ progressAckIntervalMs(queue);
296
+ const concurrency = options.queueConcurrency?.[queueType] ?? 1;
297
+ if (!Number.isInteger(concurrency) || concurrency < 1) {
298
+ throw new Error(`Worker queue '${queueType}' has invalid concurrency ${concurrency}; expected a positive integer`);
299
+ }
300
+ queueConcurrency[queueType] = concurrency;
301
+ }
302
+ const cancellation = new JobCancellationToken();
303
+ const heartbeatLoops = options.heartbeatPublisher
304
+ ? await Promise.all(queueTypes.map((queueType) => {
305
+ const queue = binding.jobs.queues[queueType];
306
+ if (!queue) {
307
+ throw new Error(`Worker queue '${queueType}' is not configured`);
308
+ }
309
+ return startWorkerHeartbeatLoop({
310
+ publisher: options.heartbeatPublisher,
311
+ service: binding.jobs.serviceName,
312
+ subjectService: binding.jobs.namespace,
313
+ jobType: queueType,
314
+ instanceId: options.instanceId,
315
+ concurrency: queueConcurrency[queueType],
316
+ version: options.version,
317
+ intervalMs: options.heartbeatIntervalMs,
318
+ nowIso: options.nowIso,
319
+ });
320
+ }))
321
+ : [];
322
+ const workers = [];
323
+ for (const queueType of queueTypes) {
324
+ const queue = getQueueBinding(binding, queueType);
325
+ for (let workerIndex = 0; workerIndex < queueConcurrency[queueType]; workerIndex += 1) {
326
+ const jsm = isCustomNatsRuntimeDeps(options)
327
+ ? options.jsm
328
+ : await jetstreamManager(options.nats);
329
+ const js = isCustomNatsRuntimeDeps(options) ? options.js : {
330
+ consumers: {
331
+ getConsumerFromInfo(info) {
332
+ return toWorkerConsumer(jetstream(options.nats).consumers.getConsumerFromInfo(info));
333
+ },
334
+ },
335
+ };
336
+ const info = await getConsumerInfo(jsm, binding.workStream, queue);
337
+ const consumer = js.consumers.getConsumerFromInfo(info);
338
+ const cancelSubscription = options.nats.subscribe(`${queue.publishPrefix}.*.cancelled`);
339
+ const direct = jsm.direct;
340
+ workers.push(await startQueueWorkerLoop({
341
+ manager: options.manager,
342
+ consumer,
343
+ cancelSubscription,
344
+ hostCancellation: cancellation,
345
+ getProjectedJob: options.getProjectedJob,
346
+ getLatestLifecycleEvent: options.getLatestLifecycleEvent ??
347
+ (direct
348
+ ? (job) => getLatestLifecycleEvent(direct, "JOBS", queue.publishPrefix, job)
349
+ : undefined),
350
+ payloadSchema: queue.payload,
351
+ validatePayload: options.validatePayload,
352
+ resultSchema: queue.result,
353
+ validateResult: options.validateResult,
354
+ handler: options.handler,
355
+ instanceId: options.instanceId,
356
+ deferralBackoffMs: queue.backoffMs[0] ?? 1_000,
357
+ backoffMs: queue.backoffMs,
358
+ progressAckIntervalMs: progressAckIntervalMs(queue),
359
+ }));
360
+ }
361
+ }
362
+ return {
363
+ workerCount() {
364
+ return workers.length;
365
+ },
366
+ async stop() {
367
+ cancellation.cancelForShutdown();
368
+ const results = await Promise.allSettled([
369
+ ...workers.map((worker) => worker.stop()),
370
+ ...heartbeatLoops.map((loop) => loop.stop()),
371
+ ]);
372
+ const failures = results
373
+ .filter((result) => result.status === "rejected")
374
+ .map((result) => result.reason);
375
+ if (failures.length > 0) {
376
+ throw new WorkerHostStopError(failures);
377
+ }
378
+ },
379
+ };
380
+ }
381
+ function retryDelayMs(delivery, configured) {
382
+ const schedule = configured?.length
383
+ ? configured
384
+ : [5_000, 30_000, 120_000, 600_000];
385
+ return schedule[Math.min(Math.max(0, delivery - 1), schedule.length - 1)];
386
+ }
387
+ export function progressAckIntervalMs(queue) {
388
+ const wait = queue.backoffMs.length > 0
389
+ ? Math.min(...queue.backoffMs)
390
+ : queue.ackWaitMs;
391
+ if (!Number.isInteger(wait) || wait < 1) {
392
+ throw new Error(`Worker queue '${queue.queueType}' has invalid acknowledgement wait ${wait}ms; expected a positive whole millisecond`);
393
+ }
394
+ return Math.max(1, Math.floor(wait / 3));
395
+ }
396
+ async function getConsumerInfo(jsm, stream, queue) {
397
+ try {
398
+ return await jsm.consumers.info(stream, queue.consumerName);
399
+ }
400
+ catch (error) {
401
+ if (isStreamNotFoundError(error) || isConsumerNotFoundError(error)) {
402
+ throw new JobsInfrastructureMissingError(stream, queue.queueType);
403
+ }
404
+ throw error;
405
+ }
406
+ }
407
+ function isStreamNotFoundError(error) {
408
+ return error instanceof Error && (error.name === "StreamNotFoundError" ||
409
+ error.message.includes("stream not found"));
410
+ }
411
+ function isConsumerNotFoundError(error) {
412
+ return error instanceof Error && (error.name === "ConsumerNotFoundError" ||
413
+ error.message.includes("consumer not found"));
414
+ }
415
+ function getQueueBinding(binding, queueType) {
416
+ const queue = binding.jobs.queues[queueType];
417
+ if (!queue) {
418
+ throw new Error(`Requested worker queue binding '${queueType}' is missing`);
419
+ }
420
+ return queue;
421
+ }
422
+ async function getLatestLifecycleEvent(direct, stream, publishPrefix, job) {
423
+ try {
424
+ const msg = await direct.getMessage(stream, {
425
+ last_by_subj: `${publishPrefix}.${job.id}.*`,
426
+ });
427
+ if (!msg) {
428
+ return undefined;
429
+ }
430
+ return parseWorkPayloadEvent(msg.data);
431
+ }
432
+ catch (error) {
433
+ if (isMessageNotFoundError(error)) {
434
+ return undefined;
435
+ }
436
+ if (isStreamNotFoundError(error)) {
437
+ throw new JobsInfrastructureMissingError(stream, job.type);
438
+ }
439
+ throw error;
440
+ }
441
+ }
442
+ function isMessageNotFoundError(error) {
443
+ return error instanceof Error && (error.name === "MessageNotFoundError" ||
444
+ error.message.includes("message not found") ||
445
+ error.message.includes("no message found"));
446
+ }
447
+ function parseWorkPayloadEvent(payload) {
448
+ try {
449
+ return JSON.parse(new TextDecoder().decode(payload));
450
+ }
451
+ catch {
452
+ return undefined;
453
+ }
454
+ }