nsh-engine 0.5.0

Engine thread that drives the JS host and the core and emits mount batches.
Documentation
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
//! `fetch` through the engine: requests reach the platform network on its
//! own threads, responses come back to JS, aborted requests are cancelled.

use std::{
    sync::{Arc, Mutex, mpsc},
    time::Duration,
};

use nsh_core::{ApproxTextEngine, MountBatch, MountItem, Size, geometry::px};
use nsh_engine::{
    Bundle, Engine, EngineConfig, FetchEvent, FetchEvents, FetchTask, HttpBody, HttpHead,
    HttpRequest, MountSink, Network,
};

struct Sink(mpsc::Sender<MountBatch>);

impl MountSink for Sink {
    fn submit(&self, batch: MountBatch) {
        let _ = self.0.send(batch);
    }
}

/// A task that only records its cancellation.
struct Task(Option<Box<dyn FnOnce() + Send>>);

impl FetchTask for Task {
    fn send(&mut self, _: Vec<u8>) {}
    fn finish(&mut self) {}
    fn pause(&mut self, _: bool) {}
    fn cancel(mut self: Box<Self>) {
        if let Some(f) = self.0.take() {
            f();
        }
    }
}

/// Answers `response` with `body` in two chunks, on another thread.
fn answer(mut events: FetchEvents, head: HttpHead, body: Vec<u8>) {
    std::thread::spawn(move || {
        std::thread::sleep(Duration::from_millis(5));
        events(FetchEvent::Head(head));
        let (a, b) = body.split_at(body.len() / 2);
        events(FetchEvent::Data(a.to_vec()));
        events(FetchEvent::Data(b.to_vec()));
        events(FetchEvent::End);
    });
}

/// Answers on a background thread, echoing the request.
#[derive(Default)]
struct EchoNetwork {
    cancelled: Arc<Mutex<Vec<String>>>,
}

impl Network for EchoNetwork {
    fn fetch(&self, request: HttpRequest, events: FetchEvents) -> Box<dyn FetchTask> {
        let url = request.url.clone();
        if url.ends_with("/slow") {
            let cancelled = self.cancelled.clone();
            return Box::new(Task(Some(Box::new(move || {
                cancelled.lock().unwrap().push(url)
            }))));
        }
        let sent = match &request.body {
            HttpBody::Bytes(b) => String::from_utf8_lossy(b).into_owned(),
            _ => String::new(),
        };
        let body = format!("{} {} {sent}", request.method, request.url);
        let head = HttpHead {
            status: 200,
            url: request.url,
            headers: vec![("content-type".into(), "text/plain".into())],
            ..HttpHead::default()
        };
        answer(events, head, body.into_bytes());
        Box::new(Task(None))
    }
}

const APP: &str = r#"
import { mount, signal, Text } from "nsh";
const text = signal("loading");
const slow = new AbortController();
fetch("https://example.com/slow", { signal: slow.signal }).catch((e) => console.log(e.name));
fetch("https://example.com/echo", { method: "PUT", body: "hi" })
  .then((r) => r.text())
  .then((t) => { text.set(t); slow.abort(); });
mount(() => <Text>{text()}</Text>);
"#;

fn texts(batch: &MountBatch) -> Vec<String> {
    batch
        .items
        .iter()
        .filter_map(|i| match i {
            MountItem::Text { text, .. } => Some(text.text.to_string()),
            _ => None,
        })
        .collect()
}

#[test]
fn fetch_round_trips_through_the_platform_network() {
    let dir = std::env::temp_dir().join(format!("nsh-fetch-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let entry = dir.join("App.tsx");
    std::fs::write(&entry, APP).unwrap();
    let bundle = nsh_bundler::bundle(&nsh_bundler::BundleOptions {
        entry,
        minify: false,
        split: false,
        ui_sets: vec![nsh_base::registry().into()],
        ..Default::default()
    })
    .unwrap();
    let network = Arc::new(EchoNetwork::default());
    let cancelled = network.cancelled.clone();
    let (tx, rx) = mpsc::channel();
    let config = EngineConfig {
        // SAFETY: compiled just now by this runtime.
        app: nsh_engine::App::Js(unsafe {
            Bundle::bytecode(nsh_js::compile_bytecode(&bundle.code, false).unwrap())
        }),
        viewport: Size::new(px(320.0), px(480.0)),
        trace: false,
        content_culling: false,
        network: Some(network),
        websocket: None,
        refuse_connections: None,
        filesystem: None,
        assets: None,
        environment: Default::default(),
        header_heights: (nsh_core::Points(44.0), nsh_core::Points(96.0)),
        limits: nsh_engine::Limits::default(),
        ui_sets: Vec::new(),
        runtime: None,
        data_dir: None,
        cache: nsh_engine::CacheOptions::off(),
        storage: None,
        clock: Default::default(),
        context: Default::default(),
        pinned: Default::default(),
        clipboard: None,
        host: Default::default(),
        picker: None,
        speech: None,
        audio: None,
        windows: None,
    };
    let _engine = Engine::start(config, || ApproxTextEngine, Sink(tx)).unwrap();
    assert_eq!(
        texts(&rx.recv_timeout(Duration::from_secs(5)).unwrap()),
        ["loading"]
    );
    assert_eq!(
        texts(&rx.recv_timeout(Duration::from_secs(5)).unwrap()),
        ["PUT https://example.com/echo hi"]
    );
    // The abort reaches the network once the engine pumps it.
    let deadline = std::time::Instant::now() + Duration::from_secs(5);
    while cancelled.lock().unwrap().is_empty() {
        assert!(
            std::time::Instant::now() < deadline,
            "slow request not cancelled"
        );
        std::thread::sleep(Duration::from_millis(5));
    }
    assert_eq!(*cancelled.lock().unwrap(), ["https://example.com/slow"]);
}

/// Redirects `/hop/<url>` to `<url>`; answers everything else.
struct RedirectNetwork {
    seen: Arc<Mutex<Vec<String>>>,
}

impl Network for RedirectNetwork {
    fn fetch(&self, request: HttpRequest, events: FetchEvents) -> Box<dyn FetchTask> {
        self.seen.lock().unwrap().push(request.url.clone());
        assert!(
            !request.follow_redirects,
            "the engine follows redirects itself"
        );
        let (head, body) = match request.url.split_once("/hop/") {
            Some((_, to)) => (
                HttpHead {
                    status: 302,
                    url: request.url.clone(),
                    headers: vec![("location".into(), to.into())],
                    ..HttpHead::default()
                },
                b"moved".to_vec(),
            ),
            None => (
                HttpHead {
                    status: 200,
                    url: request.url.clone(),
                    ..HttpHead::default()
                },
                b"ok".to_vec(),
            ),
        };
        answer(events, head, body);
        Box::new(Task(None))
    }
}

const CHECKED_APP: &str = r#"
import { mount, registerFont, signal, Text } from "nsh";
const text = signal("loading");
const outcome = (p) => p.then(
  (r) => r.text().then((t) => `${t}${r.redirected ? " (redirected)" : ""}`),
  (e) => `${e.name} ${e.code} ${e.permission} ${e.resource}: ${e.message}`,
);
const font = (p) => p.then(
  ({ family }) => `registered ${family}`,
  (e) => `${e.name} ${e.code} ${e.permission} ${e.resource}`,
);
Promise.all([
  outcome(fetch("https://evil.io/")),
  outcome(fetch("https://api.example.com/hop/https://api.example.com/final")),
  outcome(fetch("https://api.example.com/hop/https://evil.io/steal")),
  font(registerFont("https://evil.io/font.woff2")),
  font(registerFont("https://api.example.com/hop/https://evil.io/font.woff2")),
]).then((r) => text.set(r.join(" | ")));
mount(() => <Text>{text()}</Text>);
"#;

#[test]
fn fetch_stays_within_the_capabilities() {
    let dir = std::env::temp_dir().join(format!("nsh-fetch-caps-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let entry = dir.join("App.tsx");
    std::fs::write(&entry, CHECKED_APP).unwrap();
    let bundle = nsh_bundler::bundle(&nsh_bundler::BundleOptions {
        entry,
        minify: false,
        split: false,
        ui_sets: vec![nsh_base::registry().into()],
        ..Default::default()
    })
    .unwrap();
    let seen = Arc::new(Mutex::new(Vec::new()));
    let (tx, rx) = mpsc::channel();
    let config = EngineConfig {
        // SAFETY: compiled just now by this runtime.
        app: nsh_engine::App::Js(
            unsafe { Bundle::bytecode(nsh_js::compile_bytecode(&bundle.code, false).unwrap()) }
                .with_capabilities_json(Some(r#"{ "network": { "hosts": ["api.example.com"] } }"#))
                .unwrap(),
        ),
        viewport: Size::new(px(320.0), px(480.0)),
        trace: false,
        content_culling: false,
        network: Some(Arc::new(RedirectNetwork { seen: seen.clone() })),
        websocket: None,
        refuse_connections: None,
        filesystem: None,
        assets: None,
        environment: Default::default(),
        header_heights: (nsh_core::Points(44.0), nsh_core::Points(96.0)),
        limits: nsh_engine::Limits::default(),
        ui_sets: Vec::new(),
        runtime: None,
        data_dir: None,
        cache: nsh_engine::CacheOptions::off(),
        storage: None,
        clock: Default::default(),
        context: Default::default(),
        pinned: Default::default(),
        clipboard: None,
        host: Default::default(),
        picker: None,
        speech: None,
        audio: None,
        windows: None,
    };
    let _engine = Engine::start(config, || ApproxTextEngine, Sink(tx)).unwrap();
    assert_eq!(
        texts(&rx.recv_timeout(Duration::from_secs(5)).unwrap()),
        ["loading"]
    );
    let result = texts(&rx.recv_timeout(Duration::from_secs(5)).unwrap()).join("");
    let parts: Vec<&str> = result.split(" | ").collect();
    // Refused requests and redirects reject as every failed fetch, with a
    // `TypeError`, and say what was refused.
    assert!(
        parts[0].starts_with("TypeError ERR_ACCESS_DENIED network https://evil.io/: ")
            && parts[0].contains("`evil.io` to capabilities.network"),
        "{result}"
    );
    assert_eq!(parts[1], "ok (redirected)");
    assert!(
        parts[2].starts_with("TypeError ERR_ACCESS_DENIED network https://evil.io/steal: ")
            && parts[2].contains("https://evil.io/steal is not granted"),
        "{result}"
    );
    // `registerFont` reads its URL as `fetch` does, and its refusals carry
    // the same fields, a redirect's too: an `Error`, as every module
    // function's refusal.
    assert_eq!(
        parts[3],
        "Error ERR_ACCESS_DENIED network https://evil.io/font.woff2"
    );
    assert_eq!(
        parts[4],
        "Error ERR_ACCESS_DENIED network https://evil.io/font.woff2"
    );
    // evil.io was never contacted.
    assert!(
        seen.lock()
            .unwrap()
            .iter()
            .all(|u| !u.starts_with("https://evil.io"))
    );
}

const PATH_APP: &str = r#"
import { mount, registerFont, signal, Text } from "nsh";
const text = signal("loading");
const outcome = (p) => p.then((r) => r.text(), (e) => `${e.code} ${e.resource}`);
const font = (p) => p.then(({ family }) => `registered ${family}`, (e) => `${e.code ?? e.name}`);
Promise.all([
  outcome(fetch("https://api.example.com/public/../private")),
  font(registerFont("https://api.example.com/public/../private.woff2")),
  font(registerFont("https://api.example.com/public/%2e%2e/private.woff2")),
  font(registerFont("https://api.example.com/private/../public/f.woff2")),
]).then((r) => text.set(r.join(" | ")));
mount(() => <Text>{text()}</Text>);
"#;

/// A path rule holds for every request, `registerFont`'s raw URL as much as
/// `fetch`'s parsed one: the path is matched as WHATWG's parser resolves it,
/// and the request goes out with that URL.
#[test]
fn path_rules_hold_for_every_request() {
    let dir = std::env::temp_dir().join(format!("nsh-fetch-paths-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let entry = dir.join("App.tsx");
    std::fs::write(&entry, PATH_APP).unwrap();
    let bundle = nsh_bundler::bundle(&nsh_bundler::BundleOptions {
        entry,
        minify: false,
        split: false,
        ui_sets: vec![nsh_base::registry().into()],
        ..Default::default()
    })
    .unwrap();
    let seen = Arc::new(Mutex::new(Vec::new()));
    let (tx, rx) = mpsc::channel();
    let config = EngineConfig {
        // SAFETY: compiled just now by this runtime.
        app: nsh_engine::App::Js(
            unsafe { Bundle::bytecode(nsh_js::compile_bytecode(&bundle.code, false).unwrap()) }
                .with_capabilities_json(Some(
                    r#"{ "network": { "http": [{ "host": "api.example.com", "pathPrefix": "/public" }] } }"#,
                ))
                .unwrap(),
        ),
        viewport: Size::new(px(320.0), px(480.0)),
        trace: false,
        content_culling: false,
        network: Some(Arc::new(RedirectNetwork { seen: seen.clone() })),
        websocket: None,
        refuse_connections: None,
        filesystem: None,
        assets: None,
        environment: Default::default(),
        header_heights: (nsh_core::Points(44.0), nsh_core::Points(96.0)),
        limits: nsh_engine::Limits::default(),
        ui_sets: Vec::new(),
        runtime: None,
        data_dir: None,
        cache: nsh_engine::CacheOptions::off(),
        storage: None,
        clock: Default::default(),
        context: Default::default(),
        pinned: Default::default(),
        clipboard: None,
        host: Default::default(),
        picker: None,
        speech: None,
        audio: None,
        windows: None,
    };
    let _engine = Engine::start(config, || ApproxTextEngine, Sink(tx)).unwrap();
    assert_eq!(
        texts(&rx.recv_timeout(Duration::from_secs(5)).unwrap()),
        ["loading"]
    );
    let result = texts(&rx.recv_timeout(Duration::from_secs(5)).unwrap()).join("");
    let parts: Vec<&str> = result.split(" | ").collect();
    assert_eq!(
        parts[0], "ERR_ACCESS_DENIED https://api.example.com/private",
        "{result}"
    );
    assert_eq!(parts[1], "ERR_ACCESS_DENIED", "{result}");
    assert_eq!(parts[2], "ERR_ACCESS_DENIED", "{result}");
    // Granted as resolved, and requested as resolved: no font in the
    // stand-in's answer, but no refusal either.
    assert_ne!(parts[3], "ERR_ACCESS_DENIED", "{result}");
    assert_eq!(
        *seen.lock().unwrap(),
        ["https://api.example.com/public/f.woff2"]
    );
}

/// A Rust component whose task fetches: the echo's text shows, and the slow
/// request is cancelled with the task that waited for it.
#[nsh_core::element::component]
fn Fetcher() -> impl nsh_core::element::IntoElement {
    use nsh_core::prelude::*;
    let shown = signal(SharedString::from("loading"));
    spawn(async move {
        let slow = spawn(fetch("https://example.com/slow"));
        let echo = fetch(HttpRequest::new("put", "https://example.com/echo").body("hi")).await;
        slow.cancel();
        shown.set(match echo {
            Ok(response) => format!("{} {}", response.status(), response.text()).into(),
            Err(error) => error.into(),
        });
    });
    text(move || shown.get())
}

#[test]
fn rust_components_fetch_through_the_platform_network() {
    let network = Arc::new(EchoNetwork::default());
    let cancelled = network.cancelled.clone();
    let (tx, rx) = mpsc::channel();
    let config = EngineConfig {
        app: nsh_engine::App::Rust(nsh_core::element::Root::of::<Fetcher>()),
        viewport: Size::new(px(320.0), px(480.0)),
        trace: false,
        content_culling: false,
        network: Some(network),
        websocket: None,
        refuse_connections: None,
        filesystem: None,
        assets: None,
        environment: Default::default(),
        header_heights: (nsh_core::Points(44.0), nsh_core::Points(96.0)),
        limits: nsh_engine::Limits::default(),
        ui_sets: Vec::new(),
        runtime: None,
        data_dir: None,
        cache: nsh_engine::CacheOptions::off(),
        storage: None,
        clock: Default::default(),
        context: Default::default(),
        pinned: Default::default(),
        clipboard: None,
        host: Default::default(),
        picker: None,
        speech: None,
        audio: None,
        windows: None,
    };
    let _engine = Engine::start(config, || ApproxTextEngine, Sink(tx)).unwrap();
    let mut shown = Vec::new();
    while !shown.iter().any(|t: &String| t.starts_with("200")) {
        let batch = rx
            .recv_timeout(Duration::from_secs(5))
            .expect("no response");
        shown.extend(texts(&batch));
    }
    assert_eq!(shown.last().unwrap(), "200 PUT https://example.com/echo hi");
    let deadline = std::time::Instant::now() + Duration::from_secs(5);
    while cancelled.lock().unwrap().is_empty() {
        assert!(
            std::time::Instant::now() < deadline,
            "slow request not cancelled"
        );
        std::thread::sleep(Duration::from_millis(5));
    }
    assert_eq!(*cancelled.lock().unwrap(), ["https://example.com/slow"]);
}