@kumiai/hub-tunnel 0.4.1 → 0.5.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.
@@ -32,9 +32,18 @@ function wrapHub({ hub, encryptor, groupID, onEvent, onEncryptError }) {
32
32
  unsubscribe (subscriberDID, topicID) {
33
33
  return hub.unsubscribe?.(subscriberDID, topicID);
34
34
  },
35
- receive (subscriberDID) {
36
- const inner = hub.receive(subscriberDID);
35
+ receive (subscriberDID, options) {
36
+ const inner = hub.receive(subscriberDID, options);
37
37
  const innerIterator = inner[Symbol.asyncIterator]();
38
+ // A hub's ack may be synchronous and throw synchronously, before `Promise.resolve` sees it —
39
+ // so the rejection guard alone is not enough (same fix as `ackUpstream` in `rpc/src/hub-mux.ts`).
40
+ const ackHandled = (sequenceID)=>{
41
+ try {
42
+ void Promise.resolve(inner.ack?.(sequenceID)).catch(()=>{});
43
+ } catch {
44
+ // ignore
45
+ }
46
+ };
38
47
  const iterator = {
39
48
  async next () {
40
49
  while(true){
@@ -59,24 +68,25 @@ function wrapHub({ hub, encryptor, groupID, onEvent, onEncryptError }) {
59
68
  type: 'frame-dropped',
60
69
  reason: 'envelope-decode'
61
70
  });
71
+ // Dropped here, never reaching the read pump's ack site — so acked here, or it is
72
+ // undecodable and redelivered forever.
73
+ ackHandled(message.sequenceID);
62
74
  continue;
63
75
  }
64
76
  throw error;
65
77
  }
66
- // WHY: the envelope states its group in the clear and we stamp ours on publish, so a
67
- // frame addressed to another group is dropped before we ever hand it to the cipher.
68
- // Honestly: against a working AEAD this catches little — a foreign group's frame is
69
- // encrypted under a key we do not hold and would fail to decrypt anyway. What it does
70
- // catch is the same-key case the cipher cannot see: a misroute or a configuration
71
- // error that puts two groups on one key or one topic, where the bytes authenticate
72
- // perfectly and are still not ours. It is one string compare, before any crypto, so
73
- // the cost of keeping it is nil and the cost of trusting the cipher alone for a
74
- // property the envelope states outright is a silent cross-group delivery.
78
+ // The envelope states its group in the clear and we stamp ours on publish. Against a
79
+ // working AEAD a foreign group's frame would fail to decrypt anyway; what this one string
80
+ // compare catches, before any crypto, is the same-key misroute the cipher cannot see —
81
+ // two groups on one key or topic, bytes authenticating perfectly and still not ours.
75
82
  if (envelope.groupID !== groupID) {
76
83
  onEvent?.({
77
84
  type: 'frame-dropped',
78
85
  reason: 'group-mismatch'
79
86
  });
87
+ // Permanently unhandleable — this reader never holds the right key — so acked, else
88
+ // redelivered every reconnect until the age bound.
89
+ ackHandled(message.sequenceID);
80
90
  continue;
81
91
  }
82
92
  let plaintext;
@@ -94,6 +104,11 @@ function wrapHub({ hub, encryptor, groupID, onEvent, onEncryptError }) {
94
104
  type: 'frame-dropped',
95
105
  reason: 'decrypt'
96
106
  });
107
+ // Acked like the other drop paths. Unlike them this is not permanent by construction —
108
+ // it's a property of the key this reader holds. Safe only because `Encryptor` is fixed
109
+ // for the transport's life; an epoch-keyed encryptor must revisit this (acking here
110
+ // would discard a frame a later key could open).
111
+ ackHandled(message.sequenceID);
97
112
  continue;
98
113
  }
99
114
  const decrypted = {
@@ -128,13 +143,19 @@ function wrapHub({ hub, encryptor, groupID, onEvent, onEncryptError }) {
128
143
  },
129
144
  return () {
130
145
  inner.return?.();
131
- }
146
+ },
147
+ // Forwarded through — this wrapper re-writes the payload and nothing else. Dropping it
148
+ // would sever the durable-ack contract for every lane behind an encrypting hub. Uses the
149
+ // guarded helper so a synchronous `inner.ack` throw does not escape.
150
+ ...inner.ack != null ? {
151
+ ack: ackHandled
152
+ } : {}
132
153
  };
133
- }
154
+ },
155
+ ...hub.events != null ? {
156
+ events: hub.events
157
+ } : {}
134
158
  };
135
- if (hub.events != null) {
136
- wrapped.events = hub.events;
137
- }
138
159
  return wrapped;
139
160
  }
140
161
  export function createEncryptedHubTunnelTransport(params) {
package/lib/index.d.ts CHANGED
@@ -4,4 +4,4 @@ export { decodeEnvelope, encodeEnvelope, TUNNEL_ENVELOPE_VERSION, type TunnelEnv
4
4
  export { BackpressureError, DecryptError, EncryptError, EnvelopeDecodeError, FrameDecodeError, HubReconnectingError, SessionNotEstablishedError, } from './errors.js';
5
5
  export type { FrameDroppedReason, ObservabilityEvent, ObservabilityEventListener, } from './events.js';
6
6
  export { decodeFrame, encodeFrame, HUB_FRAME_VERSION, type HubFrame, type HubFrameMessageBody, hubFrameSchema, } from './frame.js';
7
- export { createHubTunnelTransport, type HubBase, type HubFetchTopicParams, type HubFetchTopicResult, type HubPublishParams, type HubReceiveSubscription, type HubSubscribeOptions, type HubTunnelSessionID, type HubTunnelTransportParams, type LogHub, type MailboxHub, type MailboxHubEvent, type MailboxHubEventListener, type MailboxHubEvents, type MailboxPublishParams, } from './transport.js';
7
+ export { createHubTunnelTransport, type HubBase, type HubFetchTopicParams, type HubFetchTopicResult, type HubPublishParams, type HubReceiveOptions, type HubReceiveSubscription, type HubSubscribeOptions, type HubTunnelSessionID, type HubTunnelTransportParams, type LogHub, type MailboxHub, type MailboxHubEvent, type MailboxHubEvents, type MailboxPublishParams, } from './transport.js';
@@ -1,5 +1,6 @@
1
1
  import { type TransportType } from '@enkaku/transport';
2
2
  import type { StoredMessage } from '@kumiai/hub-protocol';
3
+ import type { EventEmitter } from '@sozai/event';
3
4
  import type { ObservabilityEventListener } from './events.js';
4
5
  export type HubReceiveSubscription = AsyncIterable<StoredMessage> & {
5
6
  return?: () => void;
@@ -11,6 +12,14 @@ export type HubReceiveSubscription = AsyncIterable<StoredMessage> & {
11
12
  */
12
13
  ack?: (sequenceID: string) => void | Promise<void>;
13
14
  };
15
+ /**
16
+ * Scope for a receive stream. Naming the topic lets a refcounted-ack hub know which consumers will
17
+ * handle a frame — an unscoped stream is a candidate holder for every message on every topic.
18
+ * Optional, and a hub is free to ignore it: the consumer still filters what it is handed.
19
+ */
20
+ export type HubReceiveOptions = {
21
+ topicID?: string;
22
+ };
14
23
  export type MailboxHubEvent = {
15
24
  type: 'reconnecting';
16
25
  } | {
@@ -18,10 +27,9 @@ export type MailboxHubEvent = {
18
27
  } | {
19
28
  type: 'disconnected';
20
29
  };
21
- export type MailboxHubEventListener = (event: MailboxHubEvent) => void;
22
- export type MailboxHubEvents = {
23
- subscribe: (listener: MailboxHubEventListener) => () => void;
24
- };
30
+ export type MailboxHubEvents = EventEmitter<{
31
+ status: MailboxHubEvent;
32
+ }>;
25
33
  /**
26
34
  * A mailbox-class publish — the only kind a {@link MailboxHub} accepts. No retention class, no
27
35
  * compare-and-set, no idempotency key: the lanes a MailboxHub fronts (directed tunnel, encrypting
@@ -90,8 +98,8 @@ export type HubFetchTopicResult = {
90
98
  export type HubBase = {
91
99
  subscribe: (subscriberDID: string, topicID: string, options?: HubSubscribeOptions) => Promise<void> | void;
92
100
  unsubscribe?: (subscriberDID: string, topicID: string) => Promise<void> | void;
93
- receive: (subscriberDID: string) => HubReceiveSubscription;
94
- events?: MailboxHubEvents;
101
+ receive: (subscriberDID: string, options?: HubReceiveOptions) => HubReceiveSubscription;
102
+ readonly events?: MailboxHubEvents;
95
103
  };
96
104
  /**
97
105
  * Publish and push-delivery over topics. A subscriber sees only what is published after it
package/lib/transport.js CHANGED
@@ -23,7 +23,9 @@ const DEFAULT_INBOX_CAPACITY = 1024;
23
23
  // Best-effort subscribe; rejection is swallowed (the receive stream still
24
24
  // attaches, and a missing subscription simply yields no inbound frames).
25
25
  void Promise.resolve(hub.subscribe(localDID, receiveTopicID)).catch(()=>{});
26
- const subscription = hub.receive(localDID);
26
+ const subscription = hub.receive(localDID, {
27
+ topicID: receiveTopicID
28
+ });
27
29
  const iterator = subscription[Symbol.asyncIterator]();
28
30
  let abortHandler;
29
31
  let torndown = false;
@@ -110,6 +112,16 @@ const DEFAULT_INBOX_CAPACITY = 1024;
110
112
  const markActivity = ()=>{
111
113
  lastActivity = Date.now();
112
114
  };
115
+ // A hub's ack may be synchronous and throw synchronously, before `Promise.resolve` sees it — so
116
+ // the rejection guard alone is not enough (same fix as `ackUpstream` in rpc/src/hub-mux.ts). An
117
+ // escape here would kill the pump's IIFE.
118
+ const ackHandled = (sequenceID)=>{
119
+ try {
120
+ void Promise.resolve(subscription.ack?.(sequenceID)).catch(()=>{});
121
+ } catch {
122
+ // ignore
123
+ }
124
+ };
113
125
  const readable = new ReadableStream({
114
126
  start (controller) {
115
127
  readableController = controller;
@@ -141,61 +153,79 @@ const DEFAULT_INBOX_CAPACITY = 1024;
141
153
  return;
142
154
  }
143
155
  const message = result.value;
144
- if (message.topicID !== receiveTopicID) {
145
- onEvent?.({
146
- type: 'frame-dropped',
147
- reason: 'topic-mismatch'
148
- });
149
- continue;
150
- }
151
- let frame;
156
+ // Every outcome below is HANDLED (enqueued, filtered, deduped, undecodable, session-end)
157
+ // except the two teardown branches — backpressure overflow and a non-FrameDecodeError
158
+ // decode — which flip this false: the frame never reached the consumer, so acking would
159
+ // report a lost frame as handled. The ack lives in the `finally` (one place, not one per
160
+ // `continue`) so a new drop path can't skip it.
161
+ let handled = true;
152
162
  try {
153
- frame = decodeFrame(message.payload);
154
- } catch (error) {
155
- if (error instanceof FrameDecodeError) continue;
156
- teardown(error);
157
- return;
158
- }
159
- if (lockedSessionID == null) {
160
- lockedSessionID = frame.sessionID;
161
- } else if (frame.sessionID !== lockedSessionID) {
162
- onEvent?.({
163
- type: 'frame-dropped',
164
- reason: 'session-mismatch'
165
- });
166
- continue;
167
- }
168
- if (frame.kind === 'session-end') {
169
- torndown = true;
170
- clearIdleTimer();
163
+ if (message.topicID !== receiveTopicID) {
164
+ onEvent?.({
165
+ type: 'frame-dropped',
166
+ reason: 'topic-mismatch'
167
+ });
168
+ continue;
169
+ }
170
+ let frame;
171
171
  try {
172
- controller.close();
173
- } catch {
174
- // already closed
172
+ frame = decodeFrame(message.payload);
173
+ } catch (error) {
174
+ if (error instanceof FrameDecodeError) continue;
175
+ handled = false;
176
+ teardown(error);
177
+ return;
178
+ }
179
+ if (lockedSessionID == null) {
180
+ lockedSessionID = frame.sessionID;
181
+ } else if (frame.sessionID !== lockedSessionID) {
182
+ onEvent?.({
183
+ type: 'frame-dropped',
184
+ reason: 'session-mismatch'
185
+ });
186
+ continue;
187
+ }
188
+ if (frame.kind === 'session-end') {
189
+ torndown = true;
190
+ clearIdleTimer();
191
+ try {
192
+ controller.close();
193
+ } catch {
194
+ // already closed
195
+ }
196
+ // Before `iterator.return?.()`: a subscription whose close abandons outstanding
197
+ // claims (hub-mux's mailbox facade does) can no longer honour an ack afterwards.
198
+ ackHandled(message.sequenceID);
199
+ handled = false;
200
+ iterator.return?.();
201
+ onSessionEnd?.();
202
+ return;
203
+ }
204
+ if (frame.kind !== 'message') {
205
+ continue;
206
+ }
207
+ if (frame.seq < expectedSeq) {
208
+ onEvent?.({
209
+ type: 'frame-dropped',
210
+ reason: 'dedup'
211
+ });
212
+ continue;
213
+ }
214
+ const desired = controller.desiredSize;
215
+ if (desired != null && desired <= 0) {
216
+ const err = new BackpressureError(`Hub tunnel inbox overflow: capacity=${inboxCapacity} session=${lockedSessionID}`);
217
+ handled = false;
218
+ teardown(err);
219
+ return;
220
+ }
221
+ expectedSeq = frame.seq + 1;
222
+ markActivity();
223
+ controller.enqueue(frame.body);
224
+ } finally{
225
+ if (handled) {
226
+ ackHandled(message.sequenceID);
175
227
  }
176
- iterator.return?.();
177
- onSessionEnd?.();
178
- return;
179
- }
180
- if (frame.kind !== 'message') {
181
- continue;
182
- }
183
- if (frame.seq < expectedSeq) {
184
- onEvent?.({
185
- type: 'frame-dropped',
186
- reason: 'dedup'
187
- });
188
- continue;
189
- }
190
- const desired = controller.desiredSize;
191
- if (desired != null && desired <= 0) {
192
- const err = new BackpressureError(`Hub tunnel inbox overflow: capacity=${inboxCapacity} session=${lockedSessionID}`);
193
- teardown(err);
194
- return;
195
228
  }
196
- expectedSeq = frame.seq + 1;
197
- markActivity();
198
- controller.enqueue(frame.body);
199
229
  }
200
230
  })();
201
231
  },
@@ -262,7 +292,7 @@ const DEFAULT_INBOX_CAPACITY = 1024;
262
292
  teardown(new HubReconnectingError('reconnect timeout exceeded'));
263
293
  }, reconnectTimeoutMs);
264
294
  };
265
- unsubscribeEvents = hub.events.subscribe((event)=>{
295
+ unsubscribeEvents = hub.events.on('status', (event)=>{
266
296
  if (torndown) return;
267
297
  switch(event.type){
268
298
  case 'reconnecting':
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kumiai/hub-tunnel",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "Peer-to-peer Enkaku transport tunneled through a hub relay",
5
5
  "keywords": [
6
6
  "enkaku",
@@ -28,16 +28,20 @@
28
28
  "dependencies": {
29
29
  "@enkaku/transport": "^0.20.0",
30
30
  "@sozai/async": "^0.2.1",
31
- "@sozai/codec": "^0.2.0",
31
+ "@sozai/codec": "^0.3.0",
32
+ "@sozai/event": "^0.1.3",
32
33
  "@sozai/schema": "^0.1.1",
33
- "@kumiai/hub-protocol": "^0.4.1"
34
+ "@kumiai/hub-protocol": "^0.5.0"
34
35
  },
35
36
  "devDependencies": {
36
37
  "@enkaku/client": "^0.20.0",
37
38
  "@enkaku/protocol": "^0.20.0",
38
39
  "@enkaku/server": "^0.20.0",
39
40
  "@kokuin/token": "^0.3.0",
40
- "@kumiai/hub-conformance": "^0.4.1"
41
+ "@kumiai/hub-conformance": "^0.5.0"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
41
45
  },
42
46
  "scripts": {
43
47
  "build": "pnpm run build:clean && pnpm run build:js && pnpm run build:types",