@friggframework/core 2.0.0--canary.658.130b4ec.0 → 2.0.0--canary.657.798cee9.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.
@@ -0,0 +1,74 @@
1
+ const { toPositiveInteger } = require('./queue-delivery');
2
+
3
+ const MAX_DEFERRALS = 30;
4
+ const MAX_DEFERRED_MS = 26 * 60 * 60 * 1000;
5
+ const MAX_DELAY_SECONDS = 900;
6
+ const MAX_VISIBILITY_TIMEOUT_SECONDS = 43_200;
7
+ const MAX_LAMBDA_RUN_SECONDS = 900;
8
+ const MAX_BATCHING_WINDOW_SECONDS = 300;
9
+ const MAX_DEFERRED_VISIBILITY_SECONDS =
10
+ MAX_VISIBILITY_TIMEOUT_SECONDS -
11
+ MAX_LAMBDA_RUN_SECONDS -
12
+ MAX_BATCHING_WINDOW_SECONDS;
13
+ const MAX_DEFERRALS_ENV = 'FRIGG_QUEUE_MAX_DEFERRALS';
14
+ const MAX_DEFERRED_MS_ENV = 'FRIGG_QUEUE_MAX_DEFERRED_MS';
15
+
16
+ const readDeferralLimits = (env = process.env) => ({
17
+ maxDeferrals: toPositiveInteger(env[MAX_DEFERRALS_ENV]) ?? MAX_DEFERRALS,
18
+ maxDeferredMs:
19
+ toPositiveInteger(env[MAX_DEFERRED_MS_ENV]) ?? MAX_DEFERRED_MS,
20
+ });
21
+
22
+ const readDeferral = (body) => {
23
+ const frigg = body?._frigg;
24
+ const deferrals =
25
+ Number.isInteger(frigg?.deferrals) && frigg.deferrals > 0
26
+ ? frigg.deferrals
27
+ : 0;
28
+ const firstDeferredAt =
29
+ typeof frigg?.firstDeferredAt === 'string' &&
30
+ !Number.isNaN(Date.parse(frigg.firstDeferredAt))
31
+ ? frigg.firstDeferredAt
32
+ : undefined;
33
+ const deferralId =
34
+ typeof frigg?.deferralId === 'string' && frigg.deferralId !== ''
35
+ ? frigg.deferralId
36
+ : undefined;
37
+ return { deferrals, firstDeferredAt, deferralId };
38
+ };
39
+
40
+ const nextDeferral = (body, now = Date.now(), messageId) => {
41
+ const current = readDeferral(body);
42
+ return {
43
+ deferrals: current.deferrals + 1,
44
+ firstDeferredAt: current.firstDeferredAt ?? new Date(now).toISOString(),
45
+ deferralId: current.deferralId ?? messageId,
46
+ };
47
+ };
48
+
49
+ const withDeferral = (body, deferral) => ({
50
+ ...body,
51
+ _frigg: { ...body._frigg, ...deferral },
52
+ });
53
+
54
+ const deferredMs = ({ firstDeferredAt, retryAt }) =>
55
+ retryAt.getTime() - Date.parse(firstDeferredAt);
56
+
57
+ const isDeferralCapped = (deferral, { maxDeferrals, maxDeferredMs }) =>
58
+ deferral.deferrals > maxDeferrals || deferredMs(deferral) > maxDeferredMs;
59
+
60
+ module.exports = {
61
+ MAX_DEFERRALS,
62
+ MAX_DEFERRALS_ENV,
63
+ MAX_DEFERRED_MS,
64
+ MAX_DEFERRED_MS_ENV,
65
+ MAX_DEFERRED_VISIBILITY_SECONDS,
66
+ MAX_DELAY_SECONDS,
67
+ MAX_VISIBILITY_TIMEOUT_SECONDS,
68
+ deferredMs,
69
+ isDeferralCapped,
70
+ nextDeferral,
71
+ readDeferral,
72
+ readDeferralLimits,
73
+ withDeferral,
74
+ };
@@ -38,4 +38,5 @@ module.exports = {
38
38
  INTEGRATION_QUEUE_MAX_RECEIVE_COUNT,
39
39
  QUEUE_MAX_RECEIVE_COUNT_ENV,
40
40
  readQueueDelivery,
41
+ toPositiveInteger,
41
42
  };
@@ -126,4 +126,4 @@ const QueuerUtil = {
126
126
  },
127
127
  };
128
128
 
129
- module.exports = { QueuerUtil };
129
+ module.exports = { QueuerUtil, awsConfigOptions };
@@ -47,8 +47,27 @@ declare module "@friggframework/core" {
47
47
  send(params: object & { QueueUrl: any }, delay?: number): Promise<string>;
48
48
 
49
49
  sendAsyncSQSMessage(params: SendSQSMessageParams): Promise<string>;
50
+
51
+ recordRateLimitWait(
52
+ body: object,
53
+ error: Error,
54
+ state: RateLimitWaitState
55
+ ): Promise<void>;
56
+
57
+ clearRateLimitWait(
58
+ body: object,
59
+ options?: { deferralId?: string }
60
+ ): Promise<void>;
50
61
  }
51
62
 
63
+ export type RateLimitWaitState = {
64
+ status: "WAITING" | "EXHAUSTED";
65
+ mechanism: "delay" | "schedule" | "visibility" | "none";
66
+ deferrals: number;
67
+ deferralId?: string;
68
+ retryAt: Date;
69
+ };
70
+
52
71
  interface IWorker {
53
72
  getQueueURL(params: GetQueueURLParams): Promise<string | undefined>;
54
73
  run(params: { Records: any }, context?: object): Promise<BatchItemFailuresResponse>;
@@ -1,22 +1,6 @@
1
1
  declare module "@friggframework/integrations" {
2
2
  import { Delegate, IFriggDelegate } from "@friggframework/core";
3
3
 
4
- export type IntegrationMessageAction =
5
- | { type: "RETRY_WHEN_READY" }
6
- | { type: "LINK"; label: string; url: string };
7
-
8
- export interface IntegrationMessage {
9
- title: string;
10
- message: string;
11
- timestamp: number;
12
- code?: string;
13
- module?: string;
14
- reason?: string;
15
- retryAt?: string;
16
- actions?: IntegrationMessageAction[];
17
- [key: string]: unknown;
18
- }
19
-
20
4
  export interface Integration {
21
5
  entities: any[];
22
6
  userId: string;
@@ -24,10 +8,10 @@ declare module "@friggframework/integrations" {
24
8
  config: any;
25
9
  version: string;
26
10
  messages: {
27
- errors: IntegrationMessage[];
28
- warnings: IntegrationMessage[];
29
- info: IntegrationMessage[];
30
- logs: IntegrationMessage[];
11
+ errors: [];
12
+ warnings: [];
13
+ info: [];
14
+ logs: [];
31
15
  };
32
16
  }
33
17
 
@@ -1,6 +1,6 @@
1
1
  declare module "@friggframework/module-plugin" {
2
2
  import { Delegate, IFriggDelegate } from "@friggframework/core";
3
- import type { RateLimitError, RateLimitHint } from "@friggframework/errors";
3
+ import type { RateLimitHint } from "@friggframework/errors";
4
4
 
5
5
  export interface Credential {
6
6
  id?: string;
@@ -65,7 +65,6 @@ declare module "@friggframework/module-plugin" {
65
65
  static requestTimeoutMs?: number;
66
66
 
67
67
  DLGT_INVALID_AUTH: string;
68
- DLGT_RATE_LIMITED: string;
69
68
  requestTimeoutMs: number;
70
69
  backOff: number[];
71
70
  fetch: any;
@@ -85,7 +84,6 @@ declare module "@friggframework/module-plugin" {
85
84
  parseBody(response: any): Promise<any>;
86
85
  refreshAuth(): Promise<any>;
87
86
  _adoptNewerCredential(): Promise<boolean>;
88
- _notifyRateLimited(rateLimitError: RateLimitError): Promise<void>;
89
87
 
90
88
  delegate: any;
91
89
  delegateTypes: any[];
@@ -103,7 +101,6 @@ declare module "@friggframework/module-plugin" {
103
101
  isRefreshable: boolean;
104
102
  refreshCount: number;
105
103
  DLGT_INVALID_AUTH: string;
106
- DLGT_RATE_LIMITED: string;
107
104
  fetch: any;
108
105
 
109
106
  parseBody(response: any): Promise<any>;
@@ -119,7 +116,6 @@ declare module "@friggframework/module-plugin" {
119
116
  _delete(options: RequestOptions): Promise<any>;
120
117
  refreshAuth(): Promise<any>;
121
118
  _adoptNewerCredential(): Promise<boolean>;
122
- _notifyRateLimited(rateLimitError: RateLimitError): Promise<void>;
123
119
  }
124
120
 
125
121
  type RequestOptions = {
@@ -1,4 +0,0 @@
1
- const messagesOfType = (record, messageType) =>
2
- Array.isArray(record[messageType]) ? record[messageType] : [];
3
-
4
- module.exports = { messagesOfType };
@@ -1,24 +0,0 @@
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 };
@@ -1,110 +0,0 @@
1
- const { getLogger } = require('../../logs');
2
- const { MAX_MESSAGES_PER_TYPE } = require('./update-integration-messages');
3
-
4
- const log = getLogger('frigg.integrations');
5
-
6
- const RATE_LIMITED_MESSAGE_CODE = 'RATE_LIMITED';
7
- const SAME_LIMIT_WINDOW_MS = 60_000;
8
- const MINUTE_MS = 60_000;
9
-
10
- const isNonEmptyString = (value) => typeof value === 'string' && value !== '';
11
-
12
- const isValidTime = (value) =>
13
- value !== null &&
14
- value !== undefined &&
15
- !Number.isNaN(new Date(value).getTime());
16
-
17
- const isLink = (link) =>
18
- typeof link?.label === 'string' && typeof link?.url === 'string';
19
-
20
- const linkActions = (links) =>
21
- (Array.isArray(links) ? links : [])
22
- .filter(isLink)
23
- .map(({ label, url }) => ({ type: 'LINK', label, url }));
24
-
25
- function formatResetTime(date) {
26
- const minute = new Date(Math.ceil(date.getTime() / MINUTE_MS) * MINUTE_MS);
27
- return `${minute.toISOString().slice(0, 16).replace('T', ' ')} UTC`;
28
- }
29
-
30
- /**
31
- * @class RecordRateLimitMessage
32
- */
33
- class RecordRateLimitMessage {
34
- /**
35
- * @param {Object} params - Configuration parameters.
36
- * @param {import('../repositories/integration-repository-interface').IntegrationRepositoryInterface} params.integrationRepository - Repository for integration data operations.
37
- */
38
- constructor({ integrationRepository }) {
39
- this.integrationRepository = integrationRepository;
40
- }
41
-
42
- /**
43
- * @async
44
- * @param {string} integrationId - ID of the integration to warn on.
45
- * @param {Object} payload - The RATE_LIMITED payload of the Module.
46
- * @param {string} payload.moduleName
47
- * @param {string} payload.reason
48
- * @param {Date|string|number} payload.retryAt
49
- * @param {Array<{label: string, url: string}>} [payload.links]
50
- */
51
- async execute(integrationId, payload) {
52
- const { moduleName, reason, retryAt, links } = payload ?? {};
53
- if (!isNonEmptyString(moduleName) || !isValidTime(retryAt)) return;
54
-
55
- try {
56
- await this._recordUnlessStored(integrationId, {
57
- moduleName,
58
- reason,
59
- resetAt: new Date(retryAt),
60
- links,
61
- });
62
- } catch (error) {
63
- log.warn('Failed to record rate limit message', {
64
- eventName:
65
- 'frigg.integrations.rate_limit_message_record_failed',
66
- integrationId,
67
- moduleName,
68
- error,
69
- });
70
- }
71
- }
72
-
73
- async _recordUnlessStored(
74
- integrationId,
75
- { moduleName, reason, resetAt, links }
76
- ) {
77
- const warnings =
78
- await this.integrationRepository.findIntegrationMessages(
79
- integrationId,
80
- 'warnings'
81
- );
82
- const alreadyRecorded = warnings.some(
83
- (warning) =>
84
- warning?.code === RATE_LIMITED_MESSAGE_CODE &&
85
- warning.module === moduleName &&
86
- Math.abs(Date.parse(warning.retryAt) - resetAt.getTime()) <=
87
- SAME_LIMIT_WINDOW_MS
88
- );
89
- if (alreadyRecorded) return;
90
-
91
- const resetsAt = formatResetTime(resetAt);
92
- await this.integrationRepository.updateIntegrationMessages(
93
- integrationId,
94
- 'warnings',
95
- {
96
- title: 'Rate limit reached',
97
- message: `The ${moduleName} API rate limit was reached and resets at ${resetsAt}.`,
98
- timestamp: Date.now(),
99
- code: RATE_LIMITED_MESSAGE_CODE,
100
- module: moduleName,
101
- reason,
102
- retryAt: resetAt.toISOString(),
103
- actions: [{ type: 'RETRY_WHEN_READY' }, ...linkActions(links)],
104
- },
105
- { keepLast: MAX_MESSAGES_PER_TYPE }
106
- );
107
- }
108
- }
109
-
110
- module.exports = { RecordRateLimitMessage };