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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
use crate::{error::PrepareError, host::PrepareResultSender};
use always_assert::always;
use async_std::path::{Path, PathBuf};
use polkadot_parachain::primitives::ValidationCodeHash;
use std::{
collections::HashMap,
time::{Duration, SystemTime},
};
pub struct CompiledArtifact(Vec<u8>);
impl CompiledArtifact {
pub fn new(code: Vec<u8>) -> Self {
Self(code)
}
}
impl AsRef<[u8]> for CompiledArtifact {
fn as_ref(&self) -> &[u8] {
self.0.as_slice()
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ArtifactId {
pub(crate) code_hash: ValidationCodeHash,
}
impl ArtifactId {
const PREFIX: &'static str = "wasmtime_";
pub fn new(code_hash: ValidationCodeHash) -> Self {
Self { code_hash }
}
#[cfg(test)]
pub fn from_file_name(file_name: &str) -> Option<Self> {
use polkadot_core_primitives::Hash;
use std::str::FromStr as _;
let file_name = file_name.strip_prefix(Self::PREFIX)?;
let code_hash = Hash::from_str(file_name).ok()?.into();
Some(Self { code_hash })
}
pub fn path(&self, cache_path: &Path) -> PathBuf {
let file_name = format!("{}{:#x}", Self::PREFIX, self.code_hash);
cache_path.join(file_name)
}
}
#[derive(Debug, Clone)]
pub struct ArtifactPathId {
pub(crate) id: ArtifactId,
pub(crate) path: PathBuf,
}
impl ArtifactPathId {
pub(crate) fn new(artifact_id: ArtifactId, cache_path: &Path) -> Self {
Self { path: artifact_id.path(cache_path), id: artifact_id }
}
}
pub enum ArtifactState {
Prepared {
last_time_needed: SystemTime,
},
Preparing { waiting_for_response: Vec<PrepareResultSender> },
FailedToProcess(PrepareError),
}
pub struct Artifacts {
artifacts: HashMap<ArtifactId, ArtifactState>,
}
impl Artifacts {
pub async fn new(cache_path: &Path) -> Self {
let _ = async_std::fs::remove_dir_all(cache_path).await;
let _ = async_std::fs::create_dir_all(cache_path).await;
Self { artifacts: HashMap::new() }
}
#[cfg(test)]
pub(crate) fn empty() -> Self {
Self { artifacts: HashMap::new() }
}
pub fn artifact_state_mut(&mut self, artifact_id: &ArtifactId) -> Option<&mut ArtifactState> {
self.artifacts.get_mut(artifact_id)
}
pub fn insert_preparing(
&mut self,
artifact_id: ArtifactId,
waiting_for_response: Vec<PrepareResultSender>,
) {
always!(self
.artifacts
.insert(artifact_id, ArtifactState::Preparing { waiting_for_response })
.is_none());
}
#[cfg(test)]
pub fn insert_prepared(&mut self, artifact_id: ArtifactId, last_time_needed: SystemTime) {
always!(self
.artifacts
.insert(artifact_id, ArtifactState::Prepared { last_time_needed })
.is_none());
}
pub fn prune(&mut self, artifact_ttl: Duration) -> Vec<ArtifactId> {
let now = SystemTime::now();
let mut to_remove = vec![];
for (k, v) in self.artifacts.iter() {
if let ArtifactState::Prepared { last_time_needed, .. } = *v {
if now
.duration_since(last_time_needed)
.map(|age| age > artifact_ttl)
.unwrap_or(false)
{
to_remove.push(k.clone());
}
}
}
for artifact in &to_remove {
self.artifacts.remove(artifact);
}
to_remove
}
}
#[cfg(test)]
mod tests {
use super::{ArtifactId, Artifacts};
use async_std::path::Path;
use sp_core::H256;
use std::str::FromStr;
#[test]
fn from_file_name() {
assert!(ArtifactId::from_file_name("").is_none());
assert!(ArtifactId::from_file_name("junk").is_none());
assert_eq!(
ArtifactId::from_file_name(
"wasmtime_0x0022800000000000000000000000000000000000000000000000000000000000"
),
Some(ArtifactId::new(
hex_literal::hex![
"0022800000000000000000000000000000000000000000000000000000000000"
]
.into()
)),
);
}
#[test]
fn path() {
let path = Path::new("/test");
let hash =
H256::from_str("1234567890123456789012345678901234567890123456789012345678901234")
.unwrap()
.into();
assert_eq!(
ArtifactId::new(hash).path(path).to_str(),
Some(
"/test/wasmtime_0x1234567890123456789012345678901234567890123456789012345678901234"
),
);
}
#[test]
fn artifacts_removes_cache_on_startup() {
let fake_cache_path = async_std::task::block_on(async move {
crate::worker_common::tmpfile("test-cache").await.unwrap()
});
let fake_artifact_path = {
let mut p = fake_cache_path.clone();
p.push("wasmtime_0x1234567890123456789012345678901234567890123456789012345678901234");
p
};
std::fs::create_dir_all(&fake_cache_path).unwrap();
std::fs::File::create(fake_artifact_path).unwrap();
let p = &fake_cache_path;
async_std::task::block_on(async { Artifacts::new(p).await });
assert_eq!(std::fs::read_dir(&fake_cache_path).unwrap().count(), 0);
std::fs::remove_dir_all(fake_cache_path).unwrap();
}
}