1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
use std::path::{Path, PathBuf};

use tempfile::NamedTempFile;
use wasmer::{Engine, Module};

use crate::runtime::module_cache::{CacheError, ModuleCache, ModuleHash};

/// A cache that saves modules to a folder on the host filesystem using
/// [`Module::serialize()`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileSystemCache {
    cache_dir: PathBuf,
}

impl FileSystemCache {
    pub fn new(cache_dir: impl Into<PathBuf>) -> Self {
        FileSystemCache {
            cache_dir: cache_dir.into(),
        }
    }

    pub fn cache_dir(&self) -> &Path {
        &self.cache_dir
    }

    fn path(&self, key: ModuleHash, deterministic_id: &str) -> PathBuf {
        let artifact_version = wasmer_types::MetadataHeader::CURRENT_VERSION;
        self.cache_dir
            .join(format!("{deterministic_id}-v{artifact_version}"))
            .join(key.to_string())
            .with_extension("bin")
    }
}

#[async_trait::async_trait]
impl ModuleCache for FileSystemCache {
    #[tracing::instrument(level = "debug", skip_all, fields(%key))]
    async fn load(&self, key: ModuleHash, engine: &Engine) -> Result<Module, CacheError> {
        let path = self.path(key, engine.deterministic_id());

        // FIXME: This will all block the thread at the moment. Ideally,
        // deserializing and uncompressing would happen on a thread pool in the
        // background.
        // https://github.com/wasmerio/wasmer/issues/3851

        let uncompressed = read_compressed(&path)?;

        let res = unsafe { Module::deserialize(&engine, uncompressed) };
        match res {
            Ok(m) => {
                tracing::debug!("Cache hit!");
                Ok(m)
            }
            Err(e) => {
                tracing::debug!(
                    %key,
                    path=%path.display(),
                    error=&e as &dyn std::error::Error,
                    "Deleting the cache file because the artifact couldn't be deserialized",
                );

                if let Err(e) = std::fs::remove_file(&path) {
                    tracing::warn!(
                        %key,
                        path=%path.display(),
                        error=&e as &dyn std::error::Error,
                        "Unable to remove the corrupted cache file",
                    );
                }

                Err(CacheError::Deserialize(e))
            }
        }
    }

    #[tracing::instrument(level = "debug", skip_all, fields(%key))]
    async fn save(
        &self,
        key: ModuleHash,
        engine: &Engine,
        module: &Module,
    ) -> Result<(), CacheError> {
        let path = self.path(key, engine.deterministic_id());

        // FIXME: This will all block the thread at the moment. Ideally,
        // serializing and compressing would happen on a thread pool in the
        // background.
        // https://github.com/wasmerio/wasmer/issues/3851

        let parent = path
            .parent()
            .expect("Unreachable - always created by joining onto cache_dir");

        if let Err(e) = std::fs::create_dir_all(parent) {
            tracing::warn!(
                dir=%parent.display(),
                error=&e as &dyn std::error::Error,
                "Unable to create the cache directory",
            );
        }

        // Note: We save to a temporary file and persist() it at the end so
        // concurrent readers won't see a partially written module.
        let mut f = NamedTempFile::new_in(parent).map_err(CacheError::other)?;
        let serialized = module.serialize()?;

        if let Err(e) = save_compressed(&mut f, &serialized) {
            return Err(CacheError::FileWrite { path, error: e });
        }

        f.persist(&path).map_err(CacheError::other)?;

        Ok(())
    }
}

fn save_compressed(writer: impl std::io::Write, data: &[u8]) -> Result<(), std::io::Error> {
    let mut encoder = weezl::encode::Encoder::new(weezl::BitOrder::Msb, 8);
    encoder
        .into_stream(writer)
        .encode_all(std::io::Cursor::new(data))
        .status?;

    Ok(())
}

fn read_compressed(path: &Path) -> Result<Vec<u8>, CacheError> {
    let compressed = match std::fs::read(path) {
        Ok(bytes) => bytes,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return Err(CacheError::NotFound);
        }
        Err(error) => {
            return Err(CacheError::FileRead {
                path: path.to_path_buf(),
                error,
            });
        }
    };

    let mut uncompressed = Vec::new();
    let mut decoder = weezl::decode::Decoder::new(weezl::BitOrder::Msb, 8);
    decoder
        .into_vec(&mut uncompressed)
        .decode_all(&compressed)
        .status
        .map_err(CacheError::other)?;

    Ok(uncompressed)
}

#[cfg(test)]
mod tests {
    use std::fs::File;

    use tempfile::TempDir;

    use super::*;

    const ADD_WAT: &[u8] = br#"(
        module
            (func
                (export "add")
                (param $x i64)
                (param $y i64)
                (result i64)
                (i64.add (local.get $x) (local.get $y)))
        )"#;

    #[tokio::test]
    async fn save_to_disk() {
        let temp = TempDir::new().unwrap();
        let engine = Engine::default();
        let module = Module::new(&engine, ADD_WAT).unwrap();
        let cache = FileSystemCache::new(temp.path());
        let key = ModuleHash::from_bytes([0; 32]);
        let expected_path = cache.path(key, engine.deterministic_id());

        cache.save(key, &engine, &module).await.unwrap();

        assert!(expected_path.exists());
    }

    #[tokio::test]
    async fn create_cache_dir_automatically() {
        let temp = TempDir::new().unwrap();
        let engine = Engine::default();
        let module = Module::new(&engine, ADD_WAT).unwrap();
        let cache_dir = temp.path().join("this").join("doesn't").join("exist");
        assert!(!cache_dir.exists());
        let cache = FileSystemCache::new(&cache_dir);
        let key = ModuleHash::from_bytes([0; 32]);

        cache.save(key, &engine, &module).await.unwrap();

        assert!(cache_dir.is_dir());
    }

    #[tokio::test]
    async fn missing_file() {
        let temp = TempDir::new().unwrap();
        let engine = Engine::default();
        let key = ModuleHash::from_bytes([0; 32]);
        let cache = FileSystemCache::new(temp.path());

        let err = cache.load(key, &engine).await.unwrap_err();

        assert!(matches!(err, CacheError::NotFound));
    }

    #[tokio::test]
    async fn load_from_disk() {
        let temp = TempDir::new().unwrap();
        let engine = Engine::default();
        let module = Module::new(&engine, ADD_WAT).unwrap();
        let key = ModuleHash::from_bytes([0; 32]);
        let cache = FileSystemCache::new(temp.path());
        let expected_path = cache.path(key, engine.deterministic_id());
        std::fs::create_dir_all(expected_path.parent().unwrap()).unwrap();
        let serialized = module.serialize().unwrap();
        save_compressed(File::create(&expected_path).unwrap(), &serialized).unwrap();

        let module = cache.load(key, &engine).await.unwrap();

        let exports: Vec<_> = module
            .exports()
            .map(|export| export.name().to_string())
            .collect();
        assert_eq!(exports, ["add"]);
    }
}