devbox mode (#474): final review fixes, link store and owner state
A links write whose rename landed but whose directory sync failed now returns ErrUnsynced and updates memory to match the disk. Share rolls the published link back, and unshare puts the record back before its row, or finishes the unshare when the record cannot return. After any failed mutation and a restart, every route has an owner record and every record its route; tests reopen the store through unexported seams. /list sends an empty owner plus the uid for an account the machine no longer knows, and the CLI renders DBX-C20 from that, not from "uid N" text. The retained-snapshot cap test now reaches two reshares.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+431
−39
devbox_cli.go+4 −3devbox_cli_test.go+18 −0internal/devbox/links.go+35 −14internal/devbox/links_test.go+93 −0internal/devbox/registrar.go+50 −12internal/devbox/registrar_test.go+231 −10
diff --git a/devbox_cli.go b/devbox_cli.go| index 3838c953b..0d6f6065e 100644 |
| --- a/devbox_cli.go |
| +++ b/devbox_cli.go |
| @@ -413,10 +413,11 @@ func (c *devboxCLI) list(args []string) error { |
| return tw.Flush() |
| } |
| -// devboxOwner is the owner column. The registrar shows an account it |
| -// cannot name as "uid N"; that account is gone from this machine. |
| +// devboxOwner is the owner column. The registrar sends an empty owner, with |
| +// the uid, for an account it cannot name: that account is gone from this |
| +// machine. |
| func devboxOwner(e devbox.ListEntry) string { |
| - if e.Owner == "" || e.Owner == "uid "+strconv.FormatUint(uint64(e.OwnerUID), 10) { |
| + if e.Owner == "" { |
| return devboxOwnerGone |
| } |
| return e.Owner |
diff --git a/devbox_cli_test.go b/devbox_cli_test.go| index 41572b448..8121996cf 100644 |
| --- a/devbox_cli_test.go |
| +++ b/devbox_cli_test.go |
| @@ -327,6 +327,24 @@ func TestDevboxListAccountRemoved(t *testing.T) { |
| } |
| } |
| +// The owner column comes from the structured state: an empty owner is an |
| +// account gone from the machine (DBX-C20), whatever its uid; any name the |
| +// registrar sends is shown as it is. |
| +func TestDevboxOwnerColumnFromStructuredState(t *testing.T) { |
| + for _, c := range []struct { |
| + e devbox.ListEntry |
| + want string |
| + }{ |
| + {devbox.ListEntry{Owner: "", OwnerUID: 1003}, devboxOwnerGone}, |
| + {devbox.ListEntry{Owner: "", OwnerUID: 0}, devboxOwnerGone}, |
| + {devbox.ListEntry{Owner: "ana", OwnerUID: 1001}, "ana"}, |
| + } { |
| + if got := devboxOwner(c.e); got != c.want { |
| + t.Fatalf("devboxOwner(%+v) = %q, want %q", c.e, got, c.want) |
| + } |
| + } |
| +} |
| + |
| // Someone else's name, through the real registrar: share is refused with |
| // the owner's name, and so is unshare. |
| func TestDevboxOthersLinkRefused(t *testing.T) { |
diff --git a/internal/devbox/links.go b/internal/devbox/links.go| index 5fa64aa84..da8c0dccc 100644 |
| --- a/internal/devbox/links.go |
| +++ b/internal/devbox/links.go |
| @@ -77,8 +77,17 @@ func (l *Links) Get(name string) (Link, bool) { |
| return k, ok |
| } |
| +// ErrUnsynced is what Put and Delete return, wrapped, when the new file was |
| +// published (renamed into place) but the directory sync after the rename |
| +// failed. The change is on disk and in memory: the store reads as updated, |
| +// now and after a restart, only the rename may not survive a crash. A caller |
| +// undoing its own work must undo this change too. Any other error means |
| +// nothing changed, on disk or in memory. |
| +var ErrUnsynced = errors.New("devbox: links file published but its directory sync failed") |
| + |
| // Put stores link, replacing any link of the same name, and writes the file |
| -// durably before returning. If the write fails the store is unchanged. |
| +// durably before returning. If the write fails the store is unchanged, except |
| +// for ErrUnsynced, when the store holds link. |
| func (l *Links) Put(link Link) error { |
| if err := ValidName(link.Name); err != nil { |
| return err |
| @@ -87,14 +96,12 @@ func (l *Links) Put(link Link) error { |
| defer l.mu.Unlock() |
| next := l.copyLocked() |
| next[link.Name] = link |
| - if err := l.write(next); err != nil { |
| - return err |
| - } |
| - l.links = next |
| - return nil |
| + return l.commitLocked(next) |
| } |
| -// Delete removes the link called name. A name that is not there is not an error. |
| +// Delete removes the link called name. A name that is not there is not an |
| +// error. If the write fails the store is unchanged, except for ErrUnsynced, |
| +// when name is gone. |
| func (l *Links) Delete(name string) error { |
| l.mu.Lock() |
| defer l.mu.Unlock() |
| @@ -103,11 +110,18 @@ func (l *Links) Delete(name string) error { |
| } |
| next := l.copyLocked() |
| delete(next, name) |
| - if err := l.write(next); err != nil { |
| - return err |
| - } |
| - l.links = next |
| - return nil |
| + return l.commitLocked(next) |
| +} |
| + |
| +// commitLocked writes next and makes it the store whenever the file now |
| +// holds it: on success, and on ErrUnsynced, so memory never disagrees with |
| +// what a restart would read. |
| +func (l *Links) commitLocked(next map[string]Link) error { |
| + err := l.write(next) |
| + if err == nil || errors.Is(err, ErrUnsynced) { |
| + l.links = next |
| + } |
| + return err |
| } |
| // All returns every link, sorted by name. |
| @@ -131,7 +145,8 @@ func (l *Links) copyLocked() map[string]Link { |
| } |
| // write replaces the file with links: temp file in the same directory, fsync, |
| -// rename, then fsync the directory so the rename itself survives a crash. |
| +// rename, then fsync the directory so the rename itself survives a crash. A |
| +// failed directory sync, the one step after the rename, wraps ErrUnsynced. |
| func (l *Links) write(links map[string]Link) error { |
| f := linksFile{Links: make([]Link, 0, len(links))} |
| for _, k := range links { |
| @@ -172,9 +187,15 @@ func (l *Links) write(links map[string]Link) error { |
| os.Remove(tmpName) |
| return err |
| } |
| - return syncDir(dir) |
| + if err := syncLinksDir(dir); err != nil { |
| + return fmt.Errorf("%w: %w", ErrUnsynced, err) |
| + } |
| + return nil |
| } |
| +// syncLinksDir is syncDir; a test swaps it to fail after the rename. |
| +var syncLinksDir = syncDir |
| + |
| // syncDir fsyncs a directory. Windows cannot fsync a directory handle, so the |
| // error is tolerated there. |
| func syncDir(dir string) error { |
diff --git a/internal/devbox/links_test.go b/internal/devbox/links_test.go| index 8636cfb07..2e60b0f07 100644 |
| --- a/internal/devbox/links_test.go |
| +++ b/internal/devbox/links_test.go |
| @@ -1,9 +1,11 @@ |
| package devbox |
| import ( |
| + "errors" |
| "os" |
| "path/filepath" |
| "reflect" |
| + "syscall" |
| "testing" |
| "time" |
| ) |
| @@ -127,3 +129,94 @@ func TestLinksCorruptFileIsError(t *testing.T) { |
| t.Error("corrupt file was modified") |
| } |
| } |
| + |
| +// failLinksSync makes every links directory sync after the rename fail |
| +// until the test ends, and counts the calls. |
| +func failLinksSync(t *testing.T) *int { |
| + t.Helper() |
| + calls := 0 |
| + syncLinksDir = func(string) error { calls++; return syscall.EIO } |
| + t.Cleanup(func() { syncLinksDir = syncDir }) |
| + return &calls |
| +} |
| + |
| +// A directory sync that fails after the rename landed is ErrUnsynced, and |
| +// the store reads as updated: in memory, and from disk after a reopen. |
| +func TestLinksUnsyncedPutAndDeleteArePublished(t *testing.T) { |
| + path := filepath.Join(t.TempDir(), "links.json") |
| + l, err := OpenLinks(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := l.Put(sample("kept")); err != nil { |
| + t.Fatal(err) |
| + } |
| + calls := failLinksSync(t) |
| + |
| + err = l.Put(sample("shop")) |
| + if !errors.Is(err, ErrUnsynced) || !errors.Is(err, syscall.EIO) { |
| + t.Fatalf("Put with a failing sync = %v, want ErrUnsynced wrapping EIO", err) |
| + } |
| + if *calls != 1 { |
| + t.Fatalf("sync seam called %d times", *calls) |
| + } |
| + if _, ok := l.Get("shop"); !ok { |
| + t.Fatal("published Put not in memory") |
| + } |
| + again, err := OpenLinks(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, ok := again.Get("shop"); !ok || got != sample("shop") { |
| + t.Fatalf("reopened: %+v %v", got, ok) |
| + } |
| + |
| + if err := l.Delete("kept"); !errors.Is(err, ErrUnsynced) { |
| + t.Fatalf("Delete with a failing sync = %v", err) |
| + } |
| + if _, ok := l.Get("kept"); ok { |
| + t.Fatal("published Delete still in memory") |
| + } |
| + again, err = OpenLinks(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, ok := again.Get("kept"); ok { |
| + t.Fatal("reopened store still has the deleted link") |
| + } |
| + if !reflect.DeepEqual(again.All(), l.All()) { |
| + t.Fatalf("disk %+v, memory %+v", again.All(), l.All()) |
| + } |
| +} |
| + |
| +// A write that fails before the rename is not ErrUnsynced and changes |
| +// nothing, on disk or in memory. |
| +func TestLinksFailedWriteChangesNothing(t *testing.T) { |
| + dir := t.TempDir() |
| + path := filepath.Join(dir, "links.json") |
| + l, err := OpenLinks(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := l.Put(sample("kept")); err != nil { |
| + t.Fatal(err) |
| + } |
| + // A non-empty directory where the file should be makes the rename fail. |
| + l.path = filepath.Join(dir, "blocked") |
| + if err := os.MkdirAll(filepath.Join(l.path, "x"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + err = l.Put(sample("shop")) |
| + if err == nil || errors.Is(err, ErrUnsynced) { |
| + t.Fatalf("Put over a directory = %v, want a plain error", err) |
| + } |
| + if _, ok := l.Get("shop"); ok { |
| + t.Fatal("failed Put in memory") |
| + } |
| + if err := l.Delete("kept"); err == nil || errors.Is(err, ErrUnsynced) { |
| + t.Fatalf("Delete over a directory = %v", err) |
| + } |
| + if _, ok := l.Get("kept"); !ok { |
| + t.Fatal("failed Delete removed the link from memory") |
| + } |
| +} |
diff --git a/internal/devbox/registrar.go b/internal/devbox/registrar.go| index 57bd0563d..ef806fe4c 100644 |
| --- a/internal/devbox/registrar.go |
| +++ b/internal/devbox/registrar.go |
| @@ -118,8 +118,10 @@ type WireError struct { |
| // ListEntry is one link as share, unshare and /list report it. |
| type ListEntry struct { |
| - Name string `json:"name"` |
| - Host string `json:"host"` |
| + Name string `json:"name"` |
| + Host string `json:"host"` |
| + // Owner is the owner's username, or "" when the account is not known |
| + // on this machine (removed since it shared); OwnerUID is set either way. |
| Owner string `json:"owner"` |
| OwnerUID uint32 `json:"ownerUID"` |
| Kind Kind `json:"kind"` |
| @@ -226,8 +228,9 @@ func decodeJSON(w http.ResponseWriter, req *http.Request, v any) *refusal { |
| func (r *Registrar) host(name string) string { return name + "." + r.Domain } |
| -// owner is how a uid is shown: its username now, or "uid N" when the |
| -// account is unknown. |
| +// owner is how a refusal names a uid: its username now, or "uid N" when |
| +// the account is unknown. A ListEntry carries the parts instead (Owner and |
| +// OwnerUID), so the CLI can tell an unknown account apart. |
| func (r *Registrar) owner(uid uint32) string { |
| if r.LookupUser != nil { |
| if n := r.LookupUser(uid); n != "" { |
| @@ -245,7 +248,7 @@ func (r *Registrar) lookupName(uid uint32) string { |
| } |
| func (r *Registrar) entry(k Link) ListEntry { |
| - e := ListEntry{Name: k.Name, Host: r.host(k.Name), Owner: r.owner(k.OwnerUID), OwnerUID: k.OwnerUID, |
| + e := ListEntry{Name: k.Name, Host: r.host(k.Name), Owner: r.lookupName(k.OwnerUID), OwnerUID: k.OwnerUID, |
| Kind: k.Kind, Created: k.Created, Updated: k.Updated} |
| if k.Kind == KindLive { |
| e.Target = liveAddr(k.Port) |
| @@ -278,6 +281,11 @@ func (r *Registrar) claim(uid uint32, name string) (prev Link, had bool, ref *re |
| // restoreLink puts Links back to what claim saw. Share writes the link |
| // before the row, and its one row write is a single statement, so when a |
| // share fails the row has not changed and only the link needs undoing. |
| +// |
| +// The share's own Links write may have failed with ErrUnsynced, which means |
| +// it landed: Links then holds the new link, in memory and on disk, and this |
| +// undoes it like any other. A restore that itself ends in ErrUnsynced landed |
| +// too, which is all a rollback needs. |
| func (r *Registrar) restoreLink(name string, prev Link, had bool) { |
| var err error |
| if had { |
| @@ -290,6 +298,16 @@ func (r *Registrar) restoreLink(name string, prev Link, had bool) { |
| } |
| } |
| +// putFailed handles a share's failed Links.Put. Any error but ErrUnsynced |
| +// changed nothing. ErrUnsynced published the new link with no row behind |
| +// it, so it is undone before the share reports the failure. |
| +func (r *Registrar) putFailed(name string, prev Link, had bool, err error) *refusal { |
| + if errors.Is(err, ErrUnsynced) { |
| + r.restoreLink(name, prev, had) |
| + } |
| + return internalErr("links put", err) |
| +} |
| + |
| func (r *Registrar) serveShareLive(uid uint32, w http.ResponseWriter, req *http.Request) (any, *refusal) { |
| var in struct { |
| Name string `json:"name"` |
| @@ -317,7 +335,7 @@ func (r *Registrar) serveShareLive(uid uint32, w http.ResponseWriter, req *http. |
| link.Created = prev.Created |
| } |
| if err := r.Links.Put(link); err != nil { |
| - return nil, internalErr("links put", err) |
| + return nil, r.putFailed(in.Name, prev, had, err) |
| } |
| row := registry.Route{Host: r.host(in.Name), Kind: "service", Addr: liveAddr(in.Port), App: in.Name, Status: "ready"} |
| if err := r.Reg.UpsertUnlessRootfs(row); err != nil { |
| @@ -361,17 +379,36 @@ func (r *Registrar) serveUnshare(uid uint32, w http.ResponseWriter, req *http.Re |
| return nil, internalErr("registry delete", err) |
| } |
| if err := r.Links.Delete(in.Name); err != nil { |
| - if prevRow != nil { |
| - if rerr := r.Reg.UpsertUnlessRootfs(*prevRow); rerr != nil { |
| - log.Printf("devbox registrar: rollback row %s: %v", host, rerr) |
| - } |
| - } |
| + r.undoUnshare(in.Name, prev, prevRow, err) |
| return nil, internalErr("links delete", err) |
| } |
| r.removeSpool(in.Name) |
| return r.entry(prev), nil |
| } |
| +// undoUnshare rolls back an unshare whose Links.Delete failed after its row |
| +// was deleted. ErrUnsynced means the delete landed, so the link is put back |
| +// first. The row is restored only behind a link that is there now: a row |
| +// with no owner record is what unshare's order exists to prevent, and if |
| +// the link cannot be put back the unshare is finished instead, spool and |
| +// all, so the row and the link are gone together. |
| +func (r *Registrar) undoUnshare(name string, prev Link, prevRow *registry.Route, err error) { |
| + if errors.Is(err, ErrUnsynced) { |
| + if perr := r.Links.Put(prev); perr != nil { |
| + log.Printf("devbox registrar: rollback link %s: %v", name, perr) |
| + } |
| + } |
| + if _, ok := r.Links.Get(name); !ok { |
| + r.removeSpool(name) |
| + return |
| + } |
| + if prevRow != nil { |
| + if rerr := r.Reg.UpsertUnlessRootfs(*prevRow); rerr != nil { |
| + log.Printf("devbox registrar: rollback row %s: %v", prevRow.Host, rerr) |
| + } |
| + } |
| +} |
| + |
| func (r *Registrar) serveShareFolder(uid uint32, w http.ResponseWriter, req *http.Request) (any, *refusal) { |
| name := req.URL.Query().Get("name") |
| if ValidName(name) != nil { |
| @@ -470,8 +507,9 @@ func (r *Registrar) serveShareFolder(uid uint32, w http.ResponseWriter, req *htt |
| link.Created = prev.Created |
| } |
| if err := r.Links.Put(link); err != nil { |
| + ref := r.putFailed(name, prev, had, err) |
| discard(snapDir) |
| - return nil, internalErr("links put", err) |
| + return nil, ref |
| } |
| if published, err := swapCurrent(dir, snap); err != nil { |
| // The rename can land and the directory sync after it fail: then |
diff --git a/internal/devbox/registrar_test.go b/internal/devbox/registrar_test.go| index 9ee251c5c..4a8027e31 100644 |
| --- a/internal/devbox/registrar_test.go |
| +++ b/internal/devbox/registrar_test.go |
| @@ -14,6 +14,7 @@ import ( |
| "net/url" |
| "os" |
| "path/filepath" |
| + "reflect" |
| "runtime" |
| "sort" |
| "strings" |
| @@ -759,12 +760,15 @@ func TestListDialsConcurrently(t *testing.T) { |
| } |
| } |
| -func TestListShowsUnknownOwnerAsUID(t *testing.T) { |
| +// An account the machine no longer knows is listed as structured state: an |
| +// empty owner and the uid, never a "uid N" string. Refusals still name it |
| +// as "uid N", which the deck's owner placeholder shows as is. |
| +func TestListShowsUnknownOwnerAsEmptyWithUID(t *testing.T) { |
| f := newFixture(t) |
| f.r.LookupUser = func(uint32) string { return "" } |
| wantOK(t, f.shareLive(t, 1003, "shop", closedPort(t))) |
| got := f.list(t, 1001) |
| - if len(got) != 1 || got[0].Owner != "uid 1003" || got[0].OwnerUID != 1003 { |
| + if len(got) != 1 || got[0].Owner != "" || got[0].OwnerUID != 1003 { |
| t.Fatalf("list = %+v", got) |
| } |
| e := wantCode(t, f.shareLive(t, 1001, "shop", 8080), CodeOwned) |
| @@ -773,8 +777,16 @@ func TestListShowsUnknownOwnerAsUID(t *testing.T) { |
| } |
| // A nil LookupUser behaves the same. |
| f.r.LookupUser = nil |
| - if got := f.list(t, 1001); got[0].Owner != "uid 1003" { |
| - t.Fatalf("nil lookup owner = %q", got[0].Owner) |
| + if got := f.list(t, 1001); got[0].Owner != "" || got[0].OwnerUID != 1003 { |
| + t.Fatalf("nil lookup entry = %+v", got[0]) |
| + } |
| + // A known account is listed by name. |
| + f.r.LookupUser = func(uid uint32) string { return testUsers[uid] } |
| + wantOK(t, f.shareLive(t, 1001, "mine", closedPort(t))) |
| + for _, e := range f.list(t, 1001) { |
| + if e.Name == "mine" && (e.Owner != "ana" || e.OwnerUID != 1001) { |
| + t.Fatalf("known owner entry = %+v", e) |
| + } |
| } |
| } |
| @@ -923,23 +935,37 @@ func TestShareFolderSpoolCapCountsImplicitDirs(t *testing.T) { |
| } |
| // Many distinct directory chains, no directory headers, uploaded until |
| - // the spool refuses: usage never passes the cap. |
| + // the spool refuses: usage never passes the cap. One upload is 51 |
| + // blocks of snapshot (its dir and 10 chains of d/x/y/z/f) and admission |
| + // charges 54. Two names alternate, so after the first two uploads |
| + // (106 blocks published) every upload is a reshare that keeps the |
| + // previous tree beside the new one (R7): the third lands at 157 blocks |
| + // and the fourth at 208. The fifth would need 208+54, past the cap. |
| var hdrs []*tar.Header |
| for i := 0; i < 10; i++ { |
| hdrs = append(hdrs, &tar.Header{Name: fmt.Sprintf("d%d/x/y/z/f", i), Typeflag: tar.TypeReg, Mode: 0o644}) |
| } |
| chains := rawTar(t, hdrs...) |
| g := newFixture(t) |
| - g.r.SpoolCap = 150 * b |
| - accepted := 0 |
| + g.r.SpoolCap = 220 * b |
| + accepted, reshared := 0, 0 |
| + seen := map[string]bool{} |
| for i := 0; i < 20; i++ { |
| - name := fmt.Sprintf("s%d", i%3) // reshares too, so R7's kept trees count |
| + name := fmt.Sprintf("s%d", i%2) |
| rec := g.shareFolder(t, 1001, name, chains) |
| if rec.Code != 200 { |
| wantCode(t, rec, CodeSpoolFull) |
| break |
| } |
| accepted++ |
| + if seen[name] { |
| + reshared++ |
| + // The reshare kept the previous tree: two snapshots and current. |
| + if n := len(dirNames(t, filepath.Join(g.spool, name))); n != 3 { |
| + t.Fatalf("upload %d: %s holds %d entries, want current and two snapshots", i, name, n) |
| + } |
| + } |
| + seen[name] = true |
| used, err := spoolUsage(g.spool) |
| if err != nil { |
| t.Fatal(err) |
| @@ -948,8 +974,8 @@ func TestShareFolderSpoolCapCountsImplicitDirs(t *testing.T) { |
| t.Fatalf("upload %d: usage %d passes the cap %d", i, used, g.r.SpoolCap) |
| } |
| } |
| - if accepted == 0 { |
| - t.Fatal("nothing accepted") |
| + if accepted != 4 || reshared != 2 { |
| + t.Fatalf("accepted %d uploads with %d reshares, want 4 with 2", accepted, reshared) |
| } |
| } |
| @@ -1042,3 +1068,198 @@ func TestShareFolderLstatErrorDoesNotSpin(t *testing.T) { |
| lstatSnapshot = os.Lstat |
| wantOK(t, f.shareLive(t, 1001, "other", 8080)) |
| } |
| + |
| +// checkOwnedRoutes reopens the link store from disk, as a restarted |
| +// registrar would, and checks the invariant every failed mutation must keep: |
| +// every route under the devbox domain has an owner record, and every owner |
| +// record has its route. The store in memory must match the disk too. |
| +func checkOwnedRoutes(t *testing.T, f *fixture) *Links { |
| + t.Helper() |
| + again, err := OpenLinks(f.linksPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rows, err := f.reg.List() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + hosts := map[string]bool{} |
| + for _, rt := range rows { |
| + if strings.HasSuffix(rt.Host, "."+testDomain) { |
| + hosts[rt.Host] = true |
| + } |
| + } |
| + for _, k := range again.All() { |
| + h := k.Name + "." + testDomain |
| + if !hosts[h] { |
| + t.Fatalf("owner record %s has no route", k.Name) |
| + } |
| + delete(hosts, h) |
| + } |
| + for h := range hosts { |
| + t.Fatalf("route %s has no owner record", h) |
| + } |
| + if disk, mem := again.All(), f.r.Links.All(); !reflect.DeepEqual(disk, mem) { |
| + t.Fatalf("links on disk %+v, in memory %+v", disk, mem) |
| + } |
| + return again |
| +} |
| + |
| +// failLinksSyncOnce fails the next links directory sync after its rename, |
| +// and only that one; failLinksSync (links_test.go) fails every one. |
| +func failLinksSyncOnce(t *testing.T) *int { |
| + t.Helper() |
| + calls := 0 |
| + syncLinksDir = func(dir string) error { |
| + calls++ |
| + if calls == 1 { |
| + return syscall.EIO |
| + } |
| + return syncDir(dir) |
| + } |
| + t.Cleanup(func() { syncLinksDir = syncDir }) |
| + return &calls |
| +} |
| + |
| +// A share whose links write lands but whose directory sync fails is rolled |
| +// back on disk, not only in memory: after a restart there is no owner |
| +// record without its route, whether the sync fails once or keeps failing |
| +// through the rollback. |
| +func TestShareRollsBackUnsyncedLink(t *testing.T) { |
| + for _, mode := range []string{"once", "always"} { |
| + t.Run(mode, func(t *testing.T) { |
| + f := newFixture(t) |
| + wantOK(t, f.shareLive(t, 1001, "live", 5173)) |
| + wantOK(t, f.shareFolder(t, 1001, "site", packSite(t, map[string]string{"index.html": "one"}))) |
| + live0, _ := f.r.Links.Get("live") |
| + site0, _ := f.r.Links.Get("site") |
| + var calls *int |
| + if mode == "once" { |
| + calls = failLinksSyncOnce(t) |
| + } else { |
| + calls = failLinksSync(t) |
| + } |
| + // rearm zeroes the count, so in "once" mode the next operation's |
| + // first sync fails again. |
| + rearm := func() { *calls = 0 } |
| + |
| + // First shares: no record and no row survive. |
| + wantCode(t, f.shareLive(t, 1001, "fresh", 6000), CodeInternal) |
| + if *calls < 2 { |
| + t.Fatalf("sync seam called %d times; the rollback did not write", *calls) |
| + } |
| + rearm() |
| + wantCode(t, f.shareFolder(t, 1001, "page", packSite(t, map[string]string{"index.html": "x"})), CodeInternal) |
| + rearm() |
| + // Reshares: the earlier record and row survive, unchanged. |
| + wantCode(t, f.shareLive(t, 1001, "live", 6000), CodeInternal) |
| + rearm() |
| + wantCode(t, f.shareFolder(t, 1001, "site", packSite(t, map[string]string{"index.html": "two"})), CodeInternal) |
| + |
| + again := checkOwnedRoutes(t, f) |
| + for _, n := range []string{"fresh", "page"} { |
| + if _, ok := again.Get(n); ok { |
| + t.Fatalf("%s: record left on disk", n) |
| + } |
| + } |
| + if _, err := os.Lstat(filepath.Join(f.spool, "page")); !os.IsNotExist(err) { |
| + t.Fatalf("page: spool dir left: %v", err) |
| + } |
| + if k, _ := again.Get("live"); k != live0 { |
| + t.Fatalf("live on disk %+v, want %+v", k, live0) |
| + } |
| + if k, _ := again.Get("site"); k != site0 { |
| + t.Fatalf("site on disk %+v, want %+v", k, site0) |
| + } |
| + if rt := f.row(t, "live"); rt.Addr != liveAddr(5173) { |
| + t.Fatalf("live row %+v", rt) |
| + } |
| + if got := readCurrent(t, f.spool, "site", "index.html"); got != "one" { |
| + t.Fatalf("site current = %q", got) |
| + } |
| + |
| + // Once the disk behaves, the names work as before: free ones are |
| + // free, and the owner still owns the rest. |
| + syncLinksDir = syncDir |
| + wantOK(t, f.shareLive(t, 1002, "fresh", 6000)) |
| + wantOK(t, f.shareFolder(t, 1002, "page", packSite(t, map[string]string{"index.html": "x"}))) |
| + wantCode(t, f.shareLive(t, 1002, "live", 6000), CodeOwned) |
| + wantOK(t, f.unshare(t, 1001, "site")) |
| + checkOwnedRoutes(t, f) |
| + }) |
| + } |
| +} |
| + |
| +// An unshare whose links delete lands but whose directory sync fails puts |
| +// the record back and then the row, so the owner still owns a link that |
| +// serves and can unshare it again. |
| +func TestUnshareRollsBackUnsyncedLink(t *testing.T) { |
| + for _, mode := range []string{"once", "always"} { |
| + t.Run(mode, func(t *testing.T) { |
| + f := newFixture(t) |
| + wantOK(t, f.shareLive(t, 1001, "shop", 5173)) |
| + wantOK(t, f.shareFolder(t, 1001, "site", packSite(t, map[string]string{"index.html": "one"}))) |
| + shop0, _ := f.r.Links.Get("shop") |
| + if mode == "once" { |
| + failLinksSyncOnce(t) |
| + } else { |
| + failLinksSync(t) |
| + } |
| + wantCode(t, f.unshare(t, 1001, "shop"), CodeInternal) |
| + if mode == "once" { |
| + failLinksSyncOnce(t) |
| + } |
| + wantCode(t, f.unshare(t, 1001, "site"), CodeInternal) |
| + |
| + again := checkOwnedRoutes(t, f) |
| + if k, _ := again.Get("shop"); k != shop0 { |
| + t.Fatalf("shop on disk %+v, want %+v", k, shop0) |
| + } |
| + if rt := f.row(t, "shop"); rt == nil || rt.Addr != liveAddr(5173) { |
| + t.Fatalf("shop row %+v", rt) |
| + } |
| + if got := readCurrent(t, f.spool, "site", "index.html"); got != "one" { |
| + t.Fatalf("site current = %q", got) |
| + } |
| + |
| + syncLinksDir = syncDir |
| + wantCode(t, f.unshare(t, 1002, "shop"), CodeNotYours) |
| + wantOK(t, f.unshare(t, 1001, "shop")) |
| + wantOK(t, f.unshare(t, 1001, "site")) |
| + checkOwnedRoutes(t, f) |
| + if f.row(t, "shop") != nil || f.row(t, "site") != nil { |
| + t.Fatal("rows left after unshare") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// When the record cannot be put back after an unsynced delete, the unshare |
| +// is finished instead: the row stays deleted and the spool goes, so no |
| +// route is left without an owner. |
| +func TestUnshareFinishesWhenRecordCannotReturn(t *testing.T) { |
| + f := newFixture(t) |
| + wantOK(t, f.shareFolder(t, 1001, "site", packSite(t, map[string]string{"index.html": "one"}))) |
| + path := f.r.Links.path |
| + blocked := filepath.Join(t.TempDir(), "blocked") |
| + if err := os.MkdirAll(filepath.Join(blocked, "x"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + // The delete's rename lands and its sync fails; from then on every |
| + // rename fails, so the record cannot be put back. |
| + syncLinksDir = func(string) error { |
| + f.r.Links.path = blocked |
| + return syscall.EIO |
| + } |
| + t.Cleanup(func() { syncLinksDir = syncDir }) |
| + wantCode(t, f.unshare(t, 1001, "site"), CodeInternal) |
| + f.r.Links.path = path |
| + |
| + checkOwnedRoutes(t, f) |
| + if f.row(t, "site") != nil { |
| + t.Fatal("row restored with no owner record behind it") |
| + } |
| + if _, err := os.Lstat(filepath.Join(f.spool, "site")); !os.IsNotExist(err) { |
| + t.Fatalf("spool dir left: %v", err) |
| + } |
| +} |