runcycles 0.2.3

Rust client for the Cycles budget-management protocol — deterministic spend control for AI agents and LLM workflows
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
//! Async HTTP client for the Cycles API.

use std::sync::Arc;
use std::time::Duration;

use reqwest::header::{HeaderMap, HeaderValue};
use serde::de::DeserializeOwned;
use serde::Serialize;

use crate::config::{CyclesClientBuilder, CyclesConfig};
use crate::constants::{
    API_KEY_HEADER, BALANCES_PATH, DECIDE_PATH, EVENTS_PATH, IDEMPOTENCY_KEY_HEADER,
    RESERVATIONS_PATH,
};
use crate::error::Error;
use crate::guard::ReservationGuard;
use crate::models::enums::Unit;
use crate::models::request::{
    BalanceParams, CommitRequest, DecisionRequest, EventCreateRequest, ExtendRequest,
    ListReservationsParams, ReleaseRequest, ReservationCreateRequest,
};
use crate::models::response::{
    BalanceResponse, CommitResponse, DecisionResponse, ErrorResponse, EventCreateResponse,
    ExtendResponse, ReleaseResponse, ReservationCreateResponse, ReservationDetail,
    ReservationListResponse,
};
use crate::models::{ErrorCode, ReservationId};
use crate::response::ApiResponse;
use crate::validation;

/// Marker prefix the server emits when a reservation targets a scope for which
/// no budget exists at the requested unit. The server indexes budgets by the
/// composite key `(scope, unit)`, so a scope that has an active budget in one
/// unit (e.g. `USD_MICROCENTS`) surfaces as a `NOT_FOUND` when the client
/// reserves in a different unit (e.g. `TOKENS`). The raw 404 message then
/// reads like a plain scope-lookup miss, which is misleading. See issue #8.
const BUDGET_NOT_FOUND_MARKER: &str = "Budget not found for provided scope";

/// If `err` is a 404 `NOT_FOUND` whose message matches the server's
/// "Budget not found for provided scope" pattern, enrich it with the unit that
/// was sent so unit-mismatch cases are self-diagnosing.
fn enrich_budget_not_found(err: Error, unit: Unit) -> Error {
    match err {
        Error::Api {
            status: 404,
            code: Some(ErrorCode::NotFound),
            message,
            request_id,
            retry_after,
            details,
        } if message.starts_with(BUDGET_NOT_FOUND_MARKER) => {
            let unit_wire = serde_json::to_string(&unit)
                .ok()
                .map(|s| s.trim_matches('"').to_string())
                .unwrap_or_else(|| "UNKNOWN".to_string());
            let enriched = format!(
                "{message} (request was sent with unit={unit_wire}; \
                 verify an ACTIVE budget exists at this scope AND unit — \
                 the server indexes budgets by (scope, unit), so a mismatched \
                 unit surfaces as a 404 NOT_FOUND)"
            );
            Error::Api {
                status: 404,
                code: Some(ErrorCode::NotFound),
                message: enriched,
                request_id,
                retry_after,
                details,
            }
        }
        other => other,
    }
}

/// Async client for the Cycles budget authority API.
///
/// The client is cheaply cloneable (uses `Arc` internally) and can be shared
/// across tasks. It is `Send + Sync`.
///
/// # Example
///
/// ```rust,no_run
/// use runcycles::{CyclesClient, models::*};
///
/// # async fn example() -> Result<(), runcycles::Error> {
/// let client = CyclesClient::builder("my-api-key", "http://localhost:7878")
///     .tenant("acme")
///     .build();
///
/// let guard = client.reserve(
///     ReservationCreateRequest::builder()
///         .subject(Subject { tenant: Some("acme".into()), ..Default::default() })
///         .action(Action::new("llm.completion", "gpt-4o"))
///         .estimate(Amount::usd_microcents(5000))
///         .build()
/// ).await?;
///
/// // ... do work ...
///
/// guard.commit(
///     CommitRequest::builder()
///         .actual(Amount::usd_microcents(3200))
///         .build()
/// ).await?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct CyclesClient {
    inner: Arc<ClientInner>,
}

struct ClientInner {
    http: reqwest::Client,
    config: CyclesConfig,
}

impl std::fmt::Debug for CyclesClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CyclesClient")
            .field("base_url", &self.inner.config.base_url)
            .finish()
    }
}

impl CyclesClient {
    /// Create a new client builder.
    pub fn builder(api_key: impl Into<String>, base_url: impl Into<String>) -> CyclesClientBuilder {
        CyclesClientBuilder::new(api_key, base_url)
    }

    /// Create a client from a pre-built config.
    pub fn new(config: CyclesConfig) -> Self {
        Self::from_builder(config, None)
    }

    /// Internal constructor used by the builder.
    pub(crate) fn from_builder(config: CyclesConfig, http_client: Option<reqwest::Client>) -> Self {
        let http = http_client.unwrap_or_else(|| {
            reqwest::Client::builder()
                .connect_timeout(config.connect_timeout)
                .timeout(config.connect_timeout + config.read_timeout)
                .build()
                .expect("failed to build HTTP client")
        });

        Self {
            inner: Arc::new(ClientInner { http, config }),
        }
    }

    /// Access the client configuration.
    pub fn config(&self) -> &CyclesConfig {
        &self.inner.config
    }

    // ─── High-Level API ──────────────────────────────────────────────

    /// Reserve budget and return an RAII guard.
    ///
    /// The guard must be committed or released. If dropped without either,
    /// a best-effort release is attempted.
    ///
    /// Returns `Err(Error::BudgetExceeded)` if the decision is `Deny`.
    #[tracing::instrument(skip(self, req), fields(cycles.reservation_id, cycles.decision))]
    pub async fn reserve(&self, req: ReservationCreateRequest) -> Result<ReservationGuard, Error> {
        validation::validate_subject(&req.subject)?;
        validation::validate_ttl_ms(req.ttl_ms)?;
        validation::validate_grace_period_ms(req.grace_period_ms)?;
        validation::validate_non_negative(req.estimate.amount, "estimate.amount")?;

        let resp = self.create_reservation(&req).await?;

        if resp.decision.is_denied() {
            return Err(Error::BudgetExceeded {
                message: resp
                    .reason_code
                    .clone()
                    .unwrap_or_else(|| "budget exceeded".to_string()),
                affected_scopes: resp.affected_scopes.clone(),
                retry_after: resp.retry_after_ms.map(Duration::from_millis),
                request_id: None,
            });
        }

        let reservation_id = resp
            .reservation_id
            .clone()
            .expect("reservation_id must be present when decision is ALLOW");

        let span = tracing::Span::current();
        span.record("cycles.reservation_id", reservation_id.as_str());
        span.record("cycles.decision", tracing::field::debug(&resp.decision));

        Ok(ReservationGuard::new(
            self.clone(),
            reservation_id,
            resp.decision,
            resp.caps.clone(),
            resp.expires_at_ms,
            resp.affected_scopes.clone(),
            req.ttl_ms,
        ))
    }

    // ─── Low-Level API ──────────────────────────────────────────────

    /// Create a budget reservation.
    pub async fn create_reservation(
        &self,
        req: &ReservationCreateRequest,
    ) -> Result<ReservationCreateResponse, Error> {
        self.post_json(RESERVATIONS_PATH, req, Some(req.idempotency_key.as_str()))
            .await
            .map_err(|e| enrich_budget_not_found(e, req.estimate.unit))
    }

    /// Create a reservation and return the response with metadata.
    pub async fn create_reservation_with_metadata(
        &self,
        req: &ReservationCreateRequest,
    ) -> Result<ApiResponse<ReservationCreateResponse>, Error> {
        self.post_json_with_metadata(RESERVATIONS_PATH, req, Some(req.idempotency_key.as_str()))
            .await
            .map_err(|e| enrich_budget_not_found(e, req.estimate.unit))
    }

    /// Commit actual spend against a reservation.
    pub async fn commit_reservation(
        &self,
        id: &ReservationId,
        req: &CommitRequest,
    ) -> Result<CommitResponse, Error> {
        let path = format!("{RESERVATIONS_PATH}/{}/commit", id.as_str());
        self.post_json(&path, req, Some(req.idempotency_key.as_str()))
            .await
    }

    /// Release (cancel) a reservation, returning reserved budget.
    pub async fn release_reservation(
        &self,
        id: &ReservationId,
        req: &ReleaseRequest,
    ) -> Result<ReleaseResponse, Error> {
        let path = format!("{RESERVATIONS_PATH}/{}/release", id.as_str());
        self.post_json(&path, req, Some(req.idempotency_key.as_str()))
            .await
    }

    /// Extend a reservation's TTL (heartbeat).
    pub async fn extend_reservation(
        &self,
        id: &ReservationId,
        req: &ExtendRequest,
    ) -> Result<ExtendResponse, Error> {
        let path = format!("{RESERVATIONS_PATH}/{}/extend", id.as_str());
        self.post_json(&path, req, Some(req.idempotency_key.as_str()))
            .await
    }

    /// Preflight budget decision check (no reservation created).
    pub async fn decide(&self, req: &DecisionRequest) -> Result<DecisionResponse, Error> {
        self.post_json(DECIDE_PATH, req, Some(req.idempotency_key.as_str()))
            .await
            .map_err(|e| enrich_budget_not_found(e, req.estimate.unit))
    }

    /// Create a direct-debit event (no prior reservation).
    pub async fn create_event(
        &self,
        req: &EventCreateRequest,
    ) -> Result<EventCreateResponse, Error> {
        self.post_json(EVENTS_PATH, req, Some(req.idempotency_key.as_str()))
            .await
            .map_err(|e| enrich_budget_not_found(e, req.actual.unit))
    }

    /// List reservations with optional filters.
    pub async fn list_reservations(
        &self,
        params: &ListReservationsParams,
    ) -> Result<ReservationListResponse, Error> {
        self.get_json(RESERVATIONS_PATH, Some(params)).await
    }

    /// Get details of a single reservation.
    pub async fn get_reservation(&self, id: &ReservationId) -> Result<ReservationDetail, Error> {
        let path = format!("{RESERVATIONS_PATH}/{}", id.as_str());
        self.get_json::<(), _>(&path, None).await
    }

    /// Query budget balances for scopes.
    pub async fn get_balances(&self, params: &BalanceParams) -> Result<BalanceResponse, Error> {
        if !params.has_filter() {
            return Err(Error::Validation(
                "getBalances requires at least one subject filter".to_string(),
            ));
        }
        self.get_json(BALANCES_PATH, Some(params)).await
    }

    // ─── Internal HTTP Methods ──────────────────────────────────────

    async fn post_json<B: Serialize, R: DeserializeOwned>(
        &self,
        path: &str,
        body: &B,
        idempotency_key: Option<&str>,
    ) -> Result<R, Error> {
        let resp: ApiResponse<R> = self
            .post_json_with_metadata(path, body, idempotency_key)
            .await?;
        Ok(resp.into_inner())
    }

    async fn post_json_with_metadata<B: Serialize, R: DeserializeOwned>(
        &self,
        path: &str,
        body: &B,
        idempotency_key: Option<&str>,
    ) -> Result<ApiResponse<R>, Error> {
        let url = format!("{}{}", self.inner.config.base_url, path);

        let mut headers = HeaderMap::new();
        headers.insert(
            API_KEY_HEADER,
            HeaderValue::from_str(&self.inner.config.api_key)
                .map_err(|e| Error::Config(format!("invalid API key header value: {e}")))?,
        );
        if let Some(key) = idempotency_key {
            if let Ok(val) = HeaderValue::from_str(key) {
                headers.insert(IDEMPOTENCY_KEY_HEADER, val);
            }
        }

        let resp = self
            .inner
            .http
            .post(&url)
            .headers(headers)
            .json(body)
            .send()
            .await?;

        let response_headers = resp.headers().clone();
        let status = resp.status().as_u16();

        if (200..300).contains(&status) {
            let data: R = resp
                .json()
                .await
                .map_err(|e| Error::Deserialization(serde::de::Error::custom(e.to_string())))?;
            Ok(ApiResponse::from_response(data, &response_headers))
        } else {
            Err(self
                .parse_error_response(status, resp, &response_headers)
                .await)
        }
    }

    async fn get_json<Q: Serialize, R: DeserializeOwned>(
        &self,
        path: &str,
        query: Option<&Q>,
    ) -> Result<R, Error> {
        let url = format!("{}{}", self.inner.config.base_url, path);

        let mut request = self
            .inner
            .http
            .get(&url)
            .header(API_KEY_HEADER, &self.inner.config.api_key);

        if let Some(q) = query {
            request = request.query(q);
        }

        let resp = request.send().await?;
        let response_headers = resp.headers().clone();
        let status = resp.status().as_u16();

        if (200..300).contains(&status) {
            resp.json()
                .await
                .map_err(|e| Error::Deserialization(serde::de::Error::custom(e.to_string())))
        } else {
            Err(self
                .parse_error_response(status, resp, &response_headers)
                .await)
        }
    }

    async fn parse_error_response(
        &self,
        status: u16,
        resp: reqwest::Response,
        headers: &HeaderMap,
    ) -> Error {
        let header_request_id = headers
            .get("x-request-id")
            .and_then(|v| v.to_str().ok())
            .map(String::from);

        let body: Option<ErrorResponse> = resp.json().await.ok();

        let message = body
            .as_ref()
            .map(|b| b.message.clone())
            .unwrap_or_else(|| format!("HTTP {status}"));

        let error_code: Option<ErrorCode> = body
            .as_ref()
            .and_then(|b| serde_json::from_value(serde_json::Value::String(b.error.clone())).ok());

        let details = body.as_ref().and_then(|b| b.details.clone());

        // Prefer request_id from body, fall back to header
        let request_id = body
            .as_ref()
            .and_then(|b| b.request_id.clone())
            .or(header_request_id);

        // Classify budget-related 409 errors
        if status == 409
            && matches!(
                error_code,
                Some(ErrorCode::BudgetExceeded)
                    | Some(ErrorCode::OverdraftLimitExceeded)
                    | Some(ErrorCode::DebtOutstanding)
            )
        {
            return Error::BudgetExceeded {
                message,
                affected_scopes: vec![],
                retry_after: None,
                request_id,
            };
        }

        Error::Api {
            status,
            code: error_code,
            message,
            request_id,
            retry_after: None,
            details,
        }
    }
}

// Compile-time assertion: CyclesClient is Send + Sync.
const _: fn() = || {
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<CyclesClient>();
};

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn enrich_budget_not_found_adds_unit_hint() {
        let err = Error::Api {
            status: 404,
            code: Some(ErrorCode::NotFound),
            message: "Budget not found for provided scope: tenant:rider".to_string(),
            request_id: Some("req-1".to_string()),
            retry_after: None,
            details: None,
        };
        let enriched = enrich_budget_not_found(err, Unit::Tokens);
        match enriched {
            Error::Api {
                status,
                code,
                message,
                request_id,
                ..
            } => {
                assert_eq!(status, 404);
                assert_eq!(code, Some(ErrorCode::NotFound));
                assert!(message.starts_with("Budget not found for provided scope: tenant:rider"));
                assert!(message.contains("unit=TOKENS"));
                assert!(message.contains("(scope, unit)"));
                assert_eq!(request_id.as_deref(), Some("req-1"));
            }
            other => panic!("expected Api error, got {other:?}"),
        }
    }

    #[test]
    fn enrich_budget_not_found_uses_wire_format_for_unit() {
        let err = Error::Api {
            status: 404,
            code: Some(ErrorCode::NotFound),
            message: "Budget not found for provided scope: tenant:acme".to_string(),
            request_id: None,
            retry_after: None,
            details: None,
        };
        let enriched = enrich_budget_not_found(err, Unit::UsdMicrocents);
        if let Error::Api { message, .. } = enriched {
            assert!(message.contains("unit=USD_MICROCENTS"));
        } else {
            panic!("expected Api error");
        }
    }

    #[test]
    fn enrich_budget_not_found_ignores_non_matching_messages() {
        let err = Error::Api {
            status: 404,
            code: Some(ErrorCode::NotFound),
            message: "Reservation not found: rsv_xyz".to_string(),
            request_id: None,
            retry_after: None,
            details: None,
        };
        let enriched = enrich_budget_not_found(err, Unit::Tokens);
        if let Error::Api { message, .. } = enriched {
            assert_eq!(message, "Reservation not found: rsv_xyz");
            assert!(!message.contains("unit="));
        } else {
            panic!("expected Api error");
        }
    }

    #[test]
    fn enrich_budget_not_found_ignores_non_404_errors() {
        let err = Error::Api {
            status: 409,
            code: Some(ErrorCode::NotFound),
            message: "Budget not found for provided scope: tenant:rider".to_string(),
            request_id: None,
            retry_after: None,
            details: None,
        };
        let enriched = enrich_budget_not_found(err, Unit::Tokens);
        if let Error::Api { message, .. } = enriched {
            // 409 is not enriched — only 404 NOT_FOUND with the server marker is
            assert_eq!(message, "Budget not found for provided scope: tenant:rider");
        } else {
            panic!("expected Api error");
        }
    }

    #[test]
    fn enrich_budget_not_found_passes_through_other_error_kinds() {
        let err = Error::Validation("bad input".to_string());
        let enriched = enrich_budget_not_found(err, Unit::Tokens);
        assert!(matches!(enriched, Error::Validation(msg) if msg == "bad input"));
    }
}