Skip to main content

common_memory_manager/
guard.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::{fmt, mem};
16
17use snafu::ensure;
18use tokio::sync::{OwnedSemaphorePermit, TryAcquireError};
19
20use crate::error::{MemoryAcquireTimeoutSnafu, MemoryLimitExceededSnafu, Result};
21use crate::manager::{MemoryMetrics, MemoryQuota, UnlimitedMemoryQuota};
22use crate::policy::OnExhaustedPolicy;
23
24/// Guard representing a slice of reserved memory.
25pub struct MemoryGuard<M: MemoryMetrics> {
26    pub(crate) state: GuardState<M>,
27}
28
29pub(crate) enum GuardState<M: MemoryMetrics> {
30    Released,
31    Unlimited {
32        quota: UnlimitedMemoryQuota<M>,
33        granted_bytes: u64,
34    },
35    Limited {
36        quota: MemoryQuota<M>,
37        permit: OwnedSemaphorePermit,
38    },
39}
40
41impl<M: MemoryMetrics> GuardState<M> {
42    fn release(self) {
43        match self {
44            GuardState::Released => {}
45            GuardState::Unlimited {
46                quota,
47                granted_bytes,
48            } => {
49                quota.sub_in_use(granted_bytes);
50            }
51            GuardState::Limited { quota, permit } => {
52                quota.release_permit(permit);
53            }
54        }
55    }
56}
57
58impl<M: MemoryMetrics> MemoryGuard<M> {
59    pub(crate) fn unlimited(quota: UnlimitedMemoryQuota<M>, bytes: u64) -> Self {
60        quota.add_in_use(bytes);
61        Self {
62            state: GuardState::Unlimited {
63                quota,
64                granted_bytes: bytes,
65            },
66        }
67    }
68
69    pub(crate) fn limited(quota: MemoryQuota<M>, permit: OwnedSemaphorePermit) -> Self {
70        Self {
71            state: GuardState::Limited { quota, permit },
72        }
73    }
74
75    /// Returns granted quota in bytes.
76    pub fn granted_bytes(&self) -> u64 {
77        match &self.state {
78            GuardState::Released => 0,
79            GuardState::Unlimited { granted_bytes, .. } => *granted_bytes,
80            GuardState::Limited { quota, permit } => {
81                quota.permits_to_bytes(permit.num_permits() as u32)
82            }
83        }
84    }
85
86    /// Acquires additional memory, waiting if necessary until enough is available.
87    ///
88    /// On success, merges the new memory into this guard.
89    ///
90    /// # Errors
91    /// - Returns error if requested bytes would exceed the manager's total limit
92    /// - Returns error if the semaphore is unexpectedly closed
93    pub async fn acquire_additional(&mut self, bytes: u64) -> Result<()> {
94        if bytes == 0 {
95            return Ok(());
96        }
97
98        match &mut self.state {
99            GuardState::Released => {
100                debug_assert!(false, "released memory guard state should not be reused");
101                Ok(())
102            }
103            GuardState::Unlimited {
104                quota,
105                granted_bytes,
106            } => {
107                quota.add_in_use(bytes);
108                *granted_bytes = granted_bytes.saturating_add(bytes);
109                Ok(())
110            }
111            GuardState::Limited { quota, permit } => {
112                let additional_permits = quota.bytes_to_permits(bytes);
113                let current_permits = permit.num_permits() as u32;
114
115                ensure!(
116                    current_permits.saturating_add(additional_permits) <= quota.limit_permits,
117                    MemoryLimitExceededSnafu {
118                        requested_bytes: bytes,
119                        limit_bytes: quota.permits_to_bytes(quota.limit_permits)
120                    }
121                );
122
123                let additional_permit = quota.acquire_permits(additional_permits).await?;
124
125                permit.merge(additional_permit);
126                quota.update_in_use_metric();
127                Ok(())
128            }
129        }
130    }
131
132    /// Tries to acquire additional memory without waiting.
133    ///
134    /// On success, merges the new memory into this guard and returns true.
135    /// On failure, returns false and leaves this guard unchanged.
136    pub fn try_acquire_additional(&mut self, bytes: u64) -> bool {
137        if bytes == 0 {
138            return true;
139        }
140
141        match &mut self.state {
142            GuardState::Released => {
143                debug_assert!(false, "released memory guard state should not be reused");
144                false
145            }
146            GuardState::Unlimited {
147                quota,
148                granted_bytes,
149            } => {
150                quota.add_in_use(bytes);
151                *granted_bytes = granted_bytes.saturating_add(bytes);
152                true
153            }
154            GuardState::Limited { quota, permit } => {
155                let additional_permits = quota.bytes_to_permits(bytes);
156
157                match quota
158                    .semaphore
159                    .clone()
160                    .try_acquire_many_owned(additional_permits)
161                {
162                    Ok(additional_permit) => {
163                        permit.merge(additional_permit);
164                        quota.update_in_use_metric();
165                        true
166                    }
167                    Err(TryAcquireError::NoPermits) | Err(TryAcquireError::Closed) => {
168                        quota.metrics.inc_exhausted("try_acquire_additional");
169                        false
170                    }
171                }
172            }
173        }
174    }
175
176    /// Acquires additional memory based on the given policy.
177    ///
178    /// - For `OnExhaustedPolicy::Wait`: Waits up to the timeout duration for memory to become available
179    /// - For `OnExhaustedPolicy::Fail`: Returns immediately if memory is not available
180    ///
181    /// # Errors
182    /// - `MemoryLimitExceeded`: Requested bytes would exceed the total limit (both policies), or memory is currently exhausted (Fail policy only)
183    /// - `MemoryAcquireTimeout`: Timeout elapsed while waiting for memory (Wait policy only)
184    /// - `MemorySemaphoreClosed`: The internal semaphore is unexpectedly closed (rare, indicates system issue)
185    pub async fn acquire_additional_with_policy(
186        &mut self,
187        bytes: u64,
188        policy: OnExhaustedPolicy,
189    ) -> Result<()> {
190        match policy {
191            OnExhaustedPolicy::Wait { timeout } => {
192                match tokio::time::timeout(timeout, self.acquire_additional(bytes)).await {
193                    Ok(Ok(())) => Ok(()),
194                    Ok(Err(e)) => Err(e),
195                    Err(_elapsed) => MemoryAcquireTimeoutSnafu {
196                        requested_bytes: bytes,
197                        waited: timeout,
198                    }
199                    .fail(),
200                }
201            }
202            OnExhaustedPolicy::Fail => {
203                if self.try_acquire_additional(bytes) {
204                    Ok(())
205                } else {
206                    MemoryLimitExceededSnafu {
207                        requested_bytes: bytes,
208                        limit_bytes: match &self.state {
209                            GuardState::Released => 0,
210                            GuardState::Unlimited { .. } => 0, // unreachable: unlimited mode always succeeds
211                            GuardState::Limited { quota, .. } => {
212                                quota.permits_to_bytes(quota.limit_permits)
213                            }
214                        },
215                    }
216                    .fail()
217                }
218            }
219        }
220    }
221
222    /// Releases a portion of granted memory back to the pool before the guard is dropped.
223    ///
224    /// Returns true if the release succeeds or is a no-op; false if the request exceeds granted.
225    pub fn release_partial(&mut self, bytes: u64) -> bool {
226        if bytes == 0 {
227            return true;
228        }
229
230        match &mut self.state {
231            GuardState::Released => true,
232            GuardState::Unlimited {
233                quota,
234                granted_bytes,
235            } => {
236                if bytes > *granted_bytes {
237                    return false;
238                }
239
240                quota.sub_in_use(bytes);
241                *granted_bytes = granted_bytes.saturating_sub(bytes);
242                true
243            }
244            GuardState::Limited { quota, permit } => {
245                let release_permits = quota.bytes_to_permits(bytes);
246
247                match permit.split(release_permits as usize) {
248                    Some(released_permit) => {
249                        quota.release_permit(released_permit);
250                        true
251                    }
252                    None => false,
253                }
254            }
255        }
256    }
257}
258
259impl<M: MemoryMetrics> Drop for MemoryGuard<M> {
260    fn drop(&mut self) {
261        mem::replace(&mut self.state, GuardState::Released).release();
262    }
263}
264
265impl<M: MemoryMetrics> fmt::Debug for MemoryGuard<M> {
266    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267        f.debug_struct("MemoryGuard")
268            .field("granted_bytes", &self.granted_bytes())
269            .finish()
270    }
271}