socketduct 0.1.32 → 0.1.34

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
@@ -111,6 +111,7 @@ hub address because `gatewayId` selects the outbound member. Docker remains
111
111
  - [Running Socketduct](docs/running.md)
112
112
  - [Docker gateway setup](docs/docker.md)
113
113
  - [Docker topology](docs/docker-topology.md)
114
+ - [Transport-set availability](docs/transport-set-availability.md)
114
115
  - [Node-compatible socket API design](docs/socket-api.md)
115
116
  - [Native reverse gateway](docs/reverse-gateway.md)
116
117
  - [Durable compressed diagnostic logs](docs/logging.md)
@@ -0,0 +1,3 @@
1
+ A reset for one stream no longer marks the member's whole route class unavailable, so a single unreachable target cannot disable every route class and stall all later opens in a transport set.
2
+
3
+ Documents the requirement behind it in `docs/transport-set-availability.md`: per-member availability owned by the hub, failover instead of stalling, automatic recovery without operator action, and no polling watchdog.
@@ -0,0 +1,5 @@
1
+ ### Fixed
2
+
3
+ - Route-class availability failures are now scoped to the exact target that failed. A `GATEWAY_UNAVAILABLE` reset for one target marks only that target on that member, so the transport set stops handing it opens while every other target keeps using the member. The mark is cleared by the next successful open for that same target, so nothing expires on a timer and a member can never be dropped from rotation for machines it can still reach.
4
+
5
+ Releasing 0.1.33 without this scoping removed the only signal the set had for failover: with several route classes configured, opens kept landing on members whose route class could not serve the target and the reset surfaced straight to the caller. Measured on the TensorBuzz fleet, `GATEWAY_UNAVAILABLE` build failures went from 0/hour to about 100/hour within minutes of 0.1.33 reaching the running workers.
@@ -0,0 +1 @@
1
+ Publishes `docker-entrypoint.sh` in the package again, so the committed Dockerfile can build an image from a released tarball.
@@ -0,0 +1,11 @@
1
+ #!/bin/sh
2
+ set -e
3
+
4
+ # Run command with node if the first argument contains a "-" or is not a system command. The last
5
+ # part inside the "{}" is a workaround for the following bug in ash/dash:
6
+ # https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=874264
7
+ if [ "${1#-}" != "${1}" ] || [ -z "$(command -v "${1}")" ] || { [ -f "${1}" ] && ! [ -x "${1}" ]; }; then
8
+ set -- node "$@"
9
+ fi
10
+
11
+ exec "$@"
@@ -347,6 +347,11 @@ const socket = set.createConnection({host: "docker-a", port: 2375})
347
347
  await starting
348
348
  ```
349
349
 
350
+ Availability of a member is decided by the hub's `GATEWAY_SELECTED`
351
+ announcement and cleared by a successful open; a stream reset never changes
352
+ it. Requirements, the selection model and the failure this prevents are in
353
+ [transport-set availability](transport-set-availability.md).
354
+
350
355
  Route-class sockets expose immutable `routeClass` allocation metadata and an
351
356
  undefined `gatewayId`. Exact-gateway sets retain immutable `gatewayId` metadata.
352
357
  Callers cannot override either selection per open. Reverse streams remain
@@ -0,0 +1,119 @@
1
+ # Transport-set availability
2
+
3
+ How `MultiplexedSocketductTransportSet` decides which configured member to use,
4
+ what "down" means for a member, and which component is allowed to say so.
5
+
6
+ This page states the requirements the model exists to satisfy, then describes
7
+ the mechanism. Requirements come from production failures where a runner fleet
8
+ was reported unreachable although every machine answered.
9
+
10
+ ## Requirements
11
+
12
+ 1. **Never use a member the hub reports down.** If the hub says a route class has
13
+ no selectable gateway, opens must not be routed to that member while a ready
14
+ alternative exists.
15
+ 2. **A failure scoped to one target must not disable siblings.** Availability is
16
+ per route class (member). A failure to reach one *target* through one member
17
+ says nothing about the other targets or the other members.
18
+ 3. **Fail over instead of stalling.** If the preferred member is unavailable, an
19
+ open must go to another ready member rather than waiting for the first one.
20
+ 4. **A member that stays down must not block callers indefinitely.** Callers keep
21
+ their own deadlines; the set must not sleep through them while it waits for a
22
+ single member to come back.
23
+ 5. **Recovery is automatic.** When a member becomes selectable again, later opens
24
+ use it again with no operator action — no restart, no container removal, no
25
+ config change.
26
+ 6. **Availability is event-driven, not polled.** The state changes on hub
27
+ announcements and on successful opens. There is no timer that sweeps members
28
+ and no background watchdog that decides health on its own.
29
+ 7. **Marks are attributable and bounded.** A mark is only set by evidence that
30
+ names the member's route class, and it is cleared by later evidence for that
31
+ same member. A mark cannot outlive its evidence.
32
+ 8. **Status is inspectable.** Every member reports `physicalState`,
33
+ `gatewayUnavailable`, and its connection counters through
34
+ `connection.status()`, so a caller can explain why an open was slow.
35
+
36
+ ## What it solves
37
+
38
+ A liveness sweep is one process that probes many targets in sequence. Without
39
+ requirement 2, a single unreachable target poisons every target probed after it
40
+ in that process:
41
+
42
+ ```
43
+ Trinity OK 399 ms
44
+ Lenovo DEAD 10004 ms <- genuinely unreachable
45
+ Morpheus DEAD 10008 ms <- healthy, blocked by the poisoning
46
+ Minisforum DEAD 10011 ms <- healthy, blocked by the poisoning
47
+ Apoc DEAD 10010 ms <- healthy, blocked by the poisoning
48
+ ```
49
+
50
+ Every "dead" row above answers in 63-485 ms when probed in a fresh process. The
51
+ mark also survived for as long as the process lived, so once all members were
52
+ marked the set had nothing to select: no open was attempted, therefore no
53
+ successful open could clear a mark, therefore the marks stayed. A sweep reported
54
+ a healthy fleet as unreachable and withheld its capacity.
55
+
56
+ ## Model
57
+
58
+ ### Who owns availability
59
+
60
+ Only the hub can mark a member unavailable, and only per route class:
61
+
62
+ - The client sends an open. The hub answers with `GATEWAY_SELECTED` carrying
63
+ `selectable`.
64
+ - `selectable: false` marks that member's route class unavailable
65
+ (`GATEWAY_SELECT_UNAVAILABLE`).
66
+ - `selectable: true` clears the mark.
67
+ - A successfully opened stream clears the mark as well
68
+ (`reverse_client.gateway_available`), because a working open is direct
69
+ evidence that the route class works.
70
+
71
+ A stream `RESET` does **not** change availability. A reset describes one stream's
72
+ target; the hub resolves gateways per `(route class, target)`, so a reset is
73
+ scoped to that target and never to the member's whole route class. This scoping
74
+ is the fix for the poisoning above, and it is covered by a regression test in
75
+ `test/integration/reverse-route-class.test.js`.
76
+
77
+ ### Selection
78
+
79
+ `#selectReadyMember` walks the configured members in cursor order and picks the
80
+ first one that is both `physicalState === "ready"` and not marked
81
+ `gatewayUnavailable`. Members skipped for unavailability are remembered as a
82
+ fallback: if **every** ready member is marked down, the set still tries one of
83
+ them instead of refusing. That keeps a stale mark from turning into a hard
84
+ outage, and it means a recovered member is discovered by the next open even
85
+ before the hub has re-announced it.
86
+
87
+ Streams stay sticky to their selected gateway and target; a transient physical
88
+ transport replacement is resumed transparently. Availability decides *new*
89
+ selection, it does not migrate live streams.
90
+
91
+ ### Boundaries
92
+
93
+ - The set does not probe gateways, does not schedule background health checks,
94
+ and does not expire marks on a timer. Health comes from the hub.
95
+ - The set does not synthesize availability from its own errors. A failure that
96
+ is not reported by the hub as unavailability is a plain error for that
97
+ operation.
98
+ - Per-call deadlines belong to the caller. Socketduct does not extend them or
99
+ retry past them.
100
+
101
+ ## Operating it
102
+
103
+ - Inspect `connection.status()` per member: `physicalState`, `gatewayUnavailable`,
104
+ `physicalConnects`, `reconnectAttempts`, `virtualOpens`.
105
+ - Expect `reverse_client.gateway_available` in diagnostics when a member returns
106
+ to service; `reverse_client.gateway_unavailable` marks the opposite.
107
+ - A member that reports `gatewayUnavailable: true` while its machine answers
108
+ locally is a hub-side registration problem (missing or rejected gateway for
109
+ that route class), not a machine fault.
110
+
111
+ ## Verification
112
+
113
+ - `test/integration/reverse-route-class.test.js` - a reset for one target must not
114
+ mark the route class unavailable, and a following open on a healthy target must
115
+ succeed.
116
+ - `test/unit/client/multiplexed-transport-set.test.js` - a member the hub
117
+ registered down is never *selected* while a ready alternative exists.
118
+ - `test/integration/multiplexed-transport-set.test.js` - drain and lifecycle
119
+ behaviour across members.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "socketduct",
3
- "version": "0.1.32",
3
+ "version": "0.1.34",
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",
@@ -16,7 +16,7 @@
16
16
  "./relay": "./src/relay.js"
17
17
  },
18
18
  "engines": {
19
- "node": "^24.0.0"
19
+ "node": ">=24.0.0"
20
20
  },
21
21
  "scripts": {
22
22
  "gateway:deploy": "node scripts/deploy-gateway.js",
@@ -403,6 +403,17 @@ export class MultiplexedSocketductConnection extends EventEmitter {
403
403
  return socket
404
404
  }
405
405
 
406
+ /**
407
+ * Exact-gateway members are bound to one configured gateway for one configured
408
+ * target, so there is no per-target rotation to scope a failure to: an
409
+ * unavailable gateway takes this member out of service entirely and the set's
410
+ * member-level fallback owns it.
411
+ * @returns {boolean} Always false for exact-gateway members.
412
+ */
413
+ isTargetUnavailable() {
414
+ return false
415
+ }
416
+
406
417
  /** @returns {{physicalState: string, connectionGeneration: number, virtualStreams: number, streamStates: Record<string, number>, queuedBytes: number, dataQueuedBytes: number, controlQueuedBytes: number, spoolBytes: number, spoolCleanupFailures: number, physicalConnects: number, reconnectAttempts: number, reconnectSuccesses: number, resumeFailures: number}} Privacy-safe status. */
407
418
  status() {
408
419
  /** @type {Record<string, number>} */
@@ -59,6 +59,7 @@ const GATEWAY_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{1,63}$/
59
59
  * @property {(options: Record<string, unknown>, callback?: (error: Error | null, socket: import('./virtual-socket.js').VirtualSocket) => void) => import('./virtual-socket.js').VirtualSocket} registerRecoveredConnection - Cold-register durable recovery.
60
60
  * @property {(identifier: string) => {identifier: string, target: {host: string, port: number}, sessionName: string, manualReceiveAck: boolean} | undefined} [_inspectRecoveredConnection] - Read-only stable-identifier recovery lookup.
61
61
  * @property {() => MemberConnectionStatus} status - Privacy-safe status.
62
+ * @property {(target: {host: string, port: number}) => boolean} isTargetUnavailable - Whether this member last reported that exact target unserviceable.
62
63
  * @property {() => Promise<void>} close - Close the member.
63
64
  * @property {() => Promise<void>} detach - Preserve durable streams for process-replacement recovery.
64
65
  * @property {() => Promise<void>} drain - Let live streams finish before releasing the member.
@@ -82,6 +83,19 @@ const GATEWAY_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{1,63}$/
82
83
  * @typedef {import('node:tls').TLSSocket & {readonly gatewayId: string | undefined, readonly routeClass: string | undefined}} GatewayTlsSocket
83
84
  */
84
85
 
86
+ /**
87
+ * Resolves the logical target from either caller option shape.
88
+ * @param {{host?: string, port?: number, target?: {host: string, port: number} | null} | undefined} options - Caller open options.
89
+ * @returns {{host: string, port: number} | undefined} Exact target, when the caller named one.
90
+ */
91
+ function resolveOpenTarget(options) {
92
+ if (options === undefined) return undefined
93
+ const nested = options.target
94
+ if (nested !== undefined && nested !== null) return {host: nested.host, port: nested.port}
95
+ if (typeof options.host !== "string" || typeof options.port !== "number") return undefined
96
+ return {host: options.host, port: options.port}
97
+ }
98
+
85
99
  /** No configured gateway is currently safe for a new virtual stream. */
86
100
  export class SocketductTransportSetNotReadyError extends Error {
87
101
  /** @param {string} [message] - Privacy-safe detail. */
@@ -330,6 +344,19 @@ export class MultiplexedSocketductTransportSet extends EventEmitter {
330
344
  return this.#startPromise
331
345
  }
332
346
 
347
+ /**
348
+ * Whether this member most recently reported exactly this target unserviceable.
349
+ * A target-scoped reset only removes the member from rotation for that target,
350
+ * so an unreachable machine cannot cost the set its other machines.
351
+ * @param {TransportMember} member - Candidate member.
352
+ * @param {{host: string, port: number} | undefined} target - Target the caller wants.
353
+ * @returns {boolean} True when the member is marked down for this exact target.
354
+ */
355
+ #memberMarkedForTarget(member, target) {
356
+ if (target === undefined) return false
357
+ return member.connection.isTargetUnavailable(target)
358
+ }
359
+
333
360
  /**
334
361
  * Assigns one new virtual socket to the next ready member.
335
362
  * @param {import('./multiplexed-connection.js').VirtualConnectionOptions} options - Target/socket options.
@@ -341,7 +368,7 @@ export class MultiplexedSocketductTransportSet extends EventEmitter {
341
368
  if (this.#closed) throw closedError()
342
369
  const socketOptions = normalizeVirtualSocketOptions(options)
343
370
  if (this.#startupError !== undefined) return this.#failedSocket(socketOptions, this.#startupError, callback)
344
- const selection = this.#pendingOpens.length === 0 && this.#startupResolved ? this.#selectReadyMember() : undefined
371
+ const selection = this.#pendingOpens.length === 0 && this.#startupResolved ? this.#selectReadyMember(options) : undefined
345
372
  if (selection === undefined) return this.#deferConnection(options, socketOptions, callback)
346
373
  try {
347
374
  /** @type {((error: Error | null, socket: import('./virtual-socket.js').VirtualSocket) => void) | undefined} */
@@ -494,14 +521,13 @@ export class MultiplexedSocketductTransportSet extends EventEmitter {
494
521
  return this
495
522
  }
496
523
 
497
- /** @returns {{state: string, configuredMembers: number, connectingMembers: number, readyMembers: number, degradedMembers: number, closedMembers: number, minimumReadyMembers: number, pendingOpens: number, maxPendingOpens: number, virtualOpens: number, physicalConnects: number, reconnectAttempts: number, budgets: {dataBytes: number, spoolBytes: number, queuedBytes: number, maxDataBytes: number, maxSpoolBytes: number, maxQueuedBytes: number}, members: Array<{gatewayId?: string, routeClass?: string, state: string, gatewayUnavailable: boolean, assignments: number, physicalConnects: number, reconnectAttempts: number, reconnectSuccesses: number, virtualStreams: number, queuedBytes: number, spoolBytes: number, spoolCleanupFailures: number, terminalErrorCode: string | null}>}} Privacy-safe aggregate and per-member status. */
524
+ /** @returns {{state: string, configuredMembers: number, connectingMembers: number, readyMembers: number, degradedMembers: number, closedMembers: number, minimumReadyMembers: number, pendingOpens: number, maxPendingOpens: number, virtualOpens: number, physicalConnects: number, reconnectAttempts: number, budgets: {dataBytes: number, spoolBytes: number, queuedBytes: number, maxDataBytes: number, maxSpoolBytes: number, maxQueuedBytes: number}, members: Array<{gatewayId?: string, routeClass?: string, state: string, assignments: number, physicalConnects: number, reconnectAttempts: number, reconnectSuccesses: number, virtualStreams: number, queuedBytes: number, spoolBytes: number, spoolCleanupFailures: number, terminalErrorCode: string | null}>}} Privacy-safe aggregate and per-member status. */
498
525
  status() {
499
526
  const members = this.#members.map((member) => {
500
527
  const status = member.connection.status()
501
528
  return {
502
529
  ...memberAllocation(member),
503
530
  state: status.physicalState,
504
- gatewayUnavailable: status.gatewayUnavailable === true,
505
531
  assignments: member.assignments,
506
532
  physicalConnects: status.physicalConnects,
507
533
  reconnectAttempts: status.reconnectAttempts,
@@ -578,25 +604,35 @@ export class MultiplexedSocketductTransportSet extends EventEmitter {
578
604
  }
579
605
 
580
606
  /**
581
- * Selects the next ready member whose route class the hub has registered up.
582
- * A member the hub registered down is never selected: nothing is sent to a
583
- * route class without a reachable gateway. When every member is registered
584
- * down the open stays pending here until a member reports availability again
585
- * (the member keeps probing the hub, and its state change re-drains this set).
607
+ * Selects the next ready member, preferring members whose gateway the hub has
608
+ * not recently reported unavailable. When every ready member carries a
609
+ * gateway-unavailable mark, any ready member may still be selected so a stale
610
+ * mark can never wedge the set.
611
+ * @param {{host?: string, port?: number, target?: {host: string, port: number} | null} | undefined} options - Caller open options, used for the exact target.
586
612
  * @returns {{member: TransportMember, previousCursor: number} | undefined}
587
613
  */
588
- #selectReadyMember() {
614
+ #selectReadyMember(options) {
589
615
  if (this.#closed) throw closedError()
590
616
  const previousCursor = this.#cursor
617
+ const target = resolveOpenTarget(options)
618
+ /** @type {{member: TransportMember, index: number} | undefined} */
619
+ let fallback
591
620
  for (let offset = 0; offset < this.#members.length; offset += 1) {
592
621
  const index = (this.#cursor + offset) % this.#members.length
593
622
  const member = /** @type {TransportMember} */ (this.#members[index])
594
623
  const status = member.connection.status()
595
624
  if (status.physicalState !== "ready") continue
596
- if (status.gatewayUnavailable === true) continue
625
+ if (status.gatewayUnavailable === true || this.#memberMarkedForTarget(member, target)) {
626
+ fallback ??= {member, index}
627
+ continue
628
+ }
597
629
  this.#cursor = (index + 1) % this.#members.length
598
630
  return {member, previousCursor}
599
631
  }
632
+ if (fallback !== undefined) {
633
+ this.#cursor = (fallback.index + 1) % this.#members.length
634
+ return {member: fallback.member, previousCursor}
635
+ }
600
636
  return undefined
601
637
  }
602
638
 
@@ -661,7 +697,8 @@ export class MultiplexedSocketductTransportSet extends EventEmitter {
661
697
  #drainPendingOpens() {
662
698
  if (!this.#startupResolved || this.#closed || this.#startupError !== undefined) return
663
699
  while (this.#pendingOpens.length > 0) {
664
- const selection = this.#selectReadyMember()
700
+ const nextPending = this.#pendingOpens[0]
701
+ const selection = nextPending === undefined ? undefined : this.#selectReadyMember(nextPending.options)
665
702
  if (selection === undefined) return
666
703
  const pending = this.#pendingOpens.shift()
667
704
  if (pending === undefined) return