Skip to main content

rocketmq_runtime/blocking/
policy.rs

1// Copyright 2023 The RocketMQ Rust Authors
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::time::Duration;
16
17use serde::Serialize;
18
19use crate::error::RuntimeContractViolation;
20use crate::RuntimeContractPolicy;
21
22/// Represents blocking pool policy.
23#[derive(Debug, Clone)]
24pub struct BlockingPoolPolicy {
25    /// The name value.
26    pub name: String,
27    /// The max concurrency value.
28    pub max_concurrency: usize,
29    /// The max queue depth value.
30    pub max_queue_depth: usize,
31    /// The queue timeout value.
32    pub queue_timeout: Duration,
33    /// The task timeout value.
34    pub task_timeout: Duration,
35    /// The warn after value.
36    pub warn_after: Duration,
37}
38
39impl BlockingPoolPolicy {
40    /// Validates this value.
41    ///
42    /// # Errors
43    ///
44    /// Returns a contract violation when concurrency or queue depth is zero,
45    /// or when the combined queue and task timeout cannot be represented.
46    pub fn validate(&self) -> Result<(), RuntimeContractViolation> {
47        if self.max_concurrency == 0 {
48            return Err(RuntimeContractViolation::InvalidConfiguration {
49                policy: RuntimeContractPolicy::BlockingMaxConcurrencyPositive,
50            });
51        }
52        if self.max_queue_depth == 0 {
53            return Err(RuntimeContractViolation::InvalidConfiguration {
54                policy: RuntimeContractPolicy::BlockingMaxQueueDepthPositive,
55            });
56        }
57        let Some(total_timeout) = self.queue_timeout.checked_add(self.task_timeout) else {
58            return Err(RuntimeContractViolation::InvalidConfiguration {
59                policy: RuntimeContractPolicy::BlockingTimeoutRepresentable,
60            });
61        };
62        if std::time::Instant::now().checked_add(total_timeout).is_none() {
63            return Err(RuntimeContractViolation::InvalidConfiguration {
64                policy: RuntimeContractPolicy::BlockingTimeoutRepresentable,
65            });
66        }
67        Ok(())
68    }
69}
70
71impl Default for BlockingPoolPolicy {
72    fn default() -> Self {
73        Self {
74            name: "rocketmq-blocking".to_string(),
75            max_concurrency: 64,
76            max_queue_depth: 256,
77            queue_timeout: Duration::from_secs(5),
78            task_timeout: Duration::from_secs(30),
79            warn_after: Duration::from_secs(1),
80        }
81    }
82}
83
84/// Capacity-isolated blocking work owned by a service root.
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
86#[serde(rename_all = "kebab-case")]
87pub enum BlockingLane {
88    /// Represents the storage io case.
89    StorageIo,
90    /// Represents the metadata io case.
91    MetadataIo,
92    /// Represents the cpu crypto case.
93    CpuCrypto,
94    /// User consume listeners, which may block for a whole consume timeout.
95    ///
96    /// Unlike the other lanes this one does not draw from the global blocking
97    /// budget: it has a capacity of its own, and the Tokio blocking pool is
98    /// sized to hold it as well, so a slow listener cannot take slots that
99    /// storage or metadata I/O count on, and they cannot starve listeners.
100    ConsumeListener,
101}
102
103impl BlockingLane {
104    pub(crate) const ALL: [Self; 4] = [
105        Self::StorageIo,
106        Self::MetadataIo,
107        Self::CpuCrypto,
108        Self::ConsumeListener,
109    ];
110
111    /// Lanes that share the runtime's global blocking budget.
112    pub(crate) const MANAGED: [Self; 3] = [Self::StorageIo, Self::MetadataIo, Self::CpuCrypto];
113
114    pub(crate) const fn index(self) -> usize {
115        match self {
116            Self::StorageIo => 0,
117            Self::MetadataIo => 1,
118            Self::CpuCrypto => 2,
119            Self::ConsumeListener => 3,
120        }
121    }
122}
123
124/// Default listener capacity: the default `consume_thread_max` of one push
125/// consumer. Like Java's consume thread pool it does not depend on the CPU
126/// count, because listeners usually wait on I/O.
127const CONSUME_LISTENER_DEFAULT_CONCURRENCY: usize = 64;
128
129/// Listener calls queued behind a busy lane wait rather than being rejected;
130/// each consumer already bounds its own in-flight calls.
131const CONSUME_LISTENER_DEFAULT_QUEUE_DEPTH: usize = 1024;
132
133/// Java's default `consumeTimeout`. A call still queued after this long is
134/// rejected, and a call running longer is logged when it finishes.
135const CONSUME_LISTENER_DEFAULT_QUEUE_TIMEOUT: Duration = Duration::from_secs(15 * 60);
136
137/// How long a caller keeps waiting on a running listener. A listener cannot be
138/// interrupted; one that overruns `consumeTimeout` is handled by the consumer's
139/// expiry cleanup, so the caller does not give up early and cause a duplicate.
140const CONSUME_LISTENER_DEFAULT_TASK_TIMEOUT: Duration = Duration::from_secs(24 * 60 * 60);
141
142/// Represents blocking lane policies.
143#[derive(Debug, Clone)]
144pub struct BlockingLanePolicies {
145    /// The storage io value.
146    pub storage_io: BlockingPoolPolicy,
147    /// The metadata io value.
148    pub metadata_io: BlockingPoolPolicy,
149    /// The cpu crypto value.
150    pub cpu_crypto: BlockingPoolPolicy,
151    /// The consume listener value. Its capacity is not part of the global
152    /// blocking budget; see [`BlockingLane::ConsumeListener`].
153    pub consume_listener: BlockingPoolPolicy,
154}
155
156impl BlockingLanePolicies {
157    pub(crate) fn for_parallelism(parallelism: usize) -> Self {
158        let parallelism = parallelism.max(1);
159        Self {
160            storage_io: BlockingPoolPolicy {
161                name: "rocketmq-blocking.storage-io".to_string(),
162                max_concurrency: parallelism.saturating_mul(4).max(4),
163                max_queue_depth: parallelism.saturating_mul(16).max(16),
164                ..BlockingPoolPolicy::default()
165            },
166            metadata_io: BlockingPoolPolicy {
167                name: "rocketmq-blocking.metadata-io".to_string(),
168                max_concurrency: parallelism.saturating_mul(2).max(2),
169                max_queue_depth: parallelism.saturating_mul(8).max(8),
170                ..BlockingPoolPolicy::default()
171            },
172            cpu_crypto: BlockingPoolPolicy {
173                name: "rocketmq-blocking.cpu-crypto".to_string(),
174                max_concurrency: parallelism.max(2),
175                max_queue_depth: parallelism.saturating_mul(4).max(8),
176                ..BlockingPoolPolicy::default()
177            },
178            consume_listener: BlockingPoolPolicy {
179                name: "rocketmq-blocking.consume-listener".to_string(),
180                max_concurrency: CONSUME_LISTENER_DEFAULT_CONCURRENCY,
181                max_queue_depth: CONSUME_LISTENER_DEFAULT_QUEUE_DEPTH,
182                queue_timeout: CONSUME_LISTENER_DEFAULT_QUEUE_TIMEOUT,
183                task_timeout: CONSUME_LISTENER_DEFAULT_TASK_TIMEOUT,
184                warn_after: CONSUME_LISTENER_DEFAULT_QUEUE_TIMEOUT,
185            },
186        }
187    }
188
189    /// Caps the lanes that share the global budget. The consume listener lane
190    /// keeps its own capacity.
191    pub(crate) fn cap_concurrency(&mut self, global_capacity: usize) {
192        self.storage_io.max_concurrency = self.storage_io.max_concurrency.min(global_capacity).max(1);
193        self.metadata_io.max_concurrency = self.metadata_io.max_concurrency.min(global_capacity).max(1);
194        self.cpu_crypto.max_concurrency = self.cpu_crypto.max_concurrency.min(global_capacity).max(1);
195    }
196
197    /// Validates this value.
198    ///
199    /// # Errors
200    ///
201    /// Returns the first contract violation from one of the configured lanes.
202    pub fn validate(&self) -> Result<(), RuntimeContractViolation> {
203        self.storage_io.validate()?;
204        self.metadata_io.validate()?;
205        self.cpu_crypto.validate()?;
206        self.consume_listener.validate()
207    }
208
209    pub(crate) fn validate_for_global_capacity(&self, global_capacity: usize) -> Result<(), RuntimeContractViolation> {
210        self.validate()?;
211        if global_capacity < BlockingLane::MANAGED.len() {
212            return Err(RuntimeContractViolation::InvalidConfiguration {
213                policy: RuntimeContractPolicy::BlockingGlobalCapacityCoversLanes,
214            });
215        }
216        Ok(())
217    }
218
219    /// Returns the policy in force for one lane.
220    ///
221    /// Lane capacity, phase timeouts, and the warn threshold are owned here for
222    /// every consumer of the lane, so a component that accepts its own timeout
223    /// fields can report which value actually applies.
224    #[must_use]
225    pub fn policy(&self, lane: BlockingLane) -> &BlockingPoolPolicy {
226        match lane {
227            BlockingLane::StorageIo => &self.storage_io,
228            BlockingLane::MetadataIo => &self.metadata_io,
229            BlockingLane::CpuCrypto => &self.cpu_crypto,
230            BlockingLane::ConsumeListener => &self.consume_listener,
231        }
232    }
233
234    pub(crate) fn max_concurrency(&self, lane: BlockingLane) -> usize {
235        match lane {
236            BlockingLane::StorageIo => self.storage_io.max_concurrency,
237            BlockingLane::MetadataIo => self.metadata_io.max_concurrency,
238            BlockingLane::CpuCrypto => self.cpu_crypto.max_concurrency,
239            BlockingLane::ConsumeListener => self.consume_listener.max_concurrency,
240        }
241    }
242
243    /// Sum of the ceilings of the lanes that share the global budget.
244    pub(crate) fn total_max_concurrency(&self) -> usize {
245        self.storage_io
246            .max_concurrency
247            .saturating_add(self.metadata_io.max_concurrency)
248            .saturating_add(self.cpu_crypto.max_concurrency)
249    }
250
251    /// Creates the uniform value.
252    pub fn uniform(policy: BlockingPoolPolicy) -> Self {
253        let mut storage_io = policy.clone();
254        storage_io.name = format!("{}.storage-io", policy.name);
255        let mut metadata_io = policy.clone();
256        metadata_io.name = format!("{}.metadata-io", policy.name);
257        let mut cpu_crypto = policy.clone();
258        cpu_crypto.name = format!("{}.cpu-crypto", policy.name);
259        let mut consume_listener = policy;
260        consume_listener.name = format!("{}.consume-listener", consume_listener.name);
261        Self {
262            storage_io,
263            metadata_io,
264            cpu_crypto,
265            consume_listener,
266        }
267    }
268}
269
270impl Default for BlockingLanePolicies {
271    fn default() -> Self {
272        let parallelism = std::thread::available_parallelism()
273            .map(|value| value.get())
274            .unwrap_or(4);
275        Self::for_parallelism(parallelism)
276    }
277}
278
279/// Identifies the blocking kind state.
280#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
281pub enum BlockingKind {
282    /// Represents the short io case.
283    ShortIo,
284    /// Represents the cpu bound case.
285    CpuBound,
286    /// Represents the long running case.
287    LongRunning,
288}
289
290/// Represents blocking task id.
291#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
292pub struct BlockingTaskId(pub(crate) u64);
293
294impl BlockingTaskId {
295    /// Borrows this value as u64.
296    pub fn as_u64(self) -> u64 {
297        self.0
298    }
299}
300
301/// Identifies the blocking task state state.
302#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
303pub enum BlockingTaskState {
304    /// Represents the queued case.
305    Queued,
306    /// Represents the running case.
307    Running,
308    /// Represents the completed case.
309    Completed,
310    /// Represents the join failed case.
311    JoinFailed,
312    /// Represents the timed out still running case.
313    TimedOutStillRunning,
314}