feat: production-grade routing cache + stale detection fixes

Three-tier routing cache (ESL global -> file -> HTTP) eliminates HTTP
from call path for 2500-5000 concurrent calls. Lua reads cached route
in ~0.1us instead of blocking on api:execute('curl', ...).

Engine fixes:
- recalcBestLocked now skips stale nodes (was 5 min bug -> now ~10-15s)
- PickNodeForCall action_type='node' checks staleness for consistency
- onMetric callback pushes cache on every metric (no ticker delay)

Config:
- stale_threshold_sec default 20 -> 10 (industry standard)
- contrib/ included in Makefile deploy target
- route.lua paths updated for /opt/pulse-lets-go
This commit is contained in:
Maksim Totmin
2026-06-25 22:23:16 +07:00
parent a7722af29e
commit 78785e54e1
11 changed files with 266 additions and 86 deletions
+2
View File
@@ -47,6 +47,8 @@ func (a *API) handleToggleNode(w http.ResponseWriter, r *http.Request) {
return
}
a.PushRouteCache()
info, _ := a.engine.GetNodeInfo(nodeID)
writeJSON(w, http.StatusOK, info)
}
+72
View File
@@ -1,8 +1,11 @@
package api
import (
"encoding/json"
"net/http"
"os"
"github.com/pulse-lets-go/internal/esl"
"github.com/pulse-lets-go/internal/models"
)
@@ -90,6 +93,45 @@ func (a *API) handleSetRouteMode(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"mode": req.Mode})
}
// GetBalanceGateway возвращает gateway для ноды из in-memory кэша (O(1)).
func (a *API) GetBalanceGateway(nodeID string) (string, bool) {
return a.cachedBalanceGateway(nodeID)
}
// GetFallbackGateway возвращает fallback gateway из in-memory кэша (O(1)).
func (a *API) GetFallbackGateway() string {
return a.cachedFallbackGateway()
}
// SetRouteCachePath устанавливает путь к файловому кэшу маршрута.
func (a *API) SetRouteCachePath(path string) {
a.routeCachePath = path
}
// PushRouteCache читает best-node из engine, резолвит gateway из trunk cache,
// атомарно пишет файловый кэш и пушит маршрут в FreeSWITCH через ESL.
func (a *API) PushRouteCache() {
nodeID, score, fallback := a.engine.GetBestNode()
var gw string
if nodeID != "" && !fallback {
gw, _ = a.cachedBalanceGateway(nodeID)
}
if gw == "" {
gw = a.cachedFallbackGateway()
}
entry := buildRouteCacheEntry(nodeID, gw, score, fallback)
if a.routeCachePath != "" {
writeRouteCacheFile(a.routeCachePath, entry)
}
if a.eslClient != nil && a.eslClient.IsConnected() {
esl.PushRoute(a.eslClient, entry)
}
}
// cachedBalanceGateway возвращает gateway для balance-транка из in-memory кэша (O(1)).
func (a *API) cachedBalanceGateway(nodeID string) (string, bool) {
a.trunkCacheMu.RLock()
@@ -105,6 +147,36 @@ func (a *API) cachedFallbackGateway() string {
return a.fallbackGateway
}
// buildRouteCacheEntry строит запись для кэширования в ESL global / файл.
func buildRouteCacheEntry(nodeID, gw string, score float64, fallback bool) esl.RouteCacheEntry {
entry := esl.RouteCacheEntry{
SIPGateway: gw,
Score: score,
Fallback: fallback,
}
if nodeID == "" {
entry.Error = "no_nodes_registered"
} else if fallback {
entry.Reason = "all_nodes_unhealthy"
} else {
entry.NodeID = nodeID
}
return entry
}
// writeRouteCacheFile атомарно записывает файловый кэш маршрута.
func writeRouteCacheFile(path string, entry esl.RouteCacheEntry) {
b, err := json.Marshal(entry)
if err != nil {
return
}
tmpPath := path + ".tmp"
if err := os.WriteFile(tmpPath, b, 0644); err != nil {
return
}
os.Rename(tmpPath, path)
}
// getRouteNodeInfo возвращает список нод с их скорами для ответа маршрутизации.
func (a *API) getRouteNodeInfo() []models.RouteNodeInfo {
nodes := a.engine.GetAllNodes()
+2
View File
@@ -34,6 +34,8 @@ type API struct {
gatewayStates map[string]string // trunkID → "up"/"down"
fsStats esl.FsStats
fsStatsMu sync.RWMutex
routeCachePath string // путь к файловому кэшу маршрута (для Lua)
}
// NewAPI создаёт новый HTTP API с заданными зависимостями.
+1 -1
View File
@@ -420,7 +420,7 @@ func (m *Manager) createDefaultConfig() error {
ListenAddr: ":8080",
JWTSecret: jwtSecret,
MonitoringAPIKey: apiKey,
StaleThresholdSec: 20,
StaleThresholdSec: 10,
Scoring: ScoringConfig{
IdleCPUMin: 5.0,
CallFailureRateLethal: 15.0,
+6
View File
@@ -456,12 +456,18 @@ func (e *Engine) scoreNodeLocked(ns *models.NodeState, firstMetric bool) {
// recalcBestLocked пересчитывает кэш лучшей ноды.
// Вызывающий держит write lock.
// Проверяет staleness (now - ns.TS > staleThreshold) — исключает ноды без свежих метрик.
func (e *Engine) recalcBestLocked() {
bestID := ""
bestScore := -999.0
anyHealthy := false
now := time.Now().Unix()
staleThreshold := int64(e.cfg.StaleThresholdSec)
for id, ns := range e.nodes {
if now-ns.TS > staleThreshold {
continue
}
if ns.Score >= 0 {
anyHealthy = true
}
+3 -1
View File
@@ -318,8 +318,10 @@ func (e *Engine) PickNodeForCall(callerID, dest, ingress string) (nodeID string,
case "node":
e.mu.RLock()
ns, ok := e.nodes[cr.ActionNodeID]
now := time.Now().Unix()
staleThreshold := int64(e.cfg.StaleThresholdSec)
e.mu.RUnlock()
if ok && ns.Score >= 0 {
if ok && ns.Score >= 0 && now-ns.TS <= staleThreshold {
nodeID, score, matchedRule = cr.ActionNodeID, 100, cr.Name
resolved = true
}
+36
View File
@@ -0,0 +1,36 @@
package esl
import (
"encoding/json"
"fmt"
"time"
)
// RouteCacheEntry — запись для кэширования маршрута в FS global variable и файле.
type RouteCacheEntry struct {
NodeID string `json:"node_id,omitempty"`
SIPGateway string `json:"sip_gateway,omitempty"`
Score float64 `json:"score,omitempty"`
Fallback bool `json:"fallback,omitempty"`
Reason string `json:"reason,omitempty"`
Error string `json:"error,omitempty"`
TS int64 `json:"ts"`
}
// PushRoute пушит текущий маршрут в FreeSWITCH через global variable.
// Если клиент не подключён — возвращает ошибку молча (вызывающий игнорирует).
func PushRoute(c *Client, entry RouteCacheEntry) error {
if c == nil || !c.IsConnected() {
return fmt.Errorf("esl не подключён")
}
entry.TS = time.Now().Unix()
jsonBytes, err := json.Marshal(entry)
if err != nil {
return fmt.Errorf("маршалинг route cache: %w", err)
}
cmd := fmt.Sprintf("api set_global pulse_route_json=%s", string(jsonBytes))
return c.SendAsync(cmd)
}
+10
View File
@@ -23,6 +23,7 @@ type Subscriber struct {
engine *engine.Engine
logger *filelog.Logger
onNewNode func(nodeID, sipGateway string) // вызывается при первой метрике от новой ноды
onMetric func() // вызывается после каждой обработанной метрики
wg sync.WaitGroup
}
@@ -63,6 +64,11 @@ func (s *Subscriber) SetOnNewNode(fn func(nodeID, sipGateway string)) {
s.onNewNode = fn
}
// SetOnMetric устанавливает callback, вызываемый после каждой обработанной метрики.
func (s *Subscriber) SetOnMetric(fn func()) {
s.onMetric = fn
}
// handleMetric — обработчик входящих сообщений NATS.
func (s *Subscriber) handleMetric(msg *natsgo.Msg) {
var metric models.NodeMetric
@@ -86,6 +92,10 @@ func (s *Subscriber) handleMetric(msg *natsgo.Msg) {
ns := s.engine.UpdateMetric(&metric)
s.logger.Log(ns)
if s.onMetric != nil {
s.onMetric()
}
// Авто-создание balance-транка для новой ноды
if isNew && metric.SIPGateway != "" && s.onNewNode != nil {
s.onNewNode(metric.NodeID, metric.SIPGateway)