Skip to main content

common_memory_manager/
manager.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::atomic::{AtomicU64, Ordering};
16use std::sync::{Arc, OnceLock};
17
18use snafu::ensure;
19use tokio::sync::{Notify, OwnedSemaphorePermit, Semaphore};
20
21use crate::error::{
22    MemoryAcquireTimeoutSnafu, MemoryLimitExceededSnafu, MemorySemaphoreClosedSnafu, Result,
23};
24use crate::granularity::PermitGranularity;
25use crate::guard::MemoryGuard;
26use crate::policy::OnExhaustedPolicy;
27
28/// Trait for recording memory usage metrics.
29pub trait MemoryMetrics: Clone + Send + Sync + 'static {
30    fn set_limit(&self, bytes: i64);
31    fn set_in_use(&self, bytes: i64);
32    /// Record that immediate memory acquisition failed due to exhausted quota.
33    fn inc_exhausted(&self, reason: &str);
34}
35
36/// Generic memory manager for quota-controlled operations.
37#[derive(Clone)]
38pub struct MemoryManager<M: MemoryMetrics> {
39    quota: MemoryQuotaState<M>,
40}
41
42impl<M: MemoryMetrics + Default> Default for MemoryManager<M> {
43    fn default() -> Self {
44        Self::new(0, M::default())
45    }
46}
47
48#[derive(Clone)]
49pub(crate) struct MemoryQuota<M: MemoryMetrics> {
50    pub(crate) semaphore: Arc<Semaphore>,
51    // Pools without contended stream admissions need no notification lock on release.
52    released: Arc<OnceLock<Notify>>,
53    pub(crate) limit_permits: u32,
54    pub(crate) granularity: PermitGranularity,
55    pub(crate) metrics: M,
56}
57
58#[derive(Clone)]
59pub(crate) struct UnlimitedMemoryQuota<M: MemoryMetrics> {
60    pub(crate) current_bytes: Arc<AtomicU64>,
61    pub(crate) metrics: M,
62}
63
64#[derive(Clone)]
65pub(crate) enum MemoryQuotaState<M: MemoryMetrics> {
66    Unlimited(UnlimitedMemoryQuota<M>),
67    Limited(MemoryQuota<M>),
68}
69
70impl<M: MemoryMetrics> MemoryManager<M> {
71    /// Creates a new memory manager with the given limit in bytes.
72    /// `limit_bytes = 0` disables the limit.
73    pub fn new(limit_bytes: u64, metrics: M) -> Self {
74        Self::with_granularity(limit_bytes, PermitGranularity::default(), metrics)
75    }
76
77    /// Creates a new memory manager with specified granularity.
78    pub fn with_granularity(limit_bytes: u64, granularity: PermitGranularity, metrics: M) -> Self {
79        if limit_bytes == 0 {
80            metrics.set_limit(0);
81            return Self {
82                quota: MemoryQuotaState::Unlimited(UnlimitedMemoryQuota {
83                    current_bytes: Arc::new(AtomicU64::new(0)),
84                    metrics,
85                }),
86            };
87        }
88
89        let limit_permits = granularity.bytes_to_permits(limit_bytes);
90        let limit_aligned_bytes = granularity.permits_to_bytes(limit_permits);
91        metrics.set_limit(limit_aligned_bytes as i64);
92
93        Self {
94            quota: MemoryQuotaState::Limited(MemoryQuota {
95                semaphore: Arc::new(Semaphore::new(limit_permits as usize)),
96                released: Arc::default(),
97                limit_permits,
98                granularity,
99                metrics,
100            }),
101        }
102    }
103
104    /// Returns the configured limit in bytes (0 if unlimited).
105    pub fn limit_bytes(&self) -> u64 {
106        match &self.quota {
107            MemoryQuotaState::Unlimited(_) => 0,
108            MemoryQuotaState::Limited(quota) => quota.permits_to_bytes(quota.limit_permits),
109        }
110    }
111
112    /// Returns currently used bytes.
113    pub fn used_bytes(&self) -> u64 {
114        match &self.quota {
115            MemoryQuotaState::Unlimited(quota) => quota.current_bytes.load(Ordering::Acquire),
116            MemoryQuotaState::Limited(quota) => quota.permits_to_bytes(quota.used_permits()),
117        }
118    }
119
120    /// Returns available bytes.
121    ///
122    /// Unlimited managers report `u64::MAX`.
123    pub fn available_bytes(&self) -> u64 {
124        match &self.quota {
125            MemoryQuotaState::Unlimited(_) => u64::MAX,
126            MemoryQuotaState::Limited(quota) => {
127                quota.permits_to_bytes(quota.available_permits_clamped())
128            }
129        }
130    }
131
132    /// Acquires memory, waiting if necessary until enough is available.
133    ///
134    /// # Errors
135    /// - Returns error if requested bytes exceed the total limit
136    /// - Returns error if the semaphore is unexpectedly closed
137    pub async fn acquire(&self, bytes: u64) -> Result<MemoryGuard<M>> {
138        match &self.quota {
139            MemoryQuotaState::Unlimited(quota) => Ok(MemoryGuard::unlimited(quota.clone(), bytes)),
140            MemoryQuotaState::Limited(quota) => {
141                let permits = quota.bytes_to_permits(bytes);
142
143                ensure!(
144                    permits <= quota.limit_permits,
145                    MemoryLimitExceededSnafu {
146                        requested_bytes: bytes,
147                        limit_bytes: self.limit_bytes()
148                    }
149                );
150
151                let permit = quota.acquire_permits(permits).await?;
152                quota.update_in_use_metric();
153                Ok(MemoryGuard::limited(quota.clone(), permit))
154            }
155        }
156    }
157
158    /// Tries to acquire memory. Returns Some(guard) on success, None if insufficient.
159    pub fn try_acquire(&self, bytes: u64) -> Option<MemoryGuard<M>> {
160        let grant = self.probe(bytes);
161        if grant.is_none()
162            && let MemoryQuotaState::Limited(quota) = &self.quota
163        {
164            quota.metrics.inc_exhausted("try_acquire");
165        }
166        grant
167    }
168
169    /// Tries to acquire immediately, without recording a rejection on a miss.
170    /// Use for speculative checks when the caller can still wait for a grant.
171    pub fn probe(&self, bytes: u64) -> Option<MemoryGuard<M>> {
172        match &self.quota {
173            MemoryQuotaState::Unlimited(quota) => {
174                Some(MemoryGuard::unlimited(quota.clone(), bytes))
175            }
176            MemoryQuotaState::Limited(quota) => {
177                let permits = quota.bytes_to_permits(bytes);
178
179                let permit = quota
180                    .semaphore
181                    .clone()
182                    .try_acquire_many_owned(permits)
183                    .ok()?;
184                quota.update_in_use_metric();
185                Some(MemoryGuard::limited(quota.clone(), permit))
186            }
187        }
188    }
189
190    /// Admits a new stream without letting its FIFO waiter claim partial permits.
191    /// Existing streams can still use available capacity to finish and release memory.
192    pub async fn acquire_unqueued_with_policy(
193        &self,
194        bytes: u64,
195        policy: OnExhaustedPolicy,
196    ) -> Result<MemoryGuard<M>> {
197        let (MemoryQuotaState::Limited(quota), OnExhaustedPolicy::Wait { timeout }) =
198            (&self.quota, policy)
199        else {
200            return self.acquire_with_policy(bytes, policy).await;
201        };
202        ensure!(
203            bytes <= self.limit_bytes(),
204            MemoryLimitExceededSnafu {
205                requested_bytes: bytes,
206                limit_bytes: self.limit_bytes()
207            }
208        );
209        if let Some(guard) = self.probe(bytes) {
210            return Ok(guard);
211        }
212        let notify = quota.released.get_or_init(Notify::new);
213        tokio::time::timeout(timeout, async {
214            loop {
215                // Register before checking: notify_waiters also wakes Notified
216                // futures created before the notification but not yet polled.
217                let released = notify.notified();
218                if let Some(guard) = self.probe(bytes) {
219                    return guard;
220                }
221                released.await;
222            }
223        })
224        .await
225        .map_err(|_| {
226            MemoryAcquireTimeoutSnafu {
227                requested_bytes: bytes,
228                waited: timeout,
229            }
230            .build()
231        })
232    }
233
234    /// Acquires memory based on the given policy.
235    ///
236    /// - For `OnExhaustedPolicy::Wait`: Waits up to the timeout duration for memory to become available
237    /// - For `OnExhaustedPolicy::Fail`: Returns immediately if memory is not available
238    ///
239    /// # Errors
240    /// - `MemoryLimitExceeded`: Requested bytes exceed the total limit (both policies), or memory is currently exhausted (Fail policy only)
241    /// - `MemoryAcquireTimeout`: Timeout elapsed while waiting for memory (Wait policy only)
242    /// - `MemorySemaphoreClosed`: The internal semaphore is unexpectedly closed (rare, indicates system issue)
243    pub async fn acquire_with_policy(
244        &self,
245        bytes: u64,
246        policy: OnExhaustedPolicy,
247    ) -> Result<MemoryGuard<M>> {
248        match policy {
249            OnExhaustedPolicy::Wait { timeout } => {
250                match tokio::time::timeout(timeout, self.acquire(bytes)).await {
251                    Ok(Ok(guard)) => Ok(guard),
252                    Ok(Err(e)) => Err(e),
253                    Err(_elapsed) => {
254                        // Timeout elapsed while waiting
255                        MemoryAcquireTimeoutSnafu {
256                            requested_bytes: bytes,
257                            waited: timeout,
258                        }
259                        .fail()
260                    }
261                }
262            }
263            OnExhaustedPolicy::Fail => self.try_acquire(bytes).ok_or_else(|| {
264                MemoryLimitExceededSnafu {
265                    requested_bytes: bytes,
266                    limit_bytes: self.limit_bytes(),
267                }
268                .build()
269            }),
270        }
271    }
272}
273
274impl<M: MemoryMetrics> MemoryQuota<M> {
275    pub(crate) fn bytes_to_permits(&self, bytes: u64) -> u32 {
276        self.granularity.bytes_to_permits(bytes)
277    }
278
279    pub(crate) fn permits_to_bytes(&self, permits: u32) -> u64 {
280        self.granularity.permits_to_bytes(permits)
281    }
282
283    pub(crate) fn used_permits(&self) -> u32 {
284        self.limit_permits
285            .saturating_sub(self.available_permits_clamped())
286    }
287
288    pub(crate) fn available_permits_clamped(&self) -> u32 {
289        self.semaphore
290            .available_permits()
291            .min(self.limit_permits as usize) as u32
292    }
293
294    pub(crate) fn update_in_use_metric(&self) {
295        let bytes = self.permits_to_bytes(self.used_permits());
296        self.metrics.set_in_use(bytes as i64);
297    }
298
299    pub(crate) async fn acquire_permits(&self, permits: u32) -> Result<OwnedSemaphorePermit> {
300        // Cancelling a FIFO waiter can return partially assigned permits without
301        // ever constructing a MemoryGuard. Wake unqueued admissions then too.
302        struct WakeOnCancel<'a>(Option<&'a OnceLock<Notify>>);
303        impl Drop for WakeOnCancel<'_> {
304            fn drop(&mut self) {
305                if let Some(notify) = self.0.and_then(OnceLock::get) {
306                    notify.notify_waiters();
307                }
308            }
309        }
310        let mut wake = WakeOnCancel(Some(&self.released));
311        let permit = self
312            .semaphore
313            .clone()
314            .acquire_many_owned(permits)
315            .await
316            .map_err(|_| MemorySemaphoreClosedSnafu.build())?;
317        wake.0 = None;
318        Ok(permit)
319    }
320
321    pub(crate) fn release_permit(&self, permit: OwnedSemaphorePermit) {
322        drop(permit);
323        if let Some(notify) = self.released.get() {
324            notify.notify_waiters();
325        }
326        self.update_in_use_metric();
327    }
328}
329
330impl<M: MemoryMetrics> UnlimitedMemoryQuota<M> {
331    pub(crate) fn add_in_use(&self, bytes: u64) {
332        if bytes == 0 {
333            return;
334        }
335
336        let previous = self
337            .current_bytes
338            .fetch_update(Ordering::AcqRel, Ordering::Acquire, |current| {
339                Some(current.saturating_add(bytes))
340            })
341            .unwrap();
342        let new_total = previous.saturating_add(bytes);
343        debug_assert!(
344            new_total >= previous,
345            "unlimited memory usage counter overflowed"
346        );
347        self.metrics.set_in_use(new_total as i64);
348    }
349
350    pub(crate) fn sub_in_use(&self, bytes: u64) {
351        if bytes == 0 {
352            return;
353        }
354
355        let previous = self
356            .current_bytes
357            .fetch_update(Ordering::AcqRel, Ordering::Acquire, |current| {
358                Some(current.saturating_sub(bytes))
359            })
360            .unwrap();
361        debug_assert!(
362            previous >= bytes,
363            "unlimited memory usage counter underflowed: current={previous}, release={bytes}"
364        );
365        let new_total = previous.saturating_sub(bytes);
366        self.metrics.set_in_use(new_total as i64);
367    }
368}