build / windows (push) Skipped
build / other_os (push) Skipped
build / mac_amd64 (push) Skipped
build / mac_arm64 (push) Skipped
build / linux (push) Skipped
build / go1.26 (push) Skipped
build / linux_386 (push) Skipped
build / lint (push) Skipped
build / android-all (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/386 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/amd64 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm/v6 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm/v7 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm64 (push) Skipped
Build & Push Docker Images / Merge & Push Final Docker Image (push) Waiting for needed jobs
Replace Proton-API-Bridge and go-proton-api with a client in backend/protondrive written against Proton's current Drive API, following the behaviour of Proton's official Drive SDK: - volume-based and v2 routes only - upload block verification, signed manifests and extended attributes - current content encryption (v4 node keys, v6 PKESK, SEIPDv2) - browser (session fork) sign-in, with username and password still supported - the volume's change events, used to keep the metadata cache current and for ChangeNotify, polled at most every 30 s - an in-memory fake Proton server (protontest) so the tests run without an account Uses ProtonMail/gopenpgp/v3 and ProtonMail/go-srp directly; no cgo. Written with heavy AI assistance (Claude Code). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
876 lines
30 KiB
Go
876 lines
30 KiB
Go
package protondrive
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/rclone/rclone/backend/protondrive/api"
|
|
"github.com/rclone/rclone/backend/protondrive/protontest"
|
|
"github.com/rclone/rclone/fs"
|
|
"github.com/rclone/rclone/fs/log"
|
|
"github.com/rclone/rclone/lib/random"
|
|
"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 TestPollEventsLogsPages(t *testing.T) {
|
|
logs := captureLogLines(t)
|
|
ctx := context.Background()
|
|
oldLevel := log.Handler.SetLevel(slog.LevelDebug)
|
|
ci := fs.GetConfig(ctx)
|
|
oldLogLevel := ci.LogLevel
|
|
ci.LogLevel = fs.LogLevelDebug
|
|
t.Cleanup(func() {
|
|
ci.LogLevel = oldLogLevel
|
|
log.Handler.SetLevel(oldLevel)
|
|
})
|
|
c, srv, u := newTestClient(t)
|
|
srv.SetEventsPageSize(2)
|
|
start, err := c.latestEventID(ctx)
|
|
require.NoError(t, err)
|
|
for _, name := range []string{"a", "b", "c"} {
|
|
u.SeedFolder(u.RootID(), name)
|
|
}
|
|
|
|
_, next, _, err := c.pollEvents(ctx, start)
|
|
require.NoError(t, err)
|
|
assert.Len(t, logs.matching("protondrive: events: 2 after "+start+" (more true)"), 1)
|
|
assert.Len(t, logs.matching("protondrive: events: 1 after ", " (more false)"), 1)
|
|
assert.Empty(t, logs.matching("after "+next))
|
|
}
|
|
|
|
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)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestPollEventsEndlessPages(t *testing.T) {
|
|
t.Parallel()
|
|
ctx := context.Background()
|
|
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++
|
|
body := fmt.Sprintf(`{"Code":1000,"Events":[{"EventID":"e%d","EventType":2,"Link":{"LinkID":"a"}}],"EventID":"p%d","More":true}`, pages, pages)
|
|
return &http.Response{
|
|
StatusCode: http.StatusOK,
|
|
Header: http.Header{"Content-Type": {"application/json"}},
|
|
Body: io.NopCloser(strings.NewReader(body)),
|
|
Request: r,
|
|
}, nil
|
|
})
|
|
})
|
|
changes, next, refresh, err := c.pollEvents(ctx, "start")
|
|
require.NoError(t, err)
|
|
assert.False(t, refresh)
|
|
assert.Equal(t, maxEventPages, pages)
|
|
assert.Len(t, changes, maxEventPages)
|
|
assert.Equal(t, fmt.Sprintf("p%d", maxEventPages), 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, newParentID: "root", gone: 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, gone: true},
|
|
goneNodes: []string{"file"},
|
|
goneListings: []string{"dir"},
|
|
}, {
|
|
name: "delete unknown",
|
|
change: eventChange{linkID: "gone", kind: api.EventDelete},
|
|
stale: staleNode{id: "gone", gone: true},
|
|
goneNodes: nil,
|
|
goneListings: nil,
|
|
}, {
|
|
name: "create",
|
|
change: eventChange{linkID: "new", parentID: "other", kind: api.EventCreate},
|
|
stale: staleNode{id: "new", newParentID: "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, newParentID: "dir"},
|
|
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, newParentID: "dir"},
|
|
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, newParentID: "other"},
|
|
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, newParentID: "other"},
|
|
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", newParentID: "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, newParentID: "root", gone: 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, newParentID: "dir", gone: 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", newParentID: "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"},
|
|
}, {
|
|
// The root can't move, so its descendants keep their paths.
|
|
name: "update root naming a parent",
|
|
change: eventChange{linkID: "root", parentID: "volume", kind: api.EventUpdate},
|
|
stale: staleNode{id: "root", isDir: true, known: true, newParentID: "volume"},
|
|
goneListings: []string{"root"},
|
|
}, {
|
|
name: "unknown kind",
|
|
change: eventChange{linkID: "file", parentID: "dir", kind: 42},
|
|
stale: staleNode{id: "file", parentID: "dir", name: "file", known: true, newParentID: "dir"},
|
|
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, newParentID: "dir"},
|
|
{id: "file", newParentID: "dir", gone: true},
|
|
{id: "top", parentID: "root", name: "top", known: true, newParentID: "root"},
|
|
}, 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", newParentID: "dir", gone: true}}, 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, newParentID: other}, 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")
|
|
}
|
|
|
|
// pollTimes records when a client requested pages of events.
|
|
type pollTimes struct {
|
|
mu sync.Mutex
|
|
times []time.Time
|
|
}
|
|
|
|
// get returns the times recorded so far.
|
|
func (p *pollTimes) get() []time.Time {
|
|
p.mu.Lock()
|
|
defer p.mu.Unlock()
|
|
return slices.Clone(p.times)
|
|
}
|
|
|
|
// gaps returns the time between each recorded poll and the next.
|
|
func (p *pollTimes) gaps() []time.Duration {
|
|
times := p.get()
|
|
var out []time.Duration
|
|
for i := 1; i < len(times); i++ {
|
|
out = append(out, times[i].Sub(times[i-1]))
|
|
}
|
|
return out
|
|
}
|
|
|
|
// Timing of the polling clients: short, so the tests are quick.
|
|
const (
|
|
testPollInterval = 200 * time.Millisecond
|
|
testPollJitter = 50 * time.Millisecond
|
|
)
|
|
|
|
// newPollingClient returns a client with caching enabled which polls
|
|
// events at least testPollInterval apart, with at most testPollJitter
|
|
// added, recording when it requests pages of events.
|
|
func newPollingClient(t *testing.T) (*client, *protontest.Server, *protontest.User, *pollTimes) {
|
|
t.Helper()
|
|
srv := protontest.New(t)
|
|
u := srv.AddUser("user", "pass")
|
|
polls := &pollTimes{}
|
|
c := newTestClientTransport(t, srv, u, clientOptions{EnableCaching: true, EventsInterval: testPollInterval}, func(next http.RoundTripper) http.RoundTripper {
|
|
return roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
|
if strings.HasPrefix(r.URL.Path, "/drive/v2/volumes/") && strings.Contains(r.URL.Path, "/events/") {
|
|
polls.mu.Lock()
|
|
polls.times = append(polls.times, time.Now())
|
|
polls.mu.Unlock()
|
|
}
|
|
return next.RoundTrip(r)
|
|
})
|
|
})
|
|
c.events.jitter = testPollJitter
|
|
return c, srv, u, polls
|
|
}
|
|
|
|
// eventRequests returns the requests srv had for the start cursor and
|
|
// for pages of events.
|
|
func eventRequests(srv *protontest.Server) (latest, pages int) {
|
|
got := srv.Requests()
|
|
return got["GET "+latestEventRoute], got["GET "+eventsRoute]
|
|
}
|
|
|
|
// logLines holds the lines rclone logs while they are captured.
|
|
type logLines struct {
|
|
mu sync.Mutex
|
|
lines []string
|
|
}
|
|
|
|
// matching returns the lines captured so far which contain each of subs.
|
|
func (l *logLines) matching(subs ...string) []string {
|
|
l.mu.Lock()
|
|
defer l.mu.Unlock()
|
|
var out []string
|
|
for _, line := range l.lines {
|
|
if !slices.ContainsFunc(subs, func(s string) bool { return !strings.Contains(line, s) }) {
|
|
out = append(out, line)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// captureLogLines captures rclone's log output at its usual level until
|
|
// the test ends. Tests using it must not be parallel.
|
|
func captureLogLines(t *testing.T) *logLines {
|
|
l := &logLines{}
|
|
log.Handler.SetOutput(func(level slog.Level, text string) {
|
|
l.mu.Lock()
|
|
defer l.mu.Unlock()
|
|
l.lines = append(l.lines, text)
|
|
})
|
|
t.Cleanup(log.Handler.ResetOutput)
|
|
return l
|
|
}
|
|
|
|
// addPending makes p wait to name the uncached node id, which a
|
|
// subscriber must be waiting for.
|
|
func addPending(p *eventPoller, id string) {
|
|
p.mu.Lock()
|
|
defer p.mu.Unlock()
|
|
p.addPendingLocked([]staleNode{{id: id, newParentID: "folder"}})
|
|
}
|
|
|
|
func TestPollerIdleMakesNoRequests(t *testing.T) {
|
|
t.Parallel()
|
|
c, srv, u, _ := newPollingClient(t)
|
|
u.SeedFolder(u.RootID(), "dir")
|
|
// Nothing is cached and nothing subscribed, so waking does nothing.
|
|
c.events.wake()
|
|
time.Sleep(3 * (testPollInterval + testPollJitter))
|
|
latest, pages := eventRequests(srv)
|
|
assert.Zero(t, latest+pages, "%v", srv.Requests())
|
|
}
|
|
|
|
func TestPollerPollsWhileCached(t *testing.T) {
|
|
t.Parallel()
|
|
c, srv, u, polls := newPollingClient(t)
|
|
listAll(t, c, u.RootID())
|
|
latest, pages := eventRequests(srv)
|
|
assert.Equal(t, 1, latest, "the start cursor is fetched when the cache fills")
|
|
assert.Zero(t, pages)
|
|
|
|
listAll(t, c, u.RootID())
|
|
time.Sleep(5*testPollInterval + testPollJitter)
|
|
c.events.stop()
|
|
latest, pages = eventRequests(srv)
|
|
assert.Equal(t, 1, latest)
|
|
assert.GreaterOrEqual(t, pages, 3, "about one poll per interval")
|
|
assert.LessOrEqual(t, pages, 5, "at most one poll per interval")
|
|
for _, gap := range polls.gaps() {
|
|
assert.GreaterOrEqual(t, gap, testPollInterval, "two polls within one interval")
|
|
}
|
|
}
|
|
|
|
func TestPollerSetInterval(t *testing.T) {
|
|
t.Parallel()
|
|
c, _, u, polls := newPollingClient(t)
|
|
c.events.setInterval(testPollInterval / 2)
|
|
listAll(t, c, u.RootID())
|
|
require.Eventually(t, func() bool { return len(polls.get()) >= 2 }, 5*time.Second, 5*time.Millisecond)
|
|
assert.GreaterOrEqual(t, polls.gaps()[0], testPollInterval, "shorter than the floor")
|
|
|
|
c.events.setInterval(3 * testPollInterval)
|
|
n := len(polls.get())
|
|
require.Eventually(t, func() bool { return len(polls.get()) >= n+2 }, 5*time.Second, 5*time.Millisecond)
|
|
c.events.stop()
|
|
// The poll scheduled before the change waits the old interval.
|
|
assert.GreaterOrEqual(t, polls.gaps()[n], 3*testPollInterval, "longer than the floor")
|
|
}
|
|
|
|
func TestPollerAppliesOtherClientsChange(t *testing.T) {
|
|
t.Parallel()
|
|
c, _, u, _ := newPollingClient(t)
|
|
dir := u.SeedFolder(u.RootID(), "dir")
|
|
listAll(t, c, dir)
|
|
u.SeedFile(dir, "new.txt", []byte("new"), time.Now())
|
|
assert.NotContains(t, listAll(t, c, dir), "new.txt", "the listing is cached")
|
|
|
|
assert.Eventually(t, func() bool {
|
|
_, ok := listAll(t, c, dir)["new.txt"]
|
|
return ok
|
|
}, testPollInterval+testPollJitter+500*time.Millisecond, 10*time.Millisecond, "the new file isn't listed after a poll")
|
|
}
|
|
|
|
func TestPollerRefresh(t *testing.T) {
|
|
t.Parallel()
|
|
c, srv, u, polls := newPollingClient(t)
|
|
var mu sync.Mutex
|
|
refreshes := 0
|
|
unsubscribe := c.events.subscribe(func(_ []staleNode, refresh bool) {
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
if refresh {
|
|
refreshes++
|
|
}
|
|
})
|
|
defer unsubscribe()
|
|
refreshed := func() int {
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
return refreshes
|
|
}
|
|
listAll(t, c, u.RootID())
|
|
|
|
// Just after a poll the next is an interval away, so the cursor is
|
|
// forgotten before it is used again.
|
|
require.Eventually(t, func() bool { return len(polls.get()) > 0 }, 2*time.Second, time.Millisecond)
|
|
u.SeedFolder(u.RootID(), "dir")
|
|
c.events.runMu.Lock()
|
|
addPending(c.events, "uncached")
|
|
srv.ExpireEvents(u)
|
|
c.events.runMu.Unlock()
|
|
require.Eventually(t, func() bool { return refreshed() > 0 }, 2*time.Second, time.Millisecond)
|
|
assert.True(t, c.cache.empty(), "the cache is cleared")
|
|
assert.Empty(t, c.events.pendingIDs(), "nodes are still pending")
|
|
|
|
n := len(polls.get())
|
|
time.Sleep(3 * (testPollInterval + testPollJitter))
|
|
assert.Greater(t, len(polls.get()), n, "polling continues")
|
|
assert.LessOrEqual(t, len(polls.get()), n+3, "polls in a loop")
|
|
assert.Equal(t, 1, refreshed())
|
|
|
|
// The new cursor is used.
|
|
assert.Contains(t, listAll(t, c, u.RootID()), "dir")
|
|
u.SeedFolder(u.RootID(), "after")
|
|
assert.Eventually(t, func() bool {
|
|
_, ok := listAll(t, c, u.RootID())["after"]
|
|
return ok
|
|
}, testPollInterval+testPollJitter+500*time.Millisecond, 10*time.Millisecond)
|
|
assert.Equal(t, 1, refreshed())
|
|
}
|
|
|
|
// TestPollerBackoff isn't parallel: it counts goroutines and pool
|
|
// buffers, which other tests share.
|
|
func TestPollerBackoff(t *testing.T) {
|
|
c, srv, u, polls := newPollingClient(t)
|
|
goroutines, buffers := leakBaseline(srv)
|
|
srv.Inject(protontest.Fault{Pattern: eventsRoute, Status: http.StatusServiceUnavailable, Times: 4})
|
|
listAll(t, c, u.RootID())
|
|
|
|
// Four polls fail, the fifth and sixth succeed.
|
|
require.Eventually(t, func() bool { return len(polls.get()) >= 6 }, 10*time.Second, 5*time.Millisecond)
|
|
c.events.stop()
|
|
gaps := polls.gaps()
|
|
for i, times := range []int{1, 1, 2, 3, 1} {
|
|
want := time.Duration(times) * testPollInterval
|
|
assert.GreaterOrEqual(t, gaps[i], want, "gap %d: %v", i, gaps)
|
|
assert.Less(t, gaps[i], want+testPollJitter+2*testPollInterval, "gap %d: %v", i, gaps)
|
|
}
|
|
requireNoLeaks(t, srv, goroutines, buffers)
|
|
}
|
|
|
|
func TestPollerVolumeGone(t *testing.T) {
|
|
logs := captureLogLines(t)
|
|
c, srv, u, _ := newPollingClient(t)
|
|
var refreshes atomic.Int32
|
|
unsubscribe := c.events.subscribe(func(_ []staleNode, refresh bool) {
|
|
if refresh {
|
|
refreshes.Add(1)
|
|
}
|
|
})
|
|
defer unsubscribe()
|
|
srv.Inject(protontest.Fault{Pattern: eventsRoute, Status: http.StatusUnprocessableEntity, Code: api.CodeNotExists})
|
|
addPending(c.events, "uncached")
|
|
listAll(t, c, u.RootID())
|
|
require.Eventually(t, c.cache.empty, 2*time.Second, time.Millisecond, "the cache is cleared")
|
|
assert.Empty(t, c.events.pendingIDs(), "nodes are still pending")
|
|
|
|
time.Sleep(2 * (testPollInterval + testPollJitter))
|
|
listAll(t, c, u.RootID())
|
|
c.events.wake()
|
|
time.Sleep(2 * (testPollInterval + testPollJitter))
|
|
latest, pages := eventRequests(srv)
|
|
assert.Equal(t, 1, latest)
|
|
assert.Equal(t, 1, pages, "polling stopped")
|
|
assert.Len(t, logs.matching("ERROR", "protondrive: events"), 1)
|
|
assert.Equal(t, int32(1), refreshes.Load())
|
|
}
|
|
|
|
func TestPollerFirstLatestFails(t *testing.T) {
|
|
t.Parallel()
|
|
c, srv, u, _ := newPollingClient(t)
|
|
srv.Inject(protontest.Fault{Pattern: latestEventRoute, Status: http.StatusServiceUnavailable, Times: 1})
|
|
dir := u.SeedFolder(u.RootID(), "dir")
|
|
assert.Contains(t, listAll(t, c, u.RootID()), "dir", "the listing fails with the start cursor")
|
|
|
|
// The cursor is fetched again and polling goes on.
|
|
require.Eventually(t, func() bool {
|
|
_, pages := eventRequests(srv)
|
|
return pages >= 1
|
|
}, 5*time.Second, 5*time.Millisecond, "polling doesn't start")
|
|
listAll(t, c, dir)
|
|
u.SeedFile(dir, "new.txt", []byte("new"), time.Now())
|
|
assert.Eventually(t, func() bool {
|
|
_, ok := listAll(t, c, dir)["new.txt"]
|
|
return ok
|
|
}, 5*time.Second, 10*time.Millisecond)
|
|
}
|
|
|
|
// TestPollerFirstLatestRateLimited checks a Retry-After on the start
|
|
// cursor fetched when the cache fills doesn't hold up the caller, and
|
|
// delays the next try instead.
|
|
func TestPollerFirstLatestRateLimited(t *testing.T) {
|
|
t.Parallel()
|
|
c, srv, u, _ := newPollingClient(t)
|
|
srv.Inject(protontest.Fault{Pattern: latestEventRoute, Status: http.StatusTooManyRequests, RetryAfter: 2, Times: 1})
|
|
start := time.Now()
|
|
listAll(t, c, u.RootID())
|
|
assert.Less(t, time.Since(start), time.Second, "the listing waited for the Retry-After")
|
|
|
|
require.Eventually(t, func() bool {
|
|
latest, _ := eventRequests(srv)
|
|
return latest >= 2
|
|
}, 10*time.Second, 5*time.Millisecond, "the start cursor isn't fetched again")
|
|
assert.GreaterOrEqual(t, time.Since(start), 2*time.Second, "tried again before the Retry-After")
|
|
}
|
|
|
|
// TestPollerStopKeepsCursor checks polling resumed after stop goes on
|
|
// from the cursor, rather than fetching a new one at once, so no two
|
|
// requests come within an interval.
|
|
func TestPollerStopKeepsCursor(t *testing.T) {
|
|
t.Parallel()
|
|
c, srv, u, polls := newPollingClient(t)
|
|
listAll(t, c, u.RootID())
|
|
require.Eventually(t, func() bool { return len(polls.get()) >= 1 }, 5*time.Second, time.Millisecond)
|
|
c.events.stop()
|
|
c.cache.clear()
|
|
|
|
listAll(t, c, u.RootID())
|
|
require.Eventually(t, func() bool { return len(polls.get()) >= 3 }, 5*time.Second, time.Millisecond)
|
|
c.events.stop()
|
|
latest, _ := eventRequests(srv)
|
|
assert.Equal(t, 1, latest, "the start cursor is fetched again")
|
|
for _, gap := range polls.gaps() {
|
|
assert.GreaterOrEqual(t, gap, testPollInterval, "two polls within one interval")
|
|
}
|
|
}
|
|
|
|
// TestPollerStopWaitsForPoll checks stop returns only once a poll in
|
|
// flight has finished, so nothing of it, its logging included, runs
|
|
// after Shutdown.
|
|
func TestPollerStopWaitsForPoll(t *testing.T) {
|
|
t.Parallel()
|
|
srv := protontest.New(t)
|
|
u := srv.AddUser("user", "pass")
|
|
held, release := make(chan struct{}, 1), make(chan struct{})
|
|
c := newTestClientTransport(t, srv, u, clientOptions{EnableCaching: true, EventsInterval: testPollInterval}, func(next http.RoundTripper) http.RoundTripper {
|
|
return roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
|
resp, err := next.RoundTrip(r)
|
|
if strings.HasPrefix(r.URL.Path, "/drive/v2/volumes/") && strings.Contains(r.URL.Path, "/events/") {
|
|
// The response is in, as if the poll were cancelled
|
|
// just after it arrived.
|
|
select {
|
|
case held <- struct{}{}:
|
|
default:
|
|
}
|
|
<-release
|
|
}
|
|
return resp, err
|
|
})
|
|
})
|
|
c.events.jitter = testPollJitter
|
|
listAll(t, c, u.RootID())
|
|
select {
|
|
case <-held:
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("no poll")
|
|
}
|
|
stopped := make(chan struct{})
|
|
go func() {
|
|
c.events.stop()
|
|
close(stopped)
|
|
}()
|
|
select {
|
|
case <-stopped:
|
|
t.Error("stop returned while a poll was in flight")
|
|
case <-time.After(200 * time.Millisecond):
|
|
}
|
|
close(release)
|
|
select {
|
|
case <-stopped:
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("stop didn't return after the poll finished")
|
|
}
|
|
}
|
|
|
|
// TestPollerIdleCacheCleared checks a cache unused for the idle time is
|
|
// cleared, which stops polling, unless something subscribes.
|
|
func TestPollerIdleCacheCleared(t *testing.T) {
|
|
t.Parallel()
|
|
const idle = 3 * testPollInterval
|
|
c, srv, u, polls := newPollingClient(t)
|
|
c.events.idle = idle
|
|
u.SeedFolder(u.RootID(), "dir")
|
|
listAll(t, c, u.RootID())
|
|
|
|
// Used, the cache is kept. Other clients' changes aren't use.
|
|
for range 6 {
|
|
time.Sleep(testPollInterval)
|
|
u.SeedFolder(u.RootID(), random.String(8))
|
|
c.cache.get(u.RootID())
|
|
}
|
|
assert.False(t, c.cache.empty(), "cleared while in use")
|
|
|
|
require.Eventually(t, c.cache.empty, 2*idle+2*testPollInterval, 5*time.Millisecond, "not cleared")
|
|
n := len(polls.get())
|
|
time.Sleep(3 * (testPollInterval + testPollJitter))
|
|
assert.Equal(t, n, len(polls.get()), "polled after the cache was cleared")
|
|
|
|
// The next use refills the cache and polls again, from the cursor.
|
|
assert.NotEmpty(t, listAll(t, c, u.RootID()))
|
|
require.Eventually(t, func() bool { return len(polls.get()) > n }, 5*time.Second, 5*time.Millisecond, "polling didn't resume")
|
|
latest, _ := eventRequests(srv)
|
|
assert.Equal(t, 1, latest, "the start cursor is fetched again")
|
|
|
|
// With a subscriber the cache is kept.
|
|
unsubscribe := c.events.subscribe(func([]staleNode, bool) {})
|
|
defer unsubscribe()
|
|
time.Sleep(2*idle + 2*testPollInterval)
|
|
assert.False(t, c.cache.empty(), "cleared with a subscriber")
|
|
}
|
|
|
|
// TestPollerNotifiesOutsideCallerLocks checks a subscriber isn't called
|
|
// on the goroutine which filled the cache, which may hold a lock the
|
|
// subscriber takes, as a dircache lookup holds the dircache's.
|
|
func TestPollerNotifiesOutsideCallerLocks(t *testing.T) {
|
|
t.Parallel()
|
|
c, srv, u, _ := newPollingClient(t)
|
|
var callerLock sync.Mutex
|
|
notified := make(chan bool, 1)
|
|
unsubscribe := c.events.subscribe(func(_ []staleNode, refresh bool) {
|
|
callerLock.Lock()
|
|
defer callerLock.Unlock()
|
|
notified <- refresh
|
|
})
|
|
defer unsubscribe()
|
|
srv.Inject(protontest.Fault{Pattern: latestEventRoute, Status: http.StatusUnprocessableEntity, Code: api.CodeNotExists})
|
|
|
|
done := make(chan struct{})
|
|
callerLock.Lock()
|
|
go func() {
|
|
defer close(done)
|
|
defer callerLock.Unlock()
|
|
listAll(t, c, u.RootID())
|
|
}()
|
|
select {
|
|
case <-done:
|
|
case <-time.After(10 * time.Second):
|
|
t.Fatal("deadlock: the subscriber was called inside the cache fill")
|
|
}
|
|
select {
|
|
case refresh := <-notified:
|
|
assert.True(t, refresh)
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("the subscriber wasn't notified")
|
|
}
|
|
}
|