@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
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
14
|
const { SchedulerServiceInterface } = require('./scheduler-service-interface');
|
|
15
|
+
const { awsConfigOptions } = require('../../queues/queuer-util');
|
|
15
16
|
|
|
16
17
|
const SCHEDULER_SDK = '@aws-sdk/client-scheduler';
|
|
17
18
|
|
|
@@ -72,6 +73,7 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
|
|
|
72
73
|
};
|
|
73
74
|
this.client = new SchedulerClient({
|
|
74
75
|
region: region || process.env.AWS_REGION || 'us-east-1',
|
|
76
|
+
...awsConfigOptions(),
|
|
75
77
|
});
|
|
76
78
|
this.scheduleGroupName =
|
|
77
79
|
process.env.SCHEDULE_GROUP_NAME || 'frigg-integration-schedules';
|
|
@@ -14,6 +14,10 @@ const {
|
|
|
14
14
|
IntegrationRepositoryInterface,
|
|
15
15
|
} = require('./integration-repository-interface');
|
|
16
16
|
const { validateConfigPatch } = require('./config-patch-shared');
|
|
17
|
+
const {
|
|
18
|
+
messagesOfType,
|
|
19
|
+
sameRateLimitMessage,
|
|
20
|
+
} = require('./message-item-shared');
|
|
17
21
|
|
|
18
22
|
class IntegrationRepositoryDocumentDB extends IntegrationRepositoryInterface {
|
|
19
23
|
constructor() {
|
|
@@ -94,9 +98,8 @@ class IntegrationRepositoryDocumentDB extends IntegrationRepositoryInterface {
|
|
|
94
98
|
async updateIntegrationMessages(
|
|
95
99
|
integrationId,
|
|
96
100
|
messageType,
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
messageTimestamp
|
|
101
|
+
item,
|
|
102
|
+
{ keepLast }
|
|
100
103
|
) {
|
|
101
104
|
const objectId = toObjectId(integrationId);
|
|
102
105
|
if (!objectId) {
|
|
@@ -107,13 +110,12 @@ class IntegrationRepositoryDocumentDB extends IntegrationRepositoryInterface {
|
|
|
107
110
|
throw new Error(`Integration ${integrationId} not found`);
|
|
108
111
|
}
|
|
109
112
|
const messages = this._extractMessages(existing);
|
|
110
|
-
const list =
|
|
111
|
-
list.push({
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
}
|
|
116
|
-
const updatedMessages = { ...messages, [messageType]: list };
|
|
113
|
+
const list = [...messagesOfType(messages, messageType)];
|
|
114
|
+
list.push({ ...item, title: item.title ?? null });
|
|
115
|
+
const updatedMessages = {
|
|
116
|
+
...messages,
|
|
117
|
+
[messageType]: list.slice(-keepLast),
|
|
118
|
+
};
|
|
117
119
|
await updateOne(
|
|
118
120
|
this.prisma,
|
|
119
121
|
'Integration',
|
|
@@ -132,6 +134,53 @@ class IntegrationRepositoryDocumentDB extends IntegrationRepositoryInterface {
|
|
|
132
134
|
return true;
|
|
133
135
|
}
|
|
134
136
|
|
|
137
|
+
async findIntegrationMessages(integrationId, messageType) {
|
|
138
|
+
const objectId = toObjectId(integrationId);
|
|
139
|
+
if (!objectId) {
|
|
140
|
+
throw new Error(`Integration ${integrationId} not found`);
|
|
141
|
+
}
|
|
142
|
+
const existing = await findOne(this.prisma, 'Integration', {
|
|
143
|
+
_id: objectId,
|
|
144
|
+
});
|
|
145
|
+
if (!existing) {
|
|
146
|
+
throw new Error(`Integration ${integrationId} not found`);
|
|
147
|
+
}
|
|
148
|
+
return messagesOfType(this._extractMessages(existing), messageType);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// Writes both stored copies (`messages.<type>` and `<type>`), which
|
|
152
|
+
// _extractMessages reads.
|
|
153
|
+
async appendRateLimitMessage(
|
|
154
|
+
integrationId,
|
|
155
|
+
messageType,
|
|
156
|
+
item,
|
|
157
|
+
{ retryAtFrom, retryAtTo, keepLast }
|
|
158
|
+
) {
|
|
159
|
+
const objectId = toObjectId(integrationId);
|
|
160
|
+
if (!objectId) return false;
|
|
161
|
+
const sameLimit = sameRateLimitMessage(item, { retryAtFrom, retryAtTo });
|
|
162
|
+
const push = { $each: [item], $slice: -keepLast };
|
|
163
|
+
const nested = `messages.${messageType}`;
|
|
164
|
+
const result = await updateOne(
|
|
165
|
+
this.prisma,
|
|
166
|
+
'Integration',
|
|
167
|
+
{
|
|
168
|
+
_id: objectId,
|
|
169
|
+
$nor: [{ [messageType]: sameLimit }, { [nested]: sameLimit }],
|
|
170
|
+
},
|
|
171
|
+
{
|
|
172
|
+
$push: { [messageType]: push, [nested]: push },
|
|
173
|
+
$set: { updatedAt: new Date() },
|
|
174
|
+
}
|
|
175
|
+
);
|
|
176
|
+
if (result?.writeErrors?.length) {
|
|
177
|
+
throw new Error(
|
|
178
|
+
`Failed to append rate-limit message: ${result.writeErrors[0].errmsg}`
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
return result?.n === 1;
|
|
182
|
+
}
|
|
183
|
+
|
|
135
184
|
async createIntegration(entities, userId, config) {
|
|
136
185
|
const now = new Date();
|
|
137
186
|
const document = {
|
|
@@ -97,26 +97,69 @@ class IntegrationRepositoryInterface {
|
|
|
97
97
|
}
|
|
98
98
|
|
|
99
99
|
/**
|
|
100
|
-
*
|
|
100
|
+
* Append a message item to the stored messages of one type
|
|
101
101
|
*
|
|
102
102
|
* @param {string|number} integrationId - Integration ID
|
|
103
103
|
* @param {string} messageType - Type of message (errors, warnings, info, logs)
|
|
104
|
-
* @param {
|
|
105
|
-
* @param {
|
|
106
|
-
* @param {
|
|
104
|
+
* @param {Object} item - Message item, stored as it is
|
|
105
|
+
* @param {Object} options
|
|
106
|
+
* @param {number} options.keepLast - How many of the newest items of the type to keep
|
|
107
107
|
* @returns {Promise<boolean>} Success indicator
|
|
108
108
|
* @abstract
|
|
109
109
|
*/
|
|
110
110
|
async updateIntegrationMessages(
|
|
111
111
|
integrationId,
|
|
112
112
|
messageType,
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
messageTimestamp
|
|
113
|
+
item,
|
|
114
|
+
{ keepLast }
|
|
116
115
|
) {
|
|
117
116
|
throw new Error('Method updateIntegrationMessages must be implemented by subclass');
|
|
118
117
|
}
|
|
119
118
|
|
|
119
|
+
/**
|
|
120
|
+
* Find the stored messages of one type. Reads the stored items, not the
|
|
121
|
+
* `messages` of an integration record, which some adapters do not fill.
|
|
122
|
+
*
|
|
123
|
+
* @param {string|number} integrationId - Integration ID
|
|
124
|
+
* @param {string} messageType - Type of message (errors, warnings, info, logs)
|
|
125
|
+
* @returns {Promise<Array>} The stored message items of that type, oldest first
|
|
126
|
+
* @abstract
|
|
127
|
+
*/
|
|
128
|
+
async findIntegrationMessages(integrationId, messageType) {
|
|
129
|
+
throw new Error(
|
|
130
|
+
'Method findIntegrationMessages must be implemented by subclass'
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Append a rate-limit message item in one atomic write, unless a stored
|
|
136
|
+
* item of the type has the same `code` and `module` as `item` and a
|
|
137
|
+
* `retryAt` from `retryAtFrom` to `retryAtTo`. Keeps the newest
|
|
138
|
+
* `keepLast` items of the type. Concurrent calls for the same limit
|
|
139
|
+
* store one item.
|
|
140
|
+
*
|
|
141
|
+
* @param {string|number} integrationId - Integration ID
|
|
142
|
+
* @param {string} messageType - Type of message (errors, warnings, info, logs)
|
|
143
|
+
* @param {Object} item - Message item with `code`, `module` and an ISO UTC `retryAt`
|
|
144
|
+
* @param {Object} options
|
|
145
|
+
* @param {string} options.retryAtFrom - ISO UTC start of the window, inclusive
|
|
146
|
+
* @param {string} options.retryAtTo - ISO UTC end of the window, inclusive
|
|
147
|
+
* @param {number} options.keepLast - How many of the newest items of the type to keep
|
|
148
|
+
* @returns {Promise<boolean>} True when it appended the item. False when a
|
|
149
|
+
* stored item matched or the integration does not exist.
|
|
150
|
+
* @abstract
|
|
151
|
+
*/
|
|
152
|
+
async appendRateLimitMessage(
|
|
153
|
+
integrationId,
|
|
154
|
+
messageType,
|
|
155
|
+
item,
|
|
156
|
+
{ retryAtFrom, retryAtTo, keepLast }
|
|
157
|
+
) {
|
|
158
|
+
throw new Error(
|
|
159
|
+
'Method appendRateLimitMessage must be implemented by subclass'
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
|
|
120
163
|
/**
|
|
121
164
|
* Create a new integration
|
|
122
165
|
*
|
|
@@ -3,6 +3,10 @@ const {
|
|
|
3
3
|
IntegrationRepositoryInterface,
|
|
4
4
|
} = require('./integration-repository-interface');
|
|
5
5
|
const { validateConfigPatch } = require('./config-patch-shared');
|
|
6
|
+
const {
|
|
7
|
+
messagesOfType,
|
|
8
|
+
sameRateLimitMessage,
|
|
9
|
+
} = require('./message-item-shared');
|
|
6
10
|
|
|
7
11
|
/**
|
|
8
12
|
* MongoDB Integration Repository Adapter
|
|
@@ -229,17 +233,16 @@ class IntegrationRepositoryMongo extends IntegrationRepositoryInterface {
|
|
|
229
233
|
*
|
|
230
234
|
* @param {string} integrationId - Integration ID
|
|
231
235
|
* @param {string} messageType - Type of message (errors, warnings, info, logs)
|
|
232
|
-
* @param {
|
|
233
|
-
* @param {
|
|
234
|
-
* @param {
|
|
236
|
+
* @param {Object} item - Message item, stored as it is
|
|
237
|
+
* @param {Object} options
|
|
238
|
+
* @param {number} options.keepLast - How many of the newest items of the type to keep
|
|
235
239
|
* @returns {Promise<boolean>} Success indicator
|
|
236
240
|
*/
|
|
237
241
|
async updateIntegrationMessages(
|
|
238
242
|
integrationId,
|
|
239
243
|
messageType,
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
messageTimestamp
|
|
244
|
+
item,
|
|
245
|
+
{ keepLast }
|
|
243
246
|
) {
|
|
244
247
|
// Get current integration
|
|
245
248
|
const integration = await this.prisma.integration.findUnique({
|
|
@@ -251,29 +254,98 @@ class IntegrationRepositoryMongo extends IntegrationRepositoryInterface {
|
|
|
251
254
|
}
|
|
252
255
|
|
|
253
256
|
// Parse existing messages (JSON field)
|
|
254
|
-
const
|
|
255
|
-
const messageArray = Array.isArray(messages[messageType])
|
|
256
|
-
? messages[messageType]
|
|
257
|
-
: [];
|
|
257
|
+
const messageArray = messagesOfType(integration, messageType);
|
|
258
258
|
|
|
259
259
|
// Add new message
|
|
260
|
-
messageArray.push(
|
|
261
|
-
title: messageTitle,
|
|
262
|
-
message: messageBody,
|
|
263
|
-
timestamp: messageTimestamp,
|
|
264
|
-
});
|
|
260
|
+
messageArray.push(item);
|
|
265
261
|
|
|
266
262
|
// Update messages
|
|
267
263
|
await this.prisma.integration.update({
|
|
268
264
|
where: { id: integrationId },
|
|
269
265
|
data: {
|
|
270
|
-
[messageType]: messageArray,
|
|
266
|
+
[messageType]: messageArray.slice(-keepLast),
|
|
271
267
|
},
|
|
272
268
|
});
|
|
273
269
|
|
|
274
270
|
return true; // Mongoose compatibility
|
|
275
271
|
}
|
|
276
272
|
|
|
273
|
+
/**
|
|
274
|
+
* Find the stored messages of one type
|
|
275
|
+
*
|
|
276
|
+
* @param {string} integrationId - Integration ID
|
|
277
|
+
* @param {string} messageType - Type of message (errors, warnings, info, logs)
|
|
278
|
+
* @returns {Promise<Array>} The stored message items of that type, oldest first
|
|
279
|
+
*/
|
|
280
|
+
async findIntegrationMessages(integrationId, messageType) {
|
|
281
|
+
const integration = await this.prisma.integration.findUnique({
|
|
282
|
+
where: { id: integrationId },
|
|
283
|
+
select: { [messageType]: true },
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
if (!integration) {
|
|
287
|
+
throw new Error(`Integration ${integrationId} not found`);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
return messagesOfType(integration, messageType);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Append a rate-limit message item unless the same limit is stored.
|
|
295
|
+
* One update command, so concurrent workers store one item.
|
|
296
|
+
*
|
|
297
|
+
* @param {string} integrationId - Integration ID
|
|
298
|
+
* @param {string} messageType - Type of message (errors, warnings, info, logs)
|
|
299
|
+
* @param {Object} item - Message item with `code`, `module` and an ISO UTC `retryAt`
|
|
300
|
+
* @param {Object} options
|
|
301
|
+
* @param {string} options.retryAtFrom - ISO UTC start of the window, inclusive
|
|
302
|
+
* @param {string} options.retryAtTo - ISO UTC end of the window, inclusive
|
|
303
|
+
* @param {number} options.keepLast - How many of the newest items of the type to keep
|
|
304
|
+
* @returns {Promise<boolean>} True when it appended the item
|
|
305
|
+
*/
|
|
306
|
+
async appendRateLimitMessage(
|
|
307
|
+
integrationId,
|
|
308
|
+
messageType,
|
|
309
|
+
item,
|
|
310
|
+
{ retryAtFrom, retryAtTo, keepLast }
|
|
311
|
+
) {
|
|
312
|
+
const result = await this.prisma.$runCommandRaw({
|
|
313
|
+
update: 'Integration',
|
|
314
|
+
updates: [
|
|
315
|
+
{
|
|
316
|
+
q: {
|
|
317
|
+
_id: { $oid: integrationId },
|
|
318
|
+
$nor: [
|
|
319
|
+
{
|
|
320
|
+
[messageType]: sameRateLimitMessage(item, {
|
|
321
|
+
retryAtFrom,
|
|
322
|
+
retryAtTo,
|
|
323
|
+
}),
|
|
324
|
+
},
|
|
325
|
+
],
|
|
326
|
+
},
|
|
327
|
+
u: {
|
|
328
|
+
$push: {
|
|
329
|
+
[messageType]: {
|
|
330
|
+
$each: [item],
|
|
331
|
+
$slice: -keepLast,
|
|
332
|
+
},
|
|
333
|
+
},
|
|
334
|
+
$set: {
|
|
335
|
+
updatedAt: { $date: new Date().toISOString() },
|
|
336
|
+
},
|
|
337
|
+
},
|
|
338
|
+
},
|
|
339
|
+
],
|
|
340
|
+
});
|
|
341
|
+
if (result?.writeErrors?.length) {
|
|
342
|
+
throw new Error(
|
|
343
|
+
`Failed to append rate-limit message: ${result.writeErrors[0].errmsg}`
|
|
344
|
+
);
|
|
345
|
+
}
|
|
346
|
+
return result?.n === 1;
|
|
347
|
+
}
|
|
348
|
+
|
|
277
349
|
/**
|
|
278
350
|
* Find all integrations whose entity set includes the given entity ID.
|
|
279
351
|
*
|
|
@@ -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
|
+
};
|