Initial Commit

This commit is contained in:
2026-05-27 23:29:53 +01:00
commit fbc70f96e6
10000 changed files with 1102152 additions and 0 deletions

View File

@@ -0,0 +1,109 @@
# OpenSpec Change: network-plugin-transport-manager
- **Change ID**: network-plugin-transport-manager
- **Package**: `@suaveplan/network-plugin-transport-manager` (new)
- **Status**: PROPOSED
- **Type**: new-package
- **Date**: 2026-04-29
## Why
A resilient network cannot rely on a single transport. WebRTC may fail behind symmetric NAT. WebSockets may drop on mobile network transitions. HTTP fallback may be needed for corporate firewalls. The current architecture has `network-plugin-webrtc` and mentions `network-plugin-websocket` but provides no mechanism to use them simultaneously, fail over between them intelligently, or select transports based on message priority and peer capabilities. This plugin provides **multi-transport orchestration**: simultaneous active transports, round-robin load distribution, priority-based routing, capability negotiation, and automatic degradation/recovery.
## What changes
- **ADDED**: `TransportManagerPlugin` class implementing `NetworkPlugin`.
- **ADDED**: `TransportPool` — maintains all registered transports with health scores. Supports simultaneous active connections across multiple transports to the same peer.
- **ADDED**: `TransportSelector` — selects the best transport for a message based on: message priority, transport capability, peer capability, current latency, and health score.
- **ADDED**: `CapabilityNegotiator` — exchanges capability bitmaps during peer handshake: `webrtc`, `websocket`, `http`, `bluetooth`, `local-network`. Peers agree on common transports.
- **ADDED**: `PriorityRouter` — routes messages to transports based on 5 priority tiers:
- `CRITICAL` — host election, failover, heartbeat (most reliable transport, redundant send)
- `HIGH` — session transitions, state snapshots (fastest available)
- `NORMAL` — game state, entity replication (default)
- `LOW` — telemetry, metrics, non-urgent sync (batch, tolerate delay)
- `BULK` — file chunks, large transfers (use highest-bandwidth transport, backpressure-aware)
- **ADDED**: `RoundRobinBalancer` — distributes BULK and NORMAL traffic across all healthy transports to prevent saturating any single path.
- **ADDED**: `TransportHealthMonitor` — tracks RTT, loss rate, bandwidth, and connection stability per transport. Auto-pauses degraded transports, auto-resumes on recovery.
- **ADDED**: `BatteryAwareScheduler` — when running on battery-powered devices, reduces transport keepalive frequency, defers non-critical transport probes, and prefers lower-power transports (WebSocket over WebRTC when quality is equivalent).
- **ADDED**: `BandwidthConservator` — monitors aggregate bandwidth usage across all transports. When conservation mode is active, coalesces small messages, increases batching intervals, and pauses redundant CRITICAL sends.
- **ADDED**: `RedundantSend` — CRITICAL messages are sent over 2+ transports simultaneously; first arrival wins, duplicates are detected and dropped.
- **ADDED**: `NETWORK_TM_CODES` — frozen error registry.
## Transport priority matrix
| Priority | WebRTC | WebSocket | HTTP | Behavior |
|---|---|---|---|---|
| CRITICAL | ✅ + redundant WS | ✅ + redundant WebRTC | ❌ | Send on 2+ transports |
| HIGH | ✅ preferred | ✅ fallback | ❌ | Fastest healthy |
| NORMAL | ✅ preferred | ✅ fallback | ❌ | Round-robin across healthy |
| LOW | ✅ | ✅ | ✅ | Batch, any available |
| BULK | ✅ preferred (bandwidth) | ✅ fallback | ✅ fallback | Backpressure-aware, round-robin |
## Capability bitmap
```typescript
type TransportCapability =
| 'webrtc-datachannel'
| 'websocket'
| 'http-fetch'
| 'http-sse'
| 'bluetooth-le'
| 'local-network-mdns'
| 'relay-via-host';
```
Peers exchange capabilities during the `peer:connected` handshake. The transport manager only uses transports both peers support.
## Out of scope
- Transport-specific implementations → `network-plugin-webrtc`, `network-plugin-websocket`, etc.
- Physical-layer protocols (Bluetooth, mDNS) → future `network-plugin-bluetooth`, `network-plugin-mdns`.
- Bandwidth estimation per transport → `network-plugin-quality` (pre-existing enterprise plan).
## Source mapping
This is a **new design** — suaveplan has no equivalent multi-transport orchestration layer.
### Requirements with no source line
| Requirement | Justification |
|---|---|
| Multi-transport simultaneous operation | Required for resilience — single transport failure must not partition the mesh |
| Priority-based routing | Critical control messages must not be delayed behind bulk file transfers |
| Redundant send for CRITICAL | Host election messages must arrive even if one transport drops |
| Capability negotiation | Browser peers may not support WebRTC; Node.js peers may not support Bluetooth |
| Round-robin load balancing | Prevents saturating any single transport path |
| Transport health monitoring | Automatic pause/resume based on observed quality |
## Verification approach
- `src/pool/pool.spec-conformance.test.ts` — pins registration, health tracking, removal.
- `src/selector/selector.spec-conformance.test.ts` — pins priority routing, capability filtering.
- `src/negotiator/negotiator.spec-conformance.test.ts` — pins capability exchange, common subset.
- `src/priority/priority.spec-conformance.test.ts` — pins 5-tier routing, CRITICAL redundant send.
- `src/balancer/balancer.spec-conformance.test.ts` — pins round-robin, load distribution.
- `src/health/health.spec-conformance.test.ts` — pins degradation detection, auto-pause/resume.
- `tests/dep-graph.test.ts` — pins no direct import of transport implementations.
## Enhancement: Pre-Emptive Transport Switching
**Source**: `docs/old-network-planning/PHASE_2_5.md` §Pre-emptive switching, `ADAPT_3.md`
The transport manager currently switches transports after degradation threshold. Pre-emptive switching predicts failure and switches before complete disconnect:
- `QualityTrendAnalyzer` — tracks latency trend (EMA slope), packet loss trend, bandwidth degradation.
- `PreemptiveSelector` — initiates switch when trend indicates impending failure, even if current transport is still "healthy".
- Smooth handoff: establishes new transport before tearing down old, with overlap window.
## Enhancement: Session Persistence During Disconnection
**Source**: `docs/old-network-planning/PHASE_2_5.md` §Connection Recovery, `SERVER_FAILOVER.md`
- `SessionPersistenceBuffer` — buffers connection state during temporary drops.
- `ConnectionRecoveryManager` — exponential backoff reconnection with jitter.
- `SessionContinuityGuard` — maintains session context across reconnections. Replays buffered messages in sequence on recovery.
- Prioritized recovery: CRITICAL connections recover first.
## Migration impact
None — additive only.

View File

@@ -0,0 +1,99 @@
# Tasks — network-plugin-transport-manager
> Blocked on: `network-core`.
## 1. Scaffold
- [x] 1.1 `packages/network/network-plugin-transport-manager/` with `package.json`, `tsconfig.json`, `vitest.config.ts`, `README.md`.
- [x] 1.2 Workspace deps: `@suaveplan/network`, `@suaveplan/error`, `@suaveplan/types`, `@suaveplan/events`, `@suaveplan/timing`, `@suaveplan/rate-limiter`, `@opentelemetry/api`, `zod`.
- [x] 1.3 `sideEffects: false`.
## 2. Types
- [x] 2.1 `src/types/transport.types.ts` — `TransportEntry`, `TransportHealth`, `TransportCapability`.
- [x] 2.2 `src/types/priority.types.ts` — `MessagePriority`, `PriorityConfig`.
- [x] 2.3 `src/types/selector.types.ts` — `SelectorConfig`, `SelectionResult`.
- [x] 2.4 `src/error-codes.ts` — `defineCodes("NET_TM", [...])`.
## 3. Transport pool
- [x] 3.1 `src/pool/transport-pool.ts` — `TransportPool`.
- [x] 3.2 `register(transport)`, `unregister(transportId)`, `getHealth(transportId)`.
- [x] 3.3 Health score: 0–100 based on RTT, loss rate, stability.
## 4. Capability negotiator
- [x] 4.1 `src/negotiator/capability-negotiator.ts` — `CapabilityNegotiator`.
- [x] 4.2 Exchanges capability bitmap during `peer:connected`.
- [x] 4.3 Computes intersection of local and remote capabilities.
## 5. Transport selector
- [x] 5.1 `src/selector/transport-selector.ts` — `TransportSelector`.
- [x] 5.2 Selects transport based on priority + capability + health.
- [x] 5.3 CRITICAL: selects 2+ transports for redundant send.
## 6. Priority router
- [x] 6.1 `src/priority/priority-router.ts` — `PriorityRouter`.
- [x] 6.2 5 tiers: CRITICAL, HIGH, NORMAL, LOW, BULK.
- [x] 6.3 CRITICAL messages sent redundantly on 2+ transports.
## 7. Round-robin balancer
- [x] 7.1 `src/balancer/round-robin-balancer.ts` — `RoundRobinBalancer`.
- [x] 7.2 Distributes NORMAL and BULK across healthy transports.
## 8. Health monitor
- [x] 8.1 `src/health/transport-health-monitor.ts` — `TransportHealthMonitor`.
- [x] 8.2 Auto-pauses transport when health < threshold.
- [x] 8.3 Auto-resumes when health recovers.
## 9. Plugin wrapper
- [x] 9.1 `src/plugin/transport-manager-plugin.ts` — `TransportManagerPlugin` implements `NetworkPlugin`.
## 10. Spec
- [x] 10.1 Update `openspec/specs/network/spec.md` with `NET-TM` requirements.
## 11. Conformance tests
- [x] 11.1 `src/pool/pool.spec-conformance.test.ts` — registration, health, removal.
- [x] 11.2 `src/selector/selector.spec-conformance.test.ts` — priority, capability, health.
- [x] 11.3 `src/negotiator/negotiator.spec-conformance.test.ts` — exchange, intersection.
- [x] 11.4 `src/priority/priority.spec-conformance.test.ts` — 5 tiers, redundant CRITICAL.
- [x] 11.5 `src/balancer/balancer.spec-conformance.test.ts` — round-robin, distribution.
- [x] 11.6 `src/health/health.spec-conformance.test.ts` — degradation, pause, resume.
- [x] 11.7 `src/error-codes.spec-conformance.test.ts` — frozen registry.
## 12. Pre-emptive transport switching
- [x] 12.1 `src/analyzer/quality-trend-analyzer.ts` — `QualityTrendAnalyzer`, EMA slope for latency/loss/bandwidth.
- [x] 12.2 `src/selector/preemptive-selector.ts` — `PreemptiveSelector`, switches on trend before threshold.
- [x] 12.3 Smooth handoff: establish new before teardown, overlap window.
## 13. Session persistence
- [x] 13.1 `src/persistence/session-persistence-buffer.ts` — `SessionPersistenceBuffer`, buffers state during drops.
- [x] 13.2 `src/recovery/connection-recovery-manager.ts` — `ConnectionRecoveryManager`, exponential backoff with jitter.
- [x] 13.3 `src/recovery/session-continuity-guard.ts` — `SessionContinuityGuard`, replays buffered messages on recovery.
- [x] 13.4 Prioritized recovery: CRITICAL connections recover first.
## 14. Spec
- [x] 14.1 Update `openspec/specs/network/spec.md` with `NET-46`, `NET-60`.
## 15. Conformance tests
- [x] 15.1 `src/analyzer/analyzer.spec-conformance.test.ts` — trend detection, slope calculation.
- [x] 15.2 `src/selector/preemptive.spec-conformance.test.ts` — pre-emptive switch, smooth handoff.
- [x] 15.3 `src/persistence/persistence.spec-conformance.test.ts` — buffering, replay, sequence.
- [x] 15.4 `src/recovery/recovery.spec-conformance.test.ts` — backoff, jitter, continuity, priority.
## 16. Verify
- [x] 16.1 `bunx turbo lint typecheck test --filter=@suaveplan/network-plugin-transport-manager` green.
- [x] 16.2 `bunx turbo test:coverage --filter=@suaveplan/network-plugin-transport-manager` 100/100/100/100.
- [x] 16.3 `bun scripts/openspec-conformance.ts @suaveplan/network-plugin-transport-manager` PASS.