Skip to main content

redup_bootstrap/
context.rs

1//! Контекст создания модуля.
2
3use redup_abstractions::Health;
4use redup_bootstrap_client::ClientFactory;
5use redup_bootstrap_grpc::{Binder, Grpc};
6use tokio_util::sync::CancellationToken;
7
8use crate::apoptosis::Apoptosis;
9use crate::dependency::{Dependencies, DependencyBuilder};
10use crate::stopper::Stopper;
11use crate::telemetry::Telemetry;
12use crate::telemetry::load::Load;
13use crate::telemetry::metrics::Meter;
14
15/// То, чем инстанс делится с модулями: телеметрия, привязка gRPC и фабрика клиентов.
16pub(crate) struct Platform<'a> {
17    pub(crate) telemetry: &'a Telemetry,
18    pub(crate) grpc: &'a Binder,
19    pub(crate) clients: &'a ClientFactory,
20}
21
22/// То, что модуль получает от инстанса при создании. Действует, пока выполняется точка создания.
23///
24/// Счётчик метрик действует только в точке создания: инструменты создаются в ней и остаются у
25/// модуля. Учёт нагрузки — дескриптор: его сохраняют на всё время жизни модуля.
26pub struct Context<'a> {
27    module: &'static str,
28    health: Option<Health>,
29    dependencies: &'a mut Dependencies,
30    token: CancellationToken,
31    apoptosis: Apoptosis,
32    stopper: Stopper,
33    platform: Platform<'a>,
34}
35
36impl<'a> Context<'a> {
37    pub(crate) fn new(
38        module: &'static str,
39        dependencies: &'a mut Dependencies,
40        token: CancellationToken,
41        apoptosis: Apoptosis,
42        stopper: Stopper,
43        platform: Platform<'a>,
44    ) -> Self {
45        Self {
46            module,
47            health: None,
48            dependencies,
49            token,
50            apoptosis,
51            stopper,
52            platform,
53        }
54    }
55
56    pub(crate) fn into_health(self) -> Option<Health> {
57        self.health
58    }
59
60    /// Имя модуля.
61    pub fn name(&self) -> &'static str {
62        self.module
63    }
64
65    /// Здоровье модуля. Первый вызов создаёт дескриптор и регистрирует его в инстансе. Модуль без
66    /// дескриптора считается работающим. Новый дескриптор сообщает фазу `Starting`.
67    pub fn health(&mut self) -> Health {
68        self.health.get_or_insert_with(Health::new).clone()
69    }
70
71    /// Токен модуля: под ним живёт его фоновая работа. Отменяется при остановке инстанса, после
72    /// дренажа.
73    pub fn token(&self) -> CancellationToken {
74        self.token.clone()
75    }
76
77    /// Зарегистрировать зависимость от соседа.
78    pub fn dependency(&mut self, name: impl Into<String>) -> DependencyBuilder<'_> {
79        self.dependencies.builder(name)
80    }
81
82    /// Отчёт о нехватке памяти, которую не исправить.
83    pub fn apoptosis(&self) -> Apoptosis {
84        self.apoptosis.clone()
85    }
86
87    /// Остановщик инстанса: штатная остановка (`stop`) и фатальная (`fatal`), когда продолжать
88    /// работу опасно.
89    pub fn stopper(&self) -> Stopper {
90        self.stopper.clone()
91    }
92
93    /// Привязка gRPC-служб модуля. Служба привязывается в точке создания модуля: `bind` получает
94    /// сервер службы, собранный кодогенерацией.
95    pub fn grpc(&self) -> Grpc {
96        Grpc::new(self.platform.grpc.clone(), self.module)
97    }
98
99    /// Фабрика клиентов к соседям: единственный способ создать клиент.
100    pub fn clients(&self) -> &ClientFactory {
101        self.platform.clients
102    }
103
104    /// Счётчик метрик: инструменты модуля создаются здесь, с префиксом службы.
105    pub fn meter(&self) -> &Meter {
106        self.platform.telemetry.meter()
107    }
108
109    /// Учёт нагрузки: время фоновой работы модуля попадает в `worker_load`.
110    pub fn load(&self) -> Load {
111        self.platform.telemetry.load()
112    }
113}