loonfs-server 0.2.0

The reference LoonFS HTTP server.
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
//! The one wire commit surface: batches commit atomically, a failing
//! operation names its position, and replay shares one fingerprint domain
//! with the embedded runtime.

use crate::common::http_split_support::*;
use crate::common::start_server;
use loonfs::publish::CommitRequest as CoreCommitRequest;
use loonfs::{CreateNamespaceOptions, FsWriter, ListChangesOptions, StoreConfig};
use loonfs_api::{
    v0::CommittedChange, AbsolutePath, ChangeSeq, CommitId, CommitRequest, ContentRef,
    DeleteDirectoryBehavior, DestinationBehavior, ErrorCode, FilesystemOperation,
};
use loonfs_client::{ClientError, NamespacePath};
use loonfs_test_support::ids::namespace_id;
use tempfile::tempdir;

const REPORTS_DIR: &str = "/reports";
const FIRST_FILE: &str = "/reports/january.txt";
const SECOND_FILE: &str = "/reports/february.txt";
const FIRST_BYTES: &[u8] = b"january numbers";
const SECOND_BYTES: &[u8] = b"february numbers";

fn absolute(path: &str) -> AbsolutePath {
    AbsolutePath::parse(path).expect("valid absolute path")
}

fn commit_id(value: &str) -> CommitId {
    CommitId::parse(value).expect("valid commit id")
}

/// The comparable content of one committed change: everything the feed
/// promises except the wall-clock stamp, which is observational.
/// The parts of a change two transports must agree on.
///
/// Content identity is left out on purpose: each transport staged its own
/// content objects, so their ids differ by construction. The rest of the
/// reference — size and checksums — stays in, so identical bytes still have
/// to produce identical evidence.
fn change_identity(change: &CommittedChange) -> (ChangeSeq, String, Option<String>, String) {
    let mut events = serde_json::to_value(&change.events).expect("serialize events");
    for event in events.as_array_mut().expect("events array") {
        if let Some(content_ref) = event.get_mut("content_ref") {
            content_ref["content_id"] = serde_json::Value::from("<normalized>");
        }
    }
    (
        change.seq,
        change.commit_id.to_string(),
        change.message.clone(),
        events.to_string(),
    )
}

/// The directory-then-two-files batch.
///
/// Both transports below build their operations from this one helper, which
/// they can because there is one operation language: the served arm and the
/// embedded arm differ only in the content each staged.
fn batch(first: &ContentRef, second: &ContentRef) -> Vec<FilesystemOperation> {
    vec![
        FilesystemOperation::CreateDirectory {
            path: absolute(REPORTS_DIR),
            parents: false,
        },
        FilesystemOperation::PutFile {
            path: absolute(FIRST_FILE),
            content_ref: first.clone(),
            behavior: DestinationBehavior::NoReplace,
            expected_revision_no: None,
        },
        FilesystemOperation::PutFile {
            path: absolute(SECOND_FILE),
            content_ref: second.clone(),
            behavior: DestinationBehavior::NoReplace,
            expected_revision_no: None,
        },
    ]
}

/// One batch, two transports: the same three operations submitted over HTTP
/// and embedded produce the same single commit and the same ordered events.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_batch_commits_once_and_matches_the_same_batch_embedded() {
    let temp_dir = tempdir().expect("tempdir");
    let store_root = temp_dir.path().join("store");
    let harness = start_server(test_config(
        store_root.clone(),
        "loonfs-server-batch",
        "http-commits",
    ))
    .await;

    // Two namespaces in one store: writer epochs are per namespace, so the
    // embedded arm and the served arm never fence each other.
    let remote_ns = namespace_id("remote");
    harness
        .client
        .create_namespace(&remote_ns)
        .await
        .expect("create remote namespace");
    let first = stage_uploaded_content(&harness.client, &remote_ns, FIRST_BYTES).await;
    let second = stage_uploaded_content(&harness.client, &remote_ns, SECOND_BYTES).await;

    let committed = harness
        .client
        .commit(
            &remote_ns,
            &CommitRequest {
                commit_id: commit_id("batch-one"),
                message: Some("import the reports".to_owned()),
                content_tokens: vec![
                    validated_content_token(&first),
                    validated_content_token(&second),
                ],
                operations: batch(&first.content_ref, &second.content_ref),
            },
        )
        .await
        .expect("batch commits");
    // Three operations, one commit: the namespace advanced exactly once.
    assert_eq!(committed.committed_seq, ChangeSeq(1));
    assert_eq!(committed.commit_id.as_str(), "batch-one");

    let remote_changes = harness
        .client
        .list_changes(&remote_ns, ChangeSeq(0), None)
        .await
        .expect("remote changes");
    assert_eq!(remote_changes.changes.len(), 1, "{remote_changes:?}");
    // One event per operation, in request order: the directory, then the
    // two files created under it.
    assert_eq!(remote_changes.changes[0].events.len(), 3);

    // Every path the batch named is visible, and only because the whole
    // batch committed.
    for (path, bytes) in [(FIRST_FILE, FIRST_BYTES), (SECOND_FILE, SECOND_BYTES)] {
        let spec = NamespacePath::parse("remote", path).expect("path");
        assert_eq!(
            harness
                .client
                .get_file_bytes(&spec)
                .await
                .expect("batch file readable"),
            bytes
        );
    }

    // The same batch, submitted embedded against the same store.
    let embedded_ns = namespace_id("embedded");
    let writer = FsWriter::builder(StoreConfig::LocalFs {
        root: store_root.display().to_string(),
        key_prefix: Some("http-commits".to_owned()),
    })
    .writer_id("loonfs-embedded-batch")
    .build()
    .await
    .expect("embedded writer");
    writer
        .create_namespace(&embedded_ns, CreateNamespaceOptions::default())
        .await
        .expect("create embedded namespace");
    let first_prepared = writer
        .prepare_file_bytes(&embedded_ns, FIRST_BYTES)
        .await
        .expect("prepare first");
    let second_prepared = writer
        .prepare_file_bytes(&embedded_ns, SECOND_BYTES)
        .await
        .expect("prepare second");
    let embedded_committed = writer
        .commit_prepared(
            &embedded_ns,
            CoreCommitRequest {
                commit_id: commit_id("batch-one"),
                message: Some("import the reports".to_owned()),
                operations: batch(first_prepared.content_ref(), second_prepared.content_ref()),
            },
            vec![first_prepared, second_prepared],
        )
        .await
        .expect("embedded batch commits");
    assert_eq!(embedded_committed.committed_seq, committed.committed_seq);

    let embedded_changes = writer
        .reader()
        .list_changes(&embedded_ns, ChangeSeq(0), ListChangesOptions::default())
        .await
        .expect("embedded changes");

    // The parity claim: the two transports produced the same commit —
    // same sequence, same id, same annotation, same ordered events.
    assert_eq!(
        remote_changes
            .changes
            .iter()
            .map(change_identity)
            .collect::<Vec<_>>(),
        embedded_changes
            .changes
            .iter()
            .map(change_identity)
            .collect::<Vec<_>>()
    );

    writer
        .shutdown()
        .await
        .expect("settle embedded background work");
    harness.server.abort();
}

/// A batch is all-or-nothing: the operation that stops it names its own
/// position, and nothing the batch would have written is visible.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_failing_operation_names_its_position_and_commits_nothing() {
    let temp_dir = tempdir().expect("tempdir");
    let harness = start_server(test_config(
        temp_dir.path().join("store"),
        "loonfs-server-batch-failure",
        "http-commit-failure",
    ))
    .await;

    let namespace = namespace_id("demo");
    harness
        .client
        .create_namespace(&namespace)
        .await
        .expect("create namespace");
    let staged = stage_uploaded_content(&harness.client, &namespace, FIRST_BYTES).await;

    // Operations 0 and 1 are valid and depend on each other; operation 2
    // deletes a path that was never bound.
    let error = harness
        .client
        .commit(
            &namespace,
            &CommitRequest {
                commit_id: commit_id("batch-stops-at-two"),
                message: None,
                content_tokens: vec![validated_content_token(&staged)],
                operations: vec![
                    FilesystemOperation::CreateDirectory {
                        path: absolute(REPORTS_DIR),
                        parents: false,
                    },
                    FilesystemOperation::PutFile {
                        path: absolute(FIRST_FILE),
                        content_ref: staged.content_ref.clone(),
                        behavior: DestinationBehavior::NoReplace,
                        expected_revision_no: None,
                    },
                    FilesystemOperation::DeletePath {
                        path: absolute("/never-existed.txt"),
                        behavior: DeleteDirectoryBehavior::NonRecursive,
                        expected_inode_id: None,
                    },
                ],
            },
        )
        .await
        .expect_err("the third operation has nothing to delete");

    match error {
        ClientError::Api {
            status,
            code,
            details,
            ..
        } => {
            // The code stays the failing operation's own; the position is
            // what batching adds.
            assert_eq!(status, 404);
            assert_eq!(code, ErrorCode::PathNotFound.as_str());
            let details = details.expect("failed batch carries details");
            assert_eq!(details.operation_index, Some(2));
            assert_eq!(
                details.commit_id.as_ref().map(CommitId::as_str),
                Some("batch-stops-at-two")
            );
        }
        other => unreachable!("expected path_not_found with a position, got {other:?}"),
    }

    // Nothing the batch would have written became visible, and the head
    // never advanced.
    for path in [REPORTS_DIR, FIRST_FILE] {
        let spec = NamespacePath::parse("demo", path).expect("path");
        let missing = harness
            .client
            .stat_path(&spec)
            .await
            .expect_err("the aborted batch wrote nothing");
        match missing {
            ClientError::Api { code, .. } => assert_eq!(code, ErrorCode::PathNotFound.as_str()),
            other => unreachable!("expected path_not_found, got {other:?}"),
        }
    }
    assert_eq!(
        harness
            .client
            .namespace_status(&namespace)
            .await
            .expect("status")
            .head_seq,
        ChangeSeq(0)
    );

    harness.server.abort();
}

/// An empty operation list is the one shape the language does not accept;
/// the wire surfaces core's own classification for it.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn an_empty_operation_list_is_rejected() {
    let temp_dir = tempdir().expect("tempdir");
    let harness = start_server(test_config(
        temp_dir.path().join("store"),
        "loonfs-server-empty-batch",
        "http-empty-batch",
    ))
    .await;

    let namespace = namespace_id("demo");
    harness
        .client
        .create_namespace(&namespace)
        .await
        .expect("create namespace");

    let error = harness
        .client
        .commit(
            &namespace,
            &CommitRequest {
                commit_id: commit_id("empty-batch"),
                message: None,
                content_tokens: Vec::new(),
                operations: Vec::new(),
            },
        )
        .await
        .expect_err("an empty request has nothing to commit");
    match error {
        ClientError::Api { status, code, .. } => {
            assert_eq!(status, 400);
            assert_eq!(code, ErrorCode::InvalidRequest.as_str());
        }
        other => unreachable!("expected invalid_request, got {other:?}"),
    }
    assert_eq!(
        harness
            .client
            .namespace_status(&namespace)
            .await
            .expect("status")
            .head_seq,
        ChangeSeq(0)
    );

    harness.server.abort();
}

/// The root is readable but never a mutation target, alone or inside a
/// batch, and rejecting it commits nothing.
///
/// The planners own the rule, so the rejection is attributed exactly like
/// every other planning failure: a batch names the operation that stopped
/// it, a one-operation request names nothing, and both echo the commit id.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn the_root_path_is_rejected_as_a_mutation_target() {
    let temp_dir = tempdir().expect("tempdir");
    let harness = start_server(test_config(
        temp_dir.path().join("store"),
        "loonfs-server-root-mutation",
        "http-root-mutation",
    ))
    .await;

    let namespace = namespace_id("demo");
    harness
        .client
        .create_namespace(&namespace)
        .await
        .expect("create namespace");

    let alone = harness
        .client
        .commit(
            &namespace,
            &CommitRequest {
                commit_id: commit_id("root-alone"),
                message: None,
                content_tokens: Vec::new(),
                operations: vec![FilesystemOperation::CreateDirectory {
                    path: absolute("/"),
                    parents: false,
                }],
            },
        )
        .await
        .expect_err("the root cannot be created");
    match alone {
        ClientError::Api {
            status,
            code,
            details,
            ..
        } => {
            assert_eq!(status, 400);
            assert_eq!(code, ErrorCode::InvalidRequest.as_str());
            let details = details.expect("a failed commit carries details");
            // One operation has one place to fail, so nothing disambiguates it.
            assert_eq!(
                details.operation_index, None,
                "a one-operation request names no position"
            );
            assert_eq!(
                details.commit_id.as_ref().map(CommitId::as_str),
                Some("root-alone")
            );
        }
        other => unreachable!("expected invalid_request, got {other:?}"),
    }

    let in_batch = harness
        .client
        .commit(
            &namespace,
            &CommitRequest {
                commit_id: commit_id("root-in-batch"),
                message: None,
                content_tokens: Vec::new(),
                operations: vec![
                    FilesystemOperation::CreateDirectory {
                        path: absolute(REPORTS_DIR),
                        parents: false,
                    },
                    FilesystemOperation::DeletePath {
                        path: absolute("/"),
                        behavior: DeleteDirectoryBehavior::Recursive,
                        expected_inode_id: None,
                    },
                ],
            },
        )
        .await
        .expect_err("the root cannot be deleted");
    match in_batch {
        ClientError::Api {
            status,
            code,
            details,
            ..
        } => {
            assert_eq!(status, 400);
            assert_eq!(code, ErrorCode::InvalidRequest.as_str());
            let details = details.expect("a failed commit carries details");
            // Planning stops at the root operation, so the batch names its
            // position like it names every other failure's.
            assert_eq!(
                details.operation_index,
                Some(1),
                "the batch names the operation that stopped it"
            );
            assert_eq!(
                details.commit_id.as_ref().map(CommitId::as_str),
                Some("root-in-batch")
            );
        }
        other => unreachable!("expected invalid_request, got {other:?}"),
    }

    // The valid first operation of the rejected batch did not land either.
    assert_eq!(
        harness
            .client
            .namespace_status(&namespace)
            .await
            .expect("status")
            .head_seq,
        ChangeSeq(0)
    );

    // The rule is the planners', so it is answered where every other path
    // rule is: against a namespace that exists. A root mutation aimed at a
    // namespace that does not answers for the namespace instead.
    let unknown = harness
        .client
        .commit(
            &namespace_id("missing"),
            &CommitRequest {
                commit_id: commit_id("root-unknown-namespace"),
                message: None,
                content_tokens: Vec::new(),
                operations: vec![FilesystemOperation::CreateDirectory {
                    path: absolute("/"),
                    parents: false,
                }],
            },
        )
        .await
        .expect_err("the namespace does not exist");
    match unknown {
        ClientError::Api { status, code, .. } => {
            assert_eq!(status, 404);
            assert_eq!(code, ErrorCode::NamespaceNotFound.as_str());
        }
        other => unreachable!("expected namespace_not_found, got {other:?}"),
    }

    harness.server.abort();
}

/// Replay over the wire: the same id with the same batch returns the
/// original receipt, and the same id with a different batch conflicts.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_batch_replays_under_its_commit_id() {
    let temp_dir = tempdir().expect("tempdir");
    let harness = start_server(test_config(
        temp_dir.path().join("store"),
        "loonfs-server-batch-replay",
        "http-commit-replay",
    ))
    .await;

    let namespace = namespace_id("demo");
    harness
        .client
        .create_namespace(&namespace)
        .await
        .expect("create namespace");

    let batch = |ops: Vec<FilesystemOperation>| CommitRequest {
        commit_id: commit_id("replayed-batch"),
        message: Some("two directories".to_owned()),
        content_tokens: Vec::new(),
        operations: ops,
    };
    let operations = vec![
        FilesystemOperation::CreateDirectory {
            path: absolute(REPORTS_DIR),
            parents: false,
        },
        FilesystemOperation::CreateDirectory {
            path: absolute("/reports/2026"),
            parents: false,
        },
    ];

    let first = harness
        .client
        .commit(&namespace, &batch(operations.clone()))
        .await
        .expect("batch commits");
    let replayed = harness
        .client
        .commit(&namespace, &batch(operations.clone()))
        .await
        .expect("identical resubmission replays");
    assert_eq!(replayed, first);
    assert_eq!(
        harness
            .client
            .namespace_status(&namespace)
            .await
            .expect("status")
            .head_seq,
        first.committed_seq,
        "the replay committed nothing new"
    );

    // Dropping the second operation is a different commit under the same
    // id, so the id is spent.
    let conflict = harness
        .client
        .commit(&namespace, &batch(operations[..1].to_vec()))
        .await
        .expect_err("a different batch cannot reuse the id");
    match conflict {
        ClientError::Api { code, .. } => {
            assert_eq!(code, ErrorCode::CommitIdReuseConflict.as_str());
        }
        other => unreachable!("expected commit_id_reuse_conflict, got {other:?}"),
    }

    harness.server.abort();
}

/// One fingerprint domain across transports: a batch committed embedded
/// replays over HTTP under the same commit id, and a different batch under
/// that id conflicts over HTTP just as it would embedded.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_commit_id_used_embedded_replays_over_http() {
    let temp_dir = tempdir().expect("tempdir");
    let store_root = temp_dir.path().join("store");
    let namespace = namespace_id("shared");

    let operations = || {
        vec![
            FilesystemOperation::CreateDirectory {
                path: absolute(REPORTS_DIR),
                parents: false,
            },
            FilesystemOperation::CreateDirectory {
                path: absolute("/reports/2026"),
                parents: false,
            },
            FilesystemOperation::MovePath {
                from_path: absolute("/reports/2026"),
                to_path: absolute("/reports/2025"),
                behavior: DestinationBehavior::NoReplace,
            },
        ]
    };

    // Committed embedded first, then the writer goes away: the served
    // writer acquires its own epoch afterward and finds the receipt.
    let embedded_receipt = {
        let writer = FsWriter::builder(StoreConfig::LocalFs {
            root: store_root.display().to_string(),
            key_prefix: Some("http-cross-transport".to_owned()),
        })
        .writer_id("loonfs-embedded-cross")
        .build()
        .await
        .expect("embedded writer");
        writer
            .create_namespace(&namespace, CreateNamespaceOptions::default())
            .await
            .expect("create namespace");
        let receipt = writer
            .commit(
                &namespace,
                CoreCommitRequest {
                    commit_id: commit_id("crosses-transports"),
                    message: Some("shaped once".to_owned()),
                    operations: operations(),
                },
            )
            .await
            .expect("embedded batch commits");
        writer
            .shutdown()
            .await
            .expect("settle embedded background work");
        receipt
    };

    let harness = start_server(test_config(
        store_root.clone(),
        "loonfs-server-cross",
        "http-cross-transport",
    ))
    .await;

    // The same commit, written in the wire language under the same id.
    let wire_operations = vec![
        FilesystemOperation::CreateDirectory {
            path: absolute(REPORTS_DIR),
            parents: false,
        },
        FilesystemOperation::CreateDirectory {
            path: absolute("/reports/2026"),
            parents: false,
        },
        FilesystemOperation::MovePath {
            from_path: absolute("/reports/2026"),
            to_path: absolute("/reports/2025"),
            behavior: DestinationBehavior::NoReplace,
        },
    ];
    let replayed = harness
        .client
        .commit(
            &namespace,
            &CommitRequest {
                commit_id: commit_id("crosses-transports"),
                message: Some("shaped once".to_owned()),
                content_tokens: Vec::new(),
                operations: wire_operations.clone(),
            },
        )
        .await
        .expect("the embedded commit replays over http");
    assert_eq!(replayed, embedded_receipt);
    assert_eq!(
        harness
            .client
            .namespace_status(&namespace)
            .await
            .expect("status")
            .head_seq,
        embedded_receipt.committed_seq,
        "the cross-transport replay committed nothing new"
    );

    // And the conflict crosses too: a different batch under the spent id
    // fails over HTTP on a receipt the embedded runtime wrote.
    let conflict = harness
        .client
        .commit(
            &namespace,
            &CommitRequest {
                commit_id: commit_id("crosses-transports"),
                message: Some("shaped once".to_owned()),
                content_tokens: Vec::new(),
                operations: wire_operations[..2].to_vec(),
            },
        )
        .await
        .expect_err("a different batch cannot reuse the embedded id");
    match conflict {
        ClientError::Api { code, .. } => {
            assert_eq!(code, ErrorCode::CommitIdReuseConflict.as_str());
        }
        other => unreachable!("expected commit_id_reuse_conflict, got {other:?}"),
    }

    harness.server.abort();
}