Skip to main content

toolkit/runtime/
grpc_installers.rs

1use std::collections::VecDeque;
2
3use parking_lot::Mutex;
4use tokio::sync::{Notify, oneshot};
5
6use crate::grpc_registration::RegisterGrpcServiceFn;
7
8/// Installers for a specific gear (gear name + service installers).
9#[derive(Default)]
10pub struct GearInstallers {
11    pub gear_name: String,
12    pub installers: Vec<RegisterGrpcServiceFn>,
13}
14
15/// Grouped installers for all gears in the process.
16#[derive(Default)]
17pub struct GrpcInstallerData {
18    pub gears: Vec<GearInstallers>,
19    /// Whether a later batch may follow ([`GrpcInstallerStore::publish_late`]):
20    /// the application group's services, installed once it has started. An
21    /// empty initial batch with more to come still needs a listener.
22    pub more_batches: bool,
23}
24
25/// A batch of installers published after the hub started serving. The hub
26/// installs it on its running listener, then [`ack`](Self::ack)s it.
27pub struct LateBatch {
28    pub gears: Vec<GearInstallers>,
29    ack: oneshot::Sender<anyhow::Result<()>>,
30}
31
32impl LateBatch {
33    /// Report whether the batch is installed and callable.
34    pub fn ack(self, result: anyhow::Result<()>) {
35        // The publisher stopped waiting: nothing to report to.
36        drop(self.ack.send(result));
37    }
38}
39
40/// Runtime-owned gRPC installers: the hub takes system services before serving,
41/// then installs and acknowledges application services on the same listener.
42/// Each batch runs once; earlier installers are never rerun.
43pub struct GrpcInstallerStore {
44    inner: Mutex<Inner>,
45    late_published: Notify,
46}
47
48#[derive(Default)]
49struct Inner {
50    initial: Option<GrpcInstallerData>,
51    initial_set: bool,
52    late: VecDeque<LateBatch>,
53    closed: bool,
54}
55
56impl GrpcInstallerStore {
57    #[must_use]
58    pub fn new() -> Self {
59        Self {
60            inner: Mutex::new(Inner::default()),
61            late_published: Notify::new(),
62        }
63    }
64
65    /// Set the initial batch once. Fails if already set.
66    ///
67    /// # Errors
68    /// Returns an error if the initial batch has already been set.
69    pub fn set(&self, data: GrpcInstallerData) -> anyhow::Result<()> {
70        let mut guard = self.inner.lock();
71        if guard.initial_set {
72            anyhow::bail!("gRPC installers already initialized");
73        }
74        guard.initial_set = true;
75        guard.initial = Some(data);
76        Ok(())
77    }
78
79    /// Consume and return the initial batch.
80    pub fn take(&self) -> Option<GrpcInstallerData> {
81        self.inner.lock().initial.take()
82    }
83
84    /// Check if the initial batch is absent (optional helper).
85    #[allow(dead_code)]
86    pub fn is_empty(&self) -> bool {
87        self.inner.lock().initial.is_none()
88    }
89
90    /// Publish a late batch for the running hub. The receiver resolves with
91    /// the hub's [`LateBatch::ack`]; it errs when the hub drops the batch
92    /// without installing it.
93    ///
94    /// # Errors
95    /// The store is closed: no more batches are accepted.
96    pub fn publish_late(
97        &self,
98        gears: Vec<GearInstallers>,
99    ) -> anyhow::Result<oneshot::Receiver<anyhow::Result<()>>> {
100        let (ack, installed) = oneshot::channel();
101        {
102            let mut guard = self.inner.lock();
103            anyhow::ensure!(!guard.closed, "gRPC installer store is closed");
104            guard.late.push_back(LateBatch { gears, ack });
105        }
106        self.late_published.notify_waiters();
107        Ok(installed)
108    }
109
110    /// The next late batch; `None` once the store is closed and drained.
111    // cancel-safe: a batch is popped and returned under the lock with no await
112    // in between, so a future dropped at its await loses no batch.
113    pub async fn next_late(&self) -> Option<LateBatch> {
114        loop {
115            let published = self.late_published.notified();
116            tokio::pin!(published);
117            published.as_mut().enable();
118            {
119                let mut guard = self.inner.lock();
120                if let Some(batch) = guard.late.pop_front() {
121                    return Some(batch);
122                }
123                if guard.closed {
124                    return None;
125                }
126            }
127            published.await;
128        }
129    }
130
131    /// No more late batches: [`next_late`](Self::next_late) ends once the
132    /// queued ones are taken.
133    pub fn close(&self) {
134        self.inner.lock().closed = true;
135        self.late_published.notify_waiters();
136    }
137}
138
139impl Default for GrpcInstallerStore {
140    fn default() -> Self {
141        Self::new()
142    }
143}
144
145#[cfg(test)]
146#[path = "grpc_installers_tests.rs"]
147mod grpc_installers_tests;