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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/CLAUDE.md +166 -7
  2. package/core/CLAUDE.md +57 -1
  3. package/core/Worker.js +420 -9
  4. package/core/create-handler.js +20 -0
  5. package/core/index.js +6 -0
  6. package/core/invocation-deadline.js +91 -0
  7. package/core/invocation-scope.js +30 -24
  8. package/core/rate-limited-response.js +27 -0
  9. package/database/encryption/field-encryption-service.js +42 -0
  10. package/database/encryption/prisma-encryption-extension.js +6 -9
  11. package/encrypt/Cryptor.js +90 -38
  12. package/errors/fetch-error.js +10 -6
  13. package/errors/index.js +2 -0
  14. package/errors/rate-limit-error.js +46 -0
  15. package/generated/prisma-mongodb/edge.js +6 -2
  16. package/generated/prisma-mongodb/index.js +10 -2
  17. package/generated/prisma-mongodb/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  18. package/generated/prisma-mongodb/package.json +1 -1
  19. package/generated/prisma-mongodb/schema.prisma +1 -1
  20. package/generated/prisma-mongodb/wasm.js +6 -2
  21. package/generated/prisma-postgresql/edge.js +6 -2
  22. package/generated/prisma-postgresql/index.js +10 -2
  23. package/generated/prisma-postgresql/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  24. package/generated/prisma-postgresql/package.json +1 -1
  25. package/generated/prisma-postgresql/schema.prisma +1 -1
  26. package/generated/prisma-postgresql/wasm.js +6 -2
  27. package/handlers/app-handler-helpers.js +15 -0
  28. package/handlers/backend-utils.js +75 -1
  29. package/handlers/workers/integration-defined-workers.js +2 -0
  30. package/index.js +18 -0
  31. package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +2 -0
  32. package/integrations/repositories/integration-repository-documentdb.js +59 -10
  33. package/integrations/repositories/integration-repository-interface.js +50 -7
  34. package/integrations/repositories/integration-repository-mongo.js +88 -16
  35. package/integrations/repositories/integration-repository-postgres.js +89 -16
  36. package/integrations/repositories/message-item-shared.js +17 -0
  37. package/integrations/tests/doubles/prisma-message-row.js +24 -0
  38. package/integrations/tests/doubles/test-integration-repository.js +32 -2
  39. package/integrations/use-cases/clear-rate-limit-wait.js +28 -0
  40. package/integrations/use-cases/index.js +7 -1
  41. package/integrations/use-cases/record-rate-limit-message.js +104 -0
  42. package/integrations/use-cases/record-rate-limit-wait.js +36 -0
  43. package/integrations/use-cases/update-integration-messages.js +28 -9
  44. package/logs/serialize.js +15 -0
  45. package/modules/requester/oauth-2.js +8 -0
  46. package/modules/requester/rate-limit/index.js +4 -0
  47. package/modules/requester/rate-limit/parsers.js +249 -0
  48. package/modules/requester/rate-limit/policy.js +321 -0
  49. package/modules/requester/requester.js +187 -9
  50. package/package.json +7 -6
  51. package/prisma-mongodb/schema.prisma +1 -1
  52. package/prisma-postgresql/schema.prisma +1 -1
  53. package/queues/queue-deferral.js +80 -0
  54. package/queues/queue-delivery.js +1 -0
  55. package/queues/queuer-util.js +1 -1
  56. package/telemetry/otel-telemetry.js +76 -3
  57. package/telemetry/telemetry-config.js +16 -5
  58. package/telemetry/telemetry-runtime.js +14 -1
  59. package/types/core/consumer.fixture.ts +12 -0
  60. package/types/core/index.d.ts +84 -0
  61. package/types/errors/index.d.ts +47 -0
  62. package/types/integrations/index.d.ts +25 -4
  63. package/types/module-plugin/index.d.ts +45 -0
@@ -0,0 +1,321 @@
1
+ const {
2
+ BUILT_IN_PARSERS,
3
+ definedOnly,
4
+ hintFromRetryAt,
5
+ hintFromWait,
6
+ } = require('./parsers');
7
+
8
+ const DEFAULT_PARSERS = ['retryAfter', 'resetHeaders', 'ietf'];
9
+ const RESET_DELTA_UNITS = ['s', 'ms'];
10
+ const MIN_HINTED_WAIT_MS = 1_000;
11
+ const JITTER_MAX_MS = 1_000;
12
+ const JITTER_RATIO = 0.1;
13
+
14
+ const REASONS = new Set([
15
+ 'burst',
16
+ 'daily',
17
+ 'monthly',
18
+ 'concurrency',
19
+ 'unknown',
20
+ ]);
21
+ const CLASSIFY_SOURCES = new Set(['header', 'body', 'static']);
22
+ const SCOPES = new Set(['credential', 'entity', 'app']);
23
+
24
+ const normalizedPolicies = new WeakSet();
25
+ const policiesByClass = new WeakMap();
26
+
27
+ const isObject = (value) => value !== null && typeof value === 'object';
28
+ const isThenable = (value) => typeof value?.then === 'function';
29
+
30
+ function isPlainObject(value) {
31
+ if (!isObject(value) || Array.isArray(value)) return false;
32
+ const prototype = Object.getPrototypeOf(value);
33
+ return prototype === Object.prototype || prototype === null;
34
+ }
35
+
36
+ function readParsers(raw, owner) {
37
+ if (!Array.isArray(raw.parsers)) return [...DEFAULT_PARSERS];
38
+ for (const name of raw.parsers) {
39
+ if (!Object.hasOwn(BUILT_IN_PARSERS, name)) {
40
+ throw new TypeError(
41
+ `${owner}.rateLimit.parsers: unknown parser "${String(
42
+ name
43
+ )}"; known: ${Object.keys(BUILT_IN_PARSERS).join(', ')}`
44
+ );
45
+ }
46
+ }
47
+ return [...raw.parsers];
48
+ }
49
+
50
+ function readResetDeltaUnit(raw, owner) {
51
+ const unit = raw.resetDeltaUnit;
52
+ if (unit === undefined || RESET_DELTA_UNITS.includes(unit)) return unit;
53
+ throw new TypeError(
54
+ `${owner}.rateLimit.resetDeltaUnit: unknown unit "${String(
55
+ unit
56
+ )}"; known: ${RESET_DELTA_UNITS.join(', ')}`
57
+ );
58
+ }
59
+
60
+ function normalizePolicy(raw, owner) {
61
+ if (!isPlainObject(raw)) return undefined;
62
+
63
+ const policy = {
64
+ scope:
65
+ SCOPES.has(raw.scope) || typeof raw.scope === 'function'
66
+ ? raw.scope
67
+ : 'entity',
68
+ parsers: readParsers(raw, owner),
69
+ };
70
+ if (typeof raw.classify === 'function') {
71
+ policy.classify = (signal) => raw.classify(signal);
72
+ }
73
+ const resetDeltaUnit = readResetDeltaUnit(raw, owner);
74
+ if (resetDeltaUnit) policy.resetDeltaUnit = resetDeltaUnit;
75
+ if (Number.isFinite(raw.minRetryAfterMs) && raw.minRetryAfterMs >= 0) {
76
+ policy.minRetryAfterMs = raw.minRetryAfterMs;
77
+ }
78
+ if (Number.isInteger(raw.maxConcurrency) && raw.maxConcurrency > 0) {
79
+ policy.maxConcurrency = raw.maxConcurrency;
80
+ }
81
+ if (Array.isArray(raw.windows)) policy.windows = raw.windows;
82
+ if (isPlainObject(raw.userHints)) policy.userHints = raw.userHints;
83
+
84
+ normalizedPolicies.add(policy);
85
+ return policy;
86
+ }
87
+
88
+ function readRateLimitPolicy(ctor) {
89
+ if (typeof ctor !== 'function') return undefined;
90
+ if (policiesByClass.has(ctor)) return policiesByClass.get(ctor);
91
+ const policy = normalizePolicy(ctor.rateLimit, ctor.name || 'Requester');
92
+ policiesByClass.set(ctor, policy);
93
+ return policy;
94
+ }
95
+
96
+ function asPolicy(value) {
97
+ if (!isObject(value)) return undefined;
98
+ if (normalizedPolicies.has(value)) return value;
99
+ return normalizePolicy(value, 'policy');
100
+ }
101
+
102
+ function computeScopeKey(policy, requester) {
103
+ const label = requester?._telemetryModuleLabel?.() ?? 'unknown';
104
+ const scope = policy?.scope ?? 'entity';
105
+ const delegate = requester?.delegate;
106
+
107
+ if (scope === 'app') return `${label}:app`;
108
+ if (scope === 'entity') {
109
+ const id = delegate?.entity?.id;
110
+ return id === undefined || id === null
111
+ ? undefined
112
+ : `${label}:entity:${id}`;
113
+ }
114
+ if (scope === 'credential') {
115
+ const credential = delegate?.credential;
116
+ const id =
117
+ credential?.id ??
118
+ (typeof credential === 'string' ? credential : undefined);
119
+ return id === undefined || id === null
120
+ ? undefined
121
+ : `${label}:credential:${id}`;
122
+ }
123
+ if (typeof scope === 'function') {
124
+ try {
125
+ const value = scope(requester);
126
+ return typeof value === 'string' || Number.isFinite(value)
127
+ ? `${label}:custom:${value}`
128
+ : undefined;
129
+ } catch {
130
+ return undefined;
131
+ }
132
+ }
133
+ return undefined;
134
+ }
135
+
136
+ function toDate(value) {
137
+ if (value === undefined || value === null) return null;
138
+ const date = value instanceof Date ? value : new Date(value);
139
+ return Number.isNaN(date.getTime()) ? null : date;
140
+ }
141
+
142
+ function normalizeClassified(raw, now) {
143
+ if (!isObject(raw)) return null;
144
+ const retryAt = toDate(raw.retryAt);
145
+ if (!REASONS.has(raw.reason) && !Number.isFinite(raw.waitMs) && !retryAt) {
146
+ return null;
147
+ }
148
+
149
+ const extra = {
150
+ reason: REASONS.has(raw.reason) ? raw.reason : 'unknown',
151
+ policy: typeof raw.policy === 'string' ? raw.policy : undefined,
152
+ remaining: Number.isFinite(raw.remaining) ? raw.remaining : undefined,
153
+ source: CLASSIFY_SOURCES.has(raw.source) ? raw.source : 'body',
154
+ };
155
+
156
+ let hint = retryAt ? hintFromRetryAt(retryAt, now, extra) : null;
157
+ if (!hint && Number.isFinite(raw.waitMs)) {
158
+ hint = hintFromWait(raw.waitMs, now, extra);
159
+ }
160
+ return {
161
+ reason: extra.reason,
162
+ policy: extra.policy,
163
+ remaining: extra.remaining,
164
+ hint,
165
+ };
166
+ }
167
+
168
+ function runClassify(policy, signal, now, onClassifyError) {
169
+ if (typeof policy?.classify !== 'function') return null;
170
+ let raw;
171
+ try {
172
+ raw = policy.classify({
173
+ status: signal.status,
174
+ headers: signal.headers,
175
+ body: signal.body,
176
+ });
177
+ if (isThenable(raw)) {
178
+ Promise.resolve(raw).catch(() => {});
179
+ throw new TypeError(
180
+ 'classify() must return a hint or null, not a Promise'
181
+ );
182
+ }
183
+ } catch (error) {
184
+ if (!onClassifyError) throw error;
185
+ onClassifyError(error);
186
+ return null;
187
+ }
188
+ return normalizeClassified(raw, now);
189
+ }
190
+
191
+ function parsedHint(policy, headers, now) {
192
+ for (const name of policy?.parsers ?? DEFAULT_PARSERS) {
193
+ const hint = BUILT_IN_PARSERS[name](headers, {
194
+ now,
195
+ resetDeltaUnit: policy?.resetDeltaUnit,
196
+ });
197
+ if (hint) return hint;
198
+ }
199
+ return null;
200
+ }
201
+
202
+ function staticHint(policy, reason, now) {
203
+ const window = policy?.windows?.find(
204
+ (candidate) =>
205
+ candidate &&
206
+ candidate.name === reason &&
207
+ Number.isFinite(candidate.perMs) &&
208
+ candidate.perMs > 0
209
+ );
210
+ const waitMs = Math.max(window?.perMs ?? 0, policy?.minRetryAfterMs ?? 0);
211
+ return waitMs > 0 ? hintFromWait(waitMs, now, { source: 'static' }) : null;
212
+ }
213
+
214
+ function withClassified(hint, classified) {
215
+ return {
216
+ ...hint,
217
+ reason: classified?.reason ?? 'unknown',
218
+ ...definedOnly({
219
+ policy: classified?.policy ?? hint.policy,
220
+ remaining: classified?.remaining ?? hint.remaining,
221
+ }),
222
+ };
223
+ }
224
+
225
+ function resolveCandidates(policy, signal, { now, onClassifyError }) {
226
+ const classified = runClassify(policy, signal, now, onClassifyError);
227
+ if (signal.status !== 429 && !classified) return { hint: null, classified };
228
+ if (classified?.hint) return { hint: classified.hint, classified };
229
+
230
+ const parsed = parsedHint(policy, signal.headers, now);
231
+ if (parsed) return { hint: withClassified(parsed, classified), classified };
232
+
233
+ const fromPolicy = staticHint(policy, classified?.reason, now);
234
+ if (fromPolicy) {
235
+ return { hint: withClassified(fromPolicy, classified), classified };
236
+ }
237
+ return { hint: null, classified };
238
+ }
239
+
240
+ function classifyRateLimit(policy, signal, options = {}) {
241
+ const { now = Date.now(), onClassifyError } = options;
242
+ return resolveCandidates(asPolicy(policy), signal, { now, onClassifyError })
243
+ .hint;
244
+ }
245
+
246
+ function resolveRateLimitHint(policy, signal, options = {}) {
247
+ const {
248
+ attempt = 0,
249
+ backOff = [],
250
+ now = Date.now(),
251
+ onClassifyError,
252
+ } = options;
253
+ const { hint, classified } = resolveCandidates(asPolicy(policy), signal, {
254
+ now,
255
+ onClassifyError,
256
+ });
257
+ if (hint) return hint;
258
+ if (signal.status !== 429 && !classified) return null;
259
+ if (signal.status !== 429) {
260
+ return {
261
+ reason: classified.reason,
262
+ ...definedOnly({
263
+ policy: classified.policy,
264
+ remaining: classified.remaining,
265
+ }),
266
+ };
267
+ }
268
+
269
+ const waitMs =
270
+ attempt < backOff.length ? Number(backOff[attempt]) * 1000 || 0 : 0;
271
+ return {
272
+ waitMs,
273
+ retryAt: new Date(now + waitMs),
274
+ reason: classified?.reason ?? 'unknown',
275
+ ...definedOnly({
276
+ policy: classified?.policy,
277
+ remaining: classified?.remaining,
278
+ }),
279
+ source: 'backoff',
280
+ };
281
+ }
282
+
283
+ function computeWaitMs({ hint, policy, budgetMs, random = Math.random }) {
284
+ const base = Math.max(
285
+ hint.waitMs,
286
+ policy?.minRetryAfterMs ?? 0,
287
+ MIN_HINTED_WAIT_MS
288
+ );
289
+ if (base > budgetMs) return { waitMs: base, fits: false };
290
+
291
+ const jitter = Math.floor(
292
+ random() * Math.min(JITTER_MAX_MS, base * JITTER_RATIO)
293
+ );
294
+ return { waitMs: Math.min(base + jitter, budgetMs), fits: true };
295
+ }
296
+
297
+ function inProcessBudgetMs({
298
+ maxInProcessWaitMs,
299
+ requestTimeoutMs,
300
+ remainingMs = Infinity,
301
+ waitedMs = 0,
302
+ } = {}) {
303
+ const halfLeftMs = remainingMs / 2;
304
+ const sleepableMs =
305
+ requestTimeoutMs > 0
306
+ ? Math.max(remainingMs - requestTimeoutMs, halfLeftMs)
307
+ : halfLeftMs;
308
+ return Math.max(0, Math.min(maxInProcessWaitMs - waitedMs, sleepableMs));
309
+ }
310
+
311
+ module.exports = {
312
+ DEFAULT_PARSERS,
313
+ JITTER_MAX_MS,
314
+ MIN_HINTED_WAIT_MS,
315
+ classifyRateLimit,
316
+ computeScopeKey,
317
+ computeWaitMs,
318
+ inProcessBudgetMs,
319
+ readRateLimitPolicy,
320
+ resolveRateLimitHint,
321
+ };
@@ -1,13 +1,24 @@
1
1
  const fetch = require('node-fetch');
2
2
  const { AsyncLocalStorage } = require('async_hooks');
3
3
  const { Delegate } = require('../../core');
4
- const { FetchError } = require('../../errors');
4
+ const {
5
+ invocationMaxInProcessWaitMs,
6
+ remainingInvocationMs,
7
+ } = require('../../core/invocation-deadline');
8
+ const { FetchError, RateLimitError } = require('../../errors');
5
9
  const { get } = require('../../assertions');
6
10
  const { getTelemetry } = require('../../telemetry/telemetry-runtime');
7
11
  const { getLogger } = require('../../logs');
8
12
  const { redactUrl } = require('../../logs/redact');
9
13
  const { toSanitizedSurrogate } = require('../../logs/serialize');
10
14
  const { getLoggerScope } = require('../../logs/context');
15
+ const {
16
+ computeScopeKey,
17
+ computeWaitMs,
18
+ inProcessBudgetMs,
19
+ readRateLimitPolicy,
20
+ resolveRateLimitHint,
21
+ } = require('./rate-limit');
11
22
 
12
23
  const DEFAULT_REQUEST_TIMEOUT_MS = 60_000;
13
24
 
@@ -22,6 +33,10 @@ function sanitizedCause(err) {
22
33
  }
23
34
  const MAX_AUTH_RETRIES = 3;
24
35
 
36
+ // Hinted waits are bounded by time, but a provider that always answers with a
37
+ // short Retry-After would still keep the request in a long loop.
38
+ const MAX_HINTED_RETRIES = 10;
39
+
25
40
  // This context marks the async call chain that holds the refresh slot, and
26
41
  // names the requester that holds it. Token requests re-enter _rawRequest
27
42
  // through this._post. A 401 from inside that chain must fail fast: if it
@@ -34,6 +49,8 @@ class Requester extends Delegate {
34
49
  constructor(params) {
35
50
  super(params);
36
51
  this.backOff = get(params, 'backOff', [1, 3, 10, 30, 60, 180]);
52
+ this._rateLimitPolicy = readRateLimitPolicy(this.constructor);
53
+ this._random = params?.random ?? Math.random;
37
54
  this.isRefreshable = false;
38
55
  this.refreshCount = 0;
39
56
  this.authGraceRetryCount = 0;
@@ -211,9 +228,16 @@ class Requester extends Delegate {
211
228
  * @param {Object} options - Fetch options, as built by `_request`.
212
229
  * @param {number} attempt - 0-based count of retries already made for
213
230
  * this call. Indexes `this.backOff` for the next delay and is passed
214
- * back in on each recursive retry.
231
+ * back in on each recursive retry. A hinted retry leaves it unchanged.
232
+ * @param {{ waitedMs: number, retries: number }} hinted - The time slept
233
+ * and the retries made for rate-limit hints, for the whole call.
215
234
  */
216
- async _rawRequest(url, options, attempt = 0) {
235
+ async _rawRequest(
236
+ url,
237
+ options,
238
+ attempt = 0,
239
+ hinted = { waitedMs: 0, retries: 0 }
240
+ ) {
217
241
  let encodedUrl = encodeURI(url);
218
242
  if (options.query) {
219
243
  let queryBuild = '?';
@@ -279,7 +303,7 @@ class Requester extends Delegate {
279
303
  clearRequestTimer();
280
304
  const delay = this.backOff[attempt] * 1000;
281
305
  await new Promise((resolve) => setTimeout(resolve, delay));
282
- return this._rawRequest(url, options, attempt + 1);
306
+ return this._rawRequest(url, options, attempt + 1, hinted);
283
307
  }
284
308
  const fetchError = await FetchError.create({
285
309
  resource: encodedUrl,
@@ -298,15 +322,41 @@ class Requester extends Delegate {
298
322
 
299
323
  const { status } = response;
300
324
 
325
+ const throttle = await this._detectThrottle(
326
+ response,
327
+ status,
328
+ attempt
329
+ );
330
+ const hintedDelayMs = await this._hintedRetryDelayMs({
331
+ throttle,
332
+ status,
333
+ attempt,
334
+ hinted,
335
+ encodedUrl,
336
+ options,
337
+ response,
338
+ timeoutMs,
339
+ });
340
+ if (hintedDelayMs !== null) {
341
+ clearRequestTimer();
342
+ await new Promise((resolve) =>
343
+ setTimeout(resolve, hintedDelayMs)
344
+ );
345
+ return this._rawRequest(url, options, attempt, {
346
+ waitedMs: hinted.waitedMs + hintedDelayMs,
347
+ retries: hinted.retries + 1,
348
+ });
349
+ }
350
+
301
351
  // If the status is retriable and there are back off requests left, retry the request
302
352
  if (
303
- (status === 429 || status >= 500) &&
353
+ (throttle?.throttled || status >= 500) &&
304
354
  attempt < this.backOff.length
305
355
  ) {
306
356
  clearRequestTimer();
307
357
  const delay = this.backOff[attempt] * 1000;
308
358
  await new Promise((resolve) => setTimeout(resolve, delay));
309
- return this._rawRequest(url, options, attempt + 1);
359
+ return this._rawRequest(url, options, attempt + 1, hinted);
310
360
  }
311
361
 
312
362
  if (status === 401) {
@@ -327,7 +377,7 @@ class Requester extends Delegate {
327
377
  // This request did not try the current token. Retry with
328
378
  // it. Do not spend one more provider-side rotation.
329
379
  clearRequestTimer();
330
- return this._rawRequest(url, options, attempt + 1);
380
+ return this._rawRequest(url, options, attempt + 1, hinted);
331
381
  }
332
382
 
333
383
  if (!this.isRefreshable) {
@@ -344,7 +394,12 @@ class Requester extends Delegate {
344
394
  await new Promise((resolve) =>
345
395
  setTimeout(resolve, delay)
346
396
  );
347
- return this._rawRequest(url, options, attempt + 1);
397
+ return this._rawRequest(
398
+ url,
399
+ options,
400
+ attempt + 1,
401
+ hinted
402
+ );
348
403
  }
349
404
 
350
405
  throw await this._invalidateAuth(
@@ -377,7 +432,7 @@ class Requester extends Delegate {
377
432
  const refreshSucceeded = await this._refreshAuthOnce();
378
433
  if (refreshSucceeded) {
379
434
  clearRequestTimer();
380
- return this._rawRequest(url, options, attempt + 1);
435
+ return this._rawRequest(url, options, attempt + 1, hinted);
381
436
  }
382
437
 
383
438
  throw await this._invalidateAuth(encodedUrl, options, response);
@@ -392,6 +447,7 @@ class Requester extends Delegate {
392
447
  resource: encodedUrl,
393
448
  init: options,
394
449
  response,
450
+ responseBody: throttle?.responseBody,
395
451
  });
396
452
  throw this._maybeFlagTimeoutDuringBodyRead(
397
453
  fetchError,
@@ -421,6 +477,128 @@ class Requester extends Delegate {
421
477
  }
422
478
  }
423
479
 
480
+ async _hintedRetryDelayMs({
481
+ throttle,
482
+ status,
483
+ attempt,
484
+ hinted,
485
+ encodedUrl,
486
+ options,
487
+ response,
488
+ timeoutMs,
489
+ }) {
490
+ if (!throttle?.throttled || throttle.hint.source === 'backoff') {
491
+ return null;
492
+ }
493
+ const { hint } = throttle;
494
+ const untimed = hint.waitMs === undefined;
495
+ const mayWait =
496
+ this.backOff.length > 0 && hinted.retries < MAX_HINTED_RETRIES;
497
+ const budgetMs = mayWait
498
+ ? inProcessBudgetMs({
499
+ maxInProcessWaitMs: invocationMaxInProcessWaitMs(),
500
+ requestTimeoutMs: this.requestTimeoutMs,
501
+ remainingMs: remainingInvocationMs(),
502
+ waitedMs: hinted.waitedMs,
503
+ })
504
+ : 0;
505
+ const { waitMs, fits } = untimed
506
+ ? { waitMs: undefined, fits: false }
507
+ : computeWaitMs({
508
+ hint,
509
+ policy: this._rateLimitPolicy,
510
+ budgetMs,
511
+ random: this._random,
512
+ });
513
+ if (fits) {
514
+ this._logRateLimited({
515
+ status,
516
+ hint,
517
+ waitMs,
518
+ attempt,
519
+ waitedMs: hinted.waitedMs,
520
+ });
521
+ return waitMs;
522
+ }
523
+
524
+ this._logRequestFailed(encodedUrl, options, status);
525
+ const rateLimitError = await RateLimitError.create({
526
+ resource: encodedUrl,
527
+ init: options,
528
+ response,
529
+ responseBody: throttle.responseBody,
530
+ hint,
531
+ waitMs,
532
+ module: this._telemetryModuleLabel(),
533
+ scopeKey: computeScopeKey(this._rateLimitPolicy, this),
534
+ });
535
+ throw this._maybeFlagTimeoutDuringBodyRead(rateLimitError, timeoutMs);
536
+ }
537
+
538
+ async _detectThrottle(response, status, attempt) {
539
+ const policy = this._rateLimitPolicy;
540
+ const canClassify =
541
+ typeof policy?.classify === 'function' &&
542
+ status >= 400 &&
543
+ status !== 401;
544
+ if (status !== 429 && !canClassify) return null;
545
+
546
+ let responseBody;
547
+ let body;
548
+ if (canClassify) {
549
+ ({ text: responseBody, json: body } =
550
+ await this._readBodyForClassify(response));
551
+ }
552
+
553
+ const hint = resolveRateLimitHint(
554
+ policy,
555
+ { status, headers: response.headers, body },
556
+ {
557
+ attempt,
558
+ backOff: this.backOff,
559
+ now: Date.now(),
560
+ onClassifyError: (error) =>
561
+ this._logClassifyFailed(status, error),
562
+ }
563
+ );
564
+ return { throttled: Boolean(hint), hint, responseBody };
565
+ }
566
+
567
+ async _readBodyForClassify(response) {
568
+ if (response.bodyUsed || typeof response.text !== 'function') {
569
+ return {};
570
+ }
571
+ const text = await response.text();
572
+ try {
573
+ return { text, json: JSON.parse(text) };
574
+ } catch {
575
+ return { text };
576
+ }
577
+ }
578
+
579
+ _logRateLimited({ status, hint, waitMs, attempt, waitedMs }) {
580
+ const logger = this.logger;
581
+ logger.trace('Rate limited', {
582
+ eventName: `${logger.name}.rate_limited`,
583
+ statusCode: status,
584
+ waitMs,
585
+ retryAt: new Date(Date.now() + waitMs).toISOString(),
586
+ reason: hint.reason,
587
+ hintSource: hint.source,
588
+ attempt,
589
+ waitedMs,
590
+ });
591
+ }
592
+
593
+ _logClassifyFailed(status, error) {
594
+ const logger = this.logger;
595
+ logger.warn('Rate limit classifier failed', {
596
+ eventName: `${logger.name}.rate_limit_classify_failed`,
597
+ statusCode: status,
598
+ error,
599
+ });
600
+ }
601
+
424
602
  _logRequestFailed(encodedUrl, options, status) {
425
603
  const logger = this.logger;
426
604
  if (!logger.isLevelEnabled('DEBUG')) return;
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-next.127",
4
+ "version": "2.0.0-next.129",
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-next.127",
14
+ "@friggframework/schemas": "2.0.0-next.129",
15
15
  "@hapi/boom": "^10.0.1",
16
16
  "@opentelemetry/api": "^1.9.1",
17
17
  "@opentelemetry/context-async-hooks": "^2.9.0",
@@ -49,12 +49,13 @@
49
49
  }
50
50
  },
51
51
  "devDependencies": {
52
- "@friggframework/eslint-config": "2.0.0-next.127",
53
- "@friggframework/prettier-config": "2.0.0-next.127",
54
- "@friggframework/test": "2.0.0-next.127",
52
+ "@friggframework/eslint-config": "2.0.0-next.129",
53
+ "@friggframework/prettier-config": "2.0.0-next.129",
54
+ "@friggframework/test": "2.0.0-next.129",
55
55
  "@prisma/client": "^6.19.3",
56
56
  "@types/lodash": "4.17.15",
57
57
  "@typescript-eslint/eslint-plugin": "^8.0.0",
58
+ "aws-sdk-client-mock": "^4.1.0",
58
59
  "chai": "^4.3.6",
59
60
  "eslint": "^8.22.0",
60
61
  "eslint-plugin-import": "^2.29.1",
@@ -92,5 +93,5 @@
92
93
  "publishConfig": {
93
94
  "access": "public"
94
95
  },
95
- "gitHead": "e6796e46e531d2eb18d801ae9ace8cebdc93be03"
96
+ "gitHead": "4326b2498dcb1627e43fceada462b384b722da52"
96
97
  }
@@ -5,7 +5,7 @@
5
5
  generator client {
6
6
  provider = "prisma-client-js"
7
7
  output = "../generated/prisma-mongodb"
8
- binaryTargets = ["native", "rhel-openssl-3.0.x"] // native for local dev, rhel for Lambda deployment
8
+ binaryTargets = ["native", "rhel-openssl-3.0.x", "linux-arm64-openssl-3.0.x"] // native for local dev, rhel for x86_64 Lambda, linux-arm64 for arm64 Lambda
9
9
  // Library engine (default since Prisma 3.x): Rust query engine loads as a
10
10
  // Node-API addon inside the same process. The binary engine forks a child
11
11
  // query-engine subprocess and communicates over a local HTTP/IPC pipe with
@@ -5,7 +5,7 @@
5
5
  generator client {
6
6
  provider = "prisma-client-js"
7
7
  output = "../generated/prisma-postgresql"
8
- binaryTargets = ["native", "rhel-openssl-3.0.x"] // native for local dev, rhel for Lambda deployment
8
+ binaryTargets = ["native", "rhel-openssl-3.0.x", "linux-arm64-openssl-3.0.x"] // native for local dev, rhel for x86_64 Lambda, linux-arm64 for arm64 Lambda
9
9
  // Library engine (default since Prisma 3.x): Rust query engine loads as a
10
10
  // Node-API addon inside the same process. The binary engine forks a child
11
11
  // query-engine subprocess and communicates over a local HTTP/IPC pipe with