capsule_core/sidecar/region.rs
1//! Labelled image regions — the sidecar's `regions` map (SSoT: [Organization — Labels] and
2//! [Metadata — Grouping Convergence]).
3//!
4//! A region is a circle or rectangle in coordinates normalized to `[0, 1]` over the original's
5//! **display orientation** (after EXIF orientation), so it survives every derivative size. Each
6//! region has a UUIDv7 and its own labels OR-set. On the wire the map is
7//! `Map<UUIDv7, Lww<Option<Region>>>`: a stamped `Some` is a live region, a stamped `None` is a
8//! deleted one.
9//!
10//! # Merge
11//!
12//! A region register does not merge as a plain [`Lww`]. Two concurrent label edits on one
13//! region must both survive ("labels as tags"), and folding label sets into a last-writer-wins
14//! value is not associative once a delete sits between them. The register therefore merges as a
15//! join-semilattice:
16//!
17//! - **Delete is final.** A tombstone absorbs every live write, whatever its stamp; between two
18//! tombstones the later stamp wins. A region id is minted fresh per create, so no create ever
19//! races an earlier delete of the same id — the only write a tombstone overrides is an edit
20//! concurrent with or after the delete.
21//! - **Live ⊔ live** takes the shape of the later `(ts, device_id)` stamp (ties broken on the
22//! shape's canonical bytes) and the **union** of the two label OR-sets.
23//!
24//! Each component is a semilattice, so [`merge_regions`] is commutative, associative and
25//! idempotent. A merged register keeps no superseded log: every displaced label survives in the
26//! union, and a displaced shape is not a value a user authored alone.
27//!
28//! [Organization — Labels]: https://docs/design/organization/#labels
29//! [Metadata — Grouping Convergence]: https://docs/design/metadata/#grouping-convergence-requirement
30
31use std::cmp::Ordering;
32use std::collections::BTreeMap;
33
34use serde::{Deserialize, Serialize};
35use thiserror::Error;
36use uuid::Uuid;
37
38use crate::cbor;
39use crate::metadata::crdt::{Lww, OrSet, Stamped};
40
41/// The sidecar's region map: region id (UUIDv7) to its register.
42pub type Regions = BTreeMap<Uuid, Lww<Option<Region>>>;
43
44/// A region's outline, in coordinates normalized to `[0, 1]` over the display orientation.
45#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
46#[serde(rename_all = "kebab-case")]
47pub enum RegionShape {
48 /// A circle centred at `(cx, cy)` (fractions of width / height) with radius `r`, a fraction
49 /// of the image's shorter side, `min(width, height)`, so it is round on any aspect ratio
50 /// and `r = 0.5` centred is the inscribed circle.
51 Circle {
52 /// Centre, horizontal.
53 cx: f32,
54 /// Centre, vertical.
55 cy: f32,
56 /// Radius.
57 r: f32,
58 },
59 /// A rectangle with top-left `(x, y)`, width `w` and height `h`.
60 Rect {
61 /// Left edge.
62 x: f32,
63 /// Top edge.
64 y: f32,
65 /// Width.
66 w: f32,
67 /// Height.
68 h: f32,
69 },
70}
71
72/// Why a region shape was refused.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
74pub enum RegionError {
75 /// A coordinate is not a finite number in `[0, 1]`.
76 #[error("region coordinate out of range [0, 1]")]
77 OutOfRange,
78 /// A radius, width or height is zero.
79 #[error("region has no area")]
80 Empty,
81 /// A rectangle extends past the right or bottom edge, or a circle past an edge.
82 #[error("region extends past the image edge")]
83 PastEdge,
84}
85
86impl RegionShape {
87 /// Check the normalized-coordinate contract: every value finite and in `[0, 1]`, a positive
88 /// extent, and the shape wholly inside the image. A circle spans exactly `r` of the shorter
89 /// axis, and the shape does not record which axis that is, so it must fit `r` from its
90 /// centre on both: on the longer axis it spans less.
91 ///
92 /// # Errors
93 ///
94 /// The [`RegionError`] naming the first violated rule.
95 pub fn validate(&self) -> Result<(), RegionError> {
96 let unit = |v: f32| v.is_finite() && (0.0..=1.0).contains(&v);
97 match *self {
98 Self::Circle { cx, cy, r } => {
99 if ![cx, cy, r].into_iter().all(unit) {
100 return Err(RegionError::OutOfRange);
101 }
102 if r <= 0.0 {
103 return Err(RegionError::Empty);
104 }
105 if cx < r || cy < r || cx + r > 1.0 || cy + r > 1.0 {
106 return Err(RegionError::PastEdge);
107 }
108 }
109 Self::Rect { x, y, w, h } => {
110 if ![x, y, w, h].into_iter().all(unit) {
111 return Err(RegionError::OutOfRange);
112 }
113 if w <= 0.0 || h <= 0.0 {
114 return Err(RegionError::Empty);
115 }
116 if x + w > 1.0 || y + h > 1.0 {
117 return Err(RegionError::PastEdge);
118 }
119 }
120 }
121 Ok(())
122 }
123
124 fn canonical_bytes(&self) -> Vec<u8> {
125 cbor::to_canonical_vec(self).expect("a region shape serializes")
126 }
127}
128
129/// One labelled region of an image.
130#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
131pub struct Region {
132 /// The outline.
133 pub shape: RegionShape,
134 /// The region's labels.
135 pub labels: OrSet<String>,
136}
137
138impl Region {
139 /// A region with no labels yet.
140 pub fn new(shape: RegionShape) -> Self {
141 Self {
142 shape,
143 labels: OrSet::new(),
144 }
145 }
146}
147
148/// The total order on stamps: parsed time, then the writing device, then the raw string (so an
149/// unparseable time still orders deterministically, below every parseable one).
150fn stamp_key<T>(s: &Stamped<T>) -> (Option<jiff::Timestamp>, Uuid, &str) {
151 (s.ts.parse().ok(), s.by, s.ts.as_str())
152}
153
154fn later<'a, T>(a: &'a Stamped<T>, b: &'a Stamped<T>) -> Ordering {
155 stamp_key(a).cmp(&stamp_key(b))
156}
157
158/// Merge two writes to one region register into their join (see the module docs).
159fn join(a: &Stamped<Option<Region>>, b: &Stamped<Option<Region>>) -> Stamped<Option<Region>> {
160 match (&a.value, &b.value) {
161 // A tombstone absorbs a live write.
162 (None, Some(_)) => a.clone(),
163 (Some(_), None) => b.clone(),
164 // Two tombstones: the later stamp.
165 (None, None) => {
166 if later(a, b) == Ordering::Less {
167 b.clone()
168 } else {
169 a.clone()
170 }
171 }
172 (Some(ra), Some(rb)) => {
173 let order = later(a, b)
174 .then_with(|| ra.shape.canonical_bytes().cmp(&rb.shape.canonical_bytes()));
175 let (winner, winner_region) = if order == Ordering::Less {
176 (b, rb)
177 } else {
178 (a, ra)
179 };
180 let mut labels = ra.labels.clone();
181 labels.merge(&rb.labels);
182 Stamped {
183 value: Some(Region {
184 shape: winner_region.shape,
185 labels,
186 }),
187 ts: winner.ts.clone(),
188 by: winner.by,
189 }
190 }
191 }
192}
193
194/// Merge two registers for one region id. A never-written register is the identity.
195pub fn merge_region_register(
196 a: &Lww<Option<Region>>,
197 b: &Lww<Option<Region>>,
198) -> Lww<Option<Region>> {
199 let current = match (&a.current, &b.current) {
200 (None, None) => None,
201 (Some(x), None) | (None, Some(x)) => Some(x.clone()),
202 (Some(x), Some(y)) => Some(join(x, y)),
203 };
204 Lww {
205 current,
206 superseded: Vec::new(),
207 }
208}
209
210/// Merge `other`'s region map into `local`: the union of region ids, each register merged by
211/// [`merge_region_register`]. Commutative, associative and idempotent.
212pub fn merge_regions(local: &mut Regions, other: &Regions) {
213 for (id, theirs) in other {
214 let merged = match local.get(id) {
215 Some(ours) => merge_region_register(ours, theirs),
216 None => merge_region_register(&Lww::new(), theirs),
217 };
218 local.insert(*id, merged);
219 }
220}
221
222/// Write `value` into a region register as a new local write: the register's current value
223/// becomes `value` stamped `(ts, by)`, and nothing is logged as superseded — a local edit
224/// already folded the prior state into `value`.
225pub fn write_region(
226 register: &mut Lww<Option<Region>>,
227 value: Option<Region>,
228 ts: String,
229 by: Uuid,
230) {
231 register.current = Some(Stamped { value, ts, by });
232 register.superseded.clear();
233}
234
235/// The live region a register holds, if it is neither unwritten nor deleted.
236pub fn live_region(register: &Lww<Option<Region>>) -> Option<&Region> {
237 register.get().and_then(Option::as_ref)
238}
239
240#[cfg(test)]
241mod tests;