@h-ai/cache 1.0.0-beta.30 → 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 +10 -325
- package/README.ja.md +9 -322
- package/README.md +9 -333
- package/package.json +2 -2
package/README.en.md
CHANGED
|
@@ -8,340 +8,25 @@ A unified cache module. The `cache` object provides KV / Hash / List / Set / ZSe
|
|
|
8
8
|
|
|
9
9
|
## Quick Start
|
|
10
10
|
|
|
11
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
23
|
+
[Browse the API list](../../docs/usage/function/cache.en.md#api-reference) for entry points, inputs, results and examples.
|
|
329
24
|
|
|
330
|
-
|
|
25
|
+
## Data Structures
|
|
331
26
|
|
|
332
|
-
|
|
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
|
package/README.ja.md
CHANGED
|
@@ -8,336 +8,23 @@
|
|
|
8
8
|
|
|
9
9
|
## クイックスタート
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
import { cache } from '@h-ai/cache'
|
|
13
|
-
import { core } from '@h-ai/core'
|
|
11
|
+
`pnpm add @h-ai/cache` でインストールします。
|
|
14
12
|
|
|
15
|
-
|
|
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` は**機密情報をマスクした設定スナップショット**を返します。Redis の `password` / `url` などの認証情報は自動処理されるため、元の秘密情報を書き戻す用途には使わないでください。
|
|
36
|
-
|
|
37
|
-
## 機能
|
|
38
|
-
|
|
39
|
-
メモリー KV は有効期限に達した時点で無効になります。`incr/decr/incrBy/decrBy` は安全な整数値または整数文字列のみを受け付け、不正な増分やオーバーフローでは元の値を保持して `OPERATION_FAILED` を返します。Hash の `__proto__` / `constructor` などは通常のフィールドとして保持され、戻り値のオブジェクトのプロトタイプを変更しません。
|
|
40
|
-
|
|
41
|
-
Memory の KV・Hash・List・Set・ZSet は一つの key 名前空間を共有します。`exists/expire/expireAt/ttl/persist/keys/scan/del/type` は全構造を対象とし、期限切れ key は構造操作でも直ちに存在しないものとして扱います。del は実際に削除した論理 key を数え、異なる型の構造操作は失敗します。
|
|
42
|
-
|
|
43
|
-
接続はヘルスチェック成功後に公開します。初期化失敗時は候補リソースを解放し、解放にも失敗した場合は初期化エラーの `error.ext.cleanupPending` が `true` になります。`cache.close()` は `Promise<HaiResult<void>>` を返し、初期化を待機して並行する終了処理をまとめます。解放開始後は `isInitialized` が `false` となり、設定と操作は利用できません。解放に失敗したリソースは保持され、次の `close()` または `init()` で再試行します。解放が成功するまで代替接続は作成しません。終了結果を必ず確認してください。
|
|
44
|
-
|
|
45
|
-
```ts
|
|
46
|
-
const closed = await cache.close()
|
|
47
|
-
if (!closed.success) {
|
|
48
|
-
// 障害への対処後に一度再試行し、再失敗はアプリへ報告します。
|
|
49
|
-
const retried = await cache.close()
|
|
50
|
-
if (!retried.success)
|
|
51
|
-
throw new Error(retried.error.message)
|
|
52
|
-
}
|
|
53
|
-
```
|
|
54
|
-
|
|
55
|
-
Redis の QUIT が失敗した場合は disconnect で切断し、解放が完了した場合のみ成功を返します。
|
|
56
|
-
|
|
57
|
-
### 操作と入出力
|
|
58
|
-
|
|
59
|
-
本節の完全な初期化手順を先に実行します。例の業務値はホストが検証・認可し、非同期領域結果は success を確認してから data を読みます。void はデータなし完了、null は不存在、同期ファクトリー/ツールは表の型を直接返します。
|
|
60
|
-
|
|
61
|
-
key/keys は業務キー、field/fields はハッシュ項目、value/members は JSON 値。start/stop/index は添字、min/max は点数範囲、seconds/ttl/timeout は秒、timestamp は Unix 秒。owner は acquire の戻り値。
|
|
62
|
-
|
|
63
|
-
#### cache.kv
|
|
64
|
-
|
|
65
|
-
JSON スナップショットを保存。get/mget は値/null(入力順)、set は TTL/NX/XX と適用 boolean、mset は [key,value][] から void。
|
|
66
|
-
|
|
67
|
-
| 入口 | 入力引数 | 成功結果 | 呼出し例 |
|
|
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
|
-
ノード間の版付き確定。key・expected・value・期限を原子的に比較し applied を返す。undefined は不存在/削除、不一致時は値と TTL を保持。
|
|
77
|
-
|
|
78
|
-
| 入口 | 入力引数 | 成功結果 | 呼出し例 |
|
|
79
|
-
| ------------------------- | ----------------------------- | --------- | ------------------------------------------------ |
|
|
80
|
-
| `cache.kv.compareAndSwap` | key, expected, value, options | `boolean` | `await cache.kv.compareAndSwap('version', 1, 2)` |
|
|
81
|
-
|
|
82
|
-
#### cache.kv
|
|
83
|
-
|
|
84
|
-
全構造をキー単位で管理。del/exists は複数キーから削除数/存在数、type は単一キーから構造名を返す。
|
|
85
|
-
|
|
86
|
-
| 入口 | 入力引数 | 成功結果 | 呼出し例 |
|
|
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
|
-
保存期限を管理。相対秒・Unix 秒・キーで TTL を設定/照会/解除。変更は boolean、ttl は秒(-1 無期限、-2 不存在)。
|
|
95
|
-
|
|
96
|
-
| 入口 | 入力引数 | 成功結果 | 呼出し例 |
|
|
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
|
-
カウンターはキーと整数増分から更新後の安全な整数を返す。型不正・桁あふれは元値を変更せず失敗。
|
|
106
|
-
|
|
107
|
-
| 入口 | 入力引数 | 成功結果 | 呼出し例 |
|
|
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
|
-
列挙。keys は glob からキー配列、scan は不透明カーソルと match/count から [次カーソル,キー配列]。スナップショット・一意性保証なし。
|
|
117
|
-
|
|
118
|
-
| 入口 | 入力引数 | 成功結果 | 呼出し例 |
|
|
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
|
-
フィールド保存。キーとフィールド/配列/オブジェクト/増分を入力。読取は値/null・オブジェクト・配列・長さ、hset/hdel は件数、hexists は boolean、hincrBy は更新整数。
|
|
126
|
-
|
|
127
|
-
| 入口 | 入力引数 | 成功結果 | 呼出し例 |
|
|
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
|
-
順序キュー。キー・値・添字/範囲を入力し push は長さ、pop/index は値/null、range は配列、set/trim は void。阻塞 pop は秒数とキーから [key,value]/null。
|
|
143
|
-
|
|
144
|
-
| 入口 | 入力引数 | 成功結果 | 呼出し例 |
|
|
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
|
-
重複排除・集合演算。キーと要素の追加/削除/判定は件数/boolean。members は配列、card は数、random/pop は count により要素/配列/null、積/和/差は複数キーから配列。
|
|
13
|
+
[最小構成の導入手順](../../docs/usage/function/cache.ja.md#quick-start)を参照してください。
|
|
161
14
|
|
|
162
|
-
|
|
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
|
+
## 設定一覧
|
|
174
16
|
|
|
175
|
-
|
|
17
|
+
生成したプロジェクトでは、バックエンドの種類と Redis の接続設定を `config/_cache.yml` に記述します。アプリの起動コードがファイルを読み込み、設定オブジェクトを `cache.init(config)` に渡します。
|
|
176
18
|
|
|
177
|
-
|
|
19
|
+
設定の入口、既定値、指定できる値、反映の条件は[設定一覧](../../docs/usage/configuration/cache.ja.md)を参照してください。
|
|
178
20
|
|
|
179
|
-
|
|
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
|
-
短期排他。acquire はキー/TTL から owner/null、release/extend は owner 必須で boolean、isLocked は観測のみ。資源側 CAS の代用ではない。
|
|
198
|
-
|
|
199
|
-
| 入口 | 入力引数 | 成功結果 | 呼出し例 |
|
|
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
|
-
引数なしの健全性確認。バックエンド応答文字列、接続障害は失敗。
|
|
209
|
-
|
|
210
|
-
| 入口 | 入力引数 | 成功結果 | 呼出し例 |
|
|
211
|
-
| ------------ | -------- | -------- | -------------------- |
|
|
212
|
-
| `cache.ping` | 引数なし | `string` | `await cache.ping()` |
|
|
213
|
-
|
|
214
|
-
- 開発・テスト用のメモリーキャッシュ
|
|
215
|
-
- 本番環境の Redis キャッシュ(単一ノード、URL、Cluster、Sentinel)
|
|
216
|
-
- IAM セッション・権限用の集合キャッシュ
|
|
217
|
-
- 複数ノード間の排他制御に使う分散ロック
|
|
218
|
-
|
|
219
|
-
### API 一覧
|
|
220
|
-
|
|
221
|
-
- `cache.kv`:文字列・オブジェクトのキーと値、および TTL(`set/get/mget/mset/expire/ttl/...`)。
|
|
222
|
-
- `cache.hash`:Hash 構造(`hset/hget/hgetall/...`)。
|
|
223
|
-
- `cache.list`:リスト(`lpush/rpush/lpop/rpop/...`)。
|
|
224
|
-
- `cache.set_`:集合(`sadd/smembers/sismember/...`)。
|
|
225
|
-
- `cache.zset`:ソート済み集合(`zadd/zrange/zrevrange/...`)。
|
|
226
|
-
- `cache.lock`:分散ロック(`acquire/release/isLocked/extend`)。
|
|
227
|
-
|
|
228
|
-
`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 スナップショットを保存します。
|
|
229
|
-
|
|
230
|
-
compareAndSwap は単一キーの JSON 値を原子的に比較・置換/削除し、適用有無を返します。expected の undefined は不存在、value の undefined は削除、null は JSON 値です。px は正の整数で keepTtl と排他です。期限省略時は永続保存し、不一致なら TTL を変更しません。
|
|
231
|
-
|
|
232
|
-
### Cluster の複数キー操作と走査
|
|
233
|
-
|
|
234
|
-
`mget/del/exists` は slot ごとの独立操作を有界並行実行し、MGET は入力順序を維持します。slot 間の原子性やスナップショットは提供しません。DEL の失敗時は一部削除済みの場合があり、再試行は冪等です。`mset`、集合演算、複数キーの blocking pop は同一 slot が必要です。共通の `{hash-tag}` を使わない場合は `CROSS_SLOT` を返し、MSET の部分書き込みは行いません。
|
|
235
|
-
|
|
236
|
-
`scan` は文字列 `'0'` で開始し、不透明な返却カーソルをそのまま渡します。同じ設定とトポロジーなら別のアプリケーションノードで継続できます。Cluster の全 master を走査し、トポロジー・match・keyPrefix が変わると `SCAN_TOPOLOGY_CHANGED` を返すため `'0'` から再開します。返却キーから keyPrefix を除去し、prefix の glob 文字はリテラルとして扱います。`keys` も同じ規則で重複を除去します。SCAN はスナップショットではなく重複を許容し、count は正の整数の目安です。無効なカーソル/count は `INVALID_SCAN` を返します。
|
|
237
|
-
|
|
238
|
-
### 分散ロック
|
|
239
|
-
|
|
240
|
-
SET NX EX を利用する分散排他ロックで、複数ノードのデプロイに適しています。
|
|
241
|
-
|
|
242
|
-
```ts
|
|
243
|
-
// 获取锁(TTL 30 秒,owner 用于标识持有者)
|
|
244
|
-
const acquired = await cache.lock.acquire('my-lock', { ttl: 30 })
|
|
245
|
-
if (acquired.success && acquired.data) {
|
|
246
|
-
try {
|
|
247
|
-
// 执行受保护操作
|
|
248
|
-
}
|
|
249
|
-
finally {
|
|
250
|
-
await cache.lock.release('my-lock', acquired.data)
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
// 检查锁状态
|
|
255
|
-
const locked = await cache.lock.isLocked('my-lock')
|
|
256
|
-
|
|
257
|
-
// 续期锁
|
|
258
|
-
if (acquired.success && acquired.data)
|
|
259
|
-
await cache.lock.extend('my-lock', 60, acquired.data)
|
|
260
|
-
```
|
|
261
|
-
|
|
262
|
-
- **Memory バックエンド**:Map と TTL による有効期限管理。
|
|
263
|
-
- **Redis バックエンド**:`SET NX EX` でアトミックにロックを取得。Lua スクリプトで owner を検証して安全に解除・延長します。
|
|
264
|
-
- `acquire` は取得ごとの一意なトークン(競合時は `null`)を返します。解除・延長にはこのトークンが必須です。ノード ID やトークンなしの操作は使用できません。
|
|
265
|
-
|
|
266
|
-
owner はリース延長・解除の所有権であり、リソースの fencing token ではありません。停止した処理は期限切れ後も再開できるため、最終書込には保存先の CAS・世代条件・トランザクション制約が必要です。延長や処理後の失敗返却だけでは旧書込を防げません。
|
|
267
|
-
|
|
268
|
-
### 本番の共有状態
|
|
269
|
-
|
|
270
|
-
本番は Redis(Cluster を含む)が必須です。memory は開発・明示的テスト用であり、Redis 障害時もローカルへフォールバックしません。 NODE_ENV または HAI_CORE_ENV が production の場合、初期化成功前に検証します。明示的な HAI_E2E=1/HAI_E2E_MOCK=1 テストのみ除外します。 [状態・並行制御・復旧範囲(中国語)](../../.agents/instructions/distributed-state.md).
|
|
271
|
-
|
|
272
|
-
## 設定
|
|
273
|
-
|
|
274
|
-
ライフサイクル。init にバックエンド/業務設定を渡し成功後に使用します。借用依存先の解放前に close の完了を待ち、正確な戻り値は例と公開署名に従います。
|
|
275
|
-
|
|
276
|
-
```ts
|
|
277
|
-
// Memory(开发/测试)
|
|
278
|
-
await cache.init({ type: 'memory' })
|
|
279
|
-
|
|
280
|
-
// Redis 单机
|
|
281
|
-
await cache.init({
|
|
282
|
-
type: 'redis',
|
|
283
|
-
host: 'localhost',
|
|
284
|
-
port: 6379,
|
|
285
|
-
password: 'secret',
|
|
286
|
-
db: 0,
|
|
287
|
-
})
|
|
288
|
-
|
|
289
|
-
// Redis URL(优先级最高)
|
|
290
|
-
await cache.init({
|
|
291
|
-
type: 'redis',
|
|
292
|
-
url: 'redis://:password@localhost:6379/0',
|
|
293
|
-
})
|
|
294
|
-
|
|
295
|
-
// Redis 集群
|
|
296
|
-
await cache.init({
|
|
297
|
-
type: 'redis',
|
|
298
|
-
cluster: [
|
|
299
|
-
{ host: 'node1', port: 6379 },
|
|
300
|
-
{ host: 'node2', port: 6379 },
|
|
301
|
-
],
|
|
302
|
-
})
|
|
303
|
-
|
|
304
|
-
// Redis 哨兵
|
|
305
|
-
await cache.init({
|
|
306
|
-
type: 'redis',
|
|
307
|
-
sentinel: {
|
|
308
|
-
sentinels: [
|
|
309
|
-
{ host: 'sentinel1', port: 26379 }
|
|
310
|
-
],
|
|
311
|
-
name: 'mymaster',
|
|
312
|
-
},
|
|
313
|
-
})
|
|
314
|
-
```
|
|
315
|
-
|
|
316
|
-
`cache.init(config)` は組み込み memory/redis を選択します。Provider は内部契約であり、独自バックエンドの登録 API はありません。
|
|
317
|
-
|
|
318
|
-
`password` は単独・Cluster・Sentinel のデータノードに使用され、発見・リダイレクト後の接続にも適用します。`url` 指定時は URL 内の認証情報を使用し、独立した password フィールドでは上書きしません。
|
|
319
|
-
|
|
320
|
-
設定はホストが読込・検証してから渡します。秘密はサーバーの非公開環境に保存し、利用場面に応じてバックエンド・容量・期限・ログを選びます。変更後は再初期化の結果を確認してください。
|
|
321
|
-
|
|
322
|
-
[項目別の用途・適用場面・例](../../docs/usage/configuration/data.md).
|
|
323
|
-
|
|
324
|
-
## エラー処理
|
|
21
|
+
## 機能
|
|
325
22
|
|
|
326
|
-
|
|
23
|
+
[API 一覧](../../docs/usage/function/cache.ja.md#api-reference)で、呼び出し方、入力、戻り値、使用例を確認できます。
|
|
327
24
|
|
|
328
|
-
|
|
25
|
+
## データ構造
|
|
329
26
|
|
|
330
|
-
|
|
331
|
-
| -------------------------------------- | --------------- | ---------------------- |
|
|
332
|
-
| `HaiCacheError.CONNECTION_FAILED` | `hai:cache:001` | 接続に失敗 |
|
|
333
|
-
| `HaiCacheError.OPERATION_FAILED` | `hai:cache:002` | 操作に失敗 |
|
|
334
|
-
| `HaiCacheError.SERIALIZATION_FAILED` | `hai:cache:003` | シリアライズに失敗 |
|
|
335
|
-
| `HaiCacheError.DESERIALIZATION_FAILED` | `hai:cache:004` | デシリアライズに失敗 |
|
|
336
|
-
| `HaiCacheError.KEY_NOT_FOUND` | `hai:cache:005` | キーが存在しない |
|
|
337
|
-
| `HaiCacheError.TIMEOUT` | `hai:cache:006` | タイムアウト |
|
|
338
|
-
| `HaiCacheError.NOT_INITIALIZED` | `hai:cache:010` | 未初期化 |
|
|
339
|
-
| `HaiCacheError.UNSUPPORTED_TYPE` | `hai:cache:011` | 未対応のキャッシュ種別 |
|
|
340
|
-
| `HaiCacheError.CONFIG_ERROR` | `hai:cache:012` | 設定エラー |
|
|
27
|
+
Redis とメモリの値型、キー、TTL、ロック所有者については[データ構造](../../docs/usage/data/cache.ja.md)を参照してください。
|
|
341
28
|
|
|
342
29
|
## 開発とテスト
|
|
343
30
|
|
package/README.md
CHANGED
|
@@ -8,347 +8,23 @@
|
|
|
8
8
|
|
|
9
9
|
## 快速开始
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
import { cache } from '@h-ai/cache'
|
|
13
|
-
import { core } from '@h-ai/core'
|
|
11
|
+
使用 pnpm 安装:`pnpm add @h-ai/cache`。
|
|
14
12
|
|
|
15
|
-
|
|
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` 返回的是**脱敏后的配置快照**:如后续接入 Redis `password` / `url` 等凭证字段,会自动做安全处理,不应用作回写原始密钥。
|
|
36
|
-
|
|
37
|
-
## 功能
|
|
38
|
-
|
|
39
|
-
内存 KV 在到期时间点即视为失效;`incr/decr/incrBy/decrBy` 只接受安全整数数值或整数字符串,非法增量和溢出返回 `OPERATION_FAILED` 并保留原值。Hash 的 `__proto__` / `constructor` 等名称按普通字段保留,不修改返回对象原型。
|
|
40
|
-
|
|
41
|
-
Memory 的 KV、Hash、List、Set、ZSet 共用 key 命名空间。`exists/expire/expireAt/ttl/persist/keys/scan/del/type` 覆盖全部结构,期限到达后结构操作也立即视为不存在;del 按实际删除的逻辑 key 计数,错误类型的结构操作返回失败。
|
|
42
|
-
|
|
43
|
-
初始化只在健康检查成功后发布连接;失败时释放候选资源。若清理仍失败,初始化错误的 `error.ext.cleanupPending` 为 `true`。`cache.close()` 返回 `Promise<HaiResult<void>>`,等待正在进行的初始化,并合并并发关闭。开始清理后 `isInitialized` 为 `false`,配置与业务操作不再可用;清理失败仍保留资源,后续 `close()` 或 `init()` 先重试释放,成功前不会创建替代连接。调用方必须检查关闭结果。
|
|
44
|
-
|
|
45
|
-
```ts
|
|
46
|
-
const closed = await cache.close()
|
|
47
|
-
if (!closed.success) {
|
|
48
|
-
// 处理清理故障后有限重试;再次失败应向应用报告。
|
|
49
|
-
const retried = await cache.close()
|
|
50
|
-
if (!retried.success)
|
|
51
|
-
throw new Error(retried.error.message)
|
|
52
|
-
}
|
|
53
|
-
```
|
|
54
|
-
|
|
55
|
-
Redis 的 QUIT 失败后会强制 disconnect;只有实际释放成功才报告关闭成功。
|
|
56
|
-
|
|
57
|
-
### 功能输入输出
|
|
58
|
-
|
|
59
|
-
以下片段依赖本节完整初始化流程。示例中的业务值由宿主校验和授权后传入;异步领域结果先判断 success,再读取 data。表中 void 表示操作已完成且没有返回数据,null 表示不存在;同步工厂/工具直接返回表中类型。
|
|
60
|
-
|
|
61
|
-
key/keys 是业务键,field/fields 是哈希字段,value/members 为 JSON 值;start/stop/index 为下标,min/max 为分数边界;seconds/ttl/timeout 为秒,timestamp 为 Unix 秒;owner 只能使用 acquire 返回值。
|
|
62
|
-
|
|
63
|
-
#### cache.kv
|
|
64
|
-
|
|
65
|
-
缓存 JSON 快照。get/mget 返回值或 null(批量保序);set 输入期限/NX/XX,返回实际写入 boolean;mset 接收 [key,value][] 返回 void。
|
|
66
|
-
|
|
67
|
-
| 入口 | 输入参数 | 成功结果 | 调用示例 |
|
|
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
|
-
跨节点版本提交。key、expected、value 加期限选项原子比较后返回 applied;undefined 代表不存在/删除,比较失败不改原值或 TTL。
|
|
77
|
-
|
|
78
|
-
| 入口 | 输入参数 | 成功结果 | 调用示例 |
|
|
79
|
-
| ------------------------- | ----------------------------- | --------- | ------------------------------------------------ |
|
|
80
|
-
| `cache.kv.compareAndSwap` | key, expected, value, options | `boolean` | `await cache.kv.compareAndSwap('version', 1, 2)` |
|
|
81
|
-
|
|
82
|
-
#### cache.kv
|
|
83
|
-
|
|
84
|
-
按 key 管理全部数据结构;del/exists 输入一个或多个键,返回删除/存在数;type 输入单键返回结构类型。
|
|
85
|
-
|
|
86
|
-
| 入口 | 输入参数 | 成功结果 | 调用示例 |
|
|
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
|
-
控制保存期限;相对秒数、Unix 秒数或键分别设置/查询/移除 TTL。修改返回 boolean,ttl 返回秒数(-1 无期限、-2 不存在)。
|
|
95
|
-
|
|
96
|
-
| 入口 | 输入参数 | 成功结果 | 调用示例 |
|
|
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
|
-
计数器输入 key 和可选整数增量,返回新安全整数;类型不符或溢出失败且不修改原值。
|
|
106
|
-
|
|
107
|
-
| 入口 | 输入参数 | 成功结果 | 调用示例 |
|
|
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
|
-
运维遍历。keys 接收 glob 返回键数组;scan 接收不透明游标和 match/count,返回 [新游标,键数组],不保证快照或无重复。
|
|
117
|
-
|
|
118
|
-
| 入口 | 输入参数 | 成功结果 | 调用示例 |
|
|
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
|
-
字段缓存输入 key、field/fields/对象或增量。读取返回值/null、对象、字段/值数组或长度;hset/hdel 返回新增/删除数,hexists 返回 boolean,hincrBy 返回新整数。
|
|
126
|
-
|
|
127
|
-
| 入口 | 输入参数 | 成功结果 | 调用示例 |
|
|
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
|
-
有序队列输入 key、值、索引/区间;push 返回长度,pop/index 返回值/null,range 返回数组,set/trim 返回 void。阻塞 pop 输入秒数与键,返回 [key,value]/null。
|
|
143
|
-
|
|
144
|
-
| 入口 | 输入参数 | 成功结果 | 调用示例 |
|
|
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
|
-
去重/集合运算。key+成员用于增删/成员判定,返回数量/boolean;members 返回数组,card 返回基数,random/pop 按 count 返回成员/数组/null,交并差接收多个键返回数组。
|
|
161
|
-
|
|
162
|
-
| 入口 | 输入参数 | 成功结果 | 调用示例 |
|
|
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')` |
|
|
174
|
-
|
|
175
|
-
#### cache.zset
|
|
176
|
-
|
|
177
|
-
排行榜输入成员及 score、排序范围或分数范围;新增/删除返回数量,score/rank 返回数字/null,range 返回成员或带分数对象数组,incrBy 返回新分数,card/count 返回数量。
|
|
178
|
-
|
|
179
|
-
| 入口 | 输入参数 | 成功结果 | 调用示例 |
|
|
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
|
-
短期互斥。acquire 输入键/TTL 返回 owner 或 null;release/extend 必须传 owner,返回 boolean;isLocked 仅观察占用。锁不替代业务存储的 CAS。
|
|
198
|
-
|
|
199
|
-
| 入口 | 输入参数 | 成功结果 | 调用示例 |
|
|
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
|
-
健康检查,无参数;返回后端响应字符串,连接故障为失败。
|
|
209
|
-
|
|
210
|
-
| 入口 | 输入参数 | 成功结果 | 调用示例 |
|
|
211
|
-
| ------------ | -------- | -------- | -------------------- |
|
|
212
|
-
| `cache.ping` | 无参数 | `string` | `await cache.ping()` |
|
|
213
|
-
|
|
214
|
-
- 开发/测试场景下的内存缓存
|
|
215
|
-
- 生产环境 Redis 缓存(单机、URL、集群、哨兵)
|
|
216
|
-
- IAM 会话与权限相关的集合缓存
|
|
217
|
-
- 分布式锁(多节点部署互斥控制)
|
|
218
|
-
|
|
219
|
-
### API 概览
|
|
220
|
-
|
|
221
|
-
- `cache.kv`: 字符串/对象键值与 TTL(`set/get/mget/mset/expire/ttl/...`)
|
|
222
|
-
- `cache.hash`: 哈希结构(`hset/hget/hgetall/...`)
|
|
223
|
-
- `cache.list`: 列表结构(`lpush/rpush/lpop/rpop/...`)
|
|
224
|
-
- `cache.set_`: 集合结构(`sadd/smembers/sismember/...`)
|
|
225
|
-
- `cache.zset`: 有序集合(`zadd/zrange/zrevrange/...`)
|
|
226
|
-
- `cache.lock`: 分布式锁(`acquire/release/isLocked/extend`)
|
|
227
|
-
|
|
228
|
-
`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 快照。
|
|
229
|
-
|
|
230
|
-
compareAndSwap 对一个 key 原子比较 JSON 值并替换/删除,返回 boolean applied;expected=undefined 表示不存在,value=undefined 表示删除,null 是实际 JSON 值。px 必须为正整数且与 keepTtl 互斥,省略过期策略会持久保存;比较失败不改 TTL。可用于跨节点版本提交,不能把进程锁当作提交条件。
|
|
231
|
-
|
|
232
|
-
### Cluster 多键与扫描
|
|
233
|
-
|
|
234
|
-
`mget/del/exists` 支持跨 slot,按独立 key 有界执行,mget 保留输入顺序;不提供跨 slot 的原子性或快照。DEL 失败可能已有部分键被删除,重试幂等。`mset`、集合交/并/差和多键阻塞弹出要求同 slot;用共同的 `{hash-tag}` 分组,否则返回 `CROSS_SLOT`,MSET 不进行部分写入。
|
|
235
|
-
|
|
236
|
-
`scan` 首次传字符串 `'0'`,返回不透明字符串游标,可在配置和拓扑一致的不同应用节点继续。Cluster 遍历全部主节点;拓扑、match 或 keyPrefix 变化返回 `SCAN_TOPOLOGY_CHANGED`,调用方从 `'0'` 重新遍历。返回 key 已去除 keyPrefix,前缀中的 glob 字符按字面量匹配;`keys` 也遵循此规则并去重。SCAN 无快照,允许重复项,count 是正整数提示值,不保证返回条数。无效游标/count 返回 `INVALID_SCAN`。
|
|
237
|
-
|
|
238
|
-
```ts
|
|
239
|
-
let cursor = '0'
|
|
240
|
-
do {
|
|
241
|
-
const page = await cache.kv.scan(cursor, { match: 'users:*', count: 100 })
|
|
242
|
-
if (!page.success)
|
|
243
|
-
throw new Error(page.error.message)
|
|
244
|
-
cursor = page.data[0]
|
|
245
|
-
await consume(page.data[1])
|
|
246
|
-
} while (cursor !== '0')
|
|
247
|
-
```
|
|
248
|
-
|
|
249
|
-
### 分布式锁
|
|
250
|
-
|
|
251
|
-
基于 SET NX EX 模式实现的分布式互斥锁,适用于多节点部署场景。
|
|
252
|
-
|
|
253
|
-
```ts
|
|
254
|
-
// 获取锁(TTL 30 秒,owner 用于标识持有者)
|
|
255
|
-
const acquired = await cache.lock.acquire('my-lock', { ttl: 30 })
|
|
256
|
-
if (acquired.success && acquired.data) {
|
|
257
|
-
try {
|
|
258
|
-
// 执行受保护操作
|
|
259
|
-
}
|
|
260
|
-
finally {
|
|
261
|
-
await cache.lock.release('my-lock', acquired.data)
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
// 检查锁状态
|
|
266
|
-
const locked = await cache.lock.isLocked('my-lock')
|
|
267
|
-
|
|
268
|
-
// 续期锁
|
|
269
|
-
if (acquired.success && acquired.data)
|
|
270
|
-
await cache.lock.extend('my-lock', 60, acquired.data)
|
|
271
|
-
```
|
|
272
|
-
|
|
273
|
-
- **Memory 后端**:基于 Map + TTL 过期机制
|
|
274
|
-
- **Redis 后端**:使用 `SET NX EX` 原子获锁,Lua 脚本实现 owner 验证的安全释放/续期
|
|
275
|
-
- `acquire` 返回本次获锁的唯一凭据,锁占用时为 `null`;释放/续租必须传回该凭据,禁止使用节点 ID 或无凭据强制操作。
|
|
276
|
-
|
|
277
|
-
owner 只保护锁的续期与释放,不是资源 fencing token。进程暂停或租约到期后旧任务仍能继续;最终写入必须在资源存储中使用 CAS、代际条件或事务约束。续租成功或最后返回失败都不能代替提交条件。
|
|
278
|
-
|
|
279
|
-
### 生产共享状态
|
|
280
|
-
|
|
281
|
-
生产仅使用 Redis(含 Cluster);memory 只用于开发/明确测试。Redis 故障返回失败,不回退本机缓存。 NODE_ENV 或 HAI_CORE_ENV 为 production 时在初始化发布成功前校验;仅 HAI_E2E=1/HAI_E2E_MOCK=1 明确测试可豁免。 [状态、并发和恢复边界](../../.agents/instructions/distributed-state.md).
|
|
282
|
-
|
|
283
|
-
## 配置
|
|
284
|
-
|
|
285
|
-
生命周期:init 输入后端/业务配置,成功后才能使用;close 在释放借用依赖前等待完成。返回值以快速开始示例和公开签名为准。
|
|
286
|
-
|
|
287
|
-
```ts
|
|
288
|
-
// Memory(开发/测试)
|
|
289
|
-
await cache.init({ type: 'memory' })
|
|
290
|
-
|
|
291
|
-
// Redis 单机
|
|
292
|
-
await cache.init({
|
|
293
|
-
type: 'redis',
|
|
294
|
-
host: 'localhost',
|
|
295
|
-
port: 6379,
|
|
296
|
-
password: 'secret',
|
|
297
|
-
db: 0,
|
|
298
|
-
})
|
|
299
|
-
|
|
300
|
-
// Redis URL(优先级最高)
|
|
301
|
-
await cache.init({
|
|
302
|
-
type: 'redis',
|
|
303
|
-
url: 'redis://:password@localhost:6379/0',
|
|
304
|
-
})
|
|
305
|
-
|
|
306
|
-
// Redis 集群
|
|
307
|
-
await cache.init({
|
|
308
|
-
type: 'redis',
|
|
309
|
-
cluster: [
|
|
310
|
-
{ host: 'node1', port: 6379 },
|
|
311
|
-
{ host: 'node2', port: 6379 },
|
|
312
|
-
],
|
|
313
|
-
})
|
|
314
|
-
|
|
315
|
-
// Redis 哨兵
|
|
316
|
-
await cache.init({
|
|
317
|
-
type: 'redis',
|
|
318
|
-
sentinel: {
|
|
319
|
-
sentinels: [
|
|
320
|
-
{ host: 'sentinel1', port: 26379 }
|
|
321
|
-
],
|
|
322
|
-
name: 'mymaster',
|
|
323
|
-
},
|
|
324
|
-
})
|
|
325
|
-
```
|
|
326
|
-
|
|
327
|
-
内置后端由 `cache.init(config)` 选择 memory/redis;Provider 实现是内部契约,不提供自定义后端注册入口。
|
|
13
|
+
[跟着最小示例完成接入](../../docs/usage/function/cache.md#quick-start)。
|
|
328
14
|
|
|
329
|
-
|
|
15
|
+
## 配置清单
|
|
330
16
|
|
|
331
|
-
|
|
17
|
+
生成的项目在 `config/_cache.yml` 中设置后端类型和 Redis 连接参数。应用启动代码读取该文件,把配置对象传给 `cache.init(config)`。
|
|
332
18
|
|
|
333
|
-
[
|
|
19
|
+
在[模块配置清单](../../docs/usage/configuration/cache.md)中查阅配置入口、默认值、取值限制和生效条件。
|
|
334
20
|
|
|
335
|
-
##
|
|
21
|
+
## 功能说明
|
|
336
22
|
|
|
337
|
-
|
|
23
|
+
[查 API 清单](../../docs/usage/function/cache.md#api-reference),包含调用入口、输入、返回值和用法。
|
|
338
24
|
|
|
339
|
-
|
|
25
|
+
## 数据结构
|
|
340
26
|
|
|
341
|
-
|
|
342
|
-
| -------------------------------------- | --------------- | ---------------- |
|
|
343
|
-
| `HaiCacheError.CONNECTION_FAILED` | `hai:cache:001` | 连接失败 |
|
|
344
|
-
| `HaiCacheError.OPERATION_FAILED` | `hai:cache:002` | 操作失败 |
|
|
345
|
-
| `HaiCacheError.SERIALIZATION_FAILED` | `hai:cache:003` | 序列化失败 |
|
|
346
|
-
| `HaiCacheError.DESERIALIZATION_FAILED` | `hai:cache:004` | 反序列化失败 |
|
|
347
|
-
| `HaiCacheError.KEY_NOT_FOUND` | `hai:cache:005` | 键不存在 |
|
|
348
|
-
| `HaiCacheError.TIMEOUT` | `hai:cache:006` | 超时 |
|
|
349
|
-
| `HaiCacheError.NOT_INITIALIZED` | `hai:cache:010` | 未初始化 |
|
|
350
|
-
| `HaiCacheError.UNSUPPORTED_TYPE` | `hai:cache:011` | 不支持的缓存类型 |
|
|
351
|
-
| `HaiCacheError.CONFIG_ERROR` | `hai:cache:012` | 配置错误 |
|
|
27
|
+
查看[数据结构](../../docs/usage/data/cache.md),了解Redis/内存的数据类型、键、TTL 和锁所有者。
|
|
352
28
|
|
|
353
29
|
## 开发测试
|
|
354
30
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@h-ai/cache",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "1.0.0-beta.
|
|
4
|
+
"version": "1.0.0-beta.31",
|
|
5
5
|
"description": "Hai Framework cache module with memory and Redis backends.",
|
|
6
6
|
"license": "Apache-2.0",
|
|
7
7
|
"exports": {
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"node": "^22.23.4 || ^24.22.1 || ^26.12.1"
|
|
24
24
|
},
|
|
25
25
|
"dependencies": {
|
|
26
|
-
"@h-ai/core": "1.0.0-beta.
|
|
26
|
+
"@h-ai/core": "1.0.0-beta.31",
|
|
27
27
|
"ioredis": "^6.0.0",
|
|
28
28
|
"zod": "^4.6.7"
|
|
29
29
|
},
|