diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index 6886570398..50e2498a81 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -47,6 +47,7 @@ const ( snapsDir = "snaps" extReq = "swb.req" + extAttempt = "swb.attempt" // the id of the intent of the attempt that wrote the entry extSnapGen = "swb.snap.gen" extSnapEpoch = "swb.snap.epoch" extSnapLSN = "swb.snap.lsn" @@ -497,57 +498,49 @@ func decodeSnap(p string, e *filerpb.Entry) (SnapshotInfo, string, error) { }, doc.RequestID, nil } -// settleIntents removes every intent under root that operation tag wrote: -// those of this attempt and of earlier ones whose outcome it has now -// settled. A failure leaves intents behind, which only over-protects. -func (c *Catalog) settleIntents(ctx context.Context, root, tag string) { - ctx = context.WithoutCancel(ctx) - dir := path.Join(root, intentsDir) - after := "" - for { - page, err := c.f.ListEntries(ctx, dir, "", after, listPage) - if err != nil { - return - } - for _, e := range page { - after = e.GetName() - if string(e.Extended[extHolder]) == tag { - _ = c.f.DeleteEntry(ctx, dir, e.GetName(), nil) - } - } - if len(page) < listPage { - return - } - } +// dropIntent deletes one attempt's own intent, once that attempt's create +// is confirmed or can never apply. It never touches another attempt's +// intent, even under the same operation: an earlier attempt's create may +// still be held by the server and land later (W5 rule). A failed delete +// leaves the intent, which only over-protects. +func (c *Catalog) dropIntent(ctx context.Context, root, id string) { + _ = c.f.DeleteEntry(context.WithoutCancel(ctx), path.Join(root, intentsDir), id, nil) } type createOutcome int const ( - createdNow createOutcome = iota // this call's create applied (confirmed) - existsOurs // the entry exists and is this operation's - existsOther // another entry holds the name: our create can never land - createUnknown // the create's outcome is not known + createdNow createOutcome = iota // this attempt's create applied (confirmed) + createRefused // the filer refused it (the name exists): it will never apply + createUnsettled // no answer: it may still apply, even later ) -// createResolved makes an exclusive create and resolves its outcome against -// the operation's identity (ours) by re-reading the entry on any failure. -// Only a re-read that finds the entry settles an ambiguous failure; a -// failed re-read, or not finding it, leaves the outcome unknown (the create -// may still land later). -func (c *Catalog) createResolved(ctx context.Context, dir string, e *filerpb.Entry, ours func(*filerpb.Entry) bool) (createOutcome, error) { +// createResolved makes this attempt's exclusive create of e under dir and +// returns its outcome and the entry now under the name (nil if unread). +// attempt, when not empty, is stored in e as extAttempt; a re-read that +// finds it confirms this attempt's create. Only the filer's own "already +// exists" answer settles a failure as refused; any other failure leaves +// the create unsettled, whatever entry the re-read finds (that entry may +// be another attempt's, and this one may still land after it is gone). +func (c *Catalog) createResolved(ctx context.Context, dir string, e *filerpb.Entry, attempt string) (createOutcome, *filerpb.Entry, error) { + if attempt != "" { + e.Extended[extAttempt] = []byte(attempt) + } err := c.f.CreateEntry(ctx, dir, e, true) if err == nil { - return createdNow, nil + return createdNow, e, nil } got, lerr := c.f.LookupEntry(ctx, dir, e.GetName()) if lerr != nil { - return createUnknown, err + got = nil } - if ours(got) { - return existsOurs, nil + if got != nil && attempt != "" && string(got.Extended[extAttempt]) == attempt { + return createdNow, got, nil } - return existsOther, nil + if errors.Is(err, ErrExists) { + return createRefused, got, err + } + return createUnsettled, got, err } func headDigest(h storage.ChunkHead) (string, error) { @@ -602,7 +595,6 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe } if existing, prev, _, err := c.readSnap(ctx, vol, req.Name); err == nil { if prev == req.RequestID { - c.settleIntents(ctx, root, "snapshot:"+vol+"/"+req.Name+"/"+req.RequestID) existing.Replayed = true return existing, nil } @@ -651,25 +643,34 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe } if c.now().Sub(readAt) > c.deadline() { // Clean abort: the snapshot entry was never sent. - _ = c.f.DeleteEntry(context.WithoutCancel(ctx), path.Join(root, intentsDir), id, nil) + c.dropIntent(ctx, root, id) return SnapshotInfo{}, catErr(CodeDeadlineExceeded, true, nil, "snapshot %s/%s: %v since the cut, over the %v deadline; nothing written", vol, req.Name, c.now().Sub(readAt), c.deadline()) } dir := path.Join(root, snapsDir) - ours := func(got *filerpb.Entry) bool { return string(got.Extended[extReq]) == req.RequestID } - outcome, cerr := c.createResolved(ctx, dir, e, ours) - switch outcome { - case createUnknown: + outcome, got, cerr := c.createResolved(ctx, dir, e, id) + if outcome != createUnsettled { + c.dropIntent(ctx, root, id) // confirmed, or refused for good + } + if outcome == createdNow { + info, _, _, err := c.readSnap(ctx, vol, req.Name) + return info, err + } + // Not this attempt's entry. When unsettled, its intent stays: this + // create may still land after the entry found here is removed. + if got == nil && outcome == createUnsettled { return SnapshotInfo{}, catErr(CodeOutcomeUnknown, true, cerr, "snapshot %s/%s: create outcome unknown; its intent is kept, retry with the same request id", vol, req.Name) - case existsOther: - c.settleIntents(ctx, root, tag) // our exclusive create can never land + } + if got == nil { + return SnapshotInfo{}, remoteErr(cerr, "snapshot %s/%s exists but could not be read; retry with the same request id", vol, req.Name) + } + if string(got.Extended[extReq]) != req.RequestID { return SnapshotInfo{}, catErr(CodeSnapshotExists, false, nil, "snapshot %s/%s exists (another request)", vol, req.Name) } - c.settleIntents(ctx, root, tag) // confirmed published - info, _, _, err := c.readSnap(ctx, vol, req.Name) + info, _, err := decodeSnap(path.Join(dir, req.Name), got) if err != nil { return SnapshotInfo{}, err } - info.Replayed = outcome == existsOurs && errors.Is(cerr, ErrExists) + info.Replayed = true // another attempt of this request wrote it return info, nil } @@ -799,8 +800,10 @@ func (c *Catalog) ListVolumes(ctx context.Context) ([]string, error) { // the snapshot's remote_lsn (LSNs carry forward). // // The HEAD write is refused once OpDeadline has passed since step 1. An -// uncertain outcome of step 2 or 4 is outcome_unknown and keeps the intent; -// a retry with the same request id settles it. +// uncertain outcome of step 2 or 4 is outcome_unknown; a retry with the same +// request id completes the fork. An attempt whose HEAD create stays +// unsettled keeps its own intent (that create may still land); no attempt +// or replay deletes another attempt's intent. func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) { if _, err := c.volRoot(req.Source); err != nil { return ForkResult{}, err @@ -837,7 +840,6 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) return ForkResult{}, remoteErr(err, "read HEAD of %s", req.Target) } if has { - c.settleIntents(ctx, dstRoot, tag) return forkResult(existing, true), nil } } @@ -884,15 +886,17 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) if err != nil { return ForkResult{}, err } - outcome, cerr := c.createResolved(ctx, dstRoot, ve, func(got *filerpb.Entry) bool { + // VOLUME names no chunk keys, so it needs no intent; a found VOLUME + // is this request's when it binds the same request and image. + outcome, got, cerr := c.createResolved(ctx, dstRoot, ve, "") + if outcome != createdNow { + if got == nil { + return ForkResult{}, catErr(CodeOutcomeUnknown, true, cerr, "fork %s: VOLUME create outcome unknown; retry with the same request id", req.Target) + } v, err := decodeVolume(path.Join(dstRoot, volumeName), got) - return err == nil && c.checkForkRecord(v, req) == nil && v.Fork.HeadSHA256 == digest - }) - switch outcome { - case createUnknown: - return ForkResult{}, catErr(CodeOutcomeUnknown, true, cerr, "fork %s: VOLUME create outcome unknown; retry with the same request id", req.Target) - case existsOther: - return ForkResult{}, catErr(CodeTargetExists, false, nil, "volume %s exists (another request, or another image)", req.Target) + if err != nil || c.checkForkRecord(v, req) != nil || v.Fork.HeadSHA256 != digest { + return ForkResult{}, catErr(CodeTargetExists, false, nil, "volume %s exists (another request, or another image)", req.Target) + } } existing = vol } @@ -908,17 +912,21 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) } if c.now().Sub(readAt) > c.deadline() { // Clean abort: HEAD was never sent. - _ = c.f.DeleteEntry(context.WithoutCancel(ctx), path.Join(dstRoot, intentsDir), id, nil) + c.dropIntent(ctx, dstRoot, id) return ForkResult{}, catErr(CodeDeadlineExceeded, true, nil, "fork %s: %v since reading the snapshot, over the %v deadline; HEAD not written", req.Target, c.now().Sub(readAt), c.deadline()) } - // Under this request's VOLUME only this fork ever writes HEAD (attach - // refuses a fork without HEAD), so any HEAD found there is ours. - outcome, cerr := c.createResolved(ctx, dstRoot, he, func(*filerpb.Entry) bool { return true }) - if outcome == createUnknown { + // Under this request's VOLUME only this request's attempts write HEAD + // (attach refuses a fork without HEAD), so a HEAD found there completes + // the fork; if it is another attempt's and this create is unsettled, + // this attempt's intent stays (the create may land after HEAD is gone). + outcome, got, cerr := c.createResolved(ctx, dstRoot, he, id) + if outcome != createUnsettled { + c.dropIntent(ctx, dstRoot, id) // confirmed, or refused for good + } + if outcome == createUnsettled && got == nil { return ForkResult{}, catErr(CodeOutcomeUnknown, true, cerr, "fork %s: HEAD create outcome unknown; its intent is kept, retry with the same request id", req.Target) } - c.settleIntents(ctx, dstRoot, tag) - return forkResult(existing, outcome == existsOurs && errors.Is(cerr, ErrExists)), nil + return forkResult(existing, outcome != createdNow), nil // refused: the filer says HEAD exists } // checkForkRecord refuses a target VOLUME that is not this fork request's. diff --git a/seaweed-block/core/frontend/chunkstore/catalog_held_create_test.go b/seaweed-block/core/frontend/chunkstore/catalog_held_create_test.go new file mode 100644 index 0000000000..275863f173 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/catalog_held_create_test.go @@ -0,0 +1,266 @@ +package chunkstore + +import ( + "context" + "path" + "testing" + + "google.golang.org/protobuf/proto" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" +) + +// Schedules where the filer holds an attempt's create and runs it after the +// attempt has returned (second review of #111, P1). The rule (W5): an +// attempt deletes only its own intent, and only once its own create is +// confirmed or can never apply; never another attempt's, even under the same +// request, since that attempt's create may still land. + +// holdFirst makes the filer hold the first create of p. +func holdFirst(f *fakeFiler, p string) { + held := false + f.deferCreate = func(q string, _ *filerpb.Entry) bool { + if q != p || held { + return false + } + held = true + return true + } +} + +// holdFirstBehindAnother holds the first create of p and, in the same +// moment, lets another attempt of the same request write p (a copy of the +// held entry stamped with another attempt id). +func holdFirstBehindAnother(f *fakeFiler, p string) { + held := false + f.deferCreate = func(q string, e *filerpb.Entry) bool { + if q != p || held { + return false + } + held = true + other := proto.Clone(e).(*filerpb.Entry) + other.Extended["swb.attempt"] = []byte("0-00000000000000ff") + f.entries[q] = other + return true + } +} + +// gcRemove removes an entry, as GC does after a delete. +func gcRemove(f *fakeFiler, p string) { + f.mu.Lock() + delete(f.entries, p) + f.mu.Unlock() +} + +// assertKeysProtected fails unless every key is named by an intent of vol. +func assertKeysProtected(t *testing.T, f *fakeFiler, vol string, keys []string) { + t.Helper() + named := map[string]bool{} + for _, in := range intentsOf(t, f, vol) { + for _, k := range in.Keys { + named[k] = true + } + } + for _, k := range keys { + if !named[k] { + t.Fatalf("key %s of the late entry is named by no intent of %s: GC may delete it", k, vol) + } + } +} + +func lateSnapshotKeys(t *testing.T, f *fakeFiler, vol, name string) []string { + t.Helper() + dir := path.Join(catBase, vol, snapsDir) + e, err := f.LookupEntry(context.Background(), dir, name) + if err != nil { + t.Fatalf("the held create did not land: %v", err) + } + info, _, err := decodeSnap(path.Join(dir, name), e) + if err != nil { + t.Fatal(err) + } + return sortedKeysOf(info.Head(), "") +} + +func lateHeadKeys(t *testing.T, f *fakeFiler, b *fakeBlobs, vol string) []string { + t.Helper() + r, _ := NewChunkRemote(f, b, path.Join(catBase, vol)) + h, err := r.GetHead(context.Background()) + if err != nil { + t.Fatalf("the held HEAD create did not land: %v", err) + } + return sortedKeysOf(h, "") +} + +// Attempt A's snapshot create is held; retry B of the same request publishes +// the snapshot and deletes only B's intent. The snapshot is deleted and GC +// removes it; then A's held create lands. Its keys are still protected by +// A's intent. +func TestCatalog_HeldSnapshotCreateKeepsItsIntent(t *testing.T) { + f, _, c, h := catalogFixture(t) + ctx := context.Background() + p := catBase + "/v1/snaps/s1" + holdFirst(f, p) + req := SnapshotRequest{Name: "s1", RequestID: "r"} + if _, err := c.CreateSnapshot(ctx, "v1", req, h); CodeOf(err) != CodeOutcomeUnknown { + t.Fatalf("attempt A, create held: %v, want outcome_unknown", err) + } + a := intentsOf(t, f, "v1") + if len(a) != 1 { + t.Fatalf("attempt A left %d intents, want its own", len(a)) + } + if info, err := c.CreateSnapshot(ctx, "v1", req, h); err != nil || info.Replayed { + t.Fatalf("retry B: %+v %v", info, err) + } + if in := intentsOf(t, f, "v1"); len(in) != 1 || in[0].ID != a[0].ID { + t.Fatalf("after B: intents %+v, want only A's %s (A's create is still held)", in, a[0].ID) + } + if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { + t.Fatal(err) + } + gcRemove(f, p) + if n := f.releaseDeferredCreates(); n != 1 { + t.Fatalf("A's held create applied %d times, want 1", n) + } + assertKeysProtected(t, f, "v1", lateSnapshotKeys(t, f, "v1", "s1")) +} + +// Attempt A's create is held while another attempt of the same request +// writes the snapshot. A reports the snapshot but keeps its own intent; when +// the snapshot is later removed, A's create lands with its keys protected. +func TestCatalog_HeldSnapshotCreateBehindAnotherAttempt(t *testing.T) { + f, _, c, h := catalogFixture(t) + ctx := context.Background() + p := catBase + "/v1/snaps/s1" + holdFirstBehindAnother(f, p) + info, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h) + if in := intentsOf(t, f, "v1"); len(in) != 1 { + t.Fatalf("attempt A (err %v) left %d intents; its held create needs its own", err, len(in)) + } + if err != nil || !info.Replayed || info.HeadGen != h.Gen { + t.Fatalf("attempt A behind another attempt: %+v %v, want the replayed snapshot", info, err) + } + if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { + t.Fatal(err) + } + gcRemove(f, p) + if n := f.releaseDeferredCreates(); n != 1 { + t.Fatalf("A's held create applied %d times, want 1", n) + } + assertKeysProtected(t, f, "v1", lateSnapshotKeys(t, f, "v1", "s1")) +} + +// The filer's own "already exists" answer refuses the create for good: the +// attempt deletes its own intent and leaks none. +func TestCatalog_RefusedSnapshotCreateDropsItsIntent(t *testing.T) { + f, _, c, h := catalogFixture(t) + ctx := context.Background() + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "other"}, h); err != nil { + t.Fatal(err) + } + // The name is taken after this request's read and before its create. + taken := f.entries[catBase+"/v1/snaps/s1"] + gcRemove(f, catBase+"/v1/snaps/s1") + f.beforeCreate = func(p string) { + if path.Dir(p) == catBase+"/v1/intents" { + f.entries[catBase+"/v1/snaps/s1"] = taken + } + } + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); CodeOf(err) != CodeSnapshotExists { + t.Fatalf("refused create: %v, want snapshot_exists", err) + } + if in := intentsOf(t, f, "v1"); len(in) != 0 { + t.Fatalf("a refused create left %d intents", len(in)) + } +} + +// Fork: attempt A's HEAD create is held; retry B completes the fork and +// deletes only B's intent; a replay C deletes none. The target's HEAD is +// later removed; A's held create lands with its qualified keys protected. +func TestFork_HeldHeadCreateKeepsItsIntent(t *testing.T) { + f, b, c, h := catalogFixture(t) + ctx := context.Background() + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + p := catBase + "/v2/HEAD" + holdFirst(f, p) + req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"} + if _, err := c.Fork(ctx, req); CodeOf(err) != CodeOutcomeUnknown { + t.Fatalf("attempt A, HEAD create held: %v, want outcome_unknown", err) + } + a := intentsOf(t, f, "v2") + if len(a) != 1 { + t.Fatalf("attempt A left %d intents, want its own", len(a)) + } + if res, err := c.Fork(ctx, req); err != nil || res.Replayed { + t.Fatalf("retry B: %+v %v", res, err) + } + if res, err := c.Fork(ctx, req); err != nil || !res.Replayed { + t.Fatalf("replay C: %+v %v", res, err) + } + if in := intentsOf(t, f, "v2"); len(in) != 1 || in[0].ID != a[0].ID { + t.Fatalf("after B and C: intents %+v, want only A's %s (A's HEAD create is still held)", in, a[0].ID) + } + gcRemove(f, p) + if n := f.releaseDeferredCreates(); n != 1 { + t.Fatalf("A's held HEAD create applied %d times, want 1", n) + } + assertKeysProtected(t, f, "v2", lateHeadKeys(t, f, b, "v2")) +} + +// Fork: attempt A's HEAD create is held while another attempt writes HEAD. +// A reports the completed fork and keeps its own intent. +func TestFork_HeldHeadCreateBehindAnotherAttempt(t *testing.T) { + f, b, c, h := catalogFixture(t) + ctx := context.Background() + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + p := catBase + "/v2/HEAD" + holdFirstBehindAnother(f, p) + res, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}) + if in := intentsOf(t, f, "v2"); len(in) != 1 { + t.Fatalf("attempt A (err %v) left %d intents; its held create needs its own", err, len(in)) + } + if err != nil || !res.Replayed || res.HeadGen != 1 { + t.Fatalf("attempt A behind another attempt: %+v %v, want the completed fork", res, err) + } + gcRemove(f, p) + if n := f.releaseDeferredCreates(); n != 1 { + t.Fatalf("A's held HEAD create applied %d times, want 1", n) + } + assertKeysProtected(t, f, "v2", lateHeadKeys(t, f, b, "v2")) +} + +// The filer's "already exists" answer to a fork's HEAD create: HEAD is there +// (only this request writes it), so the fork is complete and the attempt +// deletes its own intent. +func TestFork_RefusedHeadCreateDropsItsIntent(t *testing.T) { + f, _, c, h := catalogFixture(t) + ctx := context.Background() + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"} + if _, err := c.Fork(ctx, req); err != nil { + t.Fatal(err) + } + // HEAD is written by another attempt after this attempt finds it absent + // and before this attempt's create. + p := catBase + "/v2/HEAD" + head := f.entries[p] + gcRemove(f, p) + f.beforeCreate = func(q string) { + if path.Dir(q) == catBase+"/v2/intents" { + f.entries[p] = head + } + } + res, err := c.Fork(ctx, req) + if err != nil || !res.Replayed || res.HeadGen != 1 { + t.Fatalf("refused HEAD create: %+v %v, want the completed fork", res, err) + } + if in := intentsOf(t, f, "v2"); len(in) != 0 { + t.Fatalf("a refused HEAD create left %d intents", len(in)) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go b/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go index b5030f6c79..82e4702d54 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go @@ -45,8 +45,10 @@ func sameStrings(a, b []string) bool { } // An uncertain snapshot create keeps the intent that protects the -// snapshot's keys; a retry with the same request id settles it and removes -// every intent of the operation (review of #111, P1). +// snapshot's keys (review of #111, P1). A retry with the same +// request id publishes the snapshot and deletes only its own intent: from +// the catalog's view the first create may still land, so its intent stays +// (W5 rule; second review). func TestCatalog_SnapshotUncertainCreateKeepsIntent(t *testing.T) { f, _, c, h := catalogFixture(t) ctx := context.Background() @@ -68,8 +70,8 @@ func TestCatalog_SnapshotUncertainCreateKeepsIntent(t *testing.T) { if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { t.Fatalf("retry: %v", err) } - if in := intentsOf(t, f, "v1"); len(in) != 0 { - t.Fatalf("a settled snapshot left %d intents", len(in)) + if got := intentsOf(t, f, "v1"); len(got) != 1 || got[0].ID != in[0].ID { + t.Fatalf("after the retry: intents %+v, want only the first attempt's %s", got, in[0].ID) } } @@ -118,8 +120,8 @@ func TestFork_UncertainHeadCreateKeepsIntent(t *testing.T) { if err != nil || res.Replayed { t.Fatalf("retry: %+v %v", res, err) } - if in := intentsOf(t, f, "v2"); len(in) != 0 { - t.Fatalf("a settled fork left %d intents", len(in)) + if got := intentsOf(t, f, "v2"); len(got) != 1 || got[0].ID != in[0].ID { + t.Fatalf("after the retry: intents %+v, want only the first attempt's %s", got, in[0].ID) } // Applied, response lost: confirmed by the re-read. diff --git a/seaweed-block/core/frontend/chunkstore/fake_test.go b/seaweed-block/core/frontend/chunkstore/fake_test.go index 86b563c492..a9286fb823 100644 --- a/seaweed-block/core/frontend/chunkstore/fake_test.go +++ b/seaweed-block/core/frontend/chunkstore/fake_test.go @@ -42,6 +42,14 @@ type fakeFiler struct { // failCreateAfterApply, if set, is called after a create was applied; a // non-nil return is reported to the caller (applied, response lost). failCreateAfterApply func(p string) error + // deferCreate, if set and true for a create, makes the server retain + // it (not applied yet) and return an error; releaseDeferredCreates + // applies retained creates later, each only if its name is still free + // (exclusive create, evaluated when the server finally runs it). It + // runs under the lock and may read or change f.entries (e is the + // caller's entry: read it, do not keep it). + deferCreate func(p string, e *filerpb.Entry) bool + deferredCreates []deferredCreate } func newFakeFiler() *fakeFiler { return &fakeFiler{entries: map[string]*filerpb.Entry{}} } @@ -71,6 +79,10 @@ func (f *fakeFiler) CreateEntry(_ context.Context, dir string, e *filerpb.Entry, return err } } + if f.deferCreate != nil && f.deferCreate(p, e) { + f.deferredCreates = append(f.deferredCreates, deferredCreate{p: p, e: proto.Clone(e).(*filerpb.Entry)}) + return errors.New("fake: create retained by the server") + } c := proto.Clone(e).(*filerpb.Entry) f.entries[p] = c f.written = append(f.written, proto.Clone(e).(*filerpb.Entry)) @@ -157,6 +169,29 @@ func (f *fakeFiler) DeleteEntry(_ context.Context, dir, name string, expected ma return nil } +type deferredCreate struct { + p string + e *filerpb.Entry +} + +// releaseDeferredCreates lets the server finish retained creates; it returns +// how many applied (a name that is taken by then is not overwritten). +func (f *fakeFiler) releaseDeferredCreates() int { + f.mu.Lock() + defer f.mu.Unlock() + applied := 0 + for _, d := range f.deferredCreates { + if _, taken := f.entries[d.p]; taken { + continue + } + f.entries[d.p] = d.e + f.written = append(f.written, proto.Clone(d.e).(*filerpb.Entry)) + applied++ + } + f.deferredCreates = nil + return applied +} + // bumpExtended mutates a stored entry's extended key, as another writer would. func (f *fakeFiler) bumpExtended(p, key, val string) { f.mu.Lock()