@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
package/core/Worker.js CHANGED
@@ -1,14 +1,38 @@
1
- const { SQSClient, GetQueueUrlCommand, SendMessageCommand } = require('@aws-sdk/client-sqs');
1
+ const {
2
+ SQSClient,
3
+ GetQueueUrlCommand,
4
+ SendMessageCommand,
5
+ ChangeMessageVisibilityCommand,
6
+ } = require('@aws-sdk/client-sqs');
2
7
  const _ = require('lodash');
3
8
  const { RequiredPropertyError } = require('../errors');
4
9
  const { get } = require('../assertions');
5
10
  const { readQueueDelivery } = require('../queues/queue-delivery');
11
+ const { awsConfigOptions } = require('../queues/queuer-util');
12
+ const {
13
+ MAX_DEFERRED_VISIBILITY_SECONDS,
14
+ MAX_DELAY_SECONDS,
15
+ deferredMs,
16
+ isDeferralCapped,
17
+ nextDeferral,
18
+ readDeferral,
19
+ readDeferralLimits,
20
+ withDeferral,
21
+ } = require('../queues/queue-deferral');
6
22
  const { runMessageScope } = require('./invocation-scope');
7
23
  const { getLogger } = require('../logs');
8
24
 
9
- const sqs = new SQSClient({ region: process.env.AWS_REGION });
25
+ const sqs = new SQSClient({
26
+ region: process.env.AWS_REGION,
27
+ ...awsConfigOptions(),
28
+ });
10
29
  const log = getLogger('frigg.worker');
11
30
 
31
+ const validDate = (value) =>
32
+ value instanceof Date && !Number.isNaN(value.getTime()) ? value : null;
33
+ const queueNameOf = (arn) =>
34
+ typeof arn === 'string' && arn ? arn.split(':').pop() : undefined;
35
+
12
36
  class Worker {
13
37
  async getQueueURL(params) {
14
38
  // Passing params in because there will be multiple QueueNames
@@ -33,12 +57,31 @@ class Worker {
33
57
  // messageId, receiveCount and the event come from the scope.
34
58
  log.debug('Record started', { eventName: 'frigg.worker.record_started' });
35
59
 
60
+ const delivery = readQueueDelivery(record);
61
+ let runParams;
36
62
  try {
37
- const runParams = JSON.parse(record.body);
63
+ runParams = JSON.parse(record.body);
38
64
  this._validateParams(runParams);
39
- await this._run(runParams, context, readQueueDelivery(record));
65
+ await this._run(runParams, context, delivery);
66
+ await this._clearDeferredState(record, runParams, delivery);
40
67
  log.debug('Record succeeded', { eventName: 'frigg.worker.record_succeeded' });
41
68
  } catch (error) {
69
+ let deferralResult;
70
+ if (error.isRateLimited && runParams) {
71
+ deferralResult = await this.defer(
72
+ record,
73
+ runParams,
74
+ error,
75
+ delivery
76
+ );
77
+ if (deferralResult.outcome === 'acked') return;
78
+ if (deferralResult.outcome === 'failed') {
79
+ batchItemFailures.push({
80
+ itemIdentifier: record.messageId,
81
+ });
82
+ return;
83
+ }
84
+ }
42
85
  if (error.isHaltError) {
43
86
  // HaltError means "discard this message, don't retry".
44
87
  // Treat as success so SQS deletes it from the queue.
@@ -51,11 +94,30 @@ class Worker {
51
94
  });
52
95
  return;
53
96
  }
54
- // The message goes back to SQS, so WARN (ADR-048 §4).
55
- log.warn('Record failed, returned for retry', {
56
- eventName: 'frigg.worker.record_failed',
57
- error,
58
- });
97
+ const skippedDeferral = deferralResult && {
98
+ deferral: {
99
+ skipped: deferralResult.skipped,
100
+ ...(deferralResult.cause && {
101
+ cause: deferralResult.cause,
102
+ }),
103
+ },
104
+ };
105
+ if (skippedDeferral && delivery.isLastAttempt) {
106
+ this._logLost({
107
+ retryAt: validDate(error.retryAt)?.toISOString(),
108
+ reason: error.reason,
109
+ module: error.module,
110
+ ...skippedDeferral,
111
+ error,
112
+ });
113
+ } else {
114
+ // The message goes back to SQS, so WARN (ADR-048 §4).
115
+ log.warn('Record failed, returned for retry', {
116
+ eventName: 'frigg.worker.record_failed',
117
+ error,
118
+ ...skippedDeferral,
119
+ });
120
+ }
59
121
  batchItemFailures.push({ itemIdentifier: record.messageId });
60
122
  }
61
123
  });
@@ -75,6 +137,245 @@ class Worker {
75
137
  // parameters
76
138
  }
77
139
 
140
+ async defer(record, body, error, delivery) {
141
+ const retryAt = validDate(error.retryAt);
142
+ if (!retryAt) return { outcome: 'skipped', skipped: 'no_retry_at' };
143
+ const queueName = queueNameOf(record.eventSourceARN);
144
+ if (!queueName || queueName.endsWith('.fifo')) {
145
+ return { outcome: 'skipped', skipped: 'no_event_source' };
146
+ }
147
+
148
+ const now = Date.now();
149
+ const counters = nextDeferral(body, now, record.messageId);
150
+ const deferral = {
151
+ record,
152
+ queueName,
153
+ body,
154
+ deferredBody: withDeferral(body, counters),
155
+ error,
156
+ delivery,
157
+ retryAt,
158
+ waitMs: Math.max(0, retryAt.getTime() - now),
159
+ counters,
160
+ };
161
+
162
+ const limits = readDeferralLimits();
163
+ if (isDeferralCapped({ ...counters, retryAt }, limits)) {
164
+ await this._recordWait(deferral, 'EXHAUSTED', 'none');
165
+ this._logUnacked(
166
+ deferral,
167
+ 'record_deferral_capped',
168
+ 'Rate-limit deferral capped',
169
+ {
170
+ maxDeferrals: limits.maxDeferrals,
171
+ maxDeferredMs: limits.maxDeferredMs,
172
+ deferredMs: deferredMs({ ...counters, retryAt }),
173
+ }
174
+ );
175
+ return { outcome: 'failed' };
176
+ }
177
+
178
+ if (deferral.waitMs <= MAX_DELAY_SECONDS * 1000)
179
+ return this._deferWithDelay(deferral);
180
+ const scheduled = await this._deferWithSchedule(deferral);
181
+ if (scheduled?.outcome) return scheduled;
182
+ return this._deferWithVisibility(deferral, scheduled?.scheduleError);
183
+ }
184
+
185
+ async _deferWithDelay(deferral) {
186
+ const delaySeconds = Math.ceil(deferral.waitMs / 1000);
187
+ try {
188
+ const queueUrl = await this._queueUrl(deferral.queueName);
189
+ await this.send(
190
+ { ...deferral.deferredBody, QueueUrl: queueUrl },
191
+ delaySeconds
192
+ );
193
+ } catch (cause) {
194
+ return { outcome: 'skipped', skipped: 'send_failed', cause };
195
+ }
196
+ return this._acknowledgeDeferral(deferral, 'delay', { delaySeconds });
197
+ }
198
+
199
+ async _deferWithSchedule(deferral) {
200
+ const { record, retryAt, deferredBody } = deferral;
201
+ const scheduleName = `frigg-defer-${record.messageId}`;
202
+ try {
203
+ const scheduler = this.getSchedulerService();
204
+ if (!scheduler) return null;
205
+ await scheduler.scheduleOneTime({
206
+ scheduleName,
207
+ scheduleAt: retryAt,
208
+ queueResourceId: record.eventSourceARN,
209
+ payload: deferredBody,
210
+ });
211
+ } catch (cause) {
212
+ if (cause?.name !== 'ConflictException')
213
+ return { scheduleError: cause };
214
+ }
215
+ return this._acknowledgeDeferral(deferral, 'schedule', {
216
+ scheduleName,
217
+ });
218
+ }
219
+
220
+ async _deferWithVisibility(deferral, scheduleError) {
221
+ const { record, queueName, delivery, waitMs } = deferral;
222
+ const visibilityTimeout = Math.min(
223
+ Math.ceil(waitMs / 1000),
224
+ MAX_DEFERRED_VISIBILITY_SECONDS
225
+ );
226
+ try {
227
+ const queueUrl = await this._queueUrl(queueName);
228
+ await sqs.send(
229
+ new ChangeMessageVisibilityCommand({
230
+ QueueUrl: queueUrl,
231
+ ReceiptHandle: record.receiptHandle,
232
+ VisibilityTimeout: visibilityTimeout,
233
+ })
234
+ );
235
+ } catch (cause) {
236
+ return { outcome: 'skipped', skipped: 'visibility_failed', cause };
237
+ }
238
+ await this._recordWait(
239
+ deferral,
240
+ delivery.isLastAttempt ? 'EXHAUSTED' : 'WAITING',
241
+ 'visibility'
242
+ );
243
+ this._logUnacked(
244
+ deferral,
245
+ 'record_visibility_extended',
246
+ 'Record visibility extended',
247
+ {
248
+ mechanism: 'visibility',
249
+ visibilityTimeout,
250
+ ...(scheduleError && { scheduleError }),
251
+ }
252
+ );
253
+ return { outcome: 'failed' };
254
+ }
255
+
256
+ async _acknowledgeDeferral(deferral, mechanism, fields) {
257
+ await this._recordWait(deferral, 'WAITING', mechanism);
258
+ log.warn('Record deferred', {
259
+ eventName: 'frigg.worker.record_deferred',
260
+ mechanism,
261
+ ...fields,
262
+ ...this._deferralLogFields(deferral),
263
+ error: deferral.error,
264
+ });
265
+ return { outcome: 'acked' };
266
+ }
267
+
268
+ getSchedulerService() {
269
+ if (this._schedulerService !== undefined) return this._schedulerService;
270
+ if (
271
+ !process.env.SCHEDULER_ROLE_ARN ||
272
+ process.env.SCHEDULER_PROVIDER === 'mock'
273
+ ) {
274
+ this._schedulerService = null;
275
+ return null;
276
+ }
277
+ const {
278
+ createSchedulerService,
279
+ SCHEDULER_PROVIDERS,
280
+ } = require('../infrastructure/scheduler/scheduler-service-factory');
281
+ this._schedulerService = createSchedulerService({
282
+ provider: SCHEDULER_PROVIDERS.EVENTBRIDGE,
283
+ });
284
+ return this._schedulerService;
285
+ }
286
+
287
+ recordRateLimitWait() {
288
+ return Promise.resolve();
289
+ }
290
+
291
+ clearRateLimitWait() {
292
+ return Promise.resolve();
293
+ }
294
+
295
+ _queueUrl(queueName) {
296
+ this._queueUrls ??= new Map();
297
+ if (!this._queueUrls.has(queueName)) {
298
+ const lookup = this.getQueueURL({ QueueName: queueName }).catch(
299
+ (error) => {
300
+ this._queueUrls.delete(queueName);
301
+ throw error;
302
+ }
303
+ );
304
+ this._queueUrls.set(queueName, lookup);
305
+ }
306
+ return this._queueUrls.get(queueName);
307
+ }
308
+
309
+ async _recordWait({ body, error, counters, retryAt }, status, mechanism) {
310
+ await this._runStateHook('record', () =>
311
+ this.recordRateLimitWait(body, error, {
312
+ status,
313
+ mechanism,
314
+ deferrals: counters.deferrals,
315
+ deferralId: counters.deferralId,
316
+ retryAt,
317
+ })
318
+ );
319
+ }
320
+
321
+ async _clearDeferredState(record, body, delivery) {
322
+ const redelivered = delivery.receiveCount > 1;
323
+ const { deferrals, deferralId } = readDeferral(body);
324
+ if (deferrals === 0 && !redelivered) return;
325
+ await this._runStateHook('clear', () =>
326
+ this.clearRateLimitWait(body, {
327
+ deferralId: deferralId ?? record.messageId,
328
+ })
329
+ );
330
+ }
331
+
332
+ async _runStateHook(operation, hook) {
333
+ try {
334
+ await hook();
335
+ } catch (error) {
336
+ log.warn('Rate-limit run state not written', {
337
+ eventName: 'frigg.worker.rate_limit_state_failed',
338
+ operation,
339
+ error,
340
+ });
341
+ }
342
+ }
343
+
344
+ _deferralLogFields({ error, retryAt, waitMs, counters }) {
345
+ return {
346
+ waitMs,
347
+ retryAt: retryAt.toISOString(),
348
+ deferrals: counters.deferrals,
349
+ firstDeferredAt: counters.firstDeferredAt,
350
+ reason: error.reason,
351
+ module: error.module,
352
+ statusCode: error.statusCode,
353
+ };
354
+ }
355
+
356
+ _logUnacked(deferral, eventName, message, fields) {
357
+ const logFields = {
358
+ ...fields,
359
+ ...this._deferralLogFields(deferral),
360
+ error: deferral.error,
361
+ };
362
+ if (deferral.delivery.isLastAttempt) {
363
+ this._logLost(logFields);
364
+ return;
365
+ }
366
+ log.warn(message, {
367
+ eventName: `frigg.worker.${eventName}`,
368
+ ...logFields,
369
+ });
370
+ }
371
+
372
+ _logLost(fields) {
373
+ log.error(
374
+ 'Rate-limited record lost: the message goes to the dead-letter queue next',
375
+ { eventName: 'frigg.worker.record_lost_rate_limited', ...fields }
376
+ );
377
+ }
378
+
78
379
  // returns the message id
79
380
  async send(params, delay = 0) {
80
381
  this._validateParams(params);
@@ -12,6 +12,7 @@ const {
12
12
  runInvocationScope,
13
13
  DEFAULT_FLUSH_TIMEOUT_MS,
14
14
  } = require('./invocation-scope');
15
+ const { MAX_IN_PROCESS_WAIT_MS } = require('./invocation-deadline');
15
16
  const { secretsToEnv } = require('./secrets-to-env');
16
17
  const { parametersToEnv } = require('./parameters-to-env');
17
18
  const {
@@ -31,6 +32,7 @@ const createHandler = (optionByName = {}) => {
31
32
  telemetry,
32
33
  flushTimeoutMs = DEFAULT_FLUSH_TIMEOUT_MS,
33
34
  usageRollup,
35
+ maxInProcessWaitMs = MAX_IN_PROCESS_WAIT_MS.http,
34
36
  } = optionByName;
35
37
 
36
38
  if (!method) {
@@ -144,6 +146,7 @@ const createHandler = (optionByName = {}) => {
144
146
  shouldUseDatabase,
145
147
  flushTimeoutMs,
146
148
  context,
149
+ maxInProcessWaitMs,
147
150
  }
148
151
  );
149
152
  };
package/core/index.js CHANGED
@@ -3,6 +3,10 @@ const { Worker } = require('./Worker');
3
3
  const { loadInstalledModules } = require('./load-installed-modules');
4
4
  const { createHandler } = require('./create-handler');
5
5
  const { runInvocationScope } = require('./invocation-scope');
6
+ const {
7
+ runWithInvocationDeadline,
8
+ remainingInvocationMs,
9
+ } = require('./invocation-deadline');
6
10
 
7
11
  module.exports = {
8
12
  Delegate,
@@ -10,4 +14,6 @@ module.exports = {
10
14
  loadInstalledModules,
11
15
  createHandler,
12
16
  runInvocationScope,
17
+ runWithInvocationDeadline,
18
+ remainingInvocationMs,
13
19
  };
@@ -0,0 +1,91 @@
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,6 +1,11 @@
1
1
  const { runInContext, LOGGER_SCOPE_KEY } = require('../logs/context');
2
2
  const { summarizeMessageBody } = require('../logs/summarize-event');
3
3
  const { flushSinks, hasFlushableSinks } = require('../logs/logger-runtime');
4
+ const {
5
+ deadlineFromContext,
6
+ remainingTimeMs,
7
+ runWithInvocationDeadline,
8
+ } = require('./invocation-deadline');
4
9
 
5
10
  // Bounds the tail latency telemetry adds to every warm invocation. Kept low so
6
11
  // an unreachable OTLP endpoint (e.g. a VPC Lambda with no NAT/egress) costs at
@@ -111,15 +116,6 @@ function withDeadline(ms, fn) {
111
116
  });
112
117
  }
113
118
 
114
- function remainingTimeMs(context) {
115
- try {
116
- const remaining = context?.getRemainingTimeInMillis?.();
117
- return typeof remaining === 'number' ? remaining : Infinity;
118
- } catch (_) {
119
- return Infinity;
120
- }
121
- }
122
-
123
119
  async function flushInvocation({
124
120
  telemetry,
125
121
  usageRollup,
@@ -167,22 +163,32 @@ async function runInvocationScope(fields, fn, opts = {}) {
167
163
  shouldUseDatabase = true,
168
164
  flushTimeoutMs = DEFAULT_FLUSH_TIMEOUT_MS,
169
165
  context,
166
+ maxInProcessWaitMs,
170
167
  } = opts;
171
- return runInContext({ [LOGGER_SCOPE_KEY]: { ...(fields || {}) } }, async () => {
172
- try {
173
- return await fn();
174
- } finally {
175
- // Every step is guarded, so a flush never changes the result.
176
- await flushInvocation({
177
- telemetry,
178
- usageRollup,
179
- eventSummary,
180
- shouldUseDatabase,
181
- flushTimeoutMs,
182
- context,
183
- });
184
- }
185
- });
168
+ const deadline = {
169
+ deadlineAt: deadlineFromContext(context),
170
+ maxInProcessWaitMs,
171
+ };
172
+ return runWithInvocationDeadline(deadline, () =>
173
+ runInContext(
174
+ { [LOGGER_SCOPE_KEY]: { ...(fields || {}) } },
175
+ async () => {
176
+ try {
177
+ return await fn();
178
+ } finally {
179
+ // Every step is guarded, so a flush never changes the result.
180
+ await flushInvocation({
181
+ telemetry,
182
+ usageRollup,
183
+ eventSummary,
184
+ shouldUseDatabase,
185
+ flushTimeoutMs,
186
+ context,
187
+ });
188
+ }
189
+ }
190
+ )
191
+ );
186
192
  }
187
193
 
188
194
  function toCount(value) {
@@ -1,5 +1,4 @@
1
1
  const { Cryptor } = require('../encrypt/Cryptor');
2
- const { isEncryptedEnvelope } = require('./encryption/ciphertext-format');
3
2
  const {
4
3
  getEncryptedFields,
5
4
  getFieldsToEncryptOnWrite,
@@ -296,7 +295,39 @@ class DocumentDBEncryptionService {
296
295
  * _isEncryptedValue({}) // false
297
296
  */
298
297
  _isEncryptedValue(value) {
299
- return isEncryptedEnvelope(value);
298
+ // Must be string
299
+ if (typeof value !== 'string') {
300
+ return false;
301
+ }
302
+
303
+ // Must have exactly 4 colon-separated parts
304
+ const parts = value.split(':');
305
+ if (parts.length !== 4) {
306
+ return false;
307
+ }
308
+
309
+ // Enhanced validation: check for base64 pattern
310
+ // This prevents false positives on URLs, connection strings, etc.
311
+ const base64Pattern = /^[A-Za-z0-9+/=]+$/;
312
+
313
+ // All parts should be base64-encoded
314
+ if (!parts.every(part => base64Pattern.test(part))) {
315
+ return false;
316
+ }
317
+
318
+ // Encrypted values should be sufficiently long to be valid
319
+ // Real encrypted values from Cryptor are always >50 chars due to envelope encryption format:
320
+ // - keyId (base64): ~12 chars minimum
321
+ // - iv (base64): ~24 chars for 16-byte IV
322
+ // - ciphertext (base64): varies, minimum ~16 chars for small values
323
+ // - encryptedKey (base64): ~44 chars for 32-byte data key
324
+ // Total minimum: ~96 chars, so 50 is a safe lower bound
325
+ // This prevents false positives on non-encrypted strings that happen to have 4 colons
326
+ if (value.length < 50) {
327
+ return false;
328
+ }
329
+
330
+ return true;
300
331
  }
301
332
  }
302
333
 
@@ -58,10 +58,7 @@ async function insertOne(client, collection, document) {
58
58
 
59
59
  // Provide helpful context for common errors
60
60
  if (error.code === 11000) {
61
- throw Object.assign(
62
- new Error(`${errorMsg} - Duplicate key violation`),
63
- { code: 11000 }
64
- );
61
+ throw new Error(`${errorMsg} - Duplicate key violation`);
65
62
  }
66
63
  throw new Error(errorMsg);
67
64
  }
@@ -508,9 +508,9 @@ return entities.map((e) => ({
508
508
 
509
509
  **Verified:**
510
510
 
511
- - ✅ `postgres-relation-decryption.db.test.js` - Proves the bug exists
512
- - ✅ `postgres-decryption-fix-verification.db.test.js` - Verifies separate queries work
513
- - ✅ `mongo-decryption-fix-verification.db.test.js` - Verifies fix for MongoDB
511
+ - ✅ `postgres-relation-decryption.test.js` - Proves the bug exists
512
+ - ✅ `postgres-decryption-fix-verification.test.js` - Verifies separate queries work
513
+ - ✅ `mongo-decryption-fix-verification.test.js` - Verifies fix for MongoDB
514
514
 
515
515
  **Implementation Examples:**
516
516