arora-web 9.0.1

Run an Arora device in the browser: the AroraRuntime wasm-bindgen device over the arora runtime, plus engine and module tooling.
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
//! Browser integration tests. One loads the test-rust-wasm guest module
//! (built by the workspace's `arora-integration-tests` crate as a
//! bindep, into `target/wasm32-wasip1/debug/test_rust_wasm.wasm`)
//! through arora-web's JS-facing `Engine`, then calls its `ping`
//! function; the others drive a device's client operations and drain its
//! store's changes through `AroraRuntime`, stepping it by hand as a page does.

#![cfg(target_arch = "wasm32")]

use arora::{Arora, ModuleBuilder};
use arora_behavior::Status;
use arora_types::call::{CallError, CallResult};
use arora_types::data::{DataStore, Key, StateChange};
use arora_types::module::low::Header;
use arora_types::record::module::frozen::{Function, Parameter};
use arora_types::record::ty::{FrozenScalar, FrozenTy, PrimitiveKind};
use arora_types::record::{FrozenReference, Version};
use arora_types::value::Value;
use arora_web::{AroraWeb, AroraWebBuilder, CompiledModule, Engine};
use uuid::Uuid;
use wasm_bindgen::JsValue;
use wasm_bindgen_futures::JsFuture;
use wasm_bindgen_test::*;

wasm_bindgen_test_configure!(run_in_browser);

// test-rust-wasm is a cdylib artifact dependency; cargo exposes its built wasm
// path as CARGO_CDYLIB_FILE_<DEP>_<lib>.
const WASM_BYTES: &[u8] = include_bytes!(env!("CARGO_CDYLIB_FILE_TEST_RUST_WASM_test_rust_wasm"));

// `ping`, as the guest's Rust declaration pins it.
const PING_FN_ID: &str = "5f423ba9-d5f9-46d7-a9b5-fb7d28f99ea6";

/// The guest's header, from its declaration — what an export step would write
/// as a `module.yaml`, here handed straight to the engine.
fn header() -> Header {
    test_rust_wasm::test_rust_wasm::header(arora_types::module::low::Executor {
        name: "wasm".to_string(),
        min_version: None,
        max_version: None,
    })
}

fn header_json() -> String {
    serde_json::to_string(&header()).expect("the declared header serializes to json")
}

#[wasm_bindgen_test]
fn load_and_ping_test_rust_wasm() {
    let header_json = header_json();
    let mut engine = Engine::new();

    let module_id: String = engine
        .load_module(&header_json, WASM_BYTES)
        .map_err(jsval_to_string)
        .expect("loadModule succeeded");

    // Sanity: returned ID matches the header's id.
    assert_eq!(module_id, header().id.to_string());

    let call_json = format!(r#"{{"id":"{PING_FN_ID}","args":[]}}"#);
    let result = engine
        .call(&call_json)
        .map_err(jsval_to_string)
        .expect("call(ping) succeeded");

    // Just assert we got some non-empty JSON back; full result shape is
    // an `arora_types::call::CallResult` (return value + mutated).
    assert!(!result.is_empty(), "result was empty");
}

/// Same flow through the prepared-module path used for executables larger
/// than Chrome's 8 MB main-thread compile/instantiate limit.
#[wasm_bindgen_test]
async fn prepare_load_and_ping_test_rust_wasm() {
    let header_json = header_json();
    let mut engine = Engine::new();

    wasm_bindgen_futures::JsFuture::from(engine.prepare_module(&header_json, WASM_BYTES.to_vec()))
        .await
        .expect("prepareModule succeeded");

    let module_id: String = engine
        .load_prepared_module(&header_json)
        .map_err(jsval_to_string)
        .expect("loadPreparedModule succeeded");

    assert_eq!(module_id, header().id.to_string());

    let call_json = format!(r#"{{"id":"{PING_FN_ID}","args":[]}}"#);
    let result = engine
        .call(&call_json)
        .map_err(jsval_to_string)
        .expect("call(ping) succeeded");
    assert!(!result.is_empty(), "result was empty");
}

/// Devices built with `withCompiledModule` from one `CompiledModule` each run
/// the module: a call reaches it on every device.
#[wasm_bindgen_test]
async fn devices_share_one_compiled_module() {
    let compiled = CompiledModule::new(&header_json(), WASM_BYTES)
        .map_err(jsval_to_string)
        .expect("the test guest compiles");
    let call_json = format!(
        r#"{{"module_id":"{}","id":"{PING_FN_ID}","args":[]}}"#,
        header().id
    );
    for _ in 0..2 {
        let mut builder = AroraWebBuilder::new();
        builder.with_compiled_module(&compiled);
        let web = builder.build().map_err(jsval_to_string).expect("build");
        let pinged = web.call(&call_json);
        web.step(10.0).expect("step");
        JsFuture::from(pinged)
            .await
            .map_err(jsval_to_string)
            .expect("ping answers");
    }
}

// =============================================================================
// The device's client operations
// =============================================================================

const TOOLS: Uuid = Uuid::from_u128(0x7001);
const DOUBLE: Uuid = Uuid::from_u128(0x7002);
const DOUBLE_X: Uuid = Uuid::from_u128(0x7003);
const WAVE: Uuid = Uuid::from_u128(0x7004);
const TOOLS_STOP: Uuid = Uuid::from_u128(0x7005);
const PLAYER: Uuid = Uuid::from_u128(0x7101);
const PLAYER_STOP: Uuid = Uuid::from_u128(0x7102);

fn answer(ret: Value) -> Result<CallResult, CallError> {
    Ok(CallResult {
        ret,
        mutated: Vec::new(),
    })
}

/// A device whose `tools` module exports `double(x: f64) -> f64`, the
/// task-shaped `wave() -> Status` (running until halted) and `stop()`, and whose
/// `player` module exports a `stop()` of its own.
fn device() -> AroraWeb {
    let signature = |parameters: &[(Uuid, &str)], return_ty: FrozenTy| Function {
        parameters: parameters
            .iter()
            .map(|(id, name)| {
                (
                    *id,
                    Parameter {
                        name: name.to_string(),
                        ty: FrozenTy::from(PrimitiveKind::F64),
                        mutable: false,
                    },
                )
            })
            .collect(),
        parameter_ordering: parameters.iter().map(|(id, _)| *id).collect(),
        return_ty,
    };
    let status = FrozenTy::FrozenScalar(FrozenScalar {
        reference: FrozenReference {
            id: arora_behavior::STATUS_ENUMERATION_ID,
            version: Version::parse("1.0.0").expect("a valid version"),
        },
    });
    let unit = || FrozenTy::from(PrimitiveKind::Unit);
    let tools = ModuleBuilder::new(TOOLS)
        .described_function(
            DOUBLE,
            "double",
            signature(&[(DOUBLE_X, "x")], FrozenTy::from(PrimitiveKind::F64)),
            |call| match call.args.first().map(|field| field.value.as_ref()) {
                Some(Value::F64(x)) => answer(Value::F64(2.0 * x)),
                _ => Err(CallError::Generic {
                    message: "double takes an f64".to_string(),
                }),
            },
        )
        .described_function(WAVE, "wave", signature(&[], status), |_call| {
            answer(Status::Running.into())
        })
        .described_function(TOOLS_STOP, "stop", signature(&[], unit()), |_call| {
            answer(Value::Unit)
        })
        .build();
    let player = ModuleBuilder::new(PLAYER)
        .described_function(PLAYER_STOP, "stop", signature(&[], unit()), |_call| {
            answer(Value::String("player stopped".to_string()))
        })
        .build();
    AroraWeb::from(
        Arora::builder()
            .with_host_module(tools)
            .with_host_module(player)
            .build()
            .expect("build the device"),
    )
}

/// Let the promise tasks the last step woke run: an `invoke` reads the
/// method's signature on one step and queues its call from its promise task.
async fn yield_to_tasks() {
    for _ in 0..4 {
        JsFuture::from(js_sys::Promise::resolve(&JsValue::NULL))
            .await
            .expect("a resolved promise");
    }
}

fn json(value: JsValue) -> serde_json::Value {
    serde_wasm_bindgen::from_value(value).expect("a JSON-shaped answer")
}

fn status_json(status: Status) -> serde_json::Value {
    serde_json::to_value(Value::from(status)).expect("a status serializes")
}

/// Each operation is queued before its method returns: a `step()` in the same
/// turn applies it, with no await in between.
#[wasm_bindgen_test]
async fn an_operation_is_applied_by_a_step_in_the_same_turn() {
    let web = device();
    web.set_value("face/mouth", r#"{"f64": 0.5}"#)
        .expect("write a key");

    let keys = web.list_keys(Some("face/".to_string()));
    let methods = web.describe_methods(Some("dou".to_string()));
    web.step(10.0).expect("step");

    let keys = json(JsFuture::from(keys).await.expect("listKeys resolves"));
    assert_eq!(keys[0]["path"], "face/mouth", "{keys}");
    assert!(keys[0]["__meta"].is_object(), "{keys}");
    assert_eq!(keys.as_array().map(Vec::len), Some(1), "{keys}");

    let methods = json(
        JsFuture::from(methods)
            .await
            .expect("describeMethods resolves"),
    );
    assert_eq!(methods[0]["path"], "double", "{methods}");
    assert_eq!(methods[0]["module"], TOOLS.to_string(), "{methods}");
    assert_eq!(methods[0]["params"][0]["name"], "x", "{methods}");
    assert_eq!(methods[0]["task"], false, "{methods}");
}

/// `invoke` of a plain method resolves to its return value; of a task-shaped
/// one, to the run's handle, whose status key reads Running once a step ticks
/// the run, and which `halt` ends.
#[wasm_bindgen_test]
async fn invoke_answers_a_value_or_starts_a_run() {
    let web = device();

    let doubled = web.invoke("double", r#"{"x": {"f64": 2.5}}"#, None);
    web.step(10.0).expect("step");
    yield_to_tasks().await;
    web.step(10.0).expect("step");
    let doubled = json(JsFuture::from(doubled).await.expect("double answers"));
    // A JS number carries no int/float distinction, so compare it as one.
    assert_eq!(doubled["f64"].as_f64(), Some(5.0), "{doubled}");

    let started = web.invoke("wave", "{}", None);
    web.step(10.0).expect("step");
    yield_to_tasks().await;
    web.step(10.0).expect("step");
    let handle = json(JsFuture::from(started).await.expect("wave starts"));
    // A plain object, keys as paths.
    let run = handle["run"]
        .as_str()
        .unwrap_or_else(|| panic!("the handle names its run: {handle}"))
        .to_string();
    assert!(Uuid::parse_str(&run).is_ok(), "{handle}");
    let status_key = handle["status"]
        .as_str()
        .unwrap_or_else(|| panic!("the handle names its status key: {handle}"))
        .to_string();
    for keys in ["feedback", "result", "update"] {
        assert!(handle[keys].is_array(), "{keys} is a path array: {handle}");
    }

    web.step(10.0).expect("step");
    let read = |web: &AroraWeb| {
        let paths = serde_wasm_bindgen::to_value(&vec![status_key.clone()]).expect("paths");
        json(web.read_values(paths).expect("read the status"))[&status_key].clone()
    };
    assert_eq!(read(&web), status_json(Status::Running));

    let halted = web.halt(&run);
    web.step(10.0).expect("step");
    JsFuture::from(halted).await.expect("the halt is applied");
    web.step(10.0).expect("step");
    assert_eq!(
        read(&web),
        status_json(Status::Failure),
        "a halted run ends Failure"
    );
}

/// A name two modules export rejects naming both, until the module is named.
#[wasm_bindgen_test]
async fn invoke_of_a_shared_name_needs_its_module() {
    let web = device();

    let ambiguous = web.invoke("stop", "{}", None);
    web.step(10.0).expect("step");
    let error = jsval_to_string(
        JsFuture::from(ambiguous)
            .await
            .expect_err("stop is ambiguous"),
    );
    assert!(error.contains(&TOOLS.to_string()), "{error}");
    assert!(error.contains(&PLAYER.to_string()), "{error}");

    let chosen = web.invoke("stop", "{}", Some(PLAYER.to_string()));
    web.step(10.0).expect("step");
    yield_to_tasks().await;
    web.step(10.0).expect("step");
    let stopped = json(
        JsFuture::from(chosen)
            .await
            .expect("the module disambiguates"),
    );
    assert_eq!(stopped, serde_json::json!({"str": "player stopped"}));
}

// =============================================================================
// Draining the store's changes
// =============================================================================

/// A demo device and a sibling handle of its store, through which a test
/// writes as the device's own writers do.
fn device_and_store() -> (AroraWeb, Box<dyn DataStore>) {
    let arora = Arora::builder().build().expect("build the device");
    let store = arora.store().clone_box();
    (AroraWeb::from(arora), store)
}

fn value_json(value: Value) -> serde_json::Value {
    serde_json::to_value(value).expect("a value serializes")
}

/// A drain holds the net change since the previous one: a key set twice reads
/// its second value, a key set then unset reads cleared.
#[wasm_bindgen_test]
fn a_drain_holds_the_net_change_since_the_previous_one() {
    let (web, store) = device_and_store();
    web.drain_changes().expect("the first drain");

    let set = |path: &str, value: f64| {
        store
            .write(StateChange::set(path, Value::F64(value)))
            .expect("set a key");
    };
    set("face/mouth", 0.25);
    set("face/brow", 1.5);
    web.step(10.0).expect("step");
    set("face/mouth", 0.5);
    set("face/brow", 2.5);
    web.step(10.0).expect("step");
    let mut unset = StateChange::new();
    unset.unset.insert(Key::new("face/brow"));
    store.write(unset).expect("unset a key");
    web.step(10.0).expect("step");

    let drained = json(web.drain_changes().expect("drain"));
    assert_eq!(
        drained["face/mouth"],
        value_json(Value::F64(0.5)),
        "{drained}"
    );
    assert_eq!(drained["face/brow"], serde_json::Value::Null, "{drained}");

    let again = json(web.drain_changes().expect("drain again"));
    assert_eq!(
        again,
        serde_json::json!({}),
        "nothing changed since: {again}"
    );
}

/// The first drain holds the store's whole state, the keys written before the
/// device was wrapped included.
#[wasm_bindgen_test]
fn the_first_drain_holds_the_full_state() {
    let arora = Arora::builder().build().expect("build the device");
    let mut before = StateChange::new();
    before
        .set
        .insert(Key::new("face/mouth"), Some(Value::F64(0.25)));
    before
        .set
        .insert(Key::new("face/brow"), Some(Value::F64(1.5)));
    arora.store().write(before).expect("write before wrapping");
    let web = AroraWeb::from(arora);
    for _ in 0..3 {
        web.step(10.0).expect("step");
    }

    let drained = json(web.drain_changes().expect("the first drain"));
    let snapshot = json(web.snapshot().expect("snapshot"));
    assert_eq!(drained, snapshot, "the first drain is the store's state");
    assert_eq!(
        drained["face/mouth"],
        value_json(Value::F64(0.25)),
        "{drained}"
    );
    assert_eq!(
        drained["face/brow"],
        value_json(Value::F64(1.5)),
        "{drained}"
    );
}

fn jsval_to_string(v: JsValue) -> String {
    v.as_string().unwrap_or_else(|| format!("{v:?}"))
}