1#[cfg(not(target_arch = "wasm32"))]
7pub mod git;
8#[cfg(not(target_arch = "wasm32"))]
9pub mod http;
10#[cfg(not(target_arch = "wasm32"))]
11pub mod onchain;
12pub mod path;
13
14use crate::file::ImportSource;
15use std::path::PathBuf;
16
17#[derive(Debug, Clone)]
23pub struct FetcherConfig {
24 pub allow_path: bool,
26 pub allow_git: bool,
28 pub allow_http: bool,
30 pub allow_onchain: bool,
32
33 pub git_config: GitFetcherConfig,
35
36 pub onchain_config: OnchainFetcherConfig,
38
39 pub cache_config: CacheConfig,
41}
42
43impl Default for FetcherConfig {
44 fn default() -> Self {
45 Self::cli_default()
46 }
47}
48
49impl FetcherConfig {
50 pub fn cli_default() -> Self {
52 Self {
53 allow_path: true,
54 allow_git: true,
55 allow_http: true,
56 allow_onchain: true,
57 git_config: GitFetcherConfig::default(),
58 onchain_config: OnchainFetcherConfig::default(),
59 cache_config: CacheConfig::default(),
60 }
61 }
62
63 pub fn wasm_default() -> Self {
65 Self {
66 allow_path: false,
67 allow_git: false,
68 allow_http: false,
69 allow_onchain: false,
70 git_config: GitFetcherConfig::default(),
71 onchain_config: OnchainFetcherConfig::default(),
72 cache_config: CacheConfig::disabled(),
73 }
74 }
75
76 pub fn production_build() -> Self {
78 Self {
79 allow_path: false,
80 allow_git: false,
81 allow_http: false,
82 allow_onchain: true,
83 git_config: GitFetcherConfig::default(),
84 onchain_config: OnchainFetcherConfig::default(),
85 cache_config: CacheConfig::default(),
86 }
87 }
88
89 pub fn local_only() -> Self {
91 Self {
92 allow_path: true,
93 allow_git: false,
94 allow_http: false,
95 allow_onchain: false,
96 git_config: GitFetcherConfig::default(),
97 onchain_config: OnchainFetcherConfig::default(),
98 cache_config: CacheConfig::disabled(),
99 }
100 }
101
102 pub fn is_allowed(&self, source: &ImportSource) -> bool {
104 match source {
105 ImportSource::Path { .. } => self.allow_path,
106 ImportSource::Git { .. } => self.allow_git,
107 ImportSource::Http { .. } => self.allow_http,
108 ImportSource::Onchain { .. } => self.allow_onchain,
109 }
110 }
111}
112
113#[derive(Debug, Clone, Default)]
115pub struct GitFetcherConfig {
116 pub ssh_key_path: Option<PathBuf>,
118 pub use_credential_helper: bool,
120 pub proxy: Option<String>,
122 pub timeout_seconds: u64,
124}
125
126impl GitFetcherConfig {
127 pub fn new() -> Self {
129 Self {
130 ssh_key_path: None,
131 use_credential_helper: true,
132 proxy: None,
133 timeout_seconds: 60,
134 }
135 }
136}
137
138#[derive(Debug, Clone)]
140pub struct OnchainFetcherConfig {
141 pub rpc_endpoints: std::collections::HashMap<String, String>,
143 pub default_network: String,
145 pub timeout_seconds: u64,
147 pub abi_manager_program_id: String,
149 pub abi_manager_is_ephemeral: bool,
151}
152
153impl Default for OnchainFetcherConfig {
154 fn default() -> Self {
155 let mut rpc_endpoints = std::collections::HashMap::new();
156 rpc_endpoints.insert(
157 "alphanet".to_string(),
158 "https://rpc.alphanet.thru.org".to_string(),
159 );
160
161 Self {
162 rpc_endpoints,
163 default_network: "alphanet".to_string(),
164 timeout_seconds: 30,
165 abi_manager_program_id: "taAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACrG7".to_string(),
166 abi_manager_is_ephemeral: false,
167 }
168 }
169}
170
171impl OnchainFetcherConfig {
172 pub fn get_endpoint(&self, network: &str) -> Option<&str> {
174 self.rpc_endpoints.get(network).map(|s| s.as_str())
175 }
176
177 pub fn set_endpoint(&mut self, network: impl Into<String>, endpoint: impl Into<String>) {
179 self.rpc_endpoints.insert(network.into(), endpoint.into());
180 }
181}
182
183#[derive(Debug, Clone)]
185pub struct CacheConfig {
186 pub enabled: bool,
188 pub cache_dir: PathBuf,
190 pub max_age_seconds: u64,
192}
193
194impl Default for CacheConfig {
195 fn default() -> Self {
196 Self {
197 enabled: true,
198 cache_dir: default_cache_dir(),
199 max_age_seconds: 3600, }
201 }
202}
203
204#[cfg(not(target_arch = "wasm32"))]
205fn default_cache_dir() -> PathBuf {
206 dirs::home_dir()
207 .unwrap_or_else(|| PathBuf::from("."))
208 .join(".thru")
209 .join("abi-cache")
210}
211
212#[cfg(target_arch = "wasm32")]
213fn default_cache_dir() -> PathBuf {
214 PathBuf::new()
215}
216
217impl CacheConfig {
218 pub fn disabled() -> Self {
220 Self {
221 enabled: false,
222 cache_dir: PathBuf::new(),
223 max_age_seconds: 0,
224 }
225 }
226
227 pub fn with_dir(cache_dir: PathBuf) -> Self {
229 Self {
230 enabled: true,
231 cache_dir,
232 max_age_seconds: 3600,
233 }
234 }
235}
236
237#[derive(Debug, Clone)]
243pub struct FetchContext {
244 pub base_path: Option<PathBuf>,
246 pub parent_is_remote: bool,
248 pub include_dirs: Vec<PathBuf>,
250}
251
252impl FetchContext {
253 pub fn for_root(file_path: Option<PathBuf>, include_dirs: Vec<PathBuf>) -> Self {
255 Self {
256 base_path: file_path,
257 parent_is_remote: false,
258 include_dirs,
259 }
260 }
261
262 pub fn child_context(&self, source: &ImportSource, resolved_path: Option<PathBuf>) -> Self {
264 Self {
265 base_path: resolved_path,
266 parent_is_remote: source.is_remote(),
267 include_dirs: self.include_dirs.clone(),
268 }
269 }
270}
271
272#[derive(Debug, Clone)]
278pub struct FetchResult {
279 pub content: String,
281 pub canonical_location: String,
283 pub is_remote: bool,
285 pub resolved_path: Option<PathBuf>,
287}
288
289#[derive(Debug)]
295pub enum FetchError {
296 UnsupportedSource(String),
298 NotAllowed(ImportSource),
300 LocalFromRemote(String),
302 NotFound(String),
304 Io(std::io::Error),
306 Git(String),
308 Http { status: u16, message: String },
310 Onchain(String),
312 Parse(String),
314 UnknownNetwork(String),
316 RevisionMismatch { required: String, actual: u64 },
318}
319
320impl std::fmt::Display for FetchError {
321 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
322 match self {
323 FetchError::UnsupportedSource(s) => write!(f, "Unsupported import source: {}", s),
324 FetchError::NotAllowed(s) => write!(f, "Import type not allowed: {:?}", s),
325 FetchError::LocalFromRemote(s) => {
326 write!(f, "Local import '{}' not allowed from remote source", s)
327 }
328 FetchError::NotFound(s) => write!(f, "Import not found: {}", s),
329 FetchError::Io(e) => write!(f, "IO error: {}", e),
330 FetchError::Git(s) => write!(f, "Git error: {}", s),
331 FetchError::Http { status, message } => {
332 write!(f, "HTTP error {}: {}", status, message)
333 }
334 FetchError::Onchain(s) => write!(f, "On-chain fetch error: {}", s),
335 FetchError::Parse(s) => write!(f, "Parse error: {}", s),
336 FetchError::UnknownNetwork(s) => write!(f, "Unknown network: {}", s),
337 FetchError::RevisionMismatch { required, actual } => {
338 write!(
339 f,
340 "Revision mismatch: required {}, got {}",
341 required, actual
342 )
343 }
344 }
345 }
346}
347
348impl std::error::Error for FetchError {
349 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
350 match self {
351 FetchError::Io(e) => Some(e),
352 _ => None,
353 }
354 }
355}
356
357impl From<std::io::Error> for FetchError {
358 fn from(e: std::io::Error) -> Self {
359 FetchError::Io(e)
360 }
361}
362
363pub trait ImportFetcher: Send + Sync {
369 fn handles(&self, source: &ImportSource) -> bool;
371
372 fn fetch(&self, source: &ImportSource, ctx: &FetchContext) -> Result<FetchResult, FetchError>;
374}
375
376pub struct CompositeFetcher {
382 fetchers: Vec<Box<dyn ImportFetcher>>,
383 config: FetcherConfig,
384}
385
386impl CompositeFetcher {
387 pub fn new(config: FetcherConfig) -> Result<Self, FetchError> {
389 let mut fetchers: Vec<Box<dyn ImportFetcher>> = Vec::new();
390
391 if config.allow_path {
392 fetchers.push(Box::new(path::PathFetcher::new()));
393 }
394 #[cfg(not(target_arch = "wasm32"))]
395 if config.allow_git {
396 fetchers.push(Box::new(git::GitFetcher::new(&config.git_config)));
397 }
398 #[cfg(not(target_arch = "wasm32"))]
399 if config.allow_http {
400 fetchers.push(Box::new(http::HttpFetcher::new()?));
401 }
402 #[cfg(not(target_arch = "wasm32"))]
403 if config.allow_onchain {
404 fetchers.push(Box::new(onchain::OnchainFetcher::new(
405 &config.onchain_config,
406 )));
407 }
408
409 Ok(Self { fetchers, config })
410 }
411
412 pub fn fetch(
414 &self,
415 source: &ImportSource,
416 ctx: &FetchContext,
417 ) -> Result<FetchResult, FetchError> {
418 if !self.config.is_allowed(source) {
420 return Err(FetchError::NotAllowed(source.clone()));
421 }
422
423 for fetcher in &self.fetchers {
425 if fetcher.handles(source) {
426 return fetcher.fetch(source, ctx);
427 }
428 }
429
430 Err(FetchError::UnsupportedSource(format!("{:?}", source)))
431 }
432
433 pub fn config(&self) -> &FetcherConfig {
435 &self.config
436 }
437}
438
439#[cfg(test)]
440mod tests {
441 use super::*;
442
443 #[test]
444 fn test_fetcher_config_is_allowed() {
445 let config = FetcherConfig::local_only();
446
447 let path_import = ImportSource::Path {
448 path: "test.abi.yaml".to_string(),
449 };
450 let git_import = ImportSource::Git {
451 url: "https://github.com/test/repo".to_string(),
452 git_ref: "main".to_string(),
453 path: "abi.yaml".to_string(),
454 };
455
456 assert!(config.is_allowed(&path_import));
457 assert!(!config.is_allowed(&git_import));
458 }
459
460 #[test]
461 fn test_cache_config_default() {
462 let config = CacheConfig::default();
463 assert!(config.enabled);
464 assert!(config.cache_dir.to_string_lossy().contains(".thru"));
465 }
466}