hprof-analyzer 0.2.0

Fast, low-memory Java HPROF heap-dump analyzer with Eclipse MAT-parity reports (System Overview, Leak Suspects, Top Consumers).
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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
//! Binary-level integration tests for the `server` subcommand.
//!
//! Each test starts a fresh server process on a free OS-assigned port, makes
//! real HTTP requests via `curl`, asserts on responses, then kills the process.
//! All tests are gated on the philosophers fixture being fully hydrated (≥1024
//! bytes); when the fixture is absent (unhydrated LFS pointer) the test returns
//! immediately, matching the pattern in `cli_query.rs`.
//!
//! Tests that require a fully-analysed server (those calling `wait_for_ready`)
//! share a single long-lived server process via `READY_SERVER`.  This cuts the
//! number of concurrent analysis jobs from ~12 down to 1, eliminating the
//! "server did not reach ready" timeouts that occur under parallel test load.

use std::process::{Child, Command, Stdio};
use std::sync::OnceLock;

const BIN: &str = env!("CARGO_BIN_EXE_hprof-analyzer");

/// Locate the committed philosophers dump, or `None` when it is an unhydrated
/// LFS pointer (so CI without LFS still passes).
fn philosophers() -> Option<String> {
    let p = format!(
        "{}/tests/fixtures/dump_4_philosophers.hprof",
        env!("CARGO_MANIFEST_DIR")
    );
    match std::fs::metadata(&p) {
        Ok(m) if m.len() >= 1024 => Some(p),
        _ => None,
    }
}

// ── Shared ready server ───────────────────────────────────────────────────────

/// A single server process that has been fully analysed (POST /analyze done,
/// GET /status returns `"ready"`).  Shared across all tests that call
/// `ready_port()`, so only one analysis runs even under `cargo test`'s default
/// parallel execution.  The `Child` is intentionally leaked; the OS reclaims it
/// when the test binary exits.
static READY_SERVER: OnceLock<u16> = OnceLock::new();

/// Return the port of the shared, already-analysed server.
/// Initialises it on first call (spawns + analyses); subsequent calls return
/// immediately.  Returns `None` when the philosophers fixture is absent.
fn ready_port() -> Option<u16> {
    let hprof = philosophers()?;
    let port = READY_SERVER.get_or_init(|| {
        let (_, port) = start_server(&hprof);
        // Trigger analysis and wait up to 120 s for it to complete.
        curl_post(port, "/analyze", "");
        wait_for_ready(port);
        port
    });
    Some(*port)
}

/// Bind to an OS-assigned free port, record it, drop the listener, then start
/// the server on that port.  There is a tiny TOCTOU window, but it is
/// acceptable for tests.
fn start_server(hprof: &str) -> (Child, u16) {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let port = listener.local_addr().unwrap().port();
    drop(listener);

    let child = Command::new(BIN)
        .args(["server", hprof, "--port", &port.to_string()])
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .expect("failed to spawn server");

    // Poll /status until the server is accepting connections (up to 60 s).
    let url = format!("http://127.0.0.1:{port}/status");
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
    loop {
        if std::time::Instant::now() > deadline {
            panic!("server on port {port} did not start within 60 s");
        }
        let ok = Command::new("curl")
            .args(["-s", "--max-time", "1", &url])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .map(|s| s.success())
            .unwrap_or(false);
        if ok {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(100));
    }
    (child, port)
}

/// GET `path` from the server on `port`.
/// Returns `(http_status_code, response_body)`.
fn curl_get(port: u16, path: &str) -> (u32, String) {
    let url = format!("http://127.0.0.1:{port}{path}");
    // Use `-w "\n%{http_code}"` so the last line is always the status code.
    let out = Command::new("curl")
        .args(["-s", "-w", "\n%{http_code}", &url])
        .output()
        .expect("curl failed");
    let raw = String::from_utf8_lossy(&out.stdout);
    parse_curl_output(&raw)
}

/// POST `body` to `path` on the server running on `port`.
/// Returns `(http_status_code, response_body)`.
fn curl_post(port: u16, path: &str, body: &str) -> (u32, String) {
    let url = format!("http://127.0.0.1:{port}{path}");
    let out = Command::new("curl")
        .args(["-s", "-w", "\n%{http_code}", "-X", "POST", "-d", body, &url])
        .output()
        .expect("curl failed");
    let raw = String::from_utf8_lossy(&out.stdout);
    parse_curl_output(&raw)
}

fn parse_curl_output(raw: &str) -> (u32, String) {
    // The last non-empty line is the status code written by `-w "\n%{http_code}"`.
    let mut lines: Vec<&str> = raw.lines().collect();
    let status: u32 = lines.pop().and_then(|l| l.trim().parse().ok()).unwrap_or(0);
    let body = lines.join("\n");
    (status, body)
}

/// Poll GET /status until the body contains `"ready"` (analysis done).
/// Panics if 120 s elapse without reaching ready.
fn wait_for_ready(port: u16) {
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
    loop {
        if std::time::Instant::now() > deadline {
            panic!("server on port {port} did not reach ready within 120 s");
        }
        let (_, body) = curl_get(port, "/status");
        if body.contains("\"ready\"") {
            return;
        }
        std::thread::sleep(std::time::Duration::from_millis(500));
    }
}

// ── Tests ────────────────────────────────────────────────────────────────────

/// GET /status immediately after startup must report `not_started`.
#[test]
fn server_status_not_started() {
    let Some(hprof) = philosophers() else { return };
    let (mut child, port) = start_server(&hprof);
    let (status, body) = curl_get(port, "/status");
    child.kill().ok();
    child.wait().ok();
    assert_eq!(status, 200, "expected HTTP 200 from /status, got {status}");
    assert!(
        body.contains("not_started"),
        "/status before any analysis should return not_started, got: {body}"
    );
}

/// POST /analyze must return HTTP 200 and a recognised status string.
#[test]
fn server_analyze_returns_started() {
    let Some(hprof) = philosophers() else { return };
    let (mut child, port) = start_server(&hprof);
    let (status, body) = curl_post(port, "/analyze", "");
    child.kill().ok();
    child.wait().ok();
    assert_eq!(
        status, 200,
        "expected HTTP 200 from POST /analyze, got {status}"
    );
    let recognised = body.contains("started")
        || body.contains("already_running")
        || body.contains("already_done");
    assert!(
        recognised,
        "POST /analyze body should contain started/already_running/already_done, got: {body}"
    );
}

/// After triggering analysis, GET /status must eventually reach `ready`.
#[test]
fn server_status_ready_after_analyze() {
    let Some(port) = ready_port() else { return };
    let (status, body) = curl_get(port, "/status");
    assert_eq!(status, 200, "expected HTTP 200 from /status, got {status}");
    assert!(
        body.contains("\"ready\""),
        "/status after analysis should contain 'ready', got: {body}"
    );
}

/// GET /report after analysis returns valid JSON (no top-level error key, starts with `{`).
#[test]
fn server_report_json_has_fields() {
    let Some(port) = ready_port() else { return };
    let (status, body) = curl_get(port, "/report");
    assert_eq!(status, 200, "expected HTTP 200 from /report, got {status}");
    let trimmed = body.trim();
    assert!(
        trimmed.starts_with('{'),
        "/report should return a JSON object, got: {}",
        &body[..body.len().min(200)]
    );
    assert!(
        body.contains("\"schema_version\""),
        "/report JSON missing 'schema_version' field: {}",
        &body[..body.len().min(300)]
    );
    // The full report JSON must not carry a top-level "error" indicating failure.
    assert!(
        !body.contains("\"error\":{\"kind\":"),
        "/report returned an error response: {body}"
    );
}

/// GET /report/overview returns JSON containing a recognisable top-level field.
#[test]
fn server_report_overview_json() {
    let Some(port) = ready_port() else { return };
    let (status, body) = curl_get(port, "/report/overview");
    assert_eq!(
        status, 200,
        "expected HTTP 200 from /report/overview, got {status}"
    );
    assert!(
        body.trim().starts_with('{'),
        "/report/overview should return a JSON object, got: {}",
        &body[..body.len().min(200)]
    );
}

/// GET /report/overview?format=md returns Markdown text mentioning "heap" (case-insensitive).
#[test]
fn server_report_overview_md() {
    let Some(port) = ready_port() else { return };
    let (status, body) = curl_get(port, "/report/overview?format=md");
    assert_eq!(
        status, 200,
        "expected HTTP 200 from /report/overview?format=md, got {status}"
    );
    assert!(
        body.to_lowercase().contains("heap"),
        "/report/overview?format=md should mention 'heap', got: {}",
        &body[..body.len().min(400)]
    );
}

/// GET /report/leaks returns a JSON object.
#[test]
fn server_report_leaks_json() {
    let Some(port) = ready_port() else { return };
    let (status, body) = curl_get(port, "/report/leaks");
    assert_eq!(
        status, 200,
        "expected HTTP 200 from /report/leaks, got {status}"
    );
    assert!(
        body.trim().starts_with('{'),
        "/report/leaks should return a JSON object, got: {}",
        &body[..body.len().min(200)]
    );
    assert!(
        body.contains("\"suspects\"") && body.contains("\"total_shallow\""),
        "/report/leaks JSON missing expected keys 'suspects'/'total_shallow': {}",
        &body[..body.len().min(300)]
    );
}

/// GET /report/top returns a JSON object.
#[test]
fn server_report_top_json() {
    let Some(port) = ready_port() else { return };
    let (status, body) = curl_get(port, "/report/top");
    assert_eq!(
        status, 200,
        "expected HTTP 200 from /report/top, got {status}"
    );
    assert!(
        body.trim().starts_with('{'),
        "/report/top should return a JSON object, got: {}",
        &body[..body.len().min(200)]
    );
}

/// GET /report/threads returns a JSON object.
#[test]
fn server_report_threads_json() {
    let Some(port) = ready_port() else { return };
    let (status, body) = curl_get(port, "/report/threads");
    assert_eq!(
        status, 200,
        "expected HTTP 200 from /report/threads, got {status}"
    );
    assert!(
        body.trim().starts_with('{'),
        "/report/threads should return a JSON object, got: {}",
        &body[..body.len().min(200)]
    );
}

/// POST / with an OQL query returns a QueryResult JSON containing `rows` or `columns`.
#[test]
fn server_oql_post_works() {
    let Some(hprof) = philosophers() else { return };
    let (mut child, port) = start_server(&hprof);
    let (status, body) = curl_post(port, "/", "SELECT COUNT(*) FROM java.lang.String");
    child.kill().ok();
    child.wait().ok();
    assert_eq!(status, 200, "expected HTTP 200 from POST /, got {status}");
    let has_result_fields = body.contains("\"rows\"") || body.contains("\"columns\"");
    assert!(
        has_result_fields,
        "OQL response should contain 'rows' or 'columns', got: {}",
        &body[..body.len().min(400)]
    );
}

/// GET /version returns JSON listing at least one `/report` endpoint path.
#[test]
fn server_version_lists_report() {
    let Some(hprof) = philosophers() else { return };
    let (mut child, port) = start_server(&hprof);
    let (status, body) = curl_get(port, "/version");
    child.kill().ok();
    child.wait().ok();
    assert_eq!(status, 200, "expected HTTP 200 from /version, got {status}");
    assert!(
        body.contains("/report"),
        "/version JSON should list /report endpoint, got: {body}"
    );
}

/// Issue a request with an arbitrary HTTP method (useful for 405 checks).
fn curl_request(port: u16, method: &str, path: &str) -> (u32, String) {
    let url = format!("http://127.0.0.1:{port}{path}");
    let out = Command::new("curl")
        .args(["-s", "-w", "\n%{http_code}", "-X", method, &url])
        .output()
        .expect("curl failed");
    let raw = String::from_utf8_lossy(&out.stdout);
    parse_curl_output(&raw)
}

// ── Error / edge-case tests ───────────────────────────────────────────────────

/// GET /analyze (wrong method) must return 405.
#[test]
fn server_wrong_method_405() {
    let Some(hprof) = philosophers() else { return };
    let (mut child, port) = start_server(&hprof);
    let (status, body) = curl_request(port, "GET", "/analyze");
    child.kill().ok();
    child.wait().ok();
    assert_eq!(
        status, 405,
        "expected HTTP 405 for GET /analyze, got {status}: {body}"
    );
    assert!(
        body.contains("\"kind\"") || body.contains("method"),
        "405 body should describe the error, got: {body}"
    );
}

/// POST /report (wrong method) must return 405.
#[test]
fn server_report_post_is_405() {
    let Some(hprof) = philosophers() else { return };
    let (mut child, port) = start_server(&hprof);
    let (status, _body) = curl_post(port, "/report", "");
    child.kill().ok();
    child.wait().ok();
    assert_eq!(
        status, 405,
        "expected HTTP 405 for POST /report, got {status}"
    );
}

/// GET /report/bogus (unknown section) must return 404 even after analysis.
#[test]
fn server_report_invalid_section_404() {
    let Some(port) = ready_port() else { return };
    let (status, _body) = curl_get(port, "/report/bogus-section");
    assert_eq!(
        status, 404,
        "expected 404 for /report/bogus-section, got {status}"
    );
}

/// GET /reportgarbage (no slash after /report) must NOT trigger analysis — 404.
#[test]
fn server_report_no_trailing_slash_404() {
    let Some(hprof) = philosophers() else { return };
    let (mut child, port) = start_server(&hprof);
    let (status, _body) = curl_get(port, "/reportgarbage");
    child.kill().ok();
    child.wait().ok();
    assert_eq!(
        status, 404,
        "/reportgarbage should be 404 (not a valid report path), got {status}"
    );
}

/// POST / with syntactically invalid OQL must return 400.
#[test]
fn server_oql_syntax_error_400() {
    let Some(hprof) = philosophers() else { return };
    let (mut child, port) = start_server(&hprof);
    let (status, body) = curl_post(port, "/", "THIS IS NOT VALID OQL AT ALL !!!!");
    child.kill().ok();
    child.wait().ok();
    assert_eq!(
        status, 400,
        "expected HTTP 400 for bad OQL, got {status}: {body}"
    );
    assert!(
        body.contains("error") || body.contains("Error"),
        "400 response should describe the parse error, got: {body}"
    );
}

/// POST /query (alias) with the same OQL as POST / returns the same result shape.
#[test]
fn server_oql_query_alias_works() {
    let Some(hprof) = philosophers() else { return };
    let (mut child, port) = start_server(&hprof);
    let (status, body) = curl_post(port, "/query", "SELECT COUNT(*) FROM java.lang.String");
    child.kill().ok();
    child.wait().ok();
    assert_eq!(
        status, 200,
        "expected HTTP 200 from POST /query, got {status}"
    );
    assert!(
        body.contains("\"rows\"") || body.contains("\"columns\""),
        "POST /query should return QueryResult shape, got: {}",
        &body[..body.len().min(300)]
    );
}

/// POST /stream returns NDJSON: first line is a meta object, subsequent lines are rows.
#[test]
fn server_stream_endpoint_works() {
    let Some(hprof) = philosophers() else { return };
    let (mut child, port) = start_server(&hprof);
    let (status, body) = curl_post(port, "/stream", "SELECT COUNT(*) FROM java.lang.String");
    child.kill().ok();
    child.wait().ok();
    assert_eq!(
        status, 200,
        "expected HTTP 200 from POST /stream, got {status}"
    );
    // First line of NDJSON should be a JSON object (meta or result row).
    let first_line = body.lines().next().unwrap_or("");
    assert!(
        first_line.trim_start().starts_with('{'),
        "POST /stream first line should be a JSON object, got: {first_line}"
    );
}

// ── Markdown endpoint tests ───────────────────────────────────────────────────

/// GET /report?format=md returns a Markdown string (starts with `#` heading or contains `##`).
#[test]
fn server_report_full_md() {
    let Some(port) = ready_port() else { return };
    let (status, body) = curl_get(port, "/report?format=md");
    assert_eq!(
        status, 200,
        "expected HTTP 200 from /report?format=md, got {status}"
    );
    assert!(
        body.contains("##") || body.starts_with('#'),
        "/report?format=md should contain Markdown headings, got: {}",
        &body[..body.len().min(300)]
    );
}

/// GET /report/threads?format=md contains the word "Thread" (from thread names or section heading).
#[test]
fn server_report_threads_md_has_thread_names() {
    let Some(port) = ready_port() else { return };
    let (status, body) = curl_get(port, "/report/threads?format=md");
    assert_eq!(
        status, 200,
        "expected HTTP 200 from /report/threads?format=md, got {status}"
    );
    assert!(
        body.contains("Thread") || body.contains("thread"),
        "/report/threads?format=md should mention threads, got: {}",
        &body[..body.len().min(400)]
    );
}

// ── OQL query correctness tests via server endpoint ───────────────────────────

/// GROUP BY + ORDER BY + LIMIT via server returns the top class by instance count.
#[test]
fn server_oql_group_by_order_by() {
    let Some(hprof) = philosophers() else { return };
    let (mut child, port) = start_server(&hprof);
    let (status, body) = curl_post(
        port,
        "/",
        "SELECT @displayName, COUNT(*) AS n FROM INSTANCEOF java.lang.Object \
         GROUP BY @displayName ORDER BY n DESC LIMIT 5",
    );
    child.kill().ok();
    child.wait().ok();
    assert_eq!(
        status, 200,
        "expected HTTP 200 from GROUP BY query, got {status}"
    );
    // The result JSON must have rows and the first row must contain a displayName
    // (a Java class name always contains ".") and a positive count.
    assert!(
        body.contains("\"rows\""),
        "GROUP BY response should contain 'rows', got: {}",
        &body[..body.len().min(500)]
    );
}

/// WHERE predicate filters results correctly — only matching rows returned.
#[test]
fn server_oql_where_predicate() {
    let Some(hprof) = philosophers() else { return };
    let (mut child, port) = start_server(&hprof);
    // Count strings with @usedHeapSize > 0 — should be > 0 rows.
    let (status, body) = curl_post(
        port,
        "/",
        "SELECT COUNT(*) FROM java.lang.String WHERE @usedHeapSize > 0",
    );
    child.kill().ok();
    child.wait().ok();
    assert_eq!(
        status, 200,
        "expected HTTP 200 from WHERE query, got {status}"
    );
    assert!(
        body.contains("\"rows\""),
        "WHERE query should have rows field, got: {}",
        &body[..body.len().min(300)]
    );
    // The count should be a positive integer somewhere in the rows.
    assert!(
        body.contains("\"value\"") || body.contains("COUNT"),
        "WHERE count result should contain a value, got: {}",
        &body[..body.len().min(300)]
    );
}

/// UNION of two class queries returns rows from both — row count > either alone.
#[test]
fn server_oql_union() {
    let Some(hprof) = philosophers() else { return };
    let (mut child, port) = start_server(&hprof);
    let (status, body) = curl_post(
        port,
        "/",
        "SELECT @displayName FROM java.lang.String LIMIT 2 \
         UNION SELECT @displayName FROM java.lang.Thread LIMIT 2",
    );
    child.kill().ok();
    child.wait().ok();
    assert_eq!(
        status, 200,
        "expected HTTP 200 from UNION query, got {status}"
    );
    assert!(
        body.contains("\"rows\""),
        "UNION response should contain 'rows', got: {}",
        &body[..body.len().min(400)]
    );
}

/// SUM aggregate over @usedHeapSize returns a positive integer.
#[test]
fn server_oql_aggregate_sum() {
    let Some(hprof) = philosophers() else { return };
    let (mut child, port) = start_server(&hprof);
    let (status, body) = curl_post(port, "/", "SELECT SUM(@usedHeapSize) FROM java.lang.String");
    child.kill().ok();
    child.wait().ok();
    assert_eq!(
        status, 200,
        "expected HTTP 200 from SUM query, got {status}"
    );
    assert!(
        body.contains("\"rows\""),
        "SUM response should contain 'rows', got: {}",
        &body[..body.len().min(300)]
    );
}

/// DISTINCT de-duplicates rows — thread display names collapse to one row.
#[test]
fn server_oql_distinct() {
    let Some(hprof) = philosophers() else { return };
    let (mut child, port) = start_server(&hprof);
    // All Thread instances have the same @displayName: one distinct row expected.
    let (status, body) = curl_post(
        port,
        "/",
        "SELECT DISTINCT @displayName FROM java.lang.Thread",
    );
    child.kill().ok();
    child.wait().ok();
    assert_eq!(
        status, 200,
        "expected HTTP 200 from DISTINCT query, got {status}"
    );
    assert!(
        body.contains("\"rows\""),
        "DISTINCT response should contain 'rows', got: {}",
        &body[..body.len().min(300)]
    );
    // Should have exactly 1 row: ["java.lang.Thread"]
    let row_count = body.matches("java.lang.Thread").count();
    assert!(
        row_count >= 1,
        "DISTINCT threads should yield at least one row with 'java.lang.Thread', got: {}",
        &body[..body.len().min(400)]
    );
}

/// GET /bogus-nonexistent must return HTTP 404.
#[test]
fn server_unknown_route_404() {
    let Some(hprof) = philosophers() else { return };
    let (mut child, port) = start_server(&hprof);
    let (status, _body) = curl_get(port, "/bogus-nonexistent");
    child.kill().ok();
    child.wait().ok();
    assert_eq!(
        status, 404,
        "expected HTTP 404 for unknown route, got {status}"
    );
}

/// GET /report/leaks?limit=2 returns at most 2 suspects.
#[test]
fn server_report_leaks_limit() {
    let Some(port) = ready_port() else { return };
    let (status, body) = curl_get(port, "/report/leaks?limit=2");
    assert_eq!(
        status, 200,
        "expected 200 from /report/leaks?limit=2, got {status}"
    );
    assert!(
        body.contains("\"suspects\""),
        "response should have suspects field: {}",
        &body[..body.len().min(300)]
    );
    // Count the number of "is_single" occurrences as a proxy for suspect entries.
    // Each Suspect object has exactly one "is_single" field, so the count equals
    // the number of suspects in the array.
    let suspect_count = body.matches("\"is_single\"").count();
    assert!(
        suspect_count <= 2,
        "expected at most 2 suspects with limit=2, counted {suspect_count} in: {}",
        &body[..body.len().min(500)]
    );
}

/// GET /report/leaks (no limit) returns the full suspects list.
#[test]
fn server_report_leaks_no_limit() {
    let Some(port) = ready_port() else { return };
    let (status, body) = curl_get(port, "/report/leaks");
    assert_eq!(status, 200, "expected 200 from /report/leaks, got {status}");
    assert!(
        body.contains("\"suspects\""),
        "response should have suspects field: {}",
        &body[..body.len().min(300)]
    );
}

/// After POST /analyze completes, `@retainedHeapSize` queries must succeed.
/// Before this fix, the OQL server was permanently locked to `reachable_only=true`,
/// which caused retained-size / dominator queries to error with
/// "requires the full analysis pipeline".
#[test]
fn server_oql_retained_size_after_analysis() {
    let Some(port) = ready_port() else { return };
    let (status, body) = curl_post(
        port,
        "/",
        "SELECT @displayName, @retainedHeapSize FROM java.lang.Thread \
         ORDER BY @retainedHeapSize DESC LIMIT 3",
    );
    assert_eq!(
        status, 200,
        "expected HTTP 200 for @retainedHeapSize query after analysis, got {status}: {body}"
    );
    assert!(
        body.contains("\"rows\""),
        "@retainedHeapSize query should contain 'rows', got: {}",
        &body[..body.len().min(500)]
    );
    assert!(
        !body.contains("requires the full analysis pipeline"),
        "@retainedHeapSize query must not error with 'requires the full analysis pipeline', got: {}",
        &body[..body.len().min(500)]
    );
}

/// POST / with a JSON body {"query":"SELECT ..."} works the same as a raw body.
#[test]
fn server_oql_json_body() {
    let Some(hprof) = philosophers() else { return };
    let (mut child, port) = start_server(&hprof);
    let url = format!("http://127.0.0.1:{port}/");
    let out = std::process::Command::new("curl")
        .args([
            "-s",
            "-w",
            "\n%{http_code}",
            "-X",
            "POST",
            "-H",
            "Content-Type: application/json",
            "-d",
            r#"{"query":"SELECT COUNT(*) FROM java.lang.String"}"#,
            &url,
        ])
        .output()
        .expect("curl failed");
    let raw = String::from_utf8_lossy(&out.stdout);
    let mut lines: Vec<&str> = raw.lines().collect();
    let status: u32 = lines.pop().and_then(|l| l.trim().parse().ok()).unwrap_or(0);
    let body = lines.join("\n");
    child.kill().ok();
    child.wait().ok();
    assert_eq!(
        status, 200,
        "JSON body POST / should return 200, got {status}: {body}"
    );
    assert!(
        body.contains("\"rows\"") || body.contains("\"columns\""),
        "JSON body OQL response should contain QueryResult fields, got: {}",
        &body[..body.len().min(400)]
    );
}