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,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>
|
||||
Reference in New Issue
Block a user