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