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    /// Acquires the initial stream reservation without claiming partial permits
68    /// needed by already admitted streams.
69    pub(crate) async fn admit_stream(
70        &self,
71        bytes: u64,
72    ) -> Result<MemoryGuard<RequestMemoryMetrics>> {
73        self.manager
74            .acquire_unqueued_with_policy(bytes, self.policy)
75            .await
76            .context(MemoryLimitExceededSnafu)
77    }
78
79    pub(crate) fn available_bytes(&self) -> u64 {
80        self.manager.available_bytes()
81    }
82
83    /// Fast path for a caller that will attempt admission on a miss.
84    pub(crate) fn probe(&self, bytes: u64) -> Option<MemoryGuard<RequestMemoryMetrics>> {
85        self.manager.probe(bytes)
86    }
87
88    /// Try to acquire memory without waiting.
89    pub fn try_acquire(&self, bytes: u64) -> Option<MemoryGuard<RequestMemoryMetrics>> {
90        self.manager.try_acquire(bytes)
91    }
92
93    /// Rejects requests whose additional bytes cannot fit alongside their own held permits.
94    pub fn check_request_fits(&self, bytes: u64, held_bytes: u64) -> Result<()> {
95        let requested_bytes = held_bytes.checked_add(bytes);
96        let limit_bytes = self.limit_bytes();
97        match requested_bytes {
98            Some(bytes) if limit_bytes == 0 || bytes <= limit_bytes => Ok(()),
99            _ => Err(MemoryLimitExceededSnafu.into_error(
100                common_memory_manager::Error::MemoryLimitExceeded {
101                    requested_bytes: requested_bytes.unwrap_or(u64::MAX),
102                    limit_bytes,
103                },
104            )),
105        }
106    }
107
108    /// Non-blockingly reserves additional conversion memory while caller permits may be held.
109    pub(crate) fn reserve_conversion_memory(
110        &self,
111        estimated_bytes: usize,
112        held_bytes: u64,
113    ) -> Result<Option<MemoryGuard<RequestMemoryMetrics>>> {
114        if self.limit_bytes() == 0 {
115            return Ok(None);
116        }
117        let bytes = u64::try_from(estimated_bytes).unwrap_or(u64::MAX);
118        self.check_request_fits(bytes, held_bytes)?;
119        self.try_acquire(bytes).map(Some).ok_or_else(|| {
120            let source = common_memory_manager::Error::MemoryLimitExceeded {
121                requested_bytes: bytes,
122                limit_bytes: self.limit_bytes(),
123            };
124            // Remote Write senders must retry contention under the wait policy.
125            match self.policy() {
126                OnExhaustedPolicy::Wait { .. } => {
127                    crate::error::OtherSnafu.into_error(common_error::ext::BoxedError::new(source))
128                }
129                OnExhaustedPolicy::Fail => {
130                    crate::error::MemoryLimitExceededSnafu.into_error(source)
131                }
132            }
133        })
134    }
135
136    pub(crate) fn policy(&self) -> OnExhaustedPolicy {
137        self.policy
138    }
139
140    /// Returns total memory limit in bytes (0 if unlimited).
141    pub fn limit_bytes(&self) -> u64 {
142        self.manager.limit_bytes()
143    }
144
145    /// Returns currently reserved (in-flight) bytes.
146    pub fn used_bytes(&self) -> u64 {
147        self.manager.used_bytes()
148    }
149}
150
151impl operator::batcher::ConversionMemoryLimiter for ServerMemoryLimiter {
152    fn limit_bytes(&self) -> u64 {
153        self.limit_bytes()
154    }
155
156    fn reserve(
157        &self,
158        estimated_bytes: usize,
159        held_bytes: u64,
160    ) -> operator::error::Result<operator::batcher::PendingRowsPermit> {
161        let guard = self
162            .reserve_conversion_memory(estimated_bytes, held_bytes)
163            .map_err(common_error::ext::BoxedError::new)
164            .context(operator::error::ExternalSnafu)?;
165        Ok(Arc::new(guard))
166    }
167}