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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
// Copyright 2023-2026 Hugo Osvaldo Barrera
//
// SPDX-License-Identifier: EUPL-1.2

//! Collection operation generation.

use std::collections::HashMap;
use std::sync::Arc;

use log::warn;

use crate::ErrorKind;
use crate::property::Property;
use crate::sync::items::SideState;
use crate::sync::mapping::ResolvedMapping;
use crate::sync::operation::PropertyOp;
use crate::sync::{Mode, Side};
use crate::sync::{
    declare::{OnDelete, OnEmpty, StoragePair},
    operation::{CollectionOp, MappingUidSource, Operation},
    ordering::{DeletionBarrier, completion_pair},
    status::{MappingUid, StatusDatabase, StatusError},
};

use tokio::sync::mpsc::Sender;

use super::{PlanError, items::items_for_collection};

/// Error during plan generation for a single collection.
#[derive(Debug, thiserror::Error)]
pub(super) enum GenerateError {
    /// A genuine error planning operations for this collection.
    #[error(transparent)]
    Plan(#[from] PlanError),
    /// The receiver was dropped; the task should exit cleanly.
    #[error("receiver dropped")]
    ChannelClosed,
}

impl From<StatusError> for GenerateError {
    fn from(e: StatusError) -> Self {
        GenerateError::Plan(e.into())
    }
}

/// Send a single operation into the channel.
async fn send_op(
    tx: &Sender<Result<Operation, PlanError>>,
    op: Operation,
) -> Result<(), GenerateError> {
    tx.send(Ok(op))
        .await
        .map_err(|_| GenerateError::ChannelClosed)
}

/// Generate all operations for a single collection and send them into the channel.
///
/// Returns `Ok(())` when the collection is fully processed or the receiver has been dropped.
/// Returns `Err` only for fatal errors (storage or status database failures).
#[allow(clippy::too_many_lines)]
pub(super) async fn generate_collection_operations(
    tx: &Sender<Result<Operation, PlanError>>,
    pair: &StoragePair,
    mapping: Arc<ResolvedMapping>,
    status: Option<&StatusDatabase>,
) -> Result<(), GenerateError> {
    let mapping_uid = status
        .map(|s| s.get_mapping_uid(mapping.a().href(), mapping.b().href()))
        .transpose()?
        .flatten();

    let (result_a, result_b) = tokio::try_join!(
        items_for_collection(
            status,
            pair.storage_a().as_ref(),
            mapping.a().href(),
            Side::A,
            mapping_uid
        ),
        items_for_collection(
            status,
            pair.storage_b().as_ref(),
            mapping.b().href(),
            Side::B,
            mapping_uid
        ),
    )?;

    let items_a = result_a.items;
    let items_b = result_b.items;
    let new_sync_token_a = result_a.new_sync_token;
    let new_sync_token_b = result_b.new_sync_token;

    let status_uids = match (status, mapping_uid) {
        (Some(s), Some(m)) => {
            let uids = s.all_uids(m)?;
            if !uids.is_empty() && pair.on_empty == OnEmpty::Skip {
                // Status has entries and we've been told to skip emptying.
                if items_a.is_empty() && !items_b.is_empty() {
                    warn!(
                        "Collection {} has been emptied on storage a.",
                        mapping.alias
                    );
                    return Ok(());
                }
                if !items_a.is_empty() && items_b.is_empty() {
                    warn!(
                        "Collection {} has been emptied on storage b.",
                        mapping.alias
                    );
                    return Ok(());
                }
            }
            uids
        }
        _ => Vec::new(),
    };

    let CollectionPlan {
        op,
        deletion,
        deletion_barrier,
        mapping_uid_source,
    } = determine_collection_operation(
        result_a.exists,
        result_b.exists,
        mapping_uid,
        pair.on_delete,
        mapping.clone(),
    );

    // Ensure that tokens are only applied after all other collection operations.
    let deletion_barrier = deletion_barrier.or_else(|| {
        if new_sync_token_a.is_some() || new_sync_token_b.is_some() {
            Some(DeletionBarrier::new())
        } else {
            None
        }
    });

    // Implicitly deduplicate UIDs across both sides and status.
    let mut items_by_uid = HashMap::<String, (Option<SideState>, Option<SideState>)>::new();
    for item in items_a {
        let uid = item.state().uid.clone();
        items_by_uid.entry(uid).or_default().0 = Some(item);
    }
    for item in items_b {
        let uid = item.state().uid.clone();
        items_by_uid.entry(uid).or_default().1 = Some(item);
    }
    for uid in status_uids {
        items_by_uid.entry(uid).or_default();
    }

    if let Some(op) = op {
        send_op(tx, Operation::Collection(op)).await?;
    }

    for (uid, (side_a, side_b)) in items_by_uid {
        let previous = match (status, mapping_uid_source.immediate()) {
            (Some(s), Some(m)) => s.get_item_hash_by_uid(m, &uid)?,
            _ => None,
        };

        if let Some(item_op) = pair.mode.decide_item_action(
            side_a,
            side_b,
            previous,
            &mapping,
            mapping_uid_source.clone(),
            deletion_barrier.as_ref(),
        ) {
            send_op(tx, Operation::Item(item_op)).await?;
        }
    }

    let skip_properties = deletion.is_some();
    if !skip_properties {
        let props = generate_property_operations(
            &mapping,
            &mapping_uid_source,
            pair,
            status,
            deletion_barrier.as_ref(),
            &*pair.mode,
        )
        .await?;

        for op in props {
            send_op(tx, Operation::Property(op)).await?;
        }
    }

    // Sync token ops (barrier is guaranteed to exist when tokens are present).
    if let Some(barrier) = deletion_barrier.as_ref() {
        if let Some(token) = new_sync_token_a {
            let op = Operation::Collection(CollectionOp::StoreSyncToken {
                mapping_uid: mapping_uid_source.clone(),
                side: Side::A,
                token,
                wait_for_items: barrier.wait_handle(),
            });
            send_op(tx, op).await?;
        }
        if let Some(token) = new_sync_token_b {
            let op = Operation::Collection(CollectionOp::StoreSyncToken {
                mapping_uid: mapping_uid_source.clone(),
                side: Side::B,
                token,
                wait_for_items: barrier.wait_handle(),
            });
            send_op(tx, op).await?;
        }
    }

    // Collection deletion.
    if let Some(op) = deletion {
        send_op(tx, Operation::Collection(op)).await?;
    }

    Ok(())
}

/// Decision about what operations are needed for a collection.
/// This is a simple data-holder for passing around data.
struct CollectionPlan {
    /// None if no-op or in case of deletion.
    op: Option<CollectionOp>,
    /// None unless this is a deletion scenario.
    deletion: Option<CollectionOp>,
    /// Barrier for coordinating deletion with item/property operations.
    /// None unless this is a deletion scenario.
    deletion_barrier: Option<DeletionBarrier>,
    /// Source of mapping UID for items in this collection.
    mapping_uid_source: MappingUidSource,
}

/// Determine the collection operation plan based on current state.
#[allow(clippy::too_many_lines)]
fn determine_collection_operation(
    a_exists: bool,
    b_exists: bool,
    mapping_uid: Option<MappingUid>,
    on_delete: OnDelete,
    mapping: Arc<ResolvedMapping>,
) -> CollectionPlan {
    match (a_exists, b_exists, mapping_uid) {
        // Both missing: create on both sides.
        (false, false, _) => {
            let (completion, wait) = completion_pair();
            CollectionPlan {
                op: Some(CollectionOp::CreateInBoth {
                    mapping,
                    completion,
                }),
                deletion: None,
                deletion_barrier: None,
                mapping_uid_source: MappingUidSource::Deferred(wait),
            }
        }
        // Both exist and are new: save to status.
        (true, true, None) => {
            let (completion, wait) = completion_pair();
            CollectionPlan {
                op: Some(CollectionOp::SaveToStatus {
                    mapping,
                    completion,
                }),
                deletion: None,
                deletion_barrier: None,
                mapping_uid_source: MappingUidSource::Deferred(wait),
            }
        }
        // Both exist, already in status: noop.
        (true, true, Some(m)) => CollectionPlan {
            op: None,
            deletion: None,
            deletion_barrier: None,
            mapping_uid_source: MappingUidSource::Immediate(m),
        },

        // Deleted from A (exists in B): delete from B.
        (false, true, Some(m)) => {
            if on_delete == OnDelete::Skip {
                CollectionPlan {
                    op: None,
                    deletion: None,
                    deletion_barrier: None,
                    mapping_uid_source: MappingUidSource::Immediate(m),
                }
            } else {
                let barrier = DeletionBarrier::new();
                let wait_handle = barrier.wait_handle();

                CollectionPlan {
                    op: None,
                    deletion: Some(CollectionOp::Delete {
                        mapping,
                        mapping_uid: m,
                        side: Side::B,
                        wait_for_items: wait_handle,
                    }),
                    deletion_barrier: Some(barrier),
                    mapping_uid_source: MappingUidSource::Immediate(m),
                }
            }
        }
        // New in B only: create in A.
        (false, true, None) => {
            let (completion, wait) = completion_pair();
            CollectionPlan {
                op: Some(CollectionOp::CreateInOne {
                    mapping,
                    side: Side::A,
                    completion,
                }),
                deletion: None,
                deletion_barrier: None,
                mapping_uid_source: MappingUidSource::Deferred(wait),
            }
        }
        // New in A only: create in B.
        (true, false, None) => {
            let (completion, wait) = completion_pair();
            CollectionPlan {
                op: Some(CollectionOp::CreateInOne {
                    mapping,
                    side: Side::B,
                    completion,
                }),
                deletion: None,
                deletion_barrier: None,
                mapping_uid_source: MappingUidSource::Deferred(wait),
            }
        }
        // Deleted from B (exists in A): delete from A.
        (true, false, Some(m)) => {
            if on_delete == OnDelete::Skip {
                CollectionPlan {
                    op: None,
                    deletion: None,
                    deletion_barrier: None,
                    mapping_uid_source: MappingUidSource::Immediate(m),
                }
            } else {
                let barrier = DeletionBarrier::new();
                let wait_handle = barrier.wait_handle();

                CollectionPlan {
                    op: None,
                    deletion: Some(CollectionOp::Delete {
                        mapping,
                        mapping_uid: m,
                        side: Side::A,
                        wait_for_items: wait_handle,
                    }),
                    deletion_barrier: Some(barrier),
                    mapping_uid_source: MappingUidSource::Immediate(m),
                }
            }
        }
    }
}

/// Load properties and generate property operations.
async fn generate_property_operations(
    mapping: &Arc<ResolvedMapping>,
    mapping_uid: &MappingUidSource,
    pair: &StoragePair,
    status: Option<&StatusDatabase>,
    deletion_completion: Option<&DeletionBarrier>,
    mode: &dyn Mode,
) -> Result<Vec<PropertyOp>, PlanError> {
    let (props_a, props_b) = match tokio::try_join!(
        pair.storage_a().list_properties(mapping.a().href()),
        pair.storage_b().list_properties(mapping.b().href()),
    ) {
        Ok((a, b)) => (a, b),
        Err(error) => {
            // If storage doesn't support properties or doesn't exist, return empty.
            if let ErrorKind::DoesNotExist | ErrorKind::Unsupported = error.kind {
                return Ok(Vec::new());
            }
            return Err(error.into());
        }
    };

    let props_status = match (status, mapping_uid) {
        (Some(s), MappingUidSource::Immediate(u)) => s.list_properties_for_collection(*u)?,
        _ => Vec::new(),
    };

    let mut all_props =
        HashMap::<Property, (Option<String>, Option<String>, Option<String>)>::new();
    for p in props_a {
        all_props.entry(p.property).or_default().0 = Some(p.value);
    }
    for p in props_b {
        all_props.entry(p.property).or_default().1 = Some(p.value);
    }
    for p in props_status {
        all_props.entry(p.property).or_default().2 = Some(p.value);
    }

    let mut operations = Vec::new();
    for (property, values) in all_props {
        if let Some(op) = mode.decide_property_action(
            property,
            values.0,
            values.1,
            values.2,
            mapping,
            mapping_uid,
            deletion_completion,
        ) {
            operations.push(op);
        }
    }

    Ok(operations)
}