@friggframework/core 2.0.0-next.127 → 2.0.0-next.129
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/CLAUDE.md +166 -7
- package/core/CLAUDE.md +57 -1
- package/core/Worker.js +420 -9
- package/core/create-handler.js +20 -0
- package/core/index.js +6 -0
- package/core/invocation-deadline.js +91 -0
- package/core/invocation-scope.js +30 -24
- package/core/rate-limited-response.js +27 -0
- package/database/encryption/field-encryption-service.js +42 -0
- package/database/encryption/prisma-encryption-extension.js +6 -9
- package/encrypt/Cryptor.js +90 -38
- package/errors/fetch-error.js +10 -6
- package/errors/index.js +2 -0
- package/errors/rate-limit-error.js +46 -0
- package/generated/prisma-mongodb/edge.js +6 -2
- package/generated/prisma-mongodb/index.js +10 -2
- package/generated/prisma-mongodb/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
- package/generated/prisma-mongodb/package.json +1 -1
- package/generated/prisma-mongodb/schema.prisma +1 -1
- package/generated/prisma-mongodb/wasm.js +6 -2
- package/generated/prisma-postgresql/edge.js +6 -2
- package/generated/prisma-postgresql/index.js +10 -2
- package/generated/prisma-postgresql/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
- package/generated/prisma-postgresql/package.json +1 -1
- package/generated/prisma-postgresql/schema.prisma +1 -1
- package/generated/prisma-postgresql/wasm.js +6 -2
- package/handlers/app-handler-helpers.js +15 -0
- package/handlers/backend-utils.js +75 -1
- package/handlers/workers/integration-defined-workers.js +2 -0
- package/index.js +18 -0
- package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +2 -0
- package/integrations/repositories/integration-repository-documentdb.js +59 -10
- package/integrations/repositories/integration-repository-interface.js +50 -7
- package/integrations/repositories/integration-repository-mongo.js +88 -16
- package/integrations/repositories/integration-repository-postgres.js +89 -16
- package/integrations/repositories/message-item-shared.js +17 -0
- package/integrations/tests/doubles/prisma-message-row.js +24 -0
- package/integrations/tests/doubles/test-integration-repository.js +32 -2
- package/integrations/use-cases/clear-rate-limit-wait.js +28 -0
- package/integrations/use-cases/index.js +7 -1
- package/integrations/use-cases/record-rate-limit-message.js +104 -0
- package/integrations/use-cases/record-rate-limit-wait.js +36 -0
- package/integrations/use-cases/update-integration-messages.js +28 -9
- package/logs/serialize.js +15 -0
- package/modules/requester/oauth-2.js +8 -0
- package/modules/requester/rate-limit/index.js +4 -0
- package/modules/requester/rate-limit/parsers.js +249 -0
- package/modules/requester/rate-limit/policy.js +321 -0
- package/modules/requester/requester.js +187 -9
- package/package.json +7 -6
- package/prisma-mongodb/schema.prisma +1 -1
- package/prisma-postgresql/schema.prisma +1 -1
- package/queues/queue-deferral.js +80 -0
- package/queues/queue-delivery.js +1 -0
- package/queues/queuer-util.js +1 -1
- package/telemetry/otel-telemetry.js +76 -3
- package/telemetry/telemetry-config.js +16 -5
- package/telemetry/telemetry-runtime.js +14 -1
- package/types/core/consumer.fixture.ts +12 -0
- package/types/core/index.d.ts +84 -0
- package/types/errors/index.d.ts +47 -0
- package/types/integrations/index.d.ts +25 -4
- package/types/module-plugin/index.d.ts +45 -0
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
const { readRateLimitPolicy } = require('../../modules/requester/rate-limit');
|
|
2
|
+
const { MAX_MESSAGES_PER_TYPE } = require('./update-integration-messages');
|
|
3
|
+
|
|
4
|
+
const RATE_LIMITED_MESSAGE_CODE = 'RATE_LIMITED';
|
|
5
|
+
const SAME_LIMIT_WINDOW_MS = 60_000;
|
|
6
|
+
const MINUTE_MS = 60_000;
|
|
7
|
+
|
|
8
|
+
const isNonEmptyString = (value) => typeof value === 'string' && value !== '';
|
|
9
|
+
|
|
10
|
+
const isLink = (link) =>
|
|
11
|
+
typeof link?.label === 'string' && typeof link?.url === 'string';
|
|
12
|
+
|
|
13
|
+
const linkActions = (links) =>
|
|
14
|
+
(Array.isArray(links) ? links : [])
|
|
15
|
+
.filter(isLink)
|
|
16
|
+
.map(({ label, url }) => ({ type: 'LINK', label, url }));
|
|
17
|
+
|
|
18
|
+
function formatMinuteUtc(date) {
|
|
19
|
+
const minute = new Date(Math.ceil(date.getTime() / MINUTE_MS) * MINUTE_MS);
|
|
20
|
+
return `${minute.toISOString().slice(0, 16).replace('T', ' ')} UTC`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function defaultText(module, retryAt, capped) {
|
|
24
|
+
if (capped) {
|
|
25
|
+
return `The ${module} API rate limit was reached for longer than the integration waits. Some work may not complete.`;
|
|
26
|
+
}
|
|
27
|
+
return `The ${module} API rate limit was reached. The integration tries again at ${formatMinuteUtc(
|
|
28
|
+
retryAt
|
|
29
|
+
)}.`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Writes the client-safe RATE_LIMITED warning of ADR-049 section 5. The text
|
|
34
|
+
* and the links come from the `userHints` of the module's `static rateLimit`,
|
|
35
|
+
* keyed by reason.
|
|
36
|
+
* @class RecordRateLimitMessage
|
|
37
|
+
*/
|
|
38
|
+
class RecordRateLimitMessage {
|
|
39
|
+
/**
|
|
40
|
+
* @param {Object} params
|
|
41
|
+
* @param {import('../repositories/integration-repository-interface').IntegrationRepositoryInterface} params.integrationRepository
|
|
42
|
+
* @param {Array<{moduleName: string, API: Function}>} [params.moduleDefinitions] - The API module definitions of the integration.
|
|
43
|
+
*/
|
|
44
|
+
constructor({ integrationRepository, moduleDefinitions = [] }) {
|
|
45
|
+
if (!integrationRepository) {
|
|
46
|
+
throw new Error('integrationRepository is required');
|
|
47
|
+
}
|
|
48
|
+
this.integrationRepository = integrationRepository;
|
|
49
|
+
this.moduleDefinitions = moduleDefinitions;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* @param {string} integrationId
|
|
54
|
+
* @param {Object} limit
|
|
55
|
+
* @param {string} limit.module - The module that the RATE_LIMITED event names.
|
|
56
|
+
* @param {string} [limit.reason]
|
|
57
|
+
* @param {Date} limit.retryAt - The retry time, or the probe time when the provider gave none.
|
|
58
|
+
* @param {boolean} [limit.capped] - True when a cap ended the deferrals.
|
|
59
|
+
* @returns {Promise<boolean>} True when it wrote the warning. False when
|
|
60
|
+
* the same limit is stored already, or the event names no module.
|
|
61
|
+
*/
|
|
62
|
+
async execute(integrationId, { module, reason, retryAt, capped = false }) {
|
|
63
|
+
if (!isNonEmptyString(module)) return false;
|
|
64
|
+
const hint = this._userHint(module, reason);
|
|
65
|
+
const item = {
|
|
66
|
+
title: 'Rate limit reached',
|
|
67
|
+
message: isNonEmptyString(hint?.message)
|
|
68
|
+
? hint.message
|
|
69
|
+
: defaultText(module, retryAt, capped),
|
|
70
|
+
timestamp: Date.now(),
|
|
71
|
+
code: RATE_LIMITED_MESSAGE_CODE,
|
|
72
|
+
module,
|
|
73
|
+
reason: reason ?? 'unknown',
|
|
74
|
+
retryAt: retryAt.toISOString(),
|
|
75
|
+
actions: [
|
|
76
|
+
{ type: 'RETRY_WHEN_READY' },
|
|
77
|
+
...linkActions(hint?.links),
|
|
78
|
+
],
|
|
79
|
+
};
|
|
80
|
+
return this.integrationRepository.appendRateLimitMessage(
|
|
81
|
+
integrationId,
|
|
82
|
+
'warnings',
|
|
83
|
+
item,
|
|
84
|
+
{
|
|
85
|
+
retryAtFrom: new Date(
|
|
86
|
+
retryAt.getTime() - SAME_LIMIT_WINDOW_MS
|
|
87
|
+
).toISOString(),
|
|
88
|
+
retryAtTo: new Date(
|
|
89
|
+
retryAt.getTime() + SAME_LIMIT_WINDOW_MS
|
|
90
|
+
).toISOString(),
|
|
91
|
+
keepLast: MAX_MESSAGES_PER_TYPE,
|
|
92
|
+
}
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
_userHint(module, reason) {
|
|
97
|
+
const definition = this.moduleDefinitions.find(
|
|
98
|
+
(candidate) => candidate?.moduleName === module
|
|
99
|
+
);
|
|
100
|
+
return readRateLimitPolicy(definition?.API)?.userHints?.[reason];
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
module.exports = { RATE_LIMITED_MESSAGE_CODE, RecordRateLimitMessage };
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
const keepsCurrentRateLimit = (current, next) => {
|
|
2
|
+
if (!current) return false;
|
|
3
|
+
if (next.status === 'EXHAUSTED') return false;
|
|
4
|
+
if (current.status === 'EXHAUSTED') return true;
|
|
5
|
+
return Date.parse(current.retryAt) > next.retryAt.getTime();
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
class RecordRateLimitWait {
|
|
9
|
+
constructor({ processRepository }) {
|
|
10
|
+
if (!processRepository) {
|
|
11
|
+
throw new Error('processRepository is required');
|
|
12
|
+
}
|
|
13
|
+
this.processRepository = processRepository;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async execute(processId, wait) {
|
|
17
|
+
const process = await this.processRepository.findById(processId);
|
|
18
|
+
if (keepsCurrentRateLimit(process?.context?.rateLimit, wait)) return;
|
|
19
|
+
await this.processRepository.applyProcessUpdate(processId, {
|
|
20
|
+
set: {
|
|
21
|
+
'context.rateLimit': {
|
|
22
|
+
status: wait.status,
|
|
23
|
+
mechanism: wait.mechanism,
|
|
24
|
+
retryAt: wait.retryAt.toISOString(),
|
|
25
|
+
reason: wait.reason,
|
|
26
|
+
module: wait.module,
|
|
27
|
+
deferrals: wait.deferrals,
|
|
28
|
+
deferralId: wait.deferralId,
|
|
29
|
+
updatedAt: new Date().toISOString(),
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
module.exports = { RecordRateLimitWait };
|
|
@@ -1,3 +1,17 @@
|
|
|
1
|
+
const MAX_MESSAGES_PER_TYPE = 50;
|
|
2
|
+
|
|
3
|
+
const isPlainObject = (value) =>
|
|
4
|
+
value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
5
|
+
|
|
6
|
+
function toMessageItem(titleOrItem, messageBody, messageTimestamp) {
|
|
7
|
+
if (isPlainObject(titleOrItem)) return { ...titleOrItem };
|
|
8
|
+
return {
|
|
9
|
+
title: titleOrItem,
|
|
10
|
+
message: messageBody,
|
|
11
|
+
timestamp: messageTimestamp,
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
|
|
1
15
|
/**
|
|
2
16
|
* Use case for updating messages associated with an integration.
|
|
3
17
|
* @class UpdateIntegrationMessages
|
|
@@ -13,19 +27,21 @@ class UpdateIntegrationMessages {
|
|
|
13
27
|
}
|
|
14
28
|
|
|
15
29
|
/**
|
|
16
|
-
* Executes the integration messages update.
|
|
30
|
+
* Executes the integration messages update. Pass the positional form
|
|
31
|
+
* (title, body, timestamp) or one message item object; the keys of an item
|
|
32
|
+
* object are stored as they are.
|
|
17
33
|
* @async
|
|
18
34
|
* @param {string} integrationId - ID of the integration to update.
|
|
19
35
|
* @param {string} messageType - Type of message: 'errors', 'warnings', 'info', or 'logs'.
|
|
20
|
-
* @param {string}
|
|
21
|
-
* @param {string} messageBody - Body content of the message.
|
|
22
|
-
* @param {string} messageTimestamp - Timestamp when the message was created.
|
|
36
|
+
* @param {string|Object} messageTitleOrItem - Title of the message, or the whole message item.
|
|
37
|
+
* @param {string} [messageBody] - Body content of the message (positional form).
|
|
38
|
+
* @param {string} [messageTimestamp] - Timestamp when the message was created (positional form).
|
|
23
39
|
* @returns {Promise<Object>} The updated integration record.
|
|
24
40
|
*/
|
|
25
41
|
async execute(
|
|
26
42
|
integrationId,
|
|
27
43
|
messageType,
|
|
28
|
-
|
|
44
|
+
messageTitleOrItem,
|
|
29
45
|
messageBody,
|
|
30
46
|
messageTimestamp
|
|
31
47
|
) {
|
|
@@ -33,12 +49,15 @@ class UpdateIntegrationMessages {
|
|
|
33
49
|
await this.integrationRepository.updateIntegrationMessages(
|
|
34
50
|
integrationId,
|
|
35
51
|
messageType,
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
52
|
+
toMessageItem(
|
|
53
|
+
messageTitleOrItem,
|
|
54
|
+
messageBody,
|
|
55
|
+
messageTimestamp
|
|
56
|
+
),
|
|
57
|
+
{ keepLast: MAX_MESSAGES_PER_TYPE }
|
|
39
58
|
);
|
|
40
59
|
return integration;
|
|
41
60
|
}
|
|
42
61
|
}
|
|
43
62
|
|
|
44
|
-
module.exports = { UpdateIntegrationMessages };
|
|
63
|
+
module.exports = { MAX_MESSAGES_PER_TYPE, UpdateIntegrationMessages };
|
package/logs/serialize.js
CHANGED
|
@@ -235,6 +235,20 @@ function errorCode(err) {
|
|
|
235
235
|
return undefined;
|
|
236
236
|
}
|
|
237
237
|
|
|
238
|
+
function rateLimitFields(err) {
|
|
239
|
+
const retryAt = attempt(
|
|
240
|
+
() => (err.isRateLimited ? err.retryAt : undefined),
|
|
241
|
+
undefined
|
|
242
|
+
);
|
|
243
|
+
if (!(retryAt instanceof Date) || Number.isNaN(retryAt.getTime())) {
|
|
244
|
+
return {};
|
|
245
|
+
}
|
|
246
|
+
const reason = attempt(() => err.reason, undefined);
|
|
247
|
+
return typeof reason === 'string'
|
|
248
|
+
? { retryAt: retryAt.toISOString(), reason: cleanString(reason) }
|
|
249
|
+
: { retryAt: retryAt.toISOString() };
|
|
250
|
+
}
|
|
251
|
+
|
|
238
252
|
function errorStack(err, type, message) {
|
|
239
253
|
const stack = attempt(() => err.stack, undefined);
|
|
240
254
|
if (typeof stack !== 'string') return undefined;
|
|
@@ -279,6 +293,7 @@ function serializeErrorAt(err, depth, seen) {
|
|
|
279
293
|
if (code !== undefined) out.code = code;
|
|
280
294
|
const status = errorStatus(err);
|
|
281
295
|
if (status !== undefined) out.status = status;
|
|
296
|
+
Object.assign(out, rateLimitFields(err));
|
|
282
297
|
const stack = errorStack(err, type, message);
|
|
283
298
|
if (stack !== undefined) out.stack = stack;
|
|
284
299
|
|
|
@@ -398,6 +398,14 @@ class OAuth2Requester extends Requester {
|
|
|
398
398
|
);
|
|
399
399
|
transportError.statusCode = status;
|
|
400
400
|
transportError.isTokenRefreshTransportFailure = true;
|
|
401
|
+
if (error?.isRateLimited) {
|
|
402
|
+
transportError.isRateLimited = true;
|
|
403
|
+
transportError.retryAt = error.retryAt;
|
|
404
|
+
transportError.waitMs = error.waitMs;
|
|
405
|
+
transportError.reason = error.reason;
|
|
406
|
+
transportError.module = error.module;
|
|
407
|
+
transportError.scopeKey = error.scopeKey;
|
|
408
|
+
}
|
|
401
409
|
return transportError;
|
|
402
410
|
}
|
|
403
411
|
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
const MAX_HINT_WAIT_MS = 366 * 24 * 60 * 60 * 1000;
|
|
2
|
+
|
|
3
|
+
const SECONDS_PATTERN = /^\d+(?:\.\d+)?$/;
|
|
4
|
+
const HAS_LETTER = /[A-Za-z]/;
|
|
5
|
+
const EPOCH_SECONDS_MIN = 1e9;
|
|
6
|
+
const EPOCH_MILLISECONDS_MIN = 1e12;
|
|
7
|
+
|
|
8
|
+
const RESET_HEADERS = [
|
|
9
|
+
'x-ratelimit-reset',
|
|
10
|
+
'ratelimit-reset',
|
|
11
|
+
'x-rate-limit-reset',
|
|
12
|
+
];
|
|
13
|
+
const REMAINING_HEADERS = [
|
|
14
|
+
'x-ratelimit-remaining',
|
|
15
|
+
'ratelimit-remaining',
|
|
16
|
+
'x-rate-limit-remaining',
|
|
17
|
+
];
|
|
18
|
+
|
|
19
|
+
const isMissing = (value) => value === undefined || value === null;
|
|
20
|
+
|
|
21
|
+
function readEntries(headers, wanted) {
|
|
22
|
+
for (const entry of headers) {
|
|
23
|
+
if (Array.isArray(entry) && String(entry[0]).toLowerCase() === wanted) {
|
|
24
|
+
return entry[1];
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function readKeys(headers, wanted) {
|
|
31
|
+
for (const key of Object.keys(headers)) {
|
|
32
|
+
if (key.toLowerCase() === wanted) return headers[key];
|
|
33
|
+
}
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function headerValue(headers, name) {
|
|
38
|
+
if (!headers || typeof headers !== 'object') return undefined;
|
|
39
|
+
const wanted = name.toLowerCase();
|
|
40
|
+
const hasGet = typeof headers.get === 'function';
|
|
41
|
+
|
|
42
|
+
let value;
|
|
43
|
+
if (hasGet) {
|
|
44
|
+
value = headers.get(name);
|
|
45
|
+
if (isMissing(value)) value = headers.get(wanted);
|
|
46
|
+
}
|
|
47
|
+
if (isMissing(value) && typeof headers[Symbol.iterator] === 'function') {
|
|
48
|
+
value = readEntries(headers, wanted);
|
|
49
|
+
}
|
|
50
|
+
if (isMissing(value) && !hasGet && !Array.isArray(headers)) {
|
|
51
|
+
value = readKeys(headers, wanted);
|
|
52
|
+
}
|
|
53
|
+
if (Array.isArray(value)) value = value[0];
|
|
54
|
+
if (isMissing(value)) return undefined;
|
|
55
|
+
|
|
56
|
+
const text = String(value).trim();
|
|
57
|
+
return text === '' ? undefined : text;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function definedOnly(fields) {
|
|
61
|
+
const result = {};
|
|
62
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
63
|
+
if (value !== undefined) result[key] = value;
|
|
64
|
+
}
|
|
65
|
+
return result;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function hintFromWait(waitMs, now, { source = 'header', ...extra } = {}) {
|
|
69
|
+
if (!Number.isFinite(waitMs) || waitMs < 0 || waitMs > MAX_HINT_WAIT_MS) {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
return {
|
|
73
|
+
waitMs,
|
|
74
|
+
retryAt: new Date(now + waitMs),
|
|
75
|
+
...definedOnly(extra),
|
|
76
|
+
source,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function hintFromRetryAt(retryAt, now, { source = 'header', ...extra } = {}) {
|
|
81
|
+
const at = retryAt instanceof Date ? retryAt.getTime() : Number.NaN;
|
|
82
|
+
if (Number.isNaN(at)) return null;
|
|
83
|
+
const waitMs = Math.max(0, at - now);
|
|
84
|
+
if (waitMs > MAX_HINT_WAIT_MS) return null;
|
|
85
|
+
return { waitMs, retryAt: new Date(at), ...definedOnly(extra), source };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function parseDate(text) {
|
|
89
|
+
if (!HAS_LETTER.test(text)) return null;
|
|
90
|
+
const at = Date.parse(text);
|
|
91
|
+
return Number.isNaN(at) ? null : new Date(at);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function parseRetryAfter(value, { now = Date.now() } = {}) {
|
|
95
|
+
if (isMissing(value)) return null;
|
|
96
|
+
const text = String(value).trim();
|
|
97
|
+
if (text === '') return null;
|
|
98
|
+
if (SECONDS_PATTERN.test(text))
|
|
99
|
+
return hintFromWait(Number(text) * 1000, now);
|
|
100
|
+
const date = parseDate(text);
|
|
101
|
+
return date ? hintFromRetryAt(date, now) : null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function numberOrUndefined(text) {
|
|
105
|
+
if (text === undefined) return undefined;
|
|
106
|
+
const number = Number(text);
|
|
107
|
+
return Number.isFinite(number) ? number : undefined;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function firstHeader(headers, names) {
|
|
111
|
+
for (const name of names) {
|
|
112
|
+
const value = headerValue(headers, name);
|
|
113
|
+
if (value !== undefined) return value;
|
|
114
|
+
}
|
|
115
|
+
return undefined;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function parseResetValue(text, now, deltaToMs, extra) {
|
|
119
|
+
if (SECONDS_PATTERN.test(text)) {
|
|
120
|
+
const number = Number(text);
|
|
121
|
+
if (number >= EPOCH_MILLISECONDS_MIN) {
|
|
122
|
+
return hintFromRetryAt(new Date(number), now, extra);
|
|
123
|
+
}
|
|
124
|
+
if (number >= EPOCH_SECONDS_MIN) {
|
|
125
|
+
return hintFromRetryAt(new Date(number * 1000), now, extra);
|
|
126
|
+
}
|
|
127
|
+
return hintFromWait(number * deltaToMs, now, extra);
|
|
128
|
+
}
|
|
129
|
+
const date = parseDate(text);
|
|
130
|
+
return date ? hintFromRetryAt(date, now, extra) : null;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function parseResetHeaders(
|
|
134
|
+
headers,
|
|
135
|
+
{ now = Date.now(), resetDeltaUnit = 's' } = {}
|
|
136
|
+
) {
|
|
137
|
+
const remaining = numberOrUndefined(
|
|
138
|
+
firstHeader(headers, REMAINING_HEADERS)
|
|
139
|
+
);
|
|
140
|
+
const extra = { remaining };
|
|
141
|
+
const deltaToMs = resetDeltaUnit === 'ms' ? 1 : 1000;
|
|
142
|
+
|
|
143
|
+
const after = headerValue(headers, 'x-ratelimit-reset-after');
|
|
144
|
+
if (after !== undefined && SECONDS_PATTERN.test(after)) {
|
|
145
|
+
return hintFromWait(Number(after) * deltaToMs, now, extra);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
for (const name of RESET_HEADERS) {
|
|
149
|
+
const value = headerValue(headers, name);
|
|
150
|
+
if (value === undefined) continue;
|
|
151
|
+
const hint = parseResetValue(value, now, deltaToMs, extra);
|
|
152
|
+
if (hint) return hint;
|
|
153
|
+
}
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function splitList(text) {
|
|
158
|
+
const items = [];
|
|
159
|
+
let current = '';
|
|
160
|
+
let quoted = false;
|
|
161
|
+
for (const char of text) {
|
|
162
|
+
if (char === '"') quoted = !quoted;
|
|
163
|
+
if (char === ',' && !quoted) {
|
|
164
|
+
items.push(current);
|
|
165
|
+
current = '';
|
|
166
|
+
} else {
|
|
167
|
+
current += char;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
items.push(current);
|
|
171
|
+
return items.map((item) => item.trim()).filter(Boolean);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function parseStructuredItem(item) {
|
|
175
|
+
const [head, ...params] = item.split(';').map((part) => part.trim());
|
|
176
|
+
const values = {};
|
|
177
|
+
for (const param of params) {
|
|
178
|
+
const [key, raw] = param.split('=').map((part) => part.trim());
|
|
179
|
+
if (key) values[key] = numberOrUndefined(raw);
|
|
180
|
+
}
|
|
181
|
+
const name = head.replace(/^"|"$/g, '');
|
|
182
|
+
return {
|
|
183
|
+
name: name || undefined,
|
|
184
|
+
remaining: values.r,
|
|
185
|
+
waitSeconds: values.t,
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function pickStructured(items) {
|
|
190
|
+
const usable = items.filter(
|
|
191
|
+
(item) => Number.isFinite(item.waitSeconds) && item.waitSeconds >= 0
|
|
192
|
+
);
|
|
193
|
+
usable.sort((a, b) => {
|
|
194
|
+
const byRemaining =
|
|
195
|
+
(a.remaining ?? Infinity) - (b.remaining ?? Infinity);
|
|
196
|
+
if (byRemaining !== 0 && !Number.isNaN(byRemaining)) return byRemaining;
|
|
197
|
+
return b.waitSeconds - a.waitSeconds;
|
|
198
|
+
});
|
|
199
|
+
return usable[0];
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function readKeyValue(text, key) {
|
|
203
|
+
const match = new RegExp(
|
|
204
|
+
String.raw`(?:^|[,;\s])${key}\s*=\s*([^,;\s]+)`,
|
|
205
|
+
'i'
|
|
206
|
+
).exec(text);
|
|
207
|
+
return match ? match[1] : undefined;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function parseIetfRateLimit(headers, { now = Date.now() } = {}) {
|
|
211
|
+
const raw = headerValue(headers, 'ratelimit');
|
|
212
|
+
if (raw === undefined) return null;
|
|
213
|
+
const policyHeader = headerValue(headers, 'ratelimit-policy');
|
|
214
|
+
|
|
215
|
+
if (/;\s*t\s*=/.test(raw)) {
|
|
216
|
+
const chosen = pickStructured(splitList(raw).map(parseStructuredItem));
|
|
217
|
+
if (!chosen) return null;
|
|
218
|
+
return hintFromWait(chosen.waitSeconds * 1000, now, {
|
|
219
|
+
remaining: chosen.remaining,
|
|
220
|
+
policy: chosen.name ?? policyHeader,
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const reset = readKeyValue(raw, 'reset');
|
|
225
|
+
if (reset === undefined || !SECONDS_PATTERN.test(reset)) return null;
|
|
226
|
+
return hintFromWait(Number(reset) * 1000, now, {
|
|
227
|
+
remaining: numberOrUndefined(readKeyValue(raw, 'remaining')),
|
|
228
|
+
policy: policyHeader,
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const BUILT_IN_PARSERS = {
|
|
233
|
+
retryAfter: (headers, { now } = {}) =>
|
|
234
|
+
parseRetryAfter(headerValue(headers, 'retry-after'), { now }),
|
|
235
|
+
resetHeaders: parseResetHeaders,
|
|
236
|
+
ietf: parseIetfRateLimit,
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
module.exports = {
|
|
240
|
+
BUILT_IN_PARSERS,
|
|
241
|
+
MAX_HINT_WAIT_MS,
|
|
242
|
+
definedOnly,
|
|
243
|
+
headerValue,
|
|
244
|
+
hintFromRetryAt,
|
|
245
|
+
hintFromWait,
|
|
246
|
+
parseIetfRateLimit,
|
|
247
|
+
parseResetHeaders,
|
|
248
|
+
parseRetryAfter,
|
|
249
|
+
};
|