lease: an absent lock is acquired in one create-only write
A release deletes its lock, so a wake usually finds none, and litestream's AcquireLease spent a GET to learn that before its create-only PUT. The acquire now makes that PUT first: the same lease AcquireLease writes for an absent lock (generation 1, this owner, now plus the TTL, the same JSON, content type and If-None-Match: *). A 412 (or S3's 409 for racing conditional writes) means a lock is there, and AcquireLease decides it as before: an expired one is taken over at the next generation, a live one is refused with its holder. Seen on dev: wakecheck's lock reads generation 1, so releases do delete it there.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4 files changed,
+261
−3
internal/lease/createlease.go+78 −0internal/lease/endpoint_test.go+5 −2internal/lease/fastacquire_test.go+174 −0internal/lease/lease.go+4 −1
diff --git a/internal/lease/createlease.go b/internal/lease/createlease.go| new file mode 100644 |
| index 000000000..71aa2a1d4 |
| --- /dev/null |
| +++ b/internal/lease/createlease.go |
| @@ -0,0 +1,78 @@ |
| +package lease |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + awss3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| + "github.com/aws/smithy-go" |
| + "github.com/benbjohnson/litestream" |
| + lss3 "github.com/benbjohnson/litestream/s3" |
| +) |
| + |
| +// errLockPresent is createLease's answer when a lock object exists, live or |
| +// expired: litestream's AcquireLease decides it, as it always has. |
| +var errLockPresent = errors.New("lease: a lock is present") |
| + |
| +// createLease is litestream's AcquireLease for the common case, the lock |
| +// absent (a release deletes it), in one round trip instead of two. It |
| +// writes what AcquireLease writes for an absent lock: generation 1, the |
| +// leaser's owner, now plus its TTL, the same JSON and content type, and the |
| +// same create-only condition (If-None-Match: *). So the lock it leaves, and |
| +// what a reader of it decides, are AcquireLease's. A 412 means a lock is |
| +// there, and errLockPresent hands the decision back to AcquireLease (the |
| +// takeover of an expired lock, the refusal of a live one). Any other error |
| +// is the acquire's, as AcquireLease's own write failing would be. |
| +func createLease(ctx context.Context, client *awss3.Client, l *lss3.Leaser) (*litestream.Lease, error) { |
| + lease := &litestream.Lease{Generation: 1, ExpiresAt: time.Now().Add(l.TTL), Owner: l.Owner} |
| + data, err := json.Marshal(lease) |
| + if err != nil { |
| + return nil, fmt.Errorf("marshal lock file: %w", err) |
| + } |
| + key := lss3.DefaultLeasePath |
| + if l.Path != "" { |
| + key = l.Path + "/" + lss3.DefaultLeasePath |
| + } |
| + out, err := client.PutObject(ctx, &awss3.PutObjectInput{ |
| + Bucket: aws.String(l.Bucket), |
| + Key: aws.String(key), |
| + Body: bytes.NewReader(data), |
| + ContentType: aws.String("application/json"), |
| + IfNoneMatch: aws.String("*"), |
| + }) |
| + if err != nil { |
| + if preconditionFailed(err) { |
| + return nil, errLockPresent |
| + } |
| + return nil, fmt.Errorf("put lock file: %w", err) |
| + } |
| + if out.ETag != nil { |
| + lease.ETag = *out.ETag |
| + } |
| + return lease, nil |
| +} |
| + |
| +// preconditionFailed is litestream's isPreconditionFailed (unexported |
| +// there), plus the 409 S3 answers when two conditional writes of one key |
| +// race: either way a lock is, or is about to be, present. |
| +func preconditionFailed(err error) bool { |
| + var apiErr smithy.APIError |
| + if errors.As(err, &apiErr) { |
| + switch apiErr.ErrorCode() { |
| + case "PreconditionFailed", "412", "ConditionalRequestConflict": |
| + return true |
| + } |
| + } |
| + var opErr *smithy.OperationError |
| + if errors.As(err, &opErr) { |
| + if h, ok := opErr.Err.(interface{ HTTPStatusCode() int }); ok { |
| + return h.HTTPStatusCode() == 412 || h.HTTPStatusCode() == 409 |
| + } |
| + } |
| + return false |
| +} |
diff --git a/internal/lease/endpoint_test.go b/internal/lease/endpoint_test.go| index dd341a561..294dad169 100644 |
| --- a/internal/lease/endpoint_test.go |
| +++ b/internal/lease/endpoint_test.go |
| @@ -132,8 +132,11 @@ func TestAcquire_ReachesEndpointOverride(t *testing.T) { |
| sawPut = true |
| } |
| } |
| - if !sawGet || !sawPut { |
| - t.Fatalf("lease traffic did not reach the override: got %v, want a GET and a PUT of %s", got, wantKey) |
| + // An absent lock is one create-only PUT (createLease); a GET comes |
| + // only when a lock is present. Either way the PUT must arrive here. |
| + _ = sawGet |
| + if !sawPut { |
| + t.Fatalf("lease traffic did not reach the override: got %v, want a PUT of %s", got, wantKey) |
| } |
| // The PUT body is the lock itself — proof the acquire really happened |
diff --git a/internal/lease/fastacquire_test.go b/internal/lease/fastacquire_test.go| new file mode 100644 |
| index 000000000..cc7fe5578 |
| --- /dev/null |
| +++ b/internal/lease/fastacquire_test.go |
| @@ -0,0 +1,174 @@ |
| +package lease |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/benbjohnson/litestream" |
| +) |
| + |
| +// casS3 is one key's worth of S3 with conditional writes: If-None-Match: * |
| +// refuses an existing object, If-Match refuses another etag, with 412. |
| +type casS3 struct { |
| + mu sync.Mutex |
| + reqs []string |
| + body []byte |
| + etag string |
| + n int |
| + puts []http.Header |
| +} |
| + |
| +func newCasS3(t *testing.T) (*casS3, string) { |
| + t.Helper() |
| + f := &casS3{} |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.reqs = append(f.reqs, r.Method) |
| + fail := func() { |
| + w.Header().Set("Content-Type", "application/xml") |
| + w.WriteHeader(http.StatusPreconditionFailed) |
| + _, _ = w.Write([]byte(`<?xml version="1.0" encoding="UTF-8"?><Error><Code>PreconditionFailed</Code><Message>precondition</Message></Error>`)) |
| + } |
| + switch r.Method { |
| + case http.MethodGet: |
| + if f.body == nil { |
| + w.Header().Set("Content-Type", "application/xml") |
| + w.WriteHeader(http.StatusNotFound) |
| + _, _ = w.Write([]byte(`<?xml version="1.0" encoding="UTF-8"?><Error><Code>NoSuchKey</Code><Message>no such key</Message></Error>`)) |
| + return |
| + } |
| + w.Header().Set("ETag", f.etag) |
| + _, _ = w.Write(f.body) |
| + case http.MethodPut: |
| + f.puts = append(f.puts, r.Header.Clone()) |
| + if r.Header.Get("If-None-Match") == "*" && f.body != nil { |
| + fail() |
| + return |
| + } |
| + if m := r.Header.Get("If-Match"); m != "" && strings.Trim(m, `"`) != strings.Trim(f.etag, `"`) { |
| + fail() |
| + return |
| + } |
| + b, _ := io.ReadAll(r.Body) |
| + f.n++ |
| + f.body, f.etag = b, fmt.Sprintf(`"etag-%d"`, f.n) |
| + w.Header().Set("ETag", f.etag) |
| + case http.MethodDelete: |
| + if m := r.Header.Get("If-Match"); m != "" && strings.Trim(m, `"`) != strings.Trim(f.etag, `"`) { |
| + fail() |
| + return |
| + } |
| + f.body, f.etag = nil, "" |
| + w.WriteHeader(http.StatusNoContent) |
| + } |
| + })) |
| + t.Cleanup(srv.Close) |
| + return f, srv.URL |
| +} |
| + |
| +func (f *casS3) set(t *testing.T, l litestream.Lease) { |
| + t.Helper() |
| + raw, err := json.Marshal(l) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.n++ |
| + f.body, f.etag = raw, fmt.Sprintf(`"etag-%d"`, f.n) |
| +} |
| + |
| +func (f *casS3) methods() []string { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return append([]string(nil), f.reqs...) |
| +} |
| + |
| +func (f *casS3) lease(t *testing.T) litestream.Lease { |
| + t.Helper() |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + var l litestream.Lease |
| + if err := json.Unmarshal(f.body, &l); err != nil { |
| + t.Fatalf("lock %q: %v", f.body, err) |
| + } |
| + return l |
| +} |
| + |
| +func casEnv(t *testing.T) (*casS3, context.Context) { |
| + t.Helper() |
| + f, url := newCasS3(t) |
| + fakeCreds(t) |
| + t.Setenv("CARLOS_S3_ENDPOINT", url) |
| + return f, context.Background() |
| +} |
| + |
| +// A released lease deletes its lock, so the next wake finds none: it |
| +// writes the lease create-only in one round trip, the same lease |
| +// litestream writes for an absent lock (generation 1, this owner). |
| +func TestAcquireAnAbsentLockIsOneCreateOnlyWrite(t *testing.T) { |
| + f, ctx := casEnv(t) |
| + held, err := Acquire(ctx, "b", "inst/x.example.com", "eu-west-1") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := f.methods(); len(got) != 1 || got[0] != http.MethodPut { |
| + t.Fatalf("requests = %v, want one PUT", got) |
| + } |
| + if h := f.puts[0]; h.Get("If-None-Match") != "*" || h.Get("If-Match") != "" { |
| + t.Fatalf("the write was not create-only: %v", h) |
| + } |
| + l := f.lease(t) |
| + if l.Generation != 1 || l.Owner == "" || time.Until(l.ExpiresAt) < LeaseTTL-time.Minute { |
| + t.Fatalf("lease = %+v, want generation 1, an owner and a full TTL", l) |
| + } |
| + // The handle carries the etag its write returned: release is |
| + // conditional on it, so it deletes this lock and no other. |
| + if err := held.Release(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := f.methods(); got[len(got)-1] != http.MethodDelete { |
| + t.Fatalf("requests = %v, want the release's DELETE", got) |
| + } |
| +} |
| + |
| +// An expired lock is taken over as litestream takes it over: read, then a |
| +// conditional write of the next generation. |
| +func TestAcquireAnExpiredLockFallsBackToTheTakeover(t *testing.T) { |
| + f, ctx := casEnv(t) |
| + f.set(t, litestream.Lease{Generation: 4, ExpiresAt: time.Now().Add(-time.Minute), Owner: "gone:1"}) |
| + held, err := Acquire(ctx, "b", "inst/x.example.com", "eu-west-1") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer held.Release(ctx) |
| + if l := f.lease(t); l.Generation != 5 || l.Owner == "gone:1" { |
| + t.Fatalf("lease = %+v, want generation 5 under this owner", l) |
| + } |
| +} |
| + |
| +// A live lock is someone else's: refused with its holder, as before, and |
| +// left exactly as it was. |
| +func TestAcquireALiveLockIsRefused(t *testing.T) { |
| + f, ctx := casEnv(t) |
| + f.set(t, litestream.Lease{Generation: 2, ExpiresAt: time.Now().Add(10 * time.Minute), Owner: "other:7"}) |
| + before := f.lease(t) |
| + _, err := Acquire(ctx, "b", "inst/x.example.com", "eu-west-1") |
| + var held *HeldError |
| + if !errors.As(err, &held) || held.Owner != "other:7" { |
| + t.Fatalf("Acquire = %v, want a HeldError naming other:7", err) |
| + } |
| + if after := f.lease(t); after != before { |
| + t.Fatalf("lock changed: %+v -> %+v", before, after) |
| + } |
| +} |
diff --git a/internal/lease/lease.go b/internal/lease/lease.go| index 11c14c5de..b926b7e78 100644 |
| --- a/internal/lease/lease.go |
| +++ b/internal/lease/lease.go |
| @@ -190,7 +190,10 @@ func AcquireTTL(ctx context.Context, bucket, prefix, region string, ttl time.Dur |
| leaser.TTL = ttl |
| started := time.Now() |
| - lease, err := leaser.AcquireLease(ctx) |
| + lease, err := createLease(ctx, client, leaser) |
| + if errors.Is(err, errLockPresent) { |
| + lease, err = leaser.AcquireLease(ctx) |
| + } |
| if err != nil { |
| // A *litestream.LeaseExistsError means someone else holds it — |
| // re-surfaced as *HeldError so callers stay litestream-free. |