@h-ai/cache 1.0.0-beta.30 → 1.0.0-beta.32

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.en.md CHANGED
@@ -8,346 +8,31 @@ A unified cache module. The `cache` object provides KV / Hash / List / Set / ZSe
8
8
 
9
9
  ## Quick Start
10
10
 
11
- ```ts
12
- import { cache } from '@h-ai/cache'
13
- import { core } from '@h-ai/core'
11
+ Install with pnpm: `pnpm add @h-ai/cache`.
14
12
 
15
- const initialized = await cache.init({ type: 'redis', host: 'localhost' })
16
- if (!initialized.success)
17
- throw new Error(initialized.error.message)
18
- try {
19
- const written = await cache.kv.set('user:1', { name: 'Alice' }, { ex: 3600 })
20
- if (!written.success)
21
- throw new Error(written.error.message)
22
- const user = await cache.kv.get<{ name: string }>('user:1')
23
- if (!user.success)
24
- throw new Error(user.error.message)
25
- if (user.data)
26
- core.logger.info('Cached user', { name: user.data.name })
27
- }
28
- finally {
29
- const closed = await cache.close()
30
- if (!closed.success)
31
- core.logger.error('Cache cleanup pending', { code: closed.error.code })
32
- }
33
- ```
34
-
35
- `cache.config` returns a **redacted configuration snapshot**. Redis credential fields such as `password` / `url` are sanitized automatically; do not use the snapshot to write back original secrets.
36
-
37
- ## Features
38
-
39
- Memory KV entries expire at their expiration time. `incr/decr/incrBy/decrBy` accept only safe integers or integer strings; invalid increments and overflow return `OPERATION_FAILED` without changing the original value. Hash names such as `__proto__` / `constructor` remain ordinary fields and do not change the returned object's prototype.
40
-
41
- Memory KV, Hash, List, Set, and ZSet share one key namespace. `exists/expire/expireAt/ttl/persist/keys/scan/del/type` cover every structure; structure operations also treat expired keys as absent. del counts logical keys actually removed, and structure operations on another key type fail.
42
-
43
- Connections become available only after a successful health check. Failed initialization disposes its candidate; `error.ext.cleanupPending === true` identifies cleanup that still needs retry. `cache.close()` returns `Promise<HaiResult<void>>`, waits for initialization, and coalesces concurrent close calls. Once cleanup starts, `isInitialized` is false and configuration/operations are unavailable. A failed cleanup retains the resource: the next `close()` or `init()` retries disposal before allocating a replacement. Always inspect the close result.
44
-
45
- ```ts
46
- const closed = await cache.close()
47
- if (!closed.success) {
48
- // Retry once after addressing the cleanup failure; report another failure.
49
- const retried = await cache.close()
50
- if (!retried.success)
51
- throw new Error(retried.error.message)
52
- }
53
- ```
54
-
55
- Redis falls back to disconnect when QUIT fails, and reports success only after releasing the client.
56
-
57
- ### Operations and results
58
-
59
- Use the complete initialization flow in this section first. The host validates and authorizes example business values; check success before reading data from asynchronous domain results. Here void means completion without data, null means absent; synchronous factories/tools return the listed type directly.
60
-
61
- key/keys identify business keys, field/fields hash fields, value/members JSON values; start/stop/index are indexes, min/max score bounds; seconds/ttl/timeout are seconds, timestamp Unix seconds; owner must come from acquire.
62
-
63
- #### cache.kv
64
-
65
- Cache JSON snapshots: get/mget yield values/null in input order; set takes TTL/NX/XX and returns applied boolean; mset takes [key,value][] and yields void.
66
-
67
- | Entry | Input parameters | Successful result | Call example |
68
- | --------------- | ------------------- | ----------------- | ---------------------------------------------------------- |
69
- | `cache.kv.get` | key | `T \| null` | `await cache.kv.get('u:1')` |
70
- | `cache.kv.set` | key, value, options | `boolean` | `await cache.kv.set('u:1', { name: 'Alice' }, { ex: 60 })` |
71
- | `cache.kv.mget` | keys | `(T \| null)[]` | `await cache.kv.mget('u:1', 'u:2')` |
72
- | `cache.kv.mset` | entries | `void` | `await cache.kv.mset([['u:1', { name: 'Alice' }]])` |
73
-
74
- #### cache.kv
75
-
76
- Versioned cross-node commit: key, expected, value and expiry atomically return applied; undefined means absent/delete, a mismatch preserves data and TTL.
77
-
78
- | Entry | Input parameters | Successful result | Call example |
79
- | ------------------------- | ----------------------------- | ----------------- | ------------------------------------------------ |
80
- | `cache.kv.compareAndSwap` | key, expected, value, options | `boolean` | `await cache.kv.compareAndSwap('version', 1, 2)` |
81
-
82
- #### cache.kv
83
-
84
- Manage all structures by key: del/exists take keys and return deleted/existing counts; type takes one key and returns its structure name.
85
-
86
- | Entry | Input parameters | Successful result | Call example |
87
- | ----------------- | ---------------- | ----------------- | ------------------------------------- |
88
- | `cache.kv.del` | keys | `number` | `await cache.kv.del('u:1', 'u:2')` |
89
- | `cache.kv.exists` | keys | `number` | `await cache.kv.exists('u:1', 'u:2')` |
90
- | `cache.kv.type` | key | `string` | `await cache.kv.type('u:1')` |
91
-
92
- #### cache.kv
93
-
94
- Retention: relative seconds, Unix seconds or key set/read/remove TTL. Changes yield boolean; ttl yields seconds (-1 persistent, -2 absent).
95
-
96
- | Entry | Input parameters | Successful result | Call example |
97
- | ------------------- | ---------------- | ----------------- | -------------------------------------------------------------------- |
98
- | `cache.kv.expire` | key, seconds | `boolean` | `await cache.kv.expire('u:1', 60)` |
99
- | `cache.kv.expireAt` | key, timestamp | `boolean` | `await cache.kv.expireAt('u:1', Math.floor(Date.now() / 1000) + 60)` |
100
- | `cache.kv.ttl` | key | `number` | `await cache.kv.ttl('u:1')` |
101
- | `cache.kv.persist` | key | `boolean` | `await cache.kv.persist('u:1')` |
102
-
103
- #### cache.kv
104
-
105
- Counters take a key and optional integer delta and return the new safe integer; invalid type/overflow fails without changing data.
106
-
107
- | Entry | Input parameters | Successful result | Call example |
108
- | ----------------- | ---------------- | ----------------- | ----------------------------------- |
109
- | `cache.kv.incr` | key | `number` | `await cache.kv.incr('hits')` |
110
- | `cache.kv.incrBy` | key, increment | `number` | `await cache.kv.incrBy('hits', 2)` |
111
- | `cache.kv.decr` | key | `number` | `await cache.kv.decr('stock')` |
112
- | `cache.kv.decrBy` | key, decrement | `number` | `await cache.kv.decrBy('stock', 2)` |
113
-
114
- #### cache.kv
115
-
116
- Enumeration: keys takes a glob and yields keys; scan takes an opaque cursor and match/count and yields [nextCursor,keys], without snapshot or uniqueness guarantees.
117
-
118
- | Entry | Input parameters | Successful result | Call example |
119
- | --------------- | ---------------- | -------------------- | -------------------------------------------------------- |
120
- | `cache.kv.keys` | pattern | `string[]` | `await cache.kv.keys('u:*')` |
121
- | `cache.kv.scan` | cursor, options | `[string, string[]]` | `await cache.kv.scan('0', { match: 'u:*', count: 100 })` |
122
-
123
- #### cache.hash
124
-
125
- Field cache accepts key plus fields/object/delta. Reads yield value/null, object, field/value arrays or length; hset/hdel count additions/deletions, hexists yields boolean, hincrBy the new integer.
126
-
127
- | Entry | Input parameters | Successful result | Call example |
128
- | -------------------- | --------------------- | ----------------- | ----------------------------------------------- |
129
- | `cache.hash.hget` | key, field | `T \| null` | `await cache.hash.hget('u:1', 'name')` |
130
- | `cache.hash.hset` | key, field, value | `number` | `await cache.hash.hset('u:1', 'name', 'Alice')` |
131
- | `cache.hash.hdel` | key, fields | `number` | `await cache.hash.hdel('u:1', 'name')` |
132
- | `cache.hash.hexists` | key, field | `boolean` | `await cache.hash.hexists('u:1', 'name')` |
133
- | `cache.hash.hgetall` | key | `T` | `await cache.hash.hgetall('u:1')` |
134
- | `cache.hash.hkeys` | key | `string[]` | `await cache.hash.hkeys('u:1')` |
135
- | `cache.hash.hvals` | key | `T[]` | `await cache.hash.hvals('u:1')` |
136
- | `cache.hash.hlen` | key | `number` | `await cache.hash.hlen('u:1')` |
137
- | `cache.hash.hmget` | key, fields | `(T \| null)[]` | `await cache.hash.hmget('u:1', 'name', 'age')` |
138
- | `cache.hash.hincrBy` | key, field, increment | `number` | `await cache.hash.hincrBy('u:1', 'visits', 1)` |
139
-
140
- #### cache.list
141
-
142
- Ordered queues use key, values and index/range: push returns length, pop/index value/null, range an array, set/trim void. Blocking pops take seconds and keys and return [key,value]/null.
143
-
144
- | Entry | Input parameters | Successful result | Call example |
145
- | ------------------- | ----------------- | --------------------- | ------------------------------------------------- |
146
- | `cache.list.lpush` | key, values | `number` | `await cache.list.lpush('jobs', 'job-1')` |
147
- | `cache.list.rpush` | key, values | `number` | `await cache.list.rpush('jobs', 'job-2')` |
148
- | `cache.list.lpop` | key | `T \| null` | `await cache.list.lpop('jobs')` |
149
- | `cache.list.rpop` | key | `T \| null` | `await cache.list.rpop('jobs')` |
150
- | `cache.list.llen` | key | `number` | `await cache.list.llen('jobs')` |
151
- | `cache.list.lrange` | key, start, stop | `T[]` | `await cache.list.lrange('jobs', 0, 9)` |
152
- | `cache.list.lindex` | key, index | `T \| null` | `await cache.list.lindex('jobs', 0)` |
153
- | `cache.list.lset` | key, index, value | `void` | `await cache.list.lset('jobs', 0, 'replacement')` |
154
- | `cache.list.ltrim` | key, start, stop | `void` | `await cache.list.ltrim('jobs', 0, 99)` |
155
- | `cache.list.blpop` | timeout, keys | `[string, T] \| null` | `await cache.list.blpop(5, 'jobs')` |
156
- | `cache.list.brpop` | timeout, keys | `[string, T] \| null` | `await cache.list.brpop(5, 'jobs')` |
157
-
158
- #### cache.set_
159
-
160
- Deduplication/set operations: key+members add/remove/test with count/boolean; members returns an array, card a count, random/pop a member/array/null by count, intersections/unions/differences take keys and yield arrays.
13
+ [Open the quick-start guide](../../docs/usage/function/cache.en.md#quick-start).
161
14
 
162
- | Entry | Input parameters | Successful result | Call example |
163
- | ------------------------ | ---------------- | ------------------ | ----------------------------------------------- |
164
- | `cache.set_.sadd` | key, members | `number` | `await cache.set_.sadd('roles', 'editor')` |
165
- | `cache.set_.srem` | key, members | `number` | `await cache.set_.srem('roles', 'editor')` |
166
- | `cache.set_.smembers` | key | `T[]` | `await cache.set_.smembers('roles')` |
167
- | `cache.set_.sismember` | key, member | `boolean` | `await cache.set_.sismember('roles', 'editor')` |
168
- | `cache.set_.scard` | key | `number` | `await cache.set_.scard('roles')` |
169
- | `cache.set_.srandmember` | key, count | `T \| T[] \| null` | `await cache.set_.srandmember('roles', 2)` |
170
- | `cache.set_.spop` | key, count | `T \| T[] \| null` | `await cache.set_.spop('roles', 1)` |
171
- | `cache.set_.sinter` | keys | `T[]` | `await cache.set_.sinter('roles:a', 'roles:b')` |
172
- | `cache.set_.sunion` | keys | `T[]` | `await cache.set_.sunion('roles:a', 'roles:b')` |
173
- | `cache.set_.sdiff` | keys | `T[]` | `await cache.set_.sdiff('roles:a', 'roles:b')` |
15
+ ## Configuration Reference
174
16
 
175
- #### cache.zset
17
+ Generated projects define the backend type and Redis connection settings in `config/_cache.yml`. At startup, the application reads the file and passes the settings object to `cache.init(config)`.
176
18
 
177
- Rankings accept members/scores or rank/score ranges; adds/removals yield counts, score/rank number/null, ranges member/scored-object arrays, incrBy the new score, card/count counts.
19
+ See the [configuration reference](../../docs/usage/configuration/cache.en.md) for configuration entry points, defaults, accepted values and when changes take effect.
178
20
 
179
- | Entry | Input parameters | Successful result | Call example |
180
- | ----------------------------- | ---------------------------- | ----------------------- | ------------------------------------------------------------------------- |
181
- | `cache.zset.zadd` | key, members | `number` | `await cache.zset.zadd('scores', { member: 'u1', score: 10 })` |
182
- | `cache.zset.zrem` | key, members | `number` | `await cache.zset.zrem('scores', 'u1')` |
183
- | `cache.zset.zscore` | key, member | `number \| null` | `await cache.zset.zscore('scores', 'u1')` |
184
- | `cache.zset.zrank` | key, member | `number \| null` | `await cache.zset.zrank('scores', 'u1')` |
185
- | `cache.zset.zrevrank` | key, member | `number \| null` | `await cache.zset.zrevrank('scores', 'u1')` |
186
- | `cache.zset.zrange` | key, start, stop, withScores | `string[] \| ZMember[]` | `await cache.zset.zrange('scores', 0, 9, true)` |
187
- | `cache.zset.zrevrange` | key, start, stop, withScores | `string[] \| ZMember[]` | `await cache.zset.zrevrange('scores', 0, 9, true)` |
188
- | `cache.zset.zrangeByScore` | key, min, max, options | `string[] \| ZMember[]` | `await cache.zset.zrangeByScore('scores', 10, 100, { withScores: true })` |
189
- | `cache.zset.zcard` | key | `number` | `await cache.zset.zcard('scores')` |
190
- | `cache.zset.zcount` | key, min, max | `number` | `await cache.zset.zcount('scores', 10, 100)` |
191
- | `cache.zset.zincrBy` | key, increment, member | `number` | `await cache.zset.zincrBy('scores', 5, 'u1')` |
192
- | `cache.zset.zremRangeByRank` | key, start, stop | `number` | `await cache.zset.zremRangeByRank('scores', 0, 9)` |
193
- | `cache.zset.zremRangeByScore` | key, min, max | `number` | `await cache.zset.zremRangeByScore('scores', 0, 10)` |
194
-
195
- #### cache.lock
196
-
197
- Short leases: acquire takes key/TTL and yields owner/null; release/extend require owner and yield boolean; isLocked only observes. A lease does not replace resource-side CAS.
198
-
199
- | Entry | Input parameters | Successful result | Call example |
200
- | --------------------- | ---------------- | ----------------- | ------------------------------------------------ |
201
- | `cache.lock.acquire` | key, options | `string \| null` | `await cache.lock.acquire('daily', { ttl: 30 })` |
202
- | `cache.lock.release` | key, owner | `boolean` | `await cache.lock.release('daily', owner)` |
203
- | `cache.lock.isLocked` | key | `boolean` | `await cache.lock.isLocked('daily')` |
204
- | `cache.lock.extend` | key, ttl, owner | `boolean` | `await cache.lock.extend('daily', 60, owner)` |
205
-
206
- #### cache
207
-
208
- Health check with no arguments; returns the backend response string or a connection failure.
209
-
210
- | Entry | Input parameters | Successful result | Call example |
211
- | ------------ | ---------------- | ----------------- | -------------------- |
212
- | `cache.ping` | No arguments | `string` | `await cache.ping()` |
213
-
214
- - In-memory caching for development and tests
215
- - Redis caching in production (standalone, URL, Cluster, Sentinel)
216
- - Set caches for IAM sessions and permissions
217
- - Distributed locks for mutual exclusion across nodes
218
-
219
- ### Initialization options
220
-
221
- ```ts
222
- // Memory(开发/测试)
223
- await cache.init({ type: 'memory' })
224
-
225
- // Redis 单机
226
- await cache.init({
227
- type: 'redis',
228
- host: 'localhost',
229
- port: 6379,
230
- password: 'secret',
231
- db: 0,
232
- })
233
-
234
- // Redis URL(优先级最高)
235
- await cache.init({
236
- type: 'redis',
237
- url: 'redis://:password@localhost:6379/0',
238
- })
239
-
240
- // Redis 集群
241
- await cache.init({
242
- type: 'redis',
243
- cluster: [
244
- { host: 'node1', port: 6379 },
245
- { host: 'node2', port: 6379 },
246
- ],
247
- })
248
-
249
- // Redis 哨兵
250
- await cache.init({
251
- type: 'redis',
252
- sentinel: {
253
- sentinels: [
254
- { host: 'sentinel1', port: 26379 }
255
- ],
256
- name: 'mymaster',
257
- },
258
- })
259
- ```
260
-
261
- `cache.init(config)` selects the built-in memory/redis backend. Provider implementations are internal; there is no custom backend registration API.
262
-
263
- `password` authenticates standalone, Cluster, and Sentinel data nodes, including discovered/redirected Cluster connections. In `url` mode the credentials in the URL take precedence; the separate password field does not override them.
264
-
265
- ### API overview
266
-
267
- - `cache.kv`: string/object key-value storage and TTL (`set/get/mget/mset/expire/ttl/...`).
268
- - `cache.hash`: hash structures (`hset/hget/hgetall/...`).
269
- - `cache.list`: lists (`lpush/rpush/lpop/rpop/...`).
270
- - `cache.set_`: sets (`sadd/smembers/sismember/...`).
271
- - `cache.zset`: sorted sets (`zadd/zrange/zrevrange/...`).
272
- - `cache.lock`: distributed locks (`acquire/release/isLocked/extend`).
273
-
274
- `kv.set` returns `HaiResult<boolean>`: `data=true` means the write applied. An NX/XX miss returns `success=true,data=false` without changing the value or TTL. Check both fields before issuing tickets, sessions or key registrations. `ex/px/exat/pxat` use seconds, milliseconds, Unix seconds and Unix milliseconds; choose one positive safe integer, excluding `keepTtl=true`. NX and XX are mutually exclusive. Zero, negative, fractional, non-finite or overflowing values return `INVALID_SET_OPTIONS` (`cache:016`) without creating a permanent key. A positive absolute deadline in the past expires immediately. Omitting expiry removes an existing TTL; `keepTtl` retains it and leaves new keys permanent. Both providers store JSON snapshots.
275
-
276
- compareAndSwap atomically compares one JSON value and replaces/deletes it, returning boolean applied. Undefined expected means absent; undefined value deletes; null is a JSON value. px is a positive integer and excludes keepTtl. Omitting expiry persists the replacement; a comparison miss preserves TTL. Use it for shared versioned commits.
277
-
278
- ### Cluster multi-key operations and scanning
279
-
280
- `mget/del/exists` support multiple slots through bounded independent key operations. MGET preserves input order; there is no cross-slot atomicity or snapshot. A failed DEL may already have deleted some keys; retry is idempotent. `mset`, set algebra and multi-key blocking pops require a shared slot; group keys with a common `{hash-tag}` or receive `CROSS_SLOT`. MSET never falls back to partial writes.
281
-
282
- Start `scan` with string `'0'` and pass the returned opaque cursor unchanged. Another application node with the same configuration and topology can continue it. Cluster scans every master. A topology, match or keyPrefix change returns `SCAN_TOPOLOGY_CHANGED`; restart from `'0'`. Returned keys omit keyPrefix, whose glob characters are literal. `keys` follows the same rule and deduplicates. SCAN has no snapshot and may repeat keys; count is a positive integer hint, not an output limit. Invalid cursors/count return `INVALID_SCAN`.
283
-
284
- ### Distributed locks
285
-
286
- Distributed mutual exclusion based on SET NX EX, suitable for deployments across multiple nodes.
287
-
288
- ```ts
289
- // 获取锁(TTL 30 秒,owner 用于标识持有者)
290
- const acquired = await cache.lock.acquire('my-lock', { ttl: 30 })
291
- if (acquired.success && acquired.data) {
292
- try {
293
- // 执行受保护操作
294
- }
295
- finally {
296
- await cache.lock.release('my-lock', acquired.data)
297
- }
298
- }
299
-
300
- // 检查锁状态
301
- const locked = await cache.lock.isLocked('my-lock')
302
-
303
- // 续期锁
304
- if (acquired.success && acquired.data)
305
- await cache.lock.extend('my-lock', 60, acquired.data)
306
- ```
307
-
308
- - **Memory backend**: Map-based storage with TTL expiration.
309
- - **Redis backend**: atomic locking with `SET NX EX`; Lua scripts verify the owner for safe release and renewal.
310
- - `acquire` returns a unique acquisition token, or `null` while occupied. Release/renewal require this token; node IDs and ownerless operations are not supported.
311
-
312
- The owner token only protects lease renewal and release; it is not a resource fencing token. A paused task can resume after expiry. Final writes require CAS, generation predicates or transactional constraints in the resource store; renewal or returning a failure afterwards cannot prevent a stale commit.
313
-
314
- ### Production shared state
315
-
316
- Production requires Redis (including Cluster); memory is for development/explicit tests. Redis errors fail rather than falling back locally. Initialization checks apply when NODE_ENV or HAI_CORE_ENV is production; only explicit HAI_E2E=1/HAI_E2E_MOCK=1 tests are exempt. [State, concurrency and recovery (Chinese)](../../.agents/instructions/distributed-state.md).
317
-
318
- ## Configuration
319
-
320
- Lifecycle: init takes backend/business configuration; use the module only after success. Await close before releasing borrowed dependencies. Follow the quick-start example and public signatures for exact return values.
321
-
322
- The host loads and validates configuration before passing it to this module. Keep secrets in private server environment files. Select the backend, capacity, deadlines and logging for the actual use case; reinitialize and check the result after changes.
323
-
324
- [Per-option purpose, use cases and examples](../../docs/usage/configuration/data.md).
325
-
326
- ## Error Handling
21
+ ## Features
327
22
 
328
- Check result.success for domain operations. Handle failures with the module error definitions and safe messages; retain codes, correlation IDs and sanitized causes in server logs. Synchronous tools, factories, stream iteration and lifecycle calls follow their own signatures. A completed Promise alone is not business success. See each feature for recovery limits.
23
+ [Browse the API list](../../docs/usage/function/cache.en.md#api-reference) for entry points, inputs, results and examples.
329
24
 
330
- All operations return `HaiResult<T>`. Common error codes:
25
+ ## Data Structures
331
26
 
332
- | Error code | code | Description |
333
- | -------------------------------------- | --------------- | ---------------------- |
334
- | `HaiCacheError.CONNECTION_FAILED` | `hai:cache:001` | Connection failed |
335
- | `HaiCacheError.OPERATION_FAILED` | `hai:cache:002` | Operation failed |
336
- | `HaiCacheError.SERIALIZATION_FAILED` | `hai:cache:003` | Serialization failed |
337
- | `HaiCacheError.DESERIALIZATION_FAILED` | `hai:cache:004` | Deserialization failed |
338
- | `HaiCacheError.KEY_NOT_FOUND` | `hai:cache:005` | Key not found |
339
- | `HaiCacheError.TIMEOUT` | `hai:cache:006` | Timeout |
340
- | `HaiCacheError.NOT_INITIALIZED` | `hai:cache:010` | Not initialized |
341
- | `HaiCacheError.UNSUPPORTED_TYPE` | `hai:cache:011` | Unsupported cache type |
342
- | `HaiCacheError.CONFIG_ERROR` | `hai:cache:012` | Invalid configuration |
27
+ See the [data reference](../../docs/usage/data/cache.en.md) for Redis and memory value types, keys, TTL and lock ownership.
343
28
 
344
- ## Development
29
+ ## Development and Testing
345
30
 
346
31
  ```bash
347
32
  pnpm --filter @h-ai/cache test
348
33
  ```
349
34
 
350
- > Redis tests require Docker.
35
+ > Redis integration tests require a Docker API, provided by Docker or Podman with its Docker-compatible API enabled.
351
36
 
352
37
  Public contracts and internal structures include typechecked examples; see the [JSDoc conventions (Chinese)](../../.agents/instructions/module-conventions.md#jsdoc-与示例验证).
353
38