cross-stream 0.13.4

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
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
use tempfile::TempDir;

use serde_json::json;

use crate::error::Error;
use crate::store::{FollowOption, Frame, ReadOptions, Store};

#[tokio::test]
async fn test_action_with_pipeline() -> Result<(), Error> {
    let (_dir, store) = 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");

    // Define the action
    let frame_action = store.append(
        Frame::builder("xs.action.echo.create")
            .hash(
                store
                    .cas_insert(
                        r#"{
                            run: {|frame|
                                let input = if ($frame.hash != null) { .cas $frame.hash } else { null }
                                let n = $frame.meta.args.n
                                1..($n) | each {$"($in): ($input)"}
                            }
                            return_options: { target: "cas" }
                        }"#,
                    )
                    .await?,
            )
            .build(),
    )?;
    assert_eq!(recver.recv().await.unwrap().topic, "xs.action.echo.create");
    assert_eq!(recver.recv().await.unwrap().topic, "xs.action.echo.active");

    // Call the action
    let frame_call = store.append(
        Frame::builder("echo.call")
            .hash(store.cas_insert(r#"foo"#).await?)
            .meta(json!({"args": {"n": 3}}))
            .build(),
    )?;
    assert_eq!(recver.recv().await.unwrap().topic, "echo.call");

    // Validate the response event with all outputs
    let frame = recver.recv().await.unwrap();
    assert_eq!(frame.topic, "echo.response");
    let meta = frame.meta.as_ref().expect("Meta should be present");
    assert_eq!(meta["action_id"], frame_action.id.to_string());
    assert_eq!(meta["frame_id"], frame_call.id.to_string());

    let hash = frame.hash.as_ref().expect("Hash should be present");
    let content = store.cas_read(hash).await?;
    let content_str = String::from_utf8(content)?;
    let values: Vec<String> = serde_json::from_str(&content_str)?;
    assert_eq!(values, vec!["1: foo", "2: foo", "3: foo"]);

    assert_no_more_frames(&mut recver).await;
    Ok(())
}

#[tokio::test]
async fn test_action_error_handling() -> Result<(), Error> {
    let (_dir, store) = 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");

    // Define action that will error with invalid access
    let frame_action = store
        .append(
            Frame::builder("xs.action.will_error.create")
                .hash(
                    store
                        .cas_insert(
                            r#"{
                            run: {|frame|
                                $frame.meta.args.not_exists # This will error
                            }
                        }"#,
                        )
                        .await?,
                )
                .build(),
        )
        .unwrap();
    assert_eq!(
        recver.recv().await.unwrap().topic,
        "xs.action.will_error.create"
    );
    assert_eq!(
        recver.recv().await.unwrap().topic,
        "xs.action.will_error.active"
    );

    // Call the action
    let frame_call = store
        .append(
            Frame::builder("will_error.call")
                .hash(store.cas_insert(r#""input""#).await?)
                .meta(json!({"args": {}}))
                .build(),
        )
        .unwrap();
    assert_eq!(recver.recv().await.unwrap().topic, "will_error.call");

    // Should get error event
    let frame = recver.recv().await.unwrap();
    assert_eq!(frame.topic, "will_error.error");
    let meta = frame.meta.as_ref().expect("Meta should be present");
    assert_eq!(meta["action_id"], frame_action.id.to_string());
    assert_eq!(meta["frame_id"], frame_call.id.to_string());
    assert!(meta["error"].as_str().unwrap().contains("not_exists"));

    assert_no_more_frames(&mut recver).await;
    Ok(())
}

#[tokio::test]
async fn test_action_single_value() -> Result<(), Error> {
    let (_dir, store) = 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");

    // Define the action
    let frame_action = store.append(
        Frame::builder("xs.action.single.create")
            .hash(
                store
                    .cas_insert(
                        r#"{
                            run: {|frame| "single value output"}
                            return_options: { target: "cas" }
                        }"#,
                    )
                    .await?,
            )
            .build(),
    )?;
    assert_eq!(
        recver.recv().await.unwrap().topic,
        "xs.action.single.create"
    );
    assert_eq!(
        recver.recv().await.unwrap().topic,
        "xs.action.single.active"
    );

    // Call the action
    let frame_call = store.append(Frame::builder("single.call").build())?;
    assert_eq!(recver.recv().await.unwrap().topic, "single.call");

    // Expect single response event
    let frame_resp = recver.recv().await.unwrap();
    assert_eq!(frame_resp.topic, "single.response");
    let meta_resp = frame_resp.meta.as_ref().expect("Meta should be present");
    assert_eq!(meta_resp["action_id"], frame_action.id.to_string());
    assert_eq!(meta_resp["frame_id"], frame_call.id.to_string());

    let hash = frame_resp.hash.as_ref().expect("Hash should be present");
    let content = store.cas_read(hash).await?;
    let content_str = String::from_utf8(content)?;
    let value: String = serde_json::from_str(&content_str)?;
    assert_eq!(value, "single value output".to_string());

    assert_no_more_frames(&mut recver).await;
    Ok(())
}

#[tokio::test]
async fn test_action_empty_output() -> Result<(), Error> {
    let (_dir, store) = 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");

    // Define the action
    let frame_action = store.append(
        Frame::builder("xs.action.empty.create")
            .hash(
                store
                    .cas_insert(
                        r#"{
                            run: {|frame|}
                        }"#,
                    )
                    .await?,
            )
            .build(),
    )?;
    assert_eq!(recver.recv().await.unwrap().topic, "xs.action.empty.create");
    assert_eq!(recver.recv().await.unwrap().topic, "xs.action.empty.active");

    // Call the action
    let frame_call = store.append(Frame::builder("empty.call").build())?;
    assert_eq!(recver.recv().await.unwrap().topic, "empty.call");

    // Expect single response event with no hash
    let frame = recver.recv().await.unwrap();
    assert_eq!(frame.topic, "empty.response");
    let meta = frame.meta.as_ref().expect("Meta should be present");
    assert_eq!(meta["action_id"], frame_action.id.to_string());
    assert_eq!(meta["frame_id"], frame_call.id.to_string());
    assert!(frame.hash.is_none(), "empty output should have no hash");

    assert_no_more_frames(&mut recver).await;
    Ok(())
}

#[tokio::test]
async fn test_action_tee_and_append() -> Result<(), Error> {
    let (_dir, store) = 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");

    // Define the action that outputs a simple pipeline of 1, 2, 3
    let frame_action = store.append(
        Frame::builder("xs.action.numbers.create")
            .hash(
                store
                    .cas_insert(
                        r#"{
                            run: {|frame|
                                [1 2 3] | tee { collect { math sum } | to json -r | .append sum }
                            }
                            return_options: { target: "cas" }
                        }"#,
                    )
                    .await?,
            )
            .build(),
    )?;
    assert_eq!(
        recver.recv().await.unwrap().topic,
        "xs.action.numbers.create"
    );
    assert_eq!(
        recver.recv().await.unwrap().topic,
        "xs.action.numbers.active"
    );

    // Call the action
    let frame_call = store.append(Frame::builder("numbers.call").build())?;
    assert_eq!(recver.recv().await.unwrap().topic, "numbers.call");

    let expected_meta = json!({"action_id": frame_action.id, "frame_id": frame_call.id});

    // Expect sum event from tee side pipeline
    let frame = recver.recv().await.unwrap();
    assert_eq!(frame.topic, "sum");
    assert_eq!(frame.meta.unwrap(), expected_meta);
    let content = store.cas_read(&frame.hash.unwrap()).await?;
    let content_str = String::from_utf8(content)?;
    assert_eq!(content_str, "6");

    // Then expect response with the collected pipeline
    let frame = recver.recv().await.unwrap();
    assert_eq!(frame.topic, "numbers.response");
    assert_eq!(frame.meta.unwrap(), expected_meta);
    let content = store.cas_read(&frame.hash.unwrap()).await?;
    let content_str = String::from_utf8(content)?;
    let values: Vec<i64> = serde_json::from_str(&content_str)?;
    assert_eq!(values, vec![1, 2, 3]);

    assert_no_more_frames(&mut recver).await;
    Ok(())
}

#[tokio::test]
async fn test_action_record_output_goes_to_meta() -> Result<(), Error> {
    let (_dir, store) = 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");

    let frame_action = store.append(
        Frame::builder("xs.action.rec.create")
            .hash(
                store
                    .cas_insert(
                        r#"{
                            run: {|frame| {status: "ok", count: 42} }
                        }"#,
                    )
                    .await?,
            )
            .build(),
    )?;
    assert_eq!(recver.recv().await.unwrap().topic, "xs.action.rec.create");
    assert_eq!(recver.recv().await.unwrap().topic, "xs.action.rec.active");

    let frame_call = store.append(Frame::builder("rec.call").build())?;
    assert_eq!(recver.recv().await.unwrap().topic, "rec.call");

    let frame = recver.recv().await.unwrap();
    assert_eq!(frame.topic, "rec.response");
    assert!(frame.hash.is_none(), "record output should not use CAS");
    let meta = frame.meta.unwrap();
    assert_eq!(meta["action_id"], frame_action.id.to_string());
    assert_eq!(meta["frame_id"], frame_call.id.to_string());
    assert_eq!(meta["status"], "ok");
    assert_eq!(meta["count"], 42);

    assert_no_more_frames(&mut recver).await;
    Ok(())
}

/// I4 Bidirectional lifecycle for actions: xs.action.<name>.term removes the
/// active action and emits xs.action.<name>.fin.term. Subsequent .call frames
/// produce no .response / .error (the action no longer exists).
#[tokio::test]
async fn inv4_action_term_removes_action_and_blocks_calls() -> Result<(), Error> {
    let (_dir, store) = 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");

    // Define a passing-through action.
    let define = store
        .append(
            Frame::builder("xs.action.echo.create")
                .hash(
                    store
                        .cas_insert(r#"{run: {|frame| "hi"}, return_options: {target: "cas"}}"#)
                        .await?,
                )
                .build(),
        )
        .unwrap();
    assert_eq!(recver.recv().await.unwrap().topic, "xs.action.echo.create");
    let ready = recver.recv().await.unwrap();
    assert_eq!(ready.topic, "xs.action.echo.active");
    assert_eq!(
        ready.meta.as_ref().unwrap()["action_id"],
        define.id.to_string()
    );

    // A call before term works.
    let call = store.append(Frame::builder("echo.call").build()).unwrap();
    assert_eq!(recver.recv().await.unwrap().topic, "echo.call");
    let resp = recver.recv().await.unwrap();
    assert_eq!(resp.topic, "echo.response");
    let _ = call;

    // Append term.
    store
        .append(Frame::builder("xs.action.echo.term").build())
        .unwrap();
    assert_eq!(recver.recv().await.unwrap().topic, "xs.action.echo.term");
    let fin = recver.recv().await.unwrap();
    assert_eq!(fin.topic, "xs.action.echo.fin.term");

    // A call after term lands as a frame but produces no response or error.
    store.append(Frame::builder("echo.call").build()).unwrap();
    assert_eq!(recver.recv().await.unwrap().topic, "echo.call");
    assert_no_more_frames(&mut recver).await;
    Ok(())
}

/// I6 Ack traceability for actions: lifecycle acks carry meta.action_id
/// pointing at the originating .define (now .create). Touches .active,
/// .invalid, and .fin.term.
#[tokio::test]
async fn inv6_action_acks_carry_source_pointer() -> Result<(), Error> {
    let (_dir, store) = 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");

    // Good define -> .active.
    let define = store
        .append(
            Frame::builder("xs.action.tr.create")
                .hash(store.cas_insert(r#"{run: {|frame| "hi"}}"#).await?)
                .build(),
        )
        .unwrap();
    assert_eq!(recver.recv().await.unwrap().topic, "xs.action.tr.create");
    let active = recver.recv().await.unwrap();
    assert_eq!(active.topic, "xs.action.tr.active");
    assert_eq!(
        active.meta.as_ref().unwrap()["action_id"],
        define.id.to_string()
    );

    // .term -> .fin.term referencing the term frame (action.serve emits
    // meta.frame_id for the term).
    let term = store
        .append(Frame::builder("xs.action.tr.term").build())
        .unwrap();
    assert_eq!(recver.recv().await.unwrap().topic, "xs.action.tr.term");
    let fin = recver.recv().await.unwrap();
    assert_eq!(fin.topic, "xs.action.tr.fin.term");
    assert_eq!(fin.meta.as_ref().unwrap()["frame_id"], term.id.to_string());

    // Broken define -> .invalid referencing the broken create.
    let bad = store
        .append(
            Frame::builder("xs.action.tr.create")
                .hash(store.cas_insert(r#"not valid nu"#).await?)
                .build(),
        )
        .unwrap();
    assert_eq!(recver.recv().await.unwrap().topic, "xs.action.tr.create");
    let invalid = recver.recv().await.unwrap();
    assert_eq!(invalid.topic, "xs.action.tr.invalid");
    assert_eq!(
        invalid.meta.as_ref().unwrap()["action_id"],
        bad.id.to_string()
    );

    Ok(())
}

/// I8 Single live instance for actions: re-defining an action under the
/// same name replaces the previous definition. Calls go to the latest
/// definition, not both.
#[tokio::test]
async fn inv8_action_single_live_instance_per_name() -> Result<(), Error> {
    let (_dir, store) = 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");

    let _first = store
        .append(
            Frame::builder("xs.action.echo.create")
                .hash(
                    store
                        .cas_insert(
                            r#"{run: {|frame| {who: "first"}}, return_options: {target: "cas"}}"#,
                        )
                        .await?,
                )
                .build(),
        )
        .unwrap();
    assert_eq!(recver.recv().await.unwrap().topic, "xs.action.echo.create");
    assert_eq!(recver.recv().await.unwrap().topic, "xs.action.echo.active");

    let second = store
        .append(
            Frame::builder("xs.action.echo.create")
                .hash(
                    store
                        .cas_insert(
                            r#"{run: {|frame| {who: "second"}}, return_options: {target: "cas"}}"#,
                        )
                        .await?,
                )
                .build(),
        )
        .unwrap();
    assert_eq!(recver.recv().await.unwrap().topic, "xs.action.echo.create");
    assert_eq!(recver.recv().await.unwrap().topic, "xs.action.echo.active");

    // A call: the response should reference the SECOND definition's id,
    // not the first. There is no second response from the old one.
    let call = store.append(Frame::builder("echo.call").build()).unwrap();
    assert_eq!(recver.recv().await.unwrap().topic, "echo.call");
    let resp = recver.recv().await.unwrap();
    assert_eq!(resp.topic, "echo.response");
    let meta = resp.meta.as_ref().unwrap();
    assert_eq!(meta["action_id"], second.id.to_string());
    assert_eq!(meta["frame_id"], call.id.to_string());

    assert_no_more_frames(&mut recver).await;
    Ok(())
}

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
        }
    }
}

async fn setup_test_environment() -> (TempDir, Store) {
    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::action::run(store).await.unwrap();
        }));
    }

    (temp_dir, store)
}