返回 CodeWhale
registry.rs
根目录 / crates / cloud-facts / src / registry.rs
1 use std::path::{Path, PathBuf};
2 use std::sync::Arc;
3
4 use codewhale_config::catalog::now_unix;
5 use codewhale_config::cloud_facts::registry::{
6 AdmittedRegistry, BuiltinNames, MAX_REGISTRY_ENVELOPE_BYTES, REGISTRY_CHANNEL, REGISTRY_SCHEMA,
7 admit_registry, verify_registry_envelope,
8 };
9 use codewhale_config::cloud_facts::{FactsRejection, TrustedKey, overlay};
10 use codewhale_config::persistence::atomic_write;
11 use serde::{Deserialize, Serialize};
12
13 use super::{
14 Fetched, RefreshError, STATE_SUBDIR, Settings, checked_url, fetch_envelope, fetch_limited,
15 fetch_suppressed, off_runtime, publish_off_runtime, read_bounded_regular,
16 };
17
18 pub const ENV_REGISTRY_URL: &str = "CODEWHALE_REGISTRY_URL";
19 pub const ENV_REGISTRY_PATH: &str = "CODEWHALE_REGISTRY_PATH";
20 pub const REGISTRY_CACHE_FILE: &str = "registry-cache.json";
21 const REGISTRY_CACHE_SCHEMA: u32 = 1;
22 const MAX_REGISTRY_CACHE_BYTES: usize = MAX_REGISTRY_ENVELOPE_BYTES + 64 * 1024;
23
24 #[derive(Debug, Clone, PartialEq, Eq, Default)]
25 pub struct RegistrySettings {
26 pub enabled: bool,
27 pub url: Option<String>,
28 pub local_path: Option<PathBuf>,
29 pub cache_path: Option<PathBuf>,
30 }
31
32 #[must_use]
33 pub fn default_registry_url(facts_url: Option<&str>) -> String {
34 let template = facts_url
35 .map(str::trim)
36 .filter(|url| url.contains("{channel}"))
37 .unwrap_or(super::DEFAULT_URL_TEMPLATE);
38 template.replace("{channel}", REGISTRY_CHANNEL)
39 }
40
41 impl RegistrySettings {
42 #[must_use]
43 pub fn from_facts(settings: &Settings) -> Self {
44 let env = |name: &str| {
45 std::env::var(name)
46 .ok()
47 .map(|value| value.trim().to_string())
48 .filter(|value| !value.is_empty())
49 };
50 let local_path = env(ENV_REGISTRY_PATH).map(PathBuf::from);
51 let explicit_url =
52 env(ENV_REGISTRY_URL).map(|url| url.replace("{channel}", REGISTRY_CHANNEL));
53 let url = if local_path.is_some() {
54 explicit_url
55 } else {
56 explicit_url.or_else(|| {
57 let facts_url = settings.url.clone().or_else(|| env(super::ENV_URL));
58 Some(default_registry_url(facts_url.as_deref()))
59 })
60 };
61 Self {
62 enabled: settings.enabled && !overlay::hard_disabled(),
63 url,
64 local_path,
65 cache_path: settings
66 .cache_path
67 .as_ref()
68 .map(|path| path.with_file_name(REGISTRY_CACHE_FILE)),
69 }
70 }
71
72 #[must_use]
73 pub fn active(&self) -> bool {
74 self.enabled
75 && !overlay::hard_disabled()
76 && (self.url.is_some() || self.local_path.is_some())
77 }
78
79 fn source(&self) -> String {
80 match (&self.local_path, &self.url) {
81 (Some(path), _) => format!("file:{}", path.display()),
82 (None, Some(url)) => url.clone(),
83 (None, None) => String::new(),
84 }
85 }
86
87 fn cache_file(&self) -> Option<PathBuf> {
88 self.cache_path.clone().or_else(|| {
89 codewhale_config::resolve_state_dir(STATE_SUBDIR)
90 .ok()
91 .map(|dir| dir.join(REGISTRY_CACHE_FILE))
92 })
93 }
94 }
95
96 #[derive(Debug, Clone, Serialize, Deserialize, Default)]
97 struct RegistryCache {
98 schema_version: u32,
99 #[serde(default)]
100 source: String,
101 #[serde(default)]
102 highest_revision: Option<u64>,
103 #[serde(default)]
104 fetched_at: u64,
105 #[serde(default)]
106 etag: Option<String>,
107 #[serde(default)]
108 envelope: String,
109 }
110
111 fn load_cache(path: Option<&Path>) -> RegistryCache {
112 path.and_then(|path| read_bounded_regular(path, MAX_REGISTRY_CACHE_BYTES).ok())
113 .and_then(|bytes| serde_json::from_slice::<RegistryCache>(&bytes).ok())
114 .filter(|cache| {
115 cache.schema_version == REGISTRY_CACHE_SCHEMA
116 && cache.envelope.len() <= MAX_REGISTRY_ENVELOPE_BYTES
117 })
118 .unwrap_or_default()
119 }
120
121 fn save_cache(path: Option<&Path>, cache: &RegistryCache) {
122 let Some(path) = path else {
123 return;
124 };
125 if let Ok(bytes) = serde_json::to_vec(cache)
126 && bytes.len() <= MAX_REGISTRY_CACHE_BYTES
127 && let Err(err) = atomic_write(path, &bytes)
128 {
129 tracing::debug!(target: "cloud_facts", error = %err, "registry cache write failed");
130 }
131 }
132
133 fn cache_for(settings: &RegistrySettings, path: Option<&Path>) -> RegistryCache {
134 let source = settings.source();
135 let mut cache = load_cache(path);
136 if cache.source != source {
137 cache = RegistryCache {
138 highest_revision: cache.highest_revision,
139 ..RegistryCache::default()
140 };
141 }
142 cache.schema_version = REGISTRY_CACHE_SCHEMA;
143 cache.source = source;
144 cache.highest_revision = cache
145 .highest_revision
146 .max(overlay::highest_seen(REGISTRY_SCHEMA));
147 cache
148 }
149
150 fn verify_and_admit(
151 bytes: &[u8],
152 floor: Option<u64>,
153 keys: &[TrustedKey],
154 ) -> Result<AdmittedRegistry, FactsRejection> {
155 let verified = verify_registry_envelope(bytes, floor, keys, now_unix())?;
156 Ok(admit_registry(verified, &BuiltinNames::bundled()))
157 }
158
159 pub(crate) fn load_cached_registry(
160 settings: &RegistrySettings,
161 ticket: &overlay::OverlayTicket,
162 keys: &[TrustedKey],
163 ) -> Option<u64> {
164 if !settings.active() {
165 overlay::publish_registry(ticket, None, |_| {});
166 return None;
167 }
168 let path = settings.cache_file();
169 let cache = cache_for(settings, path.as_deref());
170 if cache.envelope.is_empty() {
171 overlay::publish_registry(ticket, None, |_| {});
172 return None;
173 }
174 match verify_and_admit(cache.envelope.as_bytes(), cache.highest_revision, keys) {
175 Ok(admitted) => {
176 let revision = admitted.revision;
177 overlay::publish_registry(ticket, Some(Arc::new(admitted)), |_| {}).then_some(revision)
178 }
179 Err(FactsRejection::Rollback { .. }) => None,
180 Err(reason) => {
181 tracing::debug!(target: "cloud_facts", %reason, "cached registry rejected");
182 overlay::publish_registry(ticket, None, |floor| {
183 let mut current = load_cache(path.as_deref());
184 if current.envelope == cache.envelope {
185 current.envelope.clear();
186 current.etag = None;
187 current.highest_revision = current.highest_revision.max(floor);
188 save_cache(path.as_deref(), &current);
189 }
190 });
191 None
192 }
193 }
194 }
195
196 pub(crate) async fn refresh_registry_using<F, Fut>(
197 settings: &RegistrySettings,
198 ticket: &overlay::OverlayTicket,
199 keys: &[TrustedKey],
200 suppress_network: bool,
201 transport: F,
202 ) -> Result<Option<u64>, RefreshError>
203 where
204 F: FnOnce(String, Option<String>, usize) -> Fut,
205 Fut: std::future::Future<Output = Result<Fetched, RefreshError>>,
206 {
207 if !settings.active() {
208 return Err(RefreshError::Disabled);
209 }
210 let path = settings.cache_file();
211 let mut cache = {
212 let (settings, path) = (settings.clone(), path.clone());
213 off_runtime(move || Ok(cache_for(&settings, path.as_deref()))).await?
214 };
215 let fetched = fetch_envelope(
216 settings.local_path.clone(),
217 MAX_REGISTRY_ENVELOPE_BYTES,
218 suppress_network,
219 || checked_url(settings.url.as_deref().unwrap_or_default()),
220 cache.etag.clone().filter(|_| !cache.envelope.is_empty()),
221 |url, etag| transport(url, etag, MAX_REGISTRY_ENVELOPE_BYTES),
222 )
223 .await?;
224 let (bytes, etag) = match fetched {
225 Fetched::NotModified => (cache.envelope.as_bytes().to_vec(), cache.etag.clone()),
226 Fetched::NotFound => return Ok(None),
227 Fetched::Body { bytes, etag } => (bytes, etag),
228 };
229 let admitted =
230 verify_and_admit(&bytes, cache.highest_revision, keys).map_err(RefreshError::Rejected)?;
231 let revision = admitted.revision;
232 cache.fetched_at = now_unix();
233 cache.etag = etag;
234 cache.envelope = String::from_utf8(bytes).map_err(|e| RefreshError::Io(e.to_string()))?;
235 let ticket = ticket.clone();
236 publish_off_runtime(move || {
237 overlay::publish_registry(&ticket, Some(Arc::new(admitted)), |floor| {
238 cache.highest_revision = cache.highest_revision.max(floor);
239 save_cache(path.as_deref(), &cache);
240 })
241 })
242 .await?;
243 Ok(Some(revision))
244 }
245
246 pub(crate) fn spawn_registry_refresh(
247 settings: RegistrySettings,
248 ticket: overlay::OverlayTicket,
249 on_update: Option<Arc<dyn Fn() + Send + Sync>>,
250 ) {
251 if !settings.active() || (settings.local_path.is_none() && fetch_suppressed()) {
252 return;
253 }
254 tokio::spawn(async move {
255 let before = overlay::snapshot().generation;
256 let outcome = refresh_registry_using(
257 &settings,
258 &ticket,
259 codewhale_config::cloud_facts::TRUSTED_KEYS,
260 fetch_suppressed(),
261 fetch_limited,
262 )
263 .await;
264 tracing::debug!(target: "cloud_facts", ?outcome, "registry refresh settled");
265 if overlay::snapshot().generation != before
266 && let Some(hook) = on_update
267 {
268 hook();
269 }
270 });
271 }
272
273 #[cfg(test)]
274 mod tests;
275
275 lines RUST