1use 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#[derive(Debug, Clone, PartialEq, Eq, Hash)]
40pub struct ScopeId(Arc<str>);
41
42impl ScopeId {
43 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 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 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#[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
220pub(crate) struct RootGroupPermit(());
225
226impl RootServiceContext {
227 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 pub fn name(&self) -> &str {
250 &self.name
251 }
252
253 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 pub fn process_budget(&self) -> ResourceBudget {
270 self.resources.process_budget()
271 }
272
273 pub fn resources(&self) -> &RuntimeResources {
275 &self.resources
276 }
277
278 pub fn diagnostics_snapshot(&self) -> RuntimeDiagnosticsSnapshot {
280 self.diagnostics
281 .snapshot(&self.task_group, self.blocking_lanes.snapshots())
282 }
283
284 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 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#[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 pub fn name(&self) -> &str {
379 &self.name
380 }
381
382 pub fn task_spawner(&self) -> TaskSpawner {
384 TaskSpawner::new(self.task_group.clone())
385 }
386
387 pub fn task_group(&self) -> &TaskGroup {
389 &self.task_group
390 }
391
392 pub fn blocking(&self, lane: BlockingLane) -> &BlockingExecutor {
394 self.blocking_lanes.get(lane)
395 }
396
397 pub fn storage_io(&self) -> &BlockingExecutor {
399 self.blocking(BlockingLane::StorageIo)
400 }
401
402 pub fn metadata_io(&self) -> &BlockingExecutor {
404 self.blocking(BlockingLane::MetadataIo)
405 }
406
407 pub fn cpu_crypto(&self) -> &BlockingExecutor {
409 self.blocking(BlockingLane::CpuCrypto)
410 }
411
412 pub fn consume_listener(&self) -> &BlockingExecutor {
414 self.blocking(BlockingLane::ConsumeListener)
415 }
416
417 pub fn diagnostics(&self) -> &RuntimeDiagnostics {
419 &self.diagnostics
420 }
421
422 pub fn process_budget(&self) -> ResourceBudget {
424 self.resources.process_budget()
425 }
426
427 pub fn resources(&self) -> &RuntimeResources {
429 &self.resources
430 }
431
432 pub fn diagnostics_snapshot(&self) -> RuntimeDiagnosticsSnapshot {
434 self.diagnostics
435 .snapshot(&self.task_group, self.blocking_lanes.snapshots())
436 }
437
438 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 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 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 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 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 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 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 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 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 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 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}