Elffuss BraidHub

kikocis/utopia public

dev · 8.9 KiBRawPermalink
1//! Trino(旧名 Presto):REST 协议 `POST /v1/statement`,然后沿 `nextUri` 一页页取。
2//! 一个引擎顶起整个湖仓——Iceberg / Delta / Hive / Hudi 都是它的 catalog,
3//! 换格式不换协议。Starburst 同协议。
4//!
5//! 没有会话可设只读:超时靠 `X-Trino-Session: query_max_execution_time`,
6//! 只读靠 `guard_sql_for`。
7
8use super::conn::TrinoConn;
9use super::{
10 rows_to_json_lines, sql_literal, truncate_rows, wrap_limit, QueryEngine, QueryResult,
11 SchemaColumn, HTTP_POLL_BUDGET, STATEMENT_TIMEOUT_SECS,
12};
13use base64::Engine as _;
14use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION};
15use serde::Deserialize;
16use std::time::Instant;
17
18pub struct TrinoEngine {
19 conn: TrinoConn,
20}
21
22#[derive(Deserialize)]
23struct Column {
24 name: String,
25}
26
27#[derive(Deserialize)]
28struct Page {
29 #[serde(rename = "nextUri")]
30 next_uri: Option<String>,
31 columns: Option<Vec<Column>>,
32 data: Option<Vec<Vec<serde_json::Value>>>,
33 error: Option<TrinoError>,
34}
35
36#[derive(Deserialize)]
37struct TrinoError {
38 message: String,
39 #[serde(rename = "errorName")]
40 error_name: Option<String>,
41}
42
43impl TrinoEngine {
44 pub fn new(conn: TrinoConn) -> Self {
45 Self { conn }
46 }
47
48 fn headers(&self) -> anyhow::Result<HeaderMap> {
49 let mut h = HeaderMap::new();
50 h.insert("X-Trino-User", HeaderValue::from_str(&self.conn.user)?);
51 h.insert("X-Trino-Source", HeaderValue::from_static("utopia"));
52 h.insert(
53 "X-Trino-Session",
54 HeaderValue::from_str(&format!(
55 "query_max_execution_time={STATEMENT_TIMEOUT_SECS}s"
56 ))?,
57 );
58 if let Some(c) = &self.conn.catalog {
59 h.insert("X-Trino-Catalog", HeaderValue::from_str(c)?);
60 }
61 if let Some(s) = &self.conn.schema {
62 h.insert("X-Trino-Schema", HeaderValue::from_str(s)?);
63 }
64 if let Some(p) = &self.conn.password {
65 let raw = format!("{}:{p}", self.conn.user);
66 let token = base64::engine::general_purpose::STANDARD.encode(raw);
67 h.insert(
68 AUTHORIZATION,
69 HeaderValue::from_str(&format!("Basic {token}"))?,
70 );
71 }
72 Ok(h)
73 }
74
75 /// 提交并沿 nextUri 收完:列在第一个带 columns 的页上,数据分页累积
76 async fn run(&self, sql: &str) -> anyhow::Result<(Vec<String>, Vec<Vec<serde_json::Value>>)> {
77 let client = super::http()?;
78 let headers = self.headers()?;
79 let mut page: Page = client
80 .post(format!("{}/v1/statement", self.conn.base))
81 .headers(headers.clone())
82 .body(sql.to_string())
83 .send()
84 .await?
85 .error_for_status()?
86 .json()
87 .await?;
88 let started = Instant::now();
89 let mut columns: Option<Vec<String>> = None;
90 let mut rows = Vec::new();
91 loop {
92 if let Some(e) = page.error {
93 let name = e.error_name.map(|n| format!("{n}: ")).unwrap_or_default();
94 anyhow::bail!("{name}{}", e.message);
95 }
96 if columns.is_none() {
97 columns = page
98 .columns
99 .take()
100 .map(|cs| cs.into_iter().map(|c| c.name).collect());
101 }
102 if let Some(d) = page.data.take() {
103 rows.extend(d);
104 }
105 let Some(next) = page.next_uri.take() else {
106 break;
107 };
108 if started.elapsed() > HTTP_POLL_BUDGET {
109 anyhow::bail!(
110 "Trino query did not finish within {}s",
111 HTTP_POLL_BUDGET.as_secs()
112 );
113 }
114 page = client
115 .get(&next)
116 .headers(headers.clone())
117 .send()
118 .await?
119 .error_for_status()?
120 .json()
121 .await?;
122 }
123 Ok((columns.unwrap_or_default(), rows))
124 }
125}
126
127#[async_trait::async_trait]
128impl QueryEngine for TrinoEngine {
129 async fn test(&self) -> anyhow::Result<()> {
130 self.run("SELECT 1").await.map(|_| ())
131 }
132
133 async fn fetch_schema(&self) -> anyhow::Result<Vec<SchemaColumn>> {
134 let catalog = self.conn.catalog.as_deref().ok_or_else(|| {
135 anyhow::anyhow!("trino://: put the catalog in the connection string (trino://user@host/CATALOG) so the schema can be read")
136 })?;
137 let schema_filter = self
138 .conn
139 .schema
140 .as_deref()
141 .map(|s| format!(" AND table_schema = {}", sql_literal(s)))
142 .unwrap_or_default();
143 let sql = format!(
144 "SELECT table_schema, table_name, column_name, data_type, comment \
145 FROM \"{}\".information_schema.columns \
146 WHERE table_schema <> 'information_schema'{schema_filter} \
147 ORDER BY table_schema, table_name, ordinal_position",
148 catalog.replace('"', "\"\"")
149 );
150 let (_, rows) = self.run(&sql).await?;
151 Ok(rows.into_iter().map(schema_row).collect())
152 }
153
154 async fn execute(&self, sql: &str) -> anyhow::Result<QueryResult> {
155 let (columns, rows) = self.run(&wrap_limit(sql)).await?;
156 let (rows, truncated) = truncate_rows(rows);
157 Ok(QueryResult {
158 rows: rows_to_json_lines(&columns, &rows),
159 truncated,
160 })
161 }
162}
163
164/// information_schema 的一行 → SchemaColumn(值可能是 null,comment 常是)
165pub(crate) fn schema_row(row: Vec<serde_json::Value>) -> SchemaColumn {
166 let text = |i: usize| -> String {
167 row.get(i)
168 .and_then(|v| v.as_str())
169 .unwrap_or_default()
170 .to_string()
171 };
172 SchemaColumn {
173 schema: text(0),
174 table: text(1),
175 column: text(2),
176 data_type: text(3),
177 comment: row
178 .get(4)
179 .and_then(|v| v.as_str())
180 .filter(|s| !s.is_empty())
181 .map(str::to_string),
182 }
183}
184
185#[cfg(test)]
186mod tests {
187 use super::super::conn::TrinoConn;
188 use super::super::QueryEngine;
189 use super::TrinoEngine;
190 use serde_json::json;
191 use wiremock::matchers::{body_string_contains, header, method, path};
192 use wiremock::{Mock, MockServer, ResponseTemplate};
193
194 #[tokio::test]
195 async fn follows_next_uri_and_keeps_column_order() {
196 let server = MockServer::start().await;
197 Mock::given(method("POST"))
198 .and(path("/v1/statement"))
199 .and(header("X-Trino-User", "alice"))
200 .and(header("X-Trino-Catalog", "hive"))
201 .and(body_string_contains("LIMIT 201"))
202 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
203 "id": "q1",
204 "nextUri": format!("{}/v1/statement/q1/1", server.uri()),
205 "stats": { "state": "QUEUED" }
206 })))
207 .expect(1)
208 .mount(&server)
209 .await;
210 Mock::given(method("GET"))
211 .and(path("/v1/statement/q1/1"))
212 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
213 "id": "q1",
214 "columns": [ { "name": "region", "type": "varchar" }, { "name": "total", "type": "double" } ],
215 "data": [ ["east", 12.5], ["west", 3] ],
216 "stats": { "state": "FINISHED" }
217 })))
218 .expect(1)
219 .mount(&server)
220 .await;
221
222 let uri = server.uri();
223 let conn = TrinoConn::parse(&format!(
224 "trino://alice@{}/hive/default?ssl=false",
225 uri.trim_start_matches("http://")
226 ))
227 .unwrap();
228 let out = TrinoEngine::new(conn)
229 .execute("SELECT region, total FROM orders")
230 .await
231 .unwrap();
232 assert_eq!(
233 out.rows,
234 vec![
235 r#"{"region":"east","total":12.5}"#,
236 r#"{"region":"west","total":3}"#
237 ]
238 );
239 assert!(!out.truncated);
240 }
241
242 #[tokio::test]
243 async fn a_trino_error_page_becomes_an_error() {
244 let server = MockServer::start().await;
245 Mock::given(method("POST"))
246 .and(path("/v1/statement"))
247 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
248 "id": "q2",
249 "error": { "message": "line 1:8: Table 'hive.default.nope' does not exist", "errorName": "TABLE_NOT_FOUND" },
250 "stats": { "state": "FAILED" }
251 })))
252 .mount(&server)
253 .await;
254 let conn = TrinoConn::parse(&format!(
255 "trino://alice@{}/hive?ssl=false",
256 server.uri().trim_start_matches("http://")
257 ))
258 .unwrap();
259 let err = TrinoEngine::new(conn)
260 .execute("SELECT * FROM nope")
261 .await
262 .unwrap_err()
263 .to_string();
264 assert!(err.contains("TABLE_NOT_FOUND"), "{err}");
265 }
266}