Skip to main content

rings_core/message/
quota.rs

1//! Runtime-local origin quotas for final-destination transactions.
2//!
3//! A quota key is `(network_id, origin account DID, destination DID, logical lane)`. Each key
4//! owns independent fixed-point message and byte token buckets, and quota records in each lane's
5//! bounded table are charged to their introducing [`Principal`] under [`SlotAccounting`]
6//! ([`ORIGIN_QUOTA_SHARES`]), preserving each connection slot's floor, [`Principal::Local`], and
7//! [`Principal::Inbox`] (#1178). [`OriginQuota::admit`] is the pure transition; the destination
8//! replay runtime owns the bounded table and supplies monotonic time. Quota records are
9//! intentionally absent from the durable replay store.
10//!
11//! An admission either enforces the message limit or, for traffic whose namespace delegated its
12//! admission, skips it ([`MessageLimit`]); the byte limit and the record bound always apply. A
13//! delegated admission pays at least [`DELEGATED_MIN_CHARGE`] bytes, so the byte bucket also
14//! bounds how many messages core admits for it.
15
16use std::collections::BTreeMap;
17use std::sync::atomic::AtomicU64;
18use std::sync::atomic::Ordering;
19
20use serde::Deserialize;
21use serde::Serialize;
22
23use crate::dht::Did;
24use crate::fair_admission::Principal;
25use crate::fair_admission::Shares;
26use crate::fair_admission::SlotAccounting;
27use crate::message::admission_delegation::MessageLimit;
28use crate::message::types::MessageCategory;
29
30const NANOS_PER_SECOND: u128 = 1_000_000_000;
31/// Default message rate admitted for one origin in one logical lane.
32pub const DEFAULT_ORIGIN_QUOTA_MESSAGES_PER_SECOND: u64 = 64;
33/// Default instantaneous message allowance for one origin in one logical lane.
34pub const DEFAULT_ORIGIN_QUOTA_MESSAGE_BURST: u64 = 128;
35/// Default byte rate admitted for one origin in one logical lane.
36pub const DEFAULT_ORIGIN_QUOTA_BYTES_PER_SECOND: u64 = 4 * 1024 * 1024;
37/// Default instantaneous byte allowance for one origin in one logical lane.
38///
39/// This exceeds the 60 MB logical-message protocol ceiling, so every valid message can fit an
40/// otherwise full bucket.
41pub const DEFAULT_ORIGIN_QUOTA_BYTE_BURST: u64 = 64 * 1024 * 1024;
42/// Minimum byte charge of a delegated admission.
43///
44/// Every admitted final-destination message costs core a fixed amount of work: the
45/// replay-record persist under the replay lock, then its logical lane, validation and dispatch.
46/// A delegated admission skips the message limit, so without a floor only the byte bucket would
47/// bound how many messages are admitted, and tiny messages would multiply that work. Charging
48/// `max(len, DELEGATED_MIN_CHARGE)` bounds a neighbour's delegated admissions to
49/// `byte_rate / 16 KiB` per second (256/s under the default 4 MiB/s), with a burst of
50/// `byte_burst / 16 KiB` (4096 by default). Messages of at least 16 KiB pay exactly their
51/// length. The decode and signature checks run before the quota and are not bounded by it.
52pub const DELEGATED_MIN_CHARGE: usize = 16 * 1024;
53/// Default number of runtime-local origin records retained per logical lane.
54pub const DEFAULT_ORIGIN_QUOTA_RECORDS_PER_LANE: usize = 4096;
55
56/// The shares of one logical lane's origin-quota record table under
57/// [`DEFAULT_ORIGIN_QUOTA_RECORDS_PER_LANE`] (load-bounds paper, Law 1, #1178): `f = 1` record
58/// per connection slot, a shared pool of `2048`, a local share of `1056` and an inbox share of
59/// `640`, so `B(s) = R(s) + 3744`: `4074` at `s = 4` and `4096` at `s = 15`.
60pub(crate) const ORIGIN_QUOTA_SHARES: Shares = Shares {
61    floor: 1,
62    pool: 2048,
63    local: 1056,
64    inbox: 640,
65    custody: 0,
66};
67
68const ORIGIN_QUOTA_SUCCESSORS_MAX: usize = 15;
69const _: () = assert!(
70    ORIGIN_QUOTA_SHARES.bound(crate::dht::topology::edge_slots(
71        ORIGIN_QUOTA_SUCCESSORS_MAX
72    )) <= DEFAULT_ORIGIN_QUOTA_RECORDS_PER_LANE
73);
74const _: () = assert!(
75    ORIGIN_QUOTA_SHARES.bound(crate::dht::topology::edge_slots(
76        ORIGIN_QUOTA_SUCCESSORS_MAX + 1
77    )) > DEFAULT_ORIGIN_QUOTA_RECORDS_PER_LANE
78);
79
80const fn shares_for_capacity(max_records: usize) -> Shares {
81    if max_records >= DEFAULT_ORIGIN_QUOTA_RECORDS_PER_LANE {
82        Shares {
83            floor: ORIGIN_QUOTA_SHARES.floor,
84            pool: ORIGIN_QUOTA_SHARES
85                .pool
86                .saturating_add(max_records - DEFAULT_ORIGIN_QUOTA_RECORDS_PER_LANE),
87            local: ORIGIN_QUOTA_SHARES.local,
88            inbox: ORIGIN_QUOTA_SHARES.inbox,
89            custody: ORIGIN_QUOTA_SHARES.custody,
90        }
91    } else {
92        Shares {
93            floor: 1,
94            pool: max_records.saturating_sub(2),
95            local: max_records,
96            inbox: max_records,
97            custody: 0,
98        }
99    }
100}
101
102/// Validated token-bucket and record-table limits for one logical lane.
103#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
104#[serde(into = "OriginQuotaLaneConfigWire")]
105pub struct OriginQuotaLaneConfig {
106    message_rate_per_second: u64,
107    message_burst: u64,
108    byte_rate_per_second: u64,
109    byte_burst: u64,
110    max_records: usize,
111}
112
113#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
114struct OriginQuotaLaneConfigWire {
115    message_rate_per_second: u64,
116    message_burst: u64,
117    byte_rate_per_second: u64,
118    byte_burst: u64,
119    max_records: usize,
120}
121
122impl OriginQuotaLaneConfig {
123    /// Validate and construct one lane's token-bucket and table limits.
124    pub fn new(
125        message_rate_per_second: u64,
126        message_burst: u64,
127        byte_rate_per_second: u64,
128        byte_burst: u64,
129        max_records: usize,
130    ) -> std::result::Result<Self, OriginQuotaConfigError> {
131        if message_rate_per_second == 0 {
132            return Err(OriginQuotaConfigError::ZeroMessageRate);
133        }
134        if message_burst == 0 {
135            return Err(OriginQuotaConfigError::ZeroMessageBurst);
136        }
137        if byte_rate_per_second == 0 {
138            return Err(OriginQuotaConfigError::ZeroByteRate);
139        }
140        if byte_burst == 0 {
141            return Err(OriginQuotaConfigError::ZeroByteBurst);
142        }
143        if max_records == 0 {
144            return Err(OriginQuotaConfigError::ZeroRecordCapacity);
145        }
146        Ok(Self {
147            message_rate_per_second,
148            message_burst,
149            byte_rate_per_second,
150            byte_burst,
151            max_records,
152        })
153    }
154
155    /// Messages replenished per second.
156    pub const fn message_rate_per_second(self) -> u64 {
157        self.message_rate_per_second
158    }
159
160    /// Maximum accumulated message tokens.
161    pub const fn message_burst(self) -> u64 {
162        self.message_burst
163    }
164
165    /// Bytes replenished per second.
166    pub const fn byte_rate_per_second(self) -> u64 {
167        self.byte_rate_per_second
168    }
169
170    /// Maximum accumulated byte tokens.
171    pub const fn byte_burst(self) -> u64 {
172        self.byte_burst
173    }
174
175    /// Maximum runtime-local records retained for this lane.
176    pub const fn max_records(self) -> usize {
177        self.max_records
178    }
179}
180
181impl Default for OriginQuotaLaneConfig {
182    fn default() -> Self {
183        Self {
184            message_rate_per_second: DEFAULT_ORIGIN_QUOTA_MESSAGES_PER_SECOND,
185            message_burst: DEFAULT_ORIGIN_QUOTA_MESSAGE_BURST,
186            byte_rate_per_second: DEFAULT_ORIGIN_QUOTA_BYTES_PER_SECOND,
187            byte_burst: DEFAULT_ORIGIN_QUOTA_BYTE_BURST,
188            max_records: DEFAULT_ORIGIN_QUOTA_RECORDS_PER_LANE,
189        }
190    }
191}
192
193impl From<OriginQuotaLaneConfig> for OriginQuotaLaneConfigWire {
194    fn from(value: OriginQuotaLaneConfig) -> Self {
195        Self {
196            message_rate_per_second: value.message_rate_per_second,
197            message_burst: value.message_burst,
198            byte_rate_per_second: value.byte_rate_per_second,
199            byte_burst: value.byte_burst,
200            max_records: value.max_records,
201        }
202    }
203}
204
205impl TryFrom<OriginQuotaLaneConfigWire> for OriginQuotaLaneConfig {
206    type Error = OriginQuotaConfigError;
207
208    fn try_from(value: OriginQuotaLaneConfigWire) -> Result<Self, Self::Error> {
209        Self::new(
210            value.message_rate_per_second,
211            value.message_burst,
212            value.byte_rate_per_second,
213            value.byte_burst,
214            value.max_records,
215        )
216    }
217}
218
219impl<'de> Deserialize<'de> for OriginQuotaLaneConfig {
220    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
221    where D: serde::Deserializer<'de> {
222        OriginQuotaLaneConfigWire::deserialize(deserializer)?
223            .try_into()
224            .map_err(serde::de::Error::custom)
225    }
226}
227
228/// Per-lane final-destination quota configuration.
229#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
230pub struct OriginQuotaConfig {
231    /// Chord control-lane limits.
232    pub dht_control: OriginQuotaLaneConfig,
233    /// Storage-lane limits.
234    pub storage: OriginQuotaLaneConfig,
235    /// End-to-end protocol-lane limits.
236    pub e2e: OriginQuotaLaneConfig,
237    /// Application-lane limits.
238    pub application: OriginQuotaLaneConfig,
239}
240
241impl OriginQuotaConfig {
242    /// Construct a validated per-lane configuration.
243    pub const fn new(
244        dht_control: OriginQuotaLaneConfig,
245        storage: OriginQuotaLaneConfig,
246        e2e: OriginQuotaLaneConfig,
247        application: OriginQuotaLaneConfig,
248    ) -> Self {
249        Self {
250            dht_control,
251            storage,
252            e2e,
253            application,
254        }
255    }
256
257    /// Return the limits for `lane`.
258    pub const fn lane(self, lane: MessageCategory) -> OriginQuotaLaneConfig {
259        match lane {
260            MessageCategory::DhtControl => self.dht_control,
261            MessageCategory::Storage => self.storage,
262            MessageCategory::E2e => self.e2e,
263            MessageCategory::Application => self.application,
264        }
265    }
266}
267
268impl Default for OriginQuotaConfig {
269    fn default() -> Self {
270        let lane = OriginQuotaLaneConfig::default();
271        Self::new(lane, lane, lane, lane)
272    }
273}
274
275/// Why a lane quota configuration is invalid.
276#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
277pub enum OriginQuotaConfigError {
278    /// A zero rate could never replenish a message bucket.
279    #[error("origin quota message rate must be non-zero")]
280    ZeroMessageRate,
281    /// A zero burst could never admit a message.
282    #[error("origin quota message burst must be non-zero")]
283    ZeroMessageBurst,
284    /// A zero rate could never replenish a byte bucket.
285    #[error("origin quota byte rate must be non-zero")]
286    ZeroByteRate,
287    /// A zero burst could never admit message bytes.
288    #[error("origin quota byte burst must be non-zero")]
289    ZeroByteBurst,
290    /// A zero bound could retain no origin record.
291    #[error("origin quota record capacity must be non-zero")]
292    ZeroRecordCapacity,
293}
294
295/// Monotonic runtime-local instant used by the pure quota transition.
296#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
297pub struct OriginQuotaInstant(u128);
298
299impl OriginQuotaInstant {
300    /// The runtime start instant.
301    pub const ZERO: Self = Self(0);
302
303    /// Construct an instant from elapsed monotonic nanoseconds.
304    pub const fn from_nanos(nanos: u128) -> Self {
305        Self(nanos)
306    }
307}
308
309/// Identity of one runtime-local origin quota record.
310#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
311pub struct OriginQuotaKey {
312    /// Overlay in which the transaction signature is valid.
313    pub network_id: u32,
314    /// Account DID recovered from the transaction signature.
315    pub origin_account: Did,
316    /// Final logical destination.
317    pub destination: Did,
318    /// Logical inbound lane selected from the verified message.
319    pub lane: MessageCategory,
320}
321
322impl OriginQuotaKey {
323    /// Name one origin-to-destination lane inside an overlay.
324    pub const fn new(
325        network_id: u32,
326        origin_account: Did,
327        destination: Did,
328        lane: MessageCategory,
329    ) -> Self {
330        Self {
331            network_id,
332            origin_account,
333            destination,
334            lane,
335        }
336    }
337}
338
339#[derive(Clone, Copy, Debug, Eq, PartialEq)]
340struct TokenBucket {
341    scaled_tokens: u128,
342}
343
344impl TokenBucket {
345    fn full(burst: u64) -> Self {
346        Self {
347            scaled_tokens: u128::from(burst) * NANOS_PER_SECOND,
348        }
349    }
350
351    fn refill(self, rate: u64, burst: u64, elapsed_nanos: u128) -> Self {
352        let capacity = u128::from(burst) * NANOS_PER_SECOND;
353        let replenished = elapsed_nanos.saturating_mul(u128::from(rate));
354        Self {
355            scaled_tokens: self.scaled_tokens.saturating_add(replenished).min(capacity),
356        }
357    }
358
359    fn has(self, scaled_cost: u128) -> bool {
360        self.scaled_tokens >= scaled_cost
361    }
362
363    fn consume(&mut self, scaled_cost: u128) {
364        self.scaled_tokens = self.scaled_tokens.saturating_sub(scaled_cost);
365    }
366
367    fn is_full(self, burst: u64) -> bool {
368        self.scaled_tokens == u128::from(burst) * NANOS_PER_SECOND
369    }
370}
371
372/// Pure message and byte token-bucket state for one origin quota key.
373#[derive(Clone, Copy, Debug, Eq, PartialEq)]
374pub struct OriginQuota {
375    messages: TokenBucket,
376    bytes: TokenBucket,
377    last_refill: OriginQuotaInstant,
378}
379
380impl OriginQuota {
381    /// Construct a fully replenished record at `now`.
382    pub fn full(config: OriginQuotaLaneConfig, now: OriginQuotaInstant) -> Self {
383        Self {
384            messages: TokenBucket::full(config.message_burst),
385            bytes: TokenBucket::full(config.byte_burst),
386            last_refill: now,
387        }
388    }
389
390    /// Apply one deterministic logical-message admission transition.
391    ///
392    /// Rejected transitions retain any refill but consume neither dimension. The byte cost is the
393    /// verified transaction's serialized logical `data` length; chunk-envelope sizes never enter
394    /// this transition. Under [`MessageLimit::Delegated`] the message cost is zero: the message
395    /// bucket is neither checked nor consumed, while the byte bucket is charged at least
396    /// [`DELEGATED_MIN_CHARGE`].
397    pub fn admit(
398        self,
399        config: OriginQuotaLaneConfig,
400        message_limit: MessageLimit,
401        byte_cost: usize,
402        now: OriginQuotaInstant,
403    ) -> Result<(Self, OriginQuotaVerdict), OriginQuotaArithmeticError> {
404        let mut next = self.refilled(config, now)?;
405        let message_cost = scaled_message_cost(message_limit);
406        if !next.messages.has(message_cost) {
407            return Ok((next, OriginQuotaVerdict::MessageRateExhausted));
408        }
409        let byte_cost = charged_bytes(message_limit, byte_cost);
410        let byte_cost =
411            u128::try_from(byte_cost).map_err(|_| OriginQuotaArithmeticError::ByteCostOverflow)?;
412        let scaled_byte_cost = byte_cost
413            .checked_mul(NANOS_PER_SECOND)
414            .ok_or(OriginQuotaArithmeticError::ByteCostOverflow)?;
415        if !next.bytes.has(scaled_byte_cost) {
416            return Ok((next, OriginQuotaVerdict::ByteRateExhausted));
417        }
418        next.messages.consume(message_cost);
419        next.bytes.consume(scaled_byte_cost);
420        Ok((next, OriginQuotaVerdict::Admitted))
421    }
422
423    fn refilled(
424        self,
425        config: OriginQuotaLaneConfig,
426        now: OriginQuotaInstant,
427    ) -> Result<Self, OriginQuotaArithmeticError> {
428        let elapsed = now
429            .0
430            .checked_sub(self.last_refill.0)
431            .ok_or(OriginQuotaArithmeticError::MonotonicTimeRegressed)?;
432        Ok(Self {
433            messages: self.messages.refill(
434                config.message_rate_per_second,
435                config.message_burst,
436                elapsed,
437            ),
438            bytes: self
439                .bytes
440                .refill(config.byte_rate_per_second, config.byte_burst, elapsed),
441            last_refill: now,
442        })
443    }
444
445    fn fully_replenished_at(
446        self,
447        config: OriginQuotaLaneConfig,
448        now: OriginQuotaInstant,
449    ) -> Result<bool, OriginQuotaArithmeticError> {
450        let replenished = self.refilled(config, now)?;
451        Ok(replenished.messages.is_full(config.message_burst)
452            && replenished.bytes.is_full(config.byte_burst))
453    }
454
455    #[cfg(test)]
456    fn whole_message_tokens(self) -> u128 {
457        self.messages.scaled_tokens / NANOS_PER_SECOND
458    }
459
460    #[cfg(test)]
461    fn whole_byte_tokens(self) -> u128 {
462        self.bytes.scaled_tokens / NANOS_PER_SECOND
463    }
464}
465
466/// Scaled message tokens one admission costs: one token, or none when admission is delegated.
467const fn scaled_message_cost(message_limit: MessageLimit) -> u128 {
468    match message_limit {
469        MessageLimit::Enforced => NANOS_PER_SECOND,
470        MessageLimit::Delegated => 0,
471    }
472}
473
474/// Bytes one admission of `byte_cost` logical bytes is charged: its length, raised to
475/// [`DELEGATED_MIN_CHARGE`] when admission is delegated.
476fn charged_bytes(message_limit: MessageLimit, byte_cost: usize) -> usize {
477    match message_limit {
478        MessageLimit::Enforced => byte_cost,
479        MessageLimit::Delegated => byte_cost.max(DELEGATED_MIN_CHARGE),
480    }
481}
482
483/// Typed result of applying an origin quota decision.
484#[derive(Clone, Copy, Debug, Eq, PartialEq)]
485pub enum OriginQuotaVerdict {
486    /// Both token dimensions admitted and consumed the logical message.
487    Admitted,
488    /// The message token bucket lacks one complete token.
489    MessageRateExhausted,
490    /// The byte token bucket lacks the complete deterministic logical-message cost.
491    ByteRateExhausted,
492}
493
494impl OriginQuotaVerdict {
495    fn rejection(self) -> Option<OriginQuotaRejection> {
496        match self {
497            Self::Admitted => None,
498            Self::MessageRateExhausted => Some(OriginQuotaRejection::MessageRate),
499            Self::ByteRateExhausted => Some(OriginQuotaRejection::ByteRate),
500        }
501    }
502}
503
504/// Arithmetic failure in the pure quota transition.
505#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
506pub enum OriginQuotaArithmeticError {
507    /// The supplied monotonic instant preceded the record's last refill.
508    #[error("origin quota monotonic time regressed")]
509    MonotonicTimeRegressed,
510    /// The deterministic logical-message byte cost could not be represented safely.
511    #[error("origin quota byte cost overflowed fixed-point arithmetic")]
512    ByteCostOverflow,
513}
514
515/// Failure at the final-destination origin-quota boundary.
516#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
517pub enum OriginQuotaError {
518    /// A verified origin exhausted its message-rate allowance.
519    #[error("Origin quota message rate exhausted for {key:?}")]
520    MessageRateExhausted {
521        /// Origin, destination, overlay, and logical lane sharing the allowance.
522        key: OriginQuotaKey,
523    },
524    /// A verified origin exhausted its byte-rate allowance.
525    #[error(
526        "Origin quota byte rate exhausted for {key:?} while admitting {requested_bytes} bytes"
527    )]
528    ByteRateExhausted {
529        /// Origin, destination, overlay, and logical lane sharing the allowance.
530        key: OriginQuotaKey,
531        /// Deterministic logical-message bytes requested.
532        requested_bytes: usize,
533    },
534    /// A lane's bounded origin table had no fully replenished record safe to reuse.
535    #[error("Origin quota table for {lane:?} exhausted its {capacity} records")]
536    TableCapacityExhausted {
537        /// Logical lane whose record bound was reached.
538        lane: MessageCategory,
539        /// Maximum retained records for that lane.
540        capacity: usize,
541    },
542    /// The pure origin-quota transition could not be evaluated safely.
543    #[error("Origin quota arithmetic failed for {key:?}: {source}")]
544    Arithmetic {
545        /// Origin, destination, overlay, and logical lane being evaluated.
546        key: OriginQuotaKey,
547        /// Typed arithmetic or monotonic-clock failure.
548        #[source]
549        source: OriginQuotaArithmeticError,
550    },
551}
552
553#[derive(Debug)]
554pub(super) enum OriginQuotaAdmissionError {
555    Verdict(OriginQuotaRejection),
556    Arithmetic(OriginQuotaArithmeticError),
557}
558
559#[derive(Debug)]
560pub(super) enum OriginQuotaRejection {
561    MessageRate,
562    ByteRate,
563    Capacity { capacity: usize },
564}
565
566#[derive(Clone, Copy, Debug, Eq, PartialEq)]
567pub(super) struct OriginQuotaRecord {
568    quota: OriginQuota,
569    introducer: Principal,
570}
571
572#[derive(Debug)]
573pub(super) struct OriginQuotaReservation {
574    key: OriginQuotaKey,
575    introducer: Principal,
576    previous: Option<OriginQuotaRecord>,
577    evicted: Option<(OriginQuotaKey, OriginQuotaRecord)>,
578}
579
580impl OriginQuotaReservation {
581    pub(super) fn rollback(self, table: &mut OriginQuotaTable) {
582        match self.previous {
583            Some(previous) => {
584                table.records.insert(self.key, previous);
585            }
586            None => {
587                table.records.remove(&self.key);
588                table
589                    .lane_accounting_mut(self.key.lane)
590                    .release(self.introducer, 1);
591            }
592        }
593        if let Some((victim_key, victim_record)) = self.evicted {
594            table
595                .lane_accounting_mut(victim_key.lane)
596                .hold(victim_record.introducer, 1);
597            table.records.insert(victim_key, victim_record);
598        }
599    }
600}
601
602pub(super) struct OriginQuotaTable {
603    config: OriginQuotaConfig,
604    records: BTreeMap<OriginQuotaKey, OriginQuotaRecord>,
605    accounting: [SlotAccounting; MessageCategory::COUNT],
606}
607
608impl OriginQuotaTable {
609    pub(super) fn new(config: OriginQuotaConfig) -> Self {
610        let accounting = [
611            MessageCategory::DhtControl,
612            MessageCategory::Storage,
613            MessageCategory::E2e,
614            MessageCategory::Application,
615        ]
616        .map(|lane| SlotAccounting::new(shares_for_capacity(config.lane(lane).max_records)));
617        Self {
618            config,
619            records: BTreeMap::new(),
620            accounting,
621        }
622    }
623
624    fn lane_accounting(&self, lane: MessageCategory) -> &SlotAccounting {
625        let [dht_control, storage, e2e, application] = &self.accounting;
626        match lane {
627            MessageCategory::DhtControl => dht_control,
628            MessageCategory::Storage => storage,
629            MessageCategory::E2e => e2e,
630            MessageCategory::Application => application,
631        }
632    }
633
634    fn lane_accounting_mut(&mut self, lane: MessageCategory) -> &mut SlotAccounting {
635        let [dht_control, storage, e2e, application] = &mut self.accounting;
636        match lane {
637            MessageCategory::DhtControl => dht_control,
638            MessageCategory::Storage => storage,
639            MessageCategory::E2e => e2e,
640            MessageCategory::Application => application,
641        }
642    }
643
644    pub(super) fn reserve(
645        &mut self,
646        key: OriginQuotaKey,
647        introducer: Principal,
648        message_limit: MessageLimit,
649        byte_cost: usize,
650        now: OriginQuotaInstant,
651    ) -> Result<OriginQuotaReservation, OriginQuotaAdmissionError> {
652        let lane_config = self.config.lane(key.lane);
653        match self.records.get(&key).copied() {
654            Some(previous) => {
655                let (next_quota, origin_verdict) = previous
656                    .quota
657                    .admit(lane_config, message_limit, byte_cost, now)
658                    .map_err(OriginQuotaAdmissionError::Arithmetic)?;
659                self.records.insert(key, OriginQuotaRecord {
660                    quota: next_quota,
661                    introducer: previous.introducer,
662                });
663                origin_verdict.rejection().map_or_else(
664                    || {
665                        Ok(OriginQuotaReservation {
666                            key,
667                            introducer: previous.introducer,
668                            previous: Some(previous),
669                            evicted: None,
670                        })
671                    },
672                    |rejection| Err(OriginQuotaAdmissionError::Verdict(rejection)),
673                )
674            }
675            None => {
676                let (next_quota, origin_verdict) = OriginQuota::full(lane_config, now)
677                    .admit(lane_config, message_limit, byte_cost, now)
678                    .map_err(OriginQuotaAdmissionError::Arithmetic)?;
679                origin_verdict.rejection().map_or(Ok(()), |rejection| {
680                    Err(OriginQuotaAdmissionError::Verdict(rejection))
681                })?;
682                let evicted = self.allocate_record(key.lane, introducer, lane_config, now)?;
683                self.records.insert(key, OriginQuotaRecord {
684                    quota: next_quota,
685                    introducer,
686                });
687                Ok(OriginQuotaReservation {
688                    key,
689                    introducer,
690                    previous: None,
691                    evicted,
692                })
693            }
694        }
695    }
696
697    fn allocate_record(
698        &mut self,
699        lane: MessageCategory,
700        introducer: Principal,
701        config: OriginQuotaLaneConfig,
702        now: OriginQuotaInstant,
703    ) -> Result<Option<(OriginQuotaKey, OriginQuotaRecord)>, OriginQuotaAdmissionError> {
704        let floor = shares_for_capacity(config.max_records).floor;
705        let held = self.lane_accounting(lane).held(introducer);
706        let prefers_own_floor_recycle =
707            matches!(introducer, Principal::Slot(_) | Principal::Unbound) && held >= floor;
708
709        if let Some(evicted) =
710            self.evict_own_victim_if(lane, introducer, config, now, prefers_own_floor_recycle)?
711        {
712            Ok(Some(evicted))
713        } else if self.admit_into_free_capacity(lane, introducer, config) {
714            Ok(None)
715        } else if let Some(evicted) =
716            self.evict_own_victim_if(lane, introducer, config, now, held > 0)?
717        {
718            Ok(Some(evicted))
719        } else {
720            self.evict_pool_victim_for(lane, introducer, config, now)?
721                .map(Some)
722                .ok_or(OriginQuotaAdmissionError::Verdict(
723                    OriginQuotaRejection::Capacity {
724                        capacity: config.max_records,
725                    },
726                ))
727        }
728    }
729
730    fn evict_own_victim_if(
731        &mut self,
732        lane: MessageCategory,
733        introducer: Principal,
734        config: OriginQuotaLaneConfig,
735        now: OriginQuotaInstant,
736        eligible: bool,
737    ) -> Result<Option<(OriginQuotaKey, OriginQuotaRecord)>, OriginQuotaAdmissionError> {
738        eligible
739            .then(|| self.safe_victim(lane, config, now, |record| record.introducer == introducer))
740            .transpose()
741            .map(|victim| {
742                victim
743                    .flatten()
744                    .and_then(|victim_key| {
745                        self.records
746                            .remove(&victim_key)
747                            .map(|record| (victim_key, record))
748                    })
749                    .inspect(|(_, victim_record)| {
750                        self.lane_accounting_mut(lane)
751                            .release(victim_record.introducer, 1);
752                        self.lane_accounting_mut(lane).hold(introducer, 1);
753                    })
754            })
755    }
756
757    fn admit_into_free_capacity(
758        &mut self,
759        lane: MessageCategory,
760        introducer: Principal,
761        config: OriginQuotaLaneConfig,
762    ) -> bool {
763        let lane_records = self
764            .records
765            .keys()
766            .filter(|candidate| candidate.lane == lane)
767            .count();
768        (lane_records < config.max_records && self.lane_accounting(lane).admit(introducer).is_ok())
769            .then(|| self.lane_accounting_mut(lane).hold(introducer, 1))
770            .is_some()
771    }
772
773    fn evict_pool_victim_for(
774        &mut self,
775        lane: MessageCategory,
776        introducer: Principal,
777        config: OriginQuotaLaneConfig,
778        now: OriginQuotaInstant,
779    ) -> Result<Option<(OriginQuotaKey, OriginQuotaRecord)>, OriginQuotaAdmissionError> {
780        let accounting = self.lane_accounting(lane);
781        let pool_victim = self.safe_victim(lane, config, now, |record| {
782            accounting.pool_items(record.introducer) > 0
783        })?;
784        Ok(pool_victim
785            .and_then(|victim_key| {
786                self.records
787                    .remove(&victim_key)
788                    .map(|record| (victim_key, record))
789            })
790            .and_then(|(victim_key, victim_record)| {
791                self.lane_accounting_mut(lane)
792                    .release(victim_record.introducer, 1);
793                match self.lane_accounting(lane).admit(introducer).is_ok() {
794                    true => {
795                        self.lane_accounting_mut(lane).hold(introducer, 1);
796                        Some((victim_key, victim_record))
797                    }
798                    false => {
799                        self.lane_accounting_mut(lane)
800                            .hold(victim_record.introducer, 1);
801                        self.records.insert(victim_key, victim_record);
802                        None
803                    }
804                }
805            }))
806    }
807
808    fn safe_victim(
809        &self,
810        lane: MessageCategory,
811        config: OriginQuotaLaneConfig,
812        now: OriginQuotaInstant,
813        eligible: impl Fn(&OriginQuotaRecord) -> bool,
814    ) -> Result<Option<OriginQuotaKey>, OriginQuotaAdmissionError> {
815        self.records
816            .iter()
817            .filter(|(key, record)| key.lane == lane && eligible(record))
818            .try_fold(None, |victim, (key, record)| {
819                record
820                    .quota
821                    .fully_replenished_at(config, now)
822                    .map_err(OriginQuotaAdmissionError::Arithmetic)
823                    .map(|replenished| {
824                        replenished
825                            .then_some((record.quota.last_refill, *key))
826                            .filter(|&candidate| victim.is_none_or(|current| candidate < current))
827                            .or(victim)
828                    })
829            })
830            .map(|victim| victim.map(|(_, key)| key))
831    }
832
833    #[cfg(test)]
834    pub(super) fn len(&self) -> usize {
835        self.records.len()
836    }
837
838    #[cfg(test)]
839    pub(super) fn held(&self, lane: MessageCategory, principal: Principal) -> usize {
840        self.lane_accounting(lane).held(principal)
841    }
842
843    /// The whole `(message, byte)` tokens `key`'s record held after its last admission.
844    #[cfg(all(test, feature = "dummy", not(target_family = "wasm")))]
845    pub(super) fn whole_tokens(&self, key: OriginQuotaKey) -> Option<(u128, u128)> {
846        self.records.get(&key).map(|record| {
847            (
848                record.quota.whole_message_tokens(),
849                record.quota.whole_byte_tokens(),
850            )
851        })
852    }
853
854    #[cfg(test)]
855    pub(super) fn get(&self, key: OriginQuotaKey) -> Option<OriginQuota> {
856        self.records.get(&key).map(|record| record.quota)
857    }
858}
859
860/// Aggregate quota drop counters for one logical lane.
861#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
862pub struct OriginQuotaLaneCounters {
863    /// Drops caused by message-token exhaustion.
864    pub message_rate_exhausted: u64,
865    /// Drops caused by byte-token exhaustion.
866    pub byte_rate_exhausted: u64,
867    /// Drops caused by the bounded table having no safe victim.
868    pub capacity_exhausted: u64,
869    /// Drops caused by arithmetic or monotonic-clock failure.
870    pub arithmetic_failure: u64,
871}
872
873/// Aggregate quota drop counters partitioned only by bounded logical lane.
874#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
875pub struct OriginQuotaCounters {
876    lanes: [OriginQuotaLaneCounters; 4],
877}
878
879impl OriginQuotaCounters {
880    /// Return aggregate drop counters for `lane`.
881    pub const fn lane(self, lane: MessageCategory) -> OriginQuotaLaneCounters {
882        let [dht_control, storage, e2e, application] = self.lanes;
883        match lane {
884            MessageCategory::DhtControl => dht_control,
885            MessageCategory::Storage => storage,
886            MessageCategory::E2e => e2e,
887            MessageCategory::Application => application,
888        }
889    }
890}
891
892#[derive(Default)]
893struct OriginQuotaLaneCounterState {
894    message_rate_exhausted: AtomicU64,
895    byte_rate_exhausted: AtomicU64,
896    capacity_exhausted: AtomicU64,
897    arithmetic_failure: AtomicU64,
898}
899
900impl OriginQuotaLaneCounterState {
901    fn snapshot(&self) -> OriginQuotaLaneCounters {
902        OriginQuotaLaneCounters {
903            message_rate_exhausted: self.message_rate_exhausted.load(Ordering::Relaxed),
904            byte_rate_exhausted: self.byte_rate_exhausted.load(Ordering::Relaxed),
905            capacity_exhausted: self.capacity_exhausted.load(Ordering::Relaxed),
906            arithmetic_failure: self.arithmetic_failure.load(Ordering::Relaxed),
907        }
908    }
909}
910
911pub(super) struct OriginQuotaCounterState {
912    lanes: [OriginQuotaLaneCounterState; 4],
913}
914
915impl Default for OriginQuotaCounterState {
916    fn default() -> Self {
917        Self {
918            lanes: std::array::from_fn(|_| OriginQuotaLaneCounterState::default()),
919        }
920    }
921}
922
923impl OriginQuotaCounterState {
924    pub(super) fn snapshot(&self) -> OriginQuotaCounters {
925        OriginQuotaCounters {
926            lanes: self
927                .lanes
928                .each_ref()
929                .map(OriginQuotaLaneCounterState::snapshot),
930        }
931    }
932
933    pub(super) fn record(&self, lane: MessageCategory, error: &OriginQuotaAdmissionError) {
934        let [dht_control, storage, e2e, application] = &self.lanes;
935        let counters = match lane {
936            MessageCategory::DhtControl => dht_control,
937            MessageCategory::Storage => storage,
938            MessageCategory::E2e => e2e,
939            MessageCategory::Application => application,
940        };
941        match error {
942            OriginQuotaAdmissionError::Verdict(OriginQuotaRejection::MessageRate) => {
943                counters
944                    .message_rate_exhausted
945                    .fetch_add(1, Ordering::Relaxed);
946            }
947            OriginQuotaAdmissionError::Verdict(OriginQuotaRejection::ByteRate) => {
948                counters.byte_rate_exhausted.fetch_add(1, Ordering::Relaxed);
949            }
950            OriginQuotaAdmissionError::Verdict(OriginQuotaRejection::Capacity { .. }) => {
951                counters.capacity_exhausted.fetch_add(1, Ordering::Relaxed);
952            }
953            OriginQuotaAdmissionError::Arithmetic(_) => {
954                counters.arithmetic_failure.fetch_add(1, Ordering::Relaxed);
955            }
956        }
957    }
958}
959
960pub(super) fn quota_admission_error(
961    key: OriginQuotaKey,
962    byte_cost: usize,
963    error: OriginQuotaAdmissionError,
964) -> crate::error::Error {
965    match error {
966        OriginQuotaAdmissionError::Verdict(OriginQuotaRejection::MessageRate) => {
967            OriginQuotaError::MessageRateExhausted { key }.into()
968        }
969        OriginQuotaAdmissionError::Verdict(OriginQuotaRejection::ByteRate) => {
970            OriginQuotaError::ByteRateExhausted {
971                key,
972                requested_bytes: byte_cost,
973            }
974            .into()
975        }
976        OriginQuotaAdmissionError::Verdict(OriginQuotaRejection::Capacity { capacity }) => {
977            OriginQuotaError::TableCapacityExhausted {
978                lane: key.lane,
979                capacity,
980            }
981            .into()
982        }
983        OriginQuotaAdmissionError::Arithmetic(source) => {
984            OriginQuotaError::Arithmetic { key, source }.into()
985        }
986    }
987}
988
989#[cfg(test)]
990mod test_quota;