diff --git a/Cargo.lock b/Cargo.lock
index 4404e2199..ad40a02a6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -831,6 +831,19 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
+[[package]]
+name = "clickhouse_http"
+version = "0.1.0"
+dependencies = [
+ "async-trait",
+ "axum",
+ "common",
+ "form_urlencoded",
+ "reqwest",
+ "thiserror 1.0.69",
+ "tokio",
+]
+
[[package]]
name = "cmake"
version = "0.1.58"
@@ -983,8 +996,10 @@ dependencies = [
"asap_sketchlib",
"axum",
"clap",
+ "clickhouse_http",
"common",
"control_plane",
+ "elastic_http",
"flate2",
"form_urlencoded",
"futures",
@@ -1641,6 +1656,19 @@ version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"
+[[package]]
+name = "elastic_http"
+version = "0.1.0"
+dependencies = [
+ "async-trait",
+ "axum",
+ "common",
+ "reqwest",
+ "serde_json",
+ "thiserror 1.0.69",
+ "tokio",
+]
+
[[package]]
name = "enquote"
version = "1.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index a7c0e8fd2..1c533a992 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -4,6 +4,8 @@ members = [
"crates/adapters/ingest/otlp",
"crates/adapters/ingest/prometheus-remote-write",
"crates/adapters/ingest/victoriametrics-remote-write",
+ "crates/adapters/query/clickhouse-http",
+ "crates/adapters/query/elastic-http",
"crates/adapters/query/prometheus-http",
"crates/common",
"crates/control-plane",
@@ -44,8 +46,10 @@ clap = { version = "4.0", features = ["derive", "env"] }
tokio = { version = "1.0", features = ["full"] }
axum = "0.7"
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
+clickhouse_http = { path = "crates/adapters/query/clickhouse-http" }
control_plane = { path = "crates/control-plane" }
common = { path = "crates/common" }
+elastic_http = { path = "crates/adapters/query/elastic-http" }
internal_metrics = { path = "crates/internal-metrics" }
otlp = { path = "crates/adapters/ingest/otlp" }
precompute = { path = "crates/precompute" }
diff --git a/README.md b/README.md
index 3bcbde083..c139f74ad 100644
--- a/README.md
+++ b/README.md
@@ -224,6 +224,16 @@ cost and predicted usage per node and per query. The data facts the plan
assumed are printed. The Planner returns a plan only when its executor
compiles it; otherwise the control plane fails.
+`--clickhouse-url URL` (with `--clickhouse-database`, default `default`)
+serves ClickHouse's query route on ASAPQuery's path, `/clickhouse/query`
+(`query` in the URL or a form), and `--elastic-url URL` (with
+`--elastic-index`) Elasticsearch's, `POST /_sql` and `POST /_search`. Each
+query goes through the plan first; the control plane plans PromQL only, so
+today every one is forwarded to its server with the client's
+`Authorization`, and the server's answer is returned as is
+(`x-asap-execution: forwarded`). Without the flag the routes are not
+served; neither flag can be used with `--no-forward`.
+
`--forward-timeout-seconds` bounds each forwarded query (default 120, matching
Prometheus's default query timeout); a query that runs longer gets 502.
@@ -248,6 +258,8 @@ not stored) with a Prometheus `execution` error (422,
| `crates/adapters/ingest/prometheus-remote-write/` | package `prometheus_remote_write`: Remote Write v1 decoding and validation |
| `crates/adapters/ingest/victoriametrics-remote-write/` | package `victoriametrics_remote_write`: VictoriaMetrics Remote Write (the Remote Write protobuf, zstd-compressed), `POST /api/v1/import` |
| `crates/adapters/ingest/otlp/` | package `otlp`: OTLP/HTTP metrics decoding into samples, `POST /v1/metrics` |
+| `crates/adapters/query/clickhouse-http/` | package `clickhouse_http`: the `query` parameter, TabSeparated bodies and the fallback client of a ClickHouse server, `/clickhouse/query` |
+| `crates/adapters/query/elastic-http/` | package `elastic_http`: `_sql` and `_search` bodies and the fallback client of an Elasticsearch server, `POST /_sql`, `POST /_search` |
| `crates/adapters/query/prometheus-http/` | package `prometheus_http`: query parameters, response bodies and the fallback client of a Prometheus-compatible server |
| `benchmarks/` | the backend alone: `micro/` benchmarks (examples of `data_plane`) and `scripts/` |
| `eval/` | comparisons with other systems and the live demo; see [eval/README.md](eval/README.md) |
diff --git a/crates/adapters/query/clickhouse-http/Cargo.toml b/crates/adapters/query/clickhouse-http/Cargo.toml
new file mode 100644
index 000000000..380da2598
--- /dev/null
+++ b/crates/adapters/query/clickhouse-http/Cargo.toml
@@ -0,0 +1,19 @@
+[package]
+name = "clickhouse_http"
+version.workspace = true
+edition.workspace = true
+
+# ClickHouse's HTTP interface: the query parameter, TabSeparated response
+# bodies, and the fallback client of a ClickHouse server. An adapter: of
+# this workspace it depends on `common` only, never on an engine or a store.
+[dependencies]
+common.workspace = true
+# `common::FallbackClient`'s async method.
+async-trait.workspace = true
+form_urlencoded = "1"
+reqwest.workspace = true
+thiserror.workspace = true
+
+[dev-dependencies]
+axum.workspace = true
+tokio.workspace = true
diff --git a/crates/adapters/query/clickhouse-http/src/fallback.rs b/crates/adapters/query/clickhouse-http/src/fallback.rs
new file mode 100644
index 000000000..ab1a18b4d
--- /dev/null
+++ b/crates/adapters/query/clickhouse-http/src/fallback.rs
@@ -0,0 +1,235 @@
+//! The client of a ClickHouse server that answers the queries the data
+//! plane does not, as ASAPQuery's `ClickHouseHttpFallback` sends them.
+
+use std::time::Duration;
+
+use async_trait::async_trait;
+use common::{
+ FallbackClient, FallbackError, FallbackResponse, QueryEval, QueryLanguage, QueryRequest,
+ SqlDialect,
+};
+use reqwest::header::{self, HeaderName, HeaderValue};
+
+/// Sends queries to one ClickHouse server's HTTP interface.
+pub struct ClickHouseHttpFallback {
+ /// `/?database=`, where every query is posted.
+ query_url: String,
+ client: reqwest::Client,
+}
+
+impl ClickHouseHttpFallback {
+ /// A client of the server at `base_url` that runs queries in
+ /// `database`, each request bounded by `timeout`, from sending it to
+ /// reading the whole response.
+ pub fn new(base_url: &str, database: &str, timeout: Duration) -> Self {
+ let database: String = form_urlencoded::byte_serialize(database.as_bytes()).collect();
+ Self {
+ query_url: format!("{}/?database={database}", base_url.trim_end_matches('/')),
+ client: reqwest::Client::builder()
+ .timeout(timeout)
+ .build()
+ .expect("reqwest client with only a timeout set"),
+ }
+ }
+}
+
+#[async_trait]
+impl FallbackClient for ClickHouseHttpFallback {
+ /// `POST /?database=` with the query as the body, so the
+ /// server answers in its default format (TabSeparated) unless the
+ /// query names one. A ClickHouse SQL instant query only: ClickHouse has
+ /// no range queries. Header pairs that are not valid HTTP headers are
+ /// skipped.
+ async fn execute(
+ &self,
+ request: &QueryRequest,
+ headers: &[(String, String)],
+ ) -> Result {
+ if request.language != QueryLanguage::SQL(SqlDialect::ClickhouseSQL) {
+ return Err(FallbackError::new(format!(
+ "a ClickHouse server answers ClickHouse SQL, not {:?}",
+ request.language
+ )));
+ }
+ if let QueryEval::Range { .. } = request.eval {
+ return Err(FallbackError::new("ClickHouse has no range queries"));
+ }
+ let mut upstream = self.client.post(&self.query_url);
+ for (name, value) in headers {
+ if let (Ok(name), Ok(value)) = (
+ HeaderName::try_from(name.as_str()),
+ HeaderValue::try_from(value.as_str()),
+ ) {
+ upstream = upstream.header(name, value);
+ }
+ }
+ let upstream = upstream
+ .body(request.query.clone())
+ .send()
+ .await
+ .map_err(|error| FallbackError::new(format!("forwarding to ClickHouse: {error}")))?;
+ let status_code = upstream.status().as_u16();
+ // A server that names no type sent bytes of unknown type (RFC 9110
+ // section 8.3).
+ let content_type = upstream
+ .headers()
+ .get(header::CONTENT_TYPE)
+ .and_then(|value| value.to_str().ok())
+ .unwrap_or("application/octet-stream")
+ .to_string();
+ let body = upstream
+ .bytes()
+ .await
+ .map_err(|error| FallbackError::new(format!("reading ClickHouse response: {error}")))?;
+ Ok(FallbackResponse {
+ status_code,
+ content_type,
+ body: body.into(),
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::sync::{Arc, Mutex};
+
+ use axum::extract::{OriginalUri, State};
+ use axum::http::{HeaderMap, StatusCode};
+ use axum::routing::post;
+ use axum::Router;
+
+ use super::*;
+
+ /// What the mock server received: path and query, `Authorization`, body.
+ type Received = Arc, String)>>>;
+
+ /// A ClickHouse server that records each request and answers 200 with
+ /// a TabSeparated row, or, for a query on `missing`, 404 with
+ /// ClickHouse's plain-text exception; its base URL.
+ async fn server(received: Received) -> String {
+ async fn record(
+ State(received): State,
+ OriginalUri(uri): OriginalUri,
+ headers: HeaderMap,
+ body: String,
+ ) -> (StatusCode, [(header::HeaderName, &'static str); 1], String) {
+ let authorization = headers
+ .get(header::AUTHORIZATION)
+ .map(|v| v.to_str().unwrap().to_string());
+ let missing = body.contains("missing");
+ received
+ .lock()
+ .unwrap()
+ .push((uri.to_string(), authorization, body));
+ if missing {
+ return (
+ StatusCode::NOT_FOUND,
+ [(header::CONTENT_TYPE, "text/plain; charset=UTF-8")],
+ "Code: 60. DB::Exception: Table default.missing does not exist.".into(),
+ );
+ }
+ (
+ StatusCode::OK,
+ [(
+ header::CONTENT_TYPE,
+ "text/tab-separated-values; charset=UTF-8",
+ )],
+ "1\n".into(),
+ )
+ }
+ let app = Router::new().route("/", post(record)).with_state(received);
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ format!("http://{address}/")
+ }
+
+ fn request(query: &str) -> QueryRequest {
+ QueryRequest {
+ language: QueryLanguage::SQL(SqlDialect::ClickhouseSQL),
+ query: query.into(),
+ eval: QueryEval::Instant { time_ms: 0 },
+ }
+ }
+
+ /// From ASAPQuery's `test_execute_query_success` and
+ /// `test_url_with_database_param`: the query is posted as the body to
+ /// `/?database=` with the client's headers, and the server's
+ /// status, `Content-Type` and body come back unchanged, an exception
+ /// included (`test_execute_query_error_response`).
+ #[tokio::test]
+ async fn posts_the_query_and_returns_the_response_unchanged() {
+ let received = Received::default();
+ let fallback = ClickHouseHttpFallback::new(
+ &server(received.clone()).await,
+ "test db",
+ Duration::from_secs(5),
+ );
+ let headers = [("Authorization".to_string(), "Basic dTpw".to_string())];
+ let response = fallback
+ .execute(&request("SELECT 1"), &headers)
+ .await
+ .unwrap();
+ assert_eq!(
+ response,
+ FallbackResponse {
+ status_code: 200,
+ content_type: "text/tab-separated-values; charset=UTF-8".into(),
+ body: b"1\n".to_vec(),
+ }
+ );
+ let error = fallback
+ .execute(&request("SELECT * FROM missing"), &[])
+ .await
+ .unwrap();
+ assert_eq!(error.status_code, 404);
+ assert_eq!(
+ error.body,
+ b"Code: 60. DB::Exception: Table default.missing does not exist."
+ );
+ let received = received.lock().unwrap();
+ assert_eq!(
+ received[0],
+ (
+ "/?database=test+db".to_string(),
+ Some("Basic dTpw".to_string()),
+ "SELECT 1".to_string()
+ )
+ );
+ assert_eq!(received[1].1, None);
+ }
+
+ /// A range query (ASAPQuery's `test_range_query_not_implemented`) or a
+ /// query in another language is not sent; an unreachable server
+ /// (`test_clickhouse_server_unreachable`) is an error.
+ #[tokio::test]
+ async fn refuses_what_clickhouse_cannot_answer_and_reports_an_unreachable_server() {
+ let fallback =
+ ClickHouseHttpFallback::new("http://127.0.0.1:1", "default", Duration::from_secs(5));
+ let range = QueryRequest {
+ eval: QueryEval::Range {
+ start_ms: 0,
+ end_ms: 60_000,
+ step_ms: 15_000,
+ },
+ ..request("SELECT 1")
+ };
+ assert_eq!(
+ fallback.execute(&range, &[]).await,
+ Err(FallbackError::new("ClickHouse has no range queries"))
+ );
+ let promql = QueryRequest {
+ language: QueryLanguage::PromQL,
+ ..request("up")
+ };
+ assert!(fallback.execute(&promql, &[]).await.is_err());
+ let error = fallback
+ .execute(&request("SELECT 1"), &[])
+ .await
+ .unwrap_err();
+ assert!(
+ error.message.starts_with("forwarding to ClickHouse: "),
+ "{error}"
+ );
+ }
+}
diff --git a/crates/adapters/query/clickhouse-http/src/lib.rs b/crates/adapters/query/clickhouse-http/src/lib.rs
new file mode 100644
index 000000000..1bbab6a47
--- /dev/null
+++ b/crates/adapters/query/clickhouse-http/src/lib.rs
@@ -0,0 +1,237 @@
+//! ClickHouse's HTTP interface as the data plane speaks it, on ASAPQuery's
+//! route (`/clickhouse/query`): the query, TabSeparated result
+//! bodies, and the [`fallback`] client that sends a query the data plane
+//! does not answer to a ClickHouse server. An adapter: it depends on
+//! `common` only.
+
+use std::collections::BTreeSet;
+use std::io::Write as _;
+
+use common::{QueryEval, QueryLanguage, QueryRequest, QueryResult, SqlDialect, TableValue};
+
+pub mod fallback;
+
+/// The request has no query (400).
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+#[error("missing parameter \"query\"")]
+pub struct MissingQuery;
+
+/// The `Content-Type` of a TabSeparated body, as ClickHouse sends it.
+pub const TAB_SEPARATED_CONTENT_TYPE: &str = "text/tab-separated-values; charset=UTF-8";
+
+/// The ClickHouse SQL query of a request, evaluated at `now_ms` (ClickHouse
+/// queries name no evaluation time): the `query` parameter of the URL query
+/// or of a form body, else, as ASAPQuery reads it, the whole body (the
+/// ClickHouse HTTP interface's plain SQL `POST`).
+pub fn parse_query(
+ url_query: Option<&str>,
+ body: &[u8],
+ now_ms: i64,
+) -> Result {
+ let parameter = form_urlencoded::parse(url_query.unwrap_or_default().as_bytes())
+ .chain(form_urlencoded::parse(body))
+ .find(|(name, _)| name == "query");
+ let query = match parameter {
+ Some((_, query)) => query.into_owned(),
+ None if !body.is_empty() => std::str::from_utf8(body)
+ .map_err(|_| MissingQuery)?
+ .to_string(),
+ None => return Err(MissingQuery),
+ };
+ Ok(QueryRequest {
+ language: QueryLanguage::SQL(SqlDialect::ClickhouseSQL),
+ query,
+ eval: QueryEval::Instant { time_ms: now_ms },
+ })
+}
+
+/// A result a TabSeparated body cannot hold (a range or a scalar).
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+#[error("a ClickHouse response cannot hold a {0} result")]
+pub struct UnsupportedResult(&'static str);
+
+/// `result` in ClickHouse's default format, TabSeparated: one line per row,
+/// values separated by tabs, with `\`, tab, newline, carriage return and
+/// NUL escaped. A table
+/// writes its rows; an instant vector one row per series: its label values
+/// (every label any series has, by name; empty where it has none), then its
+/// value.
+pub fn tab_separated(result: &QueryResult) -> Result, UnsupportedResult> {
+ let mut body = Vec::new();
+ match result {
+ QueryResult::Table(table) => {
+ for row in &table.rows {
+ for (index, cell) in row.iter().enumerate() {
+ if index > 0 {
+ body.push(b'\t');
+ }
+ match cell {
+ TableValue::String(text) => write_escaped(&mut body, text),
+ TableValue::Float(value) => write_float(&mut body, *value),
+ }
+ }
+ body.push(b'\n');
+ }
+ }
+ QueryResult::Vector(vector) => {
+ let names: BTreeSet<&String> = vector
+ .series
+ .iter()
+ .flat_map(|series| series.labels.keys())
+ .collect();
+ for series in &vector.series {
+ for name in &names {
+ write_escaped(
+ &mut body,
+ series.labels.get(*name).map_or("", String::as_str),
+ );
+ body.push(b'\t');
+ }
+ write_float(&mut body, series.value);
+ body.push(b'\n');
+ }
+ }
+ QueryResult::Matrix(_) => return Err(UnsupportedResult("range")),
+ QueryResult::Scalar(_) => return Err(UnsupportedResult("scalar")),
+ }
+ Ok(body)
+}
+
+/// TabSeparated's escapes for the characters that end a value or a row.
+fn write_escaped(body: &mut Vec, text: &str) {
+ for byte in text.bytes() {
+ match byte {
+ b'\\' => body.extend_from_slice(b"\\\\"),
+ b'\t' => body.extend_from_slice(b"\\t"),
+ b'\n' => body.extend_from_slice(b"\\n"),
+ b'\r' => body.extend_from_slice(b"\\r"),
+ b'\0' => body.extend_from_slice(b"\\0"),
+ _ => body.push(byte),
+ }
+ }
+}
+
+/// As ClickHouse writes a `Float64`: shortest round-trip digits, `nan`,
+/// `inf` and `-inf`.
+fn write_float(body: &mut Vec, value: f64) {
+ if value.is_nan() {
+ body.extend_from_slice(b"nan");
+ } else if value.is_infinite() {
+ body.extend_from_slice(if value > 0.0 { b"inf" } else { b"-inf" });
+ } else {
+ write!(body, "{value}").expect("writing to a Vec does not fail");
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use common::{InstantVector, InstantVectorElement, LabelSet, RangeVector, Table};
+
+ use super::*;
+
+ fn clickhouse(query: &str, now_ms: i64) -> QueryRequest {
+ QueryRequest {
+ language: QueryLanguage::SQL(SqlDialect::ClickhouseSQL),
+ query: query.into(),
+ eval: QueryEval::Instant { time_ms: now_ms },
+ }
+ }
+
+ /// From ASAPQuery's `test_parse_get_request`, `test_parse_post_request_form`
+ /// and `test_missing_query_parameter`: the query comes from the URL
+ /// query, the form body or the plain body and is evaluated now; without
+ /// one the request is refused.
+ #[test]
+ fn parses_the_query_parameter() {
+ assert_eq!(
+ parse_query(Some("query=SELECT%201"), b"", 7),
+ Ok(clickhouse("SELECT 1", 7))
+ );
+ assert_eq!(
+ parse_query(None, b"query=SELECT+*+FROM+table", 7),
+ Ok(clickhouse("SELECT * FROM table", 7))
+ );
+ assert_eq!(
+ parse_query(None, b"SELECT count() FROM t WHERE a=1", 7),
+ Ok(clickhouse("SELECT count() FROM t WHERE a=1", 7))
+ );
+ assert_eq!(parse_query(Some("database=d"), b"", 7), Err(MissingQuery));
+ assert_eq!(parse_query(None, b"\xff", 7), Err(MissingQuery));
+ assert_eq!(MissingQuery.to_string(), "missing parameter \"query\"");
+ }
+
+ /// ASAPQuery's `test_format_success_response`: one row per series, its
+ /// label values then its value.
+ #[test]
+ fn writes_an_instant_vector_as_rows() {
+ let series = |host: &str, value| InstantVectorElement {
+ labels: LabelSet::from([("hostname".to_string(), host.to_string())]),
+ value,
+ };
+ let result = QueryResult::Vector(InstantVector {
+ timestamp_ms: 1000,
+ series: vec![series("host1", 91.0), series("host2", 77.5)],
+ });
+ assert_eq!(tab_separated(&result).unwrap(), b"host1\t91\nhost2\t77.5\n");
+ }
+
+ /// A table writes its rows in column order, with values escaped and
+ /// floats as ClickHouse writes them; a series lacking a label another
+ /// has gets an empty value there.
+ #[test]
+ fn writes_tables_and_escapes_values() {
+ let table = QueryResult::Table(Table {
+ columns: vec!["job".into(), "p99".into()],
+ rows: vec![
+ vec![
+ TableValue::String("a\tb\\c\nd".into()),
+ TableValue::Float(0.25),
+ ],
+ vec![TableValue::String("e".into()), TableValue::Float(f64::NAN)],
+ vec![
+ TableValue::String("f".into()),
+ TableValue::Float(f64::NEG_INFINITY),
+ ],
+ ],
+ });
+ assert_eq!(
+ tab_separated(&table).unwrap(),
+ b"a\\tb\\\\c\\nd\t0.25\ne\tnan\nf\t-inf\n"
+ );
+ let labels = |pairs: &[(&str, &str)]| -> LabelSet {
+ pairs
+ .iter()
+ .map(|(n, v)| (n.to_string(), v.to_string()))
+ .collect()
+ };
+ let vector = QueryResult::Vector(InstantVector {
+ timestamp_ms: 0,
+ series: vec![
+ InstantVectorElement {
+ labels: labels(&[("a", "1"), ("b", "2")]),
+ value: 1.0,
+ },
+ InstantVectorElement {
+ labels: labels(&[("b", "3")]),
+ value: 2.0,
+ },
+ ],
+ });
+ assert_eq!(tab_separated(&vector).unwrap(), b"1\t2\t1\n\t3\t2\n");
+ }
+
+ /// Ranges and scalars have no ClickHouse form (ASAPQuery answered 501).
+ #[test]
+ fn refuses_ranges_and_scalars() {
+ let range = QueryResult::Matrix(RangeVector { series: vec![] });
+ assert_eq!(
+ tab_separated(&range).unwrap_err().to_string(),
+ "a ClickHouse response cannot hold a range result"
+ );
+ let scalar = QueryResult::Scalar(common::Sample {
+ timestamp_ms: 0,
+ value: 1.0,
+ });
+ assert!(tab_separated(&scalar).is_err());
+ }
+}
diff --git a/crates/adapters/query/elastic-http/Cargo.toml b/crates/adapters/query/elastic-http/Cargo.toml
new file mode 100644
index 000000000..10cda72df
--- /dev/null
+++ b/crates/adapters/query/elastic-http/Cargo.toml
@@ -0,0 +1,20 @@
+[package]
+name = "elastic_http"
+version.workspace = true
+edition.workspace = true
+
+# Elasticsearch's `_sql` and `_search` HTTP APIs: request bodies, `_search`
+# response bodies, and the fallback client of an Elasticsearch server. An
+# adapter: of this workspace it depends on `common` only, never on an
+# engine or a store.
+[dependencies]
+common.workspace = true
+# `common::FallbackClient`'s async method.
+async-trait.workspace = true
+reqwest.workspace = true
+serde_json.workspace = true
+thiserror.workspace = true
+
+[dev-dependencies]
+axum.workspace = true
+tokio.workspace = true
diff --git a/crates/adapters/query/elastic-http/src/fallback.rs b/crates/adapters/query/elastic-http/src/fallback.rs
new file mode 100644
index 000000000..0f1479dd5
--- /dev/null
+++ b/crates/adapters/query/elastic-http/src/fallback.rs
@@ -0,0 +1,257 @@
+//! The client of an Elasticsearch server that answers the queries the data
+//! plane does not, as ASAPQuery's `ElasticHttpFallback` sends them.
+
+use std::time::Duration;
+
+use async_trait::async_trait;
+use common::{
+ FallbackClient, FallbackError, FallbackResponse, QueryEval, QueryLanguage, QueryRequest,
+ SqlDialect,
+};
+use reqwest::header::{self, HeaderName, HeaderValue};
+
+/// Rows per page an Elasticsearch SQL query asks for, as ASAPQuery asks.
+const SQL_FETCH_SIZE: u64 = 1000;
+
+/// Sends queries to one Elasticsearch server.
+pub struct ElasticHttpFallback {
+ /// Without a trailing `/`.
+ base_url: String,
+ /// The index (or index pattern) a Query DSL search reads; empty: every
+ /// index (`/_search`).
+ index: String,
+ client: reqwest::Client,
+}
+
+impl ElasticHttpFallback {
+ /// A client of the server at `base_url` whose Query DSL searches read
+ /// `index`, each request bounded by `timeout`, from sending it to
+ /// reading the whole response.
+ pub fn new(base_url: &str, index: &str, timeout: Duration) -> Self {
+ Self {
+ base_url: base_url.trim_end_matches('/').to_string(),
+ index: index.to_string(),
+ client: reqwest::Client::builder()
+ .timeout(timeout)
+ .build()
+ .expect("reqwest client with only a timeout set"),
+ }
+ }
+}
+
+#[async_trait]
+impl FallbackClient for ElasticHttpFallback {
+ /// Elasticsearch SQL: `POST /_sql` with `{"query", "fetch_size"}`, the
+ /// query without a trailing `;`. Query DSL: `POST //_search`
+ /// with the query as the body. Instant queries only: Elasticsearch has
+ /// no range queries. Header pairs that are not valid HTTP headers are
+ /// skipped.
+ async fn execute(
+ &self,
+ request: &QueryRequest,
+ headers: &[(String, String)],
+ ) -> Result {
+ if let QueryEval::Range { .. } = request.eval {
+ return Err(FallbackError::new("Elasticsearch has no range queries"));
+ }
+ let (url, body) = match &request.language {
+ QueryLanguage::SQL(SqlDialect::ElasticSQL) => {
+ let body = serde_json::json!({
+ "query": request.query.trim().trim_end_matches(';'),
+ "fetch_size": SQL_FETCH_SIZE,
+ });
+ (format!("{}/_sql", self.base_url), body.to_string())
+ }
+ QueryLanguage::ElasticDSL if self.index.is_empty() => {
+ (format!("{}/_search", self.base_url), request.query.clone())
+ }
+ QueryLanguage::ElasticDSL => (
+ format!("{}/{}/_search", self.base_url, self.index),
+ request.query.clone(),
+ ),
+ language => {
+ let message =
+ format!("Elasticsearch answers its SQL and Query DSL, not {language:?}");
+ return Err(FallbackError::new(message));
+ }
+ };
+ let mut upstream = self
+ .client
+ .post(url)
+ .header(header::CONTENT_TYPE, "application/json");
+ for (name, value) in headers {
+ if let (Ok(name), Ok(value)) = (
+ HeaderName::try_from(name.as_str()),
+ HeaderValue::try_from(value.as_str()),
+ ) {
+ upstream = upstream.header(name, value);
+ }
+ }
+ let upstream =
+ upstream.body(body).send().await.map_err(|error| {
+ FallbackError::new(format!("forwarding to Elasticsearch: {error}"))
+ })?;
+ let status_code = upstream.status().as_u16();
+ // A server that names no type sent bytes of unknown type (RFC 9110
+ // section 8.3).
+ let content_type = upstream
+ .headers()
+ .get(header::CONTENT_TYPE)
+ .and_then(|value| value.to_str().ok())
+ .unwrap_or("application/octet-stream")
+ .to_string();
+ let body = upstream.bytes().await.map_err(|error| {
+ FallbackError::new(format!("reading Elasticsearch response: {error}"))
+ })?;
+ Ok(FallbackResponse {
+ status_code,
+ content_type,
+ body: body.into(),
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::sync::{Arc, Mutex};
+
+ use axum::extract::{OriginalUri, State};
+ use axum::http::HeaderMap;
+ use axum::routing::post;
+ use axum::Router;
+
+ use super::*;
+
+ /// What the mock server received: path, `Content-Type`,
+ /// `Authorization`, body.
+ type Received = Arc, String)>>>;
+
+ /// An Elasticsearch server that records each request and answers 200
+ /// with a JSON body naming its path; its base URL.
+ async fn server(received: Received) -> String {
+ async fn record(
+ State(received): State,
+ OriginalUri(uri): OriginalUri,
+ headers: HeaderMap,
+ body: String,
+ ) -> ([(header::HeaderName, &'static str); 1], String) {
+ let header = |name| {
+ headers
+ .get(name)
+ .map(|v: &HeaderValue| v.to_str().unwrap().to_string())
+ };
+ received.lock().unwrap().push((
+ uri.to_string(),
+ header(header::CONTENT_TYPE).unwrap_or_default(),
+ header(header::AUTHORIZATION),
+ body,
+ ));
+ (
+ [(header::CONTENT_TYPE, "application/json")],
+ format!("{{\"path\":\"{}\"}}", uri.path()),
+ )
+ }
+ let app = Router::new()
+ .route("/_sql", post(record))
+ .route("/_search", post(record))
+ .route("/:index/_search", post(record))
+ .with_state(received);
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ format!("http://{address}/")
+ }
+
+ fn request(language: QueryLanguage, query: &str) -> QueryRequest {
+ QueryRequest {
+ language,
+ query: query.into(),
+ eval: QueryEval::Instant { time_ms: 0 },
+ }
+ }
+
+ /// An SQL query is posted to `/_sql` wrapped with ASAPQuery's fetch
+ /// size and without its `;`; a Query DSL query to the index's
+ /// `_search` (or `/_search` with no index) as sent; both as JSON with
+ /// the client's `Authorization`. The server's response comes back
+ /// unchanged.
+ #[tokio::test]
+ async fn posts_sql_and_query_dsl_and_returns_the_response_unchanged() {
+ let received = Received::default();
+ let url = server(received.clone()).await;
+ let fallback = ElasticHttpFallback::new(&url, "logs-*", Duration::from_secs(5));
+ let headers = [("Authorization".to_string(), "ApiKey k".to_string())];
+ let sql = request(
+ QueryLanguage::SQL(SqlDialect::ElasticSQL),
+ " SELECT COUNT(*) FROM logs; ",
+ );
+ let response = fallback.execute(&sql, &headers).await.unwrap();
+ assert_eq!(
+ response,
+ FallbackResponse {
+ status_code: 200,
+ content_type: "application/json".into(),
+ body: br#"{"path":"/_sql"}"#.to_vec(),
+ }
+ );
+ let search = r#"{"query": {"match_all": {}}}"#;
+ fallback
+ .execute(&request(QueryLanguage::ElasticDSL, search), &[])
+ .await
+ .unwrap();
+ ElasticHttpFallback::new(&url, "", Duration::from_secs(5))
+ .execute(&request(QueryLanguage::ElasticDSL, search), &[])
+ .await
+ .unwrap();
+ let received = received.lock().unwrap();
+ let json = "application/json".to_string();
+ let (path, content_type, authorization, body) = &received[0];
+ assert_eq!(
+ (path.as_str(), content_type, authorization.as_deref()),
+ ("/_sql", &json, Some("ApiKey k"))
+ );
+ assert_eq!(
+ serde_json::from_str::(body).unwrap(),
+ serde_json::json!({"query": "SELECT COUNT(*) FROM logs", "fetch_size": 1000})
+ );
+ assert_eq!(
+ received[1],
+ (
+ "/logs-*/_search".to_string(),
+ json.clone(),
+ None,
+ search.to_string()
+ )
+ );
+ assert_eq!(received[2].0, "/_search");
+ }
+
+ /// A range query or a query in another language is not sent; an
+ /// unreachable server is an error.
+ #[tokio::test]
+ async fn refuses_what_elasticsearch_cannot_answer_and_reports_an_unreachable_server() {
+ let fallback = ElasticHttpFallback::new("http://127.0.0.1:1", "", Duration::from_secs(5));
+ let range = QueryRequest {
+ eval: QueryEval::Range {
+ start_ms: 0,
+ end_ms: 60_000,
+ step_ms: 15_000,
+ },
+ ..request(QueryLanguage::ElasticDSL, "{}")
+ };
+ assert_eq!(
+ fallback.execute(&range, &[]).await,
+ Err(FallbackError::new("Elasticsearch has no range queries"))
+ );
+ let clickhouse = request(QueryLanguage::SQL(SqlDialect::ClickhouseSQL), "SELECT 1");
+ assert!(fallback.execute(&clickhouse, &[]).await.is_err());
+ let error = fallback
+ .execute(&request(QueryLanguage::ElasticDSL, "{}"), &[])
+ .await
+ .unwrap_err();
+ assert!(
+ error.message.starts_with("forwarding to Elasticsearch: "),
+ "{error}"
+ );
+ }
+}
diff --git a/crates/adapters/query/elastic-http/src/lib.rs b/crates/adapters/query/elastic-http/src/lib.rs
new file mode 100644
index 000000000..c4d38a226
--- /dev/null
+++ b/crates/adapters/query/elastic-http/src/lib.rs
@@ -0,0 +1,194 @@
+//! Elasticsearch's HTTP query APIs as the data plane speaks them, on
+//! ASAPQuery's routes: `POST /_sql` (Elasticsearch SQL) and `POST /_search`
+//! (Query DSL) request bodies, `_search` response and error bodies, and the
+//! [`fallback`] client that sends a query the data plane does not answer to
+//! an Elasticsearch server. An adapter: it depends on `common` only.
+
+use common::{QueryEval, QueryLanguage, QueryRequest, QueryResult, SqlDialect};
+use serde_json::{json, Map, Value};
+
+pub mod fallback;
+
+/// A request body that is not the query its endpoint takes: the reason.
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+#[error("{0}")]
+pub struct BadRequestBody(String);
+
+impl BadRequestBody {
+ /// The 400 body: a `parsing_exception` with the reason.
+ pub fn error_body(&self) -> Value {
+ error_body("parsing_exception", &self.0)
+ }
+}
+
+/// The 400 body refusing a `GET`, ASAPQuery's reason: Elasticsearch
+/// queries are posted as JSON.
+pub fn get_refused_body() -> Value {
+ let reason = "GET requests not supported for Elasticsearch queries. Use POST with Query DSL.";
+ error_body("illegal_argument_exception", reason)
+}
+
+/// The `query` string of a `_sql` body (`{"query": "SELECT …", …}`; other
+/// fields such as `time_zone` are not kept), evaluated at `now_ms`:
+/// Elasticsearch queries name no evaluation time.
+pub fn parse_sql(body: &[u8], now_ms: i64) -> Result {
+ let body: Value = serde_json::from_slice(body)
+ .map_err(|error| BadRequestBody(format!("Invalid JSON: {error}")))?;
+ let query = body
+ .get("query")
+ .and_then(Value::as_str)
+ .ok_or_else(|| BadRequestBody("missing parameter \"query\"".into()))?;
+ Ok(QueryRequest {
+ language: QueryLanguage::SQL(SqlDialect::ElasticSQL),
+ query: query.to_string(),
+ eval: QueryEval::Instant { time_ms: now_ms },
+ })
+}
+
+/// A `_search` body, a Query DSL JSON object, kept as sent (the fallback
+/// sends these bytes), evaluated at `now_ms`.
+pub fn parse_search(body: &[u8], now_ms: i64) -> Result {
+ let query = std::str::from_utf8(body)
+ .map_err(|error| BadRequestBody(format!("Invalid JSON: {error}")))?;
+ serde_json::from_str::