lettermint-rs 0.3.1

Lettermint email service client
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
use std::borrow::Cow;
use std::future::Future;

use bytes::Bytes;
use http::{Request, Response, StatusCode};
use std::error::Error;
use thiserror::Error;
use tracing::Instrument;

/// A trait for providing the necessary information for a single REST API endpoint.
pub trait Endpoint {
    type Request: serde::Serialize + Send + Sync;
    type Response: serde::de::DeserializeOwned + Send + Sync;

    /// The path to the endpoint.
    fn endpoint(&self) -> Cow<'static, str>;
    /// The body for the endpoint.
    fn body(&self) -> &Self::Request;
    /// The HTTP method for the endpoint.
    fn method(&self) -> http::Method {
        http::Method::POST
    }
    /// Optional extra headers (e.g., Idempotency-Key).
    fn extra_headers(&self) -> Vec<(Cow<'static, str>, Cow<'static, str>)> {
        vec![]
    }
    /// Parse the raw response body into [`Self::Response`].
    ///
    /// The default implementation deserializes JSON. Override this for
    /// endpoints that return non-JSON responses (e.g. plain text).
    ///
    /// # Errors
    ///
    /// Returns a [`serde_json::Error`] if the body cannot be parsed.
    fn parse_response(&self, body: &[u8]) -> Result<Self::Response, serde_json::Error> {
        serde_json::from_slice(body)
    }
}

/// A trait which represents an asynchronous query which may be made to a Lettermint client.
pub trait Query<C> {
    type Result;
    /// Perform the query against the client.
    fn execute(self, client: &C) -> impl Future<Output = Self::Result> + Send;
}

/// An error thrown by the [`Query`] trait.
///
/// This enum is `#[non_exhaustive]` — new variants may be added in future
/// releases without a semver-breaking change.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum QueryError<E>
where
    E: Error + Send + Sync + 'static,
{
    #[error("client error: {}", source)]
    Client { source: E },

    #[error("failed to serialize request body: {}", source)]
    SerializeBody { source: serde_json::Error },

    #[error("could not parse JSON response: {}", source)]
    DeserializeResponse { source: serde_json::Error },

    #[error("failed to build request: {}", source)]
    Body {
        #[from]
        source: http::Error,
    },

    /// Validation error (HTTP 422) with per-field details.
    #[error("validation error: {message:?}")]
    Validation {
        error_type: Option<String>,
        message: Option<String>,
        /// Per-field validation errors (e.g., `{"from": ["domain not verified"]}`)
        errors: Option<std::collections::HashMap<String, Vec<String>>>,
        body: Bytes,
    },

    /// Authentication or authorization error (HTTP 401/403).
    #[error("authentication error: {message:?}")]
    Authentication {
        message: Option<String>,
        body: Bytes,
    },

    /// Rate limit exceeded (HTTP 429).
    #[error("rate limit exceeded: {message:?}")]
    RateLimit {
        message: Option<String>,
        body: Bytes,
    },

    /// Any other non-success API response.
    #[error("api error: status={status}, error_type={error_type:?}, message={message:?}")]
    Api {
        status: StatusCode,
        error_type: Option<String>,
        message: Option<String>,
        body: Bytes,
    },
}

impl<E> QueryError<E>
where
    E: Error + Send + Sync + 'static,
{
    pub fn client(source: E) -> Self {
        QueryError::Client { source }
    }
}

impl<T, C> Query<C> for T
where
    T: Endpoint + Send + Sync,
    C: Client + Send + Sync,
{
    type Result = Result<T::Response, QueryError<C::Error>>;

    async fn execute(self, client: &C) -> Self::Result {
        let method = self.method();
        let endpoint = self.endpoint();

        let span = tracing::debug_span!(
            "lettermint.request",
            method = %method,
            endpoint = %endpoint,
            status = tracing::field::Empty,
        );

        async {
            // Always format as an absolute path so http::Uri parses it correctly.
            // The Client implementation joins this with its base URL.
            let uri = format!("/{}", endpoint.trim_start_matches('/'));
            let mut req_builder = http::Request::builder()
                .method(method.clone())
                .uri(uri)
                .header("Accept", "application/json");

            for (name, value) in self.extra_headers() {
                req_builder = req_builder.header(name.as_ref(), value.as_ref());
            }

            let body = match method {
                http::Method::GET | http::Method::DELETE | http::Method::HEAD => Bytes::new(),
                _ => {
                    req_builder = req_builder.header("Content-Type", "application/json");
                    serde_json::to_vec(self.body())
                        .map_err(|e| {
                            tracing::error!(error = %e, "failed to serialize request body");
                            QueryError::SerializeBody { source: e }
                        })?
                        .into()
                }
            };

            let http_req = req_builder.body(body)?;
            let response = client.execute(http_req).await.map_err(|e| {
                tracing::error!(error = %e, "client transport error");
                QueryError::client(e)
            })?;

            let status = response.status();
            tracing::Span::current().record("status", status.as_u16());

            if !status.is_success() {
                #[derive(serde::Deserialize)]
                struct LettermintErrorBody {
                    error_type: Option<String>,
                    error: Option<String>,
                    message: Option<String>,
                    errors: Option<std::collections::HashMap<String, Vec<String>>>,
                }

                let body = response.body().clone();
                let parsed = serde_json::from_slice::<LettermintErrorBody>(&body).ok();
                let error_type = parsed
                    .as_ref()
                    .and_then(|p| p.error_type.clone().or_else(|| p.error.clone()));
                let message = parsed.as_ref().and_then(|p| p.message.clone());

                tracing::warn!(
                    status = status.as_u16(),
                    error_type = error_type.as_deref(),
                    message = message.as_deref(),
                    "API error response",
                );

                return Err(match status.as_u16() {
                    422 => QueryError::Validation {
                        error_type,
                        message,
                        errors: parsed.and_then(|p| p.errors),
                        body,
                    },
                    401 | 403 => QueryError::Authentication { message, body },
                    429 => QueryError::RateLimit { message, body },
                    _ => QueryError::Api {
                        status,
                        error_type,
                        message,
                        body,
                    },
                });
            }

            tracing::debug!(status = status.as_u16(), "request completed");

            self.parse_response(response.body()).map_err(|e| {
                tracing::error!(error = %e, "failed to deserialize response body");
                QueryError::DeserializeResponse { source: e }
            })
        }
        .instrument(span)
        .await
    }
}

/// A trait representing a client which can communicate with a Lettermint instance.
pub trait Client {
    type Error: Error + Send + Sync + 'static;
    fn execute(
        &self,
        req: Request<Bytes>,
    ) -> impl Future<Output = Result<Response<Bytes>, Self::Error>> + Send;
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::borrow::Cow;
    use std::sync::{Arc, Mutex};

    #[derive(Debug, thiserror::Error)]
    #[error("test client error")]
    struct MockClientError;

    #[derive(Clone)]
    struct MockClient {
        last_request: Arc<Mutex<Option<Request<Bytes>>>>,
        response_status: StatusCode,
        response_body: Bytes,
    }

    impl MockClient {
        fn ok(body: &'static [u8]) -> Self {
            Self {
                last_request: Arc::new(Mutex::new(None)),
                response_status: StatusCode::OK,
                response_body: Bytes::from_static(body),
            }
        }

        fn error(status: StatusCode, body: &'static [u8]) -> Self {
            Self {
                last_request: Arc::new(Mutex::new(None)),
                response_status: status,
                response_body: Bytes::from_static(body),
            }
        }

        fn last_request(&self) -> Request<Bytes> {
            self.last_request
                .lock()
                .expect("lock")
                .clone()
                .expect("request present")
        }
    }

    impl Client for MockClient {
        type Error = MockClientError;

        async fn execute(&self, req: Request<Bytes>) -> Result<Response<Bytes>, Self::Error> {
            *self.last_request.lock().expect("lock") = Some(req);
            Ok(Response::builder()
                .status(self.response_status)
                .body(self.response_body.clone())
                .expect("response"))
        }
    }

    #[derive(serde::Serialize)]
    struct TestBody {
        value: &'static str,
    }

    #[derive(Debug, serde::Deserialize, PartialEq)]
    struct TestResponse {
        ok: bool,
    }

    struct PostEndpoint {
        body: TestBody,
        extra: Vec<(Cow<'static, str>, Cow<'static, str>)>,
    }

    impl PostEndpoint {
        fn new() -> Self {
            Self {
                body: TestBody { value: "hello" },
                extra: vec![],
            }
        }

        fn with_extra_header(mut self, name: &'static str, value: impl Into<String>) -> Self {
            self.extra
                .push((Cow::Borrowed(name), Cow::Owned(value.into())));
            self
        }
    }

    impl Endpoint for PostEndpoint {
        type Request = TestBody;
        type Response = TestResponse;

        fn endpoint(&self) -> Cow<'static, str> {
            "send".into()
        }

        fn body(&self) -> &Self::Request {
            &self.body
        }

        fn extra_headers(&self) -> Vec<(Cow<'static, str>, Cow<'static, str>)> {
            self.extra.clone()
        }
    }

    #[derive(serde::Serialize)]
    struct NoBody;

    struct GetEndpoint;
    impl Endpoint for GetEndpoint {
        type Request = NoBody;
        type Response = TestResponse;

        fn endpoint(&self) -> Cow<'static, str> {
            "messages".into()
        }

        fn body(&self) -> &Self::Request {
            static BODY: NoBody = NoBody;
            &BODY
        }

        fn method(&self) -> http::Method {
            http::Method::GET
        }
    }

    #[tokio::test]
    async fn post_request_has_json_body_and_content_type() {
        let client = MockClient::ok(br#"{"ok":true}"#);
        let resp = PostEndpoint::new().execute(&client).await.expect("execute");
        assert!(resp.ok);

        let req = client.last_request();
        assert_eq!(req.method(), http::Method::POST);
        assert_eq!(req.body(), &Bytes::from_static(br#"{"value":"hello"}"#));
        assert_eq!(
            req.headers().get("Content-Type").unwrap().to_str().unwrap(),
            "application/json"
        );
        assert_eq!(
            req.headers().get("Accept").unwrap().to_str().unwrap(),
            "application/json"
        );
    }

    #[tokio::test]
    async fn get_request_has_no_body_or_content_type() {
        let client = MockClient::ok(br#"{"ok":true}"#);
        let resp = GetEndpoint.execute(&client).await.expect("execute");
        assert!(resp.ok);

        let req = client.last_request();
        assert_eq!(req.method(), http::Method::GET);
        assert!(req.body().is_empty());
        assert!(req.headers().get("Content-Type").is_none());
        assert!(req.headers().get("Accept").is_some());
    }

    #[tokio::test]
    async fn extra_headers_are_applied() {
        let client = MockClient::ok(br#"{"ok":true}"#);
        PostEndpoint::new()
            .with_extra_header("Idempotency-Key", "test-key")
            .execute(&client)
            .await
            .expect("execute");

        let req = client.last_request();
        assert_eq!(
            req.headers()
                .get("Idempotency-Key")
                .unwrap()
                .to_str()
                .unwrap(),
            "test-key"
        );
    }

    #[tokio::test]
    async fn validation_error_422() {
        let client = MockClient::error(
            StatusCode::UNPROCESSABLE_ENTITY,
            br#"{"error_type":"DailyLimitExceeded","message":"Limit reached"}"#,
        );

        let err = PostEndpoint::new()
            .execute(&client)
            .await
            .expect_err("should fail");

        match err {
            QueryError::Validation {
                error_type,
                message,
                ..
            } => {
                assert_eq!(error_type.as_deref(), Some("DailyLimitExceeded"));
                assert_eq!(message.as_deref(), Some("Limit reached"));
            }
            _ => panic!("expected Validation error, got: {err:?}"),
        }
    }

    #[tokio::test]
    async fn authentication_error_401() {
        let client = MockClient::error(
            StatusCode::UNAUTHORIZED,
            br#"{"message":"Invalid API token"}"#,
        );

        let err = PostEndpoint::new()
            .execute(&client)
            .await
            .expect_err("should fail");

        match err {
            QueryError::Authentication { message, .. } => {
                assert_eq!(message.as_deref(), Some("Invalid API token"));
            }
            _ => panic!("expected Authentication error, got: {err:?}"),
        }
    }

    #[tokio::test]
    async fn rate_limit_error_429() {
        let client = MockClient::error(
            StatusCode::TOO_MANY_REQUESTS,
            br#"{"message":"Rate limit exceeded"}"#,
        );

        let err = PostEndpoint::new()
            .execute(&client)
            .await
            .expect_err("should fail");

        match err {
            QueryError::RateLimit { message, .. } => {
                assert_eq!(message.as_deref(), Some("Rate limit exceeded"));
            }
            _ => panic!("expected RateLimit error, got: {err:?}"),
        }
    }

    #[tokio::test]
    async fn api_error_with_non_json_body() {
        let client = MockClient::error(StatusCode::BAD_GATEWAY, b"gateway timeout");

        let err = PostEndpoint::new()
            .execute(&client)
            .await
            .expect_err("should fail");

        match err {
            QueryError::Api {
                status,
                error_type,
                message,
                body,
            } => {
                assert_eq!(status, StatusCode::BAD_GATEWAY);
                assert_eq!(error_type, None);
                assert_eq!(message, None);
                assert_eq!(body, Bytes::from_static(b"gateway timeout"));
            }
            _ => panic!("expected Api error, got: {err:?}"),
        }
    }

    #[tokio::test]
    async fn success_with_invalid_json_returns_deserialize_error() {
        let client = MockClient::ok(b"not json");
        let err = PostEndpoint::new()
            .execute(&client)
            .await
            .expect_err("should fail");

        assert!(matches!(err, QueryError::DeserializeResponse { .. }));
    }

    #[tokio::test]
    async fn api_error_with_error_field_fallback() {
        let client = MockClient::error(
            StatusCode::BAD_REQUEST,
            br#"{"error":"invalid_request","message":"Bad from address"}"#,
        );

        let err = PostEndpoint::new()
            .execute(&client)
            .await
            .expect_err("should fail");

        match err {
            QueryError::Api {
                status,
                error_type,
                message,
                ..
            } => {
                assert_eq!(status, StatusCode::BAD_REQUEST);
                assert_eq!(error_type.as_deref(), Some("invalid_request"));
                assert_eq!(message.as_deref(), Some("Bad from address"));
            }
            _ => panic!("expected Api error, got: {err:?}"),
        }
    }

    #[tokio::test]
    async fn authentication_error_403() {
        let client = MockClient::error(StatusCode::FORBIDDEN, br#"{"message":"Access denied"}"#);

        let err = PostEndpoint::new()
            .execute(&client)
            .await
            .expect_err("should fail");

        assert!(matches!(err, QueryError::Authentication { .. }));
    }
}