taba-client 0.0.0-stage → 0.1.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/src/client.js ADDED
@@ -0,0 +1,537 @@
1
+ 'use strict';
2
+
3
+ const { TabaError } = require('./errors');
4
+ const { Transport, encode } = require('./transport');
5
+ const {
6
+ MessageContext,
7
+ parseMessages,
8
+ parsePage,
9
+ parsePublishResponse,
10
+ parseBatchResults,
11
+ parseTopic,
12
+ parseVisibilityResponse,
13
+ } = require('./models');
14
+
15
+ /** The version of this connector. */
16
+ const VERSION = '0.1.0';
17
+
18
+ /** The version of the API contract this connector implements. */
19
+ const CONTRACT_VERSION = '1';
20
+
21
+ // `consume` waits `waitTime` plus this slack, not the `requestTimeout`.
22
+ const LONG_POLL_SLACK_MS = 10000;
23
+
24
+ const HANDLER_MAX_MESSAGES = 1;
25
+ const HANDLER_VISIBILITY_TIMEOUT = 120;
26
+ const HANDLER_WAIT_TIME = 20;
27
+
28
+ function isAbort(e, signal) {
29
+ return signal !== undefined && signal.aborted && (e === signal.reason || (e && e.name === 'AbortError'));
30
+ }
31
+
32
+ function normalize(config) {
33
+ if (config === null || typeof config !== 'object') {
34
+ throw TabaError.client('client.invalid-config', 'config must be an object with at least baseUrl');
35
+ }
36
+ return {
37
+ baseUrl: config.baseUrl,
38
+ token: config.token,
39
+ connectTimeout: config.connectTimeout !== undefined ? config.connectTimeout : 5000,
40
+ requestTimeout: config.requestTimeout !== undefined ? config.requestTimeout : 30000,
41
+ maxAttempts: config.maxAttempts !== undefined ? config.maxAttempts : 3,
42
+ userAgent: config.userAgent !== undefined ? config.userAgent : `taba-node/${VERSION}`,
43
+ serializer: config.serializer,
44
+ agent: config.agent,
45
+ };
46
+ }
47
+
48
+ function call(method, path) {
49
+ return {
50
+ method,
51
+ path,
52
+ query: [],
53
+ body: null,
54
+ contentType: undefined,
55
+ requestId: undefined,
56
+ traceparent: undefined,
57
+ timeout: undefined,
58
+ retryGateway: false,
59
+ recover: [],
60
+ };
61
+ }
62
+
63
+ function withQuery(c, key, value) {
64
+ c.query.push([key, String(value)]);
65
+ return c;
66
+ }
67
+
68
+ function withJson(c, text) {
69
+ c.body = Buffer.from(text, 'utf8');
70
+ return c;
71
+ }
72
+
73
+ function segment(value) {
74
+ return encode(String(value));
75
+ }
76
+
77
+ function consumeCall(topic, options) {
78
+ const o = options || {};
79
+ const c = call('GET', `/topics/${segment(topic)}/messages`);
80
+ if (o.maxMessages !== undefined) {
81
+ withQuery(c, 'maxMessages', o.maxMessages);
82
+ }
83
+ if (o.visibilityTimeout !== undefined) {
84
+ withQuery(c, 'visibilityTimeout', o.visibilityTimeout);
85
+ }
86
+ if (o.waitTime !== undefined) {
87
+ withQuery(c, 'waitTime', o.waitTime);
88
+ }
89
+ if (o.autoCreate) {
90
+ withQuery(c, 'autoCreate', true);
91
+ if (o.volatile !== undefined) {
92
+ withQuery(c, 'volatile', o.volatile);
93
+ }
94
+ if (o.idleTimeout !== undefined) {
95
+ withQuery(c, 'idleTimeout', o.idleTimeout);
96
+ }
97
+ if (o.fifo !== undefined) {
98
+ withQuery(c, 'fifo', o.fifo);
99
+ }
100
+ for (const [key, value] of Object.entries(o.tags || {})) {
101
+ withQuery(c, `tag.${key}`, value);
102
+ }
103
+ }
104
+ c.requestId = o.requestId;
105
+ c.traceparent = o.traceparent;
106
+ c.timeout = (o.waitTime || 0) * 1000 + LONG_POLL_SLACK_MS;
107
+ return c;
108
+ }
109
+
110
+ function handlerDefaults(options) {
111
+ const o = Object.assign({}, options);
112
+ if (o.maxMessages === undefined) o.maxMessages = HANDLER_MAX_MESSAGES;
113
+ if (o.visibilityTimeout === undefined) o.visibilityTimeout = HANDLER_VISIBILITY_TIMEOUT;
114
+ if (o.waitTime === undefined) o.waitTime = HANDLER_WAIT_TIME;
115
+ return o;
116
+ }
117
+
118
+ /** A third of the invisibility (and never all of it), so a failed renewal can be tried again in time. */
119
+ function renewalInterval(leaseSeconds) {
120
+ return (Math.max(1, leaseSeconds) / 3) * 1000;
121
+ }
122
+
123
+ function createJson(request) {
124
+ return topicJson(request, true);
125
+ }
126
+
127
+ /** The body of `PUT /topics/{topic}`: the same fields without `name` (it goes in the path). */
128
+ function putJson(request) {
129
+ return topicJson(request, false);
130
+ }
131
+
132
+ function topicJson(request, withName) {
133
+ const out = withName ? { name: request.name || '', type: request.type || '' } : { type: request.type || '' };
134
+ if (request.tags && Object.keys(request.tags).length > 0) out.tags = request.tags;
135
+ if (request.prefixes && request.prefixes.length > 0) out.prefixes = request.prefixes;
136
+ for (const key of ['volatile', 'idleTimeout', 'fifo', 'maxMessageBytes', 'ttl', 'maxDeliveries']) {
137
+ if (request[key] !== undefined && request[key] !== null) out[key] = request[key];
138
+ }
139
+ return JSON.stringify(out);
140
+ }
141
+
142
+ /** A PATCH sends what is set; `null` goes back to the server default and `undefined` is left out. */
143
+ function updateJson(update) {
144
+ const out = {};
145
+ for (const key of ['tags', 'prefixes', 'idleTimeout', 'maxMessageBytes', 'ttl', 'maxDeliveries']) {
146
+ if (update[key] !== undefined) out[key] = update[key];
147
+ }
148
+ return JSON.stringify(out);
149
+ }
150
+
151
+ /**
152
+ * The Taba client API client (doc 21): the nine operations, `subscribe` and the consume with a handler.
153
+ * Everything is asynchronous (there is no synchronous HTTP in Node). A single object serves any number of
154
+ * concurrent calls.
155
+ */
156
+ class TabaClient {
157
+ /**
158
+ * @param {object} config `baseUrl` (required), `token`, `connectTimeout` (ms, 5000), `requestTimeout` (ms,
159
+ * 30000), `maxAttempts` (3), `userAgent`, `serializer` (`{stringify, parse}`), `agent`.
160
+ * @param {{sleep?: (ms: number, signal?: AbortSignal) => Promise<void>}} [internals] For tests.
161
+ */
162
+ constructor(config, internals) {
163
+ this._config = normalize(config);
164
+ this._transport = new Transport(this._config, internals && internals.sleep);
165
+ this._serializer = this._config.serializer || JSON;
166
+ }
167
+
168
+ /** Releases the connections the client opened. */
169
+ close() {
170
+ this._transport.close();
171
+ }
172
+
173
+ _send(c, signal) {
174
+ return this._transport.send(c, signal);
175
+ }
176
+
177
+ async createTopic(request, { signal } = {}) {
178
+ if (!request) {
179
+ throw TabaError.client('client.invalid-request', 'request is required');
180
+ }
181
+ const c = withJson(call('POST', '/topics'), createJson(request));
182
+ c.recover.push([409, 'topic.already-exists']);
183
+ const reply = await this._send(c, signal);
184
+ if (reply.recovered) {
185
+ return this.getTopic(request.name, { signal });
186
+ }
187
+ return parseTopic(reply.text);
188
+ }
189
+
190
+ async getTopic(name, { signal } = {}) {
191
+ const reply = await this._send(call('GET', `/topics/${segment(name)}`), signal);
192
+ return parseTopic(reply.text);
193
+ }
194
+
195
+ /** `GET /topics`. Parameters left `undefined` do not go in the query. */
196
+ async listTopics({ limit, cursor, name, signal } = {}) {
197
+ const c = call('GET', '/topics');
198
+ if (limit !== undefined) withQuery(c, 'limit', limit);
199
+ if (cursor !== undefined && cursor !== null) withQuery(c, 'cursor', cursor);
200
+ if (name !== undefined) withQuery(c, 'name', name);
201
+ const reply = await this._send(c, signal);
202
+ return parsePage(reply.text);
203
+ }
204
+
205
+ /** All topics, page by page. */
206
+ async listAllTopics({ name, signal } = {}) {
207
+ const all = [];
208
+ let cursor = null;
209
+ do {
210
+ const page = await this.listTopics({ cursor, name, signal });
211
+ all.push(...page.items);
212
+ cursor = page.nextCursor;
213
+ } while (cursor !== null);
214
+ return all;
215
+ }
216
+
217
+ async updateTopic(name, update, { signal } = {}) {
218
+ if (!update) {
219
+ throw TabaError.client('client.invalid-request', 'update is required');
220
+ }
221
+ const c = withJson(call('PATCH', `/topics/${segment(name)}`), updateJson(update));
222
+ const reply = await this._send(c, signal);
223
+ return parseTopic(reply.text);
224
+ }
225
+
226
+ /**
227
+ * `PUT /topics/{topic}`: brings the topic to the declared state, creating it if it does not exist. What is left
228
+ * out goes back to the server default (a full replacement, unlike `updateTopic`); `request.name` is the topic of
229
+ * the path. Another `type`, `fifo` or `volatile` is `409 topic.immutable-mismatch` unless `recreate`
230
+ * (`'if-empty'` or `'always'`) says otherwise. Repeated after a 503 like the other calls: the route is idempotent.
231
+ * Resolves to `{ topic, outcome }`, `outcome` being `'created'`, `'updated'` or `'recreated'`.
232
+ */
233
+ async createOrUpdateTopic(request, { recreate, signal } = {}) {
234
+ if (!request) {
235
+ throw TabaError.client('client.invalid-request', 'request is required');
236
+ }
237
+ if (recreate !== undefined && recreate !== null && recreate !== 'if-empty' && recreate !== 'always') {
238
+ throw TabaError.client('client.invalid-request', "recreate must be 'if-empty' or 'always'");
239
+ }
240
+ const c = withJson(call('PUT', `/topics/${segment(request.name || '')}`), putJson(request));
241
+ if (recreate) withQuery(c, 'recreate', recreate);
242
+ const reply = await this._send(c, signal);
243
+ const header = reply.headers ? reply.headers['taba-topic-recreated'] : undefined;
244
+ const recreated = String(header || '').trim().toLowerCase() === 'true';
245
+ let outcome = 'updated';
246
+ if (reply.status === 201) outcome = recreated ? 'recreated' : 'created';
247
+ return { topic: parseTopic(reply.text), outcome };
248
+ }
249
+
250
+ /**
251
+ * `DELETE /topics/{topic}`. With `ifEmpty: true`, removes the queue only if it and its dead-letter hold no message
252
+ * on any node (`409 topic.not-empty` otherwise; a distributor holds none).
253
+ */
254
+ async deleteTopic(name, { ifEmpty, signal } = {}) {
255
+ const c = call('DELETE', `/topics/${segment(name)}`);
256
+ if (ifEmpty) withQuery(c, 'ifEmpty', 'true');
257
+ c.recover.push([404, 'topic.not-found']);
258
+ await this._send(c, signal);
259
+ }
260
+
261
+ /**
262
+ * `POST /topics/{topic}/messages`. The body goes as bytes (a `Buffer`, `Uint8Array` or string), without
263
+ * validation. Options: `contentType` (default `application/json`), `groupId`, `deduplicationId`,
264
+ * `requestId`, `traceparent`, `fifo` (set it for a FIFO queue: only there can a 502/504 be repeated) and `signal`.
265
+ */
266
+ async publish(topic, body, options) {
267
+ const o = options || {};
268
+ const c = call('POST', `/topics/${segment(topic)}/messages`);
269
+ c.body = body === undefined || body === null ? Buffer.alloc(0) : Buffer.from(body);
270
+ c.contentType = o.contentType || 'application/json';
271
+ c.requestId = o.requestId;
272
+ c.traceparent = o.traceparent;
273
+ c.retryGateway = Boolean(o.fifo);
274
+ if (o.groupId !== undefined) withQuery(c, 'groupId', o.groupId);
275
+ if (o.deduplicationId !== undefined) withQuery(c, 'deduplicationId', o.deduplicationId);
276
+ const reply = await this._send(c, o.signal);
277
+ return parsePublishResponse(reply.text);
278
+ }
279
+
280
+ /** Serializes the value (with the configured `serializer`, or `JSON`) and publishes as `application/json`. */
281
+ publishJson(topic, value, options) {
282
+ if (value === undefined || value === null) {
283
+ throw TabaError.client('client.invalid-request', 'value is required');
284
+ }
285
+ let text;
286
+ try {
287
+ text = this._serializer.stringify(value);
288
+ } catch (e) {
289
+ throw TabaError.client('client.invalid-request', `cannot serialize the value: ${e.message}`, e);
290
+ }
291
+ return this.publish(topic, Buffer.from(text, 'utf8'), Object.assign({}, options, { contentType: 'application/json' }));
292
+ }
293
+
294
+ /** Publishes a JSON text the application already built, without serializing. */
295
+ publishRawJson(topic, json, options) {
296
+ return this.publish(topic, Buffer.from(json, 'utf8'), Object.assign({}, options, { contentType: 'application/json' }));
297
+ }
298
+
299
+ /** Publishes a text (`Content-Type: text/plain; charset=utf-8`). */
300
+ publishText(topic, text, options) {
301
+ return this.publish(topic, Buffer.from(text, 'utf8'), Object.assign({}, options, { contentType: 'text/plain; charset=utf-8' }));
302
+ }
303
+
304
+ /**
305
+ * `POST /topics/{topic}/messages/batch`: publishes many messages in one request (1 to the server's
306
+ * `api.batch.max-messages`, 1000 by default). Each item is `{ body, contentType, groupId, deduplicationId }`, the
307
+ * same fields as `publish`; the bytes travel in base64. Each item is answered as its single publication and one
308
+ * that fails does not undo the others (look at `ok` of each result). A failure of the network is not repeated.
309
+ */
310
+ async publishBatch(topic, messages, { signal } = {}) {
311
+ const items = (messages || []).map((m) => {
312
+ const item = {
313
+ body: Buffer.from(m.body === undefined || m.body === null ? '' : m.body).toString('base64'),
314
+ bodyEncoding: 'base64',
315
+ };
316
+ if (m.contentType !== undefined) item.contentType = m.contentType;
317
+ if (m.groupId !== undefined) item.groupId = m.groupId;
318
+ if (m.deduplicationId !== undefined) item.deduplicationId = m.deduplicationId;
319
+ return item;
320
+ });
321
+ const c = call('POST', `/topics/${segment(topic)}/messages/batch`);
322
+ withJson(c, JSON.stringify({ messages: items }));
323
+ const reply = await this._send(c, signal);
324
+ return parseBatchResults(reply.text);
325
+ }
326
+
327
+ /** `POST /topics/{topic}/messages/ack`: acknowledges many messages `consume` returned, in one request. */
328
+ async ackBatch(topic, messages, { signal } = {}) {
329
+ const c = call('POST', `/topics/${segment(topic)}/messages/ack`);
330
+ withJson(c, JSON.stringify({ messages: (messages || []).map((m) => ({ id: m.id, receiptToken: m.receiptToken })) }));
331
+ const reply = await this._send(c, signal);
332
+ return parseBatchResults(reply.text);
333
+ }
334
+
335
+ /** `POST /topics/{topic}/messages/visibility`: the invisibility of many delivered messages, `seconds` from now. */
336
+ async changeVisibilityBatch(topic, messages, seconds, { signal } = {}) {
337
+ const c = call('POST', `/topics/${segment(topic)}/messages/visibility`);
338
+ withJson(
339
+ c,
340
+ JSON.stringify({
341
+ messages: (messages || []).map((m) => ({ id: m.id, receiptToken: m.receiptToken, visibilityTimeout: seconds })),
342
+ }),
343
+ );
344
+ const reply = await this._send(c, signal);
345
+ return parseBatchResults(reply.text);
346
+ }
347
+
348
+ /**
349
+ * `GET /topics/{topic}/messages`. The read time is `waitTime + 10 s`, not the `requestTimeout`. A timeout is
350
+ * not repeated (the node may have captured messages, which come back by themselves at the end of the
351
+ * `visibilityTimeout`). Resolves an empty array when there are no messages.
352
+ */
353
+ async consume(topic, options) {
354
+ const reply = await this._send(consumeCall(topic, options), options && options.signal);
355
+ return parseMessages(reply.text);
356
+ }
357
+
358
+ /** `DELETE /topics/{topic}/messages/{id}?receiptToken=`. `message` is what `consume` returned. */
359
+ async ack(topic, message, { signal } = {}) {
360
+ const c = call('DELETE', `/topics/${segment(topic)}/messages/${segment(message.id)}`);
361
+ withQuery(c, 'receiptToken', message.receiptToken);
362
+ await this._send(c, signal);
363
+ }
364
+
365
+ /** `PUT /topics/{topic}/messages/{id}/visibility?receiptToken=`. */
366
+ async changeVisibility(topic, message, seconds, { signal } = {}) {
367
+ const c = call('PUT', `/topics/${segment(topic)}/messages/${segment(message.id)}/visibility`);
368
+ withQuery(c, 'receiptToken', message.receiptToken);
369
+ withJson(c, JSON.stringify({ visibilityTimeout: seconds }));
370
+ const reply = await this._send(c, signal);
371
+ return parseVisibilityResponse(reply.text);
372
+ }
373
+
374
+ /**
375
+ * Reads from the queue and hands each message to `handler(context)`. The message is deleted if the handler
376
+ * finishes without throwing (`context.delete = false` keeps it). While the handler runs, the invisibility is
377
+ * renewed every third of it. Defaults: one message at a time, 20 s of long polling, 120 s of invisibility.
378
+ * If the handler throws, the message is not deleted and the error propagates. Resolves how many messages
379
+ * were handled.
380
+ */
381
+ async consumeWith(topic, options, handler) {
382
+ if (typeof handler !== 'function') {
383
+ throw TabaError.client('client.invalid-request', 'handler is required');
384
+ }
385
+ const o = handlerDefaults(options);
386
+ const messages = await this.consume(topic, o);
387
+ let handled = 0;
388
+ for (const message of messages) {
389
+ const context = this._context(topic, o, message);
390
+ await this._handle(topic, context, () => handler(context), o.signal);
391
+ handled++;
392
+ }
393
+ return handled;
394
+ }
395
+
396
+ /**
397
+ * `consumeWith` with the body already parsed (with the configured `serializer`, or `JSON`) in
398
+ * `context.body`. A body that does not parse gives `client.invalid-response` before the handler is
399
+ * called, and the message is not deleted.
400
+ */
401
+ async consumeJson(topic, options, handler) {
402
+ if (typeof handler !== 'function') {
403
+ throw TabaError.client('client.invalid-request', 'handler is required');
404
+ }
405
+ const o = handlerDefaults(options);
406
+ const messages = await this.consume(topic, o);
407
+ let handled = 0;
408
+ for (const message of messages) {
409
+ let body;
410
+ try {
411
+ body = this._serializer.parse(message.bodyText);
412
+ } catch (e) {
413
+ throw TabaError.client('client.invalid-response', `body of message ${message.id} is not valid JSON: ${e.message}`, e);
414
+ }
415
+ const context = this._context(topic, o, message);
416
+ context.body = body;
417
+ await this._handle(topic, context, () => handler(context), o.signal);
418
+ handled++;
419
+ }
420
+ return handled;
421
+ }
422
+
423
+ _context(topic, options, message) {
424
+ return new MessageContext(
425
+ message,
426
+ options.visibilityTimeout,
427
+ (seconds) => this.changeVisibility(topic, message, seconds, { signal: options.signal }),
428
+ options.signal,
429
+ );
430
+ }
431
+
432
+ async _handle(topic, context, run, signal) {
433
+ const stop = new AbortController();
434
+ const onAbort = () => stop.abort();
435
+ if (signal) {
436
+ signal.addEventListener('abort', onAbort, { once: true });
437
+ }
438
+ const renewal = this._keepAlive(topic, context, stop.signal);
439
+ try {
440
+ await run();
441
+ } finally {
442
+ stop.abort();
443
+ if (signal) {
444
+ signal.removeEventListener('abort', onAbort);
445
+ }
446
+ await renewal;
447
+ }
448
+ if (context.delete) {
449
+ try {
450
+ // Without the signal: the message was already handled, and acknowledging it must not be cut short.
451
+ await this.ack(topic, context.message);
452
+ } catch (e) {
453
+ if (!(e instanceof TabaError && (e.status === 409 || e.status === 404))) {
454
+ throw e;
455
+ }
456
+ // The message already went back to the queue (deadline expired) or is already gone.
457
+ }
458
+ }
459
+ }
460
+
461
+ /** The second task: renews the invisibility until the handler finishes. Never rejects. */
462
+ async _keepAlive(topic, context, signal) {
463
+ try {
464
+ while (!signal.aborted) {
465
+ await this._transport.sleep(renewalInterval(context.leaseSeconds), signal);
466
+ try {
467
+ await this.changeVisibility(topic, context.message, context.leaseSeconds, { signal });
468
+ } catch (e) {
469
+ if (e instanceof TabaError && (e.status === 409 || e.status === 404)) {
470
+ // The message already went back to the queue or was deleted: renewing is no longer of any use.
471
+ context._lost = true;
472
+ return;
473
+ }
474
+ if (signal.aborted) {
475
+ return;
476
+ }
477
+ // Transient failure (network, 5xx): tries again on the next round, before the deadline expires.
478
+ }
479
+ }
480
+ } catch (e) {
481
+ // The handler finished (the signal was aborted while waiting).
482
+ }
483
+ }
484
+
485
+ /**
486
+ * The consume loop: long polling (`waitTime` 20 and one message at a time, if not set), calls
487
+ * `handler(message)` and acknowledges by itself only if it finishes without throwing (a message that fails
488
+ * goes back to the queue at the end of the `visibilityTimeout`, and the error goes to `onError(message, error)`).
489
+ * Resolves, without an error, when `signal` is aborted. A server error while consuming rejects.
490
+ */
491
+ async subscribe(topic, options, handler, { signal, onError } = {}) {
492
+ if (typeof handler !== 'function') {
493
+ throw TabaError.client('client.invalid-request', 'handler is required');
494
+ }
495
+ const poll = Object.assign({}, options, { signal });
496
+ if (poll.waitTime === undefined) poll.waitTime = HANDLER_WAIT_TIME;
497
+ if (poll.maxMessages === undefined) poll.maxMessages = HANDLER_MAX_MESSAGES;
498
+ while (!(signal && signal.aborted)) {
499
+ let messages;
500
+ try {
501
+ messages = await this.consume(topic, poll);
502
+ } catch (e) {
503
+ if (isAbort(e, signal)) {
504
+ return;
505
+ }
506
+ throw e;
507
+ }
508
+ for (const message of messages) {
509
+ let handled;
510
+ try {
511
+ await handler(message);
512
+ handled = true;
513
+ } catch (e) {
514
+ handled = false;
515
+ if (onError) {
516
+ onError(message, e);
517
+ }
518
+ }
519
+ if (handled) {
520
+ try {
521
+ // Without the signal: the message was already handled, and acknowledging it must not be cut short.
522
+ await this.ack(topic, message);
523
+ } catch (e) {
524
+ if (!(e instanceof TabaError && (e.status === 409 || e.status === 404))) {
525
+ throw e;
526
+ }
527
+ }
528
+ }
529
+ if (signal && signal.aborted) {
530
+ return;
531
+ }
532
+ }
533
+ }
534
+ }
535
+ }
536
+
537
+ module.exports = { TabaClient, VERSION, CONTRACT_VERSION, consumeCall, renewalInterval };
package/src/errors.js ADDED
@@ -0,0 +1,37 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * The only kind of error of the connector (doc 21, "The common contract"): the API `ErrorResponse`, or a
5
+ * failure of the client itself, with `status` zero and `code` `client.network`, `client.timeout`,
6
+ * `client.invalid-config`, `client.invalid-response` or `client.invalid-request`. The application tests the
7
+ * `code`, never the `message`.
8
+ */
9
+ class TabaError extends Error {
10
+ /**
11
+ * @param {number} status HTTP status, or zero on a failure of the client itself.
12
+ * @param {string} code
13
+ * @param {string} message
14
+ * @param {{requestId?: string, retryAfter?: number, details?: string, body?: Buffer, cause?: unknown}} [extra]
15
+ */
16
+ constructor(status, code, message, extra) {
17
+ super(message, extra && extra.cause !== undefined ? { cause: extra.cause } : undefined);
18
+ this.name = 'TabaError';
19
+ this.status = status;
20
+ this.code = code || '';
21
+ this.requestId = extra && extra.requestId !== undefined ? extra.requestId : undefined;
22
+ this.retryAfter = extra && extra.retryAfter !== undefined ? extra.retryAfter : undefined;
23
+ this.details = extra && extra.details !== undefined ? extra.details : undefined;
24
+ this.body = extra && extra.body ? extra.body : Buffer.alloc(0);
25
+ }
26
+
27
+ /** A failure of the client itself, not a server response. */
28
+ get isClientSide() {
29
+ return this.status === 0;
30
+ }
31
+
32
+ static client(code, message, cause) {
33
+ return new TabaError(0, code, message, { cause });
34
+ }
35
+ }
36
+
37
+ module.exports = { TabaError };