Skip to main content

mz_environmentd/http/
sql.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::collections::BTreeMap;
11use std::net::{IpAddr, SocketAddr};
12use std::pin::pin;
13use std::sync::Arc;
14use std::time::{Duration, Instant};
15
16use anyhow::anyhow;
17use async_trait::async_trait;
18use axum::extract::connect_info::ConnectInfo;
19use axum::extract::ws::{CloseFrame, Message, Utf8Bytes, WebSocket};
20use axum::extract::{State, WebSocketUpgrade};
21use axum::response::IntoResponse;
22use axum::{Extension, Json};
23use futures::Future;
24use futures::SinkExt;
25use futures::future::BoxFuture;
26
27use http::StatusCode;
28use itertools::Itertools;
29use mz_adapter::client::{RecordFirstRowStream, redact_sql_for_logging};
30use mz_adapter::session::{EndTransactionAction, TransactionStatus};
31use mz_adapter::statement_logging::{StatementEndedExecutionReason, StatementExecutionStrategy};
32use mz_adapter::{
33    AdapterError, AdapterNotice, ExecuteContextGuard, ExecuteResponse, ExecuteResponseKind,
34    ExecutionTime, PeekResponseUnary, SessionClient, verify_datum_desc,
35};
36use mz_auth::password::Password;
37use mz_catalog::memory::objects::{Cluster, ClusterReplica};
38use mz_interchange::encode::TypedDatum;
39use mz_interchange::json::{JsonNumberPolicy, ToJson};
40use mz_ore::cast::CastFrom;
41use mz_ore::metrics::{MakeCollectorOpts, MetricsRegistry};
42use mz_ore::result::ResultExt;
43use mz_ore::sql::Sql;
44use mz_repr::{Datum, RelationDesc, RowArena, RowIterator};
45use mz_sql::ast::display::AstDisplay;
46use mz_sql::ast::{CopyDirection, CopyStatement, CopyTarget, Raw, Statement, StatementKind};
47use mz_sql::parse::StatementParseResult;
48use mz_sql::plan::Plan;
49use mz_sql::session::metadata::SessionMetadata;
50use prometheus::Opts;
51use prometheus::core::{AtomicF64, GenericGaugeVec};
52use serde::{Deserialize, Serialize};
53use tokio::{select, time};
54use tokio_postgres::error::SqlState;
55use tower_sessions::Session as TowerSession;
56use tracing::{debug, info};
57use tungstenite::protocol::frame::coding::CloseCode;
58
59use crate::http::prometheus::PrometheusSqlQuery;
60use crate::http::{
61    AuthError, AuthedClient, AuthedUser, MAX_REQUEST_SIZE, WsState, ensure_session_unexpired,
62    init_ws, maybe_get_authenticated_session,
63};
64
65#[derive(Debug, thiserror::Error)]
66pub enum Error {
67    #[error(transparent)]
68    Adapter(#[from] AdapterError),
69    #[error(transparent)]
70    Json(#[from] serde_json::Error),
71    #[error(transparent)]
72    Axum(#[from] axum::Error),
73    #[error("SUBSCRIBE only supported over websocket")]
74    SubscribeOnlyOverWs,
75    #[error("current transaction is aborted, commands ignored until end of transaction block")]
76    AbortedTransaction,
77    #[error("unsupported via this API: {0}")]
78    Unsupported(String),
79    #[error("{0}")]
80    Unstructured(anyhow::Error),
81}
82
83impl Error {
84    pub fn detail(&self) -> Option<String> {
85        match self {
86            Error::Adapter(err) => err.detail(),
87            _ => None,
88        }
89    }
90
91    pub fn hint(&self) -> Option<String> {
92        match self {
93            Error::Adapter(err) => err.hint(),
94            _ => None,
95        }
96    }
97
98    pub fn position(&self) -> Option<usize> {
99        match self {
100            Error::Adapter(err) => err.position(),
101            _ => None,
102        }
103    }
104
105    pub fn code(&self) -> SqlState {
106        match self {
107            Error::Adapter(err) => err.code(),
108            Error::AbortedTransaction => SqlState::IN_FAILED_SQL_TRANSACTION,
109            _ => SqlState::INTERNAL_ERROR,
110        }
111    }
112}
113
114static PER_REPLICA_LABELS: &[&str] = &["replica_full_name", "instance_id", "replica_id"];
115
116async fn execute_promsql_query(
117    client: &mut AuthedClient,
118    query: &PrometheusSqlQuery<'_>,
119    metrics_registry: &MetricsRegistry,
120    metrics_by_name: &mut BTreeMap<String, GenericGaugeVec<AtomicF64>>,
121    cluster: Option<(&Cluster, &ClusterReplica)>,
122) {
123    assert_eq!(query.per_replica, cluster.is_some());
124
125    let mut res = SqlResponse {
126        results: Vec::new(),
127    };
128
129    execute_request(client, query.to_sql_request(cluster), &mut res)
130        .await
131        .expect("valid SQL query");
132
133    let result = match res.results.as_slice() {
134        // Each query issued is preceded by several SET commands
135        // to make sure it is routed to the right cluster replica.
136        [
137            SqlResult::Ok { .. },
138            SqlResult::Ok { .. },
139            SqlResult::Ok { .. },
140            result,
141        ] => result,
142        // Transient errors are fine, like if the cluster or replica
143        // was dropped before the promsql query was executed. We
144        // should not see errors in the steady state.
145        _ => {
146            info!(
147                "error executing prometheus query {}: {:?}",
148                query.metric_name, res
149            );
150            return;
151        }
152    };
153
154    let SqlResult::Rows { desc, rows, .. } = result else {
155        info!(
156            "did not receive rows for SQL query for prometheus metric {}: {:?}, {:?}",
157            query.metric_name, result, cluster
158        );
159        return;
160    };
161
162    let gauge_vec = metrics_by_name
163        .entry(query.metric_name.to_string())
164        .or_insert_with(|| {
165            let mut label_names: Vec<String> = desc
166                .columns
167                .iter()
168                .filter(|col| col.name != query.value_column_name)
169                .map(|col| col.name.clone())
170                .collect();
171
172            if query.per_replica {
173                label_names.extend(PER_REPLICA_LABELS.iter().map(|label| label.to_string()));
174            }
175
176            metrics_registry.register::<GenericGaugeVec<AtomicF64>>(MakeCollectorOpts {
177                opts: Opts::new(query.metric_name, query.help).variable_labels(label_names),
178                buckets: None,
179            })
180        });
181
182    for row in rows {
183        // Rows are stored as pre-serialized JSON arrays. Parse each one back to
184        // `Value`s here. Promsql results are tiny, so the parse cost is
185        // negligible.
186        let row: Vec<serde_json::Value> =
187            serde_json::from_str(row.get()).expect("row is a valid JSON array");
188
189        // Non-value columns become Prometheus label values. A SQL `NULL`
190        // arrives as JSON `null` and yields `None` from `as_str()`; fall back
191        // to an empty label rather than panicking. The query author is
192        // responsible for `COALESCE`ing nullable columns to a meaningful
193        // value; this is a defensive backstop.
194        let mut label_values = desc
195            .columns
196            .iter()
197            .zip_eq(&row)
198            .filter(|(col, _)| col.name != query.value_column_name)
199            .map(|(_, val)| val.as_str().unwrap_or(""))
200            .collect::<Vec<_>>();
201
202        let value = desc
203            .columns
204            .iter()
205            .zip_eq(&row)
206            .find(|(col, _)| col.name == query.value_column_name)
207            .map(|(_, val)| val.as_str().unwrap_or("0").parse::<f64>().unwrap_or(0.0))
208            .unwrap_or(0.0);
209
210        match cluster {
211            Some((cluster, replica)) => {
212                let replica_full_name = format!("{}.{}", cluster.name, replica.name);
213                let cluster_id = cluster.id.to_string();
214                let replica_id = replica.replica_id.to_string();
215
216                label_values.push(&replica_full_name);
217                label_values.push(&cluster_id);
218                label_values.push(&replica_id);
219
220                gauge_vec
221                    .get_metric_with_label_values(&label_values)
222                    .expect("valid labels")
223                    .set(value);
224            }
225            None => {
226                gauge_vec
227                    .get_metric_with_label_values(&label_values)
228                    .expect("valid labels")
229                    .set(value);
230            }
231        }
232    }
233}
234
235async fn handle_promsql_query(
236    client: &mut AuthedClient,
237    query: &PrometheusSqlQuery<'_>,
238    metrics_registry: &MetricsRegistry,
239    metrics_by_name: &mut BTreeMap<String, GenericGaugeVec<AtomicF64>>,
240) {
241    if !query.per_replica {
242        execute_promsql_query(client, query, metrics_registry, metrics_by_name, None).await;
243        return;
244    }
245
246    let catalog = client.client.catalog_snapshot("handle_promsql_query").await;
247    let clusters: Vec<&Cluster> = catalog.clusters().collect();
248
249    for cluster in clusters {
250        for replica in cluster.replicas() {
251            execute_promsql_query(
252                client,
253                query,
254                metrics_registry,
255                metrics_by_name,
256                Some((cluster, replica)),
257            )
258            .await;
259        }
260    }
261}
262
263pub async fn handle_promsql(
264    mut client: AuthedClient,
265    queries: &[PrometheusSqlQuery<'_>],
266) -> MetricsRegistry {
267    let metrics_registry = MetricsRegistry::new();
268    let mut metrics_by_name = BTreeMap::new();
269
270    for query in queries {
271        handle_promsql_query(&mut client, query, &metrics_registry, &mut metrics_by_name).await;
272    }
273
274    metrics_registry
275}
276
277pub async fn handle_sql(
278    mut client: AuthedClient,
279    Json(request): Json<SqlRequest>,
280) -> impl IntoResponse {
281    let mut res = SqlResponse {
282        results: Vec::new(),
283    };
284    // Don't need to worry about timeouts or resetting cancel here because there is always exactly 1
285    // request.
286    match execute_request(&mut client, request, &mut res).await {
287        Ok(()) => Ok(Json(res)),
288        Err(e) => Err((StatusCode::BAD_REQUEST, e.to_string())),
289    }
290}
291
292#[derive(Debug)]
293pub enum ExistingUser {
294    /// An AuthedUser provided by the
295    /// `x_materialize_user_header_auth` middleware
296    XMaterializeUserHeader(AuthedUser),
297    /// An AuthedUser provided by an authenticated session
298    /// established via [`crate::http::handle_login`].
299    Session(AuthedUser),
300}
301
302pub(crate) async fn handle_sql_ws(
303    State(state): State<WsState>,
304    existing_user: Option<Extension<AuthedUser>>,
305    ws: WebSocketUpgrade,
306    ConnectInfo(addr): ConnectInfo<SocketAddr>,
307    tower_session: Option<Extension<TowerSession>>,
308) -> Result<impl IntoResponse, AuthError> {
309    let session = tower_session.map(|Extension(session)| session);
310    // The `x_materialize_user_header_auth` middleware may have already provided the user for us
311    let user = match existing_user {
312        Some(Extension(user)) => Some(ExistingUser::XMaterializeUserHeader(user)),
313        None => {
314            let session = maybe_get_authenticated_session(session.as_ref()).await;
315            if let Some((session, session_data)) = session {
316                let user = ensure_session_unexpired(session, session_data).await?;
317                Some(ExistingUser::Session(user))
318            } else {
319                None
320            }
321        }
322    };
323
324    let addr = Box::new(addr.ip());
325    Ok(ws
326        .max_message_size(MAX_REQUEST_SIZE)
327        .on_upgrade(|ws| async move { run_ws(state, user, *addr, ws).await }))
328}
329
330#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
331#[serde(untagged)]
332pub enum WebSocketAuth {
333    Basic {
334        user: String,
335        password: Password,
336        #[serde(default)]
337        options: BTreeMap<String, String>,
338    },
339    Bearer {
340        token: String,
341        #[serde(default)]
342        options: BTreeMap<String, String>,
343    },
344    OptionsOnly {
345        #[serde(default)]
346        options: BTreeMap<String, String>,
347    },
348}
349
350async fn run_ws(state: WsState, user: Option<ExistingUser>, peer_addr: IpAddr, mut ws: WebSocket) {
351    let mut client = match init_ws(state, user, peer_addr, &mut ws).await {
352        Ok(client) => client,
353        Err(e) => {
354            // We omit most detail from the error message we send to the client, to
355            // avoid giving attackers unnecessary information during auth. AdapterErrors
356            // are safe to return because they're generated after authentication.
357            debug!("WS request failed init: {}", e);
358            let reason: Utf8Bytes = match e.downcast_ref::<AdapterError>() {
359                Some(error) => error.to_string().into(),
360                None => "unauthorized".to_string().into(),
361            };
362            let _ = ws
363                .send(Message::Close(Some(CloseFrame {
364                    code: CloseCode::Protocol.into(),
365                    reason,
366                })))
367                .await;
368            return;
369        }
370    };
371
372    // Successful auth, send startup messages.
373    let mut msgs = Vec::new();
374    let session = client.client.session();
375    for var in session.vars().notify_set() {
376        msgs.push(WebSocketResponse::ParameterStatus(ParameterStatus {
377            name: var.name().to_string(),
378            value: var.value(),
379        }));
380    }
381    msgs.push(WebSocketResponse::BackendKeyData(BackendKeyData {
382        conn_id: session.conn_id().unhandled(),
383        secret_key: session.secret_key(),
384    }));
385    msgs.push(WebSocketResponse::ReadyForQuery(
386        session.transaction_code().into(),
387    ));
388    for msg in msgs {
389        let _ = ws
390            .send(Message::Text(
391                serde_json::to_string(&msg).expect("must serialize").into(),
392            ))
393            .await;
394    }
395
396    // Send any notices that might have been generated on startup.
397    let notices = session.drain_notices();
398    if let Err(err) = forward_notices(&mut ws, notices).await {
399        debug!("failed to forward notices to WebSocket, {err:?}");
400        return;
401    }
402
403    loop {
404        // Handle timeouts first so we don't execute any statements when there's a pending timeout.
405        let msg = select! {
406            biased;
407
408            // `recv_timeout()` is cancel-safe as per it's docs.
409            Some(timeout) = client.client.recv_timeout() => {
410                client.client.terminate().await;
411                // We must wait for the client to send a request before we can send the error
412                // response. Although this isn't the PG wire protocol, we choose to mirror it by
413                // only sending errors as responses to requests.
414                let _ = ws.recv().await;
415                let err = Error::from(AdapterError::from(timeout));
416                let _ = send_ws_response(&mut ws, WebSocketResponse::Error(err.into())).await;
417                return;
418            },
419            message = ws.recv() => message,
420        };
421
422        client.client.remove_idle_in_transaction_session_timeout();
423
424        let msg = match msg {
425            Some(Ok(msg)) => msg,
426            _ => {
427                // client disconnected
428                return;
429            }
430        };
431
432        let req: Result<SqlRequest, Error> = match msg {
433            Message::Text(data) => serde_json::from_str(&data).err_into(),
434            Message::Binary(data) => serde_json::from_slice(&data).err_into(),
435            // Handled automatically by the server.
436            Message::Ping(_) => {
437                continue;
438            }
439            Message::Pong(_) => {
440                continue;
441            }
442            Message::Close(_) => {
443                return;
444            }
445        };
446
447        // Figure out if we need to send an error, any notices, but always the ready message.
448        let err = match run_ws_request(req, &mut client, &mut ws).await {
449            Ok(()) => None,
450            Err(err) => Some(WebSocketResponse::Error(err.into())),
451        };
452
453        // After running our request, there are several messages we need to send in a
454        // specific order.
455        //
456        // Note: we nest these into a closure so we can centralize our error handling
457        // for when sending over the WebSocket fails. We could also use a try {} block
458        // here, but those aren't stabilized yet.
459        let ws_response = || async {
460            // First respond with any error that might have occurred.
461            if let Some(e_resp) = err {
462                send_ws_response(&mut ws, e_resp).await?;
463            }
464
465            // Then forward along any notices we generated.
466            let notices = client.client.session().drain_notices();
467            forward_notices(&mut ws, notices).await?;
468
469            // Finally, respond that we're ready for the next query.
470            let ready =
471                WebSocketResponse::ReadyForQuery(client.client.session().transaction_code().into());
472            send_ws_response(&mut ws, ready).await?;
473
474            Ok::<_, Error>(())
475        };
476
477        if let Err(err) = ws_response().await {
478            debug!("failed to send response over WebSocket, {err:?}");
479            return;
480        }
481    }
482}
483
484async fn run_ws_request(
485    req: Result<SqlRequest, Error>,
486    client: &mut AuthedClient,
487    ws: &mut WebSocket,
488) -> Result<(), Error> {
489    let req = req?;
490    execute_request(client, req, ws).await
491}
492
493/// Sends a single [`WebSocketResponse`] over the provided [`WebSocket`] and flushes it.
494async fn send_ws_response(ws: &mut WebSocket, resp: WebSocketResponse) -> Result<(), Error> {
495    feed_ws_response(ws, resp).await?;
496    ws.flush().await?;
497
498    Ok(())
499}
500
501/// Queues a single [`WebSocketResponse`] on the provided [`WebSocket`] without flushing it, so
502/// the caller must flush before it waits on anything but the socket.
503///
504/// The queue stays bounded. Once it exceeds tungstenite's `write_buffer_size` it is written to
505/// the socket, and a socket that is not writable makes the next call wait.
506async fn feed_ws_response(ws: &mut WebSocket, resp: WebSocketResponse) -> Result<(), Error> {
507    let msg = serde_json::to_string(&resp).unwrap();
508    ws.feed(Message::Text(msg.into())).await?;
509
510    Ok(())
511}
512
513/// Forwards a collection of Notices to the provided [`WebSocket`].
514async fn forward_notices(
515    ws: &mut WebSocket,
516    notices: impl IntoIterator<Item = AdapterNotice>,
517) -> Result<(), Error> {
518    let ws_notices = notices
519        .into_iter()
520        .map(|notice| WebSocketResponse::Notice(Notice::from(notice)));
521
522    for notice in ws_notices {
523        send_ws_response(ws, notice).await?;
524    }
525
526    Ok(())
527}
528
529/// A request to execute SQL over HTTP or WebSocket. Execution stops at the first statement
530/// that fails, including a statement whose implicit transaction fails to commit.
531#[derive(Serialize, Deserialize, Debug)]
532#[serde(untagged)]
533pub enum SqlRequest {
534    /// One SQL string without parameters, as in PostgreSQL's simple query protocol. Its
535    /// statements, separated by semicolons, share one implicit transaction, unless `BEGIN` and
536    /// `COMMIT` among them group statements into an explicit transaction.
537    Simple { query: Sql },
538    /// A list of statements, each with its own parameters. Each statement runs in its own
539    /// implicit transaction, as if it were followed by a `Sync` in PostgreSQL's extended query
540    /// protocol, unless `BEGIN` and `COMMIT` entries group statements into an explicit transaction.
541    Extended { queries: Vec<ExtendedRequest> },
542}
543
544/// One statement of an [`SqlRequest::Extended`].
545#[derive(Serialize, Deserialize, Debug)]
546pub struct ExtendedRequest {
547    /// A SQL string containing exactly one statement.
548    query: String,
549    /// The values of the statement's parameters, as text. `None` is SQL `NULL`.
550    #[serde(default)]
551    params: Vec<Option<String>>,
552}
553
554/// The response to a `SqlRequest`.
555#[derive(Debug, Serialize, Deserialize)]
556pub struct SqlResponse {
557    /// The results for each query in the request.
558    pub(in crate::http) results: Vec<SqlResult>,
559}
560
561impl SqlResponse {
562    /// Creates a new empty SqlResponse for collecting results.
563    pub(in crate::http) fn new() -> Self {
564        Self {
565            results: Vec::new(),
566        }
567    }
568}
569
570pub(in crate::http) enum StatementResult {
571    /// A complete result: an error, or the success of a statement without rows.
572    SqlResult(SqlResult),
573    /// A result whose rows are streamed, such as that of a `SELECT` or of a
574    /// write with `RETURNING`. The stream is consumed lazily by the sender so a
575    /// large result is not buffered whole. Contrast `SqlResult::Rows`, which
576    /// holds already-collected rows and exists only for the buffered JSON
577    /// transport.
578    Rows {
579        desc: RelationDesc,
580        rows_stream: RecordFirstRowStream,
581        max_result_size: usize,
582        /// Whether the statement ends its statement group. If it does, the group's implicit
583        /// transaction, if any, commits after the last row and before the statement's completion.
584        ends_group: bool,
585    },
586    Subscribe {
587        desc: RelationDesc,
588        tag: String,
589        rx: RecordFirstRowStream,
590        ctx_extra: ExecuteContextGuard,
591    },
592}
593
594impl From<SqlResult> for StatementResult {
595    fn from(inner: SqlResult) -> Self {
596        Self::SqlResult(inner)
597    }
598}
599
600/// The result of a single query in a [`SqlResponse`].
601#[derive(Debug, Serialize, Deserialize)]
602#[serde(untagged)]
603pub enum SqlResult {
604    /// The query returned rows.
605    Rows {
606        /// The command complete tag.
607        tag: String,
608        /// The result rows, each already serialized to a compact JSON array.
609        ///
610        /// We accumulate pre-serialized rows rather than a `serde_json::Value`
611        /// tree so the buffered footprint stays close to the wire size. A
612        /// `Value` tree is ~10-15x larger (each cell a heap `Value`, in a
613        /// per-row `Vec`, in the outer `Vec`), which is what let a large
614        /// `SELECT` over the JSON endpoint OOM the process. `RawValue`
615        /// re-serializes verbatim, so the wire format is unchanged.
616        rows: Vec<Box<serde_json::value::RawValue>>,
617        /// Information about each column.
618        desc: Description,
619        // Any notices generated during execution of the query.
620        notices: Vec<Notice>,
621    },
622    /// The query executed successfully but did not return rows.
623    Ok {
624        /// The command complete tag.
625        ok: String,
626        /// Any notices generated during execution of the query.
627        notices: Vec<Notice>,
628        /// Any parameters that may have changed.
629        ///
630        /// Note: skip serializing this field in a response if the list of parameters is empty.
631        #[serde(skip_serializing_if = "Vec::is_empty")]
632        parameters: Vec<ParameterStatus>,
633        /// The opted-in execution time notice, kept apart from `notices` because the WebSocket API
634        /// sends it before `CommandComplete` and the other notices after.
635        #[serde(skip)]
636        execution_time: Option<Notice>,
637    },
638    /// The query returned an error.
639    Err {
640        error: SqlError,
641        // Any notices generated during execution of the query.
642        notices: Vec<Notice>,
643    },
644}
645
646impl SqlResult {
647    /// Convert adapter Row results into the buffered web row result format.
648    /// Return an error result if, for example, the row format does not match the
649    /// expected descriptor, the result exceeds `max_query_result_size`, or the
650    /// commit of an implicit transaction that the statement ends fails. `Err`
651    /// means that the connection failed.
652    ///
653    /// This buffers the whole result, so it is used only by the JSON transport,
654    /// whose response is a single document. The WebSocket transport streams rows
655    /// through `StatementResult::Rows` and never calls this. The size guard
656    /// counts `Row::byte_len`, matching the WebSocket transport and pgwire, and
657    /// rows are stored as pre-serialized compact `RawValue`s to avoid the
658    /// amplified `Value`-tree buffering that could OOM.
659    async fn rows<S>(
660        sender: &mut S,
661        client: &mut SessionClient,
662        mut rows_stream: RecordFirstRowStream,
663        max_query_result_size: usize,
664        desc: &RelationDesc,
665        ends_group: bool,
666    ) -> Result<SqlResult, Error>
667    where
668        S: ResultSender,
669    {
670        let mut rows: Vec<Box<serde_json::value::RawValue>> = vec![];
671        let mut datum_vec = mz_repr::DatumVec::new();
672        let types = &desc.typ().column_types;
673
674        let mut query_result_size: usize = 0;
675
676        loop {
677            let peek_response = tokio::select! {
678                notice = client.session().recv_notice(), if S::SUPPORTS_STREAMING_NOTICES => {
679                    sender.emit_streaming_notices(vec![notice]).await?;
680                    continue;
681                }
682                e = sender.connection_error() => return Err(e),
683                r = rows_stream.recv() => {
684                    match r {
685                        Some(r) => r,
686                        None => break,
687                    }
688                },
689            };
690
691            let mut sql_rows = match peek_response {
692                PeekResponseUnary::Rows(rows) => rows,
693                PeekResponseUnary::Error(e) => {
694                    return Ok(SqlResult::err(client, e));
695                }
696                PeekResponseUnary::DependencyDropped(dep) => {
697                    return Ok(SqlResult::err(client, dep.to_concurrent_dependency_drop()));
698                }
699                PeekResponseUnary::Canceled => {
700                    return Ok(SqlResult::err(client, AdapterError::Canceled));
701                }
702            };
703
704            if let Err(err) = verify_datum_desc(desc, &mut sql_rows) {
705                return Ok(SqlResult::Err {
706                    error: err.into(),
707                    notices: make_notices(client),
708                });
709            }
710
711            while let Some(row) = sql_rows.next() {
712                // Enforce `max_result_size` on `Row::byte_len`, the same quantity
713                // pgwire and the WebSocket transport use, so the cap means one
714                // thing across every transport.
715                query_result_size = query_result_size.saturating_add(row.byte_len());
716                if query_result_size > max_query_result_size {
717                    use bytesize::ByteSize;
718                    return Ok(SqlResult::err(
719                        client,
720                        AdapterError::ResultSize(format!(
721                            "result exceeds max size of {}",
722                            ByteSize::b(u64::cast_from(max_query_result_size))
723                        )),
724                    ));
725                }
726                let datums = datum_vec.borrow_with(row);
727                let json_row: Vec<serde_json::Value> = datums
728                    .iter()
729                    .enumerate()
730                    .map(|(i, d)| {
731                        TypedDatum::new(*d, &types[i])
732                            .json(&JsonNumberPolicy::ConvertNumberToString)
733                    })
734                    .collect();
735                // Keep only the compact serialized JSON text. The transient
736                // `Value` tree above is dropped per row, so at most one row's tree
737                // is resident, avoiding the amplified buffering that could OOM.
738                let raw = serde_json::value::to_raw_value(&json_row)
739                    .expect("row of JSON values always serializes");
740                rows.push(raw);
741            }
742        }
743
744        let execution_time = rows_stream
745            .take_execution_time()
746            .map(|time| client.session().maybe_mark_staged(time));
747        // TODO(SQL-815): `SqlResult::Rows` has no `parameters` field, so the parameters the
748        // commit reverted (a `SET LOCAL` earlier in the group) are dropped.
749        if let Err(err) = client.settle_statement(ends_group).await {
750            return Ok(SqlResult::err(client, err));
751        }
752        let mut notices = make_notices(client);
753        notices.extend(
754            execution_time
755                .and_then(|time| client.session().execution_time_notice(time))
756                .map(Notice::from),
757        );
758        let tag = format!("SELECT {}", rows.len());
759        Ok(SqlResult::Rows {
760            tag,
761            rows,
762            desc: Description::from(desc),
763            notices,
764        })
765    }
766
767    fn err(client: &mut SessionClient, error: impl Into<SqlError>) -> SqlResult {
768        SqlResult::Err {
769            error: error.into(),
770            notices: make_notices(client),
771        }
772    }
773
774    /// The result of a statement whose response carries no rows. If `ends_group` and the
775    /// statement runs in an implicit transaction, that transaction commits first, a failed commit
776    /// becomes the result, and the parameters the commit reverted follow `params`.
777    async fn ok(
778        client: &mut SessionClient,
779        tag: String,
780        mut params: Vec<ParameterStatus>,
781        ends_group: bool,
782        execution_time: ExecutionTime,
783    ) -> SqlResult {
784        match client.settle_statement(ends_group).await {
785            Ok(settled) => {
786                params.extend(notify_params(client, settled.reverted));
787                SqlResult::Ok {
788                    ok: tag,
789                    parameters: params,
790                    notices: make_notices(client),
791                    execution_time: client
792                        .session()
793                        .execution_time_notice(execution_time)
794                        .map(Notice::from),
795                }
796            }
797            Err(err) => SqlResult::err(client, err),
798        }
799    }
800}
801
802#[derive(Debug, Deserialize, Serialize)]
803pub struct SqlError {
804    pub message: String,
805    pub code: String,
806    #[serde(skip_serializing_if = "Option::is_none")]
807    pub detail: Option<String>,
808    #[serde(skip_serializing_if = "Option::is_none")]
809    pub hint: Option<String>,
810    #[serde(skip_serializing_if = "Option::is_none")]
811    pub position: Option<usize>,
812}
813
814impl From<Error> for SqlError {
815    fn from(err: Error) -> Self {
816        SqlError {
817            message: err.to_string(),
818            code: err.code().code().to_string(),
819            detail: err.detail(),
820            hint: err.hint(),
821            position: err.position(),
822        }
823    }
824}
825
826impl From<AdapterError> for SqlError {
827    fn from(value: AdapterError) -> Self {
828        Error::from(value).into()
829    }
830}
831
832#[derive(Debug, Deserialize, Serialize)]
833#[serde(tag = "type", content = "payload")]
834pub enum WebSocketResponse {
835    ReadyForQuery(String),
836    Notice(Notice),
837    Rows(Description),
838    Row(Vec<serde_json::Value>),
839    CommandStarting(CommandStarting),
840    CommandComplete(String),
841    Error(SqlError),
842    ParameterStatus(ParameterStatus),
843    BackendKeyData(BackendKeyData),
844}
845
846#[derive(Debug, Serialize, Deserialize)]
847pub struct Notice {
848    message: String,
849    code: String,
850    severity: String,
851    #[serde(skip_serializing_if = "Option::is_none")]
852    pub detail: Option<String>,
853    #[serde(skip_serializing_if = "Option::is_none")]
854    pub hint: Option<String>,
855}
856
857impl Notice {
858    pub fn message(&self) -> &str {
859        &self.message
860    }
861}
862
863#[derive(Debug, Serialize, Deserialize)]
864pub struct Description {
865    pub columns: Vec<Column>,
866}
867
868impl From<&RelationDesc> for Description {
869    fn from(desc: &RelationDesc) -> Self {
870        let columns = desc
871            .iter()
872            .map(|(name, typ)| {
873                let pg_type = mz_pgrepr::Type::from(&typ.scalar_type);
874                Column {
875                    name: name.to_string(),
876                    type_oid: pg_type.oid(),
877                    type_len: pg_type.typlen(),
878                    type_mod: pg_type.typmod(),
879                }
880            })
881            .collect();
882        Description { columns }
883    }
884}
885
886#[derive(Debug, Serialize, Deserialize)]
887pub struct Column {
888    pub name: String,
889    pub type_oid: u32,
890    pub type_len: i16,
891    pub type_mod: i32,
892}
893
894#[derive(Debug, Serialize, Deserialize)]
895pub struct ParameterStatus {
896    name: String,
897    value: String,
898}
899
900#[derive(Debug, Serialize, Deserialize)]
901pub struct BackendKeyData {
902    conn_id: u32,
903    secret_key: u32,
904}
905
906#[derive(Debug, Serialize, Deserialize)]
907pub struct CommandStarting {
908    has_rows: bool,
909    is_streaming: bool,
910}
911
912/// Trait describing how to transmit a response to a client. HTTP clients
913/// accumulate into a Vec and send all at once. WebSocket clients send each
914/// message as they occur.
915#[async_trait]
916pub(in crate::http) trait ResultSender: Send {
917    const SUPPORTS_STREAMING_NOTICES: bool = false;
918
919    /// Adds a result to the client. The first component of the return value is
920    /// Err if sending to the client
921    /// produced an error and the server should disconnect. It is Ok(Err) if the statement
922    /// produced an error and should error the transaction, but remain connected. It is Ok(Ok(()))
923    /// if the statement succeeded.
924    /// The second component of the return value is `Some` if execution still
925    /// needs to be retired for statement logging purposes.
926    async fn add_result(
927        &mut self,
928        client: &mut SessionClient,
929        res: StatementResult,
930    ) -> (
931        Result<Result<(), ()>, Error>,
932        Option<(StatementEndedExecutionReason, ExecuteContextGuard)>,
933    );
934
935    /// Returns a future that resolves only when the client connection has gone away.
936    fn connection_error(&mut self) -> BoxFuture<'_, Error>;
937    /// Reports whether the client supports streaming SUBSCRIBE results.
938    fn allow_subscribe(&self) -> bool;
939
940    /// Emits a streaming notice if the sender supports it.
941    ///
942    /// Does nothing if `SUPPORTS_STREAMING_NOTICES` is false.
943    async fn emit_streaming_notices(&mut self, _: Vec<AdapterNotice>) -> Result<(), Error> {
944        unreachable!("streaming notices marked as unsupported")
945    }
946}
947
948#[async_trait]
949impl ResultSender for SqlResponse {
950    // The first component of the return value is
951    // Err if sending to the client
952    // produced an error and the server should disconnect. It is Ok(Err) if the statement
953    // produced an error and should error the transaction, but remain connected. It is Ok(Ok(()))
954    // if the statement succeeded.
955    // The second component of the return value is `Some` if execution still
956    // needs to be retired for statement logging purposes.
957    async fn add_result(
958        &mut self,
959        client: &mut SessionClient,
960        res: StatementResult,
961    ) -> (
962        Result<Result<(), ()>, Error>,
963        Option<(StatementEndedExecutionReason, ExecuteContextGuard)>,
964    ) {
965        let (res, stmt_logging) = match res {
966            StatementResult::SqlResult(mut res) => {
967                if let SqlResult::Ok {
968                    notices,
969                    execution_time,
970                    ..
971                } = &mut res
972                {
973                    notices.extend(execution_time.take());
974                }
975                let is_err = matches!(res, SqlResult::Err { .. });
976                self.results.push(res);
977                let res = if is_err { Err(()) } else { Ok(()) };
978                (res, None)
979            }
980            StatementResult::Rows {
981                desc,
982                rows_stream,
983                max_result_size,
984                ends_group,
985            } => {
986                // The JSON transport is a single buffered document, so the rows
987                // must be collected before the response is serialized.
988                // `SqlResult::rows` bounds that buffer against `max_result_size`.
989                let res = match SqlResult::rows(
990                    self,
991                    client,
992                    rows_stream,
993                    max_result_size,
994                    &desc,
995                    ends_group,
996                )
997                .await
998                {
999                    Ok(res) => res,
1000                    Err(e) => return (Err(e), None),
1001                };
1002                let is_err = matches!(res, SqlResult::Err { .. });
1003                self.results.push(res);
1004                let res = if is_err { Err(()) } else { Ok(()) };
1005                (res, None)
1006            }
1007            StatementResult::Subscribe { ctx_extra, .. } => {
1008                let message = "SUBSCRIBE only supported over websocket";
1009                self.results.push(SqlResult::Err {
1010                    error: Error::SubscribeOnlyOverWs.into(),
1011                    notices: Vec::new(),
1012                });
1013                (
1014                    Err(()),
1015                    Some((
1016                        StatementEndedExecutionReason::Errored {
1017                            error: message.into(),
1018                        },
1019                        ctx_extra,
1020                    )),
1021                )
1022            }
1023        };
1024        (Ok(res), stmt_logging)
1025    }
1026
1027    fn connection_error(&mut self) -> BoxFuture<'_, Error> {
1028        Box::pin(futures::future::pending())
1029    }
1030
1031    fn allow_subscribe(&self) -> bool {
1032        false
1033    }
1034}
1035
1036#[async_trait]
1037impl ResultSender for WebSocket {
1038    const SUPPORTS_STREAMING_NOTICES: bool = true;
1039
1040    // The first component of the return value is Err if sending to the client produced an error and
1041    // the server should disconnect. It is Ok(Err) if the statement produced an error and should
1042    // error the transaction, but remain connected. It is Ok(Ok(())) if the statement succeeded. The
1043    // second component of the return value is `Some` if execution still needs to be retired for
1044    // statement logging purposes.
1045    async fn add_result(
1046        &mut self,
1047        client: &mut SessionClient,
1048        res: StatementResult,
1049    ) -> (
1050        Result<Result<(), ()>, Error>,
1051        Option<(StatementEndedExecutionReason, ExecuteContextGuard)>,
1052    ) {
1053        let (has_rows, is_streaming) = match res {
1054            StatementResult::SqlResult(SqlResult::Err { .. }) => (false, false),
1055            StatementResult::SqlResult(SqlResult::Ok { .. }) => (false, false),
1056            StatementResult::SqlResult(SqlResult::Rows { .. }) => (true, false),
1057            StatementResult::Rows { .. } => (true, false),
1058            StatementResult::Subscribe { .. } => (true, true),
1059        };
1060        if let Err(e) = send_ws_response(
1061            self,
1062            WebSocketResponse::CommandStarting(CommandStarting {
1063                has_rows,
1064                is_streaming,
1065            }),
1066        )
1067        .await
1068        {
1069            return (Err(e), None);
1070        }
1071
1072        let (is_err, msgs, stmt_logging) = match res {
1073            StatementResult::SqlResult(SqlResult::Rows { .. }) => {
1074                // `SqlResult::Rows` holds already-collected rows for the buffered
1075                // JSON transport only. The WebSocket transport streams peek
1076                // results through `StatementResult::Rows` and never materializes
1077                // a `SqlResult::Rows`.
1078                unreachable!("WebSocket streams peek rows via StatementResult::Rows")
1079            }
1080            StatementResult::Rows {
1081                ref desc,
1082                mut rows_stream,
1083                max_result_size,
1084                ends_group,
1085            } => match stream_ws_peek_rows(
1086                self,
1087                client,
1088                desc,
1089                &mut rows_stream,
1090                max_result_size,
1091                ends_group,
1092            )
1093            .await
1094            {
1095                Ok(result) => result,
1096                // A write failure means the remote broke the connection, which we
1097                // treat as a cancellation to match pgwire.
1098                Err(e) => return (Err(e), None),
1099            },
1100            StatementResult::SqlResult(SqlResult::Ok {
1101                ok,
1102                parameters,
1103                notices,
1104                execution_time,
1105            }) => {
1106                // The execution time precedes `CommandComplete`, so clients attribute it to this
1107                // statement rather than to the next one.
1108                let mut msgs: Vec<_> = execution_time
1109                    .into_iter()
1110                    .map(WebSocketResponse::Notice)
1111                    .collect();
1112                msgs.push(WebSocketResponse::CommandComplete(ok));
1113                msgs.extend(notices.into_iter().map(WebSocketResponse::Notice));
1114                msgs.extend(
1115                    parameters
1116                        .into_iter()
1117                        .map(WebSocketResponse::ParameterStatus),
1118                );
1119                (false, msgs, None)
1120            }
1121            StatementResult::SqlResult(SqlResult::Err { error, notices }) => {
1122                let mut msgs = vec![WebSocketResponse::Error(error)];
1123                msgs.extend(notices.into_iter().map(WebSocketResponse::Notice));
1124                (true, msgs, None)
1125            }
1126            StatementResult::Subscribe {
1127                ref desc,
1128                tag,
1129                mut rx,
1130                ctx_extra,
1131            } => {
1132                if let Err(e) = send_ws_response(self, WebSocketResponse::Rows(desc.into())).await {
1133                    // We consider the remote breaking the connection to be a cancellation,
1134                    // matching the behavior for pgwire
1135                    return (
1136                        Err(e),
1137                        Some((StatementEndedExecutionReason::Canceled, ctx_extra)),
1138                    );
1139                }
1140
1141                let mut datum_vec = mz_repr::DatumVec::new();
1142                let mut result_size: usize = 0;
1143                let mut rows_returned = 0;
1144                loop {
1145                    let res = match await_rows(self, client, rx.recv()).await {
1146                        Ok(res) => res,
1147                        Err(e) => {
1148                            // We consider the remote breaking the connection to be a cancellation,
1149                            // matching the behavior for pgwire
1150                            return (
1151                                Err(e),
1152                                Some((StatementEndedExecutionReason::Canceled, ctx_extra)),
1153                            );
1154                        }
1155                    };
1156                    match res {
1157                        Some(PeekResponseUnary::Rows(mut rows)) => {
1158                            if let Err(err) = verify_datum_desc(desc, &mut rows) {
1159                                let error = err.to_string();
1160                                break (
1161                                    true,
1162                                    vec![WebSocketResponse::Error(err.into())],
1163                                    Some((
1164                                        StatementEndedExecutionReason::Errored { error },
1165                                        ctx_extra,
1166                                    )),
1167                                );
1168                            }
1169
1170                            rows_returned += rows.count();
1171                            while let Some(row) = rows.next() {
1172                                result_size = result_size.saturating_add(row.byte_len());
1173                                let datums = datum_vec.borrow_with(row);
1174                                let types = &desc.typ().column_types;
1175                                if let Err(e) = feed_ws_response(
1176                                    self,
1177                                    WebSocketResponse::Row(
1178                                        datums
1179                                            .iter()
1180                                            .enumerate()
1181                                            .map(|(i, d)| {
1182                                                TypedDatum::new(*d, &types[i])
1183                                                    .json(&JsonNumberPolicy::ConvertNumberToString)
1184                                            })
1185                                            .collect(),
1186                                    ),
1187                                )
1188                                .await
1189                                {
1190                                    // We consider the remote breaking the connection to be a cancellation,
1191                                    // matching the behavior for pgwire
1192                                    return (
1193                                        Err(e),
1194                                        Some((StatementEndedExecutionReason::Canceled, ctx_extra)),
1195                                    );
1196                                }
1197                            }
1198                            if let Err(e) = self.flush().await {
1199                                return (
1200                                    Err(e.into()),
1201                                    Some((StatementEndedExecutionReason::Canceled, ctx_extra)),
1202                                );
1203                            }
1204                        }
1205                        Some(PeekResponseUnary::Error(err)) => {
1206                            let error = err.to_string();
1207                            break (
1208                                true,
1209                                vec![WebSocketResponse::Error(err.into())],
1210                                Some((StatementEndedExecutionReason::Errored { error }, ctx_extra)),
1211                            );
1212                        }
1213                        Some(PeekResponseUnary::DependencyDropped(dep)) => {
1214                            let err = dep.to_concurrent_dependency_drop();
1215                            let error = err.to_string();
1216                            break (
1217                                true,
1218                                vec![WebSocketResponse::Error(err.into())],
1219                                Some((StatementEndedExecutionReason::Errored { error }, ctx_extra)),
1220                            );
1221                        }
1222                        Some(PeekResponseUnary::Canceled) => {
1223                            break (
1224                                true,
1225                                vec![WebSocketResponse::Error(AdapterError::Canceled.into())],
1226                                Some((StatementEndedExecutionReason::Canceled, ctx_extra)),
1227                            );
1228                        }
1229                        None => {
1230                            break (
1231                                false,
1232                                vec![WebSocketResponse::CommandComplete(tag)],
1233                                Some((
1234                                    StatementEndedExecutionReason::Success {
1235                                        result_size: Some(u64::cast_from(result_size)),
1236                                        rows_returned: Some(u64::cast_from(rows_returned)),
1237                                        execution_strategy: Some(
1238                                            StatementExecutionStrategy::Standard,
1239                                        ),
1240                                    },
1241                                    ctx_extra,
1242                                )),
1243                            );
1244                        }
1245                    }
1246                }
1247            }
1248        };
1249        for msg in msgs {
1250            if let Err(e) = send_ws_response(self, msg).await {
1251                return (
1252                    Err(e),
1253                    stmt_logging.map(|(_old_reason, ctx_extra)| {
1254                        (StatementEndedExecutionReason::Canceled, ctx_extra)
1255                    }),
1256                );
1257            }
1258        }
1259        (Ok(if is_err { Err(()) } else { Ok(()) }), stmt_logging)
1260    }
1261
1262    // Send a websocket Ping every second to verify the client is still
1263    // connected.
1264    fn connection_error(&mut self) -> BoxFuture<'_, Error> {
1265        Box::pin(async {
1266            let mut tick = time::interval(Duration::from_secs(1));
1267            tick.tick().await;
1268            loop {
1269                tick.tick().await;
1270                if let Err(err) = self.send(Message::Ping(Vec::new().into())).await {
1271                    return err.into();
1272                }
1273            }
1274        })
1275    }
1276
1277    fn allow_subscribe(&self) -> bool {
1278        true
1279    }
1280
1281    async fn emit_streaming_notices(&mut self, notices: Vec<AdapterNotice>) -> Result<(), Error> {
1282        forward_notices(self, notices).await
1283    }
1284}
1285
1286async fn await_rows<S, F, R>(sender: &mut S, client: &mut SessionClient, f: F) -> Result<R, Error>
1287where
1288    S: ResultSender,
1289    F: Future<Output = R> + Send,
1290{
1291    let mut f = pin!(f);
1292    loop {
1293        tokio::select! {
1294            notice = client.session().recv_notice(), if S::SUPPORTS_STREAMING_NOTICES => {
1295                sender.emit_streaming_notices(vec![notice]).await?;
1296            }
1297            e = sender.connection_error() => return Err(e),
1298            r = &mut f => return Ok(r),
1299        }
1300    }
1301}
1302
1303/// Streams a result with rows, such as that of a `SELECT`, to a WebSocket
1304/// client one batch at a time, flushing between batches so a slow client
1305/// applies real backpressure and only one batch is resident. This gives a large
1306/// `SELECT` over WebSocket the same bounded memory profile as pgwire `SELECT`,
1307/// and mirrors the `Subscribe` arm of `WebSocket::add_result`.
1308///
1309/// On success returns the `(is_err, msgs, stmt_logging)` triple that
1310/// `add_result` folds into its response. An `Err` means a write to the socket
1311/// failed, so the server should disconnect. `add_result` turns that into a
1312/// cancellation to match pgwire.
1313///
1314/// The `Rows` descriptor is sent lazily, right before the first batch of rows
1315/// or an empty successful result, but never before an error. So a query that
1316/// fails before producing any rows emits only an `Error`.
1317async fn stream_ws_peek_rows(
1318    ws: &mut WebSocket,
1319    client: &mut SessionClient,
1320    desc: &RelationDesc,
1321    rows_stream: &mut RecordFirstRowStream,
1322    max_result_size: usize,
1323    ends_group: bool,
1324) -> Result<
1325    (
1326        bool,
1327        Vec<WebSocketResponse>,
1328        Option<(StatementEndedExecutionReason, ExecuteContextGuard)>,
1329    ),
1330    Error,
1331> {
1332    let mut datum_vec = mz_repr::DatumVec::new();
1333    let mut result_size: usize = 0;
1334    let mut rows_returned: usize = 0;
1335    let mut sent_rows_desc = false;
1336    loop {
1337        // Bind before matching so the `Option<PeekResponseUnary>` (which has a
1338        // significant `Drop`) is not a temporary living for the whole match.
1339        let res = await_rows(ws, client, rows_stream.recv()).await?;
1340        match res {
1341            Some(PeekResponseUnary::Rows(mut rows)) => {
1342                if let Err(err) = verify_datum_desc(desc, &mut rows) {
1343                    return Ok(ws_peek_result(
1344                        client,
1345                        true,
1346                        vec![WebSocketResponse::Error(err.into())],
1347                    ));
1348                }
1349                // The header waits until a batch has passed `verify_datum_desc`,
1350                // so a query that fails before producing any rows emits only an
1351                // `Error`. Sending it before the loop, as the `Subscribe` arm
1352                // does, would put a `Rows` header in front of that `Error`.
1353                if !sent_rows_desc {
1354                    send_ws_response(ws, WebSocketResponse::Rows(desc.into())).await?;
1355                    sent_rows_desc = true;
1356                }
1357                let types = &desc.typ().column_types;
1358                while let Some(row) = rows.next() {
1359                    result_size = result_size.saturating_add(row.byte_len());
1360                    if result_size > max_result_size {
1361                        use bytesize::ByteSize;
1362                        return Ok(ws_peek_result(
1363                            client,
1364                            true,
1365                            vec![WebSocketResponse::Error(
1366                                AdapterError::ResultSize(format!(
1367                                    "result exceeds max size of {}",
1368                                    ByteSize::b(u64::cast_from(max_result_size))
1369                                ))
1370                                .into(),
1371                            )],
1372                        ));
1373                    }
1374                    let datums = datum_vec.borrow_with(row);
1375                    feed_ws_response(
1376                        ws,
1377                        WebSocketResponse::Row(
1378                            datums
1379                                .iter()
1380                                .enumerate()
1381                                .map(|(i, d)| {
1382                                    TypedDatum::new(*d, &types[i])
1383                                        .json(&JsonNumberPolicy::ConvertNumberToString)
1384                                })
1385                                .collect(),
1386                        ),
1387                    )
1388                    .await?;
1389                    rows_returned += 1;
1390                }
1391                ws.flush().await?;
1392            }
1393            Some(PeekResponseUnary::Error(error)) => {
1394                return Ok(ws_peek_result(
1395                    client,
1396                    true,
1397                    vec![WebSocketResponse::Error(error.into())],
1398                ));
1399            }
1400            Some(PeekResponseUnary::DependencyDropped(dep)) => {
1401                return Ok(ws_peek_result(
1402                    client,
1403                    true,
1404                    vec![WebSocketResponse::Error(
1405                        dep.to_concurrent_dependency_drop().into(),
1406                    )],
1407                ));
1408            }
1409            Some(PeekResponseUnary::Canceled) => {
1410                return Ok(ws_peek_result(
1411                    client,
1412                    true,
1413                    vec![WebSocketResponse::Error(AdapterError::Canceled.into())],
1414                ));
1415            }
1416            None => {
1417                let execution_time = rows_stream
1418                    .take_execution_time()
1419                    .map(|time| client.session().maybe_mark_staged(time));
1420                let settled = match client.settle_statement(ends_group).await {
1421                    Ok(settled) => settled,
1422                    Err(err) => {
1423                        return Ok(ws_peek_result(
1424                            client,
1425                            true,
1426                            vec![WebSocketResponse::Error(err.into())],
1427                        ));
1428                    }
1429                };
1430                // An empty successful result still owes the client a `Rows`
1431                // descriptor before `CommandComplete`.
1432                if !sent_rows_desc {
1433                    send_ws_response(ws, WebSocketResponse::Rows(desc.into())).await?;
1434                }
1435                let command_complete =
1436                    WebSocketResponse::CommandComplete(format!("SELECT {rows_returned}"));
1437                let msgs = execution_time
1438                    .and_then(|time| client.session().execution_time_notice(time))
1439                    .map(|notice| WebSocketResponse::Notice(Notice::from(notice)))
1440                    .into_iter()
1441                    .chain([command_complete])
1442                    .collect();
1443                let (is_err, mut msgs, stmt_logging) = ws_peek_result(client, false, msgs);
1444                let reverted = notify_params(client, settled.reverted);
1445                msgs.extend(reverted.into_iter().map(WebSocketResponse::ParameterStatus));
1446                return Ok((is_err, msgs, stmt_logging));
1447            }
1448        }
1449    }
1450}
1451
1452/// Packages a terminal result of `stream_ws_peek_rows`, appending any notices
1453/// still buffered on the session after `msgs`.
1454///
1455/// The streaming loop forwards notices live through `await_rows`' `recv_notice`
1456/// select, but the terminal `recv() -> None` can race a still-buffered notice
1457/// and end the loop first. Draining here restores the buffered path's guarantee
1458/// that all notices reach the client, after `CommandComplete` or `Error`.
1459fn ws_peek_result(
1460    client: &mut SessionClient,
1461    is_err: bool,
1462    mut msgs: Vec<WebSocketResponse>,
1463) -> (
1464    bool,
1465    Vec<WebSocketResponse>,
1466    Option<(StatementEndedExecutionReason, ExecuteContextGuard)>,
1467) {
1468    msgs.extend(
1469        make_notices(client)
1470            .into_iter()
1471            .map(WebSocketResponse::Notice),
1472    );
1473    (is_err, msgs, None)
1474}
1475
1476async fn send_and_retire<S: ResultSender>(
1477    res: StatementResult,
1478    client: &mut SessionClient,
1479    sender: &mut S,
1480) -> Result<Result<(), ()>, Error> {
1481    let (res, stmt_logging) = sender.add_result(client, res).await;
1482    if let Some((reason, ctx_extra)) = stmt_logging {
1483        client.retire_execute(ctx_extra, reason);
1484    }
1485    res
1486}
1487
1488/// Returns Ok(Err) if any statement error'd during execution.
1489async fn execute_stmt_group<S: ResultSender>(
1490    client: &mut SessionClient,
1491    sender: &mut S,
1492    stmt_group: Vec<(Statement<Raw>, String, Vec<Option<String>>)>,
1493) -> Result<Result<(), ()>, Error> {
1494    let num_stmts = stmt_group.len();
1495    for (idx, (stmt, sql, params)) in stmt_group.into_iter().enumerate() {
1496        assert!(
1497            num_stmts <= 1 || params.is_empty(),
1498            "statement groups contain more than 1 statement iff Simple request, which does not support parameters"
1499        );
1500
1501        let is_aborted_txn = matches!(client.session().transaction(), TransactionStatus::Failed(_));
1502        if is_aborted_txn && !is_txn_exit_stmt(&stmt) {
1503            let err = SqlResult::err(client, Error::AbortedTransaction);
1504            let _ = send_and_retire(err.into(), client, sender).await?;
1505            return Ok(Err(()));
1506        }
1507
1508        // Mirror the behavior of the PostgreSQL simple query protocol.
1509        // See the pgwire::protocol::StateMachine::query method for details.
1510        if let Err(e) = client.start_transaction(Some(num_stmts)) {
1511            let err = SqlResult::err(client, e);
1512            let _ = send_and_retire(err.into(), client, sender).await?;
1513            return Ok(Err(()));
1514        }
1515        let ends_group = idx + 1 == num_stmts;
1516        let res = execute_stmt(client, sender, stmt, sql, params, ends_group).await?;
1517        let is_err = send_and_retire(res, client, sender).await?;
1518
1519        if is_err.is_err() {
1520            // Mirror StateMachine::error, which sometimes will clean up the
1521            // transaction state instead of always leaving it in Failed.
1522            let txn = client.session().transaction();
1523            match txn {
1524                // Error can be called from describe and parse and so might not be in an active
1525                // transaction.
1526                TransactionStatus::Default | TransactionStatus::Failed(_) => {}
1527                // In Started (i.e., a single statement) and implicit transactions cleanup themselves.
1528                TransactionStatus::Started(_) | TransactionStatus::InTransactionImplicit(_) => {
1529                    if let Err(err) = client.end_transaction(EndTransactionAction::Rollback).await {
1530                        let err = SqlResult::err(client, err);
1531                        let _ = send_and_retire(err.into(), client, sender).await?;
1532                    }
1533                }
1534                // Explicit transactions move to failed.
1535                TransactionStatus::InTransaction(_) => {
1536                    client.fail_transaction();
1537                }
1538            }
1539            return Ok(Err(()));
1540        }
1541    }
1542    Ok(Ok(()))
1543}
1544
1545/// Executes an entire [`SqlRequest`].
1546///
1547/// See the user-facing documentation about the HTTP API for a description of
1548/// the semantics of this function.
1549/// Executes a SQL request and sends results to the provided sender.
1550///
1551/// Made visible to http submodules (like mcp) via `pub(in crate::http)` to allow
1552/// reuse of SQL execution logic.
1553pub(in crate::http) async fn execute_request<S: ResultSender>(
1554    client: &mut AuthedClient,
1555    request: SqlRequest,
1556    sender: &mut S,
1557) -> Result<(), Error> {
1558    let client = &mut client.client;
1559
1560    if client.statement_arrival_logging_enabled().await {
1561        let session = client.session();
1562        let conn_id = session.conn_id();
1563        let session_uuid = session.uuid();
1564        match &request {
1565            SqlRequest::Simple { query } => {
1566                info!(
1567                    %conn_id, %session_uuid, kind = "http_simple",
1568                    sql = %redact_sql_for_logging(query.as_str()),
1569                    "statement arrival"
1570                );
1571            }
1572            SqlRequest::Extended { queries } => {
1573                for ExtendedRequest { query, params } in queries {
1574                    // Parameter values are data that redaction cannot reach,
1575                    // so only their count is logged.
1576                    info!(
1577                        %conn_id, %session_uuid, kind = "http_extended",
1578                        sql = %redact_sql_for_logging(query), num_params = params.len(),
1579                        "statement arrival"
1580                    );
1581                }
1582            }
1583        }
1584    }
1585
1586    // This API prohibits executing statements with responses whose
1587    // semantics are at odds with an HTTP response.
1588    fn check_prohibited_stmts<S: ResultSender>(
1589        sender: &S,
1590        stmt: &Statement<Raw>,
1591    ) -> Result<(), Error> {
1592        let kind: StatementKind = stmt.into();
1593        let execute_responses = Plan::generated_from(&kind)
1594            .into_iter()
1595            .map(ExecuteResponse::generated_from)
1596            .flatten()
1597            .collect::<Vec<_>>();
1598
1599        // Special-case `COPY TO` statements that are not `COPY ... TO STDOUT`, since
1600        // StatementKind::Copy links to several `ExecuteResponseKind`s that are not supported,
1601        // but this specific statement should be allowed.
1602        let is_valid_copy = matches!(
1603            stmt,
1604            Statement::Copy(CopyStatement {
1605                direction: CopyDirection::To,
1606                target: CopyTarget::Expr(_),
1607                ..
1608            }) | Statement::Copy(CopyStatement {
1609                direction: CopyDirection::From,
1610                target: CopyTarget::Expr(_),
1611                ..
1612            })
1613        );
1614
1615        if !is_valid_copy
1616            && execute_responses.iter().any(|execute_response| {
1617                // Returns true if a statement or execute response are unsupported.
1618                match execute_response {
1619                    ExecuteResponseKind::Subscribing if sender.allow_subscribe() => false,
1620                    ExecuteResponseKind::Fetch
1621                    | ExecuteResponseKind::Subscribing
1622                    | ExecuteResponseKind::CopyFrom
1623                    | ExecuteResponseKind::DeclaredCursor
1624                    | ExecuteResponseKind::ClosedCursor => true,
1625                    // Various statements generate `PeekPlan` (`SELECT`, `COPY`,
1626                    // `EXPLAIN`, `SHOW`) which has both `SendRows` and `CopyTo` as its
1627                    // possible response types. but `COPY` needs be picked out because
1628                    // http don't support its response type
1629                    ExecuteResponseKind::CopyTo if matches!(kind, StatementKind::Copy) => true,
1630                    _ => false,
1631                }
1632            })
1633        {
1634            return Err(Error::Unsupported(stmt.to_ast_string_simple()));
1635        }
1636        Ok(())
1637    }
1638
1639    fn parse<'a>(
1640        client: &SessionClient,
1641        query: &'a str,
1642    ) -> Result<Vec<StatementParseResult<'a>>, Error> {
1643        let result = client
1644            .parse(query)
1645            .map_err(|e| Error::Unstructured(anyhow!(e)))?;
1646        result.map_err(|e| AdapterError::from(e).into())
1647    }
1648
1649    let mut stmt_groups = vec![];
1650
1651    match request {
1652        SqlRequest::Simple { query } => match parse(client, query.as_str()) {
1653            Ok(stmts) => {
1654                let mut stmt_group = Vec::with_capacity(stmts.len());
1655                let mut stmt_err = None;
1656                for StatementParseResult { ast: stmt, sql } in stmts {
1657                    if let Err(err) = check_prohibited_stmts(sender, &stmt) {
1658                        stmt_err = Some(err);
1659                        break;
1660                    }
1661                    stmt_group.push((stmt, sql.to_string(), vec![]));
1662                }
1663                stmt_groups.push(stmt_err.map(Err).unwrap_or_else(|| Ok(stmt_group)));
1664            }
1665            Err(e) => stmt_groups.push(Err(e)),
1666        },
1667        SqlRequest::Extended { queries } => {
1668            for ExtendedRequest { query, params } in queries {
1669                match parse(client, &query) {
1670                    Ok(mut stmts) => {
1671                        if stmts.len() != 1 {
1672                            return Err(Error::Unstructured(anyhow!(
1673                                "each query must contain exactly 1 statement, but \"{}\" contains {}",
1674                                query,
1675                                stmts.len()
1676                            )));
1677                        }
1678
1679                        let StatementParseResult { ast: stmt, sql } = stmts.pop().unwrap();
1680                        stmt_groups.push(
1681                            check_prohibited_stmts(sender, &stmt)
1682                                .map(|_| vec![(stmt, sql.to_string(), params)]),
1683                        );
1684                    }
1685                    Err(e) => stmt_groups.push(Err(e)),
1686                };
1687            }
1688        }
1689    }
1690
1691    for stmt_group_res in stmt_groups {
1692        let executed = match stmt_group_res {
1693            Ok(stmt_group) => execute_stmt_group(client, sender, stmt_group).await,
1694            Err(e) => {
1695                let err = SqlResult::err(client, e);
1696                let _ = send_and_retire(err.into(), client, sender).await?;
1697                Ok(Err(()))
1698            }
1699        };
1700        // At the end of each group, commit implicit transactions. Do that here so that any `?`
1701        // early return can still be handled here.
1702        let mut commit_failed = false;
1703        if client.session().transaction().is_implicit() {
1704            let ended = client.end_transaction(EndTransactionAction::Commit).await;
1705            if let Err(err) = ended {
1706                let err = SqlResult::err(client, err);
1707                let _ = send_and_retire(StatementResult::SqlResult(err), client, sender).await?;
1708                commit_failed = true;
1709            }
1710        }
1711        if executed?.is_err() || commit_failed {
1712            break;
1713        }
1714    }
1715
1716    Ok(())
1717}
1718
1719/// Executes a single statement in a [`SqlRequest`].
1720async fn execute_stmt<S: ResultSender>(
1721    client: &mut SessionClient,
1722    sender: &mut S,
1723    stmt: Statement<Raw>,
1724    sql: String,
1725    raw_params: Vec<Option<String>>,
1726    ends_group: bool,
1727) -> Result<StatementResult, Error> {
1728    const EMPTY_PORTAL: &str = "";
1729    if let Err(e) = client
1730        .prepare(EMPTY_PORTAL.into(), Some(stmt.clone()), sql, vec![])
1731        .await
1732    {
1733        return Ok(SqlResult::err(client, e).into());
1734    }
1735
1736    let prep_stmt = match client.get_prepared_statement(EMPTY_PORTAL).await {
1737        Ok(stmt) => stmt,
1738        Err(err) => {
1739            return Ok(SqlResult::err(client, err).into());
1740        }
1741    };
1742
1743    let param_types = &prep_stmt.desc().param_types;
1744    if param_types.len() != raw_params.len() {
1745        let message = anyhow!(
1746            "request supplied {actual} parameters, \
1747                        but {statement} requires {expected}",
1748            statement = stmt.to_ast_string_simple(),
1749            actual = raw_params.len(),
1750            expected = param_types.len()
1751        );
1752        return Ok(SqlResult::err(client, Error::Unstructured(message)).into());
1753    }
1754
1755    let buf = RowArena::new();
1756    let mut params = vec![];
1757    for (raw_param, mz_typ) in raw_params.into_iter().zip_eq(param_types) {
1758        let pg_typ = mz_pgrepr::Type::from(mz_typ);
1759        let datum = match raw_param {
1760            None => Datum::Null,
1761            Some(raw_param) => {
1762                match mz_pgrepr::Value::decode(
1763                    mz_pgwire_common::Format::Text,
1764                    &pg_typ,
1765                    raw_param.as_bytes(),
1766                ) {
1767                    Ok(param) => match param.into_datum_decode_error(&buf, &pg_typ, "parameter") {
1768                        Ok(datum) => datum,
1769                        Err(msg) => {
1770                            return Ok(
1771                                SqlResult::err(client, Error::Unstructured(anyhow!(msg))).into()
1772                            );
1773                        }
1774                    },
1775                    Err(err) => {
1776                        let msg = anyhow!("unable to decode parameter: {}", err);
1777                        return Ok(SqlResult::err(client, Error::Unstructured(msg)).into());
1778                    }
1779                }
1780            }
1781        };
1782        params.push((datum, mz_typ.clone()))
1783    }
1784
1785    let result_formats = vec![
1786        mz_pgwire_common::Format::Text;
1787        prep_stmt
1788            .desc()
1789            .relation_desc
1790            .clone()
1791            .map(|desc| desc.typ().column_types.len())
1792            .unwrap_or(0)
1793    ];
1794
1795    let desc = prep_stmt.desc().clone();
1796    let logging = Arc::clone(prep_stmt.logging());
1797    let stmt_ast = prep_stmt.stmt().cloned();
1798    let state_revision = prep_stmt.state_revision;
1799    if let Err(err) = client.session().set_portal(
1800        EMPTY_PORTAL.into(),
1801        desc,
1802        stmt_ast,
1803        logging,
1804        params,
1805        result_formats,
1806        state_revision,
1807    ) {
1808        return Ok(SqlResult::err(client, err).into());
1809    }
1810
1811    let desc = client
1812        .session()
1813        // We do not need to verify here because `client.execute` verifies below.
1814        .get_portal_unverified(EMPTY_PORTAL)
1815        .map(|portal| portal.desc.clone())
1816        .expect("unnamed portal should be present");
1817
1818    let res = client
1819        .execute(EMPTY_PORTAL.into(), futures::future::pending(), None)
1820        .await;
1821    // The execution time of a statement whose response carries no rows is taken here, before
1822    // notices are sent.
1823    let executed = Instant::now();
1824
1825    if S::SUPPORTS_STREAMING_NOTICES {
1826        sender
1827            .emit_streaming_notices(client.session().drain_notices())
1828            .await?;
1829    }
1830
1831    let (res, execute_started) = match res {
1832        Ok(res) => res,
1833        Err(e) => {
1834            return Ok(SqlResult::err(client, e).into());
1835        }
1836    };
1837    let execution_time = client.session().maybe_mark_staged(ExecutionTime::completed(
1838        executed.duration_since(execute_started),
1839    ));
1840    let tag = res.tag();
1841
1842    Ok(match res {
1843        ExecuteResponse::CreatedConnection { .. }
1844        | ExecuteResponse::CreatedDatabase { .. }
1845        | ExecuteResponse::CreatedSchema { .. }
1846        | ExecuteResponse::CreatedRole
1847        | ExecuteResponse::CreatedCluster { .. }
1848        | ExecuteResponse::CreatedClusterReplica { .. }
1849        | ExecuteResponse::CreatedTable { .. }
1850        | ExecuteResponse::CreatedIndex { .. }
1851        | ExecuteResponse::CreatedMetricSink { .. }
1852        | ExecuteResponse::CreatedIntrospectionSubscribe
1853        | ExecuteResponse::CreatedSecret { .. }
1854        | ExecuteResponse::CreatedSource { .. }
1855        | ExecuteResponse::CreatedSink { .. }
1856        | ExecuteResponse::CreatedView { .. }
1857        | ExecuteResponse::CreatedViews { .. }
1858        | ExecuteResponse::CreatedMaterializedView { .. }
1859        | ExecuteResponse::CreatedType
1860        | ExecuteResponse::CreatedNetworkPolicy
1861        | ExecuteResponse::CreatedQueryPolicy
1862        | ExecuteResponse::Comment
1863        | ExecuteResponse::Deleted(_)
1864        | ExecuteResponse::DiscardedTemp
1865        | ExecuteResponse::DroppedObject(_)
1866        | ExecuteResponse::DroppedOwned
1867        | ExecuteResponse::EmptyQuery
1868        | ExecuteResponse::GrantedPrivilege
1869        | ExecuteResponse::GrantedRole
1870        | ExecuteResponse::Inserted(_)
1871        | ExecuteResponse::Copied(_)
1872        | ExecuteResponse::Raised
1873        | ExecuteResponse::ReassignOwned
1874        | ExecuteResponse::RevokedPrivilege
1875        | ExecuteResponse::AlteredDefaultPrivileges
1876        | ExecuteResponse::RevokedRole
1877        | ExecuteResponse::StartedTransaction { .. }
1878        | ExecuteResponse::Updated(_)
1879        | ExecuteResponse::AlteredObject(_)
1880        | ExecuteResponse::AlteredRole
1881        | ExecuteResponse::AlteredSystemConfiguration
1882        | ExecuteResponse::Deallocate { .. }
1883        | ExecuteResponse::ValidatedConnection
1884        | ExecuteResponse::Prepare => SqlResult::ok(
1885            client,
1886            tag.expect("ok only called on tag-generating results"),
1887            Vec::default(),
1888            ends_group,
1889            execution_time,
1890        )
1891        .await
1892        .into(),
1893        ExecuteResponse::TransactionCommitted { params }
1894        | ExecuteResponse::TransactionRolledBack { params }
1895        | ExecuteResponse::DiscardedAll { params } => {
1896            let params = notify_params(client, params);
1897            SqlResult::ok(
1898                client,
1899                tag.expect("ok only called on tag-generating results"),
1900                params,
1901                ends_group,
1902                execution_time,
1903            )
1904            .await
1905            .into()
1906        }
1907        ExecuteResponse::SetVariable { name, .. } => {
1908            let mut params = Vec::with_capacity(1);
1909            if let Some(var) = client
1910                .session()
1911                .vars()
1912                .notify_set()
1913                .find(|v| v.name() == &name)
1914            {
1915                params.push(ParameterStatus {
1916                    name,
1917                    value: var.value(),
1918                });
1919            };
1920            SqlResult::ok(
1921                client,
1922                tag.expect("ok only called on tag-generating results"),
1923                params,
1924                ends_group,
1925                execution_time,
1926            )
1927            .await
1928            .into()
1929        }
1930        ExecuteResponse::SendingRowsStreaming {
1931            rows,
1932            instance_id,
1933            strategy,
1934        } => {
1935            let max_result_size = max_result_size(client).await;
1936
1937            let rows_stream = RecordFirstRowStream::new(
1938                Box::new(rows),
1939                execute_started,
1940                client,
1941                Some(instance_id),
1942                Some(strategy),
1943            );
1944
1945            StatementResult::Rows {
1946                desc: desc.relation_desc.expect("RelationDesc must exist"),
1947                rows_stream,
1948                max_result_size,
1949                ends_group,
1950            }
1951        }
1952        ExecuteResponse::SendingRowsImmediate { rows } => {
1953            let max_result_size = max_result_size(client).await;
1954
1955            let rows = futures::stream::once(futures::future::ready(PeekResponseUnary::Rows(rows)));
1956            let rows_stream = RecordFirstRowStream::new(
1957                Box::new(rows),
1958                execute_started,
1959                client,
1960                None,
1961                Some(StatementExecutionStrategy::Constant),
1962            );
1963
1964            StatementResult::Rows {
1965                desc: desc.relation_desc.expect("RelationDesc must exist"),
1966                rows_stream,
1967                max_result_size,
1968                ends_group,
1969            }
1970        }
1971        ExecuteResponse::Subscribing {
1972            rx,
1973            ctx_extra,
1974            instance_id,
1975        } => StatementResult::Subscribe {
1976            tag: "SUBSCRIBE".into(),
1977            desc: desc.relation_desc.unwrap(),
1978            rx: RecordFirstRowStream::new(rx, execute_started, client, Some(instance_id), None)
1979                .without_execution_time(),
1980            ctx_extra,
1981        },
1982        res @ (ExecuteResponse::Fetch { .. }
1983        | ExecuteResponse::CopyTo { .. }
1984        | ExecuteResponse::CopyFrom { .. }
1985        | ExecuteResponse::DeclaredCursor
1986        | ExecuteResponse::ClosedCursor) => SqlResult::err(
1987            client,
1988            Error::Unstructured(anyhow!(
1989                "internal error: encountered prohibited ExecuteResponse {:?}.\n\n
1990            This is a bug. Can you please file an bug report letting us know?\n
1991            https://github.com/MaterializeInc/materialize/discussions/new?category=bug-reports",
1992                ExecuteResponseKind::from(res)
1993            )),
1994        )
1995        .into(),
1996    })
1997}
1998
1999/// The current `max_result_size` system variable.
2000///
2001/// Reads the session's cached catalog, which usually needs no coordinator round trip.
2002async fn max_result_size(client: &mut SessionClient) -> usize {
2003    let catalog = client.catalog_snapshot("http_max_result_size").await;
2004    usize::cast_from(catalog.system_config().max_result_size())
2005}
2006
2007/// The session parameters among `params` that clients are notified about.
2008fn notify_params(
2009    client: &mut SessionClient,
2010    params: BTreeMap<&'static str, String>,
2011) -> Vec<ParameterStatus> {
2012    let notify_set: mz_ore::collections::HashSet<_> = client
2013        .session()
2014        .vars()
2015        .notify_set()
2016        .map(|v| v.name().to_string())
2017        .collect();
2018    params
2019        .into_iter()
2020        .filter(|(name, _value)| notify_set.contains(*name))
2021        .map(|(name, value)| ParameterStatus {
2022            name: name.to_string(),
2023            value,
2024        })
2025        .collect()
2026}
2027
2028fn make_notices(client: &mut SessionClient) -> Vec<Notice> {
2029    client
2030        .session()
2031        .drain_notices()
2032        .into_iter()
2033        .map(Notice::from)
2034        .collect()
2035}
2036
2037impl From<AdapterNotice> for Notice {
2038    fn from(notice: AdapterNotice) -> Self {
2039        Notice {
2040            message: notice.to_string(),
2041            code: notice.code().code().to_string(),
2042            severity: notice.severity().as_str().to_lowercase(),
2043            detail: notice.detail(),
2044            hint: notice.hint(),
2045        }
2046    }
2047}
2048
2049// Duplicated from protocol.rs.
2050// See postgres' backend/tcop/postgres.c IsTransactionExitStmt.
2051fn is_txn_exit_stmt(stmt: &Statement<Raw>) -> bool {
2052    matches!(
2053        stmt,
2054        Statement::Commit(_) | Statement::Rollback(_) | Statement::Prepare(_)
2055    )
2056}
2057
2058#[cfg(test)]
2059mod tests {
2060    use std::collections::BTreeMap;
2061
2062    use super::{Password, WebSocketAuth};
2063
2064    #[mz_ore::test]
2065    fn smoke_test_websocket_auth_parse() {
2066        struct TestCase {
2067            json: &'static str,
2068            expected: WebSocketAuth,
2069        }
2070
2071        let test_cases = vec![
2072            TestCase {
2073                json: r#"{ "user": "mz", "password": "1234" }"#,
2074                expected: WebSocketAuth::Basic {
2075                    user: "mz".to_string(),
2076                    password: Password("1234".to_string()),
2077                    options: BTreeMap::default(),
2078                },
2079            },
2080            TestCase {
2081                json: r#"{ "user": "mz", "password": "1234", "options": {} }"#,
2082                expected: WebSocketAuth::Basic {
2083                    user: "mz".to_string(),
2084                    password: Password("1234".to_string()),
2085                    options: BTreeMap::default(),
2086                },
2087            },
2088            TestCase {
2089                json: r#"{ "token": "i_am_a_token" }"#,
2090                expected: WebSocketAuth::Bearer {
2091                    token: "i_am_a_token".to_string(),
2092                    options: BTreeMap::default(),
2093                },
2094            },
2095            TestCase {
2096                json: r#"{ "token": "i_am_a_token", "options": { "foo": "bar" } }"#,
2097                expected: WebSocketAuth::Bearer {
2098                    token: "i_am_a_token".to_string(),
2099                    options: BTreeMap::from([("foo".to_string(), "bar".to_string())]),
2100                },
2101            },
2102        ];
2103
2104        fn assert_parse(json: &'static str, expected: WebSocketAuth) {
2105            let parsed: WebSocketAuth = serde_json::from_str(json).unwrap();
2106            assert_eq!(parsed, expected);
2107        }
2108
2109        for TestCase { json, expected } in test_cases {
2110            assert_parse(json, expected)
2111        }
2112    }
2113}