monetize_product/lib.rs
1//! **`Product` — the plugin that makes monetize speak one product's language.**
2//!
3//! monetize handles MANY products, and each product's plugin lives in this
4//! repository. So monetize is
5//! one service for gunnar.rs, holger.rs, njord, …, and each product is a crate under
6//! `products/<name>` implementing this trait. The product itself carries only the thin
7//! `monetize-embed` hook behind a cargo feature; it never learns what capacity costs.
8//!
9//! ```text
10//! product box ──Usage (gRPC, the product's own API)──▶ Product plugin ──▶ monetize core
11//! product box ◀──Entitlement (product's own API)──── Product plugin ◀── monetize core
12//! ```
13//!
14//! # Two directions, both facts
15//!
16//! * [`Product::read_usage`] — what a tenant is consuming, in the product's own units
17//! (gunnar: pack bytes, read-cache bytes, LFS bytes, tombstoned bytes, open-store RAM;
18//! holger: whatever holger meters). The plugin maps them to [`Usage`], a flat bag of
19//! named meters, so core never has product-specific fields.
20//! * [`Product::push_entitlement`] — the verdict, written back over the product's own
21//! control plane (gunnar: `Entitlement.Set` with `source = payment:<vendor>:<ref>`).
22//! Signed by monetize's key; the product appends it to its attestation log.
23//!
24//! # A plugin never blocks the product
25//!
26//! Counting is done **inside the product, always, open source** — a self-hoster wants the
27//! numbers too. The plugin only *reads* them. If monetize is down the product keeps
28//! serving on its cached entitlement; the plugin's job on reconnect is to catch up, not
29//! to have been in the request path.
30
31use std::collections::BTreeMap;
32
33/// **Reading a daily `*_today` counter out of a series of readings** — the fold
34/// behind the console's SILENT and FRICTION lists. Pure; see the module doc for
35/// why summing the readings is the wrong arithmetic and why it lives here.
36pub mod flow;
37
38/// A tenant, as the product names it. gunnar: the `Namespace` name (`team/sub`).
39#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize, serde::Deserialize)]
40pub struct TenantId(pub String);
41
42/// **Whether the product will actually POLICE a cap on this meter.**
43///
44/// CPU and RAM exist as quota even where gunnar cannot cap them, and that gap is
45/// narrowed without redoing the engine.
46///
47/// An order may cap any declared meter. But a cap on a meter nothing checks is a
48/// promise nobody keeps, and the tenant cannot tell the difference from the
49/// invoice. So the product says, per meter, which kind of promise it is — and
50/// the console shows it beside the number rather than letting every cap look
51/// like a guarantee.
52///
53/// This is the smallest honest way to let CPU and RAM be sold: they ARE bought,
54/// with real money, and they DO change what the box can do — they are simply not
55/// something a git server polices per namespace. Saying so is better than either
56/// refusing to sell them or pretending they are enforced.
57#[derive(Clone, Copy, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
58pub enum Enforcement {
59 /// **The product refuses when over.** A cap here is a wall the tenant hits.
60 /// gunnar: `pack_bytes` (receive-pack refused before the bytes),
61 /// `cache_bytes` (the explode budget).
62 Enforced,
63 /// **Counted and reported, not policed.** The number is true and monetize
64 /// can bill on it or a human can act on it, but nothing refuses. A cap here
65 /// is a threshold, not a wall.
66 Measured,
67 /// **Neither counted nor policed BY THE PRODUCT — it is iron monetize
68 /// bought.** CPU and RAM: a bigger plan at the provider, real money, real
69 /// effect, and no per-namespace check anywhere in the product. The
70 /// provider's invoice is the enforcement.
71 Provisioned,
72}
73
74impl Enforcement {
75 /// One line for the console, beside the cap.
76 pub fn describe(self) -> &'static str {
77 match self {
78 Enforcement::Enforced => "the product refuses when over",
79 Enforcement::Measured => "counted and reported; nothing refuses",
80 Enforcement::Provisioned => "provisioned at the cloud provider; not policed by the product",
81 }
82 }
83
84 /// Is a cap on this meter a wall the tenant will actually hit?
85 pub fn is_a_wall(self) -> bool {
86 matches!(self, Enforcement::Enforced)
87 }
88}
89
90/// **What a cap on this meter is MADE OF**, for the meters where a cap is a
91/// promise of CAPACITY rather than a count — and therefore what UNIT the price
92/// list prices it in and what iron the transaction buys for it.
93///
94/// A plan that sells bytes it never buys is the one bug here that silently
95/// converts money into nothing. Since the plan catalogue went (2026-09-05), an
96/// ORDER names caps and nothing else, and this is the field that turns a cap
97/// into a purchase: `monetize::order::resources_for` translates the DELTA on a
98/// disk-backed meter into a `Resource::Disk`, and `monetize::PriceList` prices
99/// each backing's delta by its own unit.
100///
101/// It lives on the meter and not on the order because only the PRODUCT knows
102/// what its meter is made of — that `pack_bytes` is block storage and `pushes`
103/// is a count of events that costs nothing to promise.
104#[derive(Clone, Copy, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
105pub enum Backing {
106 /// **Bytes of block storage.** A delta here becomes a `Resource::Disk` of
107 /// `ceil(bytes / 2^30)` GiB, and is priced per GiB per month
108 /// (`disk_gib_month` on the price list).
109 DiskBytes,
110 /// **CPU, in millicores (1000 = one core).** Priced per core per month
111 /// (`cpu_core_month`). monetize does NOT translate millicores into a
112 /// provider's plan name (`2xCPU-4GB` is a name, and a table of names goes
113 /// stale every time a provider renames a size), so a delta here buys no
114 /// cloud resource of its own: the ceiling is the product's own measurement
115 /// (`Product::can_absorb`) and the box's declared limit
116 /// (`CloudProvider::ceilings`).
117 CpuMillicores,
118 /// **RAM, in bytes.** Priced per GiB per month (`ram_gib_month`); the same
119 /// ceiling rule as [`Backing::CpuMillicores`].
120 RamBytes,
121}
122
123impl Backing {
124 /// The price-list key this backing is priced under, and the unit it means:
125 /// `disk_gib_month` | `cpu_core_month` | `ram_gib_month`.
126 pub fn unit(self) -> &'static str {
127 match self {
128 Backing::DiskBytes => "disk_gib_month",
129 Backing::CpuMillicores => "cpu_core_month",
130 Backing::RamBytes => "ram_gib_month",
131 }
132 }
133
134 /// Every backing, in the order the price list is written in.
135 pub const ALL: [Backing; 3] = [Backing::DiskBytes, Backing::CpuMillicores, Backing::RamBytes];
136
137 /// The backing a price-list key names, if any.
138 pub fn from_unit(unit: &str) -> Option<Backing> {
139 Backing::ALL.into_iter().find(|b| b.unit() == unit)
140 }
141
142 /// **Price `delta` of this backing at `minor_per_unit_month`, for one
143 /// month**, in minor units. Integer arithmetic, rounded UP to the unit for
144 /// bytes (a customer who asks for one byte over a GiB is sold the next GiB,
145 /// which is what the provider sells us) and exact per millicore for CPU
146 /// (`minor × millicores / 1000`).
147 pub fn price_month(self, delta: u64, minor_per_unit_month: u64) -> u64 {
148 const GIB: u64 = 1 << 30;
149 match self {
150 Backing::DiskBytes | Backing::RamBytes => delta.div_ceil(GIB).saturating_mul(minor_per_unit_month),
151 Backing::CpuMillicores => u64::try_from(u128::from(delta) * u128::from(minor_per_unit_month) / 1000).unwrap_or(u64::MAX),
152 }
153 }
154}
155
156/// **WHERE a meter's number is even meaningful: per tenant, or per product.**
157///
158/// Disk is the whole game, and it is per tenant. CPU and RAM stay in the model,
159/// but for gunnar they are not interesting per user — they are interesting per
160/// product: a tenant does not own cores, the box does.
161///
162/// Orthogonal to [`Enforcement`], and the pair is what makes a fleet total
163/// honest. `Enforcement` says whether a cap is a WALL. Scope says whether adding
164/// one tenant's figure to another's produces anything at all:
165///
166/// * `pack_bytes` is per tenant, so nine tenants' pack bytes sum to the fleet's
167/// pack bytes;
168/// * `cpu_millicores` is per product, so nine tenants' CPU does not sum to
169/// anything — nobody measured a tenant's cores, and adding nine numbers that
170/// were never measured is arithmetic on nothing.
171///
172/// **It is the PRODUCT's call, not a global rule.** gunnar meters disk per tenant
173/// and CPU per product; another product may legitimately meter CPU per user, or
174/// disk only in total. [`Product::meters`] is already that seam, and nothing
175/// outside a product decides which of its meters are per-tenant. `monetize::fleet`
176/// sums only [`Scope::Tenant`], whatever a product declares.
177#[derive(Clone, Copy, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
178pub enum Scope {
179 /// **Measured, or sold, per TENANT.** A fleet figure is the sum over tenants.
180 /// The default, because it is what a meter usually is.
181 Tenant,
182 /// **Measured, or bought, for the WHOLE PRODUCT.** It appears ONCE, on the
183 /// product screen, and never in a per-tenant sum. A cap on it may still be
184 /// sold — CPU and RAM are bought with real money — it simply is not a
185 /// quantity any one tenant holds.
186 Product,
187}
188
189impl Scope {
190 /// May a figure for this meter be summed across tenants? Only [`Scope::Tenant`].
191 pub fn sums_across_tenants(self) -> bool {
192 matches!(self, Scope::Tenant)
193 }
194
195 /// `tenant` | `product` — the wire and JSON spelling, one writer.
196 pub fn name(self) -> &'static str {
197 match self {
198 Scope::Tenant => "tenant",
199 Scope::Product => "product",
200 }
201 }
202}
203
204/// **One meter a product declares**: its name, what it means, and whether a cap
205/// on it is policed. An order may only cap a declared meter, and the console
206/// shows [`Enforcement`] beside the number.
207#[derive(Clone, Copy, PartialEq, Eq, Debug)]
208pub struct Meter {
209 /// The wire name, and the key in [`EntitlementFact::caps`] and [`Usage::meters`].
210 pub name: &'static str,
211 /// One line, the plugin's own words.
212 pub meaning: &'static str,
213 pub enforcement: Enforcement,
214 /// **Does [`Product::read_usage`] carry a reading for this meter?**
215 ///
216 /// A meter exists to do one or both of two jobs: carry a usage READING, and
217 /// accept a CAP. Most do both. Two kinds do not, and conflating them was
218 /// caught by a test rather than by thinking:
219 ///
220 /// * `cpu_millicores`, `ram_bytes` — the product has no idea what was
221 /// bought; monetize does, from the order. Reporting `0` would read as "you
222 /// have none", which is worse than saying nothing.
223 /// * `concurrent_transfers` — a cap the engine enforces instantly, with no
224 /// stored reading to bill from. The limit is real; the gauge does not exist.
225 ///
226 /// So a plugin's `read_usage` must report EXACTLY the meters with this set,
227 /// which is an equality a test can hold in both directions: an undeclared
228 /// reading is a leak, and a declared reading that stopped arriving is a
229 /// silently emptied bill.
230 pub reports_usage: bool,
231 /// **What a cap on this meter is made of**, or `None` when a cap here costs
232 /// nothing to grant (a count of pushes, a number of repositories the
233 /// existing box already holds). `Some` is what makes an order on this meter
234 /// a PURCHASE: the delta is priced by the backing's unit and, for disk,
235 /// bought as iron. See [`Backing`].
236 pub backing: Option<Backing>,
237 /// **Whether this meter's number is per tenant or per product.** See
238 /// [`Scope`]; it is what keeps a fleet total from adding up figures nobody
239 /// measured per tenant.
240 pub scope: Scope,
241}
242
243impl Meter {
244 /// A meter that both reports a reading and may be capped — the common case.
245 pub const fn new(name: &'static str, meaning: &'static str, enforcement: Enforcement) -> Meter {
246 Meter { name, meaning, enforcement, reports_usage: true, backing: None, scope: Scope::Tenant }
247 }
248
249 /// A meter that may be CAPPED but carries no reading. See
250 /// [`Meter::reports_usage`] for the two kinds and why `0` is not a truthful
251 /// substitute.
252 pub const fn cap_only(name: &'static str, meaning: &'static str, enforcement: Enforcement) -> Meter {
253 Meter { name, meaning, enforcement, reports_usage: false, backing: None, scope: Scope::Tenant }
254 }
255
256 /// The same meter, declaring what a cap on it is MADE OF — and so what an
257 /// order on it buys and what the price list prices it by. A
258 /// [`Enforcement::Provisioned`] meter without one is a cap monetize can
259 /// neither price nor buy; gunnar's own test holds its list to that.
260 pub const fn with_backing(self, backing: Backing) -> Meter {
261 Meter { backing: Some(backing), ..self }
262 }
263
264 /// The same meter, measured for the WHOLE PRODUCT rather than per tenant —
265 /// so a fleet total leaves it out instead of adding up figures nobody took.
266 /// See [`Scope`].
267 pub const fn per_product(self) -> Meter {
268 Meter { scope: Scope::Product, ..self }
269 }
270}
271
272/// **What a product says it could still serve, or why it could not say.**
273///
274/// The other half of the oversell number: `sum(what has been sold) − servable`.
275/// Without it monetize could sell ten tenants 10 GiB each on a box with 55 GiB
276/// servable and nothing would object until the sixth push.
277///
278/// The two arms are the distinction `BASE-MODEL.md` rule 3 turns on and the same
279/// one [`Product::can_absorb`] already makes: **an unanswered capacity question
280/// is a measurement that did not happen, not a full disk and not an empty one.**
281/// The live gunnar.rs appliance predates gunnar's `Admin.Capacity` RPC and
282/// answers [`Servable::Unmeasured`] today; a fleet total that turned that into a
283/// zero would report every deployment as catastrophically oversold, and one that
284/// turned it into infinity would report every deployment as fine. Neither is a
285/// measurement.
286/// **Can this product's store grow while it runs?** Carried on
287/// [`Servable::Measured`] beside the bytes, because the two answer different
288/// questions and an operator acts differently on each: a full box that can grow
289/// wants a disk; a full box that is SEALED wants its set enlarged by an operator
290/// maintenance operation (the volumes it already has, grown in place) or a fresh
291/// install onto a larger one, and a disk bought for it is billed and invisible.
292///
293/// Each arm carries the PRODUCT's own remediation sentence (gunnar's
294/// `remediation()`), so the console renders what the product said rather than a
295/// paraphrase of it — `UI.md` screen 2's `⚠ cannot grow` badge holds exactly
296/// that paragraph.
297#[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
298pub enum Growth {
299 /// Cannot gain capacity while it runs, and nothing on the machine can give
300 /// it any. `GROWTH_SEALED` on gunnar's wire.
301 Sealed(String),
302 /// The product will not grow the set itself, but an operator can, out of
303 /// band. `GROWTH_OPERATOR_ONLY`.
304 OperatorOnly(String),
305 /// The product could not tell. NOT a promise that it can grow.
306 Unknown(String),
307 /// **Grows at its next restart** once every member volume has been
308 /// enlarged to one equal size (gunnar's `GROWTH_AT_RESTART`, 2026-09-14).
309 /// Still no hot-plug: a disk ATTACHED to it is as invisible as under
310 /// `Sealed`; what helps is the outside actor enlarging the members
311 /// ([`ApplianceGrow`] + `monetize_cloud::grow`).
312 AtRestart(String),
313 /// **Grows without a restart**: the product drains, unmounts and grows into
314 /// enlarged members while its control plane stays up (gunnar's
315 /// `GROWTH_AT_RUNTIME`). The shape [`ApplianceGrow`] drives.
316 AtRuntime(String),
317}
318
319impl Growth {
320 /// The wire word: `sealed` | `operator_only` | `unknown` | `at_restart` |
321 /// `at_runtime`.
322 pub fn name(&self) -> &'static str {
323 match self {
324 Growth::Sealed(_) => "sealed",
325 Growth::OperatorOnly(_) => "operator_only",
326 Growth::Unknown(_) => "unknown",
327 Growth::AtRestart(_) => "at_restart",
328 Growth::AtRuntime(_) => "at_runtime",
329 }
330 }
331
332 /// The product's own sentence about what to do.
333 pub fn detail(&self) -> &str {
334 match self {
335 Growth::Sealed(s) | Growth::OperatorOnly(s) | Growth::Unknown(s) | Growth::AtRestart(s) | Growth::AtRuntime(s) => s,
336 }
337 }
338}
339
340#[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
341pub enum Servable {
342 /// The product measured its own store.
343 Measured {
344 /// **Bytes that may still be handed to tenants**, beyond what they already
345 /// hold, after whatever reserve the product keeps for itself. gunnar's
346 /// `servable_bytes` (`free − disk floor`) — never its `free_bytes`, which
347 /// includes a reserve monetize must not sell.
348 servable_bytes: u64,
349 /// The whole store, reserve and all. `used + servable_bytes` is what the
350 /// fleet could grow to; `total_bytes` is larger than that by the reserve
351 /// and by anything on the filesystem that is not tenant data. 0 when the
352 /// product measures what is left but not what there is in total.
353 total_bytes: u64,
354 /// **Whether the store can EVER hold more than `total_bytes`.** A
355 /// measurement of the box, independent of the bytes: gunnar's
356 /// `Admin.Capacity` answers it as `growth`, and it is the field that
357 /// stops "buy another disk" being the reflex answer to a full fleet.
358 growth: Growth,
359 /// **The box's MEASURED ceilings on product-scope meters**, by the
360 /// product's own meter name: gunnar's `cpu_millicores_total` and
361 /// `ram_bytes_total` (Admin.Capacity, since gunnar 744bf72d) land here
362 /// as `cpu_millicores` / `ram_bytes`. A meter ABSENT here was not
363 /// measured — the wire spells that as an absent field, never as 0, and
364 /// a reader must never take a 0 as a ceiling. An order that would
365 /// raise a product-scope cap past a number here is refused by name;
366 /// the box's DECLARED ceilings (`CloudProvider::ceilings`) carry only
367 /// for a meter this map does not hold.
368 ceilings: BTreeMap<String, u64>,
369 },
370 /// **It could not be asked, or would not say — which is not zero.** The
371 /// string names WHICH: an RPC the deployed build predates, a control plane
372 /// that is down, a plugin that was never wired.
373 Unmeasured(String),
374}
375
376/// One named meter. Names are the product's, documented in its plugin crate, e.g.
377/// `pack_bytes`, `cache_bytes`, `lfs_bytes`, `tombstoned_bytes`, `open_store_ram_bytes`,
378/// `pushes`, `anonymous_reads`. Values are the product's units, usually bytes or counts.
379#[derive(Clone, PartialEq, Eq, Debug, Default, serde::Serialize, serde::Deserialize)]
380pub struct Usage {
381 pub meters: BTreeMap<String, u64>,
382 pub measured_at_unix_ms: u64,
383}
384
385/// **One tenant's FLOW for one UTC day** — what MOVED, as against what is held.
386///
387/// Every number in [`Usage`] is a STOCK reading: it answers *how much is on the
388/// product's disk*, and it reads exactly the same for a customer who worked
389/// this morning and one who last touched the product in March. monetize could
390/// therefore bill nine tenants correctly and not know that six of them had
391/// stopped. This is the other kind, and it is what the SILENT and FRICTION
392/// lists are made of.
393///
394/// **The meters are the product's own names**, exactly as [`Usage::meters`] is,
395/// and for the same reason: core has never held a product-specific field and
396/// must not gain one here. gunnar fills `bytes_in`, `bytes_out`, `pushes`,
397/// `fetches`, `lfs_bytes_in`, `lfs_bytes_out`, `refused`, its three
398/// `refused_*` reasons, `auth_failures`, `distinct_principals` and the two
399/// `last_*_unix_ms` timestamps. Another product will fill something else, and
400/// nothing here needs to know.
401///
402/// **A day with no traffic has NO ROW.** Not a row of zeroes: the caller knows
403/// which days it asked for, and zero-filling would put a bar of height zero
404/// beside a bar that means *not counted*.
405#[derive(Clone, PartialEq, Eq, Debug, Default, serde::Serialize, serde::Deserialize)]
406pub struct ActivityDay {
407 /// Midnight UTC of the day, in Unix milliseconds.
408 pub day_unix_ms: u64,
409 /// The product's own meter names. See the type's doc.
410 pub meters: BTreeMap<String, u64>,
411}
412
413/// **A tenant's kept activity, and how far back the product remembers.**
414///
415/// The second half is not decoration. An empty `days` means one of two opposite
416/// things — *nothing happened* or *you asked about a time the product no longer
417/// remembers* — and only `retained_days` can tell them apart. A console that
418/// drew an empty series as "silent" without it would report every tenant on a
419/// freshly installed box as a lapsed customer.
420#[derive(Clone, PartialEq, Eq, Debug, Default, serde::Serialize, serde::Deserialize)]
421pub struct Activity {
422 /// Oldest first. Days with no traffic are absent.
423 pub days: Vec<ActivityDay>,
424 /// How many days the product keeps. `0` when it would not say.
425 pub retained_days: u64,
426}
427
428/// The verdict monetize pushes back. Product-agnostic; the plugin maps it to the
429/// product's own enum (gunnar: `EntitlementState`).
430#[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
431pub struct EntitlementFact {
432 pub tenant: TenantId,
433 /// **The ORDER this verdict came from** — the ledger reference
434 /// (`<product>/<tenant>/<date>+<caps>`) for a purchase, an operator's own
435 /// label (or nothing) for a hand-set fact. The field is still called `plan`
436 /// on the wire and in the signed canonical form (`monetize_embed::signing`),
437 /// because gunnar verifies that form and a renamed field would invalidate
438 /// every signature a deployed gunnar checks; the CONTENT is an order
439 /// reference since the plan catalogue went on 2026-09-05.
440 pub plan: String,
441 pub state: State,
442 pub paid_until_unix_ms: Option<u64>,
443 /// Per-meter caps the product enforces itself (gunnar: `pack_quota_bytes`,
444 /// `explode_budget_bytes`). Absent = product default.
445 pub caps: BTreeMap<String, u64>,
446 /// `operator` | `payment:<vendor>:<reference>` — lands in the product's attestation log.
447 pub source: String,
448 /// Ed25519 over the canonical JSON of the fields above, by monetize-server's key.
449 pub signature: Vec<u8>,
450}
451
452/// The ladder. Numbers (grace/retention days) are the deployment's policy
453/// (`monetize::Policy`), not the enum's.
454#[derive(Clone, Copy, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
455pub enum State {
456 Free,
457 Paid,
458 Grace,
459 Suspended,
460 Retention,
461}
462
463#[derive(Clone, Debug)]
464pub enum ProductError {
465 /// The product's control plane refused (auth, unknown tenant).
466 Refused(String),
467 /// Product unreachable. Retryable; nothing was written.
468 Unavailable(String),
469}
470
471impl std::fmt::Display for ProductError {
472 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
473 match self {
474 ProductError::Refused(r) => write!(f, "product refused: {r}"),
475 ProductError::Unavailable(r) => write!(f, "product unavailable: {r}"),
476 }
477 }
478}
479impl std::error::Error for ProductError {}
480
481/// **Where the room for a target comes from, as the product measured it** —
482/// what [`Product::can_absorb`] answers when it can serve.
483///
484/// A yes is two different facts, and the difference is money. gunnar's
485/// `Admin.Capacity` answers a `verdict` and a `growth`, and the three readings
486/// of them a seller can act on are: there is room already (buy nothing), there
487/// is no room but a bought disk will be used (buy, and somebody has to extend a
488/// filesystem), and there is no room and a bought disk will NOT be used (refuse).
489/// The third is a refusal and never reaches this type. Before this type existed
490/// a yes was `Ok(())` and the cloud was asked to `ensure` a disk regardless. With
491/// the front's configuration (`pool_reserve_gib` covering the whole data set)
492/// UpCloud's pool arithmetic answers "short" for every order, so every yes
493/// bought and attached a disk to an appliance that had just said it had room —
494/// read from the code and the config, not from a bill.
495///
496/// The transaction turns it into `monetize_cloud::Room` for the provider, so
497/// the cloud is told what the product measured and never has to know which
498/// product that was.
499#[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
500pub enum Absorb {
501 /// **Served out of what the product already has.** Nothing may be bought
502 /// for it: a disk bought on top of this answer is billed and not needed.
503 OnHand,
504 /// **Short today, and bought iron becomes usable** — by the hand `note`
505 /// names, in the product's own words (gunnar: an operator extends the
506 /// filesystem out of band, and gunnar measures the larger one on its next
507 /// look). Carried onto the purchase row so the ledger records that
508 /// somebody still has a job to do after the disk is attached.
509 WithIron { note: String },
510}
511
512/// The plugin seam. Sync for the same reason as the vendor traits.
513pub trait Product: Send + Sync {
514 /// `gunnar`, `holger`, `njord`. Also the first segment of every payment reference.
515 fn id(&self) -> &'static str;
516 /// The meters this product declares — the UI and the order form read this,
517 /// so an order can only cap a meter that exists, and the console can say
518 /// whether a cap on it is policed ([`Enforcement`]).
519 fn meters(&self) -> &[Meter];
520
521 fn list_tenants(&self) -> Result<Vec<TenantId>, ProductError>;
522 fn read_usage(&self, tenant: &TenantId) -> Result<Usage, ProductError>;
523
524 /// **What the tenant has been DOING, day by day** — the flow series behind
525 /// the console's SILENT and FRICTION lists.
526 ///
527 /// [`Product::read_usage`] answers *how much is held*. Only this answers
528 /// *is this customer using the product, has it gone quiet, and is it being
529 /// refused* — and no stock meter has ever been able to.
530 ///
531 /// The window is Unix milliseconds, inclusive, resolved by the PRODUCT to
532 /// whole UTC days: `0` for `since` means the whole kept window, `0` for
533 /// `until` means now. The product is the half that knows what it keeps, and
534 /// a second arithmetic here would be a second answer to one question.
535 ///
536 /// # The default REFUSES BY NAME
537 ///
538 /// [`Product::purge_tenant`]'s rule, for the same shape of danger. The
539 /// permissive answer here is an empty series, and an empty series is
540 /// rendered as *this tenant has gone quiet* — so a product that never
541 /// implemented this would put every one of its customers on the SILENT list
542 /// and an operator would go and ask them why they had stopped. A refusal
543 /// naming the product is the safe wrong answer, and it says which plugin
544 /// owes the work.
545 fn read_activity(
546 &self,
547 tenant: &TenantId,
548 since_unix_ms: u64,
549 until_unix_ms: u64,
550 ) -> Result<Activity, ProductError> {
551 let _ = (tenant, since_unix_ms, until_unix_ms);
552 Err(ProductError::Refused(format!(
553 "the {} plugin cannot report a tenant's activity: it has no flow series, so an empty answer here would read as a customer who had gone quiet rather than as a question nobody asked the product.",
554 self.id()
555 )))
556 }
557 fn push_entitlement(&self, fact: &EntitlementFact) -> Result<(), ProductError>;
558
559 /// **Can this product actually DELIVER these caps to this tenant, today —
560 /// and out of what?** `Ok` says where the room comes from ([`Absorb`]);
561 /// `Err(reason)` is a refusal that names what is missing, in words for an
562 /// OPERATOR (the transaction gives a customer its own sentence instead).
563 ///
564 /// # Why it exists
565 ///
566 /// Everything else in monetize checks whether the money can be taken and
567 /// whether the iron can be bought. Nothing asked the third question, and it
568 /// is the one that decides whether the sale is honest: **once the disk is
569 /// attached, can the product use it?**
570 ///
571 /// For gunnar today the answer is often NO. The appliance's `/data` is a
572 /// 4x75 GB raid0 xfs set laid once at install (`InstallMode::Fresh`), there
573 /// is no runtime data-set growth, and gunnar is PID 1 with no shell — so a
574 /// disk monetize buys and attaches is **billed and invisible**. Selling a
575 /// bigger quota there does not fail; it succeeds, charges the customer, signs
576 /// a fact promising capacity, and the capacity is not there. That is the
577 /// worst failure shape this system has: money moved, everything green, the
578 /// promise hollow.
579 ///
580 /// # The contract
581 ///
582 /// * `caps` is the FULL target cap set, not a delta — the product is asked
583 /// about the world it would have to serve, not about the change.
584 /// * It is asked **before the reserve**, so a refusal costs nothing and
585 /// nothing has to be unwound. See
586 /// `monetize::transaction::Transaction::increase`.
587 /// * `Ok` is a claim, not a shrug. A plugin that cannot tell must say so
588 /// in an `Err`, because a plugin that guesses yes is indistinguishable
589 /// from one that knows, right up until a tenant is charged for nothing.
590 /// * `Ok(Absorb::OnHand)` forbids a purchase and `Ok(Absorb::WithIron)`
591 /// permits one. A product whose store cannot use bought iron must never
592 /// answer `WithIron`: it refuses instead, and says what would help.
593 /// * It has **no default implementation**, deliberately. A default `Ok(())`
594 /// would let a product that never thought about this answer yes forever,
595 /// which is exactly the silence this method exists to break.
596 ///
597 /// It may talk to the product (it is the plugin's own control plane), so it
598 /// may fail for the usual reasons; report those as a refusal with the reason
599 /// in it rather than inventing a yes.
600 fn can_absorb(&self, tenant: &TenantId, caps: &BTreeMap<String, u64>) -> Result<Absorb, String>;
601
602 /// **How much this product could still serve, across the whole product.**
603 ///
604 /// The denominator of `UI.md`'s `184 / 300 GiB` and the servable half of the
605 /// oversell number (`monetize::fleet`). [`Product::can_absorb`] asks the same
606 /// box a narrower question — *can you take THIS tenant to THIS cap* — and
607 /// answers yes or no; this one asks for the figure, because a fleet total
608 /// needs a number and not a verdict.
609 ///
610 /// **It has no default implementation, for [`Product::can_absorb`]'s reason.**
611 /// A default would let a product that never thought about capacity answer
612 /// forever, and whichever constant it returned would be a lie: 0 reads as a
613 /// full disk, `u64::MAX` reads as an empty one, and the truth for a product
614 /// that cannot measure is [`Servable::Unmeasured`] — which the plugin must
615 /// say in its own words, naming what is missing.
616 ///
617 /// It may talk to the product, so it may fail for the usual reasons; report
618 /// those as `Unmeasured` with the reason in them rather than inventing a
619 /// number.
620 fn servable(&self) -> Servable;
621
622 /// **Delete everything this tenant has in the product, and keep them locked
623 /// out while it happens.**
624 ///
625 /// The product half of a super purge. `monetize` can give the IRON back on
626 /// its own — `transaction::release_tenant` and
627 /// `CloudProvider::release_for` — and it cannot delete a byte of what is on
628 /// it, because only the product knows what a tenant's data IS. In gunnar it
629 /// is every repository in the account plus two classes of bytes that are
630 /// not in the catalog at all; nothing on this side of the seam could
631 /// enumerate that.
632 ///
633 /// # It must LOCK, and the lock is the product's
634 ///
635 /// A purge is not atomic — it walks and reclaims over minutes while the
636 /// product goes on serving — so anything the tenant does during the walk
637 /// lands behind it. The lockout that prevents that can only live where the
638 /// requests arrive, which is the product. gunnar's is `Accounts.Gate`, and
639 /// it is total rather than read-only because in gunnar a read creates
640 /// things: a fetch explodes objects into a cache the purge just unlinked.
641 ///
642 /// [`Purged::still_locked`] carries the outcome back, because a product
643 /// that emptied a tenant and could not let them back in has left an account
644 /// nobody can use, and that must not read as success anywhere above here.
645 ///
646 /// # The default REFUSES BY NAME
647 ///
648 /// Unlike [`Product::can_absorb`] and [`Product::servable`], which have no
649 /// default at all because every constant they could return is a lie about
650 /// capacity, this one's dangerous answer is a permissive `Ok` — a product
651 /// that never implemented it reporting a tenant's data gone when it is
652 /// still there, after which a super purge would cheerfully destroy the
653 /// disks it is on. A refusal naming the product is the safe wrong answer
654 /// and it says which product owes the work.
655 fn purge_tenant(&self, tenant: &TenantId, reason: &str) -> Result<Purged, ProductError> {
656 let _ = (tenant, reason);
657 Err(ProductError::Refused(format!(
658 "the {} plugin cannot purge a tenant's data: it has no purge verb, so nothing here \
659 can promise the tenant's bytes are gone. Empty the tenant in the product itself \
660 before releasing its resources.",
661 self.id()
662 )))
663 }
664
665 /// **The product's own half of a data-set growth**, if it has one. `None`
666 /// — the default — is a product whose set cannot be grown at runtime from
667 /// outside; monetize then refuses a growth by name before touching a
668 /// volume. See [`ApplianceGrow`].
669 fn grow(&self) -> Option<&dyn ApplianceGrow> {
670 None
671 }
672
673 /// **The product's twins, as its primary hears them** — one row per twin:
674 /// the heartbeat state, and the fill of the twin's data volume the twin
675 /// reported on its last poll. What the batcher's twin-fill trigger reads.
676 /// The default is no twins: a product without a twin has nothing to grow.
677 fn twins(&self) -> Result<Vec<TwinFill>, ProductError> {
678 Ok(Vec::new())
679 }
680
681 /// **Whether a tenant-presented actor ticket can be verified at all by this
682 /// product.** False means a console must not offer self-service renewal —
683 /// there is nothing here that could tell a customer from a stranger, so the
684 /// route must not exist rather than existing and refusing.
685 ///
686 /// Reported on the wire as `ProductInfo.tenant_renewal`.
687 fn tenant_renewal(&self) -> bool {
688 false
689 }
690
691 /// **May the bearer of this ticket act for `tenant`? Default DENY.**
692 ///
693 /// The ticket is the product's own appliance vouching that the human
694 /// driving a console holds the tenant they are paying for
695 /// (`monetize_embed::ticket`). monetize's gRPC surface authenticates one
696 /// shared bearer — an empty one means open — so this is the ONLY thing that
697 /// can tell "alice renewing alice" from "somebody renewing alice".
698 ///
699 /// # Why the argument is raw bytes
700 ///
701 /// `monetize-embed` — which owns `ActorTicket` and `verify_ticket` —
702 /// depends on THIS crate, so this crate cannot name that type without a
703 /// dependency cycle. The verification therefore happens in the PLUGIN,
704 /// which may depend on `monetize-embed`, and the seam carries the opaque
705 /// bytes it was handed. That is not a compromise: the plugin is also the
706 /// only half that holds the appliance's key, so it is where the check
707 /// belongs whichever way the crates pointed.
708 ///
709 /// # Why the default refuses
710 ///
711 /// A plugin is out of tree and nobody edits it when a path like this ships.
712 /// A default of `Allowed` would silently turn every such plugin into one
713 /// that honours signed bytes it holds no key for; a default that REFUSES
714 /// makes an unaudited product safe by omission rather than by somebody
715 /// remembering. The cost of the wrong default here is a customer who cannot
716 /// renew themselves; the cost of the other one is a stranger who can.
717 /// `purpose` and `caps` are what the REQUEST says, and they are arguments
718 /// rather than things the plugin reads off the ticket, because a verifier
719 /// cannot compare a claim against itself. A ticket names the verb it
720 /// authorises and — for an order — the amount it covers; the plugin's job
721 /// is to check both against the call that arrived. Passing them in is what
722 /// makes "this ticket is for a different order" a refusal that no
723 /// implementation can forget to make.
724 ///
725 /// `caps` is empty for a renewal, and a plugin must refuse a renewal ticket
726 /// that carries any.
727 fn may_act_for(
728 &self,
729 _tenant: &TenantId,
730 _purpose: &str,
731 _caps: &std::collections::BTreeMap<String, u64>,
732 _ticket: &[u8],
733 ) -> Result<ActorVerdict, ProductError> {
734 Ok(ActorVerdict::Refused("this product cannot verify a tenant-presented ticket".into()))
735 }
736}
737
738/// **What a product says about a ticket somebody presented.**
739///
740/// Not a `bool` and not a `Result<(), ProductError>`: a refusal is a normal,
741/// expected answer that carries a SENTENCE — the words a caller may show — and
742/// a `ProductError` means something else entirely (the product's control plane
743/// is down, the question could not be asked). Conflating the two would let an
744/// unreachable appliance read as a refused ticket, or worse, the reverse.
745#[derive(Clone, PartialEq, Eq, Debug)]
746pub enum ActorVerdict {
747 /// The ticket verifies, names this tenant, this product and this verb, is
748 /// inside its life, and has not been spent before.
749 Allowed,
750 /// Refused, and why — in words a customer surface may show. A verifier must
751 /// not name the ticket's own tenant back to whoever asked about another
752 /// one; see `monetize_embed::verify_ticket`.
753 Refused(String),
754}
755
756/// One twin as its primary last heard from it (gunnar's `TwinHeartbeat`).
757#[derive(Clone, PartialEq, Eq, Debug, Default, serde::Serialize, serde::Deserialize)]
758pub struct TwinFill {
759 pub principal: String,
760 pub address: String,
761 /// `ok` | `behind` | `silent`.
762 pub state: String,
763 /// Wall clock of the twin's last poll; 0 = never heard.
764 pub last_seen_unix_ms: i64,
765 pub lag_entries: u64,
766 pub disk_total_bytes: u64,
767 pub disk_used_bytes: u64,
768 /// used × 1000 / total; 0 when total is unknown.
769 pub fill_permille: u32,
770}
771
772impl TwinFill {
773 /// The primary can still hear it: `ok` or `behind`, never `silent` or a word we do not know.
774 pub fn visible(&self) -> bool {
775 matches!(self.state.as_str(), "ok" | "behind")
776 }
777}
778
779// ── the appliance's half of a data-set growth ───────────────────────────────
780
781/// **What the appliance does INSIDE the box while the outside actor grows its
782/// volumes** (`DATA-SET-GROWTH-FLOW.md` §0 ruling 1, T6): drain, unmount, wait
783/// for the members to come back larger, run its engine, mount, reopen. monetize
784/// drives it — flush → start → wait `unmounted` → cloud steps → resume → wait
785/// `done|failed` — and every verb here is one call on the product's control
786/// plane. Vendor-neutral: the words are the phases the flow document names,
787/// and the go-ahead is opaque bytes the product verifies on its own terms.
788pub trait ApplianceGrow: Send + Sync {
789 /// **Prove the twin is caught up** (T11, step 0) — flush replication to
790 /// every standby, bounded by `timeout_secs` (0 = the product's own ceiling),
791 /// and report. Changes no role and no roster.
792 fn flush(&self, timeout_secs: u32) -> Result<FlushReport, ProductError>;
793 /// Begin the growth: drain, unmount, wait for the members. `go_ahead` is
794 /// the signed approval (see `monetize_embed::signing::go_ahead_message`);
795 /// `target_sectors_per_member` is in 512-byte sectors, 0 = "whatever every
796 /// member comes back larger at". Answers the status after the call.
797 fn start(&self, target_sectors_per_member: u64, go_ahead: &[u8]) -> Result<GrowStatus, ProductError>;
798 /// The phase and the members, as the product sees them. **Must answer
799 /// while the set is unmounted and, where the product offers it, without a
800 /// credential** — the outside actor decides whether to re-attach from it.
801 fn status(&self) -> Result<GrowStatus, ProductError>;
802 /// "Look again": the members are back. With `give_up`, stop waiting and
803 /// serve whatever is there at whatever size it is.
804 fn resume(&self, give_up: bool) -> Result<GrowStatus, ProductError>;
805}
806
807/// The phases a product reports, as `DATA-SET-GROWTH-FLOW.md` names them.
808/// Kept as words on the wire (`GrowStatus::phase`); this is the reader.
809#[derive(Clone, Copy, PartialEq, Eq, Debug)]
810pub enum GrowPhase {
811 Idle,
812 Draining,
813 Unmounted,
814 WaitingMembers,
815 Growing,
816 Mounting,
817 Done,
818 Failed,
819 /// A word this monetize does not know — a newer product. Shown, never
820 /// acted on.
821 Other,
822}
823
824impl GrowPhase {
825 pub fn parse(word: &str) -> GrowPhase {
826 match word {
827 "idle" => GrowPhase::Idle,
828 "draining" => GrowPhase::Draining,
829 "unmounted" => GrowPhase::Unmounted,
830 "waiting-members" => GrowPhase::WaitingMembers,
831 "growing" => GrowPhase::Growing,
832 "mounting" => GrowPhase::Mounting,
833 "done" => GrowPhase::Done,
834 "failed" => GrowPhase::Failed,
835 _ => GrowPhase::Other,
836 }
837 }
838 /// The set is off the stripe: the outside actor may touch the volumes.
839 pub fn volumes_free(self) -> bool {
840 matches!(self, GrowPhase::Unmounted | GrowPhase::WaitingMembers)
841 }
842 pub fn is_terminal(self) -> bool {
843 matches!(self, GrowPhase::Done | GrowPhase::Failed | GrowPhase::Idle)
844 }
845}
846
847/// One member of the set as the product last surveyed it.
848#[derive(Clone, PartialEq, Eq, Debug, Default, serde::Serialize, serde::Deserialize)]
849pub struct GrowMember {
850 pub index: u32,
851 pub device: String,
852 pub disk_bytes: u64,
853 pub set_bytes: u64,
854 pub larger: bool,
855}
856
857/// The product's answer to [`ApplianceGrow::status`].
858#[derive(Clone, PartialEq, Eq, Debug, Default, serde::Serialize, serde::Deserialize)]
859pub struct GrowStatus {
860 /// `idle` | `draining` | `unmounted` | `waiting-members` | `growing` |
861 /// `mounting` | `done` | `failed`. Read with [`GrowPhase::parse`].
862 pub phase: String,
863 /// `failed`'s reason; empty otherwise.
864 pub why: String,
865 pub epoch: u64,
866 pub target_sectors_per_member: u64,
867 pub members: Vec<GrowMember>,
868 pub members_verdict: String,
869 pub engine_present: bool,
870 pub serving: bool,
871 pub in_flight: u64,
872 pub since_unix_ms: i64,
873 pub detail: String,
874 pub go_ahead_signer: String,
875 pub set_uuid: String,
876 pub total_bytes: u64,
877}
878
879impl GrowStatus {
880 pub fn phase(&self) -> GrowPhase {
881 GrowPhase::parse(&self.phase)
882 }
883}
884
885/// The product's answer to [`ApplianceGrow::flush`]: is the twin caught up,
886/// and what does that prove.
887#[derive(Clone, PartialEq, Eq, Debug, Default, serde::Serialize, serde::Deserialize)]
888pub struct FlushReport {
889 pub caught_up: bool,
890 pub in_flight: u64,
891 pub pending: u64,
892 pub bus_gaps: u64,
893 pub needs_full_resync: bool,
894 pub last_success_unix_ms: i64,
895 pub flushed_at_unix_ms: i64,
896 pub waited_ms: u64,
897 pub catalog_repos: u64,
898 pub standbys: u64,
899 pub verdict: String,
900}
901
902/// What [`Product::purge_tenant`] did.
903#[derive(Clone, PartialEq, Eq, Debug)]
904pub struct Purged {
905 pub tenant: TenantId,
906 /// What the product removed, in its own words and its own units — "5 of 5
907 /// stores, 1.2 GiB". Free text because every product counts different
908 /// things and a shared schema would force each of them to lie a little.
909 pub detail: String,
910 /// Bytes the product says it reclaimed. `None` means it does not count
911 /// them, which is not the same as zero and must not be rendered as it.
912 pub bytes_reclaimed: Option<u64>,
913 /// **Is the tenant still locked out of the product?**
914 ///
915 /// `true` is a real and expected outcome — an operator may have suspended
916 /// the account separately, and the purge correctly refuses to lift a
917 /// lockout it did not take — but it is also what a purge that could not
918 /// unlock reports, and either way the tenant cannot use what is left.
919 /// Carried so a super purge can say so rather than infer it.
920 pub still_locked: bool,
921 /// One line per thing the product could not remove. Non-empty means the
922 /// tenant's data is PARTIALLY there, and the caller must not go on to
923 /// destroy the iron it is sitting on.
924 pub failures: Vec<String>,
925}
926
927/// **Bytes in the largest unit that still leaves a digit before the decimal
928/// point**, by integer arithmetic: `10.0 GiB`, `64.0 MiB`, `999 B`.
929///
930/// One writer, because there used to be three and every one of them carried the
931/// same bug. Each divided by 1 GiB unconditionally and printed one decimal, so
932/// anything under a gibibyte rendered `0.0 GiB` — and `0.0` beside a quantity is
933/// read as *there is none*:
934///
935/// * the console (then a Plans page) showed a real 64 MiB
936/// `pack_bytes` cap as `0.0 GiB`, which an operator reads as "no quota";
937/// * the old catalogue validator said *"sells pack_bytes = 10.0 GiB but
938/// its resources buy only 10.0 GiB — short 0.0 GiB"*, a sentence in which
939/// every number is wrong in the direction of "nothing is the matter";
940/// * `products/gunnar`'s capacity refusals said "short 0.0 GiB" for the same
941/// reason.
942///
943/// It lives here because this is the crate that already owns the meter
944/// vocabulary ([`Meter`], [`Backing::DiskBytes`]) and the only one every side
945/// can depend on: core, the product plugins, and the browser console alike. It
946/// pulls in nothing (this crate is `serde` and nothing else), so the wasm
947/// bundle pays a few hundred bytes for a formatter it was carrying anyway.
948///
949/// Truncates, never rounds up: a reading must not appear to cross a cap it has
950/// not crossed.
951pub fn bytes(n: u64) -> String {
952 const KIB: u64 = 1 << 10;
953 const MIB: u64 = 1 << 20;
954 const GIB: u64 = 1 << 30;
955 const TIB: u64 = 1 << 40;
956 let (unit, per) = match n {
957 n if n >= TIB => ("TiB", TIB),
958 n if n >= GIB => ("GiB", GIB),
959 n if n >= MIB => ("MiB", MIB),
960 n if n >= KIB => ("KiB", KIB),
961 // Under a kibibyte there is nothing to scale to, and `0.0 KiB` would be
962 // the same lie one unit down. Bytes are exact and short.
963 n => return format!("{n} B"),
964 };
965 format!("{}.{} {unit}", n / per, ((n % per) * 10) / per)
966}
967
968#[cfg(test)]
969mod backing_tests {
970 use super::Backing;
971
972 /// **A byte over the GiB is sold the next GiB, and a millicore is priced
973 /// as a thousandth of a core.** Distinct non-zero numbers: 2200 öre per
974 /// GiB-month, 90 GiB + 1 byte, 1500 millicores at 30 000.
975 #[test]
976 fn prices_round_bytes_up_to_the_unit_and_cpu_by_the_millicore() {
977 const GIB: u64 = 1 << 30;
978 assert_eq!(Backing::DiskBytes.price_month(90 * GIB, 2200), 198_000, "90 GiB × 22.00 SEK");
979 assert_eq!(Backing::DiskBytes.price_month(90 * GIB + 1, 2200), 200_200, "one byte over is the 91st GiB");
980 assert_eq!(Backing::DiskBytes.price_month(0, 2200), 0);
981 assert_eq!(Backing::RamBytes.price_month(3 * GIB, 700), 2100);
982 assert_eq!(Backing::CpuMillicores.price_month(1500, 30_000), 45_000, "1.5 cores at 300.00");
983 assert_eq!(Backing::CpuMillicores.price_month(1, 30_000), 30, "one millicore is not free and not a core");
984 // A zero unit price is FREE, whatever the delta: the open-source list.
985 for b in Backing::ALL {
986 assert_eq!(b.price_month(u64::MAX / 4, 0), 0, "{b:?}");
987 }
988 // The unit names are the price list's keys, both ways.
989 for b in Backing::ALL {
990 assert_eq!(Backing::from_unit(b.unit()), Some(b));
991 }
992 assert_eq!(Backing::from_unit("moon_month"), None);
993 }
994}
995
996#[cfg(test)]
997mod bytes_tests {
998 use super::bytes;
999
1000 /// **A quantity that exists never renders as zero.** RED before this
1001 /// function existed: `0.0 GiB` for every value under 2^30, in three separate
1002 /// copies of the same six lines.
1003 #[test]
1004 fn only_a_genuine_zero_reads_as_zero() {
1005 for n in [1u64, 512, 1 << 20, 67_108_864, (1 << 30) - 1] {
1006 let s = bytes(n);
1007 assert!(!s.starts_with("0.0 ") && !s.starts_with("0 "), "{n} bytes rendered as {s:?}, which reads as nothing");
1008 }
1009 assert_eq!(bytes(0), "0 B");
1010 }
1011
1012 #[test]
1013 fn the_unit_scales_and_the_value_truncates() {
1014 assert_eq!(bytes(999), "999 B");
1015 assert_eq!(bytes(1536), "1.5 KiB");
1016 assert_eq!(bytes(67_108_864), "64.0 MiB");
1017 assert_eq!(bytes((1 << 30) - 1), "1023.9 MiB", "truncates, never rounds up past the cap");
1018 assert_eq!(bytes(10 << 30), "10.0 GiB");
1019 assert_eq!(bytes(3 << 40), "3.0 TiB");
1020 assert_eq!(bytes(u64::MAX), "16777215.9 TiB", "no overflow at the top of the range");
1021 }
1022}
1023
1024#[cfg(test)]
1025mod actor_tests {
1026 use super::*;
1027
1028 /// A plugin written before the tenant path existed: it implements every
1029 /// method the trait REQUIRES and knows nothing about tickets.
1030 struct OldPlugin;
1031
1032 impl Product for OldPlugin {
1033 fn id(&self) -> &'static str {
1034 "old"
1035 }
1036 fn meters(&self) -> &[Meter] {
1037 &[]
1038 }
1039 fn list_tenants(&self) -> Result<Vec<TenantId>, ProductError> {
1040 Ok(Vec::new())
1041 }
1042 fn read_usage(&self, _tenant: &TenantId) -> Result<Usage, ProductError> {
1043 Err(ProductError::Refused("no".into()))
1044 }
1045 fn push_entitlement(&self, _fact: &EntitlementFact) -> Result<(), ProductError> {
1046 Ok(())
1047 }
1048 fn can_absorb(&self, _tenant: &TenantId, _caps: &BTreeMap<String, u64>) -> Result<Absorb, String> {
1049 Ok(Absorb::OnHand)
1050 }
1051 fn servable(&self) -> Servable {
1052 Servable::Unmeasured("a test double measures nothing".to_owned())
1053 }
1054 }
1055
1056 /// ★ **Safe by OMISSION, not by remembering.**
1057 ///
1058 /// The out-of-tree plugin nobody will edit when this path ships must not
1059 /// start honouring signed bytes it has no key for. Both halves of the
1060 /// default say no: it does not advertise the capability, and it refuses
1061 /// every ticket rather than falling through to an allow.
1062 #[test]
1063 fn a_product_that_never_heard_of_a_ticket_refuses_every_one() {
1064 let p = OldPlugin;
1065 assert!(!p.tenant_renewal(), "a console must not be told to offer self-service here");
1066 let verdict = // The literal and not a constant: this crate cannot depend on
1067 // `monetize-embed` (that would be a cycle), which is exactly why the
1068 // trait takes the purpose as a `&str`. The default refuses whatever it
1069 // is handed, so the word decides nothing here.
1070 p.may_act_for(&TenantId("alice".into()), "renew", &Default::default(), b"anything at all").expect("the default answers rather than erroring");
1071 let ActorVerdict::Refused(why) = verdict else { panic!("the default must DENY") };
1072 assert!(!why.trim().is_empty(), "a refusal says why");
1073 }
1074}