Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

[MUL-6269] Use Redis for channel WebSocket leases (#7055)

Multica Eve2832f003aed5
diff --git a/.env.example b/.env.example
index efa93ad3ca..6860330dfd 100644
--- a/.env.example
+++ b/.env.example
@@ -321,6 +321,40 @@ CORS_ALLOWED_ORIGINS=
# command (e.g. GCP Memorystore, AWS ElastiCache with restricted ACLs).
# Default is false (client naming enabled for connection observability).
# REDIS_DISABLE_CLIENT_NAME=true
+
+# ==================== Channel WebSocket leases ====================
+# Multi-replica production should use Redis. The channel supervisor gets a
+# dedicated Redis client/pool and fails closed (does not start connections) if
+# its Redis URL, Ping, or the atomic lease scripts are unavailable at startup.
+# PostgreSQL remains available for self-hosted single-node use and rollback.
+# Switch every API replica together; there is intentionally no dual-lock mode.
+# CHANNEL_WS_LEASE_BACKEND=redis
+# Strongly recommended in production: point this at a lease-only Redis/Valkey
+# instance. When unset it falls back to REDIS_URL (acceptable for local/small
+# self-hosted deployments, but it shares memory and eviction policy with
+# caches, rate limits, and realtime state).
+# CHANNEL_WS_LEASE_REDIS_URL=redis://lease-redis:6379/0
+# REQUIRED operational policy for the lease instance: `maxmemory-policy
+# noeviction`. Enable HA plus persistence appropriate to the provider, and
+# alert on memory/capacity, evictions (must stay zero), availability, and
+# command latency. Silent lease-key eviction can interrupt channel connections.
+# Required in Redis mode. Use a stable deployment identifier so environments
+# sharing one Redis database never contend on each other's installation IDs.
+# Allowed characters: letters, digits, dot, underscore, hyphen.
+# CHANNEL_WS_LEASE_NAMESPACE=production
+# Lease timing must satisfy: 0 < poll <= renew < TTL.
+# CHANNEL_WS_LEASE_TTL=180s
+# CHANNEL_WS_LEASE_RENEW_INTERVAL=60s
+# CHANNEL_WS_LEASE_POLL_INTERVAL=30s
+# Redis errors retry quickly, but the owner disconnects before its last
+# confirmed TTL (minus the safety margin) to prevent split-brain.
+# CHANNEL_WS_LEASE_ERROR_RETRY_INTERVAL=5s
+# CHANNEL_WS_LEASE_EXPIRY_SAFETY_MARGIN=5s
+# The explicit PostgreSQL rollback backend restores correctness, not the Redis
+# load reduction: foreign owners still cause one SQL acquire attempt per poll.
+# It also uses the timing values above; set TTL=90s, renew=30s, poll=30s if the
+# previous PostgreSQL failover profile is required during rollback.
+
# Max requests per IP per minute. Defaults are 5 for send-code/google
# and 20 for verify-code.
# RATE_LIMIT_AUTH=5
diff --git a/server/cmd/server/channel_lease_config_test.go b/server/cmd/server/channel_lease_config_test.go
new file mode 100644
index 0000000000..d21fd54221
--- /dev/null
+++ b/server/cmd/server/channel_lease_config_test.go
@@ -0,0 +1,90 @@
+package main
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ redismock "github.com/go-redis/redismock/v9"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+)
+
+type channelLeaseTestStore struct{}
+
+func (channelLeaseTestStore) ListActiveInstallations(context.Context) ([]engine.Installation, error) {
+ return nil, nil
+}
+func (channelLeaseTestStore) ListHeldWSLeases(context.Context, []pgtype.UUID) (map[string]struct{}, error) {
+ return map[string]struct{}{}, nil
+}
+func (channelLeaseTestStore) TryAcquireWSLease(context.Context, engine.AcquireLeaseParams) error {
+ return nil
+}
+func (channelLeaseTestStore) RenewWSLease(context.Context, engine.AcquireLeaseParams) error {
+ return nil
+}
+func (channelLeaseTestStore) ReleaseWSLease(context.Context, engine.ReleaseLeaseParams) error {
+ return nil
+}
+
+func clearChannelLeaseTimingEnv(t *testing.T) {
+ t.Helper()
+ for _, name := range []string{
+ "CHANNEL_WS_LEASE_TTL",
+ "CHANNEL_WS_LEASE_RENEW_INTERVAL",
+ "CHANNEL_WS_LEASE_POLL_INTERVAL",
+ "CHANNEL_WS_LEASE_ERROR_RETRY_INTERVAL",
+ "CHANNEL_WS_LEASE_EXPIRY_SAFETY_MARGIN",
+ } {
+ t.Setenv(name, "")
+ }
+}
+
+func TestChannelSupervisorConfigDefaults(t *testing.T) {
+ clearChannelLeaseTimingEnv(t)
+ cfg, err := channelSupervisorConfigFromEnv(nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if cfg.LeaseTTL != 180*time.Second || cfg.LeaseRenewInterval != 60*time.Second || cfg.PollInterval != 30*time.Second {
+ t.Fatalf("unexpected defaults: ttl=%s renew=%s poll=%s", cfg.LeaseTTL, cfg.LeaseRenewInterval, cfg.PollInterval)
+ }
+}
+
+func TestChannelSupervisorConfigRejectsUnsafeRelation(t *testing.T) {
+ clearChannelLeaseTimingEnv(t)
+ t.Setenv("CHANNEL_WS_LEASE_POLL_INTERVAL", "90s")
+ if _, err := channelSupervisorConfigFromEnv(nil); err == nil {
+ t.Fatalf("poll > renew should fail closed")
+ }
+}
+
+func TestBuildChannelSupervisorRedisDoesNotFallbackWhenClientMissing(t *testing.T) {
+ clearChannelLeaseTimingEnv(t)
+ t.Setenv("CHANNEL_WS_LEASE_BACKEND", "redis")
+ t.Setenv("CHANNEL_WS_LEASE_NAMESPACE", "prod")
+ store := channelLeaseTestStore{}
+ sup := buildChannelSupervisor(store, store, channel.NewRegistry(), nil, RouterOptions{})
+ if sup != nil {
+ t.Fatalf("Redis mode without a client must disable the supervisor, not fall back to PostgreSQL")
+ }
+}
+
+func TestBuildChannelSupervisorRedisRequiresReadyBackend(t *testing.T) {
+ clearChannelLeaseTimingEnv(t)
+ t.Setenv("CHANNEL_WS_LEASE_BACKEND", "redis")
+ t.Setenv("CHANNEL_WS_LEASE_NAMESPACE", "prod")
+ rdb, mock := redismock.NewClientMock()
+ mock.ExpectPing().SetErr(context.DeadlineExceeded)
+ store := channelLeaseTestStore{}
+ sup := buildChannelSupervisor(store, store, channel.NewRegistry(), nil, RouterOptions{ChannelLeaseRedis: rdb})
+ if sup != nil {
+ t.Fatalf("unready Redis backend must disable the supervisor")
+ }
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index 6483771dfb..e8f1d7459f 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -51,6 +51,13 @@ func redisClientName(existing, suffix string) string {
return "multica-api:" + suffix
}
+func channelLeaseRedisURLFromEnv() string {
+ if dedicated := strings.TrimSpace(os.Getenv("CHANNEL_WS_LEASE_REDIS_URL")); dedicated != "" {
+ return dedicated
+ }
+ return strings.TrimSpace(os.Getenv("REDIS_URL"))
+}
+
func closeRedisClient(label string, client *redis.Client) {
if client == nil {
return
@@ -262,10 +269,12 @@ func main() {
// is the sole broadcaster and the server stays single-node (legacy).
// Runtime local-skill stores and realtime relay traffic use separate Redis
// clients so blocking stream consumers cannot starve request-path Redis
- // operations.
+ // operations. Channel leases are initialized separately below so production
+ // can point them at a dedicated no-eviction Redis instance.
relayCtx, relayCancel := context.WithCancel(context.Background())
var broadcaster realtime.Broadcaster = hub
var storeRedis *redis.Client
+ var channelLeaseRedis *redis.Client
var relayWriteRedis *redis.Client
var relayReadRedis *redis.Client
var shardedReadRedis *redis.Client
@@ -283,6 +292,7 @@ func main() {
closeRedisClient("realtime-read-sharded", shardedReadRedis)
closeRedisClient("realtime-read", relayReadRedis)
closeRedisClient("realtime-write", relayWriteRedis)
+ closeRedisClient("channel-lease", channelLeaseRedis)
closeRedisClient("store", storeRedis)
}()
if redisURL := os.Getenv("REDIS_URL"); redisURL != "" {
@@ -336,6 +346,16 @@ func main() {
} else {
slog.Info("realtime: REDIS_URL not set — using in-memory hub (single-node mode)")
}
+ if strings.EqualFold(strings.TrimSpace(os.Getenv("CHANNEL_WS_LEASE_BACKEND")), "redis") {
+ leaseRedisURL := channelLeaseRedisURLFromEnv()
+ if leaseRedisURL == "" {
+ slog.Error("channel leases: CHANNEL_WS_LEASE_REDIS_URL and REDIS_URL are unset")
+ } else if opts, err := redis.ParseURL(leaseRedisURL); err != nil {
+ slog.Error("channel leases: invalid Redis URL; supervisor will fail closed", "error", err)
+ } else {
+ channelLeaseRedis = newNamedRedisClient(opts, "channel-lease")
+ }
+ }
registerListeners(bus, broadcaster)
analyticsClient := analytics.NewFromEnv()
@@ -356,6 +376,7 @@ func main() {
var businessMetrics *obsmetrics.BusinessMetrics
var samplerPool *pgxpool.Pool
var channelMediaMetrics *obsmetrics.ChannelMediaReconcilerMetrics
+ var channelLeaseMetrics *obsmetrics.ChannelLeaseMetrics
var wecomMetrics *obsmetrics.WecomMetrics
if metricsConfig.Enabled() {
// Build a dedicated tiny pool for the BusinessSamplerCollector
@@ -385,6 +406,7 @@ func main() {
httpMetrics = metricsRegistry.HTTP
businessMetrics = metricsRegistry.Business
channelMediaMetrics = metricsRegistry.ChannelMedia
+ channelLeaseMetrics = metricsRegistry.ChannelLease
wecomMetrics = metricsRegistry.Wecom
// Forward inbound daemon WS frames into the per-kind counter so
// dashboards can split heartbeat / unknown / invalid traffic.
@@ -410,13 +432,15 @@ func main() {
heartbeatScheduler := handler.NewBatchedHeartbeatScheduler(queries, handler.DefaultHeartbeatBatchInterval)
r, h := NewRouterWithOptions(pool, hub, bus, analyticsClient, storeRedis, RouterOptions{
- HTTPMetrics: httpMetrics,
- BusinessMetrics: businessMetrics,
- WecomMetrics: wecomMetrics,
- DaemonHub: daemonHub,
- DaemonWakeup: daemonWakeup,
- FeatureFlags: flags,
- HeartbeatScheduler: heartbeatScheduler,
+ HTTPMetrics: httpMetrics,
+ BusinessMetrics: businessMetrics,
+ ChannelLeaseMetrics: channelLeaseMetrics,
+ ChannelLeaseRedis: channelLeaseRedis,
+ WecomMetrics: wecomMetrics,
+ DaemonHub: daemonHub,
+ DaemonWakeup: daemonWakeup,
+ FeatureFlags: flags,
+ HeartbeatScheduler: heartbeatScheduler,
})
srv := &http.Server{
@@ -457,10 +481,10 @@ func main() {
h.PRRefresh.Start(sweepCtx)
// Channel inbound supervisor (MUL-3620): holds the §4.4 WS lease per
- // installation and drives each channel.Channel. It is built
- // unconditionally (it is channel-agnostic, not Lark-specific), so it
- // always exists here; with no platform registered or no installation
- // rows it simply idles. Lifecycle is bound to sweepCtx so it winds down
+ // installation and drives each channel.Channel. It is channel-agnostic,
+ // not Lark-specific, but remains nil when lease startup validation fails
+ // (notably Redis fail-closed readiness). With no platform registered or no
+ // installation rows it simply idles. Lifecycle is bound to sweepCtx so it winds down
// alongside the other long-running workers, AFTER the HTTP server has
// drained.
if h.ChannelSupervisor != nil {
diff --git a/server/cmd/server/main_test.go b/server/cmd/server/main_test.go
index 9d5908d740..0ca254994b 100644
--- a/server/cmd/server/main_test.go
+++ b/server/cmd/server/main_test.go
@@ -39,6 +39,22 @@ func TestRedisClientName(t *testing.T) {
}
}
+func TestChannelLeaseRedisURLFromEnvPrefersDedicatedInstance(t *testing.T) {
+ t.Setenv("REDIS_URL", "redis://shared:6379/0")
+ t.Setenv("CHANNEL_WS_LEASE_REDIS_URL", "redis://leases:6379/0")
+ if got := channelLeaseRedisURLFromEnv(); got != "redis://leases:6379/0" {
+ t.Fatalf("channel lease Redis URL = %q", got)
+ }
+}
+
+func TestChannelLeaseRedisURLFromEnvFallsBackToSharedRedis(t *testing.T) {
+ t.Setenv("REDIS_URL", "redis://shared:6379/0")
+ t.Setenv("CHANNEL_WS_LEASE_REDIS_URL", "")
+ if got := channelLeaseRedisURLFromEnv(); got != "redis://shared:6379/0" {
+ t.Fatalf("channel lease Redis URL = %q", got)
+ }
+}
+
func TestNewNamedRedisClient_SetsClientName(t *testing.T) {
t.Setenv("REDIS_DISABLE_CLIENT_NAME", "")
base := &redis.Options{Addr: "localhost:6379"}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 9d5eedd279..b93a955717 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -3,6 +3,7 @@ package main
import (
"context"
"crypto/sha256"
+ "fmt"
"log/slog"
"net/http"
"net/netip"
@@ -173,8 +174,12 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus, analytics
}
type RouterOptions struct {
- HTTPMetrics *obsmetrics.HTTPMetrics
- BusinessMetrics *obsmetrics.BusinessMetrics
+ HTTPMetrics *obsmetrics.HTTPMetrics
+ BusinessMetrics *obsmetrics.BusinessMetrics
+ ChannelLeaseMetrics *obsmetrics.ChannelLeaseMetrics
+ // ChannelLeaseRedis is a dedicated non-blocking Redis client/pool. It is
+ // required only when CHANNEL_WS_LEASE_BACKEND=redis.
+ ChannelLeaseRedis *redis.Client
// WecomMetrics is the WeCom adapter's health sink. Nil discards every
// counter, which is what a deployment with /metrics turned off gets.
WecomMetrics *obsmetrics.WecomMetrics
@@ -188,6 +193,108 @@ type RouterOptions struct {
HeartbeatScheduler handler.HeartbeatScheduler
}
+func buildChannelSupervisor(
+ installations engine.InstallationStore,
+ postgresLeases engine.LeaseStore,
+ registry *channel.Registry,
+ inbound channel.InboundHandler,
+ opts RouterOptions,
+) *engine.Supervisor {
+ cfg, err := channelSupervisorConfigFromEnv(opts.ChannelLeaseMetrics)
+ if err != nil {
+ slog.Error("channel engine: invalid lease configuration; supervisor disabled", "error", err)
+ return nil
+ }
+
+ backend := strings.ToLower(strings.TrimSpace(os.Getenv("CHANNEL_WS_LEASE_BACKEND")))
+ if backend == "" {
+ backend = "postgres"
+ }
+ var leases engine.LeaseStore
+ switch backend {
+ case "postgres":
+ leases = postgresLeases
+ case "redis":
+ if opts.ChannelLeaseRedis == nil {
+ slog.Error("channel engine: Redis lease backend selected but CHANNEL_WS_LEASE_REDIS_URL/REDIS_URL is missing or invalid; supervisor disabled")
+ return nil
+ }
+ namespace := strings.TrimSpace(os.Getenv("CHANNEL_WS_LEASE_NAMESPACE"))
+ redisLeases, err := engine.NewRedisLeaseStore(opts.ChannelLeaseRedis, namespace)
+ if err != nil {
+ slog.Error("channel engine: Redis lease configuration invalid; supervisor disabled", "error", err)
+ return nil
+ }
+ readyCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ err = redisLeases.Ready(readyCtx)
+ cancel()
+ if err != nil {
+ slog.Error("channel engine: Redis lease backend unavailable; supervisor disabled", "error", err)
+ return nil
+ }
+ leases = redisLeases
+ default:
+ slog.Error("channel engine: unsupported CHANNEL_WS_LEASE_BACKEND; supervisor disabled", "backend", backend)
+ return nil
+ }
+
+ slog.Info("channel engine: lease backend configured",
+ "backend", backend,
+ "ttl", cfg.LeaseTTL.String(),
+ "renew_interval", cfg.LeaseRenewInterval.String(),
+ "poll_interval", cfg.PollInterval.String(),
+ )
+ return engine.NewSupervisor(installations, leases, registry, inbound, cfg)
+}
+
+func channelSupervisorConfigFromEnv(leaseMetrics *obsmetrics.ChannelLeaseMetrics) (engine.Config, error) {
+ ttl, err := strictPositiveDurationEnv("CHANNEL_WS_LEASE_TTL", 180*time.Second)
+ if err != nil {
+ return engine.Config{}, err
+ }
+ renew, err := strictPositiveDurationEnv("CHANNEL_WS_LEASE_RENEW_INTERVAL", 60*time.Second)
+ if err != nil {
+ return engine.Config{}, err
+ }
+ poll, err := strictPositiveDurationEnv("CHANNEL_WS_LEASE_POLL_INTERVAL", 30*time.Second)
+ if err != nil {
+ return engine.Config{}, err
+ }
+ retry, err := strictPositiveDurationEnv("CHANNEL_WS_LEASE_ERROR_RETRY_INTERVAL", 5*time.Second)
+ if err != nil {
+ return engine.Config{}, err
+ }
+ margin, err := strictPositiveDurationEnv("CHANNEL_WS_LEASE_EXPIRY_SAFETY_MARGIN", 5*time.Second)
+ if err != nil {
+ return engine.Config{}, err
+ }
+ cfg := engine.Config{
+ LeaseTTL: ttl,
+ LeaseRenewInterval: renew,
+ PollInterval: poll,
+ LeaseErrorRetryInterval: retry,
+ LeaseExpirySafetyMargin: margin,
+ LeaseMetrics: leaseMetrics,
+ Logger: slog.Default(),
+ }
+ if err := cfg.Validate(); err != nil {
+ return engine.Config{}, err
+ }
+ return cfg, nil
+}
+
+func strictPositiveDurationEnv(name string, fallback time.Duration) (time.Duration, error) {
+ raw := strings.TrimSpace(os.Getenv(name))
+ if raw == "" {
+ return fallback, nil
+ }
+ value, err := time.ParseDuration(raw)
+ if err != nil || value <= 0 {
+ return 0, fmt.Errorf("%s must be a positive duration (got %q)", name, raw)
+ }
+ return value, nil
+}
+
// NewRouterWithOptions builds the fully-configured Chi router and
// returns the *handler.Handler it was constructed from. Callers that
// need to drive background lifecycle on services attached to the
@@ -312,11 +419,13 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
Logger: slog.Default(),
}
}
- h.ChannelSupervisor = engine.NewSupervisor(
- lark.NewChannelInstallationStore(queries),
+ installationStore := lark.NewChannelInstallationStore(queries)
+ h.ChannelSupervisor = buildChannelSupervisor(
+ installationStore,
+ installationStore,
channelRegistry,
channelRouter.Handle,
- engine.Config{},
+ opts,
)
// Lark integration. Only wired when MULTICA_LARK_SECRET_KEY is set:
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index 7523db16d8..61b099269d 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -230,9 +230,10 @@ type Handler struct {
// ChannelSupervisor owns the per-installation supervisor goroutines
// that hold the §4.4 WS lease and drive each channel.Channel
// (MUL-3620 generalized the Feishu-only Hub into this channel-agnostic
- // engine). The router constructs it UNCONDITIONALLY — it drives any
- // channel type, not just Feishu, so it does not depend on the Lark
- // master key; each platform registers its Factory only when configured
+ // engine). The router constructs it independently of platform secrets — it
+ // drives any channel type, not just Feishu. It remains nil when lease
+ // configuration is unsafe or a selected Redis backend fails its startup
+ // readiness check; each platform registers its Factory only when configured
// (Feishu when MULTICA_LARK_SECRET_KEY is set). The router does NOT
// call Run; the process owner (main.go) starts it under a long-running
// context and joins via WaitWithTimeout (bounded, fenced by
diff --git a/server/internal/integrations/channel/engine/redis_lease_store.go b/server/internal/integrations/channel/engine/redis_lease_store.go
new file mode 100644
index 0000000000..6e5fefcc86
--- /dev/null
+++ b/server/internal/integrations/channel/engine/redis_lease_store.go
@@ -0,0 +1,162 @@
+package engine
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "regexp"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/redis/go-redis/v9"
+)
+
+const redisLeaseKeyPrefix = "multica:channel-lease:v1:"
+
+var leaseNamespacePattern = regexp.MustCompile(`^[A-Za-z0-9._-]+$`)
+
+const redisTryAcquireLeaseSource = `
+local current = redis.call('GET', KEYS[1])
+if (not current) or current == ARGV[1] then
+ redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2])
+ return 1
+end
+return 0
+`
+
+const redisRenewLeaseSource = `
+if redis.call('GET', KEYS[1]) == ARGV[1] then
+ return redis.call('PEXPIRE', KEYS[1], ARGV[2])
+end
+return 0
+`
+
+const redisReleaseLeaseSource = `
+if redis.call('GET', KEYS[1]) == ARGV[1] then
+ return redis.call('DEL', KEYS[1])
+end
+return 0
+`
+
+var redisTryAcquireLease = redis.NewScript(redisTryAcquireLeaseSource)
+var redisRenewLease = redis.NewScript(redisRenewLeaseSource)
+var redisReleaseLease = redis.NewScript(redisReleaseLeaseSource)
+
+// RedisLeaseStore implements token-fenced channel leases in a dedicated Redis
+// client/pool. Every mutation is a single Lua operation, so compare + expiry
+// update/delete cannot be interleaved by another replica.
+type RedisLeaseStore struct {
+ client *redis.Client
+ namespace string
+}
+
+func NewRedisLeaseStore(client *redis.Client, namespace string) (*RedisLeaseStore, error) {
+ if client == nil {
+ return nil, errors.New("channel lease redis client is nil")
+ }
+ if !leaseNamespacePattern.MatchString(namespace) {
+ return nil, errors.New("CHANNEL_WS_LEASE_NAMESPACE must match [A-Za-z0-9._-]+")
+ }
+ return &RedisLeaseStore{client: client, namespace: namespace}, nil
+}
+
+// Ready verifies connectivity and preloads every lease script. Redis-backed
+// startup is fail-closed: callers must not start the Supervisor if this fails.
+func (s *RedisLeaseStore) Ready(ctx context.Context) error {
+ if err := s.client.Ping(ctx).Err(); err != nil {
+ return fmt.Errorf("ping: %w", err)
+ }
+ for _, item := range []struct {
+ name string
+ script *redis.Script
+ }{
+ {name: "try_acquire", script: redisTryAcquireLease},
+ {name: "renew", script: redisRenewLease},
+ {name: "release", script: redisReleaseLease},
+ } {
+ if err := item.script.Load(ctx, s.client).Err(); err != nil {
+ return fmt.Errorf("load %s script: %w", item.name, err)
+ }
+ }
+ readyKey := redisLeaseKeyPrefix + s.namespace + ":__ready__:" + newNodeID()
+ const readyToken = "readiness-check"
+ for _, item := range []struct {
+ name string
+ script *redis.Script
+ args []any
+ }{
+ {name: "try_acquire", script: redisTryAcquireLease, args: []any{readyToken, int64(5000)}},
+ {name: "renew", script: redisRenewLease, args: []any{readyToken, int64(5000)}},
+ {name: "release", script: redisReleaseLease, args: []any{readyToken}},
+ } {
+ result, err := item.script.Run(ctx, s.client, []string{readyKey}, item.args...).Int64()
+ if err != nil {
+ return fmt.Errorf("execute %s script: %w", item.name, err)
+ }
+ if result != 1 {
+ return fmt.Errorf("execute %s script: unexpected result %d", item.name, result)
+ }
+ }
+ return nil
+}
+
+func (s *RedisLeaseStore) ListHeldWSLeases(ctx context.Context, ids []pgtype.UUID) (map[string]struct{}, error) {
+ held := make(map[string]struct{}, len(ids))
+ if len(ids) == 0 {
+ return held, nil
+ }
+ keys := make([]string, len(ids))
+ for i, id := range ids {
+ keys[i] = s.key(id)
+ }
+ // RedisLeaseStore intentionally takes *redis.Client (standalone/sentinel),
+ // not ClusterClient. A future cluster-mode implementation must group keys by
+ // hash slot or pipeline individual GETs; cross-slot MGET is not valid.
+ values, err := s.client.MGet(ctx, keys...).Result()
+ if err != nil {
+ return nil, err
+ }
+ for i, value := range values {
+ if value != nil {
+ held[uuidString(ids[i])] = struct{}{}
+ }
+ }
+ return held, nil
+}
+
+func (s *RedisLeaseStore) TryAcquireWSLease(ctx context.Context, arg AcquireLeaseParams) error {
+ return s.runLeaseScript(ctx, redisTryAcquireLease, arg)
+}
+
+func (s *RedisLeaseStore) RenewWSLease(ctx context.Context, arg AcquireLeaseParams) error {
+ return s.runLeaseScript(ctx, redisRenewLease, arg)
+}
+
+func (s *RedisLeaseStore) ReleaseWSLease(ctx context.Context, arg ReleaseLeaseParams) error {
+ _, err := redisReleaseLease.Run(ctx, s.client, []string{s.key(arg.ID)}, arg.Token).Int64()
+ if err != nil {
+ return err
+ }
+ // A stale token returns 0 and is an intentional fenced no-op.
+ return nil
+}
+
+func (s *RedisLeaseStore) runLeaseScript(ctx context.Context, script *redis.Script, arg AcquireLeaseParams) error {
+ ttlMillis := arg.TTL.Milliseconds()
+ if ttlMillis <= 0 {
+ return errors.New("channel lease TTL must be at least 1ms")
+ }
+ result, err := script.Run(ctx, s.client, []string{s.key(arg.ID)}, arg.Token, ttlMillis).Int64()
+ if err != nil {
+ return err
+ }
+ if result == 0 {
+ return ErrLeaseNotAcquired
+ }
+ return nil
+}
+
+func (s *RedisLeaseStore) key(id pgtype.UUID) string {
+ return redisLeaseKeyPrefix + s.namespace + ":" + uuidString(id)
+}
+
+var _ LeaseStore = (*RedisLeaseStore)(nil)
diff --git a/server/internal/integrations/channel/engine/redis_lease_store_test.go b/server/internal/integrations/channel/engine/redis_lease_store_test.go
new file mode 100644
index 0000000000..6e799b22c1
--- /dev/null
+++ b/server/internal/integrations/channel/engine/redis_lease_store_test.go
@@ -0,0 +1,96 @@
+package engine
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+
+ redismock "github.com/go-redis/redismock/v9"
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+func TestRedisLeaseStoreRequiresSafeNamespace(t *testing.T) {
+ rdb, _ := redismock.NewClientMock()
+ for _, namespace := range []string{"", "prod:blue", "prod blue"} {
+ if _, err := NewRedisLeaseStore(rdb, namespace); err == nil {
+ t.Fatalf("namespace %q should be rejected", namespace)
+ }
+ }
+ if _, err := NewRedisLeaseStore(rdb, "prod-blue_1.eu"); err != nil {
+ t.Fatalf("valid namespace rejected: %v", err)
+ }
+}
+
+func TestRedisLeaseStoreReadyPingsAndLoadsScripts(t *testing.T) {
+ rdb, mock := redismock.NewClientMock()
+ store, err := NewRedisLeaseStore(rdb, "prod")
+ if err != nil {
+ t.Fatal(err)
+ }
+ mock.ExpectPing().SetVal("PONG")
+ mock.ExpectScriptLoad(redisTryAcquireLeaseSource).SetVal(redisTryAcquireLease.Hash())
+ mock.ExpectScriptLoad(redisRenewLeaseSource).SetVal(redisRenewLease.Hash())
+ mock.ExpectScriptLoad(redisReleaseLeaseSource).SetVal(redisReleaseLease.Hash())
+ mock.Regexp().ExpectEvalSha(redisTryAcquireLease.Hash(), []string{`multica:channel-lease:v1:prod:__ready__:.+`}, "readiness-check", int64(5000)).SetVal(int64(1))
+ mock.Regexp().ExpectEvalSha(redisRenewLease.Hash(), []string{`multica:channel-lease:v1:prod:__ready__:.+`}, "readiness-check", int64(5000)).SetVal(int64(1))
+ mock.Regexp().ExpectEvalSha(redisReleaseLease.Hash(), []string{`multica:channel-lease:v1:prod:__ready__:.+`}, "readiness-check").SetVal(int64(1))
+ if err := store.Ready(context.Background()); err != nil {
+ t.Fatalf("Ready: %v", err)
+ }
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestRedisLeaseStoreAtomicOperationsAreTokenFenced(t *testing.T) {
+ rdb, mock := redismock.NewClientMock()
+ store, err := NewRedisLeaseStore(rdb, "prod")
+ if err != nil {
+ t.Fatal(err)
+ }
+ id := uuidFromString(t, "12121212-1212-1212-1212-121212121212")
+ key := "multica:channel-lease:v1:prod:12121212-1212-1212-1212-121212121212"
+ arg := AcquireLeaseParams{ID: id, Token: "node-g1", TTL: 180 * time.Second}
+
+ mock.ExpectEvalSha(redisTryAcquireLease.Hash(), []string{key}, "node-g1", int64(180000)).SetVal(int64(1))
+ if err := store.TryAcquireWSLease(context.Background(), arg); err != nil {
+ t.Fatalf("TryAcquireWSLease: %v", err)
+ }
+ mock.ExpectEvalSha(redisRenewLease.Hash(), []string{key}, "node-g1", int64(180000)).SetVal(int64(1))
+ if err := store.RenewWSLease(context.Background(), arg); err != nil {
+ t.Fatalf("RenewWSLease: %v", err)
+ }
+ mock.ExpectEvalSha(redisRenewLease.Hash(), []string{key}, "node-g1", int64(180000)).SetVal(int64(0))
+ if err := store.RenewWSLease(context.Background(), arg); !errors.Is(err, ErrLeaseNotAcquired) {
+ t.Fatalf("mismatched renewal error = %v, want ErrLeaseNotAcquired", err)
+ }
+ mock.ExpectEvalSha(redisReleaseLease.Hash(), []string{key}, "node-g1").SetVal(int64(0))
+ if err := store.ReleaseWSLease(context.Background(), ReleaseLeaseParams{ID: id, Token: "node-g1"}); err != nil {
+ t.Fatalf("stale release should be a fenced no-op: %v", err)
+ }
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestRedisLeaseStoreListsOnlyHeldKeys(t *testing.T) {
+ rdb, mock := redismock.NewClientMock()
+ store, err := NewRedisLeaseStore(rdb, "prod")
+ if err != nil {
+ t.Fatal(err)
+ }
+ id1 := uuidFromString(t, "13131313-1313-1313-1313-131313131313")
+ id2 := uuidFromString(t, "14141414-1414-1414-1414-141414141414")
+ mock.ExpectMGet(store.key(id1), store.key(id2)).SetVal([]interface{}{"owner", nil})
+ held, err := store.ListHeldWSLeases(context.Background(), []pgtype.UUID{id1, id2})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := held[uuidString(id1)]; !ok {
+ t.Fatalf("first ID should be held: %#v", held)
+ }
+ if _, ok := held[uuidString(id2)]; ok {
+ t.Fatalf("second ID should be absent: %#v", held)
+ }
+}
diff --git a/server/internal/integrations/channel/engine/supervisor.go b/server/internal/integrations/channel/engine/supervisor.go
index e5fe9092b3..f9a2ff1558 100644
--- a/server/internal/integrations/channel/engine/supervisor.go
+++ b/server/internal/integrations/channel/engine/supervisor.go
@@ -56,6 +56,7 @@ type AcquireLeaseParams struct {
ID pgtype.UUID
Token string
ExpiresAt time.Time
+ TTL time.Duration
}
// ReleaseLeaseParams releases a WS supervisor lease the caller still
@@ -66,31 +67,51 @@ type ReleaseLeaseParams struct {
Token string
}
-// ErrLeaseNotAcquired is the sentinel a store returns from AcquireWSLease
+// ErrLeaseNotAcquired is the sentinel a store returns from TryAcquireWSLease
// when the CAS predicate did not match — i.e. another replica (or an
// in-process predecessor mid-rotation) holds a live lease. The Supervisor
// treats it as "not ours yet, retry later", distinct from a transport
// error. Stores wrap their backend's no-rows signal into this.
var ErrLeaseNotAcquired = errors.New("engine: ws lease held elsewhere")
-// InstallationStore is the narrow data seam the Supervisor needs:
-// enumerate active installations across every channel type and manage the
-// per-installation WS lease. The application backs it with the generalized
-// channel_* tables; tests substitute a fake.
+// InstallationStore enumerates active installations across every channel
+// type. LeaseStore is deliberately separate so production can keep
+// installation metadata in PostgreSQL while using Redis for low-churn leases.
type InstallationStore interface {
// ListActiveInstallations returns every active installation across ALL
// channel types. There is no per-platform filter here — that hard-coded
// "feishu" was the whole limitation MUL-3620 removes.
ListActiveInstallations(ctx context.Context) ([]Installation, error)
+}
+
+// LeaseStore owns the token-fenced, per-installation WebSocket leases.
+type LeaseStore interface {
+ // ListHeldWSLeases returns the IDs that currently have any live owner.
+ // It is a sweep optimization only; TryAcquireWSLease remains the authority.
+ ListHeldWSLeases(ctx context.Context, ids []pgtype.UUID) (map[string]struct{}, error)
- // AcquireWSLease grants or renews the lease, or returns
- // ErrLeaseNotAcquired when it is held elsewhere.
- AcquireWSLease(ctx context.Context, arg AcquireLeaseParams) error
+ // TryAcquireWSLease grants when the lease is absent or already carries the
+ // same token (safe retry after an uncertain response); otherwise it returns
+ // ErrLeaseNotAcquired.
+ TryAcquireWSLease(ctx context.Context, arg AcquireLeaseParams) error
- // ReleaseWSLease releases a lease the caller holds (token-fenced).
+ // RenewWSLease extends only a lease whose current value equals Token.
+ // ErrLeaseNotAcquired means ownership has been lost.
+ RenewWSLease(ctx context.Context, arg AcquireLeaseParams) error
+
+ // ReleaseWSLease deletes only a lease whose current value equals Token.
ReleaseWSLease(ctx context.Context, arg ReleaseLeaseParams) error
}
+// LeaseMetrics is the optional, backend-agnostic observability seam.
+type LeaseMetrics interface {
+ RecordLeaseOperation(operation, outcome string)
+ SetActiveLeaseOwners(count float64)
+ SetOwnersWithRenewalErrors(count float64)
+ SetLastSuccessfulRenewal(at time.Time)
+ ObserveTakeoverLatency(delay time.Duration)
+}
+
// Config tunes the Supervisor's lifecycle loops. All fields have sensible
// production defaults via withDefaults; tests typically set Now and Logger
// to inject determinism.
@@ -109,6 +130,13 @@ type Config struct {
// take over (new ones, or ones whose lease expired on another replica).
PollInterval time.Duration
+ // LeaseErrorRetryInterval is the fast retry cadence after a renewal
+ // transport error. LeaseExpirySafetyMargin is subtracted from the last
+ // confirmed TTL so a partitioned owner disconnects before Redis can grant
+ // a successor.
+ LeaseErrorRetryInterval time.Duration
+ LeaseExpirySafetyMargin time.Duration
+
// MinBackoff / MaxBackoff bound the per-installation reconnect
// schedule: start at MinBackoff, double after each consecutive failure
// (capped at MaxBackoff), reset on any connection that lived at least
@@ -128,6 +156,12 @@ type Config struct {
// connection ends, for the same reason as LeaseReleaseTimeout.
DisconnectTimeout time.Duration
+ // RotationWaitTimeout bounds how long one sweep waits for all cancelled
+ // credential-rotation predecessors to disconnect and release their leases.
+ // A single shared deadline covers the whole batch, so many simultaneous
+ // rotations cannot stall a sweep for N times this duration.
+ RotationWaitTimeout time.Duration
+
// ShutdownTimeout bounds how long Wait blocks for supervisor goroutines
// after their parent ctx is cancelled. Wait itself does not enforce it;
// callers pass it to WaitWithTimeout. Exposed so boot and tests share a
@@ -140,17 +174,26 @@ type Config struct {
// Logger optional; defaults to slog.Default.
Logger *slog.Logger
+
+ // LeaseMetrics is optional; nil disables Prometheus recording.
+ LeaseMetrics LeaseMetrics
}
func (c Config) withDefaults() Config {
if c.LeaseTTL == 0 {
- c.LeaseTTL = 90 * time.Second
+ c.LeaseTTL = 180 * time.Second
}
if c.LeaseRenewInterval == 0 {
- c.LeaseRenewInterval = 30 * time.Second
+ c.LeaseRenewInterval = min(60*time.Second, c.LeaseTTL/3)
}
if c.PollInterval == 0 {
- c.PollInterval = 30 * time.Second
+ c.PollInterval = min(30*time.Second, c.LeaseRenewInterval/2)
+ }
+ if c.LeaseErrorRetryInterval == 0 {
+ c.LeaseErrorRetryInterval = min(5*time.Second, c.LeaseRenewInterval/4)
+ }
+ if c.LeaseExpirySafetyMargin == 0 {
+ c.LeaseExpirySafetyMargin = min(5*time.Second, c.LeaseTTL/10)
}
if c.MinBackoff == 0 {
c.MinBackoff = 2 * time.Second
@@ -167,6 +210,9 @@ func (c Config) withDefaults() Config {
if c.DisconnectTimeout == 0 {
c.DisconnectTimeout = 5 * time.Second
}
+ if c.RotationWaitTimeout == 0 {
+ c.RotationWaitTimeout = c.DisconnectTimeout + c.LeaseReleaseTimeout
+ }
if c.ShutdownTimeout == 0 {
c.ShutdownTimeout = 15 * time.Second
}
@@ -176,9 +222,34 @@ func (c Config) withDefaults() Config {
if c.Logger == nil {
c.Logger = slog.Default()
}
+ if err := c.Validate(); err != nil {
+ panic(err)
+ }
return c
}
+// Validate enforces the timing invariant required for safe fail-closed lease
+// renewal. Callers parsing deployment config can use it before constructing a
+// Supervisor; NewSupervisor also rejects invalid programmatic configs.
+func (c Config) Validate() error {
+ if c.PollInterval <= 0 || c.LeaseRenewInterval <= 0 || c.LeaseTTL <= 0 {
+ return errors.New("channel engine: lease intervals must be positive")
+ }
+ if c.PollInterval > c.LeaseRenewInterval || c.LeaseRenewInterval >= c.LeaseTTL {
+ return fmt.Errorf("channel engine: require poll <= renew < ttl (poll=%s renew=%s ttl=%s)", c.PollInterval, c.LeaseRenewInterval, c.LeaseTTL)
+ }
+ if c.LeaseErrorRetryInterval <= 0 {
+ return errors.New("channel engine: lease error retry interval must be positive")
+ }
+ if c.LeaseExpirySafetyMargin <= 0 || c.LeaseExpirySafetyMargin >= c.LeaseTTL-c.LeaseRenewInterval {
+ return fmt.Errorf("channel engine: lease expiry safety margin must be positive and less than ttl-renew (margin=%s)", c.LeaseExpirySafetyMargin)
+ }
+ if c.RotationWaitTimeout < 0 {
+ return errors.New("channel engine: rotation wait timeout cannot be negative")
+ }
+ return nil
+}
+
// Supervisor owns the per-installation supervisor goroutines that keep a
// long-running connection per active installation, across every channel
// type. It enforces the multi-replica safety rule via the WS lease CAS —
@@ -192,15 +263,16 @@ func (c Config) withDefaults() Config {
//
// Lifecycle:
//
-// sup := NewSupervisor(store, registry, handler, engine.Config{})
+// sup := NewSupervisor(installations, leases, registry, handler, engine.Config{})
// go sup.Run(ctx) // returns when ctx is cancelled
// ... ctx cancellation triggers ...
// sup.Wait() // joins on every per-installation goroutine
type Supervisor struct {
- store InstallationStore
- registry *channel.Registry
- handler channel.InboundHandler
- cfg Config
+ store InstallationStore
+ leaseStore LeaseStore
+ registry *channel.Registry
+ handler channel.InboundHandler
+ cfg Config
// nodeID is the per-process lease ownership token. AcquireWSLease
// treats matching tokens as "this is us, renew", so a stable nodeID
@@ -214,6 +286,14 @@ type Supervisor struct {
// next sweep tears the connection down and rebuilds it with fresh
// credentials.
supervisors map[string]supervisorEntry
+ // contendedSince tracks when this node first observed a foreign owner so
+ // successful expiry takeover latency can be measured without per-ID labels.
+ contendedSince map[string]time.Time
+ activeOwners int
+ // renewalErrors is a bounded set (active local owners only) used to expose
+ // partial renewal failure that a process-wide "last success" timestamp can
+ // otherwise hide when some other installation remains healthy.
+ renewalErrors map[string]struct{}
// supervisorGen is the source of the monotonic gen counter stored on
// each entry. Bumped under mu when a new entry is minted (initial start
// or rotation restart).
@@ -232,26 +312,42 @@ type Supervisor struct {
// path already swapped in.
type supervisorEntry struct {
cancel context.CancelFunc
+ done <-chan struct{}
fingerprint string
gen uint64
}
+type leaseCandidate struct {
+ installation Installation
+ // localRotation suppresses takeover-latency accounting if the candidate is
+ // still blocked by this process's own predecessor after the bounded wait.
+ localRotation bool
+}
+
+type rotationWait struct {
+ installationID string
+ done <-chan struct{}
+}
+
// NewSupervisor constructs a Supervisor bound to the supplied store,
// channel registry, and shared inbound handler. The handler is injected
// into every Channel the Supervisor builds (via channel.Config.Handler) so
// the inbound pipeline is written once and shared across platforms. The
// Supervisor starts no goroutines until Run is called. A nil registry or
// store is a programming error and will panic at Run.
-func NewSupervisor(store InstallationStore, registry *channel.Registry, handler channel.InboundHandler, cfg Config) *Supervisor {
+func NewSupervisor(store InstallationStore, leaseStore LeaseStore, registry *channel.Registry, handler channel.InboundHandler, cfg Config) *Supervisor {
cfg = cfg.withDefaults()
return &Supervisor{
- store: store,
- registry: registry,
- handler: handler,
- cfg: cfg,
- nodeID: newNodeID(),
- supervisors: make(map[string]supervisorEntry),
- stopChan: make(chan struct{}),
+ store: store,
+ leaseStore: leaseStore,
+ registry: registry,
+ handler: handler,
+ cfg: cfg,
+ nodeID: newNodeID(),
+ supervisors: make(map[string]supervisorEntry),
+ contendedSince: make(map[string]time.Time),
+ renewalErrors: make(map[string]struct{}),
+ stopChan: make(chan struct{}),
}
}
@@ -344,6 +440,9 @@ func (s *Supervisor) sweep(ctx context.Context) {
return
}
active := make(map[string]struct{}, len(rows))
+ candidates := make([]leaseCandidate, 0, len(rows))
+ candidateIDs := make([]pgtype.UUID, 0, len(rows))
+ rotationWaits := make([]rotationWait, 0)
for _, row := range rows {
// Skip channel types with no registered per-installation Factory. Such
// rows are driven outside the Supervisor (e.g. Slack's app-level Socket
@@ -357,8 +456,14 @@ func (s *Supervisor) sweep(ctx context.Context) {
}
id := uuidString(row.ID)
active[id] = struct{}{}
- s.maybeRestartOnRotation(id, row)
- s.startSupervisor(ctx, row)
+ done, rotated := s.cancelOnRotation(id, row)
+ if rotated {
+ rotationWaits = append(rotationWaits, rotationWait{installationID: id, done: done})
+ }
+ if !s.isSupervised(id) {
+ candidates = append(candidates, leaseCandidate{installation: row, localRotation: rotated})
+ candidateIDs = append(candidateIDs, row.ID)
+ }
}
// Reap supervisors whose installation is no longer active (revoked
// since the last sweep). The supervisor exits on the next boundary,
@@ -370,21 +475,56 @@ func (s *Supervisor) sweep(ctx context.Context) {
delete(s.supervisors, id)
}
}
+ for id := range s.contendedSince {
+ if _, stillActive := active[id]; !stillActive {
+ delete(s.contendedSince, id)
+ }
+ }
s.mu.Unlock()
+
+ if len(candidates) == 0 {
+ return
+ }
+ s.waitForRotations(ctx, rotationWaits)
+ held, err := s.leaseStore.ListHeldWSLeases(ctx, candidateIDs)
+ if err != nil {
+ s.recordLeaseOperation("list", "error")
+ s.cfg.Logger.Warn("channel engine: list held leases failed; acquisition sweep skipped", "error", err)
+ return
+ }
+ s.recordLeaseOperation("list", "success")
+ for _, candidate := range candidates {
+ row := candidate.installation
+ id := uuidString(row.ID)
+ if _, occupied := held[id]; occupied {
+ if !candidate.localRotation {
+ s.markContended(id)
+ }
+ continue
+ }
+ s.startSupervisor(ctx, row)
+ }
+}
+
+func (s *Supervisor) isSupervised(id string) bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ _, ok := s.supervisors[id]
+ return ok
}
-// maybeRestartOnRotation cancels an existing supervisor when its
-// fingerprint differs from the current row's. The replacement is started by
-// the subsequent startSupervisor call in the same sweep iteration. The map
-// entry is dropped inline so the startSupervisor "skip if already
-// supervised" guard does not race the cancel.
-func (s *Supervisor) maybeRestartOnRotation(id string, row Installation) {
+// cancelOnRotation cancels an existing supervisor when its fingerprint differs
+// from the current row's and returns its completion signal. sweep cancels every
+// rotated predecessor first, then waits for the batch under one bounded
+// deadline before checking held keys. A promptly-cancelled predecessor releases
+// its key in time for its replacement to start in the same sweep.
+func (s *Supervisor) cancelOnRotation(id string, row Installation) (<-chan struct{}, bool) {
want := row.Fingerprint
s.mu.Lock()
entry, ok := s.supervisors[id]
if !ok || entry.fingerprint == want {
s.mu.Unlock()
- return
+ return nil, false
}
s.cfg.Logger.Info("channel engine: credentials rotated, restarting supervisor",
"installation_id", id,
@@ -393,6 +533,37 @@ func (s *Supervisor) maybeRestartOnRotation(id string, row Installation) {
entry.cancel()
delete(s.supervisors, id)
s.mu.Unlock()
+ return entry.done, true
+}
+
+func (s *Supervisor) waitForRotations(ctx context.Context, waits []rotationWait) {
+ if len(waits) == 0 {
+ return
+ }
+ deadline := time.Now().Add(s.cfg.RotationWaitTimeout)
+ for _, wait := range waits {
+ remaining := time.Until(deadline)
+ if remaining <= 0 {
+ s.cfg.Logger.Warn("channel engine: timed out waiting for credential rotations to stop",
+ "timeout", s.cfg.RotationWaitTimeout.String(),
+ )
+ return
+ }
+ t := time.NewTimer(remaining)
+ select {
+ case <-ctx.Done():
+ t.Stop()
+ return
+ case <-wait.done:
+ t.Stop()
+ case <-t.C:
+ s.cfg.Logger.Warn("channel engine: timed out waiting for rotated supervisor to stop",
+ "installation_id", wait.installationID,
+ "timeout", s.cfg.RotationWaitTimeout.String(),
+ )
+ return
+ }
+ }
}
func (s *Supervisor) startSupervisor(parent context.Context, inst Installation) {
@@ -407,16 +578,18 @@ func (s *Supervisor) startSupervisor(parent context.Context, inst Installation)
return
}
ctx, cancel := context.WithCancel(parent)
+ done := make(chan struct{})
s.supervisorGen++
gen := s.supervisorGen
s.supervisors[id] = supervisorEntry{
cancel: cancel,
+ done: done,
fingerprint: inst.Fingerprint,
gen: gen,
}
s.wg.Add(1)
s.mu.Unlock()
- go s.supervise(ctx, inst, id, gen)
+ go s.supervise(ctx, inst, id, gen, done)
}
// leaseToken composes the per-supervisor lease token: the process-wide
@@ -433,8 +606,9 @@ func leaseToken(nodeID string, gen uint64) string {
// acquire lease → build channel → run it (Connect blocks) → renew lease
// while it runs → on exit, release + back off → repeat. Returns when ctx is
// cancelled.
-func (s *Supervisor) supervise(ctx context.Context, inst Installation, id string, gen uint64) {
+func (s *Supervisor) supervise(ctx context.Context, inst Installation, id string, gen uint64, done chan<- struct{}) {
defer s.wg.Done()
+ defer close(done)
defer func() {
// Only clear the map entry if it still belongs to us — gen
// disambiguates "this entry is mine" from "the rotation path already
@@ -460,22 +634,24 @@ func (s *Supervisor) supervise(ctx context.Context, inst Installation, id string
return
}
- // Claim the WS lease. If another replica owns a live lease, sleep
- // until it expires or our context is cancelled.
- leased, err := s.acquireLease(ctx, inst.ID, leaseTok)
+ // A losing candidate exits. The next batched sweep observes Redis and
+ // starts a fresh attempt only after the key disappears, avoiding a
+ // per-installation blind retry loop on every replica.
+ leased, confirmedUntil, err := s.acquireLease(ctx, inst.ID, leaseTok)
if err != nil {
+ s.recordLeaseOperation("acquire", "error")
log.Warn("channel engine: acquire lease error", "error", err)
- if sleep(ctx, s.cfg.LeaseRenewInterval) {
- return
- }
- continue
+ return
}
if !leased {
- if sleep(ctx, s.cfg.LeaseRenewInterval) {
- return
- }
- continue
+ s.recordLeaseOperation("acquire", "contended")
+ s.markContended(id)
+ return
}
+ s.recordLeaseOperation("acquire", "success")
+ s.observeTakeover(id)
+ s.setRenewalError(id, false)
+ s.adjustActiveOwners(1)
// Lease acquired. Build the platform channel via the registry,
// run it under a child context, and renew the lease in parallel.
@@ -488,6 +664,7 @@ func (s *Supervisor) supervise(ctx context.Context, inst Installation, id string
if err != nil {
log.Error("channel engine: build channel failed", "error", err)
s.releaseLease(inst.ID, leaseTok)
+ s.adjustActiveOwners(-1)
if sleep(ctx, backoff) {
return
}
@@ -503,7 +680,7 @@ func (s *Supervisor) supervise(ctx context.Context, inst Installation, id string
// channel exits even if its wire I/O is blocked. This is what
// makes "at most one active connection per installation across
// replicas" hold under lease theft.
- s.renewLeaseUntil(runCtx, runCancel, inst.ID, leaseTok)
+ s.renewLeaseUntil(runCtx, runCancel, inst.ID, leaseTok, confirmedUntil)
}()
startedAt := s.cfg.Now()
@@ -512,6 +689,7 @@ func (s *Supervisor) supervise(ctx context.Context, inst Installation, id string
<-renewDone
s.disconnect(ch, id, log)
s.releaseLease(inst.ID, leaseTok)
+ s.adjustActiveOwners(-1)
if ctx.Err() != nil {
return
@@ -539,20 +717,22 @@ func (s *Supervisor) supervise(ctx context.Context, inst Installation, id string
// when owned after the call; (false, nil) when held elsewhere; (false, err)
// for transport / DB failures. token is the per-supervisor token (see
// leaseToken), NOT the process-wide nodeID.
-func (s *Supervisor) acquireLease(ctx context.Context, instID pgtype.UUID, token string) (bool, error) {
- expires := s.cfg.Now().Add(s.cfg.LeaseTTL)
- err := s.store.AcquireWSLease(ctx, AcquireLeaseParams{
+func (s *Supervisor) acquireLease(ctx context.Context, instID pgtype.UUID, token string) (bool, time.Time, error) {
+ started := s.cfg.Now()
+ expires := started.Add(s.cfg.LeaseTTL)
+ err := s.leaseStore.TryAcquireWSLease(ctx, AcquireLeaseParams{
ID: instID,
Token: token,
ExpiresAt: expires,
+ TTL: s.cfg.LeaseTTL,
})
if err == nil {
- return true, nil
+ return true, started.Add(s.cfg.LeaseTTL - s.cfg.LeaseExpirySafetyMargin), nil
}
if errors.Is(err, ErrLeaseNotAcquired) {
- return false, nil
+ return false, time.Time{}, nil
}
- return false, err
+ return false, time.Time{}, err
}
// renewLeaseUntil re-acquires the lease on a tight cadence so a single
@@ -563,33 +743,66 @@ func (s *Supervisor) acquireLease(ctx context.Context, instID pgtype.UUID, token
// the same installation" failure mode. cancelRun forces the channel's ctx
// done immediately, so Connect returns in bounded time even on a silent
// socket. token MUST be the same per-supervisor token used to acquire.
-func (s *Supervisor) renewLeaseUntil(ctx context.Context, cancelRun context.CancelFunc, instID pgtype.UUID, token string) {
- t := time.NewTicker(s.cfg.LeaseRenewInterval)
- defer t.Stop()
+func (s *Supervisor) renewLeaseUntil(ctx context.Context, cancelRun context.CancelFunc, instID pgtype.UUID, token string, confirmedUntil time.Time) {
+ nextDelay := renewalJitter(s.cfg.LeaseRenewInterval)
for {
+ remaining := confirmedUntil.Sub(s.cfg.Now())
+ if remaining <= 0 {
+ s.leaseLost(instID, cancelRun, "last confirmed lease expired")
+ return
+ }
+ wait := min(nextDelay, remaining)
+ t := time.NewTimer(wait)
select {
case <-ctx.Done():
+ t.Stop()
return
case <-t.C:
- leased, err := s.acquireLease(ctx, instID, token)
- if err != nil {
- s.cfg.Logger.Warn("channel engine: lease renewal error",
- "installation_id", uuidString(instID),
- "error", err,
- )
- continue
- }
- if !leased {
- s.cfg.Logger.Warn("channel engine: lease lost; tearing down connection",
- "installation_id", uuidString(instID),
- )
- cancelRun()
+ }
+ if !s.cfg.Now().Before(confirmedUntil) {
+ s.leaseLost(instID, cancelRun, "last confirmed lease expired")
+ return
+ }
+
+ started := s.cfg.Now()
+ attemptCtx, attemptCancel := context.WithTimeout(ctx, confirmedUntil.Sub(started))
+ err := s.leaseStore.RenewWSLease(attemptCtx, AcquireLeaseParams{
+ ID: instID, Token: token, ExpiresAt: started.Add(s.cfg.LeaseTTL), TTL: s.cfg.LeaseTTL,
+ })
+ attemptCancel()
+ if err != nil {
+ if errors.Is(err, ErrLeaseNotAcquired) {
+ s.leaseLost(instID, cancelRun, "lease token no longer matches")
return
}
+ s.setRenewalError(uuidString(instID), true)
+ s.recordLeaseOperation("renew", "error")
+ s.cfg.Logger.Warn("channel engine: lease renewal error",
+ "installation_id", uuidString(instID),
+ "error", err,
+ "confirmed_until", confirmedUntil,
+ )
+ nextDelay = s.cfg.LeaseErrorRetryInterval
+ continue
+ }
+ confirmedUntil = started.Add(s.cfg.LeaseTTL - s.cfg.LeaseExpirySafetyMargin)
+ s.setRenewalError(uuidString(instID), false)
+ s.recordLeaseOperation("renew", "success")
+ if s.cfg.LeaseMetrics != nil {
+ s.cfg.LeaseMetrics.SetLastSuccessfulRenewal(s.cfg.Now())
}
+ nextDelay = renewalJitter(s.cfg.LeaseRenewInterval)
}
}
+func (s *Supervisor) leaseLost(instID pgtype.UUID, cancelRun context.CancelFunc, reason string) {
+ s.setRenewalError(uuidString(instID), false)
+ s.recordLeaseOperation("renew", "lost")
+ s.cfg.Logger.Warn("channel engine: lease lost; tearing down connection",
+ "installation_id", uuidString(instID), "reason", reason)
+ cancelRun()
+}
+
// releaseLease writes a token-fenced release so the next supervisor (this
// process or another replica) can pick up the installation without waiting
// for LeaseTTL. It runs on a fresh, bounded context (the parent ctx is
@@ -597,16 +810,74 @@ func (s *Supervisor) renewLeaseUntil(ctx context.Context, cancelRun context.Canc
// token used to acquire — a rotation successor's lease carries a different
// token, so a stale release no-ops instead of clobbering it.
func (s *Supervisor) releaseLease(instID pgtype.UUID, token string) {
+ s.setRenewalError(uuidString(instID), false)
ctx, cancel := context.WithTimeout(context.Background(), s.cfg.LeaseReleaseTimeout)
defer cancel()
- if err := s.store.ReleaseWSLease(ctx, ReleaseLeaseParams{
+ if err := s.leaseStore.ReleaseWSLease(ctx, ReleaseLeaseParams{
ID: instID,
Token: token,
}); err != nil {
+ s.recordLeaseOperation("release", "error")
s.cfg.Logger.Warn("channel engine: release lease failed",
"installation_id", uuidString(instID),
"error", err,
)
+ return
+ }
+ s.recordLeaseOperation("release", "success")
+}
+
+func (s *Supervisor) recordLeaseOperation(operation, outcome string) {
+ if s.cfg.LeaseMetrics != nil {
+ s.cfg.LeaseMetrics.RecordLeaseOperation(operation, outcome)
+ }
+}
+
+func (s *Supervisor) adjustActiveOwners(delta int) {
+ s.mu.Lock()
+ s.activeOwners += delta
+ count := s.activeOwners
+ s.mu.Unlock()
+ if s.cfg.LeaseMetrics != nil {
+ s.cfg.LeaseMetrics.SetActiveLeaseOwners(float64(count))
+ }
+}
+
+func (s *Supervisor) setRenewalError(id string, hasError bool) {
+ s.mu.Lock()
+ _, alreadySet := s.renewalErrors[id]
+ if hasError {
+ s.renewalErrors[id] = struct{}{}
+ } else {
+ delete(s.renewalErrors, id)
+ }
+ count := len(s.renewalErrors)
+ s.mu.Unlock()
+ if alreadySet == hasError {
+ return
+ }
+ if s.cfg.LeaseMetrics != nil {
+ s.cfg.LeaseMetrics.SetOwnersWithRenewalErrors(float64(count))
+ }
+}
+
+func (s *Supervisor) markContended(id string) {
+ s.mu.Lock()
+ if _, ok := s.contendedSince[id]; !ok {
+ s.contendedSince[id] = s.cfg.Now()
+ }
+ s.mu.Unlock()
+}
+
+func (s *Supervisor) observeTakeover(id string) {
+ s.mu.Lock()
+ started, ok := s.contendedSince[id]
+ if ok {
+ delete(s.contendedSince, id)
+ }
+ s.mu.Unlock()
+ if ok && s.cfg.LeaseMetrics != nil {
+ s.cfg.LeaseMetrics.ObserveTakeoverLatency(s.cfg.Now().Sub(started))
}
}
@@ -664,6 +935,16 @@ func jitter(d time.Duration) time.Duration {
return d - delta + time.Duration(mathrand.Int64N(int64(2*delta)+1))
}
+// renewalJitter uses a narrow [0.9d, 1.1d] window so replicas spread their
+// Redis calls without eroding the configured TTL safety budget.
+func renewalJitter(d time.Duration) time.Duration {
+ if d <= 0 {
+ return d
+ }
+ delta := d / 10
+ return d - delta + time.Duration(mathrand.Int64N(int64(2*delta)+1))
+}
+
// sleep is a ctx-aware time.Sleep. Returns true iff ctx was cancelled before
// the sleep completed, so callers can short-circuit shutdown.
func sleep(ctx context.Context, d time.Duration) bool {
diff --git a/server/internal/integrations/channel/engine/supervisor_test.go b/server/internal/integrations/channel/engine/supervisor_test.go
index 89787a6e3d..5968296b99 100644
--- a/server/internal/integrations/channel/engine/supervisor_test.go
+++ b/server/internal/integrations/channel/engine/supervisor_test.go
@@ -19,15 +19,19 @@ import (
// held in memory so a single fake can play both "we hold the lease" and
// "another replica holds the lease" within one test.
type fakeStore struct {
- mu sync.Mutex
- installations []Installation
- listErr error
- leaseOwner map[string]string // installation_id -> lease token
- leaseExpiresAt map[string]time.Time // installation_id -> expiry
- acquireErr error
- releaseErr error
- now func() time.Time
- acquireCount int32
+ mu sync.Mutex
+ installations []Installation
+ listErr error
+ leaseOwner map[string]string // installation_id -> lease token
+ leaseExpiresAt map[string]time.Time // installation_id -> expiry
+ acquireErr error
+ acquireAfterWriteErr error
+ renewErr error
+ listHeldErr error
+ releaseErr error
+ now func() time.Time
+ acquireCount int32
+ renewCount int32
// releaseBlock, if non-nil, makes ReleaseWSLease block until it is
// closed/sent on OR the caller's ctx fires. Simulates a frozen pool so
@@ -55,7 +59,23 @@ func (f *fakeStore) ListActiveInstallations(ctx context.Context) ([]Installation
return out, nil
}
-func (f *fakeStore) AcquireWSLease(ctx context.Context, arg AcquireLeaseParams) error {
+func (f *fakeStore) ListHeldWSLeases(_ context.Context, ids []pgtype.UUID) (map[string]struct{}, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if f.listHeldErr != nil {
+ return nil, f.listHeldErr
+ }
+ held := make(map[string]struct{}, len(ids))
+ for _, instID := range ids {
+ id := uuidString(instID)
+ if _, ok := f.leaseOwner[id]; ok && f.leaseExpiresAt[id].After(f.now()) {
+ held[id] = struct{}{}
+ }
+ }
+ return held, nil
+}
+
+func (f *fakeStore) TryAcquireWSLease(ctx context.Context, arg AcquireLeaseParams) error {
atomic.AddInt32(&f.acquireCount, 1)
f.mu.Lock()
defer f.mu.Unlock()
@@ -70,11 +90,31 @@ func (f *fakeStore) AcquireWSLease(ctx context.Context, arg AcquireLeaseParams)
if !hasOwner || exp.Before(now) || owner == arg.Token {
f.leaseOwner[id] = arg.Token
f.leaseExpiresAt[id] = arg.ExpiresAt
+ if f.acquireAfterWriteErr != nil {
+ err := f.acquireAfterWriteErr
+ f.acquireAfterWriteErr = nil
+ return err
+ }
return nil
}
return ErrLeaseNotAcquired
}
+func (f *fakeStore) RenewWSLease(_ context.Context, arg AcquireLeaseParams) error {
+ atomic.AddInt32(&f.renewCount, 1)
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if f.renewErr != nil {
+ return f.renewErr
+ }
+ id := uuidString(arg.ID)
+ if f.leaseOwner[id] != arg.Token || !f.leaseExpiresAt[id].After(f.now()) {
+ return ErrLeaseNotAcquired
+ }
+ f.leaseExpiresAt[id] = arg.ExpiresAt
+ return nil
+}
+
func (f *fakeStore) ReleaseWSLease(ctx context.Context, arg ReleaseLeaseParams) error {
f.mu.Lock()
block := f.releaseBlock
@@ -232,7 +272,7 @@ func TestSupervisorAcquiresLeaseAndConnects(t *testing.T) {
var builds int32
reg := fakeRegistry(fc, &builds, nil)
- sup := NewSupervisor(q, reg, nil, fastConfig())
+ sup := NewSupervisor(q, q, reg, nil, fastConfig())
ctx, cancel := context.WithCancel(context.Background())
go sup.Run(ctx)
@@ -273,7 +313,7 @@ func TestSupervisorSkipsUnregisteredChannelType(t *testing.T) {
var builds int32
reg := fakeRegistry(fc, &builds, nil) // registers ONLY TypeFeishu
- sup := NewSupervisor(q, reg, nil, fastConfig())
+ sup := NewSupervisor(q, q, reg, nil, fastConfig())
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go sup.Run(ctx)
@@ -305,7 +345,7 @@ func TestSupervisorInjectsHandler(t *testing.T) {
called.Store(true)
return nil
}
- sup := NewSupervisor(q, reg, handler, fastConfig())
+ sup := NewSupervisor(q, q, reg, handler, fastConfig())
ctx, cancel := context.WithCancel(context.Background())
go sup.Run(ctx)
@@ -337,7 +377,7 @@ func TestSupervisorSkipsWhenAnotherReplicaHoldsLease(t *testing.T) {
var builds int32
reg := fakeRegistry(fc, &builds, nil)
- sup := NewSupervisor(q, reg, nil, fastConfig())
+ sup := NewSupervisor(q, q, reg, nil, fastConfig())
ctx, cancel := context.WithCancel(context.Background())
go sup.Run(ctx)
@@ -349,11 +389,82 @@ func TestSupervisorSkipsWhenAnotherReplicaHoldsLease(t *testing.T) {
if owner, _ := q.leaseHolder(instID); owner != "other-replica" {
t.Fatalf("foreign lease should be untouched, got %q", owner)
}
+ if got := atomic.LoadInt32(&q.acquireCount); got != 0 {
+ t.Fatalf("loser should rely on batched held-key sweeps, acquire attempts=%d", got)
+ }
+
+ // Revoking an installation this node only observed as contended must prune
+ // its takeover-timing state; otherwise repeated install/revoke cycles leak.
+ q.mu.Lock()
+ q.installations = nil
+ q.mu.Unlock()
+ if !waitFor(200*time.Millisecond, func() bool {
+ sup.mu.Lock()
+ defer sup.mu.Unlock()
+ _, ok := sup.contendedSince[uuidString(instID)]
+ return !ok
+ }) {
+ t.Fatalf("revoked contended installation was not pruned")
+ }
cancel()
sup.Wait()
}
+func TestSupervisorTwoNodesHaveExactlyOneOwner(t *testing.T) {
+ q := newFakeStore()
+ instID := uuidFromString(t, "23232323-2323-2323-2323-232323232323")
+ q.installations = []Installation{activeInst(instID, "fp1")}
+
+ first := &fakeChannel{typ: channel.TypeFeishu}
+ second := &fakeChannel{typ: channel.TypeFeishu}
+ var firstBuilds, secondBuilds int32
+ supA := NewSupervisor(q, q, fakeRegistry(first, &firstBuilds, nil), nil, fastConfig())
+ supB := NewSupervisor(q, q, fakeRegistry(second, &secondBuilds, nil), nil, fastConfig())
+ ctx, cancel := context.WithCancel(context.Background())
+ go supA.Run(ctx)
+ go supB.Run(ctx)
+
+ if !waitFor(300*time.Millisecond, func() bool { return first.Connects()+second.Connects() == 1 }) {
+ t.Fatalf("expected one owner, connects A=%d B=%d", first.Connects(), second.Connects())
+ }
+ time.Sleep(100 * time.Millisecond)
+ if got := first.Connects() + second.Connects(); got != 1 {
+ t.Fatalf("both nodes connected to one installation: connects=%d", got)
+ }
+
+ cancel()
+ supA.Wait()
+ supB.Wait()
+}
+
+func TestSupervisorAcquireResponseLossWaitsForExpiryBeforeRetry(t *testing.T) {
+ q := newFakeStore()
+ q.acquireAfterWriteErr = errors.New("response lost")
+ instID := uuidFromString(t, "24242424-2424-2424-2424-242424242424")
+ q.installations = []Installation{activeInst(instID, "fp1")}
+ fc := &fakeChannel{typ: channel.TypeFeishu}
+ var builds int32
+ sup := NewSupervisor(q, q, fakeRegistry(fc, &builds, nil), nil, fastConfig())
+ ctx, cancel := context.WithCancel(context.Background())
+ go sup.Run(ctx)
+ defer func() {
+ cancel()
+ sup.Wait()
+ }()
+
+ time.Sleep(150 * time.Millisecond)
+ if got := fc.Connects(); got != 0 {
+ t.Fatalf("must not connect when acquire acknowledgement was lost; connects=%d", got)
+ }
+ if got := atomic.LoadInt32(&q.acquireCount); got != 1 {
+ t.Fatalf("held key should suppress retries before expiry; attempts=%d", got)
+ }
+ if !waitFor(800*time.Millisecond, func() bool { return fc.Connects() == 1 }) {
+ t.Fatalf("expected takeover after uncertain lease expired")
+ }
+}
+
func TestSupervisorReclaimsLeaseAfterExpiry(t *testing.T) {
q := newFakeStore()
instID := uuidFromString(t, "33333333-3333-3333-3333-333333333333")
@@ -364,7 +475,7 @@ func TestSupervisorReclaimsLeaseAfterExpiry(t *testing.T) {
var builds int32
reg := fakeRegistry(fc, &builds, nil)
- sup := NewSupervisor(q, reg, nil, fastConfig())
+ sup := NewSupervisor(q, q, reg, nil, fastConfig())
ctx, cancel := context.WithCancel(context.Background())
go sup.Run(ctx)
@@ -385,7 +496,7 @@ func TestSupervisorReapsSupervisorWhenRevoked(t *testing.T) {
var builds int32
reg := fakeRegistry(fc, &builds, nil)
- sup := NewSupervisor(q, reg, nil, fastConfig())
+ sup := NewSupervisor(q, q, reg, nil, fastConfig())
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go sup.Run(ctx)
@@ -417,7 +528,7 @@ func TestSupervisorRestartsOnCredentialsRotation(t *testing.T) {
var builds int32
reg := fakeRegistry(fc, &builds, nil)
- sup := NewSupervisor(q, reg, nil, fastConfig())
+ sup := NewSupervisor(q, q, reg, nil, fastConfig())
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go sup.Run(ctx)
@@ -437,6 +548,44 @@ func TestSupervisorRestartsOnCredentialsRotation(t *testing.T) {
}
}
+func TestSupervisorRotationReplacesConnectionInSameSweep(t *testing.T) {
+ q := newFakeStore()
+ instID := uuidFromString(t, "56565656-5656-5656-5656-565656565656")
+ q.installations = []Installation{activeInst(instID, "fp-one")}
+
+ fc := &fakeChannel{typ: channel.TypeFeishu}
+ var builds int32
+ cfg := fastConfig()
+ cfg.LeaseTTL = 6 * time.Second
+ cfg.LeaseRenewInterval = 3 * time.Second
+ cfg.PollInterval = 2 * time.Second
+ cfg.LeaseErrorRetryInterval = 100 * time.Millisecond
+ cfg.LeaseExpirySafetyMargin = 500 * time.Millisecond
+ cfg.RotationWaitTimeout = 500 * time.Millisecond
+ sup := NewSupervisor(q, q, fakeRegistry(fc, &builds, nil), nil, cfg)
+ ctx, cancel := context.WithCancel(context.Background())
+ go sup.Run(ctx)
+ defer func() {
+ cancel()
+ sup.Wait()
+ }()
+ if !waitFor(300*time.Millisecond, func() bool { return atomic.LoadInt32(&builds) == 1 }) {
+ t.Fatalf("initial channel never built")
+ }
+
+ q.mu.Lock()
+ q.installations[0].Fingerprint = "fp-two"
+ q.mu.Unlock()
+ started := time.Now()
+ sup.sweep(ctx)
+ if !waitFor(500*time.Millisecond, func() bool { return atomic.LoadInt32(&builds) == 2 }) {
+ t.Fatalf("rotation waited for the next %s poll instead of restarting in the same sweep", cfg.PollInterval)
+ }
+ if elapsed := time.Since(started); elapsed >= cfg.PollInterval {
+ t.Fatalf("rotation replacement took %s, poll interval is %s", elapsed, cfg.PollInterval)
+ }
+}
+
func TestSupervisorDoesNotRestartOnUnchangedRow(t *testing.T) {
q := newFakeStore()
instID := uuidFromString(t, "66666666-6666-6666-6666-666666666666")
@@ -446,7 +595,7 @@ func TestSupervisorDoesNotRestartOnUnchangedRow(t *testing.T) {
var builds int32
reg := fakeRegistry(fc, &builds, nil)
- sup := NewSupervisor(q, reg, nil, fastConfig())
+ sup := NewSupervisor(q, q, reg, nil, fastConfig())
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go sup.Run(ctx)
@@ -470,7 +619,7 @@ func TestSupervisorBacksOffOnBuildError(t *testing.T) {
var builds int32
reg := fakeRegistry(fc, &builds, errors.New("boom"))
- sup := NewSupervisor(q, reg, nil, fastConfig())
+ sup := NewSupervisor(q, q, reg, nil, fastConfig())
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go sup.Run(ctx)
@@ -504,7 +653,7 @@ func TestSupervisorLeaseLossCancelsConnection(t *testing.T) {
var builds int32
reg := fakeRegistry(fc, &builds, nil)
- sup := NewSupervisor(q, reg, nil, fastConfig())
+ sup := NewSupervisor(q, q, reg, nil, fastConfig())
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go sup.Run(ctx)
@@ -524,6 +673,123 @@ func TestSupervisorLeaseLossCancelsConnection(t *testing.T) {
}
}
+func TestSupervisorClearedLeaseKeyCancelsOldOwner(t *testing.T) {
+ q := newFakeStore()
+ instID := uuidFromString(t, "8b8b8b8b-8b8b-8b8b-8b8b-8b8b8b8b8b8b")
+ q.installations = []Installation{activeInst(instID, "fp1")}
+
+ connectReturned := make(chan struct{}, 1)
+ fc := &fakeChannel{
+ typ: channel.TypeFeishu,
+ script: []func(context.Context) error{func(ctx context.Context) error {
+ <-ctx.Done()
+ connectReturned <- struct{}{}
+ return ctx.Err()
+ }},
+ }
+ var builds int32
+ sup := NewSupervisor(q, q, fakeRegistry(fc, &builds, nil), nil, fastConfig())
+ ctx, cancel := context.WithCancel(context.Background())
+ go sup.Run(ctx)
+ defer func() {
+ cancel()
+ sup.Wait()
+ }()
+ if !waitFor(300*time.Millisecond, func() bool { return fc.Connects() == 1 }) {
+ t.Fatalf("channel never connected")
+ }
+
+ // Simulate Redis losing/clearing the key. Strict renewal must treat absence
+ // as lease loss instead of recreating the key from the old owner.
+ q.mu.Lock()
+ delete(q.leaseOwner, uuidString(instID))
+ delete(q.leaseExpiresAt, uuidString(instID))
+ q.mu.Unlock()
+ select {
+ case <-connectReturned:
+ case <-time.After(500 * time.Millisecond):
+ t.Fatalf("cleared lease key did not tear down the old owner")
+ }
+}
+
+func TestSupervisorTransientRenewalErrorRecoversBeforeDeadline(t *testing.T) {
+ q := newFakeStore()
+ instID := uuidFromString(t, "89898989-8989-8989-8989-898989898989")
+ q.installations = []Installation{activeInst(instID, "fp1")}
+ fc := &fakeChannel{typ: channel.TypeFeishu}
+ var builds int32
+ sup := NewSupervisor(q, q, fakeRegistry(fc, &builds, nil), nil, fastConfig())
+ ctx, cancel := context.WithCancel(context.Background())
+ go sup.Run(ctx)
+ defer func() {
+ cancel()
+ sup.Wait()
+ }()
+ if !waitFor(300*time.Millisecond, func() bool { return fc.Connects() == 1 }) {
+ t.Fatalf("channel never connected")
+ }
+
+ q.mu.Lock()
+ q.renewErr = errors.New("temporary redis timeout")
+ q.mu.Unlock()
+ if !waitFor(200*time.Millisecond, func() bool { return atomic.LoadInt32(&q.renewCount) >= 2 }) {
+ t.Fatalf("renewal errors were not retried quickly")
+ }
+ q.mu.Lock()
+ q.renewErr = nil
+ q.mu.Unlock()
+ before := atomic.LoadInt32(&q.renewCount)
+ if !waitFor(200*time.Millisecond, func() bool { return atomic.LoadInt32(&q.renewCount) > before }) {
+ t.Fatalf("renewal did not recover")
+ }
+ if got := fc.Connects(); got != 1 {
+ t.Fatalf("transient error should not reconnect the channel; connects=%d", got)
+ }
+}
+
+func TestSupervisorOneWayRedisPartitionDisconnectsBeforeConfirmedExpiry(t *testing.T) {
+ q := newFakeStore()
+ q.releaseBlock = make(chan struct{})
+ instID := uuidFromString(t, "8a8a8a8a-8a8a-8a8a-8a8a-8a8a8a8a8a8a")
+ q.installations = []Installation{activeInst(instID, "fp1")}
+ connectReturned := make(chan struct{}, 1)
+ fc := &fakeChannel{
+ typ: channel.TypeFeishu,
+ script: []func(context.Context) error{func(ctx context.Context) error {
+ <-ctx.Done()
+ connectReturned <- struct{}{}
+ return ctx.Err()
+ }},
+ }
+ var builds int32
+ cfg := fastConfig()
+ cfg.LeaseReleaseTimeout = 100 * time.Millisecond
+ sup := NewSupervisor(q, q, fakeRegistry(fc, &builds, nil), nil, cfg)
+ ctx, cancel := context.WithCancel(context.Background())
+ go sup.Run(ctx)
+ if !waitFor(300*time.Millisecond, func() bool { return fc.Connects() == 1 }) {
+ t.Fatalf("channel never connected")
+ }
+
+ q.mu.Lock()
+ q.renewErr = errors.New("partitioned from redis")
+ q.mu.Unlock()
+ select {
+ case <-connectReturned:
+ case <-time.After(800 * time.Millisecond):
+ t.Fatalf("partitioned owner stayed connected beyond confirmed lease")
+ }
+ q.mu.Lock()
+ expiresAt := q.leaseExpiresAt[uuidString(instID)]
+ q.mu.Unlock()
+ if !time.Now().Before(expiresAt) {
+ t.Fatalf("connection was not cancelled before backend lease expiry: expires_at=%s", expiresAt)
+ }
+ close(q.releaseBlock)
+ cancel()
+ sup.Wait()
+}
+
func TestSupervisorReleaseLeaseBoundedByTimeout(t *testing.T) {
q := newFakeStore()
q.releaseBlock = make(chan struct{}) // never closed; release always hits ctx.Done
@@ -536,7 +802,7 @@ func TestSupervisorReleaseLeaseBoundedByTimeout(t *testing.T) {
cfg := fastConfig()
cfg.LeaseReleaseTimeout = 40 * time.Millisecond
- sup := NewSupervisor(q, reg, nil, cfg)
+ sup := NewSupervisor(q, q, reg, nil, cfg)
ctx, cancel := context.WithCancel(context.Background())
go sup.Run(ctx)
@@ -568,7 +834,7 @@ func TestSupervisorWaitWithTimeoutReturnsFalseWhenStuck(t *testing.T) {
cfg := fastConfig()
cfg.LeaseReleaseTimeout = 10 * time.Second // longer than the WaitWithTimeout below
- sup := NewSupervisor(q, reg, nil, cfg)
+ sup := NewSupervisor(q, q, reg, nil, cfg)
ctx, cancel := context.WithCancel(context.Background())
go sup.Run(ctx)
@@ -598,7 +864,7 @@ func TestSupervisorRotationStaleReleaseDoesNotClearSuccessorLease(t *testing.T)
var builds int32
reg := fakeRegistry(fc, &builds, nil)
- sup := NewSupervisor(q, reg, nil, fastConfig())
+ sup := NewSupervisor(q, q, reg, nil, fastConfig())
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go sup.Run(ctx)
@@ -627,7 +893,8 @@ func TestSupervisorRotationStaleReleaseDoesNotClearSuccessorLease(t *testing.T)
}
func TestSupervisorConfigDefaults(t *testing.T) {
- sup := NewSupervisor(newFakeStore(), channel.NewRegistry(), nil, Config{})
+ store := newFakeStore()
+ sup := NewSupervisor(store, store, channel.NewRegistry(), nil, Config{})
if sup.cfg.LeaseTTL <= 0 || sup.cfg.LeaseRenewInterval <= 0 || sup.cfg.PollInterval <= 0 {
t.Fatalf("lifecycle intervals must default to positive values")
}
@@ -637,6 +904,9 @@ func TestSupervisorConfigDefaults(t *testing.T) {
if sup.ShutdownTimeout() <= 0 {
t.Fatalf("shutdown timeout must default to a positive value")
}
+ if sup.cfg.RotationWaitTimeout <= 0 {
+ t.Fatalf("rotation wait timeout must default to a positive value")
+ }
if sup.cfg.Now == nil || sup.cfg.Logger == nil {
t.Fatalf("Now and Logger must be defaulted")
}
@@ -644,3 +914,27 @@ func TestSupervisorConfigDefaults(t *testing.T) {
t.Fatalf("node id must be assigned")
}
}
+
+func TestSupervisorPartialTTLConfigDerivesSafeIntervals(t *testing.T) {
+ store := newFakeStore()
+ sup := NewSupervisor(store, store, channel.NewRegistry(), nil, Config{LeaseTTL: 30 * time.Second})
+ if sup.cfg.LeaseRenewInterval != 10*time.Second {
+ t.Fatalf("renew interval = %s, want TTL/3", sup.cfg.LeaseRenewInterval)
+ }
+ if sup.cfg.PollInterval != 5*time.Second {
+ t.Fatalf("poll interval = %s, want renew/2", sup.cfg.PollInterval)
+ }
+}
+
+func TestSupervisorRejectsUnsafeLeaseIntervals(t *testing.T) {
+ store := newFakeStore()
+ defer func() {
+ if recover() == nil {
+ t.Fatalf("expected invalid poll/renew/ttl relation to panic")
+ }
+ }()
+ NewSupervisor(store, store, channel.NewRegistry(), nil, Config{
+ LeaseTTL: 30 * time.Second, LeaseRenewInterval: 20 * time.Second, PollInterval: 25 * time.Second,
+ LeaseErrorRetryInterval: time.Second, LeaseExpirySafetyMargin: time.Second,
+ })
+}
diff --git a/server/internal/integrations/lark/feishu_channel.go b/server/internal/integrations/lark/feishu_channel.go
index 2f8445d65f..3f6b7dafca 100644
--- a/server/internal/integrations/lark/feishu_channel.go
+++ b/server/internal/integrations/lark/feishu_channel.go
@@ -241,9 +241,16 @@ type channelInstallationStore struct {
q *db.Queries
}
+// ChannelInstallationStore exposes both PostgreSQL seams used by the engine:
+// durable installation discovery and the explicit rollback lease backend.
+type ChannelInstallationStore interface {
+ engine.InstallationStore
+ engine.LeaseStore
+}
+
// NewChannelInstallationStore builds the engine.InstallationStore backed by the
// generalized channel_* tables.
-func NewChannelInstallationStore(q *db.Queries) engine.InstallationStore {
+func NewChannelInstallationStore(q *db.Queries) ChannelInstallationStore {
return &channelInstallationStore{q: q}
}
@@ -264,7 +271,23 @@ func (s *channelInstallationStore) ListActiveInstallations(ctx context.Context)
return out, nil
}
-func (s *channelInstallationStore) AcquireWSLease(ctx context.Context, arg engine.AcquireLeaseParams) error {
+// PostgreSQL remains an explicit rollback/self-host lease backend. Its sweep
+// optimization returns no known holders, so the SQL CAS remains authoritative
+// and each unowned installation is attempted once per poll (never in a blind
+// per-installation loop).
+func (s *channelInstallationStore) ListHeldWSLeases(_ context.Context, _ []pgtype.UUID) (map[string]struct{}, error) {
+ return map[string]struct{}{}, nil
+}
+
+func (s *channelInstallationStore) TryAcquireWSLease(ctx context.Context, arg engine.AcquireLeaseParams) error {
+ return s.acquireOrRenewWSLease(ctx, arg)
+}
+
+func (s *channelInstallationStore) RenewWSLease(ctx context.Context, arg engine.AcquireLeaseParams) error {
+ return s.acquireOrRenewWSLease(ctx, arg)
+}
+
+func (s *channelInstallationStore) acquireOrRenewWSLease(ctx context.Context, arg engine.AcquireLeaseParams) error {
_, err := s.q.AcquireChannelWSLease(ctx, db.AcquireChannelWSLeaseParams{
NewToken: pgtype.Text{String: arg.Token, Valid: true},
NewExpiresAt: pgtype.Timestamptz{Time: arg.ExpiresAt, Valid: true},
@@ -286,6 +309,9 @@ func (s *channelInstallationStore) ReleaseWSLease(ctx context.Context, arg engin
})
}
+var _ engine.InstallationStore = (*channelInstallationStore)(nil)
+var _ engine.LeaseStore = (*channelInstallationStore)(nil)
+
// rowFingerprint condenses the credential-bearing config of a
// channel_installation row into an opaque string. Any change to the platform
// config (Feishu rotates app_id / app_secret / region on re-install) flips the
diff --git a/server/internal/metrics/channel_lease.go b/server/internal/metrics/channel_lease.go
new file mode 100644
index 0000000000..965ace976f
--- /dev/null
+++ b/server/internal/metrics/channel_lease.go
@@ -0,0 +1,87 @@
+package metrics
+
+import (
+ "time"
+
+ "github.com/prometheus/client_golang/prometheus"
+)
+
+// ChannelLeaseMetrics exposes the ownership signals needed to verify a Redis
+// lease cutover without putting installation IDs into metric labels.
+type ChannelLeaseMetrics struct {
+ Operations *prometheus.CounterVec
+ ActiveOwners prometheus.Gauge
+ OwnersWithRenewalErrors prometheus.Gauge
+ LastSuccessfulRenew prometheus.Gauge
+ TakeoverLatency prometheus.Histogram
+}
+
+func NewChannelLeaseMetrics() *ChannelLeaseMetrics {
+ return &ChannelLeaseMetrics{
+ Operations: prometheus.NewCounterVec(prometheus.CounterOpts{
+ Namespace: "multica",
+ Subsystem: "channel_lease",
+ Name: "operations_total",
+ Help: "Channel lease operations by operation and outcome.",
+ }, []string{"operation", "outcome"}),
+ ActiveOwners: prometheus.NewGauge(prometheus.GaugeOpts{
+ Namespace: "multica",
+ Subsystem: "channel_lease",
+ Name: "active_owners",
+ Help: "Channel installations currently owned by this process.",
+ }),
+ OwnersWithRenewalErrors: prometheus.NewGauge(prometheus.GaugeOpts{
+ Namespace: "multica",
+ Subsystem: "channel_lease",
+ Name: "owners_with_renewal_errors",
+ Help: "Channel lease owners whose latest renewal attempt failed.",
+ }),
+ LastSuccessfulRenew: prometheus.NewGauge(prometheus.GaugeOpts{
+ Namespace: "multica",
+ Subsystem: "channel_lease",
+ Name: "last_successful_renewal_timestamp_seconds",
+ Help: "Unix timestamp of the most recent successful channel lease renewal.",
+ }),
+ TakeoverLatency: prometheus.NewHistogram(prometheus.HistogramOpts{
+ Namespace: "multica",
+ Subsystem: "channel_lease",
+ Name: "takeover_latency_seconds",
+ Help: "Time from first observed contention until this process acquires the lease.",
+ Buckets: []float64{1, 5, 15, 30, 60, 120, 180, 300},
+ }),
+ }
+}
+
+func (m *ChannelLeaseMetrics) RecordLeaseOperation(operation, outcome string) {
+ if m != nil {
+ m.Operations.WithLabelValues(operation, outcome).Inc()
+ }
+}
+
+func (m *ChannelLeaseMetrics) SetActiveLeaseOwners(count float64) {
+ if m != nil {
+ m.ActiveOwners.Set(count)
+ }
+}
+
+func (m *ChannelLeaseMetrics) SetOwnersWithRenewalErrors(count float64) {
+ if m != nil {
+ m.OwnersWithRenewalErrors.Set(count)
+ }
+}
+
+func (m *ChannelLeaseMetrics) SetLastSuccessfulRenewal(at time.Time) {
+ if m != nil {
+ m.LastSuccessfulRenew.Set(float64(at.Unix()))
+ }
+}
+
+func (m *ChannelLeaseMetrics) ObserveTakeoverLatency(delay time.Duration) {
+ if m != nil {
+ m.TakeoverLatency.Observe(delay.Seconds())
+ }
+}
+
+func (m *ChannelLeaseMetrics) Collectors() []prometheus.Collector {
+ return []prometheus.Collector{m.Operations, m.ActiveOwners, m.OwnersWithRenewalErrors, m.LastSuccessfulRenew, m.TakeoverLatency}
+}
diff --git a/server/internal/metrics/channel_lease_test.go b/server/internal/metrics/channel_lease_test.go
new file mode 100644
index 0000000000..5e2c9ea904
--- /dev/null
+++ b/server/internal/metrics/channel_lease_test.go
@@ -0,0 +1,41 @@
+package metrics
+
+import (
+ "testing"
+ "time"
+
+ "github.com/prometheus/client_golang/prometheus"
+)
+
+func TestChannelLeaseMetricsRegisterAndRecord(t *testing.T) {
+ m := NewChannelLeaseMetrics()
+ reg := prometheus.NewPedanticRegistry()
+ reg.MustRegister(m.Collectors()...)
+ m.RecordLeaseOperation("renew", "error")
+ m.SetActiveLeaseOwners(2)
+ m.SetOwnersWithRenewalErrors(1)
+ m.SetLastSuccessfulRenewal(time.Unix(123, 0))
+ m.ObserveTakeoverLatency(30 * time.Second)
+
+ families, err := reg.Gather()
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := map[string]bool{
+ "multica_channel_lease_operations_total": false,
+ "multica_channel_lease_active_owners": false,
+ "multica_channel_lease_owners_with_renewal_errors": false,
+ "multica_channel_lease_last_successful_renewal_timestamp_seconds": false,
+ "multica_channel_lease_takeover_latency_seconds": false,
+ }
+ for _, family := range families {
+ if _, ok := want[family.GetName()]; ok {
+ want[family.GetName()] = true
+ }
+ }
+ for name, seen := range want {
+ if !seen {
+ t.Fatalf("metric %s was not gathered", name)
+ }
+ }
+}
diff --git a/server/internal/metrics/registry.go b/server/internal/metrics/registry.go
index 63853ace6b..e4a3984c3a 100644
--- a/server/internal/metrics/registry.go
+++ b/server/internal/metrics/registry.go
@@ -31,6 +31,7 @@ type Registry struct {
HTTP *HTTPMetrics
Business *BusinessMetrics
ChannelMedia *ChannelMediaReconcilerMetrics
+ ChannelLease *ChannelLeaseMetrics
Wecom *WecomMetrics
// Sampler is non-nil only when RegistryOptions.BusinessSampler was
// supplied with a valid Pool. Exposed so the cmd/server entrypoint
@@ -59,6 +60,9 @@ func NewRegistry(opts RegistryOptions) *Registry {
channelMedia := NewChannelMediaReconcilerMetrics()
reg.MustRegister(channelMedia.Collectors()...)
+ channelLease := NewChannelLeaseMetrics()
+ reg.MustRegister(channelLease.Collectors()...)
+
wecomMetrics := NewWecomMetrics()
reg.MustRegister(wecomMetrics.Collectors()...)
@@ -82,6 +86,7 @@ func NewRegistry(opts RegistryOptions) *Registry {
HTTP: httpMetrics,
Business: businessMetrics,
ChannelMedia: channelMedia,
+ ChannelLease: channelLease,
Wecom: wecomMetrics,
Sampler: sampler,
}