ag_ui/patch.rs
1//! JSON Patch operations, as defined by [RFC 6902].
2//!
3//! `STATE_DELTA` and `ACTIVITY_DELTA` carry a patch document: an array of these
4//! operations, applied in order to the previous snapshot.
5//!
6//! [RFC 6902]: https://datatracker.ietf.org/doc/html/rfc6902
7
8use std::collections::BTreeMap;
9
10use serde::{Deserialize, Serialize};
11use serde_json::Value;
12
13/// A JSON Patch document: an ordered list of operations.
14pub type JsonPatch = Vec<PatchOperation>;
15
16/// A single [RFC 6902] operation.
17///
18/// The serde representation is the RFC wire format exactly: an object with an
19/// `op` discriminator, a `path` JSON Pointer, and — depending on the operation
20/// — a `value` or a `from` pointer. Additional members are retained in `extra`:
21/// RFC 6902 operations are open objects, so proxies and event observers must
22/// preserve these members even though applying the patch ignores them.
23///
24/// # Why `value` has a default
25///
26/// Upstream types both patch fields as `z.array(z.any())` / `List[Any]` and
27/// validates nothing, so a producer that drops `value` still parses there. The
28/// case is not hypothetical: `JSON.stringify({op: "add", path: "/x", value:
29/// undefined})` yields `{"op":"add","path":"/x"}`, which is what a JavaScript
30/// producer emits whenever the new state holds `undefined` at that key. Making
31/// `value` required would turn that into a deserialization failure for the whole
32/// `STATE_DELTA` event — and in an SSE stream a failed event is usually a failed
33/// run. An omitted `value` therefore reads as JSON `null`, which is how the
34/// JavaScript patch libraries apply it, and re-serializes explicitly as `null`.
35///
36/// Everything else about the operation stays strictly typed: an unrecognized
37/// `op` is still rejected, because the six RFC operations are the whole
38/// vocabulary and a seventh is a producer bug worth surfacing rather than
39/// carrying silently to an applier that cannot execute it.
40///
41/// ```
42/// # use ag_ui::PatchOperation;
43/// let op = PatchOperation::Replace {
44/// path: "/counter".into(),
45/// value: serde_json::json!(2),
46/// extra: Default::default(),
47/// };
48/// assert_eq!(
49/// serde_json::to_string(&op).unwrap(),
50/// r#"{"op":"replace","path":"/counter","value":2}"#
51/// );
52/// ```
53///
54/// [RFC 6902]: https://datatracker.ietf.org/doc/html/rfc6902
55#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
56#[serde(tag = "op", rename_all = "lowercase")]
57#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
58#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
59pub enum PatchOperation {
60 /// Inserts `value` at `path`, shifting array elements right when `path`
61 /// ends in an array index or `-`.
62 Add {
63 /// JSON Pointer to the location to add.
64 path: String,
65 /// The value to insert. An omitted `value` reads as `null`; see the
66 /// type-level docs.
67 #[serde(default)]
68 value: Value,
69 /// Additional members, preserved on the wire and ignored by patch application.
70 #[serde(flatten)]
71 extra: BTreeMap<String, Value>,
72 },
73
74 /// Removes the value at `path`.
75 Remove {
76 /// JSON Pointer to the location to remove.
77 path: String,
78 /// Additional members, preserved on the wire and ignored by patch application.
79 #[serde(flatten)]
80 extra: BTreeMap<String, Value>,
81 },
82
83 /// Replaces the value at `path`, which must already exist.
84 Replace {
85 /// JSON Pointer to the location to overwrite.
86 path: String,
87 /// The replacement value. An omitted `value` reads as `null`.
88 #[serde(default)]
89 value: Value,
90 /// Additional members, preserved on the wire and ignored by patch application.
91 #[serde(flatten)]
92 extra: BTreeMap<String, Value>,
93 },
94
95 /// Moves the value at `from` to `path`.
96 Move {
97 /// JSON Pointer to the source location.
98 from: String,
99 /// JSON Pointer to the destination.
100 path: String,
101 /// Additional members, preserved on the wire and ignored by patch application.
102 #[serde(flatten)]
103 extra: BTreeMap<String, Value>,
104 },
105
106 /// Copies the value at `from` to `path`.
107 Copy {
108 /// JSON Pointer to the source location.
109 from: String,
110 /// JSON Pointer to the destination.
111 path: String,
112 /// Additional members, preserved on the wire and ignored by patch application.
113 #[serde(flatten)]
114 extra: BTreeMap<String, Value>,
115 },
116
117 /// Asserts that the value at `path` equals `value`; a failed test aborts
118 /// the whole patch.
119 Test {
120 /// JSON Pointer to the location to test.
121 path: String,
122 /// The value the location is expected to hold. An omitted `value` reads
123 /// as `null`.
124 #[serde(default)]
125 value: Value,
126 /// Additional members, preserved on the wire and ignored by patch application.
127 #[serde(flatten)]
128 extra: BTreeMap<String, Value>,
129 },
130}
131
132impl PatchOperation {
133 /// Builds an [`Add`](PatchOperation::Add) operation.
134 pub fn add(path: impl Into<String>, value: impl Into<Value>) -> Self {
135 Self::Add {
136 path: path.into(),
137 value: value.into(),
138 extra: BTreeMap::new(),
139 }
140 }
141
142 /// Builds a [`Remove`](PatchOperation::Remove) operation.
143 pub fn remove(path: impl Into<String>) -> Self {
144 Self::Remove {
145 path: path.into(),
146 extra: BTreeMap::new(),
147 }
148 }
149
150 /// Builds a [`Replace`](PatchOperation::Replace) operation.
151 pub fn replace(path: impl Into<String>, value: impl Into<Value>) -> Self {
152 Self::Replace {
153 path: path.into(),
154 value: value.into(),
155 extra: BTreeMap::new(),
156 }
157 }
158
159 /// Builds a [`Move`](PatchOperation::Move) operation.
160 pub fn mv(from: impl Into<String>, path: impl Into<String>) -> Self {
161 Self::Move {
162 from: from.into(),
163 path: path.into(),
164 extra: BTreeMap::new(),
165 }
166 }
167
168 /// Builds a [`Copy`](PatchOperation::Copy) operation.
169 pub fn copy(from: impl Into<String>, path: impl Into<String>) -> Self {
170 Self::Copy {
171 from: from.into(),
172 path: path.into(),
173 extra: BTreeMap::new(),
174 }
175 }
176
177 /// Builds a [`Test`](PatchOperation::Test) operation.
178 pub fn test(path: impl Into<String>, value: impl Into<Value>) -> Self {
179 Self::Test {
180 path: path.into(),
181 value: value.into(),
182 extra: BTreeMap::new(),
183 }
184 }
185
186 /// Additional wire members. Patch execution does not interpret them.
187 pub const fn extra(&self) -> &BTreeMap<String, Value> {
188 match self {
189 Self::Add { extra, .. }
190 | Self::Remove { extra, .. }
191 | Self::Replace { extra, .. }
192 | Self::Move { extra, .. }
193 | Self::Copy { extra, .. }
194 | Self::Test { extra, .. } => extra,
195 }
196 }
197
198 /// The `op` string as it appears on the wire.
199 pub const fn op(&self) -> &'static str {
200 match self {
201 Self::Add { .. } => "add",
202 Self::Remove { .. } => "remove",
203 Self::Replace { .. } => "replace",
204 Self::Move { .. } => "move",
205 Self::Copy { .. } => "copy",
206 Self::Test { .. } => "test",
207 }
208 }
209
210 /// The JSON Pointer this operation targets.
211 pub fn path(&self) -> &str {
212 match self {
213 Self::Add { path, .. }
214 | Self::Remove { path, .. }
215 | Self::Replace { path, .. }
216 | Self::Move { path, .. }
217 | Self::Copy { path, .. }
218 | Self::Test { path, .. } => path,
219 }
220 }
221
222 /// The source pointer of a `move` or `copy`, or `None` for other operations.
223 pub fn from(&self) -> Option<&str> {
224 match self {
225 Self::Move { from, .. } | Self::Copy { from, .. } => Some(from),
226 _ => None,
227 }
228 }
229
230 /// The payload of an `add`, `replace` or `test`, or `None` for other
231 /// operations.
232 pub const fn value(&self) -> Option<&Value> {
233 match self {
234 Self::Add { value, .. } | Self::Replace { value, .. } | Self::Test { value, .. } => {
235 Some(value)
236 }
237 _ => None,
238 }
239 }
240}