@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
@@ -1,4 +1,7 @@
1
1
  const { Module } = require('../module');
2
+ const {
3
+ findModuleDefinitionForEntity,
4
+ } = require('../utils/find-module-definition');
2
5
 
3
6
  class GetModule {
4
7
  constructor({ moduleRepository, moduleDefinitions }) {
@@ -42,10 +45,10 @@ class GetModule {
42
45
  }
43
46
 
44
47
  const entityType = entity.moduleName;
45
- const moduleDefinition = this.moduleDefinitions.find((def) => {
46
- const modelName = Module.getEntityModelFromDefinition(def).modelName;
47
- return entityType === modelName;
48
- });
48
+ const moduleDefinition = findModuleDefinitionForEntity(
49
+ this.moduleDefinitions,
50
+ entity
51
+ );
49
52
 
50
53
  if (!moduleDefinition) {
51
54
  throw new Error(
@@ -59,15 +62,33 @@ class GetModule {
59
62
  definition: moduleDefinition,
60
63
  });
61
64
 
62
- // todo: this properties should be methods in the Module class
65
+ // The credential itself (tokens, API keys) never leaves the server:
66
+ // the response names it and says whether it still works, as the v2
67
+ // entity DTO does.
68
+ const credential = module.credential;
69
+ const credentialId =
70
+ credential && typeof credential === 'object'
71
+ ? credential.id
72
+ : credential;
73
+ const ownerId = module.entity.userId ?? module.entity.user;
63
74
  return {
64
75
  id: module.entity.id,
65
76
  name: module.entity.name,
66
77
  moduleName: module.entity.moduleName,
67
- credential: module.credential,
78
+ credentialId:
79
+ credentialId === undefined || credentialId === null
80
+ ? null
81
+ : String(credentialId),
82
+ authIsValid:
83
+ typeof credential?.authIsValid === 'boolean'
84
+ ? credential.authIsValid
85
+ : null,
68
86
  externalId: module.entity.externalId,
69
- userId: module.entity.user.toString(),
70
- }
87
+ userId:
88
+ ownerId === undefined || ownerId === null
89
+ ? null
90
+ : String(ownerId),
91
+ };
71
92
  }
72
93
  }
73
94
 
@@ -1,5 +1,8 @@
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');
3
6
 
4
7
  // Statuses considered "broken" for an integration whose credentials have just
5
8
  // been successfully re-authorized. Both ERROR (system-driven auth failure) and
@@ -28,10 +31,12 @@ class ProcessAuthorizationCallback {
28
31
  }
29
32
 
30
33
  async execute(userId, entityType, params) {
31
- const hasCode = Boolean(params && params.code);
32
- console.log(
33
- `[Frigg] processAuthorizationCallback start userId=${userId} entityType=${entityType} hasCode=${hasCode}`
34
- );
34
+ log.debug('Authorization callback started', {
35
+ eventName: `${log.name}.started`,
36
+ userId,
37
+ entityType,
38
+ hasCode: Boolean(params && params.code),
39
+ });
35
40
 
36
41
  const moduleDefinition = this.moduleDefinitions.find((def) => {
37
42
  return entityType === def.moduleName;
@@ -58,9 +63,11 @@ class ProcessAuthorizationCallback {
58
63
  : null;
59
64
 
60
65
  if (existingEntity) {
61
- console.log(
62
- `[Frigg] processAuthorizationCallback found existing entity id=${existingEntity.id} credentialId=${existingEntity.credential?.id}`
63
- );
66
+ log.debug('Existing entity found', {
67
+ eventName: `${log.name}.existing_entity_found`,
68
+ entityId: existingEntity.id,
69
+ credentialId: existingEntity.credential?.id,
70
+ });
64
71
  }
65
72
 
66
73
  const module = new Module({
@@ -69,15 +76,26 @@ class ProcessAuthorizationCallback {
69
76
  definition: moduleDefinition,
70
77
  });
71
78
 
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
+
72
86
  let tokenResponse;
73
- if (module.apiClass.requesterType === ModuleConstants.authType.oauth2) {
87
+ if (authType === ModuleConstants.authType.oauth2) {
88
+ log.debug('Exchanging authorization code for token', {
89
+ eventName: `${log.name}.token_exchanging`,
90
+ });
74
91
  tokenResponse = await moduleDefinition.requiredAuthMethods.getToken(
75
92
  module.api,
76
93
  params
77
94
  );
78
- console.log(
79
- `[Frigg] processAuthorizationCallback OAuth getToken complete userId=${userId} entityType=${entityType}`
80
- );
95
+ log.debug('Token exchange completed', {
96
+ eventName: `${log.name}.token_exchanged`,
97
+ tokenKeys: Object.keys(tokenResponse || {}),
98
+ });
81
99
  // Belt-and-suspenders: persist tokens explicitly here rather than
82
100
  // relying solely on the DLGT_TOKEN_UPDATE notification chain
83
101
  // inside setTokens. The notification path remains in place but
@@ -86,6 +104,9 @@ class ProcessAuthorizationCallback {
86
104
  // OAuth flow appears to succeed.
87
105
  await this.onTokenUpdate(module, moduleDefinition, userId);
88
106
  } else {
107
+ log.debug('Setting auth params', {
108
+ eventName: `${log.name}.auth_params_setting`,
109
+ });
89
110
  tokenResponse =
90
111
  await moduleDefinition.requiredAuthMethods.setAuthParams(
91
112
  module.api,
@@ -94,15 +115,24 @@ class ProcessAuthorizationCallback {
94
115
  await this.onTokenUpdate(module, moduleDefinition, userId);
95
116
  }
96
117
 
97
- console.log(
98
- `[Frigg] processAuthorizationCallback credential persisted credentialId=${module.credential?.id} authIsValid=${module.credential?.authIsValid}`
99
- );
118
+ log.debug('Credential persisted', {
119
+ eventName: `${log.name}.credential_persisted`,
120
+ credentialId: module.credential?.id,
121
+ authIsValid: module.credential?.authIsValid,
122
+ });
100
123
 
124
+ log.debug('Testing auth', { eventName: `${log.name}.auth_testing` });
101
125
  const authRes = await module.testAuth();
102
126
  if (!authRes) {
103
127
  throw new Error('Authorization failed');
104
128
  }
129
+ log.debug('Auth test passed', {
130
+ eventName: `${log.name}.auth_test_passed`,
131
+ });
105
132
 
133
+ log.debug('Fetching entity details', {
134
+ eventName: `${log.name}.entity_details_fetching`,
135
+ });
106
136
  const entityDetails =
107
137
  await moduleDefinition.requiredAuthMethods.getEntityDetails(
108
138
  module.api,
@@ -110,17 +140,29 @@ class ProcessAuthorizationCallback {
110
140
  tokenResponse,
111
141
  userId
112
142
  );
143
+ log.debug('Entity details received', {
144
+ eventName: `${log.name}.entity_details_received`,
145
+ externalId: entityDetails.identifiers?.externalId,
146
+ });
113
147
 
114
148
  Object.assign(
115
149
  entityDetails.details,
116
150
  module.apiParamsFromEntity(module.api)
117
151
  );
118
152
 
153
+ log.debug('Finding or creating entity', {
154
+ eventName: `${log.name}.entity_resolving`,
155
+ });
119
156
  const persistedEntity = await this.findOrCreateEntity(
120
157
  entityDetails,
121
158
  entityType,
122
159
  module.credential.id
123
160
  );
161
+ log.debug('Authorization callback completed', {
162
+ eventName: `${log.name}.completed`,
163
+ entityId: persistedEntity.id,
164
+ credentialId: module.credential.id,
165
+ });
124
166
 
125
167
  // Best-effort: a hiccup here must not fail a successful re-auth whose
126
168
  // credential + entity are already persisted. Operators can recover
@@ -129,14 +171,17 @@ class ProcessAuthorizationCallback {
129
171
  const restoredCount = await this.restoreIntegrationsForEntity(
130
172
  persistedEntity.id
131
173
  );
132
- console.log(
133
- `[Frigg] processAuthorizationCallback restored ${restoredCount} integration(s) for entityId=${persistedEntity.id}`
134
- );
174
+ log.debug('Integrations restored', {
175
+ eventName: `${log.name}.integrations_restored`,
176
+ entityId: persistedEntity.id,
177
+ restoredCount,
178
+ });
135
179
  } catch (err) {
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
- );
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
+ });
140
185
  }
141
186
 
142
187
  return {
@@ -155,9 +200,12 @@ class ProcessAuthorizationCallback {
155
200
  let restored = 0;
156
201
  for (const integration of integrations) {
157
202
  if (STATUSES_RESET_ON_REAUTH.includes(integration.status)) {
158
- console.log(
159
- `[Frigg] Restoring integration ${integration.id} from ${integration.status} to ENABLED after successful re-auth (entityId=${entityId})`
160
- );
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
+ });
161
209
  await this.integrationRepository.updateIntegrationStatus(
162
210
  integration.id,
163
211
  'ENABLED'
@@ -219,9 +267,12 @@ class ProcessAuthorizationCallback {
219
267
  credentialId &&
220
268
  String(existingCredentialId) !== String(credentialId)
221
269
  ) {
222
- console.log(
223
- `[Frigg] Repointing entity ${existingEntity.id} credentialId ${existingCredentialId} -> ${credentialId} after re-auth`
224
- );
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
+ });
225
276
  const updated = await this.moduleRepository.updateEntity(
226
277
  existingEntity.id,
227
278
  { credential: credentialId }
@@ -1,4 +1,7 @@
1
1
  const { Module } = require('../module');
2
+ const {
3
+ findModuleDefinitionForEntity,
4
+ } = require('../utils/find-module-definition');
2
5
 
3
6
  class RefreshEntityOptions {
4
7
  /**
@@ -46,11 +49,10 @@ class RefreshEntityOptions {
46
49
  }
47
50
 
48
51
  const entityType = entity.moduleName;
49
- const moduleDefinition = this.moduleDefinitions.find((def) => {
50
- const modelName =
51
- Module.getEntityModelFromDefinition(def).modelName;
52
- return entityType === modelName;
53
- });
52
+ const moduleDefinition = findModuleDefinitionForEntity(
53
+ this.moduleDefinitions,
54
+ entity
55
+ );
54
56
 
55
57
  if (!moduleDefinition) {
56
58
  throw new Error(
@@ -1,4 +1,7 @@
1
1
  const { Module } = require('../module');
2
+ const {
3
+ findModuleDefinitionForEntity,
4
+ } = require('../utils/find-module-definition');
2
5
 
3
6
  class TestModuleAuth {
4
7
  /**
@@ -45,11 +48,10 @@ class TestModuleAuth {
45
48
  }
46
49
 
47
50
  const entityType = entity.moduleName;
48
- const moduleDefinition = this.moduleDefinitions.find((def) => {
49
- const modelName =
50
- Module.getEntityModelFromDefinition(def).modelName;
51
- return entityType === modelName;
52
- });
51
+ const moduleDefinition = findModuleDefinitionForEntity(
52
+ this.moduleDefinitions,
53
+ entity
54
+ );
53
55
 
54
56
  if (!moduleDefinition) {
55
57
  throw new Error(
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The API module definition a stored entity belongs to.
3
+ *
4
+ * Entities are persisted with `moduleName` set to the definition's
5
+ * `moduleName` (see ProcessAuthorizationCallback.findOrCreateEntity). A
6
+ * definition's legacy `modelName` is accepted as well, for entities written
7
+ * before the two were the same.
8
+ *
9
+ * @param {Array<Object>} moduleDefinitions
10
+ * @param {Object} entity - entity record with a `moduleName`
11
+ * @returns {Object|undefined}
12
+ */
13
+ function findModuleDefinitionForEntity(moduleDefinitions, entity) {
14
+ const entityType = entity?.moduleName;
15
+ if (!entityType) return undefined;
16
+ return (moduleDefinitions || []).find(
17
+ (def) =>
18
+ def &&
19
+ (def.moduleName === entityType || def.modelName === entityType)
20
+ );
21
+ }
22
+
23
+ module.exports = { findModuleDefinitionForEntity };
@@ -1,3 +1,5 @@
1
+ const { toCredentialId } = require('./to-credential-id');
2
+
1
3
  /**
2
4
  * @param {import('../module').Module} moduleInstance
3
5
  * Convert a Module domain instance to a plain DTO suitable for JSON responses.
@@ -10,9 +12,9 @@ function mapModuleClassToModuleDTO(moduleInstance) {
10
12
  name: moduleInstance.name,
11
13
  userId: moduleInstance.userId,
12
14
  entity: moduleInstance.entity,
13
- credentialId: moduleInstance.credential?._id?.toString(),
14
- type: moduleInstance.getName()
15
+ credentialId: toCredentialId(moduleInstance.credential),
16
+ type: moduleInstance.getName(),
15
17
  };
16
18
  }
17
19
 
18
- module.exports = { mapModuleClassToModuleDTO };
20
+ module.exports = { mapModuleClassToModuleDTO };
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Resolve the credential id from an entity's or module's `credential`, which
3
+ * repositories return as the decrypted credential object (or a bare id).
4
+ * @param {Object|string|number|null|undefined} credential
5
+ * @returns {string|null}
6
+ */
7
+ function toCredentialId(credential) {
8
+ if (credential && typeof credential === 'object') {
9
+ return credential.id?.toString() ?? null;
10
+ }
11
+ return credential?.toString() ?? null;
12
+ }
13
+
14
+ module.exports = { toCredentialId };
package/package.json CHANGED
@@ -1,15 +1,17 @@
1
1
  {
2
2
  "name": "@friggframework/core",
3
3
  "prettier": "@friggframework/prettier-config",
4
- "version": "2.0.0--canary.658.e11f3b0.0",
4
+ "version": "2.0.0--canary.737.83b4e17.0",
5
5
  "dependencies": {
6
6
  "@aws-sdk/client-apigatewaymanagementapi": "^3.588.0",
7
7
  "@aws-sdk/client-kms": "^3.588.0",
8
8
  "@aws-sdk/client-lambda": "^3.714.0",
9
9
  "@aws-sdk/client-s3": "^3.588.0",
10
+ "@aws-sdk/client-scheduler": "^3.588.0",
10
11
  "@aws-sdk/client-sqs": "^3.588.0",
11
12
  "@aws-sdk/client-ssm": "^3.588.0",
12
13
  "@aws-sdk/s3-request-presigner": "^3.588.0",
14
+ "@friggframework/schemas": "2.0.0--canary.737.83b4e17.0",
13
15
  "@hapi/boom": "^10.0.1",
14
16
  "@opentelemetry/api": "^1.9.1",
15
17
  "@opentelemetry/context-async-hooks": "^2.9.0",
@@ -19,12 +21,12 @@
19
21
  "@opentelemetry/sdk-metrics": "^2.9.0",
20
22
  "@opentelemetry/sdk-trace-base": "^2.9.0",
21
23
  "bcryptjs": "^2.4.3",
22
- "body-parser": "^1.20.5",
24
+ "body-parser": "^1.20.9",
23
25
  "bson": "^4.7.2",
24
26
  "chalk": "^4.1.2",
25
27
  "cors": "^2.8.5",
26
28
  "dotenv": "^16.4.7",
27
- "express": "^4.22.2",
29
+ "express": "^4.22.3",
28
30
  "express-async-handler": "^1.2.0",
29
31
  "form-data": "^4.0.6",
30
32
  "fs-extra": "^11.2.0",
@@ -47,9 +49,9 @@
47
49
  }
48
50
  },
49
51
  "devDependencies": {
50
- "@friggframework/eslint-config": "2.0.0--canary.658.e11f3b0.0",
51
- "@friggframework/prettier-config": "2.0.0--canary.658.e11f3b0.0",
52
- "@friggframework/test": "2.0.0--canary.658.e11f3b0.0",
52
+ "@friggframework/eslint-config": "2.0.0--canary.737.83b4e17.0",
53
+ "@friggframework/prettier-config": "2.0.0--canary.737.83b4e17.0",
54
+ "@friggframework/test": "2.0.0--canary.737.83b4e17.0",
53
55
  "@prisma/client": "^6.19.3",
54
56
  "@types/lodash": "4.17.15",
55
57
  "@typescript-eslint/eslint-plugin": "^8.0.0",
@@ -67,6 +69,7 @@
67
69
  "scripts": {
68
70
  "lint:fix": "prettier --write --loglevel error . && eslint . --fix",
69
71
  "test": "jest --passWithNoTests # TODO",
72
+ "test:db": "jest --config jest.db.config.js --runInBand",
70
73
  "prisma:generate:mongo": "npx prisma generate --schema ./prisma-mongodb/schema.prisma",
71
74
  "prisma:generate:postgres": "npx prisma generate --schema ./prisma-postgresql/schema.prisma",
72
75
  "prisma:generate": "npm run prisma:generate:mongo && npm run prisma:generate:postgres",
@@ -89,5 +92,5 @@
89
92
  "publishConfig": {
90
93
  "access": "public"
91
94
  },
92
- "gitHead": "e11f3b028efaf4d1f0afba0bf94022537a210356"
95
+ "gitHead": "83b4e17ac7ec4481bd8143508a2a532e399fcce8"
93
96
  }
@@ -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"] // native for local dev, rhel for Lambda deployment
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
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"] // native for local dev, rhel for Lambda deployment
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
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
@@ -1,6 +1,7 @@
1
1
  const { v4: uuid } = require('uuid');
2
2
  const { SQSClient, SendMessageCommand, SendMessageBatchCommand } = require('@aws-sdk/client-sqs');
3
3
  const { summarizeMessageBody } = require('../logs/summarize-event');
4
+ const { toSqsMessageBody } = require('./sqs-message-body');
4
5
 
5
6
  const awsConfigOptions = () => {
6
7
  const config = {};
@@ -78,7 +79,7 @@ const inspectBatchResult = (result, queueUrl, buffer) => {
78
79
  const QueuerUtil = {
79
80
  send: async (message, queueUrl) => {
80
81
  const command = new SendMessageCommand({
81
- MessageBody: JSON.stringify(message),
82
+ MessageBody: toSqsMessageBody(message),
82
83
  QueueUrl: queueUrl,
83
84
  });
84
85
  const result = await sqs.send(command);
@@ -95,18 +96,19 @@ const QueuerUtil = {
95
96
  for (const entry of entries) {
96
97
  buffer.push({
97
98
  Id: uuid(),
98
- MessageBody: JSON.stringify(entry),
99
+ MessageBody: toSqsMessageBody(entry),
99
100
  });
100
- // Sends 10, then purges the buffer
101
+ // Sends 10, then starts a fresh buffer. Each command gets its own
102
+ // array: clearing the shared buffer in place would also empty the
103
+ // Entries of a command that was already sent.
101
104
  if (buffer.length === batchSize) {
105
+ const batch = buffer.splice(0, buffer.length);
102
106
  const command = new SendMessageBatchCommand({
103
- Entries: buffer,
107
+ Entries: batch,
104
108
  QueueUrl: queueUrl,
105
109
  });
106
110
  const result = await sqs.send(command);
107
- inspectBatchResult(result, queueUrl, buffer);
108
- // Purge the buffer
109
- buffer.splice(0, buffer.length);
111
+ inspectBatchResult(result, queueUrl, batch);
110
112
  }
111
113
  }
112
114
 
@@ -0,0 +1,17 @@
1
+ // SQS accepts only #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] |
2
+ // [#x10000-#x10FFFF] and rejects the whole message otherwise
3
+ // (InvalidMessageContents). JSON.stringify already escapes control characters
4
+ // and lone surrogates, but leaves U+FFFE and U+FFFF raw. Those can only occur
5
+ // inside JSON strings, so a \uXXXX escape keeps the JSON valid and JSON.parse
6
+ // returns the original message exactly.
7
+ const SQS_DISALLOWED_CHARACTERS =
8
+ /[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}]/gu;
9
+
10
+ const toSqsMessageBody = (message) =>
11
+ JSON.stringify(message).replace(
12
+ SQS_DISALLOWED_CHARACTERS,
13
+ (character) =>
14
+ `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`
15
+ );
16
+
17
+ module.exports = { toSqsMessageBody };
@@ -16,6 +16,7 @@ const { createTelemetryEventBus } = require('./telemetry-event-bus');
16
16
  const {
17
17
  runWithTelemetryContext,
18
18
  mergeTelemetryContext,
19
+ getTelemetryContextStore,
19
20
  } = require('./telemetry-context');
20
21
  const { serializeError } = require('../logs/serialize');
21
22
  const { LOGGER_SCOPE_KEY } = require('../logs/context');
@@ -27,6 +28,74 @@ const TRACER_NAME = 'frigg';
27
28
  const METRIC_EXPORT_INTERVAL_MS =
28
29
  Number(process.env.OTEL_METRIC_EXPORT_INTERVAL_MS) || 60000;
29
30
 
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
+
30
99
  /**
31
100
  * Register an AsyncLocalStorage-backed OTel context manager once per process.
32
101
  * Without it `BasicTracerProvider` uses the Noop context manager, so
@@ -83,12 +152,16 @@ class OtelTelemetry {
83
152
  })
84
153
  : new AlwaysOnSampler();
85
154
 
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
+ }
86
161
  this._tracerProvider = new BasicTracerProvider({
87
162
  resource: res,
88
163
  sampler,
89
- spanProcessors: traceExporter
90
- ? [new BatchSpanProcessor(traceExporter)]
91
- : [],
164
+ spanProcessors,
92
165
  });
93
166
 
94
167
  const metricReader = metricExporter
@@ -3,11 +3,14 @@
3
3
  * into a normalized config the TelemetryService and
4
4
  * usage rollup consume: `{ exporter, northStar, sampleRatio }`.
5
5
  *
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.
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.
11
14
  */
12
15
  const VALID_EXPORTER_TYPES = [
13
16
  'none',
@@ -18,8 +21,16 @@ const VALID_EXPORTER_TYPES = [
18
21
  'datadog',
19
22
  ];
20
23
 
24
+ function hasOtlpEndpointEnv() {
25
+ const endpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
26
+ return typeof endpoint === 'string' && endpoint.trim().length > 0;
27
+ }
28
+
21
29
  function normalizeExporterConfig(exporter, stage) {
22
30
  if (!exporter) {
31
+ if (hasOtlpEndpointEnv()) {
32
+ return { type: 'otlp' };
33
+ }
23
34
  return stage === 'local' ? { type: 'console' } : { type: 'none' };
24
35
  }
25
36