capsule_core/wasm/
execution_policy.rs1use serde::{Deserialize, Serialize};
2use std::time::Duration;
3
4#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
5#[serde(rename_all = "snake_case")]
6pub enum Compute {
7 Low,
8 Medium,
9 High,
10 Custom(u64),
11}
12
13impl Compute {
14 pub fn as_fuel(&self) -> u64 {
15 match self {
16 Compute::Low => 100_000_000,
17 Compute::Medium => 2_000_000_000,
18 Compute::High => 50_000_000_000,
19 Compute::Custom(fuel) => *fuel,
20 }
21 }
22
23 pub fn to_u64(&self) -> u64 {
24 self.as_fuel()
25 }
26}
27
28#[derive(Clone, Serialize, Deserialize)]
29pub struct ExecutionPolicy {
30 pub name: String,
31 pub compute: Compute,
32 pub ram: Option<u64>,
33 pub timeout: Option<String>,
34 pub max_retries: u64,
35}
36
37impl Default for ExecutionPolicy {
38 fn default() -> Self {
39 Self {
40 name: "default".to_string(),
41 compute: Compute::Medium,
42 ram: None,
43 timeout: None,
44 max_retries: 0,
45 }
46 }
47}
48
49impl ExecutionPolicy {
50 pub fn new() -> Self {
51 Self::default()
52 }
53
54 pub fn name(mut self, name: Option<String>) -> Self {
55 if let Some(n) = name {
56 self.name = n;
57 }
58 self
59 }
60
61 pub fn compute(mut self, compute: Option<Compute>) -> Self {
62 if let Some(c) = compute {
63 self.compute = c;
64 }
65 self
66 }
67
68 pub fn ram(mut self, ram: Option<u64>) -> Self {
69 self.ram = ram;
70 self
71 }
72
73 pub fn timeout(mut self, timeout: Option<String>) -> Self {
74 self.timeout = timeout;
75 self
76 }
77
78 pub fn max_retries(mut self, max_retries: Option<u64>) -> Self {
79 if let Some(m) = max_retries {
80 self.max_retries = m;
81 }
82 self
83 }
84
85 pub fn timeout_duration(&self) -> Option<Duration> {
86 self.timeout
87 .as_ref()
88 .and_then(|s| humantime::parse_duration(s).ok())
89 }
90}
91
92#[cfg(test)]
93mod tests {
94 use super::*;
95
96 #[test]
97 fn test_execution_policy() {
98 let policy = ExecutionPolicy::new()
99 .name(Some("test".to_string()))
100 .compute(None)
101 .ram(Some(128))
102 .timeout(Some("60s".to_string()))
103 .max_retries(Some(3));
104
105 assert_eq!(policy.name, "test");
106 assert_eq!(policy.compute, Compute::Medium);
107 assert_eq!(policy.ram, Some(128));
108 assert_eq!(policy.timeout, Some("60s".to_string()));
109 assert_eq!(policy.max_retries, 3);
110 }
111}