Skip to main content

greentic_flow/cache/
engine_profile.rs

1use sha2::{Digest, Sha256};
2use wasmtime::Engine;
3
4#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5pub enum CpuPolicy {
6    Native,
7    Baseline,
8}
9
10impl CpuPolicy {
11    pub fn as_str(&self) -> &'static str {
12        match self {
13            CpuPolicy::Native => "native",
14            CpuPolicy::Baseline => "baseline",
15        }
16    }
17}
18
19#[derive(Clone, Debug, PartialEq, Eq)]
20pub struct EngineProfile {
21    pub wasmtime_version: String,
22    pub target_triple: String,
23    pub cpu_policy: CpuPolicy,
24    pub config_fingerprint: String,
25    pub engine_profile_id: String,
26}
27
28impl EngineProfile {
29    pub fn from_engine(
30        _engine: &Engine,
31        cpu_policy: CpuPolicy,
32        config_fingerprint: String,
33    ) -> Self {
34        let wasmtime_version = wasmtime_environ::VERSION.to_string();
35        let target_triple = format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS);
36        let engine_profile_id = compute_engine_profile_id(
37            &wasmtime_version,
38            &target_triple,
39            cpu_policy,
40            &config_fingerprint,
41        );
42        Self {
43            wasmtime_version,
44            target_triple,
45            cpu_policy,
46            config_fingerprint,
47            engine_profile_id,
48        }
49    }
50
51    pub fn id(&self) -> &str {
52        &self.engine_profile_id
53    }
54}
55
56fn compute_engine_profile_id(
57    wasmtime_version: &str,
58    target_triple: &str,
59    cpu_policy: CpuPolicy,
60    config_fingerprint: &str,
61) -> String {
62    let mut hasher = Sha256::new();
63    hasher.update(wasmtime_version.as_bytes());
64    hasher.update(target_triple.as_bytes());
65    hasher.update(cpu_policy.as_str().as_bytes());
66    hasher.update(config_fingerprint.as_bytes());
67    let digest = hasher.finalize();
68    format!(
69        "sha256:{}",
70        digest
71            .iter()
72            .map(|byte| format!("{byte:02x}"))
73            .collect::<String>()
74    )
75}