pkg/ezagentapi/leaf_sync.go
package ezagentapi
import (
"context"
"errors"
"sort"
"git.cafe/ezterry/ez-agent/pkg/protocol"
)
// LeafListOptions selects leaves for list_leaves. Zero fields are omitted.
// Cwd takes precedence over RootID; metadata filters combine with either.
type LeafListOptions struct {
RootID string
Cwd string
MetadataKeys []string
IsActive bool
MetadataEquals map[string]string
MetadataPresent []string
}
func (o LeafListOptions) request() protocol.ListLeaves {
return protocol.ListLeaves{Type: "list_leaves", RootID: o.RootID, Cwd: o.Cwd, MetadataKeys: o.MetadataKeys,
IsActive: o.IsActive, MetadataEquals: o.MetadataEquals, MetadataPresent: o.MetadataPresent}
}
// ListLeavesWithOptions returns a plain, unsynced list.
func (s *RPC) ListLeavesWithOptions(ctx context.Context, opts LeafListOptions) ([]protocol.LeafInfo, error) {
list, err := s.ListLeavesRequest(ctx, opts.request())
if err != nil {
return nil, err
}
return list.Leaves, nil
}
// ListLeavesRequest sends one list_leaves frame and returns the whole reply,
// including sync fields. Type and RequestID are supplied by the RPC.
func (s *RPC) ListLeavesRequest(ctx context.Context, req protocol.ListLeaves) (protocol.LeafList, error) {
req.Type = "list_leaves"
return serviceCall(ctx, s.conn, s.leafListPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
req.RequestID = reqID
return s.conn.sendFrame(ctx, req)
})
}
// IsLeafListSyncUnavailable reports whether err asks the client to reopen a
// sync view.
func IsLeafListSyncUnavailable(err error) bool {
var service *ServiceError
return errors.As(err, &service) && service.Code == protocol.LeafListSyncUnavailable
}
// LeafSyncView keeps a local copy of one list_leaves query current. Refresh
// opens a server sync view, then polls it for changed and removed rows,
// reopening when the service no longer holds the view. Against a service
// without sync support every Refresh is a full list. A LeafSyncView is not
// safe for concurrent use; callers keep at most one Refresh in flight.
type LeafSyncView struct {
rpc *RPC
opts LeafListOptions
syncID string
revision int64
rows map[string]protocol.LeafInfo
sorted []protocol.LeafInfo
loaded bool
}
// NewLeafSyncView prepares a view; no request is sent until Refresh.
func NewLeafSyncView(rpc *RPC, opts LeafListOptions) *LeafSyncView {
return &LeafSyncView{rpc: rpc, opts: opts}
}
// Leaves returns the last complete copy, newest first. Rows include the
// recipient's HasPendingQuestions flag; older services omit it (false).
// Callers must not modify the returned rows.
func (v *LeafSyncView) Leaves() []protocol.LeafInfo { return v.sorted }
// Loaded reports whether a complete copy has been received.
func (v *LeafSyncView) Loaded() bool { return v.loaded }
// Refresh brings the copy up to date and reports whether it changed. On error
// the previous copy and revision are kept, so the next Refresh retries.
func (v *LeafSyncView) Refresh(ctx context.Context) ([]protocol.LeafInfo, bool, error) {
if v.syncID != "" {
changed, err := v.poll(ctx)
if err == nil || !IsLeafListSyncUnavailable(err) {
return v.sorted, changed, err
}
v.syncID, v.revision = "", 0
}
changed, err := v.open(ctx)
if IsLeafListSyncUnavailable(err) {
// Discovery can change visibility between the first page and a chunk read.
changed, err = v.open(ctx)
}
return v.sorted, changed, err
}
func (v *LeafSyncView) open(ctx context.Context) (bool, error) {
req := v.opts.request()
req.Sync = true
first, err := v.rpc.ListLeavesRequest(ctx, req)
if err != nil {
return false, err
}
if first.SyncID == "" {
// An older service ignores sync and returns a complete plain list.
v.replace(first.Leaves)
return true, nil
}
leaves, _, err := v.collect(ctx, first)
if err != nil {
return false, err
}
v.replace(leaves)
v.syncID, v.revision = first.SyncID, first.Revision
return true, nil
}
func (v *LeafSyncView) poll(ctx context.Context) (bool, error) {
first, err := v.rpc.ListLeavesRequest(ctx, protocol.ListLeaves{SyncID: v.syncID, Revision: v.revision})
if err != nil {
return false, err
}
if first.SyncID != v.syncID {
return false, &ServiceError{Code: protocol.LeafListSyncUnavailable, Message: "sync reply names a different view"}
}
leaves, removed, err := v.collect(ctx, first)
if err != nil {
return false, err
}
v.revision = first.Revision
if len(leaves) == 0 && len(removed) == 0 {
return false, nil
}
for _, id := range removed {
delete(v.rows, id)
}
for _, leaf := range leaves {
v.rows[leaf.ID] = leaf
}
v.resort()
return true, nil
}
// collect fetches the remaining chunks of first's revision.
func (v *LeafSyncView) collect(ctx context.Context, first protocol.LeafList) ([]protocol.LeafInfo, []string, error) {
leaves := append([]protocol.LeafInfo(nil), first.Leaves...)
removed := append([]string(nil), first.Removed...)
if first.Total == nil {
return leaves, removed, nil
}
for int64(len(leaves)) < *first.Total {
offset := int64(len(leaves))
next, err := v.rpc.ListLeavesRequest(ctx, protocol.ListLeaves{SyncID: first.SyncID, Revision: first.Revision, Offset: &offset})
if err != nil {
return nil, nil, err
}
if len(next.Leaves) == 0 {
return nil, nil, &ServiceError{Code: protocol.LeafListSyncUnavailable, Message: "sync chunk ended early"}
}
leaves = append(leaves, next.Leaves...)
removed = append(removed, next.Removed...)
}
return leaves, removed, nil
}
func (v *LeafSyncView) replace(leaves []protocol.LeafInfo) {
v.rows = make(map[string]protocol.LeafInfo, len(leaves))
for _, leaf := range leaves {
v.rows[leaf.ID] = leaf
}
v.loaded = true
v.resort()
}
// resort matches the service order: updated_at, then ID, both descending.
func (v *LeafSyncView) resort() {
sorted := make([]protocol.LeafInfo, 0, len(v.rows))
for _, leaf := range v.rows {
sorted = append(sorted, leaf)
}
sort.Slice(sorted, func(i, j int) bool {
if sorted[i].UpdatedAt != sorted[j].UpdatedAt {
return sorted[i].UpdatedAt > sorted[j].UpdatedAt
}
return sorted[i].ID > sorted[j].ID
})
v.sorted = sorted
}