region HA P1a Task 6: every acquire classifies the lock; the HA acquire
hafresh gains the lock vocabulary (Marker, Lock, View, DecodeLock, MarkerBody, HAOn) and DecideAcquire, the HA acquire's one table. lease: AcquireTTL's present-lock case now runs takeLegacy in place of litestream's AcquireLease. takeLegacy and AcquireHA share one classify-and-take loop: read the lock with its ETag, classify that exact view, write conditional on it, reclassify on a lost condition, at most three rounds. The legacy path refuses an HA-format lock (a marker, or an owner with ;ha=1) with *HALockError and writes nothing. AcquireHA refuses without an obligation store or a box identity, settles the key's pending release obligation before it reads, proves an absent lock's prefix empty (one LIST, max-keys 1) before it creates, and releases a late-acknowledged take through the unclean marker, never a DELETE. A failed marker write is persisted under SetObligationDir before *ObligationError returns. Held.View is the view classified before the take. locktest gains AfterWrite (a late acknowledgement) and FailNextMatching (a fault a renewal cannot use up).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
13 files changed,
+1,539
−14
internal/hafresh/acquire.go+93 −0internal/hafresh/acquire_test.go+123 −0internal/hafresh/lock.go+103 −0internal/lease/createlease.go+4 −4internal/lease/export_test.go+16 −0internal/lease/ha.go+190 −0internal/lease/ha_test.go+395 −0internal/lease/lease.go+15 −8internal/lease/legacytake.go+165 −0internal/lease/locktest/fixture.go+46 −2internal/lease/locktest/fixture_test.go+22 −0internal/lease/owed.go+282 −0internal/lease/release.go+85 −0
diff --git a/internal/hafresh/acquire.go b/internal/hafresh/acquire.go| new file mode 100644 |
| index 000000000..2c59ab1cd |
| --- /dev/null |
| +++ b/internal/hafresh/acquire.go |
| @@ -0,0 +1,93 @@ |
| +package hafresh |
| + |
| +import "time" |
| + |
| +// Action is what an HA acquire does with the lock it read. |
| +type Action int |
| + |
| +const ( |
| + ActCreate Action = iota + 1 // the lock is absent: create it, if the prefix is empty |
| + ActTake // write over the lock, conditional on its ETag |
| + ActHeld // someone holds it: refuse, naming them |
| + ActRefuse // refuse: Reason says why |
| +) |
| + |
| +func (a Action) String() string { |
| + switch a { |
| + case ActCreate: |
| + return "create" |
| + case ActTake: |
| + return "take" |
| + case ActHeld: |
| + return "held" |
| + case ActRefuse: |
| + return "refuse" |
| + } |
| + return "unknown" |
| +} |
| + |
| +// Decision is DecideAcquire's answer. Reason is "absent", "release |
| +// marker", the holder's owner for ActHeld, or the refusal. |
| +type Decision struct { |
| + Action Action |
| + Reason string |
| +} |
| + |
| +// Proofs are the facts DecideAcquire cannot read from the lock. |
| +// SameBoxEmpty proves that nothing of the host still runs on this box |
| +// (Task 12); nil, false or an error refuses the same-box takeover. |
| +type Proofs struct{ SameBoxEmpty func() (bool, error) } |
| + |
| +// Refusal reasons, matched by callers and tests. |
| +const ( |
| + ReasonAbsent = "absent" |
| + ReasonMarker = "release marker" |
| + ReasonLeftoverLock = "leftover lock" |
| + ReasonBadMarker = "malformed release marker" |
| + ReasonSameBoxUnsure = "same box without emptiness proof" |
| + ReasonOtherExpired = "another box's expired lease" |
| +) |
| + |
| +// DecideAcquire is the HA acquire's one table (I1), for HA hosts only: |
| +// |
| +// - absent: create (the caller still proves the prefix empty); |
| +// - present, not HA-format: refuse, a leftover lock; |
| +// - a release marker, clean or not: take; |
| +// - an unexpired HA owner: held, by that owner; |
| +// - expired, owned by this box's non-empty instance id: take only with |
| +// the same-box emptiness proof, else refuse; |
| +// - expired, any other box: refuse. Expiry alone never hands an HA lock |
| +// to another box. |
| +func DecideAcquire(v View, self Self, now time.Time, p Proofs) Decision { |
| + if v.Absent { |
| + return Decision{ActCreate, ReasonAbsent} |
| + } |
| + if !v.HAOn() { |
| + return Decision{ActRefuse, ReasonLeftoverLock} |
| + } |
| + if v.Lock.Release != nil { |
| + return Decision{ActTake, ReasonMarker} |
| + } |
| + o, ok := ParseOwner(v.Lock.Owner) |
| + if !ok { |
| + // HA-format by its marker owner, but without the marker record. |
| + return Decision{ActRefuse, ReasonBadMarker} |
| + } |
| + if !now.After(v.Lock.ExpiresAt) { |
| + return Decision{ActHeld, v.Lock.Owner} |
| + } |
| + if self.IID == "" || o.IID != self.IID { |
| + return Decision{ActRefuse, ReasonOtherExpired} |
| + } |
| + if p.SameBoxEmpty == nil { |
| + return Decision{ActRefuse, ReasonSameBoxUnsure} |
| + } |
| + empty, err := p.SameBoxEmpty() |
| + if err != nil { |
| + return Decision{ActRefuse, ReasonSameBoxUnsure + ": " + err.Error()} |
| + } |
| + if !empty { |
| + return Decision{ActRefuse, ReasonSameBoxUnsure} |
| + } |
| + return Decision{ActTake, "same box, proven empty"} |
| +} |
diff --git a/internal/hafresh/acquire_test.go b/internal/hafresh/acquire_test.go| new file mode 100644 |
| index 000000000..dc9e8a076 |
| --- /dev/null |
| +++ b/internal/hafresh/acquire_test.go |
| @@ -0,0 +1,123 @@ |
| +package hafresh |
| + |
| +import ( |
| + "encoding/json" |
| + "errors" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestDecideAcquireTable(t *testing.T) { |
| + now := time.Unix(1_800_000_000, 0) |
| + self := Self{Ref: "a", IID: "i-a"} |
| + exp := now.Add(-time.Minute) |
| + other, mine := OwnerFor(Self{"b", "i-b"}, 9, true), OwnerFor(self, 9, true) |
| + yes := Proofs{SameBoxEmpty: func() (bool, error) { return true, nil }} |
| + no := Proofs{SameBoxEmpty: func() (bool, error) { return false, nil }} |
| + broken := Proofs{SameBoxEmpty: func() (bool, error) { return true, errors.New("cgroup unreadable") }} |
| + for i, c := range []struct { |
| + v View |
| + p Proofs |
| + want Action |
| + }{ |
| + {View{Absent: true}, Proofs{}, ActCreate}, |
| + {View{Lock: Lock{ExpiresAt: exp, Owner: "ip-10-0-0-1:77"}}, Proofs{}, ActRefuse}, |
| + {View{Lock: Lock{Owner: "released/v1;ref=b;iid=i-b", Release: &Marker{Box: "b"}}}, Proofs{}, ActTake}, |
| + {View{Lock: Lock{ExpiresAt: now.Add(time.Minute), Owner: other}}, Proofs{}, ActHeld}, |
| + {View{Lock: Lock{ExpiresAt: exp, Owner: other}}, yes, ActRefuse}, |
| + {View{Lock: Lock{ExpiresAt: exp, Owner: mine}}, Proofs{}, ActRefuse}, |
| + {View{Lock: Lock{ExpiresAt: exp, Owner: mine}}, yes, ActTake}, |
| + // Beyond the plan's table: a proof that says "not empty", or that |
| + // fails, refuses; an unexpired lock of this very box is held; a |
| + // legacy box owner (no ;ha=1) is a leftover lock even when it is |
| + // this box's; a marker owner without its record is refused. |
| + {View{Lock: Lock{ExpiresAt: exp, Owner: mine}}, no, ActRefuse}, |
| + {View{Lock: Lock{ExpiresAt: exp, Owner: mine}}, broken, ActRefuse}, |
| + {View{Lock: Lock{ExpiresAt: now.Add(time.Minute), Owner: mine}}, yes, ActHeld}, |
| + {View{Lock: Lock{ExpiresAt: exp, Owner: OwnerFor(self, 9, false)}}, yes, ActRefuse}, |
| + {View{Lock: Lock{ExpiresAt: exp, Owner: "released/v1;ref=b"}}, yes, ActRefuse}, |
| + {View{Lock: Lock{ExpiresAt: exp, Owner: other}}, Proofs{}, ActRefuse}, |
| + } { |
| + if got := DecideAcquire(c.v, self, now, c.p).Action; got != c.want { |
| + t.Errorf("case %d: %v, want %v", i, got, c.want) |
| + } |
| + } |
| + // The reasons callers match on. |
| + for _, c := range []struct { |
| + v View |
| + p Proofs |
| + want string |
| + }{ |
| + {View{Lock: Lock{ExpiresAt: exp, Owner: "ip-10-0-0-1:77"}}, Proofs{}, ReasonLeftoverLock}, |
| + {View{Lock: Lock{ExpiresAt: exp, Owner: other}}, yes, ReasonOtherExpired}, |
| + {View{Lock: Lock{ExpiresAt: exp, Owner: mine}}, Proofs{}, ReasonSameBoxUnsure}, |
| + {View{Lock: Lock{ExpiresAt: now.Add(time.Minute), Owner: other}}, Proofs{}, other}, |
| + } { |
| + if got := DecideAcquire(c.v, self, now, c.p).Reason; got != c.want { |
| + t.Errorf("reason %q, want %q", got, c.want) |
| + } |
| + } |
| + // A box whose instance id is still unknown never proves itself the |
| + // owner of an expired lock, even one with no iid either. |
| + noIID := OwnerFor(Self{Ref: "a"}, 9, true) |
| + if d := DecideAcquire(View{Lock: Lock{ExpiresAt: exp, Owner: noIID}}, Self{Ref: "a"}, now, yes); d.Action != ActRefuse { |
| + t.Fatalf("no iid: %+v", d) |
| + } |
| +} |
| + |
| +func TestMarkerBodyFormat(t *testing.T) { |
| + at := time.Date(2026, 10, 26, 12, 0, 0, 0, time.UTC) |
| + body, err := MarkerBody(7, Marker{V: 1, Box: "a", IID: "i-a", Lifetime: "L1", TXID: 12, FilesGen: "3:ab", At: at, Clean: true}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var raw map[string]any |
| + if err := json.Unmarshal(body, &raw); err != nil { |
| + t.Fatal(err) |
| + } |
| + if raw["expires_at"] != "1970-01-01T00:00:00Z" || raw["owner"] != "released/v1;ref=a;iid=i-a" || raw["generation"] != float64(7) { |
| + t.Fatalf("marker %s", body) |
| + } |
| + rel, _ := raw["carlos_release"].(map[string]any) |
| + for k, want := range map[string]any{"v": float64(1), "box": "a", "iid": "i-a", "lifetime": "L1", "txid": float64(12), "files_gen": "3:ab", "at": "2026-10-26T12:00:00Z", "clean": true} { |
| + if rel[k] != want { |
| + t.Errorf("carlos_release.%s = %v, want %v", k, rel[k], want) |
| + } |
| + } |
| + v, err := DecodeLock(body, `"e"`) |
| + if err != nil || !v.HAOn() || v.Lock.Release == nil || v.Lock.Release.TXID != 12 || v.ETag != `"e"` { |
| + t.Fatalf("%+v %v", v, err) |
| + } |
| + if b, _ := MarkerBody(1, Marker{V: 1, Box: "a"}); !strings.Contains(string(b), `"owner":"released/v1;ref=a"`) { |
| + t.Fatalf("iid not left out: %s", b) |
| + } |
| + if _, err := MarkerBody(1, Marker{V: 1}); err == nil { |
| + t.Fatal("a marker with no box") |
| + } |
| +} |
| + |
| +func TestDecodeLockAndHAOn(t *testing.T) { |
| + if _, err := DecodeLock([]byte(`{"generation":1,"owner":"x"}`), ""); err == nil { |
| + t.Fatal("a lock with no expiry decoded") |
| + } |
| + if _, err := DecodeLock([]byte(`not json`), ""); err == nil { |
| + t.Fatal("garbage decoded") |
| + } |
| + for body, ha := range map[string]bool{ |
| + `{"generation":1,"expires_at":"2030-01-01T00:00:00Z","owner":"ip-10-0-0-1:77"}`: false, |
| + `{"generation":1,"expires_at":"2030-01-01T00:00:00Z","owner":"box/v1;ref=a;iid=i-a;pid=7"}`: false, |
| + `{"generation":1,"expires_at":"2030-01-01T00:00:00Z","owner":"moved:abc"}`: false, |
| + `{"generation":1,"expires_at":"2030-01-01T00:00:00Z","owner":"box/v1;ref=a;iid=i-a;pid=7;ha=1"}`: true, |
| + `{"generation":1,"expires_at":"1970-01-01T00:00:00Z","owner":"released/v1;ref=a"}`: true, |
| + `{"generation":1,"expires_at":"1970-01-01T00:00:00Z","owner":"x","carlos_release":{"v":1,"box":"a"}}`: true, |
| + } { |
| + v, err := DecodeLock([]byte(body), "") |
| + if err != nil || v.HAOn() != ha { |
| + t.Errorf("%s: HAOn %v (err %v), want %v", body, v.HAOn(), err, ha) |
| + } |
| + } |
| + if (View{Absent: true}).HAOn() { |
| + t.Fatal("an absent lock is HA-format") |
| + } |
| +} |
diff --git a/internal/hafresh/lock.go b/internal/hafresh/lock.go| new file mode 100644 |
| index 000000000..261381e51 |
| --- /dev/null |
| +++ b/internal/hafresh/lock.go |
| @@ -0,0 +1,103 @@ |
| +package hafresh |
| + |
| +import ( |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "strings" |
| + "time" |
| +) |
| + |
| +// Marker is a release marker's carlos_release record: which box let the |
| +// host go, for which lifetime, at which replica position and files |
| +// generation, and whether that release was clean (the final sync |
| +// succeeded and the files tree was complete). Only a clean marker can let |
| +// a box keep its local copy; every other release writes Clean false. |
| +type Marker struct { |
| + V int `json:"v"` |
| + Box string `json:"box"` |
| + IID string `json:"iid"` |
| + Lifetime string `json:"lifetime"` |
| + TXID uint64 `json:"txid"` |
| + FilesGen string `json:"files_gen"` |
| + At time.Time `json:"at"` |
| + Clean bool `json:"clean"` |
| +} |
| + |
| +// Lock is lock.json as region HA reads it: litestream's lease fields, plus |
| +// the release marker an HA host's lock carries once it is released. |
| +type Lock struct { |
| + Generation int64 `json:"generation"` |
| + ExpiresAt time.Time `json:"expires_at"` |
| + Owner string `json:"owner"` |
| + Release *Marker `json:"carlos_release,omitempty"` |
| +} |
| + |
| +// View is one read of a lock: absent, or the lock and the ETag it was read |
| +// at. Every conditional write is made against exactly the ETag of the |
| +// view it classified. |
| +type View struct { |
| + Absent bool |
| + Lock Lock |
| + ETag string |
| +} |
| + |
| +// MarkerOwnerPrefix starts a release marker's owner. A marker is never a |
| +// box owner (ParseOwner refuses it), so an old reader that only knows |
| +// owners and expiry sees an expired lease of nobody it knows. |
| +const MarkerOwnerPrefix = "released/v1;" |
| + |
| +// markerExpiry is a marker's expires_at: long past, so every reader, |
| +// litestream's own included, reads the lock as free of holders. Region HA |
| +// never takes one on expiry alone; it reads the marker. |
| +var markerExpiry = time.Unix(0, 0).UTC() |
| + |
| +// MarkerOwner is the owner a marker for m carries: |
| +// released/v1;ref=<box>;iid=<iid>, iid= left out while it is unknown. |
| +func MarkerOwner(m Marker) string { |
| + s := MarkerOwnerPrefix + "ref=" + m.Box |
| + if m.IID != "" { |
| + s += ";iid=" + m.IID |
| + } |
| + return s |
| +} |
| + |
| +// MarkerBody is the lock.json body that releases an HA lock at |
| +// generation: expired since 1970, owned by the marker owner, with m as its |
| +// carlos_release. The generation stays the released lease's; the next |
| +// take writes generation+1. |
| +func MarkerBody(generation int64, m Marker) ([]byte, error) { |
| + if m.Box == "" { |
| + return nil, errors.New("hafresh: a release marker names its box") |
| + } |
| + return json.Marshal(Lock{Generation: generation, ExpiresAt: markerExpiry, Owner: MarkerOwner(m), Release: &m}) |
| +} |
| + |
| +// DecodeLock reads a lock.json body read at etag. A body that is not a |
| +// lock, or a lock with no expiry, is an error, never "free": absence is |
| +// only ever S3's own answer, which the caller reads before calling this. |
| +func DecodeLock(body []byte, etag string) (View, error) { |
| + var l Lock |
| + if err := json.Unmarshal(body, &l); err != nil { |
| + return View{}, fmt.Errorf("hafresh: decode lock: %w", err) |
| + } |
| + if l.ExpiresAt.IsZero() { |
| + return View{}, errors.New("hafresh: the lock has no expiry") |
| + } |
| + return View{Lock: l, ETag: etag}, nil |
| +} |
| + |
| +// HAOn reports whether the lock is HA-format: a release marker (the |
| +// carlos_release record, or a marker owner), or an owner that parses with |
| +// ;ha=1. An HA-format lock is never written by the legacy acquire, and a |
| +// box treats its host as HA from then on. |
| +func (v View) HAOn() bool { |
| + if v.Absent { |
| + return false |
| + } |
| + if v.Lock.Release != nil || strings.HasPrefix(v.Lock.Owner, MarkerOwnerPrefix) { |
| + return true |
| + } |
| + o, ok := ParseOwner(v.Lock.Owner) |
| + return ok && o.HA |
| +} |
diff --git a/internal/lease/createlease.go b/internal/lease/createlease.go| index 2394a4196..a3759bf55 100644 |
| --- a/internal/lease/createlease.go |
| +++ b/internal/lease/createlease.go |
| @@ -16,7 +16,7 @@ import ( |
| ) |
| // errLockPresent is createLease's answer when a lock object exists, live or |
| -// expired: litestream's AcquireLease decides it, as it always has. |
| +// expired: takeLegacy (legacytake.go) classifies it. |
| var errLockPresent = errors.New("lease: a lock is present") |
| // createLease is litestream's AcquireLease for the common case, the lock |
| @@ -25,9 +25,9 @@ var errLockPresent = errors.New("lease: a lock is present") |
| // leaser's owner (currentOwner, which AcquireTTL set), 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. |
| +// there, and errLockPresent hands the decision to takeLegacy (the |
| +// takeover of an expired lock, the refusal of a live or HA-format one). |
| +// Any other error is the acquire's. |
| 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) |
diff --git a/internal/lease/export_test.go b/internal/lease/export_test.go| index c6c589e69..bdb175a49 100644 |
| --- a/internal/lease/export_test.go |
| +++ b/internal/lease/export_test.go |
| @@ -7,3 +7,19 @@ import awss3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| func NewVersionedS3WithClients(clients map[string]*awss3.Client) VersionedStore { |
| return &versionedS3{clients: clients} |
| } |
| + |
| +// Narrow access for the external (package lease_test) HA tests. |
| +var ( |
| + LockHeldForTest = lockHeld |
| + LeaseFreeForTest = leaseFree |
| + AcquireHATTL = acquireHATTL |
| +) |
| + |
| +// ResetForTest is a fresh process's lease state: no self, no obligation |
| +// store, nothing pending. |
| +func ResetForTest() { |
| + self.Store(nil) |
| + owed.mu.Lock() |
| + owed.dir, owed.pending = "", nil |
| + owed.mu.Unlock() |
| +} |
diff --git a/internal/lease/ha.go b/internal/lease/ha.go| new file mode 100644 |
| index 000000000..9ab131d86 |
| --- /dev/null |
| +++ b/internal/lease/ha.go |
| @@ -0,0 +1,190 @@ |
| +package lease |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "os" |
| + "strings" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + awss3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| + lss3 "github.com/benbjohnson/litestream/s3" |
| + |
| + "github.com/carlosframework/platform/internal/hafresh" |
| +) |
| + |
| +// RefusedError is an HA acquire's refusal (hafresh.DecideAcquire's |
| +// reasons, or "leftover data" for a first wake over a non-empty prefix). |
| +// Nothing was written. |
| +type RefusedError struct{ Reason string } |
| + |
| +func (e *RefusedError) Error() string { return "lease: HA acquire refused: " + e.Reason } |
| + |
| +// ReasonLeftoverData refuses the first wake of an HA host (no lock) whose |
| +// prefix already holds something. |
| +const ReasonLeftoverData = "leftover data" |
| + |
| +// ErrNoSelf refuses an HA acquire before SetSelf: an HA lock's owner must |
| +// name the box. |
| +var ErrNoSelf = errors.New("lease: no box identity set; HA acquire refused") |
| + |
| +// AcquireHA is the acquire for HA hosts, and the only one: it never falls |
| +// back to litestream's AcquireLease or to the legacy path. |
| +// |
| +// 0. A pending obligation for this key is retried first (one PUT). If it |
| +// fails, that *ObligationError is returned and nothing is read. |
| +// 1. The lock is read with its ETag and classified (hafresh.DecideAcquire). |
| +// 2. Absent: the prefix must be empty (PrefixEmpty), else *RefusedError |
| +// "leftover data"; then a create, If-None-Match: *. |
| +// 3. A marker, or this box's expired lock with Proofs.SameBoxEmpty: a |
| +// take, If-Match the ETag classified, generation+1, the HA owner. |
| +// 4. Held: *HeldError. Refused: *RefusedError. Nothing written. |
| +// 5. A lost condition re-reads and reclassifies, at most three rounds. |
| +// |
| +// The renewer starts from the write's own send time. If the safe deadline |
| +// has passed by the time the write is acknowledged, the lease is released |
| +// at once through the unclean marker, never a DELETE. base (box, instance |
| +// id, lifetime) is kept for the handle's unclean releases; an empty box or |
| +// instance id is this box's own. |
| +// |
| +// The budget: a marker or same-box wake is 1 GET and 1 PUT; a first wake |
| +// 1 GET, 1 LIST (max-keys 1) and 1 PUT. |
| +func AcquireHA(ctx context.Context, bucket, prefix, region string, base hafresh.Marker, p hafresh.Proofs) (*Held, error) { |
| + return acquireHATTL(ctx, bucket, prefix, region, base, p, LeaseTTL) |
| +} |
| + |
| +func acquireHATTL(ctx context.Context, bucket, prefix, region string, base hafresh.Marker, p hafresh.Proofs, ttl time.Duration) (*Held, error) { |
| + if !obligationStoreSet() { |
| + return nil, ErrNoObligationStore |
| + } |
| + s := self.Load() |
| + if s == nil || s.Ref == "" { |
| + return nil, ErrNoSelf |
| + } |
| + me := *s |
| + key, err := lockKey(bucket, prefix) |
| + if err != nil { |
| + return nil, err |
| + } |
| + loc := strings.TrimSuffix(prefix, "/") |
| + began := time.Now() |
| + client, region, err := newLeaserClient(ctx, region) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if e := pendingFor(bucket, key); e != nil { |
| + if err := settle(ctx, e); err != nil { |
| + return nil, fmt.Errorf("acquire HA lease: settle the owed release first: %w", err) |
| + } |
| + } |
| + |
| + leaser := lss3.NewLeaser() |
| + leaser.SetClient(client) |
| + leaser.Bucket = bucket |
| + leaser.Path = loc |
| + leaser.TTL = ttl |
| + leaser.Owner = hafresh.OwnerFor(me, os.Getpid(), true) // renewals keep it |
| + lease, view, started, err := classifyAndTake(ctx, client, bucket, key, leaser.Owner, ttl, func(v hafresh.View) error { |
| + d := hafresh.DecideAcquire(v, me, time.Now(), p) |
| + switch d.Action { |
| + case hafresh.ActCreate: |
| + empty, err := prefixEmpty(ctx, client, bucket, loc) |
| + if err != nil { |
| + return err |
| + } |
| + if !empty { |
| + return &RefusedError{Reason: ReasonLeftoverData} |
| + } |
| + return nil |
| + case hafresh.ActTake: |
| + return nil |
| + case hafresh.ActHeld: |
| + return &HeldError{Owner: v.Lock.Owner, ExpiresAt: v.Lock.ExpiresAt} |
| + default: |
| + return &RefusedError{Reason: d.Reason} |
| + } |
| + }) |
| + if err != nil { |
| + return nil, fmt.Errorf("acquire HA lease: %w", err) |
| + } |
| + if base.Box == "" { |
| + base.Box = me.Ref |
| + } |
| + if base.IID == "" { |
| + base.IID = me.IID |
| + } |
| + base.V = 1 |
| + rn := startRenewer(leaser, lease, started, marginForTTL(ttl)) |
| + if err := rn.Err(); err != nil { |
| + // A late acknowledgement: the lock is ours, the deadline is not. |
| + // Let it go through the marker, on its own budget. |
| + cur := rn.stop() |
| + relCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| + defer cancel() |
| + return nil, errors.Join(fmt.Errorf("acquire HA lease: %w", err), releaseWithMarker(relCtx, leaser, region, cur, uncleanMarker(base, 0))) |
| + } |
| + log.Printf("lease: %s: HA lease acquired in %s (%s)", prefix, time.Since(began).Round(time.Millisecond), viewWord(view)) |
| + return &Held{leaser: leaser, region: region, rn: rn, ha: true, view: view, base: base}, nil |
| +} |
| + |
| +func viewWord(v hafresh.View) string { |
| + switch { |
| + case v.Absent: |
| + return "first wake" |
| + case v.Lock.Release != nil && v.Lock.Release.Clean: |
| + return "clean marker" |
| + case v.Lock.Release != nil: |
| + return "unclean marker" |
| + } |
| + return "same-box takeover" |
| +} |
| + |
| +// HA reports whether the handle holds an HA lease (AcquireHA). |
| +func (h *Held) HA() bool { return h.ha } |
| + |
| +// View is the lock exactly as AcquireHA classified it before its take: |
| +// the release marker it took over, or Absent on a first wake. It is never |
| +// re-read, and never the lock the take wrote. Zero for a legacy handle. |
| +func (h *Held) View() hafresh.View { return h.view } |
| + |
| +// ReadLock reads s3://bucket/<prefix>/lock.json with its ETag, through the |
| +// client Acquire builds. Only S3's NoSuchKey is Absent. |
| +func ReadLock(ctx context.Context, bucket, prefix, region string) (hafresh.View, error) { |
| + key, err := lockKey(bucket, prefix) |
| + if err != nil { |
| + return hafresh.View{}, err |
| + } |
| + client, _, err := newLeaserClient(ctx, region) |
| + if err != nil { |
| + return hafresh.View{}, err |
| + } |
| + return readView(ctx, client, bucket, key) |
| +} |
| + |
| +// PrefixEmpty reports whether nothing at all is stored under prefix/: one |
| +// ListObjectsV2, max-keys 1. |
| +func PrefixEmpty(ctx context.Context, bucket, prefix, region string) (bool, error) { |
| + if _, err := lockKey(bucket, prefix); err != nil { |
| + return false, err |
| + } |
| + client, _, err := newLeaserClient(ctx, region) |
| + if err != nil { |
| + return false, err |
| + } |
| + return prefixEmpty(ctx, client, bucket, strings.TrimSuffix(prefix, "/")) |
| +} |
| + |
| +type lister interface { |
| + ListObjectsV2(ctx context.Context, params *awss3.ListObjectsV2Input, optFns ...func(*awss3.Options)) (*awss3.ListObjectsV2Output, error) |
| +} |
| + |
| +func prefixEmpty(ctx context.Context, client lister, bucket, loc string) (bool, error) { |
| + out, err := client.ListObjectsV2(ctx, &awss3.ListObjectsV2Input{Bucket: aws.String(bucket), Prefix: aws.String(loc + "/"), MaxKeys: aws.Int32(1)}) |
| + if err != nil { |
| + return false, fmt.Errorf("lease: list %s/: %w", loc, err) |
| + } |
| + return len(out.Contents) == 0 && aws.ToInt32(out.KeyCount) == 0 && !aws.ToBool(out.IsTruncated), nil |
| +} |
diff --git a/internal/lease/ha_test.go b/internal/lease/ha_test.go| new file mode 100644 |
| index 000000000..b6d620b2a |
| --- /dev/null |
| +++ b/internal/lease/ha_test.go |
| @@ -0,0 +1,395 @@ |
| +package lease_test |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "os" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/benbjohnson/litestream" |
| + |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/lease" |
| + leasetest "github.com/carlosframework/platform/internal/lease/locktest" |
| +) |
| + |
| +var ctx = context.Background() |
| + |
| +// leaseBody is a lock.json body as the leaser writes it. |
| +func leaseBody(owner string, expires time.Time) []byte { |
| + b, _ := json.Marshal(litestream.Lease{Generation: 9, ExpiresAt: expires, Owner: owner}) |
| + return b |
| +} |
| + |
| +// delayPutAck makes the next PUT land at once and its answer arrive d |
| +// later: the acknowledgement comes past the safe deadline. |
| +func delayPutAck(t *testing.T, fx *leasetest.LockFixture, d time.Duration) { |
| + t.Helper() |
| + var once sync.Once |
| + fx.AfterWrite(func(m, _ string) { |
| + if m == http.MethodPut { |
| + once.Do(func() { time.Sleep(d) }) |
| + } |
| + }) |
| +} |
| + |
| +// haBox is a fresh process on box a (i-a) with an obligation store. |
| +func haBox(t *testing.T) { |
| + t.Helper() |
| + lease.ResetForTest() |
| + t.Cleanup(lease.ResetForTest) |
| + lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a"}) |
| + if err := lease.SetObligationDir(t.TempDir()); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func dirFiles(t *testing.T, dir string) []string { |
| + t.Helper() |
| + es, err := os.ReadDir(dir) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var names []string |
| + for _, e := range es { |
| + names = append(names, e.Name()) |
| + } |
| + return names |
| +} |
| + |
| +func writes(fx *leasetest.LockFixture) []string { |
| + return slices.DeleteFunc(fx.Requests(), func(s string) bool { return !strings.HasPrefix(s, "PUT") && !strings.HasPrefix(s, "DELETE") }) |
| +} |
| + |
| +func TestMarkerReadAsFreeByOldReaders(t *testing.T) { |
| + body, _ := hafresh.MarkerBody(7, hafresh.Marker{V: 1, Box: "a", IID: "i-a", TXID: 12, Clean: true}) |
| + var l litestream.Lease |
| + if err := json.NewDecoder(bytes.NewReader(body)).Decode(&l); err != nil || !l.IsExpired() { |
| + t.Fatal(err) |
| + } |
| + if lease.LockHeldForTest(l.ExpiresAt, time.Now()) || !lease.LeaseFreeForTest(l.ExpiresAt, time.Now()) { |
| + t.Fatal("read as held") |
| + } |
| +} |
| + |
| +// r2.12: a wake over a marker is one GET and one conditional PUT, and the |
| +// handle's View is the marker it classified, not the lock it wrote. |
| +func TestAcquireHAMarkerCostsOneGetOnePut(t *testing.T) { |
| + haBox(t) |
| + fx := leasetest.NewLockFixture(t) |
| + body, _ := hafresh.MarkerBody(3, hafresh.Marker{V: 1, Box: "b", IID: "i-b", Clean: true}) |
| + fx.PutLock("instances/h", body) |
| + h, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1, Box: "a", IID: "i-a"}, hafresh.Proofs{}) |
| + if err != nil || !h.HA() { |
| + t.Fatal(err) |
| + } |
| + defer h.Release(ctx) |
| + if r := fx.Requests(); !slices.Equal(r, []string{"GET instances/h/lock.json", "PUT instances/h/lock.json"}) { |
| + t.Fatalf("%v", r) |
| + } |
| + v := h.View() |
| + if v.Absent || v.Lock.Release == nil || v.Lock.Release.Box != "b" || v.Lock.Generation != 3 || v.ETag == "" { |
| + t.Fatalf("View is not the classified marker: %+v", v) |
| + } |
| + now, _ := hafresh.DecodeLock(fx.LockBody("instances/h"), "") |
| + if o, ok := hafresh.ParseOwner(now.Lock.Owner); !ok || !o.HA || o.IID != "i-a" || now.Lock.Generation != 4 || now.Lock.Release != nil { |
| + t.Fatalf("taken lock %+v", now.Lock) |
| + } |
| +} |
| + |
| +// The first wake's budget: 1 GET (404), 1 LIST (max-keys 1), 1 PUT. |
| +func TestAcquireHAFirstWakeCostsOneGetOneListOnePut(t *testing.T) { |
| + haBox(t) |
| + fx := leasetest.NewLockFixture(t) |
| + h, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer h.Release(ctx) |
| + if r := fx.Requests(); !slices.Equal(r, []string{"GET instances/h/lock.json", "LIST instances/h/", "PUT instances/h/lock.json"}) { |
| + t.Fatalf("%v", r) |
| + } |
| + if !h.View().Absent { |
| + t.Fatalf("View %+v", h.View()) |
| + } |
| + if o, ok := hafresh.ParseOwner(fx.LockOwner("instances/h")); !ok || !o.HA { |
| + t.Fatalf("owner %q", fx.LockOwner("instances/h")) |
| + } |
| +} |
| + |
| +// r2.6: a lost condition re-reads and reclassifies; it never writes over |
| +// what it did not classify. |
| +func TestAcquireHAReclassifiesOnConflict(t *testing.T) { |
| + haBox(t) |
| + fx := leasetest.NewLockFixture(t) |
| + body, _ := hafresh.MarkerBody(3, hafresh.Marker{V: 1, Box: "b", IID: "i-b", Clean: true}) |
| + fx.PutLock("instances/h", body) |
| + fx.BeforeWrite(func(m, k string) { |
| + fx.PutLock("instances/h", leaseBody(hafresh.OwnerFor(hafresh.Self{Ref: "c", IID: "i-c"}, 1, true), time.Now().Add(time.Hour))) |
| + }) |
| + _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{}) |
| + var held *lease.HeldError |
| + if !errors.As(err, &held) || !strings.Contains(held.Owner, "ref=c") { |
| + t.Fatalf("did not reclassify: %v", err) |
| + } |
| + if r := fx.Requests(); !slices.Equal(r, []string{"GET instances/h/lock.json", "PUT instances/h/lock.json", "GET instances/h/lock.json"}) { |
| + t.Fatalf("%v", r) |
| + } |
| +} |
| + |
| +// At most three rounds: a lock that changes under every write ends the |
| +// acquire with an error after three reads and three writes. |
| +func TestAcquireHAGivesUpAfterThreeRounds(t *testing.T) { |
| + haBox(t) |
| + fx := leasetest.NewLockFixture(t) |
| + gen := int64(3) |
| + marker := func() []byte { |
| + gen++ |
| + b, _ := hafresh.MarkerBody(gen, hafresh.Marker{V: 1, Box: "b", IID: "i-b"}) |
| + return b |
| + } |
| + fx.PutLock("instances/h", marker()) |
| + fx.BeforeWrite(func(m, k string) { fx.PutLock("instances/h", marker()) }) |
| + if _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{}); err == nil { |
| + t.Fatal("acquired a lock that never held still") |
| + } |
| + want := slices.Repeat([]string{"GET instances/h/lock.json", "PUT instances/h/lock.json"}, 3) |
| + if r := fx.Requests(); !slices.Equal(r, want) { |
| + t.Fatalf("%v", r) |
| + } |
| +} |
| + |
| +func TestAcquireHAFirstWakeRefusesLeftovers(t *testing.T) { |
| + haBox(t) |
| + fx := leasetest.NewLockFixture(t) |
| + fx.PutObject("instances/h/files/0/manifest.json", []byte(`{}`)) |
| + _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{}) |
| + var r *lease.RefusedError |
| + if !errors.As(err, &r) || r.Reason != lease.ReasonLeftoverData || slices.ContainsFunc(fx.Requests(), func(s string) bool { return strings.HasPrefix(s, "PUT") }) { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// Every refusal and every hold writes nothing. |
| +func TestAcquireHARefusesWithoutWriting(t *testing.T) { |
| + haBox(t) |
| + other := hafresh.OwnerFor(hafresh.Self{Ref: "b", IID: "i-b"}, 9, true) |
| + mine := hafresh.OwnerFor(hafresh.Self{Ref: "a", IID: "i-a"}, 9, true) |
| + empty := func(ok bool) hafresh.Proofs { |
| + return hafresh.Proofs{SameBoxEmpty: func() (bool, error) { return ok, nil }} |
| + } |
| + for _, c := range []struct { |
| + name string |
| + body []byte |
| + p hafresh.Proofs |
| + reason string // "" for a HeldError |
| + }{ |
| + {"legacy lock", leaseBody("ip-10-0-0-1:77", time.Now().Add(-time.Hour)), empty(true), hafresh.ReasonLeftoverLock}, |
| + {"other box expired", leaseBody(other, time.Now().Add(-time.Hour)), empty(true), hafresh.ReasonOtherExpired}, |
| + {"own box unproven", leaseBody(mine, time.Now().Add(-time.Hour)), empty(false), hafresh.ReasonSameBoxUnsure}, |
| + {"held", leaseBody(other, time.Now().Add(time.Hour)), empty(true), ""}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + fx := leasetest.NewLockFixture(t) |
| + fx.PutLock("instances/h", c.body) |
| + _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, c.p) |
| + var r *lease.RefusedError |
| + var held *lease.HeldError |
| + switch { |
| + case c.reason == "" && !errors.As(err, &held): |
| + t.Fatalf("want held: %v", err) |
| + case c.reason != "" && (!errors.As(err, &r) || r.Reason != c.reason): |
| + t.Fatalf("want refused %q: %v", c.reason, err) |
| + } |
| + if w := writes(fx); len(w) != 0 || !bytes.Equal(fx.LockBody("instances/h"), c.body) { |
| + t.Fatalf("wrote %v", w) |
| + } |
| + }) |
| + } |
| + // With the proof, this box's own expired lock is taken. |
| + fx := leasetest.NewLockFixture(t) |
| + fx.PutLock("instances/h", leaseBody(mine, time.Now().Add(-time.Hour))) |
| + h, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, empty(true)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + h.Release(ctx) |
| +} |
| + |
| +// No self, no HA acquire: the owner would not name the box. |
| +func TestAcquireHARefusesWithoutSelf(t *testing.T) { |
| + lease.ResetForTest() |
| + t.Cleanup(lease.ResetForTest) |
| + if err := lease.SetObligationDir(t.TempDir()); err != nil { |
| + t.Fatal(err) |
| + } |
| + fx := leasetest.NewLockFixture(t) |
| + if _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{}); !errors.Is(err, lease.ErrNoSelf) || len(fx.Requests()) != 0 { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// r2.1: the PUT lands, its answer arrives past the safe deadline. The |
| +// acquire fails and leaves the lock an unclean marker, never deleted. |
| +func TestAcquireHALateAckWritesUncleanMarker(t *testing.T) { |
| + haBox(t) |
| + fx := leasetest.NewLockFixture(t) |
| + delayPutAck(t, fx, 4*time.Second) |
| + if _, err := lease.AcquireHATTL(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1, Box: "a", IID: "i-a"}, hafresh.Proofs{}, 3*time.Second); err == nil { |
| + t.Fatal("late ack accepted") |
| + } |
| + v, _ := hafresh.DecodeLock(fx.LockBody("instances/h"), "") |
| + if v.Absent || v.Lock.Release == nil || v.Lock.Release.Clean || v.Lock.Release.Box != "a" { |
| + t.Fatalf("HA lock not left as an unclean marker: %+v", v) |
| + } |
| + if slices.ContainsFunc(fx.Requests(), func(s string) bool { return strings.HasPrefix(s, "DELETE") }) { |
| + t.Fatal("HA lock deleted") |
| + } |
| +} |
| + |
| +// r3.1: the legacy path refuses an HA-format lock, a marker or another |
| +// box's expired HA owner, and writes nothing. |
| +func TestLegacyAcquireRefusesHALock(t *testing.T) { |
| + expired := leaseBody(hafresh.OwnerFor(hafresh.Self{Ref: "b", IID: "i-b"}, 9, true), time.Now().Add(-time.Hour)) |
| + marker, _ := hafresh.MarkerBody(3, hafresh.Marker{V: 1, Box: "b", IID: "i-b", Clean: true}) |
| + for _, body := range [][]byte{expired, marker} { |
| + fx := leasetest.NewLockFixture(t) |
| + fx.PutLock("instances/h", body) |
| + _, err := lease.Acquire(ctx, fx.Bucket, "instances/h", "") |
| + var ha *lease.HALockError |
| + if !errors.As(err, &ha) || !bytes.Equal(fx.LockBody("instances/h"), body) { |
| + t.Fatalf("legacy path took an HA lock: %v", err) |
| + } |
| + if w := writes(fx); !slices.Equal(w, []string{"PUT instances/h/lock.json"}) { // the create-only write, refused |
| + t.Fatalf("writes %v", w) |
| + } |
| + } |
| +} |
| + |
| +// r3.1 interleaving: the legacy take is conditional on the ETag it |
| +// classified, and a lost condition is reclassified. |
| +func TestLegacyTakeIsConditionalOnTheClassifiedETag(t *testing.T) { |
| + fx := leasetest.NewLockFixture(t) |
| + fx.PutLock("instances/h", leaseBody("ip-10-0-0-1:77", time.Now().Add(-time.Hour))) |
| + var once sync.Once // the create's PUT 412s; before the take's PUT, a born-HA box takes the key |
| + fx.BeforeWrite(func(m, k string) { |
| + if m == http.MethodPut && slices.Contains(fx.Requests(), "GET instances/h/lock.json") { |
| + once.Do(func() { |
| + fx.PutLock("instances/h", leaseBody(hafresh.OwnerFor(hafresh.Self{Ref: "b", IID: "i-b"}, 9, true), time.Now().Add(-time.Second))) |
| + }) |
| + } |
| + }) |
| + _, err := lease.Acquire(ctx, fx.Bucket, "instances/h", "") |
| + var ha *lease.HALockError |
| + if !errors.As(err, &ha) { |
| + t.Fatalf("the 412 was not reclassified: %v", err) |
| + } |
| + if o, ok := hafresh.ParseOwner(fx.LockOwner("instances/h")); !ok || o.Ref != "b" { |
| + t.Fatalf("the HA lock was overwritten: %q", fx.LockOwner("instances/h")) |
| + } |
| +} |
| + |
| +// The legacy path is unchanged for legacy locks: an expired one is taken |
| +// at the next generation, a live one is refused with its holder. |
| +func TestLegacyTakeKeepsLegacyLocks(t *testing.T) { |
| + fx := leasetest.NewLockFixture(t) |
| + fx.PutLock("instances/h", leaseBody("ip-10-0-0-1:77", time.Now().Add(-time.Hour))) |
| + h, err := lease.Acquire(ctx, fx.Bucket, "instances/h", "") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + v, _ := hafresh.DecodeLock(fx.LockBody("instances/h"), "") |
| + if v.Lock.Generation != 10 || v.HAOn() { |
| + t.Fatalf("%+v", v) |
| + } |
| + if err := h.Release(ctx); err != nil || fx.LockBody("instances/h") != nil { |
| + t.Fatalf("legacy release: %v", err) |
| + } |
| + fx.PutLock("instances/h", leaseBody("ip-10-0-0-1:77", time.Now().Add(time.Hour))) |
| + _, err = lease.Acquire(ctx, fx.Bucket, "instances/h", "") |
| + var held *lease.HeldError |
| + if !errors.As(err, &held) || held.Owner != "ip-10-0-0-1:77" { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func TestHAAcquireRefusedWithoutObligationStore(t *testing.T) { |
| + lease.ResetForTest() |
| + t.Cleanup(lease.ResetForTest) |
| + lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a"}) |
| + fx := leasetest.NewLockFixture(t) |
| + if _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{}); !errors.Is(err, lease.ErrNoObligationStore) || len(fx.Requests()) != 0 { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// r3.3, path 1: a late ack, then its marker PUT fails. The obligation is |
| +// on disk before the error returns; a new process settles it before it |
| +// reads the lock. |
| +func TestAcquireCleanupObligationSurvivesRestart(t *testing.T) { |
| + haBox(t) |
| + dir := t.TempDir() |
| + if err := lease.SetObligationDir(dir); err != nil { |
| + t.Fatal(err) |
| + } |
| + fx := leasetest.NewLockFixture(t) |
| + delayPutAck(t, fx, 4*time.Second) // the acquire's PUT |
| + // The marker's PUT fails with an error the SDK does not retry. |
| + fx.FailNextMatching(http.MethodPut, http.StatusForbidden, func(_ string, b []byte) bool { return bytes.Contains(b, []byte("carlos_release")) }) |
| + _, err := lease.AcquireHATTL(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1, Box: "a", IID: "i-a"}, hafresh.Proofs{}, 3*time.Second) |
| + var oe *lease.ObligationError |
| + if !errors.As(err, &oe) || len(dirFiles(t, dir)) != 1 { |
| + t.Fatalf("not persisted: %v", err) |
| + } |
| + lease.ResetForTest() // a new process |
| + lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a"}) |
| + if err := lease.SetObligationDir(dir); err != nil || len(lease.PendingObligations()) != 1 { |
| + t.Fatalf("not loaded: %v", err) |
| + } |
| + h, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1, Box: "a", IID: "i-a"}, hafresh.Proofs{}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer h.Release(ctx) |
| + if w := fx.Requests(); !slices.Equal(w[len(w)-3:], []string{"PUT instances/h/lock.json", "GET instances/h/lock.json", "PUT instances/h/lock.json"}) || len(dirFiles(t, dir)) != 0 { |
| + t.Fatalf("the marker was not settled before the read: %v", w) |
| + } |
| + if v := h.View(); v.Lock.Release == nil || v.Lock.Release.Clean { |
| + t.Fatalf("took over %+v, want the settled unclean marker", v) |
| + } |
| + if len(lease.PendingObligations()) != 0 { |
| + t.Fatal("still pending") |
| + } |
| +} |
| + |
| +// A pending obligation that still fails blocks its key's acquire: the |
| +// *ObligationError comes back and the lock is not read. |
| +func TestAcquireHAWithAFailingObligationReadsNothing(t *testing.T) { |
| + haBox(t) |
| + fx := leasetest.NewLockFixture(t) |
| + delayPutAck(t, fx, 2*time.Second) |
| + fx.FailNextMatching(http.MethodPut, http.StatusForbidden, func(_ string, b []byte) bool { return bytes.Contains(b, []byte("carlos_release")) }) |
| + if _, err := lease.AcquireHATTL(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{}, time.Second); err == nil { |
| + t.Fatal("late ack accepted") |
| + } |
| + fx.FailNextMatching(http.MethodPut, http.StatusForbidden, func(_ string, b []byte) bool { return bytes.Contains(b, []byte("carlos_release")) }) |
| + before := len(fx.Requests()) |
| + _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{}) |
| + var oe *lease.ObligationError |
| + if !errors.As(err, &oe) { |
| + t.Fatal(err) |
| + } |
| + if r := fx.Requests()[before:]; !slices.Equal(r, []string{"PUT instances/h/lock.json"}) { |
| + t.Fatalf("%v", r) |
| + } |
| + if len(lease.PendingObligations()) != 1 { |
| + t.Fatal("the obligation was dropped") |
| + } |
| +} |
diff --git a/internal/lease/lease.go b/internal/lease/lease.go| index 8b844f415..ac65cc2c8 100644 |
| --- a/internal/lease/lease.go |
| +++ b/internal/lease/lease.go |
| @@ -23,6 +23,8 @@ import ( |
| "github.com/benbjohnson/litestream" |
| lss3 "github.com/benbjohnson/litestream/s3" |
| + |
| + "github.com/carlosframework/platform/internal/hafresh" |
| ) |
| // LeaseTTL is deliberately long — 30× litestream's 30s default. Renewal runs |
| @@ -146,8 +148,15 @@ type Held struct { |
| // owed is the lease record a failed Release could not delete (#292). |
| // Release spends the handle either way; RetryRelease re-issues the |
| // same conditional delete until it lands or the lease is no longer |
| - // ours. Guarded by mu. |
| + // ours. Guarded by mu. An HA handle never owes a delete: its failed |
| + // releases are obligations in the package's store (owed.go). |
| owed *litestream.Lease |
| + // ha, view and base are an HA handle's (AcquireHA): the lock as it was |
| + // classified before the take, and the box, instance id and lifetime its |
| + // unclean releases name. |
| + ha bool |
| + view hafresh.View |
| + base hafresh.Marker |
| } |
| // Acquire claims the single-writer lease at s3://bucket/prefix/lock.json |
| @@ -193,15 +202,13 @@ func AcquireTTL(ctx context.Context, bucket, prefix, region string, ttl time.Dur |
| started := time.Now() |
| lease, err := createLease(ctx, client, leaser) |
| if errors.Is(err, errLockPresent) { |
| - lease, err = leaser.AcquireLease(ctx) |
| + // A lock is there. takeLegacy classifies it, as every acquire |
| + // does (legacytake.go): an HA-format lock is *HALockError and a |
| + // live one *HeldError, both with nothing written; an expired one |
| + // is taken conditional on the ETag it was read at. |
| + lease, err = takeLegacy(ctx, client, leaser) |
| } |
| if err != nil { |
| - // A *litestream.LeaseExistsError means someone else holds it — |
| - // re-surfaced as *HeldError so callers stay litestream-free. |
| - var lexists *litestream.LeaseExistsError |
| - if errors.As(err, &lexists) { |
| - return nil, fmt.Errorf("acquire lease: %w", &HeldError{Owner: lexists.Owner, ExpiresAt: lexists.ExpiresAt}) |
| - } |
| return nil, fmt.Errorf("acquire lease: %w", err) |
| } |
| rn := startRenewer(leaser, lease, started, marginForTTL(ttl)) |
diff --git a/internal/lease/legacytake.go b/internal/lease/legacytake.go| new file mode 100644 |
| index 000000000..6ac445018 |
| --- /dev/null |
| +++ b/internal/lease/legacytake.go |
| @@ -0,0 +1,165 @@ |
| +package lease |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + awss3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| + "github.com/benbjohnson/litestream" |
| + lss3 "github.com/benbjohnson/litestream/s3" |
| + |
| + "github.com/carlosframework/platform/internal/hafresh" |
| +) |
| + |
| +// HALockError is the legacy acquire's answer for an HA-format lock (a |
| +// release marker, or an owner with ;ha=1): nothing was written, whatever |
| +// the caller believed about the host. The caller takes the HA acquire |
| +// instead and treats the host as HA from then on. View is the lock as it |
| +// was classified. |
| +type HALockError struct{ View hafresh.View } |
| + |
| +func (e *HALockError) Error() string { |
| + return fmt.Sprintf("lease: the lock is HA-format (owner %q); the legacy acquire wrote nothing", e.View.Lock.Owner) |
| +} |
| + |
| +// errLockContended is classifyAndTake's answer when every round's |
| +// conditional write lost to another writer. |
| +var errLockContended = errors.New("lease: the lock changed under every conditional write") |
| + |
| +// takeRounds bounds classifyAndTake: a read, a decision and a conditional |
| +// write, again after each lost condition. |
| +const takeRounds = 3 |
| + |
| +// takeLegacy is the legacy acquire's read of a lock createLease found |
| +// present, in place of litestream's AcquireLease (which decodes an HA lock |
| +// leniently and would take an expired one): |
| +// |
| +// - an HA-format lock: *HALockError, nothing written; |
| +// - unexpired (leaseFree is false): *HeldError, nothing written; |
| +// - expired, or gone again since createLease: the next generation under |
| +// this leaser's owner, conditional on the exact ETag classified |
| +// (If-None-Match: * when it was gone). |
| +// |
| +// A lost condition re-reads and reclassifies, at most takeRounds times. |
| +func takeLegacy(ctx context.Context, client lss3.S3API, l *lss3.Leaser) (*litestream.Lease, error) { |
| + key := lss3.DefaultLeasePath |
| + if l.Path != "" { |
| + key = l.Path + "/" + lss3.DefaultLeasePath |
| + } |
| + lease, _, _, err := classifyAndTake(ctx, client, l.Bucket, key, l.Owner, l.TTL, func(v hafresh.View) error { |
| + if v.Absent { |
| + return nil |
| + } |
| + if v.HAOn() { |
| + return &HALockError{View: v} |
| + } |
| + if !leaseFree(v.Lock.ExpiresAt, time.Now()) { |
| + return &HeldError{Owner: v.Lock.Owner, ExpiresAt: v.Lock.ExpiresAt} |
| + } |
| + return nil |
| + }) |
| + return lease, err |
| +} |
| + |
| +// classifyAndTake is the one loop both acquires run (I1): read the lock |
| +// with its ETag, let decide classify that exact view, and write the next |
| +// lease conditional on it: If-None-Match: * on an absent lock, If-Match |
| +// on the classified ETag otherwise. decide returns nil to take the lock, |
| +// or the error to stop with (nothing is written then). A lost condition |
| +// (412, 409, or the classified lock gone) goes back to the read, at most |
| +// takeRounds times. |
| +// |
| +// The written lease is generation 1 on an absent lock and the classified |
| +// generation plus one otherwise, owned by owner, expiring ttl after the |
| +// write was sent. started is when the winning write was sent: the safe |
| +// deadline counts from it, never from its acknowledgement. |
| +func classifyAndTake(ctx context.Context, client lss3.S3API, bucket, key, owner string, ttl time.Duration, decide func(hafresh.View) error) (lease *litestream.Lease, view hafresh.View, started time.Time, err error) { |
| + for round := 0; round < takeRounds; round++ { |
| + view, err = readView(ctx, client, bucket, key) |
| + if err != nil { |
| + return nil, view, time.Time{}, err |
| + } |
| + if err := decide(view); err != nil { |
| + return nil, view, time.Time{}, err |
| + } |
| + next := &litestream.Lease{Generation: 1, Owner: owner} |
| + if !view.Absent { |
| + next.Generation = view.Lock.Generation + 1 |
| + } |
| + started = time.Now() |
| + next.ExpiresAt = started.Add(ttl) |
| + etag, err := putLock(ctx, client, bucket, key, next, view) |
| + if err != nil { |
| + if preconditionFailed(err) || (!view.Absent && lockAbsent(err)) { |
| + continue |
| + } |
| + return nil, view, time.Time{}, err |
| + } |
| + next.ETag = etag |
| + return next, view, started, nil |
| + } |
| + return nil, view, time.Time{}, fmt.Errorf("%w (%d rounds)", errLockContended, takeRounds) |
| +} |
| + |
| +// readView reads key with the ETag it was read at. Only S3's explicit |
| +// NoSuchKey is absence (lockAbsent); an unreadable or oversized body, a |
| +// lock with no expiry, or an answer with no ETag is an error. |
| +func readView(ctx context.Context, client lss3.S3API, bucket, key string) (hafresh.View, error) { |
| + out, err := client.GetObject(ctx, &awss3.GetObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)}) |
| + if err != nil { |
| + if lockAbsent(err) { |
| + return hafresh.View{Absent: true}, nil |
| + } |
| + return hafresh.View{}, fmt.Errorf("lease: read %s: %w", key, err) |
| + } |
| + defer out.Body.Close() |
| + body, err := io.ReadAll(io.LimitReader(out.Body, lockBodyLimit+1)) |
| + if err != nil { |
| + return hafresh.View{}, fmt.Errorf("lease: read %s: %w", key, err) |
| + } |
| + if len(body) > lockBodyLimit { |
| + return hafresh.View{}, fmt.Errorf("lease: %s is larger than a lock", key) |
| + } |
| + if out.ETag == nil || *out.ETag == "" { |
| + return hafresh.View{}, fmt.Errorf("lease: %s came back without an ETag", key) |
| + } |
| + v, err := hafresh.DecodeLock(body, *out.ETag) |
| + if err != nil { |
| + return hafresh.View{}, fmt.Errorf("lease: %s: %w", key, err) |
| + } |
| + return v, nil |
| +} |
| + |
| +// putLock writes next at key, conditional on the view it was decided |
| +// from, and returns the new ETag. |
| +func putLock(ctx context.Context, client lss3.S3API, bucket, key string, next *litestream.Lease, v hafresh.View) (string, error) { |
| + data, err := json.Marshal(next) |
| + if err != nil { |
| + return "", fmt.Errorf("marshal lock file: %w", err) |
| + } |
| + in := &awss3.PutObjectInput{ |
| + Bucket: aws.String(bucket), |
| + Key: aws.String(key), |
| + Body: bytes.NewReader(data), |
| + ContentType: aws.String("application/json"), |
| + } |
| + if v.Absent { |
| + in.IfNoneMatch = aws.String("*") |
| + } else { |
| + in.IfMatch = aws.String(v.ETag) |
| + } |
| + out, err := client.PutObject(ctx, in) |
| + if err != nil { |
| + return "", fmt.Errorf("put lock file: %w", err) |
| + } |
| + if out.ETag == nil || *out.ETag == "" { |
| + return "", fmt.Errorf("lease: the write of %s came back without an ETag", key) |
| + } |
| + return *out.ETag, nil |
| +} |
diff --git a/internal/lease/locktest/fixture.go b/internal/lease/locktest/fixture.go| index dce1527f0..e9ff25a84 100644 |
| --- a/internal/lease/locktest/fixture.go |
| +++ b/internal/lease/locktest/fixture.go |
| @@ -46,7 +46,16 @@ type LockFixture struct { |
| log []string |
| seen map[string]int // verb -> requests served so far |
| failAt map[string]map[int]int // verb -> request number -> status |
| + failWhen []matchFault |
| beforeWrite func(method, key string) |
| + afterWrite func(method, key string) |
| +} |
| + |
| +// matchFault fails the next request of verb whose key and body match. |
| +type matchFault struct { |
| + verb string |
| + status int |
| + match func(key string, body []byte) bool |
| } |
| // NewLockFixture starts the endpoint for the test's life and points the |
| @@ -142,6 +151,26 @@ func (f *LockFixture) BeforeWrite(hook func(method, key string)) { |
| f.beforeWrite = hook |
| } |
| +// FailNextMatching fails the next request of verb whose key and body |
| +// match with status, before it touches any object. Unlike FailNext it |
| +// does not count requests, so a request it does not match (a lease |
| +// renewal, say) cannot use it up. |
| +func (f *LockFixture) FailNextMatching(verb string, status int, match func(key string, body []byte) bool) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.failWhen = append(f.failWhen, matchFault{verb: verb, status: status, match: match}) |
| +} |
| + |
| +// AfterWrite runs hook after each PUT or DELETE has been decided (applied, |
| +// or refused by its condition) and before its answer is sent, with no |
| +// lock held: a hook that sleeps makes a write land on time and its |
| +// acknowledgement arrive late. A request a fault failed does not run it. |
| +func (f *LockFixture) AfterWrite(hook func(method, key string)) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.afterWrite = hook |
| +} |
| + |
| func (f *LockFixture) storeLocked(key string, body []byte) object { |
| sum := md5.Sum(body) |
| o := object{body: append([]byte(nil), body...), etag: `"` + hex.EncodeToString(sum[:]) + `"`, modified: time.Now().UTC()} |
| @@ -201,7 +230,16 @@ func (f *LockFixture) serve(w http.ResponseWriter, r *http.Request) { |
| f.seen[verb]++ |
| status, failing := f.failAt[verb][f.seen[verb]] |
| delete(f.failAt[verb], f.seen[verb]) |
| - hook := f.beforeWrite |
| + if !failing { |
| + for i, m := range f.failWhen { |
| + if m.verb == verb && m.match(key, body) { |
| + status, failing = m.status, true |
| + f.failWhen = append(f.failWhen[:i:i], f.failWhen[i+1:]...) |
| + break |
| + } |
| + } |
| + } |
| + hook, after := f.beforeWrite, f.afterWrite |
| f.mu.Unlock() |
| if failing { |
| s3error(w, status, codeFor(status)) |
| @@ -211,9 +249,15 @@ func (f *LockFixture) serve(w http.ResponseWriter, r *http.Request) { |
| s3error(w, http.StatusNotFound, "NoSuchBucket") |
| return |
| } |
| - if hook != nil && (r.Method == http.MethodPut || r.Method == http.MethodDelete) { |
| + write := r.Method == http.MethodPut || r.Method == http.MethodDelete |
| + if hook != nil && write { |
| hook(r.Method, key) |
| } |
| + if after != nil && write { |
| + // Deferred before the unlock, so it runs after it: the write is |
| + // applied and visible, and the answer waits for the hook. |
| + defer after(r.Method, key) |
| + } |
| f.mu.Lock() |
| defer f.mu.Unlock() |
diff --git a/internal/lease/locktest/fixture_test.go b/internal/lease/locktest/fixture_test.go| index cd3b6e7a4..24c7b2aa4 100644 |
| --- a/internal/lease/locktest/fixture_test.go |
| +++ b/internal/lease/locktest/fixture_test.go |
| @@ -88,3 +88,25 @@ func TestLockFixtureSpeaksConditionalS3(t *testing.T) { |
| t.Fatalf("hooked %q, want %q", hooked, want) |
| } |
| } |
| + |
| +// A matching fault fails only the request it matches, however many others |
| +// come first; the after-write hook runs once the write is visible and |
| +// holds back its answer. |
| +func TestLockFixtureMatchingFaultAndLateAck(t *testing.T) { |
| + f := NewLockFixture(t) |
| + f.FailNextMatching("PUT", 403, func(key string, body []byte) bool { return strings.Contains(string(body), "marker") }) |
| + if st, _, _ := do(t, f, "PUT", "/locks/a", nil, `renewal`); st != 200 { |
| + t.Fatalf("unmatched PUT %d", st) |
| + } |
| + if st, _, _ := do(t, f, "PUT", "/locks/a", nil, `marker`); st != 403 || string(f.objects["a"].body) != "renewal" { |
| + t.Fatalf("matched PUT %d", st) |
| + } |
| + if st, _, _ := do(t, f, "PUT", "/locks/a", nil, `marker`); st != 200 { |
| + t.Fatalf("the fault fired twice: %d", st) |
| + } |
| + var visible bool |
| + f.AfterWrite(func(m, k string) { visible = string(f.LockBody("p")) == "late" }) |
| + if st, _, _ := do(t, f, "PUT", "/locks/p/lock.json", nil, `late`); st != 200 || !visible { |
| + t.Fatalf("after-write hook: %d, write visible %v", st, visible) |
| + } |
| +} |
diff --git a/internal/lease/owed.go b/internal/lease/owed.go| new file mode 100644 |
| index 000000000..d4ad7c775 |
| --- /dev/null |
| +++ b/internal/lease/owed.go |
| @@ -0,0 +1,282 @@ |
| +package lease |
| + |
| +// Release obligations (r3.3): a release marker this process could not |
| +// write. They are lease's own, not the caller's. Each is on disk, fsynced, |
| +// before the *ObligationError that reports it is returned, so no caller |
| +// can drop one and a restart finds it again. An obligation ends only when |
| +// its marker PUT succeeds or answers 412 (the lease it released is no |
| +// longer ours). Expiry never ends one: an expired HA lock is not free to |
| +// another box, so the marker is what lets the host go. |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "runtime" |
| + "sort" |
| + "strings" |
| + "sync" |
| + "time" |
| +) |
| + |
| +// ErrObligationVoid is RetryObligation's answer when the marker's |
| +// condition fails: the lock changed since the lease it releases, so there |
| +// is nothing of ours left to release. |
| +var ErrObligationVoid = errors.New("lease: the marker's lease is no longer ours") |
| + |
| +// ErrNoObligationStore refuses an HA acquire before SetObligationDir: a |
| +// failed release of the lease it would take could not be kept. |
| +var ErrNoObligationStore = errors.New("lease: no obligation store; HA acquire refused") |
| + |
| +// Obligation is one owed marker write: Body to s3://Bucket/Key, If-Match |
| +// ETag, signed for Region. |
| +type Obligation struct { |
| + Bucket, Region, Key, ETag string |
| + Body []byte |
| +} |
| + |
| +// ObligationError reports a release whose marker write failed. The |
| +// obligation is already persisted (unless Err says it is pending in |
| +// memory only) and lease retries it: RetryPending, and AcquireHA before |
| +// it reads that key's lock. |
| +type ObligationError struct { |
| + Obligation Obligation |
| + Err error |
| +} |
| + |
| +func (e *ObligationError) Error() string { |
| + return fmt.Sprintf("lease: release marker owed for s3://%s/%s (If-Match %s): %v", e.Obligation.Bucket, e.Obligation.Key, e.Obligation.ETag, e.Err) |
| +} |
| + |
| +func (e *ObligationError) Unwrap() error { return e.Err } |
| + |
| +// Retry spacing for a pending obligation: a minute after it failed, |
| +// doubling to ten minutes. AcquireHA's retry of its own key ignores it. |
| +const ( |
| + owedFirstRetry = time.Minute |
| + owedMaxRetry = 10 * time.Minute |
| +) |
| + |
| +type owedEntry struct { |
| + o Obligation |
| + onDisk bool |
| + next time.Time // RetryPending skips it until then |
| + backoff time.Duration // the wait after the next failure is twice this, at most owedMaxRetry |
| +} |
| + |
| +// owed is the process's obligation store. dir is "" until SetObligationDir. |
| +var owed struct { |
| + mu sync.Mutex |
| + dir string |
| + pending map[string]*owedEntry // by obligationID |
| +} |
| + |
| +// owedNow is the store's clock (a test seam for the retry spacing). |
| +var owedNow = time.Now |
| + |
| +func obligationID(bucket, key string) string { |
| + sum := sha256.Sum256([]byte(bucket + "/" + key)) |
| + return hex.EncodeToString(sum[:]) |
| +} |
| + |
| +// obligationFile is an obligation's on-disk form. |
| +type obligationFile struct { |
| + V int `json:"v"` |
| + Bucket string `json:"bucket"` |
| + Region string `json:"region"` |
| + Key string `json:"key"` |
| + ETag string `json:"etag"` |
| + Body []byte `json:"body"` |
| +} |
| + |
| +// SetObligationDir names the directory obligations are kept in, creating |
| +// it, and loads every obligation already there as pending. The agent calls |
| +// it once at start, before any HA acquire. A file it cannot read is an |
| +// error, and the store stays unset: an obligation is never dropped |
| +// because it could not be read. |
| +func SetObligationDir(dir string) error { |
| + if dir == "" { |
| + return errors.New("lease: an empty obligation directory") |
| + } |
| + if err := os.MkdirAll(dir, 0o700); err != nil { |
| + return fmt.Errorf("lease: obligation directory: %w", err) |
| + } |
| + entries, err := os.ReadDir(dir) |
| + if err != nil { |
| + return fmt.Errorf("lease: obligation directory: %w", err) |
| + } |
| + loaded := map[string]Obligation{} |
| + for _, de := range entries { |
| + name := de.Name() |
| + if de.IsDir() || strings.HasPrefix(name, ".") || !strings.HasSuffix(name, ".json") { |
| + continue // a directory, or a temporary file a crash left before its rename |
| + } |
| + raw, err := os.ReadFile(filepath.Join(dir, name)) |
| + if err != nil { |
| + return fmt.Errorf("lease: obligation %s: %w", name, err) |
| + } |
| + var f obligationFile |
| + if err := json.Unmarshal(raw, &f); err != nil { |
| + return fmt.Errorf("lease: obligation %s: %w", name, err) |
| + } |
| + if f.V != 1 || f.Bucket == "" || f.Key == "" || f.ETag == "" || len(f.Body) == 0 || obligationID(f.Bucket, f.Key)+".json" != name { |
| + return fmt.Errorf("lease: obligation %s is not one this package wrote", name) |
| + } |
| + loaded[strings.TrimSuffix(name, ".json")] = Obligation{Bucket: f.Bucket, Region: f.Region, Key: f.Key, ETag: f.ETag, Body: f.Body} |
| + } |
| + owed.mu.Lock() |
| + defer owed.mu.Unlock() |
| + if owed.pending == nil { |
| + owed.pending = map[string]*owedEntry{} |
| + } |
| + for id, o := range loaded { |
| + if _, ok := owed.pending[id]; !ok { |
| + owed.pending[id] = &owedEntry{o: o, onDisk: true} |
| + } |
| + } |
| + owed.dir = dir |
| + return nil |
| +} |
| + |
| +func obligationStoreSet() bool { |
| + owed.mu.Lock() |
| + defer owed.mu.Unlock() |
| + return owed.dir != "" |
| +} |
| + |
| +// owe records o as pending, writes it to the store and returns the |
| +// *ObligationError reporting cause. A write that fails leaves it pending |
| +// in memory, and the error says so; RetryPending writes it again. |
| +func owe(o Obligation, cause error) error { |
| + owed.mu.Lock() |
| + defer owed.mu.Unlock() |
| + if owed.pending == nil { |
| + owed.pending = map[string]*owedEntry{} |
| + } |
| + e := &owedEntry{o: o, next: owedNow().Add(owedFirstRetry), backoff: owedFirstRetry} |
| + owed.pending[obligationID(o.Bucket, o.Key)] = e |
| + if err := persistLocked(o); err != nil { |
| + return &ObligationError{Obligation: o, Err: fmt.Errorf("%w; the obligation is pending in memory only, not on disk: %v", cause, err)} |
| + } |
| + e.onDisk = true |
| + return &ObligationError{Obligation: o, Err: cause} |
| +} |
| + |
| +// persistLocked writes o's file: a temporary file, fsynced, renamed into |
| +// place, and the directory fsynced. owed.mu is held. |
| +func persistLocked(o Obligation) error { |
| + if owed.dir == "" { |
| + return ErrNoObligationStore |
| + } |
| + data, err := json.Marshal(obligationFile{V: 1, Bucket: o.Bucket, Region: o.Region, Key: o.Key, ETag: o.ETag, Body: o.Body}) |
| + if err != nil { |
| + return err |
| + } |
| + tmp, err := os.CreateTemp(owed.dir, ".owed-*.tmp") |
| + if err != nil { |
| + return err |
| + } |
| + _, werr := tmp.Write(data) |
| + serr := tmp.Sync() |
| + cerr := tmp.Close() |
| + if err := errors.Join(werr, serr, cerr); err != nil { |
| + os.Remove(tmp.Name()) |
| + return err |
| + } |
| + if err := os.Rename(tmp.Name(), filepath.Join(owed.dir, obligationID(o.Bucket, o.Key)+".json")); err != nil { |
| + os.Remove(tmp.Name()) |
| + return err |
| + } |
| + return syncDir(owed.dir) |
| +} |
| + |
| +// discharge removes the obligation e, if it is still the pending one for |
| +// its key: its file first, then the entry. A file that cannot be removed |
| +// keeps the entry pending; its next retry answers 412 and tries again. |
| +func discharge(e *owedEntry) error { |
| + owed.mu.Lock() |
| + defer owed.mu.Unlock() |
| + id := obligationID(e.o.Bucket, e.o.Key) |
| + if owed.pending[id] != e { |
| + return nil // replaced by a newer obligation for the key, or already gone |
| + } |
| + if owed.dir != "" { |
| + if err := os.Remove(filepath.Join(owed.dir, id+".json")); err != nil && !errors.Is(err, os.ErrNotExist) { |
| + return fmt.Errorf("lease: remove settled obligation: %w", err) |
| + } |
| + if err := syncDir(owed.dir); err != nil { |
| + return fmt.Errorf("lease: remove settled obligation: %w", err) |
| + } |
| + } |
| + delete(owed.pending, id) |
| + return nil |
| +} |
| + |
| +// failed spaces e's next retry after a failed attempt. |
| +func failed(e *owedEntry) { |
| + owed.mu.Lock() |
| + defer owed.mu.Unlock() |
| + e.backoff = min(2*e.backoff, owedMaxRetry) |
| + if e.backoff <= 0 { |
| + e.backoff = owedFirstRetry |
| + } |
| + e.next = owedNow().Add(e.backoff) |
| +} |
| + |
| +func pendingFor(bucket, key string) *owedEntry { |
| + owed.mu.Lock() |
| + defer owed.mu.Unlock() |
| + return owed.pending[obligationID(bucket, key)] |
| +} |
| + |
| +// settle is one retry of e: discharged on success or ErrObligationVoid, |
| +// else spaced out and returned as its *ObligationError. |
| +func settle(ctx context.Context, e *owedEntry) error { |
| + err := RetryObligation(ctx, e.o) |
| + if err == nil || errors.Is(err, ErrObligationVoid) { |
| + return discharge(e) |
| + } |
| + failed(e) |
| + return &ObligationError{Obligation: e.o, Err: err} |
| +} |
| + |
| +// RetryObligation writes o's marker again, If-Match its ETag: nil once it |
| +// lands, ErrObligationVoid if the condition fails (412), or the error. It |
| +// never reads the lock's expiry. It does not change the pending set; |
| +// RetryPending and AcquireHA do. |
| +func RetryObligation(ctx context.Context, o Obligation) error { |
| + client, _, err := newLeaserClient(ctx, o.Region) |
| + if err != nil { |
| + return err |
| + } |
| + return putMarker(ctx, client, o) |
| +} |
| + |
| +// PendingObligations is every obligation not yet settled, by key. |
| +func PendingObligations() []Obligation { |
| + owed.mu.Lock() |
| + defer owed.mu.Unlock() |
| + out := make([]Obligation, 0, len(owed.pending)) |
| + for _, e := range owed.pending { |
| + out = append(out, e.o) |
| + } |
| + sort.Slice(out, func(i, j int) bool { return out[i].Bucket+"/"+out[i].Key < out[j].Bucket+"/"+out[j].Key }) |
| + return out |
| +} |
| + |
| +func syncDir(dir string) error { |
| + if runtime.GOOS == "windows" { |
| + return nil // no directory fsync there; the agent that relies on this runs on Linux |
| + } |
| + d, err := os.Open(dir) |
| + if err != nil { |
| + return err |
| + } |
| + serr := d.Sync() |
| + return errors.Join(serr, d.Close()) |
| +} |
diff --git a/internal/lease/release.go b/internal/lease/release.go| new file mode 100644 |
| index 000000000..20bcf5e79 |
| --- /dev/null |
| +++ b/internal/lease/release.go |
| @@ -0,0 +1,85 @@ |
| +package lease |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + awss3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| + "github.com/benbjohnson/litestream" |
| + lss3 "github.com/benbjohnson/litestream/s3" |
| + |
| + "github.com/carlosframework/platform/internal/hafresh" |
| +) |
| + |
| +// releaseWithMarker is the one HA release. lease never deletes an HA lock: |
| +// it rewrites it as a release marker, MarkerBody(cur.Generation, m), If-Match |
| +// cur's ETag. The caller has stopped the renewer and passes the lease it |
| +// returned. |
| +// |
| +// - written: nil; |
| +// - 412: nil (the lock changed since cur; someone else holds it now); |
| +// - anything else: the obligation is persisted (owe) and returned as |
| +// *ObligationError. |
| +func releaseWithMarker(ctx context.Context, leaser *lss3.Leaser, region string, cur *litestream.Lease, m hafresh.Marker) error { |
| + if cur == nil || cur.ETag == "" { |
| + return errors.New("lease: no lease to release") |
| + } |
| + if m.V == 0 { |
| + m.V = 1 |
| + } |
| + if m.At.IsZero() { |
| + m.At = time.Now().UTC() |
| + } |
| + body, err := hafresh.MarkerBody(cur.Generation, m) |
| + if err != nil { |
| + return err |
| + } |
| + key := lss3.DefaultLeasePath |
| + if leaser.Path != "" { |
| + key = leaser.Path + "/" + lss3.DefaultLeasePath |
| + } |
| + o := Obligation{Bucket: leaser.Bucket, Region: region, Key: key, ETag: cur.ETag, Body: body} |
| + err = putMarker(ctx, leaser.Client(), o) |
| + if err == nil || errors.Is(err, ErrObligationVoid) { |
| + return nil |
| + } |
| + return owe(o, err) |
| +} |
| + |
| +// putMarker is one conditional write of an obligation's marker. |
| +func putMarker(ctx context.Context, client lss3.S3API, o Obligation) error { |
| + _, err := client.PutObject(ctx, &awss3.PutObjectInput{ |
| + Bucket: aws.String(o.Bucket), |
| + Key: aws.String(o.Key), |
| + Body: bytes.NewReader(o.Body), |
| + ContentType: aws.String("application/json"), |
| + IfMatch: aws.String(o.ETag), |
| + }) |
| + if err == nil { |
| + return nil |
| + } |
| + if conditionFailed(err) { |
| + return fmt.Errorf("%w: %w", ErrObligationVoid, err) |
| + } |
| + return fmt.Errorf("lease: write release marker: %w", err) |
| +} |
| + |
| +// conditionFailed is a 412 only. A 409 (two conditional writes racing) |
| +// says nothing about whose the lock is, so the marker is retried. |
| +func conditionFailed(err error) bool { |
| + code, status := apiCode(err) |
| + return code == "PreconditionFailed" || status == http.StatusPreconditionFailed |
| +} |
| + |
| +// uncleanMarker is the marker every release but the clean one writes: the |
| +// handle's base (box, instance id, lifetime), Clean false, at txid. |
| +func uncleanMarker(base hafresh.Marker, txid uint64) hafresh.Marker { |
| + m := base |
| + m.V, m.TXID, m.FilesGen, m.Clean, m.At = 1, txid, "", false, time.Now().UTC() |
| + return m |
| +} |