vstorage 0.8.1

Common API for various icalendar/vcard storages.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
// Copyright 2023-2025 Hugo Osvaldo Barrera
//
// SPDX-License-Identifier: EUPL-1.2

//! Synchronisation operations.
//!
//! The main type is [`Operation`], which represents a single atomic synchronisation action.

use std::sync::Arc;

use crate::{
    Href,
    base::{ItemHash, ItemVersion},
    property::Property,
    sync::{
        conflict::ConflictInfo,
        items::ItemSource,
        mapping::ResolvedMapping,
        ordering::{
            CompletionDroppedError, CompletionHandle, DeletionCompletionHandle, DeletionWaitHandle,
            WaitHandle,
        },
        status::{MappingUid, Side, StatusVersions},
    },
};

/// Operation to be executed on a pair.
#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum Operation {
    /// Flush stale mappings from status database.
    FlushStaleMappings { stale_uids: Vec<MappingUid> },

    /// Collection-level operation
    Collection(CollectionOp),

    /// Item-level operation
    Item(ItemOp),

    /// Property-level operation
    Property(PropertyOp),
}

impl Operation {
    /// Returns true if this operation represents a conflict requiring resolution.
    #[must_use]
    pub fn is_conflict(&self) -> bool {
        matches!(
            self,
            Operation::Item(ItemOp::Conflict { .. })
                | Operation::Property(PropertyOp {
                    kind: PropertyOpKind::Conflict { .. },
                    ..
                })
        )
    }
}

/// Collection-level synchronisation operation.
#[derive(Debug, Clone)]
pub enum CollectionOp {
    /// Save new collection mapping to status database.
    SaveToStatus {
        mapping: Arc<ResolvedMapping>,
        completion: CompletionHandle,
    },

    /// Create collection on one side.
    CreateInOne {
        mapping: Arc<ResolvedMapping>,
        side: Side,
        completion: CompletionHandle,
    },

    /// Create collection on both sides.
    CreateInBoth {
        mapping: Arc<ResolvedMapping>,
        completion: CompletionHandle,
    },

    /// Delete collection (after items removed).
    ///
    /// Guaranteed to be queued after all item operations for this collection.
    /// Execution waits for all item/property operations to complete via the deletion barrier.
    Delete {
        mapping: Arc<ResolvedMapping>,
        mapping_uid: MappingUid,
        side: Side,
        /// Wait handle for deletion barrier - ensures all items/properties complete before deletion.
        wait_for_items: DeletionWaitHandle,
    },

    /// Store sync token for a collection side.
    StoreSyncToken {
        mapping_uid: MappingUidSource,
        side: Side,
        token: String,
        wait_for_items: DeletionWaitHandle,
    },
}

/// Source of mapping UID for item operations.
///
/// The mapping UID may be immediately available (for existing collections)
/// or deferred via a wait handle (for collections being created).
#[derive(Debug, Clone)]
pub enum MappingUidSource {
    /// Mapping UID is immediately available.
    Immediate(MappingUid),
    /// Mapping UID will be provided via wait handle when collection operation completes.
    Deferred(WaitHandle),
}

impl MappingUidSource {
    /// Returns the immediate mapping UID if available, otherwise None.
    #[must_use]
    pub fn immediate(&self) -> Option<MappingUid> {
        match self {
            MappingUidSource::Immediate(uid) => Some(*uid),
            MappingUidSource::Deferred(_) => None,
        }
    }

    /// Returns the wait handle if mapping UID is deferred, otherwise None.
    #[must_use]
    pub fn wait_handle(&self) -> Option<&WaitHandle> {
        match self {
            MappingUidSource::Immediate(_) => None,
            MappingUidSource::Deferred(handle) => Some(handle),
        }
    }

    /// Resolves the mapping UID, waiting if necessary.
    ///
    /// If immediate, returns the UID. If deferred, waits on the handle.
    ///
    /// # Errors
    ///
    /// Returns an error if the completion handle was dropped before signaling.
    pub async fn resolve(self) -> Result<MappingUid, CompletionDroppedError> {
        match self {
            MappingUidSource::Immediate(uid) => Ok(uid),
            MappingUidSource::Deferred(mut handle) => handle.wait().await,
        }
    }
}

/// Storage operation to perform on the target side.
#[derive(Debug, Clone)]
pub enum StorageWrite {
    /// Create a new item in the given collection.
    Create {
        collection: Href,
        resource_name: Option<Href>,
    },
    /// Update an existing item at the given href/etag.
    Update { target: ItemVersion },
}

/// Extract the resource name (last path component) from an href.
pub(super) fn resource_name(href: &str) -> String {
    href.rsplit('/').next().unwrap_or(href).to_string()
}

/// Status database operation to perform after the storage write.
#[derive(Debug, Clone)]
pub enum StatusWrite {
    /// Insert a new entry into the status database.
    Insert,
    /// Update an existing status entry.
    Update { old: StatusVersions },
}

/// Write item to the target side from the source on the opposite side.
#[derive(Debug, Clone)]
pub struct WriteItem {
    /// Data from the source side (the side being read from).
    pub source: ItemSource,
    /// Which side to write to.
    pub target_side: Side,
    pub storage_write: StorageWrite,
    pub status_write: StatusWrite,
    pub mapping_uid: MappingUidSource,
    /// Optional handle to signal collection deletion barrier when this operation completes.
    pub on_complete: Option<DeletionCompletionHandle>,
}

impl From<WriteItem> for ItemOp {
    fn from(inner: WriteItem) -> Self {
        ItemOp::Write(inner)
    }
}

/// Delete item from one side.
#[derive(Debug, Clone)]
pub struct DeleteItem {
    pub target: ItemVersion,
    /// Which side to delete from.
    pub side: Side,
    pub uid: String,
    pub mapping_uid: MappingUidSource,
    /// Optional handle to signal collection deletion barrier when this operation completes.
    pub on_complete: Option<DeletionCompletionHandle>,
}

impl From<DeleteItem> for ItemOp {
    fn from(inner: DeleteItem) -> Self {
        ItemOp::Delete(inner)
    }
}

/// Only update status database (no storage operations).
#[derive(Debug, Clone)]
pub struct StatusOnly {
    pub action: StatusAction,
    pub mapping_uid: MappingUidSource,
    /// Optional handle to signal collection deletion barrier when this operation completes.
    pub on_complete: Option<DeletionCompletionHandle>,
}

impl From<StatusOnly> for ItemOp {
    fn from(inner: StatusOnly) -> Self {
        ItemOp::StatusOnly(inner)
    }
}

/// Item-level synchronisation operation.
#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum ItemOp {
    /// Write item to one side from source on the other.
    ///
    /// If collection creation is pending, the mapping UID will be received via a wait handle.
    Write(WriteItem),

    /// Delete item from one side.
    Delete(DeleteItem),

    /// Only update status database (no storage operations).
    StatusOnly(StatusOnly),

    /// Conflict requiring resolution.
    Conflict {
        info: ConflictInfo,
        mapping: Arc<ResolvedMapping>,
        mapping_uid: MappingUidSource,
        /// Signal collection deletion barrier when this operation completes.
        /// Only meaningful if some form of auto-resolution is in use.
        on_complete: Option<DeletionCompletionHandle>,
    },
}

impl ItemOp {
    /// Returns the wait handle that must be awaited before executing this operation, if any.
    #[must_use]
    pub fn wait_handle(&self) -> Option<&WaitHandle> {
        match self {
            ItemOp::Write(inner) => inner.mapping_uid.wait_handle(),
            ItemOp::StatusOnly(inner) => inner.mapping_uid.wait_handle(),
            _ => None,
        }
    }

    /// Returns the item UID for this operation, if applicable.
    #[must_use]
    pub fn uid(&self) -> Option<&str> {
        match self {
            ItemOp::Write(inner) => Some(&inner.source.state.uid),
            ItemOp::Delete(inner) => Some(&inner.uid),
            ItemOp::StatusOnly(inner) => match &inner.action {
                StatusAction::Insert { uid, .. } | StatusAction::Clear { uid } => Some(uid),
                StatusAction::Update { .. } => None,
            },
            ItemOp::Conflict { info, .. } => Some(&info.a.state.uid),
        }
    }

    /// Returns the mapping UID source for this operation.
    #[must_use]
    pub fn mapping_uid(&self) -> MappingUidSource {
        match self {
            ItemOp::Write(inner) => inner.mapping_uid.clone(),
            ItemOp::Delete(inner) => inner.mapping_uid.clone(),
            ItemOp::StatusOnly(inner) => inner.mapping_uid.clone(),
            ItemOp::Conflict { mapping_uid, .. } => mapping_uid.clone(),
        }
    }
}

/// Actions that only affect the status database.
#[derive(PartialEq, Debug, Clone)]
pub enum StatusAction {
    /// Item is new and identical on both sides.
    Insert {
        uid: String,
        hash: ItemHash,
        versions: StatusVersions,
    },
    /// Item has changed on both sides but remains in sync.
    Update {
        hash: ItemHash,
        old: StatusVersions,
        new: StatusVersions,
    },
    /// Item is gone from both sides but still present in status db.
    Clear { uid: String },
}

impl std::fmt::Display for StatusAction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            StatusAction::Insert { uid, .. } => write!(f, "save to status (uid: {uid})"),
            StatusAction::Update { old, .. } => {
                write!(f, "update in status (a.href: {})", old.a.href)
            }
            StatusAction::Clear { uid } => write!(f, "clear from status (uid: {uid})"),
        }
    }
}

/// Property-level synchronisation operation.
#[derive(Debug, Clone)]
pub struct PropertyOp {
    pub property: Property,
    pub mapping: Arc<ResolvedMapping>,
    pub mapping_uid: MappingUidSource,
    /// Optional handle to signal collection deletion barrier when this operation completes.
    pub on_complete: Option<DeletionCompletionHandle>,
    pub kind: PropertyOpKind,
}

/// The specific kind of property operation.
#[derive(Debug, Clone)]
pub enum PropertyOpKind {
    /// Write property to one side.
    Write { value: String, side: Side },

    /// Delete property from one side.
    Delete { side: Side },

    /// Clear property from status database.
    ClearStatus,

    /// Update property in status database.
    UpdateStatus { value: String },

    /// Property has conflicting values.
    Conflict { value_a: String, value_b: String },
}

impl std::fmt::Display for CollectionOp {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CollectionOp::SaveToStatus { mapping, .. } => {
                write!(f, "save collection '{}' to status", mapping.alias())
            }
            CollectionOp::CreateInOne { mapping, side, .. } => {
                let alias = mapping.alias();
                write!(f, "create collection '{alias}' in storage {side}")
            }
            CollectionOp::CreateInBoth { mapping, .. } => {
                let alias = mapping.alias();
                write!(f, "create collection '{alias}' in both storages")
            }
            CollectionOp::Delete { mapping, side, .. } => {
                let alias = mapping.alias();
                write!(f, "delete collection '{alias}' from storage {side}")
            }
            CollectionOp::StoreSyncToken {
                mapping_uid, side, ..
            } => {
                write!(
                    f,
                    "store sync token for collection (uid: {mapping_uid:?}) side {side}"
                )
            }
        }
    }
}

impl std::fmt::Display for ItemOp {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ItemOp::Write(inner) => {
                let side = inner.target_side;
                match &inner.storage_write {
                    StorageWrite::Create { .. } => write!(f, "write to {side} (create new)"),
                    StorageWrite::Update { .. } => write!(f, "write to {side} (update existing)"),
                }
            }
            ItemOp::Delete(inner) => {
                write!(f, "delete from {}", inner.side)
            }
            ItemOp::StatusOnly(_) => {
                write!(f, "status only")
            }
            ItemOp::Conflict { .. } => {
                write!(f, "conflict")
            }
        }
    }
}

impl std::fmt::Display for PropertyOp {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.kind {
            PropertyOpKind::Write { value, side } => {
                write!(f, "write to {side} (value: {value:?})")
            }
            PropertyOpKind::Delete { side } => {
                write!(f, "delete from {side}")
            }
            PropertyOpKind::ClearStatus => {
                write!(f, "clear from status")
            }
            PropertyOpKind::UpdateStatus { value } => {
                write!(f, "update in status (value: {value:?})")
            }
            PropertyOpKind::Conflict { value_a, value_b } => {
                write!(f, "conflict (a: {value_a:?}, b: {value_b:?})")
            }
        }
    }
}