Skip to main content

servers/batcher/logical_table/
flow_notifier.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
15#[cfg(test)]
16use common_meta::cache::TableFlownodeSetCacheRef;
17#[cfg(test)]
18use common_meta::node_manager::NodeManagerRef;
19use common_telemetry::error;
20use datatypes::timestamp::append_timestamps;
21
22use crate::batcher::flow_notifier::FlowNotifier;
23#[cfg(test)]
24use crate::batcher::flow_notifier::start_flow_notification_worker;
25use crate::batcher::flow_sender::FlowNotification;
26use crate::batcher::logical_table::batch_convert::TableBatch;
27#[cfg(test)]
28use crate::metrics::FLOW_NOTIFICATION_DROPPED;
29
30pub(in crate::batcher::logical_table) fn extract_timestamps(table_batch: &TableBatch) -> Vec<i64> {
31    let mut timestamps = Vec::with_capacity(table_batch.row_count);
32    for batch in &table_batch.batches {
33        let timestamp_column = batch.batch.column(batch.timestamp_index);
34        let Some(()) = append_timestamps(timestamp_column, &mut timestamps) else {
35            error!(
36                "Failed to extract timestamps from record batch, table_id: {}, timestamp_index: {}",
37                table_batch.table_id, batch.timestamp_index
38            );
39            continue;
40        };
41    }
42    timestamps
43}
44
45pub(in crate::batcher::logical_table) fn enqueue_flow_notifications(
46    table_batches: Vec<TableBatch>,
47    tx: &FlowNotifier,
48) {
49    for table_batch in table_batches {
50        let timestamps = extract_timestamps(&table_batch);
51        if timestamps.is_empty() {
52            continue;
53        }
54        tx.try_notify(FlowNotification {
55            table_id: table_batch.table_id,
56            timestamps,
57        });
58    }
59}
60
61#[cfg(test)]
62pub(in crate::batcher::logical_table) fn notify_flow_dirty_windows_after_flush(
63    table_batches: Vec<TableBatch>,
64    table_flownode_set_cache: TableFlownodeSetCacheRef,
65    node_manager: NodeManagerRef,
66) {
67    let (tx, rx) = FlowNotifier::try_new(
68        table_batches.len().max(1),
69        FLOW_NOTIFICATION_DROPPED.clone(),
70    )
71    .unwrap();
72    start_flow_notification_worker(rx, table_flownode_set_cache, node_manager);
73    enqueue_flow_notifications(table_batches, &tx);
74}
75
76#[cfg(test)]
77mod tests {
78    use std::any::Any;
79    use std::sync::{Arc, Mutex};
80    use std::time::Duration;
81
82    use api::v1::meta::Peer;
83    use async_trait::async_trait;
84    use common_meta::cache::new_table_flownode_set_cache;
85    use common_meta::error::Result as MetaResult;
86    use common_meta::instruction::{CacheIdent, CreateFlow};
87    use common_meta::kv_backend::{KvBackend, TxnService};
88    use common_meta::node_manager::NodeManagerRef;
89    use common_meta::rpc::store::{
90        BatchDeleteRequest, BatchDeleteResponse, BatchGetRequest, BatchGetResponse,
91        BatchPutRequest, BatchPutResponse, DeleteRangeRequest, DeleteRangeResponse, PutRequest,
92        PutResponse, RangeRequest, RangeResponse,
93    };
94    use moka::future::CacheBuilder;
95    use tokio::sync::{Notify, mpsc, oneshot};
96
97    use crate::batcher::flow_notifier::FlowNotifier;
98    use crate::batcher::flow_sender::FlowNotification;
99    use crate::batcher::logical_table::batch_convert::TableBatch;
100    use crate::batcher::logical_table::flow_notifier::notify_flow_dirty_windows_after_flush;
101    use crate::batcher::logical_table::test_util::{
102        FlowNotificationMockNodeManager, RecordingFlownode, mock_aligned_tag_batch,
103    };
104    use crate::batcher::test_util::mock_table_flownode_cache;
105    use crate::metrics::FLOW_NOTIFICATION_DROPPED;
106
107    #[test]
108    fn test_flow_notification_queue_drops_when_full() {
109        let (tx, mut rx) = FlowNotifier::try_new(1, FLOW_NOTIFICATION_DROPPED.clone()).unwrap();
110        let notification = |table_id| FlowNotification {
111            table_id,
112            timestamps: vec![table_id as i64],
113        };
114        let dropped = FLOW_NOTIFICATION_DROPPED.with_label_values(&["full"]);
115        let dropped_before = dropped.get();
116
117        assert!(tx.try_notify(notification(1)));
118        assert!(!tx.try_notify(notification(2)));
119
120        assert_eq!(1, rx.try_recv().unwrap().table_id);
121        assert_eq!(dropped_before + 1, dropped.get());
122
123        let closed = FLOW_NOTIFICATION_DROPPED.with_label_values(&["closed"]);
124        let closed_before = closed.get();
125        drop(rx);
126        assert!(!tx.try_notify(notification(3)));
127        assert_eq!(closed_before + 1, closed.get());
128    }
129
130    #[tokio::test]
131    async fn test_flow_notifications_do_not_block_on_previous_table_cache_lookup() {
132        let blocked_table_id = 41;
133        let cached_table_id = 42;
134        let peer = Peer {
135            id: 7,
136            addr: "flow-7".to_string(),
137        };
138        let (range_started_tx, range_started_rx) = oneshot::channel();
139        let range_release = Arc::new(Notify::new());
140        let backend = Arc::new(BlockingRangeKvBackend {
141            range_started: Mutex::new(None),
142            range_release: range_release.clone(),
143        });
144        let cache = Arc::new(new_table_flownode_set_cache(
145            "test".to_string(),
146            CacheBuilder::new(2).build(),
147            backend.clone(),
148        ));
149        cache.get(cached_table_id).await.unwrap();
150        *backend.range_started.lock().unwrap() = Some(range_started_tx);
151        cache
152            .invalidate(&[CacheIdent::CreateFlow(CreateFlow {
153                flow_id: 1,
154                source_table_ids: vec![cached_table_id],
155                partition_to_peer_mapping: vec![(0, peer)],
156            })])
157            .await
158            .unwrap();
159        let (requests_tx, mut requests_rx) = mpsc::unbounded_channel();
160        let _requests_tx = requests_tx.clone();
161        let node_manager: NodeManagerRef = Arc::new(FlowNotificationMockNodeManager {
162            flownode: Arc::new(RecordingFlownode { requests_tx }),
163        });
164        let table_batches = vec![
165            TableBatch {
166                table_name: "blocked".to_string(),
167                table_id: blocked_table_id,
168                batches: vec![mock_aligned_tag_batch("tag1", "host-1", 1000, 1.0)],
169                row_count: 1,
170            },
171            TableBatch {
172                table_name: "cached".to_string(),
173                table_id: cached_table_id,
174                batches: vec![mock_aligned_tag_batch("tag1", "host-2", 2000, 2.0)],
175                row_count: 1,
176            },
177        ];
178
179        notify_flow_dirty_windows_after_flush(table_batches, cache, node_manager);
180
181        tokio::time::timeout(Duration::from_secs(1), range_started_rx)
182            .await
183            .unwrap()
184            .unwrap();
185        let requests = tokio::time::timeout(Duration::from_secs(1), requests_rx.recv())
186            .await
187            .unwrap()
188            .unwrap();
189        assert_eq!(cached_table_id, requests.requests[0].table_id);
190        range_release.notify_one();
191    }
192
193    #[tokio::test]
194    async fn test_successful_flush_notifies_flownode_with_logical_table_timestamps() {
195        let table_id = 42;
196        let peer = Peer {
197            id: 7,
198            addr: "flow-7".to_string(),
199        };
200        let cache = mock_table_flownode_cache(table_id, vec![(0, peer.clone()), (1, peer)]).await;
201        let (requests_tx, mut requests_rx) = mpsc::unbounded_channel();
202        let _requests_tx = requests_tx.clone();
203        let node_manager: NodeManagerRef = Arc::new(FlowNotificationMockNodeManager {
204            flownode: Arc::new(RecordingFlownode { requests_tx }),
205        });
206        let table_batches = vec![TableBatch {
207            table_name: "cpu".to_string(),
208            table_id,
209            batches: vec![mock_aligned_tag_batch("tag1", "host-1", 1000, 1.0)],
210            row_count: 1,
211        }];
212
213        notify_flow_dirty_windows_after_flush(table_batches, cache, node_manager);
214
215        let requests = tokio::time::timeout(Duration::from_secs(1), requests_rx.recv())
216            .await
217            .unwrap()
218            .unwrap();
219        assert_eq!(
220            vec![api::v1::flow::DirtyWindowRequest {
221                table_id,
222                timestamps: vec![1000],
223                time_ranges: Vec::new(),
224            }],
225            requests.requests
226        );
227        assert!(
228            tokio::time::timeout(Duration::from_millis(50), requests_rx.recv())
229                .await
230                .is_err()
231        );
232    }
233
234    #[tokio::test]
235    async fn test_successful_flush_coalesces_logical_batches_per_flownode() {
236        let table_id = 42;
237        let peer = Peer {
238            id: 7,
239            addr: "flow-7".to_string(),
240        };
241        let cache = mock_table_flownode_cache(table_id, vec![(0, peer.clone()), (1, peer)]).await;
242        let (requests_tx, mut requests_rx) = mpsc::unbounded_channel();
243        let _requests_tx = requests_tx.clone();
244        let node_manager: NodeManagerRef = Arc::new(FlowNotificationMockNodeManager {
245            flownode: Arc::new(RecordingFlownode { requests_tx }),
246        });
247        let table_batches = vec![TableBatch {
248            table_name: "cpu".to_string(),
249            table_id,
250            batches: vec![
251                mock_aligned_tag_batch("tag1", "host-1", 1000, 1.0),
252                mock_aligned_tag_batch("tag1", "host-1", 2000, 2.0),
253            ],
254            row_count: 2,
255        }];
256
257        notify_flow_dirty_windows_after_flush(table_batches, cache, node_manager);
258
259        let requests = tokio::time::timeout(Duration::from_secs(1), requests_rx.recv())
260            .await
261            .unwrap()
262            .unwrap();
263        assert_eq!(
264            vec![api::v1::flow::DirtyWindowRequest {
265                table_id,
266                timestamps: vec![1000, 2000],
267                time_ranges: Vec::new(),
268            }],
269            requests.requests
270        );
271        assert!(
272            tokio::time::timeout(Duration::from_millis(50), requests_rx.recv())
273                .await
274                .is_err()
275        );
276    }
277
278    struct BlockingRangeKvBackend {
279        range_started: Mutex<Option<oneshot::Sender<()>>>,
280        range_release: Arc<Notify>,
281    }
282
283    impl TxnService for BlockingRangeKvBackend {
284        type Error = common_meta::error::Error;
285    }
286
287    #[async_trait]
288    impl KvBackend for BlockingRangeKvBackend {
289        fn name(&self) -> &str {
290            "blocking_range"
291        }
292
293        fn as_any(&self) -> &dyn Any {
294            self
295        }
296
297        async fn range(&self, _req: RangeRequest) -> MetaResult<RangeResponse> {
298            let range_started = self.range_started.lock().unwrap().take();
299            if let Some(range_started) = range_started {
300                let _ = range_started.send(());
301                self.range_release.notified().await;
302            }
303            Ok(RangeResponse {
304                kvs: Vec::new(),
305                more: false,
306            })
307        }
308
309        async fn put(&self, _req: PutRequest) -> MetaResult<PutResponse> {
310            unimplemented!()
311        }
312
313        async fn batch_put(&self, _req: BatchPutRequest) -> MetaResult<BatchPutResponse> {
314            unimplemented!()
315        }
316
317        async fn batch_get(&self, _req: BatchGetRequest) -> MetaResult<BatchGetResponse> {
318            unimplemented!()
319        }
320
321        async fn delete_range(&self, _req: DeleteRangeRequest) -> MetaResult<DeleteRangeResponse> {
322            unimplemented!()
323        }
324
325        async fn batch_delete(&self, _req: BatchDeleteRequest) -> MetaResult<BatchDeleteResponse> {
326            unimplemented!()
327        }
328    }
329}