meteroid-rs 0.31.4

Official Rust SDK for Meteroid, the open-source billing platform: subscriptions, invoicing, usage-based billing and webhooks.
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
// this file is @generated by Perseid; edit the shared runtime template.
//! Paginated list operations: the call of the first page, its pages and every item across them.
#![allow(dead_code)]
use std::{
    collections::VecDeque,
    fmt,
    future::{Future, IntoFuture},
    ops::Deref,
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
};

use super::{ApiResponse, Call};
use crate::error::Error;

/// How an operation selects its page: the parameter in its options, by style.
pub(crate) enum Walk<O> {
    Cursor {
        get: fn(&O) -> Option<String>,
        set: fn(&mut O, String),
        /// The parameter that, set, pages backwards from the first item of each page.
        before: Option<Cursor<O>>,
    },
    Page {
        first: i64,
        get: fn(&O) -> Option<i64>,
        set: fn(&mut O, i64),
    },
    Offset {
        get: fn(&O) -> Option<i64>,
        set: fn(&mut O, i64),
    },
}

/// The accessors of a cursor parameter in the options `O`.
pub(crate) struct Cursor<O> {
    pub(crate) get: fn(&O) -> Option<String>,
    pub(crate) set: fn(&mut O, String),
}

impl<O> Clone for Cursor<O> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<O> Copy for Cursor<O> {}

impl<O> Clone for Walk<O> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<O> Copy for Walk<O> {}

/// Typed accessors of the paging fields of a response `P` listing `T`s.
pub(crate) struct Fields<P, T> {
    pub(crate) items: fn(&P) -> Option<&Vec<T>>,
    pub(crate) items_mut: fn(&mut P) -> Option<&mut Vec<T>>,
    pub(crate) next_cursor: Option<fn(&P) -> Option<&str>>,
    pub(crate) item_cursor: Option<fn(&T) -> Option<&str>>,
    pub(crate) has_more: Option<fn(&P) -> Option<bool>>,
    /// Total pages for page pagination, total items for offset pagination.
    pub(crate) total: Option<fn(&P) -> Option<i64>>,
}

impl<P, T> Clone for Fields<P, T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<P, T> Copy for Fields<P, T> {}

type PageFuture<P, T> =
    Pin<Box<dyn Future<Output = Result<ApiResponse<Page<P, T>>, Error>> + Send>>;

/// The request of one page, able to tell the request of the following one.
trait Fetch<P, T>: Send + Sync {
    fn fetch(&self) -> PageFuture<P, T>;
}

struct PageRequest<O, P, T> {
    options: O,
    call: Arc<dyn Fn(O) -> Call<P> + Send + Sync>,
    walk: Walk<O>,
    fields: Fields<P, T>,
}

impl<O: Clone, P, T> Clone for PageRequest<O, P, T> {
    fn clone(&self) -> Self {
        Self {
            options: self.options.clone(),
            call: self.call.clone(),
            walk: self.walk,
            fields: self.fields,
        }
    }
}

impl<O, P, T> PageRequest<O, P, T>
where
    O: Clone + Send + Sync + 'static,
    P: Send + Sync + 'static,
    T: Send + Sync + 'static,
{
    /// The request of the page after `page`, if there is one.
    fn after(&self, page: &P) -> Option<Arc<dyn Fetch<P, T>>> {
        let fields = self.fields;
        let items = (fields.items)(page).map_or(&[][..], Vec::as_slice);
        let has_more = fields.has_more.and_then(|has_more| has_more(page));
        if items.is_empty() || has_more == Some(false) {
            return None;
        }
        let total = fields.total.and_then(|total| total(page));
        let mut options = self.options.clone();
        match self.walk {
            Walk::Cursor { get, set, before } => {
                let backwards = before.filter(|before| (before.get)(&self.options).is_some());
                let (get, set) = backwards.map_or((get, set), |before| (before.get, before.set));
                let next = match (fields.item_cursor, fields.next_cursor) {
                    (Some(cursor), _) if backwards.is_some() => items.first().and_then(cursor),
                    (Some(cursor), _) => items.last().and_then(cursor),
                    (None, Some(cursor)) => cursor(page),
                    (None, None) => None,
                };
                let next = next.filter(|next| {
                    !next.is_empty() && get(&self.options).as_deref() != Some(*next)
                })?;
                set(&mut options, next.to_owned());
            }
            Walk::Page { first, get, set } => {
                let current = get(&self.options).unwrap_or(first);
                if total.is_some_and(|total| current - first + 1 >= total) {
                    return None;
                }
                set(&mut options, current + 1);
            }
            Walk::Offset { get, set } => {
                let count = i64::try_from(items.len()).unwrap_or(i64::MAX);
                let offset = get(&self.options).unwrap_or(0).saturating_add(count);
                if total.is_some_and(|total| offset >= total) {
                    return None;
                }
                set(&mut options, offset);
            }
        }
        Some(Arc::new(Self {
            options,
            ..self.clone()
        }))
    }
}

impl<O, P, T> Fetch<P, T> for PageRequest<O, P, T>
where
    O: Clone + Send + Sync + 'static,
    P: Send + Sync + 'static,
    T: Send + Sync + 'static,
{
    fn fetch(&self) -> PageFuture<P, T> {
        let call = (self.call)(self.options.clone());
        let request = self.clone();
        Box::pin(async move {
            let response = call.with_response().await?;
            Ok(response.map(|inner| Page {
                next: request.after(&inner),
                inner,
                fields: request.fields,
            }))
        })
    }
}

/// A paginated list operation, sent when awaited: `client.items().list(None).await?` gives the
/// first [`Page`].
///
/// [`items`](Self::items) streams every item across pages and [`pages`](Self::pages) every
/// page, fetching each one when needed; [`with_response`](Self::with_response) also gives the
/// status and headers of the first page.
#[must_use = "a call does nothing until it is awaited"]
pub struct PageCall<P, T> {
    first: Arc<dyn Fetch<P, T>>,
}

impl<P, T> PageCall<P, T>
where
    P: Send + Sync + 'static,
    T: Send + Sync + 'static,
{
    pub(crate) fn new<O: Clone + Send + Sync + 'static>(
        options: O,
        walk: Walk<O>,
        fields: Fields<P, T>,
        call: impl Fn(O) -> Call<P> + Send + Sync + 'static,
    ) -> Self {
        let first = PageRequest {
            options,
            call: Arc::new(call),
            walk,
            fields,
        };
        Self {
            first: Arc::new(first),
        }
    }

    /// Fetches the first page, resolving to the status and headers of its response along with
    /// the page.
    ///
    /// # Errors
    ///
    /// Fails like awaiting the call does.
    pub async fn with_response(self) -> Result<ApiResponse<Page<P, T>>, Error> {
        self.first.fetch().await
    }

    /// Every item of every page, fetching the next page once the current one is consumed.
    pub fn items(self) -> Paginator<P, T> {
        Paginator {
            next: Some(self.first),
            pending: None,
            buffered: VecDeque::new(),
        }
    }

    /// Every page, starting with the first one.
    pub fn pages(self) -> Pages<P, T> {
        Pages(self.items())
    }
}

impl<P, T> IntoFuture for PageCall<P, T>
where
    P: Send + Sync + 'static,
    T: Send + Sync + 'static,
{
    type Output = Result<Page<P, T>, Error>;
    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send>>;

    fn into_future(self) -> Self::IntoFuture {
        let first = self.first.fetch();
        Box::pin(async move { first.await.map(ApiResponse::into_data) })
    }
}

impl<P, T> fmt::Debug for PageCall<P, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PageCall").finish_non_exhaustive()
    }
}

/// One page of a paginated list: the response body, its items, and the way to the next page.
/// It dereferences to the body, so the body's fields read as `page.field`.
pub struct Page<P, T> {
    inner: P,
    next: Option<Arc<dyn Fetch<P, T>>>,
    fields: Fields<P, T>,
}

impl<P, T> Page<P, T> {
    /// The items of this page.
    #[must_use]
    pub fn items(&self) -> &[T] {
        (self.fields.items)(&self.inner).map_or(&[], Vec::as_slice)
    }

    /// The items of this page, dropping the rest of the body.
    #[must_use]
    pub fn into_items(mut self) -> Vec<T> {
        (self.fields.items_mut)(&mut self.inner)
            .map(std::mem::take)
            .unwrap_or_default()
    }

    /// The response body.
    #[must_use]
    pub fn into_inner(self) -> P {
        self.inner
    }

    /// Whether a page follows this one.
    #[must_use]
    pub fn has_next_page(&self) -> bool {
        self.next.is_some()
    }

    /// Fetches the page after this one, `None` on the last page.
    ///
    /// # Errors
    ///
    /// Fails like the list operation does.
    pub async fn next_page(&self) -> Result<Option<Self>, Error> {
        match &self.next {
            Some(next) => next
                .fetch()
                .await
                .map(|response| Some(response.into_data())),
            None => Ok(None),
        }
    }
}

impl<P, T> Deref for Page<P, T> {
    type Target = P;

    fn deref(&self) -> &P {
        &self.inner
    }
}

impl<P: fmt::Debug, T> fmt::Debug for Page<P, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Page")
            .field("inner", &self.inner)
            .field("has_next_page", &self.has_next_page())
            .finish_non_exhaustive()
    }
}

/// Every item of a paginated list operation, from [`PageCall::items`], fetching the next page
/// once the current one is consumed: `while let Some(item) = items.next().await`. It is also a
/// `futures_core::Stream`, and it owns all it needs, so it can move to another task.
#[must_use = "a paginator does nothing until it is polled"]
pub struct Paginator<P, T> {
    next: Option<Arc<dyn Fetch<P, T>>>,
    pending: Option<PageFuture<P, T>>,
    buffered: VecDeque<T>,
}

// Items are never pinned: only the boxed page future is polled in place.
impl<P, T> Unpin for Paginator<P, T> {}

impl<P, T> Paginator<P, T>
where
    P: Send + Sync + 'static,
    T: Send + Sync + 'static,
{
    /// The next item, `None` once every item has been read. An error ends the iteration.
    pub async fn next(&mut self) -> Option<Result<T, Error>> {
        std::future::poll_fn(|cx| self.poll_item(cx)).await
    }

    fn poll_item(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<T, Error>>> {
        loop {
            if let Some(item) = self.buffered.pop_front() {
                return Poll::Ready(Some(Ok(item)));
            }
            match std::task::ready!(self.poll_page(cx)) {
                Some(Ok(page)) => self.buffered.extend(page.into_items()),
                Some(Err(error)) => return Poll::Ready(Some(Err(error))),
                None => return Poll::Ready(None),
            }
        }
    }

    fn poll_page(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<Page<P, T>, Error>>> {
        if self.pending.is_none() {
            let Some(next) = self.next.take() else {
                return Poll::Ready(None);
            };
            self.pending = Some(next.fetch());
        }
        let response = std::task::ready!(self.pending.as_mut().unwrap().as_mut().poll(cx));
        self.pending = None;
        let page = response.map(ApiResponse::into_data);
        if let Ok(page) = &page {
            self.next.clone_from(&page.next);
        }
        Poll::Ready(Some(page))
    }

    /// Reads every remaining item.
    ///
    /// # Errors
    ///
    /// Fails on the first page that does.
    pub async fn collect(mut self) -> Result<Vec<T>, Error> {
        let mut items = Vec::new();
        while let Some(item) = self.next().await {
            items.push(item?);
        }
        Ok(items)
    }
}

impl<P, T> futures_core::Stream for Paginator<P, T>
where
    P: Send + Sync + 'static,
    T: Send + Sync + 'static,
{
    type Item = Result<T, Error>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.get_mut().poll_item(cx)
    }
}

impl<P, T> fmt::Debug for Paginator<P, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Paginator")
            .field("buffered", &self.buffered.len())
            .finish_non_exhaustive()
    }
}

/// Every page of a paginated list operation, from [`PageCall::pages`], fetching each one when
/// needed: `while let Some(page) = pages.next().await`. It is also a `futures_core::Stream`.
#[must_use = "pages do nothing until polled"]
pub struct Pages<P, T>(Paginator<P, T>);

impl<P, T> Pages<P, T>
where
    P: Send + Sync + 'static,
    T: Send + Sync + 'static,
{
    /// The next page, `None` after the last one. An error ends the iteration.
    pub async fn next(&mut self) -> Option<Result<Page<P, T>, Error>> {
        std::future::poll_fn(|cx| self.0.poll_page(cx)).await
    }
}

impl<P, T> futures_core::Stream for Pages<P, T>
where
    P: Send + Sync + 'static,
    T: Send + Sync + 'static,
{
    type Item = Result<Page<P, T>, Error>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.get_mut().0.poll_page(cx)
    }
}

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