carlos / platform Public

region-ha p1b-1: termfence.Confirmer, one cached describe per owner

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 779775e55a1269b160f7e2fea01c4be3771e4f80 parent 03accb0
2 files changed, +404 −0
  • internal/termfence/confirm.go +191 −0
  • internal/termfence/confirm_test.go +213 −0
diff --git a/internal/termfence/confirm.go b/internal/termfence/confirm.go
new file mode 100644
index 000000000..0c61ffb0a
--- /dev/null
+++ b/internal/termfence/confirm.go
@@ -0,0 +1,191 @@
+package termfence
+
+import (
+ "context"
+ "errors"
+ "log"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/boxid"
+)
+
+const (
+ // ConfirmPositiveTTL keeps a "terminated" answer: an instance does not
+ // come back, and AWS forgets it within about an hour.
+ ConfirmPositiveTTL = 24 * time.Hour
+ // ConfirmNegativeTTL keeps every other answer, errors included, so a
+ // caller that asks every tick makes about one describe in ten seconds.
+ ConfirmNegativeTTL = 10 * time.Second
+)
+
+// SameAccountTerminated is Verify's identity and state check for a caller
+// that holds no roster entry for the instance: it is another box of this
+// box's own account and region, so self supplies both. It returns nil only
+// for a describe reply that names iid, in self's account and region, in the
+// state terminated. Every refusal wraps ErrNotEvidence.
+func SameAccountTerminated(self boxid.Cloud, iid string, o Observation) error {
+ switch {
+ case !self.Complete():
+ return refuse("this box has no proven cloud identity")
+ case iid == "":
+ return refuse("no instance to confirm")
+ case iid == self.InstanceID:
+ return refuse("%s is this box", iid)
+ case o.Via != ViaDescribe:
+ return refuse("source %q is not a describe", o.Via)
+ case !o.Found:
+ return refuse("the describe said nothing about %s; absence is not termination", iid)
+ case o.InstanceID != iid:
+ return refuse("observed %s, asked about %s", o.InstanceID, iid)
+ case o.Account != self.Account:
+ return refuse("observed in account %q, this box is in %q", o.Account, self.Account)
+ case o.Region != self.Region:
+ return refuse("observed in region %q, this box is in %q", o.Region, self.Region)
+ case o.State != stateTerminated:
+ return refuse("state is %q; only %q counts", o.State, stateTerminated)
+ }
+ return nil
+}
+
+// Confirmer answers whether another box's instance is terminated, asking
+// EC2 in this box's own account and region and nowhere else. One describe
+// per instance id per TTL; the cache lives as long as the process.
+type Confirmer struct {
+ // API builds the EC2 client for region. It is called once, on the
+ // first describe, and the client is kept.
+ API func(ctx context.Context, region string) (EC2, error)
+ // Self is this box's proven cloud identity.
+ Self func() boxid.Cloud
+ // Now is time.Now when nil.
+ Now func() time.Time
+ // Logf is log.Printf when nil.
+ Logf func(string, ...any)
+
+ mu sync.Mutex
+ api EC2
+ cache map[string]confirmed
+ evident map[string]bool // instances whose first evidence is logged
+}
+
+type confirmed struct {
+ until time.Time
+ yes bool
+ err error
+}
+
+func (c *Confirmer) now() time.Time {
+ if c.Now != nil {
+ return c.Now()
+ }
+ return time.Now()
+}
+
+func (c *Confirmer) logf(format string, a ...any) {
+ if c.Logf != nil {
+ c.Logf(format, a...)
+ return
+ }
+ log.Printf(format, a...)
+}
+
+// Terminated reports whether the EC2 instance iid is terminated. It
+// answers false without error for this box's own instance and for anything
+// a describe does not prove: another state, another account or region, an
+// instance AWS no longer lists. A describe failure, or a Self that is not
+// a complete identity, is an error.
+func (c *Confirmer) Terminated(ctx context.Context, iid string) (bool, error) {
+ self := c.Self()
+ if !self.Complete() {
+ return false, errors.New("termfence: this box's cloud identity is incomplete")
+ }
+ if iid == "" || iid == self.InstanceID {
+ return false, nil
+ }
+ if e, ok := c.cached(iid); ok {
+ return e.yes, e.err
+ }
+ e := c.ask(ctx, self, iid)
+ ttl := ConfirmNegativeTTL
+ if e.yes {
+ ttl = ConfirmPositiveTTL
+ }
+ e.until = c.now().Add(ttl)
+ c.mu.Lock()
+ if c.cache == nil {
+ c.cache = map[string]confirmed{}
+ }
+ c.cache[iid] = e
+ c.mu.Unlock()
+ return e.yes, e.err
+}
+
+func (c *Confirmer) cached(iid string) (confirmed, bool) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ e, ok := c.cache[iid]
+ if !ok || !c.now().Before(e.until) {
+ return confirmed{}, false
+ }
+ return e, true
+}
+
+// client returns the kept client, building it on first use. The mutex is
+// not held across API: two first callers may each build one, and the first
+// to finish is kept.
+func (c *Confirmer) client(ctx context.Context, region string) (EC2, error) {
+ c.mu.Lock()
+ api := c.api
+ c.mu.Unlock()
+ if api != nil {
+ return api, nil
+ }
+ api, err := c.API(ctx, region)
+ if err != nil {
+ return nil, err
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.api == nil {
+ c.api = api
+ }
+ return c.api, nil
+}
+
+// ask makes one describe and decides. The mutex is not held across it.
+func (c *Confirmer) ask(ctx context.Context, self boxid.Cloud, iid string) confirmed {
+ api, err := c.client(ctx, self.Region)
+ if err != nil {
+ c.logf("termfence: describe %s: %v", iid, err)
+ return confirmed{err: err}
+ }
+ out, err := DescribeInstance(ctx, api, boxid.Cloud{Provider: "aws", Account: self.Account, Region: self.Region, InstanceID: iid})
+ if err != nil {
+ c.logf("termfence: describe %s: %v", iid, err)
+ return confirmed{err: err}
+ }
+ o := FromDescribe(out, iid, self.Region)
+ if o.Found {
+ c.logf("termfence: describe %s: %s", iid, o.State)
+ } else {
+ c.logf("termfence: describe %s: not found", iid)
+ }
+ switch err := SameAccountTerminated(self, iid, o); {
+ case err == nil:
+ c.mu.Lock()
+ first := !c.evident[iid]
+ if c.evident == nil {
+ c.evident = map[string]bool{}
+ }
+ c.evident[iid] = true
+ c.mu.Unlock()
+ if first {
+ c.logf("termfence: %s confirmed terminated (first evidence, request %s)", iid, o.RequestID)
+ }
+ return confirmed{yes: true}
+ case errors.Is(err, ErrNotEvidence):
+ return confirmed{}
+ default:
+ return confirmed{err: err}
+ }
+}
diff --git a/internal/termfence/confirm_test.go b/internal/termfence/confirm_test.go
new file mode 100644
index 000000000..67a729d21
--- /dev/null
+++ b/internal/termfence/confirm_test.go
@@ -0,0 +1,213 @@
+package termfence
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/service/ec2"
+ "github.com/aws/aws-sdk-go-v2/service/ec2/types"
+
+ "github.com/carlosframework/platform/internal/boxid"
+)
+
+var confirmSelf = boxid.Cloud{Provider: "aws", Account: "111122223333", Region: "eu-west-1", InstanceID: "i-a"}
+
+type confirmRig struct {
+ f *fakeEC2
+ c *Confirmer
+ mu sync.Mutex
+ logs []string
+ at time.Time
+ apis int
+}
+
+func newConfirmRig(f *fakeEC2) *confirmRig {
+ r := &confirmRig{f: f, at: time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC)}
+ r.c = &Confirmer{
+ API: func(context.Context, string) (EC2, error) { r.apis++; return r.f, nil },
+ Self: func() boxid.Cloud { return confirmSelf },
+ Now: func() time.Time { return r.at },
+ Logf: func(format string, a ...any) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.logs = append(r.logs, strings.TrimSpace(fmt.Sprintf(format, a...)))
+ },
+ }
+ return r
+}
+
+func (r *confirmRig) count(prefix string) int {
+ n := 0
+ for _, l := range r.logs {
+ if strings.HasPrefix(l, prefix) {
+ n++
+ }
+ }
+ return n
+}
+
+func TestConfirmTerminatedOwner(t *testing.T) {
+ r := newConfirmRig(&fakeEC2{out: withRequestID(describe("111122223333", "i-b", types.InstanceStateNameTerminated), "req-1")})
+ ok, err := r.c.Terminated(context.Background(), "i-b")
+ if err != nil || !ok {
+ t.Fatalf("got %v, %v", ok, err)
+ }
+ if len(r.f.regions) != 1 || r.f.regions[0] != "eu-west-1" || len(r.f.ids[0]) != 1 || r.f.ids[0][0] != "i-b" {
+ t.Fatalf("called in %v for %v", r.f.regions, r.f.ids)
+ }
+ if r.count("termfence: describe i-b: terminated") != 1 {
+ t.Fatalf("logs %q", r.logs)
+ }
+ if r.count("termfence: i-b confirmed terminated (first evidence, request req-1)") != 1 || len(r.logs) != 2 {
+ t.Fatalf("logs %q", r.logs)
+ }
+}
+
+func TestConfirmStatesOtherThanTerminated(t *testing.T) {
+ for _, st := range []types.InstanceStateName{
+ types.InstanceStateNameRunning, types.InstanceStateNameStopped, types.InstanceStateNameStopping,
+ types.InstanceStateNameShuttingDown, types.InstanceStateNamePending,
+ } {
+ r := newConfirmRig(&fakeEC2{out: describe("111122223333", "i-b", st)})
+ ok, err := r.c.Terminated(context.Background(), "i-b")
+ if ok || err != nil {
+ t.Fatalf("%s: got %v, %v", st, ok, err)
+ }
+ if r.count("termfence: describe i-b: "+string(st)) != 1 || r.count("termfence: i-b confirmed") != 0 {
+ t.Fatalf("%s: logs %q", st, r.logs)
+ }
+ }
+ r := newConfirmRig(&fakeEC2{out: &ec2.DescribeInstancesOutput{}})
+ ok, err := r.c.Terminated(context.Background(), "i-b")
+ if ok || err != nil {
+ t.Fatalf("empty reply: got %v, %v", ok, err)
+ }
+ if r.count("termfence: describe i-b: not found") != 1 {
+ t.Fatalf("logs %q", r.logs)
+ }
+}
+
+func TestConfirmRefusesOtherAccountOrRegion(t *testing.T) {
+ r := newConfirmRig(&fakeEC2{out: describe("999999999999", "i-b", types.InstanceStateNameTerminated)})
+ ok, err := r.c.Terminated(context.Background(), "i-b")
+ if ok || err != nil {
+ t.Fatalf("other account: got %v, %v", ok, err)
+ }
+ if len(r.f.regions) != 1 || r.f.regions[0] != "eu-west-1" {
+ t.Fatalf("called in %v", r.f.regions)
+ }
+ if r.count("termfence: i-b confirmed") != 0 {
+ t.Fatalf("logs %q", r.logs)
+ }
+ // The identity check itself, without a describe.
+ good := FromDescribe(describe("111122223333", "i-b", types.InstanceStateNameTerminated), "i-b", "eu-west-1")
+ if err := SameAccountTerminated(confirmSelf, "i-b", good); err != nil {
+ t.Fatal(err)
+ }
+ bad := map[string]Observation{}
+ o := good
+ o.Region = "us-east-1"
+ bad["region"] = o
+ o = good
+ o.Via = ViaEvent
+ bad["event"] = o
+ o = good
+ o.InstanceID = "i-c"
+ bad["instance"] = o
+ o = good
+ o.Found = false
+ bad["notfound"] = o
+ for name, o := range bad {
+ if err := SameAccountTerminated(confirmSelf, "i-b", o); !errors.Is(err, ErrNotEvidence) {
+ t.Fatalf("%s: %v", name, err)
+ }
+ }
+ if err := SameAccountTerminated(confirmSelf, "i-a", good); !errors.Is(err, ErrNotEvidence) {
+ t.Fatalf("self: %v", err)
+ }
+}
+
+func TestConfirmRefusesSelfAndIncompleteIdentity(t *testing.T) {
+ r := newConfirmRig(&fakeEC2{out: describe("111122223333", "i-a", types.InstanceStateNameTerminated)})
+ ok, err := r.c.Terminated(context.Background(), "i-a")
+ if ok || err != nil || len(r.f.regions) != 0 {
+ t.Fatalf("self: got %v, %v, %d describes", ok, err, len(r.f.regions))
+ }
+ r.c.Self = func() boxid.Cloud { c := confirmSelf; c.Account = ""; return c }
+ ok, err = r.c.Terminated(context.Background(), "i-b")
+ if ok || err == nil || len(r.f.regions) != 0 {
+ t.Fatalf("incomplete: got %v, %v, %d describes", ok, err, len(r.f.regions))
+ }
+}
+
+func TestConfirmCachesPositiveForADay(t *testing.T) {
+ r := newConfirmRig(&fakeEC2{out: describe("111122223333", "i-b", types.InstanceStateNameTerminated)})
+ t0 := r.at
+ for _, at := range []time.Duration{0, 23 * time.Hour} {
+ r.at = t0.Add(at)
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); !ok || err != nil {
+ t.Fatalf("at %v: %v, %v", at, ok, err)
+ }
+ }
+ if len(r.f.regions) != 1 || r.count("termfence: i-b confirmed") != 1 {
+ t.Fatalf("describes %d, logs %q", len(r.f.regions), r.logs)
+ }
+ r.at = t0.Add(24*time.Hour + time.Second)
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); !ok || err != nil {
+ t.Fatalf("after a day: %v, %v", ok, err)
+ }
+ if len(r.f.regions) != 2 || r.count("termfence: i-b confirmed") != 1 || r.count("termfence: describe i-b") != 2 {
+ t.Fatalf("describes %d, logs %q", len(r.f.regions), r.logs)
+ }
+ if r.apis != 1 {
+ t.Fatalf("API built %d times", r.apis)
+ }
+}
+
+func TestConfirmErrorIsCachedBriefly(t *testing.T) {
+ boom := errors.New("throttled")
+ r := newConfirmRig(&fakeEC2{err: boom})
+ t0 := r.at
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); ok || !errors.Is(err, boom) {
+ t.Fatalf("got %v, %v", ok, err)
+ }
+ if r.count("termfence: describe i-b: throttled") != 1 {
+ t.Fatalf("logs %q", r.logs)
+ }
+ r.at = t0.Add(5 * time.Second)
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); ok || !errors.Is(err, boom) {
+ t.Fatalf("cached: got %v, %v", ok, err)
+ }
+ if len(r.f.regions) != 1 {
+ t.Fatalf("describes %d", len(r.f.regions))
+ }
+ r.at = t0.Add(11 * time.Second)
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); ok || !errors.Is(err, boom) {
+ t.Fatalf("after ttl: got %v, %v", ok, err)
+ }
+ if len(r.f.regions) != 2 {
+ t.Fatalf("describes %d", len(r.f.regions))
+ }
+}
+
+func TestConfirmNegativeCachedTenSeconds(t *testing.T) {
+ r := newConfirmRig(&fakeEC2{out: describe("111122223333", "i-b", types.InstanceStateNameRunning)})
+ t0 := r.at
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); ok || err != nil {
+ t.Fatalf("got %v, %v", ok, err)
+ }
+ r.at = t0.Add(9 * time.Second)
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); ok || err != nil || len(r.f.regions) != 1 {
+ t.Fatalf("cached: got %v, %v, %d describes", ok, err, len(r.f.regions))
+ }
+ r.f.out = describe("111122223333", "i-b", types.InstanceStateNameTerminated)
+ r.at = t0.Add(11 * time.Second)
+ if ok, err := r.c.Terminated(context.Background(), "i-b"); !ok || err != nil || len(r.f.regions) != 2 {
+ t.Fatalf("after ttl: got %v, %v, %d describes", ok, err, len(r.f.regions))
+ }
+}