Skip to main content

lean_ctx_protocol/cloud/
error.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Error body of every non-2xx Cloud response: `{"error":{...}}`.
4
5use serde::{Deserialize, Serialize};
6
7/// Machine-readable error code. Unknown codes from a newer service decode as
8/// [`CloudErrorCode::Unknown`] and are handled by HTTP status.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
10#[serde(rename_all = "snake_case")]
11pub enum CloudErrorCode {
12    /// 400, device flow: the user has not approved yet; poll again after `interval`.
13    AuthorizationPending,
14    /// 400, device flow: polling too fast; add 5 s to the interval.
15    SlowDown,
16    /// 400, device flow: the device code expired; start again.
17    ExpiredToken,
18    /// 400, device flow: the user refused.
19    AccessDenied,
20    /// 400: body failed validation or carried unknown fields.
21    InvalidRequest,
22    /// 401: access token missing, expired or not for this instance.
23    Unauthorized,
24    /// 402: the organization's plan does not include Cloud.
25    PlanRequired,
26    /// 403: the lease lacks the right this route needs.
27    ForbiddenRight,
28    /// 403 with `kind` (1.4): the organization switched this upload off.
29    /// Stop that kind of upload and drop its queue until a lease allows it.
30    UploadDisabled,
31    /// 404: unknown instance, vault, proposal or lease.
32    NotFound,
33    /// 404 with `feature` (Cloud API.md "feature switches"): the operator
34    /// switched this feature off on this Cloud (`instance_metrics` while
35    /// `CLOUD_ENGINE_METRICS` is off). The route exists; try again much later.
36    FeatureDisabled,
37    /// 409 with `limit`/`used`: every instance seat is taken.
38    InstanceLimit,
39    /// 409 with `expected`/`actual`: knowledge moved on.
40    RevisionConflict,
41    /// 409 with `reason` (1.5): the object is not in a state that allows
42    /// this.
43    InvalidState,
44    /// 401: the instance lease is past `grace_until`; renew or reconnect.
45    LeaseExpired,
46    /// 422: the service screening refused content the engine should have removed.
47    ScreeningRequired,
48    /// 429 with `retry_after_s`.
49    RateLimited,
50    /// 426 with `min_instance` (also in the `Cloud-Min-Instance` header).
51    UpgradeRequired,
52    /// 401 with `revocation` (C0 2.0 E12, §3.17.3): a workspace admin
53    /// revoked this instance; every engine route answers it until a new
54    /// connect. Never retried.
55    InstanceRevoked,
56    /// Release B quotas (Cloud API §8.1): `resource`, `limit`, `used`,
57    /// `reset_at`. Counted resources (`registered_instances`,
58    /// `private_vaults`) answer 409 (`registered_instances` in Personal adds
59    /// `cooldown_days`, `reset_at` = when a cooling-down slot frees);
60    /// monthly ones (`transfer_bytes`, `bus_messages`) answer 429 with
61    /// `retry_after_s` and `Retry-After` until `reset_at`. Never overage:
62    /// the engine waits, its outbox keeps local work.
63    QuotaExceeded,
64    /// 403 with `member` (dotted policy path) and `level` (the outermost
65    /// level whose document refuses; consent refusals add `action`): Cloud
66    /// itself enforces an `x-enforcement: server` policy member (§7.2).
67    PolicyDenied,
68    /// 403 with `resource: "storage_bytes"`, `limit`/`used` and
69    /// `limit_bytes`/`used_bytes`: the workspace's LeanCTX Cloud storage is
70    /// full. Nothing frees by waiting; a person frees storage or upgrades.
71    StorageQuotaExceeded,
72    /// 429 with `limit_bytes_per_hour`, `retry_after_s` and `Retry-After`:
73    /// the sliding-hour upload allowance (max(storage/4, 256 MiB)) is used
74    /// up. Transient: wait `retry_after_s`, then upload the rest.
75    UploadRateLimited,
76    /// Any code this engine does not know.
77    #[serde(other)]
78    Unknown,
79}
80
81impl CloudErrorCode {
82    /// HTTP status the service answers with for this code.
83    pub fn http_status(self) -> u16 {
84        match self {
85            Self::AuthorizationPending
86            | Self::SlowDown
87            | Self::ExpiredToken
88            | Self::AccessDenied
89            | Self::InvalidRequest => 400,
90            Self::Unauthorized | Self::LeaseExpired | Self::InstanceRevoked => 401,
91            Self::PlanRequired => 402,
92            Self::ForbiddenRight
93            | Self::UploadDisabled
94            | Self::PolicyDenied
95            | Self::StorageQuotaExceeded => 403,
96            Self::NotFound | Self::FeatureDisabled => 404,
97            Self::InstanceLimit | Self::RevisionConflict | Self::InvalidState => 409,
98            Self::ScreeningRequired => 422,
99            Self::UpgradeRequired => 426,
100            // 409 for counted resources; the monthly ones, the common case
101            // on data routes, are 429.
102            Self::RateLimited | Self::QuotaExceeded | Self::UploadRateLimited => 429,
103            Self::Unknown => 500,
104        }
105    }
106}
107
108/// The `error` object.
109#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
110pub struct CloudErrorDetailV1 {
111    pub code: CloudErrorCode,
112    /// Human-readable, safe to show; never contains secrets or tokens.
113    pub message: String,
114    #[serde(default, skip_serializing_if = "Option::is_none")]
115    pub retry_after_s: Option<u64>,
116    /// `instance_limit`: seats in the plan; `quota_exceeded`: the quota
117    /// (bytes for `transfer_bytes`, so wider than 32 bits).
118    #[serde(default, skip_serializing_if = "Option::is_none")]
119    pub limit: Option<u64>,
120    /// `instance_limit`: seats in use; `quota_exceeded`: what is used.
121    #[serde(default, skip_serializing_if = "Option::is_none")]
122    pub used: Option<u64>,
123    /// `quota_exceeded`: the quota (`registered_instances`, `private_vaults`,
124    /// `transfer_bytes`, `bus_messages`, or one a newer Cloud adds).
125    #[serde(default, skip_serializing_if = "Option::is_none")]
126    pub resource: Option<String>,
127    /// `quota_exceeded`: when it frees (RFC 3339; `null` when nothing frees
128    /// by itself).
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    pub reset_at: Option<String>,
131    /// `quota_exceeded` `registered_instances`: the Personal slot cool-down.
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    pub cooldown_days: Option<u32>,
134    /// `policy_denied`: the dotted member path that refused.
135    #[serde(default, skip_serializing_if = "Option::is_none")]
136    pub member: Option<String>,
137    /// `policy_denied`: the outermost level whose document refuses.
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub level: Option<String>,
140    /// `policy_denied` of `consent_required_for`: the action.
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    pub action: Option<String>,
143    /// `revision_conflict`: revision the client expected.
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub expected: Option<u64>,
146    /// `revision_conflict`: current revision.
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub actual: Option<u64>,
149    /// `upgrade_required`: lowest engine version accepted.
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    pub min_instance: Option<String>,
152    /// `upload_disabled`: which upload the organization switched off.
153    #[serde(default, skip_serializing_if = "Option::is_none")]
154    pub kind: Option<CloudUploadKind>,
155    /// 1.5: machine-readable detail of the code (`[a-z_]`, ≤ 64), e.g.
156    /// `required`.
157    #[serde(default, skip_serializing_if = "Option::is_none")]
158    pub reason: Option<String>,
159    /// 1.5: the request field the error is about (`invalid_request`).
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub field: Option<String>,
162    /// 1.6: the proposal an error is about (`proposal_state`, `not_found`).
163    #[serde(default, skip_serializing_if = "Option::is_none")]
164    pub number: Option<u64>,
165    /// `not_permitted` (Cloud task #17): the check that failed, `presence`
166    /// (the agent has no live presence on the bus) or `role` (present in
167    /// another role).
168    #[serde(default, skip_serializing_if = "Option::is_none")]
169    pub check: Option<String>,
170    /// `not_permitted`: the task's role.
171    #[serde(default, skip_serializing_if = "Option::is_none")]
172    pub role: Option<String>,
173    /// `not_permitted` with `check: role`: the role the agent is present in.
174    #[serde(default, skip_serializing_if = "Option::is_none")]
175    pub agent_role: Option<String>,
176    /// 2.x `plan_required`: the feature the plan lacks (`repos`,
177    /// `internal_vaults`, …; absent from a 1.x Cloud, where it means Cloud
178    /// itself). `limit`/`used` carry a counted feature's numbers.
179    /// `feature_disabled`: the feature switched off on this Cloud
180    /// (`instance_metrics`).
181    #[serde(default, skip_serializing_if = "Option::is_none")]
182    pub feature: Option<String>,
183    /// 2.x `plan_required`: the lowest plan that includes `feature`
184    /// (`pro`, `team`, `enterprise`).
185    #[serde(default, skip_serializing_if = "Option::is_none")]
186    pub plan_needed: Option<String>,
187    /// Limit refusals (`quota_exceeded`, `storage_quota_exceeded`,
188    /// `upload_rate_limited`, `instance_limit`, `plan_required`): the
189    /// workspace's plan (`personal`, `team`, `enterprise`, `locked`).
190    #[serde(default, skip_serializing_if = "Option::is_none")]
191    pub plan: Option<String>,
192    /// Limit refusals: what helps (`subscribe`, `top_up`, `upgrade_team`,
193    /// `add_seats`, `contact`, `wait`, or one a newer service adds).
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub next_step: Option<String>,
196    /// `storage_quota_exceeded`: the storage quota in bytes.
197    #[serde(default, skip_serializing_if = "Option::is_none")]
198    pub limit_bytes: Option<u64>,
199    /// `storage_quota_exceeded`: the storage used in bytes.
200    #[serde(default, skip_serializing_if = "Option::is_none")]
201    pub used_bytes: Option<u64>,
202    /// `upload_rate_limited`: the upload allowance per sliding hour.
203    #[serde(default, skip_serializing_if = "Option::is_none")]
204    pub limit_bytes_per_hour: Option<u64>,
205    /// `instance_limit` in Team: the workspace's seats.
206    #[serde(default, skip_serializing_if = "Option::is_none")]
207    pub seats: Option<u64>,
208    /// `instance_limit` in Team: the allowance of each seat.
209    #[serde(default, skip_serializing_if = "Option::is_none")]
210    pub per_seat: Option<u64>,
211}
212
213/// An upload an organization can switch off (1.4).
214#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
215#[serde(rename_all = "snake_case")]
216pub enum CloudUploadKind {
217    Metrics,
218    Receipts,
219    #[serde(other)]
220    Unknown,
221}
222
223impl CloudErrorDetailV1 {
224    /// An error with only code and message.
225    pub fn new(code: CloudErrorCode, message: impl Into<String>) -> Self {
226        Self {
227            code,
228            message: message.into(),
229            retry_after_s: None,
230            limit: None,
231            used: None,
232            resource: None,
233            reset_at: None,
234            cooldown_days: None,
235            member: None,
236            level: None,
237            action: None,
238            expected: None,
239            actual: None,
240            min_instance: None,
241            kind: None,
242            reason: None,
243            field: None,
244            number: None,
245            check: None,
246            role: None,
247            agent_role: None,
248            feature: None,
249            plan_needed: None,
250            plan: None,
251            next_step: None,
252            limit_bytes: None,
253            used_bytes: None,
254            limit_bytes_per_hour: None,
255            seats: None,
256            per_seat: None,
257        }
258    }
259}
260
261/// Body of every non-2xx response.
262#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
263pub struct CloudErrorBody {
264    pub error: CloudErrorDetailV1,
265}
266
267#[cfg(test)]
268mod tests {
269    use super::*;
270
271    #[test]
272    fn unknown_codes_decode_as_unknown() {
273        let body: CloudErrorBody =
274            serde_json::from_str(r#"{"error":{"code":"brand_new","message":"x","extra":1}}"#)
275                .unwrap();
276        assert_eq!(body.error.code, CloudErrorCode::Unknown);
277    }
278
279    /// Cloud answers `POST /v1/metrics/hours` with this while
280    /// `CLOUD_ENGINE_METRICS` is off (dogfood 05.11.: decoded as `unknown`).
281    #[test]
282    fn feature_disabled_decodes_with_its_feature() {
283        let body: CloudErrorBody = serde_json::from_str(
284            r#"{"error":{"code":"feature_disabled","message":"this feature is switched off on this Cloud","feature":"instance_metrics"}}"#,
285        )
286        .unwrap();
287        assert_eq!(body.error.code, CloudErrorCode::FeatureDisabled);
288        assert_eq!(body.error.code.http_status(), 404);
289        assert_eq!(body.error.feature.as_deref(), Some("instance_metrics"));
290    }
291
292    /// C0 2.0 `routes/instance_revoked.error.json` decodes to its own code
293    /// (dogfood 25.10.: it decoded as `unknown`, shown as "401 (unknown)").
294    #[test]
295    fn instance_revoked_decodes_from_the_c0_fixture() {
296        let body: CloudErrorBody = serde_json::from_str(include_str!(
297            "../../tests/fixtures/cloud-v2/routes/instance_revoked.error.json"
298        ))
299        .unwrap();
300        assert_eq!(body.error.code, CloudErrorCode::InstanceRevoked);
301        assert_eq!(body.error.code.http_status(), 401);
302    }
303
304    /// C0 2.x `routes/quota_exceeded.error.json` (Release B §8.1): a byte
305    /// quota wider than 32 bits decodes, with resource and reset.
306    #[test]
307    fn quota_exceeded_decodes_from_the_c0_fixture() {
308        let body: CloudErrorBody = serde_json::from_str(include_str!(
309            "../../tests/fixtures/cloud-v2/routes/quota_exceeded.error.json"
310        ))
311        .unwrap();
312        let e = body.error;
313        assert_eq!(e.code, CloudErrorCode::QuotaExceeded);
314        assert_eq!(e.resource.as_deref(), Some("transfer_bytes"));
315        assert_eq!(e.limit, Some(42_949_672_960));
316        assert_eq!(e.used, Some(42_949_672_960));
317        assert_eq!(e.reset_at.as_deref(), Some("2026-11-01T00:00:00Z"));
318        assert_eq!(e.retry_after_s, Some(86_400));
319    }
320
321    /// The server's own shapes (API §7.2 and §3): `policy_denied {member,
322    /// level, action?}` and the Personal slot cool-down; a 1.x engine that does
323    /// not know them still decodes the body (unknown code, extra fields).
324    #[test]
325    fn policy_denied_and_cooldown_decode_and_stay_tolerant() {
326        let denied: CloudErrorBody = serde_json::from_str(
327            r#"{"error":{"code":"policy_denied","message":"x","member":"sharing.consent_required_for","level":"org","action":"trust_boundary"}}"#,
328        )
329        .unwrap();
330        assert_eq!(denied.error.code, CloudErrorCode::PolicyDenied);
331        assert_eq!(denied.error.code.http_status(), 403);
332        assert_eq!(
333            denied.error.member.as_deref(),
334            Some("sharing.consent_required_for")
335        );
336        assert_eq!(denied.error.level.as_deref(), Some("org"));
337        assert_eq!(denied.error.action.as_deref(), Some("trust_boundary"));
338        let slot: CloudErrorBody = serde_json::from_str(
339            r#"{"error":{"code":"quota_exceeded","message":"x","resource":"registered_instances","limit":3,"used":3,"reset_at":"2026-11-02T08:00:00Z","cooldown_days":7}}"#,
340        )
341        .unwrap();
342        assert_eq!(slot.error.cooldown_days, Some(7));
343        let newer: CloudErrorBody = serde_json::from_str(
344            r#"{"error":{"code":"quota_exceeded","message":"x","resource":"gpu_minutes","reset_at":null,"extra":1}}"#,
345        )
346        .unwrap();
347        assert_eq!(newer.error.resource.as_deref(), Some("gpu_minutes"));
348        assert_eq!(newer.error.reset_at, None);
349    }
350
351    /// The cloud's limit refusals (plan limits of 17.11.) decode with
352    /// every field; none of them is `unknown` any more.
353    #[test]
354    fn cloud_limit_refusals_decode_with_their_fields() {
355        let storage: CloudErrorBody = serde_json::from_str(
356            r#"{"error":{"code":"storage_quota_exceeded","message":"x","resource":"storage_bytes","limit":1073741824,"used":1073741824,"limit_bytes":1073741824,"used_bytes":1073741824,"plan":"personal","next_step":"upgrade_team"}}"#,
357        )
358        .unwrap();
359        let e = storage.error;
360        assert_eq!(e.code, CloudErrorCode::StorageQuotaExceeded);
361        assert_eq!(e.code.http_status(), 403);
362        assert_eq!(e.resource.as_deref(), Some("storage_bytes"));
363        assert_eq!(e.limit_bytes, Some(1_073_741_824));
364        assert_eq!(e.used_bytes, Some(1_073_741_824));
365        assert_eq!(e.plan.as_deref(), Some("personal"));
366        assert_eq!(e.next_step.as_deref(), Some("upgrade_team"));
367
368        let rate: CloudErrorBody = serde_json::from_str(
369            r#"{"error":{"code":"upload_rate_limited","message":"x","limit_bytes_per_hour":268435456,"plan":"personal","next_step":"wait","retry_after_s":1200}}"#,
370        )
371        .unwrap();
372        let e = rate.error;
373        assert_eq!(e.code, CloudErrorCode::UploadRateLimited);
374        assert_eq!(e.code.http_status(), 429);
375        assert_eq!(e.limit_bytes_per_hour, Some(268_435_456));
376        assert_eq!(e.retry_after_s, Some(1200));
377        assert_eq!(e.next_step.as_deref(), Some("wait"));
378
379        let seats: CloudErrorBody = serde_json::from_str(
380            r#"{"error":{"code":"instance_limit","message":"x","resource":"connected_instances","limit":4,"used":4,"plan":"team","next_step":"add_seats","seats":2,"per_seat":2}}"#,
381        )
382        .unwrap();
383        let e = seats.error;
384        assert_eq!(e.code, CloudErrorCode::InstanceLimit);
385        assert_eq!(e.resource.as_deref(), Some("connected_instances"));
386        assert_eq!((e.seats, e.per_seat), (Some(2), Some(2)));
387        assert_eq!(e.plan.as_deref(), Some("team"));
388
389        let locked: CloudErrorBody = serde_json::from_str(
390            r#"{"error":{"code":"plan_required","message":"x","feature":"read_only","reason":"trial_ended","plan":"locked","next_step":"subscribe"}}"#,
391        )
392        .unwrap();
393        assert_eq!(locked.error.code, CloudErrorCode::PlanRequired);
394        assert_eq!(locked.error.plan.as_deref(), Some("locked"));
395        assert_eq!(locked.error.next_step.as_deref(), Some("subscribe"));
396    }
397
398    #[test]
399    fn codes_map_to_their_status() {
400        assert_eq!(CloudErrorCode::PlanRequired.http_status(), 402);
401        assert_eq!(CloudErrorCode::InstanceLimit.http_status(), 409);
402        assert_eq!(CloudErrorCode::UpgradeRequired.http_status(), 426);
403        assert_eq!(CloudErrorCode::UploadDisabled.http_status(), 403);
404    }
405
406    #[test]
407    fn upload_disabled_names_its_kind_and_tolerates_new_ones() {
408        let body: CloudErrorBody = serde_json::from_str(
409            r#"{"error":{"code":"upload_disabled","message":"x","kind":"receipts"}}"#,
410        )
411        .unwrap();
412        assert_eq!(body.error.code, CloudErrorCode::UploadDisabled);
413        assert_eq!(body.error.kind, Some(CloudUploadKind::Receipts));
414        let newer: CloudErrorBody = serde_json::from_str(
415            r#"{"error":{"code":"upload_disabled","message":"x","kind":"traces"}}"#,
416        )
417        .unwrap();
418        assert_eq!(newer.error.kind, Some(CloudUploadKind::Unknown));
419    }
420}