@friggframework/core 2.0.0--canary.743.81eabd1.0 → 2.0.0--canary.743.265a5cd.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.
package/core/Worker.js CHANGED
@@ -217,6 +217,21 @@ class Worker {
217
217
  });
218
218
  }
219
219
 
220
+ // A paced error carries the key's next slot. A message that was paced
221
+ // before and is paced again comes back at a random point between the
222
+ // earliest call time and that slot, so the messages that came in after
223
+ // it do not keep it at the back of the backlog.
224
+ _pacedRetryAt(error, slotAt, body) {
225
+ const notBefore = validDate(error.notBefore);
226
+ if (!notBefore || !(readDeferral(body).pacedDeferrals > 0)) {
227
+ return slotAt;
228
+ }
229
+ const span = Math.max(0, slotAt.getTime() - notBefore.getTime());
230
+ return new Date(
231
+ notBefore.getTime() + Math.floor((this._random ?? Math.random)() * span)
232
+ );
233
+ }
234
+
220
235
  async defer(record, body, error, delivery) {
221
236
  const queueName = queueNameOf(record.eventSourceARN);
222
237
  if (!queueName || queueName.endsWith('.fifo')) {
@@ -230,8 +245,9 @@ class Worker {
230
245
  // The requester already spread a paced error over the key's slots.
231
246
  // An error from a module with no rate-limit policy keeps its exact
232
247
  // retryAt: no policy, no change (ADR-049 A.4).
233
- const retryAt =
234
- error.paced || error.declaredPolicy !== true
248
+ const retryAt = error.paced
249
+ ? this._pacedRetryAt(error, earliest, body)
250
+ : error.declaredPolicy !== true
235
251
  ? earliest
236
252
  : jitteredRetryAt(
237
253
  earliest,
@@ -1,6 +1,10 @@
1
1
  const {
2
2
  STATE_FIELD,
3
3
  } = require('../requester/rate-limit/state/rate-limit-state-repository-interface');
4
+ const {
5
+ getEncryptedFields,
6
+ getFieldsToEncryptOnWrite,
7
+ } = require('../../database/encryption/encryption-schema-registry');
4
8
 
5
9
  // Entity.data holds the integration's own fields and, under STATE_FIELD, the
6
10
  // shared rate-limit state that the pacer writes with atomic statements
@@ -38,8 +42,30 @@ function dataSetPaths(fields) {
38
42
  return paths;
39
43
  }
40
44
 
45
+ /**
46
+ * True when an update may merge Entity.data with a raw statement. A raw
47
+ * statement skips the Prisma encryption extension, so it is used only when
48
+ * the app encrypts no Entity field on write. Otherwise the update goes
49
+ * through the Prisma model, which encrypts, and the rate-limit state is
50
+ * written back as it was read (the pacer's state is advisory and fails open).
51
+ */
52
+ function canMergeEntityDataRaw() {
53
+ return getFieldsToEncryptOnWrite('Entity').length === 0;
54
+ }
55
+
56
+ /**
57
+ * True when Entity.data is stored as a JSON object that the pacer can merge
58
+ * its state into. When the app encrypts the whole `data` field, the column
59
+ * holds ciphertext and the shared rate-limit state is not used.
60
+ */
61
+ function entityDataHoldsRateLimitState() {
62
+ return !getEncryptedFields('Entity').includes('data');
63
+ }
64
+
41
65
  module.exports = {
42
66
  RATE_LIMIT_STATE_FIELD: STATE_FIELD,
67
+ canMergeEntityDataRaw,
43
68
  dataSetPaths,
44
69
  entityDataFields,
70
+ entityDataHoldsRateLimitState,
45
71
  };
@@ -1,5 +1,9 @@
1
1
  const { prisma } = require('../../database/prisma');
2
- const { entityDataFields, RATE_LIMIT_STATE_FIELD, dataSetPaths } = require('./entity-data');
2
+ const {
3
+ dataSetPaths,
4
+ entityDataFields,
5
+ RATE_LIMIT_STATE_FIELD,
6
+ } = require('./entity-data');
3
7
  const {
4
8
  toObjectId,
5
9
  fromObjectId,
@@ -1,5 +1,10 @@
1
1
  const { prisma } = require('../../database/prisma');
2
- const { entityDataFields, RATE_LIMIT_STATE_FIELD, dataSetPaths } = require('./entity-data');
2
+ const {
3
+ canMergeEntityDataRaw,
4
+ dataSetPaths,
5
+ entityDataFields,
6
+ RATE_LIMIT_STATE_FIELD,
7
+ } = require('./entity-data');
3
8
  const { ModuleRepositoryInterface } = require('./module-repository-interface');
4
9
 
5
10
  /**
@@ -349,21 +354,34 @@ class ModuleRepositoryMongo extends ModuleRepositoryInterface {
349
354
 
350
355
  // A shallow merge with one `$set` path for each field: the rate-limit
351
356
  // state that the pacer writes in the same document is never written
352
- // back. A key that cannot be a path segment falls back to a whole
353
- // `data` write, which keeps the state as it was read.
357
+ // back. A key that cannot be a path segment, or an app that encrypts
358
+ // an Entity field (a raw command skips encryption), falls back to a
359
+ // whole `data` write through the Prisma model, which keeps the state
360
+ // as it was read.
354
361
  const fields = entityDataFields(dynamicData);
355
362
  if (Object.keys(fields).length > 0) {
356
363
  const paths =
357
- existing.data && typeof existing.data === 'object'
364
+ existing.data &&
365
+ typeof existing.data === 'object' &&
366
+ canMergeEntityDataRaw()
358
367
  ? dataSetPaths(fields)
359
368
  : null;
360
369
  if (paths) {
361
- await this.prisma.$runCommandRaw({
370
+ const result = await this.prisma.$runCommandRaw({
362
371
  update: 'Entity',
363
372
  updates: [
364
373
  { q: { _id: { $oid: entityId } }, u: { $set: paths } },
365
374
  ],
366
375
  });
376
+ const writeError =
377
+ result?.writeErrors?.[0] || result?.writeConcernError;
378
+ if (writeError || (result && result.ok !== undefined && !result.ok)) {
379
+ throw new Error(
380
+ `Entity data update failed: ${
381
+ writeError?.errmsg || 'command not acknowledged'
382
+ }`
383
+ );
384
+ }
367
385
  } else {
368
386
  const state = existing.data?.[RATE_LIMIT_STATE_FIELD];
369
387
  schemaUpdates.data = {
@@ -1,5 +1,9 @@
1
1
  const { prisma } = require('../../database/prisma');
2
- const { entityDataFields } = require('./entity-data');
2
+ const {
3
+ canMergeEntityDataRaw,
4
+ entityDataFields,
5
+ RATE_LIMIT_STATE_FIELD,
6
+ } = require('./entity-data');
3
7
  const { ModuleRepositoryInterface } = require('./module-repository-interface');
4
8
 
5
9
  /**
@@ -391,20 +395,38 @@ class ModuleRepositoryPostgres extends ModuleRepositoryInterface {
391
395
  if (externalId !== undefined) schemaUpdates.externalId = externalId;
392
396
 
393
397
  // A shallow merge in one statement: the rate-limit state that the
394
- // pacer writes in the same column is never written back.
398
+ // pacer writes in the same column is never written back. The merge
399
+ // and the update of the other columns commit together. When the app
400
+ // encrypts an Entity field, a raw statement would skip encryption,
401
+ // so the whole `data` goes through the Prisma model instead.
395
402
  const fields = entityDataFields(dynamicData);
396
- if (Object.keys(fields).length > 0) {
397
- await this.prisma.$executeRaw`
398
- UPDATE "Entity"
399
- SET "data" = COALESCE("data", '{}'::jsonb) || ${JSON.stringify(fields)}::jsonb
400
- WHERE "id" = ${intId}`;
403
+ const hasFields = Object.keys(fields).length > 0;
404
+ const rawMerge = hasFields && canMergeEntityDataRaw();
405
+ if (hasFields && !rawMerge) {
406
+ const state = existing.data?.[RATE_LIMIT_STATE_FIELD];
407
+ schemaUpdates.data = {
408
+ ...entityDataFields(existing.data),
409
+ ...fields,
410
+ ...(state !== undefined && { [RATE_LIMIT_STATE_FIELD]: state }),
411
+ };
401
412
  }
402
413
 
403
414
  try {
404
- const entity = await this.prisma.entity.update({
415
+ const update = this.prisma.entity.update({
405
416
  where: { id: intId },
406
417
  data: schemaUpdates,
407
418
  });
419
+ const entity = rawMerge
420
+ ? (
421
+ await this.prisma.$transaction([
422
+ this.prisma.$executeRaw`
423
+ UPDATE "Entity"
424
+ SET "data" = COALESCE("data", '{}'::jsonb) || ${JSON.stringify(fields)}::jsonb
425
+ WHERE "id" = ${intId}`,
426
+ update,
427
+ ])
428
+ )[1]
429
+ : await update;
408
430
 
409
431
  const credentialObj = await this._fetchCredential(entity.credentialId);
410
432
 
@@ -28,8 +28,8 @@ const SHARED_FAILURE_PAUSE_MS = 30_000;
28
28
  const MIN_SHARED_BLOCK_STEP_MS = 250;
29
29
  // The SQS delay range: a paced retry that can come back inside it stays in it.
30
30
  const MAX_PACED_RETRY_MS = 900 * 1000;
31
- // When every slot of that range is taken: spread over its last minute.
32
- const FULL_RETRY_SPREAD_MS = 60_000;
31
+ // The most that one caller waits past the end of a block, at random.
32
+ const MAX_RELEASE_JITTER_MS = 1_000;
33
33
  // A retry without a known rate spreads over at least this time.
34
34
  const MIN_RETRY_SPREAD_MS = 1_000;
35
35
  const HEADER_PARSERS = ['ietf', 'resetHeaders'];
@@ -390,9 +390,26 @@ class RateLimitPacer {
390
390
 
391
391
  if (waitMs > budgetMs) return { granted: false, waitMs, reason };
392
392
  for (const bucket of buckets) bucket.take();
393
- return waitMs > 0
394
- ? { granted: true, waitMs, reason }
395
- : { granted: true, waitMs: 0 };
393
+ if (waitMs === 0) return { granted: true, waitMs: 0 };
394
+ // Callers that wait for the end of a block do not all call at that
395
+ // moment: each one adds a random part of the block (up to 1 s, or one
396
+ // interval of the key), inside the budget, so the calls of many
397
+ // processes spread out.
398
+ const jitterMs =
399
+ reason === 'blocked'
400
+ ? Math.floor(
401
+ this.random() *
402
+ Math.max(
403
+ Math.min(blockWaitMs, MAX_RELEASE_JITTER_MS),
404
+ this.intervalMs({ scopeKey, policy }) ?? 0
405
+ )
406
+ )
407
+ : 0;
408
+ return {
409
+ granted: true,
410
+ waitMs: Math.max(waitMs, Math.min(waitMs + jitterMs, budgetMs)),
411
+ reason,
412
+ };
396
413
  }
397
414
 
398
415
  /**
@@ -486,36 +503,36 @@ class RateLimitPacer {
486
503
  * spread is max(waitMs, 1 s), but never more than
487
504
  * FRIGG_QUEUE_DEFERRAL_JITTER_MAX_MS.
488
505
  *
489
- * A retry that can come back inside the SQS delay range (900 s) stays in
490
- * it. When every slot up to the end of that range is taken, the message
491
- * does not take a slot: it comes back at a random point in the last
492
- * minute of the range, and the pacer defers it again without a call. So
493
- * a burst backlog never leaves the delay tier, never spends receives,
494
- * and never writes a user message.
506
+ * Slots exist only inside the SQS delay range (900 s from now):
507
+ * - A retry that cannot come back inside it (a long quota wait) takes no
508
+ * slot, so it never moves the sequence past the range. It comes back at
509
+ * a random point after notBefore, like a retry without a known rate.
510
+ * - When every slot up to the end of the range is taken, the message
511
+ * takes no slot and comes back at a random point in the rest of the
512
+ * range. The sequence moves back inside the range as time passes.
513
+ * So a burst backlog stays in the delay tier, never spends receives, and
514
+ * never writes a user message. (The queue worker moves a message that is
515
+ * paced again to a random point before its slot, so it is not put behind
516
+ * every newer message.)
495
517
  *
496
518
  * @returns {Promise<Date>}
497
519
  */
498
520
  async reserveRetry({ scopeKey, entityId, policy, notBefore, waitMs = 0 }) {
499
521
  const nb = notBefore.getTime();
500
522
  const delayEnd = this.now() + MAX_PACED_RETRY_MS;
501
- const cap = nb <= delayEnd ? delayEnd : undefined;
502
523
  const intervalMs = scopeKey
503
524
  ? this.intervalMs({ scopeKey, policy })
504
525
  : undefined;
505
- if (!intervalMs) {
526
+ if (!intervalMs || nb > delayEnd) {
506
527
  let spread = Math.min(
507
528
  Math.max(waitMs, MIN_RETRY_SPREAD_MS),
508
529
  jitterMaxMs(this.env)
509
530
  );
510
- if (cap !== undefined) spread = Math.min(spread, cap - nb);
531
+ if (nb <= delayEnd) spread = Math.min(spread, delayEnd - nb);
511
532
  return new Date(nb + Math.floor(this.random() * spread));
512
533
  }
513
534
 
514
- const options = {
515
- notBefore,
516
- intervalMs,
517
- ...(cap !== undefined && { notAfter: new Date(cap) }),
518
- };
535
+ const options = { notBefore, intervalMs, notAfter: new Date(delayEnd) };
519
536
  let slot;
520
537
  const store = this._shared(policy, entityId);
521
538
  if (store) {
@@ -525,11 +542,10 @@ class RateLimitPacer {
525
542
  }
526
543
  slot ??= await this.localStore.reserveSlot({ scopeKey }, options);
527
544
  if (slot === SLOTS_FULL) {
528
- const spread = Math.min(FULL_RETRY_SPREAD_MS, cap - nb);
529
- return new Date(cap - Math.floor(this.random() * spread));
545
+ return new Date(nb + Math.floor(this.random() * (delayEnd - nb)));
530
546
  }
531
547
  const at = slot.getTime() + Math.floor(this.random() * intervalMs);
532
- return new Date(cap === undefined ? at : Math.min(at, cap));
548
+ return new Date(Math.min(at, delayEnd));
533
549
  }
534
550
  }
535
551
 
@@ -5,8 +5,15 @@ const {
5
5
  /**
6
6
  * The shared store for the app's database type. Required lazily, so a
7
7
  * requester that never uses shared state never loads Prisma.
8
+ *
9
+ * Returns null when the app encrypts the whole Entity `data` field: the
10
+ * column then holds ciphertext, and pacing stays in process.
8
11
  */
9
12
  function createRateLimitStateRepository({ dbType } = {}) {
13
+ const {
14
+ entityDataHoldsRateLimitState,
15
+ } = require('../../../repositories/entity-data');
16
+ if (!entityDataHoldsRateLimitState()) return null;
10
17
  const type = dbType ?? require('../../../../database/config').DB_TYPE;
11
18
  switch (type) {
12
19
  case 'postgresql': {
@@ -653,6 +653,8 @@ class Requester extends Delegate {
653
653
  error.statusCode = 429;
654
654
  error.preempted = true;
655
655
  error.paced = true;
656
+ // The earliest time a call can go; retryAt is the key's slot.
657
+ error.notBefore = new Date(now + gate.waitMs);
656
658
  error.message = `${error.message} paced: not sent`;
657
659
  this._logPaced(gate, scopeKey, error);
658
660
  throw error;
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.743.81eabd1.0",
4
+ "version": "2.0.0--canary.743.265a5cd.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,7 @@
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.743.81eabd1.0",
14
+ "@friggframework/schemas": "2.0.0--canary.743.265a5cd.0",
15
15
  "@hapi/boom": "^10.0.1",
16
16
  "@opentelemetry/api": "^1.9.1",
17
17
  "@opentelemetry/context-async-hooks": "^2.9.0",
@@ -49,9 +49,9 @@
49
49
  }
50
50
  },
51
51
  "devDependencies": {
52
- "@friggframework/eslint-config": "2.0.0--canary.743.81eabd1.0",
53
- "@friggframework/prettier-config": "2.0.0--canary.743.81eabd1.0",
54
- "@friggframework/test": "2.0.0--canary.743.81eabd1.0",
52
+ "@friggframework/eslint-config": "2.0.0--canary.743.265a5cd.0",
53
+ "@friggframework/prettier-config": "2.0.0--canary.743.265a5cd.0",
54
+ "@friggframework/test": "2.0.0--canary.743.265a5cd.0",
55
55
  "@prisma/client": "^6.19.3",
56
56
  "@types/lodash": "4.17.15",
57
57
  "@typescript-eslint/eslint-plugin": "^8.0.0",
@@ -93,5 +93,5 @@
93
93
  "publishConfig": {
94
94
  "access": "public"
95
95
  },
96
- "gitHead": "81eabd10e0cb7ab8384f240d96c98c88a0de4410"
96
+ "gitHead": "265a5cd5f39515f47164aec0b99fed86048b59d9"
97
97
  }