@aniket-lodh/veyra-sdk 0.1.1 → 0.2.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 (50) hide show
  1. package/README.md +205 -116
  2. package/dist/cjs/client.d.ts +204 -0
  3. package/dist/cjs/client.js +647 -0
  4. package/dist/cjs/errors.d.ts +147 -0
  5. package/dist/cjs/errors.js +262 -0
  6. package/dist/cjs/handlers.d.ts +165 -0
  7. package/dist/cjs/handlers.js +46 -0
  8. package/dist/cjs/index.d.ts +15 -0
  9. package/dist/cjs/index.js +37 -0
  10. package/dist/cjs/package.json +3 -0
  11. package/dist/cjs/standard-schema.d.ts +86 -0
  12. package/dist/cjs/standard-schema.js +49 -0
  13. package/dist/cjs/types.d.ts +430 -0
  14. package/dist/cjs/types.js +6 -0
  15. package/dist/cjs/webhook.d.ts +98 -0
  16. package/dist/cjs/webhook.js +165 -0
  17. package/dist/cjs/worker.d.ts +101 -0
  18. package/dist/cjs/worker.js +497 -0
  19. package/dist/client.d.ts +159 -25
  20. package/dist/client.js +501 -122
  21. package/dist/errors.d.ts +123 -10
  22. package/dist/errors.js +192 -19
  23. package/dist/handlers.d.ts +165 -0
  24. package/dist/handlers.js +42 -0
  25. package/dist/index.d.ts +13 -6
  26. package/dist/index.js +12 -6
  27. package/dist/standard-schema.d.ts +86 -0
  28. package/dist/standard-schema.js +45 -0
  29. package/dist/types.d.ts +281 -36
  30. package/dist/types.js +2 -2
  31. package/dist/webhook.d.ts +98 -0
  32. package/dist/webhook.js +128 -0
  33. package/dist/worker.d.ts +80 -55
  34. package/dist/worker.js +308 -192
  35. package/package.json +21 -12
  36. package/dist/client.d.ts.map +0 -1
  37. package/dist/client.js.map +0 -1
  38. package/dist/errors.d.ts.map +0 -1
  39. package/dist/errors.js.map +0 -1
  40. package/dist/index.d.ts.map +0 -1
  41. package/dist/index.js.map +0 -1
  42. package/dist/types.d.ts.map +0 -1
  43. package/dist/types.js.map +0 -1
  44. package/dist/worker.d.ts.map +0 -1
  45. package/dist/worker.js.map +0 -1
  46. package/src/client.ts +0 -389
  47. package/src/errors.ts +0 -82
  48. package/src/index.ts +0 -8
  49. package/src/types.ts +0 -217
  50. package/src/worker.ts +0 -469
package/README.md CHANGED
@@ -2,18 +2,18 @@
2
2
 
3
3
  Lightweight, zero-dependency TypeScript & Node.js SDK for the [Veyra](https://github.com/Aniket-lodh/veyra) Distributed Execution Platform.
4
4
 
5
- Built directly on top of Veyra's REST API and HTTP Worker Protocol. Uses native web and Node 18+ standards (`fetch`, `AbortController`, `crypto`). No native binary bindings or direct database connections required.
5
+ Built on Veyra's REST API and HTTP worker protocol using only native web and Node 18+ standards (`fetch`, `AbortController`, Web Crypto). No runtime dependencies, no native bindings, no direct database access.
6
6
 
7
7
  ---
8
8
 
9
9
  ## Features
10
10
 
11
- - **Client Methods:** `enqueue()`, `getJob()`, `cancelJob()`, `retryJob()`
12
- - **Robust Worker Engine:** Automatic worker registration, background heartbeats, empty queue backoff (`204 No Content`), and transparent `404` recovery/re-registration.
13
- - **Concurrency & Leases:** Tunable concurrency pool, automatic periodic lease renewals during execution, and instant lease termination with `AbortSignal` triggering on `409 Conflict` (lease expired or reclaimed).
14
- - **Completion Webhooks & HMAC Verification:** Supports enqueueing jobs with `callbackUrl` and provides guidance/helpers for verifying HMAC-SHA256 signatures (`X-Veyra-Signature`).
15
- - **Failures & Dead-Lettering:** Automatic error formatting, stack trace capture, and immediate dead-lettering via `NonRetryableError`.
16
- - **Graceful Shutdown:** Drains in-flight jobs within a configurable timeout, cancels timers, and cleanly deregisters from the fleet.
11
+ - **End-to-end types:** built-in handler payloads/results, custom `defineHandler` contracts, and typed enqueue → retrieve → execute → webhook flows.
12
+ - **Standard Schema validation:** works with Zod, Valibot, ArkType, or any Standard Schema v1 library. `staticSchema<T>()` gives the same types with zero runtime validation.
13
+ - **Robust worker engine:** registration, heartbeats, `204` backoff, and transparent `404` re-registration.
14
+ - **Leases:** automatic renewal, `AbortSignal` on `409` lease loss, and graceful drain.
15
+ - **Typed webhooks:** HMAC-SHA256 verification and result validation for `callbackUrl` deliveries.
16
+ - **Backwards compatible:** existing string-based `enqueue` and `registerHandler` calls keep working.
17
17
 
18
18
  ---
19
19
 
@@ -23,177 +23,266 @@ Built directly on top of Veyra's REST API and HTTP Worker Protocol. Uses native
23
23
  npm install @aniket-lodh/veyra-sdk
24
24
  # or
25
25
  pnpm add @aniket-lodh/veyra-sdk
26
- # or
27
- yarn add @aniket-lodh/veyra-sdk
28
26
  ```
29
27
 
30
- ---
28
+ The package ships both module formats from one install: `import` resolves to the ESM build, `require` resolves to the CommonJS build, and each entry point carries its own type declarations. Node 18+ is required.
31
29
 
32
- ## Client Usage
30
+ ```ts
31
+ // ESM
32
+ import { VeyraClient, defineHandler } from '@aniket-lodh/veyra-sdk';
33
33
 
34
- ### 1. Initialize Client & Enqueue a Job
34
+ // CommonJS
35
+ const { VeyraClient, defineHandler } = require('@aniket-lodh/veyra-sdk');
36
+ ```
37
+
38
+ ---
35
39
 
36
- ```typescript
40
+ ## Client
41
+
42
+ ```ts
37
43
  import { VeyraClient } from '@aniket-lodh/veyra-sdk';
38
44
 
39
45
  const client = new VeyraClient({
40
- baseUrl: process.env.VEYRA_API_URL || 'http://localhost:8080',
41
- apiKey: process.env.VEYRA_API_KEY || 'veyra_...',
46
+ baseUrl: process.env.VEYRA_API_URL ?? 'http://localhost:8008',
47
+ apiKey: process.env.VEYRA_API_KEY ?? 'veyra_...',
42
48
  defaultQueue: 'default',
43
49
  });
50
+ ```
51
+
52
+ ### Built-in handlers
53
+
54
+ The Go worker ships `http_request`, `send_email`. Their payloads and results are typed automatically:
44
55
 
45
- // Enqueue a job with priority, backoff, and completion webhook
56
+ ```ts
46
57
  const job = await client.enqueue({
47
- queue: 'default',
48
- handler: 'sync_inventory',
58
+ handler: 'http_request',
49
59
  payload: {
50
- sku: 'SKU-8921',
51
- warehouseId: 'wh_west_1',
52
- quantity: 140,
60
+ url: 'https://api.example.com/sync',
61
+ method: 'POST',
62
+ headers: { 'Content-Type': 'application/json' },
63
+ body: { sku: 'SKU-8921' },
64
+ timeoutSeconds: 15,
53
65
  },
54
- priority: 7, // 0 (lowest) to 9 (highest)
55
- maxAttempts: 3,
56
- backoff: {
57
- kind: 'exponential',
58
- baseSeconds: 30,
59
- capSeconds: 3600,
60
- },
61
- idempotencyKey: 'inv-sync-2026-11-20-001',
62
- callbackUrl: 'https://api.example.com/webhooks/veyra-completion',
63
66
  });
64
67
 
65
- console.log('Enqueued job:', job.id, job.status);
68
+ // job is Job<HttpRequestPayload, HttpRequestResult>
69
+ console.log(job.result?.statusCode, job.result?.durationMs);
66
70
  ```
67
71
 
68
- ### 2. Inspect, Cancel, or Retry Jobs
69
-
70
- ```typescript
71
- // Fetch job status and attempt history
72
- const job = await client.getJob('job_01JC...XYZ');
72
+ ```ts
73
+ await client.enqueue({
74
+ handler: 'send_email',
75
+ payload: {
76
+ to: 'user@example.com',
77
+ subject: 'Welcome',
78
+ text: 'Thanks for signing up.',
79
+ },
80
+ });
81
+ ```
73
82
 
74
- // Cancel an active or queued job
75
- await client.cancelJob('job_01JC...XYZ');
83
+ ### Inspect, cancel, retry
76
84
 
77
- // Retry a failed, cancelled, or dead-lettered job
78
- await client.retryJob('job_01JC...XYZ');
85
+ ```ts
86
+ const job = await client.getJob('01JC...XYZ');
87
+ await client.cancelJob('01JC...XYZ');
88
+ await client.retryJob('01JC...XYZ');
79
89
  ```
80
90
 
81
91
  ---
82
92
 
83
- ## Distributed Worker Usage
93
+ ## Typed custom handlers
84
94
 
85
- ### Running Custom Handlers with Concurrency & Leases
95
+ Define a handler once and reuse it on producers, workers, and webhook consumers.
86
96
 
87
- ```typescript
88
- import { VeyraClient, NonRetryableError } from '@aniket-lodh/veyra-sdk';
97
+ ### Compile-time only (`staticSchema`)
89
98
 
90
- const client = new VeyraClient({
91
- baseUrl: process.env.VEYRA_API_URL || 'http://localhost:8080',
92
- apiKey: process.env.VEYRA_API_KEY || 'veyra_...',
99
+ ```ts
100
+ import { defineHandler, staticSchema } from '@aniket-lodh/veyra-sdk';
101
+
102
+ const sendEmail = defineHandler({
103
+ name: 'send_email',
104
+ queue: 'emails',
105
+ payload: staticSchema<{ to: string; subject: string }>(),
106
+ result: staticSchema<{ messageId: string }>(),
93
107
  });
94
108
 
95
- // Create managed worker
96
- const worker = client.createWorker({
97
- queues: ['default', 'inventory'],
98
- concurrency: 5, // Concurrent jobs executed in parallel
99
- pollIntervalMs: 1_000, // Backoff when queue is empty (204 No Content)
100
- heartbeatIntervalMs: 10_000, // Worker health heartbeat
101
- leaseHeartbeatIntervalMs: 10_000, // In-flight lease renewal cadence
109
+ // Producer: payload is checked, result is typed.
110
+ const job = await client.enqueue(sendEmail, {
111
+ to: 'user@example.com',
112
+ subject: 'Welcome',
102
113
  });
114
+ // Or using the object form:
115
+ // await client.enqueue({ handler: sendEmail, payload: { to: 'user@example.com', subject: 'Welcome' } });
116
+ job.result?.messageId; // string | null
117
+ ```
103
118
 
104
- // Register custom handler
105
- worker.registerHandler('sync_inventory', async (job, ctx) => {
106
- console.log(`Processing job ${job.id} (attempt ${ctx.attempt})`);
119
+ ### Runtime validation (Standard Schema / Zod)
107
120
 
108
- // Check abort signal: aborted if another worker reclaimed or lease expired
109
- if (ctx.signal.aborted) {
110
- throw new Error('Execution aborted: lease lost or expired');
111
- }
121
+ ```ts
122
+ import { z } from 'zod';
123
+ import { defineHandler } from '@aniket-lodh/veyra-sdk';
112
124
 
113
- const { sku, quantity } = job.payload as { sku: string; quantity: number };
125
+ const sendEmail = defineHandler({
126
+ name: 'send_email',
127
+ queue: 'emails',
128
+ payload: z.object({ to: z.string().email(), subject: z.string() }),
129
+ result: z.object({ messageId: z.string() }),
130
+ });
114
131
 
115
- if (!sku) {
116
- // Throw NonRetryableError to dead-letter immediately without retries
117
- throw new NonRetryableError('SKU is required');
118
- }
132
+ // Invalid payloads throw VeyraValidationError before the HTTP request.
133
+ await client.enqueue(sendEmail, { to: 'not-an-email', subject: 'Hi' });
134
+ ```
135
+
136
+ ### Minimal typing without schemas
119
137
 
120
- // Execute task...
121
- return { updated: true, sku, quantity, processedAt: new Date().toISOString() };
138
+ ```ts
139
+ const syncInventory = defineHandler<{ sku: string; quantity: number }, { updated: boolean }>({
140
+ name: 'sync_inventory',
141
+ });
142
+ ```
143
+
144
+ ---
145
+
146
+ ## Worker
147
+
148
+ ```ts
149
+ import { VeyraClient, NonRetryableError } from '@aniket-lodh/veyra-sdk';
150
+
151
+ const client = new VeyraClient({ baseUrl, apiKey });
152
+ const worker = client.createWorker({
153
+ queues: ['default', 'emails'],
154
+ concurrency: 5,
155
+ pollIntervalMs: 1_000,
156
+ heartbeatIntervalMs: 10_000,
157
+ leaseHeartbeatIntervalMs: 10_000,
158
+ });
159
+
160
+ worker.register(sendEmail, async (job, ctx) => {
161
+ // job.payload is { to: string; subject: string }
162
+ if (ctx.signal.aborted) throw new Error('lease lost');
163
+ if (!job.payload.to) throw new NonRetryableError('missing recipient');
164
+
165
+ return { messageId: await deliver(job.payload) }; // must satisfy { messageId: string }
122
166
  });
123
167
 
124
- // Start claiming and processing jobs
125
168
  await worker.start();
126
- console.log(`Worker ${worker.workerId} active and polling...`);
127
169
 
128
- // Handle graceful shutdown
129
- const shutdown = async () => {
130
- console.log('Draining worker and shutting down...');
170
+ process.on('SIGINT', async () => {
131
171
  await worker.stop({ timeoutMs: 15_000 });
132
172
  process.exit(0);
133
- };
173
+ });
174
+ ```
175
+
176
+ - Payload schemas run before the callback; result schemas run before completion is reported.
177
+ - Both failures raise `VeyraValidationError` (permanent, dead-lettered immediately).
178
+ - String registration remains available: `worker.register('send_invoice', async (job) => ...)` or `worker.registerHandler(...)`.
179
+
180
+ ---
181
+
182
+ ## Shared handler registry
183
+
184
+ When producer and consumer live in different services, type the client/worker once:
185
+
186
+ ```ts
187
+ import { VeyraClient, VeyraWorker } from '@aniket-lodh/veyra-sdk';
188
+
189
+ interface MyHandlers {
190
+ send_email: {
191
+ payload: { to: string; subject: string };
192
+ result: { messageId: string };
193
+ };
194
+ }
195
+
196
+ const client = new VeyraClient<MyHandlers>({ baseUrl, apiKey });
197
+ const job = await client.enqueue({
198
+ handler: 'send_email', // autocompletes
199
+ payload: { to: 'user@example.com', subject: 'Welcome' },
200
+ });
201
+ job.result?.messageId; // string | null
134
202
 
135
- process.on('SIGINT', shutdown);
136
- process.on('SIGTERM', shutdown);
203
+ const worker = new VeyraWorker<MyHandlers>(client, { queues: ['emails'] });
137
204
  ```
138
205
 
206
+ Built-ins are always merged in. Unknown string handler names fall back to inferred payloads and `unknown` results.
207
+
139
208
  ---
140
209
 
141
- ## Completion Webhooks & HMAC Verification
210
+ ## Completion webhooks
142
211
 
143
- When jobs are enqueued with a `callbackUrl`, Veyra delivers an HTTP POST notification upon reaching a terminal state (`succeeded`, `failed`, `dead_lettered`, or `cancelled`).
212
+ Enqueue with `callbackUrl` to receive a POST when a job reaches `succeeded`, `dead_lettered`, or `cancelled`:
144
213
 
145
- ### Webhook Headers & Payload Structure
214
+ ```ts
215
+ await client.enqueue(sendEmail, payload, {
216
+ callbackUrl: 'https://api.example.com/webhooks/veyra',
217
+ });
218
+ ```
146
219
 
147
- Veyra includes the following headers with each webhook dispatch:
220
+ Veyra signs the raw body with HMAC-SHA256 when `VEYRA_CALLBACK_SECRET` is configured:
148
221
 
149
- - `Content-Type: application/json`
150
- - `X-Veyra-Event: job.completed`
151
- - `X-Veyra-Job-Id: <job_id>`
152
- - `X-Veyra-Status: <status>`
153
- - `X-Veyra-Attempt: <attempt_number>`
154
- - `X-Veyra-Delivery-Attempt: <callback_attempt>`
155
- - `X-Veyra-Timestamp: <iso_timestamp>`
156
- - `X-Veyra-Signature: sha256=<hex_hmac>` (when `VEYRA_CALLBACK_SECRET` is configured on API)
222
+ ```
223
+ X-Veyra-Signature: sha256=<hex>
224
+ X-Veyra-Event: job.completed
225
+ X-Veyra-Job-Id: <jobId>
226
+ X-Veyra-Status: <status>
227
+ X-Veyra-Attempt: <attempt>
228
+ X-Veyra-Delivery-Attempt: <callbackAttempts>
229
+ X-Veyra-Timestamp: <RFC3339>
230
+ ```
157
231
 
158
- ### Verifying HMAC Signatures (Node.js / Express)
232
+ ### Express
159
233
 
160
- ```typescript
161
- import crypto from 'node:crypto';
234
+ ```ts
235
+ import express from 'express';
236
+ import { parseWebhook, verifyWebhookSignature } from '@aniket-lodh/veyra-sdk';
162
237
 
163
- export function verifyVeyraWebhook(
164
- rawBody: Buffer | string,
165
- signatureHeader: string | undefined,
166
- secret: string
167
- ): boolean {
168
- if (!signatureHeader || !signatureHeader.startsWith('sha256=')) {
169
- return false;
170
- }
238
+ const app = express();
171
239
 
172
- const expectedSignature = signatureHeader.slice('sha256='.length);
173
- const hmac = crypto.createHmac('sha256', secret);
174
- hmac.update(rawBody);
175
- const actualSignature = hmac.digest('hex');
240
+ app.post(
241
+ '/webhooks/veyra',
242
+ express.raw({ type: 'application/json' }),
243
+ async (req, res) => {
244
+ const rawBody = req.body as Buffer;
245
+ const signature = req.header('x-veyra-signature');
176
246
 
177
- return crypto.timingSafeEqual(
178
- Buffer.from(actualSignature, 'hex'),
179
- Buffer.from(expectedSignature, 'hex')
180
- );
181
- }
247
+ if (!(await verifyWebhookSignature(rawBody, signature, process.env.VEYRA_CALLBACK_SECRET!))) {
248
+ return res.status(401).send('invalid signature');
249
+ }
250
+
251
+ const event = await parseWebhook(rawBody, sendEmail, {
252
+ secret: process.env.VEYRA_CALLBACK_SECRET,
253
+ signature,
254
+ });
255
+
256
+ console.log(event.status, event.result?.messageId);
257
+ res.sendStatus(204);
258
+ }
259
+ );
182
260
  ```
183
261
 
262
+ Pass the exact raw request bytes. Re-serializing the JSON breaks the signature.
263
+
184
264
  ---
185
265
 
186
- ## Development & Testing
266
+ ## Error handling
187
267
 
188
- ```bash
189
- # Typecheck
190
- pnpm typecheck
268
+ | Error | Meaning |
269
+ | --- | --- |
270
+ | `VeyraApiError` | Non-2xx response; `status`, `statusText`, `body` |
271
+ | `VeyraAuthError` | `401` / `403` |
272
+ | `VeyraNotFoundError` | `404` |
273
+ | `VeyraConflictError` | `409` |
274
+ | `LeaseLostError` | `409` caused by an expired/reclaimed lease |
275
+ | `VeyraValidationError` | Standard Schema failure; `issues`, permanent |
276
+ | `NonRetryableError` | Throw from a handler to dead-letter immediately |
277
+
278
+ ---
191
279
 
192
- # Run unit tests
193
- pnpm test
280
+ ## Development
194
281
 
195
- # Build bundle and declaration files
196
- pnpm build
282
+ ```bash
283
+ pnpm typecheck # source + type-level tests
284
+ pnpm build # dist/*.js + dist/*.d.ts
285
+ pnpm test # build, typecheck tests, run unit tests
197
286
  ```
198
287
 
199
288
  ---
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Veyra HTTP client.
3
+ */
4
+ import type { BuiltInHandlers, DefinitionPayload, DefinitionResult, HandlerDefinition, HandlerName, HandlerPayload, HandlerResult, ResolvedHandlers } from './handlers.js';
5
+ import type { ClaimParams, CompleteJobResponse, DefinitionEnqueueInput, DeregisterWorkerResponse, EnqueueOptions, FailJobParams, FailJobResponse, HeartbeatResponse, Job, JobClaim, RenewLeaseResponse, RequestOptions, TypedEnqueueInput, TypedEnqueuePayload, TypedEnqueueResult, VeyraClientConfig, VeyraWorkerOptions, WorkerRecord, WorkerRegisterParams } from './types.js';
6
+ import { VeyraWorker } from './worker.js';
7
+ /**
8
+ * Typed client for the Veyra REST API.
9
+ *
10
+ * @typeParam THandlers - Extra handler contracts merged over {@link BuiltInHandlers}.
11
+ * Register handlers here to get autocomplete and payload/result checking on
12
+ * string-based `enqueue` calls shared across services.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * interface MyHandlers {
17
+ * send_email: { payload: { to: string }; result: { messageId: string } };
18
+ * }
19
+ * const client = new VeyraClient<MyHandlers>({ baseUrl, apiKey });
20
+ * const job = await client.enqueue({ handler: 'send_email', payload: { to: 'a@b.c' } });
21
+ * job.result?.messageId; // string
22
+ * ```
23
+ */
24
+ export declare class VeyraClient<THandlers extends object = BuiltInHandlers> {
25
+ #private;
26
+ /** API origin without a trailing slash. */
27
+ readonly baseUrl: string;
28
+ /** Queue used when `enqueue` omits `queue`. */
29
+ readonly defaultQueue: string;
30
+ /**
31
+ * @param config - API origin, API key, and transport settings.
32
+ * @throws {VeyraValidationError} When `baseUrl` or `apiKey` is invalid.
33
+ */
34
+ constructor(config: VeyraClientConfig);
35
+ /**
36
+ * Safe JSON representation redacting all sensitive credentials.
37
+ */
38
+ toJSON(): Record<string, unknown>;
39
+ /**
40
+ * Enqueues a job from a {@link HandlerDefinition}. The payload is validated
41
+ * against the definition's schema before the request is sent.
42
+ *
43
+ * @param handler - Definition created with `defineHandler`.
44
+ * @param payload - Payload matching the definition.
45
+ * @param options - Per-call overrides. `options.queue` wins over the definition's queue.
46
+ * @returns The created (or idempotently replayed) job.
47
+ * @throws {VeyraValidationError} When the payload fails schema validation or inputs are invalid.
48
+ *
49
+ * @example
50
+ * ```ts
51
+ * await client.enqueue(sendEmail, { to: 'a@b.c', subject: 'Hi' });
52
+ * ```
53
+ */
54
+ enqueue<TName extends string, TPayload, TResult, TQueue extends string | undefined>(handler: HandlerDefinition<TName, TPayload, TResult, TQueue>, payload: TPayload, options?: EnqueueOptions): Promise<Job<TPayload, TResult>>;
55
+ /**
56
+ * Enqueues a job using an object containing a {@link HandlerDefinition}.
57
+ * The payload is validated against the definition's schema before sending.
58
+ *
59
+ * @param input - Definition handler, payload, and optional enqueue options.
60
+ * @returns The created (or idempotently replayed) job.
61
+ * @throws {VeyraValidationError} When the payload fails schema validation or inputs are invalid.
62
+ *
63
+ * @example
64
+ * ```ts
65
+ * await client.enqueue({ handler: sendEmail, payload: { to: 'a@b.c', subject: 'Hi' } });
66
+ * ```
67
+ */
68
+ enqueue<TDefinition extends HandlerDefinition<any, any, any, any>>(input: DefinitionEnqueueInput<TDefinition>): Promise<Job<DefinitionPayload<TDefinition>, DefinitionResult<TDefinition>>>;
69
+ /**
70
+ * Enqueues a job using the object form.
71
+ *
72
+ * Known handler names (built-ins plus `THandlers`) autocomplete and constrain
73
+ * `payload` and type `result`; unknown string names fall back to the supplied generics.
74
+ *
75
+ * @param input - Handler name, payload, and optional enqueue options.
76
+ * @returns The created (or idempotently replayed) job.
77
+ * @throws {VeyraApiError} When the API rejects the request.
78
+ *
79
+ * @example
80
+ * ```ts
81
+ * await client.enqueue({ handler: 'http_request', payload: { url: 'https://example.com' } });
82
+ * ```
83
+ */
84
+ enqueue<TPayload = unknown, TResult = unknown, const TName extends HandlerName<ResolvedHandlers<THandlers>> | (string & {}) = HandlerName<ResolvedHandlers<THandlers>> | (string & {})>(input: TypedEnqueueInput<ResolvedHandlers<THandlers>, TName, TPayload>): Promise<Job<TypedEnqueuePayload<ResolvedHandlers<THandlers>, TName, TPayload>, TypedEnqueueResult<ResolvedHandlers<THandlers>, TName, TResult>>>;
85
+ /**
86
+ * Fetches a job and validates its result with the definition's schema.
87
+ *
88
+ * @param jobId - Job ULID.
89
+ * @param handler - Definition whose result schema should validate `job.result`.
90
+ * @param options - Request cancellation and retry options.
91
+ * @returns The job with `result` typed as the definition's result.
92
+ */
93
+ getJob<TName extends string, TPayload, TResult, TQueue extends string | undefined>(jobId: string, handler: HandlerDefinition<TName, TPayload, TResult, TQueue>, options?: RequestOptions): Promise<Job<TPayload, TResult>>;
94
+ /**
95
+ * Fetches a job for a known built-in or registered handler name.
96
+ *
97
+ * @param jobId - Job ULID.
98
+ * @param handler - Known handler name string.
99
+ * @param options - Request cancellation and retry options.
100
+ * @returns The job with `payload` and `result` typed according to the handler contract.
101
+ */
102
+ getJob<const TName extends HandlerName<ResolvedHandlers<THandlers>>>(jobId: string, handler: TName, options?: RequestOptions): Promise<Job<HandlerPayload<ResolvedHandlers<THandlers>, TName>, HandlerResult<ResolvedHandlers<THandlers>, TName>>>;
103
+ /**
104
+ * Fetches a job with only the result type specified.
105
+ *
106
+ * @param jobId - Job ULID.
107
+ * @param options - Request cancellation and retry options.
108
+ * @returns The job with `result` typed as `TResult`.
109
+ */
110
+ getJob<TResult = unknown>(jobId: string, options?: RequestOptions): Promise<Job<unknown, TResult>>;
111
+ /** @deprecated Prefer `getJob<TResult>(jobId)` or `getJob(jobId, handler)`. */
112
+ getJob<TPayload = unknown, TResult = unknown>(jobId: string, options?: RequestOptions): Promise<Job<TPayload, TResult>>;
113
+ /**
114
+ * Cancels a queued, scheduled, failed, or running job.
115
+ *
116
+ * @param jobId - Job ULID.
117
+ * @param options - Request cancellation and retry options.
118
+ * @returns The cancelled job.
119
+ * @throws {VeyraConflictError} When the job already succeeded or was dead-lettered.
120
+ */
121
+ cancelJob(jobId: string, options?: RequestOptions): Promise<Job>;
122
+ /**
123
+ * Retries a failed, cancelled, or dead-lettered job.
124
+ *
125
+ * @param jobId - Job ULID.
126
+ * @param options - Request cancellation and retry options.
127
+ * @returns The retried job.
128
+ * @throws {VeyraConflictError} When the job is not in a retryable state.
129
+ */
130
+ retryJob(jobId: string, options?: RequestOptions): Promise<Job>;
131
+ /**
132
+ * Registers a worker with the cluster.
133
+ *
134
+ * @param params - Identity, queues, handlers, and concurrency.
135
+ * @returns The stored worker record.
136
+ */
137
+ registerWorker(params: WorkerRegisterParams): Promise<WorkerRecord>;
138
+ /**
139
+ * Sends a worker-level heartbeat.
140
+ *
141
+ * @param workerId - Worker id.
142
+ * @returns The worker's current state and heartbeat timestamp.
143
+ * @throws {VeyraNotFoundError} When the worker no longer exists.
144
+ */
145
+ heartbeatWorker(workerId: string): Promise<HeartbeatResponse>;
146
+ /**
147
+ * Claims the next runnable job for a worker.
148
+ *
149
+ * @param workerId - Worker id.
150
+ * @param params - Optional queue/handler filter.
151
+ * @returns The claimed job, or `null` on `204 No Content`.
152
+ */
153
+ claimJob<TPayload = unknown>(workerId: string, params?: ClaimParams): Promise<JobClaim<TPayload> | null>;
154
+ /**
155
+ * Renews the lease for an in-flight job.
156
+ *
157
+ * @param workerId - Worker id.
158
+ * @param jobId - Job ULID.
159
+ * @returns The renewed lease.
160
+ * @throws {LeaseLostError} When the lease expired or was reassigned.
161
+ */
162
+ renewJobLease(workerId: string, jobId: string): Promise<RenewLeaseResponse>;
163
+ /**
164
+ * Marks a job as completed with an optional result payload.
165
+ *
166
+ * @param workerId - Worker id.
167
+ * @param jobId - Job ULID.
168
+ * @param result - JSON result recorded on the job.
169
+ * @returns The completion acknowledgement.
170
+ * @throws {LeaseLostError} When the lease expired or was reassigned.
171
+ */
172
+ completeJob(workerId: string, jobId: string, result?: unknown): Promise<CompleteJobResponse>;
173
+ /**
174
+ * Reports a job execution failure.
175
+ *
176
+ * @param workerId - Worker id.
177
+ * @param jobId - Job ULID.
178
+ * @param params - Error class, message, stack trace, and permanence.
179
+ * @returns The failure acknowledgement.
180
+ */
181
+ failJob(workerId: string, jobId: string, params: FailJobParams): Promise<FailJobResponse>;
182
+ /**
183
+ * Transitions a worker to `draining` so it stops claiming new jobs.
184
+ *
185
+ * @param workerId - Worker id.
186
+ * @returns The updated worker record.
187
+ */
188
+ drainWorker(workerId: string): Promise<WorkerRecord>;
189
+ /**
190
+ * Deregisters a worker from the active fleet.
191
+ *
192
+ * @param workerId - Worker id.
193
+ * @returns The deregistration acknowledgement.
194
+ * @throws {VeyraConflictError} When the worker still holds active leases.
195
+ */
196
+ deregisterWorker(workerId: string): Promise<DeregisterWorkerResponse>;
197
+ /**
198
+ * Creates a managed {@link VeyraWorker} bound to this client.
199
+ *
200
+ * @param options - Queues, concurrency, and lifecycle callbacks.
201
+ * @returns A worker that inherits this client's handler map.
202
+ */
203
+ createWorker(options: VeyraWorkerOptions): VeyraWorker<THandlers>;
204
+ }