1use std::{
2 collections::{BTreeMap, BTreeSet},
3 io::{Read, Write},
4 path::Path,
5};
6
7use serde::{Deserialize, Deserializer, Serialize, de::Error as _};
8use serde_json::Value;
9use sha2::{Digest, Sha256};
10use unicode_casefold::UnicodeCaseFold;
11use unicode_normalization::UnicodeNormalization;
12
13use crate::{
14 FolderbaseError, ObjectId, Result, VersionId, migration::validate_managed_block_body_syntax,
15 traversal_policy::is_reserved_workspace_component,
16};
17
18pub const MAX_REORGANIZATION_RECORD_BYTES: usize = 8 * 1024 * 1024;
19pub const MAX_CANONICAL_JSON_INTEGER: u64 = 9_007_199_254_740_991;
20const MAX_REORGANIZATION_TEXT_CHARACTERS: usize = 2 * 1024 * 1024;
21const MAX_REORGANIZATION_PATH_CHARACTERS: usize = 4_096;
22const MAX_REORGANIZATION_SCOPE_ENTRIES: usize = 100_000;
23const MAX_REORGANIZATION_OPERATIONS: usize = 10_000;
24const MAX_REORGANIZATION_QUESTIONS: usize = 1_024;
25
26const REORGANIZATION_PROTOCOL_VERSION: &str = "0.3.0";
27const REORGANIZATION_DRAFT_PROFILE: &str = "folderbase-reorganization-draft-v1";
28const REORGANIZATION_PLAN_PROFILE: &str = "folderbase-reorganization-plan-v1";
29const ANALYSIS_SCOPE_DIGEST_DOMAIN: &[u8] = b"folderbase-reorganization-analysis-scope-v1\0";
30const PLAN_DIGEST_DOMAIN: &[u8] = b"folderbase-reorganization-plan-v1\0";
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
33pub enum PathProfile {
34 #[serde(rename = "portable-case-sensitive-v1")]
35 CaseSensitive,
36 #[serde(rename = "portable-case-fold-v1")]
37 CaseFold,
38}
39
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41#[serde(tag = "expectation", rename_all = "snake_case", deny_unknown_fields)]
42pub enum ScopeEntry {
43 Absent {
44 path: String,
45 },
46 Directory {
47 path: String,
48 },
49 File {
50 path: String,
51 sha256: String,
52 #[serde(deserialize_with = "deserialize_canonical_u64")]
53 byte_count: u64,
54 },
55 TrackedObject {
56 path: String,
57 object_id: ObjectId,
58 version_id: VersionId,
59 },
60}
61
62impl ScopeEntry {
63 fn path(&self) -> &str {
64 match self {
65 Self::Absent { path }
66 | Self::Directory { path }
67 | Self::File { path, .. }
68 | Self::TrackedObject { path, .. } => path,
69 }
70 }
71}
72
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
74#[serde(deny_unknown_fields)]
75pub struct NestedBoundary {
76 pub path: String,
77 pub manifest_sha256: String,
78}
79
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81#[serde(deny_unknown_fields)]
82pub struct AnalysisScope {
83 pub manifest_sha256: String,
84 pub ignore_policy: ScopeEntry,
85 pub structural_changes_policy: StructuralChangesPolicy,
86 pub nested_boundaries: Vec<NestedBoundary>,
87 pub operation_closure: Vec<ScopeEntry>,
88 pub declared_entries: Vec<ScopeEntry>,
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
92#[serde(rename_all = "snake_case")]
93pub enum StructuralChangesPolicy {
94 Suggest,
95 Approve,
96 Autonomous,
97}
98
99#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
100#[serde(
101 tag = "type",
102 content = "value",
103 rename_all = "snake_case",
104 deny_unknown_fields
105)]
106pub enum ConsequentialAnswer {
107 Text(String),
108 Boolean(bool),
109 SingleChoice(String),
110}
111
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
113#[serde(rename_all = "snake_case")]
114pub enum ConsequentialAnswerType {
115 Text,
116 Boolean,
117 SingleChoice,
118}
119
120#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
121#[serde(deny_unknown_fields)]
122pub struct ConsequentialQuestion {
123 pub id: String,
124 pub prompt: String,
125 pub answer_type: ConsequentialAnswerType,
126 pub required: bool,
127 #[serde(default, skip_serializing_if = "Vec::is_empty")]
128 pub options: Vec<String>,
129 #[serde(default, skip_serializing_if = "Option::is_none")]
130 pub answer: Option<ConsequentialAnswer>,
131}
132
133#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
134#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
135pub enum ReorganizationOperation {
136 CreateDirectory {
137 path: String,
138 },
139 CreateUtf8File {
140 path: String,
141 content: String,
142 },
143 ReplaceUtf8File {
144 path: String,
145 expected_sha256: String,
146 content: String,
147 },
148 UpdateManagedAgentBlock {
149 path: String,
150 adapter: String,
151 expected_sha256: String,
152 managed_block: String,
153 },
154 MoveFile {
155 source_path: String,
156 destination_path: String,
157 expected_sha256: String,
158 #[serde(deserialize_with = "deserialize_canonical_u64")]
159 expected_byte_count: u64,
160 },
161 MoveTrackedObject {
162 source_path: String,
163 destination_path: String,
164 object_id: ObjectId,
165 expected_version_id: VersionId,
166 },
167 MarkCanonical {
168 object_record_path: String,
169 object_id: ObjectId,
170 expected_version_id: VersionId,
171 expected_record_sha256: String,
172 },
173 MarkSuperseded {
174 object_record_path: String,
175 object_id: ObjectId,
176 expected_version_id: VersionId,
177 superseded_by: ObjectId,
178 expected_record_sha256: String,
179 },
180 ArchiveObject {
181 object_record_path: String,
182 object_id: ObjectId,
183 expected_version_id: VersionId,
184 expected_record_sha256: String,
185 },
186 AddRelationship {
187 object_record_path: String,
188 object_id: ObjectId,
189 expected_version_id: VersionId,
190 relationship_type: String,
191 target_object_id: ObjectId,
192 expected_record_sha256: String,
193 },
194}
195
196#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
197#[serde(deny_unknown_fields)]
198pub struct ReorganizationDraft {
199 pub protocol_version: String,
200 pub profile: String,
201 pub id: String,
202 #[serde(deserialize_with = "deserialize_canonical_u64")]
203 pub generation: u64,
204 pub folderbase_id: String,
205 pub path_profile: PathProfile,
206 pub analysis_scope: AnalysisScope,
207 pub questions: Vec<ConsequentialQuestion>,
208 pub rationale: String,
209 #[serde(default, skip_serializing_if = "Vec::is_empty")]
210 pub template_references: Vec<String>,
211 pub operations: Vec<ReorganizationOperation>,
212}
213
214#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
215#[serde(deny_unknown_fields)]
216pub struct ReorganizationPlan {
217 pub protocol_version: String,
218 pub profile: String,
219 pub id: String,
220 #[serde(deserialize_with = "deserialize_canonical_u64")]
221 pub generation: u64,
222 pub folderbase_id: String,
223 pub path_profile: PathProfile,
224 pub analysis_scope: AnalysisScope,
225 pub analysis_scope_digest: String,
226 pub questions: Vec<ConsequentialQuestion>,
227 pub rationale: String,
228 #[serde(default, skip_serializing_if = "Vec::is_empty")]
229 pub template_references: Vec<String>,
230 pub operations: Vec<ReorganizationOperation>,
231 pub plan_digest: String,
232}
233
234pub fn decode_reorganization_draft(reader: impl Read) -> Result<ReorganizationDraft> {
235 let bytes = read_bounded_record(reader)?;
236 decode_reorganization_draft_slice(&bytes)
237}
238
239pub fn decode_reorganization_draft_slice(bytes: &[u8]) -> Result<ReorganizationDraft> {
240 if bytes.len() > MAX_REORGANIZATION_RECORD_BYTES {
241 return invalid_record("reorganization draft exceeds the 8 MiB encoded-record limit");
242 }
243 let mut draft: ReorganizationDraft = serde_json::from_slice(bytes)
244 .map_err(|source| FolderbaseError::json("<reorganization-draft>", source))?;
245 validate_draft(&draft)?;
246 normalize_draft(&mut draft);
247 Ok(draft)
248}
249
250pub fn decode_reorganization_plan(reader: impl Read) -> Result<ReorganizationPlan> {
251 let bytes = read_bounded_record(reader)?;
252 decode_reorganization_plan_slice(&bytes)
253}
254
255pub fn decode_reorganization_plan_slice(bytes: &[u8]) -> Result<ReorganizationPlan> {
256 if bytes.len() > MAX_REORGANIZATION_RECORD_BYTES {
257 return invalid_record("reorganization plan exceeds the 8 MiB encoded-record limit");
258 }
259 let mut plan: ReorganizationPlan = serde_json::from_slice(bytes)
260 .map_err(|source| FolderbaseError::json("<reorganization-plan>", source))?;
261 validate_plan(&plan)?;
262 normalize_plan(&mut plan);
263 Ok(plan)
264}
265
266fn read_bounded_record(reader: impl Read) -> Result<Vec<u8>> {
267 let mut bytes = Vec::new();
268 reader
269 .take(MAX_REORGANIZATION_RECORD_BYTES as u64 + 1)
270 .read_to_end(&mut bytes)
271 .map_err(|source| FolderbaseError::io("<reorganization>", source))?;
272 if bytes.len() > MAX_REORGANIZATION_RECORD_BYTES {
273 return invalid_record("reorganization record exceeds the 8 MiB encoded-record limit");
274 }
275 Ok(bytes)
276}
277
278pub fn seal_reorganization_draft(mut draft: ReorganizationDraft) -> Result<ReorganizationPlan> {
279 validate_draft(&draft)?;
280 if draft
281 .questions
282 .iter()
283 .any(|question| question.required && question.answer.is_none())
284 {
285 return invalid_record(
286 "all required consequential questions must be answered before sealing",
287 );
288 }
289 normalize_draft(&mut draft);
290
291 let analysis_scope_digest = reorganization_analysis_scope_sha256(&draft.analysis_scope)?;
292 let mut plan = ReorganizationPlan {
293 protocol_version: draft.protocol_version,
294 profile: REORGANIZATION_PLAN_PROFILE.to_owned(),
295 id: draft.id,
296 generation: draft.generation,
297 folderbase_id: draft.folderbase_id,
298 path_profile: draft.path_profile,
299 analysis_scope: draft.analysis_scope,
300 analysis_scope_digest,
301 questions: draft.questions,
302 rationale: draft.rationale,
303 template_references: draft.template_references,
304 operations: draft.operations,
305 plan_digest: String::new(),
306 };
307 plan.plan_digest = canonical_plan_digest(&plan)?;
308 validate_plan(&plan)?;
309 Ok(plan)
310}
311
312pub fn validate_reorganization_draft(draft: &ReorganizationDraft) -> Result<()> {
313 validate_draft(draft)
314}
315
316pub fn validate_reorganization_plan(plan: &ReorganizationPlan) -> Result<()> {
317 validate_plan(plan)
318}
319
320pub fn reorganization_analysis_scope_sha256(scope: &AnalysisScope) -> Result<String> {
321 ensure_aggregate_record_bound(scope, "reorganization analysis scope")?;
322 let mut normalized = scope.clone();
323 normalize_scope(&mut normalized);
324 canonical_digest(ANALYSIS_SCOPE_DIGEST_DOMAIN, &normalized)
325}
326
327pub fn reorganization_plan_sha256(plan: &ReorganizationPlan) -> Result<String> {
328 canonical_plan_digest(plan)
329}
330
331fn validate_plan(plan: &ReorganizationPlan) -> Result<()> {
332 ensure_aggregate_record_bound(plan, "reorganization plan")?;
333 if plan.profile != REORGANIZATION_PLAN_PROFILE {
334 return invalid_record(format!(
335 "unsupported reorganization plan profile {}",
336 plan.profile
337 ));
338 }
339 let draft_shape = ReorganizationDraft {
340 protocol_version: plan.protocol_version.clone(),
341 profile: REORGANIZATION_DRAFT_PROFILE.to_owned(),
342 id: plan.id.clone(),
343 generation: plan.generation,
344 folderbase_id: plan.folderbase_id.clone(),
345 path_profile: plan.path_profile,
346 analysis_scope: plan.analysis_scope.clone(),
347 questions: plan.questions.clone(),
348 rationale: plan.rationale.clone(),
349 template_references: plan.template_references.clone(),
350 operations: plan.operations.clone(),
351 };
352 validate_draft(&draft_shape)?;
353 if plan
354 .questions
355 .iter()
356 .any(|question| question.required && question.answer.is_none())
357 {
358 return invalid_record("sealed plans require answers to all consequential questions");
359 }
360 validate_digest(&plan.analysis_scope_digest)?;
361 let expected_scope = reorganization_analysis_scope_sha256(&plan.analysis_scope)?;
362 if plan.analysis_scope_digest != expected_scope {
363 return invalid_record("reorganization analysis-scope digest does not match");
364 }
365 validate_digest(&plan.plan_digest)?;
366 let expected_plan = canonical_plan_digest(plan)?;
367 if plan.plan_digest != expected_plan {
368 return invalid_record("reorganization plan digest does not match");
369 }
370 Ok(())
371}
372
373fn validate_draft(draft: &ReorganizationDraft) -> Result<()> {
374 ensure_aggregate_record_bound(draft, "reorganization draft")?;
375 if draft.protocol_version != REORGANIZATION_PROTOCOL_VERSION {
376 return invalid_record(format!(
377 "unsupported reorganization protocol {}",
378 draft.protocol_version
379 ));
380 }
381 if draft.profile != REORGANIZATION_DRAFT_PROFILE {
382 return invalid_record(format!(
383 "unsupported reorganization draft profile {}",
384 draft.profile
385 ));
386 }
387 validate_reorganization_id(&draft.id)?;
388 validate_folderbase_id(&draft.folderbase_id)?;
389 if draft.generation == 0 || draft.generation > MAX_CANONICAL_JSON_INTEGER {
390 return invalid_record(
391 "reorganization generation must be a positive canonical JSON integer",
392 );
393 }
394 validate_digest(&draft.analysis_scope.manifest_sha256)?;
395 validate_scope(draft.path_profile, &draft.analysis_scope)?;
396 if draft.questions.len() > MAX_REORGANIZATION_QUESTIONS {
397 return invalid_record("reorganization draft contains too many questions");
398 }
399 let mut question_ids = BTreeSet::new();
400 for question in &draft.questions {
401 validate_question(question)?;
402 if !question_ids.insert(question.id.as_str()) {
403 return invalid_record(format!("question id must be unique: {}", question.id));
404 }
405 }
406 let mut template_references = BTreeSet::new();
407 for reference in &draft.template_references {
408 if reference.is_empty()
409 || reference.chars().count() > 255
410 || reference.chars().any(char::is_control)
411 || !template_references.insert(reference)
412 {
413 return invalid_record(
414 "template references must be bounded, unique provenance strings",
415 );
416 }
417 }
418 if draft.rationale.is_empty()
419 || draft.rationale.chars().count() > MAX_REORGANIZATION_TEXT_CHARACTERS
420 {
421 return invalid_record("reorganization rationale must be non-empty and bounded");
422 }
423 if draft.operations.is_empty() || draft.operations.len() > MAX_REORGANIZATION_OPERATIONS {
424 return invalid_record("reorganization operations must be non-empty and bounded");
425 }
426 for operation in &draft.operations {
427 validate_operation(operation)?;
428 }
429 validate_operation_path_uniqueness(draft.path_profile, &draft.operations)?;
430 validate_nested_boundary_confinement(
431 draft.path_profile,
432 &draft.analysis_scope,
433 &draft.operations,
434 )?;
435 validate_operation_closure(draft.path_profile, &draft.analysis_scope, &draft.operations)?;
436 Ok(())
437}
438
439fn normalize_draft(draft: &mut ReorganizationDraft) {
440 normalize_scope(&mut draft.analysis_scope);
441 draft.template_references.sort();
442}
443
444fn normalize_plan(plan: &mut ReorganizationPlan) {
445 normalize_scope(&mut plan.analysis_scope);
446 plan.template_references.sort();
447}
448
449fn normalize_scope(scope: &mut AnalysisScope) {
450 scope
451 .nested_boundaries
452 .sort_by_key(|boundary| boundary.path.nfc().collect::<String>());
453 scope
454 .operation_closure
455 .sort_by_key(|entry| entry.path().nfc().collect::<String>());
456 scope
457 .declared_entries
458 .sort_by_key(|entry| entry.path().nfc().collect::<String>());
459}
460
461fn validate_scope(path_profile: PathProfile, scope: &AnalysisScope) -> Result<()> {
462 if scope.nested_boundaries.len() > MAX_REORGANIZATION_SCOPE_ENTRIES {
463 return invalid_record("reorganization analysis scope contains too many boundaries");
464 }
465 if scope.declared_entries.len() > MAX_REORGANIZATION_SCOPE_ENTRIES {
466 return invalid_record("reorganization analysis scope contains too many entries");
467 }
468 if scope.operation_closure.len() > MAX_REORGANIZATION_SCOPE_ENTRIES {
469 return invalid_record("reorganization operation closure contains too many entries");
470 }
471 if scope.ignore_policy.path() != ".folderbaseignore" {
472 return invalid_record("ignore policy fact must describe .folderbaseignore");
473 }
474 if !matches!(
475 scope.ignore_policy,
476 ScopeEntry::Absent { .. } | ScopeEntry::File { .. }
477 ) {
478 return invalid_record("ignore policy snapshot must be an exact file or absence fact");
479 }
480 validate_scope_entry(&scope.ignore_policy)?;
481 let mut boundary_paths: BTreeSet<String> = BTreeSet::new();
482 for boundary in &scope.nested_boundaries {
483 validate_path(&boundary.path)?;
484 validate_digest(&boundary.manifest_sha256)?;
485 let key = portable_path_key(path_profile, &boundary.path);
486 if set_contains_path_at_or_above(&boundary_paths, &key)
487 || set_contains_path_below(&boundary_paths, &key)
488 {
489 return invalid_record(
490 "nested Folderbase boundaries must be unique and non-overlapping",
491 );
492 }
493 boundary_paths.insert(key);
494 }
495 for entry in &scope.operation_closure {
496 validate_scope_entry(entry)?;
497 }
498 for entry in &scope.declared_entries {
499 validate_scope_entry(entry)?;
500 }
501 Ok(())
502}
503
504fn validate_scope_entry(entry: &ScopeEntry) -> Result<()> {
505 validate_path(entry.path())?;
506 match entry {
507 ScopeEntry::File {
508 sha256, byte_count, ..
509 } => {
510 validate_digest(sha256)?;
511 validate_canonical_integer(*byte_count)
512 }
513 ScopeEntry::TrackedObject {
514 object_id,
515 version_id,
516 ..
517 } => {
518 validate_object_id(object_id)?;
519 validate_version_id(version_id)
520 }
521 ScopeEntry::Absent { .. } | ScopeEntry::Directory { .. } => Ok(()),
522 }
523}
524
525fn validate_question(question: &ConsequentialQuestion) -> Result<()> {
526 validate_token(&question.id, "question id")?;
527 if question.prompt.is_empty()
528 || question.prompt.chars().count() > MAX_REORGANIZATION_TEXT_CHARACTERS
529 {
530 return invalid_record("question prompt must be non-empty and bounded");
531 }
532 match question.answer_type {
533 ConsequentialAnswerType::SingleChoice => {
534 if question.options.is_empty() {
535 return invalid_record("single-choice questions require options");
536 }
537 let unique = question.options.iter().collect::<BTreeSet<_>>();
538 if unique.len() != question.options.len() {
539 return invalid_record("single-choice options must be unique");
540 }
541 for option in &question.options {
542 validate_token(option, "single-choice option")?;
543 }
544 }
545 ConsequentialAnswerType::Text | ConsequentialAnswerType::Boolean => {
546 if !question.options.is_empty() {
547 return invalid_record("only single-choice questions may declare options");
548 }
549 }
550 }
551 if let Some(answer) = &question.answer {
552 match (question.answer_type, answer) {
553 (ConsequentialAnswerType::Text, ConsequentialAnswer::Text(value)) => {
554 if value.is_empty() || value.chars().count() > MAX_REORGANIZATION_TEXT_CHARACTERS {
555 return invalid_record("text answers must be non-empty and bounded");
556 }
557 }
558 (ConsequentialAnswerType::Boolean, ConsequentialAnswer::Boolean(_)) => {}
559 (ConsequentialAnswerType::SingleChoice, ConsequentialAnswer::SingleChoice(value))
560 if question.options.contains(value) => {}
561 _ => return invalid_record("question answer does not match its declared type"),
562 }
563 }
564 Ok(())
565}
566
567fn validate_operation(operation: &ReorganizationOperation) -> Result<()> {
568 match operation {
569 ReorganizationOperation::CreateDirectory { path } => validate_ordinary_content_path(path),
570 ReorganizationOperation::CreateUtf8File { path, content } => {
571 validate_ordinary_content_path(path)?;
572 validate_bounded_text(content)
573 }
574 ReorganizationOperation::ReplaceUtf8File {
575 path,
576 expected_sha256,
577 content,
578 } => {
579 validate_ordinary_content_path(path)?;
580 validate_digest(expected_sha256)?;
581 validate_bounded_text(content)
582 }
583 ReorganizationOperation::UpdateManagedAgentBlock {
584 path,
585 adapter,
586 expected_sha256,
587 managed_block,
588 } => {
589 validate_agent_adapter_path(path, adapter)?;
590 validate_digest(expected_sha256)?;
591 validate_managed_block_body_syntax(managed_block, Path::new(path))?;
592 validate_bounded_text(managed_block)
593 }
594 ReorganizationOperation::MoveFile {
595 source_path,
596 destination_path,
597 expected_sha256,
598 expected_byte_count,
599 } => {
600 validate_distinct_paths(source_path, destination_path)?;
601 validate_ordinary_content_path(source_path)?;
602 validate_ordinary_content_path(destination_path)?;
603 validate_digest(expected_sha256)?;
604 validate_canonical_integer(*expected_byte_count)
605 }
606 ReorganizationOperation::MoveTrackedObject {
607 source_path,
608 destination_path,
609 object_id,
610 expected_version_id,
611 } => {
612 validate_distinct_paths(source_path, destination_path)?;
613 validate_ordinary_content_path(source_path)?;
614 validate_ordinary_content_path(destination_path)?;
615 validate_object_id(object_id)?;
616 validate_version_id(expected_version_id)
617 }
618 ReorganizationOperation::MarkCanonical {
619 object_record_path,
620 object_id,
621 expected_version_id,
622 expected_record_sha256,
623 } => {
624 validate_object_id(object_id)?;
625 validate_object_record_path(object_record_path, object_id)?;
626 validate_version_id(expected_version_id)?;
627 validate_digest(expected_record_sha256)
628 }
629 ReorganizationOperation::MarkSuperseded {
630 object_record_path,
631 object_id,
632 expected_version_id,
633 superseded_by,
634 expected_record_sha256,
635 } => {
636 validate_object_id(object_id)?;
637 validate_object_record_path(object_record_path, object_id)?;
638 validate_version_id(expected_version_id)?;
639 validate_digest(expected_record_sha256)?;
640 validate_object_id(superseded_by)
641 }
642 ReorganizationOperation::ArchiveObject {
643 object_record_path,
644 object_id,
645 expected_version_id,
646 expected_record_sha256,
647 } => {
648 validate_object_id(object_id)?;
649 validate_object_record_path(object_record_path, object_id)?;
650 validate_version_id(expected_version_id)?;
651 validate_digest(expected_record_sha256)
652 }
653 ReorganizationOperation::AddRelationship {
654 object_record_path,
655 object_id,
656 expected_version_id,
657 relationship_type,
658 target_object_id,
659 expected_record_sha256,
660 } => {
661 validate_object_id(object_id)?;
662 validate_object_record_path(object_record_path, object_id)?;
663 validate_version_id(expected_version_id)?;
664 validate_relationship_type(relationship_type)?;
665 validate_object_id(target_object_id)?;
666 validate_digest(expected_record_sha256)
667 }
668 }
669}
670
671#[derive(Debug, Clone, PartialEq, Eq)]
672enum ClosureRequirement {
673 Absent,
674 Directory,
675 File {
676 sha256: String,
677 byte_count: Option<u64>,
678 },
679 TrackedObject {
680 object_id: ObjectId,
681 version_id: VersionId,
682 },
683}
684
685fn validate_operation_closure(
686 path_profile: PathProfile,
687 scope: &AnalysisScope,
688 operations: &[ReorganizationOperation],
689) -> Result<()> {
690 let created_directory_indices = operations
691 .iter()
692 .enumerate()
693 .filter_map(|(index, operation)| match operation {
694 ReorganizationOperation::CreateDirectory { path } => {
695 Some((portable_path_key(path_profile, path), index))
696 }
697 _ => None,
698 })
699 .collect::<BTreeMap<_, _>>();
700 for operation in operations {
701 for path in operation_preexisting_paths(operation) {
702 for ancestor in path_ancestors(path) {
703 let key = portable_path_key(path_profile, ancestor);
704 if created_directory_indices.contains_key(&key) {
705 return invalid_record(format!(
706 "preexisting source cannot be below a planned-created directory: {path}"
707 ));
708 }
709 }
710 }
711 }
712 for (operation_index, operation) in operations.iter().enumerate() {
713 for path in operation_paths(operation) {
714 for ancestor in path_ancestors(path) {
715 let key = portable_path_key(path_profile, ancestor);
716 if created_directory_indices
717 .get(&key)
718 .is_some_and(|created_index| *created_index >= operation_index)
719 {
720 return invalid_record(format!(
721 "created parent directory must precede its child operation: {ancestor}"
722 ));
723 }
724 }
725 }
726 }
727 let created_directories = created_directory_indices
728 .keys()
729 .cloned()
730 .collect::<BTreeSet<_>>();
731 let mut expected = BTreeMap::new();
732 for operation in operations {
733 match operation {
734 ReorganizationOperation::CreateDirectory { path }
735 | ReorganizationOperation::CreateUtf8File { path, .. } => {
736 insert_closure_requirement(
737 path_profile,
738 &mut expected,
739 path,
740 ClosureRequirement::Absent,
741 )?;
742 }
743 ReorganizationOperation::ReplaceUtf8File {
744 path,
745 expected_sha256,
746 ..
747 }
748 | ReorganizationOperation::UpdateManagedAgentBlock {
749 path,
750 expected_sha256,
751 ..
752 } => {
753 insert_closure_requirement(
754 path_profile,
755 &mut expected,
756 path,
757 ClosureRequirement::File {
758 sha256: expected_sha256.clone(),
759 byte_count: None,
760 },
761 )?;
762 }
763 ReorganizationOperation::MoveFile {
764 source_path,
765 destination_path,
766 expected_sha256,
767 expected_byte_count,
768 } => {
769 insert_closure_requirement(
770 path_profile,
771 &mut expected,
772 source_path,
773 ClosureRequirement::File {
774 sha256: expected_sha256.clone(),
775 byte_count: Some(*expected_byte_count),
776 },
777 )?;
778 insert_closure_requirement(
779 path_profile,
780 &mut expected,
781 destination_path,
782 ClosureRequirement::Absent,
783 )?;
784 }
785 ReorganizationOperation::MoveTrackedObject {
786 source_path,
787 destination_path,
788 object_id,
789 expected_version_id,
790 } => {
791 insert_closure_requirement(
792 path_profile,
793 &mut expected,
794 source_path,
795 ClosureRequirement::TrackedObject {
796 object_id: object_id.clone(),
797 version_id: expected_version_id.clone(),
798 },
799 )?;
800 insert_closure_requirement(
801 path_profile,
802 &mut expected,
803 destination_path,
804 ClosureRequirement::Absent,
805 )?;
806 }
807 ReorganizationOperation::MarkCanonical {
808 object_record_path,
809 expected_record_sha256,
810 ..
811 }
812 | ReorganizationOperation::MarkSuperseded {
813 object_record_path,
814 expected_record_sha256,
815 ..
816 }
817 | ReorganizationOperation::ArchiveObject {
818 object_record_path,
819 expected_record_sha256,
820 ..
821 }
822 | ReorganizationOperation::AddRelationship {
823 object_record_path,
824 expected_record_sha256,
825 ..
826 } => {
827 insert_closure_requirement(
828 path_profile,
829 &mut expected,
830 object_record_path,
831 ClosureRequirement::File {
832 sha256: expected_record_sha256.clone(),
833 byte_count: None,
834 },
835 )?;
836 }
837 }
838 for path in operation_paths(operation) {
839 for ancestor in path_ancestors(path) {
840 let key = portable_path_key(path_profile, ancestor);
841 let requirement = if created_directories.contains(&key) {
842 ClosureRequirement::Absent
843 } else {
844 ClosureRequirement::Directory
845 };
846 insert_closure_requirement(path_profile, &mut expected, ancestor, requirement)?;
847 }
848 }
849 }
850
851 let mut actual = BTreeMap::new();
852 for entry in &scope.operation_closure {
853 let key = portable_path_key(path_profile, entry.path());
854 if actual.insert(key, entry).is_some() {
855 return invalid_record(format!(
856 "operation closure contains an aliasing path: {}",
857 entry.path()
858 ));
859 }
860 }
861 if actual.len() != expected.len() {
862 return invalid_record(format!(
863 "operation closure must contain exactly {} derived path facts, found {}",
864 expected.len(),
865 actual.len()
866 ));
867 }
868 for (path, requirement) in &expected {
869 let Some(entry) = actual.get(path) else {
870 return invalid_record(format!(
871 "operation closure is missing a derived path fact: {path}"
872 ));
873 };
874 if !closure_entry_matches(entry, requirement) {
875 return invalid_record(format!(
876 "operation closure fact does not match the derived precondition: {path}"
877 ));
878 }
879 }
880
881 let reserved = expected
882 .keys()
883 .cloned()
884 .chain([
885 portable_path_key(path_profile, ".folderbaseignore"),
886 portable_path_key(path_profile, ".folderbase/manifest.json"),
887 ])
888 .collect::<BTreeSet<_>>();
889 let mut declared = BTreeSet::new();
890 for entry in &scope.declared_entries {
891 let key = portable_path_key(path_profile, entry.path());
892 if reserved.contains(&key) || !declared.insert(key) {
893 return invalid_record(format!(
894 "declared analysis entry is not an additional unique path: {}",
895 entry.path()
896 ));
897 }
898 }
899 Ok(())
900}
901
902fn insert_closure_requirement(
903 path_profile: PathProfile,
904 requirements: &mut BTreeMap<String, ClosureRequirement>,
905 path: &str,
906 requirement: ClosureRequirement,
907) -> Result<()> {
908 let key = portable_path_key(path_profile, path);
909 if let Some(existing) = requirements.get(&key) {
910 if existing != &requirement {
911 return invalid_record(format!(
912 "operations require incompatible preconditions for {path}"
913 ));
914 }
915 return Ok(());
916 }
917 requirements.insert(key, requirement);
918 Ok(())
919}
920
921fn path_ancestors(path: &str) -> Vec<&str> {
922 path.match_indices('/')
923 .map(|(index, _)| &path[..index])
924 .collect()
925}
926
927fn closure_entry_matches(entry: &ScopeEntry, requirement: &ClosureRequirement) -> bool {
928 match (entry, requirement) {
929 (ScopeEntry::Absent { .. }, ClosureRequirement::Absent)
930 | (ScopeEntry::Directory { .. }, ClosureRequirement::Directory) => true,
931 (
932 ScopeEntry::File {
933 sha256, byte_count, ..
934 },
935 ClosureRequirement::File {
936 sha256: expected_sha256,
937 byte_count: expected_byte_count,
938 },
939 ) => {
940 sha256 == expected_sha256
941 && expected_byte_count.is_none_or(|expected| expected == *byte_count)
942 }
943 (
944 ScopeEntry::TrackedObject {
945 object_id,
946 version_id,
947 ..
948 },
949 ClosureRequirement::TrackedObject {
950 object_id: expected_object_id,
951 version_id: expected_version_id,
952 },
953 ) => object_id == expected_object_id && version_id == expected_version_id,
954 _ => false,
955 }
956}
957
958fn validate_operation_path_uniqueness(
959 path_profile: PathProfile,
960 operations: &[ReorganizationOperation],
961) -> Result<()> {
962 let mut paths = BTreeMap::new();
963 for operation in operations {
964 for path in operation_paths(operation) {
965 let key = portable_path_key(path_profile, path);
966 if let Some(existing) = paths.insert(key, path) {
967 return invalid_record(format!(
968 "operation path {path} aliases another operation path {existing}"
969 ));
970 }
971 }
972 }
973 Ok(())
974}
975
976fn validate_nested_boundary_confinement(
977 path_profile: PathProfile,
978 scope: &AnalysisScope,
979 operations: &[ReorganizationOperation],
980) -> Result<()> {
981 let boundaries = scope
982 .nested_boundaries
983 .iter()
984 .map(|boundary| portable_path_key(path_profile, &boundary.path))
985 .collect::<BTreeSet<_>>();
986
987 for entry in scope
988 .operation_closure
989 .iter()
990 .chain(&scope.declared_entries)
991 {
992 let path = portable_path_key(path_profile, entry.path());
993 if set_contains_path_at_or_above(&boundaries, &path) {
994 return invalid_record(format!(
995 "declared analysis path enters a nested Folderbase boundary: {}",
996 entry.path()
997 ));
998 }
999 }
1000 for operation in operations {
1001 for path in operation_paths(operation) {
1002 let key = portable_path_key(path_profile, path);
1003 if set_contains_path_at_or_above(&boundaries, &key) {
1004 return invalid_record(format!(
1005 "operation path enters a nested Folderbase boundary: {path}"
1006 ));
1007 }
1008 }
1009 }
1010 Ok(())
1011}
1012
1013fn operation_paths(operation: &ReorganizationOperation) -> Vec<&str> {
1014 match operation {
1015 ReorganizationOperation::CreateDirectory { path }
1016 | ReorganizationOperation::CreateUtf8File { path, .. }
1017 | ReorganizationOperation::ReplaceUtf8File { path, .. }
1018 | ReorganizationOperation::UpdateManagedAgentBlock { path, .. } => vec![path],
1019 ReorganizationOperation::MoveFile {
1020 source_path,
1021 destination_path,
1022 ..
1023 }
1024 | ReorganizationOperation::MoveTrackedObject {
1025 source_path,
1026 destination_path,
1027 ..
1028 } => vec![source_path, destination_path],
1029 ReorganizationOperation::MarkCanonical {
1030 object_record_path, ..
1031 }
1032 | ReorganizationOperation::MarkSuperseded {
1033 object_record_path, ..
1034 }
1035 | ReorganizationOperation::ArchiveObject {
1036 object_record_path, ..
1037 }
1038 | ReorganizationOperation::AddRelationship {
1039 object_record_path, ..
1040 } => vec![object_record_path],
1041 }
1042}
1043
1044fn operation_preexisting_paths(operation: &ReorganizationOperation) -> Vec<&str> {
1045 match operation {
1046 ReorganizationOperation::CreateDirectory { .. }
1047 | ReorganizationOperation::CreateUtf8File { .. } => Vec::new(),
1048 ReorganizationOperation::ReplaceUtf8File { path, .. }
1049 | ReorganizationOperation::UpdateManagedAgentBlock { path, .. } => vec![path],
1050 ReorganizationOperation::MoveFile { source_path, .. }
1051 | ReorganizationOperation::MoveTrackedObject { source_path, .. } => vec![source_path],
1052 ReorganizationOperation::MarkCanonical {
1053 object_record_path, ..
1054 }
1055 | ReorganizationOperation::MarkSuperseded {
1056 object_record_path, ..
1057 }
1058 | ReorganizationOperation::ArchiveObject {
1059 object_record_path, ..
1060 }
1061 | ReorganizationOperation::AddRelationship {
1062 object_record_path, ..
1063 } => vec![object_record_path],
1064 }
1065}
1066
1067fn portable_path_key(profile: PathProfile, path: &str) -> String {
1068 let normalized = path.nfc().collect::<String>();
1069 match profile {
1070 PathProfile::CaseSensitive => normalized,
1071 PathProfile::CaseFold => normalized.case_fold().collect(),
1072 }
1073}
1074
1075fn set_contains_path_at_or_above(paths: &BTreeSet<String>, path: &str) -> bool {
1076 paths.contains(path)
1077 || path_ancestors(path)
1078 .into_iter()
1079 .any(|ancestor| paths.contains(ancestor))
1080}
1081
1082fn set_contains_path_below(paths: &BTreeSet<String>, path: &str) -> bool {
1083 let descendant_prefix = format!("{path}/");
1084 paths
1085 .range(descendant_prefix.clone()..)
1086 .next()
1087 .is_some_and(|candidate| candidate.starts_with(&descendant_prefix))
1088}
1089
1090fn validate_canonical_integer(value: u64) -> Result<()> {
1091 if value > MAX_CANONICAL_JSON_INTEGER {
1092 return invalid_record(format!(
1093 "value exceeds the maximum canonical JSON integer {MAX_CANONICAL_JSON_INTEGER}"
1094 ));
1095 }
1096 Ok(())
1097}
1098
1099fn deserialize_canonical_u64<'de, D>(deserializer: D) -> std::result::Result<u64, D::Error>
1100where
1101 D: Deserializer<'de>,
1102{
1103 let number = serde_json::Number::deserialize(deserializer)?;
1104 exact_canonical_u64(&number.to_string()).map_err(D::Error::custom)
1105}
1106
1107fn exact_canonical_u64(lexeme: &str) -> std::result::Result<u64, String> {
1108 let (negative, unsigned) = lexeme
1109 .strip_prefix('-')
1110 .map_or((false, lexeme), |unsigned| (true, unsigned));
1111 let exponent_index = unsigned.find(['e', 'E']);
1112 let (mantissa, exponent_text) = exponent_index.map_or((unsigned, None), |index| {
1113 (&unsigned[..index], Some(&unsigned[index + 1..]))
1114 });
1115 let (integer, fraction) = mantissa
1116 .split_once('.')
1117 .map_or((mantissa, ""), |(integer, fraction)| (integer, fraction));
1118 let mut digits = String::with_capacity(integer.len() + fraction.len());
1119 digits.push_str(integer);
1120 digits.push_str(fraction);
1121 if digits.bytes().all(|byte| byte == b'0') {
1122 return Ok(0);
1123 }
1124 if negative {
1125 return Err("expected a non-negative exact canonical JSON integer".to_owned());
1126 }
1127
1128 let exponent = parse_bounded_decimal_exponent(exponent_text.unwrap_or("0"))?;
1129 let fraction_len =
1130 i64::try_from(fraction.len()).map_err(|_| "number lexeme is too large".to_owned())?;
1131 let scale = exponent
1132 .checked_sub(fraction_len)
1133 .ok_or_else(|| "number exponent is outside the supported range".to_owned())?;
1134 let significant = digits.trim_start_matches('0');
1135 let canonical_digits = if scale >= 0 {
1136 let zero_count =
1137 usize::try_from(scale).map_err(|_| "number exponent is too large".to_owned())?;
1138 if significant.len().saturating_add(zero_count) > 16 {
1139 return Err(format!(
1140 "canonical JSON integer exceeds {MAX_CANONICAL_JSON_INTEGER}"
1141 ));
1142 }
1143 let mut value = significant.to_owned();
1144 value.extend(std::iter::repeat_n('0', zero_count));
1145 value
1146 } else {
1147 let removed = usize::try_from(scale.unsigned_abs())
1148 .map_err(|_| "number exponent is too small".to_owned())?;
1149 if removed >= digits.len()
1150 || !digits[digits.len() - removed..]
1151 .bytes()
1152 .all(|byte| byte == b'0')
1153 {
1154 return Err("expected a non-negative exact canonical JSON integer".to_owned());
1155 }
1156 digits[..digits.len() - removed]
1157 .trim_start_matches('0')
1158 .to_owned()
1159 };
1160 let value = canonical_digits
1161 .parse::<u64>()
1162 .map_err(|_| format!("canonical JSON integer exceeds {MAX_CANONICAL_JSON_INTEGER}"))?;
1163 if value > MAX_CANONICAL_JSON_INTEGER {
1164 return Err(format!(
1165 "canonical JSON integer exceeds {MAX_CANONICAL_JSON_INTEGER}"
1166 ));
1167 }
1168 Ok(value)
1169}
1170
1171fn parse_bounded_decimal_exponent(value: &str) -> std::result::Result<i64, String> {
1172 let (negative, digits) = match value.as_bytes().first() {
1173 Some(b'+') => (false, &value[1..]),
1174 Some(b'-') => (true, &value[1..]),
1175 _ => (false, value),
1176 };
1177 let significant = digits.trim_start_matches('0');
1178 if significant.is_empty() {
1179 return Ok(0);
1180 }
1181 if significant.len() > 9 {
1182 return Err(if negative {
1183 "number exponent is too small".to_owned()
1184 } else {
1185 "number exponent is too large".to_owned()
1186 });
1187 }
1188 let magnitude = significant
1189 .parse::<i64>()
1190 .map_err(|_| "invalid number exponent".to_owned())?;
1191 Ok(if negative { -magnitude } else { magnitude })
1192}
1193
1194fn validate_distinct_paths(source: &str, destination: &str) -> Result<()> {
1195 validate_path(source)?;
1196 validate_path(destination)?;
1197 if source == destination {
1198 return invalid_record("move source and destination must differ");
1199 }
1200 let normalized_source = source.nfc().collect::<String>();
1201 let normalized_destination = destination.nfc().collect::<String>();
1202 let folded_source = normalized_source.case_fold().collect::<String>();
1203 let folded_destination = normalized_destination.case_fold().collect::<String>();
1204 if folded_source == folded_destination {
1205 return invalid_record("reorganization-v1 refuses a case-only rename");
1206 }
1207 Ok(())
1208}
1209
1210fn validate_bounded_text(value: &str) -> Result<()> {
1211 if value.chars().count() > MAX_REORGANIZATION_TEXT_CHARACTERS {
1212 return invalid_record("reorganization text content exceeds the 2M-character limit");
1213 }
1214 Ok(())
1215}
1216
1217fn validate_digest(value: &str) -> Result<()> {
1218 if value.len() != 64
1219 || !value
1220 .bytes()
1221 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
1222 {
1223 return invalid_record(
1224 "digest must be exactly 64 lowercase hexadecimal SHA-256 characters",
1225 );
1226 }
1227 Ok(())
1228}
1229
1230fn validate_reorganization_id(value: &str) -> Result<()> {
1231 let Some(uuid_text) = value.strip_prefix("reorg_") else {
1232 return invalid_record("reorganization identifier is invalid");
1233 };
1234 let Ok(uuid) = uuid::Uuid::parse_str(uuid_text) else {
1235 return invalid_record("reorganization identifier is invalid");
1236 };
1237 if uuid.hyphenated().to_string() != uuid_text {
1238 return invalid_record("reorganization identifier is invalid");
1239 }
1240 Ok(())
1241}
1242
1243fn validate_folderbase_id(value: &str) -> Result<()> {
1244 validate_exact_prefixed_uuid(value, "folderbase_", "folderbase identifier")
1245}
1246
1247fn validate_object_id(value: &ObjectId) -> Result<()> {
1248 validate_exact_prefixed_uuid(value.as_str(), "obj_", "object identifier")
1249}
1250
1251fn validate_version_id(value: &VersionId) -> Result<()> {
1252 validate_exact_prefixed_uuid(value.as_str(), "version_", "version identifier")
1253}
1254
1255fn validate_exact_prefixed_uuid(value: &str, prefix: &str, label: &str) -> Result<()> {
1256 let Some(uuid_text) = value.strip_prefix(prefix) else {
1257 return invalid_record(format!("{label} is invalid"));
1258 };
1259 let Ok(uuid) = uuid::Uuid::parse_str(uuid_text) else {
1260 return invalid_record(format!("{label} is invalid"));
1261 };
1262 if uuid.hyphenated().to_string() != uuid_text {
1263 return invalid_record(format!("{label} is invalid"));
1264 }
1265 Ok(())
1266}
1267
1268fn validate_relationship_type(value: &str) -> Result<()> {
1269 let mut bytes = value.bytes();
1270 if value.len() > 255
1271 || !bytes.next().is_some_and(|byte| byte.is_ascii_lowercase())
1272 || !bytes.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
1273 {
1274 return invalid_record("relationship type must be a lowercase protocol token");
1275 }
1276 Ok(())
1277}
1278
1279fn validate_ordinary_content_path(path: &str) -> Result<()> {
1280 validate_path(path)?;
1281 if Path::new(path)
1282 .components()
1283 .filter_map(|component| match component {
1284 std::path::Component::Normal(name) => Some(name),
1285 _ => None,
1286 })
1287 .any(is_reserved_workspace_component)
1288 || (!path.contains('/')
1289 && ["AGENTS.md", "CLAUDE.md", ".folderbaseignore"]
1290 .iter()
1291 .any(|reserved| path.eq_ignore_ascii_case(reserved)))
1292 {
1293 return invalid_record(format!(
1294 "ordinary operation path is reserved and requires an exact typed operation: {path}"
1295 ));
1296 }
1297 Ok(())
1298}
1299
1300fn validate_agent_adapter_path(path: &str, adapter: &str) -> Result<()> {
1301 validate_path(path)?;
1302 let expected = match adapter {
1303 "codex" => "AGENTS.md",
1304 "claude" => "CLAUDE.md",
1305 _ => return invalid_record("unsupported managed agent adapter"),
1306 };
1307 if path != expected {
1308 return invalid_record(format!(
1309 "managed {adapter} adapter operation must target {expected}"
1310 ));
1311 }
1312 Ok(())
1313}
1314
1315fn validate_object_record_path(path: &str, object_id: &ObjectId) -> Result<()> {
1316 validate_path(path)?;
1317 let expected = format!(".folderbase/objects/{object_id}.json");
1318 if path != expected {
1319 return invalid_record(format!(
1320 "object protocol operation must target the canonical object record path {expected}"
1321 ));
1322 }
1323 Ok(())
1324}
1325
1326fn validate_token(value: &str, label: &str) -> Result<()> {
1327 if value.is_empty()
1328 || value.len() > 255
1329 || !value
1330 .bytes()
1331 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))
1332 {
1333 return invalid_record(format!("{label} is not a portable token"));
1334 }
1335 Ok(())
1336}
1337
1338fn validate_path(value: &str) -> Result<()> {
1339 let bytes = value.as_bytes();
1340 let has_drive_prefix = bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':';
1341 if value.is_empty()
1342 || value.chars().count() > MAX_REORGANIZATION_PATH_CHARACTERS
1343 || value.starts_with('/')
1344 || value.ends_with('/')
1345 || value.contains('\\')
1346 || value.contains('\0')
1347 || value.contains("//")
1348 || has_drive_prefix
1349 || value.split('/').any(|part| matches!(part, "" | "." | ".."))
1350 || Path::new(value).is_absolute()
1351 {
1352 return invalid_record(format!("unsafe portable path: {value}"));
1353 }
1354 Ok(())
1355}
1356
1357fn canonical_plan_digest(plan: &ReorganizationPlan) -> Result<String> {
1358 ensure_aggregate_record_bound(plan, "reorganization plan")?;
1359 let mut normalized = plan.clone();
1360 normalize_plan(&mut normalized);
1361 let mut value = serde_json::to_value(normalized)
1362 .map_err(|source| FolderbaseError::json("<reorganization-plan>", source))?;
1363 value
1364 .as_object_mut()
1365 .expect("a plan always serializes as an object")
1366 .remove("plan_digest");
1367 canonical_value_digest(PLAN_DIGEST_DOMAIN, &value)
1368}
1369
1370fn canonical_digest<T: Serialize>(domain: &[u8], value: &T) -> Result<String> {
1371 ensure_aggregate_record_bound(value, "reorganization digest input")?;
1372 let value = serde_json::to_value(value)
1373 .map_err(|source| FolderbaseError::json("<reorganization-digest>", source))?;
1374 canonical_value_digest(domain, &value)
1375}
1376
1377fn ensure_aggregate_record_bound(value: &(impl Serialize + ?Sized), label: &str) -> Result<()> {
1378 let mut writer = BoundedJsonWriter { written: 0 };
1379 if serde_json::to_writer(&mut writer, value).is_err() {
1380 return invalid_record(format!("{label} exceeds the 8 MiB encoded-record limit"));
1381 }
1382 Ok(())
1383}
1384
1385struct BoundedJsonWriter {
1386 written: usize,
1387}
1388
1389impl Write for BoundedJsonWriter {
1390 fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
1391 if self.written.saturating_add(bytes.len()) > MAX_REORGANIZATION_RECORD_BYTES {
1392 return Err(std::io::Error::other(
1393 "reorganization encoded-record limit exceeded",
1394 ));
1395 }
1396 self.written += bytes.len();
1397 Ok(bytes.len())
1398 }
1399
1400 fn flush(&mut self) -> std::io::Result<()> {
1401 Ok(())
1402 }
1403}
1404
1405fn canonical_value_digest(domain: &[u8], value: &Value) -> Result<String> {
1406 let mut canonical = Vec::new();
1407 write_canonical_json(value, &mut canonical)?;
1408 let mut hasher = Sha256::new();
1409 hasher.update(domain);
1410 hasher.update(canonical);
1411 Ok(format!("{:x}", hasher.finalize()))
1412}
1413
1414fn write_canonical_json(value: &Value, output: &mut Vec<u8>) -> Result<()> {
1415 match value {
1416 Value::Null => output.extend_from_slice(b"null"),
1417 Value::Bool(value) => output.extend_from_slice(if *value { b"true" } else { b"false" }),
1418 Value::Number(value) => output.extend_from_slice(value.to_string().as_bytes()),
1419 Value::String(value) => {
1420 let encoded = serde_json::to_string(value).map_err(|source| {
1421 FolderbaseError::json("<reorganization-canonical-json>", source)
1422 })?;
1423 output.extend_from_slice(encoded.as_bytes());
1424 }
1425 Value::Array(values) => {
1426 output.push(b'[');
1427 for (index, value) in values.iter().enumerate() {
1428 if index != 0 {
1429 output.push(b',');
1430 }
1431 write_canonical_json(value, output)?;
1432 }
1433 output.push(b']');
1434 }
1435 Value::Object(values) => {
1436 output.push(b'{');
1437 let mut entries = values.iter().collect::<Vec<_>>();
1438 entries.sort_by(|left, right| left.0.cmp(right.0));
1439 for (index, (key, value)) in entries.into_iter().enumerate() {
1440 if index != 0 {
1441 output.push(b',');
1442 }
1443 let encoded = serde_json::to_string(key).map_err(|source| {
1444 FolderbaseError::json("<reorganization-canonical-json>", source)
1445 })?;
1446 output.extend_from_slice(encoded.as_bytes());
1447 output.push(b':');
1448 write_canonical_json(value, output)?;
1449 }
1450 output.push(b'}');
1451 }
1452 }
1453 Ok(())
1454}
1455
1456fn invalid_record<T>(message: impl Into<String>) -> Result<T> {
1457 Err(FolderbaseError::InvalidRecord {
1458 path: "<reorganization>".into(),
1459 message: message.into(),
1460 })
1461}