@friggframework/core 2.0.0--canary.743.57dc4bf.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')) {
@@ -228,14 +243,18 @@ class Worker {
228
243
  const knownRetryAt = validDate(error.retryAt);
229
244
  const earliest = knownRetryAt ?? new Date(now + limits.probeMs);
230
245
  // The requester already spread a paced error over the key's slots.
246
+ // An error from a module with no rate-limit policy keeps its exact
247
+ // retryAt: no policy, no change (ADR-049 A.4).
231
248
  const retryAt = error.paced
232
- ? earliest
233
- : jitteredRetryAt(
234
- earliest,
235
- Math.max(0, earliest.getTime() - now),
236
- { ...limits, now },
237
- this._random
238
- );
249
+ ? this._pacedRetryAt(error, earliest, body)
250
+ : error.declaredPolicy !== true
251
+ ? earliest
252
+ : jitteredRetryAt(
253
+ earliest,
254
+ Math.max(0, earliest.getTime() - now),
255
+ { ...limits, now },
256
+ this._random
257
+ );
239
258
  const counters = nextDeferral(body, now, record.messageId, {
240
259
  preempted: error.preempted === true,
241
260
  maxPacedDeferrals: limits.maxPacedDeferrals,
@@ -0,0 +1,71 @@
1
+ const {
2
+ STATE_FIELD,
3
+ } = require('../requester/rate-limit/state/rate-limit-state-repository-interface');
4
+ const {
5
+ getEncryptedFields,
6
+ getFieldsToEncryptOnWrite,
7
+ } = require('../../database/encryption/encryption-schema-registry');
8
+
9
+ // Entity.data holds the integration's own fields and, under STATE_FIELD, the
10
+ // shared rate-limit state that the pacer writes with atomic statements
11
+ // (ADR-049 section 6, 2b). Entity reads and writes never carry that state:
12
+ // a read does not show it, and an update never writes it back, so an update
13
+ // cannot overwrite a newer value.
14
+
15
+ /** The integration's own fields of Entity.data, without the pacer's state. */
16
+ function entityDataFields(data) {
17
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return {};
18
+ if (!(STATE_FIELD in data)) return data;
19
+ const { [STATE_FIELD]: _state, ...fields } = data;
20
+ return fields;
21
+ }
22
+
23
+ /** A key that MongoDB accepts as one segment of a dotted `$set` path. */
24
+ const isPathSafeKey = (key) =>
25
+ typeof key === 'string' &&
26
+ key !== '' &&
27
+ !key.includes('.') &&
28
+ !key.startsWith('$');
29
+
30
+ /**
31
+ * `$set` paths for a shallow merge into Entity.data: one `data.<key>` path
32
+ * for each field. Returns null when a key cannot be a path segment.
33
+ */
34
+ function dataSetPaths(fields) {
35
+ const paths = {};
36
+ for (const [key, value] of Object.entries(fields)) {
37
+ if (!isPathSafeKey(key)) return null;
38
+ // The same JSON shape that a Prisma Json field stores.
39
+ paths[`data.${key}`] =
40
+ value === undefined ? null : JSON.parse(JSON.stringify(value));
41
+ }
42
+ return paths;
43
+ }
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
+
65
+ module.exports = {
66
+ RATE_LIMIT_STATE_FIELD: STATE_FIELD,
67
+ canMergeEntityDataRaw,
68
+ dataSetPaths,
69
+ entityDataFields,
70
+ entityDataHoldsRateLimitState,
71
+ };
@@ -1,4 +1,9 @@
1
1
  const { prisma } = require('../../database/prisma');
2
+ const {
3
+ dataSetPaths,
4
+ entityDataFields,
5
+ RATE_LIMIT_STATE_FIELD,
6
+ } = require('./entity-data');
2
7
  const {
3
8
  toObjectId,
4
9
  fromObjectId,
@@ -133,7 +138,7 @@ class ModuleRepositoryDocumentDB extends ModuleRepositoryInterface {
133
138
  name: name ?? null,
134
139
  moduleName: moduleName ?? null,
135
140
  externalId: externalId ?? null,
136
- data: dynamicData,
141
+ data: entityDataFields(dynamicData),
137
142
  };
138
143
  const insertedId = await insertOne(this.prisma, 'Entity', document);
139
144
  const created = await findOne(this.prisma, 'Entity', { _id: insertedId });
@@ -170,8 +175,28 @@ class ModuleRepositoryDocumentDB extends ModuleRepositoryInterface {
170
175
  if (moduleName !== undefined) updatePayload.moduleName = moduleName;
171
176
  if (externalId !== undefined) updatePayload.externalId = externalId;
172
177
 
173
- if (Object.keys(dynamicData).length > 0) {
174
- updatePayload.data = { ...(existing.data || {}), ...dynamicData };
178
+ // A shallow merge with one `$set` path for each field: the rate-limit
179
+ // state that the pacer writes in the same document is never written
180
+ // back. A key that cannot be a path segment falls back to a whole
181
+ // `data` write, which keeps the state as it was read.
182
+ const fields = entityDataFields(dynamicData);
183
+ if (Object.keys(fields).length > 0) {
184
+ const paths =
185
+ existing.data && typeof existing.data === 'object'
186
+ ? dataSetPaths(fields)
187
+ : null;
188
+ if (paths) {
189
+ Object.assign(updatePayload, paths);
190
+ } else {
191
+ const state = existing.data?.[RATE_LIMIT_STATE_FIELD];
192
+ updatePayload.data = {
193
+ ...entityDataFields(existing.data),
194
+ ...fields,
195
+ ...(state !== undefined && {
196
+ [RATE_LIMIT_STATE_FIELD]: state,
197
+ }),
198
+ };
199
+ }
175
200
  }
176
201
 
177
202
  await updateOne(
@@ -333,7 +358,7 @@ class ModuleRepositoryDocumentDB extends ModuleRepositoryInterface {
333
358
  }
334
359
 
335
360
  _mapEntity(doc, credential) {
336
- const dynamicData = doc?.data || {};
361
+ const dynamicData = entityDataFields(doc?.data);
337
362
  return {
338
363
  id: fromObjectId(doc?._id),
339
364
  credential,
@@ -1,4 +1,10 @@
1
1
  const { prisma } = require('../../database/prisma');
2
+ const {
3
+ canMergeEntityDataRaw,
4
+ dataSetPaths,
5
+ entityDataFields,
6
+ RATE_LIMIT_STATE_FIELD,
7
+ } = require('./entity-data');
2
8
  const { ModuleRepositoryInterface } = require('./module-repository-interface');
3
9
 
4
10
  /**
@@ -102,7 +108,7 @@ class ModuleRepositoryMongo extends ModuleRepositoryInterface {
102
108
  name: entity.name,
103
109
  externalId: entity.externalId,
104
110
  moduleName: entity.moduleName,
105
- ...(entity.data || {}),
111
+ ...entityDataFields(entity.data),
106
112
  };
107
113
  }
108
114
 
@@ -128,7 +134,7 @@ class ModuleRepositoryMongo extends ModuleRepositoryInterface {
128
134
  name: e.name,
129
135
  externalId: e.externalId,
130
136
  moduleName: e.moduleName,
131
- ...(e.data || {}),
137
+ ...entityDataFields(e.data),
132
138
  }));
133
139
  }
134
140
 
@@ -154,7 +160,7 @@ class ModuleRepositoryMongo extends ModuleRepositoryInterface {
154
160
  name: e.name,
155
161
  externalId: e.externalId,
156
162
  moduleName: e.moduleName,
157
- ...(e.data || {}),
163
+ ...entityDataFields(e.data),
158
164
  }));
159
165
  }
160
166
 
@@ -184,7 +190,7 @@ class ModuleRepositoryMongo extends ModuleRepositoryInterface {
184
190
  name: e.name,
185
191
  externalId: e.externalId,
186
192
  moduleName: e.moduleName,
187
- ...(e.data || {}),
193
+ ...entityDataFields(e.data),
188
194
  }));
189
195
  }
190
196
 
@@ -230,7 +236,7 @@ class ModuleRepositoryMongo extends ModuleRepositoryInterface {
230
236
  name: entity.name,
231
237
  externalId: entity.externalId,
232
238
  moduleName: entity.moduleName,
233
- ...(entity.data || {}),
239
+ ...entityDataFields(entity.data),
234
240
  };
235
241
  }
236
242
 
@@ -258,7 +264,7 @@ class ModuleRepositoryMongo extends ModuleRepositoryInterface {
258
264
  name: e.name,
259
265
  externalId: e.externalId,
260
266
  moduleName: e.moduleName,
261
- ...(e.data || {}),
267
+ ...entityDataFields(e.data),
262
268
  }));
263
269
  }
264
270
 
@@ -287,7 +293,7 @@ class ModuleRepositoryMongo extends ModuleRepositoryInterface {
287
293
  name,
288
294
  moduleName,
289
295
  externalId,
290
- data: dynamicData,
296
+ data: entityDataFields(dynamicData),
291
297
  };
292
298
 
293
299
  const entity = await this.prisma.entity.create({
@@ -303,7 +309,7 @@ class ModuleRepositoryMongo extends ModuleRepositoryInterface {
303
309
  name: entity.name,
304
310
  externalId: entity.externalId,
305
311
  moduleName: entity.moduleName,
306
- ...(entity.data || {}),
312
+ ...entityDataFields(entity.data),
307
313
  };
308
314
  }
309
315
 
@@ -346,8 +352,46 @@ class ModuleRepositoryMongo extends ModuleRepositoryInterface {
346
352
  if (moduleName !== undefined) schemaUpdates.moduleName = moduleName;
347
353
  if (externalId !== undefined) schemaUpdates.externalId = externalId;
348
354
 
349
- if (Object.keys(dynamicData).length > 0) {
350
- schemaUpdates.data = { ...(existing.data || {}), ...dynamicData };
355
+ // A shallow merge with one `$set` path for each field: the rate-limit
356
+ // state that the pacer writes in the same document is never written
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.
361
+ const fields = entityDataFields(dynamicData);
362
+ if (Object.keys(fields).length > 0) {
363
+ const paths =
364
+ existing.data &&
365
+ typeof existing.data === 'object' &&
366
+ canMergeEntityDataRaw()
367
+ ? dataSetPaths(fields)
368
+ : null;
369
+ if (paths) {
370
+ const result = await this.prisma.$runCommandRaw({
371
+ update: 'Entity',
372
+ updates: [
373
+ { q: { _id: { $oid: entityId } }, u: { $set: paths } },
374
+ ],
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
+ }
385
+ } else {
386
+ const state = existing.data?.[RATE_LIMIT_STATE_FIELD];
387
+ schemaUpdates.data = {
388
+ ...entityDataFields(existing.data),
389
+ ...fields,
390
+ ...(state !== undefined && {
391
+ [RATE_LIMIT_STATE_FIELD]: state,
392
+ }),
393
+ };
394
+ }
351
395
  }
352
396
 
353
397
  try {
@@ -365,7 +409,7 @@ class ModuleRepositoryMongo extends ModuleRepositoryInterface {
365
409
  name: entity.name,
366
410
  externalId: entity.externalId,
367
411
  moduleName: entity.moduleName,
368
- ...(entity.data || {}),
412
+ ...entityDataFields(entity.data),
369
413
  };
370
414
  } catch (error) {
371
415
  if (error.code === 'P2025') {
@@ -1,4 +1,9 @@
1
1
  const { prisma } = require('../../database/prisma');
2
+ const {
3
+ canMergeEntityDataRaw,
4
+ entityDataFields,
5
+ RATE_LIMIT_STATE_FIELD,
6
+ } = require('./entity-data');
2
7
  const { ModuleRepositoryInterface } = require('./module-repository-interface');
3
8
 
4
9
  /**
@@ -136,7 +141,7 @@ class ModuleRepositoryPostgres extends ModuleRepositoryInterface {
136
141
  name: entity.name,
137
142
  externalId: entity.externalId,
138
143
  moduleName: entity.moduleName,
139
- ...(entity.data || {}),
144
+ ...entityDataFields(entity.data),
140
145
  };
141
146
  }
142
147
 
@@ -164,7 +169,7 @@ class ModuleRepositoryPostgres extends ModuleRepositoryInterface {
164
169
  name: e.name,
165
170
  externalId: e.externalId,
166
171
  moduleName: e.moduleName,
167
- ...(e.data || {}),
172
+ ...entityDataFields(e.data),
168
173
  }));
169
174
  }
170
175
 
@@ -192,7 +197,7 @@ class ModuleRepositoryPostgres extends ModuleRepositoryInterface {
192
197
  name: e.name,
193
198
  externalId: e.externalId,
194
199
  moduleName: e.moduleName,
195
- ...(e.data || {}),
200
+ ...entityDataFields(e.data),
196
201
  }));
197
202
  }
198
203
 
@@ -224,7 +229,7 @@ class ModuleRepositoryPostgres extends ModuleRepositoryInterface {
224
229
  name: e.name,
225
230
  externalId: e.externalId,
226
231
  moduleName: e.moduleName,
227
- ...(e.data || {}),
232
+ ...entityDataFields(e.data),
228
233
  }));
229
234
  }
230
235
 
@@ -271,7 +276,7 @@ class ModuleRepositoryPostgres extends ModuleRepositoryInterface {
271
276
  name: entity.name,
272
277
  externalId: entity.externalId,
273
278
  moduleName: entity.moduleName,
274
- ...(entity.data || {}),
279
+ ...entityDataFields(entity.data),
275
280
  };
276
281
  }
277
282
 
@@ -299,7 +304,7 @@ class ModuleRepositoryPostgres extends ModuleRepositoryInterface {
299
304
  name: e.name,
300
305
  externalId: e.externalId,
301
306
  moduleName: e.moduleName,
302
- ...(e.data || {}),
307
+ ...entityDataFields(e.data),
303
308
  }));
304
309
  }
305
310
 
@@ -328,7 +333,7 @@ class ModuleRepositoryPostgres extends ModuleRepositoryInterface {
328
333
  name,
329
334
  moduleName,
330
335
  externalId,
331
- data: dynamicData,
336
+ data: entityDataFields(dynamicData),
332
337
  };
333
338
 
334
339
  const entity = await this.prisma.entity.create({
@@ -344,7 +349,7 @@ class ModuleRepositoryPostgres extends ModuleRepositoryInterface {
344
349
  name: entity.name,
345
350
  externalId: entity.externalId,
346
351
  moduleName: entity.moduleName,
347
- ...(entity.data || {}),
352
+ ...entityDataFields(entity.data),
348
353
  };
349
354
  }
350
355
 
@@ -389,15 +394,39 @@ class ModuleRepositoryPostgres extends ModuleRepositoryInterface {
389
394
  if (moduleName !== undefined) schemaUpdates.moduleName = moduleName;
390
395
  if (externalId !== undefined) schemaUpdates.externalId = externalId;
391
396
 
392
- if (Object.keys(dynamicData).length > 0) {
393
- schemaUpdates.data = { ...(existing.data || {}), ...dynamicData };
397
+ // A shallow merge in one statement: the rate-limit state that the
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.
402
+ const fields = entityDataFields(dynamicData);
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
+ };
394
412
  }
395
413
 
396
414
  try {
397
- const entity = await this.prisma.entity.update({
415
+ const update = this.prisma.entity.update({
398
416
  where: { id: intId },
399
417
  data: schemaUpdates,
400
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;
401
430
 
402
431
  const credentialObj = await this._fetchCredential(entity.credentialId);
403
432
 
@@ -408,7 +437,7 @@ class ModuleRepositoryPostgres extends ModuleRepositoryInterface {
408
437
  name: entity.name,
409
438
  externalId: entity.externalId,
410
439
  moduleName: entity.moduleName,
411
- ...(entity.data || {}),
440
+ ...entityDataFields(entity.data),
412
441
  };
413
442
  } catch (error) {
414
443
  if (error.code === 'P2025') {
@@ -3,6 +3,7 @@ const { BUILT_IN_PARSERS, headerValue } = require('./parsers');
3
3
  const {
4
4
  RateLimitStateRepositoryMemory,
5
5
  } = require('./state/rate-limit-state-repository-memory');
6
+ const { SLOTS_FULL } = require('./state/rate-limit-state-repository-interface');
6
7
 
7
8
  // ADR-049 section 6: pacing. 2a is the in-process part (token buckets from
8
9
  // `windows`, a block from the headers). 2b is the shared part: the block and
@@ -25,6 +26,10 @@ const DEFAULT_JITTER_MAX_MS = 5 * 60 * 1000;
25
26
  const SHARED_FAILURE_PAUSE_MS = 30_000;
26
27
  // A block that moves by less than this is not written again to the store.
27
28
  const MIN_SHARED_BLOCK_STEP_MS = 250;
29
+ // The SQS delay range: a paced retry that can come back inside it stays in it.
30
+ const MAX_PACED_RETRY_MS = 900 * 1000;
31
+ // The most that one caller waits past the end of a block, at random.
32
+ const MAX_RELEASE_JITTER_MS = 1_000;
28
33
  // A retry without a known rate spreads over at least this time.
29
34
  const MIN_RETRY_SPREAD_MS = 1_000;
30
35
  const HEADER_PARSERS = ['ietf', 'resetHeaders'];
@@ -269,8 +274,12 @@ class RateLimitPacer {
269
274
  this._sharedStore = createRateLimitStateRepository();
270
275
  }
271
276
  } catch (error) {
272
- this._sharedStore = null;
277
+ // Try again after the pause: a cold start can fail on its first
278
+ // database connection.
279
+ this._sharedStore = undefined;
280
+ this._sharedPausedUntil = this.now() + SHARED_FAILURE_PAUSE_MS;
273
281
  this._reportFailure('create', error);
282
+ return null;
274
283
  }
275
284
  return this._sharedStore;
276
285
  }
@@ -381,9 +390,26 @@ class RateLimitPacer {
381
390
 
382
391
  if (waitMs > budgetMs) return { granted: false, waitMs, reason };
383
392
  for (const bucket of buckets) bucket.take();
384
- return waitMs > 0
385
- ? { granted: true, waitMs, reason }
386
- : { 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
+ };
387
413
  }
388
414
 
389
415
  /**
@@ -477,42 +503,49 @@ class RateLimitPacer {
477
503
  * spread is max(waitMs, 1 s), but never more than
478
504
  * FRIGG_QUEUE_DEFERRAL_JITTER_MAX_MS.
479
505
  *
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.)
517
+ *
480
518
  * @returns {Promise<Date>}
481
519
  */
482
520
  async reserveRetry({ scopeKey, entityId, policy, notBefore, waitMs = 0 }) {
521
+ const nb = notBefore.getTime();
522
+ const delayEnd = this.now() + MAX_PACED_RETRY_MS;
483
523
  const intervalMs = scopeKey
484
524
  ? this.intervalMs({ scopeKey, policy })
485
525
  : undefined;
486
- if (!intervalMs) {
487
- const spread = Math.min(
526
+ if (!intervalMs || nb > delayEnd) {
527
+ let spread = Math.min(
488
528
  Math.max(waitMs, MIN_RETRY_SPREAD_MS),
489
529
  jitterMaxMs(this.env)
490
530
  );
491
- return new Date(
492
- notBefore.getTime() + Math.floor(this.random() * spread)
493
- );
531
+ if (nb <= delayEnd) spread = Math.min(spread, delayEnd - nb);
532
+ return new Date(nb + Math.floor(this.random() * spread));
494
533
  }
495
534
 
535
+ const options = { notBefore, intervalMs, notAfter: new Date(delayEnd) };
496
536
  let slot;
497
537
  const store = this._shared(policy, entityId);
498
538
  if (store) {
499
539
  slot = await this._storeCall('reserveSlot', () =>
500
- store.reserveSlot(
501
- { entityId, scopeKey },
502
- { notBefore, intervalMs }
503
- )
540
+ store.reserveSlot({ entityId, scopeKey }, options)
504
541
  );
505
542
  }
506
- slot ??= await this.localStore.reserveSlot(
507
- { scopeKey },
508
- {
509
- notBefore,
510
- intervalMs,
511
- }
512
- );
513
- return new Date(
514
- slot.getTime() + Math.floor(this.random() * intervalMs)
515
- );
543
+ slot ??= await this.localStore.reserveSlot({ scopeKey }, options);
544
+ if (slot === SLOTS_FULL) {
545
+ return new Date(nb + Math.floor(this.random() * (delayEnd - nb)));
546
+ }
547
+ const at = slot.getTime() + Math.floor(this.random() * intervalMs);
548
+ return new Date(Math.min(at, delayEnd));
516
549
  }
517
550
  }
518
551
 
@@ -216,6 +216,26 @@ function staticHint(policy, reason, now) {
216
216
  return waitMs > 0 ? hintFromWait(waitMs, now, { source: 'static' }) : null;
217
217
  }
218
218
 
219
+ /**
220
+ * How long a throttle blocks the whole scope key: the provider's time only.
221
+ * A parsed or classified hint gives it directly. A static hint is
222
+ * `max(window.perMs, minRetryAfterMs)`; only the named window is the
223
+ * provider's, so `minRetryAfterMs` delays the one message, not the key.
224
+ * Returns 0 when the provider gave no time.
225
+ */
226
+ function scopeBlockMs(hint, policy) {
227
+ if (!hint || !Number.isFinite(hint.waitMs)) return 0;
228
+ if (hint.source !== 'static') return Math.max(0, hint.waitMs);
229
+ const window = policy?.windows?.find(
230
+ (candidate) =>
231
+ candidate &&
232
+ candidate.name === hint.reason &&
233
+ Number.isFinite(candidate.perMs) &&
234
+ candidate.perMs > 0
235
+ );
236
+ return window?.perMs ?? 0;
237
+ }
238
+
219
239
  function withClassified(hint, classified) {
220
240
  return {
221
241
  ...hint,
@@ -314,6 +334,7 @@ function inProcessBudgetMs({
314
334
  }
315
335
 
316
336
  module.exports = {
337
+ scopeBlockMs,
317
338
  DEFAULT_PARSERS,
318
339
  JITTER_MAX_MS,
319
340
  MIN_HINTED_WAIT_MS,
@@ -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': {
@@ -41,16 +41,21 @@ class RateLimitStateRepositoryInterface {
41
41
  /**
42
42
  * Take the next retry slot of the key, in one atomic step:
43
43
  * `slot = max(nextSlotMs, notBefore)`, then `nextSlotMs = slot + intervalMs`.
44
- * Two callers never get the same slot.
44
+ * Two callers never get the same slot. When `slot` would be after
45
+ * `notAfter`, nothing changes and the result is SLOTS_FULL: the sequence
46
+ * never runs further ahead than the caller can wait.
45
47
  * @param {RateLimitLocation} location
46
- * @param {{ notBefore: Date, intervalMs: number }} options
47
- * @returns {Promise<Date|null>} the start of the slot
48
+ * @param {{ notBefore: Date, notAfter?: Date, intervalMs: number }} options
49
+ * @returns {Promise<Date|null|typeof SLOTS_FULL>} the start of the slot
48
50
  */
49
51
  async reserveSlot(/* location, { notBefore, intervalMs } */) {
50
52
  throw new Error('reserveSlot must be implemented by subclass');
51
53
  }
52
54
  }
53
55
 
56
+ /** reserveSlot result: every slot up to `notAfter` is taken. */
57
+ const SLOTS_FULL = Symbol.for('@friggframework/core.rate-limit-slots-full');
58
+
54
59
  /** The JSON field in Entity.data that holds the state. */
55
60
  const STATE_FIELD = 'friggRateLimit';
56
61
 
@@ -64,6 +69,7 @@ function stateMemberName(scopeKey) {
64
69
 
65
70
  module.exports = {
66
71
  RateLimitStateRepositoryInterface,
72
+ SLOTS_FULL,
67
73
  STATE_FIELD,
68
74
  stateMemberName,
69
75
  };
@@ -1,5 +1,6 @@
1
1
  const {
2
2
  RateLimitStateRepositoryInterface,
3
+ SLOTS_FULL,
3
4
  } = require('./rate-limit-state-repository-interface');
4
5
 
5
6
  const MAX_KEYS = 10_000;
@@ -46,9 +47,10 @@ class RateLimitStateRepositoryMemory extends RateLimitStateRepositoryInterface {
46
47
  }
47
48
  }
48
49
 
49
- async reserveSlot(location, { notBefore, intervalMs }) {
50
+ async reserveSlot(location, { notBefore, notAfter, intervalMs }) {
50
51
  const row = this._row(location);
51
52
  const slot = Math.max(row.nextSlotMs ?? 0, notBefore.getTime());
53
+ if (notAfter && slot > notAfter.getTime()) return SLOTS_FULL;
52
54
  row.nextSlotMs = slot + slotStepMs(intervalMs);
53
55
  return new Date(slot);
54
56
  }
@@ -1,5 +1,6 @@
1
1
  const {
2
2
  RateLimitStateRepositoryInterface,
3
+ SLOTS_FULL,
3
4
  STATE_FIELD,
4
5
  stateMemberName,
5
6
  } = require('./rate-limit-state-repository-interface');
@@ -95,16 +96,24 @@ class RateLimitStateRepositoryMongo extends RateLimitStateRepositoryInterface {
95
96
  });
96
97
  }
97
98
 
98
- async reserveSlot({ entityId, scopeKey }, { notBefore, intervalMs }) {
99
+ async reserveSlot(
100
+ { entityId, scopeKey },
101
+ { notBefore, notAfter, intervalMs }
102
+ ) {
99
103
  const filter = entityFilter(entityId);
100
104
  if (!filter) return null;
101
105
  const path = this._path(scopeKey, 'nextSlotMs');
102
106
  const step = slotStepMs(intervalMs);
103
107
  const notBeforeMs = notBefore.getTime();
108
+ const notAfterMs = notAfter ? notAfter.getTime() : undefined;
109
+ const ahead =
110
+ notAfterMs === undefined
111
+ ? { $gte: notBeforeMs }
112
+ : { $gte: notBeforeMs, $lte: notAfterMs };
104
113
  for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
105
114
  const advanced = await this._command({
106
115
  findAndModify: COLLECTION,
107
- query: { ...filter, [path]: { $gte: notBeforeMs } },
116
+ query: { ...filter, [path]: ahead },
108
117
  update: { $inc: { [path]: step } },
109
118
  fields: { [path]: 1 },
110
119
  new: false,
@@ -134,10 +143,21 @@ class RateLimitStateRepositoryMongo extends RateLimitStateRepositoryInterface {
134
143
  const exists = await this._command({
135
144
  find: COLLECTION,
136
145
  filter,
137
- projection: { _id: 1 },
146
+ projection: { [path]: 1 },
138
147
  limit: 1,
139
148
  });
140
- if (!exists?.cursor?.firstBatch?.length) return null;
149
+ const doc = exists?.cursor?.firstBatch?.[0];
150
+ if (!doc) return null;
151
+ const next = toNumber(
152
+ doc.data?.[STATE_FIELD]?.[stateMemberName(scopeKey)]?.nextSlotMs
153
+ );
154
+ if (
155
+ notAfterMs !== undefined &&
156
+ next !== null &&
157
+ next > notAfterMs
158
+ ) {
159
+ return SLOTS_FULL;
160
+ }
141
161
  }
142
162
  throw new Error(
143
163
  `rate-limit slot for ${scopeKey} not reserved after ${MAX_ATTEMPTS} attempts`
@@ -1,5 +1,6 @@
1
1
  const {
2
2
  RateLimitStateRepositoryInterface,
3
+ SLOTS_FULL,
3
4
  STATE_FIELD,
4
5
  stateMemberName,
5
6
  } = require('./rate-limit-state-repository-interface');
@@ -61,12 +62,19 @@ class RateLimitStateRepositoryPostgres extends RateLimitStateRepositoryInterface
61
62
  WHERE "id" = ${id}`;
62
63
  }
63
64
 
64
- async reserveSlot({ entityId, scopeKey }, { notBefore, intervalMs }) {
65
+ async reserveSlot(
66
+ { entityId, scopeKey },
67
+ { notBefore, notAfter, intervalMs }
68
+ ) {
65
69
  const id = toEntityId(entityId);
66
70
  if (id === undefined) return null;
67
71
  const member = stateMemberName(scopeKey);
68
72
  const step = BigInt(slotStepMs(intervalMs));
69
73
  const notBeforeMs = BigInt(notBefore.getTime());
74
+ // No limit: the largest bigint, so the WHERE always passes.
75
+ const notAfterMs = notAfter
76
+ ? BigInt(notAfter.getTime())
77
+ : 9223372036854775807n;
70
78
  const rows = await this.prisma.$queryRaw`
71
79
  UPDATE "Entity" SET "data" =
72
80
  COALESCE("data", '{}'::jsonb) || jsonb_build_object(
@@ -83,10 +91,20 @@ class RateLimitStateRepositoryPostgres extends RateLimitStateRepositoryInterface
83
91
  )
84
92
  )
85
93
  WHERE "id" = ${id}
94
+ AND GREATEST(
95
+ COALESCE(("data" -> ${STATE_FIELD}::text -> ${member}::text
96
+ ->> 'nextSlotMs')::bigint, 0),
97
+ ${notBeforeMs}::bigint
98
+ ) <= ${notAfterMs}::bigint
86
99
  RETURNING ("data" -> ${STATE_FIELD}::text -> ${member}::text
87
100
  ->> 'nextSlotMs')::bigint AS "nextSlotMs"`;
88
- if (rows.length === 0) return null;
89
- return new Date(Number(rows[0].nextSlotMs) - Number(step));
101
+ if (rows.length > 0) {
102
+ return new Date(Number(rows[0].nextSlotMs) - Number(step));
103
+ }
104
+ // No row: the entity is gone, or every slot up to notAfter is taken.
105
+ const exists = await this.prisma.$queryRaw`
106
+ SELECT 1 AS "found" FROM "Entity" WHERE "id" = ${id}`;
107
+ return exists.length > 0 ? SLOTS_FULL : null;
90
108
  }
91
109
  }
92
110
 
@@ -15,6 +15,7 @@ const { getLoggerScope } = require('../../logs/context');
15
15
  const {
16
16
  computeScopeKey,
17
17
  computeWaitMs,
18
+ scopeBlockMs,
18
19
  inProcessBudgetMs,
19
20
  readRateLimitPolicy,
20
21
  resolveRateLimitHint,
@@ -538,7 +539,11 @@ class Requester extends Delegate {
538
539
  // the jitter delay this message, not every other call on the key.
539
540
  if (!untimed) {
540
541
  await this._blockScope(
541
- Date.now() + Math.max(hint.waitMs, MIN_SCOPE_BLOCK_MS)
542
+ Date.now() +
543
+ Math.max(
544
+ scopeBlockMs(hint, this._rateLimitPolicy),
545
+ MIN_SCOPE_BLOCK_MS
546
+ )
542
547
  );
543
548
  }
544
549
  if (fits) {
@@ -569,6 +574,9 @@ class Requester extends Delegate {
569
574
  if (retryWaitMs !== undefined && this._pacingScopeKey()) {
570
575
  rateLimitError.paced = true;
571
576
  }
577
+ // The queue worker spreads only the retries of a module that
578
+ // declared a policy. No policy, no change (ADR-049 A.4).
579
+ if (this._rateLimitPolicy) rateLimitError.declaredPolicy = true;
572
580
  throw this._maybeFlagTimeoutDuringBodyRead(rateLimitError, timeoutMs);
573
581
  }
574
582
 
@@ -645,6 +653,8 @@ class Requester extends Delegate {
645
653
  error.statusCode = 429;
646
654
  error.preempted = true;
647
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);
648
658
  error.message = `${error.message} paced: not sent`;
649
659
  this._logPaced(gate, scopeKey, error);
650
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.57dc4bf.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.57dc4bf.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.57dc4bf.0",
53
- "@friggframework/prettier-config": "2.0.0--canary.743.57dc4bf.0",
54
- "@friggframework/test": "2.0.0--canary.743.57dc4bf.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": "57dc4bfa7d4bd3dbf00a286355c7e4c041acd0fe"
96
+ "gitHead": "265a5cd5f39515f47164aec0b99fed86048b59d9"
97
97
  }