Skip to main content

risingwave_frontend/
test_utils.rs

1// Copyright 2022 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, HashMap, HashSet};
16use std::io::Write;
17use std::net::{IpAddr, Ipv4Addr, SocketAddr};
18use std::sync::Arc;
19use std::sync::atomic::{AtomicU32, Ordering};
20
21use futures_async_stream::for_await;
22use parking_lot::RwLock;
23use pgwire::net::{Address, AddressRef};
24use pgwire::pg_response::StatementType;
25use pgwire::pg_server::{SessionId, SessionManager, UserAuthenticator};
26use pgwire::types::Row;
27use risingwave_common::catalog::{
28    AlterDatabaseParam, DEFAULT_DATABASE_NAME, DEFAULT_SCHEMA_NAME, DEFAULT_SUPER_USER,
29    DEFAULT_SUPER_USER_FOR_ADMIN, DEFAULT_SUPER_USER_FOR_ADMIN_ID, DEFAULT_SUPER_USER_ID,
30    FunctionId, IndexId, NON_RESERVED_USER_ID, ObjectId, PG_CATALOG_SCHEMA_NAME,
31    RW_CATALOG_SCHEMA_NAME, TableId,
32};
33use risingwave_common::config::FrontendConfig;
34use risingwave_common::hash::{VirtualNode, VnodeCount, VnodeCountCompat};
35use risingwave_common::id::{ConnectionId, JobId, SourceId, SubscriptionId, ViewId, WorkerId};
36use risingwave_common::session_config::SessionConfig;
37use risingwave_common::system_param::AdaptiveParallelismStrategy;
38use risingwave_common::system_param::reader::SystemParamsReader;
39use risingwave_common::util::cluster_limit::ClusterLimit;
40use risingwave_common::util::worker_util::DEFAULT_RESOURCE_GROUP;
41use risingwave_hummock_sdk::change_log::TableChangeLogs;
42use risingwave_hummock_sdk::version::{HummockVersion, HummockVersionDelta};
43use risingwave_hummock_sdk::{CompactionGroupId, HummockVersionId, INVALID_VERSION_ID};
44use risingwave_pb::backup_service::MetaSnapshotMetadata;
45use risingwave_pb::catalog::{
46    PbComment, PbDatabase, PbFunction, PbIndex, PbSchema, PbSink, PbSource, PbStreamJobStatus,
47    PbSubscription, PbTable, PbView, Table,
48};
49use risingwave_pb::common::{PbObjectType, WorkerNode};
50use risingwave_pb::ddl_service::alter_owner_request::Object;
51use risingwave_pb::ddl_service::create_iceberg_table_request::{PbSinkJobInfo, PbTableJobInfo};
52use risingwave_pb::ddl_service::{
53    DdlProgress, PbTableJobType, TableJobType, alter_name_request, alter_set_schema_request,
54    alter_swap_rename_request, create_connection_request, streaming_job_resource_type,
55};
56use risingwave_pb::hummock::rise_ctl_update_compaction_config_request::mutable_config::MutableConfig as PbMutableConfig;
57use risingwave_pb::hummock::write_limits::WriteLimit;
58use risingwave_pb::hummock::{
59    BranchedObject, CompactTaskAssignment, CompactTaskProgress, CompactionGroupInfo,
60};
61use risingwave_pb::id::ActorId;
62use risingwave_pb::meta::cancel_creating_jobs_request::PbJobs;
63use risingwave_pb::meta::list_actor_splits_response::ActorSplit;
64use risingwave_pb::meta::list_actor_states_response::ActorState;
65use risingwave_pb::meta::list_cdc_progress_response::PbCdcProgress;
66use risingwave_pb::meta::list_iceberg_compaction_status_response::IcebergCompactionStatus;
67use risingwave_pb::meta::list_iceberg_tables_response::IcebergTable;
68use risingwave_pb::meta::list_rate_limits_response::RateLimitInfo;
69use risingwave_pb::meta::list_refresh_table_states_response::RefreshTableState;
70use risingwave_pb::meta::list_streaming_job_states_response::StreamingJobState;
71use risingwave_pb::meta::list_table_fragments_response::TableFragmentInfo;
72use risingwave_pb::meta::{
73    EventLog, FragmentDistribution, ObjectDependency as PbObjectDependency, PbTableParallelism,
74    PbThrottleTarget, RecoveryStatus, RefreshRequest, RefreshResponse, SystemParams,
75    list_sink_log_store_tables_response,
76};
77use risingwave_pb::secret::PbSecretRef;
78use risingwave_pb::stream_plan::StreamFragmentGraph;
79use risingwave_pb::user::alter_default_privilege_request::Operation as AlterDefaultPrivilegeOperation;
80use risingwave_pb::user::update_user_request::UpdateField;
81use risingwave_pb::user::{GrantPrivilege, UserInfo};
82use risingwave_rpc_client::error::Result as RpcResult;
83use tempfile::{Builder, NamedTempFile};
84
85use crate::FrontendOpts;
86use crate::catalog::catalog_service::CatalogWriter;
87use crate::catalog::root_catalog::Catalog;
88use crate::catalog::{DatabaseId, FragmentId, SchemaId, SecretId, SinkId};
89use crate::error::{ErrorCode, Result, RwError};
90use crate::handler::RwPgResponse;
91use crate::meta_client::FrontendMetaClient;
92use crate::scheduler::HummockSnapshotManagerRef;
93use crate::session::{AuthContext, FrontendEnv, SessionImpl};
94use crate::user::UserId;
95use crate::user::user_manager::UserInfoManager;
96use crate::user::user_service::UserInfoWriter;
97
98/// An embedded frontend without starting meta and without starting frontend as a tcp server.
99pub struct LocalFrontend {
100    pub opts: FrontendOpts,
101    env: FrontendEnv,
102}
103
104impl SessionManager for LocalFrontend {
105    type Error = RwError;
106    type Session = SessionImpl;
107
108    fn create_dummy_session(
109        &self,
110        _database_id: DatabaseId,
111    ) -> std::result::Result<Arc<Self::Session>, Self::Error> {
112        unreachable!()
113    }
114
115    fn connect(
116        &self,
117        _database: &str,
118        _user_name: &str,
119        _peer_addr: AddressRef,
120    ) -> std::result::Result<Arc<Self::Session>, Self::Error> {
121        Ok(self.session_ref())
122    }
123
124    fn cancel_queries_in_session(&self, _session_id: SessionId) {
125        unreachable!()
126    }
127
128    fn cancel_creating_jobs_in_session(&self, _session_id: SessionId) {
129        unreachable!()
130    }
131
132    fn end_session(&self, _session: &Self::Session) {
133        unreachable!()
134    }
135}
136
137impl LocalFrontend {
138    #[expect(clippy::unused_async)]
139    pub async fn new(opts: FrontendOpts) -> Self {
140        let env = FrontendEnv::mock();
141        Self { opts, env }
142    }
143
144    #[expect(clippy::unused_async)]
145    pub async fn with_frontend_config(opts: FrontendOpts, frontend_config: FrontendConfig) -> Self {
146        let mut env = FrontendEnv::mock();
147        env.set_frontend_config_for_test(frontend_config);
148        Self { opts, env }
149    }
150
151    pub async fn run_sql(
152        &self,
153        sql: impl Into<String>,
154    ) -> std::result::Result<RwPgResponse, Box<dyn std::error::Error + Send + Sync>> {
155        let sql: Arc<str> = Arc::from(sql.into());
156        Box::pin(self.session_ref().run_statement(sql, vec![])).await
157    }
158
159    pub async fn run_sql_with_session(
160        &self,
161        session_ref: Arc<SessionImpl>,
162        sql: impl Into<String>,
163    ) -> std::result::Result<RwPgResponse, Box<dyn std::error::Error + Send + Sync>> {
164        let sql: Arc<str> = Arc::from(sql.into());
165        Box::pin(session_ref.run_statement(sql, vec![])).await
166    }
167
168    pub async fn run_user_sql(
169        &self,
170        sql: impl Into<String>,
171        database: String,
172        user_name: String,
173        user_id: UserId,
174    ) -> std::result::Result<RwPgResponse, Box<dyn std::error::Error + Send + Sync>> {
175        let sql: Arc<str> = Arc::from(sql.into());
176        Box::pin(
177            self.session_user_ref(database, user_name, user_id)
178                .run_statement(sql, vec![]),
179        )
180        .await
181    }
182
183    pub async fn query_formatted_result(&self, sql: impl Into<String>) -> Vec<String> {
184        let mut rsp = self.run_sql(sql).await.unwrap();
185        let mut res = vec![];
186        #[for_await]
187        for row_set in rsp.values_stream() {
188            for row in row_set.unwrap() {
189                res.push(format!("{:?}", row));
190            }
191        }
192        res
193    }
194
195    pub async fn get_explain_output(&self, sql: impl Into<String>) -> String {
196        let mut rsp = self.run_sql(sql).await.unwrap();
197        assert_eq!(rsp.stmt_type(), StatementType::EXPLAIN);
198        let mut res = String::new();
199        #[for_await]
200        for row_set in rsp.values_stream() {
201            for row in row_set.unwrap() {
202                let row: Row = row;
203                let row = row.values()[0].as_ref().unwrap();
204                res += std::str::from_utf8(row).unwrap();
205                res += "\n";
206            }
207        }
208        res
209    }
210
211    /// Creates a new session
212    pub fn session_ref(&self) -> Arc<SessionImpl> {
213        self.session_user_ref(
214            DEFAULT_DATABASE_NAME.to_owned(),
215            DEFAULT_SUPER_USER.to_owned(),
216            DEFAULT_SUPER_USER_ID,
217        )
218    }
219
220    pub fn session_user_ref(
221        &self,
222        database: String,
223        user_name: String,
224        user_id: UserId,
225    ) -> Arc<SessionImpl> {
226        Arc::new(SessionImpl::new(
227            self.env.clone(),
228            AuthContext::new(database, user_name, user_id),
229            UserAuthenticator::None,
230            // Local Frontend use a non-sense id.
231            (0, 0),
232            Address::Tcp(SocketAddr::new(
233                IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
234                6666,
235            ))
236            .into(),
237            Default::default(),
238        ))
239    }
240}
241
242pub async fn get_explain_output(mut rsp: RwPgResponse) -> String {
243    if rsp.stmt_type() != StatementType::EXPLAIN {
244        panic!("RESPONSE INVALID: {rsp:?}");
245    }
246    let mut res = String::new();
247    #[for_await]
248    for row_set in rsp.values_stream() {
249        for row in row_set.unwrap() {
250            let row: Row = row;
251            let row = row.values()[0].as_ref().unwrap();
252            res += std::str::from_utf8(row).unwrap();
253            res += "\n";
254        }
255    }
256    res
257}
258
259pub struct MockCatalogWriter {
260    catalog: Arc<RwLock<Catalog>>,
261    id: AtomicU32,
262    table_id_to_schema_id: RwLock<HashMap<u32, SchemaId>>,
263    schema_id_to_database_id: RwLock<HashMap<SchemaId, DatabaseId>>,
264    hummock_snapshot_manager: HummockSnapshotManagerRef,
265}
266
267#[async_trait::async_trait]
268impl CatalogWriter for MockCatalogWriter {
269    async fn create_database(
270        &self,
271        db_name: &str,
272        owner: UserId,
273        resource_group: &str,
274        barrier_interval_ms: Option<u32>,
275        checkpoint_frequency: Option<u64>,
276    ) -> Result<()> {
277        let database_id = DatabaseId::new(self.gen_id());
278        self.catalog.write().create_database(&PbDatabase {
279            name: db_name.to_owned(),
280            id: database_id,
281            owner,
282            resource_group: resource_group.to_owned(),
283            barrier_interval_ms,
284            checkpoint_frequency,
285        });
286        self.create_schema(database_id, DEFAULT_SCHEMA_NAME, owner)
287            .await?;
288        self.create_schema(database_id, PG_CATALOG_SCHEMA_NAME, owner)
289            .await?;
290        self.create_schema(database_id, RW_CATALOG_SCHEMA_NAME, owner)
291            .await?;
292        Ok(())
293    }
294
295    async fn create_schema(
296        &self,
297        db_id: DatabaseId,
298        schema_name: &str,
299        owner: UserId,
300    ) -> Result<()> {
301        let id = self.gen_id();
302        self.catalog.write().create_schema(&PbSchema {
303            id,
304            name: schema_name.to_owned(),
305            database_id: db_id,
306            owner,
307        });
308        self.add_schema_id(id, db_id);
309        Ok(())
310    }
311
312    async fn create_materialized_view(
313        &self,
314        mut table: PbTable,
315        _graph: StreamFragmentGraph,
316        dependencies: HashSet<ObjectId>,
317        _resource_type: streaming_job_resource_type::ResourceType,
318        _if_not_exists: bool,
319        _refresh_interval_sec: Option<u64>,
320    ) -> Result<()> {
321        table.id = self.gen_id();
322        table.stream_job_status = PbStreamJobStatus::Created as _;
323        table.maybe_vnode_count = VnodeCount::for_test().to_protobuf();
324        self.catalog.write().create_table(&table);
325        self.add_table_or_source_id(table.id.as_raw_id(), table.schema_id, table.database_id);
326        self.insert_object_dependencies(table.id.as_object_id(), dependencies);
327        self.hummock_snapshot_manager.add_table_for_test(table.id);
328        Ok(())
329    }
330
331    async fn replace_materialized_view(
332        &self,
333        mut table: PbTable,
334        _graph: StreamFragmentGraph,
335    ) -> Result<()> {
336        table.stream_job_status = PbStreamJobStatus::Created as _;
337        assert_eq!(table.vnode_count(), VirtualNode::COUNT_FOR_TEST);
338        self.catalog.write().update_table(&table);
339        Ok(())
340    }
341
342    async fn create_view(&self, mut view: PbView, dependencies: HashSet<ObjectId>) -> Result<()> {
343        view.id = self.gen_id();
344        self.catalog.write().create_view(&view);
345        self.add_table_or_source_id(view.id.as_raw_id(), view.schema_id, view.database_id);
346        self.insert_object_dependencies(view.id.as_object_id(), dependencies);
347        Ok(())
348    }
349
350    async fn create_table(
351        &self,
352        source: Option<PbSource>,
353        mut table: PbTable,
354        graph: StreamFragmentGraph,
355        _job_type: PbTableJobType,
356        if_not_exists: bool,
357        dependencies: HashSet<ObjectId>,
358    ) -> Result<()> {
359        if let Some(source) = source {
360            let source_id = self.create_source_inner(source)?;
361            table.optional_associated_source_id = Some(source_id.into());
362        }
363        self.create_materialized_view(
364            table,
365            graph,
366            dependencies,
367            streaming_job_resource_type::ResourceType::Regular(true),
368            if_not_exists,
369            None,
370        )
371        .await?;
372        Ok(())
373    }
374
375    async fn replace_table(
376        &self,
377        _source: Option<PbSource>,
378        mut table: PbTable,
379        _graph: StreamFragmentGraph,
380        _job_type: TableJobType,
381    ) -> Result<()> {
382        table.stream_job_status = PbStreamJobStatus::Created as _;
383        assert_eq!(table.vnode_count(), VirtualNode::COUNT_FOR_TEST);
384        self.catalog.write().update_table(&table);
385        Ok(())
386    }
387
388    async fn replace_source(&self, source: PbSource, _graph: StreamFragmentGraph) -> Result<()> {
389        self.catalog.write().update_source(&source);
390        Ok(())
391    }
392
393    async fn create_source(
394        &self,
395        source: PbSource,
396        _graph: Option<StreamFragmentGraph>,
397        _if_not_exists: bool,
398    ) -> Result<()> {
399        self.create_source_inner(source).map(|_| ())
400    }
401
402    async fn create_sink(
403        &self,
404        sink: PbSink,
405        graph: StreamFragmentGraph,
406        dependencies: HashSet<ObjectId>,
407        _resource_type: streaming_job_resource_type::ResourceType,
408        _if_not_exists: bool,
409        _since_timestamp_epoch: Option<u64>,
410    ) -> Result<()> {
411        let sink_id = self.create_sink_inner(sink, graph)?;
412        self.insert_object_dependencies(sink_id.as_object_id(), dependencies);
413        Ok(())
414    }
415
416    async fn replace_sink(
417        &self,
418        old_sink_id: SinkId,
419        sink: PbSink,
420        graph: StreamFragmentGraph,
421        _dependencies: HashSet<ObjectId>,
422        _resource_type: streaming_job_resource_type::ResourceType,
423    ) -> Result<()> {
424        let (database_id, schema_id) = self.drop_table_or_sink_id(old_sink_id.as_raw_id());
425        self.catalog
426            .write()
427            .drop_sink(database_id, schema_id, old_sink_id);
428        self.create_sink_inner(sink, graph)?;
429        Ok(())
430    }
431
432    async fn create_subscription(&self, subscription: PbSubscription) -> Result<()> {
433        self.create_subscription_inner(subscription)
434    }
435
436    async fn create_index(
437        &self,
438        mut index: PbIndex,
439        mut index_table: PbTable,
440        _graph: StreamFragmentGraph,
441        _resource_type: streaming_job_resource_type::ResourceType,
442        _if_not_exists: bool,
443    ) -> Result<()> {
444        index_table.id = self.gen_id();
445        index_table.stream_job_status = PbStreamJobStatus::Created as _;
446        index_table.maybe_vnode_count = VnodeCount::for_test().to_protobuf();
447        self.catalog.write().create_table(&index_table);
448        self.add_table_or_index_id(
449            index_table.id.as_raw_id(),
450            index_table.schema_id,
451            index_table.database_id,
452        );
453
454        index.id = index_table.id.as_raw_id().into();
455        index.index_table_id = index_table.id;
456        self.catalog.write().create_index(&index);
457        Ok(())
458    }
459
460    async fn create_function(&self, _function: PbFunction) -> Result<()> {
461        unreachable!()
462    }
463
464    async fn create_connection(
465        &self,
466        _connection_name: String,
467        _database_id: DatabaseId,
468        _schema_id: SchemaId,
469        _owner_id: UserId,
470        _connection: create_connection_request::Payload,
471    ) -> Result<()> {
472        unreachable!()
473    }
474
475    async fn create_secret(
476        &self,
477        _secret_name: String,
478        _database_id: DatabaseId,
479        _schema_id: SchemaId,
480        _owner_id: UserId,
481        _payload: Vec<u8>,
482    ) -> Result<()> {
483        unreachable!()
484    }
485
486    async fn comment_on(&self, _comment: PbComment) -> Result<()> {
487        unreachable!()
488    }
489
490    async fn drop_table(
491        &self,
492        source_id: Option<SourceId>,
493        table_id: TableId,
494        cascade: bool,
495    ) -> Result<()> {
496        if cascade {
497            return Err(ErrorCode::NotSupported(
498                "drop cascade in MockCatalogWriter is unsupported".to_owned(),
499                "use drop instead".to_owned(),
500            )
501            .into());
502        }
503        if let Some(source_id) = source_id {
504            self.drop_table_or_source_id(source_id.as_raw_id());
505        }
506        let (database_id, schema_id) = self.drop_table_or_source_id(table_id.as_raw_id());
507        let indexes =
508            self.catalog
509                .read()
510                .get_all_indexes_related_to_object(database_id, schema_id, table_id);
511        for index in indexes {
512            self.drop_index(index.id, cascade).await?;
513        }
514        self.catalog
515            .write()
516            .drop_table(database_id, schema_id, table_id);
517        if let Some(source_id) = source_id {
518            self.catalog
519                .write()
520                .drop_source(database_id, schema_id, source_id);
521        }
522        Ok(())
523    }
524
525    async fn drop_view(&self, _view_id: ViewId, _cascade: bool) -> Result<()> {
526        unreachable!()
527    }
528
529    async fn drop_materialized_view(&self, table_id: TableId, cascade: bool) -> Result<()> {
530        if cascade {
531            return Err(ErrorCode::NotSupported(
532                "drop cascade in MockCatalogWriter is unsupported".to_owned(),
533                "use drop instead".to_owned(),
534            )
535            .into());
536        }
537        let (database_id, schema_id) = self.drop_table_or_source_id(table_id.as_raw_id());
538        let indexes =
539            self.catalog
540                .read()
541                .get_all_indexes_related_to_object(database_id, schema_id, table_id);
542        for index in indexes {
543            self.drop_index(index.id, cascade).await?;
544        }
545        self.catalog
546            .write()
547            .drop_table(database_id, schema_id, table_id);
548        Ok(())
549    }
550
551    async fn drop_source(&self, source_id: SourceId, cascade: bool) -> Result<()> {
552        if cascade {
553            return Err(ErrorCode::NotSupported(
554                "drop cascade in MockCatalogWriter is unsupported".to_owned(),
555                "use drop instead".to_owned(),
556            )
557            .into());
558        }
559        let (database_id, schema_id) = self.drop_table_or_source_id(source_id.as_raw_id());
560        self.catalog
561            .write()
562            .drop_source(database_id, schema_id, source_id);
563        Ok(())
564    }
565
566    async fn reset_source(&self, _source_id: SourceId) -> Result<()> {
567        Ok(())
568    }
569
570    async fn drop_sink(&self, sink_id: SinkId, cascade: bool) -> Result<()> {
571        if cascade {
572            return Err(ErrorCode::NotSupported(
573                "drop cascade in MockCatalogWriter is unsupported".to_owned(),
574                "use drop instead".to_owned(),
575            )
576            .into());
577        }
578        let (database_id, schema_id) = self.drop_table_or_sink_id(sink_id.as_raw_id());
579        self.catalog
580            .write()
581            .drop_sink(database_id, schema_id, sink_id);
582        Ok(())
583    }
584
585    async fn drop_subscription(
586        &self,
587        subscription_id: SubscriptionId,
588        cascade: bool,
589    ) -> Result<()> {
590        if cascade {
591            return Err(ErrorCode::NotSupported(
592                "drop cascade in MockCatalogWriter is unsupported".to_owned(),
593                "use drop instead".to_owned(),
594            )
595            .into());
596        }
597        let (database_id, schema_id) =
598            self.drop_table_or_subscription_id(subscription_id.as_raw_id());
599        self.catalog
600            .write()
601            .drop_subscription(database_id, schema_id, subscription_id);
602        Ok(())
603    }
604
605    async fn drop_index(&self, index_id: IndexId, cascade: bool) -> Result<()> {
606        if cascade {
607            return Err(ErrorCode::NotSupported(
608                "drop cascade in MockCatalogWriter is unsupported".to_owned(),
609                "use drop instead".to_owned(),
610            )
611            .into());
612        }
613        let &schema_id = self
614            .table_id_to_schema_id
615            .read()
616            .get(&index_id.as_raw_id())
617            .unwrap();
618        let database_id = self.get_database_id_by_schema(schema_id);
619
620        let index = {
621            let catalog_reader = self.catalog.read();
622            let schema_catalog = catalog_reader
623                .get_schema_by_id(database_id, schema_id)
624                .unwrap();
625            schema_catalog.get_index_by_id(index_id).unwrap().clone()
626        };
627
628        let index_table_id = index.index_table().id;
629        let (database_id, schema_id) = self.drop_table_or_index_id(index_id.as_raw_id());
630        self.catalog
631            .write()
632            .drop_index(database_id, schema_id, index_id);
633        self.catalog
634            .write()
635            .drop_table(database_id, schema_id, index_table_id);
636        Ok(())
637    }
638
639    async fn drop_function(&self, _function_id: FunctionId, _cascade: bool) -> Result<()> {
640        unreachable!()
641    }
642
643    async fn drop_connection(&self, _connection_id: ConnectionId, _cascade: bool) -> Result<()> {
644        unreachable!()
645    }
646
647    async fn drop_secret(&self, _secret_id: SecretId, _cascade: bool) -> Result<()> {
648        unreachable!()
649    }
650
651    async fn drop_database(&self, database_id: DatabaseId) -> Result<()> {
652        self.catalog.write().drop_database(database_id);
653        Ok(())
654    }
655
656    async fn drop_schema(&self, schema_id: SchemaId, _cascade: bool) -> Result<()> {
657        let database_id = self.drop_schema_id(schema_id);
658        self.catalog.write().drop_schema(database_id, schema_id);
659        Ok(())
660    }
661
662    async fn alter_name(
663        &self,
664        object_id: alter_name_request::Object,
665        object_name: &str,
666    ) -> Result<()> {
667        match object_id {
668            alter_name_request::Object::TableId(table_id) => {
669                self.catalog
670                    .write()
671                    .alter_table_name_by_id(table_id, object_name);
672                Ok(())
673            }
674            _ => {
675                unimplemented!()
676            }
677        }
678    }
679
680    async fn alter_source(&self, source: PbSource) -> Result<()> {
681        self.catalog.write().update_source(&source);
682        Ok(())
683    }
684
685    async fn alter_owner(&self, object: Object, owner_id: UserId) -> Result<()> {
686        for database in self.catalog.read().iter_databases() {
687            for schema in database.iter_schemas() {
688                match object {
689                    Object::TableId(table_id) => {
690                        if let Some(table) = schema.get_created_table_by_id(TableId::from(table_id))
691                        {
692                            let mut pb_table = table.to_prost();
693                            pb_table.owner = owner_id;
694                            self.catalog.write().update_table(&pb_table);
695                            return Ok(());
696                        }
697                    }
698                    _ => unreachable!(),
699                }
700            }
701        }
702
703        Err(ErrorCode::ItemNotFound(format!("object not found: {:?}", object)).into())
704    }
705
706    async fn alter_subscription_retention(
707        &self,
708        subscription_id: SubscriptionId,
709        retention_seconds: u64,
710        definition: String,
711    ) -> Result<()> {
712        for database in self.catalog.read().iter_databases() {
713            for schema in database.iter_schemas() {
714                if let Some(subscription) = schema.get_subscription_by_id(subscription_id) {
715                    let mut pb_subscription = subscription.to_proto();
716                    pb_subscription.retention_seconds = retention_seconds;
717                    pb_subscription.definition = definition;
718                    self.catalog.write().update_subscription(&pb_subscription);
719                    return Ok(());
720                }
721            }
722        }
723
724        Err(
725            ErrorCode::ItemNotFound(format!("subscription not found: {:?}", subscription_id))
726                .into(),
727        )
728    }
729
730    async fn alter_set_schema(
731        &self,
732        object: alter_set_schema_request::Object,
733        new_schema_id: SchemaId,
734    ) -> Result<()> {
735        match object {
736            alter_set_schema_request::Object::TableId(table_id) => {
737                let mut pb_table = {
738                    let reader = self.catalog.read();
739                    let table = reader.get_any_table_by_id(table_id)?.to_owned();
740                    table.to_prost()
741                };
742                pb_table.schema_id = new_schema_id;
743                self.catalog.write().update_table(&pb_table);
744                self.table_id_to_schema_id
745                    .write()
746                    .insert(table_id.as_raw_id(), new_schema_id);
747                Ok(())
748            }
749            _ => unreachable!(),
750        }
751    }
752
753    async fn alter_parallelism(
754        &self,
755        _job_id: JobId,
756        _parallelism: PbTableParallelism,
757        _adaptive_parallelism_strategy: Option<AdaptiveParallelismStrategy>,
758        _deferred: bool,
759    ) -> Result<()> {
760        todo!()
761    }
762
763    async fn alter_backfill_parallelism(
764        &self,
765        _job_id: JobId,
766        _parallelism: Option<PbTableParallelism>,
767        _adaptive_parallelism_strategy: Option<AdaptiveParallelismStrategy>,
768        _deferred: bool,
769    ) -> Result<()> {
770        todo!()
771    }
772
773    async fn alter_config(
774        &self,
775        _job_id: JobId,
776        _entries_to_add: HashMap<String, String>,
777        _keys_to_remove: Vec<String>,
778    ) -> Result<()> {
779        todo!()
780    }
781
782    async fn alter_swap_rename(&self, _object: alter_swap_rename_request::Object) -> Result<()> {
783        todo!()
784    }
785
786    async fn alter_secret(
787        &self,
788        _secret_id: SecretId,
789        _secret_name: String,
790        _database_id: DatabaseId,
791        _schema_id: SchemaId,
792        _owner_id: UserId,
793        _payload: Vec<u8>,
794    ) -> Result<()> {
795        unreachable!()
796    }
797
798    async fn alter_resource_group(
799        &self,
800        _job_id: JobId,
801        _resource_group: Option<String>,
802        _deferred: bool,
803    ) -> Result<()> {
804        todo!()
805    }
806
807    async fn alter_database_resource_group(
808        &self,
809        database_id: DatabaseId,
810        resource_group: Option<String>,
811        _deferred: bool,
812    ) -> Result<()> {
813        let mut pb_database = {
814            let reader = self.catalog.read();
815            let database = reader.get_database_by_id(database_id)?.to_owned();
816            database.to_prost()
817        };
818        pb_database.resource_group =
819            resource_group.unwrap_or_else(|| DEFAULT_RESOURCE_GROUP.to_owned());
820        self.catalog.write().update_database(&pb_database);
821        Ok(())
822    }
823
824    async fn alter_database_param(
825        &self,
826        database_id: DatabaseId,
827        param: AlterDatabaseParam,
828    ) -> Result<()> {
829        let mut pb_database = {
830            let reader = self.catalog.read();
831            let database = reader.get_database_by_id(database_id)?.to_owned();
832            database.to_prost()
833        };
834        match param {
835            AlterDatabaseParam::BarrierIntervalMs(interval) => {
836                pb_database.barrier_interval_ms = interval;
837            }
838            AlterDatabaseParam::CheckpointFrequency(frequency) => {
839                pb_database.checkpoint_frequency = frequency;
840            }
841        }
842        self.catalog.write().update_database(&pb_database);
843        Ok(())
844    }
845
846    async fn create_iceberg_table(
847        &self,
848        _table_job_info: PbTableJobInfo,
849        _sink_job_info: PbSinkJobInfo,
850        _iceberg_source: PbSource,
851        _if_not_exists: bool,
852    ) -> Result<()> {
853        todo!()
854    }
855
856    async fn wait(&self, _job_id: Option<JobId>) -> Result<()> {
857        Ok(())
858    }
859}
860
861impl MockCatalogWriter {
862    pub fn new(
863        catalog: Arc<RwLock<Catalog>>,
864        hummock_snapshot_manager: HummockSnapshotManagerRef,
865    ) -> Self {
866        catalog.write().create_database(&PbDatabase {
867            id: 0.into(),
868            name: DEFAULT_DATABASE_NAME.to_owned(),
869            owner: DEFAULT_SUPER_USER_ID,
870            resource_group: DEFAULT_RESOURCE_GROUP.to_owned(),
871            barrier_interval_ms: None,
872            checkpoint_frequency: None,
873        });
874        catalog.write().create_schema(&PbSchema {
875            id: 1.into(),
876            name: DEFAULT_SCHEMA_NAME.to_owned(),
877            database_id: 0.into(),
878            owner: DEFAULT_SUPER_USER_ID,
879        });
880        catalog.write().create_schema(&PbSchema {
881            id: 2.into(),
882            name: PG_CATALOG_SCHEMA_NAME.to_owned(),
883            database_id: 0.into(),
884            owner: DEFAULT_SUPER_USER_ID,
885        });
886        catalog.write().create_schema(&PbSchema {
887            id: 3.into(),
888            name: RW_CATALOG_SCHEMA_NAME.to_owned(),
889            database_id: 0.into(),
890            owner: DEFAULT_SUPER_USER_ID,
891        });
892        let mut map: HashMap<SchemaId, DatabaseId> = HashMap::new();
893        map.insert(1_u32.into(), 0_u32.into());
894        map.insert(2_u32.into(), 0_u32.into());
895        map.insert(3_u32.into(), 0_u32.into());
896        Self {
897            catalog,
898            id: AtomicU32::new(3),
899            table_id_to_schema_id: Default::default(),
900            schema_id_to_database_id: RwLock::new(map),
901            hummock_snapshot_manager,
902        }
903    }
904
905    fn gen_id<T: From<u32>>(&self) -> T {
906        // Since the 0 value is `dev` schema and database, so jump out the 0 value.
907        (self.id.fetch_add(1, Ordering::SeqCst) + 1).into()
908    }
909
910    fn add_table_or_source_id(&self, table_id: u32, schema_id: SchemaId, _database_id: DatabaseId) {
911        self.table_id_to_schema_id
912            .write()
913            .insert(table_id, schema_id);
914    }
915
916    fn drop_table_or_source_id(&self, table_id: u32) -> (DatabaseId, SchemaId) {
917        let schema_id = self
918            .table_id_to_schema_id
919            .write()
920            .remove(&table_id)
921            .unwrap();
922        (self.get_database_id_by_schema(schema_id), schema_id)
923    }
924
925    fn add_table_or_sink_id(&self, table_id: u32, schema_id: SchemaId, _database_id: DatabaseId) {
926        self.table_id_to_schema_id
927            .write()
928            .insert(table_id, schema_id);
929    }
930
931    fn add_table_or_subscription_id(
932        &self,
933        table_id: u32,
934        schema_id: SchemaId,
935        _database_id: DatabaseId,
936    ) {
937        self.table_id_to_schema_id
938            .write()
939            .insert(table_id, schema_id);
940    }
941
942    fn add_table_or_index_id(&self, table_id: u32, schema_id: SchemaId, _database_id: DatabaseId) {
943        self.table_id_to_schema_id
944            .write()
945            .insert(table_id, schema_id);
946    }
947
948    fn drop_table_or_sink_id(&self, table_id: u32) -> (DatabaseId, SchemaId) {
949        let schema_id = self
950            .table_id_to_schema_id
951            .write()
952            .remove(&table_id)
953            .unwrap();
954        (self.get_database_id_by_schema(schema_id), schema_id)
955    }
956
957    fn drop_table_or_subscription_id(&self, table_id: u32) -> (DatabaseId, SchemaId) {
958        let schema_id = self
959            .table_id_to_schema_id
960            .write()
961            .remove(&table_id)
962            .unwrap();
963        (self.get_database_id_by_schema(schema_id), schema_id)
964    }
965
966    fn drop_table_or_index_id(&self, table_id: u32) -> (DatabaseId, SchemaId) {
967        let schema_id = self
968            .table_id_to_schema_id
969            .write()
970            .remove(&table_id)
971            .unwrap();
972        (self.get_database_id_by_schema(schema_id), schema_id)
973    }
974
975    fn add_schema_id(&self, schema_id: SchemaId, database_id: DatabaseId) {
976        self.schema_id_to_database_id
977            .write()
978            .insert(schema_id, database_id);
979    }
980
981    fn drop_schema_id(&self, schema_id: SchemaId) -> DatabaseId {
982        self.schema_id_to_database_id
983            .write()
984            .remove(&schema_id)
985            .unwrap()
986    }
987
988    fn create_source_inner(&self, mut source: PbSource) -> Result<SourceId> {
989        source.id = self.gen_id();
990        self.catalog.write().create_source(&source);
991        self.add_table_or_source_id(source.id.as_raw_id(), source.schema_id, source.database_id);
992        Ok(source.id)
993    }
994
995    fn create_sink_inner(&self, mut sink: PbSink, _graph: StreamFragmentGraph) -> Result<SinkId> {
996        sink.id = self.gen_id();
997        sink.stream_job_status = PbStreamJobStatus::Created as _;
998        self.catalog.write().create_sink(&sink);
999        self.add_table_or_sink_id(sink.id.as_raw_id(), sink.schema_id, sink.database_id);
1000        Ok(sink.id)
1001    }
1002
1003    fn create_subscription_inner(&self, mut subscription: PbSubscription) -> Result<()> {
1004        subscription.id = self.gen_id();
1005        self.catalog.write().create_subscription(&subscription);
1006        self.add_table_or_subscription_id(
1007            subscription.id.as_raw_id(),
1008            subscription.schema_id,
1009            subscription.database_id,
1010        );
1011        Ok(())
1012    }
1013
1014    fn get_database_id_by_schema(&self, schema_id: SchemaId) -> DatabaseId {
1015        *self
1016            .schema_id_to_database_id
1017            .read()
1018            .get(&schema_id)
1019            .unwrap()
1020    }
1021
1022    fn get_object_type(&self, object_id: ObjectId) -> PbObjectType {
1023        let catalog = self.catalog.read();
1024        for database in catalog.iter_databases() {
1025            for schema in database.iter_schemas() {
1026                if let Some(table) = schema.get_created_table_by_id(object_id.as_table_id()) {
1027                    return if table.is_mview() {
1028                        PbObjectType::Mview
1029                    } else {
1030                        PbObjectType::Table
1031                    };
1032                }
1033                if schema.get_source_by_id(object_id.as_source_id()).is_some() {
1034                    return PbObjectType::Source;
1035                }
1036                if schema.get_view_by_id(object_id.as_view_id()).is_some() {
1037                    return PbObjectType::View;
1038                }
1039                if schema.get_index_by_id(object_id.as_index_id()).is_some() {
1040                    return PbObjectType::Index;
1041                }
1042            }
1043        }
1044        PbObjectType::Unspecified
1045    }
1046
1047    fn insert_object_dependencies(&self, object_id: ObjectId, dependencies: HashSet<ObjectId>) {
1048        if dependencies.is_empty() {
1049            return;
1050        }
1051        let dependencies = dependencies
1052            .into_iter()
1053            .map(|referenced_object_id| PbObjectDependency {
1054                object_id,
1055                referenced_object_id,
1056                referenced_object_type: self.get_object_type(referenced_object_id) as i32,
1057            })
1058            .collect();
1059        self.catalog
1060            .write()
1061            .insert_object_dependencies(dependencies);
1062    }
1063}
1064
1065pub struct MockUserInfoWriter {
1066    id: AtomicU32,
1067    user_info: Arc<RwLock<UserInfoManager>>,
1068}
1069
1070#[async_trait::async_trait]
1071impl UserInfoWriter for MockUserInfoWriter {
1072    async fn create_user(&self, user: UserInfo) -> Result<()> {
1073        let mut user = user;
1074        user.id = self.gen_id().into();
1075        self.user_info.write().create_user(user);
1076        Ok(())
1077    }
1078
1079    async fn drop_user(&self, id: UserId) -> Result<()> {
1080        self.user_info.write().drop_user(id);
1081        Ok(())
1082    }
1083
1084    async fn update_user(
1085        &self,
1086        update_user: UserInfo,
1087        update_fields: Vec<UpdateField>,
1088    ) -> Result<()> {
1089        let mut lock = self.user_info.write();
1090        let id = update_user.get_id();
1091        let Some(old_name) = lock.get_user_name_by_id(id) else {
1092            return Ok(());
1093        };
1094        let mut user_info = lock.get_user_by_name(&old_name).unwrap().to_prost();
1095        update_fields.into_iter().for_each(|field| match field {
1096            UpdateField::Super => user_info.is_super = update_user.is_super,
1097            UpdateField::Login => user_info.can_login = update_user.can_login,
1098            UpdateField::CreateDb => user_info.can_create_db = update_user.can_create_db,
1099            UpdateField::CreateUser => user_info.can_create_user = update_user.can_create_user,
1100            UpdateField::AuthInfo => user_info.auth_info.clone_from(&update_user.auth_info),
1101            UpdateField::Rename => user_info.name.clone_from(&update_user.name),
1102            UpdateField::Admin => user_info.is_admin = update_user.is_admin,
1103            UpdateField::Unspecified => unreachable!(),
1104        });
1105        lock.update_user(update_user);
1106        Ok(())
1107    }
1108
1109    /// In `MockUserInfoWriter`, we don't support expand privilege with `GrantAllTables` and
1110    /// `GrantAllSources` when grant privilege to user.
1111    async fn grant_privilege(
1112        &self,
1113        users: Vec<UserId>,
1114        privileges: Vec<GrantPrivilege>,
1115        with_grant_option: bool,
1116        _grantor: UserId,
1117    ) -> Result<()> {
1118        let privileges = privileges
1119            .into_iter()
1120            .map(|mut p| {
1121                p.action_with_opts
1122                    .iter_mut()
1123                    .for_each(|ao| ao.with_grant_option = with_grant_option);
1124                p
1125            })
1126            .collect::<Vec<_>>();
1127        for user_id in users {
1128            if let Some(u) = self.user_info.write().get_user_mut(user_id) {
1129                u.extend_privileges(privileges.clone());
1130            }
1131        }
1132        Ok(())
1133    }
1134
1135    /// In `MockUserInfoWriter`, we don't support expand privilege with `RevokeAllTables` and
1136    /// `RevokeAllSources` when revoke privilege from user.
1137    async fn revoke_privilege(
1138        &self,
1139        users: Vec<UserId>,
1140        privileges: Vec<GrantPrivilege>,
1141        _granted_by: UserId,
1142        _revoke_by: UserId,
1143        revoke_grant_option: bool,
1144        _cascade: bool,
1145    ) -> Result<()> {
1146        for user_id in users {
1147            if let Some(u) = self.user_info.write().get_user_mut(user_id) {
1148                u.revoke_privileges(privileges.clone(), revoke_grant_option);
1149            }
1150        }
1151        Ok(())
1152    }
1153
1154    async fn alter_default_privilege(
1155        &self,
1156        _users: Vec<UserId>,
1157        _database_id: DatabaseId,
1158        _schemas: Vec<SchemaId>,
1159        _operation: AlterDefaultPrivilegeOperation,
1160        _operated_by: UserId,
1161    ) -> Result<()> {
1162        todo!()
1163    }
1164}
1165
1166impl MockUserInfoWriter {
1167    pub fn new(user_info: Arc<RwLock<UserInfoManager>>) -> Self {
1168        user_info.write().create_user(UserInfo {
1169            id: DEFAULT_SUPER_USER_ID,
1170            name: DEFAULT_SUPER_USER.to_owned(),
1171            is_super: true,
1172            can_create_db: true,
1173            can_create_user: true,
1174            can_login: true,
1175            ..Default::default()
1176        });
1177        user_info.write().create_user(UserInfo {
1178            id: DEFAULT_SUPER_USER_FOR_ADMIN_ID,
1179            name: DEFAULT_SUPER_USER_FOR_ADMIN.to_owned(),
1180            is_super: true,
1181            can_create_db: true,
1182            can_create_user: true,
1183            can_login: true,
1184            is_admin: true,
1185            ..Default::default()
1186        });
1187        Self {
1188            user_info,
1189            id: AtomicU32::new(NON_RESERVED_USER_ID.as_raw_id()),
1190        }
1191    }
1192
1193    fn gen_id(&self) -> u32 {
1194        self.id.fetch_add(1, Ordering::SeqCst)
1195    }
1196}
1197
1198pub struct MockFrontendMetaClient {}
1199
1200#[async_trait::async_trait]
1201impl FrontendMetaClient for MockFrontendMetaClient {
1202    async fn try_unregister(&self) {}
1203
1204    async fn flush(&self, _database_id: DatabaseId) -> RpcResult<HummockVersionId> {
1205        Ok(INVALID_VERSION_ID)
1206    }
1207
1208    async fn cancel_creating_jobs(&self, _infos: PbJobs) -> RpcResult<Vec<u32>> {
1209        Ok(vec![])
1210    }
1211
1212    async fn list_table_fragments(
1213        &self,
1214        _table_ids: &[JobId],
1215    ) -> RpcResult<HashMap<JobId, TableFragmentInfo>> {
1216        Ok(HashMap::default())
1217    }
1218
1219    async fn list_streaming_job_states(&self) -> RpcResult<Vec<StreamingJobState>> {
1220        Ok(vec![])
1221    }
1222
1223    async fn list_fragment_distribution(
1224        &self,
1225        _include_node: bool,
1226    ) -> RpcResult<Vec<FragmentDistribution>> {
1227        Ok(vec![])
1228    }
1229
1230    async fn list_creating_fragment_distribution(&self) -> RpcResult<Vec<FragmentDistribution>> {
1231        Ok(vec![])
1232    }
1233
1234    async fn list_actor_states(&self) -> RpcResult<Vec<ActorState>> {
1235        Ok(vec![])
1236    }
1237
1238    async fn list_actor_splits(&self) -> RpcResult<Vec<ActorSplit>> {
1239        Ok(vec![])
1240    }
1241
1242    async fn list_meta_snapshots(&self) -> RpcResult<Vec<MetaSnapshotMetadata>> {
1243        Ok(vec![])
1244    }
1245
1246    async fn list_sink_log_store_tables(
1247        &self,
1248    ) -> RpcResult<Vec<list_sink_log_store_tables_response::SinkLogStoreTable>> {
1249        Ok(vec![])
1250    }
1251
1252    async fn set_system_param(
1253        &self,
1254        _param: String,
1255        _value: Option<String>,
1256    ) -> RpcResult<Option<SystemParamsReader>> {
1257        Ok(Some(SystemParams::default().into()))
1258    }
1259
1260    async fn get_session_params(&self) -> RpcResult<SessionConfig> {
1261        Ok(Default::default())
1262    }
1263
1264    async fn set_session_param(&self, _param: String, _value: Option<String>) -> RpcResult<String> {
1265        Ok("".to_owned())
1266    }
1267
1268    async fn get_ddl_progress(&self) -> RpcResult<Vec<DdlProgress>> {
1269        Ok(vec![])
1270    }
1271
1272    async fn get_tables(
1273        &self,
1274        _table_ids: Vec<crate::catalog::TableId>,
1275        _include_dropped_tables: bool,
1276    ) -> RpcResult<HashMap<crate::catalog::TableId, Table>> {
1277        Ok(HashMap::new())
1278    }
1279
1280    async fn list_hummock_pinned_versions(&self) -> RpcResult<Vec<(WorkerId, HummockVersionId)>> {
1281        unimplemented!()
1282    }
1283
1284    async fn list_refresh_table_states(&self) -> RpcResult<Vec<RefreshTableState>> {
1285        unimplemented!()
1286    }
1287
1288    async fn get_hummock_current_version(&self) -> RpcResult<HummockVersion> {
1289        Ok(HummockVersion::default())
1290    }
1291
1292    async fn get_hummock_checkpoint_version(&self) -> RpcResult<HummockVersion> {
1293        unimplemented!()
1294    }
1295
1296    async fn list_version_deltas(&self) -> RpcResult<Vec<HummockVersionDelta>> {
1297        unimplemented!()
1298    }
1299
1300    async fn list_branched_objects(&self) -> RpcResult<Vec<BranchedObject>> {
1301        unimplemented!()
1302    }
1303
1304    async fn list_hummock_compaction_group_configs(&self) -> RpcResult<Vec<CompactionGroupInfo>> {
1305        unimplemented!()
1306    }
1307
1308    async fn list_hummock_active_write_limits(
1309        &self,
1310    ) -> RpcResult<HashMap<CompactionGroupId, WriteLimit>> {
1311        unimplemented!()
1312    }
1313
1314    async fn list_hummock_meta_configs(&self) -> RpcResult<HashMap<String, String>> {
1315        unimplemented!()
1316    }
1317
1318    async fn list_event_log(&self) -> RpcResult<Vec<EventLog>> {
1319        Ok(vec![])
1320    }
1321
1322    async fn list_compact_task_assignment(&self) -> RpcResult<Vec<CompactTaskAssignment>> {
1323        unimplemented!()
1324    }
1325
1326    async fn list_all_nodes(&self) -> RpcResult<Vec<WorkerNode>> {
1327        Ok(vec![])
1328    }
1329
1330    async fn list_compact_task_progress(&self) -> RpcResult<Vec<CompactTaskProgress>> {
1331        unimplemented!()
1332    }
1333
1334    async fn recover(&self) -> RpcResult<()> {
1335        unimplemented!()
1336    }
1337
1338    async fn backup_meta(&self, _remarks: Option<String>) -> RpcResult<u64> {
1339        unimplemented!()
1340    }
1341
1342    async fn get_backup_job_status(
1343        &self,
1344        _job_id: u64,
1345    ) -> RpcResult<(risingwave_pb::backup_service::BackupJobStatus, String)> {
1346        unimplemented!()
1347    }
1348
1349    async fn delete_meta_snapshot(&self, _snapshot_ids: &[u64]) -> RpcResult<()> {
1350        unimplemented!()
1351    }
1352
1353    async fn apply_throttle(
1354        &self,
1355        _throttle_target: PbThrottleTarget,
1356        _throttle_type: risingwave_pb::common::PbThrottleType,
1357        _id: u32,
1358        _rate_limit: Option<u32>,
1359    ) -> RpcResult<()> {
1360        unimplemented!()
1361    }
1362
1363    async fn alter_fragment_parallelism(
1364        &self,
1365        _fragment_ids: Vec<FragmentId>,
1366        _parallelism: Option<PbTableParallelism>,
1367    ) -> RpcResult<()> {
1368        unimplemented!()
1369    }
1370
1371    async fn get_cluster_recovery_status(&self) -> RpcResult<RecoveryStatus> {
1372        Ok(RecoveryStatus::StatusRunning)
1373    }
1374
1375    async fn get_cluster_limits(&self) -> RpcResult<Vec<ClusterLimit>> {
1376        Ok(vec![])
1377    }
1378
1379    async fn list_rate_limits(&self) -> RpcResult<Vec<RateLimitInfo>> {
1380        Ok(vec![])
1381    }
1382
1383    async fn list_cdc_progress(&self) -> RpcResult<HashMap<JobId, PbCdcProgress>> {
1384        Ok(HashMap::default())
1385    }
1386
1387    async fn get_meta_store_endpoint(&self) -> RpcResult<String> {
1388        unimplemented!()
1389    }
1390
1391    async fn alter_sink_props(
1392        &self,
1393        _sink_id: SinkId,
1394        _changed_props: BTreeMap<String, String>,
1395        _changed_secret_refs: BTreeMap<String, PbSecretRef>,
1396        _connector_conn_ref: Option<ConnectionId>,
1397    ) -> RpcResult<()> {
1398        unimplemented!()
1399    }
1400
1401    async fn alter_iceberg_table_props(
1402        &self,
1403        _table_id: TableId,
1404        _sink_id: SinkId,
1405        _source_id: SourceId,
1406        _changed_props: BTreeMap<String, String>,
1407        _changed_secret_refs: BTreeMap<String, PbSecretRef>,
1408        _connector_conn_ref: Option<ConnectionId>,
1409    ) -> RpcResult<()> {
1410        unimplemented!()
1411    }
1412
1413    async fn alter_source_connector_props(
1414        &self,
1415        _source_id: SourceId,
1416        _changed_props: BTreeMap<String, String>,
1417        _changed_secret_refs: BTreeMap<String, PbSecretRef>,
1418        _connector_conn_ref: Option<ConnectionId>,
1419    ) -> RpcResult<()> {
1420        unimplemented!()
1421    }
1422
1423    async fn alter_connection_connector_props(
1424        &self,
1425        _connection_id: u32,
1426        _changed_props: BTreeMap<String, String>,
1427        _changed_secret_refs: BTreeMap<String, PbSecretRef>,
1428    ) -> RpcResult<()> {
1429        Ok(())
1430    }
1431
1432    async fn list_hosted_iceberg_tables(&self) -> RpcResult<Vec<IcebergTable>> {
1433        unimplemented!()
1434    }
1435
1436    async fn list_iceberg_compaction_status(&self) -> RpcResult<Vec<IcebergCompactionStatus>> {
1437        Ok(vec![])
1438    }
1439
1440    async fn get_fragment_by_id(
1441        &self,
1442        _fragment_id: FragmentId,
1443    ) -> RpcResult<Option<FragmentDistribution>> {
1444        unimplemented!()
1445    }
1446
1447    async fn get_fragment_vnodes(
1448        &self,
1449        _fragment_id: FragmentId,
1450    ) -> RpcResult<Vec<(ActorId, Vec<u32>)>> {
1451        unimplemented!()
1452    }
1453
1454    async fn get_actor_vnodes(&self, _actor_id: ActorId) -> RpcResult<Vec<u32>> {
1455        unimplemented!()
1456    }
1457
1458    fn worker_id(&self) -> WorkerId {
1459        0.into()
1460    }
1461
1462    async fn set_sync_log_store_aligned(&self, _job_id: JobId, _aligned: bool) -> RpcResult<()> {
1463        Ok(())
1464    }
1465
1466    async fn compact_iceberg_table(&self, _sink_id: SinkId) -> RpcResult<u64> {
1467        Ok(1)
1468    }
1469
1470    async fn expire_iceberg_table_snapshots(&self, _sink_id: SinkId) -> RpcResult<()> {
1471        Ok(())
1472    }
1473
1474    async fn refresh(&self, _request: RefreshRequest) -> RpcResult<RefreshResponse> {
1475        Ok(RefreshResponse { status: None })
1476    }
1477
1478    fn cluster_id(&self) -> &str {
1479        "test-cluster-uuid"
1480    }
1481
1482    async fn list_unmigrated_tables(&self) -> RpcResult<HashMap<crate::catalog::TableId, String>> {
1483        unimplemented!()
1484    }
1485
1486    async fn get_hummock_table_change_log(
1487        &self,
1488        _start_epoch_inclusive: Option<u64>,
1489        _end_epoch_inclusive: Option<u64>,
1490        _table_ids: Option<HashSet<TableId>>,
1491        _exclude_empty: bool,
1492        _limit: Option<u32>,
1493    ) -> RpcResult<TableChangeLogs> {
1494        Ok(HashMap::default())
1495    }
1496
1497    async fn update_compaction_config(
1498        &self,
1499        _compaction_group_ids: Vec<risingwave_hummock_sdk::CompactionGroupId>,
1500        _configs: Vec<PbMutableConfig>,
1501    ) -> RpcResult<()> {
1502        Ok(())
1503    }
1504}
1505
1506#[cfg(test)]
1507pub static PROTO_FILE_DATA: &str = r#"
1508    syntax = "proto3";
1509    package test;
1510    message TestRecord {
1511      int32 id = 1;
1512      Country country = 3;
1513      int64 zipcode = 4;
1514      float rate = 5;
1515    }
1516    message TestRecordAlterType {
1517        string id = 1;
1518        Country country = 3;
1519        int32 zipcode = 4;
1520        float rate = 5;
1521      }
1522    message TestRecordExt {
1523      int32 id = 1;
1524      Country country = 3;
1525      int64 zipcode = 4;
1526      float rate = 5;
1527      string name = 6;
1528    }
1529    message Country {
1530      string address = 1;
1531      City city = 2;
1532      string zipcode = 3;
1533    }
1534    message City {
1535      string address = 1;
1536      string zipcode = 2;
1537    }"#;
1538
1539/// Returns the file.
1540/// (`NamedTempFile` will automatically delete the file when it goes out of scope.)
1541pub fn create_proto_file(proto_data: &str) -> NamedTempFile {
1542    let in_file = Builder::new()
1543        .prefix("temp")
1544        .suffix(".proto")
1545        .rand_bytes(8)
1546        .tempfile()
1547        .unwrap();
1548
1549    let out_file = Builder::new()
1550        .prefix("temp")
1551        .suffix(".pb")
1552        .rand_bytes(8)
1553        .tempfile()
1554        .unwrap();
1555
1556    let mut file = in_file.as_file();
1557    file.write_all(proto_data.as_ref())
1558        .expect("writing binary to test file");
1559    file.flush().expect("flush temp file failed");
1560    let include_path = in_file
1561        .path()
1562        .parent()
1563        .unwrap()
1564        .to_string_lossy()
1565        .into_owned();
1566    let out_path = out_file.path().to_string_lossy().into_owned();
1567    let in_path = in_file.path().to_string_lossy().into_owned();
1568    let mut compile = std::process::Command::new("protoc");
1569
1570    let out = compile
1571        .arg("--include_imports")
1572        .arg("-I")
1573        .arg(include_path)
1574        .arg(format!("--descriptor_set_out={}", out_path))
1575        .arg(in_path)
1576        .output()
1577        .expect("failed to compile proto");
1578    if !out.status.success() {
1579        panic!("compile proto failed \n output: {:?}", out);
1580    }
1581    out_file
1582}