sprites 0.1.0

Official Rust SDK for Sprites - stateful sandbox environments from Fly.io
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
//! Sprites API client
//!
//! The main entry point for interacting with the Sprites API.

use crate::error::{Error, Result};
use crate::sprite::Sprite;
use crate::types::{
    CreateSpriteRequest, CreateSpriteResponse, ListOptions, ListSpritesResponse, SpriteConfig,
    SpriteInfo, UrlSettings,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::time::Duration;

/// Default API base URL
const DEFAULT_BASE_URL: &str = "https://api.sprites.dev";

/// Sprites API client
///
/// # Example
///
/// ```no_run
/// use sprites::SpritesClient;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let client = SpritesClient::new("your-token");
///
///     // List all sprites
///     let sprites = client.list().await?;
///     for sprite in sprites {
///         println!("{}: {:?}", sprite.name, sprite.status);
///     }
///
///     Ok(())
/// }
/// ```
#[derive(Clone)]
pub struct SpritesClient {
    inner: Arc<ClientInner>,
}

struct ClientInner {
    base_url: String,
    token: String,
    http: reqwest::Client,
}

impl SpritesClient {
    /// Create a new client with the given token
    ///
    /// # Example
    ///
    /// ```
    /// use sprites::SpritesClient;
    ///
    /// let client = SpritesClient::new("your-token");
    /// ```
    pub fn new(token: impl Into<String>) -> Self {
        Self::with_base_url(token, DEFAULT_BASE_URL)
    }

    /// Create a new client with a custom base URL
    ///
    /// # Example
    ///
    /// ```
    /// use sprites::SpritesClient;
    ///
    /// let client = SpritesClient::with_base_url("token", "https://custom.api.dev");
    /// ```
    pub fn with_base_url(token: impl Into<String>, base_url: impl Into<String>) -> Self {
        let token = token.into();
        let base_url = base_url.into().trim_end_matches('/').to_string();

        let http = reqwest::Client::new();

        Self {
            inner: Arc::new(ClientInner {
                base_url,
                token,
                http,
            }),
        }
    }

    /// Create a new client with a custom HTTP client
    ///
    /// This allows you to configure timeouts, retries, proxies, etc.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use sprites::SpritesClient;
    /// use std::time::Duration;
    ///
    /// let http = reqwest::Client::builder()
    ///     .timeout(Duration::from_secs(60))
    ///     .build()
    ///     .unwrap();
    ///
    /// let client = SpritesClient::with_http_client("token", http);
    /// ```
    pub fn with_http_client(token: impl Into<String>, http: reqwest::Client) -> Self {
        Self {
            inner: Arc::new(ClientInner {
                base_url: DEFAULT_BASE_URL.to_string(),
                token: token.into(),
                http,
            }),
        }
    }

    /// Create a builder for configuring the client
    ///
    /// # Example
    ///
    /// ```no_run
    /// use sprites::SpritesClient;
    /// use std::time::Duration;
    ///
    /// let client = SpritesClient::builder("your-token")
    ///     .base_url("https://custom.api.dev")
    ///     .timeout(Duration::from_secs(30))
    ///     .build();
    /// ```
    pub fn builder(token: impl Into<String>) -> SpritesClientBuilder {
        SpritesClientBuilder::new(token)
    }

    /// Create a Sprites token from a Fly.io macaroon
    ///
    /// This exchanges Fly.io credentials for a Sprites API token.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use sprites::SpritesClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let token = SpritesClient::create_token(
    ///         "your-fly-macaroon",
    ///         "your-org-slug",
    ///         None,
    ///     ).await?;
    ///
    ///     let client = SpritesClient::new(token);
    ///     Ok(())
    /// }
    /// ```
    pub async fn create_token(
        fly_macaroon: &str,
        org_slug: &str,
        invite_code: Option<&str>,
    ) -> Result<String> {
        Self::create_token_with_url(fly_macaroon, org_slug, invite_code, DEFAULT_BASE_URL).await
    }

    /// Create a Sprites token with a custom API URL
    ///
    /// # Example
    ///
    /// ```no_run
    /// use sprites::SpritesClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let token = SpritesClient::create_token_with_url(
    ///         "your-fly-macaroon",
    ///         "your-org-slug",
    ///         None,
    ///         "https://custom.api.dev",
    ///     ).await?;
    ///
    ///     let client = SpritesClient::new(token);
    ///     Ok(())
    /// }
    /// ```
    pub async fn create_token_with_url(
        fly_macaroon: &str,
        org_slug: &str,
        invite_code: Option<&str>,
        api_url: &str,
    ) -> Result<String> {
        let http = reqwest::Client::new();
        let url = format!("{}/v1/tokens", api_url.trim_end_matches('/'));

        let mut request = CreateTokenRequest {
            fly_macaroon: fly_macaroon.to_string(),
            org_slug: org_slug.to_string(),
            invite_code: None,
        };

        if let Some(code) = invite_code {
            request.invite_code = Some(code.to_string());
        }

        let response = http.post(&url).json(&request).send().await?;

        let status = response.status();
        if !status.is_success() {
            let message = response.text().await.unwrap_or_default();
            return Err(Error::api(status.as_u16(), message));
        }

        let token_response: CreateTokenResponse = response.json().await?;
        Ok(token_response.token)
    }

    /// Get the base URL
    pub fn base_url(&self) -> &str {
        &self.inner.base_url
    }

    /// Get the token
    pub fn token(&self) -> &str {
        &self.inner.token
    }

    /// Get the HTTP client
    pub(crate) fn http(&self) -> &reqwest::Client {
        &self.inner.http
    }

    /// Build a URL for an API endpoint
    pub(crate) fn url(&self, path: &str) -> String {
        format!("{}/v1{}", self.inner.base_url, path)
    }

    /// Get the authorization header value
    pub(crate) fn auth_header(&self) -> String {
        format!("Bearer {}", self.inner.token)
    }

    /// Get a sprite handle by name
    ///
    /// This does NOT create the sprite on the server. Use [`create`] to create a new sprite.
    ///
    /// # Example
    ///
    /// ```
    /// use sprites::SpritesClient;
    ///
    /// let client = SpritesClient::new("token");
    /// let sprite = client.sprite("my-sprite");
    /// ```
    pub fn sprite(&self, name: impl Into<String>) -> Sprite {
        Sprite::new(self.clone(), name.into())
    }

    /// Create a new sprite
    ///
    /// # Example
    ///
    /// ```no_run
    /// use sprites::SpritesClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = SpritesClient::new("token");
    ///     let sprite = client.create("my-sprite").await?;
    ///     println!("Created sprite: {}", sprite.name());
    ///     Ok(())
    /// }
    /// ```
    pub async fn create(&self, name: impl Into<String>) -> Result<Sprite> {
        self.create_with_config(name, None, None).await
    }

    /// Create a new sprite with configuration
    pub async fn create_with_config(
        &self,
        name: impl Into<String>,
        config: Option<SpriteConfig>,
        url_settings: Option<UrlSettings>,
    ) -> Result<Sprite> {
        let name = name.into();
        let request = CreateSpriteRequest {
            name: name.clone(),
            config,
            url_settings,
        };

        let response = self
            .http()
            .post(self.url("/sprites"))
            .header("Authorization", self.auth_header())
            .json(&request)
            .send()
            .await?;

        let status = response.status();
        if !status.is_success() {
            let message = response.text().await.unwrap_or_default();
            return Err(Error::api(status.as_u16(), message));
        }

        let _: CreateSpriteResponse = response.json().await?;

        Ok(self.sprite(name))
    }

    /// Get sprite information
    pub async fn get(&self, name: &str) -> Result<SpriteInfo> {
        let response = self
            .http()
            .get(self.url(&format!("/sprites/{name}")))
            .header("Authorization", self.auth_header())
            .send()
            .await?;

        let status = response.status();
        if status == reqwest::StatusCode::NOT_FOUND {
            return Err(Error::not_found(name));
        }
        if !status.is_success() {
            let message = response.text().await.unwrap_or_default();
            return Err(Error::api(status.as_u16(), message));
        }

        let info: SpriteInfo = response.json().await?;
        Ok(info)
    }

    /// List all sprites
    pub async fn list(&self) -> Result<Vec<SpriteInfo>> {
        self.list_all_with_options(ListOptions::default()).await
    }

    /// List sprites with options
    pub async fn list_with_options(&self, options: ListOptions) -> Result<ListSpritesResponse> {
        let mut url = self.url("/sprites");
        let mut query_params = Vec::new();

        if let Some(max) = options.max_results {
            query_params.push(format!("max_results={max}"));
        }
        if let Some(ref token) = options.continuation_token {
            query_params.push(format!("continuation_token={token}"));
        }
        if let Some(ref prefix) = options.prefix {
            query_params.push(format!("prefix={prefix}"));
        }

        if !query_params.is_empty() {
            url = format!("{}?{}", url, query_params.join("&"));
        }

        let response = self.http().get(&url).header("Authorization", self.auth_header()).send().await?;

        let status = response.status();
        if !status.is_success() {
            let message = response.text().await.unwrap_or_default();
            return Err(Error::api(status.as_u16(), message));
        }

        let list: ListSpritesResponse = response.json().await?;
        Ok(list)
    }

    /// List all sprites (handles pagination automatically)
    pub async fn list_all_with_options(&self, options: ListOptions) -> Result<Vec<SpriteInfo>> {
        let mut all_sprites = Vec::new();
        let mut continuation_token = options.continuation_token.clone();

        loop {
            let opts = ListOptions {
                max_results: options.max_results,
                continuation_token: continuation_token.clone(),
                prefix: options.prefix.clone(),
            };

            let response = self.list_with_options(opts).await?;
            all_sprites.extend(response.sprites);

            // Break if no more pages, or if has_more but no continuation token
            // (prevents infinite loop when API returns has_more=true without a token)
            match (response.has_more, response.next_continuation_token) {
                (true, Some(token)) => continuation_token = Some(token),
                _ => break,
            }
        }

        Ok(all_sprites)
    }

    /// Delete a sprite
    pub async fn delete(&self, name: &str) -> Result<()> {
        let response = self
            .http()
            .delete(self.url(&format!("/sprites/{name}")))
            .header("Authorization", self.auth_header())
            .send()
            .await?;

        let status = response.status();
        if status == reqwest::StatusCode::NOT_FOUND {
            return Err(Error::not_found(name));
        }
        if !status.is_success() {
            let message = response.text().await.unwrap_or_default();
            return Err(Error::api(status.as_u16(), message));
        }

        Ok(())
    }

    /// Get server version information
    ///
    /// # Example
    ///
    /// ```no_run
    /// use sprites::SpritesClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = SpritesClient::new("token");
    ///     let version = client.version().await?;
    ///     println!("Server version: {}", version.version);
    ///     Ok(())
    /// }
    /// ```
    pub async fn version(&self) -> Result<Version> {
        let response = self
            .http()
            .get(self.url("/version"))
            .header("Authorization", self.auth_header())
            .send()
            .await?;

        let status = response.status();
        if !status.is_success() {
            let message = response.text().await.unwrap_or_default();
            return Err(Error::api(status.as_u16(), message));
        }

        let version: Version = response.json().await?;
        Ok(version)
    }
}

impl std::fmt::Debug for SpritesClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SpritesClient")
            .field("base_url", &self.inner.base_url)
            .field("token", &"[REDACTED]")
            .finish()
    }
}

/// Builder for configuring a SpritesClient
///
/// # Example
///
/// ```no_run
/// use sprites::SpritesClient;
/// use std::time::Duration;
///
/// let client = SpritesClient::builder("your-token")
///     .base_url("https://custom.api.dev")
///     .timeout(Duration::from_secs(30))
///     .build();
/// ```
pub struct SpritesClientBuilder {
    token: String,
    base_url: Option<String>,
    http_client: Option<reqwest::Client>,
    timeout: Option<Duration>,
}

impl SpritesClientBuilder {
    /// Create a new builder with the given token
    pub fn new(token: impl Into<String>) -> Self {
        Self {
            token: token.into(),
            base_url: None,
            http_client: None,
            timeout: None,
        }
    }

    /// Set a custom base URL
    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = Some(url.into());
        self
    }

    /// Set a custom HTTP client
    ///
    /// This overrides the timeout setting if both are specified.
    pub fn http_client(mut self, client: reqwest::Client) -> Self {
        self.http_client = Some(client);
        self
    }

    /// Set a request timeout
    ///
    /// This is ignored if a custom HTTP client is provided.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Build the SpritesClient
    pub fn build(self) -> SpritesClient {
        let base_url = self
            .base_url
            .unwrap_or_else(|| DEFAULT_BASE_URL.to_string())
            .trim_end_matches('/')
            .to_string();

        let http = if let Some(client) = self.http_client {
            client
        } else if let Some(timeout) = self.timeout {
            reqwest::Client::builder()
                .timeout(timeout)
                .build()
                .unwrap_or_else(|_| reqwest::Client::new())
        } else {
            reqwest::Client::new()
        };

        SpritesClient {
            inner: Arc::new(ClientInner {
                base_url,
                token: self.token,
                http,
            }),
        }
    }
}

/// Request to create a token from Fly.io credentials
#[derive(Serialize)]
struct CreateTokenRequest {
    fly_macaroon: String,
    org_slug: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    invite_code: Option<String>,
}

/// Response from token creation
#[derive(Deserialize)]
struct CreateTokenResponse {
    token: String,
}

/// Server version information
#[derive(Debug, Clone, Deserialize)]
pub struct Version {
    /// Server version string
    pub version: String,

    /// API version
    #[serde(default)]
    pub api_version: Option<String>,
}

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

    #[test]
    fn test_client_creation() {
        let client = SpritesClient::new("test-token");
        assert_eq!(client.base_url(), DEFAULT_BASE_URL);
    }

    #[test]
    fn test_client_custom_url() {
        let client = SpritesClient::with_base_url("token", "https://custom.api.dev/");
        assert_eq!(client.base_url(), "https://custom.api.dev");
    }

    #[test]
    fn test_url_building() {
        let client = SpritesClient::new("token");
        assert_eq!(
            client.url("/sprites"),
            "https://api.sprites.dev/v1/sprites"
        );
    }
}