pkg/service/leaf_sync.go

package service

import (
	"context"
	"errors"
	"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
}

// Advertising support does not grant approval authority. Restricted peers and
// daemon-managed providers are not human approval clients.
func (s *Server) toolApprovalEligible(c *Connection) bool {
	return !toolConnectionClosed(c) && c.canAnswerQuestions()
}

func toolApprovalSupportKnown(c *Connection) bool {
	version, err := c.apiConn.RemoteSupportsIfKnown(protocol.ExtraToolApproval, 1, 1)
	return err == nil && version == 1
}

type approvalSnapshotReplay struct{ leafID string }

// After a compatible snapshot, wait outside the leaf gate. Refresh only a
// current subscription with a pending approval to show.
func (s *Server) replayWhenApprovalSupportKnown(c *Connection) {
	version, err := c.apiConn.RemoteSupports(context.Background(), protocol.ExtraToolApproval, 1, 1)
	if err != nil || version != 1 {
		return
	}
	c.selectionMu.Lock()
	replay := c.approvalReplay
	c.selectionMu.Unlock()
	if replay == nil {
		return
	}
	gate, ok := s.leaves.acquireGate(replay.leafID)
	if !ok {
		return
	}
	defer s.leaves.releaseGate(replay.leafID, gate)
	c.selectionMu.Lock()
	defer c.selectionMu.Unlock()
	if c.approvalReplay != replay || !s.isSubscribed(c, replay.leafID) {
		return
	}
	c.approvalReplay = nil
	approvals := s.toolApprovals.pendingQuestions(replay.leafID)
	if len(approvals) == 0 {
		return
	}
	if update, ok := s.leaves.buildSnapshotLocked(replay.leafID, ""); ok {
		s.enqueueRecipientSnapshotLocked(c, update, approvals)
	}
}

// The leaf gate and selectionMu are held. Copy the question slice only when
// adding tool approvals, leaving the compatible snapshot intact for others.
func (s *Server) enqueueRecipientSnapshotLocked(c *Connection, update protocol.LeafUpdated, approvals []*toolApproval) bool {
	var unknown *ezagentapi.CapabilityUnknownError
	var err error
	if s.toolApprovalEligible(c) && s.isSubscribed(c, update.LeafID) {
		var version int
		version, err = c.apiConn.RemoteSupportsIfKnown(protocol.ExtraToolApproval, 1, 1)
		if err == nil && version == 1 && len(approvals) != 0 {
			questions := make([]protocol.PendingQuestion, 0, len(update.PendingQuestions)+len(approvals))
			questions = append(questions, update.PendingQuestions...)
			update.PendingQuestions = appendRecipientApprovals(questions, approvals, c)
		}
	}
	if !enqueueLeafSnapshot(c.apiConn, update) {
		return false
	}
	if errors.As(err, &unknown) {
		if c.approvalReplay == nil {
			c.approvalReplay = &approvalSnapshotReplay{leafID: update.LeafID}
		}
		c.approvalDiscovery.Do(func() { go s.replayWhenApprovalSupportKnown(c) })
	} else if c.approvalReplay != nil && c.approvalReplay.leafID == update.LeafID {
		c.approvalReplay = nil
	}
	return true
}

// The asking provider never sees or answers its own question.
func appendRecipientApprovals(questions []protocol.PendingQuestion, approvals []*toolApproval, c *Connection) []protocol.PendingQuestion {
	for _, approval := range approvals {
		if approval.provider != c {
			questions = append(questions, approval.question)
		}
	}
	return questions
}

// answerableQuestionsLocked requires the leaf gate, which orders this capture
// with snapshots and replies. It returns only questions c may answer and
// reads project trust without recording an observation.
func (s *Server) answerableQuestionsLocked(c *Connection, leafID string) []protocol.PendingQuestion {
	if !s.toolApprovalEligible(c) || !approvalTransportLive(c) {
		return nil
	}
	questions := s.leaves.observedProjectQuestionsLocked(leafID)
	// Start or reuse SDK discovery without waiting, even when there are no
	// approvals. The extra request must not reveal that an approval exists.
	if toolApprovalSupportKnown(c) {
		questions = appendRecipientApprovals(questions, s.toolApprovals.pendingQuestions(leafID), c)
	}
	return questions
}

func (s *Server) enqueueLeafSnapshotLocked(update protocol.LeafUpdated, target *Connection, requireSubscription bool) bool {
	if hook := s.beforeLeafSnapshotEnqueue; hook != nil {
		hook(update)
	}
	approvals := s.toolApprovals.pendingQuestions(update.LeafID)
	if target != nil {
		target.selectionMu.Lock()
		defer target.selectionMu.Unlock()
		if !s.isCurrentConnection(target) || (requireSubscription && !s.isSubscribed(target, update.LeafID)) {
			return false
		}
		return s.enqueueRecipientSnapshotLocked(target, update, approvals)
	}

	// One fanout operation enqueues a complete snapshot per recipient while
	// the leaf gate preserves capture/send order.
	enqueued := true
	for _, c := range s.leafSubscribers(update.LeafID) {
		c.selectionMu.Lock()
		if s.isSubscribed(c, update.LeafID) && !s.enqueueRecipientSnapshotLocked(c, update, approvals) {
			enqueued = false
		}
		c.selectionMu.Unlock()
	}
	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, false)
}

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, false)
	})
}

// 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)
}