package protondrive import ( "slices" "sync" "sync/atomic" "time" ) // nodeCache holds decrypted nodes and folder listings in memory. // // A nil nodeCache, as newNodeCache returns when caching is disabled, // holds nothing: its lookups miss and its updates do nothing. Cached // nodes are shared and must not be modified. type nodeCache struct { mu sync.Mutex nodes map[string]*node // by ID listings map[string][]string // IDs of the complete listing of a folder, by folder ID fetching map[string]*fetchState // folders being listed from the server, by folder ID used atomic.Int64 // when the cache was last read or filled, in Unix nanoseconds // onFill, if set, is called without mu held when the cache gains // its first entry, from empty. It is read without mu, so it must // be set before the cache is shared. onFill func() } // fetchState tracks the listings of a folder being fetched, so that // one which began before a change to the folder's children isn't // cached over it. type fetchState struct { count int // listings in progress changes uint64 // changes to the folder's children since the first began } // newNodeCache returns an empty cache, or nil if enabled is false. func newNodeCache(enabled bool) *nodeCache { if !enabled { return nil } return &nodeCache{ nodes: make(map[string]*node), listings: make(map[string][]string), fetching: make(map[string]*fetchState), } } // get returns the node id, or nil if it isn't cached. func (c *nodeCache) get(id string) *node { if c == nil { return nil } c.touch() return c.peek(id) } // peek is get, but doesn't count as a use of the cache: it is for the // cache's own upkeep. func (c *nodeCache) peek(id string) *node { if c == nil { return nil } c.mu.Lock() defer c.mu.Unlock() return c.nodes[id] } // touch records that the cache is in use now. func (c *nodeCache) touch() { c.used.Store(time.Now().UnixNano()) } // unusedFor returns how long ago the cache was last read or filled; a // nil cache, or one never used, counts as used now. func (c *nodeCache) unusedFor() time.Duration { if c == nil { return 0 } used := c.used.Load() if used == 0 { return 0 } return time.Since(time.Unix(0, used)) } // put caches n, replacing any node with its ID. If the cached node had // another parent, the listings of both parents are forgotten. func (c *nodeCache) put(n *node) { if c == nil { return } c.touch() c.mu.Lock() defer c.filled(c.emptyLocked()) defer c.mu.Unlock() if old := c.nodes[n.ID]; old != nil && old.ParentID != n.ParentID { c.childrenChangedLocked(old.ParentID) c.childrenChangedLocked(n.ParentID) } c.nodes[n.ID] = n } // children returns the cached listing of folder parentID. It reports // false if the listing, or any node in it, isn't cached. func (c *nodeCache) children(parentID string) ([]*node, bool) { if c == nil { return nil, false } c.touch() c.mu.Lock() defer c.mu.Unlock() ids, ok := c.listings[parentID] if !ok { return nil, false } out := make([]*node, 0, len(ids)) for _, id := range ids { n := c.nodes[id] if n == nil { return nil, false } out = append(out, n) } return out, true } // setChildren caches nodes as the complete listing of folder parentID, // and each of the nodes. The listings of other parents a node was // cached under are forgotten. func (c *nodeCache) setChildren(parentID string, nodes []*node) { if c == nil { return } c.touch() c.mu.Lock() defer c.filled(c.emptyLocked()) defer c.mu.Unlock() c.setChildrenLocked(parentID, nodes) } // setChildrenLocked is setChildren with c.mu held. func (c *nodeCache) setChildrenLocked(parentID string, nodes []*node) { ids := make([]string, len(nodes)) for i, n := range nodes { ids[i] = n.ID if old := c.nodes[n.ID]; old != nil && old.ParentID != parentID { c.childrenChangedLocked(old.ParentID) } c.nodes[n.ID] = n } c.listings[parentID] = ids } // startFetch records that a listing of folder parentID is being read // from the server and returns the token to pass to endFetch, which // must be called. func (c *nodeCache) startFetch(parentID string) (token uint64) { if c == nil { return 0 } c.mu.Lock() defer c.mu.Unlock() st := c.fetching[parentID] if st == nil { st = &fetchState{} c.fetching[parentID] = st } st.count++ return st.changes } // endFetch ends a listing of folder parentID begun by startFetch with // token. If complete is set, nodes are cached as the listing, unless // the folder's children changed since it began, when what it read may // be out of date. func (c *nodeCache) endFetch(parentID string, token uint64, nodes []*node, complete bool) { if c == nil { return } c.touch() c.mu.Lock() defer c.filled(c.emptyLocked()) defer c.mu.Unlock() st := c.fetching[parentID] if complete && st.changes == token { c.setChildrenLocked(parentID, nodes) } st.count-- if st.count == 0 { delete(c.fetching, parentID) } } // childrenChangedLocked forgets the listing of folder parentID, and // marks its listings being fetched as out of date. c.mu must be held. func (c *nodeCache) childrenChangedLocked(parentID string) { delete(c.listings, parentID) if st := c.fetching[parentID]; st != nil { st.changes++ } } // add caches n, a node new to its parent, and adds it to the cached // listing of its parent, if there is one. func (c *nodeCache) add(n *node) { if c == nil { return } c.touch() c.mu.Lock() defer c.filled(c.emptyLocked()) defer c.mu.Unlock() if old := c.nodes[n.ID]; old != nil && old.ParentID != n.ParentID { c.childrenChangedLocked(old.ParentID) c.childrenChangedLocked(n.ParentID) } c.nodes[n.ID] = n if st := c.fetching[n.ParentID]; st != nil { st.changes++ } if ids, ok := c.listings[n.ParentID]; ok && !slices.Contains(ids, n.ID) { c.listings[n.ParentID] = append(ids, n.ID) } } // invalidate forgets the node id, its listing if it is a folder, and // the listing of its parent. func (c *nodeCache) invalidate(id string) { if c == nil { return } c.mu.Lock() defer c.mu.Unlock() if n := c.nodes[id]; n != nil { c.childrenChangedLocked(n.ParentID) } else { // Its parent is unknown, and any listing being fetched may // hold it. for _, st := range c.fetching { st.changes++ } } delete(c.nodes, id) c.childrenChangedLocked(id) } // invalidateTree forgets the node id, the listing of its parent, and // the node, listing and descendants of everything below it: the // descendants of a folder deleted or moved are cached under paths they // no longer have. func (c *nodeCache) invalidateTree(id string) { if c == nil { return } c.mu.Lock() defer c.mu.Unlock() if n := c.nodes[id]; n != nil { c.childrenChangedLocked(n.ParentID) } else { // Its parent is unknown, and any listing being fetched may // hold it. for _, st := range c.fetching { st.changes++ } } // Descendants may be cached without their parent's listing, so // they are found by parent ID. Every node a listing names is // cached, so the listings add none. children := make(map[string][]string) for childID, n := range c.nodes { children[n.ParentID] = append(children[n.ParentID], childID) } // Visited IDs end the walk of a cycle a hostile server reported. visited := map[string]bool{id: true} pending := []string{id} for len(pending) > 0 { next := pending[len(pending)-1] pending = pending[:len(pending)-1] delete(c.nodes, next) c.childrenChangedLocked(next) for _, childID := range children[next] { if !visited[childID] { visited[childID] = true pending = append(pending, childID) } } } } // invalidateChildren forgets the listing of folder parentID, but not // the nodes in it. func (c *nodeCache) invalidateChildren(parentID string) { if c == nil { return } c.mu.Lock() defer c.mu.Unlock() c.childrenChangedLocked(parentID) } // clear forgets everything. func (c *nodeCache) clear() { if c == nil { return } c.mu.Lock() defer c.mu.Unlock() clear(c.nodes) clear(c.listings) for _, st := range c.fetching { st.changes++ } } // empty reports whether nothing is cached. A nil cache is empty. func (c *nodeCache) empty() bool { if c == nil { return true } c.mu.Lock() defer c.mu.Unlock() return c.emptyLocked() } // emptyLocked is empty with c.mu held. func (c *nodeCache) emptyLocked() bool { return len(c.nodes) == 0 && len(c.listings) == 0 } // filled calls onFill if the cache was empty before an update, as // wasEmpty says, and holds something now. c.mu must not be held. func (c *nodeCache) filled(wasEmpty bool) { if wasEmpty && c.onFill != nil && !c.empty() { c.onFill() } }