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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
#[cfg(feature = "debugger")]
use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::process::Stdio;
use log::{debug, info, warn};
use simpath::{FileType, FoundType, Simpath};
use tempdir::TempDir;
use url::Url;
use flowcore::model::function_definition::FunctionDefinition;
use crate::compiler::cargo_build;
use crate::errors::*;
pub fn compile_implementation(
target_dir: &Path,
function: &mut FunctionDefinition,
native_only: bool,
optimize: bool,
#[cfg(feature = "debugger")] source_urls: &mut HashSet<(Url, Url)>,
) -> Result<(PathBuf, bool)> {
let mut built = false;
let (source_path, wasm_destination) = get_paths(target_dir, function)?;
#[cfg(feature = "debugger")]
source_urls.insert((
Url::from_file_path(&source_path).map_err(|_| "Could not create Url from file path")?,
Url::from_file_path(&wasm_destination)
.map_err(|_| "Could not create Url from file path")?,
));
let (missing, out_of_date) = out_of_date(&source_path, &wasm_destination)?;
if missing || out_of_date {
if native_only {
if missing {
let message = format!("Implementation at '{}' is missing and you have selected to skip building, so flows relaying on this implementation will not execute correctly.\nYou can build it using 'flowc', using the '-p' option", wasm_destination.display());
warn!("{}", message);
}
if out_of_date {
info!(
"Implementation at '{}' is out of date with source at '{}'",
wasm_destination.display(),
source_path.display()
);
}
} else {
match function.build_type.as_str() {
"rust" => cargo_build::run(&source_path, &wasm_destination,
optimize)
.chain_err(|| format!("Cargo build of project at '{}' failed",
source_path.display()))?,
_ => bail!(
"Unknown build type '{}' for function at '{}'",
function.build_type,
function.source_url
),
}
if optimize {
optimize_wasm_file_size(&wasm_destination)?;
}
built = true;
}
} else {
debug!(
"wasm at '{}' is up-to-date with source at '{}'",
wasm_destination.display(),
source_path.display()
);
}
function.set_implementation(
wasm_destination
.to_str()
.ok_or("Could not convert path to string")?,
);
Ok((wasm_destination, built))
}
fn run_optional_command(wasm_path: &Path, command: &str, mut args: Vec<String>) -> Result<()> {
if let Ok(FoundType::File(command_path)) =
Simpath::new("PATH").find_type(command, FileType::File)
{
let tmp_dir = TempDir::new_in(
wasm_path
.parent()
.ok_or("Could not get destination directory to create TempDir in")?,
"wasm-opt",
)?;
let temp_file_path = tmp_dir
.path()
.join(wasm_path.file_name().ok_or("Could not get wasm filename")?);
let mut command = Command::new(&command_path);
let mut command_args = vec![wasm_path.to_string_lossy().to_string()];
if !args.is_empty() {
command_args.append(&mut args);
}
command_args.append(&mut vec![temp_file_path.to_string_lossy().to_string()]);
let child = command
.args(command_args)
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
let output = child.output()?;
match output.status.code() {
Some(0) | None => fs::rename(&temp_file_path, &wasm_path)?,
Some(_) => bail!(format!(
"{} exited with non-zero status code",
command_path.to_string_lossy()
)),
}
fs::remove_dir_all(&tmp_dir)?;
}
Ok(())
}
fn optimize_wasm_file_size(wasm_path: &Path) -> Result<()> {
run_optional_command(wasm_path, "wasm-gc", vec!["-o".into()])?;
run_optional_command(wasm_path, "wasm-snip", vec!["-o".into()])?;
run_optional_command(wasm_path, "wasm-gc", vec!["-o".into()])?;
run_optional_command(
wasm_path,
"wasm-opt",
vec!["-O4".into(), "--dce".into(), "-o".into()],
)
}
fn get_paths(target_dir: &Path, function: &FunctionDefinition) -> Result<(PathBuf, PathBuf)> {
let source_url = function.get_source_url().join(function.get_source())?;
let source_path = source_url
.to_file_path()
.map_err(|_| "Could not convert source url to file path")?;
let mut wasm_path = target_dir.join(function.get_source());
wasm_path.set_extension("wasm");
Ok((source_path, wasm_path))
}
fn out_of_date(source: &Path, derived: &Path) -> Result<(bool, bool)> {
let source_last_modified = fs::metadata(source)
.chain_err(|| format!("Could not get metadata for file: '{}'", source.display()))?
.modified()?;
if derived.exists() {
let derived_last_modified = fs::metadata(derived)
.chain_err(|| format!("Could not get metadata for file: '{}'", derived.display()))?
.modified()?;
Ok(((source_last_modified > derived_last_modified), false))
} else {
Ok((true, true))
}
}
#[cfg(test)]
mod test {
use std::{env, fs};
#[cfg(feature = "debugger")]
use std::collections::HashSet;
use std::fs::{File, remove_file, write};
use std::path::Path;
use std::time::Duration;
use serial_test::serial;
use tempdir::TempDir;
#[cfg(feature = "debugger")]
#[cfg(feature = "debugger")]
use url::Url;
use flowcore::model::datatype::STRING_TYPE;
use flowcore::model::function_definition::FunctionDefinition;
use flowcore::model::io::IO;
use flowcore::model::output_connection::{OutputConnection, Source};
use flowcore::model::route::Route;
use super::{get_paths, run_optional_command};
use super::out_of_date;
#[test]
fn test_run_optional_non_existent() {
let _ = run_optional_command(Path::new("/tmp"), "foo", vec!["bar".into()]);
}
#[test]
fn test_run_optional_exists() {
let temp_dir = TempDir::new("flow-tests").expect("Could not get temp dir");
let temp_file_path = temp_dir.path().join("from.test");
File::create(&temp_file_path).expect("Could not create test file");
let _ = run_optional_command(temp_file_path.as_path(), "cp", vec![]);
assert!(temp_file_path.exists());
}
#[test]
fn test_run_optional_exists_fail() {
let temp_dir = TempDir::new("flow-tests").expect("Could not get temp dir");
let temp_file_path = temp_dir.path().join("from.test");
File::create(&temp_file_path).expect("Could not create test file");
let _ = run_optional_command(
temp_file_path.as_path(),
"cp",
vec!["--no-such-flag".into()],
);
assert!(temp_file_path.exists());
}
#[test]
fn out_of_date_test() {
let output_dir = tempdir::TempDir::new("flow")
.expect("Could not create TempDir during testing")
.into_path();
let older = output_dir.join("older");
let derived = older.clone();
write(&older, "older").expect("Could not write to file during testing");
std::thread::sleep(Duration::from_secs(1));
let newer = output_dir.join("newer");
let source = newer.clone();
write(&newer, "newer").expect("Could not write to file during testing");
assert!(
out_of_date(&source, &derived)
.expect("Error in 'out__of_date'")
.0
);
}
#[test]
fn not_out_of_date_test() {
let output_dir = tempdir::TempDir::new("flow")
.expect("Could not create TempDir during testing")
.into_path();
let older = output_dir.join("older");
let source = older.clone();
write(&older, "older").expect("Could not write to file {} during testing");
let newer = output_dir.join("newer");
let derived = newer.clone();
write(&newer, "newer").expect("Could not write to file {} during testing");
assert!(
!out_of_date(&source, &derived)
.expect("Error in 'out_of_date'")
.0
);
}
#[test]
fn out_of_date_missing_test() {
let output_dir = tempdir::TempDir::new("flow")
.expect("Could not create TempDir during testing")
.into_path();
let older = output_dir.join("older");
let source = older.clone();
write(&older, "older").expect("Could not write to file {} during testing");
let newer = output_dir.join("newer");
write(&newer, "newer").expect("Could not write to file {} during testing");
let derived = newer.clone();
remove_file(newer).unwrap_or_else(|_| panic!("Error in 'remove_file' during testing"));
assert!(
out_of_date(&source, &derived)
.expect("Error in 'out__of_date'")
.1
);
}
fn test_function() -> FunctionDefinition {
FunctionDefinition::new(
"Stdout".into(),
false,
"test.rs".to_string(),
"print".into(),
vec![IO::new(vec!(STRING_TYPE.into()), Route::default())],
vec![IO::new(vec!(STRING_TYPE.into()), Route::default())],
Url::parse(&format!(
"file://{}/{}",
env!("CARGO_MANIFEST_DIR"),
"tests/test-functions/test/test"
))
.expect("Could not create source Url"),
Route::from("/flow0/stdout"),
Some(Url::parse("lib::/tests/test-functions/test/test")
.expect("Could not parse Url")),
None,
vec![OutputConnection::new(
Source::default(),
1,
0,
0,
0,
false,
String::default(),
#[cfg(feature = "debugger")]
String::default(),
0,
)],
0,
0,
)
}
#[test]
fn paths_test() {
let function = test_function();
let target_dir = tempdir::TempDir::new("flow")
.expect("Could not create TempDir during testing")
.into_path();
let expected_output_wasm = target_dir.join("test.wasm");
let (impl_source_path, impl_wasm_path) =
get_paths(&target_dir, &function).expect("Error in 'get_paths'");
assert_eq!(
format!(
"{}/{}",
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.expect("Error getting Manifest Dir")
.display(),
"flowc/tests/test-functions/test/test.rs"
),
impl_source_path
.to_str()
.expect("Error converting path to str")
);
assert_eq!(expected_output_wasm, impl_wasm_path);
}
#[test]
#[serial(stdio_wasm_compile)]
fn test_compile_implementation_skip() {
let mut function = test_function();
#[cfg(feature = "debugger")]
let mut source_urls = HashSet::<(Url, Url)>::new();
let target_dir = tempdir::TempDir::new("flow")
.expect("Could not create TempDir during testing")
.into_path();
let expected_output_wasm = target_dir.join("test.wasm");
let (wasm_destination, built) = super::compile_implementation(
&target_dir,
&mut function,
true,
false,
#[cfg(feature = "debugger")]
&mut source_urls,
)
.expect("compile_implementation() failed");
assert!(!built);
assert_eq!(expected_output_wasm, wasm_destination);
}
#[test]
#[serial(stdio_wasm_compile)]
fn test_compile_implementation_skip_missing() {
let mut function = test_function();
let target_dir = tempdir::TempDir::new("flow")
.expect("Could not create TempDir during testing")
.into_path();
let expected_output_wasm = target_dir.join("test.wasm");
let _ = fs::remove_file(&expected_output_wasm);
#[cfg(feature = "debugger")]
let mut source_urls = HashSet::<(Url, Url)>::new();
let (wasm_destination, built) = super::compile_implementation(
&target_dir,
&mut function,
true,
false,
#[cfg(feature = "debugger")]
&mut source_urls,
)
.expect("compile_implementation() failed");
assert!(!built);
assert_eq!(wasm_destination, expected_output_wasm);
}
#[test]
#[serial(stdio_wasm_compile)]
fn test_compile_implementation() {
let mut function = test_function();
function.build_type = "rust".into();
let target_dir = tempdir::TempDir::new("flow")
.expect("Could not create TempDir during testing")
.into_path();
let expected_output_wasm = target_dir.join("test.wasm");
let _ = fs::remove_file(&expected_output_wasm);
#[cfg(feature = "debugger")]
let mut source_urls = HashSet::<(Url, Url)>::new();
let (wasm_destination, built) = super::compile_implementation(
&target_dir,
&mut function,
false,
false,
#[cfg(feature = "debugger")]
&mut source_urls,
)
.expect("compile_implementation() failed");
assert!(built);
assert_eq!(wasm_destination, expected_output_wasm);
}
#[test]
#[serial(stdio_wasm_compile)]
fn test_compile_implementation_not_needed() {
let mut function = test_function();
let target_dir = tempdir::TempDir::new("flow")
.expect("Could not create TempDir during testing")
.into_path();
let expected_output_wasm = target_dir.join("test.wasm");
let _ = fs::remove_file(&expected_output_wasm);
write(&expected_output_wasm, b"file touched during testing")
.expect("Could not write to file during testing");
#[cfg(feature = "debugger")]
let mut source_urls = HashSet::<(Url, Url)>::new();
let (wasm_destination, built) = super::compile_implementation(
&target_dir,
&mut function,
false,
false,
#[cfg(feature = "debugger")]
&mut source_urls,
)
.expect("compile_implementation() failed");
assert!(!built);
assert_eq!(wasm_destination, expected_output_wasm);
}
#[test]
#[serial(stdio_wasm_compile)]
fn test_compile_implementation_invalid_paths() {
let mut function = test_function();
function.set_source("does_not_exist");
#[cfg(feature = "debugger")]
let mut source_urls = HashSet::<(Url, Url)>::new();
let target_dir = tempdir::TempDir::new("flow")
.expect("Could not create TempDir during testing")
.into_path();
assert!(super::compile_implementation(
&target_dir,
&mut function,
true,
false,
#[cfg(feature = "debugger")]
&mut source_urls,
)
.is_err());
}
}