calmlens 0.44.0

Rust SDK for CalmLens moderation, storage and CDN delivery
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
//! The blocking client (the `blocking` feature): the async client's API without `async`.
//!
//! It runs the async client on a private Tokio runtime with one worker thread, so it can be
//! created, cloned and dropped anywhere, including inside an async runtime. Its methods block
//! the calling thread, so do not call them from async code: use [`crate::ServerClient`] there, or
//! call them inside `tokio::task::spawn_blocking`.
//!
//! ```no_run
//! use calmlens::{blocking::ServerClient, models::*};
//!
//! fn main() -> calmlens::Result<()> {
//!     let client = ServerClient::new("your-api-key", "proj_8fK2mQx7Lp4NvB3tRz9Y")?;
//!     let asset = client.assets().classify(SubmitAsset::text("Hello world"))?;
//!     for asset in client.assets().iterate(ListAssets::default()) {
//!         println!("{}", asset?.id);
//!     }
//!     Ok(())
//! }
//! ```
use crate::error::{invalid_config, ErrorCode};
use crate::models::*;
use crate::{Error, ResourceEvent, Result};
use bytes::Bytes;
use futures_util::{Stream, StreamExt};
use http::{HeaderMap, StatusCode};
use std::{fmt, future::Future, pin::Pin, sync::Arc, time::Duration};

struct Runtime(Option<tokio::runtime::Runtime>);
impl Runtime {
    fn block_on<F: Future>(&self, future: F) -> F::Output {
        self.0
            .as_ref()
            .expect("runtime is present until drop")
            .block_on(future)
    }
}
impl Drop for Runtime {
    fn drop(&mut self) {
        // Never blocks, so dropping the client inside an async runtime cannot panic.
        if let Some(runtime) = self.0.take() {
            runtime.shutdown_background();
        }
    }
}

/// Configures a [`ServerClient`]; the options match [`crate::ServerClientBuilder`].
#[derive(Clone, Debug)]
pub struct ServerClientBuilder(crate::ServerClientBuilder);
impl ServerClientBuilder {
    /// A builder from the environment. See [`crate::ServerClientBuilder::from_env`].
    pub fn from_env() -> Result<Self> {
        crate::ServerClientBuilder::from_env().map(Self)
    }
    /// The API base URL.
    pub fn base_url(self, value: impl Into<String>) -> Self {
        Self(self.0.base_url(value))
    }
    /// The CDN base URL.
    pub fn cdn_base_url(self, value: impl Into<String>) -> Self {
        Self(self.0.cdn_base_url(value))
    }
    /// The timeout of each API call attempt. See [`crate::ServerClientBuilder::timeout`].
    pub fn timeout(self, value: Duration) -> Self {
        Self(self.0.timeout(value))
    }
    /// The timeout of each binary upload attempt. See
    /// [`crate::ServerClientBuilder::upload_timeout`].
    pub fn upload_timeout(self, value: Duration) -> Self {
        Self(self.0.upload_timeout(value))
    }
    /// The largest API response body the client reads. See
    /// [`crate::ServerClientBuilder::max_response_bytes`].
    pub fn max_response_bytes(self, value: usize) -> Self {
        Self(self.0.max_response_bytes(value))
    }
    /// The connect timeout.
    pub fn connect_timeout(self, value: Duration) -> Self {
        Self(self.0.connect_timeout(value))
    }
    /// The longest wait for the next response bytes.
    pub fn read_timeout(self, value: Duration) -> Self {
        Self(self.0.read_timeout(value))
    }
    /// How many times to retry a repeatable request.
    pub fn max_retries(self, value: u32) -> Self {
        Self(self.0.max_retries(value))
    }
    /// Sends every request through a proxy. See [`crate::ServerClientBuilder::proxy`].
    pub fn proxy(self, url: impl Into<String>) -> Self {
        Self(self.0.proxy(url))
    }
    /// Also trusts PEM root certificates. See
    /// [`crate::ServerClientBuilder::add_root_certificate`].
    pub fn add_root_certificate(self, pem: impl Into<Vec<u8>>) -> Self {
        Self(self.0.add_root_certificate(pem))
    }
    /// Names your application in the `User-Agent`. See [`crate::ServerClientBuilder::app_info`].
    pub fn app_info(
        self,
        name: impl Into<String>,
        version: Option<&str>,
        url: Option<&str>,
    ) -> Self {
        Self(self.0.app_info(name, version, url))
    }
    /// Validates the options and creates the client.
    pub fn build(self) -> Result<ServerClient> {
        ServerClient::from_async(self.0.build()?)
    }
}

/// The blocking CalmLens client. Clones are cheap and share connections and the runtime.
#[derive(Clone)]
pub struct ServerClient {
    client: crate::ServerClient,
    runtime: Arc<Runtime>,
}
impl fmt::Debug for ServerClient {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("blocking::ServerClient")
            .field(&self.client)
            .finish()
    }
}

impl ServerClient {
    /// A client for the production API with default options.
    pub fn new(api_key: impl Into<String>, project_id: impl Into<String>) -> Result<Self> {
        Self::builder(api_key, project_id).build()
    }
    /// A client from the environment. See [`crate::ServerClientBuilder::from_env`].
    pub fn from_env() -> Result<Self> {
        ServerClientBuilder::from_env()?.build()
    }
    /// A builder for a client with custom URLs, timeouts, retries, proxy or certificates.
    pub fn builder(
        api_key: impl Into<String>,
        project_id: impl Into<String>,
    ) -> ServerClientBuilder {
        ServerClientBuilder(crate::ServerClient::builder(api_key, project_id))
    }
    /// Wraps an async client, sharing its connections and lens cache.
    pub fn from_async(client: crate::ServerClient) -> Result<Self> {
        let runtime = tokio::runtime::Builder::new_multi_thread()
            .worker_threads(1)
            .thread_name("calmlens-blocking")
            .enable_all()
            .build()
            .map_err(|cause| {
                invalid_config(format!("Could not start the client runtime: {cause}"))
                    .with_source(cause)
            })?;
        Ok(Self {
            client,
            runtime: Arc::new(Runtime(Some(runtime))),
        })
    }
    /// The async client this wraps.
    pub fn as_async(&self) -> &crate::ServerClient {
        &self.client
    }
    /// A handle whose calls, including uploads and CDN downloads, time out after `timeout`.
    pub fn with_timeout(&self, timeout: Duration) -> Self {
        Self {
            client: self.client.with_timeout(timeout),
            runtime: self.runtime.clone(),
        }
    }
    /// A handle that retries repeatable requests up to `max_retries` times.
    pub fn with_max_retries(&self, max_retries: u32) -> Self {
        Self {
            client: self.client.with_max_retries(max_retries),
            runtime: self.runtime.clone(),
        }
    }
    fn wait<T>(&self, future: impl Future<Output = T>) -> T {
        self.runtime.block_on(future)
    }
    fn iter<T>(&self, stream: impl Stream<Item = T> + Send + 'static) -> Iter<T> {
        Iter {
            stream: Box::pin(stream),
            runtime: self.runtime.clone(),
        }
    }
    /// Asset operations.
    pub fn assets(&self) -> AssetsClient<'_> {
        AssetsClient(self)
    }
    /// Folder operations.
    pub fn folders(&self) -> FoldersClient<'_> {
        FoldersClient(self)
    }
    /// Hash list operations.
    pub fn hash_lists(&self) -> HashListsClient<'_> {
        HashListsClient(self)
    }
    /// Moderation policy operations.
    pub fn policies(&self) -> PoliciesClient<'_> {
        PoliciesClient(self)
    }
    /// The project's upload presets: the rules for uploads from browsers and apps.
    pub fn upload_presets(&self) -> UploadPresetsClient<'_> {
        UploadPresetsClient(self)
    }
    /// The project's settings.
    pub fn project_settings(&self) -> ProjectSettingsClient<'_> {
        ProjectSettingsClient(self)
    }
    /// The project's metadata fields.
    pub fn metadata_fields(&self) -> MetadataFieldsClient<'_> {
        MetadataFieldsClient(self)
    }
    /// Lens operations: the project's named CDN transforms.
    pub fn lenses(&self) -> LensesClient<'_> {
        LensesClient(self)
    }
    /// The project's events feed.
    pub fn events(&self) -> EventsClient<'_> {
        EventsClient(self)
    }
    /// CDN URLs and downloads.
    pub fn cdn(&self) -> CdnClient<'_> {
        CdnClient(self)
    }
    /// Text moderation.
    pub fn text(&self) -> TextClient<'_> {
        TextClient(self)
    }
    /// Upload tokens for upload presets, signed locally.
    pub fn upload_tokens(&self) -> UploadTokensClient<'_> {
        UploadTokensClient(self)
    }
    /// See [`crate::ServerClient::ensure_lens`].
    pub fn ensure_lens(&self, lens: LensDefinition) -> Result<Lens> {
        self.wait(self.client.ensure_lens(lens))
    }
    /// See [`crate::ServerClient::ensure_lenses`].
    pub fn ensure_lenses(&self, options: EnsureLenses) -> Result<Vec<Lens>> {
        self.wait(self.client.ensure_lenses(options))
    }
}

/// An iterator that fetches pages as it is read.
pub struct Iter<T> {
    stream: Pin<Box<dyn Stream<Item = T> + Send>>,
    runtime: Arc<Runtime>,
}
impl<T> fmt::Debug for Iter<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Iter").finish_non_exhaustive()
    }
}
impl<T> Iterator for Iter<T> {
    type Item = T;
    fn next(&mut self) -> Option<T> {
        self.runtime.block_on(self.stream.next())
    }
}

macro_rules! blocking_methods {
    ($handle:ident => $async_handle:ident { $( $(#[$doc:meta])* fn $name:ident($($arg:ident: $ty:ty),*) -> $ret:ty; )* }) => {
        impl $handle<'_> {
            $(
                $(#[$doc])*
                pub fn $name(&self, $($arg: $ty),*) -> $ret {
                    self.0.wait(self.0.client.$async_handle().$name($($arg),*))
                }
            )*
        }
    };
}

/// Asset operations. See [`crate::AssetsClient`].
#[derive(Debug, Clone, Copy)]
pub struct AssetsClient<'a>(&'a ServerClient);
blocking_methods!(AssetsClient => assets {
    /// See [`crate::AssetsClient::create`].
    fn create(options: SubmitAsset) -> Result<Asset>;
    /// See [`crate::AssetsClient::classify`].
    fn classify(options: SubmitAsset) -> Result<Asset>;
    /// See [`crate::AssetsClient::upload_part`].
    fn upload_part(options: UploadPart) -> Result<Asset>;
    /// See [`crate::AssetsClient::search`].
    fn search(options: SearchAssets) -> Result<AssetSearchResponse>;
    /// See [`crate::AssetsClient::list`].
    fn list(options: ListAssets) -> Result<AssetPage>;
    /// See [`crate::AssetsClient::list_children`].
    fn list_children(options: ListChildren) -> Result<AssetPage>;
    /// See [`crate::AssetsClient::list_timeline`].
    fn list_timeline(options: ListTimeline) -> Result<AssetTimelinePage>;
    /// See [`crate::AssetsClient::retrieve`].
    fn retrieve(options: RetrieveAsset) -> Result<Asset>;
    /// See [`crate::AssetsClient::retrieve_by_external_id`].
    fn retrieve_by_external_id(options: RetrieveByExternalId) -> Result<Asset>;
    /// See [`crate::AssetsClient::wait_for_decision`]. Blocks until the asset is decided or
    /// the timeout passes.
    fn wait_for_decision(options: WaitForDecision) -> Result<Asset>;
    /// See [`crate::AssetsClient::update`].
    fn update(options: UpdateAsset) -> Result<Asset>;
    /// See [`crate::AssetsClient::retry`].
    fn retry(options: AssetId) -> Result<Asset>;
    /// See [`crate::AssetsClient::decide`].
    fn decide(options: DecideAsset) -> Result<Asset>;
    /// See [`crate::AssetsClient::request_review`].
    fn request_review(options: RequestAssetReview) -> Result<AssetReviewRequest>;
    /// See [`crate::AssetsClient::remove_content`].
    fn remove_content(options: AssetId) -> Result<Asset>;
    /// See [`crate::AssetsClient::delete`].
    fn delete(options: AssetId) -> Result<()>;
    /// See [`crate::AssetsClient::batch`].
    fn batch(options: BatchAssets) -> Result<BatchAssetsResponse>;
    /// See [`crate::AssetsClient::move_asset`].
    fn move_asset(options: MoveAsset) -> Result<Asset>;
});
impl AssetsClient<'_> {
    /// Every asset from `options.cursor` on, fetching pages as the iterator is read.
    pub fn iterate(&self, options: ListAssets) -> Iter<Result<Asset>> {
        self.0.iter(self.0.client.assets().iterate(options))
    }
    /// Every child of an asset from `options.cursor` on.
    pub fn iterate_children(&self, options: ListChildren) -> Iter<Result<Asset>> {
        self.0
            .iter(self.0.client.assets().iterate_children(options))
    }
    /// Every segment of an asset's findings timeline from `options.cursor` on.
    pub fn iterate_timeline(
        &self,
        options: ListTimeline,
    ) -> Iter<Result<MediaClassificationSegment>> {
        self.0
            .iter(self.0.client.assets().iterate_timeline(options))
    }
}

/// Folder operations. See [`crate::FoldersClient`].
#[derive(Debug, Clone, Copy)]
pub struct FoldersClient<'a>(&'a ServerClient);
blocking_methods!(FoldersClient => folders {
    /// See [`crate::FoldersClient::list`].
    fn list(options: ListFolders) -> Result<FolderPage>;
    /// See [`crate::FoldersClient::create`].
    fn create(options: CreateFolder) -> Result<Folder>;
    /// See [`crate::FoldersClient::retrieve`].
    fn retrieve(options: FolderId) -> Result<Folder>;
    /// See [`crate::FoldersClient::update`].
    fn update(options: UpdateFolder) -> Result<Folder>;
    /// See [`crate::FoldersClient::move_folder`].
    fn move_folder(options: MoveFolder) -> Result<Folder>;
    /// See [`crate::FoldersClient::delete`].
    fn delete(options: FolderId) -> Result<()>;
});
impl FoldersClient<'_> {
    /// Every child folder from `options.cursor` on, fetching pages as the iterator is read.
    pub fn iterate(&self, options: ListFolders) -> Iter<Result<Folder>> {
        self.0.iter(self.0.client.folders().iterate(options))
    }
}

/// Hash list operations. See [`crate::HashListsClient`].
#[derive(Debug, Clone, Copy)]
pub struct HashListsClient<'a>(&'a ServerClient);
blocking_methods!(HashListsClient => hash_lists {
    /// See [`crate::HashListsClient::list`].
    fn list(options: ListHashLists) -> Result<HashListPage>;
    /// See [`crate::HashListsClient::retrieve`].
    fn retrieve(options: HashListId) -> Result<HashList>;
    /// See [`crate::HashListsClient::create`].
    fn create(options: CreateHashList) -> Result<HashList>;
    /// See [`crate::HashListsClient::update`].
    fn update(options: UpdateHashList) -> Result<HashList>;
    /// See [`crate::HashListsClient::delete`].
    fn delete(options: HashListId) -> Result<()>;
    /// See [`crate::HashListsClient::list_entries`].
    fn list_entries(options: ListHashListEntries) -> Result<HashListEntryPage>;
    /// See [`crate::HashListsClient::add_entry`].
    fn add_entry(options: AddHashListEntry) -> Result<HashListEntry>;
    /// See [`crate::HashListsClient::remove_entry`].
    fn remove_entry(options: HashListEntryId) -> Result<()>;
});
impl HashListsClient<'_> {
    /// Every hash list from `options.cursor` on, fetching pages as the iterator is read.
    pub fn iterate(&self, options: ListHashLists) -> Iter<Result<HashList>> {
        self.0.iter(self.0.client.hash_lists().iterate(options))
    }
    /// Every entry of a hash list from `options.cursor` on.
    pub fn iterate_entries(&self, options: ListHashListEntries) -> Iter<Result<HashListEntry>> {
        self.0
            .iter(self.0.client.hash_lists().iterate_entries(options))
    }
}

/// Moderation policy operations. See [`crate::PoliciesClient`].
#[derive(Debug, Clone, Copy)]
pub struct PoliciesClient<'a>(&'a ServerClient);
blocking_methods!(PoliciesClient => policies {
    /// See [`crate::PoliciesClient::list`].
    fn list(options: ListPolicies) -> Result<PolicyPage>;
    /// See [`crate::PoliciesClient::retrieve`].
    fn retrieve(options: PolicyId) -> Result<Policy>;
    /// See [`crate::PoliciesClient::create`].
    fn create(options: CreatePolicy) -> Result<Policy>;
    /// See [`crate::PoliciesClient::update`].
    fn update(options: UpdatePolicy) -> Result<Policy>;
    /// See [`crate::PoliciesClient::reset`].
    fn reset(options: ResetPolicy) -> Result<Policy>;
    /// See [`crate::PoliciesClient::upgrade`].
    fn upgrade(options: UpgradePolicy) -> Result<Policy>;
    /// See [`crate::PoliciesClient::set_automatic_updates`].
    fn set_automatic_updates(options: SetPolicyAutomaticUpdates) -> Result<Policy>;
    /// See [`crate::PoliciesClient::delete`].
    fn delete(options: PolicyId) -> Result<()>;
    /// See [`crate::PoliciesClient::retrieve_assigned`].
    fn retrieve_assigned() -> Result<Policy>;
    /// See [`crate::PoliciesClient::assign`].
    fn assign(options: AssignPolicy) -> Result<Policy>;
});
impl PoliciesClient<'_> {
    /// Every policy of the organisation from `options.cursor` on.
    pub fn iterate(&self, options: ListPolicies) -> Iter<Result<Policy>> {
        self.0.iter(self.0.client.policies().iterate(options))
    }
}

/// Upload preset operations. See [`crate::UploadPresetsClient`].
#[derive(Debug, Clone, Copy)]
pub struct UploadPresetsClient<'a>(&'a ServerClient);
blocking_methods!(UploadPresetsClient => upload_presets {
    /// See [`crate::UploadPresetsClient::list`].
    fn list(options: ListUploadPresets) -> Result<UploadPresetPage>;
    /// See [`crate::UploadPresetsClient::ensure`].
    fn ensure(options: EnsureUploadPresets) -> Result<EnsureUploadPresetsResponse>;
    /// See [`crate::UploadPresetsClient::delete`].
    fn delete(options: UploadPresetId) -> Result<()>;
});
impl UploadPresetsClient<'_> {
    /// Every upload preset of the project from `options.cursor` on.
    pub fn iterate(&self, options: ListUploadPresets) -> Iter<Result<UploadPreset>> {
        self.0.iter(self.0.client.upload_presets().iterate(options))
    }
}

/// Project settings operations. See [`crate::ProjectSettingsClient`].
#[derive(Debug, Clone, Copy)]
pub struct ProjectSettingsClient<'a>(&'a ServerClient);
blocking_methods!(ProjectSettingsClient => project_settings {
    /// See [`crate::ProjectSettingsClient::get`].
    fn get() -> Result<ProjectSettingsResource>;
    /// See [`crate::ProjectSettingsClient::update`].
    fn update(options: UpdateProjectSettings) -> Result<ProjectSettingsResource>;
    /// See [`crate::ProjectSettingsClient::patch`].
    fn patch(options: PatchProjectSettings) -> Result<ProjectSettingsResource>;
});

/// Metadata field operations. See [`crate::MetadataFieldsClient`].
#[derive(Debug, Clone, Copy)]
pub struct MetadataFieldsClient<'a>(&'a ServerClient);
blocking_methods!(MetadataFieldsClient => metadata_fields {
    /// See [`crate::MetadataFieldsClient::list`].
    fn list() -> Result<MetadataFieldsResource>;
    /// See [`crate::MetadataFieldsClient::ensure`].
    fn ensure(options: EnsureMetadataFields) -> Result<MetadataFieldsResource>;
    /// See [`crate::MetadataFieldsClient::delete`].
    fn delete(options: DeleteMetadataField) -> Result<()>;
});

/// Lens operations. See [`crate::LensesClient`].
#[derive(Debug, Clone, Copy)]
pub struct LensesClient<'a>(&'a ServerClient);
blocking_methods!(LensesClient => lenses {
    /// See [`crate::LensesClient::list`].
    fn list(options: ListLenses) -> Result<LensPage>;
    /// See [`crate::LensesClient::create`].
    fn create(options: LensDefinition) -> Result<Lens>;
    /// See [`crate::LensesClient::retrieve`].
    fn retrieve(options: LensId) -> Result<Lens>;
    /// See [`crate::LensesClient::update`].
    fn update(options: UpdateLens) -> Result<Lens>;
    /// See [`crate::LensesClient::delete`].
    fn delete(options: LensId) -> Result<()>;
});
impl LensesClient<'_> {
    /// Every lens of the project from `options.cursor` on.
    pub fn iterate(&self, options: ListLenses) -> Iter<Result<Lens>> {
        self.0.iter(self.0.client.lenses().iterate(options))
    }
}

/// The events feed. See [`crate::EventsClient`].
#[derive(Debug, Clone, Copy)]
pub struct EventsClient<'a>(&'a ServerClient);
blocking_methods!(EventsClient => events {
    /// See [`crate::EventsClient::list`].
    fn list(options: ListEvents) -> Result<EventsPage>;
});
impl EventsClient<'_> {
    /// See [`crate::EventsClient::iterate`].
    pub fn iterate(&self, options: ListEvents) -> Iter<Result<Event>> {
        self.0.iter(self.0.client.events().iterate(options))
    }
    /// See [`crate::EventsClient::pages`].
    pub fn pages(&self, options: ListEvents) -> Iter<Result<EventsPage>> {
        self.0.iter(self.0.client.events().pages(options))
    }
    /// See [`crate::EventsClient::retrieve_asset`].
    pub fn retrieve_asset(&self, event: &impl ResourceEvent) -> Result<Option<Asset>> {
        self.0.wait(self.0.client.events().retrieve_asset(event))
    }
}

/// Text moderation. See [`crate::TextClient`].
#[derive(Debug, Clone, Copy)]
pub struct TextClient<'a>(&'a ServerClient);
blocking_methods!(TextClient => text {
    /// See [`crate::TextClient::classify`].
    fn classify(options: ClassifyText) -> Result<Asset>;
});

/// Signs upload tokens. See [`crate::UploadTokensClient`].
#[derive(Debug, Clone, Copy)]
pub struct UploadTokensClient<'a>(&'a ServerClient);
impl UploadTokensClient<'_> {
    /// See [`crate::UploadTokensClient::sign`].
    pub fn sign(&self, options: SignUploadToken) -> Result<SignedUploadToken> {
        self.0.client.upload_tokens().sign(options)
    }
}

/// CDN URLs, signed asset URLs, display info and downloads. See [`crate::CdnClient`].
#[derive(Debug, Clone, Copy)]
pub struct CdnClient<'a>(&'a ServerClient);
impl CdnClient<'_> {
    /// See [`crate::CdnClient::get_asset_url`].
    pub fn get_asset_url(&self, options: &CdnRequest) -> Result<String> {
        self.0.client.cdn().get_asset_url(options)
    }
    /// See [`crate::CdnClient::sign_asset_url`].
    pub fn sign_asset_url(&self, options: SignAssetUrlOptions) -> Result<SignedAssetUrl> {
        self.0.client.cdn().sign_asset_url(options)
    }
    /// See [`crate::CdnClient::get_asset_info`].
    pub fn get_asset_info(&self, url: &str, options: GetAssetInfoOptions) -> Result<AssetInfo> {
        self.0
            .wait(self.0.client.cdn().get_asset_info(url, options))
    }
    /// Fetches an asset through the CDN; the response implements [`std::io::Read`].
    pub fn serve(&self, options: CdnRequest) -> Result<CdnResponse> {
        let response = self.0.wait(self.0.client.cdn().serve(options))?;
        Ok(CdnResponse {
            response,
            runtime: self.0.runtime.clone(),
            pending: Bytes::new(),
        })
    }
}

/// A streaming CDN response that implements [`std::io::Read`]. Drop it to close an
/// unfinished download.
pub struct CdnResponse {
    response: crate::CdnResponse,
    runtime: Arc<Runtime>,
    pending: Bytes,
}
impl fmt::Debug for CdnResponse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.response.fmt(f)
    }
}
impl CdnResponse {
    /// The HTTP status.
    pub fn status(&self) -> StatusCode {
        self.response.status()
    }
    /// The response headers.
    pub fn headers(&self) -> &HeaderMap {
        self.response.headers()
    }
    /// Reads served image dimensions from the headers without consuming the body.
    pub fn get_asset_info(&self) -> Option<crate::ServedAssetInfo> {
        self.response.get_asset_info()
    }
    /// The next chunk of the body, or `None` at the end.
    pub fn chunk(&mut self) -> Result<Option<Bytes>> {
        if !self.pending.is_empty() {
            return Ok(Some(std::mem::take(&mut self.pending)));
        }
        self.runtime.block_on(self.response.chunk())
    }
    /// The whole body in memory.
    pub fn bytes(mut self) -> Result<Bytes> {
        let mut body = Vec::new();
        while let Some(chunk) = self.chunk()? {
            body.extend_from_slice(&chunk);
        }
        Ok(body.into())
    }
    /// The whole body as UTF-8 text.
    pub fn text(self) -> Result<String> {
        String::from_utf8(self.bytes()?.to_vec()).map_err(|cause| {
            Error::new(ErrorCode::InvalidResponse, "Invalid UTF-8 response").with_source(cause)
        })
    }
}
impl std::io::Read for CdnResponse {
    fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
        if self.pending.is_empty() {
            match self.runtime.block_on(self.response.chunk()) {
                Ok(Some(chunk)) => self.pending = chunk,
                Ok(None) => return Ok(0),
                Err(error) => {
                    let kind = if error.is_timeout() {
                        std::io::ErrorKind::TimedOut
                    } else {
                        std::io::ErrorKind::Other
                    };
                    return Err(std::io::Error::new(kind, error));
                }
            }
        }
        let count = buffer.len().min(self.pending.len());
        buffer[..count].copy_from_slice(&self.pending.split_to(count));
        Ok(count)
    }
}