githttp-fs 1.15.4

A git-backed content management database served over HTTP
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
// githttp-fs
//
// Git-based Content Management System
// Copyright: 2026, Valerian Saliou <valerian@valeriansaliou.name>
// License: Mozilla Public License v2.0 (MPL v2.0)

//! Integration tests for the file dates the read routes report through
//! `include_updated_at` / `include_created_at` (and the batch route's
//! `include` object), and for the `.dates.json` index that records them.
//!
//! A recorded date is the `committed_at` of the commit that made the change,
//! so every expectation here is read back from the commit list rather than
//! from the clock: two commits landing in the same second are then still
//! told apart by which commit they are, not by when the test ran.

use axum::http::StatusCode;
use serde_json::{json, Value};

use crate::tests::harness::{author, TestServer};

const TENANT: &str = "/docs/acme";

/// The read route's `(updated_at, created_at)` for `path`, both asked for.
async fn file_dates(server: &TestServer, path: &str) -> (Value, Value) {
    let body = server
        .get(&format!(
            "{}/files/{}?include_updated_at=true&include_created_at=true",
            TENANT, path
        ))
        .await
        .expect_status(StatusCode::OK)
        .json();

    (body["updated_at"].clone(), body["created_at"].clone())
}

/// `committed_at` of the latest commit.
async fn head_date(server: &TestServer) -> Value {
    server
        .get(&format!("{}/commits?per_page=1", TENANT))
        .await
        .json()["commits"][0]["committed_at"]
        .clone()
}

/// The repository's HEAD tree, read directly — for asserting on the stored
/// index, which no route exposes.
fn head_tree_holds(server: &TestServer, path: &str) -> bool {
    let repo = git2::Repository::open(server.repo_path("docs", "acme")).expect("no repository");
    let tree = repo
        .head()
        .unwrap()
        .peel_to_commit()
        .unwrap()
        .tree()
        .unwrap();

    tree.get_path(std::path::Path::new(path)).is_ok()
}

#[tokio::test]
async fn dates_are_absent_unless_asked_for() {
    // API.md: "Each key is present only when its parameter is `true`, so a
    // response without them is unchanged."
    let server = TestServer::start().await;

    server.write_file(TENANT, "a.md", "one").await;

    let written = head_date(&server).await;

    for query in ["", "?include_updated_at=false&include_created_at=false"] {
        let body = server
            .get(&format!("{}/files/a.md{}", TENANT, query))
            .await
            .json();

        assert!(body.get("updated_at").is_none(), "{}", query);
        assert!(body.get("created_at").is_none(), "{}", query);
    }

    let updated = server
        .get(&format!("{}/files/a.md?include_updated_at=true", TENANT))
        .await
        .json();

    assert_eq!(updated["updated_at"], written);
    assert!(updated.get("created_at").is_none());

    let created = server
        .get(&format!("{}/files/a.md?include_created_at=true", TENANT))
        .await
        .json();

    assert_eq!(created["created_at"], written);
    assert!(created.get("updated_at").is_none());
}

#[tokio::test]
async fn dates_are_those_of_the_creating_and_the_last_changing_commit() {
    let server = TestServer::start().await;

    server.write_file(TENANT, "docs/a.md", "one").await;

    let created = head_date(&server).await;

    // A sibling's change must leave this file's dates alone.
    server.write_file(TENANT, "docs/b.md", "one").await;
    server.write_file(TENANT, "docs/a.md", "two").await;

    let updated = head_date(&server).await;

    server.write_file(TENANT, "docs/b.md", "two").await;

    assert_eq!(file_dates(&server, "docs/a.md").await, (updated, created));

    // An unchanged write commits nothing, so it records nothing either.
    let before = file_dates(&server, "docs/b.md").await;

    server.write_file(TENANT, "docs/b.md", "two").await;

    assert_eq!(file_dates(&server, "docs/b.md").await, before);
}

#[tokio::test]
async fn created_at_follows_file_and_folder_moves() {
    // API.md: "Moves are followed backward, so a file moved (or moved several
    // times, a folder move included) keeps the date it was first created
    // under its original path." The move itself is the latest change.
    let server = TestServer::start().await;

    server.write_file(TENANT, "a.md", "one").await;

    let created = head_date(&server).await;

    server
        .post(
            &format!("{}/files/a.md/move", TENANT),
            json!({ "author": author(), "destination": "first/a.md" }),
        )
        .await
        .expect_status(StatusCode::OK);

    server
        .post(
            &format!("{}/files/first/move", TENANT),
            json!({
                "author": author(),
                "destination": "second/nested",
                "allow_prefix_path_recurse": true
            }),
        )
        .await
        .expect_status(StatusCode::OK);

    let moved = head_date(&server).await;

    assert_eq!(
        file_dates(&server, "second/nested/a.md").await,
        (moved, created)
    );

    // Nothing is left behind where the file used to be.
    assert!(!head_tree_holds(&server, ".dates.json"));
    assert!(!head_tree_holds(&server, "first"));
}

#[tokio::test]
async fn a_file_created_again_dates_from_its_new_creation() {
    // API.md: "A file deleted and later created again at the same path dates
    // from that later creation."
    let server = TestServer::start().await;

    server.write_file(TENANT, "keep.md", "keep").await;
    server.write_file(TENANT, "b.md", "one").await;

    server
        .delete(
            &format!("{}/files/b.md", TENANT),
            json!({ "author": author() }),
        )
        .await
        .expect_status(StatusCode::OK);

    server.write_file(TENANT, "b.md", "again").await;

    let recreated = head_date(&server).await;

    assert_eq!(
        file_dates(&server, "b.md").await,
        (recreated.clone(), recreated)
    );
}

#[tokio::test]
async fn deleting_a_folder_last_file_leaves_no_index_behind() {
    // An emptied index is removed, so it never keeps a folder alive.
    let server = TestServer::start().await;

    server.write_file(TENANT, "keep.md", "keep").await;
    server.write_file(TENANT, "docs/only.md", "x").await;

    assert!(head_tree_holds(&server, "docs/.dates.json"));

    server
        .delete(
            &format!("{}/files/docs/only.md", TENANT),
            json!({ "author": author() }),
        )
        .await
        .expect_status(StatusCode::OK);

    assert!(!head_tree_holds(&server, "docs"));

    let listing = server.get(&format!("{}/files", TENANT)).await.json();
    let names: Vec<&str> = listing["files"]
        .as_array()
        .unwrap()
        .iter()
        .map(|node| node["name"].as_str().unwrap())
        .collect();

    assert_eq!(names, vec!["keep.md"]);
}

#[tokio::test]
async fn dates_never_recorded_read_as_null() {
    // A file committed without passing through this server (a store written
    // before the index existed) has no entry: its dates are unknown, so a
    // requested date is `null` rather than absent or guessed.
    use crate::tests::fixture::{at, commit_files_at};

    let server = TestServer::start().await;

    server.write_file(TENANT, "seed.md", "seed").await;

    commit_files_at(
        &server.repo_path("docs", "acme"),
        at("2020-01-01T00:00:00Z"),
        "add legacy",
        &[("legacy.md", b"old")],
    );

    let body = server
        .get(&format!(
            "{}/files/legacy.md?include_updated_at=true&include_created_at=true",
            TENANT
        ))
        .await
        .json();

    assert!(body["updated_at"].is_null());
    assert!(body["created_at"].is_null());
    assert!(body.get("updated_at").is_some() && body.get("created_at").is_some());

    // Its first change through the server records when that happened, but
    // the creation it never saw stays unknown.
    server.write_file(TENANT, "legacy.md", "new").await;

    let updated = head_date(&server).await;

    assert_eq!(
        file_dates(&server, "legacy.md").await,
        (updated, Value::Null)
    );
}

#[tokio::test]
async fn a_revert_stamps_its_own_changes_instead_of_restoring_old_dates() {
    let server = TestServer::start().await;

    server.write_file(TENANT, "a.md", "one").await;

    let created = head_date(&server).await;

    server.write_file(TENANT, "a.md", "two").await;

    let update_sha = server
        .get(&format!("{}/commits?per_page=1", TENANT))
        .await
        .json()["commits"][0]["sha"]
        .as_str()
        .unwrap()
        .to_string();

    server
        .post(
            &format!("{}/commits/{}/revert", TENANT, update_sha),
            json!({ "author": author() }),
        )
        .await
        .expect_status(StatusCode::OK);

    let reverted = head_date(&server).await;

    assert_eq!(
        server.read_file(TENANT, "a.md").await.as_deref(),
        Some("one")
    );
    assert_eq!(file_dates(&server, "a.md").await, (reverted, created));
}

#[tokio::test]
async fn the_dates_index_is_invisible_to_every_files_route_and_commit_view() {
    let server = TestServer::start().await;

    server.write_file(TENANT, "a.md", "one").await;

    assert!(head_tree_holds(&server, ".dates.json"));

    let listing = server
        .get(&format!("{}/files?include_hidden_files=true", TENANT))
        .await
        .json();

    assert_eq!(listing["files"].as_array().unwrap().len(), 1);

    let count = server
        .get(&format!("{}/count/files?include_hidden_files=true", TENANT))
        .await
        .json();

    assert_eq!(count["files"], 1);

    server
        .get(&format!("{}/files/.dates.json", TENANT))
        .await
        .expect_status(StatusCode::NOT_FOUND);

    server
        .head(&format!("{}/files/.dates.json", TENANT))
        .await
        .expect_status(StatusCode::NOT_FOUND);

    server
        .put(
            &format!("{}/files/.dates.json", TENANT),
            json!({ "author": author(), "content": "{}" }),
        )
        .await
        .expect_status(StatusCode::BAD_REQUEST);

    server
        .post(
            &format!("{}/files/a.md/move", TENANT),
            json!({ "author": author(), "destination": ".dates.json" }),
        )
        .await
        .expect_status(StatusCode::BAD_REQUEST);

    // The commit that wrote `a.md` also wrote the index; its detail and its
    // statistics report the file alone.
    let sha = server
        .get(&format!(
            "{}/commits?per_page=1&include_statistics=true",
            TENANT
        ))
        .await
        .json()["commits"][0]
        .clone();

    assert_eq!(sha["statistics"]["files_changed"], 1);

    let detail = server
        .get(&format!(
            "{}/commits/{}",
            TENANT,
            sha["sha"].as_str().unwrap()
        ))
        .await
        .json();

    let paths: Vec<&str> = detail["files"]
        .as_array()
        .unwrap()
        .iter()
        .map(|file| file["path"].as_str().unwrap())
        .collect();

    assert_eq!(paths, vec!["a.md"]);
    assert_eq!(detail["statistics"]["files_changed"], 1);
}

#[tokio::test]
async fn asking_for_dates_does_not_change_a_missing_file_answer() {
    let server = TestServer::start().await;

    server.write_file(TENANT, "a.md", "one").await;

    server
        .get(&format!(
            "{}/files/missing.md?include_updated_at=true&include_created_at=true",
            TENANT
        ))
        .await
        .expect_status(StatusCode::NOT_FOUND);

    server
        .get(&format!("{}/files/a.md?include_created_at=yes", TENANT))
        .await
        .expect_status(StatusCode::BAD_REQUEST);
}

/// Asserts `keys` appear in this order in a raw JSON body — a parsed `Value`
/// sorts its keys, so the order can only be checked on the text.
fn assert_key_order(text: &str, keys: &[&str]) {
    let offsets: Vec<usize> = keys
        .iter()
        .map(|key| {
            text.find(&format!("\"{}\"", key))
                .unwrap_or_else(|| panic!("{} missing: {}", key, text))
        })
        .collect();

    assert!(offsets.windows(2).all(|pair| pair[0] < pair[1]), "{}", text);
}

#[tokio::test]
async fn dates_come_last_in_the_read_response() {
    let server = TestServer::start().await;

    server.write_file(TENANT, "a.md", "one").await;

    let text = server
        .get(&format!(
            "{}/files/a.md?include_updated_at=true&include_created_at=true",
            TENANT
        ))
        .await
        .text;

    assert_key_order(
        &text,
        &["path", "content", "position", "updated_at", "created_at"],
    );
}

#[tokio::test]
async fn a_batch_read_dates_every_found_file_like_the_single_read() {
    // API.md: the `include` booleans "carry the exact meaning of the single
    // read route's `include_updated_at` / `include_created_at` query
    // parameters", apply to every file found, and a `null` slot stays `null`.
    let server = TestServer::start().await;

    server.write_file(TENANT, "a.md", "one").await;
    server.write_file(TENANT, "docs/b.md", "one").await;
    server.write_file(TENANT, "a.md", "two").await;

    let body = server
        .post(
            &format!("{}/batch/files/read", TENANT),
            json!({
                "files": ["a.md", "missing.md", "docs/b.md"],
                "include": { "updated_at": true, "created_at": true }
            }),
        )
        .await
        .expect_status(StatusCode::OK)
        .json();

    let files = body["files"].as_array().expect("files is not an array");

    for (slot, path) in [(0, "a.md"), (2, "docs/b.md")] {
        let (updated, created) = file_dates(&server, path).await;

        assert_eq!(files[slot]["updated_at"], updated, "{}", path);
        assert_eq!(files[slot]["created_at"], created, "{}", path);
    }

    assert!(files[1].is_null());
}

#[tokio::test]
async fn a_batch_read_carries_only_the_dates_asked_for() {
    let server = TestServer::start().await;

    server.write_file(TENANT, "a.md", "one").await;

    let read = |include: Value| async move {
        let mut body = json!({ "files": ["a.md"] });

        if !include.is_null() {
            body["include"] = include;
        }

        body
    };

    let plain = server
        .post(
            &format!("{}/batch/files/read", TENANT),
            read(Value::Null).await,
        )
        .await
        .json();

    assert!(plain["files"][0].get("updated_at").is_none());
    assert!(plain["files"][0].get("created_at").is_none());

    let updated = server
        .post(
            &format!("{}/batch/files/read", TENANT),
            read(json!({ "updated_at": true })).await,
        )
        .await
        .json();

    assert!(updated["files"][0]["updated_at"].is_string());
    assert!(updated["files"][0].get("created_at").is_none());

    let created = server
        .post(
            &format!("{}/batch/files/read", TENANT),
            read(json!({ "created_at": true })).await,
        )
        .await
        .json();

    assert!(created["files"][0]["created_at"].is_string());
    assert!(created["files"][0].get("updated_at").is_none());

    let text = server
        .post(
            &format!("{}/batch/files/read", TENANT),
            read(json!({ "updated_at": true, "created_at": true })).await,
        )
        .await
        .text;

    assert_key_order(&text, &["path", "content", "updated_at", "created_at"]);
}