reqkey 0.1.0

Official Rust SDK for ReqKey API key validation, credit metering, and analytics
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
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
use std::{collections::BTreeMap, env, time::Duration};

use http::{header, HeaderMap, HeaderValue};
use serde::Serialize;
use serde_json::{Map, Value};

use crate::{
    error::{Error, Operation, Result},
    models::{VerificationReason, VerificationResult},
    VERSION,
};

/// Default ReqKey API origin.
pub const DEFAULT_BASE_URL: &str = "https://api.reqkey.com";
/// Default timeout for each ReqKey operation.
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(2);
/// Maximum number of Unicode characters sent for request or response bodies.
pub const MAX_BODY_CHARACTERS: usize = 1_000;

fn user_agent() -> String {
    format!("reqkey-rust/{VERSION}")
}

#[derive(Clone, Debug)]
struct ClientConfig {
    project_key: String,
    base_url: String,
    timeout: Duration,
}

impl ClientConfig {
    fn from_builder(
        project_key: Option<String>,
        root_key: Option<String>,
        base_url: &str,
        timeout: Duration,
    ) -> Result<Self> {
        if project_key.is_some() && root_key.is_some() {
            return Err(Error::Configuration(
                "pass project_key or root_key, not both".into(),
            ));
        }
        let project_key = project_key
            .or(root_key)
            .unwrap_or_default()
            .trim()
            .to_owned();
        if project_key.is_empty() {
            return Err(Error::Configuration(
                "a project key is required; configure one directly or set \
                 REQKEY_PROJECT_KEY/REQKEY_ROOT_KEY"
                    .into(),
            ));
        }
        if timeout.is_zero() {
            return Err(Error::Configuration(
                "timeout must be greater than zero".into(),
            ));
        }
        let base_url = base_url.trim().trim_end_matches('/').to_owned();
        if base_url.is_empty() {
            return Err(Error::Configuration("base_url cannot be empty".into()));
        }
        let parsed = url::Url::parse(&base_url)
            .map_err(|error| Error::Configuration(format!("base_url is invalid: {error}")))?;
        if !matches!(parsed.scheme(), "http" | "https") {
            return Err(Error::Configuration(
                "base_url must use http or https".into(),
            ));
        }
        Ok(Self {
            project_key,
            base_url,
            timeout,
        })
    }

    fn headers(&self) -> Result<HeaderMap> {
        let mut headers = HeaderMap::new();
        let authorization = HeaderValue::from_str(&format!("Bearer {}", self.project_key))
            .map_err(|_| Error::Configuration("project key contains invalid bytes".into()))?;
        headers.insert(header::AUTHORIZATION, authorization);
        headers.insert(
            header::CONTENT_TYPE,
            HeaderValue::from_static("application/json"),
        );
        headers.insert(
            header::USER_AGENT,
            HeaderValue::from_str(&user_agent())
                .map_err(|_| Error::Configuration("invalid SDK user agent".into()))?,
        );
        Ok(headers)
    }
}

/// Builder for the asynchronous [`Client`].
#[derive(Default)]
#[must_use = "a client builder does nothing until build() is called"]
pub struct ClientBuilder {
    project_key: Option<String>,
    root_key: Option<String>,
    base_url: Option<String>,
    timeout: Option<Duration>,
    http_client: Option<reqwest::Client>,
}

impl ClientBuilder {
    /// Set the preferred project credential.
    pub fn project_key(mut self, key: impl Into<String>) -> Self {
        self.project_key = Some(key.into());
        self
    }

    /// Set the backward-compatible root-key alias.
    pub fn root_key(mut self, key: impl Into<String>) -> Self {
        self.root_key = Some(key.into());
        self
    }

    /// Override the ReqKey API origin, primarily for private deployments or tests.
    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = Some(base_url.into());
        self
    }

    /// Set the timeout applied independently to validation and ingestion.
    pub const fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Inject a preconfigured Reqwest client.
    ///
    /// ReqKey authentication and SDK headers are still set on each request.
    pub fn http_client(mut self, client: reqwest::Client) -> Self {
        self.http_client = Some(client);
        self
    }

    /// Build the client after validating all options.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Configuration`] for missing/conflicting credentials,
    /// an invalid URL/timeout, or a transport builder failure.
    pub fn build(self) -> Result<Client> {
        let base_url = self.base_url.unwrap_or_else(|| DEFAULT_BASE_URL.to_owned());
        let config = ClientConfig::from_builder(
            self.project_key,
            self.root_key,
            &base_url,
            self.timeout.unwrap_or(DEFAULT_TIMEOUT),
        )?;
        let http = if let Some(http) = self.http_client {
            http
        } else {
            reqwest::Client::builder()
                .timeout(config.timeout)
                .build()
                .map_err(|error| Error::Configuration(error.to_string()))?
        };
        Ok(Client { config, http })
    }
}

/// Asynchronous ReqKey API client.
#[derive(Clone)]
pub struct Client {
    config: ClientConfig,
    http: reqwest::Client,
}

impl Client {
    /// Create a client with default transport settings.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Configuration`] when the key or default transport is invalid.
    pub fn new(project_key: impl Into<String>) -> Result<Self> {
        Self::builder().project_key(project_key).build()
    }

    /// Start configuring a client.
    pub fn builder() -> ClientBuilder {
        ClientBuilder::default()
    }

    /// Create a client from `REQKEY_PROJECT_KEY`, falling back to `REQKEY_ROOT_KEY`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Configuration`] when no key is set or transport setup fails.
    pub fn from_env() -> Result<Self> {
        let key = env::var("REQKEY_PROJECT_KEY")
            .ok()
            .filter(|value| !value.trim().is_empty())
            .or_else(|| env::var("REQKEY_ROOT_KEY").ok());
        let mut builder = Self::builder();
        if let Some(key) = key {
            builder = builder.project_key(key);
        }
        builder.build()
    }

    /// Begin a consumer-key validation request.
    pub fn verify(&self, key: impl Into<String>) -> Verify<'_> {
        Verify {
            client: self,
            key: key.into(),
            api_id: None,
            credits: 1,
            resource: None,
        }
    }

    /// Send one analytics event to `/ingest`.
    ///
    /// # Errors
    ///
    /// Returns a configuration, timeout, transport, or API error.
    pub async fn ingest(&self, event: &IngestEvent) -> Result<()> {
        event.validate()?;
        let response = self
            .http
            .post(format!("{}/ingest", self.config.base_url))
            .headers(self.config.headers()?)
            .json(&event)
            .send()
            .await
            .map_err(|error| transport_error(&error, Operation::Ingest))?;
        let status = response.status().as_u16();
        if matches!(status, 200 | 202) {
            return Ok(());
        }
        let value = response_value(response, Operation::Ingest).await?;
        Err(api_error(status, value, "ReqKey ingestion failed"))
    }

    async fn send_verify(&self, payload: &VerifyPayload) -> Result<VerificationResult> {
        let response = self
            .http
            .post(format!("{}/key/validate", self.config.base_url))
            .headers(self.config.headers()?)
            .json(payload)
            .send()
            .await
            .map_err(|error| transport_error(&error, Operation::Validate))?;
        let status = response.status().as_u16();
        let retry_after_header = response
            .headers()
            .get(header::RETRY_AFTER)
            .and_then(|value| value.to_str().ok())
            .and_then(|value| value.parse::<f64>().ok());
        let value = response_value(response, Operation::Validate).await?;
        verification_result(status, retry_after_header, value)
    }
}

/// Fluent validation request produced by [`Client::verify`].
#[must_use = "a validation request does nothing until send() is awaited"]
pub struct Verify<'a> {
    client: &'a Client,
    key: String,
    api_id: Option<String>,
    credits: u64,
    resource: Option<String>,
}

impl Verify<'_> {
    /// Associate the decision with a specific ReqKey API.
    pub fn api_id(mut self, api_id: impl Into<String>) -> Self {
        self.api_id = Some(api_id.into());
        self
    }

    /// Atomically deduct this many credits when validation succeeds.
    pub const fn credits(mut self, credits: u64) -> Self {
        self.credits = credits;
        self
    }

    /// Set the endpoint/resource identifier evaluated by ReqKey.
    pub fn resource(mut self, resource: impl Into<String>) -> Self {
        self.resource = Some(resource.into());
        self
    }

    /// Validate the configured key.
    ///
    /// # Errors
    ///
    /// Returns a configuration, timeout, transport, authentication, or API error.
    pub async fn send(self) -> Result<VerificationResult> {
        let payload = VerifyPayload::new(self.key, self.api_id, self.credits, self.resource)?;
        self.client.send_verify(&payload).await
    }
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct VerifyPayload {
    key: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    api_id: Option<String>,
    credits: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    resource: Option<String>,
}

impl VerifyPayload {
    fn new(
        key: String,
        api_id: Option<String>,
        credits: u64,
        resource: Option<String>,
    ) -> Result<Self> {
        if key.trim().is_empty() {
            return Err(Error::Configuration(
                "the consumer API key cannot be empty".into(),
            ));
        }
        Ok(Self {
            key,
            api_id,
            credits,
            resource,
        })
    }
}

/// Request/response analytics event accepted by `/ingest`.
#[derive(Clone, Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IngestEvent {
    #[serde(skip_serializing_if = "Option::is_none")]
    request_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    api_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    method: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    endpoint: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    status_code: Option<u16>,
    #[serde(skip_serializing_if = "Option::is_none")]
    latency_ms: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    client_ip: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    user_agent: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    user_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    consumer_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    api_key: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    consumer_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    query_params: Option<BTreeMap<String, Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    request_headers: Option<BTreeMap<String, String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    response_headers: Option<BTreeMap<String, String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    request_body: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    response_body: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    timestamp: Option<String>,
}

impl IngestEvent {
    /// Start building an event.
    pub fn builder() -> IngestEventBuilder {
        IngestEventBuilder::default()
    }

    fn validate(&self) -> Result<()> {
        if self.request_id.as_deref().is_some_and(str::trim_is_empty) {
            return Err(Error::Configuration(
                "request_id cannot be empty when provided".into(),
            ));
        }
        if self.api_id.as_deref().is_some_and(str::trim_is_empty) {
            return Err(Error::Configuration(
                "api_id cannot be empty when provided".into(),
            ));
        }
        if self.request_id.is_none() && self.api_id.is_none() {
            return Err(Error::Configuration(
                "ingestion requires request_id, api_id, or both".into(),
            ));
        }
        Ok(())
    }
}

trait TrimIsEmpty {
    fn trim_is_empty(&self) -> bool;
}

impl TrimIsEmpty for str {
    fn trim_is_empty(&self) -> bool {
        self.trim().is_empty()
    }
}

/// Builder for [`IngestEvent`].
#[derive(Default)]
#[must_use = "an ingest event builder does nothing until build() is called"]
pub struct IngestEventBuilder(IngestEvent);

macro_rules! string_setter {
    ($name:ident, $field:ident, $doc:literal) => {
        #[doc = $doc]
        pub fn $name(mut self, value: impl Into<String>) -> Self {
            self.0.$field = Some(value.into());
            self
        }
    };
}

impl IngestEventBuilder {
    string_setter!(request_id, request_id, "Set the validation correlation ID.");
    string_setter!(api_id, api_id, "Set the ReqKey API ID.");
    string_setter!(method, method, "Set the HTTP request method.");
    string_setter!(endpoint, endpoint, "Set the normalized endpoint/resource.");
    string_setter!(
        path,
        path,
        "Set the request path, optionally including a safe query."
    );
    string_setter!(client_ip, client_ip, "Set the resolved client IP address.");
    string_setter!(user_agent, user_agent, "Set the request user agent.");
    string_setter!(user_id, user_id, "Set an application user identifier.");
    string_setter!(
        consumer_name,
        consumer_name,
        "Set an explicit consumer display name."
    );
    string_setter!(
        api_key,
        api_key,
        "Set the consumer API key for identity resolution."
    );
    string_setter!(
        consumer_id,
        consumer_id,
        "Set a fallback ReqKey consumer ID."
    );
    string_setter!(timestamp, timestamp, "Set an ISO-8601 event timestamp.");

    /// Set the HTTP response status.
    pub const fn status_code(mut self, value: u16) -> Self {
        self.0.status_code = Some(value);
        self
    }

    /// Set endpoint processing latency in milliseconds.
    pub const fn latency_ms(mut self, value: u64) -> Self {
        self.0.latency_ms = Some(value);
        self
    }

    /// Set captured query parameters.
    pub fn query_params(mut self, value: BTreeMap<String, Value>) -> Self {
        self.0.query_params = Some(value);
        self
    }

    /// Set privacy-filtered request headers.
    pub fn request_headers(mut self, value: BTreeMap<String, String>) -> Self {
        self.0.request_headers = Some(value);
        self
    }

    /// Set privacy-filtered response headers.
    pub fn response_headers(mut self, value: BTreeMap<String, String>) -> Self {
        self.0.response_headers = Some(value);
        self
    }

    /// Set a captured request body. It is truncated to 1,000 Unicode characters.
    pub fn request_body(mut self, value: impl Into<String>) -> Self {
        let value = value.into();
        self.0.request_body = Some(truncate_body(&value));
        self
    }

    /// Set a captured response body. It is truncated to 1,000 Unicode characters.
    pub fn response_body(mut self, value: impl Into<String>) -> Self {
        let value = value.into();
        self.0.response_body = Some(truncate_body(&value));
        self
    }

    /// Validate and finish the event.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Configuration`] when both IDs are absent or either
    /// provided ID is empty.
    pub fn build(mut self) -> Result<IngestEvent> {
        self.0.request_body = self.0.request_body.map(|value| truncate_body(&value));
        self.0.response_body = self.0.response_body.map(|value| truncate_body(&value));
        self.0.validate()?;
        Ok(self.0)
    }
}

fn truncate_body(value: &str) -> String {
    value.chars().take(MAX_BODY_CHARACTERS).collect()
}

async fn response_value(response: reqwest::Response, operation: Operation) -> Result<Value> {
    let status = response.status().as_u16();
    response.json::<Value>().await.map_err(|_| Error::Api {
        status,
        message: format!("ReqKey returned a non-JSON response during {operation}"),
        body: None,
    })
}

fn transport_error(error: &reqwest::Error, operation: Operation) -> Error {
    if error.is_timeout() {
        Error::Timeout { operation }
    } else {
        Error::Transport {
            operation,
            message: error.to_string(),
        }
    }
}

fn api_error(status: u16, value: Value, fallback: &str) -> Error {
    let message = error_message(&value).unwrap_or_else(|| fallback.to_owned());
    if status == 401 {
        Error::Authentication {
            status,
            message,
            body: Some(value),
        }
    } else {
        Error::Api {
            status,
            message,
            body: Some(value),
        }
    }
}

fn error_message(value: &Value) -> Option<String> {
    let object = value.as_object()?;
    ["error", "message"]
        .into_iter()
        .find_map(|key| object.get(key).and_then(Value::as_str))
        .filter(|value| !value.is_empty())
        .map(ToOwned::to_owned)
}

fn verification_result(
    status: u16,
    retry_after_header: Option<f64>,
    value: Value,
) -> Result<VerificationResult> {
    if status == 401 {
        return Err(api_error(
            status,
            value,
            "ReqKey rejected the project credential",
        ));
    }
    if !matches!(status, 200 | 402 | 403 | 429) {
        return Err(api_error(
            status,
            value,
            &format!("ReqKey returned HTTP {status}"),
        ));
    }
    let raw = value.as_object().cloned().ok_or_else(|| Error::Api {
        status,
        message: "ReqKey returned an unexpected response body".into(),
        body: Some(value.clone()),
    })?;
    let valid = raw.get("valid").and_then(Value::as_bool) == Some(true);
    let reason = match status {
        402 => VerificationReason::InsufficientCredits,
        403 => VerificationReason::Forbidden,
        429 => VerificationReason::RateLimited,
        _ if raw.get("rateLimited").and_then(Value::as_bool) == Some(true) => {
            VerificationReason::RateLimited
        }
        _ if valid => VerificationReason::Valid,
        200 => VerificationReason::InvalidKey,
        _ => VerificationReason::Denied,
    };
    let allowed_apis = raw
        .get("allowedApis")
        .and_then(Value::as_array)
        .map(|items| {
            items
                .iter()
                .map(|item| {
                    item.as_str()
                        .map_or_else(|| item.to_string(), ToOwned::to_owned)
                })
                .collect()
        })
        .unwrap_or_default();
    let retry_after = raw
        .get("retryAfter")
        .and_then(Value::as_f64)
        .or(retry_after_header);
    Ok(VerificationResult {
        valid,
        reason,
        status_code: status,
        request_id: string_field(&raw, "requestId"),
        message: string_field(&raw, "message"),
        api_id: string_field(&raw, "apiId"),
        api_name: string_field(&raw, "apiName"),
        resource: string_field(&raw, "resource"),
        credits_remaining: raw.get("creditsRemaining").and_then(Value::as_i64),
        credits_limit: raw.get("creditsLimit").and_then(Value::as_i64),
        allowed_apis,
        retry_after,
        rate_limit: raw.get("rateLimit").and_then(Value::as_object).cloned(),
        raw,
    })
}

fn string_field(map: &Map<String, Value>, key: &str) -> Option<String> {
    map.get(key).and_then(Value::as_str).map(ToOwned::to_owned)
}

#[cfg(feature = "blocking")]
mod blocking {
    #[allow(clippy::wildcard_imports)]
    use super::*;

    /// Builder for the synchronous [`SyncClient`].
    #[derive(Default)]
    #[must_use = "a client builder does nothing until build() is called"]
    pub struct SyncClientBuilder {
        project_key: Option<String>,
        root_key: Option<String>,
        base_url: Option<String>,
        timeout: Option<Duration>,
        http_client: Option<reqwest::blocking::Client>,
    }

    impl SyncClientBuilder {
        /// Set the preferred project credential.
        pub fn project_key(mut self, key: impl Into<String>) -> Self {
            self.project_key = Some(key.into());
            self
        }

        /// Set the backward-compatible root-key alias.
        pub fn root_key(mut self, key: impl Into<String>) -> Self {
            self.root_key = Some(key.into());
            self
        }

        /// Override the ReqKey API origin.
        pub fn base_url(mut self, value: impl Into<String>) -> Self {
            self.base_url = Some(value.into());
            self
        }

        /// Set the timeout applied to each ReqKey operation.
        pub const fn timeout(mut self, value: Duration) -> Self {
            self.timeout = Some(value);
            self
        }

        /// Inject a preconfigured blocking Reqwest client.
        pub fn http_client(mut self, client: reqwest::blocking::Client) -> Self {
            self.http_client = Some(client);
            self
        }

        /// Build the synchronous client.
        ///
        /// # Errors
        ///
        /// Returns [`Error::Configuration`] for invalid client settings.
        pub fn build(self) -> Result<SyncClient> {
            let base_url = self.base_url.unwrap_or_else(|| DEFAULT_BASE_URL.to_owned());
            let config = ClientConfig::from_builder(
                self.project_key,
                self.root_key,
                &base_url,
                self.timeout.unwrap_or(DEFAULT_TIMEOUT),
            )?;
            let http = if let Some(http) = self.http_client {
                http
            } else {
                reqwest::blocking::Client::builder()
                    .timeout(config.timeout)
                    .build()
                    .map_err(|error| Error::Configuration(error.to_string()))?
            };
            Ok(SyncClient { config, http })
        }
    }

    /// Synchronous ReqKey client for non-async applications.
    pub struct SyncClient {
        config: ClientConfig,
        http: reqwest::blocking::Client,
    }

    impl SyncClient {
        /// Create a client with default transport settings.
        ///
        /// # Errors
        ///
        /// Returns [`Error::Configuration`] when client setup fails.
        pub fn new(project_key: impl Into<String>) -> Result<Self> {
            Self::builder().project_key(project_key).build()
        }

        /// Start configuring a synchronous client.
        pub fn builder() -> SyncClientBuilder {
            SyncClientBuilder::default()
        }

        /// Create a client from `REQKEY_PROJECT_KEY`, falling back to `REQKEY_ROOT_KEY`.
        ///
        /// # Errors
        ///
        /// Returns [`Error::Configuration`] when no key is set or setup fails.
        pub fn from_env() -> Result<Self> {
            let key = env::var("REQKEY_PROJECT_KEY")
                .ok()
                .filter(|value| !value.trim().is_empty())
                .or_else(|| env::var("REQKEY_ROOT_KEY").ok());
            let mut builder = Self::builder();
            if let Some(key) = key {
                builder = builder.project_key(key);
            }
            builder.build()
        }

        /// Begin a consumer-key validation request.
        pub fn verify(&self, key: impl Into<String>) -> SyncVerify<'_> {
            SyncVerify {
                client: self,
                key: key.into(),
                api_id: None,
                credits: 1,
                resource: None,
            }
        }

        /// Send one analytics event to `/ingest`.
        ///
        /// # Errors
        ///
        /// Returns a configuration, timeout, transport, or API error.
        pub fn ingest(&self, event: &IngestEvent) -> Result<()> {
            event.validate()?;
            let response = self
                .http
                .post(format!("{}/ingest", self.config.base_url))
                .headers(self.config.headers()?)
                .json(&event)
                .send()
                .map_err(|error| transport_error(&error, Operation::Ingest))?;
            let status = response.status().as_u16();
            if matches!(status, 200 | 202) {
                return Ok(());
            }
            let value = blocking_response_value(response, Operation::Ingest)?;
            Err(api_error(status, value, "ReqKey ingestion failed"))
        }

        fn send_verify(&self, payload: &VerifyPayload) -> Result<VerificationResult> {
            let response = self
                .http
                .post(format!("{}/key/validate", self.config.base_url))
                .headers(self.config.headers()?)
                .json(payload)
                .send()
                .map_err(|error| transport_error(&error, Operation::Validate))?;
            let status = response.status().as_u16();
            let retry_after = response
                .headers()
                .get(header::RETRY_AFTER)
                .and_then(|value| value.to_str().ok())
                .and_then(|value| value.parse::<f64>().ok());
            let value = blocking_response_value(response, Operation::Validate)?;
            verification_result(status, retry_after, value)
        }
    }

    /// Fluent validation request produced by [`SyncClient::verify`].
    #[must_use = "a validation request does nothing until send() is called"]
    pub struct SyncVerify<'a> {
        client: &'a SyncClient,
        key: String,
        api_id: Option<String>,
        credits: u64,
        resource: Option<String>,
    }

    impl SyncVerify<'_> {
        /// Associate the decision with a ReqKey API.
        pub fn api_id(mut self, value: impl Into<String>) -> Self {
            self.api_id = Some(value.into());
            self
        }

        /// Atomically deduct this many credits when validation succeeds.
        pub const fn credits(mut self, value: u64) -> Self {
            self.credits = value;
            self
        }

        /// Set the endpoint/resource identifier evaluated by ReqKey.
        pub fn resource(mut self, value: impl Into<String>) -> Self {
            self.resource = Some(value.into());
            self
        }

        /// Validate the configured key.
        ///
        /// # Errors
        ///
        /// Returns a configuration, timeout, transport, authentication, or API error.
        pub fn send(self) -> Result<VerificationResult> {
            let payload = VerifyPayload::new(self.key, self.api_id, self.credits, self.resource)?;
            self.client.send_verify(&payload)
        }
    }

    fn blocking_response_value(
        response: reqwest::blocking::Response,
        operation: Operation,
    ) -> Result<Value> {
        let status = response.status().as_u16();
        response.json::<Value>().map_err(|_| Error::Api {
            status,
            message: format!("ReqKey returned a non-JSON response during {operation}"),
            body: None,
        })
    }
}

#[cfg(feature = "blocking")]
pub use blocking::{SyncClient, SyncClientBuilder, SyncVerify};

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::{truncate_body, verification_result, Error, VerificationReason, VerifyPayload};

    #[test]
    fn verify_payload_rejects_an_empty_consumer_key() {
        assert!(matches!(
            VerifyPayload::new("  ".into(), None, 1, None),
            Err(Error::Configuration(_))
        ));
    }

    #[test]
    fn normalizer_maps_rate_limited_body_flag() {
        let result = verification_result(200, None, json!({"valid": false, "rateLimited": true}))
            .expect("decision");
        assert_eq!(result.reason, VerificationReason::RateLimited);
    }

    #[test]
    fn body_limit_counts_unicode_characters() {
        let body = truncate_body(&"🦀".repeat(1_050));
        assert_eq!(body.chars().count(), 1_000);
    }
}