socketduct 0.1.17 → 0.1.18

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.
@@ -0,0 +1 @@
1
+ Native reverse-gateway streams now keep their app and target sockets alive across transient hub transport loss, preserve unread flow-control and terminal-close state, and replay durably spooled bytes exactly once after paired resume.
@@ -106,14 +106,21 @@ resolved from the requested target for each `OPEN`. The hub maps frames without
106
106
  opening the target or nesting another Socketduct transport. Each home gateway
107
107
  applies the final local allowlist before connecting to its private Docker shim.
108
108
 
109
- Gateway registration reconnects with generation fencing. Established reverse
110
- streams are terminal on transport loss because replaying an ambiguous Docker
111
- operation would be unsafe. Live-transport buffers remain bounded; durable
112
- spooling and resume continue to apply to ordinary Socketduct sessions only.
109
+ Gateway and client registrations reconnect with generation fencing. The hub
110
+ retains each established bridge for a bounded window while the live gateway
111
+ keeps its original target socket and both endpoints durably retain
112
+ unacknowledged send chunks. Replacement physical generations exchange paired
113
+ resume manifests; the hub reconciles receiver-committed sequence positions
114
+ before either side replays. This resumes the same byte stream without reopening
115
+ the target or issuing a second application request. Reverse process replacement
116
+ remains terminal because the original target/app socket objects cannot move to
117
+ a new process.
118
+
113
119
  The hub serializes output independently for each physical destination with a
114
120
  bounded queue, so one backpressured target gateway cannot stop client frames
115
121
  bound for a healthy sibling gateway. Exceeding that destination bound closes
116
- only the unhealthy physical owner and releases its mapped streams.
122
+ only the unhealthy physical owner and fails its mapped streams with the causal
123
+ limit error.
117
124
  See [Native reverse gateway](reverse-gateway.md).
118
125
 
119
126
  ### Edge
package/docs/protocol.md CHANGED
@@ -43,13 +43,17 @@ emits it and ordinary handlers reject it as unnegotiated.
43
43
  before `AUTH_OK`.
44
44
  - `PING` / `PONG`: connection heartbeat and readiness.
45
45
  - `RESUME` / `RESUMED`: bounded pages of stream manifests. Each entry contains
46
- stream ID, stable identifier and both directional acknowledgement positions.
46
+ stream ID, stable identifier and both directional sequence/acknowledgement
47
+ positions. Ordinary v3 uses one client manifest; native reverse resume pairs
48
+ independently authenticated client and gateway manifests at the hub.
47
49
  - `GOAWAY`: terminal physical-connection shutdown. Authentication,
48
50
  authorization and TLS failures are terminal and are not retried forever.
49
51
  - `GATEWAY_REGISTER` / `GATEWAY_REGISTERED`: reverse-only authenticated stable
50
- gateway registration and generation fencing.
52
+ gateway registration and generation fencing. The response declares whether
53
+ retained logical streams require a resume manifest.
51
54
  - `GATEWAY_SELECT` / `GATEWAY_SELECTED`: reverse-only binding of a client
52
- physical member to one currently registered gateway before readiness.
55
+ physical member to one exact gateway or route class before readiness. The
56
+ response likewise declares retained resume state.
53
57
 
54
58
  ### Stream control (nonzero stream ID)
55
59
 
@@ -72,11 +76,13 @@ bounded per stream and in aggregate per connection. Control frames have
72
76
  priority; DATA frames use round-robin scheduling with bounded frame sizes, so a
73
77
  large upload cannot monopolize the physical connection.
74
78
 
75
- Flow-control credit and scheduler position belong to one physical generation.
76
- After both peers reconcile cumulative durable acknowledgements in RESUME, each
77
- surviving stream begins the replacement generation with a fresh negotiated
78
- window and replay is rebuilt strictly above the reconciled ACK. Credit consumed
79
- by a failed transport is never carried forward.
79
+ Scheduler position belongs to one physical generation, while receive-side
80
+ flow-control debt belongs to the logical stream. After both peers reconcile in
81
+ RESUME, a sender retains its negotiated window minus bytes the receiver already
82
+ accepted but has not application-acknowledged. Those bytes are not replayed,
83
+ but remain spooled until the durable ACK advances; replay starts strictly above
84
+ the receiver's high-water sequence. A failed transport therefore cannot turn
85
+ unread `VirtualSocket` bytes back into fresh credit.
80
86
 
81
87
  Relay retention is bounded independently per stream, per connection identity,
82
88
  and process-wide. The process-wide reservation is owned by the relay runtime
@@ -113,7 +119,31 @@ then authorizes the exact principal/gateway/target tuple and the gateway
113
119
  separately authorizes its local target. Zero, multiple, stale, disconnected, or
114
120
  mismatched resolutions reset the stream without weakening sibling routes.
115
121
  Registration reconnect uses a higher generation, but any established stream on
116
- the lost gateway is reset and never replayed.
122
+ the lost gateway remains bound to its original client, gateway process, and
123
+ target socket during the bounded resume window. The hub also replaces the
124
+ corresponding client physical transport so neither endpoint can advance without
125
+ paired reconciliation.
126
+
127
+ On replacement, both reverse peers send paginated `RESUME` entries containing
128
+ the stable identifier, each direction's allocated sequence and durable ACK,
129
+ and directional END state. The hub verifies authenticated owner, stable stream
130
+ ID/identifier, monotonic bounds, and cross-peer positions. It preserves both
131
+ the receiver high-water sequence and its application-acknowledged boundary in
132
+ each per-stream `RESUMED` result, and only then admits replay. Senders replay
133
+ durable raw chunks strictly above the high-water sequence while retaining
134
+ unacknowledged chunks and charging their outstanding bytes to the new window.
135
+ A DATA frame that entered a failed physical socket but did not reach the
136
+ logical receiver is therefore replayed; a byte already buffered by the receiver
137
+ is not delivered twice. The target socket is never reopened and the application
138
+ request is never recreated as a new stream.
139
+
140
+ Reverse send replay is persisted before transmission on both the Server3 client
141
+ and outbound gateway. ACKs truncate those private temporary spools. Missing
142
+ targets, expired retention, identity or manifest mismatch, and configured
143
+ buffer/spool/output bounds produce one terminal stream error with the causal
144
+ code. Process-replacement recovery remains unsupported for reverse streams
145
+ because a replacement gateway process cannot inherit the original target TCP
146
+ socket.
117
147
 
118
148
  Hub output has one ordered owner per physical destination. Frames for a
119
149
  backpressured gateway remain in that gateway's bounded queue while frames for
@@ -124,8 +154,10 @@ destinations. Ordering within each destination and stream is preserved.
124
154
  Stream IDs must increase monotonically on each physical connection. END and
125
155
  CLOSE positions must match the sender's accepted raw-byte sequence; a
126
156
  gateway-originated CLOSE is retained until the client acknowledges it with
127
- CLOSE. RESET is immediately terminal. Repeats, data after END, and stale ACKs
128
- are protocol violations.
157
+ CLOSE, including across physical resume. A client that echoes CLOSE immediately
158
+ after resume uses the receiver-confirmed client-to-gateway position rather than
159
+ a stale pre-resume transmit position. RESET is immediately terminal. Repeats,
160
+ data after END, and stale ACKs are protocol violations.
129
161
 
130
162
  Reverse peers must negotiate `zstd` before selection/registration completes.
131
163
  A compressed DATA payload is `uint32_be(uncompressedLength)` followed by one
@@ -65,8 +65,9 @@ The hub rejects unknown IDs, registration by the wrong principal, a second
65
65
  connection identity claiming the same ID, stale generations, repeated IDs,
66
66
  malformed frames, unauthorized routes, and configured limits. A higher
67
67
  generation from the same stable connection identity fences its prior transport.
68
- At the configured identity bound, the oldest disconnected client identity is
69
- evicted; active owners are never evicted and retain generation fencing.
68
+ At the configured identity bound, the oldest disconnected, streamless client
69
+ identity is evicted; retained-stream and active owners are never evicted and
70
+ retain generation fencing.
70
71
  Zero eligible gateways denies the target, and multiple eligible gateways deny
71
72
  the stream as ambiguous. Unknown classes, class mismatches, stale registrations,
72
73
  and disconnected resolved gateways also fail closed. The home gateway
@@ -82,17 +83,30 @@ zstd runtime support and always uses TLS with certificate verification enabled;
82
83
  there is no plaintext or `rejectUnauthorized:false` reverse option.
83
84
 
84
85
  Each peer advertises its receive window during authentication and stream open;
85
- senders use the smaller local and peer window for stream credit. A graceful hub
86
- shutdown is transient and reconnects the client and gateway registrations, while
87
- authentication, authorization, and stale-generation rejections remain terminal.
86
+ senders use the smaller local and peer window for stream credit. A hub-directed
87
+ physical replacement is transient and reconnects the client and gateway
88
+ registrations, while loss of the hub's retained state, authentication,
89
+ authorization, and stale-generation rejections remain terminal.
90
+
91
+ After an established stream loses either reverse physical transport, the hub
92
+ retains its authenticated bridge for the configured resume window and fences the
93
+ old generation. It makes both logical endpoints reconnect so each can present a
94
+ paginated `RESUME` manifest containing the stable stream identifier, both
95
+ directional sequence/ACK positions, and half-close state. The hub releases the
96
+ replacement generation only after both manifests agree. Each sender then
97
+ replays only durable chunks above the receiver-confirmed high-water position,
98
+ with its flow-control window reduced by bytes already buffered but not yet
99
+ consumed at the receiver. A registered gateway completing this paired resume is
100
+ not healthy or eligible for a new selection or `OPEN`; retained peers alone may
101
+ attach to submit their resume manifests.
88
102
 
89
103
  The hub owns a separate ordered output queue for every client and gateway
90
104
  physical connection. Each queue defaults to a 32 MiB bound and can be set with
91
105
  the programmatic `maxOutputBytesPerConnection` hub option. Backpressure on one
92
106
  gateway therefore cannot pause client input for a healthy gateway in the same
93
107
  route class. If one destination exceeds its bound, the hub closes that physical
94
- connection and its mapped streams through the normal detach path; sibling
95
- gateways and the route-class client connection remain usable.
108
+ connection and fails its mapped streams with `OUTPUT_BACKPRESSURE_LIMIT`;
109
+ sibling gateways and the route-class client connection remain usable.
96
110
 
97
111
  An application write may be larger than the configured reverse-stream buffer.
98
112
  The client admits it in bounded slices no larger than the negotiated peer window
@@ -110,21 +124,35 @@ in-memory gateway registry across independent cluster workers.
110
124
  ## Failure and replay boundary
111
125
 
112
126
  Gateway registration reconnects with bounded exponential delay and a higher
113
- generation. An established Docker stream does **not** survive that transport
114
- loss: the hub resets it with `GATEWAY_DISCONNECTED`, both endpoints release the
115
- stream, and the gateway destroys its local Docker socket. A route-class client
116
- physical connection stays authenticated, so streams through other gateways in
117
- the class and later opens to those targets remain usable. This is intentional.
118
- A Docker request whose write reached dockerd but whose response did not reach
119
- TensorBuzz has an ambiguous outcome and must never be replayed automatically.
120
- TensorBuzz must reconcile that Docker operation and then create a new stream.
121
-
122
- Consequently reverse streams have bounded in-memory flow-control/replay queues
123
- only for the live transport and report zero spool bytes. They do not persist an
124
- operation spool across disconnect or process replacement; `recoverConnection()`
125
- fails explicitly. Ordinary resumable Socketduct sessions retain their existing
126
- durable spool behavior. This split is the safety boundary between reconnecting
127
- the gateway registration and replaying privileged Docker operations.
127
+ generation. An established Docker stream survives a transient physical loss
128
+ when the hub process and its retained state, live client object, outbound gateway process, and
129
+ original target socket remain available through the configured resume window.
130
+ Socketduct keeps
131
+ the app-facing socket open, durably spools each direction's unacknowledged raw
132
+ chunks before sending them, reconciles the two receiver-committed ACK positions,
133
+ and separately preserves each receiver's accepted high-water position. It
134
+ replays only bytes above the high-water position, retains buffered-but-unread
135
+ bytes against the flow-control window until ACK, and keeps terminal CLOSE state
136
+ until the echoed CLOSE arrives. It never creates a replacement logical stream
137
+ or reconnects dockerd, so an application request is not executed again merely
138
+ because the WAN transport changed.
139
+
140
+ This is transparent transport replay, not application-operation retry. Bytes
141
+ already committed to dockerd are acknowledged by the surviving gateway and are
142
+ not replayed; bytes already accepted by the surviving app-facing socket are
143
+ likewise not delivered twice. Sequence gaps, overlaps, identity/ownership
144
+ mismatches, invalid manifests, spool/buffer limits, and authorization failures
145
+ fail closed.
146
+
147
+ Reverse replay state is bounded per stream and connection and stored in private
148
+ temporary spool directories. ACKed chunks are truncated, and terminal
149
+ close/reset removes the spool. `status().spoolBytes` reports retained durable
150
+ payload. `registerRecoveredConnection()` remains unsupported for reverse mode:
151
+ a process replacement cannot inherit the live target socket or the prior
152
+ `VirtualSocket`. If either endpoint process disappears, the target socket is
153
+ lost, or the hub resume window expires, the logical stream fails once with the
154
+ causal session-loss/reset code and the application must reconcile at its own
155
+ protocol layer.
128
156
 
129
157
  Target bytes already observed by the gateway are ordered before a subsequent
130
158
  target-error reset. Stream `END` remains a directional half-close, while protocol
@@ -207,11 +235,18 @@ await starting
207
235
  Route-class sockets expose immutable `routeClass` allocation metadata and an
208
236
  undefined `gatewayId`. Exact-gateway sets retain immutable `gatewayId` metadata.
209
237
  Callers cannot override either selection per open. Reverse streams remain
210
- non-recoverable after an uncertain transport loss.
238
+ sticky to their selected gateway/target but resume transparently after a
239
+ transient physical transport replacement.
211
240
 
212
241
  The socket is returned immediately and waits inside Socketduct until the set
213
242
  reaches minimum readiness. New sockets rotate equally across ready members and
214
243
  stay on their assigned member. If all members are reconnecting, new sockets wait
215
244
  FIFO without selecting a connecting gateway; a recovered member resumes those
216
245
  opens. A disconnected member leaves readiness and rejoins after authenticated
217
- registration; existing streams on it fail for application-level reconciliation.
246
+ registration and paired stream resume; existing sockets remain open unless the
247
+ target/session is genuinely lost or a configured resume/buffer bound expires.
248
+
249
+ The paired reverse-resume fields are a protocol compatibility boundary. Upgrade
250
+ the hub, outbound gateways, and Server3/TensorBuzz Socketduct consumer together;
251
+ 0.1.17 and older reverse peers do not exchange these manifests and cannot
252
+ provide transparent established-stream recovery.
package/docs/security.md CHANGED
@@ -166,10 +166,18 @@ stops reading cannot grow an unbounded queue or stall authorization, DATA, or
166
166
  OPEN processing for a healthy sibling; exceeding the bound disconnects only
167
167
  that destination and resets its owned streams.
168
168
 
169
- Reverse registration can reconnect; established Docker streams cannot resume
170
- or spool across loss. They fail with an explicit uncertain-operation error so
171
- the caller must reconcile before retrying. This prevents privileged Docker API
172
- writes from being applied twice.
169
+ Native reverse peers retain established logical streams for a bounded resume
170
+ window when only a hub transport is lost. Both authenticated endpoints must
171
+ reconnect with the same stable identities and newer generations, then present
172
+ matching per-stream identifiers, byte positions, acknowledgements, and
173
+ half-close state. Application bytes are durably spooled before transmission;
174
+ the hub reconciles to each receiver's committed position and permits replay
175
+ only above it. This preserves exact-once delivery without reopening or
176
+ reissuing a privileged Docker request. Ownership mismatches, missing targets,
177
+ invalid or incomplete manifests, resource-bound failures, and expired resume
178
+ windows fail the affected logical stream once instead of falling back to a new
179
+ stream. Process replacement remains terminal because the live app and target
180
+ sockets cannot be inherited safely.
173
181
 
174
182
  ## Network exposure
175
183
 
@@ -268,4 +276,6 @@ To roll back TLS: remove the TLS env vars from `.env`. If the relay binds to a n
268
276
  - reverse registration rejects wrong principals, duplicate IDs, and stale generations
269
277
  - reverse clients reject unknown/unavailable gateway IDs and wrong TLS CAs
270
278
  - both hub route policy and the home-local allowlist deny unauthorized Docker targets
271
- - gateway loss cleans every stream and target without replay, then a fresh stream works after re-registration
279
+ - transient reverse hub transport loss preserves each live stream and target,
280
+ replays only unacknowledged spooled bytes, and cleans all retained state after
281
+ close; target loss and resume expiry fail once with their causal codes
@@ -11,22 +11,33 @@ spawn per-stream reconnects.
11
11
  ## Reverse-gateway lifecycle
12
12
 
13
13
  An outbound gateway moves through `connecting -> authenticated -> registering
14
- -> ready`. Transport loss destroys every local target stream, advances the
15
- gateway generation, and reconnects with bounded exponential delay. Selected
16
- Server3 client members leave readiness when that gateway disappears and rejoin
17
- only after it registers again.
18
-
19
- Reverse stream loss is terminal even when registration later recovers. No
20
- established Docker bytes are persisted or replayed because their outcome may
21
- already be committed at dockerd. The application receives
22
- `GATEWAY_DISCONNECTED`, reconciles the operation, and opens a new stream.
14
+ -> ready`. Transport loss advances the gateway generation and reconnects with
15
+ bounded exponential delay without destroying established local targets. The hub
16
+ retains authenticated bridge ownership for the configured resume window and
17
+ replaces the affected Server3 client physical generation as well.
18
+
19
+ Both reverse endpoints keep their logical sockets alive, persist unacknowledged
20
+ send chunks, and submit their stable identifiers plus both directional
21
+ sequence/ACK positions. The hub resumes a bridge only after the two manifests
22
+ agree and returns both the receiver's accepted high-water sequence and its
23
+ application-consumed ACK to each sender. Bytes above the high-water position
24
+ replay on the same logical stream; accepted-but-unread bytes stay charged to the
25
+ window and spooled until ACK. This preserves exact-once, in-order delivery
26
+ without opening a second target or retrying an application operation.
27
+
28
+ If the original target socket disappears, an owner/identifier or sequence does
29
+ not match, a buffer/spool bound is exceeded, or the resume window expires, that
30
+ logical stream fails once with the causal error and releases both sides. Reverse
31
+ process-replacement recovery remains unsupported because the live target and
32
+ app-facing socket cannot be transferred to replacement JavaScript objects.
23
33
 
24
34
  The bounded, paginated resume manifest carries stable identifiers and both
25
35
  directional acknowledgement positions. The relay returns an independent result
26
36
  per stream. A stream omitted because it was closed while disconnected is
27
37
  cleaned up at the relay. A target lost during interruption returns a stream-local
28
38
  resume reset and a typed session-loss error, while retained siblings continue.
29
- Only bytes above the peer acknowledgement are replayed.
39
+ Only bytes above the peer's received high-water sequence are replayed; spool
40
+ cleanup remains governed by its acknowledgement.
30
41
 
31
42
  ## States
32
43
 
@@ -190,8 +190,9 @@ becomes the stable, immutable configured ID. For a route-class set,
190
190
  the socket first removes the pending open, so later readiness cannot leak a
191
191
  member stream. An exact relay member selected immediately before its path drops
192
192
  retains the stream and performs member-local v3 recovery; the set never
193
- speculatively migrates it. A reverse route-class stream fails terminally on an
194
- uncertain transport loss and is never replayed.
193
+ speculatively migrates it. A reverse route-class stream likewise remains on its
194
+ resolved target gateway while Socketduct replaces and resumes the physical
195
+ client/gateway transports underneath it.
195
196
 
196
197
  `createConnection(options, callback)` is pre-bound and invokes its callback once
197
198
  on `connect` or the terminal pre-connect error; the socket emits `connect` before
@@ -220,7 +221,9 @@ stickiness. Every returned raw or TLS socket exposes enumerable `gatewayId` and
220
221
  `routeClass` allocation metadata. Only the configured identity is set. Persist
221
222
  an exact set's immutable `gatewayId` after connection so a replacement can
222
223
  recover the stream on its original member. Reverse route-class streams are not
223
- recoverable after an uncertain transport loss.
224
+ recoverable across process replacement, but they do recover transparently from
225
+ a transient physical transport loss while the original objects and target
226
+ socket remain alive.
224
227
 
225
228
  Process-replacement recovery is deliberately separate from ordinary selection.
226
229
  First detach the old set when an orderly handoff is possible. Construct the
@@ -399,8 +402,12 @@ It selects exactly one registered gateway during `connect()`. The existing
399
402
  `MultiplexedSocketductTransportSet` accepts `endpoint.reverseHub`, allowing
400
403
  three ready members to retain deterministic health-aware round-robin behavior.
401
404
  Reverse established operations deliberately do not support
402
- `registerRecoveredConnection()` or durable replay; a transport loss is a typed
403
- terminal result requiring application reconciliation.
405
+ `registerRecoveredConnection()` across process replacement. They do durably
406
+ spool unacknowledged send chunks during the lifetime of the client and gateway
407
+ objects, then use paired v3 resume manifests to survive physical transport
408
+ replacement without reopening the target or replaying an application request
409
+ as a new logical stream. Target loss, resume expiry, identity mismatch, or a
410
+ configured bound remains terminal and requires application reconciliation.
404
411
 
405
412
  Reverse virtual sockets accept individual writes larger than their configured
406
413
  retained-byte limit. The connection progresses those writes in slices bounded by
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "socketduct",
3
- "version": "0.1.17",
3
+ "version": "0.1.18",
4
4
  "description": "Resilient authenticated tunnel/proxy for keeping socket streams alive across flaky links.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -270,6 +270,7 @@ export class MultiplexedSocketductTransportSet extends EventEmitter {
270
270
  tls: endpoint.tls,
271
271
  ...(endpoint.createPhysicalSocket === undefined ? {} : {createPhysicalSocket: endpoint.createPhysicalSocket}),
272
272
  connectionId: identity.connectionId,
273
+ spoolDirectory: join(validated.spoolDirectory, identity.spoolName),
273
274
  continuousReconnect: true,
274
275
  aggregateBudget: this.#budget,
275
276
  ...(this.#logger === undefined ? {} : {logger: this.#logger})