Skip to main content

rocketmq_runtime/
service_context.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::future::Future;
16use std::sync::Arc;
17
18use crate::blocking::BlockingExecutor;
19use crate::blocking::BlockingLane;
20use crate::blocking::BlockingLanePolicies;
21use crate::blocking::GlobalBlockingBudget;
22use crate::critical::CriticalFailureState;
23use crate::diagnostics::RuntimeDiagnostics;
24use crate::diagnostics::RuntimeDiagnosticsSnapshot;
25use crate::error::RuntimeContractViolation;
26use crate::error::RuntimeResult;
27use crate::handle::RuntimeHandle;
28use crate::resource_budget::ResourceBudget;
29use crate::resources::RuntimeResources;
30use crate::scheduled::ScheduledTaskGroup;
31use crate::shutdown_report::ShutdownReport;
32use crate::task_group::TaskGroup;
33use crate::task_group::TaskId;
34use crate::task_group::TaskKind;
35use crate::task_spawner::TaskSpawner;
36use crate::RuntimeContractPolicy;
37
38/// A validated, named position in the service ownership tree.
39#[derive(Debug, Clone, PartialEq, Eq, Hash)]
40pub struct ScopeId(Arc<str>);
41
42impl ScopeId {
43    /// Creates a scope identifier.
44    ///
45    /// # Errors
46    ///
47    /// Returns a deterministic contract violation when `name` is empty or
48    /// only contains whitespace.
49    pub fn try_new(name: impl Into<Arc<str>>) -> Result<Self, RuntimeContractViolation> {
50        let name = name.into();
51        if name.trim().is_empty() {
52            return Err(RuntimeContractViolation::InvalidConfiguration {
53                policy: RuntimeContractPolicy::ServiceContextScopeNotBlank,
54            });
55        }
56        Ok(Self(name))
57    }
58
59    /// Creates a statically named scope.
60    ///
61    /// # Panics
62    ///
63    /// Panics when `name` is empty or only contains whitespace. Static scope
64    /// names are programmer-owned lifecycle invariants.
65    pub fn from_static(name: &'static str) -> Self {
66        Self::try_new(Arc::<str>::from(name)).expect("static service context scope name must be valid")
67    }
68
69    /// Borrows this value as str.
70    pub fn as_str(&self) -> &str {
71        &self.0
72    }
73
74    fn into_inner(self) -> Arc<str> {
75        self.0
76    }
77}
78
79impl From<&'static str> for ScopeId {
80    fn from(value: &'static str) -> Self {
81        Self::from_static(value)
82    }
83}
84
85impl TryFrom<String> for ScopeId {
86    type Error = RuntimeContractViolation;
87
88    fn try_from(value: String) -> Result<Self, Self::Error> {
89        Self::try_new(Arc::<str>::from(value))
90    }
91}
92
93impl TryFrom<Arc<str>> for ScopeId {
94    type Error = RuntimeContractViolation;
95
96    fn try_from(value: Arc<str>) -> Result<Self, Self::Error> {
97        Self::try_new(value)
98    }
99}
100
101#[cfg(test)]
102mod scope_id_tests {
103    use super::*;
104
105    #[test]
106    fn dynamic_scope_ids_return_contract_violations() {
107        assert_eq!(
108            ScopeId::try_new(Arc::<str>::from("  ")),
109            Err(RuntimeContractViolation::InvalidConfiguration {
110                policy: RuntimeContractPolicy::ServiceContextScopeNotBlank,
111            })
112        );
113        assert!(ScopeId::try_from(String::new()).is_err());
114    }
115}
116
117#[derive(Debug, Clone)]
118struct BlockingLanes {
119    storage_io: BlockingExecutor,
120    metadata_io: BlockingExecutor,
121    cpu_crypto: BlockingExecutor,
122    consume_listener: BlockingExecutor,
123}
124
125impl BlockingLanes {
126    fn new(policies: BlockingLanePolicies, global_capacity: usize, runtime: RuntimeHandle, scope: &TaskGroup) -> Self {
127        let budget = GlobalBlockingBudget::managed(global_capacity, &policies);
128        let listener_budget =
129            GlobalBlockingBudget::dedicated(BlockingLane::ConsumeListener, policies.consume_listener.max_concurrency);
130        Self {
131            storage_io: BlockingExecutor::new_managed(
132                policies.storage_io,
133                BlockingLane::StorageIo,
134                budget.clone(),
135                runtime.clone(),
136            )
137            .expect("RuntimeConfig validates storage blocking policy before root context construction")
138            .scoped_to(scope.clone()),
139            metadata_io: BlockingExecutor::new_managed(
140                policies.metadata_io,
141                BlockingLane::MetadataIo,
142                budget.clone(),
143                runtime.clone(),
144            )
145            .expect("RuntimeConfig validates metadata blocking policy before root context construction")
146            .scoped_to(scope.clone()),
147            cpu_crypto: BlockingExecutor::new_managed(
148                policies.cpu_crypto,
149                BlockingLane::CpuCrypto,
150                budget,
151                runtime.clone(),
152            )
153            .expect("RuntimeConfig validates CPU blocking policy before root context construction")
154            .scoped_to(scope.clone()),
155            consume_listener: BlockingExecutor::new_managed(
156                policies.consume_listener,
157                BlockingLane::ConsumeListener,
158                listener_budget,
159                runtime,
160            )
161            .expect("RuntimeConfig validates consume listener blocking policy before root context construction")
162            .scoped_to(scope.clone()),
163        }
164    }
165
166    fn scoped_to(&self, scope: &TaskGroup) -> Self {
167        Self {
168            storage_io: self.storage_io.scoped_to(scope.clone()),
169            metadata_io: self.metadata_io.scoped_to(scope.clone()),
170            cpu_crypto: self.cpu_crypto.scoped_to(scope.clone()),
171            consume_listener: self.consume_listener.scoped_to(scope.clone()),
172        }
173    }
174
175    fn get(&self, lane: BlockingLane) -> &BlockingExecutor {
176        match lane {
177            BlockingLane::StorageIo => &self.storage_io,
178            BlockingLane::MetadataIo => &self.metadata_io,
179            BlockingLane::CpuCrypto => &self.cpu_crypto,
180            BlockingLane::ConsumeListener => &self.consume_listener,
181        }
182    }
183
184    fn snapshots(&self) -> Vec<crate::blocking::BlockingExecutorSnapshot> {
185        vec![
186            self.storage_io.snapshot(),
187            self.metadata_io.snapshot(),
188            self.cpu_crypto.snapshot(),
189            self.consume_listener.snapshot(),
190        ]
191    }
192
193    fn aggregates(&self) -> Vec<crate::blocking::BlockingExecutorAggregate> {
194        vec![
195            self.storage_io.aggregate(),
196            self.metadata_io.aggregate(),
197            self.cpu_crypto.aggregate(),
198            self.consume_listener.aggregate(),
199        ]
200    }
201}
202
203/// The unique, non-cloneable lifecycle root owned by [`crate::RuntimeOwner`].
204///
205/// The type has no public constructor and cannot be promoted from a child
206/// context. Composition roots only use it to derive the first named child.
207#[derive(Debug)]
208pub struct RootServiceContext {
209    name: Arc<str>,
210    task_group: TaskGroup,
211    blocking_lanes: BlockingLanes,
212    diagnostics: RuntimeDiagnostics,
213    resources: RuntimeResources,
214    _sealed: RootContextSeal,
215}
216
217#[derive(Debug)]
218struct RootContextSeal;
219
220/// Permit to create a root [`TaskGroup`].
221///
222/// The private field keeps construction inside this module, so
223/// [`RootServiceContext::new`] is the only code that can create a root group.
224pub(crate) struct RootGroupPermit(());
225
226impl RootServiceContext {
227    /// Creates a root context and the root task group it owns.
228    pub(crate) fn new(
229        name: Arc<str>,
230        runtime: RuntimeHandle,
231        blocking_policies: BlockingLanePolicies,
232        global_blocking_capacity: usize,
233        diagnostics: RuntimeDiagnostics,
234        resources: RuntimeResources,
235    ) -> Self {
236        let task_group = TaskGroup::root(Arc::clone(&name), runtime.clone(), RootGroupPermit(()));
237        let blocking_lanes = BlockingLanes::new(blocking_policies, global_blocking_capacity, runtime, &task_group);
238        Self {
239            name,
240            task_group,
241            blocking_lanes,
242            diagnostics,
243            resources,
244            _sealed: RootContextSeal,
245        }
246    }
247
248    /// Returns the name.
249    pub fn name(&self) -> &str {
250        &self.name
251    }
252
253    /// Creates a long-lived component context owned by this process root.
254    ///
255    /// Dynamically supplied names must be validated with [`ScopeId::try_new`]
256    /// before they reach this boundary. Static literals may use the constrained
257    /// `From<&'static str>` conversion.
258    pub fn component(&self, scope: impl Into<ScopeId>) -> ChildServiceContext {
259        ChildServiceContext::new(
260            scope.into(),
261            &self.task_group,
262            self.blocking_lanes.clone(),
263            self.diagnostics.clone(),
264            self.resources.clone(),
265        )
266    }
267
268    /// Returns the shared process resource-budget root.
269    pub fn process_budget(&self) -> ResourceBudget {
270        self.resources.process_budget()
271    }
272
273    /// Returns the process-wide runtime resource capabilities.
274    pub fn resources(&self) -> &RuntimeResources {
275        &self.resources
276    }
277
278    /// Returns the diagnostics snapshot.
279    pub fn diagnostics_snapshot(&self) -> RuntimeDiagnosticsSnapshot {
280        self.diagnostics
281            .snapshot(&self.task_group, self.blocking_lanes.snapshots())
282    }
283
284    /// Returns a bounded, sanitized diagnostics view for this service runtime.
285    pub fn diagnostics_view_v1(
286        &self,
287        component: crate::diagnostics::RuntimeComponent,
288    ) -> crate::diagnostics::RuntimeDiagnosticsViewV1 {
289        self.diagnostics.view_v1_with_aggregates(
290            component,
291            &self.task_group,
292            self.blocking_lanes.aggregates(),
293            Default::default(),
294        )
295    }
296
297    pub(crate) fn task_group(&self) -> &TaskGroup {
298        &self.task_group
299    }
300
301    pub(crate) fn blocking(&self, lane: BlockingLane) -> &BlockingExecutor {
302        self.blocking_lanes.get(lane)
303    }
304
305    pub(crate) fn diagnostics(&self) -> &RuntimeDiagnostics {
306        &self.diagnostics
307    }
308
309    /// Adds the blocking work of the managed lanes and of the isolated
310    /// executors bound to this tree to `report`.
311    pub(crate) fn merge_blocking_into(&self, report: &mut ShutdownReport) {
312        for snapshot in self.blocking_lanes.snapshots() {
313            report.merge_blocking(snapshot);
314        }
315        let (still_running, tasks) = self.task_group.isolated_blocking_report();
316        report.merge_blocking_tasks(still_running, tasks);
317    }
318}
319
320/// A sealed, cloneable descendant of a [`RootServiceContext`].
321///
322/// Libraries receive this type or a capability derived from it. They cannot
323/// construct it from a Tokio handle, create a root task group, or promote it
324/// back to a root.
325#[derive(Debug, Clone)]
326pub struct ChildServiceContext {
327    name: Arc<str>,
328    task_group: TaskGroup,
329    blocking_lanes: BlockingLanes,
330    diagnostics: RuntimeDiagnostics,
331    resources: RuntimeResources,
332    _sealed: Arc<ChildContextSeal>,
333}
334
335#[derive(Debug)]
336struct ChildContextSeal;
337
338impl ChildServiceContext {
339    fn new(
340        scope: ScopeId,
341        parent_group: &TaskGroup,
342        blocking_lanes: BlockingLanes,
343        diagnostics: RuntimeDiagnostics,
344        resources: RuntimeResources,
345    ) -> Self {
346        let name = scope.into_inner();
347        let task_group = parent_group.component(name.clone());
348        Self {
349            name: name.clone(),
350            task_group: task_group.clone(),
351            blocking_lanes: blocking_lanes.scoped_to(&task_group),
352            diagnostics,
353            resources,
354            _sealed: Arc::new(ChildContextSeal),
355        }
356    }
357
358    fn try_new(
359        scope: ScopeId,
360        parent_group: &TaskGroup,
361        blocking_lanes: BlockingLanes,
362        diagnostics: RuntimeDiagnostics,
363        resources: RuntimeResources,
364    ) -> RuntimeResult<Self> {
365        let name = scope.into_inner();
366        let task_group = parent_group.try_child(name.clone())?;
367        Ok(Self {
368            name: name.clone(),
369            task_group: task_group.clone(),
370            blocking_lanes: blocking_lanes.scoped_to(&task_group),
371            diagnostics,
372            resources,
373            _sealed: Arc::new(ChildContextSeal),
374        })
375    }
376
377    /// Returns the name.
378    pub fn name(&self) -> &str {
379        &self.name
380    }
381
382    /// Returns the task spawner.
383    pub fn task_spawner(&self) -> TaskSpawner {
384        TaskSpawner::new(self.task_group.clone())
385    }
386
387    /// Returns the task group.
388    pub fn task_group(&self) -> &TaskGroup {
389        &self.task_group
390    }
391
392    /// Returns the blocking.
393    pub fn blocking(&self, lane: BlockingLane) -> &BlockingExecutor {
394        self.blocking_lanes.get(lane)
395    }
396
397    /// Returns the storage io.
398    pub fn storage_io(&self) -> &BlockingExecutor {
399        self.blocking(BlockingLane::StorageIo)
400    }
401
402    /// Returns the metadata io.
403    pub fn metadata_io(&self) -> &BlockingExecutor {
404        self.blocking(BlockingLane::MetadataIo)
405    }
406
407    /// Returns the cpu crypto.
408    pub fn cpu_crypto(&self) -> &BlockingExecutor {
409        self.blocking(BlockingLane::CpuCrypto)
410    }
411
412    /// Returns the lane that runs user consume listeners.
413    pub fn consume_listener(&self) -> &BlockingExecutor {
414        self.blocking(BlockingLane::ConsumeListener)
415    }
416
417    /// Returns the diagnostics.
418    pub fn diagnostics(&self) -> &RuntimeDiagnostics {
419        &self.diagnostics
420    }
421
422    /// Returns the shared process resource-budget root.
423    pub fn process_budget(&self) -> ResourceBudget {
424        self.resources.process_budget()
425    }
426
427    /// Returns the process-wide runtime resource capabilities.
428    pub fn resources(&self) -> &RuntimeResources {
429        &self.resources
430    }
431
432    /// Returns the diagnostics snapshot.
433    pub fn diagnostics_snapshot(&self) -> RuntimeDiagnosticsSnapshot {
434        self.diagnostics
435            .snapshot(&self.task_group, self.blocking_lanes.snapshots())
436    }
437
438    /// Returns a bounded, sanitized diagnostics view for this service subtree.
439    pub fn diagnostics_view_v1(
440        &self,
441        component: crate::diagnostics::RuntimeComponent,
442    ) -> crate::diagnostics::RuntimeDiagnosticsViewV1 {
443        self.diagnostics.view_v1_with_aggregates(
444            component,
445            &self.task_group,
446            self.blocking_lanes.aggregates(),
447            Default::default(),
448        )
449    }
450
451    /// Returns a bounded, explicitly scoped diagnostics view for this subtree.
452    ///
453    /// The runtime context does not own scheduled groups or a metadata actor, so
454    /// the caller supplies the snapshots it holds; a section without an input is
455    /// reported as absent rather than as an empty value.
456    pub fn diagnostics_view_v2(
457        &self,
458        component: crate::diagnostics::RuntimeComponent,
459        inputs: crate::diagnostics::RuntimeDiagnosticsInputs,
460    ) -> crate::diagnostics::RuntimeDiagnosticsViewV2 {
461        self.diagnostics_view_v2_with_options(
462            component,
463            inputs,
464            crate::diagnostics::RuntimeDiagnosticsViewOptionsV2::default(),
465        )
466    }
467
468    /// Returns a bounded, explicitly scoped diagnostics view with explicit
469    /// budget limits, including the scan and output budgets of an on-demand task
470    /// detail list.
471    pub fn diagnostics_view_v2_with_options(
472        &self,
473        component: crate::diagnostics::RuntimeComponent,
474        inputs: crate::diagnostics::RuntimeDiagnosticsInputs,
475        options: crate::diagnostics::RuntimeDiagnosticsViewOptionsV2,
476    ) -> crate::diagnostics::RuntimeDiagnosticsViewV2 {
477        self.diagnostics.view_v2_with_aggregates(
478            component,
479            &self.task_group,
480            self.blocking_lanes.aggregates(),
481            inputs,
482            options,
483        )
484    }
485
486    /// Creates a long-lived component context owned by this service.
487    ///
488    /// Dynamically supplied names must be validated with [`ScopeId::try_new`]
489    /// before they reach this boundary. Static literals may use the constrained
490    /// `From<&'static str>` conversion.
491    pub fn component(&self, scope: impl Into<ScopeId>) -> Self {
492        Self::new(
493            scope.into(),
494            &self.task_group,
495            self.blocking_lanes.clone(),
496            self.diagnostics.clone(),
497            self.resources.clone(),
498        )
499    }
500
501    /// Creates an independently cancellable child component owned by this service.
502    ///
503    /// Parent cancellation propagates to the returned component. Cancelling the
504    /// child does not cancel this service or sibling components.
505    ///
506    /// # Errors
507    ///
508    /// Returns an unavailable runtime failure after this service starts
509    /// shutting down or becomes poisoned. Dynamically supplied names must be
510    /// validated with [`ScopeId::try_new`] before this call.
511    pub fn try_component(&self, scope: impl Into<ScopeId>) -> RuntimeResult<Self> {
512        Self::try_new(
513            scope.into(),
514            &self.task_group,
515            self.blocking_lanes.clone(),
516            self.diagnostics.clone(),
517            self.resources.clone(),
518        )
519    }
520
521    /// Returns the scheduled tasks.
522    pub fn scheduled_tasks(&self, scope: impl Into<ScopeId>) -> ScheduledTaskGroup {
523        let component = self.component(scope);
524        ScheduledTaskGroup::new(component.task_group)
525    }
526
527    /// Spawns the supplied task.
528    pub fn spawn<F>(&self, name: impl Into<crate::TaskName>, kind: TaskKind, future: F) -> RuntimeResult<TaskId>
529    where
530        F: Future<Output = ()> + Send + 'static,
531    {
532        self.task_group.spawn(name, kind, future)
533    }
534
535    /// Spawns a service that owns its shutdown protocol.
536    ///
537    /// Use [`Self::spawn_cancellable_service`] when owner cancellation may
538    /// safely drop the service future immediately.
539    pub fn spawn_service<F>(&self, name: impl Into<crate::TaskName>, future: F) -> RuntimeResult<TaskId>
540    where
541        F: Future<Output = ()> + Send + 'static,
542    {
543        self.task_group.spawn_service(name, future)
544    }
545
546    /// Spawns a service that exits when either its future completes or this context is cancelled.
547    ///
548    /// # Errors
549    ///
550    /// Returns an error when this service context is shutting down or closed.
551    pub fn spawn_cancellable_service<F>(&self, name: impl Into<crate::TaskName>, future: F) -> RuntimeResult<TaskId>
552    where
553        F: Future<Output = ()> + Send + 'static,
554    {
555        self.task_group.spawn_cancellable_service(name, future)
556    }
557
558    /// Spawns work whose panic is recorded as a critical failure.
559    ///
560    /// # Errors
561    ///
562    /// Returns an error when this service context is shutting down or closed.
563    pub fn spawn_critical<F>(
564        &self,
565        name: impl Into<crate::TaskName>,
566        kind: TaskKind,
567        failures: CriticalFailureState,
568        future: F,
569    ) -> RuntimeResult<TaskId>
570    where
571        F: Future<Output = ()> + Send + 'static,
572    {
573        self.task_group.spawn_critical(name, kind, failures, future)
574    }
575
576    /// Spawns a critical service that must run until this context is cancelled.
577    ///
578    /// # Errors
579    ///
580    /// Returns an error when this service context is shutting down or closed.
581    pub fn spawn_critical_service<F>(
582        &self,
583        name: impl Into<crate::TaskName>,
584        failures: CriticalFailureState,
585        future: F,
586    ) -> RuntimeResult<TaskId>
587    where
588        F: Future<Output = ()> + Send + 'static,
589    {
590        self.task_group.spawn_critical_service(name, failures, future)
591    }
592}