littlegraph 0.2.1

Command-line tools and network servers for the littlegraph graph database
#![cfg(unix)]

use std::io::{BufRead, BufReader, Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};

use littlegraph_core::Neo4jStorage;

struct ChildGuard(Child);

impl Drop for ChildGuard {
    fn drop(&mut self) {
        if self.0.try_wait().ok().flatten().is_none() {
            let _ = self.0.kill();
            let _ = self.0.wait();
        }
    }
}

fn spawn_server(database: &Path) -> ChildGuard {
    let auth_file = database.parent().unwrap().join("query-auth.txt");
    std::fs::write(&auth_file, "rw::process-test-token\n").unwrap();
    ChildGuard(
        Command::new(env!("CARGO_BIN_EXE_littlegraph"))
            .args([
                "serve",
                database.to_str().unwrap(),
                "--bolt",
                "127.0.0.1:0",
                "--query",
                "127.0.0.1:0",
                "--query-auth-file",
                auth_file.to_str().unwrap(),
            ])
            .stdout(Stdio::null())
            .stderr(Stdio::piped())
            .spawn()
            .unwrap(),
    )
}

fn spawn_query_only_server(database: &Path) -> ChildGuard {
    let auth_file = database.parent().unwrap().join("query-auth.txt");
    std::fs::write(&auth_file, "rw::process-test-token\n").unwrap();
    ChildGuard(
        Command::new(env!("CARGO_BIN_EXE_littlegraph"))
            .args([
                "serve",
                database.to_str().unwrap(),
                "--query",
                "127.0.0.1:0",
                "--query-auth-file",
                auth_file.to_str().unwrap(),
            ])
            .stdout(Stdio::null())
            .stderr(Stdio::piped())
            .spawn()
            .unwrap(),
    )
}

fn wait_for_query_address(child: &mut ChildGuard) -> SocketAddr {
    let stderr = child.0.stderr.take().unwrap();
    let mut reader = BufReader::new(stderr);
    let deadline = Instant::now() + Duration::from_secs(10);
    let mut output = String::new();
    while Instant::now() < deadline {
        let mut line = String::new();
        if reader.read_line(&mut line).unwrap() == 0 {
            break;
        }
        output.push_str(&line);
        if let Some(address) = line.strip_prefix("Query API server listening on ") {
            child.0.stderr = Some(reader.into_inner());
            return address.trim().parse().unwrap();
        }
    }
    panic!("server did not report Query API readiness: {output}");
}

fn query(address: SocketAddr, token: &str) -> (u16, serde_json::Value) {
    let body = r#"{"statement":"RETURN 1"}"#;
    let mut stream = TcpStream::connect(address).unwrap();
    write!(
        stream,
        "POST /db/self/query/v2 HTTP/1.1\r\nHost: {address}\r\nAuthorization: Bearer {token}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
        body.len()
    )
    .unwrap();
    let mut response = Vec::new();
    stream.read_to_end(&mut response).unwrap();
    let separator = response
        .windows(4)
        .position(|window| window == b"\r\n\r\n")
        .unwrap();
    let head = std::str::from_utf8(&response[..separator]).unwrap();
    let status = head
        .lines()
        .next()
        .unwrap()
        .split_whitespace()
        .nth(1)
        .unwrap()
        .parse()
        .unwrap();
    let body = serde_json::from_slice(&response[separator + 4..]).unwrap();
    (status, body)
}

fn terminate_and_wait(child: &mut ChildGuard) {
    let result = unsafe { libc::kill(child.0.id() as libc::pid_t, libc::SIGTERM) };
    assert_eq!(result, 0);
    let deadline = Instant::now() + Duration::from_secs(10);
    loop {
        if let Some(status) = child.0.try_wait().unwrap() {
            assert!(status.success(), "server exited with {status}");
            return;
        }
        assert!(
            Instant::now() < deadline,
            "server did not stop after SIGTERM"
        );
        std::thread::sleep(Duration::from_millis(10));
    }
}

#[test]
fn serves_authenticated_query_api_and_stops_with_bolt() {
    let directory = tempfile::tempdir().unwrap();
    let database = directory.path().join("neo4j");
    let mut child = spawn_server(&database);
    let address = wait_for_query_address(&mut child);
    assert_ne!(address.port(), 0);

    let (status, body) = query(address, "wrong-token");
    assert_eq!(status, 401);
    assert_eq!(
        body["errors"][0]["code"],
        "Neo.ClientError.Security.Unauthorized"
    );
    let (status, body) = query(address, "process-test-token");
    assert_eq!(status, 202);
    assert_eq!(body["data"]["values"], serde_json::json!([[1]]));

    terminate_and_wait(&mut child);
    littlegraph_core::Graph::open_neo4j_writable(&database).unwrap();
}

#[test]
fn serves_query_api_without_bolt_and_releases_the_database() {
    let directory = tempfile::tempdir().unwrap();
    let database = directory.path().join("neo4j");
    let mut child = spawn_query_only_server(&database);
    let address = wait_for_query_address(&mut child);

    let (status, body) = query(address, "process-test-token");
    assert_eq!(status, 202);
    assert_eq!(body["data"]["values"], serde_json::json!([[1]]));

    terminate_and_wait(&mut child);
    littlegraph_core::Graph::open_neo4j_writable(&database).unwrap();
}

#[test]
fn serve_without_a_listener_exits_nonzero() {
    let directory = tempfile::tempdir().unwrap();
    let database = directory.path().join("neo4j");
    let output = Command::new(env!("CARGO_BIN_EXE_littlegraph"))
        .args(["serve", database.to_str().unwrap()])
        .output()
        .unwrap();

    assert!(!output.status.success());
    let diagnostics = String::from_utf8_lossy(&output.stderr);
    assert!(diagnostics.contains("--bolt <HOST:PORT>"));
    assert!(diagnostics.contains("--query <HOST:PORT>"));
    assert!(diagnostics.contains("--mcp <HOST:PORT>"));
}

#[test]
fn query_bind_failure_exits_nonzero() {
    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
    let address = listener.local_addr().unwrap();
    let directory = tempfile::tempdir().unwrap();
    let database = directory.path().join("neo4j");
    Neo4jStorage::initialize_if_empty(&database).unwrap();

    let output = Command::new(env!("CARGO_BIN_EXE_littlegraph"))
        .args([
            "serve",
            database.to_str().unwrap(),
            "--bolt",
            "127.0.0.1:0",
            "--query",
            &address.to_string(),
        ])
        .output()
        .unwrap();
    assert!(!output.status.success());
    assert!(
        String::from_utf8_lossy(&output.stderr).contains("Address already in use"),
        "unexpected diagnostics: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn invalid_query_auth_file_is_not_echoed() {
    let directory = tempfile::tempdir().unwrap();
    let database = directory.path().join("neo4j");
    let auth_file = directory.path().join("query-auth.txt");
    let secret = "invalid secret value";
    std::fs::write(&auth_file, secret).unwrap();
    let output = Command::new(env!("CARGO_BIN_EXE_littlegraph"))
        .args([
            "serve",
            database.to_str().unwrap(),
            "--bolt",
            "127.0.0.1:0",
            "--query",
            "127.0.0.1:0",
            "--query-auth-file",
            auth_file.to_str().unwrap(),
        ])
        .output()
        .unwrap();
    assert!(!output.status.success());
    let diagnostics = String::from_utf8_lossy(&output.stderr);
    assert!(diagnostics.contains("line 1 must use the format"));
    assert!(!diagnostics.contains(secret));
}