@friggframework/core 2.0.0--canary.731.ffe61d3.0 → 2.0.0--canary.657.18fb0ee.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 (101) hide show
  1. package/CLAUDE.md +93 -48
  2. package/application/commands/README.md +11 -17
  3. package/application/commands/entity-commands.js +60 -18
  4. package/application/commands/integration-commands.js +0 -63
  5. package/core/CLAUDE.md +30 -1
  6. package/core/Worker.js +310 -9
  7. package/core/create-handler.js +3 -0
  8. package/core/index.js +6 -0
  9. package/core/invocation-deadline.js +91 -0
  10. package/core/invocation-scope.js +30 -24
  11. package/database/documentdb-encryption-service.js +33 -2
  12. package/database/documentdb-utils.js +1 -4
  13. package/database/encryption/README.md +3 -3
  14. package/database/encryption/encryption-schema-registry.js +29 -109
  15. package/database/encryption/field-encryption-service.js +16 -55
  16. package/database/encryption/prisma-encryption-extension.js +9 -6
  17. package/database/prisma.js +1 -10
  18. package/encrypt/Cryptor.js +38 -90
  19. package/errors/fetch-error.js +11 -18
  20. package/errors/index.js +2 -4
  21. package/errors/rate-limit-error.js +45 -0
  22. package/generated/prisma-mongodb/edge.js +2 -6
  23. package/generated/prisma-mongodb/index.js +2 -10
  24. package/generated/prisma-mongodb/package.json +1 -1
  25. package/generated/prisma-mongodb/schema.prisma +1 -1
  26. package/generated/prisma-mongodb/wasm.js +2 -6
  27. package/generated/prisma-postgresql/edge.js +2 -6
  28. package/generated/prisma-postgresql/index.js +2 -10
  29. package/generated/prisma-postgresql/package.json +1 -1
  30. package/generated/prisma-postgresql/schema.prisma +1 -1
  31. package/generated/prisma-postgresql/wasm.js +2 -6
  32. package/handlers/WEBHOOKS.md +0 -29
  33. package/handlers/app-definition-loader.js +2 -9
  34. package/handlers/app-handler-helpers.js +1 -12
  35. package/handlers/backend-utils.js +30 -1
  36. package/handlers/workers/integration-defined-workers.js +2 -0
  37. package/index.js +18 -2
  38. package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +15 -67
  39. package/integrations/integration-base.js +9 -52
  40. package/integrations/integration-router.js +22 -30
  41. package/integrations/repositories/integration-mapping-repository-documentdb.js +0 -50
  42. package/integrations/repositories/integration-mapping-repository-interface.js +0 -15
  43. package/integrations/repositories/integration-mapping-repository-mongo.js +0 -29
  44. package/integrations/repositories/integration-mapping-repository-postgres.js +0 -30
  45. package/integrations/repositories/integration-mapping-repository.js +0 -29
  46. package/integrations/repositories/integration-repository-documentdb.js +0 -32
  47. package/integrations/repositories/integration-repository-interface.js +0 -30
  48. package/integrations/repositories/integration-repository-mongo.js +1 -53
  49. package/integrations/repositories/integration-repository-postgres.js +0 -58
  50. package/integrations/repositories/process-repository-mongo.js +1 -1
  51. package/integrations/use-cases/clear-rate-limit-wait.js +28 -0
  52. package/integrations/use-cases/create-integration.js +19 -57
  53. package/integrations/use-cases/delete-integration-for-user.js +11 -8
  54. package/integrations/use-cases/get-integration-instance.js +12 -12
  55. package/integrations/use-cases/index.js +5 -1
  56. package/integrations/use-cases/record-rate-limit-wait.js +36 -0
  57. package/integrations/use-cases/update-integration.js +12 -12
  58. package/jest-setup.js +2 -13
  59. package/jest-teardown.js +2 -5
  60. package/jest.config.js +0 -4
  61. package/logs/serialize.js +15 -0
  62. package/modules/requester/oauth-2.js +7 -0
  63. package/modules/requester/rate-limit/index.js +4 -0
  64. package/modules/requester/rate-limit/parsers.js +245 -0
  65. package/modules/requester/rate-limit/policy.js +304 -0
  66. package/modules/requester/requester.js +187 -9
  67. package/modules/use-cases/get-entity-options-by-id.js +5 -7
  68. package/modules/use-cases/get-module.js +8 -29
  69. package/modules/use-cases/process-authorization-callback.js +27 -78
  70. package/modules/use-cases/refresh-entity-options.js +5 -7
  71. package/modules/use-cases/test-module-auth.js +5 -7
  72. package/modules/utils/map-module-dto.js +3 -5
  73. package/package.json +8 -9
  74. package/prisma-mongodb/schema.prisma +1 -1
  75. package/prisma-postgresql/schema.prisma +1 -1
  76. package/queues/queue-deferral.js +74 -0
  77. package/queues/queue-delivery.js +1 -0
  78. package/queues/queuer-util.js +6 -7
  79. package/telemetry/otel-telemetry.js +3 -76
  80. package/telemetry/telemetry-config.js +5 -16
  81. package/telemetry/telemetry-runtime.js +1 -14
  82. package/token/repositories/token-repository-documentdb.js +1 -13
  83. package/token/repositories/token-repository-mongo.js +1 -13
  84. package/token/repositories/token-repository-postgres.js +1 -13
  85. package/types/core/index.d.ts +52 -0
  86. package/types/errors/index.d.ts +47 -0
  87. package/types/module-plugin/index.d.ts +43 -0
  88. package/user/tests/doubles/test-user-repository.js +1 -1
  89. package/user/use-cases/authenticate-user.js +7 -23
  90. package/user/use-cases/get-user-from-bearer-token.js +2 -7
  91. package/database/encryption/ciphertext-format.js +0 -24
  92. package/errors/mapping-already-exists-error.js +0 -14
  93. package/generated/prisma-mongodb/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  94. package/generated/prisma-postgresql/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  95. package/integrations/use-cases/add-entities-to-integration.js +0 -92
  96. package/integrations/use-cases/remove-entities-from-integration.js +0 -70
  97. package/integrations/utils/assert-entity-ids-input.js +0 -42
  98. package/jest.db.config.js +0 -23
  99. package/modules/use-cases/create-entity-from-credential.js +0 -105
  100. package/modules/utils/find-module-definition.js +0 -23
  101. package/modules/utils/to-credential-id.js +0 -14
@@ -1,8 +1,5 @@
1
1
  const { Module } = require('../module');
2
2
  const { ModuleConstants } = require('../ModuleConstants');
3
- const { getLogger } = require('../../logs');
4
-
5
- const log = getLogger('frigg.modules.authorization_callback');
6
3
 
7
4
  // Statuses considered "broken" for an integration whose credentials have just
8
5
  // been successfully re-authorized. Both ERROR (system-driven auth failure) and
@@ -31,12 +28,10 @@ class ProcessAuthorizationCallback {
31
28
  }
32
29
 
33
30
  async execute(userId, entityType, params) {
34
- log.debug('Authorization callback started', {
35
- eventName: `${log.name}.started`,
36
- userId,
37
- entityType,
38
- hasCode: Boolean(params && params.code),
39
- });
31
+ const hasCode = Boolean(params && params.code);
32
+ console.log(
33
+ `[Frigg] processAuthorizationCallback start userId=${userId} entityType=${entityType} hasCode=${hasCode}`
34
+ );
40
35
 
41
36
  const moduleDefinition = this.moduleDefinitions.find((def) => {
42
37
  return entityType === def.moduleName;
@@ -63,11 +58,9 @@ class ProcessAuthorizationCallback {
63
58
  : null;
64
59
 
65
60
  if (existingEntity) {
66
- log.debug('Existing entity found', {
67
- eventName: `${log.name}.existing_entity_found`,
68
- entityId: existingEntity.id,
69
- credentialId: existingEntity.credential?.id,
70
- });
61
+ console.log(
62
+ `[Frigg] processAuthorizationCallback found existing entity id=${existingEntity.id} credentialId=${existingEntity.credential?.id}`
63
+ );
71
64
  }
72
65
 
73
66
  const module = new Module({
@@ -76,26 +69,15 @@ class ProcessAuthorizationCallback {
76
69
  definition: moduleDefinition,
77
70
  });
78
71
 
79
- const authType = module.apiClass.requesterType;
80
- log.debug('Module created', {
81
- eventName: `${log.name}.module_created`,
82
- moduleName: module.getName(),
83
- authType,
84
- });
85
-
86
72
  let tokenResponse;
87
- if (authType === ModuleConstants.authType.oauth2) {
88
- log.debug('Exchanging authorization code for token', {
89
- eventName: `${log.name}.token_exchanging`,
90
- });
73
+ if (module.apiClass.requesterType === ModuleConstants.authType.oauth2) {
91
74
  tokenResponse = await moduleDefinition.requiredAuthMethods.getToken(
92
75
  module.api,
93
76
  params
94
77
  );
95
- log.debug('Token exchange completed', {
96
- eventName: `${log.name}.token_exchanged`,
97
- tokenKeys: Object.keys(tokenResponse || {}),
98
- });
78
+ console.log(
79
+ `[Frigg] processAuthorizationCallback OAuth getToken complete userId=${userId} entityType=${entityType}`
80
+ );
99
81
  // Belt-and-suspenders: persist tokens explicitly here rather than
100
82
  // relying solely on the DLGT_TOKEN_UPDATE notification chain
101
83
  // inside setTokens. The notification path remains in place but
@@ -104,9 +86,6 @@ class ProcessAuthorizationCallback {
104
86
  // OAuth flow appears to succeed.
105
87
  await this.onTokenUpdate(module, moduleDefinition, userId);
106
88
  } else {
107
- log.debug('Setting auth params', {
108
- eventName: `${log.name}.auth_params_setting`,
109
- });
110
89
  tokenResponse =
111
90
  await moduleDefinition.requiredAuthMethods.setAuthParams(
112
91
  module.api,
@@ -115,24 +94,15 @@ class ProcessAuthorizationCallback {
115
94
  await this.onTokenUpdate(module, moduleDefinition, userId);
116
95
  }
117
96
 
118
- log.debug('Credential persisted', {
119
- eventName: `${log.name}.credential_persisted`,
120
- credentialId: module.credential?.id,
121
- authIsValid: module.credential?.authIsValid,
122
- });
97
+ console.log(
98
+ `[Frigg] processAuthorizationCallback credential persisted credentialId=${module.credential?.id} authIsValid=${module.credential?.authIsValid}`
99
+ );
123
100
 
124
- log.debug('Testing auth', { eventName: `${log.name}.auth_testing` });
125
101
  const authRes = await module.testAuth();
126
102
  if (!authRes) {
127
103
  throw new Error('Authorization failed');
128
104
  }
129
- log.debug('Auth test passed', {
130
- eventName: `${log.name}.auth_test_passed`,
131
- });
132
105
 
133
- log.debug('Fetching entity details', {
134
- eventName: `${log.name}.entity_details_fetching`,
135
- });
136
106
  const entityDetails =
137
107
  await moduleDefinition.requiredAuthMethods.getEntityDetails(
138
108
  module.api,
@@ -140,29 +110,17 @@ class ProcessAuthorizationCallback {
140
110
  tokenResponse,
141
111
  userId
142
112
  );
143
- log.debug('Entity details received', {
144
- eventName: `${log.name}.entity_details_received`,
145
- externalId: entityDetails.identifiers?.externalId,
146
- });
147
113
 
148
114
  Object.assign(
149
115
  entityDetails.details,
150
116
  module.apiParamsFromEntity(module.api)
151
117
  );
152
118
 
153
- log.debug('Finding or creating entity', {
154
- eventName: `${log.name}.entity_resolving`,
155
- });
156
119
  const persistedEntity = await this.findOrCreateEntity(
157
120
  entityDetails,
158
121
  entityType,
159
122
  module.credential.id
160
123
  );
161
- log.debug('Authorization callback completed', {
162
- eventName: `${log.name}.completed`,
163
- entityId: persistedEntity.id,
164
- credentialId: module.credential.id,
165
- });
166
124
 
167
125
  // Best-effort: a hiccup here must not fail a successful re-auth whose
168
126
  // credential + entity are already persisted. Operators can recover
@@ -171,17 +129,14 @@ class ProcessAuthorizationCallback {
171
129
  const restoredCount = await this.restoreIntegrationsForEntity(
172
130
  persistedEntity.id
173
131
  );
174
- log.debug('Integrations restored', {
175
- eventName: `${log.name}.integrations_restored`,
176
- entityId: persistedEntity.id,
177
- restoredCount,
178
- });
132
+ console.log(
133
+ `[Frigg] processAuthorizationCallback restored ${restoredCount} integration(s) for entityId=${persistedEntity.id}`
134
+ );
179
135
  } catch (err) {
180
- log.error('Failed to restore integrations after re-auth', {
181
- eventName: `${log.name}.integrations_restore_failed`,
182
- entityId: persistedEntity.id,
183
- error: err,
184
- });
136
+ console.error(
137
+ `[Frigg] Failed to restore integrations for entity ${persistedEntity.id} after successful re-auth — manual intervention may be needed`,
138
+ err
139
+ );
185
140
  }
186
141
 
187
142
  return {
@@ -200,12 +155,9 @@ class ProcessAuthorizationCallback {
200
155
  let restored = 0;
201
156
  for (const integration of integrations) {
202
157
  if (STATUSES_RESET_ON_REAUTH.includes(integration.status)) {
203
- log.info('Integration restored to ENABLED after re-auth', {
204
- eventName: `${log.name}.integration_restored`,
205
- integrationId: integration.id,
206
- previousStatus: integration.status,
207
- entityId,
208
- });
158
+ console.log(
159
+ `[Frigg] Restoring integration ${integration.id} from ${integration.status} to ENABLED after successful re-auth (entityId=${entityId})`
160
+ );
209
161
  await this.integrationRepository.updateIntegrationStatus(
210
162
  integration.id,
211
163
  'ENABLED'
@@ -267,12 +219,9 @@ class ProcessAuthorizationCallback {
267
219
  credentialId &&
268
220
  String(existingCredentialId) !== String(credentialId)
269
221
  ) {
270
- log.info('Entity credential repointed after re-auth', {
271
- eventName: `${log.name}.entity_credential_repointed`,
272
- entityId: existingEntity.id,
273
- previousCredentialId: existingCredentialId,
274
- credentialId,
275
- });
222
+ console.log(
223
+ `[Frigg] Repointing entity ${existingEntity.id} credentialId ${existingCredentialId} -> ${credentialId} after re-auth`
224
+ );
276
225
  const updated = await this.moduleRepository.updateEntity(
277
226
  existingEntity.id,
278
227
  { credential: credentialId }
@@ -1,7 +1,4 @@
1
1
  const { Module } = require('../module');
2
- const {
3
- findModuleDefinitionForEntity,
4
- } = require('../utils/find-module-definition');
5
2
 
6
3
  class RefreshEntityOptions {
7
4
  /**
@@ -49,10 +46,11 @@ class RefreshEntityOptions {
49
46
  }
50
47
 
51
48
  const entityType = entity.moduleName;
52
- const moduleDefinition = findModuleDefinitionForEntity(
53
- this.moduleDefinitions,
54
- entity
55
- );
49
+ const moduleDefinition = this.moduleDefinitions.find((def) => {
50
+ const modelName =
51
+ Module.getEntityModelFromDefinition(def).modelName;
52
+ return entityType === modelName;
53
+ });
56
54
 
57
55
  if (!moduleDefinition) {
58
56
  throw new Error(
@@ -1,7 +1,4 @@
1
1
  const { Module } = require('../module');
2
- const {
3
- findModuleDefinitionForEntity,
4
- } = require('../utils/find-module-definition');
5
2
 
6
3
  class TestModuleAuth {
7
4
  /**
@@ -48,10 +45,11 @@ class TestModuleAuth {
48
45
  }
49
46
 
50
47
  const entityType = entity.moduleName;
51
- const moduleDefinition = findModuleDefinitionForEntity(
52
- this.moduleDefinitions,
53
- entity
54
- );
48
+ const moduleDefinition = this.moduleDefinitions.find((def) => {
49
+ const modelName =
50
+ Module.getEntityModelFromDefinition(def).modelName;
51
+ return entityType === modelName;
52
+ });
55
53
 
56
54
  if (!moduleDefinition) {
57
55
  throw new Error(
@@ -1,5 +1,3 @@
1
- const { toCredentialId } = require('./to-credential-id');
2
-
3
1
  /**
4
2
  * @param {import('../module').Module} moduleInstance
5
3
  * Convert a Module domain instance to a plain DTO suitable for JSON responses.
@@ -12,9 +10,9 @@ function mapModuleClassToModuleDTO(moduleInstance) {
12
10
  name: moduleInstance.name,
13
11
  userId: moduleInstance.userId,
14
12
  entity: moduleInstance.entity,
15
- credentialId: toCredentialId(moduleInstance.credential),
16
- type: moduleInstance.getName(),
13
+ credentialId: moduleInstance.credential?._id?.toString(),
14
+ type: moduleInstance.getName()
17
15
  };
18
16
  }
19
17
 
20
- module.exports = { mapModuleClassToModuleDTO };
18
+ module.exports = { mapModuleClassToModuleDTO };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@friggframework/core",
3
3
  "prettier": "@friggframework/prettier-config",
4
- "version": "2.0.0--canary.731.ffe61d3.0",
4
+ "version": "2.0.0--canary.657.18fb0ee.0",
5
5
  "dependencies": {
6
6
  "@aws-sdk/client-apigatewaymanagementapi": "^3.588.0",
7
7
  "@aws-sdk/client-kms": "^3.588.0",
@@ -11,7 +11,6 @@
11
11
  "@aws-sdk/client-sqs": "^3.588.0",
12
12
  "@aws-sdk/client-ssm": "^3.588.0",
13
13
  "@aws-sdk/s3-request-presigner": "^3.588.0",
14
- "@friggframework/schemas": "2.0.0--canary.731.ffe61d3.0",
15
14
  "@hapi/boom": "^10.0.1",
16
15
  "@opentelemetry/api": "^1.9.1",
17
16
  "@opentelemetry/context-async-hooks": "^2.9.0",
@@ -21,12 +20,12 @@
21
20
  "@opentelemetry/sdk-metrics": "^2.9.0",
22
21
  "@opentelemetry/sdk-trace-base": "^2.9.0",
23
22
  "bcryptjs": "^2.4.3",
24
- "body-parser": "^1.20.9",
23
+ "body-parser": "^1.20.5",
25
24
  "bson": "^4.7.2",
26
25
  "chalk": "^4.1.2",
27
26
  "cors": "^2.8.5",
28
27
  "dotenv": "^16.4.7",
29
- "express": "^4.22.3",
28
+ "express": "^4.22.2",
30
29
  "express-async-handler": "^1.2.0",
31
30
  "form-data": "^4.0.6",
32
31
  "fs-extra": "^11.2.0",
@@ -49,12 +48,13 @@
49
48
  }
50
49
  },
51
50
  "devDependencies": {
52
- "@friggframework/eslint-config": "2.0.0--canary.731.ffe61d3.0",
53
- "@friggframework/prettier-config": "2.0.0--canary.731.ffe61d3.0",
54
- "@friggframework/test": "2.0.0--canary.731.ffe61d3.0",
51
+ "@friggframework/eslint-config": "2.0.0--canary.657.18fb0ee.0",
52
+ "@friggframework/prettier-config": "2.0.0--canary.657.18fb0ee.0",
53
+ "@friggframework/test": "2.0.0--canary.657.18fb0ee.0",
55
54
  "@prisma/client": "^6.19.3",
56
55
  "@types/lodash": "4.17.15",
57
56
  "@typescript-eslint/eslint-plugin": "^8.0.0",
57
+ "aws-sdk-client-mock": "^4.1.0",
58
58
  "chai": "^4.3.6",
59
59
  "eslint": "^8.22.0",
60
60
  "eslint-plugin-import": "^2.29.1",
@@ -69,7 +69,6 @@
69
69
  "scripts": {
70
70
  "lint:fix": "prettier --write --loglevel error . && eslint . --fix",
71
71
  "test": "jest --passWithNoTests # TODO",
72
- "test:db": "jest --config jest.db.config.js --runInBand",
73
72
  "prisma:generate:mongo": "npx prisma generate --schema ./prisma-mongodb/schema.prisma",
74
73
  "prisma:generate:postgres": "npx prisma generate --schema ./prisma-postgresql/schema.prisma",
75
74
  "prisma:generate": "npm run prisma:generate:mongo && npm run prisma:generate:postgres",
@@ -92,5 +91,5 @@
92
91
  "publishConfig": {
93
92
  "access": "public"
94
93
  },
95
- "gitHead": "ffe61d3981e0f6a83e9c8063efcb77ce121c1286"
94
+ "gitHead": "18fb0eec33ecfe46362d17ff8660d06a929ae9ae"
96
95
  }
@@ -5,7 +5,7 @@
5
5
  generator client {
6
6
  provider = "prisma-client-js"
7
7
  output = "../generated/prisma-mongodb"
8
- binaryTargets = ["native", "rhel-openssl-3.0.x", "linux-arm64-openssl-3.0.x"] // native for local dev, rhel for x86_64 Lambda, linux-arm64 for arm64 Lambda
8
+ binaryTargets = ["native", "rhel-openssl-3.0.x"] // native for local dev, rhel for Lambda deployment
9
9
  // Library engine (default since Prisma 3.x): Rust query engine loads as a
10
10
  // Node-API addon inside the same process. The binary engine forks a child
11
11
  // query-engine subprocess and communicates over a local HTTP/IPC pipe with
@@ -5,7 +5,7 @@
5
5
  generator client {
6
6
  provider = "prisma-client-js"
7
7
  output = "../generated/prisma-postgresql"
8
- binaryTargets = ["native", "rhel-openssl-3.0.x", "linux-arm64-openssl-3.0.x"] // native for local dev, rhel for x86_64 Lambda, linux-arm64 for arm64 Lambda
8
+ binaryTargets = ["native", "rhel-openssl-3.0.x"] // native for local dev, rhel for Lambda deployment
9
9
  // Library engine (default since Prisma 3.x): Rust query engine loads as a
10
10
  // Node-API addon inside the same process. The binary engine forks a child
11
11
  // query-engine subprocess and communicates over a local HTTP/IPC pipe with
@@ -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
  };
@@ -97,17 +97,16 @@ const QueuerUtil = {
97
97
  Id: uuid(),
98
98
  MessageBody: JSON.stringify(entry),
99
99
  });
100
- // Sends 10, then starts a fresh buffer. Each command gets its own
101
- // array: clearing the shared buffer in place would also empty the
102
- // Entries of a command that was already sent.
100
+ // Sends 10, then purges the buffer
103
101
  if (buffer.length === batchSize) {
104
- const batch = buffer.splice(0, buffer.length);
105
102
  const command = new SendMessageBatchCommand({
106
- Entries: batch,
103
+ Entries: buffer,
107
104
  QueueUrl: queueUrl,
108
105
  });
109
106
  const result = await sqs.send(command);
110
- inspectBatchResult(result, queueUrl, batch);
107
+ inspectBatchResult(result, queueUrl, buffer);
108
+ // Purge the buffer
109
+ buffer.splice(0, buffer.length);
111
110
  }
112
111
  }
113
112
 
@@ -127,4 +126,4 @@ const QueuerUtil = {
127
126
  },
128
127
  };
129
128
 
130
- module.exports = { QueuerUtil };
129
+ module.exports = { QueuerUtil, awsConfigOptions };
@@ -16,7 +16,6 @@ const { createTelemetryEventBus } = require('./telemetry-event-bus');
16
16
  const {
17
17
  runWithTelemetryContext,
18
18
  mergeTelemetryContext,
19
- getTelemetryContextStore,
20
19
  } = require('./telemetry-context');
21
20
  const { serializeError } = require('../logs/serialize');
22
21
  const { LOGGER_SCOPE_KEY } = require('../logs/context');
@@ -28,74 +27,6 @@ const TRACER_NAME = 'frigg';
28
27
  const METRIC_EXPORT_INTERVAL_MS =
29
28
  Number(process.env.OTEL_METRIC_EXPORT_INTERVAL_MS) || 60000;
30
29
 
31
- // ADR-011 §2: high-cardinality ids ride baggage/ALS; copy onto SPANS only
32
- // (never metric labels). Keys match withContext baggage entry names.
33
- const BAGGAGE_TO_SPAN_ATTR = Object.freeze({
34
- integrationId: 'frigg.integration_id',
35
- userId: 'frigg.user_id',
36
- integrationType: 'integration_type',
37
- version: 'frigg.version',
38
- });
39
-
40
- function nonEmptyString(value) {
41
- if (value === undefined || value === null) return null;
42
- const s = String(value).trim();
43
- return s.length > 0 ? s : null;
44
- }
45
-
46
- /**
47
- * Built-in processor: stamp active baggage (fallback ALS) onto each new span
48
- * as Frigg span attributes. Runs ahead of BatchSpanProcessor so exported OTLP
49
- * spans carry attribution Watchtower/backends can index. Never touches metrics.
50
- */
51
- class BaggageAttributeSpanProcessor {
52
- onStart(span, parentContext) {
53
- try {
54
- const baggage = otelApi.propagation.getBaggage(parentContext);
55
- const als = getTelemetryContextStore();
56
- const existing =
57
- span && span.attributes && typeof span.attributes === 'object'
58
- ? span.attributes
59
- : null;
60
-
61
- for (const [baggageKey, attrName] of Object.entries(
62
- BAGGAGE_TO_SPAN_ATTR
63
- )) {
64
- if (
65
- existing &&
66
- existing[attrName] !== undefined &&
67
- existing[attrName] !== null
68
- ) {
69
- continue; // explicit span attribute wins
70
- }
71
- let value = null;
72
- if (baggage) {
73
- const entry = baggage.getEntry(baggageKey);
74
- value = nonEmptyString(entry && entry.value);
75
- }
76
- if (!value && als) {
77
- value = nonEmptyString(als[baggageKey]);
78
- }
79
- if (value) {
80
- span.setAttribute(attrName, value);
81
- }
82
- }
83
- } catch (_) {
84
- // Telemetry must never break the wrapped path.
85
- }
86
- }
87
-
88
- onEnd() {}
89
-
90
- shutdown() {
91
- return Promise.resolve();
92
- }
93
-
94
- forceFlush() {
95
- return Promise.resolve();
96
- }
97
- }
98
-
99
30
  /**
100
31
  * Register an AsyncLocalStorage-backed OTel context manager once per process.
101
32
  * Without it `BasicTracerProvider` uses the Noop context manager, so
@@ -152,16 +83,12 @@ class OtelTelemetry {
152
83
  })
153
84
  : new AlwaysOnSampler();
154
85
 
155
- // Attribution processor ahead of the batch exporter so every exported
156
- // span (handler, apimodule, adopter) carries frigg.* ids from baggage.
157
- const spanProcessors = [new BaggageAttributeSpanProcessor()];
158
- if (traceExporter) {
159
- spanProcessors.push(new BatchSpanProcessor(traceExporter));
160
- }
161
86
  this._tracerProvider = new BasicTracerProvider({
162
87
  resource: res,
163
88
  sampler,
164
- spanProcessors,
89
+ spanProcessors: traceExporter
90
+ ? [new BatchSpanProcessor(traceExporter)]
91
+ : [],
165
92
  });
166
93
 
167
94
  const metricReader = metricExporter
@@ -3,14 +3,11 @@
3
3
  * into a normalized config the TelemetryService and
4
4
  * usage rollup consume: `{ exporter, northStar, sampleRatio }`.
5
5
  *
6
- * Exporter default when `Definition.telemetry.exporter` is omitted:
7
- * 1. `OTEL_EXPORTER_OTLP_ENDPOINT` set (non-empty after trim) → `{ type: 'otlp' }`
8
- * (zero-code Watchtower / collector activation on any stage, including local)
9
- * 2. else STAGE=local → `{ type: 'console' }` (visible, free)
10
- * 3. else → `{ type: 'none' }` (deployed stages must not surprise-write to
11
- * CloudWatch; `dev` is a deployed AWS stage)
12
- * An explicit `Definition.telemetry.exporter` always wins over the env var, so
13
- * `{ type: 'none' }` still disables export even when the endpoint is set.
6
+ * Exporter default is keyed off STAGE: only a genuinely LOCAL run (STAGE=local)
7
+ * gets `console` (visible, free); every deployed stage — including `dev` —
8
+ * defaults to `none`. `dev` is a deployed AWS stage, and `console` there would
9
+ * write full spans to CloudWatch by default (cost + a data-exposure surface).
10
+ * Adopters opt into `console`/`otlp` explicitly for deployed stages.
14
11
  */
15
12
  const VALID_EXPORTER_TYPES = [
16
13
  'none',
@@ -21,16 +18,8 @@ const VALID_EXPORTER_TYPES = [
21
18
  'datadog',
22
19
  ];
23
20
 
24
- function hasOtlpEndpointEnv() {
25
- const endpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
26
- return typeof endpoint === 'string' && endpoint.trim().length > 0;
27
- }
28
-
29
21
  function normalizeExporterConfig(exporter, stage) {
30
22
  if (!exporter) {
31
- if (hasOtlpEndpointEnv()) {
32
- return { type: 'otlp' };
33
- }
34
23
  return stage === 'local' ? { type: 'console' } : { type: 'none' };
35
24
  }
36
25
 
@@ -47,21 +47,8 @@ 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
- }
63
50
  state.telemetry = createTelemetry({
64
- exporter,
51
+ exporter: telemetry.exporter,
65
52
  sampleRatio: telemetry.sampleRatio,
66
53
  resource: { service: process.env.FRIGG_STACK || 'frigg', stage },
67
54
  });
@@ -119,19 +119,7 @@ class TokenRepositoryDocumentDB extends TokenRepositoryInterface {
119
119
 
120
120
  getJSONTokenFromBase64BufferToken(buffer) {
121
121
  const tokenStr = Buffer.from(buffer.trim(), 'base64').toString('ascii');
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;
122
+ return JSON.parse(tokenStr);
135
123
  }
136
124
 
137
125
  _mapToken(record) {
@@ -212,19 +212,7 @@ class TokenRepositoryMongo extends TokenRepositoryInterface {
212
212
  */
213
213
  getJSONTokenFromBase64BufferToken(buffer) {
214
214
  const tokenStr = Buffer.from(buffer.trim(), 'base64').toString('ascii');
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;
215
+ return JSON.parse(tokenStr);
228
216
  }
229
217
  }
230
218