update docs and housekeeping
This commit is contained in:
File diff suppressed because it is too large
Load Diff
603
docs/WASM_IMPLEMENTATION_TASKS.md
Normal file
603
docs/WASM_IMPLEMENTATION_TASKS.md
Normal file
@@ -0,0 +1,603 @@
|
||||
# WASM/Browser + Native WebRTC — Detailed Task List
|
||||
|
||||
**80 tasks across 6 phases, ~234 hours estimated**
|
||||
|
||||
---
|
||||
|
||||
## Phase 0: Preparation and Audit (4 tasks, ~7h)
|
||||
|
||||
### T0.1 — Create `src/platform/` directory (1h)
|
||||
- Create empty `src/platform/` directory for platform-specific code
|
||||
- No build changes yet
|
||||
|
||||
### T0.2 — Audit every Socket access point (2h)
|
||||
- Read-only audit of all files importing `core.Socket`
|
||||
- Produce reference table: every call to send, sendTo, receive, receiveFrom, bind, listen, accept, connect, close, poll, setNonBlocking with file:line
|
||||
- **Output**: Reference document for Transport interface design
|
||||
- Files: `src/core/socket.zig`, `src/network/network_manager.zig`, `src/network/secure_connection.zig`, `src/network/upnp.zig`, `src/network/nat_pmp.zig`, `src/network/discovery.zig`, `src/network/nat.zig`, `src/network/turn_integration.zig`, `src/mwp/hole_punch.zig`, `src/p2p/connection.zig`, `src/p2p/messaging.zig`
|
||||
|
||||
### T0.3 — Audit Mutex usage and threading model (2h)
|
||||
- Classify each of the 835 Mutex occurrences into:
|
||||
- (a) Protects truly concurrent multi-thread access (e.g., worker thread + update loop)
|
||||
- (b) Single-threaded access only (artifact of lock ordering discipline)
|
||||
- (c) Within spawned worker threads (handler.zig, verification_pool.zig)
|
||||
- Identify which 4 files spawn threads: `nat.zig`, `handler.zig`, `request_tracker.zig`, `verification_pool.zig`
|
||||
|
||||
### T0.4 — Audit random and time usage (1.5h)
|
||||
- Document all `std.crypto.random.bytes()` sites (18 files, 30+ calls)
|
||||
- Document all `std.time.milliTimestamp()`, `timestamp()`, `nanoTimestamp()` sites (50+ files)
|
||||
- Identify hot-path vs initialization-only usage
|
||||
- Check if Zig's std.crypto/std.time has WASM support via WASI
|
||||
|
||||
---
|
||||
|
||||
## Phase 1: Transport Abstraction (16 tasks, ~48h)
|
||||
|
||||
### T1.1 — Define Transport interface (3h)
|
||||
- **Create**: `src/core/transport.zig`
|
||||
- Define `Transport` struct with vtable: `send`, `receive`, `close`, `canSend`, `canReceive`, `getRemoteId`, `getState`
|
||||
- Define `TransportError` error set
|
||||
- Include datagram methods: `sendTo(data, address)`, `receiveFrom(buffer) -> {size, address}`
|
||||
- Unit test with mock vtable dispatch
|
||||
- **Decision**: Single interface with mode flag (stream + datagram), not two separate interfaces. Unsupported ops return `OperationNotSupported`.
|
||||
- **Depends on**: T0.1, T0.2
|
||||
|
||||
### T1.2 — Define TransportFactory interface (2h)
|
||||
- **Modify**: `src/core/transport.zig`
|
||||
- Add `TransportFactory` with vtable: `connect(address, callback)`, `listen(address, callback)`, `stopListening()`, `poll(timeout_ms)`
|
||||
- Factory creates Transport instances
|
||||
- **Depends on**: T1.1
|
||||
|
||||
### T1.3 — Implement PosixStreamTransport (4h)
|
||||
- **Create**: `src/platform/posix_transport.zig`
|
||||
- Wraps existing `Socket` for TCP (not replacing Socket, wrapping it)
|
||||
- Implements Transport vtable: send → socket.send, receive → socket.receive, etc.
|
||||
- `canSend`/`canReceive` use `posix.poll()` with 0ms timeout
|
||||
- Unit test: create, send data through loopback, receive
|
||||
- **Depends on**: T1.1, T1.2
|
||||
|
||||
### T1.4 — Implement PosixDatagramTransport (3h)
|
||||
- **Modify**: `src/platform/posix_transport.zig`
|
||||
- Add datagram variant: `sendTo` → socket.sendTo, `receiveFrom` → socket.receiveFrom
|
||||
- Critical for DHT and discovery (UDP)
|
||||
- Unit test: two UDP sockets exchanging packets
|
||||
- **Depends on**: T1.3
|
||||
|
||||
### T1.5 — Implement MockTransport (2h)
|
||||
- **Create**: `src/platform/mock_transport.zig`
|
||||
- In-memory transport with configurable delays, errors, queued data
|
||||
- Mirrors existing MockSocket pattern in socket.zig (line 1025+)
|
||||
- Both stream and datagram modes
|
||||
- **Depends on**: T1.1
|
||||
|
||||
### T1.6 — Export Transport types from core module (1h)
|
||||
- **Modify**: `src/core.zig`
|
||||
- Add `pub const transport = @import("core/transport.zig")`
|
||||
- Re-export: Transport, TransportFactory, TransportError, TransportState
|
||||
- **Depends on**: T1.1
|
||||
|
||||
### T1.7 — Add transport module to build.zig (1h)
|
||||
- **Modify**: `build.zig`
|
||||
- Add `src/platform/` files to appropriate module
|
||||
- Add `const is_wasm = target.cpu_arch == .wasm32;` for conditional compilation
|
||||
- Verify `zig build` succeeds and runs transport unit tests
|
||||
- **Depends on**: T1.3, T1.4, T1.5, T1.6
|
||||
|
||||
### T1.8 — Refactor PeerConnection: `*Socket` → `Transport` (4h) ⚠️ HIGH RISK
|
||||
- **Modify**: `src/network/network_manager.zig` (PeerConnection struct, ~line 136)
|
||||
- Change `PeerConnection.socket: *Socket` to `PeerConnection.transport: Transport`
|
||||
- Update `init()`, `initSecure()`, all methods accessing `self.socket`
|
||||
- Add backward-compatible factory: `PeerConnection.initFromSocket()` wraps Socket in PosixStreamTransport
|
||||
- Must preserve atomic send semantics and PendingSend/EncryptedQueueEntry patterns
|
||||
- **ALL existing tests must pass unchanged**
|
||||
- **Depends on**: T1.3, T1.7
|
||||
- **Risk**: Most invasive change — touches sendToPeerAtomicImpl, drainPendingSendsImpl, processReceive, processSendQueue
|
||||
|
||||
### T1.9 — Refactor SecureConnection to use Transport (4h)
|
||||
- **Modify**: `src/network/secure_connection.zig` (447 lines)
|
||||
- Change `SecureConnection.socket: *Socket` → accept Transport
|
||||
- Update `sendRaw()` (line 379) and `receiveRaw()` (line 401) to use transport.send/receive
|
||||
- Blocking retry loops with Thread.sleep remain for now (Phase 2 fixes these)
|
||||
- Update sendEncrypted/receiveDecrypted
|
||||
- **Depends on**: T1.8
|
||||
|
||||
### T1.10 — Refactor NetworkManager receive path (3h)
|
||||
- **Modify**: `src/network/network_manager.zig` — `processReceive()` (~line 971)
|
||||
- Read from PeerConnection.transport instead of Socket directly
|
||||
- Pattern: iterate peer_connections, check transport.canReceive(), call transport.receive()
|
||||
- **Depends on**: T1.8
|
||||
|
||||
### T1.11 — Refactor NetworkManager send path (3h)
|
||||
- **Modify**: `src/network/network_manager.zig` — `sendMessage()`, `processSendQueue()`
|
||||
- **Modify**: `src/p2p/connection.zig` — `sendToPeerAtomicImpl()`, `sendSegmentsToPeerAtomicImpl()`, `drainPendingSendsImpl()`
|
||||
- Replace peer_conn.socket.send() with peer_conn.transport.send()
|
||||
- WouldBlock handling unchanged — just goes through Transport
|
||||
- **Depends on**: T1.8, T1.10
|
||||
|
||||
### T1.12 — Refactor connection establishment to use TransportFactory (4h)
|
||||
- **Modify**: `src/p2p/connection.zig` — `connectToPeerImpl()`, `attemptConnectionInternalImpl()`, `acceptConnectionsImpl()`
|
||||
- New flow: TransportFactory.connect() → Transport → PeerConnection
|
||||
- For accept: TransportFactory.listen() callback yields new Transports
|
||||
- PosixTransportFactory wraps existing Socket creation
|
||||
- **Depends on**: T1.2, T1.8, T1.11
|
||||
|
||||
### T1.13 — Refactor discovery module to use Transport (3h)
|
||||
- **Modify**: `src/network/discovery.zig`
|
||||
- Uses Socket/MockSocket directly (line 12). Change to DatagramTransport.
|
||||
- Broadcast/multicast → DatagramTransport.sendTo()
|
||||
- Receive → DatagramTransport.receiveFrom()
|
||||
- **Depends on**: T1.4
|
||||
|
||||
### T1.14 — Refactor NAT module to use Transport (3h)
|
||||
- **Modify**: `src/network/nat.zig`
|
||||
- Already generic over Socket/MockSocket (lines 36-37). Change to DatagramTransport.
|
||||
- STUN message exchange through Transport
|
||||
- Hole punch UDP send/receive through Transport
|
||||
- Thread.spawn for hole punching remains for now (Phase 2)
|
||||
- **Depends on**: T1.4
|
||||
|
||||
### T1.15 — Refactor DHT coordinator to use Transport (3h)
|
||||
- **Modify**: `src/network/dht.zig`, `src/p2p/dht.zig`
|
||||
- DHT messages flow through P2P send path (already through NetworkManager)
|
||||
- Ensure DHT-specific send/receive routes through Transport
|
||||
- Remove any direct Socket references
|
||||
- **Depends on**: T1.11
|
||||
|
||||
### T1.16 — Phase 1 full regression test (4h)
|
||||
- Run `zig build test`, `zig build test-integration`
|
||||
- Fix any failures from Transport refactoring
|
||||
- Run performance benchmarks — no regression
|
||||
- Verify TestP2PPair still works (real TCP on localhost)
|
||||
- **Depends on**: T1.8 through T1.15
|
||||
- **Gate**: MUST pass before Phase 2
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Event-Driven I/O (13 tasks, ~37h)
|
||||
|
||||
### T2.1 — Implement EventQueue (3h)
|
||||
- **Create**: `src/platform/event_queue.zig`
|
||||
- Events: transport_readable, transport_writable, transport_state, timer, file_io_complete
|
||||
- Methods: push(), processAll(), processN(), registerHandler()
|
||||
- Optional for native (poll-based loop works). Required for WASM.
|
||||
- **Depends on**: T1.7
|
||||
|
||||
### T2.2 — Implement platform-aware Mutex (2h)
|
||||
- **Create**: `src/platform/sync.zig`
|
||||
- `pub const Mutex = if (builtin.target.isWasm()) WasmMutex else std.Thread.Mutex;`
|
||||
- WasmMutex: no-op with debug recursive lock detection
|
||||
- **Depends on**: T0.3
|
||||
|
||||
### T2.3 — Implement platform-aware time abstraction (2h)
|
||||
- **Create**: `src/platform/time.zig`
|
||||
- `milliTimestamp()`: std.time.milliTimestamp() on native, js_timestamp_ms() on WASM
|
||||
- Same for timestamp(), nanoTimestamp()
|
||||
- **Depends on**: T0.4
|
||||
|
||||
### T2.4 — Implement platform-aware random abstraction (2h)
|
||||
- **Create**: `src/platform/random.zig`
|
||||
- `bytes(buf)`: std.crypto.random.bytes() on native, js_random_bytes() on WASM (crypto.getRandomValues)
|
||||
- **Depends on**: T0.4
|
||||
|
||||
### T2.5 — Non-blocking Noise handshake (4h) ⚠️ HIGH RISK
|
||||
- **Modify**: `src/network/secure_connection.zig` — sendRaw() (line 379), receiveRaw() (line 401)
|
||||
- Replace blocking retry loops with state machine: `HandshakeState { .sending_msg1, .awaiting_msg2, .sending_msg3, .complete }`
|
||||
- Each call to `advanceHandshake()` does non-blocking I/O, returns `.progress` or `.would_block`
|
||||
- Caller (connection.zig) calls from update loop
|
||||
- Must buffer partial sends/receives
|
||||
- **Depends on**: T1.9
|
||||
- **Risk**: Noise XX expects complete messages from writeMessage/readMessage
|
||||
|
||||
### T2.6 — Non-blocking connection establishment (4h)
|
||||
- **Modify**: `src/p2p/connection.zig` — attemptConnectionInternalImpl()
|
||||
- Multi-step state: Connecting → HandshakeMsg1 → HandshakeMsg2 → HandshakeMsg3 → Connected
|
||||
- Pending connections stored in list, advanced each update cycle
|
||||
- **Depends on**: T2.5
|
||||
|
||||
### T2.7 — Remove Thread.sleep from network_manager, dht, discovery (3h)
|
||||
- **Modify**: `src/network/network_manager.zig`, `src/network/dht.zig`, `src/network/discovery.zig`
|
||||
- Replace sleep with timestamp-based retry (store retry-at, check in update loop)
|
||||
- **Depends on**: T2.3
|
||||
|
||||
### T2.8 — Remove Thread.sleep from MWP modules (2h)
|
||||
- **Modify**: `src/mwp_integration.zig`, `src/mwp/meeting_point.zig`, `src/mwp/hole_punch.zig`
|
||||
- Hole punch resend (500ms) → timestamp check in update loop instead of sleep
|
||||
- **Depends on**: T2.3
|
||||
|
||||
### T2.9 — Remove Thread.sleep from file transfer (2h)
|
||||
- **Modify**: `src/files/manager.zig`, `src/files/piece_pipeline.zig`, `src/files/verification_pool.zig`
|
||||
- Replace blocking sleeps with cooperative patterns
|
||||
- Thread spawning handled separately in T2.11
|
||||
- **Depends on**: T2.3
|
||||
|
||||
### T2.10 — Replace Thread.spawn in protocol handler with TaskQueue (4h)
|
||||
- **Create**: `src/platform/task_queue.zig`
|
||||
- **Modify**: `src/protocol/handler.zig`
|
||||
- Implement cooperative TaskQueue (design doc Section 9.3)
|
||||
- Comptime switch: `if (builtin.target.isWasm()) task_queue.schedule(...) else Thread.spawn(...)`
|
||||
- **Depends on**: T2.2
|
||||
|
||||
### T2.11 — Replace Thread.spawn in verification_pool (3h)
|
||||
- **Modify**: `src/files/verification_pool.zig`
|
||||
- WASM: chunked single-threaded SHA-256 verification (process N bytes per update, yield)
|
||||
- Native: keep existing thread pool
|
||||
- Comptime switch
|
||||
- **Depends on**: T2.10
|
||||
|
||||
### T2.12 — Replace Thread.spawn in NAT and request_tracker (2h)
|
||||
- **Modify**: `src/network/nat.zig`, `src/protocol/request_tracker.zig`
|
||||
- Hole punching → update-loop-driven (check timer, send packet, return)
|
||||
- Request tracker cleanup → update-loop-driven
|
||||
- **Depends on**: T2.10
|
||||
|
||||
### T2.13 — Phase 2 full regression test (3h)
|
||||
- All tests pass
|
||||
- Verify: no Thread.sleep or Thread.spawn in WASM code paths (grep)
|
||||
- **Depends on**: T2.5 through T2.12
|
||||
- **Gate**: MUST pass before Phase 3
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: WASM WebRTC Transport — Browser Side (8 tasks, ~24h)
|
||||
|
||||
### T3.1 — Create WASM entry point and exports (3h)
|
||||
- **Create**: `src/wasm/main.zig`, `src/wasm/exports.zig`
|
||||
- Exports: p2p_init, p2p_connect, p2p_send, wasm_tick, alloc, free, on_timer, on_data_available, on_channel_closed
|
||||
- `zig build -Dtarget=wasm32-freestanding` produces .wasm
|
||||
- **Depends on**: T2.2, T2.3, T2.4
|
||||
|
||||
### T3.2 — Implement WebRTCTransport for WASM (Zig side) (3h)
|
||||
- **Create**: `src/platform/webrtc_wasm_transport.zig`
|
||||
- Transport vtable backed by `extern "webrtc"` imports (js_send, js_recv, js_close, etc.)
|
||||
- Channel-ID based
|
||||
- **Depends on**: T1.1
|
||||
|
||||
### T3.3 — Create JS WebRTC glue layer (4h)
|
||||
- **Create**: `wasm/js/webrtc-transport.js`
|
||||
- WebRTCTransportManager class: RTCPeerConnection + RTCDataChannel management
|
||||
- Provides WASM imports (js_send, js_recv, etc.)
|
||||
- Handles connection setup, ICE, data channel lifecycle
|
||||
- **Depends on**: T3.2
|
||||
|
||||
### T3.4 — Implement signaling protocol (3h)
|
||||
- **Create**: `wasm/js/signaling.js`, `tools/signaling-server.js`
|
||||
- Simple WebSocket signaling (~50 lines Node.js)
|
||||
- Message types: register, offer, answer, ice-candidate
|
||||
- **Depends on**: T3.3
|
||||
|
||||
### T3.5 — Create main JS API (3h)
|
||||
- **Create**: `wasm/js/zig-p2p.js`
|
||||
- ZigP2P class: init(), connect(), send(), onMessage(), onPeerConnected()
|
||||
- WASM loading, memory management, event loop (requestAnimationFrame → wasm_tick)
|
||||
- **Depends on**: T3.1, T3.3, T3.4
|
||||
|
||||
### T3.6 — Build system WASM target (3h)
|
||||
- **Modify**: `build.zig`
|
||||
- Add `wasm` step: wasm32-freestanding target, export symbols, disable entry, copy JS files
|
||||
- `zig build wasm` produces `zig-out/wasm/zig-p2p.wasm` + JS files
|
||||
- Native build unaffected
|
||||
- **Depends on**: T3.1, T3.2
|
||||
|
||||
### T3.7 — Browser demo page (2h)
|
||||
- **Create**: `wasm/demo/index.html`, `wasm/demo/demo.js`
|
||||
- Load zig-p2p WASM, connect to signaling server, show peers, send messages
|
||||
- **Depends on**: T3.5, T3.6
|
||||
|
||||
### T3.8 — Browser-to-browser integration test (3h)
|
||||
- **Create**: `tests/browser/test_browser_p2p.js` (Playwright)
|
||||
- Two browser contexts: init P2P, connect, exchange encrypted messages
|
||||
- `npx playwright test`
|
||||
- **Depends on**: T3.7
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: File System and Threading Adaptation (7 tasks, ~17h)
|
||||
|
||||
### T4.1 — Define FileSystem interface (2h)
|
||||
- **Create**: `src/platform/filesystem_interface.zig`
|
||||
- Vtable: open, read, write, close, stat, delete
|
||||
- Replaces `use_mock_fs` compile-time flag with runtime dispatch
|
||||
- **Depends on**: T1.1
|
||||
|
||||
### T4.2 — Implement NativeFileSystem (2h)
|
||||
- **Create**: `src/platform/native_fs.zig`
|
||||
- Wraps std.fs.File operations
|
||||
- **Depends on**: T4.1
|
||||
|
||||
### T4.3 — Implement IndexedDB FileSystem (3h)
|
||||
- **Create**: `src/platform/indexeddb_fs.zig`, `wasm/js/indexeddb-fs.js`
|
||||
- Zig: vtable backed by extern "indexeddb" imports
|
||||
- JS: IndexedDBFileSystem class with blob storage
|
||||
- **Depends on**: T4.1
|
||||
|
||||
### T4.4 — Refactor files module to use FileSystem interface (4h)
|
||||
- **Modify**: `src/files/filesystem.zig`, `src/files/manager.zig`, `src/files/download.zig`, `src/files/upload.zig`
|
||||
- Replace use_mock_fs with runtime FileSystem
|
||||
- FileSharingManager receives FileSystem in config
|
||||
- **Depends on**: T4.2
|
||||
|
||||
### T4.5 — Refactor crypto key persistence (2h)
|
||||
- **Modify**: `src/protocol/crypto.zig`, `src/network/key_pinning.zig`
|
||||
- These use std.fs directly. Accept FileSystem in config.
|
||||
- WASM: keys go to IndexedDB. Native: keys go to disk.
|
||||
- **Depends on**: T4.1
|
||||
|
||||
### T4.6 — Create platform module aggregator (2h)
|
||||
- **Create**: `src/platform/native.zig`, `src/platform/wasm.zig`
|
||||
- Each exports platform-specific implementations
|
||||
- `pub const platform = if (builtin.target.isWasm()) @import("platform/wasm.zig") else @import("platform/native.zig");`
|
||||
- **Depends on**: T2.2, T4.2, T4.3
|
||||
|
||||
### T4.7 — Phase 4 regression test (2h)
|
||||
- All native tests pass
|
||||
- WASM builds compile
|
||||
- File transfer works with NativeFS and MockFS
|
||||
- **Depends on**: T4.1 through T4.6
|
||||
|
||||
---
|
||||
|
||||
## Phase 5: Native WebRTC via libdatachannel C Bindings (23 tasks, ~71h)
|
||||
|
||||
### T5.1 — Install libdatachannel and verify headers (2h)
|
||||
- System install: `brew install libdatachannel` (macOS) or build from source
|
||||
- Verify `rtc/rtc.h` accessible
|
||||
- Document version + install instructions in `docs/WEBRTC_BUILD.md`
|
||||
- Pin to specific version (e.g., 0.21.x)
|
||||
|
||||
### T5.2 — Create @cImport wrapper and type mappings (3h)
|
||||
- **Create**: `src/platform/webrtc_native.zig`
|
||||
- `const rtc = @cImport({ @cInclude("rtc/rtc.h"); });`
|
||||
- Zig type aliases for C types: RtcConfiguration, RtcDataChannelInit, RtcReliability
|
||||
- Map rtcState enum → Transport.State
|
||||
- Verify: rtc.rtcPreload() + rtc.rtcCleanup() callable from Zig
|
||||
- **Depends on**: T5.1
|
||||
|
||||
### T5.3 — Add `-Denable-webrtc` build option (2h)
|
||||
- **Modify**: `build.zig`
|
||||
- `b.option(bool, "enable-webrtc", "Enable native WebRTC transport via libdatachannel")`
|
||||
- When true: linkSystemLibrary("datachannel"), linkLibC(), add include path
|
||||
- When false: no WebRTC code compiled or linked
|
||||
- **Depends on**: T5.2
|
||||
|
||||
### T5.4 — Smoke test: lifecycle (1.5h)
|
||||
- **Create**: `tests/integration/test_webrtc_smoke.zig`
|
||||
- Call rtcPreload(), create PeerConnection, close, delete, rtcCleanup()
|
||||
- Verify no crashes, no leaks (TrackingAllocator)
|
||||
- **Depends on**: T5.3
|
||||
|
||||
### T5.5 — Implement C→Zig callback bridge (4h) ⚠️ HIGH RISK
|
||||
- **Modify**: `src/platform/webrtc_native.zig`
|
||||
- 8 `callconv(.c)` callbacks: onLocalDescription, onLocalCandidate, onStateChange, onGatheringStateChange, onMessage, onOpen, onClosed, onError
|
||||
- Each recovers ChannelState via rtcGetUserPointer, updates state or queues data
|
||||
- **CRITICAL**: libdatachannel calls from internal thread → must be thread-safe
|
||||
- Push to lock-free queue or use atomic state flags consumed by update loop
|
||||
- **Depends on**: T5.2
|
||||
|
||||
### T5.6 — Implement thread-safe ChannelState (3h)
|
||||
- **Modify**: `src/platform/webrtc_native.zig`
|
||||
- `state: std.atomic.Value(Transport.State)` — lock-free state reads
|
||||
- `recv_queue` — mutex-protected FIFO (SPSC: libdatachannel thread writes, update loop reads)
|
||||
- `local_sdp`, `local_candidates`, `gathering_complete` — atomic or mutex-protected
|
||||
- Concurrent read/write test from two threads
|
||||
- **Depends on**: T5.5
|
||||
|
||||
### T5.7 — Implement createOffer() (4h)
|
||||
- **Modify**: `src/platform/webrtc_native.zig`
|
||||
- Build rtcConfiguration with ICE servers
|
||||
- rtcCreatePeerConnection → allocate ChannelState → wire callbacks via rtcSetUserPointer
|
||||
- rtcCreateDataChannelEx (reliable, ordered, protocol "zig-p2p")
|
||||
- Wire DataChannel callbacks (open, closed, message)
|
||||
- Return {channel_id, state}. Caller polls state.local_sdp for generated offer.
|
||||
- Test: createOffer(), wait for local_sdp != null, verify SDP contains "v=0"
|
||||
- **Depends on**: T5.6
|
||||
|
||||
### T5.8 — Implement acceptOffer() (3h)
|
||||
- **Modify**: `src/platform/webrtc_native.zig`
|
||||
- Create PeerConnection, set remote description (triggers answer generation)
|
||||
- Wire DataChannel callback for incoming channel from remote
|
||||
- Test: createOffer on A → pass SDP to acceptOffer on B → verify answer SDP
|
||||
- **Depends on**: T5.7
|
||||
|
||||
### T5.9 — Implement send/receive/close (3h)
|
||||
- **Modify**: `src/platform/webrtc_native.zig`
|
||||
- send() → rtcSendMessage(dc_id, data.ptr, data.len)
|
||||
- receive() → read from ChannelState.recv_queue
|
||||
- close() → rtcClose, rtcDeleteDataChannel, rtcDeletePeerConnection
|
||||
- canSend() → check rtcGetBufferedAmount < threshold
|
||||
- canReceive() → check recv_queue non-empty
|
||||
- **Depends on**: T5.7, T5.8
|
||||
|
||||
### T5.10 — Implement ICE candidate exchange (2h)
|
||||
- **Modify**: `src/platform/webrtc_native.zig`
|
||||
- addRemoteCandidate(channel_id, candidate) → rtcAddRemoteCandidate(pc_id, cand, "0")
|
||||
- drainLocalCandidates(channel_id) → return accumulated local candidates, clear list
|
||||
- getLocalSdp(channel_id) → return SDP
|
||||
- Test: two NativeWebRTCTransport exchanging SDP/ICE in-memory
|
||||
- **Depends on**: T5.9
|
||||
|
||||
### T5.11 — Loopback integration test: two native WebRTC peers (4h)
|
||||
- **Create**: `tests/integration/test_webrtc_loopback.zig`
|
||||
- Two NativeWebRTCTransport instances
|
||||
- A creates offer, B accepts, exchange ICE in-memory
|
||||
- Wait for DataChannel open
|
||||
- Send "hello world" A→B, verify. Send response B→A, verify.
|
||||
- Test reliable and unreliable channel configs
|
||||
- **Depends on**: T5.10
|
||||
- **Risk**: ICE may fail in loopback. Use 127.0.0.1 bind, may need STUN disabled.
|
||||
|
||||
### T5.12 — Conform to Transport vtable (3h)
|
||||
- **Modify**: `src/platform/webrtc_native.zig`
|
||||
- Create `WebRTCChannelTransport` wrapper: holds ref to NativeWebRTCTransport + channel_id
|
||||
- Implements Transport vtable (send → self.manager.send(self.channel_id, data), etc.)
|
||||
- Interchangeable with PosixStreamTransport in PeerConnection
|
||||
- **Depends on**: T5.9, T1.1
|
||||
|
||||
### T5.13 — Implement SignalingMessage serialization (3h)
|
||||
- **Create**: `src/platform/webrtc_signaling.zig`
|
||||
- SignalingMessage: msg_type (offer/answer/ice_candidate), from_pubkey, sdp/candidate, timestamp, Ed25519 signature
|
||||
- serialize/deserialize
|
||||
- computeSignalingKey() — SHA-256(sorted pubkeys), same as MWP meeting point
|
||||
- Roundtrip + signature verification tests
|
||||
- **Depends on**: none (uses existing Ed25519)
|
||||
|
||||
### T5.14 — Implement DHT-based signaling (4h)
|
||||
- **Create**: `src/platform/webrtc_dht_signaling.zig`
|
||||
- Use dhtStore/dhtFindValue to exchange WebRTC signaling messages
|
||||
- Flow: compute meeting key → store offer → poll for answer → exchange ICE
|
||||
- Reuse MWP meeting point derivation
|
||||
- Timeout with retry
|
||||
- Test: two P2P instances on localhost, one stores offer in DHT, other finds it
|
||||
- **Depends on**: T5.13, T1.15
|
||||
|
||||
### T5.15 — Implement ICE candidate trickle via DHT (3h)
|
||||
- **Modify**: `src/platform/webrtc_dht_signaling.zig`
|
||||
- Periodically store batched candidates in DHT
|
||||
- Other peer polls for new candidates
|
||||
- Versioned keys or growing value
|
||||
- Test: ICE candidates propagate, connection succeeds with delayed candidates
|
||||
- **Depends on**: T5.14
|
||||
|
||||
### T5.16 — WebSocket signaling fallback (3h)
|
||||
- **Create**: `src/platform/webrtc_ws_signaling.zig`
|
||||
- For bootstrap: when DHT unavailable (first browser peer with no native bootstrap)
|
||||
- Use libdatachannel's WebSocket client (rtcCreateWebSocket — free with the library)
|
||||
- Lower priority — DHT signaling (T5.14) is primary path
|
||||
- **Depends on**: T5.10, T3.4
|
||||
|
||||
### T5.17 — Integrate WebRTC transport into P2P connection flow (4h)
|
||||
- **Modify**: `src/p2p/connection.zig`, `src/p2p/config.zig`
|
||||
- Add `webrtc: bool = false` to P2PConfig.transports
|
||||
- When enabled + peer is browser: WebRTC connection path
|
||||
- Flow: compute signaling key → create/wait offer → exchange SDP/ICE via DHT → DataChannel opens → create PeerConnection with WebRTCChannelTransport → Noise handshake
|
||||
- When connecting to native peer: prefer UDP
|
||||
- **Depends on**: T5.12, T5.14, T1.12
|
||||
|
||||
### T5.18 — Noise handshake over WebRTC DataChannel (3h)
|
||||
- Verify Noise XX works over WebRTC DataChannel transport
|
||||
- SecureConnection uses Transport interface (T1.9), WebRTCChannelTransport implements it (T5.12)
|
||||
- Should work without code changes — create integration test
|
||||
- Test: two peers connect via WebRTC, Noise handshake, exchange encrypted messages, verify wire envelope nonce auth
|
||||
- **Depends on**: T5.12, T1.9
|
||||
|
||||
### T5.19 — Native-to-browser connection test (4h) ⚠️ HIGH RISK
|
||||
- **Create**: `tests/integration/test_native_browser.js` (Playwright + native)
|
||||
- Launch native peer with WebRTC enabled
|
||||
- Launch browser page with WASM peer
|
||||
- Exchange signaling via WebSocket signaling server
|
||||
- Verify DataChannel established
|
||||
- Send native→browser, verify. Send browser→native, verify.
|
||||
- **Depends on**: T5.17, T3.7
|
||||
- **Risk**: DTLS negotiation, SDP format, ICE candidates must be compatible
|
||||
|
||||
### T5.20 — File transfer over WebRTC DataChannel (3h)
|
||||
- Test piece-based file transfer through WebRTC transport
|
||||
- Key: WebRTC DataChannel max message size (default 256KB) must be >= piece size
|
||||
- Configure rtcConfiguration.maxMessageSize if needed
|
||||
- Test: 1MB file from native to browser, all pieces verified
|
||||
- **Depends on**: T5.19
|
||||
|
||||
### T5.21 — Cleanup and resource management (3h)
|
||||
- **Modify**: `src/platform/webrtc_native.zig`
|
||||
- Proper deinit(): close DataChannels, delete PeerConnections, rtcCleanup()
|
||||
- Edge cases: disconnect during handshake, ICE failure, DataChannel close
|
||||
- Leak test: 100 connections created+closed, verify zero leaked allocations
|
||||
- **Depends on**: T5.11
|
||||
|
||||
### T5.22 — CI build integration (2h)
|
||||
- Add CI step: `zig build -Denable-webrtc=true`
|
||||
- Document install steps per platform
|
||||
- Non-WebRTC builds unaffected
|
||||
- **Depends on**: T5.3
|
||||
|
||||
### T5.23 — Phase 5 comprehensive test (4h)
|
||||
- Full suite with WebRTC enabled
|
||||
- Matrix: native↔native via UDP (no regression), native↔native via WebRTC, native↔browser via WebRTC
|
||||
- Verify Noise + wire envelope on all paths
|
||||
- **Depends on**: T5.17 through T5.21
|
||||
- **Gate**: MUST pass before Phase 6
|
||||
|
||||
---
|
||||
|
||||
## Phase 6: Integration and Polish (9 tasks, ~30h)
|
||||
|
||||
### T6.1 — Auto-transport negotiation (4h)
|
||||
- **Modify**: `src/p2p/connection.zig`, `src/p2p/config.zig`
|
||||
- Native-to-native: prefer UDP. Native-to-browser: use WebRTC.
|
||||
- Store transport capabilities in DHT peer metadata
|
||||
- Auto-select on connection
|
||||
- **Depends on**: T5.17
|
||||
|
||||
### T6.2 — Connection upgrade: WebRTC → UDP (3h)
|
||||
- **Modify**: `src/p2p/connection.zig`
|
||||
- If two native peers connected via WebRTC, attempt upgrade to UDP
|
||||
- Exchange UDP addresses, attempt direct connection, migrate transport
|
||||
- **Depends on**: T6.1
|
||||
|
||||
### T6.3 — Error handling and timeouts (3h)
|
||||
- **Modify**: `src/platform/webrtc_native.zig`, `src/platform/webrtc_dht_signaling.zig`
|
||||
- 30s timeout for WebRTC connection establishment
|
||||
- Handle ICE failure, DTLS failure, DataChannel not opening
|
||||
- Propagate errors for retry/fallback
|
||||
- **Depends on**: T5.17
|
||||
|
||||
### T6.4 — TURN server support (2h)
|
||||
- **Modify**: `src/platform/webrtc_native.zig`
|
||||
- Add TURN server URLs to rtcConfiguration
|
||||
- Config: `ice_servers: ["stun:stun.l.google.com:19302", "turn:user:pass@turn.example.com:3478"]`
|
||||
- **Depends on**: T5.7
|
||||
|
||||
### T6.5 — End-to-end browser + DHT test (4h)
|
||||
- **Create**: `tests/e2e/test_full_stack.js`
|
||||
- 3 native peers forming DHT + 1 browser peer
|
||||
- Browser discovers native peers via DHT, connects via WebRTC
|
||||
- Exchange messages, store/retrieve DHT values across transport boundaries
|
||||
- **Depends on**: T5.19, T5.14
|
||||
|
||||
### T6.6 — Cross-browser testing (3h)
|
||||
- Run browser tests on Chrome, Firefox, Safari
|
||||
- Fix browser-specific WebRTC quirks
|
||||
- Document minimum browser versions
|
||||
- **Depends on**: T3.8
|
||||
|
||||
### T6.7 — Performance profiling (3h)
|
||||
- Measure: WebRTC connection setup time, DataChannel throughput, latency vs UDP, WASM memory, CPU
|
||||
- Compare against design doc targets (setup <500ms, throughput >10MB/s)
|
||||
- Document results
|
||||
- **Depends on**: T5.23
|
||||
|
||||
### T6.8 — Documentation (4h)
|
||||
- **Create/Modify**: `docs/WEBRTC_BUILD.md`, `docs/WASM_QUICKSTART.md`, README.md
|
||||
- Build instructions, deployment guide, API reference, architecture diagrams
|
||||
- New developer can follow docs to run native-to-browser demo
|
||||
- **Depends on**: T6.5
|
||||
|
||||
### T6.9 — Final regression and cleanup (4h)
|
||||
- Full suite: native + WASM + WebRTC
|
||||
- No Thread.sleep in WASM paths, no direct posix.* in platform-agnostic code
|
||||
- Remove temporary workarounds
|
||||
- **Depends on**: all above
|
||||
|
||||
---
|
||||
|
||||
## Critical Path
|
||||
|
||||
```
|
||||
T0.2 → T1.1 → T1.3 → T1.7 → T1.8 → T1.9 → T2.5 → T2.6 → T2.13
|
||||
↓
|
||||
T5.1 → T5.2 → T5.3 → T5.5 → T5.6 → T5.7 → T5.9 → T5.12 → T5.17 → T5.19
|
||||
```
|
||||
|
||||
## Summary
|
||||
|
||||
| Phase | Tasks | Hours |
|
||||
|-------|-------|-------|
|
||||
| 0: Audit | 4 | 7 |
|
||||
| 1: Transport Abstraction | 16 | 48 |
|
||||
| 2: Event-Driven I/O | 13 | 37 |
|
||||
| 3: WASM Browser | 8 | 24 |
|
||||
| 4: FileSystem | 7 | 17 |
|
||||
| 5: Native WebRTC (libdatachannel) | 23 | 71 |
|
||||
| 6: Integration | 9 | 30 |
|
||||
| **Total** | **80** | **~234** |
|
||||
|
||||
Phase 3 and Phase 4 can run in parallel after Phase 2 completes.
|
||||
Reference in New Issue
Block a user