openapi-contract 0.1.0

Compile-time OpenAPI contract checking for Rust HTTP clients. Validates paths, parameters, and response types against your OpenAPI spec at macro expansion.
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
use std::marker::PhantomData;

use futures_core::Stream;
use serde::de::DeserializeOwned;

use crate::client::{ApiClient, Method};
use crate::error::{ApiError, DefinedErrorBody};
use crate::sse::SseEvent;

fn parse_error_response(status: u16, body: String) -> ApiError {
    if let Ok(parsed) = serde_json::from_str::<DefinedErrorBody>(&body) {
        if parsed.defined && !parsed.code.is_empty() {
            return ApiError::Defined {
                status,
                code: parsed.code,
                message: parsed.message,
            };
        }
    }
    ApiError::Api {
        status,
        message: body,
    }
}

/// A type-safe API request built by the `api!` macro.
///
/// `T` is the expected response type, inferred from the OpenAPI spec at compile time.
pub struct ApiRequest<T> {
    pub method: Method,
    pub path: String,
    pub query: Option<String>,
    pub body: Option<String>,
    pub _marker: PhantomData<T>,
}

impl<T> ApiRequest<T> {
    pub fn new(method: Method, path: String) -> Self {
        Self {
            method,
            path,
            query: None,
            body: None,
            _marker: PhantomData,
        }
    }

    pub fn query_raw(mut self, qs: impl Into<String>) -> Self {
        self.query = Some(qs.into());
        self
    }

    pub fn body_json(mut self, body: &impl serde::Serialize) -> Self {
        self.body = Some(serde_json::to_string(body).expect("request body must be serializable"));
        self
    }

    /// Set a pre-serialized JSON body. Returns an error if serialization fails.
    pub fn try_body_json(mut self, body: &impl serde::Serialize) -> Result<Self, ApiError> {
        self.body = Some(serde_json::to_string(body)?);
        Ok(self)
    }
}

impl<T: DeserializeOwned> ApiRequest<T> {
    /// Execute the request and deserialize the response.
    pub async fn fetch(self, client: &(impl ApiClient + ?Sized)) -> Result<T, ApiError> {
        let resp = client
            .request(self.method, &self.path, self.query.as_deref(), self.body)
            .await?;

        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(parse_error_response(status.as_u16(), body));
        }

        let text = resp.text().await?;
        if text.is_empty() {
            return serde_json::from_str("null").map_err(ApiError::from);
        }
        serde_json::from_str(&text).map_err(ApiError::from)
    }
}

impl ApiRequest<()> {
    /// Execute a request that returns no body (e.g. DELETE, PUT with 204).
    pub async fn fetch_empty(self, client: &(impl ApiClient + ?Sized)) -> Result<(), ApiError> {
        let resp = client
            .request(self.method, &self.path, self.query.as_deref(), self.body)
            .await?;

        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(parse_error_response(status.as_u16(), body));
        }
        Ok(())
    }
}

impl<T> ApiRequest<T> {
    /// Execute the request and return an SSE event stream.
    pub async fn fetch_stream(
        self,
        client: &(impl ApiClient + ?Sized),
    ) -> Result<impl Stream<Item = Result<SseEvent, ApiError>>, ApiError> {
        let stream = client
            .request_stream(self.method, &self.path, self.query.as_deref())
            .await?;
        Ok(stream)
    }
}

fn percent_encode(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    for byte in input.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(byte as char);
            }
            _ => {
                out.push('%');
                out.push_str(&format!("{:02X}", byte));
            }
        }
    }
    out
}

/// Build a URL-encoded query string from key-value pairs.
pub fn build_query_string(pairs: &[(&str, &dyn ToString)]) -> String {
    pairs
        .iter()
        .map(|(k, v)| format!("{}={}", percent_encode(k), percent_encode(&v.to_string())))
        .collect::<Vec<_>>()
        .join("&")
}

#[cfg(test)]
#[allow(clippy::manual_async_fn)]
mod tests {
    use super::*;
    use crate::sse::SseStream;
    use tokio::io::AsyncWriteExt;
    use tokio::time::{sleep, Duration};

    // ── Helpers ─────────────────────────────────────────────────

    async fn mock_response(status: u16, body: &str) -> reqwest::Response {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", "/mock")
            .with_status(status as usize)
            .with_header("content-type", "application/json")
            .with_body(body)
            .create_async()
            .await;
        reqwest::get(&format!("{}/mock", server.url()))
            .await
            .unwrap()
    }

    fn make_reqwest_error() -> reqwest::Error {
        reqwest::Client::new()
            .get("http://localhost:1/x")
            .header("bad\0header", "v")
            .build()
            .unwrap_err()
    }

    async fn malformed_chunked_response() -> reqwest::Response {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            let (mut socket, _) = listener.accept().await.unwrap();
            socket
                .write_all(
                    b"HTTP/1.1 200 OK\r\n\
Content-Type: application/json\r\n\
Content-Length: 40\r\n\
Connection: close\r\n\
\r\n\
{}",
                )
                .await
                .unwrap();
            sleep(Duration::from_millis(250)).await;
            socket.shutdown().await.unwrap();
        });
        let resp = reqwest::get(format!("http://{addr}")).await.unwrap();
        let _ = server.await;
        resp
    }

    struct MockClient {
        status: u16,
        body: String,
    }
    struct FailingClient;
    struct MalformedBodyClient;

    impl ApiClient for MockClient {
        fn request(
            &self,
            _: Method,
            _: &str,
            _: Option<&str>,
            _: Option<String>,
        ) -> impl std::future::Future<Output = Result<reqwest::Response, ApiError>> + Send {
            let status = self.status;
            let body = self.body.clone();
            async move { Ok(mock_response(status, &body).await) }
        }
        fn request_stream(
            &self,
            _: Method,
            _: &str,
            _: Option<&str>,
        ) -> impl std::future::Future<Output = Result<SseStream, ApiError>> + Send {
            async move {
                let chunks: Vec<Result<bytes::Bytes, reqwest::Error>> =
                    vec![Ok(bytes::Bytes::from(&b"data: hi\n\n"[..]))];
                Ok(SseStream::new(Box::pin(futures_util::stream::iter(chunks))))
            }
        }
    }

    impl ApiClient for FailingClient {
        fn request(
            &self,
            _: Method,
            _: &str,
            _: Option<&str>,
            _: Option<String>,
        ) -> impl std::future::Future<Output = Result<reqwest::Response, ApiError>> + Send {
            async { Err(ApiError::Http(make_reqwest_error())) }
        }
        fn request_stream(
            &self,
            _: Method,
            _: &str,
            _: Option<&str>,
        ) -> impl std::future::Future<Output = Result<SseStream, ApiError>> + Send {
            async { Err(ApiError::Http(make_reqwest_error())) }
        }
    }

    impl ApiClient for MalformedBodyClient {
        fn request(
            &self,
            _: Method,
            _: &str,
            _: Option<&str>,
            _: Option<String>,
        ) -> impl std::future::Future<Output = Result<reqwest::Response, ApiError>> + Send {
            async { Ok(malformed_chunked_response().await) }
        }
        fn request_stream(
            &self,
            _: Method,
            _: &str,
            _: Option<&str>,
        ) -> impl std::future::Future<Output = Result<SseStream, ApiError>> + Send {
            async { Err(ApiError::Http(make_reqwest_error())) }
        }
    }

    // ── Builder tests ───────────────────────────────────────────

    #[test]
    fn api_request_builder() {
        // new
        let req = ApiRequest::<String>::new(Method::GET, "/test".into());
        assert_eq!(req.method, Method::GET);
        assert_eq!(req.path, "/test");
        assert!(req.query.is_none());
        assert!(req.body.is_none());

        // chaining query + body
        let body = serde_json::json!({"x": 1});
        let req = ApiRequest::<String>::new(Method::POST, "/x".into())
            .query_raw("q=1")
            .body_json(&body);
        assert_eq!(req.query.as_deref(), Some("q=1"));
        assert_eq!(req.body.as_deref(), Some(r#"{"x":1}"#));
    }

    #[test]
    fn body_serialization() {
        // try_body_json success
        let req = ApiRequest::<String>::new(Method::POST, "/t".into())
            .try_body_json(&serde_json::json!({"x": 1}))
            .unwrap();
        assert!(req.body.is_some());

        // try_body_json failure
        #[derive(Debug)]
        struct Bad;
        impl serde::Serialize for Bad {
            fn serialize<S: serde::Serializer>(&self, _: S) -> Result<S::Ok, S::Error> {
                Err(serde::ser::Error::custom("fail"))
            }
        }
        assert!(ApiRequest::<String>::new(Method::POST, "/t".into())
            .try_body_json(&Bad)
            .is_err());
    }

    #[test]
    #[should_panic(expected = "request body must be serializable")]
    fn body_json_panics_on_bad_input() {
        #[derive(Debug)]
        struct Bad;
        impl serde::Serialize for Bad {
            fn serialize<S: serde::Serializer>(&self, _: S) -> Result<S::Ok, S::Error> {
                Err(serde::ser::Error::custom("fail"))
            }
        }
        let _ = ApiRequest::<String>::new(Method::POST, "/t".into()).body_json(&Bad);
    }

    #[test]
    fn query_string_and_percent_encode() {
        assert_eq!(build_query_string(&[]), "");
        assert_eq!(build_query_string(&[("limit", &10)]), "limit=10");
        assert_eq!(
            build_query_string(&[("a", &"hello"), ("b", &42)]),
            "a=hello&b=42"
        );
        assert_eq!(
            build_query_string(&[("q", &"hello world"), ("x", &"a&b=c")]),
            "q=hello%20world&x=a%26b%3Dc"
        );
        assert_eq!(percent_encode("abc-_.~123"), "abc-_.~123");
        assert_eq!(percent_encode("&="), "%26%3D");
    }

    // ── fetch tests ─────────────────────────────────────────────

    #[tokio::test]
    async fn fetch_success_and_edge_cases() {
        // Normal success
        let client = MockClient {
            status: 200,
            body: r#""hello""#.into(),
        };
        assert_eq!(
            ApiRequest::<String>::new(Method::GET, "/t".into())
                .fetch(&client)
                .await
                .unwrap(),
            "hello"
        );

        // Empty body → null
        let client = MockClient {
            status: 200,
            body: String::new(),
        };
        let result: Option<String> = ApiRequest::new(Method::GET, "/t".into())
            .fetch(&client)
            .await
            .unwrap();
        assert_eq!(result, None);

        // Deserialization error
        let client = MockClient {
            status: 200,
            body: "not-json".into(),
        };
        assert!(ApiRequest::<i32>::new(Method::GET, "/t".into())
            .fetch(&client)
            .await
            .unwrap_err()
            .to_string()
            .starts_with("serialization error:"));
    }

    #[tokio::test]
    async fn fetch_error_responses() {
        // Plain API error
        let client = MockClient {
            status: 403,
            body: "forbidden".into(),
        };
        let err = ApiRequest::<String>::new(Method::GET, "/t".into())
            .fetch(&client)
            .await
            .unwrap_err();
        assert!(matches!(err, ApiError::Api { status: 403, .. }));

        // Defined error
        let client = MockClient {
            status: 404,
            body: r#"{"defined":true,"code":"TEAM_NOT_FOUND","message":"Team not found"}"#.into(),
        };
        let err = ApiRequest::<String>::new(Method::GET, "/t".into())
            .fetch(&client)
            .await
            .unwrap_err();
        assert!(err.is_code("TEAM_NOT_FOUND"));
        assert_eq!(err.status(), Some(404));

        // Non-defined JSON fallback
        let client = MockClient {
            status: 400,
            body: r#"{"defined":false,"code":"NOPE","message":"nope"}"#.into(),
        };
        let err = ApiRequest::<String>::new(Method::GET, "/t".into())
            .fetch(&client)
            .await
            .unwrap_err();
        assert!(matches!(err, ApiError::Api { status: 400, .. }));
        assert_eq!(err.code(), None);
    }

    #[tokio::test]
    async fn fetch_empty_success_and_errors() {
        // Success
        let client = MockClient {
            status: 204,
            body: String::new(),
        };
        assert!(ApiRequest::<()>::new(Method::DELETE, "/t".into())
            .fetch_empty(&client)
            .await
            .is_ok());

        // API error
        let client = MockClient {
            status: 500,
            body: "oops".into(),
        };
        assert!(matches!(
            ApiRequest::<()>::new(Method::DELETE, "/t".into())
                .fetch_empty(&client)
                .await
                .unwrap_err(),
            ApiError::Api { status: 500, .. }
        ));

        // Defined error
        let client = MockClient {
            status: 403,
            body: r#"{"defined":true,"code":"FORBIDDEN","message":"no access"}"#.into(),
        };
        let err = ApiRequest::<()>::new(Method::DELETE, "/t".into())
            .fetch_empty(&client)
            .await
            .unwrap_err();
        assert!(err.is_code("FORBIDDEN"));

        // Request error propagation
        assert!(ApiRequest::<()>::new(Method::DELETE, "/t".into())
            .fetch_empty(&FailingClient)
            .await
            .unwrap_err()
            .to_string()
            .starts_with("HTTP error:"));
    }

    #[tokio::test]
    async fn fetch_stream_success_and_errors() {
        use futures_util::StreamExt;

        // Success
        let client = MockClient {
            status: 200,
            body: String::new(),
        };
        let mut stream = ApiRequest::<()>::new(Method::GET, "/sse".into())
            .fetch_stream(&client)
            .await
            .unwrap();
        assert_eq!(stream.next().await.unwrap().unwrap().data, "hi");

        // Request error propagation
        assert!(ApiRequest::<()>::new(Method::GET, "/sse".into())
            .fetch_stream(&FailingClient)
            .await
            .is_err());
    }

    #[tokio::test]
    async fn fetch_propagates_body_read_error() {
        let err = ApiRequest::<String>::new(Method::GET, "/t".into())
            .fetch(&MalformedBodyClient)
            .await
            .unwrap_err();
        assert!(err.to_string().starts_with("HTTP error:"));
    }
}