Skip to main content

common_meta/cache/flow/
table_flownode.rs

1// Copyright 2023 Greptime Team
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::HashMap;
16use std::sync::Arc;
17
18use common_telemetry::info;
19use futures::future::BoxFuture;
20use moka::future::Cache;
21use moka::ops::compute::Op;
22use table::metadata::TableId;
23
24use crate::cache::container::{CacheEntries, Invalidation};
25use crate::cache::{CacheContainer, Initializer};
26use crate::instruction::{CacheIdent, CreateFlow, DropFlow};
27use crate::key::flow::{TableFlowManager, TableFlowManagerRef};
28use crate::key::{FlowId, FlowPartitionId};
29use crate::kv_backend::KvBackendRef;
30use crate::peer::Peer;
31
32/// Flow id&flow partition key
33#[derive(Debug, Clone, PartialEq, Eq, Hash)]
34pub struct FlowIdent {
35    pub flow_id: FlowId,
36    pub partition_id: FlowPartitionId,
37}
38
39impl FlowIdent {
40    pub fn new(flow_id: FlowId, partition_id: FlowPartitionId) -> Self {
41        Self {
42            flow_id,
43            partition_id,
44        }
45    }
46}
47
48/// cache for TableFlowManager, the table_id part is in the outer cache
49/// include flownode_id, flow_id, partition_id mapping to Peer
50type FlownodeFlowSet = Arc<HashMap<FlowIdent, Peer>>;
51
52pub type TableFlownodeSetCacheRef = Arc<TableFlownodeSetCache>;
53
54/// [TableFlownodeSetCache] caches the [TableId] to [FlownodeSet] mapping.
55pub type TableFlownodeSetCache = CacheContainer<TableId, FlownodeFlowSet, CacheIdent>;
56
57/// Constructs a [TableFlownodeSetCache].
58pub fn new_table_flownode_set_cache(
59    name: String,
60    cache: Cache<(usize, TableId), FlownodeFlowSet>,
61    kv_backend: KvBackendRef,
62) -> TableFlownodeSetCache {
63    let table_flow_manager = Arc::new(TableFlowManager::new(kv_backend));
64    let init = init_factory(table_flow_manager);
65
66    CacheContainer::with_invalidation(
67        name,
68        cache,
69        init,
70        Invalidation::Events(Box::new(invalidator)),
71    )
72}
73
74fn init_factory(table_flow_manager: TableFlowManagerRef) -> Initializer<TableId, FlownodeFlowSet> {
75    Arc::new(move |&table_id| {
76        let table_flow_manager = table_flow_manager.clone();
77        Box::pin(async move {
78            table_flow_manager
79                .flows(table_id)
80                .await
81                .map(|flows| {
82                    flows
83                        .into_iter()
84                        .map(|(key, value)| {
85                            (
86                                FlowIdent::new(key.flow_id(), key.partition_id()),
87                                value.peer,
88                            )
89                        })
90                        .collect::<HashMap<_, _>>()
91                })
92                // We must cache the `HashSet` even if it's empty,
93                // to avoid future requests to the remote storage next time;
94                // If the value is added to the remote storage,
95                // we have a corresponding cache invalidation mechanism to invalidate `(Key, EmptyHashSet)`.
96                .map(Arc::new)
97                .map(Some)
98                .inspect(|set| {
99                    if set.as_ref().map(|s| !s.is_empty()).unwrap_or(false) {
100                        info!(
101                            "Initialized table_flownode cache for table_id: {}, set: {:?}",
102                            table_id, set
103                        );
104                    };
105                })
106        })
107    })
108}
109
110async fn handle_create_flow(
111    cache: &CacheEntries<'_, TableId, FlownodeFlowSet>,
112    CreateFlow {
113        flow_id,
114        source_table_ids,
115        partition_to_peer_mapping: flow_part2nodes,
116    }: &CreateFlow,
117) {
118    for table_id in source_table_ids {
119        cache
120            .compute(table_id, |entry| {
121                let Some(mut map) = entry else {
122                    // CreateFlow carries only the new flow. A cold lookup must load
123                    // all flows that use this source table.
124                    return Op::Nop;
125                };
126                Arc::make_mut(&mut map).extend(
127                    flow_part2nodes
128                        .iter()
129                        .map(|(part, peer)| (FlowIdent::new(*flow_id, *part), peer.clone())),
130                );
131                Op::Put(map)
132            })
133            .await;
134    }
135}
136
137async fn handle_drop_flow(
138    cache: &CacheEntries<'_, TableId, FlownodeFlowSet>,
139    DropFlow {
140        flow_id,
141        source_table_ids,
142        flow_part2node_id,
143    }: &DropFlow,
144) {
145    for table_id in source_table_ids {
146        cache
147            .compute(table_id, |entry| match entry {
148                Some(entry) => {
149                    let mut set = entry.as_ref().clone();
150                    for (part, _node) in flow_part2node_id {
151                        let key = FlowIdent::new(*flow_id, *part);
152                        set.remove(&key);
153                    }
154
155                    Op::Put(Arc::new(set))
156                }
157                None => {
158                    // Do nothing
159                    Op::Nop
160                }
161            })
162            .await;
163    }
164}
165
166fn invalidator<'a>(
167    cache: CacheEntries<'a, TableId, FlownodeFlowSet>,
168    idents: &'a [CacheIdent],
169) -> BoxFuture<'a, ()> {
170    Box::pin(async move {
171        for ident in idents {
172            match ident {
173                CacheIdent::CreateFlow(create_flow) => {
174                    handle_create_flow(&cache, create_flow).await
175                }
176                CacheIdent::DropFlow(drop_flow) => handle_drop_flow(&cache, drop_flow).await,
177                CacheIdent::FlowNodeAddressChange(node_id) => {
178                    info!(
179                        "Invalidate flow node cache for node_id in table_flownode: {}",
180                        node_id
181                    );
182                    cache.invalidate_all();
183                }
184                _ => {}
185            }
186        }
187    })
188}
189
190#[cfg(test)]
191mod tests {
192    use std::collections::{BTreeMap, HashMap};
193    use std::sync::Arc;
194
195    use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
196    use moka::future::CacheBuilder;
197    use table::table_name::TableName;
198
199    use crate::cache::flow::table_flownode::{FlowIdent, new_table_flownode_set_cache};
200    use crate::instruction::{CacheIdent, CreateFlow, DropFlow};
201    use crate::key::flow::FlowMetadataManager;
202    use crate::key::flow::flow_info::{FlowInfoValue, FlowStatus};
203    use crate::key::flow::flow_route::FlowRouteValue;
204    use crate::kv_backend::memory::MemoryKvBackend;
205    use crate::peer::Peer;
206
207    #[tokio::test]
208    async fn test_cache_empty_set() {
209        let mem_kv = Arc::new(MemoryKvBackend::default());
210        let cache = CacheBuilder::new(128).build();
211        let cache = new_table_flownode_set_cache("test".to_string(), cache, mem_kv);
212        let set = cache.get(1024).await.unwrap().unwrap();
213        assert!(set.is_empty());
214    }
215
216    #[tokio::test]
217    async fn test_get() {
218        let mem_kv = Arc::new(MemoryKvBackend::default());
219        let flownode_metadata_manager = FlowMetadataManager::new(mem_kv.clone());
220        flownode_metadata_manager
221            .create_flow_metadata(
222                1024,
223                FlowInfoValue {
224                    source_table_ids: vec![1024, 1025],
225                    sink_table_name: TableName {
226                        catalog_name: DEFAULT_CATALOG_NAME.to_string(),
227                        schema_name: DEFAULT_SCHEMA_NAME.to_string(),
228                        table_name: "sink_table".to_string(),
229                    },
230                    flownode_ids: BTreeMap::from([(0, 1), (1, 2), (2, 3)]),
231                    catalog_name: DEFAULT_CATALOG_NAME.to_string(),
232                    query_context: None,
233                    flow_name: "my_flow".to_string(),
234                    all_source_table_names: vec![],
235                    unresolved_source_table_names: vec![],
236                    raw_sql: "sql".to_string(),
237                    expire_after: Some(300),
238                    eval_interval_secs: None,
239                    comment: "comment".to_string(),
240                    options: Default::default(),
241                    status: FlowStatus::Active,
242                    created_time: chrono::Utc::now(),
243                    updated_time: chrono::Utc::now(),
244                    eval_schedule: None,
245                    allow_sink_create: true,
246                },
247                (1..=3)
248                    .map(|i| {
249                        (
250                            (i - 1) as u32,
251                            FlowRouteValue {
252                                peer: Peer::empty(i),
253                            },
254                        )
255                    })
256                    .collect::<Vec<_>>(),
257            )
258            .await
259            .unwrap();
260        let cache = CacheBuilder::new(128).build();
261        let cache = new_table_flownode_set_cache("test".to_string(), cache, mem_kv);
262        let set = cache.get(1024).await.unwrap().unwrap();
263        assert_eq!(
264            set.as_ref().clone(),
265            HashMap::from_iter(
266                (1..=3).map(|i| { (FlowIdent::new(1024, (i - 1) as u32), Peer::empty(i),) })
267            )
268        );
269        let set = cache.get(1025).await.unwrap().unwrap();
270        assert_eq!(
271            set.as_ref().clone(),
272            HashMap::from_iter(
273                (1..=3).map(|i| { (FlowIdent::new(1024, (i - 1) as u32), Peer::empty(i),) })
274            )
275        );
276        let result = cache.get(1026).await.unwrap().unwrap();
277        assert_eq!(result.len(), 0);
278    }
279
280    #[tokio::test]
281    async fn test_create_flow_updates_warm_table_and_reloads_cold_table() {
282        use crate::key::flow::table_flow::{TableFlowManager, TableFlowValue};
283        use crate::kv_backend::TxnService;
284
285        let backend = Arc::new(MemoryKvBackend::default());
286        let manager = TableFlowManager::new(backend.clone());
287        let cache = new_table_flownode_set_cache(
288            "test".into(),
289            CacheBuilder::new(8).build(),
290            backend.clone(),
291        );
292        let tables = [1024, 1025];
293        let create_flow = |flow_id, peer_id| {
294            manager
295                .build_create_txn(
296                    flow_id,
297                    vec![(
298                        0,
299                        TableFlowValue {
300                            peer: Peer::empty(peer_id),
301                        },
302                    )],
303                    &tables,
304                )
305                .unwrap()
306        };
307        backend.txn(create_flow(1, 10)).await.unwrap();
308        // Both tables feed the old flow, but only the first mapping is cached.
309        assert_eq!(1, cache.get(tables[0]).await.unwrap().unwrap().len());
310        backend.txn(create_flow(2, 20)).await.unwrap();
311
312        cache
313            .invalidate(&[CacheIdent::CreateFlow(CreateFlow {
314                flow_id: 2,
315                source_table_ids: tables.to_vec(),
316                partition_to_peer_mapping: vec![(0, Peer::empty(20))],
317            })])
318            .await
319            .unwrap();
320
321        assert!(cache.contains_key(&tables[0]));
322        assert!(!cache.contains_key(&tables[1]));
323        let expected = HashMap::from([
324            (FlowIdent::new(1, 0), Peer::empty(10)),
325            (FlowIdent::new(2, 0), Peer::empty(20)),
326        ]);
327        for id in tables {
328            assert_eq!(&expected, cache.get(id).await.unwrap().unwrap().as_ref());
329        }
330    }
331
332    #[tokio::test]
333    async fn test_flow_event_waits_for_source_lookup() {
334        let (started, mut loads) = tokio::sync::mpsc::unbounded_channel();
335        let cache = super::CacheContainer::with_invalidation(
336            "test".into(),
337            CacheBuilder::new(8).build(),
338            Arc::new(move |_| {
339                let (resume, gate) = tokio::sync::oneshot::channel();
340                started.send(resume).unwrap();
341                Box::pin(async move {
342                    gate.await.unwrap();
343                    Ok(Some(Arc::new(HashMap::new())))
344                })
345            }),
346            super::Invalidation::Events(Box::new(super::invalidator)),
347        );
348        let mut read = Box::pin(cache.get(1));
349        assert!(futures::poll!(&mut read).is_pending());
350        let resume = loads.try_recv().unwrap();
351        let events = [CacheIdent::CreateFlow(CreateFlow {
352            flow_id: 3,
353            source_table_ids: vec![1, 2],
354            partition_to_peer_mapping: [(0, Peer::empty(7))].into_iter().collect(),
355        })];
356        let mut update = Box::pin(cache.invalidate(&events));
357        assert!(futures::poll!(&mut update).is_pending());
358        resume.send(()).unwrap();
359        assert!(read.await.unwrap().unwrap().is_empty());
360        update.await.unwrap();
361        let set = cache.get(1).await.unwrap().unwrap();
362        assert_eq!(set[&FlowIdent::new(3, 0)], Peer::empty(7));
363        assert!(!cache.contains_key(&2));
364        cache
365            .invalidate(&[CacheIdent::FlowNodeAddressChange(7)])
366            .await
367            .unwrap();
368        assert!(!cache.contains_key(&1));
369        assert!(!cache.contains_key(&2));
370    }
371
372    #[tokio::test]
373    async fn test_replace_flow() {
374        let mem_kv = Arc::new(MemoryKvBackend::default());
375        let cache = CacheBuilder::new(128).build();
376        let cache = new_table_flownode_set_cache("test".to_string(), cache, mem_kv);
377        for id in [1024, 1025, 1026, 1027] {
378            assert!(cache.get(id).await.unwrap().unwrap().is_empty());
379        }
380        let ident = vec![CacheIdent::CreateFlow(CreateFlow {
381            flow_id: 2001,
382            source_table_ids: vec![1024, 1025],
383            partition_to_peer_mapping: (1..=5).map(|i| (i as u32, Peer::empty(i + 1))).collect(),
384        })];
385        cache.invalidate(&ident).await.unwrap();
386        let set = cache.get(1024).await.unwrap().unwrap();
387        assert_eq!(set.len(), 5);
388        let set = cache.get(1025).await.unwrap().unwrap();
389        assert_eq!(set.len(), 5);
390
391        let drop_then_create_flow = vec![
392            CacheIdent::DropFlow(DropFlow {
393                flow_id: 2001,
394                source_table_ids: vec![1024, 1025],
395                flow_part2node_id: (1..=5).map(|i| (i as u32, i + 1)).collect(),
396            }),
397            CacheIdent::CreateFlow(CreateFlow {
398                flow_id: 2001,
399                source_table_ids: vec![1026, 1027],
400                partition_to_peer_mapping: (11..=15)
401                    .map(|i| (i as u32, Peer::empty(i + 1)))
402                    .collect(),
403            }),
404            CacheIdent::FlowId(2001),
405        ];
406        cache.invalidate(&drop_then_create_flow).await.unwrap();
407
408        let set = cache.get(1024).await.unwrap().unwrap();
409        assert!(set.is_empty());
410
411        let expected = HashMap::from_iter(
412            (11..=15).map(|i| (FlowIdent::new(2001, i as u32), Peer::empty(i + 1))),
413        );
414        let set = cache.get(1026).await.unwrap().unwrap();
415
416        assert_eq!(set.as_ref().clone(), expected);
417
418        let set = cache.get(1027).await.unwrap().unwrap();
419
420        assert_eq!(set.as_ref().clone(), expected);
421    }
422
423    #[tokio::test]
424    async fn test_drop_flow() {
425        let mem_kv = Arc::new(MemoryKvBackend::default());
426        let cache = CacheBuilder::new(128).build();
427        let cache = new_table_flownode_set_cache("test".to_string(), cache, mem_kv);
428        for id in [1024, 1025] {
429            assert!(cache.get(id).await.unwrap().unwrap().is_empty());
430        }
431        let ident = vec![
432            CacheIdent::CreateFlow(CreateFlow {
433                flow_id: 2001,
434                source_table_ids: vec![1024, 1025],
435                partition_to_peer_mapping: (1..=5)
436                    .map(|i| (i as u32, Peer::empty(i + 1)))
437                    .collect(),
438            }),
439            CacheIdent::CreateFlow(CreateFlow {
440                flow_id: 2002,
441                source_table_ids: vec![1024, 1025],
442                partition_to_peer_mapping: (11..=12)
443                    .map(|i| (i as u32, Peer::empty(i + 1)))
444                    .collect(),
445            }),
446            // same flownode that hold multiple flows
447            CacheIdent::CreateFlow(CreateFlow {
448                flow_id: 2003,
449                source_table_ids: vec![1024, 1025],
450                partition_to_peer_mapping: (1..=5)
451                    .map(|i| (i as u32, Peer::empty(i + 1)))
452                    .collect(),
453            }),
454        ];
455        cache.invalidate(&ident).await.unwrap();
456        let set = cache.get(1024).await.unwrap().unwrap();
457        assert_eq!(set.len(), 12);
458        let set = cache.get(1025).await.unwrap().unwrap();
459        assert_eq!(set.len(), 12);
460
461        let ident = vec![CacheIdent::DropFlow(DropFlow {
462            flow_id: 2001,
463            source_table_ids: vec![1024, 1025],
464            flow_part2node_id: (1..=5).map(|i| (i as u32, i + 1)).collect(),
465        })];
466        cache.invalidate(&ident).await.unwrap();
467        let set = cache.get(1024).await.unwrap().unwrap();
468        assert_eq!(
469            set.as_ref().clone(),
470            HashMap::from_iter(
471                (11..=12)
472                    .map(|i| (FlowIdent::new(2002, i as u32), Peer::empty(i + 1)))
473                    .chain((1..=5).map(|i| (FlowIdent::new(2003, i as u32), Peer::empty(i + 1))))
474            )
475        );
476        let set = cache.get(1025).await.unwrap().unwrap();
477        assert_eq!(
478            set.as_ref().clone(),
479            HashMap::from_iter(
480                (11..=12)
481                    .map(|i| (FlowIdent::new(2002, i as u32), Peer::empty(i + 1)))
482                    .chain((1..=5).map(|i| (FlowIdent::new(2003, i as u32), Peer::empty(i + 1))))
483            )
484        );
485    }
486}