vstorage 0.6.0

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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
// 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;
use crate::base::{ItemVersion, Property};
use crate::sync::analysis::{ItemSource, ResolvedMapping, StatusAction};
use crate::sync::conflict::ConflictInfo;
use crate::sync::ordering::CompletionDroppedError;
use crate::sync::status::StatusVersions;

use super::ordering::{CompletionHandle, DeletionCompletionHandle, DeletionWaitHandle, WaitHandle};
use super::status::{MappingUid, Side};

/// 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::PropertyConflict { .. })
        )
    }
}

/// 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,
    },

    /// Collection requires no action (already in sync).
    NoAction { mapping_uid: MappingUid },

    /// 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,
        }
    }
}

/// Specifies how a write operation should interact with storage and status database.
#[derive(Debug, Clone)]
pub enum WriteMode {
    /// Create new item in collection, insert into status database.
    CreateNew { collection: Href },

    /// Create new item in collection, update existing status entry.
    CreateRefresh {
        collection: Href,
        old: StatusVersions,
    },

    /// Update existing item, insert into status database.
    /// Used for first sync, [`OneWaySync`](super::one_way::OneWaySync) or conflict resolution.
    UpdateNew { target: ItemVersion },

    /// Update existing item, update existing status entry.
    UpdateExisting { old: StatusVersions },

    /// Update existing item which does not match the status entry.
    /// Use for conflict resolution or [`OneWaySync`](super::one_way::OneWaySync) sync.
    UpdateForce {
        target: ItemVersion,
        old: StatusVersions,
    },
}

/// Write item to storage A from source in storage B.
#[derive(Debug, Clone)]
pub struct WriteInA {
    pub source_b: ItemSource,
    pub mode: WriteMode,
    pub mapping_uid: MappingUidSource,
    /// Optional handle to signal collection deletion barrier when this operation completes.
    pub on_complete: Option<DeletionCompletionHandle>,
}

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

/// Write item to storage B from source in storage A.
#[derive(Debug, Clone)]
pub struct WriteInB {
    pub source_a: ItemSource,
    pub mode: WriteMode,
    pub mapping_uid: MappingUidSource,
    /// Optional handle to signal collection deletion barrier when this operation completes.
    pub on_complete: Option<DeletionCompletionHandle>,
}

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

/// Delete item from storage A.
#[derive(Debug, Clone)]
pub struct DeleteA {
    pub target_a: ItemVersion,
    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<DeleteA> for ItemOp {
    fn from(inner: DeleteA) -> Self {
        ItemOp::DeleteA(inner)
    }
}

/// Delete item from storage B.
#[derive(Debug, Clone)]
pub struct DeleteB {
    pub target_b: ItemVersion,
    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<DeleteB> for ItemOp {
    fn from(inner: DeleteB) -> Self {
        ItemOp::DeleteB(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 storage A from source in B.
    ///
    /// If collection creation is pending, `wait_for` will receive the mapping UID when it completes.
    WriteInA(WriteInA),

    /// Write item to storage B from source in A.
    ///
    /// If collection creation is pending, `wait_for` will receive the mapping UID when it completes.
    WriteInB(WriteInB),

    /// Delete item from storage A.
    DeleteA(DeleteA),

    /// Delete item from storage B.
    DeleteB(DeleteB),

    /// 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.
        deletion_completion: 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::WriteInA(inner) => inner.mapping_uid.wait_handle(),
            ItemOp::WriteInB(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::WriteInA(inner) => Some(&inner.source_b.state.uid),
            ItemOp::WriteInB(inner) => Some(&inner.source_a.state.uid),
            ItemOp::DeleteA(inner) => Some(&inner.uid),
            ItemOp::DeleteB(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::WriteInA(inner) => inner.mapping_uid.clone(),
            ItemOp::WriteInB(inner) => inner.mapping_uid.clone(),
            ItemOp::DeleteA(inner) => inner.mapping_uid.clone(),
            ItemOp::DeleteB(inner) => inner.mapping_uid.clone(),
            ItemOp::StatusOnly(inner) => inner.mapping_uid.clone(),
            ItemOp::Conflict { mapping_uid, .. } => mapping_uid.clone(),
        }
    }
}

/// Property-level synchronisation operation.
#[derive(Debug, Clone)]
pub enum PropertyOp {
    /// Write property to one side.
    Write {
        property: Property,
        value: String,
        side: Side,
        mapping: Arc<ResolvedMapping>,
        mapping_uid: MappingUidSource,
        /// Optional handle to signal collection deletion barrier when this operation completes.
        deletion_completion: Option<DeletionCompletionHandle>,
    },

    /// Delete property from one side.
    Delete {
        property: Property,
        side: Side,
        mapping: Arc<ResolvedMapping>,
        mapping_uid: MappingUidSource,
        /// Optional handle to signal collection deletion barrier when this operation completes.
        deletion_completion: Option<DeletionCompletionHandle>,
    },

    /// Clear property from status database.
    ClearStatus {
        property: Property,
        mapping: Arc<ResolvedMapping>,
        mapping_uid: MappingUidSource,
        /// Optional handle to signal collection deletion barrier when this operation completes.
        deletion_completion: Option<DeletionCompletionHandle>,
    },

    /// Update property in status database.
    UpdateStatus {
        property: Property,
        value: String,
        mapping: Arc<ResolvedMapping>,
        mapping_uid: MappingUidSource,
        /// Optional handle to signal collection deletion barrier when this operation completes.
        deletion_completion: Option<DeletionCompletionHandle>,
    },

    /// Property has conflicting values.
    PropertyConflict {
        property: Property,
        value_a: String,
        value_b: String,
        mapping: Arc<ResolvedMapping>,
        mapping_uid: MappingUidSource,
        /// Optional handle to signal collection deletion barrier when this operation completes.
        deletion_completion: Option<DeletionCompletionHandle>,
    },
}

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::NoAction { mapping_uid } => {
                write!(f, "no action for collection (uid: {mapping_uid:?})")
            }
            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::WriteInA(inner) => {
                let uid = &inner.source_b.state.uid;
                match &inner.mode {
                    WriteMode::CreateNew { .. } | WriteMode::CreateRefresh { .. } => {
                        write!(f, "create in storage A (uid: {uid})")
                    }
                    WriteMode::UpdateNew { .. }
                    | WriteMode::UpdateExisting { .. }
                    | WriteMode::UpdateForce { .. } => {
                        write!(f, "update in storage A (uid: {uid})")
                    }
                }
            }
            ItemOp::WriteInB(inner) => {
                let uid = &inner.source_a.state.uid;
                match &inner.mode {
                    WriteMode::CreateNew { .. } | WriteMode::CreateRefresh { .. } => {
                        write!(f, "create in storage B (uid: {uid})")
                    }
                    WriteMode::UpdateNew { .. }
                    | WriteMode::UpdateExisting { .. }
                    | WriteMode::UpdateForce { .. } => {
                        write!(f, "update in storage B (uid: {uid})")
                    }
                }
            }
            ItemOp::DeleteA(inner) => {
                write!(f, "delete from storage A (uid: {})", inner.uid)
            }
            ItemOp::DeleteB(inner) => {
                write!(f, "delete from storage B (uid: {})", inner.uid)
            }
            ItemOp::StatusOnly(inner) => {
                write!(f, "status only: {}", inner.action)
            }
            ItemOp::Conflict { info, .. } => {
                write!(f, "conflict (uid: {})", info.a.state.uid)
            }
        }
    }
}

impl std::fmt::Display for PropertyOp {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PropertyOp::Write {
                property,
                value,
                side,
                mapping,
                ..
            } => {
                let alias = mapping.alias();
                write!(
                    f,
                    "write property {property:?} to storage {side} on collection '{alias}': {value}",
                )
            }
            PropertyOp::Delete {
                property,
                side,
                mapping,
                ..
            } => {
                let alias = mapping.alias();
                write!(
                    f,
                    "delete property {property:?} from storage {side} on collection '{alias}'",
                )
            }
            PropertyOp::ClearStatus {
                property, mapping, ..
            } => {
                let alias = mapping.alias();
                write!(
                    f,
                    "clear property {property:?} from status for collection '{alias}'",
                )
            }
            PropertyOp::UpdateStatus {
                property, mapping, ..
            } => {
                let alias = mapping.alias();
                write!(
                    f,
                    "update property {property:?} in status for collection '{alias}'",
                )
            }
            PropertyOp::PropertyConflict {
                property, mapping, ..
            } => {
                let alias = mapping.alias();
                write!(f, "property {property:?} conflict on collection '{alias}'")
            }
        }
    }
}