@friggframework/core 2.0.0-next.128 → 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/errors/fetch-error.js +10 -6
- package/errors/index.js +2 -0
- package/errors/rate-limit-error.js +46 -0
- 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/queues/queue-deferral.js +80 -0
- package/queues/queue-delivery.js +1 -0
- package/queues/queuer-util.js +1 -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
|
@@ -3,6 +3,7 @@ const {
|
|
|
3
3
|
IntegrationRepositoryInterface,
|
|
4
4
|
} = require('./integration-repository-interface');
|
|
5
5
|
const { validateConfigPatch } = require('./config-patch-shared');
|
|
6
|
+
const { MESSAGE_TYPES, messagesOfType } = require('./message-item-shared');
|
|
6
7
|
const { strictIntId } = require('./report-id');
|
|
7
8
|
|
|
8
9
|
/**
|
|
@@ -273,17 +274,16 @@ class IntegrationRepositoryPostgres extends IntegrationRepositoryInterface {
|
|
|
273
274
|
*
|
|
274
275
|
* @param {string} integrationId - Integration ID (string from application layer)
|
|
275
276
|
* @param {string} messageType - Type of message (errors, warnings, info, logs)
|
|
276
|
-
* @param {
|
|
277
|
-
* @param {
|
|
278
|
-
* @param {
|
|
277
|
+
* @param {Object} item - Message item, stored as it is
|
|
278
|
+
* @param {Object} options
|
|
279
|
+
* @param {number} options.keepLast - How many of the newest items of the type to keep
|
|
279
280
|
* @returns {Promise<boolean>} Success indicator
|
|
280
281
|
*/
|
|
281
282
|
async updateIntegrationMessages(
|
|
282
283
|
integrationId,
|
|
283
284
|
messageType,
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
messageTimestamp
|
|
285
|
+
item,
|
|
286
|
+
{ keepLast }
|
|
287
287
|
) {
|
|
288
288
|
const intId = this._convertId(integrationId);
|
|
289
289
|
|
|
@@ -297,29 +297,102 @@ class IntegrationRepositoryPostgres extends IntegrationRepositoryInterface {
|
|
|
297
297
|
}
|
|
298
298
|
|
|
299
299
|
// Parse existing messages (JSON field)
|
|
300
|
-
const
|
|
301
|
-
const messageArray = Array.isArray(messages[messageType])
|
|
302
|
-
? messages[messageType]
|
|
303
|
-
: [];
|
|
300
|
+
const messageArray = messagesOfType(integration, messageType);
|
|
304
301
|
|
|
305
302
|
// Add new message
|
|
306
|
-
messageArray.push(
|
|
307
|
-
title: messageTitle,
|
|
308
|
-
message: messageBody,
|
|
309
|
-
timestamp: messageTimestamp,
|
|
310
|
-
});
|
|
303
|
+
messageArray.push(item);
|
|
311
304
|
|
|
312
305
|
// Update messages
|
|
313
306
|
await this.prisma.integration.update({
|
|
314
307
|
where: { id: intId },
|
|
315
308
|
data: {
|
|
316
|
-
[messageType]: messageArray,
|
|
309
|
+
[messageType]: messageArray.slice(-keepLast),
|
|
317
310
|
},
|
|
318
311
|
});
|
|
319
312
|
|
|
320
313
|
return true; // Mongoose compatibility
|
|
321
314
|
}
|
|
322
315
|
|
|
316
|
+
/**
|
|
317
|
+
* Find the stored messages of one type
|
|
318
|
+
*
|
|
319
|
+
* @param {string} integrationId - Integration ID (string from application layer)
|
|
320
|
+
* @param {string} messageType - Type of message (errors, warnings, info, logs)
|
|
321
|
+
* @returns {Promise<Array>} The stored message items of that type, oldest first
|
|
322
|
+
*/
|
|
323
|
+
async findIntegrationMessages(integrationId, messageType) {
|
|
324
|
+
const intId = this._convertId(integrationId);
|
|
325
|
+
const integration = await this.prisma.integration.findUnique({
|
|
326
|
+
where: { id: intId },
|
|
327
|
+
select: { [messageType]: true },
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
if (!integration) {
|
|
331
|
+
throw new Error(`Integration ${integrationId} not found`);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
return messagesOfType(integration, messageType);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* Append a rate-limit message item unless the same limit is stored.
|
|
339
|
+
* One UPDATE with a NOT EXISTS guard. A concurrent UPDATE of the row
|
|
340
|
+
* waits for the row lock and then evaluates the guard again on the new
|
|
341
|
+
* row, so concurrent workers store one item. retryAt values are ISO UTC
|
|
342
|
+
* strings, so a byte-wise (COLLATE "C") comparison orders them by time.
|
|
343
|
+
*
|
|
344
|
+
* @param {string} integrationId - Integration ID (string from application layer)
|
|
345
|
+
* @param {string} messageType - Type of message (errors, warnings, info, logs)
|
|
346
|
+
* @param {Object} item - Message item with `code`, `module` and an ISO UTC `retryAt`
|
|
347
|
+
* @param {Object} options
|
|
348
|
+
* @param {string} options.retryAtFrom - ISO UTC start of the window, inclusive
|
|
349
|
+
* @param {string} options.retryAtTo - ISO UTC end of the window, inclusive
|
|
350
|
+
* @param {number} options.keepLast - How many of the newest items of the type to keep
|
|
351
|
+
* @returns {Promise<boolean>} True when it appended the item
|
|
352
|
+
*/
|
|
353
|
+
async appendRateLimitMessage(
|
|
354
|
+
integrationId,
|
|
355
|
+
messageType,
|
|
356
|
+
item,
|
|
357
|
+
{ retryAtFrom, retryAtTo, keepLast }
|
|
358
|
+
) {
|
|
359
|
+
if (!MESSAGE_TYPES.includes(messageType)) {
|
|
360
|
+
throw new Error(`Unknown message type: ${messageType}`);
|
|
361
|
+
}
|
|
362
|
+
const column = `"${messageType}"`;
|
|
363
|
+
const stored = `(CASE WHEN jsonb_typeof(${column}) = 'array' THEN ${column} ELSE '[]'::jsonb END)`;
|
|
364
|
+
const sql = `
|
|
365
|
+
UPDATE "Integration"
|
|
366
|
+
SET ${column} = (
|
|
367
|
+
SELECT COALESCE(jsonb_agg(elem ORDER BY idx), '[]'::jsonb)
|
|
368
|
+
FROM jsonb_array_elements(${stored} || jsonb_build_array($1::jsonb))
|
|
369
|
+
WITH ORDINALITY AS t(elem, idx)
|
|
370
|
+
WHERE idx > jsonb_array_length(${stored}) + 1 - $2::int
|
|
371
|
+
),
|
|
372
|
+
"updatedAt" = NOW()
|
|
373
|
+
WHERE "id" = $3
|
|
374
|
+
AND NOT EXISTS (
|
|
375
|
+
SELECT 1
|
|
376
|
+
FROM jsonb_array_elements(${stored}) AS kept(elem)
|
|
377
|
+
WHERE kept.elem ->> 'code' = $4
|
|
378
|
+
AND kept.elem ->> 'module' = $5
|
|
379
|
+
AND (kept.elem ->> 'retryAt') COLLATE "C" BETWEEN $6 AND $7
|
|
380
|
+
)
|
|
381
|
+
RETURNING "id"
|
|
382
|
+
`;
|
|
383
|
+
const rows = await this.prisma.$queryRawUnsafe(
|
|
384
|
+
sql,
|
|
385
|
+
JSON.stringify(item),
|
|
386
|
+
keepLast,
|
|
387
|
+
this._convertId(integrationId),
|
|
388
|
+
item.code,
|
|
389
|
+
item.module,
|
|
390
|
+
retryAtFrom,
|
|
391
|
+
retryAtTo
|
|
392
|
+
);
|
|
393
|
+
return rows.length === 1;
|
|
394
|
+
}
|
|
395
|
+
|
|
323
396
|
/**
|
|
324
397
|
* Create a new integration
|
|
325
398
|
*
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
const MESSAGE_TYPES = Object.freeze(['errors', 'warnings', 'info', 'logs']);
|
|
2
|
+
|
|
3
|
+
const messagesOfType = (record, messageType) =>
|
|
4
|
+
Array.isArray(record[messageType]) ? record[messageType] : [];
|
|
5
|
+
|
|
6
|
+
const sameRateLimitMessage = (
|
|
7
|
+
{ code, module },
|
|
8
|
+
{ retryAtFrom, retryAtTo }
|
|
9
|
+
) => ({
|
|
10
|
+
$elemMatch: {
|
|
11
|
+
code,
|
|
12
|
+
module,
|
|
13
|
+
retryAt: { $gte: retryAtFrom, $lte: retryAtTo },
|
|
14
|
+
},
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
module.exports = { MESSAGE_TYPES, messagesOfType, sameRateLimitMessage };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
const copy = (value) => JSON.parse(JSON.stringify(value));
|
|
2
|
+
|
|
3
|
+
function withMessageRow(repo, id, stored = {}) {
|
|
4
|
+
const row = {
|
|
5
|
+
id,
|
|
6
|
+
errors: [],
|
|
7
|
+
warnings: [],
|
|
8
|
+
info: [],
|
|
9
|
+
logs: [],
|
|
10
|
+
...stored,
|
|
11
|
+
};
|
|
12
|
+
repo.prisma = {
|
|
13
|
+
integration: {
|
|
14
|
+
findUnique: jest.fn(async () => copy(row)),
|
|
15
|
+
update: jest.fn(async ({ data }) => {
|
|
16
|
+
Object.assign(row, copy(data));
|
|
17
|
+
return copy(row);
|
|
18
|
+
}),
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
return { repo, row };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
module.exports = { withMessageRow };
|
|
@@ -72,18 +72,48 @@ class TestIntegrationRepository {
|
|
|
72
72
|
return results;
|
|
73
73
|
}
|
|
74
74
|
|
|
75
|
-
async updateIntegrationMessages(id, type,
|
|
75
|
+
async updateIntegrationMessages(id, type, item, { keepLast }) {
|
|
76
76
|
const rec = this.store.get(id);
|
|
77
77
|
if (!rec) {
|
|
78
78
|
this.operationHistory.push({ operation: 'updateMessages', id, success: false });
|
|
79
79
|
return false;
|
|
80
80
|
}
|
|
81
81
|
if (!rec.messages[type]) rec.messages[type] = [];
|
|
82
|
-
rec.messages[type].push(
|
|
82
|
+
rec.messages[type].push(item);
|
|
83
|
+
rec.messages[type] = rec.messages[type].slice(-keepLast);
|
|
83
84
|
this.operationHistory.push({ operation: 'updateMessages', id, type, success: true });
|
|
84
85
|
return true;
|
|
85
86
|
}
|
|
86
87
|
|
|
88
|
+
async findIntegrationMessages(id, type) {
|
|
89
|
+
const rec = this.store.get(id);
|
|
90
|
+
this.operationHistory.push({
|
|
91
|
+
operation: 'findMessages',
|
|
92
|
+
id,
|
|
93
|
+
type,
|
|
94
|
+
found: !!rec,
|
|
95
|
+
});
|
|
96
|
+
if (!rec) throw new Error(`Integration ${id} not found`);
|
|
97
|
+
return [...(rec.messages[type] ?? [])];
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async appendRateLimitMessage(id, type, item, { retryAtFrom, retryAtTo, keepLast }) {
|
|
101
|
+
const rec = this.store.get(id);
|
|
102
|
+
if (!rec) return false;
|
|
103
|
+
const stored = rec.messages[type] ?? [];
|
|
104
|
+
const sameLimit = stored.some(
|
|
105
|
+
(kept) =>
|
|
106
|
+
kept?.code === item.code &&
|
|
107
|
+
kept.module === item.module &&
|
|
108
|
+
kept.retryAt >= retryAtFrom &&
|
|
109
|
+
kept.retryAt <= retryAtTo
|
|
110
|
+
);
|
|
111
|
+
if (sameLimit) return false;
|
|
112
|
+
rec.messages[type] = [...stored, item].slice(-keepLast);
|
|
113
|
+
this.operationHistory.push({ operation: 'appendRateLimitMessage', id, type });
|
|
114
|
+
return true;
|
|
115
|
+
}
|
|
116
|
+
|
|
87
117
|
async updateIntegrationConfig(id, config) {
|
|
88
118
|
if (config === null || config === undefined) {
|
|
89
119
|
throw new Error('Config parameter is required');
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
const CLEAR_RATE_LIMIT_TOLERANCE_MS = 5_000;
|
|
2
|
+
|
|
3
|
+
const isOwnWait = (current, deferralId) =>
|
|
4
|
+
Boolean(deferralId) && current.deferralId === deferralId;
|
|
5
|
+
|
|
6
|
+
const isOver = (current) =>
|
|
7
|
+
Date.parse(current.retryAt) - Date.now() <= CLEAR_RATE_LIMIT_TOLERANCE_MS;
|
|
8
|
+
|
|
9
|
+
class ClearRateLimitWait {
|
|
10
|
+
constructor({ processRepository }) {
|
|
11
|
+
if (!processRepository) {
|
|
12
|
+
throw new Error('processRepository is required');
|
|
13
|
+
}
|
|
14
|
+
this.processRepository = processRepository;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
async execute(processId, { deferralId } = {}) {
|
|
18
|
+
const process = await this.processRepository.findById(processId);
|
|
19
|
+
const current = process?.context?.rateLimit;
|
|
20
|
+
if (current?.status !== 'WAITING') return;
|
|
21
|
+
if (!isOwnWait(current, deferralId) && !isOver(current)) return;
|
|
22
|
+
await this.processRepository.applyProcessUpdate(processId, {
|
|
23
|
+
set: { 'context.rateLimit': null },
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
module.exports = { ClearRateLimitWait };
|
|
@@ -6,6 +6,9 @@ const { CreateProcess } = require('./create-process');
|
|
|
6
6
|
const { UpdateProcessState } = require('./update-process-state');
|
|
7
7
|
const { UpdateProcessMetrics } = require('./update-process-metrics');
|
|
8
8
|
const { GetProcess } = require('./get-process');
|
|
9
|
+
const { RecordRateLimitWait } = require('./record-rate-limit-wait');
|
|
10
|
+
const { ClearRateLimitWait } = require('./clear-rate-limit-wait');
|
|
11
|
+
const { RecordRateLimitMessage } = require('./record-rate-limit-message');
|
|
9
12
|
|
|
10
13
|
module.exports = {
|
|
11
14
|
GetIntegrationsForUser,
|
|
@@ -16,4 +19,7 @@ module.exports = {
|
|
|
16
19
|
UpdateProcessState,
|
|
17
20
|
UpdateProcessMetrics,
|
|
18
21
|
GetProcess,
|
|
19
|
-
|
|
22
|
+
RecordRateLimitWait,
|
|
23
|
+
ClearRateLimitWait,
|
|
24
|
+
RecordRateLimitMessage,
|
|
25
|
+
};
|
|
@@ -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
|
|