@haatlabs-core/rate-limit 0.0.0-stage → 0.11.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Haatlabs
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,29 @@
1
- # Temporary Holding Version
1
+ # @haatlabs-core/rate-limit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A token bucket kept in Redis, so every process shares one limit.
4
+
5
+ import { perMinutePolicy, RedisTokenBucketLimiter } from '@haatlabs-core/rate-limit';
6
+ const limiter = new RedisTokenBucketLimiter(redis, { keyPrefix: 'myapp:' });
7
+ const { allowed, retryAfterMs } = await limiter.consume('provider:search', perMinutePolicy(60));
8
+
9
+ Every limiter is given a prefix of its own, so apps that share a Redis keep their buckets
10
+ apart; an empty one is refused:
11
+
12
+ new RedisTokenBucketLimiter(redis, { keyPrefix: 'myapp:' }); // keys myapp:ratelimit:…
13
+
14
+ `RedisShopifyThrottle` paces each Shopify shop for every process of an app (one small hash a
15
+ shop). When Redis is away (the failed call and ten seconds after it) it hands the shops to its
16
+ `fallback`, or, without one, lets calls through and each client's own pacing goes on:
17
+
18
+ import { processShopifyThrottle } from '@haatlabs-core/shopify';
19
+ const throttle = new RedisShopifyThrottle(redis, {
20
+ keyPrefix: 'myapp:',
21
+ logger,
22
+ fallback: processShopifyThrottle,
23
+ });
24
+
25
+ ## Install
26
+
27
+ pnpm add @haatlabs-core/rate-limit
28
+
29
+ It leaves one package to your app, so the app holds one copy: `ioredis`.
@@ -0,0 +1,37 @@
1
+ import type { Redis } from 'ioredis';
2
+ export interface RateLimitPolicy {
3
+ capacity: number;
4
+ refillPerSecond: number;
5
+ }
6
+ /**
7
+ * A policy that lets no more than `perMinute` through in any sixty seconds: a tenth of it
8
+ * at once, the rest refilled evenly (so nine tenths of it, minute after minute). It is how a limit a provider states as "requests a
9
+ * minute" is kept, which a bucket holding the whole minute would not: that one lets a
10
+ * full bucket and a minute's refill through together.
11
+ */
12
+ export declare function perMinutePolicy(perMinute: number): RateLimitPolicy;
13
+ export interface RateLimitResult {
14
+ allowed: boolean;
15
+ remaining: number;
16
+ retryAfterMs: number;
17
+ }
18
+ export interface RateLimiter {
19
+ consume(key: string, policy: RateLimitPolicy, cost?: number): Promise<RateLimitResult>;
20
+ }
21
+ export interface RedisTokenBucketLimiterOptions {
22
+ now?: () => number;
23
+ /**
24
+ * Put before every key, so apps that share a Redis keep separate buckets: an app's name
25
+ * and a colon, for example. Required, and never empty.
26
+ */
27
+ keyPrefix: string;
28
+ }
29
+ export declare class RedisTokenBucketLimiter implements RateLimiter {
30
+ private readonly redis;
31
+ private readonly now;
32
+ private readonly keyPrefix;
33
+ constructor(redis: Redis, options: RedisTokenBucketLimiterOptions);
34
+ consume(key: string, policy: RateLimitPolicy, cost?: number): Promise<RateLimitResult>;
35
+ }
36
+ export { RedisShopifyThrottle } from './shopify-throttle.js';
37
+ export type { RedisShopifyThrottleOptions, ShopifyBucketLike, ShopifyThrottleLike, } from './shopify-throttle.js';
@@ -0,0 +1,98 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var index_exports = {};
19
+ __export(index_exports, {
20
+ RedisShopifyThrottle: () => import_shopify_throttle.RedisShopifyThrottle,
21
+ RedisTokenBucketLimiter: () => RedisTokenBucketLimiter,
22
+ perMinutePolicy: () => perMinutePolicy
23
+ });
24
+ module.exports = __toCommonJS(index_exports);
25
+ var import_shopify_throttle = require("./shopify-throttle.js");
26
+ const SECONDS_PER_MINUTE = 60;
27
+ const BURST_SHARE = 10;
28
+ function perMinutePolicy(perMinute) {
29
+ if (!Number.isInteger(perMinute) || perMinute < 2) {
30
+ throw new RangeError(`perMinute must be a whole number of at least 2, got ${perMinute}`);
31
+ }
32
+ const capacity = Math.max(1, Math.floor(perMinute / BURST_SHARE));
33
+ return { capacity, refillPerSecond: (perMinute - capacity) / SECONDS_PER_MINUTE };
34
+ }
35
+ const TOKEN_BUCKET_SCRIPT = `
36
+ local capacity = tonumber(ARGV[1])
37
+ local refill = tonumber(ARGV[2])
38
+ local cost = tonumber(ARGV[3])
39
+ local now = tonumber(ARGV[4])
40
+ local msPerSecond = tonumber(ARGV[5])
41
+ local ttlPaddingMs = tonumber(ARGV[6])
42
+ local state = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
43
+ local tokens = tonumber(state[1])
44
+ local ts = tonumber(state[2])
45
+ if tokens == nil then
46
+ tokens = capacity
47
+ ts = now
48
+ end
49
+ tokens = math.min(capacity, tokens + math.max(0, now - ts) / msPerSecond * refill)
50
+ local allowed = 0
51
+ local retry = 0
52
+ if tokens >= cost then
53
+ tokens = tokens - cost
54
+ allowed = 1
55
+ else
56
+ retry = math.ceil((cost - tokens) / refill * msPerSecond)
57
+ end
58
+ redis.call('HSET', KEYS[1], 'tokens', tostring(tokens), 'ts', tostring(math.max(ts, now)))
59
+ redis.call('PEXPIRE', KEYS[1], math.ceil(capacity / refill * msPerSecond) + ttlPaddingMs)
60
+ return { allowed, math.floor(tokens), retry }
61
+ `;
62
+ const KEY_PREFIX = "ratelimit:";
63
+ const MS_PER_SECOND = 1e3;
64
+ const TTL_PADDING_MS = 1e3;
65
+ function requirePositiveFinite(name, value) {
66
+ if (!Number.isFinite(value) || value <= 0) {
67
+ throw new RangeError(`${name} must be a finite number greater than 0, got ${value}`);
68
+ }
69
+ }
70
+ class RedisTokenBucketLimiter {
71
+ redis;
72
+ now;
73
+ keyPrefix;
74
+ constructor(redis, options) {
75
+ this.redis = redis;
76
+ if (!options?.keyPrefix) {
77
+ throw new Error("RedisTokenBucketLimiter needs a keyPrefix: apps that share a Redis would share buckets");
78
+ }
79
+ this.now = options.now ?? Date.now;
80
+ this.keyPrefix = options.keyPrefix;
81
+ }
82
+ async consume(key, policy, cost = 1) {
83
+ requirePositiveFinite("capacity", policy.capacity);
84
+ requirePositiveFinite("refillPerSecond", policy.refillPerSecond);
85
+ requirePositiveFinite("cost", cost);
86
+ if (cost > policy.capacity) {
87
+ throw new RangeError(`cost ${cost} exceeds capacity ${policy.capacity}`);
88
+ }
89
+ const [allowed, remaining, retryAfterMs] = await this.redis.eval(TOKEN_BUCKET_SCRIPT, 1, `${this.keyPrefix}${KEY_PREFIX}${key}`, policy.capacity, policy.refillPerSecond, cost, this.now(), MS_PER_SECOND, TTL_PADDING_MS);
90
+ return { allowed: allowed === 1, remaining, retryAfterMs };
91
+ }
92
+ }
93
+ // Annotate the CommonJS export names for ESM import in node:
94
+ 0 && (module.exports = {
95
+ RedisShopifyThrottle,
96
+ RedisTokenBucketLimiter,
97
+ perMinutePolicy
98
+ });
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
@@ -0,0 +1,70 @@
1
+ import type { Redis } from 'ioredis';
2
+ /** @haatlabs-core/shopify's ShopifyBucket, by shape: this package does not depend on that one. */
3
+ export interface ShopifyBucketLike {
4
+ requestedQueryCost: number | null;
5
+ actualQueryCost: number | null;
6
+ currentlyAvailable: number;
7
+ maximumAvailable: number;
8
+ restoreRate: number;
9
+ }
10
+ /** @haatlabs-core/shopify's ShopifyThrottle, by shape. */
11
+ export interface ShopifyThrottleLike {
12
+ wait(shopDomain: string, signal?: AbortSignal): Promise<void>;
13
+ report(shopDomain: string, bucket: ShopifyBucketLike): Promise<void>;
14
+ }
15
+ export interface RedisShopifyThrottleOptions {
16
+ /** Put before every key (`<prefix>shopify:throttle:<shop>`): the app's name and a colon. */
17
+ keyPrefix: string;
18
+ /** Default 0.1: a tenth of the bucket kept back. */
19
+ reserveShare?: number;
20
+ /** Default 60 s: the most one request waits for its turn. */
21
+ maxWaitMs?: number;
22
+ now?: () => number;
23
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
24
+ /** Told, at most once a minute, that Redis could not be reached. */
25
+ logger?: {
26
+ warn(obj: object, msg: string): void;
27
+ };
28
+ /** Default 1 s: a command slower than this counts as Redis away. */
29
+ commandTimeoutMs?: number;
30
+ /**
31
+ * Paces the shops while Redis is away (the failed call and the cool-off after it), as
32
+ * `processShopifyThrottle` of @haatlabs-core/shopify does in each process. Left out: the throttle
33
+ * lets every call through and each client's own pacing goes on.
34
+ */
35
+ fallback?: ShopifyThrottleLike;
36
+ }
37
+ /**
38
+ * When the next request may start, or null for at once. The same arithmetic as
39
+ * @haatlabs-core/shopify's `nextShopifyStart`, run against the same table of cases; it is copied
40
+ * here because this package must not depend on that one at run time.
41
+ */
42
+ export declare function nextShopifyStart(bucket: ShopifyBucketLike, now: number, maxWaitMs?: number, reserveShare?: number): number | null;
43
+ /**
44
+ * A ShopifyThrottle (@haatlabs-core/shopify) shared by every process of an app: one hash per
45
+ * shop, raised by a Lua max(). When Redis is away or slow, for ten seconds after the failure,
46
+ * `wait` and `report` go to the `fallback` throttle; without one, `wait` resolves at once and
47
+ * `report` does nothing, and each client's own pacing goes on. Shopify's THROTTLED answer
48
+ * remains the backstop.
49
+ */
50
+ export declare class RedisShopifyThrottle {
51
+ private readonly redis;
52
+ private readonly options;
53
+ private readonly keyPrefix;
54
+ private readonly reserveShare;
55
+ private readonly maxWaitMs;
56
+ private readonly now;
57
+ private readonly sleep;
58
+ private readonly commandTimeoutMs;
59
+ private lastWarnedAt;
60
+ private coolOffUntil;
61
+ constructor(redis: Redis, options: RedisShopifyThrottleOptions);
62
+ private key;
63
+ private within;
64
+ private failed;
65
+ private coolingOff;
66
+ wait(shopDomain: string, signal?: AbortSignal): Promise<void>;
67
+ /** Redis away: the fallback paces this call, or nothing does. */
68
+ private fallBack;
69
+ report(shopDomain: string, bucket: ShopifyBucketLike): Promise<void>;
70
+ }
@@ -0,0 +1,222 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var shopify_throttle_exports = {};
19
+ __export(shopify_throttle_exports, {
20
+ RedisShopifyThrottle: () => RedisShopifyThrottle,
21
+ nextShopifyStart: () => nextShopifyStart
22
+ });
23
+ module.exports = __toCommonJS(shopify_throttle_exports);
24
+ const DEFAULT_RESERVE_SHARE = 0.1;
25
+ const DEFAULT_MAX_WAIT_MS = 6e4;
26
+ const DEFAULT_COMMAND_TIMEOUT_MS = 1e3;
27
+ const WARN_EVERY_MS = 6e4;
28
+ const COOL_OFF_MS = 1e4;
29
+ const MS_PER_SECOND = 1e3;
30
+ const MAX_SPACING_MS = 1e4;
31
+ const DEFAULT_SPACING_MS = 250;
32
+ const TTL_PADDING_MS = 1e3;
33
+ const KEY = "shopify:throttle:";
34
+ const RAISE_SCRIPT = `
35
+ local current = tonumber(redis.call('HGET', KEYS[1], 'notBefore') or '0')
36
+ local candidate = tonumber(ARGV[1])
37
+ if candidate > current then
38
+ redis.call('HSET', KEYS[1], 'notBefore', ARGV[1], 'spacingMs', ARGV[3])
39
+ redis.call('HINCRBY', KEYS[1], 'epoch', 1)
40
+ redis.call('PEXPIRE', KEYS[1], ARGV[2])
41
+ return candidate
42
+ end
43
+ return current
44
+ `;
45
+ const CLAIM_SCRIPT = `
46
+ local now = tonumber(ARGV[1])
47
+ local notBefore = tonumber(redis.call('HGET', KEYS[1], 'notBefore') or '0')
48
+ local epoch = redis.call('HGET', KEYS[1], 'epoch') or '0'
49
+ if notBefore <= now then
50
+ return { now, epoch }
51
+ end
52
+ if notBefore - now > tonumber(ARGV[4]) then
53
+ return { notBefore, epoch }
54
+ end
55
+ local spacing = tonumber(redis.call('HGET', KEYS[1], 'spacingMs') or ARGV[2])
56
+ redis.call('HSET', KEYS[1], 'notBefore', tostring(notBefore + spacing))
57
+ redis.call('PEXPIRE', KEYS[1], notBefore + spacing - now + tonumber(ARGV[3]))
58
+ return { notBefore, epoch }
59
+ `;
60
+ function nextShopifyStart(bucket, now, maxWaitMs = DEFAULT_MAX_WAIT_MS, reserveShare = DEFAULT_RESERVE_SHARE) {
61
+ const { currentlyAvailable, maximumAvailable, restoreRate } = bucket;
62
+ if (![currentlyAvailable, maximumAvailable, restoreRate].every(Number.isFinite) || restoreRate <= 0) {
63
+ return null;
64
+ }
65
+ const cost = bucket.actualQueryCost ?? bucket.requestedQueryCost ?? 0;
66
+ const needed = Math.max(cost, Math.ceil(maximumAvailable * reserveShare));
67
+ if (currentlyAvailable >= needed)
68
+ return null;
69
+ const waitMs = Math.ceil((needed - currentlyAvailable) / restoreRate * MS_PER_SECOND);
70
+ return now + Math.min(maxWaitMs, waitMs);
71
+ }
72
+ function abortableSleep(ms, signal) {
73
+ return new Promise((resolve, reject) => {
74
+ const abort = () => signal?.reason ?? new DOMException("The wait was aborted", "AbortError");
75
+ if (signal?.aborted) {
76
+ reject(abort());
77
+ return;
78
+ }
79
+ const onAbort = () => {
80
+ clearTimeout(handle);
81
+ reject(abort());
82
+ };
83
+ const handle = setTimeout(() => {
84
+ signal?.removeEventListener("abort", onAbort);
85
+ resolve();
86
+ }, ms);
87
+ signal?.addEventListener("abort", onAbort, { once: true });
88
+ });
89
+ }
90
+ class CommandTimeoutError extends Error {
91
+ constructor() {
92
+ super("Redis did not answer in time");
93
+ }
94
+ }
95
+ const AWAY_CODES = /* @__PURE__ */ new Set(["ECONNREFUSED", "ECONNRESET", "ETIMEDOUT", "EPIPE"]);
96
+ const AWAY_MESSAGE = /Connection is closed|max retries per request|enableOfflineQueue options is false|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EPIPE|^LOADING\b/;
97
+ function isAway(error) {
98
+ if (error instanceof CommandTimeoutError)
99
+ return true;
100
+ if (!(error instanceof Error))
101
+ return false;
102
+ const code = error.code;
103
+ return typeof code === "string" && AWAY_CODES.has(code) || AWAY_MESSAGE.test(error.message);
104
+ }
105
+ class RedisShopifyThrottle {
106
+ redis;
107
+ options;
108
+ keyPrefix;
109
+ reserveShare;
110
+ maxWaitMs;
111
+ now;
112
+ sleep;
113
+ commandTimeoutMs;
114
+ lastWarnedAt = Number.NEGATIVE_INFINITY;
115
+ coolOffUntil = Number.NEGATIVE_INFINITY;
116
+ constructor(redis, options) {
117
+ this.redis = redis;
118
+ this.options = options;
119
+ if (!options?.keyPrefix) {
120
+ throw new Error("RedisShopifyThrottle needs a keyPrefix: apps that share a Redis would share shops");
121
+ }
122
+ this.keyPrefix = options.keyPrefix;
123
+ this.reserveShare = options.reserveShare ?? DEFAULT_RESERVE_SHARE;
124
+ this.maxWaitMs = options.maxWaitMs ?? DEFAULT_MAX_WAIT_MS;
125
+ if (!Number.isFinite(this.reserveShare) || this.reserveShare < 0 || this.reserveShare > 1) {
126
+ throw new RangeError(`reserveShare must be between 0 and 1, got ${this.reserveShare}`);
127
+ }
128
+ if (!Number.isInteger(this.maxWaitMs) || this.maxWaitMs < 1) {
129
+ throw new RangeError(`maxWaitMs must be a whole number of at least 1, got ${this.maxWaitMs}`);
130
+ }
131
+ this.now = options.now ?? (() => Date.now());
132
+ this.sleep = options.sleep ?? abortableSleep;
133
+ this.commandTimeoutMs = options.commandTimeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS;
134
+ }
135
+ key(shopDomain) {
136
+ return `${this.keyPrefix}${KEY}${shopDomain.trim().toLowerCase()}`;
137
+ }
138
+ within(work) {
139
+ let handle;
140
+ const late = new Promise((_, reject) => {
141
+ handle = setTimeout(() => reject(new CommandTimeoutError()), this.commandTimeoutMs);
142
+ });
143
+ work.catch(() => void 0);
144
+ return Promise.race([work, late]).finally(() => clearTimeout(handle));
145
+ }
146
+ failed(error) {
147
+ const at = this.now();
148
+ const away = isAway(error);
149
+ if (away)
150
+ this.coolOffUntil = at + COOL_OFF_MS;
151
+ if (at - this.lastWarnedAt < WARN_EVERY_MS)
152
+ return;
153
+ this.lastWarnedAt = at;
154
+ const fallsBack = this.options.fallback ? "it falls back to its fallback throttle" : "it falls back to each client\u2019s own pacing";
155
+ this.options.logger?.warn({}, away ? `The Shopify throttle cannot reach Redis; ${fallsBack}` : `The Shopify throttle failed against Redis; ${fallsBack}`);
156
+ }
157
+ coolingOff() {
158
+ return this.now() < this.coolOffUntil;
159
+ }
160
+ async wait(shopDomain, signal) {
161
+ if (signal?.aborted) {
162
+ throw signal.reason ?? new DOMException("The wait was aborted", "AbortError");
163
+ }
164
+ if (this.coolingOff())
165
+ return this.fallBack(shopDomain, signal);
166
+ const key = this.key(shopDomain);
167
+ let waited = 0;
168
+ while (waited < this.maxWaitMs && !this.coolingOff()) {
169
+ let slot;
170
+ let epoch;
171
+ try {
172
+ const at = this.now();
173
+ const claimed = await this.within(this.redis.eval(CLAIM_SCRIPT, 1, key, at, DEFAULT_SPACING_MS, TTL_PADDING_MS, this.maxWaitMs - waited));
174
+ slot = Number(claimed[0]);
175
+ epoch = String(claimed[1]);
176
+ } catch (error) {
177
+ this.failed(error);
178
+ return this.fallBack(shopDomain, signal);
179
+ }
180
+ const ms = Math.min(this.maxWaitMs - waited, slot - this.now());
181
+ if (!(ms > 0))
182
+ return;
183
+ await this.sleep(ms, signal);
184
+ waited += ms;
185
+ try {
186
+ const now = await this.within(this.redis.hget(key, "epoch"));
187
+ if ((now ?? "0") === epoch)
188
+ return;
189
+ } catch (error) {
190
+ this.failed(error);
191
+ return this.fallBack(shopDomain, signal);
192
+ }
193
+ }
194
+ }
195
+ /** Redis away: the fallback paces this call, or nothing does. */
196
+ async fallBack(shopDomain, signal) {
197
+ await this.options.fallback?.wait(shopDomain, signal);
198
+ }
199
+ async report(shopDomain, bucket) {
200
+ if (this.coolingOff()) {
201
+ await this.options.fallback?.report(shopDomain, bucket).catch(() => void 0);
202
+ return;
203
+ }
204
+ const at = this.now();
205
+ const next = nextShopifyStart(bucket, at, this.maxWaitMs, this.reserveShare);
206
+ if (next === null)
207
+ return;
208
+ const cost = bucket.actualQueryCost ?? bucket.requestedQueryCost ?? 0;
209
+ const spacing = Math.min(MAX_SPACING_MS, Math.ceil(cost / bucket.restoreRate * MS_PER_SECOND));
210
+ try {
211
+ await this.within(this.redis.eval(RAISE_SCRIPT, 1, this.key(shopDomain), next, next - at + TTL_PADDING_MS, spacing));
212
+ } catch (error) {
213
+ this.failed(error);
214
+ await this.options.fallback?.report(shopDomain, bucket).catch(() => void 0);
215
+ }
216
+ }
217
+ }
218
+ // Annotate the CommonJS export names for ESM import in node:
219
+ 0 && (module.exports = {
220
+ RedisShopifyThrottle,
221
+ nextShopifyStart
222
+ });
@@ -0,0 +1,37 @@
1
+ import type { Redis } from 'ioredis';
2
+ export interface RateLimitPolicy {
3
+ capacity: number;
4
+ refillPerSecond: number;
5
+ }
6
+ /**
7
+ * A policy that lets no more than `perMinute` through in any sixty seconds: a tenth of it
8
+ * at once, the rest refilled evenly (so nine tenths of it, minute after minute). It is how a limit a provider states as "requests a
9
+ * minute" is kept, which a bucket holding the whole minute would not: that one lets a
10
+ * full bucket and a minute's refill through together.
11
+ */
12
+ export declare function perMinutePolicy(perMinute: number): RateLimitPolicy;
13
+ export interface RateLimitResult {
14
+ allowed: boolean;
15
+ remaining: number;
16
+ retryAfterMs: number;
17
+ }
18
+ export interface RateLimiter {
19
+ consume(key: string, policy: RateLimitPolicy, cost?: number): Promise<RateLimitResult>;
20
+ }
21
+ export interface RedisTokenBucketLimiterOptions {
22
+ now?: () => number;
23
+ /**
24
+ * Put before every key, so apps that share a Redis keep separate buckets: an app's name
25
+ * and a colon, for example. Required, and never empty.
26
+ */
27
+ keyPrefix: string;
28
+ }
29
+ export declare class RedisTokenBucketLimiter implements RateLimiter {
30
+ private readonly redis;
31
+ private readonly now;
32
+ private readonly keyPrefix;
33
+ constructor(redis: Redis, options: RedisTokenBucketLimiterOptions);
34
+ consume(key: string, policy: RateLimitPolicy, cost?: number): Promise<RateLimitResult>;
35
+ }
36
+ export { RedisShopifyThrottle } from './shopify-throttle.js';
37
+ export type { RedisShopifyThrottleOptions, ShopifyBucketLike, ShopifyThrottleLike, } from './shopify-throttle.js';
package/dist/index.js ADDED
@@ -0,0 +1,80 @@
1
+ const SECONDS_PER_MINUTE = 60;
2
+ /** The share of a minute's allowance that may be spent at once. */
3
+ const BURST_SHARE = 10;
4
+ /**
5
+ * A policy that lets no more than `perMinute` through in any sixty seconds: a tenth of it
6
+ * at once, the rest refilled evenly (so nine tenths of it, minute after minute). It is how a limit a provider states as "requests a
7
+ * minute" is kept, which a bucket holding the whole minute would not: that one lets a
8
+ * full bucket and a minute's refill through together.
9
+ */
10
+ export function perMinutePolicy(perMinute) {
11
+ if (!Number.isInteger(perMinute) || perMinute < 2) {
12
+ throw new RangeError(`perMinute must be a whole number of at least 2, got ${perMinute}`);
13
+ }
14
+ const capacity = Math.max(1, Math.floor(perMinute / BURST_SHARE));
15
+ return { capacity, refillPerSecond: (perMinute - capacity) / SECONDS_PER_MINUTE };
16
+ }
17
+ // KEYS[1] bucket; ARGV: capacity, refill per second, cost, now (ms), ms per second, TTL padding (ms).
18
+ // The whole read-modify-write runs inside Redis, so concurrent callers cannot overspend.
19
+ const TOKEN_BUCKET_SCRIPT = `
20
+ local capacity = tonumber(ARGV[1])
21
+ local refill = tonumber(ARGV[2])
22
+ local cost = tonumber(ARGV[3])
23
+ local now = tonumber(ARGV[4])
24
+ local msPerSecond = tonumber(ARGV[5])
25
+ local ttlPaddingMs = tonumber(ARGV[6])
26
+ local state = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
27
+ local tokens = tonumber(state[1])
28
+ local ts = tonumber(state[2])
29
+ if tokens == nil then
30
+ tokens = capacity
31
+ ts = now
32
+ end
33
+ tokens = math.min(capacity, tokens + math.max(0, now - ts) / msPerSecond * refill)
34
+ local allowed = 0
35
+ local retry = 0
36
+ if tokens >= cost then
37
+ tokens = tokens - cost
38
+ allowed = 1
39
+ else
40
+ retry = math.ceil((cost - tokens) / refill * msPerSecond)
41
+ end
42
+ redis.call('HSET', KEYS[1], 'tokens', tostring(tokens), 'ts', tostring(math.max(ts, now)))
43
+ redis.call('PEXPIRE', KEYS[1], math.ceil(capacity / refill * msPerSecond) + ttlPaddingMs)
44
+ return { allowed, math.floor(tokens), retry }
45
+ `;
46
+ const KEY_PREFIX = 'ratelimit:';
47
+ const MS_PER_SECOND = 1000;
48
+ // Extra lifetime past a full refill so an idle bucket is not evicted while still partly drained.
49
+ const TTL_PADDING_MS = 1000;
50
+ function requirePositiveFinite(name, value) {
51
+ if (!Number.isFinite(value) || value <= 0) {
52
+ throw new RangeError(`${name} must be a finite number greater than 0, got ${value}`);
53
+ }
54
+ }
55
+ export class RedisTokenBucketLimiter {
56
+ redis;
57
+ now;
58
+ keyPrefix;
59
+ constructor(redis, options) {
60
+ this.redis = redis;
61
+ // No options at all gets the same error, not a TypeError.
62
+ if (!options?.keyPrefix) {
63
+ throw new Error('RedisTokenBucketLimiter needs a keyPrefix: apps that share a Redis would share buckets');
64
+ }
65
+ this.now = options.now ?? Date.now;
66
+ this.keyPrefix = options.keyPrefix;
67
+ }
68
+ async consume(key, policy, cost = 1) {
69
+ requirePositiveFinite('capacity', policy.capacity);
70
+ requirePositiveFinite('refillPerSecond', policy.refillPerSecond);
71
+ requirePositiveFinite('cost', cost);
72
+ if (cost > policy.capacity) {
73
+ throw new RangeError(`cost ${cost} exceeds capacity ${policy.capacity}`);
74
+ }
75
+ const [allowed, remaining, retryAfterMs] = (await this.redis.eval(TOKEN_BUCKET_SCRIPT, 1, `${this.keyPrefix}${KEY_PREFIX}${key}`, policy.capacity, policy.refillPerSecond, cost, this.now(), MS_PER_SECOND, TTL_PADDING_MS));
76
+ return { allowed: allowed === 1, remaining, retryAfterMs };
77
+ }
78
+ }
79
+ export { RedisShopifyThrottle } from './shopify-throttle.js';
80
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAOA,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAC9B,mEAAmE;AACnE,MAAM,WAAW,GAAG,EAAE,CAAC;AAEvB;;;;;GAKG;AACH,MAAM,UAAU,eAAe,CAAC,SAAiB;IAC/C,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,SAAS,CAAC,IAAI,SAAS,GAAG,CAAC,EAAE,CAAC;QAClD,MAAM,IAAI,UAAU,CAAC,uDAAuD,SAAS,EAAE,CAAC,CAAC;IAC3F,CAAC;IACD,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,SAAS,GAAG,WAAW,CAAC,CAAC,CAAC;IAClE,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,CAAC,SAAS,GAAG,QAAQ,CAAC,GAAG,kBAAkB,EAAE,CAAC;AACpF,CAAC;AAYD,sGAAsG;AACtG,yFAAyF;AACzF,MAAM,mBAAmB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AM,CAAC,OAAO,EAAE,SAAS,EAAE,YAAY,CAAC,GAAG,CAAC,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,CAC/D,mBAAmB,EACnB,CAAC,EACD,GAAG,IAAI,CAAC,SAAS,GAAG,UAAU,GAAG,GAAG,EAAE,EACtC,MAAM,CAAC,QAAQ,EACf,MAAM,CAAC,eAAe,EACtB,IAAI,EACJ,IAAI,CAAC,GAAG,EAAE,EACV,aAAa,EACb,cAAc,CACf,CAA6B,CAAC;QAC/B,OAAO,EAAE,OAAO,EAAE,OAAO,KAAK,CAAC,EAAE,SAAS,EAAE,YAAY,EAAE,CAAC;IAC7D,CAAC;CACF;AAED,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC"}
@@ -0,0 +1,70 @@
1
+ import type { Redis } from 'ioredis';
2
+ /** @haatlabs-core/shopify's ShopifyBucket, by shape: this package does not depend on that one. */
3
+ export interface ShopifyBucketLike {
4
+ requestedQueryCost: number | null;
5
+ actualQueryCost: number | null;
6
+ currentlyAvailable: number;
7
+ maximumAvailable: number;
8
+ restoreRate: number;
9
+ }
10
+ /** @haatlabs-core/shopify's ShopifyThrottle, by shape. */
11
+ export interface ShopifyThrottleLike {
12
+ wait(shopDomain: string, signal?: AbortSignal): Promise<void>;
13
+ report(shopDomain: string, bucket: ShopifyBucketLike): Promise<void>;
14
+ }
15
+ export interface RedisShopifyThrottleOptions {
16
+ /** Put before every key (`<prefix>shopify:throttle:<shop>`): the app's name and a colon. */
17
+ keyPrefix: string;
18
+ /** Default 0.1: a tenth of the bucket kept back. */
19
+ reserveShare?: number;
20
+ /** Default 60 s: the most one request waits for its turn. */
21
+ maxWaitMs?: number;
22
+ now?: () => number;
23
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
24
+ /** Told, at most once a minute, that Redis could not be reached. */
25
+ logger?: {
26
+ warn(obj: object, msg: string): void;
27
+ };
28
+ /** Default 1 s: a command slower than this counts as Redis away. */
29
+ commandTimeoutMs?: number;
30
+ /**
31
+ * Paces the shops while Redis is away (the failed call and the cool-off after it), as
32
+ * `processShopifyThrottle` of @haatlabs-core/shopify does in each process. Left out: the throttle
33
+ * lets every call through and each client's own pacing goes on.
34
+ */
35
+ fallback?: ShopifyThrottleLike;
36
+ }
37
+ /**
38
+ * When the next request may start, or null for at once. The same arithmetic as
39
+ * @haatlabs-core/shopify's `nextShopifyStart`, run against the same table of cases; it is copied
40
+ * here because this package must not depend on that one at run time.
41
+ */
42
+ export declare function nextShopifyStart(bucket: ShopifyBucketLike, now: number, maxWaitMs?: number, reserveShare?: number): number | null;
43
+ /**
44
+ * A ShopifyThrottle (@haatlabs-core/shopify) shared by every process of an app: one hash per
45
+ * shop, raised by a Lua max(). When Redis is away or slow, for ten seconds after the failure,
46
+ * `wait` and `report` go to the `fallback` throttle; without one, `wait` resolves at once and
47
+ * `report` does nothing, and each client's own pacing goes on. Shopify's THROTTLED answer
48
+ * remains the backstop.
49
+ */
50
+ export declare class RedisShopifyThrottle {
51
+ private readonly redis;
52
+ private readonly options;
53
+ private readonly keyPrefix;
54
+ private readonly reserveShare;
55
+ private readonly maxWaitMs;
56
+ private readonly now;
57
+ private readonly sleep;
58
+ private readonly commandTimeoutMs;
59
+ private lastWarnedAt;
60
+ private coolOffUntil;
61
+ constructor(redis: Redis, options: RedisShopifyThrottleOptions);
62
+ private key;
63
+ private within;
64
+ private failed;
65
+ private coolingOff;
66
+ wait(shopDomain: string, signal?: AbortSignal): Promise<void>;
67
+ /** Redis away: the fallback paces this call, or nothing does. */
68
+ private fallBack;
69
+ report(shopDomain: string, bucket: ShopifyBucketLike): Promise<void>;
70
+ }
@@ -0,0 +1,233 @@
1
+ const DEFAULT_RESERVE_SHARE = 0.1;
2
+ const DEFAULT_MAX_WAIT_MS = 60_000;
3
+ const DEFAULT_COMMAND_TIMEOUT_MS = 1_000;
4
+ const WARN_EVERY_MS = 60_000;
5
+ /** After a failed command, Redis is left alone this long. */
6
+ const COOL_OFF_MS = 10_000;
7
+ const MS_PER_SECOND = 1_000;
8
+ /** The longest gap kept between two requests released by one start. */
9
+ const MAX_SPACING_MS = 10_000;
10
+ /** The gap when a start was stored without one. */
11
+ const DEFAULT_SPACING_MS = 250;
12
+ /** The hash outlives the wait it holds by this much. */
13
+ const TTL_PADDING_MS = 1_000;
14
+ const KEY = 'shopify:throttle:';
15
+ // KEYS[1] the shop's hash; ARGV: the candidate start (ms), the hash's lifetime (ms), the spacing
16
+ // between two requests (ms). max(): a later answer never brings a start forward. The epoch
17
+ // counts the answers that moved it, so a sleeper can tell that one did.
18
+ const RAISE_SCRIPT = `
19
+ local current = tonumber(redis.call('HGET', KEYS[1], 'notBefore') or '0')
20
+ local candidate = tonumber(ARGV[1])
21
+ if candidate > current then
22
+ redis.call('HSET', KEYS[1], 'notBefore', ARGV[1], 'spacingMs', ARGV[3])
23
+ redis.call('HINCRBY', KEYS[1], 'epoch', 1)
24
+ redis.call('PEXPIRE', KEYS[1], ARGV[2])
25
+ return candidate
26
+ end
27
+ return current
28
+ `;
29
+ // KEYS[1] the shop's hash; ARGV: now (ms), the spacing when none is stored (ms), TTL padding (ms),
30
+ // the caller's remaining budget (ms).
31
+ // A caller takes the start in force, and the next one is put one spacing after it, so that
32
+ // callers woken together by one start do not all go at once. Nothing pending, or a start
33
+ // beyond the caller's budget (it is released at its cap): no write.
34
+ const CLAIM_SCRIPT = `
35
+ local now = tonumber(ARGV[1])
36
+ local notBefore = tonumber(redis.call('HGET', KEYS[1], 'notBefore') or '0')
37
+ local epoch = redis.call('HGET', KEYS[1], 'epoch') or '0'
38
+ if notBefore <= now then
39
+ return { now, epoch }
40
+ end
41
+ if notBefore - now > tonumber(ARGV[4]) then
42
+ return { notBefore, epoch }
43
+ end
44
+ local spacing = tonumber(redis.call('HGET', KEYS[1], 'spacingMs') or ARGV[2])
45
+ redis.call('HSET', KEYS[1], 'notBefore', tostring(notBefore + spacing))
46
+ redis.call('PEXPIRE', KEYS[1], notBefore + spacing - now + tonumber(ARGV[3]))
47
+ return { notBefore, epoch }
48
+ `;
49
+ /**
50
+ * When the next request may start, or null for at once. The same arithmetic as
51
+ * @haatlabs-core/shopify's `nextShopifyStart`, run against the same table of cases; it is copied
52
+ * here because this package must not depend on that one at run time.
53
+ */
54
+ export function nextShopifyStart(bucket, now, maxWaitMs = DEFAULT_MAX_WAIT_MS, reserveShare = DEFAULT_RESERVE_SHARE) {
55
+ const { currentlyAvailable, maximumAvailable, restoreRate } = bucket;
56
+ if (![currentlyAvailable, maximumAvailable, restoreRate].every(Number.isFinite) ||
57
+ restoreRate <= 0) {
58
+ return null;
59
+ }
60
+ const cost = bucket.actualQueryCost ?? bucket.requestedQueryCost ?? 0;
61
+ const needed = Math.max(cost, Math.ceil(maximumAvailable * reserveShare));
62
+ if (currentlyAvailable >= needed)
63
+ return null;
64
+ const waitMs = Math.ceil(((needed - currentlyAvailable) / restoreRate) * MS_PER_SECOND);
65
+ return now + Math.min(maxWaitMs, waitMs);
66
+ }
67
+ function abortableSleep(ms, signal) {
68
+ return new Promise((resolve, reject) => {
69
+ const abort = () => signal?.reason ?? new DOMException('The wait was aborted', 'AbortError');
70
+ if (signal?.aborted) {
71
+ reject(abort());
72
+ return;
73
+ }
74
+ const onAbort = () => {
75
+ clearTimeout(handle);
76
+ reject(abort());
77
+ };
78
+ const handle = setTimeout(() => {
79
+ signal?.removeEventListener('abort', onAbort);
80
+ resolve();
81
+ }, ms);
82
+ signal?.addEventListener('abort', onAbort, { once: true });
83
+ });
84
+ }
85
+ class CommandTimeoutError extends Error {
86
+ constructor() {
87
+ super('Redis did not answer in time');
88
+ }
89
+ }
90
+ const AWAY_CODES = new Set(['ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT', 'EPIPE']);
91
+ const AWAY_MESSAGE = /Connection is closed|max retries per request|enableOfflineQueue options is false|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EPIPE|^LOADING\b/;
92
+ /** Redis away (slow, unreachable, loading), as against a command it refused. */
93
+ function isAway(error) {
94
+ if (error instanceof CommandTimeoutError)
95
+ return true;
96
+ if (!(error instanceof Error))
97
+ return false;
98
+ const code = error.code;
99
+ return (typeof code === 'string' && AWAY_CODES.has(code)) || AWAY_MESSAGE.test(error.message);
100
+ }
101
+ /**
102
+ * A ShopifyThrottle (@haatlabs-core/shopify) shared by every process of an app: one hash per
103
+ * shop, raised by a Lua max(). When Redis is away or slow, for ten seconds after the failure,
104
+ * `wait` and `report` go to the `fallback` throttle; without one, `wait` resolves at once and
105
+ * `report` does nothing, and each client's own pacing goes on. Shopify's THROTTLED answer
106
+ * remains the backstop.
107
+ */
108
+ export class RedisShopifyThrottle {
109
+ redis;
110
+ options;
111
+ keyPrefix;
112
+ reserveShare;
113
+ maxWaitMs;
114
+ now;
115
+ sleep;
116
+ commandTimeoutMs;
117
+ lastWarnedAt = Number.NEGATIVE_INFINITY;
118
+ coolOffUntil = Number.NEGATIVE_INFINITY;
119
+ constructor(redis, options) {
120
+ this.redis = redis;
121
+ this.options = options;
122
+ // No options at all gets the same error, not a TypeError.
123
+ if (!options?.keyPrefix) {
124
+ throw new Error('RedisShopifyThrottle needs a keyPrefix: apps that share a Redis would share shops');
125
+ }
126
+ this.keyPrefix = options.keyPrefix;
127
+ this.reserveShare = options.reserveShare ?? DEFAULT_RESERVE_SHARE;
128
+ this.maxWaitMs = options.maxWaitMs ?? DEFAULT_MAX_WAIT_MS;
129
+ if (!Number.isFinite(this.reserveShare) || this.reserveShare < 0 || this.reserveShare > 1) {
130
+ throw new RangeError(`reserveShare must be between 0 and 1, got ${this.reserveShare}`);
131
+ }
132
+ if (!Number.isInteger(this.maxWaitMs) || this.maxWaitMs < 1) {
133
+ throw new RangeError(`maxWaitMs must be a whole number of at least 1, got ${this.maxWaitMs}`);
134
+ }
135
+ // The caller's clock is the one read for every start, here and in the sleeps: a clock far
136
+ // from Redis's peers only shifts waits, which are capped at maxWaitMs.
137
+ this.now = options.now ?? (() => Date.now());
138
+ this.sleep = options.sleep ?? abortableSleep;
139
+ this.commandTimeoutMs = options.commandTimeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS;
140
+ }
141
+ key(shopDomain) {
142
+ return `${this.keyPrefix}${KEY}${shopDomain.trim().toLowerCase()}`;
143
+ }
144
+ within(work) {
145
+ let handle;
146
+ const late = new Promise((_, reject) => {
147
+ handle = setTimeout(() => reject(new CommandTimeoutError()), this.commandTimeoutMs);
148
+ });
149
+ work.catch(() => undefined);
150
+ return Promise.race([work, late]).finally(() => clearTimeout(handle));
151
+ }
152
+ failed(error) {
153
+ const at = this.now();
154
+ const away = isAway(error);
155
+ if (away)
156
+ this.coolOffUntil = at + COOL_OFF_MS;
157
+ if (at - this.lastWarnedAt < WARN_EVERY_MS)
158
+ return;
159
+ this.lastWarnedAt = at;
160
+ const fallsBack = this.options.fallback
161
+ ? 'it falls back to its fallback throttle'
162
+ : 'it falls back to each client’s own pacing';
163
+ this.options.logger?.warn({}, away
164
+ ? `The Shopify throttle cannot reach Redis; ${fallsBack}`
165
+ : `The Shopify throttle failed against Redis; ${fallsBack}`);
166
+ }
167
+ coolingOff() {
168
+ return this.now() < this.coolOffUntil;
169
+ }
170
+ async wait(shopDomain, signal) {
171
+ if (signal?.aborted) {
172
+ throw signal.reason ?? new DOMException('The wait was aborted', 'AbortError');
173
+ }
174
+ if (this.coolingOff())
175
+ return this.fallBack(shopDomain, signal);
176
+ const key = this.key(shopDomain);
177
+ let waited = 0;
178
+ while (waited < this.maxWaitMs && !this.coolingOff()) {
179
+ let slot;
180
+ let epoch;
181
+ try {
182
+ const at = this.now();
183
+ const claimed = (await this.within(this.redis.eval(CLAIM_SCRIPT, 1, key, at, DEFAULT_SPACING_MS, TTL_PADDING_MS, this.maxWaitMs - waited)));
184
+ slot = Number(claimed[0]);
185
+ epoch = String(claimed[1]);
186
+ }
187
+ catch (error) {
188
+ this.failed(error);
189
+ return this.fallBack(shopDomain, signal);
190
+ }
191
+ const ms = Math.min(this.maxWaitMs - waited, slot - this.now());
192
+ if (!(ms > 0))
193
+ return;
194
+ // An aborted or re-claiming waiter leaves its claimed slot unused, a gap of one spacing: accepted.
195
+ await this.sleep(ms, signal);
196
+ waited += ms;
197
+ // An answer that came in while this caller slept may have put the start later still.
198
+ try {
199
+ const now = await this.within(this.redis.hget(key, 'epoch'));
200
+ if ((now ?? '0') === epoch)
201
+ return;
202
+ }
203
+ catch (error) {
204
+ this.failed(error);
205
+ return this.fallBack(shopDomain, signal);
206
+ }
207
+ }
208
+ }
209
+ /** Redis away: the fallback paces this call, or nothing does. */
210
+ async fallBack(shopDomain, signal) {
211
+ await this.options.fallback?.wait(shopDomain, signal);
212
+ }
213
+ async report(shopDomain, bucket) {
214
+ if (this.coolingOff()) {
215
+ await this.options.fallback?.report(shopDomain, bucket).catch(() => undefined);
216
+ return;
217
+ }
218
+ const at = this.now();
219
+ const next = nextShopifyStart(bucket, at, this.maxWaitMs, this.reserveShare);
220
+ if (next === null)
221
+ return;
222
+ const cost = bucket.actualQueryCost ?? bucket.requestedQueryCost ?? 0;
223
+ const spacing = Math.min(MAX_SPACING_MS, Math.ceil((cost / bucket.restoreRate) * MS_PER_SECOND));
224
+ try {
225
+ await this.within(this.redis.eval(RAISE_SCRIPT, 1, this.key(shopDomain), next, next - at + TTL_PADDING_MS, spacing));
226
+ }
227
+ catch (error) {
228
+ this.failed(error);
229
+ await this.options.fallback?.report(shopDomain, bucket).catch(() => undefined);
230
+ }
231
+ }
232
+ }
233
+ //# sourceMappingURL=shopify-throttle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shopify-throttle.js","sourceRoot":"","sources":["../src/shopify-throttle.ts"],"names":[],"mappings":"AAsCA,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAClC,MAAM,mBAAmB,GAAG,MAAM,CAAC;AACnC,MAAM,0BAA0B,GAAG,KAAK,CAAC;AACzC,MAAM,aAAa,GAAG,MAAM,CAAC;AAC7B,6DAA6D;AAC7D,MAAM,WAAW,GAAG,MAAM,CAAC;AAC3B,MAAM,aAAa,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AS,CAAC,CAAC;QACjF,CAAC;IACH,CAAC;CACF"}
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@haatlabs-core/rate-limit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.11.0",
4
+ "description": "A Redis token bucket shared by every process.",
5
+ "keywords": [
6
+ "haatlabs",
7
+ "redis"
8
+ ],
9
+ "homepage": "https://haatlabs.shop/docs/packages/rate-limit/",
10
+ "license": "Apache-2.0",
11
+ "type": "module",
12
+ "engines": {
13
+ "node": ">=24"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/Haatlabs/haatlabs-platform.git",
18
+ "directory": "packages/rate-limit"
19
+ },
20
+ "publishConfig": {
21
+ "access": "public",
22
+ "registry": "https://registry.npmjs.org"
23
+ },
24
+ "files": [
25
+ "dist"
26
+ ],
27
+ "exports": {
28
+ ".": {
29
+ "import": {
30
+ "types": "./dist/index.d.ts",
31
+ "default": "./dist/index.js"
32
+ },
33
+ "require": {
34
+ "types": "./dist/cjs/index.d.ts",
35
+ "default": "./dist/cjs/index.js"
36
+ }
37
+ }
38
+ },
39
+ "peerDependencies": {
40
+ "ioredis": "^6.0.0"
41
+ },
42
+ "devDependencies": {
43
+ "@testcontainers/redis": "^12.2.0",
44
+ "ioredis": "^6.0.0",
45
+ "@haatlabs-core/shopify": "0.11.0",
46
+ "@haatlabs-core/tsconfig": "0.11.0",
47
+ "@haatlabs-core/vitest-config": "0.11.0"
48
+ },
49
+ "scripts": {
50
+ "build": "rm -rf dist && tsc -p tsconfig.build.json && node ../../scripts/build-cjs.mjs",
51
+ "typecheck": "tsc --noEmit",
52
+ "test": "vitest run",
53
+ "test:int": "vitest run --config vitest.int.config.ts",
54
+ "check:package": "publint --strict && attw --pack . --profile node16"
55
+ },
56
+ "platformRegistry": "npm"
57
+ }