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
//! Hand-written. The [`Client`] and how to build one.

use std::{future::Future, ops::Deref, time::Duration};

use progenitor_client::{ClientInfo, ResponseValue};
use reqwest::header::{AUTHORIZATION, HeaderMap, HeaderName, HeaderValue, USER_AGENT};

use crate::{
    api,
    error::{Error, Result},
    transport::{Inner, RetryPolicy},
};

/// The production API.
pub const DEFAULT_BASE_URL: &str = "https://api.nolgia.ai/v1";
/// The staging API. Staging keys are minted on stg.nolgia.ai and do not work
/// against production.
pub const STAGING_BASE_URL: &str = "https://api.stg.nolgia.ai/v1";

/// The environment variable [`Client::from_env`] reads the API key from.
pub const API_KEY_ENV: &str = "NOLGIA_API_KEY";
/// Also accepted for the API key, as the CLI and the other SDKs' examples use it.
pub const TOKEN_ENV: &str = "NOLGIA_TOKEN";
/// The environment variable [`Client::from_env`] reads the base URL from.
pub const BASE_URL_ENV: &str = "NOLGIA_BASE_URL";

const SURFACE_HEADER: HeaderName = HeaderName::from_static("x-nolgia-surface");

/// A Nolgia API client.
///
/// Cheap to clone (the HTTP connection pool is shared). It dereferences to the
/// generated [`api::Client`], so every endpoint in the API reference is a
/// method on it, with a builder for its parameters:
///
/// ```no_run
/// # async fn run() -> nolgia::Result<()> {
/// use nolgia::Typed;
///
/// let nolgia = nolgia::Client::from_env()?;
/// let me = nolgia.get_current_user().send().typed().await?;
/// println!("signed in as {}", me.email);
/// # Ok(()) }
/// ```
///
/// The hand-written helpers ([`submit`](Client::submit),
/// [`subscribe`](Client::subscribe), [`wait_job`](Client::wait_job),
/// [`upload_file`](Client::upload_file), [`download`](Client::download),
/// [`paginate_assets`](Client::paginate_assets),
/// [`run_agent`](Client::run_agent), the event streams) sit beside them.
#[derive(Debug, Clone)]
pub struct Client {
    pub(crate) api: api::Client,
    /// For URLs that are not the API: signed storage URLs carry their own
    /// credential, and a bearer token that can spend money must never go there.
    pub(crate) anon: reqwest::Client,
}

impl Deref for Client {
    type Target = api::Client;

    fn deref(&self) -> &api::Client {
        &self.api
    }
}

impl Client {
    /// A production client authenticated with `api_key` (a personal access
    /// token `nol_...`, an organization key, or a JWT).
    pub fn new(api_key: impl Into<String>) -> Result<Self> {
        Self::builder().api_key(api_key).build()
    }

    /// A client from the environment: the key from `NOLGIA_API_KEY` (or
    /// `NOLGIA_TOKEN`), and the base URL from `NOLGIA_BASE_URL` when set.
    pub fn from_env() -> Result<Self> {
        ClientBuilder::from_env()?.build()
    }

    /// A builder for every other option.
    pub fn builder() -> ClientBuilder {
        ClientBuilder::default()
    }

    /// The generated client: one method per API operation.
    pub fn api(&self) -> &api::Client {
        &self.api
    }

    /// The base URL every request goes to, ending in `/v1`.
    pub fn base_url(&self) -> &str {
        self.api.baseurl()
    }

    /// A clone of this client that sends `Idempotency-Key: <key>` on every
    /// `POST`.
    ///
    /// The API refuses a repeat of an identical generation submitted in the
    /// last five minutes with `409` naming the existing job, so a lost
    /// response never turns into a second charge. A distinct key declares a
    /// deliberate new generation of the same request; repeating a key makes
    /// your own retries collapse onto one job.
    pub fn with_idempotency_key(&self, key: impl AsRef<str>) -> Result<Self> {
        let value = HeaderValue::from_str(key.as_ref()).map_err(|_| {
            Error::Config(format!(
                "idempotency key {:?} is not a valid header value",
                key.as_ref()
            ))
        })?;
        let mut inner = self.api.inner().clone();
        inner.idempotency_key = Some(value);
        Ok(self.rebuild(inner))
    }

    /// A clone of this client with a different retry policy.
    pub fn with_retry(&self, retry: RetryPolicy) -> Self {
        let mut inner = self.api.inner().clone();
        inner.retry = retry;
        self.rebuild(inner)
    }

    fn rebuild(&self, inner: Inner) -> Self {
        Self {
            api: api::Client::new_with_client(self.api.baseurl(), self.api.client().clone(), inner),
            anon: self.anon.clone(),
        }
    }

    pub(crate) fn url(&self, path: &str) -> String {
        format!("{}{path}", self.api.baseurl())
    }

    pub(crate) fn http(&self) -> &reqwest::Client {
        self.api.client()
    }

    pub(crate) fn inner(&self) -> &Inner {
        self.api.inner()
    }

    /// Send a hand-built request to the API through the retrying transport.
    /// Non-2xx answers become [`Error::Api`].
    pub(crate) async fn send(
        &self,
        request: reqwest::RequestBuilder,
        operation: &str,
    ) -> Result<reqwest::Response> {
        let request = request.build().map_err(Error::transport)?;
        let response =
            crate::transport::execute(self.api.client(), self.inner(), request, operation)
                .await
                .map_err(Error::transport)?;
        if response.status().is_success() {
            Ok(response)
        } else {
            Err(Error::from_response(response).await)
        }
    }

    pub(crate) async fn send_json<T: serde::de::DeserializeOwned>(
        &self,
        request: reqwest::RequestBuilder,
        operation: &str,
    ) -> Result<T> {
        let response = self.send(request, operation).await?;
        decode(response).await
    }
}

pub(crate) async fn decode<T: serde::de::DeserializeOwned>(
    response: reqwest::Response,
) -> Result<T> {
    let status = response.status().as_u16();
    let bytes = response.bytes().await.map_err(Error::transport)?;
    serde_json::from_slice(&bytes).map_err(|err| Error::decode(Some(status), err))
}

/// Configures a [`Client`].
#[derive(Debug, Clone)]
pub struct ClientBuilder {
    api_key: Option<String>,
    base_url: String,
    timeout: Duration,
    connect_timeout: Duration,
    retry: RetryPolicy,
    surface: Option<String>,
    idempotency_key: Option<String>,
    user_agent: Option<String>,
    headers: HeaderMap,
    invalid_header: Option<String>,
}

impl Default for ClientBuilder {
    fn default() -> Self {
        Self {
            api_key: None,
            base_url: DEFAULT_BASE_URL.to_owned(),
            timeout: Duration::from_secs(120),
            connect_timeout: Duration::from_secs(15),
            retry: RetryPolicy::default(),
            surface: None,
            idempotency_key: None,
            user_agent: None,
            headers: HeaderMap::new(),
            invalid_header: None,
        }
    }
}

impl ClientBuilder {
    /// A builder reading `NOLGIA_API_KEY` (or `NOLGIA_TOKEN`) and, when set,
    /// `NOLGIA_BASE_URL`. Fails when no key is set.
    pub fn from_env() -> Result<Self> {
        let non_empty = |name: &str| std::env::var(name).ok().filter(|v| !v.trim().is_empty());
        let key = non_empty(API_KEY_ENV)
            .or_else(|| non_empty(TOKEN_ENV))
            .ok_or_else(|| {
                Error::Config(format!(
                    "{API_KEY_ENV} is not set: create an API key at \
                     https://nolgia.com/settings/api-tokens and export it, or build the \
                     client with nolgia::Client::new(key)"
                ))
            })?;
        let mut builder = Self::default().api_key(key);
        if let Some(url) = non_empty(BASE_URL_ENV) {
            builder = builder.base_url(url);
        }
        Ok(builder)
    }

    /// The API key: a personal access token (`nol_...`), an organization key,
    /// or a JWT. Sent as `Authorization: Bearer <key>`.
    pub fn api_key(mut self, key: impl Into<String>) -> Self {
        self.api_key = Some(key.into());
        self
    }

    /// The API server. `/v1` is appended when missing. Default
    /// [`DEFAULT_BASE_URL`]; [`STAGING_BASE_URL`] for staging.
    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = url.into();
        self
    }

    /// The whole-request timeout for ordinary calls. Default 120 s. Long polls
    /// (`wait_job`) set their own, longer, per-request timeout.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// The connection timeout. Default 15 s.
    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
        self.connect_timeout = timeout;
        self
    }

    /// The retry policy. Default [`RetryPolicy::default`]; [`RetryPolicy::none`]
    /// turns retries off.
    pub fn retry(mut self, retry: RetryPolicy) -> Self {
        self.retry = retry;
        self
    }

    /// Shorthand for the retry count, keeping the default delays.
    pub fn max_retries(mut self, retries: u32) -> Self {
        self.retry.max_retries = retries;
        self
    }

    /// Identify the calling surface (sent as `X-Nolgia-Surface`), for an
    /// integration that wants its traffic recognised. Optional.
    pub fn surface(mut self, surface: impl Into<String>) -> Self {
        self.surface = Some(surface.into());
        self
    }

    /// Send this `Idempotency-Key` on every `POST`. See
    /// [`Client::with_idempotency_key`] for a per-call key.
    pub fn idempotency_key(mut self, key: impl Into<String>) -> Self {
        self.idempotency_key = Some(key.into());
        self
    }

    /// Send this header on every API request (for example `X-Request-Id`).
    /// It is never sent to the storage hosts behind signed URLs. Fails at
    /// [`build`](Self::build) if the name or value is not a valid header.
    pub fn header(mut self, name: &str, value: &str) -> Self {
        match (
            HeaderName::from_bytes(name.as_bytes()),
            HeaderValue::from_str(value),
        ) {
            (Ok(name), Ok(value)) => {
                self.headers.insert(name, value);
            }
            _ => self.invalid_header = Some(name.to_owned()),
        }
        self
    }

    /// Append to the `User-Agent` (`nolgia-rust/<version> <yours>`).
    pub fn user_agent(mut self, product: impl Into<String>) -> Self {
        self.user_agent = Some(product.into());
        self
    }

    /// Build the client.
    pub fn build(self) -> Result<Client> {
        if let Some(name) = &self.invalid_header {
            return Err(Error::Config(format!(
                "header {name:?} is not a valid header"
            )));
        }
        let key = self
            .api_key
            .filter(|k| !k.trim().is_empty())
            .ok_or_else(|| {
                Error::Config("an API key is required: ClientBuilder::api_key".into())
            })?;
        let mut auth = HeaderValue::from_str(&format!("Bearer {}", key.trim()))
            .map_err(|_| Error::Config("the API key is not a valid header value".into()))?;
        auth.set_sensitive(true);

        let agent = match &self.user_agent {
            Some(extra) => format!("nolgia-rust/{} {extra}", env!("CARGO_PKG_VERSION")),
            None => format!("nolgia-rust/{}", env!("CARGO_PKG_VERSION")),
        };
        let agent = HeaderValue::from_str(&agent)
            .map_err(|_| Error::Config("the user agent is not a valid header value".into()))?;

        let mut headers = self.headers.clone();
        headers.insert(AUTHORIZATION, auth);
        headers.insert(USER_AGENT, agent.clone());
        if let Some(surface) = &self.surface {
            let value = HeaderValue::from_str(surface)
                .map_err(|_| Error::Config("the surface is not a valid header value".into()))?;
            headers.insert(SURFACE_HEADER, value);
        }
        let idempotency_key = self
            .idempotency_key
            .map(|key| {
                HeaderValue::from_str(&key).map_err(|_| {
                    Error::Config(format!(
                        "idempotency key {key:?} is not a valid header value"
                    ))
                })
            })
            .transpose()?;

        let http = reqwest::Client::builder()
            .default_headers(headers)
            .timeout(self.timeout)
            .connect_timeout(self.connect_timeout)
            .build()
            .map_err(|err| Error::Config(format!("could not build the HTTP client: {err}")))?;
        let anon = reqwest::Client::builder()
            .user_agent(agent)
            .connect_timeout(self.connect_timeout)
            .build()
            .map_err(|err| Error::Config(format!("could not build the HTTP client: {err}")))?;

        let inner = Inner {
            retry: self.retry,
            idempotency_key,
        };
        Ok(Client {
            api: api::Client::new_with_client(&normalize_base_url(&self.base_url), http, inner),
            anon,
        })
    }
}

pub(crate) fn normalize_base_url(base_url: &str) -> String {
    let trimmed = base_url.trim().trim_end_matches('/');
    if trimmed.ends_with("/v1") {
        trimmed.to_owned()
    } else {
        format!("{trimmed}/v1")
    }
}

/// Turns a generated call's result into `nolgia::Result<T>`: the response
/// body, or a typed [`Error`] whose [`ApiError`](crate::ApiError) carries the
/// problem's status, `code`, `detail` and `request_id`.
///
/// ```no_run
/// # async fn run(nolgia: nolgia::Client) -> nolgia::Result<()> {
/// use nolgia::Typed;
///
/// let models = nolgia.list_models().send().typed().await?;
/// # Ok(()) }
/// ```
pub trait Typed<T> {
    /// Await the call and convert its result.
    fn typed(self) -> impl Future<Output = Result<T>> + Send;
}

impl<F, T> Typed<T> for F
where
    F: Future<Output = std::result::Result<ResponseValue<T>, progenitor_client::Error<()>>> + Send,
    T: Send,
{
    async fn typed(self) -> Result<T> {
        match self.await {
            Ok(value) => Ok(value.into_inner()),
            Err(err) => Err(Error::from_api(err).await),
        }
    }
}

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

    #[test]
    fn base_url_gets_v1_once() {
        assert_eq!(
            normalize_base_url("https://api.nolgia.ai"),
            DEFAULT_BASE_URL
        );
        assert_eq!(
            normalize_base_url("https://api.nolgia.ai/v1/"),
            DEFAULT_BASE_URL
        );
        assert_eq!(
            normalize_base_url("http://localhost:8080"),
            "http://localhost:8080/v1"
        );
    }

    #[test]
    fn builder_requires_a_key() {
        let err = Client::builder().build().unwrap_err();
        assert!(err.to_string().contains("API key"));
        assert!(Client::new("nol_x").is_ok());
    }

    #[test]
    fn custom_headers_are_validated() {
        assert!(
            Client::builder()
                .api_key("k")
                .header("x-request-id", "r1")
                .build()
                .is_ok()
        );
        assert!(
            Client::builder()
                .api_key("k")
                .header("bad name", "v")
                .build()
                .is_err()
        );
    }

    #[test]
    fn idempotency_clone_keeps_the_original_untouched() {
        let client = Client::new("nol_x").unwrap();
        let keyed = client.with_idempotency_key("abc").unwrap();
        assert!(client.inner().idempotency_key.is_none());
        assert_eq!(keyed.inner().idempotency_key.as_ref().unwrap(), "abc");
        assert!(client.with_idempotency_key("bad\nkey").is_err());
    }
}