1mod v2;
4
5use serde::Deserialize;
6
7use super::{CollabOpId, CollaborationOperationEnvelope};
8
9#[derive(Debug, thiserror::Error)]
10pub enum CollaborationCodecError {
11 #[error("collaboration operation encoding failed: {0}")]
12 Encoding(String),
13 #[error("collaboration operation decoding failed: {0}")]
14 Decoding(String),
15 #[error("unsupported collaboration operation version {0}")]
16 UnsupportedVersion(u16),
17 #[error("invalid collaboration operation: {0}")]
18 Invalid(String),
19}
20
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct DecodedCollaborationOperation {
23 pub operation_id: CollabOpId,
24 pub operation: CollaborationOperationEnvelope,
25}
26
27#[derive(Deserialize)]
28struct VersionProbe {
29 schema_version: u16,
30}
31
32pub(crate) fn encode(
33 operation: &CollaborationOperationEnvelope,
34) -> Result<Vec<u8>, CollaborationCodecError> {
35 operation.validate()?;
36 v2::encode(operation)
37}
38
39pub(crate) fn decode(
40 bytes: &[u8],
41) -> Result<DecodedCollaborationOperation, CollaborationCodecError> {
42 let probe: VersionProbe = rmp_serde::from_slice(bytes)
43 .map_err(|error| CollaborationCodecError::Decoding(error.to_string()))?;
44 if probe.schema_version != super::COLLABORATION_OPERATION_SCHEMA_VERSION {
45 return Err(CollaborationCodecError::UnsupportedVersion(
46 probe.schema_version,
47 ));
48 }
49 let operation = v2::decode(bytes)?;
50 operation.validate()?;
51 operation.canonical_body.store(bytes.to_vec());
54 Ok(DecodedCollaborationOperation {
55 operation_id: CollabOpId::for_bytes(bytes),
56 operation,
57 })
58}
59
60#[cfg(test)]
61mod tests {
62 use serde::Serialize;
63
64 use super::*;
65 use crate::object::{
66 AnnotationKind, Attribution, ChangeId, CollaborationAnchor, CollaborationAnchorStatus,
67 CollaborationIdempotencyKey, CollaborationOperationBodyV1, CollaborationResolution,
68 ContentHash, DiscussionRecordId, DiscussionTurnV1, LegacyDiscussionId,
69 LegacyDiscussionResolutionV1, LegacySourceLocator, Principal, StateAttachmentId, StateId,
70 VisibilityTier,
71 };
72
73 #[derive(Serialize)]
74 struct Unsupported<'a> {
75 schema_version: u16,
76 body: &'a [u8],
77 }
78
79 #[test]
80 fn unsupported_version_is_rejected_before_body_decode() {
81 let bytes = rmp_serde::to_vec_named(&Unsupported {
82 schema_version: 3,
83 body: &[0xc1],
84 })
85 .unwrap();
86 assert!(matches!(
87 decode(&bytes),
88 Err(CollaborationCodecError::UnsupportedVersion(3))
89 ));
90 }
91
92 fn golden_operation(name: &str, body: CollaborationOperationBodyV1) -> (String, Vec<u8>) {
93 let root = matches!(
94 body,
95 CollaborationOperationBodyV1::Open { .. }
96 | CollaborationOperationBodyV1::LegacyImported { .. }
97 );
98 let operation = CollaborationOperationEnvelope::new(
99 "disc-018f47ea-4a54-7c89-b012-3456789abcde"
100 .parse::<DiscussionRecordId>()
101 .unwrap(),
102 if root {
103 Vec::new()
104 } else if matches!(body, CollaborationOperationBodyV1::ResolveConflict { .. }) {
105 vec![
106 CollabOpId::from_bytes([7; 32]),
107 CollabOpId::from_bytes([8; 32]),
108 ]
109 } else {
110 vec![CollabOpId::from_bytes([7; 32])]
111 },
112 CollaborationIdempotencyKey::new("k").unwrap(),
113 Attribution::human(Principal::new("A", "a@b")),
114 0,
115 body,
116 )
117 .unwrap();
118 (name.to_string(), operation.encode().unwrap())
119 }
120
121 fn golden_vectors() -> Vec<(String, Vec<u8>)> {
122 let state = StateId::from_bytes([1; 32]);
123 let change = ChangeId::from_bytes([2; 16]);
124 let turn = || DiscussionTurnV1::new("x").unwrap();
125 let open = |anchor| CollaborationOperationBodyV1::Open {
126 tags: Vec::new(),
127 blocking: false,
128 title: "t".to_string(),
129 anchor,
130 visibility: VisibilityTier::default(),
131 turn: turn(),
132 thread_ref: None,
133 };
134 let locator = LegacySourceLocator::new(
135 state,
136 StateAttachmentId::from_hash(ContentHash::from_bytes([3; 32])),
137 ContentHash::from_bytes([4; 32]),
138 );
139 let legacy = |resolution| CollaborationOperationBodyV1::LegacyImported {
140 source: locator.clone(),
141 legacy_discussion_id: LegacyDiscussionId::new("l").unwrap(),
142 aliases: vec![LegacySourceLocator::new(
143 StateId::from_bytes([5; 32]),
144 StateAttachmentId::from_hash(ContentHash::from_bytes([6; 32])),
145 ContentHash::from_bytes([7; 32]),
146 )],
147 title: "t".to_string(),
148 anchor: CollaborationAnchor::Symbol {
149 state_id: state,
150 path: "p".to_string(),
151 symbol: "s".to_string(),
152 },
153 visibility: VisibilityTier::default(),
154 turns: vec![turn()],
155 resolution,
156 };
157 vec![
158 golden_operation("open_repository", open(CollaborationAnchor::Repository)),
159 golden_operation(
160 "open_state",
161 open(CollaborationAnchor::State { state_id: state }),
162 ),
163 golden_operation(
164 "open_change",
165 open(CollaborationAnchor::Change { change_id: change }),
166 ),
167 golden_operation(
168 "open_path",
169 open(CollaborationAnchor::Path {
170 state_id: state,
171 path: "p".to_string(),
172 }),
173 ),
174 golden_operation(
175 "open_symbol",
176 open(CollaborationAnchor::Symbol {
177 state_id: state,
178 path: "p".to_string(),
179 symbol: "s".to_string(),
180 }),
181 ),
182 golden_operation(
183 "append_turn",
184 CollaborationOperationBodyV1::AppendTurn { turn: turn() },
185 ),
186 golden_operation(
187 "rebind_anchor",
188 CollaborationOperationBodyV1::RebindAnchor {
189 anchor: CollaborationAnchor::Symbol {
190 state_id: state,
191 path: "p".to_string(),
192 symbol: "s2".to_string(),
193 },
194 status: CollaborationAnchorStatus::Moved,
195 body_changed_since_open: true,
196 },
197 ),
198 golden_operation(
199 "resolve_state",
200 CollaborationOperationBodyV1::Resolve {
201 resolution: CollaborationResolution::AddressedByState { state_id: state },
202 },
203 ),
204 golden_operation(
205 "resolve_change",
206 CollaborationOperationBodyV1::Resolve {
207 resolution: CollaborationResolution::AddressedByChange { change_id: change },
208 },
209 ),
210 golden_operation(
211 "resolve_dismissed",
212 CollaborationOperationBodyV1::Resolve {
213 resolution: CollaborationResolution::Dismissed {
214 reason: "r".to_string(),
215 },
216 },
217 ),
218 golden_operation(
219 "resolve_annotation",
220 CollaborationOperationBodyV1::Resolve {
221 resolution: CollaborationResolution::Annotation {
222 annotation_id: "a".to_string(),
223 },
224 },
225 ),
226 golden_operation(
227 "resolve_into_annotation",
228 CollaborationOperationBodyV1::Resolve {
229 resolution: CollaborationResolution::IntoAnnotation {
230 annotation_kind: AnnotationKind::Rationale,
231 content: "why".to_string(),
232 tags: vec!["design".to_string()],
233 },
234 },
235 ),
236 golden_operation(
237 "reopen",
238 CollaborationOperationBodyV1::Reopen {
239 reason: "r".to_string(),
240 },
241 ),
242 golden_operation(
243 "resolve_conflict",
244 CollaborationOperationBodyV1::ResolveConflict {
245 competing: vec![
246 CollabOpId::from_bytes([7; 32]),
247 CollabOpId::from_bytes([8; 32]),
248 ],
249 selected: CollabOpId::from_bytes([7; 32]),
250 },
251 ),
252 golden_operation("legacy_open", legacy(LegacyDiscussionResolutionV1::Open)),
253 golden_operation(
254 "legacy_state",
255 legacy(LegacyDiscussionResolutionV1::AddressedByState { state_id: state }),
256 ),
257 golden_operation(
258 "legacy_dismissed",
259 legacy(LegacyDiscussionResolutionV1::Dismissed {
260 reason: "r".to_string(),
261 }),
262 ),
263 golden_operation(
264 "legacy_annotation",
265 legacy(LegacyDiscussionResolutionV1::Annotation {
266 annotation_id: "a".to_string(),
267 }),
268 ),
269 ]
270 }
271
272 #[test]
273 fn v2_full_variant_msgpack_vectors_are_frozen() {
274 let expected = [
275 (
276 "open_repository",
277 "69b3baebacb9d29c3d6c5cac73d6f14b2fe5231e061065249e808e2d92cddefe",
278 ),
279 (
280 "open_state",
281 "785cf6234fdfc4a01ff068a9b67a2c0d60172f59795c39c3c5b4e1037176a964",
282 ),
283 (
284 "open_change",
285 "e520779bc52b05e753a139bddafd25dcc8765182b865cd305691f85129b58c03",
286 ),
287 (
288 "open_path",
289 "1c814db69893d0ee71abe9d5a1d7d17724ff893fdf36bf90e9c40aa4beae9803",
290 ),
291 (
292 "open_symbol",
293 "9f43eb25d8c920d89a31c148fcd177e789e909eb7d3715fc2f899f85fa680197",
294 ),
295 (
296 "append_turn",
297 "777d8164d530fe27545685f23b283765a3b912f96a262dbad836faba498a9279",
298 ),
299 (
300 "rebind_anchor",
301 "e548683d8c7f20c8550627886f196a81b91e6ae52b8cdaadbfdd8944ceda1f8d",
302 ),
303 (
304 "resolve_state",
305 "7063d23abba098f608b13f2b807892bf7a5b61cb7b8487897ba84e95ff519dc9",
306 ),
307 (
308 "resolve_change",
309 "bcaa6bd96243624dcfe25942e92f59104d08291b2daf5dfd4c8d68f6fbd98472",
310 ),
311 (
312 "resolve_dismissed",
313 "4277710d09ae7043616335695b98fc89ce15583fd90437b28587c310492fe8f0",
314 ),
315 (
316 "resolve_annotation",
317 "c4eee97f235a3b534e423f20159ddba3077f9e0079ebc0697fa6c2426b394827",
318 ),
319 (
320 "resolve_into_annotation",
321 "e1470222f139ff1e6e06480996a7c27c2ef9d162eed2405ad3d838304d94d73e",
322 ),
323 (
324 "reopen",
325 "fa59e9c396a77ce07e57cb7b312f76438c3a002a1a4f053d1da13d9d10e03f7d",
326 ),
327 (
328 "resolve_conflict",
329 "d4c76d8ff078907d528613f7811151797d204f01216876623aecd675e9466606",
330 ),
331 (
332 "legacy_open",
333 "56e355d619b3db940a4cce75d525dac493d7e925c3e37cf85e1a789c6454713b",
334 ),
335 (
336 "legacy_state",
337 "44281502243244c40fc8be8b1fa452e3fd4491a455271462cb1236bac5b8136d",
338 ),
339 (
340 "legacy_dismissed",
341 "c9dd8f6850af3fce3797bb2ce853414dee066d29821756cbb8e2c6627ed56688",
342 ),
343 (
344 "legacy_annotation",
345 "8148359eab1c913a5a1b98debc9aa9f2a455cbbbc7b376b43b80b59c0b709331",
346 ),
347 ];
348 let actual = golden_vectors()
349 .into_iter()
350 .map(|(name, bytes)| {
351 let decoded = CollaborationOperationEnvelope::decode(&bytes).unwrap();
352 assert_eq!(decoded.operation_id, CollabOpId::for_bytes(&bytes));
353 assert_eq!(
354 decoded.operation.id().expect("id reuses decoded bytes"),
355 decoded.operation_id
356 );
357 assert_eq!(
358 decoded.operation.id().expect("cached id"),
359 CollabOpId::for_bytes(&decoded.operation.encode().expect("re-encode"))
360 );
361 (name, ContentHash::compute(&bytes).to_hex())
362 })
363 .collect::<Vec<_>>();
364 assert_eq!(actual.len(), expected.len());
365 for ((actual_name, actual_hash), (expected_name, expected_hash)) in
366 actual.iter().zip(expected)
367 {
368 assert_eq!(actual_name, expected_name);
369 assert_eq!(actual_hash, expected_hash);
370 }
371 }
372}