Skip to content

Distribution

Internals of the Distribution domain. For the public API, see Distribution API.

The domain keeps a registry of the CDN nodes an organization runs (Castis Streamer, cproxy cache nodes, Castis ELB load balancers), turns DB rows into cproxy configuration, provisions node software over SSH, and drives the shared colorbars test-signal broadcaster. To run it locally, see Distribution: run locally. The PlayoutAdmin screens are in PlayoutAdmin: distribution, and the org and workspace auth model in Playout workspace auth.

Domain structure

domain/distribution/
├── config.go        Config + ConfigFromEnv(): COLORBARS_HOST, COLORBARS_PORT, INSTALLER_ASSETS_DIR
├── models.go        Streamer, Cache, SLB, CacheOriginKey, CacheOriginStreamer, StreamerWorkspaceAccess
├── helper.go        ApplyNodeFilters() (status, search on name/host)
├── validation.go    ParseID()
├── handlers/
│   ├── handler.go                 Handler, org scoping helpers (inOrg, cacheInOrg, streamerInOrg)
│   ├── handler_streamer.go        streamer CRUD, ping, proxy, ProbeUDP, ProbeStreamFormat
│   ├── handler_streamer_access.go GET/PUT /streamers/:id/access
│   ├── handler_cache.go           cache CRUD, ping, proxy, SwitchOrigin, PutOrigins
│   ├── handler_cache_origins.go   origin keys, streamer assignment, keys/sync, topology queries
│   ├── handler_cache_relays.go    external relays CRUD + relays/sync
│   ├── handler_slb.go             SLB CRUD, ping, proxy
│   ├── handler_install.go         SSH install / status / uninstall (streamer and cache)
│   └── handler_colorbars.go       colorbars controller passthrough
├── relay/           external relay naming, expansion, reconciler, warmer, SSRF checks
└── routes/          wire.go (Setup) + routes.go (registerRoutes)

pkg/cdn/streamer     Castis Streamer HTTP client (was pkg/StreamerClient)
pkg/cdn/cproxy       cproxy HTTP client, incl. relay_origin.go (additive relay writer)
pkg/cdn/elb          Castis ELB HTTP client
pkg/cdn/colorbar     colorbars controller client
pkg/installer        SSH-push provisioning, profile-driven

Mounted by distributionroutes.Setup(v1, …) in routes_platform.go, so every route is under /api/v1. The relay reconciler and warmer are started from infra.go.

Data model

erDiagram
    Streamer {
        uint id
        string organization_id
        string name "unique per org"
        string host
        string public_host
        int http_port
        int api_port
        bool has_gpu
        string role "ingest | cproxy"
        string access_mode "all_workspaces | selected"
        string status
        string install_status
    }
    StreamerWorkspaceAccess {
        uint streamer_id
        string workspace_id
    }
    Cache {
        uint id
        string organization_id
        string name "unique per org"
        string host
        string public_host
        string public_base_url
        bool relay_default "max one per org"
        int http_port
        int api_port
        string status
        string install_status
    }
    SLB {
        uint id
        string organization_id
        string name
        string host
        int proxy_port
        int api_port
        string status
    }
    CacheOriginKey {
        uint id
        uint cache_id
        string origin_key
        string url_pattern
        string source_kind "streamer | external"
        string path_prefix "relays"
        string external_url "relays"
        bool disabled
        string last_sync_status
    }
    CacheOriginStreamer {
        uint id
        uint origin_key_id
        uint streamer_id
        int priority
    }
    ChannelOrigin {
        uint channel_id
        uint streamer_id
        string ingest_mode
    }
    Streamer ||--o{ StreamerWorkspaceAccess : "grants"
    Streamer ||--o{ ChannelOrigin : "hosts"
    Cache ||--o{ CacheOriginKey : "has keys"
    CacheOriginKey ||--o{ CacheOriginStreamer : "origin urls"
    Streamer ||--o{ CacheOriginStreamer : "assigned to"

Tables: streamers, caches, slbs, cache_origin_keys, cache_origin_streamers, streamer_workspace_access (migration 2026-09-30_streamer_workspace_access.sql). cache_origin_keys and cache_origin_streamers carry no organization_id; handlers scope them through the parent cache. Install fields (install_status, install_stage, install_error, install_started_at) are on both streamers and caches and share one InstallStatus type.

Colorbars streams are not persisted: they live in the colorbars container's memory and reset on restart.

Streamer role

role is ingest (default, full origin streamer with UDP/multicast ingest) or cproxy (cache/shield only). It is enforced: playback's CreateChannel rejects a UDP-mode origin on a cproxy-role streamer, recorded per origin in that origin's failures[] entry rather than as an upfront validation error. A wrong role is a common cause of "channel created but this origin failed" when the node itself is healthy.

Workspace access

Streamers are org infrastructure; the org decides which workspaces may put channels on each one.

  • streamers.access_mode column default is all_workspaces, so rows created before access control keep working. POST /streamers forces selected with no grants; PUT /streamers/:id can't change the mode.
  • Grants live in streamer_workspace_access (streamer_id, workspace_id). They are kept while the mode is all_workspaces and apply only in selected.
  • Playback reads the same two tables: GET /api/v1/playback/:workspaceId/streamers (streamersForWorkspace) is the workspace picker, and CreateChannel rejects a streamer the workspace can't use (400). Revoking a grant doesn't touch running channels.
  • Every org role (incl. ORG_MEMBER) has org:distribution:view, so any member can list the org's nodes; only ORG_OWNER and ORG_ADMIN have org:distribution:manage (pkg/seed/roles.go).

Auth and org scoping

/distribution/:orgId runs behind ProtectedRS256, then per route RequireOrgPermission (org:distribution:view for GETs and pings, org:distribution:manage for everything else, incl. probes and every */proxy/*). OrgHasPermission requires :orgId == claims.Org.OrgID, so a foreign org ID is a 403 with {message}, not a 404. Inside the org, inOrg() filters by organization_id, so another org's node ID is a 404. Colorbars sit at /distribution/colorbars (outside :orgId) behind RequirePlatformPermission(platform:org:manage), because they drive one controller shared by every org.

Routes not in the partner reference

The partner distribution.yaml documents node registry, workspace access, probes, topology, origin keys and relays. These routes exist in routes.go but are left out of it, because they are operator tools rather than an integration surface:

Route Permission Why it is internal
ALL /streamers/:id/proxy/*, ALL /caches/:id/proxy/*, ALL /slbs/:id/proxy/* org:distribution:manage Forwards any method and path verbatim to the node's control API and returns the node's raw body (no envelope). The node APIs are vendor APIs with no stability contract.
POST /streamers/:id/install, GET /streamers/:id/install/status, DELETE /streamers/:id/install manage / view / manage SSH-push provisioning with SSH credentials in the body. See Installation.
POST /caches/:id/install, GET /caches/:id/install/status manage / view Same, for cproxy.
POST /caches/:id/origins/:originKey/switch org:distribution:manage Legacy: hot-swap URLs on an existing cproxy key, then purge. Superseded by origin keys + keys/sync.
PUT /caches/:id/origins org:distribution:manage Legacy: pass a raw cproxy origins array straight to the node. Bypasses the DB and drops relay origins.
/distribution/colorbars/* (7 routes) platform:org:manage Platform-only test-signal broadcaster. See Colorbars.

Not routed at all: DeleteStreamer (handler exists; waits for a check that no channel_origins reference the node) and UninstallCache (DELETE /caches/:id/install is commented out in routes.go with no reason given; the handler is complete). Both need a decision.

Node clients

All node traffic goes CoreAPI → node control API (http://{host}:{apiPort}/api/...), with a package-level http.Client (10 s timeout) in each client package.

  • Streamer (pkg/cdn/streamer, formerly pkg/StreamerClient): CreateStream, DeleteStream, GetStreams, GetTraffic, BuildStreamID ("BBC World" → bbc_world.stream), BuildPayload (merges ingest URL, ingest config and transcoders into one stream body), PlaybackURL, ProxyRequest. readResponse wraps a non-JSON upstream body (for example an HTML error page) as a JSON string, so the shape stays consistent. Every CreateStream and ProxyRequest logs method, URL, status and body with the standard log package, with no level gating. Full reference: StreamerClient.
  • cproxy (pkg/cdn/cproxy): ProxyRequest, PutOriginURLs, PutOrigins, PurgeOrigin, PurgeContent, GetTraffic, plus the relay writer in relay_origin.go. See CProxyClient.
  • ELB (pkg/cdn/elb): ProxyRequest, GetVersion, GetTraffic. ELB has no /api/ping; ping uses GET /api/version. cproxy also has no /api/ping and is pinged with /api/version.
  • Colorbars (pkg/cdn/colorbar): the colorbars Fiber API.

Topology

CoreAPI
  ├── streamers  → Castis Streamer control API (:apiPort)   probe, proxy, channel origins
  ├── caches     → cproxy control API (:apiPort)            keys/sync, relays, proxy
  ├── slbs       → Castis ELB API (:apiPort, e.g. 8100)     ping, proxy
  ├── colorbars  → COLORBARS_HOST:COLORBARS_PORT            stream lifecycle
  └── SSH :22    → any node being installed (installer only)

viewer → ELB proxyPort (e.g. 8090) → cproxy httpPort → streamer httpPort
colorbars → UDP multicast (e.g. udp://239.0.0.8:4444) → every streamer that joins the group

In local compose the CDN nodes sit on playtelly_internal, and colorbars plus streamers also on playtelly_cdn_net (172.28.0.0/16) so multicast reaches every streamer.

cproxy origin keys and sync

Origin keys are named routing slots on a cproxy node (food, ads, live-ch1): urlPattern, optional rewriter, TTL and an ordered list of streamers. The DB is the source of truth; POST /caches/:id/keys/sync rebuilds the full origins array and sends it with PUT /api/config/origins (cproxy v1.1.5.rc1 or later; earlier versions return 404).

buildOriginsPayload fills fixed defaults for every key: ttlRules (.ts .m4s .mp4 .m4a .aac 30 s, .m3u8 .mpd 500 ms), healthCheck {5s, 1s}, failoverResponses ["404","5xx"], retryCount 1, balancingPolicy first-active, memCacheConfigId mem-cache. Origin URLs are http://<streamer.host>:<streamer.httpPort>. Keys with no streamer in the caller's org are skipped; if none is left the sync refuses with 400 rather than PUT an empty array. A sync is refused with 409 when the cache has relay rows (soft-deleted ones included), because a full replace would drop them.

cproxy boots with a placeholder origin ^/__placeholder__/.*$; the first sync replaces it.

Legacy routes still mounted: SwitchOrigin (GET config → replace one key's originUrls → PUT full array → purge, non-fatal if purge fails) and PutOrigins (caller owns the full array).

cproxy bind-mount workaround

PUT /api/config/origins backs up cproxy.yml by renaming it, which a Docker bind mount blocks (device or resource busy), and the whole PUT rolls back. Mount the config at a temp path and copy it at start:

volumes:
  - ./cdn/cproxy-bkk-1/cproxy.yml:/tmp/cproxy-init.yml
command: bash -c "cp /tmp/cproxy-init.yml /castis/bin/cproxy/cproxy.yml && ./cproxy"

External relays

A relay row (cache_origin_keys.source_kind = 'external') makes a cproxy node serve a third-party HTTP(S) stream under its own path. The partner-facing behaviour is in External relay channels and the Distribution API; the implementation is the relay package:

  • Expand turns one row into up to three cproxy origins: <key>-master (the pinned entry playlist, long TTL so every viewer shares one upstream session, needed for Wowza-style feeds that hand out a session per playlist request), <key>-seg (segments, DefaultSegmentTTL 60 s) and <key> (everything else, ttlNoCache).
  • Additive writes. The writer only adds, changes, reorders or removes origins whose key starts with relay- (cproxy.ManagedKeyPrefix). Origins the DB has never heard of are left alone, so two environments sharing a node can't delete each other's relays. MaxPerNode is 50.
  • Reconciler (relay.Start, every RELAY_RECONCILE_INTERVAL_SECONDS, default 60, minimum 10). The node forgets runtime-added origins on restart (the deployment copies its ConfigMap over cproxy.yml) and any full-replace PUT drops them, so the desired state is re-pushed. Each cache is locked with a Postgres advisory lock (8_420_200 + cacheId; ticketing schedulers use 8_420_001-005, livethumb 8_420_101), so replicas don't race; a concurrent request gets ErrBusy in sync.error. Rows that fail validation are marked error and left off the node.
  • SSRF guard (ssrf.go). Every address the upstream host resolves to must be public (no loopback, private, link-local, CGNAT, multicast or metadata). RELAY_ALLOWED_HOSTS optionally restricts hosts to suffixes and should be set in production. The check is repeated on every reconcile and at dial time (CheckDialAddress) to close DNS rebinding. RELAY_ALLOW_PRIVATE=true disables the address check, for local testing only.
  • Warmer (relay.StartWarmer, off unless RELAY_WARM_ENABLED=true, every RELAY_WARM_INTERVAL_SECONDS, default 1). Plays one silent viewer per relay through the cproxy so the entry playlist, media playlist and newest 4 segments stay cached. Per relay opt-out: disable_warm.
  • Naming (names.go): relay channels are served at /<slug>/…; RELAY_INSTANCE prefixes names when two environments share a node.
  • Default node: relay.DefaultCache picks the org's relay_default cache, else its only cache; with several and none marked, relay channel creation fails with ErrNoRelayCache.
  • UpdateCache calls relay.RefreshChannelURLs, so stored relay channel URLs follow a node address change.

Installation: streamer and cproxy

SSH-push provisioning of a Castis binary onto a blank Linux node: no agent, credentials supplied per request and never written to the DB. One profile-driven Install() / Uninstall() in pkg/installer handles both, parameterized by a BinaryProfile (StreamerProfile, CproxyProfile): vendor directory, binary path in the tarball, install directory, lib subdirectories, OS dependencies, config/tarball/template file names and start environment.

Request body (installer.InstallRequest): sshHost, sshPort (default 22), sshUser, sshPassword or sshPrivateKey (pasted PEM), httpPort, apiPort, hasGpu. Uninstall takes the same SSH fields and ?purge=true|false.

SSH passwords are written to the CoreAPI log

pkg/installer/debug.go has DebugLogCreds = true, and Install() and Uninstall() call debugLogRequest, which logs sshHost, sshPort, sshUser and the plain sshPassword on every call. Set it to false or delete the file before anyone installs a node outside a test setup, and treat passwords already used as exposed in the log store.

Flow: the handler returns 202 {"status":"install_started"} and runs the install in a goroutine, writing each stage to the row. A second install while pending or installing is refused with 409. installStatus: not_installed → pending → installing → installed | failed. Reinstall uses the same route and is idempotent: dependency install is skipped when rpm -q finds every package, and starting stops a running process first.

Stages: connecting → installing_dependencies → uploading_tarball → uploading_config → uploading_media (streamer only, sample media) → extracting → configuring_libs (only when the profile has LibSubdirs; cproxy has none) → starting → installed.

Assets come from INSTALLER_ASSETS_DIR: streamer.tar.gz, streamer.yml.tmpl, kitchen.mp4, cproxy.tar.gz, cproxy.yml.tmpl. Lessons kept in the profiles and commands:

  • epel-release is installed in its own dnf install before the rest (zeromq needs EPEL), with --allowerasing (cproxy conflicts with a preinstalled curl-minimal) and --setopt=timeout=10 --setopt=minrate=50000 so slow mirrors are dropped.
  • Only the parent lib/ directory is created before mv, or mv nests lib/common/common/ and ldconfig misses the libraries.
  • The start command uses setsid and Session.Start() with a non-blocking Wait() (runCommandNoWait), because CombinedOutput() hangs on a backgrounded nohup … & disown process.
  • The streamer tarball extracts to streamer-latest.el9.x86_64.dir/{bin,lib,doc} with the binary named streamer-latest.el9.x86_64; extraction mirrors the original Dockerfile's mv sequence.

ELB installation isn't built; it would be a third BinaryProfile with no new orchestration code.

UDP probes

POST /streamers/:id/probe creates a temporary stream probe_<group>_<port>.stream with {"url":"udp://group:port"} on the streamer, polls GET /api/streams/<id> every second for up to 6 s, deletes it, and returns detected: true once the status is Running (Waiting means the socket is open but no data arrived). PlayoutAdmin's "Check signal" button uses it.

POST /streamers/:id/probe-format is a separate route so the probe's binary contract stays stable. It creates a pass-through stream (no transcoders, so the SPS describes the source, not our output) probefmt_…, waits up to 10 s for a demuxed video representation, decodes the H.264 SPS with pkg/h264sps, and recommends whether the deinterlace and format filter chain (weave, format, bwdif, hwupload_cuda) is needed. HEVC is detected but not decoded. With ingestPresetId the result is written to ingest_presets.last_probe_result / last_probed_at with a raw table update (importing domain/playback would be a cycle), scoped to the org.

Colorbars

The colorbars container is a Go Fiber app that runs one ffmpeg process per stream, each sending SMPTE colorbars and a 1 kHz tone as MPEG-TS over UDP multicast. Multicast lets one send reach every streamer that joins the group.

  • Each stream needs a unique port: the Castis streamer binds on the port when it joins a group, so two streams on one port (even different groups) mix. The controller returns 409 for a used port.
  • Lifecycle: create (idle in memory) → start (spawns ffmpeg to udp://239.x.x.x:PORT?pkt_size=1316&localaddr=0.0.0.0&ttl=5) → stop (kills ffmpeg, keeps the stream) → delete; PATCH updates config and hot-restarts a running stream.
  • CoreAPI routes: GET /status, POST /streams, PATCH /streams/:streamId, POST /streams/:streamId/start, POST /streams/:streamId/stop, DELETE /streams/:streamId, ALL /proxy/*, all under /api/v1/distribution/colorbars, platform-only.
  • In local compose the controller also serves its own UI on port 9999.

Environment variables

Variable Default Used for
COLORBARS_HOST colorbars Colorbars controller host
COLORBARS_PORT 9999 Colorbars controller port
INSTALLER_ASSETS_DIR /castis/installer-assets Tarballs, config templates and sample media for SSH installs (bind-mounted)
RELAY_RECONCILER_ENABLED on false stops the relay reconciler (emergency switch)
RELAY_RECONCILE_INTERVAL_SECONDS 60 Reconcile interval, minimum 10
RELAY_ALLOWED_HOSTS unset Comma-separated allowed upstream host suffixes; set in production
RELAY_ALLOW_PRIVATE unset true allows private upstream addresses (local testing only)
RELAY_WARM_ENABLED off true starts the relay cache warmer
RELAY_WARM_INTERVAL_SECONDS 1 Warmer interval
RELAY_INSTANCE unset Prefix for relay names when environments share a node

Seeding

pkg/seed/streamer.go, cache.go and slb.go seed the local compose nodes on every boot, owned by the platform organization (pdb.PlatformOrgID). Rows with the same name and no organization are adopted into the platform org. An existing streamer row has public_host, ports and has_gpu refreshed and is marked installed if it was not_installed; new rows are created. Seeded nodes: streamers streamer-bkk and streamer-ntb, cache cproxy-bkk-1, SLB elb-bkk (port values are in the seed files). See Seed package.

Installation test nodes (compose service node_x, container streamer_x) are not seeded: they are blank Rocky 9 containers, registered by hand, and one often hosts a streamer and a cproxy on different port pairs.

Known gaps

  • DeleteStreamer and UninstallCache are implemented but not routed (see above).
  • DebugLogCreds = true logs SSH passwords (see the warning above).
  • PUT on nodes uses GORM struct updates, so zero values ("", 0, false) can't be written: publicHost can't be cleared and hasGpu can't go back to false. The same body can also set installStatus and status, which should be server-owned.
  • ApplyNodeFilters uses LIKE, so search is case-sensitive on Postgres.
  • No GSLB management yet.

Change history

Internal changes to the domain, newest first. Partner-visible API changes are in the Distribution API changelog.

2026-11-16

Docs split into partner reference and internals

The old api/distribution/index.md and its changelog mixed partner reference with internals. The internals, the operator-only routes (proxy, install, colorbars, legacy origin switch/replace) and this change history moved here. The partner distribution.yaml now lists only the routes an integrator calls. No code changes.

2026-10-06

External relays

relay package, handler_cache_relays.go and pkg/cdn/cproxy/relay_origin.go added; new cache_origin_keys relay columns and caches.public_base_url / relay_default. Reconciler always on, warmer opt-in. See External relays.

2026-10-01

Org-scoped auth and per-workspace streamer access

  • Routes moved to /distribution/:orgId/… with ProtectedRS256 + RequireOrgPermission (colorbars: platform only).
  • New streamers.access_mode (all_workspaces default, selected for API-created) and streamer_workspace_access; GET/PUT /streamers/:id/access.
  • Workspace picker moved to GET /playback/:workspaceId/streamers; CreateChannel enforces it.
  • Migration: CoreAPI/migration/2026-09-30_streamer_workspace_access.sql.

See Playout workspace auth.

2026-08-05

Signal-format probe

ProbeStreamFormat and pkg/h264sps added. See UDP probes.

2026-08-03

Documentation audit — corrections, no code changes

Cross-checked index.md against the actual handler code and routes.go. Three corrections made, no runtime behavior changed:

  • Streamer.Role ("ingest" | "cproxy") was missing from the ER diagram and had no narrative section at all, despite being actively enforced (CreateChannel in the playback domain rejects UDP-mode origins on cproxy-role streamers). Added a "Streamer Role" section and the field to the ER diagram.
  • handler_cache_origins.go (~400 lines, 9 handlers — origin-key CRUD
  • streamer topology queries) was missing from the "Domain Structure" file tree, even though its functionality was already documented narratively elsewhere on the page. Added to the tree.
  • DELETE /distribution/caches/:id/install was documented as live ("mirrors the streamer routes exactly") but is commented out in routes.go. UninstallCache itself is fully implemented — this is either a forgotten doc update after disabling the route, or the route was disabled by accident. Flagged as a decision item rather than silently re-enabled or silently left wrong.

Also added Cache.PublicHost/SLB.PublicHost to the ER diagram (present on the model, previously undocumented on those two entities — Streamer.PublicHost was already documented via playout/distribution.md's field list).

2026-07-01

Bug fixes — streamer installer post-generalization

Several bugs surfaced after the BinaryProfile refactor, all fixed in this session.

Missing OS dependencies in StreamerProfile

StreamerProfile.OSDependencies only contained "epel-release" — the full package list (libunwind, libicu, zeromq, harfbuzz, fribidi, fontconfig, freetype, etc.) was left behind as a comment stub when the old hardcoded streamer-specific Install() was replaced by the generic profile-driven version. The installer would complete without error (dnf installed only epel-release and returned 0) but the streamer binary would fail to start with error while loading shared libraries: libunwind.so.8.

Fix: restore the full package list to StreamerProfile.OSDependencies.

epel-release must be installed before the rest

Some packages (zeromq in particular) are only available via EPEL repos. Installing them in a single dnf install call alongside epel-release fails because dnf resolves the full package list before installing anything — EPEL repos aren't registered yet when it tries to resolve zeromq.

Fix: split installing_dependencies into two sequential dnf install calls — first epel-release alone, then the remaining packages.

Double-nesting of lib/ subdirectories during extraction

The generic moveLibsCmd loop in install.go did:

mkdir -p /castis/bin/streamer/lib/common && mv "$SRC"/lib/common /castis/bin/streamer/lib/common
mv with a pre-existing destination directory moves the source into it rather than renaming it, producing lib/common/common/ instead of lib/common/. The .so files were one level deeper than ldconfig expected, so ldconfig -p | grep libsrt returned nothing even though the files were on disk.

Fix: only pre-create the parent lib/ directory, not the subdirs — let mv rename them cleanly:

mkdir -p /castis/bin/streamer/lib && mv "$SRC"/lib/common /castis/bin/streamer/lib/common

rpm -q pre-check added to skip dnf on already-provisioned nodes

Reinstall was always re-running the full dnf install even when all packages were already present, causing 30–90s delays waiting on mirror metadata. Added a fast rpm -q check before running dnf — if all packages are already installed, the installing_dependencies stage completes instantly with no network traffic.

dnf mirror timeout flags added

Added --setopt=timeout=10 --setopt=minrate=50000 to both dnf calls so slow/bad mirrors are abandoned after 10s (down from 30s default) rather than blocking the install for minutes per mirror timeout.

s_id vs sid column name — duplicate column from two migration paths

The channels table ended up with both s_id and sid columns after adding gorm:"column:sid" to domain/playback/models.go. Root cause: pkg/db/migrate.go contained a duplicate Channel struct (without the column tag) that ran first via RunMigrations(), creating s_id. Then RunMigrationMain() ran with the fixed model, adding sid. Two migration paths, two struct definitions, two columns, inserts failing with null value in column "s_id".

Fix: remove Channel, ChannelOrigin, and Streamer from RunMigrations() in pkg/db/migrate.go and delete their local struct definitions — these are now exclusively managed by RunMigrationMain() via RegisterModels() using the real domain model imports. No more duplication, no more drift risk.

ch.sid column reference in raw SQL

GetStreamerChannels used ch.sid in a raw SQL query but the DB column was s_id (GORM's auto-naming for all-caps SID field). Fixed as part of the column rename above — now ch.sid matches the actual column name after the migration cleanup.

GORM all-caps field naming behavior documented

GORM's NamingStrategy splits consecutive uppercase letters: SID → s_id, CID → c_id. Only trailing ID is special-cased (e.g. UserID → user_id). Standalone acronym fields need explicit gorm:"column:..." tags to control the output — SID int \gorm:"column:sid"`renders assid, nots_id`.

2026-06-30 (installer generalized)

Installer generalized to support cproxy — BinaryProfile introduced

pkg/installer's Install()/Uninstall() are no longer streamer-specific. A new BinaryProfile struct parameterizes everything binary-specific (vendor tarball layout, OS dependencies, lib paths, start command), so the same SSH/SFTP orchestration now drives installation of both Castis Streamer and cproxy. StreamerProfile and CproxyProfile are the two profiles defined today; ELB/GSLB are the natural next additions following the same pattern.

New routes (cache/cproxy side, mirroring the existing streamer routes): - POST /caches/:id/install — start install (async, 202) - GET /caches/:id/install/status — poll current stage/status - DELETE /caches/:id/install?purge=true|false — uninstall

New Cache fields: installStatus, installStage, installError, installStartedAt — same shape as Streamer's, reusing the existing package-level InstallStatus type/consts (no new enum).

BinaryProfile shape:

type BinaryProfile struct {
    Name             string
    VendorDirName    string
    BinaryInTar      string
    InstallDir       string
    LibSubdirs       []string          // nil → configuring_libs stage is skipped entirely
    OSDependencies   []string
    ConfigFilename   string
    TarballFilename  string
    TemplateFilename string
    StartEnv         map[string]string // nil → no env vars on start command
}

Install() conditionally skips two stages based on the profile: uploading_media (streamer-only — cproxy has no bundled sample asset) and configuring_libs (skipped whenever len(profile.LibSubdirs) == 0 — cproxy's tarball has no lib/ directory at all, confirmed via tar -tzvf, so there's nothing to ldconfig).

Uninstall() signature changed — now takes a profile BinaryProfile as a third argument so it knows the correct binary path/install directory to stop and (optionally) purge. Both UninstallStreamer and the new UninstallCache call it with their respective profile.

Dependency install fix: the generic installing_dependencies stage was initially missing --allowerasing on the dnf install command (present in the original streamer-specific version, dropped during generalization). Without it, installing cproxy's dependency list failed against a pre-existing curl-minimal package already present on the test node (problem with installed package curl...) — dnf refuses to swap a conflicting package without explicit permission. Fixed by adding --allowerasing back to the shared depsCmd construction, which is harmless for streamer's dependency list too (only matters when an actual conflict exists).

Test fixture renamed: the blank test node's compose service key changed from streamer_x to node_x to reflect that it now hosts both a streamer and a cproxy install simultaneously on different ports — container_name remains streamer_x for now (cosmetic mismatch, not yet cleaned up).

See pkg/installer for full documentation, including the BinaryProfile reference and updated stage lists per profile.

2026-06-30

Streamer SSH-push installer added

New pkg/installer package and handler_install.go in the distribution domain. Provisions a Castis Streamer binary onto a blank Linux node over SSH — no agent, no pre-existing software required on the target beyond SSH access.

New routes: - POST /streamers/:id/install — start install (async, returns 202 immediately) - GET /streamers/:id/install/status — poll current stage/status - DELETE /streamers/:id/install?purge=true|false — uninstall, optionally wiping data

New Streamer fields: installStatus, installStage, installError, installStartedAt. No new table — columns added to the existing streamers table via AutoMigrate.

SSH credentials are never persisted. Every install/uninstall call requires sshHost/sshUser/sshPassword or sshPrivateKey fresh in the request body — read once for the duration of the call, then discarded.

Install stages: connecting → installing_dependencies → uploading_tarball → uploading_config → uploading_media → extracting → configuring_libs → starting → installed

Asset layout: INSTALLER_ASSETS_DIR (default /castis/installer-assets, bind-mounted, sibling to the CoreAPI repo) holds streamer.tar.gz, streamer.yml.tmpl, kitchen.mp4.

Known issue resolved during build-out: the starting stage originally hung indefinitely — Session.CombinedOutput() in golang.org/x/crypto/ssh blocks until all inherited file descriptors close, which a backgrounded nohup ... & disown process doesn't fully release even with stdin redirected to /dev/null. Fixed by switching to Session.Start() + a non-blocking Wait() reaper (runCommandNoWait in pkg/installer/ssh.go), combined with setsid on the remote command for full session detachment.

Tarball layout note: the vendor tarball extracts to streamer-latest.el9.x86_64.dir/{bin,lib,doc}/..., with the binary itself named streamer-latest.el9.x86_64 rather than streamer — the extraction stage now mirrors the original Dockerfile's mv sequence move-for-move instead of assuming a generic --strip-components depth.

See pkg/installer for full documentation.

2026-06-26

Cache origin key management added

Two new tables: cache_origin_keys, cache_origin_streamers.

Replaces the manual PUT /caches/:id/origins raw-JSON workflow with a DB-backed CRUD API. DB is now source of truth for cproxy origins — cproxy config is derived from DB and pushed on demand.

New routes: - GET/POST /caches/:id/keys — list/create origin keys - PUT/DELETE /caches/:id/keys/:keyId — update/delete a key - POST /caches/:id/keys/:keyId/streamers — assign streamer to a key's origin-urls - DELETE /caches/:id/keys/:keyId/streamers/:streamerId — remove streamer from key - POST /caches/:id/keys/sync — push full DB state to cproxy via PUT /api/config/origins

New topology routes: - GET /streamers/:id/channels — channels hosted on this streamer (queries channel_origins) - GET /streamers/:id/caches — cproxy origin keys this streamer is assigned to

cproxy boot config: starts with placeholder origin ^/__placeholder__/.*$ that matches no real traffic. First sync replaces it entirely.

Port note: buildOriginsPayload uses streamer.Host (Docker internal DNS) with internal port 18080. streamer.HTTPPort is the host-mapped port for browser playback and should NOT be used for cproxy→streamer internal URLs.

2026-06-24

cproxy origin management upgraded to v1.1.5 API

PutOriginURLs in pkg/CProxyClient rewritten to use PUT /api/config/origins (cproxy v1.1.5+) instead of PATCH /api/config.

Old flow (v1.1.1):

PATCH /api/config → { origins: [{ key, originUrls }] }
Could only modify URLs on existing keys. New keys required SSH + yml edit + restart.

New flow (v1.1.5+):

GET /api/config → extract origins array
modify target key's originUrls
PUT /api/config/origins → full array replace
Preserves all fields (ttlRules, healthCheck, retryCount, failoverResponses) that were silently dropped by the old PATCH approach. Persists to disk automatically — survives container restarts.

Version requirement: cproxy v1.1.5.rc1 or later. Earlier versions return 404 for PUT /api/config/origins.

2026-06-24

PutOrigins handler added

PUT /caches/:id/origins added to handler_cache.go.

Accepts the full desired origins array and pushes it straight to cproxy via PUT /api/config/origins. No GET/merge step — caller owns full state.

Use this to add new origin keys, remove keys, or reorder. SwitchOrigin only modifies URLs on existing keys — it cannot add new keys.

# add a new 'jap' origin key alongside existing food + ads
curl -X PUT http://localhost:3000/api/v1/distribution/caches/1/origins \
  -H "Content-Type: application/json" \
  -d '[
    {"key":"food","urlPattern":"^/food/.*$","urlRewriters":[{"matchPattern":"^/food/(.*)$","replace":"/$1"}],"originUrls":[{"url":"http://streamer_bkk:18080"},{"url":"http://streamer_ntb:18080"}],"memCacheConfigId":"mem-cache","ttl":"1s","ttlRules":[{"extensions":[".ts",".m4s",".mp4",".m4a",".aac"],"ttl":"30s"},{"extensions":[".m3u8",".mpd"],"ttl":"500ms"}],"healthCheck":{"period":"5s","timeout":"1s"},"failoverResponses":["404","5xx"],"retryCount":1,"balancingPolicy":"first-active"},
    {"key":"ads","urlPattern":"^/ads/.*$","urlRewriters":[{"matchPattern":"^/ads/(.*)$","replace":"/$1"}],"originUrls":[{"url":"http://streamer_bkk:18080"}],"memCacheConfigId":"mem-cache","ttl":"1s","ttlRules":[{"extensions":[".ts",".m4s",".mp4",".m4a",".aac"],"ttl":"30s"},{"extensions":[".m3u8",".mpd"],"ttl":"500ms"}],"healthCheck":{"period":"5s","timeout":"1s"},"failoverResponses":["404","5xx"],"retryCount":1,"balancingPolicy":"first-active"},
    {"key":"jap","urlPattern":"^/jap/.*$","urlRewriters":[{"matchPattern":"^/jap/(.*)$","replace":"/$1"}],"originUrls":[{"url":"http://streamer_bkk:18080"}],"memCacheConfigId":"mem-cache","ttl":"1s","ttlRules":[{"extensions":[".ts",".m4s",".mp4",".m4a",".aac"],"ttl":"30s"},{"extensions":[".m3u8",".mpd"],"ttl":"500ms"}],"healthCheck":{"period":"5s","timeout":"1s"},"failoverResponses":["404","5xx"],"retryCount":1,"balancingPolicy":"first-active"}
  ]'

PutOrigins function added to pkg/CProxyClient — passes raw JSON array straight to cproxy with no modification.

Route added: PUT /distribution/caches/:id/origins

2026-06-24

cproxy bind mount workaround

PUT /api/config/origins writes back to cproxy.yml on disk by first renaming the existing file to a timestamped backup, then writing the new file. Docker bind mounts block the rename operation (device or resource busy), causing the entire PUT to roll back with no change applied.

Fix: mount config to a temp path and copy at container startup:

cproxy_bkk_1:
  volumes:
    - ./cdn/cproxy-bkk-1/cproxy.yml:/tmp/cproxy-init.yml   # not directly over target
    - ./cdn/cproxy-bkk-1/logs:/data/log/cproxy
    - ./cdn/cproxy-bkk-1/filecache:/data/cproxy/filecache
  command: bash -c "cp /tmp/cproxy-init.yml /castis/bin/cproxy/cproxy.yml && ./cproxy"

cproxy starts with the host-managed config and can freely rename/backup the file at runtime. Config changes via PUT /api/config/origins now persist correctly.

2026-06-21

SLB (Castis ELB) node management added

New handler_slb.go in distribution domain. CoreAPI uses the term SLB (Server Load Balancer) as a vendor-agnostic abstraction — the underlying technology is the Castis ELB. pkg/ElbClient wraps the ELB API.

Routes added under /api/v1/distribution/slbs/:

Route Description
GET /slbs List SLB nodes
POST /slbs Register node
GET /slbs/:id Get by ID
PUT /slbs/:id Update
DELETE /slbs/:id Remove
POST /slbs/:id/ping Health check via GET /api/version
ALL /slbs/:id/proxy/* Passthrough to ELB API

pkg/ElbClient/ added — ProxyRequest, GetVersion, GetTraffic.

Model: SLB struct in domain/distribution/models.go, table slbs. Fields: name, host, proxyPort (:8090), apiPort (:8100), status, lastPingedAt.

Seed: pkg/seed/slb.go — seeds elb-bkk → elb_bkk:8100 on startup.

ELB startup fix: image binary lives at /usr/local/castis/GSLB/elb-1.0.3.rc1.x86_64, not /castis/bin/elb/. Config mount and command updated in cdn.yml:

volumes:
  - ./cdn/elb-bkk/elb.yml:/usr/local/castis/GSLB/elb.yml:ro
command: bash -c "cd /usr/local/castis/GSLB && chmod +x elb-1.0.3.rc1.x86_64 && ./elb-1.0.3.rc1.x86_64"

2026-06-21

Colorbars broadcaster added

New handler_colorbars.go in distribution domain. The colorbars container is a Go Fiber app that manages ffmpeg subprocesses — each one broadcasts SMPTE colorbars + 1kHz sine tone as MPEG-TS over UDP multicast to playtelly_cdn_net.

Routes added under /api/v1/distribution/colorbars/:

Route Description
GET /status List all streams and running state
POST /streams Create stream (port-unique enforced)
PATCH /streams/:id Update config — hot-restarts ffmpeg if running
POST /streams/:id/start Spawn ffmpeg subprocess
POST /streams/:id/stop Kill ffmpeg subprocess
DELETE /streams/:id Stop + remove from memory
ALL /proxy/* Passthrough to colorbars Fiber API on :9999

pkg/ColorbarClient/ added — mirrors StreamerClient and CProxyClient pattern.

Port uniqueness constraint discovered: Castis Streamer binds on port only when joining a multicast group. Two streams on the same port — even different IPs — cause the streamer to receive mixed data. createStream now returns 409 if the port is already in use.

compose/infrastructure/cdn.yml: colorbars now on both internal + cdn_net compose/infrastructure/networks-volumes.yml: cdn_net bridge added (172.28.0.0/16)

2026-06-21

UDP multicast probe added

ProbeUDP handler added to handler_streamer.go.

Creates a temporary .stream file on the target streamer node, polls GET /api/streams/:probeId every second for up to 6 seconds, then cleans up. Returns { "detected": true } if status reaches Running, false on timeout.

curl -X POST http://localhost:3000/api/v1/distribution/streamers/5/probe \
  -H "Content-Type: application/json" \
  -d '{"udp":"239.0.0.8","port":4444}'

Route added: POST /distribution/streamers/:id/probe

2026-06-21

Route prefix changed to /distribution

All distribution routes moved from /api/v1/streamers and /api/v1/caches to /api/v1/distribution/streamers and /api/v1/distribution/caches.

wire.go — Setup() now mounts under r.Group("/distribution") instead of directly on v1.

Old routes (deprecated):

GET  /api/v1/streamers
GET  /api/v1/caches

New routes:

GET  /api/v1/distribution/streamers
GET  /api/v1/distribution/caches

2026-06-21

Cache (cproxy) handlers added

handler_cache.go added alongside handler_streamer.go. Covers the cproxy edge cache layer in the CDN stack.

Route Description
GET /caches List cproxy nodes
POST /caches Register node
PUT /caches/:id Update
DELETE /caches/:id Remove
POST /caches/:id/ping Health check via /api/version (cproxy has no /api/ping)
POST /caches/:id/origins/:key/switch Patch origin URLs + purge stale cache
ALL /caches/:id/proxy/* Passthrough to cproxy API

pkg/CProxyClient/ added — PatchOriginURLs, PurgeOrigin, PurgeContent, GetTraffic.

2026-06-20

DeleteStreamer added (guarded)

DeleteStreamer handler added. Route commented out in routes.go pending an origin safety check — deleting a streamer node while channels still reference it leaves orphaned ChannelOrigin records. Will be enabled once the check is in place.

2026-06-20

config.go added

Environment variables centralized into domain/distribution/config.go. ConfigFromEnv() reads COLORBARS_HOST (default: colorbars) and COLORBARS_PORT (default: 9999). Handler no longer calls os.Getenv directly.

2026-06-19

Initial distribution domain

Extracted from legacy domain/service/ flat package.

Nested package structure established:

domain/distribution/
├── config.go
├── models.go       — Streamer, Cache structs, status consts
├── helper.go       — ApplyNodeFilters()
├── validation.go   — ParseID()
├── handlers/
│   ├── handler.go
│   └── handler_streamer.go
└── routes/
    ├── wire.go
    └── routes.go

pkg/StreamerClient/ added — CreateStream, DeleteStream, GetStreams, GetTraffic, PlaybackURL, BuildPayload, ProxyRequest.

Streamer proxy passthrough: ALL /streamers/:id/proxy/* forwards verbatim to the streamer's API port. Used for traffic inspection and direct stream management without adding wrapper endpoints for every Castis API operation.

Seeding: pkg/seed/streamer.go seeds local compose nodes (streamer-bkk, streamer-ntb) and staging nodes on startup. Existing records skipped by name.