plans: monthly PDF render cap
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
17 files changed,
+347
−18
internal/console/apipdf.go+0 −3internal/console/apipdf_test.go+47 −0internal/console/billingpage.go+3 −0internal/console/billingpage_copy.go+3 −0internal/console/billingusage.go+14 −6internal/console/billingusage_test.go+32 −0internal/console/plancaps_copy.go+3 −0internal/console/planexempt_test.go+1 −1internal/console/plangrace.go+7 −6internal/console/plangracepass.go+5 −0internal/console/planmeasure.go+4 −0internal/console/planpdf.go+30 −0internal/console/planpdf_test.go+164 −0internal/console/plansponsor.go+1 −0internal/plans/catalog.go+3 −1internal/plans/catalog_test.go+28 −0internal/plans/team.go+2 −1
CI failed — run details
diff --git a/internal/console/apipdf.go b/internal/console/apipdf.go| index 89b3755fa..8845dc163 100644 |
| --- a/internal/console/apipdf.go |
| +++ b/internal/console/apipdf.go |
| @@ -60,9 +60,6 @@ type pdfRenderRow struct { |
| At time.Time |
| } |
| -// Task 4 replaces the plan admission stub. |
| -func (*Server) pdfPlanCheck(context.Context, *Account, time.Time) error { return nil } |
| - |
| func (s *Server) handleAPIPDF(w http.ResponseWriter, r *http.Request) { |
| _, acct, app, ok := s.apiAccountApp(w, r) |
| if !ok { |
diff --git a/internal/console/apipdf_test.go b/internal/console/apipdf_test.go| index 020ef097d..8ddbbf721 100644 |
| --- a/internal/console/apipdf_test.go |
| +++ b/internal/console/apipdf_test.go |
| @@ -909,3 +909,50 @@ func TestPDFDoorIdleEngineAfterClientEOF(t *testing.T) { |
| } |
| }) |
| } |
| + |
| +func TestPDFDoorRefusesAtCeiling(t *testing.T) { |
| + var calls atomic.Int32 |
| + fx := newPDFDoorFixture(t, func(w http.ResponseWriter, r *http.Request) { calls.Add(1); io.WriteString(w, "%PDF-invoice") }) |
| + acct := planAccount(t, fx.consoleFixture, 501) |
| + capsApp(t, fx.consoleFixture, acct, "shop") |
| + fx.sqid = acct.Sqid |
| + fx.token = serviceToken(t, fx.st, acct.ID, "pdf", "shop", svcrole.Service) |
| + fx.srv.cfg.PlanCatalog = pdfPlanCatalog(t, 100) |
| + now := time.Now().UTC() |
| + recordPlanPDFs(t, fx.st, acct.Sqid, 200, now) |
| + // More than the default burst: refusals must leave every token available. |
| + for range 21 { |
| + resp := fx.request(t, pdfHTMLRoute, nil, nil) |
| + var body map[string]string |
| + err := json.NewDecoder(resp.Body).Decode(&body) |
| + resp.Body.Close() |
| + if err != nil || resp.StatusCode != 402 || body["error"] != pdfCapAt200 { |
| + t.Fatalf("refusal = %d %v, %v", resp.StatusCode, body, err) |
| + } |
| + fx.row(t, pdfRefused, 402) |
| + } |
| + if calls.Load() != 0 { |
| + t.Fatal("plan refusal reached engine") |
| + } |
| + if got := countWhere(t, fx.st, "pdf_renders", "account = ? AND outcome = 'refused' AND status = 402", acct.Sqid); got != 21 { |
| + t.Fatalf("refused rows = %d", got) |
| + } |
| + fx.srv.pdfLimiter.mu.Lock() |
| + total, accounts := fx.srv.pdfLimiter.total, len(fx.srv.pdfLimiter.accounts) |
| + fx.srv.pdfLimiter.mu.Unlock() |
| + if total != 0 || accounts != 0 { |
| + t.Fatalf("refusals touched limiter: total %d, accounts %d", total, accounts) |
| + } |
| + // Cheap route refusal still wins over the exhausted plan. |
| + pdfWantError(t, fx.request(t, "health", nil, nil), 404, "pdf.unknown_route") |
| + fx.row(t, pdfRefused, 404) |
| + // A plan increase is effective immediately, with the full burst intact. |
| + fx.srv.cfg.PlanCatalog = pdfPlanCatalog(t, 200) |
| + resp := fx.request(t, pdfHTMLRoute, nil, nil) |
| + _, err := io.Copy(io.Discard, resp.Body) |
| + resp.Body.Close() |
| + if err != nil || resp.StatusCode != 200 || calls.Load() != 1 { |
| + t.Fatalf("larger plan = %d, calls %d, %v", resp.StatusCode, calls.Load(), err) |
| + } |
| + fx.row(t, pdfRendered, 200) |
| +} |
diff --git a/internal/console/billingpage.go b/internal/console/billingpage.go| index 30340c519..75967b567 100644 |
| --- a/internal/console/billingpage.go |
| +++ b/internal/console/billingpage.go |
| @@ -750,6 +750,9 @@ func planIncludes(l plans.Limits, maxMembers int) []billingInclude { |
| if l.DiskBytes > 0 { |
| add(fmt.Sprintf(billingCopy["limit.disk"], billingBytes(l.DiskBytes))) |
| } |
| + if l.PDFRendersMonth > 0 { |
| + add(fmt.Sprintf(billingCopy["limit.pdf"], billingCount(int64(l.PDFRendersMonth)))) |
| + } |
| if l.CustomDomains { |
| add(billingCopy["limit.domains"]) |
| } |
diff --git a/internal/console/billingpage_copy.go b/internal/console/billingpage_copy.go| index 52facf5c7..bc0831c5a 100644 |
| --- a/internal/console/billingpage_copy.go |
| +++ b/internal/console/billingpage_copy.go |
| @@ -133,6 +133,7 @@ var billingCopy = map[string]string{ |
| "limit.disk": "%s disk per app", |
| "limit.storage": "%s object storage", |
| "limit.email": "%s emails a day", |
| + "limit.pdf": "%s PDFs a month", |
| "limit.bandwidth": "%s bandwidth a month", |
| "limit.domains": "Custom domains", |
| "limit.members": "Up to %d members", |
| @@ -171,6 +172,7 @@ var billingCopy = map[string]string{ |
| "usage.of": "%s of %s used", |
| "usage.of_today": "%s of %s used today", |
| "usage.of_month": "%s of %s used this month", |
| + "usage.pdf": "%d of %d PDFs this month", |
| "usage.unknown": "Usage not known yet", |
| "usage.disk": "Up to %s per app", |
| "usage.you_use": "You use %s", |
| @@ -178,5 +180,6 @@ var billingCopy = map[string]string{ |
| "usage.label.running": "Apps and instances", |
| "usage.label.storage": "Object storage", |
| "usage.label.email": "Email", |
| + "usage.label.pdf": "PDFs", |
| "usage.label.bandwidth": "Bandwidth", |
| } |
diff --git a/internal/console/billingusage.go b/internal/console/billingusage.go| index 5c14518b4..ccf9cec7a 100644 |
| --- a/internal/console/billingusage.go |
| +++ b/internal/console/billingusage.go |
| @@ -20,8 +20,8 @@ import ( |
| // use, so it shows as not known, never as its old figure or as zero. |
| // Disk is a per-app limit nothing measures centrally: its limit alone. |
| -// usageCaps are the caps the page shows, in order: the ones a pack raises. |
| -var usageCaps = []capID{capRunningThings, capStorage, capEmail, capBandwidth} |
| +// usageCaps are the caps the page shows, in order. |
| +var usageCaps = []capID{capRunningThings, capStorage, capEmail, capBandwidth, capPDF} |
| // billingUse is a use beside a limit as the page shows it. Level is "" |
| // below 80% of the limit, "warn" from 80% up to it, "over" past it. |
| @@ -37,8 +37,7 @@ type billingUsageRow struct { |
| // billingUsageView is the account's usage on the page. AsOf is the "Usage |
| // as of" line, at the oldest measurement shown. Rows is the summary's |
| -// list, set only when no pack row carries the usage (a member, or a page |
| -// with no packs to change). |
| +// list, for usage no pack row carries. |
| type billingUsageView struct { |
| AsOf string |
| Rows []billingUsageRow |
| @@ -80,6 +79,8 @@ func capLimit(l plans.Limits, c capID) int64 { |
| return int64(l.EmailPerDay) |
| case capBandwidth: |
| return l.BandwidthBytesMonth |
| + case capPDF: |
| + return int64(l.PDFRendersMonth) |
| } |
| return 0 |
| } |
| @@ -127,6 +128,9 @@ func useOfLimit(used map[capID]int64, c capID, limit int64) *billingUse { |
| // No limit to be "of": the launch sponsorship's figure. |
| return &billingUse{Text: fmt.Sprintf(billingCopy["usage.you_use"], capAmount(c, n))} |
| } |
| + if c == capPDF { |
| + return &billingUse{Text: fmt.Sprintf(billingCopy["usage.pdf"], n, limit), Level: useLevel(c, n, limit)} |
| + } |
| return &billingUse{Text: fmt.Sprintf(billingCopy[key], capAmount(c, n), capAmount(c, limit)), Level: useLevel(c, n, limit)} |
| } |
| @@ -183,12 +187,16 @@ func addUsage(v *billingView, cat *plans.Catalog, rows []capState, members int, |
| if v.Change != nil { |
| packs(v.Change.Packs) |
| } |
| - if !inPacks { |
| + if !inPacks || v.limits.PDFRendersMonth > 0 { |
| // No pack row carries it (a member, or no packs to change): the |
| // summary lists it instead. |
| labels := map[capID]string{capRunningThings: "usage.label.running", capStorage: "usage.label.storage", |
| - capEmail: "usage.label.email", capBandwidth: "usage.label.bandwidth"} |
| + capEmail: "usage.label.email", capBandwidth: "usage.label.bandwidth", capPDF: "usage.label.pdf"} |
| for _, c := range usageCaps { |
| + // PDFs have no pack row, so their usage always belongs in the summary. |
| + if inPacks && c != capPDF { |
| + continue |
| + } |
| if use := useOfLimit(used, c, capLimit(*v.limits, c)); use != nil { |
| u.Rows = append(u.Rows, billingUsageRow{Label: billingCopy[labels[c]], Use: use}) |
| } |
diff --git a/internal/console/billingusage_test.go b/internal/console/billingusage_test.go| index 80b63f05e..5cd6d5427 100644 |
| --- a/internal/console/billingusage_test.go |
| +++ b/internal/console/billingusage_test.go |
| @@ -336,3 +336,35 @@ func TestBillingPageUsageMakesNoRequests(t *testing.T) { |
| t.Errorf("the billing page made %d deployment-store requests, want none: %v", len(counter.calls), counter.calls) |
| } |
| } |
| + |
| +func TestBillingPageUsagePDF(t *testing.T) { |
| + for _, paid := range []bool{false, true} { |
| + name := "buy" |
| + if paid { |
| + name = "paid" |
| + } |
| + t.Run(name, func(t *testing.T) { |
| + pf := newBillingPageFixture(t) |
| + pf.srv.cfg.PlanCatalog = pdfPlanCatalog(t, 100) |
| + if paid { |
| + pf.payFor(t, "personal", map[string]int{"email": 1}, nil) |
| + } |
| + now := time.Now().UTC() |
| + putCapRows(t, pf, usageRow(capPDF, 85, now), usageRow(capEmail, 10, now)) |
| + _, body := pf.page(t, "") |
| + for _, want := range []string{"PDFs", "85 of 100 PDFs this month", "100 PDFs a month"} { |
| + if !strings.Contains(body, want) { |
| + t.Errorf("page missing %q", want) |
| + } |
| + } |
| + if !strings.Contains(body, `<dd class="use use-warn">85 of 100 PDFs this month</dd>`) { |
| + t.Error("PDF usage not warned at 85 percent") |
| + } |
| + putCapRows(t, pf, usageRow(capPDF, 85, now.AddDate(0, -1, 0))) |
| + _, body = pf.page(t, "") |
| + if strings.Contains(body, "85 of 100 PDFs this month") { |
| + t.Error("stale PDF count displayed") |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/console/plancaps_copy.go b/internal/console/plancaps_copy.go| index 92a31958f..707ad171c 100644 |
| --- a/internal/console/plancaps_copy.go |
| +++ b/internal/console/plancaps_copy.go |
| @@ -19,6 +19,7 @@ var capCopy = map[string]string{ |
| "cli.cap.daemon": "this release declares the daemon capability, which keeps an app running all the time. on shared boxes apps sleep when idle, so place the app on your own boxes (a fleet) to run it, or ship it without daemon", |
| "cli.cap.always_on": "on shared boxes apps sleep when idle, so sidecars cannot be set to stay awake. place the app on your own boxes (a fleet) to keep them running, or remove hibernate: false", |
| "cli.cap.schedule": "on shared boxes this plan runs schedules at most every %d minutes. choose a longer interval, place the app on your own boxes (a fleet), or move to a plan that allows more", |
| + "cli.cap.pdf_renders": "this account has rendered %d PDFs this month, twice its monthly limit of %d. rendering starts again on the 1st of the UTC month, or move to a larger plan", |
| // Plans 6b: the member cap and the free-account refusal above. DRAFTS |
| // for the Luna pass. |
| "browser.cap.members": "This plan has room for %d members. Move to a team plan to add more.", |
| @@ -38,6 +39,7 @@ var planNoticeCopy = map[string]string{ |
| "usage.running_things": "%d of %d apps and instances", |
| "usage.storage": "%s of %s object storage", |
| "usage.email": "%d of %d emails today", |
| + "usage.pdf": "%d of %d PDFs this month", |
| "usage.bandwidth": "%s of %s bandwidth this month", |
| "usage.awake_hours": "%d of %d awake hours this month", |
| "banner.warn": "This account has used %s. If it goes over, nothing changes during the grace period.", |
| @@ -52,6 +54,7 @@ var planNoticeCopy = map[string]string{ |
| // Plans 4b: an after-grace stage in force. Approved by delegation (Luna, |
| // docs/superpowers/specs/LUNA-COPY-RESULT-PLANS-4B.md). |
| "banner.email_paused": "Email is paused until midnight UTC: this account sent %s.", |
| + "banner.pdf_refused": "This account has used twice its PDF allowance this month. New PDFs are refused until the 1st of the UTC month, or until it moves to a larger plan.", |
| "cli.email_paused": "email is paused until midnight utc: this account sent %s", |
| "banner.storage_denied": "New uploads to this account's storage are refused: %s. Downloads and deletes still work.", |
| "cli.storage_denied": "new uploads to this account's storage are refused: %s. downloads and deletes still work", |
diff --git a/internal/console/planexempt_test.go b/internal/console/planexempt_test.go| index 3e692fcab..a2873c397 100644 |
| --- a/internal/console/planexempt_test.go |
| +++ b/internal/console/planexempt_test.go |
| @@ -300,7 +300,7 @@ var planExemptSites = []string{ |
| // Limits (req 1). |
| "EnsureDefaultPlans", "publishAccountLimits", "EffectiveLimits", |
| // Caps and lifecycle (req 2). |
| - "checkMemberCap", "lapseEligible", "planBanner", "writePlanWarnings", |
| + "checkMemberCap", "pdfPlanCheck", "lapseEligible", "planBanner", "writePlanWarnings", |
| "transitionAccountPlan", "membershipTransition", |
| // Free accounts (req 3). |
| "checkNewFreeAccount", |
diff --git a/internal/console/plangrace.go b/internal/console/plangrace.go| index dbbbda11f..5b6b5e57a 100644 |
| --- a/internal/console/plangrace.go |
| +++ b/internal/console/plangrace.go |
| @@ -15,13 +15,14 @@ const ( |
| capStorage capID = "storage" // bytes, per account |
| capEmail capID = "email" // sends, per UTC day |
| capBandwidth capID = "bandwidth" // bytes, per UTC month |
| + capPDF capID = "pdf" // renders, per UTC month |
| capAwakeHours capID = "awake_hours" // hours, per UTC month |
| capSidecars capID = "sidecars" // workers beyond the per-app cap, summed; lapse only |
| capCustomDomains capID = "custom_domains" // custom domains on a plan without them; lapse only |
| ) |
| // capOrder is the order caps are listed in, everywhere. |
| -var capOrder = []capID{capRunningThings, capStorage, capEmail, capBandwidth, capAwakeHours, capSidecars, capCustomDomains} |
| +var capOrder = []capID{capRunningThings, capStorage, capEmail, capBandwidth, capPDF, capAwakeHours, capSidecars, capCustomDomains} |
| // leftoverCap names the caps only a lapse measures (plans 4d): what an |
| // account kept from a plan it no longer has. Their level is ok (nothing |
| @@ -62,27 +63,27 @@ func capPeriod(c capID, now time.Time) string { |
| switch c { |
| case capEmail: |
| return now.UTC().Format("2006-01-02") |
| - case capBandwidth, capAwakeHours: |
| + case capBandwidth, capPDF, capAwakeHours: |
| return now.UTC().Format("2006-01") |
| } |
| return "" |
| } |
| -// hasCeiling: email, bandwidth and awake hours give grace "up to 2x" |
| +// hasCeiling: email, bandwidth, PDFs and awake hours give grace "up to 2x" |
| // (spec §6), so 2x is a level of its own. Counts and sizes do not. |
| func hasCeiling(c capID) bool { |
| - return c == capEmail || c == capBandwidth || c == capAwakeHours |
| + return c == capEmail || c == capBandwidth || c == capPDF || c == capAwakeHours |
| } |
| // graceEnd is when grace started at first runs out (spec §6): 7 days for |
| // counts and sizes, the rest of the UTC day for email, the rest of the |
| -// UTC month for bandwidth and awake hours. |
| +// UTC month for bandwidth, PDFs and awake hours. |
| func graceEnd(c capID, first time.Time) time.Time { |
| u := first.UTC() |
| switch c { |
| case capEmail: |
| return time.Date(u.Year(), u.Month(), u.Day()+1, 0, 0, 0, 0, time.UTC) |
| - case capBandwidth, capAwakeHours: |
| + case capBandwidth, capPDF, capAwakeHours: |
| return time.Date(u.Year(), u.Month()+1, 1, 0, 0, 0, 0, time.UTC) |
| } |
| return u.Add(7 * 24 * time.Hour) |
diff --git a/internal/console/plangracepass.go b/internal/console/plangracepass.go| index 949ff2fe6..683b95238 100644 |
| --- a/internal/console/plangracepass.go |
| +++ b/internal/console/plangracepass.go |
| @@ -308,6 +308,9 @@ func planNoticesOf(states []capState, now time.Time, stage func(capState) string |
| // planNoticeText renders one notice for a surface: "banner", "cli" or |
| // "email". |
| func planNoticeText(n planNotice, surface string) string { |
| + if n.Stage == "pdf_refused" && surface == "banner" { |
| + return planNoticeCopy["banner.pdf_refused"] |
| + } |
| use := usagePhrase(n) |
| if n.Stage == "lapse_grace" { |
| return fmt.Sprintf(planNoticeCopy[surface+".lapse_grace"], use, n.GraceEnds.UTC().Format("2 January 2006")) |
| @@ -451,6 +454,8 @@ func (s *Server) planStage(acct *Account, now time.Time) func(capState) string { |
| return stage |
| } |
| switch { |
| + case st.Cap == capPDF && st.Period == capPeriod(capPDF, now) && l.PDFRendersMonth > 0 && st.Used/2 >= int64(l.PDFRendersMonth): |
| + return "pdf_refused" |
| case st.Cap == capEmail && pauseAt > 0 && st.Used >= pauseAt: |
| return "email_paused" |
| case st.Cap == capStorage && storageDenyDue(st, now): |
diff --git a/internal/console/planmeasure.go b/internal/console/planmeasure.go| index 4b6edd7da..e18c1b98a 100644 |
| --- a/internal/console/planmeasure.go |
| +++ b/internal/console/planmeasure.go |
| @@ -55,6 +55,10 @@ func (s *Server) measureCaps(ctx context.Context, acct *Account, l *plans.Limits |
| n, err := s.store.AccountSends(ctx, acct.Sqid, usage.DayOf(now)) |
| put(capEmail, n, int64(l.EmailPerDay), err) |
| } |
| + if l.PDFRendersMonth > 0 { |
| + n, err := s.store.AccountPDFRenders(ctx, acct.Sqid, pdfMonthStart(now)) |
| + put(capPDF, n, int64(l.PDFRendersMonth), err) |
| + } |
| return got, errs |
| } |
diff --git a/internal/console/planpdf.go b/internal/console/planpdf.go| new file mode 100644 |
| index 000000000..46cefeefc |
| --- /dev/null |
| +++ b/internal/console/planpdf.go |
| @@ -0,0 +1,30 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "time" |
| +) |
| + |
| +func (s *Server) pdfPlanCheck(ctx context.Context, acct *Account, now time.Time) error { |
| + if s.store.planExempt(acct.ID) { |
| + return nil |
| + } |
| + l, err := s.EffectiveLimits(acct) |
| + if err != nil || l == nil || l.PDFRendersMonth == 0 { |
| + return err |
| + } |
| + used, err := s.store.AccountPDFRenders(ctx, acct.Sqid, pdfMonthStart(now)) |
| + if err != nil { |
| + return err |
| + } |
| + limit := int64(l.PDFRendersMonth) |
| + if used/2 >= limit { |
| + return &planCapError{msg: capMessage("cli.cap.pdf_renders", used, limit)} |
| + } |
| + return nil |
| +} |
| + |
| +func pdfMonthStart(now time.Time) time.Time { |
| + u := now.UTC() |
| + return time.Date(u.Year(), u.Month(), 1, 0, 0, 0, 0, time.UTC) |
| +} |
diff --git a/internal/console/planpdf_test.go b/internal/console/planpdf_test.go| new file mode 100644 |
| index 000000000..7ffbe0d0f |
| --- /dev/null |
| +++ b/internal/console/planpdf_test.go |
| @@ -0,0 +1,164 @@ |
| +package console |
| + |
| +import ( |
| + "errors" |
| + "math" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/plans" |
| +) |
| + |
| +const pdfCapAt200 = "this account has rendered 200 PDFs this month, twice its monthly limit of 100. rendering starts again on the 1st of the UTC month, or move to a larger plan" |
| +const pdfCeilingBanner = "This account has used twice its PDF allowance this month. New PDFs are refused until the 1st of the UTC month, or until it moves to a larger plan." |
| + |
| +func pdfPlanCatalog(t *testing.T, limit int) *plans.Catalog { |
| + t.Helper() |
| + cat := examplePlanCatalog(t) |
| + for name, p := range cat.Plans { |
| + if p.Team == nil { |
| + p.Limits.PDFRendersMonth = limit |
| + cat.Plans[name] = p |
| + } |
| + } |
| + return cat |
| +} |
| + |
| +func recordPlanPDFs(t *testing.T, st *Store, account string, n int, at time.Time) { |
| + t.Helper() |
| + for range n { |
| + if err := st.RecordPDFRender(t.Context(), pdfRenderRow{Account: account, App: "shop", Outcome: pdfRendered, Status: 200, At: at}); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| +} |
| + |
| +func TestPDFPlanCheck(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + acct := planAccount(t, fx, 501) |
| + now := time.Now().UTC() |
| + fx.srv.cfg.PlanCatalog = pdfPlanCatalog(t, 100) |
| + recordPlanPDFs(t, fx.st, acct.Sqid, 199, now) |
| + if err := fx.srv.pdfPlanCheck(t.Context(), acct, now); err != nil { |
| + t.Fatalf("199 renders: %v", err) |
| + } |
| + recordPlanPDFs(t, fx.st, acct.Sqid, 1, now) |
| + var capErr *planCapError |
| + if err := fx.srv.pdfPlanCheck(t.Context(), acct, now); !errors.As(err, &capErr) || capErr.Error() != pdfCapAt200 { |
| + t.Fatalf("200 renders: %v", err) |
| + } |
| + next := time.Date(now.Year(), now.Month()+1, 1, 0, 0, 0, 0, time.UTC) |
| + if err := fx.srv.pdfPlanCheck(t.Context(), acct, next); err != nil { |
| + t.Fatalf("new month: %v", err) |
| + } |
| + fx.srv.cfg.PlanCatalog = pdfPlanCatalog(t, 101) |
| + if err := fx.srv.pdfPlanCheck(t.Context(), acct, now); err != nil { |
| + t.Fatalf("larger plan: %v", err) |
| + } |
| + fx.srv.cfg.PlanCatalog = pdfPlanCatalog(t, 0) |
| + if err := fx.srv.pdfPlanCheck(t.Context(), acct, now); err != nil { |
| + t.Fatalf("zero limit: %v", err) |
| + } |
| + fx.srv.cfg.PlanCatalog = pdfPlanCatalog(t, math.MaxInt) |
| + if err := fx.srv.pdfPlanCheck(t.Context(), acct, now); err != nil { |
| + t.Fatalf("large limit: %v", err) |
| + } |
| + fx.srv.cfg.PlanCatalog = pdfPlanCatalog(t, 100) |
| + ops, err := fx.st.AccountBySqid(fx.sqid) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + recordPlanPDFs(t, fx.st, ops.Sqid, 500, now) |
| + if err := fx.srv.pdfPlanCheck(t.Context(), ops, now); err != nil { |
| + t.Fatalf("exempt: %v", err) |
| + } |
| + fx.srv.cfg.PlanCatalog = nil |
| + if err := fx.srv.pdfPlanCheck(t.Context(), acct, now); err != nil { |
| + t.Fatalf("no catalog: %v", err) |
| + } |
| + if got := sponsorUnlimited().PDFRendersMonth; got != sponsorMost { |
| + t.Fatalf("sponsored PDF limit = %d", got) |
| + } |
| +} |
| + |
| +func TestPDFCapLevels(t *testing.T) { |
| + for used, want := range map[int64]capLevel{79: levelOK, 80: levelWarn, 100: levelWarn, 101: levelOver, 199: levelOver, 200: levelCeiling} { |
| + if got := levelOf(capPDF, used, 100); got != want { |
| + t.Errorf("used %d: %s, want %s", used, got, want) |
| + } |
| + } |
| + now := time.Date(2026, 12, 1, 0, 30, 0, 0, time.FixedZone("east", 3600)) |
| + if got := capPeriod(capPDF, now); got != "2026-11" { |
| + t.Errorf("period = %s", got) |
| + } |
| + end := time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC) |
| + if got := graceEnd(capPDF, now); !got.Equal(end) { |
| + t.Errorf("grace end = %s", got) |
| + } |
| +} |
| + |
| +func TestMeasureCapsPDF(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + acct := planAccount(t, fx, 501) |
| + // The next month locally is still this month in UTC. |
| + today := time.Now().UTC() |
| + now := time.Date(today.Year(), today.Month()+1, 1, 0, 30, 0, 0, time.FixedZone("east", 3600)) |
| + month := time.Date(today.Year(), today.Month(), 1, 0, 0, 0, 0, time.UTC) |
| + recordPlanPDFs(t, fx.st, acct.Sqid, 3, month) |
| + recordPlanPDFs(t, fx.st, acct.Sqid, 2, month.Add(-time.Second)) |
| + recordPlanPDFs(t, fx.st, fx.sqid, 4, month) |
| + for _, outcome := range []pdfOutcome{pdfRefused, pdfFailed, pdfAborted, pdfEngineError} { |
| + if err := fx.st.RecordPDFRender(t.Context(), pdfRenderRow{Account: acct.Sqid, App: "shop", Outcome: outcome, At: now}); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + l := &plans.Limits{PDFRendersMonth: 100} |
| + got, errs := fx.srv.measureCaps(t.Context(), acct, l, now) |
| + if len(errs) != 0 || got[capPDF] != (capMeasure{Used: 3, Limit: 100}) { |
| + t.Fatalf("measure = %v, %v", got, errs) |
| + } |
| + got, errs = fx.srv.measureCaps(t.Context(), acct, &plans.Limits{}, now) |
| + if len(got) != 0 || len(errs) != 0 { |
| + t.Fatalf("zero limit = %v, %v", got, errs) |
| + } |
| + if _, err := fx.st.db.Exec(`DROP TABLE pdf_renders`); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, errs = fx.srv.measureCaps(t.Context(), acct, l, now) |
| + if _, ok := got[capPDF]; ok || errs[capPDF] == nil { |
| + t.Fatalf("failed measure = %v, %v", got, errs) |
| + } |
| + fx.srv.cfg.PlanCatalog = pdfPlanCatalog(t, 100) |
| + if err := fx.srv.pdfPlanCheck(t.Context(), acct, now); err == nil || isCap(err) { |
| + t.Fatalf("failed count = %v", err) |
| + } |
| +} |
| + |
| +func TestPDFCapBanner(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + acct := planAccount(t, fx, 501) |
| + fx.srv.cfg.PlanCatalog = pdfPlanCatalog(t, 100) |
| + now := time.Now().UTC() |
| + st := evaluateCap(nil, capPDF, 200, 100, now) |
| + st.AccountID = acct.ID |
| + if err := fx.st.PutCapState(st); err != nil { |
| + t.Fatal(err) |
| + } |
| + lines, _ := fx.srv.planBanner(acct, RoleOwner, now) |
| + if len(lines) != 1 || lines[0] != pdfCeilingBanner { |
| + t.Fatalf("banner = %q", lines) |
| + } |
| + if got := usagePhrase(planNotice{Cap: capPDF, Used: 200, Limit: 100}); got != "200 of 100 PDFs this month" { |
| + t.Fatalf("usage = %q", got) |
| + } |
| + next := time.Date(now.Year(), now.Month()+1, 1, 0, 0, 0, 0, time.UTC) |
| + if lines, _ := fx.srv.planBanner(acct, RoleOwner, next); len(lines) != 0 { |
| + t.Fatalf("stale banner = %q", lines) |
| + } |
| + fx.srv.cfg.PlanCatalog = pdfPlanCatalog(t, 200) |
| + lines, _ = fx.srv.planBanner(acct, RoleOwner, now) |
| + if strings.Contains(strings.Join(lines, " "), pdfCeilingBanner) { |
| + t.Fatalf("larger plan still refuses: %q", lines) |
| + } |
| +} |
diff --git a/internal/console/plansponsor.go b/internal/console/plansponsor.go| index 7439dcd89..83b7da62d 100644 |
| --- a/internal/console/plansponsor.go |
| +++ b/internal/console/plansponsor.go |
| @@ -89,6 +89,7 @@ func sponsorUnlimited() plans.Limits { |
| StorageSelfServe: true, |
| EmailPerDay: sponsorMost, |
| BandwidthBytesMonth: sponsorMost, |
| + PDFRendersMonth: sponsorMost, |
| CustomDomains: true, |
| Fleets: true, |
| MinScheduleSeconds: 1, |
diff --git a/internal/plans/catalog.go b/internal/plans/catalog.go| index f863d9f85..d8f5cfc0b 100644 |
| --- a/internal/plans/catalog.go |
| +++ b/internal/plans/catalog.go |
| @@ -38,6 +38,7 @@ type Limits struct { |
| StorageSelfServe bool `json:"storage_self_serve,omitempty"` |
| EmailPerDay int `json:"email_per_day,omitempty"` |
| BandwidthBytesMonth int64 `json:"bandwidth_bytes_month,omitempty"` |
| + PDFRendersMonth int `json:"pdf_renders_month,omitempty"` |
| CustomDomains bool `json:"custom_domains,omitempty"` |
| Fleets bool `json:"fleets,omitempty"` |
| MinScheduleSeconds int `json:"min_schedule_seconds,omitempty"` |
| @@ -230,7 +231,7 @@ func (c *Catalog) validate() error { |
| func (l Limits) nonNegative() error { |
| if l.RunningThings < 0 || l.SidecarsPerApp < 0 || l.IdleSeconds < 0 || l.AwakeHoursMonth < 0 || |
| l.DiskBytes < 0 || l.StorageBytes < 0 || l.EmailPerDay < 0 || l.BandwidthBytesMonth < 0 || |
| - l.MinScheduleSeconds < 0 || l.HistoryDays < 0 || |
| + l.MinScheduleSeconds < 0 || l.HistoryDays < 0 || l.PDFRendersMonth < 0 || |
| l.RateClientShare < 0 || l.RatePerSecond < 0 || l.RateBurst < 0 { |
| return errors.New("limits may not be negative") |
| } |
| @@ -361,6 +362,7 @@ func (l Limits) generous(o Limits) Limits { |
| l.StorageBytes = max(l.StorageBytes, o.StorageBytes) |
| l.EmailPerDay = max(l.EmailPerDay, o.EmailPerDay) |
| l.BandwidthBytesMonth = max(l.BandwidthBytesMonth, o.BandwidthBytesMonth) |
| + l.PDFRendersMonth = max(l.PDFRendersMonth, o.PDFRendersMonth) |
| l.HistoryDays = max(l.HistoryDays, o.HistoryDays) |
| l.RateClientShare = generousRate(l.RateClientShare, o.RateClientShare) |
| l.RatePerSecond = generousRate(l.RatePerSecond, o.RatePerSecond) |
diff --git a/internal/plans/catalog_test.go b/internal/plans/catalog_test.go| index eb1127ecf..a8d5e7e48 100644 |
| --- a/internal/plans/catalog_test.go |
| +++ b/internal/plans/catalog_test.go |
| @@ -278,3 +278,31 @@ func TestCatalogSponsorAccountsBefore(t *testing.T) { |
| } |
| } |
| } |
| + |
| +func TestLimitsPDFRendersMonth(t *testing.T) { |
| + l := Limits{PDFRendersMonth: 100} |
| + b, err := json.Marshal(l) |
| + if err != nil || string(b) != `{"pdf_renders_month":100}` { |
| + t.Fatalf("marshal = %s, %v", b, err) |
| + } |
| + var got Limits |
| + if err := json.Unmarshal(b, &got); err != nil || got.PDFRendersMonth != 100 { |
| + t.Fatalf("round trip = %+v, %v", got, err) |
| + } |
| + if err := (Limits{PDFRendersMonth: -1}).nonNegative(); err == nil { |
| + t.Fatal("negative PDF limit accepted") |
| + } |
| + for _, n := range []int{50, 200} { |
| + if got := l.generous(Limits{PDFRendersMonth: n}).PDFRendersMonth; got != max(100, n) { |
| + t.Fatalf("generous = %d", got) |
| + } |
| + } |
| + c := exampleCatalog(t) |
| + p := c.Plans["personal"] |
| + p.Limits.PDFRendersMonth = 100 |
| + c.Plans["personal"] = p |
| + team, err := c.Effective("community", nil, nil, 15) |
| + if err != nil || team.PDFRendersMonth != 300 { |
| + t.Fatalf("pooled PDF limit = %d, %v", team.PDFRendersMonth, err) |
| + } |
| +} |
diff --git a/internal/plans/team.go b/internal/plans/team.go| index 5602ab129..e3064ca18 100644 |
| --- a/internal/plans/team.go |
| +++ b/internal/plans/team.go |
| @@ -32,7 +32,7 @@ var ErrTeamMembers = errors.New("team member count out of range") |
| // PooledLimits are the limits a team plan takes from its base, multiplied |
| // per member, by JSON name. Disk is not one of them (Call 7). |
| -var PooledLimits = []string{"running_things", "awake_hours_month", "storage_bytes", "email_per_day", "bandwidth_bytes_month"} |
| +var PooledLimits = []string{"running_things", "awake_hours_month", "storage_bytes", "email_per_day", "bandwidth_bytes_month", "pdf_renders_month"} |
| // pooledFields is PooledLimits as accessors, in the same order (a test |
| // keeps the two equal). |
| @@ -46,6 +46,7 @@ var pooledFields = []struct { |
| {"storage_bytes", func(l Limits) int64 { return l.StorageBytes }, func(l *Limits, v int64) { l.StorageBytes = v }}, |
| {"email_per_day", func(l Limits) int64 { return int64(l.EmailPerDay) }, func(l *Limits, v int64) { l.EmailPerDay = int(v) }}, |
| {"bandwidth_bytes_month", func(l Limits) int64 { return l.BandwidthBytesMonth }, func(l *Limits, v int64) { l.BandwidthBytesMonth = v }}, |
| + {"pdf_renders_month", func(l Limits) int64 { return int64(l.PDFRendersMonth) }, func(l *Limits, v int64) { l.PDFRendersMonth = int(v) }}, |
| } |
| // Billed is the member count the account is billed and limited at: never |