diff --git a/AGENTS.md b/AGENTS.md index f0bb22a81..b844f2882 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -43,6 +43,7 @@ Other CI-touching rules: - the frontend trees (`admin/`, `web/`, `site/`, `qa/`) each have their own CI jobs; run `pnpm typecheck` in any tree you touched and `pnpm lint` when the rules are non-trivial - never push without first re-running the relevant `*build*` / `*typecheck*` / `*lint*` step on the affected tree - a `make lint` (or `gofmt -l`) failure is always a real CI failure; do not push hoping it will pass +- keep CI fast and minimal. A feature's tests run inside the existing jobs; do not add a job, a matrix entry, a step or a named live-test list for it. Touch `.github/` only to fix CI itself Migrations are numbered against `main`, not against your branch: diff --git a/docs/content/docs/api/error-codes.mdx b/docs/content/docs/api/error-codes.mdx index 936c6d3f5..ae2128a60 100644 --- a/docs/content/docs/api/error-codes.mdx +++ b/docs/content/docs/api/error-codes.mdx @@ -820,6 +820,7 @@ The [Buy mailboxes](/guides/buy-mailboxes/) routes (`/store/*`, see [domains and | `price_changed` | 409 | `POST /store/orders` when the total, priced again for an expired quote, differs from `expected_due_now_micros`. Nothing is charged. `details.quote` is a fresh quote at the current prices: show its total and, once the person confirms, order again with its `id` | | `payment_processing` | 409 | The card payment for the shortfall has not settled yet. Nothing was ordered; try again in a minute | | `charge_in_progress` | 409 | Another payment for this workspace is still going through, or `POST /store/mailboxes/:id/resume` while the mailbox's own monthly payment is. Try again in a minute | +| `store_purchases_active` | 409 | Deleting a workspace, or an account that owns one, while it still has purchased mailboxes that are not cancelled, purchased domains set to renew, or an order in progress. Cancel them first | | `domain_unavailable` | 409 | The domain was registered by someone else after the search, or cannot be registered. Pick another. From `POST /store/domains/connect`, the body carries a top-level `reason` when one is known: `already_added` (the domain is already in this workspace), `registered` (another workspace bought it here) or `connected_elsewhere` (another workspace is connecting it) | | `domain_registered_elsewhere` | 409 | Renewing, transferring out or changing `auto_renew` on a domain the workspace connected. It is registered elsewhere, so renew or transfer it at its registrar | | `domain_registered_here` | 409 | `DELETE /store/domains/:id` on a domain bought here. A purchased domain leaves by `POST /store/domains/:id/transfer-out` | diff --git a/internal/app/dangerzone/service.go b/internal/app/dangerzone/service.go index dcb75c304..7a8092c5b 100644 --- a/internal/app/dangerzone/service.go +++ b/internal/app/dangerzone/service.go @@ -151,6 +151,9 @@ func (s *service) ScheduleOrganizationDeletion(ctx context.Context, orgID, reque if errors.Is(err, repository.ErrOrganizationCloudLinked) { return nil, errx.NewWithIdentifier(errx.Conflict, "organization_cloud_connected", "Disconnect owned workspaces from Warmbly Cloud before scheduling deletion.") } + if errors.Is(err, repository.ErrStorePurchasesActive) { + return nil, errx.NewWithIdentifier(errx.Conflict, "store_purchases_active", "Cancel this workspace's purchased mailboxes and turn off renewal on its purchased domains before deleting it.") + } if errors.Is(err, repository.ErrPendingDeletionExists) { return nil, errx.New(errx.Conflict, "organization is already scheduled for deletion") } @@ -277,6 +280,9 @@ func (s *service) ScheduleUserDeletion(ctx context.Context, userID uuid.UUID, re if errors.Is(err, repository.ErrOwnedAgencyBilled) { return nil, errx.NewWithIdentifier(errx.Conflict, "agency_subscription_active", "Cancel the plan of every agency you own before deleting your account.") } + if errors.Is(err, repository.ErrStorePurchasesActive) { + return nil, errx.NewWithIdentifier(errx.Conflict, "store_purchases_active", "Cancel the purchased mailboxes and turn off renewal on the purchased domains of every workspace you own before deleting your account.") + } if errors.Is(err, repository.ErrPendingDeletionExists) { return nil, errx.New(errx.Conflict, "account is already scheduled for deletion") } @@ -383,7 +389,7 @@ func (s *service) ExecuteDuePendingDeletions(ctx context.Context) (int, int, err if err := s.runHardDelete(ctx, &d); err != nil { // A refusal waits for the account to change, so it is recorded and rechecked daily, not reported. - if errors.Is(err, repository.ErrAccountHoldsSharedWork) || errors.Is(err, repository.ErrOwnedWorkspaceBilled) || errors.Is(err, repository.ErrOwnedAgencyBilled) { + if errors.Is(err, repository.ErrAccountHoldsSharedWork) || errors.Is(err, repository.ErrOwnedWorkspaceBilled) || errors.Is(err, repository.ErrOwnedAgencyBilled) || errors.Is(err, repository.ErrStorePurchasesActive) { log.Info().Err(err).Str("deletion_id", d.ID.String()).Msg("scheduled account deletion is waiting") if merr := s.repo.MarkWaiting(ctx, d.ID, err.Error(), time.Now().Add(24*time.Hour)); merr != nil { errs.CaptureException(fmt.Errorf("record waiting deletion %s: %w", d.ID, merr)) diff --git a/internal/app/organization/service.go b/internal/app/organization/service.go index cf82f7cf2..a4871122a 100644 --- a/internal/app/organization/service.go +++ b/internal/app/organization/service.go @@ -566,6 +566,9 @@ func (s *organizationService) Delete(ctx context.Context, orgID uuid.UUID) *errx if errors.Is(err, repository.ErrOrganizationCloudLinked) { return errx.NewWithIdentifier(errx.Conflict, "organization_cloud_connected", "Disconnect this workspace from Warmbly Cloud before deleting it.") } + if errors.Is(err, repository.ErrStorePurchasesActive) { + return errx.NewWithIdentifier(errx.Conflict, "store_purchases_active", "Cancel this workspace's purchased mailboxes and turn off renewal on its purchased domains before deleting it.") + } errs.CaptureException(err) return errx.New(errx.Internal, "failed to delete organization") } diff --git a/internal/app/store/billing.go b/internal/app/store/billing.go index 436730ec5..376531ed5 100644 --- a/internal/app/store/billing.go +++ b/internal/app/store/billing.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "strconv" + "strings" "time" "github.com/google/uuid" @@ -139,7 +140,12 @@ func (s *Service) RenewNow(ctx context.Context, orgID, id uuid.UUID) (*Domain, e // attempts already refunded, so a retry replays the same charge and a refused // attempt is never confused with the next one. func renewKey(d *models.StoreDomain) string { - return "store:renew:" + d.ID.String() + ":" + strconv.FormatInt(d.ExpiresAt.Unix(), 10) + ":" + strconv.Itoa(d.RenewalFailures) + return renewPrefix(d) + strconv.Itoa(d.RenewalFailures) +} + +// renewPrefix is the part of a renewal key naming the expiry it renews from. +func renewPrefix(d *models.StoreDomain) string { + return "store:renew:" + d.ID.String() + ":" + strconv.FormatInt(d.ExpiresAt.Unix(), 10) + ":" } // renew charges the current renewal price and renews from the stored expiry. @@ -152,19 +158,31 @@ func (s *Service) renew(ctx context.Context, d *models.StoreDomain, manual bool) if d.Source == models.StoreDomainConnected { return nil, registeredElsewhere() } - if d.ExpiresAt == nil || (d.Status != graphkit.DomainActive && d.Status != graphkit.DomainExpired) { - return nil, errx.NewWithIdentifier(errx.Conflict, CodeDomainNotRenewable, "This domain can't be renewed.") + notRenewable := errx.NewWithIdentifier(errx.Conflict, CodeDomainNotRenewable, "This domain can't be renewed.") + if d.ExpiresAt == nil { + return nil, notRenewable } key := renewKey(d) - if d.RenewalChargeKey != nil && *d.RenewalChargeKey != key { - // The expiry moved since that charge: the renewal it paid for happened. - if err := s.Repo.SetRenewalCharge(ctx, orgID, d.ID, nil); err != nil { - return nil, err + if d.RenewalChargeKey != nil { + if !strings.HasPrefix(*d.RenewalChargeKey, renewPrefix(d)) { + // The expiry moved since that charge: the renewal it paid for happened. + if err := s.Repo.SetRenewalCharge(ctx, orgID, d.ID, nil); err != nil { + return nil, err + } + d.RenewalChargeKey = nil + if !manual { + return nil, nil + } + } else { + // A charge in flight is settled under its own key. + key = *d.RenewalChargeKey } - d.RenewalChargeKey = nil - if !manual { - return nil, nil + } + if d.Status != graphkit.DomainActive && d.Status != graphkit.DomainExpired { + if d.RenewalChargeKey != nil { + s.abandonRenewal(ctx, d, key) } + return nil, notRenewable } live, gerr := s.api().GetDomain(ctx, d.GraphKitDomainID) if gerr != nil { @@ -273,6 +291,23 @@ func (s *Service) chargeRenewal(ctx context.Context, d *models.StoreDomain, pric return nil } +// abandonRenewal settles a charged renewal on a domain that can no longer be +// renewed: adopted when GraphKit renewed it, refunded otherwise. +func (s *Service) abandonRenewal(ctx context.Context, d *models.StoreDomain, key string) { + live, gerr := s.api().GetDomain(ctx, d.GraphKitDomainID) + if gerr != nil { + logUpstream("domain.renew.read", gerr) + return + } + if live.ExpiresAt != nil && live.ExpiresAt.After(*d.ExpiresAt) { + if err := s.Repo.RecordDomainRenewal(context.WithoutCancel(ctx), d.OrganizationID, d.ID, *live.ExpiresAt); err == nil { + _, _ = s.upsertDomain(ctx, d.OrganizationID, nil, live) + } + return + } + s.refundRenewal(ctx, d, key, "Domain renewal · "+d.Name+" · 1 year") +} + // refundRenewal gives back an attempt's charge and moves on to the next attempt's key. // A refund that does not go through leaves the attempt in flight, so the next pass tries again. func (s *Service) refundRenewal(ctx context.Context, d *models.StoreDomain, key, reason string) { diff --git a/internal/app/store/checkout.go b/internal/app/store/checkout.go index 5c490ad1d..195ba96f0 100644 --- a/internal/app/store/checkout.go +++ b/internal/app/store/checkout.go @@ -29,6 +29,9 @@ var ( localRe = regexp.MustCompile(`^[a-z0-9]([a-z0-9._-]{0,62}[a-z0-9])?$`) ) +// chargeWindow is how long an order's own request may still be charging it. +const chargeWindow = 2 * time.Minute + // quoteMargin treats a quote this close to expiry as expired, so GraphKit never sees it lapse mid-order. const quoteMargin = 30 * time.Second @@ -392,6 +395,10 @@ func (s *Service) charge(ctx context.Context, row *models.StoreOrder, snap quote owed += l.AmountMicros } } + if !created && owed > 0 && s.now().Sub(row.UpdatedAt) < chargeWindow { + // The request that started this order may still be charging it. + return errx.NewWithIdentifier(errx.Conflict, CodeChargeInProgress, "This order is already being placed. Try again in a minute.") + } if err := s.collect(ctx, orgID, owed, row.ChargeKey, describe(snap.Lines, row.CreatedAt), false); err != nil { // A card payment still going through keeps the order, so the retry resumes the same charge. if created && owed == snap.DueNowMicros && errCode(err) != CodePaymentProcessing { diff --git a/internal/app/store/fixes_test.go b/internal/app/store/fixes_test.go new file mode 100644 index 000000000..f30aa46b7 --- /dev/null +++ b/internal/app/store/fixes_test.go @@ -0,0 +1,120 @@ +package store + +import ( + "context" + "testing" + "time" + + "github.com/google/uuid" + + "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/pkg/graphkit" +) + +// startedOrder is an order another request created and has not charged yet. +func startedOrder(t *testing.T, h *harness, q *Quote) uuid.UUID { + t.Helper() + stored, _ := h.repo.GetQuote(context.Background(), h.org, q.ID) + rowID := uuid.New() + if _, _, err := h.repo.CreateOrder(context.Background(), &models.StoreOrder{ID: rowID, OrganizationID: h.org, QuoteID: q.ID, Status: models.StoreOrderCharging, + Quote: stored.Snapshot, DueNowMicros: models.Micro(q.DueNowMicros), ChargeKey: "store:order:" + rowID.String()}); err != nil { + t.Fatal(err) + } + return rowID +} + +// A second checkout of a quote whose order another request is charging charges nothing and leaves the order alone. +func TestSecondCheckoutNeverChargesAlongsideTheFirst(t *testing.T) { + h := newHarness(t) + h.fund(100) + ctx := context.Background() + q, err := h.s.CreateQuote(ctx, h.org, domainAndMailboxes("acmeoutreach.com", graphkit.ProviderGoogle, 1)) + if err != nil { + t.Fatal(err) + } + rowID := startedOrder(t, h, q) + due := q.DueNowMicros + if _, err := h.s.PlaceOrder(ctx, h.org, h.user, OrderRequest{QuoteID: q.ID, ExpectedDueNowMicros: &due}); code(err) != CodeChargeInProgress { + t.Fatalf("second request = %v", err) + } + if net := h.credits.net(h.org); net != 0 { + t.Fatalf("the second request charged %d", net) + } + if row, _ := h.repo.GetOrder(ctx, h.org, rowID); row == nil || row.GraphKitOrderID != nil { + t.Fatalf("order after the second request = %+v", row) + } +} + +// An order whose lines were debited and then refunded is never placed by the reconciler. +func TestReconcilerDoesNotPlaceARefundedOrder(t *testing.T) { + h := newHarness(t) + h.fund(100) + ctx := context.Background() + q, err := h.s.CreateQuote(ctx, h.org, domainAndMailboxes("acmeoutreach.com", graphkit.ProviderGoogle, 1)) + if err != nil { + t.Fatal(err) + } + rowID := startedOrder(t, h, q) + row, _ := h.repo.GetOrder(ctx, h.org, rowID) + for i, l := range q.Lines { + if _, err := h.credits.ChargeAmount(ctx, h.org, models.Micro(l.AmountMicros), "line", lineKey(row.ChargeKey, i)); err != nil { + t.Fatal(err) + } + if _, err := h.credits.RefundCharge(ctx, h.org, lineKey(row.ChargeKey, i), "back"); err != nil { + t.Fatal(err) + } + } + h.clock.advance(openOrderAge + time.Minute) + if err := h.s.Reconcile(ctx); err != nil { + t.Fatal(err) + } + if got, _ := h.repo.GetOrder(ctx, h.org, rowID); got != nil && got.GraphKitOrderID != nil { + t.Fatalf("a refunded order was placed: %s", got.Status) + } +} + +// A month paid late whose resume got no answer is refunded once the cancellation takes effect. +func TestLatePaymentRefundedWhenTheCancellationTakesEffect(t *testing.T) { + h := newHarness(t) + m := unpaidCancelled(t, h) + h.hook().resume = func(context.Context, string, string) (*graphkit.Mailbox, error) { return nil, noAnswer } + h.cards.decline = "" + ctx := context.Background() + if err := h.s.RetryUnpaid(ctx, h.org); err != nil { + t.Fatal(err) + } + if got := h.box(t, m.ID); got.BillingFailures != 0 || got.PaidKey == nil { + t.Fatalf("setup: the late month was not paid: %+v", got) + } + h.repo.mu.Lock() + h.repo.mailboxes[m.ID].Status = graphkit.MailboxCancelled + h.repo.mu.Unlock() + h.clock.advance(24 * time.Hour) + _ = h.s.Bill(ctx) + if paid := monthLines(h); paid != 0 { + t.Fatalf("the workspace paid %d net for a month that never started", paid) + } + if got := h.box(t, m.ID); got.UnpaidCancel || !got.PaidThrough.Equal(m.PaidThrough) { + t.Fatalf("mailbox after the refund: %+v", got) + } +} + +// A workspace's monthly mailbox cost counts its oldest live mailbox however many ended ones came after it. +func TestMonthlyMailboxesCountsLiveRowsPastAPage(t *testing.T) { + h := newHarness(t) + ctx := context.Background() + add := func(status string) { + h.clock.advance(time.Minute) + if _, err := h.repo.UpsertMailbox(ctx, &models.StoreMailbox{ID: uuid.New(), OrganizationID: h.org, GraphKitMailboxID: "mbx_" + uuid.NewString(), + Email: uuid.NewString()[:8] + "@acme.test", Provider: "google", Status: status, MonthlyRetailMicros: monthFee, PaidThrough: h.clock.now()}); err != nil { + t.Fatal(err) + } + } + add(graphkit.MailboxActive) + for range maxPageLimit * 5 { + add(graphkit.MailboxCancelled) + } + if got := h.s.monthlyMailboxes(ctx, h.org); got != int64(monthFee) { + t.Fatalf("monthly %d, want the one live mailbox", got) + } +} diff --git a/internal/app/store/mailbox_billing.go b/internal/app/store/mailbox_billing.go index bd4e1c388..e746679ef 100644 --- a/internal/app/store/mailbox_billing.go +++ b/internal/app/store/mailbox_billing.go @@ -70,7 +70,7 @@ func (s *Service) ensureAnchor(ctx context.Context, orgID uuid.UUID) (*models.St if acct.BillDay > 0 && acct.NextBillAnchor != nil { return acct, nil } - boxes, err := s.Repo.ListMailboxes(ctx, orgID, nil, maxPageLimit*5) + boxes, err := s.Repo.OpenMailboxes(ctx, orgID) if err != nil { return nil, err } @@ -105,9 +105,21 @@ func (s *Service) billMailboxes(ctx context.Context) error { return err } var errs []error + billed := map[uuid.UUID]bool{} for _, orgID := range orgs { + billed[orgID] = true errs = append(errs, s.billOrg(ctx, orgID, false)) } + // A workspace whose last mailboxes ended still gets back a month they paid for. + unsettled, err := s.Repo.OrgsWithUnsettledCancels(ctx, 10_000) + if err != nil { + return errors.Join(append(errs, err)...) + } + for _, orgID := range unsettled { + if !billed[orgID] { + errs = append(errs, s.settleCancels(ctx, orgID)) + } + } return errors.Join(errs...) } @@ -440,14 +452,18 @@ func (s *Service) enforceUnpaid(ctx context.Context, orgID uuid.UUID) error { // once that month is paid, while the cancellation can still be undone, and // gives back a month collected for a period a cancellation keeps from starting. func (s *Service) settleCancels(ctx context.Context, orgID uuid.UUID) error { - boxes, err := s.Repo.ListMailboxes(ctx, orgID, nil, maxPageLimit*5) + boxes, err := s.Repo.OpenMailboxes(ctx, orgID) if err != nil { return err } for i := range boxes { m := &boxes[i] switch { - case m.PendingChargeKey != nil || m.CancelsAt == nil: + case m.PendingChargeKey != nil: + case m.UnpaidCancel && m.BillingFailures == 0 && endedStatus(m.Status): + // The cancellation took effect, so the month paid late never starts. + s.refundMonth(ctx, m) + case m.CancelsAt == nil: case m.UnpaidCancel && m.BillingFailures == 0 && m.Status == graphkit.MailboxCancelling: s.resumePaid(ctx, m) case !m.UnpaidCancel: diff --git a/internal/app/store/memrepo_test.go b/internal/app/store/memrepo_test.go index 985095981..d8952baaf 100644 --- a/internal/app/store/memrepo_test.go +++ b/internal/app/store/memrepo_test.go @@ -439,6 +439,12 @@ func (r *memRepo) SetDomainAutoRenew(_ context.Context, orgID, id uuid.UUID, on defer r.mu.Unlock() if d := r.domain(orgID, id); d != nil { d.AutoRenew = on + if on { + if d.RenewalChargeKey == nil { + d.RenewalFailures = 0 + } + d.RenewalAttemptAt = nil + } } return nil } @@ -542,7 +548,7 @@ func (r *memRepo) DueDomainRenewals(_ context.Context, horizon, attemptedBefore, due := d.AutoRenew && !d.ExpiresAt.After(horizon) && (d.RenewalAttemptAt == nil || d.RenewalAttemptAt.Before(attemptedBefore)) && ((d.RenewalNoticeAt != nil && !d.RenewalNoticeAt.After(noticedBefore)) || !d.ExpiresAt.After(urgent)) - if (d.Status == "active" || d.Status == "expired") && d.ExpiresAt != nil && (due || d.RenewalChargeKey != nil) { + if d.ExpiresAt != nil && ((due && (d.Status == "active" || d.Status == "expired")) || d.RenewalChargeKey != nil) { out = append(out, *r.withCount(d)) } } @@ -646,6 +652,16 @@ func (r *memRepo) GetMailboxByEmail(_ context.Context, orgID uuid.UUID, email st return nil, nil } +// newestFirst orders mailboxes as the repository does: created_at, then id, descending. +func newestFirst(out []models.StoreMailbox) { + sort.Slice(out, func(i, j int) bool { + if !out[i].CreatedAt.Equal(out[j].CreatedAt) { + return out[i].CreatedAt.After(out[j].CreatedAt) + } + return out[i].ID.String() > out[j].ID.String() + }) +} + func (r *memRepo) ListMailboxes(_ context.Context, orgID uuid.UUID, _ *models.StorePage, limit int) ([]models.StoreMailbox, error) { r.mu.Lock() defer r.mu.Unlock() @@ -655,9 +671,41 @@ func (r *memRepo) ListMailboxes(_ context.Context, orgID uuid.UUID, _ *models.St out = append(out, *m) } } + newestFirst(out) return out[:min(limit, len(out))], nil } +func unsettledCancel(m *models.StoreMailbox) bool { + return m.UnpaidCancel && m.BillingFailures == 0 && endedMailbox(m) +} + +func (r *memRepo) OpenMailboxes(_ context.Context, orgID uuid.UUID) ([]models.StoreMailbox, error) { + r.mu.Lock() + defer r.mu.Unlock() + var out []models.StoreMailbox + for _, m := range r.mailboxes { + if m.OrganizationID == orgID && (!endedMailbox(m) || unsettledCancel(m)) { + out = append(out, *m) + } + } + newestFirst(out) + return out, nil +} + +func (r *memRepo) OrgsWithUnsettledCancels(context.Context, int) ([]uuid.UUID, error) { + r.mu.Lock() + defer r.mu.Unlock() + seen := map[uuid.UUID]bool{} + out := []uuid.UUID{} + for _, m := range r.mailboxes { + if unsettledCancel(m) && !seen[m.OrganizationID] { + seen[m.OrganizationID] = true + out = append(out, m.OrganizationID) + } + } + return out, nil +} + func (r *memRepo) ListMailboxesByOrder(_ context.Context, orgID, orderID uuid.UUID) ([]models.StoreMailbox, error) { r.mu.Lock() defer r.mu.Unlock() diff --git a/internal/app/store/reload.go b/internal/app/store/reload.go index 36cda3a97..c82ee95dc 100644 --- a/internal/app/store/reload.go +++ b/internal/app/store/reload.go @@ -75,7 +75,7 @@ func neverConfigured(cfg *models.AISpendSettings) bool { // monthlyMailboxes is what the workspace's mailboxes cost a month, the size of its next bundle. func (s *Service) monthlyMailboxes(ctx context.Context, orgID uuid.UUID) int64 { - boxes, err := s.Repo.ListMailboxes(ctx, orgID, nil, maxPageLimit*5) + boxes, err := s.Repo.OpenMailboxes(ctx, orgID) if err != nil { return 0 } diff --git a/internal/app/store/sync.go b/internal/app/store/sync.go index 0c2b4d3eb..1948e4a8f 100644 --- a/internal/app/store/sync.go +++ b/internal/app/store/sync.go @@ -310,7 +310,7 @@ func (s *Service) recoverStranded(ctx context.Context, row *models.StoreOrder) e if err != nil { return err } - if prior != nil { + if prior != nil && prior.Refunded < prior.Taken { debited++ taken += prior.Taken } diff --git a/internal/repository/pg_credit.go b/internal/repository/pg_credit.go index 4a718d5ec..163285175 100644 --- a/internal/repository/pg_credit.go +++ b/internal/repository/pg_credit.go @@ -245,17 +245,21 @@ func (r *creditRepository) Debit(ctx context.Context, orgID uuid.UUID, d models. } defer tx.Rollback(ctx) - if key != "" { + replay := func() (*models.CreditTransaction, error) { + if key == "" { + return nil, nil + } existing, err := replayByKey(ctx, tx, key) + if err != nil || existing == nil { + return nil, err + } + return existing, tx.Commit(ctx) + } + if existing, err := replay(); err != nil || existing != nil { if err != nil { return 0, nil, false, err } - if existing != nil { - if cerr := tx.Commit(ctx); cerr != nil { - return 0, nil, false, cerr - } - return existing.MonthlyAfter + existing.PurchasedAfter, existing, true, nil - } + return existing.MonthlyAfter + existing.PurchasedAfter, existing, true, nil } // The row lock serializes concurrent debits; a missing ledger is an empty one. @@ -281,6 +285,13 @@ func (r *creditRepository) Debit(ctx context.Context, orgID uuid.UUID, d models. return 0, nil, false, err } } + // A same-key debit that committed while this one waited on the lock replays. + if existing, err := replay(); err != nil || existing != nil { + if err != nil { + return 0, nil, false, err + } + return existing.MonthlyAfter + existing.PurchasedAfter, existing, true, nil + } var agency models.AgencyAILedger var agencyAvail models.Micro if funding != nil { diff --git a/internal/repository/pg_danger_zone.go b/internal/repository/pg_danger_zone.go index fadb7d925..cd1bc9358 100644 --- a/internal/repository/pg_danger_zone.go +++ b/internal/repository/pg_danger_zone.go @@ -131,6 +131,11 @@ func (r *dangerZoneRepository) CreatePending(ctx context.Context, d *models.Sche return ErrOrganizationCloudLinked } } + if d.ResourceType == models.DeletionResourceOrganization { + if err := storePurchasesEnded(ctx, tx, []uuid.UUID{d.ResourceID}); err != nil { + return err + } + } if d.ResourceType == models.DeletionResourceUser { owned, err := ownedWorkspaces(ctx, tx, d.ResourceID, false) if err != nil { @@ -387,6 +392,12 @@ func (r *dangerZoneRepository) HardDeleteOrganization(ctx context.Context, orgID return nil, err } defer tx.Rollback(ctx) + if _, err := tx.Exec(ctx, `SELECT 1 FROM organizations WHERE id = $1 FOR UPDATE`, orgID); err != nil { + return nil, err + } + if err := storePurchasesEnded(ctx, tx, []uuid.UUID{orgID}); err != nil { + return nil, err + } placements, err := eraseAndDelete(ctx, tx, `a.organization_id = $1`, []any{orgID}, deletion{`DELETE FROM organizations WHERE id = $1`, []any{orgID}}) if err != nil { @@ -499,7 +510,30 @@ func ownedWorkspaces(ctx context.Context, tx pgx.Tx, userID uuid.UUID, lock bool return owned, err } +// ErrStorePurchasesActive refuses deleting a workspace that still holds store +// mailboxes, domains or orders that are not cancelled, ended or failed. +var ErrStorePurchasesActive = errors.New("workspace has active store purchases") + +// storePurchasesEnded refuses while any of the workspaces holds a running store purchase. +func storePurchasesEnded(ctx context.Context, q queryRower, orgs []uuid.UUID) error { + var active bool + err := q.QueryRow(ctx, ` + SELECT EXISTS (SELECT 1 FROM store_mailboxes m WHERE m.organization_id = ANY($1) + AND m.status NOT IN ('cancelled', 'cancelling', 'failed') AND m.cancels_at IS NULL) + OR EXISTS (SELECT 1 FROM store_domains d WHERE d.organization_id = ANY($1) AND d.source = 'purchased' + AND (d.renewal_charge_key IS NOT NULL OR (d.auto_renew AND d.status IN ('registering', 'active')))) + OR EXISTS (SELECT 1 FROM store_orders o WHERE o.organization_id = ANY($1) AND o.status IN ('charging', 'processing'))`, + orgs).Scan(&active) + if err == nil && active { + return ErrStorePurchasesActive + } + return err +} + func accountDeletable(ctx context.Context, tx pgx.Tx, userID uuid.UUID, owned []uuid.UUID) error { + if err := storePurchasesEnded(ctx, tx, owned); err != nil { + return err + } var shared, billed, agencyBilled bool err := tx.QueryRow(ctx, ` SELECT diff --git a/internal/repository/pg_organization.go b/internal/repository/pg_organization.go index c201f795e..84381a8d4 100644 --- a/internal/repository/pg_organization.go +++ b/internal/repository/pg_organization.go @@ -237,12 +237,27 @@ func (r *organizationRepository) UpdateAvatar(ctx context.Context, orgID uuid.UU var ErrOrganizationCloudLinked = errors.New("disconnect workspace Cloud link before deleting") func (r *organizationRepository) Delete(ctx context.Context, id uuid.UUID) error { - _, err := r.db.Exec(ctx, `DELETE FROM organizations WHERE id = $1`, id) + tx, err := r.db.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + // The row lock holds off new store rows until the delete commits. + if _, err := tx.Exec(ctx, `SELECT 1 FROM organizations WHERE id = $1 FOR UPDATE`, id); err != nil { + return err + } + if err := storePurchasesEnded(ctx, tx, []uuid.UUID{id}); err != nil { + return err + } + _, err = tx.Exec(ctx, `DELETE FROM organizations WHERE id = $1`, id) var pgErr *pgconn.PgError if errors.As(err, &pgErr) && pgErr.ConstraintName == "cloud_link_organization_id_fkey" { return ErrOrganizationCloudLinked } - return err + if err != nil { + return err + } + return tx.Commit(ctx) } // GetUserOrganizations retrieves all organizations a user is a member of diff --git a/internal/repository/pg_store.go b/internal/repository/pg_store.go index 9f979deb9..a8c163589 100644 --- a/internal/repository/pg_store.go +++ b/internal/repository/pg_store.go @@ -160,6 +160,10 @@ type StoreRepository interface { ClearBillingRetry(ctx context.Context, orgID uuid.UUID) error // OrgsWithLiveMailboxes are the workspaces holding a purchased mailbox that is not cancelled or failed. OrgsWithLiveMailboxes(ctx context.Context, limit int) ([]uuid.UUID, error) + // OrgsWithUnsettledCancels are the workspaces holding an ended mailbox whose unpaid cancellation still holds a paid month. + OrgsWithUnsettledCancels(ctx context.Context, limit int) ([]uuid.UUID, error) + // OpenMailboxes is every mailbox of the workspace not cancelled or failed, plus an ended one still holding an unpaid cancellation, newest first. + OpenMailboxes(ctx context.Context, orgID uuid.UUID) ([]models.StoreMailbox, error) HasLiveMailboxes(ctx context.Context, orgID uuid.UUID) (bool, error) // CreatePhoto records an uploaded photo whose bytes are already stored. CreatePhoto(ctx context.Context, p *models.StorePhoto) error @@ -630,7 +634,9 @@ func (r *storeRepository) ListDomainsByOrder(ctx context.Context, orgID, orderID } func (r *storeRepository) SetDomainAutoRenew(ctx context.Context, orgID, id uuid.UUID, on bool) error { - return r.exec(ctx, `UPDATE store_domains SET auto_renew = $3, renewal_failures = CASE WHEN $3 THEN 0 ELSE renewal_failures END, + // A renewal in flight keeps its attempt count, which its charge key carries. + return r.exec(ctx, `UPDATE store_domains SET auto_renew = $3, + renewal_failures = CASE WHEN $3 AND renewal_charge_key IS NULL THEN 0 ELSE renewal_failures END, renewal_attempt_at = CASE WHEN $3 THEN NULL ELSE renewal_attempt_at END, updated_at = now() WHERE organization_id = $1 AND id = $2`, orgID, id, on) } @@ -684,8 +690,8 @@ func (r *storeRepository) SetRenewalCharge(ctx context.Context, orgID, id uuid.U func (r *storeRepository) DueDomainRenewals(ctx context.Context, horizon, attemptedBefore, noticedBefore, urgent time.Time, limit int) ([]models.StoreDomain, error) { return r.domains(ctx, `SELECT `+storeDomainColumns+` FROM store_domains d - WHERE d.status IN ('active', 'expired') AND d.expires_at IS NOT NULL - AND (d.renewal_charge_key IS NOT NULL OR (d.auto_renew AND d.expires_at <= $1 + WHERE d.expires_at IS NOT NULL + AND (d.renewal_charge_key IS NOT NULL OR (d.status IN ('active', 'expired') AND d.auto_renew AND d.expires_at <= $1 AND (d.renewal_attempt_at IS NULL OR d.renewal_attempt_at < $2) AND (d.renewal_notice_at <= $3 OR d.expires_at <= $4))) ORDER BY d.expires_at LIMIT $5`, horizon, attemptedBefore, noticedBefore, urgent, limit) @@ -1011,6 +1017,19 @@ func (r *storeRepository) OrgsWithLiveMailboxes(ctx context.Context, limit int) return r.uuids(ctx, `SELECT DISTINCT organization_id FROM store_mailboxes WHERE `+storeLiveMailbox+` LIMIT $1`, limit) } +// storeUnsettledCancel is an ended mailbox whose unpaid cancellation is not settled, with nothing left unpaid. +const storeUnsettledCancel = `(unpaid_cancel AND billing_failures = 0 AND ` + storeEndedMailbox + `)` + +func (r *storeRepository) OrgsWithUnsettledCancels(ctx context.Context, limit int) ([]uuid.UUID, error) { + return r.uuids(ctx, `SELECT DISTINCT organization_id FROM store_mailboxes WHERE `+storeUnsettledCancel+` LIMIT $1`, limit) +} + +func (r *storeRepository) OpenMailboxes(ctx context.Context, orgID uuid.UUID) ([]models.StoreMailbox, error) { + return r.mailboxes(ctx, `SELECT `+storeMailboxColumns+` FROM store_mailboxes + WHERE organization_id = $1 AND (NOT `+storeEndedMailbox+` OR `+storeUnsettledCancel+`) + ORDER BY created_at DESC, id DESC`, orgID) +} + func (r *storeRepository) HasLiveMailboxes(ctx context.Context, orgID uuid.UUID) (bool, error) { var ok bool err := r.db.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM store_mailboxes WHERE organization_id = $1 AND `+storeLiveMailbox+`)`, orgID).Scan(&ok) diff --git a/internal/repository/store_fixes_live_test.go b/internal/repository/store_fixes_live_test.go new file mode 100644 index 000000000..bb06700d5 --- /dev/null +++ b/internal/repository/store_fixes_live_test.go @@ -0,0 +1,78 @@ +package repository + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/google/uuid" + + "github.com/warmbly/warmbly/internal/models" +) + +// Concurrent debits under one key take the money once and every caller gets the same transaction. +func TestLiveStoreMoneyConcurrentSameKeyDebitReplays(t *testing.T) { + f := newStoreMoneyFixture(t) + ctx := context.Background() + if _, _, err := f.credits.GrantPurchased(ctx, f.org, 50*usd1, "top_up", "invoice:in_race"); err != nil { + t.Fatal(err) + } + key := "store:order:" + uuid.NewString() + ":0" + var wg sync.WaitGroup + ids := make([]uuid.UUID, 8) + for i := range ids { + wg.Go(func() { + _, txn, _, err := f.credits.Debit(ctx, f.org, storeDebit(5*usd1, key)) + if err != nil { + t.Errorf("debit %d: %v", i, err) + return + } + ids[i] = txn.ID + }) + } + wg.Wait() + for _, id := range ids { + if id != ids[0] { + t.Fatalf("debits under one key returned different transactions: %v", ids) + } + } + if l, _ := f.credits.GetBalance(ctx, f.org); l.Purchased != 45*usd1 { + t.Fatalf("purchased %d, want one debit", l.Purchased) + } +} + +// A workspace holding a running store mailbox cannot be deleted by any path until the mailbox is cancelled. +func TestLiveStoreWorkspaceDeletionWaitsForPurchasesToEnd(t *testing.T) { + f := newStoreMoneyFixture(t) + ctx := context.Background() + m := f.mailbox(f.domain().ID, time.Now().Add(24*time.Hour)) + f.exec(`UPDATE store_domains SET auto_renew = false WHERE organization_id = $1`, f.org) + dz := NewDangerZoneRepository(f.pool) + orgs := NewOrganizationRepository(f.pool) + now := time.Now() + pending := func(kind models.DeletionResourceType, id uuid.UUID) error { + return dz.CreatePending(ctx, &models.ScheduledDeletion{ID: uuid.New(), ResourceType: kind, ResourceID: id, OrganizationID: &f.org, + RequestedByUserID: f.user, ScheduledAt: now, ExecuteAfter: now, GraceDays: 0, Status: models.DeletionStatusPending}) + } + if err := pending(models.DeletionResourceOrganization, f.org); !errors.Is(err, ErrStorePurchasesActive) { + t.Fatalf("schedule workspace deletion = %v", err) + } + if err := pending(models.DeletionResourceUser, f.user); !errors.Is(err, ErrStorePurchasesActive) { + t.Fatalf("schedule account deletion = %v", err) + } + if _, err := dz.HardDeleteOrganization(ctx, f.org); !errors.Is(err, ErrStorePurchasesActive) { + t.Fatalf("hard delete workspace = %v", err) + } + if _, err := dz.HardDeleteUser(ctx, f.user, nil); !errors.Is(err, ErrStorePurchasesActive) { + t.Fatalf("hard delete owner = %v", err) + } + if err := orgs.Delete(ctx, f.org); !errors.Is(err, ErrStorePurchasesActive) { + t.Fatalf("delete workspace = %v", err) + } + f.exec(`UPDATE store_mailboxes SET status = 'cancelled', cancels_at = now() WHERE id = $1`, m.ID) + if _, err := dz.HardDeleteOrganization(ctx, f.org); err != nil { + t.Fatalf("hard delete after the cancellation = %v", err) + } +}