Skip to main content

mz_adapter/catalog/
limits.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::collections::BTreeMap;
11
12use mz_adapter_types::connection::ConnectionId;
13use mz_catalog::memory::objects::CatalogItem;
14use mz_controller::clusters::{ManagedReplicaLocation, ReplicaLocation};
15use mz_controller_types::ClusterId;
16use mz_ore::soft_panic_or_log;
17use mz_repr::adt::numeric::Numeric;
18use mz_sql::names::ResolvedDatabaseSpecifier;
19use mz_sql::plan::ConnectionDetails;
20use mz_sql::session::vars::{
21    MAX_AWS_PRIVATELINK_CONNECTIONS, MAX_CLUSTERS, MAX_CREDIT_CONSUMPTION_RATE, MAX_DATABASES,
22    MAX_KAFKA_CONNECTIONS, MAX_MATERIALIZED_VIEWS, MAX_MYSQL_CONNECTIONS, MAX_NETWORK_POLICIES,
23    MAX_OBJECTS_PER_SCHEMA, MAX_POSTGRES_CONNECTIONS, MAX_QUERY_POLICIES, MAX_REPLICAS_PER_CLUSTER,
24    MAX_ROLES, MAX_SCHEMAS_PER_DATABASE, MAX_SECRETS, MAX_SINKS, MAX_SOURCES,
25    MAX_SQL_SERVER_CONNECTIONS, MAX_TABLES, SystemVars, Var,
26};
27
28use crate::AdapterError;
29use crate::catalog::{CatalogState, DropObjectInfo, Op};
30
31impl CatalogState {
32    /// Validate all resource limits in a catalog transaction and return an error if that limit is
33    /// exceeded.
34    pub(crate) fn validate_resource_limits(
35        &self,
36        ops: &[Op],
37        conn_id: &ConnectionId,
38    ) -> Result<(), AdapterError> {
39        let mut new_kafka_connections = 0;
40        let mut new_postgres_connections = 0;
41        let mut new_mysql_connections = 0;
42        let mut new_sql_server_connections = 0;
43        let mut new_aws_privatelink_connections = 0;
44        let mut new_tables = 0;
45        let mut new_sources = 0;
46        let mut new_sinks = 0;
47        let mut new_materialized_views = 0;
48        let mut new_clusters = 0;
49        let mut new_replicas_per_cluster = BTreeMap::new();
50        let mut new_credit_consumption_rate = Numeric::zero();
51        let mut new_databases = 0;
52        let mut new_schemas_per_database = BTreeMap::new();
53        let mut new_objects_per_schema = BTreeMap::new();
54        let mut new_secrets = 0;
55        let mut new_roles = 0;
56        let mut new_network_policies = 0;
57        let mut new_query_policies = 0;
58        for op in ops {
59            match op {
60                Op::CreateDatabase { .. } => {
61                    new_databases += 1;
62                }
63                Op::CreateSchema { database_id, .. } => {
64                    if let ResolvedDatabaseSpecifier::Id(database_id) = database_id {
65                        *new_schemas_per_database.entry(database_id).or_insert(0) += 1;
66                    }
67                }
68                Op::CreateRole { .. } => {
69                    new_roles += 1;
70                }
71                Op::CreateNetworkPolicy { .. } => {
72                    new_network_policies += 1;
73                }
74                Op::CreateQueryPolicy { .. } => {
75                    new_query_policies += 1;
76                }
77                Op::CreateCluster { .. } => {
78                    // TODO(benesch): having deprecated linked clusters, remove
79                    // the `max_sources` and `max_sinks` limit, and set a higher
80                    // max cluster limit?
81                    new_clusters += 1;
82                }
83                Op::CreateClusterReplica {
84                    cluster_id, config, ..
85                } => {
86                    if cluster_id.is_user() {
87                        *new_replicas_per_cluster.entry(*cluster_id).or_insert(0) += 1;
88                        if let ReplicaLocation::Managed(location) = &config.location {
89                            new_credit_consumption_rate += self.replica_credits_per_hour(location);
90                        }
91                    }
92                }
93                Op::CreateItem { name, item, .. } => {
94                    *new_objects_per_schema
95                        .entry((
96                            name.qualifiers.database_spec.clone(),
97                            name.qualifiers.schema_spec.clone(),
98                        ))
99                        .or_insert(0) += 1;
100                    match item {
101                        CatalogItem::Connection(connection) => match connection.details {
102                            ConnectionDetails::Kafka(_) => new_kafka_connections += 1,
103                            ConnectionDetails::Postgres(_) => new_postgres_connections += 1,
104                            ConnectionDetails::MySql(_) => new_mysql_connections += 1,
105                            ConnectionDetails::SqlServer(_) => new_sql_server_connections += 1,
106                            ConnectionDetails::AwsPrivatelink(_) => {
107                                new_aws_privatelink_connections += 1
108                            }
109                            ConnectionDetails::Csr(_)
110                            | ConnectionDetails::GlueSchemaRegistry(_)
111                            | ConnectionDetails::Ssh { .. }
112                            | ConnectionDetails::Aws(_)
113                            | ConnectionDetails::Gcp(_)
114                            | ConnectionDetails::IcebergCatalog(_) => {}
115                        },
116                        CatalogItem::Table(_) => {
117                            new_tables += 1;
118                        }
119                        CatalogItem::Source(source) => {
120                            new_sources += source.user_controllable_persist_shard_count()
121                        }
122                        CatalogItem::Sink(_) => new_sinks += 1,
123                        CatalogItem::MaterializedView(_) => {
124                            new_materialized_views += 1;
125                        }
126                        CatalogItem::Secret(_) => {
127                            new_secrets += 1;
128                        }
129                        CatalogItem::Log(_)
130                        | CatalogItem::View(_)
131                        | CatalogItem::Index(_)
132                        | CatalogItem::Type(_)
133                        | CatalogItem::Func(_)
134                        | CatalogItem::MetricSink(_) => {}
135                    }
136                }
137                Op::DropObjects {
138                    objects: drop_object_infos,
139                    ..
140                } => {
141                    for drop_object_info in drop_object_infos {
142                        match drop_object_info {
143                            DropObjectInfo::Cluster(_) => {
144                                new_clusters -= 1;
145                            }
146                            DropObjectInfo::ClusterReplica((cluster_id, replica_id, _reason)) => {
147                                if cluster_id.is_user() {
148                                    *new_replicas_per_cluster.entry(*cluster_id).or_insert(0) -= 1;
149                                    let cluster =
150                                        self.get_cluster_replica(*cluster_id, *replica_id);
151                                    if let ReplicaLocation::Managed(location) =
152                                        &cluster.config.location
153                                    {
154                                        new_credit_consumption_rate -=
155                                            self.replica_credits_per_hour(location);
156                                    }
157                                }
158                            }
159                            DropObjectInfo::Database(_) => {
160                                new_databases -= 1;
161                            }
162                            DropObjectInfo::Schema((database_spec, _)) => {
163                                if let ResolvedDatabaseSpecifier::Id(database_id) = database_spec {
164                                    *new_schemas_per_database.entry(database_id).or_insert(0) -= 1;
165                                }
166                            }
167                            DropObjectInfo::Role(_) => {
168                                new_roles -= 1;
169                            }
170                            DropObjectInfo::NetworkPolicy(_) => {
171                                new_network_policies -= 1;
172                            }
173                            DropObjectInfo::QueryPolicy(_) => {
174                                new_query_policies -= 1;
175                            }
176                            DropObjectInfo::Item(id) => {
177                                let entry = self.get_entry(id);
178                                *new_objects_per_schema
179                                    .entry((
180                                        entry.name().qualifiers.database_spec.clone(),
181                                        entry.name().qualifiers.schema_spec.clone(),
182                                    ))
183                                    .or_insert(0) -= 1;
184                                match entry.item() {
185                                    CatalogItem::Connection(connection) => match connection.details
186                                    {
187                                        ConnectionDetails::AwsPrivatelink(_) => {
188                                            new_aws_privatelink_connections -= 1;
189                                        }
190                                        _ => (),
191                                    },
192                                    CatalogItem::Table(_) => {
193                                        new_tables -= 1;
194                                    }
195                                    CatalogItem::Source(source) => {
196                                        new_sources -=
197                                            source.user_controllable_persist_shard_count()
198                                    }
199                                    CatalogItem::Sink(_) => new_sinks -= 1,
200                                    CatalogItem::MaterializedView(_) => {
201                                        new_materialized_views -= 1;
202                                    }
203                                    CatalogItem::Secret(_) => {
204                                        new_secrets -= 1;
205                                    }
206                                    CatalogItem::Log(_)
207                                    | CatalogItem::View(_)
208                                    | CatalogItem::Index(_)
209                                    | CatalogItem::Type(_)
210                                    | CatalogItem::Func(_)
211                                    | CatalogItem::MetricSink(_) => {}
212                                }
213                            }
214                        }
215                    }
216                }
217                Op::UpdateItem {
218                    name: _,
219                    id,
220                    to_item,
221                } => match to_item {
222                    CatalogItem::Source(source) => {
223                        let current_source = self
224                            .get_entry(id)
225                            .source()
226                            .expect("source update is for source item");
227
228                        new_sources += source.user_controllable_persist_shard_count()
229                            - current_source.user_controllable_persist_shard_count();
230                    }
231                    CatalogItem::Connection(_)
232                    | CatalogItem::Table(_)
233                    | CatalogItem::Sink(_)
234                    | CatalogItem::MaterializedView(_)
235                    | CatalogItem::Secret(_)
236                    | CatalogItem::Log(_)
237                    | CatalogItem::View(_)
238                    | CatalogItem::Index(_)
239                    | CatalogItem::Type(_)
240                    | CatalogItem::Func(_)
241                    | CatalogItem::MetricSink(_) => {}
242                },
243                Op::AlterRole { .. }
244                | Op::AlterRetainHistory { .. }
245                | Op::AlterSourceTimestampInterval { .. }
246                | Op::AlterNetworkPolicy { .. }
247                | Op::AlterQueryPolicy { .. }
248                | Op::AlterAddColumn { .. }
249                | Op::AlterMaterializedViewApplyReplacement { .. }
250                | Op::UpdatePrivilege { .. }
251                | Op::UpdateDefaultPrivilege { .. }
252                | Op::GrantRole { .. }
253                | Op::RenameCluster { .. }
254                | Op::RenameClusterReplica { .. }
255                | Op::RenameItem { .. }
256                | Op::RenameSchema { .. }
257                | Op::UpdateOwner { .. }
258                | Op::RevokeRole { .. }
259                | Op::UpdateClusterConfig { .. }
260                | Op::UpdateSourceReferences { .. }
261                | Op::UpdateSystemConfiguration { .. }
262                | Op::ResetSystemConfiguration { .. }
263                | Op::ResetAllSystemConfiguration { .. }
264                | Op::UpdateScopedSystemParameters { .. }
265                | Op::Comment { .. }
266                | Op::RenameCommand(_)
267                | Op::RotatedKeys(_)
268                | Op::CheckClusterState { .. }
269                | Op::InjectAuditEvents { .. } => {}
270            }
271        }
272
273        let mut current_aws_privatelink_connections = 0;
274        let mut current_postgres_connections = 0;
275        let mut current_mysql_connections = 0;
276        let mut current_sql_server_connections = 0;
277        let mut current_kafka_connections = 0;
278        for c in self.user_connections() {
279            let connection = c
280                .connection()
281                .expect("`user_connections()` only returns connection objects");
282
283            match connection.details {
284                ConnectionDetails::AwsPrivatelink(_) => current_aws_privatelink_connections += 1,
285                ConnectionDetails::Postgres(_) => current_postgres_connections += 1,
286                ConnectionDetails::MySql(_) => current_mysql_connections += 1,
287                ConnectionDetails::SqlServer(_) => current_sql_server_connections += 1,
288                ConnectionDetails::Kafka(_) => current_kafka_connections += 1,
289                ConnectionDetails::Csr(_)
290                | ConnectionDetails::GlueSchemaRegistry(_)
291                | ConnectionDetails::Ssh { .. }
292                | ConnectionDetails::Aws(_)
293                | ConnectionDetails::Gcp(_)
294                | ConnectionDetails::IcebergCatalog(_) => {}
295            }
296        }
297        self.validate_resource_limit(
298            current_kafka_connections,
299            new_kafka_connections,
300            SystemVars::max_kafka_connections,
301            "Kafka Connection",
302            MAX_KAFKA_CONNECTIONS.name(),
303        )?;
304        self.validate_resource_limit(
305            current_postgres_connections,
306            new_postgres_connections,
307            SystemVars::max_postgres_connections,
308            "PostgreSQL Connection",
309            MAX_POSTGRES_CONNECTIONS.name(),
310        )?;
311        self.validate_resource_limit(
312            current_mysql_connections,
313            new_mysql_connections,
314            SystemVars::max_mysql_connections,
315            "MySQL Connection",
316            MAX_MYSQL_CONNECTIONS.name(),
317        )?;
318        self.validate_resource_limit(
319            current_sql_server_connections,
320            new_sql_server_connections,
321            SystemVars::max_sql_server_connections,
322            "SQL Server Connection",
323            MAX_SQL_SERVER_CONNECTIONS.name(),
324        )?;
325        self.validate_resource_limit(
326            current_aws_privatelink_connections,
327            new_aws_privatelink_connections,
328            SystemVars::max_aws_privatelink_connections,
329            "AWS PrivateLink Connection",
330            MAX_AWS_PRIVATELINK_CONNECTIONS.name(),
331        )?;
332        self.validate_resource_limit(
333            self.user_tables().count(),
334            new_tables,
335            SystemVars::max_tables,
336            "table",
337            MAX_TABLES.name(),
338        )?;
339
340        let current_sources: usize = self
341            .user_sources()
342            .filter_map(|source| source.source())
343            .map(|source| source.user_controllable_persist_shard_count())
344            .sum::<i64>()
345            .try_into()
346            .expect("non-negative sum of sources");
347
348        self.validate_resource_limit(
349            current_sources,
350            new_sources,
351            SystemVars::max_sources,
352            "source",
353            MAX_SOURCES.name(),
354        )?;
355        self.validate_resource_limit(
356            self.user_sinks().count(),
357            new_sinks,
358            SystemVars::max_sinks,
359            "sink",
360            MAX_SINKS.name(),
361        )?;
362        self.validate_resource_limit(
363            self.user_materialized_views().count(),
364            new_materialized_views,
365            SystemVars::max_materialized_views,
366            "materialized view",
367            MAX_MATERIALIZED_VIEWS.name(),
368        )?;
369        self.validate_resource_limit(
370            // Linked compute clusters don't count against the limit, since
371            // we have a separate sources and sinks limit.
372            //
373            // TODO(benesch): remove the `max_sources` and `max_sinks` limit,
374            // and set a higher max cluster limit?
375            self.user_clusters().count(),
376            new_clusters,
377            SystemVars::max_clusters,
378            "cluster",
379            MAX_CLUSTERS.name(),
380        )?;
381        for (cluster_id, new_replicas) in new_replicas_per_cluster {
382            // It's possible that the cluster hasn't been created yet.
383            let current_amount = self
384                .try_get_cluster(cluster_id)
385                .map(|instance| instance.user_replicas().count())
386                .unwrap_or(0);
387            self.validate_resource_limit(
388                current_amount,
389                new_replicas,
390                SystemVars::max_replicas_per_cluster,
391                "cluster replica",
392                MAX_REPLICAS_PER_CLUSTER.name(),
393            )?;
394        }
395        self.validate_resource_limit_numeric(
396            self.current_credit_consumption_rate(None),
397            new_credit_consumption_rate,
398            |system_vars| {
399                self.license_key
400                    .max_credit_consumption_rate()
401                    .map_or_else(|| system_vars.max_credit_consumption_rate(), Numeric::from)
402            },
403            "cluster replica",
404            MAX_CREDIT_CONSUMPTION_RATE.name(),
405        )?;
406        self.validate_resource_limit(
407            self.databases().count(),
408            new_databases,
409            SystemVars::max_databases,
410            "database",
411            MAX_DATABASES.name(),
412        )?;
413        for (database_id, new_schemas) in new_schemas_per_database {
414            self.validate_resource_limit(
415                self.get_database(database_id).schemas_by_id.len(),
416                new_schemas,
417                SystemVars::max_schemas_per_database,
418                "schema",
419                MAX_SCHEMAS_PER_DATABASE.name(),
420            )?;
421        }
422        for ((database_spec, schema_spec), new_objects) in new_objects_per_schema {
423            // For temporary schemas that don't exist yet (lazy creation),
424            // treat them as having 0 items.
425            let current_items = self
426                .try_get_schema(&database_spec, &schema_spec, conn_id)
427                .map(|schema| schema.items.len())
428                .unwrap_or(0);
429            self.validate_resource_limit(
430                current_items,
431                new_objects,
432                SystemVars::max_objects_per_schema,
433                "object",
434                MAX_OBJECTS_PER_SCHEMA.name(),
435            )?;
436        }
437        self.validate_resource_limit(
438            self.user_secrets().count(),
439            new_secrets,
440            SystemVars::max_secrets,
441            "secret",
442            MAX_SECRETS.name(),
443        )?;
444        self.validate_resource_limit(
445            self.user_roles().count(),
446            new_roles,
447            SystemVars::max_roles,
448            "role",
449            MAX_ROLES.name(),
450        )?;
451        self.validate_resource_limit(
452            self.user_network_policies().count(),
453            new_network_policies,
454            SystemVars::max_network_policies,
455            "network_policy",
456            MAX_NETWORK_POLICIES.name(),
457        )?;
458        self.validate_resource_limit(
459            self.user_query_policies().count(),
460            new_query_policies,
461            SystemVars::max_query_policies,
462            "query policy",
463            MAX_QUERY_POLICIES.name(),
464        )?;
465        Ok(())
466    }
467
468    /// Validate a specific type of resource limit and return an error if that limit is exceeded.
469    pub(crate) fn validate_resource_limit<F>(
470        &self,
471        current_amount: usize,
472        new_instances: i64,
473        resource_limit: F,
474        resource_type: &str,
475        limit_name: &str,
476    ) -> Result<(), AdapterError>
477    where
478        F: Fn(&SystemVars) -> u32,
479    {
480        if new_instances <= 0 {
481            return Ok(());
482        }
483
484        let limit: i64 = resource_limit(self.system_config()).into();
485        let current_amount: Option<i64> = current_amount.try_into().ok();
486        let desired =
487            current_amount.and_then(|current_amount| current_amount.checked_add(new_instances));
488
489        let exceeds_limit = if let Some(desired) = desired {
490            desired > limit
491        } else {
492            true
493        };
494
495        let desired = desired
496            .map(|desired| desired.to_string())
497            .unwrap_or_else(|| format!("more than {}", i64::MAX));
498        let current = current_amount
499            .map(|current| current.to_string())
500            .unwrap_or_else(|| format!("more than {}", i64::MAX));
501        if exceeds_limit {
502            Err(AdapterError::ResourceExhaustion {
503                resource_type: resource_type.to_string(),
504                limit_name: limit_name.to_string(),
505                desired,
506                limit: limit.to_string(),
507                current,
508            })
509        } else {
510            Ok(())
511        }
512    }
513
514    /// Validate a specific type of float resource limit and return an error if that limit is exceeded.
515    ///
516    /// This is very similar to [`Self::validate_resource_limit`] but for numerics.
517    pub(crate) fn validate_resource_limit_numeric<F>(
518        &self,
519        current_amount: Numeric,
520        new_amount: Numeric,
521        resource_limit: F,
522        resource_type: &str,
523        limit_name: &str,
524    ) -> Result<(), AdapterError>
525    where
526        F: Fn(&SystemVars) -> Numeric,
527    {
528        if new_amount <= Numeric::zero() {
529            return Ok(());
530        }
531
532        let limit = resource_limit(self.system_config());
533        // Floats will overflow to infinity instead of panicking, which has the correct comparison
534        // semantics.
535        // NaN should be impossible here since both values are positive.
536        let desired = current_amount + new_amount;
537        if desired > limit {
538            Err(AdapterError::ResourceExhaustion {
539                resource_type: resource_type.to_string(),
540                limit_name: limit_name.to_string(),
541                desired: desired.to_string(),
542                limit: limit.to_string(),
543                current: current_amount.to_string(),
544            })
545        } else {
546            Ok(())
547        }
548    }
549    /// The environment's current credit consumption rate, summed over all user
550    /// cluster replicas except those of `exclude_cluster`.
551    pub(crate) fn current_credit_consumption_rate(
552        &self,
553        exclude_cluster: Option<ClusterId>,
554    ) -> Numeric {
555        self.user_cluster_replicas()
556            .filter(|replica| Some(replica.cluster_id) != exclude_cluster)
557            .filter_map(|replica| match &replica.config.location {
558                ReplicaLocation::Managed(location) => Some(self.replica_credits_per_hour(location)),
559                ReplicaLocation::Unmanaged(_) => None,
560            })
561            .sum()
562    }
563
564    /// The credit rate of a managed replica, read from the size map by its billing size.
565    ///
566    /// An unknown billing size counts as free. DDL validates `SIZE` and `BILLED AS` against
567    /// the map at replica creation, but the map is external configuration and can lose a
568    /// size later. That case is a soft panic rather than a hard one, so that in production
569    /// such a replica can still be dropped from SQL.
570    pub(crate) fn replica_credits_per_hour(&self, location: &ManagedReplicaLocation) -> Numeric {
571        let size = location.size_for_billing();
572        match self.cluster_replica_sizes().0.get(size) {
573            Some(allocation) => allocation.credits_per_hour,
574            None => {
575                soft_panic_or_log!(
576                    "replica of size {:?} bills as unknown replica size {:?}, counting it as free",
577                    location.size,
578                    size,
579                );
580                Numeric::zero()
581            }
582        }
583    }
584}