nolgia 0.1.0

Official Rust SDK for the Nolgia API: image, video, audio and agent generation, generated from the OpenAPI spec
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
//! Hand-written. One error type for every call the SDK makes.

use std::{fmt, path::PathBuf, time::Duration};

use serde_json::Value;
use uuid::Uuid;

use crate::api::types;

/// `Result<T, nolgia::Error>`.
pub type Result<T, E = Error> = std::result::Result<T, E>;

/// The machine-readable `code` the API puts on a refusal (`error.code`) or a
/// failed job (`failure.code`).
///
/// The set is OPEN: a code this build does not know arrives as
/// [`ErrorCode::Other`] with the server's spelling, never coerced. Branch on
/// the code, never on the human-readable message.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ErrorCode {
    /// The wallet cannot pay for the job. Nothing was submitted or charged.
    OutOfCredits,
    /// Refused for now (your concurrency ceiling or the provider's). Retry later.
    RateLimit,
    /// A content filter refused the request or its result on safety grounds.
    PromptNsfw,
    /// A content filter refused a real person's likeness or a protected work.
    IpDetected,
    /// The job ran and produced nothing, for any other reason.
    JobFailed,
    /// The job ran past its time budget, or a wait ended before it finished.
    Timeout,
    /// The request is not acceptable as sent; retrying unchanged fails again.
    Validation,
    /// The cost confirmation gate did not pass.
    ConfirmationRejected,
    /// The job was canceled by its owner.
    Canceled,
    /// `POST /jobs/{id}/cancel` refused: the job already finished.
    JobNotCancellable,
    /// A generation would take an agent run past the price its customer approved.
    ApprovalRequired,
    /// The agent run this generation was started for has already ended.
    RunEnded,
    /// Agent endpoints: the session is already running a turn.
    SessionBusy,
    /// Agent endpoints: the caller may not use the agent.
    AccessDenied,
    /// Agent endpoints: the credits cannot cover the agent turn.
    InsufficientCredits,
    /// Agent endpoints: the agent backend failed.
    BackendError,
    /// A code this build does not know, verbatim.
    Other(String),
}

impl ErrorCode {
    /// Parse the wire spelling. Never fails: unknown codes become [`ErrorCode::Other`].
    pub fn from_wire(code: &str) -> Self {
        match code {
            "out_of_credits" => Self::OutOfCredits,
            "rate_limit" => Self::RateLimit,
            "prompt_nsfw" => Self::PromptNsfw,
            "ip_detected" => Self::IpDetected,
            "job_failed" => Self::JobFailed,
            "timeout" => Self::Timeout,
            "validation" => Self::Validation,
            "confirmation_rejected" => Self::ConfirmationRejected,
            "canceled" => Self::Canceled,
            "job_not_cancellable" => Self::JobNotCancellable,
            "approval_required" => Self::ApprovalRequired,
            "run_ended" => Self::RunEnded,
            "session_busy" => Self::SessionBusy,
            "access_denied" => Self::AccessDenied,
            "insufficient_credits" => Self::InsufficientCredits,
            "backend_error" => Self::BackendError,
            other => Self::Other(other.to_owned()),
        }
    }

    /// The wire spelling.
    pub fn as_str(&self) -> &str {
        match self {
            Self::OutOfCredits => "out_of_credits",
            Self::RateLimit => "rate_limit",
            Self::PromptNsfw => "prompt_nsfw",
            Self::IpDetected => "ip_detected",
            Self::JobFailed => "job_failed",
            Self::Timeout => "timeout",
            Self::Validation => "validation",
            Self::ConfirmationRejected => "confirmation_rejected",
            Self::Canceled => "canceled",
            Self::JobNotCancellable => "job_not_cancellable",
            Self::ApprovalRequired => "approval_required",
            Self::RunEnded => "run_ended",
            Self::SessionBusy => "session_busy",
            Self::AccessDenied => "access_denied",
            Self::InsufficientCredits => "insufficient_credits",
            Self::BackendError => "backend_error",
            Self::Other(code) => code,
        }
    }
}

impl fmt::Display for ErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A refusal from the API: a non-2xx response, usually an RFC 7807 problem.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ApiError {
    /// The HTTP status.
    pub status: u16,
    /// The problem's machine-readable `code`, when it has one.
    pub code: Option<ErrorCode>,
    /// The problem's short `title` (for example `Upgrade Required`).
    pub title: Option<String>,
    /// The human-readable `detail`: show it, never parse it.
    pub detail: Option<String>,
    /// On a `409` duplicate submission: the job that already exists.
    pub job_id: Option<Uuid>,
    /// Quote this to support.
    pub request_id: Option<String>,
    /// The server's `Retry-After`, when it sent one.
    pub retry_after: Option<Duration>,
    /// The decoded body, when it was JSON.
    pub body: Option<Value>,
}

impl ApiError {
    pub(crate) fn from_parts(status: u16, retry_after: Option<Duration>, body: &[u8]) -> Self {
        let json: Option<Value> = serde_json::from_slice(body).ok();
        let text = |key: &str| {
            json.as_ref()
                .and_then(|v| v.get(key))
                .and_then(Value::as_str)
                .filter(|s| !s.is_empty())
                .map(str::to_owned)
        };
        let detail = text("detail").or_else(|| {
            // A non-JSON body (a load balancer page) still says something.
            let raw = String::from_utf8_lossy(body).trim().to_owned();
            (json.is_none() && !raw.is_empty()).then(|| raw.chars().take(300).collect())
        });
        Self {
            status,
            code: text("code").map(|c| ErrorCode::from_wire(&c)),
            title: text("title"),
            detail,
            job_id: text("job_id").and_then(|id| Uuid::parse_str(&id).ok()),
            request_id: text("request_id"),
            retry_after,
            body: json,
        }
    }

    /// The wallet (or an organization member budget) cannot pay: `402` with
    /// `out_of_credits`, the agent's `insufficient_credits`, or `Budget Exceeded`.
    /// Topping up fixes it; upgrading the plan does not.
    pub fn is_out_of_credits(&self) -> bool {
        matches!(
            self.code,
            Some(ErrorCode::OutOfCredits | ErrorCode::InsufficientCredits)
        ) || (self.status == 402 && self.title.as_deref() == Some("Budget Exceeded"))
    }

    /// The account's plan does not include this (`402 Upgrade Required`), for
    /// example a model published for Pro and above. Adding credits does not fix it.
    pub fn is_plan_required(&self) -> bool {
        self.status == 402 && self.title.as_deref() == Some("Upgrade Required")
    }

    /// Refused for now: `429`, or the `rate_limit` code. The same request will
    /// be accepted later; [`retry_after`](Self::retry_after) says when, if known.
    pub fn is_rate_limited(&self) -> bool {
        self.status == 429 || self.code == Some(ErrorCode::RateLimit)
    }

    /// A `409` refusing a repeat of a submission accepted in the last five
    /// minutes; [`job_id`](Self::job_id) names the job that exists. Send a
    /// distinct `Idempotency-Key` to declare a deliberate new generation.
    pub fn is_duplicate_submission(&self) -> bool {
        self.status == 409 && self.code.is_none() && self.job_id.is_some()
    }

    /// The credential is missing, invalid or expired (`401`).
    pub fn is_unauthorized(&self) -> bool {
        self.status == 401
    }

    /// Not found, or not yours (`404`).
    pub fn is_not_found(&self) -> bool {
        self.status == 404
    }
}

impl fmt::Display for ApiError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "HTTP {}", self.status)?;
        if let Some(title) = &self.title {
            write!(f, " {title}")?;
        }
        if let Some(code) = &self.code {
            write!(f, " ({code})")?;
        }
        if let Some(detail) = &self.detail {
            write!(f, ": {detail}")?;
        }
        if let Some(job) = &self.job_id {
            write!(f, " [job {job}]")?;
        }
        if let Some(request) = &self.request_id {
            write!(f, " [request {request}]")?;
        }
        Ok(())
    }
}

/// A job that reached `failed` or `canceled`.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct JobError {
    /// The job.
    pub job_id: Uuid,
    /// `failed` or `canceled`.
    pub status: String,
    /// `failure.code`, `canceled` for a canceled job, else derived (`job_failed`,
    /// or `prompt_nsfw` for a moderated failure without a code).
    pub code: ErrorCode,
    /// `failure.kind` (`moderated`, `error`, ...) or `canceled`.
    pub kind: String,
    /// The customer-facing reason (`failure.message`, or the cancellation's message).
    pub message: String,
    /// What the ledger did: `Some(true)` refunded, `Some(false)` charged,
    /// `None` unknown. Never read `None` as "no charge".
    pub credits_refunded: Option<bool>,
    /// The terminal job, as the API returned it.
    pub job: Box<types::Job>,
}

impl JobError {
    pub(crate) fn from_job(job: &types::Job) -> Self {
        if job.status == "canceled" {
            let cancellation = job.cancellation.as_ref();
            let refunded = cancellation.and_then(|c| match c.settlement.as_str() {
                "refunded" => Some(true),
                "charged" => Some(false),
                _ => None,
            });
            return Self {
                job_id: job.id,
                status: job.status.clone(),
                code: ErrorCode::Canceled,
                kind: "canceled".into(),
                message: cancellation
                    .map(|c| c.message.clone())
                    .filter(|m| !m.is_empty())
                    .or_else(|| job.status_message.clone())
                    .unwrap_or_else(|| "the job was canceled".into()),
                credits_refunded: refunded,
                job: Box::new(job.clone()),
            };
        }
        let failure = job.failure.as_ref();
        let kind = failure
            .map(|f| f.kind.clone())
            .unwrap_or_else(|| "error".into());
        let code = failure
            .and_then(|f| f.code.as_deref())
            .or_else(|| job.error.as_ref().and_then(|e| e.code.as_deref()))
            .filter(|c| !c.is_empty())
            .map(ErrorCode::from_wire)
            .unwrap_or(if kind == "moderated" {
                ErrorCode::PromptNsfw
            } else {
                ErrorCode::JobFailed
            });
        let message = failure
            .map(|f| f.message.clone())
            .or_else(|| job.error.as_ref().and_then(|e| e.detail.clone()))
            .unwrap_or_else(|| "generation failed".into());
        Self {
            job_id: job.id,
            status: job.status.clone(),
            code,
            kind,
            message,
            credits_refunded: failure.and_then(|f| f.credits_refunded),
            job: Box::new(job.clone()),
        }
    }

    /// A provider's content filter blocked it (`failure.kind == "moderated"`).
    pub fn is_moderated(&self) -> bool {
        self.kind == "moderated"
    }
}

impl fmt::Display for JobError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "job {} {} ({}): {}",
            self.job_id, self.status, self.code, self.message
        )
    }
}

/// Every way an SDK call can fail.
#[non_exhaustive]
#[derive(Debug)]
pub enum Error {
    /// The API refused the request (a non-2xx response).
    Api(Box<ApiError>),
    /// The job finished `failed` or `canceled`.
    Job(Box<JobError>),
    /// A wait ran out of time. The job is NOT canceled and keeps running (and
    /// is billed); wait again, or cancel it.
    Timeout {
        /// The job still running, when there is one.
        job_id: Option<Uuid>,
    },
    /// The request never got a response (DNS, TLS, connection, timeout).
    /// The URL is stripped: signed URLs carry credentials in the query string.
    Transport(reqwest::Error),
    /// A success response whose body did not decode.
    Decode {
        /// The HTTP status of the response.
        status: Option<u16>,
        /// What went wrong.
        message: String,
    },
    /// The client could not be built (missing API key, bad header value, ...).
    Config(String),
    /// A request the SDK refused to send (for example a request builder with
    /// a missing required field).
    InvalidRequest(String),
    /// A file could not be read or written.
    Io {
        /// The path involved.
        path: PathBuf,
        /// The filesystem error.
        source: std::io::Error,
    },
}

impl Error {
    /// The API's machine-readable code, from a refusal or a failed job.
    pub fn code(&self) -> Option<&ErrorCode> {
        match self {
            Self::Api(err) => err.code.as_ref(),
            Self::Job(err) => Some(&err.code),
            Self::Timeout { .. } => Some(&ErrorCode::Timeout),
            _ => None,
        }
    }

    /// The HTTP status of a refusal.
    pub fn status(&self) -> Option<u16> {
        match self {
            Self::Api(err) => Some(err.status),
            Self::Decode { status, .. } => *status,
            _ => None,
        }
    }

    /// The refusal, when this is one.
    pub fn as_api(&self) -> Option<&ApiError> {
        match self {
            Self::Api(err) => Some(err.as_ref()),
            _ => None,
        }
    }

    /// The failed or canceled job, when this is one.
    pub fn as_job(&self) -> Option<&JobError> {
        match self {
            Self::Job(err) => Some(err.as_ref()),
            _ => None,
        }
    }

    /// See [`ApiError::is_out_of_credits`]; also true for a job that failed
    /// with `out_of_credits`.
    pub fn is_out_of_credits(&self) -> bool {
        match self {
            Self::Api(err) => err.is_out_of_credits(),
            Self::Job(err) => err.code == ErrorCode::OutOfCredits,
            _ => false,
        }
    }

    /// See [`ApiError::is_plan_required`].
    pub fn is_plan_required(&self) -> bool {
        self.as_api().is_some_and(ApiError::is_plan_required)
    }

    /// See [`ApiError::is_rate_limited`].
    pub fn is_rate_limited(&self) -> bool {
        self.as_api().is_some_and(ApiError::is_rate_limited)
    }

    pub(crate) fn transport(err: reqwest::Error) -> Self {
        Self::Transport(err.without_url())
    }

    pub(crate) fn decode(status: Option<u16>, message: impl fmt::Display) -> Self {
        Self::Decode {
            status,
            message: message.to_string(),
        }
    }

    /// Read a non-2xx response into [`Error::Api`].
    pub(crate) async fn from_response(response: reqwest::Response) -> Self {
        let status = response.status().as_u16();
        let retry_after = crate::transport::retry_after(&response);
        match response.bytes().await {
            Ok(body) => Self::Api(Box::new(ApiError::from_parts(status, retry_after, &body))),
            Err(_) => Self::Api(Box::new(ApiError::from_parts(status, retry_after, &[]))),
        }
    }

    /// Convert an error from a generated (`api`) call, reading the refusal
    /// body when there is one. [`crate::Typed::typed`] does this for you.
    pub async fn from_api(err: progenitor_client::Error<()>) -> Self {
        use progenitor_client::Error as E;
        match err {
            E::UnexpectedResponse(response) => Self::from_response(response).await,
            E::ErrorResponse(value) => Self::Api(Box::new(ApiError {
                status: value.status().as_u16(),
                code: None,
                title: None,
                detail: None,
                job_id: None,
                request_id: None,
                retry_after: None,
                body: None,
            })),
            E::CommunicationError(err) | E::ResponseBodyError(err) => Self::transport(err),
            E::InvalidResponsePayload(bytes, err) => {
                let _ = bytes;
                Self::decode(None, err)
            }
            E::InvalidRequest(message) => Self::InvalidRequest(message),
            E::InvalidUpgrade(err) => Self::transport(err),
            E::Custom(message) => Self::InvalidRequest(message),
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Api(err) => write!(f, "{err}"),
            Self::Job(err) => write!(f, "{err}"),
            Self::Timeout { job_id: Some(id) } => write!(
                f,
                "timed out waiting for job {id}; it is still running and was not canceled"
            ),
            Self::Timeout { job_id: None } => write!(f, "timed out"),
            Self::Transport(err) => write!(f, "request failed: {err}"),
            Self::Decode { status, message } => match status {
                Some(status) => write!(f, "could not decode the HTTP {status} response: {message}"),
                None => write!(f, "could not decode the response: {message}"),
            },
            Self::Config(message) => f.write_str(message),
            Self::InvalidRequest(message) => write!(f, "invalid request: {message}"),
            Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Transport(err) => Some(err),
            Self::Io { source, .. } => Some(source),
            _ => None,
        }
    }
}

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

    #[test]
    fn problem_body_maps_to_typed_fields() {
        let body = br#"{"type":"about:blank","title":"Payment Required","status":402,
            "detail":"The available credits cannot cover this generation.","code":"out_of_credits",
            "request_id":"req_1"}"#;
        let err = ApiError::from_parts(402, None, body);
        assert_eq!(err.code, Some(ErrorCode::OutOfCredits));
        assert!(err.is_out_of_credits());
        assert!(!err.is_plan_required());
        assert_eq!(err.request_id.as_deref(), Some("req_1"));
        assert!(err.to_string().contains("out_of_credits"));
    }

    #[test]
    fn plan_refusal_is_not_a_balance_refusal() {
        let body = br#"{"type":"about:blank","title":"Upgrade Required","status":402,"detail":"a plan limit"}"#;
        let err = ApiError::from_parts(402, None, body);
        assert!(err.is_plan_required());
        assert!(!err.is_out_of_credits());
    }

    #[test]
    fn duplicate_submission_names_the_job() {
        let id = Uuid::new_v4();
        let body = format!(
            r#"{{"type":"about:blank","title":"Conflict","status":409,"detail":"already","job_id":"{id}"}}"#
        );
        let err = ApiError::from_parts(409, None, body.as_bytes());
        assert!(err.is_duplicate_submission());
        assert_eq!(err.job_id, Some(id));
    }

    #[test]
    fn unknown_codes_pass_through_verbatim() {
        assert_eq!(
            ErrorCode::from_wire("brand_new"),
            ErrorCode::Other("brand_new".into())
        );
        assert_eq!(ErrorCode::from_wire("brand_new").as_str(), "brand_new");
        for code in [
            "approval_required",
            "run_ended",
            "session_busy",
            "insufficient_credits",
        ] {
            assert_eq!(ErrorCode::from_wire(code).as_str(), code);
            assert!(!matches!(ErrorCode::from_wire(code), ErrorCode::Other(_)));
        }
    }

    #[test]
    fn non_json_body_keeps_some_text() {
        let err = ApiError::from_parts(502, None, b"<html>bad gateway</html>");
        assert_eq!(err.detail.as_deref(), Some("<html>bad gateway</html>"));
        assert!(err.code.is_none());
    }
}