pkg/service/leaf_list_sync.go

package service

import (
	"container/list"
	"encoding/json"
	"errors"
	"hash/fnv"
	"sync"
	"time"

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

// Sync views let a list_leaves client poll for changes since the revision it
// last received. Each view keeps its filters, the confirmed revision's row
// fingerprints, and the newest sent revision until the client confirms it.
// Views live only in memory, are not tied to a connection, and are evicted
// least recently used under a budget that scales with the leaf count.
const (
	leafListSyncMinIdle     = 10 * time.Minute
	leafListSyncFloorBytes  = 32 << 20
	leafListSyncBudgetViews = 32
	leafListSyncPrintBytes  = 48
	// leafListSyncViewBytes charges every view, even an empty one, for its
	// filters, maps and LRU entry so empty views still reach eviction.
	leafListSyncViewBytes    = 4 << 10
	leafListSyncMaxFilterKey = 32
)

type leafListViews struct {
	mu          sync.Mutex
	views       map[string]*leafListView
	order       *list.List // front is most recently used
	totalBytes  int64
	now         func() time.Time
	countLeaves func() (int64, error)
	query       func(session.LeafQuery, leafListVisibility) ([]protocol.LeafInfo, error)
}

// Compare the policies, not the current flags. A held page can still contain
// a question that has cleared since the page was built.
type leafListVisibility struct {
	projectTrust bool
	toolApproval bool
	// A provider that has asked for approval cannot see its own questions.
	approvalAsker string
}

type leafListView struct {
	id         string
	query      session.LeafQuery
	visibility leafListVisibility
	baseBytes  int64

	// mu serializes requests on this view; leafListViews.mu guards the rest.
	mu        sync.Mutex
	elem      *list.Element
	lastUsed  time.Time
	bytes     int64
	confirmed leafListRevision
	sent      *leafListSent
	revisions int64
}

type leafListRevision struct {
	number int64
	prints map[string]uint64
}

type leafListSent struct {
	leafListRevision
	leaves    []protocol.LeafInfo
	removed   []string
	heldBytes int64
}

// leafListSyncError is a view state the service cannot serve.
type leafListSyncError struct{ message string }

func (e *leafListSyncError) Error() string { return e.message }

// errLeafListVisibilityStale reports a capture whose recipient's visibility
// changed while it ran; nothing was published and the caller retries.
var errLeafListVisibilityStale = errors.New("leaf list visibility changed during capture")

func newLeafListViews(query func(session.LeafQuery, leafListVisibility) ([]protocol.LeafInfo, error), countLeaves func() (int64, error)) *leafListViews {
	return &leafListViews{
		views:       make(map[string]*leafListView),
		order:       list.New(),
		now:         time.Now,
		countLeaves: countLeaves,
		query:       query,
	}
}

func leafPrint(info protocol.LeafInfo) (uint64, int64) {
	encoded, _ := json.Marshal(info)
	h := fnv.New64a()
	_, _ = h.Write(encoded)
	return h.Sum64(), int64(len(encoded))
}

// open runs the query, creates a view at revision 1, and returns its first chunk.
// A non-nil stale is checked after capture, before the view is published.
func (v *leafListViews) open(q session.LeafQuery, visibility leafListVisibility, stale func() bool) (protocol.LeafList, error) {
	leaves, err := v.query(q, visibility)
	if err != nil {
		return protocol.LeafList{}, err
	}
	if stale != nil && stale() {
		return protocol.LeafList{}, errLeafListVisibilityStale
	}
	view := &leafListView{id: session.NewID("v_"), query: q, visibility: visibility, baseBytes: leafListViewBaseBytes(q), confirmed: leafListRevision{prints: map[string]uint64{}}}
	view.sent = buildSent(1, leaves, nil)
	view.revisions = 1
	reply := view.chunk(0)
	v.mu.Lock()
	v.views[view.id] = view
	view.elem = v.order.PushFront(view)
	v.touchLocked(view)
	v.evictLocked(view)
	v.mu.Unlock()
	return reply, nil
}

// continueView serves a chunk read (offset present) or a poll (offset absent).
// A poll checks a non-nil stale after capture, before changing shared view
// state, so a rejected poll leaves held revisions intact for other readers.
func (v *leafListViews) continueView(syncID string, revision int64, offset *int64, visibility leafListVisibility, stale func() bool) (protocol.LeafList, error) {
	v.mu.Lock()
	view := v.views[syncID]
	v.mu.Unlock()
	if view == nil {
		return protocol.LeafList{}, &leafListSyncError{"sync view is unknown or evicted"}
	}
	if view.visibility != visibility {
		return protocol.LeafList{}, &leafListSyncError{"sync view has different question visibility"}
	}
	view.mu.Lock()
	defer view.mu.Unlock()
	var reply protocol.LeafList
	if offset != nil {
		if view.sent == nil || view.sent.number != revision {
			return protocol.LeafList{}, &leafListSyncError{"sync revision is not held"}
		}
		if *offset > int64(len(view.sent.leaves)) {
			return protocol.LeafList{}, &leafListSyncError{"sync offset is out of range"}
		}
		reply = view.chunk(*offset)
	} else {
		baseline := view.confirmed
		switch {
		case view.sent != nil && revision == view.sent.number:
			baseline = view.sent.leafListRevision
		case revision == view.confirmed.number && revision > 0:
			// The newest sent revision was not fully received; diff again.
		default:
			return protocol.LeafList{}, &leafListSyncError{"sync revision is not held"}
		}
		leaves, err := v.query(view.query, visibility)
		if err != nil {
			return protocol.LeafList{}, err
		}
		if stale != nil && stale() {
			return protocol.LeafList{}, errLeafListVisibilityStale
		}
		view.confirmed = baseline
		view.revisions++
		view.sent = buildSent(view.revisions, leaves, baseline.prints)
		reply = view.chunk(0)
	}
	v.mu.Lock()
	if v.views[view.id] == view {
		v.order.MoveToFront(view.elem)
		v.touchLocked(view)
		v.evictLocked(view)
	}
	v.mu.Unlock()
	return reply, nil
}

// buildSent fingerprints the current rows. With a baseline it keeps only
// changed rows and lists removed IDs; a nil baseline sends every row.
func buildSent(number int64, leaves []protocol.LeafInfo, baseline map[string]uint64) *leafListSent {
	sent := &leafListSent{leafListRevision: leafListRevision{number: number, prints: make(map[string]uint64, len(leaves))}}
	for _, info := range leaves {
		fp, size := leafPrint(info)
		sent.prints[info.ID] = fp
		if old, ok := baseline[info.ID]; ok && old == fp {
			continue
		}
		sent.leaves = append(sent.leaves, info)
		sent.heldBytes += size
	}
	if baseline != nil {
		for id := range baseline {
			if _, ok := sent.prints[id]; !ok {
				sent.removed = append(sent.removed, id)
			}
		}
	}
	return sent
}

func (view *leafListView) chunk(offset int64) protocol.LeafList {
	sent := view.sent
	end := offset + protocol.LeafListSyncChunk
	if end > int64(len(sent.leaves)) {
		end = int64(len(sent.leaves))
	}
	leaves := make([]protocol.LeafInfo, 0, end-offset)
	leaves = append(leaves, sent.leaves[offset:end]...)
	total := int64(len(sent.leaves))
	reply := protocol.LeafList{Leaves: leaves, SyncID: view.id, Revision: sent.number, Offset: &offset, Total: &total}
	if offset == 0 && len(sent.removed) > 0 {
		reply.Removed = append([]string(nil), sent.removed...)
	}
	return reply
}

func leafListViewBaseBytes(q session.LeafQuery) int64 {
	bytes := int64(leafListSyncViewBytes + len(q.Cwd))
	if q.RootID != nil {
		bytes += int64(len(*q.RootID))
	}
	for _, key := range q.MetadataKeys {
		bytes += int64(len(key))
	}
	for key, value := range q.MetadataEquals {
		bytes += int64(len(key) + len(value))
	}
	for _, key := range q.MetadataPresent {
		bytes += int64(len(key))
	}
	return bytes
}

func (v *leafListViews) touchLocked(view *leafListView) {
	bytes := view.baseBytes + int64(len(view.confirmed.prints))*leafListSyncPrintBytes
	if view.sent != nil {
		bytes += int64(len(view.sent.prints))*leafListSyncPrintBytes + view.sent.heldBytes
	}
	v.totalBytes += bytes - view.bytes
	view.bytes = bytes
	view.lastUsed = v.now()
}

// evictLocked removes least recently used views over budget. Views used within
// the minimum idle time, including current, are never evicted.
func (v *leafListViews) evictLocked(current *leafListView) {
	if v.totalBytes <= leafListSyncFloorBytes {
		return
	}
	budget := int64(leafListSyncFloorBytes)
	if v.countLeaves != nil {
		if count, err := v.countLeaves(); err == nil {
			if scaled := leafListSyncBudgetViews * count * leafListSyncPrintBytes; scaled > budget {
				budget = scaled
			}
		}
	}
	now := v.now()
	for elem := v.order.Back(); elem != nil && v.totalBytes > budget; {
		view := elem.Value.(*leafListView)
		prev := elem.Prev()
		if view != current && now.Sub(view.lastUsed) >= leafListSyncMinIdle {
			v.order.Remove(elem)
			delete(v.views, view.id)
			v.totalBytes -= view.bytes
		}
		elem = prev
	}
}