@aniket-lodh/veyra-sdk 0.1.0 → 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.
- package/README.md +209 -120
- package/dist/cjs/client.d.ts +204 -0
- package/dist/cjs/client.js +647 -0
- package/dist/cjs/errors.d.ts +147 -0
- package/dist/cjs/errors.js +262 -0
- package/dist/cjs/handlers.d.ts +165 -0
- package/dist/cjs/handlers.js +46 -0
- package/dist/cjs/index.d.ts +15 -0
- package/dist/cjs/index.js +37 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/standard-schema.d.ts +86 -0
- package/dist/cjs/standard-schema.js +49 -0
- package/dist/cjs/types.d.ts +430 -0
- package/dist/cjs/types.js +6 -0
- package/dist/cjs/webhook.d.ts +98 -0
- package/dist/cjs/webhook.js +165 -0
- package/dist/cjs/worker.d.ts +101 -0
- package/dist/cjs/worker.js +497 -0
- package/dist/client.d.ts +159 -25
- package/dist/client.js +501 -122
- package/dist/errors.d.ts +123 -10
- package/dist/errors.js +192 -19
- package/dist/handlers.d.ts +165 -0
- package/dist/handlers.js +42 -0
- package/dist/index.d.ts +13 -6
- package/dist/index.js +12 -6
- package/dist/standard-schema.d.ts +86 -0
- package/dist/standard-schema.js +45 -0
- package/dist/types.d.ts +281 -36
- package/dist/types.js +2 -2
- package/dist/webhook.d.ts +98 -0
- package/dist/webhook.js +128 -0
- package/dist/worker.d.ts +80 -55
- package/dist/worker.js +308 -195
- package/package.json +27 -13
- package/dist/client.d.ts.map +0 -1
- package/dist/client.js.map +0 -1
- package/dist/errors.d.ts.map +0 -1
- package/dist/errors.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/types.d.ts.map +0 -1
- package/dist/types.js.map +0 -1
- package/dist/worker.d.ts.map +0 -1
- package/dist/worker.js.map +0 -1
- package/src/client.ts +0 -389
- package/src/errors.ts +0 -82
- package/src/index.ts +0 -8
- package/src/types.ts +0 -217
- package/src/worker.ts +0 -472
|
@@ -0,0 +1,647 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Veyra HTTP client.
|
|
4
|
+
*/
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.VeyraClient = void 0;
|
|
7
|
+
const errors_js_1 = require("./errors.js");
|
|
8
|
+
const handlers_js_1 = require("./handlers.js");
|
|
9
|
+
const standard_schema_js_1 = require("./standard-schema.js");
|
|
10
|
+
const worker_js_1 = require("./worker.js");
|
|
11
|
+
function sleep(ms, signal) {
|
|
12
|
+
return new Promise((resolve, reject) => {
|
|
13
|
+
if (signal?.aborted) {
|
|
14
|
+
reject(signal.reason ?? new errors_js_1.VeyraError('Operation was aborted'));
|
|
15
|
+
return;
|
|
16
|
+
}
|
|
17
|
+
const timer = setTimeout(() => {
|
|
18
|
+
signal?.removeEventListener('abort', onAbort);
|
|
19
|
+
resolve();
|
|
20
|
+
}, ms);
|
|
21
|
+
function onAbort() {
|
|
22
|
+
clearTimeout(timer);
|
|
23
|
+
reject(signal?.reason ?? new errors_js_1.VeyraError('Operation was aborted'));
|
|
24
|
+
}
|
|
25
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
function assertJsonSerializable(value, label) {
|
|
29
|
+
if (value === undefined) {
|
|
30
|
+
throw new errors_js_1.VeyraValidationError(label, [{ message: `${label} is required` }]);
|
|
31
|
+
}
|
|
32
|
+
try {
|
|
33
|
+
JSON.stringify(value);
|
|
34
|
+
}
|
|
35
|
+
catch (err) {
|
|
36
|
+
throw new errors_js_1.VeyraValidationError(label, [{ message: `${label} must be JSON-serializable: ${err.message}` }], { cause: err });
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function validateSafeIdentifier(value, name) {
|
|
40
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
41
|
+
throw new errors_js_1.VeyraValidationError(name, [{ message: `${name} is required and must be a non-empty string` }]);
|
|
42
|
+
}
|
|
43
|
+
const trimmed = value.trim();
|
|
44
|
+
if (/[\r\n\t\x00-\x1F\x7F]/.test(trimmed)) {
|
|
45
|
+
throw new errors_js_1.VeyraValidationError(name, [{ message: `${name} contains invalid control characters` }]);
|
|
46
|
+
}
|
|
47
|
+
return trimmed;
|
|
48
|
+
}
|
|
49
|
+
function validateCallbackUrl(raw) {
|
|
50
|
+
const trimmed = raw.trim();
|
|
51
|
+
if (trimmed.length > 2048) {
|
|
52
|
+
throw new errors_js_1.VeyraValidationError('callbackUrl', [{ message: 'callbackUrl must be at most 2048 characters' }]);
|
|
53
|
+
}
|
|
54
|
+
let parsed;
|
|
55
|
+
try {
|
|
56
|
+
parsed = new URL(trimmed);
|
|
57
|
+
}
|
|
58
|
+
catch (err) {
|
|
59
|
+
throw new errors_js_1.VeyraValidationError('callbackUrl', [{ message: `callbackUrl is not a valid URL: ${err.message}` }]);
|
|
60
|
+
}
|
|
61
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
62
|
+
throw new errors_js_1.VeyraValidationError('callbackUrl', [{ message: "callbackUrl scheme must be 'http:' or 'https:'" }]);
|
|
63
|
+
}
|
|
64
|
+
if (!parsed.host) {
|
|
65
|
+
throw new errors_js_1.VeyraValidationError('callbackUrl', [{ message: 'callbackUrl must include a valid host' }]);
|
|
66
|
+
}
|
|
67
|
+
return trimmed;
|
|
68
|
+
}
|
|
69
|
+
function parseRetryAfterMs(header) {
|
|
70
|
+
if (!header) {
|
|
71
|
+
return undefined;
|
|
72
|
+
}
|
|
73
|
+
const seconds = Number(header);
|
|
74
|
+
if (Number.isFinite(seconds) && seconds >= 0) {
|
|
75
|
+
return seconds * 1000;
|
|
76
|
+
}
|
|
77
|
+
const date = Date.parse(header);
|
|
78
|
+
if (!Number.isNaN(date)) {
|
|
79
|
+
return Math.max(0, date - Date.now());
|
|
80
|
+
}
|
|
81
|
+
return undefined;
|
|
82
|
+
}
|
|
83
|
+
function sanitizeHeader(name, value) {
|
|
84
|
+
if (/[\r\n]/.test(name) || /[\r\n]/.test(value)) {
|
|
85
|
+
throw new errors_js_1.VeyraValidationError('headers', [
|
|
86
|
+
{ message: `Header '${name}' contains invalid newline characters (CRLF)` },
|
|
87
|
+
]);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Typed client for the Veyra REST API.
|
|
92
|
+
*
|
|
93
|
+
* @typeParam THandlers - Extra handler contracts merged over {@link BuiltInHandlers}.
|
|
94
|
+
* Register handlers here to get autocomplete and payload/result checking on
|
|
95
|
+
* string-based `enqueue` calls shared across services.
|
|
96
|
+
*
|
|
97
|
+
* @example
|
|
98
|
+
* ```ts
|
|
99
|
+
* interface MyHandlers {
|
|
100
|
+
* send_email: { payload: { to: string }; result: { messageId: string } };
|
|
101
|
+
* }
|
|
102
|
+
* const client = new VeyraClient<MyHandlers>({ baseUrl, apiKey });
|
|
103
|
+
* const job = await client.enqueue({ handler: 'send_email', payload: { to: 'a@b.c' } });
|
|
104
|
+
* job.result?.messageId; // string
|
|
105
|
+
* ```
|
|
106
|
+
*/
|
|
107
|
+
class VeyraClient {
|
|
108
|
+
/** API origin without a trailing slash. */
|
|
109
|
+
baseUrl;
|
|
110
|
+
/** Queue used when `enqueue` omits `queue`. */
|
|
111
|
+
defaultQueue;
|
|
112
|
+
/** @internal Credentials are held in private state to prevent accidental leakage via inspect/JSON/keys. */
|
|
113
|
+
#apiKey;
|
|
114
|
+
#customFetch;
|
|
115
|
+
#defaultTimeoutMs;
|
|
116
|
+
#maxRetries;
|
|
117
|
+
#logger;
|
|
118
|
+
/**
|
|
119
|
+
* @param config - API origin, API key, and transport settings.
|
|
120
|
+
* @throws {VeyraValidationError} When `baseUrl` or `apiKey` is invalid.
|
|
121
|
+
*/
|
|
122
|
+
constructor(config) {
|
|
123
|
+
if (!config || typeof config !== 'object') {
|
|
124
|
+
throw new errors_js_1.VeyraValidationError('config', [{ message: 'VeyraClientConfig must be an object' }]);
|
|
125
|
+
}
|
|
126
|
+
if (!config.baseUrl || typeof config.baseUrl !== 'string') {
|
|
127
|
+
throw new errors_js_1.VeyraValidationError('baseUrl', [{ message: 'baseUrl is required and must be a string' }]);
|
|
128
|
+
}
|
|
129
|
+
let parsedUrl;
|
|
130
|
+
try {
|
|
131
|
+
parsedUrl = new URL(config.baseUrl);
|
|
132
|
+
}
|
|
133
|
+
catch (err) {
|
|
134
|
+
throw new errors_js_1.VeyraValidationError('baseUrl', [
|
|
135
|
+
{ message: `baseUrl '${config.baseUrl}' is not a valid URL: ${err.message}` },
|
|
136
|
+
]);
|
|
137
|
+
}
|
|
138
|
+
if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
|
|
139
|
+
throw new errors_js_1.VeyraValidationError('baseUrl', [
|
|
140
|
+
{ message: `baseUrl must use http: or https: protocol (received '${parsedUrl.protocol}')` },
|
|
141
|
+
]);
|
|
142
|
+
}
|
|
143
|
+
this.baseUrl = config.baseUrl.replace(/\/+$/, '');
|
|
144
|
+
if (!config.apiKey || typeof config.apiKey !== 'string') {
|
|
145
|
+
throw new errors_js_1.VeyraValidationError('apiKey', [{ message: 'apiKey is required and must be a non-empty string' }]);
|
|
146
|
+
}
|
|
147
|
+
const trimmedKey = config.apiKey.trim();
|
|
148
|
+
if (!trimmedKey) {
|
|
149
|
+
throw new errors_js_1.VeyraValidationError('apiKey', [{ message: 'apiKey must not be empty or whitespace' }]);
|
|
150
|
+
}
|
|
151
|
+
if (/[\r\n\t\x00-\x1F\x7F]/.test(trimmedKey)) {
|
|
152
|
+
throw new errors_js_1.VeyraValidationError('apiKey', [{ message: 'apiKey contains invalid control characters' }]);
|
|
153
|
+
}
|
|
154
|
+
this.#apiKey = trimmedKey;
|
|
155
|
+
if (config.timeoutMs !== undefined) {
|
|
156
|
+
if (!Number.isFinite(config.timeoutMs) || config.timeoutMs <= 0) {
|
|
157
|
+
throw new errors_js_1.VeyraValidationError('timeoutMs', [{ message: 'timeoutMs must be a positive finite number' }]);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
this.#defaultTimeoutMs = config.timeoutMs ?? 30_000;
|
|
161
|
+
if (config.maxRetries !== undefined) {
|
|
162
|
+
if (!Number.isInteger(config.maxRetries) || config.maxRetries < 0 || config.maxRetries > 10) {
|
|
163
|
+
throw new errors_js_1.VeyraValidationError('maxRetries', [{ message: 'maxRetries must be an integer between 0 and 10' }]);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
this.#maxRetries = config.maxRetries ?? 2;
|
|
167
|
+
if (config.defaultQueue !== undefined) {
|
|
168
|
+
if (typeof config.defaultQueue !== 'string' || !config.defaultQueue.trim()) {
|
|
169
|
+
throw new errors_js_1.VeyraValidationError('defaultQueue', [{ message: 'defaultQueue must be a non-empty string' }]);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
this.defaultQueue = config.defaultQueue?.trim() || 'default';
|
|
173
|
+
this.#customFetch = config.fetch;
|
|
174
|
+
this.#logger = config.logger;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Safe JSON representation redacting all sensitive credentials.
|
|
178
|
+
*/
|
|
179
|
+
toJSON() {
|
|
180
|
+
return {
|
|
181
|
+
baseUrl: this.baseUrl,
|
|
182
|
+
defaultQueue: this.defaultQueue,
|
|
183
|
+
hasApiKey: true,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Node.js custom inspection hook redacting all sensitive credentials from console output.
|
|
188
|
+
*/
|
|
189
|
+
[Symbol.for('nodejs.util.inspect.custom')]() {
|
|
190
|
+
return this.toJSON();
|
|
191
|
+
}
|
|
192
|
+
async enqueue(inputOrHandler, payload, options) {
|
|
193
|
+
let input;
|
|
194
|
+
let signal;
|
|
195
|
+
let retries;
|
|
196
|
+
if ((0, handlers_js_1.isHandlerDefinition)(inputOrHandler)) {
|
|
197
|
+
const definition = inputOrHandler;
|
|
198
|
+
const validated = await (0, standard_schema_js_1.validateWithSchema)(definition.payload, payload, `enqueue('${definition.name}') payload`);
|
|
199
|
+
input = { ...(options ?? {}), handler: definition.name, payload: validated };
|
|
200
|
+
if (input.queue === undefined && definition.queue !== undefined) {
|
|
201
|
+
input.queue = definition.queue;
|
|
202
|
+
}
|
|
203
|
+
signal = options?.signal;
|
|
204
|
+
retries = options?.retries;
|
|
205
|
+
}
|
|
206
|
+
else if (typeof inputOrHandler === 'object' &&
|
|
207
|
+
inputOrHandler !== null &&
|
|
208
|
+
'handler' in inputOrHandler &&
|
|
209
|
+
(0, handlers_js_1.isHandlerDefinition)(inputOrHandler.handler)) {
|
|
210
|
+
const defInput = inputOrHandler;
|
|
211
|
+
const definition = defInput.handler;
|
|
212
|
+
const validated = await (0, standard_schema_js_1.validateWithSchema)(definition.payload, defInput.payload, `enqueue('${definition.name}') payload`);
|
|
213
|
+
const { handler: _ignored, ...rest } = defInput;
|
|
214
|
+
input = { ...rest, handler: definition.name, payload: validated };
|
|
215
|
+
if (input.queue === undefined && definition.queue !== undefined) {
|
|
216
|
+
input.queue = definition.queue;
|
|
217
|
+
}
|
|
218
|
+
signal = defInput.signal;
|
|
219
|
+
retries = defInput.retries;
|
|
220
|
+
}
|
|
221
|
+
else {
|
|
222
|
+
input = inputOrHandler;
|
|
223
|
+
signal = input.signal;
|
|
224
|
+
retries = input.retries;
|
|
225
|
+
}
|
|
226
|
+
const handler = validateSafeIdentifier(input.handler, 'handler');
|
|
227
|
+
const queue = input.queue !== undefined
|
|
228
|
+
? validateSafeIdentifier(input.queue, 'queue')
|
|
229
|
+
: this.defaultQueue;
|
|
230
|
+
assertJsonSerializable(input.payload, `enqueue('${handler}') payload`);
|
|
231
|
+
const body = {
|
|
232
|
+
handler,
|
|
233
|
+
queue,
|
|
234
|
+
payload: input.payload,
|
|
235
|
+
};
|
|
236
|
+
if (input.priority !== undefined) {
|
|
237
|
+
if (!Number.isInteger(input.priority) || input.priority < 0 || input.priority > 9) {
|
|
238
|
+
throw new errors_js_1.VeyraValidationError('priority', [{ message: 'priority must be an integer between 0 and 9' }]);
|
|
239
|
+
}
|
|
240
|
+
body.priority = input.priority;
|
|
241
|
+
}
|
|
242
|
+
if (input.maxAttempts !== undefined) {
|
|
243
|
+
if (!Number.isInteger(input.maxAttempts) || input.maxAttempts < 1) {
|
|
244
|
+
throw new errors_js_1.VeyraValidationError('maxAttempts', [{ message: 'maxAttempts must be an integer >= 1' }]);
|
|
245
|
+
}
|
|
246
|
+
body.maxAttempts = input.maxAttempts;
|
|
247
|
+
}
|
|
248
|
+
if (input.backoff !== undefined) {
|
|
249
|
+
if (!input.backoff || typeof input.backoff !== 'object' || !input.backoff.kind) {
|
|
250
|
+
throw new errors_js_1.VeyraValidationError('backoff', [{ message: 'backoff must specify kind' }]);
|
|
251
|
+
}
|
|
252
|
+
body.backoff = input.backoff;
|
|
253
|
+
}
|
|
254
|
+
if (input.scheduledFor !== undefined) {
|
|
255
|
+
if (input.scheduledFor instanceof Date) {
|
|
256
|
+
body.scheduledFor = input.scheduledFor.toISOString();
|
|
257
|
+
}
|
|
258
|
+
else if (typeof input.scheduledFor === 'string' && input.scheduledFor.trim() !== '') {
|
|
259
|
+
body.scheduledFor = input.scheduledFor.trim();
|
|
260
|
+
}
|
|
261
|
+
else {
|
|
262
|
+
throw new errors_js_1.VeyraValidationError('scheduledFor', [{ message: 'scheduledFor must be an ISO string or Date' }]);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
const headers = {};
|
|
266
|
+
if (input.idempotencyKey !== undefined) {
|
|
267
|
+
const key = validateSafeIdentifier(input.idempotencyKey, 'idempotencyKey');
|
|
268
|
+
body.idempotencyKey = key;
|
|
269
|
+
headers['Idempotency-Key'] = key;
|
|
270
|
+
}
|
|
271
|
+
if (input.callbackUrl !== undefined) {
|
|
272
|
+
body.callbackUrl = validateCallbackUrl(input.callbackUrl);
|
|
273
|
+
}
|
|
274
|
+
const isIdempotent = Boolean(body.idempotencyKey);
|
|
275
|
+
const { data, headers: resHeaders } = await this.#request('/jobs', {
|
|
276
|
+
method: 'POST',
|
|
277
|
+
headers,
|
|
278
|
+
body,
|
|
279
|
+
signal,
|
|
280
|
+
idempotent: isIdempotent,
|
|
281
|
+
retries,
|
|
282
|
+
});
|
|
283
|
+
if (resHeaders.get('idempotent-replay') === 'true') {
|
|
284
|
+
data.isReplay = true;
|
|
285
|
+
}
|
|
286
|
+
return data;
|
|
287
|
+
}
|
|
288
|
+
async getJob(jobId, handlerOrOptions, maybeOptions) {
|
|
289
|
+
const validId = validateSafeIdentifier(jobId, 'jobId');
|
|
290
|
+
const handler = (0, handlers_js_1.isHandlerDefinition)(handlerOrOptions) || typeof handlerOrOptions === 'string'
|
|
291
|
+
? handlerOrOptions
|
|
292
|
+
: undefined;
|
|
293
|
+
const options = handler
|
|
294
|
+
? maybeOptions
|
|
295
|
+
: handlerOrOptions;
|
|
296
|
+
const { data } = await this.#request(`/jobs/${encodeURIComponent(validId)}`, {
|
|
297
|
+
method: 'GET',
|
|
298
|
+
signal: options?.signal,
|
|
299
|
+
idempotent: true,
|
|
300
|
+
retries: options?.retries,
|
|
301
|
+
});
|
|
302
|
+
if ((0, handlers_js_1.isHandlerDefinition)(handler) && handler.result && data.result !== null) {
|
|
303
|
+
data.result = await (0, standard_schema_js_1.validateWithSchema)(handler.result, data.result, `getJob('${handler.name}') result`);
|
|
304
|
+
}
|
|
305
|
+
return data;
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Cancels a queued, scheduled, failed, or running job.
|
|
309
|
+
*
|
|
310
|
+
* @param jobId - Job ULID.
|
|
311
|
+
* @param options - Request cancellation and retry options.
|
|
312
|
+
* @returns The cancelled job.
|
|
313
|
+
* @throws {VeyraConflictError} When the job already succeeded or was dead-lettered.
|
|
314
|
+
*/
|
|
315
|
+
async cancelJob(jobId, options) {
|
|
316
|
+
const validId = validateSafeIdentifier(jobId, 'jobId');
|
|
317
|
+
const { data } = await this.#request(`/jobs/${encodeURIComponent(validId)}/cancel`, {
|
|
318
|
+
method: 'POST',
|
|
319
|
+
signal: options?.signal,
|
|
320
|
+
idempotent: true,
|
|
321
|
+
retries: options?.retries,
|
|
322
|
+
});
|
|
323
|
+
return data;
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* Retries a failed, cancelled, or dead-lettered job.
|
|
327
|
+
*
|
|
328
|
+
* @param jobId - Job ULID.
|
|
329
|
+
* @param options - Request cancellation and retry options.
|
|
330
|
+
* @returns The retried job.
|
|
331
|
+
* @throws {VeyraConflictError} When the job is not in a retryable state.
|
|
332
|
+
*/
|
|
333
|
+
async retryJob(jobId, options) {
|
|
334
|
+
const validId = validateSafeIdentifier(jobId, 'jobId');
|
|
335
|
+
const { data } = await this.#request(`/jobs/${encodeURIComponent(validId)}/retry`, {
|
|
336
|
+
method: 'POST',
|
|
337
|
+
signal: options?.signal,
|
|
338
|
+
idempotent: true,
|
|
339
|
+
retries: options?.retries,
|
|
340
|
+
});
|
|
341
|
+
return data;
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Registers a worker with the cluster.
|
|
345
|
+
*
|
|
346
|
+
* @param params - Identity, queues, handlers, and concurrency.
|
|
347
|
+
* @returns The stored worker record.
|
|
348
|
+
*/
|
|
349
|
+
async registerWorker(params) {
|
|
350
|
+
const { data } = await this.#request('/workers/register', {
|
|
351
|
+
method: 'POST',
|
|
352
|
+
body: params,
|
|
353
|
+
idempotent: true,
|
|
354
|
+
});
|
|
355
|
+
return data;
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Sends a worker-level heartbeat.
|
|
359
|
+
*
|
|
360
|
+
* @param workerId - Worker id.
|
|
361
|
+
* @returns The worker's current state and heartbeat timestamp.
|
|
362
|
+
* @throws {VeyraNotFoundError} When the worker no longer exists.
|
|
363
|
+
*/
|
|
364
|
+
async heartbeatWorker(workerId) {
|
|
365
|
+
const validId = validateSafeIdentifier(workerId, 'workerId');
|
|
366
|
+
const { data } = await this.#request(`/workers/${encodeURIComponent(validId)}/heartbeat`, { method: 'POST', idempotent: true });
|
|
367
|
+
return data;
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Claims the next runnable job for a worker.
|
|
371
|
+
*
|
|
372
|
+
* @param workerId - Worker id.
|
|
373
|
+
* @param params - Optional queue/handler filter.
|
|
374
|
+
* @returns The claimed job, or `null` on `204 No Content`.
|
|
375
|
+
*/
|
|
376
|
+
async claimJob(workerId, params) {
|
|
377
|
+
const validId = validateSafeIdentifier(workerId, 'workerId');
|
|
378
|
+
const { data, status } = await this.#request(`/workers/${encodeURIComponent(validId)}/claim`, {
|
|
379
|
+
method: 'POST',
|
|
380
|
+
body: params || {},
|
|
381
|
+
idempotent: false,
|
|
382
|
+
});
|
|
383
|
+
if (status === 204 || !data) {
|
|
384
|
+
return null;
|
|
385
|
+
}
|
|
386
|
+
return data;
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Renews the lease for an in-flight job.
|
|
390
|
+
*
|
|
391
|
+
* @param workerId - Worker id.
|
|
392
|
+
* @param jobId - Job ULID.
|
|
393
|
+
* @returns The renewed lease.
|
|
394
|
+
* @throws {LeaseLostError} When the lease expired or was reassigned.
|
|
395
|
+
*/
|
|
396
|
+
async renewJobLease(workerId, jobId) {
|
|
397
|
+
const validWorkerId = validateSafeIdentifier(workerId, 'workerId');
|
|
398
|
+
const validJobId = validateSafeIdentifier(jobId, 'jobId');
|
|
399
|
+
const { data } = await this.#request(`/workers/${encodeURIComponent(validWorkerId)}/jobs/${encodeURIComponent(validJobId)}/heartbeat`, { method: 'POST', idempotent: true });
|
|
400
|
+
return data;
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Marks a job as completed with an optional result payload.
|
|
404
|
+
*
|
|
405
|
+
* @param workerId - Worker id.
|
|
406
|
+
* @param jobId - Job ULID.
|
|
407
|
+
* @param result - JSON result recorded on the job.
|
|
408
|
+
* @returns The completion acknowledgement.
|
|
409
|
+
* @throws {LeaseLostError} When the lease expired or was reassigned.
|
|
410
|
+
*/
|
|
411
|
+
async completeJob(workerId, jobId, result) {
|
|
412
|
+
const validWorkerId = validateSafeIdentifier(workerId, 'workerId');
|
|
413
|
+
const validJobId = validateSafeIdentifier(jobId, 'jobId');
|
|
414
|
+
const body = {};
|
|
415
|
+
if (result !== undefined) {
|
|
416
|
+
assertJsonSerializable(result, `completeJob('${jobId}') result`);
|
|
417
|
+
body.result = result;
|
|
418
|
+
}
|
|
419
|
+
const { data } = await this.#request(`/workers/${encodeURIComponent(validWorkerId)}/jobs/${encodeURIComponent(validJobId)}/complete`, {
|
|
420
|
+
method: 'POST',
|
|
421
|
+
body,
|
|
422
|
+
idempotent: false,
|
|
423
|
+
});
|
|
424
|
+
return data;
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* Reports a job execution failure.
|
|
428
|
+
*
|
|
429
|
+
* @param workerId - Worker id.
|
|
430
|
+
* @param jobId - Job ULID.
|
|
431
|
+
* @param params - Error class, message, stack trace, and permanence.
|
|
432
|
+
* @returns The failure acknowledgement.
|
|
433
|
+
*/
|
|
434
|
+
async failJob(workerId, jobId, params) {
|
|
435
|
+
const validWorkerId = validateSafeIdentifier(workerId, 'workerId');
|
|
436
|
+
const validJobId = validateSafeIdentifier(jobId, 'jobId');
|
|
437
|
+
const { data } = await this.#request(`/workers/${encodeURIComponent(validWorkerId)}/jobs/${encodeURIComponent(validJobId)}/fail`, {
|
|
438
|
+
method: 'POST',
|
|
439
|
+
body: params,
|
|
440
|
+
idempotent: false,
|
|
441
|
+
});
|
|
442
|
+
return data;
|
|
443
|
+
}
|
|
444
|
+
/**
|
|
445
|
+
* Transitions a worker to `draining` so it stops claiming new jobs.
|
|
446
|
+
*
|
|
447
|
+
* @param workerId - Worker id.
|
|
448
|
+
* @returns The updated worker record.
|
|
449
|
+
*/
|
|
450
|
+
async drainWorker(workerId) {
|
|
451
|
+
const validId = validateSafeIdentifier(workerId, 'workerId');
|
|
452
|
+
const { data } = await this.#request(`/workers/${encodeURIComponent(validId)}/drain`, { method: 'POST', idempotent: true });
|
|
453
|
+
return data;
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Deregisters a worker from the active fleet.
|
|
457
|
+
*
|
|
458
|
+
* @param workerId - Worker id.
|
|
459
|
+
* @returns The deregistration acknowledgement.
|
|
460
|
+
* @throws {VeyraConflictError} When the worker still holds active leases.
|
|
461
|
+
*/
|
|
462
|
+
async deregisterWorker(workerId) {
|
|
463
|
+
const validId = validateSafeIdentifier(workerId, 'workerId');
|
|
464
|
+
const { data } = await this.#request(`/workers/${encodeURIComponent(validId)}/deregister`, { method: 'POST', idempotent: true });
|
|
465
|
+
return data;
|
|
466
|
+
}
|
|
467
|
+
/**
|
|
468
|
+
* Creates a managed {@link VeyraWorker} bound to this client.
|
|
469
|
+
*
|
|
470
|
+
* @param options - Queues, concurrency, and lifecycle callbacks.
|
|
471
|
+
* @returns A worker that inherits this client's handler map.
|
|
472
|
+
*/
|
|
473
|
+
createWorker(options) {
|
|
474
|
+
return new worker_js_1.VeyraWorker(this, options);
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* Internal HTTP transport method with timeout, cancellation, credential encapsulation,
|
|
478
|
+
* safe non-JSON error handling, and exponential backoff retry for idempotent calls.
|
|
479
|
+
*/
|
|
480
|
+
async #request(path, options) {
|
|
481
|
+
const fetchImpl = this.#customFetch || globalThis.fetch;
|
|
482
|
+
if (!fetchImpl) {
|
|
483
|
+
throw new errors_js_1.VeyraError('No fetch implementation available. Node 18+ or a global fetch polyfill is required.');
|
|
484
|
+
}
|
|
485
|
+
const url = `${this.baseUrl}${path}`;
|
|
486
|
+
const baseHeaders = {
|
|
487
|
+
Authorization: `Bearer ${this.#apiKey}`,
|
|
488
|
+
Accept: 'application/json',
|
|
489
|
+
};
|
|
490
|
+
if (options.headers) {
|
|
491
|
+
for (const [k, v] of Object.entries(options.headers)) {
|
|
492
|
+
sanitizeHeader(k, v);
|
|
493
|
+
baseHeaders[k] = v;
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
let bodyStr;
|
|
497
|
+
if (options.body !== undefined) {
|
|
498
|
+
baseHeaders['Content-Type'] = 'application/json';
|
|
499
|
+
bodyStr = JSON.stringify(options.body);
|
|
500
|
+
}
|
|
501
|
+
const maxAttempts = options.idempotent
|
|
502
|
+
? 1 + (options.retries !== undefined ? Math.max(0, options.retries) : this.#maxRetries)
|
|
503
|
+
: 1;
|
|
504
|
+
let lastError;
|
|
505
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
506
|
+
if (options.signal?.aborted) {
|
|
507
|
+
throw options.signal.reason ?? new errors_js_1.VeyraError('Operation was aborted');
|
|
508
|
+
}
|
|
509
|
+
const controller = new AbortController();
|
|
510
|
+
let timedOut = false;
|
|
511
|
+
const timeoutId = setTimeout(() => {
|
|
512
|
+
timedOut = true;
|
|
513
|
+
controller.abort(new errors_js_1.VeyraTimeoutError(`Request timed out after ${this.#defaultTimeoutMs}ms: ${url}`, this.#defaultTimeoutMs));
|
|
514
|
+
}, this.#defaultTimeoutMs);
|
|
515
|
+
function onUserAbort() {
|
|
516
|
+
controller.abort(options.signal?.reason);
|
|
517
|
+
}
|
|
518
|
+
if (options.signal) {
|
|
519
|
+
options.signal.addEventListener('abort', onUserAbort, { once: true });
|
|
520
|
+
}
|
|
521
|
+
try {
|
|
522
|
+
const res = await fetchImpl(url, {
|
|
523
|
+
method: options.method,
|
|
524
|
+
headers: baseHeaders,
|
|
525
|
+
body: bodyStr,
|
|
526
|
+
signal: controller.signal,
|
|
527
|
+
});
|
|
528
|
+
clearTimeout(timeoutId);
|
|
529
|
+
options.signal?.removeEventListener('abort', onUserAbort);
|
|
530
|
+
const requestId = res.headers.get('x-request-id') ?? undefined;
|
|
531
|
+
if (res.status === 204) {
|
|
532
|
+
return { data: undefined, status: 204, headers: res.headers };
|
|
533
|
+
}
|
|
534
|
+
const text = await res.text();
|
|
535
|
+
let parsed;
|
|
536
|
+
let isJson = false;
|
|
537
|
+
if (text.length > 0) {
|
|
538
|
+
try {
|
|
539
|
+
parsed = JSON.parse(text);
|
|
540
|
+
isJson = true;
|
|
541
|
+
}
|
|
542
|
+
catch {
|
|
543
|
+
parsed = text;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
if (!res.ok) {
|
|
547
|
+
let errorMessage;
|
|
548
|
+
if (isJson &&
|
|
549
|
+
typeof parsed === 'object' &&
|
|
550
|
+
parsed !== null &&
|
|
551
|
+
'error' in parsed &&
|
|
552
|
+
typeof parsed.error === 'string') {
|
|
553
|
+
errorMessage = parsed.error;
|
|
554
|
+
}
|
|
555
|
+
else if (text.startsWith('<!DOCTYPE') ||
|
|
556
|
+
text.startsWith('<html') ||
|
|
557
|
+
text.startsWith('<HTML')) {
|
|
558
|
+
errorMessage = `HTTP ${res.status} ${res.statusText || 'Error'}`;
|
|
559
|
+
}
|
|
560
|
+
else if (text.length > 0) {
|
|
561
|
+
errorMessage = text.length > 256 ? `${text.slice(0, 256)}...` : text;
|
|
562
|
+
}
|
|
563
|
+
else {
|
|
564
|
+
errorMessage = res.statusText || `HTTP ${res.status}`;
|
|
565
|
+
}
|
|
566
|
+
let errorToThrow;
|
|
567
|
+
if (res.status === 401 || res.status === 403) {
|
|
568
|
+
errorToThrow = new errors_js_1.VeyraAuthError(res.status, res.statusText, errorMessage, parsed, { requestId });
|
|
569
|
+
}
|
|
570
|
+
else if (res.status === 404) {
|
|
571
|
+
errorToThrow = new errors_js_1.VeyraNotFoundError(res.status, res.statusText, errorMessage, parsed, { requestId });
|
|
572
|
+
}
|
|
573
|
+
else if (res.status === 409) {
|
|
574
|
+
if (errorMessage.includes('lease') || errorMessage.includes('expired')) {
|
|
575
|
+
errorToThrow = new errors_js_1.LeaseLostError(errorMessage, { requestId });
|
|
576
|
+
}
|
|
577
|
+
else {
|
|
578
|
+
errorToThrow = new errors_js_1.VeyraConflictError(res.status, res.statusText, errorMessage, parsed, { requestId });
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
else if (res.status === 429) {
|
|
582
|
+
const retryAfterMs = parseRetryAfterMs(res.headers.get('retry-after'));
|
|
583
|
+
errorToThrow = new errors_js_1.VeyraRateLimitError(res.status, res.statusText, errorMessage, parsed, {
|
|
584
|
+
requestId,
|
|
585
|
+
retryAfterMs,
|
|
586
|
+
});
|
|
587
|
+
}
|
|
588
|
+
else {
|
|
589
|
+
errorToThrow = new errors_js_1.VeyraApiError(res.status, res.statusText, errorMessage, parsed, {
|
|
590
|
+
requestId,
|
|
591
|
+
retryable: res.status === 502 || res.status === 503 || res.status === 504,
|
|
592
|
+
});
|
|
593
|
+
}
|
|
594
|
+
if (options.idempotent && errorToThrow.retryable && attempt < maxAttempts - 1) {
|
|
595
|
+
lastError = errorToThrow;
|
|
596
|
+
const backoffMs = errorToThrow instanceof errors_js_1.VeyraRateLimitError && errorToThrow.retryAfterMs !== undefined
|
|
597
|
+
? Math.min(errorToThrow.retryAfterMs, 30_000)
|
|
598
|
+
: Math.min(10_000, 150 * Math.pow(2, attempt)) + Math.random() * 100;
|
|
599
|
+
this.#logger?.warn?.(`VeyraClient retryable error (${res.status}), retrying in ${Math.round(backoffMs)}ms`, {
|
|
600
|
+
attempt: attempt + 1,
|
|
601
|
+
status: res.status,
|
|
602
|
+
requestId,
|
|
603
|
+
});
|
|
604
|
+
await sleep(backoffMs, options.signal);
|
|
605
|
+
continue;
|
|
606
|
+
}
|
|
607
|
+
throw errorToThrow;
|
|
608
|
+
}
|
|
609
|
+
return { data: parsed, status: res.status, headers: res.headers };
|
|
610
|
+
}
|
|
611
|
+
catch (err) {
|
|
612
|
+
clearTimeout(timeoutId);
|
|
613
|
+
options.signal?.removeEventListener('abort', onUserAbort);
|
|
614
|
+
let finalError;
|
|
615
|
+
if (timedOut || err instanceof errors_js_1.VeyraTimeoutError) {
|
|
616
|
+
finalError = new errors_js_1.VeyraTimeoutError(`Request timed out after ${this.#defaultTimeoutMs}ms: ${url}`, this.#defaultTimeoutMs, { cause: err });
|
|
617
|
+
}
|
|
618
|
+
else if (options.signal?.aborted) {
|
|
619
|
+
finalError = options.signal.reason ?? err;
|
|
620
|
+
}
|
|
621
|
+
else if (err instanceof errors_js_1.VeyraError) {
|
|
622
|
+
finalError = err;
|
|
623
|
+
}
|
|
624
|
+
else {
|
|
625
|
+
finalError = new errors_js_1.VeyraNetworkError(`Network error while fetching ${url}: ${err.message}`, { cause: err });
|
|
626
|
+
}
|
|
627
|
+
const isRetryable = options.idempotent &&
|
|
628
|
+
(finalError instanceof errors_js_1.VeyraNetworkError ||
|
|
629
|
+
finalError instanceof errors_js_1.VeyraTimeoutError ||
|
|
630
|
+
(finalError instanceof errors_js_1.VeyraApiError && finalError.retryable));
|
|
631
|
+
if (isRetryable && attempt < maxAttempts - 1) {
|
|
632
|
+
lastError = finalError;
|
|
633
|
+
const backoffMs = Math.min(10_000, 150 * Math.pow(2, attempt)) + Math.random() * 100;
|
|
634
|
+
this.#logger?.warn?.(`VeyraClient network error, retrying in ${Math.round(backoffMs)}ms`, {
|
|
635
|
+
attempt: attempt + 1,
|
|
636
|
+
error: finalError.message,
|
|
637
|
+
});
|
|
638
|
+
await sleep(backoffMs, options.signal);
|
|
639
|
+
continue;
|
|
640
|
+
}
|
|
641
|
+
throw finalError;
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
throw lastError;
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
exports.VeyraClient = VeyraClient;
|