# galpt/cake-stats architecture

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

- Interactive diagram: https://gitdiagram.com/galpt/cake-stats
- Repository: https://github.com/galpt/cake-stats

## Overview

cake-stats is a small Go service with a clear split between data collection, state retention, and HTTP delivery.

At a high level, the runtime looks like this:

- A Linux/OpenWrt host provides CAKE qdisc statistics via `tc -s qdisc`.
- The Go binary polls that command on a fixed interval.
- Parsed snapshots are stored in a server-side ring buffer.
- The same snapshots are published to connected browsers over Server-Sent Events.
- Browsers load a single embedded HTML UI and use JSON endpoints plus the SSE stream to render live charts and history.

#### Main executable and process boundary

The only runtime binary is `cmd/cake-stats/main.go`. It is the application entrypoint and is responsible for:

- parsing CLI flags such as port, host, poll interval, history depth, and version
- configuring logging
- starting the polling pipeline
- starting the HTTP server
- wiring together parser, history, and server packages

This is a classic daemon-style service: one long-running process, no separate worker processes, no database, and no external message broker.

#### Core subsystems

##### 1) Polling and parsing subsystem

`pkg/parser` is the boundary between the operating system and the application.

Its job is to take the raw output from `tc -s qdisc` and convert it into structured CAKE statistics. Based on the README and file structure, this package handles:

- discovery of CAKE qdiscs
- parsing interface/tier/tin data
- aggregation of multi-queue CAKE (`cake_mq`) sub-queues into one logical interface view
- extraction of all CAKE metrics the UI needs, including delay, backlog, packet counts, bytes, drops, marks, and flow counts
- handling diffserv modes and fwmark overrides
- normalizing awkward text cases such as two-word tier names

This is the only place that understands the textual `tc` format. Everything downstream works on typed data.

##### 2) State retention subsystem

`pkg/history` stores recent snapshots in a thread-safe circular buffer.

Its purpose is to preserve time-series data across refreshes or reconnects so the UI can immediately seed graphs without waiting for new samples. The README describes it as:

- a server-side ring buffer
- configurable by retention window
- able to return history per interface

Architecturally, this package is the in-memory state store for the service. It sits between the polling pipeline and the HTTP layer.

##### 3) HTTP and streaming subsystem

`pkg/server` hosts the web UI and API.

It exposes three distinct surfaces:

- `GET /` for the static UI
- `GET /api/stats` for the current snapshot
- `GET /api/history` for the retained ring-buffer history
- `GET /events` for the SSE stream

This package is the delivery boundary for all user-facing data. It likely also owns:

- routing
- request handling
- SSE connection management
- broadcasting updated snapshots to connected clients
- serving the embedded `index.html`

The README makes clear the live updates are push-based using SSE, not WebSockets or polling from the browser. That means the server owns the real-time distribution model, while clients just subscribe to a stream.

##### 4) Types and serialization subsystem

`pkg/types` defines the data model shared across parser, history, and server.

This package is important because it acts as the contract between all parts of the system:

- parser emits typed stats
- history stores typed snapshots
- server serializes typed snapshots to JSON
- the browser consumes the JSON

The presence of `types_easyjson.go` indicates JSON serialization is code-generated with easyjson to reduce reflection and allocation cost. That is a meaningful architectural decision: the wire format is optimized around a stable, generated schema rather than ad hoc marshaling.

##### 5) Utility subsystem

`pkg/util` centralizes low-level string and byte helpers:

- splitting
- trimming
- parsing
- byte/string conversion helpers

This package exists to isolate allocation-heavy or performance-sensitive operations. It is a shared internal foundation used by the parser and probably by other hot paths.

Architecturally, this is a performance boundary: the codebase intentionally keeps all low-level text manipulation in one place so it can be audited and tuned.

##### 6) Logging subsystem

`pkg/log` wraps structured logging setup with zerolog.

This is not a core data path, but it is part of operational architecture:

- compact structured logs
- near-zero allocation logging
- consistent log configuration from the entrypoint

#### End-to-end data flow

The main data flow is:

1. The daemon starts with flags controlling host, port, polling interval, and history retention.
2. A poll loop runs `tc -s qdisc` on the host.
3. `pkg/parser` converts command output into typed per-interface CAKE statistics.
4. The latest snapshot is stored in `pkg/history`.
5. The server pushes the snapshot to SSE clients on `/events`.
6. The browser UI loads `/`, fetches `/api/history` to seed initial graphs, and receives live updates over SSE.
7. The UI updates sparklines and opens a full history modal from the retained time series.

So the system is basically: OS command output -> parser -> in-memory history -> HTTP JSON/SSE -> browser visualization.

#### Web UI boundary

The frontend is not a separate app or build pipeline. It lives inside `pkg/server/index.html`, which suggests the UI is embedded directly into the Go binary.

That means:

- no frontend dependency graph
- no external static asset server
- no runtime build step for the UI
- the server binary ships the UI with it

From an architecture diagram perspective, the browser talks only to the Go server, and the server serves both HTML and live data.

#### Deployment and operating-system integration

The repo also contains deployment artifacts that matter to the system boundary:

- `install.sh` and `uninstall.sh` handle installation and removal
- `etc/init.d/cake-stats` is the OpenWrt service script
- `etc/hotplug.d/iface/99-cake-stats` is an OpenWrt hotplug fallback for interface lifecycle timing
- `verify-openwrt-install.sh` checks router-side installation
- `.github/workflows/build.yml` shows CI builds/releases the static binary

These are not part of runtime logic, but they show how the service is intended to be operated:

- OpenWrt routers via init.d/hotplug integration
- standard Linux hosts via install script and likely systemd support
- single binary deployment with no external services

#### Important architectural boundaries

##### External system boundary
The only real external dependency at runtime is the local Linux networking stack and `tc`/`sch_cake`. The service does not depend on a database, cache, or remote API.

##### Data model boundary
`pkg/types` is the shared schema boundary. It separates parsing concerns from presentation and transport.

##### Performance boundary
`pkg/util`, easyjson-generated code, and the ring buffer are all part of the “keep this cheap on embedded hardware” strategy.

##### Presentation boundary
`pkg/server` is the only package that knows about HTTP, SSE, or HTML. Everything else is headless backend logic.

#### Operational characteristics

A diagram should also reflect these non-functional constraints because they shape the architecture:

- single static binary
- low memory/CPU footprint
- polling-based collection rather than kernel event subscriptions
- real-time delivery via SSE
- embedded/OpenWrt-friendly deployment
- no authentication or HTTPS built in

#### Suggested diagram shape

A faithful architecture diagram would usually show:

- a Linux/OpenWrt host box containing the `cake-stats` process
- inside that process:
  - poller/parser
  - history ring buffer
  - HTTP/SSE server
  - embedded UI assets
- an external “browser” client consuming `/`, `/api/history`, `/api/stats`, and `/events`
- an external “kernel tc/sch_cake” source feeding the poller
- optional deployment/boot integration on OpenWrt via init.d and hotplug scripts

That captures the real structure of this repository: a compact embedded monitoring daemon with one ingestion path, one in-memory state store, and one HTTP delivery surface.

Main entry points: [`cmd/cake-stats/main.go`](https://github.com/galpt/cake-stats/blob/HEAD/cmd/cake-stats/main.go) (cake-stats), [`pkg/server/server.go`](https://github.com/galpt/cake-stats/blob/HEAD/pkg/server/server.go) (Server), [`pkg/parser/parser.go`](https://github.com/galpt/cake-stats/blob/HEAD/pkg/parser/parser.go) (Parser), [`pkg/history/history.go`](https://github.com/galpt/cake-stats/blob/HEAD/pkg/history/history.go) (History)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph "Runtime"
  entrypoint["cake-stats<br/>go main<br/>[main.go]"]
  kernel_tc[("tc qdisc<br/>linux source")]
end

subgraph "Core packages"
  parser["Parser<br/>[parser.go]"]
  history[("History<br/>ring buffer<br/>[history.go]")]
  types["Types<br/>shared schema<br/>[types.go]"]
  easyjson["JSON codegen<br/>generated json<br/>[types_easyjson.go]"]
  util["Util<br/>string helpers<br/>[parse.go]"]
  logpkg["Logging<br/>zerolog setup<br/>[log.go]"]
end

subgraph "Delivery"
  server["Server<br/>http+sse<br/>[server.go]"]
  ui["Embedded UI<br/>html asset<br/>[index.html]"]
  browser(("Browser<br/>client"))
end

subgraph "Ops"
  initd["Init script<br/>openwrt service<br/>[cake-stats]"]
  hotplug["Hotplug hook<br/>openwrt hook<br/>[99-cake-stats]"]
  install["Install<br/>shell deploy<br/>[install.sh]"]
  verify["Verify<br/>shell check"]
  ci["CI build<br/>github actions<br/>[build.yml]"]
end

kernel_tc -->|"tc output"| parser
entrypoint -->|"wires"| parser
entrypoint -->|"stores"| history
entrypoint -->|"starts"| server
entrypoint -->|"configures"| logpkg
parser -->|"emits"| types
parser -->|"uses"| util
history -->|"stores"| types
server -->|"reads history"| history
server -->|"serializes"| types
server -->|"uses"| easyjson
server -->|"serves"| ui
browser -->|"GET /, /api/*, /events"| server
initd -->|"starts"| entrypoint
hotplug -->|"restarts"| entrypoint
install -->|"installs"| initd
verify -->|"checks"| initd
ci -->|"builds"| entrypoint

click entrypoint "https://github.com/galpt/cake-stats/blob/main/cmd/cake-stats/main.go"
click parser "https://github.com/galpt/cake-stats/blob/main/pkg/parser/parser.go"
click history "https://github.com/galpt/cake-stats/blob/main/pkg/history/history.go"
click types "https://github.com/galpt/cake-stats/blob/main/pkg/types/types.go"
click easyjson "https://github.com/galpt/cake-stats/blob/main/pkg/types/types_easyjson.go"
click util "https://github.com/galpt/cake-stats/blob/main/pkg/util/parse.go"
click logpkg "https://github.com/galpt/cake-stats/blob/main/pkg/log/log.go"
click server "https://github.com/galpt/cake-stats/blob/main/pkg/server/server.go"
click ui "https://github.com/galpt/cake-stats/blob/main/pkg/server/index.html"
click initd "https://github.com/galpt/cake-stats/blob/main/etc/init.d/cake-stats"
click hotplug "https://github.com/galpt/cake-stats/blob/main/etc/hotplug.d/iface/99-cake-stats"
click install "https://github.com/galpt/cake-stats/blob/main/install.sh"
click verify "https://github.com/galpt/cake-stats/blob/main/verify-openwrt-install.sh"
click ci "https://github.com/galpt/cake-stats/blob/main/.github/workflows/build.yml"

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 entrypoint,kernel_tc toneBlue
class parser,history,types,easyjson,util,logpkg toneAmber
class server,ui,browser toneMint
class initd,hotplug,install,verify,ci toneRose
```

## Components

### Runtime

Main daemon process and its data flow

- [cake-stats](https://github.com/galpt/cake-stats/blob/HEAD/cmd/cake-stats/main.go): go main · Daemon entrypoint: flags, logging, poll loop, and server wiring · `cmd/cake-stats/main.go`
- **tc qdisc**: linux source · CAKE statistics source exposed by the host networking stack

### Core packages

Parsing, state retention, shared schema, and helpers

- [Parser](https://github.com/galpt/cake-stats/blob/HEAD/pkg/parser/parser.go): tc parser · Parses tc output into structured CAKE stats · `pkg/parser/parser.go`
- [History](https://github.com/galpt/cake-stats/blob/HEAD/pkg/history/history.go): ring buffer · Thread-safe in-memory retention of recent snapshots · `pkg/history/history.go`
- [Types](https://github.com/galpt/cake-stats/blob/HEAD/pkg/types/types.go): shared schema · Shared data model used across parser, history, and server · `pkg/types/types.go`
- [JSON codegen](https://github.com/galpt/cake-stats/blob/HEAD/pkg/types/types_easyjson.go): generated json · Generated serialization for the shared types · `pkg/types/types_easyjson.go`
- [Util](https://github.com/galpt/cake-stats/blob/HEAD/pkg/util/parse.go): string helpers · Low-level parsing and text helpers for hot paths · `pkg/util/parse.go`
- [Logging](https://github.com/galpt/cake-stats/blob/HEAD/pkg/log/log.go): zerolog setup · Structured logging configuration and wrapper · `pkg/log/log.go`

### Delivery

HTTP, SSE, and embedded browser UI

- [Server](https://github.com/galpt/cake-stats/blob/HEAD/pkg/server/server.go): http+sse · Hosts HTML, JSON endpoints, and SSE broadcasting · `pkg/server/server.go`
- [Embedded UI](https://github.com/galpt/cake-stats/blob/HEAD/pkg/server/index.html): html asset · Single embedded page served by the Go binary · `pkg/server/index.html`
- **Browser**: client · Consumes HTML, JSON history, current stats, and SSE updates

### Ops

Installation and OpenWrt integration

- [Init script](https://github.com/galpt/cake-stats/blob/HEAD/etc/init.d/cake-stats): openwrt service · OpenWrt service definition for boot-time startup · `etc/init.d/cake-stats`
- [Hotplug hook](https://github.com/galpt/cake-stats/blob/HEAD/etc/hotplug.d/iface/99-cake-stats): openwrt hook · Interface lifecycle fallback for timing-sensitive startup · `etc/hotplug.d/iface/99-cake-stats`
- [Install](https://github.com/galpt/cake-stats/blob/HEAD/install.sh): shell deploy · Installation and removal scripts for local deployment · `install.sh`
- [Verify](https://github.com/galpt/cake-stats/blob/HEAD/verify-openwrt-install.sh): shell check · OpenWrt installation verification script · `verify-openwrt-install.sh`
- [CI build](https://github.com/galpt/cake-stats/blob/HEAD/.github/workflows/build.yml): github actions · Automated build and release workflow · `.github/workflows/build.yml`

## Connections

- tc qdisc → Parser: tc output · Poller reads qdisc stats from the host and feeds them into the parser
- cake-stats → Parser: wires · Main process initializes parsing pipeline
- cake-stats → History: stores · Main process provides the retention buffer
- cake-stats → Server: starts · Main process launches the HTTP/SSE server
- cake-stats → Logging: configures · Main process sets up logging
- Parser → Types: emits · Parsed stats are represented using the shared schema
- Parser → Util: uses · Parser relies on low-level text helpers
- History → Types: stores · Ring buffer retains typed snapshots
- Server → History: reads history · HTTP API serves retained snapshots
- Server → Types: serializes · Server marshals typed snapshots to JSON
- Server → JSON codegen: uses · Generated JSON helpers support efficient encoding
- Server → Embedded UI: serves · Embedded HTML is returned from the root endpoint
- Browser → Server: GET /, /api/*, /events · Browser loads UI, fetches data, and subscribes to SSE
- Init script → cake-stats: starts · OpenWrt boot service launches the daemon
- Hotplug hook → cake-stats: restarts · Interface hook helps recover or delay startup
- Install → Init script: installs · Deployment script places the service integration
- Verify → Init script: checks · Verification script validates router-side setup
- CI build → cake-stats: builds · Workflow produces the static Go binary
