@farm.js/cache-redis 0.1.0-beta.3 → 0.1.0-beta.31
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/README.md +23 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +57 -3
- package/package.json +6 -4
package/README.md
CHANGED
|
@@ -31,3 +31,26 @@ Application code keeps using the cache APIs from `@farm.js/core/cache`.
|
|
|
31
31
|
|
|
32
32
|
Use a distinct namespace for each application or deployment environment. Do not put
|
|
33
33
|
user-specific values in shared keys unless the key includes the user or tenant identity.
|
|
34
|
+
|
|
35
|
+
## Atomic rate limits
|
|
36
|
+
|
|
37
|
+
KV `get()` followed by `set()` is not safe for enforcing a request limit across concurrent
|
|
38
|
+
instances. Use the dedicated adapter, which increments and expires the counter in one Redis Lua
|
|
39
|
+
operation:
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
import { redisRateLimitStorage } from "@farm.js/cache-redis";
|
|
43
|
+
import { middleware } from "@farm.js/core/middleware";
|
|
44
|
+
import Redis from "ioredis";
|
|
45
|
+
|
|
46
|
+
const rateLimits = redisRateLimitStorage({
|
|
47
|
+
client: () => new Redis(process.env.REDIS_URL!),
|
|
48
|
+
prefix: "storefront-ratelimit",
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
export default middleware().rateLimit({
|
|
52
|
+
requests: 100,
|
|
53
|
+
window: "1m",
|
|
54
|
+
storage: rateLimits,
|
|
55
|
+
});
|
|
56
|
+
```
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { FarmCacheAdapter } from "@farm.js/core/cache";
|
|
2
|
+
import type { RateLimitStorage } from "@farm.js/core/middleware";
|
|
2
3
|
export interface FarmRedisClient {
|
|
3
4
|
get(key: string): Promise<string | null>;
|
|
4
5
|
set(key: string, value: string): Promise<unknown>;
|
|
@@ -8,15 +9,26 @@ export interface FarmRedisClient {
|
|
|
8
9
|
mget?(...keys: string[]): Promise<Array<string | null>>;
|
|
9
10
|
eval(script: string, numberOfKeys: number, ...args: string[]): Promise<unknown>;
|
|
10
11
|
}
|
|
12
|
+
export interface FarmRedisRateLimitClient extends FarmRedisClient {
|
|
13
|
+
pttl(key: string): Promise<number>;
|
|
14
|
+
}
|
|
11
15
|
export interface RedisCacheOptions {
|
|
12
16
|
/** Existing Redis-compatible client or a lazy client factory. */
|
|
13
17
|
client: FarmRedisClient | (() => FarmRedisClient | Promise<FarmRedisClient>);
|
|
14
18
|
/** Prefix isolating Farm cache records from other Redis data. */
|
|
15
19
|
prefix?: string;
|
|
16
20
|
}
|
|
21
|
+
export interface RedisRateLimitOptions {
|
|
22
|
+
/** Existing Redis-compatible client or a lazy client factory. */
|
|
23
|
+
client: FarmRedisRateLimitClient | (() => FarmRedisRateLimitClient | Promise<FarmRedisRateLimitClient>);
|
|
24
|
+
/** Prefix isolating rate-limit counters from other Redis data. */
|
|
25
|
+
prefix?: string;
|
|
26
|
+
}
|
|
17
27
|
/**
|
|
18
28
|
* Create a Redis-backed Farm cache with atomic tag versions and regeneration
|
|
19
29
|
* leases.
|
|
20
30
|
*/
|
|
21
31
|
export declare function redisCache(options: RedisCacheOptions): FarmCacheAdapter;
|
|
32
|
+
/** Create a Redis-backed atomic fixed-window rate-limit store. */
|
|
33
|
+
export declare function redisRateLimitStorage(options: RedisRateLimitOptions): RateLimitStorage;
|
|
22
34
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAkB,MAAM,qBAAqB,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAkB,MAAM,qBAAqB,CA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,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAAC,CAAC;IACzE,kEAAkE;IAClE,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAmBD;;;GAGG;AACH,wBAAgB,UAAU,CAAC,OAAO,EAAE,iBAAiB,GAAG,gBAAgB,CAqEvE;AAED,kEAAkE;AAClE,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,qBAAqB,GAAG,gBAAgB,CAoDtF"}
|
package/dist/index.js
CHANGED
|
@@ -4,6 +4,15 @@ if redis.call("get", KEYS[1]) == ARGV[1] then
|
|
|
4
4
|
end
|
|
5
5
|
return 0
|
|
6
6
|
`;
|
|
7
|
+
const INCREMENT_RATE_LIMIT_SCRIPT = `
|
|
8
|
+
local count = redis.call("INCR", KEYS[1])
|
|
9
|
+
local ttl = redis.call("PTTL", KEYS[1])
|
|
10
|
+
if count == 1 or ttl <= 0 then
|
|
11
|
+
redis.call("PEXPIRE", KEYS[1], ARGV[1])
|
|
12
|
+
ttl = tonumber(ARGV[1])
|
|
13
|
+
end
|
|
14
|
+
return { count, ttl }
|
|
15
|
+
`;
|
|
7
16
|
/**
|
|
8
17
|
* Create a Redis-backed Farm cache with atomic tag versions and regeneration
|
|
9
18
|
* leases.
|
|
@@ -12,7 +21,7 @@ export function redisCache(options) {
|
|
|
12
21
|
if (!options?.client) {
|
|
13
22
|
throw new TypeError("redisCache requires a Redis-compatible client.");
|
|
14
23
|
}
|
|
15
|
-
const prefix = normalizePrefix(options.prefix || "farm-cache");
|
|
24
|
+
const prefix = normalizePrefix(options.prefix || "farm-cache", "redisCache");
|
|
16
25
|
let clientPromise;
|
|
17
26
|
const getClient = () => {
|
|
18
27
|
clientPromise ??= Promise.resolve(typeof options.client === "function" ? options.client() : options.client);
|
|
@@ -71,10 +80,55 @@ export function redisCache(options) {
|
|
|
71
80
|
},
|
|
72
81
|
};
|
|
73
82
|
}
|
|
74
|
-
|
|
83
|
+
/** Create a Redis-backed atomic fixed-window rate-limit store. */
|
|
84
|
+
export function redisRateLimitStorage(options) {
|
|
85
|
+
if (!options?.client) {
|
|
86
|
+
throw new TypeError("redisRateLimitStorage requires a Redis-compatible client.");
|
|
87
|
+
}
|
|
88
|
+
const prefix = normalizePrefix(options.prefix || "farm-ratelimit", "redisRateLimitStorage");
|
|
89
|
+
let clientPromise;
|
|
90
|
+
const getClient = () => {
|
|
91
|
+
clientPromise ??= Promise.resolve(typeof options.client === "function" ? options.client() : options.client);
|
|
92
|
+
return clientPromise;
|
|
93
|
+
};
|
|
94
|
+
const key = (value) => `${prefix}:${value}`;
|
|
95
|
+
return {
|
|
96
|
+
async increment(rateLimitKey, windowMs) {
|
|
97
|
+
if (!Number.isSafeInteger(windowMs) || windowMs <= 0) {
|
|
98
|
+
throw new TypeError("Rate-limit windowMs must be a positive safe integer.");
|
|
99
|
+
}
|
|
100
|
+
const result = await (await getClient()).eval(INCREMENT_RATE_LIMIT_SCRIPT, 1, key(rateLimitKey), String(windowMs));
|
|
101
|
+
if (!Array.isArray(result) || result.length < 2) {
|
|
102
|
+
throw new Error("Redis returned an invalid atomic rate-limit result.");
|
|
103
|
+
}
|
|
104
|
+
const count = Number(result[0]);
|
|
105
|
+
const ttlMs = Number(result[1]);
|
|
106
|
+
if (!Number.isSafeInteger(count) || count <= 0 || !Number.isFinite(ttlMs) || ttlMs <= 0) {
|
|
107
|
+
throw new Error("Redis returned an invalid atomic rate-limit count or expiry.");
|
|
108
|
+
}
|
|
109
|
+
return { count, resetAt: Date.now() + ttlMs };
|
|
110
|
+
},
|
|
111
|
+
async get(rateLimitKey) {
|
|
112
|
+
const client = await getClient();
|
|
113
|
+
const redisKey = key(rateLimitKey);
|
|
114
|
+
const [serializedCount, ttlMs] = await Promise.all([
|
|
115
|
+
client.get(redisKey),
|
|
116
|
+
client.pttl(redisKey),
|
|
117
|
+
]);
|
|
118
|
+
if (serializedCount === null || ttlMs <= 0)
|
|
119
|
+
return null;
|
|
120
|
+
const count = Number(serializedCount);
|
|
121
|
+
if (!Number.isSafeInteger(count) || count <= 0) {
|
|
122
|
+
throw new Error(`Redis rate-limit counter ${JSON.stringify(rateLimitKey)} is invalid.`);
|
|
123
|
+
}
|
|
124
|
+
return { count, resetAt: Date.now() + ttlMs };
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
function normalizePrefix(value, owner) {
|
|
75
129
|
const prefix = value.trim().replace(/:+$/g, "");
|
|
76
130
|
if (!prefix)
|
|
77
|
-
throw new TypeError(
|
|
131
|
+
throw new TypeError(`${owner} prefix cannot be empty.`);
|
|
78
132
|
return prefix;
|
|
79
133
|
}
|
|
80
134
|
function normalizeVersion(value) {
|
package/package.json
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@farm.js/cache-redis",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
4
|
-
"description": "Distributed Redis cache
|
|
3
|
+
"version": "0.1.0-beta.31",
|
|
4
|
+
"description": "Distributed Redis cache and atomic rate-limit adapters for Farm.js",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cache",
|
|
7
7
|
"farm.js",
|
|
8
8
|
"isr",
|
|
9
9
|
"ppr",
|
|
10
|
+
"rate-limit",
|
|
10
11
|
"redis"
|
|
11
12
|
],
|
|
12
13
|
"license": "MIT",
|
|
@@ -32,11 +33,12 @@
|
|
|
32
33
|
"access": "public"
|
|
33
34
|
},
|
|
34
35
|
"dependencies": {
|
|
35
|
-
"@farm.js/core": "0.1.
|
|
36
|
+
"@farm.js/core": "0.1.29"
|
|
36
37
|
},
|
|
37
38
|
"devDependencies": {
|
|
38
39
|
"typescript": "^5.3.3",
|
|
39
|
-
"
|
|
40
|
+
"vite": "8.3.4",
|
|
41
|
+
"vitest": "5.0.5"
|
|
40
42
|
},
|
|
41
43
|
"scripts": {
|
|
42
44
|
"build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc",
|