Skip to main content

lean_ctx_protocol/cloud/
bus.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Bus leases (C5): one holder per resource across the machines of an
4//! organization, decided by the service clock.
5//!
6//! - `POST /v1/bus/leases` [`BusLeaseRequestV1`] → [`BusLeaseV1`];
7//! - `POST /v1/bus/leases/{lease_id}/renew` [`BusLeaseRenewRequestV1`] →
8//!   [`BusLeaseV1`];
9//! - `DELETE /v1/bus/leases/{lease_id}?fencing_token=` → 204.
10//!
11//! The bus itself (`wss://<host>/v1/bus`) speaks bus v2; its frames are the
12//! C0 2.x fixtures under `tests/fixtures/cloud-v2/bus/`.
13//!
14//! Plan updates (feature `plan_updates`, local-read contract §37.2), JSON
15//! documents the engine checks itself:
16//! - `GET /v1/vaults/{vault_id}/plans?state=active` → the active plans;
17//! - `GET /v1/vaults/{vault_id}/plans/{plan_id}?version=` → one signed
18//!   plan version;
19//! - `POST /v1/vaults/{vault_id}/plans/{plan_id}/ack` → the agents' answers.
20
21use serde::{Deserialize, Serialize};
22
23use super::{require_schema, validate_id};
24use crate::{UtcTimestamp, ValidationError};
25
26pub const BUS_LEASE_REQUEST_SCHEMA: &str = "leanctx.cloud.bus-lease-request/v1";
27pub const BUS_LEASE_RENEW_REQUEST_SCHEMA: &str = "leanctx.cloud.bus-lease-renew-request/v1";
28pub const BUS_LEASE_SCHEMA: &str = "leanctx.cloud.bus-lease/v1";
29
30/// Longest bus lease.
31pub const MAX_BUS_LEASE_MS: u64 = 15 * 60 * 1000;
32
33/// Current lease holder, when a lease was not granted.
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35pub struct BusLeaseHolderV1 {
36    pub agent_id: String,
37    pub instance_id: String,
38    pub expires_at: UtcTimestamp,
39}
40
41/// `POST /v1/bus/leases`.
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
43#[serde(deny_unknown_fields)]
44pub struct BusLeaseRequestV1 {
45    pub schema: String,
46    /// e.g. `file`, `task`, `branch`.
47    pub resource_kind: String,
48    /// Lowercase hex SHA-256 of the repo-relative resource; never a path.
49    pub resource_ref: String,
50    pub vault_id: String,
51    pub owner_agent_id: String,
52    pub duration_ms: u64,
53}
54
55impl BusLeaseRequestV1 {
56    pub fn validate(&self) -> Result<(), ValidationError> {
57        require_schema(&self.schema, BUS_LEASE_REQUEST_SCHEMA)?;
58        validate_id(&self.resource_kind, "resource_kind")?;
59        super::validate_hex64(&self.resource_ref, "resource_ref")?;
60        super::validate_vault_id(&self.vault_id)?;
61        validate_id(&self.owner_agent_id, "owner_agent_id")?;
62        validate_duration(self.duration_ms)
63    }
64}
65
66fn validate_duration(duration_ms: u64) -> Result<(), ValidationError> {
67    if (1..=MAX_BUS_LEASE_MS).contains(&duration_ms) {
68        Ok(())
69    } else {
70        Err(ValidationError::new("duration_ms must be 1-900000"))
71    }
72}
73
74/// `POST /v1/bus/leases/{lease_id}/renew`.
75#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(deny_unknown_fields)]
77pub struct BusLeaseRenewRequestV1 {
78    pub schema: String,
79    pub fencing_token: u64,
80    pub duration_ms: u64,
81}
82
83impl BusLeaseRenewRequestV1 {
84    pub fn validate(&self) -> Result<(), ValidationError> {
85        require_schema(&self.schema, BUS_LEASE_RENEW_REQUEST_SCHEMA)?;
86        validate_duration(self.duration_ms)
87    }
88}
89
90/// Lease decision. Granted: `lease_id`, `fencing_token` (strictly increasing
91/// per resource) and `expires_at`. Refused: `holder`. 1.9 erratum: a renewal
92/// keeps `lease_id` and `fencing_token` and only moves `expires_at`; a new
93/// token comes only with a new grant.
94#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95pub struct BusLeaseV1 {
96    pub schema: String,
97    pub granted: bool,
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    pub lease_id: Option<String>,
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub fencing_token: Option<u64>,
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub expires_at: Option<UtcTimestamp>,
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub holder: Option<BusLeaseHolderV1>,
106    pub server_time: UtcTimestamp,
107}
108
109impl BusLeaseV1 {
110    pub fn validate(&self) -> Result<(), ValidationError> {
111        require_schema(&self.schema, BUS_LEASE_SCHEMA)?;
112        let granted_fields =
113            self.lease_id.is_some() && self.fencing_token.is_some() && self.expires_at.is_some();
114        if self.granted != granted_fields || (self.granted && self.holder.is_some()) {
115            return Err(ValidationError::new(
116                "a granted lease has id, token and expiry; a refused one has none",
117            ));
118        }
119        Ok(())
120    }
121}