spiral-contract 0.1.12

Language-neutral service wire values
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
//! Transport-independent failures returned by service implementations.

use std::error::Error;
use std::fmt::{self, Debug, Display, Formatter};

use crate::error::{ErrorEnvelope, ServiceError, canonical_http_status, new_error_instance_id};

/// An owned failure that can cross asynchronous service boundaries.
pub type BoxError = Box<dyn Error + Send + Sync + 'static>;

/// A well-formed service rejection and its optional typed interpretation.
pub struct ServiceFailure<E> {
    envelope: ErrorEnvelope,
    declared: Option<E>,
    observed_status: Option<u16>,
}

impl<E> ServiceFailure<E> {
    /// Construct a locally-created error that is not declared by the service.
    pub fn undeclared(envelope: ErrorEnvelope) -> Self {
        Self {
            envelope,
            declared: None,
            observed_status: None,
        }
    }

    /// Return the authoritative wire envelope.
    pub fn envelope(&self) -> &ErrorEnvelope {
        &self.envelope
    }

    /// Return the typed error when the envelope exactly matches this client contract.
    pub fn declared(&self) -> Option<&E> {
        self.declared.as_ref()
    }

    /// Consume this failure if it has a typed declared interpretation.
    pub fn into_declared(mut self) -> Result<E, Self> {
        match self.declared.take() {
            Some(error) => Ok(error),
            None => Err(self),
        }
    }

    /// Return the canonical HTTP status implied by the envelope's error code.
    pub fn canonical_status(&self) -> u16 {
        canonical_http_status(&self.envelope.error_code)
    }

    /// Return the status observed on an HTTP response, if this failure crossed HTTP.
    pub fn observed_status(&self) -> Option<u16> {
        self.observed_status
    }

    /// Return the observed HTTP status, or the envelope's canonical status for a local failure.
    pub fn status(&self) -> u16 {
        self.observed_status
            .unwrap_or_else(|| self.canonical_status())
    }

    fn into_local_undeclared<T>(self) -> ServiceFailure<T> {
        ServiceFailure {
            envelope: self.envelope,
            declared: None,
            observed_status: None,
        }
    }
}

impl<E: ServiceError> ServiceFailure<E> {
    fn locally_declared(error: E) -> Self {
        let envelope = error.to_envelope(new_error_instance_id());
        Self {
            envelope,
            declared: Some(error),
            observed_status: None,
        }
    }

    /// Decode a remote service failure without discarding its actual HTTP status.
    pub fn remote(status: u16, envelope: ErrorEnvelope) -> Self {
        let declared = (canonical_http_status(&envelope.error_code) == status)
            .then(|| E::from_envelope(&envelope))
            .flatten();
        Self {
            envelope,
            declared,
            observed_status: Some(status),
        }
    }
}

/// A bounded response body retained for an error that did not contain a valid envelope.
pub struct UnknownRemote {
    status: u16,
    content_type: Option<String>,
    body: Vec<u8>,
    truncated: bool,
    source: Option<BoxError>,
}

impl UnknownRemote {
    /// Return the HTTP status observed on the response.
    pub fn status(&self) -> u16 {
        self.status
    }

    /// Return the response content type when it was a valid text header.
    pub fn content_type(&self) -> Option<&str> {
        self.content_type.as_deref()
    }

    /// Return the bounded response body prefix.
    pub fn body(&self) -> &[u8] {
        &self.body
    }

    /// Report whether the response exceeded the retained body limit.
    pub fn truncated(&self) -> bool {
        self.truncated
    }
}

/// A request transport failure, optionally after response headers were received.
pub struct TransportFailure {
    source: BoxError,
    observed_status: Option<u16>,
}

impl TransportFailure {
    /// Return the response status when headers were received before the transport failed.
    pub fn observed_status(&self) -> Option<u16> {
        self.observed_status
    }
}

/// A complete response that did not satisfy the service wire contract.
pub struct ProtocolFailure {
    message: String,
    observed_status: Option<u16>,
}

impl ProtocolFailure {
    /// Return a redaction-safe description of the violated contract.
    pub fn message(&self) -> &str {
        &self.message
    }

    /// Return the response status when the violation followed response headers.
    pub fn observed_status(&self) -> Option<u16> {
        self.observed_status
    }
}

/// A service call failure, independent of local or HTTP dispatch.
pub enum CallError<E> {
    /// A well-formed service error returned locally or by an HTTP peer.
    Service(ServiceFailure<E>),
    /// A non-successful HTTP response without a valid service envelope.
    UnknownRemote(UnknownRemote),
    /// The transport failed before completing a service response.
    Transport(TransportFailure),
    /// A complete response did not satisfy the service wire contract.
    Protocol(ProtocolFailure),
    /// The local implementation encountered an undeclared failure.
    Internal {
        /// Underlying failure retained for server diagnostics.
        source: BoxError,
        /// Correlation identity returned to callers and emitted in server logs.
        error_instance_id: String,
    },
}

impl<E> CallError<E> {
    /// Preserve a transport failure that occurred before response headers arrived.
    pub fn transport(error: impl Into<BoxError>) -> Self {
        Self::Transport(TransportFailure {
            source: error.into(),
            observed_status: None,
        })
    }

    /// Preserve a transport failure that occurred after response headers arrived.
    pub fn transport_response(status: u16, error: impl Into<BoxError>) -> Self {
        Self::Transport(TransportFailure {
            source: error.into(),
            observed_status: Some(status),
        })
    }

    /// Record a malformed request configuration or response without observed headers.
    pub fn protocol(message: impl Into<String>) -> Self {
        Self::Protocol(ProtocolFailure {
            message: message.into(),
            observed_status: None,
        })
    }

    /// Record a response that violated the wire contract.
    pub fn protocol_response(status: u16, message: impl Into<String>) -> Self {
        Self::Protocol(ProtocolFailure {
            message: message.into(),
            observed_status: Some(status),
        })
    }

    /// Preserve a non-successful HTTP response without a valid error envelope.
    pub fn unknown_remote(
        status: u16,
        content_type: Option<String>,
        body: Vec<u8>,
        truncated: bool,
    ) -> Self {
        Self::UnknownRemote(UnknownRemote {
            status,
            content_type,
            body,
            truncated,
            source: None,
        })
    }

    /// Preserve a failed error-body read together with response information received first.
    pub fn unreadable_remote(
        status: u16,
        content_type: Option<String>,
        body: Vec<u8>,
        error: impl Into<BoxError>,
    ) -> Self {
        Self::UnknownRemote(UnknownRemote {
            status,
            content_type,
            body,
            truncated: false,
            source: Some(error.into()),
        })
    }

    /// Create a well-formed locally-raised error outside the declared error set.
    pub fn service(envelope: ErrorEnvelope) -> Self {
        Self::Service(ServiceFailure::undeclared(envelope))
    }

    /// Preserve an underlying local failure with a new correlation identity.
    pub fn internal(error: impl Into<BoxError>) -> Self {
        Self::Internal {
            source: error.into(),
            error_instance_id: new_error_instance_id(),
        }
    }

    /// Construct the shared missing-or-invalid-credentials error.
    pub fn unauthenticated() -> Self {
        Self::service(ErrorEnvelope::new(
            "UNAUTHENTICATED",
            "Default:Unauthenticated",
            new_error_instance_id(),
        ))
    }

    /// Construct the shared authorization-denial error.
    pub fn permission_denied(operation: impl Into<String>, resource: impl Into<String>) -> Self {
        let mut envelope = ErrorEnvelope::new(
            "PERMISSION_DENIED",
            "Default:PermissionDenied",
            new_error_instance_id(),
        );
        envelope
            .parameters
            .insert("operation".into(), operation.into());
        envelope
            .parameters
            .insert("resource".into(), resource.into());
        Self::service(envelope)
    }

    /// Return the correlation identity carried by a service or internal error.
    pub fn error_instance_id(&self) -> Option<&str> {
        match self {
            Self::Service(failure) => Some(&failure.envelope.error_instance_id),
            Self::Internal {
                error_instance_id, ..
            } => Some(error_instance_id),
            Self::UnknownRemote(_) | Self::Transport(_) | Self::Protocol(_) => None,
        }
    }

    /// Propagate caller authentication failures and hide every other dependency failure.
    pub fn from_dependency<F>(error: CallError<F>) -> Self
    where
        F: Send + Sync + 'static,
    {
        match error {
            CallError::Service(failure) if matches!(failure.canonical_status(), 401 | 403) => {
                Self::Service(failure.into_local_undeclared())
            }
            error => {
                let error_instance_id = error
                    .error_instance_id()
                    .map(ToOwned::to_owned)
                    .unwrap_or_else(new_error_instance_id);
                Self::Internal {
                    source: Box::new(error),
                    error_instance_id,
                }
            }
        }
    }
}

impl<E: ServiceError> From<E> for CallError<E> {
    fn from(error: E) -> Self {
        Self::Service(ServiceFailure::locally_declared(error))
    }
}

impl<E> Display for CallError<E> {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::Service(_) => "service call rejected",
            Self::UnknownRemote(_) => "remote service returned an unknown error",
            Self::Transport(_) => "service transport failed",
            Self::Protocol(_) => "invalid service response",
            Self::Internal { .. } => "service implementation failed",
        })
    }
}

impl<E> Debug for CallError<E> {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::Service(_) => "CallError::Service([REDACTED])",
            Self::UnknownRemote(_) => "CallError::UnknownRemote([REDACTED])",
            Self::Transport(_) => "CallError::Transport([REDACTED])",
            Self::Protocol(_) => "CallError::Protocol([REDACTED])",
            Self::Internal { .. } => "CallError::Internal([REDACTED])",
        })
    }
}

impl<E> Error for CallError<E>
where
    E: Send + Sync + 'static,
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Service(failure) => Some(&failure.envelope),
            Self::UnknownRemote(error) => error.source.as_deref().map(|error| error as _),
            Self::Transport(error) => Some(error.source.as_ref()),
            Self::Protocol(_) => None,
            Self::Internal { source, .. } => Some(source.as_ref()),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::error::Error;
    use std::io;

    use uuid::Uuid;

    use super::{CallError, ServiceFailure};
    use crate::error::{ErrorEnvelope, ServiceError};

    #[derive(Debug)]
    struct TestError;

    impl ServiceError for TestError {
        fn to_envelope(&self, instance: String) -> ErrorEnvelope {
            ErrorEnvelope::new("NOT_FOUND", "Test:NotFound", instance)
        }

        fn from_envelope(envelope: &ErrorEnvelope) -> Option<Self> {
            (envelope.error_code == "NOT_FOUND" && envelope.error_name == "Test:NotFound")
                .then_some(Self)
        }
    }

    #[test]
    fn hides_diagnostics_but_preserves_error_sources() {
        let errors = [
            CallError::<TestError>::transport(io::Error::other("secret")),
            CallError::<TestError>::protocol("secret"),
            CallError::<TestError>::internal(io::Error::other("secret")),
        ];
        for error in errors {
            assert!(!error.to_string().contains("secret"));
            assert!(!format!("{error:?}").contains("secret"));
            if !matches!(error, CallError::Protocol(_)) {
                assert_eq!(error.source().unwrap().to_string(), "secret");
            }
        }
    }

    #[test]
    fn dependency_propagation_keeps_only_canonical_auth_failures() {
        let denied = CallError::<TestError>::permission_denied("read", "resource");
        let instance = denied.error_instance_id().unwrap().to_owned();
        let propagated = CallError::<TestError>::from_dependency(denied);
        let CallError::Service(failure) = propagated else {
            panic!("permission denial was not propagated")
        };
        assert_eq!(failure.canonical_status(), 403);
        assert_eq!(failure.status(), 403);
        assert_eq!(failure.observed_status(), None);
        assert_eq!(failure.envelope().error_instance_id, instance);
        assert!(failure.declared().is_none());

        let envelope = ErrorEnvelope::new(
            "PERMISSION_DENIED",
            "Default:PermissionDenied",
            Uuid::now_v7().to_string(),
        );
        let remote = CallError::<TestError>::Service(ServiceFailure::remote(500, envelope));
        let CallError::Service(failure) = CallError::<TestError>::from_dependency(remote) else {
            panic!("canonical permission denial was not propagated")
        };
        assert_eq!(failure.status(), 403);
        assert_eq!(failure.observed_status(), None);

        let remote = CallError::<TestError>::unknown_remote(401, None, Vec::new(), false);
        assert!(matches!(
            CallError::<TestError>::from_dependency(remote),
            CallError::Internal { .. }
        ));
    }
}