id_effect_platform 0.4.0

Platform capability traits (HTTP, FS, process) for id_effect — @effect/platform-style boundaries
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
//! [`reqwest`](https://docs.rs/reqwest) helpers: `send`, JSON/schema decode, and client pools.
//!
//! For portable [`HttpClient`] / [`HttpRequest`] boundaries, use the parent [`super`] module
//! (`execute`, `execute_stream`, [`ReqwestHttpClient`]).

#![allow(
  clippy::new_ret_no_self,
  clippy::unused_unit,
  dead_code,
  unused_imports
)]

use ::id_effect::{
  Cap, CapBindR, Needs, Never, Pool, Schema, Scope, effect, fail, from_async, kernel::Effect,
};
use std::sync::Arc;

#[path = "reqwest_providers.rs"]
mod reqwest_providers;
use id_effect::data::EffectData;
use id_effect::schema::{ParseError, Unknown};
use reqwest::{Client, Error, RequestBuilder, Response};
pub use reqwest_providers::{ReqwestClientLive, provide_reqwest_client, provide_reqwest_pool};
use serde_json::Value;

mod reqwest_client_cap {
  use super::Client;
  /// Injectable [`reqwest::Client`] in the capability environment.
  #[derive(Clone, Debug)]
  pub struct ReqwestClient(pub Client);

  impl std::ops::Deref for ReqwestClient {
    type Target = Client;

    fn deref(&self) -> &Self::Target {
      &self.0
    }
  }
}
pub use reqwest_client_cap::ReqwestClient;

/// Wraps [`Client`] in an [`Arc`] so it can live in [`Pool`] ([`PartialEq`] uses pointer identity).
#[derive(Clone, Debug)]
pub struct PooledClient(Arc<Client>);

impl PooledClient {
  /// Allocation identity of the inner [`Client`] (for tests / pooling assertions).
  #[inline]
  pub fn allocation_ptr(&self) -> *const Client {
    Arc::as_ptr(&self.0)
  }
}

impl std::ops::Deref for PooledClient {
  type Target = Client;

  fn deref(&self) -> &Self::Target {
    &self.0
  }
}

impl PartialEq for PooledClient {
  fn eq(&self, other: &Self) -> bool {
    Arc::ptr_eq(&self.0, &other.0)
  }
}

impl Eq for PooledClient {}

mod reqwest_pool_cap {
  use super::{Never, PooledClient};
  use ::id_effect::Pool;
  /// Injectable [`Pool`] of [`PooledClient`] in the capability environment.
  pub type ReqwestPool = Pool<PooledClient, Never>;
}
pub use reqwest_pool_cap::ReqwestPool;

/// [`send`] with a client checked out from [`ReqwestPool`]; returns to the pool when the inner scope closes.
#[inline]
pub fn send_pooled<A, E, R, F>(build: F) -> Effect<A, E, R>
where
  A: From<Response> + 'static,
  E: From<Error> + 'static,
  R: Needs<ReqwestPool> + CapBindR + 'static,
  F: FnOnce(&Client) -> RequestBuilder + Send + 'static,
{
  effect!(|r: &mut R| {
    let pool = Needs::<ReqwestPool>::need(r).clone();
    let (pooled, scope) = ~from_async(move |_r: &mut R| async move {
      let mut scope = Scope::make();
      let pooled = pool
        .get()
        .run(&mut scope)
        .await
        .expect("pool factory is infallible");
      Ok::<(PooledClient, Scope), E>((pooled, scope))
    });
    let resp = ~from_async(move |_r: &mut R| async move {
      build(&pooled).send().await.map_err(E::from)
    });
    scope.close();
    A::from(resp)
  })
}

/// Failure from [`json_schema`].
#[derive(Debug)]
pub enum JsonSchemaError {
  /// HTTP transport or status failure from the underlying [`reqwest`] client.
  Http(Error),
  /// Invalid JSON (syntax); see message.
  Json(String),
  /// Response body did not match the expected [`Schema`].
  Schema(ParseError),
}

fn unknown_from_json_value(value: Value) -> Unknown {
  id_effect::schema::serde_bridge::unknown_from_serde_json(value)
}

fn decode_response_schema<A, I, Es>(
  schema: &Schema<A, I, Es>,
  bytes: &[u8],
) -> Result<A, JsonSchemaError>
where
  Es: EffectData + 'static,
  A: 'static,
  I: 'static,
{
  let v: Value = serde_json::from_slice(bytes).map_err(|e| JsonSchemaError::Json(e.to_string()))?;
  let u = unknown_from_json_value(v);
  schema.decode_unknown(&u).map_err(JsonSchemaError::Schema)
}

/// [`send`] then decode the response body as JSON through `schema` ([`Schema::decode_unknown`]).
#[inline]
pub fn json_schema<R, F, A, I, Es>(
  schema: Arc<Schema<A, I, Es>>,
  build: F,
) -> Effect<A, JsonSchemaError, R>
where
  R: Needs<ReqwestClient> + CapBindR + 'static,
  F: FnOnce(&Client) -> RequestBuilder + Send + 'static,
  Es: EffectData + 'static,
  A: 'static,
  I: 'static,
{
  effect!(|r: &mut R| {
    let client = Needs::<ReqwestClient>::need(r).clone();
    let schema_arc = Arc::clone(&schema);
    let resp = ~from_async(move |_r: &mut R| async move {
      build(&*client).send().await.map_err(JsonSchemaError::Http)
    });
    let buf = ~from_async(move |_r: &mut R| async move {
      resp.bytes().await.map_err(JsonSchemaError::Http)
    });
    match decode_response_schema(&schema_arc, &buf) {
      Ok(v) => v,
      Err(e) => ~fail::<A, JsonSchemaError, R>(e),
    }
  })
}

/// Run [`RequestBuilder::send`](reqwest::RequestBuilder::send) using the client from `R`.
#[inline]
pub fn send<A, E, R, F>(build: F) -> Effect<A, E, R>
where
  A: From<Response> + 'static,
  E: From<Error> + 'static,
  R: Needs<ReqwestClient> + CapBindR + 'static,
  F: FnOnce(&Client) -> RequestBuilder + Send + 'static,
{
  effect!(|r: &mut R| {
    let client = Needs::<ReqwestClient>::need(r).clone();
    ~from_async(move |_r: &mut R| async move {
      build(&*client)
        .send()
        .await
        .map_err(E::from)
        .map(A::from)
    })
  })
}

/// [`send`] then [`Response::text`](reqwest::Response::text).
#[inline]
pub fn text<A, E, R, F>(build: F) -> Effect<A, E, R>
where
  A: From<String> + 'static,
  E: From<Error> + 'static,
  R: Needs<ReqwestClient> + CapBindR + 'static,
  F: FnOnce(&Client) -> RequestBuilder + Send + 'static,
{
  effect!(|r: &mut R| {
    let client = Needs::<ReqwestClient>::need(r).clone();
    let resp = ~from_async(move |_r: &mut R| async move {
      build(&*client).send().await.map_err(E::from)
    });
    let body = ~from_async(move |_r: &mut R| async move {
      resp.text().await.map_err(E::from)
    });
    A::from(body)
  })
}

/// [`send`] then [`Response::bytes`](reqwest::Response::bytes).
#[inline]
pub fn bytes<A, E, R, F>(build: F) -> Effect<A, E, R>
where
  A: From<bytes::Bytes> + 'static,
  E: From<Error> + 'static,
  R: Needs<ReqwestClient> + CapBindR + 'static,
  F: FnOnce(&Client) -> RequestBuilder + Send + 'static,
{
  effect!(|r: &mut R| {
    let client = Needs::<ReqwestClient>::need(r).clone();
    let resp = ~from_async(move |_r: &mut R| async move {
      build(&*client).send().await.map_err(E::from)
    });
    let body = ~from_async(move |_r: &mut R| async move {
      resp.bytes().await.map_err(E::from)
    });
    A::from(body)
  })
}

/// [`send`] then [`Response::json`](reqwest::Response::json).
#[inline]
pub fn json<A, E, R, F, T>(build: F) -> Effect<A, E, R>
where
  A: From<T> + 'static,
  E: From<Error> + 'static,
  R: Needs<ReqwestClient> + CapBindR + 'static,
  F: FnOnce(&Client) -> RequestBuilder + Send + 'static,
  T: serde::de::DeserializeOwned + 'static,
{
  effect!(|r: &mut R| {
    let client = Needs::<ReqwestClient>::need(r).clone();
    let resp = ~from_async(move |_r: &mut R| async move {
      build(&*client).send().await.map_err(E::from)
    });
    let value = ~from_async(move |_r: &mut R| async move {
      resp.json::<T>().await.map_err(E::from)
    });
    A::from(value)
  })
}

/// Shorthand for [`send`]`(|c| c.get(url))`.
#[inline]
pub fn get<A, E, R>(url: String) -> Effect<A, E, R>
where
  A: From<Response> + 'static,
  E: From<Error> + 'static,
  R: Needs<ReqwestClient> + CapBindR + 'static,
{
  effect!(|_r: &mut R| {
    let x = ~send::<A, E, R, _>(move |c| c.get(url));
    x
  })
}

/// Shorthand for [`send`]`(|c| c.post(url))`.
#[inline]
pub fn post<A, E, R>(url: String) -> Effect<A, E, R>
where
  A: From<Response> + 'static,
  E: From<Error> + 'static,
  R: Needs<ReqwestClient> + CapBindR + 'static,
{
  effect!(|_r: &mut R| {
    let x = ~send::<A, E, R, _>(move |c| c.post(url));
    x
  })
}

/// Shorthand for [`send`]`(|c| c.put(url))`.
#[inline]
pub fn put<A, E, R>(url: String) -> Effect<A, E, R>
where
  A: From<Response> + 'static,
  E: From<Error> + 'static,
  R: Needs<ReqwestClient> + CapBindR + 'static,
{
  effect!(|_r: &mut R| {
    let x = ~send::<A, E, R, _>(move |c| c.put(url));
    x
  })
}

/// Shorthand for [`send`]`(|c| c.delete(url))`.
#[inline]
pub fn delete<A, E, R>(url: String) -> Effect<A, E, R>
where
  A: From<Response> + 'static,
  E: From<Error> + 'static,
  R: Needs<ReqwestClient> + CapBindR + 'static,
{
  effect!(|_r: &mut R| {
    let x = ~send::<A, E, R, _>(move |c| c.delete(url));
    x
  })
}

/// Shorthand for [`send`]`(|c| c.head(url))`.
#[inline]
pub fn head<A, E, R>(url: String) -> Effect<A, E, R>
where
  A: From<Response> + 'static,
  E: From<Error> + 'static,
  R: Needs<ReqwestClient> + CapBindR + 'static,
{
  effect!(|_r: &mut R| {
    let x = ~send::<A, E, R, _>(move |c| c.head(url));
    x
  })
}

/// Shorthand for [`send`]`(|c| c.patch(url))`.
#[inline]
pub fn patch<A, E, R>(url: String) -> Effect<A, E, R>
where
  A: From<Response> + 'static,
  E: From<Error> + 'static,
  R: Needs<ReqwestClient> + CapBindR + 'static,
{
  effect!(|_r: &mut R| {
    let x = ~send::<A, E, R, _>(move |c| c.patch(url));
    x
  })
}

#[cfg(test)]
mod tests {
  use super::*;
  use id_effect::schema;
  use id_effect::{Scope, build_env, provide, run_async, run_blocking, succeed};
  use serde::{Deserialize, Serialize};
  use std::sync::atomic::{AtomicUsize, Ordering};
  use std::time::Duration;
  use wiremock::matchers::{method, path};
  use wiremock::{Mock, MockServer, ResponseTemplate};

  #[tokio::test]
  async fn text_roundtrip() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
      .and(path("/ping"))
      .respond_with(ResponseTemplate::new(200).set_body_string("pong"))
      .mount(&server)
      .await;

    let url = format!("{}/ping", server.uri());
    let env = build_env([provide_reqwest_client(Client::new())]).expect("env");
    let body = run_async(text::<String, Error, _, _>(move |c| c.get(url)), env)
      .await
      .unwrap();
    assert_eq!(body, "pong");
  }

  #[tokio::test]
  async fn json_roundtrip() {
    #[derive(Debug, Deserialize, Serialize, PartialEq)]
    struct Msg {
      n: i32,
    }

    let server = MockServer::start().await;
    Mock::given(method("GET"))
      .and(path("/data"))
      .respond_with(ResponseTemplate::new(200).set_body_json(&Msg { n: 7 }))
      .mount(&server)
      .await;

    let url = format!("{}/data", server.uri());
    let env = build_env([provide_reqwest_client(Client::new())]).expect("env");
    let msg = run_async(json::<Msg, Error, _, _, Msg>(move |c| c.get(url)), env)
      .await
      .unwrap();
    assert_eq!(msg, Msg { n: 7 });
  }

  #[tokio::test]
  async fn provider_builds_client() {
    let env = build_env([provide!(ReqwestClientLive)]).expect("env");
    let client = env.get::<Cap<ReqwestClient>>();
    assert!(client.get("https://example.com").build().is_ok());
  }

  #[tokio::test]
  async fn reqwest_pool_reuses_connections() {
    let factory_calls = Arc::new(AtomicUsize::new(0));
    let fc = factory_calls.clone();
    let pool = run_blocking(
      Pool::make_with_ttl(1, Duration::from_secs(120), move || {
        fc.fetch_add(1, Ordering::SeqCst);
        succeed::<PooledClient, Never, ()>(PooledClient(Arc::new(Client::new())))
      }),
      (),
    )
    .expect("pool");

    let s1 = Scope::make();
    let c1 = run_async(pool.clone().get(), s1.clone())
      .await
      .expect("get1");
    let p1 = c1.allocation_ptr();
    s1.close();

    let s2 = Scope::make();
    let c2 = run_async(pool.get(), s2.clone()).await.expect("get2");
    assert_eq!(p1, c2.allocation_ptr());
    s2.close();

    assert_eq!(factory_calls.load(Ordering::SeqCst), 1);
  }

  #[tokio::test]
  async fn reqwest_response_schema_decode_error_has_field_path() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
      .and(path("/bad"))
      .respond_with(ResponseTemplate::new(200).set_body_string(r#"{"name":"x","age":"oops"}"#))
      .mount(&server)
      .await;

    let url = format!("{}/bad", server.uri());
    let sch = Arc::new(schema::struct_(
      "name",
      schema::string::<()>(),
      "age",
      schema::i64::<()>(),
    ));
    let env = build_env([provide_reqwest_client(Client::new())]).expect("env");
    let err = run_async(json_schema(sch, move |c| c.get(url)), env)
      .await
      .expect_err("schema");
    match err {
      JsonSchemaError::Schema(p) => {
        assert!(p.path.contains("age"), "path={:?}", p.path);
      }
      e => panic!("unexpected {e:?}"),
    }
  }

  // ── Additional HTTP method tests ──────────────────────────────────────────

  #[tokio::test]
  async fn bytes_roundtrip() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
      .and(path("/data"))
      .respond_with(ResponseTemplate::new(200).set_body_bytes(b"hello"))
      .mount(&server)
      .await;

    let url = format!("{}/data", server.uri());
    let env = build_env([provide_reqwest_client(Client::new())]).expect("env");
    let body = run_async(bytes::<bytes::Bytes, Error, _, _>(move |c| c.get(url)), env)
      .await
      .unwrap();
    assert_eq!(body.as_ref(), b"hello");
  }

  #[tokio::test]
  async fn get_helper_fetches_text() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
      .and(path("/hello"))
      .respond_with(ResponseTemplate::new(200).set_body_string("world"))
      .mount(&server)
      .await;

    let url = format!("{}/hello", server.uri());
    let env = build_env([provide_reqwest_client(Client::new())]).expect("env");
    let body = run_async(
      get::<Response, Error, _>(url).flat_map(|resp: Response| {
        id_effect::from_async(move |_r: &mut _| async move { resp.text().await })
      }),
      env,
    )
    .await
    .unwrap();
    assert_eq!(body, "world");
  }

  #[tokio::test]
  async fn post_helper_sends_body() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
      .and(path("/echo"))
      .respond_with(ResponseTemplate::new(200).set_body_string("ok"))
      .mount(&server)
      .await;

    let url = format!("{}/echo", server.uri());
    let env = build_env([provide_reqwest_client(Client::new())]).expect("env");
    let body = run_async(
      post::<Response, Error, _>(url).flat_map(|resp: Response| {
        id_effect::from_async(move |_r: &mut _| async move { resp.text().await })
      }),
      env,
    )
    .await
    .unwrap();
    assert_eq!(body, "ok");
  }

  #[tokio::test]
  async fn put_helper_sends_request() {
    let server = MockServer::start().await;
    Mock::given(method("PUT"))
      .and(path("/item"))
      .respond_with(ResponseTemplate::new(200).set_body_string("updated"))
      .mount(&server)
      .await;

    let url = format!("{}/item", server.uri());
    let env = build_env([provide_reqwest_client(Client::new())]).expect("env");
    let body = run_async(
      put::<Response, Error, _>(url).flat_map(|resp: Response| {
        id_effect::from_async(move |_r: &mut _| async move { resp.text().await })
      }),
      env,
    )
    .await
    .unwrap();
    assert_eq!(body, "updated");
  }

  #[tokio::test]
  async fn delete_helper_sends_request() {
    let server = MockServer::start().await;
    Mock::given(method("DELETE"))
      .and(path("/item"))
      .respond_with(ResponseTemplate::new(204))
      .mount(&server)
      .await;

    let url = format!("{}/item", server.uri());
    let env = build_env([provide_reqwest_client(Client::new())]).expect("env");
    let resp = run_async(delete::<Response, Error, _>(url), env)
      .await
      .unwrap();
    assert_eq!(resp.status().as_u16(), 204);
  }

  #[tokio::test]
  async fn patch_helper_sends_request() {
    let server = MockServer::start().await;
    Mock::given(method("PATCH"))
      .and(path("/item"))
      .respond_with(ResponseTemplate::new(200).set_body_string("patched"))
      .mount(&server)
      .await;

    let url = format!("{}/item", server.uri());
    let env = build_env([provide_reqwest_client(Client::new())]).expect("env");
    let body = run_async(
      patch::<Response, Error, _>(url).flat_map(|resp: Response| {
        id_effect::from_async(move |_r: &mut _| async move { resp.text().await })
      }),
      env,
    )
    .await
    .unwrap();
    assert_eq!(body, "patched");
  }

  #[tokio::test]
  async fn head_helper_sends_request() {
    let server = MockServer::start().await;
    Mock::given(method("HEAD"))
      .and(path("/status"))
      .respond_with(ResponseTemplate::new(200))
      .mount(&server)
      .await;

    let url = format!("{}/status", server.uri());
    let env = build_env([provide_reqwest_client(Client::new())]).expect("env");
    let resp = run_async(head::<Response, Error, _>(url), env)
      .await
      .unwrap();
    assert_eq!(resp.status().as_u16(), 200);
  }

  #[tokio::test]
  async fn provide_reqwest_client_registers_client() {
    let env = build_env([provide_reqwest_client(Client::new())]).expect("env");
    let client = env.get::<Cap<ReqwestClient>>();
    assert!(client.get("https://example.com").build().is_ok());
  }

  #[tokio::test]
  async fn provide_reqwest_client_with_builder() {
    let builder = Client::builder().timeout(Duration::from_secs(30));
    let client = builder.build().unwrap();
    let env = build_env([provide_reqwest_client(client)]).expect("env");
    assert!(
      env
        .get::<Cap<ReqwestClient>>()
        .get("https://example.com")
        .build()
        .is_ok()
    );
  }

  #[tokio::test]
  async fn provide_reqwest_pool_builds_pool() {
    let env = build_env([provide_reqwest_pool(2, Duration::from_secs(60))]).expect("env");
    let pool = env.get::<Cap<ReqwestPool>>().clone();
    let s = Scope::make();
    let client = run_async(pool.get(), s.clone()).await.expect("get");
    let _ = client.allocation_ptr();
    s.close();
  }

  // ── JsonSchemaError display / error traits ────────────────────────────────

  #[test]
  fn json_schema_error_http_display() {
    // Create a fake HTTP error by making a bad URL request
    let rt = tokio::runtime::Runtime::new().unwrap();
    let err = rt.block_on(async {
      Client::new()
        .get("not-a-url")
        .send()
        .await
        .map_err(JsonSchemaError::Http)
        .unwrap_err()
    });
    let _ = format!("{err:?}");
  }

  #[test]
  fn json_schema_error_json_debug() {
    let e = JsonSchemaError::Json("bad json".to_string());
    let s = format!("{e:?}");
    assert!(s.contains("bad json"), "debug: {s}");
  }

  #[test]
  fn json_schema_error_schema_debug() {
    let e = JsonSchemaError::Schema(id_effect::schema::ParseError::new("field", "invalid"));
    let _ = format!("{e:?}");
  }

  #[test]
  fn pooled_client_partial_eq_same_arc() {
    let client = Client::new();
    let arc = Arc::new(client);
    let a = PooledClient(arc.clone());
    let b = PooledClient(arc.clone());
    assert_eq!(a, b);
  }

  #[test]
  fn pooled_client_partial_eq_different_arc() {
    let a = PooledClient(Arc::new(Client::new()));
    let b = PooledClient(Arc::new(Client::new()));
    assert_ne!(a, b);
  }

  #[tokio::test]
  async fn send_pooled_fetches_response() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
      .and(path("/pooled"))
      .respond_with(ResponseTemplate::new(200).set_body_string("pooled-ok"))
      .mount(&server)
      .await;

    let url = format!("{}/pooled", server.uri());
    let pool = run_blocking(
      Pool::make_with_ttl(1, Duration::from_secs(60), || {
        succeed::<PooledClient, Never, ()>(PooledClient(Arc::new(Client::new())))
      }),
      (),
    )
    .expect("pool");
    let mut env = build_env([]).expect("env");
    env.insert::<Cap<ReqwestPool>>(pool);
    let resp = run_async(
      send_pooled::<Response, Error, _, _>(move |c| c.get(url)),
      env,
    )
    .await
    .unwrap();
    assert_eq!(resp.status().as_u16(), 200);
  }

  #[tokio::test]
  async fn json_schema_error_bad_json_returns_json_variant() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
      .and(path("/badjson"))
      .respond_with(ResponseTemplate::new(200).set_body_string("not json at all"))
      .mount(&server)
      .await;

    let url = format!("{}/badjson", server.uri());
    let sch = Arc::new(schema::i64::<()>());
    let env = build_env([provide_reqwest_client(Client::new())]).expect("env");
    let err = run_async(json_schema(sch, move |c| c.get(url)), env)
      .await
      .expect_err("should fail");
    assert!(matches!(err, JsonSchemaError::Json(_)));
  }
}