@kumiai/hub-tunnel 0.9.0 → 0.10.1

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.
@@ -4,5 +4,6 @@ import { type HubTunnelTransportParams } from './transport.js';
4
4
  export type EncryptedHubTunnelTransportParams = HubTunnelTransportParams & {
5
5
  encryptor: Encryptor;
6
6
  groupID: string;
7
+ drainTimeoutMs?: number;
7
8
  };
8
9
  export declare function createEncryptedHubTunnelTransport<R, W>(params: EncryptedHubTunnelTransportParams): TransportType<R, W>;
@@ -2,7 +2,7 @@ import { fromB64, toB64 } from '@sozai/codec';
2
2
  import { decodeEnvelope, encodeEnvelope } from './envelope.js';
3
3
  import { DecryptError, EncryptError, EnvelopeDecodeError } from './errors.js';
4
4
  import { createHubTunnelTransport } from './transport.js';
5
- function wrapHub({ hub, encryptor, groupID, onEvent, onEncryptError }) {
5
+ function wrapHub({ hub, encryptor, groupID, onEvent, onEncryptError, drainTimeoutMs, drains }) {
6
6
  const wrapped = {
7
7
  async publish (params) {
8
8
  let ciphertextBytes;
@@ -35,19 +35,44 @@ function wrapHub({ hub, encryptor, groupID, onEvent, onEncryptError }) {
35
35
  receive (subscriberDID, options) {
36
36
  const inner = hub.receive(subscriberDID, options);
37
37
  const innerIterator = inner[Symbol.asyncIterator]();
38
+ const ackedOnDecrypt = new Set();
39
+ const inFlightDecrypts = new Set();
40
+ let closing = false;
41
+ let closePromise;
38
42
  // A hub's ack may be synchronous and throw synchronously, before `Promise.resolve` sees it —
39
43
  // so the rejection guard alone is not enough (same fix as `ackUpstream` in `rpc/src/hub-mux.ts`).
40
- const ackHandled = (sequenceID)=>{
44
+ const ackHandled = (sequenceID, decrypted = false)=>{
45
+ if (ackedOnDecrypt.delete(sequenceID)) return;
46
+ if (inner.ack == null) return;
47
+ if (decrypted) ackedOnDecrypt.add(sequenceID);
41
48
  try {
42
- void Promise.resolve(inner.ack?.(sequenceID)).catch(()=>{});
43
- } catch {
44
- // ignore
49
+ void Promise.resolve(inner.ack(sequenceID)).catch((error)=>{
50
+ onEvent?.({
51
+ type: 'ack-failed',
52
+ sequenceID,
53
+ error
54
+ });
55
+ });
56
+ } catch (error) {
57
+ onEvent?.({
58
+ type: 'ack-failed',
59
+ sequenceID,
60
+ error
61
+ });
45
62
  }
46
63
  };
47
64
  const iterator = {
48
65
  async next () {
49
66
  while(true){
67
+ if (closing) return {
68
+ value: undefined,
69
+ done: true
70
+ };
50
71
  const result = await innerIterator.next();
72
+ if (closing) return {
73
+ value: undefined,
74
+ done: true
75
+ };
51
76
  if (result.done) {
52
77
  return {
53
78
  value: undefined,
@@ -89,9 +114,23 @@ function wrapHub({ hub, encryptor, groupID, onEvent, onEncryptError }) {
89
114
  ackHandled(message.sequenceID);
90
115
  continue;
91
116
  }
117
+ // Registered before the decryptor runs: a decryptor that synchronously triggers teardown
118
+ // must still find its own work in the drain.
119
+ let markSettled = ()=>{};
120
+ const settled = new Promise((resolve)=>{
121
+ markSettled = resolve;
122
+ });
123
+ inFlightDecrypts.add(settled);
124
+ const decryptWork = (async ()=>{
125
+ const plaintext = await encryptor.decrypt(fromB64(envelope.ciphertext));
126
+ // The receive key is spent now, even if the pump cannot deliver this frame.
127
+ ackHandled(message.sequenceID, true);
128
+ return plaintext;
129
+ })();
130
+ void decryptWork.then(markSettled, markSettled);
92
131
  let plaintext;
93
132
  try {
94
- plaintext = await encryptor.decrypt(fromB64(envelope.ciphertext));
133
+ plaintext = await decryptWork;
95
134
  } catch (cause) {
96
135
  const err = new DecryptError('decrypt failed', {
97
136
  cause
@@ -110,6 +149,15 @@ function wrapHub({ hub, encryptor, groupID, onEvent, onEncryptError }) {
110
149
  // would discard a frame a later key could open).
111
150
  ackHandled(message.sequenceID);
112
151
  continue;
152
+ } finally{
153
+ inFlightDecrypts.delete(settled);
154
+ }
155
+ if (closing) {
156
+ ackedOnDecrypt.delete(message.sequenceID);
157
+ return {
158
+ value: undefined,
159
+ done: true
160
+ };
113
161
  }
114
162
  const decrypted = {
115
163
  sequenceID: message.sequenceID,
@@ -130,11 +178,45 @@ function wrapHub({ hub, encryptor, groupID, onEvent, onEncryptError }) {
130
178
  }
131
179
  },
132
180
  return () {
133
- innerIterator.return?.();
134
- return Promise.resolve({
135
- value: undefined,
136
- done: true
137
- });
181
+ if (closePromise != null) return closePromise;
182
+ closing = true;
183
+ closePromise = (async ()=>{
184
+ if (inFlightDecrypts.size > 0) {
185
+ let timer;
186
+ const expiry = new Promise((resolve)=>{
187
+ timer = setTimeout(()=>resolve('expired'), drainTimeoutMs);
188
+ });
189
+ const outcome = await Promise.race([
190
+ Promise.allSettled([
191
+ ...inFlightDecrypts
192
+ ]).then(()=>'drained'),
193
+ expiry
194
+ ]);
195
+ if (timer != null) clearTimeout(timer);
196
+ if (outcome === 'expired') {
197
+ onEvent?.({
198
+ type: 'decrypt-drain-timeout',
199
+ timeoutMs: drainTimeoutMs
200
+ });
201
+ }
202
+ }
203
+ ackedOnDecrypt.clear();
204
+ try {
205
+ // A wire hub may leave return() parked behind an idle next().
206
+ const result = innerIterator.return?.();
207
+ if (result != null) void Promise.resolve(result).catch(()=>{});
208
+ } catch {
209
+ // Closing is best effort.
210
+ }
211
+ return {
212
+ value: undefined,
213
+ done: true
214
+ };
215
+ })();
216
+ const drain = closePromise.then(()=>{});
217
+ drains.add(drain);
218
+ void drain.then(()=>drains.delete(drain), ()=>drains.delete(drain));
219
+ return closePromise;
138
220
  }
139
221
  };
140
222
  return {
@@ -159,7 +241,8 @@ function wrapHub({ hub, encryptor, groupID, onEvent, onEncryptError }) {
159
241
  return wrapped;
160
242
  }
161
243
  export function createEncryptedHubTunnelTransport(params) {
162
- const { hub, encryptor, groupID, onEvent, signal: externalSignal, ...rest } = params;
244
+ const { hub, encryptor, groupID, onEvent, signal: externalSignal, drainTimeoutMs = 5000, ...rest } = params;
245
+ const drains = new Set();
163
246
  const internalController = new AbortController();
164
247
  if (externalSignal != null) {
165
248
  if (externalSignal.aborted) {
@@ -177,14 +260,23 @@ export function createEncryptedHubTunnelTransport(params) {
177
260
  encryptor,
178
261
  groupID,
179
262
  onEvent,
263
+ drainTimeoutMs,
264
+ drains,
180
265
  onEncryptError: (err)=>{
181
266
  internalController.abort(err);
182
267
  }
183
268
  });
184
- return createHubTunnelTransport({
269
+ const transport = createHubTunnelTransport({
185
270
  ...rest,
186
271
  hub: wrappedHub,
187
272
  signal: internalController.signal,
188
273
  onEvent
189
274
  });
275
+ // Enkaku awaits disposed listeners; the pump starts return() in its earlier listener.
276
+ transport.events.on('disposed', async ()=>{
277
+ await Promise.allSettled([
278
+ ...drains
279
+ ]);
280
+ });
281
+ return transport;
190
282
  }
package/lib/events.d.ts CHANGED
@@ -6,6 +6,13 @@ export type ObservabilityEvent = {
6
6
  } | {
7
7
  type: 'envelope-decode-failed';
8
8
  error: EnvelopeDecodeError;
9
+ } | {
10
+ type: 'decrypt-drain-timeout';
11
+ timeoutMs: number;
12
+ } | {
13
+ type: 'ack-failed';
14
+ sequenceID: string;
15
+ error: unknown;
9
16
  } | {
10
17
  type: 'frame-dropped';
11
18
  reason: FrameDroppedReason;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kumiai/hub-tunnel",
3
- "version": "0.9.0",
3
+ "version": "0.10.1",
4
4
  "description": "Peer-to-peer Enkaku transport tunneled through a hub relay",
5
5
  "keywords": [
6
6
  "enkaku",
@@ -26,19 +26,19 @@
26
26
  "lib/*"
27
27
  ],
28
28
  "dependencies": {
29
- "@enkaku/transport": "^0.21.0",
30
- "@kumiai/hub-protocol": "^0.9.0",
29
+ "@enkaku/transport": "^0.21.3",
30
+ "@kumiai/hub-protocol": "^0.10.0",
31
31
  "@sozai/async": "^0.2.1",
32
32
  "@sozai/codec": "^0.4.0",
33
33
  "@sozai/event": "^0.1.3",
34
34
  "@sozai/schema": "^0.1.2"
35
35
  },
36
36
  "devDependencies": {
37
- "@enkaku/client": "^0.21.2",
38
- "@enkaku/protocol": "^0.21.1",
39
- "@enkaku/server": "^0.21.2",
37
+ "@enkaku/client": "^0.21.3",
38
+ "@enkaku/protocol": "^0.21.3",
39
+ "@enkaku/server": "^0.21.3",
40
40
  "@kokuin/token": "^0.5.0",
41
- "@kumiai/hub-conformance": "^0.9.0"
41
+ "@kumiai/hub-conformance": "^0.10.0"
42
42
  },
43
43
  "publishConfig": {
44
44
  "access": "public"
@@ -46,8 +46,8 @@
46
46
  "scripts": {
47
47
  "build": "pnpm run build:clean && pnpm run build:js && pnpm run build:types",
48
48
  "build:clean": "del lib",
49
- "build:js": "swc src -d ./lib --config-file ../../node_modules/@kigu/dev/swc.json --strip-leading-paths",
50
- "build:types": "tsc --emitDeclarationOnly --skipLibCheck",
49
+ "build:js": "del 'lib/**/*.js' && swc src -d ./lib --config-file ../../node_modules/@kigu/dev/swc.json --strip-leading-paths",
50
+ "build:types": "del 'lib/**/*.d.ts' 'lib/**/*.d.ts.map' && tsc --emitDeclarationOnly --skipLibCheck",
51
51
  "test": "pnpm run test:types && pnpm run test:unit",
52
52
  "test:types": "tsc --noEmit -p tsconfig.test.json",
53
53
  "test:unit": "vitest run"