Files
piik/docs/research/server-consolidation.md
T
AAA 066e218d84 fix(media): improve connection recovery and capture compatibility (#498)
## Problem and outcome

Stale ICE and transport callbacks, interrupted media ownership, and optional encoder capabilities could break otherwise recoverable sharing sessions. This maintenance phase corrects those owners across Web, Native and embedded SFU, improves current-state diagnostics, and finishes the affected UI and documentation animation paths.

Android, QR invitations and App/Server headline presentation stay on their feature branch. This PR contains the accepted maintenance scope only.

## Release notes

**Play together. Your turn!**

Approved friends can play together with shared keyboard and mouse controls or optional gamepads.

**远程同乐,轮到你啦!**

获准的朋友可以共用键鼠,或使用可选手柄,一起玩本地多人游戏。

### English

This maintenance update improves connection recovery, capture compatibility and troubleshooting for existing Piik rooms.

- Keep ICE candidates and gathering completion tied to their current connection. Preserve Viewer route preferences through reconnection and retry newly available Peer opportunities after SFU fallback.
- Correct picture and voice ownership during restart, source replacement and connection retirement. Report failed picture dependencies while keeping room voice available.
- Separate capture and forwarding statistics and isolate pooled sender attachment failures.
- Improve Windows H.264 compatibility with optional encoder properties, retain safe capture failure codes, and keep shared sound volume usable without microphone support.
- Improve remote input continuity and mouse responsiveness after idle.
- Fix fullscreen handling in some mobile browsers, source-picker refresh, delayed chat confirmations, starred-site startup and local App requests. Refine control motion and reduced-motion behavior.
- Restore the mascot's face and shared animation lifecycle in the documentation header.
- Include current connection and playback state in diagnostic exports, update Zod to 4.6.6 and simplify shared lifecycle code.

Existing 2.x protocols, configuration and default quality settings are preserved.

### 中文

本次维护更新改善现有房间的连接恢复、采集兼容性和故障诊断。

- ICE 候选和收集结束事件跟随当前连接;重连保留观众线路偏好,SFU 兜底后出现新的可用 P2P 机会仍可尝试。
- 修正重启、换源和连接结束时的画面与语音生命周期;语音继续时,画面失败会明确反馈。
- 区分采集与转发统计,隔离编码池中单个输出连接的失败。
- 改善 Windows H.264 可选属性兼容性,保留有效的采集失败原因;没有麦克风能力时也能调整共享声音音量。
- 修复部分移动浏览器全屏、选源刷新、迟到聊天确认、收藏站点启动和本机 App 请求问题,打磨控件动效及减少动态效果行为。
- 修复文档导航 mascot 面部一直隐藏的问题,接回共用动画生命周期。
- 诊断导出补取当前连接与播放状态,升级 Zod 至 4.6.6,精简共用生命周期代码。

沿用现有 2.x 协议、配置和画质默认值。Android、二维码邀请及 App/Server 新增的 HEADLINE 展示留待后续版本。

## Verification

- `npm run check`: type-check, 98 test files / 1,765 tests, production Web build passed.
- `npm run check:go-core`: Go formatting, tests, vet, Windows/Linux builds passed; Darwin builds require the native CI runners.
- `npm run check:native`: current Windows capture compilation, fixtures and capability probe passed.
- `npm run build:website`, TypeScript and repository hygiene checks passed after the documentation-brand fix.
- Existing controlled media lifecycle and P2P/SFU voice acceptance covered the retained route/transport changes. Final local browser acceptance covered actual sharing and pause/resume, fullscreen, source refresh, voice/keyboard/settings, 320px to desktop layouts, both themes and all presentation modes. Documentation brand was reproduced broken, then verified on load, replay and reduced motion.
- Independent scoped reviews found no integration blocker.

## Impact

Patch release v2.4.1. Existing 2.x wire, configuration, authority, capacity and default quality contracts remain intact; no data migration. Source volume no longer depends on microphone availability. Zod 4.6.6 fixes GHSA-mrhx-c7xc-m3w5.

The device-specific Windows reports #495 and #452 remain under investigation; this PR improves compatibility and diagnostics without claiming those reports fully resolved. Physical macOS acceptance remains with its native runner/device checks.
2026-10-24 12:30:39 -04:00

8.2 KiB

Server Consolidation

  • Reviewed: 2026-10-07
  • Status: published; current physical limits are in verification status. The before/after measurements below describe the original 2026-09-06 consolidation, not current package cost.
  • Scope: one shared Go backend for Hosted and self-contained App operation

Current Ownership

cmd/piik-server (Hosted) and cmd/piik-app (App) compose the same application from internal/server and own only their defaults, reachability, and lifecycle policy. Within that scope protocol owns wire types, strict decoding, and shared scalars; config owns environment validation plus the Hosted and Local compositions; room owns room authority, participants, and the SQLite database; route decides graph transitions without I/O; signal serializes room/signaling authority and commits SFU intent, then runs slow media effects outside that lock with exact lifetime checks; sfu owns admission and embedded media through the shared Pion/LiveKit adapter; app owns HTTP composition, site access, static assets, and lifecycle; and webassets carries the embedded Browser bundle. internal/app keeps the native, launcher, and platform boundaries and supervises no server process. These are useful boundaries, not duplication to remove.

Structural Simplification

  1. Room expiry and abandonment share one terminateRoom path in signal. Preserve the distinct semantics of stopping a share, ending a room, and restarting a persistent server.
  2. The Hybrid connection-ID mirror is gone. The viewer-quality evidence path and the active media-edge lookup read the connection identity from the committed edge, and the evidence gate keeps its own last-observation identity; router tests cover in-place connection adoption during a rebuild and exact direct/peer-relayed evidence sources.

These are structural simplifications, not reproduced functional failures. The engineering reference requires a concrete ownership gain before further extraction.

Product Choice

The graph controller is now universal. The former rollout switch and ordinary Host-star signaling path were removed together, so Hosted and Local share one route authority. Embedded SFU remains an optional fallback of that graph under ADR-0013.

Target Composition

one Go module
cmd/piik-server -> shared server application
cmd/piik-app -> shared server application + launcher + native media
internal/server    -> rooms, routing, HTTP/signaling, persistence, SFU adapters
internal/app       -> current native and platform boundaries
one React/Vite static artifact -> embedded in both binaries

Use packages for cohesive owners and files for local concerns. Do not introduce a framework layer per file, a second product API, or a multi-module build. Hosted and Local construct the same validated application options; entry points own their defaults, reachability and lifecycle policy.

Each room keeps one serialized state owner. Go HTTP/WebSocket handlers must not mutate room, share and route maps independently. Run password derivation and media-transport I/O outside that owner, then apply results only while the exact session, share and operation identities still match. Preserve the existing distinction between decisions and effects rather than replacing Node serialization with unrelated locks around each map.

Reusable Components

  • Standard net/http and embed serve HTTP and the built assets.
  • Signaling reuses the App's coder/websocket.
  • Embedded SFU and Native media share internal/media/forwarding, which reuses Pion transport and LiveKit media components. SDP/ICE uses the authenticated room WebSocket; no external LiveKit room API or media-token service remains.
  • Room persistence keeps the current schema and transactions on the pure-Go modernc.org/sqlite driver, which builds without cgo and holds one exclusive connection; no ORM is needed.
  • The layout follows Go's shared internal and multiple cmd guidance. Pion, capture sidecars and control-tunnel ownership are unchanged.

Minimum Acceptance

Preserve exact Host/session replacement, grant revocation, atomic room replacement, SQLite restart continuity and Local shutdown semantics. Exercise one graph and one operation through Peer, SFU, same-edge regeneration, bounded overlap and rollback, including stale asynchronous completions. Preserve short-lived SFU authority and release resources only after physical drain confirmation.

Use the same Browser contract scenarios against Hosted and Local, plus one physical mixed Browser/App media flow. Package size, startup and idle memory are measured below. Keep one strict wire contract and one schema owner; avoid hand-maintained parallel TypeScript/Go validation rules. The Node server, bundled runtime, supervisor and old packaging paths retire in this same accepted integration boundary, preserving ADR-0005 and ADR-0010 as amended by ADR-0012.

Measured Before And After

Signaling Execution Check

On 2026-10-07, an isolated Windows loopback check used 10 rooms with one Host and 20 Viewers each. Nine Hosts changed their display names 10 times/s, exercising presence encoding and fan-out; another task changed room policy 10 times/s, and four password tasks ran once/s outside the signaling lock. The diagnostic variant additionally wrote 200 synthetic route records/s through the real file sink under that lock. Each run measured 200 requests from a separate room.

Storage / diagnostics Signaling lock wait P95 Request round-trip P95 Retained connections
Memory Below clock resolution 6.5 ms 210/210
SQLite 1.0 ms 5.9 ms 210/210
SQLite + diagnostic sink 3.0 ms 7.0 ms 210/210

These short local checks do not establish WAN, slow-disk or maximum-capacity performance. A separate overload run at 900 name changes/s and 40 password tasks/s reached 205 ms request P95 and lost 12 connections while bounded queues were exercised; it is not a passing workload. The ordinary workload provides no reason to introduce room actors or another mutation owner. Preserve the bounded queues and unlocked password/media work; measure synchronous storage and diagnostic sinks before changing execution for a larger deployment.

Original Package Consolidation

One machine, 2026-09-06: Windows 11, Node 24.15.0, Go 1.26.6. A script spawned each server with the same production configuration (PORT=18787, HTTPS public origin, site-access password, one STUN URL, loopback listen host), polled /healthz every 10 ms until {"status":"ok"}, waited 5 s idle, sampled resident memory through PowerShell WorkingSet64, then killed the process. Five runs per side; the median is reported. Before is the Node baseline at tag baseline-b20fd88; after is piik-server under the same script.

metric before after
cold start to healthy 160 ms 81 ms
idle resident memory 77,242,368 B 10,928,128 B
shipped Hosted bytes ~106.7 MB ~14.0 MB

The before total is the Node runtime (91,694,408 B), the production node_modules tree (12,640,469 B in 1,513 files), dist/client (1,492,721 B) and dist/server (856,898 B). The after total is the linux/amd64 piik-server built with -s -w and embedded assets (13,983,906 B) plus its notices and REVISION. For reference, the windows/amd64 binaries are 14,276,608 B (piik-server) and 22,703,104 B (piik-app, which also carries Pion and the terminal UI); the App package additionally drops the Node runtime and dependency tree it used to ship beside its Go executable.

The first two starts of a freshly built binary took 469 ms and 336 ms, which is consistent with on-access antivirus scanning of a new executable; the median above is the steady state. Not measured: throughput or latency under load, which this port does not change, and the Linux deployment host.