@friggframework/core 2.0.0--canary.658.e11f3b0.0 → 2.0.0--canary.737.83b4e17.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 (102) hide show
  1. package/CLAUDE.md +42 -58
  2. package/application/commands/README.md +17 -11
  3. package/application/commands/entity-commands.js +18 -60
  4. package/application/commands/integration-commands.js +63 -0
  5. package/core/CLAUDE.md +1 -3
  6. package/core/Worker.js +2 -1
  7. package/core/create-handler.js +0 -3
  8. package/core/index.js +0 -6
  9. package/core/invocation-scope.js +24 -30
  10. package/database/documentdb-encryption-service.js +2 -33
  11. package/database/documentdb-utils.js +4 -1
  12. package/database/encryption/README.md +3 -3
  13. package/database/encryption/ciphertext-format.js +24 -0
  14. package/database/encryption/encryption-schema-registry.js +109 -29
  15. package/database/encryption/field-encryption-service.js +55 -16
  16. package/database/encryption/prisma-encryption-extension.js +6 -9
  17. package/database/prisma.js +10 -1
  18. package/encrypt/Cryptor.js +90 -38
  19. package/errors/fetch-error.js +18 -11
  20. package/errors/index.js +4 -2
  21. package/errors/mapping-already-exists-error.js +14 -0
  22. package/generated/prisma-mongodb/edge.js +6 -2
  23. package/generated/prisma-mongodb/index.js +10 -2
  24. package/generated/prisma-mongodb/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  25. package/generated/prisma-mongodb/package.json +1 -1
  26. package/generated/prisma-mongodb/schema.prisma +1 -1
  27. package/generated/prisma-mongodb/wasm.js +6 -2
  28. package/generated/prisma-postgresql/edge.js +6 -2
  29. package/generated/prisma-postgresql/index.js +10 -2
  30. package/generated/prisma-postgresql/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  31. package/generated/prisma-postgresql/package.json +1 -1
  32. package/generated/prisma-postgresql/schema.prisma +1 -1
  33. package/generated/prisma-postgresql/wasm.js +6 -2
  34. package/handlers/WEBHOOKS.md +29 -0
  35. package/handlers/app-definition-loader.js +9 -2
  36. package/handlers/app-handler-helpers.js +12 -1
  37. package/handlers/workers/integration-defined-workers.js +0 -2
  38. package/index.js +2 -18
  39. package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +67 -13
  40. package/integrations/integration-base.js +52 -25
  41. package/integrations/integration-router.js +30 -22
  42. package/integrations/repositories/integration-mapping-repository-documentdb.js +50 -0
  43. package/integrations/repositories/integration-mapping-repository-interface.js +15 -0
  44. package/integrations/repositories/integration-mapping-repository-mongo.js +29 -0
  45. package/integrations/repositories/integration-mapping-repository-postgres.js +30 -0
  46. package/integrations/repositories/integration-mapping-repository.js +29 -0
  47. package/integrations/repositories/integration-repository-documentdb.js +42 -23
  48. package/integrations/repositories/integration-repository-interface.js +37 -21
  49. package/integrations/repositories/integration-repository-mongo.js +69 -30
  50. package/integrations/repositories/integration-repository-postgres.js +74 -30
  51. package/integrations/repositories/process-repository-mongo.js +1 -1
  52. package/integrations/tests/doubles/test-integration-repository.js +2 -15
  53. package/integrations/use-cases/add-entities-to-integration.js +92 -0
  54. package/integrations/use-cases/create-integration.js +57 -19
  55. package/integrations/use-cases/delete-integration-for-user.js +8 -11
  56. package/integrations/use-cases/get-integration-instance.js +12 -12
  57. package/integrations/use-cases/remove-entities-from-integration.js +70 -0
  58. package/integrations/use-cases/update-integration-messages.js +9 -28
  59. package/integrations/use-cases/update-integration.js +12 -12
  60. package/integrations/utils/assert-entity-ids-input.js +42 -0
  61. package/jest-setup.js +13 -2
  62. package/jest-teardown.js +5 -2
  63. package/jest.config.js +4 -0
  64. package/jest.db.config.js +23 -0
  65. package/logs/serialize.js +0 -15
  66. package/modules/module.js +0 -27
  67. package/modules/requester/requester.js +9 -211
  68. package/modules/use-cases/create-entity-from-credential.js +105 -0
  69. package/modules/use-cases/get-entity-options-by-id.js +7 -5
  70. package/modules/use-cases/get-module.js +29 -8
  71. package/modules/use-cases/process-authorization-callback.js +78 -27
  72. package/modules/use-cases/refresh-entity-options.js +7 -5
  73. package/modules/use-cases/test-module-auth.js +7 -5
  74. package/modules/utils/find-module-definition.js +23 -0
  75. package/modules/utils/map-module-dto.js +5 -3
  76. package/modules/utils/to-credential-id.js +14 -0
  77. package/package.json +10 -7
  78. package/prisma-mongodb/schema.prisma +1 -1
  79. package/prisma-postgresql/schema.prisma +1 -1
  80. package/queues/queuer-util.js +9 -7
  81. package/queues/sqs-message-body.js +17 -0
  82. package/telemetry/otel-telemetry.js +76 -3
  83. package/telemetry/telemetry-config.js +16 -5
  84. package/telemetry/telemetry-runtime.js +14 -1
  85. package/token/repositories/token-repository-documentdb.js +13 -1
  86. package/token/repositories/token-repository-mongo.js +13 -1
  87. package/token/repositories/token-repository-postgres.js +13 -1
  88. package/types/core/index.d.ts +0 -33
  89. package/types/errors/index.d.ts +0 -47
  90. package/types/integrations/index.d.ts +4 -20
  91. package/types/module-plugin/index.d.ts +0 -47
  92. package/user/tests/doubles/test-user-repository.js +1 -1
  93. package/user/use-cases/authenticate-user.js +23 -7
  94. package/user/use-cases/get-user-from-bearer-token.js +7 -2
  95. package/core/invocation-deadline.js +0 -91
  96. package/errors/rate-limit-error.js +0 -46
  97. package/integrations/repositories/message-item-shared.js +0 -4
  98. package/integrations/tests/doubles/prisma-message-row.js +0 -24
  99. package/integrations/use-cases/record-rate-limit-message.js +0 -110
  100. package/modules/requester/rate-limit/index.js +0 -4
  101. package/modules/requester/rate-limit/parsers.js +0 -245
  102. package/modules/requester/rate-limit/policy.js +0 -304
@@ -47,8 +47,21 @@ function getTelemetry() {
47
47
  try {
48
48
  const { telemetry = {} } = loadTelemetryConfig();
49
49
  const stage = process.env.STAGE || process.env.NODE_ENV || 'production';
50
+ // loadAppDefinition normally resolves via resolveTelemetryConfig. When the
51
+ // loader returns an unresolved block (exporter unset) — e.g. tests, or a
52
+ // Definition with no telemetry key — apply the same env-aware default so
53
+ // OTEL_EXPORTER_OTLP_ENDPOINT still auto-activates `{ type: 'otlp' }`.
54
+ // Explicit exporter (incl. `{ type: 'none' }`) always wins.
55
+ let exporter = telemetry.exporter;
56
+ if (exporter === undefined || exporter === null) {
57
+ const { resolveTelemetryConfig } = require('./telemetry-config');
58
+ exporter = resolveTelemetryConfig(
59
+ { telemetry: {} },
60
+ { stage }
61
+ ).exporter;
62
+ }
50
63
  state.telemetry = createTelemetry({
51
- exporter: telemetry.exporter,
64
+ exporter,
52
65
  sampleRatio: telemetry.sampleRatio,
53
66
  resource: { service: process.env.FRIGG_STACK || 'frigg', stage },
54
67
  });
@@ -119,7 +119,19 @@ class TokenRepositoryDocumentDB extends TokenRepositoryInterface {
119
119
 
120
120
  getJSONTokenFromBase64BufferToken(buffer) {
121
121
  const tokenStr = Buffer.from(buffer.trim(), 'base64').toString('ascii');
122
- return JSON.parse(tokenStr);
122
+ let jsonToken;
123
+ try {
124
+ jsonToken = JSON.parse(tokenStr);
125
+ } catch {
126
+ jsonToken = null;
127
+ }
128
+ if (
129
+ !['string', 'number'].includes(typeof jsonToken?.id) ||
130
+ typeof jsonToken?.token !== 'string'
131
+ ) {
132
+ throw new ClientSafeError('Invalid Token: Token is malformed', 401);
133
+ }
134
+ return jsonToken;
123
135
  }
124
136
 
125
137
  _mapToken(record) {
@@ -212,7 +212,19 @@ class TokenRepositoryMongo extends TokenRepositoryInterface {
212
212
  */
213
213
  getJSONTokenFromBase64BufferToken(buffer) {
214
214
  const tokenStr = Buffer.from(buffer.trim(), 'base64').toString('ascii');
215
- return JSON.parse(tokenStr);
215
+ let jsonToken;
216
+ try {
217
+ jsonToken = JSON.parse(tokenStr);
218
+ } catch {
219
+ jsonToken = null;
220
+ }
221
+ if (
222
+ !['string', 'number'].includes(typeof jsonToken?.id) ||
223
+ typeof jsonToken?.token !== 'string'
224
+ ) {
225
+ throw new ClientSafeError('Invalid Token: Token is malformed', 401);
226
+ }
227
+ return jsonToken;
216
228
  }
217
229
  }
218
230
 
@@ -257,7 +257,19 @@ class TokenRepositoryPostgres extends TokenRepositoryInterface {
257
257
  */
258
258
  getJSONTokenFromBase64BufferToken(buffer) {
259
259
  const tokenStr = Buffer.from(buffer.trim(), 'base64').toString('ascii');
260
- return JSON.parse(tokenStr);
260
+ let jsonToken;
261
+ try {
262
+ jsonToken = JSON.parse(tokenStr);
263
+ } catch {
264
+ jsonToken = null;
265
+ }
266
+ if (
267
+ !['string', 'number'].includes(typeof jsonToken?.id) ||
268
+ typeof jsonToken?.token !== 'string'
269
+ ) {
270
+ throw new ClientSafeError('Invalid Token: Token is malformed', 401);
271
+ }
272
+ return jsonToken;
261
273
  }
262
274
  }
263
275
 
@@ -1,10 +1,5 @@
1
1
  declare module "@friggframework/core" {
2
2
  import type { SendMessageCommandInput } from "@aws-sdk/client-sqs";
3
- import type { RateLimitHint } from "@friggframework/errors";
4
- import type {
5
- RateLimitPolicy,
6
- RateLimitSignal,
7
- } from "@friggframework/module-plugin";
8
3
 
9
4
  export class Delegate implements IFriggDelegate {
10
5
  delegate: any;
@@ -58,34 +53,6 @@ declare module "@friggframework/core" {
58
53
 
59
54
  export function loadInstalledModules(): any[];
60
55
 
61
- export function runWithInvocationDeadline<T>(
62
- limits: { deadlineAt?: number; maxInProcessWaitMs?: number },
63
- fn: () => T
64
- ): T;
65
-
66
- export function remainingInvocationMs(now?: number): number;
67
-
68
- export function classifyRateLimit(
69
- policy: RateLimitPolicy | undefined,
70
- signal: RateLimitSignal,
71
- options?: { now?: number; onClassifyError?: (error: Error) => void }
72
- ): RateLimitHint | null;
73
-
74
- export function parseRetryAfter(
75
- value: string | null | undefined,
76
- options?: { now?: number }
77
- ): RateLimitHint | null;
78
-
79
- export function parseResetHeaders(
80
- headers: object | undefined,
81
- options?: { now?: number }
82
- ): RateLimitHint | null;
83
-
84
- export function parseIetfRateLimit(
85
- headers: object | undefined,
86
- options?: { now?: number }
87
- ): RateLimitHint | null;
88
-
89
56
  type GetQueueURLParams = {
90
57
  QueueName: string;
91
58
  QueueOwnerAWSAccountId?: string;
@@ -16,57 +16,10 @@ declare module "@friggframework/errors" {
16
16
  readonly body: any;
17
17
  isTimeout?: boolean;
18
18
  timeoutMs?: number;
19
- isRateLimited?: boolean;
20
- reason?: RateLimitReason;
21
19
 
22
20
  static create(options?: CreateFetchErrorParams): Promise<FetchError>;
23
21
  }
24
22
 
25
- export type RateLimitReason =
26
- | "burst"
27
- | "daily"
28
- | "monthly"
29
- | "concurrency"
30
- | "unknown";
31
-
32
- export type RateLimitSource = "header" | "body" | "static" | "backoff";
33
-
34
- export type RateLimitHint = {
35
- retryAt: Date;
36
- waitMs: number;
37
- reason: RateLimitReason;
38
- policy?: string;
39
- remaining?: number;
40
- source: RateLimitSource;
41
- };
42
-
43
- export class RateLimitError extends FetchError {
44
- constructor(options?: RateLimitErrorConstructor);
45
-
46
- isRateLimited: true;
47
- retryAt?: Date;
48
- waitMs?: number;
49
- reason: RateLimitReason;
50
- policy?: string;
51
- source: RateLimitSource | "unknown";
52
- module?: string;
53
- scopeKey?: string;
54
-
55
- static create(
56
- options?: CreateRateLimitErrorParams
57
- ): Promise<RateLimitError>;
58
- }
59
-
60
- type RateLimitErrorConstructor = FetchErrorConstructor & {
61
- hint?: Partial<RateLimitHint>;
62
- waitMs?: number;
63
- module?: string;
64
- scopeKey?: string;
65
- now?: number;
66
- };
67
-
68
- type CreateRateLimitErrorParams = RateLimitErrorConstructor;
69
-
70
23
  type FetchErrorResponse = {
71
24
  headers?: object;
72
25
  status?: number;
@@ -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,5 @@
1
1
  declare module "@friggframework/module-plugin" {
2
2
  import { Delegate, IFriggDelegate } from "@friggframework/core";
3
- import type { RateLimitError, RateLimitHint } from "@friggframework/errors";
4
3
 
5
4
  export interface Credential {
6
5
  id?: string;
@@ -23,50 +22,8 @@ declare module "@friggframework/module-plugin" {
23
22
  export type MappedEntity = Entity & { id: string; type: any };
24
23
 
25
24
 
26
- export type RateLimitScope =
27
- | "credential"
28
- | "entity"
29
- | "app"
30
- | ((requester: Requester) => string | number | null | undefined);
31
-
32
- export type RateLimitSignal = {
33
- status?: number;
34
- headers?: { get(name: string): string | null } | object;
35
- body?: unknown;
36
- };
37
-
38
- export type RateLimitWindow = {
39
- name: string;
40
- limit?: number;
41
- perMs?: number;
42
- rollingMs?: number;
43
- resets?: { at: string; tz: string };
44
- };
45
-
46
- export type RateLimitPolicy = {
47
- scope?: RateLimitScope;
48
- windows?: RateLimitWindow[];
49
- maxConcurrency?: number;
50
- minRetryAfterMs?: number;
51
- parsers?: Array<"retryAfter" | "resetHeaders" | "ietf">;
52
- classify?(
53
- signal: RateLimitSignal
54
- ): Partial<Omit<RateLimitHint, "source">> & {
55
- source?: "header" | "body" | "static";
56
- } | null | undefined;
57
- userHints?: Record<
58
- string,
59
- { links?: Array<{ label: string; url: string }> }
60
- >;
61
- };
62
-
63
25
  export class Requester implements IFriggRequester {
64
- static rateLimit?: RateLimitPolicy;
65
- static requestTimeoutMs?: number;
66
-
67
26
  DLGT_INVALID_AUTH: string;
68
- DLGT_RATE_LIMITED: string;
69
- requestTimeoutMs: number;
70
27
  backOff: number[];
71
28
  fetch: any;
72
29
  isRefreshable: boolean;
@@ -85,7 +42,6 @@ declare module "@friggframework/module-plugin" {
85
42
  parseBody(response: any): Promise<any>;
86
43
  refreshAuth(): Promise<any>;
87
44
  _adoptNewerCredential(): Promise<boolean>;
88
- _notifyRateLimited(rateLimitError: RateLimitError): Promise<void>;
89
45
 
90
46
  delegate: any;
91
47
  delegateTypes: any[];
@@ -103,7 +59,6 @@ declare module "@friggframework/module-plugin" {
103
59
  isRefreshable: boolean;
104
60
  refreshCount: number;
105
61
  DLGT_INVALID_AUTH: string;
106
- DLGT_RATE_LIMITED: string;
107
62
  fetch: any;
108
63
 
109
64
  parseBody(response: any): Promise<any>;
@@ -119,7 +74,6 @@ declare module "@friggframework/module-plugin" {
119
74
  _delete(options: RequestOptions): Promise<any>;
120
75
  refreshAuth(): Promise<any>;
121
76
  _adoptNewerCredential(): Promise<boolean>;
122
- _notifyRateLimited(rateLimitError: RateLimitError): Promise<void>;
123
77
  }
124
78
 
125
79
  type RequestOptions = {
@@ -133,7 +87,6 @@ declare module "@friggframework/module-plugin" {
133
87
  type RequesterConstructor = {
134
88
  backOff?: number[];
135
89
  fetch?: any;
136
- random?: () => number;
137
90
  };
138
91
 
139
92
  export class ApiKeyRequester
@@ -23,7 +23,7 @@ class TestUserRepository {
23
23
 
24
24
  async createToken(userId, rawToken, minutes = 120) {
25
25
  const token = `token-for-${userId}-for-${minutes}-mins`;
26
- this.tokens.set(token, { user: userId, rawToken });
26
+ this.tokens.set(token, { id: token, userId, rawToken });
27
27
  return token;
28
28
  }
29
29
 
@@ -1,13 +1,16 @@
1
1
  const Boom = require('@hapi/boom');
2
+ const { getLogger } = require('../../logs');
3
+
4
+ const log = getLogger('frigg.user.authentication');
2
5
 
3
6
  /**
4
7
  * Use case for authenticating a user using multiple authentication strategies.
5
- *
8
+ *
6
9
  * Supports three authentication modes in priority order:
7
10
  * 1. Shared Secret (backend-to-backend with x-frigg-api-key + x-frigg headers)
8
11
  * 2. Adopter JWT (custom JWT authentication)
9
12
  * 3. Frigg Native Token (bearer token from /user/login)
10
- *
13
+ *
11
14
  * x-frigg-appUserId and x-frigg-appOrgId headers are automatically supported
12
15
  * for user identification with any auth mode. When present with JWT or Frigg
13
16
  * tokens, they are validated to match the authenticated user.
@@ -50,12 +53,18 @@ class AuthenticateUser {
50
53
  const authModes = this.userConfig.authModes || { friggToken: true };
51
54
  const appUserId = req.headers['x-frigg-appuserid'];
52
55
  const appOrgId = req.headers['x-frigg-apporgid'];
53
- let user = null;
56
+ log.debug('Request headers received', {
57
+ eventName: `${log.name}.headers_received`,
58
+ headerNames: Object.keys(req.headers),
59
+ });
54
60
 
55
61
  // Priority 1: Shared Secret (backend-to-backend with API key)
56
62
  if (authModes.sharedSecret !== false) {
57
63
  const apiKey = req.headers['x-frigg-api-key'];
58
64
  if (apiKey) {
65
+ log.debug('Attempting shared secret authentication', {
66
+ eventName: `${log.name}.shared_secret_attempted`,
67
+ });
59
68
  // Validate the API key (authentication)
60
69
  await this.authenticateWithSharedSecret.execute(apiKey);
61
70
  // Get user from x-frigg headers (authorization)
@@ -64,6 +73,9 @@ class AuthenticateUser {
64
73
  appOrgId
65
74
  );
66
75
  }
76
+ log.debug('No x-frigg-api-key header, skipping shared secret', {
77
+ eventName: `${log.name}.shared_secret_skipped`,
78
+ });
67
79
  }
68
80
 
69
81
  // Priority 2: Adopter JWT (if enabled)
@@ -71,10 +83,13 @@ class AuthenticateUser {
71
83
  authModes.adopterJwt === true &&
72
84
  req.headers.authorization?.startsWith('Bearer ')
73
85
  ) {
86
+ log.debug('Attempting adopter JWT authentication', {
87
+ eventName: `${log.name}.adopter_jwt_attempted`,
88
+ });
74
89
  const token = req.headers.authorization.split(' ')[1];
75
90
  // Detect JWT format (3 parts separated by dots)
76
91
  if (token && token.split('.').length === 3) {
77
- user = await this.getUserFromAdopterJwt.execute(token);
92
+ const user = await this.getUserFromAdopterJwt.execute(token);
78
93
  // Validate x-frigg headers match JWT claims if present
79
94
  if (appUserId || appOrgId) {
80
95
  this.validateUserMatch(user, appUserId, appOrgId);
@@ -85,7 +100,10 @@ class AuthenticateUser {
85
100
 
86
101
  // Priority 3: Frigg native token (default)
87
102
  if (authModes.friggToken !== false && req.headers.authorization) {
88
- user = await this.getUserFromBearerToken.execute(
103
+ log.debug('Attempting Frigg native token authentication', {
104
+ eventName: `${log.name}.frigg_token_attempted`,
105
+ });
106
+ const user = await this.getUserFromBearerToken.execute(
89
107
  req.headers.authorization
90
108
  );
91
109
  // Validate x-frigg headers match token user if present
@@ -123,5 +141,3 @@ class AuthenticateUser {
123
141
  }
124
142
 
125
143
  module.exports = { AuthenticateUser };
126
-
127
-
@@ -40,8 +40,13 @@ class GetUserFromBearerToken {
40
40
  throw Boom.unauthorized('Session Token Not Found');
41
41
  }
42
42
 
43
+ const tokenUserId = sessionToken.userId;
44
+ if (!tokenUserId) {
45
+ throw Boom.unauthorized('Session Token Has No User');
46
+ }
47
+
43
48
  if (this.userConfig.primary === 'organization') {
44
- const organizationUserData = await this.userRepository.findOrganizationUserById(sessionToken.user);
49
+ const organizationUserData = await this.userRepository.findOrganizationUserById(tokenUserId);
45
50
 
46
51
  if (!organizationUserData) {
47
52
  throw Boom.unauthorized('Organization User Not Found');
@@ -57,7 +62,7 @@ class GetUserFromBearerToken {
57
62
  );
58
63
  }
59
64
 
60
- const individualUserData = await this.userRepository.findIndividualUserById(sessionToken.user);
65
+ const individualUserData = await this.userRepository.findIndividualUserById(tokenUserId);
61
66
 
62
67
  if (!individualUserData) {
63
68
  throw Boom.unauthorized('Individual User Not Found');
@@ -1,91 +0,0 @@
1
- const { AsyncLocalStorage } = require('node:async_hooks');
2
-
3
- const STORE_KEY = Symbol.for('@friggframework/core.invocation-deadline');
4
-
5
- function storage() {
6
- if (!globalThis[STORE_KEY]) {
7
- globalThis[STORE_KEY] = new AsyncLocalStorage();
8
- }
9
- return globalThis[STORE_KEY];
10
- }
11
-
12
- const MAX_IN_PROCESS_WAIT_MS = Object.freeze({
13
- outsideInvocation: 300_000,
14
- http: 10_000,
15
- queueWorker: 60_000,
16
- });
17
-
18
- const validDeadline = (value) =>
19
- typeof value === 'number' && Number.isFinite(value) ? value : undefined;
20
-
21
- const validWait = (value) =>
22
- typeof value === 'number' && Number.isFinite(value) && value >= 0
23
- ? value
24
- : undefined;
25
-
26
- const lower = (outer, next) =>
27
- outer === undefined
28
- ? next
29
- : next === undefined
30
- ? outer
31
- : Math.min(outer, next);
32
-
33
- function runWithInvocationDeadline(
34
- { deadlineAt, maxInProcessWaitMs } = {},
35
- fn
36
- ) {
37
- const outer = storage().getStore();
38
- const effectiveDeadline = lower(
39
- outer?.deadlineAt,
40
- validDeadline(deadlineAt)
41
- );
42
- const effectiveWait = lower(
43
- outer?.maxInProcessWaitMs,
44
- validWait(maxInProcessWaitMs)
45
- );
46
- if (effectiveDeadline === undefined && effectiveWait === undefined) {
47
- return fn();
48
- }
49
- return storage().run(
50
- Object.freeze({
51
- deadlineAt: effectiveDeadline ?? Infinity,
52
- maxInProcessWaitMs: effectiveWait,
53
- }),
54
- fn
55
- );
56
- }
57
-
58
- function remainingTimeMs(context) {
59
- try {
60
- const remaining = context?.getRemainingTimeInMillis?.();
61
- return typeof remaining === 'number' ? remaining : Infinity;
62
- } catch (_) {
63
- return Infinity;
64
- }
65
- }
66
-
67
- function deadlineFromContext(context) {
68
- const remaining = remainingTimeMs(context);
69
- return Number.isFinite(remaining) ? Date.now() + remaining : undefined;
70
- }
71
-
72
- function remainingInvocationMs(now = Date.now()) {
73
- const store = storage().getStore();
74
- return store ? Math.max(0, store.deadlineAt - now) : Infinity;
75
- }
76
-
77
- function invocationMaxInProcessWaitMs() {
78
- return (
79
- storage().getStore()?.maxInProcessWaitMs ??
80
- MAX_IN_PROCESS_WAIT_MS.outsideInvocation
81
- );
82
- }
83
-
84
- module.exports = {
85
- MAX_IN_PROCESS_WAIT_MS,
86
- deadlineFromContext,
87
- invocationMaxInProcessWaitMs,
88
- remainingInvocationMs,
89
- remainingTimeMs,
90
- runWithInvocationDeadline,
91
- };
@@ -1,46 +0,0 @@
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,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 };