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/README.md +81 -2
- package/index.d.ts +268 -0
- package/index.js +7 -0
- package/package.json +28 -4
- package/src/client.js +537 -0
- package/src/errors.js +37 -0
- package/src/json.js +188 -0
- package/src/models.js +230 -0
- package/src/transport.js +273 -0
package/src/json.js
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The minimal JSON reader (doc 21, "No dependencies"): walks the text once, delivers the fields of an
|
|
5
|
+
* object as name -> text fragment and the items of an array as text fragments, without interpreting them.
|
|
6
|
+
* That keeps the message `body` exactly as the server sent it (`JSON.parse` would turn `1.0` into `1`
|
|
7
|
+
* and lose integers above 2^53).
|
|
8
|
+
*/
|
|
9
|
+
class JsonError extends Error {}
|
|
10
|
+
|
|
11
|
+
function skipWhitespace(s, i) {
|
|
12
|
+
while (i < s.length) {
|
|
13
|
+
const c = s.charCodeAt(i);
|
|
14
|
+
if (c !== 0x20 && c !== 0x09 && c !== 0x0a && c !== 0x0d) {
|
|
15
|
+
break;
|
|
16
|
+
}
|
|
17
|
+
i++;
|
|
18
|
+
}
|
|
19
|
+
return i;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function scanString(s, i) {
|
|
23
|
+
for (i++; i < s.length; i++) {
|
|
24
|
+
const c = s[i];
|
|
25
|
+
if (c === '\\') {
|
|
26
|
+
i++;
|
|
27
|
+
} else if (c === '"') {
|
|
28
|
+
return i + 1;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
throw new JsonError('unterminated string');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The index right after the value that starts at `i` (iterative: deep nesting does not use the stack). */
|
|
35
|
+
function scanValue(s, i) {
|
|
36
|
+
if (i >= s.length) {
|
|
37
|
+
throw new JsonError('value expected');
|
|
38
|
+
}
|
|
39
|
+
const first = s[i];
|
|
40
|
+
if (first === '"') {
|
|
41
|
+
return scanString(s, i);
|
|
42
|
+
}
|
|
43
|
+
if (first === '{' || first === '[') {
|
|
44
|
+
let depth = 0;
|
|
45
|
+
for (; i < s.length; i++) {
|
|
46
|
+
const c = s[i];
|
|
47
|
+
if (c === '"') {
|
|
48
|
+
i = scanString(s, i) - 1;
|
|
49
|
+
} else if (c === '{' || c === '[') {
|
|
50
|
+
depth++;
|
|
51
|
+
} else if (c === '}' || c === ']') {
|
|
52
|
+
depth--;
|
|
53
|
+
if (depth === 0) {
|
|
54
|
+
return i + 1;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
throw new JsonError('unterminated object or array');
|
|
59
|
+
}
|
|
60
|
+
const start = i;
|
|
61
|
+
while (i < s.length && ',]} \t\r\n'.indexOf(s[i]) < 0) {
|
|
62
|
+
i++;
|
|
63
|
+
}
|
|
64
|
+
if (i === start) {
|
|
65
|
+
throw new JsonError('value expected');
|
|
66
|
+
}
|
|
67
|
+
return i;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Decodes a string fragment (with the quotes) into text. */
|
|
71
|
+
function decodeString(fragment) {
|
|
72
|
+
if (fragment[0] !== '"') {
|
|
73
|
+
throw new JsonError('string expected');
|
|
74
|
+
}
|
|
75
|
+
try {
|
|
76
|
+
return JSON.parse(fragment);
|
|
77
|
+
} catch (e) {
|
|
78
|
+
throw new JsonError('invalid string');
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The items of an array fragment, each as a text fragment. */
|
|
83
|
+
function arrayItems(fragment) {
|
|
84
|
+
const s = fragment;
|
|
85
|
+
let i = skipWhitespace(s, 0);
|
|
86
|
+
if (s[i] !== '[') {
|
|
87
|
+
throw new JsonError('array expected');
|
|
88
|
+
}
|
|
89
|
+
const items = [];
|
|
90
|
+
i = skipWhitespace(s, i + 1);
|
|
91
|
+
if (s[i] === ']') {
|
|
92
|
+
return items;
|
|
93
|
+
}
|
|
94
|
+
for (;;) {
|
|
95
|
+
i = skipWhitespace(s, i);
|
|
96
|
+
const end = scanValue(s, i);
|
|
97
|
+
items.push(s.slice(i, end));
|
|
98
|
+
i = skipWhitespace(s, end);
|
|
99
|
+
if (s[i] === ',') {
|
|
100
|
+
i++;
|
|
101
|
+
} else if (s[i] === ']') {
|
|
102
|
+
return items;
|
|
103
|
+
} else {
|
|
104
|
+
throw new JsonError('"," or "]" expected');
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The fields of one JSON object. */
|
|
110
|
+
class JsonFields {
|
|
111
|
+
constructor(map) {
|
|
112
|
+
this._map = map;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
static parse(text) {
|
|
116
|
+
const s = String(text);
|
|
117
|
+
const map = new Map();
|
|
118
|
+
let i = skipWhitespace(s, 0);
|
|
119
|
+
if (s[i] !== '{') {
|
|
120
|
+
throw new JsonError('object expected');
|
|
121
|
+
}
|
|
122
|
+
i = skipWhitespace(s, i + 1);
|
|
123
|
+
if (s[i] !== '}') {
|
|
124
|
+
for (;;) {
|
|
125
|
+
i = skipWhitespace(s, i);
|
|
126
|
+
if (s[i] !== '"') {
|
|
127
|
+
throw new JsonError('field name expected');
|
|
128
|
+
}
|
|
129
|
+
const keyEnd = scanString(s, i);
|
|
130
|
+
const key = decodeString(s.slice(i, keyEnd));
|
|
131
|
+
i = skipWhitespace(s, keyEnd);
|
|
132
|
+
if (s[i] !== ':') {
|
|
133
|
+
throw new JsonError('":" expected');
|
|
134
|
+
}
|
|
135
|
+
i = skipWhitespace(s, i + 1);
|
|
136
|
+
const end = scanValue(s, i);
|
|
137
|
+
map.set(key, s.slice(i, end));
|
|
138
|
+
i = skipWhitespace(s, end);
|
|
139
|
+
if (s[i] === ',') {
|
|
140
|
+
i++;
|
|
141
|
+
} else if (s[i] === '}') {
|
|
142
|
+
break;
|
|
143
|
+
} else {
|
|
144
|
+
throw new JsonError('"," or "}" expected');
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
if (skipWhitespace(s, i + 1) !== s.length) {
|
|
149
|
+
throw new JsonError('unexpected text after the object');
|
|
150
|
+
}
|
|
151
|
+
return new JsonFields(map);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** The field's text fragment, or `null` when absent or `null`. */
|
|
155
|
+
raw(name) {
|
|
156
|
+
const value = this._map.get(name);
|
|
157
|
+
return value === undefined || value === 'null' ? null : value;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
string(name) {
|
|
161
|
+
const value = this.raw(name);
|
|
162
|
+
return value === null ? null : decodeString(value);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
boolean(name) {
|
|
166
|
+
const value = this.raw(name);
|
|
167
|
+
if (value === null) {
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
if (value === 'true' || value === 'false') {
|
|
171
|
+
return value === 'true';
|
|
172
|
+
}
|
|
173
|
+
throw new JsonError(`field "${name}" is not a boolean`);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
integer(name) {
|
|
177
|
+
const value = this.raw(name);
|
|
178
|
+
if (value === null) {
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
if (!/^-?\d+$/.test(value)) {
|
|
182
|
+
throw new JsonError(`field "${name}" is not an integer`);
|
|
183
|
+
}
|
|
184
|
+
return Number(value);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
module.exports = { JsonError, JsonFields, arrayItems, decodeString };
|
package/src/models.js
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { TabaError } = require('./errors');
|
|
4
|
+
const { JsonError, JsonFields, arrayItems, decodeString } = require('./json');
|
|
5
|
+
|
|
6
|
+
/** A delivered message. The `body` always comes out as bytes (doc 21, "The delivered message"). */
|
|
7
|
+
class Message {
|
|
8
|
+
constructor(fields) {
|
|
9
|
+
Object.assign(this, fields);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** The `body` as UTF-8 text. */
|
|
13
|
+
get bodyText() {
|
|
14
|
+
return this.body.toString('utf8');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** The `body` read as JSON. */
|
|
18
|
+
json() {
|
|
19
|
+
return JSON.parse(this.bodyText);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* What the `consumeWith` handler receives: the `message`, the `delete` flag (the message is deleted at the end
|
|
25
|
+
* if the handler finishes without throwing; the default is `true`) and `changeVisibility`. While the handler
|
|
26
|
+
* runs, the connector renews the invisibility by itself, so no other consumer takes the message.
|
|
27
|
+
*/
|
|
28
|
+
class MessageContext {
|
|
29
|
+
constructor(message, leaseSeconds, change, signal) {
|
|
30
|
+
this.message = message;
|
|
31
|
+
this.delete = true;
|
|
32
|
+
this.signal = signal;
|
|
33
|
+
this._leaseSeconds = leaseSeconds;
|
|
34
|
+
this._lost = false;
|
|
35
|
+
this._change = change;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The seconds of invisibility the automatic renewal requests on each round. */
|
|
39
|
+
get leaseSeconds() {
|
|
40
|
+
return this._leaseSeconds;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** `true` when the server refused the renewal (the message already went back to the queue or was deleted). */
|
|
44
|
+
get leaseLost() {
|
|
45
|
+
return this._lost;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Changes the invisibility to `seconds` from now on. The value becomes the one of the automatic renewal. */
|
|
49
|
+
async changeVisibility(seconds) {
|
|
50
|
+
await this._change(seconds);
|
|
51
|
+
this._leaseSeconds = seconds;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function invalid(what, e) {
|
|
56
|
+
if (e instanceof JsonError) {
|
|
57
|
+
return TabaError.client('client.invalid-response', `${what}: ${e.message}`);
|
|
58
|
+
}
|
|
59
|
+
return e;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function fields(raw, what) {
|
|
63
|
+
try {
|
|
64
|
+
return JsonFields.parse(raw);
|
|
65
|
+
} catch (e) {
|
|
66
|
+
throw invalid(what, e);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function isJsonType(contentType) {
|
|
71
|
+
const media = contentType.split(';')[0].trim().toLowerCase();
|
|
72
|
+
return media === 'application/json' || media.endsWith('+json');
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function parseTopic(raw) {
|
|
76
|
+
const f = fields(raw, 'topic');
|
|
77
|
+
try {
|
|
78
|
+
return {
|
|
79
|
+
id: f.string('id') || '',
|
|
80
|
+
name: f.string('name') || '',
|
|
81
|
+
type: f.string('type') || '',
|
|
82
|
+
createdAt: f.string('createdAt') || '',
|
|
83
|
+
fifo: f.boolean('fifo'),
|
|
84
|
+
volatile: f.boolean('volatile'),
|
|
85
|
+
raw,
|
|
86
|
+
};
|
|
87
|
+
} catch (e) {
|
|
88
|
+
throw invalid('topic', e);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function parseMessage(raw) {
|
|
93
|
+
const f = fields(raw, 'message');
|
|
94
|
+
try {
|
|
95
|
+
const contentType = f.string('contentType') || 'application/json';
|
|
96
|
+
const body = f.raw('body');
|
|
97
|
+
let bytes;
|
|
98
|
+
if (body === null) {
|
|
99
|
+
bytes = Buffer.alloc(0);
|
|
100
|
+
} else if (f.string('bodyEncoding') === 'base64') {
|
|
101
|
+
const text = decodeString(body);
|
|
102
|
+
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(text) || text.length % 4 !== 0) {
|
|
103
|
+
throw TabaError.client('client.invalid-response', 'invalid base64 body');
|
|
104
|
+
}
|
|
105
|
+
bytes = Buffer.from(text, 'base64');
|
|
106
|
+
} else if (isJsonType(contentType)) {
|
|
107
|
+
bytes = Buffer.from(body, 'utf8');
|
|
108
|
+
} else {
|
|
109
|
+
bytes = Buffer.from(decodeString(body), 'utf8');
|
|
110
|
+
}
|
|
111
|
+
return new Message({
|
|
112
|
+
id: f.string('id') || '',
|
|
113
|
+
body: bytes,
|
|
114
|
+
contentType,
|
|
115
|
+
receiptToken: f.string('receiptToken') || '',
|
|
116
|
+
deliveryCount: f.integer('deliveryCount') || 0,
|
|
117
|
+
publishedAt: f.string('publishedAt') || '',
|
|
118
|
+
invisibleUntil: f.string('invisibleUntil') || '',
|
|
119
|
+
groupId: f.string('groupId'),
|
|
120
|
+
deduplicationId: f.string('deduplicationId'),
|
|
121
|
+
deadLetteredAt: f.string('deadLetteredAt'),
|
|
122
|
+
deadLetterReason: f.string('deadLetterReason'),
|
|
123
|
+
raw,
|
|
124
|
+
});
|
|
125
|
+
} catch (e) {
|
|
126
|
+
throw invalid('message', e);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function parseMessages(raw) {
|
|
131
|
+
const f = fields(raw, 'consume');
|
|
132
|
+
try {
|
|
133
|
+
return arrayItems(f.raw('messages') || '[]').map(parseMessage);
|
|
134
|
+
} catch (e) {
|
|
135
|
+
throw invalid('messages', e);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function parsePage(raw) {
|
|
140
|
+
const f = fields(raw, 'page');
|
|
141
|
+
try {
|
|
142
|
+
return {
|
|
143
|
+
items: arrayItems(f.raw('items') || '[]').map(parseTopic),
|
|
144
|
+
nextCursor: f.string('nextCursor'),
|
|
145
|
+
raw,
|
|
146
|
+
};
|
|
147
|
+
} catch (e) {
|
|
148
|
+
throw invalid('page items', e);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function parsePublishResponse(raw) {
|
|
153
|
+
const f = fields(raw, 'publication');
|
|
154
|
+
try {
|
|
155
|
+
const deliveries = [];
|
|
156
|
+
const list = f.raw('deliveries');
|
|
157
|
+
if (list !== null) {
|
|
158
|
+
for (const item of arrayItems(list)) {
|
|
159
|
+
const d = JsonFields.parse(item);
|
|
160
|
+
const error = d.raw('error');
|
|
161
|
+
const e = error !== null && error.startsWith('{') ? JsonFields.parse(error) : null;
|
|
162
|
+
deliveries.push({
|
|
163
|
+
topic: d.string('topic') || '',
|
|
164
|
+
id: d.string('id'),
|
|
165
|
+
errorCode: e === null ? null : e.string('code') || '',
|
|
166
|
+
errorMessage: e === null ? null : e.string('message'),
|
|
167
|
+
succeeded: e === null,
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return {
|
|
172
|
+
id: f.string('id'),
|
|
173
|
+
duplicate: f.boolean('duplicate'),
|
|
174
|
+
matched: f.integer('matched'),
|
|
175
|
+
deliveries,
|
|
176
|
+
raw,
|
|
177
|
+
};
|
|
178
|
+
} catch (e) {
|
|
179
|
+
throw invalid('publication', e);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** The `results` of a batch, one per item in the order of the request. `ok`: the item was applied. */
|
|
184
|
+
function parseBatchResults(raw) {
|
|
185
|
+
const f = fields(raw, 'batch');
|
|
186
|
+
try {
|
|
187
|
+
const results = [];
|
|
188
|
+
for (const item of arrayItems(f.raw('results') || '[]')) {
|
|
189
|
+
const r = JsonFields.parse(item);
|
|
190
|
+
const error = r.raw('error');
|
|
191
|
+
const e = error !== null && error.startsWith('{') ? JsonFields.parse(error) : null;
|
|
192
|
+
const status = r.integer('status') || 0;
|
|
193
|
+
results.push({
|
|
194
|
+
status,
|
|
195
|
+
ok: e === null && status < 300,
|
|
196
|
+
id: r.string('id'),
|
|
197
|
+
duplicate: r.boolean('duplicate'),
|
|
198
|
+
matched: r.integer('matched'),
|
|
199
|
+
invisibleUntil: r.string('invisibleUntil'),
|
|
200
|
+
errorCode: e === null ? null : e.string('code') || '',
|
|
201
|
+
errorMessage: e === null ? null : e.string('message'),
|
|
202
|
+
raw: item,
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
return results;
|
|
206
|
+
} catch (e) {
|
|
207
|
+
throw invalid('batch results', e);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function parseVisibilityResponse(raw) {
|
|
212
|
+
const f = fields(raw, 'visibility');
|
|
213
|
+
try {
|
|
214
|
+
return { id: f.string('id') || '', invisibleUntil: f.string('invisibleUntil') || '', raw };
|
|
215
|
+
} catch (e) {
|
|
216
|
+
throw invalid('visibility', e);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
module.exports = {
|
|
221
|
+
Message,
|
|
222
|
+
MessageContext,
|
|
223
|
+
parseTopic,
|
|
224
|
+
parseMessage,
|
|
225
|
+
parseMessages,
|
|
226
|
+
parsePage,
|
|
227
|
+
parsePublishResponse,
|
|
228
|
+
parseBatchResults,
|
|
229
|
+
parseVisibilityResponse,
|
|
230
|
+
};
|
package/src/transport.js
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const http = require('node:http');
|
|
4
|
+
const https = require('node:https');
|
|
5
|
+
const { TabaError } = require('./errors');
|
|
6
|
+
const { JsonFields } = require('./json');
|
|
7
|
+
|
|
8
|
+
// Refused, DNS and unreachable: the body was never sent, so the call can be repeated like a 503.
|
|
9
|
+
const CONNECT_FAILURES = new Set(['ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'ENETUNREACH', 'EHOSTUNREACH']);
|
|
10
|
+
|
|
11
|
+
const connectFailures = new WeakSet();
|
|
12
|
+
|
|
13
|
+
function sleep(ms, signal) {
|
|
14
|
+
return new Promise((resolve, reject) => {
|
|
15
|
+
if (signal && signal.aborted) {
|
|
16
|
+
reject(signal.reason);
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
const onAbort = () => {
|
|
20
|
+
clearTimeout(timer);
|
|
21
|
+
reject(signal.reason);
|
|
22
|
+
};
|
|
23
|
+
const timer = setTimeout(() => {
|
|
24
|
+
if (signal) {
|
|
25
|
+
signal.removeEventListener('abort', onAbort);
|
|
26
|
+
}
|
|
27
|
+
resolve();
|
|
28
|
+
}, ms);
|
|
29
|
+
if (signal) {
|
|
30
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function validateBaseUrl(baseUrl) {
|
|
36
|
+
let url = null;
|
|
37
|
+
if (typeof baseUrl === 'string' && baseUrl.trim() !== '') {
|
|
38
|
+
try {
|
|
39
|
+
url = new URL(baseUrl.trim());
|
|
40
|
+
} catch (e) {
|
|
41
|
+
url = null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
if (url === null || (url.protocol !== 'http:' && url.protocol !== 'https:')) {
|
|
45
|
+
const shown = typeof baseUrl === 'string' && baseUrl.trim() !== '' ? baseUrl : 'empty';
|
|
46
|
+
throw TabaError.client(
|
|
47
|
+
'client.invalid-config',
|
|
48
|
+
`baseUrl must be an http:// or https:// address (received: ${shown})`,
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
return url;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function errorFrom(status, headers, body) {
|
|
55
|
+
const text = body.toString('utf8');
|
|
56
|
+
let code = null;
|
|
57
|
+
let message = null;
|
|
58
|
+
let requestId = null;
|
|
59
|
+
let details = null;
|
|
60
|
+
try {
|
|
61
|
+
const f = JsonFields.parse(text);
|
|
62
|
+
code = f.string('code');
|
|
63
|
+
if (code !== null) {
|
|
64
|
+
message = f.string('message') || '';
|
|
65
|
+
requestId = f.string('requestId');
|
|
66
|
+
details = f.raw('details');
|
|
67
|
+
}
|
|
68
|
+
} catch (e) {
|
|
69
|
+
// Not an ErrorResponse: falls to the generic code below.
|
|
70
|
+
}
|
|
71
|
+
if (code === null) {
|
|
72
|
+
code = `http.${status}`;
|
|
73
|
+
const trimmed = text.trim();
|
|
74
|
+
message = trimmed.length === 0 ? `response ${status} with no body` : trimmed.slice(0, 300);
|
|
75
|
+
}
|
|
76
|
+
const retryHeader = headers['retry-after'];
|
|
77
|
+
const retryAfter = typeof retryHeader === 'string' && /^\d+$/.test(retryHeader.trim())
|
|
78
|
+
? Number(retryHeader.trim())
|
|
79
|
+
: undefined;
|
|
80
|
+
return new TabaError(status, code, message, {
|
|
81
|
+
requestId: requestId || headers['x-request-id'] || undefined,
|
|
82
|
+
retryAfter,
|
|
83
|
+
details: details === null ? undefined : details,
|
|
84
|
+
body,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function errorCodeOf(body) {
|
|
89
|
+
try {
|
|
90
|
+
return JsonFields.parse(body.toString('utf8')).string('code');
|
|
91
|
+
} catch (e) {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function recovers(call, status, body) {
|
|
97
|
+
return call.recover.some(([s, code]) => s === status && errorCodeOf(body) === code);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function describe(e) {
|
|
101
|
+
const code = e.code ? `${e.code}: ` : '';
|
|
102
|
+
return code + (e.message || String(e));
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Percent-encodes for a path segment or a query part (RFC 3986 unreserved characters stay). */
|
|
106
|
+
function encode(value) {
|
|
107
|
+
return encodeURIComponent(value).replace(/[!'()*]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase());
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The client's HTTP transport: builds the request, sends it, reads the body, turns the API error into a
|
|
112
|
+
* `TabaError` and does the call retries of the common contract (doc 21).
|
|
113
|
+
*/
|
|
114
|
+
class Transport {
|
|
115
|
+
constructor(config, sleepFn) {
|
|
116
|
+
this._config = config;
|
|
117
|
+
this._url = validateBaseUrl(config.baseUrl);
|
|
118
|
+
this._base = config.baseUrl.trim().replace(/\/+$/, '');
|
|
119
|
+
this._lib = this._url.protocol === 'https:' ? https : http;
|
|
120
|
+
this._owned = !config.agent;
|
|
121
|
+
const agentOptions = { keepAlive: true };
|
|
122
|
+
if (this._url.protocol === 'https:') {
|
|
123
|
+
agentOptions.minVersion = 'TLSv1.2';
|
|
124
|
+
}
|
|
125
|
+
this._agent = config.agent || new this._lib.Agent(agentOptions);
|
|
126
|
+
this.sleep = sleepFn || sleep;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
close() {
|
|
130
|
+
if (this._owned) {
|
|
131
|
+
this._agent.destroy();
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
_path(call) {
|
|
136
|
+
let path = new URL(this._base + call.path).pathname;
|
|
137
|
+
if (call.query.length > 0) {
|
|
138
|
+
path += '?' + call.query.map(([k, v]) => `${encode(k)}=${encode(v)}`).join('&');
|
|
139
|
+
}
|
|
140
|
+
return path;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
_headers(call) {
|
|
144
|
+
const headers = { Accept: 'application/json', 'User-Agent': this._config.userAgent };
|
|
145
|
+
if (this._config.token) {
|
|
146
|
+
headers.Authorization = `Bearer ${this._config.token}`;
|
|
147
|
+
}
|
|
148
|
+
if (call.requestId) {
|
|
149
|
+
headers['X-Request-Id'] = call.requestId;
|
|
150
|
+
}
|
|
151
|
+
if (call.traceparent) {
|
|
152
|
+
headers.traceparent = call.traceparent;
|
|
153
|
+
}
|
|
154
|
+
if (call.body) {
|
|
155
|
+
headers['Content-Type'] = call.contentType || 'application/json';
|
|
156
|
+
headers['Content-Length'] = call.body.length;
|
|
157
|
+
}
|
|
158
|
+
return headers;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** One attempt: resolves `{status, headers, body}`; rejects with a `TabaError` or the abort reason. */
|
|
162
|
+
_once(call, timeoutMs, signal) {
|
|
163
|
+
return new Promise((resolve, reject) => {
|
|
164
|
+
if (signal && signal.aborted) {
|
|
165
|
+
reject(signal.reason);
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
let settled = false;
|
|
169
|
+
let timedOut = false;
|
|
170
|
+
let gotResponse = false;
|
|
171
|
+
let connectTimer = null;
|
|
172
|
+
const onAbort = () => {
|
|
173
|
+
req.destroy();
|
|
174
|
+
finish(reject, signal.reason);
|
|
175
|
+
};
|
|
176
|
+
const finish = (fn, value) => {
|
|
177
|
+
if (settled) {
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
settled = true;
|
|
181
|
+
clearTimeout(timer);
|
|
182
|
+
clearTimeout(connectTimer);
|
|
183
|
+
if (signal) {
|
|
184
|
+
signal.removeEventListener('abort', onAbort);
|
|
185
|
+
}
|
|
186
|
+
fn(value);
|
|
187
|
+
};
|
|
188
|
+
const req = this._lib.request({
|
|
189
|
+
method: call.method,
|
|
190
|
+
hostname: this._url.hostname.replace(/^\[|\]$/g, ''),
|
|
191
|
+
port: this._url.port || undefined,
|
|
192
|
+
path: this._path(call),
|
|
193
|
+
headers: this._headers(call),
|
|
194
|
+
agent: this._agent,
|
|
195
|
+
}, (res) => {
|
|
196
|
+
gotResponse = true;
|
|
197
|
+
const chunks = [];
|
|
198
|
+
res.on('data', (chunk) => chunks.push(chunk));
|
|
199
|
+
res.on('end', () => finish(resolve, { status: res.statusCode, headers: res.headers, body: Buffer.concat(chunks) }));
|
|
200
|
+
res.on('error', (e) => finish(reject, TabaError.client('client.network', describe(e), e)));
|
|
201
|
+
});
|
|
202
|
+
const timer = setTimeout(() => {
|
|
203
|
+
timedOut = true;
|
|
204
|
+
req.destroy();
|
|
205
|
+
finish(reject, TabaError.client('client.timeout', 'timed out waiting for the response'));
|
|
206
|
+
}, timeoutMs);
|
|
207
|
+
if (signal) {
|
|
208
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
209
|
+
}
|
|
210
|
+
req.on('socket', (socket) => {
|
|
211
|
+
if (socket.connecting) {
|
|
212
|
+
connectTimer = setTimeout(() => {
|
|
213
|
+
req.destroy(Object.assign(new Error('timed out connecting'), { code: 'ETIMEDOUT' }));
|
|
214
|
+
}, this._config.connectTimeout);
|
|
215
|
+
socket.once('connect', () => clearTimeout(connectTimer));
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
req.on('error', (e) => {
|
|
219
|
+
if (timedOut) {
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
const error = TabaError.client('client.network', describe(e), e);
|
|
223
|
+
// A pooled connection the server closed while idle fails before anything is sent.
|
|
224
|
+
const stale = req.reusedSocket && !gotResponse && (e.code === 'ECONNRESET' || e.code === 'EPIPE');
|
|
225
|
+
if (CONNECT_FAILURES.has(e.code) || stale) {
|
|
226
|
+
connectFailures.add(error);
|
|
227
|
+
}
|
|
228
|
+
finish(reject, error);
|
|
229
|
+
});
|
|
230
|
+
req.end(call.body || undefined);
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Makes the call, retrying only what the contract says to retry: 429 and 503 (waiting for the
|
|
236
|
+
* `Retry-After`, or 1 s, 2 s, 4 s), 502 and 504 only with `retryGateway`, and a failure to connect
|
|
237
|
+
* (refused, DNS). Never a 4xx (except 429), nor a failure after the body was sent, nor a timeout.
|
|
238
|
+
*/
|
|
239
|
+
async send(call, signal) {
|
|
240
|
+
const timeoutMs = call.timeout !== undefined ? call.timeout : this._config.requestTimeout;
|
|
241
|
+
const max = Math.max(1, this._config.maxAttempts);
|
|
242
|
+
let afterRetryable = false;
|
|
243
|
+
for (let attempt = 1; ; attempt++) {
|
|
244
|
+
const backoff = 1000 * 2 ** Math.min(attempt - 1, 6);
|
|
245
|
+
let wait;
|
|
246
|
+
try {
|
|
247
|
+
const { status, headers, body } = await this._once(call, timeoutMs, signal);
|
|
248
|
+
if (status < 400) {
|
|
249
|
+
return { status, headers, body, text: body.toString('utf8'), recovered: false };
|
|
250
|
+
}
|
|
251
|
+
if (afterRetryable && recovers(call, status, body)) {
|
|
252
|
+
return { status, body, text: body.toString('utf8'), recovered: true };
|
|
253
|
+
}
|
|
254
|
+
const error = errorFrom(status, headers, body);
|
|
255
|
+
const retry = status === 429 || status === 503 || ((status === 502 || status === 504) && call.retryGateway);
|
|
256
|
+
if (!retry || attempt >= max) {
|
|
257
|
+
throw error;
|
|
258
|
+
}
|
|
259
|
+
afterRetryable = afterRetryable || status === 503;
|
|
260
|
+
wait = error.retryAfter !== undefined ? error.retryAfter * 1000 : backoff;
|
|
261
|
+
} catch (e) {
|
|
262
|
+
if (!connectFailures.has(e) || attempt >= max) {
|
|
263
|
+
throw e;
|
|
264
|
+
}
|
|
265
|
+
afterRetryable = true;
|
|
266
|
+
wait = backoff;
|
|
267
|
+
}
|
|
268
|
+
await this.sleep(wait, signal);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
module.exports = { Transport, sleep, encode };
|