1use std::{
5 collections::VecDeque,
6 future::{self, Future},
7 sync::{Arc, Mutex, MutexGuard, PoisonError},
8};
9
10use bytes::Bytes;
11
12use crate::{
13 http_client::{
14 self, HttpClientExt, LazyBody, MultipartForm, Request, Response, StreamingResponse,
15 },
16 wasm_compat::WasmCompatSend,
17};
18
19fn not_implemented() -> http_client::Error {
22 http_client::Error::non_success_with_details(
23 http::StatusCode::NOT_IMPLEMENTED,
24 http::HeaderMap::new(),
25 String::new(),
26 )
27}
28
29fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
31 mutex.lock().unwrap_or_else(PoisonError::into_inner)
32}
33
34macro_rules! no_unary_surface {
40 () => {
41 fn send(
42 &self,
43 _req: Request<Bytes>,
44 ) -> impl Future<Output = http_client::Result<Response<LazyBody>>>
45 + WasmCompatSend
46 + 'static {
47 future::ready(Err(not_implemented()))
48 }
49
50 fn send_multipart(
51 &self,
52 _req: Request<MultipartForm>,
53 ) -> impl Future<Output = http_client::Result<Response<LazyBody>>>
54 + WasmCompatSend
55 + 'static {
56 future::ready(Err(not_implemented()))
57 }
58 };
59}
60
61#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct CapturedHttpRequest {
64 pub uri: String,
66 pub headers: http::HeaderMap,
68 pub body: Bytes,
70}
71
72#[derive(Clone, Debug)]
74pub enum MockHttpResponse {
75 Success(Bytes),
77 SuccessWithHeaders(Bytes, http::HeaderMap),
80 ErrorResponse(http::StatusCode, Bytes),
83 ErrorWithHeaders(http::StatusCode, String, http::HeaderMap),
86 ErrorResponseWithHeaders(http::StatusCode, Bytes, http::HeaderMap),
89}
90
91impl MockHttpResponse {
92 pub fn success(body: impl Into<Bytes>) -> Self {
94 Self::Success(body.into())
95 }
96
97 pub fn success_typed(body: impl Into<Bytes>, content_type: &'static str) -> Self {
99 let mut headers = http::HeaderMap::new();
100 headers.insert(
101 http::header::CONTENT_TYPE,
102 http::HeaderValue::from_static(content_type),
103 );
104 Self::SuccessWithHeaders(body.into(), headers)
105 }
106
107 pub fn error(status: http::StatusCode, message: impl Into<String>) -> Self {
111 Self::error_with_headers(status, message, http::HeaderMap::new())
112 }
113
114 pub fn error_with_headers(
117 status: http::StatusCode,
118 message: impl Into<String>,
119 headers: http::HeaderMap,
120 ) -> Self {
121 Self::ErrorWithHeaders(status, message.into(), headers)
122 }
123}
124
125impl MockHttpResponse {
126 fn into_parts(self) -> http_client::Result<(http::StatusCode, Bytes, Option<http::HeaderMap>)> {
129 Ok(match self {
130 Self::Success(body) => (http::StatusCode::OK, body, None),
131 Self::SuccessWithHeaders(body, headers) => (http::StatusCode::OK, body, Some(headers)),
132 Self::ErrorWithHeaders(status, body, headers) => {
133 return Err(http_client::Error::InvalidStatusCodeWithDetails {
134 status,
135 body,
136 headers,
137 });
138 }
139 Self::ErrorResponse(status, body) => (status, body, None),
140 Self::ErrorResponseWithHeaders(status, body, headers) => (status, body, Some(headers)),
141 })
142 }
143}
144
145impl Default for MockHttpResponse {
146 fn default() -> Self {
147 Self::Success(Bytes::new())
148 }
149}
150
151#[derive(Clone, Debug, Default)]
154pub struct RecordingHttpClient {
155 requests: Arc<Mutex<Vec<CapturedHttpRequest>>>,
156 response: Arc<Mutex<MockHttpResponse>>,
157}
158
159impl RecordingHttpClient {
160 fn scripted(response: MockHttpResponse) -> Self {
162 Self {
163 requests: Arc::default(),
164 response: Arc::new(Mutex::new(response)),
165 }
166 }
167
168 pub fn new(response_body: impl Into<Bytes>) -> Self {
170 Self::scripted(MockHttpResponse::success(response_body))
171 }
172
173 pub fn with_error(status: http::StatusCode, message: impl Into<String>) -> Self {
175 Self::scripted(MockHttpResponse::error(status, message))
176 }
177
178 pub fn with_error_headers(
182 status: http::StatusCode,
183 message: impl Into<String>,
184 headers: http::HeaderMap,
185 ) -> Self {
186 Self::scripted(MockHttpResponse::error_with_headers(
187 status, message, headers,
188 ))
189 }
190
191 pub fn with_error_response_headers(
194 status: http::StatusCode,
195 body: impl Into<Bytes>,
196 headers: http::HeaderMap,
197 ) -> Self {
198 Self::scripted(MockHttpResponse::ErrorResponseWithHeaders(
199 status,
200 body.into(),
201 headers,
202 ))
203 }
204
205 pub fn requests(&self) -> Vec<CapturedHttpRequest> {
207 lock(&self.requests).clone()
208 }
209
210 fn record_request(&self, uri: String, headers: http::HeaderMap, body: Bytes) {
211 lock(&self.requests).push(CapturedHttpRequest { uri, headers, body });
212 }
213
214 fn build_unary_response(response: MockHttpResponse) -> http_client::Result<Response<LazyBody>> {
215 let (status, response_body, response_headers) = response.into_parts()?;
216 let body: LazyBody = Box::pin(async move { Ok(response_body) });
217 let mut builder = Response::builder().status(status);
218 if let Some(headers) = response_headers
219 && let Some(slot) = builder.headers_mut()
220 {
221 *slot = headers;
222 }
223 builder.body(body).map_err(http_client::Error::Protocol)
224 }
225}
226
227impl HttpClientExt for RecordingHttpClient {
228 fn send(
229 &self,
230 req: Request<Bytes>,
231 ) -> impl Future<Output = http_client::Result<Response<LazyBody>>> + WasmCompatSend + 'static
232 {
233 let response = lock(&self.response).clone();
234 let (parts, body) = req.into_parts();
235 self.record_request(parts.uri.to_string(), parts.headers, body);
236
237 async move { Self::build_unary_response(response) }
238 }
239
240 fn send_multipart(
241 &self,
242 req: Request<MultipartForm>,
243 ) -> impl Future<Output = http_client::Result<Response<LazyBody>>> + WasmCompatSend + 'static
244 {
245 let response = lock(&self.response).clone();
246 let (parts, body) = req.into_parts();
247 let (_, body) = body.boundary("recording-http-client").encode();
248 self.record_request(parts.uri.to_string(), parts.headers, body);
249
250 async move { Self::build_unary_response(response) }
251 }
252
253 fn send_streaming(
254 &self,
255 _req: Request<Bytes>,
256 ) -> impl Future<Output = http_client::Result<StreamingResponse>> + WasmCompatSend {
257 future::ready(Err(not_implemented()))
258 }
259}
260
261#[derive(Clone, Debug, Default)]
268pub struct SequencedHttpClient {
269 requests: Arc<Mutex<Vec<CapturedHttpRequest>>>,
270 responses: Arc<Mutex<VecDeque<MockHttpResponse>>>,
271}
272
273impl SequencedHttpClient {
274 pub fn new(responses: impl IntoIterator<Item = MockHttpResponse>) -> Self {
276 Self {
277 requests: Arc::new(Mutex::new(Vec::new())),
278 responses: Arc::new(Mutex::new(responses.into_iter().collect())),
279 }
280 }
281
282 pub fn requests(&self) -> Vec<CapturedHttpRequest> {
284 lock(&self.requests).clone()
285 }
286
287 pub fn remaining_responses(&self) -> usize {
289 lock(&self.responses).len()
290 }
291
292 fn answer(&self, parts: http::request::Parts, body: Bytes) -> Option<MockHttpResponse> {
295 lock(&self.requests).push(CapturedHttpRequest {
296 uri: parts.uri.to_string(),
297 headers: parts.headers,
298 body,
299 });
300 lock(&self.responses).pop_front()
301 }
302}
303
304impl HttpClientExt for SequencedHttpClient {
305 fn send(
306 &self,
307 req: Request<Bytes>,
308 ) -> impl Future<Output = http_client::Result<Response<LazyBody>>> + WasmCompatSend + 'static
309 {
310 let (parts, body) = req.into_parts();
311 let response = self.answer(parts, body);
312 async move { RecordingHttpClient::build_unary_response(response.ok_or_else(not_implemented)?) }
313 }
314
315 fn send_multipart(
316 &self,
317 req: Request<MultipartForm>,
318 ) -> impl Future<Output = http_client::Result<Response<LazyBody>>> + WasmCompatSend + 'static
319 {
320 let (parts, _body) = req.into_parts();
321 let response = self.answer(parts, Bytes::new());
322 async move { RecordingHttpClient::build_unary_response(response.ok_or_else(not_implemented)?) }
323 }
324
325 fn send_streaming(
326 &self,
327 req: Request<Bytes>,
328 ) -> impl Future<Output = http_client::Result<StreamingResponse>> + WasmCompatSend {
329 let (parts, body) = req.into_parts();
330 let response = self.answer(parts, body);
331 future::ready(
332 response
333 .ok_or_else(not_implemented)
334 .and_then(streaming_response),
335 )
336 }
337}
338
339fn streaming_response(response: MockHttpResponse) -> http_client::Result<StreamingResponse> {
341 let (status, body, headers) = response.into_parts()?;
342 let chunks: http_client::BoxedStream = Box::pin(futures::stream::iter([Ok::<
343 Bytes,
344 http_client::Error,
345 >(body)]));
346 let mut response = Response::builder()
347 .status(status)
348 .body(chunks)
349 .map_err(http_client::Error::Protocol)?;
350 if let Some(headers) = headers {
351 *response.headers_mut() = headers;
352 }
353 Ok(response)
354}
355
356#[derive(Clone, Debug, Default)]
360pub struct MockStreamingClient {
361 pub sse_bytes: Bytes,
363}
364
365impl HttpClientExt for MockStreamingClient {
366 no_unary_surface!();
367
368 fn send_streaming(
369 &self,
370 _req: Request<Bytes>,
371 ) -> impl Future<Output = http_client::Result<StreamingResponse>> + WasmCompatSend {
372 let sse_bytes = self.sse_bytes.clone();
373 async move {
374 let byte_stream =
375 futures::stream::iter(vec![Ok::<Bytes, http_client::Error>(sse_bytes)]);
376 let boxed_stream: http_client::BoxedStream = Box::pin(byte_stream);
377
378 Response::builder()
379 .status(http::StatusCode::OK)
380 .header(http::header::CONTENT_TYPE, "text/event-stream")
381 .body(boxed_stream)
382 .map_err(http_client::Error::Protocol)
383 }
384 }
385}
386
387#[derive(Clone, Debug, Default)]
390pub struct SilentStreamingClient;
391
392impl HttpClientExt for SilentStreamingClient {
393 no_unary_surface!();
394
395 fn send_streaming(
396 &self,
397 _req: Request<Bytes>,
398 ) -> impl Future<Output = http_client::Result<StreamingResponse>> + WasmCompatSend {
399 std::future::pending()
400 }
401}
402
403#[derive(Clone, Debug, Default)]
406pub struct PacedStreamingClient {
407 pub chunks: Vec<&'static str>,
409 pub gap: std::time::Duration,
411}
412
413impl HttpClientExt for PacedStreamingClient {
414 no_unary_surface!();
415
416 fn send_streaming(
417 &self,
418 _req: Request<Bytes>,
419 ) -> impl Future<Output = http_client::Result<StreamingResponse>> + WasmCompatSend {
420 let (chunks, gap) = (self.chunks.clone(), self.gap);
421 async move {
422 let byte_stream =
423 futures::StreamExt::then(futures::stream::iter(chunks), move |chunk| async move {
424 crate::wasm_compat::sleep(gap).await;
425 Ok::<Bytes, http_client::Error>(Bytes::from_static(chunk.as_bytes()))
426 });
427 let byte_stream = futures::StreamExt::chain(byte_stream, futures::stream::pending());
428 let boxed_stream: http_client::BoxedStream = Box::pin(byte_stream);
429 Response::builder()
430 .status(http::StatusCode::OK)
431 .header(http::header::CONTENT_TYPE, "text/event-stream")
432 .body(boxed_stream)
433 .map_err(http_client::Error::Protocol)
434 }
435 }
436}
437
438#[derive(Debug, Clone)]
441pub struct HttpErrorStreamingClient {
442 pub status: http::StatusCode,
443 pub body: String,
444}
445
446impl HttpErrorStreamingClient {
447 pub fn new(status: http::StatusCode, body: impl Into<String>) -> Self {
449 Self {
450 status,
451 body: body.into(),
452 }
453 }
454}
455
456impl Default for HttpErrorStreamingClient {
457 fn default() -> Self {
460 Self::new(http::StatusCode::INTERNAL_SERVER_ERROR, String::new())
461 }
462}
463
464impl HttpClientExt for HttpErrorStreamingClient {
465 no_unary_surface!();
466
467 fn send_streaming(
468 &self,
469 _req: Request<Bytes>,
470 ) -> impl Future<Output = http_client::Result<StreamingResponse>> + WasmCompatSend {
471 let status = self.status;
472 let body = self.body.clone();
473 async move {
474 Err(http_client::Error::non_success_with_details(
475 status,
476 http::HeaderMap::new(),
477 body,
478 ))
479 }
480 }
481}
482
483#[derive(Debug, Clone)]
487pub struct NonSuccessStreamingClient {
488 pub status: http::StatusCode,
489 pub headers: http::HeaderMap,
490 pub body: Bytes,
491}
492
493impl HttpClientExt for NonSuccessStreamingClient {
494 no_unary_surface!();
495
496 fn send_streaming(
497 &self,
498 _req: Request<Bytes>,
499 ) -> impl Future<Output = http_client::Result<StreamingResponse>> + WasmCompatSend {
500 let status = self.status;
501 let headers = self.headers.clone();
502 let body = self.body.clone();
503 async move {
504 let byte_stream = futures::stream::iter(vec![Ok::<Bytes, http_client::Error>(body)]);
505 let boxed_stream: http_client::BoxedStream = Box::pin(byte_stream);
506 let mut response = Response::builder()
507 .status(status)
508 .body(boxed_stream)
509 .map_err(http_client::Error::Protocol)?;
510 *response.headers_mut() = headers;
511 Ok(response)
512 }
513 }
514}
515
516#[derive(Debug, Clone, Default)]
519pub struct SequencedStreamingHttpClient {
520 chunks: Arc<Mutex<Option<Vec<http_client::Result<Bytes>>>>>,
521}
522
523impl SequencedStreamingHttpClient {
524 pub fn new(chunks: Vec<http_client::Result<Bytes>>) -> Self {
526 Self {
527 chunks: Arc::new(Mutex::new(Some(chunks))),
528 }
529 }
530}
531
532impl HttpClientExt for SequencedStreamingHttpClient {
533 no_unary_surface!();
534
535 fn send_streaming(
536 &self,
537 _req: Request<Bytes>,
538 ) -> impl Future<Output = http_client::Result<StreamingResponse>> + WasmCompatSend {
539 let chunks = lock(&self.chunks).take();
540
541 async move {
542 let Some(chunks) = chunks else {
543 return Err(http_client::Error::non_success_with_details(
544 http::StatusCode::INTERNAL_SERVER_ERROR,
545 http::HeaderMap::new(),
546 "streaming chunks should only be consumed once".to_string(),
547 ));
548 };
549
550 let byte_stream = futures::stream::iter(chunks);
551 let boxed_stream: http_client::BoxedStream = Box::pin(byte_stream);
552
553 Response::builder()
554 .status(http::StatusCode::OK)
555 .header(http::header::CONTENT_TYPE, "text/event-stream")
556 .body(boxed_stream)
557 .map_err(http_client::Error::Protocol)
558 }
559 }
560}