@hile/micro 1.0.4 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,14 +1,24 @@
1
1
  # @hile/micro
2
2
 
3
- 基于 `@hile/message-loader` 与 `@hile/message-ws` 的轻量级 **WebSocket 服务注册与发现**:用固定格式的连接 URL 标识对端,`Registry` 按逻辑 namespace 记录实例,`Application` 从注册中心拉取地址并缓存到远端服务的会话。
3
+ 基于 `@hile/message-loader` 与 `@hile/message-ws` 的轻量级 **WebSocket 微服务框架**。提供服务注册与发现、心跳保活、熔断、请求超时、自动重试、调用链路追踪等功能。
4
4
 
5
- ## 概念分层
5
+ ## 架构分层
6
6
 
7
- 1. **`Server`**:实现「服务」的 **底层协议与运行时**——基于 `ws` 监听、按路径解析对端身份,对内用 `MessageLoader` 做 `{ url, data }` 路由;不关心注册中心,只负责连接语义与消息派发。
8
- 2. **`Registry`**:**注册中心**,维护「逻辑 namespace 一组实例地址」,`/-/find` 随机返回其一。
9
- 3. **`Application`**:**基于 `Server` 的具体应用侧实现**——继承 `Server`,在 `listen` 后自动连上 `Registry`,用 `get(namespace)` 发现其它服务并缓存 `Client`。
7
+ ```
8
+ MessageLoader (路由) + MessageWs (请求/响应传输)
9
+ └── Server(WebSocket 服务底层)
10
+ ├── Registry(注册中心)
11
+ └── Application(应用服务)
12
+ ```
10
13
 
11
- 同一进程里通常只建一个 `Application`,它 **同时** 扮演 **provider**(`register` 暴露接口)与 **consumer**(`get` + `request`/`push` 调用其它 namespace);文档里把「提供方 / 调用方」拆开示例,是为了说明两种用法,而不是两类不同的类。
14
+ | 组件 | 职责 |
15
+ |------|------|
16
+ | **Server** | WebSocket 监听、连接管理、消息路由。不关心注册中心 |
17
+ | **Client** | 远端 Server 的代理,提供 `request()` / `push()` 通信接口 |
18
+ | **Registry** | 注册中心。维护 namespace → 实例列表,心跳检测剔除死实例 |
19
+ | **Application** | 应用服务。集成注册发现、熔断、重试、追踪等功能 |
20
+
21
+ 一个 `Application` 实例 **同时** 扮演 provider(`register` 暴露接口)和 consumer(`get` / `call` 调用其它服务)。
12
22
 
13
23
  ## 安装
14
24
 
@@ -16,34 +26,13 @@
16
26
  pnpm add @hile/micro
17
27
  ```
18
28
 
19
- 依赖:`@hile/message-loader`、`@hile/message-ws`、`ws`(随 workspace 一并解析)。
29
+ 依赖:`@hile/message-loader`、`@hile/message-ws`、`ws`。
20
30
 
21
31
  ---
22
32
 
23
- ## 能做什么?
24
-
25
- | 组件 | 作用 |
26
- |------|------|
27
- | `Server` | **底层协议**:监听 WebSocket;解析路径中的调用方地址与可选分段;对内用 `register`/`dispatch` 处理 `{ url, data }` |
28
- | `Client` | 连到远端 `Server`,`request`/`push` 走 `MessageModem`,`dispose()` 会关闭底层连接 |
29
- | `Registry` | **注册中心**:固定 namespace `'registry'`;实例上线/下线更新 namespace→地址集合;`/-/find` **随机** 返回其中一个地址 |
30
- | `Application` | **基于 `Server` 的应用实现**:启动后连接 Registry;`register` 侧即 provider、`get` 侧即 consumer;`get(ns)` 查询并 **缓存** 到目标服务的 `Client`,断连后清空缓存 |
31
-
32
- 连接串格式(出站):
33
-
34
- `ws://目标主机:端口/{宣告地址}/{本机监听端口}/{本机namespace}`
35
-
36
- 宣告地址:构造 `Server` / `Application` / `Registry` 时可通过 **`advertiseHost`** 显式传入;未传则使用 `getLocalIPv4()`。若二者皆无(例如无可用 IPv4),**构造阶段即抛错**。容器、多网卡或 CI 环境建议设置 `advertiseHost`(如 `127.0.0.1` 或 Pod IP)。
37
-
38
- `Application` 还支持 **`registryLookupTimeoutMs`**(默认 `10000`),限制对 Registry `/-/find` 的响应等待时间。
33
+ ## 快速开始
39
34
 
40
- 出站 `connect` 默认 **5 秒**握手超时,超时报错 `Connection timeout`。
41
-
42
- ---
43
-
44
- ## 快速示例
45
-
46
- ### 1. Registry
35
+ ### 1. 启动 Registry
47
36
 
48
37
  ```typescript
49
38
  import { Registry } from '@hile/micro';
@@ -52,7 +41,9 @@ const registry = new Registry({ advertiseHost: '127.0.0.1' });
52
41
  await registry.listen(9000);
53
42
  ```
54
43
 
55
- ### 2. 服务提供方(被其它 Application 发现的进程)
44
+ ### 2. 启动 Provider(服务 A)
45
+
46
+ 以下 `provider` 和 `consumer` 是两个不同进程(不同 namespace),**每个进程只需要一个 `Application` 实例**,同时扮演 provider 和 consumer:
56
47
 
57
48
  ```typescript
58
49
  import { Application } from '@hile/micro';
@@ -70,7 +61,7 @@ provider.register('/charge', async ({ data }) => {
70
61
  });
71
62
  ```
72
63
 
73
- ### 3. 调用方(通过 Registry 解析地址)
64
+ ### 3. 启动 Consumer 调用(服务 B)
74
65
 
75
66
  ```typescript
76
67
  import { Application } from '@hile/micro';
@@ -83,38 +74,373 @@ const consumer = new Application({
83
74
 
84
75
  await consumer.listen(9200);
85
76
 
86
- const remote = await consumer.get('payments');
87
- const { response } = remote.request('/charge', { amount: 100 });
88
- const result = await response<{ charged: boolean; amount: number }>();
89
- console.log(result);
77
+ // call() = get() + request() + response() + 熔断 + 重试
78
+ const result = await consumer.call('payments', '/charge', { amount: 100 });
79
+ console.log(result); // { charged: true, amount: 100 }
90
80
  ```
91
81
 
92
- ### 关闭
82
+ ### 4. 关闭
93
83
 
94
- `listen` 返回的 teardown 函数会关闭 WebSocketServer 并对已有 `Client` 调用 `dispose()`:
84
+ `listen()` 返回的 teardown 函数关闭 WebSocketServer 并断开所有连接:
95
85
 
96
86
  ```typescript
97
87
  const stop = await provider.listen(9100);
98
- // ...
99
88
  await stop();
100
89
  ```
101
90
 
102
91
  ---
103
92
 
104
- ## 与 Hile core 的关系
93
+ ## 核心功能
105
94
 
106
- `@hile/micro` **不依赖** `@hile/core`,可与任意 Node.js 进程或在未来由 `defineService` 包装后接入 Hile 容器。
95
+ ### 服务发现 (`get`)
107
96
 
108
- ---
97
+ 按 namespace 从 Registry 获取一个远端 Client 并缓存:
98
+
99
+ ```typescript
100
+ const client = await consumer.get('payments');
101
+ const { response } = client.request('/charge', { amount: 100 });
102
+ const result = await response();
103
+ ```
104
+
105
+ - 首次查询通过 Registry `/-/find` 获取地址
106
+ - 结果**缓存**在内存中(namespace → Client)
107
+ - 当 Client 断连时自动清理缓存,下次 `get` 重新发现
108
+
109
+ ### 熔断器 (Circuit Breaker)
110
+
111
+ `call()` 自动跟踪每个 namespace 下各 peer 的调用失败。失败的 peer 被临时排除,**30 秒冷卻期**后自动恢复。
112
+
113
+ | 场景 | 行为 |
114
+ |------|------|
115
+ | 调用 peer A 失败 | A 加入排除列表(30s cooldown) |
116
+ | 再次调用该 namespace | Registry `/‑/find` 带上 `exclude`,返回其他 peer |
117
+ | 所有 peer 都被排除 | 重置排除列表,重新从所有 peer 中选择 |
118
+ | 调用成功 | 该 peer 从排除列表中移除 |
119
+
120
+ 排除列表:
121
+ - 键:`${host}:${port}`
122
+ - 存储:`Map<namespace, Map<peerKey, openedAt>>`
123
+ - 冷卻期:`CB_COOLDOWN_MS = 30_000`(30 秒)
124
+ - 过期检查:`getActiveExcludes()` 在每次 `call()` 调用时执行
125
+
126
+ ### 请求超时
127
+
128
+ 每个请求都有超时控制:
129
+
130
+ ```typescript
131
+ // 构造时设置全局默认超时
132
+ const app = new Application({
133
+ namespace: 'svc',
134
+ registry: { host, port },
135
+ requestTimeoutMs: 10_000, // 默认 30000ms
136
+ });
137
+
138
+ // 单次调用覆盖
139
+ await app.call('svc', '/api', data, 5_000); // 5s 超时
140
+ await app.call('svc', '/api', data, 1_000, 0); // 1s 超时, 不重试
141
+ ```
142
+
143
+ 超时触发时,底层 MessageModem 会向对端发送 **ABORT** 消息取消远程执行。
144
+
145
+ ### 手动取消请求
146
+
147
+ 使用 `get()` 拿到 Client 后,`request()` 返回的 `abort()` 可主动取消正在等待响应的请求:
148
+
149
+ ```typescript
150
+ const client = await consumer.get('payments');
151
+ const { response, abort } = client.request('/charge', { amount: 100 });
109
152
 
110
- ## 文档策略
153
+ // 例如 5 秒后主动取消
154
+ setTimeout(() => abort(), 5000);
111
155
 
112
- | 文档 | 读者 | 用途 |
156
+ try {
157
+ const result = await response();
158
+ } catch (err) {
159
+ // 超时或手动 abort 都会 reject
160
+ }
161
+ ```
162
+
163
+ - `abort()` 向对端发送 **ABORT 消息**,让远程 handler 提前终止
164
+ - 超时到期内部也会调用 `controller.abort()`,机制相同
165
+ - 适用场景:用户取消、页面卸载、竞态淘汰
166
+
167
+ ### 自动重试
168
+
169
+ `call()` 默认 retries=1,失败后自动换 peer 重试:
170
+
171
+ ```typescript
172
+ await app.call('svc', '/api', data); // 默认重试 1 次
173
+ await app.call('svc', '/api', data, 5000, 3); // 超时 5s, 重试 3 次
174
+ await app.call('svc', '/api', data, 5000, 0); // 超时 5s, 不重试
175
+ ```
176
+
177
+ 重试策略:失败 → `recordFailure`(peer 被排除)→ 递归 `call(retries-1)` → `getActiveExcludes` 排除已失败的 peer → Registry `/‑/find` 返回其他 peer。
178
+
179
+ ### Correlation ID 链路追踪
180
+
181
+ `call()` 自动为每次调用注入唯一 `_correlationId`:
182
+
183
+ ```typescript
184
+ provider.register('/api', async ({ data }) => {
185
+ console.log(data._correlationId); // 自动注入的 UUID
186
+ });
187
+ ```
188
+
189
+ 行为规则:
190
+
191
+ | 入参 data | 结果 |
192
+ |-----------|------|
193
+ | `null / undefined` | 包装为 `{ _correlationId, data: null }` |
194
+ | 字符串 / 数字 | 包装为 `{ _correlationId, data: '原始值' }` |
195
+ | 数组 | 包装为 `{ _correlationId, data: [原始数组] }` |
196
+ | `{ value: 1 }` (无 `_correlationId`) | 扩展为 `{ value: 1, _correlationId: 'uuid' }` |
197
+ | `{ _correlationId: 'trace-1' }` | 保留已有 ID,**不覆盖** |
198
+
199
+ > **注意:** 原 data 对象不会被修改(使用浅拷贝 `{ ...data, _correlationId }`)。
200
+
201
+ ### 健康检查
202
+
203
+ 每个 `Application` 自动注册 `/-/health` 端点:
204
+
205
+ ```typescript
206
+ // 通过 dispatch 调用(同进程内)
207
+ const health = await app.dispatch('/-/health', {});
208
+ // { status: 'ok', registry: true, uptime: 123.45, namespaces: ['payments'] }
209
+ ```
210
+
211
+ 返回字段:
212
+
213
+ | 字段 | 类型 | 说明 |
113
214
  |------|------|------|
114
- | README | 使用者 | 安装、概念、示例 |
115
- | `SKILL.md` | AI / 贡献者 | 路由约定、类型、反模式、测试门禁 |
215
+ | `status` | `'ok'` | 固定值 |
216
+ | `registry` | `boolean` | 是否已连接 Registry |
217
+ | `uptime` | `number` | 进程启动时长(秒) |
218
+ | `namespaces` | `string[]` | 本地已缓存的 namespace 列表 |
219
+
220
+ ### 缓存降级
221
+
222
+ 当 Registry 不可用但本地仍有已缓存的 Client 连接时,`get()` 自动降级使用缓存:
223
+
224
+ | 场景 | 行为 |
225
+ |------|------|
226
+ | Registry 宕机 + 缓存有效 | 返回缓存 Client,继续服务 |
227
+ | Registry 宕机 + 缓存已过期 | 报错 |
228
+ | 全新 namespace + Registry 宕机 | 报错 |
229
+ | Registry 恢复 | 恢复正常查询 |
230
+
231
+ ### Registry 心跳保活
232
+
233
+ - **Application** 每 10 秒向 Registry 推送 `/-/heartbeat`
234
+ - **Registry** 每 1 秒检查所有实例的心跳时间戳
235
+ - 超过 20 秒未收到心跳的实例被自动剔除并断开连接
236
+
237
+ ### Registry 重连
238
+
239
+ 当 Application 与 Registry 的连接断开时:
240
+ 1. 立即尝试重连(`reconnectToRegistry`)
241
+ 2. 若失败,3 秒后重试(`scheduleRegistryRetry`)
242
+ 3. 若 `listen()` 返回的 teardown 已触发(`stopped = true`),停止重连
243
+
244
+ ---
245
+
246
+ ## 配置管理
247
+
248
+ ### Registry 工作目录
249
+
250
+ Registry 启动时自动创建 `~/.registry/` 工作目录。YAML 配置文件存放在 `~/.registry/configs/` 下,按 namespace 分文件管理:
251
+
252
+ ```
253
+ ~/.registry/
254
+ └── configs/
255
+ ├── service-a.config.yaml
256
+ ├── service-b.config.yaml
257
+ └── global.config.yaml
258
+ ```
259
+
260
+ ### 配置文件热加载
261
+
262
+ Regsitry 监听 `configs/` 目录的文件变化,新增或修改 `*.config.yaml` 文件时自动加载(兼容 vim 原子写入),无需重启:
263
+
264
+ ```bash
265
+ # 创建或修改 ~/.registry/configs/my-service.config.yaml
266
+ # Registry 自动检测变化并更新内存中的配置
267
+ ```
268
+
269
+ ### 远程读取配置
270
+
271
+ 通过 `/-/env/variables` 端点,已连服务可按 namespace 和字段从 Registry 远程读取配置:
272
+
273
+ ```typescript
274
+ // Application 侧
275
+ const result = await app.getEnvVariables(
276
+ { namespace: 'service-a', fields: ['db.host', 'db.port'] },
277
+ { namespace: 'global' },
278
+ );
279
+ // result = {
280
+ // 'service-a': { 'db.host': '10.0.0.2', 'db.port': 3306 },
281
+ // 'global': { featureFlag: true },
282
+ // }
283
+ ```
284
+
285
+ ---
286
+
287
+ ## CLI
288
+
289
+ ### `hile registry`
290
+
291
+ 启动注册中心:
292
+
293
+ ```bash
294
+ # 使用默认配置
295
+ hile registry
296
+
297
+ # 指定端口
298
+ hile registry --port 8888
299
+
300
+ # 指定宣告地址
301
+ hile registry --host 10.0.0.1
302
+ ```
303
+
304
+ ### `hile registry configs`
305
+
306
+ 管理 `~/.registry/configs/` 下的 YAML 配置文件:
307
+
308
+ ```bash
309
+ # 列出所有 namespace
310
+ hile registry configs
311
+
312
+ # 查看配置(YAML 输出)
313
+ hile registry configs get my-service
314
+
315
+ # 查看配置(JSON 输出)
316
+ hile registry configs get my-service --json
317
+
318
+ # 设置配置项
319
+ hile registry configs set my-service port=8080
320
+ hile registry configs set my-service debug=true
321
+
322
+ # 删除整个 namespace
323
+ hile registry configs del my-service
324
+
325
+ # 删除某个字段(需确认)
326
+ hile registry configs del my-service port
327
+
328
+ # 跳过确认删除
329
+ hile registry configs del my-service -y
330
+ ```
331
+
332
+ ## 连接协议
333
+
334
+ ### 连接 URL 格式
335
+
336
+ 出站 WebSocket URL:
337
+
338
+ ```
339
+ ws://{targetHost}:{targetPort}/{announceHost}/{listenPort}/{namespace}
340
+ ```
341
+
342
+ - `announceHost`:构造时传入 `advertiseHost` 或自动获取的 IPv4
343
+ - `listenPort`:`listen(port)` 设置的端口
344
+ - `namespace`:构造时传入的 namespace 字符串
345
+
346
+ ### 入站路径解析
347
+
348
+ `Server.onConnected` 将 URL 路径按 `/` 分割为:
349
+
350
+ ```
351
+ [callerHost, callerPort, ...extras]
352
+ ```
353
+
354
+ - `extras` 以 `/` 分段,Registry 用 `extras.join('/')` 作为 namespace
355
+
356
+ ---
357
+
358
+ ## API 参考
359
+
360
+ ### ApplicationProps
361
+
362
+ ```typescript
363
+ type ApplicationProps = {
364
+ namespace: string; // 本服务 namespace
365
+ registry: { host: string; port: number }; // Registry 地址
366
+ registryLookupTimeoutMs?: number; // /-/find 超时,默认 10000
367
+ requestTimeoutMs?: number; // 单次请求超时,默认 30000
368
+ } & { advertiseHost?: string }; // 出站宣告地址
369
+ ```
370
+
371
+ ### Application
372
+
373
+ ```typescript
374
+ class Application extends Server {
375
+ constructor(props: ApplicationProps);
376
+
377
+ // 启动监听,自动连接 Registry,启动心跳
378
+ listen(port: number): Promise<() => Promise<void>>;
379
+
380
+ // 获取 namespace 对应的远端 Client(缓存 + 自动发现)
381
+ get(namespace: string, exclude?: string[]): Promise<Client>;
382
+
383
+ // 一站式调用:get + request + response + 熔断 + 重试 + 追踪
384
+ call<T = any>(
385
+ namespace: string,
386
+ url: string,
387
+ data: any,
388
+ timeout?: number, // 请求超时(ms),默认 requestTimeoutMs
389
+ retries?: number, // 失败重试次数,默认 1
390
+ ): Promise<T>;
391
+
392
+ // 注册路由(provider 侧)
393
+ register<T = any>(url: string, handler: (ctx) => Promise<T>): () => void;
394
+
395
+ // 同进程调用路由
396
+ dispatch(url: string, data: any): Promise<any>;
397
+
398
+ // 远程读取 Registry 的配置(强类型)
399
+ getEnvVariables<
400
+ T extends Record<string, Record<string, any>>,
401
+ const Requests extends readonly EnvRequest<T>[],
402
+ >(...data: Requests): Promise<GetEnvVariablesResult<T, Requests>>;
403
+ }
404
+ ```
405
+
406
+ ### Registry
407
+
408
+ ```typescript
409
+ class Registry extends Server {
410
+ constructor(props?: MicroServerProps);
411
+ listen(port: number): Promise<() => Promise<void>>;
412
+ onFind(): void; // 幂等地挂载 /-/find 路由
413
+ watchEnvFile(): fs.FSWatcher | undefined; // 监听 ~/.registry/configs/ 目录内的 *.config.yaml 文件变化
414
+ }
415
+ ```
416
+
417
+ ### Server
418
+
419
+ ```typescript
420
+ class Server extends MessageLoader {
421
+ constructor(namespace: string, props?: MicroServerProps);
422
+ listen(port: number): Promise<() => Promise<void>>;
423
+ setPort(port: number): this;
424
+ // 以下方法受保护:
425
+ protected connect(host: string, port: number, timeout?: number): Promise<Client>;
426
+ }
427
+ ```
428
+
429
+ ### Client
430
+
431
+ ```typescript
432
+ class Client extends MessageWs {
433
+ request(url: string, data: any, timeout?: number): { abort(): void; response<T>(): Promise<T> };
434
+ push(url: string, data: any, timeout?: number): void;
435
+ dispose(): void;
436
+ }
437
+ ```
438
+
439
+ ---
440
+
441
+ ## 与 Hile core 的关系
116
442
 
117
- 仓库线上文档见 Mintlify:**API 参考 @hile/micro**(若已启用)。
443
+ `@hile/micro` 不依赖 `@hile/core`,可与任意 Node.js 进程或在未来由 `defineService` 包装后接入 Hile 容器。
118
444
 
119
445
  ---
120
446