vstorage 0.10.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
// Copyright 2025-2026 Hugo Osvaldo Barrera
//
// SPDX-License-Identifier: EUPL-1.2

//! Resolve conflicts during synchronisation.

use std::sync::Arc;

use futures_util::{Stream, StreamExt as _};

use crate::{
    Href,
    property::Property,
    sync::{
        Side,
        items::ItemWithData,
        mapping::ResolvedMapping,
        operation::{
            ItemOp, MappingUidSource, Operation, PropertyOp, PropertyOpKind, StatusWrite,
            StorageWrite, WriteItem,
        },
        plan::PlanError,
        status::{MappingUid, StatusVersions},
    },
};

/// Wrap a stream of operations to automatically resolve conflicts.
///
/// Takes a stream that may contain conflict operations and a conflict resolver,
/// and returns a new stream where all conflicts have been replaced with resolved operations.
pub fn resolve_conflicts<S, R>(
    operations: S,
    resolver: R,
) -> impl Stream<Item = Result<Operation, PlanError>>
where
    S: Stream<Item = Result<Operation, PlanError>>,
    R: ConflictResolver + Clone + 'static,
{
    operations.then(move |result| {
        let resolver = resolver.clone();
        async move {
            match result {
                Ok(operation) => match operation {
                    Operation::Item(ItemOp::Conflict {
                        info, mapping_uid, ..
                    }) => match mapping_uid.resolve().await {
                        Ok(uid) => Ok(Operation::Item(resolver.resolve_item(info, uid))),
                        Err(err) => Err(PlanError::from(err)),
                    },
                    Operation::Property(PropertyOp {
                        kind: PropertyOpKind::Conflict { value_a, value_b },
                        property,
                        mapping,
                        mapping_uid,
                        ..
                    }) => match mapping_uid.resolve().await {
                        Ok(uid) => Ok(Operation::Property(
                            resolver.resolve_property(property, value_a, value_b, mapping, uid),
                        )),
                        Err(err) => Err(PlanError::from(err)),
                    },
                    // Pass through non-conflict operations unchanged
                    op => Ok(op),
                },
                Err(e) => Err(e),
            }
        }
    })
}

/// Conflict information for items that have diverged.
#[derive(PartialEq, Debug, Clone)]
pub struct ConflictInfo {
    pub a: ItemWithData,
    pub b: ItemWithData,
    pub old: Option<StatusVersions>,
    pub collection_a: Href,
    pub collection_b: Href,
}

/// Trait for resolving conflicts in operation streams.
pub trait ConflictResolver: Send + Sync {
    /// Resolve an item conflict, returning the resolved operation.
    ///
    /// The returned operation must be an [`ItemOp`] variant that performs
    /// the appropriate sync action  based on the resolution strategy.
    fn resolve_item(&self, conflict: ConflictInfo, mapping_uid: MappingUid) -> ItemOp;

    /// Resolve a property conflict.
    ///
    /// The returned operation must be a `PropertyOp` variant that writes
    /// or deletes the property based on the resolution strategy.
    fn resolve_property(
        &self,
        property: Property,
        value_a: String,
        value_b: String,
        mapping: Arc<ResolvedMapping>,
        mapping_uid: MappingUid,
    ) -> PropertyOp;
}

/// Conflict resolver that always keeps the specified side.
///
/// Treats the given side as the authoritative source and updates the other side to match it.
#[derive(Debug, Clone, Copy)]
pub struct KeepSideResolver(pub Side);

impl ConflictResolver for KeepSideResolver {
    fn resolve_item(&self, conflict: ConflictInfo, mapping_uid: MappingUid) -> ItemOp {
        let (source, target_version, target_side) = match self.0 {
            Side::A => (conflict.a, conflict.b.state.version, Side::B),
            Side::B => (conflict.b, conflict.a.state.version, Side::A),
        };
        let (storage_write, status_write) = match conflict.old {
            Some(old) => (
                StorageWrite::Update {
                    target: old.for_side(target_side).clone(),
                },
                StatusWrite::Update { old },
            ),
            None => (
                StorageWrite::Update {
                    target: target_version,
                },
                StatusWrite::Insert,
            ),
        };
        ItemOp::Write(WriteItem {
            source: source.into(),
            target_side,
            storage_write,
            status_write,
            mapping_uid: MappingUidSource::Immediate(mapping_uid),
            on_complete: None,
        })
    }

    fn resolve_property(
        &self,
        property: Property,
        value_a: String,
        value_b: String,
        mapping: Arc<ResolvedMapping>,
        mapping_uid: MappingUid,
    ) -> PropertyOp {
        let (value, side) = match self.0 {
            Side::A => (value_a, Side::B),
            Side::B => (value_b, Side::A),
        };
        PropertyOp {
            property,
            mapping,
            mapping_uid: MappingUidSource::Immediate(mapping_uid),
            on_complete: None,
            kind: PropertyOpKind::Write { value, side },
        }
    }
}

#[cfg(test)]
mod test {
    use std::{str::FromStr, sync::Arc};

    use futures_util::stream::StreamExt;
    use tempfile::Builder;

    use crate::{
        CollectionId, ItemKind,
        sync::{
            Side,
            declare::{OnEmpty, StoragePair, SyncedCollection},
            operation::{CollectionOp, ItemOp, Operation},
            plan::Plan,
        },
        vdir::VdirStorage,
    };

    #[tokio::test]
    async fn test_stream_no_mappings() {
        let dir_a = Builder::new().prefix("vstorage").tempdir().unwrap();
        let dir_b = Builder::new().prefix("vstorage").tempdir().unwrap();

        let storage_a = Arc::new(
            VdirStorage::builder(dir_a.path().to_path_buf().try_into().unwrap())
                .unwrap()
                .build(ItemKind::Calendar),
        );
        let storage_b = Arc::from(
            VdirStorage::builder(dir_b.path().to_path_buf().try_into().unwrap())
                .unwrap()
                .build(ItemKind::Calendar),
        );

        // This sync would be a no-op, but it's not "wrong".
        let pair = StoragePair::new(storage_a.clone(), storage_b.clone());
        let stream = Plan::new(pair, None).await.unwrap();

        let operations: Vec<_> = stream.collect::<Vec<_>>().await;
        assert_eq!(operations.len(), 0);
    }

    #[tokio::test]
    async fn test_stream_simple_mapping() {
        let dir_a = Builder::new().prefix("vstorage").tempdir().unwrap();
        let dir_b = Builder::new().prefix("vstorage").tempdir().unwrap();

        let storage_a = Arc::new(
            VdirStorage::builder(dir_a.path().to_path_buf().try_into().unwrap())
                .unwrap()
                .build(ItemKind::Calendar),
        );
        let storage_b = Arc::from(
            VdirStorage::builder(dir_b.path().to_path_buf().try_into().unwrap())
                .unwrap()
                .build(ItemKind::Calendar),
        );

        // This sync has a single direct collection mapping.
        let collection = CollectionId::from_str("test").unwrap();
        let pair = StoragePair::new(storage_a.clone(), storage_b.clone())
            .with_mapping(SyncedCollection::direct(collection));

        let stream = Plan::new(pair, None).await.unwrap();

        let operations: Vec<_> = stream.collect::<Vec<_>>().await;
        assert!(!operations.is_empty());

        let first = operations.first().unwrap();
        assert!(matches!(first, Ok(Operation::Collection(_))));
    }

    #[tokio::test]
    async fn test_collection_creation_before_items() {
        let dir_a = Builder::new().prefix("vstorage").tempdir().unwrap();
        let dir_b = Builder::new().prefix("vstorage").tempdir().unwrap();

        let storage_a = Arc::new(
            VdirStorage::builder(dir_a.path().to_path_buf().try_into().unwrap())
                .unwrap()
                .build(ItemKind::Calendar),
        );
        let storage_b = Arc::from(
            VdirStorage::builder(dir_b.path().to_path_buf().try_into().unwrap())
                .unwrap()
                .build(ItemKind::Calendar),
        );

        // Create collection on side A with an item
        let collection_id = CollectionId::from_str("test").unwrap();
        let collection_path = dir_a.path().join("test");
        std::fs::create_dir(&collection_path).unwrap();

        // Add an item to the collection
        std::fs::write(
            collection_path.join("item.ics"),
            [
                "BEGIN:VCALENDAR",
                "VERSION:2.0",
                "BEGIN:VEVENT",
                "UID:test-item",
                "DTSTART:20240101T120000Z",
                "END:VEVENT",
                "END:VCALENDAR",
                "",
            ]
            .join("\r\n"),
        )
        .unwrap();

        // Collection doesn't exist on side B, so it needs to be created
        let pair = StoragePair::new(storage_a.clone(), storage_b.clone())
            .with_mapping(SyncedCollection::direct(collection_id));

        let stream = Plan::new(pair, None).await.unwrap();
        let operations: Vec<_> = stream.collect::<Vec<_>>().await;

        // Find positions of collection creation and item operations
        let mut collection_create_pos = None;
        let mut first_item_pos = None;

        for (i, op_result) in operations.iter().enumerate() {
            if let Ok(op) = op_result {
                match op {
                    Operation::Collection(
                        CollectionOp::CreateInOne { .. } | CollectionOp::CreateInBoth { .. },
                    ) => {
                        assert!(
                            collection_create_pos.replace(i).is_none(),
                            "more than one collection creation event"
                        );
                    }
                    Operation::Item(ItemOp::Write(w)) if w.target_side == Side::B => {
                        assert!(
                            first_item_pos.replace(i).is_none(),
                            "more than one item write event"
                        );
                    }
                    _ => {}
                }
            }
        }

        let coll_pos = collection_create_pos.unwrap();
        let item_pos = first_item_pos.unwrap();
        assert!(coll_pos < item_pos);
    }

    #[tokio::test]
    async fn test_collection_deletion_after_items() {
        use crate::sync::status::StatusDatabase;

        let dir_a = Builder::new().prefix("vstorage").tempdir().unwrap();
        let dir_b = Builder::new().prefix("vstorage").tempdir().unwrap();
        let db_path = Builder::new().prefix("vstorage").tempdir().unwrap();

        let storage_a = Arc::new(
            VdirStorage::builder(dir_a.path().to_path_buf().try_into().unwrap())
                .unwrap()
                .build(ItemKind::Calendar),
        );
        let storage_b = Arc::from(
            VdirStorage::builder(dir_b.path().to_path_buf().try_into().unwrap())
                .unwrap()
                .build(ItemKind::Calendar),
        );

        let collection_id = CollectionId::from_str("test").unwrap();
        let collection_path = dir_b.path().join("test");
        std::fs::create_dir(&collection_path).unwrap();

        std::fs::write(
            collection_path.join("item.ics"),
            [
                "BEGIN:VCALENDAR",
                "VERSION:2.0",
                "BEGIN:VEVENT",
                "UID:test-item",
                "DTSTART:20240101T120000Z",
                "END:VEVENT",
                "END:VCALENDAR",
                "",
            ]
            .join("\r\n"),
        )
        .unwrap();

        // Create status database and record the collection + item as previously synced.
        let status_path = db_path.path().join("status.db");
        let status = Arc::new(StatusDatabase::open_or_create(&status_path).unwrap());

        // Set up the pair with the collection mapping.
        let pair = StoragePair::new(storage_a.clone(), storage_b.clone())
            .with_mapping(SyncedCollection::direct(collection_id.clone()))
            .on_empty(OnEmpty::Sync);

        // First sync: establish the collection and item in status database
        {
            use crate::sync::execute::Executor;
            let mut stream = Plan::new(pair.clone(), Some(status.clone())).await.unwrap();
            let executor = Executor::new(storage_a.clone(), storage_b.clone(), status.clone());
            while let Some(op_result) = stream.next().await {
                let op = op_result.unwrap();
                executor.execute_operation(op).await.unwrap().unwrap();
            }
        }

        // Simulate out-of-band deletion from side B only.
        std::fs::remove_dir_all(&collection_path).unwrap();

        // Second sync: should delete items first, then collection.
        let stream = Plan::new(pair, Some(status)).await.unwrap();
        let operations: Vec<_> = stream.collect::<Vec<_>>().await;

        let mut first_item_delete_pos = None;
        let mut collection_delete_pos = None;

        for (i, op_result) in operations.iter().enumerate() {
            if let Ok(op) = op_result {
                match op {
                    Operation::Item(ItemOp::Delete(d))
                        if d.side == Side::A && first_item_delete_pos.is_none() =>
                    {
                        first_item_delete_pos = Some(i);
                    }
                    Operation::Collection(CollectionOp::Delete { .. })
                        if collection_delete_pos.is_none() =>
                    {
                        collection_delete_pos = Some(i);
                    }
                    _ => {}
                }
            }
        }

        let item_pos = first_item_delete_pos.unwrap();
        let coll_pos = collection_delete_pos.unwrap();
        assert!(
            item_pos < coll_pos,
            "Item deletion (pos {item_pos}) must come before collection deletion (pos {coll_pos})"
        );
    }
}