toolkit/runtime/
grpc_installers.rs1use std::collections::VecDeque;
2
3use parking_lot::Mutex;
4use tokio::sync::{Notify, oneshot};
5
6use crate::grpc_registration::RegisterGrpcServiceFn;
7
8#[derive(Default)]
10pub struct GearInstallers {
11 pub gear_name: String,
12 pub installers: Vec<RegisterGrpcServiceFn>,
13}
14
15#[derive(Default)]
17pub struct GrpcInstallerData {
18 pub gears: Vec<GearInstallers>,
19 pub more_batches: bool,
23}
24
25pub struct LateBatch {
28 pub gears: Vec<GearInstallers>,
29 ack: oneshot::Sender<anyhow::Result<()>>,
30}
31
32impl LateBatch {
33 pub fn ack(self, result: anyhow::Result<()>) {
35 drop(self.ack.send(result));
37 }
38}
39
40pub 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 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 pub fn take(&self) -> Option<GrpcInstallerData> {
81 self.inner.lock().initial.take()
82 }
83
84 #[allow(dead_code)]
86 pub fn is_empty(&self) -> bool {
87 self.inner.lock().initial.is_none()
88 }
89
90 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 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 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;