@friggframework/core 2.0.0--canary.743.57dc4bf.0 → 2.0.0--canary.743.81eabd1.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
@@ -228,14 +228,17 @@ class Worker {
228
228
  const knownRetryAt = validDate(error.retryAt);
229
229
  const earliest = knownRetryAt ?? new Date(now + limits.probeMs);
230
230
  // The requester already spread a paced error over the key's slots.
231
- const retryAt = error.paced
232
- ? earliest
233
- : jitteredRetryAt(
234
- earliest,
235
- Math.max(0, earliest.getTime() - now),
236
- { ...limits, now },
237
- this._random
238
- );
231
+ // An error from a module with no rate-limit policy keeps its exact
232
+ // retryAt: no policy, no change (ADR-049 A.4).
233
+ const retryAt =
234
+ error.paced || error.declaredPolicy !== true
235
+ ? earliest
236
+ : jitteredRetryAt(
237
+ earliest,
238
+ Math.max(0, earliest.getTime() - now),
239
+ { ...limits, now },
240
+ this._random
241
+ );
239
242
  const counters = nextDeferral(body, now, record.messageId, {
240
243
  preempted: error.preempted === true,
241
244
  maxPacedDeferrals: limits.maxPacedDeferrals,
@@ -0,0 +1,45 @@
1
+ const {
2
+ STATE_FIELD,
3
+ } = require('../requester/rate-limit/state/rate-limit-state-repository-interface');
4
+
5
+ // Entity.data holds the integration's own fields and, under STATE_FIELD, the
6
+ // shared rate-limit state that the pacer writes with atomic statements
7
+ // (ADR-049 section 6, 2b). Entity reads and writes never carry that state:
8
+ // a read does not show it, and an update never writes it back, so an update
9
+ // cannot overwrite a newer value.
10
+
11
+ /** The integration's own fields of Entity.data, without the pacer's state. */
12
+ function entityDataFields(data) {
13
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return {};
14
+ if (!(STATE_FIELD in data)) return data;
15
+ const { [STATE_FIELD]: _state, ...fields } = data;
16
+ return fields;
17
+ }
18
+
19
+ /** A key that MongoDB accepts as one segment of a dotted `$set` path. */
20
+ const isPathSafeKey = (key) =>
21
+ typeof key === 'string' &&
22
+ key !== '' &&
23
+ !key.includes('.') &&
24
+ !key.startsWith('$');
25
+
26
+ /**
27
+ * `$set` paths for a shallow merge into Entity.data: one `data.<key>` path
28
+ * for each field. Returns null when a key cannot be a path segment.
29
+ */
30
+ function dataSetPaths(fields) {
31
+ const paths = {};
32
+ for (const [key, value] of Object.entries(fields)) {
33
+ if (!isPathSafeKey(key)) return null;
34
+ // The same JSON shape that a Prisma Json field stores.
35
+ paths[`data.${key}`] =
36
+ value === undefined ? null : JSON.parse(JSON.stringify(value));
37
+ }
38
+ return paths;
39
+ }
40
+
41
+ module.exports = {
42
+ RATE_LIMIT_STATE_FIELD: STATE_FIELD,
43
+ dataSetPaths,
44
+ entityDataFields,
45
+ };
@@ -1,4 +1,5 @@
1
1
  const { prisma } = require('../../database/prisma');
2
+ const { entityDataFields, RATE_LIMIT_STATE_FIELD, dataSetPaths } = require('./entity-data');
2
3
  const {
3
4
  toObjectId,
4
5
  fromObjectId,
@@ -133,7 +134,7 @@ class ModuleRepositoryDocumentDB extends ModuleRepositoryInterface {
133
134
  name: name ?? null,
134
135
  moduleName: moduleName ?? null,
135
136
  externalId: externalId ?? null,
136
- data: dynamicData,
137
+ data: entityDataFields(dynamicData),
137
138
  };
138
139
  const insertedId = await insertOne(this.prisma, 'Entity', document);
139
140
  const created = await findOne(this.prisma, 'Entity', { _id: insertedId });
@@ -170,8 +171,28 @@ class ModuleRepositoryDocumentDB extends ModuleRepositoryInterface {
170
171
  if (moduleName !== undefined) updatePayload.moduleName = moduleName;
171
172
  if (externalId !== undefined) updatePayload.externalId = externalId;
172
173
 
173
- if (Object.keys(dynamicData).length > 0) {
174
- updatePayload.data = { ...(existing.data || {}), ...dynamicData };
174
+ // A shallow merge with one `$set` path for each field: the rate-limit
175
+ // state that the pacer writes in the same document is never written
176
+ // back. A key that cannot be a path segment falls back to a whole
177
+ // `data` write, which keeps the state as it was read.
178
+ const fields = entityDataFields(dynamicData);
179
+ if (Object.keys(fields).length > 0) {
180
+ const paths =
181
+ existing.data && typeof existing.data === 'object'
182
+ ? dataSetPaths(fields)
183
+ : null;
184
+ if (paths) {
185
+ Object.assign(updatePayload, paths);
186
+ } else {
187
+ const state = existing.data?.[RATE_LIMIT_STATE_FIELD];
188
+ updatePayload.data = {
189
+ ...entityDataFields(existing.data),
190
+ ...fields,
191
+ ...(state !== undefined && {
192
+ [RATE_LIMIT_STATE_FIELD]: state,
193
+ }),
194
+ };
195
+ }
175
196
  }
176
197
 
177
198
  await updateOne(
@@ -333,7 +354,7 @@ class ModuleRepositoryDocumentDB extends ModuleRepositoryInterface {
333
354
  }
334
355
 
335
356
  _mapEntity(doc, credential) {
336
- const dynamicData = doc?.data || {};
357
+ const dynamicData = entityDataFields(doc?.data);
337
358
  return {
338
359
  id: fromObjectId(doc?._id),
339
360
  credential,
@@ -1,4 +1,5 @@
1
1
  const { prisma } = require('../../database/prisma');
2
+ const { entityDataFields, RATE_LIMIT_STATE_FIELD, dataSetPaths } = require('./entity-data');
2
3
  const { ModuleRepositoryInterface } = require('./module-repository-interface');
3
4
 
4
5
  /**
@@ -102,7 +103,7 @@ class ModuleRepositoryMongo extends ModuleRepositoryInterface {
102
103
  name: entity.name,
103
104
  externalId: entity.externalId,
104
105
  moduleName: entity.moduleName,
105
- ...(entity.data || {}),
106
+ ...entityDataFields(entity.data),
106
107
  };
107
108
  }
108
109
 
@@ -128,7 +129,7 @@ class ModuleRepositoryMongo extends ModuleRepositoryInterface {
128
129
  name: e.name,
129
130
  externalId: e.externalId,
130
131
  moduleName: e.moduleName,
131
- ...(e.data || {}),
132
+ ...entityDataFields(e.data),
132
133
  }));
133
134
  }
134
135
 
@@ -154,7 +155,7 @@ class ModuleRepositoryMongo extends ModuleRepositoryInterface {
154
155
  name: e.name,
155
156
  externalId: e.externalId,
156
157
  moduleName: e.moduleName,
157
- ...(e.data || {}),
158
+ ...entityDataFields(e.data),
158
159
  }));
159
160
  }
160
161
 
@@ -184,7 +185,7 @@ class ModuleRepositoryMongo extends ModuleRepositoryInterface {
184
185
  name: e.name,
185
186
  externalId: e.externalId,
186
187
  moduleName: e.moduleName,
187
- ...(e.data || {}),
188
+ ...entityDataFields(e.data),
188
189
  }));
189
190
  }
190
191
 
@@ -230,7 +231,7 @@ class ModuleRepositoryMongo extends ModuleRepositoryInterface {
230
231
  name: entity.name,
231
232
  externalId: entity.externalId,
232
233
  moduleName: entity.moduleName,
233
- ...(entity.data || {}),
234
+ ...entityDataFields(entity.data),
234
235
  };
235
236
  }
236
237
 
@@ -258,7 +259,7 @@ class ModuleRepositoryMongo extends ModuleRepositoryInterface {
258
259
  name: e.name,
259
260
  externalId: e.externalId,
260
261
  moduleName: e.moduleName,
261
- ...(e.data || {}),
262
+ ...entityDataFields(e.data),
262
263
  }));
263
264
  }
264
265
 
@@ -287,7 +288,7 @@ class ModuleRepositoryMongo extends ModuleRepositoryInterface {
287
288
  name,
288
289
  moduleName,
289
290
  externalId,
290
- data: dynamicData,
291
+ data: entityDataFields(dynamicData),
291
292
  };
292
293
 
293
294
  const entity = await this.prisma.entity.create({
@@ -303,7 +304,7 @@ class ModuleRepositoryMongo extends ModuleRepositoryInterface {
303
304
  name: entity.name,
304
305
  externalId: entity.externalId,
305
306
  moduleName: entity.moduleName,
306
- ...(entity.data || {}),
307
+ ...entityDataFields(entity.data),
307
308
  };
308
309
  }
309
310
 
@@ -346,8 +347,33 @@ class ModuleRepositoryMongo extends ModuleRepositoryInterface {
346
347
  if (moduleName !== undefined) schemaUpdates.moduleName = moduleName;
347
348
  if (externalId !== undefined) schemaUpdates.externalId = externalId;
348
349
 
349
- if (Object.keys(dynamicData).length > 0) {
350
- schemaUpdates.data = { ...(existing.data || {}), ...dynamicData };
350
+ // A shallow merge with one `$set` path for each field: the rate-limit
351
+ // 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.
354
+ const fields = entityDataFields(dynamicData);
355
+ if (Object.keys(fields).length > 0) {
356
+ const paths =
357
+ existing.data && typeof existing.data === 'object'
358
+ ? dataSetPaths(fields)
359
+ : null;
360
+ if (paths) {
361
+ await this.prisma.$runCommandRaw({
362
+ update: 'Entity',
363
+ updates: [
364
+ { q: { _id: { $oid: entityId } }, u: { $set: paths } },
365
+ ],
366
+ });
367
+ } else {
368
+ const state = existing.data?.[RATE_LIMIT_STATE_FIELD];
369
+ schemaUpdates.data = {
370
+ ...entityDataFields(existing.data),
371
+ ...fields,
372
+ ...(state !== undefined && {
373
+ [RATE_LIMIT_STATE_FIELD]: state,
374
+ }),
375
+ };
376
+ }
351
377
  }
352
378
 
353
379
  try {
@@ -365,7 +391,7 @@ class ModuleRepositoryMongo extends ModuleRepositoryInterface {
365
391
  name: entity.name,
366
392
  externalId: entity.externalId,
367
393
  moduleName: entity.moduleName,
368
- ...(entity.data || {}),
394
+ ...entityDataFields(entity.data),
369
395
  };
370
396
  } catch (error) {
371
397
  if (error.code === 'P2025') {
@@ -1,4 +1,5 @@
1
1
  const { prisma } = require('../../database/prisma');
2
+ const { entityDataFields } = require('./entity-data');
2
3
  const { ModuleRepositoryInterface } = require('./module-repository-interface');
3
4
 
4
5
  /**
@@ -136,7 +137,7 @@ class ModuleRepositoryPostgres extends ModuleRepositoryInterface {
136
137
  name: entity.name,
137
138
  externalId: entity.externalId,
138
139
  moduleName: entity.moduleName,
139
- ...(entity.data || {}),
140
+ ...entityDataFields(entity.data),
140
141
  };
141
142
  }
142
143
 
@@ -164,7 +165,7 @@ class ModuleRepositoryPostgres extends ModuleRepositoryInterface {
164
165
  name: e.name,
165
166
  externalId: e.externalId,
166
167
  moduleName: e.moduleName,
167
- ...(e.data || {}),
168
+ ...entityDataFields(e.data),
168
169
  }));
169
170
  }
170
171
 
@@ -192,7 +193,7 @@ class ModuleRepositoryPostgres extends ModuleRepositoryInterface {
192
193
  name: e.name,
193
194
  externalId: e.externalId,
194
195
  moduleName: e.moduleName,
195
- ...(e.data || {}),
196
+ ...entityDataFields(e.data),
196
197
  }));
197
198
  }
198
199
 
@@ -224,7 +225,7 @@ class ModuleRepositoryPostgres extends ModuleRepositoryInterface {
224
225
  name: e.name,
225
226
  externalId: e.externalId,
226
227
  moduleName: e.moduleName,
227
- ...(e.data || {}),
228
+ ...entityDataFields(e.data),
228
229
  }));
229
230
  }
230
231
 
@@ -271,7 +272,7 @@ class ModuleRepositoryPostgres extends ModuleRepositoryInterface {
271
272
  name: entity.name,
272
273
  externalId: entity.externalId,
273
274
  moduleName: entity.moduleName,
274
- ...(entity.data || {}),
275
+ ...entityDataFields(entity.data),
275
276
  };
276
277
  }
277
278
 
@@ -299,7 +300,7 @@ class ModuleRepositoryPostgres extends ModuleRepositoryInterface {
299
300
  name: e.name,
300
301
  externalId: e.externalId,
301
302
  moduleName: e.moduleName,
302
- ...(e.data || {}),
303
+ ...entityDataFields(e.data),
303
304
  }));
304
305
  }
305
306
 
@@ -328,7 +329,7 @@ class ModuleRepositoryPostgres extends ModuleRepositoryInterface {
328
329
  name,
329
330
  moduleName,
330
331
  externalId,
331
- data: dynamicData,
332
+ data: entityDataFields(dynamicData),
332
333
  };
333
334
 
334
335
  const entity = await this.prisma.entity.create({
@@ -344,7 +345,7 @@ class ModuleRepositoryPostgres extends ModuleRepositoryInterface {
344
345
  name: entity.name,
345
346
  externalId: entity.externalId,
346
347
  moduleName: entity.moduleName,
347
- ...(entity.data || {}),
348
+ ...entityDataFields(entity.data),
348
349
  };
349
350
  }
350
351
 
@@ -389,8 +390,14 @@ class ModuleRepositoryPostgres extends ModuleRepositoryInterface {
389
390
  if (moduleName !== undefined) schemaUpdates.moduleName = moduleName;
390
391
  if (externalId !== undefined) schemaUpdates.externalId = externalId;
391
392
 
392
- if (Object.keys(dynamicData).length > 0) {
393
- schemaUpdates.data = { ...(existing.data || {}), ...dynamicData };
393
+ // A shallow merge in one statement: the rate-limit state that the
394
+ // pacer writes in the same column is never written back.
395
+ 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}`;
394
401
  }
395
402
 
396
403
  try {
@@ -408,7 +415,7 @@ class ModuleRepositoryPostgres extends ModuleRepositoryInterface {
408
415
  name: entity.name,
409
416
  externalId: entity.externalId,
410
417
  moduleName: entity.moduleName,
411
- ...(entity.data || {}),
418
+ ...entityDataFields(entity.data),
412
419
  };
413
420
  } catch (error) {
414
421
  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
+ // When every slot of that range is taken: spread over its last minute.
32
+ const FULL_RETRY_SPREAD_MS = 60_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
  }
@@ -477,42 +486,50 @@ class RateLimitPacer {
477
486
  * spread is max(waitMs, 1 s), but never more than
478
487
  * FRIGG_QUEUE_DEFERRAL_JITTER_MAX_MS.
479
488
  *
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.
495
+ *
480
496
  * @returns {Promise<Date>}
481
497
  */
482
498
  async reserveRetry({ scopeKey, entityId, policy, notBefore, waitMs = 0 }) {
499
+ const nb = notBefore.getTime();
500
+ const delayEnd = this.now() + MAX_PACED_RETRY_MS;
501
+ const cap = nb <= delayEnd ? delayEnd : undefined;
483
502
  const intervalMs = scopeKey
484
503
  ? this.intervalMs({ scopeKey, policy })
485
504
  : undefined;
486
505
  if (!intervalMs) {
487
- const spread = Math.min(
506
+ let spread = Math.min(
488
507
  Math.max(waitMs, MIN_RETRY_SPREAD_MS),
489
508
  jitterMaxMs(this.env)
490
509
  );
491
- return new Date(
492
- notBefore.getTime() + Math.floor(this.random() * spread)
493
- );
510
+ if (cap !== undefined) spread = Math.min(spread, cap - nb);
511
+ return new Date(nb + Math.floor(this.random() * spread));
494
512
  }
495
513
 
514
+ const options = {
515
+ notBefore,
516
+ intervalMs,
517
+ ...(cap !== undefined && { notAfter: new Date(cap) }),
518
+ };
496
519
  let slot;
497
520
  const store = this._shared(policy, entityId);
498
521
  if (store) {
499
522
  slot = await this._storeCall('reserveSlot', () =>
500
- store.reserveSlot(
501
- { entityId, scopeKey },
502
- { notBefore, intervalMs }
503
- )
523
+ store.reserveSlot({ entityId, scopeKey }, options)
504
524
  );
505
525
  }
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
- );
526
+ slot ??= await this.localStore.reserveSlot({ scopeKey }, options);
527
+ 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));
530
+ }
531
+ const at = slot.getTime() + Math.floor(this.random() * intervalMs);
532
+ return new Date(cap === undefined ? at : Math.min(at, cap));
516
533
  }
517
534
  }
518
535
 
@@ -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,
@@ -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
 
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.81eabd1.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.81eabd1.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.81eabd1.0",
53
+ "@friggframework/prettier-config": "2.0.0--canary.743.81eabd1.0",
54
+ "@friggframework/test": "2.0.0--canary.743.81eabd1.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": "81eabd10e0cb7ab8384f240d96c98c88a0de4410"
97
97
  }