@h-ai/cache 1.0.0-beta.3 → 1.0.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.en.md CHANGED
@@ -4,177 +4,29 @@
4
4
 
5
5
  [Framework home](../../README.en.md) · Related modules: [@h-ai/core](../core/README.en.md)
6
6
 
7
- ## Introduction
8
-
9
7
  A unified cache module. The `cache` object provides KV / Hash / List / Set / ZSet / distributed lock operations with Memory and Redis backends.
10
8
 
11
- 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.
12
-
13
- 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.
14
-
15
- ```ts
16
- const closed = await cache.close()
17
- if (!closed.success) {
18
- // Retry once after addressing the cleanup failure; report another failure.
19
- const retried = await cache.close()
20
- if (!retried.success)
21
- throw new Error(retried.error.message)
22
- }
23
- ```
24
-
25
- Redis falls back to disconnect when QUIT fails, and reports success only after releasing the client.
26
-
27
- ## Core features
28
-
29
- - In-memory caching for development and tests
30
- - Redis caching in production (standalone, URL, Cluster, Sentinel)
31
- - Set caches for IAM sessions and permissions
32
- - Distributed locks for mutual exclusion across nodes
33
-
34
- ## Getting started
35
-
36
- ### Quick start
37
-
38
- ```ts
39
- import { cache } from '@h-ai/cache'
40
- import { core } from '@h-ai/core'
41
-
42
- const initialized = await cache.init({ type: 'redis', host: 'localhost' })
43
- if (!initialized.success)
44
- throw new Error(initialized.error.message)
45
- try {
46
- const written = await cache.kv.set('user:1', { name: 'Alice' }, { ex: 3600 })
47
- if (!written.success)
48
- throw new Error(written.error.message)
49
- const user = await cache.kv.get<{ name: string }>('user:1')
50
- if (!user.success)
51
- throw new Error(user.error.message)
52
- if (user.data)
53
- core.logger.info('Cached user', { name: user.data.name })
54
- }
55
- finally {
56
- const closed = await cache.close()
57
- if (!closed.success)
58
- core.logger.error('Cache cleanup pending', { code: closed.error.code })
59
- }
60
- ```
61
-
62
- `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.
63
-
64
- ### Initialization options
65
-
66
- ```ts
67
- // Memory(开发/测试)
68
- await cache.init({ type: 'memory' })
69
-
70
- // Redis 单机
71
- await cache.init({
72
- type: 'redis',
73
- host: 'localhost',
74
- port: 6379,
75
- password: 'secret',
76
- db: 0,
77
- })
78
-
79
- // Redis URL(优先级最高)
80
- await cache.init({
81
- type: 'redis',
82
- url: 'redis://:password@localhost:6379/0',
83
- })
84
-
85
- // Redis 集群
86
- await cache.init({
87
- type: 'redis',
88
- cluster: [
89
- { host: 'node1', port: 6379 },
90
- { host: 'node2', port: 6379 },
91
- ],
92
- })
93
-
94
- // Redis 哨兵
95
- await cache.init({
96
- type: 'redis',
97
- sentinel: {
98
- sentinels: [{ host: 'sentinel1', port: 26379 }],
99
- name: 'mymaster',
100
- },
101
- })
102
- ```
103
-
104
- `cache.init(config)` selects the built-in memory/redis backend. Provider implementations are internal; there is no custom backend registration API.
105
-
106
- `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.
107
-
108
- ### API overview
9
+ ## Quick Start
109
10
 
110
- - `cache.kv`: string/object key-value storage and TTL (`set/get/mget/mset/expire/ttl/...`).
111
- - `cache.hash`: hash structures (`hset/hget/hgetall/...`).
112
- - `cache.list`: lists (`lpush/rpush/lpop/rpop/...`).
113
- - `cache.set_`: sets (`sadd/smembers/sismember/...`).
114
- - `cache.zset`: sorted sets (`zadd/zrange/zrevrange/...`).
115
- - `cache.lock`: distributed locks (`acquire/release/isLocked/extend`).
11
+ Install with pnpm: `pnpm add @h-ai/cache`.
116
12
 
117
- `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.
118
-
119
- 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.
120
-
121
- ### Cluster multi-key operations and scanning
122
-
123
- `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.
124
-
125
- 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`.
126
-
127
- ### Distributed locks
128
-
129
- Distributed mutual exclusion based on SET NX EX, suitable for deployments across multiple nodes.
130
-
131
- ```ts
132
- // 获取锁(TTL 30 秒,owner 用于标识持有者)
133
- const acquired = await cache.lock.acquire('my-lock', { ttl: 30 })
134
- if (acquired.success && acquired.data) {
135
- try {
136
- // 执行受保护操作
137
- }
138
- finally {
139
- await cache.lock.release('my-lock', acquired.data)
140
- }
141
- }
142
-
143
- // 检查锁状态
144
- const locked = await cache.lock.isLocked('my-lock')
145
-
146
- // 续期锁
147
- if (acquired.success && acquired.data)
148
- await cache.lock.extend('my-lock', 60, acquired.data)
149
- ```
13
+ [Open the quick-start guide](../../docs/usage/function/cache.en.md#quick-start).
150
14
 
151
- - **Memory backend**: Map-based storage with TTL expiration.
152
- - **Redis backend**: atomic locking with `SET NX EX`; Lua scripts verify the owner for safe release and renewal.
153
- - `acquire` returns a unique acquisition token, or `null` while occupied. Release/renewal require this token; node IDs and ownerless operations are not supported.
15
+ ## Configuration Reference
154
16
 
155
- 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.
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)`.
156
18
 
157
- ### Error codes
19
+ See the [configuration reference](../../docs/usage/configuration/cache.en.md) for configuration entry points, defaults, accepted values and when changes take effect.
158
20
 
159
- All operations return `HaiResult<T>`. Common error codes:
21
+ ## Features
160
22
 
161
- | Error code | code | Description |
162
- | -------------------------------------- | --------------- | ---------------------- |
163
- | `HaiCacheError.CONNECTION_FAILED` | `hai:cache:001` | Connection failed |
164
- | `HaiCacheError.OPERATION_FAILED` | `hai:cache:002` | Operation failed |
165
- | `HaiCacheError.SERIALIZATION_FAILED` | `hai:cache:003` | Serialization failed |
166
- | `HaiCacheError.DESERIALIZATION_FAILED` | `hai:cache:004` | Deserialization failed |
167
- | `HaiCacheError.KEY_NOT_FOUND` | `hai:cache:005` | Key not found |
168
- | `HaiCacheError.TIMEOUT` | `hai:cache:006` | Timeout |
169
- | `HaiCacheError.NOT_INITIALIZED` | `hai:cache:010` | Not initialized |
170
- | `HaiCacheError.UNSUPPORTED_TYPE` | `hai:cache:011` | Unsupported cache type |
171
- | `HaiCacheError.CONFIG_ERROR` | `hai:cache:012` | Invalid configuration |
23
+ [Browse the API list](../../docs/usage/function/cache.en.md#api-reference) for entry points, inputs, results and examples.
172
24
 
173
- ## Production shared state
25
+ ## Data Structures
174
26
 
175
- 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)。
27
+ See the [data reference](../../docs/usage/data/cache.en.md) for Redis and memory value types, keys, TTL and lock ownership.
176
28
 
177
- ## Development and testing
29
+ ## Development and Testing
178
30
 
179
31
  ```bash
180
32
  pnpm --filter @h-ai/cache test
package/README.ja.md CHANGED
@@ -4,175 +4,27 @@
4
4
 
5
5
  [フレームワークのホーム](../../README.ja.md) · 関連モジュール:[@h-ai/core](../core/README.ja.md)
6
6
 
7
- ## 概要
8
-
9
7
  統一されたキャッシュモジュールです。`cache` オブジェクトで KV / Hash / List / Set / ZSet / 分散ロックを操作し、メモリーと Redis のバックエンドに対応します。
10
8
 
11
- メモリー KV は有効期限に達した時点で無効になります。`incr/decr/incrBy/decrBy` は安全な整数値または整数文字列のみを受け付け、不正な増分やオーバーフローでは元の値を保持して `OPERATION_FAILED` を返します。Hash の `__proto__` / `constructor` などは通常のフィールドとして保持され、戻り値のオブジェクトのプロトタイプを変更しません。
12
-
13
- 接続はヘルスチェック成功後に公開します。初期化失敗時は候補リソースを解放し、解放にも失敗した場合は初期化エラーの `error.ext.cleanupPending` が `true` になります。`cache.close()` は `Promise<HaiResult<void>>` を返し、初期化を待機して並行する終了処理をまとめます。解放開始後は `isInitialized` が `false` となり、設定と操作は利用できません。解放に失敗したリソースは保持され、次の `close()` または `init()` で再試行します。解放が成功するまで代替接続は作成しません。終了結果を必ず確認してください。
14
-
15
- ```ts
16
- const closed = await cache.close()
17
- if (!closed.success) {
18
- // 障害への対処後に一度再試行し、再失敗はアプリへ報告します。
19
- const retried = await cache.close()
20
- if (!retried.success)
21
- throw new Error(retried.error.message)
22
- }
23
- ```
24
-
25
- Redis の QUIT が失敗した場合は disconnect で切断し、解放が完了した場合のみ成功を返します。
26
-
27
- ## 主な機能
28
-
29
- - 開発・テスト用のメモリーキャッシュ
30
- - 本番環境の Redis キャッシュ(単一ノード、URL、Cluster、Sentinel)
31
- - IAM セッション・権限用の集合キャッシュ
32
- - 複数ノード間の排他制御に使う分散ロック
33
-
34
- ## 使い始める
35
-
36
- ### クイックスタート
37
-
38
- ```ts
39
- import { cache } from '@h-ai/cache'
40
- import { core } from '@h-ai/core'
41
-
42
- const initialized = await cache.init({ type: 'redis', host: 'localhost' })
43
- if (!initialized.success)
44
- throw new Error(initialized.error.message)
45
- try {
46
- const written = await cache.kv.set('user:1', { name: 'Alice' }, { ex: 3600 })
47
- if (!written.success)
48
- throw new Error(written.error.message)
49
- const user = await cache.kv.get<{ name: string }>('user:1')
50
- if (!user.success)
51
- throw new Error(user.error.message)
52
- if (user.data)
53
- core.logger.info('Cached user', { name: user.data.name })
54
- }
55
- finally {
56
- const closed = await cache.close()
57
- if (!closed.success)
58
- core.logger.error('Cache cleanup pending', { code: closed.error.code })
59
- }
60
- ```
61
-
62
- `cache.config` は**機密情報をマスクした設定スナップショット**を返します。Redis の `password` / `url` などの認証情報は自動処理されるため、元の秘密情報を書き戻す用途には使わないでください。
63
-
64
- ### 初期化設定
65
-
66
- ```ts
67
- // Memory(开发/测试)
68
- await cache.init({ type: 'memory' })
69
-
70
- // Redis 单机
71
- await cache.init({
72
- type: 'redis',
73
- host: 'localhost',
74
- port: 6379,
75
- password: 'secret',
76
- db: 0,
77
- })
78
-
79
- // Redis URL(优先级最高)
80
- await cache.init({
81
- type: 'redis',
82
- url: 'redis://:password@localhost:6379/0',
83
- })
84
-
85
- // Redis 集群
86
- await cache.init({
87
- type: 'redis',
88
- cluster: [
89
- { host: 'node1', port: 6379 },
90
- { host: 'node2', port: 6379 },
91
- ],
92
- })
93
-
94
- // Redis 哨兵
95
- await cache.init({
96
- type: 'redis',
97
- sentinel: {
98
- sentinels: [{ host: 'sentinel1', port: 26379 }],
99
- name: 'mymaster',
100
- },
101
- })
102
- ```
103
-
104
- `cache.init(config)` は組み込み memory/redis を選択します。Provider は内部契約であり、独自バックエンドの登録 API はありません。
105
-
106
- `password` は単独・Cluster・Sentinel のデータノードに使用され、発見・リダイレクト後の接続にも適用します。`url` 指定時は URL 内の認証情報を使用し、独立した password フィールドでは上書きしません。
107
-
108
- ### API 一覧
9
+ ## クイックスタート
109
10
 
110
- - `cache.kv`:文字列・オブジェクトのキーと値、および TTL(`set/get/mget/mset/expire/ttl/...`)。
111
- - `cache.hash`:Hash 構造(`hset/hget/hgetall/...`)。
112
- - `cache.list`:リスト(`lpush/rpush/lpop/rpop/...`)。
113
- - `cache.set_`:集合(`sadd/smembers/sismember/...`)。
114
- - `cache.zset`:ソート済み集合(`zadd/zrange/zrevrange/...`)。
115
- - `cache.lock`:分散ロック(`acquire/release/isLocked/extend`)。
11
+ `pnpm add @h-ai/cache` でインストールします。
116
12
 
117
- `kv.set` は `HaiResult<boolean>` を返し、`data=true` は書き込みの適用を表します。NX/XX が不成立なら `success=true,data=false` となり、値と TTL を変更しません。チケット、セッション、公鍵登録の発行前に両方を確認してください。`ex/px/exat/pxat` の単位は秒、ミリ秒、Unix 秒、Unix ミリ秒です。正の安全な整数を一つだけ指定し、`keepTtl=true` と併用できません。NX と XX も排他です。ゼロ、負数、小数、非有限値、オーバーフローは `INVALID_SET_OPTIONS`(`cache:016`)となり、永続キーを作成しません。過去の正の絶対期限は即時失効します。期限を省略すると既存 TTL は削除され、`keepTtl` は既存 TTL を維持します。新規キーは期限なしです。両 provider は JSON スナップショットを保存します。
118
-
119
- compareAndSwap は単一キーの JSON 値を原子的に比較・置換/削除し、適用有無を返します。expected の undefined は不存在、value の undefined は削除、null は JSON 値です。px は正の整数で keepTtl と排他です。期限省略時は永続保存し、不一致なら TTL を変更しません。
120
-
121
- ### Cluster の複数キー操作と走査
122
-
123
- `mget/del/exists` は slot ごとの独立操作を有界並行実行し、MGET は入力順序を維持します。slot 間の原子性やスナップショットは提供しません。DEL の失敗時は一部削除済みの場合があり、再試行は冪等です。`mset`、集合演算、複数キーの blocking pop は同一 slot が必要です。共通の `{hash-tag}` を使わない場合は `CROSS_SLOT` を返し、MSET の部分書き込みは行いません。
124
-
125
- `scan` は文字列 `'0'` で開始し、不透明な返却カーソルをそのまま渡します。同じ設定とトポロジーなら別のアプリケーションノードで継続できます。Cluster の全 master を走査し、トポロジー・match・keyPrefix が変わると `SCAN_TOPOLOGY_CHANGED` を返すため `'0'` から再開します。返却キーから keyPrefix を除去し、prefix の glob 文字はリテラルとして扱います。`keys` も同じ規則で重複を除去します。SCAN はスナップショットではなく重複を許容し、count は正の整数の目安です。無効なカーソル/count は `INVALID_SCAN` を返します。
126
-
127
- ### 分散ロック
128
-
129
- SET NX EX を利用する分散排他ロックで、複数ノードのデプロイに適しています。
130
-
131
- ```ts
132
- // 获取锁(TTL 30 秒,owner 用于标识持有者)
133
- const acquired = await cache.lock.acquire('my-lock', { ttl: 30 })
134
- if (acquired.success && acquired.data) {
135
- try {
136
- // 执行受保护操作
137
- }
138
- finally {
139
- await cache.lock.release('my-lock', acquired.data)
140
- }
141
- }
142
-
143
- // 检查锁状态
144
- const locked = await cache.lock.isLocked('my-lock')
145
-
146
- // 续期锁
147
- if (acquired.success && acquired.data)
148
- await cache.lock.extend('my-lock', 60, acquired.data)
149
- ```
13
+ [最小構成の導入手順](../../docs/usage/function/cache.ja.md#quick-start)を参照してください。
150
14
 
151
- - **Memory バックエンド**:Map と TTL による有効期限管理。
152
- - **Redis バックエンド**:`SET NX EX` でアトミックにロックを取得。Lua スクリプトで owner を検証して安全に解除・延長します。
153
- - `acquire` は取得ごとの一意なトークン(競合時は `null`)を返します。解除・延長にはこのトークンが必須です。ノード ID やトークンなしの操作は使用できません。
15
+ ## 設定一覧
154
16
 
155
- owner はリース延長・解除の所有権であり、リソースの fencing token ではありません。停止した処理は期限切れ後も再開できるため、最終書込には保存先の CAS・世代条件・トランザクション制約が必要です。延長や処理後の失敗返却だけでは旧書込を防げません。
17
+ 生成したプロジェクトでは、バックエンドの種類と Redis の接続設定を `config/_cache.yml` に記述します。アプリの起動コードがファイルを読み込み、設定オブジェクトを `cache.init(config)` に渡します。
156
18
 
157
- ### エラーコード
19
+ 設定の入口、既定値、指定できる値、反映の条件は[設定一覧](../../docs/usage/configuration/cache.ja.md)を参照してください。
158
20
 
159
- すべての操作は `HaiResult<T>` を返します。主なエラーコード:
21
+ ## 機能
160
22
 
161
- | エラーコード | code | 説明 |
162
- | -------------------------------------- | --------------- | ---------------------- |
163
- | `HaiCacheError.CONNECTION_FAILED` | `hai:cache:001` | 接続に失敗 |
164
- | `HaiCacheError.OPERATION_FAILED` | `hai:cache:002` | 操作に失敗 |
165
- | `HaiCacheError.SERIALIZATION_FAILED` | `hai:cache:003` | シリアライズに失敗 |
166
- | `HaiCacheError.DESERIALIZATION_FAILED` | `hai:cache:004` | デシリアライズに失敗 |
167
- | `HaiCacheError.KEY_NOT_FOUND` | `hai:cache:005` | キーが存在しない |
168
- | `HaiCacheError.TIMEOUT` | `hai:cache:006` | タイムアウト |
169
- | `HaiCacheError.NOT_INITIALIZED` | `hai:cache:010` | 未初期化 |
170
- | `HaiCacheError.UNSUPPORTED_TYPE` | `hai:cache:011` | 未対応のキャッシュ種別 |
171
- | `HaiCacheError.CONFIG_ERROR` | `hai:cache:012` | 設定エラー |
23
+ [API 一覧](../../docs/usage/function/cache.ja.md#api-reference)で、呼び出し方、入力、戻り値、使用例を確認できます。
172
24
 
173
- ## 本番の共有状態
25
+ ## データ構造
174
26
 
175
- 本番は Redis(Cluster を含む)が必須です。memory は開発・明示的テスト用であり、Redis 障害時もローカルへフォールバックしません。 NODE_ENV または HAI_CORE_ENV が production の場合、初期化成功前に検証します。明示的な HAI_E2E=1/HAI_E2E_MOCK=1 テストのみ除外します。 [状態・並行制御・復旧範囲(中国語)](../../.agents/instructions/distributed-state.md)。
27
+ Redis とメモリの値型、キー、TTL、ロック所有者については[データ構造](../../docs/usage/data/cache.ja.md)を参照してください。
176
28
 
177
29
  ## 開発とテスト
178
30
 
package/README.md CHANGED
@@ -4,186 +4,27 @@
4
4
 
5
5
  [框架首页](../../README.md) · 相关模块:[@h-ai/core](../core/README.md)
6
6
 
7
- ## 简介
8
-
9
7
  统一缓存模块,通过 `cache` 对象提供 KV / Hash / List / Set / ZSet / 分布式锁 操作,支持内存与 Redis 两种后端。
10
8
 
11
- 内存 KV 在到期时间点即视为失效;`incr/decr/incrBy/decrBy` 只接受安全整数数值或整数字符串,非法增量和溢出返回 `OPERATION_FAILED` 并保留原值。Hash 的 `__proto__` / `constructor` 等名称按普通字段保留,不修改返回对象原型。
12
-
13
- 初始化只在健康检查成功后发布连接;失败时释放候选资源。若清理仍失败,初始化错误的 `error.ext.cleanupPending` 为 `true`。`cache.close()` 返回 `Promise<HaiResult<void>>`,等待正在进行的初始化,并合并并发关闭。开始清理后 `isInitialized` 为 `false`,配置与业务操作不再可用;清理失败仍保留资源,后续 `close()` 或 `init()` 先重试释放,成功前不会创建替代连接。调用方必须检查关闭结果。
14
-
15
- ```ts
16
- const closed = await cache.close()
17
- if (!closed.success) {
18
- // 处理清理故障后有限重试;再次失败应向应用报告。
19
- const retried = await cache.close()
20
- if (!retried.success)
21
- throw new Error(retried.error.message)
22
- }
23
- ```
24
-
25
- Redis 的 QUIT 失败后会强制 disconnect;只有实际释放成功才报告关闭成功。
26
-
27
- ## 核心功能清单
28
-
29
- - 开发/测试场景下的内存缓存
30
- - 生产环境 Redis 缓存(单机、URL、集群、哨兵)
31
- - IAM 会话与权限相关的集合缓存
32
- - 分布式锁(多节点部署互斥控制)
33
-
34
- ## 使用入门
35
-
36
- ### 快速开始
37
-
38
- ```ts
39
- import { cache } from '@h-ai/cache'
40
- import { core } from '@h-ai/core'
41
-
42
- const initialized = await cache.init({ type: 'redis', host: 'localhost' })
43
- if (!initialized.success)
44
- throw new Error(initialized.error.message)
45
- try {
46
- const written = await cache.kv.set('user:1', { name: 'Alice' }, { ex: 3600 })
47
- if (!written.success)
48
- throw new Error(written.error.message)
49
- const user = await cache.kv.get<{ name: string }>('user:1')
50
- if (!user.success)
51
- throw new Error(user.error.message)
52
- if (user.data)
53
- core.logger.info('Cached user', { name: user.data.name })
54
- }
55
- finally {
56
- const closed = await cache.close()
57
- if (!closed.success)
58
- core.logger.error('Cache cleanup pending', { code: closed.error.code })
59
- }
60
- ```
61
-
62
- `cache.config` 返回的是**脱敏后的配置快照**:如后续接入 Redis `password` / `url` 等凭证字段,会自动做安全处理,不应用作回写原始密钥。
63
-
64
- ### 初始化配置
65
-
66
- ```ts
67
- // Memory(开发/测试)
68
- await cache.init({ type: 'memory' })
69
-
70
- // Redis 单机
71
- await cache.init({
72
- type: 'redis',
73
- host: 'localhost',
74
- port: 6379,
75
- password: 'secret',
76
- db: 0,
77
- })
78
-
79
- // Redis URL(优先级最高)
80
- await cache.init({
81
- type: 'redis',
82
- url: 'redis://:password@localhost:6379/0',
83
- })
84
-
85
- // Redis 集群
86
- await cache.init({
87
- type: 'redis',
88
- cluster: [
89
- { host: 'node1', port: 6379 },
90
- { host: 'node2', port: 6379 },
91
- ],
92
- })
93
-
94
- // Redis 哨兵
95
- await cache.init({
96
- type: 'redis',
97
- sentinel: {
98
- sentinels: [{ host: 'sentinel1', port: 26379 }],
99
- name: 'mymaster',
100
- },
101
- })
102
- ```
103
-
104
- 内置后端由 `cache.init(config)` 选择 memory/redis;Provider 实现是内部契约,不提供自定义后端注册入口。
105
-
106
- `password` 用于单机、Cluster 与 Sentinel 数据节点;Cluster 发现和重定向后的节点连接也携带密码。配置 `url` 时采用 URL 自身的认证信息,独立 password 字段不覆盖它。
107
-
108
- ### API 概览
109
-
110
- - `cache.kv`: 字符串/对象键值与 TTL(`set/get/mget/mset/expire/ttl/...`)
111
- - `cache.hash`: 哈希结构(`hset/hget/hgetall/...`)
112
- - `cache.list`: 列表结构(`lpush/rpush/lpop/rpop/...`)
113
- - `cache.set_`: 集合结构(`sadd/smembers/sismember/...`)
114
- - `cache.zset`: 有序集合(`zadd/zrange/zrevrange/...`)
115
- - `cache.lock`: 分布式锁(`acquire/release/isLocked/extend`)
9
+ ## 快速开始
116
10
 
117
- `kv.set` 返回 `HaiResult<boolean>`:`data=true` 表示实际写入,NX/XX 未命中返回 `success=true,data=false` 且不改变原值或 TTL。签发票据、会话或登记公钥前必须检查这两个字段。`ex/px/exat/pxat` 分别使用秒、毫秒、Unix 秒、Unix 毫秒,须为正安全整数且只能指定一种,与 `keepTtl=true` 互斥;`nx/xx` 也互斥。零、负数、小数、非有限值或溢出返回 `INVALID_SET_OPTIONS`(`cache:016`),不会写成永久键。过去的正绝对时间表示立即过期。省略期限会移除原 TTL;`keepTtl` 保留已有 TTL,新键仍永久保存。memory 和 Redis 都保存 JSON 快照。
11
+ 使用 pnpm 安装:`pnpm add @h-ai/cache`。
118
12
 
119
- compareAndSwap 对一个 key 原子比较 JSON 值并替换/删除,返回 boolean applied;expected=undefined 表示不存在,value=undefined 表示删除,null 是实际 JSON 值。px 必须为正整数且与 keepTtl 互斥,省略过期策略会持久保存;比较失败不改 TTL。可用于跨节点版本提交,不能把进程锁当作提交条件。
120
-
121
- ### Cluster 多键与扫描
122
-
123
- `mget/del/exists` 支持跨 slot,按独立 key 有界执行,mget 保留输入顺序;不提供跨 slot 的原子性或快照。DEL 失败可能已有部分键被删除,重试幂等。`mset`、集合交/并/差和多键阻塞弹出要求同 slot;用共同的 `{hash-tag}` 分组,否则返回 `CROSS_SLOT`,MSET 不进行部分写入。
124
-
125
- `scan` 首次传字符串 `'0'`,返回不透明字符串游标,可在配置和拓扑一致的不同应用节点继续。Cluster 遍历全部主节点;拓扑、match 或 keyPrefix 变化返回 `SCAN_TOPOLOGY_CHANGED`,调用方从 `'0'` 重新遍历。返回 key 已去除 keyPrefix,前缀中的 glob 字符按字面量匹配;`keys` 也遵循此规则并去重。SCAN 无快照,允许重复项,count 是正整数提示值,不保证返回条数。无效游标/count 返回 `INVALID_SCAN`。
126
-
127
- ```ts
128
- let cursor = '0'
129
- do {
130
- const page = await cache.kv.scan(cursor, { match: 'users:*', count: 100 })
131
- if (!page.success)
132
- throw new Error(page.error.message)
133
- cursor = page.data[0]
134
- await consume(page.data[1])
135
- } while (cursor !== '0')
136
- ```
137
-
138
- ### 分布式锁
139
-
140
- 基于 SET NX EX 模式实现的分布式互斥锁,适用于多节点部署场景。
141
-
142
- ```ts
143
- // 获取锁(TTL 30 秒,owner 用于标识持有者)
144
- const acquired = await cache.lock.acquire('my-lock', { ttl: 30 })
145
- if (acquired.success && acquired.data) {
146
- try {
147
- // 执行受保护操作
148
- }
149
- finally {
150
- await cache.lock.release('my-lock', acquired.data)
151
- }
152
- }
153
-
154
- // 检查锁状态
155
- const locked = await cache.lock.isLocked('my-lock')
156
-
157
- // 续期锁
158
- if (acquired.success && acquired.data)
159
- await cache.lock.extend('my-lock', 60, acquired.data)
160
- ```
13
+ [跟着最小示例完成接入](../../docs/usage/function/cache.md#quick-start)。
161
14
 
162
- - **Memory 后端**:基于 Map + TTL 过期机制
163
- - **Redis 后端**:使用 `SET NX EX` 原子获锁,Lua 脚本实现 owner 验证的安全释放/续期
164
- - `acquire` 返回本次获锁的唯一凭据,锁占用时为 `null`;释放/续租必须传回该凭据,禁止使用节点 ID 或无凭据强制操作。
15
+ ## 配置清单
165
16
 
166
- owner 只保护锁的续期与释放,不是资源 fencing token。进程暂停或租约到期后旧任务仍能继续;最终写入必须在资源存储中使用 CAS、代际条件或事务约束。续租成功或最后返回失败都不能代替提交条件。
17
+ 生成的项目在 `config/_cache.yml` 中设置后端类型和 Redis 连接参数。应用启动代码读取该文件,把配置对象传给 `cache.init(config)`。
167
18
 
168
- ### 错误码
19
+ 在[模块配置清单](../../docs/usage/configuration/cache.md)中查阅配置入口、默认值、取值限制和生效条件。
169
20
 
170
- 所有操作返回 `HaiResult<T>`,常用错误码如下:
21
+ ## 功能说明
171
22
 
172
- | 错误码 | code | 说明 |
173
- | -------------------------------------- | --------------- | ---------------- |
174
- | `HaiCacheError.CONNECTION_FAILED` | `hai:cache:001` | 连接失败 |
175
- | `HaiCacheError.OPERATION_FAILED` | `hai:cache:002` | 操作失败 |
176
- | `HaiCacheError.SERIALIZATION_FAILED` | `hai:cache:003` | 序列化失败 |
177
- | `HaiCacheError.DESERIALIZATION_FAILED` | `hai:cache:004` | 反序列化失败 |
178
- | `HaiCacheError.KEY_NOT_FOUND` | `hai:cache:005` | 键不存在 |
179
- | `HaiCacheError.TIMEOUT` | `hai:cache:006` | 超时 |
180
- | `HaiCacheError.NOT_INITIALIZED` | `hai:cache:010` | 未初始化 |
181
- | `HaiCacheError.UNSUPPORTED_TYPE` | `hai:cache:011` | 不支持的缓存类型 |
182
- | `HaiCacheError.CONFIG_ERROR` | `hai:cache:012` | 配置错误 |
23
+ [查 API 清单](../../docs/usage/function/cache.md#api-reference),包含调用入口、输入、返回值和用法。
183
24
 
184
- ## 生产共享状态
25
+ ## 数据结构
185
26
 
186
- 生产仅使用 Redis(含 Cluster);memory 只用于开发/明确测试。Redis 故障返回失败,不回退本机缓存。 NODE_ENV 或 HAI_CORE_ENV 为 production 时在初始化发布成功前校验;仅 HAI_E2E=1/HAI_E2E_MOCK=1 明确测试可豁免。 [状态、并发和恢复边界](../../.agents/instructions/distributed-state.md)。
27
+ 查看[数据结构](../../docs/usage/data/cache.md),了解Redis/内存的数据类型、键、TTL 和锁所有者。
187
28
 
188
29
  ## 开发测试
189
30
 
@@ -193,7 +34,7 @@ pnpm --filter @h-ai/cache test
193
34
 
194
35
  > Redis 相关测试需要 Docker 环境。
195
36
 
196
- 公开契约与内部结构均提供可类型检查的示例;见[模块 JSDoc 约定](../../.agents/instructions/module-conventions.md#jsdoc-与示例验证)。
37
+ 公开契约与内部结构均提供可类型检查的示例;见[模块 JSDoc 约定](../../.agents/instructions/module-conventions.md#jsdoc-与示例验证).
197
38
 
198
39
  ## 许可证
199
40
 
package/dist/index.d.ts CHANGED
@@ -668,4 +668,5 @@ interface CacheFunctions extends CacheCompositeOperations {
668
668
  */
669
669
  declare const cache: CacheFunctions;
670
670
 
671
- export { type CacheCompositeOperations, type CacheConfig, type CacheConfigInput, CacheConfigSchema, type CacheFunctions, type CacheValue, type CompareAndSwapOptions, HaiCacheError, type HashOperations, type KvOperations, type ListOperations, type LockOperations, type LockOptions, MemoryConfigSchema, type RedisClusterNode, RedisClusterNodeSchema, RedisConfigSchema, type RedisSentinelConfig, RedisSentinelConfigSchema, type ScanOptions, type SetOperations, type SetOptions, type ZMember, type ZSetOperations, cache };
671
+ export { CacheConfigSchema, HaiCacheError, MemoryConfigSchema, RedisClusterNodeSchema, RedisConfigSchema, RedisSentinelConfigSchema, cache };
672
+ export type { CacheCompositeOperations, CacheConfig, CacheConfigInput, CacheFunctions, CacheValue, CompareAndSwapOptions, HashOperations, KvOperations, ListOperations, LockOperations, LockOptions, RedisClusterNode, RedisSentinelConfig, ScanOptions, SetOperations, SetOptions, ZMember, ZSetOperations };