bibby 0.1.0

The official Rust SDK for Bytebury — typed clients, smart .env initialization, and ergonomic macros for Geo, Images, PDF, Mailer, Uploader, Cron, Forms, Webhooks, Monitors, and Vault.
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
//! Core [`Bibby`] client and [`BibbyBuilder`].

use std::fmt;
use std::sync::Arc;
use std::time::Duration;

use reqwest::header::{
    AUTHORIZATION, CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue, USER_AGENT,
};
use reqwest::{Method, Response};
use serde::Serialize;
use serde::de::DeserializeOwned;

use crate::error::{Error, Result, parse_api_error};
use crate::services::{
    CronClient, FormsClient, GeoClient, ImagesClient, MailerClient, MonitorsClient, PdfClient,
    UploaderClient, VaultClient, WebhooksClient,
};

/// Default base URL for the Bytebury public API gateway.
pub const DEFAULT_BASE_URL: &str = "https://api.bytebury.com";

/// Default environment variable read by [`Bibby::init`].
pub const API_TOKEN_ENV: &str = "BYTEBURY_API_TOKEN";

/// Optional environment variable checked by [`Bibby::init`] to override [`DEFAULT_BASE_URL`].
pub const API_URL_ENV: &str = "BYTEBURY_API_URL";

const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60);
const DEFAULT_USER_AGENT: &str = concat!("bibby/", env!("CARGO_PKG_VERSION"));

/// Wrapper that keeps API tokens out of [`Debug`] output.
#[derive(Clone)]
struct ApiToken(String);

impl fmt::Debug for ApiToken {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("ApiToken(\"***\")")
    }
}

#[derive(Debug)]
struct ClientInner {
    http: reqwest::Client,
    token: ApiToken,
    base_url: String,
}

/// The main Bytebury SDK client.
///
/// `Bibby` is cheaply cloneable (backed by an [`Arc`]) and safe to share across
/// async tasks and HTTP handlers (for example, inside Axum state).
///
/// # Quick start
///
/// ```no_run
/// use bibby::Bibby;
///
/// # async fn example() -> bibby::Result<()> {
/// // Loads `.env` (if present) and reads `BYTEBURY_API_TOKEN`:
/// let client = Bibby::init()?;
///
/// let location = client.geo().lookup("8.8.8.8").await?;
/// println!("{} ({})", location.country.name, location.country.code);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct Bibby {
    inner: Arc<ClientInner>,
}

impl Bibby {
    /// Initializes a [`Bibby`] client from the environment, automatically
    /// loading a local `.env` file if one exists.
    ///
    /// - Reads the API key from [`BYTEBURY_API_TOKEN`](API_TOKEN_ENV).
    /// - Optionally reads a custom base URL from [`BYTEBURY_API_URL`](API_URL_ENV)
    ///   (defaults to `https://api.bytebury.com`).
    ///
    /// Missing `.env` files are silently ignored so production environments
    /// that inject variables directly work without changes.
    ///
    /// # Errors
    ///
    /// Returns [`Error::MissingApiToken`] if `BYTEBURY_API_TOKEN` is unset or empty.
    pub fn init() -> Result<Self> {
        Self::from_env_var(API_TOKEN_ENV)
    }

    /// Initializes a [`Bibby`] client by loading `.env` (if present) and reading
    /// the API token from `env_var`.
    ///
    /// Also respects [`BYTEBURY_API_URL`](API_URL_ENV) if set.
    pub fn from_env_var(env_var: &str) -> Result<Self> {
        let _ = dotenvy::dotenv();

        let token = std::env::var(env_var)
            .ok()
            .map(|v| v.trim().to_string())
            .filter(|v| !v.is_empty())
            .ok_or_else(|| Error::MissingApiToken {
                env_var: env_var.to_string(),
            })?;

        let mut builder = Self::builder().api_token(token);

        if let Ok(url) = std::env::var(API_URL_ENV) {
            let trimmed = url.trim();
            if !trimmed.is_empty() {
                builder = builder.base_url(trimmed);
            }
        }

        builder.build()
    }

    /// Creates a [`Bibby`] client directly from an explicit API token.
    ///
    /// # Example
    ///
    /// ```
    /// use bibby::Bibby;
    ///
    /// let client = Bibby::new("bb_live_example_token")?;
    /// # Ok::<(), bibby::Error>(())
    /// ```
    pub fn new(api_token: impl Into<String>) -> Result<Self> {
        Self::builder().api_token(api_token).build()
    }

    /// Returns a [`BibbyBuilder`] for fine-grained configuration (custom base URL,
    /// timeout, user agent, or custom `reqwest::Client`).
    pub fn builder() -> BibbyBuilder {
        BibbyBuilder::default()
    }

    /// Returns the configured API base URL (without trailing slash).
    pub fn base_url(&self) -> &str {
        &self.inner.base_url
    }

    /// Access **Bytebury Geo** (IP geolocation, random IPs, corrections).
    pub fn geo(&self) -> GeoClient<'_> {
        GeoClient::new(self)
    }

    /// Access **Bytebury Images** (resize, transform, background removal, vectorize, analyze, icons, compare, QR codes).
    pub fn images(&self) -> ImagesClient<'_> {
        ImagesClient::new(self)
    }

    /// Access **Bytebury PDF** (HTML/CSS and URL to PDF rendering).
    pub fn pdf(&self) -> PdfClient<'_> {
        PdfClient::new(self)
    }

    /// Access **Bytebury Mailer** (transactional email sending & address validation).
    pub fn mailer(&self) -> MailerClient<'_> {
        MailerClient::new(self)
    }

    /// Access **Bytebury Uploader** (file storage, signed URLs, share links, one-time upload links).
    pub fn uploader(&self) -> UploaderClient<'_> {
        UploaderClient::new(self)
    }

    /// Access **Bytebury Cron** (scheduled HTTP jobs, manual runs, schedule previews).
    pub fn cron(&self) -> CronClient<'_> {
        CronClient::new(self)
    }

    /// Access **Bytebury Forms** (form endpoints, submissions, CSV export).
    pub fn forms(&self) -> FormsClient<'_> {
        FormsClient::new(self)
    }

    /// Access **Bytebury Webhooks** (endpoints, event publishing, deliveries, replay, signature verification).
    pub fn webhooks(&self) -> WebhooksClient<'_> {
        WebhooksClient::new(self)
    }

    /// Access **Bytebury Monitors** (uptime monitors, checks, status summaries, incidents, heartbeats).
    pub fn monitors(&self) -> MonitorsClient<'_> {
        MonitorsClient::new(self)
    }

    /// Access **Bytebury Vault** (encrypted secrets, `.env` import/export, versions, burn-after-reading shares).
    pub fn vault(&self) -> VaultClient<'_> {
        VaultClient::new(self)
    }

    // -------------------------------------------------------------------------
    // Internal HTTP helpers shared by all service clients
    // -------------------------------------------------------------------------

    pub(crate) fn url(&self, product: &str, path: &str) -> String {
        let path = path.trim_start_matches('/');
        format!("{}/{product}/v1/{path}", self.inner.base_url)
    }

    pub(crate) fn request(
        &self,
        method: Method,
        product: &str,
        path: &str,
    ) -> reqwest::RequestBuilder {
        self.inner
            .http
            .request(method, self.url(product, path))
            .header(AUTHORIZATION, format!("Bearer {}", self.inner.token.0))
    }

    pub(crate) async fn get_json<T: DeserializeOwned>(
        &self,
        product: &str,
        path: &str,
    ) -> Result<T> {
        let resp = self.request(Method::GET, product, path).send().await?;
        parse_json_response(resp).await
    }

    pub(crate) async fn get_json_query<Q: Serialize + ?Sized, T: DeserializeOwned>(
        &self,
        product: &str,
        path: &str,
        query: &Q,
    ) -> Result<T> {
        let resp = self
            .request(Method::GET, product, path)
            .query(query)
            .send()
            .await?;
        parse_json_response(resp).await
    }

    pub(crate) async fn get_text(&self, product: &str, path: &str) -> Result<String> {
        let resp = self.request(Method::GET, product, path).send().await?;
        parse_text_response(resp).await
    }

    pub(crate) async fn get_text_query<Q: Serialize + ?Sized>(
        &self,
        product: &str,
        path: &str,
        query: &Q,
    ) -> Result<String> {
        let resp = self
            .request(Method::GET, product, path)
            .query(query)
            .send()
            .await?;
        parse_text_response(resp).await
    }

    pub(crate) async fn post_json<B: Serialize + ?Sized, T: DeserializeOwned>(
        &self,
        product: &str,
        path: &str,
        body: &B,
    ) -> Result<T> {
        let resp = self
            .request(Method::POST, product, path)
            .json(body)
            .send()
            .await?;
        parse_json_response(resp).await
    }

    pub(crate) async fn post_json_with_headers<B: Serialize + ?Sized, T: DeserializeOwned>(
        &self,
        product: &str,
        path: &str,
        body: &B,
        headers: HeaderMap,
    ) -> Result<T> {
        let resp = self
            .request(Method::POST, product, path)
            .headers(headers)
            .json(body)
            .send()
            .await?;
        parse_json_response(resp).await
    }

    pub(crate) async fn post_empty<T: DeserializeOwned>(
        &self,
        product: &str,
        path: &str,
    ) -> Result<T> {
        let resp = self.request(Method::POST, product, path).send().await?;
        parse_json_response(resp).await
    }

    pub(crate) async fn post_empty_with_timeout<T: DeserializeOwned>(
        &self,
        product: &str,
        path: &str,
        timeout: Duration,
    ) -> Result<T> {
        let resp = self
            .request(Method::POST, product, path)
            .timeout(timeout)
            .send()
            .await?;
        parse_json_response(resp).await
    }

    pub(crate) async fn patch_json<B: Serialize + ?Sized, T: DeserializeOwned>(
        &self,
        product: &str,
        path: &str,
        body: &B,
    ) -> Result<T> {
        let resp = self
            .request(Method::PATCH, product, path)
            .json(body)
            .send()
            .await?;
        parse_json_response(resp).await
    }

    pub(crate) async fn delete_json<T: DeserializeOwned>(
        &self,
        product: &str,
        path: &str,
    ) -> Result<T> {
        let resp = self.request(Method::DELETE, product, path).send().await?;
        parse_json_response(resp).await
    }

    pub(crate) async fn delete_unit(&self, product: &str, path: &str) -> Result<()> {
        let resp = self.request(Method::DELETE, product, path).send().await?;
        let status = resp.status();
        if status.is_success() {
            Ok(())
        } else {
            let body = resp.bytes().await?;
            Err(parse_api_error(status.as_u16(), &body))
        }
    }

    pub(crate) async fn post_bytes_query<Q: Serialize + ?Sized, T: DeserializeOwned>(
        &self,
        product: &str,
        path: &str,
        query: &Q,
        bytes: Vec<u8>,
        content_type: Option<&str>,
        timeout: Duration,
    ) -> Result<T> {
        let mut req = self
            .request(Method::POST, product, path)
            .query(query)
            .timeout(timeout);

        if let Some(ct) = content_type {
            req = req.header(CONTENT_TYPE, ct);
        }

        let resp = req.body(bytes).send().await?;
        parse_json_response(resp).await
    }
}

pub(crate) fn header_pair(name: &'static str, value: &str) -> Result<HeaderMap> {
    let mut map = HeaderMap::new();
    let header_name = HeaderName::from_static(name);
    let header_value = HeaderValue::from_str(value)
        .map_err(|e| Error::InvalidConfig(format!("invalid header `{name}`: {e}")))?;
    map.insert(header_name, header_value);
    Ok(map)
}

async fn parse_json_response<T: DeserializeOwned>(resp: Response) -> Result<T> {
    let status = resp.status();
    let bytes = resp.bytes().await?;
    if !status.is_success() {
        return Err(parse_api_error(status.as_u16(), &bytes));
    }
    serde_json::from_slice(&bytes).map_err(Error::from)
}

async fn parse_text_response(resp: Response) -> Result<String> {
    let status = resp.status();
    let bytes = resp.bytes().await?;
    if !status.is_success() {
        return Err(parse_api_error(status.as_u16(), &bytes));
    }
    Ok(String::from_utf8_lossy(&bytes).into_owned())
}

/// Builder for customizing a [`Bibby`] client.
///
/// ```
/// use std::time::Duration;
/// use bibby::Bibby;
///
/// let client = Bibby::builder()
///     .api_token("bb_live_example_token")
///     .base_url("https://api.bytebury.com")
///     .timeout(Duration::from_secs(30))
///     .build()?;
/// # Ok::<(), bibby::Error>(())
/// ```
#[derive(Debug, Default)]
pub struct BibbyBuilder {
    api_token: Option<String>,
    base_url: Option<String>,
    timeout: Option<Duration>,
    user_agent: Option<String>,
    http_client: Option<reqwest::Client>,
}

impl BibbyBuilder {
    /// Sets the Bytebury API token (`bb_live_...`).
    pub fn api_token(mut self, token: impl Into<String>) -> Self {
        self.api_token = Some(token.into());
        self
    }

    /// Loads `.env` (if present) and reads `BYTEBURY_API_TOKEN` (and optionally
    /// `BYTEBURY_API_URL`) into this builder.
    pub fn from_env(mut self) -> Self {
        let _ = dotenvy::dotenv();
        if let Ok(token) = std::env::var(API_TOKEN_ENV) {
            let trimmed = token.trim();
            if !trimmed.is_empty() {
                self.api_token = Some(trimmed.to_string());
            }
        }
        if self.base_url.is_none()
            && let Ok(url) = std::env::var(API_URL_ENV)
        {
            let trimmed = url.trim();
            if !trimmed.is_empty() {
                self.base_url = Some(trimmed.to_string());
            }
        }
        self
    }

    /// Overrides the API gateway base URL (defaults to [`DEFAULT_BASE_URL`]).
    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = Some(url.into());
        self
    }

    /// Sets the default per-request HTTP timeout (defaults to 60 seconds).
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Sets a custom `User-Agent` header.
    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
        self.user_agent = Some(user_agent.into());
        self
    }

    /// Supplies a pre-configured [`reqwest::Client`].
    pub fn http_client(mut self, client: reqwest::Client) -> Self {
        self.http_client = Some(client);
        self
    }

    /// Builds the [`Bibby`] client.
    ///
    /// # Errors
    ///
    /// Returns [`Error::MissingApiToken`] if no API token was supplied, or
    /// [`Error::InvalidConfig`] if the base URL is empty or the HTTP client
    /// cannot be constructed.
    pub fn build(self) -> Result<Bibby> {
        let token = self
            .api_token
            .map(|t| t.trim().to_string())
            .filter(|t| !t.is_empty())
            .ok_or_else(|| Error::MissingApiToken {
                env_var: API_TOKEN_ENV.to_string(),
            })?;

        let base_url = self
            .base_url
            .unwrap_or_else(|| DEFAULT_BASE_URL.to_string())
            .trim()
            .trim_end_matches('/')
            .to_string();

        if base_url.is_empty()
            || (!base_url.starts_with("http://") && !base_url.starts_with("https://"))
        {
            return Err(Error::InvalidConfig(format!(
                "base URL must start with http:// or https://, got `{base_url}`"
            )));
        }

        let http = match self.http_client {
            Some(client) => client,
            None => {
                let mut headers = HeaderMap::new();
                let ua = self.user_agent.as_deref().unwrap_or(DEFAULT_USER_AGENT);
                let ua_value = HeaderValue::from_str(ua)
                    .map_err(|e| Error::InvalidConfig(format!("invalid User-Agent: {e}")))?;
                headers.insert(USER_AGENT, ua_value);

                reqwest::Client::builder()
                    .default_headers(headers)
                    .timeout(self.timeout.unwrap_or(DEFAULT_TIMEOUT))
                    .build()
                    .map_err(|e| {
                        Error::InvalidConfig(format!("failed to build HTTP client: {e}"))
                    })?
            }
        };

        Ok(Bibby {
            inner: Arc::new(ClientInner {
                http,
                token: ApiToken(token),
                base_url,
            }),
        })
    }
}