ha: add bounded termination consumer lifecycle and SQS adapter
Separate queue startup acknowledgment from inventory and recovery. Validate the configured queue and event hints, retain only SDK method values, and bound receive retries and shutdown.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
go.mod+1 −0go.sum+2 −0internal/awsterminations/queue.go+144 −0internal/awsterminations/queue_test.go+102 −0internal/hadeparture/consumer.go+183 −0internal/hadeparture/consumer_test.go+251 −0internal/hadeparture/types.go+52 −0
Intent
<task-notification> <task-id>bkz2g7fap</task-id> <tool-use-id>toolu_01GNeCFXW4R8kHheL5hbBiJP</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22c9817b-87ae-432b-b6d2-3ebbc209af38/tasks/bkz2g7fap.output</output-file> <status>completed</status> <summary>Background command "Wait for B2 fix round 1" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>a521de241f84b37f1</task-id> <tool-use-id>toolu_01YRVdEhK1vDJjsv9NAMoY2W</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22c9817b-87ae-432b-b6d2-3ebbc209af38/tasks/a521de241f84b37f1.output</output-file> <status>completed</status> <summary>Agent "Opus review Task B2" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Task quality: Approved.** All seven findings in fix round 1 are addressed. The fix diff adds no new Critical or Important issues (0 Critical, 0 Important). 1. **Important 1, ADDRESSED.** - **Fix:** receipts are now keyed by departure, host, lifetime and binding, and the old table is migrated in one transaction (`internal/registry/ha_departures.go`, `migrateHAAdoptions`). An import looks only at the current binding. Phase updates compare the caller's binding as well as the current one, so an old receipt cannot finalize a new binding. - **Tests:** `TestHAAdoptReceiptCannotCrossRouteRecreation`, `TestHAAdoptReceiptMigration` and `TestHAAdoptRecreatedRoute` (covers both route recreation and a Pair change). 2. **Important 2, ADDRESSED.** - **Fix:** ordinary restore (`hostfiles.ImportWake`) is back to checking only version, host and replication. It fills in a missing registration inside the transaction (`internal/hostfiles/wake.go`, `internal/registry/ha_departures.go`). Adoption keeps the strict checks, and errors now name the host, field and value. - **Tests:** `TestImportWakeLegacyRows`, `TestImportWakeValidationFields` and `TestHAOrdinaryRestoreLegacyWake`. 3. **Minor 1, ADDRESSED.** - **Fix:** the visitor path now just advances the revision unconditionally (`internal/activator/hawake.go:339-343`). There is no compare-and-swap and the basis is left alone. - **Test:** `TestHAVisitorRefusalPreservesAdoption`. 4. **Minor 2, ADDRESSED.** - **Fix:** the `DutyStore` interface gained `Get`, `HADuty` and `BindHADuty` (`internal/activator/haduties.go:86-89`). Every store now goes through the shared lifetime check, and the type assertion on the concrete registry is gone. - **Test:** `TestHADutyStoreValidatesWrappedLifetime`. 5. **Minor 3, ADDRESSED.** `TestHAAdoptRemoteParity` now sends every duty and adoption method through the real remote transport. That includes stale revisions, all four phase changes and the error sentinels. 6. **Minor 4, ADDRESSED.** The refusal cases in `TestHAAdoptAuthority` now also check the stored state. The basis is not `adopted`. Marker failures leave the phase at `marker_pending`, and held or exact-expiry refusals write no receipt. 7. **Minor 5, ADDRESSED.** - **Test:** `interruptAdoptionBeforeAcquire` stops the real `AdoptHost` after the `acquiring` phase is saved. It checks that no write was sent and the departed lock is unchanged. - **Test:** `TestHAAdoptRestartAcquiringDepartedLock` then reopens the database and gets `Adopted`. **New Minors:** - Adoption still refuses the legacy wake shape that ordinary restore now accepts. A departed host like that stays `Deferred` with a named error on every scan, so B3/B4 should treat it as a per-host unsupported reason and page. - Every registry open now takes a brief write lock for the receipt migration check. - A missing registration is filled in again on each restore until the next publish. Report: `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b3b-duties/.superpowers/sdd/2026-11-03-region-ha-p1b3b-duties/task-B2-review-r2.md`</result> <usage><subagent_tokens>203191</subagent_tokens><tool_uses>6</tool_uses><duration_ms>90421</duration_ms></usage> </task-notification>
diff --git a/go.mod b/go.mod| index 1190f0976..e485e3252 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -16,6 +16,7 @@ require ( |
| github.com/aws/aws-sdk-go-v2/service/route53 v1.64.1 |
| github.com/aws/aws-sdk-go-v2/service/s3 v1.105.0 |
| github.com/aws/aws-sdk-go-v2/service/sesv2 v1.66.6 |
| + github.com/aws/aws-sdk-go-v2/service/sqs v1.42.19 |
| github.com/aws/aws-sdk-go-v2/service/ssm v1.74.0 |
| github.com/aws/aws-sdk-go-v2/service/sts v1.45.6 |
| github.com/aws/smithy-go v1.28.1 |
diff --git a/go.sum b/go.sum| index 68e971383..f90cabcb9 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -72,6 +72,8 @@ github.com/aws/aws-sdk-go-v2/service/signin v1.0.4 h1:HpI7aMmJ+mm1wkSHIA2t5EaFFv |
| github.com/aws/aws-sdk-go-v2/service/signin v1.0.4/go.mod h1:C5RdGMYGlfM0gYq/tifqgn4EbyX99V15P2V3R+VHbQU= |
| github.com/aws/aws-sdk-go-v2/service/sns v1.43.0 h1:VPYjwn0BoX34hb44OT8T+Ikgn4NzsN7fHetaHaevsDc= |
| github.com/aws/aws-sdk-go-v2/service/sns v1.43.0/go.mod h1:I1vnLPvvi9KBqxddu8nJ4vktoPJvaIG05UmjBD9sqm8= |
| +github.com/aws/aws-sdk-go-v2/service/sqs v1.42.19 h1:Wtx5NE/VM+PImR21szw+NWt0sx3pgdzqa7M+doup/NI= |
| +github.com/aws/aws-sdk-go-v2/service/sqs v1.42.19/go.mod h1:OG0Y3TgC+IeM++ngh+IcEkN24ruGsmRiAP8GUsOhMW8= |
| github.com/aws/aws-sdk-go-v2/service/ssm v1.74.0 h1:11o/Z2uQatZTTWrkwN4MMPjhcVGnVQtLra5Md1tSSq0= |
| github.com/aws/aws-sdk-go-v2/service/ssm v1.74.0/go.mod h1:uF4ifVWSlieuvF0ZSy9m6flJJojvWuEu80pJIO3UJ0U= |
| github.com/aws/aws-sdk-go-v2/service/sso v1.30.8 h1:aM/Q24rIlS3bRAhTyFurowU8A0SMyGDtEOY/l/s/1Uw= |
diff --git a/internal/awsterminations/queue.go b/internal/awsterminations/queue.go| new file mode 100644 |
| index 000000000..f73c74cae |
| --- /dev/null |
| +++ b/internal/awsterminations/queue.go |
| @@ -0,0 +1,144 @@ |
| +package awsterminations |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net/url" |
| + "regexp" |
| + "strings" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/service/sqs" |
| + "github.com/aws/aws-sdk-go-v2/service/sqs/types" |
| + "github.com/carlosframework/platform/internal/boxid" |
| + "github.com/carlosframework/platform/internal/hadeparture" |
| + "github.com/carlosframework/platform/internal/termfence" |
| +) |
| + |
| +var ErrQueueIdentity = errors.New("ha_queue_identity_invalid") |
| +var ErrHint = errors.New("ha_termination_hint_invalid") |
| +var iidPattern = regexp.MustCompile(`^i-([0-9a-f]{8}|[0-9a-f]{17})$`) |
| +var accountPattern = regexp.MustCompile(`^[0-9]{12}$`) |
| +var queuePattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,80}$`) |
| + |
| +type Queue struct { |
| + url string |
| + receive func(context.Context, *sqs.ReceiveMessageInput, ...func(*sqs.Options)) (*sqs.ReceiveMessageOutput, error) |
| + delete func(context.Context, *sqs.DeleteMessageInput, ...func(*sqs.Options)) (*sqs.DeleteMessageOutput, error) |
| +} |
| + |
| +// New retains method values, so linking the adapter does not retain every SQS |
| +// method. The caller supplies the combined five-second initialization context. |
| +func New(ctx context.Context, cfg aws.Config, rawURL string, self boxid.Cloud) (*Queue, error) { |
| + u, err := url.Parse(rawURL) |
| + if err != nil || !self.Complete() || !accountPattern.MatchString(self.Account) || !iidPattern.MatchString(self.InstanceID) || cfg.Region != self.Region { |
| + return nil, ErrQueueIdentity |
| + } |
| + suffix, partition := "amazonaws.com", "aws" |
| + if strings.HasPrefix(self.Region, "cn-") { |
| + suffix = "amazonaws.com.cn" |
| + partition = "aws-cn" |
| + } else if strings.HasPrefix(self.Region, "us-gov-") { |
| + partition = "aws-us-gov" |
| + } |
| + parts := strings.Split(u.Path, "/") |
| + if u.Scheme != "https" || u.Host != "sqs."+self.Region+"."+suffix || u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || u.RawPath != "" || len(parts) != 3 || parts[1] != self.Account || !queuePattern.MatchString(parts[2]) { |
| + return nil, ErrQueueIdentity |
| + } |
| + cfg.RetryMaxAttempts = 1 |
| + client := sqs.NewFromConfig(cfg) |
| + attrs, err := client.GetQueueAttributes(ctx, &sqs.GetQueueAttributesInput{QueueUrl: aws.String(rawURL), AttributeNames: []types.QueueAttributeName{types.QueueAttributeNameQueueArn}}) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if attrs == nil || attrs.Attributes["QueueArn"] != "arn:"+partition+":sqs:"+self.Region+":"+self.Account+":"+parts[2] { |
| + return nil, ErrQueueIdentity |
| + } |
| + return &Queue{url: rawURL, receive: client.ReceiveMessage, delete: client.DeleteMessage}, nil |
| +} |
| +func (q *Queue) Receive(ctx context.Context, wait time.Duration) ([]hadeparture.Message, error) { |
| + if wait != hadeparture.LongPoll { |
| + return nil, errors.New("ha_queue_poll_invalid") |
| + } |
| + out, err := q.receive(ctx, &sqs.ReceiveMessageInput{QueueUrl: aws.String(q.url), MaxNumberOfMessages: 1, WaitTimeSeconds: 20, VisibilityTimeout: 120}) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if out == nil { |
| + return nil, errors.New("ha_queue_response_missing") |
| + } |
| + messages := make([]hadeparture.Message, 0, len(out.Messages)) |
| + for _, m := range out.Messages { |
| + messages = append(messages, hadeparture.Message{ID: aws.ToString(m.MessageId), Receipt: aws.ToString(m.ReceiptHandle), Body: []byte(aws.ToString(m.Body))}) |
| + } |
| + return messages, nil |
| +} |
| +func (q *Queue) Delete(ctx context.Context, receipt string) error { |
| + if receipt == "" { |
| + return errors.New("ha_queue_receipt_missing") |
| + } |
| + _, err := q.delete(ctx, &sqs.DeleteMessageInput{QueueUrl: aws.String(q.url), ReceiptHandle: aws.String(receipt)}) |
| + return err |
| +} |
| + |
| +// Hint returns an iid to resolve through verified immutable records. Neither an |
| +// accepted event nor its receipt proves termination or permits adoption. |
| +func Hint(body []byte, self boxid.Cloud) (string, error) { |
| + if len(body) > hadeparture.MaxBodyBytes || !self.Complete() { |
| + return "", ErrHint |
| + } |
| + dec := json.NewDecoder(bytes.NewReader(body)) |
| + if err := uniqueJSON(dec); err != nil { |
| + return "", ErrHint |
| + } |
| + if _, err := dec.Token(); err != io.EOF { |
| + return "", ErrHint |
| + } |
| + o, err := termfence.FromEvent(body) |
| + if err != nil || !o.Found || o.State != "terminated" || o.Account != self.Account || o.Region != self.Region || o.InstanceID == self.InstanceID || !iidPattern.MatchString(o.InstanceID) { |
| + return "", ErrHint |
| + } |
| + return o.InstanceID, nil |
| +} |
| +func uniqueJSON(d *json.Decoder) error { |
| + token, err := d.Token() |
| + if err != nil { |
| + return err |
| + } |
| + delim, ok := token.(json.Delim) |
| + if !ok { |
| + return nil |
| + } |
| + switch delim { |
| + case '{': |
| + seen := map[string]bool{} |
| + for d.More() { |
| + k, err := d.Token() |
| + if err != nil { |
| + return err |
| + } |
| + name, ok := k.(string) |
| + if !ok || seen[name] { |
| + return ErrHint |
| + } |
| + seen[name] = true |
| + if err = uniqueJSON(d); err != nil { |
| + return err |
| + } |
| + } |
| + case '[': |
| + for d.More() { |
| + if err = uniqueJSON(d); err != nil { |
| + return err |
| + } |
| + } |
| + default: |
| + return ErrHint |
| + } |
| + _, err = d.Token() |
| + return err |
| +} |
diff --git a/internal/awsterminations/queue_test.go b/internal/awsterminations/queue_test.go| new file mode 100644 |
| index 000000000..4ce5f11dd |
| --- /dev/null |
| +++ b/internal/awsterminations/queue_test.go |
| @@ -0,0 +1,102 @@ |
| +package awsterminations |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "io" |
| + "net/http" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/credentials" |
| + "github.com/carlosframework/platform/internal/boxid" |
| +) |
| + |
| +type transport func(*http.Request) (*http.Response, error) |
| + |
| +func (f transport) Do(r *http.Request) (*http.Response, error) { return f(r) } |
| + |
| +const queueURL = "https://sqs.eu-west-1.amazonaws.com/123456789012/terminations" |
| + |
| +func own() boxid.Cloud { |
| + return boxid.Cloud{Provider: "aws", Account: "123456789012", Region: "eu-west-1", InstanceID: "i-0123456789abcdef0"} |
| +} |
| +func TestTerminationQueueAdapter(t *testing.T) { |
| + var targets []string |
| + cfg := aws.Config{Region: "eu-west-1", Credentials: credentials.NewStaticCredentialsProvider("key", "secret", ""), RetryMaxAttempts: 1, HTTPClient: transport(func(r *http.Request) (*http.Response, error) { |
| + target := r.Header.Get("X-Amz-Target") |
| + targets = append(targets, target) |
| + var in map[string]any |
| + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { |
| + t.Fatal(err) |
| + } |
| + if in["QueueUrl"] != queueURL { |
| + t.Fatal(in) |
| + } |
| + body := `{}` |
| + switch target { |
| + case "AmazonSQS.GetQueueAttributes": |
| + body = `{"Attributes":{"QueueArn":"arn:aws:sqs:eu-west-1:123456789012:terminations"}}` |
| + case "AmazonSQS.ReceiveMessage": |
| + if in["MaxNumberOfMessages"] != float64(1) || in["WaitTimeSeconds"] != float64(20) || in["VisibilityTimeout"] != float64(120) { |
| + t.Fatal(in) |
| + } |
| + body = `{"Messages":[{"MessageId":"event","ReceiptHandle":"private","Body":"payload"}]}` |
| + case "AmazonSQS.DeleteMessage": |
| + if in["ReceiptHandle"] != "private" { |
| + t.Fatal(in) |
| + } |
| + default: |
| + t.Fatal(target) |
| + } |
| + return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{"application/x-amz-json-1.0"}}, Body: io.NopCloser(strings.NewReader(body))}, nil |
| + })} |
| + q, err := New(context.Background(), cfg, queueURL, own()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + msgs, err := q.Receive(context.Background(), 20*time.Second) |
| + if err != nil || len(msgs) != 1 || msgs[0].ID != "event" || msgs[0].Receipt != "private" || string(msgs[0].Body) != "payload" { |
| + t.Fatalf("%v %v", msgs, err) |
| + } |
| + if err = q.Delete(context.Background(), msgs[0].Receipt); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(targets) != 3 { |
| + t.Fatal(targets) |
| + } |
| + if _, err = q.Receive(context.Background(), 0); err == nil { |
| + t.Fatal("short poll") |
| + } |
| +} |
| +func TestTerminationQueueIdentity(t *testing.T) { |
| + for _, url := range []string{"", strings.Replace(queueURL, "https:", "http:", 1), queueURL + "?x=y", queueURL + "#x", strings.Replace(queueURL, "123456789012", "999999999999", 1), strings.Replace(queueURL, "eu-west-1", "eu-west-2", 1), strings.Replace(queueURL, "sqs.eu-west-1.amazonaws.com", "attacker.example.com", 1), queueURL + "/extra", queueURL + "%2fextra", strings.Replace(queueURL, "https://", "https://user@", 1)} { |
| + t.Run(url, func(t *testing.T) { |
| + cfg := aws.Config{Region: "eu-west-1", HTTPClient: transport(func(*http.Request) (*http.Response, error) { t.Fatal("request for invalid URL"); return nil, nil })} |
| + if _, err := New(context.Background(), cfg, url, own()); err == nil { |
| + t.Fatal("accepted") |
| + } |
| + }) |
| + } |
| + for _, reply := range []string{`{}`, `{"Attributes":{"QueueArn":"arn:aws:sqs:eu-west-1:999999999999:terminations"}}`, `{"Attributes":{"QueueArn":"arn:aws:sqs:eu-west-2:123456789012:terminations"}}`, `{"Attributes":{"QueueArn":"arn:aws:sqs:eu-west-1:123456789012:other"}}`} { |
| + cfg := aws.Config{Region: "eu-west-1", Credentials: credentials.NewStaticCredentialsProvider("key", "secret", ""), HTTPClient: transport(func(*http.Request) (*http.Response, error) { |
| + return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(reply))}, nil |
| + })} |
| + if _, err := New(context.Background(), cfg, queueURL, own()); err == nil { |
| + t.Fatal("accepted bad attributes") |
| + } |
| + } |
| +} |
| +func TestTerminationEventEvidence(t *testing.T) { |
| + valid := `{"id":"event","source":"aws.ec2","detail-type":"EC2 Instance State-change Notification","account":"123456789012","region":"eu-west-1","detail":{"instance-id":"i-1123456789abcdef0","state":"terminated"}}` |
| + if iid, err := Hint([]byte(valid), own()); err != nil || iid != "i-1123456789abcdef0" { |
| + t.Fatalf("%s %v", iid, err) |
| + } |
| + for _, body := range []string{strings.Replace(valid, "terminated", "stopped", 1), strings.Replace(valid, "terminated", "shutting-down", 1), strings.Replace(valid, "123456789012", "999999999999", 1), strings.Replace(valid, "eu-west-1", "eu-west-2", 1), strings.Replace(valid, "i-1123456789abcdef0", own().InstanceID, 1), strings.Replace(valid, "i-1123456789abcdef0", "../../key", 1), strings.Replace(valid, "aws.ec2", "aws.other", 1), strings.Repeat("x", 65537), `{}`, valid + valid, strings.Replace(valid, `"id":"event"`, `"id":"event","id":"duplicate"`, 1)} { |
| + if _, err := Hint([]byte(body), own()); err == nil { |
| + t.Fatalf("accepted %s", body[:min(200, len(body))]) |
| + } |
| + } |
| +} |
diff --git a/internal/hadeparture/consumer.go b/internal/hadeparture/consumer.go| new file mode 100644 |
| index 000000000..85fccd6cd |
| --- /dev/null |
| +++ b/internal/hadeparture/consumer.go |
| @@ -0,0 +1,183 @@ |
| +package hadeparture |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "math/rand/v2" |
| + "sync" |
| + "sync/atomic" |
| + "time" |
| +) |
| + |
| +var ErrStarted = errors.New("ha_consumer_already_started") |
| + |
| +type InitError struct { |
| + Stage string |
| + Err error |
| +} |
| + |
| +func (e *InitError) Error() string { return "ha_consumer_init_" + e.Stage } |
| +func (e *InitError) Unwrap() error { return e.Err } |
| + |
| +type Consumer struct { |
| + initialize func(context.Context) error |
| + record func(context.Context, Message) error |
| + work func(context.Context) error |
| + wait func(context.Context, time.Duration) error |
| + mu sync.Mutex |
| + invoked bool |
| + ctx context.Context |
| + cancel context.CancelFunc |
| + started, done chan struct{} |
| + running atomic.Bool |
| +} |
| + |
| +// NewConsumer's record callback must durably save or definitively reject the |
| +// message. It does not confirm, import or acknowledge it. Work is the optional |
| +// bounded replay worker; it must join its children before returning. |
| +func NewConsumer(initialize func(context.Context) error, record func(context.Context, Message) error, work func(context.Context) error) *Consumer { |
| + return &Consumer{initialize: initialize, record: record, work: work, wait: waitContext, started: make(chan struct{}), done: make(chan struct{})} |
| +} |
| +func (c *Consumer) Started() <-chan struct{} { return c.started } |
| +func (c *Consumer) Done() <-chan struct{} { return c.done } |
| +func (c *Consumer) Running() bool { |
| + c.mu.Lock() |
| + ctx := c.ctx |
| + c.mu.Unlock() |
| + return c.running.Load() && ctx != nil && ctx.Err() == nil |
| +} |
| +func (c *Consumer) Stop(ctx context.Context) error { |
| + c.mu.Lock() |
| + cancel := c.cancel |
| + invoked := c.invoked |
| + c.mu.Unlock() |
| + c.running.Store(false) |
| + if cancel != nil { |
| + cancel() |
| + } |
| + if !invoked { |
| + return nil |
| + } |
| + select { |
| + case <-c.done: |
| + return nil |
| + case <-ctx.Done(): |
| + return ctx.Err() |
| + } |
| +} |
| +func (c *Consumer) Start(parent context.Context, makeQueue func(context.Context) (Queue, error)) (Lifecycle, error) { |
| + c.mu.Lock() |
| + if c.invoked { |
| + c.mu.Unlock() |
| + return c, ErrStarted |
| + } |
| + c.invoked = true |
| + c.ctx, c.cancel = context.WithCancel(parent) |
| + ctx := c.ctx |
| + c.mu.Unlock() |
| + initCtx, cancel := context.WithTimeout(ctx, InitializeTimeout) |
| + defer cancel() |
| + fail := func(stage string, err error) (Lifecycle, error) { |
| + c.cancel() |
| + close(c.done) |
| + return c, &InitError{stage, err} |
| + } |
| + if c.initialize == nil || c.record == nil || makeQueue == nil { |
| + return fail("dependencies", errors.New("ha_consumer_dependency_missing")) |
| + } |
| + if err := c.initialize(initCtx); err != nil { |
| + return fail("journal", err) |
| + } |
| + if err := initCtx.Err(); err != nil { |
| + return fail("journal", err) |
| + } |
| + q, err := makeQueue(initCtx) |
| + if err != nil { |
| + return fail("queue", err) |
| + } |
| + if err = initCtx.Err(); err != nil { |
| + return fail("queue", err) |
| + } |
| + if q == nil { |
| + return fail("queue", errors.New("ha_consumer_queue_missing")) |
| + } |
| + c.running.Store(true) |
| + go func() { |
| + defer close(c.done) |
| + defer c.running.Store(false) |
| + defer c.cancel() |
| + var workers sync.WaitGroup |
| + if c.work != nil { |
| + workers.Go(func() { defer c.cancel(); _ = c.work(ctx) }) |
| + } |
| + c.receive(ctx, q) |
| + c.cancel() |
| + workers.Wait() |
| + }() |
| + return c, nil |
| +} |
| +func (c *Consumer) receive(ctx context.Context, q Queue) { |
| + started := false |
| + failures := 0 |
| + for ctx.Err() == nil { |
| + began := time.Now() |
| + request, cancel := context.WithTimeout(ctx, ReceiveTimeout) |
| + messages, err := q.Receive(request, LongPoll) |
| + if err == nil { |
| + err = request.Err() |
| + } |
| + if err == nil { |
| + for _, m := range messages { |
| + // A handle belongs only to this receive. The journal never sees it. |
| + m.Receipt = "" |
| + if err = c.record(request, m); err != nil { |
| + break |
| + } |
| + if err = request.Err(); err != nil { |
| + break |
| + } |
| + } |
| + } |
| + cancel() |
| + if ctx.Err() != nil { |
| + return |
| + } |
| + if err != nil { |
| + if c.wait(ctx, retryDelay(failures)) != nil { |
| + return |
| + } |
| + failures++ |
| + continue |
| + } |
| + failures = 0 |
| + if !started { |
| + close(c.started) |
| + started = true |
| + } |
| + if len(messages) == 0 { |
| + if remaining := LongPoll - time.Since(began); remaining > 0 { |
| + if c.wait(ctx, remaining) != nil { |
| + return |
| + } |
| + } |
| + } |
| + } |
| +} |
| +func retryDelay(failures int) time.Duration { |
| + seconds := 30 |
| + if failures < 5 { |
| + seconds = 1 << max(0, failures) |
| + } |
| + d := time.Duration(seconds) * time.Second |
| + return d*8/10 + time.Duration(rand.Int64N(int64(d/5)+1)) |
| +} |
| +func waitContext(ctx context.Context, d time.Duration) error { |
| + timer := time.NewTimer(d) |
| + defer timer.Stop() |
| + select { |
| + case <-ctx.Done(): |
| + return ctx.Err() |
| + case <-timer.C: |
| + return nil |
| + } |
| +} |
diff --git a/internal/hadeparture/consumer_test.go b/internal/hadeparture/consumer_test.go| new file mode 100644 |
| index 000000000..28cd945f0 |
| --- /dev/null |
| +++ b/internal/hadeparture/consumer_test.go |
| @@ -0,0 +1,251 @@ |
| +package hadeparture |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| +) |
| + |
| +type testQueue struct { |
| + receive func(context.Context, time.Duration) ([]Message, error) |
| + deletes atomic.Int32 |
| +} |
| + |
| +func (q *testQueue) Receive(ctx context.Context, d time.Duration) ([]Message, error) { |
| + return q.receive(ctx, d) |
| +} |
| +func (q *testQueue) Delete(context.Context, string) error { q.deletes.Add(1); return nil } |
| +func waitClosed(t *testing.T, ch <-chan struct{}) { |
| + t.Helper() |
| + select { |
| + case <-ch: |
| + case <-time.After(time.Second): |
| + t.Fatal("channel open") |
| + } |
| +} |
| +func assertOpen(t *testing.T, ch <-chan struct{}) { |
| + t.Helper() |
| + select { |
| + case <-ch: |
| + t.Fatal("channel closed") |
| + default: |
| + } |
| +} |
| +func testConsumer() *Consumer { |
| + return NewConsumer(func(context.Context) error { return nil }, func(context.Context, Message) error { return nil }, nil) |
| +} |
| +func TestTerminationConsumerStartupBound(t *testing.T) { |
| + c := testConsumer() |
| + var initLeft, receiveLeft time.Duration |
| + c.initialize = func(ctx context.Context) error { |
| + d, ok := ctx.Deadline() |
| + if !ok { |
| + t.Error("no init deadline") |
| + } |
| + initLeft = time.Until(d) |
| + return nil |
| + } |
| + q := &testQueue{receive: func(ctx context.Context, poll time.Duration) ([]Message, error) { |
| + d, ok := ctx.Deadline() |
| + if !ok { |
| + t.Error("no receive deadline") |
| + } |
| + receiveLeft = time.Until(d) |
| + if poll != 20*time.Second { |
| + t.Error(poll) |
| + } |
| + return nil, nil |
| + }} |
| + life, err := c.Start(context.Background(), func(ctx context.Context) (Queue, error) { |
| + d, _ := ctx.Deadline() |
| + if time.Until(d) > 5*time.Second { |
| + t.Error("client deadline") |
| + } |
| + return q, nil |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + waitClosed(t, life.Started()) |
| + if initLeft <= 0 || initLeft > 5*time.Second || receiveLeft <= 0 || receiveLeft > 25*time.Second { |
| + t.Fatalf("deadlines %s %s", initLeft, receiveLeft) |
| + } |
| + // The consumer has no inventory interface. Missing/incomplete families and an unchanged index cannot gate this empty receive. |
| + if err := life.Stop(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + waitClosed(t, life.Done()) |
| + if q.deletes.Load() != 0 { |
| + t.Fatal("early delete") |
| + } |
| +} |
| +func TestTerminationConsumerLifecycle(t *testing.T) { |
| + t.Run("durable receipt before started", func(t *testing.T) { |
| + entered, release := make(chan struct{}), make(chan struct{}) |
| + c := testConsumer() |
| + c.record = func(ctx context.Context, m Message) error { |
| + if m.Receipt != "" { |
| + t.Error("receipt persisted") |
| + } |
| + close(entered) |
| + select { |
| + case <-release: |
| + return nil |
| + case <-ctx.Done(): |
| + return ctx.Err() |
| + } |
| + } |
| + var receives atomic.Int32 |
| + q := &testQueue{receive: func(ctx context.Context, _ time.Duration) ([]Message, error) { |
| + if receives.Add(1) > 1 { |
| + <-ctx.Done() |
| + return nil, ctx.Err() |
| + } |
| + return []Message{{ID: "one", Body: []byte("event"), Receipt: "private"}}, nil |
| + }} |
| + life, err := c.Start(context.Background(), func(context.Context) (Queue, error) { return q, nil }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + waitClosed(t, entered) |
| + assertOpen(t, life.Started()) |
| + close(release) |
| + waitClosed(t, life.Started()) |
| + _ = life.Stop(context.Background()) |
| + if q.deletes.Load() != 0 { |
| + t.Fatal("early delete") |
| + } |
| + }) |
| + t.Run("receive error then recovery", func(t *testing.T) { |
| + c := testConsumer() |
| + var calls atomic.Int32 |
| + c.wait = func(ctx context.Context, _ time.Duration) error { return ctx.Err() } |
| + q := &testQueue{receive: func(ctx context.Context, _ time.Duration) ([]Message, error) { |
| + if calls.Add(1) == 1 { |
| + return nil, errors.New("offline") |
| + } |
| + return nil, nil |
| + }} |
| + life, err := c.Start(context.Background(), func(context.Context) (Queue, error) { return q, nil }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + waitClosed(t, life.Started()) |
| + if !life.Running() { |
| + t.Fatal("not running") |
| + } |
| + if _, err = c.Start(context.Background(), func(context.Context) (Queue, error) { return q, nil }); err == nil { |
| + t.Fatal("second start") |
| + } |
| + _ = life.Stop(context.Background()) |
| + }) |
| + for _, stage := range []string{"init", "client"} { |
| + t.Run(stage, func(t *testing.T) { |
| + c := testConsumer() |
| + bad := errors.New("unavailable") |
| + if stage == "init" { |
| + c.initialize = func(context.Context) error { return bad } |
| + } |
| + life, err := c.Start(context.Background(), func(context.Context) (Queue, error) { return nil, bad }) |
| + var ie *InitError |
| + if !errors.As(err, &ie) || life.Running() { |
| + t.Fatalf("%v", err) |
| + } |
| + assertOpen(t, life.Started()) |
| + waitClosed(t, life.Done()) |
| + }) |
| + } |
| + t.Run("parent cancels receive", func(t *testing.T) { |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + c := testConsumer() |
| + entered := make(chan struct{}) |
| + q := &testQueue{receive: func(ctx context.Context, _ time.Duration) ([]Message, error) { |
| + close(entered) |
| + <-ctx.Done() |
| + return nil, ctx.Err() |
| + }} |
| + life, err := c.Start(ctx, func(context.Context) (Queue, error) { return q, nil }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + waitClosed(t, entered) |
| + cancel() |
| + if life.Running() { |
| + t.Fatal("running after cancel") |
| + } |
| + waitClosed(t, life.Done()) |
| + assertOpen(t, life.Started()) |
| + _ = life.Stop(context.Background()) |
| + }) |
| + t.Run("bounded stop joins import", func(t *testing.T) { |
| + c := testConsumer() |
| + entered, release := make(chan struct{}), make(chan struct{}) |
| + c.work = func(context.Context) error { close(entered); <-release; return nil } |
| + q := &testQueue{receive: func(ctx context.Context, _ time.Duration) ([]Message, error) { <-ctx.Done(); return nil, ctx.Err() }} |
| + life, err := c.Start(context.Background(), func(context.Context) (Queue, error) { return q, nil }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + waitClosed(t, entered) |
| + ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) |
| + defer cancel() |
| + if err := life.Stop(ctx); !errors.Is(err, context.DeadlineExceeded) { |
| + t.Fatal(err) |
| + } |
| + if life.Running() { |
| + t.Fatal("running") |
| + } |
| + assertOpen(t, life.Done()) |
| + close(release) |
| + waitClosed(t, life.Done()) |
| + _ = life.Stop(context.Background()) |
| + }) |
| + t.Run("unexpected worker exit", func(t *testing.T) { |
| + c := testConsumer() |
| + c.work = func(context.Context) error { return errors.New("worker_exit") } |
| + q := &testQueue{receive: func(ctx context.Context, _ time.Duration) ([]Message, error) { <-ctx.Done(); return nil, ctx.Err() }} |
| + life, err := c.Start(context.Background(), func(context.Context) (Queue, error) { return q, nil }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + waitClosed(t, life.Done()) |
| + if life.Running() { |
| + t.Fatal("running") |
| + } |
| + }) |
| +} |
| +func TestTerminationConsumerPacing(t *testing.T) { |
| + c := testConsumer() |
| + waits := make(chan time.Duration, 1) |
| + c.wait = func(ctx context.Context, d time.Duration) error { |
| + select { |
| + case waits <- d: |
| + default: |
| + } |
| + <-ctx.Done() |
| + return ctx.Err() |
| + } |
| + q := &testQueue{receive: func(context.Context, time.Duration) ([]Message, error) { return nil, nil }} |
| + life, err := c.Start(context.Background(), func(context.Context) (Queue, error) { return q, nil }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + waitClosed(t, life.Started()) |
| + select { |
| + case d := <-waits: |
| + if d < 19*time.Second || d > 20*time.Second { |
| + t.Fatal(d) |
| + } |
| + case <-time.After(time.Second): |
| + t.Fatal("not paced") |
| + } |
| + _ = life.Stop(context.Background()) |
| + for i, want := range []time.Duration{1, 2, 4, 8, 16, 30, 30} { |
| + got := retryDelay(i) |
| + if got < want*time.Second*8/10 || got > want*time.Second { |
| + t.Fatalf("retry %d: %s", i, got) |
| + } |
| + } |
| +} |
diff --git a/internal/hadeparture/types.go b/internal/hadeparture/types.go| new file mode 100644 |
| index 000000000..bcc23e4a5 |
| --- /dev/null |
| +++ b/internal/hadeparture/types.go |
| @@ -0,0 +1,52 @@ |
| +package hadeparture |
| + |
| +import ( |
| + "context" |
| + "time" |
| +) |
| + |
| +const ( |
| + MaxBodyBytes = 64 * 1024 |
| + MaxInboxRows = 1024 |
| + InitializeTimeout = 5 * time.Second |
| + ReceiveTimeout = 25 * time.Second |
| + LongPoll = 20 * time.Second |
| +) |
| + |
| +type Scope struct{ CloudRegion, Placement, DataBucket, SecretsKeyFP string } |
| +type Box struct { |
| + Ref, InstanceID, Account, RecordSHA256 string |
| + Scope Scope |
| +} |
| +type BoxObservation struct { |
| + Box Box |
| + Known bool |
| + PlacementNull bool |
| + EdgesKey, EdgesETag, Generation string |
| + PublishedAt time.Time |
| +} |
| +type Departure struct { |
| + ID string |
| + Box Box |
| + EdgesKey, EdgesETag string |
| + ObservedAt time.Time |
| +} |
| +type DepartureView struct { |
| + Self BoxObservation |
| + Peers []BoxObservation |
| + Complete bool |
| +} |
| +type Message struct { |
| + ID, Receipt string |
| + Body []byte |
| +} |
| +type Queue interface { |
| + Receive(context.Context, time.Duration) ([]Message, error) |
| + Delete(context.Context, string) error |
| +} |
| +type Lifecycle interface { |
| + Started() <-chan struct{} |
| + Done() <-chan struct{} |
| + Running() bool |
| + Stop(context.Context) error |
| +} |