logdive-api 0.3.0

Read-only HTTP API server for a logdive index
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
//! End-to-end integration tests for the HTTP API.
//!
//! These tests build a real [`Router`] via [`logdive_api::router::build_router`]
//! against a tempfile-backed SQLite database, then exercise it via
//! [`tower::ServiceExt::oneshot`] — which bypasses the network stack while
//! still running the full extractor → handler → `IntoResponse` pipeline.
//!
//! Coverage spans the two endpoints' happy paths, their user-fault error
//! paths (400), and the default unknown-route behavior (404). Server-fault
//! paths (500) are exercised by the unit tests inside `error.rs`; surfacing
//! them through a live request-response cycle would require deliberately
//! corrupting the DB mid-flight, which adds noise without meaningful
//! additional coverage.

use std::path::PathBuf;

use axum::{
    body::Body,
    http::{HeaderValue, Request, StatusCode},
};
use http_body_util::BodyExt;
use serde_json::Value;
use tempfile::TempDir;
use tower::ServiceExt; // for `.oneshot`

use logdive_api::{router::build_router, state::AppState};
use logdive_core::{Indexer, LogEntry};

// ---------------------------------------------------------------------------
// Fixtures
// ---------------------------------------------------------------------------

/// Create an empty, schema-initialized index in a fresh temp directory.
///
/// Returns the `TempDir` (must be kept alive for the lifetime of the test
/// to prevent early cleanup) and the DB path within it.
fn empty_db() -> (TempDir, PathBuf) {
    let dir = tempfile::tempdir().expect("tempdir");
    let db = dir.path().join("index.db");
    // Touch the DB file and create the schema via the core writable opener.
    let _ = Indexer::open(&db).expect("init empty db");
    (dir, db)
}

/// Create a populated index with three entries spanning two tags and two
/// levels, suitable for exercising /query and /stats against real data.
fn populated_db() -> (TempDir, PathBuf) {
    let (dir, db) = empty_db();
    let mut idx = Indexer::open(&db).expect("reopen for populate");
    idx.insert_batch(&[
        entry(
            "2026-04-20T10:00:00Z",
            "error",
            "payment failed",
            Some("api"),
        ),
        entry(
            "2026-04-20T11:00:00Z",
            "info",
            "health check ok",
            Some("api"),
        ),
        entry("2026-04-20T12:00:00Z", "error", "database timeout", None),
    ])
    .expect("insert fixtures");
    (dir, db)
}

fn entry(ts: &str, level: &str, message: &str, tag: Option<&str>) -> LogEntry {
    let tag_part = tag.map(|t| format!(r#","tag":"{t}""#)).unwrap_or_default();
    let raw =
        format!(r#"{{"timestamp":"{ts}","level":"{level}","message":"{message}"{tag_part}}}"#);
    let mut e = LogEntry::new(raw);
    e.timestamp = Some(ts.to_string());
    e.level = Some(level.to_string());
    e.message = Some(message.to_string());
    e.tag = tag.map(|t| t.to_string());
    e
}

fn app(db: PathBuf) -> axum::Router {
    build_router(AppState::new(db), vec![])
}

async fn body_bytes(resp: axum::response::Response) -> Vec<u8> {
    resp.into_body()
        .collect()
        .await
        .expect("collect body")
        .to_bytes()
        .to_vec()
}

async fn body_text(resp: axum::response::Response) -> String {
    String::from_utf8(body_bytes(resp).await).expect("utf-8 body")
}

async fn body_json(resp: axum::response::Response) -> Value {
    let text = body_text(resp).await;
    serde_json::from_str(&text).unwrap_or_else(|e| panic!("body is not JSON: {e}; body=`{text}`"))
}

/// Parse an NDJSON body into a `Vec<Value>`. Empty bodies yield an empty vec.
fn parse_ndjson(text: &str) -> Vec<Value> {
    text.lines()
        .filter(|l| !l.is_empty())
        .map(|l| serde_json::from_str::<Value>(l).expect("each NDJSON line is valid JSON"))
        .collect()
}

// ---------------------------------------------------------------------------
// GET /stats
// ---------------------------------------------------------------------------

#[tokio::test]
async fn stats_on_populated_db_returns_expected_shape() {
    let (_dir, db) = populated_db();
    let router = app(db.clone());

    let resp = router
        .oneshot(
            Request::builder()
                .uri("/stats")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("oneshot");

    assert_eq!(resp.status(), StatusCode::OK);
    let content_type = resp
        .headers()
        .get(axum::http::header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or_default()
        .to_string();
    assert!(content_type.starts_with("application/json"));

    let v = body_json(resp).await;
    assert_eq!(v["entries"], 3);
    assert_eq!(v["min_timestamp"], "2026-04-20T10:00:00Z");
    assert_eq!(v["max_timestamp"], "2026-04-20T12:00:00Z");

    // Tags: null (untagged row) first, then "api". Clients get the raw
    // core ordering; no "(untagged)" rewriting at this layer.
    let tags = v["tags"].as_array().expect("tags is array");
    assert_eq!(tags.len(), 2);
    assert!(tags[0].is_null());
    assert_eq!(tags[1], "api");

    assert_eq!(v["db_path"], db.display().to_string());
    assert!(v["db_size_bytes"].as_u64().unwrap() > 0);
}

#[tokio::test]
async fn stats_on_empty_db_returns_zeroed_values() {
    let (_dir, db) = empty_db();
    let router = app(db);

    let resp = router
        .oneshot(
            Request::builder()
                .uri("/stats")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("oneshot");

    assert_eq!(resp.status(), StatusCode::OK);
    let v = body_json(resp).await;
    assert_eq!(v["entries"], 0);
    assert!(v["min_timestamp"].is_null());
    assert!(v["max_timestamp"].is_null());
    assert_eq!(v["tags"].as_array().unwrap().len(), 0);
}

// ---------------------------------------------------------------------------
// GET /query
// ---------------------------------------------------------------------------

#[tokio::test]
async fn query_with_matching_expression_returns_ndjson() {
    let (_dir, db) = populated_db();
    let router = app(db);

    let resp = router
        .oneshot(
            Request::builder()
                // level=error matches two of the three fixture rows.
                .uri("/query?q=level%3Derror")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("oneshot");

    assert_eq!(resp.status(), StatusCode::OK);
    let ct = resp
        .headers()
        .get(axum::http::header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or_default()
        .to_string();
    assert_eq!(ct, "application/x-ndjson");

    let text = body_text(resp).await;
    let rows = parse_ndjson(&text);
    assert_eq!(rows.len(), 2);
    assert!(rows.iter().all(|r| r["level"] == "error"));
}

#[tokio::test]
async fn query_with_and_expression_narrows_results() {
    let (_dir, db) = populated_db();
    let router = app(db);

    let resp = router
        .oneshot(
            Request::builder()
                // level=error AND tag=api → one row
                .uri("/query?q=level%3Derror+AND+tag%3Dapi")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("oneshot");

    assert_eq!(resp.status(), StatusCode::OK);
    let rows = parse_ndjson(&body_text(resp).await);
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0]["message"], "payment failed");
}

#[tokio::test]
async fn query_with_or_expression_returns_union() {
    // OR is fully supported in v0.2.0. Both error rows and the info row
    // should be returned.
    let (_dir, db) = populated_db();
    let router = app(db);

    let resp = router
        .oneshot(
            Request::builder()
                // level=error OR level=info → all three fixture rows
                .uri("/query?q=level%3Derror+OR+level%3Dinfo")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("oneshot");

    assert_eq!(resp.status(), StatusCode::OK);
    let rows = parse_ndjson(&body_text(resp).await);
    assert_eq!(rows.len(), 3);
}

#[tokio::test]
async fn query_missing_q_parameter_returns_400() {
    let (_dir, db) = populated_db();
    let router = app(db);

    let resp = router
        .oneshot(
            Request::builder()
                .uri("/query")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("oneshot");

    assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    let v = body_json(resp).await;
    let msg = v["error"].as_str().unwrap_or_default();
    assert!(msg.contains('q'), "error message should mention `q`: {msg}");
}

#[tokio::test]
async fn query_empty_q_parameter_returns_400() {
    let (_dir, db) = populated_db();
    let router = app(db);

    let resp = router
        .oneshot(
            Request::builder()
                .uri("/query?q=")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("oneshot");

    assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}

#[tokio::test]
async fn query_malformed_expression_returns_400() {
    let (_dir, db) = populated_db();
    let router = app(db);

    // A syntactically broken query: `level =` has no value after the
    // operator and is rejected by the parser regardless of grammar version.
    let resp = router
        .oneshot(
            Request::builder()
                .uri("/query?q=level+%3D")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("oneshot");

    assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    let v = body_json(resp).await;
    assert!(!v["error"].as_str().unwrap_or_default().is_empty());
}

#[tokio::test]
async fn query_with_zero_results_returns_empty_ndjson_body() {
    let (_dir, db) = populated_db();
    let router = app(db);

    let resp = router
        .oneshot(
            Request::builder()
                .uri("/query?q=level%3Dnonsense")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("oneshot");

    assert_eq!(resp.status(), StatusCode::OK);
    let text = body_text(resp).await;
    // Empty body → zero NDJSON lines; still a successful response.
    assert!(text.is_empty() || text == "\n");
    assert_eq!(parse_ndjson(&text).len(), 0);
}

#[tokio::test]
async fn query_with_limit_zero_returns_all_matches_unlimited() {
    let (_dir, db) = populated_db();
    let router = app(db);

    let resp = router
        .oneshot(
            Request::builder()
                // Match everything via a "since" clause far enough in the past.
                .uri("/query?q=since+2020-01-01&limit=0")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("oneshot");

    assert_eq!(resp.status(), StatusCode::OK);
    let rows = parse_ndjson(&body_text(resp).await);
    assert_eq!(rows.len(), 3);
}

#[tokio::test]
async fn query_respects_explicit_limit() {
    let (_dir, db) = populated_db();
    let router = app(db);

    let resp = router
        .oneshot(
            Request::builder()
                .uri("/query?q=since+2020-01-01&limit=1")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("oneshot");

    assert_eq!(resp.status(), StatusCode::OK);
    let rows = parse_ndjson(&body_text(resp).await);
    assert_eq!(rows.len(), 1);
    // Default ordering is newest-first — expect the 12:00 row.
    assert_eq!(rows[0]["timestamp"], "2026-04-20T12:00:00Z");
}

// ---------------------------------------------------------------------------
// Routing
// ---------------------------------------------------------------------------

#[tokio::test]
async fn unknown_route_returns_404() {
    let (_dir, db) = populated_db();
    let router = app(db);

    let resp = router
        .oneshot(
            Request::builder()
                .uri("/no-such-endpoint")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("oneshot");

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

#[tokio::test]
async fn post_to_query_endpoint_returns_405() {
    // GET-only: Axum rejects other methods with 405 Method Not Allowed.
    let (_dir, db) = populated_db();
    let router = app(db);

    let resp = router
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/query?q=level%3Derror")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("oneshot");

    assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
}

// ---------------------------------------------------------------------------
// Additional coverage (H2)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn query_limit_larger_than_match_count_returns_all_matches() {
    // limit=100 on a 3-row DB must return all 3 rows — the limit is a cap,
    // not an exact count.
    let (_dir, db) = populated_db();
    let router = app(db);

    let resp = router
        .oneshot(
            Request::builder()
                .uri("/query?q=since+2020-01-01&limit=100")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("oneshot");

    assert_eq!(resp.status(), StatusCode::OK);
    let rows = parse_ndjson(&body_text(resp).await);
    assert_eq!(rows.len(), 3, "limit > count must return all matching rows");
}

#[tokio::test]
async fn query_with_contains_operator_returns_substring_match() {
    let (_dir, db) = populated_db();
    let router = app(db);

    // "payment failed" contains "failed"; "health check ok" does not.
    let resp = router
        .oneshot(
            Request::builder()
                .uri("/query?q=message+contains+%22failed%22")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("oneshot");

    assert_eq!(resp.status(), StatusCode::OK);
    let rows = parse_ndjson(&body_text(resp).await);
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0]["message"], "payment failed");
}

#[tokio::test]
async fn query_with_since_time_range_filters_by_timestamp() {
    // Fixture rows: 10:00, 11:00, 12:00. since 11:00 must return the two
    // rows at 11:00 and 12:00 (the boundary is inclusive).
    let (_dir, db) = populated_db();
    let router = app(db);

    let resp = router
        .oneshot(
            Request::builder()
                .uri("/query?q=since+2026-04-20T11%3A00%3A00Z")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("oneshot");

    assert_eq!(resp.status(), StatusCode::OK);
    let rows = parse_ndjson(&body_text(resp).await);
    assert_eq!(
        rows.len(),
        2,
        "since boundary is inclusive; 2 rows expected"
    );
}

#[tokio::test]
async fn options_preflight_with_wildcard_cors_returns_acao_star() {
    // When the router has wildcard CORS enabled, an OPTIONS preflight must
    // receive an Access-Control-Allow-Origin: * header.
    let (_dir, db) = populated_db();
    let state = logdive_api::state::AppState::new(db);
    let router = logdive_api::router::build_router(state, vec![HeaderValue::from_static("*")]);

    let resp = router
        .oneshot(
            Request::builder()
                .method("OPTIONS")
                .uri("/query")
                .header("Origin", "https://example.com")
                .header("Access-Control-Request-Method", "GET")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("oneshot");

    let acao = resp
        .headers()
        .get("access-control-allow-origin")
        .and_then(|v| v.to_str().ok());
    assert_eq!(
        acao,
        Some("*"),
        "wildcard CORS preflight must return ACAO: *"
    );
}

#[tokio::test]
async fn query_response_entries_include_raw_field() {
    // Each NDJSON row must carry the `raw` field so clients can reproduce
    // the original log line without loss.
    let (_dir, db) = populated_db();
    let router = app(db);

    let resp = router
        .oneshot(
            Request::builder()
                .uri("/query?q=level%3Derror&limit=1")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("oneshot");

    assert_eq!(resp.status(), StatusCode::OK);
    let rows = parse_ndjson(&body_text(resp).await);
    assert_eq!(rows.len(), 1);
    assert!(
        rows[0]["raw"].is_string(),
        "each response entry must include the `raw` field"
    );
    assert!(
        !rows[0]["raw"].as_str().unwrap().is_empty(),
        "`raw` field must be non-empty"
    );
}

// ---------------------------------------------------------------------------
// GET /query — pagination (?offset=)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn query_with_offset_skips_leading_rows() {
    // 3-row fixture, newest-first: 12:00, 11:00, 10:00.
    // offset=1 skips the 12:00 row and returns the remaining two.
    let (_dir, db) = populated_db();
    let router = app(db);

    let resp = router
        .oneshot(
            Request::builder()
                .uri("/query?q=since+2020-01-01&offset=1")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("oneshot");

    assert_eq!(resp.status(), StatusCode::OK);
    let rows = parse_ndjson(&body_text(resp).await);
    assert_eq!(rows.len(), 2, "offset=1 must skip the first row");
    assert_eq!(
        rows[0]["timestamp"], "2026-04-20T11:00:00Z",
        "first returned row after offset must be the second newest"
    );
}

#[tokio::test]
async fn query_with_limit_and_offset_returns_correct_page() {
    // offset=1&limit=1 on 3 rows: skip the 12:00 row, return only 11:00.
    let (_dir, db) = populated_db();
    let router = app(db);

    let resp = router
        .oneshot(
            Request::builder()
                .uri("/query?q=since+2020-01-01&limit=1&offset=1")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("oneshot");

    assert_eq!(resp.status(), StatusCode::OK);
    let rows = parse_ndjson(&body_text(resp).await);
    assert_eq!(
        rows.len(),
        1,
        "limit=1&offset=1 must return exactly one row"
    );
    assert_eq!(rows[0]["timestamp"], "2026-04-20T11:00:00Z");
}

#[tokio::test]
async fn query_with_offset_beyond_result_set_returns_empty() {
    let (_dir, db) = populated_db();
    let router = app(db);

    let resp = router
        .oneshot(
            Request::builder()
                .uri("/query?q=since+2020-01-01&offset=100")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("oneshot");

    assert_eq!(resp.status(), StatusCode::OK);
    let rows = parse_ndjson(&body_text(resp).await);
    assert_eq!(
        rows.len(),
        0,
        "offset past end of result set must return empty"
    );
}