rehearsal-4: broker rent face — Provider port (DO real, fake), rental ledger + TTL reaper, offer/rent/renew/release #647

Closed
opened 2026-08-22 04:12:32 +00:00 by ben · 2 comments
Owner

Arc: #183 rehearsal phase 4 — rented gateway (S4a). Spec: docs/superpowers/specs/2026-08-21-183-phase-4-rented-gateway-rehearsal-design.md. Plan: docs/superpowers/plans/2026-08-21-183-phase-4-rented-gateway-rehearsal.md (read its Global Constraints first — they apply to this task). This ticket's body is the plan's task verbatim. Phase-3 precedent: #515–#523.

Task 3: Broker rent face — Provider port, rental ledger + reaper, four routes

Files:

  • Create: broker/internal/broker/provider.go (Provider interface, FakeProvider)
  • Create: broker/internal/broker/provider_do.go (DigitalOcean over net/http, no SDK)
  • Create: broker/internal/broker/rentals.go (ledger + Rental + reaper)
  • Create: broker/internal/broker/rentals_store.go (RentalStore iface, memory + file)
  • Create: broker/internal/broker/rentals_test.go, provider_do_test.go, http_rent_test.go
  • Modify: broker/internal/broker/http.go (four routes), broker/internal/broker/broker.go (Version = "0.2.0-alpha-rentals")
  • Modify: broker/cmd/broker/main.go (wire provider + ledger + reaper from env)
  • Modify: broker/README.md (or create) — env vars + OpenAPI snippet
  • Modify: STATUS.md

Interfaces:

  • Produces:

    type Provider interface {
        Create(ctx context.Context, req CreateRequest) (Server, error) // CreateRequest{Name, Image, Size, Region string; SSHPubKey string; Tags []string}; Server{ID, IP string}
        Destroy(ctx context.Context, id string) error                  // idempotent: unknown id is nil
        Exists(ctx context.Context, id string) (bool, error)
    }
    type Rental struct { Host, ServerID, IP, Image, Provider, Region, Size string; Created, Expires time.Time; Released bool }
    type Offer struct { Preset, Provider, Region, Price, TTL, Terms, Note string } // Price always ""
    type Rentals struct{ ... } // NewRentals(store RentalStore, prov Provider, cfg RentalConfig) ; RentalConfig{Image func(ctx) (string, error); Size, Region string; TTL time.Duration; Now func() time.Time}
    func (r *Rentals) Offer() Offer
    func (r *Rentals) Rent(ctx, host, sshPubKey string) (Rental, error)   // ErrAlreadyRented if an unreleased rental exists for host
    func (r *Rentals) Renew(ctx, host string) (Rental, error)             // Expires = now+TTL
    func (r *Rentals) Release(ctx, host string) error                     // idempotent
    func (r *Rentals) Reap(ctx) (destroyed []string, err error)           // lapsed && !Released → Destroy + mark Released
    

    Wire: GET /v1/gateways/offer → Offer JSON; POST /v1/gateways/rent {host, ssh_pubkey} + Bearer claim secret → {host, ip, server_id, image, provider, region, size, expires} 200 / 401 / 403 / 409 already rented / 502 {error, stage:"provision"}; POST /v1/gateways/renew {host} + Bearer → {expires}; POST /v1/gateways/release {host} + Bearer → 204. Rehearsal fault hook: host whose slug starts with rehearsal-rentfail → after a REAL Create the broker Destroys it and returns 502 stage provision message rehearsal fault: provision failed after create (server destroyed).
    Env: IDSS_DO_TOKEN (file path IDSS_DO_TOKEN_FILE preferred), IDSS_GATEWAY_SIZE (default s-2vcpu-4gb), IDSS_GATEWAY_REGION (default syd1), IDSS_GATEWAY_TTL (default 24h), IDSS_GATEWAY_IMAGE_PREFIX (default idss-gateway-), ledger BROKER_STATE_DIR/rentals.json, reaper every 5 min.

  • Consumes: Registry.Authorize(slug, secret) (exists), issuer.slugOf(host) (exists), Task 2's snapshot naming (the DO provider resolves the image by listing snapshots with the prefix, newest created_at).

  • Step 1: Write rentals_test.go (failing) with a FakeProvider recording calls: TestRent_BindsToHostAndPersists, TestRent_TwiceRefusesAlreadyRented, TestRent_ProviderFailureAfterCreateDestroysAndLeavesNoRecord (fake fails on a post-create hook — simulate with FakeProvider.FailAfterCreate = true that returns Server + error), TestRentFailHostIsDestroyedAndErrors (rehearsal-rentfail.idss.nz), TestRenew_ExtendsExpires, TestRelease_DestroysAndIsIdempotent, TestReap_DestroysLapsedUnreleasedOnly, TestLedger_SurvivesRestart (memory store shared across two NewRentals).

  • Step 2: Run cd broker && go test ./internal/broker -run 'Rent|Renew|Release|Reap|Ledger' -v → FAIL (undefined).

  • Step 3: Implement provider.go, rentals_store.go, rentals.go per the Interfaces block (mutex + persist-on-every-change, mirroring Registry; Rent: Create with Name: "idss-gateway-"+slug+"-"+rand4hex, Tags: []string{"idss-gateway", "idss-rental"}; on any error after a non-empty Server.ID call Destroy then return &ProvisionError{Stage:"provision", Err: err}).

  • Step 4: Run tests → PASS.

  • Step 5: Write provider_do_test.go (failing) using httptest.Server: Create POSTs /v2/droplets with image (numeric id resolved from /v2/snapshots?resource_type=droplet, newest name matching prefix), ssh_keys = the fingerprint of a key it first POSTs to /v2/account/keys (or reuses when 422 duplicate), polls /v2/droplets/<id> until status=="active" and a public v4 IP is present; Destroy DELETEs and treats 404 as nil; Exists GETs.

  • Step 6: Implement provider_do.go (NewDigitalOcean(token string, client *http.Client, imagePrefix string)), run → PASS.

  • Step 7: Write http_rent_test.go (failing): offer 200 with price==""; rent without bearer 401, wrong bearer 403, unknown host 400, happy 200 body fields, second rent 409, rentfail host 502 with stage:"provision"; renew/release 204/200 shapes.

  • Step 8: Add the routes to http.go; NewHandler(issuer *Issuer, rentals *Rentals, log) (update the two existing callers/tests); run → PASS.

  • Step 9: Wire main.go: read env, resolveProvider (no token → UnconfiguredProvider{} that fails loud: "no IDSS_DO_TOKEN — renting is refused, never a fabricated server"), OpenRentals(store), go rentals.RunReaper(ctx, 5*time.Minute). README documents env + the four routes.

  • Step 10: Run cd broker && go vet ./... && go test ./... → PASS; gofmt -l . empty.

  • Step 11: Commit — git commit -m "rehearsal-4: broker rent face — Provider port (DO real, fake), rental ledger + TTL reaper, offer/rent/renew/release (ADR 0189) (#647)".

**Arc:** #183 rehearsal phase 4 — rented gateway (S4a). Spec: `docs/superpowers/specs/2026-08-21-183-phase-4-rented-gateway-rehearsal-design.md`. Plan: `docs/superpowers/plans/2026-08-21-183-phase-4-rented-gateway-rehearsal.md` (read its **Global Constraints** first — they apply to this task). This ticket's body is the plan's task verbatim. Phase-3 precedent: #515–#523. ### Task 3: Broker rent face — Provider port, rental ledger + reaper, four routes **Files:** - Create: `broker/internal/broker/provider.go` (Provider interface, `FakeProvider`) - Create: `broker/internal/broker/provider_do.go` (DigitalOcean over `net/http`, no SDK) - Create: `broker/internal/broker/rentals.go` (ledger + `Rental` + reaper) - Create: `broker/internal/broker/rentals_store.go` (`RentalStore` iface, memory + file) - Create: `broker/internal/broker/rentals_test.go`, `provider_do_test.go`, `http_rent_test.go` - Modify: `broker/internal/broker/http.go` (four routes), `broker/internal/broker/broker.go` (`Version = "0.2.0-alpha-rentals"`) - Modify: `broker/cmd/broker/main.go` (wire provider + ledger + reaper from env) - Modify: `broker/README.md` (or create) — env vars + OpenAPI snippet - Modify: `STATUS.md` **Interfaces:** - Produces: ```go type Provider interface { Create(ctx context.Context, req CreateRequest) (Server, error) // CreateRequest{Name, Image, Size, Region string; SSHPubKey string; Tags []string}; Server{ID, IP string} Destroy(ctx context.Context, id string) error // idempotent: unknown id is nil Exists(ctx context.Context, id string) (bool, error) } type Rental struct { Host, ServerID, IP, Image, Provider, Region, Size string; Created, Expires time.Time; Released bool } type Offer struct { Preset, Provider, Region, Price, TTL, Terms, Note string } // Price always "" type Rentals struct{ ... } // NewRentals(store RentalStore, prov Provider, cfg RentalConfig) ; RentalConfig{Image func(ctx) (string, error); Size, Region string; TTL time.Duration; Now func() time.Time} func (r *Rentals) Offer() Offer func (r *Rentals) Rent(ctx, host, sshPubKey string) (Rental, error) // ErrAlreadyRented if an unreleased rental exists for host func (r *Rentals) Renew(ctx, host string) (Rental, error) // Expires = now+TTL func (r *Rentals) Release(ctx, host string) error // idempotent func (r *Rentals) Reap(ctx) (destroyed []string, err error) // lapsed && !Released → Destroy + mark Released ``` Wire: `GET /v1/gateways/offer` → `Offer` JSON; `POST /v1/gateways/rent {host, ssh_pubkey}` + Bearer claim secret → `{host, ip, server_id, image, provider, region, size, expires}` 200 / 401 / 403 / 409 already rented / 502 `{error, stage:"provision"}`; `POST /v1/gateways/renew {host}` + Bearer → `{expires}`; `POST /v1/gateways/release {host}` + Bearer → 204. Rehearsal fault hook: `host` whose slug starts with `rehearsal-rentfail` → after a REAL `Create` the broker `Destroy`s it and returns 502 stage `provision` message `rehearsal fault: provision failed after create (server destroyed)`. Env: `IDSS_DO_TOKEN` (file path `IDSS_DO_TOKEN_FILE` preferred), `IDSS_GATEWAY_SIZE` (default `s-2vcpu-4gb`), `IDSS_GATEWAY_REGION` (default `syd1`), `IDSS_GATEWAY_TTL` (default `24h`), `IDSS_GATEWAY_IMAGE_PREFIX` (default `idss-gateway-`), ledger `BROKER_STATE_DIR/rentals.json`, reaper every 5 min. - Consumes: `Registry.Authorize(slug, secret)` (exists), `issuer.slugOf(host)` (exists), Task 2's snapshot naming (the DO provider resolves the image by listing snapshots with the prefix, newest `created_at`). - [ ] **Step 1: Write `rentals_test.go`** (failing) with a `FakeProvider` recording calls: `TestRent_BindsToHostAndPersists`, `TestRent_TwiceRefusesAlreadyRented`, `TestRent_ProviderFailureAfterCreateDestroysAndLeavesNoRecord` (fake fails on a post-create hook — simulate with `FakeProvider.FailAfterCreate = true` that returns `Server` + error), `TestRentFailHostIsDestroyedAndErrors` (`rehearsal-rentfail.idss.nz`), `TestRenew_ExtendsExpires`, `TestRelease_DestroysAndIsIdempotent`, `TestReap_DestroysLapsedUnreleasedOnly`, `TestLedger_SurvivesRestart` (memory store shared across two `NewRentals`). - [ ] **Step 2: Run** `cd broker && go test ./internal/broker -run 'Rent|Renew|Release|Reap|Ledger' -v` → FAIL (undefined). - [ ] **Step 3: Implement `provider.go`, `rentals_store.go`, `rentals.go`** per the Interfaces block (mutex + persist-on-every-change, mirroring `Registry`; `Rent`: `Create` with `Name: "idss-gateway-"+slug+"-"+rand4hex`, `Tags: []string{"idss-gateway", "idss-rental"}`; on any error after a non-empty `Server.ID` call `Destroy` then return `&ProvisionError{Stage:"provision", Err: err}`). - [ ] **Step 4: Run tests** → PASS. - [ ] **Step 5: Write `provider_do_test.go`** (failing) using `httptest.Server`: `Create` POSTs `/v2/droplets` with `image` (numeric id resolved from `/v2/snapshots?resource_type=droplet`, newest name matching prefix), `ssh_keys` = the fingerprint of a key it first POSTs to `/v2/account/keys` (or reuses when 422 duplicate), polls `/v2/droplets/<id>` until `status=="active"` and a public v4 IP is present; `Destroy` DELETEs and treats 404 as nil; `Exists` GETs. - [ ] **Step 6: Implement `provider_do.go`** (`NewDigitalOcean(token string, client *http.Client, imagePrefix string)`), run → PASS. - [ ] **Step 7: Write `http_rent_test.go`** (failing): offer 200 with `price==""`; rent without bearer 401, wrong bearer 403, unknown host 400, happy 200 body fields, second rent 409, rentfail host 502 with `stage:"provision"`; renew/release 204/200 shapes. - [ ] **Step 8: Add the routes to `http.go`**; `NewHandler(issuer *Issuer, rentals *Rentals, log)` (update the two existing callers/tests); run → PASS. - [ ] **Step 9: Wire `main.go`**: read env, `resolveProvider` (no token → `UnconfiguredProvider{}` that fails loud: "no IDSS_DO_TOKEN — renting is refused, never a fabricated server"), `OpenRentals(store)`, `go rentals.RunReaper(ctx, 5*time.Minute)`. README documents env + the four routes. - [ ] **Step 10: Run** `cd broker && go vet ./... && go test ./...` → PASS; `gofmt -l .` empty. - [ ] **Step 11: Commit** — `git commit -m "rehearsal-4: broker rent face — Provider port (DO real, fake), rental ledger + TTL reaper, offer/rent/renew/release (ADR 0189) (#647)"`.

swarm-claim host=matou-dev-server-01 run=8627
(automated multi-host claim — lowest live claim id works this ticket)

swarm-claim host=matou-dev-server-01 run=8627 (automated multi-host claim — lowest live claim id works this ticket)

close-report for #647 — status success

✅ close-report gates passed — every claim verified against main; closing.

envelope
{
  "issue": 647,
  "status": "success",
  "commits": [
    "8585a9546dd3b953f25f7348f6aabef8e971ec6f"
  ],
  "changed_files": [
    "STATUS.md",
    "broker/README.md",
    "broker/cmd/broker/main.go",
    "broker/internal/broker/broker.go",
    "broker/internal/broker/http.go",
    "broker/internal/broker/http_rent_test.go",
    "broker/internal/broker/http_test.go",
    "broker/internal/broker/provider.go",
    "broker/internal/broker/provider_do.go",
    "broker/internal/broker/provider_do_test.go",
    "broker/internal/broker/rentals.go",
    "broker/internal/broker/rentals_store.go",
    "broker/internal/broker/rentals_test.go"
  ],
  "tests": [
    {
      "command": "cd broker && go vet ./...",
      "exit_code": 0
    },
    {
      "command": "cd broker && go test ./...",
      "exit_code": 0
    },
    {
      "command": "cd broker && gofmt -l .",
      "exit_code": 0
    },
    {
      "command": "cd broker && golangci-lint run ./...",
      "exit_code": 0
    }
  ],
  "criteria": {
    "Provider port (DO real, fake, unconfigured) built to the interface": "broker/internal/broker/provider.go + provider_do.go; TestDO_* in provider_do_test.go prove snapshot resolution, key registration, droplet create+poll, 404-as-gone, exists",
    "Rental ledger + Rent/Renew/Release/Reap with no-half-rented (ADR 0047)": "broker/internal/broker/rentals.go + rentals_store.go; TestRent_*/TestRenew_*/TestRelease_*/TestReap_*/TestLedger_SurvivesRestart green",
    "Rehearsal fault hook (rehearsal-rentfail -> real create, destroy, 502 provision)": "rentals.go errRehearsalFault; TestRentFailHostIsDestroyedAndErrors + TestGateway_RentFailHostIs502WithStage",
    "Four HTTP routes offer/rent/renew/release with 200/401/403/409/502 shapes, price always empty": "broker/internal/broker/http.go registerGatewayRoutes; TestGateway_* in http_rent_test.go",
    "main.go wires provider+ledger+reaper from env; UnconfiguredProvider fails loud": "broker/cmd/broker/main.go resolveRentals/resolveProvider; broker README documents env + routes",
    "Version bumped to 0.2.0-alpha-rentals": "broker/internal/broker/broker.go",
    "go vet + go test green, gofmt clean": "tests[] all exit 0; pre-push nix go-ci gate ran the full Go suite green"
  },
  "summary": "Broker grows its rented-gateway rent face: Provider port (DO over net/http, fake, unconfigured), durable TTL-reaped rental ledger, and four claim-secret-gated HTTP verbs, all TDD-covered.",
  "blockers": []
}
**close-report** for #647 — status `success` :white_check_mark: **close-report gates passed** — every claim verified against main; closing. <details><summary>envelope</summary> ```json { "issue": 647, "status": "success", "commits": [ "8585a9546dd3b953f25f7348f6aabef8e971ec6f" ], "changed_files": [ "STATUS.md", "broker/README.md", "broker/cmd/broker/main.go", "broker/internal/broker/broker.go", "broker/internal/broker/http.go", "broker/internal/broker/http_rent_test.go", "broker/internal/broker/http_test.go", "broker/internal/broker/provider.go", "broker/internal/broker/provider_do.go", "broker/internal/broker/provider_do_test.go", "broker/internal/broker/rentals.go", "broker/internal/broker/rentals_store.go", "broker/internal/broker/rentals_test.go" ], "tests": [ { "command": "cd broker && go vet ./...", "exit_code": 0 }, { "command": "cd broker && go test ./...", "exit_code": 0 }, { "command": "cd broker && gofmt -l .", "exit_code": 0 }, { "command": "cd broker && golangci-lint run ./...", "exit_code": 0 } ], "criteria": { "Provider port (DO real, fake, unconfigured) built to the interface": "broker/internal/broker/provider.go + provider_do.go; TestDO_* in provider_do_test.go prove snapshot resolution, key registration, droplet create+poll, 404-as-gone, exists", "Rental ledger + Rent/Renew/Release/Reap with no-half-rented (ADR 0047)": "broker/internal/broker/rentals.go + rentals_store.go; TestRent_*/TestRenew_*/TestRelease_*/TestReap_*/TestLedger_SurvivesRestart green", "Rehearsal fault hook (rehearsal-rentfail -> real create, destroy, 502 provision)": "rentals.go errRehearsalFault; TestRentFailHostIsDestroyedAndErrors + TestGateway_RentFailHostIs502WithStage", "Four HTTP routes offer/rent/renew/release with 200/401/403/409/502 shapes, price always empty": "broker/internal/broker/http.go registerGatewayRoutes; TestGateway_* in http_rent_test.go", "main.go wires provider+ledger+reaper from env; UnconfiguredProvider fails loud": "broker/cmd/broker/main.go resolveRentals/resolveProvider; broker README documents env + routes", "Version bumped to 0.2.0-alpha-rentals": "broker/internal/broker/broker.go", "go vet + go test green, gofmt clean": "tests[] all exit 0; pre-push nix go-ci gate ran the full Go suite green" }, "summary": "Broker grows its rented-gateway rent face: Provider port (DO over net/http, fake, unconfigured), durable TTL-reaped rental ledger, and four claim-secret-gated HTTP verbs, all TDD-covered.", "blockers": [] } ``` </details>
Sign in to join this conversation.
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
Matou/idss#647
No description provided.