@farm.js/cache-redis 0.1.0-beta.10

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,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Farm.js Team
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
package/README.md ADDED
@@ -0,0 +1,56 @@
1
+ # @farm.js/cache-redis
2
+
3
+ Redis-backed distributed cache for Farm.js applications. It provides shared cache entries,
4
+ atomic tag invalidation, and ownership-safe regeneration leases across server instances.
5
+
6
+ ## Install
7
+
8
+ ```bash
9
+ pnpm add @farm.js/cache-redis ioredis
10
+ ```
11
+
12
+ ## Configure
13
+
14
+ ```ts
15
+ import { redisCache } from "@farm.js/cache-redis";
16
+ import { defineConfig } from "@farm.js/core";
17
+ import Redis from "ioredis";
18
+
19
+ export default defineConfig({
20
+ cache: {
21
+ adapter: redisCache({
22
+ client: () => new Redis(process.env.REDIS_URL!),
23
+ }),
24
+ namespace: process.env.FARM_CACHE_NAMESPACE || "storefront",
25
+ },
26
+ });
27
+ ```
28
+
29
+ Farm uses the shared adapter for cached queries, ISR and PPR output, and tag/path invalidation.
30
+ Application code keeps using the cache APIs from `@farm.js/core/cache`.
31
+
32
+ Use a distinct namespace for each application or deployment environment. Do not put
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
+ ```
@@ -0,0 +1,34 @@
1
+ import type { FarmCacheAdapter } from "@farm.js/core/cache";
2
+ import type { RateLimitStorage } from "@farm.js/core/middleware";
3
+ export interface FarmRedisClient {
4
+ get(key: string): Promise<string | null>;
5
+ set(key: string, value: string): Promise<unknown>;
6
+ set(key: string, value: string, expiryMode: "PX", ttlMs: number, condition: "NX"): Promise<unknown>;
7
+ del(key: string): Promise<number>;
8
+ incr(key: string): Promise<number>;
9
+ mget?(...keys: string[]): Promise<Array<string | null>>;
10
+ eval(script: string, numberOfKeys: number, ...args: string[]): Promise<unknown>;
11
+ }
12
+ export interface FarmRedisRateLimitClient extends FarmRedisClient {
13
+ pttl(key: string): Promise<number>;
14
+ }
15
+ export interface RedisCacheOptions {
16
+ /** Existing Redis-compatible client or a lazy client factory. */
17
+ client: FarmRedisClient | (() => FarmRedisClient | Promise<FarmRedisClient>);
18
+ /** Prefix isolating Farm cache records from other Redis data. */
19
+ prefix?: string;
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
+ }
27
+ /**
28
+ * Create a Redis-backed Farm cache with atomic tag versions and regeneration
29
+ * leases.
30
+ */
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;
34
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAkB,MAAM,qBAAqB,CAAC;AAC5E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAEjE,MAAM,WAAW,eAAe;IAC9B,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IACzC,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAClD,GAAG,CACD,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,MAAM,EACb,UAAU,EAAE,IAAI,EAChB,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,IAAI,GACd,OAAO,CAAC,OAAO,CAAC,CAAC;IACpB,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAClC,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACnC,IAAI,CAAC,CAAC,GAAG,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC;IACxD,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CACjF;AAED,MAAM,WAAW,wBAAyB,SAAQ,eAAe;IAC/D,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CACpC;AAED,MAAM,WAAW,iBAAiB;IAChC,iEAAiE;IACjE,MAAM,EAAE,eAAe,GAAG,CAAC,MAAM,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC,CAAC;IAC7E,iEAAiE;IACjE,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,qBAAqB;IACpC,iEAAiE;IACjE,MAAM,EACF,wBAAwB,GACxB,CAAC,MAAM,wBAAwB,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 ADDED
@@ -0,0 +1,145 @@
1
+ const RELEASE_LEASE_SCRIPT = `
2
+ if redis.call("get", KEYS[1]) == ARGV[1] then
3
+ return redis.call("del", KEYS[1])
4
+ end
5
+ return 0
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
+ `;
16
+ /**
17
+ * Create a Redis-backed Farm cache with atomic tag versions and regeneration
18
+ * leases.
19
+ */
20
+ export function redisCache(options) {
21
+ if (!options?.client) {
22
+ throw new TypeError("redisCache requires a Redis-compatible client.");
23
+ }
24
+ const prefix = normalizePrefix(options.prefix || "farm-cache", "redisCache");
25
+ let clientPromise;
26
+ const getClient = () => {
27
+ clientPromise ??= Promise.resolve(typeof options.client === "function" ? options.client() : options.client);
28
+ return clientPromise;
29
+ };
30
+ const key = (value) => `${prefix}:${value}`;
31
+ return {
32
+ name: "redis",
33
+ async get(cacheKey) {
34
+ const serialized = await (await getClient()).get(key(cacheKey));
35
+ if (serialized === null)
36
+ return null;
37
+ try {
38
+ return JSON.parse(serialized);
39
+ }
40
+ catch (error) {
41
+ throw new Error(`Redis cache entry ${JSON.stringify(cacheKey)} is not valid JSON.`, {
42
+ cause: error,
43
+ });
44
+ }
45
+ },
46
+ async set(cacheKey, entry) {
47
+ let serialized;
48
+ try {
49
+ serialized = JSON.stringify(entry);
50
+ }
51
+ catch (error) {
52
+ throw new TypeError(`Redis cache entry ${JSON.stringify(cacheKey)} is not JSON serializable.`, { cause: error });
53
+ }
54
+ await (await getClient()).set(key(cacheKey), serialized);
55
+ },
56
+ async delete(cacheKey) {
57
+ await (await getClient()).del(key(cacheKey));
58
+ },
59
+ async getTagVersions(tags) {
60
+ if (tags.length === 0)
61
+ return {};
62
+ const client = await getClient();
63
+ const keys = tags.map((tag) => key(`tag-version:${tag}`));
64
+ const values = client.mget
65
+ ? await client.mget(...keys)
66
+ : await Promise.all(keys.map((tagKey) => client.get(tagKey)));
67
+ return Object.fromEntries(tags.map((tag, index) => [tag, normalizeVersion(values[index])]));
68
+ },
69
+ async invalidateTags(tags) {
70
+ const client = await getClient();
71
+ await Promise.all(tags.map((tag) => client.incr(key(`tag-version:${tag}`))));
72
+ },
73
+ async acquireLease(leaseKey, ttlMs) {
74
+ const token = createLeaseToken();
75
+ const result = await (await getClient()).set(key(`lease:${leaseKey}`), token, "PX", ttlMs, "NX");
76
+ return result === "OK" ? token : null;
77
+ },
78
+ async releaseLease(leaseKey, token) {
79
+ await (await getClient()).eval(RELEASE_LEASE_SCRIPT, 1, key(`lease:${leaseKey}`), token);
80
+ },
81
+ };
82
+ }
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) {
129
+ const prefix = value.trim().replace(/:+$/g, "");
130
+ if (!prefix)
131
+ throw new TypeError(`${owner} prefix cannot be empty.`);
132
+ return prefix;
133
+ }
134
+ function normalizeVersion(value) {
135
+ if (!value)
136
+ return 0;
137
+ const version = Number(value);
138
+ return Number.isSafeInteger(version) && version > 0 ? version : 0;
139
+ }
140
+ function createLeaseToken() {
141
+ if (typeof globalThis.crypto?.randomUUID === "function") {
142
+ return globalThis.crypto.randomUUID();
143
+ }
144
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
145
+ }
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@farm.js/cache-redis",
3
+ "version": "0.1.0-beta.10",
4
+ "description": "Distributed Redis cache and atomic rate-limit adapters for Farm.js",
5
+ "keywords": [
6
+ "cache",
7
+ "farm.js",
8
+ "isr",
9
+ "ppr",
10
+ "rate-limit",
11
+ "redis"
12
+ ],
13
+ "license": "MIT",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "https://github.com/farming-labs/farm.js",
17
+ "directory": "packages/farm-cache-redis"
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "type": "module",
23
+ "main": "./dist/index.js",
24
+ "module": "./dist/index.js",
25
+ "types": "./dist/index.d.ts",
26
+ "exports": {
27
+ ".": {
28
+ "types": "./dist/index.d.ts",
29
+ "import": "./dist/index.js"
30
+ }
31
+ },
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "dependencies": {
36
+ "@farm.js/core": "0.1.6"
37
+ },
38
+ "devDependencies": {
39
+ "typescript": "^5.3.3",
40
+ "vitest": "^3.2.7"
41
+ },
42
+ "scripts": {
43
+ "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc",
44
+ "dev": "tsc --watch",
45
+ "type-check": "tsc --noEmit",
46
+ "test": "vitest run"
47
+ }
48
+ }