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
5 changes: 5 additions & 0 deletions .github/workflows/security.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ on:
- "Cargo.toml"
- "Cargo.lock"
- "rust-toolchain.toml"
- "contracts/**"
- "scripts/sync-query-contract.py"
schedule:
- cron: "17 9 * * 1"
workflow_dispatch:
Expand Down Expand Up @@ -49,6 +51,9 @@ jobs:
- name: Check formatting
run: cargo fmt --check

- name: Check generated query schema
run: python3 scripts/sync-query-contract.py --check

- name: Run Clippy
run: cargo clippy --all-targets --all-features -- -D clippy::correctness -D clippy::suspicious

Expand Down
1 change: 1 addition & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ RUN apt-get update && apt-get install -y pkg-config libssl-dev build-essential c
WORKDIR /app
COPY Cargo.toml Cargo.lock ./
COPY src ./src
COPY contracts ./contracts

RUN cargo build --locked --release --no-default-features --features oss

Expand Down
123 changes: 123 additions & 0 deletions contracts/client.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());
}
}
48 changes: 48 additions & 0 deletions contracts/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Generated from query-api/contracts/client.ts. Run query-api/scripts/sync-query-contract.py.
import registry from '../../contracts/query-v1.json'

export const QUERY_ENDPOINT = '/query/execute'
export interface UnifiedQuery {
version: 'v1'
signal: string
operation: string
time_range: { from: string; to: string }
filters: unknown[]
search: string | null
options: Record<string, unknown>
}

/** Preserve legacy call signatures at the UI boundary, not on the wire. */
export function adaptQuery(path: string, body: Record<string, unknown>): UnifiedQuery | undefined {
const fullPath = path.startsWith('/api/v1/') ? path : `/api/v1${path}`
const route = registry.routes.find(r => r.path === fullPath)
if (!route || !body.time_range) return undefined
const { time_range, filters = [], search = null, ...options } = body
let signal = route.signal
if (signal === 'dynamic') {
const key = route.operation === 'scatter' ? 'source' : 'signal'
signal = String(options[key])
delete options[key]
}
return { version: 'v1', signal, operation: route.operation,
time_range: time_range as UnifiedQuery['time_range'], filters: filters as unknown[],
search: search as string | null, options }
}

export function metricsQuery(query: string, start: number, end: number, step?: number): UnifiedQuery {
const options: Record<string, unknown> = { query }
if (step !== undefined) options.step = String(step)
return { version: 'v1', signal: 'metrics', operation: step === undefined ? 'instant' : 'range',
time_range: { from: new Date(start * 1000).toISOString(), to: new Date(end * 1000).toISOString() },
filters: [], search: null, options }
}

export function decodeQuery<T>(envelope: unknown, request: UnifiedQuery): T {
if (!envelope || typeof envelope !== 'object') throw new Error('Invalid query response')
const result = envelope as Record<string, unknown>
if (result.version !== request.version || result.signal !== request.signal
|| result.operation !== request.operation || !Object.hasOwn(result, 'data')) {
throw new Error('Query response contract mismatch. Check your API version.')
}
return result.data as T
}
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"]}
]
}
Loading
Loading