Skip to main content

session/
write_progress.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//! Process-local acknowledgements for a finite write request.
16
17use std::fmt;
18use std::sync::Arc;
19use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
20use tokio::sync::Notify;
21
22/// Counts only confirmed storage writes, including partial successes.
23#[derive(Default)]
24pub struct WriteProgress {
25    written: AtomicU64,
26    accepted: AtomicBool,
27    // A queued write must keep its decoder's memory reservation alive.
28    reservation: Option<(u64, Arc<dyn Send + Sync>)>,
29    on_write: Option<Box<dyn Fn(u64) + Send + Sync>>,
30    pending: AtomicUsize,
31    completed: Notify,
32}
33
34/// Keeps a queued submission pending until the worker reports its result.
35pub struct PendingWrite(Arc<WriteProgress>);
36
37impl Drop for PendingWrite {
38    fn drop(&mut self) {
39        if self.0.pending.fetch_sub(1, Ordering::AcqRel) == 1 {
40            self.0.completed.notify_waiters();
41        }
42    }
43}
44
45impl fmt::Debug for WriteProgress {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        f.debug_struct("WriteProgress")
48            .field("written", &self.written())
49            .field("accepted", &self.accepted())
50            .finish_non_exhaustive()
51    }
52}
53
54impl WriteProgress {
55    pub fn start(self: &Arc<Self>) -> PendingWrite {
56        self.pending.fetch_add(1, Ordering::Relaxed);
57        PendingWrite(self.clone())
58    }
59
60    /// Waits for previously queued submissions before returning a failed request's counts.
61    pub async fn wait(&self) {
62        loop {
63            let notified = self.completed.notified();
64            tokio::pin!(notified);
65            notified.as_mut().enable();
66            if self.pending.load(Ordering::Acquire) == 0 {
67                return;
68            }
69            notified.await;
70        }
71    }
72
73    /// Retains a fixed-size reservation and its granted bytes for later memory admission.
74    pub fn with_reservation(reserved_bytes: u64, reservation: Arc<dyn Send + Sync>) -> Self {
75        Self {
76            reservation: Some((reserved_bytes, reservation)),
77            ..Self::default()
78        }
79    }
80
81    /// Returns the quota retained by this request's decoder or exemplar rows.
82    pub fn reserved_bytes(&self) -> u64 {
83        self.reservation.as_ref().map_or(0, |(bytes, _)| *bytes)
84    }
85
86    pub fn add_written(&self, rows: usize) {
87        self.written.fetch_add(rows as u64, Ordering::Relaxed);
88        self.observe(rows as u64);
89    }
90
91    pub fn with_observer(mut self, observer: impl Fn(u64) + Send + Sync + 'static) -> Self {
92        self.on_write = Some(Box::new(observer));
93        self
94    }
95
96    /// A synchronous whole-request acknowledgement also covers handlers without region tracking.
97    pub fn confirm(&self, rows: u64) {
98        let previous = self.written.fetch_max(rows, Ordering::Relaxed);
99        self.observe(rows.saturating_sub(previous));
100    }
101
102    fn observe(&self, rows: u64) {
103        if rows > 0
104            && let Some(observer) = &self.on_write
105        {
106            observer(rows);
107        }
108    }
109
110    pub fn written(&self) -> u64 {
111        self.written.load(Ordering::Relaxed)
112    }
113
114    /// Records an acknowledgement returned before storage completion.
115    pub fn mark_accepted(&self) {
116        self.accepted.store(true, Ordering::Relaxed);
117    }
118
119    pub fn accepted(&self) -> bool {
120        self.accepted.load(Ordering::Relaxed)
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use std::sync::atomic::AtomicUsize;
127
128    use super::*;
129
130    #[test]
131    fn confirmations_do_not_double_count_and_contexts_keep_local_ownership() {
132        let observed = Arc::new(AtomicUsize::new(0));
133        let counter = observed.clone();
134        let progress = Arc::new(
135            WriteProgress::with_reservation(2048, Arc::new(())).with_observer(move |rows| {
136                counter.fetch_add(rows as usize, Ordering::Relaxed);
137            }),
138        );
139        let mut context = crate::context::QueryContext::with("greptime", "public");
140        let body_bytes = Arc::new(AtomicU64::new(0));
141        context.set_body_memory_bytes(Arc::downgrade(&body_bytes));
142        context.set_write_progress(progress.clone());
143        let fork = context.with_write_admission();
144        assert!(Arc::ptr_eq(fork.write_progress().unwrap(), &progress));
145        assert_eq!(fork.held_memory_bytes(), 2048);
146        body_bytes.store(1024, Ordering::Release);
147        assert_eq!(context.held_memory_bytes(), 3072);
148        assert_eq!(fork.held_memory_bytes(), 3072);
149        let wire = api::v1::QueryContext::from(context);
150        let received = crate::context::QueryContext::try_from(wire).unwrap();
151        assert!(received.write_progress().is_none());
152        assert_eq!(received.held_memory_bytes(), 0);
153        drop(body_bytes);
154        assert_eq!(fork.held_memory_bytes(), 2048);
155        progress.add_written(2);
156        progress.confirm(3);
157        progress.confirm(3);
158        progress.mark_accepted();
159        assert_eq!(progress.written(), 3);
160        assert_eq!(observed.load(Ordering::Relaxed), 3);
161        assert!(progress.accepted());
162    }
163}