Skip to main content

servers/batcher/table/
pending_batch.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::sync::Arc;
16
17use arrow::record_batch::RecordBatch;
18use common_error::ext::BoxedError;
19use common_query::WriteProgress;
20use operator::batcher::PendingRowsPermit;
21use operator::error::Error;
22use session::context::QueryContextRef;
23use snafu::IntoError;
24use table::metadata::TableInfoRef;
25use tokio::sync::oneshot;
26
27/// One complete input and its completion/admission ownership.
28pub(in crate::batcher::table) struct PendingBatch {
29    pub table_info: TableInfoRef,
30    pub batch: RecordBatch,
31    pub ctx: QueryContextRef,
32    pub response_tx: oneshot::Sender<WriteProgress>,
33    pub _permit: PendingRowsPermit,
34    pub _completion: Option<session::write_progress::PendingWrite>,
35}
36
37pub(in crate::batcher::table) fn notify_batches(
38    batches: Vec<PendingBatch>,
39    result: Result<(), Arc<Error>>,
40) {
41    for batch in batches {
42        let progress = match &result {
43            Ok(()) => WriteProgress {
44                affected_rows: batch.batch.num_rows(),
45                error: None,
46            },
47            Err(error) => WriteProgress::failed(BoxedError::new(
48                operator::error::BatchFlushSnafu.into_error(error.clone()),
49            )),
50        };
51        let _ = batch.response_tx.send(progress);
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use arrow::array::Int32Array;
58    use arrow::datatypes::{DataType, Field, Schema};
59    use operator::error::UnexpectedSnafu;
60    use operator::test_util::new_test_table_info;
61    use session::context::QueryContext;
62    use tokio::sync::Semaphore;
63
64    use crate::batcher::table::pending_batch::*;
65
66    #[tokio::test]
67    async fn test_completion_fans_out_and_releases_admission() {
68        for fail in [false, true] {
69            let semaphore = Arc::new(Semaphore::new(3));
70            let mut batches = Vec::new();
71            let mut receivers = Vec::new();
72            for value in 0..3 {
73                let (response_tx, response_rx) = oneshot::channel();
74                let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
75                batches.push(PendingBatch {
76                    _completion: None,
77                    table_info: Arc::new(new_test_table_info(1, "t", [0].into_iter())),
78                    batch: RecordBatch::try_new(
79                        schema,
80                        vec![Arc::new(Int32Array::from(vec![value]))],
81                    )
82                    .unwrap(),
83                    ctx: QueryContext::arc(),
84                    response_tx,
85                    _permit: Arc::new(semaphore.clone().acquire_owned().await.unwrap()),
86                });
87                receivers.push(response_rx);
88            }
89            assert_eq!(0, semaphore.available_permits());
90            // A cancelled waiter must not prevent delivery to the others.
91            drop(receivers.pop());
92            let error = Arc::new(
93                UnexpectedSnafu {
94                    violated: "test flush failure".to_string(),
95                }
96                .build(),
97            );
98            notify_batches(batches, if fail { Err(error.clone()) } else { Ok(()) });
99            assert_eq!(3, semaphore.available_permits());
100            for receiver in receivers {
101                let progress = receiver.await.unwrap();
102                assert_eq!(progress.error.is_some(), fail);
103                assert_eq!(progress.affected_rows, if fail { 0 } else { 1 });
104                if let Some(error) = progress.error {
105                    assert!(error.to_string().contains("test flush failure"));
106                }
107            }
108        }
109    }
110}