@imbingox/acex 0.4.0-beta.16 → 0.4.0-beta.18

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.
@@ -0,0 +1,98 @@
1
+ import type {
2
+ RateLimitBucketDescriptor,
3
+ RateLimitScope,
4
+ RateLimitSnapshot,
5
+ } from "../../types/index.ts";
6
+
7
+ export function scopeKey(scope: RateLimitScope): string {
8
+ return [scope.venue, scope.accountId ?? "", scope.endpointKey].join("\0");
9
+ }
10
+
11
+ export function bucketStateKey(
12
+ scope: RateLimitScope,
13
+ bucket: RateLimitBucketDescriptor,
14
+ ): string {
15
+ return [
16
+ bucket.id,
17
+ ...bucket.scope.map((dimension) => scopeValue(scope, dimension)),
18
+ ].join("\0");
19
+ }
20
+
21
+ function scopeValue(
22
+ scope: RateLimitScope,
23
+ dimension: RateLimitBucketDescriptor["scope"][number],
24
+ ): string {
25
+ switch (dimension) {
26
+ case "venue":
27
+ return scope.venue;
28
+ case "account":
29
+ return scope.accountId ?? "";
30
+ case "endpoint":
31
+ return scope.endpointKey;
32
+ }
33
+ }
34
+
35
+ export function windowStartMs(now: number, intervalMs: number): number {
36
+ return Math.floor(now / intervalMs) * intervalMs;
37
+ }
38
+
39
+ export function windowEndMs(windowStart: number, intervalMs: number): number {
40
+ return windowStart + intervalMs;
41
+ }
42
+
43
+ export function maxOptional(
44
+ left: number | undefined,
45
+ right: number | undefined,
46
+ ): number | undefined {
47
+ if (left === undefined) {
48
+ return right;
49
+ }
50
+ if (right === undefined) {
51
+ return left;
52
+ }
53
+ return Math.max(left, right);
54
+ }
55
+
56
+ export function nextRateLimitState(
57
+ existingState: RateLimitSnapshot["state"] | undefined,
58
+ patchState: RateLimitSnapshot["state"] | undefined,
59
+ patchWinsBlock: boolean,
60
+ blockedUntil: number | undefined,
61
+ ): RateLimitSnapshot["state"] | undefined {
62
+ if (!patchState) {
63
+ return blockedUntil !== undefined ? (existingState ?? "ok") : existingState;
64
+ }
65
+ if (!patchWinsBlock && existingState) {
66
+ return moreSevereState(existingState, patchState);
67
+ }
68
+ return patchState;
69
+ }
70
+
71
+ export function nextRetryAfterMs<T extends { retryAfterMs?: number }>(
72
+ existing: T | undefined,
73
+ patch: Partial<T>,
74
+ patchWinsBlock: boolean,
75
+ ): number | undefined {
76
+ if (patchWinsBlock) {
77
+ return patch.retryAfterMs ?? existing?.retryAfterMs;
78
+ }
79
+ return existing?.retryAfterMs;
80
+ }
81
+
82
+ function moreSevereState(
83
+ left: RateLimitSnapshot["state"],
84
+ right: RateLimitSnapshot["state"],
85
+ ): RateLimitSnapshot["state"] {
86
+ return stateSeverity(left) >= stateSeverity(right) ? left : right;
87
+ }
88
+
89
+ export function stateSeverity(state: RateLimitSnapshot["state"]): number {
90
+ switch (state) {
91
+ case "banned":
92
+ return 2;
93
+ case "rate_limited":
94
+ return 1;
95
+ case "ok":
96
+ return 0;
97
+ }
98
+ }
@@ -0,0 +1,123 @@
1
+ import type {
2
+ RateLimitBucketDescriptor,
3
+ RateLimitPlan,
4
+ } from "../../types/index.ts";
5
+
6
+ export function validateBucketDescriptor(
7
+ bucket: RateLimitBucketDescriptor,
8
+ ): void {
9
+ if (!bucket.id) {
10
+ throw new Error("Rate limit bucket descriptor id is required");
11
+ }
12
+ if (!Number.isFinite(bucket.limit) || bucket.limit < 0) {
13
+ throw new Error(`Invalid rate limit bucket limit: ${bucket.id}`);
14
+ }
15
+ if (!Number.isFinite(bucket.intervalMs) || bucket.intervalMs <= 0) {
16
+ throw new Error(`Invalid rate limit bucket interval: ${bucket.id}`);
17
+ }
18
+ if (bucket.reserve) {
19
+ if (!bucket.reserve.priority) {
20
+ throw new Error(
21
+ `Invalid rate limit bucket reserve priority: ${bucket.id}`,
22
+ );
23
+ }
24
+ if (
25
+ !Number.isFinite(bucket.reserve.units) ||
26
+ bucket.reserve.units < 0 ||
27
+ bucket.reserve.units > bucket.limit
28
+ ) {
29
+ throw new Error(`Invalid rate limit bucket reserve units: ${bucket.id}`);
30
+ }
31
+ }
32
+ }
33
+
34
+ export function validatePlan(
35
+ plan: RateLimitPlan,
36
+ buckets: ReadonlyMap<string, RateLimitBucketDescriptor>,
37
+ ): void {
38
+ if (!plan.id) {
39
+ throw new Error("Rate limit plan id is required");
40
+ }
41
+ for (const cost of plan.costs) {
42
+ if (!buckets.has(cost.bucketId)) {
43
+ throw new Error(
44
+ `Rate limit plan ${plan.id} references unknown bucket: ${cost.bucketId}`,
45
+ );
46
+ }
47
+ if (!Number.isFinite(cost.cost) || cost.cost < 0) {
48
+ throw new Error(`Invalid rate limit cost for plan: ${plan.id}`);
49
+ }
50
+ }
51
+ }
52
+
53
+ export function cloneBucketDescriptor(
54
+ bucket: RateLimitBucketDescriptor,
55
+ ): RateLimitBucketDescriptor {
56
+ return {
57
+ ...bucket,
58
+ reserve: bucket.reserve ? { ...bucket.reserve } : undefined,
59
+ scope: [...bucket.scope],
60
+ };
61
+ }
62
+
63
+ export function clonePlan(plan: RateLimitPlan): RateLimitPlan {
64
+ return {
65
+ ...plan,
66
+ costs: plan.costs.map((cost) => ({ ...cost })),
67
+ };
68
+ }
69
+
70
+ export function bucketDescriptorsEqual(
71
+ left: RateLimitBucketDescriptor,
72
+ right: RateLimitBucketDescriptor,
73
+ ): boolean {
74
+ return (
75
+ left.id === right.id &&
76
+ left.kind === right.kind &&
77
+ left.limit === right.limit &&
78
+ left.intervalMs === right.intervalMs &&
79
+ left.utilizationTarget === right.utilizationTarget &&
80
+ reservesEqual(left.reserve, right.reserve) &&
81
+ arraysEqual(left.scope, right.scope)
82
+ );
83
+ }
84
+
85
+ export function plansEqual(left: RateLimitPlan, right: RateLimitPlan): boolean {
86
+ if (
87
+ left.id !== right.id ||
88
+ left.priority !== right.priority ||
89
+ left.costs.length !== right.costs.length
90
+ ) {
91
+ return false;
92
+ }
93
+
94
+ return left.costs.every((cost, index) => {
95
+ const other = right.costs[index];
96
+ if (!other) {
97
+ return false;
98
+ }
99
+ return cost.bucketId === other.bucketId && cost.cost === other.cost;
100
+ });
101
+ }
102
+
103
+ function arraysEqual<T>(left: readonly T[], right: readonly T[]): boolean {
104
+ return (
105
+ left.length === right.length &&
106
+ left.every((value, index) => value === right[index])
107
+ );
108
+ }
109
+
110
+ function reservesEqual(
111
+ left: RateLimitBucketDescriptor["reserve"],
112
+ right: RateLimitBucketDescriptor["reserve"],
113
+ ): boolean {
114
+ if (!left || !right) {
115
+ return left === right;
116
+ }
117
+
118
+ return left.priority === right.priority && left.units === right.units;
119
+ }
120
+
121
+ export function uniqueStrings(values: readonly string[]): string[] {
122
+ return [...new Set(values)];
123
+ }
@@ -0,0 +1,49 @@
1
+ import type {
2
+ RateLimitPriority,
3
+ RateLimitSnapshot,
4
+ RateLimitUsage,
5
+ } from "../../types/index.ts";
6
+
7
+ export interface ReactiveRateLimiterOptions {
8
+ readonly now?: () => number;
9
+ readonly sleep?: (ms: number) => Promise<void>;
10
+ readonly random?: () => number;
11
+ readonly defaultRateLimitMs?: number;
12
+ readonly defaultBanMs?: number;
13
+ readonly retryJitterMs?: number;
14
+ readonly utilizationTarget?: number;
15
+ }
16
+
17
+ export interface EndpointRateLimitState {
18
+ usage?: RateLimitUsage;
19
+ blockedUntil?: number;
20
+ retryAfterMs?: number;
21
+ banStrikeCount?: number;
22
+ state: RateLimitSnapshot["state"];
23
+ updatedAt?: number;
24
+ }
25
+
26
+ export interface BucketRateLimitState {
27
+ used?: number;
28
+ windowStartMs?: number;
29
+ blockedUntil?: number;
30
+ retryAfterMs?: number;
31
+ banStrikeCount?: number;
32
+ state: RateLimitSnapshot["state"];
33
+ updatedAt?: number;
34
+ }
35
+
36
+ export interface RateLimitReservationBucket {
37
+ bucketId: string;
38
+ stateKey: string;
39
+ cost: number;
40
+ windowStartMs: number;
41
+ }
42
+
43
+ export interface BudgetRateLimitReservation {
44
+ readonly __opaqueRateLimitReservation?: never;
45
+ readonly admittedAt: number;
46
+ readonly planId: string;
47
+ readonly priority: RateLimitPriority;
48
+ readonly buckets: readonly RateLimitReservationBucket[];
49
+ }
@@ -0,0 +1,48 @@
1
+ import type {
2
+ RateLimitBucketDescriptor,
3
+ RateLimitUsage,
4
+ } from "../../types/index.ts";
5
+
6
+ export function cloneUsage(usage: RateLimitUsage): RateLimitUsage {
7
+ return {
8
+ weight: usage.weight ? { ...usage.weight } : undefined,
9
+ orderCount: usage.orderCount ? { ...usage.orderCount } : undefined,
10
+ };
11
+ }
12
+
13
+ export function usageForBucket(
14
+ usage: RateLimitUsage,
15
+ bucket: RateLimitBucketDescriptor,
16
+ ): number | undefined {
17
+ const intervalKey = intervalKeyFromMs(bucket.intervalMs);
18
+ if (!intervalKey) {
19
+ return undefined;
20
+ }
21
+
22
+ if (bucket.kind === "request_weight") {
23
+ return usage.weight?.[intervalKey];
24
+ }
25
+
26
+ if (bucket.kind === "orders") {
27
+ return usage.orderCount?.[intervalKey];
28
+ }
29
+
30
+ return undefined;
31
+ }
32
+
33
+ function intervalKeyFromMs(intervalMs: number): string | undefined {
34
+ const units: Array<readonly [suffix: string, ms: number]> = [
35
+ ["d", 86_400_000],
36
+ ["h", 3_600_000],
37
+ ["m", 60_000],
38
+ ["s", 1_000],
39
+ ];
40
+
41
+ for (const [suffix, ms] of units) {
42
+ if (intervalMs >= ms && intervalMs % ms === 0) {
43
+ return `${intervalMs / ms}${suffix}`;
44
+ }
45
+ }
46
+
47
+ return undefined;
48
+ }