Skip to main content

marketplace_client/
lib.rs

1//! Transport-only client for the Argone marketplace, isolated at the extraction boundary: REST for
2//! the auth bootstrap (whoami) and gRPC for `Registry.Publish`. Carries no crypto — callers
3//! assemble signed bytes and hand them over as primitives.
4
5pub mod proto;
6
7mod consume;
8mod grpc;
9mod rest;
10
11/// One error taxonomy folding both gRPC `Status` and REST ProblemDetails.
12#[derive(Debug)]
13pub enum MarketplaceError {
14    /// Connect/IO/timeout, or an unusable base URL.
15    Transport(String),
16    /// gRPC `Unauthenticated` | REST 401 — bad/missing PAT or credentials.
17    Unauthenticated,
18    /// gRPC `PermissionDenied` | REST 403 — authenticated but not allowed.
19    PermissionDenied,
20    /// gRPC `InvalidArgument` | REST 400 — message carries the server detail.
21    Invalid(String),
22    /// gRPC `AlreadyExists` | REST 409 — duplicate (e.g. version already published).
23    Conflict(String),
24    /// Other REST failure with the ProblemDetails status + detail.
25    Http { status: u16, detail: String },
26    /// Response body / metadata could not be decoded as expected.
27    Decode(String),
28}
29
30impl std::fmt::Display for MarketplaceError {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        match self {
33            MarketplaceError::Transport(m) => write!(f, "transport error: {m}"),
34            MarketplaceError::Unauthenticated => {
35                write!(f, "unauthenticated (check your PAT / credentials)")
36            }
37            MarketplaceError::PermissionDenied => write!(f, "permission denied"),
38            MarketplaceError::Invalid(m) => write!(f, "invalid request: {m}"),
39            MarketplaceError::Conflict(m) => write!(f, "conflict: {m}"),
40            MarketplaceError::Http { status, detail } => write!(f, "http {status}: {detail}"),
41            MarketplaceError::Decode(m) => write!(f, "decode error: {m}"),
42        }
43    }
44}
45impl std::error::Error for MarketplaceError {}
46
47pub struct PublishParams {
48    pub app_wasm: Vec<u8>,
49    pub manifest_mpack: Vec<u8>,
50    pub release_json: Vec<u8>,
51    pub artifact_sig: [u8; 64],
52    pub publisher_pubkey: [u8; 32],
53}
54#[derive(Debug)]
55pub struct PackageRef {
56    pub name: String,
57    pub version: String,
58}
59
60/// Search result summary decoded from `proto::PackageSummary` — plain data, no crypto.
61#[derive(Debug)]
62pub struct PackageSummary {
63    pub name: String,
64    pub kind: String,
65    pub current_version: String,
66    pub publisher_handle: String,
67    pub download_count: u64,
68}
69
70/// Display-grade capability list decoded from `proto::Capabilities` — no crypto.
71#[derive(Debug)]
72pub struct CapabilitiesView {
73    pub wasi: Vec<String>,
74    pub argone: Vec<String>,
75    pub accept_hash: String,
76}
77
78/// One published version decoded from `proto::VersionInfo`.
79#[derive(Debug)]
80pub struct VersionInfo {
81    pub version: String,
82    pub critical: bool,
83    pub channel: String,
84    pub published_at: String,
85    pub capabilities: CapabilitiesView,
86    pub download_count: u64,
87}
88
89/// Update available for an installed package decoded from `proto::UpdateAvailable`.
90#[derive(Debug)]
91pub struct UpdateAvailable {
92    pub name: String,
93    pub latest_version: String,
94    pub critical: bool,
95}
96
97/// Full package detail decoded from `proto::GetPackageResponse`.
98#[derive(Debug)]
99pub struct PackageInfo {
100    pub package: PackageSummary,
101    pub readme: String,
102    pub publisher_handle: String,
103    pub versions: Vec<VersionInfo>,
104}
105
106/// Downloaded artifact reassembled from the `Download` stream (header-first, then app_wasm
107/// chunks) — plain data, no crypto. Callers verify/decode signatures and manifest.
108#[derive(Debug)]
109pub struct DownloadedArtifact {
110    pub name: String,
111    pub version: String,
112    pub release_json: Vec<u8>,
113    pub manifest_mpack: Vec<u8>,
114    pub artifact_sig: [u8; 64],
115    pub publisher_pubkey: [u8; 32],
116    pub root_countersig: [u8; 64],
117    pub capabilities: CapabilitiesView,
118    pub app_wasm: Vec<u8>,
119}
120
121/// Marketplace client. `base_url` scheme selects TLS: `https` → rustls, `http` → plaintext h2c.
122///
123/// Fields are read by the REST (`rest.rs`) and gRPC (`grpc.rs`) transports.
124pub struct Client {
125    base_url: String,
126    http: reqwest::Client,
127}
128
129impl Client {
130    /// REST client over HTTP/1.1 (TLS+ALPN on `https`, plain HTTP/1.1 on `http`). Used against real
131    /// (TLS-terminated) marketplaces and the wiremock REST tests, which only speak HTTP/1.1.
132    pub fn connect(base_url: &str) -> Result<Client, MarketplaceError> {
133        build_client(base_url, false)
134    }
135
136    /// REST client that speaks h2c (HTTP/2 prior-knowledge) over `http://`. Needed for a local/CI
137    /// plaintext dev server whose single port is configured `HttpProtocols.Http2`-only (no ALPN
138    /// available without TLS, so HTTP/1.1 isn't served) — e.g. the marketplace smoke-test server.
139    pub fn connect_h2c(base_url: &str) -> Result<Client, MarketplaceError> {
140        build_client(base_url, true)
141    }
142}
143
144fn build_client(base_url: &str, h2c: bool) -> Result<Client, MarketplaceError> {
145    if !(base_url.starts_with("http://") || base_url.starts_with("https://")) {
146        return Err(MarketplaceError::Transport(format!(
147            "registry URL must start with http:// or https:// (got {base_url})"
148        )));
149    }
150    let mut builder = reqwest::Client::builder();
151    if h2c {
152        builder = builder.http2_prior_knowledge();
153    }
154    let http = builder
155        .build()
156        .map_err(|e| MarketplaceError::Transport(e.to_string()))?;
157    Ok(Client {
158        base_url: base_url.trim_end_matches('/').to_string(),
159        http,
160    })
161}
162
163#[cfg(test)]
164mod codegen_smoke {
165    #[test]
166    fn generated_types_are_accessible() {
167        // Proves the protox→tonic-build pipeline produced the expected symbols.
168        let req = crate::proto::PublishRequest::default();
169        assert!(req.app_wasm.is_empty());
170        let _ref = crate::proto::PackageRef {
171            name: "hello".into(),
172            version: "1.2.3".into(),
173        };
174    }
175}
176
177#[cfg(test)]
178mod connect_tests {
179    use super::*;
180    #[test]
181    fn rejects_unsupported_scheme() {
182        assert!(matches!(
183            Client::connect("ftp://x"),
184            Err(MarketplaceError::Transport(_))
185        ));
186    }
187    #[test]
188    fn accepts_http_and_https() {
189        assert!(Client::connect("http://localhost:8080").is_ok());
190        assert!(Client::connect("https://marketplace.example").is_ok());
191    }
192    #[test]
193    fn connect_h2c_accepts_http_and_https() {
194        assert!(Client::connect_h2c("http://localhost:8080").is_ok());
195        assert!(Client::connect_h2c("https://marketplace.example").is_ok());
196    }
197}