Overview
The architecture consists of three primary layers:- Client Layer - TUI, CLI commands, browser extensions, HTTP API clients
- Service Layer - Download orchestration, event streaming, state management
- Engine Layer - Worker pools, concurrent downloaders, file I/O
Surge runs one background engine per machine. All clients connect to this shared daemon, ensuring downloads continue even when you close the TUI.
Core Components
The daemon is composed of several global components initialized at startup:GlobalPool (WorkerPool)
Manages concurrent downloads with configurable slots (default: 3).- Queue management (up to 100 buffered tasks)
- Worker allocation (spawns N goroutines)
- Pause/Resume/Cancel operations
- Graceful shutdown with state persistence
Add(cfg types.DownloadConfig)- Queues a new downloadPause(downloadID string)- Pauses active download and saves stateResume(downloadID string)- Hot-resumes from saved.surgefileGracefulShutdown()- Pauses all downloads before exit
WorkerPool Implementation Details
WorkerPool Implementation Details
The WorkerPool maintains two maps:Each worker goroutine continuously pulls from
taskChan and invokes TUIDownload() with cancellable contexts.GlobalService (LocalDownloadService)
Provides a unified API for all download operations and event streaming.DownloadStartedMsg- File metadata resolvedDownloadProgressMsg- Speed/bytes/ETA updates (150ms interval)DownloadCompleteMsg- Success with elapsed timeDownloadErrorMsg- Failure with error detailsDownloadPausedMsg/DownloadResumedMsgDownloadQueuedMsg/DownloadRemovedMsg
All TUI instances, the HTTP server, and headless consumers receive the same event stream via
StreamEvents(). This enables real-time sync across multiple terminals.GlobalProgressCh (Event Channel)
A buffered channel (capacity: 100) that workers use to publish events.Communication Flow
TUI Mode (Interactive)
Server Mode (Headless)
In server mode, Surge runs without a TUI:- HTTP server binds to
0.0.0.0:1700(configurable) - Events stream to stdout instead of TUI
- Browser extension sends downloads via POST
/download - Token-based authentication (Bearer token)
Remote TUI Mode (Connect)
Connect to a remote daemon:- TUI sends HTTP requests instead of calling
GlobalServicedirectly - Uses
RemoteDownloadServicewrapper - WebSocket or polling for event streaming
Local Architecture
Direct Access
- TUI → GlobalService (in-process)
- Zero latency
- Shared memory state
Remote Architecture
HTTP API
- TUI → HTTP Client → Server
- Network latency
- REST + SSE/WebSocket
Download Engine
Each download is handled by either:Single-Threaded Downloader
Used when:- Server doesn’t support range requests (
Accept-Ranges: none) - File size is unknown (
Content-Lengthmissing)
- Probe server with HEAD request
- Open single GET connection
- Stream to file with progress reporting
Concurrent Downloader
Used when:- Server supports range requests (
Accept-Ranges: bytes) - File size is known
- Calculate optimal connections (square root heuristic)
- Split file into large chunks (fileSize / numWorkers)
- Spawn N workers, each downloading a chunk
- Workers write to file using
WriteAt()(thread-safe) - Progress aggregated via atomic counters
For a 100 MB file: √100 = 10 connections
For a 1 GB file: √1024 ≈ 32 connections (capped at max)
For a 1 GB file: √1024 ≈ 32 connections (capped at max)
State Persistence
Surge uses two persistence layers:1. Master Download List (SQLite)
Located at~/.local/state/surge/surge.db (Linux) or ~/Library/Application Support/surge/surge.db (macOS).
Stores:
- Download history (completed/error/queued)
- Metadata (URL, filename, size, speed)
- User-initiated pauses
2. Resume State Files (.surge)
Located alongside incomplete downloads (e.g.,file.zip.surge).
Stores:
- Remaining byte ranges (task queue)
- Downloaded byte count
- Chunk bitmap (visual representation)
- Mirror list
- Elapsed time
HTTP API
The daemon exposes a REST API on port 1700 (auto-increment if busy). Key Endpoints:POST /download- Add new downloadGET /download?id=<uuid>- Query statusPOST /pause/<id>- Pause downloadPOST /resume/<id>- Resume downloadDELETE /download/<id>- Cancel and removeGET /downloads- List all downloads
The browser extension uses this API to send intercepted downloads. If ExtensionPrompt is enabled in settings, downloads require TUI confirmation.
Locking and Concurrency
Surge prevents multiple instances from running simultaneously:- Linux:
/run/user/<uid>/surge/surge.lock - macOS:
~/Library/Caches/surge/surge.lock - Windows:
%LOCALAPPDATA%\surge\surge.lock
Summary
Single Engine
One
GlobalPool manages all downloads across all clientsEvent-Driven
GlobalProgressCh streams events to TUI, API, and logsPersistent
SQLite +
.surge files enable seamless resumeMulti-Client
TUI, CLI, browser extension, and API share the same backend