carlos / platform Public

plans: monthly media minutes, audio at a tenth

Task 6 of media conversion plan 2: media_minutes_month, handled as
pdf_renders_month is (spec §7.3).

- plans.Limits gains MediaMinutesMonth. Packs may raise it (pre-flight
  F8): additive(), the validation message, Effective's addPack and the
  ceiling clamp; a pack never turns an unlimited (0) plan into a limit.
- Console cap "media": monthly, ceiling at 2x, grace to the 1st of next
  month, after PDFs in capOrder. measureCaps uses mediajobs'
  ChargedMinutes, the door's figure. media_refused stage at twice the
  limit; banner and CLI notices from the deck, digits grouped.
- Billing page: Media minutes in usage, limit.media on plan cards and
  the media pack row; the summary lists media when no pack row does.
- mediaAllowance reads the real field; sponsorship and its file give
  unlimited media minutes; planExemptSites covers mediaAllowance.
- Test fixtures carry the proposed values (Free 30, Personal 600,
  Community 1,200, Business 12,000, a 1,000-minute pack). The production
  catalogs and price books are not changed here.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 50cd6029c616bd21c2fc73537c125e0d758780e0 parent f830667
23 files changed, +738 −39
  • deploy/billing/sponsored-unlimited.json +1 −0
  • docs/site/plans.md +1 −1
  • internal/console/apimedia_test.go +67 −0
  • internal/console/billingpage.go +6 −0
  • internal/console/billingpage_copy.go +3 −0
  • internal/console/billingsync_test.go +7 −1
  • internal/console/billingusage.go +35 −20
  • internal/console/billingusage_test.go +64 −0
  • internal/console/mediawire.go +2 −4
  • internal/console/opbilling_store.go +1 −1
  • internal/console/plancaps_copy.go +5 −0
  • internal/console/planexempt_test.go +1 −1
  • internal/console/plangrace.go +9 −7
  • internal/console/plangracepass.go +9 −1
  • internal/console/planmeasure.go +7 −0
  • internal/console/planmedia_test.go +272 −0
  • internal/console/plansponsor.go +1 −0
  • internal/console/plansponsor_test.go +1 −1
  • internal/plans/catalog.go +11 −2
  • internal/plans/catalog_test.go +106 −0
  • internal/plans/repo_catalog_test.go +3 −0
  • internal/plans/testdata/media-catalog.json +102 −0
  • internal/plans/testdata/media-pricebook.json +24 −0
diff --git a/deploy/billing/sponsored-unlimited.json b/deploy/billing/sponsored-unlimited.json
index be445a80c..11e72b164 100644
--- a/deploy/billing/sponsored-unlimited.json
+++ b/deploy/billing/sponsored-unlimited.json
@@ -10,6 +10,7 @@
"email_per_day": 2305843009213693951,
"bandwidth_bytes_month": 2305843009213693951,
"pdf_renders_month": 2305843009213693951,
+ "media_minutes_month": 2305843009213693951,
"custom_domains": true,
"fleets": true,
"min_schedule_seconds": 1,
diff --git a/docs/site/plans.md b/docs/site/plans.md
index a6c3709c3..0fe6418d7 100644
--- a/docs/site/plans.md
+++ b/docs/site/plans.md
@@ -32,7 +32,7 @@ The console reads the file when it starts. If the file is missing or wrong, the
}
```
-Every account without a plan of its own is on `default_plan`. Packs may only raise counts and sizes: apps and instances, disk, storage, email and bandwidth. A ceiling is the most any plan with packs can reach.
+Every account without a plan of its own is on `default_plan`. Packs may only raise counts and sizes: apps and instances, disk, storage, email, bandwidth and media minutes. A ceiling is the most any plan with packs can reach.
Set `pdf_renders_month` in a plan's limits to give your account a monthly PDF allowance shared by its apps. A value of 0 means no monthly limit. The PDF service's fair-use limits still apply.
diff --git a/internal/console/apimedia_test.go b/internal/console/apimedia_test.go
index ffb4c08a9..8d90e3b2b 100644
--- a/internal/console/apimedia_test.go
+++ b/internal/console/apimedia_test.go
@@ -1088,3 +1088,70 @@ func TestRepeatOfAJobThatFailedEarlierAnswersTheJob(t *testing.T) {
})
}
}
+
+// TestDoorRefusesAtTwiceTheLimit: with a plan catalog the door's cap is the
+// account's media_minutes_month (Task 6). 1,200 charged minutes on a limit
+// of 600 is 402 plan_limit with the deck's cli.cap.media_minutes and no
+// row; audio counts a tenth; a minute less, a media pack, or the ops
+// account's exemption admits it.
+func TestDoorRefusesAtTwiceTheLimit(t *testing.T) {
+ audio := func(f *mediaDoorFixture, id string, sourceMS int64) {
+ if _, err := f.st.db.Exec(`INSERT INTO media_jobs
+ (account, app, incarnation, job_id, key, etag, bytes, preset, class, bucket, state, submitted_at, settled, source_ms, ended_at)
+ VALUES (?, 'titogo', 'seeded', ?, 'uploads/seed.m4a', 'e', 1, 'audio-aac', 'short', 'b', 'done', ?, 1, ?, ?)`,
+ f.sqid, id, f.clock.UnixMilli(), sourceMS, f.clock.UnixMilli()); err != nil {
+ f.t.Fatal(err)
+ }
+ }
+ for _, tc := range []struct {
+ name string
+ setup func(f *mediaDoorFixture)
+ refuse bool
+ }{
+ {name: "twice the limit", refuse: true, setup: func(f *mediaDoorFixture) {
+ f.seed(f.sqid, "seeded-done", "done", 1200*60_000)
+ }},
+ {name: "audio at a tenth", refuse: true, setup: func(f *mediaDoorFixture) {
+ f.seed(f.sqid, "seeded-done", "done", 600*60_000)
+ audio(f, "seeded-audio", 6000*60_000)
+ }},
+ {name: "a minute under", setup: func(f *mediaDoorFixture) {
+ f.seed(f.sqid, "seeded-done", "done", 1199*60_000)
+ }},
+ {name: "a media pack", setup: func(f *mediaDoorFixture) {
+ f.srv.cfg.PlanCatalog = mediaPlanCatalog(f.t)
+ ops, err := f.st.AccountBySqid(f.sqid)
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ if _, err := f.st.SetAccountPlan(ops.ID, "personal", map[string]int{"media": 1}, PlanSourceOperator, nil, "test", "test", time.Now()); err != nil {
+ f.t.Fatal(err)
+ }
+ f.seed(f.sqid, "seeded-done", "done", 1200*60_000) // under 2 × 1,600
+ }},
+ {name: "ops account exempt", setup: func(f *mediaDoorFixture) {
+ f.st.planExemptID = OpsAccountID
+ f.seed(f.sqid, "seeded-done", "done", 5000*60_000)
+ }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ f := newMediaDoor(t, "code-media-twice-"+strings.ReplaceAll(tc.name, " ", "-"))
+ f.st.planExemptID = 0
+ f.srv.cfg.PlanCatalog = mediaLimitCatalog(t, 600)
+ f.setLimits(func(l *media.Limits) { l.AccountMinutes = 1 }) // the catalog's figure wins
+ tc.setup(f)
+ before := f.rows()
+ r := f.submit(mediaTestKey)
+ if !tc.refuse {
+ if r.status != 202 || f.rows() != before+1 {
+ t.Fatalf("answered %d %s, rows %d to %d", r.status, r.raw, before, f.rows())
+ }
+ return
+ }
+ wantMediaRefusal(t, r, 402, "plan_limit", capMessage("cli.cap.media_minutes", 1200, 600))
+ if n := f.rows(); n != before {
+ t.Fatalf("media_jobs went from %d to %d rows", before, n)
+ }
+ })
+ }
+}
diff --git a/internal/console/billingpage.go b/internal/console/billingpage.go
index c1ac964e6..908d947f2 100644
--- a/internal/console/billingpage.go
+++ b/internal/console/billingpage.go
@@ -731,6 +731,9 @@ func planIncludes(l plans.Limits, maxMembers int) []billingInclude {
if l.PDFRendersMonth > 0 {
add(fmt.Sprintf(billingCopy["limit.pdf"], billingCount(int64(l.PDFRendersMonth))))
}
+ if l.MediaMinutesMonth > 0 {
+ add(fmt.Sprintf(billingCopy["limit.media"], billingCount(int64(l.MediaMinutesMonth))))
+ }
if l.EmailPerHour > 0 {
add(fmt.Sprintf(freeStorageCopy["billing.limit.email_hour"], billingCount(int64(l.EmailPerHour))))
}
@@ -765,6 +768,9 @@ func packAdds(a plans.Limits) string {
if a.BandwidthBytesMonth > 0 {
parts = append(parts, fmt.Sprintf(billingCopy["limit.bandwidth"], billingBytes(a.BandwidthBytesMonth)))
}
+ if a.MediaMinutesMonth > 0 {
+ parts = append(parts, fmt.Sprintf(billingCopy["limit.media"], billingCount(int64(a.MediaMinutesMonth))))
+ }
if len(parts) == 0 {
return ""
}
diff --git a/internal/console/billingpage_copy.go b/internal/console/billingpage_copy.go
index 72857b984..53bf8283a 100644
--- a/internal/console/billingpage_copy.go
+++ b/internal/console/billingpage_copy.go
@@ -123,6 +123,7 @@ var billingCopy = map[string]string{
"limit.email": "%s emails a day",
"limit.pdf": "%s PDFs a month",
"limit.bandwidth": "%s bandwidth a month",
+ "limit.media": "%s media minutes a month", // the media conversion copy deck, approved 2026-11-17
"limit.domains": "Custom domains",
"limit.members": "Up to %d people", // approved by Paul, 2026-11-14 (#1057)
"limit.unlimited": "Unlimited", // in place of a number at the launch sponsorship's figure (plansponsor.go); DRAFT 2026-10-31
@@ -161,6 +162,7 @@ var billingCopy = map[string]string{
"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.media": "%s of %s media minutes this month", // the media conversion copy deck, approved 2026-11-17
"usage.unknown": "Usage not known yet",
"usage.disk": "Up to %s per app",
"usage.you_use": "You use %s",
@@ -169,5 +171,6 @@ var billingCopy = map[string]string{
"usage.label.storage": "Object storage",
"usage.label.email": "Email",
"usage.label.pdf": "PDFs",
+ "usage.label.media": "Media minutes", // the media conversion copy deck, approved 2026-11-17
"usage.label.bandwidth": "Bandwidth",
}
diff --git a/internal/console/billingsync_test.go b/internal/console/billingsync_test.go
index c0ec131f6..7b510a3e4 100644
--- a/internal/console/billingsync_test.go
+++ b/internal/console/billingsync_test.go
@@ -212,7 +212,13 @@ type billingFixture struct {
// price map and a Fake provider.
func testBillingConfig(t *testing.T, cat *plans.Catalog) (*BillingConfig, *billingtest.Fake) {
t.Helper()
- book, err := plans.LoadPriceBook("../plans/testdata/example-pricebook.json", cat)
+ return testBillingConfigFrom(t, cat, "../plans/testdata/example-pricebook.json")
+}
+
+// testBillingConfigFrom is testBillingConfig with the price book at path.
+func testBillingConfigFrom(t *testing.T, cat *plans.Catalog, path string) (*BillingConfig, *billingtest.Fake) {
+ t.Helper()
+ book, err := plans.LoadPriceBook(path, cat)
if err != nil {
t.Fatal(err)
}
diff --git a/internal/console/billingusage.go b/internal/console/billingusage.go
index a8986a318..d611d9e72 100644
--- a/internal/console/billingusage.go
+++ b/internal/console/billingusage.go
@@ -21,12 +21,12 @@ import (
// Disk is a per-app limit nothing measures centrally: its limit alone.
// usageCaps are the caps the page shows, in order.
-var usageCaps = []capID{capRunningThings, capStorage, capEmail, capBandwidth, capPDF}
+var usageCaps = []capID{capRunningThings, capStorage, capEmail, capBandwidth, capPDF, capMedia}
// usageCapLabels is each of usageCaps' label key in billingCopy: the usage
// summary's rows and the billing overview's nearest limit.
var usageCapLabels = map[capID]string{capRunningThings: "usage.label.running", capStorage: "usage.label.storage",
- capEmail: "usage.label.email", capBandwidth: "usage.label.bandwidth", capPDF: "usage.label.pdf"}
+ capEmail: "usage.label.email", capBandwidth: "usage.label.bandwidth", capPDF: "usage.label.pdf", capMedia: "usage.label.media"}
// 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.
@@ -86,6 +86,8 @@ func capLimit(l plans.Limits, c capID) int64 {
return l.BandwidthBytesMonth
case capPDF:
return int64(l.PDFRendersMonth)
+ case capMedia:
+ return int64(l.MediaMinutesMonth)
}
return 0
}
@@ -136,17 +138,28 @@ func useOfLimit(used map[capID]int64, c capID, limit int64) *billingUse {
if c == capPDF {
return &billingUse{Text: fmt.Sprintf(billingCopy["usage.pdf"], n, limit), Level: useLevel(c, n, limit)}
}
+ if c == capMedia {
+ return &billingUse{Text: fmt.Sprintf(billingCopy["usage.media"], billingCount(n), billingCount(limit)), Level: useLevel(c, n, limit)}
+ }
return &billingUse{Text: fmt.Sprintf(billingCopy[key], capAmount(c, n), capAmount(c, limit)), Level: useLevel(c, n, limit)}
}
+// packCap is the measured cap a pack raises, "" for none.
+func packCap(adds plans.Limits) capID {
+ for _, c := range usageCaps {
+ if capLimit(adds, c) > 0 {
+ return c
+ }
+ }
+ return ""
+}
+
// packUse is a pack row's use: of the limit the pack raises, at the
// account's limits today, or disk's limit alone; nil when the pack raises
// nothing the page measures.
func packUse(used map[capID]int64, adds, limits plans.Limits) *billingUse {
- for _, c := range usageCaps {
- if capLimit(adds, c) > 0 {
- return useOfLimit(used, c, capLimit(limits, c))
- }
+ if c := packCap(adds); c != "" {
+ return useOfLimit(used, c, capLimit(limits, c))
}
if adds.DiskBytes > 0 && limits.DiskBytes > 0 {
return &billingUse{Text: fmt.Sprintf(billingCopy["usage.disk"], billingBytes(limits.DiskBytes))}
@@ -164,10 +177,13 @@ func addUsage(v *billingView, cat *plans.Catalog, rows []capState, now time.Time
}
u := &billingUsageView{AsOf: fmt.Sprintf(billingCopy["usage.as_of"], oldest.UTC().Format("2006-01-02 15:04 UTC"))}
inPacks := false
+ carried := map[capID]bool{}
packs := func(ps []billingPackInput) {
for i := range ps {
- if ps[i].Use = packUse(used, cat.Packs[ps[i].Name].Adds, *v.limits); ps[i].Use != nil {
+ adds := cat.Packs[ps[i].Name].Adds
+ if ps[i].Use = packUse(used, adds, *v.limits); ps[i].Use != nil {
inPacks = true
+ carried[packCap(adds)] = true
}
}
}
@@ -192,21 +208,20 @@ func addUsage(v *billingView, cat *plans.Catalog, rows []capState, now time.Time
if v.Change != nil {
packs(v.Change.Packs)
}
- if !inPacks || v.limits.PDFRendersMonth > 0 {
- // No pack row carries it (a member, or no packs to change): the
- // summary lists it instead.
- 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[usageCapLabels[c]], Use: use})
- }
+ // No pack row carries it (a member, or no packs to change): the
+ // summary lists it instead. PDFs have no pack row, so their usage
+ // always belongs in the summary, and media minutes do whenever no
+ // media pack row shows them (a plan that offers no media pack).
+ for _, c := range usageCaps {
+ if inPacks && c != capPDF && (c != capMedia || carried[capMedia]) {
+ continue
}
- if len(u.Rows) == 0 {
- return
+ if use := useOfLimit(used, c, capLimit(*v.limits, c)); use != nil {
+ u.Rows = append(u.Rows, billingUsageRow{Label: billingCopy[usageCapLabels[c]], Use: use})
}
}
+ if !inPacks && len(u.Rows) == 0 {
+ return
+ }
v.Usage = u
}
diff --git a/internal/console/billingusage_test.go b/internal/console/billingusage_test.go
index b071d2ec4..8c63aecde 100644
--- a/internal/console/billingusage_test.go
+++ b/internal/console/billingusage_test.go
@@ -368,3 +368,67 @@ func TestBillingPageUsagePDF(t *testing.T) {
})
}
}
+
+// TestBillingPageUsageMedia: media minutes beside their limit, digits
+// grouped as the deck asks (pre-flight F10), warned from 80%. With no
+// media pack row (a member's view, or a plan without the pack) the summary
+// lists them; an owner's media pack row carries them instead, once.
+func TestBillingPageUsageMedia(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 = mediaLimitCatalog(t, 600)
+ if paid {
+ pf.payFor(t, "personal", map[string]int{"email": 1}, nil)
+ }
+ now := time.Now().UTC()
+ putCapRows(t, pf, usageRow(capMedia, 540, now), usageRow(capEmail, 10, now))
+ _, body := pf.page(t, "")
+ for _, want := range []string{"<dt>Media minutes</dt>", "600 media minutes a month",
+ `<dd class="use use-warn">540 of 600 media minutes this month</dd>`} {
+ if !strings.Contains(body, want) {
+ t.Errorf("page missing %q", want)
+ }
+ }
+ putCapRows(t, pf, usageRow(capMedia, 540, now.AddDate(0, -1, 0)))
+ _, body = pf.page(t, "")
+ if strings.Contains(body, "540 of 600 media minutes this month") {
+ t.Error("stale media count displayed")
+ }
+ })
+ }
+ for _, tc := range []struct {
+ plan string
+ packs map[string]int
+ used int64
+ use string
+ }{
+ {"personal", map[string]int{"media": 1}, 540, `<span class="small use">540 of 1,600 media minutes this month</span>`},
+ {"business", nil, 9600, `<span class="small use use-warn">9,600 of 12,000 media minutes this month</span>`},
+ } {
+ t.Run("pack/"+tc.plan, func(t *testing.T) {
+ pf := newBillingPageFixture(t)
+ cat := mediaPlanCatalog(t)
+ cfg, _ := testBillingConfigFrom(t, cat, mediaBookFixture)
+ cfg.Provider = pf.srv.cfg.Billing.Provider
+ pf.srv.cfg.PlanCatalog, pf.srv.cfg.Billing, pf.srv.billing = cat, cfg, newBillingRuntime(cfg)
+ pf.srv.billing.ready.Store(true)
+ pf.payFor(t, tc.plan, tc.packs, func(b *billingAccount) { b.Book = cfg.Book.Version })
+ putCapRows(t, pf, usageRow(capMedia, tc.used, time.Now().UTC()))
+ _, body := pf.page(t, "")
+ row := changeRow(t, body, "media")
+ for _, want := range []string{"Adds 1,000 media minutes a month", tc.use} {
+ if !strings.Contains(row, want) {
+ t.Errorf("media pack row missing %q:\n%s", want, row)
+ }
+ }
+ if strings.Contains(body, "<dt>Media minutes</dt>") {
+ t.Error("the summary repeats what the media pack row shows")
+ }
+ })
+ }
+}
diff --git a/internal/console/mediawire.go b/internal/console/mediawire.go
index 854a944f7..a4582a178 100644
--- a/internal/console/mediawire.go
+++ b/internal/console/mediawire.go
@@ -91,7 +91,5 @@ func (s *Server) mediaAllowance(ctx context.Context, account string) (int64, err
return minutes, nil
}
-// planMediaMinutes is the plan's media_minutes_month. Task 6 adds the
-// field to plans.Limits and reads it here; until then no plan limits
-// media minutes.
-func planMediaMinutes(l *plans.Limits) int64 { return 0 }
+// planMediaMinutes is the account's effective media_minutes_month.
+func planMediaMinutes(l *plans.Limits) int64 { return int64(l.MediaMinutesMonth) }
diff --git a/internal/console/opbilling_store.go b/internal/console/opbilling_store.go
index b9293fae8..67fc8b8dd 100644
--- a/internal/console/opbilling_store.go
+++ b/internal/console/opbilling_store.go
@@ -32,7 +32,7 @@ func (s *Store) BillingFunnel(now time.Time) (signedUp, withApp, active30 int, e
}
// NearestCaps is, per account, the cap closest to its limit at now. The
-// contract: only the five labelled caps (usageCaps, the caps the usage
+// contract: only the six labelled caps (usageCaps, the caps the usage
// summary names and that have approved labels); only rows of the current
// period (Period == capPeriod(cap, now), as the usage summary counts them);
// among rows with cap_limit > 0, the highest used / cap_limit; ties go to
diff --git a/internal/console/plancaps_copy.go b/internal/console/plancaps_copy.go
index ac8e002bf..358dd04b5 100644
--- a/internal/console/plancaps_copy.go
+++ b/internal/console/plancaps_copy.go
@@ -43,10 +43,13 @@ var planNoticeCopy = map[string]string{
"cli.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.pdf_over": "this account is over its PDF allowance: %s. at twice the allowance, new PDFs are refused until %s. move to a larger plan for more",
"banner.pdf_over": "This account is over its PDF allowance: %s. At twice the allowance, new PDFs are refused until %s. Move to a larger plan for more.",
+ "cli.media_over": "this account is over its media allowance: %s. at twice the allowance, new conversions are refused until %s. buy a media pack or move to a larger plan for more", // the media conversion copy deck, approved 2026-11-17
+ "banner.media_over": "This account is over its media allowance: %s. At twice the allowance, new conversions are refused until %s. Buy a media pack or move to a larger plan for more.", // the media conversion copy deck, approved 2026-11-17
"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.media": "%s of %s media minutes this month", // the media conversion copy deck, approved 2026-11-17
"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.",
@@ -62,6 +65,8 @@ var planNoticeCopy = map[string]string{
// 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.",
+ "banner.media_refused": "This account has used twice its media allowance this month. New conversions are refused until the 1st of the UTC month, or until it buys a media pack or moves to a larger plan.", // the media conversion copy deck, approved 2026-11-17
+ "cli.media_refused": "this account has used twice its media allowance this month. new conversions are refused until the 1st of the UTC month, or until it buys a media pack or moves to a larger plan", // the media conversion copy deck, approved 2026-11-17
"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 38155ed9c..47960557e 100644
--- a/internal/console/planexempt_test.go
+++ b/internal/console/planexempt_test.go
@@ -306,7 +306,7 @@ var planExemptSites = []string{
// Limits (req 1).
"EnsureDefaultPlans", "publishAccountLimits", "EffectiveLimits",
// Caps and lifecycle (req 2).
- "checkMemberCap", "pdfPlanCheck", "lapseEligible", "planBanner", "writePlanWarnings",
+ "checkMemberCap", "pdfPlanCheck", "mediaAllowance", "lapseEligible", "planBanner", "writePlanWarnings",
"transitionAccountPlan",
// Free accounts (req 3).
"checkNewFreeAccount",
diff --git a/internal/console/plangrace.go b/internal/console/plangrace.go
index 5b6b5e57a..3938b2a6a 100644
--- a/internal/console/plangrace.go
+++ b/internal/console/plangrace.go
@@ -16,13 +16,14 @@ const (
capEmail capID = "email" // sends, per UTC day
capBandwidth capID = "bandwidth" // bytes, per UTC month
capPDF capID = "pdf" // renders, per UTC month
+ capMedia capID = "media" // allowance minutes charged, per UTC month (internal/mediajobs)
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, capPDF, capAwakeHours, capSidecars, capCustomDomains}
+var capOrder = []capID{capRunningThings, capStorage, capEmail, capBandwidth, capPDF, capMedia, 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
@@ -63,27 +64,28 @@ func capPeriod(c capID, now time.Time) string {
switch c {
case capEmail:
return now.UTC().Format("2006-01-02")
- case capBandwidth, capPDF, capAwakeHours:
+ case capBandwidth, capPDF, capMedia, capAwakeHours:
return now.UTC().Format("2006-01")
}
return ""
}
-// 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.
+// hasCeiling: email, bandwidth, PDFs, media minutes 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 == capPDF || c == capAwakeHours
+ return c == capEmail || c == capBandwidth || c == capPDF || c == capMedia || 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, PDFs and awake hours.
+// UTC month for bandwidth, PDFs, media minutes 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, capPDF, capAwakeHours:
+ case capBandwidth, capPDF, capMedia, 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 29c5e97b1..632383a72 100644
--- a/internal/console/plangracepass.go
+++ b/internal/console/plangracepass.go
@@ -326,7 +326,7 @@ func planNoticeText(n planNotice, surface string) string {
return fmt.Sprintf(planNoticeCopy[surface+".lapse_grace"], use, n.GraceEnds.UTC().Format("2 January 2006"))
}
if f, ok := planNoticeCopy[surface+"."+n.Stage]; ok && n.Stage != "" {
- if n.Stage == "pdf_refused" {
+ if n.Stage == "pdf_refused" || n.Stage == "media_refused" {
return f
}
return fmt.Sprintf(f, use)
@@ -335,6 +335,9 @@ func planNoticeText(n planNotice, surface string) string {
if f, ok := planNoticeCopy[surface+".pdf_over"]; ok && n.Cap == capPDF {
return fmt.Sprintf(f, use, n.GraceEnds.UTC().Format("2 January 2006"))
}
+ if f, ok := planNoticeCopy[surface+".media_over"]; ok && n.Cap == capMedia {
+ return fmt.Sprintf(f, use, n.GraceEnds.UTC().Format("2 January 2006"))
+ }
return fmt.Sprintf(planNoticeCopy[surface+".over"], use, n.GraceEnds.UTC().Format("2 January 2006"))
}
return fmt.Sprintf(planNoticeCopy[surface+".warn"], use)
@@ -347,6 +350,9 @@ func usagePhrase(n planNotice) string {
return fmt.Sprintf(f, humanGB(n.Used), humanGB(n.Limit))
case capCustomDomains:
return fmt.Sprintf(f, n.Used)
+ case capMedia:
+ // The deck groups the digits: plan values reach 12,000.
+ return fmt.Sprintf(f, billingCount(n.Used), billingCount(n.Limit))
}
return fmt.Sprintf(f, n.Used, n.Limit)
}
@@ -472,6 +478,8 @@ func (s *Server) planStage(acct *Account, now time.Time) func(capState) string {
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 == capMedia && st.Period == capPeriod(capMedia, now) && l.MediaMinutesMonth > 0 && st.Used/2 >= int64(l.MediaMinutesMonth):
+ return "media_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 fec7cca24..4e013fd94 100644
--- a/internal/console/planmeasure.go
+++ b/internal/console/planmeasure.go
@@ -63,6 +63,13 @@ func (s *Server) measureCaps(ctx context.Context, acct *Account, l *plans.Limits
n, err := s.store.AccountPDFRenders(ctx, acct.Sqid, pdfMonthStart(now))
put(capPDF, n, int64(l.PDFRendersMonth), err)
}
+ if l.MediaMinutesMonth > 0 {
+ // The door's figure (mediaFairUse): settled charges in the UTC
+ // month each job ended, so a job that ends after midnight on the
+ // last day counts in the month it ended.
+ n, err := s.media.ChargedMinutes(ctx, acct.Sqid, pdfMonthStart(now))
+ put(capMedia, n, int64(l.MediaMinutesMonth), err)
+ }
return got, errs
}
diff --git a/internal/console/planmedia_test.go b/internal/console/planmedia_test.go
new file mode 100644
index 000000000..7e20591ca
--- /dev/null
+++ b/internal/console/planmedia_test.go
@@ -0,0 +1,272 @@
+package console
+
+import (
+ "fmt"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/media"
+ "github.com/carlosframework/platform/internal/plans"
+)
+
+// The media allowance (spec §7.3): media_minutes_month, handled as
+// pdf_renders_month is. The figures are mediajobs' charges: a done job
+// w × source_ms, any other settled job w × charged_ms, w in tenths (video
+// 10, audio 1), counted in the UTC month the job ended.
+
+// mediaCatalogFixture is plans' media fixture: the example catalog with
+// Free 30, Personal 600, Community 1,200 and Business 12,000 media
+// minutes, and a media pack of 1,000 on every paid plan. mediaBookFixture
+// prices it (USD 1200 / EUR 1000 / GBP 900 cents, provisional).
+const (
+ mediaCatalogFixture = "../plans/testdata/media-catalog.json"
+ mediaBookFixture = "../plans/testdata/media-pricebook.json"
+)
+
+func mediaPlanCatalog(t *testing.T) *plans.Catalog {
+ t.Helper()
+ c, err := plans.LoadCatalog(mediaCatalogFixture)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return c
+}
+
+// mediaLimitCatalog is the example catalog (no media pack) with every
+// plan's media_minutes_month at limit.
+func mediaLimitCatalog(t *testing.T, limit int) *plans.Catalog {
+ t.Helper()
+ cat := examplePlanCatalog(t)
+ for name, p := range cat.Plans {
+ p.Limits.MediaMinutesMonth = limit
+ cat.Plans[name] = p
+ }
+ return cat
+}
+
+// chargeMedia writes a settled media_jobs row for account that ended at
+// ended: a done row charged w × sourceMS, any other w × chargedMS.
+func chargeMedia(t *testing.T, st *Store, account, id, state, preset string, sourceMS, chargedMS int64, ended time.Time) {
+ t.Helper()
+ if _, err := st.db.Exec(`INSERT INTO media_jobs
+ (account, app, incarnation, job_id, key, etag, bytes, preset, class, bucket, state, submitted_at,
+ execution_id, settled, source_ms, charged_ms, ended_at)
+ VALUES (?, 'shop', 'inc', ?, 'uploads/a.mov', 'e', 1, ?, 'short', 'b', ?, ?, 'x', 1, ?, ?, ?)`,
+ account, id, preset, state, ended.Add(-time.Hour).UnixMilli(), sourceMS, chargedMS, ended.UnixMilli()); err != nil {
+ t.Fatal(err)
+ }
+}
+
+const videoMinute = int64(60_000)
+
+func TestMediaAllowance(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ ctx := t.Context()
+ allowance := func(sqid string) int64 {
+ t.Helper()
+ n, err := fx.srv.mediaAllowance(ctx, sqid)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return n
+ }
+ fx.srv.cfg.PlanCatalog = mediaLimitCatalog(t, 600)
+ if got := allowance(acct.Sqid); got != 600 {
+ t.Errorf("limit 600: %d", got)
+ }
+ if got := allowance(fx.sqid); got != 0 {
+ t.Errorf("exempt ops account: %d, want 0 (no limit)", got)
+ }
+ fx.srv.cfg.PlanCatalog = mediaLimitCatalog(t, 0)
+ if got := allowance(acct.Sqid); got != 0 {
+ t.Errorf("zero limit: %d", got)
+ }
+
+ // The fixture's plan values, a pack on top, and a sponsored account.
+ fx.srv.cfg.PlanCatalog = mediaPlanCatalog(t)
+ if got := allowance(acct.Sqid); got != 30 {
+ t.Errorf("free: %d, want 30", got)
+ }
+ if _, err := fx.st.SetAccountPlan(acct.ID, "personal", map[string]int{"media": 2}, PlanSourceOperator, nil, "test", "test", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if got := allowance(acct.Sqid); got != 2600 {
+ t.Errorf("personal with two media packs: %d, want 2600", got)
+ }
+ sponsored := sponsorUnlimited()
+ if _, err := fx.st.SetAccountPlan(acct.ID, "free", nil, PlanSourceSponsored, &sponsored, "test", "test", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if got := allowance(acct.Sqid); got != 0 {
+ t.Errorf("sponsored: %d, want 0 (no limit)", got)
+ }
+ if got := sponsorUnlimited().MediaMinutesMonth; got != sponsorMost {
+ t.Errorf("sponsored media limit = %d", got)
+ }
+
+ // No catalog: the deployment's one figure.
+ fx.srv.cfg.PlanCatalog = nil
+ fx.srv.cfg.MediaLimits.AccountMinutes = 45
+ if got := allowance(acct.Sqid); got != 45 {
+ t.Errorf("no catalog, account_minutes=45: %d", got)
+ }
+ if got := allowance(fx.sqid); got != 0 {
+ t.Errorf("exempt ops account with no catalog: %d", got)
+ }
+}
+
+func TestMediaCapLevels(t *testing.T) {
+ for used, want := range map[int64]capLevel{0: levelOK, 479: levelOK, 480: levelWarn, 600: levelWarn, 601: levelOver,
+ 1199: levelOver, 1200: levelCeiling, 5000: levelCeiling} {
+ if got := levelOf(capMedia, used, 600); got != want {
+ t.Errorf("used %d of 600: %s, want %s", used, got, want)
+ }
+ }
+ // A local December clock is still November in UTC.
+ now := time.Date(2026, 12, 1, 0, 30, 0, 0, time.FixedZone("east", 3600))
+ if got := capPeriod(capMedia, now); got != "2026-11" {
+ t.Errorf("period = %s", got)
+ }
+ if got, end := graceEnd(capMedia, now), time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC); !got.Equal(end) {
+ t.Errorf("grace end = %s", got)
+ }
+ if !hasCeiling(capMedia) || leftoverCap(capMedia) {
+ t.Error("media is a monthly cap with a ceiling")
+ }
+ for i, c := range capOrder {
+ if c == capPDF && (i+1 >= len(capOrder) || capOrder[i+1] != capMedia) {
+ t.Errorf("capOrder %v: media does not follow PDFs", capOrder)
+ }
+ }
+}
+
+func TestMeasureCapsMedia(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ ctx := t.Context()
+ today := time.Now().UTC()
+ month := time.Date(today.Year(), today.Month(), 1, 0, 0, 0, 0, time.UTC)
+ next := month.AddDate(0, 1, 0)
+ // The next month locally is still this month in UTC.
+ now := time.Date(next.Year(), next.Month(), 1, 0, 30, 0, 0, time.FixedZone("east", 3600))
+
+ // This month: a 10-minute video done, and an audio job that failed
+ // after 6 minutes of engine time (0.6 allowance minutes). 10.6 rounds
+ // up to 11.
+ chargeMedia(t, fx.st, acct.Sqid, "v10", "done", media.PresetVideo720p, 10*videoMinute, 99*videoMinute, month)
+ chargeMedia(t, fx.st, acct.Sqid, "a6", "failed", media.PresetAudioAAC, 99*videoMinute, 6*videoMinute, now)
+ // Not this month's: ended a second before it, or after midnight on
+ // its last day (Review Focus 4: charged in the month it ended).
+ chargeMedia(t, fx.st, acct.Sqid, "before", "done", media.PresetVideo720p, 7*videoMinute, 0, month.Add(-time.Second))
+ chargeMedia(t, fx.st, acct.Sqid, "after", "done", media.PresetVideo720p, 5*videoMinute, 0, next.Add(30*time.Second))
+ // Another account's job, and a running job's reservation, are not
+ // charged to this one.
+ chargeMedia(t, fx.st, fx.sqid, "other", "done", media.PresetVideo720p, 40*videoMinute, 0, month)
+ if _, err := fx.st.db.Exec(`INSERT INTO media_jobs (account, app, incarnation, job_id, key, etag, bytes, preset, class, bucket,
+ state, submitted_at, execution_id, granted_s, deadline_s, task_stopped) VALUES (?, 'shop', 'inc', 'run', 'k', 'e', 1,
+ 'video-720p', 'short', 'b', 'running', ?, 'x', 600, 900, 0)`, acct.Sqid, month.UnixMilli()); err != nil {
+ t.Fatal(err)
+ }
+
+ l := &plans.Limits{MediaMinutesMonth: 600}
+ got, errs := fx.srv.measureCaps(ctx, acct, l, now)
+ if len(errs) != 0 || got[capMedia] != (capMeasure{Used: 11, Limit: 600}) {
+ t.Fatalf("measure = %v, %v", got, errs)
+ }
+ // The door's own figure agrees.
+ if n, err := fx.srv.media.ChargedMinutes(ctx, acct.Sqid, pdfMonthStart(now)); err != nil || n != 11 {
+ t.Fatalf("door figure = %d, %v", n, err)
+ }
+ // Into the next month, only the job that ended there.
+ got, _ = fx.srv.measureCaps(ctx, acct, l, next.Add(time.Minute))
+ if got[capMedia] != (capMeasure{Used: 5, Limit: 600}) {
+ t.Fatalf("next month = %v", got[capMedia])
+ }
+ got, errs = fx.srv.measureCaps(ctx, acct, &plans.Limits{}, now)
+ if len(got) != 0 || len(errs) != 0 {
+ t.Fatalf("zero limit = %v, %v", got, errs)
+ }
+
+ // The grace pass stores the row, at the level levelOf gives.
+ fx.srv.cfg.PlanCatalog = mediaLimitCatalog(t, 12)
+ if err := fx.srv.planGraceAccount(ctx, acct, now); err != nil {
+ t.Fatal(err)
+ }
+ rows, err := fx.st.CapStates(acct.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var row *capState
+ for i := range rows {
+ if rows[i].Cap == capMedia {
+ row = &rows[i]
+ }
+ }
+ if row == nil || row.Used != 11 || row.Limit != 12 || row.Level != levelWarn || row.Period != capPeriod(capMedia, now) {
+ t.Fatalf("media row = %+v", row)
+ }
+
+ if _, err := fx.st.db.Exec(`DROP TABLE media_jobs`); err != nil {
+ t.Fatal(err)
+ }
+ got, errs = fx.srv.measureCaps(ctx, acct, l, now)
+ if _, ok := got[capMedia]; ok || errs[capMedia] == nil {
+ t.Fatalf("failed measure = %v, %v", got, errs)
+ }
+}
+
+func TestMediaCapNotices(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ now := time.Now().UTC()
+ date := time.Date(now.Year(), now.Month()+1, 1, 0, 0, 0, 0, time.UTC).Format("2 January 2006")
+ for _, tc := range []struct {
+ used, limit int64
+ banner, cli string
+ }{
+ {9600, 12000,
+ "This account has used 9,600 of 12,000 media minutes this month. If it goes over, nothing changes during the grace period.",
+ "this account has used 9,600 of 12,000 media minutes this month"},
+ {601, 600,
+ "This account is over its media allowance: 601 of 600 media minutes this month. At twice the allowance, new conversions are refused until " + date + ". Buy a media pack or move to a larger plan for more.",
+ "this account is over its media allowance: 601 of 600 media minutes this month. at twice the allowance, new conversions are refused until " + date + ". buy a media pack or move to a larger plan for more"},
+ {1200, 600,
+ "This account has used twice its media allowance this month. New conversions are refused until the 1st of the UTC month, or until it buys a media pack or moves to a larger plan.",
+ "this account has used twice its media allowance this month. new conversions are refused until the 1st of the UTC month, or until it buys a media pack or moves to a larger plan"},
+ } {
+ t.Run(fmt.Sprint(tc.used), func(t *testing.T) {
+ fx.srv.cfg.PlanCatalog = mediaLimitCatalog(t, int(tc.limit))
+ st := evaluateCap(nil, capMedia, tc.used, tc.limit, 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] != tc.banner {
+ t.Errorf("banner = %q, want %q", lines, tc.banner)
+ }
+ req := httptest.NewRequest("GET", "/", nil)
+ req.Header.Set(planWarningsAccept, "1")
+ w := httptest.NewRecorder()
+ fx.srv.writePlanWarnings(w, req, Principal{}, acct)
+ if got := w.Header().Values(planWarningHeader); len(got) != 1 || got[0] != tc.cli {
+ t.Errorf("CLI header = %q, want %q", got, tc.cli)
+ }
+ })
+ }
+ // A bigger plan lifts the refusal at once; a new month drops the row.
+ fx.srv.cfg.PlanCatalog = mediaLimitCatalog(t, 1200)
+ if lines, _ := fx.srv.planBanner(acct, RoleOwner, now); strings.Contains(strings.Join(lines, " "), "twice its media allowance") {
+ t.Errorf("larger plan still refuses: %q", lines)
+ }
+ 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.Errorf("stale banner = %q", lines)
+ }
+ if got := usagePhrase(planNotice{Cap: capMedia, Used: 12001, Limit: 12000}); got != "12,001 of 12,000 media minutes this month" {
+ t.Errorf("usage = %q", got)
+ }
+}
diff --git a/internal/console/plansponsor.go b/internal/console/plansponsor.go
index 83b7da62d..c6a6fa78c 100644
--- a/internal/console/plansponsor.go
+++ b/internal/console/plansponsor.go
@@ -90,6 +90,7 @@ func sponsorUnlimited() plans.Limits {
EmailPerDay: sponsorMost,
BandwidthBytesMonth: sponsorMost,
PDFRendersMonth: sponsorMost,
+ MediaMinutesMonth: sponsorMost,
CustomDomains: true,
Fleets: true,
MinScheduleSeconds: 1,
diff --git a/internal/console/plansponsor_test.go b/internal/console/plansponsor_test.go
index 71d6cd4b1..b329e2fbb 100644
--- a/internal/console/plansponsor_test.go
+++ b/internal/console/plansponsor_test.go
@@ -375,7 +375,7 @@ func TestBillingShowsTheSponsorshipAsUnlimited(t *testing.T) {
for _, inc := range planIncludes(l, 0) {
got = append(got, inc.Text)
}
- want := []string{"Unlimited apps and instances", "Unlimited disk per app", "Unlimited PDFs a month", "Custom domains"}
+ want := []string{"Unlimited apps and instances", "Unlimited disk per app", "Unlimited PDFs a month", "Unlimited media minutes a month", "Custom domains"}
if strings.Join(got, "|") != strings.Join(want, "|") {
t.Fatalf("includes = %q, want %q", got, want)
}
diff --git a/internal/plans/catalog.go b/internal/plans/catalog.go
index 3c0dd677a..8918e7450 100644
--- a/internal/plans/catalog.go
+++ b/internal/plans/catalog.go
@@ -51,6 +51,7 @@ type Limits struct {
EmailPerHour int `json:"email_per_hour,omitempty"`
BandwidthBytesMonth int64 `json:"bandwidth_bytes_month,omitempty"`
PDFRendersMonth int `json:"pdf_renders_month,omitempty"`
+ MediaMinutesMonth int `json:"media_minutes_month,omitempty"` // per UTC month: a video minute is 1, an audio minute 0.1 (internal/mediajobs); 0 is no limit
CustomDomains bool `json:"custom_domains,omitempty"`
Fleets bool `json:"fleets,omitempty"`
MinScheduleSeconds int `json:"min_schedule_seconds,omitempty"`
@@ -318,7 +319,7 @@ func (c *Catalog) validate() error {
return fmt.Errorf("pack %q: %w", name, err)
}
if pk.Adds != pk.Adds.additive() {
- return fmt.Errorf("pack %q may only add running_things, disk_bytes, storage_bytes, email_per_day or bandwidth_bytes_month", name)
+ return fmt.Errorf("pack %q may only add running_things, disk_bytes, storage_bytes, email_per_day, bandwidth_bytes_month or media_minutes_month", name)
}
}
return nil
@@ -361,7 +362,7 @@ func (c *Catalog) CeilingsFor(plan string) Limits {
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.EmailPerHour < 0 || l.BandwidthBytesMonth < 0 ||
- l.MinScheduleSeconds < 0 || l.HistoryDays < 0 || l.PDFRendersMonth < 0 ||
+ l.MinScheduleSeconds < 0 || l.HistoryDays < 0 || l.PDFRendersMonth < 0 || l.MediaMinutesMonth < 0 ||
l.RateClientShare < 0 || l.RatePerSecond < 0 || l.RateBurst < 0 {
return errors.New("limits may not be negative")
}
@@ -388,6 +389,7 @@ func (l Limits) additive() Limits {
StorageBytes: l.StorageBytes,
EmailPerDay: l.EmailPerDay,
BandwidthBytesMonth: l.BandwidthBytesMonth,
+ MediaMinutesMonth: l.MediaMinutesMonth,
}
}
@@ -427,6 +429,11 @@ func (c *Catalog) Effective(plan string, packs map[string]int, sponsored *Limits
l.StorageBytes = addPack(l.StorageBytes, qty, pk.Adds.StorageBytes, &fits)
l.EmailPerDay = addPack(l.EmailPerDay, qty, pk.Adds.EmailPerDay, &fits)
l.BandwidthBytesMonth = addPack(l.BandwidthBytesMonth, qty, pk.Adds.BandwidthBytesMonth, &fits)
+ // Zero media minutes is no limit: a pack leaves that as it is,
+ // rather than buying the account a smaller allowance.
+ if l.MediaMinutesMonth > 0 {
+ l.MediaMinutesMonth = addPack(l.MediaMinutesMonth, qty, pk.Adds.MediaMinutesMonth, &fits)
+ }
if !fits {
return Limits{}, fmt.Errorf("%w: %q overflows", ErrPackQuantity, name)
}
@@ -437,6 +444,7 @@ func (c *Catalog) Effective(plan string, packs map[string]int, sponsored *Limits
l.EmailPerDay = clamp(l.EmailPerDay, ce.EmailPerDay)
l.BandwidthBytesMonth = clamp(l.BandwidthBytesMonth, ce.BandwidthBytesMonth)
l.PDFRendersMonth = clamp(l.PDFRendersMonth, ce.PDFRendersMonth)
+ l.MediaMinutesMonth = clamp(l.MediaMinutesMonth, ce.MediaMinutesMonth)
l.IdleSeconds = clamp(l.IdleSeconds, ce.IdleSeconds)
l.RateClientShare = clampRate(l.RateClientShare, ce.RateClientShare)
l.RatePerSecond = clampRate(l.RatePerSecond, ce.RatePerSecond)
@@ -479,6 +487,7 @@ func (l Limits) generous(o Limits) Limits {
l.EmailPerHour = generousRate(l.EmailPerHour, o.EmailPerHour)
l.BandwidthBytesMonth = max(l.BandwidthBytesMonth, o.BandwidthBytesMonth)
l.PDFRendersMonth = max(l.PDFRendersMonth, o.PDFRendersMonth)
+ l.MediaMinutesMonth = max(l.MediaMinutesMonth, o.MediaMinutesMonth)
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 dae33803a..afb3a4ece 100644
--- a/internal/plans/catalog_test.go
+++ b/internal/plans/catalog_test.go
@@ -408,3 +408,109 @@ func TestDisplayName(t *testing.T) {
t.Errorf("no catalog: %q", got)
}
}
+
+// mediaCatalogPath is the example catalog with the media allowance plan 3
+// proposes (spec §7.3, decision 6): Free 30, Personal 600, Community 1,200
+// and Business 12,000 media minutes a month, and a media pack of 1,000
+// minutes on every paid plan. mediaBookPath prices the pack at the
+// provisional USD 1200 / EUR 1000 / GBP 900 cents.
+const (
+ mediaCatalogPath = "testdata/media-catalog.json"
+ mediaBookPath = "testdata/media-pricebook.json"
+)
+
+func TestLimitsMediaMinutesMonth(t *testing.T) {
+ l := Limits{MediaMinutesMonth: 600}
+ b, err := json.Marshal(l)
+ if err != nil || string(b) != `{"media_minutes_month":600}` {
+ t.Fatalf("marshal = %s, %v", b, err)
+ }
+ var got Limits
+ if err := json.Unmarshal(b, &got); err != nil || got.MediaMinutesMonth != 600 {
+ t.Fatalf("round trip = %+v, %v", got, err)
+ }
+ if b, _ := json.Marshal(Limits{}); string(b) != `{}` {
+ t.Fatalf("unset media minutes marshal as %s", b)
+ }
+ if err := (Limits{MediaMinutesMonth: -1}).nonNegative(); err == nil {
+ t.Fatal("negative media limit accepted")
+ }
+ for _, n := range []int{50, 6000} {
+ if got := l.generous(Limits{MediaMinutesMonth: n}).MediaMinutesMonth; got != max(600, n) {
+ t.Fatalf("generous = %d", got)
+ }
+ }
+ if got := (Limits{MediaMinutesMonth: 1000, PDFRendersMonth: 5}).additive(); got != (Limits{MediaMinutesMonth: 1000}) {
+ t.Fatalf("additive = %+v", got)
+ }
+
+ c, err := LoadCatalog(mediaCatalogPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := LoadPriceBook(mediaBookPath, c); err != nil {
+ t.Fatalf("media price book: %v", err)
+ }
+ for plan, want := range map[string]int{"free": 30, "personal": 600, "community": 1200, "business": 12000} {
+ got, err := c.Effective(plan, nil, nil)
+ if err != nil || got.MediaMinutesMonth != want {
+ t.Errorf("%s = %d, %v; want %d", plan, got.MediaMinutesMonth, err, want)
+ }
+ }
+ // A pack adds 1,000 per unit, up to the ceiling.
+ for _, tc := range []struct{ qty, ceiling, want int }{{1, 0, 1600}, {3, 0, 3600}, {20, 0, 20600}, {3, 2500, 2500}, {1, 2500, 1600}} {
+ c, _ := LoadCatalog(mediaCatalogPath)
+ c.Ceilings.MediaMinutesMonth = tc.ceiling
+ got, err := c.Effective("personal", map[string]int{"media": tc.qty}, nil)
+ if err != nil || got.MediaMinutesMonth != tc.want {
+ t.Errorf("personal + %d media packs under ceiling %d = %d, %v; want %d", tc.qty, tc.ceiling, got.MediaMinutesMonth, err, tc.want)
+ }
+ }
+ if _, err := c.Effective("personal", map[string]int{"media": 21}, nil); !errors.Is(err, ErrPackQuantity) {
+ t.Errorf("21 media packs: %v", err)
+ }
+ if _, err := c.Effective("free", map[string]int{"media": 1}, nil); !errors.Is(err, ErrPackNotOffered) {
+ t.Errorf("media pack on free: %v", err)
+ }
+ // Zero is no limit, and a pack does not turn it into 1,000.
+ p := c.Plans["personal"]
+ p.Limits.MediaMinutesMonth = 0
+ c.Plans["personal"] = p
+ if got, err := c.Effective("personal", map[string]int{"media": 2}, nil); err != nil || got.MediaMinutesMonth != 0 {
+ t.Errorf("unlimited plan with packs = %d, %v; want 0", got.MediaMinutesMonth, err)
+ }
+ // A sponsored figure is the more generous one, unclamped.
+ c, _ = LoadCatalog(mediaCatalogPath)
+ c.Ceilings.MediaMinutesMonth = 700
+ if got, _ := c.Effective("free", nil, &Limits{MediaMinutesMonth: 5000}); got.MediaMinutesMonth != 5000 {
+ t.Errorf("sponsored = %d", got.MediaMinutesMonth)
+ }
+}
+
+// TestCatalogValidationMediaPack: a pack may add media minutes (pre-flight
+// F8), and still nothing outside the additive fields; a negative media
+// figure is refused on a plan or a pack.
+func TestCatalogValidationMediaPack(t *testing.T) {
+ b, err := os.ReadFile(mediaCatalogPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ base := string(b)
+ if _, err := ParseCatalog(b); err != nil {
+ t.Fatalf("media pack refused: %v", err)
+ }
+ for name, body := range map[string]string{
+ "pack adds PDFs": strings.Replace(base, `{"media_minutes_month": 1000}`, `{"media_minutes_month": 1000, "pdf_renders_month": 10}`, 1),
+ "negative pack": strings.Replace(base, `{"media_minutes_month": 1000}`, `{"media_minutes_month": -1000}`, 1),
+ "negative plan": strings.Replace(base, `"media_minutes_month": 30,`, `"media_minutes_month": -30,`, 1),
+ } {
+ if body == base {
+ t.Fatalf("%s: fixture line moved", name)
+ }
+ if _, err := ParseCatalog([]byte(body)); err == nil {
+ t.Errorf("%s: accepted", name)
+ } else if name == "pack adds PDFs" && !strings.Contains(err.Error(), "bandwidth_bytes_month or media_minutes_month") {
+ t.Errorf("%s: %v", name, err)
+ }
+ }
+}
diff --git a/internal/plans/repo_catalog_test.go b/internal/plans/repo_catalog_test.go
index 92f55dac4..e737c5ace 100644
--- a/internal/plans/repo_catalog_test.go
+++ b/internal/plans/repo_catalog_test.go
@@ -143,6 +143,9 @@ func TestNewFieldsKeepOldIDs(t *testing.T) {
if p.KeptStorage != nil || p.Limits.EmailPerHour != 0 || p.Limits.StorageScanRequired {
t.Fatal("example catalog grew a #1076 field")
}
+ if p.Limits.MediaMinutesMonth != 0 {
+ t.Fatal("example catalog grew media_minutes_month")
+ }
}
}
diff --git a/internal/plans/testdata/media-catalog.json b/internal/plans/testdata/media-catalog.json
new file mode 100644
index 000000000..fab8ccecb
--- /dev/null
+++ b/internal/plans/testdata/media-catalog.json
@@ -0,0 +1,102 @@
+{
+ "version": "media-example-v1",
+ "default_plan": "free",
+ "free_accounts_per_person": 1,
+ "plans": {
+ "free": {
+ "paid": false,
+ "max_members": 3,
+ "limits": {
+ "running_things": 3,
+ "sidecars_per_app": 1,
+ "idle_seconds": 90,
+ "memory_tier": "small",
+ "awake_hours_month": 90,
+ "disk_bytes": 1073741824,
+ "storage_bytes": 1073741824,
+ "email_per_day": 50,
+ "bandwidth_bytes_month": 10737418240,
+ "media_minutes_month": 30,
+ "min_schedule_seconds": 900
+ }
+ },
+ "personal": {
+ "paid": true,
+ "limits": {
+ "running_things": 25,
+ "sidecars_per_app": 5,
+ "idle_seconds": 900,
+ "memory_tier": "default",
+ "awake_hours_month": 1500,
+ "disk_bytes": 10737418240,
+ "storage_bytes": 26843545600,
+ "storage_self_serve": true,
+ "email_per_day": 1000,
+ "bandwidth_bytes_month": 53687091200,
+ "media_minutes_month": 600,
+ "custom_domains": true,
+ "fleets": true,
+ "min_schedule_seconds": 60,
+ "history_days": 7
+ },
+ "packs": ["apps", "disk", "storage", "email", "bandwidth", "media"]
+ },
+ "community": {
+ "name": "Teams",
+ "paid": true,
+ "limits": {
+ "running_things": 50,
+ "sidecars_per_app": 5,
+ "idle_seconds": 900,
+ "memory_tier": "default",
+ "awake_hours_month": 3000,
+ "disk_bytes": 10737418240,
+ "storage_bytes": 53687091200,
+ "storage_self_serve": true,
+ "email_per_day": 2000,
+ "bandwidth_bytes_month": 107374182400,
+ "media_minutes_month": 1200,
+ "custom_domains": true,
+ "fleets": true,
+ "min_schedule_seconds": 60
+ },
+ "packs": ["apps", "disk", "storage", "email", "bandwidth", "media"],
+ "ceilings": {"running_things": 400, "email_per_day": 20000, "idle_seconds": 900}
+ },
+ "business": {
+ "paid": true,
+ "limits": {
+ "running_things": 500,
+ "sidecars_per_app": 5,
+ "idle_seconds": 900,
+ "memory_tier": "default",
+ "awake_hours_month": 30000,
+ "disk_bytes": 10737418240,
+ "storage_bytes": 536870912000,
+ "storage_self_serve": true,
+ "email_per_day": 20000,
+ "bandwidth_bytes_month": 1073741824000,
+ "media_minutes_month": 12000,
+ "custom_domains": true,
+ "fleets": true,
+ "min_schedule_seconds": 60,
+ "history_days": 7
+ },
+ "packs": ["apps", "disk", "storage", "email", "bandwidth", "media"],
+ "ceilings": {"running_things": 4000, "email_per_day": 200000, "idle_seconds": 900}
+ }
+ },
+ "packs": {
+ "apps": {"adds": {"running_things": 5}, "max_quantity": 20},
+ "disk": {"adds": {"disk_bytes": 10737418240}, "max_quantity": 20},
+ "storage": {"adds": {"storage_bytes": 53687091200}, "max_quantity": 20},
+ "email": {"adds": {"email_per_day": 1000}, "max_quantity": 20},
+ "bandwidth": {"adds": {"bandwidth_bytes_month": 53687091200}, "max_quantity": 20},
+ "media": {"adds": {"media_minutes_month": 1000}, "max_quantity": 20}
+ },
+ "ceilings": {
+ "running_things": 200,
+ "email_per_day": 10000,
+ "idle_seconds": 900
+ }
+}
diff --git a/internal/plans/testdata/media-pricebook.json b/internal/plans/testdata/media-pricebook.json
new file mode 100644
index 000000000..3c27ab56d
--- /dev/null
+++ b/internal/plans/testdata/media-pricebook.json
@@ -0,0 +1,24 @@
+{
+ "version": "media-example-v1",
+ "status": "draft",
+ "catalog_version": "media-example-v1",
+ "default_currency": "usd",
+ "currencies": ["usd", "eur", "gbp"],
+ "country_currency": {
+ "eur": ["AT", "BE", "BG", "HR", "CY", "CZ", "DK", "EE", "FI", "FR", "DE", "GR", "HU", "IE", "IT", "LV", "LT", "LU", "MT", "NL", "PL", "PT", "RO", "SK", "SI", "ES", "SE"],
+ "gbp": ["GB"]
+ },
+ "plans": {
+ "personal": {"usd": 2800, "eur": 2400, "gbp": 2200},
+ "community": {"usd": 6000, "eur": 5000, "gbp": 4500},
+ "business": {"usd": 60000, "eur": 50000, "gbp": 45000}
+ },
+ "packs": {
+ "apps": {"usd": 1200, "eur": 1000, "gbp": 900},
+ "disk": {"usd": 3600, "eur": 3100, "gbp": 2800},
+ "storage": {"usd": 1200, "eur": 1000, "gbp": 900},
+ "email": {"usd": 2400, "eur": 2100, "gbp": 1900},
+ "bandwidth": {"usd": 4800, "eur": 4100, "gbp": 3800},
+ "media": {"usd": 1200, "eur": 1000, "gbp": 900}
+ }
+}