wasm-rquickjs-cli 0.4.12

Tool for wrapping JavaScript modules as WebAssembly components using the QuickJS engine
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
//! Resumable node_compat classification validator.
//!
//! This harness expands `tests/node_compat/config.jsonc` into the same file/subtest inventory as
//! the dynamic runner, executes each entry directly through the node-compat runner component, and
//! appends one JSON object per validated entry to a JSONL file. On restart, already-recorded keys
//! are skipped.
//!
//! Usage:
//!   NODE_COMPAT_VALIDATE_RESULTS=tmp/node-compat-validation/results.jsonl \
//!     cargo test --test node_compat_validate -- --nocapture
//!
//! Useful optional environment variables:
//!   NODE_COMPAT_VALIDATE_LIMIT=10       # stop after N new entries
//!   NODE_COMPAT_VALIDATE_START_AFTER=...# skip until after this expanded key

#[allow(dead_code)]
#[path = "common/mod.rs"]
mod common;

use camino::Utf8Path;
use common::js_subtest_parser::{
    SubtestDiscovery, discover_subtests_with_options, rewrite_for_block_with_options,
    rewrite_for_node_test,
};
use common::{
    CompiledTest, GolemPreparedComponent, NodeCompatCategory, TestInstance,
    load_node_compat_config, setup_node_compat_test_files,
};
use serde_json::json;
use std::collections::{BTreeMap, BTreeSet};
use std::fs::{self, OpenOptions};
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::time::timeout;
use wasmtime::component::Val;

#[derive(Clone)]
struct ValidationCase {
    key: String,
    path: String,
    category: NodeCompatCategory,
    reason: Option<String>,
    timeout_secs: u64,
    subtest_index: Option<usize>,
    nested_node_test: bool,
    isolate_block_subtests: bool,
}

#[derive(Debug)]
enum ActualResult {
    Pass,
    Skip(String),
    Fail(String),
    Error(String),
}

fn main() -> anyhow::Result<()> {
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()?
        .block_on(async_main())
}

async fn async_main() -> anyhow::Result<()> {
    let results_path = std::env::var("NODE_COMPAT_VALIDATE_RESULTS")
        .map(PathBuf::from)
        .unwrap_or_else(|_| PathBuf::from("tmp/node-compat-validation/results.jsonl"));
    let limit = std::env::var("NODE_COMPAT_VALIDATE_LIMIT")
        .ok()
        .and_then(|v| v.parse::<usize>().ok());
    let start_after = std::env::var("NODE_COMPAT_VALIDATE_START_AFTER").ok();

    let cases = load_cases()?;
    let completed = load_completed_keys(&results_path)?;
    let pending_count = cases
        .iter()
        .filter(|case| !completed.contains(&case.key))
        .count();

    println!(
        "Loaded {} validation cases ({} completed, {} pending). Results: {}",
        cases.len(),
        completed.len(),
        pending_count,
        results_path.display()
    );

    if limit == Some(0) || pending_count == 0 {
        return Ok(());
    }

    let prepared = prepare_runner().await?;
    if let Some(parent) = results_path.parent() {
        fs::create_dir_all(parent)?;
    }
    let mut results_file = OpenOptions::new()
        .create(true)
        .append(true)
        .open(&results_path)?;

    let mut source_cache: BTreeMap<String, (String, SubtestDiscovery)> = BTreeMap::new();
    let mut processed = 0usize;
    let mut seen_start = start_after.is_none();

    for case in cases {
        if !seen_start {
            if start_after.as_deref() == Some(case.key.as_str()) {
                seen_start = true;
            }
            continue;
        }
        if completed.contains(&case.key) {
            continue;
        }
        if limit.is_some_and(|limit| processed >= limit) {
            break;
        }

        let started = Instant::now();
        println!(
            "[{}/{}] {} ({})",
            processed + 1,
            limit.unwrap_or(pending_count),
            case.key,
            category_id(case.category)
        );

        let actual = run_case(&prepared, &case, &mut source_cache).await;
        let elapsed_ms = started.elapsed().as_millis();
        let validation = validation_status(case.category, case.reason.as_deref(), &actual);

        let record = json!({
            "key": case.key,
            "path": case.path,
            "category": category_id(case.category),
            "reason": case.reason,
            "actual": actual_json(&actual),
            "validation": validation,
            "elapsed_ms": elapsed_ms,
        });
        serde_json::to_writer(&mut results_file, &record)?;
        writeln!(results_file)?;
        results_file.flush()?;

        println!("  -> {} ({elapsed_ms}ms)", validation);
        processed += 1;
    }

    println!("Validated {processed} new case(s).");
    Ok(())
}

fn load_cases() -> anyhow::Result<Vec<ValidationCase>> {
    let entries = load_node_compat_config("tests/node_compat/config.jsonc")?;
    let mut cases = Vec::new();
    for entry in entries {
        if entry.split && !entry.subtests.is_empty() {
            for subtest in entry.subtests {
                cases.push(ValidationCase {
                    key: format!("{}#{}", entry.path, subtest.name),
                    path: entry.path.clone(),
                    category: subtest.category,
                    reason: subtest.reason,
                    timeout_secs: entry.timeout_secs,
                    subtest_index: Some(subtest.index),
                    nested_node_test: entry.nested_node_test,
                    isolate_block_subtests: entry.isolate_block_subtests,
                });
            }
        } else {
            cases.push(ValidationCase {
                key: entry.path.clone(),
                path: entry.path,
                category: entry.category,
                reason: entry.reason,
                timeout_secs: entry.timeout_secs,
                subtest_index: None,
                nested_node_test: entry.nested_node_test,
                isolate_block_subtests: entry.isolate_block_subtests,
            });
        }
    }
    Ok(cases)
}

fn load_completed_keys(path: &Path) -> anyhow::Result<BTreeSet<String>> {
    let mut completed = BTreeSet::new();
    if !path.exists() {
        return Ok(completed);
    }

    let file = fs::File::open(path)?;
    for line in BufReader::new(file).lines() {
        let line = line?;
        if line.trim().is_empty() {
            continue;
        }
        if let Ok(value) = serde_json::from_str::<serde_json::Value>(&line)
            && let Some(key) = value.get("key").and_then(|v| v.as_str())
        {
            completed.insert(key.to_string());
        }
    }
    Ok(completed)
}

async fn prepare_runner() -> anyhow::Result<Arc<GolemPreparedComponent>> {
    let path = Utf8Path::new("examples/runtime/node-compat-runner");
    let compiled = CompiledTest::new_with_features(
        path,
        true,
        common::FeatureCombination::FullNoLoggingWithGolem,
    )
    .await?;
    Ok(Arc::new(GolemPreparedComponent::new(compiled.wasm_path())?))
}

async fn run_case(
    prepared: &Arc<GolemPreparedComponent>,
    case: &ValidationCase,
    source_cache: &mut BTreeMap<String, (String, SubtestDiscovery)>,
) -> ActualResult {
    let result: anyhow::Result<ActualResult> = async {
        let mut instance = TestInstance::from_golem_prepared(prepared).await?;
        instance.set_epoch_deadline(case.timeout_secs);
        setup_node_compat_test_files(instance.temp_dir_path(), &case.path)?;

        if let Some(index) = case.subtest_index {
            let (source, discovery) = load_split_source(
                &case.path,
                case.nested_node_test,
                case.isolate_block_subtests,
                source_cache,
            )?;
            let rewritten = match discovery {
                SubtestDiscovery::Block(blocks) => rewrite_for_block_with_options(
                    source,
                    blocks,
                    index,
                    case.isolate_block_subtests,
                ),
                SubtestDiscovery::NodeTest(tests) => rewrite_for_node_test(source, tests, index),
                SubtestDiscovery::None => source.to_string(),
            };
            let test_filename = case.path.rsplit('/').next().unwrap_or(&case.path);
            let suite = case.path.split('/').next().unwrap_or("parallel");
            let rewritten_path = instance
                .temp_dir_path()
                .join("home")
                .join("node")
                .join("test")
                .join(suite)
                .join(test_filename);
            fs::write(&rewritten_path, &rewritten)?;
        }

        let guest_path = format!("/home/node/test/{}", case.path);
        let invocation = async {
            instance
                .invoke_and_capture_output_with_stderr(None, "run-test", &[Val::String(guest_path)])
                .await
        };

        match timeout(Duration::from_secs(case.timeout_secs), invocation).await {
            Ok((result, stdout, stderr)) => Ok(parse_invocation_result(result, stdout, stderr)),
            Err(_) => {
                let stdout = instance.read_stdout().unwrap_or_default();
                let stderr = instance.read_stderr().unwrap_or_default();
                Ok(ActualResult::Error(format!(
                    "Timeout after {}s\n[stdout]\n{}\n[stderr]\n{}",
                    case.timeout_secs,
                    stdout.trim(),
                    stderr.trim()
                )))
            }
        }
    }
    .await;

    match result {
        Ok(actual) => actual,
        Err(err) => ActualResult::Error(format!("{err:#}")),
    }
}

fn load_split_source<'a>(
    path: &str,
    nested_node_test: bool,
    isolate_block_subtests: bool,
    source_cache: &'a mut BTreeMap<String, (String, SubtestDiscovery)>,
) -> anyhow::Result<(&'a str, &'a SubtestDiscovery)> {
    let cache_key = format!("{path}#{nested_node_test}#{isolate_block_subtests}");
    if !source_cache.contains_key(&cache_key) {
        let source = fs::read_to_string(format!("tests/node_compat/suite/{path}"))?;
        let discovery =
            discover_subtests_with_options(path, &source, nested_node_test, isolate_block_subtests);
        source_cache.insert(cache_key.clone(), (source, discovery));
    }
    let (source, discovery) = source_cache
        .get(&cache_key)
        .expect("split source was just inserted");
    Ok((source.as_str(), discovery))
}

fn parse_invocation_result(
    result: anyhow::Result<Option<Val>>,
    stdout: String,
    stderr: String,
) -> ActualResult {
    match result {
        Ok(Some(Val::String(ref s))) if s.starts_with("PASS") => ActualResult::Pass,
        Ok(Some(Val::String(ref s))) if s.starts_with("SKIP:") => {
            ActualResult::Skip(s.strip_prefix("SKIP:").unwrap().trim().to_string())
        }
        Ok(Some(Val::String(ref s))) if s.starts_with("FAIL:") => {
            ActualResult::Fail(s.strip_prefix("FAIL:").unwrap().trim().to_string())
        }
        Ok(Some(Val::String(s))) => ActualResult::Fail(s),
        Ok(other) => ActualResult::Fail(format!(
            "Unexpected return: {other:?}\n[stdout]\n{}\n[stderr]\n{}",
            stdout.trim(),
            stderr.trim()
        )),
        Err(err) => ActualResult::Error(format!(
            "Invocation error: {err:#}\n[stdout]\n{}\n[stderr]\n{}",
            stdout.trim(),
            stderr.trim()
        )),
    }
}

fn validation_status(
    category: NodeCompatCategory,
    reason: Option<&str>,
    actual: &ActualResult,
) -> &'static str {
    let has_reason = reason.is_some_and(|reason| !reason.trim().is_empty());
    match category {
        NodeCompatCategory::Runnable => match actual {
            ActualResult::Pass => "ok",
            ActualResult::Skip(_) | ActualResult::Fail(_) | ActualResult::Error(_) => "mismatch",
        },
        NodeCompatCategory::KnownGap => match actual {
            ActualResult::Pass => "stale-pass",
            ActualResult::Skip(_) | ActualResult::Fail(_) | ActualResult::Error(_)
                if has_reason =>
            {
                "ok-observed-gap"
            }
            ActualResult::Skip(_) | ActualResult::Fail(_) | ActualResult::Error(_) => {
                "missing-reason"
            }
        },
        NodeCompatCategory::WasmImpossible => match actual {
            ActualResult::Pass => "mismatch-pass",
            ActualResult::Skip(_) | ActualResult::Fail(_) | ActualResult::Error(_)
                if has_reason =>
            {
                "ok-observed-impossible"
            }
            ActualResult::Skip(_) | ActualResult::Fail(_) | ActualResult::Error(_) => {
                "missing-reason"
            }
        },
        NodeCompatCategory::EngineDifference => match actual {
            ActualResult::Pass => "mismatch-pass",
            ActualResult::Skip(_) | ActualResult::Fail(_) | ActualResult::Error(_)
                if has_reason =>
            {
                "ok-observed-engine-difference"
            }
            ActualResult::Skip(_) | ActualResult::Fail(_) | ActualResult::Error(_) => {
                "missing-reason"
            }
        },
        NodeCompatCategory::NodeInternals => match actual {
            ActualResult::Pass => "stale-pass",
            ActualResult::Skip(_) | ActualResult::Fail(_) | ActualResult::Error(_) => {
                "ok-observed-internals"
            }
        },
        NodeCompatCategory::Unevaluated => match actual {
            ActualResult::Pass => "needs-triage-pass",
            ActualResult::Skip(_) | ActualResult::Fail(_) | ActualResult::Error(_) => {
                "needs-triage"
            }
        },
    }
}

fn actual_json(actual: &ActualResult) -> serde_json::Value {
    match actual {
        ActualResult::Pass => json!({ "result": "pass" }),
        ActualResult::Skip(message) => json!({ "result": "skip", "message": message }),
        ActualResult::Fail(message) => json!({ "result": "fail", "message": message }),
        ActualResult::Error(message) => json!({ "result": "error", "message": message }),
    }
}

fn category_id(category: NodeCompatCategory) -> &'static str {
    match category {
        NodeCompatCategory::Runnable => "runnable",
        NodeCompatCategory::KnownGap => "known-gap",
        NodeCompatCategory::WasmImpossible => "wasi-impossible",
        NodeCompatCategory::EngineDifference => "engine-difference",
        NodeCompatCategory::NodeInternals => "node-internals",
        NodeCompatCategory::Unevaluated => "unevaluated",
    }
}