1use 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;
31pub const DEFAULT_ORIGIN_QUOTA_MESSAGES_PER_SECOND: u64 = 64;
33pub const DEFAULT_ORIGIN_QUOTA_MESSAGE_BURST: u64 = 128;
35pub const DEFAULT_ORIGIN_QUOTA_BYTES_PER_SECOND: u64 = 4 * 1024 * 1024;
37pub const DEFAULT_ORIGIN_QUOTA_BYTE_BURST: u64 = 64 * 1024 * 1024;
42pub const DELEGATED_MIN_CHARGE: usize = 16 * 1024;
53pub const DEFAULT_ORIGIN_QUOTA_RECORDS_PER_LANE: usize = 4096;
55
56pub(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#[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 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 pub const fn message_rate_per_second(self) -> u64 {
157 self.message_rate_per_second
158 }
159
160 pub const fn message_burst(self) -> u64 {
162 self.message_burst
163 }
164
165 pub const fn byte_rate_per_second(self) -> u64 {
167 self.byte_rate_per_second
168 }
169
170 pub const fn byte_burst(self) -> u64 {
172 self.byte_burst
173 }
174
175 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#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
230pub struct OriginQuotaConfig {
231 pub dht_control: OriginQuotaLaneConfig,
233 pub storage: OriginQuotaLaneConfig,
235 pub e2e: OriginQuotaLaneConfig,
237 pub application: OriginQuotaLaneConfig,
239}
240
241impl OriginQuotaConfig {
242 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 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#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
277pub enum OriginQuotaConfigError {
278 #[error("origin quota message rate must be non-zero")]
280 ZeroMessageRate,
281 #[error("origin quota message burst must be non-zero")]
283 ZeroMessageBurst,
284 #[error("origin quota byte rate must be non-zero")]
286 ZeroByteRate,
287 #[error("origin quota byte burst must be non-zero")]
289 ZeroByteBurst,
290 #[error("origin quota record capacity must be non-zero")]
292 ZeroRecordCapacity,
293}
294
295#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
297pub struct OriginQuotaInstant(u128);
298
299impl OriginQuotaInstant {
300 pub const ZERO: Self = Self(0);
302
303 pub const fn from_nanos(nanos: u128) -> Self {
305 Self(nanos)
306 }
307}
308
309#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
311pub struct OriginQuotaKey {
312 pub network_id: u32,
314 pub origin_account: Did,
316 pub destination: Did,
318 pub lane: MessageCategory,
320}
321
322impl OriginQuotaKey {
323 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
374pub struct OriginQuota {
375 messages: TokenBucket,
376 bytes: TokenBucket,
377 last_refill: OriginQuotaInstant,
378}
379
380impl OriginQuota {
381 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 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
466const 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
474fn 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
485pub enum OriginQuotaVerdict {
486 Admitted,
488 MessageRateExhausted,
490 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#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
506pub enum OriginQuotaArithmeticError {
507 #[error("origin quota monotonic time regressed")]
509 MonotonicTimeRegressed,
510 #[error("origin quota byte cost overflowed fixed-point arithmetic")]
512 ByteCostOverflow,
513}
514
515#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
517pub enum OriginQuotaError {
518 #[error("Origin quota message rate exhausted for {key:?}")]
520 MessageRateExhausted {
521 key: OriginQuotaKey,
523 },
524 #[error(
526 "Origin quota byte rate exhausted for {key:?} while admitting {requested_bytes} bytes"
527 )]
528 ByteRateExhausted {
529 key: OriginQuotaKey,
531 requested_bytes: usize,
533 },
534 #[error("Origin quota table for {lane:?} exhausted its {capacity} records")]
536 TableCapacityExhausted {
537 lane: MessageCategory,
539 capacity: usize,
541 },
542 #[error("Origin quota arithmetic failed for {key:?}: {source}")]
544 Arithmetic {
545 key: OriginQuotaKey,
547 #[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 #[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#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
862pub struct OriginQuotaLaneCounters {
863 pub message_rate_exhausted: u64,
865 pub byte_rate_exhausted: u64,
867 pub capacity_exhausted: u64,
869 pub arithmetic_failure: u64,
871}
872
873#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
875pub struct OriginQuotaCounters {
876 lanes: [OriginQuotaLaneCounters; 4],
877}
878
879impl OriginQuotaCounters {
880 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;