This repository has been archived on 2026-04-03. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
core/server/cluster/registry.go
Jeffrey Smith 35d2309450
All checks were successful
CI/CD / detect-changes (pull_request) Successful in 21s
CI/CD / test-frontend (pull_request) Successful in 5s
CI/CD / test-go-pg (pull_request) Successful in 2m58s
CI/CD / test-sqlite (pull_request) Successful in 3m2s
CI/CD / build-and-deploy (pull_request) Successful in 1m15s
Feat v0.6.0 cluster registry + HA
PG-backed cluster registry for horizontal scaling — zero new
infrastructure (no etcd/Consul/Redis). MVP convergence point.

- node_registry UNLOGGED table (migration 013)
- Self-registration, heartbeat tick (10s), stale sweep (30s),
  self-eviction (os.Exit on 0 rows → K8s restarts)
- GET /api/v1/admin/cluster returns nodes with runtime stats
- Health endpoints include node_id + cluster size/peers
- cluster-dashboard admin surface with auto-refresh
- 3-replica E2E test (docker-compose-e2e.yml + ci/e2e-cluster-test.sh)
- chat + cluster-dashboard added to curated default bundle
- 5 new tests (3 unit + 2 handler), all passing

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 22:20:56 +00:00

144 lines
3.5 KiB
Go

package cluster
import (
"context"
"encoding/json"
"log"
"os"
"runtime"
"sync"
"time"
"switchboard-core/store"
)
// ConnCounter provides WebSocket connection count (satisfied by events.Hub).
type ConnCounter interface {
ConnCount() int
}
// RegistryConfig holds tunable cluster registry parameters.
type RegistryConfig struct {
HeartbeatInterval time.Duration
StaleThreshold time.Duration
}
// Registry manages node self-registration, heartbeat, and stale sweep.
// Follows the workflow.Scanner pattern: stopCh + wg + ticker.
type Registry struct {
nodeID string
endpoint string
store store.ClusterStore
hub ConnCounter
cfg RegistryConfig
startTime time.Time
stopCh chan struct{}
wg sync.WaitGroup
}
// NewRegistry creates a cluster registry instance.
func NewRegistry(nodeID, endpoint string, s store.ClusterStore, hub ConnCounter, cfg RegistryConfig) *Registry {
return &Registry{
nodeID: nodeID,
endpoint: endpoint,
store: s,
hub: hub,
cfg: cfg,
startTime: time.Now(),
stopCh: make(chan struct{}),
}
}
// NodeID returns this node's identifier.
func (r *Registry) NodeID() string { return r.nodeID }
// Start registers the node and launches the heartbeat goroutine.
func (r *Registry) Start() error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := r.store.Register(ctx, r.nodeID, r.endpoint); err != nil {
return err
}
r.wg.Add(1)
go func() {
defer r.wg.Done()
ticker := time.NewTicker(r.cfg.HeartbeatInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
r.tick()
case <-r.stopCh:
return
}
}
}()
log.Printf("[cluster] started (node=%s, heartbeat=%s, stale=%s)",
r.nodeID, r.cfg.HeartbeatInterval, r.cfg.StaleThreshold)
return nil
}
// Stop deregisters the node and waits for the heartbeat goroutine to exit.
func (r *Registry) Stop() {
close(r.stopCh)
r.wg.Wait()
// Best-effort deregister so peers don't have to wait for stale sweep.
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if err := r.store.Deregister(ctx, r.nodeID); err != nil {
log.Printf("[cluster] deregister failed: %v", err)
}
log.Printf("[cluster] stopped (node=%s)", r.nodeID)
}
// tick runs one heartbeat + sweep cycle.
func (r *Registry) tick() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
stats := r.collectStats()
rows, err := r.store.Heartbeat(ctx, r.nodeID, stats)
if err != nil {
log.Printf("[cluster] heartbeat error: %v", err)
return
}
if rows == 0 {
// Self-eviction: this node was swept by a peer.
// Kubernetes will restart the process → re-register.
log.Printf("[cluster] FATAL: node %s evicted from registry — shutting down", r.nodeID)
os.Exit(1)
}
swept, err := r.store.SweepStale(ctx, r.cfg.StaleThreshold)
if err != nil {
log.Printf("[cluster] sweep error: %v", err)
return
}
if swept > 0 {
log.Printf("[cluster] swept %d stale node(s)", swept)
}
}
// collectStats gathers runtime metrics for the stats JSONB column.
func (r *Registry) collectStats() json.RawMessage {
var m runtime.MemStats
runtime.ReadMemStats(&m)
stats := map[string]any{
"goroutines": runtime.NumGoroutine(),
"heap_alloc": m.HeapAlloc,
"heap_sys": m.HeapSys,
"gc_cycles": m.NumGC,
"gc_pause_ns": m.PauseNs[(m.NumGC+255)%256],
"uptime_sec": time.Since(r.startTime).Seconds(),
"ws_clients": r.hub.ConnCount(),
}
data, _ := json.Marshal(stats)
return data
}