Line data Source code
1 : use std::pin::pin;
2 : use std::sync::Arc;
3 :
4 : use bytes::Bytes;
5 : use futures::future::select;
6 : use futures::future::try_join;
7 : use futures::future::Either;
8 : use futures::StreamExt;
9 : use futures::TryFutureExt;
10 : use http_body_util::BodyExt;
11 : use http_body_util::Full;
12 : use hyper1::body::Body;
13 : use hyper1::body::Incoming;
14 : use hyper1::header;
15 : use hyper1::http::HeaderName;
16 : use hyper1::http::HeaderValue;
17 : use hyper1::Response;
18 : use hyper1::StatusCode;
19 : use hyper1::{HeaderMap, Request};
20 : use serde_json::json;
21 : use serde_json::Value;
22 : use tokio::time;
23 : use tokio_postgres::error::DbError;
24 : use tokio_postgres::error::ErrorPosition;
25 : use tokio_postgres::error::SqlState;
26 : use tokio_postgres::GenericClient;
27 : use tokio_postgres::IsolationLevel;
28 : use tokio_postgres::NoTls;
29 : use tokio_postgres::ReadyForQueryStatus;
30 : use tokio_postgres::Transaction;
31 : use tokio_util::sync::CancellationToken;
32 : use tracing::error;
33 : use tracing::info;
34 : use url::Url;
35 : use utils::http::error::ApiError;
36 :
37 : use crate::auth::backend::ComputeUserInfo;
38 : use crate::auth::endpoint_sni;
39 : use crate::auth::ComputeUserInfoParseError;
40 : use crate::config::ProxyConfig;
41 : use crate::config::TlsConfig;
42 : use crate::context::RequestMonitoring;
43 : use crate::error::ErrorKind;
44 : use crate::error::ReportableError;
45 : use crate::error::UserFacingError;
46 : use crate::metrics::HttpDirection;
47 : use crate::metrics::Metrics;
48 : use crate::proxy::run_until_cancelled;
49 : use crate::proxy::NeonOptions;
50 : use crate::serverless::backend::HttpConnError;
51 : use crate::usage_metrics::MetricCounterRecorder;
52 : use crate::DbName;
53 : use crate::RoleName;
54 :
55 : use super::backend::PoolingBackend;
56 : use super::conn_pool::Client;
57 : use super::conn_pool::ConnInfo;
58 : use super::http_util::json_response;
59 : use super::json::json_to_pg_text;
60 : use super::json::pg_text_row_to_json;
61 : use super::json::JsonConversionError;
62 :
63 0 : #[derive(serde::Deserialize)]
64 : #[serde(rename_all = "camelCase")]
65 : struct QueryData {
66 : query: String,
67 : #[serde(deserialize_with = "bytes_to_pg_text")]
68 : params: Vec<Option<String>>,
69 : #[serde(default)]
70 : array_mode: Option<bool>,
71 : }
72 :
73 0 : #[derive(serde::Deserialize)]
74 : struct BatchQueryData {
75 : queries: Vec<QueryData>,
76 : }
77 :
78 : #[derive(serde::Deserialize)]
79 : #[serde(untagged)]
80 : enum Payload {
81 : Single(QueryData),
82 : Batch(BatchQueryData),
83 : }
84 :
85 : const MAX_RESPONSE_SIZE: usize = 10 * 1024 * 1024; // 10 MiB
86 : const MAX_REQUEST_SIZE: u64 = 10 * 1024 * 1024; // 10 MiB
87 :
88 : static RAW_TEXT_OUTPUT: HeaderName = HeaderName::from_static("neon-raw-text-output");
89 : static ARRAY_MODE: HeaderName = HeaderName::from_static("neon-array-mode");
90 : static ALLOW_POOL: HeaderName = HeaderName::from_static("neon-pool-opt-in");
91 : static TXN_ISOLATION_LEVEL: HeaderName = HeaderName::from_static("neon-batch-isolation-level");
92 : static TXN_READ_ONLY: HeaderName = HeaderName::from_static("neon-batch-read-only");
93 : static TXN_DEFERRABLE: HeaderName = HeaderName::from_static("neon-batch-deferrable");
94 :
95 : static HEADER_VALUE_TRUE: HeaderValue = HeaderValue::from_static("true");
96 :
97 0 : fn bytes_to_pg_text<'de, D>(deserializer: D) -> Result<Vec<Option<String>>, D::Error>
98 0 : where
99 0 : D: serde::de::Deserializer<'de>,
100 0 : {
101 : // TODO: consider avoiding the allocation here.
102 0 : let json: Vec<Value> = serde::de::Deserialize::deserialize(deserializer)?;
103 0 : Ok(json_to_pg_text(json))
104 0 : }
105 :
106 0 : #[derive(Debug, thiserror::Error)]
107 : pub enum ConnInfoError {
108 : #[error("invalid header: {0}")]
109 : InvalidHeader(&'static str),
110 : #[error("invalid connection string: {0}")]
111 : UrlParseError(#[from] url::ParseError),
112 : #[error("incorrect scheme")]
113 : IncorrectScheme,
114 : #[error("missing database name")]
115 : MissingDbName,
116 : #[error("invalid database name")]
117 : InvalidDbName,
118 : #[error("missing username")]
119 : MissingUsername,
120 : #[error("invalid username: {0}")]
121 : InvalidUsername(#[from] std::string::FromUtf8Error),
122 : #[error("missing password")]
123 : MissingPassword,
124 : #[error("missing hostname")]
125 : MissingHostname,
126 : #[error("invalid hostname: {0}")]
127 : InvalidEndpoint(#[from] ComputeUserInfoParseError),
128 : #[error("malformed endpoint")]
129 : MalformedEndpoint,
130 : }
131 :
132 : impl ReportableError for ConnInfoError {
133 0 : fn get_error_kind(&self) -> ErrorKind {
134 0 : ErrorKind::User
135 0 : }
136 : }
137 :
138 : impl UserFacingError for ConnInfoError {
139 0 : fn to_string_client(&self) -> String {
140 0 : self.to_string()
141 0 : }
142 : }
143 :
144 0 : fn get_conn_info(
145 0 : ctx: &mut RequestMonitoring,
146 0 : headers: &HeaderMap,
147 0 : tls: &TlsConfig,
148 0 : ) -> Result<ConnInfo, ConnInfoError> {
149 0 : // HTTP only uses cleartext (for now and likely always)
150 0 : ctx.set_auth_method(crate::context::AuthMethod::Cleartext);
151 :
152 0 : let connection_string = headers
153 0 : .get("Neon-Connection-String")
154 0 : .ok_or(ConnInfoError::InvalidHeader("Neon-Connection-String"))?
155 0 : .to_str()
156 0 : .map_err(|_| ConnInfoError::InvalidHeader("Neon-Connection-String"))?;
157 :
158 0 : let connection_url = Url::parse(connection_string)?;
159 :
160 0 : let protocol = connection_url.scheme();
161 0 : if protocol != "postgres" && protocol != "postgresql" {
162 0 : return Err(ConnInfoError::IncorrectScheme);
163 0 : }
164 :
165 0 : let mut url_path = connection_url
166 0 : .path_segments()
167 0 : .ok_or(ConnInfoError::MissingDbName)?;
168 :
169 0 : let dbname: DbName = url_path.next().ok_or(ConnInfoError::InvalidDbName)?.into();
170 0 : ctx.set_dbname(dbname.clone());
171 :
172 0 : let username = RoleName::from(urlencoding::decode(connection_url.username())?);
173 0 : if username.is_empty() {
174 0 : return Err(ConnInfoError::MissingUsername);
175 0 : }
176 0 : ctx.set_user(username.clone());
177 :
178 0 : let password = connection_url
179 0 : .password()
180 0 : .ok_or(ConnInfoError::MissingPassword)?;
181 0 : let password = urlencoding::decode_binary(password.as_bytes());
182 :
183 0 : let hostname = connection_url
184 0 : .host_str()
185 0 : .ok_or(ConnInfoError::MissingHostname)?;
186 :
187 0 : let endpoint =
188 0 : endpoint_sni(hostname, &tls.common_names)?.ok_or(ConnInfoError::MalformedEndpoint)?;
189 0 : ctx.set_endpoint_id(endpoint.clone());
190 0 :
191 0 : let pairs = connection_url.query_pairs();
192 0 :
193 0 : let mut options = Option::None;
194 :
195 0 : for (key, value) in pairs {
196 0 : match &*key {
197 0 : "options" => {
198 0 : options = Some(NeonOptions::parse_options_raw(&value));
199 0 : }
200 0 : "application_name" => ctx.set_application(Some(value.into())),
201 0 : _ => {}
202 : }
203 : }
204 :
205 0 : let user_info = ComputeUserInfo {
206 0 : endpoint,
207 0 : user: username,
208 0 : options: options.unwrap_or_default(),
209 0 : };
210 0 :
211 0 : Ok(ConnInfo {
212 0 : user_info,
213 0 : dbname,
214 0 : password: match password {
215 0 : std::borrow::Cow::Borrowed(b) => b.into(),
216 0 : std::borrow::Cow::Owned(b) => b.into(),
217 : },
218 : })
219 0 : }
220 :
221 : // TODO: return different http error codes
222 0 : pub async fn handle(
223 0 : config: &'static ProxyConfig,
224 0 : mut ctx: RequestMonitoring,
225 0 : request: Request<Incoming>,
226 0 : backend: Arc<PoolingBackend>,
227 0 : cancel: CancellationToken,
228 0 : ) -> Result<Response<Full<Bytes>>, ApiError> {
229 0 : let result = handle_inner(cancel, config, &mut ctx, request, backend).await;
230 :
231 0 : let mut response = match result {
232 0 : Ok(r) => {
233 0 : ctx.set_success();
234 0 : r
235 : }
236 0 : Err(e @ SqlOverHttpError::Cancelled(_)) => {
237 0 : let error_kind = e.get_error_kind();
238 0 : ctx.set_error_kind(error_kind);
239 0 :
240 0 : let message = "Query cancelled, connection was terminated";
241 0 :
242 0 : tracing::info!(
243 0 : kind=error_kind.to_metric_label(),
244 0 : error=%e,
245 0 : msg=message,
246 0 : "forwarding error to user"
247 : );
248 :
249 0 : json_response(
250 0 : StatusCode::BAD_REQUEST,
251 0 : json!({ "message": message, "code": SqlState::PROTOCOL_VIOLATION.code() }),
252 0 : )?
253 : }
254 0 : Err(e) => {
255 0 : let error_kind = e.get_error_kind();
256 0 : ctx.set_error_kind(error_kind);
257 0 :
258 0 : let mut message = e.to_string_client();
259 0 : let db_error = match &e {
260 0 : SqlOverHttpError::ConnectCompute(HttpConnError::ConnectionError(e))
261 0 : | SqlOverHttpError::Postgres(e) => e.as_db_error(),
262 0 : _ => None,
263 : };
264 0 : fn get<'a, T: serde::Serialize>(
265 0 : db: Option<&'a DbError>,
266 0 : x: impl FnOnce(&'a DbError) -> T,
267 0 : ) -> Value {
268 0 : db.map(x)
269 0 : .and_then(|t| serde_json::to_value(t).ok())
270 0 : .unwrap_or_default()
271 0 : }
272 :
273 0 : if let Some(db_error) = db_error {
274 0 : db_error.message().clone_into(&mut message);
275 0 : }
276 :
277 0 : let position = db_error.and_then(|db| db.position());
278 0 : let (position, internal_position, internal_query) = match position {
279 0 : Some(ErrorPosition::Original(position)) => (
280 0 : Value::String(position.to_string()),
281 0 : Value::Null,
282 0 : Value::Null,
283 0 : ),
284 0 : Some(ErrorPosition::Internal { position, query }) => (
285 0 : Value::Null,
286 0 : Value::String(position.to_string()),
287 0 : Value::String(query.clone()),
288 0 : ),
289 0 : None => (Value::Null, Value::Null, Value::Null),
290 : };
291 :
292 0 : let code = get(db_error, |db| db.code().code());
293 0 : let severity = get(db_error, |db| db.severity());
294 0 : let detail = get(db_error, |db| db.detail());
295 0 : let hint = get(db_error, |db| db.hint());
296 0 : let where_ = get(db_error, |db| db.where_());
297 0 : let table = get(db_error, |db| db.table());
298 0 : let column = get(db_error, |db| db.column());
299 0 : let schema = get(db_error, |db| db.schema());
300 0 : let datatype = get(db_error, |db| db.datatype());
301 0 : let constraint = get(db_error, |db| db.constraint());
302 0 : let file = get(db_error, |db| db.file());
303 0 : let line = get(db_error, |db| db.line().map(|l| l.to_string()));
304 0 : let routine = get(db_error, |db| db.routine());
305 0 :
306 0 : tracing::info!(
307 0 : kind=error_kind.to_metric_label(),
308 0 : error=%e,
309 0 : msg=message,
310 0 : "forwarding error to user"
311 : );
312 :
313 : // TODO: this shouldn't always be bad request.
314 0 : json_response(
315 0 : StatusCode::BAD_REQUEST,
316 0 : json!({
317 0 : "message": message,
318 0 : "code": code,
319 0 : "detail": detail,
320 0 : "hint": hint,
321 0 : "position": position,
322 0 : "internalPosition": internal_position,
323 0 : "internalQuery": internal_query,
324 0 : "severity": severity,
325 0 : "where": where_,
326 0 : "table": table,
327 0 : "column": column,
328 0 : "schema": schema,
329 0 : "dataType": datatype,
330 0 : "constraint": constraint,
331 0 : "file": file,
332 0 : "line": line,
333 0 : "routine": routine,
334 0 : }),
335 0 : )?
336 : }
337 : };
338 :
339 0 : response
340 0 : .headers_mut()
341 0 : .insert("Access-Control-Allow-Origin", HeaderValue::from_static("*"));
342 0 : Ok(response)
343 0 : }
344 :
345 0 : #[derive(Debug, thiserror::Error)]
346 : pub enum SqlOverHttpError {
347 : #[error("{0}")]
348 : ReadPayload(#[from] ReadPayloadError),
349 : #[error("{0}")]
350 : ConnectCompute(#[from] HttpConnError),
351 : #[error("{0}")]
352 : ConnInfo(#[from] ConnInfoError),
353 : #[error("request is too large (max is {MAX_REQUEST_SIZE} bytes)")]
354 : RequestTooLarge,
355 : #[error("response is too large (max is {MAX_RESPONSE_SIZE} bytes)")]
356 : ResponseTooLarge,
357 : #[error("invalid isolation level")]
358 : InvalidIsolationLevel,
359 : #[error("{0}")]
360 : Postgres(#[from] tokio_postgres::Error),
361 : #[error("{0}")]
362 : JsonConversion(#[from] JsonConversionError),
363 : #[error("{0}")]
364 : Cancelled(SqlOverHttpCancel),
365 : }
366 :
367 : impl ReportableError for SqlOverHttpError {
368 0 : fn get_error_kind(&self) -> ErrorKind {
369 0 : match self {
370 0 : SqlOverHttpError::ReadPayload(e) => e.get_error_kind(),
371 0 : SqlOverHttpError::ConnectCompute(e) => e.get_error_kind(),
372 0 : SqlOverHttpError::ConnInfo(e) => e.get_error_kind(),
373 0 : SqlOverHttpError::RequestTooLarge => ErrorKind::User,
374 0 : SqlOverHttpError::ResponseTooLarge => ErrorKind::User,
375 0 : SqlOverHttpError::InvalidIsolationLevel => ErrorKind::User,
376 0 : SqlOverHttpError::Postgres(p) => p.get_error_kind(),
377 0 : SqlOverHttpError::JsonConversion(_) => ErrorKind::Postgres,
378 0 : SqlOverHttpError::Cancelled(c) => c.get_error_kind(),
379 : }
380 0 : }
381 : }
382 :
383 : impl UserFacingError for SqlOverHttpError {
384 0 : fn to_string_client(&self) -> String {
385 0 : match self {
386 0 : SqlOverHttpError::ReadPayload(p) => p.to_string(),
387 0 : SqlOverHttpError::ConnectCompute(c) => c.to_string_client(),
388 0 : SqlOverHttpError::ConnInfo(c) => c.to_string_client(),
389 0 : SqlOverHttpError::RequestTooLarge => self.to_string(),
390 0 : SqlOverHttpError::ResponseTooLarge => self.to_string(),
391 0 : SqlOverHttpError::InvalidIsolationLevel => self.to_string(),
392 0 : SqlOverHttpError::Postgres(p) => p.to_string(),
393 0 : SqlOverHttpError::JsonConversion(_) => "could not parse postgres response".to_string(),
394 0 : SqlOverHttpError::Cancelled(_) => self.to_string(),
395 : }
396 0 : }
397 : }
398 :
399 0 : #[derive(Debug, thiserror::Error)]
400 : pub enum ReadPayloadError {
401 : #[error("could not read the HTTP request body: {0}")]
402 : Read(#[from] hyper1::Error),
403 : #[error("could not parse the HTTP request body: {0}")]
404 : Parse(#[from] serde_json::Error),
405 : }
406 :
407 : impl ReportableError for ReadPayloadError {
408 0 : fn get_error_kind(&self) -> ErrorKind {
409 0 : match self {
410 0 : ReadPayloadError::Read(_) => ErrorKind::ClientDisconnect,
411 0 : ReadPayloadError::Parse(_) => ErrorKind::User,
412 : }
413 0 : }
414 : }
415 :
416 0 : #[derive(Debug, thiserror::Error)]
417 : pub enum SqlOverHttpCancel {
418 : #[error("query was cancelled")]
419 : Postgres,
420 : #[error("query was cancelled while stuck trying to connect to the database")]
421 : Connect,
422 : }
423 :
424 : impl ReportableError for SqlOverHttpCancel {
425 0 : fn get_error_kind(&self) -> ErrorKind {
426 0 : match self {
427 0 : SqlOverHttpCancel::Postgres => ErrorKind::ClientDisconnect,
428 0 : SqlOverHttpCancel::Connect => ErrorKind::ClientDisconnect,
429 : }
430 0 : }
431 : }
432 :
433 : #[derive(Clone, Copy, Debug)]
434 : struct HttpHeaders {
435 : raw_output: bool,
436 : default_array_mode: bool,
437 : txn_isolation_level: Option<IsolationLevel>,
438 : txn_read_only: bool,
439 : txn_deferrable: bool,
440 : }
441 :
442 : impl HttpHeaders {
443 0 : fn try_parse(headers: &hyper1::http::HeaderMap) -> Result<Self, SqlOverHttpError> {
444 0 : // Determine the output options. Default behaviour is 'false'. Anything that is not
445 0 : // strictly 'true' assumed to be false.
446 0 : let raw_output = headers.get(&RAW_TEXT_OUTPUT) == Some(&HEADER_VALUE_TRUE);
447 0 : let default_array_mode = headers.get(&ARRAY_MODE) == Some(&HEADER_VALUE_TRUE);
448 :
449 : // isolation level, read only and deferrable
450 0 : let txn_isolation_level = match headers.get(&TXN_ISOLATION_LEVEL) {
451 0 : Some(x) => Some(
452 0 : map_header_to_isolation_level(x).ok_or(SqlOverHttpError::InvalidIsolationLevel)?,
453 : ),
454 0 : None => None,
455 : };
456 :
457 0 : let txn_read_only = headers.get(&TXN_READ_ONLY) == Some(&HEADER_VALUE_TRUE);
458 0 : let txn_deferrable = headers.get(&TXN_DEFERRABLE) == Some(&HEADER_VALUE_TRUE);
459 0 :
460 0 : Ok(Self {
461 0 : raw_output,
462 0 : default_array_mode,
463 0 : txn_isolation_level,
464 0 : txn_read_only,
465 0 : txn_deferrable,
466 0 : })
467 0 : }
468 : }
469 :
470 0 : fn map_header_to_isolation_level(level: &HeaderValue) -> Option<IsolationLevel> {
471 0 : match level.as_bytes() {
472 0 : b"Serializable" => Some(IsolationLevel::Serializable),
473 0 : b"ReadUncommitted" => Some(IsolationLevel::ReadUncommitted),
474 0 : b"ReadCommitted" => Some(IsolationLevel::ReadCommitted),
475 0 : b"RepeatableRead" => Some(IsolationLevel::RepeatableRead),
476 0 : _ => None,
477 : }
478 0 : }
479 :
480 0 : fn map_isolation_level_to_headers(level: IsolationLevel) -> Option<HeaderValue> {
481 0 : match level {
482 0 : IsolationLevel::ReadUncommitted => Some(HeaderValue::from_static("ReadUncommitted")),
483 0 : IsolationLevel::ReadCommitted => Some(HeaderValue::from_static("ReadCommitted")),
484 0 : IsolationLevel::RepeatableRead => Some(HeaderValue::from_static("RepeatableRead")),
485 0 : IsolationLevel::Serializable => Some(HeaderValue::from_static("Serializable")),
486 0 : _ => None,
487 : }
488 0 : }
489 :
490 0 : async fn handle_inner(
491 0 : cancel: CancellationToken,
492 0 : config: &'static ProxyConfig,
493 0 : ctx: &mut RequestMonitoring,
494 0 : request: Request<Incoming>,
495 0 : backend: Arc<PoolingBackend>,
496 0 : ) -> Result<Response<Full<Bytes>>, SqlOverHttpError> {
497 0 : let _requeset_gauge = Metrics::get().proxy.connection_requests.guard(ctx.protocol);
498 0 : info!(
499 : protocol = %ctx.protocol,
500 0 : "handling interactive connection from client"
501 : );
502 :
503 : //
504 : // Determine the destination and connection params
505 : //
506 0 : let headers = request.headers();
507 :
508 : // TLS config should be there.
509 0 : let conn_info = get_conn_info(ctx, headers, config.tls_config.as_ref().unwrap())?;
510 0 : info!(user = conn_info.user_info.user.as_str(), "credentials");
511 :
512 : // Allow connection pooling only if explicitly requested
513 : // or if we have decided that http pool is no longer opt-in
514 0 : let allow_pool = !config.http_config.pool_options.opt_in
515 0 : || headers.get(&ALLOW_POOL) == Some(&HEADER_VALUE_TRUE);
516 :
517 0 : let parsed_headers = HttpHeaders::try_parse(headers)?;
518 :
519 0 : let request_content_length = match request.body().size_hint().upper() {
520 0 : Some(v) => v,
521 0 : None => MAX_REQUEST_SIZE + 1,
522 : };
523 0 : info!(request_content_length, "request size in bytes");
524 0 : Metrics::get()
525 0 : .proxy
526 0 : .http_conn_content_length_bytes
527 0 : .observe(HttpDirection::Request, request_content_length as f64);
528 0 :
529 0 : // we don't have a streaming request support yet so this is to prevent OOM
530 0 : // from a malicious user sending an extremely large request body
531 0 : if request_content_length > MAX_REQUEST_SIZE {
532 0 : return Err(SqlOverHttpError::RequestTooLarge);
533 0 : }
534 0 :
535 0 : let fetch_and_process_request = async {
536 0 : let body = request.into_body().collect().await?.to_bytes();
537 0 : info!(length = body.len(), "request payload read");
538 0 : let payload: Payload = serde_json::from_slice(&body)?;
539 0 : Ok::<Payload, ReadPayloadError>(payload) // Adjust error type accordingly
540 0 : }
541 0 : .map_err(SqlOverHttpError::from);
542 0 :
543 0 : let authenticate_and_connect = async {
544 0 : let keys = backend
545 0 : .authenticate(ctx, &config.authentication_config, &conn_info)
546 0 : .await?;
547 0 : let client = backend
548 0 : .connect_to_compute(ctx, conn_info, keys, !allow_pool)
549 0 : .await?;
550 : // not strictly necessary to mark success here,
551 : // but it's just insurance for if we forget it somewhere else
552 0 : ctx.latency_timer.success();
553 0 : Ok::<_, HttpConnError>(client)
554 0 : }
555 0 : .map_err(SqlOverHttpError::from);
556 :
557 0 : let (payload, mut client) = match run_until_cancelled(
558 0 : // Run both operations in parallel
559 0 : try_join(
560 0 : pin!(fetch_and_process_request),
561 0 : pin!(authenticate_and_connect),
562 0 : ),
563 0 : &cancel,
564 0 : )
565 0 : .await
566 : {
567 0 : Some(result) => result?,
568 0 : None => return Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Connect)),
569 : };
570 :
571 0 : let mut response = Response::builder()
572 0 : .status(StatusCode::OK)
573 0 : .header(header::CONTENT_TYPE, "application/json");
574 :
575 : //
576 : // Now execute the query and return the result
577 : //
578 0 : let result = match payload {
579 0 : Payload::Single(stmt) => stmt.process(cancel, &mut client, parsed_headers).await?,
580 0 : Payload::Batch(statements) => {
581 0 : if parsed_headers.txn_read_only {
582 0 : response = response.header(TXN_READ_ONLY.clone(), &HEADER_VALUE_TRUE);
583 0 : }
584 0 : if parsed_headers.txn_deferrable {
585 0 : response = response.header(TXN_DEFERRABLE.clone(), &HEADER_VALUE_TRUE);
586 0 : }
587 0 : if let Some(txn_isolation_level) = parsed_headers
588 0 : .txn_isolation_level
589 0 : .and_then(map_isolation_level_to_headers)
590 0 : {
591 0 : response = response.header(TXN_ISOLATION_LEVEL.clone(), txn_isolation_level);
592 0 : }
593 :
594 0 : statements
595 0 : .process(cancel, &mut client, parsed_headers)
596 0 : .await?
597 : }
598 : };
599 :
600 0 : let metrics = client.metrics();
601 0 :
602 0 : // how could this possibly fail
603 0 : let body = serde_json::to_string(&result).expect("json serialization should not fail");
604 0 : let len = body.len();
605 0 : let response = response
606 0 : .body(Full::new(Bytes::from(body)))
607 0 : // only fails if invalid status code or invalid header/values are given.
608 0 : // these are not user configurable so it cannot fail dynamically
609 0 : .expect("building response payload should not fail");
610 0 :
611 0 : // count the egress bytes - we miss the TLS and header overhead but oh well...
612 0 : // moving this later in the stack is going to be a lot of effort and ehhhh
613 0 : metrics.record_egress(len as u64);
614 0 : Metrics::get()
615 0 : .proxy
616 0 : .http_conn_content_length_bytes
617 0 : .observe(HttpDirection::Response, len as f64);
618 0 :
619 0 : Ok(response)
620 0 : }
621 :
622 : impl QueryData {
623 0 : async fn process(
624 0 : self,
625 0 : cancel: CancellationToken,
626 0 : client: &mut Client<tokio_postgres::Client>,
627 0 : parsed_headers: HttpHeaders,
628 0 : ) -> Result<Value, SqlOverHttpError> {
629 0 : let (inner, mut discard) = client.inner();
630 0 : let cancel_token = inner.cancel_token();
631 :
632 0 : let res = match select(
633 0 : pin!(query_to_json(&*inner, self, &mut 0, parsed_headers)),
634 0 : pin!(cancel.cancelled()),
635 0 : )
636 0 : .await
637 : {
638 : // The query successfully completed.
639 0 : Either::Left((Ok((status, results)), __not_yet_cancelled)) => {
640 0 : discard.check_idle(status);
641 0 : Ok(results)
642 : }
643 : // The query failed with an error
644 0 : Either::Left((Err(e), __not_yet_cancelled)) => {
645 0 : discard.discard();
646 0 : return Err(e);
647 : }
648 : // The query was cancelled.
649 0 : Either::Right((_cancelled, query)) => {
650 0 : tracing::info!("cancelling query");
651 0 : if let Err(err) = cancel_token.cancel_query(NoTls).await {
652 0 : tracing::error!(?err, "could not cancel query");
653 0 : }
654 : // wait for the query cancellation
655 0 : match time::timeout(time::Duration::from_millis(100), query).await {
656 : // query successed before it was cancelled.
657 0 : Ok(Ok((status, results))) => {
658 0 : discard.check_idle(status);
659 0 : Ok(results)
660 : }
661 : // query failed or was cancelled.
662 0 : Ok(Err(error)) => {
663 0 : let db_error = match &error {
664 0 : SqlOverHttpError::ConnectCompute(HttpConnError::ConnectionError(e))
665 0 : | SqlOverHttpError::Postgres(e) => e.as_db_error(),
666 0 : _ => None,
667 : };
668 :
669 : // if errored for some other reason, it might not be safe to return
670 0 : if !db_error.is_some_and(|e| *e.code() == SqlState::QUERY_CANCELED) {
671 0 : discard.discard();
672 0 : }
673 :
674 0 : Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Postgres))
675 : }
676 0 : Err(_timeout) => {
677 0 : discard.discard();
678 0 : Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Postgres))
679 : }
680 : }
681 : }
682 : };
683 0 : res
684 0 : }
685 : }
686 :
687 : impl BatchQueryData {
688 0 : async fn process(
689 0 : self,
690 0 : cancel: CancellationToken,
691 0 : client: &mut Client<tokio_postgres::Client>,
692 0 : parsed_headers: HttpHeaders,
693 0 : ) -> Result<Value, SqlOverHttpError> {
694 0 : info!("starting transaction");
695 0 : let (inner, mut discard) = client.inner();
696 0 : let cancel_token = inner.cancel_token();
697 0 : let mut builder = inner.build_transaction();
698 0 : if let Some(isolation_level) = parsed_headers.txn_isolation_level {
699 0 : builder = builder.isolation_level(isolation_level);
700 0 : }
701 0 : if parsed_headers.txn_read_only {
702 0 : builder = builder.read_only(true);
703 0 : }
704 0 : if parsed_headers.txn_deferrable {
705 0 : builder = builder.deferrable(true);
706 0 : }
707 :
708 0 : let transaction = builder.start().await.map_err(|e| {
709 0 : // if we cannot start a transaction, we should return immediately
710 0 : // and not return to the pool. connection is clearly broken
711 0 : discard.discard();
712 0 : e
713 0 : })?;
714 :
715 0 : let results =
716 0 : match query_batch(cancel.child_token(), &transaction, self, parsed_headers).await {
717 0 : Ok(results) => {
718 0 : info!("commit");
719 0 : let status = transaction.commit().await.map_err(|e| {
720 0 : // if we cannot commit - for now don't return connection to pool
721 0 : // TODO: get a query status from the error
722 0 : discard.discard();
723 0 : e
724 0 : })?;
725 0 : discard.check_idle(status);
726 0 : results
727 : }
728 : Err(SqlOverHttpError::Cancelled(_)) => {
729 0 : if let Err(err) = cancel_token.cancel_query(NoTls).await {
730 0 : tracing::error!(?err, "could not cancel query");
731 0 : }
732 : // TODO: after cancelling, wait to see if we can get a status. maybe the connection is still safe.
733 0 : discard.discard();
734 0 :
735 0 : return Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Postgres));
736 : }
737 0 : Err(err) => {
738 0 : info!("rollback");
739 0 : let status = transaction.rollback().await.map_err(|e| {
740 0 : // if we cannot rollback - for now don't return connection to pool
741 0 : // TODO: get a query status from the error
742 0 : discard.discard();
743 0 : e
744 0 : })?;
745 0 : discard.check_idle(status);
746 0 : return Err(err);
747 : }
748 : };
749 :
750 0 : Ok(json!({ "results": results }))
751 0 : }
752 : }
753 :
754 0 : async fn query_batch(
755 0 : cancel: CancellationToken,
756 0 : transaction: &Transaction<'_>,
757 0 : queries: BatchQueryData,
758 0 : parsed_headers: HttpHeaders,
759 0 : ) -> Result<Vec<Value>, SqlOverHttpError> {
760 0 : let mut results = Vec::with_capacity(queries.queries.len());
761 0 : let mut current_size = 0;
762 0 : for stmt in queries.queries {
763 0 : let query = pin!(query_to_json(
764 0 : transaction,
765 0 : stmt,
766 0 : &mut current_size,
767 0 : parsed_headers,
768 0 : ));
769 0 : let cancelled = pin!(cancel.cancelled());
770 0 : let res = select(query, cancelled).await;
771 0 : match res {
772 : // TODO: maybe we should check that the transaction bit is set here
773 0 : Either::Left((Ok((_, values)), _cancelled)) => {
774 0 : results.push(values);
775 0 : }
776 0 : Either::Left((Err(e), _cancelled)) => {
777 0 : return Err(e);
778 : }
779 0 : Either::Right((_cancelled, _)) => {
780 0 : return Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Postgres));
781 : }
782 : }
783 : }
784 0 : Ok(results)
785 0 : }
786 :
787 0 : async fn query_to_json<T: GenericClient>(
788 0 : client: &T,
789 0 : data: QueryData,
790 0 : current_size: &mut usize,
791 0 : parsed_headers: HttpHeaders,
792 0 : ) -> Result<(ReadyForQueryStatus, Value), SqlOverHttpError> {
793 0 : info!("executing query");
794 0 : let query_params = data.params;
795 0 : let mut row_stream = std::pin::pin!(client.query_raw_txt(&data.query, query_params).await?);
796 0 : info!("finished executing query");
797 :
798 : // Manually drain the stream into a vector to leave row_stream hanging
799 : // around to get a command tag. Also check that the response is not too
800 : // big.
801 0 : let mut rows: Vec<tokio_postgres::Row> = Vec::new();
802 0 : while let Some(row) = row_stream.next().await {
803 0 : let row = row?;
804 0 : *current_size += row.body_len();
805 0 : rows.push(row);
806 0 : // we don't have a streaming response support yet so this is to prevent OOM
807 0 : // from a malicious query (eg a cross join)
808 0 : if *current_size > MAX_RESPONSE_SIZE {
809 0 : return Err(SqlOverHttpError::ResponseTooLarge);
810 0 : }
811 : }
812 :
813 0 : let ready = row_stream.ready_status();
814 0 :
815 0 : // grab the command tag and number of rows affected
816 0 : let command_tag = row_stream.command_tag().unwrap_or_default();
817 0 : let mut command_tag_split = command_tag.split(' ');
818 0 : let command_tag_name = command_tag_split.next().unwrap_or_default();
819 0 : let command_tag_count = if command_tag_name == "INSERT" {
820 : // INSERT returns OID first and then number of rows
821 0 : command_tag_split.nth(1)
822 : } else {
823 : // other commands return number of rows (if any)
824 0 : command_tag_split.next()
825 : }
826 0 : .and_then(|s| s.parse::<i64>().ok());
827 0 :
828 0 : info!(
829 0 : rows = rows.len(),
830 0 : ?ready,
831 0 : command_tag,
832 0 : "finished reading rows"
833 : );
834 :
835 0 : let mut fields = vec![];
836 0 : let mut columns = vec![];
837 :
838 0 : for c in row_stream.columns() {
839 0 : fields.push(json!({
840 0 : "name": Value::String(c.name().to_owned()),
841 0 : "dataTypeID": Value::Number(c.type_().oid().into()),
842 0 : "tableID": c.table_oid(),
843 0 : "columnID": c.column_id(),
844 0 : "dataTypeSize": c.type_size(),
845 0 : "dataTypeModifier": c.type_modifier(),
846 0 : "format": "text",
847 0 : }));
848 0 : columns.push(client.get_type(c.type_oid()).await?);
849 : }
850 :
851 0 : let array_mode = data.array_mode.unwrap_or(parsed_headers.default_array_mode);
852 :
853 : // convert rows to JSON
854 0 : let rows = rows
855 0 : .iter()
856 0 : .map(|row| pg_text_row_to_json(row, &columns, parsed_headers.raw_output, array_mode))
857 0 : .collect::<Result<Vec<_>, _>>()?;
858 :
859 : // resulting JSON format is based on the format of node-postgres result
860 0 : Ok((
861 0 : ready,
862 0 : json!({
863 0 : "command": command_tag_name,
864 0 : "rowCount": command_tag_count,
865 0 : "rows": rows,
866 0 : "fields": fields,
867 0 : "rowAsArray": array_mode,
868 0 : }),
869 0 : ))
870 0 : }
|