Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions internal/client/callback_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
2 changes: 1 addition & 1 deletion internal/client/robustness_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}

Expand Down
116 changes: 116 additions & 0 deletions internal/client/shared_invalidation_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package client

import (
"os"
"path/filepath"
"strings"
"sync"
"testing"
Expand Down Expand Up @@ -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 := &notifyRecorder{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)
}
}
20 changes: 20 additions & 0 deletions internal/fileserver/callback_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 == "" {
Expand Down
20 changes: 16 additions & 4 deletions internal/fileserver/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -997,13 +999,18 @@ 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)
opErr = err
return &pb.TrashFileResponse{Success: false, Error: err.Error()}, nil
}

h.fileServer.NotifyFileDeletedInDir(parentFID, originalName, effectiveUser)

return &pb.TrashFileResponse{Success: true, TrashedName: trashedName}, nil
}

Expand Down Expand Up @@ -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
}

Expand Down
Loading