package protondrive import ( "bytes" "cmp" "context" "encoding/base64" "errors" "fmt" "io" "maps" "slices" "strings" "sync" "testing" "time" "github.com/pquerna/otp/totp" "github.com/rclone/rclone/backend/protondrive/api" "github.com/rclone/rclone/backend/protondrive/protontest" "github.com/rclone/rclone/fs" "github.com/rclone/rclone/fs/config/configmap" "github.com/rclone/rclone/fs/config/obscure" "github.com/rclone/rclone/fs/fserrors" "github.com/rclone/rclone/fs/object" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestTranslateError(t *testing.T) { apiErr := func(code int) error { return fmt.Errorf("call: %w", &api.Error{Status: 422, Code: code, Message: "proton says no"}) } notFound := fmt.Errorf("get node: %w", errNotFound) exists := fmt.Errorf("create: %w", errExists) other := errors.New("other") for _, test := range []struct { name string err error op errorOp want error // compared with ==, if set check func(t *testing.T, got error) }{ {name: "nil", err: nil, op: opObject, want: nil}, {name: "not found object", err: notFound, op: opObject, want: fs.ErrorObjectNotFound}, {name: "not found dir", err: notFound, op: opDir, want: fs.ErrorDirNotFound}, {name: "code 2501 object", err: apiErr(api.CodeNotExists), op: opObject, want: fs.ErrorObjectNotFound}, {name: "code 2501 dir", err: apiErr(api.CodeNotExists), op: opDir, want: fs.ErrorDirNotFound}, {name: "exists mkdir", err: exists, op: opMkdir, want: nil}, {name: "exists move", err: exists, op: opMove, want: fs.ErrorCantMove}, {name: "exists copy", err: exists, op: opCopy, want: fs.ErrorCantCopy}, {name: "exists dirmove", err: exists, op: opDirMove, want: fs.ErrorDirExists}, {name: "exists object", err: exists, op: opObject, check: func(t *testing.T, got error) { assert.ErrorIs(t, got, errExists) }}, {name: "other unchanged", err: other, op: opObject, want: other}, } { t.Run(test.name, func(t *testing.T) { got := translateError(test.err, test.op) if test.check != nil { test.check(t, got) return } assert.Equal(t, test.want, got) }) } for _, code := range []int{ api.CodeInsufficientQuota, api.CodeInsufficientSpace, api.CodeMaxFileSizeForFreeUser, api.CodeMaxPublicEditModeForFreeUser, api.CodeTooManyChildren, api.CodeNestingTooDeep, } { t.Run(fmt.Sprintf("code %d no retry", code), func(t *testing.T) { got := translateError(apiErr(code), opObject) assert.True(t, fserrors.IsNoRetryError(got)) assert.False(t, fserrors.IsFatalError(got)) assert.Contains(t, got.Error(), "proton says no") }) } for _, code := range []int{api.CodeAppVersionMissing, api.CodeAppVersionBad} { t.Run(fmt.Sprintf("code %d fatal", code), func(t *testing.T) { got := translateError(apiErr(code), opObject) assert.True(t, fserrors.IsFatalError(got)) assert.Contains(t, got.Error(), "upgrade rclone") assert.Contains(t, got.Error(), "proton says no") }) } t.Run("code 2000 no retry", func(t *testing.T) { got := translateError(apiErr(api.CodeInvalidRequirements), opMove) assert.True(t, fserrors.IsNoRetryError(got)) assert.False(t, fserrors.IsFatalError(got)) assert.NotContains(t, got.Error(), "upgrade rclone") assert.Contains(t, got.Error(), "proton says no") }) t.Run("code 2028 not fatal", func(t *testing.T) { got := translateError(apiErr(api.CodeFeatureBlocked), opObject) assert.False(t, fserrors.IsFatalError(got)) assert.False(t, fserrors.IsNoRetryError(got)) assert.NotContains(t, got.Error(), "upgrade rclone") assert.Contains(t, got.Error(), "proton says no") }) for _, err := range []error{errIntegrity, errUploadSuperseded} { t.Run(err.Error()+" no retry", func(t *testing.T) { got := translateError(fmt.Errorf("op: %w", err), opObject) assert.True(t, fserrors.IsNoRetryError(got)) assert.ErrorIs(t, got, err) }) } for _, err := range []error{errUploadOutcomeUnknown, errUploadUnconfirmed, errUploadMismatch} { t.Run(err.Error()+" no low level retry", func(t *testing.T) { got := translateError(fmt.Errorf("op: %w", err), opObject) assert.True(t, fserrors.IsNoLowLevelRetryError(got)) assert.False(t, fserrors.IsNoRetryError(got)) assert.ErrorIs(t, got, err) }) } } // sessionConfig returns the config keys of a v1.76 remote holding a new // saved session of u, pointed at srv. func sessionConfig(srv *protontest.Server, u *protontest.User) configmap.Simple { sess := srv.NewSession(u) return configmap.Simple{ "type": "protondrive", "username": "", "password": "", "mailbox_password": "", "2fa": "", "otp_secret_key": "", "client_uid": sess.UID, "client_access_token": sess.AccessToken, "client_refresh_token": sess.RefreshToken, "client_salted_key_pass": base64.StdEncoding.EncodeToString([]byte(u.KeyPassword())), "encoding": "Slash,LeftSpace,RightSpace,InvalidUtf8,Dot", "original_file_size": "true", "app_version": "", "replace_existing_draft": "false", "enable_caching": "true", // Not a v1.76 key, but the only way to reach the fake. "endpoint": srv.URL(), } } // newTestFs returns an Fs for the config m, shut down when the test ends. func newTestFs(t *testing.T, m configmap.Mapper) *Fs { t.Helper() f, err := NewFs(context.Background(), "test", "", m) require.NoError(t, err) t.Cleanup(func() { _ = f.(*Fs).Shutdown(context.Background()) }) return f.(*Fs) } // authRequests returns the auth requests made to srv. func authRequests(srv *protontest.Server) []string { var out []string for route := range srv.Requests() { if strings.Contains(route, "/auth") { out = append(out, route) } } return out } func TestOptionsBackwardsCompatible(t *testing.T) { srv := protontest.New(t) u := srv.AddUser("user", "pass") m := sessionConfig(srv, u) want := m["client_access_token"] f := newTestFs(t, m) _, err := f.List(context.Background(), "") require.NoError(t, err) assert.Empty(t, authRequests(srv), "a saved session must be used without signing in") assert.Equal(t, want, m["client_access_token"]) assert.Len(t, m["draft_client_uid"], 32, "draft_client_uid is generated and saved") assert.True(t, f.opt.ReportOriginalSize) assert.True(t, f.opt.EnableCaching) } // unsavedMap is a config which saves nothing, as one from environment // variables or a connection string. type unsavedMap struct{ configmap.Simple } // Set does nothing. func (unsavedMap) Set(key, value string) {} func TestDraftClientUIDStableWhenUnsaved(t *testing.T) { ctx := context.Background() srv := protontest.New(t) u := srv.AddUser("user", "pass") uid := func(name string) string { m := sessionConfig(srv, u) f, err := NewFs(ctx, name, "", unsavedMap{m}) require.NoError(t, err) t.Cleanup(func() { _ = f.(*Fs).Shutdown(ctx) }) got := f.(*Fs).c.opt.DraftClientUID assert.Len(t, got, 32) return got } first := uid("env") assert.Equal(t, first, uid("env"), "a later run of the same remote has another draft client ID") assert.NotEqual(t, first, uid("other"), "another remote of the account has the same draft client ID") } func TestNewFsPasswordFallback(t *testing.T) { srv := protontest.New(t) u := srv.AddUser("user", "pass") m := sessionConfig(srv, u) m["username"] = "user" m["password"] = obscure.MustObscure("pass") oldUID := m["client_uid"] srv.RevokeSession(oldUID) f := newTestFs(t, m) _, err := f.List(context.Background(), "") require.NoError(t, err) assert.NotEqual(t, oldUID, m["client_uid"]) assert.NotEmpty(t, m["client_access_token"]) assert.NotEmpty(t, m["client_refresh_token"]) keyPass, err := base64.StdEncoding.DecodeString(m["client_salted_key_pass"]) require.NoError(t, err) assert.Equal(t, u.KeyPassword(), string(keyPass)) assert.Equal(t, 1, srv.Requests()["POST /core/v4/auth"]) } func TestNewFsPasswordFallbackTOTP(t *testing.T) { srv := protontest.New(t) u := srv.AddUser("user", "pass") secret := u.EnableTOTP() m := sessionConfig(srv, u) for _, k := range []string{"client_uid", "client_access_token", "client_refresh_token", "client_salted_key_pass"} { m[k] = "" } m["username"] = "user" m["password"] = obscure.MustObscure("pass") m["otp_secret_key"] = obscure.MustObscure(secret) newTestFs(t, m) assert.NotEmpty(t, m["client_uid"]) assert.Equal(t, 1, srv.Requests()["POST /core/v4/auth/2fa"]) } func TestNewFsNoCredentials(t *testing.T) { srv := protontest.New(t) u := srv.AddUser("user", "pass") t.Run("none saved", func(t *testing.T) { m := configmap.Simple{"endpoint": srv.URL()} _, err := NewFs(context.Background(), "myremote", "", m) require.Error(t, err) assert.Contains(t, err.Error(), `rclone config reconnect myremote:`) }) t.Run("revoked", func(t *testing.T) { m := sessionConfig(srv, u) srv.RevokeSession(m["client_uid"]) _, err := NewFs(context.Background(), "myremote", "", m) require.Error(t, err) assert.Contains(t, err.Error(), `rclone config reconnect myremote:`) }) t.Run("undecodable key password", func(t *testing.T) { m := sessionConfig(srv, u) m["client_salted_key_pass"] = "not base64!" _, err := NewFs(context.Background(), "myremote", "", m) require.Error(t, err) assert.Contains(t, err.Error(), `rclone config reconnect myremote:`) }) t.Run("wrong key password", func(t *testing.T) { m := sessionConfig(srv, u) m["client_salted_key_pass"] = base64.StdEncoding.EncodeToString([]byte("wrong")) _, err := NewFs(context.Background(), "myremote", "", m) require.Error(t, err) assert.Contains(t, err.Error(), "is the password right?") assert.Contains(t, err.Error(), `rclone config reconnect myremote:`) assert.True(t, fserrors.IsFatalError(err)) }) } func TestTwoRemotesIsolated(t *testing.T) { ctx := context.Background() srv := protontest.New(t) u1 := srv.AddUser("user1", "pass1") u2 := srv.AddUser("user2", "pass2") m1, m2 := sessionConfig(srv, u1), sessionConfig(srv, u2) uid1, uid2 := m1["client_uid"], m2["client_uid"] f1, f2 := newTestFs(t, m1), newTestFs(t, m2) require.NoError(t, f1.Mkdir(ctx, "one")) require.NoError(t, f2.Mkdir(ctx, "two")) // Make both sessions refresh, saving new tokens. access1, access2 := m1["client_access_token"], m2["client_access_token"] srv.ResetRequests() srv.ExpireAccessToken(uid1) srv.ExpireAccessToken(uid2) f1.DirCacheFlush() f2.DirCacheFlush() entries1, err := f1.List(ctx, "") require.NoError(t, err) entries2, err := f2.List(ctx, "") require.NoError(t, err) require.Len(t, entries1, 1) assert.Equal(t, "one", entries1[0].Remote()) require.Len(t, entries2, 1) assert.Equal(t, "two", entries2[0].Remote()) assert.Equal(t, 2, srv.Requests()["POST /auth/v4/refresh"]) assert.NotEqual(t, access1, m1["client_access_token"], "remote 1 saved its refreshed token") assert.NotEqual(t, access2, m2["client_access_token"], "remote 2 saved its refreshed token") assert.Equal(t, uid1, m1["client_uid"]) assert.Equal(t, uid2, m2["client_uid"]) for _, k := range []string{"client_uid", "client_access_token", "client_refresh_token", "client_salted_key_pass", "draft_client_uid"} { assert.NotEqual(t, m1[k], m2[k], k) } } // configAnswers drives configure through its states, answering each // question by its state from answers, and returns the questions asked. func configAnswers(t *testing.T, m configmap.Mapper, signIn signInOptions, answers map[string]string) []*fs.ConfigOut { t.Helper() var asked []*fs.ConfigOut in := fs.ConfigIn{} for range 10 { out, err := configure(context.Background(), "test", m, in, signIn) require.NoError(t, err) if out == nil { return asked } require.Empty(t, out.Error) in = fs.ConfigIn{State: out.State} if out.Option != nil { asked = append(asked, out) answer, ok := answers[out.State] require.True(t, ok, "unexpected question in state %q: %s", out.State, out.Option.Help) in.Result = answer } } t.Fatal("config didn't finish") return nil } // requireSession checks m holds a working session of u on srv. func requireSession(t *testing.T, srv *protontest.Server, m configmap.Simple, u *protontest.User) { t.Helper() keyPass, err := base64.StdEncoding.DecodeString(m["client_salted_key_pass"]) require.NoError(t, err) assert.Equal(t, u.KeyPassword(), string(keyPass)) srv.ResetRequests() newTestFs(t, m) assert.Empty(t, authRequests(srv)) } func TestConfigBrowser(t *testing.T) { srv := protontest.New(t) u := srv.AddUser("user", "pass") m := configmap.Simple{"endpoint": srv.URL()} var shown string signIn := signInOptions{ pollInterval: 10 * time.Millisecond, pollTimeout: 10 * time.Second, showURL: func(signInURL string) { shown = signInURL require.NoError(t, srv.ApproveFork(signInURL, u)) }, } asked := configAnswers(t, m, signIn, map[string]string{"choose": "true"}) require.Len(t, asked, 1) assert.Contains(t, asked[0].Option.Help, "rclone is a third-party application not officially supported by Proton.") assert.Equal(t, true, asked[0].Option.Default) assert.True(t, strings.HasPrefix(shown, forkSignInURL), shown) requireSession(t, srv, m, u) } func TestConfigPassword(t *testing.T) { srv := protontest.New(t) t.Run("no 2fa", func(t *testing.T) { u := srv.AddUser("user", "pass") m := configmap.Simple{"endpoint": srv.URL(), "username": "user", "password": obscure.MustObscure("pass")} asked := configAnswers(t, m, signInOptions{}, map[string]string{"choose": "false"}) require.Len(t, asked, 1) assert.Equal(t, false, asked[0].Option.Default, "password sign-in is the default when a password is set") requireSession(t, srv, m, u) }) t.Run("2fa asked", func(t *testing.T) { u := srv.AddUser("user2fa", "pass") secret := u.EnableTOTP() m := configmap.Simple{"endpoint": srv.URL(), "username": "user2fa", "password": obscure.MustObscure("pass")} code, err := totp.GenerateCode(secret, time.Now()) require.NoError(t, err) asked := configAnswers(t, m, signInOptions{}, map[string]string{"choose": "false", "password_2fa": code}) require.Len(t, asked, 2) requireSession(t, srv, m, u) assert.Empty(t, m["2fa"], "the 2FA code is not saved") }) t.Run("captcha", func(t *testing.T) { u := srv.AddUser("usercaptcha", "pass") srv.RequireCaptcha(u) m := configmap.Simple{"endpoint": srv.URL(), "username": "usercaptcha", "password": obscure.MustObscure("pass")} out, err := configure(context.Background(), "test", m, fs.ConfigIn{State: "password"}, signInOptions{}) require.NoError(t, err) require.NotNil(t, out) assert.Contains(t, out.Error, "web browser") assert.Equal(t, "method", out.State, "goes back to the choice of sign-in") assert.Empty(t, m["client_uid"]) }) t.Run("no password", func(t *testing.T) { m := configmap.Simple{"endpoint": srv.URL()} out, err := configure(context.Background(), "test", m, fs.ConfigIn{State: "password"}, signInOptions{}) require.NoError(t, err) require.NotNil(t, out) assert.NotEmpty(t, out.Error) }) } func TestConfigStore(t *testing.T) { creds := credentials{UID: "uid", AccessToken: "access", RefreshToken: "refresh", KeyPassword: "key\x00pass"} t.Run("round trip", func(t *testing.T) { m := configmap.Simple{} s := &configStore{m: m} s.Save(creds) assert.Equal(t, base64.StdEncoding.EncodeToString([]byte(creds.KeyPassword)), m[clientSaltedKeyPassKey]) assert.Equal(t, creds, s.Load()) // Another user of the config saves newer tokens. m[clientRefreshTokenKey] = "newer" assert.Equal(t, "newer", s.Load().RefreshToken) }) t.Run("overridden", func(t *testing.T) { // Values from the environment or the command line take // precedence over the config file the store saves to. env := configmap.Simple{clientUIDKey: "old uid", clientAccessTokenKey: "old access", clientRefreshTokenKey: "old refresh"} file := configmap.Simple{} m := configmap.New().AddGetter(env, configmap.PriorityNormal).AddGetter(file, configmap.PriorityConfig).AddSetter(file) s := &configStore{m: m} assert.Equal(t, "old refresh", s.Load().RefreshToken) s.Save(creds) assert.Equal(t, creds, s.Load(), "saved credentials must not be shadowed by spent ones") }) } // putFile uploads content to f at remote and returns the object. func putFile(t *testing.T, f fs.Fs, remote string, content []byte) fs.Object { t.Helper() src := object.NewStaticObjectInfo(remote, time.Now(), int64(len(content)), true, nil, nil) o, err := f.Put(context.Background(), bytes.NewReader(content), src) require.NoError(t, err) return o } // readObject returns the content of o read with options. func readObject(t *testing.T, o fs.Object, options ...fs.OpenOption) ([]byte, error) { t.Helper() rc, err := o.Open(context.Background(), options...) if err != nil { return nil, err } defer func() { require.NoError(t, rc.Close()) }() return io.ReadAll(rc) } func TestRmdirRefusesHiddenChildren(t *testing.T) { ctx := context.Background() srv := protontest.New(t) u := srv.AddUser("user", "pass") f := newTestFs(t, sessionConfig(srv, u)) require.NoError(t, f.Mkdir(ctx, "docs")) docsID, err := f.dirCache.FindDir(ctx, "docs", false) require.NoError(t, err) u.SeedDoc(docsID, "notes") assert.Equal(t, fs.ErrorDirectoryNotEmpty, f.Rmdir(ctx, "docs")) // Filled by another client after an empty listing was cached. require.NoError(t, f.Mkdir(ctx, "later")) entries, err := f.List(ctx, "later") require.NoError(t, err) require.Empty(t, entries) laterID, err := f.dirCache.FindDir(ctx, "later", false) require.NoError(t, err) u.SeedFile(laterID, "new.txt", []byte("x"), time.Now()) assert.Equal(t, fs.ErrorDirectoryNotEmpty, f.Rmdir(ctx, "later")) require.NoError(t, f.Mkdir(ctx, "empty")) require.NoError(t, f.Rmdir(ctx, "empty")) paths := map[string]bool{} for _, d := range u.Dump() { paths[d.Path] = d.State == api.LinkStateActive } assert.True(t, paths["docs/notes"]) assert.True(t, paths["later/new.txt"]) } func TestConfigKeepsSession(t *testing.T) { srv := protontest.New(t) u := srv.AddUser("user", "pass") ri, err := fs.Find("protondrive") require.NoError(t, err) t.Run("default", func(t *testing.T) { m := sessionConfig(srv, u) want := maps.Clone(m) srv.ResetRequests() asked := configAnswers(t, m, signInOptions{}, map[string]string{"reauth": "false"}) require.Len(t, asked, 1) assert.Equal(t, false, asked[0].Option.Default) assert.Equal(t, "config_refresh_token", asked[0].Option.Name) assert.Empty(t, srv.Requests()) assert.Equal(t, want, m) }) t.Run("config update", func(t *testing.T) { // As "rclone config update remote enable_caching=false" runs it. m := sessionConfig(srv, u) srv.ResetRequests() out, err := fs.BackendConfig(context.Background(), "test", m, ri, configmap.Simple{"config_refresh_token": "false"}, fs.ConfigIn{}) require.NoError(t, err) assert.Nil(t, out) assert.Empty(t, srv.Requests()) }) } func TestConfigSignInAgain(t *testing.T) { srv := protontest.New(t) u := srv.AddUser("user", "pass") m := sessionConfig(srv, u) m["username"] = "user" m["password"] = obscure.MustObscure("pass") old := maps.Clone(m) configAnswers(t, m, signInOptions{}, map[string]string{"reauth": "true", "choose": "false"}) assert.NotEqual(t, old["client_uid"], m["client_uid"]) assert.Equal(t, 1, srv.Requests()["DELETE /core/v4/auth"], "the old session is signed out") requireSession(t, srv, m, u) // The old session no longer works. old["username"], old["password"] = "", "" _, err := NewFs(context.Background(), "test", "", old) require.Error(t, err) } func TestShutdownKeepsFsUsable(t *testing.T) { ctx := context.Background() srv := protontest.New(t) u := srv.AddUser("user", "pass") f := newTestFs(t, sessionConfig(srv, u)) o := putFile(t, f, "dir/a.txt", []byte("hello")) require.NoError(t, f.Shutdown(ctx)) require.NoError(t, f.Shutdown(ctx)) got, err := readObject(t, o) require.NoError(t, err) assert.Equal(t, "hello", string(got)) putFile(t, f, "dir/b.txt", []byte("world")) entries, err := f.List(ctx, "dir") require.NoError(t, err) assert.Len(t, entries, 2) o, err = f.NewObject(ctx, "dir/b.txt") require.NoError(t, err) got, err = readObject(t, o) require.NoError(t, err) assert.Equal(t, "world", string(got)) } func TestPollerShutdownAndReuse(t *testing.T) { ctx := context.Background() srv := protontest.New(t) u := srv.AddUser("user", "pass") m := sessionConfig(srv, u) m["events_min_interval"] = testPollInterval.String() f := newTestFs(t, m) f.c.events.jitter = testPollJitter putFile(t, f, "dir/a.txt", []byte("hello")) // Shut down while a poll is in flight. hold, held := make(chan struct{}), make(chan struct{}, 1) srv.Inject(protontest.Fault{Pattern: eventsRoute, Times: 1, Hold: hold, Held: held}) select { case <-held: case <-time.After(5 * time.Second): t.Fatal("no poll") } require.NoError(t, f.Shutdown(ctx)) close(hold) require.NoError(t, f.Shutdown(ctx)) srv.ResetRequests() time.Sleep(2 * (testPollInterval + testPollJitter)) latest, pages := eventRequests(srv) assert.Zero(t, latest+pages, "polled after Shutdown") // Used again, it polls again from the cursor, once per interval. // The first poll applies the changes made before Shutdown, which // may empty the cache and so stop polling until the next use. reused := time.Now() entries, err := f.List(ctx, "dir") require.NoError(t, err) assert.Len(t, entries, 1) require.Eventually(t, func() bool { _, pages := eventRequests(srv) return pages >= 1 }, 5*time.Second, time.Millisecond, "polling didn't resume") assert.GreaterOrEqual(t, time.Since(reused), testPollInterval, "polled within an interval of reuse") // Kept in use, it keeps polling. require.Eventually(t, func() bool { _, err := f.List(ctx, "dir") require.NoError(t, err) _, pages := eventRequests(srv) return pages >= 4 }, 10*time.Second, 20*time.Millisecond, "polling stopped") latest, pages = eventRequests(srv) assert.Zero(t, latest, "the start cursor is fetched again") assert.LessOrEqual(t, pages, int(time.Since(reused)/testPollInterval), "more than one poll per interval") } func TestEventsMinIntervalClamp(t *testing.T) { logs := captureLogLines(t) for _, test := range []struct { endpoint string set time.Duration want time.Duration }{ {defaultEndpoint, time.Second, minEventsInterval}, {defaultEndpoint + "/", 0, minEventsInterval}, {"https://DRIVE-API.proton.me:443", time.Second, minEventsInterval}, {"https://drive-api.proton.me./", time.Second, minEventsInterval}, {"https://Proton.Me.:443", time.Second, minEventsInterval}, {"https://drive-api.proton.me.example.com", time.Second, time.Second}, {defaultEndpoint, minEventsInterval, minEventsInterval}, {defaultEndpoint, time.Hour, time.Hour}, {"http://127.0.0.1:1234", time.Second, time.Second}, } { before := len(logs.matching("NOTICE", "events_min_interval")) opt := &Options{Endpoint: test.endpoint, EventsMinInterval: fs.Duration(test.set)} clampEventsMinInterval(opt) assert.Equal(t, test.want, time.Duration(opt.EventsMinInterval), "%s %v", test.endpoint, test.set) notices := len(logs.matching("NOTICE", "events_min_interval")) - before if test.set < test.want { assert.Equal(t, 1, notices, "%s %v", test.endpoint, test.set) } else { assert.Zero(t, notices, "%s %v", test.endpoint, test.set) } } opt, err := fs.Find("protondrive") require.NoError(t, err) assert.Equal(t, fs.Duration(minEventsInterval), opt.Options.Get("events_min_interval").Default) srv := protontest.New(t) u := srv.AddUser("user", "pass") m := sessionConfig(srv, u) m["events_min_interval"] = "1s" f := newTestFs(t, m) assert.Equal(t, time.Second, f.c.events.floor, "the fake's endpoint isn't Proton's") } func TestDisconnect(t *testing.T) { ctx := context.Background() srv := protontest.New(t) u := srv.AddUser("user", "pass") m := sessionConfig(srv, u) f := newTestFs(t, m) o := putFile(t, f, "a.txt", []byte("hello")) require.NoError(t, f.Disconnect(ctx)) assert.Empty(t, m["client_access_token"]) assert.Empty(t, m["client_refresh_token"]) _, err := f.List(ctx, "") require.Error(t, err) assert.Contains(t, err.Error(), `rclone config reconnect test:`) _, err = readObject(t, o) require.Error(t, err) assert.Contains(t, err.Error(), `rclone config reconnect test:`) _, err = f.Put(ctx, bytes.NewReader([]byte("x")), object.NewStaticObjectInfo("b.txt", time.Now(), 1, true, nil, nil)) require.Error(t, err) assert.Contains(t, err.Error(), `rclone config reconnect test:`) } func TestSessionExpiredNamesRemote(t *testing.T) { ctx := context.Background() srv := protontest.New(t) u := srv.AddUser("user", "pass") m := sessionConfig(srv, u) f := newTestFs(t, m) f.c.s.adoptWait = 0 srv.RevokeSession(m["client_uid"]) _, err := f.List(ctx, "") require.ErrorIs(t, err, errSessionExpired) assert.Contains(t, err.Error(), `rclone config reconnect test:`) assert.NotContains(t, err.Error(), "remote:") } func TestTrashedBehindTheFsBack(t *testing.T) { ctx := context.Background() srv := protontest.New(t) u := srv.AddUser("user", "pass") f := newTestFs(t, sessionConfig(srv, u)) other := newTestFs(t, sessionConfig(srv, u)) o := putFile(t, f, "a.txt", []byte("hello")) require.NoError(t, f.Mkdir(ctx, "dir")) _, err := f.List(ctx, "") require.NoError(t, err) trash := func(remote string) { otherObj, err := other.NewObject(ctx, remote) if err == nil { require.NoError(t, otherObj.Remove(ctx)) return } require.NoError(t, other.Purge(ctx, remote)) } trash("a.txt") trash("dir") src := object.NewStaticObjectInfo("a.txt", time.Now(), 1, true, nil, nil) assert.Equal(t, fs.ErrorObjectNotFound, o.Update(ctx, bytes.NewReader([]byte("x")), src)) _, err = f.Move(ctx, o, "b.txt") assert.Equal(t, fs.ErrorObjectNotFound, err) _, err = f.Copy(ctx, o, "c.txt") assert.Equal(t, fs.ErrorObjectNotFound, err) assert.Equal(t, fs.ErrorDirNotFound, f.DirMove(ctx, f, "dir", "dir2")) for _, d := range u.Dump() { assert.NotContains(t, []string{"b.txt", "c.txt", "dir2"}, d.Path) } } func TestOpenRange(t *testing.T) { srv := protontest.New(t) u := srv.AddUser("user", "pass") content := []byte("0123456789abcdefghijklmnopqrstuvwxyz") // A file without extended attributes, whose plaintext size only // its content tells. seeded := u.SeedFile(u.RootID(), "tmp", content, time.Now()) stored := u.StoredFile(seeded) stored.Revision.XAttr = "" m := sessionConfig(srv, u) cleanup := newTestFs(t, m) o, err := cleanup.NewObject(context.Background(), "tmp") require.NoError(t, err) require.NoError(t, o.Remove(context.Background())) u.SeedStoredFile(u.RootID(), stored) for _, original := range []bool{true, false} { t.Run(fmt.Sprint("original_file_size=", original), func(t *testing.T) { m := sessionConfig(srv, u) m["original_file_size"] = fmt.Sprint(original) f := newTestFs(t, m) put := putFile(t, f, fmt.Sprintf("put-%v.txt", original), content) bare, err := f.NewObject(context.Background(), "tmp") require.NoError(t, err) for _, o := range []fs.Object{put, bare} { for _, test := range []struct { opt fs.OpenOption want string }{ {&fs.RangeOption{Start: -1, End: 5}, "vwxyz"}, {&fs.RangeOption{Start: 30, End: -1}, "uvwxyz"}, {&fs.RangeOption{Start: 30, End: 1000}, "uvwxyz"}, {&fs.RangeOption{Start: 2, End: 4}, "234"}, {&fs.SeekOption{Offset: 33}, "xyz"}, {&fs.RangeOption{Start: -1, End: 1000}, string(content)}, } { got, err := readObject(t, o, test.opt) require.NoError(t, err) assert.Equal(t, test.want, string(got), "%s %v", o.Remote(), test.opt) } } }) } } // TestPutNestedReadBackLag puts a file into new nested directories // while the server takes a moment to show new nodes. func TestPutNestedReadBackLag(t *testing.T) { srv := protontest.New(t) u := srv.AddUser("user", "pass") f := newTestFs(t, sessionConfig(srv, u)) srv.SetReadLag(2, protontest.LagMissing) o := putFile(t, f, "A1/B1/C1/one", []byte("aaa")) assert.Equal(t, int64(3), o.Size()) } // newPollingFs returns an Fs at root on a new fake server, polling // events every testPollInterval with at most testPollJitter added, and // another Fs of the same user which doesn't poll, standing for another // client. func newPollingFs(t *testing.T, root string) (f, other *Fs, srv *protontest.Server, u *protontest.User) { t.Helper() srv = protontest.New(t) u = srv.AddUser("user", "pass") m := sessionConfig(srv, u) m["events_min_interval"] = testPollInterval.String() fsys, err := NewFs(context.Background(), "test", root, m) require.NoError(t, err) f = fsys.(*Fs) t.Cleanup(func() { _ = f.Shutdown(context.Background()) }) f.c.events.jitter = testPollJitter return f, newTestFs(t, sessionConfig(srv, u)), srv, u } // subscribers returns the number of subscribers of p. func (p *eventPoller) subscribers() int { p.mu.Lock() defer p.mu.Unlock() return len(p.subs) } // polling reports whether p has subscribers and a cursor to poll from. func (p *eventPoller) polling() bool { p.mu.Lock() defer p.mu.Unlock() return len(p.subs) > 0 && p.cursor != "" } // setCursor makes p poll from cursor next, after any poll running. func (p *eventPoller) setCursor(cursor string) { p.runMu.Lock() defer p.runMu.Unlock() p.mu.Lock() defer p.mu.Unlock() p.cursor = cursor } // changes collects what ChangeNotify reports. type changes struct { mu sync.Mutex got map[changedPath]int } // notify records path and entryType. func (c *changes) notify(path string, entryType fs.EntryType) { c.mu.Lock() defer c.mu.Unlock() if c.got == nil { c.got = make(map[changedPath]int) } c.got[changedPath{path, entryType}]++ } // paths returns the paths reported so far, each once. func (c *changes) paths() []changedPath { c.mu.Lock() defer c.mu.Unlock() out := make([]changedPath, 0, len(c.got)) for p := range c.got { out = append(out, p) } slices.SortFunc(out, compareChangedPaths) return out } // startChangeNotify starts ChangeNotify on f at testPollInterval, // returning what it reports and the interval channel, closed when the // test ends. func startChangeNotify(t *testing.T, f *Fs) (*changes, chan<- time.Duration) { t.Helper() got := &changes{} intervals := make(chan time.Duration) f.ChangeNotify(context.Background(), got.notify, intervals) intervals <- testPollInterval require.Eventually(t, f.c.events.polling, 2*time.Second, time.Millisecond) t.Cleanup(func() { close(intervals) }) return got, intervals } // requireChanges waits for got to report exactly want, and checks no // more is reported over the next poll. func requireChanges(t *testing.T, got *changes, want ...changedPath) { t.Helper() slices.SortFunc(want, compareChangedPaths) if want == nil { want = []changedPath{} } if !assert.Eventually(t, func() bool { return slices.Equal(want, got.paths()) }, 3*time.Second, 5*time.Millisecond) { t.Fatalf("want %v, got %v", want, got.paths()) } time.Sleep(2 * (testPollInterval + testPollJitter)) assert.Equal(t, want, got.paths(), "more reported") } // compareChangedPaths orders changed paths by path, then type. func compareChangedPaths(a, b changedPath) int { return cmp.Or(strings.Compare(a.path, b.path), cmp.Compare(a.entryType, b.entryType)) } // dirChange and objChange are a changed directory and object at path. func dirChange(path string) changedPath { return changedPath{path, fs.EntryDirectory} } func objChange(path string) changedPath { return changedPath{path, fs.EntryObject} } func TestChangeNotifyEvents(t *testing.T) { t.Parallel() ctx := context.Background() for _, test := range []struct { name string change func(t *testing.T, f, other *Fs, srv *protontest.Server, u *protontest.User) want []changedPath flushed []string // dircache paths gone afterwards refresh bool }{{ name: "created file", change: func(t *testing.T, f, other *Fs, srv *protontest.Server, u *protontest.User) { putFile(t, other, "dir/new.txt", []byte("new")) }, want: []changedPath{dirChange("dir")}, }, { name: "created folder", change: func(t *testing.T, f, other *Fs, srv *protontest.Server, u *protontest.User) { require.NoError(t, other.Mkdir(ctx, "dir/newdir")) }, want: []changedPath{dirChange("dir")}, }, { name: "updated", change: func(t *testing.T, f, other *Fs, srv *protontest.Server, u *protontest.User) { o, err := other.NewObject(ctx, "dir/file.txt") require.NoError(t, err) src := object.NewStaticObjectInfo("dir/file.txt", time.Now(), 7, true, nil, nil) require.NoError(t, o.Update(ctx, bytes.NewReader([]byte("changed")), src)) }, want: []changedPath{objChange("dir/file.txt")}, }, { name: "deleted file", change: func(t *testing.T, f, other *Fs, srv *protontest.Server, u *protontest.User) { o, err := other.NewObject(ctx, "dir/file.txt") require.NoError(t, err) dirID, ok := f.dirCache.Get("dir") require.True(t, ok) srv.InjectEvent(u, protontest.Event{Type: protontest.EventDelete, LinkID: o.(fs.IDer).ID(), ParentLinkID: dirID}) }, want: []changedPath{objChange("dir/file.txt")}, }, { name: "deleted folder", change: func(t *testing.T, f, other *Fs, srv *protontest.Server, u *protontest.User) { dirID, ok := f.dirCache.Get("dir") require.True(t, ok) subID, ok := f.dirCache.Get("dir/sub") require.True(t, ok) srv.InjectEvent(u, protontest.Event{Type: protontest.EventDelete, LinkID: subID, ParentLinkID: dirID}) }, want: []changedPath{dirChange("dir/sub")}, flushed: []string{"dir/sub"}, }, { name: "trashed and emptied", change: func(t *testing.T, f, other *Fs, srv *protontest.Server, u *protontest.User) { o, err := other.NewObject(ctx, "dir/file.txt") require.NoError(t, err) require.NoError(t, o.Remove(ctx)) require.NoError(t, other.CleanUp(ctx)) }, // The trash names the cached file. The file is gone for good // when the events are read, so they report no parent, and the // deletion of a node no longer cached names nothing more. want: []changedPath{objChange("dir/file.txt")}, }, { name: "moved file", change: func(t *testing.T, f, other *Fs, srv *protontest.Server, u *protontest.User) { o, err := other.NewObject(ctx, "dir/file.txt") require.NoError(t, err) _, err = other.Move(ctx, o, "dir/sub/file.txt") require.NoError(t, err) }, want: []changedPath{objChange("dir/file.txt"), objChange("dir/sub/file.txt")}, }, { name: "renamed file", change: func(t *testing.T, f, other *Fs, srv *protontest.Server, u *protontest.User) { o, err := other.NewObject(ctx, "dir/file.txt") require.NoError(t, err) _, err = other.Move(ctx, o, "dir/renamed.txt") require.NoError(t, err) }, want: []changedPath{objChange("dir/file.txt")}, }, { name: "moved folder", change: func(t *testing.T, f, other *Fs, srv *protontest.Server, u *protontest.User) { require.NoError(t, other.DirMove(ctx, other, "dir/sub", "sub")) }, want: []changedPath{dirChange("dir/sub"), dirChange("sub")}, flushed: []string{"dir/sub"}, }, { name: "renamed folder", change: func(t *testing.T, f, other *Fs, srv *protontest.Server, u *protontest.User) { require.NoError(t, other.DirMove(ctx, other, "dir/sub", "dir/sub2")) }, want: []changedPath{dirChange("dir/sub"), dirChange("dir")}, flushed: []string{"dir/sub"}, }, { name: "trashed file", change: func(t *testing.T, f, other *Fs, srv *protontest.Server, u *protontest.User) { o, err := other.NewObject(ctx, "dir/file.txt") require.NoError(t, err) require.NoError(t, o.Remove(ctx)) }, want: []changedPath{objChange("dir/file.txt")}, }, { name: "trashed folder", change: func(t *testing.T, f, other *Fs, srv *protontest.Server, u *protontest.User) { require.NoError(t, other.Purge(ctx, "dir/sub")) }, want: []changedPath{dirChange("dir/sub")}, flushed: []string{"dir/sub"}, }, { name: "tree refresh", change: func(t *testing.T, f, other *Fs, srv *protontest.Server, u *protontest.User) { f.c.events.setCursor("unknown") }, want: []changedPath{dirChange("")}, flushed: []string{"dir", "dir/sub"}, refresh: true, }, { name: "cursor expired", change: func(t *testing.T, f, other *Fs, srv *protontest.Server, u *protontest.User) { f.c.events.mu.Lock() old := f.c.events.cursor f.c.events.mu.Unlock() require.NoError(t, other.Mkdir(ctx, "dir/sub/newdir")) srv.ExpireEvents(u) f.c.events.setCursor(old) }, // Whether or not a poll saw the new folder first. want: []changedPath{dirChange("")}, flushed: []string{"dir", "dir/sub"}, refresh: true, }} { t.Run(test.name, func(t *testing.T) { t.Parallel() f, other, srv, u := newPollingFs(t, "") putFile(t, other, "dir/file.txt", []byte("hello")) putFile(t, other, "dir/sub/deep.txt", []byte("deep")) for _, dir := range []string{"", "dir", "dir/sub"} { _, err := f.List(ctx, dir) require.NoError(t, err) } got, _ := startChangeNotify(t, f) test.change(t, f, other, srv, u) requireChanges(t, got, test.want...) for _, p := range test.flushed { _, ok := f.dirCache.Get(p) assert.False(t, ok, "%s is still in the dircache", p) } rootID, ok := f.dirCache.Get("") assert.True(t, ok && rootID == f.c.rootID(), "the root is kept") if test.refresh { assert.True(t, f.c.cache.empty(), "the cache is cleared") } }) } } func TestChangeNotifyProtonEvents(t *testing.T) { t.Parallel() ctx := context.Background() f, other, srv, u := newPollingFs(t, "") o := putFile(t, other, "dir/file.txt", []byte("hello")) for _, dir := range []string{"", "dir"} { _, err := f.List(ctx, dir) require.NoError(t, err) } dirID, ok := f.dirCache.Get("dir") require.True(t, ok) got, _ := startChangeNotify(t, f) lastEvents := func(n int) []protontest.Event { events := srv.Events(u) require.GreaterOrEqual(t, len(events), n) return events[len(events)-n:] } // A folder made and removed between polls: its Create reports it // already trashed. f.c.events.runMu.Lock() require.NoError(t, other.Mkdir(ctx, "dir/brief")) require.NoError(t, other.Rmdir(ctx, "dir/brief")) f.c.events.runMu.Unlock() events := lastEvents(2) briefID := events[0].LinkID assert.Equal(t, []protontest.Event{ {Type: protontest.EventCreate, LinkID: briefID, ParentLinkID: dirID, IsTrashed: true}, {Type: protontest.EventUpdateMetadata, LinkID: briefID, ParentLinkID: dirID, IsTrashed: true}, }, events) requireChanges(t, got, dirChange("dir")) _, ok = f.c.cache.children(dirID) assert.False(t, ok, "the listing of dir is still cached") // A rename reported as UpdateMetadata. _, err := f.List(ctx, "dir") require.NoError(t, err) fileID := o.(fs.IDer).ID() require.NotNil(t, f.c.cache.get(fileID)) _, err = other.Move(ctx, o, "dir/renamed.txt") require.NoError(t, err) assert.Equal(t, []protontest.Event{{Type: protontest.EventUpdateMetadata, LinkID: fileID, ParentLinkID: dirID}}, lastEvents(1)) requireChanges(t, got, dirChange("dir"), objChange("dir/file.txt")) assert.Nil(t, f.c.cache.get(fileID), "the renamed file is still cached") _, ok = f.c.cache.children(dirID) assert.False(t, ok, "the listing of dir is still cached") } func TestChangeNotifyOutsideRoot(t *testing.T) { t.Parallel() ctx := context.Background() f, other, _, _ := newPollingFs(t, "dir") putFile(t, other, "dir/in.txt", []byte("in")) putFile(t, other, "elsewhere/x.txt", []byte("x")) putFile(t, other, "top.txt", []byte("top")) // The root was looked for, and the cursor fetched, before the // files were made: skip their events, then find the root again, // caching the folders above it. latest, err := f.c.latestEventID(ctx) require.NoError(t, err) f.c.events.setCursor(latest) f.c.cache.clear() f.dirCache.ResetRoot() _, err = f.List(ctx, "") require.NoError(t, err) elsewhereID, ok := other.dirCache.Get("elsewhere") require.True(t, ok) require.NotNil(t, f.c.cache.get(elsewhereID), "nothing cached outside the root") got, _ := startChangeNotify(t, f) putFile(t, other, "elsewhere/y.txt", []byte("y")) putFile(t, other, "top2.txt", []byte("top")) o, err := other.NewObject(ctx, "top.txt") require.NoError(t, err) require.NoError(t, o.Remove(ctx)) require.NoError(t, other.DirMove(ctx, other, "elsewhere", "elsewhere2")) // A change inside the root, so there is something to wait for. putFile(t, other, "dir/sentinel.txt", []byte("in")) requireChanges(t, got, dirChange("")) } func TestChangeNotifyPauseAndClose(t *testing.T) { t.Parallel() ctx := context.Background() f, other, srv, _ := newPollingFs(t, "") require.True(t, f.c.cache.empty()) got := &changes{} intervals := make(chan time.Duration) f.ChangeNotify(ctx, got.notify, intervals) intervals <- testPollInterval require.Eventually(t, func() bool { return f.c.events.polling() }, 2*time.Second, time.Millisecond) // Polling runs with nothing cached. putFile(t, other, "a.txt", []byte("a")) requireChanges(t, got, dirChange("")) _, err := f.List(ctx, "") require.NoError(t, err) // Paused, nothing is reported. intervals <- 0 require.Eventually(t, func() bool { return f.c.events.subscribers() == 0 }, 2*time.Second, time.Millisecond) require.NoError(t, other.Mkdir(ctx, "paused")) time.Sleep(3 * (testPollInterval + testPollJitter)) assert.Equal(t, []changedPath{dirChange("")}, got.paths()) // Resumed, changes are reported again. intervals <- testPollInterval require.Eventually(t, func() bool { return f.c.events.subscribers() == 1 }, 2*time.Second, time.Millisecond) _, err = f.List(ctx, "") require.NoError(t, err) putFile(t, other, "paused/b.txt", []byte("b")) requireChanges(t, got, dirChange(""), dirChange("paused")) // Closed, it unsubscribes, and with nothing cached polling stops. close(intervals) require.Eventually(t, func() bool { return f.c.events.subscribers() == 0 }, 2*time.Second, time.Millisecond) f.c.cache.clear() time.Sleep(testPollInterval + testPollJitter) srv.ResetRequests() time.Sleep(3 * (testPollInterval + testPollJitter)) latest, pages := eventRequests(srv) assert.Zero(t, latest+pages, "polled with nothing cached and nothing subscribed") } // TestChangeNotifyCachedAfterEvent checks an item whose event is // applied before it is cached, as an upload's can be, is named by its // folder at once and by its own path at the next poll once cached. func TestChangeNotifyCachedAfterEvent(t *testing.T) { t.Parallel() ctx := context.Background() f, other, _, _ := newPollingFs(t, "") putFile(t, other, "dir/file.txt", []byte("hello")) for _, dir := range []string{"", "dir"} { _, err := f.List(ctx, dir) require.NoError(t, err) } got, _ := startChangeNotify(t, f) // One poll applies both events, with neither node cached. f.c.events.runMu.Lock() putFile(t, other, "dir/new.txt", []byte("new")) require.NoError(t, other.Mkdir(ctx, "dir/newdir")) f.c.events.runMu.Unlock() require.Eventually(t, func() bool { return len(got.paths()) > 0 }, 3*time.Second, 5*time.Millisecond) assert.Equal(t, []changedPath{dirChange("dir")}, got.paths()) // Both are cached before the next poll. f.c.events.runMu.Lock() _, err := f.NewObject(ctx, "dir/new.txt") require.NoError(t, err) _, err = f.List(ctx, "dir") require.NoError(t, err) f.c.events.runMu.Unlock() requireChanges(t, got, dirChange("dir"), objChange("dir/new.txt"), dirChange("dir/newdir")) assert.Empty(t, f.c.events.pendingIDs(), "nothing left pending") _, ok := f.dirCache.Get("dir/newdir") assert.True(t, ok, "a folder named late is flushed from the dircache") } // pendingIDs returns the IDs of the nodes p waits to name, oldest first. func (p *eventPoller) pendingIDs() []string { p.mu.Lock() defer p.mu.Unlock() var ids []string for _, pn := range p.pending { ids = append(ids, pn.id) } return ids } func TestPollerPendingBounded(t *testing.T) { t.Parallel() p := newEventPoller(eventsTestClient(), 0) unknown := func(ids ...int) []staleNode { var stale []staleNode for _, id := range ids { stale = append(stale, staleNode{id: fmt.Sprint(id), newParentID: "dir"}) } return stale } add := func(stale []staleNode) { p.mu.Lock() defer p.mu.Unlock() p.addPendingLocked(stale) } // Nothing is kept without subscribers. add(unknown(1)) assert.Empty(t, p.pendingIDs()) unsubscribe := p.subscribe(func([]staleNode, bool) {}) ids := make([]int, maxPendingNodes+1) for i := range ids { ids[i] = i } add(unknown(ids...)) // Neither nodes deleted or trashed nor those of no known parent. add([]staleNode{{id: "gone", newParentID: "dir", gone: true}, {id: "orphan"}}) pending := p.pendingIDs() require.Len(t, pending, maxPendingNodes) assert.Equal(t, "1", pending[0], "the oldest is dropped") assert.Equal(t, fmt.Sprint(maxPendingNodes), pending[len(pending)-1]) // An ID seen again moves to the end. add(unknown(1)) pending = p.pendingIDs() require.Len(t, pending, maxPendingNodes) assert.Equal(t, "1", pending[len(pending)-1]) unsubscribe() assert.Empty(t, p.pendingIDs(), "kept after the last unsubscribe") p.subscribe(func([]staleNode, bool) {}) add(unknown(1)) p.stop() assert.Empty(t, p.pendingIDs(), "kept after stop") } // TestPollerResolvesPending checks a pending node is named once cached, // and given up after two polls if not. func TestPollerResolvesPending(t *testing.T) { t.Parallel() c := eventsTestClient() p := newEventPoller(c, 0) p.subscribe(func([]staleNode, bool) {}) p.mu.Lock() defer p.mu.Unlock() p.addPendingLocked([]staleNode{ {id: "late", newParentID: "dir"}, {id: "never", newParentID: "dir"}, }) assert.Empty(t, p.resolvePendingLocked()) c.cache.put(&node{ID: "late", ParentID: "dir", Name: "late.txt"}) assert.Equal(t, []staleNode{{id: "late", parentID: "dir", name: "late.txt", known: true, late: true}}, p.resolvePendingLocked()) assert.Empty(t, p.pending, "given up after two polls") } // TestChangeNotifyUncachedFolderInDirCache checks a folder the node // cache no longer holds but the dircache does is named and flushed at // its old path when another client moves it. func TestChangeNotifyUncachedFolderInDirCache(t *testing.T) { t.Parallel() ctx := context.Background() f, other, _, _ := newPollingFs(t, "") putFile(t, other, "dir/sub/deep.txt", []byte("deep")) require.NoError(t, other.Mkdir(ctx, "elsewhere")) for _, dir := range []string{"", "dir", "dir/sub"} { _, err := f.List(ctx, dir) require.NoError(t, err) } got, _ := startChangeNotify(t, f) f.c.events.runMu.Lock() f.c.cache.clear() f.c.events.runMu.Unlock() _, ok := f.dirCache.Get("dir/sub") require.True(t, ok) require.NoError(t, other.DirMove(ctx, other, "dir/sub", "elsewhere/sub")) requireChanges(t, got, dirChange("dir/sub"), dirChange("elsewhere")) _, ok = f.dirCache.Get("dir/sub") assert.False(t, ok, "dir/sub is still in the dircache") } // TestChangeNotifyRootIsFile checks an Fs rooted at a file keeps its // dircache up to date with events too. func TestChangeNotifyRootIsFile(t *testing.T) { t.Parallel() ctx := context.Background() srv := protontest.New(t) u := srv.AddUser("user", "pass") other := newTestFs(t, sessionConfig(srv, u)) putFile(t, other, "a/file.txt", []byte("file")) putFile(t, other, "a/sub/x.txt", []byte("x")) m := sessionConfig(srv, u) m["events_min_interval"] = testPollInterval.String() fsys, err := NewFs(ctx, "test", "a/file.txt", m) require.ErrorIs(t, err, fs.ErrorIsFile) f := fsys.(*Fs) t.Cleanup(func() { _ = f.Shutdown(context.Background()) }) f.c.events.jitter = testPollJitter _, err = f.List(ctx, "sub") require.NoError(t, err) _, ok := f.dirCache.Get("sub") require.True(t, ok) require.NoError(t, other.DirMove(ctx, other, "a/sub", "a/sub2")) assert.Eventually(t, func() bool { _, ok := f.dirCache.Get("sub") return !ok }, 3*time.Second, 5*time.Millisecond, "sub is still in the dircache") } func TestDirCacheFlushKeepsRoot(t *testing.T) { t.Parallel() ctx := context.Background() srv := protontest.New(t) u := srv.AddUser("user", "pass") other := newTestFs(t, sessionConfig(srv, u)) putFile(t, other, "dir/sub/x.txt", []byte("x")) fsys, err := NewFs(ctx, "test", "dir", sessionConfig(srv, u)) require.NoError(t, err) f := fsys.(*Fs) t.Cleanup(func() { _ = f.Shutdown(context.Background()) }) dirID, ok := f.dirCache.Get("") require.True(t, ok) _, err = f.List(ctx, "") require.NoError(t, err) _, ok = f.dirCache.Get("sub") require.True(t, ok) f.DirCacheFlush() _, ok = f.dirCache.Get("sub") assert.False(t, ok, "sub is still in the dircache") rootID, ok := f.dirCache.Get("") assert.True(t, ok && rootID == dirID, "the root is kept") assert.True(t, f.c.cache.empty(), "the cache is cleared") entries, err := f.List(ctx, "sub") require.NoError(t, err) assert.Len(t, entries, 1) }