Skip to main content

coven_format/
path.rs

1//! Canonical object names and listing prefixes from format.md D10.
2//!
3//! Crate-to-crate API: coven's format, storage and sync code build paths and
4//! prefixes here. Native provider adapters map these validated paths into
5//! their provider's object names.
6
7use coven_foundation::id_source::{DeviceId, InviteId, ObjectId, StoreId};
8use coven_merge::Audience;
9use serde::{Deserialize, Serialize};
10use std::num::NonZeroU64;
11
12/// One validated encrypted-object path in the layout of §§5, 10, 12, 13, 16 and 17.
13#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
14#[serde(try_from = "String", into = "String")]
15pub struct ObjectPath(String);
16
17impl ObjectPath {
18    /// One create-once slot in the store's shared sequence (§5).
19    pub fn slot(store: StoreId, number: NonZeroU64) -> Self {
20        Self(format!("{store}/seq/{number}"))
21    }
22    /// The positive number of a sequence slot.
23    pub fn slot_number(&self) -> Option<crate::value::Slot> {
24        self.relative()
25            .strip_prefix("seq/")
26            .map(|number| number.parse::<NonZeroU64>().expect("validated slot").into())
27    }
28    /// The store's conditionally replaced floor pointer (§16.4).
29    pub fn floor(store: StoreId) -> Self {
30        Self(format!("{store}/floor"))
31    }
32    /// One floor body, created once at a number of its writing device's own
33    /// (§16.4).
34    pub fn floor_body(store: StoreId, device: DeviceId, number: NonZeroU64) -> Self {
35        Self(format!("{store}/floors/{}/{number}", device.0))
36    }
37    /// The writer and number a floor body's path names.
38    pub fn floor_body_id(&self) -> Option<(DeviceId, NonZeroU64)> {
39        match self.relative().split('/').collect::<Vec<_>>().as_slice() {
40            ["floors", device, number] => Some((
41                DeviceId(device.parse().expect("validated device id")),
42                number.parse().expect("validated number"),
43            )),
44            _ => None,
45        }
46    }
47    /// The identity carried by a snapshot path.
48    pub fn snapshot_id(&self) -> Option<crate::admin::SnapshotId> {
49        let rest = self.relative().strip_prefix("snapshots/")?;
50        let (audience, rest) = rest.split_once('/').expect("validated snapshot path");
51        let (device, number) = rest.split_once('/').expect("validated snapshot path");
52        let audience: Audience = audience.parse().expect("validated audience");
53        Some(crate::admin::SnapshotId {
54            audience,
55            device: DeviceId(device.parse().expect("validated device")),
56            number: number.parse().expect("validated number"),
57        })
58    }
59    /// A snapshot written by a device (§16).
60    pub fn snapshot(
61        store: StoreId,
62        audience: Audience,
63        device: DeviceId,
64        number: NonZeroU64,
65    ) -> Self {
66        Self(format!("{store}/snapshots/{}/{}/{number}", audience, device.0))
67    }
68    /// A stored object: encrypted file bytes named by their object id (§17.5).
69    pub fn file(store: StoreId, device: DeviceId, object: ObjectId) -> Self {
70        Self(format!("{store}/files/{}/{object}", device.0))
71    }
72    /// An encrypted join request under the device that made its invite and
73    /// the invite's id (§13.2).
74    pub fn join_request(store: StoreId, inviting: DeviceId, invite: InviteId) -> Self {
75        Self(format!("{store}/join-requests/{}/{invite}", inviting.0))
76    }
77    /// The marker of a device gone for good, beside the join requests to
78    /// its invites (§13.2).
79    pub fn device_gone(store: StoreId, device: DeviceId) -> Self {
80        Self(format!("{store}/join-requests/{}/{GONE}", device.0))
81    }
82    /// The invite named by a join request's path.
83    pub fn join_request_invite(&self) -> Option<InviteId> {
84        match self.relative().split('/').collect::<Vec<_>>().as_slice() {
85            ["join-requests", _, GONE] => None,
86            ["join-requests", _, invite] => {
87                Some(InviteId(invite.parse().expect("validated invite id")))
88            }
89            _ => None,
90        }
91    }
92    /// Parse a listed or recorded path without permitting traversal or other layouts.
93    pub fn parse(value: &str) -> Result<Self, PathError> {
94        value.to_owned().try_into()
95    }
96    /// The store whose objects this path names.
97    pub fn store(&self) -> StoreId {
98        store_id(&self.0)
99    }
100    fn relative(&self) -> &str {
101        self.0.split_once('/').expect("validated store path").1
102    }
103    /// The path bound into the object's encryption by the caller.
104    pub fn as_str(&self) -> &str {
105        &self.0
106    }
107    /// Only the floor pointer can be replaced (D10).
108    pub fn is_replaceable(&self) -> bool {
109        self.relative() == "floor"
110    }
111    /// The device named by a snapshot, floor body or uploaded file path.
112    pub fn device(&self) -> Option<DeviceId> {
113        let parts: Vec<_> = self.relative().split('/').collect();
114        match parts.as_slice() {
115            ["files", device, _] | ["floors", device, _] | ["snapshots", _, device, _] => {
116                Some(DeviceId(device.parse().expect("validated device id")))
117            }
118            _ => None,
119        }
120    }
121
122    /// The stored object's id, the last part of a stored file's path.
123    pub fn object_id(&self) -> Option<ObjectId> {
124        match self.relative().split('/').collect::<Vec<_>>().as_slice() {
125            ["files", _, object] => Some(ObjectId(object.parse().expect("validated object id"))),
126            _ => None,
127        }
128    }
129
130    /// The canonical path components, for providers with folder objects.
131    pub fn components(&self) -> Vec<&str> {
132        self.0.split('/').collect()
133    }
134    /// The last path component.
135    pub fn file_name(&self) -> &str {
136        match self.0.rsplit('/').next() {
137            Some(name) => name,
138            None => &self.0,
139        }
140    }
141    /// The provider path with a leading slash.
142    pub fn absolute(&self) -> String {
143        format!("/{}", self.0)
144    }
145}
146
147impl TryFrom<String> for ObjectPath {
148    type Error = PathError;
149    fn try_from(value: String) -> Result<Self, Self::Error> {
150        let (store, relative) = value.split_once('/').ok_or(PathError)?;
151        if !canonical_uuid(store) {
152            return Err(PathError);
153        }
154        let parts: Vec<_> = relative.split('/').collect();
155        let valid = match parts.as_slice() {
156            ["seq", n] => decimal(n, true),
157            ["snapshots", audience, device, n] => {
158                audience.parse::<Audience>().is_ok() && decimal(device, false) && decimal(n, true)
159            }
160            ["floors", device, n] => decimal(device, false) && decimal(n, true),
161            ["files", device, name] => decimal(device, false) && canonical_uuid(name),
162            ["join-requests", device, GONE] => decimal(device, false),
163            ["join-requests", device, invite] => decimal(device, false) && canonical_uuid(invite),
164            ["floor"] => true,
165            _ => false,
166        };
167        if !valid {
168            return Err(PathError);
169        }
170        Ok(Self(value))
171    }
172}
173impl From<ObjectPath> for String {
174    fn from(path: ObjectPath) -> Self {
175        path.0
176    }
177}
178
179/// The last part of a gone device's marker's path.
180const GONE: &str = "gone";
181
182/// A prefix of the validated object layout, used for provider listing.
183#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
184pub struct ObjectPrefix(String);
185impl ObjectPrefix {
186    /// All objects belonging to this store.
187    pub fn all(store: StoreId) -> Self {
188        Self(format!("{store}/"))
189    }
190    /// Every slot of the store's sequence (§5).
191    pub fn slots(store: StoreId) -> Self {
192        Self(format!("{store}/seq/"))
193    }
194    /// Every snapshot, of every audience and device (§16).
195    pub fn snapshots(store: StoreId) -> Self {
196        Self(format!("{store}/snapshots/"))
197    }
198    /// The floor bodies one device wrote (§16.6).
199    pub fn device_floors(store: StoreId, device: DeviceId) -> Self {
200        Self(format!("{store}/floors/{}/", device.0))
201    }
202    /// Every stored file.
203    pub fn files(store: StoreId) -> Self {
204        Self(format!("{store}/files/"))
205    }
206    /// The files one device uploaded (§17.5).
207    pub fn device_files(store: StoreId, device: DeviceId) -> Self {
208        Self(format!("{store}/files/{}/", device.0))
209    }
210    /// The snapshots one device stored of one audience (§16.6).
211    pub fn device_snapshots(store: StoreId, audience: Audience, device: DeviceId) -> Self {
212        Self(format!("{store}/snapshots/{}/{}/", audience, device.0))
213    }
214    /// Every waiting join request.
215    pub fn join_requests(store: StoreId) -> Self {
216        Self(format!("{store}/join-requests/"))
217    }
218    /// The join requests to one device's invites, the markers of its ended
219    /// invites, and its gone marker once it is gone for good (§13.2).
220    pub fn device_join_requests(store: StoreId, device: DeviceId) -> Self {
221        Self(format!("{store}/join-requests/{}/", device.0))
222    }
223    /// The store whose objects this prefix selects.
224    pub fn store(&self) -> StoreId {
225        store_id(&self.0)
226    }
227    /// The prefix supplied to the provider.
228    pub fn as_str(&self) -> &str {
229        &self.0
230    }
231    /// The folder this prefix names, without its closing slash, as a
232    /// provider with folders names it.
233    pub fn folder(&self) -> &str {
234        self.0.trim_end_matches('/')
235    }
236    /// Whether a validated path is under this prefix.
237    pub fn contains(&self, path: &ObjectPath) -> bool {
238        path.0.starts_with(&self.0)
239    }
240}
241
242/// The reserved folder holding one device's upload temporaries and
243/// sessions in a store (D10). It names the device, so whose they are stays
244/// known, and no object path lies under it, so listings of published
245/// objects skip it.
246pub fn device_uploads(store: StoreId, device: DeviceId) -> String {
247    format!("{store}/.coven-uploads/{}", device.0)
248}
249
250/// Validate a provider folder as a strict ancestor of an object in the
251/// layout. Empty folders left by interrupted uploads remain recognizable.
252pub fn validate_directory(value: &str) -> Result<(), PathError> {
253    let mut parts = value.split('/');
254    if !parts.next().is_some_and(canonical_uuid) {
255        return Err(PathError);
256    }
257    let parts: Vec<_> = parts.collect();
258    let valid = match parts.as_slice() {
259        [] => true,
260        ["seq" | "snapshots" | "files" | "floors" | "join-requests"] => true,
261        ["files", device] | ["floors", device] | ["join-requests", device] => {
262            decimal(device, false)
263        }
264        ["snapshots", audience] => audience.parse::<Audience>().is_ok(),
265        ["snapshots", audience, device] => {
266            audience.parse::<Audience>().is_ok() && decimal(device, false)
267        }
268        _ => false,
269    };
270    if !valid {
271        return Err(PathError);
272    }
273    Ok(())
274}
275
276fn store_id(path: &str) -> StoreId {
277    StoreId(
278        path.split_once('/').expect("validated store path").0.parse().expect("validated store id"),
279    )
280}
281
282fn decimal(part: &str, nonzero: bool) -> bool {
283    canonical_decimal(part).is_some_and(|n| !nonzero || n != 0)
284}
285
286/// The number `text` spells in decimal with no sign, padding or leading
287/// zeros (D10), the one spelling coven writes.
288pub(crate) fn canonical_decimal(text: &str) -> Option<u64> {
289    text.parse::<u64>().ok().filter(|n| n.to_string() == text)
290}
291fn canonical_uuid(value: &str) -> bool {
292    coven_foundation::id_source::canonical_uuid(value).is_ok()
293}
294
295/// A path is outside the canonical object layout.
296#[derive(Clone, Copy, Debug, PartialEq, Eq)]
297pub struct PathError;
298impl std::fmt::Display for PathError {
299    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
300        f.write_str("invalid storage path")
301    }
302}
303impl std::error::Error for PathError {}
304
305#[cfg(test)]
306#[path = "path_tests.rs"]
307mod tests;