Skip to main content

mz_adapter/coord/
command_handler.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
10//! Logic for  processing client [`Command`]s. Each [`Command`] is initiated by a
11//! client via some external Materialize API (ex: HTTP and psql).
12
13use base64::prelude::*;
14use differential_dataflow::lattice::Lattice;
15use mz_adapter_types::dyncfgs::ALLOW_USER_SESSIONS;
16use mz_auth::AuthenticatorKind;
17use mz_auth::password::Password;
18use mz_repr::namespaces::MZ_INTERNAL_SCHEMA;
19use mz_sql::catalog::AutoProvisionSource;
20use mz_sql::session::metadata::SessionMetadata;
21use std::collections::{BTreeMap, BTreeSet};
22use std::net::IpAddr;
23use std::sync::Arc;
24
25use futures::FutureExt;
26use futures::future::LocalBoxFuture;
27use mz_adapter_types::connection::{ConnectionId, ConnectionIdType};
28use mz_catalog::SYSTEM_CONN_ID;
29use mz_catalog::memory::objects::{
30    CatalogItem, DataSourceDesc, Role, Source, Table, TableDataSource,
31};
32use mz_ore::task;
33use mz_ore::tracing::OpenTelemetryContext;
34use mz_ore::{instrument, soft_panic_or_log};
35use mz_repr::role_id::RoleId;
36use mz_repr::{Diff, GlobalId, SqlScalarType, Timestamp};
37use mz_sql::ast::{
38    AlterConnectionAction, AlterConnectionStatement, AlterSinkAction, AlterSourceAction, AstInfo,
39    ConstantVisitor, CopyRelation, CopyStatement, CreateSourceOptionName, Raw, Statement,
40    SubscribeStatement,
41};
42use mz_sql::catalog::RoleAttributesRaw;
43use mz_sql::names::{Aug, PartialItemName, ResolvedIds};
44use mz_sql::plan::{
45    AbortTransactionPlan, CommitTransactionPlan, CreateRolePlan, Params, Plan,
46    StatementClassification, TransactionType,
47};
48use mz_sql::pure::{
49    materialized_view_option_contains_temporal, purify_create_materialized_view_options,
50};
51use mz_sql::rbac;
52use mz_sql::rbac::CREATE_ITEM_USAGE;
53use mz_sql::session::user::User;
54use mz_sql::session::vars::{
55    EndTransactionAction, NETWORK_POLICY, OwnedVarInput, STATEMENT_LOGGING_SAMPLE_RATE, Value, Var,
56};
57use mz_sql_parser::ast::display::AstDisplay;
58use mz_sql_parser::ast::{
59    CreateMaterializedViewStatement, ExplainPlanStatement, Explainee, InsertStatement,
60    WithOptionValue,
61};
62use mz_storage_types::sources::Timeline;
63use opentelemetry::trace::TraceContextExt;
64use tokio::sync::{mpsc, oneshot};
65use tracing::{Instrument, debug_span, info, warn};
66use tracing_opentelemetry::OpenTelemetrySpanExt;
67use uuid::Uuid;
68
69use crate::command::{
70    CatalogSnapshot, Command, ExecuteResponse, Response, SASLChallengeResponse,
71    SASLVerifyProofResponse, StartupResponse, SuperuserAttribute,
72};
73use crate::coord::appends::PendingWriteTxn;
74use crate::coord::peek::PendingPeek;
75use crate::coord::{
76    ConnMeta, Coordinator, DeferredPlanStatement, Message, PendingTxn, PlanStatement, PlanValidity,
77    PurifiedStatementReady, validate_ip_with_policy_rules,
78};
79use crate::error::{AdapterError, AuthenticationError};
80use crate::notice::AdapterNotice;
81use crate::session::{Session, TransactionOps, TransactionStatus};
82use crate::statement_logging::WatchSetCreation;
83use crate::util::{ClientTransmitter, ResultExt};
84use crate::webhook::{
85    AppendWebhookResponse, AppendWebhookValidator, WebhookAppender, WebhookAppenderInvalidator,
86};
87use crate::{AppendWebhookError, ExecuteContext, catalog, metrics};
88
89use super::ExecuteContextGuard;
90
91/// The login status of a role, used by authentication handlers to check role
92/// existence and login permission before proceeding to credential verification.
93enum RoleLoginStatus {
94    /// The role does not exist in the catalog.
95    NotFound,
96    /// The role exists and has the LOGIN attribute.
97    CanLogin,
98    /// The role exists but does not have the LOGIN attribute.
99    NonLogin,
100}
101
102fn role_login_status(role: Option<&Role>) -> RoleLoginStatus {
103    match role {
104        None => RoleLoginStatus::NotFound,
105        Some(role) => match role.attributes.login {
106            Some(login) if login => RoleLoginStatus::CanLogin,
107            _ => RoleLoginStatus::NonLogin,
108        },
109    }
110}
111
112impl Coordinator {
113    /// BOXED FUTURE: As of Nov 2023 the returned Future from this function was 58KB. This would
114    /// get stored on the stack which is bad for runtime performance, and blow up our stack usage.
115    /// Because of that we purposefully move this Future onto the heap (i.e. Box it).
116    pub(crate) fn handle_command(&mut self, mut cmd: Command) -> LocalBoxFuture<'_, ()> {
117        async move {
118            if let Some(session) = cmd.session_mut() {
119                session.apply_external_metadata_updates();
120            }
121            match cmd {
122                Command::Startup {
123                    tx,
124                    user,
125                    conn_id,
126                    secret_key,
127                    uuid,
128                    client_ip,
129                    application_name,
130                    notice_tx,
131                } => {
132                    // Note: We purposefully do not use a ClientTransmitter here because startup
133                    // handles errors and cleanup of sessions itself.
134                    self.handle_startup(
135                        tx,
136                        user,
137                        conn_id,
138                        secret_key,
139                        uuid,
140                        client_ip,
141                        application_name,
142                        notice_tx,
143                    )
144                    .await;
145                }
146
147                Command::AuthenticatePassword {
148                    tx,
149                    role_name,
150                    password,
151                } => {
152                    self.handle_authenticate_password(tx, role_name, password)
153                        .await;
154                }
155
156                Command::AuthenticateGetSASLChallenge {
157                    tx,
158                    role_name,
159                    nonce,
160                } => {
161                    self.handle_generate_sasl_challenge(tx, role_name, nonce)
162                        .await;
163                }
164
165                Command::AuthenticateVerifySASLProof {
166                    tx,
167                    role_name,
168                    proof,
169                    mock_hash,
170                    auth_message,
171                } => {
172                    self.handle_authenticate_verify_sasl_proof(
173                        tx,
174                        role_name,
175                        proof,
176                        auth_message,
177                        mock_hash,
178                    );
179                }
180
181                Command::CheckRoleCanLogin { tx, role_name } => {
182                    self.handle_role_can_login(tx, role_name);
183                }
184
185                Command::Execute {
186                    portal_name,
187                    session,
188                    tx,
189                    outer_ctx_extra,
190                } => {
191                    let tx = ClientTransmitter::new(tx, self.internal_cmd_tx.clone());
192
193                    self.handle_execute(portal_name, session, tx, outer_ctx_extra)
194                        .await;
195                }
196
197                Command::StartCopyFromStdin {
198                    target_id,
199                    target_name,
200                    columns,
201                    row_desc,
202                    params,
203                    session,
204                    tx,
205                } => {
206                    let otel_ctx = OpenTelemetryContext::obtain();
207                    let result = self.setup_copy_from_stdin(
208                        &session,
209                        target_id,
210                        target_name,
211                        columns,
212                        row_desc,
213                        params,
214                    );
215                    let _ = tx.send(Response {
216                        result,
217                        session,
218                        otel_ctx,
219                    });
220                }
221
222                Command::RetireExecute { data, reason } => self.retire_execution(reason, data),
223
224                Command::CancelRequest {
225                    conn_id,
226                    secret_key,
227                } => {
228                    self.handle_cancel(conn_id, secret_key).await;
229                }
230
231                Command::PrivilegedCancelRequest { conn_id } => {
232                    self.handle_privileged_cancel(conn_id).await;
233                }
234
235                Command::GetWebhook {
236                    database,
237                    schema,
238                    name,
239                    tx,
240                } => {
241                    self.handle_get_webhook(database, schema, name, tx);
242                }
243
244                Command::GetSystemVars { tx } => {
245                    let _ = tx.send(self.catalog.system_config().clone());
246                }
247
248                Command::SetSystemVars { vars, conn_id, tx } => {
249                    let mut ops = Vec::with_capacity(vars.len());
250                    let conn = &self.active_conns[&conn_id];
251
252                    for (name, value) in vars {
253                        if let Err(e) =
254                            self.catalog().system_config().get(&name).and_then(|var| {
255                                var.visible(conn.user(), self.catalog.system_config())
256                            })
257                        {
258                            let _ = tx.send(Err(e.into()));
259                            return;
260                        }
261
262                        ops.push(catalog::Op::UpdateSystemConfiguration {
263                            name,
264                            value: OwnedVarInput::Flat(value),
265                        });
266                    }
267
268                    let result = self
269                        .catalog_transact_with_context(Some(&conn_id), None, ops)
270                        .await;
271                    let _ = tx.send(result);
272                }
273
274                Command::InjectAuditEvents {
275                    events,
276                    conn_id,
277                    tx,
278                } => {
279                    let ops = vec![catalog::Op::InjectAuditEvents { events }];
280                    let result = self
281                        .catalog_transact_with_context(Some(&conn_id), None, ops)
282                        .await;
283                    let _ = tx.send(result);
284                }
285
286                Command::Terminate { conn_id, tx } => {
287                    self.handle_terminate(conn_id).await;
288                    // Note: We purposefully do not use a ClientTransmitter here because we're already
289                    // terminating the provided session.
290                    if let Some(tx) = tx {
291                        let _ = tx.send(Ok(()));
292                    }
293                }
294
295                Command::Commit {
296                    action,
297                    session,
298                    tx,
299                } => {
300                    let tx = ClientTransmitter::new(tx, self.internal_cmd_tx.clone());
301                    // We reach here not through a statement execution, but from the
302                    // "commit" pgwire command. Thus, we just generate a default statement
303                    // execution context (once statement logging is implemented, this will cause nothing to be logged
304                    // when the execution finishes.)
305                    let ctx = ExecuteContext::from_parts(
306                        tx,
307                        self.internal_cmd_tx.clone(),
308                        session,
309                        Default::default(),
310                    );
311                    let plan = match action {
312                        EndTransactionAction::Commit => {
313                            Plan::CommitTransaction(CommitTransactionPlan {
314                                transaction_type: TransactionType::Implicit,
315                            })
316                        }
317                        EndTransactionAction::Rollback => {
318                            Plan::AbortTransaction(AbortTransactionPlan {
319                                transaction_type: TransactionType::Implicit,
320                            })
321                        }
322                    };
323
324                    let conn_id = ctx.session().conn_id().clone();
325                    self.sequence_plan(ctx, plan, ResolvedIds::empty()).await;
326                    // Part of the Command::Commit contract is that the Coordinator guarantees that
327                    // it has cleared its transaction state for the connection.
328                    self.clear_connection(&conn_id).await;
329                }
330
331                Command::CatalogSnapshot { tx } => {
332                    let _ = tx.send(CatalogSnapshot {
333                        catalog: self.owned_catalog(),
334                    });
335                }
336
337                Command::CheckConsistency { tx } => {
338                    let _ = tx.send(self.check_consistency());
339                }
340
341                Command::Dump { tx } => {
342                    let _ = tx.send(self.dump().await);
343                }
344
345                Command::GetComputeInstanceClient { instance_id, tx } => {
346                    let _ = tx.send(self.controller.compute.instance_client(instance_id));
347                }
348
349                Command::GetOracle { timeline, tx } => {
350                    let oracle = self
351                        .global_timelines
352                        .get(&timeline)
353                        .map(|timeline_state| Arc::clone(&timeline_state.oracle))
354                        .ok_or(AdapterError::ChangedPlan(
355                            "timeline has disappeared during planning".to_string(),
356                        ));
357                    let _ = tx.send(oracle);
358                }
359
360                Command::DetermineRealTimeRecentTimestamp {
361                    source_ids,
362                    real_time_recency_timeout,
363                    tx,
364                } => {
365                    let result = self
366                        .determine_real_time_recent_timestamp(
367                            source_ids.iter().copied(),
368                            real_time_recency_timeout,
369                        )
370                        .await;
371
372                    match result {
373                        Ok(Some(fut)) => {
374                            task::spawn(|| "determine real time recent timestamp", async move {
375                                let result = fut.await.map(Some).map_err(AdapterError::from);
376                                let _ = tx.send(result);
377                            });
378                        }
379                        Ok(None) => {
380                            let _ = tx.send(Ok(None));
381                        }
382                        Err(e) => {
383                            let _ = tx.send(Err(e));
384                        }
385                    }
386                }
387
388                Command::GetTransactionReadHoldsBundle { conn_id, tx } => {
389                    let read_holds = self.txn_read_holds.get(&conn_id).cloned();
390                    let _ = tx.send(read_holds);
391                }
392
393                Command::StoreTransactionReadHolds {
394                    conn_id,
395                    read_holds,
396                    tx,
397                } => {
398                    self.store_transaction_read_holds(conn_id, read_holds);
399                    let _ = tx.send(());
400                }
401
402                Command::ExecuteSlowPathPeek {
403                    dataflow_plan,
404                    determination,
405                    finishing,
406                    compute_instance,
407                    target_replica,
408                    intermediate_result_type,
409                    source_ids,
410                    conn_id,
411                    max_result_size,
412                    max_query_result_size,
413                    watch_set,
414                    tx,
415                } => {
416                    let result = self
417                        .implement_slow_path_peek(
418                            *dataflow_plan,
419                            determination,
420                            finishing,
421                            compute_instance,
422                            target_replica,
423                            intermediate_result_type,
424                            source_ids,
425                            conn_id,
426                            max_result_size,
427                            max_query_result_size,
428                            watch_set,
429                        )
430                        .await;
431                    let _ = tx.send(result);
432                }
433
434                Command::ExecuteSubscribe {
435                    df_desc,
436                    dependency_ids,
437                    cluster_id,
438                    replica_id,
439                    conn_id,
440                    session_uuid,
441                    read_holds,
442                    plan,
443                    statement_logging_id,
444                    tx,
445                } => {
446                    let mut ctx_extra = ExecuteContextGuard::new(
447                        statement_logging_id,
448                        self.internal_cmd_tx.clone(),
449                    );
450                    let result = self
451                        .implement_subscribe(
452                            &mut ctx_extra,
453                            df_desc,
454                            dependency_ids,
455                            cluster_id,
456                            replica_id,
457                            conn_id,
458                            session_uuid,
459                            read_holds,
460                            plan,
461                        )
462                        .await;
463                    let _ = tx.send(result);
464                }
465
466                Command::CopyToPreflight {
467                    s3_sink_connection,
468                    sink_id,
469                    tx,
470                } => {
471                    // Spawn a background task to perform the slow S3 preflight operations.
472                    // This avoids blocking the coordinator's main task.
473                    let connection_context = self.connection_context().clone();
474                    task::spawn(|| "copy_to_preflight", async move {
475                        let result = mz_storage_types::sinks::s3_oneshot_sink::preflight(
476                            connection_context,
477                            &s3_sink_connection.aws_connection,
478                            &s3_sink_connection.upload_info,
479                            s3_sink_connection.connection_id,
480                            sink_id,
481                        )
482                        .await
483                        .map_err(AdapterError::from);
484                        let _ = tx.send(result);
485                    });
486                }
487
488                Command::ExecuteCopyTo {
489                    df_desc,
490                    compute_instance,
491                    target_replica,
492                    source_ids,
493                    conn_id,
494                    watch_set,
495                    tx,
496                } => {
497                    // implement_copy_to spawns a background task that sends the response
498                    // through tx when the COPY TO completes (or immediately if setup fails).
499                    // We just call it and let it handle all response sending.
500                    self.implement_copy_to(
501                        *df_desc,
502                        compute_instance,
503                        target_replica,
504                        source_ids,
505                        conn_id,
506                        watch_set,
507                        tx,
508                    )
509                    .await;
510                }
511
512                Command::ExecuteSideEffectingFunc {
513                    plan,
514                    conn_id,
515                    current_role,
516                    tx,
517                } => {
518                    let result = self
519                        .execute_side_effecting_func(plan, conn_id, current_role)
520                        .await;
521                    let _ = tx.send(result);
522                }
523                Command::RegisterFrontendPeek {
524                    uuid,
525                    conn_id,
526                    cluster_id,
527                    depends_on,
528                    is_fast_path,
529                    watch_set,
530                    tx,
531                } => {
532                    self.handle_register_frontend_peek(
533                        uuid,
534                        conn_id,
535                        cluster_id,
536                        depends_on,
537                        is_fast_path,
538                        watch_set,
539                        tx,
540                    );
541                }
542                Command::UnregisterFrontendPeek { uuid, tx } => {
543                    self.handle_unregister_frontend_peek(uuid, tx);
544                }
545                Command::ExplainTimestamp {
546                    conn_id,
547                    session_wall_time,
548                    cluster_id,
549                    id_bundle,
550                    determination,
551                    tx,
552                } => {
553                    let explanation = self.explain_timestamp(
554                        &conn_id,
555                        session_wall_time,
556                        cluster_id,
557                        &id_bundle,
558                        determination,
559                    );
560                    let _ = tx.send(explanation);
561                }
562                Command::FrontendStatementLogging(event) => {
563                    self.handle_frontend_statement_logging_event(event);
564                }
565            }
566        }
567        .instrument(debug_span!("handle_command"))
568        .boxed_local()
569    }
570
571    fn handle_role_can_login(
572        &self,
573        tx: oneshot::Sender<Result<(), AdapterError>>,
574        role_name: String,
575    ) {
576        let result =
577            match role_login_status(self.catalog().try_get_role_by_name(role_name.as_str())) {
578                RoleLoginStatus::NotFound => Err(AdapterError::AuthenticationError(
579                    AuthenticationError::RoleNotFound,
580                )),
581                RoleLoginStatus::NonLogin => Err(AdapterError::AuthenticationError(
582                    AuthenticationError::NonLogin,
583                )),
584                RoleLoginStatus::CanLogin => Ok(()),
585            };
586        let _ = tx.send(result);
587    }
588
589    fn handle_authenticate_verify_sasl_proof(
590        &self,
591        tx: oneshot::Sender<Result<SASLVerifyProofResponse, AdapterError>>,
592        role_name: String,
593        proof: String,
594        auth_message: String,
595        mock_hash: String,
596    ) {
597        let role = self.catalog().try_get_role_by_name(role_name.as_str());
598        let login_status = role_login_status(role);
599        let role_auth = role.and_then(|r| self.catalog().try_get_role_auth_by_id(&r.id));
600        let real_hash = role_auth
601            .as_ref()
602            .and_then(|auth| auth.password_hash.as_ref());
603        let hash_ref = real_hash.map(|s| s.as_str()).unwrap_or(&mock_hash);
604
605        match mz_auth::hash::sasl_verify(hash_ref, &proof, &auth_message) {
606            Ok(verifier) => {
607                // Success only if role exists, allows login, and a real password hash was used.
608                if matches!(login_status, RoleLoginStatus::CanLogin) && real_hash.is_some() {
609                    let _ = tx.send(Ok(SASLVerifyProofResponse { verifier }));
610                } else {
611                    let _ = tx.send(Err(AdapterError::AuthenticationError(match login_status {
612                        RoleLoginStatus::NonLogin => AuthenticationError::NonLogin,
613                        RoleLoginStatus::NotFound => AuthenticationError::RoleNotFound,
614                        RoleLoginStatus::CanLogin => AuthenticationError::InvalidCredentials,
615                    })));
616                }
617            }
618            Err(_) => {
619                let _ = tx.send(Err(AdapterError::AuthenticationError(
620                    AuthenticationError::InvalidCredentials,
621                )));
622            }
623        }
624    }
625
626    #[mz_ore::instrument(level = "debug")]
627    async fn handle_generate_sasl_challenge(
628        &self,
629        tx: oneshot::Sender<Result<SASLChallengeResponse, AdapterError>>,
630        role_name: String,
631        client_nonce: String,
632    ) {
633        let role_auth = self
634            .catalog()
635            .try_get_role_by_name(&role_name)
636            .and_then(|role| self.catalog().try_get_role_auth_by_id(&role.id));
637
638        let nonce = match mz_auth::hash::generate_nonce(&client_nonce) {
639            Ok(n) => n,
640            Err(e) => {
641                let msg = format!(
642                    "failed to generate nonce for client nonce {}: {}",
643                    client_nonce, e
644                );
645                let _ = tx.send(Err(AdapterError::Internal(msg.clone())));
646                soft_panic_or_log!("{msg}");
647                return;
648            }
649        };
650
651        // It's important that the mock_nonce is deterministic per role, otherwise the purpose of
652        // doing mock authentication is defeated. We use a catalog-wide nonce, and combine that
653        // with the role name to get a per-role mock nonce.
654        let send_mock_challenge =
655            |role_name: String,
656             mock_nonce: String,
657             nonce: String,
658             tx: oneshot::Sender<Result<SASLChallengeResponse, AdapterError>>| {
659                let opts = mz_auth::hash::mock_sasl_challenge(
660                    &role_name,
661                    &mock_nonce,
662                    &self.catalog().system_config().scram_iterations(),
663                );
664                let _ = tx.send(Ok(SASLChallengeResponse {
665                    iteration_count: mz_ore::cast::u32_to_usize(opts.iterations.get()),
666                    salt: BASE64_STANDARD.encode(opts.salt),
667                    nonce,
668                }));
669            };
670
671        match role_auth {
672            Some(auth) if auth.password_hash.is_some() => {
673                let hash = auth.password_hash.as_ref().expect("checked above");
674                match mz_auth::hash::scram256_parse_opts(hash) {
675                    Ok(opts) => {
676                        let _ = tx.send(Ok(SASLChallengeResponse {
677                            iteration_count: mz_ore::cast::u32_to_usize(opts.iterations.get()),
678                            salt: BASE64_STANDARD.encode(opts.salt),
679                            nonce,
680                        }));
681                    }
682                    Err(_) => {
683                        send_mock_challenge(
684                            role_name,
685                            self.catalog().state().mock_authentication_nonce(),
686                            nonce,
687                            tx,
688                        );
689                    }
690                }
691            }
692            _ => {
693                send_mock_challenge(
694                    role_name,
695                    self.catalog().state().mock_authentication_nonce(),
696                    nonce,
697                    tx,
698                );
699            }
700        }
701    }
702
703    #[mz_ore::instrument(level = "debug")]
704    async fn handle_authenticate_password(
705        &self,
706        tx: oneshot::Sender<Result<(), AdapterError>>,
707        role_name: String,
708        password: Option<Password>,
709    ) {
710        let Some(password) = password else {
711            // The user did not provide a password.
712            let _ = tx.send(Err(AdapterError::AuthenticationError(
713                AuthenticationError::PasswordRequired,
714            )));
715            return;
716        };
717        let role = self.catalog().try_get_role_by_name(role_name.as_str());
718
719        match role_login_status(role) {
720            RoleLoginStatus::NotFound => {
721                let _ = tx.send(Err(AdapterError::AuthenticationError(
722                    AuthenticationError::RoleNotFound,
723                )));
724                return;
725            }
726            RoleLoginStatus::NonLogin => {
727                let _ = tx.send(Err(AdapterError::AuthenticationError(
728                    AuthenticationError::NonLogin,
729                )));
730                return;
731            }
732            RoleLoginStatus::CanLogin => {}
733        }
734
735        let role_auth = role.and_then(|r| self.catalog().try_get_role_auth_by_id(&r.id));
736
737        if let Some(auth) = role_auth {
738            if let Some(hash) = &auth.password_hash {
739                let hash = hash.clone();
740                task::spawn_blocking(
741                    || "auth-check-hash",
742                    move || {
743                        let _ = match mz_auth::hash::scram256_verify(&password, &hash) {
744                            Ok(_) => tx.send(Ok(())),
745                            Err(_) => tx.send(Err(AdapterError::AuthenticationError(
746                                AuthenticationError::InvalidCredentials,
747                            ))),
748                        };
749                    },
750                );
751                return;
752            }
753        }
754        // Authentication failed due to missing password hash.
755        let _ = tx.send(Err(AdapterError::AuthenticationError(
756            AuthenticationError::InvalidCredentials,
757        )));
758    }
759
760    #[mz_ore::instrument(level = "debug")]
761    async fn handle_startup(
762        &mut self,
763        tx: oneshot::Sender<Result<StartupResponse, AdapterError>>,
764        user: User,
765        conn_id: ConnectionId,
766        secret_key: u32,
767        uuid: uuid::Uuid,
768        client_ip: Option<IpAddr>,
769        application_name: String,
770        notice_tx: mpsc::UnboundedSender<AdapterNotice>,
771    ) {
772        // Early return if successful, otherwise cleanup any possible state.
773        match self.handle_startup_inner(&user, &conn_id, &client_ip).await {
774            Ok((role_id, superuser_attribute, session_defaults)) => {
775                let session_type = metrics::session_type_label_value(&user);
776                self.metrics
777                    .active_sessions
778                    .with_label_values(&[session_type])
779                    .inc();
780                let conn = ConnMeta {
781                    secret_key,
782                    notice_tx,
783                    drop_sinks: BTreeSet::new(),
784                    pending_cluster_alters: BTreeSet::new(),
785                    connected_at: self.now(),
786                    user,
787                    application_name,
788                    uuid,
789                    client_ip,
790                    conn_id: conn_id.clone(),
791                    authenticated_role: role_id,
792                    deferred_lock: None,
793                };
794                let update = self.catalog().state().pack_session_update(&conn, Diff::ONE);
795                let update = self.catalog().state().resolve_builtin_table_update(update);
796                self.begin_session_for_statement_logging(&conn);
797                self.active_conns.insert(conn_id.clone(), conn);
798
799                // Note: Do NOT await the notify here, we pass this back to
800                // whatever requested the startup to prevent blocking startup
801                // and the Coordinator on a builtin table update.
802                let updates = vec![update];
803                // It's not a hard error if our list is missing a builtin table, but we want to
804                // make sure these two things stay in-sync.
805                if mz_ore::assert::soft_assertions_enabled() {
806                    let required_tables: BTreeSet<_> = super::appends::REQUIRED_BUILTIN_TABLES
807                        .iter()
808                        .map(|table| self.catalog().resolve_builtin_table(*table))
809                        .collect();
810                    let updates_tracked = updates
811                        .iter()
812                        .all(|update| required_tables.contains(&update.id));
813                    let all_mz_internal = super::appends::REQUIRED_BUILTIN_TABLES
814                        .iter()
815                        .all(|table| table.schema == MZ_INTERNAL_SCHEMA);
816                    mz_ore::soft_assert_or_log!(
817                        updates_tracked,
818                        "not tracking all required builtin table updates!"
819                    );
820                    // TODO(parkmycar): When checking if a query depends on these builtin table
821                    // writes we do not check the transitive dependencies of the query, because
822                    // we don't support creating views on mz_internal objects. If one of these
823                    // tables is promoted out of mz_internal then we'll need to add this check.
824                    mz_ore::soft_assert_or_log!(
825                        all_mz_internal,
826                        "not all builtin tables are in mz_internal! need to check transitive depends",
827                    )
828                }
829                let notify = self.builtin_table_update().background(updates);
830
831                let catalog = self.owned_catalog();
832                let build_info_human_version =
833                    catalog.state().config().build_info.human_version(None);
834
835                let statement_logging_frontend = self
836                    .statement_logging
837                    .create_frontend(build_info_human_version);
838
839                let resp = Ok(StartupResponse {
840                    role_id,
841                    write_notify: notify,
842                    session_defaults,
843                    catalog,
844                    storage_collections: Arc::clone(&self.controller.storage_collections),
845                    transient_id_gen: Arc::clone(&self.transient_id_gen),
846                    optimizer_metrics: self.optimizer_metrics.clone(),
847                    persist_client: self.persist_client.clone(),
848                    statement_logging_frontend,
849                    superuser_attribute,
850                });
851                if tx.send(resp).is_err() {
852                    // Failed to send to adapter, but everything is setup so we can terminate
853                    // normally.
854                    self.handle_terminate(conn_id).await;
855                }
856            }
857            Err(e) => {
858                // Error during startup or sending to adapter. A user may have been created and
859                // it can stay; no need to delete it.
860                // Note: Temporary schemas are created lazily, so there's nothing to clean up here.
861
862                // Communicate the error back to the client. No need to
863                // handle failures to send the error back; we've already
864                // cleaned up all necessary state.
865                let _ = tx.send(Err(e));
866            }
867        }
868    }
869
870    // Failible startup work that needs to be cleaned up on error.
871    async fn handle_startup_inner(
872        &mut self,
873        user: &User,
874        _conn_id: &ConnectionId,
875        client_ip: &Option<IpAddr>,
876    ) -> Result<(RoleId, SuperuserAttribute, BTreeMap<String, OwnedVarInput>), AdapterError> {
877        if self.catalog().try_get_role_by_name(&user.name).is_none() {
878            // If the user has made it to this point, that means they have been fully authenticated.
879            // This includes preventing any user, except a pre-defined set of system users, from
880            // connecting to an internal port. Therefore it's ok to always create a new role for the
881            // user.
882            let mut attributes = RoleAttributesRaw::new();
883            // When auto-provisioning, we store the authenticator that was used to provision the role.
884            attributes.auto_provision_source = match user.authenticator_kind {
885                Some(AuthenticatorKind::Oidc) => Some(AutoProvisionSource::Oidc),
886                Some(AuthenticatorKind::Frontegg) => Some(AutoProvisionSource::Frontegg),
887                Some(AuthenticatorKind::None) => Some(AutoProvisionSource::None),
888                _ => {
889                    warn!(
890                        "auto-provisioning role with unexpected authenticator kind: {:?}",
891                        user.authenticator_kind
892                    );
893                    None
894                }
895            };
896
897            // Auto-provision roles with the LOGIN attribute to distinguish
898            // them as users.
899            attributes.login = Some(true);
900
901            let plan = CreateRolePlan {
902                name: user.name.to_string(),
903                attributes,
904            };
905            self.sequence_create_role_for_startup(plan).await?;
906        }
907        let role = self
908            .catalog()
909            .try_get_role_by_name(&user.name)
910            .expect("created above");
911        let role_id = role.id;
912
913        let superuser_attribute = role.attributes.superuser;
914
915        if role_id.is_user() && !ALLOW_USER_SESSIONS.get(self.catalog().system_config().dyncfgs()) {
916            return Err(AdapterError::UserSessionsDisallowed);
917        }
918
919        // Initialize the default session variables for this role.
920        let mut session_defaults = BTreeMap::new();
921        let system_config = self.catalog().state().system_config();
922
923        // Override the session with any system defaults.
924        session_defaults.extend(
925            system_config
926                .iter_session()
927                .map(|v| (v.name().to_string(), OwnedVarInput::Flat(v.value()))),
928        );
929        // Special case.
930        let statement_logging_default = system_config
931            .statement_logging_default_sample_rate()
932            .format();
933        session_defaults.insert(
934            STATEMENT_LOGGING_SAMPLE_RATE.name().to_string(),
935            OwnedVarInput::Flat(statement_logging_default),
936        );
937        // Override system defaults with role defaults.
938        session_defaults.extend(
939            self.catalog()
940                .get_role(&role_id)
941                .vars()
942                .map(|(name, val)| (name.to_string(), val.clone())),
943        );
944
945        // Validate network policies for external users. Internal users can only connect on the
946        // internal interfaces (internal HTTP/ pgwire). It is up to the person deploying the system
947        // to ensure these internal interfaces are well secured.
948        //
949        // HACKY(parkmycar): We don't have a fully formed session yet for this role, but we want
950        // the default network policy for this role, so we read directly out of what the session
951        // will get initialized with.
952        if !user.is_internal() {
953            let network_policy_name = session_defaults
954                .get(NETWORK_POLICY.name())
955                .and_then(|value| match value {
956                    OwnedVarInput::Flat(name) => Some(name.clone()),
957                    OwnedVarInput::SqlSet(names) => {
958                        tracing::error!(?names, "found multiple network policies");
959                        None
960                    }
961                })
962                .unwrap_or_else(|| system_config.default_network_policy_name());
963            let maybe_network_policy = self
964                .catalog()
965                .get_network_policy_by_name(&network_policy_name);
966
967            let Some(network_policy) = maybe_network_policy else {
968                // We should prevent dropping the default network policy, or setting the policy
969                // to something that doesn't exist, so complain loudly if this occurs.
970                tracing::error!(
971                    network_policy_name,
972                    "default network policy does not exist. All user traffic will be blocked"
973                );
974                let reason = match client_ip {
975                    Some(ip) => super::NetworkPolicyError::AddressDenied(ip.clone()),
976                    None => super::NetworkPolicyError::MissingIp,
977                };
978                return Err(AdapterError::NetworkPolicyDenied(reason));
979            };
980
981            if let Some(ip) = client_ip {
982                match validate_ip_with_policy_rules(ip, &network_policy.rules) {
983                    Ok(_) => {}
984                    Err(e) => return Err(AdapterError::NetworkPolicyDenied(e)),
985                }
986            } else {
987                // Only temporary and internal representation of a session
988                // should be missing a client_ip. These sessions should not be
989                // making requests or going through handle_startup.
990                return Err(AdapterError::NetworkPolicyDenied(
991                    super::NetworkPolicyError::MissingIp,
992                ));
993            }
994        }
995
996        // Temporary schemas are now created lazily when the first temporary object is created,
997        // rather than eagerly on connection startup. This avoids expensive catalog_mut() calls
998        // for the common case where connections never create temporary objects.
999
1000        Ok((
1001            role_id,
1002            SuperuserAttribute(superuser_attribute),
1003            session_defaults,
1004        ))
1005    }
1006
1007    /// Handles an execute command.
1008    #[instrument(name = "coord::handle_execute", fields(session = session.uuid().to_string()))]
1009    pub(crate) async fn handle_execute(
1010        &mut self,
1011        portal_name: String,
1012        mut session: Session,
1013        tx: ClientTransmitter<ExecuteResponse>,
1014        // If this command was part of another execute command
1015        // (for example, executing a `FETCH` statement causes an execute to be
1016        //  issued for the cursor it references),
1017        // then `outer_context` should be `Some`.
1018        // This instructs the coordinator that the
1019        // outer execute should be considered finished once the inner one is.
1020        outer_context: Option<ExecuteContextGuard>,
1021    ) {
1022        if session.vars().emit_trace_id_notice() {
1023            let span_context = tracing::Span::current()
1024                .context()
1025                .span()
1026                .span_context()
1027                .clone();
1028            if span_context.is_valid() {
1029                session.add_notice(AdapterNotice::QueryTrace {
1030                    trace_id: span_context.trace_id(),
1031                });
1032            }
1033        }
1034
1035        if let Err(err) = Self::verify_portal(self.catalog(), &mut session, &portal_name) {
1036            // If statement logging hasn't started yet, we don't need
1037            // to add any "end" event, so just make up a no-op
1038            // `ExecuteContextExtra` here, via `Default::default`.
1039            //
1040            // It's a bit unfortunate because the edge case of failed
1041            // portal verifications won't show up in statement
1042            // logging, but there seems to be nothing else we can do,
1043            // because we need access to the portal to begin logging.
1044            //
1045            // Another option would be to log a begin and end event, but just fill in NULLs
1046            // for everything we get from the portal (prepared statement id, params).
1047            let extra = outer_context.unwrap_or_else(Default::default);
1048            let ctx = ExecuteContext::from_parts(tx, self.internal_cmd_tx.clone(), session, extra);
1049            return ctx.retire(Err(err));
1050        }
1051
1052        // The reference to `portal` can't outlive `session`, which we
1053        // use to construct the context, so scope the reference to this block where we
1054        // get everything we need from the portal for later.
1055        let (stmt, ctx, params) = {
1056            let portal = session
1057                .get_portal_unverified(&portal_name)
1058                .expect("known to exist");
1059            let params = portal.parameters.clone();
1060            let stmt = portal.stmt.clone();
1061            let logging = Arc::clone(&portal.logging);
1062            let lifecycle_timestamps = portal.lifecycle_timestamps.clone();
1063
1064            let extra = if let Some(extra) = outer_context {
1065                // We are executing in the context of another SQL statement, so we don't
1066                // want to begin statement logging anew. The context of the actual statement
1067                // being executed is the one that should be retired once this finishes.
1068                extra
1069            } else {
1070                // This is a new statement, log it and return the context
1071                let maybe_uuid = self.begin_statement_execution(
1072                    &mut session,
1073                    &params,
1074                    &logging,
1075                    lifecycle_timestamps,
1076                );
1077
1078                ExecuteContextGuard::new(maybe_uuid, self.internal_cmd_tx.clone())
1079            };
1080            let ctx = ExecuteContext::from_parts(tx, self.internal_cmd_tx.clone(), session, extra);
1081            (stmt, ctx, params)
1082        };
1083
1084        let stmt = match stmt {
1085            Some(stmt) => stmt,
1086            None => return ctx.retire(Ok(ExecuteResponse::EmptyQuery)),
1087        };
1088
1089        let session_type = metrics::session_type_label_value(ctx.session().user());
1090        let stmt_type = metrics::statement_type_label_value(&stmt);
1091        self.metrics
1092            .query_total
1093            .with_label_values(&[session_type, stmt_type])
1094            .inc();
1095        match &*stmt {
1096            Statement::Subscribe(SubscribeStatement { output, .. })
1097            | Statement::Copy(CopyStatement {
1098                relation: CopyRelation::Subscribe(SubscribeStatement { output, .. }),
1099                ..
1100            }) => {
1101                self.metrics
1102                    .subscribe_outputs
1103                    .with_label_values(&[
1104                        session_type,
1105                        metrics::subscribe_output_label_value(output),
1106                    ])
1107                    .inc();
1108            }
1109            _ => {}
1110        }
1111
1112        self.handle_execute_inner(stmt, params, ctx).await
1113    }
1114
1115    #[instrument(name = "coord::handle_execute_inner", fields(stmt = stmt.to_ast_string_redacted()))]
1116    pub(crate) async fn handle_execute_inner(
1117        &mut self,
1118        stmt: Arc<Statement<Raw>>,
1119        params: Params,
1120        mut ctx: ExecuteContext,
1121    ) {
1122        // This comment describes the various ways DDL can execute (the ordered operations: name
1123        // resolve, purify, plan, sequence), all of which are managed by this function. DDL has
1124        // three notable properties that all partially interact.
1125        //
1126        // 1. Most DDL statements (and a few others) support single-statement transaction delayed
1127        //    execution. This occurs when a session executes `BEGIN`, a single DDL, then `COMMIT`.
1128        //    We announce success of the single DDL when it is executed, but do not attempt to plan
1129        //    or sequence it until `COMMIT`, which is able to error if needed while sequencing the
1130        //    DDL (this behavior is Postgres-compatible). The purpose of this is because some
1131        //    drivers or tools wrap all statements in `BEGIN` and `COMMIT` and we would like them to
1132        //    work. When the single DDL is announced as successful we also put the session's
1133        //    transaction ops into `SingleStatement` which will produce an error if any other
1134        //    statement is run in the transaction except `COMMIT`. Additionally, this will cause
1135        //    `handle_execute_inner` to stop further processing (no planning, etc.) of the
1136        //    statement.
1137        // 2. A few other DDL statements (`ALTER .. RENAME/SWAP`) enter the `DDL` ops which allows
1138        //    any number of only these DDL statements to be executed in a transaction. During
1139        //    sequencing we run an incremental catalog dry run against in-memory transaction state
1140        //    and store the resulting `CatalogState` in `TransactionOps::DDL`, but nothing is yet
1141        //    committed to the durable catalog. At `COMMIT`, all accumulated ops are applied in one
1142        //    catalog transaction. The purpose of this is to allow multiple, atomic renames in the
1143        //    same transaction.
1144        // 3. Some DDLs do off-thread work during purification or sequencing that is expensive or
1145        //    makes network calls (interfacing with secrets, optimization of views/indexes, source
1146        //    purification). These must guarantee correctness when they return to the main
1147        //    coordinator thread because the catalog state could have changed while they were doing
1148        //    the off-thread work. Previously we would use `PlanValidity::Checks` to specify a bunch
1149        //    of IDs that we needed to exist. We discovered the way we were doing that was not
1150        //    always correct. Instead of attempting to get that completely right, we have opted to
1151        //    serialize DDL. Getting this right is difficult because catalog changes can affect name
1152        //    resolution, planning, sequencing, and optimization. Correctly writing logic that is
1153        //    aware of all possible catalog changes that would affect any of those parts is not
1154        //    something our current code has been designed to be helpful at. Even if a DDL statement
1155        //    is doing off-thread work, another DDL must not yet execute at all. Executing these
1156        //    serially will guarantee that no off-thread work has affected the state of the catalog.
1157        //    This is done by adding a VecDeque of deferred statements and a lock to the
1158        //    Coordinator. When a DDL is run in `handle_execute_inner` (after applying whatever
1159        //    transaction ops are needed to the session as described above), it attempts to own the
1160        //    lock (a tokio Mutex). If acquired, it stashes the lock in the connection`s `ConnMeta`
1161        //    struct in `active_conns` and proceeds. The lock is dropped at transaction end in
1162        //    `clear_transaction` and a message sent to the Coordinator to execute the next queued
1163        //    DDL. If the lock could not be acquired, the DDL is put into the VecDeque where it
1164        //    awaits dequeuing caused by the lock being released.
1165
1166        // Verify that this statement type can be executed in the current
1167        // transaction state.
1168        match ctx.session().transaction() {
1169            // By this point we should be in a running transaction.
1170            TransactionStatus::Default => unreachable!(),
1171
1172            // Failed transactions have already been checked in pgwire for a safe statement
1173            // (COMMIT, ROLLBACK, etc.) and can proceed.
1174            TransactionStatus::Failed(_) => {}
1175
1176            // Started is a deceptive name, and means different things depending on which
1177            // protocol was used. It's either exactly one statement (known because this
1178            // is the simple protocol and the parser parsed the entire string, and it had
1179            // one statement). Or from the extended protocol, it means *some* query is
1180            // being executed, but there might be others after it before the Sync (commit)
1181            // message. Postgres handles this by teaching Started to eagerly commit certain
1182            // statements that can't be run in a transaction block.
1183            TransactionStatus::Started(_) => {
1184                if let Statement::Declare(_) = &*stmt {
1185                    // Declare is an exception. Although it's not against any spec to execute
1186                    // it, it will always result in nothing happening, since all portals will be
1187                    // immediately closed. Users don't know this detail, so this error helps them
1188                    // understand what's going wrong. Postgres does this too.
1189                    return ctx.retire(Err(AdapterError::OperationRequiresTransaction(
1190                        "DECLARE CURSOR".into(),
1191                    )));
1192                }
1193            }
1194
1195            // Implicit or explicit transactions.
1196            //
1197            // Implicit transactions happen when a multi-statement query is executed
1198            // (a "simple query"). However if a "BEGIN" appears somewhere in there,
1199            // then the existing implicit transaction will be upgraded to an explicit
1200            // transaction. Thus, we should not separate what implicit and explicit
1201            // transactions can do unless there's some additional checking to make sure
1202            // something disallowed in explicit transactions did not previously take place
1203            // in the implicit portion.
1204            TransactionStatus::InTransactionImplicit(_) | TransactionStatus::InTransaction(_) => {
1205                match &*stmt {
1206                    // Statements that are safe in a transaction. We still need to verify that we
1207                    // don't interleave reads and writes since we can't perform those serializably.
1208                    Statement::Close(_)
1209                    | Statement::Commit(_)
1210                    | Statement::Copy(_)
1211                    | Statement::Deallocate(_)
1212                    | Statement::Declare(_)
1213                    | Statement::Discard(_)
1214                    | Statement::Execute(_)
1215                    | Statement::ExplainPlan(_)
1216                    | Statement::ExplainPushdown(_)
1217                    | Statement::ExplainAnalyzeObject(_)
1218                    | Statement::ExplainAnalyzeCluster(_)
1219                    | Statement::ExplainTimestamp(_)
1220                    | Statement::ExplainSinkSchema(_)
1221                    | Statement::Fetch(_)
1222                    | Statement::Prepare(_)
1223                    | Statement::Rollback(_)
1224                    | Statement::Select(_)
1225                    | Statement::SetTransaction(_)
1226                    | Statement::Show(_)
1227                    | Statement::SetVariable(_)
1228                    | Statement::ResetVariable(_)
1229                    | Statement::StartTransaction(_)
1230                    | Statement::Subscribe(_)
1231                    | Statement::Raise(_) => {
1232                        // Always safe.
1233                    }
1234
1235                    Statement::Insert(InsertStatement {
1236                        source, returning, ..
1237                    }) if returning.is_empty() && ConstantVisitor::insert_source(source) => {
1238                        // Inserting from constant values statements that do not need to execute on
1239                        // any cluster (no RETURNING) is always safe.
1240                    }
1241
1242                    // These statements must be kept in-sync with `must_serialize_ddl()`.
1243                    Statement::AlterObjectRename(_)
1244                    | Statement::AlterObjectSwap(_)
1245                    | Statement::CreateTableFromSource(_)
1246                    | Statement::CreateSource(_) => {
1247                        let state = self.catalog().for_session(ctx.session()).state().clone();
1248                        let revision = self.catalog().transient_revision();
1249
1250                        // Initialize our transaction with a set of empty ops, or return an error
1251                        // if we can't run a DDL transaction
1252                        let txn_status = ctx.session_mut().transaction_mut();
1253                        if let Err(err) = txn_status.add_ops(TransactionOps::DDL {
1254                            ops: vec![],
1255                            state,
1256                            revision,
1257                            side_effects: vec![],
1258                            snapshot: None,
1259                        }) {
1260                            return ctx.retire(Err(err));
1261                        }
1262                    }
1263
1264                    // Statements below must by run singly (in Started).
1265                    Statement::AlterCluster(_)
1266                    | Statement::AlterConnection(_)
1267                    | Statement::AlterDefaultPrivileges(_)
1268                    | Statement::AlterIndex(_)
1269                    | Statement::AlterMaterializedViewApplyReplacement(_)
1270                    | Statement::AlterSetCluster(_)
1271                    | Statement::AlterOwner(_)
1272                    | Statement::AlterRetainHistory(_)
1273                    | Statement::AlterRole(_)
1274                    | Statement::AlterSecret(_)
1275                    | Statement::AlterSink(_)
1276                    | Statement::AlterSource(_)
1277                    | Statement::AlterSystemReset(_)
1278                    | Statement::AlterSystemResetAll(_)
1279                    | Statement::AlterSystemSet(_)
1280                    | Statement::AlterTableAddColumn(_)
1281                    | Statement::AlterNetworkPolicy(_)
1282                    | Statement::CreateCluster(_)
1283                    | Statement::CreateClusterReplica(_)
1284                    | Statement::CreateConnection(_)
1285                    | Statement::CreateDatabase(_)
1286                    | Statement::CreateIndex(_)
1287                    | Statement::CreateMaterializedView(_)
1288                    | Statement::CreateContinualTask(_)
1289                    | Statement::CreateRole(_)
1290                    | Statement::CreateSchema(_)
1291                    | Statement::CreateSecret(_)
1292                    | Statement::CreateSink(_)
1293                    | Statement::CreateSubsource(_)
1294                    | Statement::CreateTable(_)
1295                    | Statement::CreateType(_)
1296                    | Statement::CreateView(_)
1297                    | Statement::CreateWebhookSource(_)
1298                    | Statement::CreateNetworkPolicy(_)
1299                    | Statement::Delete(_)
1300                    | Statement::DropObjects(_)
1301                    | Statement::DropOwned(_)
1302                    | Statement::GrantPrivileges(_)
1303                    | Statement::GrantRole(_)
1304                    | Statement::Insert(_)
1305                    | Statement::ReassignOwned(_)
1306                    | Statement::RevokePrivileges(_)
1307                    | Statement::RevokeRole(_)
1308                    | Statement::Update(_)
1309                    | Statement::ValidateConnection(_)
1310                    | Statement::Comment(_) => {
1311                        let txn_status = ctx.session_mut().transaction_mut();
1312
1313                        // If we're not in an implicit transaction and we could generate exactly one
1314                        // valid ExecuteResponse, we can delay execution until commit.
1315                        if !txn_status.is_implicit() {
1316                            // Statements whose tag is trivial (known only from an unexecuted statement) can
1317                            // be run in a special single-statement explicit mode. In this mode (`BEGIN;
1318                            // <stmt>; COMMIT`), we generate the expected tag from a successful <stmt>, but
1319                            // delay execution until `COMMIT`.
1320                            if let Ok(resp) = ExecuteResponse::try_from(&*stmt) {
1321                                if let Err(err) = txn_status
1322                                    .add_ops(TransactionOps::SingleStatement { stmt, params })
1323                                {
1324                                    ctx.retire(Err(err));
1325                                    return;
1326                                }
1327                                ctx.retire(Ok(resp));
1328                                return;
1329                            }
1330                        }
1331
1332                        return ctx.retire(Err(AdapterError::OperationProhibitsTransaction(
1333                            stmt.to_string(),
1334                        )));
1335                    }
1336                }
1337            }
1338        }
1339
1340        // DDLs must be planned and sequenced serially. We do not rely on PlanValidity checking
1341        // various IDs because we have incorrectly done that in the past. Attempt to acquire the
1342        // ddl lock. The lock is stashed in the ConnMeta which is dropped at transaction end. If
1343        // acquired, proceed with sequencing. If not, enqueue and return. This logic assumes that
1344        // Coordinator::clear_transaction is correctly called when session transactions are ended
1345        // because that function will release the held lock from active_conns.
1346        if Self::must_serialize_ddl(&stmt, &ctx) {
1347            if let Ok(guard) = self.serialized_ddl.try_lock_owned() {
1348                let prev = self
1349                    .active_conns
1350                    .get_mut(ctx.session().conn_id())
1351                    .expect("connection must exist")
1352                    .deferred_lock
1353                    .replace(guard);
1354                assert!(
1355                    prev.is_none(),
1356                    "connections should have at most one lock guard"
1357                );
1358            } else {
1359                if self
1360                    .active_conns
1361                    .get(ctx.session().conn_id())
1362                    .expect("connection must exist")
1363                    .deferred_lock
1364                    .is_some()
1365                {
1366                    // This session *already* has the lock, and incorrectly tried to execute another
1367                    // DDL while still holding the lock, violating the assumption documented above.
1368                    // This is an internal error, probably in some AdapterClient user (pgwire or
1369                    // http). Because the session is now in some unexpected state, return an error
1370                    // which should cause the AdapterClient user to fail the transaction.
1371                    // (Terminating the connection is maybe what we would prefer to do, but is not
1372                    // currently a thing we can do from the coordinator: calling handle_terminate
1373                    // cleans up Coordinator state for the session but doesn't inform the
1374                    // AdapterClient that the session should terminate.)
1375                    soft_panic_or_log!(
1376                        "session {} attempted to get ddl lock while already owning it",
1377                        ctx.session().conn_id()
1378                    );
1379                    ctx.retire(Err(AdapterError::Internal(
1380                        "session attempted to get ddl lock while already owning it".to_string(),
1381                    )));
1382                    return;
1383                }
1384                self.serialized_ddl.push_back(DeferredPlanStatement {
1385                    ctx,
1386                    ps: PlanStatement::Statement { stmt, params },
1387                });
1388                return;
1389            }
1390        }
1391
1392        let catalog = self.catalog();
1393        let catalog = catalog.for_session(ctx.session());
1394        let original_stmt = Arc::clone(&stmt);
1395        // `resolved_ids` should be derivable from `stmt`. If `stmt` is transformed to remove/add
1396        // IDs, then `resolved_ids` should be updated to also remove/add those IDs.
1397        let (stmt, mut resolved_ids) = match mz_sql::names::resolve(&catalog, (*stmt).clone()) {
1398            Ok(resolved) => resolved,
1399            Err(e) => return ctx.retire(Err(e.into())),
1400        };
1401        // N.B. The catalog can change during purification so we must validate that the dependencies still exist after
1402        // purification.  This should be done back on the main thread.
1403        // We do the validation:
1404        //   - In the handler for `Message::PurifiedStatementReady`, before we handle the purified statement.
1405        // If we add special handling for more types of `Statement`s, we'll need to ensure similar verification
1406        // occurs.
1407        let (stmt, resolved_ids) = match stmt {
1408            // Various statements must be purified off the main coordinator thread of control.
1409            stmt if Self::must_spawn_purification(&stmt) => {
1410                let internal_cmd_tx = self.internal_cmd_tx.clone();
1411                let conn_id = ctx.session().conn_id().clone();
1412                let catalog = self.owned_catalog();
1413                let now = self.now();
1414                let otel_ctx = OpenTelemetryContext::obtain();
1415                let current_storage_configuration = self.controller.storage.config().clone();
1416                task::spawn(|| format!("purify:{conn_id}"), async move {
1417                    let transient_revision = catalog.transient_revision();
1418                    let catalog = catalog.for_session(ctx.session());
1419
1420                    // Checks if the session is authorized to purify a statement. Usually
1421                    // authorization is checked after planning, however purification happens before
1422                    // planning, which may require the use of some connections and secrets.
1423                    if let Err(e) = rbac::check_usage(
1424                        &catalog,
1425                        ctx.session(),
1426                        &resolved_ids,
1427                        &CREATE_ITEM_USAGE,
1428                    ) {
1429                        return ctx.retire(Err(e.into()));
1430                    }
1431
1432                    let (result, cluster_id) = mz_sql::pure::purify_statement(
1433                        catalog,
1434                        now,
1435                        stmt,
1436                        &current_storage_configuration,
1437                    )
1438                    .await;
1439                    let result = result.map_err(|e| e.into());
1440                    let dependency_ids = resolved_ids.items().copied().collect();
1441                    let plan_validity = PlanValidity::new(
1442                        transient_revision,
1443                        dependency_ids,
1444                        cluster_id,
1445                        None,
1446                        ctx.session().role_metadata().clone(),
1447                    );
1448                    // It is not an error for purification to complete after `internal_cmd_rx` is dropped.
1449                    let result = internal_cmd_tx.send(Message::PurifiedStatementReady(
1450                        PurifiedStatementReady {
1451                            ctx,
1452                            result,
1453                            params,
1454                            plan_validity,
1455                            original_stmt,
1456                            otel_ctx,
1457                        },
1458                    ));
1459                    if let Err(e) = result {
1460                        tracing::warn!("internal_cmd_rx dropped before we could send: {:?}", e);
1461                    }
1462                });
1463                return;
1464            }
1465
1466            // `CREATE SUBSOURCE` statements are disallowed for users and are only generated
1467            // automatically as part of purification
1468            Statement::CreateSubsource(_) => {
1469                ctx.retire(Err(AdapterError::Unsupported(
1470                    "CREATE SUBSOURCE statements",
1471                )));
1472                return;
1473            }
1474
1475            Statement::CreateMaterializedView(mut cmvs) => {
1476                // `CREATE MATERIALIZED VIEW ... AS OF ...` syntax is disallowed for users and is
1477                // only used for storing initial frontiers in the catalog.
1478                if cmvs.as_of.is_some() {
1479                    return ctx.retire(Err(AdapterError::Unsupported(
1480                        "CREATE MATERIALIZED VIEW ... AS OF statements",
1481                    )));
1482                }
1483
1484                let mz_now = match self
1485                    .resolve_mz_now_for_create_materialized_view(
1486                        &cmvs,
1487                        &resolved_ids,
1488                        ctx.session_mut(),
1489                        true,
1490                    )
1491                    .await
1492                {
1493                    Ok(mz_now) => mz_now,
1494                    Err(e) => return ctx.retire(Err(e)),
1495                };
1496
1497                let catalog = self.catalog().for_session(ctx.session());
1498
1499                purify_create_materialized_view_options(
1500                    catalog,
1501                    mz_now,
1502                    &mut cmvs,
1503                    &mut resolved_ids,
1504                );
1505
1506                let purified_stmt =
1507                    Statement::CreateMaterializedView(CreateMaterializedViewStatement::<Aug> {
1508                        if_exists: cmvs.if_exists,
1509                        name: cmvs.name,
1510                        columns: cmvs.columns,
1511                        replacement_for: cmvs.replacement_for,
1512                        in_cluster: cmvs.in_cluster,
1513                        in_cluster_replica: cmvs.in_cluster_replica,
1514                        query: cmvs.query,
1515                        with_options: cmvs.with_options,
1516                        as_of: None,
1517                    });
1518
1519                // (Purifying CreateMaterializedView doesn't happen async, so no need to send
1520                // `Message::PurifiedStatementReady` here.)
1521                (purified_stmt, resolved_ids)
1522            }
1523
1524            Statement::ExplainPlan(ExplainPlanStatement {
1525                stage,
1526                with_options,
1527                format,
1528                explainee: Explainee::CreateMaterializedView(box_cmvs, broken),
1529            }) => {
1530                let mut cmvs = *box_cmvs;
1531                let mz_now = match self
1532                    .resolve_mz_now_for_create_materialized_view(
1533                        &cmvs,
1534                        &resolved_ids,
1535                        ctx.session_mut(),
1536                        false,
1537                    )
1538                    .await
1539                {
1540                    Ok(mz_now) => mz_now,
1541                    Err(e) => return ctx.retire(Err(e)),
1542                };
1543
1544                let catalog = self.catalog().for_session(ctx.session());
1545
1546                purify_create_materialized_view_options(
1547                    catalog,
1548                    mz_now,
1549                    &mut cmvs,
1550                    &mut resolved_ids,
1551                );
1552
1553                let purified_stmt = Statement::ExplainPlan(ExplainPlanStatement {
1554                    stage,
1555                    with_options,
1556                    format,
1557                    explainee: Explainee::CreateMaterializedView(Box::new(cmvs), broken),
1558                });
1559
1560                (purified_stmt, resolved_ids)
1561            }
1562
1563            // All other statements are handled immediately.
1564            _ => (stmt, resolved_ids),
1565        };
1566
1567        match self.plan_statement(ctx.session(), stmt, &params, &resolved_ids) {
1568            Ok(plan) => self.sequence_plan(ctx, plan, resolved_ids).await,
1569            Err(e) => ctx.retire(Err(e)),
1570        }
1571    }
1572
1573    /// Whether the statement must be serialized and is DDL.
1574    fn must_serialize_ddl(stmt: &Statement<Raw>, ctx: &ExecuteContext) -> bool {
1575        // Non-DDL is not serialized here.
1576        if !StatementClassification::from(&*stmt).is_ddl() {
1577            return false;
1578        }
1579        // Off-thread, pre-planning purification can perform arbitrarily slow network calls so must
1580        // not be serialized. These all use PlanValidity for their checking, and we must ensure
1581        // those checks are sufficient.
1582        if Self::must_spawn_purification(stmt) {
1583            return false;
1584        }
1585
1586        // Statements that support multiple DDLs in a single transaction aren't serialized here.
1587        // Their operations are serialized when applied to the catalog, guaranteeing that any
1588        // off-thread DDLs concurrent with a multiple DDL transaction will have a serial order.
1589        if ctx.session.transaction().is_ddl() {
1590            return false;
1591        }
1592
1593        // Some DDL is exempt. It is not great that we are matching on Statements here because
1594        // different plans can be produced from the same top-level statement type (i.e., `ALTER
1595        // CONNECTION ROTATE KEYS`). But the whole point of this is to prevent things from being
1596        // planned in the first place, so we accept the abstraction leak.
1597        match stmt {
1598            // Secrets have a small and understood set of dependencies, and their off-thread work
1599            // interacts with k8s.
1600            Statement::AlterSecret(_) => false,
1601            Statement::CreateSecret(_) => false,
1602            Statement::AlterConnection(AlterConnectionStatement { actions, .. })
1603                if actions
1604                    .iter()
1605                    .all(|action| matches!(action, AlterConnectionAction::RotateKeys)) =>
1606            {
1607                false
1608            }
1609
1610            // The off-thread work that altering a cluster may do (waiting for replicas to spin-up),
1611            // does not affect its catalog names or ids and so is safe to not serialize. This could
1612            // change the set of replicas that exist. For queries that name replicas or use the
1613            // current_replica session var, the `replica_id` field of `PlanValidity` serves to
1614            // ensure that those replicas exist during the query finish stage. Additionally, that
1615            // work can take hours (configured by the user), so would also be a bad experience for
1616            // users.
1617            Statement::AlterCluster(_) => false,
1618
1619            // `ALTER SINK SET FROM` waits for the old relation to make enough progress for a clean
1620            // cutover. If the old collection is stalled, it may block forever. Checks in
1621            // sequencing ensure that the operation fails if any one of these happens concurrently:
1622            //   * the sink is dropped
1623            //   * the new source relation is dropped
1624            //   * another `ALTER SINK` for the same sink is applied first
1625            Statement::AlterSink(stmt)
1626                if matches!(stmt.action, AlterSinkAction::ChangeRelation(_)) =>
1627            {
1628                false
1629            }
1630
1631            // `ALTER MATERIALIZED VIEW ... APPLY REPLACEMENT` waits for the target MV to make
1632            // enough progress for a clean cutover. If the target MV is stalled, it may block
1633            // forever. Checks in sequencing ensure the operation fails if any of these happens
1634            // concurrently:
1635            //   * the target MV is dropped
1636            //   * the replacement MV is dropped
1637            Statement::AlterMaterializedViewApplyReplacement(_) => false,
1638
1639            // Everything else must be serialized.
1640            _ => true,
1641        }
1642    }
1643
1644    /// Whether the statement must be purified off of the Coordinator thread.
1645    fn must_spawn_purification<A: AstInfo>(stmt: &Statement<A>) -> bool {
1646        // `CREATE` and `ALTER` `SOURCE` and `SINK` statements must be purified off the main
1647        // coordinator thread.
1648        if !matches!(
1649            stmt,
1650            Statement::CreateSource(_)
1651                | Statement::AlterSource(_)
1652                | Statement::CreateSink(_)
1653                | Statement::CreateTableFromSource(_)
1654        ) {
1655            return false;
1656        }
1657
1658        // However `ALTER SOURCE RETAIN HISTORY` should be excluded from off-thread purification.
1659        if let Statement::AlterSource(stmt) = stmt {
1660            let names: Vec<CreateSourceOptionName> = match &stmt.action {
1661                AlterSourceAction::SetOptions(options) => {
1662                    options.iter().map(|o| o.name.clone()).collect()
1663                }
1664                AlterSourceAction::ResetOptions(names) => names.clone(),
1665                _ => vec![],
1666            };
1667            if !names.is_empty()
1668                && names
1669                    .iter()
1670                    .all(|n| matches!(n, CreateSourceOptionName::RetainHistory))
1671            {
1672                return false;
1673            }
1674        }
1675
1676        true
1677    }
1678
1679    /// Chooses a timestamp for `mz_now()`, if `mz_now()` occurs in a REFRESH option of the
1680    /// materialized view. Additionally, if `acquire_read_holds` is true and the MV has any REFRESH
1681    /// option, this function grabs read holds at the earliest possible time on input collections
1682    /// that might be involved in the MV.
1683    ///
1684    /// Note that this is NOT what handles `mz_now()` in the query part of the MV. (handles it only
1685    /// in `with_options`).
1686    ///
1687    /// (Note that the chosen timestamp won't be the same timestamp as the system table inserts,
1688    /// unfortunately.)
1689    async fn resolve_mz_now_for_create_materialized_view(
1690        &mut self,
1691        cmvs: &CreateMaterializedViewStatement<Aug>,
1692        resolved_ids: &ResolvedIds,
1693        session: &Session,
1694        acquire_read_holds: bool,
1695    ) -> Result<Option<Timestamp>, AdapterError> {
1696        if cmvs
1697            .with_options
1698            .iter()
1699            .any(|wo| matches!(wo.value, Some(WithOptionValue::Refresh(..))))
1700        {
1701            let catalog = self.catalog().for_session(session);
1702            let cluster = mz_sql::plan::resolve_cluster_for_materialized_view(&catalog, cmvs)?;
1703            let ids = self
1704                .index_oracle(cluster)
1705                .sufficient_collections(resolved_ids.collections().copied());
1706
1707            // If there is any REFRESH option, then acquire read holds. (Strictly speaking, we'd
1708            // need this only if there is a `REFRESH AT`, not for `REFRESH EVERY`, because later
1709            // we want to check the AT times against the read holds that we acquire here. But
1710            // we do it for any REFRESH option, to avoid having so many code paths doing different
1711            // things.)
1712            //
1713            // It's important that we acquire read holds _before_ we determine the least valid read.
1714            // Otherwise, we're not guaranteed that the since frontier doesn't
1715            // advance forward from underneath us.
1716            let read_holds = self.acquire_read_holds(&ids);
1717
1718            // Does `mz_now()` occur?
1719            let mz_now_ts = if cmvs
1720                .with_options
1721                .iter()
1722                .any(materialized_view_option_contains_temporal)
1723            {
1724                let timeline_context = self
1725                    .catalog()
1726                    .validate_timeline_context(resolved_ids.collections().copied())?;
1727
1728                // We default to EpochMilliseconds, similarly to `determine_timestamp_for`,
1729                // but even in the TimestampIndependent case.
1730                // Note that we didn't accurately decide whether we are TimestampDependent
1731                // or TimestampIndependent, because for this we'd need to also check whether
1732                // `query.contains_temporal()`, similarly to how `peek_stage_validate` does.
1733                // However, this doesn't matter here, as we are just going to default to
1734                // EpochMilliseconds in both cases.
1735                let timeline = timeline_context
1736                    .timeline()
1737                    .unwrap_or(&Timeline::EpochMilliseconds);
1738
1739                // Let's start with the timestamp oracle read timestamp.
1740                let mut timestamp = self.get_timestamp_oracle(timeline).read_ts().await;
1741
1742                // If `least_valid_read` is later than the oracle, then advance to that time.
1743                // If we didn't do this, then there would be a danger of missing the first refresh,
1744                // which might cause the materialized view to be unreadable for hours. This might
1745                // be what was happening here:
1746                // https://github.com/MaterializeInc/database-issues/issues/7265#issuecomment-1931856361
1747                //
1748                // In the long term, it would be good to actually block the MV creation statement
1749                // until `least_valid_read`. https://github.com/MaterializeInc/database-issues/issues/7504
1750                // Without blocking, we have the problem that a REFRESH AT CREATION is not linearized
1751                // with the CREATE MATERIALIZED VIEW statement, in the sense that a query from the MV
1752                // after its creation might see input changes that happened after the CRATE MATERIALIZED
1753                // VIEW statement returned.
1754                let oracle_timestamp = timestamp;
1755                let least_valid_read = read_holds.least_valid_read();
1756                timestamp.advance_by(least_valid_read.borrow());
1757
1758                if oracle_timestamp != timestamp {
1759                    warn!(%cmvs.name, %oracle_timestamp, %timestamp, "REFRESH MV's inputs are not readable at the oracle read ts");
1760                }
1761
1762                info!("Resolved `mz_now()` to {timestamp} for REFRESH MV");
1763                Ok(Some(timestamp))
1764            } else {
1765                Ok(None)
1766            };
1767
1768            // NOTE: The Drop impl of ReadHolds makes sure that the hold is
1769            // released when we don't use it.
1770            if acquire_read_holds {
1771                self.store_transaction_read_holds(session.conn_id().clone(), read_holds);
1772            }
1773
1774            mz_now_ts
1775        } else {
1776            Ok(None)
1777        }
1778    }
1779
1780    /// Instruct the dataflow layer to cancel any ongoing, interactive work for
1781    /// the named `conn_id` if the correct secret key is specified.
1782    ///
1783    /// Note: Here we take a [`ConnectionIdType`] as opposed to an owned
1784    /// `ConnectionId` because this method gets called by external clients when
1785    /// they request to cancel a request.
1786    #[mz_ore::instrument(level = "debug")]
1787    async fn handle_cancel(&mut self, conn_id: ConnectionIdType, secret_key: u32) {
1788        if let Some((id_handle, conn_meta)) = self.active_conns.get_key_value(&conn_id) {
1789            // If the secret key specified by the client doesn't match the
1790            // actual secret key for the target connection, we treat this as a
1791            // rogue cancellation request and ignore it.
1792            if conn_meta.secret_key != secret_key {
1793                return;
1794            }
1795
1796            // Now that we've verified the secret key, this is a privileged
1797            // cancellation request. We can upgrade the raw connection ID to a
1798            // proper `IdHandle`.
1799            self.handle_privileged_cancel(id_handle.clone()).await;
1800        }
1801    }
1802
1803    /// Unconditionally instructs the dataflow layer to cancel any ongoing,
1804    /// interactive work for the named `conn_id`.
1805    #[mz_ore::instrument(level = "debug")]
1806    pub(crate) async fn handle_privileged_cancel(&mut self, conn_id: ConnectionId) {
1807        let mut maybe_ctx = None;
1808
1809        // Cancel pending writes. There is at most one pending write per session.
1810        let pending_write_idx = self.pending_writes.iter().position(|pending_write_txn| {
1811            matches!(pending_write_txn, PendingWriteTxn::User {
1812                pending_txn: PendingTxn { ctx, .. },
1813                ..
1814            } if *ctx.session().conn_id() == conn_id)
1815        });
1816        if let Some(idx) = pending_write_idx {
1817            if let PendingWriteTxn::User {
1818                pending_txn: PendingTxn { ctx, .. },
1819                ..
1820            } = self.pending_writes.remove(idx)
1821            {
1822                maybe_ctx = Some(ctx);
1823            }
1824        }
1825
1826        // Cancel deferred writes.
1827        if let Some(write_op) = self.deferred_write_ops.remove(&conn_id) {
1828            maybe_ctx = Some(write_op.into_ctx());
1829        }
1830
1831        // Cancel deferred statements.
1832        let deferred_ddl_idx = self
1833            .serialized_ddl
1834            .iter()
1835            .position(|deferred| *deferred.ctx.session().conn_id() == conn_id);
1836        if let Some(idx) = deferred_ddl_idx {
1837            let deferred = self
1838                .serialized_ddl
1839                .remove(idx)
1840                .expect("known to exist from call to `position` above");
1841            maybe_ctx = Some(deferred.ctx);
1842        }
1843
1844        // Cancel reads waiting on being linearized. There is at most one linearized read per
1845        // session.
1846        if let Some(pending_read_txn) = self.pending_linearize_read_txns.remove(&conn_id) {
1847            let ctx = pending_read_txn.take_context();
1848            maybe_ctx = Some(ctx);
1849        }
1850
1851        if let Some(ctx) = maybe_ctx {
1852            ctx.retire(Err(AdapterError::Canceled));
1853        }
1854
1855        self.cancel_pending_peeks(&conn_id);
1856        self.cancel_pending_watchsets(&conn_id);
1857        self.cancel_compute_sinks_for_conn(&conn_id).await;
1858        self.cancel_cluster_reconfigurations_for_conn(&conn_id)
1859            .await;
1860        self.cancel_pending_copy(&conn_id);
1861        if let Some((tx, _rx)) = self.staged_cancellation.get_mut(&conn_id) {
1862            let _ = tx.send(true);
1863        }
1864    }
1865
1866    /// Handle termination of a client session.
1867    ///
1868    /// This cleans up any state in the coordinator associated with the session.
1869    #[mz_ore::instrument(level = "debug")]
1870    async fn handle_terminate(&mut self, conn_id: ConnectionId) {
1871        // If the session doesn't exist in `active_conns`, then this method will panic later on.
1872        // Instead we explicitly panic here while dumping the entire Coord to the logs to help
1873        // debug. This panic is very infrequent so we want as much information as possible.
1874        // See https://github.com/MaterializeInc/database-issues/issues/5627.
1875        assert!(
1876            self.active_conns.contains_key(&conn_id),
1877            "unknown connection: {conn_id:?}\n\n{self:?}"
1878        );
1879
1880        // We do not need to call clear_transaction here because there are no side effects to run
1881        // based on any session transaction state.
1882        self.clear_connection(&conn_id).await;
1883
1884        self.drop_temp_items(&conn_id).await;
1885        // Only call catalog_mut() if a temporary schema actually exists for this connection.
1886        // This avoids an expensive Arc::make_mut clone for the common case where the connection
1887        // never created any temporary objects.
1888        if self.catalog().state().has_temporary_schema(&conn_id) {
1889            self.catalog_mut()
1890                .drop_temporary_schema(&conn_id)
1891                .unwrap_or_terminate("unable to drop temporary schema");
1892        }
1893        let conn = self.active_conns.remove(&conn_id).expect("conn must exist");
1894        let session_type = metrics::session_type_label_value(conn.user());
1895        self.metrics
1896            .active_sessions
1897            .with_label_values(&[session_type])
1898            .dec();
1899        self.cancel_pending_peeks(conn.conn_id());
1900        self.cancel_pending_watchsets(&conn_id);
1901        self.cancel_pending_copy(&conn_id);
1902        self.end_session_for_statement_logging(conn.uuid());
1903
1904        // Queue the builtin table update, but do not wait for it to complete. We explicitly do
1905        // this to prevent blocking the Coordinator in the case that a lot of connections are
1906        // closed at once, which occurs regularly in some workflows.
1907        let update = self
1908            .catalog()
1909            .state()
1910            .pack_session_update(&conn, Diff::MINUS_ONE);
1911        let update = self.catalog().state().resolve_builtin_table_update(update);
1912
1913        let _builtin_update_notify = self.builtin_table_update().defer(vec![update]);
1914    }
1915
1916    /// Returns the necessary metadata for appending to a webhook source, and a channel to send
1917    /// rows.
1918    #[mz_ore::instrument(level = "debug")]
1919    fn handle_get_webhook(
1920        &mut self,
1921        database: String,
1922        schema: String,
1923        name: String,
1924        tx: oneshot::Sender<Result<AppendWebhookResponse, AppendWebhookError>>,
1925    ) {
1926        /// Attempts to resolve a Webhook source from a provided `database.schema.name` path.
1927        ///
1928        /// Returns a struct that can be used to append data to the underlying storate collection, and the
1929        /// types we should cast the request to.
1930        fn resolve(
1931            coord: &mut Coordinator,
1932            database: String,
1933            schema: String,
1934            name: String,
1935        ) -> Result<AppendWebhookResponse, PartialItemName> {
1936            // Resolve our collection.
1937            let name = PartialItemName {
1938                database: Some(database),
1939                schema: Some(schema),
1940                item: name,
1941            };
1942            let Ok(entry) = coord
1943                .catalog()
1944                .resolve_entry(None, &vec![], &name, &SYSTEM_CONN_ID)
1945            else {
1946                return Err(name);
1947            };
1948
1949            // Webhooks can be created with `CREATE SOURCE` or `CREATE TABLE`.
1950            let (data_source, desc, global_id) = match entry.item() {
1951                CatalogItem::Source(Source {
1952                    data_source: data_source @ DataSourceDesc::Webhook { .. },
1953                    desc,
1954                    global_id,
1955                    ..
1956                }) => (data_source, desc.clone(), *global_id),
1957                CatalogItem::Table(
1958                    table @ Table {
1959                        desc,
1960                        data_source:
1961                            TableDataSource::DataSource {
1962                                desc: data_source @ DataSourceDesc::Webhook { .. },
1963                                ..
1964                            },
1965                        ..
1966                    },
1967                ) => (data_source, desc.latest(), table.global_id_writes()),
1968                _ => return Err(name),
1969            };
1970
1971            let DataSourceDesc::Webhook {
1972                validate_using,
1973                body_format,
1974                headers,
1975                ..
1976            } = data_source
1977            else {
1978                mz_ore::soft_panic_or_log!("programming error! checked above for webhook");
1979                return Err(name);
1980            };
1981            let body_format = body_format.clone();
1982            let header_tys = headers.clone();
1983
1984            // Assert we have one column for the body, and how ever many are required for
1985            // the headers.
1986            let num_columns = headers.num_columns() + 1;
1987            mz_ore::soft_assert_or_log!(
1988                desc.arity() <= num_columns,
1989                "expected at most {} columns, but got {}",
1990                num_columns,
1991                desc.arity()
1992            );
1993
1994            // Double check that the body column of the webhook source matches the type
1995            // we're about to deserialize as.
1996            let body_column = desc
1997                .get_by_name(&"body".into())
1998                .map(|(_idx, ty)| ty.clone())
1999                .ok_or_else(|| name.clone())?;
2000            assert!(!body_column.nullable, "webhook body column is nullable!?");
2001            assert_eq!(body_column.scalar_type, SqlScalarType::from(body_format));
2002
2003            // Create a validator that can be called to validate a webhook request.
2004            let validator = validate_using.as_ref().map(|v| {
2005                let validation = v.clone();
2006                AppendWebhookValidator::new(validation, coord.caching_secrets_reader.clone())
2007            });
2008
2009            // Get a channel so we can queue updates to be written.
2010            let row_tx = coord
2011                .controller
2012                .storage
2013                .monotonic_appender(global_id)
2014                .map_err(|_| name.clone())?;
2015            let stats = coord
2016                .controller
2017                .storage
2018                .webhook_statistics(global_id)
2019                .map_err(|_| name)?;
2020            let invalidator = coord
2021                .active_webhooks
2022                .entry(entry.id())
2023                .or_insert_with(WebhookAppenderInvalidator::new);
2024            let tx = WebhookAppender::new(row_tx, invalidator.guard(), stats);
2025
2026            Ok(AppendWebhookResponse {
2027                tx,
2028                body_format,
2029                header_tys,
2030                validator,
2031            })
2032        }
2033
2034        let response = resolve(self, database, schema, name).map_err(|name| {
2035            AppendWebhookError::UnknownWebhook {
2036                database: name.database.expect("provided"),
2037                schema: name.schema.expect("provided"),
2038                name: name.item,
2039            }
2040        });
2041        let _ = tx.send(response);
2042    }
2043
2044    /// Handle registration of a frontend peek, for statement logging and query cancellation
2045    /// handling.
2046    fn handle_register_frontend_peek(
2047        &mut self,
2048        uuid: Uuid,
2049        conn_id: ConnectionId,
2050        cluster_id: mz_controller_types::ClusterId,
2051        depends_on: BTreeSet<GlobalId>,
2052        is_fast_path: bool,
2053        watch_set: Option<WatchSetCreation>,
2054        tx: oneshot::Sender<Result<(), AdapterError>>,
2055    ) {
2056        let statement_logging_id = watch_set.as_ref().map(|ws| ws.logging_id);
2057        if let Some(ws) = watch_set {
2058            if let Err(e) = self.install_peek_watch_sets(conn_id.clone(), ws) {
2059                let _ = tx.send(Err(
2060                    AdapterError::concurrent_dependency_drop_from_watch_set_install_error(e),
2061                ));
2062                return;
2063            }
2064        }
2065
2066        // Store the peek in pending_peeks for later retrieval when results arrive
2067        self.pending_peeks.insert(
2068            uuid,
2069            PendingPeek {
2070                conn_id: conn_id.clone(),
2071                cluster_id,
2072                depends_on,
2073                ctx_extra: ExecuteContextGuard::new(
2074                    statement_logging_id,
2075                    self.internal_cmd_tx.clone(),
2076                ),
2077                is_fast_path,
2078            },
2079        );
2080
2081        // Also track it by connection ID for cancellation support
2082        self.client_pending_peeks
2083            .entry(conn_id)
2084            .or_default()
2085            .insert(uuid, cluster_id);
2086
2087        let _ = tx.send(Ok(()));
2088    }
2089
2090    /// Handle unregistration of a frontend peek that was registered but failed to issue.
2091    /// This is used for cleanup when `client.peek()` fails after `RegisterFrontendPeek` succeeds.
2092    fn handle_unregister_frontend_peek(&mut self, uuid: Uuid, tx: oneshot::Sender<()>) {
2093        // Remove from pending_peeks (this also removes from client_pending_peeks)
2094        if let Some(pending_peek) = self.remove_pending_peek(&uuid) {
2095            // Retire `ExecuteContextExtra`, because the frontend will log the peek's error result.
2096            let _ = pending_peek.ctx_extra.defuse();
2097        }
2098        let _ = tx.send(());
2099    }
2100}