@hile/ioredis 2.0.2 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/AI.md +350 -0
  2. package/README.md +43 -46
  3. package/package.json +5 -4
package/AI.md ADDED
@@ -0,0 +1,350 @@
1
+ # AI Guide For @hile/ioredis
2
+
3
+
4
+
5
+ <!-- Generated by scripts/build-ai-context.mjs from docs/ai. Do not edit by hand. -->
6
+
7
+
8
+
9
+ Purpose: Create Redis clients manually or as Hile services with lifecycle cleanup.
10
+
11
+
12
+
13
+ Use this file when an AI agent installs the npm package and needs package-local examples, package selection rules, boundaries, and verification steps.
14
+
15
+
16
+
17
+ ## Package Selection
18
+
19
+
20
+
21
+ | User asks for | Use | Also read |
22
+ |---|---|---|
23
+ | Connect to Redis | `@hile/ioredis` | `packages/core-lifecycle.md`, `packages/infrastructure.md` |
24
+
25
+
26
+
27
+ # Core Lifecycle, Bootstrap, CLI, Logger, Redis, TypeORM
28
+
29
+ Packages: `@hile/core`, `@hile/bootstrap`, `@hile/cli`, `@hile/logger`, `@hile/ioredis`, `@hile/typeorm`.
30
+
31
+ ## Use When
32
+
33
+ Use these packages when an app needs managed startup, singleton resources, dependency ordering, environment-file loading, graceful shutdown, logs, Redis, or SQL database connections.
34
+
35
+ ## Do Not Use When
36
+
37
+ - Do not use `loadService()` at module top level.
38
+ - Do not use `auto_load_packages` for file paths. It accepts package names only.
39
+ - Do not use the default `@hile/ioredis` or `@hile/typeorm` services when one app needs multiple Redis or database connections; define separate services with separate keys.
40
+
41
+ ## Install
42
+
43
+ ```bash
44
+ pnpm add @hile/core @hile/logger @hile/ioredis @hile/typeorm
45
+ pnpm add -D @hile/cli
46
+ ```
47
+
48
+ ## Imports
49
+
50
+ ```ts
51
+ import { defineService, loadService, container } from '@hile/core'
52
+ import { createLogger } from '@hile/logger'
53
+ import redisService, { createRedis } from '@hile/ioredis'
54
+ import typeormService, { createDataSource, transaction } from '@hile/typeorm'
55
+ ```
56
+
57
+ ## Copy-Paste Example
58
+
59
+ ```ts
60
+ // src/services/http.boot.ts
61
+ import { defineService } from '@hile/core'
62
+ import { Http } from '@hile/http'
63
+
64
+ export default defineService('http', async (shutdown) => {
65
+ const http = new Http({ port: Number(process.env.HTTP_PORT ?? 3000) })
66
+ await http.load(new URL('../controllers', import.meta.url).pathname)
67
+ const close = await http.listen()
68
+ shutdown(close)
69
+ return http
70
+ })
71
+ ```
72
+
73
+ Run:
74
+
75
+ ```bash
76
+ hile start --dev --env-file .env
77
+ ```
78
+
79
+ ## More Examples
80
+
81
+ Use `package.json` auto-load for integration services that default-export a Hile service:
82
+
83
+ ```json
84
+ {
85
+ "type": "module",
86
+ "scripts": {
87
+ "dev": "hile start --dev --env-file .env",
88
+ "start": "hile start --env-file .env.prod"
89
+ },
90
+ "hile": {
91
+ "auto_load_packages": ["@hile/logger", "@hile/ioredis", "@hile/typeorm"]
92
+ }
93
+ }
94
+ ```
95
+
96
+ Inside another service, load dependencies:
97
+
98
+ ```ts
99
+ import { defineService, loadService } from '@hile/core'
100
+ import redisService from '@hile/ioredis'
101
+ import typeormService from '@hile/typeorm'
102
+
103
+ export default defineService('user.service', async () => {
104
+ const [redis, ds] = await Promise.all([
105
+ loadService(redisService),
106
+ loadService(typeormService),
107
+ ])
108
+ return { redis, ds }
109
+ })
110
+ ```
111
+
112
+ ## Compose With
113
+
114
+ - Use `@hile/http` boot services to start APIs.
115
+ - Use `@hile/model` services arrays to load TypeORM or Redis for business logic.
116
+ - Use `@hile/cache`, `@hile/redis-lock`, queues, rate limits, and idempotency with a Redis client from `@hile/ioredis`.
117
+
118
+ ## Runtime And Lifecycle Notes
119
+
120
+ - `defineService(key, fn)` registers a service factory and does not execute it.
121
+ - `loadService(service)` executes the factory on first call and returns the cached value afterwards.
122
+ - The `shutdown` callback registers teardown functions; they run in LIFO order.
123
+ - The container tracks dependencies when service factories call `loadService()`.
124
+ - `container.shutdown()` triggers registered teardowns.
125
+ - `@hile/bootstrap` loads env files first, sets `NODE_ENV`, imports auto-load packages, scans boot files, and installs exit hooks.
126
+ - `@hile/logger.createLogger()` returns `{ logger, teardown }`.
127
+ - `@hile/ioredis.createRedis()` waits for `connect`.
128
+ - `@hile/typeorm.createDataSource()` initializes a TypeORM `DataSource`.
129
+
130
+ ## Anti-Patterns
131
+
132
+ - Reusing one service key for unrelated factories.
133
+ - Missing `shutdown()` callbacks for network connections or servers.
134
+ - Assuming TypeORM env config fills entities automatically when `TYPEORM_ENTITIES` is not set.
135
+ - Calling `transaction()` and manually committing; the helper commits or rolls back internally.
136
+
137
+ ## Verification Checklist
138
+
139
+ - Boot files default-export `defineService(...)`.
140
+ - Long-lived resources register teardown callbacks.
141
+ - `auto_load_packages` contains package names, not local files.
142
+ - `hile start --dev` can find `src/**/*.boot.ts`.
143
+ - Production build emits `dist/**/*.boot.js`.
144
+
145
+ # Infrastructure Helpers
146
+
147
+ Packages: `@hile/typeorm`, `@hile/ioredis`, `@hile/logger`, `@hile/cache`, `@hile/schedule`, `@hile/loader`.
148
+
149
+ ## Use When
150
+
151
+ Use these packages for database connections, Redis connections, structured logging, typed Redis caches, scheduled jobs, and file-system loaders.
152
+
153
+ ## Do Not Use When
154
+
155
+ - Do not use default TypeORM or Redis services for multiple connections.
156
+ - Do not use `@hile/cache` without returning `new Cache(...)` from the loader function.
157
+ - Do not use `@hile/schedule` distributed mode without Redis lock TTLs sized for job duration.
158
+
159
+ ## Install
160
+
161
+ ```bash
162
+ pnpm add @hile/typeorm @hile/ioredis @hile/logger @hile/cache @hile/schedule @hile/loader
163
+ ```
164
+
165
+ ## Imports
166
+
167
+ ```ts
168
+ import typeormService, { transaction } from '@hile/typeorm'
169
+ import redisService from '@hile/ioredis'
170
+ import { createLogger } from '@hile/logger'
171
+ import { Cache, defineCache, RedisCache } from '@hile/cache'
172
+ import { Scheduler, defineJob } from '@hile/schedule'
173
+ import { scanDirectory, compileRoutePath, toRouterPath, normalizePath, Loader } from '@hile/loader'
174
+ ```
175
+
176
+ ## Copy-Paste Example
177
+
178
+ ```ts
179
+ import { loadService } from '@hile/core'
180
+ import redisService from '@hile/ioredis'
181
+ import { Cache, defineCache, RedisCache } from '@hile/cache'
182
+
183
+ const userProfile = defineCache('user:{id:string}:profile', async ({ id }) => {
184
+ const user = await loadUser(id)
185
+ return new Cache(user).setExpire(300)
186
+ })
187
+
188
+ const redis = await loadService(redisService)
189
+ const cache = new RedisCache('app:', redis)
190
+ const users = await cache.loadCache(userProfile)
191
+ const user = await users.read({ id: 'u1' })
192
+ ```
193
+
194
+ ## More Examples
195
+
196
+ TypeORM transaction with compensation:
197
+
198
+ ```ts
199
+ await transaction(ds, async (runner, rollback) => {
200
+ const user = await runner.manager.save(User, input)
201
+ rollback(() => redis.del(`user:${user.id}`))
202
+ await runner.manager.save(AuditLog, { userId: user.id, action: 'create' })
203
+ return user
204
+ })
205
+ ```
206
+
207
+ Distributed scheduled job:
208
+
209
+ ```ts
210
+ const scheduler = new Scheduler()
211
+ scheduler.add('daily-report', '0 8 * * *', async () => {
212
+ await sendDailyReport()
213
+ }, {
214
+ distributed: {
215
+ redis,
216
+ ttl: 60_000,
217
+ namespace: 'reports',
218
+ policy: 'skip-if-locked',
219
+ },
220
+ })
221
+ ```
222
+
223
+ ## Compose With
224
+
225
+ - Use `RedisCache` with `@hile/ioredis`.
226
+ - Use `defineCache(..., { singleflight: true })` to reduce stampedes; internally it uses Redis locks.
227
+ - Use scheduler distributed mode with `@hile/redis-lock`.
228
+ - Use `Loader` only when building a new file-system based convention.
229
+
230
+ ## Runtime And Lifecycle Notes
231
+
232
+ - `Cache(undefined)` removes the key unless negative caching is configured.
233
+ - `Cache#setExpire(seconds)` uses seconds.
234
+ - `defineCache` typed placeholders support `string`, `number`, and `boolean`.
235
+ - `RedisCache.loadCache()` returns `read`, `write`, `remove`, `has`, and `multi`.
236
+ - `RedisCache.removeTag(tag)` removes tagged cache entries.
237
+ - `fieldable` caches use Redis hashes and cannot combine with stale or negative cache options.
238
+ - `Scheduler.add()` supports cron strings and `{ delay }`.
239
+ - `Scheduler.load()` reads default exports from `*.schedule.*` files produced by `defineJob()`.
240
+ - `scanDirectory()` matches `.ts`, `.js`, `.tsx`, `.jsx`, and `.mjs`.
241
+
242
+ ## Anti-Patterns
243
+
244
+ - Returning raw values from `defineCache` handlers instead of `new Cache(value)`.
245
+ - Treating cache as source of truth.
246
+ - Forgetting to destroy manually created Redis or TypeORM clients.
247
+ - Scheduling jobs without idempotency when side effects can repeat.
248
+
249
+ ## Verification Checklist
250
+
251
+ - Manual Redis clients call `disconnect()` during cleanup.
252
+ - Manual TypeORM data sources call `destroy()` during cleanup.
253
+ - Cache keys include app/tenant prefixes when shared Redis is used.
254
+ - Scheduled jobs have clear duplicate-run policy.
255
+
256
+
257
+
258
+ # Related Recipes
259
+
260
+
261
+
262
+ # Redis Cache With Singleflight
263
+
264
+ ## Complete Example
265
+
266
+ ```ts
267
+ import { loadService } from '@hile/core'
268
+ import redisService from '@hile/ioredis'
269
+ import { Cache, defineCache, RedisCache } from '@hile/cache'
270
+
271
+ const userProfileCache = defineCache(
272
+ 'user:{id:string}:profile',
273
+ async ({ id }) => {
274
+ const profile = await loadProfileFromDatabase(id)
275
+ if (!profile) return new Cache(undefined)
276
+ return new Cache(profile).setExpire(300)
277
+ },
278
+ {
279
+ singleflight: { ttl: 10_000, wait: 10_000 },
280
+ stale: { ttl: 60 },
281
+ negative: { ttl: 30 },
282
+ tags: (params, data) => data ? [`user:${params.id}`] : [],
283
+ },
284
+ )
285
+
286
+ const redis = await loadService(redisService)
287
+ const cache = new RedisCache('app:', redis)
288
+ const userProfiles = await cache.loadCache(userProfileCache)
289
+
290
+ const profile = await userProfiles.read({ id: 'u1' })
291
+ await userProfiles.remove({ id: 'u1' })
292
+ await cache.removeTag('user:u1')
293
+ ```
294
+
295
+ ## File Layout
296
+
297
+ ```text
298
+ src/
299
+ caches/user-profile.cache.ts
300
+ models/users/get-profile.model.ts
301
+ ```
302
+
303
+ ## User Intent
304
+
305
+ Use this recipe when reads are expensive and Redis should provide read-through caching with stampede protection.
306
+
307
+ ## Packages To Use
308
+
309
+ - `@hile/cache`
310
+ - `@hile/ioredis`
311
+ - `@hile/redis-lock` indirectly through cache singleflight
312
+
313
+ ## Implementation Steps
314
+
315
+ 1. Define a typed key with placeholders.
316
+ 2. Return `new Cache(value)` from the loader function.
317
+ 3. Add TTL with `setExpire(seconds)`.
318
+ 4. Enable `singleflight` for expensive reads.
319
+ 5. Remove cache entries after writes.
320
+
321
+ ## Failure And Cleanup Behavior
322
+
323
+ - Stale cache serves previous values while refresh runs.
324
+ - Negative cache stores missing values only when configured.
325
+ - Cache is not source of truth; database writes should remove or refresh related keys.
326
+
327
+ ## Verification Checklist
328
+
329
+ - Cache handler returns `Cache`.
330
+ - Key params match placeholders.
331
+ - Redis prefix is app-specific.
332
+ - Update flows call `remove()` or `removeTag()`.
333
+
334
+
335
+
336
+ # Global Guardrails
337
+
338
+
339
+
340
+ ## Never Generate These Patterns
341
+
342
+ - Do not call `loadService()` at module top level; it starts resources during import.
343
+ - Do not default-export plain functions from `*.boot.*` files; `hile start` expects a Hile service.
344
+ - Do not set `ctx.body` and also return a controller value.
345
+ - Do not assume `@hile/http` Zod validation mutates or coerces `ctx.query`, `ctx.params`, or `ctx.request.body`.
346
+ - Do not put reusable business logic only in controllers, pages, queue workers, or message handlers.
347
+ - Do not use old message examples that append a secondary response getter; current request APIs return promises directly.
348
+ - Do not claim exactly-once delivery or execution from Redis locks, queues, idempotency, or rate limits.
349
+ - Do not use queue `jobId` as the only side-effect idempotency boundary.
350
+ - Do not log the entire async context by default.
package/README.md CHANGED
@@ -1,67 +1,64 @@
1
1
  # @hile/ioredis
2
2
 
3
- 基于 `@hile/core` Redis 集成:将 ioredis 客户端封装为 Hile 服务(单例、可优雅断连)。
3
+ <!-- Generated by scripts/build-ai-context.mjs from docs/ai. Do not edit by hand. -->
4
4
 
5
- ## 安装
5
+ Create Redis clients manually or as Hile services with lifecycle cleanup.
6
6
 
7
- ```bash
8
- pnpm add @hile/ioredis
9
- ```
7
+ This README is intentionally short and example-first. The complete AI-facing guide ships in `AI.md` in this package.
10
8
 
11
- 同时安装依赖:`@hile/core`、`ioredis`。
9
+ ## When To Use
12
10
 
13
- ## 快速开始
11
+ Use these packages when an app needs managed startup, singleton resources, dependency ordering, environment-file loading, graceful shutdown, logs, Redis, or SQL database connections.
14
12
 
15
- ```typescript
16
- import { loadService } from '@hile/core'
17
- import ioredisService from '@hile/ioredis'
13
+ ## Install
18
14
 
19
- const redis = await loadService(ioredisService)
20
- // 使用 redis.get/set 等 ioredis API
15
+ ```bash
16
+ pnpm add @hile/ioredis
21
17
  ```
22
18
 
23
- 默认导出使用稳定的服务 key(实现中为 `Symbol.for` + 包名)。需要多个 Redis 连接时请为每个连接使用不同的 `defineService(key, ...)`。
24
-
25
- ## 环境变量
26
-
27
- 默认客户端从以下环境变量读取配置:
19
+ ## Copy-Paste Example
28
20
 
29
- | 变量 | 说明 |
30
- |------|------|
31
- | `REDIS_HOST` | Redis 主机 |
32
- | `REDIS_PORT` | Redis 端口(字符串会转为数字) |
33
- | `REDIS_USERNAME` | Redis 用户名 |
34
- | `REDIS_PASSWORD` | Redis 密码 |
35
- | `REDIS_DB` | Redis 数据库编号,默认 `0` |
21
+ ```ts
22
+ // src/services/http.boot.ts
23
+ import { defineService } from '@hile/core'
24
+ import { Http } from '@hile/http'
36
25
 
37
- 行为说明:
26
+ export default defineService('http', async (shutdown) => {
27
+ const http = new Http({ port: Number(process.env.HTTP_PORT ?? 3000) })
28
+ await http.load(new URL('../controllers', import.meta.url).pathname)
29
+ const close = await http.listen()
30
+ shutdown(close)
31
+ return http
32
+ })
33
+ ```
38
34
 
39
- - 服务首次加载时创建连接并等待 `connect` 事件
40
- - 进程退出时通过 Hile 的 shutdown 调用 `client.disconnect()`
35
+ Run:
41
36
 
42
- ## 与 @hile/cli 一起使用
37
+ ```bash
38
+ hile start --dev --env-file .env
39
+ ```
43
40
 
44
- 可在 `package.json` 配置自动加载:
41
+ ## Boundaries
45
42
 
46
- ```json
47
- {
48
- "hile": {
49
- "auto_load_packages": ["@hile/ioredis"]
50
- }
51
- }
52
- ```
43
+ - Do not use `loadService()` at module top level.
44
+ - Do not use `auto_load_packages` for file paths. It accepts package names only.
45
+ - Do not use the default `@hile/ioredis` or `@hile/typeorm` services when one app needs multiple Redis or database connections; define separate services with separate keys.
53
46
 
54
- 这样应用启动时会自动建立 Redis 连接,退出时自动断开。
47
+ - Reusing one service key for unrelated factories.
48
+ - Missing `shutdown()` callbacks for network connections or servers.
49
+ - Assuming TypeORM env config fills entities automatically when `TYPEORM_ENTITIES` is not set.
50
+ - Calling `transaction()` and manually committing; the helper commits or rolls back internally.
55
51
 
56
- ## 开发
52
+ ## Verify
57
53
 
58
- ```bash
59
- pnpm install
60
- pnpm build
61
- pnpm dev
62
- pnpm test
63
- ```
54
+ - Boot files default-export `defineService(...)`.
55
+ - Long-lived resources register teardown callbacks.
56
+ - `auto_load_packages` contains package names, not local files.
57
+ - `hile start --dev` can find `src/**/*.boot.ts`.
58
+ - Production build emits `dist/**/*.boot.js`.
64
59
 
65
- ## License
60
+ ## More Context
66
61
 
67
- MIT
62
+ - `AI.md` in this package: full package-local AI guide.
63
+ - Root `llms-full.txt`: full monorepo AI context.
64
+ - Root `references/`: source files copied from `docs/ai`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hile/ioredis",
3
- "version": "2.0.2",
3
+ "version": "3.0.0",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "scripts": {
@@ -10,7 +10,8 @@
10
10
  },
11
11
  "files": [
12
12
  "dist",
13
- "README.md"
13
+ "README.md",
14
+ "AI.md"
14
15
  ],
15
16
  "license": "MIT",
16
17
  "publishConfig": {
@@ -21,8 +22,8 @@
21
22
  "vitest": "^4.0.18"
22
23
  },
23
24
  "dependencies": {
24
- "@hile/core": "^2.0.1",
25
+ "@hile/core": "^3.0.0",
25
26
  "ioredis": "^5.11.0"
26
27
  },
27
- "gitHead": "d2495d1c31f5c5fbc25c9d447c8f32b484ab0340"
28
+ "gitHead": "0985b6f8abc1f4de0a36324063585fdc3ac1375b"
28
29
  }