From ea9b1b37f501f34ab7d114c5b1dd16dde6762d16 Mon Sep 17 00:00:00 2001 From: Umang Shikarvar Date: Sun, 18 Oct 2026 19:50:47 +0000 Subject: [PATCH] Invalidate shared users' caches on every folder change Only file creation, uploads, writes and permanent deletes sent invalidation callbacks. mkdir, moving to trash and restoring from trash changed a folder without telling anyone viewing it, so users the folder is shared with kept a stale listing. - CreateFile notifies for directories too (mkdir, folder uploads), and no longer notifies the user who made the change. - TrashFile notifies the item's original folder. - RestoreFile notifies the folder the item is restored into. - A failed upload that scraps its partial file now announces the removal, since CreateFile had already announced the file. - Client notification text covers both files and folders. Adds end-to-end tests: mkdir/trash/restore and file/folder upload by the owner are seen by the shared user's cache. --- internal/client/callback_server.go | 4 +- internal/client/robustness_test.go | 2 +- internal/client/shared_invalidation_test.go | 116 ++++++++++++++++++++ internal/fileserver/callback_server.go | 20 ++++ internal/fileserver/handler.go | 20 +++- 5 files changed, 155 insertions(+), 7 deletions(-) diff --git a/internal/client/callback_server.go b/internal/client/callback_server.go index dee4617..effbd44 100644 --- a/internal/client/callback_server.go +++ b/internal/client/callback_server.go @@ -59,10 +59,10 @@ func (s *callbackServer) Invalidate(ctx context.Context, req *cbpb.InvalidateReq switch eventType { case callbackEventDirNewFile: ch.QueueDirInvalidation(fid) - s.client.Notify("\n[NOTIFY] New file uploaded in your current directory by another user. Cache invalidated; run ls to see it.\n") + s.client.Notify("\n[NOTIFY] New file or folder added in your current directory by another user. Cache invalidated; run ls to see it.\n") case callbackEventFileDeleted: ch.QueueDirInvalidation(fid) - s.client.Notify("\n[NOTIFY] A file was deleted in your current directory by another user. Cache invalidated; run ls to see the change.\n") + s.client.Notify("\n[NOTIFY] A file or folder was deleted in your current directory by another user. Cache invalidated; run ls to see the change.\n") default: ch.QueueFileInvalidation(fid) s.client.Notify("\n[NOTIFY] File updated by another user. Cache invalidated.\n") diff --git a/internal/client/robustness_test.go b/internal/client/robustness_test.go index 42250c2..3a3c69f 100644 --- a/internal/client/robustness_test.go +++ b/internal/client/robustness_test.go @@ -122,7 +122,7 @@ func TestRobustness_CallbackServerInvalidate_EventTypesAndNotification(t *testin if err != nil || resp == nil || !resp.Success { t.Fatalf("Invalidate DirNewFile failed: resp=%+v, err=%v", resp, err) } - if !strings.Contains(notifyBuf.String(), "[NOTIFY]") || !strings.Contains(notifyBuf.String(), "New file uploaded") { + if !strings.Contains(notifyBuf.String(), "[NOTIFY]") || !strings.Contains(notifyBuf.String(), "New file or folder added") { t.Fatalf("unexpected notify output: %s", notifyBuf.String()) } diff --git a/internal/client/shared_invalidation_test.go b/internal/client/shared_invalidation_test.go index 68f5609..275f24b 100644 --- a/internal/client/shared_invalidation_test.go +++ b/internal/client/shared_invalidation_test.go @@ -1,6 +1,8 @@ package client import ( + "os" + "path/filepath" "strings" "sync" "testing" @@ -100,3 +102,117 @@ func hasFile(files []*FileInfo, name string) bool { } return false } + +// setupSharedPair connects alice (owner) and bob (shared user, with a cache +// handler) to alice's root. expect runs action and waits until bob receives a +// new notification containing want. +func setupSharedPair(t *testing.T) (alice, bob *Client, bobCache *CacheHandler, expect func(what, want string, action func() error)) { + t.Helper() + fsAddr, _, cleanupFS := startTestFileServerGRPC(t, "") + t.Cleanup(cleanupFS) + + alice = connectTestClient(t, "alice", "alice", fsAddr) + t.Cleanup(alice.Disconnect) + if err := alice.Share("bob"); err != nil { + t.Fatalf("Share failed: %v", err) + } + + bob = connectTestClient(t, "bob", "alice", fsAddr) + t.Cleanup(bob.Disconnect) + rec := ¬ifyRecorder{ch: make(chan struct{}, 64)} + bob.SetNotifyWriter(rec) + bobCache = NewCacheHandler(bob, bob.rootFID) + if bobCache == nil { + t.Fatalf("NewCacheHandler returned nil") + } + bob.AttachCacheHandler(bobCache) + + expect = func(what, want string, action func() error) { + t.Helper() + // Let callbacks from earlier steps land so they are not mistaken for this one. + time.Sleep(100 * time.Millisecond) + rec.mu.Lock() + mark := len(rec.msgs) + rec.mu.Unlock() + + if err := action(); err != nil { + t.Fatalf("%s failed: %v", what, err) + } + deadline := time.After(5 * time.Second) + for { + rec.mu.Lock() + for _, m := range rec.msgs[mark:] { + if strings.Contains(m, want) { + rec.mu.Unlock() + return + } + } + rec.mu.Unlock() + select { + case <-rec.ch: + case <-deadline: + t.Fatalf("bob never received a %q notification for %s", want, what) + } + } + } + return alice, bob, bobCache, expect +} + +func TestSharedUserNotifiedOnMkdirTrashRestore(t *testing.T) { + defer withTempWorkingDir(t)() + alice, _, bobCache, expect := setupSharedPair(t) + + if files, _ := bobCache.ListFiles(); hasFile(files, "share_test") { + t.Fatalf("share_test should not exist yet") + } + + expect("mkdir", "added", func() error { _, err := alice.CreateDirectory("share_test"); return err }) + if files, _ := bobCache.ListFiles(); !hasFile(files, "share_test") { + t.Fatalf("bob does not see share_test after mkdir: %+v", files) + } + + expect("trash", "deleted", func() error { _, err := alice.TrashFile("share_test", true); return err }) + if files, _ := bobCache.ListFiles(); hasFile(files, "share_test") { + t.Fatalf("bob still sees share_test after trash: %+v", files) + } + + expect("restore", "added", func() error { + trash, err := alice.ShowTrash() + if err != nil || len(trash) == 0 { + t.Fatalf("alice ShowTrash failed: err=%v entries=%d", err, len(trash)) + } + _, err = alice.RestoreFile(trash[0].Name) + return err + }) + if files, _ := bobCache.ListFiles(); !hasFile(files, "share_test") { + t.Fatalf("bob does not see share_test after restore: %+v", files) + } +} + +func TestSharedUserNotifiedOnUploadFileAndFolder(t *testing.T) { + defer withTempWorkingDir(t)() + alice, _, bobCache, expect := setupSharedPair(t) + + local := t.TempDir() + filePath := filepath.Join(local, "notes.txt") + if err := os.WriteFile(filePath, []byte("hello from alice"), 0o644); err != nil { + t.Fatal(err) + } + folder := filepath.Join(local, "photos") + if err := os.MkdirAll(folder, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(folder, "a.jpg"), []byte("jpg"), 0o644); err != nil { + t.Fatal(err) + } + + expect("file upload", "added", func() error { _, err := alice.Upload(filePath); return err }) + if files, _ := bobCache.ListFiles(); !hasFile(files, "notes.txt") { + t.Fatalf("bob does not see notes.txt after upload: %+v", files) + } + + expect("folder upload", "added", func() error { _, err := alice.Upload(folder); return err }) + if files, _ := bobCache.ListFiles(); !hasFile(files, "photos") { + t.Fatalf("bob does not see photos/ after folder upload: %+v", files) + } +} diff --git a/internal/fileserver/callback_server.go b/internal/fileserver/callback_server.go index 21573be..27afe39 100644 --- a/internal/fileserver/callback_server.go +++ b/internal/fileserver/callback_server.go @@ -226,6 +226,26 @@ func (fs *FileServer) sendInvalidate(target clientSession, changedFID *domain.FI fs.recordCallbackResult(target.username, true) } +// parentAndName returns a copy of the inode's parent FID and its current name, +// or (nil, "") if the inode or its parent is unknown. +func (fs *FileServer) parentAndName(fid *domain.FID) (*domain.FID, string) { + if fid == nil { + return nil, "" + } + fs.mu.RLock() + defer fs.mu.RUnlock() + inode, err := fs.GetInode(fid) + if err != nil || inode == nil || inode.Parent == nil || inode.Parent.FID == nil { + return nil, "" + } + p := inode.Parent.FID + return &domain.FID{ + FileServerID: p.FileServerID, + InodeID: p.InodeID, + GenerationNumber: p.GenerationNumber, + }, inode.Name +} + // NotifyFileUpdated notifies active users in the same current directory about file changes. func (fs *FileServer) NotifyFileUpdated(parentFID *domain.FID, name, originUsername string) { if parentFID == nil || name == "" { diff --git a/internal/fileserver/handler.go b/internal/fileserver/handler.go index 48ee29c..533383f 100644 --- a/internal/fileserver/handler.go +++ b/internal/fileserver/handler.go @@ -551,9 +551,8 @@ func (h *GRPCHandler) CreateFile(ctx context.Context, req *pb.CreateFileRequest) } log.Printf("CreateFile: success - created %s with FID %s", req.Name, fid.String()) - if fileType == domain.InodeTypeFile { - h.fileServer.NotifyNewFileInDir(parentFID, req.Name, "") - } + // Notify for directories too, so `mkdir` in a shared folder reaches other users. + h.fileServer.NotifyNewFileInDir(parentFID, req.Name, effectiveUser) return &pb.CreateFileResponse{ Success: true, @@ -579,7 +578,10 @@ func (h *GRPCHandler) cleanupFailedUpload(parentFID *domain.FID, name string, us } log.Printf("[FILESERVER] Scrapping partially uploaded file '%s' (FID: %s) for user '%s'", name, childInode.FID.String(), user) - _ = h.fileServer.DeleteFile(childInode.FID, user, false) + if err := h.fileServer.DeleteFile(childInode.FID, user, false); err == nil { + // CreateFile already announced this file; tell other users it is gone again. + h.fileServer.NotifyFileDeletedInDir(parentFID, name, user) + } } // UploadFile uploads the file chunk by chunk @@ -997,6 +999,9 @@ func (h *GRPCHandler) TrashFile(ctx context.Context, req *pb.TrashFileRequest) ( return &pb.TrashFileResponse{Success: false, Error: "user is required"}, nil } + // Capture the parent before the move so users in that directory can be notified. + parentFID, originalName := h.fileServer.parentAndName(fid) + trashedName, err := h.fileServer.TrashFile(fid, effectiveUser, req.Recursive) if err != nil { log.Printf("TrashFile: error - %v", err) @@ -1004,6 +1009,8 @@ func (h *GRPCHandler) TrashFile(ctx context.Context, req *pb.TrashFileRequest) ( return &pb.TrashFileResponse{Success: false, Error: err.Error()}, nil } + h.fileServer.NotifyFileDeletedInDir(parentFID, originalName, effectiveUser) + return &pb.TrashFileResponse{Success: true, TrashedName: trashedName}, nil } @@ -1051,6 +1058,11 @@ func (h *GRPCHandler) RestoreFile(ctx context.Context, req *pb.RestoreFileReques return &pb.RestoreFileResponse{Success: false, Error: err.Error()}, nil } + // The item reappears in its original directory; tell users who are there. + if restoredParent, _ := h.fileServer.parentAndName(fid); restoredParent != nil { + h.fileServer.NotifyNewFileInDir(restoredParent, restoredName, req.Username) + } + return &pb.RestoreFileResponse{Success: true, RestoredName: restoredName}, nil }