cross-stream 0.12.0

An event stream store for personal, local-first use, specializing in event sourcing.
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
use nu_protocol::engine::{StateWorkingSet, VirtualPath};
use tempfile::TempDir;

use crate::nu;
use crate::nu::vfs::load_modules;
use crate::store::{FollowOption, Frame, ReadOptions, Store};

async fn setup_test_environment() -> (Store, TempDir) {
    let temp_dir = TempDir::new().unwrap();
    let store = Store::new(temp_dir.path().to_path_buf()).unwrap();

    {
        let store = store.clone();
        drop(tokio::spawn(async move {
            crate::processor::actor::run(store).await.unwrap();
        }));
    }

    // Also spawn commands for the shared-parent test
    {
        let store = store.clone();
        drop(tokio::spawn(async move {
            crate::processor::action::run(store).await.unwrap();
        }));
    }

    (store, temp_dir)
}

async fn assert_no_more_frames(recver: &mut tokio::sync::mpsc::Receiver<Frame>) {
    let timeout = tokio::time::sleep(std::time::Duration::from_millis(50));
    tokio::pin!(timeout);
    tokio::select! {
        Some(frame) = recver.recv() => {
            panic!("Unexpected frame processed: {:?}", frame);
        }
        _ = &mut timeout => {
            // Success - no additional frames were processed
        }
    }
}

fn has_virtual_path(engine: &nu::Engine, name: &str) -> bool {
    let ws = StateWorkingSet::new(&engine.state);
    ws.find_virtual_path(name).is_some()
}

fn has_virtual_file(engine: &nu::Engine, name: &str) -> bool {
    let ws = StateWorkingSet::new(&engine.state);
    matches!(ws.find_virtual_path(name), Some(VirtualPath::File(_)))
}

fn has_virtual_dir(engine: &nu::Engine, name: &str) -> bool {
    let ws = StateWorkingSet::new(&engine.state);
    matches!(ws.find_virtual_path(name), Some(VirtualPath::Dir(_)))
}

// --- Unit tests for load_modules ---

async fn unit_test_store() -> (Store, tempfile::TempDir) {
    let temp_dir = tempfile::TempDir::new().unwrap();
    let store = Store::new(temp_dir.path().to_path_buf()).unwrap();
    (store, temp_dir)
}

#[tokio::test]
async fn test_load_modules_registers_vfs_paths() {
    let (store, _tmp) = unit_test_store().await;
    let mut engine = nu::Engine::new().unwrap();

    let content = r#"export def hello [] { "hi" }"#;
    let hash = store.cas_insert(content).await.unwrap();
    let frame = store
        .append(Frame::builder("mymod.nu").hash(hash).build())
        .unwrap();

    let modules = store.nu_modules_at(&frame.id);
    load_modules(&mut engine.state, &store, &modules).unwrap();

    assert!(has_virtual_file(&engine, "mymod/mod.nu"));
    assert!(has_virtual_dir(&engine, "mymod"));
}

#[tokio::test]
async fn test_load_modules_ignores_non_nu_frames() {
    let (store, _tmp) = unit_test_store().await;
    let mut engine = nu::Engine::new().unwrap();

    let hash = store.cas_insert("content").await.unwrap();
    let frame = store
        .append(Frame::builder("other.topic").hash(hash).build())
        .unwrap();

    let modules = store.nu_modules_at(&frame.id);
    load_modules(&mut engine.state, &store, &modules).unwrap();
    assert!(!has_virtual_path(&engine, "other/topic/mod.nu"));
}

#[tokio::test]
async fn test_load_modules_ignores_frames_without_hash() {
    let (store, _tmp) = unit_test_store().await;
    let mut engine = nu::Engine::new().unwrap();

    let frame = store.append(Frame::builder("mymod.nu").build()).unwrap();

    let modules = store.nu_modules_at(&frame.id);
    load_modules(&mut engine.state, &store, &modules).unwrap();
    assert!(!has_virtual_path(&engine, "mymod/mod.nu"));
}

#[tokio::test]
async fn test_load_modules_ignores_bare_nu_suffix() {
    let (store, _tmp) = unit_test_store().await;
    let mut engine = nu::Engine::new().unwrap();

    let hash = store.cas_insert("content").await.unwrap();
    // ".nu" with nothing before should be ignored by load_modules
    let mut modules = std::collections::HashMap::new();
    modules.insert(".nu".to_string(), hash);

    load_modules(&mut engine.state, &store, &modules).unwrap();
    assert!(!has_virtual_path(&engine, "mod.nu"));
}

#[tokio::test]
async fn test_load_modules_latest_version_wins() {
    let (store, _tmp) = unit_test_store().await;
    let mut engine = nu::Engine::new().unwrap();

    let _hash1 = store.cas_insert(r#"export def v1 [] { 1 }"#).await.unwrap();
    let hash2 = store.cas_insert(r#"export def v2 [] { 2 }"#).await.unwrap();

    let _f1 = store
        .append(
            Frame::builder("mymod.nu")
                .hash(store.cas_insert(r#"export def v1 [] { 1 }"#).await.unwrap())
                .build(),
        )
        .unwrap();
    let f2 = store
        .append(Frame::builder("mymod.nu").hash(hash2).build())
        .unwrap();

    // nu_modules_at compacts, so only latest hash is in the map
    let modules = store.nu_modules_at(&f2.id);
    assert_eq!(modules.len(), 1);

    load_modules(&mut engine.state, &store, &modules).unwrap();
    assert!(has_virtual_file(&engine, "mymod/mod.nu"));
}

#[tokio::test]
async fn test_load_modules_dot_separated_name() {
    let (store, _tmp) = unit_test_store().await;
    let mut engine = nu::Engine::new().unwrap();

    let hash = store
        .cas_insert(r#"export def call [] { "ok" }"#)
        .await
        .unwrap();
    let frame = store
        .append(Frame::builder("discord.api.nu").hash(hash).build())
        .unwrap();

    let modules = store.nu_modules_at(&frame.id);
    load_modules(&mut engine.state, &store, &modules).unwrap();

    assert!(has_virtual_file(&engine, "discord/api/mod.nu"));
    assert!(has_virtual_dir(&engine, "discord/api"));
    assert!(has_virtual_dir(&engine, "discord"));
}

// --- Integration tests: VFS registration via processors ---

#[tokio::test]
async fn test_module_registered_in_vfs() {
    let (store, _temp_dir) = setup_test_environment().await;
    let options = ReadOptions::builder().follow(FollowOption::On).build();
    let mut recver = store.read(options).await;

    assert_eq!(recver.recv().await.unwrap().topic, "xs.threshold");

    // Append a nu module frame
    let module_content = r#"export def greet [name: string] { $"hello ($name)" }"#;
    store
        .append(
            Frame::builder("testmod.nu")
                .hash(store.cas_insert(module_content).await.unwrap())
                .build(),
        )
        .unwrap();

    assert_eq!(recver.recv().await.unwrap().topic, "testmod.nu");

    // Register an actor that uses the module
    let actor_script = r#"{
            run: {|frame, state = null|
                use testmod
                {out: {greeting: (testmod greet "world")}, next: $state}
            }
        }"#;

    store
        .append(
            Frame::builder("vfstest.register")
                .hash(store.cas_insert(&actor_script).await.unwrap())
                .build(),
        )
        .unwrap();

    assert_eq!(recver.recv().await.unwrap().topic, "vfstest.register");

    let next = recver.recv().await.unwrap();
    if next.topic == "vfstest.unregistered" {
        let meta = next.meta.as_ref().unwrap();
        panic!("actor unregistered with error: {}", meta["error"]);
    }
    assert_eq!(next.topic, "vfstest.active");

    // Trigger the actor
    store.append(Frame::builder("ping").build()).unwrap();
    assert_eq!(recver.recv().await.unwrap().topic, "ping");

    // Handler should output the greeting
    let out_frame = recver.recv().await.unwrap();
    assert_eq!(out_frame.topic, "vfstest.out");
    assert_eq!(out_frame.meta.as_ref().unwrap()["greeting"], "hello world");

    assert_no_more_frames(&mut recver).await;
}

#[tokio::test]
async fn test_module_dot_path_maps_to_directory() {
    let (store, _temp_dir) = setup_test_environment().await;
    let options = ReadOptions::builder().follow(FollowOption::On).build();
    let mut recver = store.read(options).await;

    assert_eq!(recver.recv().await.unwrap().topic, "xs.threshold");

    // Register a module with dotted name: mylib.utils.nu
    let module_content = r#"export def add [a: int, b: int] { $a + $b }"#;
    store
        .append(
            Frame::builder("mylib.utils.nu")
                .hash(store.cas_insert(module_content).await.unwrap())
                .build(),
        )
        .unwrap();

    assert_eq!(recver.recv().await.unwrap().topic, "mylib.utils.nu");

    // Actor uses xs/mylib/utils (dots become slashes)
    let actor_script = r#"{
            run: {|frame, state = null|
                use mylib/utils
                {out: {result: (utils add 3 4)}, next: $state}
            }
        }"#;

    store
        .append(
            Frame::builder("dotpath.register")
                .hash(store.cas_insert(&actor_script).await.unwrap())
                .build(),
        )
        .unwrap();

    assert_eq!(recver.recv().await.unwrap().topic, "dotpath.register");
    assert_eq!(recver.recv().await.unwrap().topic, "dotpath.active");

    // Trigger
    store.append(Frame::builder("ping").build()).unwrap();
    assert_eq!(recver.recv().await.unwrap().topic, "ping");

    let out_frame = recver.recv().await.unwrap();
    assert_eq!(out_frame.topic, "dotpath.out");
    assert_eq!(out_frame.meta.as_ref().unwrap()["result"], 7);

    assert_no_more_frames(&mut recver).await;
}

#[tokio::test]
async fn test_live_module_registration() {
    let (store, _temp_dir) = setup_test_environment().await;
    let options = ReadOptions::builder().follow(FollowOption::On).build();
    let mut recver = store.read(options).await;

    assert_eq!(recver.recv().await.unwrap().topic, "xs.threshold");

    // Append module in live phase
    let module_content = r#"export def double [x: int] { $x * 2 }"#;
    store
        .append(
            Frame::builder("mathlib.nu")
                .hash(store.cas_insert(module_content).await.unwrap())
                .build(),
        )
        .unwrap();

    assert_eq!(recver.recv().await.unwrap().topic, "mathlib.nu");

    // Now register an actor that uses the live-registered module
    let actor_script = r#"{
            run: {|frame, state = null|
                use mathlib
                {out: {result: (mathlib double 21)}, next: $state}
            }
        }"#;

    store
        .append(
            Frame::builder("livemod.register")
                .hash(store.cas_insert(&actor_script).await.unwrap())
                .build(),
        )
        .unwrap();

    assert_eq!(recver.recv().await.unwrap().topic, "livemod.register");
    assert_eq!(recver.recv().await.unwrap().topic, "livemod.active");

    // Trigger
    store.append(Frame::builder("ping").build()).unwrap();
    assert_eq!(recver.recv().await.unwrap().topic, "ping");

    let out_frame = recver.recv().await.unwrap();
    assert_eq!(out_frame.topic, "livemod.out");
    assert_eq!(out_frame.meta.as_ref().unwrap()["result"], 42);

    assert_no_more_frames(&mut recver).await;
}

#[tokio::test]
async fn test_multiple_modules_shared_parent() {
    let (store, _temp_dir) = setup_test_environment().await;
    let options = ReadOptions::builder().follow(FollowOption::On).build();
    let mut recver = store.read(options).await;

    assert_eq!(recver.recv().await.unwrap().topic, "xs.threshold");

    // Register two modules that share a parent directory: myapp.utils and myapp.helpers
    let utils_content = r#"export def add [a: int, b: int] { $a + $b }"#;
    store
        .append(
            Frame::builder("myapp.utils.nu")
                .hash(store.cas_insert(utils_content).await.unwrap())
                .build(),
        )
        .unwrap();
    assert_eq!(recver.recv().await.unwrap().topic, "myapp.utils.nu");

    let helpers_content = r#"export def double [x: int] { $x * 2 }"#;
    store
        .append(
            Frame::builder("myapp.helpers.nu")
                .hash(store.cas_insert(helpers_content).await.unwrap())
                .build(),
        )
        .unwrap();
    assert_eq!(recver.recv().await.unwrap().topic, "myapp.helpers.nu");

    // Use a COMMAND (.define) that references the first module.
    let cmd_script = r#"{
            run: {|frame|
                use myapp/utils
                utils add 10 20
            }
            return_options: { target: "cas" }
        }"#;

    store
        .append(
            Frame::builder("sharedcmd.define")
                .hash(store.cas_insert(&cmd_script).await.unwrap())
                .build(),
        )
        .unwrap();

    assert_eq!(recver.recv().await.unwrap().topic, "sharedcmd.define");

    let next = recver.recv().await.unwrap();
    if next.topic == "sharedcmd.error" {
        let meta = next.meta.as_ref().unwrap();
        panic!("command error: {}", meta["error"]);
    }
    assert_eq!(next.topic, "sharedcmd.ready");

    // Call the command
    store
        .append(Frame::builder("sharedcmd.call").build())
        .unwrap();
    assert_eq!(recver.recv().await.unwrap().topic, "sharedcmd.call");

    let out_frame = recver.recv().await.unwrap();
    assert_eq!(out_frame.topic, "sharedcmd.response");
    let content = store.cas_read(&out_frame.hash.unwrap()).await.unwrap();
    let content_str = std::str::from_utf8(&content).unwrap();
    assert!(
        content_str.contains("30"),
        "expected '30' in output, got: {content_str}"
    );

    assert_no_more_frames(&mut recver).await;
}