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
// this file is @generated by Perseid; edit the shared runtime template.
//! Bounded-memory upload bodies. Reader-backed bodies are single-use.
#![allow(dead_code)]
use crate::{
    error::Error,
    request::{random, request_error},
};
use bytes::Bytes;
use hyper::body::{Body, Frame, SizeHint};
use std::{
    collections::VecDeque,
    fmt, io,
    pin::Pin,
    sync::{Mutex, PoisonError},
    task::{Context, Poll},
};
use tokio::io::{AsyncRead, ReadBuf};

const DEFAULT_CONTENT_TYPE: &str = "application/octet-stream";

/// A file or raw request body. Byte buffers can be retried; readers cannot.
///
/// `reader` accepts an asynchronous reader and an optional exact length.
/// Provide a length for endpoints requiring Content-Length; otherwise the HTTP
/// transport streams without a known length. Readers are never buffered in full.
pub struct Upload {
    source: Source,
    filename: Option<String>,
    content_type: String,
}

/// Makes a `Send` reader `Sync` so request futures stay `Send + Sync`.
struct SyncReader(Mutex<Pin<Box<dyn AsyncRead + Send>>>);

impl SyncReader {
    fn new(reader: impl AsyncRead + Send + 'static) -> Self {
        Self(Mutex::new(Box::pin(reader)))
    }
}

impl AsyncRead for SyncReader {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        let reader = self
            .get_mut()
            .0
            .get_mut()
            .unwrap_or_else(PoisonError::into_inner);
        reader.as_mut().poll_read(cx, buf)
    }
}

impl fmt::Debug for Upload {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let length = match &self.source {
            Source::Bytes(bytes) => Some(bytes.len() as u64),
            Source::Reader { length, .. } => *length,
        };
        f.debug_struct("Upload")
            .field("filename", &self.filename)
            .field("content_type", &self.content_type)
            .field("length", &length)
            .finish()
    }
}

enum Source {
    Bytes(Bytes),
    Reader {
        reader: Option<SyncReader>,
        length: Option<u64>,
    },
}

impl Upload {
    /// A body of bytes in memory, which a retry sends again.
    #[must_use]
    pub fn bytes(bytes: impl Into<Bytes>) -> Self {
        Self {
            source: Source::Bytes(bytes.into()),
            filename: None,
            content_type: DEFAULT_CONTENT_TYPE.into(),
        }
    }

    /// A body streamed from `reader`, of `length` bytes when known. It cannot be retried.
    #[must_use]
    pub fn reader(reader: impl AsyncRead + Send + 'static, length: Option<u64>) -> Self {
        Self {
            source: Source::Reader {
                reader: Some(SyncReader::new(reader)),
                length,
            },
            filename: None,
            content_type: DEFAULT_CONTENT_TYPE.into(),
        }
    }

    /// Filename used by multipart encoding; does not affect a raw upload.
    #[must_use]
    pub fn with_filename(mut self, filename: impl Into<String>) -> Self {
        self.filename = Some(filename.into());
        self
    }

    /// Content type used by multipart encoding; raw uploads use the spec's media type.
    #[must_use]
    pub fn with_content_type(mut self, content_type: impl Into<String>) -> Self {
        self.content_type = content_type.into();
        self
    }

    pub(crate) fn replayable(&self) -> bool {
        matches!(self.source, Source::Bytes(_))
    }

    fn length(&self) -> Option<u64> {
        match &self.source {
            Source::Bytes(bytes) => Some(bytes.len() as u64),
            Source::Reader { length, .. } => *length,
        }
    }

    fn segment(&mut self) -> Result<Segment, Error> {
        match &mut self.source {
            Source::Bytes(bytes) => Ok(Segment::Bytes(bytes.clone())),
            Source::Reader { reader, length } => Ok(Segment::Reader {
                reader: reader
                    .take()
                    .ok_or_else(|| invalid("upload reader has already been consumed"))?,
                remaining: *length,
                tail: None,
            }),
        }
    }

    pub(crate) fn body(&mut self) -> Result<RequestBody, Error> {
        Ok(RequestBody {
            remaining: self.length(),
            segments: [self.segment()?].into(),
        })
    }
}

fn invalid(message: &str) -> Error {
    request_error(message.to_owned())
}

fn quoted(value: &str) -> Result<String, Error> {
    if value.chars().any(char::is_control) {
        return Err(invalid(
            "multipart names and filenames cannot contain control characters",
        ));
    }
    Ok(value.replace('\\', "\\\\").replace('"', "\\\""))
}

/// Multipart encoder used by generated typed form builders.
pub(crate) struct Multipart {
    boundary: String,
    parts: Vec<(Bytes, Upload)>,
}

impl Default for Multipart {
    fn default() -> Self {
        Self::new()
    }
}

impl Multipart {
    pub(crate) fn new() -> Self {
        Self {
            boundary: format!("perseid-{:016x}{:016x}", random(), random()),
            parts: Vec::new(),
        }
    }

    /// Adds a field: scalars as text, objects as JSON, lists as one part per item.
    pub(crate) fn field(self, name: &str, value: impl serde::Serialize) -> Result<Self, Error> {
        self.field_with(name, value, None)
    }

    /// Like [`Self::field`], with the media type the spec declares for the part.
    pub(crate) fn field_as(
        self,
        name: &str,
        value: impl serde::Serialize,
        content_type: &str,
    ) -> Result<Self, Error> {
        self.field_with(name, value, Some(content_type))
    }

    fn field_with(
        mut self,
        name: &str,
        value: impl serde::Serialize,
        declared: Option<&str>,
    ) -> Result<Self, Error> {
        let value = serde_json::to_value(value).map_err(request_error)?;
        if let serde_json::Value::Array(items) = value {
            for item in items {
                self = self.field_with(name, item, declared)?;
            }
            return Ok(self);
        }
        let content_type = match declared {
            Some(declared) => {
                http::HeaderValue::from_str(declared).map_err(request_error)?;
                format!("Content-Type: {declared}\r\n")
            }
            None if value.is_object() || value.is_array() => {
                "Content-Type: application/json\r\n".to_owned()
            }
            None => String::new(),
        };
        let value = match value {
            serde_json::Value::String(s) => s,
            other => other.to_string(),
        };
        let header = format!(
            "--{}\r\nContent-Disposition: form-data; name=\"{}\"\r\n{content_type}\r\n",
            self.boundary,
            quoted(name)?
        );
        self.parts.push((Bytes::from(header), Upload::bytes(value)));
        Ok(self)
    }

    /// Like [`Self::file`], with the media type the spec declares for the part, used unless
    /// the upload sets its own.
    pub(crate) fn file_as(
        self,
        name: &str,
        mut upload: Upload,
        content_type: &str,
    ) -> Result<Self, Error> {
        if upload.content_type == DEFAULT_CONTENT_TYPE {
            upload.content_type = content_type.to_owned();
        }
        self.file(name, upload)
    }

    pub(crate) fn file(mut self, name: &str, upload: Upload) -> Result<Self, Error> {
        let filename = quoted(upload.filename.as_deref().unwrap_or("file"))?;
        let name = quoted(name)?;
        http::HeaderValue::from_str(&upload.content_type).map_err(request_error)?;
        let header = format!("--{}\r\nContent-Disposition: form-data; name=\"{name}\"; filename=\"{filename}\"\r\nContent-Type: {}\r\n\r\n", self.boundary, upload.content_type);
        self.parts.push((Bytes::from(header), upload));
        Ok(self)
    }

    pub(crate) fn content_type(&self) -> String {
        format!("multipart/form-data; boundary={}", self.boundary)
    }
    pub(crate) fn replayable(&self) -> bool {
        self.parts.iter().all(|(_, upload)| upload.replayable())
    }

    pub(crate) fn body(&mut self) -> Result<RequestBody, Error> {
        let mut segments = VecDeque::new();
        let mut length = Some(0u64);
        for (header, upload) in &mut self.parts {
            length = length
                .and_then(|n| n.checked_add(header.len() as u64))
                .and_then(|n| upload.length().and_then(|len| n.checked_add(len)))
                .and_then(|n| n.checked_add(2));
            segments.push_back(Segment::Bytes(header.clone()));
            segments.push_back(upload.segment()?);
            segments.push_back(Segment::Bytes(Bytes::from_static(b"\r\n")));
        }
        let end = Bytes::from(format!("--{}--\r\n", self.boundary));
        length = length.and_then(|n| n.checked_add(end.len() as u64));
        segments.push_back(Segment::Bytes(end));
        Ok(RequestBody {
            segments,
            remaining: length,
        })
    }
}

enum Segment {
    Bytes(Bytes),
    Reader {
        reader: SyncReader,
        remaining: Option<u64>,
        tail: Option<Bytes>,
    },
}

/// The body of an outgoing request, streamed to the [`HttpClient`](crate::api::HttpClient).
pub struct RequestBody {
    segments: VecDeque<Segment>,
    remaining: Option<u64>,
}

impl RequestBody {
    pub(crate) fn empty() -> Self {
        Self {
            segments: VecDeque::new(),
            remaining: Some(0),
        }
    }
    pub(crate) fn length(&self) -> Option<u64> {
        self.remaining
    }

    pub(crate) async fn validate_empty(&mut self) -> io::Result<()> {
        // Hyper may skip polling a body with an exact zero length. Probe its
        // reader first so a nonempty or failed reader cannot silently succeed.
        if self.remaining == Some(0) {
            while let Some(frame) =
                std::future::poll_fn(|cx| Pin::new(&mut *self).poll_frame(cx)).await
            {
                frame?;
            }
        }
        Ok(())
    }
}

impl Body for RequestBody {
    type Data = Bytes;
    type Error = io::Error;

    fn poll_frame(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Bytes>, io::Error>>> {
        loop {
            let Some(segment) = self.segments.front_mut() else {
                return Poll::Ready(None);
            };
            let next = match segment {
                Segment::Bytes(bytes) => {
                    let bytes = bytes.clone();
                    self.segments.pop_front();
                    if bytes.is_empty() {
                        continue;
                    }
                    Ok(bytes)
                }
                Segment::Reader {
                    reader,
                    remaining,
                    tail,
                } => {
                    let mut buffer = [0u8; 16 * 1024];
                    let capacity = remaining.map_or(buffer.len(), |n| {
                        usize::try_from(n.saturating_add(1))
                            .map_or(buffer.len(), |n| n.min(buffer.len()))
                    });
                    let mut read = ReadBuf::new(&mut buffer[..capacity]);
                    match Pin::new(&mut *reader).poll_read(cx, &mut read) {
                        Poll::Pending => return Poll::Pending,
                        Poll::Ready(Err(error)) => Err(error),
                        Poll::Ready(Ok(())) => {
                            let data = read.filled();
                            if remaining.is_some_and(|n| (data.len() as u64) > n) {
                                Err(io::Error::new(
                                    io::ErrorKind::InvalidData,
                                    "upload reader exceeds its declared length",
                                ))
                            } else if data.is_empty() {
                                if remaining.is_some_and(|n| n > 0) {
                                    Err(io::Error::new(
                                        io::ErrorKind::UnexpectedEof,
                                        "upload reader is shorter than its declared length",
                                    ))
                                } else {
                                    let last = tail.take();
                                    self.segments.pop_front();
                                    if let Some(last) = last {
                                        Ok(last)
                                    } else {
                                        continue;
                                    }
                                }
                            } else {
                                if let Some(n) = remaining {
                                    *n -= data.len() as u64;
                                }
                                let bytes = Bytes::copy_from_slice(data);
                                // Probe EOF before releasing the final known-length chunk.
                                if *remaining == Some(0) {
                                    *tail = Some(bytes);
                                    continue;
                                }
                                Ok(bytes)
                            }
                        }
                    }
                }
            };
            match next {
                Ok(bytes) => {
                    if let Some(remaining) = &mut self.remaining {
                        *remaining -= bytes.len() as u64;
                    }
                    return Poll::Ready(Some(Ok(Frame::data(bytes))));
                }
                Err(error) => {
                    self.segments.clear();
                    return Poll::Ready(Some(Err(error)));
                }
            }
        }
    }

    fn is_end_stream(&self) -> bool {
        self.segments.is_empty()
    }
    fn size_hint(&self) -> SizeHint {
        let mut hint = SizeHint::new();
        if let Some(length) = self.remaining {
            hint.set_exact(length);
        }
        hint
    }
}