Merge remote-tracking branch 'origin/main' into activator-settle-wait
# Conflicts: # internal/provision/testdata/plan14-root-reads-chain.tsv
45 files changed,
+4,936
−64
.amadan/ci.d/30-minio-contract+33 −0cmd/console/main.go+11 −9dbforward_e2e_test.go+30 −1docs/superpowers/notes/census-proposal-group-observation-carry.md+23 −0docs/superpowers/notes/census-proposal-stats-prune-400.md+27 −0docs/superpowers/specs/2026-11-09-group-roll-verb-design.md+40 −0infra/modules/region-host/main.tf+38 −1infra/modules/region-host/tests/analytics_prune.tftest.hcl+131 −0infra/modules/region-host/tests/group.tftest.hcl+5 −0infra/modules/region-host/variables.tf+6 −0internal/analytics/prune.go+431 −0internal/analytics/prune_test.go+863 −0internal/analytics/prune_versions_test.go+346 −0internal/console/analyticsprune.go+112 −0internal/console/analyticsprune_test.go+268 −0internal/console/analyticsprune_versions_test.go+210 −0internal/console/apidemobox.go+15 −1internal/console/demo_serving_dispatch_test.go+122 −0internal/console/economicspass.go+4 −0internal/console/homelink.go+23 −6internal/console/server.go+12 −0internal/console/store.go+6 −0internal/console/store_gate.go+2 −0internal/edge/demo_api_integration_test.go+15 −5internal/grouproll/engine.go+71 −1internal/grouproll/fake_test.go+19 −0internal/grouproll/observation_carry_test.go+131 −0internal/grouproll/plan.go+5 −1internal/grouproll/provider.go+4 −0internal/grouprollaws/group.go+152 −0internal/grouprollaws/group_test.go+125 −2internal/grouprollaws/transport.go+12 −1internal/host/hadepartures_scan_test.go+6 −1internal/host/interactive_test.go+22 −1internal/lease/release_snapshot_test.go+30 −31internal/provision/testdata/plan14-root-reads-chain.tsv+2 −1internal/provision/testdata/plan14-root-reads-group-observation-carry.tsv+10 −0internal/provision/testdata/plan14-root-reads-stats-prune-400.tsv+15 −0internal/release/batchdelete.go+188 −0internal/release/batchdelete_test.go+302 −0internal/release/objectversions.go+339 −0internal/release/objectversions_test.go+508 −0internal/release/prunelist_test.go+38 −0internal/release/s3_minio_test.go+168 −0internal/release/store.go+16 −2
diff --git a/.amadan/ci.d/30-minio-contract b/.amadan/ci.d/30-minio-contract| index 1ee952d70..bcb0e5c98 100755 |
| --- a/.amadan/ci.d/30-minio-contract |
| +++ b/.amadan/ci.d/30-minio-contract |
| @@ -431,6 +431,39 @@ if ! grep -q '^--- PASS: TestS3StoreMinioContract (' "$out3"; then |
| exit 1 |
| fi |
| +# Analytics retention must remove noncurrent versions and delete markers. |
| +# Use a separate versioned bucket so the existing unversioned contracts keep |
| +# their semantics. The same ephemeral server and cleanup trap own it. |
| +"$mc" --quiet mb local/analytics-versions |
| +"$mc" --quiet version enable local/analytics-versions |
| +cat >"$rundir/analytics-versions.json" <<'EOF' |
| +{"Version": "2012-10-17", "Statement": [ |
| + {"Effect": "Allow", "Action": ["s3:ListBucket", "s3:ListBucketVersions"], "Resource": ["arn:aws:s3:::analytics-versions"]}, |
| + {"Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:DeleteObjectVersion"], "Resource": ["arn:aws:s3:::analytics-versions/*"]} |
| +]} |
| +EOF |
| +"$mc" --quiet admin policy create local analytics-versions "$rundir/analytics-versions.json" |
| +"$mc" --quiet admin user add local analyticsversions analyticsversionssecret1 |
| +"$mc" --quiet admin policy attach local analytics-versions --user analyticsversions |
| +out_versions=$rundir/test-s3versions.log |
| +set +e |
| +CARLOS_MINIO_TEST=1 \ |
| + MINIO_ENDPOINT="http://127.0.0.1:$port" \ |
| + MINIO_VERSIONED_BUCKET=analytics-versions \ |
| + MINIO_VERSIONED_KEY=analyticsversions \ |
| + MINIO_VERSIONED_SECRET=analyticsversionssecret1 \ |
| + go test ./internal/release/ -run '^TestS3StoreMinioVersions$' -count=1 -v >"$out_versions" 2>&1 |
| +test_status=$? |
| +set -e |
| +cat "$out_versions" |
| +if [ "$test_status" -ne 0 ]; then |
| + exit "$test_status" |
| +fi |
| +if ! grep -q '^--- PASS: TestS3StoreMinioVersions (' "$out_versions"; then |
| + echo "the versioned S3Store test did not PASS: skipped, filtered out, or renamed" >&2 |
| + exit 1 |
| +fi |
| + |
| # carlos system group end to end (group roll verb spec §10.5): plan, roll, |
| # replace and remove in-process with the fake group and box, every edges |
| # file, host lock and router pointer the engine reads served by this |
diff --git a/cmd/console/main.go b/cmd/console/main.go| index e83ec8575..37765431d 100644 |
| --- a/cmd/console/main.go |
| +++ b/cmd/console/main.go |
| @@ -489,15 +489,17 @@ func serve() { |
| log.Fatal(err) |
| } |
| cfg := console.Config{ |
| - DemoAlerts: demoAlerts, |
| - DemoAPIOrigin: os.Getenv("CONSOLE_DEMO_API_ORIGIN"), |
| - Demo: demoConfig, |
| - DemoTermsURL: demoTermsURL, |
| - DemoAbuseAddress: demoAbuseAddress, |
| - Origin: origin, |
| - Keymail: envOr("CONSOLE_KEYMAIL", "https://keymail.dev"), |
| - Registry: envOr("CARLOS_REGISTRY", "/data/registry.db"), |
| - Releases: rel, |
| + DemoAlerts: demoAlerts, |
| + DemoAPIOrigin: os.Getenv("CONSOLE_DEMO_API_ORIGIN"), |
| + Demo: demoConfig, |
| + DemoTermsURL: demoTermsURL, |
| + DemoAbuseAddress: demoAbuseAddress, |
| + Origin: origin, |
| + Keymail: envOr("CONSOLE_KEYMAIL", "https://keymail.dev"), |
| + Registry: envOr("CARLOS_REGISTRY", "/data/registry.db"), |
| + Releases: rel, |
| + AnalyticsRetentionDays: os.Getenv("CARLOS_ANALYTICS_RETENTION_DAYS"), |
| + AnalyticsRetentionDryRun: os.Getenv("CARLOS_ANALYTICS_RETENTION_DRY_RUN"), |
| // The deployment bucket's NAME, from the same variable openStore() |
| // opens it with — /fleet/architecture draws the box -> bucket edge |
| // from it. Empty on a CARLOS_DEPLOYMENT_DIR deployment, which |
diff --git a/dbforward_e2e_test.go b/dbforward_e2e_test.go| index 211a8442a..31a8b6db2 100644 |
| --- a/dbforward_e2e_test.go |
| +++ b/dbforward_e2e_test.go |
| @@ -392,6 +392,22 @@ type dbfTap struct { |
| addr string |
| mu sync.Mutex |
| down []time.Time |
| + // events says how each tapped connection ended, and when, so a |
| + // failure can tell which side closed first (#897: the CLI's read was |
| + // admitted and then "client gone" a millisecond later, on CI only). |
| + events []string |
| +} |
| + |
| +func (tp *dbfTap) event(f string, args ...any) { |
| + tp.mu.Lock() |
| + defer tp.mu.Unlock() |
| + tp.events = append(tp.events, time.Now().Format("15:04:05.000000 ")+fmt.Sprintf(f, args...)) |
| +} |
| + |
| +func (tp *dbfTap) trace() string { |
| + tp.mu.Lock() |
| + defer tp.mu.Unlock() |
| + return strings.Join(tp.events, "\n") |
| } |
| func newDBFTap(t *testing.T, target string, connect bool) *dbfTap { |
| @@ -430,25 +446,33 @@ func (tp *dbfTap) serve(c net.Conn, target string, connect bool) { |
| } |
| up, err := net.Dial("tcp", target) |
| if err != nil { |
| + tp.event("%s: dial upstream: %v", c.RemoteAddr(), err) |
| return |
| } |
| defer up.Close() |
| + id := c.RemoteAddr().String() + "->" + up.LocalAddr().String() |
| + tp.event("%s: open", id) |
| go func() { |
| - io.Copy(up, in) |
| + n, err := io.Copy(up, in) |
| + tp.event("%s: client side ended after %d bytes up: %v", id, n, err) |
| up.(*net.TCPConn).CloseWrite() |
| }() |
| buf := make([]byte, 32<<10) |
| + var total int |
| for { |
| n, err := up.Read(buf) |
| if n > 0 { |
| + total += n |
| tp.mu.Lock() |
| tp.down = append(tp.down, time.Now()) |
| tp.mu.Unlock() |
| if _, werr := c.Write(buf[:n]); werr != nil { |
| + tp.event("%s: write to client after %d bytes down: %v", id, total, werr) |
| return |
| } |
| } |
| if err != nil { |
| + tp.event("%s: upstream side ended after %d bytes down: %v", id, total, err) |
| return |
| } |
| } |
| @@ -505,6 +529,11 @@ func checkProgressAtTheCLI(t *testing.T, e *dbfE2E, tap *dbfTap, atLeast time.Du |
| err = cmd.Wait() |
| end := time.Now() |
| if err != nil || out.String() != "n\n3\n" { |
| + // One t.Logf per line: the CI gate's summary keeps only lines |
| + // carrying the test file's prefix. |
| + for _, line := range strings.Split(tap.trace(), "\n") { |
| + t.Logf("tap: %s", line) |
| + } |
| t.Fatalf("%q %v\n%s", out.String(), err, strings.Join(stderr, "\n")) |
| } |
| if reading.IsZero() || reading.Sub(start) > time.Second { |
diff --git a/docs/superpowers/notes/census-proposal-group-observation-carry.md b/docs/superpowers/notes/census-proposal-group-observation-carry.md| new file mode 100644 |
| index 000000000..68d776061 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-group-observation-carry.md |
| @@ -0,0 +1,23 @@ |
| +# Census approval: group-observation-carry |
| + |
| +Ruling `census-ruling-group-observation-carry`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/grouproll/engine.go` `Engine.preflight` | body | unchanged (1) | the same provider-observation.json read; when it names another version of the same launch template, the two versions are read from the provider (template_data, a DescribeLaunchTemplateVersions read through the adapter) and compared without user data; no new file read, nothing written | |
| +| `internal/grouproll/plan.go` `Engine.Plan` | body | unchanged (1) | the same observation read and the same carry-over rule as preflight (two template_data provider reads); no new file read, nothing written | |
| +| `internal/grouprollaws/transport.go` `boundBody.HandleDeserialize` | body | unchanged (1) | the same bounded read of the AWS answer; the buffered bytes are kept on a typed body (bufferedBody) so TemplateData can compare the raw launchTemplateData without a second read; no new read | |
| + |
| +Envelopes re-pinned: `internal/grouproll`, `internal/grouprollaws`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Recorded dispositions, which each change must still satisfy: |
| + |
| +- `internal/grouproll/engine.go` `Engine.preflight`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-group-roll-verb;basis=reads provider-observation.json from the operator's own 0700 state directory |
| +- `internal/grouproll/plan.go` `Engine.Plan`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-group-roll-verb;basis=reads provider-observation.json from the operator's own 0700 state directory;rev3=census-ruling-group-verb-followups;basis=a missing or unreadable provider-observation.json is refused as observation instead of passing the read error through (same file, same read) |
| +- `internal/grouprollaws/transport.go` `boundBody.HandleDeserialize`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-group-roll-verb;basis=reads an AWS API answer body under the 4 MiB cap |
| + |
| +Seal: `75b32391a24d2c9269fc579aae68ac80b7b1d4ccf0be55f0373490e43a2a652a` → `587f6e92c5e594b9bb6436a2d0066849454407202e311f43483bed3be4591940`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-group-observation-carry.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/notes/census-proposal-stats-prune-400.md b/docs/superpowers/notes/census-proposal-stats-prune-400.md| new file mode 100644 |
| index 000000000..a33f2e53a |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-stats-prune-400.md |
| @@ -0,0 +1,27 @@ |
| +# Census approval: stats-prune-400 |
| + |
| +Ruling `census-ruling-stats-prune-400`. The independent reviewer approves or rejects every change below, 1 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `infra/modules/region-host/main.tf` `external` | body | unchanged (1) | new aws_iam_role_policy for the console host role, count 1 only when enable_analytics_version_prune is true (default false, refused in group mode): s3:ListBucketVersions on the deployment bucket conditioned on s3:prefix apps/*, and s3:DeleteObjectVersion on deployment_bucket_arn/apps/*/*/analytics/*/days/* only; existing grants and denies unchanged; tofu only, run on an operator machine; no read is added and nothing on a box reads the file | |
| +| `infra/modules/region-host/tests/group.tftest.hcl` `external` | body | unchanged (1) | adds a mock run asserting group mode refuses enable_analytics_version_prune; test-only Terraform, no runtime reads | |
| +| `infra/modules/region-host/variables.tf` `external` | body | unchanged (1) | new variable enable_analytics_version_prune (bool, default false) driving the policy above; operator Terraform input; no box runtime read | |
| + |
| +Envelopes re-pinned: `infra/modules/region-host`, `infra/modules/region-host/tests`, `internal/analytics`, `internal/release`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Recorded dispositions, which each change must still satisfy: |
| + |
| +- `infra/modules/region-host/main.tf` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-console-invite-delivery;basis=tofu on an operator's machine with the operator's AWS credentials (no box unit; no binary embeds the file): main's module with one optional aws_iam_role_policy, host_console_mail, count 0 unless console_mail_from is set; it grants the host role ses:SendEmail on the one sending identity, the carlos-bab configuration set and its tenants, conditioned on ses:FromAddress equal to console_mail_from; no read is added and nothing on a box reads the file;rev3=census-ruling-sec-host-imdsv2-module;basis=aws_instance.host gains metadata_options (IMDSv2 required, hop limit 1, endpoint enabled), matching scanner-host; tofu configuration only, run on an operator's machine; no read, file or record write is added; applies in place on a running instance with no restart;rev3=census-ruling-hunt-account-root-hardening;basis=adds aws_iam_role_policy host_release_key_deny (count from deny_release_key_reads, default true): an explicit Deny on ssm:GetParameter, GetParameters and GetParameterHistory for parameter/carlos/release-key, and on GetParametersByPath for its ancestor paths; tofu only, run on an operator's machine; no read is added and nothing on a box reads the file;rev3=census-ruling-region-host-store-deny;basis=host_store policy: the explicit Deny on the deployment's own buckets drops s3:DeleteObject and keeps s3:DeleteBucket and s3:CreateBucket (lease release, retention and prune are DeleteObject); tofu only, run on an operator machine; no read is added and nothing on a box reads the file;rev3=census-ruling-region-ha-p3b;basis=Select default fixed resources through counted addresses and explicit moves; group mode selects scoped bucket/SSM policy, partition-aware ARNs and refuses fixed-only settings. Operator Terraform controls the instance role that can read boot parameters and write runtime bucket objects; release-key Deny and fixed-mode policy remain.;rev3=census-ruling-region-ha-g3-fixes;basis=Enable the fixed-host memory alarm with either alert input and use the selected topic for alarm and recovery notifications. Preserve module topic/subscription creation for alerts_email only. No new root runtime read or box authority.;rev3=census-ruling-managed-fleets-2b1;basis=managed fleets 2b-1 Task 5: aws_iam_policy.store_user_boundary is now counted when store_bucket_prefix is set or managed_fleets_enabled is true; its statements are concat of the unchanged object-storage pair (only with a store prefix, moved into local.store_boundary_statements byte for byte) and local.managed_boundary_statements (only with managed fleets: the fleet-data Allows on <managed_fleet_bucket_prefix>* buckets); name unchanged, description conditional on store prefix with lifecycle ignore_changes on description so a later feature switch never replaces the policy; tofu only, run on an operator's machine with the operator's AWS credentials; no box unit, user_data or binary reads the file; no read is added; default (both features off) plans no change;rev3=census-ruling-fixedbox-health-alarms;basis=Fixed host EC2 status-check alarms: auto-recover gains SNS alarm/ok actions (ec2:recover kept); new host_instance_check alarm (StatusCheckFailed_Instance 3 of 3 x 60 s -> ec2:reboot + SNS). tofu only, run on an operator machine; no read is added and nothing on a box reads the file.;rev3=census-ruling-fixed-host-ignore-user-data;basis=aws_instance.host lifecycle ignore_changes gains user_data (was [ami]): a user_data edit no longer plans an in-place update (stop/start) of a live fixed host; a new box still boots with the given script. tofu only, run on an operator machine; no read is added and nothing on a box reads the file.;rev3=census-ruling-w6-ingress-drain;basis=new aws_iam_role_policy.host_ingress_drain, count 1 only in fixed mode with ingress_target_group_arns non-empty: Allow elasticloadbalancing:DescribeTargetGroupAttributes and elasticloadbalancing:DescribeTargetHealth on Resource "*" (neither action takes a resource type). Read-only; no ELB write right. aws_iam_role.host's group-mode precondition gains length(var.ingress_target_group_arns) == 0, so group mode refuses the input. New AWS read right for the box role (the agent's drain reads); nothing a tenant or app can name. |
| +- `infra/modules/region-host/tests/group.tftest.hcl` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=Add mock plans covering group shape, network/AMI checks, launch constraints, boot config/ingress parameters and default fixed absence. Test-only Terraform, no real AWS effects or root runtime reads.;rev3=census-ruling-region-ha-group-rtb;basis=Two mock runs: implicit main route table, explicit association wins; test-only Terraform;rev3=census-ruling-region-ha-p3b1-fixes;basis=Read the plain script local in boot assertions and retain the shell injection probe through the mocked partition DNS suffix, with the same queue URL bound by the launch precondition. Mock plans only; no runtime reads. |
| +- `infra/modules/region-host/variables.tf` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-console-invite-delivery;basis=tofu on an operator's machine with the operator's AWS credentials (no box unit; no binary embeds the file): main's variables with console_mail_from (validated as one lowercase address) and console_mail_region, both empty by default; no read is added and nothing on a box reads the file;rev3=census-ruling-hunt-account-root-hardening;basis=adds deny_release_key_reads (bool, default true); no read is added and nothing on a box reads the file;rev3=census-ruling-region-ha-p3b;basis=Add default-fixed mode and validated group count, zones, pinned image/release/template, ingress, configuration key and transaction-open refusal. Operator-supplied Terraform values select root boot inputs; no direct box runtime read and no group activation by default.;rev3=census-ruling-region-ha-g2-fixes;basis=Add an empty-default set of additional alert topic ARNs, validating concrete SNS topic syntax and excluding wildcards/subscriptions; operator Terraform input, no box runtime read.;rev3=census-ruling-region-ha-g3-fixes;basis=Add optional alerts_topic_arn with concrete same-region SNS ARN validation and mutual exclusion with alerts_email. The caller owns the existing topic policy and subscriptions; no runtime sink is configured and no new root read is added.;rev3=census-ruling-managed-fleets-2b1;basis=managed fleets 2b-1 Task 5: five variables, managed_fleets_enabled (bool, default false, refused unless mode is fixed), managed_fleets_deployment, managed_fleets_regions (concrete ami/subnet/sg IDs, arm64 types, no ID in two regions), managed_fleet_bucket_prefix (1-24 chars, no reserved prefix, must not cover the deployment, data or staging buckets, disjoint from store_bucket_prefix) and managed_fleet_user_path (literal IAM path, disjoint from store_user_path); store_bucket_prefix and store_user_path gain a validation refusing *, ? or ${ only when managed fleets and object storage are both on; operator Terraform input only; no box runtime read and nothing on a box reads the file;rev3=census-ruling-fixedbox-health-alarms;basis=Add optional health_alerts_topic_arn (concrete same-region SNS ARN validation, empty default); enable_auto_recovery description covers both status alarms. Operator Terraform input; no box runtime read.;rev3=census-ruling-w6-ingress-drain;basis=new variable ingress_target_group_arns (list(string), default [], non-nullable) validated as distinct ELB target group ARNs (arn:aws(-x)*:elasticloadbalancing:<region>:<12 digits>:targetgroup/<name>/<16 hex>); drives the IAM policy and output above. No read added. |
| + |
| +New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff: |
| + |
| +- new `infra/modules/region-host/tests/analytics_prune.tftest.hcl:external`: reads +file:external; written legacy, accepted-legacy, frozen |
| + |
| +Seal: `40c8459580c3e62a53637e9989f1616e5735ce78796ec6ea1b22655a5eb4ad63` → `75b32391a24d2c9269fc579aae68ac80b7b1d4ccf0be55f0373490e43a2a652a`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-stats-prune-400.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/specs/2026-11-09-group-roll-verb-design.md b/docs/superpowers/specs/2026-11-09-group-roll-verb-design.md| index 05e64f076..78ea8b7fe 100644 |
| --- a/docs/superpowers/specs/2026-11-09-group-roll-verb-design.md |
| +++ b/docs/superpowers/specs/2026-11-09-group-roll-verb-design.md |
| @@ -379,6 +379,7 @@ build to it. |
| | V16 | `plan` reports a missing provider observation as `record` (FileNotFoundError reached check()) | `plan` says `observation`, as preflight does | REPORT follow-up 3; flagship step 4 2026-11-11 | |
| | V17 | Every provider call is made once (`--cli-read-timeout`, retries 1) | Reads (the describes, caller identity, HeadBucket, S3 GET and list) are retried while AWS throttles them: four calls at most, about 1, 2 and 4 s apart, jittered; any other failure and the last throttle fail closed as before. Writes and box sessions are never retried. Bare `carlos system group`, its -h and an unknown verb print the group's help | Step-3 dev W4 2026-11-10: the group describe refused under ASG throttling (8a3d302) | |
| | V18 | A request that gets no response is one failed call | A read whose request got no response at all (the SDK's RequestSendError: a reset or EOF on a reused connection, no call in CloudTrail) is retried as a throttle is (V17's budget); a timeout is not, and stays one bound. A failure to get credentials (AssumeRole, SSO), throttled or unanswered, is never retried, so no credential call repeats. Writes and sessions are never retried | G5 release 1, dev, 2026-11-11: the post-prepare group describe failed in 14 ms with no CloudTrail call; resume closed it (8a3d302) | |
| +| V19 | The provider observation names one launch template version; any other pinned version refuses `observation` | The observation carries across a re-pin that changes only user data (§7.1). A launch template version other than the observation's, with the same template id and name, is accepted when the two versions' launch template data are identical once UserData is removed; anything else refuses `observation` as before | G5 release 1, 2026-11-11: every release's re-pin left the next roll needing a pin-back (Paul approved option b, 11-11) | |
| Not deviations, recorded so nobody "fixes" them in the port: the drain-rerun |
| backoff and the TakeHost `wake_timeout` follow-ups from the held build stay |
| @@ -387,6 +388,45 @@ follow-ups; `check-region-group-plan.py` (the tofu plan gate), the fault harness |
| observation file `provider-observation.json` is still placed by the controller, |
| not written by `probe`. |
| +### 7.1 The observation across a user-data-only re-pin (V19) |
| + |
| +The probe observes one thing: that this group, with this hook, launching |
| +from this template, returns a member from Standby without a lifecycle hook. |
| +A release's re-pin makes a new launch template version that differs from |
| +the old one only in user data (the CARLOS release it boots), so the |
| +observation still describes the group. Rule: |
| + |
| +1. The observation is accepted as before when it names the pinned template |
| + exactly. |
| +2. Otherwise it is accepted only if every other field of the record matches |
| + (v 1, this group's ARN, this hook, documented_no_hook true), the |
| + observation's template and the pinned template have the same |
| + LaunchTemplateId and LaunchTemplateName, and their Versions are |
| + different version numbers; and |
| +3. both versions are read from the provider (`template_data`, journaled as |
| + reads like `template_release`) and their launch template data are |
| + identical once `UserData` is removed: the AMI, the instance type, the |
| + network interfaces and security groups, the IAM instance profile, the |
| + metadata options, the block devices, tags and every other field. The |
| + comparison covers both the SDK's decoded fields and the answer's own |
| + `launchTemplateData` XML byte for byte, with only its direct `userData` |
| + child element cut out by its byte span: no canonical form, so a field |
| + the SDK does not know (and its decoder skips), its whitespace or any |
| + layout difference refuses. A malformed answer, a second item or a |
| + second `userData` refuses too; the cost of a false refusal is the |
| + pin-back, as before. The group's lifecycle hook is checked as before (`hook`), |
| + and the group ARN ties the record to this group. ASG-level settings |
| + outside the launch template are not compared, as they never were for |
| + the exact-template record. |
| +4. Anything else (a different template, a field that differs, a version |
| + that cannot be read) refuses `observation`, or is the read's own |
| + Uncertain, as today. Nothing is written: the controller still places |
| + the record by hand, and the carried acceptance is re-derived on every |
| + run from the two journaled reads. |
| + |
| +`probe start` is unchanged: it still needs a member running the pinned |
| +template, and its record names that version. |
| + |
| ## 8. Serialization: one machine and account per deployment (D6) |
| Rev 2 added a claim object in the deployment bucket so any machine could run the |
diff --git a/infra/modules/region-host/main.tf b/infra/modules/region-host/main.tf| index 0f9e36518..23c9ea29b 100644 |
| --- a/infra/modules/region-host/main.tf |
| +++ b/infra/modules/region-host/main.tf |
| @@ -146,7 +146,7 @@ resource "aws_iam_role" "host" { |
| var.root_volume_size >= 1 && floor(var.root_volume_size) == var.root_volume_size && |
| var.user_data == "" && var.ssm_parameter_arn == "" && |
| (var.group_ingress == null || alltrue([for zone in var.group_zones : zone.allocation_id != null])) && |
| - !var.relay && length(var.extra_ingress) == 0 && !var.enable_cost_explorer && |
| + !var.relay && length(var.extra_ingress) == 0 && !var.enable_cost_explorer && !var.enable_analytics_version_prune && |
| var.console_mail_from == "" && var.console_mail_region == "" && |
| var.store_bucket_prefix == "" && !var.store_scanning && |
| var.scope_ssm_parameter_reads && var.deny_release_key_reads && |
| @@ -446,6 +446,43 @@ resource "aws_iam_role_policy" "host_costexplorer" { |
| }) |
| } |
| +# Analytics version prune (the console's daily statistics prune, |
| +# internal/analytics): the deployment bucket is versioned and every day file |
| +# is rewritten on each usage flush, so deleting an expired day file for good |
| +# means deleting each of its versions and delete markers. Off by default: |
| +# only the box that runs the console needs it. Version listing is held to |
| +# the apps/ prefix. The version-delete resource pattern |
| +# apps/*/*/analytics/*/days/* is not an exact day-file boundary: IAM's `*` |
| +# also matches `/`, so it can match keys with `/analytics/` followed by |
| +# `/days/` at arbitrary depth. The prune code re-checks the expected prefix |
| +# and exact date-file leaf immediately before deleting each version. The data |
| +# bucket grants above are untouched. The deployment bucket's own box-evidence Deny |
| +# (deployment-buckets/main.tf, BoxRecordsAreNeverDeleted) covers control/ |
| +# only and still wins over any Allow. |
| +resource "aws_iam_role_policy" "host_analytics_prune" { |
| + count = var.enable_analytics_version_prune ? 1 : 0 |
| + name = "${var.iam_name}-analytics-prune" |
| + role = aws_iam_role.host.id |
| + policy = jsonencode({ |
| + Version = "2012-10-17" |
| + Statement = [ |
| + { |
| + Sid = "AnalyticsDayVersionList" |
| + Effect = "Allow" |
| + Action = ["s3:ListBucketVersions"] |
| + Resource = [var.deployment_bucket_arn] |
| + Condition = { StringLike = { "s3:prefix" = "apps/*" } } |
| + }, |
| + { |
| + Sid = "AnalyticsDayVersionDelete" |
| + Effect = "Allow" |
| + Action = ["s3:DeleteObjectVersion"] |
| + Resource = ["${var.deployment_bucket_arn}/apps/*/*/analytics/*/days/*"] |
| + }, |
| + ] |
| + }) |
| +} |
| + |
| # The agent's memwatch duty (internal/host/memwatch.go) publishes |
| # MemAvailablePercent and MemoryPressureSome60 once a minute. PutMetricData |
| # has no resource ARN; the namespace condition is the whole bound — this |
diff --git a/infra/modules/region-host/tests/analytics_prune.tftest.hcl b/infra/modules/region-host/tests/analytics_prune.tftest.hcl| new file mode 100644 |
| index 000000000..568d99bbe |
| --- /dev/null |
| +++ b/infra/modules/region-host/tests/analytics_prune.tftest.hcl |
| @@ -0,0 +1,131 @@ |
| +# Plan-time tests for the console's analytics version-prune grant |
| +# (aws_iam_role_policy.host_analytics_prune). mock_provider means no AWS |
| +# account and no credentials: these assert what the module WOULD create. |
| +mock_provider "aws" {} |
| + |
| +override_data { |
| + target = data.aws_vpcs.default |
| + values = { ids = ["vpc-0aaaaaaaaaaaaaaaa"] } |
| +} |
| + |
| +override_data { |
| + target = data.aws_caller_identity.current |
| + values = { account_id = "123456789012" } |
| +} |
| + |
| +# The termination queue's ARN feeds an EventBridge target, which the provider |
| +# validates as an ARN; the mock's random string is not one. |
| +override_resource { |
| + target = aws_sqs_queue.terminations |
| + values = { arn = "arn:aws:sqs:eu-west-1:123456789012:carlos-test-host-terminations" } |
| +} |
| + |
| +variables { |
| + name = "carlos-test-ie" |
| + sg_description = "carlos test host" |
| + iam_name = "carlos-test-host" |
| + instance_type = "t4g.small" |
| + root_volume_size = 20 |
| + user_data = "#!/bin/sh\n" |
| + deployment_bucket_arn = "arn:aws:s3:::carlos-test-platform" |
| + data_bucket_arn = "arn:aws:s3:::carlos-test-ie" |
| + ssm_parameter_arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/carlos/*" |
| +} |
| + |
| +run "off_by_default" { |
| + command = plan |
| + assert { |
| + condition = length(aws_iam_role_policy.host_analytics_prune) == 0 |
| + error_message = "enable_analytics_version_prune defaults to false and must create no policy" |
| + } |
| + # Off, the host's bucket policy still grants no version action on the |
| + # deployment bucket at all. |
| + assert { |
| + condition = alltrue([ |
| + for s in jsondecode(aws_iam_role_policy.host_buckets.policy).Statement : |
| + !(contains(flatten([s.Action]), "s3:ListBucketVersions") || contains(flatten([s.Action]), "s3:DeleteObjectVersion")) || |
| + !anytrue([for r in flatten([s.Resource]) : startswith(r, "arn:aws:s3:::carlos-test-platform")]) |
| + ]) |
| + error_message = "with the prune grant off, no deployment-bucket version action may appear in host_buckets" |
| + } |
| +} |
| + |
| +run "on_grants_exactly_the_analytics_day_versions" { |
| + command = plan |
| + variables { |
| + enable_analytics_version_prune = true |
| + } |
| + assert { |
| + condition = length(aws_iam_role_policy.host_analytics_prune) == 1 |
| + error_message = "enable_analytics_version_prune = true must create one policy" |
| + } |
| + assert { |
| + condition = aws_iam_role_policy.host_analytics_prune[0].name == "carlos-test-host-analytics-prune" |
| + error_message = "the policy is named <iam_name>-analytics-prune" |
| + } |
| + # The whole policy, literally: version listing on the deployment bucket |
| + # held to s3:prefix apps/*, version deletion on exactly the analytics day |
| + # file pattern, and nothing else. |
| + assert { |
| + condition = jsonencode(jsondecode(aws_iam_role_policy.host_analytics_prune[0].policy).Statement) == jsonencode([ |
| + { |
| + Action = ["s3:ListBucketVersions"] |
| + Condition = { StringLike = { "s3:prefix" = "apps/*" } } |
| + Effect = "Allow" |
| + Resource = ["arn:aws:s3:::carlos-test-platform"] |
| + Sid = "AnalyticsDayVersionList" |
| + }, |
| + { |
| + Action = ["s3:DeleteObjectVersion"] |
| + Effect = "Allow" |
| + Resource = ["arn:aws:s3:::carlos-test-platform/apps/*/*/analytics/*/days/*"] |
| + Sid = "AnalyticsDayVersionDelete" |
| + }, |
| + ]) |
| + error_message = "the prune grant must be exactly ListBucketVersions (s3:prefix apps/*) on the deployment bucket and DeleteObjectVersion on apps/*/*/analytics/*/days/*" |
| + } |
| + # Nothing in it reaches the data bucket. |
| + assert { |
| + condition = alltrue([ |
| + for s in jsondecode(aws_iam_role_policy.host_analytics_prune[0].policy).Statement : |
| + alltrue([for r in flatten([s.Resource]) : !startswith(r, "arn:aws:s3:::carlos-test-ie")]) |
| + ]) |
| + error_message = "the prune grant must not name the data bucket" |
| + } |
| + # The data-bucket version grants in host_buckets are unchanged by the |
| + # switch: the same three statements, the same resources. |
| + assert { |
| + condition = jsonencode([ |
| + for s in jsondecode(aws_iam_role_policy.host_buckets.policy).Statement : s |
| + if contains(flatten([s.Action]), "s3:GetObjectVersion") || contains(flatten([s.Action]), "s3:DeleteObjectVersion") || contains(flatten([s.Action]), "s3:ListBucketVersions") |
| + ]) == jsonencode([ |
| + { |
| + Action = ["s3:GetObjectVersion"] |
| + Effect = "Allow" |
| + Resource = ["arn:aws:s3:::carlos-test-ie/*"] |
| + Sid = "PullDoorObjectVersions" |
| + }, |
| + { |
| + Action = ["s3:DeleteObjectVersion"] |
| + Effect = "Allow" |
| + Resource = ["arn:aws:s3:::carlos-test-ie/*"] |
| + }, |
| + { |
| + Action = ["s3:ListBucketVersions"] |
| + Effect = "Allow" |
| + Resource = ["arn:aws:s3:::carlos-test-ie"] |
| + Sid = "PullDoorVersionList" |
| + }, |
| + ]) |
| + error_message = "the data bucket's version grants in host_buckets must be unchanged with the prune grant on" |
| + } |
| + # And the object grants on both buckets are the same as ever. |
| + assert { |
| + condition = jsonencode(jsondecode(aws_iam_role_policy.host_buckets.policy).Statement[0]) == jsonencode({ |
| + Action = ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"] |
| + Effect = "Allow" |
| + Resource = ["arn:aws:s3:::carlos-test-platform/*", "arn:aws:s3:::carlos-test-ie/*"] |
| + }) |
| + error_message = "the bucket object grants must be unchanged with the prune grant on" |
| + } |
| +} |
diff --git a/infra/modules/region-host/tests/group.tftest.hcl b/infra/modules/region-host/tests/group.tftest.hcl| index 15533596c..80562c839 100644 |
| --- a/infra/modules/region-host/tests/group.tftest.hcl |
| +++ b/infra/modules/region-host/tests/group.tftest.hcl |
| @@ -241,6 +241,11 @@ run "invalid_group_console" { |
| variables { enable_cost_explorer = true } |
| expect_failures = [aws_iam_role.host] |
| } |
| +run "invalid_group_analytics_prune" { |
| + command = plan |
| + variables { enable_analytics_version_prune = true } |
| + expect_failures = [aws_iam_role.host] |
| +} |
| run "invalid_group_relay" { |
| command = plan |
| variables { relay = true } |
diff --git a/infra/modules/region-host/variables.tf b/infra/modules/region-host/variables.tf| index fd0bff04e..77dff8649 100644 |
| --- a/infra/modules/region-host/variables.tf |
| +++ b/infra/modules/region-host/variables.tf |
| @@ -206,6 +206,12 @@ variable "enable_cost_explorer" { |
| default = false |
| } |
| +variable "enable_analytics_version_prune" { |
| + description = "Let this host's role list object versions under apps/ in the deployment bucket and delete versions matching apps/*/*/analytics/*/days/*. In IAM, * also matches /, so this pattern can match keys with /analytics/ then /days/ at arbitrary depth; the prune code enforces the expected prefix and exact date-file leaf before deleting. Off by default. Set it only on the box that runs the console, in fixed mode." |
| + type = bool |
| + default = false |
| +} |
| + |
| variable "alerts_email" { |
| description = "Email address for a regional alerts topic created by this module. Leave empty when using alerts_topic_arn. If both inputs are empty, alarm notifications are disabled." |
| type = string |
diff --git a/internal/analytics/prune.go b/internal/analytics/prune.go| new file mode 100644 |
| index 000000000..0be37b01f |
| --- /dev/null |
| +++ b/internal/analytics/prune.go |
| @@ -0,0 +1,431 @@ |
| +package analytics |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "sort" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/applog" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// PruneOptions bounds a console retention pass. StartAt resumes at a box's |
| +// days prefix (or its app/account prefix if discovery timed out), always |
| +// listing that box from the beginning so failed deletes |
| +// are retried. A completed pass clears NextBox and the next pass starts over. |
| +type PruneOptions struct { |
| + // RetentionDays is the operator-selected age limit; zero keeps everything. |
| + RetentionDays int |
| + DryRun bool |
| + PageSize int |
| + MaxDeletes int |
| + MaxKeys int |
| + StartAt string |
| + Logf func(string, ...any) |
| +} |
| + |
| +type PruneStats struct { |
| + Apps, Boxes, Listed, Deleted, WouldDelete, Malformed, Errors int |
| + ListCalls, DeleteCalls int |
| + KeysListed, VersionsListed, KeysDeleted, VersionsDeleted int |
| + KeysWouldDelete, VersionsWouldDelete int |
| + NextBox string |
| +} |
| + |
| +// RetentionCutoff is midnight UTC retentionDays calendar days before today. |
| +// Exactly N days ago is kept; N+1 days ago expires, regardless of time or zone. |
| +func RetentionCutoff(now time.Time, retentionDays int) time.Time { |
| + today := now.UTC().Truncate(24 * time.Hour) |
| + // No valid YYYY-MM-DD leaf predates year zero. Clamp there so a very |
| + // large positive setting cannot overflow AddDate and expire recent data. |
| + earliest := time.Date(0, 1, 1, 0, 0, 0, 0, time.UTC) |
| + if int64(retentionDays) >= today.Unix()/86400-earliest.Unix()/86400 { |
| + return earliest |
| + } |
| + return today.AddDate(0, 0, -retentionDays) |
| +} |
| + |
| +// Prune removes expired analytics day files and, where supported, every |
| +// version and delete marker. Stores without bounded paging fail closed. |
| +// MaxDeletes and MaxKeys count versions in version mode, keys otherwise; |
| +// the console also supplies a deadline. A saved box restarts at its oldest |
| +// remaining entry, including when the previous cap fell within one key. |
| +func Prune(ctx context.Context, st release.Store, now time.Time, opt PruneOptions) (stats PruneStats, result error) { |
| + stats.NextBox = opt.StartAt |
| + if opt.RetentionDays < 0 { |
| + stats.Errors++ |
| + return stats, fmt.Errorf("analytics prune: retention days must not be negative") |
| + } |
| + if opt.RetentionDays == 0 { |
| + return stats, nil |
| + } |
| + if opt.Logf == nil { |
| + opt.Logf = log.Printf |
| + } |
| + if opt.PageSize <= 0 || opt.PageSize > 1000 { |
| + opt.PageSize = 1000 |
| + } |
| + if opt.MaxDeletes <= 0 { |
| + opt.MaxDeletes = 10000 |
| + } |
| + if opt.MaxKeys <= 0 { |
| + opt.MaxKeys = 100000 |
| + } |
| + pages, keyPaging := st.(release.PageLister) |
| + versionPages, versionPaging := st.(release.VersionPager) |
| + versionDeletes, versionDeleting := st.(release.VersionDeleter) |
| + useVersions := versionPaging && versionDeleting |
| + if !keyPaging && !useVersions { |
| + stats.Errors++ |
| + return stats, fmt.Errorf("analytics prune: store has no bounded paging") |
| + } |
| + cutoff := RetentionCutoff(now, opt.RetentionDays) |
| + var errs []error |
| + fail := func(err error) { stats.Errors++; errs = append(errs, err); opt.Logf("analytics prune: %v", err) } |
| + malformed := func(key string) { stats.Malformed++; opt.Logf("analytics prune: skipped malformed key %q", key) } |
| + defer func() { result = errors.Join(append(errs, result)...) }() |
| + permissionFailure := func(permission string, err error) { |
| + useVersions = false |
| + fail(fmt.Errorf("analytics prune: missing %s permission; noncurrent versions remain; falling back to current-key deletion for this pass: %w", permission, err)) |
| + } |
| + // Version-aware discovery also finds an entire app/box whose current |
| + // objects are delete markers. ListObjects delimiter listings hide it. |
| + dirs := func(prefix string) ([]string, error) { |
| + if err := ctx.Err(); err != nil { |
| + return nil, err |
| + } |
| + if versionDirs, ok := st.(release.VersionDirLister); useVersions && ok { |
| + dirs, calls, err := versionDirs.ListVersionDirsWithCount(ctx, prefix) |
| + stats.ListCalls += calls |
| + if !errors.Is(err, release.ErrVersionAccessDenied) { |
| + sort.Strings(dirs) |
| + return dirs, err |
| + } |
| + permissionFailure("s3:ListBucketVersions", err) |
| + } |
| + if counted, ok := st.(release.CountedDirLister); ok { |
| + dirs, calls, err := counted.ListDirsWithCount(ctx, prefix) |
| + stats.ListCalls += calls |
| + sort.Strings(dirs) |
| + return dirs, err |
| + } |
| + stats.ListCalls++ |
| + dirs, err := st.ListDirs(ctx, prefix) |
| + sort.Strings(dirs) |
| + return dirs, err |
| + } |
| + accounts, err := dirs("apps/") |
| + if err != nil { |
| + fail(err) |
| + return stats, nil |
| + } |
| + attempted := 0 |
| + for _, accountDir := range accounts { |
| + acct, valid := pruneChild("apps/", accountDir) |
| + if !valid || !release.ValidAccount(acct) { |
| + malformed(accountDir) |
| + continue |
| + } |
| + if accountDir < opt.StartAt && !strings.HasPrefix(opt.StartAt, accountDir) { |
| + continue |
| + } |
| + if accountDir > stats.NextBox { |
| + stats.NextBox = accountDir |
| + } |
| + apps, err := dirs(accountDir) |
| + if err != nil { |
| + fail(err) |
| + if ctx.Err() != nil { |
| + return stats, nil |
| + } |
| + continue |
| + } |
| + for _, appDir := range apps { |
| + app, valid := pruneChild(accountDir, appDir) |
| + if !valid || applog.CheckApp(acct, app) != nil { |
| + malformed(appDir) |
| + continue |
| + } |
| + // Account and app listings are small delimiter listings. Skip whole apps |
| + // preceding the saved box, without listing their analytics again. |
| + prefix, _ := Prefix(acct, app) |
| + if opt.StartAt != "" && prefix < opt.StartAt && !strings.HasPrefix(opt.StartAt, prefix) { |
| + continue |
| + } |
| + stats.Apps++ |
| + if prefix > stats.NextBox { |
| + stats.NextBox = prefix |
| + } |
| + boxes, err := dirs(prefix) |
| + if err != nil { |
| + fail(err) |
| + if ctx.Err() != nil { |
| + return stats, nil |
| + } |
| + continue |
| + } |
| + for _, boxDir := range boxes { |
| + box, valid := pruneChild(prefix, boxDir) |
| + if !valid || applog.CheckSegment("box", box) != nil { |
| + malformed(boxDir) |
| + continue |
| + } |
| + days, err := BoxPrefix(acct, app, box) |
| + if err != nil { |
| + malformed(boxDir) |
| + continue |
| + } |
| + if days < opt.StartAt { |
| + continue |
| + } |
| + stats.NextBox = days |
| + if err := ctx.Err(); err != nil { |
| + fail(err) |
| + return stats, nil |
| + } |
| + stats.Boxes++ |
| + after, versionMarker := "", "" |
| + seenVersions := map[[2]string]bool{} |
| + listedKeys, deletedKeys, wouldKeys := map[string]bool{}, map[string]bool{}, map[string]bool{} |
| + // A mature box normally has one expired day and many retained |
| + // days. Start small so retained files do not exhaust the pass budget; |
| + // grow only while catching up an older backlog. |
| + pageSize := min(8, opt.PageSize) |
| + for { |
| + if err := ctx.Err(); err != nil { |
| + fail(err) |
| + return stats, nil |
| + } |
| + if attempted >= opt.MaxDeletes || stats.Listed >= opt.MaxKeys { |
| + return stats, nil |
| + } |
| + limit := min(pageSize, opt.MaxKeys-stats.Listed) |
| + stats.ListCalls++ |
| + var keys []string |
| + var versions []release.ObjectVersion |
| + nextKey, nextVersion := "", "" |
| + versionPage := useVersions |
| + if versionPage { |
| + versions, nextKey, nextVersion, err = versionPages.ListVersionsPage(ctx, days, after, versionMarker, limit) |
| + if errors.Is(err, release.ErrVersionAccessDenied) { |
| + permissionFailure("s3:ListBucketVersions", err) |
| + after, versionMarker = "", "" |
| + continue |
| + } |
| + for _, v := range versions { |
| + keys = append(keys, v.Key) |
| + } |
| + } else if keyPaging { |
| + keys, err = pages.ListPage(ctx, days, after, limit) |
| + } else { |
| + err = fmt.Errorf("analytics prune: store has no bounded current-key paging for fallback") |
| + } |
| + if err != nil { |
| + fail(err) |
| + if ctx.Err() != nil { |
| + return stats, nil |
| + } |
| + break |
| + } |
| + // Refuse unordered, repeated or oversized pages before using the |
| + // date ordering to stop. Version IDs are opaque, not sortable. |
| + previous := after |
| + for i, key := range keys { |
| + bad := key < previous || (!versionPage && key == previous) || len(keys) > limit |
| + if versionPage { |
| + v := versions[i] |
| + id := [2]string{v.Key, v.VersionID} |
| + bad = bad || v.VersionID == "" || seenVersions[id] |
| + seenVersions[id] = true |
| + } |
| + if bad { |
| + fail(fmt.Errorf("analytics prune: invalid page after %q", after)) |
| + return stats, nil |
| + } |
| + previous = key |
| + } |
| + if versionPage && ((nextKey == "" && nextVersion != "") || |
| + (nextKey != "" && (len(keys) == 0 || nextKey != previous || nextVersion == "" || (nextKey == after && nextVersion == versionMarker)))) { |
| + fail(fmt.Errorf("analytics prune: invalid version continuation after %q", after)) |
| + return stats, nil |
| + } |
| + stats.Listed += len(keys) |
| + if versionPage { |
| + stats.VersionsListed += len(versions) |
| + } |
| + for _, key := range keys { |
| + if !listedKeys[key] { |
| + stats.KeysListed++ |
| + listedKeys[key] = true |
| + } |
| + } |
| + var batch []string |
| + var versionBatch []release.ObjectVersion |
| + stop := false |
| + for i, key := range keys { |
| + expired, valid := pruneEligible(days, key, cutoff) |
| + if !valid { |
| + malformed(key) |
| + continue |
| + } |
| + if !expired { |
| + stop = true |
| + break |
| + } |
| + if attempted+len(batch) >= opt.MaxDeletes { |
| + break |
| + } |
| + batch = append(batch, key) |
| + if versionPage { |
| + versionBatch = append(versionBatch, versions[i]) |
| + } |
| + } |
| + // This is the sole deletion boundary: revalidate every key against the |
| + // expected prefix and UTC cutoff immediately before handing it to Store. |
| + guarded := batch[:0] |
| + guardedVersions := versionBatch[:0] |
| + for i, key := range batch { |
| + if expired, valid := pruneEligible(days, key, cutoff); valid && expired { |
| + guarded = append(guarded, key) |
| + if versionPage { |
| + guardedVersions = append(guardedVersions, versionBatch[i]) |
| + } |
| + } else { |
| + malformed(key) |
| + } |
| + } |
| + attempted += len(guarded) |
| + if opt.DryRun { |
| + for i, key := range guarded { |
| + if versionPage { |
| + v := guardedVersions[i] |
| + opt.Logf("analytics prune: would delete %q version=%q delete_marker=%t", key, v.VersionID, v.IsDeleteMarker) |
| + } else { |
| + opt.Logf("analytics prune: would delete %q", key) |
| + } |
| + } |
| + stats.WouldDelete += len(guarded) |
| + if versionPage { |
| + stats.VersionsWouldDelete += len(guarded) |
| + } |
| + for _, key := range guarded { |
| + if !wouldKeys[key] { |
| + stats.KeysWouldDelete++ |
| + wouldKeys[key] = true |
| + } |
| + } |
| + } else if len(guarded) > 0 { |
| + if versionPage { |
| + stats.DeleteCalls++ |
| + err := versionDeletes.DeleteVersions(ctx, guardedVersions) |
| + var partial *release.VersionDeleteError |
| + known := err == nil || errors.As(err, &partial) |
| + for _, v := range guardedVersions { |
| + if known && (partial == nil || partial.Failed[v] == nil) { |
| + stats.Deleted++ |
| + stats.VersionsDeleted++ |
| + if !deletedKeys[v.Key] { |
| + stats.KeysDeleted++ |
| + deletedKeys[v.Key] = true |
| + } |
| + } |
| + } |
| + if errors.Is(err, release.ErrVersionAccessDenied) { |
| + permissionFailure("s3:DeleteObjectVersion", err) |
| + after, versionMarker = "", "" |
| + continue |
| + } |
| + if err != nil { |
| + fail(err) |
| + } |
| + } else if batcher, ok := st.(release.BatchDeleter); ok { |
| + stats.DeleteCalls++ |
| + err := batcher.DeleteKeys(ctx, guarded) |
| + if err == nil { |
| + stats.Deleted += len(guarded) |
| + for _, key := range guarded { |
| + if !deletedKeys[key] { |
| + stats.KeysDeleted++ |
| + deletedKeys[key] = true |
| + } |
| + } |
| + } else { |
| + var partial *release.BatchDeleteError |
| + if errors.As(err, &partial) { |
| + for _, key := range guarded { |
| + if perKey, failed := partial.Failed[key]; failed { |
| + opt.Logf("analytics prune: delete %q: %v", key, perKey) |
| + } else { |
| + stats.Deleted++ |
| + if !deletedKeys[key] { |
| + stats.KeysDeleted++ |
| + deletedKeys[key] = true |
| + } |
| + } |
| + } |
| + } |
| + fail(err) |
| + } |
| + } else { |
| + for _, key := range guarded { |
| + stats.DeleteCalls++ |
| + if err := st.Delete(ctx, key); err != nil { |
| + fail(err) |
| + } else { |
| + stats.Deleted++ |
| + if !deletedKeys[key] { |
| + stats.KeysDeleted++ |
| + deletedKeys[key] = true |
| + } |
| + } |
| + } |
| + } |
| + } |
| + if attempted >= opt.MaxDeletes || stats.Listed >= opt.MaxKeys { |
| + return stats, nil |
| + } |
| + if stop || (versionPage && nextKey == "") || (!versionPage && len(keys) < limit) { |
| + break |
| + } |
| + if versionPage { |
| + after, versionMarker = nextKey, nextVersion |
| + } else { |
| + after = keys[len(keys)-1] |
| + } |
| + pageSize = min(pageSize*2, opt.PageSize) |
| + } |
| + } |
| + } |
| + } |
| + if err := ctx.Err(); err != nil { |
| + fail(err) |
| + return stats, nil |
| + } |
| + stats.NextBox = "" |
| + return stats, nil |
| +} |
| + |
| +func pruneChild(prefix, dir string) (string, bool) { |
| + rest, ok := strings.CutPrefix(dir, prefix) |
| + leaf, slash := strings.CutSuffix(rest, "/") |
| + return leaf, ok && slash && leaf != "." && leaf != ".." && !strings.ContainsAny(leaf, "/\\") && leaf != "" |
| +} |
| + |
| +// pruneEligible accepts only one exact date leaf under the supplied days |
| +// prefix. Neither a nested object nor an adjacent family can become a delete. |
| +func pruneEligible(prefix, key string, cutoff time.Time) (expired, valid bool) { |
| + leaf, ok := strings.CutPrefix(key, prefix) |
| + if !ok || len(leaf) != len("2006-01-02.json") || !strings.HasSuffix(leaf, ".json") { |
| + return false, false |
| + } |
| + date := strings.TrimSuffix(leaf, ".json") |
| + d, err := time.Parse("2006-01-02", date) |
| + if err != nil || d.Format("2006-01-02") != date { |
| + return false, false |
| + } |
| + return d.Before(cutoff), true |
| +} |
diff --git a/internal/analytics/prune_test.go b/internal/analytics/prune_test.go| new file mode 100644 |
| index 000000000..2002b6c02 |
| --- /dev/null |
| +++ b/internal/analytics/prune_test.go |
| @@ -0,0 +1,863 @@ |
| +package analytics |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "slices" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// pruneNow is mid-afternoon UTC so a wrong time-of-day rule would show. |
| +// 400 days before 2026-11-11 is 2025-10-07: that date is kept, 2025-10-06 goes. |
| +var pruneNow = time.Date(2026, 11, 11, 15, 30, 0, 0, time.UTC) |
| + |
| +type pruneLog struct{ lines []string } |
| + |
| +func (l *pruneLog) logf(f string, a ...any) { l.lines = append(l.lines, fmt.Sprintf(f, a...)) } |
| +func (l *pruneLog) has(sub string) bool { |
| + for _, s := range l.lines { |
| + if strings.Contains(s, sub) { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// pruneStore is a Store wrapper that exposes PageLister (and nothing else |
| +// optional: no BatchDeleter), counts calls, and lets a test replace the |
| +// listings. |
| +type pruneStore struct { |
| + release.Store |
| + inner *release.DirStore |
| + pageCalls int |
| + dirCalls int |
| + deletes []string |
| + page func(ctx context.Context, prefix, after string, limit int) ([]string, error) |
| + dirs func(prefix string) ([]string, error) |
| + pageSeen []string |
| + afterPage func(n int) |
| +} |
| + |
| +func newPruneStore(t *testing.T) *pruneStore { |
| + t.Helper() |
| + d := release.NewDirStore(t.TempDir()) |
| + return &pruneStore{Store: d, inner: d} |
| +} |
| + |
| +func (s *pruneStore) ListPage(ctx context.Context, prefix, after string, limit int) ([]string, error) { |
| + s.pageCalls++ |
| + s.pageSeen = append(s.pageSeen, prefix) |
| + if s.afterPage != nil { |
| + defer s.afterPage(s.pageCalls) |
| + } |
| + if s.page != nil { |
| + return s.page(ctx, prefix, after, limit) |
| + } |
| + return s.inner.ListPage(ctx, prefix, after, limit) |
| +} |
| + |
| +func (s *pruneStore) ListDirs(ctx context.Context, prefix string) ([]string, error) { |
| + s.dirCalls++ |
| + if s.dirs != nil { |
| + return s.dirs(prefix) |
| + } |
| + return s.inner.ListDirs(ctx, prefix) |
| +} |
| + |
| +func (s *pruneStore) Delete(ctx context.Context, key string) error { |
| + s.deletes = append(s.deletes, key) |
| + return s.inner.Delete(ctx, key) |
| +} |
| + |
| +// batchStore adds a BatchDeleter whose behaviour the test controls. |
| +type batchStore struct { |
| + *pruneStore |
| + batches [][]string |
| + failing map[string]bool |
| +} |
| + |
| +func (b *batchStore) DeleteKeys(ctx context.Context, keys []string) error { |
| + b.batches = append(b.batches, slices.Clone(keys)) |
| + failed := map[string]error{} |
| + for _, k := range keys { |
| + if b.failing[k] { |
| + failed[k] = errors.New("denied") |
| + continue |
| + } |
| + if err := b.inner.Delete(ctx, k); err != nil { |
| + failed[k] = err |
| + } |
| + } |
| + if len(failed) > 0 { |
| + return &release.BatchDeleteError{Failed: failed} |
| + } |
| + return nil |
| +} |
| + |
| +func putKey(t *testing.T, st release.Store, key string) { |
| + t.Helper() |
| + if _, err := st.Put(context.Background(), key, []byte("{}"), ""); err != nil { |
| + t.Fatalf("put %s: %v", key, err) |
| + } |
| +} |
| + |
| +func dayAgo(t *testing.T, acct, app, box string, n int) string { |
| + t.Helper() |
| + k, err := DayKey(acct, app, box, pruneNow.AddDate(0, 0, -n).Format("2006-01-02")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return k |
| +} |
| + |
| +func allKeys(t *testing.T, st release.Store) []string { |
| + t.Helper() |
| + keys, err := st.List(context.Background(), "") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + slices.Sort(keys) |
| + return keys |
| +} |
| + |
| +func mustNotExist(t *testing.T, st release.Store, keys ...string) { |
| + t.Helper() |
| + for _, k := range keys { |
| + if _, _, err := st.Get(context.Background(), k); !errors.Is(err, os.ErrNotExist) { |
| + t.Errorf("%s should be deleted, Get err = %v", k, err) |
| + } |
| + } |
| +} |
| + |
| +func mustExist(t *testing.T, st release.Store, keys ...string) { |
| + t.Helper() |
| + for _, k := range keys { |
| + if _, _, err := st.Get(context.Background(), k); err != nil { |
| + t.Errorf("%s should be kept: %v", k, err) |
| + } |
| + } |
| +} |
| + |
| +func runPrune(t *testing.T, st release.Store, opt PruneOptions) (PruneStats, *pruneLog) { |
| + t.Helper() |
| + l := &pruneLog{} |
| + opt.Logf = l.logf |
| + stats, err := Prune(context.Background(), st, pruneNow, opt) |
| + if err != nil { |
| + t.Fatalf("Prune: %v (stats %+v)", err, stats) |
| + } |
| + return stats, l |
| +} |
| + |
| +func TestPruneCutoffIsUTCDate(t *testing.T) { |
| + want := time.Date(2025, 10, 7, 0, 0, 0, 0, time.UTC) |
| + if got := RetentionCutoff(pruneNow, 400); !got.Equal(want) { |
| + t.Fatalf("cutoff = %v, want %v", got, want) |
| + } |
| + // 22:00 in UTC-8 on Nov 11 is already Nov 12 in UTC. |
| + west := time.Date(2026, 11, 11, 22, 0, 0, 0, time.FixedZone("W", -8*3600)) |
| + want = time.Date(2025, 10, 8, 0, 0, 0, 0, time.UTC) |
| + if got := RetentionCutoff(west, 400); !got.Equal(want) { |
| + t.Fatalf("zoned cutoff = %v, want %v", got, want) |
| + } |
| + // Midnight and the last second of the same UTC day agree. |
| + a := RetentionCutoff(time.Date(2026, 11, 11, 0, 0, 0, 0, time.UTC), 400) |
| + b := RetentionCutoff(time.Date(2026, 11, 11, 23, 59, 59, 0, time.UTC), 400) |
| + if !a.Equal(b) { |
| + t.Fatalf("cutoff moved within a day: %v vs %v", a, b) |
| + } |
| +} |
| + |
| +func TestPruneBoundariesForConfiguredRetention(t *testing.T) { |
| + for _, retention := range []int{30, 400} { |
| + t.Run(fmt.Sprintf("%d days", retention), func(t *testing.T) { |
| + st := newPruneStore(t) |
| + keys := map[int]string{} |
| + for _, age := range []int{retention - 1, retention, retention + 1} { |
| + keys[age] = dayAgo(t, "acme", "shop", "b1", age) |
| + putKey(t, st, keys[age]) |
| + } |
| + stats, _ := runPrune(t, st, PruneOptions{RetentionDays: retention}) |
| + mustNotExist(t, st, keys[retention+1]) |
| + mustExist(t, st, keys[retention-1], keys[retention]) |
| + if stats.Deleted != 1 || stats.Errors != 0 || stats.Malformed != 0 { |
| + t.Fatalf("stats = %+v", stats) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPruneDisabledRetentionMakesNoStoreCalls(t *testing.T) { |
| + for _, dry := range []bool{false, true} { |
| + t.Run(fmt.Sprintf("dry-run=%t", dry), func(t *testing.T) { |
| + stats, err := Prune(context.Background(), nil, pruneNow, PruneOptions{RetentionDays: 0, DryRun: dry}) |
| + if err != nil || stats != (PruneStats{}) { |
| + t.Fatalf("Prune disabled: stats=%+v err=%v", stats, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPruneNegativeRetentionFailsBeforeStoreCalls(t *testing.T) { |
| + stats, err := Prune(context.Background(), nil, pruneNow, PruneOptions{RetentionDays: -1}) |
| + if err == nil || stats != (PruneStats{Errors: 1}) { |
| + t.Fatalf("Prune negative retention: stats=%+v err=%v", stats, err) |
| + } |
| +} |
| + |
| +func TestPruneBoundaryUsesUTCNotLocalZone(t *testing.T) { |
| + st := newPruneStore(t) |
| + k1007 := "apps/acme/shop/analytics/b1/days/2025-10-07.json" |
| + k1008 := "apps/acme/shop/analytics/b1/days/2025-10-08.json" |
| + putKey(t, st, k1007) |
| + putKey(t, st, k1008) |
| + west := time.Date(2026, 11, 11, 22, 0, 0, 0, time.FixedZone("W", -8*3600)) // UTC Nov 12 |
| + if _, err := Prune(context.Background(), st, west, PruneOptions{RetentionDays: 400, Logf: func(string, ...any) {}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + mustNotExist(t, st, k1007) |
| + mustExist(t, st, k1008) |
| +} |
| + |
| +func TestPruneMultipleAppsAndBoxes(t *testing.T) { |
| + st := release.NewDirStore(t.TempDir()) |
| + type loc struct{ acct, app, box string } |
| + locs := []loc{ |
| + {"acme", "shop", "b1"}, {"acme", "shop", "b2"}, {"acme", "blog", "b1"}, |
| + {"zeta", "docs", "b9"}, {"zeta", "docs", "b10"}, |
| + } |
| + var old, keep []string |
| + for _, l := range locs { |
| + for _, n := range []int{900, 500, 401} { |
| + k := dayAgo(t, l.acct, l.app, l.box, n) |
| + putKey(t, st, k) |
| + old = append(old, k) |
| + } |
| + for _, n := range []int{400, 100, 0} { |
| + k := dayAgo(t, l.acct, l.app, l.box, n) |
| + putKey(t, st, k) |
| + keep = append(keep, k) |
| + } |
| + } |
| + stats, _ := runPrune(t, st, PruneOptions{RetentionDays: 400}) |
| + mustNotExist(t, st, old...) |
| + mustExist(t, st, keep...) |
| + if stats.Apps != 3 || stats.Boxes != 5 || stats.Deleted != len(old) || stats.NextBox != "" { |
| + t.Fatalf("stats = %+v", stats) |
| + } |
| + // Batch path was used (DirStore is a BatchDeleter): one call per box. |
| + if stats.DeleteCalls != 5 { |
| + t.Fatalf("DeleteCalls = %d, want 5", stats.DeleteCalls) |
| + } |
| +} |
| + |
| +func TestPrunePagingFindsEveryOldKeyAndStopsEarly(t *testing.T) { |
| + st := newPruneStore(t) |
| + var old []string |
| + var keep []string |
| + for i := 0; i < 5; i++ { |
| + k := dayAgo(t, "acme", "shop", "b1", 900-i) |
| + putKey(t, st, k) |
| + old = append(old, k) |
| + } |
| + for _, n := range []int{300, 200, 1} { |
| + k := dayAgo(t, "acme", "shop", "b1", n) |
| + putKey(t, st, k) |
| + keep = append(keep, k) |
| + } |
| + stats, _ := runPrune(t, st, PruneOptions{RetentionDays: 400, PageSize: 2}) |
| + mustNotExist(t, st, old...) |
| + mustExist(t, st, keep...) |
| + // Pages: [o1 o2] [o3 o4] [o5 n1]; n1 is past the cutoff, so no 4th page. |
| + if st.pageCalls != 3 { |
| + t.Fatalf("ListPage calls = %d, want 3", st.pageCalls) |
| + } |
| + if stats.ListCalls != st.pageCalls+st.dirCalls { |
| + t.Fatalf("ListCalls = %d, want %d", stats.ListCalls, st.pageCalls+st.dirCalls) |
| + } |
| + if stats.Deleted != 5 || stats.Listed != 6 { |
| + t.Fatalf("stats = %+v", stats) |
| + } |
| +} |
| + |
| +func TestPrunePagingAllOldExactPageMultiple(t *testing.T) { |
| + st := newPruneStore(t) |
| + var old []string |
| + for i := 0; i < 4; i++ { |
| + k := dayAgo(t, "acme", "shop", "b1", 700-i) |
| + putKey(t, st, k) |
| + old = append(old, k) |
| + } |
| + stats, _ := runPrune(t, st, PruneOptions{RetentionDays: 400, PageSize: 2}) |
| + mustNotExist(t, st, old...) |
| + // [o o] [o o] [] : the empty third page ends the box. |
| + if st.pageCalls != 3 || stats.Deleted != 4 { |
| + t.Fatalf("pageCalls %d stats %+v", st.pageCalls, stats) |
| + } |
| +} |
| + |
| +func TestPrunePagingTwoBoxesSmallPages(t *testing.T) { |
| + st := newPruneStore(t) |
| + var old []string |
| + for _, box := range []string{"b1", "b2"} { |
| + for i := 0; i < 7; i++ { |
| + k := dayAgo(t, "acme", "shop", box, 800-i) |
| + putKey(t, st, k) |
| + old = append(old, k) |
| + } |
| + putKey(t, st, dayAgo(t, "acme", "shop", box, 10)) |
| + } |
| + stats, _ := runPrune(t, st, PruneOptions{RetentionDays: 400, PageSize: 2}) |
| + mustNotExist(t, st, old...) |
| + if stats.Deleted != 14 || len(allKeys(t, st)) != 2 { |
| + t.Fatalf("stats %+v keys %v", stats, allKeys(t, st)) |
| + } |
| +} |
| + |
| +func TestPruneLeavesAdjacentKeysAndLogsMalformed(t *testing.T) { |
| + st := newPruneStore(t) |
| + oldKey := "apps/acme/shop/analytics/b1/days/2020-01-01.json" |
| + putKey(t, st, oldKey) |
| + untouched := []string{ |
| + // adjacent families with old-looking names |
| + "apps/acme/shop/logs/b1/2020-01-01.json", |
| + "apps/acme/shop/errors/b1/2020-01-01.json", |
| + "apps/acme/shop/site/2020-01-01.json", |
| + // sibling files in the box dir and the analytics dir |
| + "apps/acme/shop/analytics/b1/2020-01-01.json", |
| + "apps/acme/shop/analytics/b1/meta.json", |
| + "apps/acme/shop/analytics/b1/days-old/2020-01-01.json", |
| + "apps/acme/shop/analytics/2020-01-01.json", |
| + // nested under days/ |
| + "apps/acme/shop/analytics/b1/days/nested/2020-01-01.json", |
| + "apps/acme/shop/analytics/b1/days/2019-01-01/2020-01-01.json", |
| + // malformed leaves directly under days/ |
| + "apps/acme/shop/analytics/b1/days/2025-13-40.json", |
| + "apps/acme/shop/analytics/b1/days/2020-01-01.json.bak", |
| + "apps/acme/shop/analytics/b1/days/2020-1-1.json", |
| + "apps/acme/shop/analytics/b1/days/2020-01-01.JSON", |
| + "apps/acme/shop/analytics/b1/days/notadate.json", |
| + // another app's box |
| + "apps/acme/shop2/analytics/b1/days/2020-01-01.json", |
| + } |
| + for _, k := range untouched { |
| + putKey(t, st, k) |
| + } |
| + // shop2 is a real app and IS pruned; take it out of the untouched set. |
| + untouched = untouched[:len(untouched)-1] |
| + stats, l := runPrune(t, st, PruneOptions{RetentionDays: 400}) |
| + mustNotExist(t, st, oldKey, "apps/acme/shop2/analytics/b1/days/2020-01-01.json") |
| + mustExist(t, st, untouched...) |
| + if stats.Deleted != 2 { |
| + t.Fatalf("Deleted = %d, want 2 (shop and shop2)", stats.Deleted) |
| + } |
| + for _, bad := range []string{"2025-13-40.json", "2020-01-01.json.bak", "2020-1-1.json", "2020-01-01.JSON", "notadate.json", "nested/2020-01-01.json"} { |
| + if !l.has("malformed") || !l.has(bad) { |
| + t.Errorf("no malformed log for %s; log: %v", bad, l.lines) |
| + } |
| + } |
| + if stats.Malformed < 7 { |
| + t.Fatalf("Malformed = %d, want at least 7", stats.Malformed) |
| + } |
| +} |
| + |
| +func TestPruneDryRunDeletesNothing(t *testing.T) { |
| + st := newPruneStore(t) |
| + old1 := dayAgo(t, "acme", "shop", "b1", 500) |
| + old2 := dayAgo(t, "acme", "shop", "b2", 401) |
| + keep := dayAgo(t, "acme", "shop", "b1", 400) |
| + for _, k := range []string{old1, old2, keep} { |
| + putKey(t, st, k) |
| + } |
| + before := allKeys(t, st) |
| + stats, l := runPrune(t, st, PruneOptions{RetentionDays: 400, DryRun: true}) |
| + if got := allKeys(t, st); !slices.Equal(got, before) { |
| + t.Fatalf("dry run changed the store: %v -> %v", before, got) |
| + } |
| + if stats.WouldDelete != 2 || stats.Deleted != 0 || stats.DeleteCalls != 0 || len(st.deletes) != 0 { |
| + t.Fatalf("stats = %+v deletes %v", stats, st.deletes) |
| + } |
| + if !l.has(fmt.Sprintf("would delete %q", old1)) || !l.has(fmt.Sprintf("would delete %q", old2)) { |
| + t.Fatalf("dry run did not log both keys: %v", l.lines) |
| + } |
| + if l.has(keep) { |
| + t.Fatalf("dry run mentioned a kept key: %v", l.lines) |
| + } |
| +} |
| + |
| +func TestPruneIsIdempotent(t *testing.T) { |
| + st := newPruneStore(t) |
| + for _, n := range []int{900, 450, 401, 400, 5} { |
| + putKey(t, st, dayAgo(t, "acme", "shop", "b1", n)) |
| + } |
| + first, _ := runPrune(t, st, PruneOptions{RetentionDays: 400, PageSize: 2}) |
| + if first.Deleted != 3 { |
| + t.Fatalf("first = %+v", first) |
| + } |
| + after := allKeys(t, st) |
| + second, _ := runPrune(t, st, PruneOptions{RetentionDays: 400, PageSize: 2}) |
| + if second.Deleted != 0 || second.DeleteCalls != 0 || second.WouldDelete != 0 || second.Errors != 0 { |
| + t.Fatalf("second = %+v", second) |
| + } |
| + if got := allKeys(t, st); !slices.Equal(got, after) { |
| + t.Fatalf("second run changed the store: %v -> %v", after, got) |
| + } |
| +} |
| + |
| +func TestPruneFallsBackToPerKeyDeleteWithoutBatchDeleter(t *testing.T) { |
| + st := newPruneStore(t) // PageLister yes, BatchDeleter no |
| + if _, ok := release.Store(st).(release.BatchDeleter); ok { |
| + t.Fatal("fixture unexpectedly has a BatchDeleter") |
| + } |
| + if _, ok := release.Store(st).(release.PageLister); !ok { |
| + t.Fatal("fixture lost its PageLister") |
| + } |
| + var old []string |
| + for i := 0; i < 5; i++ { |
| + k := dayAgo(t, "acme", "shop", "b1", 600+i) |
| + putKey(t, st, k) |
| + old = append(old, k) |
| + } |
| + keep := dayAgo(t, "acme", "shop", "b1", 399) |
| + putKey(t, st, keep) |
| + stats, _ := runPrune(t, st, PruneOptions{RetentionDays: 400, PageSize: 2}) |
| + mustNotExist(t, st, old...) |
| + mustExist(t, st, keep) |
| + if stats.Deleted != 5 || stats.DeleteCalls != 5 || len(st.deletes) != 5 { |
| + t.Fatalf("stats %+v deletes %v", stats, st.deletes) |
| + } |
| +} |
| + |
| +func TestPruneFailsClosedWithoutPageLister(t *testing.T) { |
| + d := release.NewDirStore(t.TempDir()) |
| + k := "apps/acme/shop/analytics/b1/days/2020-01-01.json" |
| + putKey(t, d, k) |
| + var bare release.Store = struct{ release.Store }{d} // hides ListPage and DeleteKeys |
| + l := &pruneLog{} |
| + stats, err := Prune(context.Background(), bare, pruneNow, PruneOptions{RetentionDays: 400, Logf: l.logf}) |
| + if err == nil || !strings.Contains(err.Error(), "paging") { |
| + t.Fatalf("err = %v, want a bounded-paging refusal", err) |
| + } |
| + if stats.Deleted != 0 || stats.ListCalls != 0 { |
| + t.Fatalf("stats = %+v", stats) |
| + } |
| + mustExist(t, d, k) |
| +} |
| + |
| +func TestPruneMaxDeletesAndNextBoxResume(t *testing.T) { |
| + st := newPruneStore(t) |
| + boxes := []string{"b1", "b2", "b3"} |
| + var old []string |
| + for _, b := range boxes { |
| + for i := 0; i < 2; i++ { |
| + k := dayAgo(t, "acme", "shop", b, 700+i) |
| + putKey(t, st, k) |
| + old = append(old, k) |
| + } |
| + putKey(t, st, dayAgo(t, "acme", "shop", b, 1)) |
| + } |
| + opt := PruneOptions{RetentionDays: 400, MaxDeletes: 3} |
| + first, _ := runPrune(t, st, opt) |
| + if first.Deleted != 3 { |
| + t.Fatalf("first pass deleted %d, want exactly 3: %+v", first.Deleted, first) |
| + } |
| + wantNext, _ := BoxPrefix("acme", "shop", "b2") |
| + if first.NextBox != wantNext { |
| + t.Fatalf("NextBox = %q, want %q", first.NextBox, wantNext) |
| + } |
| + remaining := 0 |
| + for _, k := range old { |
| + if _, _, err := st.Get(context.Background(), k); err == nil { |
| + remaining++ |
| + } |
| + } |
| + if remaining != 3 { |
| + t.Fatalf("remaining old keys = %d, want 3", remaining) |
| + } |
| + // Resume the next day from the saved box until the pass completes. |
| + next := first.NextBox |
| + for pass := 0; pass < 5 && next != ""; pass++ { |
| + opt.StartAt = next |
| + s, _ := runPrune(t, st, opt) |
| + if s.Deleted > 3 { |
| + t.Fatalf("pass %d deleted %d > MaxDeletes", pass, s.Deleted) |
| + } |
| + next = s.NextBox |
| + } |
| + if next != "" { |
| + t.Fatal("resume never completed") |
| + } |
| + mustNotExist(t, st, old...) |
| + if got := len(allKeys(t, st)); got != 3 { |
| + t.Fatalf("kept keys = %d, want 3", got) |
| + } |
| +} |
| + |
| +func TestPruneResumeSkipsEarlierBoxesAndApps(t *testing.T) { |
| + st := newPruneStore(t) |
| + early := dayAgo(t, "acme", "blog", "b1", 700) |
| + earlyBox := dayAgo(t, "acme", "shop", "b1", 700) |
| + late := dayAgo(t, "acme", "shop", "b2", 700) |
| + for _, k := range []string{early, earlyBox, late} { |
| + putKey(t, st, k) |
| + } |
| + start, _ := BoxPrefix("acme", "shop", "b2") |
| + stats, _ := runPrune(t, st, PruneOptions{RetentionDays: 400, StartAt: start}) |
| + mustNotExist(t, st, late) |
| + mustExist(t, st, early, earlyBox) |
| + if stats.Deleted != 1 || stats.NextBox != "" { |
| + t.Fatalf("stats = %+v", stats) |
| + } |
| +} |
| + |
| +func TestPruneCancelledBeforeStartDeletesNothing(t *testing.T) { |
| + st := newPruneStore(t) |
| + k := dayAgo(t, "acme", "shop", "b1", 700) |
| + putKey(t, st, k) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + cancel() |
| + stats, err := Prune(ctx, st, pruneNow, PruneOptions{RetentionDays: 400, Logf: func(string, ...any) {}}) |
| + if !errors.Is(err, context.Canceled) { |
| + t.Fatalf("err = %v, want context.Canceled", err) |
| + } |
| + if stats.Deleted != 0 || stats.Errors == 0 || st.pageCalls != 0 { |
| + t.Fatalf("stats = %+v pageCalls %d", stats, st.pageCalls) |
| + } |
| + mustExist(t, st, k) |
| +} |
| + |
| +func TestPruneCancelledMidRunStopsBetweenPages(t *testing.T) { |
| + st := newPruneStore(t) |
| + var old []string |
| + for i := 0; i < 6; i++ { |
| + k := dayAgo(t, "acme", "shop", "b1", 700+i) |
| + putKey(t, st, k) |
| + old = append(old, k) |
| + } |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + st.afterPage = func(n int) { |
| + if n == 1 { |
| + cancel() |
| + } |
| + } |
| + l := &pruneLog{} |
| + stats, err := Prune(ctx, st, pruneNow, PruneOptions{RetentionDays: 400, PageSize: 2, Logf: l.logf}) |
| + if !errors.Is(err, context.Canceled) { |
| + t.Fatalf("err = %v, want context.Canceled", err) |
| + } |
| + if st.pageCalls != 1 { |
| + t.Fatalf("ListPage calls after cancel = %d, want 1", st.pageCalls) |
| + } |
| + if stats.Deleted > 2 { |
| + t.Fatalf("deleted %d after cancellation, want at most the first page", stats.Deleted) |
| + } |
| + if stats.NextBox == "" { |
| + t.Fatal("NextBox must be kept so the next pass resumes") |
| + } |
| + // A later pass finishes the job. |
| + runPrune(t, st, PruneOptions{RetentionDays: 400, StartAt: stats.NextBox}) |
| + mustNotExist(t, st, old...) |
| +} |
| + |
| +func TestPruneNeverDeletesKeysOutsideTheDaysPrefix(t *testing.T) { |
| + st := newPruneStore(t) |
| + days, _ := BoxPrefix("acme", "shop", "b1") |
| + foreign := []string{ |
| + "apps/acme/shop/logs/b1/2020-01-01.json", |
| + "apps/acme/shop/analytics/b2/days/2020-01-01.json", // other box |
| + "apps/acme/shop/analytics/b1/days/x/2020-01-01.json", |
| + "apps/acme/shop/analytics/b1/2020-01-01.json", |
| + "apps/other/shop/analytics/b1/days/2020-01-01.json", |
| + "config/2020-01-01.json", |
| + days + "../2020-01-01.json", |
| + days + "2020-01-01.json/", |
| + "2020-01-01.json", |
| + "", |
| + } |
| + for _, k := range foreign { |
| + if k != "" && !strings.Contains(k, "..") && !strings.HasSuffix(k, "/") { |
| + putKey(t, st, k) |
| + } |
| + } |
| + putKey(t, st, days+"2030-01-01.json") // so the box exists |
| + st.dirs = func(prefix string) ([]string, error) { |
| + switch prefix { |
| + case "apps/": |
| + return []string{"apps/acme/"}, nil |
| + case "apps/acme/": |
| + return []string{"apps/acme/shop/"}, nil |
| + } |
| + return []string{"apps/acme/shop/analytics/b1/"}, nil |
| + } |
| + st.page = func(_ context.Context, prefix, after string, limit int) ([]string, error) { |
| + // A broken adapter ignores the prefix; keys are sorted and bounded. |
| + out := slices.Clone(foreign) |
| + slices.Sort(out) |
| + out = slices.DeleteFunc(out, func(k string) bool { return k <= after || k == "" }) |
| + return out[:min(len(out), limit)], nil |
| + } |
| + l := &pruneLog{} |
| + stats, err := Prune(context.Background(), st, pruneNow, PruneOptions{RetentionDays: 400, PageSize: 1000, Logf: l.logf}) |
| + if err != nil { |
| + t.Fatalf("Prune: %v", err) |
| + } |
| + if len(st.deletes) != 0 || stats.Deleted != 0 || stats.DeleteCalls != 0 { |
| + t.Fatalf("deleted foreign keys: %v stats %+v", st.deletes, stats) |
| + } |
| + if stats.Malformed == 0 || !l.has("malformed") { |
| + t.Fatalf("foreign keys were not reported: %+v", stats) |
| + } |
| + for _, k := range foreign { |
| + if k != "" && !strings.Contains(k, "..") && !strings.HasSuffix(k, "/") { |
| + mustExist(t, st, k) |
| + } |
| + } |
| +} |
| + |
| +func TestPruneRefusesBrokenPages(t *testing.T) { |
| + good := "apps/acme/shop/analytics/b1/days/2020-01-01.json" |
| + cases := map[string]func(prefix, after string, limit int) []string{ |
| + "unsorted": func(p, a string, l int) []string { return []string{p + "2020-01-02.json", good} }, |
| + "duplicate": func(p, a string, l int) []string { return []string{good, good} }, |
| + "not after": func(p, a string, l int) []string { return []string{p + "2019-01-01.json"}[:0:0] }, |
| + "over limit": func(p, a string, l int) []string { return []string{good, p + "2020-01-02.json", p + "2020-01-03.json"} }, |
| + "empty segment": func(p, a string, l int) []string { return []string{""} }, |
| + } |
| + delete(cases, "not after") // an empty page is legal; covered elsewhere |
| + for name, fn := range cases { |
| + t.Run(name, func(t *testing.T) { |
| + st := newPruneStore(t) |
| + putKey(t, st, good) |
| + putKey(t, st, "apps/acme/shop/analytics/b1/days/2020-01-02.json") |
| + st.page = func(_ context.Context, p, a string, l int) ([]string, error) { return fn(p, a, l), nil } |
| + stats, err := Prune(context.Background(), st, pruneNow, PruneOptions{RetentionDays: 400, PageSize: 2, Logf: func(string, ...any) {}}) |
| + if err == nil || !strings.Contains(err.Error(), "invalid page") { |
| + t.Fatalf("err = %v, want invalid page", err) |
| + } |
| + if stats.Deleted != 0 || len(st.deletes) != 0 { |
| + t.Fatalf("deleted from a broken page: %+v %v", stats, st.deletes) |
| + } |
| + mustExist(t, st, good) |
| + }) |
| + } |
| +} |
| + |
| +func TestPruneSkipsUnsafeAccountAppAndBoxSegments(t *testing.T) { |
| + st := newPruneStore(t) |
| + legit := "apps/acme/shop/analytics/b1/days/2020-01-01.json" |
| + putKey(t, st, legit) |
| + st.dirs = func(prefix string) ([]string, error) { |
| + switch prefix { |
| + case "apps/": |
| + return []string{"apps/BAD/", "apps/ab/", "apps/acme/", "apps/../", "apps/./", "apps/ac me/", "apps/acme/x/"}, nil |
| + case "apps/acme/": |
| + return []string{"apps/acme/Shop/", "apps/acme/1shop/", "apps/acme/shop/", "apps/acme/../", "apps/acme/sh_op/", "apps/acme/shop/x/"}, nil |
| + case "apps/acme/shop/analytics/": |
| + return []string{ |
| + "apps/acme/shop/analytics/b1/", "apps/acme/shop/analytics/../", "apps/acme/shop/analytics/./", |
| + "apps/acme/shop/analytics/a\\b/", "apps/acme/shop/analytics/a/b/", "apps/acme/shop/analytics//", |
| + "apps/acme/shop/analytics/", "apps/acme/shop/other/b1/", |
| + }, nil |
| + } |
| + return nil, nil // unsafe accounts/apps must not even be listed |
| + } |
| + var listed []string |
| + st.page = func(ctx context.Context, prefix, after string, limit int) ([]string, error) { |
| + listed = append(listed, prefix) |
| + return st.inner.ListPage(ctx, prefix, after, limit) |
| + } |
| + stats, _ := runPrune(t, st, PruneOptions{RetentionDays: 400}) |
| + if want := []string{"apps/acme/shop/analytics/b1/days/"}; !slices.Equal(listed, want) { |
| + t.Fatalf("ListPage prefixes = %v, want %v", listed, want) |
| + } |
| + mustNotExist(t, st, legit) |
| + if stats.Boxes != 1 || stats.Apps != 1 || stats.Malformed == 0 { |
| + t.Fatalf("stats = %+v", stats) |
| + } |
| + for _, k := range st.deletes { |
| + if k != legit { |
| + t.Fatalf("deleted %q", k) |
| + } |
| + } |
| +} |
| + |
| +func TestPruneBatchPartialFailureCountsSuccesses(t *testing.T) { |
| + b := &batchStore{pruneStore: newPruneStore(t), failing: map[string]bool{}} |
| + var old []string |
| + for i := 0; i < 4; i++ { |
| + k := dayAgo(t, "acme", "shop", "b1", 700+i) |
| + putKey(t, b, k) |
| + old = append(old, k) |
| + } |
| + b.failing[old[2]] = true |
| + l := &pruneLog{} |
| + stats, err := Prune(context.Background(), b, pruneNow, PruneOptions{RetentionDays: 400, Logf: l.logf}) |
| + if err == nil || release.FailedKeys(err)[old[2]] == nil { |
| + t.Fatalf("err = %v, want the per-key failure", err) |
| + } |
| + if stats.Deleted != 3 || stats.Errors != 1 || stats.DeleteCalls != 1 { |
| + t.Fatalf("stats = %+v", stats) |
| + } |
| + mustNotExist(t, b, old[0], old[1], old[3]) |
| + mustExist(t, b, old[2]) |
| + // The failed key is retried on the next pass. |
| + b.failing = map[string]bool{} |
| + stats2, err := Prune(context.Background(), b, pruneNow, PruneOptions{RetentionDays: 400, Logf: l.logf}) |
| + if err != nil || stats2.Deleted != 1 { |
| + t.Fatalf("retry: %v %+v", err, stats2) |
| + } |
| + mustNotExist(t, b, old[2]) |
| +} |
| + |
| +func TestPruneBatchWholeCallFailureCountsNothing(t *testing.T) { |
| + st := newPruneStore(t) |
| + k := dayAgo(t, "acme", "shop", "b1", 700) |
| + putKey(t, st, k) |
| + w := &wholeFail{pruneStore: st} |
| + stats, err := Prune(context.Background(), w, pruneNow, PruneOptions{RetentionDays: 400, Logf: func(string, ...any) {}}) |
| + if err == nil || stats.Deleted != 0 || stats.Errors != 1 { |
| + t.Fatalf("err %v stats %+v", err, stats) |
| + } |
| + mustExist(t, st, k) |
| +} |
| + |
| +type wholeFail struct{ *pruneStore } |
| + |
| +func (wholeFail) DeleteKeys(context.Context, []string) error { return errors.New("boom") } |
| + |
| +func TestPruneListErrorIsCountedAndOtherBoxesContinue(t *testing.T) { |
| + st := newPruneStore(t) |
| + b1 := dayAgo(t, "acme", "shop", "b1", 700) |
| + b2 := dayAgo(t, "acme", "shop", "b2", 700) |
| + putKey(t, st, b1) |
| + putKey(t, st, b2) |
| + bad, _ := BoxPrefix("acme", "shop", "b1") |
| + st.page = func(ctx context.Context, prefix, after string, limit int) ([]string, error) { |
| + if prefix == bad { |
| + return nil, errors.New("list failed") |
| + } |
| + return st.inner.ListPage(ctx, prefix, after, limit) |
| + } |
| + stats, err := Prune(context.Background(), st, pruneNow, PruneOptions{RetentionDays: 400, Logf: func(string, ...any) {}}) |
| + if err == nil || stats.Errors != 1 || stats.Deleted != 1 { |
| + t.Fatalf("err %v stats %+v", err, stats) |
| + } |
| + mustExist(t, st, b1) |
| + mustNotExist(t, st, b2) |
| +} |
| + |
| +func TestPruneDiscoveryFailurePreservesResume(t *testing.T) { |
| + start, _ := BoxPrefix("bab", "shop", "box") |
| + for _, prefix := range []string{"apps/", "apps/bab/", "apps/bab/shop/analytics/"} { |
| + t.Run(prefix, func(t *testing.T) { |
| + st := newPruneStore(t) |
| + putKey(t, st, dayAgo(t, "bab", "shop", "box", 401)) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + st.dirs = func(p string) ([]string, error) { |
| + if p == prefix { |
| + cancel() |
| + return nil, ctx.Err() |
| + } |
| + return st.inner.ListDirs(ctx, p) |
| + } |
| + stats, err := Prune(ctx, st, pruneNow, PruneOptions{RetentionDays: 400, StartAt: start, Logf: func(string, ...any) {}}) |
| + if !errors.Is(err, context.Canceled) || stats.NextBox != start || stats.Errors != 1 || stats.Deleted != 0 { |
| + t.Fatalf("stats=%+v err=%v", stats, err) |
| + } |
| + }) |
| + } |
| + st := newPruneStore(t) |
| + st.dirs = func(string) ([]string, error) { return nil, errors.New("transient LIST error") } |
| + stats, err := Prune(context.Background(), st, pruneNow, PruneOptions{RetentionDays: 400, StartAt: start, Logf: func(string, ...any) {}}) |
| + if err == nil || stats.NextBox != start { |
| + t.Fatalf("lost resume after root LIST failure: %+v %v", stats, err) |
| + } |
| +} |
| + |
| +func TestPruneDiscoveryTimeoutStopsOnceAndResumesNextApp(t *testing.T) { |
| + st := newPruneStore(t) |
| + for _, app := range []string{"aaa", "bbb", "ccc", "ddd"} { |
| + putKey(t, st, dayAgo(t, "bab", app, "box", 401)) |
| + } |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + stopped := "apps/bab/bbb/analytics/" |
| + st.dirs = func(p string) ([]string, error) { |
| + if p == stopped { |
| + cancel() |
| + return nil, ctx.Err() |
| + } |
| + if p > stopped { |
| + t.Errorf("continued discovery after timeout: %s", p) |
| + } |
| + return st.inner.ListDirs(ctx, p) |
| + } |
| + stats, err := Prune(ctx, st, pruneNow, PruneOptions{RetentionDays: 400, Logf: func(string, ...any) {}}) |
| + if !errors.Is(err, context.Canceled) || stats.Errors != 1 || stats.NextBox != stopped || stats.Deleted != 1 { |
| + t.Fatalf("%+v %v", stats, err) |
| + } |
| + st.dirs = nil |
| + next, _ := runPrune(t, st, PruneOptions{RetentionDays: 400, StartAt: stats.NextBox}) |
| + if next.Deleted != 3 || next.NextBox != "" { |
| + t.Fatalf("resume: %+v", next) |
| + } |
| +} |
| + |
| +func TestPruneSmallFirstPageReachesMatureBoxesWithinBudget(t *testing.T) { |
| + st := newPruneStore(t) |
| + st.dirs = func(p string) ([]string, error) { |
| + switch p { |
| + case "apps/": |
| + return []string{"apps/bab/"}, nil |
| + case "apps/bab/": |
| + return []string{"apps/bab/shop/"}, nil |
| + case "apps/bab/shop/analytics/": |
| + var dirs []string |
| + for i := 0; i < 12; i++ { |
| + dirs = append(dirs, fmt.Sprintf("%sbox-%02d/", p, i)) |
| + } |
| + return dirs, nil |
| + } |
| + t.Fatalf("unexpected directory: %s", p) |
| + return nil, nil |
| + } |
| + st.page = func(ctx context.Context, p, after string, limit int) ([]string, error) { |
| + if after != "" { |
| + t.Fatalf("listed beyond cutoff: %q", after) |
| + } |
| + var keys []string |
| + for age := 401; age >= 0 && len(keys) < limit; age-- { |
| + keys = append(keys, p+pruneNow.AddDate(0, 0, -age).Format("2006-01-02")+".json") |
| + } |
| + return keys, nil |
| + } |
| + stats, _ := runPrune(t, st, PruneOptions{RetentionDays: 400, MaxKeys: 100}) |
| + if stats.Boxes != 12 || stats.Deleted != 12 || stats.Listed > 100 || stats.NextBox != "" { |
| + t.Fatalf("mature boxes: %+v", stats) |
| + } |
| +} |
| + |
| +func TestPruneLargeRetentionKeepsEveryValidDate(t *testing.T) { |
| + st := newPruneStore(t) |
| + keys := []string{ |
| + "apps/acme/shop/analytics/b1/days/0000-01-01.json", |
| + dayAgo(t, "acme", "shop", "b1", 401), |
| + dayAgo(t, "acme", "shop", "b1", 0), |
| + } |
| + for _, key := range keys { |
| + putKey(t, st, key) |
| + } |
| + stats, _ := runPrune(t, st, PruneOptions{RetentionDays: int(^uint(0) >> 1)}) |
| + if stats.Deleted != 0 || stats.DeleteCalls != 0 || stats.Errors != 0 { |
| + t.Fatalf("large retention expired valid dates: %+v", stats) |
| + } |
| + mustExist(t, st, keys...) |
| +} |
diff --git a/internal/analytics/prune_versions_test.go b/internal/analytics/prune_versions_test.go| new file mode 100644 |
| index 000000000..d4fded7f2 |
| --- /dev/null |
| +++ b/internal/analytics/prune_versions_test.go |
| @@ -0,0 +1,346 @@ |
| +package analytics |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "slices" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// The original order remains available after deletion, just as an opaque S3 |
| +// continuation can point to a version that the preceding page deleted. |
| +type versionPruneStore struct { |
| + *pruneStore |
| + versions []release.ObjectVersion |
| + removed map[release.ObjectVersion]bool |
| + markers [][2]string |
| + deleted []release.ObjectVersion |
| + listDenied, deleteDenied, dirsDenied bool |
| + pageHook func([]release.ObjectVersion) []release.ObjectVersion |
| + deleteHook func([]release.ObjectVersion) error |
| +} |
| + |
| +func newVersionPruneStore(t *testing.T) *versionPruneStore { |
| + return &versionPruneStore{pruneStore: newPruneStore(t), removed: map[release.ObjectVersion]bool{}} |
| +} |
| + |
| +func (s *versionPruneStore) add(key string, n int, marker bool) { |
| + for i := 0; i < n; i++ { |
| + s.versions = append(s.versions, release.ObjectVersion{Key: key, VersionID: fmt.Sprintf("v%d", i), IsDeleteMarker: marker && i == 0}) |
| + } |
| + slices.SortStableFunc(s.versions, func(a, b release.ObjectVersion) int { return strings.Compare(a.Key, b.Key) }) |
| +} |
| + |
| +func (s *versionPruneStore) ListVersionDirsWithCount(_ context.Context, prefix string) ([]string, int, error) { |
| + if s.dirsDenied { |
| + return nil, 1, release.ErrVersionAccessDenied |
| + } |
| + seen := map[string]bool{} |
| + for _, v := range s.versions { |
| + if s.removed[v] { |
| + continue |
| + } |
| + rest, ok := strings.CutPrefix(v.Key, prefix) |
| + if !ok { |
| + continue |
| + } |
| + child, _, ok := strings.Cut(rest, "/") |
| + if ok { |
| + seen[prefix+child+"/"] = true |
| + } |
| + } |
| + var dirs []string |
| + for d := range seen { |
| + dirs = append(dirs, d) |
| + } |
| + slices.Sort(dirs) |
| + return dirs, 1, nil |
| +} |
| + |
| +func (s *versionPruneStore) ListVersionsPage(_ context.Context, prefix, keyMarker, versionMarker string, limit int) ([]release.ObjectVersion, string, string, error) { |
| + s.markers = append(s.markers, [2]string{keyMarker, versionMarker}) |
| + if s.listDenied { |
| + return nil, "", "", release.ErrVersionAccessDenied |
| + } |
| + start := 0 |
| + if versionMarker != "" { |
| + found := false |
| + for i, v := range s.versions { |
| + if v.Key == keyMarker && v.VersionID == versionMarker { |
| + start = i + 1 |
| + found = true |
| + break |
| + } |
| + } |
| + if !found { |
| + return nil, "", "", fmt.Errorf("unknown continuation %q %q", keyMarker, versionMarker) |
| + } |
| + } |
| + var available []release.ObjectVersion |
| + for _, v := range s.versions[start:] { |
| + if strings.HasPrefix(v.Key, prefix) && !s.removed[v] { |
| + available = append(available, v) |
| + } |
| + } |
| + page := available[:min(limit, len(available))] |
| + nextKey, nextVersion := "", "" |
| + if len(available) > limit { |
| + last := page[len(page)-1] |
| + nextKey, nextVersion = last.Key, last.VersionID |
| + } |
| + if s.pageHook != nil { |
| + page = s.pageHook(page) |
| + } |
| + return page, nextKey, nextVersion, nil |
| +} |
| + |
| +func (s *versionPruneStore) DeleteVersions(_ context.Context, versions []release.ObjectVersion) error { |
| + if s.deleteDenied { |
| + return release.ErrVersionAccessDenied |
| + } |
| + if s.deleteHook != nil { |
| + return s.deleteHook(versions) |
| + } |
| + for _, v := range versions { |
| + s.deleted = append(s.deleted, v) |
| + s.removed[v] = true |
| + } |
| + return nil |
| +} |
| + |
| +func TestPruneVersionsBoundariesForConfiguredRetention(t *testing.T) { |
| + for _, retention := range []int{30, 400} { |
| + t.Run(fmt.Sprintf("%d days", retention), func(t *testing.T) { |
| + s := newVersionPruneStore(t) |
| + for _, age := range []int{retention - 1, retention, retention + 1} { |
| + s.add(dayAgo(t, "acme", "shop", "b1", age), 2, true) |
| + } |
| + stats, _ := runPrune(t, s, PruneOptions{RetentionDays: retention, PageSize: 2}) |
| + if stats.VersionsDeleted != 2 || stats.KeysDeleted != 1 || stats.Deleted != 2 { |
| + t.Fatalf("stats=%+v", stats) |
| + } |
| + for _, age := range []int{retention - 1, retention} { |
| + key := dayAgo(t, "acme", "shop", "b1", age) |
| + for _, v := range s.versions { |
| + if v.Key == key && s.removed[v] { |
| + t.Fatalf("retained age %d version was deleted: %+v", age, v) |
| + } |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPruneVersionsBoundariesAndHiddenTrees(t *testing.T) { |
| + s := newVersionPruneStore(t) |
| + for _, age := range []int{399, 400, 401} { |
| + s.add(dayAgo(t, "acme", "shop", "b1", age), 3, true) |
| + } |
| + hidden := dayAgo(t, "hidden", "gone", "b2", 401) |
| + s.add(hidden, 4, true) // no current keys anywhere in this account/app/box |
| + protected := []string{"apps/acme/shop/logs/b1/2025-01-01.json", "apps/acme/shop/analytics/b1/2025-01-01.json", "apps/acme/shop/analytics/b1/days/2025-00-01.json", "apps/acme/shop/analytics/b1/days/2025-01-01.json/nested"} |
| + for _, k := range protected { |
| + s.add(k, 2, true) |
| + } |
| + stats, logs := runPrune(t, s, PruneOptions{RetentionDays: 400, PageSize: 2}) |
| + if stats.VersionsDeleted != 7 || stats.KeysDeleted != 2 || stats.Deleted != 7 || stats.Apps != 2 || stats.Boxes != 2 || s.pageCalls != 0 { |
| + t.Fatalf("stats=%+v current pages=%d", stats, s.pageCalls) |
| + } |
| + if stats.Malformed != 4 || !logs.has("skipped malformed") { |
| + t.Fatalf("malformed=%d logs=%v", stats.Malformed, logs.lines) |
| + } |
| + for _, v := range s.deleted { |
| + expired, valid := pruneEligible(strings.TrimSuffix(v.Key, v.Key[strings.LastIndex(v.Key, "/")+1:]), v.Key, RetentionCutoff(pruneNow, 400)) |
| + if !valid || !expired { |
| + t.Fatalf("deleted ineligible %+v", v) |
| + } |
| + } |
| + for _, v := range s.versions { |
| + if slices.Contains(protected, v.Key) && s.removed[v] { |
| + t.Fatalf("deleted protected %+v", v) |
| + } |
| + } |
| + if !slices.ContainsFunc(s.markers, func(m [2]string) bool { return m[0] == hidden && m[1] != "" }) { |
| + t.Fatalf("never resumed inside hidden key: %v", s.markers) |
| + } |
| + again, _ := runPrune(t, s, PruneOptions{RetentionDays: 400, PageSize: 2}) |
| + if again.Deleted != 0 { |
| + t.Fatalf("second pass=%+v", again) |
| + } |
| +} |
| + |
| +func TestPruneVersionsDryRunAndCaps(t *testing.T) { |
| + for _, dry := range []bool{false, true} { |
| + t.Run(fmt.Sprint(dry), func(t *testing.T) { |
| + s := newVersionPruneStore(t) |
| + key := dayAgo(t, "acme", "shop", "b1", 401) |
| + s.add(key, 9, true) |
| + stats, _ := runPrune(t, s, PruneOptions{RetentionDays: 400, DryRun: dry, PageSize: 2, MaxDeletes: 5}) |
| + if stats.NextBox != "apps/acme/shop/analytics/b1/days/" { |
| + t.Fatalf("cursor=%q", stats.NextBox) |
| + } |
| + if dry { |
| + if stats.WouldDelete != 5 || stats.VersionsWouldDelete != 5 || stats.KeysWouldDelete != 1 || len(s.deleted) != 0 { |
| + t.Fatalf("dry=%+v", stats) |
| + } |
| + } else { |
| + if stats.VersionsDeleted != 5 || stats.KeysDeleted != 1 { |
| + t.Fatalf("cap=%+v", stats) |
| + } |
| + next, _ := runPrune(t, s, PruneOptions{RetentionDays: 400, StartAt: stats.NextBox, PageSize: 2}) |
| + if next.VersionsDeleted != 4 { |
| + t.Fatalf("resume=%+v", next) |
| + } |
| + } |
| + }) |
| + } |
| + s := newVersionPruneStore(t) |
| + s.add(dayAgo(t, "acme", "shop", "b1", 401), 10, true) |
| + stats, _ := runPrune(t, s, PruneOptions{RetentionDays: 400, PageSize: 2, MaxKeys: 3}) |
| + if stats.Listed != 3 || stats.VersionsDeleted != 3 || stats.NextBox == "" { |
| + t.Fatalf("listing cap=%+v", stats) |
| + } |
| +} |
| + |
| +func TestPruneVersionsAccessDeniedFallsBackOnce(t *testing.T) { |
| + for _, where := range []string{"discovery", "listing", "deletion", "partial deletion"} { |
| + t.Run(where, func(t *testing.T) { |
| + s := newVersionPruneStore(t) |
| + for _, box := range []string{"b1", "b2"} { |
| + old := dayAgo(t, "acme", "shop", box, 401) |
| + s.add(old, 3, true) |
| + putKey(t, s, old) |
| + keep := dayAgo(t, "acme", "shop", box, 400) |
| + s.add(keep, 2, false) |
| + putKey(t, s, keep) |
| + } |
| + adjacent := "apps/acme/shop/analytics/b1/2025-01-01.json" |
| + s.add(adjacent, 2, false) |
| + putKey(t, s, adjacent) |
| + switch where { |
| + case "discovery": |
| + s.dirsDenied = true |
| + case "listing": |
| + s.listDenied = true |
| + case "deletion": |
| + s.deleteDenied = true |
| + case "partial deletion": |
| + s.deleteHook = func(vs []release.ObjectVersion) error { |
| + failed := map[release.ObjectVersion]error{} |
| + for i, v := range vs { |
| + if i == 0 { |
| + s.removed[v] = true |
| + s.deleted = append(s.deleted, v) |
| + } else { |
| + failed[v] = release.ErrVersionAccessDenied |
| + } |
| + } |
| + return &release.VersionDeleteError{Failed: failed} |
| + } |
| + } |
| + logs := &pruneLog{} |
| + stats, err := Prune(context.Background(), s, pruneNow, PruneOptions{RetentionDays: 400, PageSize: 8, Logf: logs.logf}) |
| + if !errors.Is(err, release.ErrVersionAccessDenied) || stats.Errors != 1 || len(s.deletes) != 2 || stats.KeysDeleted != 2 { |
| + t.Fatalf("stats=%+v err=%v deletes=%v", stats, err, s.deletes) |
| + } |
| + warnings := 0 |
| + for _, l := range logs.lines { |
| + if strings.Contains(l, "noncurrent versions remain") { |
| + warnings++ |
| + } |
| + } |
| + perm := "s3:ListBucketVersions" |
| + if strings.Contains(where, "deletion") { |
| + perm = "s3:DeleteObjectVersion" |
| + } |
| + if warnings != 1 || !logs.has(perm) { |
| + t.Fatalf("logs=%v", logs.lines) |
| + } |
| + if where == "partial deletion" && stats.VersionsDeleted != 1 { |
| + t.Fatalf("partial=%+v", stats) |
| + } |
| + mustExist(t, s, adjacent, dayAgo(t, "acme", "shop", "b1", 400), dayAgo(t, "acme", "shop", "b2", 400)) |
| + }) |
| + } |
| +} |
| + |
| +func TestPruneVersionsRejectBrokenPagesAndForeignKeys(t *testing.T) { |
| + for _, kind := range []string{"foreign", "duplicate", "empty version", "unordered"} { |
| + t.Run(kind, func(t *testing.T) { |
| + s := newVersionPruneStore(t) |
| + key := dayAgo(t, "acme", "shop", "b1", 401) |
| + s.add(key, 2, false) |
| + s.pageHook = func(vs []release.ObjectVersion) []release.ObjectVersion { |
| + out := slices.Clone(vs) |
| + switch kind { |
| + case "foreign": |
| + for i := range out { |
| + out[i].Key = "apps/acme/shop/logs/b1/2025-01-01.json" |
| + } |
| + case "duplicate": |
| + out[1] = out[0] |
| + case "empty version": |
| + out[0].VersionID = "" |
| + case "unordered": |
| + out[0].Key = dayAgo(t, "acme", "shop", "b1", 399) |
| + } |
| + return out |
| + } |
| + stats, err := Prune(context.Background(), s, pruneNow, PruneOptions{RetentionDays: 400, Logf: func(string, ...any) {}}) |
| + if stats.Deleted != 0 || len(s.deleted) != 0 { |
| + t.Fatalf("unsafe delete: %+v", stats) |
| + } |
| + if kind == "foreign" { |
| + if stats.Malformed != 2 { |
| + t.Fatalf("foreign=%+v err=%v", stats, err) |
| + } |
| + } else if err == nil { |
| + t.Fatal("invalid page accepted") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPruneVersionsCancellationKeepsCursor(t *testing.T) { |
| + s := newVersionPruneStore(t) |
| + s.add(dayAgo(t, "acme", "shop", "b1", 401), 6, true) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + s.deleteHook = func(vs []release.ObjectVersion) error { |
| + for _, v := range vs { |
| + s.removed[v] = true |
| + } |
| + cancel() |
| + return nil |
| + } |
| + stats, err := Prune(ctx, s, pruneNow, PruneOptions{RetentionDays: 400, PageSize: 2, Logf: func(string, ...any) {}}) |
| + if !errors.Is(err, context.Canceled) || stats.VersionsDeleted != 2 || stats.NextBox != "apps/acme/shop/analytics/b1/days/" { |
| + t.Fatalf("stats=%+v err=%v", stats, err) |
| + } |
| +} |
| + |
| +func TestPruneVersionsStopsAtRetainedDate(t *testing.T) { |
| + s := newVersionPruneStore(t) |
| + s.add(dayAgo(t, "acme", "shop", "b1", 401), 3, true) |
| + for age := 400; age >= 0; age-- { |
| + s.add(dayAgo(t, "acme", "shop", "b1", age), 3, true) |
| + } |
| + stats, _ := runPrune(t, s, PruneOptions{RetentionDays: 400, PageSize: 2}) |
| + if stats.VersionsListed != 4 || stats.VersionsDeleted != 3 || len(s.markers) != 2 { |
| + t.Fatalf("early stop=%+v pages=%d", stats, len(s.markers)) |
| + } |
| +} |
| + |
| +func TestPruneVersionsFailureDoesNotClaimSuccess(t *testing.T) { |
| + s := newVersionPruneStore(t) |
| + s.add(dayAgo(t, "acme", "shop", "b1", 401), 3, true) |
| + s.deleteHook = func(vs []release.ObjectVersion) error { return errors.New("backend unavailable") } |
| + stats, err := Prune(context.Background(), s, pruneNow, PruneOptions{RetentionDays: 400, Logf: func(string, ...any) {}}) |
| + if err == nil || stats.Errors != 1 || stats.VersionsDeleted != 0 || stats.KeysDeleted != 0 || s.pageCalls != 0 { |
| + t.Fatalf("stats=%+v err=%v", stats, err) |
| + } |
| +} |
diff --git a/internal/console/analyticsprune.go b/internal/console/analyticsprune.go| new file mode 100644 |
| index 000000000..19a2bb606 |
| --- /dev/null |
| +++ b/internal/console/analyticsprune.go |
| @@ -0,0 +1,112 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "strconv" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/analytics" |
| +) |
| + |
| +const ( |
| + analyticsPruneTimeout = 10 * time.Minute |
| + // A busy app-box-day has 24*60/5 = 288 versions. Two million covers |
| + // about 6,944 such days, or 2,000 full DeleteObjects batches of 1,000. |
| + // Allow ten listed entries per deletion for retained or malformed keys; |
| + // these are safety bounds, with the ten-minute deadline limiting work. |
| + analyticsPruneMaxDeletes = 2_000_000 |
| + analyticsPruneMaxKeys = 10 * analyticsPruneMaxDeletes |
| +) |
| + |
| +func parseAnalyticsRetention(daysRaw, dryRunRaw string) (days int, dryRun bool, err error) { |
| + if daysRaw != "" { |
| + days, err = strconv.Atoi(daysRaw) |
| + if err != nil || days <= 0 { |
| + return 0, false, fmt.Errorf("CARLOS_ANALYTICS_RETENTION_DAYS must be empty or a positive integer") |
| + } |
| + } |
| + switch dryRunRaw { |
| + case "", "0", "false": |
| + case "1", "true": |
| + dryRun = true |
| + default: |
| + return 0, false, fmt.Errorf("CARLOS_ANALYTICS_RETENTION_DRY_RUN must be empty, 1, 0, true or false") |
| + } |
| + return days, dryRun, nil |
| +} |
| + |
| +// analyticsPrunePass rides the existing hourly economics worker. Only this |
| +// local SQL admission runs on the hourly tick: object listings run at most |
| +// once in 24 hours, including after a crash or console restart. Recording the |
| +// attempt before I/O deliberately defers a failed or interrupted pass until |
| +// tomorrow instead of issuing another bucket sweep on each boot. |
| +func (s *Server) analyticsPrunePass(ctx context.Context, now time.Time) error { |
| + return s.analyticsPrunePassWithLimits(ctx, now, analyticsPruneMaxDeletes, analyticsPruneMaxKeys) |
| +} |
| + |
| +func (s *Server) analyticsPrunePassWithLimits(ctx context.Context, now time.Time, maxDeletes, maxKeys int) error { |
| + days, dryRun, err := parseAnalyticsRetention(s.cfg.AnalyticsRetentionDays, s.cfg.AnalyticsRetentionDryRun) |
| + if err != nil { |
| + return err |
| + } |
| + if days == 0 || s.cfg.Releases == nil { |
| + return nil |
| + } |
| + if s.cfg.HostClaim { |
| + return fmt.Errorf("analytics prune: unavailable on a host-claim console") |
| + } |
| + ctx, cancel := context.WithTimeout(ctx, analyticsPruneTimeout) |
| + defer cancel() |
| + var cursor string |
| + // One conditional UPDATE is the admission even if two callers arrive |
| + // together. The singleton exists from migration; no row means no run. |
| + err = s.store.db.QueryRowContext(ctx, `UPDATE analytics_prune_state SET last_started = ? |
| + WHERE id = 1 AND (last_started IS NULL OR last_started <= ?) |
| + RETURNING next_box`, now.Unix(), now.Add(-24*time.Hour).Unix()).Scan(&cursor) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return nil |
| + } |
| + if err != nil { |
| + return fmt.Errorf("analytics prune: daily admission: %w", err) |
| + } |
| + if !dryRun { |
| + s.pruneAnalyticsCaches(now) |
| + } |
| + stats, pruneErr := analytics.Prune(ctx, s.cfg.Releases, now, analytics.PruneOptions{ |
| + RetentionDays: days, DryRun: dryRun, PageSize: 1000, MaxDeletes: maxDeletes, MaxKeys: maxKeys, StartAt: cursor, |
| + }) |
| + warning := "" |
| + if stats.NextBox != "" || ctx.Err() != nil || errors.Is(pruneErr, context.DeadlineExceeded) { |
| + warning = "warning: backlog remains: " |
| + // Returning this error also fails the economics job through its |
| + // existing jobFailed call, even when the store itself succeeded. |
| + pruneErr = errors.Join(pruneErr, fmt.Errorf("analytics prune: backlog remains: entries_listed=%d deleted=%d would_delete=%d next_box=%q", stats.Listed, stats.Deleted, stats.WouldDelete, stats.NextBox)) |
| + } |
| + log.Printf("console: analytics prune: %sretention_days=%d dry_run=%t apps=%d boxes=%d entries_listed=%d deleted=%d would_delete=%d keys_listed=%d versions_listed=%d keys_deleted=%d versions_deleted=%d keys_would_delete=%d versions_would_delete=%d skipped_malformed=%d errors=%d list_requests=%d delete_requests=%d next_box=%q", |
| + warning, days, dryRun, stats.Apps, stats.Boxes, stats.Listed, stats.Deleted, stats.WouldDelete, stats.KeysListed, stats.VersionsListed, stats.KeysDeleted, stats.VersionsDeleted, stats.KeysWouldDelete, stats.VersionsWouldDelete, stats.Malformed, stats.Errors, stats.ListCalls, stats.DeleteCalls, stats.NextBox) |
| + // A timeout must not prevent saving progress. This final local write has |
| + // its own small deadline, independent of the bucket work's deadline. |
| + saveCtx, saveCancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) |
| + defer saveCancel() |
| + if _, err := s.store.db.ExecContext(saveCtx, `UPDATE analytics_prune_state SET next_box = ? WHERE id = 1 AND last_started = ?`, stats.NextBox, now.Unix()); err != nil { |
| + return fmt.Errorf("analytics prune: save progress: %w (pass: %v)", err, pruneErr) |
| + } |
| + return pruneErr |
| +} |
| + |
| +// Cache TTLs control reads; an idle entry can otherwise remain allocated long |
| +// after its last view. The daily deletion sweep also drops those old summaries. |
| +func (s *Server) pruneAnalyticsCaches(now time.Time) { |
| + s.usageDays.prune(now) |
| + s.trafficMemo.mu.Lock() |
| + defer s.trafficMemo.mu.Unlock() |
| + for key, entry := range s.trafficMemo.m { |
| + if now.Sub(entry.at) >= analyticsMemoTTL || now.Before(entry.at) { |
| + delete(s.trafficMemo.m, key) |
| + } |
| + } |
| +} |
diff --git a/internal/console/analyticsprune_test.go b/internal/console/analyticsprune_test.go| new file mode 100644 |
| index 000000000..5fa003d04 |
| --- /dev/null |
| +++ b/internal/console/analyticsprune_test.go |
| @@ -0,0 +1,268 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/analytics" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +func TestAnalyticsPruneDailyAndRestart(t *testing.T) { |
| + ctx := context.Background() |
| + now := time.Date(2026, 11, 11, 18, 0, 0, 0, time.UTC) |
| + path := filepath.Join(t.TempDir(), "console.db") |
| + db, err := Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + st := release.NewDirStore(t.TempDir()) |
| + key, _ := analytics.DayKey("bab", "shop", "box-1", now.AddDate(0, 0, -401).Format("2006-01-02")) |
| + put := func() { |
| + t.Helper() |
| + if _, err := st.Put(ctx, key, []byte("{}"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + exists := func(want bool) { |
| + t.Helper() |
| + _, _, err := st.Get(ctx, key) |
| + if (err == nil) != want || err != nil && !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("exists=%v: %v", want, err) |
| + } |
| + } |
| + srv := &Server{store: db, cfg: Config{Releases: st, AnalyticsRetentionDays: "400"}} |
| + put() |
| + if err := srv.analyticsPrunePass(ctx, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + exists(false) |
| + put() |
| + if err := srv.analyticsPrunePass(ctx, now.Add(23*time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + exists(true) |
| + if err := db.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + db, err = Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer db.Close() |
| + srv.store = db |
| + if err := srv.analyticsPrunePass(ctx, now.Add(23*time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + exists(true) |
| + if err := srv.analyticsPrunePass(ctx, now.Add(24*time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + exists(false) |
| +} |
| + |
| +func TestAnalyticsPruneSettings(t *testing.T) { |
| + for _, tc := range []struct { |
| + name, days, dry string |
| + admitted, deleted bool |
| + }{ |
| + {"unset", "", "", false, false}, |
| + {"unset-dry", "", "1", false, false}, |
| + {"dry-one", "400", "1", true, false}, |
| + {"dry-true", "400", "true", true, false}, |
| + {"delete-default", "400", "", true, true}, |
| + {"delete-zero", "400", "0", true, true}, |
| + {"delete-false", "400", "false", true, true}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + ctx := context.Background() |
| + now := time.Date(2026, 11, 11, 0, 0, 0, 0, time.UTC) |
| + st := release.NewDirStore(t.TempDir()) |
| + key, _ := analytics.DayKey("bab", "shop", "box-1", "2020-01-01") |
| + if _, err := st.Put(ctx, key, []byte("{}"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + db := openTestStore(t) |
| + srv, err := NewServer(Config{Releases: st, AnalyticsRetentionDays: tc.days, AnalyticsRetentionDryRun: tc.dry}, db) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := srv.analyticsPrunePass(ctx, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, _, err = st.Get(ctx, key) |
| + if tc.deleted { |
| + if !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("expected deletion: %v", err) |
| + } |
| + } else if err != nil { |
| + t.Fatal(err) |
| + } |
| + var stamp *int64 |
| + if err := db.db.QueryRowContext(ctx, `SELECT last_started FROM analytics_prune_state WHERE id=1`).Scan(&stamp); err != nil { |
| + t.Fatal(err) |
| + } |
| + if (stamp != nil) != tc.admitted { |
| + t.Fatalf("stamp=%v, admitted=%v", stamp, tc.admitted) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestAnalyticsPruneInvalidSettingsRefuseStartup(t *testing.T) { |
| + for _, days := range []string{"0", "-1", "-400", "30.5", "on", "1e2", " ", " 30", "30\n", "9999999999999999999999999999999"} { |
| + t.Run("days/"+days, func(t *testing.T) { |
| + srv, err := NewServer(Config{AnalyticsRetentionDays: days}, nil) |
| + if err == nil || srv != nil || !strings.Contains(err.Error(), "CARLOS_ANALYTICS_RETENTION_DAYS") { |
| + t.Fatalf("invalid days: server=%v err=%v", srv, err) |
| + } |
| + }) |
| + } |
| + for _, days := range []string{"", "30"} { |
| + for _, dry := range []string{"2", "-1", "yes", "TRUE", "False", "t", "f", "on", " ", "1 "} { |
| + t.Run("dry/"+days+"/"+dry, func(t *testing.T) { |
| + srv, err := NewServer(Config{AnalyticsRetentionDays: days, AnalyticsRetentionDryRun: dry}, nil) |
| + if err == nil || srv != nil || !strings.Contains(err.Error(), "CARLOS_ANALYTICS_RETENTION_DRY_RUN") { |
| + t.Fatalf("invalid dry-run: server=%v err=%v", srv, err) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +func TestAnalyticsPruneUnsetMakesNoStoreCalls(t *testing.T) { |
| + for _, dry := range []string{"", "0", "1", "true", "false"} { |
| + t.Run(dry, func(t *testing.T) { |
| + // Any bucket method panics through the nil embedded Store. No SQL |
| + // store is supplied either: unset must return before admission. |
| + st := struct{ release.Store }{} |
| + srv := &Server{cfg: Config{Releases: st, AnalyticsRetentionDryRun: dry}} |
| + if err := srv.analyticsPrunePass(context.Background(), time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestAnalyticsPruneConfiguredBoundary(t *testing.T) { |
| + for _, days := range []int{30, 400} { |
| + t.Run(strconv.Itoa(days), func(t *testing.T) { |
| + now := time.Date(2026, 11, 11, 18, 0, 0, 0, time.UTC) |
| + st := release.NewDirStore(t.TempDir()) |
| + keys := make(map[int]string) |
| + for _, age := range []int{days - 1, days, days + 1} { |
| + key, err := analytics.DayKey("bab", "shop", "box-1", now.AddDate(0, 0, -age).Format("2006-01-02")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + keys[age] = key |
| + if _, err := st.Put(t.Context(), key, []byte("{}"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + srv, err := NewServer(Config{Releases: st, AnalyticsRetentionDays: strconv.Itoa(days)}, openTestStore(t)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := srv.analyticsPrunePass(t.Context(), now); err != nil { |
| + t.Fatal(err) |
| + } |
| + for age, key := range keys { |
| + _, _, err := st.Get(t.Context(), key) |
| + if age > days && !errors.Is(err, os.ErrNotExist) || age <= days && err != nil { |
| + t.Errorf("age %d, retention %d: %v", age, days, err) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestAnalyticsPruneAcceptsLargeRetention(t *testing.T) { |
| + raw := strconv.Itoa(int(^uint(0) >> 1)) |
| + if _, err := NewServer(Config{AnalyticsRetentionDays: raw}, openTestStore(t)); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// The admission is persisted before I/O even when the store fails. Concurrent |
| +// attempts and a restart must not turn a failing LIST into repeated paid work. |
| +func TestAnalyticsPruneFailedAttemptAndConcurrentAdmission(t *testing.T) { |
| + db := openTestStore(t) |
| + base := release.NewDirStore(t.TempDir()) |
| + st := &pruneFailListingStore{DirStore: base} |
| + srv := &Server{store: db, cfg: Config{Releases: st, AnalyticsRetentionDays: "400"}} |
| + now := time.Now() |
| + var wg sync.WaitGroup |
| + for i := 0; i < 4; i++ { |
| + wg.Add(1) |
| + go func() { defer wg.Done(); _ = srv.analyticsPrunePass(context.Background(), now) }() |
| + } |
| + wg.Wait() |
| + if st.calls != 1 { |
| + t.Fatalf("LISTs=%d, want one", st.calls) |
| + } |
| + if err := srv.analyticsPrunePass(context.Background(), now.Add(time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if st.calls != 1 { |
| + t.Fatalf("second pass listed: %d", st.calls) |
| + } |
| +} |
| + |
| +type pruneFailListingStore struct { |
| + *release.DirStore |
| + calls int |
| +} |
| + |
| +func (s *pruneFailListingStore) ListDirs(context.Context, string) ([]string, error) { |
| + s.calls++ |
| + return nil, errors.New("test LIST failure") |
| +} |
| + |
| +func TestAnalyticsPruneHostClaimRefuses(t *testing.T) { |
| + srv := &Server{cfg: Config{HostClaim: true, AnalyticsRetentionDays: "400", Releases: release.NewDirStore(t.TempDir())}} |
| + if err := srv.analyticsPrunePass(context.Background(), time.Now()); err == nil { |
| + t.Fatal("host-claim mutation was not refused") |
| + } |
| +} |
| + |
| +func TestAnalyticsPruneTrimsIdleCachesOnlyWhenOn(t *testing.T) { |
| + for _, cfg := range []Config{{}, {AnalyticsRetentionDays: "400", AnalyticsRetentionDryRun: "1"}, {AnalyticsRetentionDays: "400"}} { |
| + t.Run(fmt.Sprintf("days=%s,dry=%s", cfg.AnalyticsRetentionDays, cfg.AnalyticsRetentionDryRun), func(t *testing.T) { |
| + now := time.Date(2026, 11, 11, 0, 0, 0, 0, time.UTC) |
| + old := now.AddDate(0, 0, -401) |
| + cfg.Releases = release.NewDirStore(t.TempDir()) |
| + srv := &Server{store: openTestStore(t), cfg: cfg} |
| + srv.trafficMemo.put("old", analytics.Summary{PV: 1}, old) |
| + entry := usageDayEntry{date: old.Format("2006-01-02"), at: old, body: []byte("{}")} |
| + srv.usageDays.entries = map[string]usageDayEntry{"old": entry} |
| + srv.usageDays.bytes = entry.size("old") |
| + if err := srv.analyticsPrunePass(context.Background(), now); err != nil { |
| + t.Fatal(err) |
| + } |
| + kept := 1 |
| + if cfg.AnalyticsRetentionDays != "" && cfg.AnalyticsRetentionDryRun != "1" { |
| + kept = 0 |
| + } |
| + if n, _ := srv.usageDays.held(); n != kept || len(srv.trafficMemo.m) != kept { |
| + t.Fatalf("cache entries: usage=%d memo=%d want=%d", n, len(srv.trafficMemo.m), kept) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestAnalyticsPruneHostClaimRefusesStartup(t *testing.T) { |
| + for _, dry := range []string{"", "1"} { |
| + if srv, err := NewServer(Config{HostClaim: true, AnalyticsRetentionDays: "30", AnalyticsRetentionDryRun: dry}, nil); err == nil || srv != nil || !strings.Contains(err.Error(), "host-claim") { |
| + t.Fatalf("host-claim startup with dry=%q: server=%v err=%v", dry, srv, err) |
| + } |
| + } |
| +} |
diff --git a/internal/console/analyticsprune_versions_test.go b/internal/console/analyticsprune_versions_test.go| new file mode 100644 |
| index 000000000..71a8162d6 |
| --- /dev/null |
| +++ b/internal/console/analyticsprune_versions_test.go |
| @@ -0,0 +1,210 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "slices" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/analytics" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// Keep the original order so continuation markers still work after deletion. |
| +// The nil Store makes any fallback to current-key operations fail the test. |
| +type analyticsPruneVersionStore struct { |
| + release.Store |
| + versions []release.ObjectVersion |
| + removed map[release.ObjectVersion]bool |
| + pages []string |
| + wait bool |
| +} |
| + |
| +func newAnalyticsPruneVersionStore(t *testing.T, apps, boxes, versions int) *analyticsPruneVersionStore { |
| + t.Helper() |
| + st := &analyticsPruneVersionStore{removed: make(map[release.ObjectVersion]bool)} |
| + for app := 0; app < apps; app++ { |
| + for box := 0; box < boxes; box++ { |
| + key, err := analytics.DayKey("bab", fmt.Sprintf("app-%02d", app), fmt.Sprintf("box-%02d", box), "2020-01-01") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for v := 0; v < versions; v++ { |
| + st.versions = append(st.versions, release.ObjectVersion{Key: key, VersionID: fmt.Sprintf("v%d", v), IsDeleteMarker: v == 0}) |
| + } |
| + } |
| + } |
| + return st |
| +} |
| + |
| +func (s *analyticsPruneVersionStore) ListVersionDirsWithCount(ctx context.Context, prefix string) ([]string, int, error) { |
| + seen := map[string]bool{} |
| + for _, v := range s.versions { |
| + if s.removed[v] { |
| + continue |
| + } |
| + if rest, ok := strings.CutPrefix(v.Key, prefix); ok { |
| + if child, _, ok := strings.Cut(rest, "/"); ok { |
| + seen[prefix+child+"/"] = true |
| + } |
| + } |
| + } |
| + var dirs []string |
| + for dir := range seen { |
| + dirs = append(dirs, dir) |
| + } |
| + slices.Sort(dirs) |
| + return dirs, 1, ctx.Err() |
| +} |
| + |
| +func (s *analyticsPruneVersionStore) ListVersionsPage(ctx context.Context, prefix, keyMarker, versionMarker string, limit int) ([]release.ObjectVersion, string, string, error) { |
| + s.pages = append(s.pages, prefix) |
| + if s.wait { |
| + <-ctx.Done() |
| + return nil, "", "", ctx.Err() |
| + } |
| + start := 0 |
| + if keyMarker != "" || versionMarker != "" { |
| + found := false |
| + for i, v := range s.versions { |
| + if v.Key == keyMarker && v.VersionID == versionMarker { |
| + start, found = i+1, true |
| + break |
| + } |
| + } |
| + if !found { |
| + return nil, "", "", fmt.Errorf("unknown version continuation %q %q", keyMarker, versionMarker) |
| + } |
| + } |
| + var page []release.ObjectVersion |
| + for _, v := range s.versions[start:] { |
| + if !strings.HasPrefix(v.Key, prefix) || s.removed[v] { |
| + continue |
| + } |
| + if len(page) == limit { |
| + last := page[len(page)-1] |
| + return page, last.Key, last.VersionID, nil |
| + } |
| + page = append(page, v) |
| + } |
| + return page, "", "", ctx.Err() |
| +} |
| + |
| +func (s *analyticsPruneVersionStore) DeleteVersions(ctx context.Context, versions []release.ObjectVersion) error { |
| + if len(versions) > 1000 { |
| + return fmt.Errorf("oversized delete batch: %d", len(versions)) |
| + } |
| + for _, v := range versions { |
| + if s.removed[v] { |
| + return fmt.Errorf("version deleted twice: %+v", v) |
| + } |
| + s.removed[v] = true |
| + } |
| + return ctx.Err() |
| +} |
| + |
| +func TestAnalyticsPruneDefaultCapsClearBusyFleet(t *testing.T) { |
| + const apps, boxes, versions = 4, 12, 288 |
| + st := newAnalyticsPruneVersionStore(t, apps, boxes, versions) |
| + srv := &Server{store: openTestStore(t), cfg: Config{Releases: st, AnalyticsRetentionDays: "400"}} |
| + if err := srv.analyticsPrunePass(t.Context(), time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(st.removed) != apps*boxes*versions { |
| + t.Fatalf("deleted %d versions, want %d", len(st.removed), apps*boxes*versions) |
| + } |
| + var cursor string |
| + if err := srv.store.db.QueryRow(`SELECT next_box FROM analytics_prune_state WHERE id = 1`).Scan(&cursor); err != nil { |
| + t.Fatal(err) |
| + } |
| + if cursor != "" { |
| + t.Fatalf("completed pass saved cursor %q", cursor) |
| + } |
| +} |
| + |
| +func TestAnalyticsPruneBacklogFailsJobAndResumes(t *testing.T) { |
| + for _, stop := range []string{"deletes", "listed", "deadline"} { |
| + t.Run(stop, func(t *testing.T) { |
| + st := newAnalyticsPruneVersionStore(t, 1, 2, 288) |
| + srv := &Server{store: openTestStore(t), cfg: Config{Releases: st, AnalyticsRetentionDays: "400"}} |
| + now := time.Now() |
| + jobs := newJobRegistry(func() time.Time { return now }) |
| + var logs bytes.Buffer |
| + oldWriter := log.Writer() |
| + log.SetOutput(&logs) |
| + t.Cleanup(func() { log.SetOutput(oldWriter) }) |
| + maxDeletes, maxKeys, wantDeleted := analyticsPruneMaxDeletes, analyticsPruneMaxKeys, 300 |
| + ctx := t.Context() |
| + switch stop { |
| + case "deletes": |
| + maxDeletes = 300 |
| + case "listed": |
| + maxKeys = 300 |
| + case "deadline": |
| + st.wait, wantDeleted = true, 0 |
| + var cancel context.CancelFunc |
| + ctx, cancel = context.WithTimeout(ctx, 250*time.Millisecond) |
| + defer cancel() |
| + } |
| + // Economics records a prune error with jobFailed and continues |
| + // its other stages. Exercise that same job-registry path here. |
| + var pruneErr error |
| + if err := jobs.Run(ctx, "economics", func(ctx context.Context) error { |
| + pruneErr = srv.analyticsPrunePassWithLimits(ctx, now, maxDeletes, maxKeys) |
| + jobFailed(ctx, pruneErr) |
| + return nil |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + if pruneErr == nil || !strings.Contains(pruneErr.Error(), "backlog remains") { |
| + t.Fatalf("unfinished pass error: %v", pruneErr) |
| + } |
| + if stop == "deadline" && !errors.Is(pruneErr, context.DeadlineExceeded) { |
| + t.Fatalf("deadline error lost: %v", pruneErr) |
| + } |
| + status := jobs.Snapshot()[0] |
| + if status.State != JobFailed || !strings.Contains(status.Err, "backlog remains") { |
| + t.Fatalf("unfinished pass job status: %+v", status) |
| + } |
| + if len(st.removed) != wantDeleted { |
| + t.Fatalf("deleted %d versions, want %d", len(st.removed), wantDeleted) |
| + } |
| + for _, field := range []string{"warning: backlog remains:", "apps=1", "boxes=", "entries_listed=", fmt.Sprintf("deleted=%d", wantDeleted), "versions_deleted=", "list_requests=", "delete_requests=", "next_box="} { |
| + if !strings.Contains(logs.String(), field) { |
| + t.Errorf("backlog log missing %q: %s", field, &logs) |
| + } |
| + } |
| + var cursor string |
| + if err := srv.store.db.QueryRow(`SELECT next_box FROM analytics_prune_state WHERE id = 1`).Scan(&cursor); err != nil || cursor == "" { |
| + t.Fatalf("saved cursor=%q err=%v", cursor, err) |
| + } |
| + pageCount := len(st.pages) |
| + if err := srv.analyticsPrunePass(t.Context(), now.Add(23*time.Hour)); err != nil || len(st.pages) != pageCount { |
| + t.Fatalf("early retry: pages=%d, want %d, err=%v", len(st.pages), pageCount, err) |
| + } |
| + st.wait = false |
| + logs.Reset() |
| + now = now.Add(24 * time.Hour) |
| + // The next day's pass uses the same caps and the persisted cursor. |
| + if err := jobs.Run(t.Context(), "economics", func(ctx context.Context) error { |
| + return srv.analyticsPrunePassWithLimits(ctx, now, maxDeletes, maxKeys) |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(st.removed) != len(st.versions) || st.pages[pageCount] != cursor { |
| + t.Fatalf("resume: removed=%d/%d first prefix=%q want=%q", len(st.removed), len(st.versions), st.pages[pageCount], cursor) |
| + } |
| + if err := srv.store.db.QueryRow(`SELECT next_box FROM analytics_prune_state WHERE id = 1`).Scan(&cursor); err != nil || cursor != "" { |
| + t.Fatalf("finished cursor=%q err=%v", cursor, err) |
| + } |
| + if status := jobs.Snapshot()[0]; status.State != JobOK || strings.Contains(logs.String(), "warning:") { |
| + t.Fatalf("completed pass: status=%+v logs=%s", status, &logs) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/console/apidemobox.go b/internal/console/apidemobox.go| index 5ed26739e..bcd59dfc1 100644 |
| --- a/internal/console/apidemobox.go |
| +++ b/internal/console/apidemobox.go |
| @@ -11,6 +11,7 @@ import ( |
| "sort" |
| "strconv" |
| "strings" |
| + "sync/atomic" |
| "time" |
| "github.com/carlosframework/platform/internal/demo" |
| @@ -205,6 +206,12 @@ func (s *Server) handleDemoBuildStream(w http.ResponseWriter, r *http.Request) { |
| } |
| }).ServeHTTP(w, r) |
| } |
| + |
| +// demoBeforeDispatch, when a test sets it, runs before each queued job is |
| +// dispatched: the window in which serving can be turned off between |
| +// sendDemoPending's check and withDemoLocked's. |
| +var demoBeforeDispatch atomic.Pointer[func(jobID string)] |
| + |
| func (s *Server) sendDemoPending(ctx context.Context, p *demoPeer, replayRetirements bool) error { |
| s.demoJobs.mu.Lock() |
| ok := s.demoPeerOK(p) |
| @@ -301,13 +308,20 @@ func (s *Server) sendDemoPending(ctx context.Context, p *demoPeer, replayRetirem |
| if r.Job.BundleSHA256 != ready.BundleSHA256 || !time.Now().Before(r.Job.Deadline) { |
| continue |
| } |
| + if hook := demoBeforeDispatch.Load(); hook != nil { |
| + (*hook)(r.Job.ID) |
| + } |
| err = s.withDemoLocked(ctx, r.Job.DemoID, func(d DemoRow, life AppLife) error { |
| if !demoJobMatches(d, life, r.Job) { |
| return errDemoJob |
| } |
| return send(demobuild.StreamMessage{Job: r.Wire}) |
| }) |
| - if err != nil && !errors.Is(err, ErrDemoToken) && !errors.Is(err, errDemoJob) { |
| + // Serving turned off after the check above leaves the job queued, |
| + // as one queued with serving already off: the wake setDemoServing |
| + // sends delivers "off" on this stream, and the job fails at its |
| + // deadline. Returning would close the stream instead. |
| + if err != nil && !errors.Is(err, ErrDemoToken) && !errors.Is(err, errDemoJob) && !errors.Is(err, demo.ErrTrafficUnavailable) { |
| return err |
| } |
| } |
diff --git a/internal/console/demo_serving_dispatch_test.go b/internal/console/demo_serving_dispatch_test.go| new file mode 100644 |
| index 000000000..b2c959ce1 |
| --- /dev/null |
| +++ b/internal/console/demo_serving_dispatch_test.go |
| @@ -0,0 +1,122 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demobuild" |
| + "github.com/carlosframework/platform/internal/interactive" |
| + "golang.org/x/net/websocket" |
| +) |
| + |
| +// An operator turning demo serving off while the worker stream is |
| +// dispatching a queued job must not close the stream: the box gets "off" |
| +// on the same connection. The skipped job ends exactly as a job queued |
| +// while serving was already off: still queued and undispatched, failed at |
| +// its deadline with its slot released, and its requester told it failed |
| +// (#897: TestDemoServingStreamConsole saw EOF instead of "off"). |
| +func TestDemoServingOffDuringDispatchKeepsTheStream(t *testing.T) { |
| + type outcome struct { |
| + queued, failed string // the job's state before and after its deadline |
| + outbox int // dispatch rows for the job, before its deadline |
| + active string // the demo's active job after its deadline |
| + status string // the requester's status answer, job ID removed |
| + } |
| + run := func(t *testing.T, offDuringDispatch bool) outcome { |
| + s, _ := demoJobServer(t) |
| + d, j := reserveDemoJob(t, s) |
| + var once sync.Once |
| + hooked := make(chan struct{}) |
| + if offDuringDispatch { |
| + hook := func(id string) { |
| + if id != j.ID { |
| + return |
| + } |
| + once.Do(func() { |
| + if err := s.setDemoServing(context.Background(), false, "operator@example.com", time.Now()); err != nil { |
| + t.Error(err) |
| + } |
| + close(hooked) |
| + }) |
| + } |
| + demoBeforeDispatch.Store(&hook) |
| + t.Cleanup(func() { demoBeforeDispatch.Store(nil) }) |
| + } else if err := s.setDemoServing(t.Context(), false, "operator@example.com", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + ts := httptest.NewServer(s.mux) |
| + defer ts.Close() |
| + wsURL, _ := interactive.WebSocketURL(ts.URL + "/api/box/demo-builds") |
| + ws, err := interactive.DialFrame(t.Context(), wsURL, ts.URL, http.Header{"Authorization": {"Bearer worker-token"}, "Carlos-Tunnel-Name": {"demo/box"}}, demobuild.MaxJobWire*2) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer ws.Close() |
| + ready := s.demoJobs.peers["box"].ready |
| + ready.ServingProbe = 100 |
| + if err = websocket.JSON.Send(ws, ready); err != nil { |
| + t.Fatal(err) |
| + } |
| + ws.SetReadDeadline(time.Now().Add(10 * time.Second)) |
| + for { |
| + var msg demobuild.StreamMessage |
| + if err := websocket.JSON.Receive(ws, &msg); err != nil { |
| + t.Fatalf("the stream ended before serving off arrived: %v", err) |
| + } |
| + if msg.Job != nil { |
| + t.Fatal("a job was dispatched with serving off") |
| + } |
| + if msg.Serving != nil && !msg.Serving.Enabled { |
| + break |
| + } |
| + } |
| + if offDuringDispatch { |
| + select { |
| + case <-hooked: |
| + default: |
| + t.Fatal("serving was never turned off inside the dispatch window") |
| + } |
| + } |
| + var o outcome |
| + if err = s.store.db.QueryRow(`SELECT state FROM demo_jobs WHERE id=?`, j.ID).Scan(&o.queued); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = s.store.db.QueryRow(`SELECT COUNT(*) FROM demo_job_outbox WHERE job_id=?`, j.ID).Scan(&o.outbox); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = s.store.db.Exec(`UPDATE demo_jobs SET deadline=1 WHERE id=?`, j.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = s.reconcileDemoJobState(t.Context(), false); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = s.store.db.QueryRow(`SELECT state FROM demo_jobs WHERE id=?`, j.ID).Scan(&o.failed); err != nil { |
| + t.Fatal(err) |
| + } |
| + current, err := s.store.demoByID(t.Context(), d.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + o.active = current.ActiveJobID |
| + r := httptest.NewRequest("GET", "/api/demo/jobs/"+j.ID, nil) |
| + r.RemoteAddr = "192.0.2.1:1000" |
| + r.SetPathValue("jobID", j.ID) |
| + w := httptest.NewRecorder() |
| + s.handleDemoStatus(w, r) |
| + o.status = strings.ReplaceAll(w.Body.String(), j.ID, "<job>") |
| + return o |
| + } |
| + skipped := run(t, true) |
| + control := run(t, false) |
| + if skipped != control { |
| + t.Fatalf("a job skipped when serving went off mid-dispatch ended as %+v, one queued with serving off as %+v", skipped, control) |
| + } |
| + if control.queued != "queued" || control.outbox != 0 || control.failed != "failed" || control.active != "" || !strings.Contains(control.status, `"state":"failed"`) { |
| + t.Fatalf("a job queued with serving off ended as %+v", control) |
| + } |
| +} |
diff --git a/internal/console/economicspass.go b/internal/console/economicspass.go| index 0f2699b1f..ad0aa06b2 100644 |
| --- a/internal/console/economicspass.go |
| +++ b/internal/console/economicspass.go |
| @@ -57,6 +57,10 @@ func (s *Server) StartEconomicsPass(ctx context.Context) { |
| // a failed stage logs and the next still runs, because a missing census day |
| // must not cost the month's statements (spec: error handling). |
| func (s *Server) economicsPass(ctx context.Context, now time.Time) error { |
| + if err := s.analyticsPrunePass(ctx, now); err != nil { |
| + log.Printf("console: analytics prune: %v", err) |
| + jobFailed(ctx, err) |
| + } |
| date := usage.DayOf(now) |
| if err := s.censusPass(ctx, date); err != nil { |
| log.Printf("console: census pass %s: %v", date, err) |
diff --git a/internal/console/homelink.go b/internal/console/homelink.go| index 3d00baf1a..504201e7c 100644 |
| --- a/internal/console/homelink.go |
| +++ b/internal/console/homelink.go |
| @@ -353,6 +353,15 @@ func (s *Server) homeLinkSave(seq uint64, base string, ans *linkPollAnswer) stri |
| log.Printf("console: home link %s: save: %v", ans.LinkID, err) |
| return copyHomeLinkSaveFailed |
| } |
| + // The request is over the moment the link is saved: clear it here, |
| + // under ops as the save, so GET /api/cli/link never answers linked |
| + // together with a pending start (#897). The poll's own clear after it |
| + // returns then finds nothing. Lock order: ops, then mu, as everywhere. |
| + s.homeLink.mu.Lock() |
| + if cur := s.homeLink.start; cur != nil && cur.seq == seq { |
| + s.homeLink.start = nil |
| + } |
| + s.homeLink.mu.Unlock() |
| log.Printf("console: home link %s: linked to %s on %s", ans.LinkID, ans.Account, base) |
| return "" |
| } |
| @@ -414,12 +423,11 @@ func (s *Server) handleAPIHomeLinkStatus(w http.ResponseWriter, r *http.Request) |
| if !ok { |
| return |
| } |
| - l, err := reg.HomeLink() |
| - if err != nil { |
| - log.Printf("console: home link: read: %v", err) |
| - jsonError(w, http.StatusServiceUnavailable, copyHomeLinkReadFailed) |
| - return |
| - } |
| + // The request is read before the link. homeLinkSave saves the link, |
| + // then clears the request: read in this order, a request found gone |
| + // means the link is already saved, so the answer is never "not linked, |
| + // no request" in the middle of a save (the CLI's wait would call that |
| + // lost), and a linked answer carries no request. |
| out := homeLinkWire{Apps: []homeLinkAppWire{}} |
| s.homeLink.mu.Lock() |
| start := s.homeLink.start |
| @@ -430,6 +438,15 @@ func (s *Server) handleAPIHomeLinkStatus(w http.ResponseWriter, r *http.Request) |
| } |
| } |
| s.homeLink.mu.Unlock() |
| + l, err := reg.HomeLink() |
| + if err != nil { |
| + log.Printf("console: home link: read: %v", err) |
| + jsonError(w, http.StatusServiceUnavailable, copyHomeLinkReadFailed) |
| + return |
| + } |
| + if l != nil { |
| + out.Start = nil |
| + } |
| if l == nil { |
| writeJSON(w, http.StatusOK, out) |
| return |
diff --git a/internal/console/server.go b/internal/console/server.go| index d8b6f6032..eec0e02c4 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -532,6 +532,11 @@ const ( |
| // Config is everything the server reads its world through. |
| type Config struct { |
| + // AnalyticsRetentionDays is empty to keep forever, or a positive day count. |
| + // Raw settings are validated by NewServer before startup. |
| + AnalyticsRetentionDays string |
| + AnalyticsRetentionDryRun string |
| + |
| Demo demo.Config |
| DemoAlerts DemoAlertConfig |
| Registrar registrar.Registrar |
| @@ -1825,6 +1830,13 @@ func normalizeDelegationZone(raw string) string { |
| // NewServer wires a server over an opened Store, loading (or minting) the |
| // console's Keymail signing key. |
| func NewServer(cfg Config, st *Store) (*Server, error) { |
| + retentionDays, _, pruneErr := parseAnalyticsRetention(cfg.AnalyticsRetentionDays, cfg.AnalyticsRetentionDryRun) |
| + if pruneErr != nil { |
| + return nil, pruneErr |
| + } |
| + if cfg.HostClaim && retentionDays > 0 { |
| + return nil, fmt.Errorf("analytics prune: unavailable on a host-claim console") |
| + } |
| demoAPIOrigin, err := validateDemoAPIOrigin(cfg.DemoAPIOrigin) |
| if err != nil { |
| return nil, err |
diff --git a/internal/console/store.go b/internal/console/store.go| index d2fa3e94b..d14a28835 100644 |
| --- a/internal/console/store.go |
| +++ b/internal/console/store.go |
| @@ -166,6 +166,12 @@ func (s *Store) Close() error { |
| // stays idempotent. |
| func (s *Store) migrate() error { |
| for _, stmt := range []string{ |
| + `CREATE TABLE IF NOT EXISTS analytics_prune_state ( |
| + id INTEGER PRIMARY KEY CHECK(id = 1), |
| + last_started INTEGER, |
| + next_box TEXT NOT NULL DEFAULT '' |
| + );`, |
| + `INSERT INTO analytics_prune_state(id) VALUES(1) ON CONFLICT(id) DO NOTHING;`, |
| `CREATE TABLE IF NOT EXISTS owners ( |
| address TEXT NOT NULL, |
| app TEXT NOT NULL, |
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go| index 1eaa8ffa1..b55cf4e94 100644 |
| --- a/internal/console/store_gate.go |
| +++ b/internal/console/store_gate.go |
| @@ -295,6 +295,8 @@ var claimSQLTables = map[string]claimSQLTable{ |
| "managed_fleet_delivered_keys": {NonApp: "fleet access key IDs ever delivered to boxes; no app identity"}, |
| + "analytics_prune_state": {NonApp: "the console retention sweep clock and resume position; no app lifecycle authority"}, |
| + |
| // The alert engine's tables (alertstore.go). A scope is "fleet" or an |
| // account; subjects name boxes, services and apps as message text only. |
| "alert_connectors": {NonApp: "alert destinations, keyed by id and owned by a scope (fleet or an account); names no app"}, |
diff --git a/internal/edge/demo_api_integration_test.go b/internal/edge/demo_api_integration_test.go| index 68cac3fdd..b36551e0a 100644 |
| --- a/internal/edge/demo_api_integration_test.go |
| +++ b/internal/edge/demo_api_integration_test.go |
| @@ -369,13 +369,23 @@ func TestDemoAPIAliasStreaming(t *testing.T) { |
| defer cancel() |
| req, _ := http.NewRequestWithContext(ctx, "POST", origin+"/api/demo/apps", pr) |
| req.Header.Set("X-Carlos-Client", "cancel") |
| - done := make(chan error, 1) |
| + // A cancelled upload never succeeds. Do returns the |
| + // cancellation, or the edge's refusal of the broken upload |
| + // when that response reached the client first: Transport |
| + // may return a response already in flight instead (#897). |
| + type answer struct { |
| + status int |
| + err error |
| + } |
| + done := make(chan answer, 1) |
| go func() { |
| resp, err := client.Do(req) |
| + a := answer{err: err} |
| if resp != nil { |
| + a.status = resp.StatusCode |
| resp.Body.Close() |
| } |
| - done <- err |
| + done <- a |
| }() |
| if _, err := pw.Write([]byte("x")); err != nil { |
| t.Fatal(err) |
| @@ -388,9 +398,9 @@ func TestDemoAPIAliasStreaming(t *testing.T) { |
| cancel() |
| pw.CloseWithError(context.Canceled) |
| select { |
| - case err := <-done: |
| - if err == nil { |
| - t.Fatal("cancel succeeded") |
| + case a := <-done: |
| + if a.err == nil && a.status != http.StatusServiceUnavailable { |
| + t.Fatalf("cancel succeeded: %d", a.status) |
| } |
| case <-time.After(3 * time.Second): |
| t.Fatal("client ignored cancellation") |
diff --git a/internal/grouproll/engine.go b/internal/grouproll/engine.go| index a6c795c19..e676314f2 100644 |
| --- a/internal/grouproll/engine.go |
| +++ b/internal/grouproll/engine.go |
| @@ -856,6 +856,72 @@ func (e *Engine) observationOK(obs any, template map[string]any) bool { |
| "template": normalTemplate(template), "documented_no_hook": true}) |
| } |
| +// observationAccepted is preflight's and plan's observation rule (spec |
| +// §7.1, V19): the record names the pinned template exactly, or it carries |
| +// across a re-pin that changed only user data. Carrying needs every other |
| +// field of the record to match, the same template id and name with another |
| +// version number, and the two versions' launch template data, read now and |
| +// journaled, identical once their user data is removed. Nothing is |
| +// written; the acceptance is re-derived on every run. |
| +func (e *Engine) observationAccepted(ctx context.Context, obs any, tpl map[string]any) (bool, error) { |
| + if e.observationOK(obs, tpl) { |
| + return true, nil |
| + } |
| + rec, ok := obs.(map[string]any) |
| + if !ok || tpl == nil { |
| + return false, nil |
| + } |
| + old, ok := rec["template"].(map[string]any) |
| + if !ok || len(old) != 3 || len(tpl) != 3 { |
| + return false, nil |
| + } |
| + for _, k := range []string{"LaunchTemplateId", "LaunchTemplateName"} { |
| + a, aok := old[k].(string) |
| + b, bok := tpl[k].(string) |
| + if !aok || !bok || a == "" || a != b { |
| + return false, nil |
| + } |
| + } |
| + ov, _ := old["Version"].(string) |
| + nv, _ := tpl["Version"].(string) |
| + if !templateVersion.MatchString(ov) || !templateVersion.MatchString(nv) || ov == nv { |
| + return false, nil |
| + } |
| + swapped := make(map[string]any, len(rec)) |
| + for k, v := range rec { |
| + swapped[k] = v |
| + } |
| + swapped["template"] = tpl |
| + if !e.observationOK(swapped, tpl) { |
| + return false, nil |
| + } |
| + was, err := e.templateData(ctx, old) |
| + if err != nil { |
| + return false, err |
| + } |
| + now, err := e.templateData(ctx, tpl) |
| + if err != nil { |
| + return false, err |
| + } |
| + return was != nil && now != nil && pyEqual(was, now), nil |
| +} |
| + |
| +// templateData is one journaled read of a template version's data without |
| +// its user data (op template_data, a read like template_release). |
| +func (e *Engine) templateData(ctx context.Context, tpl map[string]any) (map[string]any, error) { |
| + var data map[string]any |
| + _, err := e.call(ctx, "template_data", map[string]any{"template": tpl}, time.Time{}, |
| + func(ctx context.Context, _ func(string)) (any, error) { |
| + d, err := e.g.TemplateData(ctx, tpl) |
| + if err != nil { |
| + return nil, err |
| + } |
| + data = d |
| + return d, nil |
| + }) |
| + return data, err |
| +} |
| + |
| func normalTemplate(t map[string]any) any { |
| if t == nil { |
| return nil |
| @@ -928,7 +994,11 @@ func (e *Engine) preflight(ctx context.Context, iid, digest string) (snapshotVie |
| if err != nil { |
| return snapshotView{}, nil, refuse("observation") |
| } |
| - if !e.observationOK(obs, snap.View.Template) { |
| + accepted, err := e.observationAccepted(ctx, obs, snap.View.Template) |
| + if err != nil { |
| + return snapshotView{}, nil, err |
| + } |
| + if !accepted { |
| return snapshotView{}, nil, refuse("observation") |
| } |
| e.memberEdges = map[string]map[string]any{} |
diff --git a/internal/grouproll/fake_test.go b/internal/grouproll/fake_test.go| index b465620cb..0b4a24201 100644 |
| --- a/internal/grouproll/fake_test.go |
| +++ b/internal/grouproll/fake_test.go |
| @@ -93,6 +93,8 @@ type fake struct { |
| targetWarmup time.Duration |
| targetReadyAt *time.Time |
| templateRelease string |
| + templateData map[string]map[string]any // by version; default the same data for every version |
| + pinned map[string]any // the group's pinned template; nil is fakeTemplate |
| userID string |
| writes []string |
| @@ -412,6 +414,9 @@ func (f *fake) view() GroupView { |
| Template: copyArgs(fakeTemplate), |
| TargetGroups: append([]string(nil), f.c.TargetGroups...), |
| } |
| + if f.pinned != nil { |
| + g.Template = copyArgs(f.pinned) |
| + } |
| for _, iid := range f.order { |
| if raw, ok := f.states[iid]; ok && raw != "Terminated" { |
| g.Members[iid] = Member{Phase: f.phaseOf(raw), Raw: raw, Healthy: true} |
| @@ -528,6 +533,20 @@ func (f *fake) TemplateRelease(ctx context.Context, tpl map[string]any) (string, |
| return r.(string), nil |
| } |
| +func (f *fake) TemplateData(ctx context.Context, tpl map[string]any) (map[string]any, error) { |
| + r, err := f.request("template_data", map[string]any{"template": tpl}, func() (any, error) { |
| + v, _ := tpl["Version"].(string) |
| + if d, ok := f.templateData[v]; ok { |
| + return d, nil |
| + } |
| + return map[string]any{"ImageId": "ami-0123", "InstanceType": "t4g.small"}, nil |
| + }) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return r.(map[string]any), nil |
| +} |
| + |
| func (f *fake) SetMinimum(ctx context.Context, n int) (WriteResult, error) { |
| r, err := f.request("minimum", map[string]any{"value": n}, func() (any, error) { |
| f.minimum = n |
diff --git a/internal/grouproll/observation_carry_test.go b/internal/grouproll/observation_carry_test.go| new file mode 100644 |
| index 000000000..16ccf79be |
| --- /dev/null |
| +++ b/internal/grouproll/observation_carry_test.go |
| @@ -0,0 +1,131 @@ |
| +//go:build linux || darwin |
| + |
| +package grouproll |
| + |
| +import ( |
| + "reflect" |
| + "testing" |
| +) |
| + |
| +// repinned pins the fake group to fakeTemplate's version 2: the harness's |
| +// observation still names version 1. |
| +func repinned(h *harness) { |
| + p := copyArgs(fakeTemplate) |
| + p["Version"] = "2" |
| + h.f.pinned = p |
| +} |
| + |
| +func templateDataReads(h *harness) []any { |
| + var vs []any |
| + for _, r := range h.planLog().Rows() { |
| + if r["kind"] == "intent" && r["op"] == "template_data" { |
| + vs = append(vs, r["args"].(map[string]any)["template"].(map[string]any)["Version"]) |
| + } |
| + } |
| + return vs |
| +} |
| + |
| +// V19 (spec §7.1): after a re-pin that changed only user data, the |
| +// observation for the old version carries, proved by reading both |
| +// versions; plan is clean and both reads are journaled. |
| +func TestObservationCarriesUserDataOnlyRepin(t *testing.T) { |
| + h := newHarness(t, 2) |
| + repinned(h) |
| + ok, err := h.plan(fakeIID, newSHA) |
| + if err != nil || !ok { |
| + t.Fatalf("plan = %v, %v; refusals %v", ok, err, refusalsOf(t, h.planLog())) |
| + } |
| + if got := templateDataReads(h); !reflect.DeepEqual(got, []any{"1", "2"}) { |
| + t.Fatalf("template_data reads %v, want the observation's version then the pinned one", got) |
| + } |
| + // The same template, unchanged: no extra read. |
| + h = newHarness(t, 2) |
| + if ok, err := h.plan(fakeIID, newSHA); err != nil || !ok || len(templateDataReads(h)) != 0 { |
| + t.Fatalf("exact template: %v, %v, reads %v", ok, err, templateDataReads(h)) |
| + } |
| +} |
| + |
| +// Anything but user data differing refuses observation, as before. |
| +func TestObservationCarryRefusals(t *testing.T) { |
| + cases := []struct { |
| + name string |
| + setup func(h *harness) |
| + reads int |
| + }{ |
| + {"other AMI", func(h *harness) { |
| + repinned(h) |
| + h.f.templateData = map[string]map[string]any{"2": {"ImageId": "ami-other", "InstanceType": "t4g.small"}} |
| + }, 2}, |
| + {"extra field", func(h *harness) { |
| + repinned(h) |
| + h.f.templateData = map[string]map[string]any{"2": {"ImageId": "ami-0123", "InstanceType": "t4g.small", "KeyName": "k"}} |
| + }, 2}, |
| + {"other template id", func(h *harness) { |
| + p := copyArgs(fakeTemplate) |
| + p["Version"], p["LaunchTemplateId"] = "2", "lt-0fedcba9876543210" |
| + h.f.pinned = p |
| + }, 0}, |
| + {"other template name", func(h *harness) { |
| + p := copyArgs(fakeTemplate) |
| + p["Version"], p["LaunchTemplateName"] = "2", "other-group" |
| + h.f.pinned = p |
| + }, 0}, |
| + {"record for another hook", func(h *harness) { |
| + repinned(h) |
| + h.withLock(func() { |
| + if err := h.state.Write(h.state.ObservationPath(), map[string]any{"v": 1, "group_arn": h.c.GroupARN, |
| + "hook": "other-hook", "template": copyArgs(fakeTemplate), "documented_no_hook": true}); err != nil { |
| + h.t.Fatal(err) |
| + } |
| + }) |
| + }, 0}, |
| + } |
| + for _, c := range cases { |
| + t.Run(c.name, func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + c.setup(h) |
| + ok, err := h.plan(fakeIID, newSHA) |
| + if err != nil || ok { |
| + t.Fatalf("plan = %v, %v", ok, err) |
| + } |
| + if rs := refusalsOf(t, h.planLog()); !reflect.DeepEqual(rs, []string{Text("observation")}) { |
| + t.Fatalf("refusals %v, want observation only", rs) |
| + } |
| + if n := len(templateDataReads(h)); n != c.reads { |
| + t.Fatalf("template_data reads %d, want %d", n, c.reads) |
| + } |
| + }) |
| + } |
| + // A read that fails is the read's own answer, never a carried record. |
| + h := newHarness(t, 2) |
| + repinned(h) |
| + h.f.before = func(op string, _ map[string]any) error { |
| + if op == "template_data" { |
| + return Uncertain{Key: "api"} |
| + } |
| + return nil |
| + } |
| + if ok, err := h.plan(fakeIID, newSHA); err != nil || ok { |
| + t.Fatalf("plan = %v, %v", ok, err) |
| + } |
| + if rs := refusalsOf(t, h.planLog()); !reflect.DeepEqual(rs, []string{Text("api")}) { |
| + t.Fatalf("refusals %v, want api", rs) |
| + } |
| +} |
| + |
| +// The roll's preflight carries the observation too, and refuses before |
| +// any group write when the data differ. |
| +func TestPreflightObservationCarry(t *testing.T) { |
| + h := newHarness(t, 2) |
| + repinned(h) |
| + h.f.templateData = map[string]map[string]any{"2": {"ImageId": "ami-other", "InstanceType": "t4g.small"}} |
| + err := h.runRoll() |
| + if r, ok := err.(Refusal); !ok || r.Key != "observation" || len(h.f.writes) != 0 { |
| + t.Fatalf("roll = %v, writes %v", err, h.f.writes) |
| + } |
| + h = newHarness(t, 2) |
| + repinned(h) |
| + if err := h.runRoll(); err != nil { |
| + t.Fatalf("roll with a carried observation: %v", err) |
| + } |
| +} |
diff --git a/internal/grouproll/plan.go b/internal/grouproll/plan.go| index fc30c23e7..37416a36b 100644 |
| --- a/internal/grouproll/plan.go |
| +++ b/internal/grouproll/plan.go |
| @@ -117,7 +117,11 @@ func (e *Engine) Plan(ctx context.Context, iid, sha string) (ok bool, err error) |
| if err != nil { |
| return refuse("observation") |
| } |
| - return require(e.observationOK(obs, snap.View.Template), "observation")() |
| + accepted, err := e.observationAccepted(ctx, obs, snap.View.Template) |
| + if err != nil { |
| + return err |
| + } |
| + return require(accepted, "observation")() |
| }) |
| for _, m := range sortedMembers(snap.View) { |
| var on bool |
diff --git a/internal/grouproll/provider.go b/internal/grouproll/provider.go| index 6490a7fe9..924f2f733 100644 |
| --- a/internal/grouproll/provider.go |
| +++ b/internal/grouproll/provider.go |
| @@ -100,6 +100,10 @@ type Group interface { |
| Membership(ctx context.Context, iid string) (row MemberRow, found bool, err error) |
| Instance(ctx context.Context, iid string) (InstanceState, error) |
| TemplateRelease(ctx context.Context, tpl map[string]any) (string, error) |
| + // TemplateData is the launch template version's data with its user data |
| + // removed (spec §7.1): what must be identical for the provider |
| + // observation to carry across a re-pin. |
| + TemplateData(ctx context.Context, tpl map[string]any) (map[string]any, error) |
| SetMinimum(ctx context.Context, n int) (WriteResult, error) |
| RaiseDesired(ctx context.Context, n int) (WriteResult, error) |
| Park(ctx context.Context, iid string) (WriteResult, error) |
diff --git a/internal/grouprollaws/group.go b/internal/grouprollaws/group.go| index 511b93a02..62ca5c3fa 100644 |
| --- a/internal/grouprollaws/group.go |
| +++ b/internal/grouprollaws/group.go |
| @@ -5,6 +5,8 @@ import ( |
| "compress/gzip" |
| "context" |
| "encoding/base64" |
| + "encoding/json" |
| + "encoding/xml" |
| "errors" |
| "io" |
| "math" |
| @@ -640,6 +642,156 @@ func (a *Adapter) TemplateRelease(ctx context.Context, tpl map[string]any) (stri |
| return found[0][1], nil |
| } |
| +// TemplateData is one launch template version's data as the provider |
| +// describes it, with UserData removed (spec §7.1): the evidence that two |
| +// versions differ only in the release they boot. The SDK's decoder skips |
| +// XML elements it does not know (Astra r1), so beside the decoded fields |
| +// the map carries the answer's own launchTemplateData element, byte for |
| +// byte with only its userData element cut ("LaunchTemplateDataXML"): any |
| +// other difference, a field this SDK does not know included, shows. |
| +func (a *Adapter) TemplateData(ctx context.Context, tpl map[string]any) (map[string]any, error) { |
| + version, ok := tpl["Version"].(string) |
| + if tpl == nil || !ok { |
| + return nil, grouproll.Refusal{Key: "scope"} |
| + } |
| + in := &ec2.DescribeLaunchTemplateVersionsInput{Versions: []string{version}} |
| + if id, _ := tpl["LaunchTemplateId"].(string); id != "" { |
| + in.LaunchTemplateId = aws.String(id) |
| + } else { |
| + name, _ := tpl["LaunchTemplateName"].(string) |
| + in.LaunchTemplateName = aws.String(name) |
| + } |
| + var body []byte |
| + out, err := readCall(ctx, func(ctx context.Context) (*ec2.DescribeLaunchTemplateVersionsOutput, error) { |
| + body = nil |
| + return a.ec2.DescribeLaunchTemplateVersions(ctx, in, func(o *ec2.Options) { |
| + o.APIOptions = append(o.APIOptions, func(st *middleware.Stack) error { |
| + // Just outside boundBody, which has read the whole answer. |
| + return st.Deserialize.Insert(captureBody(&body), boundBodyID, middleware.Before) |
| + }) |
| + }) |
| + }) |
| + if err != nil { |
| + return nil, err |
| + } |
| + rows := out.LaunchTemplateVersions |
| + if len(rows) != 1 || rows[0].VersionNumber == nil || strconv.FormatInt(*rows[0].VersionNumber, 10) != version || |
| + rows[0].LaunchTemplateData == nil { |
| + return nil, malformed() |
| + } |
| + exact, ok := launchDataXML(body) |
| + if !ok { |
| + return nil, malformed() |
| + } |
| + if id, _ := tpl["LaunchTemplateId"].(string); id != "" && aws.ToString(rows[0].LaunchTemplateId) != id { |
| + return nil, malformed() |
| + } |
| + data := *rows[0].LaunchTemplateData |
| + data.UserData = nil |
| + raw, err := json.Marshal(data) |
| + if err != nil { |
| + return nil, malformed() |
| + } |
| + dec := json.NewDecoder(bytes.NewReader(raw)) |
| + dec.UseNumber() |
| + var m map[string]any |
| + if err := dec.Decode(&m); err != nil || m == nil { |
| + return nil, malformed() |
| + } |
| + delete(m, "UserData") |
| + m["LaunchTemplateDataXML"] = exact |
| + return m, nil |
| +} |
| + |
| +// captureBody keeps the answer boundBody read (its bufferedBody's bytes) |
| +// for the caller. An answer that is not a bufferedBody is left alone, and |
| +// TemplateData then finds no launchTemplateData and refuses as malformed. |
| +func captureBody(dst *[]byte) middleware.DeserializeMiddleware { |
| + return middleware.DeserializeMiddlewareFunc("CarlosCaptureBody", func(ctx context.Context, |
| + in middleware.DeserializeInput, next middleware.DeserializeHandler) (middleware.DeserializeOutput, middleware.Metadata, error) { |
| + out, md, err := next.HandleDeserialize(ctx, in) |
| + if err != nil { |
| + return out, md, err |
| + } |
| + if r, ok := out.RawResponse.(*smithyhttp.Response); ok && r != nil && r.Response != nil { |
| + if b, ok := r.Body.(*bufferedBody); ok { |
| + *dst = b.data |
| + } |
| + } |
| + return out, md, nil |
| + }) |
| +} |
| + |
| +// launchDataXML is the single answered version's launchTemplateData |
| +// element exactly as the provider sent it, byte for byte, with only its |
| +// direct userData child element cut out by its byte span (8a3d302, |
| +// 2026-11-11, after Astra r2): no canonical form, so any other difference |
| +// (a field this SDK does not know, its whitespace, CDATA, namespaces) |
| +// refuses. A second launchTemplateData, a second direct userData, or an |
| +// answer that is not well formed is not one ("", false). |
| +func launchDataXML(body []byte) (string, bool) { |
| + dec := xml.NewDecoder(bytes.NewReader(body)) |
| + var path []string |
| + found, depth := 0, 0 |
| + var start, end, udStart int64 = -1, -1, -1 |
| + var cuts [][2]int64 |
| + for { |
| + before := dec.InputOffset() |
| + tok, err := dec.Token() |
| + if err == io.EOF { |
| + break |
| + } |
| + if err != nil { |
| + return "", false |
| + } |
| + switch t := tok.(type) { |
| + case xml.StartElement: |
| + path = append(path, t.Name.Local) |
| + if depth == 0 && strings.Join(path, "/") == "DescribeLaunchTemplateVersionsResponse/launchTemplateVersionSet/item/launchTemplateData" { |
| + found++ |
| + // From the start tag itself, so its attributes count too |
| + // (Fable P3-2). |
| + depth, start = 1, before |
| + continue |
| + } |
| + if depth > 0 { |
| + depth++ |
| + if depth == 2 && t.Name.Local == "userData" { |
| + if len(cuts) > 0 || udStart >= 0 { |
| + return "", false |
| + } |
| + udStart = before |
| + } |
| + } |
| + case xml.EndElement: |
| + if len(path) > 0 { |
| + path = path[:len(path)-1] |
| + } |
| + if depth > 0 { |
| + depth-- |
| + if depth == 1 && udStart >= 0 { |
| + cuts = append(cuts, [2]int64{udStart, dec.InputOffset()}) |
| + udStart = -1 |
| + } |
| + if depth == 0 { |
| + end = dec.InputOffset() |
| + } |
| + } |
| + } |
| + } |
| + if found != 1 || start < 0 || end < start || end > int64(len(body)) { |
| + return "", false |
| + } |
| + var b strings.Builder |
| + at := start |
| + for _, c := range cuts { |
| + b.Write(body[at:c[0]]) |
| + at = c[1] |
| + } |
| + b.Write(body[at:end]) |
| + return b.String(), true |
| +} |
| + |
| func int32Of(n int) (int32, bool) { |
| if n < 0 || n > math.MaxInt32 { |
| return 0, false |
diff --git a/internal/grouprollaws/group_test.go b/internal/grouprollaws/group_test.go| index 3b871d33f..dd569c76a 100644 |
| --- a/internal/grouprollaws/group_test.go |
| +++ b/internal/grouprollaws/group_test.go |
| @@ -516,10 +516,11 @@ func TestWriteShapes(t *testing.T) { |
| sort.Strings(names) |
| // Run, CancelSession and CheckPlugin (session.go) are the Session |
| // Manager transport: none touches the group's capacity. |
| - // Bucket (objects.go) is a read-only object store. |
| + // Bucket (objects.go) is a read-only object store. TemplateData is a |
| + // DescribeLaunchTemplateVersions read (spec §7.1). |
| want := []string{"Activities", "Bucket", "CallerIdentity", "CancelSession", "CheckPlugin", "Describe", "Hook", |
| "Instance", "Membership", "Online", "Park", "RaiseDesired", "Run", "SetMinimum", "Targets", |
| - "TemplateRelease", "Terminate", "Unpark"} |
| + "TemplateData", "TemplateRelease", "Terminate", "Unpark"} |
| if !reflect.DeepEqual(names, want) { |
| t.Fatalf("Adapter methods = %v\nwant %v", names, want) |
| } |
| @@ -545,3 +546,125 @@ func TestCallerIdentity(t *testing.T) { |
| t.Fatalf("no UserId: %v", err) |
| } |
| } |
| + |
| +// TemplateData is the version's launch template data without UserData, |
| +// every other field kept (spec §7.1): two versions that differ only in user |
| +// data compare equal, any other field shows. |
| +func TestTemplateData(t *testing.T) { |
| + xml := func(version, extra string) string { |
| + return `<DescribeLaunchTemplateVersionsResponse xmlns="http://ec2.amazonaws.com/doc/2016-11-15/"><requestId>r</requestId><launchTemplateVersionSet><item><launchTemplateId>lt-0abc</launchTemplateId><versionNumber>` + |
| + version + `</versionNumber><launchTemplateData><imageId>ami-0123</imageId><instanceType>t4g.small</instanceType>` + extra + |
| + `<userData>` + base64.StdEncoding.EncodeToString([]byte("CARLOS_RELEASE='v"+version+"'")) + `</userData></launchTemplateData></item></launchTemplateVersionSet></DescribeLaunchTemplateVersionsResponse>` |
| + } |
| + tpl := func(v string) map[string]any { |
| + return map[string]any{"LaunchTemplateId": "lt-0abc", "LaunchTemplateName": "carlos-dev", "Version": v} |
| + } |
| + rec := newRecorder().on("DescribeLaunchTemplateVersions", xml("7", "")).on("DescribeLaunchTemplateVersions", xml("8", "")) |
| + a := testAdapter(t, rec) |
| + d7, err := a.TemplateData(ctx, tpl("7")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + d8, err := a.TemplateData(ctx, tpl("8")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, ok := d7["UserData"]; ok || d7["ImageId"] != "ami-0123" || d7["InstanceType"] != "t4g.small" { |
| + t.Fatalf("data %v", d7) |
| + } |
| + if !reflect.DeepEqual(d7, d8) { |
| + t.Fatalf("user data only differs, yet %v != %v", d7, d8) |
| + } |
| + q := rec.requests() |
| + if q[0].Form.Get("LaunchTemplateId") != "lt-0abc" || q[0].Form.Get("LaunchTemplateVersion.1") != "7" { |
| + t.Fatalf("request %+v", q[0].Form) |
| + } |
| + // Another field differs: the maps differ. |
| + d9, err := testAdapter(t, newRecorder().on("DescribeLaunchTemplateVersions", xml("9", "<keyName>k</keyName>"))).TemplateData(ctx, tpl("9")) |
| + if err != nil || reflect.DeepEqual(d7, d9) || d9["KeyName"] != "k" { |
| + t.Fatalf("key name: %v, %v", d9, err) |
| + } |
| + // The wrong version, or another template's answer, is malformed. |
| + if _, err := testAdapter(t, newRecorder().on("DescribeLaunchTemplateVersions", xml("8", ""))).TemplateData(ctx, tpl("7")); uncertainKey(t, err).Key != "api" { |
| + t.Fatalf("wrong version: %v", err) |
| + } |
| + other := strings.Replace(xml("7", ""), "lt-0abc", "lt-0def", 1) |
| + if _, err := testAdapter(t, newRecorder().on("DescribeLaunchTemplateVersions", other)).TemplateData(ctx, tpl("7")); uncertainKey(t, err).Key != "api" { |
| + t.Fatalf("other template: %v", err) |
| + } |
| +} |
| + |
| +// TemplateData's LaunchTemplateDataXML is the answer's launchTemplateData |
| +// exactly, only its direct userData element cut (Astra r1/r2): a field the |
| +// SDK does not know, its whitespace, CDATA or a layout difference all |
| +// show; the user data never does. A nested userData is kept. Two |
| +// answered versions, two userData elements or broken XML are malformed. |
| +func TestTemplateDataUnknownField(t *testing.T) { |
| + resp := func(version, data string) string { |
| + return `<DescribeLaunchTemplateVersionsResponse xmlns="http://ec2.amazonaws.com/doc/2016-11-15/"><requestId>r</requestId><launchTemplateVersionSet><item><launchTemplateId>lt-0abc</launchTemplateId><versionNumber>` + |
| + version + `</versionNumber><launchTemplateData>` + data + `</launchTemplateData></item></launchTemplateVersionSet></DescribeLaunchTemplateVersionsResponse>` |
| + } |
| + tpl := func(v string) map[string]any { |
| + return map[string]any{"LaunchTemplateId": "lt-0abc", "LaunchTemplateName": "carlos-dev", "Version": v} |
| + } |
| + get := func(version, data string) (map[string]any, error) { |
| + return testAdapter(t, newRecorder().on("DescribeLaunchTemplateVersions", resp(version, data))).TemplateData(ctx, tpl(version)) |
| + } |
| + must := func(version, data string) map[string]any { |
| + t.Helper() |
| + d, err := get(version, data) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return d |
| + } |
| + base := must("7", `<imageId>ami-0123</imageId><userData>QQ==</userData><futureSetting></futureSetting>`) |
| + if got := base["LaunchTemplateDataXML"]; got != `<launchTemplateData><imageId>ami-0123</imageId><futureSetting></futureSetting></launchTemplateData>` { |
| + t.Fatalf("exact bytes %q", got) |
| + } |
| + if same := must("8", `<imageId>ami-0123</imageId><userData>Qg==</userData><futureSetting></futureSetting>`); !reflect.DeepEqual(base, same) { |
| + t.Fatalf("user data only, yet %v != %v", base, same) |
| + } |
| + for name, data := range map[string]string{ |
| + "unknown field": `<imageId>ami-0123</imageId><userData>QQ==</userData><futureSetting></futureSetting><other>x</other>`, |
| + "whitespace in a value": `<imageId>ami-0123</imageId><userData>QQ==</userData><futureSetting> </futureSetting>`, |
| + "cdata": `<imageId>ami-0123</imageId><userData>QQ==</userData><futureSetting><![CDATA[]]></futureSetting>`, |
| + "layout": "<imageId>ami-0123</imageId>\n<userData>QQ==</userData><futureSetting></futureSetting>", |
| + "nested userData": `<imageId>ami-0123</imageId><userData>QQ==</userData><futureSetting><userData>Q</userData></futureSetting>`, |
| + } { |
| + if d := must("9", data); reflect.DeepEqual(base, d) { |
| + t.Errorf("%s: no difference seen: %v", name, d["LaunchTemplateDataXML"]) |
| + } |
| + } |
| + // A self-closing userData, or one with attributes, is cut like any |
| + // other; a version whose user data is absent equals one that has it. |
| + for name, data := range map[string]string{ |
| + "self-closing": `<imageId>ami-0123</imageId><userData/><futureSetting></futureSetting>`, |
| + "with attributes": `<imageId>ami-0123</imageId><userData kind="x">QQ==</userData><futureSetting></futureSetting>`, |
| + "absent": `<imageId>ami-0123</imageId><futureSetting></futureSetting>`, |
| + } { |
| + if d := must("9", data); !reflect.DeepEqual(base["LaunchTemplateDataXML"], d["LaunchTemplateDataXML"]) { |
| + t.Errorf("%s: %q", name, d["LaunchTemplateDataXML"]) |
| + } |
| + } |
| + // The real answer starts with an XML prolog; the element is the same. |
| + withProlog := `<?xml version="1.0" encoding="UTF-8"?>` + "\n" + resp("7", `<imageId>ami-0123</imageId><userData>QQ==</userData><futureSetting></futureSetting>`) |
| + if got, ok := launchDataXML([]byte(withProlog)); !ok || got != base["LaunchTemplateDataXML"] { |
| + t.Errorf("prolog: %q, %v", got, ok) |
| + } |
| + for name, data := range map[string]string{ |
| + "two userData": `<imageId>ami-0123</imageId><userData>QQ==</userData><userData>QQ==</userData>`, |
| + } { |
| + if _, err := get("9", data); uncertainKey(t, err).Key != "api" { |
| + t.Errorf("%s: %v", name, err) |
| + } |
| + } |
| + two := strings.Replace(resp("7", `<imageId>a</imageId>`), "</launchTemplateVersionSet>", |
| + `<item><launchTemplateData><imageId>b</imageId></launchTemplateData></item></launchTemplateVersionSet>`, 1) |
| + if _, err := testAdapter(t, newRecorder().on("DescribeLaunchTemplateVersions", two)).TemplateData(ctx, tpl("7")); uncertainKey(t, err).Key != "api" { |
| + t.Fatalf("two items: %v", err) |
| + } |
| + if _, ok := launchDataXML([]byte(resp("7", `<imageId>a</imageId>`) + "<broken")); ok { |
| + t.Fatal("broken XML accepted") |
| + } |
| +} |
diff --git a/internal/grouprollaws/transport.go b/internal/grouprollaws/transport.go| index ee7164049..667f7e35a 100644 |
| --- a/internal/grouprollaws/transport.go |
| +++ b/internal/grouprollaws/transport.go |
| @@ -100,11 +100,22 @@ func (boundBody) HandleDeserialize(ctx context.Context, in middleware.Deserializ |
| if err != nil { |
| return out, md, err |
| } |
| - resp.Body = io.NopCloser(bytes.NewReader(data)) |
| + resp.Body = &bufferedBody{Reader: bytes.NewReader(data), data: data} |
| resp.ContentLength = int64(len(data)) |
| return out, md, nil |
| } |
| +// bufferedBody is the whole bounded answer (a pointer, so bodies stay |
| +// comparable; Fable P3-3): the operation's deserializer |
| +// reads it, and a middleware outside boundBody can take its bytes without |
| +// another read (TemplateData's captureBody). |
| +type bufferedBody struct { |
| + *bytes.Reader |
| + data []byte |
| +} |
| + |
| +func (*bufferedBody) Close() error { return nil } |
| + |
| type boundedBody struct { |
| rc io.ReadCloser |
| n int64 |
diff --git a/internal/host/hadepartures_scan_test.go b/internal/host/hadepartures_scan_test.go| index a9a003f83..27c4d03d7 100644 |
| --- a/internal/host/hadepartures_scan_test.go |
| +++ b/internal/host/hadepartures_scan_test.go |
| @@ -79,7 +79,12 @@ func (l *scanLog) dumpOnFailure(t *testing.T) { |
| } |
| l.mu.Lock() |
| defer l.mu.Unlock() |
| - t.Logf("controller log (%d lines):\n%s", len(l.lines), strings.Join(l.lines, "\n")) |
| + // One t.Logf per line: the CI gate's summary keeps only lines |
| + // carrying the test file's prefix. |
| + t.Logf("controller log (%d lines):", len(l.lines)) |
| + for _, line := range l.lines { |
| + t.Logf(" %s", line) |
| + } |
| }) |
| } |
diff --git a/internal/host/interactive_test.go b/internal/host/interactive_test.go| index c0c77a37c..4b1042433 100644 |
| --- a/internal/host/interactive_test.go |
| +++ b/internal/host/interactive_test.go |
| @@ -492,6 +492,23 @@ func (d *ixDoor) wantStatus(t *testing.T, state string) { |
| } |
| } |
| +// wantEndAfterStatus is wantEnd where another connection's Status frames |
| +// may come first on the shared channel; it skips those, nothing else. |
| +func (d *ixDoor) wantEndAfterStatus(t *testing.T) interactive.End { |
| + t.Helper() |
| + for { |
| + f := d.next(t) |
| + if f.kind == interactive.KindStatus { |
| + continue |
| + } |
| + var e interactive.End |
| + if f.kind != interactive.KindEnd || json.Unmarshal(f.payload, &e) != nil { |
| + t.Fatalf("frame %q %s, want an End", f.kind, f.payload) |
| + } |
| + return e |
| + } |
| +} |
| + |
| func (d *ixDoor) wantEnd(t *testing.T) interactive.End { |
| t.Helper() |
| f := d.next(t) |
| @@ -2099,7 +2116,11 @@ func TestInteractiveWorkerReaderGivesUpWhenReplacedDuringOpen(t *testing.T) { |
| waitFor(t, "the replacement", func() bool { return s.ctx.Err() != nil }) |
| } |
| wd.session() |
| - if e := wd.door.wantEnd(t); e.Reason != interactive.EndReplaced { |
| + // The door's frames come from both connections on one channel. The old |
| + // session sends its End before the new one dials, but each connection |
| + // is read on its own goroutine, so the new session's Status can be |
| + // queued first (#897: frame 's' {"state":"starting"}, want an End). |
| + if e := wd.door.wantEndAfterStatus(t); e.Reason != interactive.EndReplaced { |
| t.Fatalf("the old session's end %+v, want replaced", e) |
| } |
| waitFor(t, "the new session to start", func() bool { return len(wd.launch.calls()) == 1 }) |
diff --git a/internal/lease/release_snapshot_test.go b/internal/lease/release_snapshot_test.go| index 3b2cafd61..7af076170 100644 |
| --- a/internal/lease/release_snapshot_test.go |
| +++ b/internal/lease/release_snapshot_test.go |
| @@ -27,22 +27,32 @@ import ( |
| // and no L0 tail. An idle sleep's release writes none. |
| // countingReplica is a replica client that counts the LTX files opened |
| -// (a restore's reads, one GET each on S3) and records the levels written, |
| -// and can refuse snapshot writes. |
| +// (a restore's reads, one GET each on S3), records the snapshots a release |
| +// writes (releaseCall), and can refuse snapshot writes. |
| // drainSnapshotOnly marks the context of the drain release's own snapshot, |
| // so a refusing fake can refuse that snapshot and no other. |
| type drainSnapshotOnly struct{} |
| +// releaseCall marks the context a test passes to a release (Finish, |
| +// FinishSnapshot, ReleaseMarker), so the fake can tell the release's own |
| +// snapshots from the store monitor's. litestream's snapshot monitor writes |
| +// the store's first snapshot about a second after a fresh replica opens, |
| +// on the store's context; on a loaded CI worker that landed inside a |
| +// release and was counted as the release's (#897). |
| +type releaseCall struct{} |
| + |
| type countingReplica struct { |
| litestream.ReplicaClient |
| mu sync.Mutex |
| opens int |
| - writes []int |
| snapshotTXID ltx.TXID |
| failSnapshot bool |
| // refuseEarly refuses a snapshot without reading any of it, as an |
| // upload that fails before it consumes the body. |
| refuseEarly bool |
| + // releaseSnaps are the TXIDs of the snapshots written on a releaseCall |
| + // context, in order. |
| + releaseSnaps []ltx.TXID |
| } |
| func (c *countingReplica) OpenLTXFile(ctx context.Context, level int, minTXID, maxTXID ltx.TXID, offset, size int64) (io.ReadCloser, error) { |
| @@ -54,7 +64,6 @@ func (c *countingReplica) OpenLTXFile(ctx context.Context, level int, minTXID, m |
| func (c *countingReplica) WriteLTXFile(ctx context.Context, level int, minTXID, maxTXID ltx.TXID, r io.Reader) (*ltx.FileInfo, error) { |
| c.mu.Lock() |
| - c.writes = append(c.writes, level) |
| fail := c.failSnapshot && level == litestream.SnapshotLevel |
| // Only the drain's own snapshot is refused: the test marks its context |
| // (drainSnapshotOnly). The store monitor's snapshots run on the store's |
| @@ -64,6 +73,9 @@ func (c *countingReplica) WriteLTXFile(ctx context.Context, level int, minTXID, |
| early := c.refuseEarly && level == litestream.SnapshotLevel && ctx.Value(drainSnapshotOnly{}) != nil |
| if level == litestream.SnapshotLevel { |
| c.snapshotTXID = maxTXID |
| + if ctx.Value(releaseCall{}) != nil { |
| + c.releaseSnaps = append(c.releaseSnaps, maxTXID) |
| + } |
| } |
| c.mu.Unlock() |
| if early { |
| @@ -76,22 +88,12 @@ func (c *countingReplica) WriteLTXFile(ctx context.Context, level int, minTXID, |
| return c.ReplicaClient.WriteLTXFile(ctx, level, minTXID, maxTXID, r) |
| } |
| -func (c *countingReplica) mark() int { |
| - c.mu.Lock() |
| - defer c.mu.Unlock() |
| - return len(c.writes) |
| -} |
| - |
| -func (c *countingReplica) snapshotsSince(n int) int { |
| +// releaseSnapshots are the snapshots written by the releases a test marked |
| +// with releaseCall, at their TXIDs. |
| +func (c *countingReplica) releaseSnapshots() []ltx.TXID { |
| c.mu.Lock() |
| defer c.mu.Unlock() |
| - k := 0 |
| - for _, l := range c.writes[n:] { |
| - if l == litestream.SnapshotLevel { |
| - k++ |
| - } |
| - } |
| - return k |
| + return append([]ltx.TXID(nil), c.releaseSnaps...) |
| } |
| func (c *countingReplica) openCount() int { |
| @@ -156,12 +158,12 @@ func TestDrainReleaseSnapshotRestoresFromOneFile(t *testing.T) { |
| dir := t.TempDir() |
| rc := &countingReplica{ReplicaClient: lsfile.NewReplicaClient(dir)} |
| r, path := manyL0(t, fx, "instances/h", rc, 200) |
| - before := rc.mark() |
| - txid, snapErr, err := r.FinishSnapshot(ctx) |
| + rctx := context.WithValue(ctx, releaseCall{}, true) |
| + txid, snapErr, err := r.FinishSnapshot(rctx) |
| if err != nil || snapErr != nil || txid == 0 { |
| t.Fatalf("FinishSnapshot: txid %d, snapshot %v, %v", txid, snapErr, err) |
| } |
| - if err := r.ReleaseMarker(ctx, hafresh.Marker{V: 1, Clean: true}); err != nil { |
| + if err := r.ReleaseMarker(rctx, hafresh.Marker{V: 1, Clean: true}); err != nil { |
| t.Fatal(err) |
| } |
| if m := lockView(t, fx, "instances/h").Lock.Release; m == nil || !m.Clean || m.TXID != txid { |
| @@ -174,11 +176,8 @@ func TestDrainReleaseSnapshotRestoresFromOneFile(t *testing.T) { |
| if got, want := dbRows(t, out), dbRows(t, path); got != want { |
| t.Fatalf("restored %q, want %q", got, want) |
| } |
| - if k := rc.snapshotsSince(before); k != 1 { |
| - t.Fatalf("%d snapshots written by the drain's release, want 1", k) |
| - } |
| - if uint64(rc.snapshotTXID) != txid { |
| - t.Fatalf("snapshot at txid %d, final txid %d", rc.snapshotTXID, txid) |
| + if snaps := rc.releaseSnapshots(); len(snaps) != 1 || uint64(snaps[0]) != txid { |
| + t.Fatalf("snapshots written by the drain's release at %v, want one at the final txid %d", snaps, txid) |
| } |
| } |
| @@ -188,15 +187,15 @@ func TestSleepReleaseWritesNoSnapshot(t *testing.T) { |
| fx := leasetest.NewLockFixture(t) |
| rc := &countingReplica{ReplicaClient: lsfile.NewReplicaClient(t.TempDir())} |
| r, _ := manyL0(t, fx, "instances/h", rc, 5) |
| - before := rc.mark() |
| - if _, err := r.Finish(ctx); err != nil { |
| + rctx := context.WithValue(ctx, releaseCall{}, true) |
| + if _, err := r.Finish(rctx); err != nil { |
| t.Fatal(err) |
| } |
| - if err := r.ReleaseMarker(ctx, hafresh.Marker{V: 1, Clean: true}); err != nil { |
| + if err := r.ReleaseMarker(rctx, hafresh.Marker{V: 1, Clean: true}); err != nil { |
| t.Fatal(err) |
| } |
| - if k := rc.snapshotsSince(before); k != 0 { |
| - t.Fatalf("a sleep's release wrote %d snapshots", k) |
| + if snaps := rc.releaseSnapshots(); len(snaps) != 0 { |
| + t.Fatalf("a sleep's release wrote %d snapshots", len(snaps)) |
| } |
| } |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index b4df057e1..d760c3897 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -169,4 +169,5 @@ plan14-root-reads-group-capacity-damping.tsv 0c649af234a7b89a75479e59e705307e329 |
| plan14-root-reads-group-verb-followups.tsv 9c74b9876a13a3a3802860fe44406898c8bcbfd3bd22e8172a59a02674c3b4af |
| plan14-root-reads-group-read-transport-retry.tsv 9c74b9876a13a3a3802860fe44406898c8bcbfd3bd22e8172a59a02674c3b4af |
| plan14-root-reads-linked-deployments-slice1.tsv 40c8459580c3e62a53637e9989f1616e5735ce78796ec6ea1b22655a5eb4ad63 |
| -plan14-root-reads-activator-settle-wait.tsv db6bde315a4956c131aba93c6e31000e862c6198d6e124136d7ffbadece831a5 |
| +plan14-root-reads-stats-prune-400.tsv 75b32391a24d2c9269fc579aae68ac80b7b1d4ccf0be55f0373490e43a2a652a |
| +plan14-root-reads-group-observation-carry.tsv 587f6e92c5e594b9bb6436a2d0066849454407202e311f43483bed3be4591940 |
diff --git a/internal/provision/testdata/plan14-root-reads-group-observation-carry.tsv b/internal/provision/testdata/plan14-root-reads-group-observation-carry.tsv| new file mode 100644 |
| index 000000000..daf9dc07c |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-group-observation-carry.tsv |
| @@ -0,0 +1,10 @@ |
| +# Census overlay group-observation-carry, written by census-propose (#369). census-ruling-group-observation-carry, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-group-observation-carry.md. |
| +# 3 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@legacy e6723f485e963b2299144956c0e14997fd81558fded6f664a9838d4abb2cc7ae internal/grouproll/engine.go Engine.preflight legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=reads provider-observation.json from the operator's own 0700 state directory;rev3=census-ruling-group-observation-carry;basis=the same provider-observation.json read; when it names another version of the same launch template, the two versions are read from the provider (template_data, a DescribeLaunchTemplateVersions read through the adapter) and compared without user data; no new file read, nothing written file:Read@713 34851c542471ef3c75b164bd80bb63d060902ed74c438a8202af5b20684b8c48 |
| +@legacy 0732aca0e25ff830a56a0ad177aa86507e3cf14d94db509e26514a90f92aa1cf internal/grouproll/plan.go Engine.Plan legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=reads provider-observation.json from the operator's own 0700 state directory;rev3=census-ruling-group-verb-followups;basis=a missing or unreadable provider-observation.json is refused as observation instead of passing the read error through (same file, same read);rev3=census-ruling-group-observation-carry;basis=the same observation read and the same carry-over rule as preflight (two template_data provider reads); no new file read, nothing written file:Read@2300 e31735a42c7a49724f503b59406ced05c5e6d39038d8135b34c0ae463b36b415 |
| +@legacy e4be70749edd7ee592f3d45d442141733639e2e105602702b4beb2b599481a4c internal/grouprollaws/transport.go boundBody.HandleDeserialize legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=reads an AWS API answer body under the 4 MiB cap;rev3=census-ruling-group-observation-carry;basis=the same bounded read of the AWS answer; the buffered bytes are kept on a typed body (bufferedBody) so TemplateData can compare the raw launchTemplateData without a second read; no new read file:ReadAll@436 8a54d323a71cbc8b179e367d700747b2c4102e13c1322d5afa27ed15cbf54601 |
| +internal/grouproll/engine.go Engine.preflight legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=reads provider-observation.json from the operator's own 0700 state directory;rev3=census-ruling-group-observation-carry;basis=the same provider-observation.json read; when it names another version of the same launch template, the two versions are read from the provider (template_data, a DescribeLaunchTemplateVersions read through the adapter) and compared without user data; no new file read, nothing written file:Read@713 34851c542471ef3c75b164bd80bb63d060902ed74c438a8202af5b20684b8c48 |
| +internal/grouproll/plan.go Engine.Plan legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=reads provider-observation.json from the operator's own 0700 state directory;rev3=census-ruling-group-verb-followups;basis=a missing or unreadable provider-observation.json is refused as observation instead of passing the read error through (same file, same read);rev3=census-ruling-group-observation-carry;basis=the same observation read and the same carry-over rule as preflight (two template_data provider reads); no new file read, nothing written file:Read@2300 e31735a42c7a49724f503b59406ced05c5e6d39038d8135b34c0ae463b36b415 |
| +internal/grouprollaws/transport.go boundBody.HandleDeserialize legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=reads an AWS API answer body under the 4 MiB cap;rev3=census-ruling-group-observation-carry;basis=the same bounded read of the AWS answer; the buffered bytes are kept on a typed body (bufferedBody) so TemplateData can compare the raw launchTemplateData without a second read; no new read file:ReadAll@436 8a54d323a71cbc8b179e367d700747b2c4102e13c1322d5afa27ed15cbf54601 |
| +@coverage internal/grouproll d0decee68f572b1fc022493d7721f5efdba74ddfe9b1438f78cf3aee716405c0 |
| +@coverage internal/grouprollaws 287bd94344295b8618f577f0d5dd4bee809d99cb7342b53c6cc1e955e66ae01d |
diff --git a/internal/provision/testdata/plan14-root-reads-stats-prune-400.tsv b/internal/provision/testdata/plan14-root-reads-stats-prune-400.tsv| new file mode 100644 |
| index 000000000..169c05ad1 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-stats-prune-400.tsv |
| @@ -0,0 +1,15 @@ |
| +# Census overlay stats-prune-400, written by census-propose (#369). census-ruling-stats-prune-400, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-stats-prune-400.md. |
| +# 3 body, 0 sites, 4 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| +@legacy d6280748bd633ca8b5a85705243d4b1e60285ba968f8c617cc285ce3c2e59a51 infra/modules/region-host/main.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-console-invite-delivery;basis=tofu on an operator's machine with the operator's AWS credentials (no box unit; no binary embeds the file): main's module with one optional aws_iam_role_policy, host_console_mail, count 0 unless console_mail_from is set; it grants the host role ses:SendEmail on the one sending identity, the carlos-bab configuration set and its tenants, conditioned on ses:FromAddress equal to console_mail_from; no read is added and nothing on a box reads the file;rev3=census-ruling-sec-host-imdsv2-module;basis=aws_instance.host gains metadata_options (IMDSv2 required, hop limit 1, endpoint enabled), matching scanner-host; tofu configuration only, run on an operator's machine; no read, file or record write is added; applies in place on a running instance with no restart;rev3=census-ruling-hunt-account-root-hardening;basis=adds aws_iam_role_policy host_release_key_deny (count from deny_release_key_reads, default true): an explicit Deny on ssm:GetParameter, GetParameters and GetParameterHistory for parameter/carlos/release-key, and on GetParametersByPath for its ancestor paths; tofu only, run on an operator's machine; no read is added and nothing on a box reads the file;rev3=census-ruling-region-host-store-deny;basis=host_store policy: the explicit Deny on the deployment's own buckets drops s3:DeleteObject and keeps s3:DeleteBucket and s3:CreateBucket (lease release, retention and prune are DeleteObject); tofu only, run on an operator machine; no read is added and nothing on a box reads the file;rev3=census-ruling-region-ha-p3b;basis=Select default fixed resources through counted addresses and explicit moves; group mode selects scoped bucket/SSM policy, partition-aware ARNs and refuses fixed-only settings. Operator Terraform controls the instance role that can read boot parameters and write runtime bucket objects; release-key Deny and fixed-mode policy remain.;rev3=census-ruling-region-ha-g3-fixes;basis=Enable the fixed-host memory alarm with either alert input and use the selected topic for alarm and recovery notifications. Preserve module topic/subscription creation for alerts_email only. No new root runtime read or box authority.;rev3=census-ruling-managed-fleets-2b1;basis=managed fleets 2b-1 Task 5: aws_iam_policy.store_user_boundary is now counted when store_bucket_prefix is set or managed_fleets_enabled is true; its statements are concat of the unchanged object-storage pair (only with a store prefix, moved into local.store_boundary_statements byte for byte) and local.managed_boundary_statements (only with managed fleets: the fleet-data Allows on <managed_fleet_bucket_prefix>* buckets); name unchanged, description conditional on store prefix with lifecycle ignore_changes on description so a later feature switch never replaces the policy; tofu only, run on an operator's machine with the operator's AWS credentials; no box unit, user_data or binary reads the file; no read is added; default (both features off) plans no change;rev3=census-ruling-fixedbox-health-alarms;basis=Fixed host EC2 status-check alarms: auto-recover gains SNS alarm/ok actions (ec2:recover kept); new host_instance_check alarm (StatusCheckFailed_Instance 3 of 3 x 60 s -> ec2:reboot + SNS). tofu only, run on an operator machine; no read is added and nothing on a box reads the file.;rev3=census-ruling-fixed-host-ignore-user-data;basis=aws_instance.host lifecycle ignore_changes gains user_data (was [ami]): a user_data edit no longer plans an in-place update (stop/start) of a live fixed host; a new box still boots with the given script. tofu only, run on an operator machine; no read is added and nothing on a box reads the file.;rev3=census-ruling-w6-ingress-drain;basis=new aws_iam_role_policy.host_ingress_drain, count 1 only in fixed mode with ingress_target_group_arns non-empty: Allow elasticloadbalancing:DescribeTargetGroupAttributes and elasticloadbalancing:DescribeTargetHealth on Resource "*" (neither action takes a resource type). Read-only; no ELB write right. aws_iam_role.host's group-mode precondition gains length(var.ingress_target_group_arns) == 0, so group mode refuses the input. New AWS read right for the box role (the agent's drain reads); nothing a tenant or app can name.;rev3=census-ruling-stats-prune-400;basis=new aws_iam_role_policy for the console host role, count 1 only when enable_analytics_version_prune is true (default false, refused in group mode): s3:ListBucketVersions on the deployment bucket conditioned on s3:prefix apps/*, and s3:DeleteObjectVersion on deployment_bucket_arn/apps/*/*/analytics/*/days/* only; existing grants and denies unchanged; tofu only, run on an operator machine; no read is added and nothing on a box reads the file file:external@0 a3057b85373d96524f107408a4a84c99d9b6bf3a3937a9b1b6934226e3a7f81b |
| +@legacy ced8bcd6a8d4d3f56060f666d1b6b2e786bee74c02f0d860df9e848aaa0eb601 infra/modules/region-host/tests/group.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=Add mock plans covering group shape, network/AMI checks, launch constraints, boot config/ingress parameters and default fixed absence. Test-only Terraform, no real AWS effects or root runtime reads.;rev3=census-ruling-region-ha-group-rtb;basis=Two mock runs: implicit main route table, explicit association wins; test-only Terraform;rev3=census-ruling-region-ha-p3b1-fixes;basis=Read the plain script local in boot assertions and retain the shell injection probe through the mocked partition DNS suffix, with the same queue URL bound by the launch precondition. Mock plans only; no runtime reads.;rev3=census-ruling-stats-prune-400;basis=adds a mock run asserting group mode refuses enable_analytics_version_prune; test-only Terraform, no runtime reads file:external@0 76bf9d5afefb0346fd675c3a11937f56772b3fd08641fa7f20b73bb5b5bb9cf1 |
| +@legacy f66e70605dbd9d4b0b041f6e0684c48016bcf65a74884baa45cc3d69846306bb infra/modules/region-host/variables.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-console-invite-delivery;basis=tofu on an operator's machine with the operator's AWS credentials (no box unit; no binary embeds the file): main's variables with console_mail_from (validated as one lowercase address) and console_mail_region, both empty by default; no read is added and nothing on a box reads the file;rev3=census-ruling-hunt-account-root-hardening;basis=adds deny_release_key_reads (bool, default true); no read is added and nothing on a box reads the file;rev3=census-ruling-region-ha-p3b;basis=Add default-fixed mode and validated group count, zones, pinned image/release/template, ingress, configuration key and transaction-open refusal. Operator-supplied Terraform values select root boot inputs; no direct box runtime read and no group activation by default.;rev3=census-ruling-region-ha-g2-fixes;basis=Add an empty-default set of additional alert topic ARNs, validating concrete SNS topic syntax and excluding wildcards/subscriptions; operator Terraform input, no box runtime read.;rev3=census-ruling-region-ha-g3-fixes;basis=Add optional alerts_topic_arn with concrete same-region SNS ARN validation and mutual exclusion with alerts_email. The caller owns the existing topic policy and subscriptions; no runtime sink is configured and no new root read is added.;rev3=census-ruling-managed-fleets-2b1;basis=managed fleets 2b-1 Task 5: five variables, managed_fleets_enabled (bool, default false, refused unless mode is fixed), managed_fleets_deployment, managed_fleets_regions (concrete ami/subnet/sg IDs, arm64 types, no ID in two regions), managed_fleet_bucket_prefix (1-24 chars, no reserved prefix, must not cover the deployment, data or staging buckets, disjoint from store_bucket_prefix) and managed_fleet_user_path (literal IAM path, disjoint from store_user_path); store_bucket_prefix and store_user_path gain a validation refusing *, ? or ${ only when managed fleets and object storage are both on; operator Terraform input only; no box runtime read and nothing on a box reads the file;rev3=census-ruling-fixedbox-health-alarms;basis=Add optional health_alerts_topic_arn (concrete same-region SNS ARN validation, empty default); enable_auto_recovery description covers both status alarms. Operator Terraform input; no box runtime read.;rev3=census-ruling-w6-ingress-drain;basis=new variable ingress_target_group_arns (list(string), default [], non-nullable) validated as distinct ELB target group ARNs (arn:aws(-x)*:elasticloadbalancing:<region>:<12 digits>:targetgroup/<name>/<16 hex>); drives the IAM policy and output above. No read added.;rev3=census-ruling-stats-prune-400;basis=new variable enable_analytics_version_prune (bool, default false) driving the policy above; operator Terraform input; no box runtime read file:external@0 9eb722a430fc99f6deac3b3fa4f727f12a42f65864dca7c441b873f0166c15fb |
| +@legacy 71985453cf78d199770ff72844015a9c4bea9627757cc64e1c3ee831ac8288be infra/modules/region-host/tests/analytics_prune.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-stats-prune-400;basis=new mock-plan test: the analytics version-prune grant is absent by default and, when on, grants exactly the analytics day-file versions; test-only Terraform, no runtime reads file:external@0 4c92921a8a4e3c9492c39b67bc554713f369d47f9d4fd3ce00a01150ca7fde93 |
| +infra/modules/region-host/main.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-console-invite-delivery;basis=tofu on an operator's machine with the operator's AWS credentials (no box unit; no binary embeds the file): main's module with one optional aws_iam_role_policy, host_console_mail, count 0 unless console_mail_from is set; it grants the host role ses:SendEmail on the one sending identity, the carlos-bab configuration set and its tenants, conditioned on ses:FromAddress equal to console_mail_from; no read is added and nothing on a box reads the file;rev3=census-ruling-sec-host-imdsv2-module;basis=aws_instance.host gains metadata_options (IMDSv2 required, hop limit 1, endpoint enabled), matching scanner-host; tofu configuration only, run on an operator's machine; no read, file or record write is added; applies in place on a running instance with no restart;rev3=census-ruling-hunt-account-root-hardening;basis=adds aws_iam_role_policy host_release_key_deny (count from deny_release_key_reads, default true): an explicit Deny on ssm:GetParameter, GetParameters and GetParameterHistory for parameter/carlos/release-key, and on GetParametersByPath for its ancestor paths; tofu only, run on an operator's machine; no read is added and nothing on a box reads the file;rev3=census-ruling-region-host-store-deny;basis=host_store policy: the explicit Deny on the deployment's own buckets drops s3:DeleteObject and keeps s3:DeleteBucket and s3:CreateBucket (lease release, retention and prune are DeleteObject); tofu only, run on an operator machine; no read is added and nothing on a box reads the file;rev3=census-ruling-region-ha-p3b;basis=Select default fixed resources through counted addresses and explicit moves; group mode selects scoped bucket/SSM policy, partition-aware ARNs and refuses fixed-only settings. Operator Terraform controls the instance role that can read boot parameters and write runtime bucket objects; release-key Deny and fixed-mode policy remain.;rev3=census-ruling-region-ha-g3-fixes;basis=Enable the fixed-host memory alarm with either alert input and use the selected topic for alarm and recovery notifications. Preserve module topic/subscription creation for alerts_email only. No new root runtime read or box authority.;rev3=census-ruling-managed-fleets-2b1;basis=managed fleets 2b-1 Task 5: aws_iam_policy.store_user_boundary is now counted when store_bucket_prefix is set or managed_fleets_enabled is true; its statements are concat of the unchanged object-storage pair (only with a store prefix, moved into local.store_boundary_statements byte for byte) and local.managed_boundary_statements (only with managed fleets: the fleet-data Allows on <managed_fleet_bucket_prefix>* buckets); name unchanged, description conditional on store prefix with lifecycle ignore_changes on description so a later feature switch never replaces the policy; tofu only, run on an operator's machine with the operator's AWS credentials; no box unit, user_data or binary reads the file; no read is added; default (both features off) plans no change;rev3=census-ruling-fixedbox-health-alarms;basis=Fixed host EC2 status-check alarms: auto-recover gains SNS alarm/ok actions (ec2:recover kept); new host_instance_check alarm (StatusCheckFailed_Instance 3 of 3 x 60 s -> ec2:reboot + SNS). tofu only, run on an operator machine; no read is added and nothing on a box reads the file.;rev3=census-ruling-fixed-host-ignore-user-data;basis=aws_instance.host lifecycle ignore_changes gains user_data (was [ami]): a user_data edit no longer plans an in-place update (stop/start) of a live fixed host; a new box still boots with the given script. tofu only, run on an operator machine; no read is added and nothing on a box reads the file.;rev3=census-ruling-w6-ingress-drain;basis=new aws_iam_role_policy.host_ingress_drain, count 1 only in fixed mode with ingress_target_group_arns non-empty: Allow elasticloadbalancing:DescribeTargetGroupAttributes and elasticloadbalancing:DescribeTargetHealth on Resource "*" (neither action takes a resource type). Read-only; no ELB write right. aws_iam_role.host's group-mode precondition gains length(var.ingress_target_group_arns) == 0, so group mode refuses the input. New AWS read right for the box role (the agent's drain reads); nothing a tenant or app can name.;rev3=census-ruling-stats-prune-400;basis=new aws_iam_role_policy for the console host role, count 1 only when enable_analytics_version_prune is true (default false, refused in group mode): s3:ListBucketVersions on the deployment bucket conditioned on s3:prefix apps/*, and s3:DeleteObjectVersion on deployment_bucket_arn/apps/*/*/analytics/*/days/* only; existing grants and denies unchanged; tofu only, run on an operator machine; no read is added and nothing on a box reads the file file:external@0 a3057b85373d96524f107408a4a84c99d9b6bf3a3937a9b1b6934226e3a7f81b |
| +infra/modules/region-host/tests/group.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=Add mock plans covering group shape, network/AMI checks, launch constraints, boot config/ingress parameters and default fixed absence. Test-only Terraform, no real AWS effects or root runtime reads.;rev3=census-ruling-region-ha-group-rtb;basis=Two mock runs: implicit main route table, explicit association wins; test-only Terraform;rev3=census-ruling-region-ha-p3b1-fixes;basis=Read the plain script local in boot assertions and retain the shell injection probe through the mocked partition DNS suffix, with the same queue URL bound by the launch precondition. Mock plans only; no runtime reads.;rev3=census-ruling-stats-prune-400;basis=adds a mock run asserting group mode refuses enable_analytics_version_prune; test-only Terraform, no runtime reads file:external@0 76bf9d5afefb0346fd675c3a11937f56772b3fd08641fa7f20b73bb5b5bb9cf1 |
| +infra/modules/region-host/variables.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-console-invite-delivery;basis=tofu on an operator's machine with the operator's AWS credentials (no box unit; no binary embeds the file): main's variables with console_mail_from (validated as one lowercase address) and console_mail_region, both empty by default; no read is added and nothing on a box reads the file;rev3=census-ruling-hunt-account-root-hardening;basis=adds deny_release_key_reads (bool, default true); no read is added and nothing on a box reads the file;rev3=census-ruling-region-ha-p3b;basis=Add default-fixed mode and validated group count, zones, pinned image/release/template, ingress, configuration key and transaction-open refusal. Operator-supplied Terraform values select root boot inputs; no direct box runtime read and no group activation by default.;rev3=census-ruling-region-ha-g2-fixes;basis=Add an empty-default set of additional alert topic ARNs, validating concrete SNS topic syntax and excluding wildcards/subscriptions; operator Terraform input, no box runtime read.;rev3=census-ruling-region-ha-g3-fixes;basis=Add optional alerts_topic_arn with concrete same-region SNS ARN validation and mutual exclusion with alerts_email. The caller owns the existing topic policy and subscriptions; no runtime sink is configured and no new root read is added.;rev3=census-ruling-managed-fleets-2b1;basis=managed fleets 2b-1 Task 5: five variables, managed_fleets_enabled (bool, default false, refused unless mode is fixed), managed_fleets_deployment, managed_fleets_regions (concrete ami/subnet/sg IDs, arm64 types, no ID in two regions), managed_fleet_bucket_prefix (1-24 chars, no reserved prefix, must not cover the deployment, data or staging buckets, disjoint from store_bucket_prefix) and managed_fleet_user_path (literal IAM path, disjoint from store_user_path); store_bucket_prefix and store_user_path gain a validation refusing *, ? or ${ only when managed fleets and object storage are both on; operator Terraform input only; no box runtime read and nothing on a box reads the file;rev3=census-ruling-fixedbox-health-alarms;basis=Add optional health_alerts_topic_arn (concrete same-region SNS ARN validation, empty default); enable_auto_recovery description covers both status alarms. Operator Terraform input; no box runtime read.;rev3=census-ruling-w6-ingress-drain;basis=new variable ingress_target_group_arns (list(string), default [], non-nullable) validated as distinct ELB target group ARNs (arn:aws(-x)*:elasticloadbalancing:<region>:<12 digits>:targetgroup/<name>/<16 hex>); drives the IAM policy and output above. No read added.;rev3=census-ruling-stats-prune-400;basis=new variable enable_analytics_version_prune (bool, default false) driving the policy above; operator Terraform input; no box runtime read file:external@0 9eb722a430fc99f6deac3b3fa4f727f12a42f65864dca7c441b873f0166c15fb |
| +infra/modules/region-host/tests/analytics_prune.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-stats-prune-400;basis=new mock-plan test: the analytics version-prune grant is absent by default and, when on, grants exactly the analytics day-file versions; test-only Terraform, no runtime reads file:external@0 4c92921a8a4e3c9492c39b67bc554713f369d47f9d4fd3ce00a01150ca7fde93 |
| +@coverage infra/modules/region-host 2f8beef4d5633ec6de97f6e8e4d9d7f7aa5e905da1f761ff579f00f36a61196c |
| +@coverage infra/modules/region-host/tests 67454e68911e1b2ea6c5a148914f19d9e1b9c0ad84ea84d24c631cc15bb06abe |
| +@coverage internal/analytics 20e16b5970364088c5cb6d815b97f3923a91593eaade823140161d16b948b2ad |
| +@coverage internal/release 4fbbdc3adb436815e762e486114f551ec1ddf0fe30e98022f54bc229d5c63e1a |
diff --git a/internal/release/batchdelete.go b/internal/release/batchdelete.go| new file mode 100644 |
| index 000000000..8340da481 |
| --- /dev/null |
| +++ b/internal/release/batchdelete.go |
| @@ -0,0 +1,188 @@ |
| +package release |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "sort" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + awss3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| + s3types "github.com/aws/aws-sdk-go-v2/service/s3/types" |
| +) |
| + |
| +// s3DeleteBatch is the most keys one S3 DeleteObjects request may carry. |
| +const s3DeleteBatch = 1000 |
| + |
| +// BatchDeleter is an optional Store capability: delete many keys in as few |
| +// requests as the backend allows. Callers type-assert for it and fall back to |
| +// per-key Delete, as with PageLister; it is deliberately not part of Store. |
| +// |
| +// Semantics match Delete: a missing key is not an error, and a successful |
| +// delete of a key that has a change scope bumps that scope (analytics and |
| +// the other data prefixes have none, see ChangeScope). |
| +// |
| +// The error is nil only if every key was deleted. Otherwise it is a |
| +// *BatchDeleteError naming every key that was not deleted and why, so a |
| +// caller can count the successes exactly: len(keys) minus len(Failed). A key |
| +// appears in Failed when its request failed, when S3 reported it, or when it |
| +// was never attempted (cancelled context). An invalid key (empty) fails |
| +// alone and does not stop the others. Duplicate keys count once. |
| +type BatchDeleter interface { |
| + DeleteKeys(ctx context.Context, keys []string) error |
| +} |
| + |
| +// BatchDeleteError reports the keys a DeleteKeys call did not delete. |
| +type BatchDeleteError struct { |
| + Failed map[string]error // key -> why; never empty |
| +} |
| + |
| +func (e *BatchDeleteError) Error() string { |
| + keys := e.sortedKeys() |
| + first := keys[0] |
| + return fmt.Sprintf("release: batch delete: %d key(s) not deleted, first %q: %v", len(keys), first, e.Failed[first]) |
| +} |
| + |
| +// Unwrap exposes each per-key error to errors.Is and errors.As. |
| +func (e *BatchDeleteError) Unwrap() []error { |
| + keys := e.sortedKeys() |
| + out := make([]error, 0, len(keys)) |
| + for _, k := range keys { |
| + out = append(out, e.Failed[k]) |
| + } |
| + return out |
| +} |
| + |
| +func (e *BatchDeleteError) sortedKeys() []string { |
| + keys := make([]string, 0, len(e.Failed)) |
| + for k := range e.Failed { |
| + keys = append(keys, k) |
| + } |
| + sort.Strings(keys) |
| + return keys |
| +} |
| + |
| +// FailedKeys returns the set of undeleted keys from err, or nil if err is not |
| +// (and does not wrap) a *BatchDeleteError. |
| +func FailedKeys(err error) map[string]error { |
| + var be *BatchDeleteError |
| + if errors.As(err, &be) { |
| + return be.Failed |
| + } |
| + return nil |
| +} |
| + |
| +func batchResult(failed map[string]error) error { |
| + if len(failed) == 0 { |
| + return nil |
| + } |
| + return &BatchDeleteError{Failed: failed} |
| +} |
| + |
| +// uniqueKeys drops duplicates, preserving order; empty keys go straight to failed. |
| +func uniqueKeys(keys []string, failed map[string]error) []string { |
| + seen := make(map[string]bool, len(keys)) |
| + out := make([]string, 0, len(keys)) |
| + for _, k := range keys { |
| + if seen[k] { |
| + continue |
| + } |
| + seen[k] = true |
| + if k == "" { |
| + failed[k] = errors.New("release: batch delete: empty key") |
| + continue |
| + } |
| + out = append(out, k) |
| + } |
| + return out |
| +} |
| + |
| +var ( |
| + _ BatchDeleter = (*DirStore)(nil) |
| + _ BatchDeleter = (*S3Store)(nil) |
| +) |
| + |
| +// DeleteKeys loops Delete; a missing key is success. |
| +func (d *DirStore) DeleteKeys(ctx context.Context, keys []string) error { |
| + failed := map[string]error{} |
| + for _, k := range uniqueKeys(keys, failed) { |
| + if err := ctx.Err(); err != nil { |
| + failed[k] = err |
| + continue |
| + } |
| + if err := d.Delete(ctx, k); err != nil { |
| + failed[k] = err |
| + } |
| + } |
| + return batchResult(failed) |
| +} |
| + |
| +// DeleteKeys sends DeleteObjects in chunks of at most 1000 keys. A request |
| +// that fails outright marks every key in it failed with that error; the next |
| +// chunk is still tried unless ctx is done. |
| +func (s *S3Store) DeleteKeys(ctx context.Context, keys []string) error { |
| + failed := map[string]error{} |
| + todo := uniqueKeys(keys, failed) |
| + for len(todo) > 0 { |
| + n := min(len(todo), s3DeleteBatch) |
| + chunk := todo[:n] |
| + todo = todo[n:] |
| + if err := ctx.Err(); err != nil { |
| + for _, k := range chunk { |
| + failed[k] = err |
| + } |
| + continue |
| + } |
| + s.deleteChunk(ctx, chunk, failed) |
| + } |
| + return batchResult(failed) |
| +} |
| + |
| +func (s *S3Store) deleteChunk(ctx context.Context, chunk []string, failed map[string]error) { |
| + ids := make([]s3types.ObjectIdentifier, len(chunk)) |
| + for i, k := range chunk { |
| + ids[i] = s3types.ObjectIdentifier{Key: aws.String(k)} |
| + } |
| + out, err := s.Client.DeleteObjects(ctx, &awss3.DeleteObjectsInput{ |
| + Bucket: aws.String(s.Bucket), |
| + Delete: &s3types.Delete{Objects: ids, Quiet: aws.Bool(true)}, |
| + }) |
| + if err != nil { |
| + err = fmt.Errorf("release: delete objects (%d keys): %w", len(chunk), err) |
| + for _, k := range chunk { |
| + failed[k] = err |
| + } |
| + return |
| + } |
| + inChunk := make(map[string]bool, len(chunk)) |
| + for _, k := range chunk { |
| + inChunk[k] = true |
| + } |
| + for _, e := range out.Errors { |
| + perKey := fmt.Errorf("release: delete %s: %s: %s", aws.ToString(e.Key), aws.ToString(e.Code), aws.ToString(e.Message)) |
| + if e.Key == nil || !inChunk[*e.Key] { |
| + // An error we cannot attribute: fail the whole chunk rather than |
| + // report keys deleted that may not be. |
| + for _, k := range chunk { |
| + if failed[k] == nil { |
| + failed[k] = perKey |
| + } |
| + } |
| + continue |
| + } |
| + failed[*e.Key] = perKey |
| + } |
| + // Bump each change scope once per chunk, for the keys that went. |
| + bumped := map[string]bool{} |
| + for _, k := range chunk { |
| + if failed[k] != nil { |
| + continue |
| + } |
| + scope, ok := ChangeScope(k) |
| + if !ok || bumped[scope] { |
| + continue |
| + } |
| + bumped[scope] = true |
| + s.bump(ctx, k) |
| + } |
| +} |
diff --git a/internal/release/batchdelete_test.go b/internal/release/batchdelete_test.go| new file mode 100644 |
| index 000000000..0ecd4fa20 |
| --- /dev/null |
| +++ b/internal/release/batchdelete_test.go |
| @@ -0,0 +1,302 @@ |
| +package release |
| + |
| +import ( |
| + "context" |
| + "encoding/xml" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "strings" |
| + "sync" |
| + "testing" |
| +) |
| + |
| +// fakeDeleteS3 is a local HTTP S3 that answers DeleteObjects (POST ?delete) |
| +// through a caller hook and records the keys of every request. It also |
| +// answers the change-index GET (404) and PUT (200), recording PUT count. |
| +type fakeDeleteS3 struct { |
| + mu sync.Mutex |
| + chunks [][]string |
| + puts int |
| + // answer returns the response status and body for the n-th (0-based) request. |
| + answer func(n int, keys []string) (int, string) |
| +} |
| + |
| +func (f *fakeDeleteS3) serve(t *testing.T) *httptest.Server { |
| + t.Helper() |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Content-Type", "application/xml") |
| + if _, ok := r.URL.Query()["delete"]; ok && r.Method == http.MethodPost { |
| + raw, _ := io.ReadAll(r.Body) |
| + var req struct { |
| + Objects []struct { |
| + Key string `xml:"Key"` |
| + } `xml:"Object"` |
| + } |
| + if err := xml.Unmarshal(raw, &req); err != nil { |
| + t.Errorf("bad DeleteObjects body: %v", err) |
| + } |
| + keys := make([]string, 0, len(req.Objects)) |
| + for _, o := range req.Objects { |
| + keys = append(keys, o.Key) |
| + } |
| + f.mu.Lock() |
| + n := len(f.chunks) |
| + f.chunks = append(f.chunks, keys) |
| + f.mu.Unlock() |
| + status, body := 200, `<?xml version="1.0" encoding="UTF-8"?><DeleteResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"></DeleteResult>` |
| + if f.answer != nil { |
| + status, body = f.answer(n, keys) |
| + } |
| + w.WriteHeader(status) |
| + fmt.Fprint(w, body) |
| + return |
| + } |
| + switch r.Method { |
| + case http.MethodGet: // change index absent |
| + w.WriteHeader(404) |
| + fmt.Fprint(w, `<Error><Code>NoSuchKey</Code><Message>no</Message></Error>`) |
| + case http.MethodPut: |
| + f.mu.Lock() |
| + f.puts++ |
| + f.mu.Unlock() |
| + w.Header().Set("ETag", `"e"`) |
| + } |
| + })) |
| + t.Cleanup(srv.Close) |
| + return srv |
| +} |
| + |
| +func (f *fakeDeleteS3) sizes() []int { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + var out []int |
| + for _, c := range f.chunks { |
| + out = append(out, len(c)) |
| + } |
| + return out |
| +} |
| + |
| +func newDeleteS3(t *testing.T, f *fakeDeleteS3) *S3Store { |
| + t.Helper() |
| + rgwEnv(t, f.serve(t).URL) |
| + s, err := NewS3Store(context.Background(), "b") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return s |
| +} |
| + |
| +func batchKeys(n int) []string { |
| + keys := make([]string, n) |
| + for i := range keys { |
| + keys[i] = fmt.Sprintf("apps/a/x/analytics/box/days/k%04d.json", i) |
| + } |
| + return keys |
| +} |
| + |
| +func s3Err(code string) (int, string) { |
| + return 403, `<?xml version="1.0" encoding="UTF-8"?><Error><Code>` + code + `</Code><Message>m</Message></Error>` |
| +} |
| + |
| +func TestBatchDeleteS3SplitsAt1000(t *testing.T) { |
| + f := &fakeDeleteS3{} |
| + s := newDeleteS3(t, f) |
| + var _ BatchDeleter = s |
| + keys := batchKeys(1001) |
| + keys = append(keys, keys[0], keys[1]) // duplicates count once |
| + if err := s.DeleteKeys(context.Background(), keys); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := f.sizes(); len(got) != 2 || got[0] != 1000 || got[1] != 1 { |
| + t.Fatalf("request sizes = %v, want [1000 1]", got) |
| + } |
| + if err := s.DeleteKeys(context.Background(), nil); err != nil || len(f.sizes()) != 2 { |
| + t.Fatalf("empty call: err=%v requests=%v", err, f.sizes()) |
| + } |
| +} |
| + |
| +func TestBatchDeleteS3PerKeyErrors(t *testing.T) { |
| + f := &fakeDeleteS3{answer: func(_ int, keys []string) (int, string) { |
| + return 200, `<?xml version="1.0" encoding="UTF-8"?><DeleteResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> |
| +<Error><Key>` + keys[1] + `</Key><Code>AccessDenied</Code><Message>nope</Message></Error> |
| +<Error><Key>` + keys[3] + `</Key><Code>InternalError</Code><Message>boom</Message></Error></DeleteResult>` |
| + }} |
| + s := newDeleteS3(t, f) |
| + keys := batchKeys(5) |
| + err := s.DeleteKeys(context.Background(), keys) |
| + var be *BatchDeleteError |
| + if !errors.As(err, &be) { |
| + t.Fatalf("err = %v, want *BatchDeleteError", err) |
| + } |
| + if len(be.Failed) != 2 || be.Failed[keys[1]] == nil || be.Failed[keys[3]] == nil { |
| + t.Fatalf("Failed = %v, want exactly keys 1 and 3", be.Failed) |
| + } |
| + if !strings.Contains(be.Failed[keys[1]].Error(), "AccessDenied") { |
| + t.Fatalf("per-key error lost its code: %v", be.Failed[keys[1]]) |
| + } |
| + if got := len(keys) - len(FailedKeys(err)); got != 3 { |
| + t.Fatalf("precise success count = %d, want 3", got) |
| + } |
| +} |
| + |
| +func TestBatchDeleteS3RequestFailure(t *testing.T) { |
| + // Second request fails outright: only its keys are reported, the first |
| + // chunk's success is not. |
| + f := &fakeDeleteS3{answer: func(n int, _ []string) (int, string) { |
| + if n == 1 { |
| + return s3Err("AccessDenied") |
| + } |
| + return 200, `<DeleteResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"></DeleteResult>` |
| + }} |
| + s := newDeleteS3(t, f) |
| + keys := batchKeys(1001) |
| + err := s.DeleteKeys(context.Background(), keys) |
| + failed := FailedKeys(err) |
| + if len(failed) != 1 || failed[keys[1000]] == nil { |
| + t.Fatalf("Failed = %d keys (%v), want only the second request's key", len(failed), err) |
| + } |
| + if !strings.Contains(failed[keys[1000]].Error(), "AccessDenied") { |
| + t.Fatalf("request failure not identified: %v", failed[keys[1000]]) |
| + } |
| + |
| + // Every request fails: every key is named. |
| + f2 := &fakeDeleteS3{answer: func(int, []string) (int, string) { return s3Err("AccessDenied") }} |
| + s2 := newDeleteS3(t, f2) |
| + err = s2.DeleteKeys(context.Background(), keys) |
| + if got := len(FailedKeys(err)); got != 1001 { |
| + t.Fatalf("Failed = %d keys, want all 1001", got) |
| + } |
| + if !errors.Is(err, FailedKeys(err)[keys[0]]) { |
| + t.Fatal("BatchDeleteError does not unwrap to its per-key errors") |
| + } |
| +} |
| + |
| +func TestBatchDeleteCancelledContextReportsEveryKey(t *testing.T) { |
| + f := &fakeDeleteS3{} |
| + s := newDeleteS3(t, f) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + cancel() |
| + keys := batchKeys(3) |
| + err := s.DeleteKeys(ctx, keys) |
| + if got := len(FailedKeys(err)); got != 3 || !errors.Is(err, context.Canceled) { |
| + t.Fatalf("err = %v, failed = %d; want all 3 with context.Canceled", err, got) |
| + } |
| + if len(f.sizes()) != 0 { |
| + t.Fatal("a cancelled call still sent requests") |
| + } |
| + d := NewDirStore(t.TempDir()) |
| + if got := len(FailedKeys(d.DeleteKeys(ctx, keys))); got != 3 { |
| + t.Fatalf("DirStore cancelled: failed = %d, want 3", got) |
| + } |
| +} |
| + |
| +func TestBatchDeleteEmptyKeyFailsAlone(t *testing.T) { |
| + d := NewDirStore(t.TempDir()) |
| + ctx := context.Background() |
| + if _, err := d.Put(ctx, "q/a", []byte("x"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + err := d.DeleteKeys(ctx, []string{"", "q/a"}) |
| + if f := FailedKeys(err); len(f) != 1 || f[""] == nil { |
| + t.Fatalf("err = %v, want only the empty key failed", err) |
| + } |
| + if _, _, err := d.Get(ctx, "q/a"); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("valid key not deleted: %v", err) |
| + } |
| +} |
| + |
| +func TestBatchDeleteDirStoreMissingIsIdempotent(t *testing.T) { |
| + ctx := context.Background() |
| + d := NewDirStore(t.TempDir()) |
| + for _, k := range []string{"q/a", "q/b"} { |
| + if _, err := d.Put(ctx, k, []byte("x"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + var _ BatchDeleter = d |
| + if err := d.DeleteKeys(ctx, []string{"q/a", "q/never", "q/b"}); err != nil { |
| + t.Fatalf("missing key reported as error: %v", err) |
| + } |
| + if err := d.DeleteKeys(ctx, []string{"q/a", "q/b"}); err != nil { |
| + t.Fatalf("second run: %v", err) |
| + } |
| + left, _ := d.List(ctx, "q/") |
| + if len(left) != 0 { |
| + t.Fatalf("left = %v", left) |
| + } |
| +} |
| + |
| +func TestBatchDeleteDirStoreChangeIndex(t *testing.T) { |
| + ctx := context.Background() |
| + d := indexedDirStore(t) |
| + other := "apps/bab/blog/instances/h.json" |
| + analytics := "apps/bab/shop/analytics/box/days/2024-01-01.json" |
| + keys := []string{bumpTestKey, "apps/bab/shop/instances/i.json", other, analytics} |
| + for _, k := range keys { |
| + if _, err := d.Put(ctx, k, []byte("x"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + shop, blog := scopeGen(t, d, bumpTestScope), scopeGen(t, d, "apps/bab/blog") |
| + if err := d.DeleteKeys(ctx, keys); err != nil { |
| + t.Fatal(err) |
| + } |
| + // Same as Delete: each deleted scoped key moves its scope (two shop keys, two bumps). |
| + if got := scopeGen(t, d, bumpTestScope); got != shop+2 { |
| + t.Fatalf("shop gen = %d, want %d", got, shop+2) |
| + } |
| + if got := scopeGen(t, d, "apps/bab/blog"); got != blog+1 { |
| + t.Fatalf("blog gen = %d, want %d", got, blog+1) |
| + } |
| + // Analytics-only batch: no scope exists, so the index is untouched. |
| + idx, _, _ := ReadChangeIndex(ctx, d) |
| + if _, err := d.Put(ctx, analytics, []byte("x"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := d.DeleteKeys(ctx, []string{analytics}); err != nil { |
| + t.Fatal(err) |
| + } |
| + after, _, _ := ReadChangeIndex(ctx, d) |
| + if fmt.Sprint(idx.Entries) != fmt.Sprint(after.Entries) { |
| + t.Fatalf("analytics delete moved the index: %v -> %v", idx.Entries, after.Entries) |
| + } |
| +} |
| + |
| +func TestBatchDeleteS3ChangeIndex(t *testing.T) { |
| + f := &fakeDeleteS3{} |
| + s := newDeleteS3(t, f) |
| + s.EnableChangeIndex() |
| + // Analytics only: no index write at all. |
| + if err := s.DeleteKeys(context.Background(), batchKeys(3)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if f.puts != 0 { |
| + t.Fatalf("analytics batch wrote the change index %d times", f.puts) |
| + } |
| + // Two keys in one scope plus an analytics key: one bump for the scope. |
| + keys := []string{bumpTestKey, "apps/bab/shop/instances/i.json", batchKeys(1)[0]} |
| + if err := s.DeleteKeys(context.Background(), keys); err != nil { |
| + t.Fatal(err) |
| + } |
| + if f.puts != 1 { |
| + t.Fatalf("change index writes = %d, want 1 for one scope", f.puts) |
| + } |
| +} |
| + |
| +func TestBatchDeleteS3FailedKeysDoNotBump(t *testing.T) { |
| + f := &fakeDeleteS3{answer: func(_ int, keys []string) (int, string) { |
| + return 200, `<DeleteResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Error><Key>` + keys[0] + `</Key><Code>AccessDenied</Code><Message>m</Message></Error></DeleteResult>` |
| + }} |
| + s := newDeleteS3(t, f) |
| + s.EnableChangeIndex() |
| + if err := s.DeleteKeys(context.Background(), []string{bumpTestKey}); err == nil { |
| + t.Fatal("expected failure") |
| + } |
| + if f.puts != 0 { |
| + t.Fatalf("a failed delete bumped the index (%d writes)", f.puts) |
| + } |
| +} |
diff --git a/internal/release/objectversions.go b/internal/release/objectversions.go| new file mode 100644 |
| index 000000000..7a08ee227 |
| --- /dev/null |
| +++ b/internal/release/objectversions.go |
| @@ -0,0 +1,339 @@ |
| +package release |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "sort" |
| + "strings" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + awss3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| + s3types "github.com/aws/aws-sdk-go-v2/service/s3/types" |
| + "github.com/aws/smithy-go" |
| +) |
| + |
| +// Optional version-level capabilities. A bucket with versioning keeps every |
| +// rewrite of a key as a noncurrent version, and a plain Delete only adds a |
| +// delete marker on top, so "delete this key for good" needs the version |
| +// identities. These are type-asserted like PageLister and BatchDeleter, NOT |
| +// Store methods: DirStore has no versions and does not implement them. |
| + |
| +// maxVersionPage is the most entries one ListObjectVersions request returns |
| +// and the most identifiers one DeleteObjects request may carry. |
| +const maxVersionPage = 1000 |
| + |
| +// ErrVersionAccessDenied is wrapped into every error caused by the backend |
| +// refusing a version listing or a version delete (S3 AccessDenied, as a whole |
| +// request or for one object). Callers test it with errors.Is to fall back to |
| +// current-key deletion and say which permission is missing. |
| +var ErrVersionAccessDenied = errors.New("release: object versions: access denied") |
| + |
| +// ObjectVersion names one stored version of a key, or one delete marker. |
| +// VersionID is opaque; "null" is a real ID for objects written before |
| +// versioning was enabled. |
| +type ObjectVersion struct { |
| + Key string |
| + VersionID string |
| + IsDeleteMarker bool |
| +} |
| + |
| +// VersionPager lists the versions and delete markers under a prefix, one |
| +// bounded page at a time. Entries come back sorted by nondecreasing Key; the |
| +// order of versions within one key is the backend's and opaque to callers. |
| +// keyMarker and versionMarker are "" for the first page, then the two |
| +// returned markers, passed back unchanged (a page may end in the middle of a |
| +// key's versions). Both returned markers are empty when the listing is |
| +// complete. limit is clamped to 1..1000 (<=0 means 1000). |
| +type VersionPager interface { |
| + ListVersionsPage(ctx context.Context, prefix, keyMarker, versionMarker string, limit int) (versions []ObjectVersion, nextKeyMarker, nextVersionMarker string, err error) |
| +} |
| + |
| +// VersionDeleter permanently deletes the exact versions named, never a bare |
| +// key. It returns nil only if every one was deleted, otherwise a |
| +// *VersionDeleteError naming each that was not. An entry with an empty Key or |
| +// empty VersionID fails alone and is never sent. Duplicates count once. |
| +type VersionDeleter interface { |
| + DeleteVersions(ctx context.Context, versions []ObjectVersion) error |
| +} |
| + |
| +// VersionDirLister lists the immediate "directories" under a prefix by |
| +// version listing, so a tree whose every key is currently a delete marker |
| +// (invisible to ListDirs) is still found. It reports the number of LIST |
| +// requests made, like CountedDirLister. Results are sorted and deduplicated. |
| +type VersionDirLister interface { |
| + ListVersionDirsWithCount(ctx context.Context, prefix string) ([]string, int, error) |
| +} |
| + |
| +var ( |
| + _ VersionPager = (*S3Store)(nil) |
| + _ VersionDeleter = (*S3Store)(nil) |
| + _ VersionDirLister = (*S3Store)(nil) |
| +) |
| + |
| +// VersionDeleteError reports the versions a DeleteVersions call did not |
| +// delete. The keys are the exact identities passed in (IsDeleteMarker |
| +// included), so a caller counts successes as len(input) minus len(Failed). |
| +type VersionDeleteError struct { |
| + Failed map[ObjectVersion]error // never empty |
| +} |
| + |
| +func (e *VersionDeleteError) sorted() []ObjectVersion { |
| + out := make([]ObjectVersion, 0, len(e.Failed)) |
| + for v := range e.Failed { |
| + out = append(out, v) |
| + } |
| + sort.Slice(out, func(i, j int) bool { |
| + if out[i].Key != out[j].Key { |
| + return out[i].Key < out[j].Key |
| + } |
| + if out[i].VersionID != out[j].VersionID { |
| + return out[i].VersionID < out[j].VersionID |
| + } |
| + return !out[i].IsDeleteMarker && out[j].IsDeleteMarker |
| + }) |
| + return out |
| +} |
| + |
| +func (e *VersionDeleteError) Error() string { |
| + vs := e.sorted() |
| + first := vs[0] |
| + return fmt.Sprintf("release: delete versions: %d version(s) not deleted, first %q version %q: %v", len(vs), first.Key, first.VersionID, e.Failed[first]) |
| +} |
| + |
| +// Unwrap exposes every per-version error to errors.Is and errors.As. |
| +func (e *VersionDeleteError) Unwrap() []error { |
| + vs := e.sorted() |
| + out := make([]error, 0, len(vs)) |
| + for _, v := range vs { |
| + out = append(out, e.Failed[v]) |
| + } |
| + return out |
| +} |
| + |
| +// FailedVersions returns the undeleted set from err, or nil if err is not |
| +// (and does not wrap) a *VersionDeleteError. |
| +func FailedVersions(err error) map[ObjectVersion]error { |
| + var ve *VersionDeleteError |
| + if errors.As(err, &ve) { |
| + return ve.Failed |
| + } |
| + return nil |
| +} |
| + |
| +func isAccessDeniedCode(code string) bool { return code == "AccessDenied" } |
| + |
| +// versionRequestErr marks a whole-request AccessDenied with the sentinel, |
| +// keeping the original error reachable. |
| +func versionRequestErr(op string, err error) error { |
| + var apiErr smithy.APIError |
| + if errors.As(err, &apiErr) && isAccessDeniedCode(apiErr.ErrorCode()) { |
| + return fmt.Errorf("release: %s: %w: %w", op, ErrVersionAccessDenied, err) |
| + } |
| + return fmt.Errorf("release: %s: %w", op, err) |
| +} |
| + |
| +// ListVersionsPage is one ListObjectVersions request. Versions and delete |
| +// markers arrive as separate lists; they are merged back into key order, and |
| +// within a key into the order S3 reports (newest first, by LastModified). |
| +// The markers are returned exactly as S3 gave them. |
| +func (s *S3Store) ListVersionsPage(ctx context.Context, prefix, keyMarker, versionMarker string, limit int) ([]ObjectVersion, string, string, error) { |
| + if limit <= 0 || limit > maxVersionPage { |
| + limit = maxVersionPage |
| + } |
| + in := &awss3.ListObjectVersionsInput{ |
| + Bucket: aws.String(s.Bucket), |
| + Prefix: aws.String(prefix), |
| + MaxKeys: aws.Int32(int32(limit)), |
| + } |
| + if keyMarker != "" { |
| + in.KeyMarker = aws.String(keyMarker) |
| + } |
| + if versionMarker != "" { |
| + in.VersionIdMarker = aws.String(versionMarker) |
| + } |
| + out, err := s.Client.ListObjectVersions(ctx, in) |
| + if err != nil { |
| + return nil, "", "", versionRequestErr("list object versions", err) |
| + } |
| + type entry struct { |
| + v ObjectVersion |
| + at int64 |
| + } |
| + entries := make([]entry, 0, len(out.Versions)+len(out.DeleteMarkers)) |
| + for _, v := range out.Versions { |
| + e := entry{v: ObjectVersion{Key: aws.ToString(v.Key), VersionID: aws.ToString(v.VersionId)}} |
| + if v.LastModified != nil { |
| + e.at = v.LastModified.UnixNano() |
| + } |
| + entries = append(entries, e) |
| + } |
| + for _, m := range out.DeleteMarkers { |
| + e := entry{v: ObjectVersion{Key: aws.ToString(m.Key), VersionID: aws.ToString(m.VersionId), IsDeleteMarker: true}} |
| + if m.LastModified != nil { |
| + e.at = m.LastModified.UnixNano() |
| + } |
| + entries = append(entries, e) |
| + } |
| + sort.SliceStable(entries, func(i, j int) bool { |
| + if entries[i].v.Key != entries[j].v.Key { |
| + return entries[i].v.Key < entries[j].v.Key |
| + } |
| + return entries[i].at > entries[j].at |
| + }) |
| + res := make([]ObjectVersion, len(entries)) |
| + for i, e := range entries { |
| + res[i] = e.v |
| + } |
| + if !aws.ToBool(out.IsTruncated) { |
| + return res, "", "", nil |
| + } |
| + nk, nv := aws.ToString(out.NextKeyMarker), aws.ToString(out.NextVersionIdMarker) |
| + if nk == "" { |
| + return nil, "", "", errors.New("release: list object versions: truncated page without a next key marker") |
| + } |
| + if nk == keyMarker && nv == versionMarker { |
| + return nil, "", "", errors.New("release: list object versions: markers did not advance") |
| + } |
| + return res, nk, nv, nil |
| +} |
| + |
| +// ListVersionDirsWithCount lists CommonPrefixes under prefix with |
| +// delimiter "/" through ListObjectVersions, following every page. Directories |
| +// whose keys are all delete markers still appear. |
| +func (s *S3Store) ListVersionDirsWithCount(ctx context.Context, prefix string) ([]string, int, error) { |
| + if prefix != "" && !strings.HasSuffix(prefix, "/") { |
| + prefix += "/" |
| + } |
| + requests := 0 |
| + seen := map[string]bool{} |
| + var keyMarker, versionMarker string |
| + for { |
| + in := &awss3.ListObjectVersionsInput{ |
| + Bucket: aws.String(s.Bucket), |
| + Prefix: aws.String(prefix), |
| + Delimiter: aws.String("/"), |
| + MaxKeys: aws.Int32(maxVersionPage), |
| + } |
| + if keyMarker != "" { |
| + in.KeyMarker = aws.String(keyMarker) |
| + } |
| + if versionMarker != "" { |
| + in.VersionIdMarker = aws.String(versionMarker) |
| + } |
| + requests++ |
| + out, err := s.Client.ListObjectVersions(ctx, in) |
| + if err != nil { |
| + return nil, requests, versionRequestErr("list object version dirs", err) |
| + } |
| + for _, cp := range out.CommonPrefixes { |
| + seen[aws.ToString(cp.Prefix)] = true |
| + } |
| + if !aws.ToBool(out.IsTruncated) { |
| + break |
| + } |
| + nk, nv := aws.ToString(out.NextKeyMarker), aws.ToString(out.NextVersionIdMarker) |
| + if nk == "" || (nk == keyMarker && nv == versionMarker) { |
| + return nil, requests, errors.New("release: list object version dirs: markers did not advance") |
| + } |
| + keyMarker, versionMarker = nk, nv |
| + } |
| + dirs := make([]string, 0, len(seen)) |
| + for d := range seen { |
| + dirs = append(dirs, d) |
| + } |
| + sort.Strings(dirs) |
| + return dirs, requests, nil |
| +} |
| + |
| +// DeleteVersions sends DeleteObjects with explicit version IDs in chunks of |
| +// at most 1000. A request that fails outright marks every version in it |
| +// failed; later chunks are still tried unless ctx is done, and every version |
| +// not attempted is reported failed with the context error. A bare key is |
| +// never deleted: an empty VersionID is rejected before anything is sent. |
| +func (s *S3Store) DeleteVersions(ctx context.Context, versions []ObjectVersion) error { |
| + failed := map[ObjectVersion]error{} |
| + seen := map[[2]string]bool{} |
| + todo := make([]ObjectVersion, 0, len(versions)) |
| + for _, v := range versions { |
| + id := [2]string{v.Key, v.VersionID} |
| + if seen[id] { |
| + continue |
| + } |
| + seen[id] = true |
| + switch { |
| + case v.Key == "": |
| + failed[v] = errors.New("release: delete versions: empty key") |
| + case v.VersionID == "": |
| + failed[v] = fmt.Errorf("release: delete versions: %s: empty version id", v.Key) |
| + default: |
| + todo = append(todo, v) |
| + } |
| + } |
| + for len(todo) > 0 { |
| + n := min(len(todo), maxVersionPage) |
| + chunk := todo[:n] |
| + todo = todo[n:] |
| + if err := ctx.Err(); err != nil { |
| + for _, v := range chunk { |
| + failed[v] = err |
| + } |
| + continue |
| + } |
| + s.deleteVersionChunk(ctx, chunk, failed) |
| + } |
| + if len(failed) == 0 { |
| + return nil |
| + } |
| + return &VersionDeleteError{Failed: failed} |
| +} |
| + |
| +func (s *S3Store) deleteVersionChunk(ctx context.Context, chunk []ObjectVersion, failed map[ObjectVersion]error) { |
| + ids := make([]s3types.ObjectIdentifier, len(chunk)) |
| + byID := make(map[[2]string]ObjectVersion, len(chunk)) |
| + for i, v := range chunk { |
| + ids[i] = s3types.ObjectIdentifier{Key: aws.String(v.Key), VersionId: aws.String(v.VersionID)} |
| + byID[[2]string{v.Key, v.VersionID}] = v |
| + } |
| + out, err := s.Client.DeleteObjects(ctx, &awss3.DeleteObjectsInput{ |
| + Bucket: aws.String(s.Bucket), |
| + Delete: &s3types.Delete{Objects: ids, Quiet: aws.Bool(true)}, |
| + }) |
| + if err != nil { |
| + err = versionRequestErr(fmt.Sprintf("delete object versions (%d)", len(chunk)), err) |
| + for _, v := range chunk { |
| + failed[v] = err |
| + } |
| + return |
| + } |
| + for _, e := range out.Errors { |
| + perItem := fmt.Errorf("release: delete %s version %s: %s: %s", aws.ToString(e.Key), aws.ToString(e.VersionId), aws.ToString(e.Code), aws.ToString(e.Message)) |
| + if isAccessDeniedCode(aws.ToString(e.Code)) { |
| + perItem = fmt.Errorf("%w: %w", ErrVersionAccessDenied, perItem) |
| + } |
| + v, ok := byID[[2]string{aws.ToString(e.Key), aws.ToString(e.VersionId)}] |
| + if e.Key == nil || e.VersionId == nil || !ok { |
| + // Cannot attribute it: fail the chunk rather than report deleted |
| + // what may not be. |
| + for _, c := range chunk { |
| + if failed[c] == nil { |
| + failed[c] = perItem |
| + } |
| + } |
| + continue |
| + } |
| + failed[v] = perItem |
| + } |
| + bumped := map[string]bool{} |
| + for _, v := range chunk { |
| + if failed[v] != nil { |
| + continue |
| + } |
| + scope, ok := ChangeScope(v.Key) |
| + if !ok || bumped[scope] { |
| + continue |
| + } |
| + bumped[scope] = true |
| + s.bump(ctx, v.Key) |
| + } |
| +} |
diff --git a/internal/release/objectversions_test.go b/internal/release/objectversions_test.go| new file mode 100644 |
| index 000000000..fb165f1e9 |
| --- /dev/null |
| +++ b/internal/release/objectversions_test.go |
| @@ -0,0 +1,508 @@ |
| +package release |
| + |
| +import ( |
| + "context" |
| + "encoding/xml" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// fakeVersionS3 is a local HTTP S3 that answers ListObjectVersions (GET |
| +// ?versions) from an ordered entry list and DeleteObjects (POST ?delete) |
| +// through a hook. Like S3 it reports Versions and DeleteMarkers in separate |
| +// lists, pages by (key marker, version marker) and groups by delimiter. |
| +type fakeVersionS3 struct { |
| + mu sync.Mutex |
| + entries []fakeVer // sorted by key; within a key, newest first |
| + lists []string // raw query of every list request |
| + deletes [][]ObjectVersion |
| + puts int |
| + failAll string // list/delete request answered 403 with this code |
| + answer func(n int, ids []ObjectVersion) (int, string) |
| +} |
| + |
| +type fakeVer struct { |
| + key, id string |
| + marker bool |
| + age int // larger = older |
| +} |
| + |
| +func (f *fakeVersionS3) add(key string, ids ...string) { |
| + for i, id := range ids { |
| + f.entries = append(f.entries, fakeVer{key: key, id: id, age: i}) |
| + } |
| +} |
| + |
| +func (f *fakeVersionS3) addMarker(key, id string, age int) { |
| + f.entries = append(f.entries, fakeVer{key: key, id: id, marker: true, age: age}) |
| +} |
| + |
| +func (f *fakeVersionS3) sortEntries() { |
| + sort.SliceStable(f.entries, func(i, j int) bool { |
| + if f.entries[i].key != f.entries[j].key { |
| + return f.entries[i].key < f.entries[j].key |
| + } |
| + return f.entries[i].age < f.entries[j].age |
| + }) |
| +} |
| + |
| +func xmlEsc(s string) string { |
| + var b strings.Builder |
| + _ = xml.EscapeText(&b, []byte(s)) |
| + return b.String() |
| +} |
| + |
| +func (f *fakeVersionS3) serve(t *testing.T) *httptest.Server { |
| + t.Helper() |
| + f.sortEntries() |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Content-Type", "application/xml") |
| + q := r.URL.Query() |
| + _, isDelete := q["delete"] |
| + _, isVersions := q["versions"] |
| + f.mu.Lock() |
| + deny := f.failAll |
| + f.mu.Unlock() |
| + switch { |
| + case isVersions && r.Method == http.MethodGet: |
| + f.mu.Lock() |
| + f.lists = append(f.lists, r.URL.RawQuery) |
| + f.mu.Unlock() |
| + if deny != "" { |
| + w.WriteHeader(403) |
| + fmt.Fprintf(w, `<Error><Code>%s</Code><Message>m</Message></Error>`, deny) |
| + return |
| + } |
| + f.list(w, q.Get("prefix"), q.Get("delimiter"), q.Get("key-marker"), q.Get("version-id-marker"), q.Get("max-keys")) |
| + case isDelete && r.Method == http.MethodPost: |
| + raw, _ := io.ReadAll(r.Body) |
| + var req struct { |
| + Objects []struct { |
| + Key string `xml:"Key"` |
| + VersionID string `xml:"VersionId"` |
| + } `xml:"Object"` |
| + } |
| + if err := xml.Unmarshal(raw, &req); err != nil { |
| + t.Errorf("bad DeleteObjects body: %v", err) |
| + } |
| + ids := make([]ObjectVersion, 0, len(req.Objects)) |
| + for _, o := range req.Objects { |
| + ids = append(ids, ObjectVersion{Key: o.Key, VersionID: o.VersionID}) |
| + } |
| + f.mu.Lock() |
| + n := len(f.deletes) |
| + f.deletes = append(f.deletes, ids) |
| + f.mu.Unlock() |
| + if deny != "" { |
| + w.WriteHeader(403) |
| + fmt.Fprintf(w, `<Error><Code>%s</Code><Message>m</Message></Error>`, deny) |
| + return |
| + } |
| + status, body := 200, `<?xml version="1.0" encoding="UTF-8"?><DeleteResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"></DeleteResult>` |
| + if f.answer != nil { |
| + status, body = f.answer(n, ids) |
| + } |
| + w.WriteHeader(status) |
| + fmt.Fprint(w, body) |
| + case r.Method == http.MethodGet: |
| + w.WriteHeader(404) |
| + fmt.Fprint(w, `<Error><Code>NoSuchKey</Code><Message>no</Message></Error>`) |
| + case r.Method == http.MethodPut: |
| + f.mu.Lock() |
| + f.puts++ |
| + f.mu.Unlock() |
| + w.Header().Set("ETag", `"e"`) |
| + } |
| + })) |
| + t.Cleanup(srv.Close) |
| + return srv |
| +} |
| + |
| +func (f *fakeVersionS3) list(w http.ResponseWriter, prefix, delim, keyMarker, verMarker, maxKeys string) { |
| + max, _ := strconv.Atoi(maxKeys) |
| + if max <= 0 || max > 1000 { |
| + max = 1000 |
| + } |
| + // Start after the marker: after every entry of a key lower than the |
| + // marker key, and after the marker version within the marker key. |
| + start := 0 |
| + if keyMarker != "" { |
| + for start < len(f.entries) && f.entries[start].key < keyMarker { |
| + start++ |
| + } |
| + if verMarker != "" { |
| + for start < len(f.entries) && f.entries[start].key == keyMarker { |
| + start++ |
| + if f.entries[start-1].id == verMarker { |
| + break |
| + } |
| + } |
| + } else { |
| + for start < len(f.entries) && f.entries[start].key == keyMarker { |
| + start++ |
| + } |
| + } |
| + } |
| + var vs, ms []fakeVer |
| + prefixes := map[string]bool{} |
| + count := 0 |
| + truncated := false |
| + var lastKey, lastID string |
| + for i := start; i < len(f.entries); i++ { |
| + e := f.entries[i] |
| + if !strings.HasPrefix(e.key, prefix) { |
| + continue |
| + } |
| + if delim != "" { |
| + rest := e.key[len(prefix):] |
| + if j := strings.Index(rest, delim); j >= 0 { |
| + p := prefix + rest[:j+1] |
| + if !prefixes[p] { |
| + if count == max { |
| + truncated = true |
| + break |
| + } |
| + prefixes[p] = true |
| + count++ |
| + lastKey, lastID = e.key, e.id |
| + } |
| + continue |
| + } |
| + } |
| + if count == max { |
| + truncated = true |
| + break |
| + } |
| + count++ |
| + lastKey, lastID = e.key, e.id |
| + if e.marker { |
| + ms = append(ms, e) |
| + } else { |
| + vs = append(vs, e) |
| + } |
| + } |
| + var b strings.Builder |
| + b.WriteString(`<?xml version="1.0" encoding="UTF-8"?><ListVersionsResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">`) |
| + fmt.Fprintf(&b, "<IsTruncated>%v</IsTruncated>", truncated) |
| + if truncated { |
| + fmt.Fprintf(&b, "<NextKeyMarker>%s</NextKeyMarker><NextVersionIdMarker>%s</NextVersionIdMarker>", xmlEsc(lastKey), xmlEsc(lastID)) |
| + } |
| + base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) |
| + for _, e := range vs { |
| + fmt.Fprintf(&b, "<Version><Key>%s</Key><VersionId>%s</VersionId><IsLatest>false</IsLatest><LastModified>%s</LastModified></Version>", |
| + xmlEsc(e.key), xmlEsc(e.id), base.Add(-time.Duration(e.age)*time.Hour).Format(time.RFC3339)) |
| + } |
| + for _, e := range ms { |
| + fmt.Fprintf(&b, "<DeleteMarker><Key>%s</Key><VersionId>%s</VersionId><IsLatest>false</IsLatest><LastModified>%s</LastModified></DeleteMarker>", |
| + xmlEsc(e.key), xmlEsc(e.id), base.Add(-time.Duration(e.age)*time.Hour).Format(time.RFC3339)) |
| + } |
| + var ps []string |
| + for p := range prefixes { |
| + ps = append(ps, p) |
| + } |
| + sort.Strings(ps) |
| + for _, p := range ps { |
| + fmt.Fprintf(&b, "<CommonPrefixes><Prefix>%s</Prefix></CommonPrefixes>", xmlEsc(p)) |
| + } |
| + b.WriteString("</ListVersionsResult>") |
| + fmt.Fprint(w, b.String()) |
| +} |
| + |
| +func newVersionS3(t *testing.T, f *fakeVersionS3) *S3Store { |
| + t.Helper() |
| + rgwEnv(t, f.serve(t).URL) |
| + s, err := NewS3Store(context.Background(), "b") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return s |
| +} |
| + |
| +func TestListVersionsPageMergesMarkersAndVersionsInKeyOrder(t *testing.T) { |
| + f := &fakeVersionS3{} |
| + f.add("p/b.json", "b1", "b2") |
| + f.addMarker("p/a.json", "am", 0) // newest of a: a marker on top |
| + f.add("p/a.json", "a1") |
| + f.entries[len(f.entries)-1].age = 1 |
| + f.addMarker("p/c.json", "cm", 0) |
| + f.add("other/x.json", "x1") |
| + s := newVersionS3(t, f) |
| + got, nk, nv, err := s.ListVersionsPage(context.Background(), "p/", "", "", 0) |
| + if err != nil || nk != "" || nv != "" { |
| + t.Fatalf("err=%v markers=%q,%q", err, nk, nv) |
| + } |
| + want := []ObjectVersion{ |
| + {"p/a.json", "am", true}, {"p/a.json", "a1", false}, |
| + {"p/b.json", "b1", false}, {"p/b.json", "b2", false}, |
| + {"p/c.json", "cm", true}, |
| + } |
| + if fmt.Sprint(got) != fmt.Sprint(want) { |
| + t.Fatalf("got %v\nwant %v", got, want) |
| + } |
| +} |
| + |
| +func TestListVersionsPagesThroughMidKeyBoundaryKeepingBothMarkers(t *testing.T) { |
| + f := &fakeVersionS3{} |
| + f.add("p/a.json", "a1", "a2", "a3") |
| + f.addMarker("p/b.json", "bm", 0) |
| + f.add("p/b.json", "b1") |
| + f.entries[len(f.entries)-1].age = 1 |
| + s := newVersionS3(t, f) |
| + |
| + var all []ObjectVersion |
| + kmk, vmk := "", "" |
| + pages := 0 |
| + for { |
| + page, nk, nv, err := s.ListVersionsPage(context.Background(), "p/", kmk, vmk, 2) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + pages++ |
| + all = append(all, page...) |
| + if nk == "" { |
| + if nv != "" { |
| + t.Fatalf("version marker %q without key marker", nv) |
| + } |
| + break |
| + } |
| + if pages == 1 && (nk != "p/a.json" || nv != "a2") { |
| + t.Fatalf("first page markers = %q,%q; want the mid-key pair p/a.json,a2", nk, nv) |
| + } |
| + kmk, vmk = nk, nv |
| + } |
| + if pages != 3 || len(all) != 5 { |
| + t.Fatalf("pages=%d entries=%v", pages, all) |
| + } |
| + seen := map[ObjectVersion]bool{} |
| + for _, v := range all { |
| + if seen[v] { |
| + t.Fatalf("duplicate %v across pages", v) |
| + } |
| + seen[v] = true |
| + } |
| + if !sort.SliceIsSorted(all, func(i, j int) bool { return all[i].Key < all[j].Key }) { |
| + t.Fatalf("not sorted by key: %v", all) |
| + } |
| + // The markers reached S3 unchanged on the second request. |
| + if !strings.Contains(f.lists[1], "key-marker=p%2Fa.json") || !strings.Contains(f.lists[1], "version-id-marker=a2") { |
| + t.Fatalf("second list query %q lacks both markers", f.lists[1]) |
| + } |
| +} |
| + |
| +func TestListVersionsPageBoundsLimit(t *testing.T) { |
| + f := &fakeVersionS3{} |
| + f.add("p/a.json", "a1") |
| + s := newVersionS3(t, f) |
| + for _, lim := range []int{0, -5, 5000} { |
| + if _, _, _, err := s.ListVersionsPage(context.Background(), "p/", "", "", lim); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + for i, q := range f.lists { |
| + if !strings.Contains(q, "max-keys=1000") { |
| + t.Fatalf("request %d query %q: want max-keys=1000", i, q) |
| + } |
| + } |
| + if _, _, _, err := s.ListVersionsPage(context.Background(), "p/", "", "", 7); err != nil { |
| + t.Fatal(err) |
| + } |
| + if q := f.lists[len(f.lists)-1]; !strings.Contains(q, "max-keys=7") { |
| + t.Fatalf("query %q: want max-keys=7", q) |
| + } |
| +} |
| + |
| +func TestListVersionDirsFindsDeleteMarkerOnlyTreesAndCounts(t *testing.T) { |
| + f := &fakeVersionS3{} |
| + f.addMarker("apps/acct/shop/analytics/box1/days/2025-01-01.json", "m1", 0) // marker only |
| + f.add("apps/acct/shop/analytics/box2/days/2025-01-01.json", "v1", "v2") |
| + f.add("apps/acct/shop/analytics/box2/days/2025-01-02.json", "v3") |
| + f.add("apps/acct/shop/analytics/readme.json", "r1") |
| + s := newVersionS3(t, f) |
| + dirs, n, err := s.ListVersionDirsWithCount(context.Background(), "apps/acct/shop/analytics") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := "[apps/acct/shop/analytics/box1/ apps/acct/shop/analytics/box2/]" |
| + if fmt.Sprint(dirs) != want || n != 1 { |
| + t.Fatalf("dirs=%v requests=%d, want %s and 1", dirs, n, want) |
| + } |
| +} |
| + |
| +func TestListVersionDirsPagesAndDeduplicates(t *testing.T) { |
| + f := &fakeVersionS3{} |
| + // 1005 distinct directories overflow one 1000-entry page; two files in |
| + // the first directory check that a directory is reported once. |
| + for i := 0; i < 1005; i++ { |
| + f.add(fmt.Sprintf("q/d%04d/f.json", i), "v1", "v2") |
| + } |
| + f.add("q/d0000/g.json", "g1") |
| + s := newVersionS3(t, f) |
| + dirs, n, err := s.ListVersionDirsWithCount(context.Background(), "q") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(dirs) != 1005 || dirs[0] != "q/d0000/" || dirs[1004] != "q/d1004/" || n != 2 || n != len(f.lists) { |
| + t.Fatalf("dirs=%d requests=%d server saw %d", len(dirs), n, len(f.lists)) |
| + } |
| + if !sort.StringsAreSorted(dirs) { |
| + t.Fatal("dirs not sorted") |
| + } |
| +} |
| + |
| +func vers(n int) []ObjectVersion { |
| + out := make([]ObjectVersion, n) |
| + for i := range out { |
| + out[i] = ObjectVersion{Key: fmt.Sprintf("apps/a/x/analytics/box/days/d%04d.json", i/2), VersionID: fmt.Sprintf("v%d", i)} |
| + } |
| + return out |
| +} |
| + |
| +func TestDeleteVersionsSplitsAt1000AndDeduplicates(t *testing.T) { |
| + f := &fakeVersionS3{} |
| + s := newVersionS3(t, f) |
| + in := vers(1001) |
| + in = append(in, in[0], in[5]) // exact duplicates count once |
| + in = append(in, ObjectVersion{Key: in[0].Key, VersionID: "null", IsDeleteMarker: true}) |
| + if err := s.DeleteVersions(context.Background(), in); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(f.deletes) != 2 || len(f.deletes[0]) != 1000 || len(f.deletes[1]) != 2 { |
| + t.Fatalf("chunk sizes: %d chunks", len(f.deletes)) |
| + } |
| + for _, c := range f.deletes { |
| + for _, v := range c { |
| + if v.VersionID == "" { |
| + t.Fatalf("key-only delete sent: %v", v) |
| + } |
| + } |
| + } |
| + if err := s.DeleteVersions(context.Background(), nil); err != nil || len(f.deletes) != 2 { |
| + t.Fatalf("empty call sent a request or failed: %v", err) |
| + } |
| +} |
| + |
| +func TestDeleteVersionsRejectsInvalidIdentitiesWithoutSending(t *testing.T) { |
| + f := &fakeVersionS3{} |
| + s := newVersionS3(t, f) |
| + good := ObjectVersion{Key: "apps/a/x/analytics/b/days/2020-01-01.json", VersionID: "null"} // "null" is valid |
| + keyOnly := ObjectVersion{Key: "apps/a/x/analytics/b/days/2020-01-02.json"} |
| + noKey := ObjectVersion{VersionID: "v1", IsDeleteMarker: true} |
| + err := s.DeleteVersions(context.Background(), []ObjectVersion{keyOnly, good, noKey}) |
| + failed := FailedVersions(err) |
| + if len(failed) != 2 || failed[keyOnly] == nil || failed[noKey] == nil || failed[good] != nil { |
| + t.Fatalf("failed = %v", failed) |
| + } |
| + if len(f.deletes) != 1 || len(f.deletes[0]) != 1 || f.deletes[0][0] != good { |
| + t.Fatalf("sent %v, want only the good one", f.deletes) |
| + } |
| + // Only invalid: nothing is sent at all. |
| + f2 := &fakeVersionS3{} |
| + s2 := newVersionS3(t, f2) |
| + if err := s2.DeleteVersions(context.Background(), []ObjectVersion{keyOnly}); err == nil || len(f2.deletes) != 0 { |
| + t.Fatalf("err=%v sent=%v", err, f2.deletes) |
| + } |
| +} |
| + |
| +func TestDeleteVersionsPerVersionErrorsKeepExactIdentity(t *testing.T) { |
| + f := &fakeVersionS3{answer: func(_ int, ids []ObjectVersion) (int, string) { |
| + return 200, `<?xml version="1.0" encoding="UTF-8"?><DeleteResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> |
| +<Error><Key>` + ids[1].Key + `</Key><VersionId>` + ids[1].VersionID + `</VersionId><Code>InternalError</Code><Message>boom</Message></Error> |
| +<Error><Key>` + ids[3].Key + `</Key><VersionId>` + ids[3].VersionID + `</VersionId><Code>AccessDenied</Code><Message>nope</Message></Error></DeleteResult>` |
| + }} |
| + s := newVersionS3(t, f) |
| + in := vers(5) |
| + in[1].IsDeleteMarker = true |
| + err := s.DeleteVersions(context.Background(), in) |
| + failed := FailedVersions(err) |
| + if len(failed) != 2 || failed[in[1]] == nil || failed[in[3]] == nil { |
| + t.Fatalf("failed = %v (identities must match the input exactly, marker flag included)", failed) |
| + } |
| + if !errors.Is(err, ErrVersionAccessDenied) { |
| + t.Fatalf("per-object AccessDenied not detected: %v", err) |
| + } |
| + if !strings.Contains(err.Error(), "2 version(s)") { |
| + t.Fatalf("error text: %v", err) |
| + } |
| +} |
| + |
| +func TestVersionAccessDeniedSentinelRequestLevel(t *testing.T) { |
| + f := &fakeVersionS3{failAll: "AccessDenied"} |
| + s := newVersionS3(t, f) |
| + if _, _, _, err := s.ListVersionsPage(context.Background(), "p/", "", "", 10); !errors.Is(err, ErrVersionAccessDenied) { |
| + t.Fatalf("list: %v", err) |
| + } |
| + if _, _, err := s.ListVersionDirsWithCount(context.Background(), "p/"); !errors.Is(err, ErrVersionAccessDenied) { |
| + t.Fatalf("dirs: %v", err) |
| + } |
| + err := s.DeleteVersions(context.Background(), vers(3)) |
| + if !errors.Is(err, ErrVersionAccessDenied) || len(FailedVersions(err)) != 3 { |
| + t.Fatalf("delete: %v", err) |
| + } |
| + // Other failures are not permission failures. |
| + f2 := &fakeVersionS3{failAll: "SlowDown"} |
| + s2 := newVersionS3(t, f2) |
| + if _, _, _, err := s2.ListVersionsPage(context.Background(), "p/", "", "", 10); err == nil || errors.Is(err, ErrVersionAccessDenied) { |
| + t.Fatalf("SlowDown: %v", err) |
| + } |
| + if err := s2.DeleteVersions(context.Background(), vers(1)); err == nil || errors.Is(err, ErrVersionAccessDenied) { |
| + t.Fatalf("SlowDown delete: %v", err) |
| + } |
| +} |
| + |
| +func TestDeleteVersionsCancelledMarksEveryVersionUnattempted(t *testing.T) { |
| + f := &fakeVersionS3{} |
| + s := newVersionS3(t, f) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + cancel() |
| + err := s.DeleteVersions(ctx, vers(1500)) |
| + if len(FailedVersions(err)) != 1500 || !errors.Is(err, context.Canceled) { |
| + t.Fatalf("failed %d, err %v", len(FailedVersions(err)), err) |
| + } |
| + if len(f.deletes) != 0 { |
| + t.Fatalf("%d requests sent on a cancelled context", len(f.deletes)) |
| + } |
| +} |
| + |
| +func TestDeleteVersionsRequestFailureStillTriesNextChunk(t *testing.T) { |
| + f := &fakeVersionS3{answer: func(_ int, ids []ObjectVersion) (int, string) { |
| + if len(ids) == 1000 { // the first chunk, however often the SDK retries it |
| + return 500, `<Error><Code>InternalError</Code><Message>x</Message></Error>` |
| + } |
| + return 200, `<?xml version="1.0" encoding="UTF-8"?><DeleteResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"></DeleteResult>` |
| + }} |
| + s := newVersionS3(t, f) |
| + err := s.DeleteVersions(context.Background(), vers(1200)) |
| + if got := len(FailedVersions(err)); got != 1000 { |
| + t.Fatalf("failed %d, want the first chunk's 1000", got) |
| + } |
| +} |
| + |
| +func TestDeleteVersionsBumpsChangeScopeForSuccesses(t *testing.T) { |
| + f := &fakeVersionS3{} |
| + s := newVersionS3(t, f) |
| + s.EnableChangeIndex() |
| + scoped := []ObjectVersion{ |
| + {Key: "apps/a/x/app.json", VersionID: "v1"}, |
| + {Key: "apps/a/x/app.json", VersionID: "v2", IsDeleteMarker: true}, |
| + } |
| + if err := s.DeleteVersions(context.Background(), scoped); err != nil { |
| + t.Fatal(err) |
| + } |
| + if f.puts != 1 { |
| + t.Fatalf("change index puts = %d, want one bump for the one scope", f.puts) |
| + } |
| + // Analytics keys have no change scope: no bump. |
| + f.puts = 0 |
| + if err := s.DeleteVersions(context.Background(), vers(3)); err != nil || f.puts != 0 { |
| + t.Fatalf("analytics versions bumped %d: %v", f.puts, err) |
| + } |
| +} |
diff --git a/internal/release/prunelist_test.go b/internal/release/prunelist_test.go| new file mode 100644 |
| index 000000000..95b293466 |
| --- /dev/null |
| +++ b/internal/release/prunelist_test.go |
| @@ -0,0 +1,38 @@ |
| +package release |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "testing" |
| +) |
| + |
| +func TestPruneListDirsRequestCount(t *testing.T) { |
| + calls := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + calls++ |
| + if r.URL.Query().Get("delimiter") != "/" || r.URL.Query().Get("prefix") != "apps/" { |
| + t.Errorf("query: %s", r.URL.RawQuery) |
| + } |
| + if r.URL.Query().Get("continuation-token") == "" { |
| + fmt.Fprint(w, `<ListBucketResult><IsTruncated>true</IsTruncated><NextContinuationToken>next</NextContinuationToken><CommonPrefixes><Prefix>apps/bbb/</Prefix></CommonPrefixes></ListBucketResult>`) |
| + } else { |
| + fmt.Fprint(w, `<ListBucketResult><IsTruncated>false</IsTruncated><CommonPrefixes><Prefix>apps/aaa/</Prefix></CommonPrefixes></ListBucketResult>`) |
| + } |
| + })) |
| + defer srv.Close() |
| + rgwEnv(t, srv.URL) |
| + st, err := NewS3Store(context.Background(), "bucket") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + dirs, n, err := st.ListDirsWithCount(context.Background(), "apps/") |
| + if err != nil || n != 2 || calls != 2 || fmt.Sprint(dirs) != "[apps/aaa/ apps/bbb/]" { |
| + t.Fatalf("dirs=%v requests=%d actual=%d err=%v", dirs, n, calls, err) |
| + } |
| + dirs, err = st.ListDirs(context.Background(), "apps/") |
| + if err != nil || calls != 4 || fmt.Sprint(dirs) != "[apps/aaa/ apps/bbb/]" { |
| + t.Fatalf("legacy listing: %v %d %v", dirs, calls, err) |
| + } |
| +} |
diff --git a/internal/release/s3_minio_test.go b/internal/release/s3_minio_test.go| index 3fd07ca51..8ffd1dbc2 100644 |
| --- a/internal/release/s3_minio_test.go |
| +++ b/internal/release/s3_minio_test.go |
| @@ -1,8 +1,12 @@ |
| package release_test |
| import ( |
| + "context" |
| + "fmt" |
| "os" |
| + "strings" |
| "testing" |
| + "time" |
| "github.com/aws/aws-sdk-go-v2/aws" |
| "github.com/aws/aws-sdk-go-v2/credentials" |
| @@ -48,3 +52,167 @@ func minioEnv(t *testing.T, name string) string { |
| } |
| return v |
| } |
| + |
| +// TestS3StoreMinioVersions runs ListVersionsPage, ListVersionDirsWithCount |
| +// and DeleteVersions against a real VERSIONED bucket: every rewrite of a key |
| +// is a noncurrent version, a plain Delete adds a delete marker on top, and |
| +// only a delete naming the version ID removes data. It needs a versioned |
| +// bucket and a user allowed s3:ListBucketVersions, s3:PutObject, s3:DeleteObject |
| +// and s3:DeleteObjectVersion on it (MINIO_VERSIONED_BUCKET, _KEY, _SECRET), |
| +// so it skips unless those are set as well as CARLOS_MINIO_TEST=1. |
| +// .amadan/ci.d/30-minio-contract provisions that bucket and user, and requires |
| +// this test to PASS rather than silently accepting a skip. |
| +func TestS3StoreMinioVersions(t *testing.T) { |
| + if os.Getenv("CARLOS_MINIO_TEST") != "1" { |
| + t.Skip("set CARLOS_MINIO_TEST=1 and the MINIO_VERSIONED_* env vars to run the versioned S3Store test") |
| + } |
| + bucket := os.Getenv("MINIO_VERSIONED_BUCKET") |
| + if bucket == "" { |
| + t.Skip("MINIO_VERSIONED_BUCKET is not set: no versioned bucket provisioned for this run") |
| + } |
| + endpoint := minioEnv(t, "MINIO_ENDPOINT") |
| + key := minioEnv(t, "MINIO_VERSIONED_KEY") |
| + secret := minioEnv(t, "MINIO_VERSIONED_SECRET") |
| + client := awss3.New(awss3.Options{ |
| + Region: "us-east-1", |
| + Credentials: credentials.NewStaticCredentialsProvider(key, secret, ""), |
| + BaseEndpoint: aws.String(endpoint), |
| + UsePathStyle: true, |
| + RequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired, |
| + ResponseChecksumValidation: aws.ResponseChecksumValidationWhenRequired, |
| + }) |
| + s := &release.S3Store{Client: client, Bucket: bucket} |
| + ctx := context.Background() |
| + |
| + run := fmt.Sprintf("vtest-%d/", time.Now().UnixNano()) |
| + live := run + "apps/a/x/analytics/box1/days/2020-01-01.json" |
| + gone := run + "apps/a/x/analytics/box2/days/2020-01-02.json" // ends under a delete marker |
| + other := run + "apps/a/x/logs/keep.json" |
| + t.Cleanup(func() { // leave nothing behind, whatever the test did |
| + all := listAllVersions(t, s, run, 1000) |
| + _ = s.DeleteVersions(ctx, all) |
| + }) |
| + etags := map[string]string{} // create-only first, then replace-only |
| + for i := 0; i < 3; i++ { |
| + for _, k := range []string{live, gone, other} { |
| + etag, err := s.Put(ctx, k, []byte(fmt.Sprintf("v%d", i)), etags[k]) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + etags[k] = etag |
| + } |
| + } |
| + if err := s.Delete(ctx, gone); err != nil { // current version becomes a delete marker |
| + t.Fatal(err) |
| + } |
| + |
| + // Marker-only trees are invisible to ListDirs but found by version dirs. |
| + dirs, n, err := s.ListVersionDirsWithCount(ctx, run+"apps/a/x/analytics") |
| + if err != nil || n < 1 || strings.Join(dirs, ",") != run+"apps/a/x/analytics/box1/,"+run+"apps/a/x/analytics/box2/" { |
| + t.Fatalf("version dirs = %v (%d requests), err %v", dirs, n, err) |
| + } |
| + // Plain ListDirs on a marker-only tree differs by backend: AWS S3 hides |
| + // box2, MinIO still returns it. The prune does not rely on either answer |
| + // (it discovers trees by version dirs), so only the live box is required. |
| + live0, err := s.ListDirs(ctx, run+"apps/a/x/analytics") |
| + if err != nil || len(live0) < 1 || live0[0] != run+"apps/a/x/analytics/box1/" { |
| + t.Fatalf("plain ListDirs = %v, err %v: expected the live box first", live0, err) |
| + } |
| + |
| + // Page by 2 so a page boundary falls inside one key's versions. |
| + small := listAllVersions(t, s, run, 2) |
| + big := listAllVersions(t, s, run, 1000) |
| + if len(small) != 10 || len(big) != 10 { // 3+3+3 versions + 1 marker |
| + t.Fatalf("small=%d big=%d, want 10 each: %v", len(small), len(big), big) |
| + } |
| + seen := map[release.ObjectVersion]bool{} |
| + for _, v := range small { |
| + if seen[v] { |
| + t.Fatalf("version repeated across pages: %+v", v) |
| + } |
| + seen[v] = true |
| + } |
| + for _, v := range big { |
| + if !seen[v] { |
| + t.Fatalf("version missing from small pages: %+v", v) |
| + } |
| + } |
| + markers := 0 |
| + for _, v := range big { |
| + if v.IsDeleteMarker { |
| + markers++ |
| + } |
| + if v.VersionID == "" { |
| + t.Fatalf("empty version id: %v", v) |
| + } |
| + } |
| + if markers != 1 { |
| + t.Fatalf("delete markers = %d, want 1", markers) |
| + } |
| + |
| + // Delete every version under analytics/ only. |
| + var doomed []release.ObjectVersion |
| + for _, v := range big { |
| + if strings.Contains(v.Key, "/analytics/") { |
| + doomed = append(doomed, v) |
| + } |
| + } |
| + if len(doomed) != 7 { |
| + t.Fatalf("doomed = %d, want 7", len(doomed)) |
| + } |
| + // Delete each page before following its continuation, as the prune does. |
| + // The next request must still work when its marker version is now gone. |
| + km, vm := "", "" |
| + deleted := 0 |
| + for i := 0; i < 20; i++ { |
| + page, nk, nv, err := s.ListVersionsPage(ctx, run+"apps/a/x/analytics/", km, vm, 2) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.DeleteVersions(ctx, page); err != nil { |
| + t.Fatal(err) |
| + } |
| + deleted += len(page) |
| + if nk == "" { |
| + break |
| + } |
| + km, vm = nk, nv |
| + } |
| + if deleted != len(doomed) { |
| + t.Fatalf("deleted %d versions, want %d", deleted, len(doomed)) |
| + } |
| + after := listAllVersions(t, s, run, 1000) |
| + if len(after) != 3 { |
| + t.Fatalf("after delete %v, want only the three logs versions", after) |
| + } |
| + for _, v := range after { |
| + if !strings.Contains(v.Key, "/logs/") { |
| + t.Fatalf("an analytics version survived: %v", v) |
| + } |
| + } |
| + if err := s.DeleteVersions(ctx, doomed); err != nil { |
| + t.Fatalf("deleting already-gone versions should succeed: %v", err) |
| + } |
| + if err := s.DeleteVersions(ctx, []release.ObjectVersion{{Key: live}}); err == nil { |
| + t.Fatal("a key-only delete must be refused") |
| + } |
| +} |
| + |
| +func listAllVersions(t *testing.T, s *release.S3Store, prefix string, limit int) []release.ObjectVersion { |
| + t.Helper() |
| + var all []release.ObjectVersion |
| + km, vm := "", "" |
| + for i := 0; i < 1000; i++ { |
| + page, nk, nv, err := s.ListVersionsPage(context.Background(), prefix, km, vm, limit) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + all = append(all, page...) |
| + if nk == "" && nv == "" { |
| + return all |
| + } |
| + km, vm = nk, nv |
| + } |
| + t.Fatal("version listing did not finish") |
| + return nil |
| +} |
diff --git a/internal/release/store.go b/internal/release/store.go| index 3a23310bd..cb34f9ce7 100644 |
| --- a/internal/release/store.go |
| +++ b/internal/release/store.go |
| @@ -369,6 +369,13 @@ func OpenObject(ctx context.Context, s Store, key string) (io.ReadCloser, string |
| return io.NopCloser(bytes.NewReader(b)), etag, nil |
| } |
| +// CountedDirLister reports the number of delimiter LIST requests as well as |
| +// the directories. Retention jobs use it to account for paginated ListDirs. |
| +// Counts are API calls, excluding SDK transport retries. |
| +type CountedDirLister interface { |
| + ListDirsWithCount(ctx context.Context, prefix string) ([]string, int, error) |
| +} |
| + |
| // PageLister is the optional BOUNDED listing. List, ListMod and ListSizes all |
| // return every key under a prefix, which is right for a sweep that wants the |
| // whole picture and wrong for a queue drain that wants the oldest few. |
| @@ -1222,6 +1229,12 @@ func (s *S3Store) BucketShapedListDirs() bool { return true } |
| // prefixes rather than by the total object count beneath them. Objects AT |
| // this level come back in Contents, which this deliberately ignores. |
| func (s *S3Store) ListDirs(ctx context.Context, prefix string) ([]string, error) { |
| + dirs, _, err := s.ListDirsWithCount(ctx, prefix) |
| + return dirs, err |
| +} |
| + |
| +func (s *S3Store) ListDirsWithCount(ctx context.Context, prefix string) ([]string, int, error) { |
| + requests := 0 |
| if prefix != "" && !strings.HasSuffix(prefix, "/") { |
| prefix += "/" |
| } |
| @@ -1232,16 +1245,17 @@ func (s *S3Store) ListDirs(ctx context.Context, prefix string) ([]string, error) |
| Delimiter: aws.String("/"), |
| }) |
| for p.HasMorePages() { |
| + requests++ |
| page, err := p.NextPage(ctx) |
| if err != nil { |
| - return nil, err |
| + return nil, requests, err |
| } |
| for _, cp := range page.CommonPrefixes { |
| out = append(out, aws.ToString(cp.Prefix)) |
| } |
| } |
| sort.Strings(out) |
| - return out, nil |
| + return out, requests, nil |
| } |
| func (s *S3Store) Delete(ctx context.Context, key string) error { |