logdive-api 0.2.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
//! 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::{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);
}