@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
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
const isValidDate = (value) =>
|
|
2
|
+
value instanceof Date && !Number.isNaN(value.getTime());
|
|
3
|
+
|
|
4
|
+
function rateLimitedResponse(error, now = Date.now()) {
|
|
5
|
+
if (error?.isRateLimited !== true) return null;
|
|
6
|
+
if (!isValidDate(error.retryAt)) {
|
|
7
|
+
return {
|
|
8
|
+
statusCode: 429,
|
|
9
|
+
headers: {},
|
|
10
|
+
body: { error: 'Too Many Requests' },
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
const retryAfterSeconds = Math.max(
|
|
14
|
+
0,
|
|
15
|
+
Math.ceil((error.retryAt.getTime() - now) / 1000)
|
|
16
|
+
);
|
|
17
|
+
return {
|
|
18
|
+
statusCode: 429,
|
|
19
|
+
headers: { 'Retry-After': String(retryAfterSeconds) },
|
|
20
|
+
body: {
|
|
21
|
+
error: 'Too Many Requests',
|
|
22
|
+
retryAt: error.retryAt.toISOString(),
|
|
23
|
+
},
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
module.exports = { rateLimitedResponse };
|
package/errors/fetch-error.js
CHANGED
|
@@ -66,12 +66,16 @@ class FetchError extends BaseError {
|
|
|
66
66
|
|
|
67
67
|
static async create(options = {}) {
|
|
68
68
|
const { response } = options;
|
|
69
|
-
let responseBody =
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
69
|
+
let { responseBody } = options;
|
|
70
|
+
if (responseBody === undefined || responseBody === null) {
|
|
71
|
+
const canRead =
|
|
72
|
+
response &&
|
|
73
|
+
!response.bodyUsed &&
|
|
74
|
+
typeof response.text === 'function';
|
|
75
|
+
responseBody = (canRead && (await response.text())) || options.body;
|
|
76
|
+
}
|
|
77
|
+
const ErrorClass = typeof this === 'function' ? this : FetchError;
|
|
78
|
+
return new ErrorClass({ ...options, responseBody });
|
|
75
79
|
}
|
|
76
80
|
}
|
|
77
81
|
|
package/errors/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const { BaseError } = require('./base-error');
|
|
2
2
|
const { FetchError } = require('./fetch-error');
|
|
3
3
|
const { HaltError } = require('./halt-error');
|
|
4
|
+
const { RateLimitError } = require('./rate-limit-error');
|
|
4
5
|
const {
|
|
5
6
|
RequiredPropertyError,
|
|
6
7
|
ParameterTypeError,
|
|
@@ -14,6 +15,7 @@ module.exports = {
|
|
|
14
15
|
BaseError,
|
|
15
16
|
FetchError,
|
|
16
17
|
HaltError,
|
|
18
|
+
RateLimitError,
|
|
17
19
|
RequiredPropertyError,
|
|
18
20
|
ParameterTypeError,
|
|
19
21
|
ClientSafeError,
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
const { FetchError } = require('./fetch-error');
|
|
2
|
+
|
|
3
|
+
function resolveTiming({ hint, waitMs, now }) {
|
|
4
|
+
if (waitMs !== undefined) {
|
|
5
|
+
return { waitMs, retryAt: new Date(now + waitMs) };
|
|
6
|
+
}
|
|
7
|
+
if (hint?.retryAt) {
|
|
8
|
+
const retryAt = new Date(hint.retryAt);
|
|
9
|
+
if (!Number.isNaN(retryAt.getTime())) {
|
|
10
|
+
return { waitMs: Math.max(0, retryAt.getTime() - now), retryAt };
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
if (hint?.waitMs !== undefined) {
|
|
14
|
+
return {
|
|
15
|
+
waitMs: hint.waitMs,
|
|
16
|
+
retryAt: new Date(now + hint.waitMs),
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
return { waitMs: undefined, retryAt: undefined };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
class RateLimitError extends FetchError {
|
|
23
|
+
constructor({
|
|
24
|
+
hint,
|
|
25
|
+
waitMs,
|
|
26
|
+
module,
|
|
27
|
+
scopeKey,
|
|
28
|
+
now = Date.now(),
|
|
29
|
+
...fetchErrorArgs
|
|
30
|
+
} = {}) {
|
|
31
|
+
super(fetchErrorArgs);
|
|
32
|
+
|
|
33
|
+
const timing = resolveTiming({ hint, waitMs, now });
|
|
34
|
+
this.statusCode ??= fetchErrorArgs.cause?.statusCode;
|
|
35
|
+
this.isRateLimited = true;
|
|
36
|
+
this.waitMs = timing.waitMs;
|
|
37
|
+
this.retryAt = timing.retryAt;
|
|
38
|
+
this.reason = hint?.reason ?? 'unknown';
|
|
39
|
+
this.policy = hint?.policy;
|
|
40
|
+
this.source = hint?.source ?? 'unknown';
|
|
41
|
+
this.module = module;
|
|
42
|
+
this.scopeKey = scopeKey;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
module.exports = { RateLimitError };
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const { createHandler } = require('@friggframework/core');
|
|
2
2
|
const { getLogger } = require('../logs');
|
|
3
3
|
const { summarizeExpressRequest } = require('../logs/summarize-event');
|
|
4
|
+
const { rateLimitedResponse } = require('../core/rate-limited-response');
|
|
4
5
|
const express = require('express');
|
|
5
6
|
const bodyParser = require('body-parser');
|
|
6
7
|
const cors = require('cors');
|
|
@@ -38,6 +39,20 @@ const createApp = (applyMiddleware) => {
|
|
|
38
39
|
|
|
39
40
|
// The express boundary: send the error response and log it one time.
|
|
40
41
|
app.use((err, req, res, next) => {
|
|
42
|
+
const rateLimited = rateLimitedResponse(err);
|
|
43
|
+
if (rateLimited) {
|
|
44
|
+
log.warn('Request rate limited', {
|
|
45
|
+
eventName: 'frigg.http.request_rate_limited',
|
|
46
|
+
statusCode: rateLimited.statusCode,
|
|
47
|
+
invocation: summarizeExpressRequest(req),
|
|
48
|
+
error: err,
|
|
49
|
+
});
|
|
50
|
+
res.set(rateLimited.headers)
|
|
51
|
+
.status(rateLimited.statusCode)
|
|
52
|
+
.json(rateLimited.body);
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
|
|
41
56
|
const boomError = toBoom(err);
|
|
42
57
|
const {
|
|
43
58
|
output: { statusCode = 500 },
|
|
@@ -21,6 +21,15 @@ const {
|
|
|
21
21
|
getModulesDefinitionFromIntegrationClasses,
|
|
22
22
|
} = require('../integrations/utils/map-integration-dto');
|
|
23
23
|
const { processNotFound } = require('../integrations/use-cases/process-errors');
|
|
24
|
+
const {
|
|
25
|
+
RecordRateLimitWait,
|
|
26
|
+
} = require('../integrations/use-cases/record-rate-limit-wait');
|
|
27
|
+
const {
|
|
28
|
+
ClearRateLimitWait,
|
|
29
|
+
} = require('../integrations/use-cases/clear-rate-limit-wait');
|
|
30
|
+
const {
|
|
31
|
+
RecordRateLimitMessage,
|
|
32
|
+
} = require('../integrations/use-cases/record-rate-limit-message');
|
|
24
33
|
|
|
25
34
|
const loadRouterFromObject = (IntegrationClass, routerObject) => {
|
|
26
35
|
const router = Router();
|
|
@@ -161,10 +170,73 @@ const loadIntegrationForProcess = async (processId, integrationClass) => {
|
|
|
161
170
|
return instance;
|
|
162
171
|
};
|
|
163
172
|
|
|
173
|
+
const RATE_LIMITED_EVENT = 'RATE_LIMITED';
|
|
174
|
+
|
|
164
175
|
const createQueueWorker = (integrationClass) => {
|
|
165
176
|
const integrationName = integrationClass.Definition.name;
|
|
177
|
+
// The hydrated instance of each message, so the RATE_LIMITED handler runs
|
|
178
|
+
// on the instance that ran the job, with no second hydration.
|
|
179
|
+
const runsByMessage = new WeakMap();
|
|
166
180
|
|
|
167
181
|
class QueueWorker extends Worker {
|
|
182
|
+
async decideRateLimited(event) {
|
|
183
|
+
const run = runsByMessage.get(event.message);
|
|
184
|
+
if (
|
|
185
|
+
!run?.dispatcher.findEventHandler(
|
|
186
|
+
run.dispatcher.integrationInstance,
|
|
187
|
+
RATE_LIMITED_EVENT
|
|
188
|
+
)
|
|
189
|
+
) {
|
|
190
|
+
return undefined;
|
|
191
|
+
}
|
|
192
|
+
return run.dispatcher.dispatchJob({
|
|
193
|
+
event: RATE_LIMITED_EVENT,
|
|
194
|
+
data: event,
|
|
195
|
+
context: run.context,
|
|
196
|
+
delivery: run.delivery,
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async recordRateLimitWait(body, error, state) {
|
|
201
|
+
const processId = body.data?.processId;
|
|
202
|
+
if (!processId) return;
|
|
203
|
+
const recordRateLimitWait = new RecordRateLimitWait({
|
|
204
|
+
processRepository: createProcessRepository(),
|
|
205
|
+
});
|
|
206
|
+
await recordRateLimitWait.execute(processId, {
|
|
207
|
+
...state,
|
|
208
|
+
reason: error.reason,
|
|
209
|
+
module: error.module,
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async recordRateLimitMessage(body, error, { retryAt, capped }) {
|
|
214
|
+
const integrationId =
|
|
215
|
+
runsByMessage.get(body)?.dispatcher.integrationInstance.id;
|
|
216
|
+
if (!integrationId) return;
|
|
217
|
+
const recordRateLimitMessage = new RecordRateLimitMessage({
|
|
218
|
+
integrationRepository: createIntegrationRepository(),
|
|
219
|
+
moduleDefinitions: getModulesDefinitionFromIntegrationClasses([
|
|
220
|
+
integrationClass,
|
|
221
|
+
]),
|
|
222
|
+
});
|
|
223
|
+
await recordRateLimitMessage.execute(integrationId, {
|
|
224
|
+
module: error.module,
|
|
225
|
+
reason: error.reason,
|
|
226
|
+
retryAt,
|
|
227
|
+
capped,
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
async clearRateLimitWait(body, { deferralId } = {}) {
|
|
232
|
+
const processId = body?.data?.processId;
|
|
233
|
+
if (!processId) return;
|
|
234
|
+
const clearRateLimitWait = new ClearRateLimitWait({
|
|
235
|
+
processRepository: createProcessRepository(),
|
|
236
|
+
});
|
|
237
|
+
await clearRateLimitWait.execute(processId, { deferralId });
|
|
238
|
+
}
|
|
239
|
+
|
|
168
240
|
async _run(params, context, delivery) {
|
|
169
241
|
const logCtx = {
|
|
170
242
|
integration: integrationName,
|
|
@@ -246,6 +318,7 @@ const createQueueWorker = (integrationClass) => {
|
|
|
246
318
|
const dispatcher = new IntegrationEventDispatcher(
|
|
247
319
|
integrationInstance
|
|
248
320
|
);
|
|
321
|
+
runsByMessage.set(params, { dispatcher, context, delivery });
|
|
249
322
|
|
|
250
323
|
console.log(
|
|
251
324
|
`[QueueWorker] dispatching ${params.event}`,
|
|
@@ -285,7 +358,8 @@ const createQueueWorker = (integrationClass) => {
|
|
|
285
358
|
status >= 400 &&
|
|
286
359
|
status < 500 &&
|
|
287
360
|
status !== 408 &&
|
|
288
|
-
status !== 429
|
|
361
|
+
status !== 429 &&
|
|
362
|
+
!error.isRateLimited
|
|
289
363
|
) {
|
|
290
364
|
error.isHaltError = true;
|
|
291
365
|
console.warn(
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const { createHandler } = require('@friggframework/core');
|
|
2
2
|
const { loadAppDefinition } = require('../app-definition-loader');
|
|
3
3
|
const { createQueueWorker } = require('../backend-utils');
|
|
4
|
+
const { MAX_IN_PROCESS_WAIT_MS } = require('../../core/invocation-deadline');
|
|
4
5
|
// TODO(Phase 2): mount extension-declared workers in addition to the per-integration
|
|
5
6
|
// default queue worker. Today, getExtensionWorkers(IntegrationClass) returns the
|
|
6
7
|
// declared workers but they are not yet bound to dedicated SQS sources. Extension-
|
|
@@ -19,6 +20,7 @@ integrationClasses.forEach((IntegrationClass) => {
|
|
|
19
20
|
queueWorker: createHandler({
|
|
20
21
|
eventName: `Queue Worker for ${IntegrationClass.Definition.name}`,
|
|
21
22
|
isUserFacingResponse: false,
|
|
23
|
+
maxInProcessWaitMs: MAX_IN_PROCESS_WAIT_MS.queueWorker,
|
|
22
24
|
method: async (event, context) => {
|
|
23
25
|
const worker = new defaultQueueWorker();
|
|
24
26
|
return await worker.run(event, context);
|
package/index.js
CHANGED
|
@@ -12,6 +12,8 @@ const {
|
|
|
12
12
|
loadInstalledModules,
|
|
13
13
|
createHandler,
|
|
14
14
|
runInvocationScope,
|
|
15
|
+
runWithInvocationDeadline,
|
|
16
|
+
remainingInvocationMs,
|
|
15
17
|
} = require('./core/index');
|
|
16
18
|
const {
|
|
17
19
|
prisma,
|
|
@@ -55,6 +57,7 @@ const {
|
|
|
55
57
|
BaseError,
|
|
56
58
|
FetchError,
|
|
57
59
|
HaltError,
|
|
60
|
+
RateLimitError,
|
|
58
61
|
RequiredPropertyError,
|
|
59
62
|
ParameterTypeError,
|
|
60
63
|
MappingAlreadyExistsError,
|
|
@@ -101,6 +104,12 @@ const {
|
|
|
101
104
|
ModuleConstants,
|
|
102
105
|
ModuleFactory,
|
|
103
106
|
} = require('./modules/index');
|
|
107
|
+
const {
|
|
108
|
+
classifyRateLimit,
|
|
109
|
+
parseRetryAfter,
|
|
110
|
+
parseResetHeaders,
|
|
111
|
+
parseIetfRateLimit,
|
|
112
|
+
} = require('./modules/requester/rate-limit');
|
|
104
113
|
const application = require('./application');
|
|
105
114
|
const utils = require('./utils');
|
|
106
115
|
|
|
@@ -121,6 +130,8 @@ module.exports = {
|
|
|
121
130
|
loadInstalledModules,
|
|
122
131
|
createHandler,
|
|
123
132
|
runInvocationScope,
|
|
133
|
+
runWithInvocationDeadline,
|
|
134
|
+
remainingInvocationMs,
|
|
124
135
|
|
|
125
136
|
// database
|
|
126
137
|
prisma,
|
|
@@ -143,10 +154,17 @@ module.exports = {
|
|
|
143
154
|
BaseError,
|
|
144
155
|
FetchError,
|
|
145
156
|
HaltError,
|
|
157
|
+
RateLimitError,
|
|
146
158
|
RequiredPropertyError,
|
|
147
159
|
ParameterTypeError,
|
|
148
160
|
MappingAlreadyExistsError,
|
|
149
161
|
|
|
162
|
+
// rate limit
|
|
163
|
+
classifyRateLimit,
|
|
164
|
+
parseRetryAfter,
|
|
165
|
+
parseResetHeaders,
|
|
166
|
+
parseIetfRateLimit,
|
|
167
|
+
|
|
150
168
|
// integrations
|
|
151
169
|
IntegrationBase,
|
|
152
170
|
Options,
|
|
@@ -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
|
*
|