@friggframework/core 2.0.0--canary.743.265a5cd.0 → 2.0.0--canary.744.95fdcc7.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 +0 -7
- package/core/Worker.js +5 -43
- package/index.js +0 -8
- package/modules/repositories/module-repository-documentdb.js +4 -29
- package/modules/repositories/module-repository-mongo.js +11 -55
- package/modules/repositories/module-repository-postgres.js +12 -41
- package/modules/requester/oauth-2.js +37 -0
- package/modules/requester/rate-limit/index.js +1 -3
- package/modules/requester/rate-limit/policy.js +0 -26
- package/modules/requester/requester.js +66 -180
- package/package.json +6 -6
- package/queues/queue-deferral.js +3 -78
- package/types/module-plugin/index.d.ts +4 -8
- package/modules/repositories/entity-data.js +0 -71
- package/modules/requester/rate-limit/pacer.js +0 -584
- package/modules/requester/rate-limit/state/rate-limit-state-repository-factory.js +0 -42
- package/modules/requester/rate-limit/state/rate-limit-state-repository-interface.js +0 -75
- package/modules/requester/rate-limit/state/rate-limit-state-repository-memory.js +0 -64
- package/modules/requester/rate-limit/state/rate-limit-state-repository-mongo.js +0 -168
- package/modules/requester/rate-limit/state/rate-limit-state-repository-postgres.js +0 -111
|
@@ -15,16 +15,10 @@ const { getLoggerScope } = require('../../logs/context');
|
|
|
15
15
|
const {
|
|
16
16
|
computeScopeKey,
|
|
17
17
|
computeWaitMs,
|
|
18
|
-
scopeBlockMs,
|
|
19
18
|
inProcessBudgetMs,
|
|
20
19
|
readRateLimitPolicy,
|
|
21
20
|
resolveRateLimitHint,
|
|
22
21
|
} = require('./rate-limit');
|
|
23
|
-
const {
|
|
24
|
-
getRateLimitPacer,
|
|
25
|
-
maxPacingWaitMs,
|
|
26
|
-
pacingEnabled,
|
|
27
|
-
} = require('./rate-limit/pacer');
|
|
28
22
|
|
|
29
23
|
const DEFAULT_REQUEST_TIMEOUT_MS = 60_000;
|
|
30
24
|
|
|
@@ -39,11 +33,14 @@ function sanitizedCause(err) {
|
|
|
39
33
|
}
|
|
40
34
|
const MAX_AUTH_RETRIES = 3;
|
|
41
35
|
|
|
36
|
+
// After a proactive refresh that failed, the requester waits this long
|
|
37
|
+
// before it tries again. Without it, every request would call the token
|
|
38
|
+
// endpoint while the endpoint is down.
|
|
39
|
+
const PROACTIVE_REFRESH_COOLDOWN_MS = 60_000;
|
|
40
|
+
|
|
42
41
|
// Hinted waits are bounded by time, but a provider that always answers with a
|
|
43
42
|
// short Retry-After would still keep the request in a long loop.
|
|
44
43
|
const MAX_HINTED_RETRIES = 10;
|
|
45
|
-
// A provider hint shorter than this still blocks the key this long.
|
|
46
|
-
const MIN_SCOPE_BLOCK_MS = 1_000;
|
|
47
44
|
|
|
48
45
|
// This context marks the async call chain that holds the refresh slot, and
|
|
49
46
|
// names the requester that holds it. Token requests re-enter _rawRequest
|
|
@@ -67,6 +64,8 @@ class Requester extends Delegate {
|
|
|
67
64
|
// This counter increases when the tokens change. A stale 401 (the
|
|
68
65
|
// token changed already) then retries and does not refresh again.
|
|
69
66
|
this._authGeneration = 0;
|
|
67
|
+
// No proactive refresh before this time. See _refreshIfExpiringSoon().
|
|
68
|
+
this._proactiveRefreshNotBefore = 0;
|
|
70
69
|
this.DLGT_INVALID_AUTH = 'INVALID_AUTH';
|
|
71
70
|
this.delegateTypes.push(this.DLGT_INVALID_AUTH);
|
|
72
71
|
this.agent = get(params, 'agent', null);
|
|
@@ -216,18 +215,8 @@ class Requester extends Delegate {
|
|
|
216
215
|
return result;
|
|
217
216
|
} catch (err) {
|
|
218
217
|
const code = err?.status ?? err?.statusCode;
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
? 'paced'
|
|
222
|
-
: code
|
|
223
|
-
? String(code)
|
|
224
|
-
: 'error';
|
|
225
|
-
if (
|
|
226
|
-
span &&
|
|
227
|
-
typeof span.setAttribute === 'function' &&
|
|
228
|
-
code &&
|
|
229
|
-
!err?.preempted
|
|
230
|
-
) {
|
|
218
|
+
const status = code ? String(code) : 'error';
|
|
219
|
+
if (span && typeof span.setAttribute === 'function' && code) {
|
|
231
220
|
span.setAttribute('http.response.status_code', code);
|
|
232
221
|
}
|
|
233
222
|
telemetry.count(
|
|
@@ -267,7 +256,9 @@ class Requester extends Delegate {
|
|
|
267
256
|
encodedUrl += queryBuild.slice(0, -1);
|
|
268
257
|
}
|
|
269
258
|
|
|
270
|
-
|
|
259
|
+
if (attempt === 0) {
|
|
260
|
+
await this._refreshIfExpiringSoon();
|
|
261
|
+
}
|
|
271
262
|
|
|
272
263
|
options.headers = await this.addAuthHeaders(options.headers);
|
|
273
264
|
|
|
@@ -342,8 +333,6 @@ class Requester extends Delegate {
|
|
|
342
333
|
|
|
343
334
|
const { status } = response;
|
|
344
335
|
|
|
345
|
-
await this._observeRateLimit(response);
|
|
346
|
-
|
|
347
336
|
const throttle = await this._detectThrottle(
|
|
348
337
|
response,
|
|
349
338
|
status,
|
|
@@ -377,9 +366,6 @@ class Requester extends Delegate {
|
|
|
377
366
|
) {
|
|
378
367
|
clearRequestTimer();
|
|
379
368
|
const delay = this.backOff[attempt] * 1000;
|
|
380
|
-
if (throttle?.throttled) {
|
|
381
|
-
await this._blockScope(Date.now() + delay);
|
|
382
|
-
}
|
|
383
369
|
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
384
370
|
return this._rawRequest(url, options, attempt + 1, hinted);
|
|
385
371
|
}
|
|
@@ -535,17 +521,6 @@ class Requester extends Delegate {
|
|
|
535
521
|
budgetMs,
|
|
536
522
|
random: this._random,
|
|
537
523
|
});
|
|
538
|
-
// Block the key for the provider's time only. minRetryAfterMs and
|
|
539
|
-
// the jitter delay this message, not every other call on the key.
|
|
540
|
-
if (!untimed) {
|
|
541
|
-
await this._blockScope(
|
|
542
|
-
Date.now() +
|
|
543
|
-
Math.max(
|
|
544
|
-
scopeBlockMs(hint, this._rateLimitPolicy),
|
|
545
|
-
MIN_SCOPE_BLOCK_MS
|
|
546
|
-
)
|
|
547
|
-
);
|
|
548
|
-
}
|
|
549
524
|
if (fits) {
|
|
550
525
|
this._logRateLimited({
|
|
551
526
|
status,
|
|
@@ -558,161 +533,19 @@ class Requester extends Delegate {
|
|
|
558
533
|
}
|
|
559
534
|
|
|
560
535
|
this._logRequestFailed(encodedUrl, options, status);
|
|
561
|
-
const retryWaitMs = untimed
|
|
562
|
-
? undefined
|
|
563
|
-
: await this._spreadRetryWaitMs(waitMs);
|
|
564
536
|
const rateLimitError = await RateLimitError.create({
|
|
565
537
|
resource: encodedUrl,
|
|
566
538
|
init: options,
|
|
567
539
|
response,
|
|
568
540
|
responseBody: throttle.responseBody,
|
|
569
541
|
hint,
|
|
570
|
-
waitMs
|
|
542
|
+
waitMs,
|
|
571
543
|
module: this._telemetryModuleLabel(),
|
|
572
544
|
scopeKey: computeScopeKey(this._rateLimitPolicy, this),
|
|
573
545
|
});
|
|
574
|
-
if (retryWaitMs !== undefined && this._pacingScopeKey()) {
|
|
575
|
-
rateLimitError.paced = true;
|
|
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;
|
|
580
546
|
throw this._maybeFlagTimeoutDuringBodyRead(rateLimitError, timeoutMs);
|
|
581
547
|
}
|
|
582
548
|
|
|
583
|
-
// ADR-049 section 6: pacing. Every requester in the process shares one
|
|
584
|
-
// pacer, so a new requester for each queue message still sees the block.
|
|
585
|
-
_pacingScopeKey() {
|
|
586
|
-
const policy = this._rateLimitPolicy;
|
|
587
|
-
if (!policy || policy.pacing === false || !pacingEnabled()) {
|
|
588
|
-
return undefined;
|
|
589
|
-
}
|
|
590
|
-
return computeScopeKey(policy, this);
|
|
591
|
-
}
|
|
592
|
-
|
|
593
|
-
// Shared state (`shared: true`) lives on the Entity row of the module.
|
|
594
|
-
_pacingEntityId() {
|
|
595
|
-
return this.delegate?.entity?.id ?? undefined;
|
|
596
|
-
}
|
|
597
|
-
|
|
598
|
-
async _paceRequest(encodedUrl, options, hinted) {
|
|
599
|
-
// A token request inside a refresh must not wait for the key, or
|
|
600
|
-
// defer: the refresh would fail and the credential would be lost.
|
|
601
|
-
if (this._isInsideRefreshFlow()) return;
|
|
602
|
-
const scopeKey = this._pacingScopeKey();
|
|
603
|
-
if (!scopeKey) return;
|
|
604
|
-
|
|
605
|
-
const policy = this._rateLimitPolicy;
|
|
606
|
-
const pacer = getRateLimitPacer();
|
|
607
|
-
// A short pacing sleep costs less than a deferral, so it may pass the
|
|
608
|
-
// caller's hinted-wait budget (0 in a queue worker), up to a cap.
|
|
609
|
-
const budgetMs = inProcessBudgetMs({
|
|
610
|
-
maxInProcessWaitMs: Math.max(
|
|
611
|
-
invocationMaxInProcessWaitMs(),
|
|
612
|
-
maxPacingWaitMs()
|
|
613
|
-
),
|
|
614
|
-
requestTimeoutMs: this.requestTimeoutMs,
|
|
615
|
-
remainingMs: remainingInvocationMs(),
|
|
616
|
-
waitedMs: hinted.waitedMs,
|
|
617
|
-
});
|
|
618
|
-
const entityId = this._pacingEntityId();
|
|
619
|
-
const gate = await pacer.acquire({
|
|
620
|
-
scopeKey,
|
|
621
|
-
entityId,
|
|
622
|
-
policy,
|
|
623
|
-
budgetMs,
|
|
624
|
-
});
|
|
625
|
-
if (gate.granted) {
|
|
626
|
-
if (gate.waitMs > 0) {
|
|
627
|
-
this._logPaced(gate, scopeKey);
|
|
628
|
-
hinted.waitedMs += gate.waitMs;
|
|
629
|
-
await new Promise((resolve) =>
|
|
630
|
-
setTimeout(resolve, gate.waitMs)
|
|
631
|
-
);
|
|
632
|
-
}
|
|
633
|
-
return;
|
|
634
|
-
}
|
|
635
|
-
|
|
636
|
-
const now = Date.now();
|
|
637
|
-
const retryAt = await pacer.reserveRetry({
|
|
638
|
-
scopeKey,
|
|
639
|
-
entityId,
|
|
640
|
-
policy,
|
|
641
|
-
notBefore: new Date(now + gate.waitMs),
|
|
642
|
-
waitMs: gate.waitMs,
|
|
643
|
-
});
|
|
644
|
-
const error = new RateLimitError({
|
|
645
|
-
resource: encodedUrl,
|
|
646
|
-
init: options,
|
|
647
|
-
hint: { reason: 'burst', source: 'pacer' },
|
|
648
|
-
waitMs: Math.max(0, retryAt.getTime() - now),
|
|
649
|
-
module: this._telemetryModuleLabel(),
|
|
650
|
-
scopeKey,
|
|
651
|
-
now,
|
|
652
|
-
});
|
|
653
|
-
error.statusCode = 429;
|
|
654
|
-
error.preempted = true;
|
|
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);
|
|
658
|
-
error.message = `${error.message} paced: not sent`;
|
|
659
|
-
this._logPaced(gate, scopeKey, error);
|
|
660
|
-
throw error;
|
|
661
|
-
}
|
|
662
|
-
|
|
663
|
-
async _observeRateLimit(response) {
|
|
664
|
-
// A token endpoint can count on its own limit: its headers must not
|
|
665
|
-
// block the API key.
|
|
666
|
-
if (this._isInsideRefreshFlow()) return;
|
|
667
|
-
const scopeKey = this._pacingScopeKey();
|
|
668
|
-
if (!scopeKey || !response?.headers) return;
|
|
669
|
-
await getRateLimitPacer().observe({
|
|
670
|
-
scopeKey,
|
|
671
|
-
entityId: this._pacingEntityId(),
|
|
672
|
-
policy: this._rateLimitPolicy,
|
|
673
|
-
headers: response.headers,
|
|
674
|
-
status: response.status,
|
|
675
|
-
});
|
|
676
|
-
}
|
|
677
|
-
|
|
678
|
-
async _blockScope(untilMs) {
|
|
679
|
-
if (this._isInsideRefreshFlow()) return;
|
|
680
|
-
const scopeKey = this._pacingScopeKey();
|
|
681
|
-
if (!scopeKey || !Number.isFinite(untilMs)) return;
|
|
682
|
-
await getRateLimitPacer().block({
|
|
683
|
-
scopeKey,
|
|
684
|
-
entityId: this._pacingEntityId(),
|
|
685
|
-
policy: this._rateLimitPolicy,
|
|
686
|
-
until: new Date(untilMs),
|
|
687
|
-
});
|
|
688
|
-
}
|
|
689
|
-
|
|
690
|
-
// The wait of a thrown RateLimitError, spread across the scope's backlog.
|
|
691
|
-
async _spreadRetryWaitMs(waitMs) {
|
|
692
|
-
const scopeKey = this._pacingScopeKey();
|
|
693
|
-
if (!scopeKey) return waitMs;
|
|
694
|
-
const now = Date.now();
|
|
695
|
-
const retryAt = await getRateLimitPacer().reserveRetry({
|
|
696
|
-
scopeKey,
|
|
697
|
-
entityId: this._pacingEntityId(),
|
|
698
|
-
policy: this._rateLimitPolicy,
|
|
699
|
-
notBefore: new Date(now + waitMs),
|
|
700
|
-
waitMs,
|
|
701
|
-
});
|
|
702
|
-
return Math.max(waitMs, retryAt.getTime() - now);
|
|
703
|
-
}
|
|
704
|
-
|
|
705
|
-
_logPaced(gate, scopeKey, error) {
|
|
706
|
-
const logger = this.logger;
|
|
707
|
-
logger.trace(error ? 'Request deferred by pacer' : 'Request paced', {
|
|
708
|
-
eventName: `${logger.name}.${error ? 'rate_limit_deferred' : 'rate_limit_paced'}`,
|
|
709
|
-
waitMs: gate.waitMs,
|
|
710
|
-
reason: gate.reason,
|
|
711
|
-
scopeKey,
|
|
712
|
-
...(error && { retryAt: error.retryAt?.toISOString() }),
|
|
713
|
-
});
|
|
714
|
-
}
|
|
715
|
-
|
|
716
549
|
async _detectThrottle(response, status, attempt) {
|
|
717
550
|
const policy = this._rateLimitPolicy;
|
|
718
551
|
const canClassify =
|
|
@@ -948,6 +781,59 @@ class Requester extends Delegate {
|
|
|
948
781
|
return false;
|
|
949
782
|
}
|
|
950
783
|
|
|
784
|
+
/**
|
|
785
|
+
* Refreshes the token before a request when _isTokenExpiringSoon()
|
|
786
|
+
* says so. A request with a token that expired would get a 401, and
|
|
787
|
+
* then a refresh and a retry: one failed call each time.
|
|
788
|
+
*
|
|
789
|
+
* A failure here does not fail the request. The request goes out with
|
|
790
|
+
* the current token, and the 401 path stays the fallback. After a
|
|
791
|
+
* failure, no proactive refresh runs for PROACTIVE_REFRESH_COOLDOWN_MS.
|
|
792
|
+
* Concurrent callers share one refresh through _refreshAuthOnce().
|
|
793
|
+
*/
|
|
794
|
+
async _refreshIfExpiringSoon() {
|
|
795
|
+
if (this._isInsideRefreshFlow()) return;
|
|
796
|
+
if (Date.now() < this._proactiveRefreshNotBefore) return;
|
|
797
|
+
if (!this._isTokenExpiringSoon()) return;
|
|
798
|
+
|
|
799
|
+
const tokenBefore = this.access_token;
|
|
800
|
+
let refreshed = false;
|
|
801
|
+
try {
|
|
802
|
+
refreshed = await this._refreshAuthOnce();
|
|
803
|
+
} catch (error) {
|
|
804
|
+
this.logger.warn(
|
|
805
|
+
'Proactive token refresh failed, sending the request with the current token',
|
|
806
|
+
{
|
|
807
|
+
eventName: `${this.logger.name}.proactive_refresh_failed`,
|
|
808
|
+
statusCode: error?.statusCode,
|
|
809
|
+
isRateLimited: Boolean(error?.isRateLimited),
|
|
810
|
+
}
|
|
811
|
+
);
|
|
812
|
+
}
|
|
813
|
+
if (refreshed) return;
|
|
814
|
+
|
|
815
|
+
this._proactiveRefreshNotBefore =
|
|
816
|
+
Date.now() + PROACTIVE_REFRESH_COOLDOWN_MS;
|
|
817
|
+
// A failed refresh can clear the token in memory before the token
|
|
818
|
+
// request. The old token can still be valid for a few minutes.
|
|
819
|
+
if (!this.access_token && tokenBefore) {
|
|
820
|
+
this.access_token = tokenBefore;
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
/**
|
|
825
|
+
* Hook for requesters that know when their token expires. Return true
|
|
826
|
+
* to refresh before the next request. Off by default, because a
|
|
827
|
+
* provider with single-use refresh tokens must not spend one on a token
|
|
828
|
+
* that still works. OAuth2Requester turns it on with
|
|
829
|
+
* `refreshBeforeExpiryMs`.
|
|
830
|
+
*
|
|
831
|
+
* @returns {boolean}
|
|
832
|
+
*/
|
|
833
|
+
_isTokenExpiringSoon() {
|
|
834
|
+
return false;
|
|
835
|
+
}
|
|
836
|
+
|
|
951
837
|
/** True while this instance runs its own refresh. */
|
|
952
838
|
_isInsideRefreshFlow() {
|
|
953
839
|
return refreshContext.getStore()?.requester === this;
|
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.
|
|
4
|
+
"version": "2.0.0--canary.744.95fdcc7.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.
|
|
14
|
+
"@friggframework/schemas": "2.0.0--canary.744.95fdcc7.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.
|
|
53
|
-
"@friggframework/prettier-config": "2.0.0--canary.
|
|
54
|
-
"@friggframework/test": "2.0.0--canary.
|
|
52
|
+
"@friggframework/eslint-config": "2.0.0--canary.744.95fdcc7.0",
|
|
53
|
+
"@friggframework/prettier-config": "2.0.0--canary.744.95fdcc7.0",
|
|
54
|
+
"@friggframework/test": "2.0.0--canary.744.95fdcc7.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": "
|
|
96
|
+
"gitHead": "95fdcc7479f248f3ba515af2d6559e8f29532546"
|
|
97
97
|
}
|
package/queues/queue-deferral.js
CHANGED
|
@@ -14,17 +14,6 @@ const MAX_DEFERRED_VISIBILITY_SECONDS =
|
|
|
14
14
|
const MAX_DEFERRALS_ENV = 'FRIGG_QUEUE_MAX_DEFERRALS';
|
|
15
15
|
const MAX_DEFERRED_MS_ENV = 'FRIGG_QUEUE_MAX_DEFERRED_MS';
|
|
16
16
|
const RATE_LIMIT_PROBE_MS_ENV = 'FRIGG_QUEUE_RATE_LIMIT_PROBE_MS';
|
|
17
|
-
// Full jitter on a deferral that the requester did not already spread: the
|
|
18
|
-
// retry lands at a random point in [retryAt, retryAt + min(wait, max)]. One
|
|
19
|
-
// shared retryAt for a whole backlog made every message come back in the same
|
|
20
|
-
// second (a thundering herd).
|
|
21
|
-
const DEFERRAL_JITTER_MAX_MS = 5 * 60 * 1000;
|
|
22
|
-
const DEFERRAL_JITTER_MAX_MS_ENV = 'FRIGG_QUEUE_DEFERRAL_JITTER_MAX_MS';
|
|
23
|
-
// A pacer deferral (no call sent) does not use the deferral count, up to this
|
|
24
|
-
// number. Past it, each one counts: a key that never gets free must not hold
|
|
25
|
-
// a message for the full time cap with no end.
|
|
26
|
-
const MAX_PACED_DEFERRALS = 100;
|
|
27
|
-
const MAX_PACED_DEFERRALS_ENV = 'FRIGG_QUEUE_MAX_PACED_DEFERRALS';
|
|
28
17
|
|
|
29
18
|
const readDeferralLimits = (env = process.env) => ({
|
|
30
19
|
maxDeferrals: toPositiveInteger(env[MAX_DEFERRALS_ENV]) ?? MAX_DEFERRALS,
|
|
@@ -32,43 +21,8 @@ const readDeferralLimits = (env = process.env) => ({
|
|
|
32
21
|
toPositiveInteger(env[MAX_DEFERRED_MS_ENV]) ?? MAX_DEFERRED_MS,
|
|
33
22
|
probeMs:
|
|
34
23
|
toPositiveInteger(env[RATE_LIMIT_PROBE_MS_ENV]) ?? RATE_LIMIT_PROBE_MS,
|
|
35
|
-
jitterMaxMs: readJitterMaxMs(env),
|
|
36
|
-
maxPacedDeferrals:
|
|
37
|
-
toPositiveInteger(env[MAX_PACED_DEFERRALS_ENV]) ?? MAX_PACED_DEFERRALS,
|
|
38
24
|
});
|
|
39
25
|
|
|
40
|
-
function readJitterMaxMs(env) {
|
|
41
|
-
const raw = env[DEFERRAL_JITTER_MAX_MS_ENV];
|
|
42
|
-
if (raw === '0') return 0;
|
|
43
|
-
return toPositiveInteger(raw) ?? DEFERRAL_JITTER_MAX_MS;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/**
|
|
47
|
-
* @param {Date} retryAt the earliest time the provider allows
|
|
48
|
-
* @param {number} waitMs the wait until retryAt
|
|
49
|
-
* @param {Object} limits
|
|
50
|
-
* @param {number} limits.jitterMaxMs
|
|
51
|
-
* @param {number} [limits.now] when retryAt is in the SQS delay range from
|
|
52
|
-
* `now`, the result stays in it: the jitter must not move a short wait to
|
|
53
|
-
* the scheduler or to the visibility timeout.
|
|
54
|
-
* @returns {Date} retryAt plus a random part of min(waitMs, jitterMaxMs)
|
|
55
|
-
*/
|
|
56
|
-
const jitteredRetryAt = (
|
|
57
|
-
retryAt,
|
|
58
|
-
waitMs,
|
|
59
|
-
{ jitterMaxMs, now },
|
|
60
|
-
random = Math.random
|
|
61
|
-
) => {
|
|
62
|
-
let spread = Math.min(Math.max(0, waitMs), jitterMaxMs);
|
|
63
|
-
if (Number.isFinite(now)) {
|
|
64
|
-
const delayEnd = now + MAX_DELAY_SECONDS * 1000;
|
|
65
|
-
if (retryAt.getTime() <= delayEnd) {
|
|
66
|
-
spread = Math.min(spread, delayEnd - retryAt.getTime());
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
return new Date(retryAt.getTime() + Math.floor(random() * spread));
|
|
70
|
-
};
|
|
71
|
-
|
|
72
26
|
const readDeferral = (body) => {
|
|
73
27
|
const frigg = body?._frigg;
|
|
74
28
|
const deferrals =
|
|
@@ -80,41 +34,17 @@ const readDeferral = (body) => {
|
|
|
80
34
|
!Number.isNaN(Date.parse(frigg.firstDeferredAt))
|
|
81
35
|
? frigg.firstDeferredAt
|
|
82
36
|
: undefined;
|
|
83
|
-
const pacedDeferrals =
|
|
84
|
-
Number.isInteger(frigg?.pacedDeferrals) && frigg.pacedDeferrals > 0
|
|
85
|
-
? frigg.pacedDeferrals
|
|
86
|
-
: undefined;
|
|
87
37
|
const deferralId =
|
|
88
38
|
typeof frigg?.deferralId === 'string' && frigg.deferralId !== ''
|
|
89
39
|
? frigg.deferralId
|
|
90
40
|
: undefined;
|
|
91
|
-
return {
|
|
92
|
-
deferrals,
|
|
93
|
-
firstDeferredAt,
|
|
94
|
-
deferralId,
|
|
95
|
-
...(pacedDeferrals && { pacedDeferrals }),
|
|
96
|
-
};
|
|
41
|
+
return { deferrals, firstDeferredAt, deferralId };
|
|
97
42
|
};
|
|
98
43
|
|
|
99
|
-
|
|
100
|
-
* A deferral by the pacer (`preempted`: no call was sent) does not count
|
|
101
|
-
* against maxDeferrals. The key was known to be busy, so the message did not
|
|
102
|
-
* fail. The time cap still applies to it. After `maxPacedDeferrals` of them,
|
|
103
|
-
* a pacer deferral counts as a normal one.
|
|
104
|
-
*/
|
|
105
|
-
const nextDeferral = (
|
|
106
|
-
body,
|
|
107
|
-
now = Date.now(),
|
|
108
|
-
messageId,
|
|
109
|
-
{ preempted = false, maxPacedDeferrals = MAX_PACED_DEFERRALS } = {}
|
|
110
|
-
) => {
|
|
44
|
+
const nextDeferral = (body, now = Date.now(), messageId) => {
|
|
111
45
|
const current = readDeferral(body);
|
|
112
|
-
const pacedBefore = current.pacedDeferrals ?? 0;
|
|
113
|
-
const free = preempted && pacedBefore < maxPacedDeferrals;
|
|
114
|
-
const paced = pacedBefore + (free ? 1 : 0);
|
|
115
46
|
return {
|
|
116
|
-
deferrals: current.deferrals +
|
|
117
|
-
...(paced > 0 && { pacedDeferrals: paced }),
|
|
47
|
+
deferrals: current.deferrals + 1,
|
|
118
48
|
firstDeferredAt: current.firstDeferredAt ?? new Date(now).toISOString(),
|
|
119
49
|
deferralId: current.deferralId ?? messageId,
|
|
120
50
|
};
|
|
@@ -132,12 +62,8 @@ const isDeferralCapped = (deferral, { maxDeferrals, maxDeferredMs }) =>
|
|
|
132
62
|
deferral.deferrals > maxDeferrals || deferredMs(deferral) > maxDeferredMs;
|
|
133
63
|
|
|
134
64
|
module.exports = {
|
|
135
|
-
DEFERRAL_JITTER_MAX_MS,
|
|
136
|
-
DEFERRAL_JITTER_MAX_MS_ENV,
|
|
137
65
|
MAX_DEFERRALS,
|
|
138
66
|
MAX_DEFERRALS_ENV,
|
|
139
|
-
MAX_PACED_DEFERRALS,
|
|
140
|
-
MAX_PACED_DEFERRALS_ENV,
|
|
141
67
|
MAX_DEFERRED_MS,
|
|
142
68
|
MAX_DEFERRED_MS_ENV,
|
|
143
69
|
MAX_DEFERRED_VISIBILITY_SECONDS,
|
|
@@ -147,7 +73,6 @@ module.exports = {
|
|
|
147
73
|
RATE_LIMIT_PROBE_MS_ENV,
|
|
148
74
|
deferredMs,
|
|
149
75
|
isDeferralCapped,
|
|
150
|
-
jitteredRetryAt,
|
|
151
76
|
nextDeferral,
|
|
152
77
|
readDeferral,
|
|
153
78
|
readDeferralLimits,
|
|
@@ -55,14 +55,6 @@ declare module "@friggframework/module-plugin" {
|
|
|
55
55
|
): Partial<Omit<RateLimitHint, "source">> & {
|
|
56
56
|
source?: "header" | "body" | "static";
|
|
57
57
|
} | null | undefined;
|
|
58
|
-
/** Pace calls on the scope key before they are sent (default true). */
|
|
59
|
-
pacing?: boolean;
|
|
60
|
-
/**
|
|
61
|
-
* Keep the block and the retry slots of the scope key in Entity.data of
|
|
62
|
-
* the calling entity, so that parallel workers on that entity share them
|
|
63
|
-
* (default false).
|
|
64
|
-
*/
|
|
65
|
-
shared?: boolean;
|
|
66
58
|
/** Keyed by reason. Client-safe text and links for the RATE_LIMITED message. */
|
|
67
59
|
userHints?: Record<
|
|
68
60
|
string,
|
|
@@ -211,6 +203,9 @@ declare module "@friggframework/module-plugin" {
|
|
|
211
203
|
scope: string;
|
|
212
204
|
state: any;
|
|
213
205
|
username: string;
|
|
206
|
+
/** Refresh before a request when the token expires within this many ms. 0 is off. */
|
|
207
|
+
refreshBeforeExpiryMs: number;
|
|
208
|
+
static refreshBeforeExpiryMs?: number;
|
|
214
209
|
|
|
215
210
|
constructor(params: OAuth2RequesterConstructor);
|
|
216
211
|
|
|
@@ -284,6 +279,7 @@ declare module "@friggframework/module-plugin" {
|
|
|
284
279
|
username?: string;
|
|
285
280
|
password?: string;
|
|
286
281
|
state?: any;
|
|
282
|
+
refreshBeforeExpiryMs?: number;
|
|
287
283
|
};
|
|
288
284
|
|
|
289
285
|
export const ModuleConstants: {
|
|
@@ -1,71 +0,0 @@
|
|
|
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
|
-
};
|