@hile/message-ipc 4.0.3 → 4.0.4

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/AI.md CHANGED
@@ -103,6 +103,42 @@ for await (const chunk of stream) {
103
103
  }
104
104
  ```
105
105
 
106
+ Streaming request body with a normal response:
107
+
108
+ ```ts
109
+ // src/messages/upload.msg.ts
110
+ import { defineMicroMessage } from '@hile/micro'
111
+
112
+ export default defineMicroMessage(async ({ data, input, invocation }) => {
113
+ if (!input) throw new Error('upload body is required')
114
+
115
+ let bytes = 0
116
+ for await (const chunk of input) bytes += Buffer.byteLength(chunk)
117
+
118
+ return {
119
+ filename: data.filename,
120
+ bytes,
121
+ requestId: invocation.context.values.requestId,
122
+ }
123
+ })
124
+ ```
125
+
126
+ ```ts
127
+ import { createReadStream } from 'node:fs'
128
+
129
+ const result = await app.call(
130
+ 'example.service',
131
+ '/upload',
132
+ { filename: 'archive.tar' },
133
+ { context, input: createReadStream('/tmp/archive.tar') },
134
+ )
135
+ ```
136
+
137
+ If no structured metadata is needed, pass an `AsyncIterable`, `Uint8Array`, or
138
+ `ArrayBuffer` directly as `data`; Hile sends it as the request input stream and
139
+ the handler receives `data === undefined`. `app.stream()` accepts the same
140
+ request input forms when both request and response need to stream.
141
+
106
142
  Custom WebSocket modem:
107
143
 
108
144
  ```ts
@@ -126,6 +162,68 @@ class RpcWs extends MessageWs {
126
162
 
127
163
  Notice that `request()` returns a `Promise<T>`. Await it directly.
128
164
 
165
+ ## Stream Wire Model
166
+
167
+ One request ID owns the structured request and both optional stream directions:
168
+
169
+ ```ts
170
+ type RequestFrame = {
171
+ id: number
172
+ mode: MESSAGE_MODEM_TYPE.REQUEST
173
+ twoway: boolean
174
+ data?: unknown
175
+ streams?: {
176
+ input?: true
177
+ output?: { window?: number }
178
+ }
179
+ }
180
+
181
+ type StreamDataFrame = {
182
+ id: number
183
+ mode: MESSAGE_MODEM_TYPE.STREAM_DATA
184
+ twoway: false
185
+ data: {
186
+ direction: 'input' | 'output'
187
+ seq: number
188
+ payload?: unknown
189
+ final: boolean
190
+ status?: string | number
191
+ message?: string
192
+ }
193
+ }
194
+
195
+ type StreamCreditFrame = {
196
+ id: number
197
+ mode: MESSAGE_MODEM_TYPE.STREAM_CREDIT
198
+ twoway: false
199
+ data: {
200
+ direction: 'input' | 'output'
201
+ seq: number
202
+ window?: number
203
+ }
204
+ }
205
+
206
+ type StreamCancelFrame = {
207
+ id: number
208
+ mode: MESSAGE_MODEM_TYPE.STREAM_CANCEL
209
+ twoway: false
210
+ data: {
211
+ direction: 'input' | 'output'
212
+ status?: string | number
213
+ message?: string
214
+ }
215
+ }
216
+ ```
217
+
218
+ `data` is the structured message payload; stream chunks never get embedded in
219
+ it. The request frame declares the active directions, and every later stream
220
+ frame reuses the request ID. Input and output sequence numbers, credits, and
221
+ cancellation are independent.
222
+
223
+ A non-final stream frame must carry a payload other than `null` or `undefined`.
224
+ Node `Readable` reserves those values for its own end/no-op semantics, so Hile
225
+ rejects them instead of silently losing a credit or ending a stream early.
226
+
129
227
  ## Use When
130
228
 
131
229
  Use the message packages for request/response messaging over WebSocket, process IPC, worker threads, file-system message handlers, service discovery, streaming RPC, and registry-backed pub/sub.
@@ -133,6 +231,7 @@ Use the message packages for request/response messaging over WebSocket, process
133
231
  ## Do Not Use When
134
232
 
135
233
  - Do not use `stream()` for normal single-result calls.
234
+ - Do not enable retries for a streamed request input. Input streams are consumed once and cannot be replayed safely.
136
235
  - Do not rely on message IDs for business idempotency. They are transport IDs.
137
236
  - Use `defineMicroMessage()` for Micro business handlers; reserve generic `defineMessage()` for transport-neutral loaders.
138
237
  - Do not pass zero, fractional, non-finite, or oversized message timeouts. Explicit timeout values must be safe integers from `1` through `2_147_483_647` milliseconds.
@@ -167,14 +266,21 @@ import { MessageWorkerThread } from '@hile/message-worker-thread'
167
266
  - `MessageLoader` maps `*.msg.*` files to routes using `@hile/loader`.
168
267
  - `MessageLoader.dispatch(path, data, extras?)` invokes the matched handler.
169
268
  - `MessageModem._send()` returns a `Promise`.
269
+ - `_send()` and `_stream()` accept `options.input` as an `AsyncIterable`, `Uint8Array`, or `ArrayBuffer`. Passing one of those values directly as `data` automatically selects request streaming and leaves the handler's structured `data` undefined.
170
270
  - `MessageModem._send()` and `_push()` use a `30_000` ms timeout when none is provided. An explicit timeout must be a safe integer from `1` through `2_147_483_647`; invalid values throw `TypeError` before a message is sent.
171
271
  - `MessageModem._stream()` returns a Node `Readable` in object mode.
172
- - Stream `timeout` and `idleTimeout` values use the same `1` through `2_147_483_647` ms range. The stream `window` must be a safe integer from `1` through `64` and defaults to `1`.
272
+ - Stream `timeout` and `idleTimeout` values use the same `1` through `2_147_483_647` ms range. Idle timeout is refreshed by valid input or output stream activity. The response stream `window` must be a safe integer from `1` through `64` and defaults to `1`; request input uses receiver-issued credit with a window of `1`.
173
273
  - Each modem schedules request, total-stream, and idle-stream deadlines through one internal deadline scheduler. This reduces active Node.js timers without changing timeout, cancellation, ordering, or error semantics.
174
- - `@hile/message-ws` keeps public `decodeMessageFrame()` payloads isolated from caller-owned input by default. Its owned WebSocket `RawData` path uses a zero-copy binary Flight payload view internally.
274
+ - Request and response chunks share `STREAM_DATA` frames and carry an explicit `direction: 'input' | 'output'`; each direction has independent sequence and credit state. `STREAM_CANCEL` stops one direction. A cancel carrying `status` fails the owning request immediately; `ABORT` cancels the whole invocation.
275
+ - This frame model replaces the former response-only `stream`, `streamVersion`, and `streamWindow` fields. All peers on one transport connection must use compatible `@hile/message-modem` and transport package versions; do not mix old and new peers during a rolling deployment.
276
+ - `@hile/message-ws` sends `Uint8Array` and `ArrayBuffer` request and response chunks as native binary frames rather than JSON/base64. Public `decodeMessageFrame()` payloads remain isolated from caller-owned input by default; the owned WebSocket `RawData` path uses a zero-copy binary view internally.
277
+ - `@hile/message-ipc` transparently Base64-wraps only binary `STREAM_DATA` payloads so request and response streams survive Node child-process IPC's default JSON serialization. Other IPC frames keep their ordinary object representation.
175
278
  - A stream request requires `exec()` to return an async iterable.
176
- - `Application.call(namespace, url, data, options)` requires `options.context` and returns a promise.
177
- - `Application.stream(namespace, url, data, options)` requires `options.context` and returns a readable stream.
279
+ - `defineMicroMessage()` handlers receive request streams as `input: Readable | undefined`, separately from structured `data` and `invocation`.
280
+ - `Application.call(namespace, url, data, options)` requires `options.context` and returns a promise. It accepts `options.input` for a streamed request with a normal response.
281
+ - `Application.stream(namespace, url, data, options)` requires `options.context` and returns a readable response stream; it can carry a request input stream at the same time.
282
+ - `Application.call()` and `Application.stream()` default retries to `0` when request input is streamed. Explicit nonzero retries fail before service discovery because streamed input is non-replayable.
283
+ - A caller-owned request input source failure is surfaced as `MessageInputError`, aborts the peer invocation, and is not counted against that peer's circuit-breaker health.
178
284
  - `Application.publish(topic, payload)` returns an object with `update()` and `unpublish()`.
179
285
  - `Application.subscribe(topic, callback)` returns an unsubscribe function.
180
286
  - `Registry` stores service addresses and retained config/topic state under `~/.registry`.
@@ -183,6 +289,7 @@ import { MessageWorkerThread } from '@hile/message-worker-thread'
183
289
 
184
290
  - Appending a secondary response getter to `client.request('/x', data)`
185
291
  - Returning a plain object from a handler called through `stream()`.
292
+ - Retrying a consumed request stream or hiding it inside a replay-unsafe factory.
186
293
  - Using pub/sub as a durable queue.
187
294
  - Forgetting to register `shutdown(await app.listen(...))`.
188
295
 
@@ -191,6 +298,8 @@ import { MessageWorkerThread } from '@hile/message-worker-thread'
191
298
  - Micro message files default-export `defineMicroMessage(...)` and receive `invocation.context`.
192
299
  - RPC callers use `await app.call(..., { context })`.
193
300
  - Streaming handlers are async generators.
301
+ - Request-stream handlers consume `input` and callers either pass `options.input` alongside metadata or pass a stream directly as `data`.
302
+ - Streamed request calls do not configure nonzero retries.
194
303
  - Custom modem timeout values use the documented safe-integer range.
195
304
  - Registry is started before application nodes need discovery.
196
305
  - Micro apps use stable namespaces and advertise reachable hosts.
@@ -277,10 +386,13 @@ Use this recipe when services communicate over Hile registry-backed RPC.
277
386
  3. Default-export `defineMicroMessage()` handlers and load them through `app.load()`.
278
387
  4. Create context at ingress and call providers with `await app.call(namespace, url, data, { context })`.
279
388
  5. Use `app.stream()` only for async-generator handlers.
389
+ 6. For streamed request bodies, consume `input` in the `defineMicroMessage()` handler and pass the source through `options.input`; pass the stream as `data` only when no structured metadata is needed.
280
390
 
281
391
  ## Failure And Cleanup Behavior
282
392
 
283
393
  - `Application.call()` may retry; side-effecting handlers need idempotency.
394
+ - A streamed request body is non-replayable. Its retry default is `0`, and an explicit nonzero retry count is rejected before discovery.
395
+ - Request input and response output have independent credit-based backpressure and may be active together.
284
396
  - Registry disconnect triggers reconnect; apps re-declare topics and subscriptions.
285
397
  - Circuit breaker excludes failing nodes for cooldown.
286
398
 
@@ -290,6 +402,7 @@ Use this recipe when services communicate over Hile registry-backed RPC.
290
402
  - Provider namespace matches consumer call.
291
403
  - Handlers default-export `defineMicroMessage()` and consume explicit invocation context when needed.
292
404
  - Consumer code awaits `app.call(..., { context })` directly.
405
+ - Streamed request handlers consume `input: Readable`, preserve structured metadata in `data`, and do not enable retries.
293
406
 
294
407
 
295
408
 
@@ -305,6 +418,7 @@ Use this recipe when services communicate over Hile registry-backed RPC.
305
418
  - Do not assume `@hile/http` Zod validation mutates or coerces `ctx.query`, `ctx.params`, or `ctx.request.body`.
306
419
  - Do not put reusable business logic only in controllers, pages, queue workers, or message handlers.
307
420
  - Do not use old message examples that append a secondary response getter; current request APIs return promises directly.
421
+ - Do not invent service-specific HTTP-in-Micro envelopes or Base64 file bodies; use `@hile/http-over-micro` and its request/response streams.
308
422
  - Do not claim exactly-once delivery or execution from Redis locks, queues, idempotency, or rate limits.
309
423
  - Do not use queue `jobId` as the only side-effect idempotency boundary.
310
424
  - Do not log the entire async context by default.
package/README.md CHANGED
@@ -72,12 +72,14 @@ const result = await app.call('example.service', '/ping', { hello: 'world' }, {
72
72
  ## Boundaries
73
73
 
74
74
  - Do not use `stream()` for normal single-result calls.
75
+ - Do not enable retries for a streamed request input. Input streams are consumed once and cannot be replayed safely.
75
76
  - Do not rely on message IDs for business idempotency. They are transport IDs.
76
77
  - Use `defineMicroMessage()` for Micro business handlers; reserve generic `defineMessage()` for transport-neutral loaders.
77
78
  - Do not pass zero, fractional, non-finite, or oversized message timeouts. Explicit timeout values must be safe integers from `1` through `2_147_483_647` milliseconds.
78
79
 
79
80
  - Appending a secondary response getter to `client.request('/x', data)`
80
81
  - Returning a plain object from a handler called through `stream()`.
82
+ - Retrying a consumed request stream or hiding it inside a replay-unsafe factory.
81
83
  - Using pub/sub as a durable queue.
82
84
  - Forgetting to register `shutdown(await app.listen(...))`.
83
85
 
@@ -86,6 +88,8 @@ const result = await app.call('example.service', '/ping', { hello: 'world' }, {
86
88
  - Micro message files default-export `defineMicroMessage(...)` and receive `invocation.context`.
87
89
  - RPC callers use `await app.call(..., { context })`.
88
90
  - Streaming handlers are async generators.
91
+ - Request-stream handlers consume `input` and callers either pass `options.input` alongside metadata or pass a stream directly as `data`.
92
+ - Streamed request calls do not configure nonzero retries.
89
93
  - Custom modem timeout values use the documented safe-integer range.
90
94
  - Registry is started before application nodes need discovery.
91
95
  - Micro apps use stable namespaces and advertise reachable hosts.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { MessageModem, type MessageTransferFormat } from '@hile/message-modem';
2
2
  import type { ChildProcess } from 'node:child_process';
3
- export type IpcExecHandler = (data: any) => Promise<any>;
3
+ import type { Readable } from 'node:stream';
4
+ export type IpcExecHandler = (data: any, signal?: AbortSignal, input?: Readable) => Promise<any>;
4
5
  /**
5
6
  * 支持父进程和子进程双端使用的 IPC 通信层。
6
7
  * exec方法实现由子类实现,本实例不做实现
package/dist/index.js CHANGED
@@ -1,4 +1,40 @@
1
- import { MessageModem } from '@hile/message-modem';
1
+ import { MessageModem, MESSAGE_MODEM_TYPE, } from '@hile/message-modem';
2
+ const IPC_BINARY_FRAME = '@hile/message-ipc:binary-v1';
3
+ function isRecord(value) {
4
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
5
+ }
6
+ function encodeIpcMessage(message) {
7
+ const chunk = message.data;
8
+ const payload = chunk?.payload;
9
+ if (message.mode !== MESSAGE_MODEM_TYPE.STREAM_DATA
10
+ || !chunk
11
+ || (chunk.direction !== 'input' && chunk.direction !== 'output')
12
+ || (!(payload instanceof Uint8Array) && !(payload instanceof ArrayBuffer)))
13
+ return message;
14
+ const { payload: _payload, ...chunkHeader } = chunk;
15
+ return {
16
+ type: IPC_BINARY_FRAME,
17
+ message: { ...message, data: chunkHeader },
18
+ payload: Buffer.from(payload instanceof ArrayBuffer
19
+ ? payload
20
+ : payload.buffer.slice(payload.byteOffset, payload.byteOffset + payload.byteLength)).toString('base64'),
21
+ };
22
+ }
23
+ function decodeIpcMessage(value) {
24
+ if (!isRecord(value)
25
+ || value.type !== IPC_BINARY_FRAME
26
+ || !isRecord(value.message)
27
+ || typeof value.payload !== 'string'
28
+ || !isRecord(value.message.data))
29
+ return value;
30
+ return {
31
+ ...value.message,
32
+ data: {
33
+ ...value.message.data,
34
+ payload: Buffer.from(value.payload, 'base64'),
35
+ },
36
+ };
37
+ }
2
38
  /**
3
39
  * 支持父进程和子进程双端使用的 IPC 通信层。
4
40
  * exec方法实现由子类实现,本实例不做实现
@@ -25,7 +61,7 @@ export class MessageIpc extends MessageModem {
25
61
  constructor(channel) {
26
62
  super();
27
63
  this.channel = channel ?? process;
28
- this.listener = (msg) => this.receive(msg);
64
+ this.listener = (msg) => this.receive(decodeIpcMessage(msg));
29
65
  this.channel.on('message', this.listener);
30
66
  }
31
67
  post(data) {
@@ -33,7 +69,7 @@ export class MessageIpc extends MessageModem {
33
69
  if (typeof ch.send !== 'function') {
34
70
  throw new Error('IPC channel is not available. Ensure the process was forked with an IPC channel.');
35
71
  }
36
- ch.send(data);
72
+ ch.send(encodeIpcMessage(data));
37
73
  }
38
74
  /**
39
75
  * 移除消息监听,释放资源
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hile/message-ipc",
3
- "version": "4.0.3",
3
+ "version": "4.0.4",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "scripts": {
@@ -23,7 +23,7 @@
23
23
  "vitest": "^4.0.18"
24
24
  },
25
25
  "dependencies": {
26
- "@hile/message-modem": "^4.0.3"
26
+ "@hile/message-modem": "^4.0.4"
27
27
  },
28
- "gitHead": "3ea69973f9373ddb1f7d5d37338966fd7d081d66"
28
+ "gitHead": "c57b2c5a3c017ae56d4a862a089b2af01368c3ba"
29
29
  }