Skip to main content

sylphx_apps_sdk_core/
lib.rs

1//! Shared transport and auth for Sylphx Platform Rust SDKs.
2//!
3//! Wire payloads are owned by `sylphx-apps-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_apps_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, APPS_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_apps_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_apps_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/// Build a leftover `{slug}.api.sylphx.com` BaaS URL. Dest custom-domain
87/// occupancy does not mint this door as a default.
88pub fn baas_base_url(tenant_slug: &str) -> String {
89    format!("https://{tenant_slug}.api.sylphx.com/v1")
90}
91
92/// Credential material for a plane.
93#[derive(Debug, Clone)]
94pub enum Credential {
95    /// Management plane: OAuth JWT or `svc_*` service token as Bearer.
96    Bearer(String),
97    /// BaaS plane: `sk_*` / `pk_*` runtime key via `x-app-secret`.
98    AppSecret(String),
99}
100
101impl Credential {
102    /// Construct a Bearer credential; rejects empty tokens.
103    pub fn bearer(token: impl Into<String>) -> Result<Self, SdkError> {
104        let token = token.into();
105        if token.trim().is_empty() {
106            return Err(SdkError::InvalidCredential(
107                "management token must be non-empty".into(),
108            ));
109        }
110        Ok(Self::Bearer(token))
111    }
112
113    /// Construct an app-secret credential; validates `sk_` / `pk_` prefix.
114    pub fn app_secret(key: impl Into<String>) -> Result<Self, SdkError> {
115        let key = key.into();
116        if !(key.starts_with("sk_") || key.starts_with("pk_")) {
117            return Err(SdkError::InvalidCredential(
118                "BaaS key must start with sk_ or pk_".into(),
119            ));
120        }
121        Ok(Self::AppSecret(key))
122    }
123}
124
125/// Retry policy for transient failures.
126#[derive(Debug, Clone)]
127pub struct RetryConfig {
128    /// Maximum attempts including the first try.
129    pub max_attempts: u32,
130    /// Base delay between retries.
131    pub base_delay: Duration,
132}
133
134impl Default for RetryConfig {
135    fn default() -> Self {
136        Self {
137            max_attempts: 3,
138            base_delay: Duration::from_millis(100),
139        }
140    }
141}
142
143/// Add Apps and well-known Protobuf types to the application's registry.
144///
145/// Compose all product registrations at process startup, then call
146/// `buffa::type_registry::set_type_registry` once. Constructing a transport
147/// never replaces an embedding application's global registry.
148///
149/// ```
150/// let mut registry = buffa::type_registry::TypeRegistry::new();
151/// sylphx_apps_sdk_core::register_wire_types(&mut registry);
152/// // Register any other application-owned message types here.
153/// buffa::type_registry::set_type_registry(registry);
154/// ```
155pub fn register_wire_types(registry: &mut buffa::type_registry::TypeRegistry) {
156    buffa_types::register_wkt_types(registry);
157    sylphx_apps_api_types::register_types(registry);
158}
159
160/// Require a generated Operation result codec before submitting its effect.
161/// Generated SDK methods derive `T` from their descriptor's result type.
162pub fn require_registered_result<T: buffa::MessageName>() -> Result<(), SdkError> {
163    require_registered_type_url(T::TYPE_URL)
164}
165
166fn require_registered_type_url(type_url: &str) -> Result<(), SdkError> {
167    let registered = buffa::any_registry::with_any_registry(|registry| {
168        registry.and_then(|registry| registry.lookup(type_url)).is_some()
169    });
170    if registered { return Ok(()); }
171    Err(SdkError::Decode(format!(
172        "Operation result codec {type_url} is unavailable; compose sylphx_apps_sdk_core::register_wire_types into the application's Buffa TypeRegistry and install it once at startup"
173    )))
174}
175
176fn check_operation_result_registry(value: &serde_json::Value) -> Result<(), SdkError> {
177    if let Some(type_url) = value.pointer("/operation/result/@type").and_then(serde_json::Value::as_str) {
178        require_registered_type_url(type_url)?;
179    }
180    Ok(())
181}
182
183/// Shared HTTP client configuration for one plane endpoint.
184#[derive(Debug, Clone)]
185pub struct TransportConfig {
186    /// Base URL including `/v1` (no trailing slash required).
187    pub base_url: String,
188    /// Plane credential.
189    pub credential: Credential,
190    /// Per-request timeout.
191    pub timeout: Duration,
192    /// Retry policy.
193    pub retry: RetryConfig,
194}
195
196/// Production HTTP transport.
197#[derive(Debug, Clone)]
198pub struct Transport {
199    client: Client,
200    stream_client: Client,
201    config: TransportConfig,
202    organization: Option<String>,
203}
204
205/// Backpressure-aware typed Server-Sent Events response stream.
206pub type SdkEventStream<T> = Pin<Box<dyn Stream<Item = Result<T, SdkError>> + Send>>;
207
208impl Transport {
209    /// Build a transport with a shared reqwest client.
210    pub fn new(config: TransportConfig) -> Result<Self, SdkError> {
211        let client = Client::builder()
212            .timeout(config.timeout)
213            .user_agent(format!(
214                "sylphx-sdk-rust/{} ({CONTRACT_PACKAGE}@{CONTRACT_REVISION})",
215                env!("CARGO_PKG_VERSION")
216            ))
217            .build()
218            .map_err(|e| SdkError::Transport(e.to_string()))?;
219        // Streaming responses must not inherit the unary whole-request timeout:
220        // dropping the returned stream is the cancellation boundary. Connection
221        // establishment remains bounded by the configured timeout.
222        let stream_client = Client::builder()
223            .connect_timeout(config.timeout)
224            .user_agent(format!(
225                "sylphx-sdk-rust/{} ({CONTRACT_PACKAGE}@{CONTRACT_REVISION})",
226                env!("CARGO_PKG_VERSION")
227            ))
228            .build()
229            .map_err(|e| SdkError::Transport(e.to_string()))?;
230        let mut config = config;
231        config.base_url = normalize_management_base_url(&config.base_url);
232        Ok(Self {
233            client,
234            stream_client,
235            config,
236            organization: None,
237        })
238    }
239
240    /// Clone this transport with a request-scoped organization selector.
241    /// Explicit per-request headers retain their precedence.
242    pub fn with_organization(&self, organization: Option<&str>) -> Self {
243        let mut scoped = self.clone();
244        scoped.organization = organization.map(str::to_owned);
245        scoped
246    }
247
248    fn apply_request_context(
249        &self,
250        builder: reqwest::RequestBuilder,
251        extra_headers: &[(&str, &str)],
252    ) -> reqwest::RequestBuilder {
253        let mut builder = apply_credential(builder, &self.config.credential);
254        if !extra_headers.iter().any(|(key, _)| key.eq_ignore_ascii_case("x-preferred-org-id")) {
255            if let Some(organization) = &self.organization {
256                builder = builder.header("x-preferred-org-id", organization);
257            }
258        }
259        builder
260    }
261
262    /// Base URL for this transport.
263    pub fn base_url(&self) -> &str {
264        &self.config.base_url
265    }
266
267    /// Perform a JSON request and decode a successful body as `T`.
268    pub async fn request_json<B: Serialize, T: DeserializeOwned>(
269        &self,
270        method: Method,
271        path: &str,
272        body: Option<&B>,
273        extra_headers: &[(&str, &str)],
274    ) -> Result<T, SdkError> {
275        let url = join_url(&self.config.base_url, path)?;
276        let mut attempt = 0u32;
277        loop {
278            attempt += 1;
279            let mut builder = self.client.request(method.clone(), url.clone());
280            builder = self.apply_request_context(builder, extra_headers);
281            for (k, v) in extra_headers {
282                builder = builder.header(*k, *v);
283            }
284            if let Some(b) = body {
285                builder = builder.json(b);
286            }
287            let response = builder.send().await.map_err(|e| SdkError::Transport(e.to_string()))?;
288            let status = response.status();
289            let bytes = response
290                .bytes()
291                .await
292                .map_err(|e| SdkError::Transport(e.to_string()))?;
293
294            if status.is_success() {
295                if bytes.is_empty() {
296                    // Allow empty 204-style bodies only for unit type consumers via Value.
297                    return serde_json::from_value(serde_json::json!({}))
298                        .map_err(|e| SdkError::Decode(e.to_string()));
299                }
300                // Live Management may emit JSON `null` for optional repeated fields
301                // (e.g. enabledOAuthProviders: null). Protobuf JSON codecs treat
302                // repeated fields as sequences, not null — strip null object keys
303                // so wire types decode cleanly without per-field workarounds.
304                let mut value: serde_json::Value = serde_json::from_slice(&bytes).map_err(|e| {
305                    SdkError::Decode(format!("{e}; body={}", String::from_utf8_lossy(&bytes)))
306                })?;
307                check_operation_result_registry(&value)?;
308                strip_json_nulls(&mut value);
309                return serde_json::from_value(value).map_err(|e| {
310                    SdkError::Decode(format!("{e}; body={}", String::from_utf8_lossy(&bytes)))
311                });
312            }
313
314            let api_err = map_error_body(status, &bytes);
315            if attempt < self.config.retry.max_attempts && is_retryable(status) {
316                let delay = self.config.retry.base_delay * attempt;
317                tokio::time::sleep(delay).await;
318                continue;
319            }
320            return Err(api_err);
321        }
322    }
323
324    /// Perform an authenticated ProtoJSON request and decode a typed SSE stream.
325    ///
326    /// The response body is consumed only as the caller polls the returned
327    /// stream. Dropping it cancels the underlying response. Automatic retries
328    /// stop once a stream is established so resumable cursor semantics remain
329    /// owned by the caller and the descriptor contract.
330    pub async fn request_sse<B, T>(
331        &self,
332        method: Method,
333        path: &str,
334        body: Option<&B>,
335        extra_headers: &[(&str, &str)],
336    ) -> Result<SdkEventStream<T>, SdkError>
337    where
338        B: Serialize + ?Sized,
339        T: DeserializeOwned + Send + 'static,
340    {
341        const MAX_EVENT_BYTES: usize = 4 * 1024 * 1024;
342
343        let url = join_url(&self.config.base_url, path)?;
344        let mut builder = self
345            .stream_client
346            .request(method, url)
347            .header(header::ACCEPT, "text/event-stream");
348        builder = self.apply_request_context(builder, extra_headers);
349        for (key, value) in extra_headers {
350            builder = builder.header(*key, *value);
351        }
352        if let Some(value) = body {
353            builder = builder.json(value);
354        }
355        let response = builder
356            .send()
357            .await
358            .map_err(|error| SdkError::Transport(error.to_string()))?;
359        let status = response.status();
360        if !status.is_success() {
361            let bytes = response
362                .bytes()
363                .await
364                .map_err(|error| SdkError::Transport(error.to_string()))?;
365            return Err(map_error_body(status, &bytes));
366        }
367        let content_type = response
368            .headers()
369            .get(header::CONTENT_TYPE)
370            .and_then(|value| value.to_str().ok())
371            .unwrap_or_default();
372        if !content_type
373            .split(';')
374            .next()
375            .is_some_and(|value| value.trim().eq_ignore_ascii_case("text/event-stream"))
376        {
377            return Err(SdkError::Decode(format!(
378                "expected text/event-stream response, got {content_type:?}"
379            )));
380        }
381
382        let mut chunks = response.bytes_stream();
383        Ok(Box::pin(async_stream::stream! {
384            let mut pending = Vec::<u8>::new();
385            while let Some(chunk) = chunks.next().await {
386                let chunk = match chunk {
387                    Ok(chunk) => chunk,
388                    Err(error) => {
389                        yield Err(SdkError::Transport(error.to_string()));
390                        return;
391                    }
392                };
393                pending.extend_from_slice(&chunk);
394                if pending.len() > MAX_EVENT_BYTES {
395                    yield Err(SdkError::Decode(format!(
396                        "SSE event exceeds {MAX_EVENT_BYTES} bytes"
397                    )));
398                    return;
399                }
400                while let Some((frame_end, delimiter_len)) = find_sse_frame_end(&pending) {
401                    let frame = pending.drain(..frame_end).collect::<Vec<_>>();
402                    pending.drain(..delimiter_len);
403                    let data = match sse_data_payload(&frame) {
404                        Ok(Some(data)) => data,
405                        Ok(None) => continue,
406                        Err(error) => {
407                            yield Err(error);
408                            return;
409                        }
410                    };
411                    match serde_json::from_slice::<T>(&data) {
412                        Ok(value) => yield Ok(value),
413                        Err(error) => {
414                            yield Err(SdkError::Decode(format!("invalid SSE ProtoJSON payload: {error}")));
415                            return;
416                        }
417                    }
418                }
419            }
420            if !pending.iter().all(u8::is_ascii_whitespace) {
421                yield Err(SdkError::Decode("SSE stream ended with an incomplete event".into()));
422            }
423        }))
424    }
425
426
427    /// Authenticated raw request returning HTTP status and JSON `Value` (or null body).
428    ///
429    /// Used by the Management `api` escape hatch (`sylphx api METHOD path`) so any
430    /// REST route on the Management plane is reachable without a typed stub module.
431    pub async fn raw_request(
432        &self,
433        method: Method,
434        path: &str,
435        body: Option<&serde_json::Value>,
436        extra_headers: &[(&str, &str)],
437    ) -> Result<(u16, serde_json::Value), SdkError> {
438        let url = join_url(&self.config.base_url, path)?;
439        let mut attempt = 0u32;
440        loop {
441            attempt += 1;
442            let mut builder = self.client.request(method.clone(), url.clone());
443            builder = self.apply_request_context(builder, extra_headers);
444            for (k, v) in extra_headers {
445                builder = builder.header(*k, *v);
446            }
447            if let Some(b) = body {
448                builder = builder.json(b);
449            }
450            let response = builder
451                .send()
452                .await
453                .map_err(|e| SdkError::Transport(e.to_string()))?;
454            let status = response.status();
455            let bytes = response
456                .bytes()
457                .await
458                .map_err(|e| SdkError::Transport(e.to_string()))?;
459
460            if status.is_success() {
461                if bytes.is_empty() {
462                    return Ok((status.as_u16(), serde_json::Value::Null));
463                }
464                let val: serde_json::Value = serde_json::from_slice(&bytes).map_err(|e| {
465                    SdkError::Decode(format!("{e}; body={}", String::from_utf8_lossy(&bytes)))
466                })?;
467                return Ok((status.as_u16(), val));
468            }
469
470            let api_err = map_error_body(status, &bytes);
471            if attempt < self.config.retry.max_attempts && is_retryable(status) {
472                let delay = self.config.retry.base_delay * attempt;
473                tokio::time::sleep(delay).await;
474                continue;
475            }
476            return Err(api_err);
477        }
478    }
479
480    /// Authenticated raw request returning status + response bytes (for object put/get).
481    pub async fn raw_bytes_request(
482        &self,
483        method: Method,
484        path: &str,
485        body: Option<&[u8]>,
486        extra_headers: &[(&str, &str)],
487    ) -> Result<(u16, Vec<u8>), SdkError> {
488        let url = join_url(&self.config.base_url, path)?;
489        let mut attempt = 0u32;
490        loop {
491            attempt += 1;
492            let mut builder = self.client.request(method.clone(), url.clone());
493            builder = self.apply_request_context(builder, extra_headers);
494            for (k, v) in extra_headers {
495                builder = builder.header(*k, *v);
496            }
497            if let Some(b) = body {
498                builder = builder.body(b.to_vec());
499            }
500            let response = builder
501                .send()
502                .await
503                .map_err(|e| SdkError::Transport(e.to_string()))?;
504            let status = response.status();
505            let bytes = response
506                .bytes()
507                .await
508                .map_err(|e| SdkError::Transport(e.to_string()))?;
509
510            if status.is_success() {
511                return Ok((status.as_u16(), bytes.to_vec()));
512            }
513
514            let api_err = map_error_body(status, &bytes);
515            if attempt < self.config.retry.max_attempts && is_retryable(status) {
516                let delay = self.config.retry.base_delay * attempt;
517                tokio::time::sleep(delay).await;
518                continue;
519            }
520            return Err(api_err);
521        }
522    }
523
524    /// GET helper.
525    pub async fn get_json<T: DeserializeOwned>(
526        &self,
527        path: &str,
528        extra_headers: &[(&str, &str)],
529    ) -> Result<T, SdkError> {
530        self.request_json::<(), T>(Method::GET, path, None, extra_headers)
531            .await
532    }
533
534
535    /// GET helper with query string pairs (`pageToken`, `pageSize`, …).
536    pub async fn get_json_query<T: DeserializeOwned>(
537        &self,
538        path: &str,
539        query: &[(&str, String)],
540        extra_headers: &[(&str, &str)],
541    ) -> Result<T, SdkError> {
542        let path = if query.is_empty() {
543            path.to_string()
544        } else {
545            let mut qs = String::new();
546            for (i, (k, v)) in query.iter().enumerate() {
547                if i > 0 {
548                    qs.push('&');
549                }
550                qs.push_str(&urlencoding_encode(k));
551                qs.push('=');
552                qs.push_str(&urlencoding_encode(v));
553            }
554            if path.contains('?') {
555                format!("{path}&{qs}")
556            } else {
557                format!("{path}?{qs}")
558            }
559        };
560        self.request_json::<(), T>(Method::GET, &path, None, extra_headers)
561            .await
562    }
563
564    /// POST helper.
565    pub async fn post_json<B: Serialize, T: DeserializeOwned>(
566        &self,
567        path: &str,
568        body: &B,
569        extra_headers: &[(&str, &str)],
570    ) -> Result<T, SdkError> {
571        self.request_json(Method::POST, path, Some(body), extra_headers)
572            .await
573    }
574
575    /// PUT helper.
576    pub async fn put_json<B: Serialize, T: DeserializeOwned>(
577        &self,
578        path: &str,
579        body: &B,
580        extra_headers: &[(&str, &str)],
581    ) -> Result<T, SdkError> {
582        self.request_json(Method::PUT, path, Some(body), extra_headers)
583            .await
584    }
585
586    /// DELETE helper.
587    pub async fn delete_json<T: DeserializeOwned>(
588        &self,
589        path: &str,
590        extra_headers: &[(&str, &str)],
591    ) -> Result<T, SdkError> {
592        self.request_json::<(), T>(Method::DELETE, path, None, extra_headers)
593            .await
594    }
595}
596
597fn find_sse_frame_end(bytes: &[u8]) -> Option<(usize, usize)> {
598    bytes
599        .windows(2)
600        .position(|window| window == b"\n\n")
601        .map(|index| (index, 2))
602        .or_else(|| {
603            bytes
604                .windows(4)
605                .position(|window| window == b"\r\n\r\n")
606                .map(|index| (index, 4))
607        })
608}
609
610fn sse_data_payload(frame: &[u8]) -> Result<Option<Vec<u8>>, SdkError> {
611    let text = std::str::from_utf8(frame)
612        .map_err(|error| SdkError::Decode(format!("SSE event is not UTF-8: {error}")))?;
613    let mut data = Vec::<&str>::new();
614    for line in text.lines() {
615        let line = line.strip_suffix('\r').unwrap_or(line);
616        if let Some(value) = line.strip_prefix("data:") {
617            data.push(value.strip_prefix(' ').unwrap_or(value));
618        }
619    }
620    if data.is_empty() {
621        return Ok(None);
622    }
623    Ok(Some(data.join("\n").into_bytes()))
624}
625
626fn apply_credential(
627    builder: reqwest::RequestBuilder,
628    credential: &Credential,
629) -> reqwest::RequestBuilder {
630    match credential {
631        Credential::Bearer(token) => builder.bearer_auth(token),
632        Credential::AppSecret(key) => builder.header("x-app-secret", key),
633    }
634}
635
636fn join_url(base: &str, path: &str) -> Result<Url, SdkError> {
637    let base = base.trim_end_matches('/');
638    let path = if path.starts_with('/') {
639        path.to_string()
640    } else {
641        format!("/{path}")
642    };
643    Url::parse(&format!("{base}{path}")).map_err(|e| SdkError::InvalidUrl(e.to_string()))
644}
645
646fn urlencoding_encode(s: &str) -> String {
647    let mut out = String::with_capacity(s.len());
648    for b in s.bytes() {
649        match b {
650            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(b as char),
651            _ => out.push_str(&format!("%{b:02X}")),
652        }
653    }
654    out
655}
656
657fn is_retryable(status: StatusCode) -> bool {
658    status == StatusCode::REQUEST_TIMEOUT
659        || status == StatusCode::TOO_MANY_REQUESTS
660        || status.is_server_error()
661}
662
663/// Remove JSON `null` values from objects (recursively).
664///
665/// Management live rows often serialize optional repeated fields as `null`
666/// rather than `[]` or omitted. Prost/pbjson codecs reject that shape for
667/// repeated fields; dropping null keys restores ProtoJSON-compatible payloads
668/// without losing real data.
669pub fn strip_json_nulls(value: &mut serde_json::Value) {
670    match value {
671        serde_json::Value::Object(map) => {
672            map.retain(|_, v| !v.is_null());
673            for v in map.values_mut() {
674                strip_json_nulls(v);
675            }
676        }
677        serde_json::Value::Array(items) => {
678            for item in items {
679                strip_json_nulls(item);
680            }
681        }
682        _ => {}
683    }
684}
685
686fn map_error_body(status: StatusCode, bytes: &[u8]) -> SdkError {
687    if let Ok(env) = serde_json::from_slice::<ErrorEnvelope>(bytes) {
688        if let Some(detail) = env.error.into_option() {
689            let message = detail
690                .status
691                .into_option()
692                .map(|status| status.message)
693                .unwrap_or_else(|| detail.code.clone());
694            return SdkError::Api {
695                status: status.as_u16(),
696                code: detail.code,
697                message,
698                body: None,
699            };
700        }
701    }
702    // Agent Computer (and similar) returns top-level ProtoJSON error detail:
703    // { "code": "AGENT_COMPUTER_ERROR_CODE_…", "message": "…", "recovery": "…", … }
704    // rather than the generic Management envelope `{ "error": { code, message } }`.
705    if let Ok(value) = serde_json::from_slice::<serde_json::Value>(bytes) {
706        if let Some(obj) = value.as_object() {
707            if let (Some(code), Some(message)) = (
708                obj.get("code").and_then(|v| v.as_str()),
709                obj.get("message").and_then(|v| v.as_str()),
710            ) {
711                if code.starts_with("DELIVERY_REQUEST_ERROR_CODE_")
712                    || code.starts_with("AGENT_COMPUTER_ERROR_CODE_")
713                    || obj.contains_key("staleInteraction")
714                    || obj.contains_key("staleLeaseVersion")
715                    || obj.contains_key("recovery")
716                {
717                    return SdkError::Api {
718                        status: status.as_u16(),
719                        code: code.to_string(),
720                        message: message.to_string(),
721                        body: Some(value),
722                    };
723                }
724            }
725        }
726    }
727    // Fallback: raw body
728    SdkError::Api {
729        status: status.as_u16(),
730        code: status_to_code(status).into(),
731        message: String::from_utf8_lossy(bytes).into_owned(),
732        body: None,
733    }
734}
735
736fn status_to_code(status: StatusCode) -> &'static str {
737    match status.as_u16() {
738        400 => "bad_request",
739        401 => "unauthenticated",
740        403 => "permission_denied",
741        404 => "not_found",
742        409 => "conflict",
743        429 => "rate_limited",
744        _ if status.is_server_error() => "internal",
745        _ => "unknown",
746    }
747}
748
749/// SDK-level errors.
750#[derive(Debug, Error)]
751pub enum SdkError {
752    /// Invalid credential configuration.
753    #[error("invalid credential: {0}")]
754    InvalidCredential(String),
755    /// Invalid URL construction.
756    #[error("invalid url: {0}")]
757    InvalidUrl(String),
758    /// Invalid Sylphx connection URL (`sylphx://…`) — dual-oracle of TS
759    /// `InvalidConnectionUrlError`.
760    #[error("invalid connection url: {0}")]
761    InvalidConnectionUrl(String),
762    /// HTTP transport failure.
763    #[error("transport: {0}")]
764    Transport(String),
765    /// Request encoding or generated HTTP projection failure.
766    #[error("encode: {0}")]
767    Encode(String),
768    /// Successful HTTP but body decode failed.
769    #[error("decode: {0}")]
770    Decode(String),
771    /// API error envelope or status mapping.
772    #[error("api {status}: {code}: {message}")]
773    Api {
774        /// HTTP status code.
775        status: u16,
776        /// Stable error code.
777        code: String,
778        /// Human message.
779        message: String,
780        /// Full structured non-2xx body when the server returns a top-level
781        /// ProtoJSON error detail (Agent Computer `AgentComputerErrorDetail`).
782        body: Option<serde_json::Value>,
783    },
784}
785
786impl SdkError {
787    /// Machine error code when this is an API error.
788    pub fn code(&self) -> Option<&str> {
789        match self {
790            Self::Api { code, .. } => Some(code),
791            _ => None,
792        }
793    }
794
795    /// HTTP status when this is an API error.
796    pub fn status(&self) -> Option<u16> {
797        match self {
798            Self::Api { status, .. } => Some(*status),
799            _ => None,
800        }
801    }
802
803    /// Structured error body when present (Agent Computer error detail).
804    pub fn body(&self) -> Option<&serde_json::Value> {
805        match self {
806            Self::Api { body, .. } => body.as_ref(),
807            _ => None,
808        }
809    }
810}
811
812/// Build Authorization / x-app-secret header pair for inspection/tests.
813pub fn auth_header_pair(credential: &Credential) -> (header::HeaderName, String) {
814    match credential {
815        Credential::Bearer(token) => (header::AUTHORIZATION, format!("Bearer {token}")),
816        Credential::AppSecret(key) => (
817            header::HeaderName::from_static("x-app-secret"),
818            key.clone(),
819        ),
820    }
821}
822
823#[cfg(test)]
824mod tests {
825    use super::*;
826    use axum::routing::get;
827    use axum::{Json, Router};
828    use futures_util::StreamExt;
829
830    #[test]
831    fn normalize_management_base_url_appends_v1_for_host_only() {
832        assert_eq!(
833            normalize_management_base_url("https://api.sylphx.com"),
834            "https://api.sylphx.com/v1"
835        );
836        assert_eq!(
837            normalize_management_base_url("https://api.sylphx.com/"),
838            "https://api.sylphx.com/v1"
839        );
840        assert_eq!(
841            normalize_management_base_url("https://api.sylphx.com/v1"),
842            "https://api.sylphx.com/v1"
843        );
844        assert_eq!(
845            normalize_management_base_url("https://api.sylphx.com/v1/"),
846            "https://api.sylphx.com/v1"
847        );
848        assert_eq!(normalize_management_base_url(""), DEFAULT_MANAGEMENT_BASE_URL);
849    }
850
851    #[test]
852    fn baas_base_url_embeds_slug() {
853        assert_eq!(
854            baas_base_url("example-project"),
855            "https://example-project.api.sylphx.com/v1"
856        );
857    }
858
859    #[test]
860    fn bearer_rejects_empty() {
861        assert!(Credential::bearer("").is_err());
862        assert!(Credential::bearer("  ").is_err());
863    }
864
865    #[test]
866    fn app_secret_requires_prefix() {
867        assert!(Credential::app_secret("nope").is_err());
868        assert!(Credential::app_secret("sk_test_abc").is_ok());
869        assert!(Credential::app_secret("pk_live_abc").is_ok());
870    }
871
872    #[test]
873    fn auth_header_bearer_format() {
874        let cred = Credential::bearer("svc_test").unwrap();
875        let (name, value) = auth_header_pair(&cred);
876        assert_eq!(name, header::AUTHORIZATION);
877        assert_eq!(value, "Bearer svc_test");
878    }
879
880    async fn spawn_mini(routes: Router) -> (String, tokio::sync::oneshot::Sender<()>) {
881        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
882        let addr = listener.local_addr().unwrap();
883        let (tx, rx) = tokio::sync::oneshot::channel::<()>();
884        tokio::spawn(async move {
885            axum::serve(listener, routes)
886                .with_graceful_shutdown(async {
887                    let _ = rx.await;
888                })
889                .await
890                .ok();
891        });
892        tokio::task::yield_now().await;
893        (format!("http://{addr}/v1"), tx)
894    }
895
896    #[tokio::test]
897    async fn maps_error_envelope_from_server() {
898        let app = Router::new().route(
899            "/v1/boom",
900            get(|| async {
901                (
902                    axum::http::StatusCode::NOT_FOUND,
903                    Json(serde_json::json!({
904                        "error": { "message": "missing", "code": "not_found" }
905                    })),
906                )
907            }),
908        );
909        let (base, shutdown) = spawn_mini(app).await;
910        let transport = Transport::new(TransportConfig {
911            base_url: base,
912            credential: Credential::bearer("t").unwrap(),
913            timeout: Duration::from_secs(5),
914            retry: RetryConfig {
915                max_attempts: 1,
916                base_delay: Duration::from_millis(1),
917            },
918        })
919        .unwrap();
920
921        let err = transport
922            .get_json::<serde_json::Value>("/boom", &[])
923            .await
924            .unwrap_err();
925        assert_eq!(err.status(), Some(404));
926        assert_eq!(err.code(), Some("not_found"));
927        let _ = shutdown.send(());
928    }
929
930    #[tokio::test]
931    async fn decodes_success_json() {
932        let app = Router::new().route(
933            "/v1/ok",
934            get(|| async { Json(serde_json::json!({ "status": "ok" })) }),
935        );
936        let (base, shutdown) = spawn_mini(app).await;
937        let transport = Transport::new(TransportConfig {
938            base_url: base,
939            credential: Credential::bearer("t").unwrap(),
940            timeout: Duration::from_secs(5),
941            retry: RetryConfig {
942                max_attempts: 1,
943                base_delay: Duration::from_millis(1),
944            },
945        })
946        .unwrap();
947
948        let v: serde_json::Value = transport.get_json("/ok", &[]).await.unwrap();
949        assert_eq!(v["status"], "ok");
950        let _ = shutdown.send(());
951    }
952
953    #[tokio::test]
954    async fn decodes_backpressure_aware_sse_events() {
955        let app = Router::new().route(
956            "/v1/events",
957            get(|| async {
958                (
959                    [(axum::http::header::CONTENT_TYPE, "text/event-stream")],
960                    "id: 7\ndata: {\"status\":\"ready\"}\n\n",
961                )
962            }),
963        );
964        let (base, shutdown) = spawn_mini(app).await;
965        let transport = Transport::new(TransportConfig {
966            base_url: base,
967            credential: Credential::bearer("t").unwrap(),
968            timeout: Duration::from_secs(5),
969            retry: RetryConfig {
970                max_attempts: 1,
971                base_delay: Duration::from_millis(1),
972            },
973        })
974        .unwrap();
975
976        let mut events = transport
977            .request_sse::<(), serde_json::Value>(Method::GET, "/events", None, &[])
978            .await
979            .unwrap();
980        let event = events.next().await.unwrap().unwrap();
981        assert_eq!(event["status"], "ready");
982        assert!(events.next().await.is_none());
983        let _ = shutdown.send(());
984    }
985
986    /// Shipped `TransportConfig.timeout` must abort hanging peers via reqwest.
987    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
988    async fn request_timeout_is_honored_on_hanging_peer() {
989        // Accept TCP but never complete an HTTP response — client must fail on timeout.
990        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
991        let addr = listener.local_addr().unwrap();
992        let accept = tokio::spawn(async move {
993            if let Ok((mut sock, _)) = listener.accept().await {
994                use tokio::io::AsyncReadExt;
995                let mut buf = [0u8; 64];
996                let _ = sock.read(&mut buf).await;
997                tokio::time::sleep(Duration::from_secs(30)).await;
998            }
999        });
1000
1001        let transport = Transport::new(TransportConfig {
1002            base_url: format!("http://{addr}/v1"),
1003            credential: Credential::bearer("t").unwrap(),
1004            timeout: Duration::from_millis(80),
1005            retry: RetryConfig {
1006                max_attempts: 1,
1007                base_delay: Duration::from_millis(1),
1008            },
1009        })
1010        .unwrap();
1011
1012        let started = std::time::Instant::now();
1013        let err = transport
1014            .get_json::<serde_json::Value>("/hang", &[])
1015            .await
1016            .unwrap_err();
1017        let elapsed = started.elapsed();
1018        assert!(
1019            matches!(err, SdkError::Transport(_)),
1020            "expected transport timeout error, got {err:?}"
1021        );
1022        assert!(
1023            elapsed < Duration::from_millis(500),
1024            "timeout not honored: elapsed={elapsed:?}"
1025        );
1026        accept.abort();
1027    }
1028
1029    #[test]
1030    fn transport_construction_does_not_install_or_replace_host_registry() {
1031        let before = buffa::any_registry::with_any_registry(|registry| registry.map(|registry| registry as *const _));
1032        let _transport = Transport::new(TransportConfig {
1033            base_url: "http://localhost:3456/v1".into(),
1034            credential: Credential::Bearer("test-token".into()),
1035            timeout: Duration::from_secs(1),
1036            retry: RetryConfig::default(),
1037        }).unwrap();
1038        let after = buffa::any_registry::with_any_registry(|registry| registry.map(|registry| registry as *const _));
1039        assert_eq!(before, after);
1040    }
1041
1042    #[test]
1043    fn unregistered_operation_result_fails_instead_of_losing_inline_fields() {
1044        let response = serde_json::json!({"operation": {"result": {
1045            "@type": "type.googleapis.com/example.UnregisteredResult", "createdId": "resource-1"
1046        }}});
1047        let error = check_operation_result_registry(&response).unwrap_err();
1048        assert!(error.to_string().contains("register_wire_types"));
1049        assert!(error.to_string().contains("example.UnregisteredResult"));
1050    }
1051
1052    #[test]
1053    fn delivery_error_retains_recovery_and_revision() {
1054        let body = br#"{"code":"DELIVERY_REQUEST_ERROR_CODE_REVISION_CONFLICT","message":"Policy changed","field":"expectedPolicyRevision","currentRevision":"revision-2","recoveryAction":"Read policy and review changes","supportedFields":["patch"]}"#;
1055        let error = map_error_body(StatusCode::CONFLICT, body);
1056        assert_eq!(error.status(), Some(409));
1057        assert_eq!(error.code(), Some("DELIVERY_REQUEST_ERROR_CODE_REVISION_CONFLICT"));
1058        let detail = error.body().expect("typed delivery detail");
1059        assert_eq!(detail["currentRevision"], "revision-2");
1060        assert_eq!(detail["recoveryAction"], "Read policy and review changes");
1061        assert_eq!(detail["supportedFields"][0], "patch");
1062    }
1063
1064    #[test]
1065    fn organization_scope_is_immutable_and_explicit_headers_override_it() {
1066        let transport = Transport::new(TransportConfig {
1067            base_url: "http://localhost:3456/v1".into(),
1068            credential: Credential::Bearer("test-token".into()),
1069            timeout: Duration::from_secs(1),
1070            retry: RetryConfig::default(),
1071        }).unwrap();
1072        let scoped = transport.with_organization(Some("org-1"));
1073        let request = scoped.apply_request_context(scoped.client.get("http://localhost"), &[]).build().unwrap();
1074        assert_eq!(request.headers()["x-preferred-org-id"], "org-1");
1075        let original = transport.apply_request_context(transport.client.get("http://localhost"), &[]).build().unwrap();
1076        assert!(!original.headers().contains_key("x-preferred-org-id"));
1077        let overridden = scoped.apply_request_context(scoped.client.get("http://localhost"), &[("X-Preferred-Org-ID", "org-2")]).header("X-Preferred-Org-ID", "org-2").build().unwrap();
1078        assert_eq!(overridden.headers()["x-preferred-org-id"], "org-2");
1079        assert_eq!(overridden.headers().get_all("x-preferred-org-id").iter().count(), 1);
1080        let cleared = scoped.with_organization(None);
1081        assert!(cleared.organization.is_none());
1082    }
1083
1084    #[test]
1085    fn agent_computer_top_level_error_detail_preserves_code_and_body() {
1086        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}}"#;
1087        let err = map_error_body(reqwest::StatusCode::CONFLICT, body);
1088        match err {
1089            SdkError::Api { status, code, message, body } => {
1090                assert_eq!(status, 409);
1091                assert_eq!(code, "AGENT_COMPUTER_ERROR_CODE_STALE_GEOMETRY");
1092                assert_eq!(message, "geometry stale");
1093                let detail = body.expect("structured body");
1094                assert_eq!(detail["recovery"], "AGENT_COMPUTER_REQUEST_RECOVERY_DIRECTIVE_REOBSERVE");
1095                assert_eq!(detail["staleInteraction"]["effectAttempted"], false);
1096                assert_eq!(detail["staleInteraction"]["suppliedObservationRevision"], "2");
1097                assert_eq!(detail["staleInteraction"]["currentObservationRevision"], "3");
1098            }
1099            other => panic!("unexpected {other:?}"),
1100        }
1101    }
1102}