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

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,33 @@
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.
@@ -0,0 +1,22 @@
1
+ import type { FarmCacheAdapter } from "@farm.js/core/cache";
2
+ export interface FarmRedisClient {
3
+ get(key: string): Promise<string | null>;
4
+ set(key: string, value: string): Promise<unknown>;
5
+ set(key: string, value: string, expiryMode: "PX", ttlMs: number, condition: "NX"): Promise<unknown>;
6
+ del(key: string): Promise<number>;
7
+ incr(key: string): Promise<number>;
8
+ mget?(...keys: string[]): Promise<Array<string | null>>;
9
+ eval(script: string, numberOfKeys: number, ...args: string[]): Promise<unknown>;
10
+ }
11
+ export interface RedisCacheOptions {
12
+ /** Existing Redis-compatible client or a lazy client factory. */
13
+ client: FarmRedisClient | (() => FarmRedisClient | Promise<FarmRedisClient>);
14
+ /** Prefix isolating Farm cache records from other Redis data. */
15
+ prefix?: string;
16
+ }
17
+ /**
18
+ * Create a Redis-backed Farm cache with atomic tag versions and regeneration
19
+ * leases.
20
+ */
21
+ export declare function redisCache(options: RedisCacheOptions): FarmCacheAdapter;
22
+ //# 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;AAE5E,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,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;AASD;;;GAGG;AACH,wBAAgB,UAAU,CAAC,OAAO,EAAE,iBAAiB,GAAG,gBAAgB,CAqEvE"}
package/dist/index.js ADDED
@@ -0,0 +1,91 @@
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
+ /**
8
+ * Create a Redis-backed Farm cache with atomic tag versions and regeneration
9
+ * leases.
10
+ */
11
+ export function redisCache(options) {
12
+ if (!options?.client) {
13
+ throw new TypeError("redisCache requires a Redis-compatible client.");
14
+ }
15
+ const prefix = normalizePrefix(options.prefix || "farm-cache");
16
+ let clientPromise;
17
+ const getClient = () => {
18
+ clientPromise ??= Promise.resolve(typeof options.client === "function" ? options.client() : options.client);
19
+ return clientPromise;
20
+ };
21
+ const key = (value) => `${prefix}:${value}`;
22
+ return {
23
+ name: "redis",
24
+ async get(cacheKey) {
25
+ const serialized = await (await getClient()).get(key(cacheKey));
26
+ if (serialized === null)
27
+ return null;
28
+ try {
29
+ return JSON.parse(serialized);
30
+ }
31
+ catch (error) {
32
+ throw new Error(`Redis cache entry ${JSON.stringify(cacheKey)} is not valid JSON.`, {
33
+ cause: error,
34
+ });
35
+ }
36
+ },
37
+ async set(cacheKey, entry) {
38
+ let serialized;
39
+ try {
40
+ serialized = JSON.stringify(entry);
41
+ }
42
+ catch (error) {
43
+ throw new TypeError(`Redis cache entry ${JSON.stringify(cacheKey)} is not JSON serializable.`, { cause: error });
44
+ }
45
+ await (await getClient()).set(key(cacheKey), serialized);
46
+ },
47
+ async delete(cacheKey) {
48
+ await (await getClient()).del(key(cacheKey));
49
+ },
50
+ async getTagVersions(tags) {
51
+ if (tags.length === 0)
52
+ return {};
53
+ const client = await getClient();
54
+ const keys = tags.map((tag) => key(`tag-version:${tag}`));
55
+ const values = client.mget
56
+ ? await client.mget(...keys)
57
+ : await Promise.all(keys.map((tagKey) => client.get(tagKey)));
58
+ return Object.fromEntries(tags.map((tag, index) => [tag, normalizeVersion(values[index])]));
59
+ },
60
+ async invalidateTags(tags) {
61
+ const client = await getClient();
62
+ await Promise.all(tags.map((tag) => client.incr(key(`tag-version:${tag}`))));
63
+ },
64
+ async acquireLease(leaseKey, ttlMs) {
65
+ const token = createLeaseToken();
66
+ const result = await (await getClient()).set(key(`lease:${leaseKey}`), token, "PX", ttlMs, "NX");
67
+ return result === "OK" ? token : null;
68
+ },
69
+ async releaseLease(leaseKey, token) {
70
+ await (await getClient()).eval(RELEASE_LEASE_SCRIPT, 1, key(`lease:${leaseKey}`), token);
71
+ },
72
+ };
73
+ }
74
+ function normalizePrefix(value) {
75
+ const prefix = value.trim().replace(/:+$/g, "");
76
+ if (!prefix)
77
+ throw new TypeError("redisCache prefix cannot be empty.");
78
+ return prefix;
79
+ }
80
+ function normalizeVersion(value) {
81
+ if (!value)
82
+ return 0;
83
+ const version = Number(value);
84
+ return Number.isSafeInteger(version) && version > 0 ? version : 0;
85
+ }
86
+ function createLeaseToken() {
87
+ if (typeof globalThis.crypto?.randomUUID === "function") {
88
+ return globalThis.crypto.randomUUID();
89
+ }
90
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
91
+ }
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@farm.js/cache-redis",
3
+ "version": "0.1.0-beta.3",
4
+ "description": "Distributed Redis cache adapter for Farm.js",
5
+ "keywords": [
6
+ "cache",
7
+ "farm.js",
8
+ "isr",
9
+ "ppr",
10
+ "redis"
11
+ ],
12
+ "license": "MIT",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/farming-labs/farm.js",
16
+ "directory": "packages/farm-cache-redis"
17
+ },
18
+ "files": [
19
+ "dist"
20
+ ],
21
+ "type": "module",
22
+ "main": "./dist/index.js",
23
+ "module": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js"
29
+ }
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "dependencies": {
35
+ "@farm.js/core": "0.1.0-beta.4"
36
+ },
37
+ "devDependencies": {
38
+ "typescript": "^5.3.3",
39
+ "vitest": "^1.1.0"
40
+ },
41
+ "scripts": {
42
+ "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc",
43
+ "dev": "tsc --watch",
44
+ "type-check": "tsc --noEmit",
45
+ "test": "vitest run"
46
+ }
47
+ }