crucible-wire 0.10.1

What a crucible server and client share about the wire: operation descriptions, the error model, validation, timestamps and the JSON readers and writers
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
//! Errors. An implementation returns `crucible_server_runtime_rust::Result<T>` and may fail with
//! anything: a modelled error, or any other error through `?`. The framework
//! decides afterwards what reaches the caller (see `docs/framework.md`).

use std::fmt;

use serde_json::Value;

use crate::operation::ErrorInfo;
use crate::permissions::{PermissionInfo, ResourceInfo};

pub type Result<T, E = Error> = std::result::Result<T, E>;

/// Maximum depth of error source traversal to protect against cycles.
pub const MAX_SOURCE_DEPTH: usize = 64;

/// Any error. Like `anyhow::Error` it is not itself a `std::error::Error`,
/// so every error type converts into it with `?`.
pub struct Error {
    inner: Box<dyn std::error::Error + Send + Sync + 'static>,
}

impl Error {
    pub fn new(error: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self {
            inner: Box::new(error),
        }
    }

    /// An internal failure with a message for the logs. Callers never see it.
    pub fn internal(message: impl Into<String>) -> Self {
        Self::new(Internal(message.into()))
    }

    pub fn get_ref(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {
        &*self.inner
    }

    pub fn downcast_ref<E: std::error::Error + 'static>(&self) -> Option<&E> {
        self.inner.downcast_ref::<E>()
    }

    /// This error and its sources, for a log line. Traversal depth is bounded
    /// by [`MAX_SOURCE_DEPTH`] to protect against cycles in source chains.
    pub fn chain(&self) -> String {
        let mut text = self.inner.to_string();
        let mut source = self.inner.source();
        for _ in 0..MAX_SOURCE_DEPTH {
            let Some(next) = source else { break };
            text.push_str(": ");
            text.push_str(&next.to_string());
            source = next.source();
        }
        text
    }
}

impl<E: std::error::Error + Send + Sync + 'static> From<E> for Error {
    fn from(error: E) -> Self {
        Self::new(error)
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.inner, f)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.inner, f)
    }
}

#[derive(Debug)]
struct Internal(String);

impl fmt::Display for Internal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for Internal {}

/// An error shape from the model. Generated for every `@error` structure.
pub trait ModelledError: std::error::Error + Send + Sync + 'static {
    fn info(&self) -> &'static ErrorInfo;
    /// The model's shape id, independent of Rust renames.
    fn shape_id(&self) -> &'static str {
        self.info().name
    }
    /// Every member, as on the wire; the protocol moves header members out.
    fn to_json(&self) -> Value;

    /// Writes all fields as a document, including members bound to HTTP
    /// headers or payloads in unary responses. Generated errors override
    /// this to support bounded stream serialization without an intermediate value.
    fn write_json_to(&self, out: &mut dyn std::io::Write) -> serde_json::Result<()> {
        serde_json::to_writer(out, &self.to_json())
    }

    /// The body (members plus `"__type"`) straight into `out`, without the
    /// header members, which come back as (header, text). Generated errors
    /// write in one pass through [`write_error`]; this default goes through
    /// [`ModelledError::to_json`].
    fn write_json(&self, out: &mut Vec<u8>) -> serde_json::Result<Vec<(&'static str, String)>> {
        let info = self.info();
        crate::split::write_typed(&self.to_json(), info.members, Some(info.name), out)
    }
}

/// How a generated error implements [`ModelledError::write_json`]: one pass,
/// no JSON value in between.
#[doc(hidden)]
pub fn write_error<E: ModelledError + serde::Serialize>(
    error: &E,
    out: &mut Vec<u8>,
) -> serde_json::Result<Vec<(&'static str, String)>> {
    let info = error.info();
    crate::split::write_typed(error, info.members, Some(info.name), out)
}

/// Errors the framework answers itself, outside any model: a request no
/// operation serves, or an internal failure when the service models no
/// internal error.
///
/// Non-exhaustive: the framework may answer new errors, so a `match` outside
/// this crate needs a wildcard arm. [`name`](Self::name),
/// [`status`](Self::status) and [`message`](Self::message) cover every
/// variant.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum FrameworkError {
    /// Credentials were absent or refused by an authentication extension.
    Unauthenticated,
    /// An authenticated principal cannot perform the requested action.
    Forbidden,
    /// The request conflicts with one the service already accepted: an
    /// idempotency token reused for a different request, or for one still
    /// running. The message says which, and what the caller can do.
    Conflict {
        message: &'static str,
    },
    /// The resource does not exist, or the caller may not know that it
    /// does: the modelled `crucible.errors#NotFoundException` (404), whose
    /// members are the resource's fixed message ([`ResourceInfo::not_found`])
    /// and `resourceType`, its authorization name. An authorization that
    /// hides a resource and a handler reporting genuine absence both answer
    /// it, so the two are indistinguishable. It never names a permission or
    /// an identifier.
    NotFound {
        resource: &'static ResourceInfo,
    },
    /// An authenticated caller can see the resource but lacks `permission`
    /// on it: a 403 `ForbiddenException`, like `Forbidden`, whose message is
    /// the permission's [`PermissionInfo::denied`], naming its value and
    /// resource type, unless the permission is internal: then the message
    /// names neither. Unlike `Forbidden` it sends no `insufficient_scope`
    /// challenge: no token would carry a grant.
    PermissionDenied {
        permission: &'static PermissionInfo,
    },
    UnknownOperation,
    MethodNotAllowed {
        allowed: Vec<&'static str>,
    },
    UnsupportedMediaType,
    InternalFailure,
}

impl FrameworkError {
    pub fn name(&self) -> &'static str {
        match self {
            Self::Unauthenticated => "UnauthenticatedException",
            Self::Forbidden => "ForbiddenException",
            Self::Conflict { .. } => "ConflictException",
            Self::NotFound { .. } => "NotFoundException",
            Self::PermissionDenied { .. } => "ForbiddenException",
            Self::UnknownOperation => "UnknownOperation",
            Self::MethodNotAllowed { .. } => "MethodNotAllowed",
            Self::UnsupportedMediaType => "UnsupportedMediaTypeException",
            Self::InternalFailure => "InternalFailure",
        }
    }

    pub fn status(&self) -> u16 {
        match self {
            Self::Unauthenticated => 401,
            Self::Forbidden => 403,
            Self::Conflict { .. } => 409,
            Self::NotFound { .. } => 404,
            Self::PermissionDenied { .. } => 403,
            Self::UnknownOperation => 404,
            Self::MethodNotAllowed { .. } => 405,
            Self::UnsupportedMediaType => 415,
            Self::InternalFailure => 500,
        }
    }

    pub fn message(&self) -> &'static str {
        match self {
            Self::Unauthenticated => "authentication is required",
            Self::Forbidden => "access is forbidden",
            Self::Conflict { message } => message,
            Self::NotFound { resource } => resource.not_found,
            Self::PermissionDenied { permission } if permission.is_public() => permission.denied,
            Self::PermissionDenied { .. } => "This principal may not perform this operation.",
            Self::UnknownOperation => "no operation serves this request",
            Self::MethodNotAllowed { .. } => "the request method is not allowed for this target",
            Self::UnsupportedMediaType => "the request content-type is not supported",
            Self::InternalFailure => "the request failed; quote the request id when reporting it",
        }
    }
}

impl fmt::Display for FrameworkError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.message())
    }
}

impl std::error::Error for FrameworkError {}

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

    #[derive(Debug)]
    struct SimpleError(&'static str);

    impl fmt::Display for SimpleError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str(self.0)
        }
    }

    impl std::error::Error for SimpleError {}

    #[derive(Debug)]
    struct NestedError {
        msg: &'static str,
        source: Option<Box<dyn std::error::Error + Send + Sync + 'static>>,
    }

    impl fmt::Display for NestedError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str(self.msg)
        }
    }

    impl std::error::Error for NestedError {
        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
            self.source
                .as_deref()
                .map(|s| s as &(dyn std::error::Error + 'static))
        }
    }

    #[derive(Debug)]
    struct CyclicError;

    impl fmt::Display for CyclicError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("loop")
        }
    }

    impl std::error::Error for CyclicError {
        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
            Some(self)
        }
    }

    #[derive(Debug)]
    struct CycleA;
    #[derive(Debug)]
    struct CycleB;
    static CYCLE_A: CycleA = CycleA;
    static CYCLE_B: CycleB = CycleB;

    impl fmt::Display for CycleA {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("node_a")
        }
    }

    impl std::error::Error for CycleA {
        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
            Some(&CYCLE_B)
        }
    }

    impl fmt::Display for CycleB {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("node_b")
        }
    }

    impl std::error::Error for CycleB {
        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
            Some(&CYCLE_A)
        }
    }

    #[test]
    fn not_found_and_permission_denied_name_only_what_they_may() {
        use crate::permissions::Tier;

        static INBOX: ResourceInfo = ResourceInfo {
            name: "inbox",
            identifiers: &["workspaceId", "inboxId"],
            not_found: "No such inbox.",
        };
        static SEND: PermissionInfo = PermissionInfo {
            resource: &INBOX,
            symbol: "mailSend",
            value: "mail:send",
            aliases: &[],
            tier: Tier::Public,
            denied: "This principal does not hold mail:send on that inbox.",
        };
        static WATCH: PermissionInfo = PermissionInfo {
            resource: &INBOX,
            symbol: "watch",
            value: "inbox:watch",
            aliases: &[],
            tier: Tier::Internal,
            denied: "This principal does not hold inbox:watch on that inbox.",
        };
        let missing = FrameworkError::NotFound { resource: &INBOX };
        assert_eq!(missing.status(), 404);
        assert_eq!(missing.name(), "NotFoundException");
        assert_eq!(missing.message(), "No such inbox.");

        let denied = FrameworkError::PermissionDenied { permission: &SEND };
        assert_eq!(denied.status(), 403);
        assert_eq!(denied.name(), "ForbiddenException");
        assert_eq!(
            denied.message(),
            "This principal does not hold mail:send on that inbox."
        );
        // An internal permission's own message is never used.
        let internal = FrameworkError::PermissionDenied { permission: &WATCH };
        assert_eq!(
            internal.message(),
            "This principal may not perform this operation."
        );
    }

    #[test]
    fn chain_with_no_source() {
        let error = Error::internal("standalone");
        assert_eq!(error.chain(), "standalone");
    }

    #[test]
    fn chain_with_sources() {
        let leaf = SimpleError("leaf");
        let middle = NestedError {
            msg: "middle",
            source: Some(Box::new(leaf)),
        };
        let root = NestedError {
            msg: "root",
            source: Some(Box::new(middle)),
        };
        let error = Error::new(root);
        assert_eq!(error.chain(), "root: middle: leaf");
    }

    #[test]
    fn chain_terminates_on_self_referential_cycle() {
        let error = Error::new(CyclicError);
        let chain = error.chain();
        assert_eq!(chain.matches(": loop").count(), MAX_SOURCE_DEPTH);
        assert!(chain.starts_with("loop: loop"));
    }

    #[test]
    fn chain_terminates_on_mutual_cycle() {
        let error = Error::new(CycleA);
        let chain = error.chain();
        let total_sources = chain.matches(": node_a").count() + chain.matches(": node_b").count();
        assert_eq!(total_sources, MAX_SOURCE_DEPTH);
        assert!(chain.starts_with("node_a: node_b: node_a"));
    }

    #[test]
    fn chain_bounds_deep_error_hierarchy() {
        let mut current = NestedError {
            msg: "leaf",
            source: None,
        };
        for _ in 0..100 {
            current = NestedError {
                msg: "step",
                source: Some(Box::new(current)),
            };
        }
        let error = Error::new(current);
        let chain = error.chain();
        assert_eq!(chain.matches(": ").count(), MAX_SOURCE_DEPTH);
    }
}