fraiseql_core/runtime/mutation_result.rs
1//! Mutation response parser for `app.mutation_response` composite rows.
2//!
3//! Parses a typed, column-per-concern row into [`MutationOutcome`], which the
4//! executor uses to build the GraphQL response. The row shape maps 1:1 to the
5//! `app.mutation_response` PostgreSQL composite type — see
6//! `docs/architecture/mutation-response.md` for the DDL and semantics table.
7
8use std::collections::HashMap;
9
10use serde::Deserialize;
11use serde_json::Value as JsonValue;
12use uuid::Uuid;
13
14use super::cascade::MutationErrorClass;
15use crate::error::{FraiseQLError, Result};
16
17/// Minimum legal HTTP status code (informational range start).
18const HTTP_STATUS_MIN: i16 = 100;
19/// Maximum legal HTTP status code (end of 5xx range).
20const HTTP_STATUS_MAX: i16 = 599;
21
22/// Outcome of parsing a single `mutation_response` row.
23#[derive(Debug, Clone)]
24#[non_exhaustive]
25pub enum MutationOutcome {
26 /// The mutation succeeded; the result entity is available.
27 Success {
28 /// The entity JSONB returned by the function.
29 entity: JsonValue,
30 /// GraphQL type name for the entity (from the `entity_type` column).
31 entity_type: Option<String>,
32 /// UUID string of the mutated entity (from the `entity_id` column).
33 ///
34 /// Present for UPDATE and DELETE mutations. Used for entity-aware cache
35 /// invalidation: only cache entries containing this UUID are evicted,
36 /// leaving unrelated entries warm.
37 entity_id: Option<String>,
38 /// Cascade operations associated with this mutation.
39 cascade: Option<JsonValue>,
40 },
41 /// The mutation failed; error metadata is available.
42 Error {
43 /// Typed classification of the failure (mirrors `app.mutation_error_class`).
44 error_class: MutationErrorClass,
45 /// Human-readable error message.
46 message: String,
47 /// Structured metadata JSONB containing error-type field values.
48 metadata: JsonValue,
49 },
50}
51
52/// Typed `app.mutation_response` row.
53///
54/// Field types map 1:1 to the PostgreSQL composite columns. See
55/// `docs/architecture/mutation-response.md`.
56#[derive(Debug, Clone, Deserialize)]
57#[non_exhaustive]
58pub struct MutationResponse {
59 /// Terminal outcome. `true` means the operation completed (including noops).
60 pub succeeded: bool,
61 /// Did the database actually change? Independent of `succeeded`.
62 pub state_changed: bool,
63 /// `NULL` iff `succeeded`. Drives the cascade error code 1:1.
64 #[serde(default)]
65 pub error_class: Option<MutationErrorClass>,
66 /// Human-readable subtype (e.g. `"duplicate_email"`); not parsed.
67 #[serde(default)]
68 pub status_detail: Option<String>,
69 /// HTTP status, first-class. Validated to 100..=599 on ingest.
70 #[serde(default)]
71 pub http_status: Option<i16>,
72 /// Human-readable summary safe to show to end users.
73 #[serde(default)]
74 pub message: Option<String>,
75 /// Primary key of the affected entity. Present for updates/deletes.
76 #[serde(default)]
77 pub entity_id: Option<Uuid>,
78 /// GraphQL type name (e.g. `"User"`). Used for cache invalidation.
79 #[serde(default)]
80 pub entity_type: Option<String>,
81 /// Full entity payload. Populated even for noops.
82 #[serde(default)]
83 pub entity: JsonValue,
84 /// GraphQL field names that changed. Empty on noop.
85 #[serde(default)]
86 pub updated_fields: Vec<String>,
87 /// Cascade operations (see the graphql-cascade specification).
88 #[serde(default)]
89 pub cascade: JsonValue,
90 /// Structured error payload only (field / constraint / severity).
91 #[serde(default)]
92 pub error_detail: JsonValue,
93 /// Observability only (trace IDs, timings, audit extras).
94 #[serde(default)]
95 pub metadata: JsonValue,
96}
97
98/// Parse a `mutation_response` row into a [`MutationOutcome`].
99///
100/// Deserializes typed columns directly — no string parsing. Rejects the illegal
101/// combination `succeeded=false AND state_changed=true` (the builder refuses to
102/// construct such a row; defense in depth here so a hand-written SQL path
103/// cannot slip a partial-failure row past the parser).
104///
105/// `error_detail` (not `metadata`) feeds the executor's error-field projection
106/// so downstream consumers remain untouched: `metadata` carries observability
107/// only and must not be used as an error-data carrier.
108///
109/// # Errors
110///
111/// Returns [`FraiseQLError::Validation`] if:
112/// - the row fails to deserialize into [`MutationResponse`];
113/// - `http_status` is outside `100..=599`;
114/// - `succeeded=false` with `state_changed=true` (illegal per the semantics table);
115/// - `succeeded=false` with `error_class` missing.
116pub fn parse_mutation_row<S: ::std::hash::BuildHasher>(
117 row: &HashMap<String, JsonValue, S>,
118) -> Result<MutationOutcome> {
119 let obj: serde_json::Map<String, JsonValue> =
120 row.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
121 let parsed: MutationResponse =
122 serde_json::from_value(JsonValue::Object(obj)).map_err(|e| FraiseQLError::Validation {
123 message: format!("mutation_response row failed to deserialize: {e}"),
124 path: None,
125 })?;
126 to_outcome(parsed)
127}
128
129/// Lower a deserialized [`MutationResponse`] to the shared outcome seam.
130fn to_outcome(row: MutationResponse) -> Result<MutationOutcome> {
131 if let Some(status) = row.http_status {
132 if !(HTTP_STATUS_MIN..=HTTP_STATUS_MAX).contains(&status) {
133 return Err(FraiseQLError::Validation {
134 message: format!(
135 "mutation_response 'http_status' out of range: {status} \
136 (expected {HTTP_STATUS_MIN}..={HTTP_STATUS_MAX})"
137 ),
138 path: None,
139 });
140 }
141 }
142
143 if row.succeeded {
144 if row.error_class.is_some() {
145 return Err(FraiseQLError::Validation {
146 message: "mutation_response: succeeded=true but error_class is set".to_string(),
147 path: None,
148 });
149 }
150 Ok(MutationOutcome::Success {
151 entity: row.entity,
152 entity_type: row.entity_type,
153 entity_id: row.entity_id.map(|u| u.to_string()),
154 cascade: filter_null(row.cascade),
155 })
156 } else {
157 if row.state_changed {
158 return Err(FraiseQLError::Validation {
159 message: "mutation_response: succeeded=false with state_changed=true is illegal \
160 (partial-failure rows are builder-rejected)"
161 .to_string(),
162 path: None,
163 });
164 }
165 let Some(class) = row.error_class else {
166 return Err(FraiseQLError::Validation {
167 message: "mutation_response: succeeded=false requires error_class".to_string(),
168 path: None,
169 });
170 };
171 Ok(MutationOutcome::Error {
172 error_class: class,
173 message: row.message.unwrap_or_default(),
174 metadata: row.error_detail,
175 })
176 }
177}
178
179fn filter_null(v: JsonValue) -> Option<JsonValue> {
180 if v.is_null() { None } else { Some(v) }
181}