initial: svc-proxy — UDP valve for Simple Voice Chat
Standalone Go service that routes SVC client traffic to per-server
backend voice endpoints, configured via pg LISTEN/NOTIFY (same channel
mc-router subscribes to). Each pg `servers` row with both
`voice_address` and `voice_proxy_port` set spawns a Valve: a public
UDP listener that maintains per-client ephemeral bridges to the
backend's SVC port.
Pieces:
cmd/svc-proxy/main.go entry; wires config, log fan-out,
bridge.Manager, pgsync, httpsrv
internal/config/ DATABASE_URL + BIND_HOST +
BRIDGE_IDLE_TTL (default 1m) +
HTTP_ADDR (default :8081)
internal/pgsync/ LISTEN automc_routes_changed; diff
desired/actual routes; emit Apply()
internal/bridge/ Valve per public port; per-client
bridge with atomic up/down byte counters;
idle eviction every 15s against TTL
internal/httpsrv/ operator UI — embedded single-page HTML
with active-connections table polled
every 1s + SSE log stream
(last 500 lines backlog on connect)
Reverse-proxied behind server-manager at /infra/svc-proxy/* — bind
internal-only addresses for production; auth is the dashboard's
Basic gate.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,263 @@
|
||||
// Package bridge owns the UDP data plane: one Valve per backend, each Valve
|
||||
// owns a public listener socket and a pool of per-client bridges that copy
|
||||
// datagrams to the backend's voice address and back.
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.timemachine.center/timemachine/svc-proxy/internal/pgsync"
|
||||
)
|
||||
|
||||
// Manager is the top-level coordinator. Implements pgsync.Applier so the
|
||||
// pgsync goroutine can hand it desired/undesired routes; Manager turns those
|
||||
// into open/close calls on a Valve registry keyed by public port.
|
||||
type Manager struct {
|
||||
ctx context.Context
|
||||
bindHost string
|
||||
bridgeIdleTTL time.Duration
|
||||
|
||||
mu sync.Mutex
|
||||
valves map[int]*Valve // key: public UDP port
|
||||
}
|
||||
|
||||
func NewManager(ctx context.Context, bindHost string, idleTTL time.Duration) *Manager {
|
||||
return &Manager{
|
||||
ctx: ctx,
|
||||
bindHost: bindHost,
|
||||
bridgeIdleTTL: idleTTL,
|
||||
valves: map[int]*Valve{},
|
||||
}
|
||||
}
|
||||
|
||||
// Apply satisfies pgsync.Applier. Open first (so a backend-address change
|
||||
// can flip-cleanly while the new listener takes over the new port), then
|
||||
// close.
|
||||
func (m *Manager) Apply(add []pgsync.Route, del []pgsync.Route) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
for _, r := range add {
|
||||
if existing, ok := m.valves[r.Port]; ok {
|
||||
// Same port, different backend — close, then re-open.
|
||||
existing.Close()
|
||||
delete(m.valves, r.Port)
|
||||
}
|
||||
v, err := openValve(m.ctx, m.bindHost, r, m.bridgeIdleTTL)
|
||||
if err != nil {
|
||||
slog.Error("valve open failed", "port", r.Port, "addr", r.Address, "name", r.Name, "err", err)
|
||||
continue
|
||||
}
|
||||
m.valves[r.Port] = v
|
||||
slog.Info("valve open", "port", r.Port, "addr", r.Address, "name", r.Name)
|
||||
}
|
||||
|
||||
for _, r := range del {
|
||||
v, ok := m.valves[r.Port]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
v.Close()
|
||||
delete(m.valves, r.Port)
|
||||
slog.Info("valve close", "port", r.Port, "name", r.Name)
|
||||
}
|
||||
}
|
||||
|
||||
// Shutdown closes every active valve. Safe to call once; idempotent for
|
||||
// per-valve Close.
|
||||
func (m *Manager) Shutdown() {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
for port, v := range m.valves {
|
||||
v.Close()
|
||||
delete(m.valves, port)
|
||||
}
|
||||
}
|
||||
|
||||
// Valve owns one public UDP listener and the per-client bridges hanging off
|
||||
// it. Each bridge is a goroutine that copies datagrams from one ephemeral
|
||||
// upstream socket back to the original client. The public socket itself is
|
||||
// the egress for backend → client.
|
||||
type Valve struct {
|
||||
route pgsync.Route
|
||||
backend *net.UDPAddr
|
||||
pub *net.UDPConn // 0.0.0.0:<route.Port>
|
||||
|
||||
idleTTL time.Duration
|
||||
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
|
||||
mu sync.Mutex
|
||||
bridges map[string]*clientBridge // key: client.RemoteAddr().String()
|
||||
}
|
||||
|
||||
func openValve(parent context.Context, bindHost string, r pgsync.Route, idleTTL time.Duration) (*Valve, error) {
|
||||
backend, err := net.ResolveUDPAddr("udp", r.Address)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resolve backend %q: %w", r.Address, err)
|
||||
}
|
||||
pubAddr := &net.UDPAddr{IP: net.ParseIP(bindHost), Port: r.Port}
|
||||
if pubAddr.IP == nil {
|
||||
return nil, fmt.Errorf("bind host %q not an IP", bindHost)
|
||||
}
|
||||
pub, err := net.ListenUDP("udp", pubAddr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("bind %s: %w", pubAddr, err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(parent)
|
||||
v := &Valve{
|
||||
route: r,
|
||||
backend: backend,
|
||||
pub: pub,
|
||||
idleTTL: idleTTL,
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
bridges: map[string]*clientBridge{},
|
||||
}
|
||||
go v.readLoop()
|
||||
go v.evictIdle()
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// readLoop runs forever copying packets from the public socket to per-client
|
||||
// upstream sockets. The reverse direction (backend → client) is per-bridge
|
||||
// goroutines on the upstream sockets writing back to v.pub.
|
||||
func (v *Valve) readLoop() {
|
||||
buf := make([]byte, 2048) // SVC max datagram body
|
||||
for {
|
||||
n, src, err := v.pub.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
if v.ctx.Err() != nil || errors.Is(err, net.ErrClosed) {
|
||||
return
|
||||
}
|
||||
slog.Warn("valve read error", "port", v.route.Port, "err", err)
|
||||
continue
|
||||
}
|
||||
v.mu.Lock()
|
||||
b, ok := v.bridges[src.String()]
|
||||
if !ok {
|
||||
b, err = v.openBridge(src)
|
||||
if err != nil {
|
||||
v.mu.Unlock()
|
||||
slog.Warn("bridge open failed", "port", v.route.Port, "src", src, "err", err)
|
||||
continue
|
||||
}
|
||||
v.bridges[src.String()] = b
|
||||
slog.Debug("bridge open", "port", v.route.Port, "client", src.String())
|
||||
}
|
||||
v.mu.Unlock()
|
||||
b.touch()
|
||||
if _, err := b.upstream.Write(buf[:n]); err != nil {
|
||||
if v.ctx.Err() == nil {
|
||||
slog.Warn("bridge forward failed", "port", v.route.Port, "err", err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
b.counters.bytesUp.Add(uint64(n))
|
||||
}
|
||||
}
|
||||
|
||||
func (v *Valve) openBridge(src *net.UDPAddr) (*clientBridge, error) {
|
||||
up, err := net.DialUDP("udp", nil, v.backend)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("dial backend: %w", err)
|
||||
}
|
||||
now := time.Now()
|
||||
b := &clientBridge{
|
||||
client: src,
|
||||
upstream: up,
|
||||
valve: v,
|
||||
openedAt: now,
|
||||
}
|
||||
b.lastSeen = now
|
||||
go b.readBackend()
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func (v *Valve) evictIdle() {
|
||||
t := time.NewTicker(15 * time.Second)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-v.ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
cutoff := time.Now().Add(-v.idleTTL)
|
||||
v.mu.Lock()
|
||||
for k, b := range v.bridges {
|
||||
if b.lastUseBefore(cutoff) {
|
||||
slog.Debug("bridge idle evict", "port", v.route.Port, "client", k)
|
||||
b.close()
|
||||
delete(v.bridges, k)
|
||||
}
|
||||
}
|
||||
v.mu.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (v *Valve) Close() {
|
||||
v.cancel()
|
||||
v.pub.Close()
|
||||
v.mu.Lock()
|
||||
for k, b := range v.bridges {
|
||||
b.close()
|
||||
delete(v.bridges, k)
|
||||
}
|
||||
v.mu.Unlock()
|
||||
}
|
||||
|
||||
type clientBridge struct {
|
||||
client *net.UDPAddr
|
||||
upstream *net.UDPConn
|
||||
valve *Valve
|
||||
|
||||
counters counters // atomic — hot path
|
||||
|
||||
mu sync.Mutex
|
||||
lastSeen time.Time
|
||||
openedAt time.Time
|
||||
}
|
||||
|
||||
func (b *clientBridge) touch() {
|
||||
b.mu.Lock()
|
||||
b.lastSeen = time.Now()
|
||||
b.mu.Unlock()
|
||||
}
|
||||
|
||||
func (b *clientBridge) lastUseBefore(t time.Time) bool {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.lastSeen.Before(t)
|
||||
}
|
||||
|
||||
func (b *clientBridge) close() {
|
||||
_ = b.upstream.Close()
|
||||
}
|
||||
|
||||
// readBackend pumps datagrams from the backend back to the client via the
|
||||
// public socket. Exits when the upstream socket is closed.
|
||||
func (b *clientBridge) readBackend() {
|
||||
buf := make([]byte, 2048)
|
||||
for {
|
||||
n, err := b.upstream.Read(buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
b.touch()
|
||||
if _, err := b.valve.pub.WriteToUDP(buf[:n], b.client); err != nil {
|
||||
if b.valve.ctx.Err() == nil {
|
||||
slog.Warn("bridge reverse failed", "port", b.valve.route.Port, "err", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
b.counters.bytesDown.Add(uint64(n))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// counters is the per-bridge byte tally. Updated from the two hot paths
|
||||
// (readLoop client→backend, readBackend backend→client) — atomic to avoid
|
||||
// locking the bridge for every datagram.
|
||||
type counters struct {
|
||||
bytesUp atomic.Uint64 // client → backend
|
||||
bytesDown atomic.Uint64 // backend → client
|
||||
}
|
||||
|
||||
// ConnSnapshot is one row of the active-connections table the UI renders.
|
||||
// All times are wall-clock; sizes are total bytes since the bridge opened.
|
||||
type ConnSnapshot struct {
|
||||
Server string `json:"server"` // pg row name (e.g. "gtnh")
|
||||
Port int `json:"port"` // public UDP port (the valve)
|
||||
Backend string `json:"backend"` // backend addr
|
||||
Client string `json:"client"` // source IP:port
|
||||
BytesUp uint64 `json:"bytes_up"` // client → backend
|
||||
BytesDown uint64 `json:"bytes_down"` // backend → client
|
||||
OpenedAt time.Time `json:"opened_at"` // bridge creation
|
||||
LastSeen time.Time `json:"last_seen"` // most-recent datagram either direction
|
||||
IdleSeconds float64 `json:"idle_seconds"` // derived; UI sorts by this
|
||||
}
|
||||
|
||||
// Snapshot returns one row per active client bridge across all valves.
|
||||
// Cheap-ish: takes the Manager lock + each Valve lock briefly, no per-bridge
|
||||
// lock (counters are atomic; LastSeen is read under the bridge lock).
|
||||
func (m *Manager) Snapshot() []ConnSnapshot {
|
||||
m.mu.Lock()
|
||||
valves := make([]*Valve, 0, len(m.valves))
|
||||
for _, v := range m.valves {
|
||||
valves = append(valves, v)
|
||||
}
|
||||
m.mu.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
var out []ConnSnapshot
|
||||
for _, v := range valves {
|
||||
v.mu.Lock()
|
||||
for _, b := range v.bridges {
|
||||
b.mu.Lock()
|
||||
lastSeen := b.lastSeen
|
||||
opened := b.openedAt
|
||||
b.mu.Unlock()
|
||||
out = append(out, ConnSnapshot{
|
||||
Server: v.route.Name,
|
||||
Port: v.route.Port,
|
||||
Backend: v.route.Address,
|
||||
Client: b.client.String(),
|
||||
BytesUp: b.counters.bytesUp.Load(),
|
||||
BytesDown: b.counters.bytesDown.Load(),
|
||||
OpenedAt: opened,
|
||||
LastSeen: lastSeen,
|
||||
IdleSeconds: now.Sub(lastSeen).Seconds(),
|
||||
})
|
||||
}
|
||||
v.mu.Unlock()
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
DatabaseURL string
|
||||
BindHost string
|
||||
BridgeIdleTTL time.Duration
|
||||
HTTPAddr string
|
||||
LogLevel string
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
cfg := Config{
|
||||
DatabaseURL: os.Getenv("DATABASE_URL"),
|
||||
BindHost: envOr("BIND_HOST", "0.0.0.0"),
|
||||
BridgeIdleTTL: envDur("BRIDGE_IDLE_TTL", 1*time.Minute),
|
||||
HTTPAddr: envOr("HTTP_ADDR", ":8081"),
|
||||
LogLevel: envOr("LOG_LEVEL", "info"),
|
||||
}
|
||||
if cfg.DatabaseURL == "" {
|
||||
return cfg, fmt.Errorf("DATABASE_URL required")
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func envOr(key, fallback string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func envDur(key string, fallback time.Duration) time.Duration {
|
||||
v := os.Getenv(key)
|
||||
if v == "" {
|
||||
return fallback
|
||||
}
|
||||
d, err := time.ParseDuration(v)
|
||||
if err != nil {
|
||||
return fallback
|
||||
}
|
||||
return d
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package httpsrv
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// LogBus is a fan-out buffer for log lines. It holds a ring of the last N
|
||||
// entries and broadcasts new lines to live SSE subscribers. The slog Handler
|
||||
// in NewLogBus writes each formatted record into both the underlying handler
|
||||
// (stderr) AND this bus.
|
||||
type LogBus struct {
|
||||
cap int
|
||||
|
||||
mu sync.RWMutex
|
||||
ring []LogEntry
|
||||
next int
|
||||
full bool
|
||||
listeners map[chan LogEntry]struct{}
|
||||
}
|
||||
|
||||
type LogEntry struct {
|
||||
Time time.Time `json:"time"`
|
||||
Level string `json:"level"`
|
||||
Msg string `json:"msg"`
|
||||
Attrs string `json:"attrs,omitempty"`
|
||||
}
|
||||
|
||||
func NewLogBus(capacity int) *LogBus {
|
||||
if capacity <= 0 {
|
||||
capacity = 500
|
||||
}
|
||||
return &LogBus{
|
||||
cap: capacity,
|
||||
ring: make([]LogEntry, capacity),
|
||||
listeners: map[chan LogEntry]struct{}{},
|
||||
}
|
||||
}
|
||||
|
||||
func (b *LogBus) push(e LogEntry) {
|
||||
b.mu.Lock()
|
||||
b.ring[b.next] = e
|
||||
b.next = (b.next + 1) % b.cap
|
||||
if b.next == 0 {
|
||||
b.full = true
|
||||
}
|
||||
subs := make([]chan LogEntry, 0, len(b.listeners))
|
||||
for ch := range b.listeners {
|
||||
subs = append(subs, ch)
|
||||
}
|
||||
b.mu.Unlock()
|
||||
for _, ch := range subs {
|
||||
select {
|
||||
case ch <- e:
|
||||
default:
|
||||
// slow subscriber; drop rather than back-pressure the writer
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Backlog returns the buffered entries oldest-first.
|
||||
func (b *LogBus) Backlog() []LogEntry {
|
||||
b.mu.RLock()
|
||||
defer b.mu.RUnlock()
|
||||
if !b.full {
|
||||
out := make([]LogEntry, b.next)
|
||||
copy(out, b.ring[:b.next])
|
||||
return out
|
||||
}
|
||||
out := make([]LogEntry, 0, b.cap)
|
||||
out = append(out, b.ring[b.next:]...)
|
||||
out = append(out, b.ring[:b.next]...)
|
||||
return out
|
||||
}
|
||||
|
||||
// Subscribe registers a fresh channel that will receive every subsequent
|
||||
// entry. Caller must call Unsubscribe when done.
|
||||
func (b *LogBus) Subscribe() chan LogEntry {
|
||||
ch := make(chan LogEntry, 32)
|
||||
b.mu.Lock()
|
||||
b.listeners[ch] = struct{}{}
|
||||
b.mu.Unlock()
|
||||
return ch
|
||||
}
|
||||
|
||||
func (b *LogBus) Unsubscribe(ch chan LogEntry) {
|
||||
b.mu.Lock()
|
||||
delete(b.listeners, ch)
|
||||
b.mu.Unlock()
|
||||
close(ch)
|
||||
}
|
||||
|
||||
// busHandler wraps a base slog.Handler and pushes a structured copy of each
|
||||
// record to the LogBus. Errors during push are ignored — logging must never
|
||||
// stall on UI subscribers.
|
||||
type busHandler struct {
|
||||
base slog.Handler
|
||||
bus *LogBus
|
||||
}
|
||||
|
||||
// NewBusHandler returns a slog.Handler that emits to both `base` and `bus`.
|
||||
func NewBusHandler(base slog.Handler, bus *LogBus) slog.Handler {
|
||||
return &busHandler{base: base, bus: bus}
|
||||
}
|
||||
|
||||
func (h *busHandler) Enabled(ctx context.Context, lvl slog.Level) bool {
|
||||
return h.base.Enabled(ctx, lvl)
|
||||
}
|
||||
|
||||
func (h *busHandler) Handle(ctx context.Context, r slog.Record) error {
|
||||
// First emit to the base handler so console/journald behaviour is
|
||||
// preserved. Push to bus regardless of base error.
|
||||
err := h.base.Handle(ctx, r)
|
||||
|
||||
var attrs string
|
||||
r.Attrs(func(a slog.Attr) bool {
|
||||
if attrs != "" {
|
||||
attrs += " "
|
||||
}
|
||||
attrs += fmt.Sprintf("%s=%v", a.Key, a.Value.Any())
|
||||
return true
|
||||
})
|
||||
h.bus.push(LogEntry{
|
||||
Time: r.Time,
|
||||
Level: r.Level.String(),
|
||||
Msg: r.Message,
|
||||
Attrs: attrs,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (h *busHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||||
return &busHandler{base: h.base.WithAttrs(attrs), bus: h.bus}
|
||||
}
|
||||
|
||||
func (h *busHandler) WithGroup(name string) slog.Handler {
|
||||
return &busHandler{base: h.base.WithGroup(name), bus: h.bus}
|
||||
}
|
||||
|
||||
// sseLogs streams the backlog + every new entry as Server-Sent Events.
|
||||
// Each event is one JSON-encoded LogEntry on a `data:` line.
|
||||
func sseLogs(bus *LogBus) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Header().Set("Connection", "keep-alive")
|
||||
w.Header().Set("X-Accel-Buffering", "no") // disable proxy buffering
|
||||
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
for _, e := range bus.Backlog() {
|
||||
writeEvent(w, e)
|
||||
}
|
||||
flusher.Flush()
|
||||
|
||||
ch := bus.Subscribe()
|
||||
defer bus.Unsubscribe(ch)
|
||||
|
||||
// Heartbeat keeps proxies from closing the conn during silent periods.
|
||||
heartbeat := time.NewTicker(30 * time.Second)
|
||||
defer heartbeat.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
case e := <-ch:
|
||||
writeEvent(w, e)
|
||||
flusher.Flush()
|
||||
case <-heartbeat.C:
|
||||
_, _ = io.WriteString(w, ":hb\n\n")
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func writeEvent(w io.Writer, e LogEntry) {
|
||||
fmt.Fprintf(w, "data: {\"time\":%q,\"level\":%q,\"msg\":%q,\"attrs\":%q}\n\n",
|
||||
e.Time.Format(time.RFC3339Nano), e.Level, e.Msg, e.Attrs)
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// Package httpsrv exposes the svc-proxy operator UI + JSON API. Designed to
|
||||
// be reverse-proxied behind server-manager (no auth/TLS at this layer; the
|
||||
// listener should bind to the container network only).
|
||||
package httpsrv
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"git.timemachine.center/timemachine/svc-proxy/internal/bridge"
|
||||
)
|
||||
|
||||
//go:embed static/*
|
||||
var staticFS embed.FS
|
||||
|
||||
type Server struct {
|
||||
addr string
|
||||
mgr *bridge.Manager
|
||||
bus *LogBus
|
||||
srv *http.Server
|
||||
}
|
||||
|
||||
func New(addr string, mgr *bridge.Manager, bus *LogBus) *Server {
|
||||
mux := http.NewServeMux()
|
||||
s := &Server{
|
||||
addr: addr,
|
||||
mgr: mgr,
|
||||
bus: bus,
|
||||
}
|
||||
|
||||
sub, err := fs.Sub(staticFS, "static")
|
||||
if err != nil {
|
||||
panic(err) // embed.FS misconfigured at build time
|
||||
}
|
||||
mux.Handle("GET /", http.FileServer(http.FS(sub)))
|
||||
mux.HandleFunc("GET /api/connections", s.handleConnections)
|
||||
mux.HandleFunc("GET /api/logs", sseLogs(bus))
|
||||
|
||||
s.srv = &http.Server{
|
||||
Addr: addr,
|
||||
Handler: mux,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Run blocks until ctx is cancelled or the server errors.
|
||||
func (s *Server) Run(ctx context.Context) error {
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
shutCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
_ = s.srv.Shutdown(shutCtx)
|
||||
}()
|
||||
slog.Info("http server listening", "addr", s.addr)
|
||||
if err := s.srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) handleConnections(w http.ResponseWriter, _ *http.Request) {
|
||||
snap := s.mgr.Snapshot()
|
||||
// Sort by most-recently-active first so the UI can render top-down.
|
||||
sort.Slice(snap, func(i, j int) bool { return snap[i].LastSeen.After(snap[j].LastSeen) })
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"connections": snap,
|
||||
"at": time.Now(),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>svc-proxy</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #0f1115;
|
||||
--panel: #161922;
|
||||
--panel-2: #1c2030;
|
||||
--border: #2a2f42;
|
||||
--text: #d6d9e0;
|
||||
--muted: #7a8194;
|
||||
--accent: #6aa9ff;
|
||||
--up: #4ade80;
|
||||
--down: #f59e0b;
|
||||
--err: #f87171;
|
||||
--warn: #fbbf24;
|
||||
--info: #93c5fd;
|
||||
--dbg: #6b7280;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0; padding: 0;
|
||||
font: 13px/1.4 ui-monospace, "JetBrains Mono", Menlo, Consolas, monospace;
|
||||
background: var(--bg); color: var(--text);
|
||||
display: grid; grid-template-rows: auto 1fr 1fr; height: 100vh;
|
||||
}
|
||||
header {
|
||||
padding: 10px 16px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: var(--panel);
|
||||
display: flex; justify-content: space-between; align-items: center;
|
||||
}
|
||||
h1 { margin: 0; font-size: 14px; font-weight: 600; letter-spacing: 0.5px; }
|
||||
h1 .meta { color: var(--muted); margin-left: 12px; font-weight: normal; }
|
||||
.status { color: var(--muted); font-size: 12px; }
|
||||
.status.ok { color: var(--up); }
|
||||
.status.err { color: var(--err); }
|
||||
|
||||
section { padding: 12px 16px; overflow: auto; border-bottom: 1px solid var(--border); }
|
||||
section h2 {
|
||||
margin: 0 0 10px; font-size: 12px; text-transform: uppercase;
|
||||
letter-spacing: 0.7px; color: var(--muted); font-weight: 600;
|
||||
}
|
||||
section.logs { font-size: 12.5px; }
|
||||
section.logs h2 { display: flex; justify-content: space-between; align-items: center; }
|
||||
section.logs h2 .clear {
|
||||
background: transparent; color: var(--muted); border: 1px solid var(--border);
|
||||
padding: 2px 8px; cursor: pointer; font: inherit; border-radius: 3px;
|
||||
}
|
||||
section.logs h2 .clear:hover { color: var(--text); border-color: var(--accent); }
|
||||
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th, td {
|
||||
text-align: left; padding: 6px 10px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
th { color: var(--muted); font-weight: 500; font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px; }
|
||||
tbody tr:hover { background: var(--panel-2); }
|
||||
td.num { text-align: right; }
|
||||
td.up { color: var(--up); }
|
||||
td.down { color: var(--down); }
|
||||
td.idle.stale { color: var(--warn); }
|
||||
td.idle.dead { color: var(--err); }
|
||||
.empty { color: var(--muted); padding: 20px; text-align: center; }
|
||||
|
||||
pre.logbox {
|
||||
margin: 0; white-space: pre-wrap; word-break: break-word;
|
||||
max-height: 100%;
|
||||
}
|
||||
.log-line { padding: 1px 0; }
|
||||
.log-line .ts { color: var(--muted); margin-right: 8px; }
|
||||
.log-line .lvl { margin-right: 6px; font-weight: 600; }
|
||||
.log-line.lvl-DEBUG .lvl { color: var(--dbg); }
|
||||
.log-line.lvl-INFO .lvl { color: var(--info); }
|
||||
.log-line.lvl-WARN .lvl { color: var(--warn); }
|
||||
.log-line.lvl-ERROR .lvl { color: var(--err); }
|
||||
.log-line .attrs { color: var(--muted); margin-left: 8px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<h1>svc-proxy <span class="meta" id="meta">— connecting…</span></h1>
|
||||
<span class="status" id="status">log stream: connecting</span>
|
||||
</header>
|
||||
|
||||
<section class="conns">
|
||||
<h2>Active connections <span id="conn-count" style="color:var(--muted);"></span></h2>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Server</th>
|
||||
<th>Port</th>
|
||||
<th>Client</th>
|
||||
<th>Backend</th>
|
||||
<th class="num">Up</th>
|
||||
<th class="num">Down</th>
|
||||
<th class="num">Idle</th>
|
||||
<th class="num">Age</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="conn-rows"></tbody>
|
||||
</table>
|
||||
<div id="conn-empty" class="empty">no active bridges</div>
|
||||
</section>
|
||||
|
||||
<section class="logs">
|
||||
<h2>
|
||||
<span>Logs</span>
|
||||
<button class="clear" onclick="document.getElementById('logbox').innerHTML=''">clear</button>
|
||||
</h2>
|
||||
<pre class="logbox" id="logbox"></pre>
|
||||
</section>
|
||||
|
||||
<script>
|
||||
const fmtBytes = n => {
|
||||
if (n < 1024) return n + ' B';
|
||||
if (n < 1024*1024) return (n/1024).toFixed(1) + ' KiB';
|
||||
if (n < 1024*1024*1024) return (n/(1024*1024)).toFixed(2) + ' MiB';
|
||||
return (n/(1024*1024*1024)).toFixed(2) + ' GiB';
|
||||
};
|
||||
const fmtAgo = secs => {
|
||||
if (secs < 60) return secs.toFixed(0) + 's';
|
||||
if (secs < 3600) return Math.floor(secs/60) + 'm' + Math.floor(secs%60) + 's';
|
||||
const h = Math.floor(secs/3600);
|
||||
const m = Math.floor((secs % 3600) / 60);
|
||||
return h + 'h' + m + 'm';
|
||||
};
|
||||
|
||||
async function refreshConnections() {
|
||||
try {
|
||||
const r = await fetch('/api/connections');
|
||||
const j = await r.json();
|
||||
const rows = document.getElementById('conn-rows');
|
||||
const empty = document.getElementById('conn-empty');
|
||||
const count = document.getElementById('conn-count');
|
||||
rows.innerHTML = '';
|
||||
const now = new Date(j.at).getTime();
|
||||
if (!j.connections || j.connections.length === 0) {
|
||||
empty.style.display = '';
|
||||
count.textContent = '';
|
||||
} else {
|
||||
empty.style.display = 'none';
|
||||
count.textContent = '(' + j.connections.length + ')';
|
||||
for (const c of j.connections) {
|
||||
const opened = new Date(c.opened_at).getTime();
|
||||
const ageSecs = (now - opened) / 1000;
|
||||
const idleCls = c.idle_seconds > 60 ? 'dead' : c.idle_seconds > 30 ? 'stale' : '';
|
||||
const tr = document.createElement('tr');
|
||||
tr.innerHTML =
|
||||
'<td>' + c.server + '</td>' +
|
||||
'<td>:' + c.port + '</td>' +
|
||||
'<td>' + c.client + '</td>' +
|
||||
'<td>' + c.backend + '</td>' +
|
||||
'<td class="num up">↑ ' + fmtBytes(c.bytes_up) + '</td>' +
|
||||
'<td class="num down">↓ ' + fmtBytes(c.bytes_down) + '</td>' +
|
||||
'<td class="num idle ' + idleCls + '">' + fmtAgo(c.idle_seconds) + '</td>' +
|
||||
'<td class="num">' + fmtAgo(ageSecs) + '</td>';
|
||||
rows.appendChild(tr);
|
||||
}
|
||||
}
|
||||
document.getElementById('meta').textContent = '— ' + j.connections.length + ' bridges';
|
||||
} catch (e) {
|
||||
document.getElementById('meta').textContent = '— api error';
|
||||
}
|
||||
}
|
||||
setInterval(refreshConnections, 1000);
|
||||
refreshConnections();
|
||||
|
||||
function startLogStream() {
|
||||
const status = document.getElementById('status');
|
||||
const box = document.getElementById('logbox');
|
||||
const es = new EventSource('/api/logs');
|
||||
es.onopen = () => { status.textContent = 'log stream: live'; status.className = 'status ok'; };
|
||||
es.onerror = () => { status.textContent = 'log stream: reconnecting'; status.className = 'status err'; };
|
||||
es.onmessage = ev => {
|
||||
let e;
|
||||
try { e = JSON.parse(ev.data); } catch { return; }
|
||||
const ts = e.time ? e.time.split('T')[1].split('.')[0] : '';
|
||||
const div = document.createElement('div');
|
||||
div.className = 'log-line lvl-' + (e.level || 'INFO');
|
||||
div.innerHTML =
|
||||
'<span class="ts">' + ts + '</span>' +
|
||||
'<span class="lvl">' + (e.level || 'INFO') + '</span>' +
|
||||
(e.msg || '') +
|
||||
(e.attrs ? '<span class="attrs">' + e.attrs + '</span>' : '');
|
||||
box.appendChild(div);
|
||||
// Auto-scroll if near the bottom
|
||||
const parent = box.parentElement;
|
||||
if (parent.scrollHeight - parent.scrollTop - parent.clientHeight < 60) {
|
||||
parent.scrollTop = parent.scrollHeight;
|
||||
}
|
||||
while (box.children.length > 1000) box.removeChild(box.firstChild);
|
||||
};
|
||||
}
|
||||
startLogStream();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,142 @@
|
||||
// Package pgsync mirrors the LISTEN/NOTIFY route-source pattern from
|
||||
// Timemachine/mc-router's internal/automc. Watches the `servers` table for
|
||||
// rows that have both voice columns set and emits Route events whenever the
|
||||
// desired set changes.
|
||||
package pgsync
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
const (
|
||||
NotifyChannel = "automc_routes_changed"
|
||||
reconnectMin = 1 * time.Second
|
||||
reconnectMax = 30 * time.Second
|
||||
)
|
||||
|
||||
// Route is a single voice routing row from postgres. Both Port and Address
|
||||
// are guaranteed non-zero when emitted via Apply.
|
||||
type Route struct {
|
||||
Name string // human-readable; logged on open/close
|
||||
Port int // public UDP port svc-proxy binds
|
||||
Address string // backend voice host:port (e.g. "mc-gtnh:24454")
|
||||
}
|
||||
|
||||
// Applier reconciles a desired route set against currently-bound valves.
|
||||
// Add is called for routes that are new or whose backend address changed;
|
||||
// Del is called for routes that disappeared or whose backend address changed
|
||||
// (in pair with the new Add for the same port).
|
||||
type Applier interface {
|
||||
Apply(add []Route, del []Route)
|
||||
}
|
||||
|
||||
type Syncer struct {
|
||||
dsn string
|
||||
applier Applier
|
||||
current map[string]Route // key: server name
|
||||
}
|
||||
|
||||
func New(dsn string, a Applier) *Syncer {
|
||||
return &Syncer{dsn: dsn, applier: a, current: map[string]Route{}}
|
||||
}
|
||||
|
||||
// Run blocks until ctx is cancelled. Reconnects on error with exponential
|
||||
// backoff capped at reconnectMax.
|
||||
func (s *Syncer) Run(ctx context.Context) {
|
||||
backoff := reconnectMin
|
||||
for {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
err := s.connectAndLoop(ctx)
|
||||
if err != nil && !errors.Is(err, context.Canceled) {
|
||||
slog.Warn("pgsync disconnected", "err", err, "retry_in", backoff)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(backoff):
|
||||
}
|
||||
backoff *= 2
|
||||
if backoff > reconnectMax {
|
||||
backoff = reconnectMax
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Syncer) connectAndLoop(ctx context.Context) error {
|
||||
conn, err := pgx.Connect(ctx, s.dsn)
|
||||
if err != nil {
|
||||
return fmt.Errorf("pgx connect: %w", err)
|
||||
}
|
||||
defer conn.Close(context.Background())
|
||||
|
||||
if _, err := conn.Exec(ctx, "LISTEN "+NotifyChannel); err != nil {
|
||||
return fmt.Errorf("LISTEN: %w", err)
|
||||
}
|
||||
slog.Info("pgsync connected", "channel", NotifyChannel)
|
||||
|
||||
if err := s.refresh(ctx, conn); err != nil {
|
||||
return fmt.Errorf("initial refresh: %w", err)
|
||||
}
|
||||
|
||||
for {
|
||||
if _, err := conn.WaitForNotification(ctx); err != nil {
|
||||
return fmt.Errorf("wait notification: %w", err)
|
||||
}
|
||||
if err := s.refresh(ctx, conn); err != nil {
|
||||
return fmt.Errorf("refresh: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Syncer) refresh(ctx context.Context, conn *pgx.Conn) error {
|
||||
rows, err := conn.Query(ctx, `
|
||||
SELECT name, voice_proxy_port, voice_address
|
||||
FROM servers
|
||||
WHERE enabled IS NOT FALSE
|
||||
AND voice_proxy_port IS NOT NULL
|
||||
AND voice_address IS NOT NULL
|
||||
AND voice_address != ''`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
desired := map[string]Route{}
|
||||
for rows.Next() {
|
||||
var r Route
|
||||
if err := rows.Scan(&r.Name, &r.Port, &r.Address); err != nil {
|
||||
return err
|
||||
}
|
||||
desired[r.Name] = r
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
add, del := diff(s.current, desired)
|
||||
s.applier.Apply(add, del)
|
||||
s.current = desired
|
||||
return nil
|
||||
}
|
||||
|
||||
func diff(prev, next map[string]Route) (add []Route, del []Route) {
|
||||
for name, r := range next {
|
||||
if p, ok := prev[name]; !ok || p.Port != r.Port || p.Address != r.Address {
|
||||
add = append(add, r)
|
||||
}
|
||||
}
|
||||
for name, r := range prev {
|
||||
if n, ok := next[name]; !ok || n.Port != r.Port || n.Address != r.Address {
|
||||
del = append(del, r)
|
||||
}
|
||||
}
|
||||
return add, del
|
||||
}
|
||||
Reference in New Issue
Block a user