Skip to main content

abi_loader/fetcher/
mod.rs

1//! Import Fetcher Infrastructure
2//!
3//! This module provides a pluggable fetcher system for resolving ABI imports
4//! from various sources: local paths, git repositories, HTTP URLs, and on-chain.
5
6#[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/* ============================================================================
18Fetcher Configuration
19============================================================================ */
20
21/* Configuration for which import types are allowed */
22#[derive(Debug, Clone)]
23pub struct FetcherConfig {
24    /* Allow local path imports */
25    pub allow_path: bool,
26    /* Allow git repository imports */
27    pub allow_git: bool,
28    /* Allow HTTP/HTTPS URL imports */
29    pub allow_http: bool,
30    /* Allow on-chain imports */
31    pub allow_onchain: bool,
32
33    /* Git-specific configuration */
34    pub git_config: GitFetcherConfig,
35
36    /* On-chain specific configuration */
37    pub onchain_config: OnchainFetcherConfig,
38
39    /* Caching configuration */
40    pub cache_config: CacheConfig,
41}
42
43impl Default for FetcherConfig {
44    fn default() -> Self {
45        Self::cli_default()
46    }
47}
48
49impl FetcherConfig {
50    /* Default configuration for CLI usage - all import types allowed */
51    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    /* Configuration for WASM runtime - no remote fetching */
64    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    /* Configuration for production builds - only on-chain allowed */
77    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    /* Configuration for local development - only path imports */
90    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    /* Check if a given import source is allowed by this configuration */
103    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/* Git fetcher configuration */
114#[derive(Debug, Clone, Default)]
115pub struct GitFetcherConfig {
116    /* Path to SSH key for authentication (optional, uses ssh-agent by default) */
117    pub ssh_key_path: Option<PathBuf>,
118    /* Use git credential helper for HTTPS auth */
119    pub use_credential_helper: bool,
120    /* HTTP/HTTPS proxy URL */
121    pub proxy: Option<String>,
122    /* Timeout for git operations in seconds */
123    pub timeout_seconds: u64,
124}
125
126impl GitFetcherConfig {
127    /* Create with default timeout */
128    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/* On-chain fetcher configuration */
139#[derive(Debug, Clone)]
140pub struct OnchainFetcherConfig {
141    /* Map of network name to RPC endpoint URL */
142    pub rpc_endpoints: std::collections::HashMap<String, String>,
143    /* Default network to use if not specified in import */
144    pub default_network: String,
145    /* Timeout for RPC calls in seconds */
146    pub timeout_seconds: u64,
147    /* ABI manager program public key (Thru address) */
148    pub abi_manager_program_id: String,
149    /* Whether ABI manager accounts are ephemeral */
150    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    /* Get the RPC endpoint for a given network */
173    pub fn get_endpoint(&self, network: &str) -> Option<&str> {
174        self.rpc_endpoints.get(network).map(|s| s.as_str())
175    }
176
177    /* Add or update an RPC endpoint */
178    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/* Cache configuration */
184#[derive(Debug, Clone)]
185pub struct CacheConfig {
186    /* Enable caching */
187    pub enabled: bool,
188    /* Directory for cached imports */
189    pub cache_dir: PathBuf,
190    /* Maximum age of cached items in seconds (0 = no expiry) */
191    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, /* 1 hour */
200        }
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    /* Create a disabled cache configuration */
219    pub fn disabled() -> Self {
220        Self {
221            enabled: false,
222            cache_dir: PathBuf::new(),
223            max_age_seconds: 0,
224        }
225    }
226
227    /* Create with custom cache directory */
228    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/* ============================================================================
238Fetch Context
239============================================================================ */
240
241/* Context passed to fetchers during resolution */
242#[derive(Debug, Clone)]
243pub struct FetchContext {
244    /* Base path for resolving relative path imports */
245    pub base_path: Option<PathBuf>,
246    /* True if the parent import was from a remote source */
247    pub parent_is_remote: bool,
248    /* Include directories for path resolution */
249    pub include_dirs: Vec<PathBuf>,
250}
251
252impl FetchContext {
253    /* Create a new fetch context for a root file */
254    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    /* Create a child context for an import from this context */
263    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/* ============================================================================
273Fetch Result
274============================================================================ */
275
276/* Result of successfully fetching an ABI file */
277#[derive(Debug, Clone)]
278pub struct FetchResult {
279    /* Raw YAML content of the ABI file */
280    pub content: String,
281    /* Canonical location identifier (for caching and cycle detection) */
282    pub canonical_location: String,
283    /* Whether the source is remote (git, http, onchain) */
284    pub is_remote: bool,
285    /* Resolved file path (for path imports only) */
286    pub resolved_path: Option<PathBuf>,
287}
288
289/* ============================================================================
290Fetch Error
291============================================================================ */
292
293/* Errors that can occur during fetching */
294#[derive(Debug)]
295pub enum FetchError {
296    /* Import source type not supported by this fetcher */
297    UnsupportedSource(String),
298    /* Import source type not allowed by configuration */
299    NotAllowed(ImportSource),
300    /* Local import from remote parent not allowed */
301    LocalFromRemote(String),
302    /* File not found */
303    NotFound(String),
304    /* IO error */
305    Io(std::io::Error),
306    /* Git operation failed */
307    Git(String),
308    /* HTTP request failed */
309    Http { status: u16, message: String },
310    /* On-chain fetch failed */
311    Onchain(String),
312    /* Parse error */
313    Parse(String),
314    /* Network not configured */
315    UnknownNetwork(String),
316    /* Revision mismatch */
317    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
363/* ============================================================================
364Fetcher Trait
365============================================================================ */
366
367/* Trait for import source fetchers */
368pub trait ImportFetcher: Send + Sync {
369    /* Check if this fetcher handles the given import source type */
370    fn handles(&self, source: &ImportSource) -> bool;
371
372    /* Fetch the ABI content from the source */
373    fn fetch(&self, source: &ImportSource, ctx: &FetchContext) -> Result<FetchResult, FetchError>;
374}
375
376/* ============================================================================
377Composite Fetcher
378============================================================================ */
379
380/* Composite fetcher that delegates to the appropriate backend */
381pub struct CompositeFetcher {
382    fetchers: Vec<Box<dyn ImportFetcher>>,
383    config: FetcherConfig,
384}
385
386impl CompositeFetcher {
387    /* Create a new composite fetcher with the given configuration */
388    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    /* Fetch an import source */
413    pub fn fetch(
414        &self,
415        source: &ImportSource,
416        ctx: &FetchContext,
417    ) -> Result<FetchResult, FetchError> {
418        /* Check if source type is allowed */
419        if !self.config.is_allowed(source) {
420            return Err(FetchError::NotAllowed(source.clone()));
421        }
422
423        /* Find appropriate fetcher */
424        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    /* Get the configuration */
434    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}