console: domain purchase engine (pay, zone, register, capture, attach)
Co-Authored-By: Astra (gpt-6-astra) via Codex <noreply@openai.com>
12 files changed,
+1,390
−12
cmd/console/main.go+1 −0internal/console/billingwebhook.go+12 −0internal/console/claim_invariant_fixtures_test.go+19 −0internal/console/claim_invariant_test.go+1 −2internal/console/claim_workers.go+1 −0internal/console/domainbuy.go+570 −0internal/console/domainbuy_test.go+722 −0internal/console/domainstore.go+47 −8internal/console/jobs.go+1 −0internal/console/jobs_test.go+3 −2internal/console/server.go+12 −0internal/console/testdata/claim-routes.txt+1 −0
diff --git a/cmd/console/main.go b/cmd/console/main.go| index e13fd40cd..774b7710d 100644 |
| --- a/cmd/console/main.go |
| +++ b/cmd/console/main.go |
| @@ -729,6 +729,7 @@ func serve() { |
| // The billing sync (internal/console/billingpass.go, plans 6a): returns |
| // at once with CARLOS_BILLING off. |
| go srv.RunClaimWorker(context.Background(), "StartBillingSyncPass") |
| + go srv.RunClaimWorker(context.Background(), "StartDomainPurchasePass") |
| // The plans deployment marker (internal/console/plansmarker.go): once per |
| // start. Writes nothing on a deployment that never set a catalog. |
| go srv.RunClaimWorker(context.Background(), "PublishPlansMarker") |
diff --git a/internal/console/billingwebhook.go b/internal/console/billingwebhook.go| index 38c460266..c16bfb6ff 100644 |
| --- a/internal/console/billingwebhook.go |
| +++ b/internal/console/billingwebhook.go |
| @@ -58,6 +58,18 @@ func (s *Server) handleBillingWebhook(w http.ResponseWriter, r *http.Request) { |
| case billing.EventSubscription: |
| subscription = ev.Object |
| case billing.EventCheckout: |
| + purchases, readErr := s.store.LiveDomainPurchases() |
| + if readErr != nil { |
| + w.WriteHeader(http.StatusServiceUnavailable) |
| + return |
| + } |
| + for _, p := range purchases { |
| + if p.CheckoutSession == ev.Object { |
| + s.nudgePurchase(p.ID) |
| + w.WriteHeader(http.StatusNoContent) |
| + return |
| + } |
| + } |
| // A session an intent records: observe the intent (plans 6b), which |
| // syncs a completed session's subscription. |
| observed, err := s.observeCheckoutEvent(s.billingClock(r.Context()), ev.Object, now) |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index eecb2fdd9..0fe393a0c 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -2294,6 +2294,25 @@ var claimFixtures = map[string]claimFixture{ |
| }, |
| do: claimWorker("StartDoorKeyResign"), |
| }}, |
| + "worker StartDomainPurchasePass": {door: &claimDoor{ |
| + apps: claimRefs("bab/kass"), |
| + setup: setupClaimPurchase, |
| + do: claimWorker("StartDomainPurchasePass"), |
| + check: func(t *testing.T, cx *claimCase, open bool) string { |
| + p, err := cx.st.DomainPurchase("dp_claim_purchase") |
| + if err != nil || p == nil { |
| + return fmt.Sprintf("purchase: %+v %v", p, err) |
| + } |
| + want := PurchaseAwaitingPayment |
| + if open { |
| + want = PurchaseExpired |
| + } |
| + if p.State != want { |
| + return fmt.Sprintf("purchase state %s, want %s", p.State, want) |
| + } |
| + return "" |
| + }, |
| + }}, |
| "worker StartExpiryPass": {door: &claimDoor{ |
| apps: claimRefs("bab/tmp-claim-expiry"), |
| setup: func(t *testing.T, cx *claimCase) { |
diff --git a/internal/console/claim_invariant_test.go b/internal/console/claim_invariant_test.go| index 53756fbad..378f4f5b1 100644 |
| --- a/internal/console/claim_invariant_test.go |
| +++ b/internal/console/claim_invariant_test.go |
| @@ -190,8 +190,7 @@ var claimWriterReasons = map[string]string{ |
| "the only code that puts versioned objects, and its own versioned callers are the db door's reads and the purge sweep's DeleteVersion", |
| "versioned/CopyVersion": "no console door calls it: only internal/park (archive copies) and internal/hostbox call CopyVersion, " + |
| "and the console imports neither", |
| - "sql/domain_purchases": "domain registration Plan 1 Task 6 adds the store before Tasks 7-8 add its engine and buy door; " + |
| - "no route or worker writes it yet; TestDomainPurchaseClaimGate pins refusal without a permit and success under the app permit; replace this reason with door coverage when the buy door is added", |
| + |
| "sql/owners": "legacy per-app grants, written only by cmd/console's operator grant and revoke verbs " + |
| "(Store.GrantAt and Revoke); enabled operator DBs are guarded too and refuse these unbound legacy grants; no route or worker writes them", |
| "sql/mail_counts": "retired by the senders migration: nothing writes it, the one-shot backfill only reads it, " + |
diff --git a/internal/console/claim_workers.go b/internal/console/claim_workers.go| index 70eeb965b..c2e099111 100644 |
| --- a/internal/console/claim_workers.go |
| +++ b/internal/console/claim_workers.go |
| @@ -16,6 +16,7 @@ func (s *Server) registerClaimWorkers() { |
| "StartExpiryPass": s.StartExpiryPass, |
| "StartPlanLimitsPass": s.StartPlanLimitsPass, |
| "StartPlanGracePass": s.StartPlanGracePass, |
| + "StartDomainPurchasePass": s.StartDomainPurchasePass, |
| "StartBillingSyncPass": s.StartBillingSyncPass, |
| "PublishPlansMarker": s.PublishPlansMarker, |
| "StartRunSweep": s.StartRunSweep, |
diff --git a/internal/console/domainbuy.go b/internal/console/domainbuy.go| new file mode 100644 |
| index 000000000..686347c3c |
| --- /dev/null |
| +++ b/internal/console/domainbuy.go |
| @@ -0,0 +1,570 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "net/http" |
| + "net/url" |
| + "os" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/alerting" |
| + "github.com/carlosframework/platform/internal/billing" |
| + "github.com/carlosframework/platform/internal/domainreg" |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/registrar" |
| + "github.com/carlosframework/platform/internal/zonehost" |
| +) |
| + |
| +func (s *Server) domainBuyReady() bool { |
| + return s.domainPurchaseReady() && s.cfg.DomainCatalog != nil && s.cfg.DomainCatalog.DailyCap > 0 |
| +} |
| + |
| +func (s *Server) domainPurchaseReady() bool { |
| + return s.cfg.Registrar != nil && s.cfg.ZoneHost != nil && s.cfg.Releases != nil && s.billing != nil && s.billing.ready.Load() |
| +} |
| + |
| +func domainBuyUnavailable() *doorRefusal { |
| + return &doorRefusal{http.StatusServiceUnavailable, "buying domains is unavailable right now"} |
| +} |
| + |
| +func (s *Server) quoteDomain(ctx context.Context, acct *Account, name string) (domainreg.Quote, *doorRefusal) { |
| + if !s.domainBuyReady() { |
| + return domainreg.Quote{}, &doorRefusal{Status: http.StatusNotFound} |
| + } |
| + if ref := s.customDomainRefusal(acct, name); ref != nil { |
| + return domainreg.Quote{}, ref |
| + } |
| + name, err := domainreg.Normalize(name) |
| + if err != nil { |
| + return domainreg.Quote{}, &doorRefusal{http.StatusUnprocessableEntity, err.Error()} |
| + } |
| + b, err := s.store.BillingAccount(acct.ID) |
| + if err != nil || b == nil || b.Currency == "" || b.Customer == "" { |
| + return domainreg.Quote{}, domainBuyUnavailable() |
| + } |
| + a, err := s.cfg.Registrar.Check(ctx, name) |
| + if err != nil { |
| + return domainreg.Quote{}, domainBuyUnavailable() |
| + } |
| + q, err := s.cfg.DomainCatalog.Quote(name, b.Currency, a) |
| + if err != nil { |
| + return domainreg.Quote{}, &doorRefusal{http.StatusUnprocessableEntity, err.Error()} |
| + } |
| + return q, nil |
| +} |
| + |
| +func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, name string, c registrar.Contact, principal string) (*DomainPurchase, string, *doorRefusal) { |
| + if !s.domainBuyReady() { |
| + return nil, "", &doorRefusal{Status: http.StatusNotFound} |
| + } |
| + name, err := domainreg.Normalize(name) |
| + if err != nil { |
| + return nil, "", &doorRefusal{http.StatusUnprocessableEntity, err.Error()} |
| + } |
| + if ref := s.customDomainRefusal(acct, name); ref != nil { |
| + return nil, "", ref |
| + } |
| + exists, err := s.store.HasAppIn(acct.ID, app) |
| + if err != nil { |
| + return nil, "", domainBuyUnavailable() |
| + } |
| + if !exists { |
| + return nil, "", &doorRefusal{Status: http.StatusNotFound} |
| + } |
| + if err := c.Validate(); err != nil { |
| + return nil, "", &doorRefusal{http.StatusUnprocessableEntity, err.Error()} |
| + } |
| + // Keep concurrent starts on this account inside the same daily-cap check. |
| + defer s.planLock(acct)() |
| + count, err := s.store.PurchasesToday(acct.ID, time.Now()) |
| + if err != nil { |
| + return nil, "", domainBuyUnavailable() |
| + } |
| + if count >= s.cfg.DomainCatalog.DailyCap { |
| + return nil, "", &doorRefusal{http.StatusTooManyRequests, domainPurchaseCopy.DailyCap} |
| + } |
| + for _, host := range []string{name, "www." + name} { |
| + if s.domainHostDenied(host, acct.Sqid) { |
| + return nil, "", claimRefusal(host, domains.ErrHostUnavailable) |
| + } |
| + if ref := s.heldElsewhere(ctx, host, acct.Sqid, app); ref != nil { |
| + if ref.Status == http.StatusConflict { |
| + s.purchaseAlert(ctx, acct, name, "", "claim held elsewhere") |
| + } |
| + return nil, "", ref |
| + } |
| + claim, err := domains.GetClaim(ctx, s.cfg.Releases, host) |
| + if err != nil && !errors.Is(err, os.ErrNotExist) { |
| + return nil, "", domainBuyUnavailable() |
| + } |
| + if err == nil && (claim.Account != acct.Sqid || claim.App != app) { |
| + s.purchaseAlert(ctx, acct, name, "", "claim held elsewhere") |
| + return nil, "", claimRefusal(host, domains.ErrHostUnavailable) |
| + } |
| + } |
| + q, ref := s.quoteDomain(ctx, acct, name) |
| + if ref != nil { |
| + return nil, "", ref |
| + } |
| + balance, err := s.cfg.Registrar.Balance(ctx) |
| + if err != nil { |
| + return nil, "", domainBuyUnavailable() |
| + } |
| + if balance.Currency != q.Cost.Currency || balance.Minor < q.Cost.Minor { |
| + s.purchaseAlert(ctx, acct, name, "", "registrar balance") |
| + return nil, "", domainBuyUnavailable() |
| + } |
| + now := time.Now().UTC() |
| + p := DomainPurchase{ID: newDomainPurchaseID(), AccountID: acct.ID, Domain: q.Domain, App: app, Currency: q.Currency, Amount: q.Price, |
| + State: PurchaseAwaitingPayment, CheckoutExpires: now.Add(time.Hour), CreatedAt: now, UpdatedAt: now, |
| + purchaseDetails: purchaseDetails{Principal: principal, Contact: c}} |
| + err = s.store.withAutoAppSQL(ctx, acct.ID, app, "sql.CreateDomainPurchase", func(st *Store) error { return st.CreateDomainPurchase(p) }) |
| + if errors.Is(err, ErrDomainPurchaseLive) { |
| + return nil, "", claimRefusal(name, domains.ErrHostUnavailable) |
| + } |
| + if err != nil { |
| + return nil, "", domainBuyUnavailable() |
| + } |
| + checkout, err := s.purchaseCheckout(ctx, &p) |
| + if err != nil { |
| + log.Printf("console: purchase %s: checkout: %v", p.ID, err) |
| + return &p, "", domainBuyUnavailable() |
| + } |
| + s.nudgePurchase(p.ID) |
| + return &p, checkout, nil |
| +} |
| + |
| +func (s *Server) movePurchase(ctx context.Context, p *DomainPurchase, to PurchaseState, set func(*DomainPurchase)) error { |
| + err := s.store.withAutoAppSQL(ctx, p.AccountID, p.App, "sql.AdvanceDomainPurchase", func(st *Store) error { return st.compareDomainPurchase(*p, to, set) }) |
| + if err != nil { |
| + return err |
| + } |
| + // Retain our own winning snapshot; a re-read could pick up another worker's step. |
| + if set != nil { |
| + set(p) |
| + } |
| + p.State = to |
| + p.Revision++ |
| + p.UpdatedAt = time.Now().UTC().Truncate(time.Second) |
| + return nil |
| +} |
| + |
| +func (s *Server) purchaseCheckout(ctx context.Context, p *DomainPurchase) (string, error) { |
| + acct, err := s.store.AccountByID(p.AccountID) |
| + if err != nil { |
| + return "", err |
| + } |
| + if acct == nil { |
| + return "", sql.ErrNoRows |
| + } |
| + var checkout string |
| + var stepErr error |
| + err = s.claimAppMutation(ctx, acct, p.App, "domain-checkout", func(pctx context.Context) error { |
| + checkout, stepErr = s.purchaseCheckoutStep(pctx, p) |
| + return nil |
| + }) |
| + return checkout, errors.Join(err, stepErr) |
| +} |
| + |
| +func (s *Server) purchaseCheckoutStep(ctx context.Context, p *DomainPurchase) (string, error) { |
| + provider := s.billing.cfg.Provider |
| + if p.CheckoutSession != "" { |
| + info, err := provider.PaymentCheckout(ctx, p.CheckoutSession) |
| + return info.URL, err |
| + } |
| + if !time.Now().Before(p.CheckoutExpires) { |
| + if p.CheckoutPrepared == nil { |
| + return "", s.movePurchase(ctx, p, PurchaseExpired, nil) |
| + } |
| + // A lost checkout response may have authorised money. Absence locally is not failure. |
| + return "", billing.ErrIndeterminate |
| + } |
| + if p.OwnerHandle == "" { |
| + _, existing, err := s.store.DomainContact(p.AccountID) |
| + if err != nil { |
| + return "", err |
| + } |
| + handle, err := s.cfg.Registrar.EnsureContact(ctx, existing, p.Contact) |
| + if err != nil { |
| + return "", err |
| + } |
| + if handle == "" { |
| + return "", registrar.ErrIndeterminate |
| + } |
| + if err := s.movePurchase(ctx, p, p.State, func(p *DomainPurchase) { p.OwnerHandle = handle }); err != nil { |
| + return "", err |
| + } |
| + } |
| + if p.CheckoutPrepared == nil { |
| + if err := s.store.SetDomainContact(p.AccountID, p.Contact, p.OwnerHandle); err != nil { |
| + return "", err |
| + } |
| + acct, err := s.store.AccountByID(p.AccountID) |
| + if err != nil { |
| + return "", err |
| + } |
| + if acct == nil { |
| + return "", sql.ErrNoRows |
| + } |
| + b, err := s.store.BillingAccount(p.AccountID) |
| + if err != nil { |
| + return "", err |
| + } |
| + if b == nil { |
| + return "", sql.ErrNoRows |
| + } |
| + back := s.cfg.Origin + appSettingsURL(acct.Sqid, p.App, "domains") |
| + prepared, err := provider.PreparePaymentCheckout(billing.PaymentCheckoutRequest{AccountSqid: acct.Sqid, Customer: b.Customer, Currency: p.Currency, Amount: p.Amount, |
| + Description: p.Domain, Reference: p.ID, SuccessURL: back, CancelURL: back, ExpiresAt: p.CheckoutExpires, Key: p.ID}) |
| + if err != nil { |
| + return "", err |
| + } |
| + if err := s.movePurchase(ctx, p, p.State, func(p *DomainPurchase) { p.CheckoutPrepared = &prepared }); err != nil { |
| + return "", err |
| + } |
| + } |
| + result, err := provider.Send(ctx, *p.CheckoutPrepared) |
| + if err != nil { |
| + return "", err |
| + } |
| + if result.Payment == nil || result.Payment.SessionID == "" { |
| + return "", billing.ErrIndeterminate |
| + } |
| + info := result.Payment |
| + if err := s.movePurchase(ctx, p, p.State, func(p *DomainPurchase) { p.CheckoutSession = info.SessionID }); err != nil { |
| + return "", err |
| + } |
| + return info.URL, nil |
| +} |
| + |
| +func (s *Server) advancePurchase(ctx context.Context, id string) error { |
| + if !s.domainPurchaseReady() { |
| + return nil |
| + } |
| + p, err := s.store.DomainPurchase(id) |
| + if err != nil || p == nil { |
| + return err |
| + } |
| + switch p.State { |
| + case PurchaseDone, PurchaseFailed, PurchaseExpired, PurchaseUnpaid: |
| + return nil |
| + } |
| + acct, err := s.store.AccountByID(p.AccountID) |
| + if err != nil { |
| + return err |
| + } |
| + if acct == nil { |
| + return sql.ErrNoRows |
| + } |
| + ctx, cancel := context.WithTimeout(ctx, 30*time.Second) |
| + defer cancel() |
| + var stepErr error |
| + if p.State == PurchaseCaptured { |
| + // Attach takes its own lifecycle registration, which requires an open app admission. |
| + stepErr = s.advancePurchaseStep(ctx, acct, p) |
| + } else { |
| + err = s.claimAppMutation(ctx, acct, p.App, "domain-purchase", func(pctx context.Context) error { |
| + // The purchase journal owns retries; this operation excludes app changes during the provider calls. |
| + stepErr = s.advancePurchaseStep(pctx, acct, p) |
| + return nil |
| + }) |
| + } |
| + if err != nil { |
| + return errors.Join(err, stepErr) |
| + } |
| + if errors.Is(stepErr, ErrPurchaseStateMoved) { |
| + return nil |
| + } |
| + return stepErr |
| +} |
| + |
| +func (s *Server) advancePurchaseStep(ctx context.Context, acct *Account, p *DomainPurchase) error { |
| + provider := s.billing.cfg.Provider |
| + switch p.State { |
| + case PurchaseAwaitingPayment: |
| + if p.CheckoutSession == "" { |
| + _, err := s.purchaseCheckout(ctx, p) |
| + return err |
| + } |
| + info, err := provider.PaymentCheckout(ctx, p.CheckoutSession) |
| + if err != nil { |
| + return err |
| + } |
| + if info.Authorised { |
| + if info.PaymentIntent == "" || info.Currency != p.Currency || info.Amount != p.Amount { |
| + return billing.ErrIndeterminate |
| + } |
| + return s.movePurchase(ctx, p, PurchaseAuthorised, func(p *DomainPurchase) { p.PaymentIntent = info.PaymentIntent }) |
| + } |
| + if info.Status == "expired" || (info.Status == "open" && !time.Now().Before(p.CheckoutExpires)) { |
| + return s.movePurchase(ctx, p, PurchaseExpired, nil) |
| + } |
| + return nil |
| + case PurchaseAuthorised: |
| + z, err := s.cfg.ZoneHost.CreateZone(ctx, p.Domain, p.ID) |
| + if err != nil { |
| + return err |
| + } |
| + source := s.cfg.DomainApex |
| + if source == nil { |
| + source = zonehost.StaticApex(s.dnsTargets(ctx).EdgeIPs) |
| + } |
| + apex, err := source.ApexTargets(ctx) |
| + if err != nil { |
| + return err |
| + } |
| + m := zonehost.ManagedSet{Apex: apex, WWW: true} |
| + if s.cfg.DomainProof { |
| + for _, host := range []string{p.Domain, "www." + p.Domain} { |
| + txt := s.domainChallenge(host, acct.Sqid) |
| + m.TXT = append(m.TXT, zonehost.TXT{Name: txt.Name, Value: txt.Value}) |
| + } |
| + } |
| + if err := s.cfg.ZoneHost.SetManaged(ctx, z, m); err != nil { |
| + return err |
| + } |
| + return s.movePurchase(ctx, p, PurchaseZoneReady, func(p *DomainPurchase) { p.ZoneID = z.ID }) |
| + case PurchaseZoneReady: |
| + if err := s.movePurchase(ctx, p, PurchaseRegistering, func(p *DomainPurchase) { p.Attempts = 1 }); err != nil { |
| + return err |
| + } |
| + return s.registerPurchase(ctx, p) |
| + case PurchaseRegistering: |
| + if p.Reason == "taken" || p.Reason == "refused" { |
| + return s.failPurchase(ctx, p) |
| + } |
| + registered, found, err := s.cfg.Registrar.Lookup(ctx, p.Domain) |
| + if err != nil { |
| + return err |
| + } |
| + if found { |
| + return s.registeredPurchase(ctx, p, registered) |
| + } |
| + if time.Since(p.UpdatedAt) < 10*time.Minute { |
| + return nil |
| + } |
| + if err := s.movePurchase(ctx, p, p.State, func(p *DomainPurchase) { |
| + if p.Attempts < 1 { |
| + p.Attempts = 1 |
| + } |
| + p.Attempts++ |
| + }); err != nil { |
| + return err |
| + } |
| + return s.registerPurchase(ctx, p) |
| + case PurchaseRegistered: |
| + prepared, err := provider.PrepareCapture(p.PaymentIntent, p.ID+":capture") |
| + if err != nil { |
| + return err |
| + } |
| + result, sendErr := provider.Send(ctx, prepared) |
| + if sendErr == nil && result.Payment != nil && result.Payment.IntentStatus == "succeeded" { |
| + return s.movePurchase(ctx, p, PurchaseCaptured, func(p *DomainPurchase) { p.Attempts = 0 }) |
| + } |
| + // The capture may already have landed, including before the key expired. |
| + info, err := provider.PaymentCheckout(ctx, p.CheckoutSession) |
| + if err != nil { |
| + return err |
| + } |
| + if info.PaymentIntent != p.PaymentIntent { |
| + return billing.ErrIndeterminate |
| + } |
| + if info.IntentStatus == "succeeded" { |
| + return s.movePurchase(ctx, p, PurchaseCaptured, func(p *DomainPurchase) { p.Attempts = 0 }) |
| + } |
| + if info.IntentStatus == "canceled" || info.IntentStatus == "requires_payment_method" || |
| + ((errors.Is(sendErr, billing.ErrRefused) || errors.Is(sendErr, billing.ErrPaymentFailed)) && info.IntentStatus == "requires_capture") { |
| + if _, err := s.store.db.Exec(`UPDATE domain_registrations SET auto_renew=0 WHERE domain=? AND account_id=? AND registrar_id=?`, p.Domain, p.AccountID, p.RegistrarID); err != nil { |
| + return err |
| + } |
| + if err := s.movePurchase(ctx, p, PurchaseUnpaid, nil); err != nil { |
| + return err |
| + } |
| + s.purchaseAlert(ctx, acct, p.Domain, p.ID, "unpaid") |
| + s.purchaseOwnerNotice(ctx, acct, p) |
| + return nil |
| + } |
| + if sendErr != nil { |
| + return sendErr |
| + } |
| + return billing.ErrIndeterminate |
| + case PurchaseCaptured: |
| + // Claim the attempt before either attach so concurrent calls do not lose its count. |
| + if err := s.movePurchase(ctx, p, p.State, func(p *DomainPurchase) { p.Attempts++ }); err != nil { |
| + return err |
| + } |
| + for _, host := range []string{p.Domain, "www." + p.Domain} { |
| + _, ref := s.attachDomain(ctx, acct, p.App, host, "", "", p.Principal) |
| + if ref != nil { |
| + if err := s.movePurchase(ctx, p, p.State, func(p *DomainPurchase) { p.Reason = ref.Msg }); err != nil { |
| + return err |
| + } |
| + if p.Attempts == 10 { |
| + s.purchaseAlert(ctx, acct, p.Domain, p.ID, p.Reason) |
| + } |
| + return nil |
| + } |
| + } |
| + return s.movePurchase(ctx, p, PurchaseDone, func(p *DomainPurchase) { p.Reason = "" }) |
| + } |
| + return nil |
| +} |
| + |
| +func (s *Server) registerPurchase(ctx context.Context, p *DomainPurchase) error { |
| + r, err := s.cfg.Registrar.Register(ctx, registrar.Registration{Domain: p.Domain, Years: 1, Nameservers: s.cfg.ZoneHost.Nameservers(), OwnerHandle: p.OwnerHandle, Key: p.ID}) |
| + if err == nil { |
| + return s.registeredPurchase(ctx, p, r) |
| + } |
| + if p.Attempts > 1 { |
| + // Any earlier attempt may have registered it. Even a definite refusal of this request cannot disprove that. |
| + r, found, readErr := s.cfg.Registrar.Lookup(ctx, p.Domain) |
| + if readErr != nil { |
| + return readErr |
| + } |
| + if found { |
| + return s.registeredPurchase(ctx, p, r) |
| + } |
| + return nil |
| + } |
| + reason := "" |
| + if errors.Is(err, registrar.ErrUnavailable) { |
| + reason = "taken" |
| + } else if errors.Is(err, registrar.ErrRefused) { |
| + reason = "refused" |
| + } |
| + if reason == "" { |
| + return nil |
| + } |
| + if err := s.movePurchase(ctx, p, p.State, func(p *DomainPurchase) { p.Reason = reason }); err != nil { |
| + return err |
| + } |
| + return s.failPurchase(ctx, p) |
| +} |
| + |
| +func (s *Server) registeredPurchase(ctx context.Context, p *DomainPurchase, r registrar.Registered) error { |
| + if r.Domain != p.Domain || r.RegistrarID == "" { |
| + return registrar.ErrIndeterminate |
| + } |
| + // Insert before advancing; after a crash the matching row is the same registration. |
| + err := s.store.AddDomainRegistration(DomainRegistration{Domain: p.Domain, AccountID: p.AccountID, RegistrarID: r.RegistrarID, ZoneID: p.ZoneID, Expires: r.Expires, AutoRenew: true}) |
| + if err != nil { |
| + var account int64 |
| + var registrarID, zoneID string |
| + readErr := s.store.db.QueryRow(`SELECT account_id,registrar_id,zone_id FROM domain_registrations WHERE domain=?`, p.Domain).Scan(&account, ®istrarID, &zoneID) |
| + if readErr != nil || account != p.AccountID || registrarID != r.RegistrarID || zoneID != p.ZoneID { |
| + return err |
| + } |
| + } |
| + return s.movePurchase(ctx, p, PurchaseRegistered, func(p *DomainPurchase) { p.RegistrarID = r.RegistrarID; p.Reason = "" }) |
| +} |
| + |
| +func (s *Server) failPurchase(ctx context.Context, p *DomainPurchase) error { |
| + provider := s.billing.cfg.Provider |
| + prepared, err := provider.PrepareCancelPayment(p.PaymentIntent, p.ID+":cancel") |
| + if err != nil { |
| + return err |
| + } |
| + result, err := provider.Send(ctx, prepared) |
| + if err != nil || result.Payment == nil || result.Payment.IntentStatus != "canceled" { |
| + info, readErr := provider.PaymentCheckout(ctx, p.CheckoutSession) |
| + if readErr != nil { |
| + return readErr |
| + } |
| + if info.PaymentIntent != p.PaymentIntent || info.IntentStatus != "canceled" { |
| + return billing.ErrIndeterminate |
| + } |
| + } |
| + if err := s.cfg.ZoneHost.DeleteZone(ctx, zonehost.Zone{ID: p.ZoneID, Domain: p.Domain}); err != nil { |
| + return err |
| + } |
| + return s.movePurchase(ctx, p, PurchaseFailed, nil) |
| +} |
| + |
| +func (s *Server) nudgePurchase(id string) { |
| + select { |
| + case s.purchaseWake <- struct{}{}: |
| + default: |
| + } |
| +} |
| + |
| +func (s *Server) StartDomainPurchasePass(ctx context.Context) { |
| + if s.cfg.Registrar == nil || s.cfg.ZoneHost == nil || s.billing == nil { |
| + return |
| + } |
| + ticker := time.NewTicker(15 * time.Second) |
| + defer ticker.Stop() |
| + for { |
| + if ctx.Err() != nil { |
| + return |
| + } |
| + _ = s.jobs.Run(ctx, "StartDomainPurchasePass", s.domainPurchasePass) |
| + select { |
| + case <-ctx.Done(): |
| + return |
| + case <-ticker.C: |
| + case <-s.purchaseWake: |
| + } |
| + } |
| +} |
| + |
| +func (s *Server) domainPurchasePass(ctx context.Context) error { |
| + purchases, err := s.store.LiveDomainPurchases() |
| + if err != nil { |
| + return err |
| + } |
| + var errs []error |
| + for _, p := range purchases { |
| + if ctx.Err() != nil { |
| + return ctx.Err() |
| + } |
| + if err := s.advancePurchase(ctx, p.ID); err != nil { |
| + errs = append(errs, fmt.Errorf("purchase %s: %w", p.ID, err)) |
| + } |
| + } |
| + return errors.Join(errs...) |
| +} |
| + |
| +var domainPurchaseCopy = struct { |
| + DailyCap, UnpaidSubject, UnpaidBody, OperatorSubject, OperatorBody string |
| +}{ |
| + DailyCap: "You have reached today's domain purchase limit. Try again tomorrow.", |
| + UnpaidSubject: "Payment for %s needs attention", |
| + UnpaidBody: "We registered %s for you, but could not collect the payment. Your domain is still yours. Auto-renew is off while payment is outstanding.\n\nReview your billing details:\n%s\n", |
| + OperatorSubject: "Domain purchase needs attention", |
| + OperatorBody: "Domain: %s\nPurchase: %s\nAccount: %s\nReason: %s\n", |
| +} |
| + |
| +var pageDomainPurchase = alerting.Page |
| + |
| +func (s *Server) purchaseAlert(ctx context.Context, acct *Account, domain, id, reason string) { |
| + log.Printf("console: domain purchase: account=%s domain=%s purchase=%s reason=%s", acct.Sqid, domain, id, reason) |
| + body := fmt.Sprintf(domainPurchaseCopy.OperatorBody, domain, id, acct.Sqid, reason) |
| + if err := pageDomainPurchase(ctx, alerting.LevelWarning, domainPurchaseCopy.OperatorSubject, body); err != nil { |
| + log.Printf("console: purchase %s: operator alert: %v", id, err) |
| + jobFailed(ctx, err) |
| + } |
| +} |
| + |
| +func (s *Server) purchaseOwnerNotice(ctx context.Context, acct *Account, p *DomainPurchase) { |
| + members, err := s.store.Members(acct.ID) |
| + if err != nil { |
| + log.Printf("console: purchase %s: owners: %v", p.ID, err) |
| + jobFailed(ctx, err) |
| + return |
| + } |
| + subject := fmt.Sprintf(domainPurchaseCopy.UnpaidSubject, p.Domain) |
| + body := fmt.Sprintf(domainPurchaseCopy.UnpaidBody, p.Domain, s.cfg.Origin+"/a/"+url.PathEscape(acct.Sqid)+"/billing") |
| + for _, member := range members { |
| + if member.Role != RoleOwner { |
| + continue |
| + } |
| + if _, err := s.deliver(ctx, member.Name, subject, body, 8*time.Second); err != nil { |
| + log.Printf("console: purchase %s: owner notice: %v", p.ID, err) |
| + jobFailed(ctx, err) |
| + } |
| + } |
| +} |
diff --git a/internal/console/domainbuy_test.go b/internal/console/domainbuy_test.go| new file mode 100644 |
| index 000000000..34cdce957 |
| --- /dev/null |
| +++ b/internal/console/domainbuy_test.go |
| @@ -0,0 +1,722 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "path/filepath" |
| + "reflect" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| + "github.com/carlosframework/platform/internal/domainreg" |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/registrar" |
| + "github.com/carlosframework/platform/internal/registrar/registrartest" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/zonehost" |
| + "github.com/carlosframework/platform/internal/zonehost/zonehosttest" |
| +) |
| + |
| +type purchaseFixture struct { |
| + *billingFixture |
| + reg *registrartest.Fake |
| + zone *zonehosttest.Fake |
| +} |
| + |
| +func newPurchaseFixture(t *testing.T) *purchaseFixture { |
| + t.Helper() |
| + previousPage := pageDomainPurchase |
| + pageDomainPurchase = func(context.Context, string, string, string) error { return nil } |
| + t.Cleanup(func() { pageDomainPurchase = previousPage }) |
| + reg := registrartest.New() |
| + reg.BalanceMoney = registrar.Money{Currency: "usd", Minor: 100000} |
| + reg.Available["shop.com"] = registrar.Availability{Available: true, Cost: registrar.Money{Currency: "usd", Minor: 900}} |
| + zone := zonehosttest.New("ns1.carloku.test", "ns2.carloku.test", "ns3.carloku.test", "ns4.carloku.test") |
| + bf := newBillingFixtureWith(t, consoleFixtureOptions{WithKey: true, Tweak: func(c *Config) { |
| + c.Registrar, c.ZoneHost = reg, zone |
| + c.EdgeIPs = []string{"192.0.2.10"} |
| + c.DomainCatalog = &domainreg.Catalog{Version: "test", DailyCap: 3, TLDs: map[string]domainreg.TLD{"com": {Register: map[string]int64{"usd": 1500}, MaxCost: registrar.Money{Currency: "usd", Minor: 1000}}}} |
| + }}) |
| + bf.put(bf.personalSub("sub_1", "active", nil)) |
| + if err := bf.srv.syncSubscription(context.Background(), "sub_1", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := bf.st.CreateAppIn(bf.acct.ID, "kass", "buyer@example.test", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + bf.srv.cfg.Registry = attachRegistry(t, registry.Route{Host: "app.example.test", Account: bf.acct.Sqid, App: "kass", Kind: "static", Status: "ready", Channel: "canary/live"}) |
| + bf.srv.billing.ready.Store(true) |
| + bf.srv.consoleMail = &fakeConsoleMail{ready: true} |
| + bf.srv.sendFederated = nil |
| + return &purchaseFixture{bf, reg, zone} |
| +} |
| + |
| +func purchaseContact() registrar.Contact { |
| + return registrar.Contact{FirstName: "Jane", LastName: "Buyer", Email: "buyer@example.test", PhoneCountryCode: "353", Phone: "871234567", Street: "Main Street", City: "Dublin", PostalCode: "D01 A123", Country: "IE"} |
| +} |
| +func (f *purchaseFixture) start(t *testing.T) *DomainPurchase { |
| + t.Helper() |
| + p, url, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test") |
| + if ref != nil || p == nil || url == "" { |
| + t.Fatalf("start: %+v %q %+v", p, url, ref) |
| + } |
| + return p |
| +} |
| +func (f *purchaseFixture) read(t *testing.T, id string) *DomainPurchase { |
| + t.Helper() |
| + p, err := f.st.DomainPurchase(id) |
| + if err != nil || p == nil { |
| + t.Fatalf("read: %+v %v", p, err) |
| + } |
| + return p |
| +} |
| +func (f *purchaseFixture) advance(t *testing.T, id string) *DomainPurchase { |
| + t.Helper() |
| + if err := f.srv.advancePurchase(context.Background(), id); err != nil { |
| + t.Fatal(err) |
| + } |
| + return f.read(t, id) |
| +} |
| +func (f *purchaseFixture) until(t *testing.T, id string, state PurchaseState) *DomainPurchase { |
| + t.Helper() |
| + for i := 0; i < 12; i++ { |
| + p := f.read(t, id) |
| + if p.State == state { |
| + return p |
| + } |
| + f.advance(t, id) |
| + } |
| + t.Fatalf("did not reach %s: %+v", state, f.read(t, id)) |
| + return nil |
| +} |
| +func (f *purchaseFixture) authorise(t *testing.T, p *DomainPurchase) { |
| + t.Helper() |
| + if _, err := f.fake.CompletePaymentCheckout(p.CheckoutSession); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.until(t, p.ID, PurchaseAuthorised) |
| +} |
| +func purchaseCalls(calls []string, prefix string) int { |
| + n := 0 |
| + for _, c := range calls { |
| + if strings.HasPrefix(c, prefix) { |
| + n++ |
| + } |
| + } |
| + return n |
| +} |
| +func (f *purchaseFixture) sent(kind string) int { |
| + n := 0 |
| + for _, p := range f.fake.Sent { |
| + if p.Kind == kind { |
| + n++ |
| + } |
| + } |
| + return n |
| +} |
| + |
| +func TestPurchaseHappyPathAttachesApexAndWWW(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + f.until(t, p.ID, PurchaseDone) |
| + r := f.reg.Domains[p.Domain] |
| + if !reflect.DeepEqual(r.Nameservers, f.zone.Nameservers()) || purchaseCalls(f.reg.Calls, "register:") != 1 || f.sent(billing.PreparedCapture) != 1 { |
| + t.Fatalf("register/capture: %+v %v %v", r, f.reg.Calls, f.fake.Sent) |
| + } |
| + for _, host := range []string{p.Domain, "www." + p.Domain} { |
| + c, err := domains.GetClaim(context.Background(), f.rel, host) |
| + if err != nil || c.App != "kass" || c.Account != f.acct.Sqid || c.CreatedBy != "buyer@example.test" { |
| + t.Fatalf("claim: %+v %v", c, err) |
| + } |
| + } |
| + var renew bool |
| + if err := f.st.db.QueryRow(`SELECT auto_renew FROM domain_registrations WHERE domain=?`, p.Domain).Scan(&renew); err != nil || !renew { |
| + t.Fatalf("registration: %v %v", renew, err) |
| + } |
| +} |
| +func TestPurchaseCheckoutExpiredLeavesNothing(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + p := f.start(t) |
| + if err := f.st.AdvanceDomainPurchase(p.ID, p.State, p.State, func(p *DomainPurchase) { p.CheckoutExpires = time.Now().Add(-time.Minute) }); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.until(t, p.ID, PurchaseExpired) |
| + if len(f.zone.Zones) != 0 || len(f.reg.Domains) != 0 || f.sent(billing.PreparedCapture) != 0 { |
| + t.Fatal("expired purchase made resources") |
| + } |
| +} |
| +func TestPurchaseNameTakenAfterPaymentCancelsAndCleansUp(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + f.reg.RegisterErr = registrar.ErrUnavailable |
| + p = f.until(t, p.ID, PurchaseFailed) |
| + if p.Reason != "taken" || len(f.zone.Zones) != 0 || f.sent(billing.PreparedCancelPayment) != 1 { |
| + t.Fatalf("cleanup: %+v %v", p, f.fake.Sent) |
| + } |
| +} |
| +func TestPurchaseIndeterminateRegisterNeverCancels(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + f.reg.RegisterErr = registrar.ErrIndeterminate |
| + f.until(t, p.ID, PurchaseRegistering) |
| + f.advance(t, p.ID) |
| + if f.sent(billing.PreparedCancelPayment) != 0 || purchaseCalls(f.reg.Calls, "register:") != 1 { |
| + t.Fatal("unknown outcome cancelled or retried early") |
| + } |
| + f.reg.Domains[p.Domain] = registrar.Registered{Domain: p.Domain, RegistrarID: "ours", Expires: time.Now().AddDate(1, 0, 0)} |
| + f.until(t, p.ID, PurchaseRegistered) |
| +} |
| +func TestPurchaseResumesAfterRestartWithoutDoubleRegister(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + f.reg.RegisterErr = registrar.ErrIndeterminate |
| + f.until(t, p.ID, PurchaseRegistering) |
| + f.reg.Domains[p.Domain] = registrar.Registered{Domain: p.Domain, RegistrarID: "ours", Expires: time.Now().AddDate(1, 0, 0)} |
| + srv, err := NewServer(f.srv.cfg, f.st) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.srv = srv |
| + f.srv.billing.ready.Store(true) |
| + f.until(t, p.ID, PurchaseDone) |
| + if purchaseCalls(f.reg.Calls, "register:") != 1 || f.sent(billing.PreparedCapture) != 1 { |
| + t.Fatal("restart duplicated money flow") |
| + } |
| +} |
| +func TestPurchaseCaptureFailsMarksUnpaidKeepsDomain(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + p = f.until(t, p.ID, PurchaseRegistered) |
| + cancel, err := f.fake.PrepareCancelPayment(p.PaymentIntent, "external-cancel") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = f.fake.Send(context.Background(), cancel); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.until(t, p.ID, PurchaseUnpaid) |
| + if len(f.reg.Domains) != 1 || len(f.zone.Zones) != 1 { |
| + t.Fatal("lost customer's domain") |
| + } |
| + var renew bool |
| + if err := f.st.db.QueryRow(`SELECT auto_renew FROM domain_registrations WHERE domain=?`, p.Domain).Scan(&renew); err != nil || renew { |
| + t.Fatalf("unpaid renew: %v %v", renew, err) |
| + } |
| +} |
| +func TestStartRefusesClaimHeldElsewhereBeforePayment(t *testing.T) { |
| + for _, host := range []string{"shop.com", "www.shop.com"} { |
| + t.Run(host, func(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + if _, _, err := domains.AttachClaim(context.Background(), f.rel, domains.Claim{Schema: 1, Host: host, Account: "foreign", App: "other", CreatedBy: "other"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer") |
| + want := claimRefusal(host, domains.ErrHostUnavailable) |
| + if ref == nil || *ref != *want || f.sent(billing.PreparedPaymentCheckout) != 0 { |
| + t.Fatalf("refusal: %+v", ref) |
| + } |
| + }) |
| + } |
| +} |
| +func TestStartRefusesFreePlan(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + if _, err := f.st.SetAccountPlan(f.acct.ID, "free", nil, 0, PlanSourceOperator, nil, "test", "operator", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer") |
| + if ref == nil || f.sent(billing.PreparedPaymentCheckout) != 0 { |
| + t.Fatal("free plan bought domain") |
| + } |
| +} |
| +func TestStartRefusesOverDailyCap(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + f.srv.cfg.DomainCatalog.DailyCap = 1 |
| + if err := f.st.CreateDomainPurchase(DomainPurchase{AccountID: f.acct.ID, Domain: "earlier.com", App: "kass", State: PurchaseExpired}); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer") |
| + if ref == nil || f.sent(billing.PreparedPaymentCheckout) != 0 { |
| + t.Fatal("cap bypassed") |
| + } |
| +} |
| +func TestStartRefusesLowRegistrarBalance(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + alerts := 0 |
| + pageDomainPurchase = func(context.Context, string, string, string) error { alerts++; return nil } |
| + f.reg.BalanceMoney.Minor = 1 |
| + _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer") |
| + if ref == nil || ref.Msg != "buying domains is unavailable right now" || f.sent(billing.PreparedPaymentCheckout) != 0 || alerts != 1 { |
| + t.Fatalf("balance refusal: %+v", ref) |
| + } |
| +} |
| + |
| +type purchaseApex []zonehost.ApexTarget |
| + |
| +func (a purchaseApex) ApexTargets(context.Context) ([]zonehost.ApexTarget, error) { return a, nil } |
| +func TestApexFromSteeringSource(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + want := purchaseApex{{IP: "192.0.2.2", Region: "eu-west-1", SetID: "ie", HealthCheckID: "hc-ie"}, {IP: "192.0.2.3", Region: "us-east-1", SetID: "us", HealthCheckID: "hc-us"}} |
| + f.srv.cfg.DomainApex = want |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + f.until(t, p.ID, PurchaseZoneReady) |
| + if !reflect.DeepEqual(f.zone.Managed[p.Domain].Apex, []zonehost.ApexTarget(want)) { |
| + t.Fatalf("apex: %+v", f.zone.Managed) |
| + } |
| +} |
| +func TestApexStaticWithoutSteering(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + f.until(t, p.ID, PurchaseZoneReady) |
| + if !reflect.DeepEqual(f.zone.Managed[p.Domain].Apex, []zonehost.ApexTarget{{IP: "192.0.2.10"}}) { |
| + t.Fatalf("apex: %+v", f.zone.Managed) |
| + } |
| +} |
| + |
| +type retryTakenRegistrar struct { |
| + *registrartest.Fake |
| + retries int |
| +} |
| + |
| +func (r *retryTakenRegistrar) Register(ctx context.Context, req registrar.Registration) (registrar.Registered, error) { |
| + r.retries++ |
| + if r.retries == 1 { |
| + return r.Fake.Register(ctx, req) |
| + } |
| + r.Domains[req.Domain] = registrar.Registered{Domain: req.Domain, RegistrarID: "ours", Expires: time.Now().AddDate(1, 0, 0)} |
| + return registrar.Registered{}, registrar.ErrUnavailable |
| +} |
| +func TestPurchaseRetryAfterIndeterminateTakenMeansOurs(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + r := &retryTakenRegistrar{Fake: f.reg} |
| + f.srv.cfg.Registrar = r |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + f.reg.RegisterErr = registrar.ErrIndeterminate |
| + f.until(t, p.ID, PurchaseRegistering) |
| + f.advance(t, p.ID) |
| + if _, err := f.st.db.Exec(`UPDATE domain_purchases SET updated_at=? WHERE id=?`, time.Now().Add(-11*time.Minute).Unix(), p.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.until(t, p.ID, PurchaseDone) |
| + if r.retries != 2 || f.sent(billing.PreparedCancelPayment) != 0 || f.sent(billing.PreparedCapture) != 1 { |
| + t.Fatalf("retry: %d %+v", r.retries, f.fake.Sent) |
| + } |
| +} |
| +func TestPurchaseCaptureRefusedAfterWindowRereadsSuccess(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + p = f.until(t, p.ID, PurchaseRegistered) |
| + prepared, err := f.fake.PrepareCapture(p.PaymentIntent, p.ID+":capture") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = f.fake.Send(context.Background(), prepared); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.fake.AdvanceProvider(25 * time.Hour) |
| + f.until(t, p.ID, PurchaseDone) |
| + info, err := f.fake.PaymentCheckout(context.Background(), p.CheckoutSession) |
| + if err != nil || info.IntentStatus != "succeeded" || f.sent(billing.PreparedCancelPayment) != 0 || f.sent(billing.PreparedCapture) != 2 { |
| + t.Fatalf("payment: %+v %v", info, err) |
| + } |
| +} |
| +func TestPurchaseEngineConcurrentAdvance(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + f.until(t, p.ID, PurchaseZoneReady) |
| + var wg sync.WaitGroup |
| + for i := 0; i < 12; i++ { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + if err := f.srv.advancePurchase(context.Background(), p.ID); err != nil && !errors.Is(err, ErrPurchaseStateMoved) { |
| + t.Error(err) |
| + } |
| + }() |
| + } |
| + wg.Wait() |
| + f.until(t, p.ID, PurchaseDone) |
| + if purchaseCalls(f.reg.Calls, "register:") != 1 { |
| + t.Fatalf("concurrent registration: %v", f.reg.Calls) |
| + } |
| +} |
| + |
| +func setupClaimPurchase(t *testing.T, cx *claimCase) { |
| + t.Helper() |
| + enableBilling(t, cx.srv) |
| + cx.srv.billing.ready.Store(true) |
| + cx.srv.cfg.Registrar = registrartest.New() |
| + cx.srv.cfg.ZoneHost = zonehosttest.New("ns1.carloku.test") |
| + cx.srv.cfg.DomainCatalog = &domainreg.Catalog{DailyCap: 3} |
| + appID := cx.appIDs[claimAppRef{Account: "bab", App: "kass"}] |
| + scope := []claimSQLScope{{AccountID: OpsAccountID, App: "kass", AppID: appID, Mode: claimModeEffect}} |
| + err := cx.st.withClaimSQL(gateCtx(t), scope, allowAllClaimSQL, func(st *Store) error { |
| + return st.CreateDomainPurchase(DomainPurchase{ID: "dp_claim_purchase", AccountID: OpsAccountID, App: "kass", Domain: "shop.com", State: PurchaseAwaitingPayment, CheckoutExpires: time.Now().Add(-time.Minute)}) |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func TestPurchaseCheckoutLostResponseReplaysStoredRequest(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + f.fake.LoseNextResponse = true |
| + p, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test") |
| + if p == nil || ref == nil { |
| + t.Fatalf("lost checkout response: %+v %+v", p, ref) |
| + } |
| + if p.CheckoutSession != "" { |
| + t.Fatal("unexpected session response") |
| + } |
| + p = f.advance(t, p.ID) |
| + if p.CheckoutSession == "" || f.sent(billing.PreparedPaymentCheckout) != 2 { |
| + t.Fatal("checkout did not recover") |
| + } |
| + sent := f.fake.Sent |
| + if !reflect.DeepEqual(sent[0], sent[1]) { |
| + t.Fatal("checkout replay changed request") |
| + } |
| + f.authorise(t, p) |
| + f.until(t, p.ID, PurchaseDone) |
| +} |
| + |
| +func TestPurchaseCheckoutUnknownPastExpiryStaysLive(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + f.fake.LoseNextResponse = true |
| + p, _, _ := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test") |
| + if p == nil { |
| + t.Fatal("missing pending purchase") |
| + } |
| + if err := f.st.AdvanceDomainPurchase(p.ID, p.State, p.State, func(p *DomainPurchase) { p.CheckoutExpires = time.Now().Add(-time.Minute) }); err != nil { |
| + t.Fatal(err) |
| + } |
| + err := f.srv.advancePurchase(context.Background(), p.ID) |
| + if !errors.Is(err, billing.ErrIndeterminate) || f.read(t, p.ID).State != PurchaseAwaitingPayment || f.sent(billing.PreparedCancelPayment) != 0 { |
| + t.Fatalf("unknown checkout: %v", err) |
| + } |
| +} |
| + |
| +func TestPurchaseCaptureAmbiguousNeverMarksUnpaid(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + p = f.until(t, p.ID, PurchaseRegistered) |
| + f.fake.FailBeforeDelivery = 1 |
| + err := f.srv.advancePurchase(context.Background(), p.ID) |
| + if !errors.Is(err, billing.ErrNoResponse) || f.read(t, p.ID).State != PurchaseRegistered { |
| + t.Fatalf("capture uncertainty: %v", err) |
| + } |
| + f.until(t, p.ID, PurchaseDone) |
| +} |
| + |
| +func TestPurchaseProofTXTForBothHosts(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + f.srv.cfg.DomainProof = true |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + f.until(t, p.ID, PurchaseZoneReady) |
| + got := f.zone.Managed[p.Domain] |
| + if !got.WWW || len(got.TXT) != 2 { |
| + t.Fatalf("managed records: %+v", got) |
| + } |
| + for i, host := range []string{p.Domain, "www." + p.Domain} { |
| + want := f.srv.domainChallenge(host, f.acct.Sqid) |
| + if got.TXT[i].Name != want.Name || got.TXT[i].Value != want.Value { |
| + t.Fatalf("proof: %+v", got.TXT) |
| + } |
| + } |
| +} |
| + |
| +func TestPurchaseWebhookNudgesOnlyStoredSession(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + p := f.start(t) |
| + select { |
| + case <-f.srv.purchaseWake: |
| + default: |
| + } |
| + if status := billingDeliver(t, f.consoleFixture, "checkout", p.CheckoutSession, false); status != 204 { |
| + t.Fatalf("webhook: %d", status) |
| + } |
| + select { |
| + case <-f.srv.purchaseWake: |
| + default: |
| + t.Fatal("purchase webhook did not nudge") |
| + } |
| + if p := f.read(t, p.ID); p.State != PurchaseAwaitingPayment { |
| + t.Fatal("webhook advanced without a payment read") |
| + } |
| + for i := 0; i < 1000; i++ { |
| + f.srv.nudgePurchase(p.ID) |
| + } |
| +} |
| + |
| +func TestPurchaseSameStateCASRejectsStaleRetry(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + f.reg.RegisterErr = registrar.ErrIndeterminate |
| + p = f.until(t, p.ID, PurchaseRegistering) |
| + stale := *p |
| + if err := f.srv.movePurchase(context.Background(), p, PurchaseRegistering, func(p *DomainPurchase) { p.Attempts++ }); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.srv.movePurchase(context.Background(), &stale, PurchaseRegistering, func(p *DomainPurchase) { p.Attempts++ }); !errors.Is(err, ErrPurchaseStateMoved) { |
| + t.Fatalf("stale retry won: %v", err) |
| + } |
| +} |
| + |
| +func TestPurchaseClaimGateBlocksZoneEffects(t *testing.T) { |
| + cx := newClaimCase(t) |
| + setupClaimPurchase(t, cx) |
| + p, err := cx.st.DomainPurchase("dp_claim_purchase") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := cx.srv.movePurchase(context.Background(), p, PurchaseAuthorised, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + zone := cx.srv.cfg.ZoneHost.(*zonehosttest.Fake) |
| + restore := cx.foreign(t, claimAppRef{Account: "bab", App: "kass"}) |
| + defer restore() |
| + if err := cx.srv.advancePurchase(context.Background(), p.ID); err == nil { |
| + t.Fatal("foreign operation allowed purchase") |
| + } |
| + if len(zone.Calls) != 0 { |
| + t.Fatalf("foreign operation reached zone host: %v", zone.Calls) |
| + } |
| +} |
| + |
| +func TestPurchaseClaimWorkerWritesThroughPermit(t *testing.T) { |
| + cx := newClaimCase(t) |
| + setupClaimPurchase(t, cx) |
| + if err := cx.srv.domainPurchasePass(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + p, err := cx.st.DomainPurchase("dp_claim_purchase") |
| + if err != nil || p.State != PurchaseExpired { |
| + t.Fatalf("pass: %+v %v", p, err) |
| + } |
| +} |
| + |
| +func TestPurchaseExistingFlowContinuesWithBuyDoorDisabled(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + f.srv.cfg.DomainCatalog = nil |
| + if f.srv.domainBuyReady() { |
| + t.Fatal("buy door is still ready") |
| + } |
| + f.until(t, p.ID, PurchaseDone) |
| +} |
| + |
| +func TestMigrateDomainPurchaseRetryDetails(t *testing.T) { |
| + path := filepath.Join(t.TempDir(), "purchase.db") |
| + st, err := Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + p := DomainPurchase{ID: "dp_upgrade", AccountID: 1, Domain: "shop.com", App: "shop", State: PurchaseAwaitingPayment} |
| + if err := st.CreateDomainPurchase(p); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, col := range []string{"details", "revision"} { |
| + if _, err := st.db.Exec("ALTER TABLE domain_purchases DROP COLUMN " + col); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := st.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + st, err = Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer st.Close() |
| + row, err := st.DomainPurchase(p.ID) |
| + if err != nil || row == nil || row.State != p.State || row.Revision != 0 || row.Principal != "" { |
| + t.Fatalf("upgrade: %+v %v", row, err) |
| + } |
| + if err := st.AdvanceDomainPurchase(p.ID, p.State, p.State, func(p *DomainPurchase) { |
| + p.Principal = "buyer@example.test" |
| + p.OwnerHandle = "contact-1" |
| + p.Contact = purchaseContact() |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + row, err = st.DomainPurchase(p.ID) |
| + if err != nil || row.Revision != 1 || row.Principal != "buyer@example.test" || row.OwnerHandle != "contact-1" || row.Contact != purchaseContact() { |
| + t.Fatalf("details: %+v %v", row, err) |
| + } |
| +} |
| + |
| +func TestPurchaseUnpaidNotifiesOwnersAndOperator(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + previousCopy, previousPage := domainPurchaseCopy, pageDomainPurchase |
| + t.Cleanup(func() { domainPurchaseCopy = previousCopy; pageDomainPurchase = previousPage }) |
| + domainPurchaseCopy.UnpaidSubject = "%s" |
| + domainPurchaseCopy.UnpaidBody = "%s %s" |
| + domainPurchaseCopy.OperatorSubject = "purchase" |
| + domainPurchaseCopy.OperatorBody = "%s %s %s %s" |
| + var alerts []string |
| + pageDomainPurchase = func(ctx context.Context, level, subject, body string) error { |
| + alerts = append(alerts, body) |
| + return nil |
| + } |
| + mail := &fakeConsoleMail{ready: true} |
| + f.srv.consoleMail = mail |
| + f.srv.sendFederated = nil |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + p = f.until(t, p.ID, PurchaseRegistered) |
| + cancel, err := f.fake.PrepareCancelPayment(p.PaymentIntent, "external-cancel") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = f.fake.Send(context.Background(), cancel); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.until(t, p.ID, PurchaseUnpaid) |
| + if len(alerts) != 1 || !strings.Contains(alerts[0], p.ID) || !strings.Contains(alerts[0], "unpaid") { |
| + t.Fatalf("alerts: %v", alerts) |
| + } |
| + if len(mail.sentCopy()) != 1 { |
| + t.Fatalf("owner emails: %v", mail.sentCopy()) |
| + } |
| +} |
| + |
| +func TestPurchaseRetryRefusalDoesNotDisproveEarlierRegistration(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + f.reg.RegisterErr = registrar.ErrIndeterminate |
| + f.until(t, p.ID, PurchaseRegistering) |
| + if _, err := f.st.db.Exec(`UPDATE domain_purchases SET updated_at=? WHERE id=?`, time.Now().Add(-11*time.Minute).Unix(), p.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.reg.RegisterErr = registrar.ErrRefused |
| + p = f.advance(t, p.ID) |
| + if p.State != PurchaseRegistering || p.Attempts != 2 || f.sent(billing.PreparedCancelPayment) != 0 { |
| + t.Fatalf("retry refused: %+v", p) |
| + } |
| +} |
| + |
| +func TestPurchaseAttachRefusalAlertsAfterTen(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + previousCopy, previousPage := domainPurchaseCopy, pageDomainPurchase |
| + t.Cleanup(func() { domainPurchaseCopy = previousCopy; pageDomainPurchase = previousPage }) |
| + domainPurchaseCopy.OperatorSubject = "purchase" |
| + domainPurchaseCopy.OperatorBody = "%s %s %s %s" |
| + calls := 0 |
| + pageDomainPurchase = func(context.Context, string, string, string) error { calls++; return nil } |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + f.until(t, p.ID, PurchaseCaptured) |
| + f.srv.cfg.Registry = "" |
| + for i := 0; i < 9; i++ { |
| + f.advance(t, p.ID) |
| + } |
| + if calls != 0 { |
| + t.Fatal("alerted before ten refusals") |
| + } |
| + p = f.advance(t, p.ID) |
| + if calls != 1 || p.State != PurchaseCaptured || p.Reason == "" || p.Attempts != 10 { |
| + t.Fatalf("attach refusal: %+v alerts=%d", p, calls) |
| + } |
| + if f.sent(billing.PreparedCancelPayment) != 0 { |
| + t.Fatal("cancelled captured payment") |
| + } |
| +} |
| + |
| +func TestPurchaseHappyPathWithClaimSQLGate(t *testing.T) { |
| + cx := newClaimCase(t) |
| + cx.claimedRoute(t) |
| + cx.settleRegistrations(t, "bab", "titogo") |
| + fake := enableBilling(t, cx.srv) |
| + acct, err := cx.st.AccountByID(OpsAccountID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := cx.st.SetBillingCustomer(acct.ID, "cus_1", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + bf := &billingFixture{consoleFixture: cx.consoleFixture, fake: fake, acct: acct} |
| + bf.put(bf.personalSub("sub_1", "active", nil)) |
| + if err := bf.srv.syncSubscription(context.Background(), "sub_1", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + reg := registrartest.New() |
| + reg.BalanceMoney = registrar.Money{Currency: "usd", Minor: 100000} |
| + reg.Available["shop.com"] = registrar.Availability{Available: true, Cost: registrar.Money{Currency: "usd", Minor: 900}} |
| + zone := zonehosttest.New("ns1.carloku.test", "ns2.carloku.test") |
| + cx.srv.cfg.Registrar = reg |
| + cx.srv.cfg.ZoneHost = zone |
| + cx.srv.cfg.EdgeIPs = []string{"192.0.2.10"} |
| + cx.srv.cfg.DomainCatalog = &domainreg.Catalog{Version: "test", DailyCap: 3, TLDs: map[string]domainreg.TLD{"com": {Register: map[string]int64{"usd": 1500}, MaxCost: registrar.Money{Currency: "usd", Minor: 1000}}}} |
| + cx.srv.billing.ready.Store(true) |
| + f := &purchaseFixture{billingFixture: bf, reg: reg, zone: zone} |
| + p, _, ref := f.srv.startDomainPurchase(context.Background(), acct, "titogo", "shop.com", purchaseContact(), "buyer@example.test") |
| + if ref != nil || p == nil { |
| + t.Fatalf("start: %+v", ref) |
| + } |
| + _, _, duplicate := f.srv.startDomainPurchase(context.Background(), acct, "titogo", "shop.com", purchaseContact(), "buyer@example.test") |
| + if duplicate == nil || *duplicate != *claimRefusal("shop.com", domains.ErrHostUnavailable) { |
| + t.Fatalf("duplicate: %+v", duplicate) |
| + } |
| + f.authorise(t, p) |
| + f.until(t, p.ID, PurchaseDone) |
| + for _, host := range []string{p.Domain, "www." + p.Domain} { |
| + claim, err := domains.GetClaim(context.Background(), cx.rel, host) |
| + if err != nil || claim.Account != acct.Sqid || claim.App != "titogo" { |
| + t.Fatalf("claim: %+v %v", claim, err) |
| + } |
| + } |
| +} |
| + |
| +func TestPurchaseCheckoutUsesQuoteAndExistingReturnPage(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + p := f.start(t) |
| + if len(f.fake.Sent) != 1 { |
| + t.Fatalf("checkout sends: %d", len(f.fake.Sent)) |
| + } |
| + var body struct { |
| + Request billing.PaymentCheckoutRequest |
| + } |
| + if err := json.Unmarshal(f.fake.Sent[0].Body, &body); err != nil { |
| + t.Fatal(err) |
| + } |
| + r := body.Request |
| + back := f.srv.cfg.Origin + appSettingsURL(f.acct.Sqid, "kass", "domains") |
| + if r.Reference != p.ID || r.Amount != 1500 || r.Currency != "usd" || r.Customer != "cus_1" || r.SuccessURL != back || r.CancelURL != back || r.Description != p.Domain || f.fake.Sent[0].Key != p.ID || r.ExpiresAt.Sub(p.CreatedAt) != time.Hour { |
| + t.Fatal("checkout did not preserve the quote, expiry, purchase identity and return page") |
| + } |
| +} |
| + |
| +func TestPurchaseResumesContactSnapshotBeforeCheckout(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + handle, err := f.reg.EnsureContact(context.Background(), "", purchaseContact()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + p := DomainPurchase{ID: newDomainPurchaseID(), AccountID: f.acct.ID, App: "kass", Domain: "shop.com", Currency: "usd", Amount: 1500, State: PurchaseAwaitingPayment, CheckoutExpires: time.Now().Add(time.Hour), purchaseDetails: purchaseDetails{Principal: "buyer@example.test", OwnerHandle: handle, Contact: purchaseContact()}} |
| + if err := f.st.CreateDomainPurchase(p); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.advance(t, p.ID) |
| + contact, stored, err := f.st.DomainContact(f.acct.ID) |
| + if err != nil || stored != handle || contact != purchaseContact() { |
| + t.Fatalf("contact snapshot was not saved: handle=%q error=%v", stored, err) |
| + } |
| +} |
diff --git a/internal/console/domainstore.go b/internal/console/domainstore.go| index e332e78c5..e2b1e3479 100644 |
| --- a/internal/console/domainstore.go |
| +++ b/internal/console/domainstore.go |
| @@ -6,8 +6,10 @@ import ( |
| "encoding/hex" |
| "encoding/json" |
| "errors" |
| + "strings" |
| "time" |
| + "github.com/carlosframework/platform/internal/billing" |
| "github.com/carlosframework/platform/internal/registrar" |
| ) |
| @@ -31,7 +33,16 @@ var ( |
| ErrPurchaseStateMoved = errors.New("console: domain purchase state moved") |
| ) |
| +type purchaseDetails struct { |
| + Principal string |
| + OwnerHandle string |
| + Contact registrar.Contact |
| + CheckoutPrepared *billing.Prepared |
| +} |
| + |
| type DomainPurchase struct { |
| + purchaseDetails |
| + Revision int64 |
| ID string |
| AccountID int64 |
| Domain, App, Currency string |
| @@ -91,7 +102,18 @@ CREATE TABLE IF NOT EXISTS domain_registrations ( |
| auto_renew INTEGER NOT NULL DEFAULT 1, |
| created_at INTEGER NOT NULL |
| );`) |
| - return err |
| + if err != nil { |
| + return err |
| + } |
| + for _, stmt := range []string{ |
| + `ALTER TABLE domain_purchases ADD COLUMN details TEXT NOT NULL DEFAULT '{}'`, |
| + `ALTER TABLE domain_purchases ADD COLUMN revision INTEGER NOT NULL DEFAULT 0`, |
| + } { |
| + if _, err := s.db.Exec(stmt); err != nil && !strings.Contains(err.Error(), "duplicate column") { |
| + return err |
| + } |
| + } |
| + return nil |
| } |
| func newDomainPurchaseID() string { |
| @@ -101,7 +123,7 @@ func newDomainPurchaseID() string { |
| } |
| const domainPurchaseColumns = `id, account_id, domain, app, currency, amount, state, reason, |
| - checkout_session, payment_intent, zone_id, registrar_id, attempts, checkout_expires, created_at, updated_at` |
| + checkout_session, payment_intent, zone_id, registrar_id, attempts, checkout_expires, created_at, updated_at, details, revision` |
| func (s *Store) CreateDomainPurchase(p DomainPurchase) error { |
| if p.ID == "" { |
| @@ -117,12 +139,16 @@ func (s *Store) CreateDomainPurchase(p DomainPurchase) error { |
| if p.UpdatedAt.IsZero() { |
| p.UpdatedAt = now |
| } |
| + details, err := json.Marshal(p.purchaseDetails) |
| + if err != nil { |
| + return err |
| + } |
| res, err := s.db.Exec(`INSERT INTO domain_purchases (`+domainPurchaseColumns+`) |
| - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) |
| + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) |
| ON CONFLICT(domain) WHERE `+liveDomainPurchaseSQL+` DO NOTHING`, |
| p.ID, p.AccountID, p.Domain, p.App, p.Currency, p.Amount, p.State, p.Reason, |
| p.CheckoutSession, p.PaymentIntent, p.ZoneID, p.RegistrarID, p.Attempts, |
| - domainUnix(p.CheckoutExpires), p.CreatedAt.Unix(), p.UpdatedAt.Unix()) |
| + domainUnix(p.CheckoutExpires), p.CreatedAt.Unix(), p.UpdatedAt.Unix(), string(details), p.Revision) |
| if err != nil { |
| return err |
| } |
| @@ -139,9 +165,13 @@ func (s *Store) CreateDomainPurchase(p DomainPurchase) error { |
| func scanDomainPurchase(sc interface{ Scan(...any) error }) (*DomainPurchase, error) { |
| var p DomainPurchase |
| var expires, created, updated int64 |
| + var details string |
| if err := sc.Scan(&p.ID, &p.AccountID, &p.Domain, &p.App, &p.Currency, &p.Amount, &p.State, &p.Reason, |
| &p.CheckoutSession, &p.PaymentIntent, &p.ZoneID, &p.RegistrarID, &p.Attempts, |
| - &expires, &created, &updated); err != nil { |
| + &expires, &created, &updated, &details, &p.Revision); err != nil { |
| + return nil, err |
| + } |
| + if err := json.Unmarshal([]byte(details), &p.purchaseDetails); err != nil { |
| return nil, err |
| } |
| if expires != 0 { |
| @@ -167,17 +197,26 @@ func (s *Store) AdvanceDomainPurchase(id string, from, to PurchaseState, set fun |
| if p == nil || p.State != from { |
| return ErrPurchaseStateMoved |
| } |
| + return s.compareDomainPurchase(*p, to, set) |
| +} |
| + |
| +func (s *Store) compareDomainPurchase(before DomainPurchase, to PurchaseState, set func(*DomainPurchase)) error { |
| + p := before |
| if set != nil { |
| - set(p) |
| + set(&p) |
| + } |
| + details, err := json.Marshal(p.purchaseDetails) |
| + if err != nil { |
| + return err |
| } |
| p.State, p.UpdatedAt = to, time.Now().UTC() |
| res, err := s.db.Exec(`UPDATE domain_purchases SET |
| account_id = ?, domain = ?, app = ?, currency = ?, amount = ?, state = ?, reason = ?, |
| checkout_session = ?, payment_intent = ?, zone_id = ?, registrar_id = ?, attempts = ?, |
| - checkout_expires = ?, created_at = ?, updated_at = ? WHERE id = ? AND state = ?`, |
| + checkout_expires = ?, created_at = ?, updated_at = ?, details = ?, revision = revision + 1 WHERE id = ? AND state = ? AND revision = ?`, |
| p.AccountID, p.Domain, p.App, p.Currency, p.Amount, p.State, p.Reason, |
| p.CheckoutSession, p.PaymentIntent, p.ZoneID, p.RegistrarID, p.Attempts, |
| - domainUnix(p.CheckoutExpires), p.CreatedAt.Unix(), p.UpdatedAt.Unix(), id, from) |
| + domainUnix(p.CheckoutExpires), p.CreatedAt.Unix(), p.UpdatedAt.Unix(), string(details), before.ID, before.State, before.Revision) |
| if err != nil { |
| return err |
| } |
diff --git a/internal/console/jobs.go b/internal/console/jobs.go| index b6b888e04..62e3ba599 100644 |
| --- a/internal/console/jobs.go |
| +++ b/internal/console/jobs.go |
| @@ -318,6 +318,7 @@ var jobLabels = map[string]string{ |
| "ReportApexSquats": "Apex names", |
| "LogPlacementDiscrepancies": "Placement", |
| "StartBillingSyncPass": "Billing sync", |
| + "StartDomainPurchasePass": "Domain purchases", |
| "StartLifetimesCutoverWatch": "Lifetime switch check", |
| "StartLifetimeRecoveryPass": "Lifetime recovery", |
| "StartIncarnationMigrationPass": "Incarnation migration", |
diff --git a/internal/console/jobs_test.go b/internal/console/jobs_test.go| index 1f3abe96a..dccb77e98 100644 |
| --- a/internal/console/jobs_test.go |
| +++ b/internal/console/jobs_test.go |
| @@ -50,8 +50,9 @@ var jobPassFuncs = map[string][]string{ |
| "StartPlanLimitsPass": {"planLimitsPass"}, |
| "StartPlanGracePass": {"planGracePass", "planGraceAccountLocked", "notifyPlanOwners", |
| "convergeStoreDeny", "dropStaleLapseItem", "resumeStaleCapPause"}, |
| - "StartBillingSyncPass": {"billingSyncPass", "billingDiscoveryPass", "discoverCustomer", "transitionAccountPlan"}, |
| - "PublishPlansMarker": {"publishPlansMarkerOnce"}, |
| + "StartDomainPurchasePass": {"domainPurchasePass", "advancePurchase", "advancePurchaseStep", "purchaseCheckout", "purchaseCheckoutStep", "registerPurchase", "registeredPurchase", "failPurchase", "purchaseAlert", "purchaseOwnerNotice"}, |
| + "StartBillingSyncPass": {"billingSyncPass", "billingDiscoveryPass", "discoverCustomer", "transitionAccountPlan"}, |
| + "PublishPlansMarker": {"publishPlansMarkerOnce"}, |
| "StartRunSweep": {"runSweepPass", "sweepExpireQueued", "sweepLostRun", "sweepTerminalRun", "sweepOrphanRuns", |
| "orphanCandidates", "orphanConfirmed", "orphanRunEnd", "auditRunEnd", |
| "finishPendingInteractiveEnds", "interactiveSweep", "clearDeadMarker", "sweepEndRow", "scanOrphanGrants", "sweepOrphanGrants"}, |
diff --git a/internal/console/server.go b/internal/console/server.go| index 02e93c86c..6e5c61b1a 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -41,6 +41,7 @@ import ( |
| "github.com/carlosframework/platform/internal/boxid" |
| "github.com/carlosframework/platform/internal/dbreads" |
| "github.com/carlosframework/platform/internal/dnsrec" |
| + "github.com/carlosframework/platform/internal/domainreg" |
| "github.com/carlosframework/platform/internal/domains" |
| "github.com/carlosframework/platform/internal/economics" |
| "github.com/carlosframework/platform/internal/edgesfile" |
| @@ -59,6 +60,7 @@ import ( |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/publicrelease" |
| "github.com/carlosframework/platform/internal/regionlabel" |
| + "github.com/carlosframework/platform/internal/registrar" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/status" |
| @@ -66,6 +68,7 @@ import ( |
| "github.com/carlosframework/platform/internal/telemetry" |
| "github.com/carlosframework/platform/internal/usage" |
| "github.com/carlosframework/platform/internal/version" |
| + "github.com/carlosframework/platform/internal/zonehost" |
| ) |
| //go:embed templates/*.html |
| @@ -524,6 +527,11 @@ const ( |
| // Config is everything the server reads its world through. |
| type Config struct { |
| + Registrar registrar.Registrar |
| + ZoneHost zonehost.Host |
| + DomainApex zonehost.ApexSource |
| + DomainCatalog *domainreg.Catalog |
| + |
| HostClaimOps *hostops.Controller |
| HostClaimRecovery *hostops.Recovery |
| ClaimMoveRecovery func(context.Context, *hostops.MoveRecoveryGrant) error |
| @@ -969,6 +977,8 @@ type Config struct { |
| // Server is the console's http.Handler. |
| type Server struct { |
| + purchaseWake chan struct{} |
| + |
| // manifestSeen is the sqids whose accounts/<sqid>/account.json this |
| // process has seen exist (read, or written by the backfill), so an app |
| // tab stops asking the bucket for it on every view. Keyed by sqid, value |
| @@ -1728,6 +1738,8 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| } |
| km.SetSigningKey(key) |
| s := &Server{ |
| + purchaseWake: make(chan struct{}, 1), |
| + |
| jobs: newJobRegistry(time.Now), |
| alertsNow: newAlertNow(), |
| cfg: cfg, |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index 8803e8889..fcd51fd2d 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -366,6 +366,7 @@ worker ReportApexSquats |
| worker StartAlertEngine |
| worker StartBillingSyncPass |
| worker StartClaimRecoveryPass |
| +worker StartDomainPurchasePass |
| worker StartDoorKeyResign |
| worker StartEconomicsPass |
| worker StartEgressReport |