qualia_core_db/bundle/stream/runtime/
plan.rs1use crate::net::peer::runtime::{ResourceBudget, WorkClass};
3use crate::net::qdnf::{
4 errors::QdnfError,
5 types::{Generation, OperationId},
6};
7
8pub const MAX_PLAN_ROWS: usize = 64;
9#[derive(Clone, Copy, Debug)]
10pub struct TransferRequirements {
11 pub network: ResourceBudget,
12 pub proof: ResourceBudget,
13 pub storage: ResourceBudget,
14 pub consumer: ResourceBudget,
15 pub scratch: ResourceBudget,
17}
18impl TransferRequirements {
19 pub fn aggregate(self) -> Result<ResourceBudget, QdnfError> {
20 if self.network.bytes == 0
21 || self.proof.bytes == 0
22 || self.storage.bytes == 0
23 || self.consumer.bytes == 0
24 {
25 return Err(QdnfError::Malformed);
26 }
27 let mut total = ResourceBudget::ZERO;
28 for part in [
29 self.network,
30 self.proof,
31 self.storage,
32 self.consumer,
33 self.scratch,
34 ] {
35 total = total.saturating_add(part)?;
36 }
37 Ok(total)
38 }
39}
40#[derive(Clone, Copy, Debug)]
41pub struct TransferSpec {
42 pub operation: OperationId,
43 pub principal: u64,
44 pub policy_generation: Generation,
45 pub deadline: u64,
46 pub class: WorkClass,
47 pub cost: u16,
48 pub credit_bytes: u32,
49 pub requirements: TransferRequirements,
50 pub verified_peer: bool,
51}
52impl TransferSpec {
53 pub(super) fn validate(&self) -> Result<ResourceBudget, QdnfError> {
54 if self.operation == OperationId::ZERO
55 || self.principal == 0
56 || self.policy_generation == Generation::ZERO
57 || self.deadline == 0
58 || self.cost == 0
59 || self.credit_bytes == 0
60 {
61 return Err(QdnfError::Malformed);
62 }
63 if self.class == WorkClass::Control {
64 return Err(QdnfError::Unauthorized);
65 }
66 let budget = self.requirements.aggregate()?;
67 if u64::from(self.credit_bytes) > self.requirements.network.bytes {
68 return Err(QdnfError::Range);
69 }
70 Ok(budget)
71 }
72}
73#[derive(Debug)]
74pub struct ColdPlan<'a> {
75 rows: &'a [TransferSpec],
76}
77impl<'a> ColdPlan<'a> {
78 pub fn compile(rows: &'a [TransferSpec]) -> Result<Self, QdnfError> {
79 if rows.len() > MAX_PLAN_ROWS {
80 return Err(QdnfError::Capacity);
81 }
82 for (i, row) in rows.iter().enumerate() {
83 row.validate()?;
84 if rows[..i].iter().any(|r| r.operation == row.operation) {
85 return Err(QdnfError::Conflict);
86 }
87 }
88 Ok(Self { rows })
89 }
90 pub const fn len(&self) -> usize {
91 self.rows.len()
92 }
93 pub const fn is_empty(&self) -> bool {
94 self.rows.is_empty()
95 }
96 pub(super) fn row(&self, index: usize) -> Result<TransferSpec, QdnfError> {
97 self.rows.get(index).copied().ok_or(QdnfError::Range)
98 }
99}