@kumiai/hub-tunnel 0.13.2 → 0.13.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/README.md CHANGED
@@ -1,3 +1,42 @@
1
1
  # @kumiai/hub-tunnel
2
2
 
3
3
  Peer-to-peer transport tunneled through a hub relay. Carries any `@enkaku` protocol over a pluggable `Encryptor` (BYO key exchange).
4
+
5
+ ## Sharing a host receive lane
6
+
7
+ A hub server binds one receive writer per DID. A reconnect replaces that writer.
8
+ When a host runs a group peer alongside external directed tunnels, wrap its hub adapter once:
9
+
10
+ ```ts
11
+ import { createSharedHub, createHubTunnelTransport } from '@kumiai/hub-tunnel'
12
+ import { createGroupPeer } from '@kumiai/rpc'
13
+
14
+ // wireLogHub is the host's LogHub adapter over its authenticated HubClient connection.
15
+ const shared = createSharedHub({ hub: wireLogHub })
16
+ const peer = createGroupPeer({ ...peerParams, hub: shared.createView() })
17
+ const tunnel = createHubTunnelTransport({ ...tunnelParams, hub: shared.hub })
18
+
19
+ // At host shutdown, after disposing its peer and tunnels:
20
+ shared.dispose()
21
+ ```
22
+
23
+ Give each peer its own `shared.createView()`. External tunnels use `shared.hub`.
24
+ Calling the underlying adapter's
25
+ `receive` opens another wire channel and replaces the shared writer.
26
+ `HubClient.receive()` remains the low-level channel API.
27
+
28
+ `createSharedHub` accepts a `MailboxHub` or `LogHub` and preserves its publish, subscription,
29
+ fetch and connection-event behaviour. It opens one unscoped upstream receive per DID.
30
+ Local receives can name a topic. Only matching consumers receive and acknowledge each frame.
31
+ Each peer view scopes unscoped receives to topics requested through that view's `subscribe`.
32
+ This prevents peers claiming unrelated tunnel frames. Subscribe and unsubscribe still forward to the underlying hub.
33
+ Unmatched startup frames wait in a bounded host buffer until a matching consumer subscribes.
34
+ The upstream acknowledgement waits for every matching consumer. An abandoned frame remains unacknowledged.
35
+
36
+ Closing one consumer keeps the others live. Closing the last consumer releases that DID's wire lane.
37
+ A later receive opens a fresh lane. Wire errors and normal endings reach every attached consumer.
38
+ The host owns reconnection. `dispose()` closes all lanes without unsubscribing durable topics.
39
+
40
+ `inboxCapacity` defaults to 1024 queued or unacknowledged frames per consumer.
41
+ The same bound applies to unmatched frames. Past it, the lane drops the oldest local copy without acknowledging it, so a reconnect can redeliver that durable frame. The lane and its consumers stay live.
42
+ An overflowing consumer fails with `BackpressureError`, leaving other consumers live and lost frames unacknowledged.
package/lib/index.d.ts CHANGED
@@ -5,5 +5,6 @@ export { BackpressureError, DecryptError, DuplicateFrameError, EncryptError, Env
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
7
  export { precedesSequenceID } from './sequence.js';
8
+ export { createSharedHub, type SharedHub, type SharedHubParams } from './shared-hub.js';
8
9
  export type { HubBaseReceiveParams, HubBaseSubscribeParams, HubBaseUnsubscribeParams, } from './transport.js';
9
10
  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';
package/lib/index.js CHANGED
@@ -4,4 +4,5 @@ export { decodeEnvelope, encodeEnvelope, TUNNEL_ENVELOPE_VERSION, tunnelEnvelope
4
4
  export { BackpressureError, DecryptError, DuplicateFrameError, EncryptError, EnvelopeDecodeError, ExpiredFrameError, FrameDecodeError, HubReconnectingError, SessionNotEstablishedError } from './errors.js';
5
5
  export { decodeFrame, encodeFrame, HUB_FRAME_VERSION, hubFrameSchema } from './frame.js';
6
6
  export { precedesSequenceID } from './sequence.js';
7
+ export { createSharedHub } from './shared-hub.js';
7
8
  export { createHubTunnelTransport } from './transport.js';
@@ -0,0 +1,20 @@
1
+ import type { LogHub, MailboxHub } from './transport.js';
2
+ export type SharedHubParams<Hub extends MailboxHub = MailboxHub> = {
3
+ hub: Hub;
4
+ /** Maximum frames per consumer and live views' startup buffer. Default: 1024. */
5
+ inboxCapacity?: number;
6
+ };
7
+ export type SharedHub<Hub extends MailboxHub = MailboxHub> = {
8
+ hub: Hub;
9
+ /** A separate subscription-scoped view for each group peer. */
10
+ createView: () => Hub;
11
+ /** Close every local consumer and wire lane, without unsubscribing durable topics. */
12
+ dispose: () => void;
13
+ };
14
+ /**
15
+ * One host-owned receive lane per DID, shared by peers and directed tunnels.
16
+ * Give each peer a createView() and external tunnels hub. A raw receive replaces the writer.
17
+ * Each matching consumer owns an acknowledgement. Closing or overflowing one abandons its frames.
18
+ */
19
+ export declare function createSharedHub(params: SharedHubParams<LogHub>): SharedHub<LogHub>;
20
+ export declare function createSharedHub(params: SharedHubParams): SharedHub;
@@ -0,0 +1,262 @@
1
+ import { BackpressureError } from './errors.js';
2
+ export function createSharedHub({ hub, inboxCapacity = 1024 }) {
3
+ if (!Number.isSafeInteger(inboxCapacity) || inboxCapacity < 1) {
4
+ throw new Error('Shared hub inbox capacity must be a positive integer');
5
+ }
6
+ const lanes = new Map();
7
+ const consumers = new Map();
8
+ let disposed = false;
9
+ const stopSink = (lane, sink, failure)=>{
10
+ if (sink.stopped) return;
11
+ sink.stopped = true;
12
+ sink.failure = failure;
13
+ lane.sinks.delete(sink);
14
+ consumers.delete(sink);
15
+ for (const [sequenceID, message] of lane.unmatched){
16
+ if (![
17
+ ...lane.sinks
18
+ ].some((other)=>other.buffers(message.topicID))) {
19
+ lane.unmatched.delete(sequenceID);
20
+ }
21
+ }
22
+ // A partial fan-out cannot acknowledge mail another consumer abandoned.
23
+ for (const claim of sink.pending.values()){
24
+ for (const holder of claim.holders)holder.pending.delete(claim.sequenceID);
25
+ claim.holders.clear();
26
+ }
27
+ sink.pending.clear();
28
+ if (failure != null) sink.controller.error(failure.error);
29
+ else if (!sink.ended) sink.controller.close();
30
+ if (lane.sinks.size === 0) stopLane(lane);
31
+ };
32
+ const stopLane = (lane, failure, drainQueued = false)=>{
33
+ if (lane.stopped) return;
34
+ lane.stopped = true;
35
+ if (lanes.get(lane.subscriberDID) === lane) lanes.delete(lane.subscriberDID);
36
+ lane.unmatched.clear();
37
+ for (const sink of lane.sinks){
38
+ if (drainQueued) {
39
+ sink.ended = true;
40
+ sink.controller.close();
41
+ } else {
42
+ stopSink(lane, sink, failure);
43
+ }
44
+ }
45
+ // Subscription.return can interrupt a parked next; a generator's return may queue behind it.
46
+ try {
47
+ const closed = lane.subscription.return != null ? lane.subscription.return() : lane.iterator.return?.();
48
+ void Promise.resolve(closed).catch(()=>{});
49
+ } catch {
50
+ // Teardown must release the other lanes even if this source's close throws.
51
+ }
52
+ };
53
+ const deliver = (lane, message)=>{
54
+ const sinks = [
55
+ ...lane.sinks
56
+ ].filter((sink)=>sink.accepts(message.topicID));
57
+ if (sinks.length === 0) {
58
+ // Only live views can claim startup copies. Detached mail stays unacked at the hub.
59
+ if (![
60
+ ...lane.sinks
61
+ ].some((sink)=>sink.buffers(message.topicID))) return;
62
+ lane.unmatched.set(message.sequenceID, message);
63
+ if (lane.unmatched.size > inboxCapacity) {
64
+ // Release only the local copy. A reconnect can still redeliver this durable frame.
65
+ const oldest = lane.unmatched.keys().next().value;
66
+ if (oldest != null) lane.unmatched.delete(oldest);
67
+ }
68
+ return;
69
+ }
70
+ const claim = {
71
+ sequenceID: message.sequenceID,
72
+ holders: new Set(sinks)
73
+ };
74
+ if (lane.subscription.ack != null) {
75
+ for (const sink of sinks)sink.pending.set(message.sequenceID, claim);
76
+ }
77
+ for (const sink of sinks){
78
+ if ((sink.controller.desiredSize ?? 0) <= 0 || sink.pending.size > inboxCapacity) {
79
+ stopSink(lane, sink, {
80
+ error: new BackpressureError(`Shared hub inbox capacity exceeded: ${inboxCapacity}`)
81
+ });
82
+ } else {
83
+ sink.controller.enqueue(message);
84
+ }
85
+ }
86
+ };
87
+ const replay = (subscriberDID)=>{
88
+ const lane = lanes.get(subscriberDID);
89
+ if (lane == null) return;
90
+ for (const [sequenceID, message] of lane.unmatched){
91
+ if (![
92
+ ...lane.sinks
93
+ ].some((sink)=>sink.accepts(message.topicID))) continue;
94
+ lane.unmatched.delete(sequenceID);
95
+ deliver(lane, message);
96
+ }
97
+ };
98
+ const drain = async (lane)=>{
99
+ try {
100
+ while(!lane.stopped){
101
+ const result = await lane.iterator.next();
102
+ if (lane.stopped) return;
103
+ if (result.done) break;
104
+ deliver(lane, result.value);
105
+ }
106
+ stopLane(lane, undefined, true);
107
+ } catch (error) {
108
+ stopLane(lane, {
109
+ error
110
+ });
111
+ }
112
+ };
113
+ const receive = ({ subscriberDID, topicID }, accepts = ()=>true, bufferUnmatched = false)=>{
114
+ if (disposed) throw new Error('Shared hub is disposed');
115
+ let lane = lanes.get(subscriberDID);
116
+ const starting = lane == null;
117
+ if (lane == null) {
118
+ const subscription = hub.receive({
119
+ subscriberDID
120
+ });
121
+ lane = {
122
+ subscriberDID,
123
+ subscription,
124
+ iterator: subscription[Symbol.asyncIterator](),
125
+ sinks: new Set(),
126
+ unmatched: new Map(),
127
+ stopped: false
128
+ };
129
+ lanes.set(subscriberDID, lane);
130
+ }
131
+ const current = lane;
132
+ let sink;
133
+ const stream = new ReadableStream({
134
+ start (controller) {
135
+ sink = {
136
+ accepts: (topic)=>(topicID == null || topicID === topic) && accepts(topic),
137
+ buffers: (topic)=>bufferUnmatched && (topicID == null || topicID === topic),
138
+ controller,
139
+ pending: new Map(),
140
+ stopped: false,
141
+ ended: false
142
+ };
143
+ current.sinks.add(sink);
144
+ consumers.set(sink, current);
145
+ }
146
+ }, {
147
+ highWaterMark: inboxCapacity
148
+ });
149
+ // ReadableStream.start runs synchronously.
150
+ if (sink == null) throw new Error('Shared hub stream did not initialise');
151
+ const consumer = sink;
152
+ const reader = stream.getReader();
153
+ void reader.closed.catch(()=>{});
154
+ const close = ()=>stopSink(current, consumer);
155
+ const iterator = {
156
+ [Symbol.asyncIterator] () {
157
+ return this;
158
+ },
159
+ async next () {
160
+ if (consumer.failure != null) throw consumer.failure.error;
161
+ if (consumer.stopped) return {
162
+ done: true,
163
+ value: undefined
164
+ };
165
+ const result = await reader.read();
166
+ if (result.done) close();
167
+ return result.done ? {
168
+ done: true,
169
+ value: undefined
170
+ } : {
171
+ done: false,
172
+ value: result.value
173
+ };
174
+ },
175
+ async return () {
176
+ close();
177
+ return {
178
+ done: true,
179
+ value: undefined
180
+ };
181
+ }
182
+ };
183
+ replay(subscriberDID);
184
+ if (starting) void drain(current);
185
+ return {
186
+ [Symbol.asyncIterator]: ()=>iterator,
187
+ return: close,
188
+ ack: (sequenceID)=>{
189
+ const claim = consumer.pending.get(sequenceID);
190
+ if (claim == null) return;
191
+ consumer.pending.delete(sequenceID);
192
+ claim.holders.delete(consumer);
193
+ if (claim.holders.size === 0) return current.subscription.ack?.(sequenceID);
194
+ }
195
+ };
196
+ };
197
+ const shared = {
198
+ subscribe: (subscription)=>hub.subscribe(subscription),
199
+ ...hub.unsubscribe == null ? {} : {
200
+ unsubscribe: hub.unsubscribe.bind(hub)
201
+ },
202
+ publish: (publication)=>hub.publish(publication),
203
+ ...'fetchTopic' in hub ? {
204
+ fetchTopic: hub.fetchTopic.bind(hub)
205
+ } : {},
206
+ events: hub.events,
207
+ receive
208
+ };
209
+ const createView = ()=>{
210
+ const topics = new Map();
211
+ return {
212
+ ...shared,
213
+ subscribe: async (subscription)=>{
214
+ const { subscriberDID, topicID } = subscription;
215
+ let member = topics.get(subscriberDID);
216
+ if (member == null) {
217
+ member = new Map();
218
+ topics.set(subscriberDID, member);
219
+ }
220
+ let topic = member.get(topicID);
221
+ if (topic == null) {
222
+ topic = {
223
+ held: false,
224
+ pending: new Set()
225
+ };
226
+ member.set(topicID, topic);
227
+ }
228
+ const attempt = Symbol('subscribe');
229
+ topic.pending.add(attempt);
230
+ // Subscribe may push before its promise settles. Register the local scope first.
231
+ replay(subscriberDID);
232
+ try {
233
+ await hub.subscribe(subscription);
234
+ topic.held = true;
235
+ } finally{
236
+ topic.pending.delete(attempt);
237
+ if (!topic.held && topic.pending.size === 0) member.delete(topicID);
238
+ if (member.size === 0) topics.delete(subscriberDID);
239
+ }
240
+ },
241
+ ...hub.unsubscribe == null ? {} : {
242
+ unsubscribe: async (subscription)=>{
243
+ await hub.unsubscribe?.(subscription);
244
+ const member = topics.get(subscription.subscriberDID);
245
+ member?.delete(subscription.topicID);
246
+ if (member?.size === 0) topics.delete(subscription.subscriberDID);
247
+ }
248
+ },
249
+ receive: (subscription)=>{
250
+ return receive(subscription, (topicID)=>topics.get(subscription.subscriberDID)?.has(topicID) === true, true);
251
+ }
252
+ };
253
+ };
254
+ return {
255
+ hub: shared,
256
+ createView,
257
+ dispose: ()=>{
258
+ disposed = true;
259
+ for (const [sink, lane] of consumers)stopSink(lane, sink);
260
+ }
261
+ };
262
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kumiai/hub-tunnel",
3
- "version": "0.13.2",
3
+ "version": "0.13.4",
4
4
  "description": "Peer-to-peer Enkaku transport tunneled through a hub relay",
5
5
  "keywords": [
6
6
  "enkaku",
@@ -27,19 +27,20 @@
27
27
  ],
28
28
  "dependencies": {
29
29
  "@enkaku/transport": "^0.23.3",
30
- "@kumiai/hub-protocol": "^0.13.2",
31
- "@sozai/async": "^0.4.4",
32
- "@sozai/codec": "^0.4.4",
33
- "@sozai/event": "^0.1.6",
30
+ "@kumiai/hub-protocol": "^0.13.3",
31
+ "@sozai/async": "^0.4.6",
32
+ "@sozai/codec": "^0.5.0",
33
+ "@sozai/event": "^0.1.7",
34
34
  "@sozai/runtime": "^0.1.1",
35
35
  "@sozai/schema": "^0.1.6"
36
36
  },
37
37
  "devDependencies": {
38
- "@enkaku/client": "^0.23.7",
39
- "@enkaku/protocol": "^0.23.4",
40
- "@enkaku/server": "^0.23.4",
41
- "@kokuin/token": "^0.7.1",
42
- "@kumiai/hub-conformance": "^0.13.1"
38
+ "@enkaku/client": "^0.23.8",
39
+ "@enkaku/protocol": "^0.23.5",
40
+ "@enkaku/server": "^0.23.6",
41
+ "@kokuin/token": "^0.8.1",
42
+ "@kumiai/hub-conformance": "^0.13.1",
43
+ "@sozai/bytes": "^0.1.0"
43
44
  },
44
45
  "publishConfig": {
45
46
  "access": "public"