docker/streams provides building blocks for live views: aggregating many producers into
one JSON-lines response, sharing poll loops between subscribers, fanning out Docker events, and
keeping recent logs and stats in memory.
- Package
kit.getarcane.app/docker/streams- Module
kit.getarcane.app/docker- Reference
- pkg.go.dev
go get kit.getarcane.app/docker@latestPackages
Section titled “Packages”| Package | Purpose |
|---|---|
streams/agg |
JSON-lines fan-in, shared poll loops, per-environment pollers |
streams/bus |
Typed in-process pub/sub for Docker events |
streams/logs |
slog capture into a ring buffer with live subscribers |
streams/stats |
Compact per-container CPU and memory history |
streams/agg
Section titled “streams/agg”Run: fan-in to JSON lines
Section titled “Run: fan-in to JSON lines”agg.Run merges events from several producers, writes each one as a JSON line, and flushes after
each write. It returns when ctx is canceled or encoding fails.
import "kit.getarcane.app/docker/streams/agg"
func handler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/x-ndjson") flusher := w.(http.Flusher)
_ = agg.Run(r.Context(), agg.Config[Event]{ Writer: w, Flush: flusher.Flush, HeartbeatInterval: 15 * time.Second, MakeHeartbeat: func() Event { return Event{Type: "heartbeat"} }, Producers: []agg.Producer[Event]{ func(ctx context.Context, events chan<- Event) { for ev := range watchContainers(ctx) { if !agg.Send(ctx, events, ev) { return } } }, }, })}agg.Send gives up when ctx is done, so a producer can never block forever. Writer and Flush
are required, Buffer must not be negative, and HeartbeatInterval must be positive when
MakeHeartbeat is set. An invalid configuration returns *agg.InvalidConfigError.
Hub: share poll loops
Section titled “Hub: share poll loops”A Hub makes sure only one poll loop runs for each key, however many clients subscribe.
The first subscriber starts the runner, and it stops when the last one leaves. Each subscriber gets
events through a latest-wins mailbox, so a slow client skips to the newest state and never stalls
the others. The zero Hub is ready to use.
var hub agg.Hub[Snapshot]
hub.Subscribe(ctx, envID, func(ctx context.Context, publish func(Snapshot)) { ticker := time.NewTicker(2 * time.Second) defer ticker.Stop() for { publish(poll(ctx, envID)) select { case <-ctx.Done(): return case <-ticker.C: } } }, func(s Snapshot) bool { return send(s) == nil },)Subscribe blocks until ctx is done or deliver returns false. The runner’s context is tied to
the runner, not to any one subscriber. A subscriber that joins late gets the most recent event
straight away.
Reconcilers
Section titled “Reconcilers”ReconcilePollersByKey keeps one poller goroutine for each listed item until ctx is canceled.
It re-checks the list every Interval (default one minute). It restarts a poller when the item’s
Version changes, and stops it when the item leaves the list.
go agg.ReconcilePollersByKey(ctx, agg.PollerConfig[Environment]{ List: listRemoteEnvironments, Key: func(env Environment) string { return env.ID }, Version: func(env Environment) string { return env.URL }, Run: pollEnvironment, // func(ctx context.Context, env Environment) Label: "environments",})Items with an empty key are skipped. A nil Version never restarts a poller.
streams/bus
Section titled “streams/bus”DockerEventBus fans out Docker daemon events by type. Delivery never blocks. A message that
doesn’t fit in a subscriber’s buffer is dropped and reported to the optional Config.OnDrop
callback. Both bus.Config{} and bus.SubscribeOptions{} are valid zero values.
import "kit.getarcane.app/docker/streams/bus"
b := bus.NewDockerEventBus(bus.Config{ OnDrop: func(m events.Message) { slog.Warn("dropped docker event", "type", m.Type, "action", m.Action) },})defer b.Close()
containers, unsubscribe := b.Subscribe(events.ContainerEventType, bus.SubscribeOptions{Buffer: new(64)})defer unsubscribe()
go func() { for msg := range dockerEvents { b.Publish(msg) }}()SubscribeOptions.Buffer is a pointer so that new(0) can request an unbuffered channel. Nil or a
negative value uses the default buffer of 16.
streams/logs
Section titled “streams/logs”Captures slog records into a ring buffer and sends new entries to live subscribers. This is
useful for showing an application’s own logs in its UI.
import "kit.getarcane.app/docker/streams/logs"
broadcaster := logs.New(logs.Config{Capacity: 1000})slog.SetDefault(slog.New(logs.NewSlogHandler(slog.NewJSONHandler(os.Stderr, nil), broadcaster)))
recent := broadcaster.Recent() // oldest firstlive, unsubscribe := broadcaster.Subscribe()defer unsubscribe()Capacity defaults to 1000 entries. SubscriberBuffer defaults to 256; set it to new(0) for
unbuffered subscriber channels. The zero logs.Config{} uses both defaults.
streams/stats
Section titled “streams/stats”Store keeps a bounded history of compact samples for each container. Each sample holds CPU and
memory in tenths of a percent, plus memory bytes.
import "kit.getarcane.app/docker/streams/stats"
store := stats.NewStore(stats.StoreConfig{ Capacity: 60, // samples per container (default 30) TTL: 10 * time.Minute, // evict inactive containers (default 10 minutes) PruneInterval: time.Minute, // minimum time between prune passes (default 1 minute)})
sample := stats.BuildSample(resp) // from a Docker StatsResponsehistory := store.Record(stats.RecordRequest{ ContainerID: containerID, Sample: sample, IncludeHistory: true, // return the history after appending})
payload := stats.StatsStreamPayload{ StatsResponse: resp, StatsHistory: history, CurrentHistorySample: sample,}BuildSample computes CPU as cpuDelta / systemDelta without the Docker CLI’s online-CPU
multiplier, so values stay on a 0–100 scale.
Zero or negative StoreConfig fields use the defaults, and the zero Store is also usable. A zero
RecordRequest.RecordedAt means now. History reads a container’s samples without recording one,
Remove drops a container’s history, and Prune evicts expired histories on demand.