1use std::collections::HashMap;
36use std::env;
37use std::fmt;
38use std::time::Duration;
39
40use reqwest::header::{HeaderMap, HeaderName, HeaderValue, ACCEPT, AUTHORIZATION, RETRY_AFTER};
41use reqwest::{redirect, Client as HttpClient, Method, StatusCode};
42use serde_json::Value;
43
44use crate::error::{ErrorKind, Result, TypeSafeError};
45use crate::questions::{validate_questions, Question};
46use crate::retry::{jitter_seed, RetryPolicy};
47use crate::types::{ListModelsResponse, SetMetadata, SystemOneRequest, SystemOneResponse};
48
49const MAX_RESPONSE_BODY_BYTES: usize = 1024 * 1024;
53
54const PROTECTED_HEADER_NAMES: &[&str] = &[
58 "authorization",
59 "accept",
60 "x-typesafe-sdk",
61 "content-type",
62 "content-length",
63 "transfer-encoding",
64 "host",
65 "connection",
66 "cookie",
67 "proxy-authorization",
68 "proxy-authenticate",
69 "te",
70 "trailer",
71 "upgrade",
72];
73
74const DEFAULT_BASE_URL: &str = "https://api.typesafe.ai";
75const DEFAULT_MODEL: &str = "jev-latest";
76const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
77const SDK_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));
78const SYSTEM_ONE_PATH: &str = "/v1/systemone";
79const MODELS_PATH: &str = "/v1/models";
80const RETRY_AFTER_MS_HEADER: &str = "retry-after-ms";
81const REQUEST_ID_HEADER: &str = "x-typesafe-request-id";
82const MAX_ERROR_BODY_CHARS: usize = 512;
84
85#[derive(Clone)]
92#[non_exhaustive]
93pub struct ClientConfig {
94 pub api_key: String,
99 pub base_url: String,
105 pub default_model: String,
107 pub timeout: Duration,
109 pub retry: RetryPolicy,
111 pub http_client: Option<HttpClient>,
115}
116
117impl Default for ClientConfig {
118 fn default() -> Self {
126 Self {
127 api_key: String::new(),
128 base_url: DEFAULT_BASE_URL.to_string(),
129 default_model: DEFAULT_MODEL.to_string(),
130 timeout: DEFAULT_TIMEOUT,
131 retry: RetryPolicy::default(),
132 http_client: None,
133 }
134 }
135}
136
137impl ClientConfig {
138 #[must_use]
143 pub fn new(api_key: impl Into<String>) -> Self {
144 Self {
145 api_key: api_key.into(),
146 ..Self::default()
147 }
148 }
149
150 #[must_use]
152 pub fn with_api_key(mut self, api_key: impl Into<String>) -> Self {
153 self.api_key = api_key.into();
154 self
155 }
156
157 #[must_use]
159 pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
160 self.base_url = base_url.into();
161 self
162 }
163
164 #[must_use]
166 pub fn with_default_model(mut self, default_model: impl Into<String>) -> Self {
167 self.default_model = default_model.into();
168 self
169 }
170
171 #[must_use]
178 pub fn with_timeout(mut self, timeout: Duration) -> Self {
179 self.timeout = timeout;
180 self
181 }
182
183 #[must_use]
185 pub fn with_retry(mut self, retry: RetryPolicy) -> Self {
186 self.retry = retry;
187 self
188 }
189
190 #[must_use]
200 pub fn with_http_client(mut self, client: HttpClient) -> Self {
201 self.http_client = Some(client);
202 self
203 }
204}
205
206impl fmt::Debug for ClientConfig {
207 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208 f.debug_struct("ClientConfig")
209 .field("api_key", &"<redacted>")
210 .field("base_url", &self.base_url)
211 .field("default_model", &self.default_model)
212 .field("timeout", &self.timeout)
213 .field("retry", &self.retry)
214 .field("http_client", &self.http_client.is_some())
215 .finish()
216 }
217}
218
219#[derive(Clone)]
224#[non_exhaustive]
225pub struct TypeSafeClient {
226 config: ClientConfig,
227 http: HttpClient,
228 auth_header: HeaderValue,
232}
233
234impl fmt::Debug for TypeSafeClient {
235 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
236 f.debug_struct("TypeSafeClient")
237 .field("config", &self.config)
238 .finish_non_exhaustive()
239 }
240}
241
242struct Failure {
246 error: TypeSafeError,
247 retry_after: Option<Duration>,
248}
249
250impl From<TypeSafeError> for Failure {
251 fn from(error: TypeSafeError) -> Self {
252 Self {
253 error,
254 retry_after: None,
255 }
256 }
257}
258
259struct CallOpts {
262 extra_headers: Vec<(String, String)>,
263 timeout: Option<Duration>,
264 retry: Option<RetryPolicy>,
265}
266
267impl CallOpts {
268 fn empty() -> Self {
270 Self {
271 extra_headers: Vec::new(),
272 timeout: None,
273 retry: None,
274 }
275 }
276}
277
278#[derive(Clone, Default)]
296#[non_exhaustive]
297pub struct SystemOneOpts {
298 pub(crate) model: Option<String>,
300 pub(crate) state: Option<Value>,
302 pub(crate) extra_body: Option<Value>,
307 pub(crate) extra_headers: Vec<(String, String)>,
309 pub(crate) timeout: Option<Duration>,
311 pub(crate) retry: Option<RetryPolicy>,
313}
314
315impl fmt::Debug for SystemOneOpts {
316 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
317 f.debug_struct("SystemOneOpts")
318 .field("model", &self.model)
319 .field("state", &self.state.as_ref().map(|_| "<redacted>"))
321 .field(
323 "extra_body",
324 &self.extra_body.as_ref().map(|_| "<redacted>"),
325 )
326 .field(
328 "extra_headers",
329 &self
330 .extra_headers
331 .iter()
332 .map(|(k, _)| (k.as_str(), "<redacted>"))
333 .collect::<Vec<_>>(),
334 )
335 .field("timeout", &self.timeout)
336 .field("retry", &self.retry)
337 .finish()
338 }
339}
340
341impl SystemOneOpts {
342 #[must_use = "the returned SystemOneOpts should be used"]
344 pub fn new() -> Self {
345 Self::default()
346 }
347
348 #[must_use = "the returned SystemOneOpts should be used"]
350 pub fn with_model(mut self, model: Option<impl Into<String>>) -> Self {
351 self.model = model.map(|m| m.into());
352 self
353 }
354
355 #[must_use = "the returned SystemOneOpts should be used"]
357 pub fn with_state(mut self, state: impl Into<Value>) -> Self {
358 self.state = Some(state.into());
359 self
360 }
361
362 #[must_use = "the returned SystemOneOpts should be used"]
368 pub fn with_extra_body(mut self, extra: Value) -> Self {
369 self.extra_body = Some(extra);
370 self
371 }
372
373 #[must_use = "the returned SystemOneOpts should be used"]
380 pub fn with_extra_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
381 self.extra_headers.push((name.into(), value.into()));
382 self
383 }
384
385 #[must_use = "the returned SystemOneOpts should be used"]
387 pub fn with_timeout(mut self, timeout: Duration) -> Self {
388 self.timeout = Some(timeout);
389 self
390 }
391
392 #[must_use = "the returned SystemOneOpts should be used"]
395 pub fn with_retry(mut self, retry: RetryPolicy) -> Self {
396 self.retry = Some(retry);
397 self
398 }
399}
400
401impl TypeSafeClient {
402 #[must_use = "the returned client should be used to make API calls"]
404 pub fn new(api_key: impl Into<String>) -> Result<Self> {
405 let config = ClientConfig {
406 api_key: api_key.into(),
407 ..ClientConfig::default()
408 };
409 Self::from_config(config)
410 }
411
412 #[must_use = "the returned client should be used to make API calls"]
414 pub fn from_config(mut config: ClientConfig) -> Result<Self> {
415 config.api_key = config.api_key.trim().to_string();
418
419 if config.api_key.is_empty() {
420 return Err(TypeSafeError::new(ErrorKind::Validation(
421 "No API key was provided. Pass an API key to `TypeSafeClient::new` or set the `TYPESAFE_API_KEY` environment variable."
422 .to_string(),
423 )));
424 }
425
426 config.base_url = config.base_url.trim().trim_end_matches('/').to_string();
428 validate_base_url(&config.base_url)?;
429
430 if config.default_model.trim().is_empty() {
432 return Err(TypeSafeError::new(ErrorKind::Validation(
433 "Default model name cannot be empty.".to_string(),
434 )));
435 }
436
437 let mut auth =
440 HeaderValue::from_str(&format!("Bearer {}", config.api_key)).map_err(|_| {
441 TypeSafeError::new(ErrorKind::Validation(
442 "The API key contains characters that are not valid in an HTTP header."
443 .to_string(),
444 ))
445 })?;
446 auth.set_sensitive(true);
447
448 let mut headers = HeaderMap::new();
449 headers.insert(AUTHORIZATION, auth.clone());
450 headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
451 headers.insert(
452 HeaderName::from_static("x-typesafe-sdk"),
453 HeaderValue::from_static(SDK_USER_AGENT),
454 );
455
456 let http = match config.http_client.take() {
462 Some(client) => client,
463 None => HttpClient::builder()
464 .timeout(config.timeout)
465 .user_agent(SDK_USER_AGENT)
466 .default_headers(headers)
467 .redirect(redirect::Policy::none())
470 .build()
471 .map_err(|e| TypeSafeError::new(ErrorKind::Transport(e.to_string())))?,
472 };
473
474 Ok(Self {
475 config,
476 http,
477 auth_header: auth,
478 })
479 }
480
481 #[must_use = "the returned client should be used to make API calls"]
485 pub fn from_env() -> Result<Self> {
486 let api_key = env::var("TYPESAFE_API_KEY").unwrap_or_default();
487 let mut config = ClientConfig {
488 api_key,
489 ..ClientConfig::default()
490 };
491
492 if let Ok(base) = env::var("TYPESAFE_BASE_URL") {
493 if !base.trim().is_empty() {
494 config.base_url = base;
495 }
496 }
497
498 if let Ok(model) = env::var("TYPESAFE_DEFAULT_MODEL") {
499 if !model.trim().is_empty() {
500 config.default_model = model;
501 }
502 }
503
504 Self::from_config(config)
505 }
506
507 pub fn base_url(&self) -> &str {
509 &self.config.base_url
510 }
511
512 pub fn default_model(&self) -> &str {
514 &self.config.default_model
515 }
516
517 pub async fn system_one(
558 &self,
559 state: impl Into<Value>,
560 questions: HashMap<String, Question>,
561 ) -> Result<SystemOneResponse> {
562 self.system_one_with_model(state, questions, None).await
563 }
564
565 pub async fn system_one_with_model(
568 &self,
569 state: impl Into<Value>,
570 questions: HashMap<String, Question>,
571 model: Option<&str>,
572 ) -> Result<SystemOneResponse> {
573 let opts = SystemOneOpts::new().with_model(model).with_state(state);
574 self.system_one_with_opts(questions, opts).await
575 }
576
577 pub async fn system_one_with_opts(
603 &self,
604 questions: HashMap<String, Question>,
605 opts: SystemOneOpts,
606 ) -> Result<SystemOneResponse> {
607 validate_questions(&questions)?;
608
609 let model_name = opts
610 .model
611 .unwrap_or_else(|| self.config.default_model.clone());
612 if model_name.trim().is_empty() {
613 return Err(TypeSafeError::new(ErrorKind::Validation(
614 "Model name cannot be empty.".to_string(),
615 )));
616 }
617
618 let request = SystemOneRequest {
619 state: opts.state.unwrap_or(Value::Null),
620 model: model_name,
621 questions,
622 };
623
624 let mut body = serde_json::to_value(&request)?;
625
626 if let Some(extra) = &opts.extra_body {
631 let extra_obj = extra.as_object().ok_or_else(|| {
632 TypeSafeError::new(ErrorKind::Validation(
633 "extra_body must be a JSON object.".to_string(),
634 ))
635 })?;
636 const RESERVED_KEYS: &[&str] = &["state", "model", "questions"];
637 for key in extra_obj.keys() {
638 if RESERVED_KEYS.contains(&key.as_str()) {
639 return Err(TypeSafeError::new(ErrorKind::Validation(format!(
640 "extra_body cannot override reserved key `{key}`. \
641 Use the dedicated method (with_state, with_model, or the \
642 questions argument) instead."
643 ))));
644 }
645 }
646 let body_obj = body.as_object_mut().ok_or_else(|| {
647 TypeSafeError::new(ErrorKind::Validation(
648 "Internal error: request body is not a JSON object.".to_string(),
649 ))
650 })?;
651 for (k, v) in extra_obj {
652 body_obj.insert(k.clone(), v.clone());
653 }
654 }
655
656 let call_opts = CallOpts {
657 extra_headers: opts.extra_headers,
658 timeout: opts.timeout,
659 retry: opts.retry,
660 };
661
662 self.request_with_retry_opts(Method::POST, SYSTEM_ONE_PATH, Some(body), &call_opts)
663 .await
664 }
665
666 pub async fn list_models(&self) -> Result<ListModelsResponse> {
672 self.request_with_retry_opts(Method::GET, MODELS_PATH, None, &CallOpts::empty())
673 .await
674 }
675
676 async fn request_with_retry_opts<T: serde::de::DeserializeOwned + SetMetadata>(
681 &self,
682 method: Method,
683 path: &str,
684 body: Option<Value>,
685 opts: &CallOpts,
686 ) -> Result<T> {
687 let url = format!("{}{}", self.config.base_url, path);
688 let retry = opts.retry.as_ref().unwrap_or(&self.config.retry);
689 let timeout = opts.timeout.unwrap_or(self.config.timeout);
690
691 let started = std::time::Instant::now();
692 let mut attempt = 0;
693 let mut last_error: Option<TypeSafeError> = None;
694 loop {
695 let attempt_timeout = if attempt == 0 {
700 timeout
701 } else {
702 match retry.budget {
703 Some(budget) => {
704 let remaining = budget.saturating_sub(started.elapsed());
705 if remaining.is_zero() {
706 return Err(last_error.expect("last_error must be set on a retry"));
712 }
713 std::cmp::min(timeout, remaining)
714 }
715 None => timeout,
716 }
717 };
718
719 match self
720 .attempt_request(&method, &url, body.as_ref(), opts, attempt_timeout)
721 .await
722 {
723 Ok(resp) => return Ok(resp),
724 Err(failure) => {
725 let err = failure.error;
726
727 if !err.is_retryable() || attempt >= retry.max_retries {
728 return Err(err);
729 }
730
731 let delay = match failure.retry_after {
732 Some(hint) => match retry.delay_for_retry_after(attempt, hint) {
736 Some(delay) => delay,
737 None => return Err(err),
738 },
739 None => retry.delay_for_with_jitter(attempt, jitter_seed()),
740 };
741
742 if retry.budget_exceeded(started.elapsed(), delay) {
745 return Err(err);
746 }
747
748 if let Some(budget) = retry.budget {
754 let remaining_after_delay =
755 budget.saturating_sub(started.elapsed().saturating_add(delay));
756 let min_window = std::cmp::max(
757 Duration::from_millis(100),
758 Duration::from_millis(timeout.as_millis() as u64 / 10),
759 );
760 if remaining_after_delay < min_window {
761 return Err(err);
762 }
763 }
764
765 last_error = Some(err);
766 tokio::time::sleep(delay).await;
767 attempt += 1;
768 }
769 }
770 }
771 }
772
773 async fn attempt_request<T: serde::de::DeserializeOwned + SetMetadata>(
774 &self,
775 method: &Method,
776 url: &str,
777 body: Option<&Value>,
778 opts: &CallOpts,
779 timeout: Duration,
780 ) -> std::result::Result<T, Failure> {
781 let mut request = self
785 .http
786 .request(method.clone(), url)
787 .timeout(timeout)
788 .header(AUTHORIZATION, &self.auth_header)
789 .header(ACCEPT, "application/json")
790 .header("x-typesafe-sdk", SDK_USER_AGENT);
791
792 if let Some(b) = body {
793 request = request.json(b);
794 }
795
796 for (name, value) in &opts.extra_headers {
800 let lower = name.to_ascii_lowercase();
801 if PROTECTED_HEADER_NAMES.contains(&lower.as_str()) {
802 return Err(Failure::from(TypeSafeError::new(ErrorKind::Validation(
803 format!(
804 "Header `{name}` is protected and cannot be set via with_extra_header."
805 ),
806 ))));
807 }
808 let hn = HeaderName::try_from(name.as_str()).map_err(|_| {
809 Failure::from(TypeSafeError::new(ErrorKind::Validation(format!(
810 "Invalid header name: {name}"
811 ))))
812 })?;
813 let hv = HeaderValue::try_from(value.as_str()).map_err(|_| {
814 Failure::from(TypeSafeError::new(ErrorKind::Validation(format!(
815 "Invalid header value for `{name}`: contains invalid characters."
816 ))))
817 })?;
818 request = request.header(hn, hv);
819 }
820
821 let response = request
822 .send()
823 .await
824 .map_err(|e| map_reqwest_error(e, timeout))?;
825
826 self.parse_response(response).await
827 }
828
829 async fn parse_response<T: serde::de::DeserializeOwned + SetMetadata>(
830 &self,
831 response: reqwest::Response,
832 ) -> std::result::Result<T, Failure> {
833 let status = response.status();
834 let headers = response.headers();
835 let request_id = headers
837 .get(REQUEST_ID_HEADER)
838 .and_then(|v| v.to_str().ok())
839 .map(|s| s.to_string());
840 let retry_after = headers
843 .get(RETRY_AFTER_MS_HEADER)
844 .and_then(|v| v.to_str().ok())
845 .and_then(parse_retry_after_ms)
846 .or_else(|| {
847 headers
848 .get(RETRY_AFTER)
849 .and_then(|v| v.to_str().ok())
850 .and_then(parse_retry_after)
851 });
852
853 if let Some(kind) = Self::kind_for_status(status) {
857 let text = match read_body_capped(response, MAX_RESPONSE_BODY_BYTES).await {
861 Ok(bytes) => String::from_utf8_lossy(&bytes).into_owned(),
862 Err(_) => String::new(),
863 };
864 let message = Self::extract_error_message(&text)
865 .map(|m| truncate(&m, MAX_ERROR_BODY_CHARS))
866 .unwrap_or_else(|| truncate(&text, MAX_ERROR_BODY_CHARS));
867 let kind = Self::with_message(kind, message);
868 return Err(Failure {
869 error: TypeSafeError::with_request_id(kind, request_id),
870 retry_after,
871 });
872 }
873
874 let bytes = read_body_capped(response, MAX_RESPONSE_BODY_BYTES).await?;
877 let text = String::from_utf8_lossy(&bytes);
878
879 if status.is_success() {
880 let raw: Value = serde_json::from_str(&text).map_err(|e| {
884 Failure::from(TypeSafeError::new(ErrorKind::ResponseValidation {
885 message: format!(
886 "Failed to parse response body: {e}\nBody: {}",
887 truncate(&text, MAX_ERROR_BODY_CHARS)
888 ),
889 field_path: None,
890 }))
891 })?;
892 let mut result: T = T::deserialize(&raw).map_err(|e| {
893 Failure::from(TypeSafeError::new(ErrorKind::ResponseValidation {
894 message: format!(
895 "Failed to parse response body: {e}\nBody: {}",
896 truncate(&text, MAX_ERROR_BODY_CHARS)
897 ),
898 field_path: None,
899 }))
900 })?;
901 result.set_metadata(request_id, Some(raw));
904 return Ok(result);
905 }
906
907 let kind = ErrorKind::Api {
911 status: status.as_u16(),
912 message: String::new(),
913 };
914 Err(Failure {
915 error: TypeSafeError::with_request_id(kind, request_id),
916 retry_after,
917 })
918 }
919
920 fn kind_for_status(status: StatusCode) -> Option<ErrorKind> {
926 if status.is_success() {
930 return None;
931 }
932
933 match status {
934 StatusCode::UNAUTHORIZED => Some(ErrorKind::Authentication(String::new())),
936 StatusCode::BAD_REQUEST => Some(ErrorKind::BadRequest(String::new())),
937 StatusCode::NOT_FOUND => Some(ErrorKind::NotFound(String::new())),
938 StatusCode::UNPROCESSABLE_ENTITY => Some(ErrorKind::UnprocessableEntity(String::new())),
939 StatusCode::REQUEST_TIMEOUT => Some(ErrorKind::RequestTimeout(String::new())),
940
941 StatusCode::TOO_MANY_REQUESTS => Some(ErrorKind::RateLimit(String::new())),
943 StatusCode::INTERNAL_SERVER_ERROR
944 | StatusCode::BAD_GATEWAY
945 | StatusCode::SERVICE_UNAVAILABLE
946 | StatusCode::GATEWAY_TIMEOUT => Some(ErrorKind::InternalServer(String::new())),
947
948 _ if status.as_u16() == 529 => Some(ErrorKind::Overloaded(String::new())),
950 _ => Some(ErrorKind::Api {
951 status: status.as_u16(),
952 message: String::new(),
953 }),
954 }
955 }
956
957 fn with_message(kind: ErrorKind, message: String) -> ErrorKind {
961 match kind {
962 ErrorKind::Authentication(_) => ErrorKind::Authentication(message),
963 ErrorKind::BadRequest(_) => ErrorKind::BadRequest(message),
964 ErrorKind::NotFound(_) => ErrorKind::NotFound(message),
965 ErrorKind::UnprocessableEntity(_) => ErrorKind::UnprocessableEntity(message),
966 ErrorKind::RequestTimeout(_) => ErrorKind::RequestTimeout(message),
967 ErrorKind::RateLimit(_) => ErrorKind::RateLimit(message),
968 ErrorKind::InternalServer(_) => ErrorKind::InternalServer(message),
969 ErrorKind::Overloaded(_) => ErrorKind::Overloaded(message),
970 ErrorKind::Api { status, .. } => ErrorKind::Api { status, message },
971 other => other,
972 }
973 }
974
975 fn extract_error_message(text: &str) -> Option<String> {
979 let value: Value = serde_json::from_str(text).ok()?;
980 let obj = value.as_object()?;
981 if let Some(error) = obj.get("error") {
982 if let Some(msg) = error.get("message").and_then(|m| m.as_str()) {
983 return Some(msg.to_string());
984 }
985 if let Some(msg) = error.as_str() {
986 return Some(msg.to_string());
987 }
988 }
989 if let Some(detail) = obj.get("detail").and_then(|d| d.as_str()) {
990 return Some(detail.to_string());
991 }
992 if let Some(message) = obj.get("message").and_then(|m| m.as_str()) {
993 return Some(message.to_string());
994 }
995 None
996 }
997}
998
999async fn read_body_capped(
1006 response: reqwest::Response,
1007 max_bytes: usize,
1008) -> std::result::Result<Vec<u8>, TypeSafeError> {
1009 let mut bytes = Vec::new();
1010 let mut resp = response;
1011 loop {
1012 match resp.chunk().await {
1013 Ok(Some(chunk)) => {
1014 if bytes.len() + chunk.len() > max_bytes {
1015 return Err(TypeSafeError::new(ErrorKind::Transport(format!(
1016 "response body exceeds maximum size of {max_bytes} bytes"
1017 ))));
1018 }
1019 bytes.extend_from_slice(&chunk);
1020 }
1021 Ok(None) => break,
1022 Err(e) => return Err(TypeSafeError::new(ErrorKind::Transport(e.to_string()))),
1023 }
1024 }
1025 Ok(bytes)
1026}
1027
1028fn map_reqwest_error(e: reqwest::Error, timeout: Duration) -> TypeSafeError {
1045 if e.is_timeout() {
1046 TypeSafeError::new(ErrorKind::Timeout(timeout))
1047 } else if e.is_connect() {
1048 TypeSafeError::new(ErrorKind::Connection(e.to_string()))
1049 } else {
1050 TypeSafeError::new(ErrorKind::Transport(e.to_string()))
1051 }
1052}
1053
1054fn parse_retry_after(value: &str) -> Option<Duration> {
1059 value.trim().parse::<u64>().ok().map(Duration::from_secs)
1060}
1061
1062fn parse_retry_after_ms(value: &str) -> Option<Duration> {
1068 value.trim().parse::<u64>().ok().map(Duration::from_millis)
1069}
1070
1071fn truncate(s: &str, max_chars: usize) -> String {
1076 match s.char_indices().nth(max_chars) {
1077 Some((idx, _)) => format!("{}...", &s[..idx]),
1078 None => s.to_string(),
1079 }
1080}
1081
1082fn validate_base_url(raw: &str) -> Result<()> {
1087 let url = reqwest::Url::parse(raw).map_err(|e| {
1088 TypeSafeError::new(ErrorKind::Validation(format!(
1089 "Base URL is not a valid URL: {e}"
1090 )))
1091 })?;
1092
1093 if !url.username().is_empty()
1096 || url.password().is_some()
1097 || url.query().is_some()
1098 || url.fragment().is_some()
1099 {
1100 return Err(TypeSafeError::new(ErrorKind::Validation(
1101 "Base URL must not contain credentials, query parameters, or fragments.".to_string(),
1102 )));
1103 }
1104
1105 match (url.scheme(), url.host_str()) {
1106 ("https", Some(_)) => Ok(()),
1107 ("http", Some("localhost" | "127.0.0.1" | "::1" | "[::1]")) => Ok(()),
1108 (scheme, _) => Err(TypeSafeError::new(ErrorKind::Validation(format!(
1109 "Base URL must use https:// (or http:// for localhost/127.0.0.1/::1 during development); got scheme `{scheme}` and an unsupported host."
1110 )))),
1111 }
1112}
1113
1114#[cfg(test)]
1115mod tests {
1116 use super::*;
1117
1118 #[test]
1119 fn new_requires_api_key() {
1120 let result = TypeSafeClient::new("");
1121 assert!(result.is_err());
1122 }
1123
1124 #[test]
1125 fn from_config_requires_api_key() {
1126 let config = ClientConfig::default();
1127 let result = TypeSafeClient::from_config(config);
1128 assert!(result.is_err());
1129 }
1130
1131 #[test]
1132 fn extract_error_message_from_nested_object() {
1133 let text = r#"{"error":{"message":"Invalid API key"}}"#;
1134 let msg = TypeSafeClient::extract_error_message(text).unwrap();
1135 assert_eq!(msg, "Invalid API key");
1136 }
1137
1138 #[test]
1139 fn extract_error_message_from_detail() {
1140 let text = r#"{"detail":"Not found"}"#;
1141 let msg = TypeSafeClient::extract_error_message(text).unwrap();
1142 assert_eq!(msg, "Not found");
1143 }
1144
1145 #[test]
1146 fn extract_error_message_returns_none_for_plain_text() {
1147 let text = "plain text error";
1148 assert!(TypeSafeClient::extract_error_message(text).is_none());
1149 }
1150
1151 #[test]
1152 fn debug_redacts_api_key() {
1153 let config = ClientConfig {
1154 api_key: "secret_key_123".to_string(),
1155 ..ClientConfig::default()
1156 };
1157 let debug_str = format!("{config:?}");
1158 assert!(!debug_str.contains("secret_key_123"));
1159 assert!(debug_str.contains("<redacted>"));
1160 }
1161
1162 #[test]
1163 fn client_debug_does_not_leak_api_key() {
1164 let client = TypeSafeClient::new("secret_key_123").unwrap();
1165 let debug_str = format!("{client:?}");
1166 assert!(!debug_str.contains("secret_key_123"));
1167 }
1168
1169 #[test]
1170 fn trims_api_key_whitespace() {
1171 let client = TypeSafeClient::new(" apikey_test \n").unwrap();
1173 assert_eq!(client.config.api_key, "apikey_test");
1174 }
1175
1176 #[test]
1177 fn rejects_api_key_that_is_not_a_valid_header_value() {
1178 let err = TypeSafeClient::new("bad\nkey").unwrap_err();
1179 assert!(
1180 matches!(err.kind(), ErrorKind::Validation(_)),
1181 "got {err:?}"
1182 );
1183 }
1184
1185 #[test]
1186 fn rejects_http_base_url() {
1187 let config = ClientConfig {
1188 api_key: "test".to_string(),
1189 base_url: "http://api.typesafe.ai".to_string(),
1190 ..ClientConfig::default()
1191 };
1192 assert!(TypeSafeClient::from_config(config).is_err());
1193 }
1194
1195 #[test]
1196 fn allows_localhost_http() {
1197 let config = ClientConfig {
1198 api_key: "test".to_string(),
1199 base_url: "http://localhost:8080".to_string(),
1200 ..ClientConfig::default()
1201 };
1202 assert!(TypeSafeClient::from_config(config).is_ok());
1203 }
1204
1205 #[test]
1206 fn trims_trailing_slash_from_base_url() {
1207 let config = ClientConfig {
1208 api_key: "test".to_string(),
1209 base_url: "https://api.typesafe.ai/".to_string(),
1210 ..ClientConfig::default()
1211 };
1212 let client = TypeSafeClient::from_config(config).unwrap();
1213 assert_eq!(client.base_url(), "https://api.typesafe.ai");
1214 }
1215
1216 #[test]
1219 fn trailing_slash_does_not_produce_double_slash() {
1220 let config = ClientConfig {
1221 api_key: "test".to_string(),
1222 base_url: "https://api.typesafe.ai/v1/".to_string(),
1223 ..ClientConfig::default()
1224 };
1225 let client = TypeSafeClient::from_config(config).unwrap();
1226 let url = format!("{}{}", client.base_url(), "/v1/systemone");
1229 assert_eq!(url, "https://api.typesafe.ai/v1/v1/systemone");
1230 assert!(!url.contains("//v1"), "double slash in URL: {url}");
1231 }
1232
1233 #[test]
1236 fn base_url_rejects_localhost_lookalikes() {
1237 for bad in [
1238 "http://localhost.evil.example",
1239 "http://127.0.0.1.evil.example/v1",
1240 "http://localhost@evil.example",
1241 "http://localhostevil.example",
1242 "ftp://localhost",
1243 "not a url",
1244 "",
1245 ] {
1246 assert!(
1247 validate_base_url(bad).is_err(),
1248 "{bad:?} should be rejected"
1249 );
1250 }
1251 }
1252
1253 #[test]
1254 fn base_url_accepts_valid_urls() {
1255 for good in [
1256 "https://api.typesafe.ai",
1257 "HTTPS://API.TYPESAFE.AI",
1258 "https://api.typesafe.ai/prefix",
1259 "http://localhost",
1260 "http://localhost:8080",
1261 "http://LOCALHOST:8080",
1262 "http://127.0.0.1:9000",
1263 "http://[::1]:9000",
1264 ] {
1265 assert!(
1266 validate_base_url(good).is_ok(),
1267 "{good:?} should be accepted"
1268 );
1269 }
1270 }
1271
1272 #[test]
1273 fn truncate_shortens_long_strings() {
1274 let long = "x".repeat(600);
1275 let truncated = truncate(&long, 512);
1276 assert_eq!(truncated.len(), 515); assert!(truncated.ends_with("..."));
1278 }
1279
1280 #[test]
1281 fn truncate_leaves_short_strings_alone() {
1282 assert_eq!(truncate("hello", 512), "hello");
1283 assert_eq!(truncate("exactly", 7), "exactly");
1284 }
1285
1286 #[test]
1289 fn truncate_handles_multibyte_characters() {
1290 let long = "€".repeat(600);
1291 let truncated = truncate(&long, 512);
1292 assert_eq!(truncated.chars().count(), 515); assert!(truncated.ends_with("..."));
1294
1295 let mixed = "héllo wörld 日本語 🙂".repeat(20);
1297 for max in 0..mixed.chars().count() + 2 {
1298 let _ = truncate(&mixed, max); }
1300 }
1301
1302 #[test]
1303 fn parse_retry_after_seconds() {
1304 assert_eq!(parse_retry_after("5"), Some(Duration::from_secs(5)));
1305 assert_eq!(parse_retry_after(" 10 "), Some(Duration::from_secs(10)));
1306 assert_eq!(parse_retry_after("not a number"), None);
1307 assert_eq!(parse_retry_after("Wed, 21 Oct 2026 07:28:00 GMT"), None);
1309 }
1310
1311 #[test]
1312 fn parse_retry_after_ms_parses_milliseconds() {
1313 assert_eq!(
1314 parse_retry_after_ms("500"),
1315 Some(Duration::from_millis(500))
1316 );
1317 assert_eq!(
1318 parse_retry_after_ms(" 1500 "),
1319 Some(Duration::from_millis(1500))
1320 );
1321 assert_eq!(parse_retry_after_ms("not a number"), None);
1322 }
1323
1324 #[test]
1327 fn builder_errors_are_not_retryable() {
1328 let err = reqwest::Client::new().get("not a url").build().unwrap_err();
1329 let mapped = map_reqwest_error(err, Duration::from_secs(1));
1330 assert!(
1331 matches!(mapped.kind(), ErrorKind::Transport(_)),
1332 "got {mapped:?}"
1333 );
1334 assert!(!mapped.is_retryable());
1335 }
1336
1337 #[test]
1340 fn base_url_accepts_ipv6_loopback() {
1341 assert!(validate_base_url("http://[::1]:8080").is_ok());
1342 assert!(validate_base_url("http://[::1]").is_ok());
1343 }
1344
1345 #[test]
1346 fn from_config_rejects_empty_default_model() {
1347 let config = ClientConfig {
1348 api_key: "test".to_string(),
1349 default_model: " ".to_string(),
1350 ..ClientConfig::default()
1351 };
1352 let err = TypeSafeClient::from_config(config).unwrap_err();
1353 assert!(
1354 matches!(err.kind(), ErrorKind::Validation(ref m) if m.contains("model")),
1355 "got {err:?}"
1356 );
1357 }
1358
1359 #[test]
1360 fn timeout_error_preserves_subsecond_duration() {
1361 let err = TypeSafeError::new(ErrorKind::Timeout(Duration::from_millis(150)));
1362 let msg = err.to_string();
1363 assert!(
1364 msg.contains("150ms"),
1365 "expected 150ms in message, got: {msg}"
1366 );
1367 }
1368
1369 #[test]
1370 fn base_url_rejects_credentials() {
1371 assert!(validate_base_url("https://user:password@api.typesafe.ai").is_err());
1372 assert!(validate_base_url("https://user@api.typesafe.ai").is_err());
1373 }
1374
1375 #[test]
1376 fn base_url_rejects_query_and_fragment() {
1377 assert!(validate_base_url("https://api.typesafe.ai?foo=bar").is_err());
1378 assert!(validate_base_url("https://api.typesafe.ai#fragment").is_err());
1379 }
1380
1381 #[test]
1382 fn base_url_accepts_path() {
1383 assert!(validate_base_url("https://api.typesafe.ai/api").is_ok());
1384 assert!(validate_base_url("https://api.typesafe.ai/v1/").is_ok());
1385 }
1386}