shrike 0.1.1

AT Protocol library for Rust
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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
use serde::Deserialize;
use serde::{Serialize, de::DeserializeOwned};
use tokio::sync::RwLock;

use crate::xrpc::auth::AuthInfo;
use crate::xrpc::error::Error;
use crate::xrpc::retry::RetryPolicy;

const MAX_RESPONSE_BODY: u64 = 5 << 20; // 5 MB for JSON
const MAX_RAW_RESPONSE_BODY: u64 = 512 << 20; // 512 MB for binary

#[derive(Deserialize)]
struct XrpcErrorBody {
    error: String,
    #[serde(default)]
    message: String,
}

/// XRPC HTTP client for AT Protocol PDS/relay communication.
///
/// Handles authentication, retries with exponential backoff, rate limiting,
/// and response size limits. Use `Client::new` for unauthenticated requests,
/// `Client::with_auth` for authenticated requests, or `Client::create_session`
/// to log in.
///
/// ```no_run
/// use shrike::xrpc::Client;
///
/// # async fn example() -> Result<(), shrike::xrpc::Error> {
/// let client = Client::new("https://bsky.social");
/// let auth = client.create_session("alice.bsky.social", "app-password").await?;
/// // client is now authenticated; subsequent calls include the bearer token
/// # Ok(())
/// # }
/// ```
pub struct Client {
    http: reqwest::Client,
    host: String,
    auth: RwLock<Option<AuthInfo>>,
    retry: RetryPolicy,
}

impl Client {
    /// Create an unauthenticated client targeting the given host
    /// (e.g., `"https://bsky.social"`).
    pub fn new(host: &str) -> Self {
        Client {
            http: reqwest::Client::new(),
            host: host.to_owned(),
            auth: RwLock::new(None),
            retry: RetryPolicy::default(),
        }
    }

    /// Create a client with pre-existing authentication tokens. Use this when
    /// you already have an `AuthInfo` from a previous session.
    pub fn with_auth(host: &str, auth: AuthInfo) -> Self {
        Client {
            http: reqwest::Client::new(),
            host: host.to_owned(),
            auth: RwLock::new(Some(auth)),
            retry: RetryPolicy::default(),
        }
    }

    /// Create an unauthenticated client with a custom retry policy.
    pub fn with_retry(host: &str, retry: RetryPolicy) -> Self {
        Client {
            http: reqwest::Client::new(),
            host: host.to_owned(),
            auth: RwLock::new(None),
            retry,
        }
    }

    fn xrpc_url(&self, nsid: &str) -> String {
        format!("{}/xrpc/{}", self.host, nsid)
    }

    async fn bearer(&self) -> Option<String> {
        let guard = self.auth.read().await;
        guard.as_ref().map(|a| a.access_jwt.clone())
    }

    async fn refresh_bearer(&self) -> Option<String> {
        let guard = self.auth.read().await;
        guard.as_ref().map(|a| a.refresh_jwt.clone())
    }

    fn apply_auth(
        &self,
        rb: reqwest::RequestBuilder,
        token: Option<&str>,
    ) -> reqwest::RequestBuilder {
        if let Some(t) = token {
            rb.header("Authorization", format!("Bearer {t}"))
        } else {
            rb
        }
    }

    async fn check_response_size(resp: &reqwest::Response, limit: u64) -> Result<(), Error> {
        if let Some(len) = resp.content_length()
            && len > limit
        {
            return Err(Error::ResponseTooLarge { size: len, limit });
        }
        Ok(())
    }

    fn parse_retry_after(resp: &reqwest::Response) -> Option<std::time::Duration> {
        resp.headers()
            .get("retry-after")
            .and_then(|v| v.to_str().ok())
            .and_then(|s| s.parse::<u64>().ok())
            .map(std::time::Duration::from_secs)
    }

    async fn parse_error_response(resp: reqwest::Response) -> Error {
        let status = resp.status().as_u16();

        if status == 429 {
            let retry_after = Self::parse_retry_after(&resp);
            return Error::RateLimited { retry_after };
        }

        match resp.text().await {
            Ok(body) => {
                if let Ok(err_body) = serde_json::from_str::<XrpcErrorBody>(&body) {
                    Error::Xrpc {
                        status,
                        error: err_body.error,
                        message: err_body.message,
                    }
                } else {
                    Error::Xrpc {
                        status,
                        error: String::from("Unknown"),
                        message: body,
                    }
                }
            }
            Err(e) => Error::Network(e),
        }
    }

    fn is_retryable(status: u16) -> bool {
        status >= 500 || status == 429
    }

    /// Execute an XRPC query (GET /xrpc/{nsid}?{params}).
    ///
    /// Serializes `params` as query parameters and deserializes the JSON response
    /// into `O`. Retries on 5xx and 429 responses according to the retry policy.
    /// Response bodies are limited to 5 MB.
    pub async fn query<P: Serialize, O: DeserializeOwned>(
        &self,
        nsid: &str,
        params: &P,
    ) -> Result<O, Error> {
        let url = self.xrpc_url(nsid);
        let bearer = self.bearer().await;
        let max_retries = self.retry.max_retries;

        let mut last_err: Option<Error> = None;
        for attempt in 0..=max_retries {
            if attempt > 0 {
                let delay = self.retry.delay_for_attempt(attempt - 1);
                tokio::time::sleep(delay).await;
            }

            let rb = self.http.get(&url).query(params);
            let rb = self.apply_auth(rb, bearer.as_deref());

            let resp = match rb.send().await {
                Ok(r) => r,
                Err(e) => {
                    last_err = Some(Error::Network(e));
                    continue;
                }
            };

            let status = resp.status();

            if status.is_success() {
                Self::check_response_size(&resp, MAX_RESPONSE_BODY).await?;
                return resp.json::<O>().await.map_err(Error::Network);
            }

            let status_u16 = status.as_u16();
            if Self::is_retryable(status_u16) && attempt < max_retries {
                let retry_after = Self::parse_retry_after(&resp);
                last_err = Some(Error::RateLimited { retry_after });
                continue;
            }

            return Err(Self::parse_error_response(resp).await);
        }

        Err(last_err.unwrap_or_else(|| Error::Xrpc {
            status: 0,
            error: String::from("Unknown"),
            message: String::from("max retries exceeded"),
        }))
    }

    /// Execute an XRPC procedure (POST /xrpc/{nsid} with JSON body).
    ///
    /// Serializes `input` as the JSON request body and deserializes the JSON
    /// response into `O`. Retries on 5xx and 429 responses.
    pub async fn procedure<I: Serialize, O: DeserializeOwned>(
        &self,
        nsid: &str,
        input: &I,
    ) -> Result<O, Error> {
        let url = self.xrpc_url(nsid);
        let bearer = self.bearer().await;
        let body = serde_json::to_vec(input)?;
        let max_retries = self.retry.max_retries;

        let mut last_err: Option<Error> = None;
        for attempt in 0..=max_retries {
            if attempt > 0 {
                let delay = self.retry.delay_for_attempt(attempt - 1);
                tokio::time::sleep(delay).await;
            }

            let rb = self
                .http
                .post(&url)
                .header("Content-Type", "application/json")
                .body(body.clone());
            let rb = self.apply_auth(rb, bearer.as_deref());

            let resp = match rb.send().await {
                Ok(r) => r,
                Err(e) => {
                    last_err = Some(Error::Network(e));
                    continue;
                }
            };

            let status = resp.status();

            if status.is_success() {
                Self::check_response_size(&resp, MAX_RESPONSE_BODY).await?;
                return resp.json::<O>().await.map_err(Error::Network);
            }

            let status_u16 = status.as_u16();
            if Self::is_retryable(status_u16) && attempt < max_retries {
                let retry_after = Self::parse_retry_after(&resp);
                last_err = Some(Error::RateLimited { retry_after });
                continue;
            }

            return Err(Self::parse_error_response(resp).await);
        }

        Err(last_err.unwrap_or_else(|| Error::Xrpc {
            status: 0,
            error: String::from("Unknown"),
            message: String::from("max retries exceeded"),
        }))
    }

    /// Execute an XRPC query returning raw binary bytes (GET).
    ///
    /// Same as `query` but returns the response body as `Vec<u8>` instead of
    /// deserializing JSON. Response bodies are limited to 512 MB. Useful for
    /// endpoints like `com.atproto.sync.getRepo` that return CAR files.
    pub async fn query_raw(&self, nsid: &str, params: &impl Serialize) -> Result<Vec<u8>, Error> {
        let url = self.xrpc_url(nsid);
        let bearer = self.bearer().await;
        let max_retries = self.retry.max_retries;

        let mut last_err: Option<Error> = None;
        for attempt in 0..=max_retries {
            if attempt > 0 {
                let delay = self.retry.delay_for_attempt(attempt - 1);
                tokio::time::sleep(delay).await;
            }

            let rb = self.http.get(&url).query(params);
            let rb = self.apply_auth(rb, bearer.as_deref());

            let resp = match rb.send().await {
                Ok(r) => r,
                Err(e) => {
                    last_err = Some(Error::Network(e));
                    continue;
                }
            };

            let status = resp.status();

            if status.is_success() {
                if let Some(len) = resp.content_length()
                    && len > MAX_RAW_RESPONSE_BODY
                {
                    return Err(Error::ResponseTooLarge {
                        size: len,
                        limit: MAX_RAW_RESPONSE_BODY,
                    });
                }
                return resp
                    .bytes()
                    .await
                    .map(|b| b.to_vec())
                    .map_err(Error::Network);
            }

            let status_u16 = status.as_u16();
            if Self::is_retryable(status_u16) && attempt < max_retries {
                let retry_after = Self::parse_retry_after(&resp);
                last_err = Some(Error::RateLimited { retry_after });
                continue;
            }

            return Err(Self::parse_error_response(resp).await);
        }

        Err(last_err.unwrap_or_else(|| Error::Xrpc {
            status: 0,
            error: String::from("Unknown"),
            message: String::from("max retries exceeded"),
        }))
    }

    /// Execute an XRPC procedure with a raw binary body (POST).
    ///
    /// Sends `body` with the given `content_type` and returns the JSON response
    /// as `serde_json::Value`. Useful for uploading blobs.
    pub async fn procedure_raw(
        &self,
        nsid: &str,
        body: Vec<u8>,
        content_type: &str,
    ) -> Result<serde_json::Value, Error> {
        let url = self.xrpc_url(nsid);
        let bearer = self.bearer().await;
        let max_retries = self.retry.max_retries;

        let mut last_err: Option<Error> = None;
        for attempt in 0..=max_retries {
            if attempt > 0 {
                let delay = self.retry.delay_for_attempt(attempt - 1);
                tokio::time::sleep(delay).await;
            }

            let rb = self
                .http
                .post(&url)
                .header("Content-Type", content_type)
                .body(body.clone());
            let rb = self.apply_auth(rb, bearer.as_deref());

            let resp = match rb.send().await {
                Ok(r) => r,
                Err(e) => {
                    last_err = Some(Error::Network(e));
                    continue;
                }
            };

            let status = resp.status();

            if status.is_success() {
                Self::check_response_size(&resp, MAX_RESPONSE_BODY).await?;
                return resp
                    .json::<serde_json::Value>()
                    .await
                    .map_err(Error::Network);
            }

            let status_u16 = status.as_u16();
            if Self::is_retryable(status_u16) && attempt < max_retries {
                let retry_after = Self::parse_retry_after(&resp);
                last_err = Some(Error::RateLimited { retry_after });
                continue;
            }

            return Err(Self::parse_error_response(resp).await);
        }

        Err(last_err.unwrap_or_else(|| Error::Xrpc {
            status: 0,
            error: String::from("Unknown"),
            message: String::from("max retries exceeded"),
        }))
    }

    /// Create a session by logging in with a handle/DID and password.
    ///
    /// Calls `com.atproto.server.createSession` and stores the returned tokens
    /// so that subsequent requests on this client are authenticated.
    pub async fn create_session(
        &self,
        identifier: &str,
        password: &str,
    ) -> Result<AuthInfo, Error> {
        let url = self.xrpc_url("com.atproto.server.createSession");
        let body = serde_json::json!({
            "identifier": identifier,
            "password": password,
        });
        let body_bytes = serde_json::to_vec(&body)?;

        let resp = self
            .http
            .post(&url)
            .header("Content-Type", "application/json")
            .body(body_bytes)
            .send()
            .await?;

        let status = resp.status();
        if status.is_success() {
            let auth: AuthInfo = resp.json().await.map_err(Error::Network)?;
            let mut guard = self.auth.write().await;
            *guard = Some(auth.clone());
            return Ok(auth);
        }

        Err(Self::parse_error_response(resp).await)
    }

    /// Refresh the current session using the stored refresh token.
    ///
    /// Calls `com.atproto.server.refreshSession` and updates the stored tokens.
    pub async fn refresh_session(&self) -> Result<AuthInfo, Error> {
        let url = self.xrpc_url("com.atproto.server.refreshSession");
        let refresh_jwt = self.refresh_bearer().await;

        let rb = self.http.post(&url);
        let rb = self.apply_auth(rb, refresh_jwt.as_deref());

        let resp = rb.send().await?;

        let status = resp.status();
        if status.is_success() {
            let auth: AuthInfo = resp.json().await.map_err(Error::Network)?;
            let mut guard = self.auth.write().await;
            *guard = Some(auth.clone());
            return Ok(auth);
        }

        Err(Self::parse_error_response(resp).await)
    }

    /// Delete the current session (logout).
    ///
    /// Calls `com.atproto.server.deleteSession` and clears the stored tokens.
    pub async fn delete_session(&self) -> Result<(), Error> {
        let url = self.xrpc_url("com.atproto.server.deleteSession");
        let refresh_jwt = self.refresh_bearer().await;

        let rb = self.http.post(&url);
        let rb = self.apply_auth(rb, refresh_jwt.as_deref());

        let resp = rb.send().await?;

        let status = resp.status();
        if status.is_success() {
            let mut guard = self.auth.write().await;
            *guard = None;
            return Ok(());
        }

        Err(Self::parse_error_response(resp).await)
    }
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::unreachable
)]
mod tests {
    use super::*;
    use axum::{
        Json, Router,
        extract::Query,
        http::StatusCode,
        routing::{get, post},
    };
    use serde::Deserialize;
    use serde_json::json;
    use std::collections::HashMap;
    use tokio::net::TcpListener;

    async fn start_mock() -> String {
        let app =
            Router::new()
                .route(
                    "/xrpc/com.example.ping",
                    get(|| async { Json(json!({"message": "pong"})) }),
                )
                .route(
                    "/xrpc/com.example.echo",
                    post(|Json(body): Json<serde_json::Value>| async move {
                        Json(json!({"echoed": body}))
                    }),
                )
                .route(
                    "/xrpc/com.example.fail",
                    get(|| async {
                        (
                            StatusCode::BAD_REQUEST,
                            Json(json!({"error": "InvalidRequest", "message": "bad"})),
                        )
                    }),
                )
                .route(
                    "/xrpc/com.example.ratelimit",
                    get(|| async {
                        (
                            StatusCode::TOO_MANY_REQUESTS,
                            [("retry-after", "5")],
                            Json(json!({"error": "RateLimited", "message": "slow down"})),
                        )
                    }),
                )
                .route(
                    "/xrpc/com.example.servererror",
                    get(|| async {
                        (
                            StatusCode::INTERNAL_SERVER_ERROR,
                            Json(json!({"error": "InternalError", "message": "boom"})),
                        )
                    }),
                )
                .route(
                    "/xrpc/com.example.authcheck",
                    get(|headers: axum::http::HeaderMap| async move {
                        let auth = headers
                            .get("authorization")
                            .and_then(|v| v.to_str().ok())
                            .unwrap_or("")
                            .to_owned();
                        Json(json!({"authorization": auth}))
                    }),
                )
                .route(
                    "/xrpc/com.example.largeresponse",
                    get(|| async {
                        // Return 1 MB of JSON data
                        let data: Vec<String> =
                            (0..10_000).map(|i| format!("item-{i:06}")).collect();
                        Json(json!({"items": data}))
                    }),
                )
                .route(
                    "/xrpc/com.example.queryparams",
                    get(|Query(params): Query<HashMap<String, String>>| async move {
                        Json(json!({"received": params}))
                    }),
                )
                .route(
                    "/xrpc/com.atproto.server.createSession",
                    post(|| async {
                        Json(json!({
                            "accessJwt": "test-access",
                            "refreshJwt": "test-refresh",
                            "handle": "alice.test",
                            "did": "did:plc:test123456789abcdefghij"
                        }))
                    }),
                );

        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            axum::serve(listener, app).await.unwrap();
        });
        format!("http://{addr}")
    }

    #[tokio::test]
    async fn query_returns_json() {
        let url = start_mock().await;
        let client = Client::new(&url);
        let result: serde_json::Value = client.query("com.example.ping", &json!({})).await.unwrap();
        assert_eq!(result["message"], "pong");
    }

    #[tokio::test]
    async fn procedure_posts_json() {
        let url = start_mock().await;
        let client = Client::new(&url);
        let result: serde_json::Value = client
            .procedure("com.example.echo", &json!({"text": "hi"}))
            .await
            .unwrap();
        assert_eq!(result["echoed"]["text"], "hi");
    }

    #[tokio::test]
    async fn xrpc_error_parsed() {
        let url = start_mock().await;
        let client = Client::new(&url);
        let err = client
            .query::<_, serde_json::Value>("com.example.fail", &json!({}))
            .await
            .unwrap_err();
        match err {
            Error::Xrpc { status, error, .. } => {
                assert_eq!(status, 400);
                assert_eq!(error, "InvalidRequest");
            }
            other => panic!("expected Xrpc error, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn create_session() {
        let url = start_mock().await;
        let client = Client::new(&url);
        let auth = client
            .create_session("alice.test", "password")
            .await
            .unwrap();
        assert_eq!(auth.access_jwt, "test-access");
        assert_eq!(auth.did.as_str(), "did:plc:test123456789abcdefghij");
    }

    // --- RetryPolicy tests ---

    #[test]
    fn retry_policy_delay_for_attempt_zero() {
        let policy = RetryPolicy::default();
        assert_eq!(
            policy.delay_for_attempt(0),
            std::time::Duration::from_millis(500)
        );
    }

    #[test]
    fn retry_policy_delay_doubles_each_attempt() {
        let policy = RetryPolicy::default();
        assert_eq!(
            policy.delay_for_attempt(0),
            std::time::Duration::from_millis(500)
        );
        assert_eq!(
            policy.delay_for_attempt(1),
            std::time::Duration::from_millis(1000)
        );
        assert_eq!(
            policy.delay_for_attempt(2),
            std::time::Duration::from_millis(2000)
        );
    }

    #[test]
    fn retry_policy_max_delay_cap() {
        let policy = RetryPolicy {
            max_retries: 10,
            base_delay: std::time::Duration::from_millis(500),
            max_delay: std::time::Duration::from_secs(30),
        };
        // attempt 10 would be 500ms * 2^10 = 512_000ms without cap
        let delay = policy.delay_for_attempt(10);
        assert_eq!(delay, std::time::Duration::from_secs(30));
    }

    #[test]
    fn retry_policy_default_values() {
        let policy = RetryPolicy::default();
        assert_eq!(policy.max_retries, 3);
        assert_eq!(policy.base_delay, std::time::Duration::from_millis(500));
        assert_eq!(policy.max_delay, std::time::Duration::from_secs(30));
    }

    // --- Client construction tests ---

    #[test]
    fn client_new_has_no_auth() {
        // Client::new should construct successfully with no auth.
        let client = Client::new("https://bsky.social");
        let _ = client;
    }

    #[tokio::test]
    async fn client_with_auth_stores_token() {
        use crate::syntax::{Did, Handle};
        use crate::xrpc::auth::AuthInfo;

        let auth = AuthInfo {
            access_jwt: "my-access-token".to_owned(),
            refresh_jwt: "my-refresh-token".to_owned(),
            handle: Handle::try_from("alice.test").unwrap(),
            did: Did::try_from("did:plc:test123456789abcdefghij").unwrap(),
        };
        let client = Client::with_auth("https://bsky.social", auth);
        // bearer() reads the stored auth
        let bearer = client.bearer().await;
        assert_eq!(bearer.as_deref(), Some("my-access-token"));
        let refresh = client.refresh_bearer().await;
        assert_eq!(refresh.as_deref(), Some("my-refresh-token"));
    }

    // --- Error handling tests ---

    #[tokio::test]
    async fn rate_limit_429_returns_rate_limited_error() {
        let url = start_mock().await;
        // Disable retries so the 429 is returned immediately.
        let client = Client::with_retry(
            &url,
            RetryPolicy {
                max_retries: 0,
                base_delay: std::time::Duration::from_millis(1),
                max_delay: std::time::Duration::from_millis(1),
            },
        );
        let err = client
            .query::<_, serde_json::Value>("com.example.ratelimit", &json!({}))
            .await
            .unwrap_err();
        match err {
            Error::RateLimited { retry_after } => {
                assert_eq!(retry_after, Some(std::time::Duration::from_secs(5)));
            }
            other => panic!("expected RateLimited, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn server_error_500_returns_xrpc_error() {
        let url = start_mock().await;
        let client = Client::with_retry(
            &url,
            RetryPolicy {
                max_retries: 0,
                base_delay: std::time::Duration::from_millis(1),
                max_delay: std::time::Duration::from_millis(1),
            },
        );
        let err = client
            .query::<_, serde_json::Value>("com.example.servererror", &json!({}))
            .await
            .unwrap_err();
        match err {
            Error::Xrpc { status, error, .. } => {
                assert_eq!(status, 500);
                assert_eq!(error, "InternalError");
            }
            other => panic!("expected Xrpc error, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn network_timeout_returns_network_error() {
        // Connect to a port that is not listening — reqwest will get a connection refused.
        // Use zero retries to avoid 3.5s of exponential backoff in tests.
        let client = Client::with_retry(
            "http://127.0.0.1:1",
            RetryPolicy {
                max_retries: 0,
                ..RetryPolicy::default()
            },
        );
        let err = client
            .query::<_, serde_json::Value>("com.example.ping", &json!({}))
            .await
            .unwrap_err();
        assert!(
            matches!(err, Error::Network(_)),
            "expected Network error, got {err:?}"
        );
    }

    // --- Auth header tests ---

    #[tokio::test]
    async fn bearer_token_sent_when_auth_set() {
        use crate::syntax::{Did, Handle};
        use crate::xrpc::auth::AuthInfo;

        let url = start_mock().await;
        let auth = AuthInfo {
            access_jwt: "super-secret-token".to_owned(),
            refresh_jwt: "refresh".to_owned(),
            handle: Handle::try_from("alice.test").unwrap(),
            did: Did::try_from("did:plc:test123456789abcdefghij").unwrap(),
        };
        let client = Client::with_auth(&url, auth);
        let result: serde_json::Value = client
            .query("com.example.authcheck", &json!({}))
            .await
            .unwrap();
        assert_eq!(result["authorization"], "Bearer super-secret-token");
    }

    #[tokio::test]
    async fn no_auth_header_when_no_auth_set() {
        let url = start_mock().await;
        let client = Client::new(&url);
        let result: serde_json::Value = client
            .query("com.example.authcheck", &json!({}))
            .await
            .unwrap();
        // No Authorization header should be sent, so the server sees an empty string.
        assert_eq!(result["authorization"], "");
    }

    // --- Response size tests ---

    #[tokio::test]
    async fn query_raw_large_response_succeeds() {
        let url = start_mock().await;
        let client = Client::new(&url);
        // query_raw returns bytes; 1 MB of JSON should succeed (well under 512 MB limit).
        let bytes = client
            .query_raw("com.example.largeresponse", &json!({}))
            .await
            .unwrap();
        assert!(!bytes.is_empty());
        // Must be valid JSON containing items.
        let parsed: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert!(parsed["items"].is_array());
        assert_eq!(parsed["items"].as_array().unwrap().len(), 10_000);
    }

    #[test]
    fn response_too_large_error_carries_size_and_limit() {
        let err = Error::ResponseTooLarge {
            size: 600,
            limit: 512,
        };
        let msg = err.to_string();
        assert!(msg.contains("600"));
        assert!(msg.contains("512"));
    }

    // --- Query params test ---

    #[derive(serde::Serialize, Deserialize)]
    struct MultiParams {
        alpha: String,
        beta: u32,
    }

    #[tokio::test]
    async fn query_with_multiple_params() {
        let url = start_mock().await;
        let client = Client::new(&url);
        let params = MultiParams {
            alpha: "hello".to_owned(),
            beta: 42,
        };
        let result: serde_json::Value = client
            .query("com.example.queryparams", &params)
            .await
            .unwrap();
        assert_eq!(result["received"]["alpha"], "hello");
        assert_eq!(result["received"]["beta"], "42");
    }
}