audacity-sdk 0.5.0

Rust SDK for the Audacity Investments AI gateway — Amazon Bedrock Converse-compatible API surface
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use thiserror::Error;

/// Details carried by every server-derived error variant.
#[derive(Debug, Clone, Default)]
pub struct ErrorDetails {
    pub message: String,
    pub status_code: u16,
    /// Raw code/type string from the error payload.
    pub error_code: Option<String>,
    /// `request_id` captured from shape-B error payloads.
    pub request_id: Option<String>,
    /// `error.details` captured from shape-B error payloads
    /// (e.g. `binding_cap` on budget errors).
    pub details: Option<serde_json::Value>,
    /// Value of the `Retry-After` header, if present.
    pub retry_after_seconds: Option<f64>,
    pub raw_body: String,
}

impl std::fmt::Display for ErrorDetails {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.message)
    }
}

/// The SDK error type — all variants mirror the spec §4 exception taxonomy.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum Error {
    /// 400 / invalid_request_error / VALIDATION_ERROR
    #[error("ValidationException: {0}")]
    Validation(Box<ErrorDetails>),

    /// 401/403 / authentication_error / AUTHORIZATION_ERROR / MODEL_NOT_ALLOWED
    #[error("AccessDeniedException: {0}")]
    AccessDenied(Box<ErrorDetails>),

    /// 402 / usage_cap_exceeded / BUDGET_EXCEEDED
    #[error("ServiceQuotaExceededException: {0}")]
    ServiceQuotaExceeded(Box<ErrorDetails>),

    /// 404 / MODEL_NOT_FOUND
    #[error("ResourceNotFoundException: {0}")]
    ResourceNotFound(Box<ErrorDetails>),

    /// 429 (retryable) / rate_limit_exceeded / RATE_LIMIT_EXCEEDED
    #[error("ThrottlingException: {0}")]
    Throttling(Box<ErrorDetails>),

    /// 408 / TIMEOUT_ERROR
    #[error("ModelTimeoutException: {0}")]
    ModelTimeout(Box<ErrorDetails>),

    /// 5xx model-side error
    #[error("ModelErrorException: {0}")]
    ModelError(Box<ErrorDetails>),

    /// Stream-specific error (subtype of ModelError)
    #[error("ModelStreamErrorException: {0}")]
    ModelStreamError(Box<ErrorDetails>),

    /// 503/502/504 / ServiceUnavailable
    #[error("ServiceUnavailableException: {0}")]
    ServiceUnavailable(Box<ErrorDetails>),

    /// 500 / InternalServerException
    #[error("InternalServer: {0}")]
    InternalServer(Box<ErrorDetails>),

    /// No API key could be resolved from config or environment.
    #[error("MissingApiKeyError: no API key provided; set AUDACITY_API_KEY or pass api_key to Config::builder()")]
    MissingApiKey,

    /// Client-side failure. Per spec §4 only **network-level** failures are
    /// retryable; JSON-decode failures and malformed 200 bodies are not.
    #[error("SdkError: {message}")]
    Sdk { message: String, retryable: bool },
}

impl Error {
    /// A retryable network-level client failure (connect/read errors).
    pub(crate) fn sdk_network(message: impl Into<String>) -> Self {
        Error::Sdk {
            message: message.into(),
            retryable: true,
        }
    }

    /// A non-retryable client failure (decode errors, malformed bodies, internal).
    pub(crate) fn sdk(message: impl Into<String>) -> Self {
        Error::Sdk {
            message: message.into(),
            retryable: false,
        }
    }

    /// A client-side input validation failure (no HTTP exchange happened).
    pub(crate) fn client_validation(message: impl Into<String>) -> Self {
        Error::Validation(Box::new(ErrorDetails {
            message: message.into(),
            ..Default::default()
        }))
    }

    /// A stream-level failure with no HTTP error payload (transport drop, etc.).
    pub(crate) fn model_stream_error(message: impl Into<String>) -> Self {
        Error::ModelStreamError(Box::new(ErrorDetails {
            message: message.into(),
            ..Default::default()
        }))
    }

    /// Returns true if this error is retryable per the spec retry policy.
    pub fn is_retryable(&self) -> bool {
        matches!(
            self,
            Error::Throttling(_)
                | Error::ModelTimeout(_)
                | Error::ServiceUnavailable(_)
                | Error::InternalServer(_)
                | Error::Sdk {
                    retryable: true,
                    ..
                }
        )
    }

    /// Returns the `Retry-After` value if this error carries one.
    pub fn retry_after_seconds(&self) -> Option<f64> {
        match self {
            Error::Throttling(d)
            | Error::ModelTimeout(d)
            | Error::ServiceUnavailable(d)
            | Error::InternalServer(d)
            | Error::ModelError(d)
            | Error::ModelStreamError(d)
            | Error::Validation(d)
            | Error::AccessDenied(d)
            | Error::ServiceQuotaExceeded(d)
            | Error::ResourceNotFound(d) => d.retry_after_seconds,
            _ => None,
        }
    }
}

// ── error parsing ────────────────────────────────────────────────────────────

/// Parse the raw response body + HTTP status into an [`Error`].
pub(crate) fn parse_error(status: u16, body: &str, retry_after: Option<f64>) -> Error {
    let (message, error_code, request_id, error_details) = extract_error_fields(body);

    let details = Box::new(ErrorDetails {
        message: message.clone(),
        status_code: status,
        error_code: error_code.clone(),
        request_id,
        details: error_details,
        retry_after_seconds: retry_after,
        raw_body: body.to_owned(),
    });

    classify_error(status, error_code.as_deref(), details)
}

/// Map an in-stream error payload (no HTTP status) through the §4 code table
/// — the Anthropic-shaped envelope's `error.type` hits the same table via the
/// shape-A extractor — falling back to ModelStreamError for codeless or
/// unrecognized errors.
pub(crate) fn parse_stream_error(raw: &str) -> Error {
    let (message, code, request_id, error_details) = extract_error_fields(raw);
    let details = Box::new(ErrorDetails {
        message,
        status_code: 0,
        error_code: code.clone(),
        request_id,
        details: error_details,
        retry_after_seconds: None,
        raw_body: raw.to_owned(),
    });
    match code.as_deref() {
        Some(c) => classify_by_code(c, 0, details).unwrap_or_else(Error::ModelStreamError),
        None => Error::ModelStreamError(details),
    }
}

/// Pull (message, code, request_id, details) out of shape-A or shape-B bodies.
#[allow(clippy::type_complexity)]
pub(crate) fn extract_error_fields(
    body: &str,
) -> (
    String,
    Option<String>,
    Option<String>,
    Option<serde_json::Value>,
) {
    let Ok(v) = serde_json::from_str::<serde_json::Value>(body) else {
        return (body.to_owned(), None, None, None);
    };

    // Shape B: { "success": false, "error": { "code": …, "message": …,
    //            "request_id": …, "details": … } }
    if v.get("success").and_then(|s| s.as_bool()) == Some(false) {
        if let Some(err) = v.get("error") {
            let message = err
                .get("message")
                .and_then(|m| m.as_str())
                .unwrap_or("unknown error")
                .to_owned();
            let code = err.get("code").and_then(|c| c.as_str()).map(str::to_owned);
            let request_id = err
                .get("request_id")
                .and_then(|r| r.as_str())
                .map(str::to_owned);
            let details = err.get("details").filter(|d| !d.is_null()).cloned();
            return (message, code, request_id, details);
        }
    }

    // Shape A: { "error": { "message": …, "type": …, "code": … } }
    if let Some(err) = v.get("error") {
        let message = err
            .get("message")
            .and_then(|m| m.as_str())
            .unwrap_or("unknown error")
            .to_owned();
        // prefer "code" over "type"
        let code = err
            .get("code")
            .and_then(|c| c.as_str())
            .filter(|s| !s.is_empty())
            .or_else(|| err.get("type").and_then(|t| t.as_str()))
            .map(str::to_owned);
        return (message, code, None, None);
    }

    (body.to_owned(), None, None, None)
}

/// Classify into the right Error variant using the spec mapping table.
pub(crate) fn classify_error(status: u16, code: Option<&str>, details: Box<ErrorDetails>) -> Error {
    let details = match code {
        Some(c) => match classify_by_code(c, status, details) {
            Ok(err) => return err,
            Err(details) => details, // unrecognized code — fall through to HTTP status
        },
        None => details,
    };
    classify_by_status(status, details)
}

/// Map a raw error code (case-insensitive) to a variant per the spec table.
/// Returns the details back if the code is unrecognized.
pub(crate) fn classify_by_code(
    code: &str,
    status: u16,
    details: Box<ErrorDetails>,
) -> Result<Error, Box<ErrorDetails>> {
    Ok(match code.to_uppercase().as_str() {
        "INVALID_API_KEY"
        | "API_KEY_REQUIRED"
        | "AUTHENTICATION_ERROR"
        | "AUTHORIZATION_ERROR"
        | "MODEL_NOT_ALLOWED" => Error::AccessDenied(details),

        "USAGE_CAP_EXCEEDED" | "USAGE_CAP_ERROR" | "BUDGET_EXCEEDED" => {
            Error::ServiceQuotaExceeded(details)
        }

        "RATE_LIMIT_EXCEEDED" | "RATE_LIMIT_ERROR" => Error::Throttling(details),

        "INVALID_REQUEST_ERROR" | "VALIDATION_ERROR" => Error::Validation(details),

        "MODEL_NOT_FOUND" => Error::ResourceNotFound(details),

        "TIMEOUT_ERROR" => Error::ModelTimeout(details),

        "STREAM_ERROR" => Error::ModelStreamError(details),

        "UPSTREAM_ERROR" => {
            if status >= 500 {
                Error::ServiceUnavailable(details)
            } else {
                Error::ModelError(details)
            }
        }

        _ => return Err(details),
    })
}

/// Map a non-2xx response to an [`Error`] by HTTP status alone (spec §4
/// status fallback) — used for presigned-URL PUTs, whose response bodies are
/// storage-provider XML/HTML rather than gateway error payloads.
pub(crate) fn status_error(status: u16, body: &str) -> Error {
    let details = Box::new(ErrorDetails {
        message: if body.is_empty() {
            format!("HTTP {status}")
        } else {
            body.to_owned()
        },
        status_code: status,
        raw_body: body.to_owned(),
        ..Default::default()
    });
    classify_by_status(status, details)
}

/// HTTP status fallback (when the code is absent/unrecognized).
fn classify_by_status(status: u16, details: Box<ErrorDetails>) -> Error {
    match status {
        400 => Error::Validation(details),
        401 | 403 => Error::AccessDenied(details),
        402 => Error::ServiceQuotaExceeded(details),
        404 => Error::ResourceNotFound(details),
        408 => Error::ModelTimeout(details),
        429 => Error::Throttling(details),
        500 => Error::InternalServer(details),
        502..=504 => Error::ServiceUnavailable(details),
        s if (400..500).contains(&s) => Error::Validation(details),
        s if s >= 500 => Error::InternalServer(details),
        // Non-200 2xx/3xx — unexpected from this API; not retryable.
        s => Error::sdk(format!("unexpected HTTP status {s}: {}", details.message)),
    }
}

/// Parse `Retry-After` header value (seconds as integer or float).
pub(crate) fn parse_retry_after(value: &str) -> Option<f64> {
    value.trim().parse::<f64>().ok()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn shape_a_authentication_error() {
        let body = r#"{"error":{"message":"Invalid API key","type":"authentication_error","param":null,"code":"invalid_api_key"}}"#;
        let err = parse_error(401, body, None);
        assert!(matches!(err, Error::AccessDenied(_)));
        if let Error::AccessDenied(d) = err {
            assert_eq!(d.message, "Invalid API key");
            assert_eq!(d.error_code.as_deref(), Some("invalid_api_key"));
            assert!(d.request_id.is_none());
        }
    }

    #[test]
    fn shape_b_model_not_allowed() {
        let body = r#"{"success":false,"error":{"code":"MODEL_NOT_ALLOWED","message":"Model not allowed","request_id":"req-123","details":{"binding_cap":"team-alpha"}}}"#;
        let err = parse_error(403, body, None);
        assert!(matches!(err, Error::AccessDenied(_)));
        if let Error::AccessDenied(d) = err {
            assert_eq!(d.request_id.as_deref(), Some("req-123"));
            // spec §4: shape-B error.details must be carried on the exception
            let details = d.details.expect("details must be captured from shape B");
            assert_eq!(details["binding_cap"], "team-alpha");
        }
    }

    #[test]
    fn shape_a_has_no_details() {
        let body = r#"{"error":{"message":"bad request","type":"invalid_request_error"}}"#;
        let err = parse_error(400, body, None);
        if let Error::Validation(d) = err {
            assert!(d.details.is_none());
        } else {
            panic!("expected Validation");
        }
    }

    #[test]
    fn shape_b_budget_exceeded() {
        let body = r#"{"success":false,"error":{"code":"BUDGET_EXCEEDED","message":"over budget","request_id":null}}"#;
        let err = parse_error(429, body, None);
        assert!(matches!(err, Error::ServiceQuotaExceeded(_)));
        // Must NOT be retryable
        assert!(!err.is_retryable());
    }

    #[test]
    fn rate_limit_is_retryable() {
        let body = r#"{"error":{"message":"rate limited","type":"rate_limit_error","code":"rate_limit_exceeded"}}"#;
        let err = parse_error(429, body, Some(2.0));
        assert!(matches!(err, Error::Throttling(_)));
        assert!(err.is_retryable());
        assert_eq!(err.retry_after_seconds(), Some(2.0));
    }

    #[test]
    fn http_status_fallback_503() {
        let err = parse_error(503, "Service Unavailable", None);
        assert!(matches!(err, Error::ServiceUnavailable(_)));
        assert!(err.is_retryable());
    }

    #[test]
    fn upstream_error_5xx_is_service_unavailable() {
        let body = r#"{"error":{"message":"upstream","code":"UPSTREAM_ERROR"}}"#;
        let err = parse_error(502, body, None);
        assert!(matches!(err, Error::ServiceUnavailable(_)));
    }

    #[test]
    fn upstream_error_4xx_is_model_error() {
        let body = r#"{"error":{"message":"upstream","code":"UPSTREAM_ERROR"}}"#;
        let err = parse_error(400, body, None);
        assert!(matches!(err, Error::ModelError(_)));
    }

    #[test]
    fn parse_retry_after_value() {
        assert_eq!(parse_retry_after("5"), Some(5.0));
        assert_eq!(parse_retry_after("2.5"), Some(2.5));
        assert_eq!(parse_retry_after("bad"), None);
    }
}