crucible_wire/operation.rs
1//! What generated code tells the framework about a service and its
2//! operations. All of it is `'static` data built at compile time, so routing,
3//! binding and logging read it without allocation.
4
5use std::any::Any;
6
7use serde::Serialize;
8use serde::de::DeserializeOwned;
9use serde_json::Value;
10
11use crate::error::ModelledError;
12use crate::validate::{Rejection, Validate};
13
14/// One operation, as the generated marker type `GetGraph` describes it.
15pub trait Operation: Send + Sync + 'static {
16 const INFO: &'static OperationInfo;
17 /// Whether the operation's effective authentication schemes include bearer auth.
18 /// Regenerate clients with this runtime; older generated markers omit this flag.
19 /// Handwritten operations must opt in explicitly when bearer auth is supported.
20 const AUTH_BEARER: bool = false;
21 const AUTH_SCHEMES: Option<&'static [AuthScheme]> = None;
22 /// The release a generated client names in its configured
23 /// header: the `.cru` service's `version` (docs/api-versions-clients.md).
24 const API_VERSION: Option<&'static str> = None;
25 /// The lowercase HTTP header name carrying this operation's release.
26 const API_VERSION_HEADER: &'static str = "crucible-version";
27 /// How the operation pages (`@paginated`), for server extensions that
28 /// read the token from the decoded input.
29 const PAGINATION: Option<Pagination> = None;
30 /// The input member that carries the operation's idempotency token
31 /// (`@idempotencyToken`), for server extensions that read it from the
32 /// decoded input. Generated for server bindings.
33 const IDEMPOTENCY_TOKEN: Option<PaginationMember> = None;
34 /// Reads a successful output back from its JSON form
35 /// ([`Output::to_json`]), so a server extension can answer a retry with
36 /// the output an earlier attempt produced, encoded afresh for the
37 /// retry. Generated for server operations that have an idempotency token;
38 /// `None` means the operation's output cannot be replayed.
39 const OUTPUT_FROM_JSON: Option<OutputFromJson<Self::Output>> = None;
40 /// What the operation requires of its caller (`requires`, `filters`,
41 /// `requires none`, `requires pending`), for the server's `Permissions`
42 /// interceptor. Generated for server bindings; `Undeclared` otherwise.
43 const REQUIREMENTS: crate::permissions::Requirements =
44 crate::permissions::Requirements::Undeclared;
45 /// Evaluates the bindings and `when` conditions of
46 /// [`Operation::REQUIREMENTS`] against the decoded input: one
47 /// [`Check`](crate::permissions::Check) per `Check` or `Filter` clause
48 /// that applies, in clause order. Generated, so it reads fields rather
49 /// than JSON; `None` for an operation with no such clause.
50 const CHECKS: Option<crate::permissions::Checks<Self::Input>> = None;
51 /// The obligation an `assigns <member> at ..` or `assigns loaded at ..`
52 /// clause opens (docs/roles.md ยง4.5), which the handler discharges with
53 /// `roles::assign`. Generated for server bindings; `None` for an
54 /// operation that assigns nothing (or says `assigns none`).
55 const ASSIGNS: Option<crate::permissions::Assignment> = None;
56 /// Whether the model explicitly makes the operation anonymous (it takes
57 /// no credential: `@auth([])` on the operation, a `.cru` `anonymous`
58 /// operation), so it carries no requirements and there is nothing to
59 /// authorize. Never inferred from an empty list of schemes, which also
60 /// describes a service authenticated outside the model.
61 const ANONYMOUS: bool = false;
62 /// The former name of [`Operation::ANONYMOUS`]. The runtime treats an
63 /// operation as anonymous when either is `true`, so a hand-written marker
64 /// that still sets this keeps working until the shim is removed.
65 #[deprecated(since = "0.10.0", note = "use `ANONYMOUS`")]
66 const PUBLIC: bool = Self::ANONYMOUS;
67 const HAS_INPUT: bool = true;
68 const HAS_OUTPUT: bool = true;
69 type Input: DeserializeOwned + Serialize + Validate + Send + Sync + 'static;
70 type Output: Serialize + Send + Sync + 'static;
71}
72
73#[derive(Debug)]
74#[non_exhaustive]
75pub struct ServiceInfo {
76 /// External MCP tools, present only when service generation enabled MCP.
77 pub mcp_tools: Option<&'static [crate::mcp::ToolDescriptor]>,
78 /// The service's shape id, `namespace#Name`.
79 pub id: &'static str,
80 pub version: &'static str,
81 pub operations: &'static [&'static OperationInfo],
82 pub errors: &'static [&'static ErrorInfo],
83 /// Finds the modelled error inside a boxed error, by downcasting to each
84 /// of the service's error types.
85 pub classify: Classify,
86 /// The validation error a rejected request becomes, when the generator
87 /// could fill it; otherwise the service supplies one to the builder.
88 pub reject: Option<RejectFn>,
89 /// The error an internal failure is answered with, carrying only a fixed
90 /// message; `None` answers the protocol's own `InternalFailure`.
91 pub internal: Option<InternalFn>,
92 /// The error a request no operation serves is answered with: the
93 /// validation error with reason `unknownOperation`, when the model has
94 /// that standard reason; `None` answers the protocol's own
95 /// `UnknownOperation`.
96 pub unknown: Option<InternalFn>,
97 /// Every permission the model declares, primaries only
98 /// ([`ServiceInfo::with_permissions`]): what a stored authorization
99 /// decision is read back against, and where a modelled
100 /// `NotFoundException` finds its resource.
101 pub permissions: &'static [&'static crate::permissions::PermissionInfo],
102 /// The shape id of the error the service answers a hidden or missing
103 /// resource with, when the model designates its own (`notFound` in the
104 /// `.cru` service, [`ServiceInfo::with_not_found`]); `None` is the
105 /// framework's `crucible.errors#NotFoundException`. The server never
106 /// builds it: the service's `not_found_factory` does, and every
107 /// response that carries it is sent with `Cache-Control: no-store`.
108 pub not_found: Option<&'static str>,
109 /// The model's release header, preserving its declared spelling.
110 pub version_header: &'static str,
111 /// Whether ordinary HTTP requests must name a release.
112 pub unversioned_required: bool,
113}
114
115pub type Classify =
116 for<'a> fn(&'a (dyn std::error::Error + 'static)) -> Option<&'a dyn ModelledError>;
117pub type RejectFn = fn(&Rejection) -> Box<dyn ModelledError>;
118pub type InternalFn = fn() -> Box<dyn ModelledError>;
119
120impl ServiceInfo {
121 /// Sets the model's release header. Validated when the service is built.
122 pub const fn with_version_header(mut self, name: &'static str) -> Self {
123 self.version_header = name;
124 self
125 }
126
127 /// Requires ordinary HTTP requests to name a release.
128 pub const fn with_unversioned_required(mut self) -> Self {
129 self.unversioned_required = true;
130 self
131 }
132
133 pub fn operation(&self, name: &str) -> Option<&'static OperationInfo> {
134 self.operations.iter().copied().find(|op| op.name == name)
135 }
136
137 /// The same service with its permission registry: generated as
138 /// `service_info(..).with_permissions(&[..])`.
139 pub const fn with_permissions(
140 mut self,
141 permissions: &'static [&'static crate::permissions::PermissionInfo],
142 ) -> Self {
143 self.permissions = permissions;
144 self
145 }
146
147 /// The same service with its own not-found error, by shape id:
148 /// generated as `.with_not_found("pigeon.api#ResourceNotFoundException")`
149 /// for a model that designates one.
150 pub const fn with_not_found(mut self, shape_id: &'static str) -> Self {
151 self.not_found = Some(shape_id);
152 self
153 }
154
155 /// The permission `value` (or an alias of it) on the resource named
156 /// `resource`, from the registry.
157 pub fn permission(
158 &self,
159 resource: &str,
160 value: &str,
161 ) -> Option<&'static crate::permissions::PermissionInfo> {
162 self.permissions
163 .iter()
164 .copied()
165 .find(|permission| permission.resource.name == resource && permission.accepts(value))
166 }
167
168 /// The resource named `name`, from the registry.
169 pub fn resource(&self, name: &str) -> Option<&'static crate::permissions::ResourceInfo> {
170 self.permissions
171 .iter()
172 .map(|permission| permission.resource)
173 .find(|resource| resource.name == name)
174 }
175}
176
177#[derive(Debug)]
178#[non_exhaustive]
179pub struct OperationInfo {
180 /// The response is a typed sequence, not a buffered output value.
181 pub server_stream: bool,
182 /// `internal` in the model; caller authorization remains application policy.
183 pub internal: bool,
184 /// The operation's shape id, `namespace#Name`.
185 pub id: &'static str,
186 pub name: &'static str,
187 /// The resource that binds the operation, if one does.
188 pub resource: Option<&'static str>,
189 pub method: &'static str,
190 pub path: &'static [Segment],
191 /// Literal query parameters required by the modeled URI.
192 pub literal_query: &'static [(&'static str, Option<&'static str>)],
193 /// The status of a successful response.
194 pub status: u16,
195 pub input: &'static [MemberInfo],
196 pub output: &'static [MemberInfo],
197 /// The errors the operation can return, by shape name.
198 pub errors: &'static [&'static str],
199 pub readonly: bool,
200 pub idempotent: bool,
201 pub idempotency_token: Option<&'static str>,
202 /// The model's own traits on the operation: shape id and JSON value.
203 pub traits: &'static [(&'static str, &'static str)],
204 /// Who calls a sender-signed operation (`@sender`, decision 81), a
205 /// third party that signs each request; `None` for an operation the
206 /// service's clients call. Generated as `.with_sender("Stripe")`.
207 pub sender: Option<&'static str>,
208}
209
210impl OperationInfo {
211 pub const fn with_server_stream(mut self) -> Self {
212 self.server_stream = true;
213 self
214 }
215 /// The same operation, called and signed by `sender` (decision 81).
216 pub const fn with_sender(mut self, sender: &'static str) -> Self {
217 self.sender = Some(sender);
218 self
219 }
220
221 /// A trait's JSON value, as written in the model. It is parsed on each
222 /// call: a handler reads its traits once, in `Handler::prepare`.
223 pub fn trait_value(&self, id: &str) -> Option<Value> {
224 trait_value(self.traits, id)
225 }
226
227 /// A trait's value as `T`: `Ok(None)` when the operation does not have
228 /// it, an error when its value is not a `T`.
229 pub fn trait_as<T: DeserializeOwned>(&self, id: &str) -> serde_json::Result<Option<T>> {
230 self.traits
231 .iter()
232 .find(|(trait_id, _)| *trait_id == id)
233 .map(|(_, json)| serde_json::from_str(json))
234 .transpose()
235 }
236
237 pub fn has_trait(&self, id: &str) -> bool {
238 self.traits.iter().any(|(trait_id, _)| *trait_id == id)
239 }
240
241 pub fn declares(&self, error: &str) -> bool {
242 self.errors.contains(&error)
243 }
244}
245
246#[derive(Debug, Clone, Copy, PartialEq, Eq)]
247#[non_exhaustive]
248pub enum Segment {
249 GreedyLabel(&'static str),
250 Literal(&'static str),
251 Label(&'static str),
252}
253
254/// A member of an input, output or error structure, and where it travels.
255#[derive(Debug, Clone, Copy)]
256#[non_exhaustive]
257pub struct MemberInfo {
258 pub name: &'static str,
259 pub location: Location,
260 pub scalar: Scalar,
261 /// Static, recursive logging policy resolved from the model.
262 pub redaction: &'static Redaction,
263 /// The model's own traits on the member: shape id and JSON value.
264 pub traits: &'static [(&'static str, &'static str)],
265}
266
267/// Logging metadata, including recursive shapes. References are static so
268/// recursive models need no per-request schema construction.
269pub enum Redaction {
270 Public,
271 Sensitive,
272 Structure(&'static [(&'static str, &'static Redaction)]),
273 List(&'static Redaction),
274 Map(&'static Redaction),
275}
276
277impl std::fmt::Debug for Redaction {
278 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279 // Following static references here would recurse forever for a
280 // recursive model, even though redacting a finite value terminates.
281 f.write_str(match self {
282 Self::Public => "Public",
283 Self::Sensitive => "Sensitive",
284 Self::Structure(_) => "Structure(..)",
285 Self::List(_) => "List(..)",
286 Self::Map(_) => "Map(..)",
287 })
288 }
289}
290
291impl Redaction {
292 /// Removes sensitive content in place. False means the whole value is
293 /// sensitive and its parent must omit it.
294 pub fn redact(&self, value: &mut Value) -> bool {
295 match self {
296 Self::Sensitive => return false,
297 Self::Public => {}
298 Self::Structure(members) => {
299 if let Value::Object(object) = value {
300 object.retain(|name, value| {
301 members
302 .iter()
303 .find(|(member, _)| name == member)
304 .is_some_and(|(_, policy)| policy.redact(value))
305 });
306 }
307 }
308 Self::List(policy) => {
309 if let Value::Array(items) = value {
310 for item in items {
311 if !policy.redact(item) {
312 *item = Value::Null;
313 }
314 }
315 }
316 }
317 Self::Map(policy) => {
318 if let Value::Object(object) = value {
319 object.retain(|_, value| policy.redact(value));
320 }
321 }
322 }
323 true
324 }
325}
326
327impl MemberInfo {
328 /// A trait's JSON value, as written in the model.
329 pub fn trait_value(&self, id: &str) -> Option<Value> {
330 trait_value(self.traits, id)
331 }
332
333 pub fn has_trait(&self, id: &str) -> bool {
334 self.traits.iter().any(|(trait_id, _)| *trait_id == id)
335 }
336}
337
338fn trait_value(traits: &[(&str, &str)], id: &str) -> Option<Value> {
339 traits
340 .iter()
341 .find(|(trait_id, _)| *trait_id == id)
342 .and_then(|(_, json)| serde_json::from_str(json).ok())
343}
344
345#[derive(Debug, Clone, Copy, PartialEq, Eq)]
346#[non_exhaustive]
347pub enum Location {
348 Label,
349 Query(&'static str),
350 Header(&'static str),
351 Body,
352 /// The whole HTTP body, raw (`@httpPayload` on a blob), with the media
353 /// type a sender gives it. A structure with a payload member has no
354 /// other body members.
355 Payload(&'static str),
356 /// The whole HTTP body as UTF-8 text (`@httpPayload` on a string or enum).
357 TextPayload(&'static str),
358 /// The whole HTTP body as one JSON value (`@httpPayload` on a structure,
359 /// union or document). Model serialization decides omission; an explicitly
360 /// serialized null is the JSON value `null`, which reads back as the
361 /// member's null, as it would in a JSON body.
362 DocumentPayload(&'static str),
363}
364
365impl Location {
366 /// The payload member of `members`, if it has one, and its media type.
367 pub fn payload(members: &[MemberInfo]) -> Option<(&MemberInfo, &'static str)> {
368 members.iter().find_map(|member| match member.location {
369 Self::Payload(media_type)
370 | Self::TextPayload(media_type)
371 | Self::DocumentPayload(media_type) => Some((member, media_type)),
372 _ => None,
373 })
374 }
375}
376
377/// How a bound member's text reads as JSON. Body members are `Json`.
378#[derive(Debug, Clone, Copy, PartialEq, Eq)]
379#[non_exhaustive]
380pub enum Scalar {
381 BigInteger,
382 BigDecimal,
383 String,
384 Integer,
385 Float,
386 Boolean,
387 DateTime,
388 EpochSeconds,
389 HttpDate,
390 /// A timestamp whose bound text uses a different format than its JSON
391 /// value: a REST protocol's HTTP-date header for an epoch-seconds member.
392 Timestamp {
393 text: TimestampFormat,
394 json: TimestampFormat,
395 },
396 /// A `@mediaType` string bound to a header: base64 of its UTF-8 text.
397 Base64,
398 List(&'static Scalar),
399 Json,
400}
401
402impl Scalar {
403 /// HTTP-date text, whose own commas a header list does not quote.
404 pub fn http_date(self) -> bool {
405 matches!(
406 self,
407 Self::HttpDate
408 | Self::Timestamp {
409 text: TimestampFormat::HttpDate,
410 ..
411 }
412 )
413 }
414}
415
416/// A timestamp's wire format.
417#[derive(Debug, Clone, Copy, PartialEq, Eq)]
418pub enum TimestampFormat {
419 DateTime,
420 EpochSeconds,
421 HttpDate,
422}
423
424/// The input members of a `@paginated` operation that say where a listing
425/// resumes and how much of it to return.
426#[derive(Debug, Clone, Copy, PartialEq, Eq)]
427pub struct Pagination {
428 pub input_token: PaginationMember,
429 pub page_size: Option<PaginationMember>,
430 /// Whether the input token is a map rather than a string (the IR allows
431 /// either): a server extension that seals string tokens refuses such an
432 /// operation instead of reading its token as absent.
433 pub input_token_map: bool,
434 /// The largest length the model allows the input token member (`@length`
435 /// max, in characters), if it bounds one: a server extension that issues
436 /// tokens checks at build that the longest it can issue fits.
437 pub input_token_max_length: Option<u64>,
438}
439
440/// A top-level input member, named as the model names it (a validation
441/// path) and as its key in the input's JSON form ([`Input::to_json`]): a
442/// pagination member, or an operation's idempotency token
443/// ([`Operation::IDEMPOTENCY_TOKEN`]).
444#[derive(Debug, Clone, Copy, PartialEq, Eq)]
445pub struct PaginationMember {
446 pub name: &'static str,
447}
448
449#[derive(Debug)]
450#[non_exhaustive]
451pub struct ErrorInfo {
452 pub name: &'static str,
453 pub status: u16,
454 pub fault: Fault,
455 /// The model explicitly marks this error as retryable.
456 pub retryable: bool,
457 pub throttling: bool,
458 pub members: &'static [MemberInfo],
459 #[doc(hidden)]
460 pub retryable_reasons: Option<RetryableReasons>,
461}
462
463#[doc(hidden)]
464#[derive(Debug)]
465pub struct RetryableReasons {
466 pub member: Option<&'static str>,
467 pub values: &'static [&'static str],
468 pub throttling: bool,
469}
470
471impl ErrorInfo {
472 #[doc(hidden)]
473 pub const fn with_retryable_reasons(
474 mut self,
475 member: Option<&'static str>,
476 values: &'static [&'static str],
477 throttling: bool,
478 ) -> Self {
479 self.retryable_reasons = Some(RetryableReasons {
480 member,
481 values,
482 throttling,
483 });
484 self
485 }
486}
487
488#[derive(Debug, Clone, Copy, PartialEq, Eq)]
489#[non_exhaustive]
490pub enum Fault {
491 /// The caller's mistake: a 4xx.
492 Client,
493 /// The service's failure: a 5xx.
494 Server,
495}
496
497/// No value: the input of an operation that takes none, or a union member
498/// that carries nothing. `{}` on the wire.
499#[derive(
500 Debug, Clone, Copy, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize,
501)]
502#[serde(deny_unknown_fields)]
503pub struct Unit {}
504
505impl Validate for Unit {
506 fn validate(&self, _: &mut crate::validate::Validator) {}
507}
508
509/// A validated input, seen by handlers without knowing its type.
510pub trait Input: Any + Send + Sync {
511 fn to_json(&self) -> Value;
512 fn as_any(&self) -> &dyn Any;
513 fn into_any(self: Box<Self>) -> Box<dyn Any + Send>;
514}
515
516impl<T: Serialize + Any + Send + Sync> Input for T {
517 fn to_json(&self) -> Value {
518 serde_json::to_value(self).unwrap_or(Value::Null)
519 }
520
521 fn as_any(&self) -> &dyn Any {
522 self
523 }
524
525 fn into_any(self: Box<Self>) -> Box<dyn Any + Send> {
526 self
527 }
528}
529
530/// Reads an output of type `O` from its JSON form: [`Operation::OUTPUT_FROM_JSON`].
531pub type OutputFromJson<O> = fn(Value) -> serde_json::Result<O>;
532
533/// An operation's output, seen by handlers without knowing its type.
534pub trait Output: Any + Send + Sync {
535 fn to_json(&self) -> Value;
536 /// Stream serialization to a bounded sink. Custom erased outputs can
537 /// override this to avoid the default intermediate JSON value.
538 fn write_json_to(&self, out: &mut dyn std::io::Write) -> serde_json::Result<()> {
539 serde_json::to_writer(out, &self.to_json())
540 }
541 /// Serializes into `out`. Every serializable output writes straight to
542 /// bytes; this default, for other implementors, goes through `to_json`.
543 fn write_json(&self, out: &mut Vec<u8>) -> serde_json::Result<()> {
544 serde_json::to_writer(out, &self.to_json())
545 }
546 /// Serializes into `out` without the members `members` binds to
547 /// headers, returning those as (header, text); with a payload member,
548 /// `out` gets that member's bytes, raw. The default goes through
549 /// `to_json`, as `write_json`'s does.
550 fn write_json_split(
551 &self,
552 members: &[MemberInfo],
553 out: &mut Vec<u8>,
554 ) -> serde_json::Result<Vec<(&'static str, String)>> {
555 crate::split::write(&self.to_json(), members, out)
556 }
557 fn as_any(&self) -> &dyn Any;
558}
559
560impl<T: Serialize + Any + Send + Sync> Output for T {
561 fn write_json_to(&self, out: &mut dyn std::io::Write) -> serde_json::Result<()> {
562 serde_json::to_writer(out, self)
563 }
564 fn to_json(&self) -> Value {
565 serde_json::to_value(self).unwrap_or(Value::Null)
566 }
567
568 fn write_json(&self, out: &mut Vec<u8>) -> serde_json::Result<()> {
569 serde_json::to_writer(out, self)
570 }
571
572 fn write_json_split(
573 &self,
574 members: &[MemberInfo],
575 out: &mut Vec<u8>,
576 ) -> serde_json::Result<Vec<(&'static str, String)>> {
577 crate::split::write(self, members, out)
578 }
579
580 fn as_any(&self) -> &dyn Any {
581 self
582 }
583}
584
585/// Effective authentication options in modeled priority order.
586#[derive(Debug, Clone, Copy, PartialEq, Eq)]
587#[non_exhaustive]
588pub enum AuthScheme {
589 Bearer,
590}