1use serde::Deserialize;
7use std::collections::HashMap;
8use std::fs;
9use std::path::Path;
10use std::process::Command;
11use std::thread;
12use std::time::{Duration, Instant};
13use thiserror::Error;
14
15#[derive(Debug, Error)]
16pub enum SchemaFetchError {
17 #[error("{0}")]
18 Validation(String),
19
20 #[error("I/O error: {0}")]
21 Io(#[from] std::io::Error),
22
23 #[error("JSON error: {0}")]
24 Json(#[from] serde_json::Error),
25
26 #[error("Git command failed: {0}")]
27 Git(String),
28}
29
30pub type SchemaFetchResult<T> = std::result::Result<T, SchemaFetchError>;
31
32#[derive(Debug, Deserialize)]
33#[serde(deny_unknown_fields)]
34pub struct RepoSchemaConfig {
35 pub url: String,
36 #[allow(dead_code)]
39 #[serde(default)]
40 pub sha: Option<String>,
41 pub path: String,
42}
43
44#[derive(Debug, Deserialize)]
45#[serde(deny_unknown_fields)]
46pub struct RepoSchemaConfigs {
47 pub repos: HashMap<String, RepoSchemaConfig>,
48}
49
50impl RepoSchemaConfigs {
51 pub fn from_file(path: &Path) -> SchemaFetchResult<Self> {
52 let content = fs::read_to_string(path)?;
53 Ok(serde_json::from_str(&content)?)
54 }
55}
56
57pub fn fetch_schemas(config: &RepoSchemaConfigs, out_dir: &Path) -> SchemaFetchResult<()> {
59 if out_dir.exists() {
60 return Err(SchemaFetchError::Validation(format!(
61 "Output directory already exists: {}",
62 out_dir.display()
63 )));
64 }
65 fs::create_dir_all(out_dir)?;
66
67 let mut repo_names: Vec<_> = config.repos.keys().collect();
69 repo_names.sort();
70
71 let results: Vec<_> = thread::scope(|scope| {
72 let handles: Vec<_> = repo_names
73 .iter()
74 .map(|repo_name| {
75 let source = &config.repos[*repo_name];
76 let name = repo_name.as_str();
77 (
78 name,
79 scope.spawn(move || fetch_repo_schemas(name, source, out_dir)),
80 )
81 })
82 .collect();
83
84 handles
85 .into_iter()
86 .map(|(name, handle)| {
87 let result = match handle.join() {
88 Ok(Ok(())) => Ok(()),
89 Ok(Err(error)) => Err(error.to_string()),
90 Err(_) => Err(format!("{}: thread panicked", name)),
91 };
92 (name, result)
93 })
94 .collect::<Vec<_>>()
95 });
96
97 let mut errors = Vec::new();
98 for (_repo_name, result) in results {
99 match result {
100 Ok(()) => {}
101 Err(error) => errors.push(error),
102 }
103 }
104
105 if errors.is_empty() {
106 Ok(())
107 } else {
108 Err(SchemaFetchError::Git(errors.join("\n")))
109 }
110}
111
112pub fn fetch_schemas_from_file(config_path: &Path, out_dir: &Path) -> SchemaFetchResult<()> {
114 let config = RepoSchemaConfigs::from_file(config_path)?;
115 fetch_schemas(&config, out_dir)
116}
117
118const MAX_RETRIES: u32 = 3;
119const INITIAL_RETRY_DELAY: Duration = Duration::from_secs(3);
120
121fn fetch_repo_schemas(
122 repo_name: &str,
123 source: &RepoSchemaConfig,
124 out_dir: &Path,
125) -> SchemaFetchResult<()> {
126 let mut delay = INITIAL_RETRY_DELAY;
127 let mut last_error = None;
128
129 for attempt in 0..=MAX_RETRIES {
130 if attempt > 0 {
131 thread::sleep(delay);
132 delay *= 2;
133 }
134
135 let started = Instant::now();
136 match try_fetch_repo_schemas(repo_name, source, out_dir) {
137 Ok(()) => {
138 tracing::info!(
139 repo = repo_name,
140 attempt,
141 elapsed_ms = started.elapsed().as_millis() as u64,
142 "Fetched schemas"
143 );
144 return Ok(());
145 }
146 Err(error) => {
147 tracing::warn!(
148 repo = repo_name,
149 attempt,
150 elapsed_ms = started.elapsed().as_millis() as u64,
151 error = %error,
152 "Schema fetch attempt failed"
153 );
154 last_error = Some(error);
155 }
156 }
157 }
158
159 Err(last_error.expect("at least one fetch attempt must run"))
160}
161
162fn try_fetch_repo_schemas(
163 repo_name: &str,
164 source: &RepoSchemaConfig,
165 out_dir: &Path,
166) -> SchemaFetchResult<()> {
167 let temp_dir = tempfile::tempdir()?;
168 let repo_path = temp_dir.path().join("repo");
169 let repo_str = repo_path.to_str().ok_or_else(|| {
170 SchemaFetchError::Validation(format!("{}: temp path contains invalid UTF-8", repo_name))
171 })?;
172
173 git(
177 &[
178 "clone",
179 "--filter=blob:none",
180 "--sparse",
181 "--depth=1",
182 "--single-branch",
183 "--no-tags",
184 &source.url,
185 repo_str,
186 ],
187 None,
188 repo_name,
189 )?;
190 git(
191 &["sparse-checkout", "set", &source.path],
192 Some(&repo_path),
193 repo_name,
194 )?;
195
196 copy_schemas(&repo_path.join(&source.path), out_dir)
197}
198
199fn git(args: &[&str], cwd: Option<&Path>, repo_name: &str) -> SchemaFetchResult<()> {
200 let mut command = Command::new("git");
201 command.args(args);
202 if let Some(directory) = cwd {
203 command.current_dir(directory);
204 }
205 let output = command.output()?;
206 if output.status.success() {
207 Ok(())
208 } else {
209 Err(SchemaFetchError::Git(format!(
210 "{}: {}",
211 repo_name,
212 String::from_utf8_lossy(&output.stderr).trim()
213 )))
214 }
215}
216
217fn copy_schemas(src: &Path, dest: &Path) -> SchemaFetchResult<()> {
218 if !src.exists() {
219 return Err(SchemaFetchError::Validation(format!(
220 "Schemas path does not exist: {}",
221 src.display()
222 )));
223 }
224
225 for entry in fs::read_dir(src)? {
226 let entry = entry?;
227 if entry.file_type()?.is_dir() {
228 let namespace = entry.file_name();
229 let src_schema = entry.path().join("schema.json");
230 if src_schema.exists() {
231 let dest_namespace = dest.join(&namespace);
232 fs::create_dir_all(&dest_namespace)?;
233 fs::copy(src_schema, dest_namespace.join("schema.json"))?;
234 }
235 }
236 }
237 Ok(())
238}
239
240#[cfg(test)]
241mod tests {
242 use super::*;
243 use tempfile::TempDir;
244
245 #[test]
246 fn test_from_file_valid_json() {
247 let dir = TempDir::new().unwrap();
248 let path = dir.path().join("repos.json");
249 fs::write(
250 &path,
251 r#"{
252 "repos": {
253 "sentry": {
254 "url": "https://github.com/getsentry/sentry",
255 "sha": "abc123",
256 "path": "schemas/"
257 }
258 }
259 }"#,
260 )
261 .unwrap();
262
263 let config = RepoSchemaConfigs::from_file(&path).unwrap();
264 assert_eq!(config.repos.len(), 1);
265 let sentry = config.repos.get("sentry").unwrap();
266 assert_eq!(sentry.url, "https://github.com/getsentry/sentry");
267 assert_eq!(sentry.sha, Some("abc123".to_string()));
268 assert_eq!(sentry.path, "schemas/");
269 }
270
271 #[test]
272 fn test_from_file_rejects_unknown_fields() {
273 let dir = TempDir::new().unwrap();
274 let path = dir.path().join("repos.json");
275 fs::write(
276 &path,
277 r#"{
278 "repos": {
279 "sentry": {
280 "url": "https://github.com/getsentry/sentry",
281 "path": "schemas/",
282 "unknown_field": true
283 }
284 }
285 }"#,
286 )
287 .unwrap();
288
289 let error = RepoSchemaConfigs::from_file(&path).unwrap_err();
290 assert!(error.to_string().contains("unknown field `unknown_field`"));
291 }
292
293 #[test]
294 fn test_copy_schemas() {
295 let src_dir = TempDir::new().unwrap();
296 let dest_dir = TempDir::new().unwrap();
297 let namespace = src_dir.path().join("relay");
298 fs::create_dir_all(&namespace).unwrap();
299 fs::write(namespace.join("schema.json"), r#"{"version": "1.0"}"#).unwrap();
300
301 copy_schemas(src_dir.path(), dest_dir.path()).unwrap();
302
303 assert!(dest_dir.path().join("relay/schema.json").exists());
304 }
305
306 #[test]
307 fn test_fetch_schemas_errors_if_output_exists() {
308 let out_dir = TempDir::new().unwrap();
309 let config = RepoSchemaConfigs {
310 repos: HashMap::new(),
311 };
312
313 let error = fetch_schemas(&config, out_dir.path()).unwrap_err();
314 assert!(
315 error
316 .to_string()
317 .contains("Output directory already exists")
318 );
319 }
320}