@frogbotai/kv-redis 0.21.0 → 0.23.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/README.md CHANGED
@@ -2,13 +2,17 @@
2
2
 
3
3
  Redis KV store adapter for [FrogBot](https://github.com/frogbotai/frogbot).
4
4
 
5
+ `frogbot.kv` provides key-value storage, expiration, atomic claims, and ownership-checked locks. It uses your application database by default; Redis is optional.
6
+
5
7
  ## Installation
6
8
 
7
9
  ```bash
8
10
  pnpm add @frogbotai/kv-redis
9
11
  ```
10
12
 
11
- ## Usage
13
+ ## Redis configuration
14
+
15
+ Use Redis 6.2 or newer with Lua scripting enabled for TTL and lock operations.
12
16
 
13
17
  ```ts
14
18
  import { buildConfig } from 'frogbot';
@@ -17,7 +21,105 @@ import { redisKVAdapter } from '@frogbotai/kv-redis';
17
21
  export default buildConfig({
18
22
  kv: redisKVAdapter({
19
23
  redisURL: process.env.REDIS_URL,
24
+ keyPrefix: 'my-app:kv:',
20
25
  }),
21
- // ...rest of config
22
26
  });
23
27
  ```
28
+
29
+ `redisURL` defaults to `REDIS_URL`. `keyPrefix` isolates keys in a shared Redis database. The adapter keeps its existing configuration and public `RedisKVAdapter.redisClient` (an ioredis client); atomic operations use that same connection. The `frogbot.kv` facade exposes the storage and lock API, not the Redis client.
30
+
31
+ ## Database configuration
32
+
33
+ Omit `kv` to use FrogBot's database KV adapter. To customize its collection, use `databaseKVAdapter` from `frogbot/kv` (also exported from `frogbot`):
34
+
35
+ ```ts
36
+ import { buildConfig } from 'frogbot';
37
+ import { databaseKVAdapter } from 'frogbot/kv';
38
+
39
+ export default buildConfig({
40
+ kv: databaseKVAdapter({
41
+ kvCollectionOverrides: {
42
+ slug: 'app-kv',
43
+ dbName: 'app_kv_records',
44
+ },
45
+ }),
46
+ });
47
+ ```
48
+
49
+ The factory supplies required `key` (unique text) and `data` (JSON) fields, plus an indexed, nullable `expiresAt` date. Overrides must keep these fields stored and non-localized; `expiresAt` cannot have a default. Additional required fields need defaults compatible with native writes.
50
+
51
+ ### Supported backends
52
+
53
+ | Backend | TTL, atomic claims, and locks | Expiration clock |
54
+ | ---------------------------------------------------- | ----------------------------------------------- | ---------------------------- |
55
+ | PostgreSQL via `@frogbotai/db-postgres` | Supported | Database `clock_timestamp()` |
56
+ | Local SQLite via `@frogbotai/db-sqlite` | Supported with a `file:` URL and no `syncUrl` | SQLite engine time |
57
+ | MongoDB via `@frogbotai/db-mongodb` | Supported with the requirements below | Database `$$NOW` |
58
+ | Redis via `@frogbotai/kv-redis` | Supported on Redis 6.2+ with scripting | Redis `TIME` |
59
+ | Remote or synced libSQL, D1, Vercel Postgres adapter | Unsupported; ordinary storage remains available | — |
60
+
61
+ MongoDB requires a transaction-capable replica set, automatically generated ObjectId IDs, and a unique, non-partial `key` index with simple collation. These requirements apply to all operations through FrogBot's database KV adapter, including ordinary reads and writes. Custom model defaults must produce valid documents; custom IDs and custom timestamp `currentTime` functions are unsupported. Timestamp field names must not overlap `_id`, `key`, `data`, or `expiresAt`.
62
+
63
+ Explicit third-party KV factories retain their ordinary storage behavior. FrogBot does not probe or automatically upgrade them, even if they use a database collection. TTL writes, `setIfAbsent`, and locks require an adapter that explicitly implements `KVAtomicAdapter` with `[kvAtomic]: true`; otherwise they reject with `KVUnsupportedError`. These exports are available from `frogbot/kv`.
64
+
65
+ ## Storage API
66
+
67
+ All methods are asynchronous. Use string keys and JSON-serializable, non-null values.
68
+
69
+ | Method | Result and behavior |
70
+ | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
71
+ | `get<T>(key)` | `T \| null`; missing or expired entries return `null`. |
72
+ | `set(key, value, { ttl }?)` | `void`; replaces the value. Omitting `ttl` stores it without expiration and removes any previous TTL. |
73
+ | `has(key)` | `boolean`; expired entries return `false`. |
74
+ | `delete(key)` | `void`; removes the entry. |
75
+ | `keys()` | `string[]`; excludes expired entries. |
76
+ | `clear()` | `void`; removes all entries in this KV store, including locks. For Redis, limited to the configured prefix. |
77
+ | `setIfAbsent(key, value, { ttl }?)` | `boolean`; atomically writes only if the key is missing or expired. Returns `true` on success, `false` if a live entry already exists. |
78
+
79
+ ```ts
80
+ await frogbot.kv.set('report:latest', { total: 42 }, { ttl: 60_000 });
81
+ const report = await frogbot.kv.get<{ total: number }>('report:latest');
82
+
83
+ const claimed = await frogbot.kv.setIfAbsent('event:123', true, {
84
+ ttl: 300_000,
85
+ });
86
+ ```
87
+
88
+ TTLs are **milliseconds** and must be positive safe integers. Zero, negative, fractional, non-finite, or unsafe values reject with `RangeError`. A valid integer can still exceed the backend's supported expiration range and be rejected rather than clamped: SQLite supports expiration through year 9999; PostgreSQL, MongoDB, and Redis cap expiration at `8_640_000_000_000_000` milliseconds since the Unix epoch.
89
+
90
+ Expiration uses the backend clock, not the application process's wall clock. An entry is expired at its deadline and immediately counts as absent for reads and claims, even before physical cleanup. Database entries with missing or `null` expiration do not expire.
91
+
92
+ ## Locks
93
+
94
+ Locks share the KV keyspace with stored values. Reserve distinct keys for locks; ordinary `set`, `delete`, or `clear` operations do not check ownership. Processes coordinate only when they share the same store and namespace; separate local SQLite files do not coordinate replicas.
95
+
96
+ | Signature | Behavior |
97
+ | ------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
98
+ | `acquireLock(key: string, ttl: number): Promise<KVLock \| null>` | Claims the key with a unique token; returns `null` on contention. `KVLock` contains readonly `key` and `token` strings. |
99
+ | `extendLock(lock: KVLock, ttl: number): Promise<boolean>` | Sets a fresh TTL from backend time only if the token still owns a live lease. Returns `false` for an expired, missing, or replaced lease. |
100
+ | `releaseLock(lock: KVLock): Promise<boolean>` | Deletes only a live lease with the matching token; otherwise returns `false`. |
101
+ | `lock<T>(key: string, ttl: number, fn: ({ signal }: { signal: AbortSignal }) => T \| Promise<T>): Promise<T>` | Acquires, renews, runs the callback, and attempts ownership-checked release. Returns the callback result on success. |
102
+
103
+ Keep the `KVLock` returned by acquisition for manual extension or release. An expired owner cannot extend or release a successor's lease. `KVLock` and lock error classes are exported from `frogbot/kv`.
104
+
105
+ ### Scoped locks and cancellation
106
+
107
+ ```ts
108
+ const report = await frogbot.kv.lock('lock:report:weekly', 30_000, async ({ signal }) => {
109
+ signal.throwIfAborted();
110
+ const response = await fetch('https://api.example.com/reports/weekly', { signal });
111
+ return response.json();
112
+ });
113
+ ```
114
+
115
+ - Contention rejects immediately with `KVLockContentionError`; the callback does not run and acquisition is not retried.
116
+ - Renewal runs serially, scheduled roughly every `ttl / 3` after acquisition or the previous renewal completes. The TTL is a renewable lease duration, not a total callback timeout.
117
+ - A local monotonic watchdog starts the first deadline **before acquisition**. Each successful renewal sets the next deadline to **renewal request start + TTL**, not response time. Acquisition and renewal latency consume lease time; renewal must succeed before the current deadline. A late response cannot revive a lost scope.
118
+ - A long or hung acquisition, renewal, or release cannot keep the scope waiting past its last confirmed deadline. Deadline or ownership loss aborts `signal` and rejects with `KVLeaseLostError`; renewal backend failures also abort and reject. Multiple observed failures can be reported as an `AggregateError`.
119
+ - Pass `signal` to cancellable work and check it before effects. Ownership tokens protect lock operations; they do **not fence external effects**. A callback that ignores cancellation can continue after the scope rejects, and an event-loop stall delays local abort delivery.
120
+
121
+ ## Expiration cleanup
122
+
123
+ FrogBot's database KV factory registers `frogbot-cleanup-kv` hourly (`0 * * * *`) on the `default` jobs queue. Your existing jobs scheduler and runner must schedule and execute it; KV does not enable `autoRun` or create a separate runner. The task removes expired KV records only. Redis uses native expiration.
124
+
125
+ Cleanup reclaims storage; it is not a correctness dependency. Expired reads, claims, and ownership checks remain correct when cleanup is delayed or the jobs runner is stopped.
package/dist/index.d.ts CHANGED
@@ -1,2 +1,16 @@
1
- export { RedisKVAdapter, redisKVAdapter, type RedisKVAdapterOptions } from '@payloadcms/kv-redis';
1
+ import { RedisKVAdapter as PayloadRedisKVAdapter, type RedisKVAdapterOptions } from '@payloadcms/kv-redis';
2
+ import type { KVAdapterResult, KVStoreValue } from 'frogbot';
3
+ import { kvAtomic, type KVAtomicAdapter, type KVLock, type KVSetOptions } from 'frogbot/kv';
4
+ export type { RedisKVAdapterOptions } from '@payloadcms/kv-redis';
5
+ export declare class RedisKVAdapter extends PayloadRedisKVAdapter implements KVAtomicAdapter {
6
+ readonly [kvAtomic]: true;
7
+ set(key: string, value: KVStoreValue, options?: KVSetOptions): Promise<void>;
8
+ setIfAbsent(key: string, value: KVStoreValue, options?: KVSetOptions): Promise<boolean>;
9
+ extendLock(lock: KVLock, ttl: number): Promise<boolean>;
10
+ releaseLock(lock: KVLock): Promise<boolean>;
11
+ private evalTTL;
12
+ }
13
+ export declare const redisKVAdapter: (options?: RedisKVAdapterOptions) => {
14
+ init: (_args?: Parameters<KVAdapterResult["init"]>[0]) => RedisKVAdapter;
15
+ };
2
16
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,KAAK,qBAAqB,EAAE,MAAM,sBAAsB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,IAAI,qBAAqB,EACvC,KAAK,qBAAqB,EAC3B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAC7D,OAAO,EACL,QAAQ,EACR,KAAK,eAAe,EACpB,KAAK,MAAM,EACX,KAAK,YAAY,EAElB,MAAM,YAAY,CAAC;AAEpB,YAAY,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAgClE,qBAAa,cAAe,SAAQ,qBAAsB,YAAW,eAAe;IAClF,QAAQ,CAAC,CAAC,QAAQ,CAAC,OAAiB;IAErB,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,YAAY,EAAE,OAAO,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC;IAOrF,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,YAAY,EAAE,OAAO,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,OAAO,CAAC;IAUvF,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAIvD,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;YAWnC,OAAO;CAwBtB;AAED,eAAO,MAAM,cAAc,aAAa,qBAAqB;mBAS1C,UAAU,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;CAGxD,CAAC"}
package/dist/index.js CHANGED
@@ -1,2 +1,68 @@
1
- export { RedisKVAdapter, redisKVAdapter } from '@payloadcms/kv-redis';
1
+ import { RedisKVAdapter as PayloadRedisKVAdapter, } from '@payloadcms/kv-redis';
2
+ import { kvAtomic, validateKVTTL, } from 'frogbot/kv';
3
+ const expirationScript = `
4
+ local time = redis.call('TIME')
5
+ local now = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)
6
+ local ttl = tonumber(ARGV[2])
7
+ if ttl > 8640000000000000 - now then return -1 end
8
+ local expiresAt = string.format('%.0f', now + ttl)
9
+ `;
10
+ const setScript = `${expirationScript}
11
+ redis.call('SET', KEYS[1], ARGV[1], 'PXAT', expiresAt)
12
+ return 1
13
+ `;
14
+ const setIfAbsentScript = `${expirationScript}
15
+ if redis.call('SET', KEYS[1], ARGV[1], 'PXAT', expiresAt, 'NX') then return 1 end
16
+ return 0
17
+ `;
18
+ const extendLockScript = `${expirationScript}
19
+ if redis.call('PTTL', KEYS[1]) <= 0 then return 0 end
20
+ if redis.call('GET', KEYS[1]) ~= ARGV[1] then return 0 end
21
+ return redis.call('PEXPIREAT', KEYS[1], expiresAt)
22
+ `;
23
+ const releaseLockScript = `
24
+ if redis.call('PTTL', KEYS[1]) <= 0 then return 0 end
25
+ if redis.call('GET', KEYS[1]) ~= ARGV[1] then return 0 end
26
+ return redis.call('DEL', KEYS[1])
27
+ `;
28
+ export class RedisKVAdapter extends PayloadRedisKVAdapter {
29
+ [kvAtomic] = true;
30
+ async set(key, value, options) {
31
+ if (options?.ttl === undefined) {
32
+ return super.set(key, value);
33
+ }
34
+ await this.evalTTL({ script: setScript, key, value, ttl: options.ttl });
35
+ }
36
+ async setIfAbsent(key, value, options) {
37
+ if (options?.ttl === undefined) {
38
+ return ((await this.redisClient.set(`${this.keyPrefix}${key}`, JSON.stringify(value), 'NX')) ===
39
+ 'OK');
40
+ }
41
+ return this.evalTTL({ script: setIfAbsentScript, key, value, ttl: options.ttl });
42
+ }
43
+ async extendLock(lock, ttl) {
44
+ return this.evalTTL({ script: extendLockScript, key: lock.key, value: lock.token, ttl });
45
+ }
46
+ async releaseLock(lock) {
47
+ return ((await this.redisClient.eval(releaseLockScript, 1, `${this.keyPrefix}${lock.key}`, JSON.stringify(lock.token))) === 1);
48
+ }
49
+ async evalTTL({ script, key, value, ttl, }) {
50
+ validateKVTTL(ttl);
51
+ const result = await this.redisClient.eval(script, 1, `${this.keyPrefix}${key}`, JSON.stringify(value), ttl);
52
+ if (result === -1) {
53
+ throw new RangeError('KV ttl expiration exceeds the supported date range');
54
+ }
55
+ return result === 1;
56
+ }
57
+ }
58
+ export const redisKVAdapter = (options = {}) => {
59
+ const keyPrefix = options.keyPrefix ?? 'payload-kv:';
60
+ const redisURL = options.redisURL ?? process.env.REDIS_URL;
61
+ if (!redisURL) {
62
+ throw new Error('redisURL or REDIS_URL env variable is required');
63
+ }
64
+ return {
65
+ init: (_args) => new RedisKVAdapter(keyPrefix, redisURL),
66
+ };
67
+ };
2
68
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,cAAc,EAA8B,MA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AAS,IAAI,aAAa,CAAC;IACrD,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC;IAE3D,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;IACpE,CAAC;IAED,OAAO;QACL,IAAI,EAAE,CAAC,KAA8C,EAAE,EAAE,CACvD,IAAI,cAAc,CAAC,SAAS,EAAE,QAAQ,CAAC;KAC1C,CAAC;AACJ,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@frogbotai/kv-redis",
3
- "version": "0.21.0",
3
+ "version": "0.23.0",
4
4
  "description": "Redis KV store adapter for FrogBot.",
5
5
  "license": "MIT",
6
6
  "author": "Colby Gilbert",
@@ -25,14 +25,14 @@
25
25
  ],
26
26
  "sideEffects": false,
27
27
  "dependencies": {
28
- "@payloadcms/kv-redis": "3.85.1"
28
+ "@payloadcms/kv-redis": "3.88.0"
29
29
  },
30
30
  "peerDependencies": {
31
- "frogbot": "0.21.0"
31
+ "frogbot": "0.23.0"
32
32
  },
33
33
  "devDependencies": {
34
34
  "typescript": "5.6.2",
35
- "frogbot": "0.21.0"
35
+ "frogbot": "0.23.0"
36
36
  },
37
37
  "publishConfig": {
38
38
  "access": "public"