common_batcher/flush_policy.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
15pub mod timing;
16
17use tokio::time::Instant;
18
19use crate::pending_batch::PendingBatch;
20
21/// The event that caused the worker to reconsider flushing.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum FlushTrigger {
24 /// A complete submission was appended to the batch.
25 Submission,
26 /// The flush timer reached its deadline.
27 Deadline,
28}
29
30/// Decides when a pending batch is ready without owning its payloads or execution.
31///
32/// A deadline wakeup must either allow flushing or produce a future deadline;
33/// otherwise the caller would repeatedly poll an expired timer.
34pub trait FlushPolicy {
35 /// Returns the next timer deadline, or `None` when no timer is needed.
36 fn deadline<T>(&self, batch: &PendingBatch<T>) -> Option<Instant>;
37
38 /// Returns whether the batch should be flushed for this event at `now`.
39 ///
40 /// Workers never flush empty batches, regardless of this decision.
41 fn should_flush<T>(&self, batch: &PendingBatch<T>, now: Instant, trigger: FlushTrigger)
42 -> bool;
43}