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