1pub mod flow_info;
16pub(crate) mod flow_name;
17pub mod flow_route;
18pub mod flow_state;
19mod flownode_addr_helper;
20pub(crate) mod flownode_flow;
21pub(crate) mod table_flow;
22use std::collections::{BTreeMap, HashSet};
23use std::ops::Deref;
24use std::sync::Arc;
25
26use common_telemetry::info;
27use flow_route::{FlowRouteKey, FlowRouteManager, FlowRouteValue};
28use snafu::{OptionExt, ensure};
29use table_flow::TableFlowValue;
30
31use self::flow_info::{FlowInfoKey, FlowInfoValue};
32use self::flow_name::FlowNameKey;
33use self::flownode_flow::FlownodeFlowKey;
34use self::table_flow::TableFlowKey;
35use crate::ensure_values;
36use crate::error::{self, Result};
37use crate::key::flow::flow_info::FlowInfoManager;
38use crate::key::flow::flow_name::FlowNameManager;
39use crate::key::flow::flow_state::FlowStateManager;
40use crate::key::flow::flownode_flow::FlownodeFlowManager;
41pub use crate::key::flow::table_flow::{TableFlowManager, TableFlowManagerRef};
42use crate::key::txn_helper::TxnOpGetResponseSet;
43use crate::key::{DeserializedValueWithBytes, FlowId, FlowPartitionId, MetadataKey};
44use crate::kv_backend::KvBackendRef;
45use crate::kv_backend::txn::{Txn, TxnOp};
46use crate::rpc::store::BatchDeleteRequest;
47
48pub const FLOW_KEY_PREFIX: &str = "__flow";
49
50pub fn scoped_flow_key(inner_key: &str) -> String {
52 format!("{FLOW_KEY_PREFIX}/{inner_key}")
53}
54
55pub fn scoped_flow_key_prefix(inner_prefix: &str) -> String {
57 scoped_flow_key(inner_prefix)
58}
59
60pub fn flow_info_key_prefix() -> String {
62 scoped_flow_key_prefix(flow_info::FLOW_INFO_KEY_PREFIX)
63}
64
65pub fn flow_name_key_prefix() -> String {
67 scoped_flow_key_prefix(flow_name::FLOW_NAME_KEY_PREFIX)
68}
69
70pub fn flow_route_key_prefix() -> String {
72 scoped_flow_key_prefix(flow_route::FLOW_ROUTE_KEY_PREFIX)
73}
74
75pub fn table_flow_key_prefix() -> String {
77 scoped_flow_key_prefix(table_flow::TABLE_FLOW_KEY_PREFIX)
78}
79
80pub fn flownode_flow_key_prefix() -> String {
82 scoped_flow_key_prefix(flownode_flow::FLOWNODE_FLOW_KEY_PREFIX)
83}
84
85pub fn flow_state_full_key() -> String {
87 scoped_flow_key(flow_state::FLOW_STATE_KEY)
88}
89
90#[derive(Debug, Clone, PartialEq)]
92pub struct FlowScoped<T> {
93 inner: T,
94}
95
96impl<T> Deref for FlowScoped<T> {
97 type Target = T;
98
99 fn deref(&self) -> &Self::Target {
100 &self.inner
101 }
102}
103
104impl<T> FlowScoped<T> {
105 const PREFIX: &'static str = "__flow/";
106
107 pub fn new(inner: T) -> FlowScoped<T> {
109 Self { inner }
110 }
111}
112
113impl<'a, T: MetadataKey<'a, T>> MetadataKey<'a, FlowScoped<T>> for FlowScoped<T> {
114 fn to_bytes(&self) -> Vec<u8> {
115 let prefix = FlowScoped::<T>::PREFIX.as_bytes();
116 let inner = self.inner.to_bytes();
117 let mut bytes = Vec::with_capacity(prefix.len() + inner.len());
118 bytes.extend(prefix);
119 bytes.extend(inner);
120 bytes
121 }
122
123 fn from_bytes(bytes: &'a [u8]) -> Result<FlowScoped<T>> {
124 let prefix = FlowScoped::<T>::PREFIX.as_bytes();
125 ensure!(
126 bytes.starts_with(prefix),
127 error::MismatchPrefixSnafu {
128 prefix: String::from_utf8_lossy(prefix),
129 key: String::from_utf8_lossy(bytes),
130 }
131 );
132 let inner = T::from_bytes(&bytes[prefix.len()..])?;
133 Ok(FlowScoped { inner })
134 }
135}
136
137fn build_replace_ops(
142 old_keys: impl IntoIterator<Item = Vec<u8>>,
143 new_kvs: Vec<(Vec<u8>, Vec<u8>)>,
144) -> Vec<TxnOp> {
145 let new_keys = new_kvs
146 .iter()
147 .map(|(key, _)| key.as_slice())
148 .collect::<HashSet<_>>();
149 let mut ops = old_keys
150 .into_iter()
151 .filter(|key| !new_keys.contains(key.as_slice()))
152 .map(TxnOp::Delete)
153 .collect::<Vec<_>>();
154 ops.extend(
155 new_kvs
156 .into_iter()
157 .map(|(key, value)| TxnOp::Put(key, value)),
158 );
159 ops
160}
161
162pub type FlowMetadataManagerRef = Arc<FlowMetadataManager>;
163
164pub struct FlowMetadataManager {
169 flow_info_manager: FlowInfoManager,
170 flow_route_manager: FlowRouteManager,
171 flownode_flow_manager: FlownodeFlowManager,
172 table_flow_manager: TableFlowManager,
173 flow_name_manager: FlowNameManager,
174 flow_state_manager: Option<FlowStateManager>,
176 kv_backend: KvBackendRef,
177}
178
179impl FlowMetadataManager {
180 pub fn new(kv_backend: KvBackendRef) -> Self {
182 Self {
183 flow_info_manager: FlowInfoManager::new(kv_backend.clone()),
184 flow_route_manager: FlowRouteManager::new(kv_backend.clone()),
185 flow_name_manager: FlowNameManager::new(kv_backend.clone()),
186 flownode_flow_manager: FlownodeFlowManager::new(kv_backend.clone()),
187 table_flow_manager: TableFlowManager::new(kv_backend.clone()),
188 flow_state_manager: None,
189 kv_backend,
190 }
191 }
192
193 pub fn flow_name_manager(&self) -> &FlowNameManager {
195 &self.flow_name_manager
196 }
197
198 pub fn flow_state_manager(&self) -> Option<&FlowStateManager> {
199 self.flow_state_manager.as_ref()
200 }
201
202 pub fn flow_info_manager(&self) -> &FlowInfoManager {
204 &self.flow_info_manager
205 }
206
207 pub fn flow_route_manager(&self) -> &FlowRouteManager {
209 &self.flow_route_manager
210 }
211
212 pub fn flownode_flow_manager(&self) -> &FlownodeFlowManager {
214 &self.flownode_flow_manager
215 }
216
217 pub fn table_flow_manager(&self) -> &TableFlowManager {
219 &self.table_flow_manager
220 }
221
222 pub async fn flownode_addrs(
224 &self,
225 flow_id: FlowId,
226 ) -> Result<BTreeMap<FlowPartitionId, String>> {
227 let routes = self.flow_route_manager.routes(flow_id).await?;
228
229 Ok(routes
230 .into_iter()
231 .filter_map(|(key, route)| {
232 let addr = route.peer.addr;
233 (!addr.is_empty()).then_some((key.partition_id(), addr))
234 })
235 .collect())
236 }
237
238 pub async fn create_flow_metadata(
240 &self,
241 flow_id: FlowId,
242 flow_info: FlowInfoValue,
243 flow_routes: Vec<(FlowPartitionId, FlowRouteValue)>,
244 ) -> Result<()> {
245 let (create_flow_flow_name_txn, on_create_flow_flow_name_failure) = self
246 .flow_name_manager
247 .build_create_txn(&flow_info.catalog_name, &flow_info.flow_name, flow_id)?;
248
249 let (create_flow_txn, on_create_flow_failure) = self
250 .flow_info_manager
251 .build_create_txn(flow_id, &flow_info)?;
252
253 let create_flow_routes_txn = self
254 .flow_route_manager
255 .build_create_txn(flow_id, flow_routes.clone())?;
256
257 let create_flownode_flow_txn = self
258 .flownode_flow_manager
259 .build_create_txn(flow_id, flow_info.flownode_ids().clone());
260
261 let create_table_flow_txn = self.table_flow_manager.build_create_txn(
262 flow_id,
263 flow_routes
264 .into_iter()
265 .map(|(partition_id, route)| (partition_id, TableFlowValue { peer: route.peer }))
266 .collect(),
267 flow_info.source_table_ids(),
268 )?;
269
270 let txn = Txn::merge_all(vec![
271 create_flow_flow_name_txn,
272 create_flow_txn,
273 create_flow_routes_txn,
274 create_flownode_flow_txn,
275 create_table_flow_txn,
276 ]);
277 info!(
278 "Creating flow {}.{}({}), with {} txn operations",
279 flow_info.catalog_name,
280 flow_info.flow_name,
281 flow_id,
282 txn.max_operations()
283 );
284
285 let mut resp = self.kv_backend.txn(txn).await?;
286 if !resp.succeeded {
287 let mut set = TxnOpGetResponseSet::from(&mut resp.responses);
288 let remote_flow_flow_name =
289 on_create_flow_flow_name_failure(&mut set)?.with_context(|| {
290 error::UnexpectedSnafu {
291 err_msg: format!(
292 "Reads the empty flow name in comparing operation of the creating flow, flow_id: {flow_id}"
293 ),
294 }
295 })?;
296
297 if remote_flow_flow_name.flow_id() != flow_id {
298 info!(
299 "Trying to create flow {}.{}({}), but flow({}) already exists",
300 flow_info.catalog_name,
301 flow_info.flow_name,
302 flow_id,
303 remote_flow_flow_name.flow_id()
304 );
305
306 return error::FlowAlreadyExistsSnafu {
307 flow_name: format!("{}.{}", flow_info.catalog_name, flow_info.flow_name),
308 }
309 .fail();
310 }
311
312 let remote_flow =
313 on_create_flow_failure(&mut set)?.with_context(|| error::UnexpectedSnafu {
314 err_msg: format!(
315 "Reads the empty flow in comparing operation of creating flow, flow_id: {flow_id}"
316 ),
317 })?;
318 let op_name = "creating flow";
319 ensure_values!(*remote_flow, flow_info, op_name);
320 }
321
322 Ok(())
323 }
324
325 pub async fn update_flow_metadata(
327 &self,
328 flow_id: FlowId,
329 current_flow_info: &DeserializedValueWithBytes<FlowInfoValue>,
330 new_flow_info: &FlowInfoValue,
331 flow_routes: Vec<(FlowPartitionId, FlowRouteValue)>,
332 ) -> Result<()> {
333 let (update_flow_flow_name_txn, on_create_flow_flow_name_failure) =
334 self.flow_name_manager.build_update_txn(
335 &new_flow_info.catalog_name,
336 &new_flow_info.flow_name,
337 flow_id,
338 )?;
339
340 let (update_flow_txn, on_create_flow_failure) =
341 self.flow_info_manager
342 .build_update_txn(flow_id, current_flow_info, new_flow_info)?;
343
344 let update_flow_routes_txn = self.flow_route_manager.build_update_txn(
345 flow_id,
346 current_flow_info,
347 flow_routes.clone(),
348 )?;
349
350 let update_flownode_flow_txn = self.flownode_flow_manager.build_update_txn(
351 flow_id,
352 current_flow_info,
353 new_flow_info.flownode_ids().clone(),
354 );
355
356 let update_table_flow_txn = self.table_flow_manager.build_update_txn(
357 flow_id,
358 current_flow_info,
359 flow_routes
360 .into_iter()
361 .map(|(partition_id, route)| (partition_id, TableFlowValue { peer: route.peer }))
362 .collect(),
363 new_flow_info.source_table_ids(),
364 )?;
365
366 let txn = Txn::merge_all(vec![
367 update_flow_flow_name_txn,
368 update_flow_txn,
369 update_flow_routes_txn,
370 update_flownode_flow_txn,
371 update_table_flow_txn,
372 ]);
373 info!(
374 "Creating flow {}.{}({}), with {} txn operations",
375 new_flow_info.catalog_name,
376 new_flow_info.flow_name,
377 flow_id,
378 txn.max_operations()
379 );
380
381 let mut resp = self.kv_backend.txn(txn).await?;
382 if !resp.succeeded {
383 let mut set = TxnOpGetResponseSet::from(&mut resp.responses);
384 let remote_flow_flow_name =
385 on_create_flow_flow_name_failure(&mut set)?.with_context(|| {
386 error::UnexpectedSnafu {
387 err_msg: format!(
388 "Reads the empty flow name in comparing operation of the updating flow, flow_id: {flow_id}"
389 ),
390 }
391 })?;
392
393 if remote_flow_flow_name.flow_id() != flow_id {
394 info!(
395 "Trying to updating flow {}.{}({}), but flow({}) already exists with a different flow id",
396 new_flow_info.catalog_name,
397 new_flow_info.flow_name,
398 flow_id,
399 remote_flow_flow_name.flow_id()
400 );
401
402 return error::UnexpectedSnafu {
403 err_msg: format!(
404 "Reads different flow id when updating flow({2}.{3}), prev flow id = {0}, updating with flow id = {1}",
405 remote_flow_flow_name.flow_id(),
406 flow_id,
407 new_flow_info.catalog_name,
408 new_flow_info.flow_name,
409 ),
410 }.fail();
411 }
412
413 let remote_flow =
414 on_create_flow_failure(&mut set)?.with_context(|| error::UnexpectedSnafu {
415 err_msg: format!(
416 "Reads the empty flow in comparing operation of the updating flow, flow_id: {flow_id}"
417 ),
418 })?;
419 let op_name = "updating flow";
420 ensure_values!(*remote_flow, new_flow_info.clone(), op_name);
421 }
422
423 Ok(())
424 }
425
426 fn flow_metadata_keys(&self, flow_id: FlowId, flow_value: &FlowInfoValue) -> Vec<Vec<u8>> {
427 let source_table_ids = flow_value.source_table_ids();
428 let mut keys =
429 Vec::with_capacity(2 + flow_value.flownode_ids.len() * (source_table_ids.len() + 2));
430 let flow_name = FlowNameKey::new(&flow_value.catalog_name, &flow_value.flow_name);
432 keys.push(flow_name.to_bytes());
433
434 let flow_info_key = FlowInfoKey::new(flow_id);
436 keys.push(flow_info_key.to_bytes());
437
438 flow_value
440 .flownode_ids
441 .iter()
442 .for_each(|(&partition_id, &flownode_id)| {
443 keys.push(FlownodeFlowKey::new(flownode_id, flow_id, partition_id).to_bytes());
444 keys.push(FlowRouteKey::new(flow_id, partition_id).to_bytes());
445 source_table_ids.iter().for_each(|&table_id| {
446 keys.push(
447 TableFlowKey::new(table_id, flownode_id, flow_id, partition_id).to_bytes(),
448 );
449 })
450 });
451 keys
452 }
453
454 pub async fn destroy_flow_metadata(
456 &self,
457 flow_id: FlowId,
458 flow_value: &FlowInfoValue,
459 ) -> Result<()> {
460 let keys = self.flow_metadata_keys(flow_id, flow_value);
461 let _ = self
462 .kv_backend
463 .batch_delete(BatchDeleteRequest::new().with_keys(keys))
464 .await?;
465 Ok(())
466 }
467}
468
469impl std::fmt::Debug for FlowMetadataManager {
470 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
471 f.debug_struct("FlowMetadataManager").finish()
472 }
473}
474
475#[cfg(test)]
476mod tests {
477 use std::assert_matches;
478 use std::collections::BTreeMap;
479 use std::sync::Arc;
480
481 use futures::TryStreamExt;
482 use table::metadata::TableId;
483 use table::table_name::TableName;
484 use uuid::Uuid;
485
486 use super::*;
487 use crate::FlownodeId;
488 use crate::key::flow::flow_info::FlowStatus;
489 use crate::key::flow::table_flow::TableFlowKey;
490 use crate::key::node_address::{NodeAddressKey, NodeAddressValue};
491 use crate::key::{FlowPartitionId, MetadataValue};
492 use crate::kv_backend::chroot::ChrootKvBackend;
493 use crate::kv_backend::etcd::EtcdStore;
494 use crate::kv_backend::memory::MemoryKvBackend;
495 use crate::kv_backend::{KvBackend, KvBackendRef};
496 use crate::peer::Peer;
497 use crate::rpc::store::PutRequest;
498
499 #[derive(Debug)]
500 struct MockKey {
501 inner: Vec<u8>,
502 }
503
504 impl<'a> MetadataKey<'a, MockKey> for MockKey {
505 fn to_bytes(&self) -> Vec<u8> {
506 self.inner.clone()
507 }
508
509 fn from_bytes(bytes: &'a [u8]) -> Result<MockKey> {
510 Ok(MockKey {
511 inner: bytes.to_vec(),
512 })
513 }
514 }
515
516 #[test]
517 fn test_flow_scoped_to_bytes() {
518 let key = FlowScoped::new(MockKey {
519 inner: b"hi".to_vec(),
520 });
521 assert_eq!(b"__flow/hi".to_vec(), key.to_bytes());
522 }
523
524 #[test]
525 fn test_flow_scoped_from_bytes() {
526 let bytes = b"__flow/hi";
527 let key = FlowScoped::<MockKey>::from_bytes(bytes).unwrap();
528 assert_eq!(key.inner.inner, b"hi".to_vec());
529 }
530
531 #[test]
532 fn test_flow_scoped_from_bytes_mismatch() {
533 let bytes = b"__table/hi";
534 let err = FlowScoped::<MockKey>::from_bytes(bytes).unwrap_err();
535 assert_matches!(err, error::Error::MismatchPrefix { .. });
536 }
537
538 fn test_flow_info_value(
539 flow_name: &str,
540 flownode_ids: BTreeMap<FlowPartitionId, FlownodeId>,
541 source_table_ids: Vec<TableId>,
542 ) -> FlowInfoValue {
543 let catalog_name = "greptime";
544 let sink_table_name = TableName {
545 catalog_name: catalog_name.to_string(),
546 schema_name: "my_schema".to_string(),
547 table_name: "sink_table".to_string(),
548 };
549 FlowInfoValue {
550 catalog_name: catalog_name.to_string(),
551 query_context: None,
552 flow_name: flow_name.to_string(),
553 source_table_ids,
554 all_source_table_names: vec![],
555 unresolved_source_table_names: vec![],
556 sink_table_name,
557 flownode_ids,
558 raw_sql: "raw".to_string(),
559 expire_after: Some(300),
560 eval_interval_secs: None,
561 comment: "hi".to_string(),
562 options: Default::default(),
563 status: FlowStatus::Active,
564 created_time: chrono::Utc::now(),
565 updated_time: chrono::Utc::now(),
566 eval_schedule: None,
567 allow_sink_create: true,
568 }
569 }
570
571 #[tokio::test]
572 async fn test_flow_info_cache_batches_backend_reads() {
573 use crate::cache::new_flow_info_cache;
574 use crate::cache::test_util::assert_batch_cache_reads;
575
576 assert_batch_cache_reads(new_flow_info_cache, |id| {
577 let info = test_flow_info_value(&format!("flow_{id}"), Default::default(), vec![]);
578 (
579 FlowInfoKey::new(id).to_bytes(),
580 info.try_as_raw_value().unwrap(),
581 )
582 })
583 .await;
584 }
585
586 #[tokio::test]
587 async fn test_flow_info_manager_batch_get() {
588 let manager = FlowMetadataManager::new(Arc::new(MemoryKvBackend::default()));
589 let first = test_flow_info_value("first", Default::default(), vec![]);
590 let second = test_flow_info_value("second", Default::default(), vec![]);
591 for (id, info) in [(10, &first), (11, &second)] {
592 manager
593 .create_flow_metadata(id, info.clone(), vec![])
594 .await
595 .unwrap();
596 }
597 let infos = manager
598 .flow_info_manager()
599 .batch_get(&[11, 12, 10, 11])
600 .await
601 .unwrap();
602 assert_eq!(infos, [(10, first), (11, second)].into());
603 }
604
605 #[tokio::test]
606 async fn test_batch_flow_info_invalidation() {
607 use crate::cache::new_flow_info_cache;
608 use crate::instruction::CacheIdent;
609 let backend = Arc::new(MemoryKvBackend::default());
610 let manager = FlowMetadataManager::new(backend.clone());
611 let cache = new_flow_info_cache("flows".into(), moka::future::Cache::new(8), backend);
612 let info = test_flow_info_value("flow", Default::default(), vec![]);
613 assert!(cache.get(10).await.unwrap().is_none());
614 manager
615 .create_flow_metadata(10, info.clone(), vec![])
616 .await
617 .unwrap();
618 let values = cache.get_many(&[10, 11, 10]).await.unwrap();
619 assert_eq!(
620 values,
621 vec![
622 Some(Arc::new(info.clone())),
623 None,
624 Some(Arc::new(info.clone()))
625 ]
626 );
627 let previous = manager
628 .flow_info_manager()
629 .get_raw(10)
630 .await
631 .unwrap()
632 .unwrap();
633 let mut updated = info;
634 updated.comment = "updated".into();
635 manager
636 .update_flow_metadata(10, &previous, &updated, vec![])
637 .await
638 .unwrap();
639 cache.invalidate(&[CacheIdent::FlowId(10)]).await.unwrap();
640 assert_eq!(
641 cache.get_many(&[10]).await.unwrap()[0].as_deref(),
642 Some(&updated)
643 );
644 manager.destroy_flow_metadata(10, &updated).await.unwrap();
645 cache.invalidate(&[CacheIdent::FlowId(10)]).await.unwrap();
646 assert_eq!(cache.get_many(&[10]).await.unwrap(), vec![None]);
647 }
648
649 #[tokio::test]
650 async fn test_create_flow_metadata() {
651 let mem_kv = Arc::new(MemoryKvBackend::default());
652 let flow_metadata_manager = FlowMetadataManager::new(mem_kv.clone());
653 let flow_id = 10;
654 let flow_value = test_flow_info_value(
655 "flow",
656 [(0, 1u64), (1, 2u64)].into(),
657 vec![1024, 1025, 1026],
658 );
659 let flow_routes = vec![
660 (
661 1u32,
662 FlowRouteValue {
663 peer: Peer::empty(1),
664 },
665 ),
666 (
667 2,
668 FlowRouteValue {
669 peer: Peer::empty(2),
670 },
671 ),
672 ];
673 flow_metadata_manager
674 .create_flow_metadata(flow_id, flow_value.clone(), flow_routes.clone())
675 .await
676 .unwrap();
677 flow_metadata_manager
679 .create_flow_metadata(flow_id, flow_value.clone(), flow_routes.clone())
680 .await
681 .unwrap();
682 let got = flow_metadata_manager
683 .flow_info_manager()
684 .get(flow_id)
685 .await
686 .unwrap()
687 .unwrap();
688 let routes = flow_metadata_manager
689 .flow_route_manager()
690 .routes(flow_id)
691 .await
692 .unwrap();
693 assert_eq!(
694 routes,
695 vec![
696 (
697 FlowRouteKey::new(flow_id, 1),
698 FlowRouteValue {
699 peer: Peer::empty(1),
700 },
701 ),
702 (
703 FlowRouteKey::new(flow_id, 2),
704 FlowRouteValue {
705 peer: Peer::empty(2),
706 },
707 ),
708 ]
709 );
710 assert_eq!(got, flow_value);
711 let flows = flow_metadata_manager
712 .flownode_flow_manager()
713 .flows(1)
714 .try_collect::<Vec<_>>()
715 .await
716 .unwrap();
717 assert_eq!(flows, vec![(flow_id, 0)]);
718 for table_id in [1024, 1025, 1026] {
719 let nodes = flow_metadata_manager
720 .table_flow_manager()
721 .flows(table_id)
722 .await
723 .unwrap();
724 assert_eq!(
725 nodes,
726 vec![
727 (
728 TableFlowKey::new(table_id, 1, flow_id, 1),
729 TableFlowValue {
730 peer: Peer::empty(1)
731 }
732 ),
733 (
734 TableFlowKey::new(table_id, 2, flow_id, 2),
735 TableFlowValue {
736 peer: Peer::empty(2)
737 }
738 )
739 ]
740 );
741 }
742 }
743
744 #[tokio::test]
745 async fn test_flownode_addrs_remaps_to_latest_address() {
746 let mem_kv = Arc::new(MemoryKvBackend::default());
747 let flow_metadata_manager = FlowMetadataManager::new(mem_kv.clone());
748 let flow_id = 10;
749 let flow_value = test_flow_info_value("flow", [(0, 1u64)].into(), vec![1024]);
750 let flow_routes = vec![(
751 0u32,
752 FlowRouteValue {
753 peer: Peer::new(1, "old-addr"),
754 },
755 )];
756
757 flow_metadata_manager
758 .create_flow_metadata(flow_id, flow_value, flow_routes)
759 .await
760 .unwrap();
761
762 mem_kv
763 .put(PutRequest {
764 key: NodeAddressKey::with_flownode(1).to_bytes(),
765 value: NodeAddressValue::new(Peer::new(1, "new-addr"))
766 .try_as_raw_value()
767 .unwrap(),
768 ..Default::default()
769 })
770 .await
771 .unwrap();
772
773 let addrs = flow_metadata_manager.flownode_addrs(flow_id).await.unwrap();
774 assert_eq!(addrs, BTreeMap::from([(0, "new-addr".to_string())]));
775 }
776
777 #[tokio::test]
778 async fn test_flownode_addrs_falls_back_to_route_address() {
779 let mem_kv = Arc::new(MemoryKvBackend::default());
780 let flow_metadata_manager = FlowMetadataManager::new(mem_kv);
781 let flow_id = 10;
782 let flow_value = test_flow_info_value("flow", [(0, 1u64)].into(), vec![1024]);
783 let flow_routes = vec![(
784 0u32,
785 FlowRouteValue {
786 peer: Peer::new(1, "route-addr"),
787 },
788 )];
789
790 flow_metadata_manager
791 .create_flow_metadata(flow_id, flow_value, flow_routes)
792 .await
793 .unwrap();
794
795 let addrs = flow_metadata_manager.flownode_addrs(flow_id).await.unwrap();
796 assert_eq!(addrs, BTreeMap::from([(0, "route-addr".to_string())]));
797 }
798
799 #[tokio::test]
800 async fn test_flownode_addrs_skips_empty_addresses() {
801 let mem_kv = Arc::new(MemoryKvBackend::default());
802 let flow_metadata_manager = FlowMetadataManager::new(mem_kv);
803 let flow_id = 10;
804 let flow_value = test_flow_info_value("flow", [(0, 1u64)].into(), vec![1024]);
805 let flow_routes = vec![(
806 0u32,
807 FlowRouteValue {
808 peer: Peer::empty(1),
809 },
810 )];
811
812 flow_metadata_manager
813 .create_flow_metadata(flow_id, flow_value, flow_routes)
814 .await
815 .unwrap();
816
817 let addrs = flow_metadata_manager.flownode_addrs(flow_id).await.unwrap();
818 assert!(addrs.is_empty());
819 }
820
821 #[tokio::test]
822 async fn test_create_flow_metadata_flow_exists_err() {
823 let mem_kv = Arc::new(MemoryKvBackend::default());
824 let flow_metadata_manager = FlowMetadataManager::new(mem_kv);
825 let flow_id = 10;
826 let flow_value = test_flow_info_value("flow", [(0, 1u64)].into(), vec![1024, 1025, 1026]);
827 let flow_routes = vec![
828 (
829 1u32,
830 FlowRouteValue {
831 peer: Peer::empty(1),
832 },
833 ),
834 (
835 2,
836 FlowRouteValue {
837 peer: Peer::empty(2),
838 },
839 ),
840 ];
841 flow_metadata_manager
842 .create_flow_metadata(flow_id, flow_value.clone(), flow_routes.clone())
843 .await
844 .unwrap();
845 let err = flow_metadata_manager
847 .create_flow_metadata(flow_id + 1, flow_value, flow_routes.clone())
848 .await
849 .unwrap_err();
850 assert_matches!(err, error::Error::FlowAlreadyExists { .. });
851 }
852
853 #[tokio::test]
854 async fn test_create_flow_metadata_unexpected_err() {
855 let mem_kv = Arc::new(MemoryKvBackend::default());
856 let flow_metadata_manager = FlowMetadataManager::new(mem_kv);
857 let flow_id = 10;
858 let catalog_name = "greptime";
859 let flow_value = test_flow_info_value("flow", [(0, 1u64)].into(), vec![1024, 1025, 1026]);
860 let flow_routes = vec![
861 (
862 1u32,
863 FlowRouteValue {
864 peer: Peer::empty(1),
865 },
866 ),
867 (
868 2,
869 FlowRouteValue {
870 peer: Peer::empty(2),
871 },
872 ),
873 ];
874 flow_metadata_manager
875 .create_flow_metadata(flow_id, flow_value.clone(), flow_routes.clone())
876 .await
877 .unwrap();
878 let another_sink_table_name = TableName {
880 catalog_name: catalog_name.to_string(),
881 schema_name: "my_schema".to_string(),
882 table_name: "another_sink_table".to_string(),
883 };
884 let flow_value = FlowInfoValue {
885 catalog_name: "greptime".to_string(),
886 query_context: None,
887 flow_name: "flow".to_string(),
888 source_table_ids: vec![1024, 1025, 1026],
889 all_source_table_names: vec![],
890 unresolved_source_table_names: vec![],
891 sink_table_name: another_sink_table_name,
892 flownode_ids: [(0, 1u64)].into(),
893 raw_sql: "raw".to_string(),
894 expire_after: Some(300),
895 eval_interval_secs: None,
896 comment: "hi".to_string(),
897 options: Default::default(),
898 status: FlowStatus::Active,
899 created_time: chrono::Utc::now(),
900 updated_time: chrono::Utc::now(),
901 eval_schedule: None,
902 allow_sink_create: true,
903 };
904 let err = flow_metadata_manager
905 .create_flow_metadata(flow_id, flow_value, flow_routes.clone())
906 .await
907 .unwrap_err();
908 assert!(err.to_string().contains("Reads the different value"));
909 }
910
911 #[tokio::test]
912 async fn test_destroy_flow_metadata() {
913 let mem_kv = Arc::new(MemoryKvBackend::default());
914 let flow_metadata_manager = FlowMetadataManager::new(mem_kv.clone());
915 let flow_id = 10;
916 let flow_value = test_flow_info_value("flow", [(0, 1u64)].into(), vec![1024, 1025, 1026]);
917 let flow_routes = vec![(
918 0u32,
919 FlowRouteValue {
920 peer: Peer::empty(1),
921 },
922 )];
923 flow_metadata_manager
924 .create_flow_metadata(flow_id, flow_value.clone(), flow_routes.clone())
925 .await
926 .unwrap();
927
928 flow_metadata_manager
929 .destroy_flow_metadata(flow_id, &flow_value)
930 .await
931 .unwrap();
932 flow_metadata_manager
934 .destroy_flow_metadata(flow_id, &flow_value)
935 .await
936 .unwrap();
937 assert!(mem_kv.is_empty())
939 }
940
941 #[tokio::test]
942 async fn test_update_flow_metadata() {
943 let mem_kv = Arc::new(MemoryKvBackend::default());
944 let flow_metadata_manager = FlowMetadataManager::new(mem_kv.clone());
945 let flow_id = 10;
946 let flow_value = test_flow_info_value(
947 "flow",
948 [(0, 1u64), (1, 2u64)].into(),
949 vec![1024, 1025, 1026],
950 );
951 let flow_routes = vec![
952 (
953 1u32,
954 FlowRouteValue {
955 peer: Peer::empty(1),
956 },
957 ),
958 (
959 2,
960 FlowRouteValue {
961 peer: Peer::empty(2),
962 },
963 ),
964 ];
965 flow_metadata_manager
966 .create_flow_metadata(flow_id, flow_value.clone(), flow_routes.clone())
967 .await
968 .unwrap();
969
970 let new_flow_value = {
971 let mut tmp = flow_value.clone();
972 tmp.raw_sql = "new".to_string();
973 tmp
974 };
975
976 flow_metadata_manager
978 .update_flow_metadata(
979 flow_id,
980 &DeserializedValueWithBytes::from_inner(flow_value.clone()),
981 &new_flow_value,
982 flow_routes.clone(),
983 )
984 .await
985 .unwrap();
986
987 let got = flow_metadata_manager
988 .flow_info_manager()
989 .get(flow_id)
990 .await
991 .unwrap()
992 .unwrap();
993 let routes = flow_metadata_manager
994 .flow_route_manager()
995 .routes(flow_id)
996 .await
997 .unwrap();
998 assert_eq!(
999 routes,
1000 vec![
1001 (
1002 FlowRouteKey::new(flow_id, 1),
1003 FlowRouteValue {
1004 peer: Peer::empty(1),
1005 },
1006 ),
1007 (
1008 FlowRouteKey::new(flow_id, 2),
1009 FlowRouteValue {
1010 peer: Peer::empty(2),
1011 },
1012 ),
1013 ]
1014 );
1015 assert_eq!(got, new_flow_value);
1016 let flows = flow_metadata_manager
1017 .flownode_flow_manager()
1018 .flows(1)
1019 .try_collect::<Vec<_>>()
1020 .await
1021 .unwrap();
1022 assert_eq!(flows, vec![(flow_id, 0)]);
1023 for table_id in [1024, 1025, 1026] {
1024 let nodes = flow_metadata_manager
1025 .table_flow_manager()
1026 .flows(table_id)
1027 .await
1028 .unwrap();
1029 assert_eq!(
1030 nodes,
1031 vec![
1032 (
1033 TableFlowKey::new(table_id, 1, flow_id, 1),
1034 TableFlowValue {
1035 peer: Peer::empty(1)
1036 }
1037 ),
1038 (
1039 TableFlowKey::new(table_id, 2, flow_id, 2),
1040 TableFlowValue {
1041 peer: Peer::empty(2)
1042 }
1043 )
1044 ]
1045 );
1046 }
1047 }
1048
1049 #[tokio::test]
1050 async fn test_update_flow_metadata_diff_flownode() {
1051 let mem_kv = Arc::new(MemoryKvBackend::default());
1052 let flow_metadata_manager = FlowMetadataManager::new(mem_kv.clone());
1053 let flow_id = 10;
1054 let flow_value = test_flow_info_value(
1055 "flow",
1056 [(0u32, 1u64), (1u32, 2u64)].into(),
1057 vec![1024, 1025, 1026],
1058 );
1059 let flow_routes = vec![
1060 (
1061 0u32,
1062 FlowRouteValue {
1063 peer: Peer::empty(1),
1064 },
1065 ),
1066 (
1067 1,
1068 FlowRouteValue {
1069 peer: Peer::empty(2),
1070 },
1071 ),
1072 ];
1073 flow_metadata_manager
1074 .create_flow_metadata(flow_id, flow_value.clone(), flow_routes.clone())
1075 .await
1076 .unwrap();
1077
1078 let new_flow_value = {
1079 let mut tmp = flow_value.clone();
1080 tmp.raw_sql = "new".to_string();
1081 tmp.flownode_ids = [(0, 3u64), (1, 4u64)].into();
1083 tmp
1084 };
1085 let new_flow_routes = vec![
1086 (
1087 0u32,
1088 FlowRouteValue {
1089 peer: Peer::empty(3),
1090 },
1091 ),
1092 (
1093 1,
1094 FlowRouteValue {
1095 peer: Peer::empty(4),
1096 },
1097 ),
1098 ];
1099
1100 flow_metadata_manager
1102 .update_flow_metadata(
1103 flow_id,
1104 &DeserializedValueWithBytes::from_inner(flow_value.clone()),
1105 &new_flow_value,
1106 new_flow_routes.clone(),
1107 )
1108 .await
1109 .unwrap();
1110
1111 let got = flow_metadata_manager
1112 .flow_info_manager()
1113 .get(flow_id)
1114 .await
1115 .unwrap()
1116 .unwrap();
1117 let routes = flow_metadata_manager
1118 .flow_route_manager()
1119 .routes(flow_id)
1120 .await
1121 .unwrap();
1122 assert_eq!(
1123 routes,
1124 vec![
1125 (
1126 FlowRouteKey::new(flow_id, 0),
1127 FlowRouteValue {
1128 peer: Peer::empty(3),
1129 },
1130 ),
1131 (
1132 FlowRouteKey::new(flow_id, 1),
1133 FlowRouteValue {
1134 peer: Peer::empty(4),
1135 },
1136 ),
1137 ]
1138 );
1139 assert_eq!(got, new_flow_value);
1140
1141 let flows = flow_metadata_manager
1142 .flownode_flow_manager()
1143 .flows(1)
1144 .try_collect::<Vec<_>>()
1145 .await
1146 .unwrap();
1147 assert_eq!(flows, vec![]);
1149
1150 let flows = flow_metadata_manager
1151 .flownode_flow_manager()
1152 .flows(3)
1153 .try_collect::<Vec<_>>()
1154 .await
1155 .unwrap();
1156 assert_eq!(flows, vec![(flow_id, 0)]);
1157
1158 for table_id in [1024, 1025, 1026] {
1159 let nodes = flow_metadata_manager
1160 .table_flow_manager()
1161 .flows(table_id)
1162 .await
1163 .unwrap();
1164 assert_eq!(
1165 nodes,
1166 vec![
1167 (
1168 TableFlowKey::new(table_id, 3, flow_id, 0),
1169 TableFlowValue {
1170 peer: Peer::empty(3)
1171 }
1172 ),
1173 (
1174 TableFlowKey::new(table_id, 4, flow_id, 1),
1175 TableFlowValue {
1176 peer: Peer::empty(4)
1177 }
1178 )
1179 ]
1180 );
1181 }
1182 }
1183
1184 #[tokio::test]
1185 async fn test_update_flow_metadata_flow_replace_diff_id_err() {
1186 let mem_kv = Arc::new(MemoryKvBackend::default());
1187 let flow_metadata_manager = FlowMetadataManager::new(mem_kv);
1188 let flow_id = 10;
1189 let flow_value = test_flow_info_value("flow", [(0, 1u64)].into(), vec![1024, 1025, 1026]);
1190 let flow_routes = vec![
1191 (
1192 1u32,
1193 FlowRouteValue {
1194 peer: Peer::empty(1),
1195 },
1196 ),
1197 (
1198 2,
1199 FlowRouteValue {
1200 peer: Peer::empty(2),
1201 },
1202 ),
1203 ];
1204 flow_metadata_manager
1205 .create_flow_metadata(flow_id, flow_value.clone(), flow_routes.clone())
1206 .await
1207 .unwrap();
1208 flow_metadata_manager
1210 .update_flow_metadata(
1211 flow_id,
1212 &DeserializedValueWithBytes::from_inner(flow_value.clone()),
1213 &flow_value,
1214 flow_routes.clone(),
1215 )
1216 .await
1217 .unwrap();
1218 let err = flow_metadata_manager
1220 .update_flow_metadata(
1221 flow_id + 1,
1222 &DeserializedValueWithBytes::from_inner(flow_value.clone()),
1223 &flow_value,
1224 flow_routes,
1225 )
1226 .await
1227 .unwrap_err();
1228 assert_matches!(err, error::Error::Unexpected { .. });
1229 assert!(
1230 err.to_string()
1231 .contains("Reads different flow id when updating flow")
1232 );
1233 }
1234
1235 #[tokio::test]
1236 async fn test_update_flow_metadata_unexpected_err_prev_value_diff() {
1237 let mem_kv = Arc::new(MemoryKvBackend::default());
1238 let flow_metadata_manager = FlowMetadataManager::new(mem_kv);
1239 let flow_id = 10;
1240 let catalog_name = "greptime";
1241 let flow_value = test_flow_info_value("flow", [(0, 1u64)].into(), vec![1024, 1025, 1026]);
1242 let flow_routes = vec![
1243 (
1244 1u32,
1245 FlowRouteValue {
1246 peer: Peer::empty(1),
1247 },
1248 ),
1249 (
1250 2,
1251 FlowRouteValue {
1252 peer: Peer::empty(2),
1253 },
1254 ),
1255 ];
1256 flow_metadata_manager
1257 .create_flow_metadata(flow_id, flow_value.clone(), flow_routes.clone())
1258 .await
1259 .unwrap();
1260 let another_sink_table_name = TableName {
1262 catalog_name: catalog_name.to_string(),
1263 schema_name: "my_schema".to_string(),
1264 table_name: "another_sink_table".to_string(),
1265 };
1266 let flow_value = FlowInfoValue {
1267 catalog_name: "greptime".to_string(),
1268 query_context: None,
1269 flow_name: "flow".to_string(),
1270 source_table_ids: vec![1024, 1025, 1026],
1271 all_source_table_names: vec![],
1272 unresolved_source_table_names: vec![],
1273 sink_table_name: another_sink_table_name,
1274 flownode_ids: [(0, 1u64)].into(),
1275 raw_sql: "raw".to_string(),
1276 expire_after: Some(300),
1277 eval_interval_secs: None,
1278 comment: "hi".to_string(),
1279 options: Default::default(),
1280 status: FlowStatus::Active,
1281 created_time: chrono::Utc::now(),
1282 updated_time: chrono::Utc::now(),
1283 eval_schedule: None,
1284 allow_sink_create: true,
1285 };
1286 let err = flow_metadata_manager
1287 .update_flow_metadata(
1288 flow_id,
1289 &DeserializedValueWithBytes::from_inner(flow_value.clone()),
1290 &flow_value,
1291 flow_routes.clone(),
1292 )
1293 .await
1294 .unwrap_err();
1295 assert!(
1296 err.to_string().contains("Reads the different value"),
1297 "error: {:?}",
1298 err
1299 );
1300 }
1301
1302 #[test]
1303 fn test_build_replace_ops() {
1304 let ops = build_replace_ops(
1305 vec![b"a".to_vec(), b"b".to_vec()],
1306 vec![
1307 (b"b".to_vec(), b"1".to_vec()),
1308 (b"c".to_vec(), b"2".to_vec()),
1309 ],
1310 );
1311 assert_eq!(
1312 ops,
1313 vec![
1314 TxnOp::Delete(b"a".to_vec()),
1315 TxnOp::Put(b"b".to_vec(), b"1".to_vec()),
1316 TxnOp::Put(b"c".to_vec(), b"2".to_vec()),
1317 ]
1318 );
1319 }
1320
1321 async fn build_kv_backend() -> KvBackendRef {
1324 let endpoints = std::env::var("GT_ETCD_ENDPOINTS").unwrap_or_default();
1325 if endpoints.is_empty() {
1326 return Arc::new(MemoryKvBackend::default());
1327 }
1328 let endpoints = endpoints.split(',').collect::<Vec<_>>();
1329 let backend = EtcdStore::with_endpoints(endpoints, 128).await.unwrap();
1330 let chroot = format!("test_update_flow_metadata/{}/", Uuid::new_v4());
1331 Arc::new(ChrootKvBackend::new(chroot.into(), backend))
1332 }
1333
1334 async fn assert_flow_metadata(
1335 manager: &FlowMetadataManager,
1336 flow_id: FlowId,
1337 flow_info: &FlowInfoValue,
1338 ) {
1339 let got = manager.flow_info_manager().get(flow_id).await.unwrap();
1340 assert_eq!(got.as_ref(), Some(flow_info));
1341
1342 let routes = manager.flow_route_manager().routes(flow_id).await.unwrap();
1343 let expected_routes = flow_info
1344 .flownode_ids()
1345 .iter()
1346 .map(|(partition_id, flownode_id)| {
1347 (
1348 FlowRouteKey::new(flow_id, *partition_id),
1349 FlowRouteValue {
1350 peer: Peer::empty(*flownode_id),
1351 },
1352 )
1353 })
1354 .collect::<Vec<_>>();
1355 assert_eq!(routes, expected_routes);
1356
1357 for flownode_id in 1..=4 {
1358 let flows = manager
1359 .flownode_flow_manager()
1360 .flows(flownode_id)
1361 .try_collect::<Vec<_>>()
1362 .await
1363 .unwrap();
1364 let expected = flow_info
1365 .flownode_ids()
1366 .iter()
1367 .filter(|(_, id)| **id == flownode_id)
1368 .map(|(partition_id, _)| (flow_id, *partition_id))
1369 .collect::<Vec<_>>();
1370 assert_eq!(flows, expected, "flownode {flownode_id}");
1371 }
1372
1373 for table_id in 1024..=1027 {
1374 let flows = manager
1375 .table_flow_manager()
1376 .flows(table_id)
1377 .await
1378 .unwrap()
1379 .into_iter()
1380 .map(|(key, _)| (key.flownode_id(), key.partition_id()))
1381 .collect::<Vec<_>>();
1382 let expected = if flow_info.source_table_ids().contains(&table_id) {
1383 flow_info
1384 .flownode_ids()
1385 .iter()
1386 .map(|(partition_id, flownode_id)| (*flownode_id, *partition_id))
1387 .collect()
1388 } else {
1389 vec![]
1390 };
1391 assert_eq!(flows, expected, "table {table_id}");
1392 }
1393 }
1394
1395 #[tokio::test]
1396 async fn test_update_flow_metadata_with_overlapping_keys() {
1397 let flow_metadata_manager = FlowMetadataManager::new(build_kv_backend().await);
1398 let flow_id = 10;
1399 let to_routes = |flow_info: &FlowInfoValue| {
1400 flow_info
1401 .flownode_ids()
1402 .iter()
1403 .map(|(partition_id, flownode_id)| {
1404 (
1405 *partition_id,
1406 FlowRouteValue {
1407 peer: Peer::empty(*flownode_id),
1408 },
1409 )
1410 })
1411 .collect::<Vec<_>>()
1412 };
1413
1414 let mut current =
1415 test_flow_info_value("flow", [(0, 1u64), (1, 2u64)].into(), vec![1024, 1025]);
1416 flow_metadata_manager
1417 .create_flow_metadata(flow_id, current.clone(), to_routes(¤t))
1418 .await
1419 .unwrap();
1420 assert_flow_metadata(&flow_metadata_manager, flow_id, ¤t).await;
1421
1422 let updates = [
1423 ([(0, 1u64), (1, 2u64)].into(), vec![1024, 1025]),
1425 ([(0, 1u64), (1, 3u64)].into(), vec![1025, 1026]),
1427 ([(2, 4u64)].into(), vec![1027]),
1429 ];
1430 for (i, (flownode_ids, source_table_ids)) in updates.into_iter().enumerate() {
1431 let mut new_flow_info = current.clone();
1432 new_flow_info.raw_sql = format!("update {i}");
1433 new_flow_info.flownode_ids = flownode_ids;
1434 new_flow_info.source_table_ids = source_table_ids;
1435 flow_metadata_manager
1436 .update_flow_metadata(
1437 flow_id,
1438 &DeserializedValueWithBytes::from_inner(current.clone()),
1439 &new_flow_info,
1440 to_routes(&new_flow_info),
1441 )
1442 .await
1443 .unwrap();
1444 assert_flow_metadata(&flow_metadata_manager, flow_id, &new_flow_info).await;
1445 current = new_flow_info;
1446 }
1447 }
1448}