Skip to content

Concurrency Model & Goroutine Lifecycle ​

Handling dozens of high-bitrate RTSP streams alongside concurrent WebRTC viewers and continuous disk archiving requires a deterministic, leak-free concurrency architecture.


1. Goroutine Hierarchy & Context Propagation ​

Every background goroutine in RUSEON Core is bound to a structured context.Context tree:

  • Root Context: Derived from OS signals (SIGINT, SIGTERM).
  • Camera Context: Scoped to the lifecycle of an individual camera. Disconnecting a camera automatically cancels its ingestion worker, demuxer loop, and recorder channels simultaneously.
  • Client Session Context: Scoped to individual WebRTC peer connections or HLS chunk downloads.

2. Channel Ownership & Non-Blocking Patterns ​

To prevent deadlocks and channel leaks, RUSEON enforces strict channel discipline:

  1. Explicit Ownership: The producing goroutine always creates and closes channels. Consumers never close channels.
  2. Non-Blocking Ingress (select ... default): Broadcasting to subscribers always uses non-blocking select statements. A stalled subscriber cannot stall the producer.
  3. Bounded Buffers: All channels have explicit bounded capacities (e.g. RingBuffer subscriber channels have a capacity of 50–100 frames).

3. Lock Stratification (Deadlock Prevention) ​

To guarantee that concurrent lock acquisitions cannot form cyclic dependencies:

$$\text{Level 1: Ring Storage Mutex} \longrightarrow \text{Level 2: Subscriber Registry Mutex}$$

  • Rule: A goroutine holding a Subscriber Mutex is strictly forbidden from acquiring the Ring Storage Mutex.
  • Read operations on codec parameters bypass mutexes entirely using atomic.Pointer[CodecParams].

4. Graceful Shutdown Orchestration ​

When a shutdown signal (SIGTERM) is received:

  1. Stop accepting new HTTP/WHEP connections.
  2. Cancel the root context to stop camera RTSP ingestion loops.
  3. Drain all remaining in-memory frames through the fMP4 archiver.
  4. Execute unix.SyncFileRange to flush remaining 2MB sliding windows to disk.
  5. Close BadgerDB v4 safely to ensure WAL commit consistency.

Released under the MIT License.