pkg/service/leaf_sync.go

package service

import (
	"context"
	"fmt"
	"sync"

	"git.cafe/ezterry/ez-agent/pkg/ezagentapi"
	"git.cafe/ezterry/ez-agent/pkg/protocol"
	"git.cafe/ezterry/ez-agent/pkg/service/session"
)

// leafGateRegistry owns one gate for each valid leaf with synchronization work
// in flight. Its lock never covers database I/O or a leaf gate wait.
// A retiring gate remains
// registered until all waiters release it, so deletion cannot overlap a second
// gate for the same ID.
type leafGateRegistry struct {
	mu    sync.Mutex
	gates map[string]*leafGate
	audit *serviceAudit
}

type leafGate struct {
	mu       leafGateMutex
	refs     int
	retiring bool
	failure  error // guarded by registry mu, retained for validation waiters
}

// A channel lock permits request cancellation without leaving a goroutine
// waiting to mutate a leaf after its RPC has expired.
type leafGateMutex struct {
	once  sync.Once
	token chan struct{}
}

func (m *leafGateMutex) lockContext(ctx context.Context) error {
	m.once.Do(func() { m.token = make(chan struct{}, 1); m.token <- struct{}{} })
	select {
	case <-ctx.Done():
		return ctx.Err()
	case <-m.token:
		if err := ctx.Err(); err != nil {
			m.Unlock()
			return err
		}
		return nil
	}
}
func (m *leafGateMutex) Lock()   { _ = m.lockContext(context.Background()) }
func (m *leafGateMutex) Unlock() { m.token <- struct{}{} }
func (m *leafGateMutex) TryLock() bool {
	m.once.Do(func() { m.token = make(chan struct{}, 1); m.token <- struct{}{} })
	select {
	case <-m.token:
		return true
	default:
		return false
	}
}

type leafGateStorage interface {
	GetLeafContext(context.Context, string) (*session.Leaf, error)
	poolStatser
}

func (r *leafGateRegistry) acquire(storage *session.Storage, leafID string) (*leafGate, bool) {
	if storage == nil {
		return nil, false
	}
	return r.acquireContext(context.Background(), storage, leafID)
}

func (r *leafGateRegistry) acquireContext(ctx context.Context, storage leafGateStorage, leafID string) (*leafGate, bool) {
	gate, err := r.acquireResult(ctx, storage, leafID)
	return gate, err == nil
}

// leafValidationError preserves the historical public rejection presentation
// while retaining the typed storage cause for internal incident classification.
type leafValidationError struct {
	leafID string
	cause  error
}

func (e leafValidationError) Error() string { return fmt.Sprintf("leaf not found: %s", e.leafID) }
func (e leafValidationError) Unwrap() error { return e.cause }

func (r *leafGateRegistry) acquireResult(ctx context.Context, storage leafGateStorage, leafID string) (*leafGate, error) {
	if storage == nil || leafID == "" {
		return nil, leafValidationError{leafID, session.ErrLeafNotFound}
	}
	r.mu.Lock()
	if gate := r.gates[leafID]; gate != nil {
		return r.acquireExistingContextLocked(ctx, leafID, gate)
	}
	if r.gates == nil {
		r.gates = make(map[string]*leafGate)
	}
	gate := &leafGate{refs: 1}
	// Pin and lock the first gate before publishing it. Waiters share this
	// validation and cannot overtake it or allocate a competing gate.
	gate.mu.Lock()
	r.gates[leafID] = gate
	r.mu.Unlock()
	done := r.audit.operationPhase("gate_validate", serviceWaitBudget, safeIDs(leafID, ""), false)
	poolDone := r.audit.poolWait(storage, safeIDs(leafID, ""))
	_, err := storage.GetLeafContext(ctx, leafID)
	poolDone()
	done(err)
	if err != nil {
		r.mu.Lock()
		gate.failure = err
		gate.retiring = true
		r.mu.Unlock()
		r.release(leafID, gate)
		return nil, leafValidationError{leafID, err}
	}
	return gate, nil
}

// acquireExistingLocked consumes r.mu before waiting on the leaf gate.
func (r *leafGateRegistry) acquireExistingLocked(leafID string, gate *leafGate) (*leafGate, bool) {
	result, err := r.acquireExistingResultLocked(leafID, gate)
	return result, err == nil
}

func (r *leafGateRegistry) acquireExistingResultLocked(leafID string, gate *leafGate) (*leafGate, error) {
	return r.acquireExistingContextLocked(context.Background(), leafID, gate)
}

func (r *leafGateRegistry) acquireExistingContextLocked(ctx context.Context, leafID string, gate *leafGate) (*leafGate, error) {
	if gate.retiring {
		failure := gate.failure
		r.mu.Unlock()
		if failure == nil {
			failure = session.ErrLeafNotFound
		}
		return nil, leafValidationError{leafID, failure}
	}
	gate.refs++
	r.mu.Unlock()
	done := r.audit.phase("gate_wait", serviceWaitBudget, safeIDs(leafID, ""), false)
	if err := gate.mu.lockContext(ctx); err != nil {
		r.mu.Lock()
		gate.refs--
		if gate.refs == 0 && r.gates[leafID] == gate {
			delete(r.gates, leafID)
		}
		r.mu.Unlock()
		done(false)
		return nil, err
	}
	done(false)
	r.mu.Lock()
	retiring := gate.retiring
	failure := gate.failure
	r.mu.Unlock()
	if retiring {
		r.release(leafID, gate)
		if failure == nil {
			failure = session.ErrLeafNotFound
		}
		return nil, leafValidationError{leafID, failure}
	}
	return gate, nil
}

func (r *leafGateRegistry) retire(leafID string, gate *leafGate) {
	r.mu.Lock()
	if r.gates[leafID] == gate {
		gate.retiring = true
	}
	r.mu.Unlock()
}

func (r *leafGateRegistry) release(leafID string, gate *leafGate) {
	r.mu.Lock()
	gate.refs--
	if gate.refs == 0 && r.gates[leafID] == gate {
		// Unlock before unregistering while registry ownership prevents a new
		// gate from becoming live during the handoff.
		gate.mu.Unlock()
		delete(r.gates, leafID)
		r.mu.Unlock()
		return
	}
	r.mu.Unlock()
	gate.mu.Unlock()
}

func enqueueLeafSnapshot(api *ezagentapi.Conn, update protocol.LeafUpdated) bool {
	if err := api.SendLeafUpdated(context.Background(), update); err != nil {
		// A missed authoritative snapshot would leave this client synchronized to
		// an unknowable prior state. Make the transport terminal so reconnect can
		// replay a fresh snapshot instead of silently continuing after the gap.
		_ = api.Close()
		return false
	}
	return true
}

func (s *Server) enqueueLeafSnapshotLocked(update protocol.LeafUpdated, target *Connection) bool {
	if hook := s.beforeLeafSnapshotEnqueue; hook != nil {
		hook(update)
	}
	if target != nil {
		if !s.isCurrentConnection(target) {
			return false
		}
		return enqueueLeafSnapshot(target.apiConn, update)
	}

	// One fanout operation enqueues this immutable value once per subscribed
	// connection while the leaf gate preserves capture/send order.
	enqueued := true
	s.SendToLeaf(update.LeafID, func(api *ezagentapi.Conn) error {
		if !enqueueLeafSnapshot(api, update) {
			enqueued = false
		}
		return nil
	})
	return enqueued
}

// enqueueLeafSnapshot implements leafOperationRouter. The operation retains
// its leaf gate while routing fans out this immutable snapshot.
func (s *Server) enqueueLeafSnapshot(update protocol.LeafUpdated) bool {
	return s.enqueueLeafSnapshotLocked(update, nil)
}

func (s *Server) publishLeafSnapshotTo(leafID, previousTipTurnID string, target *Connection) bool {
	return s.leaves.publishLeafSnapshot(leafID, previousTipTurnID, func(update protocol.LeafUpdated) bool {
		return s.enqueueLeafSnapshotLocked(update, target)
	})
}

// PublishLeafSnapshot preserves the public EventRouter API while leaf operations
// own snapshot capture and publication ordering.
func (s *Server) PublishLeafSnapshot(leafID, previousTipTurnID string) {
	s.leaves.PublishLeafSnapshot(leafID, previousTipTurnID)
}