@friggframework/core 2.0.0--canary.737.83b4e17.0 → 2.0.0--canary.743.57dc4bf.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CLAUDE.md +173 -7
  2. package/core/CLAUDE.md +57 -1
  3. package/core/Worker.js +440 -11
  4. package/core/create-handler.js +20 -0
  5. package/core/index.js +6 -0
  6. package/core/invocation-deadline.js +91 -0
  7. package/core/invocation-scope.js +30 -24
  8. package/core/rate-limited-response.js +27 -0
  9. package/errors/fetch-error.js +10 -6
  10. package/errors/index.js +2 -0
  11. package/errors/rate-limit-error.js +46 -0
  12. package/handlers/app-handler-helpers.js +15 -0
  13. package/handlers/backend-utils.js +75 -1
  14. package/handlers/workers/integration-defined-workers.js +2 -0
  15. package/index.js +26 -0
  16. package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +2 -0
  17. package/integrations/repositories/integration-repository-documentdb.js +59 -10
  18. package/integrations/repositories/integration-repository-interface.js +50 -7
  19. package/integrations/repositories/integration-repository-mongo.js +88 -16
  20. package/integrations/repositories/integration-repository-postgres.js +89 -16
  21. package/integrations/repositories/message-item-shared.js +17 -0
  22. package/integrations/tests/doubles/prisma-message-row.js +24 -0
  23. package/integrations/tests/doubles/test-integration-repository.js +32 -2
  24. package/integrations/use-cases/clear-rate-limit-wait.js +28 -0
  25. package/integrations/use-cases/index.js +7 -1
  26. package/integrations/use-cases/record-rate-limit-message.js +104 -0
  27. package/integrations/use-cases/record-rate-limit-wait.js +36 -0
  28. package/integrations/use-cases/update-integration-messages.js +28 -9
  29. package/logs/serialize.js +15 -0
  30. package/modules/requester/oauth-2.js +8 -0
  31. package/modules/requester/rate-limit/index.js +6 -0
  32. package/modules/requester/rate-limit/pacer.js +551 -0
  33. package/modules/requester/rate-limit/parsers.js +249 -0
  34. package/modules/requester/rate-limit/policy.js +326 -0
  35. package/modules/requester/rate-limit/state/rate-limit-state-repository-factory.js +35 -0
  36. package/modules/requester/rate-limit/state/rate-limit-state-repository-interface.js +69 -0
  37. package/modules/requester/rate-limit/state/rate-limit-state-repository-memory.js +62 -0
  38. package/modules/requester/rate-limit/state/rate-limit-state-repository-mongo.js +148 -0
  39. package/modules/requester/rate-limit/state/rate-limit-state-repository-postgres.js +93 -0
  40. package/modules/requester/requester.js +357 -11
  41. package/package.json +7 -6
  42. package/queues/queue-deferral.js +155 -0
  43. package/queues/queue-delivery.js +1 -0
  44. package/queues/queuer-util.js +3 -4
  45. package/types/core/consumer.fixture.ts +12 -0
  46. package/types/core/index.d.ts +84 -0
  47. package/types/errors/index.d.ts +47 -0
  48. package/types/integrations/index.d.ts +25 -4
  49. package/types/module-plugin/index.d.ts +53 -0
  50. package/queues/sqs-message-body.js +0 -17
@@ -1,6 +1,11 @@
1
1
  const { runInContext, LOGGER_SCOPE_KEY } = require('../logs/context');
2
2
  const { summarizeMessageBody } = require('../logs/summarize-event');
3
3
  const { flushSinks, hasFlushableSinks } = require('../logs/logger-runtime');
4
+ const {
5
+ deadlineFromContext,
6
+ remainingTimeMs,
7
+ runWithInvocationDeadline,
8
+ } = require('./invocation-deadline');
4
9
 
5
10
  // Bounds the tail latency telemetry adds to every warm invocation. Kept low so
6
11
  // an unreachable OTLP endpoint (e.g. a VPC Lambda with no NAT/egress) costs at
@@ -111,15 +116,6 @@ function withDeadline(ms, fn) {
111
116
  });
112
117
  }
113
118
 
114
- function remainingTimeMs(context) {
115
- try {
116
- const remaining = context?.getRemainingTimeInMillis?.();
117
- return typeof remaining === 'number' ? remaining : Infinity;
118
- } catch (_) {
119
- return Infinity;
120
- }
121
- }
122
-
123
119
  async function flushInvocation({
124
120
  telemetry,
125
121
  usageRollup,
@@ -167,22 +163,32 @@ async function runInvocationScope(fields, fn, opts = {}) {
167
163
  shouldUseDatabase = true,
168
164
  flushTimeoutMs = DEFAULT_FLUSH_TIMEOUT_MS,
169
165
  context,
166
+ maxInProcessWaitMs,
170
167
  } = opts;
171
- return runInContext({ [LOGGER_SCOPE_KEY]: { ...(fields || {}) } }, async () => {
172
- try {
173
- return await fn();
174
- } finally {
175
- // Every step is guarded, so a flush never changes the result.
176
- await flushInvocation({
177
- telemetry,
178
- usageRollup,
179
- eventSummary,
180
- shouldUseDatabase,
181
- flushTimeoutMs,
182
- context,
183
- });
184
- }
185
- });
168
+ const deadline = {
169
+ deadlineAt: deadlineFromContext(context),
170
+ maxInProcessWaitMs,
171
+ };
172
+ return runWithInvocationDeadline(deadline, () =>
173
+ runInContext(
174
+ { [LOGGER_SCOPE_KEY]: { ...(fields || {}) } },
175
+ async () => {
176
+ try {
177
+ return await fn();
178
+ } finally {
179
+ // Every step is guarded, so a flush never changes the result.
180
+ await flushInvocation({
181
+ telemetry,
182
+ usageRollup,
183
+ eventSummary,
184
+ shouldUseDatabase,
185
+ flushTimeoutMs,
186
+ context,
187
+ });
188
+ }
189
+ }
190
+ )
191
+ );
186
192
  }
187
193
 
188
194
  function toCount(value) {
@@ -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 };
@@ -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
- response && !response.bodyUsed && typeof response.text === 'function'
71
- ? await response.text()
72
- : null;
73
- if (!responseBody) responseBody = options.responseBody ?? options.body;
74
- return new FetchError({ ...options, responseBody });
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,16 @@ const {
101
104
  ModuleConstants,
102
105
  ModuleFactory,
103
106
  } = require('./modules/index');
107
+ const {
108
+ classifyRateLimit,
109
+ parseRetryAfter,
110
+ parseResetHeaders,
111
+ parseIetfRateLimit,
112
+ RateLimitPacer,
113
+ getRateLimitPacer,
114
+ hashRateLimitScope,
115
+ setRateLimitPacer,
116
+ } = require('./modules/requester/rate-limit');
104
117
  const application = require('./application');
105
118
  const utils = require('./utils');
106
119
 
@@ -121,6 +134,8 @@ module.exports = {
121
134
  loadInstalledModules,
122
135
  createHandler,
123
136
  runInvocationScope,
137
+ runWithInvocationDeadline,
138
+ remainingInvocationMs,
124
139
 
125
140
  // database
126
141
  prisma,
@@ -143,10 +158,21 @@ module.exports = {
143
158
  BaseError,
144
159
  FetchError,
145
160
  HaltError,
161
+ RateLimitError,
146
162
  RequiredPropertyError,
147
163
  ParameterTypeError,
148
164
  MappingAlreadyExistsError,
149
165
 
166
+ // rate limit
167
+ classifyRateLimit,
168
+ parseRetryAfter,
169
+ parseResetHeaders,
170
+ parseIetfRateLimit,
171
+ RateLimitPacer,
172
+ getRateLimitPacer,
173
+ hashRateLimitScope,
174
+ setRateLimitPacer,
175
+
150
176
  // integrations
151
177
  IntegrationBase,
152
178
  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
- messageTitle,
98
- messageBody,
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 = Array.isArray(messages[messageType]) ? [...messages[messageType]] : [];
111
- list.push({
112
- title: messageTitle ?? null,
113
- message: messageBody,
114
- timestamp: messageTimestamp,
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
- * Update integration messages
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 {string} messageTitle - Message title
105
- * @param {string} messageBody - Message body
106
- * @param {Date} messageTimestamp - Message timestamp
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
- messageTitle,
114
- messageBody,
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
  *