-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathlib.rs
More file actions
239 lines (210 loc) · 6.92 KB
/
lib.rs
File metadata and controls
239 lines (210 loc) · 6.92 KB
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
use anyhow::Result;
use std::{
io::{Read, Write},
path::PathBuf,
process::Command,
sync::LazyLock,
};
/// Result from running a Shopify Function
#[derive(Debug)]
pub struct RunResult {
/// The JSON output from the function
pub output: serde_json::Value,
/// The logs from the function
pub logs: String,
/// The number of instructions executed
pub instructions: u64,
/// The memory usage in bytes
pub memory_usage: u64,
}
const FUNCTION_RUNNER_VERSION: &str = "9.1.0";
const TRAMPOLINE_VERSION: &str = "2.0.0";
fn workspace_root() -> std::path::PathBuf {
let manifest_dir = env!("CARGO_MANIFEST_DIR");
std::path::PathBuf::from(manifest_dir).join("..")
}
/// Builds the example to a `.wasm` file
fn build_example(name: &str) -> Result<()> {
let status = Command::new("cargo")
.args([
"build",
"--release",
"--target",
"wasm32-unknown-unknown",
"-p",
name,
])
.status()?;
if !status.success() {
anyhow::bail!(status);
}
Ok(())
}
static FUNCTION_RUNNER_PATH: LazyLock<anyhow::Result<PathBuf>> = LazyLock::new(|| {
let path = workspace_root().join(format!("tmp/function-runner-{FUNCTION_RUNNER_VERSION}"));
if !path.exists() {
std::fs::create_dir_all(workspace_root().join("tmp"))?;
download_function_runner(&path)?;
}
Ok(path)
});
static TRAMPOLINE_PATH: LazyLock<anyhow::Result<PathBuf>> = LazyLock::new(|| {
let path = workspace_root().join(format!("tmp/trampoline-{TRAMPOLINE_VERSION}"));
if !path.exists() {
std::fs::create_dir_all(workspace_root().join("tmp"))?;
download_trampoline(&path)?;
}
Ok(path)
});
fn download_function_runner(destination: &PathBuf) -> Result<()> {
download_from_github(
|target_arch, target_os| {
format!(
"https://github.com/Shopify/function-runner/releases/download/v{FUNCTION_RUNNER_VERSION}/function-runner-{target_arch}-{target_os}-v{FUNCTION_RUNNER_VERSION}.gz",
)
},
destination,
)
}
fn download_trampoline(destination: &PathBuf) -> Result<()> {
download_from_github(
|target_arch, target_os| {
format!(
"https://github.com/Shopify/shopify-function-wasm-api/releases/download/shopify_function_trampoline/v{TRAMPOLINE_VERSION}/shopify-function-trampoline-{target_arch}-{target_os}-v{TRAMPOLINE_VERSION}.gz",
)
},
destination,
)
}
/// Downloads a file from github and saves it to the given destination
///
/// The url_builder is a function that takes the target_arch and target_os and returns the url
fn download_from_github(
url_builder: impl Fn(&str, &str) -> String,
destination: &PathBuf,
) -> Result<()> {
let target_os = if cfg!(target_os = "macos") {
"macos"
} else if cfg!(target_os = "linux") {
"linux"
} else if cfg!(target_os = "windows") {
"windows"
} else {
anyhow::bail!("Unsupported target OS");
};
let target_arch = if cfg!(target_arch = "x86_64") {
"x86_64"
} else if cfg!(target_arch = "aarch64") {
"arm"
} else {
anyhow::bail!("Unsupported target architecture");
};
let url = url_builder(target_arch, target_os);
let response = reqwest::blocking::get(&url)?;
if !response.status().is_success() {
anyhow::bail!("Failed to download artifact: {}", response.status());
}
let bytes = response.bytes()?;
let mut gz_decoder = flate2::read::GzDecoder::new(bytes.as_ref());
let mut file = std::fs::File::create(destination)?;
std::io::copy(&mut gz_decoder, &mut file)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut perms = file.metadata()?.permissions();
perms.set_mode(0o755);
file.set_permissions(perms)?;
}
Ok(())
}
pub fn prepare_example(name: &str) -> Result<PathBuf> {
build_example(name)?;
let wasm_path = workspace_root()
.join("target/wasm32-unknown-unknown/release")
.join(format!("{name}.wasm"));
let trampolined_path = workspace_root()
.join("target/wasm32-unknown-unknown/release")
.join(format!("{name}-trampolined.wasm"));
let trampoline_path = TRAMPOLINE_PATH
.as_ref()
.map_err(|e| anyhow::anyhow!("Failed to download trampoline: {}", e))?;
let status = Command::new(trampoline_path)
.args([
"-i",
wasm_path
.to_str()
.expect("Failed to convert wasm path to string"),
"-o",
trampolined_path
.to_str()
.expect("Failed to convert wasm path to string"),
])
.status()?;
assert!(status.success());
Ok(trampolined_path)
}
pub fn run_example(path: PathBuf, export: &str, input: serde_json::Value) -> Result<RunResult> {
let function_runner_path = FUNCTION_RUNNER_PATH
.as_ref()
.map_err(|e| anyhow::anyhow!("Failed to download function runner: {}", e))?;
let input_json = serde_json::to_string(&input)?;
let mut child = Command::new(function_runner_path)
.args([
"--json",
"--function",
path.to_str().expect("Failed to convert path to string"),
"--export",
export,
])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.spawn()?;
let mut stdin = child
.stdin
.take()
.ok_or_else(|| anyhow::anyhow!("Failed to open stdin"))?;
std::thread::spawn(move || {
stdin
.write_all(input_json.as_bytes())
.expect("Failed to write to stdin");
});
let status = child.wait()?;
let mut output = child
.stdout
.take()
.ok_or_else(|| anyhow::anyhow!("Failed to open stdout"))?;
let mut output_bytes = Vec::new();
output.read_to_end(&mut output_bytes)?;
let mut output: serde_json::Value = serde_json::from_slice(&output_bytes)?;
let logs = output
.get("logs")
.ok_or_else(|| anyhow::anyhow!("No logs"))?
.as_str()
.ok_or_else(|| anyhow::anyhow!("Logs are not a string"))?
.to_string();
let instructions = output
.get("instructions")
.and_then(|v| v.as_u64())
.ok_or_else(|| anyhow::anyhow!("No instructions count"))?;
let memory_usage = output
.get("memory_usage")
.and_then(|v| v.as_u64())
.ok_or_else(|| anyhow::anyhow!("No memory_usage"))?;
if !status.success() {
anyhow::bail!(
"Function runner returned non-zero exit code: {}, logs: {}",
status,
logs,
);
}
let output_json = output
.get_mut("output")
.ok_or_else(|| anyhow::anyhow!("No output"))?
.take();
Ok(RunResult {
output: output_json,
logs,
instructions,
memory_usage,
})
}