protondrive: read volume events and invalidate the cache from them

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas WintherandClaude Opus 5.5 committed 2026-11-12 16:05:46 +01:00
1 parent d607fc6581
commit 877bb5d10c
8 files changed
+783 -6

No files matched your search

+43
View File
@@ -659,3 +659,46 @@ type CommitRevisionRequest struct {
ChecksumVerified bool `json:"ChecksumVerified"` // whether the SHA1 matched the source's
Photo *struct{} `json:"Photo"` // always null outside the photo volume
}
// Volume event types, as Event.EventType encodes them.
const (
EventDelete = 0 // deleted for good, or no longer accessible
EventCreate = 1
EventUpdate = 2 // changed, moved, trashed or restored
EventUpdateMetadata = 3
)
// LatestEventResponse is the response to GET
// /drive/volumes/{volumeID}/events/latest, as LatestEventIDResponseDto.
type LatestEventResponse struct {
Code int `json:"Code"`
EventID string `json:"EventID"`
}
// EventLink is the link an event is about, as EventLinkDataDto.
type EventLink struct {
LinkID string `json:"LinkID"`
ParentLinkID string `json:"ParentLinkID"` // empty if null or missing
IsShared bool `json:"IsShared"`
IsTrashed bool `json:"IsTrashed"`
}
// Event is a change to a link of a volume, as EventV2ResponseDto. It
// names the link but not its name or type.
type Event struct {
EventID string `json:"EventID"`
EventType int `json:"EventType"` // EventDelete etc
Link EventLink `json:"Link"`
}
// EventsResponse is the response to GET
// /drive/v2/volumes/{volumeID}/events/{eventID}, as
// ListEventsV2ResponseDto without the sharing fields: the events after
// an event ID, oldest first.
type EventsResponse struct {
Code int `json:"Code"`
Events []Event `json:"Events"`
EventID string `json:"EventID"` // pass as the event ID of the next call
More bool `json:"More"` // whether more events follow EventID
Refresh bool `json:"Refresh"` // the event ID asked for is unknown or too old: EventID is the newest
}
+55
View File
@@ -195,6 +195,51 @@ func (c *nodeCache) invalidate(id string) {
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.
children := make(map[string][]string)
for childID, n := range c.nodes {
children[n.ParentID] = append(children[n.ParentID], childID)
}
for parentID, ids := range c.listings {
children[parentID] = append(children[parentID], ids...)
}
// 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) {
@@ -219,3 +264,13 @@ func (c *nodeCache) clear() {
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 len(c.nodes) == 0 && len(c.listings) == 0
}
@@ -18,6 +18,7 @@ func TestNodeCacheDisabled(t *testing.T) {
assert.False(t, ok)
c.invalidate("a")
c.invalidateChildren("root")
c.invalidateTree("root")
c.clear()
}
@@ -182,3 +183,91 @@ func TestNodeCacheFetch(t *testing.T) {
var disabled *nodeCache
disabled.endFetch("dir", disabled.startFetch("dir"), nil, true)
}
func TestInvalidateTree(t *testing.T) {
c := newNodeCache(true)
c.setChildren("root", []*node{
{ID: "dir", ParentID: "root", IsFolder: true},
{ID: "keep", ParentID: "root"},
})
c.setChildren("dir", []*node{
{ID: "sub", ParentID: "dir", IsFolder: true},
{ID: "file", ParentID: "dir"},
})
c.setChildren("sub", []*node{{ID: "deep", ParentID: "sub"}})
// A descendant cached without its parent's listing.
c.put(&node{ID: "lone", ParentID: "sub"})
c.setChildren("elsewhere", []*node{{ID: "x", ParentID: "elsewhere"}})
dirFetch := c.startFetch("dir")
subFetch := c.startFetch("sub")
otherFetch := c.startFetch("elsewhere")
c.invalidateTree("dir")
for _, id := range []string{"dir", "sub", "file", "deep", "lone"} {
assert.Nil(t, c.get(id), id)
}
for _, id := range []string{"root", "dir", "sub"} {
_, ok := c.listings[id]
assert.False(t, ok, "listing %s kept", id)
}
assert.NotNil(t, c.get("keep"))
assert.NotNil(t, c.get("x"))
_, ok := c.children("elsewhere")
assert.True(t, ok)
// Listings of the tree in flight aren't cached; others are.
c.endFetch("dir", dirFetch, []*node{{ID: "file", ParentID: "dir"}}, true)
c.endFetch("sub", subFetch, []*node{{ID: "deep", ParentID: "sub"}}, true)
c.endFetch("elsewhere", otherFetch, []*node{{ID: "x", ParentID: "elsewhere"}}, true)
_, ok = c.children("dir")
assert.False(t, ok)
_, ok = c.children("sub")
assert.False(t, ok)
_, ok = c.children("elsewhere")
assert.True(t, ok)
assert.Empty(t, c.fetching)
// An unknown folder: its cached children go, and every listing in
// flight may hold it.
c = newNodeCache(true)
c.setChildren("ghost", []*node{{ID: "child", ParentID: "ghost"}})
c.put(&node{ID: "y", ParentID: "other"})
token := c.startFetch("other")
c.invalidateTree("ghost")
assert.Nil(t, c.get("child"))
assert.NotNil(t, c.get("y"))
c.endFetch("other", token, []*node{{ID: "y", ParentID: "other"}}, true)
_, ok = c.children("other")
assert.False(t, ok)
// A cycle, as a hostile server could report, ends.
c = newNodeCache(true)
c.put(&node{ID: "a", ParentID: "b", IsFolder: true})
c.put(&node{ID: "b", ParentID: "a", IsFolder: true})
c.invalidateTree("a")
assert.True(t, c.empty())
}
func TestNodeCacheEmpty(t *testing.T) {
var disabled *nodeCache
assert.True(t, disabled.empty())
c := newNodeCache(true)
assert.True(t, c.empty())
c.put(&node{ID: "a", ParentID: "root"})
assert.False(t, c.empty())
c.invalidate("a")
assert.True(t, c.empty())
// An empty listing is something cached.
c.setChildren("root", nil)
assert.False(t, c.empty())
c.clear()
assert.True(t, c.empty())
// Listings in flight aren't.
token := c.startFetch("root")
assert.True(t, c.empty())
c.endFetch("root", token, nil, false)
}
@@ -90,7 +90,7 @@ func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) {
// newTestClientTransport returns a client for a new session of u whose
// requests go through the transport wrap returns.
func newTestClientTransport(t *testing.T, srv *protontest.Server, u *protontest.User, opt clientOptions, wrap func(next http.RoundTripper) http.RoundTripper) *client {
func newTestClientTransport(t testing.TB, srv *protontest.Server, u *protontest.User, opt clientOptions, wrap func(next http.RoundTripper) http.RoundTripper) *client {
t.Helper()
base := newAccountSession(srv, u)
s := newSession(&http.Client{Transport: wrap(srv.Client().Transport)}, srv.URL(), testAppVersion, base.store)
+148
View File
@@ -0,0 +1,148 @@
package protondrive
import (
"context"
"errors"
"fmt"
"github.com/rclone/rclone/backend/protondrive/api"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/lib/rest"
)
// errVolumeGone is returned by the events calls when the volume no
// longer exists or can't be reached: no later poll can succeed.
var errVolumeGone = errors.New("volume gone")
// eventChange is a change to a node the volume events report. Events
// name the node and its parent but not its name or type.
type eventChange struct {
linkID string
parentID string // parent after the change; empty if not reported
kind int // api.EventDelete etc
trashed bool // whether the node is in the trash after the change
}
// staleNode is what the cache knew of a changed node before the change
// was applied.
type staleNode struct {
id string
parentID string // the cached parent if known, else the parent the change reports
name string // empty unless known
isDir bool
known bool // whether the node was cached
}
// latestEventID returns the ID of the newest event of the volume, from
// which pollEvents reports the changes made after now. It wraps
// errVolumeGone if the volume is gone.
func (c *client) latestEventID(ctx context.Context) (string, error) {
opts := &rest.Opts{
Method: "GET",
Path: c.volumePath("/drive/volumes", "events", "latest"),
}
var resp api.LatestEventResponse
if err := c.apiCall(ctx, opts, nil, &resp); err != nil {
return "", eventsError("get latest event", err)
}
if resp.EventID == "" {
return "", errors.New("get latest event: no event ID in the response")
}
return resp.EventID, nil
}
// pollEvents returns the changes after event cursor, oldest first, and
// the event ID to poll from next, reading every page there is.
//
// If the server no longer knows cursor it returns refresh set, no
// changes and the newest event ID: anything cached may be out of date.
// On error it returns no changes, and the poll should be retried from
// cursor. It wraps errVolumeGone if the volume is gone.
func (c *client) pollEvents(ctx context.Context, cursor string) (changes []eventChange, next string, refresh bool, err error) {
for {
opts := &rest.Opts{
Method: "GET",
Path: c.volumePath("/drive/v2/volumes", "events", cursor),
}
var page api.EventsResponse
if err := c.apiCall(ctx, opts, nil, &page); err != nil {
return nil, "", false, eventsError("list events", err)
}
if page.EventID == "" {
return nil, "", false, errors.New("list events: no event ID in the response")
}
if page.Refresh {
fs.Debugf(nil, "protondrive: events: event %s is no longer known: refreshing", cursor)
return nil, page.EventID, true, nil
}
changes = append(changes, eventChanges(page.Events)...)
// As in the SDK, a page without events ends the poll whatever
// More says, and so does one which doesn't advance.
if !page.More || len(page.Events) == 0 || page.EventID == cursor {
return changes, page.EventID, false, nil
}
cursor = page.EventID
}
}
// eventsError returns err of the events call what, wrapping
// errVolumeGone for API code 2501.
func eventsError(what string, err error) error {
if apiErrorCode(err) == api.CodeNotExists {
return fmt.Errorf("%s: %w: %w", what, errVolumeGone, err)
}
return fmt.Errorf("%s: %w", what, err)
}
// eventChanges returns the changes events report, leaving out any
// which name no node.
func eventChanges(events []api.Event) []eventChange {
changes := make([]eventChange, 0, len(events))
for _, e := range events {
if e.Link.LinkID == "" {
fs.Debugf(nil, "protondrive: events: ignoring event %q naming no node", e.EventID)
continue
}
changes = append(changes, eventChange{
linkID: e.Link.LinkID,
parentID: e.Link.ParentLinkID,
kind: e.EventType,
trashed: e.Link.IsTrashed,
})
}
return changes
}
// applyEvents drops from the cache what changes make out of date, in
// order, and returns what it knew of each changed node before: stale[i]
// is for changes[i].
//
// A deleted node, and a folder moved or trashed, goes with everything
// cached below it. Another changed node goes with its own listing. The
// listings of the node's parents before and after the change go too.
func (c *client) applyEvents(changes []eventChange) (stale []staleNode) {
stale = make([]staleNode, 0, len(changes))
for _, ch := range changes {
s := staleNode{id: ch.linkID, parentID: ch.parentID}
n := c.cache.get(ch.linkID)
if n == nil && c.root != nil && ch.linkID == c.root.ID {
n = c.root
}
if n != nil {
s = staleNode{id: n.ID, parentID: n.ParentID, name: n.Name, isDir: n.IsFolder, known: true}
}
stale = append(stale, s)
moved := s.known && ch.parentID != "" && ch.parentID != s.parentID
switch {
case ch.kind == api.EventDelete, s.isDir && (moved || ch.trashed):
c.cache.invalidateTree(ch.linkID)
default:
c.cache.invalidate(ch.linkID)
}
if ch.parentID != "" {
c.cache.invalidateChildren(ch.parentID)
}
}
return stale
}
+374
View File
@@ -0,0 +1,374 @@
package protondrive
import (
"context"
"errors"
"io"
"net/http"
"slices"
"strings"
"testing"
"time"
"github.com/rclone/rclone/backend/protondrive/api"
"github.com/rclone/rclone/backend/protondrive/protontest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const (
latestEventRoute = "/drive/volumes/{volumeID}/events/latest"
eventsRoute = "/drive/v2/volumes/{volumeID}/events/{eventID}"
)
func TestLatestEventID(t *testing.T) {
t.Parallel()
ctx := context.Background()
c, srv, u := newTestClient(t)
start, err := c.latestEventID(ctx)
require.NoError(t, err)
require.NotEmpty(t, start)
assert.Equal(t, 1, srv.Requests()["GET "+latestEventRoute])
changes, next, refresh, err := c.pollEvents(ctx, start)
require.NoError(t, err)
assert.False(t, refresh)
assert.Empty(t, changes)
assert.Equal(t, start, next)
u.SeedFolder(u.RootID(), "dir")
latest, err := c.latestEventID(ctx)
require.NoError(t, err)
assert.NotEqual(t, start, latest)
}
func TestPollEventsPages(t *testing.T) {
t.Parallel()
ctx := context.Background()
c, srv, u := newTestClient(t)
srv.SetEventsPageSize(2)
start, err := c.latestEventID(ctx)
require.NoError(t, err)
dir := u.SeedFolder(u.RootID(), "dir")
other := u.SeedFolder(u.RootID(), "other")
file := u.SeedFile(dir, "file", []byte("x"), time.Now())
u.SetParent(file, other)
srv.InjectEvent(u, protontest.Event{Type: protontest.EventUpdateMetadata, LinkID: dir, ParentLinkID: u.RootID(), IsTrashed: true})
srv.InjectEvent(u, protontest.Event{Type: protontest.EventDelete, LinkID: dir})
srv.InjectEvent(u, protontest.Event{Type: protontest.EventUpdate, LinkID: other, ParentLinkID: u.RootID(), IsShared: true})
events := srv.Events(u)
require.Len(t, events, 7)
srv.ResetRequests()
changes, next, refresh, err := c.pollEvents(ctx, start)
require.NoError(t, err)
assert.False(t, refresh)
want := make([]eventChange, len(events))
for i, e := range events {
want[i] = eventChange{linkID: e.LinkID, parentID: e.ParentLinkID, kind: e.Type, trashed: e.IsTrashed}
}
assert.Equal(t, want, changes)
assert.Equal(t, 4, srv.Requests()["GET "+eventsRoute], "pages of 2 for 7 events")
latest, err := c.latestEventID(ctx)
require.NoError(t, err)
assert.Equal(t, latest, next)
changes, again, refresh, err := c.pollEvents(ctx, next)
require.NoError(t, err)
assert.False(t, refresh)
assert.Empty(t, changes)
assert.Equal(t, next, again)
}
func TestPollEventsRefresh(t *testing.T) {
t.Parallel()
ctx := context.Background()
c, srv, u := newTestClient(t)
start, err := c.latestEventID(ctx)
require.NoError(t, err)
u.SeedFolder(u.RootID(), "dir")
srv.ExpireEvents(u)
changes, next, refresh, err := c.pollEvents(ctx, start)
require.NoError(t, err)
assert.True(t, refresh)
assert.Empty(t, changes)
latest, err := c.latestEventID(ctx)
require.NoError(t, err)
assert.Equal(t, latest, next)
// The new cursor is usable.
u.SeedFolder(u.RootID(), "after")
changes, _, refresh, err = c.pollEvents(ctx, next)
require.NoError(t, err)
assert.False(t, refresh)
assert.Len(t, changes, 1)
}
func TestPollEventsVolumeGone(t *testing.T) {
t.Parallel()
ctx := context.Background()
c, srv, _ := newTestClient(t)
start, err := c.latestEventID(ctx)
require.NoError(t, err)
srv.Inject(protontest.Fault{Pattern: eventsRoute, Status: http.StatusUnprocessableEntity, Code: api.CodeNotExists})
srv.Inject(protontest.Fault{Pattern: latestEventRoute, Status: http.StatusUnprocessableEntity, Code: api.CodeNotExists})
_, next, _, err := c.pollEvents(ctx, start)
assert.True(t, errors.Is(err, errVolumeGone), "%v", err)
assert.Empty(t, next)
_, err = c.latestEventID(ctx)
assert.True(t, errors.Is(err, errVolumeGone), "%v", err)
// Other errors are not the volume gone.
c2, srv2, _ := newTestClient(t)
srv2.Inject(protontest.Fault{Pattern: latestEventRoute, Status: http.StatusUnprocessableEntity, Code: api.CodeInvalidValue})
_, err = c2.latestEventID(ctx)
require.Error(t, err)
assert.False(t, errors.Is(err, errVolumeGone), "%v", err)
}
func TestPollEventsHostilePages(t *testing.T) {
t.Parallel()
ctx := context.Background()
for _, test := range []struct {
name string
body string
wantErr bool
changes int
next string
}{{
// As the SDK's fast-forward: an empty page ends the poll.
name: "more without events",
body: `{"Code":1000,"Events":[],"EventID":"later","More":true}`,
next: "later",
}, {
name: "more without a new ID",
body: `{"Code":1000,"Events":[{"EventID":"e","EventType":1,"Link":{"LinkID":"a"}}],"EventID":"start","More":true}`,
changes: 1,
next: "start",
}, {
name: "no ID",
body: `{"Code":1000,"Events":[],"EventID":"","More":false}`,
wantErr: true,
}, {
name: "refresh without an ID",
body: `{"Code":1000,"Events":[],"Refresh":true}`,
wantErr: true,
}, {
name: "event without a link ID",
body: `{"Code":1000,"Events":[{"EventID":"e","EventType":0,"Link":{"LinkID":""}}],"EventID":"e"}`,
next: "e",
}} {
t.Run(test.name, func(t *testing.T) {
srv := protontest.New(t)
u := srv.AddUser("user", "pass")
var pages int
c := newTestClientTransport(t, srv, u, clientOptions{EnableCaching: true}, func(next http.RoundTripper) http.RoundTripper {
return roundTripFunc(func(r *http.Request) (*http.Response, error) {
if !strings.Contains(r.URL.Path, "/events/") || strings.HasSuffix(r.URL.Path, "/latest") {
return next.RoundTrip(r)
}
pages++
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": {"application/json"}},
Body: io.NopCloser(strings.NewReader(test.body)),
Request: r,
}, nil
})
})
changes, next, _, err := c.pollEvents(ctx, "start")
assert.Equal(t, 1, pages)
if test.wantErr {
assert.Error(t, err)
return
}
require.NoError(t, err)
assert.Len(t, changes, test.changes)
assert.Equal(t, test.next, next)
})
}
}
// eventsTestClient returns a client for no server whose cache holds
// root/{dir/{sub/{deep}, file}, top, other/}, with every listing.
func eventsTestClient() *client {
c := &client{cache: newNodeCache(true), root: &node{ID: "root", IsFolder: true}}
c.cache.setChildren("root", []*node{
{ID: "dir", ParentID: "root", Name: "dir", IsFolder: true},
{ID: "top", ParentID: "root", Name: "top"},
{ID: "other", ParentID: "root", Name: "other", IsFolder: true},
})
c.cache.setChildren("dir", []*node{
{ID: "sub", ParentID: "dir", Name: "sub", IsFolder: true},
{ID: "file", ParentID: "dir", Name: "file"},
})
c.cache.setChildren("sub", []*node{{ID: "deep", ParentID: "sub", Name: "deep"}})
c.cache.setChildren("other", nil)
return c
}
func TestApplyEventsInvalidates(t *testing.T) {
t.Parallel()
all := []string{"dir", "top", "other", "sub", "file", "deep"}
listings := []string{"root", "dir", "sub", "other"}
for _, test := range []struct {
name string
change eventChange
stale staleNode
goneNodes []string
goneListings []string
}{{
name: "delete folder",
change: eventChange{linkID: "dir", parentID: "root", kind: api.EventDelete},
stale: staleNode{id: "dir", parentID: "root", name: "dir", isDir: true, known: true},
goneNodes: []string{"dir", "sub", "file", "deep"},
goneListings: []string{"root", "dir", "sub"},
}, {
name: "delete without parent",
change: eventChange{linkID: "file", kind: api.EventDelete},
stale: staleNode{id: "file", parentID: "dir", name: "file", known: true},
goneNodes: []string{"file"},
goneListings: []string{"dir"},
}, {
name: "delete unknown",
change: eventChange{linkID: "gone", kind: api.EventDelete},
stale: staleNode{id: "gone"},
goneNodes: nil,
goneListings: nil,
}, {
name: "create",
change: eventChange{linkID: "new", parentID: "other", kind: api.EventCreate},
stale: staleNode{id: "new", parentID: "other"},
goneListings: []string{"other"},
}, {
name: "rename file",
change: eventChange{linkID: "file", parentID: "dir", kind: api.EventUpdateMetadata},
stale: staleNode{id: "file", parentID: "dir", name: "file", known: true},
goneNodes: []string{"file"},
goneListings: []string{"dir"},
}, {
name: "rename folder",
change: eventChange{linkID: "sub", parentID: "dir", kind: api.EventUpdate},
stale: staleNode{id: "sub", parentID: "dir", name: "sub", isDir: true, known: true},
goneNodes: []string{"sub"},
goneListings: []string{"dir", "sub"},
}, {
name: "move file",
change: eventChange{linkID: "file", parentID: "other", kind: api.EventUpdate},
stale: staleNode{id: "file", parentID: "dir", name: "file", known: true},
goneNodes: []string{"file"},
goneListings: []string{"dir", "other"},
}, {
name: "move folder",
change: eventChange{linkID: "dir", parentID: "other", kind: api.EventUpdate},
stale: staleNode{id: "dir", parentID: "root", name: "dir", isDir: true, known: true},
goneNodes: []string{"dir", "sub", "file", "deep"},
goneListings: []string{"root", "dir", "sub", "other"},
}, {
name: "move unknown in",
change: eventChange{linkID: "stranger", parentID: "other", kind: api.EventUpdate},
stale: staleNode{id: "stranger", parentID: "other"},
goneListings: []string{"other"},
}, {
name: "trash file",
change: eventChange{linkID: "top", parentID: "root", kind: api.EventUpdate, trashed: true},
stale: staleNode{id: "top", parentID: "root", name: "top", known: true},
goneNodes: []string{"top"},
goneListings: []string{"root"},
}, {
name: "trash folder",
change: eventChange{linkID: "sub", parentID: "dir", kind: api.EventUpdateMetadata, trashed: true},
stale: staleNode{id: "sub", parentID: "dir", name: "sub", isDir: true, known: true},
goneNodes: []string{"sub", "deep"},
goneListings: []string{"dir", "sub"},
}, {
name: "untrash unknown",
change: eventChange{linkID: "back", parentID: "dir", kind: api.EventUpdate},
stale: staleNode{id: "back", parentID: "dir"},
goneListings: []string{"dir"},
}, {
name: "update root",
change: eventChange{linkID: "root", kind: api.EventUpdate},
stale: staleNode{id: "root", isDir: true, known: true},
goneListings: []string{"root"},
}, {
name: "unknown kind",
change: eventChange{linkID: "file", parentID: "dir", kind: 42},
stale: staleNode{id: "file", parentID: "dir", name: "file", known: true},
goneNodes: []string{"file"},
goneListings: []string{"dir"},
}} {
t.Run(test.name, func(t *testing.T) {
c := eventsTestClient()
stale := c.applyEvents([]eventChange{test.change})
assert.Equal(t, []staleNode{test.stale}, stale)
for _, id := range all {
gone := c.cache.get(id) == nil
assert.Equal(t, slices.Contains(test.goneNodes, id), gone, "node %s gone", id)
}
for _, id := range listings {
_, ok := c.cache.listings[id]
assert.Equal(t, slices.Contains(test.goneListings, id), !ok, "listing %s gone", id)
}
})
}
}
func TestApplyEventsSeveral(t *testing.T) {
t.Parallel()
c := eventsTestClient()
stale := c.applyEvents([]eventChange{
{linkID: "file", parentID: "dir", kind: api.EventUpdate},
{linkID: "file", parentID: "dir", kind: api.EventDelete},
{linkID: "top", parentID: "root", kind: api.EventCreate},
})
assert.Equal(t, []staleNode{
{id: "file", parentID: "dir", name: "file", known: true},
{id: "file", parentID: "dir"},
{id: "top", parentID: "root", name: "top", known: true},
}, stale)
assert.Nil(t, c.cache.get("file"))
assert.Nil(t, c.cache.get("top"))
assert.NotNil(t, c.cache.get("deep"))
// Without a cache the nodes are unknown.
c = &client{root: &node{ID: "root", IsFolder: true}}
stale = c.applyEvents([]eventChange{{linkID: "file", parentID: "dir", kind: api.EventDelete}})
assert.Equal(t, []staleNode{{id: "file", parentID: "dir"}}, stale)
assert.Empty(t, c.applyEvents(nil))
}
func TestApplyEventsFromFake(t *testing.T) {
t.Parallel()
ctx := context.Background()
c, srv, u := newTestClient(t)
dir := u.SeedFolder(u.RootID(), "dir")
other := u.SeedFolder(u.RootID(), "other")
u.SeedFile(dir, "file", []byte("x"), time.Now())
listAll(t, c, u.RootID())
listAll(t, c, dir)
listAll(t, c, other)
start, err := c.latestEventID(ctx)
require.NoError(t, err)
// Another client moves dir into other.
mover := newTestClientFor(t, srv, u, clientOptions{})
n, err := mover.getNode(ctx, dir)
require.NoError(t, err)
require.NoError(t, mover.move(ctx, n, other, "dir"))
assert.Contains(t, listAll(t, c, u.RootID()), "dir", "cached")
changes, _, _, err := c.pollEvents(ctx, start)
require.NoError(t, err)
stale := c.applyEvents(changes)
require.Len(t, stale, 1)
assert.Equal(t, staleNode{id: dir, parentID: u.RootID(), name: "dir", isDir: true, known: true}, stale[0])
assert.NotContains(t, listAll(t, c, u.RootID()), "dir")
assert.Contains(t, listAll(t, c, other), "dir")
assert.Contains(t, listAll(t, c, dir), "file")
}
+68
View File
@@ -13,6 +13,7 @@ import (
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"unicode/utf16"
@@ -365,3 +366,70 @@ func FuzzDecryptForkPayload(f *testing.F) {
assert.Equal(t, *p.KeyPassword, keyPassword)
})
}
func FuzzDecodeEvents(f *testing.F) {
// Pages the fake sends for changes of each kind.
srv := protontest.New(f)
u := srv.AddUser("user", "pass")
var (
mu sync.Mutex
pages [][]byte
)
c := newTestClientTransport(f, srv, u, clientOptions{EnableCaching: true}, func(next http.RoundTripper) http.RoundTripper {
return roundTripFunc(func(r *http.Request) (*http.Response, error) {
resp, err := next.RoundTrip(r)
if err != nil || !strings.Contains(r.URL.Path, "/events/") {
return resp, err
}
body, err := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if err != nil {
return nil, err
}
mu.Lock()
pages = append(pages, body)
mu.Unlock()
resp.Body = io.NopCloser(bytes.NewReader(body))
return resp, nil
})
})
srv.SetEventsPageSize(3)
ctx := context.Background()
start, err := c.latestEventID(ctx)
require.NoError(f, err)
dir := u.SeedFolder(u.RootID(), "dir")
file := u.SeedFile(dir, "file", []byte("x"), time.Now())
u.SetParent(file, u.RootID())
srv.InjectEvent(u, protontest.Event{Type: protontest.EventUpdate, LinkID: dir, ParentLinkID: u.RootID(), IsTrashed: true})
srv.InjectEvent(u, protontest.Event{Type: protontest.EventDelete, LinkID: dir})
_, _, _, err = c.pollEvents(ctx, start)
require.NoError(f, err)
srv.ExpireEvents(u)
_, _, _, err = c.pollEvents(ctx, start)
require.NoError(f, err)
require.NotEmpty(f, pages)
for _, page := range pages {
f.Add(page)
}
f.Add([]byte(`{"Code":1000,"Events":[{"EventID":"e","EventType":0,"Link":{"LinkID":"dir","ParentLinkID":null}}],"EventID":"e","More":true}`))
f.Add([]byte(`{"Events":[{"EventType":99,"Link":{"LinkID":"root","ParentLinkID":"root","IsTrashed":true}}]}`))
f.Add([]byte(`{"Events":[{"EventType":2,"Link":{"LinkID":"a","ParentLinkID":"a"}}]}`))
f.Add([]byte(`{"Events":null,"More":1}`))
f.Fuzz(func(t *testing.T, data []byte) {
var resp api.EventsResponse
if json.Unmarshal(data, &resp) != nil {
return
}
c := eventsTestClient()
c.cache.put(&node{ID: "a", ParentID: "b", IsFolder: true})
c.cache.put(&node{ID: "b", ParentID: "a", IsFolder: true})
changes := eventChanges(resp.Events)
stale := c.applyEvents(changes)
require.Len(t, stale, len(changes))
for i, ch := range changes {
assert.NotEmpty(t, ch.linkID)
assert.Equal(t, ch.linkID, stale[i].id)
assert.Nil(t, c.cache.get(ch.linkID), "changed node %s still cached", ch.linkID)
}
})
}
+5 -5
View File
@@ -123,11 +123,11 @@ prefix, Proton's exact JSON field names. In addition:
- `func (n *nodeCache) invalidateTree(id string)` and `func (n *nodeCache) empty() bool` (nil cache: `empty` is true).
- `errVolumeGone` returned by both calls on code 2501.
- [ ] **Step 1: Write failing tests**: `TestLatestEventID`; `TestPollEventsPages` (fake page size 2, 7 changes: all 7 returned in order, `next` equals the fake's newest ID); `TestPollEventsRefresh`; `TestPollEventsVolumeGone` (`errors.Is(err, errVolumeGone)`); `TestApplyEventsInvalidates` (table per event kind with a warmed cache: which nodes and listings are gone afterwards, and the returned `staleNode` values); `TestInvalidateTree` (folder with nested cached children: all gone, unrelated nodes kept, in-flight listing guard bumped); `TestNodeCacheEmpty`; `FuzzDecodeEvents` (arbitrary JSON into `api.EventsResponse` and through `applyEvents` on a small cache: no panic).
- [ ] **Step 2: Run** `RCLONE_CONFIG=/notfound go test ./backend/protondrive/ -run 'Event|InvalidateTree|NodeCacheEmpty' -v` - expect FAIL.
- [ ] **Step 3: Implement** in `events.go` (no `fs.Fs` types; logging only through `fs.Debugf`/`fs.Errorf`).
- [ ] **Step 4: Run** the tests, then `go test -run '^$' -fuzz FuzzDecodeEvents -fuzztime 20s ./backend/protondrive/` - expect PASS, no crash.
- [ ] **Step 5: Commit** `protondrive: read volume events and invalidate the cache from them`.
- [x] **Step 1: Write failing tests**: `TestLatestEventID`; `TestPollEventsPages` (fake page size 2, 7 changes: all 7 returned in order, `next` equals the fake's newest ID); `TestPollEventsRefresh`; `TestPollEventsVolumeGone` (`errors.Is(err, errVolumeGone)`); `TestApplyEventsInvalidates` (table per event kind with a warmed cache: which nodes and listings are gone afterwards, and the returned `staleNode` values); `TestInvalidateTree` (folder with nested cached children: all gone, unrelated nodes kept, in-flight listing guard bumped); `TestNodeCacheEmpty`; `FuzzDecodeEvents` (arbitrary JSON into `api.EventsResponse` and through `applyEvents` on a small cache: no panic).
- [x] **Step 2: Run** `RCLONE_CONFIG=/notfound go test ./backend/protondrive/ -run 'Event|InvalidateTree|NodeCacheEmpty' -v` - expect FAIL.
- [x] **Step 3: Implement** in `events.go` (no `fs.Fs` types; logging only through `fs.Debugf`/`fs.Errorf`).
- [x] **Step 4: Run** the tests, then `go test -run '^$' -fuzz FuzzDecodeEvents -fuzztime 20s ./backend/protondrive/` - expect PASS, no crash.
- [x] **Step 5: Commit** `protondrive: read volume events and invalidate the cache from them`.
### Task 3: The poller