Line data Source code
1 : use std::pin::pin;
2 : use std::sync::Arc;
3 :
4 : use bytes::Bytes;
5 : use futures::future::{Either, select, try_join};
6 : use futures::{StreamExt, TryFutureExt};
7 : use http::Method;
8 : use http::header::AUTHORIZATION;
9 : use http_body_util::combinators::BoxBody;
10 : use http_body_util::{BodyExt, Full};
11 : use http_utils::error::ApiError;
12 : use hyper::body::Incoming;
13 : use hyper::http::{HeaderName, HeaderValue};
14 : use hyper::{Request, Response, StatusCode, header};
15 : use indexmap::IndexMap;
16 : use postgres_client::error::{DbError, ErrorPosition, SqlState};
17 : use postgres_client::{GenericClient, IsolationLevel, NoTls, ReadyForQueryStatus, Transaction};
18 : use serde_json::Value;
19 : use serde_json::value::RawValue;
20 : use tokio::time::{self, Instant};
21 : use tokio_util::sync::CancellationToken;
22 : use tracing::{Level, debug, error, info};
23 : use typed_json::json;
24 :
25 : use super::backend::{LocalProxyConnError, PoolingBackend};
26 : use super::conn_pool::AuthData;
27 : use super::conn_pool_lib::{self, ConnInfo};
28 : use super::error::{ConnInfoError, HttpCodeError, ReadPayloadError};
29 : use super::http_util::{
30 : ALLOW_POOL, ARRAY_MODE, CONN_STRING, NEON_REQUEST_ID, RAW_TEXT_OUTPUT, TXN_DEFERRABLE,
31 : TXN_ISOLATION_LEVEL, TXN_READ_ONLY, get_conn_info, json_response, uuid_to_header_value,
32 : };
33 : use super::json::{JsonConversionError, json_to_pg_text, pg_text_row_to_json};
34 : use crate::auth::backend::ComputeCredentialKeys;
35 : use crate::config::{HttpConfig, ProxyConfig};
36 : use crate::context::RequestContext;
37 : use crate::error::{ErrorKind, ReportableError, UserFacingError};
38 : use crate::http::read_body_with_limit;
39 : use crate::metrics::{HttpDirection, Metrics};
40 : use crate::serverless::backend::HttpConnError;
41 : use crate::usage_metrics::{MetricCounter, MetricCounterRecorder};
42 : use crate::util::run_until_cancelled;
43 :
44 : #[derive(serde::Deserialize)]
45 : #[serde(rename_all = "camelCase")]
46 : struct QueryData {
47 : query: String,
48 : #[serde(deserialize_with = "bytes_to_pg_text")]
49 : #[serde(default)]
50 : params: Vec<Option<String>>,
51 : #[serde(default)]
52 : array_mode: Option<bool>,
53 : }
54 :
55 0 : #[derive(serde::Deserialize)]
56 : struct BatchQueryData {
57 : queries: Vec<QueryData>,
58 : }
59 :
60 : #[derive(serde::Deserialize)]
61 : #[serde(untagged)]
62 : enum Payload {
63 : Single(QueryData),
64 : Batch(BatchQueryData),
65 : }
66 :
67 : pub(super) const HEADER_VALUE_TRUE: HeaderValue = HeaderValue::from_static("true");
68 :
69 3 : fn bytes_to_pg_text<'de, D>(deserializer: D) -> Result<Vec<Option<String>>, D::Error>
70 3 : where
71 3 : D: serde::de::Deserializer<'de>,
72 : {
73 : // TODO: consider avoiding the allocation here.
74 3 : let json: Vec<Value> = serde::de::Deserialize::deserialize(deserializer)?;
75 3 : Ok(json_to_pg_text(json))
76 3 : }
77 :
78 0 : pub(crate) async fn handle(
79 0 : config: &'static ProxyConfig,
80 0 : ctx: RequestContext,
81 0 : request: Request<Incoming>,
82 0 : backend: Arc<PoolingBackend>,
83 0 : cancel: CancellationToken,
84 0 : ) -> Result<Response<BoxBody<Bytes, hyper::Error>>, ApiError> {
85 0 : let result = handle_inner(cancel, config, &ctx, request, backend).await;
86 :
87 0 : let mut response = match result {
88 0 : Ok(r) => {
89 0 : ctx.set_success();
90 :
91 : // Handling the error response from local proxy here
92 0 : if config.authentication_config.is_auth_broker && r.status().is_server_error() {
93 0 : let status = r.status();
94 :
95 0 : let body_bytes = r
96 0 : .collect()
97 0 : .await
98 0 : .map_err(|e| {
99 0 : ApiError::InternalServerError(anyhow::Error::msg(format!(
100 0 : "could not collect http body: {e}"
101 0 : )))
102 0 : })?
103 0 : .to_bytes();
104 :
105 0 : if let Ok(mut json_map) =
106 0 : serde_json::from_slice::<IndexMap<&str, &RawValue>>(&body_bytes)
107 : {
108 0 : let message = json_map.get("message");
109 0 : if let Some(message) = message {
110 0 : let msg: String = match serde_json::from_str(message.get()) {
111 0 : Ok(msg) => msg,
112 : Err(_) => {
113 0 : "Unable to parse the response message from server".to_string()
114 : }
115 : };
116 :
117 0 : error!("Error response from local_proxy: {status} {msg}");
118 :
119 0 : json_map.retain(|key, _| !key.starts_with("neon:")); // remove all the neon-related keys
120 :
121 0 : let resp_json = serde_json::to_string(&json_map)
122 0 : .unwrap_or("failed to serialize the response message".to_string());
123 :
124 0 : return json_response(status, resp_json);
125 0 : }
126 0 : }
127 :
128 0 : error!("Unable to parse the response message from local_proxy");
129 0 : return json_response(
130 0 : status,
131 0 : json!({ "message": "Unable to parse the response message from server".to_string() }),
132 : );
133 0 : }
134 0 : r
135 : }
136 0 : Err(e @ SqlOverHttpError::Cancelled(_)) => {
137 0 : let error_kind = e.get_error_kind();
138 0 : ctx.set_error_kind(error_kind);
139 :
140 0 : let message = "Query cancelled, connection was terminated";
141 :
142 0 : tracing::info!(
143 0 : kind=error_kind.to_metric_label(),
144 : error=%e,
145 : msg=message,
146 0 : "forwarding error to user"
147 : );
148 :
149 0 : json_response(
150 : StatusCode::BAD_REQUEST,
151 0 : json!({ "message": message, "code": SqlState::PROTOCOL_VIOLATION.code() }),
152 0 : )?
153 : }
154 0 : Err(e) => {
155 0 : let error_kind = e.get_error_kind();
156 0 : ctx.set_error_kind(error_kind);
157 :
158 0 : let mut message = e.to_string_client();
159 0 : let db_error = match &e {
160 0 : SqlOverHttpError::ConnectCompute(HttpConnError::PostgresConnectionError(e))
161 0 : | SqlOverHttpError::Postgres(e) => e.as_db_error(),
162 0 : _ => None,
163 : };
164 0 : fn get<'a, T: Default>(db: Option<&'a DbError>, x: impl FnOnce(&'a DbError) -> T) -> T {
165 0 : db.map(x).unwrap_or_default()
166 0 : }
167 :
168 0 : if let Some(db_error) = db_error {
169 0 : db_error.message().clone_into(&mut message);
170 0 : }
171 :
172 0 : let position = db_error.and_then(|db| db.position());
173 0 : let (position, internal_position, internal_query) = match position {
174 0 : Some(ErrorPosition::Original(position)) => (Some(position.to_string()), None, None),
175 0 : Some(ErrorPosition::Internal { position, query }) => {
176 0 : (None, Some(position.to_string()), Some(query.clone()))
177 : }
178 0 : None => (None, None, None),
179 : };
180 :
181 0 : let code = get(db_error, |db| db.code().code());
182 0 : let severity = get(db_error, |db| db.severity());
183 0 : let detail = get(db_error, |db| db.detail());
184 0 : let hint = get(db_error, |db| db.hint());
185 0 : let where_ = get(db_error, |db| db.where_());
186 0 : let table = get(db_error, |db| db.table());
187 0 : let column = get(db_error, |db| db.column());
188 0 : let schema = get(db_error, |db| db.schema());
189 0 : let datatype = get(db_error, |db| db.datatype());
190 0 : let constraint = get(db_error, |db| db.constraint());
191 0 : let file = get(db_error, |db| db.file());
192 0 : let line = get(db_error, |db| db.line().map(|l| l.to_string()));
193 0 : let routine = get(db_error, |db| db.routine());
194 :
195 0 : if db_error.is_some() && error_kind == ErrorKind::User {
196 : // this error contains too much info, and it's not an error we care about.
197 0 : if tracing::enabled!(Level::DEBUG) {
198 0 : debug!(
199 0 : kind=error_kind.to_metric_label(),
200 : error=%e,
201 : msg=message,
202 0 : "forwarding error to user"
203 : );
204 : } else {
205 0 : info!(
206 0 : kind = error_kind.to_metric_label(),
207 : error = "bad query",
208 0 : "forwarding error to user"
209 : );
210 : }
211 : } else {
212 0 : info!(
213 0 : kind=error_kind.to_metric_label(),
214 : error=%e,
215 : msg=message,
216 0 : "forwarding error to user"
217 : );
218 : }
219 :
220 0 : json_response(
221 0 : e.get_http_status_code(),
222 0 : json!({
223 0 : "message": message,
224 0 : "code": code,
225 0 : "detail": detail,
226 0 : "hint": hint,
227 0 : "position": position,
228 0 : "internalPosition": internal_position,
229 0 : "internalQuery": internal_query,
230 0 : "severity": severity,
231 0 : "where": where_,
232 0 : "table": table,
233 0 : "column": column,
234 0 : "schema": schema,
235 0 : "dataType": datatype,
236 0 : "constraint": constraint,
237 0 : "file": file,
238 0 : "line": line,
239 0 : "routine": routine,
240 : }),
241 0 : )?
242 : }
243 : };
244 :
245 0 : response
246 0 : .headers_mut()
247 0 : .insert("Access-Control-Allow-Origin", HeaderValue::from_static("*"));
248 0 : Ok(response)
249 0 : }
250 :
251 : #[derive(Debug, thiserror::Error)]
252 : pub(crate) enum SqlOverHttpError {
253 : #[error("{0}")]
254 : ReadPayload(#[from] ReadPayloadError),
255 : #[error("{0}")]
256 : ConnectCompute(#[from] HttpConnError),
257 : #[error("{0}")]
258 : ConnInfo(#[from] ConnInfoError),
259 : #[error("response is too large (max is {0} bytes)")]
260 : ResponseTooLarge(usize),
261 : #[error("invalid isolation level")]
262 : InvalidIsolationLevel,
263 : /// for queries our customers choose to run
264 : #[error("{0}")]
265 : Postgres(#[source] postgres_client::Error),
266 : /// for queries we choose to run
267 : #[error("{0}")]
268 : InternalPostgres(#[source] postgres_client::Error),
269 : #[error("{0}")]
270 : JsonConversion(#[from] JsonConversionError),
271 : #[error("{0}")]
272 : Cancelled(SqlOverHttpCancel),
273 : }
274 :
275 : impl ReportableError for SqlOverHttpError {
276 0 : fn get_error_kind(&self) -> ErrorKind {
277 0 : match self {
278 0 : SqlOverHttpError::ReadPayload(e) => e.get_error_kind(),
279 0 : SqlOverHttpError::ConnectCompute(e) => e.get_error_kind(),
280 0 : SqlOverHttpError::ConnInfo(e) => e.get_error_kind(),
281 0 : SqlOverHttpError::ResponseTooLarge(_) => ErrorKind::User,
282 0 : SqlOverHttpError::InvalidIsolationLevel => ErrorKind::User,
283 : // customer initiated SQL errors.
284 0 : SqlOverHttpError::Postgres(p) => {
285 0 : if p.as_db_error().is_some() {
286 0 : ErrorKind::User
287 : } else {
288 0 : ErrorKind::Compute
289 : }
290 : }
291 : // proxy initiated SQL errors.
292 0 : SqlOverHttpError::InternalPostgres(p) => {
293 0 : if p.as_db_error().is_some() {
294 0 : ErrorKind::Service
295 : } else {
296 0 : ErrorKind::Compute
297 : }
298 : }
299 : // postgres returned a bad row format that we couldn't parse.
300 0 : SqlOverHttpError::JsonConversion(_) => ErrorKind::Postgres,
301 0 : SqlOverHttpError::Cancelled(c) => c.get_error_kind(),
302 : }
303 0 : }
304 : }
305 :
306 : impl UserFacingError for SqlOverHttpError {
307 0 : fn to_string_client(&self) -> String {
308 0 : match self {
309 0 : SqlOverHttpError::ReadPayload(p) => p.to_string(),
310 0 : SqlOverHttpError::ConnectCompute(c) => c.to_string_client(),
311 0 : SqlOverHttpError::ConnInfo(c) => c.to_string_client(),
312 0 : SqlOverHttpError::ResponseTooLarge(_) => self.to_string(),
313 0 : SqlOverHttpError::InvalidIsolationLevel => self.to_string(),
314 0 : SqlOverHttpError::Postgres(p) => p.to_string(),
315 0 : SqlOverHttpError::InternalPostgres(p) => p.to_string(),
316 0 : SqlOverHttpError::JsonConversion(_) => "could not parse postgres response".to_string(),
317 0 : SqlOverHttpError::Cancelled(_) => self.to_string(),
318 : }
319 0 : }
320 : }
321 :
322 : impl HttpCodeError for SqlOverHttpError {
323 0 : fn get_http_status_code(&self) -> StatusCode {
324 0 : match self {
325 0 : SqlOverHttpError::ReadPayload(e) => e.get_http_status_code(),
326 0 : SqlOverHttpError::ConnectCompute(h) => match h.get_error_kind() {
327 0 : ErrorKind::User => StatusCode::BAD_REQUEST,
328 0 : _ => StatusCode::INTERNAL_SERVER_ERROR,
329 : },
330 0 : SqlOverHttpError::ConnInfo(_) => StatusCode::BAD_REQUEST,
331 0 : SqlOverHttpError::ResponseTooLarge(_) => StatusCode::INSUFFICIENT_STORAGE,
332 0 : SqlOverHttpError::InvalidIsolationLevel => StatusCode::BAD_REQUEST,
333 0 : SqlOverHttpError::Postgres(_) => StatusCode::BAD_REQUEST,
334 0 : SqlOverHttpError::InternalPostgres(_) => StatusCode::INTERNAL_SERVER_ERROR,
335 0 : SqlOverHttpError::JsonConversion(_) => StatusCode::INTERNAL_SERVER_ERROR,
336 0 : SqlOverHttpError::Cancelled(_) => StatusCode::INTERNAL_SERVER_ERROR,
337 : }
338 0 : }
339 : }
340 :
341 : #[derive(Debug, thiserror::Error)]
342 : pub(crate) enum SqlOverHttpCancel {
343 : #[error("query was cancelled")]
344 : Postgres,
345 : #[error("query was cancelled while stuck trying to connect to the database")]
346 : Connect,
347 : }
348 :
349 : impl ReportableError for SqlOverHttpCancel {
350 0 : fn get_error_kind(&self) -> ErrorKind {
351 0 : match self {
352 0 : SqlOverHttpCancel::Postgres => ErrorKind::ClientDisconnect,
353 0 : SqlOverHttpCancel::Connect => ErrorKind::ClientDisconnect,
354 : }
355 0 : }
356 : }
357 :
358 : #[derive(Clone, Copy, Debug)]
359 : struct HttpHeaders {
360 : raw_output: bool,
361 : default_array_mode: bool,
362 : txn_isolation_level: Option<IsolationLevel>,
363 : txn_read_only: bool,
364 : txn_deferrable: bool,
365 : }
366 :
367 : impl HttpHeaders {
368 0 : fn try_parse(headers: &hyper::http::HeaderMap) -> Result<Self, SqlOverHttpError> {
369 : // Determine the output options. Default behaviour is 'false'. Anything that is not
370 : // strictly 'true' assumed to be false.
371 0 : let raw_output = headers.get(&RAW_TEXT_OUTPUT) == Some(&HEADER_VALUE_TRUE);
372 0 : let default_array_mode = headers.get(&ARRAY_MODE) == Some(&HEADER_VALUE_TRUE);
373 :
374 : // isolation level, read only and deferrable
375 0 : let txn_isolation_level = match headers.get(&TXN_ISOLATION_LEVEL) {
376 0 : Some(x) => Some(
377 0 : map_header_to_isolation_level(x).ok_or(SqlOverHttpError::InvalidIsolationLevel)?,
378 : ),
379 0 : None => None,
380 : };
381 :
382 0 : let txn_read_only = headers.get(&TXN_READ_ONLY) == Some(&HEADER_VALUE_TRUE);
383 0 : let txn_deferrable = headers.get(&TXN_DEFERRABLE) == Some(&HEADER_VALUE_TRUE);
384 :
385 0 : Ok(Self {
386 0 : raw_output,
387 0 : default_array_mode,
388 0 : txn_isolation_level,
389 0 : txn_read_only,
390 0 : txn_deferrable,
391 0 : })
392 0 : }
393 : }
394 :
395 0 : fn map_header_to_isolation_level(level: &HeaderValue) -> Option<IsolationLevel> {
396 0 : match level.as_bytes() {
397 0 : b"Serializable" => Some(IsolationLevel::Serializable),
398 0 : b"ReadUncommitted" => Some(IsolationLevel::ReadUncommitted),
399 0 : b"ReadCommitted" => Some(IsolationLevel::ReadCommitted),
400 0 : b"RepeatableRead" => Some(IsolationLevel::RepeatableRead),
401 0 : _ => None,
402 : }
403 0 : }
404 :
405 0 : fn map_isolation_level_to_headers(level: IsolationLevel) -> Option<HeaderValue> {
406 0 : match level {
407 0 : IsolationLevel::ReadUncommitted => Some(HeaderValue::from_static("ReadUncommitted")),
408 0 : IsolationLevel::ReadCommitted => Some(HeaderValue::from_static("ReadCommitted")),
409 0 : IsolationLevel::RepeatableRead => Some(HeaderValue::from_static("RepeatableRead")),
410 0 : IsolationLevel::Serializable => Some(HeaderValue::from_static("Serializable")),
411 0 : _ => None,
412 : }
413 0 : }
414 :
415 0 : async fn handle_inner(
416 0 : cancel: CancellationToken,
417 0 : config: &'static ProxyConfig,
418 0 : ctx: &RequestContext,
419 0 : request: Request<Incoming>,
420 0 : backend: Arc<PoolingBackend>,
421 0 : ) -> Result<Response<BoxBody<Bytes, hyper::Error>>, SqlOverHttpError> {
422 0 : let _requeset_gauge = Metrics::get()
423 0 : .proxy
424 0 : .connection_requests
425 0 : .guard(ctx.protocol());
426 0 : info!(
427 0 : protocol = %ctx.protocol(),
428 0 : "handling interactive connection from client"
429 : );
430 :
431 0 : let conn_info = get_conn_info(&config.authentication_config, ctx, None, request.headers())?;
432 0 : info!(
433 0 : user = conn_info.conn_info.user_info.user.as_str(),
434 0 : "credentials"
435 : );
436 :
437 0 : match conn_info.auth {
438 0 : AuthData::Jwt(jwt) if config.authentication_config.is_auth_broker => {
439 0 : handle_auth_broker_inner(ctx, request, conn_info.conn_info, jwt, backend).await
440 : }
441 0 : auth => {
442 0 : handle_db_inner(
443 0 : cancel,
444 0 : config,
445 0 : ctx,
446 0 : request,
447 0 : conn_info.conn_info,
448 0 : auth,
449 0 : backend,
450 0 : )
451 0 : .await
452 : }
453 : }
454 0 : }
455 :
456 0 : async fn handle_db_inner(
457 0 : cancel: CancellationToken,
458 0 : config: &'static ProxyConfig,
459 0 : ctx: &RequestContext,
460 0 : request: Request<Incoming>,
461 0 : conn_info: ConnInfo,
462 0 : auth: AuthData,
463 0 : backend: Arc<PoolingBackend>,
464 0 : ) -> Result<Response<BoxBody<Bytes, hyper::Error>>, SqlOverHttpError> {
465 : //
466 : // Determine the destination and connection params
467 : //
468 0 : let headers = request.headers();
469 :
470 : // Allow connection pooling only if explicitly requested
471 : // or if we have decided that http pool is no longer opt-in
472 0 : let allow_pool = !config.http_config.pool_options.opt_in
473 0 : || headers.get(&ALLOW_POOL) == Some(&HEADER_VALUE_TRUE);
474 :
475 0 : let parsed_headers = HttpHeaders::try_parse(headers)?;
476 :
477 0 : let mut request_len = 0;
478 0 : let fetch_and_process_request = Box::pin(
479 0 : async {
480 0 : let body = read_body_with_limit(
481 0 : request.into_body(),
482 0 : config.http_config.max_request_size_bytes,
483 0 : )
484 0 : .await?;
485 :
486 0 : request_len = body.len();
487 :
488 0 : Metrics::get()
489 0 : .proxy
490 0 : .http_conn_content_length_bytes
491 0 : .observe(HttpDirection::Request, body.len() as f64);
492 :
493 0 : debug!(length = body.len(), "request payload read");
494 0 : let payload: Payload = serde_json::from_slice(&body)?;
495 0 : Ok::<Payload, ReadPayloadError>(payload) // Adjust error type accordingly
496 0 : }
497 0 : .map_err(SqlOverHttpError::from),
498 : );
499 :
500 0 : let authenticate_and_connect = Box::pin(
501 0 : async {
502 0 : let keys = match auth {
503 0 : AuthData::Password(pw) => backend
504 0 : .authenticate_with_password(ctx, &conn_info.user_info, &pw)
505 0 : .await
506 0 : .map_err(HttpConnError::AuthError)?,
507 0 : AuthData::Jwt(jwt) => backend
508 0 : .authenticate_with_jwt(ctx, &conn_info.user_info, jwt)
509 0 : .await
510 0 : .map_err(HttpConnError::AuthError)?,
511 : };
512 :
513 0 : let client = match keys.keys {
514 0 : ComputeCredentialKeys::JwtPayload(payload)
515 0 : if backend.auth_backend.is_local_proxy() =>
516 : {
517 : #[cfg(feature = "testing")]
518 0 : let disable_pg_session_jwt = config.disable_pg_session_jwt;
519 : #[cfg(not(feature = "testing"))]
520 : let disable_pg_session_jwt = false;
521 0 : let mut client = backend
522 0 : .connect_to_local_postgres(ctx, conn_info, disable_pg_session_jwt)
523 0 : .await?;
524 0 : if !disable_pg_session_jwt {
525 0 : let (cli_inner, _dsc) = client.client_inner();
526 0 : cli_inner.set_jwt_session(&payload).await?;
527 0 : }
528 0 : Client::Local(client)
529 : }
530 : _ => {
531 0 : let client = backend
532 0 : .connect_to_compute(ctx, conn_info, keys, !allow_pool)
533 0 : .await?;
534 0 : Client::Remote(client)
535 : }
536 : };
537 :
538 : // not strictly necessary to mark success here,
539 : // but it's just insurance for if we forget it somewhere else
540 0 : ctx.success();
541 0 : Ok::<_, SqlOverHttpError>(client)
542 0 : }
543 0 : .map_err(SqlOverHttpError::from),
544 : );
545 :
546 0 : let (payload, mut client) = match run_until_cancelled(
547 : // Run both operations in parallel
548 0 : try_join(
549 0 : pin!(fetch_and_process_request),
550 0 : pin!(authenticate_and_connect),
551 : ),
552 0 : &cancel,
553 : )
554 0 : .await
555 : {
556 0 : Some(result) => result?,
557 0 : None => return Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Connect)),
558 : };
559 :
560 0 : let mut response = Response::builder()
561 0 : .status(StatusCode::OK)
562 0 : .header(header::CONTENT_TYPE, "application/json");
563 :
564 : // Now execute the query and return the result.
565 0 : let json_output = match payload {
566 0 : Payload::Single(stmt) => {
567 0 : stmt.process(&config.http_config, cancel, &mut client, parsed_headers)
568 0 : .await?
569 : }
570 0 : Payload::Batch(statements) => {
571 0 : if parsed_headers.txn_read_only {
572 0 : response = response.header(TXN_READ_ONLY.clone(), &HEADER_VALUE_TRUE);
573 0 : }
574 0 : if parsed_headers.txn_deferrable {
575 0 : response = response.header(TXN_DEFERRABLE.clone(), &HEADER_VALUE_TRUE);
576 0 : }
577 0 : if let Some(txn_isolation_level) = parsed_headers
578 0 : .txn_isolation_level
579 0 : .and_then(map_isolation_level_to_headers)
580 0 : {
581 0 : response = response.header(TXN_ISOLATION_LEVEL.clone(), txn_isolation_level);
582 0 : }
583 :
584 0 : statements
585 0 : .process(&config.http_config, cancel, &mut client, parsed_headers)
586 0 : .await?
587 : }
588 : };
589 :
590 0 : let metrics = client.metrics(ctx);
591 :
592 0 : let len = json_output.len();
593 0 : let response = response
594 0 : .body(
595 0 : Full::new(Bytes::from(json_output))
596 0 : .map_err(|x| match x {})
597 0 : .boxed(),
598 : )
599 : // only fails if invalid status code or invalid header/values are given.
600 : // these are not user configurable so it cannot fail dynamically
601 0 : .expect("building response payload should not fail");
602 :
603 : // count the egress bytes - we miss the TLS and header overhead but oh well...
604 : // moving this later in the stack is going to be a lot of effort and ehhhh
605 0 : metrics.record_egress(len as u64);
606 0 : metrics.record_ingress(request_len as u64);
607 :
608 0 : Metrics::get()
609 0 : .proxy
610 0 : .http_conn_content_length_bytes
611 0 : .observe(HttpDirection::Response, len as f64);
612 :
613 0 : Ok(response)
614 0 : }
615 :
616 : static HEADERS_TO_FORWARD: &[&HeaderName] = &[
617 : &AUTHORIZATION,
618 : &CONN_STRING,
619 : &RAW_TEXT_OUTPUT,
620 : &ARRAY_MODE,
621 : &TXN_ISOLATION_LEVEL,
622 : &TXN_READ_ONLY,
623 : &TXN_DEFERRABLE,
624 : ];
625 :
626 0 : async fn handle_auth_broker_inner(
627 0 : ctx: &RequestContext,
628 0 : request: Request<Incoming>,
629 0 : conn_info: ConnInfo,
630 0 : jwt: String,
631 0 : backend: Arc<PoolingBackend>,
632 0 : ) -> Result<Response<BoxBody<Bytes, hyper::Error>>, SqlOverHttpError> {
633 0 : backend
634 0 : .authenticate_with_jwt(ctx, &conn_info.user_info, jwt)
635 0 : .await
636 0 : .map_err(HttpConnError::from)?;
637 :
638 0 : let mut client = backend.connect_to_local_proxy(ctx, conn_info).await?;
639 :
640 0 : let local_proxy_uri = ::http::Uri::from_static("http://proxy.local/sql");
641 :
642 0 : let (mut parts, body) = request.into_parts();
643 0 : let mut req = Request::builder().method(Method::POST).uri(local_proxy_uri);
644 :
645 : // todo(conradludgate): maybe auth-broker should parse these and re-serialize
646 : // these instead just to ensure they remain normalised.
647 0 : for &h in HEADERS_TO_FORWARD {
648 0 : if let Some(hv) = parts.headers.remove(h) {
649 0 : req = req.header(h, hv);
650 0 : }
651 : }
652 0 : req = req.header(&NEON_REQUEST_ID, uuid_to_header_value(ctx.session_id()));
653 :
654 0 : let req = req
655 0 : .body(body.map_err(|e| e).boxed()) //TODO: is there a potential for a regression here?
656 0 : .expect("all headers and params received via hyper should be valid for request");
657 :
658 : // todo: map body to count egress
659 0 : let _metrics = client.metrics(ctx);
660 :
661 0 : Ok(client
662 0 : .inner
663 0 : .inner
664 0 : .send_request(req)
665 0 : .await
666 0 : .map_err(LocalProxyConnError::from)
667 0 : .map_err(HttpConnError::from)?
668 0 : .map(|b| b.boxed()))
669 0 : }
670 :
671 : impl QueryData {
672 0 : async fn process(
673 0 : self,
674 0 : config: &'static HttpConfig,
675 0 : cancel: CancellationToken,
676 0 : client: &mut Client,
677 0 : parsed_headers: HttpHeaders,
678 0 : ) -> Result<String, SqlOverHttpError> {
679 0 : let (inner, mut discard) = client.inner();
680 0 : let cancel_token = inner.cancel_token();
681 :
682 0 : let mut json_buf = vec![];
683 :
684 0 : let batch_result = match select(
685 0 : pin!(query_to_json(
686 0 : config,
687 0 : &mut *inner,
688 0 : self,
689 0 : json::ValueSer::new(&mut json_buf),
690 0 : parsed_headers
691 : )),
692 0 : pin!(cancel.cancelled()),
693 : )
694 0 : .await
695 : {
696 0 : Either::Left((res, __not_yet_cancelled)) => res,
697 0 : Either::Right((_cancelled, query)) => {
698 0 : tracing::info!("cancelling query");
699 0 : if let Err(err) = cancel_token.cancel_query(NoTls).await {
700 0 : tracing::warn!(?err, "could not cancel query");
701 0 : }
702 : // wait for the query cancellation
703 0 : match time::timeout(time::Duration::from_millis(100), query).await {
704 : // query successed before it was cancelled.
705 0 : Ok(Ok(status)) => Ok(status),
706 : // query failed or was cancelled.
707 0 : Ok(Err(error)) => {
708 0 : let db_error = match &error {
709 : SqlOverHttpError::ConnectCompute(
710 0 : HttpConnError::PostgresConnectionError(e),
711 : )
712 0 : | SqlOverHttpError::Postgres(e) => e.as_db_error(),
713 0 : _ => None,
714 : };
715 :
716 : // if errored for some other reason, it might not be safe to return
717 0 : if !db_error.is_some_and(|e| *e.code() == SqlState::QUERY_CANCELED) {
718 0 : discard.discard();
719 0 : }
720 :
721 0 : return Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Postgres));
722 : }
723 0 : Err(_timeout) => {
724 0 : discard.discard();
725 0 : return Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Postgres));
726 : }
727 : }
728 : }
729 : };
730 :
731 0 : match batch_result {
732 : // The query successfully completed.
733 : Ok(_) => {
734 0 : let json_output = String::from_utf8(json_buf).expect("json should be valid utf8");
735 0 : Ok(json_output)
736 : }
737 : // The query failed with an error
738 0 : Err(e) => {
739 0 : discard.discard();
740 0 : Err(e)
741 : }
742 : }
743 0 : }
744 : }
745 :
746 : impl BatchQueryData {
747 0 : async fn process(
748 0 : self,
749 0 : config: &'static HttpConfig,
750 0 : cancel: CancellationToken,
751 0 : client: &mut Client,
752 0 : parsed_headers: HttpHeaders,
753 0 : ) -> Result<String, SqlOverHttpError> {
754 0 : info!("starting transaction");
755 0 : let (inner, mut discard) = client.inner();
756 0 : let cancel_token = inner.cancel_token();
757 0 : let mut builder = inner.build_transaction();
758 0 : if let Some(isolation_level) = parsed_headers.txn_isolation_level {
759 0 : builder = builder.isolation_level(isolation_level);
760 0 : }
761 0 : if parsed_headers.txn_read_only {
762 0 : builder = builder.read_only(true);
763 0 : }
764 0 : if parsed_headers.txn_deferrable {
765 0 : builder = builder.deferrable(true);
766 0 : }
767 :
768 0 : let mut transaction = builder
769 0 : .start()
770 0 : .await
771 0 : .inspect_err(|_| {
772 : // if we cannot start a transaction, we should return immediately
773 : // and not return to the pool. connection is clearly broken
774 0 : discard.discard();
775 0 : })
776 0 : .map_err(SqlOverHttpError::Postgres)?;
777 :
778 0 : let json_output = match query_batch_to_json(
779 0 : config,
780 0 : cancel.child_token(),
781 0 : &mut transaction,
782 0 : self,
783 0 : parsed_headers,
784 : )
785 0 : .await
786 : {
787 0 : Ok(json_output) => {
788 0 : info!("commit");
789 0 : transaction
790 0 : .commit()
791 0 : .await
792 0 : .inspect_err(|_| {
793 : // if we cannot commit - for now don't return connection to pool
794 : // TODO: get a query status from the error
795 0 : discard.discard();
796 0 : })
797 0 : .map_err(SqlOverHttpError::Postgres)?;
798 0 : json_output
799 : }
800 : Err(SqlOverHttpError::Cancelled(_)) => {
801 0 : if let Err(err) = cancel_token.cancel_query(NoTls).await {
802 0 : tracing::warn!(?err, "could not cancel query");
803 0 : }
804 : // TODO: after cancelling, wait to see if we can get a status. maybe the connection is still safe.
805 0 : discard.discard();
806 :
807 0 : return Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Postgres));
808 : }
809 0 : Err(err) => {
810 0 : return Err(err);
811 : }
812 : };
813 :
814 0 : Ok(json_output)
815 0 : }
816 : }
817 :
818 0 : async fn query_batch(
819 0 : config: &'static HttpConfig,
820 0 : cancel: CancellationToken,
821 0 : transaction: &mut Transaction<'_>,
822 0 : queries: BatchQueryData,
823 0 : parsed_headers: HttpHeaders,
824 0 : results: &mut json::ListSer<'_>,
825 0 : ) -> Result<(), SqlOverHttpError> {
826 0 : for stmt in queries.queries {
827 0 : let query = pin!(query_to_json(
828 0 : config,
829 0 : transaction,
830 0 : stmt,
831 0 : results.entry(),
832 0 : parsed_headers,
833 : ));
834 0 : let cancelled = pin!(cancel.cancelled());
835 0 : let res = select(query, cancelled).await;
836 0 : match res {
837 : // TODO: maybe we should check that the transaction bit is set here
838 0 : Either::Left((Ok(_), _cancelled)) => {}
839 0 : Either::Left((Err(e), _cancelled)) => {
840 0 : return Err(e);
841 : }
842 0 : Either::Right((_cancelled, _)) => {
843 0 : return Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Postgres));
844 : }
845 : }
846 : }
847 :
848 0 : Ok(())
849 0 : }
850 :
851 0 : async fn query_batch_to_json(
852 0 : config: &'static HttpConfig,
853 0 : cancel: CancellationToken,
854 0 : tx: &mut Transaction<'_>,
855 0 : queries: BatchQueryData,
856 0 : headers: HttpHeaders,
857 0 : ) -> Result<String, SqlOverHttpError> {
858 0 : let json_output = json::value_to_string!(|obj| json::value_as_object!(|obj| {
859 0 : let results = obj.key("results");
860 0 : json::value_as_list!(|results| {
861 0 : query_batch(config, cancel, tx, queries, headers, results).await?;
862 : });
863 : }));
864 :
865 0 : Ok(json_output)
866 0 : }
867 :
868 0 : async fn query_to_json<T: GenericClient>(
869 0 : config: &'static HttpConfig,
870 0 : client: &mut T,
871 0 : data: QueryData,
872 0 : output: json::ValueSer<'_>,
873 0 : parsed_headers: HttpHeaders,
874 0 : ) -> Result<ReadyForQueryStatus, SqlOverHttpError> {
875 0 : let query_start = Instant::now();
876 :
877 0 : let mut output = json::ObjectSer::new(output);
878 0 : let mut row_stream = client
879 0 : .query_raw_txt(&data.query, data.params)
880 0 : .await
881 0 : .map_err(SqlOverHttpError::Postgres)?;
882 0 : let query_acknowledged = Instant::now();
883 :
884 0 : let mut json_fields = output.key("fields").list();
885 0 : for c in row_stream.statement.columns() {
886 0 : let json_field = json_fields.entry();
887 0 : json::value_as_object!(|json_field| {
888 0 : json_field.entry("name", c.name());
889 0 : json_field.entry("dataTypeID", c.type_().oid());
890 0 : json_field.entry("tableID", c.table_oid());
891 0 : json_field.entry("columnID", c.column_id());
892 0 : json_field.entry("dataTypeSize", c.type_size());
893 0 : json_field.entry("dataTypeModifier", c.type_modifier());
894 0 : json_field.entry("format", "text");
895 0 : });
896 0 : }
897 0 : json_fields.finish();
898 :
899 0 : let array_mode = data.array_mode.unwrap_or(parsed_headers.default_array_mode);
900 0 : let raw_output = parsed_headers.raw_output;
901 :
902 : // Manually drain the stream into a vector to leave row_stream hanging
903 : // around to get a command tag. Also check that the response is not too
904 : // big.
905 0 : let mut rows = 0;
906 0 : let mut json_rows = output.key("rows").list();
907 0 : while let Some(row) = row_stream.next().await {
908 0 : let row = row.map_err(SqlOverHttpError::Postgres)?;
909 :
910 : // we don't have a streaming response support yet so this is to prevent OOM
911 : // from a malicious query (eg a cross join)
912 0 : if json_rows.as_buffer().len() > config.max_response_size_bytes {
913 0 : return Err(SqlOverHttpError::ResponseTooLarge(
914 0 : config.max_response_size_bytes,
915 0 : ));
916 0 : }
917 :
918 0 : pg_text_row_to_json(json_rows.entry(), &row, raw_output, array_mode)?;
919 0 : rows += 1;
920 :
921 : // assumption: parsing pg text and converting to json takes CPU time.
922 : // let's assume it is slightly expensive, so we should consume some cooperative budget.
923 : // Especially considering that `RowStream::next` might be pulling from a batch
924 : // of rows and never hit the tokio mpsc for a long time (although unlikely).
925 0 : tokio::task::consume_budget().await;
926 : }
927 0 : json_rows.finish();
928 :
929 0 : let query_resp_end = Instant::now();
930 :
931 0 : let ready = row_stream.status;
932 :
933 : // grab the command tag and number of rows affected
934 0 : let command_tag = row_stream.command_tag.unwrap_or_default();
935 0 : let mut command_tag_split = command_tag.split(' ');
936 0 : let command_tag_name = command_tag_split.next().unwrap_or_default();
937 0 : let command_tag_count = if command_tag_name == "INSERT" {
938 : // INSERT returns OID first and then number of rows
939 0 : command_tag_split.nth(1)
940 : } else {
941 : // other commands return number of rows (if any)
942 0 : command_tag_split.next()
943 : }
944 0 : .and_then(|s| s.parse::<i64>().ok());
945 :
946 0 : info!(
947 : rows,
948 : ?ready,
949 : command_tag,
950 0 : acknowledgement = ?(query_acknowledged - query_start),
951 0 : response = ?(query_resp_end - query_start),
952 0 : "finished executing query"
953 : );
954 :
955 0 : output.entry("command", command_tag_name);
956 0 : output.entry("rowCount", command_tag_count);
957 0 : output.entry("rowAsArray", array_mode);
958 :
959 0 : output.finish();
960 0 : Ok(ready)
961 0 : }
962 :
963 : enum Client {
964 : Remote(conn_pool_lib::Client<postgres_client::Client>),
965 : Local(conn_pool_lib::Client<postgres_client::Client>),
966 : }
967 :
968 : enum Discard<'a> {
969 : Remote(conn_pool_lib::Discard<'a, postgres_client::Client>),
970 : Local(conn_pool_lib::Discard<'a, postgres_client::Client>),
971 : }
972 :
973 : impl Client {
974 0 : fn metrics(&self, ctx: &RequestContext) -> Arc<MetricCounter> {
975 0 : match self {
976 0 : Client::Remote(client) => client.metrics(ctx),
977 0 : Client::Local(local_client) => local_client.metrics(ctx),
978 : }
979 0 : }
980 :
981 0 : fn inner(&mut self) -> (&mut postgres_client::Client, Discard<'_>) {
982 0 : match self {
983 0 : Client::Remote(client) => {
984 0 : let (c, d) = client.inner();
985 0 : (c, Discard::Remote(d))
986 : }
987 0 : Client::Local(local_client) => {
988 0 : let (c, d) = local_client.inner();
989 0 : (c, Discard::Local(d))
990 : }
991 : }
992 0 : }
993 : }
994 :
995 : impl Discard<'_> {
996 0 : fn discard(&mut self) {
997 0 : match self {
998 0 : Discard::Remote(discard) => discard.discard(),
999 0 : Discard::Local(discard) => discard.discard(),
1000 : }
1001 0 : }
1002 : }
1003 :
1004 : #[cfg(test)]
1005 : mod tests {
1006 : use super::*;
1007 :
1008 : #[test]
1009 1 : fn test_payload() {
1010 1 : let payload = "{\"query\":\"SELECT * FROM users WHERE name = ?\",\"params\":[\"test\"],\"arrayMode\":true}";
1011 1 : let deserialized_payload: Payload = serde_json::from_str(payload).unwrap();
1012 :
1013 1 : match deserialized_payload {
1014 : Payload::Single(QueryData {
1015 1 : query,
1016 1 : params,
1017 1 : array_mode,
1018 : }) => {
1019 1 : assert_eq!(query, "SELECT * FROM users WHERE name = ?");
1020 1 : assert_eq!(params, vec![Some(String::from("test"))]);
1021 1 : assert!(array_mode.unwrap());
1022 : }
1023 : Payload::Batch(_) => {
1024 0 : panic!("deserialization failed: case with single query, one param, and array mode")
1025 : }
1026 : }
1027 :
1028 1 : let payload = "{\"queries\":[{\"query\":\"SELECT * FROM users0 WHERE name = ?\",\"params\":[\"test0\"], \"arrayMode\":false},{\"query\":\"SELECT * FROM users1 WHERE name = ?\",\"params\":[\"test1\"],\"arrayMode\":true}]}";
1029 1 : let deserialized_payload: Payload = serde_json::from_str(payload).unwrap();
1030 :
1031 1 : match deserialized_payload {
1032 1 : Payload::Batch(BatchQueryData { queries }) => {
1033 1 : assert_eq!(queries.len(), 2);
1034 2 : for (i, query) in queries.into_iter().enumerate() {
1035 2 : assert_eq!(
1036 : query.query,
1037 2 : format!("SELECT * FROM users{i} WHERE name = ?")
1038 : );
1039 2 : assert_eq!(query.params, vec![Some(format!("test{i}"))]);
1040 2 : assert_eq!(query.array_mode.unwrap(), i > 0);
1041 : }
1042 : }
1043 0 : Payload::Single(_) => panic!("deserialization failed: case with multiple queries"),
1044 : }
1045 :
1046 1 : let payload = "{\"query\":\"SELECT 1\"}";
1047 1 : let deserialized_payload: Payload = serde_json::from_str(payload).unwrap();
1048 :
1049 1 : match deserialized_payload {
1050 : Payload::Single(QueryData {
1051 1 : query,
1052 1 : params,
1053 1 : array_mode,
1054 : }) => {
1055 1 : assert_eq!(query, "SELECT 1");
1056 1 : assert_eq!(params, vec![]);
1057 1 : assert!(array_mode.is_none());
1058 : }
1059 0 : Payload::Batch(_) => panic!("deserialization failed: case with only one query"),
1060 : }
1061 1 : }
1062 : }
|