lora-server 0.4.0

HTTP server binary for LoraDB, exposing a Cypher-over-HTTP API.
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
//! HTTP tests for the admin surface.
//!
//! The admin surface is opt-in: it only exists when the caller constructs an
//! `AdminConfig` and passes it to `build_app_with_admin`. Tests confirm
//! both that the happy path works and that the admin routes are absent when
//! no admin config is supplied.

use std::sync::Arc;

use axum::{
    body::Body,
    http::{Request, StatusCode},
};
use http_body_util::BodyExt;
use lora_database::{Database, SnapshotAdmin, SyncMode, WalAdmin, WalConfig};
use tower::ServiceExt;

use lora_server::{build_app, build_app_with_admin, AdminConfig, SnapshotAdminConfig};

fn tempdir(tag: &str) -> std::path::PathBuf {
    let mut dir = std::env::temp_dir();
    dir.push(format!(
        "lora-admin-test-{}-{}-{}",
        tag,
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::create_dir_all(&dir).unwrap();
    dir
}

#[tokio::test]
async fn admin_routes_absent_without_config() {
    let db = Arc::new(Database::in_memory());
    let app = build_app(db);

    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/admin/snapshot/save")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn admin_save_and_load_roundtrip() {
    let dir = tempdir("save_load");
    let snapshot_path = dir.join("snap.bin");

    let db = Arc::new(Database::in_memory());
    db.execute(
        "CREATE (:Person {name: 'alice'})",
        Some(lora_database::ExecuteOptions {
            format: lora_database::ResultFormat::RowArrays,
        }),
    )
    .unwrap();

    let admin = AdminConfig {
        snapshot: Some(SnapshotAdminConfig {
            path: snapshot_path.clone(),
            admin: Arc::clone(&db) as Arc<dyn SnapshotAdmin>,
        }),
        wal: None,
    };
    let app = build_app_with_admin(Arc::clone(&db), Some(admin));

    // Save.
    let response = app
        .clone()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/admin/snapshot/save")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(json["nodeCount"], 1);
    assert_eq!(json["walLsn"], serde_json::Value::Null);
    assert!(snapshot_path.exists());

    // Mutate — adds a second node so we can verify the next load reverts it.
    db.execute(
        "CREATE (:Person {name: 'bob'})",
        Some(lora_database::ExecuteOptions {
            format: lora_database::ResultFormat::RowArrays,
        }),
    )
    .unwrap();
    assert_eq!(db.node_count(), 2);

    // Load.
    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/admin/snapshot/load")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(json["nodeCount"], 1);
    assert_eq!(db.node_count(), 1);

    let _ = std::fs::remove_dir_all(&dir);
}

#[tokio::test]
async fn admin_save_honours_path_override() {
    let dir = tempdir("path_override");
    let default_path = dir.join("default.bin");
    let override_path = dir.join("override.bin");

    let db = Arc::new(Database::in_memory());
    db.execute(
        "CREATE (:N)",
        Some(lora_database::ExecuteOptions {
            format: lora_database::ResultFormat::RowArrays,
        }),
    )
    .unwrap();

    let admin = AdminConfig {
        snapshot: Some(SnapshotAdminConfig {
            path: default_path.clone(),
            admin: Arc::clone(&db) as Arc<dyn SnapshotAdmin>,
        }),
        wal: None,
    };
    let app = build_app_with_admin(Arc::clone(&db), Some(admin));

    // Save with an explicit path override — default_path must NOT be written.
    let body = serde_json::json!({ "path": override_path.to_str().unwrap() }).to_string();
    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/admin/snapshot/save")
                .header("content-type", "application/json")
                .body(Body::from(body))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(
        json["path"].as_str().unwrap(),
        override_path.display().to_string()
    );
    assert!(override_path.exists());
    assert!(!default_path.exists());

    let _ = std::fs::remove_dir_all(&dir);
}

#[tokio::test]
async fn admin_load_reports_error_for_missing_file() {
    let dir = tempdir("missing");
    let snapshot_path = dir.join("nope.bin");

    let db = Arc::new(Database::in_memory());
    let admin = AdminConfig {
        snapshot: Some(SnapshotAdminConfig {
            path: snapshot_path,
            admin: Arc::clone(&db) as Arc<dyn SnapshotAdmin>,
        }),
        wal: None,
    };
    let app = build_app_with_admin(Arc::clone(&db), Some(admin));

    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/admin/snapshot/load")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);

    let _ = std::fs::remove_dir_all(&dir);
}

// ---------------------------------------------------------------------------
// WAL admin endpoints
// ---------------------------------------------------------------------------

fn enabled(wal_dir: &std::path::Path) -> WalConfig {
    WalConfig::Enabled {
        dir: wal_dir.to_path_buf(),
        sync_mode: SyncMode::PerCommit,
        segment_target_bytes: 8 * 1024 * 1024,
    }
}

#[tokio::test]
async fn wal_routes_absent_without_wal_admin() {
    // Snapshot-only admin config: WAL endpoints must not be mounted
    // even if a WAL is available. Operators have to opt in by setting
    // `AdminConfig.wal = Some(...)`.
    let dir = tempdir("wal-absent");
    let snapshot_path = dir.join("snap.bin");

    let db = Arc::new(Database::in_memory());
    let admin =
        AdminConfig::snapshot_only(snapshot_path, Arc::clone(&db) as Arc<dyn SnapshotAdmin>);
    let app = build_app_with_admin(Arc::clone(&db), Some(admin));

    for path in [
        "/admin/checkpoint",
        "/admin/wal/status",
        "/admin/wal/truncate",
    ] {
        let response = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri(path)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            response.status(),
            StatusCode::NOT_FOUND,
            "{path} should not be mounted without AdminConfig.wal"
        );
    }

    let _ = std::fs::remove_dir_all(&dir);
}

#[tokio::test]
async fn wal_status_and_checkpoint_endpoints() {
    let dir = tempdir("wal-status");
    let wal_dir = dir.join("wal");
    std::fs::create_dir_all(&wal_dir).unwrap();
    let snapshot_path = dir.join("snap.bin");

    let db = Arc::new(Database::open_with_wal(enabled(&wal_dir)).unwrap());
    db.execute(
        "CREATE (:N {id: 1})",
        Some(lora_database::ExecuteOptions {
            format: lora_database::ResultFormat::RowArrays,
        }),
    )
    .unwrap();
    db.execute(
        "CREATE (:N {id: 2})",
        Some(lora_database::ExecuteOptions {
            format: lora_database::ResultFormat::RowArrays,
        }),
    )
    .unwrap();

    let admin = AdminConfig {
        snapshot: Some(SnapshotAdminConfig {
            path: snapshot_path.clone(),
            admin: Arc::clone(&db) as Arc<dyn SnapshotAdmin>,
        }),
        wal: Some(Arc::clone(&db) as Arc<dyn WalAdmin>),
    };
    let app = build_app_with_admin(Arc::clone(&db), Some(admin));

    // Status reflects committed traffic.
    let response = app
        .clone()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/admin/wal/status")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    let durable = json["durableLsn"].as_u64().unwrap();
    assert!(
        durable > 0,
        "durableLsn should advance with committed writes"
    );

    // Checkpoint writes a snapshot at the configured path with a
    // non-null walLsn.
    let response = app
        .clone()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/admin/checkpoint")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(json["nodeCount"], 2);
    assert!(json["walLsn"].is_u64(), "checkpoint must stamp walLsn");
    assert!(snapshot_path.exists());

    // wal/truncate without a body uses the durable LSN as fence and
    // returns 204.
    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/admin/wal/truncate")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::NO_CONTENT);

    let _ = std::fs::remove_dir_all(&dir);
}

#[tokio::test]
async fn wal_admin_routes_mount_without_snapshot_path() {
    // WAL-only admin: only --wal-dir was set, no --snapshot-path.
    // /admin/wal/{status,truncate} must still mount;
    // /admin/snapshot/{save,load} must not.
    let dir = tempdir("wal-only");
    let wal_dir = dir.join("wal");
    std::fs::create_dir_all(&wal_dir).unwrap();

    let db = Arc::new(Database::open_with_wal(enabled(&wal_dir)).unwrap());
    db.execute(
        "CREATE (:N {id: 1})",
        Some(lora_database::ExecuteOptions {
            format: lora_database::ResultFormat::RowArrays,
        }),
    )
    .unwrap();

    let admin = AdminConfig::wal_only(Arc::clone(&db) as Arc<dyn WalAdmin>);
    let app = build_app_with_admin(Arc::clone(&db), Some(admin));

    // wal/status mounts.
    let response = app
        .clone()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/admin/wal/status")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);

    // wal/truncate mounts.
    let response = app
        .clone()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/admin/wal/truncate")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::NO_CONTENT);

    // /admin/checkpoint without a configured default path AND without
    // a body path → 400 with a hint.
    let response = app
        .clone()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/admin/checkpoint")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    assert!(
        json["error"].as_str().unwrap().contains("--snapshot-path"),
        "error should mention --snapshot-path or `path` body"
    );

    // /admin/checkpoint WITH a body path works.
    let body = serde_json::json!({ "path": dir.join("ckpt.bin").to_str().unwrap() }).to_string();
    let response = app
        .clone()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/admin/checkpoint")
                .header("content-type", "application/json")
                .body(Body::from(body))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);

    // Snapshot save/load routes must NOT be mounted.
    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/admin/snapshot/save")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::NOT_FOUND);

    let _ = std::fs::remove_dir_all(&dir);
}

#[tokio::test]
async fn wal_status_errors_when_wal_admin_is_disconnected() {
    // Edge case: an `AdminConfig.wal` that points at a database
    // without a live WAL (e.g. WalConfig::Disabled). The endpoint
    // surfaces the trait error as a 500 with a useful message
    // rather than panicking.
    let dir = tempdir("wal-err");
    let snapshot_path = dir.join("snap.bin");

    let db = Arc::new(Database::in_memory()); // no WAL attached
    let admin = AdminConfig {
        snapshot: Some(SnapshotAdminConfig {
            path: snapshot_path,
            admin: Arc::clone(&db) as Arc<dyn SnapshotAdmin>,
        }),
        wal: Some(Arc::clone(&db) as Arc<dyn WalAdmin>),
    };
    let app = build_app_with_admin(Arc::clone(&db), Some(admin));

    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/admin/wal/status")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    assert!(json["error"].as_str().unwrap().contains("WAL"));

    let _ = std::fs::remove_dir_all(&dir);
}