tollgate-client 0.30.2

Instance-side quota runtime: background lease refill into the admission layer's LeaseSlot, and a bounded, batched, shed-on-overflow usage writer.
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
//! HTTP implementations of the store traits against a `tollgate-server`.
//!
//! This is the "via-server" topology: the same `LeaseManager`/`UsageWriter`
//! code runs unchanged over [`HttpStore`] instead of a direct backend — the
//! pluggability claim, made executable. Server `Problem.code` strings map
//! back to [`AllocateError`] variants, so fencing and settlement semantics
//! survive the transport.
//!
//! `SnapshotSource::subscribe` returns a closed channel: push distribution
//! over HTTP (SSE/long-poll) is a documented seam in `docs/DESIGN.md`.
//! [`SnapshotManager`](crate::SnapshotManager) detects the closure and uses
//! periodic plus negative-TTL pulls for freshness.

use std::num::NonZeroUsize;
use std::sync::Arc;

use async_trait::async_trait;
use jiff::{SignedDuration, Timestamp};
use tokio::sync::broadcast;

use tollgate_core::{
    AccountId, AccountSnapshot, CostUnits, FencingToken, LeaseId, Principal, PublishableSnapshot,
    UsageEvent,
};
use tollgate_store::wire::{
    API_PREFIX, AcquireRequest, ConsolidateRequest, IngestRequestRef, LeaseTtl, PrincipalsResponse,
    Problem, ReleaseRequest,
};
use tollgate_store::{
    AllocateError, Allocation, IngestError, IngestReport, LeaseAllocator, ReclaimBatch,
    SnapshotPush, SnapshotResolution, SnapshotSource, StoreError, UsageSink,
};

/// A `tollgate-server` client implementing [`LeaseAllocator`],
/// [`SnapshotSource`], [`UsageSink`] and `KeySource` over HTTP(S).
///
/// Every call carries the configured bearer credential, if any, and runs
/// under one request deadline that also covers obtaining that credential.
/// Server problem codes map back to the domain errors a direct backend
/// returns. Snapshot pushes are not supported, so the snapshot manager relies
/// on periodic refresh. Shared as an `Arc` by every background component;
/// [`reconfigure`](Self::reconfigure) rotates credentials and TLS material in
/// place.
pub struct HttpStore {
    base: String,
    transport: arc_swap::ArcSwap<HttpTransport>,
}

struct HttpTransport {
    client: reqwest::Client,
    bearer: Option<Arc<dyn crate::http_security::BearerProvider>>,
    request_timeout: std::time::Duration,
}

impl HttpStore {
    /// Connect with default deadlines. Unauthenticated calls are refused by
    /// tollgate-server; use `with_config` to supply credentials or mTLS.
    pub fn new(base_url: impl Into<String>) -> Result<Arc<Self>, StoreError> {
        Self::with_config(base_url, crate::http_security::HttpStoreConfig::default())
    }

    /// Connect with the given deadlines and otherwise default settings, so
    /// no credentials: tollgate-server refuses unauthenticated calls. See
    /// [`HttpStoreConfig`](crate::HttpStoreConfig) for what each deadline bounds.
    ///
    /// # Errors
    ///
    /// [`StoreError`] for an unusable URL or deadline, as
    /// [`with_config`](Self::with_config).
    pub fn with_timeouts(
        base_url: impl Into<String>,
        connect_timeout: std::time::Duration,
        request_timeout: std::time::Duration,
    ) -> Result<Arc<Self>, StoreError> {
        Self::with_config(
            base_url,
            crate::http_security::HttpStoreConfig {
                connect_timeout,
                request_timeout,
                ..Default::default()
            },
        )
    }

    /// Connect to `base_url` with `config`'s deadlines, TLS material and
    /// credential provider. No request is made here.
    ///
    /// # Errors
    ///
    /// [`StoreError`] when the URL is not HTTP(S), carries userinfo, a query
    /// or a fragment, or uses plaintext `http` to anything but a loopback
    /// address or with TLS material configured; when a deadline is zero or
    /// unrepresentable; or when the CA or identity PEM is invalid.
    pub fn with_config(
        base_url: impl Into<String>,
        config: crate::http_security::HttpStoreConfig,
    ) -> Result<Arc<Self>, StoreError> {
        let (base, client) = crate::http_security::client(&base_url.into(), &config)?;
        Ok(Arc::new(Self {
            base,
            transport: arc_swap::ArcSwap::from_pointee(HttpTransport {
                client,
                bearer: config.bearer,
                request_timeout: config.request_timeout,
            }),
        }))
    }

    /// Rotate TLS roots, the client certificate and/or credential provider as
    /// one generation. In-flight calls retain their original generation; future
    /// calls use the new one through the same Arc held by background managers.
    pub fn reconfigure(
        &self,
        config: crate::http_security::HttpStoreConfig,
    ) -> Result<(), StoreError> {
        let (_, client) = crate::http_security::client(&self.base, &config)?;
        self.transport.store(Arc::new(HttpTransport {
            client,
            bearer: config.bearer,
            request_timeout: config.request_timeout,
        }));
        Ok(())
    }

    fn request(&self, method: reqwest::Method, path: &str) -> HttpRequest {
        let transport = self.transport.load_full();
        let request = transport
            .client
            .request(method, format!("{}{API_PREFIX}{path}", self.base));
        HttpRequest { transport, request }
    }
}

// The builder owns the same generation that supplies its credentials and
// deadline. Call sites cannot combine a new bearer with an old mTLS identity.
struct HttpRequest {
    transport: Arc<HttpTransport>,
    request: reqwest::RequestBuilder,
}

impl HttpRequest {
    fn json<T: serde::Serialize + ?Sized>(mut self, body: &T) -> Self {
        self.request = self.request.json(body);
        self
    }

    async fn send(self) -> Result<reqwest::Response, StoreError> {
        let mut request = self.request;
        let deadline = tokio::time::Instant::now() + self.transport.request_timeout;
        if let Some(provider) = &self.transport.bearer {
            let token = tokio::time::timeout_at(deadline, provider.token())
                .await
                .map_err(|_| StoreError("control-plane credential deadline expired".into()))??;
            request = request.header(reqwest::header::AUTHORIZATION, token.header());
        }
        let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
        if remaining.is_zero() {
            return Err(StoreError("control-plane request deadline expired".into()));
        }
        // Reqwest's deadline includes reading the response body. Reduce it by
        // credential time so a slow identity provider cannot double the budget.
        request
            .timeout(remaining)
            .send()
            .await
            .map_err(|e| StoreError(format!("http: {}", e.without_url())))
    }
}

fn transport_error(e: reqwest::Error) -> AllocateError {
    AllocateError::Storage(StoreError(format!("http: {}", e.without_url())))
}

/// Map a server problem back into the domain vocabulary. Unknown codes are
/// storage errors: fail toward "retryable", never toward a fabricated domain
/// refusal.
fn problem_to_allocate(problem: Problem) -> AllocateError {
    match problem.code.as_str() {
        "unknown-account" => AllocateError::UnknownAccount,
        "account-inactive" => AllocateError::AccountInactive,
        // The code alone is a complete, unattested refusal. Evidence rides
        // beside it and is discarded, not escalated, when it cannot be valid:
        // zero remaining must arrive as `balance-exhausted`.
        "insufficient-balance" => match problem.balance_shortfall {
            Some(evidence) if problem.status == 409 && !evidence.remaining.is_zero() => {
                AllocateError::BalanceInsufficient(evidence)
            }
            _ => AllocateError::InsufficientBalance,
        },
        "balance-exhausted" => match problem.balance_exhaustion {
            Some(evidence) if problem.status == 409 => AllocateError::BalanceExhausted(evidence),
            _ => AllocateError::Storage(StoreError(
                "exhaustion response lacks valid evidence".into(),
            )),
        },
        "invalid-ttl" => AllocateError::InvalidTtl,
        "unknown-lease" => AllocateError::UnknownLease,
        "fenced" => AllocateError::Fenced,
        "lease-not-active" => AllocateError::LeaseNotActive,
        "invalid-release" => AllocateError::InvalidRelease,
        _ => AllocateError::Storage(StoreError(format!(
            "server {}: {}",
            problem.status, problem.title
        ))),
    }
}

/// The server's own words for a refusal, for an error a human will read.
///
/// Falls back to the status when the body is not a `Problem`: a proxy or a
/// load balancer can refuse before the handler is reached, and "server
/// returned 502" is still more use than an empty string.
async fn problem_detail(response: reqwest::Response) -> String {
    let status = response.status().as_u16();
    match response.json::<Problem>().await {
        Ok(problem) => format!("{status} {}: {}", problem.code, problem.title),
        Err(_) => format!("server returned {status}"),
    }
}

async fn read_problem(response: reqwest::Response) -> AllocateError {
    let status = response.status().as_u16();
    match response.json::<Problem>().await {
        Ok(problem) => problem_to_allocate(problem),
        Err(_) => AllocateError::Storage(StoreError(format!("server returned {status}"))),
    }
}

/// A grant's evidence counts the grant's own units, so a smaller remaining
/// cannot describe the ledger that granted it. Discard such evidence rather
/// than let it refuse quotes the account can fund; the grant itself stands.
async fn read_allocation(response: reqwest::Response) -> Result<Allocation, AllocateError> {
    require_complete(response)?
        .json()
        .await
        .map(credible_evidence)
        .map_err(transport_error)
}

fn credible_evidence(mut allocation: Allocation) -> Allocation {
    if allocation
        .funding
        .is_some_and(|funding| funding.remaining < allocation.grant.units)
    {
        allocation.funding = None;
    }
    allocation
}

#[async_trait]
impl LeaseAllocator for HttpStore {
    async fn acquire(
        &self,
        account: AccountId,
        requested: CostUnits,
        ttl: SignedDuration,
        _now: Timestamp,
    ) -> Result<Allocation, AllocateError> {
        // The server stamps its own clock; `now` stays local-only.
        let ttl = LeaseTtl::try_from(ttl)?;
        let response = self
            .request(reqwest::Method::POST, "/leases/acquire")
            .json(&AcquireRequest {
                account_id: account,
                requested,
                ttl,
            })
            .send()
            .await?;
        if !response.status().is_success() {
            return Err(read_problem(response).await);
        }
        read_allocation(response).await
    }

    async fn release(
        &self,
        lease_id: LeaseId,
        fencing_token: FencingToken,
        unspent: CostUnits,
        _now: Timestamp,
    ) -> Result<(), AllocateError> {
        let response = self
            .request(reqwest::Method::POST, "/leases/release")
            .json(&ReleaseRequest {
                lease_id,
                fencing_token,
                unspent,
            })
            .send()
            .await?;
        if !response.status().is_success() {
            return Err(read_problem(response).await);
        }
        Ok(())
    }

    async fn consolidate(
        &self,
        lease_id: LeaseId,
        fencing_token: FencingToken,
        unspent: CostUnits,
        requested: CostUnits,
        needed: CostUnits,
        ttl: SignedDuration,
        _now: Timestamp,
    ) -> Result<Allocation, AllocateError> {
        // One request, because the guarantee is transactional: two calls over
        // this transport would reintroduce exactly the gap the operation
        // exists to close. The server stamps its own clock, as it does for
        // acquire and release.
        let ttl = LeaseTtl::try_from(ttl)?;
        let response = self
            .request(reqwest::Method::POST, "/leases/consolidate")
            .json(&ConsolidateRequest {
                lease_id,
                fencing_token,
                unspent,
                requested,
                needed,
                ttl,
            })
            .send()
            .await?;
        if !response.status().is_success() {
            return Err(read_problem(response).await);
        }
        read_allocation(response).await
    }

    async fn reclaim_expired_batch(
        &self,
        _now: Timestamp,
        _limit: NonZeroUsize,
    ) -> Result<ReclaimBatch, StoreError> {
        // Reclaim is the server's own maintenance loop; the HTTP transport
        // can trigger it but instances never need to.
        Err(StoreError(
            "reclaim is server-side; not exposed through the instance transport".into(),
        ))
    }
}

#[async_trait]
impl SnapshotSource for HttpStore {
    async fn snapshot(&self, principal: Principal) -> Result<SnapshotResolution, StoreError> {
        let response = self
            .request(reqwest::Method::GET, &format!("/snapshots/{principal}"))
            .send()
            .await?;
        if response.status() == reqwest::StatusCode::NOT_FOUND {
            let problem: Problem = response.json().await.map_err(|e| {
                StoreError(format!(
                    "snapshot endpoint returned an unstructured 404, not a confirmed unknown principal: {}", e.without_url()
                ))
            })?;
            if problem.code == "unknown-principal" {
                return Ok(SnapshotResolution::Unknown);
            }
            return Err(StoreError(format!(
                "snapshot endpoint returned 404 with code {} instead of unknown-principal",
                problem.code
            )));
        }
        if response.status() == reqwest::StatusCode::GONE {
            let problem: Problem = response
                .json()
                .await
                .map_err(|e| StoreError(format!("http: {}", e.without_url())))?;
            if problem.code != "revoked-principal" {
                return Err(StoreError(format!(
                    "server {}: {}",
                    problem.status, problem.title
                )));
            }
            let generation = problem.generation.ok_or_else(|| {
                StoreError("revoked-principal response omitted generation".into())
            })?;
            return Ok(SnapshotResolution::Revoked { generation });
        }
        if !response.status().is_success() {
            return Err(StoreError(problem_detail(response).await));
        }
        let snapshot: AccountSnapshot = require_complete(response)?
            .json()
            .await
            .map_err(|e| StoreError(format!("http: {}", e.without_url())))?;
        let snapshot = PublishableSnapshot::try_new(Arc::new(snapshot))
            .map_err(|error| StoreError(format!("invalid snapshot from server: {error}")))?;
        Ok(SnapshotResolution::Present(snapshot))
    }

    fn subscribe(&self) -> broadcast::Receiver<SnapshotPush> {
        let (sender, receiver) = broadcast::channel(1);
        drop(sender);
        receiver
    }

    /// Over HTTP this is the *only* way an instance learns the principal set:
    /// `subscribe` above is a closed channel, so there are no deltas to
    /// accumulate and the periodic refresh carries everything (GL-48).
    ///
    /// A server whose backend cannot enumerate answers 501, which maps back
    /// to `None` — "stay on your configured set" — rather than to an empty
    /// catalogue, which would mean "forget everyone".
    async fn principals(&self) -> Result<Option<Vec<Principal>>, StoreError> {
        let response = self
            .request(reqwest::Method::GET, "/snapshots")
            .send()
            .await?;
        if response.status() == reqwest::StatusCode::NOT_IMPLEMENTED {
            return Ok(None);
        }
        if !response.status().is_success() {
            return Err(StoreError(problem_detail(response).await));
        }
        let body: PrincipalsResponse = require_complete(response)?
            .json()
            .await
            .map_err(|e| StoreError(format!("http: {}", e.without_url())))?;
        Ok(Some(body.principals))
    }
}

#[async_trait]
impl UsageSink for HttpStore {
    async fn ingest(
        &self,
        events: &[UsageEvent],
        _now: Timestamp,
    ) -> Result<IngestReport, IngestError> {
        let response = self
            .request(reqwest::Method::POST, "/usage/ingest")
            .json(&IngestRequestRef { events })
            .send()
            .await?;
        let status = response.status();
        if !status.is_success() {
            let detail = problem_detail(response).await;
            // A 4xx is the server's judgement about *this batch*: too large,
            // undecodable, a contract it does not implement. Replaying it
            // unchanged earns the same answer forever, so it is refused rather
            // than retried — the wedge GL-61 describes is a writer looping on
            // exactly this. The exceptions are the 4xx statuses that
            // describe the moment rather than the payload: 408 and 429 are
            // invitations to try again. 401/403 describe credentials, which
            // can rotate without changing or discarding the batch.
            let terminal = status.is_client_error()
                && status != reqwest::StatusCode::REQUEST_TIMEOUT
                && status != reqwest::StatusCode::TOO_MANY_REQUESTS
                && status != reqwest::StatusCode::UNAUTHORIZED
                && status != reqwest::StatusCode::FORBIDDEN;
            let error = StoreError(detail);
            return Err(if terminal {
                IngestError::Refused(error)
            } else {
                IngestError::Unavailable(error)
            });
        }
        let bytes = bounded_body(
            require_complete(response)?,
            tollgate_store::wire::MAX_INGEST_REPORT_BYTES,
        )
        .await?;
        let report: IngestReport = serde_json::from_slice(&bytes)
            .map_err(|_| StoreError("invalid usage acknowledgement JSON".into()))?;
        report.validate(events.len())?;
        Ok(report)
    }
}

// Successful partial responses must never become a whole snapshot or catalogue.
fn require_complete(response: reqwest::Response) -> Result<reqwest::Response, StoreError> {
    if response.status() != reqwest::StatusCode::OK
        || response
            .headers()
            .contains_key(reqwest::header::CONTENT_RANGE)
    {
        return Err(StoreError(
            "control-plane response requires a complete HTTP 200 response".into(),
        ));
    }
    Ok(response)
}

async fn bounded_body(
    mut response: reqwest::Response,
    limit: usize,
) -> Result<Vec<u8>, StoreError> {
    if response
        .content_length()
        .is_some_and(|length| length > limit as u64)
    {
        return Err(StoreError(
            "control-plane body exceeds its wire limit".into(),
        ));
    }
    let mut bytes = Vec::new();
    while let Some(chunk) = response
        .chunk()
        .await
        .map_err(|e| StoreError(format!("control-plane transport: {}", e.without_url())))?
    {
        if chunk.len() > limit.saturating_sub(bytes.len()) {
            return Err(StoreError(
                "control-plane body exceeds its wire limit".into(),
            ));
        }
        bytes.extend_from_slice(&chunk);
    }
    Ok(bytes)
}

#[async_trait]
impl tollgate_store::KeySource for HttpStore {
    async fn active_keys_page(
        &self,
        _now: Timestamp,
        after: Option<tollgate_core::KeyId>,
        limit: NonZeroUsize,
    ) -> Result<tollgate_store::KeyPage, StoreError> {
        tollgate_store::validate_key_page_limit(limit)?;
        let mut request = self.request(reqwest::Method::GET, "/keys");
        request.request = request.request.query(&[("limit", limit.get().to_string())]);
        if let Some(after) = after {
            request.request = request.request.query(&[("after", after.to_string())]);
        }
        let response = request.send().await?;
        let status = response.status();
        if !status.is_success() {
            let bytes = bounded_body(response, tollgate_store::wire::MAX_KEYS_BODY_BYTES).await?;
            let code = serde_json::from_slice::<Problem>(&bytes)
                .ok()
                .map(|p| p.code);
            let safe_code = match code.as_deref() {
                Some("authentication-required") => "authentication-required",
                Some("scope-forbidden") => "scope-forbidden",
                Some("invalid-query") => "invalid-query",
                Some("invalid-limit") => "invalid-limit",
                _ => "credential-source-unavailable",
            };
            return Err(StoreError(format!(
                "credential read refused: {status} {safe_code}"
            )));
        }
        let bytes = bounded_body(
            require_complete(response)?,
            tollgate_store::wire::MAX_KEYS_BODY_BYTES,
        )
        .await?;
        let body: tollgate_store::wire::KeysResponse = serde_json::from_slice(&bytes)
            .map_err(|_| StoreError("invalid credential page body".into()))?;
        tollgate_store::KeyPage::try_new(
            body.revision,
            body.as_of,
            after,
            limit,
            body.keys,
            body.next_after,
        )
    }
}

#[cfg(test)]
mod exhaustion_tests {
    use super::*;
    use tollgate_core::LeaseGrant;

    #[test]
    fn incomplete_exhaustion_responses_never_become_authoritative() {
        for body in [
            r#"{"status":409,"code":"balance-exhausted","title":"empty"}"#,
            r#"{"status":409,"code":"balance-exhausted","title":"empty","balance_exhaustion":{}}"#,
            r#"{"status":503,"code":"balance-exhausted","title":"empty","balance_exhaustion":{"period_end":null}}"#,
        ] {
            if let Ok(problem) = serde_json::from_str::<Problem>(body) {
                assert!(matches!(
                    problem_to_allocate(problem),
                    AllocateError::Storage(_)
                ));
            }
        }
        let old = serde_json::from_str::<Problem>(
            r#"{"status":409,"code":"insufficient-balance","title":"empty"}"#,
        )
        .unwrap();
        assert_eq!(problem_to_allocate(old), AllocateError::InsufficientBalance);
    }

    /// Every plain domain code maps back to its refusal. A code that fell
    /// through to `Storage` would turn a definite answer into an ambiguous one.
    #[test]
    fn plain_refusal_codes_round_trip() {
        for (code, expected) in [
            ("unknown-account", AllocateError::UnknownAccount),
            ("account-inactive", AllocateError::AccountInactive),
            ("insufficient-balance", AllocateError::InsufficientBalance),
            ("invalid-ttl", AllocateError::InvalidTtl),
            ("unknown-lease", AllocateError::UnknownLease),
            ("fenced", AllocateError::Fenced),
            ("lease-not-active", AllocateError::LeaseNotActive),
            ("invalid-release", AllocateError::InvalidRelease),
        ] {
            let problem = Problem {
                status: 409,
                code: code.into(),
                title: code.into(),
                generation: None,
                balance_exhaustion: None,
                balance_shortfall: None,
            };
            assert_eq!(problem_to_allocate(problem), expected, "{code}");
        }
    }

    #[test]
    fn incomplete_shortfall_responses_never_become_authoritative() {
        for body in [
            // Zero remaining is exhaustion and must arrive under its own code.
            r#"{"status":409,"code":"insufficient-balance","title":"short","balance_shortfall":{"remaining":0,"period_end":null}}"#,
            r#"{"status":503,"code":"insufficient-balance","title":"short","balance_shortfall":{"remaining":5,"period_end":null}}"#,
        ] {
            let problem = serde_json::from_str::<Problem>(body).unwrap();
            assert_eq!(
                problem_to_allocate(problem),
                AllocateError::InsufficientBalance,
                "{body}"
            );
        }
        // A period end is required, never defaulted to "unscheduled".
        assert!(
            serde_json::from_str::<Problem>(
                r#"{"status":409,"code":"insufficient-balance","title":"short","balance_shortfall":{"remaining":5}}"#
            )
            .is_err()
        );
        let attested = serde_json::from_str::<Problem>(
            r#"{"status":409,"code":"insufficient-balance","title":"short","balance_shortfall":{"remaining":5,"period_end":null}}"#,
        )
        .unwrap();
        assert_eq!(
            problem_to_allocate(attested),
            AllocateError::BalanceInsufficient(tollgate_core::BalanceShortfall {
                remaining: CostUnits(5),
                period_end: None,
            })
        );
    }

    /// A server that predates evidence sends a bare grant, which reads as a
    /// grant with nothing attested.
    #[test]
    fn a_grant_without_evidence_parses_as_unattested() {
        let grant = LeaseGrant {
            lease_id: LeaseId(1),
            account_id: AccountId(1),
            fencing_token: FencingToken(1),
            units: CostUnits(10),
            expires_at: jiff::Timestamp::UNIX_EPOCH,
        };
        let old = serde_json::to_string(&grant).unwrap();
        let parsed: Allocation = serde_json::from_str(&old).unwrap();
        assert_eq!(
            parsed,
            Allocation {
                grant,
                funding: None
            }
        );
    }

    #[test]
    fn grant_evidence_below_the_grant_itself_is_discarded() {
        let grant = LeaseGrant {
            lease_id: LeaseId(1),
            account_id: AccountId(1),
            fencing_token: FencingToken(1),
            units: CostUnits(10),
            expires_at: jiff::Timestamp::UNIX_EPOCH,
        };
        let with = |remaining| Allocation {
            grant,
            funding: Some(tollgate_core::BalanceShortfall {
                remaining: CostUnits(remaining),
                period_end: None,
            }),
        };
        assert_eq!(credible_evidence(with(9)).funding, None);
        assert_eq!(credible_evidence(with(10)), with(10));
    }
}