-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.rs
237 lines (192 loc) · 7.53 KB
/
main.rs
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
use anyhow::{anyhow, Context};
use cargo_metadata::camino::Utf8PathBuf;
use cargo_metadata::Message;
use carol::http::api::{BinaryCreated, MachineCreated}; // TODO move to carol_core?
use carol::http::server::Encoding;
use carol_core::{hex, BinaryId};
use carol_host::Executor;
use clap::{Args, Parser, Subcommand};
use std::fmt::Display;
use std::process::{Command, Stdio};
use wit_component::ComponentEncoder;
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
Build(BuildOpts),
Upload(UploadOpts),
Activate(ActivateOpts),
}
#[derive(Args)]
struct BuildOpts {
crate_dir: Option<Utf8PathBuf>,
}
#[derive(Args)]
struct UploadOpts {
carol_url: String,
binary: Utf8PathBuf,
}
#[derive(Args)]
struct ActivateOpts {
carol_url: String,
binary_id: BinaryId,
}
struct Client {
base: String,
http_client: reqwest::blocking::Client,
}
impl Client {
fn new(base: String) -> Self {
Self {
base,
http_client: reqwest::blocking::Client::new(), // blocking::get() does builder().build()?
}
}
fn post(&self, path: &str) -> reqwest::blocking::RequestBuilder {
self.http_client
.post(format!("{}/{}", self.base, path))
.header(
reqwest::header::ACCEPT,
"application/bincode, application/json", // application/json;q=0.9? // TODO randomize whether or not sent for initial development?
)
}
fn decode_response<B>(&self, response: reqwest::blocking::Response) -> anyhow::Result<B>
where
B: for<'de> serde::Deserialize<'de> + bincode::Decode,
{
let response = response.error_for_status()?;
// FIXME error if no content type specified?
let content_type = response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.map(|h| h.to_str().unwrap_or(""))
.unwrap_or("");
let encoding = Encoding::from_content_type(content_type);
let body = response.bytes().context("Reading server response")?;
encoding
.decode_body::<B>(&body)
.context("Decoding response body")
}
fn upload_binary<B: Into<reqwest::blocking::Body>>(
&self,
binary_id: &BinaryId,
binary: B,
) -> anyhow::Result<BinaryCreated> {
let http_response = self
.post("binaries") // TODO idempotent HTTP PUT?
.body(binary)
.send()
.context("Uploading compiled WASM file to {carol_url}")?;
let api_response: BinaryCreated = self
.decode_response(http_response)
.context("Parse response")?;
if api_response.id != *binary_id {
return Err(anyhow!(
"Locally computed binary ID {} doesn't match server reported value {}",
hex::encode(binary_id.as_ref()),
hex::encode(api_response.id.as_ref()),
));
}
Ok(api_response)
}
fn activate(&self, binary_id: &BinaryId) -> anyhow::Result<MachineCreated> {
let http_response = self
.post(&format!("binaries/{}", hex::encode(binary_id.as_ref())))
.send()
.context("Activating {binary_id} on {carol_url}")?;
self.decode_response::<MachineCreated>(http_response)
.context("Parse response")
}
}
fn main() -> anyhow::Result<()> {
let cli = Cli::parse();
let output: Box<dyn Display> = match &cli.command {
Commands::Build(BuildOpts { crate_dir: dir }) => {
let mut cmd = Command::new("cargo");
if let Some(dir) = dir {
cmd.current_dir(dir);
}
cmd.env("RUSTFLAGS", "-C opt-level=z")
.args([
"rustc",
"--message-format=json-render-diagnostics",
"--target",
"wasm32-unknown-unknown",
"--release",
"--crate-type=cdylib",
])
.stdout(Stdio::piped());
let mut proc = cmd.spawn().expect("things to compile");
let reader = std::io::BufReader::new(proc.stdout.take().unwrap());
let messages = cargo_metadata::Message::parse_stream(reader)
.collect::<Result<Vec<_>, _>>()
.context("Reading cargo output")?;
let final_artifact_message = messages
.into_iter()
.rev()
.find_map(|message| match message {
Message::CompilerArtifact(artifact) => Some(artifact),
_ => None,
})
.ok_or(anyhow!(
"No compiler artifact messages in output, could not find wasm output file"
))?;
if final_artifact_message.filenames.len() != 1 {
return Err(anyhow!(
"Expected a single wasm artifact in files, but got {}",
final_artifact_message.filenames.len()
));
}
let final_wasm_artifact = final_artifact_message.filenames[0].clone();
proc.wait().expect("Couldn't get cargo's exit status");
let mut component_target = final_wasm_artifact.clone();
// FIXME horrible jankyness, but it works
component_target.set_extension("");
component_target
.set_file_name(component_target.file_name().unwrap().to_owned() + "-component");
component_target.set_extension("wasm");
let wasm = std::fs::read(&final_wasm_artifact)
.context(format!("Reading compiled WASM file {final_wasm_artifact}"))?;
let encoder = ComponentEncoder::default().validate(true).module(&wasm)?;
let bytes = encoder
.encode()
.context("failed to encode a component from module")?;
std::fs::write(&component_target, bytes)
.context(format!("Writing WASM component {component_target}"))?;
// TODO remove or (after careful consideration) convert to a
// warning before release, as this strongly assumes the client side
// carlo binary and server side carol host exactly agree on the
// definition of Executor::load_binary_from_wasm_file.
_ = Executor::new()
.load_binary_from_wasm_file(&component_target)
.context("Ensuring WASM component {component_target} is loadable")?;
Box::new(component_target)
}
Commands::Upload(UploadOpts { binary, carol_url }) => {
let client = Client::new(carol_url.clone());
// Validate and derive BinaryId
let binary_id = Executor::new()
.load_binary_from_wasm_file(binary)
.context("Loading compiled binary")?
.binary_id();
let file = std::fs::File::open(binary)
.context(format!("Reading compiled WASM file {}", binary))?;
let response_binary_id = client.upload_binary(&binary_id, file)?.id;
Box::new(hex::encode(response_binary_id.as_ref()))
}
Commands::Activate(ActivateOpts {
binary_id,
carol_url,
}) => {
let client = Client::new(carol_url.clone());
let machine_id = client.activate(binary_id)?.id;
Box::new(hex::encode(machine_id.as_ref()))
}
};
println!("{output}");
Ok(())
}