1#[must_use]
11pub fn openapi_spec_hash(spec: &[u8]) -> String {
12 const HEX: &[u8; 16] = b"0123456789abcdef";
13 let digest = toolkit_security::crypto::hash::Sha256::digest(spec);
14 let mut hex = String::with_capacity(digest.len() * 2);
15 for byte in digest {
16 hex.push(HEX[(byte >> 4) as usize] as char);
17 hex.push(HEX[(byte & 0x0f) as usize] as char);
18 }
19 hex
20}
21
22pub use cf_system_sdks::directory::{
23 DirectoryClient, DirectoryInvalidArgument, DirectoryNotFound, DirectoryPermissionDenied,
24 DirectoryServiceNameConflict, GrpcServiceInfo, InstanceState, LabelSelector, RegisterAck,
25 RegisterInstanceInfo, ReportedState, ServiceEndpoint, ServiceInstanceInfo,
26};
27
28use crate::runtime::{
29 Endpoint, GearInstance, GrpcServiceNameConflict, InstanceState as RuntimeInstanceState,
30 ReportedState as RuntimeReportedState,
31};
32use uuid::Uuid;
33
34impl From<ReportedState> for RuntimeReportedState {
35 fn from(state: ReportedState) -> Self {
36 match state {
37 ReportedState::Starting => Self::Starting,
38 ReportedState::Serving => Self::Serving,
39 ReportedState::Draining => Self::Draining,
40 }
41 }
42}
43
44impl From<RuntimeInstanceState> for InstanceState {
45 fn from(state: RuntimeInstanceState) -> Self {
46 match state {
47 RuntimeInstanceState::Registered => Self::Registered,
48 RuntimeInstanceState::Ready => Self::Ready,
49 RuntimeInstanceState::Healthy => Self::Healthy,
50 RuntimeInstanceState::Quarantined => Self::Quarantined,
51 RuntimeInstanceState::Draining => Self::Draining,
52 }
53 }
54}
55
56impl From<GrpcServiceNameConflict> for DirectoryServiceNameConflict {
57 fn from(conflict: GrpcServiceNameConflict) -> Self {
58 Self {
59 service_name: conflict.service_name,
60 owner: conflict.owner,
61 recoverable: conflict.recoverable,
62 }
63 }
64}
65
66pub fn instance_from_registration(info: RegisterInstanceInfo, instance_id: Uuid) -> GearInstance {
69 let mut instance = GearInstance::new(info.gear, instance_id);
70 if let Some(version) = info.version {
71 instance = instance.with_version(version);
72 }
73 for (service_name, endpoint) in info.grpc_services {
74 instance = instance.with_grpc_service(service_name, Endpoint::from_uri(endpoint.uri));
75 }
76 if let Some(endpoint) = info.rest_endpoint {
77 instance = instance.with_rest_endpoint(Endpoint::from_uri(endpoint.uri));
78 }
79 if let Some(hash) = info.openapi_spec_hash {
80 instance = instance.with_openapi_spec_hash(hash);
81 }
82 if !info.labels.is_empty() {
83 instance = instance.with_labels(info.labels);
84 }
85 if let Some(reported) = info.reported_state {
86 instance = instance.with_reported_state(reported.into());
87 }
88 instance
89}
90
91#[must_use]
94pub fn project_instance(instance: &GearInstance) -> ServiceInstanceInfo {
95 let endpoint = instance
96 .grpc_services
97 .values()
98 .next()
99 .or(instance.rest_endpoint.as_ref())
100 .map(|endpoint| ServiceEndpoint::new(endpoint.uri.clone()));
101
102 ServiceInstanceInfo::new(&instance.gear, instance.instance_id.to_string())
103 .with_endpoint(endpoint)
104 .with_version(instance.version.clone())
105 .with_rest_endpoint(
106 instance
107 .rest_endpoint
108 .as_ref()
109 .map(|endpoint| ServiceEndpoint::new(endpoint.uri.clone())),
110 )
111 .with_openapi_spec_hash(instance.openapi_spec_hash.clone())
112 .with_grpc_services(
113 instance
114 .grpc_services
115 .iter()
116 .map(|(name, endpoint)| (name.clone(), ServiceEndpoint::new(endpoint.uri.clone())))
117 .collect(),
118 )
119 .with_labels(instance.labels.clone())
120 .with_state(instance.state().into())
121}
122
123#[cfg(any(test, feature = "test-support"))]
124pub mod test_support {
125 use anyhow::Result;
126 use async_trait::async_trait;
127 use std::sync::Arc;
128 use uuid::Uuid;
129
130 use super::{
131 DirectoryClient, DirectoryInvalidArgument, DirectoryNotFound, DirectoryServiceNameConflict,
132 LabelSelector, RegisterAck, RegisterInstanceInfo, ReportedState, ServiceEndpoint,
133 ServiceInstanceInfo, instance_from_registration, project_instance,
134 };
135 use crate::runtime::GearManager;
136
137 pub struct ManagerDirectoryClient(Arc<GearManager>);
141
142 impl ManagerDirectoryClient {
143 #[must_use]
145 pub fn new(manager: Arc<GearManager>) -> Self {
146 Self(manager)
147 }
148 }
149
150 fn registration_id(instance_id: &str) -> Result<Uuid> {
151 Uuid::parse_str(instance_id).map_err(|error| {
152 anyhow::Error::from(DirectoryInvalidArgument::new(format!(
153 "invalid instance_id '{instance_id}': {error}"
154 )))
155 })
156 }
157
158 fn not_found(gear: &str, instance_id: &str) -> anyhow::Error {
159 DirectoryNotFound::new(format!("instance {gear}/{instance_id}")).into()
160 }
161
162 #[async_trait]
163 impl DirectoryClient for ManagerDirectoryClient {
164 async fn resolve_grpc_service(&self, service_name: &str) -> Result<ServiceEndpoint> {
165 self.0
166 .pick_service_round_robin(service_name)
167 .map(|(_, _, endpoint)| ServiceEndpoint::new(endpoint.uri))
168 .ok_or_else(|| DirectoryNotFound::new(format!("service {service_name}")).into())
169 }
170
171 async fn resolve_rest_service(&self, gear_name: &str) -> Result<ServiceEndpoint> {
172 self.0
173 .pick_rest_endpoint_round_robin(gear_name)
174 .map(|endpoint| ServiceEndpoint::new(endpoint.uri))
175 .ok_or_else(|| DirectoryNotFound::new(format!("gear {gear_name}")).into())
176 }
177
178 async fn list_instances(&self, gear: &str) -> Result<Vec<ServiceInstanceInfo>> {
179 Ok(self
180 .0
181 .instances_of(gear)
182 .iter()
183 .map(|instance| project_instance(instance))
184 .collect())
185 }
186
187 async fn resolve_by_labels(
188 &self,
189 gear: &str,
190 selector: &LabelSelector,
191 ) -> Result<Vec<ServiceInstanceInfo>> {
192 Ok(self
193 .0
194 .instances_of(gear)
195 .iter()
196 .map(|instance| project_instance(instance))
197 .filter(|instance| selector.matches(&instance.labels))
198 .collect())
199 }
200
201 async fn list_all_instances(&self) -> Result<Vec<ServiceInstanceInfo>> {
202 Ok(self
203 .0
204 .all_instances()
205 .iter()
206 .filter_map(|instance| {
207 let info = project_instance(instance);
208 info.endpoint.is_some().then(|| info.without_labels())
209 })
210 .collect())
211 }
212
213 async fn register_instance(&self, info: RegisterInstanceInfo) -> Result<()> {
214 cf_system_sdks::directory::validate_labels(&info.labels).map_err(|error| {
215 anyhow::Error::from(DirectoryInvalidArgument::new(error.to_string()))
216 })?;
217 let id = registration_id(&info.instance_id)?;
218 self.0
219 .register_instance(Arc::new(instance_from_registration(info, id)))
220 .map_err(|conflict| DirectoryServiceNameConflict::from(conflict).into())
221 }
222
223 async fn register_with_lease(&self, info: RegisterInstanceInfo) -> Result<RegisterAck> {
224 self.register_instance(info).await?;
225 Ok(RegisterAck {
226 lease_ttl: Some(self.0.lease_ttl()),
227 })
228 }
229
230 async fn deregister_instance(&self, gear: &str, instance_id: &str) -> Result<()> {
231 let id = registration_id(instance_id)?;
232 self.0.deregister(gear, id);
233 Ok(())
234 }
235
236 async fn send_heartbeat(&self, gear: &str, instance_id: &str) -> Result<()> {
237 self.heartbeat(gear, instance_id, None).await
238 }
239
240 async fn heartbeat(
241 &self,
242 gear: &str,
243 instance_id: &str,
244 reported: Option<ReportedState>,
245 ) -> Result<()> {
246 let id = registration_id(instance_id)?;
247 if self.0.heartbeat(gear, id, reported.map(Into::into)) {
248 Ok(())
249 } else {
250 Err(not_found(gear, instance_id))
251 }
252 }
253 }
254}
255
256#[cfg(test)]
257mod tests {
258 use super::{DirectoryClient, DirectoryInvalidArgument, openapi_spec_hash};
259 use crate::directory::test_support::ManagerDirectoryClient;
260 use crate::runtime::GearManager;
261 use std::sync::Arc;
262
263 #[test]
264 fn openapi_hash_is_sha256_hex() {
265 assert_eq!(
266 openapi_spec_hash(b""),
267 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
268 );
269 }
270
271 #[tokio::test]
272 async fn manager_directory_client_uses_directory_invalid_argument_for_bad_request_ids() {
273 let client = ManagerDirectoryClient::new(Arc::new(GearManager::new()));
274
275 assert!(matches!(
276 client.deregister_instance("gear", "not-a-uuid").await,
277 Err(error) if error.is::<DirectoryInvalidArgument>()
278 ));
279 assert!(matches!(
280 client.heartbeat("gear", "not-a-uuid", None).await,
281 Err(error) if error.is::<DirectoryInvalidArgument>()
282 ));
283 }
284}