# cplieger/subflux architecture

> Architecture diagram of the GitHub repository cplieger/subflux, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-07-09). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/cplieger/subflux
- Repository: https://github.com/cplieger/subflux

## Overview

1. **What this repo is**
   Subflux is a single Go service that combines a CLI, an HTTP server, a subtitle-search/download worker, and a subtitle-sync engine. It is designed to manage Sonarr/Radarr-managed media libraries, query third-party subtitle providers, and write synced `.srt` files back to the media filesystem.

2. **Top-level execution model**
   The main entry points are the Go binaries in `main.go`, `cli.go`, and the `cmd/wire-codegen` helper. At runtime, the same process can act as:
   - the long-running web/API server,
   - a background scanner/scheduler,
   - and a CLI client that talks to a remote instance via `SUBFLUX_URL`.
   The Docker image is a static, nonroot distroless container, so the app is intentionally packaged as one self-contained service.

3. **Configuration and dependency wiring**
   Configuration is loaded, validated, and expanded in `internal/config`, with schema metadata in `internal/config/schema`. The repository uses explicit wiring (`internal/wiring`, plus generated wiring support) to assemble services from config and storage backends. That makes configuration a first-class boundary: load/validate config first, then build the server, providers, search engine, and auth subsystems from it.

4. **Persistent state boundary**
   State is split between a file-backed config and embedded key-value stores. The `internal/boltstore` package provides the bbolt-backed storage engine, while `internal/store/kv` and `internal/store/storetest` define lower-level KV abstractions and contracts. On top of that sit domain-specific stores such as `internal/authstore` for users/sessions/API keys/passkeys/OIDC state and `internal/cache` / `internal/server/polling` caches for runtime behavior.

5. **Media discovery and orchestration**
   The core operational loop lives in `internal/search` and `internal/server/scanning`. It consumes media inventory from Sonarr/Radarr history plus scheduled full-library scans, builds target state, and decides what subtitles are missing or need upgrading. The scanner is optimized for bounded, batch-oriented work rather than unbounded background crawling, which is central to the repo’s low-memory design.

6. **Sonarr/Radarr integration**
   `internal/arrapi` is the dedicated integration layer for Arr APIs. It fetches library/history/notify data and translates Arr-specific responses into Subflux’s internal media model. This is the main ingress for real-world media events: import history changes, wanted items, and notifications flow from Arr into the search/scanning pipeline.

7. **Provider architecture**
   Subtitle sources are isolated under `internal/provider/*` and registered through `internal/provider/registry`. Providers include OpenSubtitles, SubDL, SubSource, YIFY Subtitles, BetaSeries, AnimeTosho, Gestdown, HDBits, embedded/ffprobe-based sources, and archive helpers. The provider layer handles HTTP access, retries, provider-specific filters, and download normalization, so the rest of the system treats providers uniformly.

8. **Search, scoring, and selection**
   `internal/search` performs the main subtitle matching pipeline. It first applies identity checks using stable media identifiers and metadata, then ranks candidates using a 0–100 release-quality score in `internal/scorer` and `internal/search/scoring`. This is where the repo’s “find, score, download, upgrade” policy lives: provider results are not accepted directly; they must pass identity gates and quality heuristics before download.

9. **Subtitle download and sync pipeline**
   After a subtitle is selected, `internal/search/search_download.go` and `internal/subsync` handle the file-processing path. `internal/subsync` is a substantial pure-algorithm subsystem: it parses subtitle formats, extracts audio via ffmpeg, performs VAD and alignment, estimates framerate, and time-shifts cues so the final subtitle matches the video. The output boundary is a written subtitle file on the media filesystem, not an in-memory result.

10. **Automation, locks, and manual overrides**
    `internal/server/manualops`, `internal/server/polling`, and `internal/server/scheduler` coordinate recurring work and user-initiated actions. Manual downloads create locks so automation does not overwrite them; the system also clears locks when files are deleted or media is replaced. This separation between automated scans and explicit user actions is important in the architecture diagram.

11. **HTTP server, UI, and event flow**
    `internal/server` is the main composition layer for HTTP routes, middleware, auth, scans, config, files, coverage, and sync endpoints. The UI is a vanilla TypeScript SPA in `internal/server/static-src`, embedded into the binary under `internal/server/static`. The server also exposes SSE/live updates through the event bus in `internal/server/events`, so the UI can react to scan/search/status changes without polling everything.

12. **Authentication and security model**
    Authentication is handled by `internal/authstore` and the auth-related handlers under `internal/server/authhandlers`. Supported mechanisms include local passwords, API keys, passkeys/WebAuthn, OIDC, and TOTP. The repo treats client IP, rate limiting, and audit logs carefully; proxy awareness is configurable via trusted CIDRs so forwarded IPs are only accepted from known reverse proxies.

13. **Observability and operational boundaries**
    Metrics are exposed via `internal/metrics` and the server’s `/metrics` endpoint. The repo also includes structured logging, activity tracking, and health/operability support in `docs/OPERABILITY.md`. Operationally, the service is designed to be self-hosted and low-memory, with explicit tests and workflow files for CI, security scans, and release packaging.

14. **Key external dependencies to show in a diagram**
    The main external systems are:
    - Sonarr/Radarr instances via the Arr API layer,
    - subtitle provider APIs,
    - the media filesystem where subtitle files are written,
    - ffmpeg/ffprobe for sync and media analysis,
    - and browser clients hitting the embedded web UI/API.
    Everything else is internal composition around those boundaries.

Main entry points: [`internal/wiring/wiring.go`](https://github.com/cplieger/subflux/blob/main/internal/wiring/wiring.go) (Wiring), [`internal/server/server.go`](https://github.com/cplieger/subflux/blob/main/internal/server/server.go) (HTTP server), [`internal/search/search.go`](https://github.com/cplieger/subflux/blob/main/internal/search/search.go) (Search engine), [`internal/provider/registry.go`](https://github.com/cplieger/subflux/blob/main/internal/provider/registry.go) (Provider registry)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_runtime["Runtime entrypoints"]
  node_main(("Main service<br/>go entrypoint<br/>[main.go]"))
  node_cli(("CLI client<br/>go entrypoint<br/>[cli.go]"))
  node_wire(("Wire codegen<br/>go helper<br/>[main.go]"))
end

subgraph group_core["Core orchestration"]
  node_config["Config model<br/>config load/validate<br/>[config_load.go]"]
  node_schema["Config schema<br/>schema metadata<br/>[schema.go]"]
  node_wiring{{"Wiring<br/>composition root<br/>[wiring.go]"}}
  node_arrapi["Arr API<br/>media ingress<br/>[client.go]"]
  node_search{{"Search engine<br/>match-and-download pipeline<br/>[search.go]"}}
  node_scorer["Scoring<br/>quality ranking<br/>[scorer.go]"]
end

subgraph group_web["HTTP server"]
  node_server{{"HTTP server<br/>api composition<br/>[server.go]"}}
  node_events["Event bus<br/>live updates<br/>[bus.go]"]
  node_scanning{{"Scanner<br/>batch orchestration<br/>[scanning.go]"}}
  node_manualops["Manual ops<br/>user overrides<br/>[manualops.go]"]
end

subgraph group_data["State and stores"]
  node_authstore[("Auth store<br/>identity state<br/>[store.go]")]
  node_boltstore[("Bolt store<br/>embedded kv<br/>[store.go]")]
  node_kv["KV contracts<br/>storage abstractions<br/>[kv.go]"]
end

subgraph group_providers["Provider layer"]
  node_providerreg{{"Provider registry<br/>provider orchestration<br/>[registry.go]"}}
  node_opensubtitles["OpenSubtitles<br/>subtitle provider<br/>[opensubtitles.go]"]
  node_subdl["SubDL<br/>subtitle provider<br/>[subdl.go]"]
end

subgraph group_media["Media sync"]
  node_subsync{{"Subsync<br/>subtitle alignment<br/>[subsync.go]"}}
  node_ffmpeg["FFmpeg bridge<br/>media analysis<br/>[ffmpeg.go]"]
end

node_main -->|"load/validate"| node_config
node_main -->|"compose"| node_wiring
node_cli -->|"read config"| node_config
node_wire -->|"generate"| node_wiring
node_config -->|"schema"| node_schema
node_wiring -->|"build"| node_server
node_wiring -->|"build"| node_search
node_wiring -->|"register"| node_providerreg
node_wiring -->|"build"| node_authstore
node_wiring -->|"open"| node_boltstore
node_boltstore -->|"implements"| node_kv
node_server -->|"publish"| node_events
node_server -->|"run scans"| node_scanning
node_server -->|"manual actions"| node_manualops
node_server -->|"authenticate"| node_authstore
node_server -->|"arr routes"| node_arrapi
node_arrapi -->|"media events"| node_search
node_search -->|"query providers"| node_providerreg
node_search -->|"rank"| node_scorer
node_search -->|"sync subtitle"| node_subsync
node_subsync -->|"probe/extract"| node_ffmpeg
node_providerreg -->|"provider"| node_opensubtitles
node_providerreg -->|"provider"| node_subdl

click node_main "https://github.com/cplieger/subflux/blob/main/main.go"
click node_cli "https://github.com/cplieger/subflux/blob/main/cli.go"
click node_wire "https://github.com/cplieger/subflux/blob/main/cmd/wire-codegen/main.go"
click node_config "https://github.com/cplieger/subflux/blob/main/internal/config/config_load.go"
click node_schema "https://github.com/cplieger/subflux/blob/main/internal/config/schema/schema.go"
click node_wiring "https://github.com/cplieger/subflux/blob/main/internal/wiring/wiring.go"
click node_arrapi "https://github.com/cplieger/subflux/blob/main/internal/arrapi/client.go"
click node_search "https://github.com/cplieger/subflux/blob/main/internal/search/search.go"
click node_scorer "https://github.com/cplieger/subflux/blob/main/internal/scorer/scorer.go"
click node_server "https://github.com/cplieger/subflux/blob/main/internal/server/server.go"
click node_events "https://github.com/cplieger/subflux/blob/main/internal/server/events/bus.go"
click node_scanning "https://github.com/cplieger/subflux/blob/main/internal/server/scanning/scanning.go"
click node_manualops "https://github.com/cplieger/subflux/blob/main/internal/server/manualops/manualops.go"
click node_authstore "https://github.com/cplieger/subflux/blob/main/internal/authstore/store.go"
click node_boltstore "https://github.com/cplieger/subflux/blob/main/internal/boltstore/store.go"
click node_kv "https://github.com/cplieger/subflux/blob/main/internal/store/kv/kv.go"
click node_providerreg "https://github.com/cplieger/subflux/blob/main/internal/provider/registry.go"
click node_opensubtitles "https://github.com/cplieger/subflux/blob/main/internal/provider/opensubtitles/opensubtitles.go"
click node_subdl "https://github.com/cplieger/subflux/blob/main/internal/provider/subdl/subdl.go"
click node_subsync "https://github.com/cplieger/subflux/blob/main/internal/subsync/subsync.go"
click node_ffmpeg "https://github.com/cplieger/subflux/blob/main/internal/subsync/ffmpeg/ffmpeg.go"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_main,node_cli,node_wire toneBlue
class node_config,node_schema,node_wiring,node_arrapi,node_search,node_scorer toneAmber
class node_server,node_events,node_scanning,node_manualops toneMint
class node_authstore,node_boltstore,node_kv toneRose
class node_providerreg,node_opensubtitles,node_subdl toneIndigo
class node_subsync,node_ffmpeg toneTeal
```

## Components

### Runtime entrypoints

CLI, daemon, and codegen entrypoints.

- [Main service](https://github.com/cplieger/subflux/blob/main/main.go): go entrypoint · Long-running daemon entrypoint for server and background work. · `main.go`
- [CLI client](https://github.com/cplieger/subflux/blob/main/cli.go): go entrypoint · Command-line entrypoint for local and remote control. · `cli.go`
- [Wire codegen](https://github.com/cplieger/subflux/blob/main/cmd/wire-codegen/main.go): go helper · Dependency wiring generation helper. · `cmd/wire-codegen/main.go`

### Core orchestration

Config, wiring, search, and sync pipeline.

- [Config model](https://github.com/cplieger/subflux/blob/main/internal/config/config_load.go): config load/validate · Loads, validates, expands, and paths config as a first-class boundary. · `internal/config/config_load.go`
- [Config schema](https://github.com/cplieger/subflux/blob/main/internal/config/schema/schema.go): schema metadata · Schema and section metadata used to shape and render config. · `internal/config/schema/schema.go`
- [Wiring](https://github.com/cplieger/subflux/blob/main/internal/wiring/wiring.go): composition root · Assembles services from config, stores, providers, and server components. · `internal/wiring/wiring.go`
- [Arr API](https://github.com/cplieger/subflux/blob/main/internal/arrapi/client.go): media ingress · Sonarr/Radarr integration for history, wanted items, and notifications. · `internal/arrapi/client.go`
- [Search engine](https://github.com/cplieger/subflux/blob/main/internal/search/search.go): match-and-download pipeline · Orchestrates media inventory, provider queries, scoring, and download decisions. · `internal/search/search.go`
- [Scoring](https://github.com/cplieger/subflux/blob/main/internal/scorer/scorer.go): quality ranking · Release-quality and identity scoring used to rank candidate subtitles. · `internal/scorer/scorer.go`

### HTTP server

API, auth, UI, events, scanning, and automation.

- [HTTP server](https://github.com/cplieger/subflux/blob/main/internal/server/server.go): api composition · Main server composition for routes, middleware, auth, scans, config, files, and sync. · `internal/server/server.go`
- [Event bus](https://github.com/cplieger/subflux/blob/main/internal/server/events/bus.go): live updates · SSE/event propagation for scan, search, status, and activity updates. · `internal/server/events/bus.go`
- [Scanner](https://github.com/cplieger/subflux/blob/main/internal/server/scanning/scanning.go): batch orchestration · Scheduled and on-demand library scans that build scan items and feed the search loop. · `internal/server/scanning/scanning.go`
- [Manual ops](https://github.com/cplieger/subflux/blob/main/internal/server/manualops/manualops.go): user overrides · Manual search/download flows and locks that protect explicit user actions. · `internal/server/manualops/manualops.go`

### State and stores

Embedded storage, auth state, caches, and KV contracts.

- [Auth store](https://github.com/cplieger/subflux/blob/main/internal/authstore/store.go): identity state · Users, sessions, API keys, passkeys, OIDC state, and sweeper logic. · `internal/authstore/store.go`
- [Bolt store](https://github.com/cplieger/subflux/blob/main/internal/boltstore/store.go): embedded kv · bbolt-backed storage engine and maintenance for persistent state. · `internal/boltstore/store.go`
- [KV contracts](https://github.com/cplieger/subflux/blob/main/internal/store/kv/kv.go): storage abstractions · Low-level KV interfaces, codecs, keys, and contracts shared by stores. · `internal/store/kv/kv.go`

### Provider layer

Subtitle provider integrations and registry.

- [Provider registry](https://github.com/cplieger/subflux/blob/main/internal/provider/registry.go): provider orchestration · Registers provider implementations and normalizes provider behavior. · `internal/provider/registry.go`
- [OpenSubtitles](https://github.com/cplieger/subflux/blob/main/internal/provider/opensubtitles/opensubtitles.go): subtitle provider · Representative HTTP-backed provider with auth/search/download logic. · `internal/provider/opensubtitles/opensubtitles.go`
- [SubDL](https://github.com/cplieger/subflux/blob/main/internal/provider/subdl/subdl.go): subtitle provider · Representative provider implementation for subtitle search and download. · `internal/provider/subdl/subdl.go`

### Media sync

Subtitle parsing, alignment, and ffmpeg-driven syncing.

- [Subsync](https://github.com/cplieger/subflux/blob/main/internal/subsync/subsync.go): subtitle alignment · Parsing, ffmpeg audio extraction, VAD, framerate estimation, and cue shifting. · `internal/subsync/subsync.go`
- [FFmpeg bridge](https://github.com/cplieger/subflux/blob/main/internal/subsync/ffmpeg/ffmpeg.go): media analysis · FFmpeg/ffprobe wrappers used for extraction and probing. · `internal/subsync/ffmpeg/ffmpeg.go`

## Connections

- Main service → Config model: load/validate · Bootstraps runtime configuration before any services start.
- Main service → Wiring: compose · Builds the service graph for daemon mode.
- CLI client → Config model: read config · CLI resolves local or remote settings and targets.
- Wire codegen → Wiring: generate · Produces generated dependency wiring support.
- Config model → Config schema: schema · Configuration is constrained and documented by schema metadata.
- Wiring → HTTP server: build · Composition root creates the HTTP server and related subsystems.
- Wiring → Search engine: build · Wires search pipeline from config, stores, and providers.
- Wiring → Provider registry: register · Installs configured provider implementations.
- Wiring → Auth store: build · Creates auth/session state backed by embedded storage.
- Wiring → Bolt store: open · Opens the embedded key-value store backend.
- Bolt store → KV contracts: implements · Persistent storage is built on shared KV abstractions and codecs.
- HTTP server → Event bus: publish · Server emits lifecycle and status updates over the event bus.
- HTTP server → Scanner: run scans · HTTP and scheduler-triggered scanning flows enter the scanner.
- HTTP server → Manual ops: manual actions · User-initiated search/download operations go through manual ops.
- HTTP server → Auth store: authenticate · Auth handlers consult persistent identity/session state.
- HTTP server → Arr API: arr routes · Server and scan flows consume Sonarr/Radarr data through Arr integration.
- Arr API → Search engine: media events · Arr history and wanted-state data feed the search pipeline.
- Search engine → Provider registry: query providers · Search fans out to registered subtitle providers uniformly.
- Search engine → Scoring: rank · Candidate subtitles are filtered and scored before download.
- Search engine → Subsync: sync subtitle · Downloaded subtitles are aligned and written back to the media filesystem.
- Subsync → FFmpeg bridge: probe/extract · Alignment depends on ffmpeg/ffprobe audio and media analysis.
- Provider registry → OpenSubtitles: provider · Representative provider implementation behind the registry.
- Provider registry → SubDL: provider · Representative provider implementation behind the registry.
