Skip to main content

servers/
request_memory_limiter.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//! Unified memory limiter for all server request protocols.
16
17use std::sync::Arc;
18
19use common_memory_manager::{MemoryGuard, MemoryManager, OnExhaustedPolicy, PermitGranularity};
20use snafu::{IntoError, ResultExt};
21
22use crate::error::{MemoryLimitExceededSnafu, Result};
23use crate::request_memory_metrics::RequestMemoryMetrics;
24
25/// Unified memory limiter for all server request protocols.
26///
27/// Manages a global memory pool for HTTP requests, gRPC messages, and
28/// Arrow Flight batches without distinguishing between them.
29#[derive(Clone)]
30pub struct ServerMemoryLimiter {
31    manager: Arc<MemoryManager<RequestMemoryMetrics>>,
32    policy: OnExhaustedPolicy,
33}
34
35impl Default for ServerMemoryLimiter {
36    /// Creates a limiter with unlimited memory (0 bytes) and default policy.
37    fn default() -> Self {
38        Self::new(0, OnExhaustedPolicy::default())
39    }
40}
41
42impl ServerMemoryLimiter {
43    /// Creates a new unified memory limiter.
44    ///
45    /// # Arguments
46    ///
47    /// * `total_bytes` - Maximum total memory for all concurrent requests (0 = unlimited)
48    /// * `policy` - Policy when memory quota is exhausted
49    pub fn new(total_bytes: u64, policy: OnExhaustedPolicy) -> Self {
50        let manager = Arc::new(MemoryManager::with_granularity(
51            total_bytes,
52            PermitGranularity::Kilobyte,
53            RequestMemoryMetrics,
54        ));
55
56        Self { manager, policy }
57    }
58
59    /// Acquire memory for a request.
60    pub async fn acquire(&self, bytes: u64) -> Result<MemoryGuard<RequestMemoryMetrics>> {
61        self.manager
62            .acquire_with_policy(bytes, self.policy)
63            .await
64            .context(MemoryLimitExceededSnafu)
65    }
66
67    /// Try to acquire memory without waiting.
68    pub fn try_acquire(&self, bytes: u64) -> Option<MemoryGuard<RequestMemoryMetrics>> {
69        self.manager.try_acquire(bytes)
70    }
71
72    /// Rejects requests whose additional bytes cannot fit alongside their own held permits.
73    pub fn check_request_fits(&self, bytes: u64, held_bytes: u64) -> Result<()> {
74        let requested_bytes = held_bytes.checked_add(bytes);
75        let limit_bytes = self.limit_bytes();
76        match requested_bytes {
77            Some(bytes) if limit_bytes == 0 || bytes <= limit_bytes => Ok(()),
78            _ => Err(MemoryLimitExceededSnafu.into_error(
79                common_memory_manager::Error::MemoryLimitExceeded {
80                    requested_bytes: requested_bytes.unwrap_or(u64::MAX),
81                    limit_bytes,
82                },
83            )),
84        }
85    }
86
87    /// Non-blockingly reserves additional conversion memory while caller permits may be held.
88    pub(crate) fn reserve_conversion_memory(
89        &self,
90        estimated_bytes: usize,
91        held_bytes: u64,
92    ) -> Result<Option<MemoryGuard<RequestMemoryMetrics>>> {
93        if self.limit_bytes() == 0 {
94            return Ok(None);
95        }
96        let bytes = u64::try_from(estimated_bytes).unwrap_or(u64::MAX);
97        self.check_request_fits(bytes, held_bytes)?;
98        self.try_acquire(bytes).map(Some).ok_or_else(|| {
99            let source = common_memory_manager::Error::MemoryLimitExceeded {
100                requested_bytes: bytes,
101                limit_bytes: self.limit_bytes(),
102            };
103            // Remote Write senders must retry contention under the wait policy.
104            match self.policy() {
105                OnExhaustedPolicy::Wait { .. } => {
106                    crate::error::OtherSnafu.into_error(common_error::ext::BoxedError::new(source))
107                }
108                OnExhaustedPolicy::Fail => {
109                    crate::error::MemoryLimitExceededSnafu.into_error(source)
110                }
111            }
112        })
113    }
114
115    pub(crate) fn policy(&self) -> OnExhaustedPolicy {
116        self.policy
117    }
118
119    /// Returns total memory limit in bytes (0 if unlimited).
120    pub fn limit_bytes(&self) -> u64 {
121        self.manager.limit_bytes()
122    }
123
124    /// Returns currently reserved (in-flight) bytes.
125    pub fn used_bytes(&self) -> u64 {
126        self.manager.used_bytes()
127    }
128}
129
130impl operator::batcher::ConversionMemoryLimiter for ServerMemoryLimiter {
131    fn limit_bytes(&self) -> u64 {
132        self.limit_bytes()
133    }
134
135    fn reserve(
136        &self,
137        estimated_bytes: usize,
138        held_bytes: u64,
139    ) -> operator::error::Result<operator::batcher::PendingRowsPermit> {
140        let guard = self
141            .reserve_conversion_memory(estimated_bytes, held_bytes)
142            .map_err(common_error::ext::BoxedError::new)
143            .context(operator::error::ExternalSnafu)?;
144        Ok(Arc::new(guard))
145    }
146}