diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 022ba5a..091aef9 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -24,8 +24,10 @@ When a user interacts with a video: ## 3. Two-Phase Force Sync Ensures all peers are frame-perfect and buffered before resuming: 1. **Prepare**: Initiator sends `FORCE_SYNC_PREPARE` with the target timestamp. -2. **Buffer**: Peers seek and pause. Once buffered (`readyState >= 3`), they send a `FORCE_SYNC_ACK`. +2. **Buffer**: Peers seek and pause. Once buffered (`readyState >= 3`), they send a `FORCE_SYNC_ACK`. (Note: `content.js` limits polling to 8000ms). 3. **Execute**: Once the Initiator collects ACKs (or after an 8.5s timeout), they send `FORCE_SYNC_EXECUTE`. + > [!IMPORTANT] + > **Network Transit Buffer Rule**: The orchestrator (`background.js`) must always use a timeout at least 500ms longer than the worker (`content.js`) to account for IPC and network transit time. Never align them exactly 1:1, as this will introduce a race condition on slow connections. 4. **Resume**: All peers call `play()` simultaneously. ## 4. Episode Auto-Sync @@ -43,13 +45,21 @@ To maintain a clean room state and eliminate "Ghost Peers": - **Server Pruning**: The server runs a "Reaper" every 2 minutes. If a peer has sent **zero** activity (no events and no heartbeats) for 5 minutes, they are forcefully disconnected. - **Immediate Cleanup**: Rooms are deleted instantly when the last peer leaves or disconnects. -## 6. Security & Stability +> [!CAUTION] +> **Identity Rule**: Differentiate between `peerId` and `socket.id`. Use `socket.id` exclusively for ephemeral transport routing on the server. Use `peerId` exclusively for identity, state management, and room tracking across the stack. + +## 6. Broadcast Protocol & Routing +KoalaSync uses a megaphone routing approach to minimize server logic: +- **`emit()` Broadcast Behavior**: Any `emit()` from the extension client is unconditionally broadcast to **all other peers in the room**. It is not a direct message. +- **Storm Prevention**: When dispatching state updates in response to a new user joining (e.g., an active lobby state), ensure ONLY the initiator (or a designated leader) calls `emit()` to prevent $O(N)$ broadcast storms. + +## 7. Security & Stability - **Service Worker Lifecycle**: Uses `chrome.alarms` to prevent the Manifest V3 service worker from suspending while in an active room. - **Rate Limiting**: Server-side per-socket and per-IP rate limits to prevent sync-spamming or DoS. - **Noise Filtering**: Uses a curated blacklist of domains (Search Engines, Social Media) to declutter the "Target Tab" selector in the popup. - **Diagnostics**: A "Dev" tab provides real-time access to the underlying `