Skip to main content

sylphx_sdk_core/
lib.rs

1//! Shared transport and auth for Sylphx Platform Rust SDKs.
2//!
3//! Wire payloads are owned by `sylphx-api-types` (Protobuf). This crate only maps
4//! HTTP status + JSON error envelopes onto typed errors and applies auth.
5
6#![forbid(unsafe_code)]
7#![deny(missing_docs)]
8
9use std::pin::Pin;
10use std::time::Duration;
11
12use futures_core::Stream;
13use futures_util::StreamExt;
14use reqwest::{header, Client, Method, StatusCode};
15use serde::de::DeserializeOwned;
16use serde::Serialize;
17use sylphx_api_types::{ErrorEnvelope, CONTRACT_PACKAGE, CONTRACT_REVISION};
18use thiserror::Error;
19use url::Url;
20
21mod connection_url;
22
23/// Platform-owned signed project-binding admission for downstream services.
24pub mod project_binding;
25
26pub use project_binding::{
27    BindingAdmissionError, BindingDispatchError, CurrentBindingAuthority, CurrentBindingHead,
28    PlatformBindingVerifier, ProjectBindingAdmission, CLOCK_SKEW_SECONDS,
29    MAX_BINDING_LIFETIME_SECONDS, PLATFORM_ISSUER, PROJECT_BINDING_ALGORITHM,
30    PROJECT_BINDING_HEADER, PROJECT_BINDING_TYPE,
31};
32
33/// Connection URL SSOT (ADR-123 dual-oracle of `@sylphx/sdk` connection-url).
34pub use connection_url::{
35    build_connection_url, parse_connection_url, BuildConnectionUrlInput, ConnectionCredentialType,
36    ConnectionEnv, ParsedConnectionUrl,
37};
38
39/// Re-export contract identity for consumers and CLI evidence.
40pub use sylphx_api_types::{
41    CONTRACT_PACKAGE as API_TYPES_CONTRACT_PACKAGE,
42    CONTRACT_REVISION as API_TYPES_CONTRACT_REVISION,
43    VerifiedBindingContext, VerifiedBindingContextError,
44    VERIFIED_BINDING_CONTEXT_REVISION,
45};
46/// Deprecated aliases — prefer API_TYPES_CONTRACT_*.
47#[allow(non_upper_case_globals)]
48pub use sylphx_api_types::{
49    CONTRACT_PACKAGE as WIRE_CONTRACT_PACKAGE,
50    CONTRACT_REVISION as WIRE_CONTRACT_REVISION,
51};
52
53/// Default Management API base URL (includes `/v1`).
54pub const DEFAULT_MANAGEMENT_BASE_URL: &str = "https://api.sylphx.com/v1";
55
56/// Normalize a Management API base URL so callers always hit `/v1`.
57///
58/// Accepts host-only values such as `https://api.sylphx.com` and rewrites
59/// them to `https://api.sylphx.com/v1`. Already-versioned bases are preserved
60/// (trailing slash stripped). Empty input falls back to the default.
61pub fn normalize_management_base_url(url: &str) -> String {
62    let raw = url.trim();
63    if raw.is_empty() {
64        return DEFAULT_MANAGEMENT_BASE_URL.to_string();
65    }
66    let trimmed = raw.trim_end_matches('/');
67    match Url::parse(trimmed) {
68        Ok(parsed) => {
69            let path = parsed.path().trim_end_matches('/');
70            if path.is_empty() || path == "/" {
71                format!("{trimmed}/v1")
72            } else {
73                trimmed.to_string()
74            }
75        }
76        Err(_) => {
77            if trimmed.ends_with("api.sylphx.com") || (!trimmed.contains('/') && !trimmed.contains("/v1")) {
78                format!("{trimmed}/v1")
79            } else {
80                trimmed.to_string()
81            }
82        }
83    }
84}
85
86/// Customer Zero project slug (Console dogfood residual).
87/// Matches packages/contract platform-identity `PLATFORM_CONSOLE_SLUG`
88/// (ADR-089 §2.8.1 / ADR-3888). Identity / routing only — never an operator
89/// privilege grant (ADR-3418, ADR-3422).
90pub const PLATFORM_CONSOLE_SLUG: &str = "keen-wave-x3m9p2";
91
92/// Build the BaaS plane base URL for a tenant slug.
93pub fn baas_base_url(tenant_slug: &str) -> String {
94    format!("https://{tenant_slug}.api.sylphx.com/v1")
95}
96
97/// Customer Zero BaaS base URL (`…/v1`) for operator device login dogfood.
98///
99/// ADR-3888 / ADR-083.1 — never invent vanity hosts such as `platform.api…`.
100pub fn platform_console_baas_base_url() -> String {
101    baas_base_url(PLATFORM_CONSOLE_SLUG)
102}
103
104/// Credential material for a plane.
105#[derive(Debug, Clone)]
106pub enum Credential {
107    /// Management plane: OAuth JWT or `svc_*` service token as Bearer.
108    Bearer(String),
109    /// BaaS plane: `sk_*` / `pk_*` runtime key via `x-app-secret`.
110    AppSecret(String),
111}
112
113impl Credential {
114    /// Construct a Bearer credential; rejects empty tokens.
115    pub fn bearer(token: impl Into<String>) -> Result<Self, SdkError> {
116        let token = token.into();
117        if token.trim().is_empty() {
118            return Err(SdkError::InvalidCredential(
119                "management token must be non-empty".into(),
120            ));
121        }
122        Ok(Self::Bearer(token))
123    }
124
125    /// Construct an app-secret credential; validates `sk_` / `pk_` prefix.
126    pub fn app_secret(key: impl Into<String>) -> Result<Self, SdkError> {
127        let key = key.into();
128        if !(key.starts_with("sk_") || key.starts_with("pk_")) {
129            return Err(SdkError::InvalidCredential(
130                "BaaS key must start with sk_ or pk_".into(),
131            ));
132        }
133        Ok(Self::AppSecret(key))
134    }
135}
136
137/// Retry policy for transient failures.
138#[derive(Debug, Clone)]
139pub struct RetryConfig {
140    /// Maximum attempts including the first try.
141    pub max_attempts: u32,
142    /// Base delay between retries.
143    pub base_delay: Duration,
144}
145
146impl Default for RetryConfig {
147    fn default() -> Self {
148        Self {
149            max_attempts: 3,
150            base_delay: Duration::from_millis(100),
151        }
152    }
153}
154
155/// Shared HTTP client configuration for one plane endpoint.
156#[derive(Debug, Clone)]
157pub struct TransportConfig {
158    /// Base URL including `/v1` (no trailing slash required).
159    pub base_url: String,
160    /// Plane credential.
161    pub credential: Credential,
162    /// Per-request timeout.
163    pub timeout: Duration,
164    /// Retry policy.
165    pub retry: RetryConfig,
166}
167
168/// Production HTTP transport.
169#[derive(Debug, Clone)]
170pub struct Transport {
171    client: Client,
172    stream_client: Client,
173    config: TransportConfig,
174}
175
176/// Backpressure-aware typed Server-Sent Events response stream.
177pub type SdkEventStream<T> = Pin<Box<dyn Stream<Item = Result<T, SdkError>> + Send>>;
178
179impl Transport {
180    /// Build a transport with a shared reqwest client.
181    pub fn new(config: TransportConfig) -> Result<Self, SdkError> {
182        let client = Client::builder()
183            .timeout(config.timeout)
184            .user_agent(format!(
185                "sylphx-sdk-rust/{} ({CONTRACT_PACKAGE}@{CONTRACT_REVISION})",
186                env!("CARGO_PKG_VERSION")
187            ))
188            .build()
189            .map_err(|e| SdkError::Transport(e.to_string()))?;
190        // Streaming responses must not inherit the unary whole-request timeout:
191        // dropping the returned stream is the cancellation boundary. Connection
192        // establishment remains bounded by the configured timeout.
193        let stream_client = Client::builder()
194            .connect_timeout(config.timeout)
195            .user_agent(format!(
196                "sylphx-sdk-rust/{} ({CONTRACT_PACKAGE}@{CONTRACT_REVISION})",
197                env!("CARGO_PKG_VERSION")
198            ))
199            .build()
200            .map_err(|e| SdkError::Transport(e.to_string()))?;
201        let mut config = config;
202        config.base_url = normalize_management_base_url(&config.base_url);
203        Ok(Self {
204            client,
205            stream_client,
206            config,
207        })
208    }
209
210    /// Base URL for this transport.
211    pub fn base_url(&self) -> &str {
212        &self.config.base_url
213    }
214
215    /// Perform a JSON request and decode a successful body as `T`.
216    pub async fn request_json<B: Serialize, T: DeserializeOwned>(
217        &self,
218        method: Method,
219        path: &str,
220        body: Option<&B>,
221        extra_headers: &[(&str, &str)],
222    ) -> Result<T, SdkError> {
223        let url = join_url(&self.config.base_url, path)?;
224        let mut attempt = 0u32;
225        loop {
226            attempt += 1;
227            let mut builder = self.client.request(method.clone(), url.clone());
228            builder = apply_credential(builder, &self.config.credential);
229            for (k, v) in extra_headers {
230                builder = builder.header(*k, *v);
231            }
232            if let Some(b) = body {
233                builder = builder.json(b);
234            }
235            let response = builder.send().await.map_err(|e| SdkError::Transport(e.to_string()))?;
236            let status = response.status();
237            let bytes = response
238                .bytes()
239                .await
240                .map_err(|e| SdkError::Transport(e.to_string()))?;
241
242            if status.is_success() {
243                if bytes.is_empty() {
244                    // Allow empty 204-style bodies only for unit type consumers via Value.
245                    return serde_json::from_value(serde_json::json!({}))
246                        .map_err(|e| SdkError::Decode(e.to_string()));
247                }
248                // Live Management may emit JSON `null` for optional repeated fields
249                // (e.g. enabledOAuthProviders: null). Protobuf JSON codecs treat
250                // repeated fields as sequences, not null — strip null object keys
251                // so wire types decode cleanly without per-field workarounds.
252                let mut value: serde_json::Value = serde_json::from_slice(&bytes).map_err(|e| {
253                    SdkError::Decode(format!("{e}; body={}", String::from_utf8_lossy(&bytes)))
254                })?;
255                strip_json_nulls(&mut value);
256                return serde_json::from_value(value).map_err(|e| {
257                    SdkError::Decode(format!("{e}; body={}", String::from_utf8_lossy(&bytes)))
258                });
259            }
260
261            let api_err = map_error_body(status, &bytes);
262            if attempt < self.config.retry.max_attempts && is_retryable(status) {
263                let delay = self.config.retry.base_delay * attempt;
264                tokio::time::sleep(delay).await;
265                continue;
266            }
267            return Err(api_err);
268        }
269    }
270
271    /// Perform an authenticated ProtoJSON request and decode a typed SSE stream.
272    ///
273    /// The response body is consumed only as the caller polls the returned
274    /// stream. Dropping it cancels the underlying response. Automatic retries
275    /// stop once a stream is established so resumable cursor semantics remain
276    /// owned by the caller and the descriptor contract.
277    pub async fn request_sse<B, T>(
278        &self,
279        method: Method,
280        path: &str,
281        body: Option<&B>,
282        extra_headers: &[(&str, &str)],
283    ) -> Result<SdkEventStream<T>, SdkError>
284    where
285        B: Serialize + ?Sized,
286        T: DeserializeOwned + Send + 'static,
287    {
288        const MAX_EVENT_BYTES: usize = 4 * 1024 * 1024;
289
290        let url = join_url(&self.config.base_url, path)?;
291        let mut builder = self
292            .stream_client
293            .request(method, url)
294            .header(header::ACCEPT, "text/event-stream");
295        builder = apply_credential(builder, &self.config.credential);
296        for (key, value) in extra_headers {
297            builder = builder.header(*key, *value);
298        }
299        if let Some(value) = body {
300            builder = builder.json(value);
301        }
302        let response = builder
303            .send()
304            .await
305            .map_err(|error| SdkError::Transport(error.to_string()))?;
306        let status = response.status();
307        if !status.is_success() {
308            let bytes = response
309                .bytes()
310                .await
311                .map_err(|error| SdkError::Transport(error.to_string()))?;
312            return Err(map_error_body(status, &bytes));
313        }
314        let content_type = response
315            .headers()
316            .get(header::CONTENT_TYPE)
317            .and_then(|value| value.to_str().ok())
318            .unwrap_or_default();
319        if !content_type
320            .split(';')
321            .next()
322            .is_some_and(|value| value.trim().eq_ignore_ascii_case("text/event-stream"))
323        {
324            return Err(SdkError::Decode(format!(
325                "expected text/event-stream response, got {content_type:?}"
326            )));
327        }
328
329        let mut chunks = response.bytes_stream();
330        Ok(Box::pin(async_stream::stream! {
331            let mut pending = Vec::<u8>::new();
332            while let Some(chunk) = chunks.next().await {
333                let chunk = match chunk {
334                    Ok(chunk) => chunk,
335                    Err(error) => {
336                        yield Err(SdkError::Transport(error.to_string()));
337                        return;
338                    }
339                };
340                pending.extend_from_slice(&chunk);
341                if pending.len() > MAX_EVENT_BYTES {
342                    yield Err(SdkError::Decode(format!(
343                        "SSE event exceeds {MAX_EVENT_BYTES} bytes"
344                    )));
345                    return;
346                }
347                while let Some((frame_end, delimiter_len)) = find_sse_frame_end(&pending) {
348                    let frame = pending.drain(..frame_end).collect::<Vec<_>>();
349                    pending.drain(..delimiter_len);
350                    let data = match sse_data_payload(&frame) {
351                        Ok(Some(data)) => data,
352                        Ok(None) => continue,
353                        Err(error) => {
354                            yield Err(error);
355                            return;
356                        }
357                    };
358                    match serde_json::from_slice::<T>(&data) {
359                        Ok(value) => yield Ok(value),
360                        Err(error) => {
361                            yield Err(SdkError::Decode(format!("invalid SSE ProtoJSON payload: {error}")));
362                            return;
363                        }
364                    }
365                }
366            }
367            if !pending.iter().all(u8::is_ascii_whitespace) {
368                yield Err(SdkError::Decode("SSE stream ended with an incomplete event".into()));
369            }
370        }))
371    }
372
373
374    /// Authenticated raw request returning HTTP status and JSON `Value` (or null body).
375    ///
376    /// Used by the Management `api` escape hatch (`sylphx api METHOD path`) so any
377    /// REST route on the Management plane is reachable without a typed stub module.
378    pub async fn raw_request(
379        &self,
380        method: Method,
381        path: &str,
382        body: Option<&serde_json::Value>,
383        extra_headers: &[(&str, &str)],
384    ) -> Result<(u16, serde_json::Value), SdkError> {
385        let url = join_url(&self.config.base_url, path)?;
386        let mut attempt = 0u32;
387        loop {
388            attempt += 1;
389            let mut builder = self.client.request(method.clone(), url.clone());
390            builder = apply_credential(builder, &self.config.credential);
391            for (k, v) in extra_headers {
392                builder = builder.header(*k, *v);
393            }
394            if let Some(b) = body {
395                builder = builder.json(b);
396            }
397            let response = builder
398                .send()
399                .await
400                .map_err(|e| SdkError::Transport(e.to_string()))?;
401            let status = response.status();
402            let bytes = response
403                .bytes()
404                .await
405                .map_err(|e| SdkError::Transport(e.to_string()))?;
406
407            if status.is_success() {
408                if bytes.is_empty() {
409                    return Ok((status.as_u16(), serde_json::Value::Null));
410                }
411                let val: serde_json::Value = serde_json::from_slice(&bytes).map_err(|e| {
412                    SdkError::Decode(format!("{e}; body={}", String::from_utf8_lossy(&bytes)))
413                })?;
414                return Ok((status.as_u16(), val));
415            }
416
417            let api_err = map_error_body(status, &bytes);
418            if attempt < self.config.retry.max_attempts && is_retryable(status) {
419                let delay = self.config.retry.base_delay * attempt;
420                tokio::time::sleep(delay).await;
421                continue;
422            }
423            return Err(api_err);
424        }
425    }
426
427    /// Authenticated raw request returning status + response bytes (for object put/get).
428    pub async fn raw_bytes_request(
429        &self,
430        method: Method,
431        path: &str,
432        body: Option<&[u8]>,
433        extra_headers: &[(&str, &str)],
434    ) -> Result<(u16, Vec<u8>), SdkError> {
435        let url = join_url(&self.config.base_url, path)?;
436        let mut attempt = 0u32;
437        loop {
438            attempt += 1;
439            let mut builder = self.client.request(method.clone(), url.clone());
440            builder = apply_credential(builder, &self.config.credential);
441            for (k, v) in extra_headers {
442                builder = builder.header(*k, *v);
443            }
444            if let Some(b) = body {
445                builder = builder.body(b.to_vec());
446            }
447            let response = builder
448                .send()
449                .await
450                .map_err(|e| SdkError::Transport(e.to_string()))?;
451            let status = response.status();
452            let bytes = response
453                .bytes()
454                .await
455                .map_err(|e| SdkError::Transport(e.to_string()))?;
456
457            if status.is_success() {
458                return Ok((status.as_u16(), bytes.to_vec()));
459            }
460
461            let api_err = map_error_body(status, &bytes);
462            if attempt < self.config.retry.max_attempts && is_retryable(status) {
463                let delay = self.config.retry.base_delay * attempt;
464                tokio::time::sleep(delay).await;
465                continue;
466            }
467            return Err(api_err);
468        }
469    }
470
471    /// GET helper.
472    pub async fn get_json<T: DeserializeOwned>(
473        &self,
474        path: &str,
475        extra_headers: &[(&str, &str)],
476    ) -> Result<T, SdkError> {
477        self.request_json::<(), T>(Method::GET, path, None, extra_headers)
478            .await
479    }
480
481
482    /// GET helper with query string pairs (`pageToken`, `pageSize`, …).
483    pub async fn get_json_query<T: DeserializeOwned>(
484        &self,
485        path: &str,
486        query: &[(&str, String)],
487        extra_headers: &[(&str, &str)],
488    ) -> Result<T, SdkError> {
489        let path = if query.is_empty() {
490            path.to_string()
491        } else {
492            let mut qs = String::new();
493            for (i, (k, v)) in query.iter().enumerate() {
494                if i > 0 {
495                    qs.push('&');
496                }
497                qs.push_str(&urlencoding_encode(k));
498                qs.push('=');
499                qs.push_str(&urlencoding_encode(v));
500            }
501            if path.contains('?') {
502                format!("{path}&{qs}")
503            } else {
504                format!("{path}?{qs}")
505            }
506        };
507        self.request_json::<(), T>(Method::GET, &path, None, extra_headers)
508            .await
509    }
510
511    /// POST helper.
512    pub async fn post_json<B: Serialize, T: DeserializeOwned>(
513        &self,
514        path: &str,
515        body: &B,
516        extra_headers: &[(&str, &str)],
517    ) -> Result<T, SdkError> {
518        self.request_json(Method::POST, path, Some(body), extra_headers)
519            .await
520    }
521
522    /// PUT helper.
523    pub async fn put_json<B: Serialize, T: DeserializeOwned>(
524        &self,
525        path: &str,
526        body: &B,
527        extra_headers: &[(&str, &str)],
528    ) -> Result<T, SdkError> {
529        self.request_json(Method::PUT, path, Some(body), extra_headers)
530            .await
531    }
532
533    /// DELETE helper.
534    pub async fn delete_json<T: DeserializeOwned>(
535        &self,
536        path: &str,
537        extra_headers: &[(&str, &str)],
538    ) -> Result<T, SdkError> {
539        self.request_json::<(), T>(Method::DELETE, path, None, extra_headers)
540            .await
541    }
542}
543
544fn find_sse_frame_end(bytes: &[u8]) -> Option<(usize, usize)> {
545    bytes
546        .windows(2)
547        .position(|window| window == b"\n\n")
548        .map(|index| (index, 2))
549        .or_else(|| {
550            bytes
551                .windows(4)
552                .position(|window| window == b"\r\n\r\n")
553                .map(|index| (index, 4))
554        })
555}
556
557fn sse_data_payload(frame: &[u8]) -> Result<Option<Vec<u8>>, SdkError> {
558    let text = std::str::from_utf8(frame)
559        .map_err(|error| SdkError::Decode(format!("SSE event is not UTF-8: {error}")))?;
560    let mut data = Vec::<&str>::new();
561    for line in text.lines() {
562        let line = line.strip_suffix('\r').unwrap_or(line);
563        if let Some(value) = line.strip_prefix("data:") {
564            data.push(value.strip_prefix(' ').unwrap_or(value));
565        }
566    }
567    if data.is_empty() {
568        return Ok(None);
569    }
570    Ok(Some(data.join("\n").into_bytes()))
571}
572
573fn apply_credential(
574    builder: reqwest::RequestBuilder,
575    credential: &Credential,
576) -> reqwest::RequestBuilder {
577    match credential {
578        Credential::Bearer(token) => builder.bearer_auth(token),
579        Credential::AppSecret(key) => builder.header("x-app-secret", key),
580    }
581}
582
583fn join_url(base: &str, path: &str) -> Result<Url, SdkError> {
584    let base = base.trim_end_matches('/');
585    let path = if path.starts_with('/') {
586        path.to_string()
587    } else {
588        format!("/{path}")
589    };
590    Url::parse(&format!("{base}{path}")).map_err(|e| SdkError::InvalidUrl(e.to_string()))
591}
592
593fn urlencoding_encode(s: &str) -> String {
594    let mut out = String::with_capacity(s.len());
595    for b in s.bytes() {
596        match b {
597            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(b as char),
598            _ => out.push_str(&format!("%{b:02X}")),
599        }
600    }
601    out
602}
603
604fn is_retryable(status: StatusCode) -> bool {
605    status == StatusCode::REQUEST_TIMEOUT
606        || status == StatusCode::TOO_MANY_REQUESTS
607        || status.is_server_error()
608}
609
610/// Remove JSON `null` values from objects (recursively).
611///
612/// Management live rows often serialize optional repeated fields as `null`
613/// rather than `[]` or omitted. Prost/pbjson codecs reject that shape for
614/// repeated fields; dropping null keys restores ProtoJSON-compatible payloads
615/// without losing real data.
616pub fn strip_json_nulls(value: &mut serde_json::Value) {
617    match value {
618        serde_json::Value::Object(map) => {
619            map.retain(|_, v| !v.is_null());
620            for v in map.values_mut() {
621                strip_json_nulls(v);
622            }
623        }
624        serde_json::Value::Array(items) => {
625            for item in items {
626                strip_json_nulls(item);
627            }
628        }
629        _ => {}
630    }
631}
632
633fn map_error_body(status: StatusCode, bytes: &[u8]) -> SdkError {
634    if let Ok(env) = serde_json::from_slice::<ErrorEnvelope>(bytes) {
635        if let Some(detail) = env.error.into_option() {
636            let message = detail
637                .status
638                .into_option()
639                .map(|status| status.message)
640                .unwrap_or_else(|| detail.code.clone());
641            return SdkError::Api {
642                status: status.as_u16(),
643                code: detail.code,
644                message,
645                body: None,
646            };
647        }
648    }
649    // Agent Computer (and similar) returns top-level ProtoJSON error detail:
650    // { "code": "AGENT_COMPUTER_ERROR_CODE_…", "message": "…", "recovery": "…", … }
651    // rather than the generic Management envelope `{ "error": { code, message } }`.
652    if let Ok(value) = serde_json::from_slice::<serde_json::Value>(bytes) {
653        if let Some(obj) = value.as_object() {
654            if let (Some(code), Some(message)) = (
655                obj.get("code").and_then(|v| v.as_str()),
656                obj.get("message").and_then(|v| v.as_str()),
657            ) {
658                if code.starts_with("AGENT_COMPUTER_ERROR_CODE_")
659                    || obj.contains_key("staleInteraction")
660                    || obj.contains_key("staleLeaseVersion")
661                    || obj.contains_key("recovery")
662                {
663                    return SdkError::Api {
664                        status: status.as_u16(),
665                        code: code.to_string(),
666                        message: message.to_string(),
667                        body: Some(value),
668                    };
669                }
670            }
671        }
672    }
673    // Fallback: raw body
674    SdkError::Api {
675        status: status.as_u16(),
676        code: status_to_code(status).into(),
677        message: String::from_utf8_lossy(bytes).into_owned(),
678        body: None,
679    }
680}
681
682fn status_to_code(status: StatusCode) -> &'static str {
683    match status.as_u16() {
684        400 => "bad_request",
685        401 => "unauthenticated",
686        403 => "permission_denied",
687        404 => "not_found",
688        409 => "conflict",
689        429 => "rate_limited",
690        _ if status.is_server_error() => "internal",
691        _ => "unknown",
692    }
693}
694
695/// SDK-level errors.
696#[derive(Debug, Error)]
697pub enum SdkError {
698    /// Invalid credential configuration.
699    #[error("invalid credential: {0}")]
700    InvalidCredential(String),
701    /// Invalid URL construction.
702    #[error("invalid url: {0}")]
703    InvalidUrl(String),
704    /// Invalid Sylphx connection URL (`sylphx://…`) — dual-oracle of TS
705    /// `InvalidConnectionUrlError`.
706    #[error("invalid connection url: {0}")]
707    InvalidConnectionUrl(String),
708    /// HTTP transport failure.
709    #[error("transport: {0}")]
710    Transport(String),
711    /// Request encoding or generated HTTP projection failure.
712    #[error("encode: {0}")]
713    Encode(String),
714    /// Successful HTTP but body decode failed.
715    #[error("decode: {0}")]
716    Decode(String),
717    /// API error envelope or status mapping.
718    #[error("api {status}: {code}: {message}")]
719    Api {
720        /// HTTP status code.
721        status: u16,
722        /// Stable error code.
723        code: String,
724        /// Human message.
725        message: String,
726        /// Full structured non-2xx body when the server returns a top-level
727        /// ProtoJSON error detail (Agent Computer `AgentComputerErrorDetail`).
728        body: Option<serde_json::Value>,
729    },
730}
731
732impl SdkError {
733    /// Machine error code when this is an API error.
734    pub fn code(&self) -> Option<&str> {
735        match self {
736            Self::Api { code, .. } => Some(code),
737            _ => None,
738        }
739    }
740
741    /// HTTP status when this is an API error.
742    pub fn status(&self) -> Option<u16> {
743        match self {
744            Self::Api { status, .. } => Some(*status),
745            _ => None,
746        }
747    }
748
749    /// Structured error body when present (Agent Computer error detail).
750    pub fn body(&self) -> Option<&serde_json::Value> {
751        match self {
752            Self::Api { body, .. } => body.as_ref(),
753            _ => None,
754        }
755    }
756}
757
758/// Build Authorization / x-app-secret header pair for inspection/tests.
759pub fn auth_header_pair(credential: &Credential) -> (header::HeaderName, String) {
760    match credential {
761        Credential::Bearer(token) => (header::AUTHORIZATION, format!("Bearer {token}")),
762        Credential::AppSecret(key) => (
763            header::HeaderName::from_static("x-app-secret"),
764            key.clone(),
765        ),
766    }
767}
768
769#[cfg(test)]
770mod tests {
771    use super::*;
772    use axum::routing::get;
773    use axum::{Json, Router};
774    use futures_util::StreamExt;
775
776    #[test]
777    fn normalize_management_base_url_appends_v1_for_host_only() {
778        assert_eq!(
779            normalize_management_base_url("https://api.sylphx.com"),
780            "https://api.sylphx.com/v1"
781        );
782        assert_eq!(
783            normalize_management_base_url("https://api.sylphx.com/"),
784            "https://api.sylphx.com/v1"
785        );
786        assert_eq!(
787            normalize_management_base_url("https://api.sylphx.com/v1"),
788            "https://api.sylphx.com/v1"
789        );
790        assert_eq!(
791            normalize_management_base_url("https://api.sylphx.com/v1/"),
792            "https://api.sylphx.com/v1"
793        );
794        assert_eq!(normalize_management_base_url(""), DEFAULT_MANAGEMENT_BASE_URL);
795    }
796
797    #[test]
798    fn baas_base_url_embeds_slug() {
799        assert_eq!(PLATFORM_CONSOLE_SLUG, "keen-wave-x3m9p2");
800        assert_eq!(
801            baas_base_url(PLATFORM_CONSOLE_SLUG),
802            "https://keen-wave-x3m9p2.api.sylphx.com/v1"
803        );
804        assert_eq!(
805            platform_console_baas_base_url(),
806            "https://keen-wave-x3m9p2.api.sylphx.com/v1"
807        );
808        assert_eq!(
809            baas_base_url("keen-wave-x3m9p2"),
810            "https://keen-wave-x3m9p2.api.sylphx.com/v1"
811        );
812    }
813
814    #[test]
815    fn bearer_rejects_empty() {
816        assert!(Credential::bearer("").is_err());
817        assert!(Credential::bearer("  ").is_err());
818    }
819
820    #[test]
821    fn app_secret_requires_prefix() {
822        assert!(Credential::app_secret("nope").is_err());
823        assert!(Credential::app_secret("sk_test_abc").is_ok());
824        assert!(Credential::app_secret("pk_live_abc").is_ok());
825    }
826
827    #[test]
828    fn auth_header_bearer_format() {
829        let cred = Credential::bearer("svc_test").unwrap();
830        let (name, value) = auth_header_pair(&cred);
831        assert_eq!(name, header::AUTHORIZATION);
832        assert_eq!(value, "Bearer svc_test");
833    }
834
835    async fn spawn_mini(routes: Router) -> (String, tokio::sync::oneshot::Sender<()>) {
836        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
837        let addr = listener.local_addr().unwrap();
838        let (tx, rx) = tokio::sync::oneshot::channel::<()>();
839        tokio::spawn(async move {
840            axum::serve(listener, routes)
841                .with_graceful_shutdown(async {
842                    let _ = rx.await;
843                })
844                .await
845                .ok();
846        });
847        tokio::task::yield_now().await;
848        (format!("http://{addr}/v1"), tx)
849    }
850
851    #[tokio::test]
852    async fn maps_error_envelope_from_server() {
853        let app = Router::new().route(
854            "/v1/boom",
855            get(|| async {
856                (
857                    axum::http::StatusCode::NOT_FOUND,
858                    Json(serde_json::json!({
859                        "error": { "message": "missing", "code": "not_found" }
860                    })),
861                )
862            }),
863        );
864        let (base, shutdown) = spawn_mini(app).await;
865        let transport = Transport::new(TransportConfig {
866            base_url: base,
867            credential: Credential::bearer("t").unwrap(),
868            timeout: Duration::from_secs(5),
869            retry: RetryConfig {
870                max_attempts: 1,
871                base_delay: Duration::from_millis(1),
872            },
873        })
874        .unwrap();
875
876        let err = transport
877            .get_json::<serde_json::Value>("/boom", &[])
878            .await
879            .unwrap_err();
880        assert_eq!(err.status(), Some(404));
881        assert_eq!(err.code(), Some("not_found"));
882        let _ = shutdown.send(());
883    }
884
885    #[tokio::test]
886    async fn decodes_success_json() {
887        let app = Router::new().route(
888            "/v1/ok",
889            get(|| async { Json(serde_json::json!({ "status": "ok" })) }),
890        );
891        let (base, shutdown) = spawn_mini(app).await;
892        let transport = Transport::new(TransportConfig {
893            base_url: base,
894            credential: Credential::bearer("t").unwrap(),
895            timeout: Duration::from_secs(5),
896            retry: RetryConfig {
897                max_attempts: 1,
898                base_delay: Duration::from_millis(1),
899            },
900        })
901        .unwrap();
902
903        let v: serde_json::Value = transport.get_json("/ok", &[]).await.unwrap();
904        assert_eq!(v["status"], "ok");
905        let _ = shutdown.send(());
906    }
907
908    #[tokio::test]
909    async fn decodes_backpressure_aware_sse_events() {
910        let app = Router::new().route(
911            "/v1/events",
912            get(|| async {
913                (
914                    [(axum::http::header::CONTENT_TYPE, "text/event-stream")],
915                    "id: 7\ndata: {\"status\":\"ready\"}\n\n",
916                )
917            }),
918        );
919        let (base, shutdown) = spawn_mini(app).await;
920        let transport = Transport::new(TransportConfig {
921            base_url: base,
922            credential: Credential::bearer("t").unwrap(),
923            timeout: Duration::from_secs(5),
924            retry: RetryConfig {
925                max_attempts: 1,
926                base_delay: Duration::from_millis(1),
927            },
928        })
929        .unwrap();
930
931        let mut events = transport
932            .request_sse::<(), serde_json::Value>(Method::GET, "/events", None, &[])
933            .await
934            .unwrap();
935        let event = events.next().await.unwrap().unwrap();
936        assert_eq!(event["status"], "ready");
937        assert!(events.next().await.is_none());
938        let _ = shutdown.send(());
939    }
940
941    /// Shipped `TransportConfig.timeout` must abort hanging peers via reqwest.
942    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
943    async fn request_timeout_is_honored_on_hanging_peer() {
944        // Accept TCP but never complete an HTTP response — client must fail on timeout.
945        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
946        let addr = listener.local_addr().unwrap();
947        let accept = tokio::spawn(async move {
948            if let Ok((mut sock, _)) = listener.accept().await {
949                use tokio::io::AsyncReadExt;
950                let mut buf = [0u8; 64];
951                let _ = sock.read(&mut buf).await;
952                tokio::time::sleep(Duration::from_secs(30)).await;
953            }
954        });
955
956        let transport = Transport::new(TransportConfig {
957            base_url: format!("http://{addr}/v1"),
958            credential: Credential::bearer("t").unwrap(),
959            timeout: Duration::from_millis(80),
960            retry: RetryConfig {
961                max_attempts: 1,
962                base_delay: Duration::from_millis(1),
963            },
964        })
965        .unwrap();
966
967        let started = std::time::Instant::now();
968        let err = transport
969            .get_json::<serde_json::Value>("/hang", &[])
970            .await
971            .unwrap_err();
972        let elapsed = started.elapsed();
973        assert!(
974            matches!(err, SdkError::Transport(_)),
975            "expected transport timeout error, got {err:?}"
976        );
977        assert!(
978            elapsed < Duration::from_millis(500),
979            "timeout not honored: elapsed={elapsed:?}"
980        );
981        accept.abort();
982    }
983
984    #[test]
985    fn agent_computer_top_level_error_detail_preserves_code_and_body() {
986        let body = br#"{"code":"AGENT_COMPUTER_ERROR_CODE_STALE_GEOMETRY","message":"geometry stale","recovery":"AGENT_COMPUTER_REQUEST_RECOVERY_DIRECTIVE_REOBSERVE","staleInteraction":{"suppliedLeaseEpoch":"1","currentLeaseEpoch":"1","suppliedObservationRevision":"2","currentObservationRevision":"3","effectAttempted":false}}"#;
987        let err = map_error_body(reqwest::StatusCode::CONFLICT, body);
988        match err {
989            SdkError::Api { status, code, message, body } => {
990                assert_eq!(status, 409);
991                assert_eq!(code, "AGENT_COMPUTER_ERROR_CODE_STALE_GEOMETRY");
992                assert_eq!(message, "geometry stale");
993                let detail = body.expect("structured body");
994                assert_eq!(detail["recovery"], "AGENT_COMPUTER_REQUEST_RECOVERY_DIRECTIVE_REOBSERVE");
995                assert_eq!(detail["staleInteraction"]["effectAttempted"], false);
996                assert_eq!(detail["staleInteraction"]["suppliedObservationRevision"], "2");
997                assert_eq!(detail["staleInteraction"]["currentObservationRevision"], "3");
998            }
999            other => panic!("unexpected {other:?}"),
1000        }
1001    }
1002}