taskchampion 3.0.1

Personal task-tracking
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
use crate::errors::{Error, Result};
use crate::operation::Operation;
use crate::server::SyncOp;
use crate::storage::{StorageTxn, TaskMap};
use crate::Operations;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use uuid::Uuid;

/// Apply `operations` to the database in the given single transaction.
///
/// This updates the set of tasks in the database, but does not modify the list of operations.
/// If the operation does not make sense in the current state, it is ignored.
///
/// The transaction is not committed.
pub(super) async fn apply_operations(
    txn: &mut dyn StorageTxn,
    operations: &Operations,
) -> Result<()> {
    // A cache of TaskMaps updated in this sequence of operations, but for which `txn.set_task` has
    // not yet been called.
    let mut tasks: HashMap<Uuid, Option<TaskMap>> = HashMap::new();

    async fn get_cache<'t>(
        uuid: Uuid,
        tasks: &'t mut HashMap<Uuid, Option<TaskMap>>,
        txn: &mut dyn StorageTxn,
    ) -> Result<Option<&'t mut TaskMap>> {
        match tasks.entry(uuid) {
            Entry::Occupied(occupied_entry) => Ok(occupied_entry.into_mut().as_mut()),
            Entry::Vacant(vacant_entry) => {
                let task = txn.get_task(uuid).await?;
                Ok(vacant_entry.insert(task).as_mut())
            }
        }
    }

    // Call `txn.set_task` for this task, if necessary, and remove from the cache.
    async fn flush_cache(
        uuid: Uuid,
        tasks: &mut HashMap<Uuid, Option<TaskMap>>,
        txn: &mut dyn StorageTxn,
    ) -> Result<()> {
        if let Entry::Occupied(occupied_entry) = tasks.entry(uuid) {
            let v = occupied_entry.remove();
            if let Some(taskmap) = v {
                txn.set_task(uuid, taskmap).await?;
            }
        }
        Ok(())
    }

    for operation in operations {
        match operation {
            Operation::Create { uuid } => {
                // The create_task method will do nothing if the task exists. If it was cached
                // as not existing, clear that information. If it had cached updates, then there
                // is no harm flushing those updates now.
                flush_cache(*uuid, &mut tasks, txn).await?;
                txn.create_task(*uuid).await?;
            }
            Operation::Delete { uuid, .. } => {
                // The delete_task method will do nothing if the task does not exist.
                txn.delete_task(*uuid).await?;
                // The task now unconditionally does not exist. If there was a pending
                // `txn.set_task`, it can safely be skipped.
                tasks.insert(*uuid, None);
            }
            Operation::Update {
                uuid,
                property,
                value,
                ..
            } => {
                let task = get_cache(*uuid, &mut tasks, txn).await?;
                // If the task does not exist, do nothing.
                if let Some(task) = task {
                    if let Some(v) = value {
                        task.insert(property.clone(), v.clone());
                    } else {
                        task.remove(property);
                    }
                }
            }
            Operation::UndoPoint => {}
        }
    }

    // Flush any remaining tasks in the cache.
    while let Some((uuid, _)) = tasks.iter().next() {
        flush_cache(*uuid, &mut tasks, txn).await?;
    }

    Ok(())
}

/// Apply a [`SyncOp`] to the TaskDb's set of tasks (without recording it in the list of operations)
pub(super) async fn apply_op(txn: &mut dyn StorageTxn, op: &SyncOp) -> Result<()> {
    match op {
        SyncOp::Create { uuid } => {
            // insert if the task does not already exist
            if !txn.create_task(*uuid).await? {
                return Err(Error::Database(format!("Task {uuid} already exists")));
            }
        }
        SyncOp::Delete { ref uuid } => {
            if !txn.delete_task(*uuid).await? {
                return Err(Error::Database(format!("Task {uuid} does not exist")));
            }
        }
        SyncOp::Update {
            ref uuid,
            ref property,
            ref value,
            timestamp: _,
        } => {
            // update if this task exists, otherwise ignore
            if let Some(mut task) = txn.get_task(*uuid).await? {
                match value {
                    Some(ref val) => task.insert(property.to_string(), val.clone()),
                    None => task.remove(property),
                };
                txn.set_task(*uuid, task).await?;
            } else {
                return Err(Error::Database(format!("Task {uuid} does not exist")));
            }
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    #![allow(clippy::vec_init_then_push)]
    use super::*;
    use crate::storage::inmemory::InMemoryStorage;
    use crate::storage::{taskmap_with, Storage, TaskMap};
    use crate::taskdb::TaskDb;
    use chrono::Utc;
    use pretty_assertions::assert_eq;
    use std::collections::HashMap;
    use uuid::Uuid;

    #[tokio::test]
    async fn apply_operations_create() -> Result<()> {
        let mut db = TaskDb::new(InMemoryStorage::new());
        let uuid = Uuid::new_v4();
        let mut ops = Operations::new();
        ops.push(Operation::Create { uuid });

        {
            let mut txn = db.storage.txn().await?;
            apply_operations(txn.as_mut(), &ops).await?;
            txn.commit().await?;
        }

        assert_eq!(db.sorted_tasks().await, vec![(uuid, vec![])]);
        Ok(())
    }

    #[tokio::test]
    async fn apply_operations_create_exists() -> Result<()> {
        let mut db = TaskDb::new(InMemoryStorage::new());
        let uuid = Uuid::new_v4();
        {
            let mut txn = db.storage.txn().await?;
            txn.create_task(uuid).await?;
            txn.set_task(uuid, taskmap_with(vec![("foo".into(), "bar".into())]))
                .await?;
            txn.commit().await?;
        }

        {
            let mut ops = Operations::new();
            ops.push(Operation::Create { uuid });
            let mut txn = db.storage.txn().await?;
            apply_operations(txn.as_mut(), &ops).await?;
            txn.commit().await?;
        }

        assert_eq!(
            db.sorted_tasks().await,
            vec![(uuid, vec![("foo".into(), "bar".into())])]
        );
        Ok(())
    }

    #[tokio::test]
    async fn apply_operations_create_exists_update() -> Result<()> {
        let mut db = TaskDb::new(InMemoryStorage::new());
        let now = Utc::now();
        let uuid = Uuid::new_v4();
        {
            let mut txn = db.storage.txn().await?;
            txn.create_task(uuid).await?;
            txn.set_task(uuid, taskmap_with(vec![("foo".into(), "bar".into())]))
                .await?;
            txn.commit().await?;
        }

        {
            let mut ops = Operations::new();
            ops.push(Operation::Create { uuid });
            ops.push(Operation::Update {
                uuid,
                property: String::from("title"),
                value: Some("my task".into()),
                timestamp: now,
                old_value: None,
            });
            let mut txn = db.storage.txn().await?;
            apply_operations(txn.as_mut(), &ops).await?;
            txn.commit().await?;
        }

        assert_eq!(
            db.sorted_tasks().await,
            vec![(
                uuid,
                vec![
                    ("foo".into(), "bar".into()),
                    ("title".into(), "my task".into())
                ]
            )]
        );
        Ok(())
    }

    #[tokio::test]
    async fn apply_operations_create_update() -> Result<()> {
        let mut db = TaskDb::new(InMemoryStorage::new());
        let uuid = Uuid::new_v4();
        let now = Utc::now();
        let mut ops = Operations::new();
        ops.push(Operation::Create { uuid });
        ops.push(Operation::Update {
            uuid,
            property: String::from("title"),
            value: Some("my task".into()),
            timestamp: now,
            old_value: None,
        });

        {
            let mut txn = db.storage.txn().await?;
            apply_operations(txn.as_mut(), &ops).await?;
            txn.commit().await?;
        }

        assert_eq!(
            db.sorted_tasks().await,
            vec![(uuid, vec![("title".into(), "my task".into())])]
        );
        Ok(())
    }

    #[tokio::test]
    async fn apply_operations_create_update_delete_prop() -> Result<()> {
        let mut db = TaskDb::new(InMemoryStorage::new());
        let uuid = Uuid::new_v4();
        let now = Utc::now();
        let mut ops = Operations::new();
        ops.push(Operation::Create { uuid });
        ops.push(Operation::Update {
            uuid,
            property: String::from("title"),
            value: Some("my task".into()),
            timestamp: now,
            old_value: None,
        });
        ops.push(Operation::Update {
            uuid,
            property: String::from("priority"),
            value: Some("H".into()),
            timestamp: now,
            old_value: None,
        });
        ops.push(Operation::Update {
            uuid,
            property: String::from("title"),
            value: None,
            timestamp: now,
            old_value: Some("my task".into()),
        });

        {
            let mut txn = db.storage.txn().await?;
            apply_operations(txn.as_mut(), &ops).await?;
            txn.commit().await?;
        }

        assert_eq!(
            db.sorted_tasks().await,
            vec![(uuid, vec![("priority".into(), "H".into())])]
        );
        Ok(())
    }

    #[tokio::test]
    async fn apply_operations_update_does_not_exist() -> Result<()> {
        let mut db = TaskDb::new(InMemoryStorage::new());
        let uuid = Uuid::new_v4();
        let now = Utc::now();
        let mut ops = Operations::new();
        ops.push(Operation::Update {
            uuid,
            property: String::from("title"),
            value: Some("my task".into()),
            timestamp: now,
            old_value: None,
        });

        {
            let mut txn = db.storage.txn().await?;
            apply_operations(txn.as_mut(), &ops).await?;
            txn.commit().await?;
        }

        assert_eq!(db.sorted_tasks().await, vec![]);
        Ok(())
    }

    #[tokio::test]
    async fn apply_operations_delete_then_update() -> Result<()> {
        let mut db = TaskDb::new(InMemoryStorage::new());
        let uuid = Uuid::new_v4();
        let now = Utc::now();
        let mut ops = Operations::new();
        ops.push(Operation::Create { uuid });
        ops.push(Operation::Update {
            uuid,
            property: String::from("old"),
            value: Some("uhoh".into()),
            timestamp: now,
            old_value: None,
        });
        ops.push(Operation::Delete {
            uuid,
            old_task: taskmap_with(vec![]),
        });
        ops.push(Operation::Update {
            uuid,
            property: String::from("new"),
            value: Some("uhoh".into()),
            timestamp: now,
            old_value: None,
        });

        {
            let mut txn = db.storage.txn().await?;
            apply_operations(txn.as_mut(), &ops).await?;
            txn.commit().await?;
        }

        assert_eq!(db.sorted_tasks().await, vec![]);
        Ok(())
    }

    #[tokio::test]
    async fn apply_operations_several_tasks() -> Result<()> {
        let mut db = TaskDb::new(InMemoryStorage::new());
        let mut uuids = [Uuid::new_v4(), Uuid::new_v4()];
        uuids.sort();
        let now = Utc::now();
        let mut ops = Operations::new();
        ops.push(Operation::Create { uuid: uuids[0] });
        ops.push(Operation::Create { uuid: uuids[1] });
        ops.push(Operation::Update {
            uuid: uuids[0],
            property: String::from("p"),
            value: Some("1".into()),
            timestamp: now,
            old_value: None,
        });
        ops.push(Operation::Update {
            uuid: uuids[1],
            property: String::from("p"),
            value: Some("2".into()),
            timestamp: now,
            old_value: None,
        });

        {
            let mut txn = db.storage.txn().await?;
            apply_operations(txn.as_mut(), &ops).await?;
            txn.commit().await?;
        }

        assert_eq!(
            db.sorted_tasks().await,
            vec![
                (uuids[0], vec![("p".into(), "1".into())]),
                (uuids[1], vec![("p".into(), "2".into())])
            ]
        );
        Ok(())
    }

    #[tokio::test]
    async fn apply_operations_create_delete() -> Result<()> {
        let mut db = TaskDb::new(InMemoryStorage::new());
        let uuid = Uuid::new_v4();
        let now = Utc::now();
        let mut ops = Operations::new();
        ops.push(Operation::Create { uuid });
        ops.push(Operation::Update {
            uuid,
            property: String::from("title"),
            value: Some("my task".into()),
            timestamp: now,
            old_value: None,
        });
        ops.push(Operation::Delete {
            uuid,
            old_task: taskmap_with(vec![]),
        });

        {
            let mut txn = db.storage.txn().await?;
            apply_operations(txn.as_mut(), &ops).await?;
            txn.commit().await?;
        }

        assert_eq!(db.sorted_tasks().await, vec![]);
        Ok(())
    }

    #[tokio::test]
    async fn apply_operations_delete_not_present() -> Result<()> {
        let mut db = TaskDb::new(InMemoryStorage::new());
        let uuid = Uuid::new_v4();
        let mut ops = Operations::new();
        ops.push(Operation::Delete {
            uuid,
            old_task: taskmap_with(vec![]),
        });

        {
            let mut txn = db.storage.txn().await?;
            apply_operations(txn.as_mut(), &ops).await?;
            txn.commit().await?;
        }

        assert_eq!(db.sorted_tasks().await, vec![]);
        Ok(())
    }

    #[tokio::test]
    async fn test_apply_create() -> Result<()> {
        let mut db = TaskDb::new(InMemoryStorage::new());
        let uuid = Uuid::new_v4();
        let op = SyncOp::Create { uuid };

        {
            let mut txn = db.storage.txn().await?;
            apply_op(txn.as_mut(), &op).await?;
            txn.commit().await?;
        }

        assert_eq!(db.sorted_tasks().await, vec![(uuid, vec![])]);
        Ok(())
    }

    #[tokio::test]
    async fn test_apply_create_exists() -> Result<()> {
        let mut db = TaskDb::new(InMemoryStorage::new());
        let uuid = Uuid::new_v4();
        {
            let mut txn = db.storage.txn().await?;
            txn.create_task(uuid).await?;
            let mut taskmap = TaskMap::new();
            taskmap.insert("foo".into(), "bar".into());
            txn.set_task(uuid, taskmap).await?;
            txn.commit().await?;
        }

        let op = SyncOp::Create { uuid };
        {
            let mut txn = db.storage.txn().await?;
            assert!(apply_op(txn.as_mut(), &op).await.is_err());
        }

        // create did not delete the old task..
        assert_eq!(
            db.sorted_tasks().await,
            vec![(uuid, vec![("foo".into(), "bar".into())])]
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_apply_create_update() -> Result<()> {
        let mut db = TaskDb::new(InMemoryStorage::new());
        let uuid = Uuid::new_v4();
        let now = Utc::now();
        let op1 = SyncOp::Create { uuid };

        {
            let mut txn = db.storage.txn().await?;
            apply_op(txn.as_mut(), &op1).await?;
            txn.commit().await?;
        }

        let op2 = SyncOp::Update {
            uuid,
            property: String::from("title"),
            value: Some("my task".into()),
            timestamp: now,
        };
        {
            let mut txn = db.storage.txn().await?;
            apply_op(txn.as_mut(), &op2).await?;
            txn.commit().await?;
        }

        assert_eq!(
            db.sorted_tasks().await,
            vec![(uuid, vec![("title".into(), "my task".into())])]
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_apply_create_update_delete_prop() -> Result<()> {
        let mut db = TaskDb::new(InMemoryStorage::new());
        let uuid = Uuid::new_v4();
        let now = Utc::now();
        let op1 = SyncOp::Create { uuid };
        {
            let mut txn = db.storage.txn().await?;
            apply_op(txn.as_mut(), &op1).await?;
            txn.commit().await?;
        }

        let op2 = SyncOp::Update {
            uuid,
            property: String::from("title"),
            value: Some("my task".into()),
            timestamp: now,
        };
        {
            let mut txn = db.storage.txn().await?;
            apply_op(txn.as_mut(), &op2).await?;
            txn.commit().await?;
        }

        let op3 = SyncOp::Update {
            uuid,
            property: String::from("priority"),
            value: Some("H".into()),
            timestamp: now,
        };
        {
            let mut txn = db.storage.txn().await?;
            apply_op(txn.as_mut(), &op3).await?;
            txn.commit().await?;
        }

        let op4 = SyncOp::Update {
            uuid,
            property: String::from("title"),
            value: None,
            timestamp: now,
        };
        {
            let mut txn = db.storage.txn().await?;
            apply_op(txn.as_mut(), &op4).await?;
            txn.commit().await?;
        }

        let mut exp = HashMap::new();
        let mut task = HashMap::new();
        task.insert(String::from("priority"), String::from("H"));
        exp.insert(uuid, task);
        assert_eq!(
            db.sorted_tasks().await,
            vec![(uuid, vec![("priority".into(), "H".into())])]
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_apply_update_does_not_exist() -> Result<()> {
        let mut db = TaskDb::new(InMemoryStorage::new());
        let uuid = Uuid::new_v4();
        let op = SyncOp::Update {
            uuid,
            property: String::from("title"),
            value: Some("my task".into()),
            timestamp: Utc::now(),
        };
        {
            let mut txn = db.storage.txn().await?;
            assert_eq!(
                apply_op(txn.as_mut(), &op).await.err().unwrap().to_string(),
                format!("Task Database Error: Task {} does not exist", uuid)
            );
            txn.commit().await?;
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_apply_create_delete() -> Result<()> {
        let mut db = TaskDb::new(InMemoryStorage::new());
        let uuid = Uuid::new_v4();
        let now = Utc::now();

        let op1 = SyncOp::Create { uuid };
        {
            let mut txn = db.storage.txn().await?;
            apply_op(txn.as_mut(), &op1).await?;
            txn.commit().await?;
        }

        let op2 = SyncOp::Update {
            uuid,
            property: String::from("priority"),
            value: Some("H".into()),
            timestamp: now,
        };
        {
            let mut txn = db.storage.txn().await?;
            apply_op(txn.as_mut(), &op2).await?;
            txn.commit().await?;
        }

        let op3 = SyncOp::Delete { uuid };
        {
            let mut txn = db.storage.txn().await?;
            apply_op(txn.as_mut(), &op3).await?;
            txn.commit().await?;
        }

        assert_eq!(db.sorted_tasks().await, vec![]);
        let mut old_task = TaskMap::new();
        old_task.insert("priority".into(), "H".into());

        Ok(())
    }

    #[tokio::test]
    async fn test_apply_delete_not_present() -> Result<()> {
        let mut db = TaskDb::new(InMemoryStorage::new());
        let uuid = Uuid::new_v4();
        let op = SyncOp::Delete { uuid };
        {
            let mut txn = db.storage.txn().await?;
            assert!(apply_op(txn.as_mut(), &op).await.is_err());
            txn.commit().await?;
        }

        Ok(())
    }
}