1use std::collections::{BTreeMap, BTreeSet};
11use std::fmt::Debug;
12
13use itertools::Itertools;
14use mz_catalog::durable::{DurableCatalogError, FenceError};
15use mz_compute_client::controller::error::{
16 CollectionUpdateError, DataflowCreationError, InstanceMissing, PeekError, ReadPolicyError,
17};
18use mz_controller_types::ClusterId;
19use mz_ore::tracing::OpenTelemetryContext;
20use mz_ore::{assert_none, exit, soft_assert_no_log};
21use mz_repr::{RelationDesc, RowIterator, SqlScalarType};
22use mz_sql::names::FullItemName;
23use mz_sql::plan::StatementDesc;
24use mz_sql::session::metadata::SessionMetadata;
25use mz_sql::session::vars::Var;
26use mz_sql_parser::ast::display::AstDisplay;
27use mz_sql_parser::ast::{
28 CreateIndexStatement, Ident, Raw, RawClusterName, RawItemName, Statement,
29};
30use mz_storage_types::controller::StorageError;
31use mz_transform::TransformError;
32use tokio::sync::mpsc::UnboundedSender;
33use tokio::sync::oneshot;
34
35use crate::catalog::{Catalog, CatalogState};
36use crate::command::{Command, Response};
37use crate::coord::{Message, PendingTxnResponse};
38use crate::error::AdapterError;
39use crate::session::{EndTransactionAction, Session};
40use crate::{ExecuteContext, ExecuteResponse};
41
42#[derive(Debug)]
44pub struct ClientTransmitter<T>
45where
46 T: Transmittable,
47 <T as Transmittable>::Allowed: 'static,
48{
49 tx: Option<oneshot::Sender<Response<T>>>,
50 internal_cmd_tx: UnboundedSender<Message>,
51 allowed: Option<&'static [T::Allowed]>,
54}
55
56impl<T: Transmittable + std::fmt::Debug> ClientTransmitter<T> {
57 pub fn new(
59 tx: oneshot::Sender<Response<T>>,
60 internal_cmd_tx: UnboundedSender<Message>,
61 ) -> ClientTransmitter<T> {
62 ClientTransmitter {
63 tx: Some(tx),
64 internal_cmd_tx,
65 allowed: None,
66 }
67 }
68
69 #[mz_ore::instrument(level = "debug")]
76 pub fn send(mut self, result: Result<T, AdapterError>, session: Session) {
77 soft_assert_no_log!(
79 match (&result, self.allowed.take()) {
80 (Ok(t), Some(allowed)) => allowed.contains(&t.to_allowed()),
81 _ => true,
82 },
83 "tried to send disallowed value {result:?} through ClientTransmitter; \
84 see ClientTransmitter::set_allowed"
85 );
86
87 if let Err(res) = self
90 .tx
91 .take()
92 .expect("tx will always be `Some` unless `self` has been consumed")
93 .send(Response {
94 result,
95 session,
96 otel_ctx: OpenTelemetryContext::obtain(),
97 })
98 {
99 let send_res = self.internal_cmd_tx.send(Message::Command(
102 OpenTelemetryContext::obtain(),
103 Command::Terminate {
104 conn_id: res.session.conn_id().clone(),
105 tx: None,
106 },
107 ));
108 if send_res.is_err() {
109 tracing::warn!("coordinator gone, could not clean up session");
110 }
111 }
112 }
113
114 pub fn take(mut self) -> oneshot::Sender<Response<T>> {
115 self.tx
116 .take()
117 .expect("tx will always be `Some` unless `self` has been consumed")
118 }
119
120 pub fn set_allowed(&mut self, allowed: &'static [T::Allowed]) {
124 self.allowed = Some(allowed);
125 }
126}
127
128pub trait Transmittable {
130 type Allowed: Eq + PartialEq + std::fmt::Debug;
132 fn to_allowed(&self) -> Self::Allowed;
142}
143
144impl Transmittable for () {
145 type Allowed = bool;
146
147 fn to_allowed(&self) -> Self::Allowed {
148 true
149 }
150}
151
152#[derive(Debug)]
156pub struct CompletedClientTransmitter {
157 ctx: ExecuteContext,
158 response: Result<PendingTxnResponse, AdapterError>,
159 action: EndTransactionAction,
160}
161
162impl CompletedClientTransmitter {
163 pub fn new(
165 ctx: ExecuteContext,
166 response: Result<PendingTxnResponse, AdapterError>,
167 action: EndTransactionAction,
168 ) -> Self {
169 CompletedClientTransmitter {
170 ctx,
171 response,
172 action,
173 }
174 }
175
176 pub fn finalize(mut self) -> (ExecuteContext, Result<ExecuteResponse, AdapterError>) {
178 let changed = self
179 .ctx
180 .session_mut()
181 .vars_mut()
182 .end_transaction(self.action);
183
184 let response = self.response.map(|mut r| {
186 r.extend_params(changed);
187 ExecuteResponse::from(r)
188 });
189
190 (self.ctx, response)
191 }
192}
193
194impl<T: Transmittable> Drop for ClientTransmitter<T> {
195 fn drop(&mut self) {
196 if self.tx.is_some() {
197 panic!("client transmitter dropped without send")
198 }
199 }
200}
201
202pub fn index_sql(
205 index_name: String,
206 cluster_id: ClusterId,
207 view_name: FullItemName,
208 view_desc: &RelationDesc,
209 keys: &[usize],
210) -> String {
211 use mz_sql::ast::{Expr, Value};
212
213 CreateIndexStatement::<Raw> {
214 name: Some(Ident::new_unchecked(index_name)),
215 on_name: RawItemName::Name(mz_sql::normalize::unresolve(view_name)),
216 in_cluster: Some(RawClusterName::Resolved(cluster_id.to_string())),
217 key_parts: Some(
218 keys.iter()
219 .map(|i| match view_desc.get_unambiguous_name(*i) {
220 Some(n) => Expr::Identifier(vec![Ident::new_unchecked(n.to_string())]),
221 _ => Expr::Value(Value::Number((i + 1).to_string())),
222 })
223 .collect(),
224 ),
225 with_options: vec![],
226 if_not_exists: false,
227 }
228 .to_ast_string_stable()
229}
230
231pub fn describe(
233 catalog: &Catalog,
234 stmt: Statement<Raw>,
235 param_types: &[Option<SqlScalarType>],
236 session: &Session,
237) -> Result<StatementDesc, AdapterError> {
238 let catalog = &catalog.for_session(session);
239 let (stmt, resolved_ids) = mz_sql::names::resolve(catalog, stmt)?;
240 Ok(mz_sql::plan::describe(
241 session.pcx(),
242 catalog,
243 stmt,
244 param_types,
245 &resolved_ids,
246 )?)
247}
248
249pub trait ResultExt<T> {
250 fn unwrap_or_terminate(self, context: &str) -> T;
254
255 fn maybe_terminate(self, context: &str) -> Self;
259}
260
261impl<T, E> ResultExt<T> for Result<T, E>
262where
263 E: ShouldTerminateGracefully + Debug,
264{
265 fn unwrap_or_terminate(self, context: &str) -> T {
266 match self {
267 Ok(t) => t,
268 Err(e) if e.should_terminate_gracefully() => exit!(0, "{context}: {e:?}"),
269 Err(e) => panic!("{context}: {e:?}"),
270 }
271 }
272
273 fn maybe_terminate(self, context: &str) -> Self {
274 if let Err(e) = &self {
275 if e.should_terminate_gracefully() {
276 exit!(0, "{context}: {e:?}");
277 }
278 }
279
280 self
281 }
282}
283
284trait ShouldTerminateGracefully {
287 fn should_terminate_gracefully(&self) -> bool;
290}
291
292impl ShouldTerminateGracefully for AdapterError {
293 fn should_terminate_gracefully(&self) -> bool {
294 match self {
295 AdapterError::Catalog(e) => e.should_terminate_gracefully(),
296 _ => false,
297 }
298 }
299}
300
301impl ShouldTerminateGracefully for mz_catalog::memory::error::Error {
302 fn should_terminate_gracefully(&self) -> bool {
303 match &self.kind {
304 mz_catalog::memory::error::ErrorKind::Durable(e) => e.should_terminate_gracefully(),
305 _ => false,
306 }
307 }
308}
309
310impl ShouldTerminateGracefully for mz_catalog::durable::CatalogError {
311 fn should_terminate_gracefully(&self) -> bool {
312 match &self {
313 Self::Durable(e) => e.should_terminate_gracefully(),
314 Self::Catalog(_) => false,
315 }
316 }
317}
318
319impl ShouldTerminateGracefully for DurableCatalogError {
320 fn should_terminate_gracefully(&self) -> bool {
321 match self {
322 DurableCatalogError::Fence(err) => err.should_terminate_gracefully(),
323 DurableCatalogError::CatalogOutOfSync { .. } => true,
324 DurableCatalogError::IncompatibleDataVersion { .. }
325 | DurableCatalogError::IncompatiblePersistVersion { .. }
326 | DurableCatalogError::Proto(_)
327 | DurableCatalogError::Uninitialized
328 | DurableCatalogError::NotWritable(_)
329 | DurableCatalogError::DryRunTransaction
330 | DurableCatalogError::DuplicateKey
331 | DurableCatalogError::UniquenessViolation
332 | DurableCatalogError::Storage(_)
333 | DurableCatalogError::Internal(_) => false,
334 }
335 }
336}
337
338impl ShouldTerminateGracefully for FenceError {
339 fn should_terminate_gracefully(&self) -> bool {
340 match self {
341 FenceError::DeployGeneration { .. } => true,
342 FenceError::Epoch { .. } | FenceError::MigrationUpper { .. } => false,
343 }
344 }
345}
346
347impl ShouldTerminateGracefully for StorageError {
348 fn should_terminate_gracefully(&self) -> bool {
349 match self {
350 StorageError::CollectionMetadataAlreadyExists(_)
351 | StorageError::PersistShardAlreadyInUse(_)
352 | StorageError::PersistSchemaEvolveRace { .. }
353 | StorageError::PersistInvalidSchemaEvolve { .. }
354 | StorageError::TxnWalShardAlreadyExists
355 | StorageError::UpdateBeyondUpper(_)
356 | StorageError::ReadBeforeSince(_)
357 | StorageError::InvalidUppers(_)
358 | StorageError::InvalidUsage(_)
359 | StorageError::CollectionIdReused(_)
360 | StorageError::SinkIdReused(_)
361 | StorageError::IdentifierMissing(_)
362 | StorageError::IdentifierInvalid(_)
363 | StorageError::IngestionInstanceMissing { .. }
364 | StorageError::ExportInstanceMissing { .. }
365 | StorageError::Generic(_)
366 | StorageError::ReadOnly
367 | StorageError::DataflowError(_)
368 | StorageError::InvalidAlter { .. }
369 | StorageError::ShuttingDown(_)
370 | StorageError::MissingSubsourceReference { .. }
371 | StorageError::RtrTimeout(_)
372 | StorageError::RtrDropFailure(_) => false,
373 }
374 }
375}
376
377impl ShouldTerminateGracefully for DataflowCreationError {
378 fn should_terminate_gracefully(&self) -> bool {
379 match self {
380 DataflowCreationError::SinceViolation(_)
381 | DataflowCreationError::InstanceMissing(_)
382 | DataflowCreationError::CollectionMissing(_)
383 | DataflowCreationError::ReplicaMissing(_)
384 | DataflowCreationError::MissingAsOf
385 | DataflowCreationError::EmptyAsOfForSubscribe
386 | DataflowCreationError::EmptyAsOfForCopyTo => false,
387 }
388 }
389}
390
391impl ShouldTerminateGracefully for CollectionUpdateError {
392 fn should_terminate_gracefully(&self) -> bool {
393 match self {
394 CollectionUpdateError::InstanceMissing(_)
395 | CollectionUpdateError::CollectionMissing(_) => false,
396 }
397 }
398}
399
400impl ShouldTerminateGracefully for PeekError {
401 fn should_terminate_gracefully(&self) -> bool {
402 match self {
403 PeekError::SinceViolation(_)
404 | PeekError::ReadHoldIdMismatch(_)
405 | PeekError::InstanceMissing(_)
406 | PeekError::CollectionMissing(_)
407 | PeekError::ReplicaMissing(_) => false,
408 }
409 }
410}
411
412impl ShouldTerminateGracefully for ReadPolicyError {
413 fn should_terminate_gracefully(&self) -> bool {
414 match self {
415 ReadPolicyError::InstanceMissing(_)
416 | ReadPolicyError::CollectionMissing(_)
417 | ReadPolicyError::WriteOnlyCollection(_) => false,
418 }
419 }
420}
421
422impl ShouldTerminateGracefully for TransformError {
423 fn should_terminate_gracefully(&self) -> bool {
424 match self {
425 TransformError::Internal(_)
426 | TransformError::IdentifierMissing(_)
427 | TransformError::CallerShouldPanic(_) => false,
428 }
429 }
430}
431
432impl ShouldTerminateGracefully for InstanceMissing {
433 fn should_terminate_gracefully(&self) -> bool {
434 false
435 }
436}
437
438pub(crate) fn viewable_variables<'a>(
440 catalog: &'a CatalogState,
441 session: &'a dyn SessionMetadata,
442) -> impl Iterator<Item = &'a dyn Var> {
443 session
444 .vars()
445 .iter()
446 .chain(catalog.system_config().iter())
447 .filter(|v| v.visible(session.user(), catalog.system_config()).is_ok())
448}
449
450pub fn verify_datum_desc(
452 desc: &RelationDesc,
453 rows: &mut dyn RowIterator,
454) -> Result<(), AdapterError> {
455 let Some(row) = rows.peek() else {
462 return Ok(());
463 };
464
465 let datums = row.unpack();
466 let col_types = &desc.typ().column_types;
467 if datums.len() != col_types.len() {
468 let msg = format!(
469 "internal error: row descriptor has {} columns but row has {} columns",
470 col_types.len(),
471 datums.len(),
472 );
473 return Err(AdapterError::Internal(msg));
474 }
475
476 for (i, (d, t)) in datums.iter().zip_eq(col_types).enumerate() {
477 if !d.is_instance_of_sql(t) {
478 let msg = format!(
479 "internal error: column {} is not of expected type {:?}: {:?}",
480 i, t, d
481 );
482 return Err(AdapterError::Internal(msg));
483 }
484 }
485
486 Ok(())
487}
488
489pub fn sort_topological<T, K, FK, FD>(items: &mut Vec<T>, key_fn: FK, dependencies_fn: FD)
496where
497 T: Debug,
498 K: Debug + Copy + Ord,
499 FK: Fn(&T) -> K,
500 FD: Fn(&T) -> BTreeSet<K>,
501{
502 let mut items_by_key = BTreeMap::new();
503 for item in items.drain(..) {
504 let key = key_fn(&item);
505 let prev = items_by_key.insert(key, item);
506 assert_none!(prev);
507 }
508
509 let mut in_degree = BTreeMap::<K, usize>::new();
511 let mut dependents = BTreeMap::<K, Vec<K>>::new();
513 let mut ready = Vec::<K>::new();
515
516 for (&key, item) in &items_by_key {
518 let mut dependencies = dependencies_fn(item);
519 dependencies.retain(|dep| items_by_key.contains_key(dep) && *dep != key);
521
522 in_degree.insert(key, dependencies.len());
523
524 for dep in &dependencies {
525 dependents.entry(*dep).or_default().push(key);
526 }
527
528 if dependencies.is_empty() {
529 ready.push(key);
530 }
531 }
532
533 while let Some(id) = ready.pop() {
535 let item = items_by_key.remove(&id).expect("must exist");
536 items.push(item);
537
538 if let Some(depts) = dependents.get(&id) {
539 for dept in depts {
540 let deg = in_degree.get_mut(dept).expect("must exist");
541 *deg -= 1;
542 if *deg == 0 {
543 ready.push(*dept);
544 }
545 }
546 }
547 }
548
549 if !items_by_key.is_empty() {
551 panic!("dependency cycle: {items_by_key:?}");
552 }
553}