Skip to content

Commit 990d5c3

Browse files
committed
Merge branch 'main' into sibling-relative-import
2 parents e0371cc + 82f73d8 commit 990d5c3

File tree

12 files changed

+420
-134
lines changed

12 files changed

+420
-134
lines changed

Cargo.lock

Lines changed: 54 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

components/api-server/Cargo.toml

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ version = "0.1.0"
44
edition = "2024"
55

66
[lib]
7-
name = "clp_client"
7+
name = "api_server"
88
path = "src/lib.rs"
99

1010
[[bin]]
@@ -29,6 +29,9 @@ sqlx = { version = "0.8.6", features = ["runtime-tokio", "mysql"] }
2929
thiserror = "2.0.17"
3030
tokio = { version = "1.48.0", features = ["full"] }
3131
tokio-stream = { version = "0.1.17", features = ["fs"] }
32+
tower-http = { version = "0.6.7", features = ["cors"] }
3233
tracing = "0.1.41"
3334
tracing-appender = "0.2.3"
3435
tracing-subscriber = { version = "0.3.20", features = ["json", "env-filter", "fmt", "std"] }
36+
utoipa = { version = "5.4.0", features = ["axum_extras"] }
37+
utoipa-axum = "0.2.0"
Lines changed: 3 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,6 @@
11
use anyhow::Context;
2-
use axum::{
3-
Json,
4-
Router,
5-
extract::{Path, State},
6-
http::StatusCode,
7-
response::{
8-
IntoResponse,
9-
Sse,
10-
sse::{Event, KeepAlive},
11-
},
12-
routing::{get, post},
13-
};
142
use clap::Parser;
153
use clp_rust_utils::{clp_config::package, serde::yaml};
16-
use futures::{Stream, StreamExt};
17-
use thiserror::Error;
184
use tracing_appender::rolling::{RollingFileAppender, Rotation};
195
use tracing_subscriber::{self, fmt::writer::MakeWriterExt};
206

@@ -95,75 +81,15 @@ async fn main() -> anyhow::Result<()> {
9581
.await
9682
.context(format!("Cannot listen to {addr}"))?;
9783

98-
let client = clp_client::Client::connect(&config, &credentials)
84+
let client = api_server::client::Client::connect(&config, &credentials)
9985
.await
10086
.context("Cannot connect to CLP")?;
10187

102-
let app = Router::new()
103-
.route("/", get(health))
104-
.route("/health", get(health))
105-
.route("/query", post(query))
106-
.route("/query_results/{search_job_id}", get(query_results))
107-
.with_state(client);
88+
let router = api_server::routes::from_client(client)?;
10889

10990
tracing::info!("Server started at {addr}");
110-
axum::serve(listener, app)
91+
axum::serve(listener, router)
11192
.with_graceful_shutdown(shutdown_signal())
11293
.await?;
11394
Ok(())
11495
}
115-
116-
async fn health() -> String {
117-
"API server is running".to_owned()
118-
}
119-
120-
async fn query(
121-
State(client): State<clp_client::Client>,
122-
Json(query_config): Json<clp_client::QueryConfig>,
123-
) -> Result<Json<serde_json::Value>, HandlerError> {
124-
let search_job_id = client.submit_query(query_config).await?;
125-
let uri = format!("/query_results/{search_job_id}");
126-
Ok(Json(serde_json::json!({"query_results_uri": uri})))
127-
}
128-
129-
async fn query_results(
130-
State(client): State<clp_client::Client>,
131-
Path(search_job_id): Path<u64>,
132-
) -> Result<Sse<impl Stream<Item = Result<Event, HandlerError>>>, HandlerError> {
133-
let results_stream = client.fetch_results(search_job_id).await?;
134-
let event_stream = results_stream.map(|res| {
135-
let message = res?;
136-
let trimmed_message = message.trim();
137-
if trimmed_message.lines().count() != 1 {
138-
return Err(HandlerError::InternalServer);
139-
}
140-
Ok(Event::default().data(trimmed_message))
141-
});
142-
Ok(Sse::new(event_stream).keep_alive(KeepAlive::default()))
143-
}
144-
145-
/// Generic errors for request handlers.
146-
#[derive(Error, Debug)]
147-
enum HandlerError {
148-
#[error("Internal server error")]
149-
InternalServer,
150-
}
151-
152-
trait IntoHandlerError {}
153-
154-
impl IntoHandlerError for axum::Error {}
155-
156-
impl IntoHandlerError for clp_client::ClientError {}
157-
158-
impl<T: IntoHandlerError> From<T> for HandlerError {
159-
fn from(_: T) -> Self {
160-
Self::InternalServer
161-
}
162-
}
163-
164-
/// Converts [`HandlerError`] into an HTTP response.
165-
impl IntoResponse for HandlerError {
166-
fn into_response(self) -> axum::response::Response {
167-
StatusCode::INTERNAL_SERVER_ERROR.into_response()
168-
}
169-
}

components/api-server/src/client.rs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,24 +13,39 @@ use futures::{Stream, StreamExt};
1313
use pin_project_lite::pin_project;
1414
use serde::{Deserialize, Serialize};
1515
use sqlx::Row;
16+
use utoipa::ToSchema;
1617

1718
pub use crate::error::ClientError;
1819

1920
/// Defines the request configuration for submitting a search query.
20-
#[derive(Clone, Serialize, Deserialize)]
21+
#[derive(Clone, Serialize, Deserialize, ToSchema)]
2122
#[serde(deny_unknown_fields)]
2223
pub struct QueryConfig {
24+
/// The search query as a KQL string.
2325
pub query_string: String,
26+
27+
/// The dataset to search within. If not provided, only `default` dataset will be searched.
2428
#[serde(default)]
2529
pub dataset: Option<String>,
30+
31+
/// The maximum number of results to return. Set to `0` for no limit.
2632
#[serde(default)]
2733
pub max_num_results: u32,
34+
35+
/// The beginning timestamp (in epoch milliseconds) for the search range (inclusive).
2836
#[serde(default)]
2937
pub begin_timestamp: Option<i64>,
38+
39+
/// The ending timestamp (in epoch milliseconds) for the search range (inclusive).
3040
#[serde(default)]
3141
pub end_timestamp: Option<i64>,
42+
43+
/// Whether the string match should be case-insensitive.
3244
#[serde(default)]
3345
pub ignore_case: bool,
46+
47+
/// Whether to write the search results to files. If `false`, results will be stored in
48+
/// `MongoDB`.
3449
#[serde(default)]
3550
pub write_to_file: bool,
3651
}

components/api-server/src/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
mod client;
1+
pub mod client;
22
mod error;
3-
pub use client::*;
3+
pub mod routes;

0 commit comments

Comments
 (0)