@friggframework/core 2.0.0-next.127 → 2.0.0-next.129

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 (63) hide show
  1. package/CLAUDE.md +166 -7
  2. package/core/CLAUDE.md +57 -1
  3. package/core/Worker.js +420 -9
  4. package/core/create-handler.js +20 -0
  5. package/core/index.js +6 -0
  6. package/core/invocation-deadline.js +91 -0
  7. package/core/invocation-scope.js +30 -24
  8. package/core/rate-limited-response.js +27 -0
  9. package/database/encryption/field-encryption-service.js +42 -0
  10. package/database/encryption/prisma-encryption-extension.js +6 -9
  11. package/encrypt/Cryptor.js +90 -38
  12. package/errors/fetch-error.js +10 -6
  13. package/errors/index.js +2 -0
  14. package/errors/rate-limit-error.js +46 -0
  15. package/generated/prisma-mongodb/edge.js +6 -2
  16. package/generated/prisma-mongodb/index.js +10 -2
  17. package/generated/prisma-mongodb/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  18. package/generated/prisma-mongodb/package.json +1 -1
  19. package/generated/prisma-mongodb/schema.prisma +1 -1
  20. package/generated/prisma-mongodb/wasm.js +6 -2
  21. package/generated/prisma-postgresql/edge.js +6 -2
  22. package/generated/prisma-postgresql/index.js +10 -2
  23. package/generated/prisma-postgresql/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  24. package/generated/prisma-postgresql/package.json +1 -1
  25. package/generated/prisma-postgresql/schema.prisma +1 -1
  26. package/generated/prisma-postgresql/wasm.js +6 -2
  27. package/handlers/app-handler-helpers.js +15 -0
  28. package/handlers/backend-utils.js +75 -1
  29. package/handlers/workers/integration-defined-workers.js +2 -0
  30. package/index.js +18 -0
  31. package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +2 -0
  32. package/integrations/repositories/integration-repository-documentdb.js +59 -10
  33. package/integrations/repositories/integration-repository-interface.js +50 -7
  34. package/integrations/repositories/integration-repository-mongo.js +88 -16
  35. package/integrations/repositories/integration-repository-postgres.js +89 -16
  36. package/integrations/repositories/message-item-shared.js +17 -0
  37. package/integrations/tests/doubles/prisma-message-row.js +24 -0
  38. package/integrations/tests/doubles/test-integration-repository.js +32 -2
  39. package/integrations/use-cases/clear-rate-limit-wait.js +28 -0
  40. package/integrations/use-cases/index.js +7 -1
  41. package/integrations/use-cases/record-rate-limit-message.js +104 -0
  42. package/integrations/use-cases/record-rate-limit-wait.js +36 -0
  43. package/integrations/use-cases/update-integration-messages.js +28 -9
  44. package/logs/serialize.js +15 -0
  45. package/modules/requester/oauth-2.js +8 -0
  46. package/modules/requester/rate-limit/index.js +4 -0
  47. package/modules/requester/rate-limit/parsers.js +249 -0
  48. package/modules/requester/rate-limit/policy.js +321 -0
  49. package/modules/requester/requester.js +187 -9
  50. package/package.json +7 -6
  51. package/prisma-mongodb/schema.prisma +1 -1
  52. package/prisma-postgresql/schema.prisma +1 -1
  53. package/queues/queue-deferral.js +80 -0
  54. package/queues/queue-delivery.js +1 -0
  55. package/queues/queuer-util.js +1 -1
  56. package/telemetry/otel-telemetry.js +76 -3
  57. package/telemetry/telemetry-config.js +16 -5
  58. package/telemetry/telemetry-runtime.js +14 -1
  59. package/types/core/consumer.fixture.ts +12 -0
  60. package/types/core/index.d.ts +84 -0
  61. package/types/errors/index.d.ts +47 -0
  62. package/types/integrations/index.d.ts +25 -4
  63. package/types/module-plugin/index.d.ts +45 -0
package/core/Worker.js CHANGED
@@ -1,14 +1,46 @@
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
+ // ADR-049 section 5: a wait inside the delay tier ends within 15 minutes, so
36
+ // the user has nothing to do and gets no message.
37
+ const tellsTheUser = ({ capped, probe, waitMs }) =>
38
+ capped || probe || waitMs > MAX_DELAY_SECONDS * 1000;
39
+ const RATE_LIMITED_DECISIONS = new Map([
40
+ ['drop', { action: 'drop' }],
41
+ ['retry', { action: 'retry', skip: { skipped: 'handler_retry' } }],
42
+ ]);
43
+
12
44
  class Worker {
13
45
  async getQueueURL(params) {
14
46
  // Passing params in because there will be multiple QueueNames
@@ -33,12 +65,50 @@ class Worker {
33
65
  // messageId, receiveCount and the event come from the scope.
34
66
  log.debug('Record started', { eventName: 'frigg.worker.record_started' });
35
67
 
68
+ const delivery = readQueueDelivery(record);
69
+ let runParams;
36
70
  try {
37
- const runParams = JSON.parse(record.body);
71
+ runParams = JSON.parse(record.body);
38
72
  this._validateParams(runParams);
39
- await this._run(runParams, context, readQueueDelivery(record));
73
+ await this._run(runParams, context, delivery);
74
+ await this._clearDeferredState(record, runParams, delivery);
40
75
  log.debug('Record succeeded', { eventName: 'frigg.worker.record_succeeded' });
41
76
  } catch (error) {
77
+ let deferralResult;
78
+ if (error.isRateLimited && runParams) {
79
+ const event = this._rateLimitedEvent(
80
+ record,
81
+ runParams,
82
+ error,
83
+ delivery
84
+ );
85
+ const decision = await this._decideRateLimited(event);
86
+ if (decision.action === 'drop') {
87
+ this._logDropped(event, error);
88
+ await this._clearDeferredState(
89
+ record,
90
+ runParams,
91
+ delivery
92
+ );
93
+ return;
94
+ }
95
+ deferralResult =
96
+ decision.action === 'defer'
97
+ ? await this.defer(
98
+ record,
99
+ runParams,
100
+ error,
101
+ delivery
102
+ )
103
+ : { outcome: 'skipped', ...decision.skip };
104
+ if (deferralResult.outcome === 'acked') return;
105
+ if (deferralResult.outcome === 'failed') {
106
+ batchItemFailures.push({
107
+ itemIdentifier: record.messageId,
108
+ });
109
+ return;
110
+ }
111
+ }
42
112
  if (error.isHaltError) {
43
113
  // HaltError means "discard this message, don't retry".
44
114
  // Treat as success so SQS deletes it from the queue.
@@ -51,11 +121,30 @@ class Worker {
51
121
  });
52
122
  return;
53
123
  }
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
- });
124
+ const skippedDeferral = deferralResult && {
125
+ deferral: {
126
+ skipped: deferralResult.skipped,
127
+ ...(deferralResult.cause && {
128
+ cause: deferralResult.cause,
129
+ }),
130
+ },
131
+ };
132
+ if (skippedDeferral && delivery.isLastAttempt) {
133
+ this._logLost({
134
+ retryAt: validDate(error.retryAt)?.toISOString(),
135
+ reason: error.reason,
136
+ module: error.module,
137
+ ...skippedDeferral,
138
+ error,
139
+ });
140
+ } else {
141
+ // The message goes back to SQS, so WARN (ADR-048 §4).
142
+ log.warn('Record failed, returned for retry', {
143
+ eventName: 'frigg.worker.record_failed',
144
+ error,
145
+ ...skippedDeferral,
146
+ });
147
+ }
59
148
  batchItemFailures.push({ itemIdentifier: record.messageId });
60
149
  }
61
150
  });
@@ -75,6 +164,328 @@ class Worker {
75
164
  // parameters
76
165
  }
77
166
 
167
+ // The RATE_LIMITED event of ADR-049 section 3. The same object is meant to
168
+ // become the input of the ADR-047 orchestrator's reducer.
169
+ _rateLimitedEvent(record, body, error, delivery) {
170
+ const { deferrals, firstDeferredAt } = readDeferral(body);
171
+ return {
172
+ retryAt: validDate(error.retryAt) ?? undefined,
173
+ waitMs: error.waitMs,
174
+ reason: error.reason,
175
+ module: error.module,
176
+ scopeKey: error.scopeKey,
177
+ message: body,
178
+ delivery: {
179
+ messageId: record.messageId,
180
+ receiveCount: delivery.receiveCount,
181
+ deferrals,
182
+ deferredMs: firstDeferredAt
183
+ ? Date.now() - Date.parse(firstDeferredAt)
184
+ : 0,
185
+ },
186
+ };
187
+ }
188
+
189
+ decideRateLimited() {
190
+ return Promise.resolve();
191
+ }
192
+
193
+ async _decideRateLimited(event) {
194
+ let decision;
195
+ try {
196
+ decision = await this.decideRateLimited(event);
197
+ } catch (cause) {
198
+ return {
199
+ action: 'retry',
200
+ skip: { skipped: 'handler_failed', cause },
201
+ };
202
+ }
203
+ return RATE_LIMITED_DECISIONS.get(decision) ?? { action: 'defer' };
204
+ }
205
+
206
+ _logDropped(event, error) {
207
+ log.warn('Rate-limited record dropped by the integration', {
208
+ eventName: 'frigg.worker.record_dropped',
209
+ retryAt: event.retryAt?.toISOString(),
210
+ reason: event.reason,
211
+ module: event.module,
212
+ statusCode: error.statusCode,
213
+ error,
214
+ });
215
+ }
216
+
217
+ async defer(record, body, error, delivery) {
218
+ const queueName = queueNameOf(record.eventSourceARN);
219
+ if (!queueName || queueName.endsWith('.fifo')) {
220
+ return { outcome: 'skipped', skipped: 'no_event_source' };
221
+ }
222
+
223
+ const now = Date.now();
224
+ const limits = readDeferralLimits();
225
+ const knownRetryAt = validDate(error.retryAt);
226
+ const retryAt = knownRetryAt ?? new Date(now + limits.probeMs);
227
+ const counters = nextDeferral(body, now, record.messageId);
228
+ const deferral = {
229
+ record,
230
+ queueName,
231
+ body,
232
+ deferredBody: withDeferral(body, counters),
233
+ error,
234
+ delivery,
235
+ retryAt,
236
+ probe: !knownRetryAt,
237
+ capped: isDeferralCapped({ ...counters, retryAt }, limits),
238
+ waitMs: Math.max(0, retryAt.getTime() - now),
239
+ counters,
240
+ };
241
+
242
+ const result = await this._deferOrCap(deferral, limits);
243
+ if (result.outcome !== 'skipped' && tellsTheUser(deferral)) {
244
+ await this._recordMessage(deferral);
245
+ }
246
+ return result;
247
+ }
248
+
249
+ async _deferOrCap(deferral, limits) {
250
+ const { counters, retryAt } = deferral;
251
+ if (deferral.capped) {
252
+ await this._recordWait(deferral, 'EXHAUSTED', 'none');
253
+ this._logUnacked(
254
+ deferral,
255
+ 'frigg.worker.record_deferral_capped',
256
+ 'Rate-limit deferral capped',
257
+ {
258
+ maxDeferrals: limits.maxDeferrals,
259
+ maxDeferredMs: limits.maxDeferredMs,
260
+ deferredMs: deferredMs({ ...counters, retryAt }),
261
+ }
262
+ );
263
+ return { outcome: 'failed' };
264
+ }
265
+
266
+ if (deferral.waitMs <= MAX_DELAY_SECONDS * 1000)
267
+ return this._deferWithDelay(deferral);
268
+ const scheduled = await this._deferWithSchedule(deferral);
269
+ if (scheduled?.outcome) return scheduled;
270
+ return this._deferWithVisibility(deferral, scheduled?.scheduleError);
271
+ }
272
+
273
+ async _deferWithDelay(deferral) {
274
+ const delaySeconds = Math.ceil(deferral.waitMs / 1000);
275
+ // Write the wait before the send: with a short delay the new message
276
+ // can run, and clear the wait, before a later write lands.
277
+ await this._recordWait(deferral, 'WAITING', 'delay');
278
+ try {
279
+ const queueUrl = await this._queueUrl(deferral.queueName);
280
+ await this.send(
281
+ { ...deferral.deferredBody, QueueUrl: queueUrl },
282
+ delaySeconds
283
+ );
284
+ } catch (cause) {
285
+ await this._clearWait(deferral.body, deferral.counters.deferralId);
286
+ return { outcome: 'skipped', skipped: 'send_failed', cause };
287
+ }
288
+ return this._acknowledgeDeferral(deferral, 'delay', { delaySeconds });
289
+ }
290
+
291
+ async _deferWithSchedule(deferral) {
292
+ const { record, retryAt, deferredBody } = deferral;
293
+ const scheduleName = `frigg-defer-${record.messageId}`;
294
+ try {
295
+ const scheduler = this.getSchedulerService();
296
+ if (!scheduler) return null;
297
+ await scheduler.scheduleOneTime({
298
+ scheduleName,
299
+ scheduleAt: retryAt,
300
+ queueResourceId: record.eventSourceARN,
301
+ payload: deferredBody,
302
+ });
303
+ } catch (cause) {
304
+ if (cause?.name !== 'ConflictException')
305
+ return { scheduleError: cause };
306
+ }
307
+ await this._recordWait(deferral, 'WAITING', 'schedule');
308
+ return this._acknowledgeDeferral(deferral, 'schedule', {
309
+ scheduleName,
310
+ });
311
+ }
312
+
313
+ async _deferWithVisibility(deferral, scheduleError) {
314
+ const { record, queueName, delivery, waitMs } = deferral;
315
+ const visibilityTimeout = Math.min(
316
+ Math.ceil(waitMs / 1000),
317
+ MAX_DEFERRED_VISIBILITY_SECONDS
318
+ );
319
+ try {
320
+ const queueUrl = await this._queueUrl(queueName);
321
+ await sqs.send(
322
+ new ChangeMessageVisibilityCommand({
323
+ QueueUrl: queueUrl,
324
+ ReceiptHandle: record.receiptHandle,
325
+ VisibilityTimeout: visibilityTimeout,
326
+ })
327
+ );
328
+ } catch (cause) {
329
+ return { outcome: 'skipped', skipped: 'visibility_failed', cause };
330
+ }
331
+ await this._recordWait(
332
+ deferral,
333
+ delivery.isLastAttempt ? 'EXHAUSTED' : 'WAITING',
334
+ 'visibility'
335
+ );
336
+ this._logUnacked(
337
+ deferral,
338
+ 'frigg.worker.record_visibility_extended',
339
+ 'Record visibility extended',
340
+ {
341
+ mechanism: 'visibility',
342
+ visibilityTimeout,
343
+ ...(scheduleError && { scheduleError }),
344
+ }
345
+ );
346
+ return { outcome: 'failed' };
347
+ }
348
+
349
+ async _acknowledgeDeferral(deferral, mechanism, fields) {
350
+ log.warn('Record deferred', {
351
+ eventName: 'frigg.worker.record_deferred',
352
+ mechanism,
353
+ ...fields,
354
+ ...this._deferralLogFields(deferral),
355
+ error: deferral.error,
356
+ });
357
+ return { outcome: 'acked' };
358
+ }
359
+
360
+ getSchedulerService() {
361
+ if (this._schedulerService !== undefined) return this._schedulerService;
362
+ if (
363
+ !process.env.SCHEDULER_ROLE_ARN ||
364
+ process.env.SCHEDULER_PROVIDER === 'mock'
365
+ ) {
366
+ this._schedulerService = null;
367
+ return null;
368
+ }
369
+ const {
370
+ createSchedulerService,
371
+ SCHEDULER_PROVIDERS,
372
+ } = require('../infrastructure/scheduler/scheduler-service-factory');
373
+ this._schedulerService = createSchedulerService({
374
+ provider: SCHEDULER_PROVIDERS.EVENTBRIDGE,
375
+ });
376
+ return this._schedulerService;
377
+ }
378
+
379
+ recordRateLimitWait() {
380
+ return Promise.resolve();
381
+ }
382
+
383
+ recordRateLimitMessage() {
384
+ return Promise.resolve();
385
+ }
386
+
387
+ clearRateLimitWait() {
388
+ return Promise.resolve();
389
+ }
390
+
391
+ _queueUrl(queueName) {
392
+ this._queueUrls ??= new Map();
393
+ if (!this._queueUrls.has(queueName)) {
394
+ const lookup = this.getQueueURL({ QueueName: queueName }).catch(
395
+ (error) => {
396
+ this._queueUrls.delete(queueName);
397
+ throw error;
398
+ }
399
+ );
400
+ this._queueUrls.set(queueName, lookup);
401
+ }
402
+ return this._queueUrls.get(queueName);
403
+ }
404
+
405
+ async _recordWait({ body, error, counters, retryAt }, status, mechanism) {
406
+ await this._runStateHook('record', () =>
407
+ this.recordRateLimitWait(body, error, {
408
+ status,
409
+ mechanism,
410
+ deferrals: counters.deferrals,
411
+ deferralId: counters.deferralId,
412
+ retryAt,
413
+ })
414
+ );
415
+ }
416
+
417
+ async _recordMessage({ body, error, retryAt, capped }) {
418
+ try {
419
+ await this.recordRateLimitMessage(body, error, { retryAt, capped });
420
+ } catch (hookError) {
421
+ log.warn('Rate-limit message not written', {
422
+ eventName: 'frigg.worker.rate_limit_message_failed',
423
+ error: hookError,
424
+ });
425
+ }
426
+ }
427
+
428
+ async _clearDeferredState(record, body, delivery) {
429
+ const redelivered = delivery.receiveCount > 1;
430
+ const { deferrals, deferralId } = readDeferral(body);
431
+ if (deferrals === 0 && !redelivered) return;
432
+ await this._clearWait(body, deferralId ?? record.messageId);
433
+ }
434
+
435
+ async _clearWait(body, deferralId) {
436
+ await this._runStateHook('clear', () =>
437
+ this.clearRateLimitWait(body, { deferralId })
438
+ );
439
+ }
440
+
441
+ async _runStateHook(operation, hook) {
442
+ try {
443
+ await hook();
444
+ } catch (error) {
445
+ log.warn('Rate-limit run state not written', {
446
+ eventName: 'frigg.worker.rate_limit_state_failed',
447
+ operation,
448
+ error,
449
+ });
450
+ }
451
+ }
452
+
453
+ _deferralLogFields({ error, retryAt, probe, waitMs, counters }) {
454
+ return {
455
+ waitMs,
456
+ retryAt: retryAt.toISOString(),
457
+ ...(probe && { probe }),
458
+ deferrals: counters.deferrals,
459
+ firstDeferredAt: counters.firstDeferredAt,
460
+ reason: error.reason,
461
+ module: error.module,
462
+ statusCode: error.statusCode,
463
+ };
464
+ }
465
+
466
+ _logUnacked(deferral, eventName, message, fields) {
467
+ const logFields = {
468
+ ...fields,
469
+ ...this._deferralLogFields(deferral),
470
+ error: deferral.error,
471
+ };
472
+ if (deferral.delivery.isLastAttempt) {
473
+ this._logLost(logFields);
474
+ return;
475
+ }
476
+ log.warn(message, {
477
+ eventName,
478
+ ...logFields,
479
+ });
480
+ }
481
+
482
+ _logLost(fields) {
483
+ log.error(
484
+ 'Rate-limited record lost: the message goes to the dead-letter queue next',
485
+ { eventName: 'frigg.worker.record_lost_rate_limited', ...fields }
486
+ );
487
+ }
488
+
78
489
  // returns the message id
79
490
  async send(params, delay = 0) {
80
491
  this._validateParams(params);
@@ -12,6 +12,8 @@ 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');
16
+ const { rateLimitedResponse } = require('./rate-limited-response');
15
17
  const { secretsToEnv } = require('./secrets-to-env');
16
18
  const { parametersToEnv } = require('./parameters-to-env');
17
19
  const {
@@ -31,6 +33,7 @@ const createHandler = (optionByName = {}) => {
31
33
  telemetry,
32
34
  flushTimeoutMs = DEFAULT_FLUSH_TIMEOUT_MS,
33
35
  usageRollup,
36
+ maxInProcessWaitMs = MAX_IN_PROCESS_WAIT_MS.http,
34
37
  } = optionByName;
35
38
 
36
39
  if (!method) {
@@ -105,6 +108,22 @@ const createHandler = (optionByName = {}) => {
105
108
  };
106
109
  }
107
110
 
111
+ const rateLimited =
112
+ isUserFacingResponse && rateLimitedResponse(error);
113
+ if (rateLimited) {
114
+ log.warn('Request rate limited', {
115
+ eventName: 'frigg.handler.rate_limited',
116
+ statusCode: rateLimited.statusCode,
117
+ invocation: requestDetails,
118
+ error,
119
+ });
120
+ return {
121
+ statusCode: rateLimited.statusCode,
122
+ headers: rateLimited.headers,
123
+ body: JSON.stringify(rateLimited.body),
124
+ };
125
+ }
126
+
108
127
  // Server-to-server: halt errors succeed and won't be
109
128
  // retried, so the halt itself is the failure record.
110
129
  if (!isUserFacingResponse && error.isHaltError === true) {
@@ -144,6 +163,7 @@ const createHandler = (optionByName = {}) => {
144
163
  shouldUseDatabase,
145
164
  flushTimeoutMs,
146
165
  context,
166
+ maxInProcessWaitMs,
147
167
  }
148
168
  );
149
169
  };
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: 0,
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) {