Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions contracts/query-v1.fixtures.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[
{"path":"/api/v1/logs","body":{"time_range":{"from":"2026-01-01T00:00:00.000Z","to":"2026-01-01T01:00:00.000Z"},"filters":[{"field":"service_name","op":"=","value":"payments"}],"search":"timeout","limit":50,"slim":true},"request":{"version":"v1","signal":"logs","operation":"search","time_range":{"from":"2026-01-01T00:00:00.000Z","to":"2026-01-01T01:00:00.000Z"},"filters":[{"field":"service_name","op":"=","value":"payments"}],"search":"timeout","options":{"limit":50,"slim":true}}},
{"path":"/api/v1/query","body":{"time_range":{"from":"2026-01-01T00:00:00.000Z","to":"2026-01-01T01:00:00.000Z"},"filters":[],"cursor":"opaque","columns":"list"},"request":{"version":"v1","signal":"spans","operation":"search","time_range":{"from":"2026-01-01T00:00:00.000Z","to":"2026-01-01T01:00:00.000Z"},"filters":[],"search":null,"options":{"cursor":"opaque","columns":"list"}}},
{"path":"/api/v1/explore/search","body":{"signal":"logs","time_range":{"from":"2026-01-01T00:00:00.000Z","to":"2026-01-01T01:00:00.000Z"},"include_rows":false,"include_summary":true},"request":{"version":"v1","signal":"logs","operation":"explore","time_range":{"from":"2026-01-01T00:00:00.000Z","to":"2026-01-01T01:00:00.000Z"},"filters":[],"search":null,"options":{"include_rows":false,"include_summary":true}}},
{"path":"/prom/api/v1/query_range","params":{"query":"rate(requests_total[5m])","start":"1767225600","end":"1767229200","step":"15"},"request":{"version":"v1","signal":"metrics","operation":"range","time_range":{"from":"2026-01-01T00:00:00.000Z","to":"2026-01-01T01:00:00.000Z"},"filters":[],"search":null,"options":{"query":"rate(requests_total[5m])","step":"15"}}},
{"path":"/prom/api/v1/query","params":{"query":"up","time":"1767225600"},"request":{"version":"v1","signal":"metrics","operation":"instant","time_range":{"from":"2026-01-01T00:00:00.000Z","to":"2026-01-01T00:00:00.000Z"},"filters":[],"search":null,"options":{"query":"up"}}}
]
21 changes: 21 additions & 0 deletions contracts/query-v1.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"version": "v1",
"endpoint": "/api/v1/query/execute",
"max_filters": 30,
"max_search_bytes": 512,
"routes": [
{"path":"/api/v1/query","signal":"spans","operation":"search","options":["limit","offset","cursor","columns","group_by","aggregation"]},
{"path":"/api/v1/logs","signal":"logs","operation":"search","options":["limit","offset","cursor","slim","display_fields"]},
{"path":"/api/v1/explore/search","signal":"dynamic","operation":"explore","options":["limit","interval","group_by","display_fields","include_rows","include_summary"]},
{"path":"/api/v1/query/count","signal":"spans","operation":"count","options":["interval"]},
{"path":"/api/v1/logs/count","signal":"logs","operation":"count","options":["interval"]},
{"path":"/api/v1/query/group","signal":"spans","operation":"group","options":["group_by","aggregation","limit"]},
{"path":"/api/v1/logs/group","signal":"logs","operation":"group","options":["group_by","aggregation","limit"]},
{"path":"/api/v1/query/timeseries","signal":"spans","operation":"timeseries","options":["interval","group_by","include_heatmap"]},
{"path":"/api/v1/logs/histogram","signal":"logs","operation":"histogram","options":[]},
{"path":"/api/v1/logs/patterns","signal":"logs","operation":"patterns","options":["limit"]},
{"path":"/api/v1/query/scatter","signal":"dynamic","operation":"scatter","options":["x_field","y_field","limit"]},
{"path":"/prom/api/v1/query_range","signal":"metrics","operation":"range","options":["query","step"]},
{"path":"/prom/api/v1/query","signal":"metrics","operation":"instant","options":["query"]}
]
}
106 changes: 65 additions & 41 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,11 +172,20 @@ impl RushClient {
path: &str,
body: &serde_json::Value,
) -> Result<T, ApiError> {
let unified = crate::query_contract::adapt(path, body);
let mut request = self
.http
.post(format!("{}{}", self.base_url, path))
.post(format!(
"{}{}",
self.base_url,
if unified.is_some() {
crate::query_contract::ENDPOINT
} else {
path
}
))
.header("X-Rush-Tenant", &self.tenant)
.json(body);
.json(unified.as_ref().unwrap_or(body));
if let Some(key) = self.api_key.as_deref() {
request = request.bearer_auth(key);
}
Expand All @@ -200,7 +209,13 @@ impl RushClient {
.unwrap_or_else(|| "request failed".to_string());
let message = serde_json::from_str::<serde_json::Value>(&message)
.ok()
.and_then(|value| value.get("message")?.as_str().map(str::to_string))
.and_then(|value| {
value
.pointer("/error/message")
.or_else(|| value.get("message"))?
.as_str()
.map(str::to_string)
})
.map(|text| sanitise_server_text(&text))
// An all-control-character message sanitises to nothing, so
// fall back rather than printing an empty reason.
Expand All @@ -209,7 +224,12 @@ impl RushClient {
return Err(ApiError::Response { status, message });
}
let body = read_body_capped(response, MAX_RESPONSE_BYTES).await?;
serde_json::from_slice(&body).map_err(|error| ApiError::Response {
(if let Some(request) = unified {
crate::query_contract::decode(&body, &request)
} else {
serde_json::from_slice(&body)
})
.map_err(|error| ApiError::Response {
status,
message: format!("could not parse the response: {error}"),
})
Expand Down Expand Up @@ -350,7 +370,7 @@ mod tests {
});
let redirect = source.mock(|when, then| {
when.method(POST)
.path("/api/v1/logs")
.path("/api/v1/query/execute")
.header("authorization", "Bearer test-key")
.header("x-rush-tenant", "default")
.body_includes("private-query");
Expand Down Expand Up @@ -434,9 +454,9 @@ mod tests {
async fn escape_sequences_in_a_server_error_never_reach_the_caller() {
let server = MockServer::start();
server.mock(|when, then| {
when.method(POST).path("/api/v1/logs");
when.method(POST).path("/api/v1/query/execute");
then.status(500).json_body(json!({
"message": "\u{1b}[2Jboom\nrush: forged line"
"error": {"code":"internal_error", "message": "\u{1b}[2Jboom\nrush: forged line", "request_id":"test"}
}));
});
let spec = QuerySpec {
Expand Down Expand Up @@ -538,27 +558,29 @@ mod tests {
let server = MockServer::start();
let request = server.mock(|when, then| {
when.method(POST)
.path("/api/v1/logs")
.path("/api/v1/query/execute")
.header("authorization", "Bearer test-key")
.header("x-rush-tenant", "default")
.body_includes("\"search\":\"panic\"")
.body_includes("\"slim\":true");
then.status(200).json_body(json!({
"rows": [{
"Timestamp": 1_700_000_000_000_000_000_i64,
"TraceId": "trace-1",
"SpanId": "span-1",
"SeverityText": "ERROR",
"SeverityNumber": 17,
"ServiceName": "gateway",
"Body": "panic in request",
"TimestampNs": "1700000000000000000",
"BlockNumber": "1",
"BlockOffset": "2",
"BodyHash": "3"
}],
"total": 1
}));
then.status(200).json_body(
json!({"version":"v1","signal":"logs","operation":"search","data":{
"rows": [{
"Timestamp": 1_700_000_000_000_000_000_i64,
"TraceId": "trace-1",
"SpanId": "span-1",
"SeverityText": "ERROR",
"SeverityNumber": 17,
"ServiceName": "gateway",
"Body": "panic in request",
"TimestampNs": "1700000000000000000",
"BlockNumber": "1",
"BlockOffset": "2",
"BodyHash": "3"
}],
"total": 1
}}),
);
});
let spec = QuerySpec {
signal: Signal::Logs,
Expand All @@ -585,24 +607,26 @@ mod tests {
let server = MockServer::start();
let request = server.mock(|when, then| {
when.method(POST)
.path("/api/v1/query")
.path("/api/v1/query/execute")
.body_includes("\"columns\":\"list\"")
.body_includes("\"field\":\"service_name\"");
then.status(200).json_body(json!({
"rows": [{
"timestamp": 1_700_000_000_000_000_000_i64,
"service_name": "articles",
"span_name": "GET /articles",
"http_method": "GET",
"http_path": "/articles",
"http_status_code": 200,
"duration_ns": 25_000_000,
"status": "ok",
"trace_id": "trace-2",
"span_id": "span-2"
}],
"total": 1
}));
then.status(200).json_body(
json!({"version":"v1","signal":"spans","operation":"search","data":{
"rows": [{
"timestamp": 1_700_000_000_000_000_000_i64,
"service_name": "articles",
"span_name": "GET /articles",
"http_method": "GET",
"http_path": "/articles",
"http_status_code": 200,
"duration_ns": 25_000_000,
"status": "ok",
"trace_id": "trace-2",
"span_id": "span-2"
}],
"total": 1
}}),
);
});
let spec = QuerySpec {
signal: Signal::Apm,
Expand All @@ -628,7 +652,7 @@ mod tests {
async fn maps_unauthorized_responses_to_actionable_error() {
let server = MockServer::start();
server.mock(|when, then| {
when.method(POST).path("/api/v1/logs");
when.method(POST).path("/api/v1/query/execute");
then.status(401);
});
let spec = QuerySpec {
Expand Down
2 changes: 1 addition & 1 deletion src/api_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ async fn minimal_rows_and_empty_results_are_valid() {
let server = MockServer::start();
server.mock(|when, then| {
when.method(POST);
then.status(200).json_body(json!({"rows":rows}));
then.status(200).json_body(json!({"version":"v1","signal":if signal == Signal::Logs {"logs"} else {"spans"},"operation":"search","data":{"rows":rows}}));
});
let mut query = spec();
query.signal = signal;
Expand Down
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ mod app;
mod cli;
mod config;
mod model;
mod query_contract;
mod ui;

#[cfg(test)]
Expand Down
20 changes: 9 additions & 11 deletions src/poll_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,17 @@ async fn query_switch_cancels_slow_fetch_for_search_and_signal() {
let server = MockServer::start();
let slow = server.mock(|when, then| {
when.method(POST)
.path("/api/v1/logs")
.path("/api/v1/query/execute")
.body_includes("old-query");
then.status(200)
.delay(Duration::from_secs(10))
.json_body(json!({"rows":[]}));
then.status(200).delay(Duration::from_secs(10)).json_body(
json!({"version":"v1","signal":"logs","operation":"search","data":{"rows":[]}}),
);
});
let fresh = server.mock(|when, then| {
when.method(POST)
.path(if signal == model::Signal::Logs {
"/api/v1/logs"
} else {
"/api/v1/query"
})
.path("/api/v1/query/execute")
.body_includes("new-query");
then.status(200).json_body(json!({"rows":[]}));
then.status(200).json_body(json!({"version":"v1","signal":if signal == model::Signal::Logs {"logs"} else {"spans"},"operation":"search","data":{"rows":[]}}));
});
let mut old = spec();
old.search = "old-query".into();
Expand Down Expand Up @@ -114,7 +110,9 @@ async fn poll_recovers_after_error_and_stops_when_consumer_closes() {
failure.delete();
server.mock(|when, then| {
when.method(POST);
then.status(200).json_body(json!({"rows":[]}));
then.status(200).json_body(
json!({"version":"v1","signal":"logs","operation":"search","data":{"rows":[]}}),
);
});
tokio::time::timeout(Duration::from_secs(3), async {
loop {
Expand Down
123 changes: 123 additions & 0 deletions src/query_contract.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
//! Generated from query-api/contracts/client.rs. Run query-api/scripts/sync-query-contract.py.
//! Transport adapter only. Validation, authorization and query execution belong to the API.
use serde::de::DeserializeOwned;
use serde_json::{Value, json};

pub const ENDPOINT: &str = "/api/v1/query/execute";

pub fn adapt(path: &str, body: &Value) -> Option<Value> {
let registry: Value = serde_json::from_str(include_str!("../contracts/query-v1.json")).ok()?;
let route = registry["routes"]
.as_array()?
.iter()
.find(|r| r["path"] == path)?;
let mut options = body.as_object()?.clone();
let time_range = options.remove("time_range")?;
let filters = options.remove("filters").unwrap_or_else(|| json!([]));
let search = options.remove("search").unwrap_or(Value::Null);
let signal = if route["signal"] == "dynamic" {
options.remove(if route["operation"] == "scatter" {
"source"
} else {
"signal"
})?
} else {
route["signal"].clone()
};
Some(
json!({"version":"v1", "signal":signal, "operation":route["operation"],
"time_range":time_range, "filters":filters, "search":search, "options":options}),
)
}

#[allow(dead_code)] // The tail-only CLI does not issue PromQL queries.
pub fn prom_request(path: &str, params: &[(&str, String)]) -> Option<Value> {
if !matches!(path, "/prom/api/v1/query" | "/prom/api/v1/query_range") {
return None;
}
let get = |key: &str| {
params
.iter()
.find(|(k, _)| *k == key)
.map(|(_, v)| v.clone())
};
// Resolve "now" once, so instant queries have an explicit, reproducible evaluation time.
let end = get(if path.ends_with("query_range") {
"end"
} else {
"time"
})
.unwrap_or_else(|| (chrono::Utc::now().timestamp_millis() as f64 / 1000.0).to_string());
let start = get("start").unwrap_or_else(|| end.clone());
let timestamp = |s: &str| {
let seconds = s.parse::<f64>().ok()?;
if !seconds.is_finite() {
return None;
}
chrono::DateTime::from_timestamp_millis((seconds * 1000.0) as i64)
.map(|t| t.to_rfc3339_opts(chrono::SecondsFormat::Millis, true))
};
let mut options = json!({"query": get("query")?});
if let Some(step) = get("step") {
options["step"] = json!(step);
}
Some(json!({"version":"v1", "signal":"metrics",
"operation":if path.ends_with("query_range") { "range" } else { "instant" },
"time_range":{"from":timestamp(&start)?, "to":timestamp(&end)?},
"filters":[], "search":null, "options":options}))
}

/// Reject a wrong version or a response for a different query before decoding data.
pub fn decode<T: DeserializeOwned>(bytes: &[u8], request: &Value) -> Result<T, serde_json::Error> {
let envelope: Value = serde_json::from_slice(bytes)?;
for key in ["version", "signal", "operation"] {
if envelope.get(key) != request.get(key) {
return Err(<serde_json::Error as serde::de::Error>::custom(
"query response contract mismatch",
));
}
}
let data = envelope.get("data").cloned().ok_or_else(|| {
<serde_json::Error as serde::de::Error>::custom("query response is missing data")
})?;
serde_json::from_value(data)
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn shared_fixtures() {
let cases: Value =
serde_json::from_str(include_str!("../contracts/query-v1.fixtures.json")).unwrap();
for c in cases.as_array().unwrap() {
let actual = if let Some(params) = c.get("params") {
let pairs: Vec<_> = params
.as_object()
.unwrap()
.iter()
.map(|(k, v)| (k.as_str(), v.as_str().unwrap().to_string()))
.collect();
prom_request(c["path"].as_str().unwrap(), &pairs)
} else {
adapt(c["path"].as_str().unwrap(), &c["body"])
};
assert_eq!(actual, Some(c["request"].clone()), "{}", c["path"]);
let response = json!({"version":"v1", "signal":c["request"]["signal"],
"operation":c["request"]["operation"], "data":{"rows":[]}, "meta":{}});
assert_eq!(
decode::<Value>(&serde_json::to_vec(&response).unwrap(), &c["request"]).unwrap(),
json!({"rows":[]})
);
}
}

#[test]
fn rejects_wrong_envelopes_and_leaves_mutations_alone() {
assert!(adapt("/api/v1/dashboards", &json!({})).is_none());
let request = json!({"version":"v1", "signal":"logs", "operation":"search"});
assert!(decode::<Value>(br#"{"version":"v2","data":{}}"#, &request).is_err());
assert!(decode::<Value>(br#"{"rows":[]}"#, &request).is_err());
}
}
Loading
Loading