@friggframework/core 2.0.0--canary.744.e18e27f.0 → 2.0.0--canary.743.d13a976.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/CLAUDE.md CHANGED
@@ -949,6 +949,14 @@ Use test doubles from `@friggframework/test` package for consistent mocking.
949
949
  - `FRIGG_QUEUE_MAX_DEFERRALS` - Most rate-limit deferrals of one message (default 30)
950
950
  - `FRIGG_QUEUE_MAX_DEFERRED_MS` - Most time in ms from a message's first rate-limit deferral to its retry time (default 26 h)
951
951
  - `FRIGG_QUEUE_RATE_LIMIT_PROBE_MS` - Time in ms until the retry of a rate-limited message whose `retryAt` is unknown (default 1 h)
952
+ - `FRIGG_QUEUE_DEFERRAL_JITTER_MAX_MS` - Most random spread in ms added to a rate-limit deferral (default 5 min; `0` turns it off). A wait in the 900 s SQS delay range stays in it
953
+ - `FRIGG_QUEUE_MAX_PACED_DEFERRALS` - Pacer deferrals (no call sent) of one message that do not count against `FRIGG_QUEUE_MAX_DEFERRALS` (default 100)
954
+ - `FRIGG_RATE_LIMIT_PACING` - `off` turns off pacing before a call (ADR-049 section 6) in all modules
955
+ - `FRIGG_RATE_LIMIT_MAX_PACING_WAIT_MS` - Longest pacing sleep in ms before the call defers instead (default 5 s)
956
+ - `FRIGG_RATE_LIMIT_MAX_SLOT_HORIZON_MS` - Furthest ahead in ms a shared call slot may be taken; a later slot defers the call without sending it (default 5 s)
957
+ - `FRIGG_RATE_LIMIT_MAX_BLOCK_MS` - Longest block of a scope key in ms (default 15 min)
958
+ - `FRIGG_RATE_LIMIT_SHARED_CACHE_MS` - How long in ms a worker keeps the shared block it read (default 1 s)
959
+ - `FRIGG_RATE_LIMIT_SHARED_TIMEOUT_MS` - Longest wait in ms for the shared rate-limit store before pacing goes on in process at a reduced rate (default 1 s)
952
960
 
953
961
  ## Version Information
954
962
 
package/core/Worker.js CHANGED
@@ -14,6 +14,7 @@ const {
14
14
  MAX_DELAY_SECONDS,
15
15
  deferredMs,
16
16
  isDeferralCapped,
17
+ jitteredRetryAt,
17
18
  nextDeferral,
18
19
  readDeferral,
19
20
  readDeferralLimits,
@@ -167,7 +168,8 @@ class Worker {
167
168
  // The RATE_LIMITED event of ADR-049 section 3. The same object is meant to
168
169
  // become the input of the ADR-047 orchestrator's reducer.
169
170
  _rateLimitedEvent(record, body, error, delivery) {
170
- const { deferrals, firstDeferredAt } = readDeferral(body);
171
+ const { deferrals, pacedDeferrals, firstDeferredAt } =
172
+ readDeferral(body);
171
173
  return {
172
174
  retryAt: validDate(error.retryAt) ?? undefined,
173
175
  waitMs: error.waitMs,
@@ -179,6 +181,7 @@ class Worker {
179
181
  messageId: record.messageId,
180
182
  receiveCount: delivery.receiveCount,
181
183
  deferrals,
184
+ pacedDeferrals: pacedDeferrals ?? 0,
182
185
  deferredMs: firstDeferredAt
183
186
  ? Date.now() - Date.parse(firstDeferredAt)
184
187
  : 0,
@@ -223,8 +226,23 @@ class Worker {
223
226
  const now = Date.now();
224
227
  const limits = readDeferralLimits();
225
228
  const knownRetryAt = validDate(error.retryAt);
226
- const retryAt = knownRetryAt ?? new Date(now + limits.probeMs);
227
- const counters = nextDeferral(body, now, record.messageId);
229
+ const earliest = knownRetryAt ?? new Date(now + limits.probeMs);
230
+ // The requester already spread a paced error over the key's slots.
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
+ );
242
+ const counters = nextDeferral(body, now, record.messageId, {
243
+ preempted: error.preempted === true,
244
+ maxPacedDeferrals: limits.maxPacedDeferrals,
245
+ });
228
246
  const deferral = {
229
247
  record,
230
248
  queueName,
@@ -427,8 +445,8 @@ class Worker {
427
445
 
428
446
  async _clearDeferredState(record, body, delivery) {
429
447
  const redelivered = delivery.receiveCount > 1;
430
- const { deferrals, deferralId } = readDeferral(body);
431
- if (deferrals === 0 && !redelivered) return;
448
+ const { deferrals, pacedDeferrals, deferralId } = readDeferral(body);
449
+ if (deferrals === 0 && !pacedDeferrals && !redelivered) return;
432
450
  await this._clearWait(body, deferralId ?? record.messageId);
433
451
  }
434
452
 
@@ -455,7 +473,11 @@ class Worker {
455
473
  waitMs,
456
474
  retryAt: retryAt.toISOString(),
457
475
  ...(probe && { probe }),
476
+ ...(error.preempted && { preempted: true }),
458
477
  deferrals: counters.deferrals,
478
+ ...(counters.pacedDeferrals && {
479
+ pacedDeferrals: counters.pacedDeferrals,
480
+ }),
459
481
  firstDeferredAt: counters.firstDeferredAt,
460
482
  reason: error.reason,
461
483
  module: error.module,
package/index.js CHANGED
@@ -109,6 +109,10 @@ const {
109
109
  parseRetryAfter,
110
110
  parseResetHeaders,
111
111
  parseIetfRateLimit,
112
+ RateLimitPacer,
113
+ getRateLimitPacer,
114
+ hashRateLimitScope,
115
+ setRateLimitPacer,
112
116
  } = require('./modules/requester/rate-limit');
113
117
  const application = require('./application');
114
118
  const utils = require('./utils');
@@ -164,6 +168,10 @@ module.exports = {
164
168
  parseRetryAfter,
165
169
  parseResetHeaders,
166
170
  parseIetfRateLimit,
171
+ RateLimitPacer,
172
+ getRateLimitPacer,
173
+ hashRateLimitScope,
174
+ setRateLimitPacer,
167
175
 
168
176
  // integrations
169
177
  IntegrationBase,
@@ -66,12 +66,11 @@ class IntegrationRepositoryMongo extends IntegrationRepositoryInterface {
66
66
  * @returns {Promise<Array>} Array of integration objects (possibly empty)
67
67
  */
68
68
  async findIntegrations({ type, status } = {}) {
69
- let where = {};
69
+ const where = {};
70
70
  if (type) {
71
- const ids = await this._findIdsByType(type, { status });
72
- if (ids.length === 0) return [];
73
- where = { id: { in: ids } };
74
- } else if (status) {
71
+ where.config = { path: ['type'], equals: type };
72
+ }
73
+ if (status) {
75
74
  where.status = status;
76
75
  }
77
76
 
@@ -94,28 +93,6 @@ class IntegrationRepositoryMongo extends IntegrationRepositoryInterface {
94
93
  }));
95
94
  }
96
95
 
97
- /**
98
- * Ids of the integrations whose config.type is `type`. Prisma's MongoDB
99
- * connector has no JSON path filter (a where on config.type throws), so
100
- * the filter runs as a raw query and returns the ids only.
101
- *
102
- * @param {string} type - Integration type (config.type)
103
- * @param {Object} [options]
104
- * @param {string} [options.status] - Integration status
105
- * @param {number} [options.limit] - Most ids to return
106
- * @returns {Promise<string[]>}
107
- * @private
108
- */
109
- async _findIdsByType(type, { status, limit } = {}) {
110
- const filter = { 'config.type': type };
111
- if (status) filter.status = status;
112
- const options = { projection: { _id: 1 } };
113
- if (limit) options.limit = limit;
114
-
115
- const docs = await this.prisma.integration.findRaw({ filter, options });
116
- return (docs ?? []).map(({ _id }) => String(_id?.$oid ?? _id));
117
- }
118
-
119
96
  /**
120
97
  * Find every integration in a report-shaped projection.
121
98
  *
@@ -176,13 +153,17 @@ class IntegrationRepositoryMongo extends IntegrationRepositoryInterface {
176
153
  * @returns {Promise<Object>} Integration object
177
154
  */
178
155
  async findIntegrationByName(name) {
179
- const [id] = await this._findIdsByType(name, { limit: 1 });
180
- const integration = id
181
- ? await this.prisma.integration.findUnique({
182
- where: { id },
183
- include: { entities: true },
184
- })
185
- : null;
156
+ const integration = await this.prisma.integration.findFirst({
157
+ where: {
158
+ config: {
159
+ path: ['type'],
160
+ equals: name,
161
+ },
162
+ },
163
+ include: {
164
+ entities: true,
165
+ },
166
+ });
186
167
 
187
168
  if (!integration) {
188
169
  throw new Error(`Integration with name ${name} not found`);
@@ -0,0 +1,72 @@
1
+ const {
2
+ STATE_FIELD,
3
+ } = require('../requester/rate-limit/state/rate-limit-state-repository-interface');
4
+ const {
5
+ getEncryptedFields,
6
+ } = require('../../database/encryption/encryption-schema-registry');
7
+
8
+ // Entity.data holds the integration's own fields and, under STATE_FIELD, the
9
+ // shared rate-limit state that the pacer writes with atomic statements
10
+ // (ADR-049 section 6, 2b). Entity reads and writes never carry that state:
11
+ // a read does not show it, and an update never writes it back, so an update
12
+ // cannot overwrite a newer value.
13
+
14
+ /** The integration's own fields of Entity.data, without the pacer's state. */
15
+ function entityDataFields(data) {
16
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return {};
17
+ if (!(STATE_FIELD in data)) return data;
18
+ const { [STATE_FIELD]: _state, ...fields } = data;
19
+ return fields;
20
+ }
21
+
22
+ /** A key that MongoDB accepts as one segment of a dotted `$set` path. */
23
+ const isPathSafeKey = (key) =>
24
+ typeof key === 'string' &&
25
+ key !== '' &&
26
+ !key.includes('.') &&
27
+ !key.startsWith('$');
28
+
29
+ /**
30
+ * `$set` paths for a shallow merge into Entity.data: one `data.<key>` path
31
+ * for each field. Returns null when a key cannot be a path segment.
32
+ */
33
+ function dataSetPaths(fields) {
34
+ const paths = {};
35
+ for (const [key, value] of Object.entries(fields)) {
36
+ if (!isPathSafeKey(key)) return null;
37
+ // The same JSON shape that a Prisma Json field stores.
38
+ paths[`data.${key}`] =
39
+ value === undefined ? null : JSON.parse(JSON.stringify(value));
40
+ }
41
+ return paths;
42
+ }
43
+
44
+ /**
45
+ * True when an update may merge Entity.data with a raw statement. A raw
46
+ * statement skips the Prisma encryption extension, so it is used only when
47
+ * the app lists no Entity field for encryption (opted out or not). Otherwise the update goes
48
+ * through the Prisma model, which encrypts, and the rate-limit state is
49
+ * written back as it was read (the pacer's state is advisory and fails open).
50
+ */
51
+ function canMergeEntityDataRaw() {
52
+ // Every listed field, opted-out ones too: an opted-out field can still
53
+ // hold ciphertext in old rows, and only the Prisma model reads it.
54
+ return getEncryptedFields('Entity').length === 0;
55
+ }
56
+
57
+ /**
58
+ * True when Entity.data is stored as a JSON object that the pacer can merge
59
+ * its state into. When the app encrypts the whole `data` field, the column
60
+ * holds ciphertext and the shared rate-limit state is not used.
61
+ */
62
+ function entityDataHoldsRateLimitState() {
63
+ return !getEncryptedFields('Entity').includes('data');
64
+ }
65
+
66
+ module.exports = {
67
+ RATE_LIMIT_STATE_FIELD: STATE_FIELD,
68
+ canMergeEntityDataRaw,
69
+ dataSetPaths,
70
+ entityDataFields,
71
+ entityDataHoldsRateLimitState,
72
+ };
@@ -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') {
@@ -116,62 +116,6 @@ class OAuth2Requester extends Requester {
116
116
 
117
117
  /** @type {boolean} Whether this requester supports token refresh */
118
118
  this.isRefreshable = true;
119
-
120
- /**
121
- * @type {number} Refresh the access token before a request when it
122
- * expires within this many ms. 0 turns it off (the default). A
123
- * module opts in with `static refreshBeforeExpiryMs`; the
124
- * constructor param overrides the class value. Opt in only when the
125
- * provider's refresh token survives a refresh, and persist
126
- * `accessTokenExpire` in `apiPropertiesToPersist.credential` so a
127
- * new invocation knows the expiry.
128
- */
129
- const refreshBeforeExpiryMs =
130
- params?.refreshBeforeExpiryMs ??
131
- this.constructor.refreshBeforeExpiryMs ??
132
- 0;
133
- this.refreshBeforeExpiryMs =
134
- Number.isFinite(refreshBeforeExpiryMs) && refreshBeforeExpiryMs > 0
135
- ? refreshBeforeExpiryMs
136
- : 0;
137
- }
138
-
139
- /**
140
- * True when the module opted in (`refreshBeforeExpiryMs` > 0) and a
141
- * refresh token is held. Off for the `client_credentials` grant:
142
- * getTokenFromClientCredentials() reports any failure, a 503 too, as
143
- * invalid auth, which would disable a working credential. Without a
144
- * refresh token, the provider rejects the refresh, which would also mark
145
- * the credential invalid.
146
- *
147
- * @returns {boolean}
148
- */
149
- isProactiveRefreshEnabled() {
150
- if (!this.refreshBeforeExpiryMs) return false;
151
- if (this.grant_type === 'client_credentials') return false;
152
- return Boolean(this.refresh_token);
153
- }
154
-
155
- /**
156
- * True when proactive refresh is on and the access token expires within
157
- * `refreshBeforeExpiryMs`. `accessTokenExpire` can be a Date, or an ISO
158
- * string from the credential store. An unknown or unreadable expiry
159
- * returns false: the 401 path handles that token.
160
- *
161
- * @returns {boolean}
162
- */
163
- _isTokenExpiringSoon() {
164
- if (!this.isProactiveRefreshEnabled()) return false;
165
- if (!this.accessTokenExpire) return false;
166
- const expiresAt = new Date(this.accessTokenExpire).getTime();
167
- if (Number.isNaN(expiresAt)) return false;
168
- return expiresAt - Date.now() <= this.refreshBeforeExpiryMs;
169
- }
170
-
171
- /** True when the URL, without its query, is `tokenUri`. */
172
- _isTokenRequest(url) {
173
- if (!this.tokenUri || typeof url !== 'string') return false;
174
- return url.split('?')[0] === String(this.tokenUri).split('?')[0];
175
119
  }
176
120
 
177
121
  /**
@@ -1,4 +1,6 @@
1
1
  const parsers = require('./parsers');
2
2
  const policy = require('./policy');
3
+ const pacer = require('./pacer');
4
+ const state = require('./state/rate-limit-state-repository-factory');
3
5
 
4
- module.exports = { ...parsers, ...policy };
6
+ module.exports = { ...parsers, ...policy, ...pacer, ...state };