Skip to main content

logicaffeine_cli/project/
registry.rs

1//! Phase 39: Registry Client
2//!
3//! HTTP client for communicating with the LOGOS package registry.
4//!
5//! This module provides the [`RegistryClient`] for authenticated API calls to
6//! the package registry, along with supporting types for package metadata and
7//! error handling.
8//!
9//! # Architecture
10//!
11//! The registry client uses [`ureq`] for HTTP requests with Bearer token
12//! authentication. All requests are made over HTTPS to the configured registry
13//! URL (defaulting to `registry.logicaffeine.com`).
14//!
15//! # Example
16//!
17//! ```no_run
18//! use logicaffeine_cli::project::registry::{RegistryClient, PublishMetadata};
19//!
20//! let client = RegistryClient::new("https://registry.logicaffeine.com", "tok_xxx");
21//!
22//! // Validate authentication
23//! let user = client.validate_token()?;
24//! println!("Authenticated as: {}", user.login);
25//! # Ok::<(), Box<dyn std::error::Error>>(())
26//! ```
27
28use std::path::Path;
29
30const DEFAULT_REGISTRY_URL: &str = "https://registry.logicaffeine.com";
31
32/// HTTP client for the LOGOS package registry API.
33///
34/// Provides authenticated access to registry operations including:
35/// - Token validation
36/// - Package publishing
37///
38/// # Authentication
39///
40/// All API calls require a Bearer token, typically obtained via `largo login`.
41/// Tokens are validated against the registry's `/auth/me` endpoint.
42///
43/// # Example
44///
45/// ```no_run
46/// use logicaffeine_cli::project::registry::RegistryClient;
47///
48/// let client = RegistryClient::new(
49///     RegistryClient::default_url(),
50///     "tok_xxxxx"
51/// );
52///
53/// // Verify the token is valid
54/// match client.validate_token() {
55///     Ok(user) => println!("Logged in as {}", user.login),
56///     Err(e) => eprintln!("Auth failed: {}", e),
57/// }
58/// ```
59pub struct RegistryClient {
60    /// Base URL of the registry API (without trailing slash).
61    base_url: String,
62    /// Bearer token for authentication.
63    token: String,
64}
65
66impl RegistryClient {
67    /// Create a new registry client with the given URL and authentication token.
68    ///
69    /// # Arguments
70    ///
71    /// * `base_url` - The registry API base URL. Trailing slashes are stripped.
72    /// * `token` - Bearer token for authentication.
73    ///
74    /// # Example
75    ///
76    /// ```
77    /// use logicaffeine_cli::project::registry::RegistryClient;
78    ///
79    /// let client = RegistryClient::new(
80    ///     "https://registry.logicaffeine.com",
81    ///     "tok_xxxxx"
82    /// );
83    /// ```
84    pub fn new(base_url: &str, token: &str) -> Self {
85        Self {
86            base_url: base_url.trim_end_matches('/').to_string(),
87            token: token.to_string(),
88        }
89    }
90
91    /// Returns the default registry URL.
92    ///
93    /// Currently returns `https://registry.logicaffeine.com`.
94    pub fn default_url() -> &'static str {
95        DEFAULT_REGISTRY_URL
96    }
97
98    /// Validate the authentication token by querying the registry.
99    ///
100    /// Makes a request to `/auth/me` to verify the token is valid and
101    /// retrieve the associated user information.
102    ///
103    /// # Errors
104    ///
105    /// Returns [`RegistryError::Unauthorized`] if the token is invalid or expired.
106    /// Returns [`RegistryError::Network`] for connection failures.
107    pub fn validate_token(&self) -> Result<UserInfo, RegistryError> {
108        let url = format!("{}/auth/me", self.base_url);
109
110        let response = ureq::get(&url)
111            .set("Authorization", &format!("Bearer {}", self.token))
112            .call()
113            .map_err(|e| match e {
114                ureq::Error::Status(401, _) => RegistryError::Unauthorized,
115                ureq::Error::Status(403, r) => {
116                    let msg = r.into_string().unwrap_or_default();
117                    RegistryError::Forbidden(msg)
118                }
119                ureq::Error::Status(code, r) => RegistryError::Server {
120                    status: code,
121                    message: r.into_string().unwrap_or_default(),
122                },
123                e => RegistryError::Network(e.to_string()),
124            })?;
125
126        let user: UserInfo = response
127            .into_json()
128            .map_err(|e| RegistryError::Network(e.to_string()))?;
129
130        Ok(user)
131    }
132
133    /// Publish a package to the registry.
134    ///
135    /// Uploads a package tarball with metadata to the registry's publish endpoint.
136    /// The request is sent as multipart form data.
137    ///
138    /// # Arguments
139    ///
140    /// * `name` - Package name (must match manifest)
141    /// * `version` - Semantic version string
142    /// * `tarball` - Gzipped tar archive of the package
143    /// * `metadata` - Package metadata for the registry index
144    ///
145    /// # Errors
146    ///
147    /// - [`RegistryError::Unauthorized`] - Invalid or missing token
148    /// - [`RegistryError::VersionExists`] - This version already published
149    /// - [`RegistryError::TooLarge`] - Package exceeds 10MB limit
150    /// - [`RegistryError::InvalidPackage`] - Metadata serialization failed
151    pub fn publish(
152        &self,
153        name: &str,
154        version: &str,
155        tarball: &[u8],
156        metadata: &PublishMetadata,
157    ) -> Result<PublishResult, RegistryError> {
158        let url = format!("{}/packages/publish", self.base_url);
159
160        // Create multipart form data
161        let boundary = format!("----LargoBoundary{}", rand::random::<u64>());
162
163        let metadata_json = serde_json::to_string(metadata)
164            .map_err(|e| RegistryError::InvalidPackage(e.to_string()))?;
165
166        let mut body = Vec::new();
167
168        // Add metadata field
169        body.extend_from_slice(
170            format!(
171                "--{}\r\nContent-Disposition: form-data; name=\"metadata\"\r\n\r\n{}\r\n",
172                boundary, metadata_json
173            )
174            .as_bytes(),
175        );
176
177        // Add tarball field
178        body.extend_from_slice(format!(
179            "--{}\r\nContent-Disposition: form-data; name=\"tarball\"; filename=\"{}-{}.tar.gz\"\r\nContent-Type: application/gzip\r\n\r\n",
180            boundary, name, version
181        ).as_bytes());
182        body.extend_from_slice(tarball);
183        body.extend_from_slice(format!("\r\n--{}--\r\n", boundary).as_bytes());
184
185        let response = ureq::post(&url)
186            .set("Authorization", &format!("Bearer {}", self.token))
187            .set(
188                "Content-Type",
189                &format!("multipart/form-data; boundary={}", boundary),
190            )
191            .send_bytes(&body)
192            .map_err(|e| match e {
193                ureq::Error::Status(401, _) => RegistryError::Unauthorized,
194                ureq::Error::Status(403, r) => {
195                    let msg = r.into_string().unwrap_or_else(|_| "Forbidden".to_string());
196                    RegistryError::Forbidden(msg)
197                }
198                ureq::Error::Status(409, _) => RegistryError::VersionExists {
199                    name: name.to_string(),
200                    version: version.to_string(),
201                },
202                ureq::Error::Status(413, _) => RegistryError::TooLarge,
203                ureq::Error::Status(code, r) => RegistryError::Server {
204                    status: code,
205                    message: r.into_string().unwrap_or_default(),
206                },
207                e => RegistryError::Network(e.to_string()),
208            })?;
209
210        let result: PublishResult = response
211            .into_json()
212            .map_err(|e| RegistryError::Network(e.to_string()))?;
213
214        Ok(result)
215    }
216}
217
218/// Create a gzipped tarball from a LOGOS project.
219///
220/// Packages the project for upload to the registry. The tarball includes:
221/// - `Largo.toml` (required)
222/// - `src/` directory recursively (required)
223/// - `README.md` (if present)
224/// - `LICENSE` (if present)
225///
226/// Hidden files (starting with `.`) and the `target/` directory are excluded.
227/// Only `.lg`, `.md`, `.toml`, and `.json` files are included from `src/`.
228///
229/// # Arguments
230///
231/// * `project_dir` - Root directory of the LOGOS project
232///
233/// # Errors
234///
235/// Returns [`PackageError::MissingFile`] if `Largo.toml` or `src/` is missing.
236pub fn create_tarball(project_dir: &Path) -> Result<Vec<u8>, PackageError> {
237    use flate2::write::GzEncoder;
238    use flate2::Compression;
239    use tar::Builder;
240
241    let mut tarball = Vec::new();
242
243    {
244        let encoder = GzEncoder::new(&mut tarball, Compression::default());
245        let mut builder = Builder::new(encoder);
246
247        // Add Largo.toml
248        let manifest_path = project_dir.join("Largo.toml");
249        if !manifest_path.exists() {
250            return Err(PackageError::MissingFile("Largo.toml".to_string()));
251        }
252        add_file_to_tar(&mut builder, project_dir, "Largo.toml")?;
253
254        // Add src/ directory recursively
255        let src_dir = project_dir.join("src");
256        if !src_dir.exists() {
257            return Err(PackageError::MissingFile("src/".to_string()));
258        }
259        add_dir_recursive(&mut builder, project_dir, "src")?;
260
261        // Add README.md if it exists
262        if project_dir.join("README.md").exists() {
263            add_file_to_tar(&mut builder, project_dir, "README.md")?;
264        }
265
266        // Add LICENSE if it exists
267        if project_dir.join("LICENSE").exists() {
268            add_file_to_tar(&mut builder, project_dir, "LICENSE")?;
269        }
270
271        builder
272            .finish()
273            .map_err(|e| PackageError::TarError(e.to_string()))?;
274    }
275
276    Ok(tarball)
277}
278
279fn add_file_to_tar<W: std::io::Write>(
280    builder: &mut tar::Builder<W>,
281    base_dir: &Path,
282    rel_path: &str,
283) -> Result<(), PackageError> {
284    let full_path = base_dir.join(rel_path);
285    let content =
286        std::fs::read(&full_path).map_err(|e| PackageError::Io(format!("{}: {}", rel_path, e)))?;
287
288    let mut header = tar::Header::new_gnu();
289    header
290        .set_path(rel_path)
291        .map_err(|e| PackageError::TarError(e.to_string()))?;
292    header.set_size(content.len() as u64);
293    header.set_mode(0o644);
294    header.set_mtime(0); // Reproducible builds
295    header.set_cksum();
296
297    builder
298        .append(&header, content.as_slice())
299        .map_err(|e| PackageError::TarError(e.to_string()))?;
300
301    Ok(())
302}
303
304fn add_dir_recursive<W: std::io::Write>(
305    builder: &mut tar::Builder<W>,
306    base_dir: &Path,
307    rel_dir: &str,
308) -> Result<(), PackageError> {
309    let full_dir = base_dir.join(rel_dir);
310
311    for entry in
312        std::fs::read_dir(&full_dir).map_err(|e| PackageError::Io(format!("{}: {}", rel_dir, e)))?
313    {
314        let entry = entry.map_err(|e| PackageError::Io(e.to_string()))?;
315        let path = entry.path();
316        let name = entry.file_name();
317        let rel_path = format!("{}/{}", rel_dir, name.to_string_lossy());
318
319        // Skip hidden files and target directory
320        let name_str = name.to_string_lossy();
321        if name_str.starts_with('.') || name_str == "target" {
322            continue;
323        }
324
325        if path.is_dir() {
326            add_dir_recursive(builder, base_dir, &rel_path)?;
327        } else if path.is_file() {
328            // Only include .lg, .md, and common config files
329            let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
330            if matches!(ext, "lg" | "md" | "toml" | "json") || name_str == "LICENSE" {
331                add_file_to_tar(builder, base_dir, &rel_path)?;
332            }
333        }
334    }
335
336    Ok(())
337}
338
339/// Check if the git working directory has uncommitted changes.
340///
341/// Runs `git status --porcelain` and returns `true` if there is any output,
342/// indicating uncommitted changes (modified, staged, or untracked files).
343///
344/// Returns `false` if:
345/// - The directory is not a git repository
346/// - Git is not available on the system
347/// - The working directory is clean
348///
349/// # Arguments
350///
351/// * `project_dir` - Directory to check (should contain `.git`)
352pub fn is_git_dirty(project_dir: &Path) -> bool {
353    use std::process::Command;
354
355    let output = Command::new("git")
356        .args(["status", "--porcelain"])
357        .current_dir(project_dir)
358        .output();
359
360    match output {
361        Ok(out) if out.status.success() => !out.stdout.is_empty(),
362        _ => false, // Not a git repo or git not available
363    }
364}
365
366// ============== Types ==============
367
368/// User information returned from the registry's `/auth/me` endpoint.
369///
370/// Contains details about the authenticated user, used to confirm
371/// successful login and display user information.
372#[derive(Debug, serde::Deserialize)]
373pub struct UserInfo {
374    /// Unique user identifier in the registry.
375    pub id: String,
376    /// GitHub username (used for login).
377    pub login: String,
378    /// Display name (may differ from login).
379    pub name: Option<String>,
380    /// Whether the user has registry admin privileges.
381    pub is_admin: bool,
382}
383
384/// Metadata submitted when publishing a package.
385///
386/// This information is stored in the registry index and displayed
387/// on the package's registry page.
388#[derive(Debug, serde::Serialize)]
389pub struct PublishMetadata {
390    /// Package name (must match `Largo.toml`).
391    pub name: String,
392    /// Semantic version string (e.g., "1.0.0").
393    pub version: String,
394    /// Short description of the package.
395    pub description: Option<String>,
396    /// URL to the source repository (e.g., GitHub).
397    pub repository: Option<String>,
398    /// URL to the project homepage or documentation.
399    pub homepage: Option<String>,
400    /// SPDX license identifier (e.g., "MIT", "Apache-2.0").
401    pub license: Option<String>,
402    /// Searchable keywords for discovery.
403    pub keywords: Vec<String>,
404    /// Relative path to the entry point file.
405    pub entry_point: String,
406    /// Map of dependency names to version requirements.
407    pub dependencies: std::collections::HashMap<String, String>,
408    /// Full README content (if `README.md` exists).
409    pub readme: Option<String>,
410}
411
412/// Response from a successful publish operation.
413///
414/// Returned by the registry after a package is successfully uploaded
415/// and indexed.
416#[derive(Debug, serde::Deserialize)]
417pub struct PublishResult {
418    /// Whether the publish succeeded.
419    pub success: bool,
420    /// The published package name.
421    pub package: String,
422    /// The published version.
423    pub version: String,
424    /// SHA-256 hash of the uploaded tarball.
425    pub sha256: String,
426    /// Size of the tarball in bytes.
427    pub size: u64,
428}
429
430// ============== Errors ==============
431
432/// Errors that can occur during registry API operations.
433///
434/// Each variant includes a user-friendly error message with guidance
435/// on how to resolve the issue.
436#[derive(Debug)]
437pub enum RegistryError {
438    /// No authentication token was provided or found.
439    NoToken,
440    /// The provided token is invalid or expired (HTTP 401).
441    Unauthorized,
442    /// The server rejected the request (HTTP 403).
443    Forbidden(String),
444    /// The package version already exists in the registry (HTTP 409).
445    VersionExists {
446        /// Package name.
447        name: String,
448        /// Version that already exists.
449        version: String,
450    },
451    /// The package tarball exceeds the size limit (HTTP 413).
452    TooLarge,
453    /// Network or connection error.
454    Network(String),
455    /// The server returned an unexpected error.
456    Server {
457        /// HTTP status code.
458        status: u16,
459        /// Error message from the server.
460        message: String,
461    },
462    /// The package metadata could not be serialized.
463    InvalidPackage(String),
464}
465
466impl std::fmt::Display for RegistryError {
467    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
468        match self {
469            Self::NoToken => write!(
470                f,
471                "No authentication token found.\n\
472                 Run 'largo login' or set LOGOS_TOKEN environment variable."
473            ),
474            Self::Unauthorized => write!(
475                f,
476                "Authentication failed. Your token may be invalid or expired.\n\
477                 Run 'largo login' to get a new token."
478            ),
479            Self::Forbidden(msg) => write!(f, "Access denied: {}", msg),
480            Self::VersionExists { name, version } => write!(
481                f,
482                "Version {} of package '{}' already exists.\n\
483                 Update the version in Largo.toml and try again.",
484                version, name
485            ),
486            Self::TooLarge => write!(f, "Package too large. Maximum size is 10MB."),
487            Self::Network(e) => write!(f, "Network error: {}", e),
488            Self::Server { status, message } => {
489                write!(f, "Registry returned error {}: {}", status, message)
490            }
491            Self::InvalidPackage(e) => write!(f, "Invalid package: {}", e),
492        }
493    }
494}
495
496impl std::error::Error for RegistryError {}
497
498/// Errors that can occur when creating a package tarball.
499#[derive(Debug)]
500pub enum PackageError {
501    /// A required file is missing from the project.
502    MissingFile(String),
503    /// A file system operation failed.
504    Io(String),
505    /// The tar archive could not be created.
506    TarError(String),
507}
508
509impl std::fmt::Display for PackageError {
510    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
511        match self {
512            Self::MissingFile(name) => write!(f, "Missing required file: {}", name),
513            Self::Io(e) => write!(f, "I/O error: {}", e),
514            Self::TarError(e) => write!(f, "Failed to create tarball: {}", e),
515        }
516    }
517}
518
519impl std::error::Error for PackageError {}