risingwave_meta/controller/
mod.rs

1// Copyright 2023 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::BTreeMap;
16use std::time::Duration;
17
18use anyhow::{Context, anyhow};
19use risingwave_common::bail;
20use risingwave_common::cast::datetime_to_timestamp_millis;
21use risingwave_common::hash::VnodeCount;
22use risingwave_common::util::epoch::Epoch;
23use risingwave_meta_model::{
24    PrivateLinkService, connection, database, function, index, object, schema, secret, sink,
25    source, subscription, table, view,
26};
27use risingwave_meta_model_migration::{MigrationStatus, Migrator, MigratorTrait};
28use risingwave_pb::catalog::connection::PbInfo as PbConnectionInfo;
29use risingwave_pb::catalog::table::{CdcTableType as PbCdcTableType, PbEngine, PbTableType};
30use risingwave_pb::catalog::{
31    PbConnection, PbCreateType, PbDatabase, PbFunction, PbHandleConflictBehavior, PbIndex,
32    PbSchema, PbSecret, PbSink, PbSinkType, PbSource, PbStreamJobStatus, PbSubscription, PbTable,
33    PbView,
34};
35use sea_orm::{ConnectOptions, DatabaseConnection, DbBackend, ModelTrait};
36
37use crate::{MetaError, MetaResult, MetaStoreBackend};
38
39pub mod catalog;
40pub mod cluster;
41pub mod fragment;
42pub mod id;
43pub mod rename;
44pub mod scale;
45pub mod session_params;
46pub mod streaming_job;
47pub mod system_param;
48pub mod user;
49pub mod utils;
50
51// todo: refine the error transform.
52impl From<sea_orm::DbErr> for MetaError {
53    fn from(err: sea_orm::DbErr) -> Self {
54        if let Some(err) = err.sql_err() {
55            return anyhow!(err).into();
56        }
57        anyhow!(err).into()
58    }
59}
60
61#[derive(Clone)]
62pub struct SqlMetaStore {
63    pub conn: DatabaseConnection,
64    pub endpoint: String,
65}
66
67impl SqlMetaStore {
68    /// Connect to the SQL meta store based on the given configuration.
69    pub async fn connect(backend: MetaStoreBackend) -> MetaResult<Self> {
70        const MAX_DURATION: Duration = Duration::new(u64::MAX / 4, 0);
71
72        #[easy_ext::ext]
73        impl ConnectOptions {
74            /// Apply common settings for `SQLite` connections.
75            fn sqlite_common(&mut self) -> &mut Self {
76                self
77                    // Since Sqlite is prone to the error "(code: 5) database is locked" under concurrent access,
78                    // here we forcibly specify the number of connections as 1.
79                    .min_connections(1)
80                    .max_connections(1)
81                    // Workaround for https://github.com/risingwavelabs/risingwave/issues/18966.
82                    // Note: don't quite get the point but `acquire_timeout` and `connect_timeout` maps to the
83                    //       same underlying setting in `sqlx` under current implementation.
84                    .acquire_timeout(MAX_DURATION)
85                    .connect_timeout(MAX_DURATION)
86            }
87        }
88
89        Ok(match backend {
90            MetaStoreBackend::Mem => {
91                const IN_MEMORY_STORE: &str = "sqlite::memory:";
92
93                let mut options = ConnectOptions::new(IN_MEMORY_STORE);
94
95                options
96                    .sqlite_common()
97                    // Releasing the connection to in-memory SQLite database is unacceptable
98                    // because it will clear the database. Set a large enough timeout to prevent it.
99                    // `sqlx` actually supports disabling these timeouts by passing a `None`, but
100                    // `sea-orm` does not expose this option.
101                    .idle_timeout(MAX_DURATION)
102                    .max_lifetime(MAX_DURATION);
103
104                let conn = sea_orm::Database::connect(options).await?;
105                Self {
106                    conn,
107                    endpoint: IN_MEMORY_STORE.to_owned(),
108                }
109            }
110            MetaStoreBackend::Sql { endpoint, config } => {
111                let mut options = ConnectOptions::new(endpoint.clone());
112                options
113                    .max_connections(config.max_connections)
114                    .min_connections(config.min_connections)
115                    .connect_timeout(Duration::from_secs(config.connection_timeout_sec))
116                    .idle_timeout(Duration::from_secs(config.idle_timeout_sec))
117                    .acquire_timeout(Duration::from_secs(config.acquire_timeout_sec));
118
119                if DbBackend::Sqlite.is_prefix_of(&endpoint) {
120                    if endpoint.contains(":memory:") || endpoint.contains("mode=memory") {
121                        bail!(
122                            "use the `mem` backend instead of specifying a URL of in-memory SQLite"
123                        );
124                    }
125                    options.sqlite_common();
126                }
127
128                let conn = sea_orm::Database::connect(options).await?;
129                Self { conn, endpoint }
130            }
131        })
132    }
133
134    #[cfg(any(test, feature = "test"))]
135    pub async fn for_test() -> Self {
136        let this = Self::connect(MetaStoreBackend::Mem).await.unwrap();
137        Migrator::up(&this.conn, None).await.unwrap();
138        this
139    }
140
141    /// Check whether the cluster, which uses SQL as the backend, is a new cluster.
142    /// It determines this by inspecting the applied migrations. If the migration `m20230908_072257_init` has been applied,
143    /// then it is considered an old cluster.
144    ///
145    /// Note: this check should be performed before [`Self::up()`].
146    async fn is_first_launch(&self) -> MetaResult<bool> {
147        let migrations = Migrator::get_applied_migrations(&self.conn)
148            .await
149            .context("failed to get applied migrations")?;
150        for migration in migrations {
151            if migration.name() == "m20230908_072257_init"
152                && migration.status() == MigrationStatus::Applied
153            {
154                return Ok(false);
155            }
156        }
157        Ok(true)
158    }
159
160    /// Apply all the migrations to the meta store before starting the service.
161    ///
162    /// Returns whether the cluster is the first launch.
163    pub async fn up(&self) -> MetaResult<bool> {
164        let cluster_first_launch = self.is_first_launch().await?;
165        // Try to upgrade if any new model changes are added.
166        Migrator::up(&self.conn, None)
167            .await
168            .context("failed to upgrade models in meta store")?;
169
170        Ok(cluster_first_launch)
171    }
172}
173
174pub struct ObjectModel<M: ModelTrait>(M, object::Model);
175
176impl From<ObjectModel<database::Model>> for PbDatabase {
177    fn from(value: ObjectModel<database::Model>) -> Self {
178        Self {
179            id: value.0.database_id,
180            name: value.0.name,
181            owner: value.1.owner_id as _,
182            resource_group: value.0.resource_group.clone(),
183            barrier_interval_ms: value.0.barrier_interval_ms.map(|v| v as u32),
184            checkpoint_frequency: value.0.checkpoint_frequency.map(|v| v as u64),
185        }
186    }
187}
188
189impl From<ObjectModel<secret::Model>> for PbSecret {
190    fn from(value: ObjectModel<secret::Model>) -> Self {
191        Self {
192            id: value.0.secret_id,
193            name: value.0.name,
194            database_id: value.1.database_id.unwrap(),
195            value: value.0.value,
196            owner: value.1.owner_id as _,
197            schema_id: value.1.schema_id.unwrap(),
198        }
199    }
200}
201
202impl From<ObjectModel<schema::Model>> for PbSchema {
203    fn from(value: ObjectModel<schema::Model>) -> Self {
204        Self {
205            id: value.0.schema_id,
206            name: value.0.name,
207            database_id: value.1.database_id.unwrap(),
208            owner: value.1.owner_id as _,
209        }
210    }
211}
212
213impl From<ObjectModel<table::Model>> for PbTable {
214    fn from(value: ObjectModel<table::Model>) -> Self {
215        Self {
216            id: value.0.table_id,
217            schema_id: value.1.schema_id.unwrap(),
218            database_id: value.1.database_id.unwrap(),
219            name: value.0.name,
220            columns: value.0.columns.to_protobuf(),
221            pk: value.0.pk.to_protobuf(),
222            table_type: PbTableType::from(value.0.table_type) as _,
223            distribution_key: value.0.distribution_key.0,
224            stream_key: value.0.stream_key.0,
225            append_only: value.0.append_only,
226            owner: value.1.owner_id as _,
227            fragment_id: value.0.fragment_id.unwrap_or_default(),
228            vnode_col_index: value.0.vnode_col_index.map(|index| index as _),
229            row_id_index: value.0.row_id_index.map(|index| index as _),
230            value_indices: value.0.value_indices.0,
231            definition: value.0.definition,
232            handle_pk_conflict_behavior: PbHandleConflictBehavior::from(
233                value.0.handle_pk_conflict_behavior,
234            ) as _,
235            version_column_indices: value
236                .0
237                .version_column_indices
238                .unwrap_or_default()
239                .0
240                .iter()
241                .map(|&idx| idx as u32)
242                .collect(),
243            read_prefix_len_hint: value.0.read_prefix_len_hint as _,
244            watermark_indices: value.0.watermark_indices.0,
245            dist_key_in_pk: value.0.dist_key_in_pk.0,
246            dml_fragment_id: value.0.dml_fragment_id,
247            cardinality: value
248                .0
249                .cardinality
250                .map(|cardinality| cardinality.to_protobuf()),
251            initialized_at_epoch: Some(
252                Epoch::from_unix_millis(datetime_to_timestamp_millis(value.1.initialized_at) as _)
253                    .0,
254            ),
255            created_at_epoch: Some(
256                Epoch::from_unix_millis(datetime_to_timestamp_millis(value.1.created_at) as _).0,
257            ),
258            #[expect(deprecated)]
259            cleaned_by_watermark: value.0.cleaned_by_watermark,
260            stream_job_status: PbStreamJobStatus::Created as _,
261            create_type: PbCreateType::Foreground as _,
262            version: value.0.version.map(|v| v.to_protobuf()),
263            optional_associated_source_id: value.0.optional_associated_source_id.map(Into::into),
264            description: value.0.description,
265            #[expect(deprecated)]
266            incoming_sinks: vec![],
267            initialized_at_cluster_version: value.1.initialized_at_cluster_version,
268            created_at_cluster_version: value.1.created_at_cluster_version,
269            retention_seconds: value.0.retention_seconds.map(|id| id as u32),
270            cdc_table_id: value.0.cdc_table_id,
271            maybe_vnode_count: VnodeCount::set(value.0.vnode_count).to_protobuf(),
272            webhook_info: value.0.webhook_info.map(|info| info.to_protobuf()),
273            job_id: value.0.belongs_to_job_id,
274            engine: value.0.engine.map(|engine| PbEngine::from(engine) as i32),
275            #[expect(deprecated)]
276            clean_watermark_index_in_pk: value.0.clean_watermark_index_in_pk,
277            clean_watermark_indices: value
278                .0
279                .clean_watermark_indices
280                .map(|indices| indices.0.iter().map(|&x| x as u32).collect())
281                .unwrap_or_default(),
282            refreshable: value.0.refreshable,
283            vector_index_info: value.0.vector_index_info.map(|index| index.to_protobuf()),
284            cdc_table_type: value
285                .0
286                .cdc_table_type
287                .map(|cdc_type| PbCdcTableType::from(cdc_type) as i32),
288        }
289    }
290}
291
292impl From<ObjectModel<source::Model>> for PbSource {
293    fn from(value: ObjectModel<source::Model>) -> Self {
294        let mut secret_ref_map = BTreeMap::new();
295        if let Some(secret_ref) = value.0.secret_ref {
296            secret_ref_map = secret_ref.to_protobuf();
297        }
298        Self {
299            id: value.0.source_id as _,
300            schema_id: value.1.schema_id.unwrap(),
301            database_id: value.1.database_id.unwrap(),
302            name: value.0.name,
303            row_id_index: value.0.row_id_index.map(|id| id as _),
304            columns: value.0.columns.to_protobuf(),
305            pk_column_ids: value.0.pk_column_ids.0,
306            with_properties: value.0.with_properties.0,
307            owner: value.1.owner_id as _,
308            info: value.0.source_info.map(|info| info.to_protobuf()),
309            watermark_descs: value.0.watermark_descs.to_protobuf(),
310            definition: value.0.definition,
311            connection_id: value.0.connection_id,
312            // todo: using the timestamp from the database directly.
313            initialized_at_epoch: Some(
314                Epoch::from_unix_millis(datetime_to_timestamp_millis(value.1.initialized_at) as _)
315                    .0,
316            ),
317            created_at_epoch: Some(
318                Epoch::from_unix_millis(datetime_to_timestamp_millis(value.1.created_at) as _).0,
319            ),
320            version: value.0.version as _,
321            optional_associated_table_id: value.0.optional_associated_table_id.map(Into::into),
322            initialized_at_cluster_version: value.1.initialized_at_cluster_version,
323            created_at_cluster_version: value.1.created_at_cluster_version,
324            secret_refs: secret_ref_map,
325            rate_limit: value.0.rate_limit.map(|v| v as _),
326            refresh_mode: value
327                .0
328                .refresh_mode
329                .map(|refresh_mode| refresh_mode.to_protobuf()),
330        }
331    }
332}
333
334impl From<ObjectModel<sink::Model>> for PbSink {
335    fn from(value: ObjectModel<sink::Model>) -> Self {
336        let mut secret_ref_map = BTreeMap::new();
337        if let Some(secret_ref) = value.0.secret_ref {
338            secret_ref_map = secret_ref.to_protobuf();
339        }
340        Self {
341            id: value.0.sink_id as _,
342            schema_id: value.1.schema_id.unwrap(),
343            database_id: value.1.database_id.unwrap(),
344            name: value.0.name,
345            columns: value.0.columns.to_protobuf(),
346            plan_pk: value.0.plan_pk.to_protobuf(),
347            distribution_key: value.0.distribution_key.0,
348            downstream_pk: value.0.downstream_pk.0,
349            sink_type: PbSinkType::from(value.0.sink_type) as _,
350            raw_ignore_delete: value.0.ignore_delete,
351            owner: value.1.owner_id as _,
352            properties: value.0.properties.0,
353            definition: value.0.definition,
354            connection_id: value.0.connection_id,
355            initialized_at_epoch: Some(
356                Epoch::from_unix_millis(datetime_to_timestamp_millis(value.1.initialized_at) as _)
357                    .0,
358            ),
359            created_at_epoch: Some(
360                Epoch::from_unix_millis(datetime_to_timestamp_millis(value.1.created_at) as _).0,
361            ),
362            db_name: value.0.db_name,
363            sink_from_name: value.0.sink_from_name,
364            stream_job_status: PbStreamJobStatus::Created as _,
365            format_desc: value.0.sink_format_desc.map(|desc| desc.to_protobuf()),
366            target_table: value.0.target_table,
367            initialized_at_cluster_version: value.1.initialized_at_cluster_version,
368            created_at_cluster_version: value.1.created_at_cluster_version,
369            create_type: PbCreateType::Foreground as _,
370            secret_refs: secret_ref_map,
371            original_target_columns: value
372                .0
373                .original_target_columns
374                .map(|cols| cols.to_protobuf())
375                .unwrap_or_default(),
376            auto_refresh_schema_from_table: value.0.auto_refresh_schema_from_table,
377        }
378    }
379}
380
381impl From<ObjectModel<subscription::Model>> for PbSubscription {
382    fn from(value: ObjectModel<subscription::Model>) -> Self {
383        Self {
384            id: value.0.subscription_id as _,
385            schema_id: value.1.schema_id.unwrap(),
386            database_id: value.1.database_id.unwrap(),
387            name: value.0.name,
388            owner: value.1.owner_id as _,
389            retention_seconds: value.0.retention_seconds as _,
390            definition: value.0.definition,
391            initialized_at_epoch: Some(
392                Epoch::from_unix_millis(datetime_to_timestamp_millis(value.1.initialized_at) as _)
393                    .0,
394            ),
395            created_at_epoch: Some(
396                Epoch::from_unix_millis(datetime_to_timestamp_millis(value.1.created_at) as _).0,
397            ),
398            initialized_at_cluster_version: value.1.initialized_at_cluster_version,
399            created_at_cluster_version: value.1.created_at_cluster_version,
400            dependent_table_id: value.0.dependent_table_id,
401            subscription_state: value.0.subscription_state as _,
402        }
403    }
404}
405
406impl From<ObjectModel<index::Model>> for PbIndex {
407    fn from(value: ObjectModel<index::Model>) -> Self {
408        Self {
409            id: value.0.index_id as _,
410            schema_id: value.1.schema_id.unwrap(),
411            database_id: value.1.database_id.unwrap(),
412            name: value.0.name,
413            owner: value.1.owner_id as _,
414            index_table_id: value.0.index_table_id,
415            primary_table_id: value.0.primary_table_id,
416            index_item: value.0.index_items.to_protobuf(),
417            index_column_properties: value
418                .0
419                .index_column_properties
420                .map(|p| p.to_protobuf())
421                .unwrap_or_default(),
422            index_columns_len: value.0.index_columns_len as _,
423            initialized_at_epoch: Some(
424                Epoch::from_unix_millis(datetime_to_timestamp_millis(value.1.initialized_at) as _)
425                    .0,
426            ),
427            created_at_epoch: Some(
428                Epoch::from_unix_millis(datetime_to_timestamp_millis(value.1.created_at) as _).0,
429            ),
430            stream_job_status: PbStreamJobStatus::Created as _,
431            initialized_at_cluster_version: value.1.initialized_at_cluster_version,
432            created_at_cluster_version: value.1.created_at_cluster_version,
433            create_type: risingwave_pb::catalog::CreateType::Foreground.into(), /* Default for existing indexes */
434        }
435    }
436}
437
438impl From<ObjectModel<view::Model>> for PbView {
439    fn from(value: ObjectModel<view::Model>) -> Self {
440        Self {
441            id: value.0.view_id as _,
442            schema_id: value.1.schema_id.unwrap(),
443            database_id: value.1.database_id.unwrap(),
444            name: value.0.name,
445            owner: value.1.owner_id as _,
446            properties: value.0.properties.0,
447            sql: value.0.definition,
448            columns: value.0.columns.to_protobuf(),
449            created_at_epoch: Some(
450                Epoch::from_unix_millis(datetime_to_timestamp_millis(value.1.created_at) as _).0,
451            ),
452            created_at_cluster_version: value.1.created_at_cluster_version,
453        }
454    }
455}
456
457impl From<ObjectModel<connection::Model>> for PbConnection {
458    fn from(value: ObjectModel<connection::Model>) -> Self {
459        let info: PbConnectionInfo = if value.0.info == PrivateLinkService::default() {
460            PbConnectionInfo::ConnectionParams(value.0.params.to_protobuf())
461        } else {
462            PbConnectionInfo::PrivateLinkService(value.0.info.to_protobuf())
463        };
464        Self {
465            id: value.1.oid.as_connection_id(),
466            schema_id: value.1.schema_id.unwrap(),
467            database_id: value.1.database_id.unwrap(),
468            name: value.0.name,
469            owner: value.1.owner_id as _,
470            info: Some(info),
471        }
472    }
473}
474
475impl From<ObjectModel<function::Model>> for PbFunction {
476    fn from(value: ObjectModel<function::Model>) -> Self {
477        Self {
478            id: value.0.function_id as _,
479            schema_id: value.1.schema_id.unwrap(),
480            database_id: value.1.database_id.unwrap(),
481            name: value.0.name,
482            owner: value.1.owner_id as _,
483            arg_names: value.0.arg_names.split(',').map(|s| s.to_owned()).collect(),
484            arg_types: value.0.arg_types.to_protobuf(),
485            return_type: Some(value.0.return_type.to_protobuf()),
486            language: value.0.language,
487            runtime: value.0.runtime,
488            link: value.0.link,
489            name_in_runtime: value.0.name_in_runtime,
490            body: value.0.body,
491            compressed_binary: value.0.compressed_binary,
492            kind: Some(value.0.kind.into()),
493            always_retry_on_network_error: value.0.always_retry_on_network_error,
494            is_async: value
495                .0
496                .options
497                .as_ref()
498                .and_then(|o| o.0.get("async").map(|v| v == "true")),
499            is_batched: value
500                .0
501                .options
502                .as_ref()
503                .and_then(|o| o.0.get("batch").map(|v| v == "true")),
504            created_at_epoch: Some(
505                Epoch::from_unix_millis(datetime_to_timestamp_millis(value.1.created_at) as _).0,
506            ),
507            created_at_cluster_version: value.1.created_at_cluster_version,
508        }
509    }
510}