Skip to content

RFC-014a: Registry Protocol Specification ​

This RFC is a sub-RFC of RFC-014: Package Management System Design.

2026-09-15 Review Resolution ​

The following resolution was finalized by the owner on 2026-09-15; the corresponding sections of the body are retained as the complete specification for "after the official Registry goes live":

  1. Scope Reduction (the single most important item in this document): The official Registry server, authentication (login/logout), and yank are postponed indefinitely. Phase 4 deliverables in practice = GitHub Release / Git adapter layer + Registry trait finalization + .yxpkg packaging + publish --github. Rationale: bootstrapping the ecosystem only needs the git/GitHub channel (Go went through the same phase early on); the operational, account-system, and abuse-governance costs of a Registry server are pure liabilities at a stage with no third-party packages.
  2. Bare-name add is unavailable: Before the official Registry is online, yaoxiang add <bare-name> errors out; adding dependencies requires an explicit source (--git / --path). The "source priority" lookup chain below takes effect from Registry launch.
  3. Package format unification: .yxpkg contains only source code (yaoxiang.toml/src//build.yx/SHA256SUMS); the build/native/ prebuilt-output directory is removed; binary distribution is handled exclusively through RFC-014b's [binaries] external links (Release/CDN), to avoid package-size and global-cache bloat.
  4. Source distribution implementation: The four built-in sources (Local/Git/Registry/GitHub) are a closed set; the implementation layer uses an enum for dispatch (avoiding dyn-async Send bounds and async-trait dependencies); the Source trait definition stays in the semantic layer, and if third-party Sources are ever opened up, they will be wired in via trait objects in the future.
  5. API versioning: URL path /api/v1/ + protocol version in response headers; breaking changes bump to v2 and coexist, no in-place changes.
  6. Rate limiting: Exponential backoff + ETag conditional-request caching in the GitHub adapter; Registry-side rate policy is postponed along with the official Registry.
  7. Package size limit: Source package 20 MiB (initial value, adjustable); the GitHub channel is governed by the platform itself.

Summary ​

Defines the Registry protocol for the YaoXiang package management system: open interface design, official Registry specification, GitHub adapter layer, package publish/yank flow, authentication model.

Motivation ​

RFC-014 master document defines the overall architecture of the package management system, but the Registry section is only marked as "reserved." Without a Registry protocol, packages cannot be distributed — that's like designing a shopping cart without a store.

Current Problems ​

  • RegistrySource is stub code (source/mod.rs:150-203); resolve directly returns the declared version, and download returns an empty path
  • No HTTP client (no reqwest dependency)
  • No package publish mechanism
  • No authentication/authorization

Proposal ​

Core Design: Open Protocol + Adapter Layer ​

┌──────────────────────────────────────────┐
│         yaoxiang publish/install         │  ← CLI layer
└──────────────────┬───────────────────────┘
                   │
                   ▼
┌──────────────────────────────────────────┐
│          Registry Trait                  │  ← Protocol layer (open interface)
│  ┌─────────┬──────────┬────────────┐    │
│  │ .publish│ .search  │ .download  │    │
│  │ .yank   │ .info    │ .versions  │    │
│  └─────────┴──────────┴────────────┘    │
└──────────────────┬───────────────────────┘
                   │
        ┌──────────┼──────────┐
        ▼          ▼          ▼
   ┌─────────┐ ┌────────┐ ┌─────────┐
   │ Official│ │ GitHub │ │ Custom  │
   │Registry │ │Adapter │ │Registry │
   └─────────┘ └────────┘ └─────────┘

Async Architecture Decision ​

The Source trait is unified to async, fully embracing tokio:

rust
// Existing (sync) → changed to (async)
#[async_trait]
pub trait Source: Send + Sync {
    fn name(&self) -> &str;
    fn kind(&self) -> SourceKind;

    async fn resolve(&self, spec: &DependencySpec) -> PackageResult<String>;
    async fn download(&self, spec: &DependencySpec, dest: &Path) -> PackageResult<ResolvedPackage>;
}

All implementations (LocalSource, GitSource, RegistrySource) are unified to async. The CLI entry point is driven via #[tokio::main] or Runtime::block_on.

Rationale:

  • Registry needs HTTP requests; blocking would stall the entire install flow
  • Parallel download of multiple dependencies (join_all) significantly improves install speed
  • Git clone is also I/O; async is more natural
  • tokio is already in the project dependencies

Registry Trait ​

rust
#[async_trait]
trait Registry: Send + Sync {
    /// Publish a package
    async fn publish(&self, package: &PackageManifest, artifact: &Path) -> PackageResult<()>;

    /// Delete a published version (irrecoverable, version number is locked)
    async fn yank(&self, name: &str, version: &Version) -> PackageResult<()>;

    /// Query package information
    async fn info(&self, name: &str) -> PackageResult<PackageInfo>;

    /// Query the list of available versions
    async fn versions(&self, name: &str) -> PackageResult<Vec<Version>>;

    /// Search packages
    async fn search(&self, query: &str) -> PackageResult<Vec<PackageSummary>>;

    /// Download a specific version
    async fn download(&self, name: &str, version: &Version) -> PackageResult<PathBuf>;

    /// Authenticate
    async fn authenticate(&self, credentials: &Credentials) -> PackageResult<()>;
}

Source Priority (Default Lookup Chain) ​

Default lookup order when running yaoxiang add foo (no flag):

PriorityLookupDescription
1Global cache~/.yaoxiang/cache/registry/foo-<ver>/
2Official RegistryQuery version → download
3FailureError, prompt user to check name or network

Explicit override (bypasses the default chain):

flagBehavior
--git <url>Skip Registry, git clone directly (Release assets preferred → fallback to tag/branch)
--path <dir>Skip Registry, use local path directly
--registry <url>Skip official Registry, use the specified Registry

Official Registry ​

The official Registry is similar to crates.io and is the primary channel for package distribution.

API endpoints:

EndpointMethodDescription
/api/v1/packages/{name}GETQuery package information
/api/v1/packages/{name}/versionsGETQuery version list
/api/v1/packages/{name}/{version}GETDownload package
/api/v1/packagesPUTPublish package
/api/v1/packages/{name}/{version}/yankDELETEYank version
/api/v1/search?q={query}GETSearch packages
/api/v1/loginPOSTAuthenticate

GitHub Integration ​

When GitHub is used as a package source, a Go modules-style strategy is adopted:

  1. Prefer Release assets: check the GitHub Release page for matching platform prebuilts
  2. Fallback to the main branch: git clone if no Release
toml
[dependencies]
# Basic git dependency
foo = { git = "https://github.com/user/foo" }

# Specify version (match tag)
bar = { git = "https://github.com/user/bar", version = "^1.0.0" }

# Specify branch
baz = { git = "https://github.com/user/baz", branch = "main" }

# Specify commit
qux = { git = "https://github.com/user/qux", rev = "abc123" }

# Private repo (use GitHub token in credentials.toml)
private = { git = "https://github.com/my-org/private-lib" }

Package Format (.yxpkg) ​

2026-09-15 resolution: source code only; build/ prebuilt outputs removed — binaries are distributed exclusively via RFC-014b [binaries] external links.

foo-1.2.3.yxpkg (tar.gz)
├── yaoxiang.toml          # Package metadata
├── src/                   # Source code
├── build.yx               # Build script (if any)
└── SHA256SUMS             # Checksums

publish Flow ​

bash
# Publish to the official Registry
yaoxiang publish

# Publish to a specified Registry
yaoxiang publish --registry my-company

# Also create a GitHub Release
yaoxiang publish --github

# Dry run
yaoxiang publish --dry-run

Pre-publish validation:

  1. yaoxiang.toml must have name, version, description
  2. The version must not already exist
  3. Run tests (optional, skip with --no-test)
  4. Compute SHA-256 of all files
  5. Pack into .yxpkg (tar.gz)
  6. Upload to Registry

yank Semantics ​

bash
yaoxiang yank foo@1.2.3

Delete + version-number lock:

  • The package is completely deleted and irrecoverable
  • The version number is permanently occupied; the same version number cannot be republished
  • Projects whose existing lockfiles reference this version will error and need to upgrade to another version
  • Security purpose: prevent npm-style supply-chain attacks. Attackers have previously snatched deleted package version numbers to inject malicious code; locking the version number on yank completely closes that path.

Authentication Model ​

toml
# ~/.yaoxiang/credentials.toml
[github]
token = "ghp_xxxx"

[registries.my-company]
url = "https://yxreg.my-company.com"
token = "xxx"

Mapping rule: yaoxiang login --registry <url> matches the url field in [registries.*] by URL. If no match, create a new entry (auto-generated name, e.g., reg-1).

Priority: environment variables > config file

Environment variablePurpose
$YX_GITHUB_TOKENGitHub authentication
$YX_REGISTRY_TOKENRegistry authentication (for the default Registry)
$YX_REGISTRY_URLDefault Registry address

CLI commands:

bash
yaoxiang login --registry https://yxreg.example.com   # Match by URL or create new
yaoxiang login --github                                # GitHub OAuth or token
yaoxiang logout --registry https://yxreg.example.com   # Remove the matching entry

Security constraints:

  • Tokens are never written into yaoxiang.toml or yaoxiang.lock
  • credentials.toml file permissions 600
  • Use environment variables in CI; use the file in development

Detailed Design ​

RegistrySource Implementation ​

Replace the existing stub code (source/mod.rs:150-203):

rust
pub struct RegistrySource {
    client: reqwest::Client,
    base_url: String,
}

#[async_trait]
impl Source for RegistrySource {
    fn name(&self) -> &str { "registry" }
    fn kind(&self) -> SourceKind { SourceKind::Registry }

    async fn resolve(&self, spec: &DependencySpec) -> PackageResult<String> {
        let url = format!("{}/api/v1/packages/{}/versions", self.base_url, spec.name);
        let versions: Vec<Version> = self.client.get(&url).send().await?.json().await?;
        let req = parse_version_req(&spec.version)?;
        select_best(&req, &versions)
            .map(|v| v.to_string())
            .ok_or(PackageError::DependencyNotFound(spec.name.clone()))
    }

    async fn download(&self, spec: &DependencySpec, dest: &Path) -> PackageResult<ResolvedPackage> {
        let version = self.resolve(spec).await?;
        let url = format!("{}/api/v1/packages/{}/{}/download", self.base_url, spec.name, version);
        let bytes = self.client.get(&url).send().await?.bytes().await?;

        // SHA-256 validation
        let actual_hash = sha256_hex(&bytes);
        // ... extract to dest ...

        Ok(ResolvedPackage {
            name: spec.name.clone(),
            version,
            source_kind: SourceKind::Registry,
            source_url: self.base_url.clone(),
            local_path: dest.to_path_buf(),
            checksum: Some(actual_hash),
        })
    }
}

Dependencies ​

cratePurpose
reqwestHTTP client
sha2SHA-256 validation
flate2 + tarPackage format handling
async-traitRetired — per resolution 4, adopt enum dispatch + native async fn in trait, no such dependency

Error Types ​

rust
#[derive(Debug, thiserror::Error)]
pub enum RegistryError {
    #[error("package '{0}' does not exist")]
    PackageNotFound(String),

    #[error("version '{0}' does not exist")]
    VersionNotFound(String),

    #[error("version '{0}' is already taken")]
    VersionAlreadyExists(String),

    #[error("authentication failed: {0}")]
    AuthFailed(String),

    #[error("network error: {0}")]
    NetworkError(#[from] reqwest::Error),

    #[error("SHA-256 validation failed: expected {expected}, actual {actual}")]
    ChecksumMismatch { expected: String, actual: String },

    #[error("insufficient permissions: {0}")]
    Forbidden(String),
}

Trade-offs ​

Pros ​

  • Open protocol, not bound to a specific server
  • GitHub as a lightweight distribution channel lowers the entry barrier
  • Security model with locked version numbers
  • Install strategy that prefers prebuilts

Cons ​

  • The official Registry requires independent operation
  • GitHub API has rate limits
  • Locking version numbers may lead to wasted version numbers

Alternatives ​

PlanWhy not chosen
GitHub onlyConstrained by the GitHub ecosystem, cannot self-host a Registry
Cargo-style crates.ioToo complex; not needed in the early YaoXiang ecosystem
npm-style yank (mark only)Security risk; known supply-chain attack cases

Implementation Strategy ​

Phase Breakdown ​

PhaseContentStatus
Phase 3.5Source dispatch enum-ification (resolution 4) + native async fn in trait + migration of all implementations✅ Done
Phase 4aGitHub adapter layer (original "Registry trait + reqwest + local mock" reduced per resolution 1: github.com git dependency routes GitHubSource; API parsing + .yxpkg asset download + git fallback; exponential backoff + ETag conditional cache per resolution 6)✅ Done
Phase 4b.yxpkg package format (tar.gz + SHA256SUMS + 20 MiB limit, resolutions 3/7; deterministic packaging, mandatory validation on extraction)✅ Done
Phase 4cpublish command (--dry-run full local chain; --github duplicate-check → tag validation → Release → asset upload; 6d workspace reference substitution materialized at pack time)✅ Done
Phase 4dAuthentication (login/logout/credentials.toml) + yankPostponed indefinitely (along with the official Registry, resolution 1)

Landing notes (2026-09-29):

  • HTTP stack: reqwest (rustls, no OpenSSL cross-compilation) + package-management's own tokio current_thread runtime (package::runtime::drive); POST requests (create Release / upload assets) do not auto-retry — they are non-idempotent, and resending after a 5xx may create duplicates.
  • Target repo resolution for publish: [package].repository first, fallback to git remote origin; the tag is required to already exist (same semantics as Cargo: publish does not tag on your behalf).
  • Pre-publish test run (validation step 3 above) is wired up (2026-09-30, alongside RFC-014b): by default runs tests discovered by [tool.test]; failure aborts publish; --no-test skips.
  • credentials.toml and login/logout/yank commands are postponed along with the official Registry; current authentication is only the $YX_GITHUB_TOKEN environment variable (priority rule unchanged: environment variable > config file).

Dependencies ​

  • Depends on RFC-014 Phase 3 (global cache, semver replacement)
  • Depends on RFC-014b (build system, used for build/ directory handling)

Open Questions ​

  • [x] Does the Registry API need versioning (/api/v1/ vs /api/v2/)? → URL /api/v1/ + version response header; breaking changes bump to v2 and coexist (2026-09-15)
  • [x] Do package names support namespaces (e.g., @org/pkg)? → Not supported initially; flat package names (2026-09-15, see master document)
  • [x] Rate-limiting strategy? → Backoff + cache in the GitHub adapter; Registry-side policy postponed along with the official Registry (2026-09-15)
  • [x] Package size limit? → Source package 20 MiB initial value (2026-09-15, adjustable)

References ​