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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
//! What survives a restart: peers, relationships, baselines and conflicts.
//!
//! A machine-level SQLite database beside the machine identity, separate from
//! every worktree's own. The split is deliberate — see `wsb::daemon::machine`.
//! Peers are a fact about this MACHINE; a worktree's model, catalogue and
//! secrets are facts about the worktree, and putting them in one file would
//! make the daemon's globalisation a globalisation of everything it touches.
//!
//! # What must survive, and what must not
//!
//! Survive: which machines are paired and their pinned keys, which
//! relationships the operator enabled, the baselines convergence is computed
//! against, and every unresolved conflict. Losing any of those loses work or
//! trust.
//!
//! Must NOT survive as fact: "synced". That is an observation about two live
//! trees, and a daemon that came back up and believed a stored `synced` would
//! skip the very check that tells it the tree changed while it was down. It is
//! recomputed, always, from `checking`.
use std::collections::BTreeMap;
use std::path::Path;
use rusqlite::{params, Connection, OptionalExtension};
use wsb::peer::converge::{Baseline, Entry, EntryKind};
use wsb::peer::identity::{Fingerprint, PairedPeer};
use wsb::peer::model::{Desired, PeerId, RepositoryId, Service, Switch, SyncMode, SharedWorktreeId};
/// The machine's peers, pairings and continuity state: tables of the
/// workshop's one database ([`wsb::store`]).
pub struct MachineStore {
connection: std::sync::Mutex<Connection>,
}
impl MachineStore {
/// Open its tables in the database at `path`, creating them the first
/// time.
pub fn open(path: &Path) -> Result<Self, String> {
let connection = Connection::open(path)
.map_err(|e| format!("cannot open {}: {e}", path.display()))?;
// Write-ahead logging: the coordinator writes baselines while the web
// handlers read state, and a reader blocking a write here would stall
// a transfer behind a page refresh.
connection
.execute_batch(
"PRAGMA journal_mode = WAL;
PRAGMA synchronous = FULL;
PRAGMA foreign_keys = ON;",
)
.map_err(|e| format!("cannot configure {}: {e}", path.display()))?;
let mut connection = connection;
// The workshop's one migration set: the peers' tables are in it, beside
// everything else the database holds, whichever opens it first.
wsb::persist::global::migrations::runner()
.run(&mut connection)
.map_err(|e| format!("cannot bring {} up to date: {e}", path.display()))?;
Ok(Self {
connection: std::sync::Mutex::new(connection),
})
}
fn with<T>(&self, body: impl FnOnce(&Connection) -> Result<T, rusqlite::Error>) -> Result<T, String> {
let connection = self
.connection
.lock()
.map_err(|_| "the machine database is unusable after a panic".to_string())?;
body(&connection).map_err(|e| format!("machine database: {e}"))
}
// ── peers ──────────────────────────────────────────────────────────────
pub fn add_peer(&self, peer: &PairedPeer) -> Result<(), String> {
self.with(|c| {
c.execute(
"INSERT INTO peers (peer_id, name, public_key, fingerprint, address, paired_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6)
ON CONFLICT(peer_id) DO UPDATE SET
name = excluded.name,
address = excluded.address",
params![
peer.id.as_str(),
peer.name,
peer.public_key,
peer.fingerprint.as_str(),
peer.address,
peer.paired_at as i64,
],
)?;
Ok(())
})?;
// A peer whose key changed is a different machine wearing a name.
// Re-pairing is the only way in, and it goes through `remove_peer`
// first — so this refuses rather than updating the key in place.
let stored = self.peer(&peer.id)?.ok_or_else(|| "the peer vanished".to_string())?;
if stored.public_key != peer.public_key {
return Err(format!(
"{} is already paired with a different identity ({}). Remove it first if \
this is deliberate.",
peer.id, stored.fingerprint
));
}
Ok(())
}
pub fn peer(&self, id: &PeerId) -> Result<Option<PairedPeer>, String> {
self.with(|c| {
c.query_row(
"SELECT peer_id, name, public_key, fingerprint, address, paired_at
FROM peers WHERE peer_id = ?1",
params![id.as_str()],
row_to_peer,
)
.optional()
})
}
pub fn peers(&self) -> Result<Vec<PairedPeer>, String> {
self.with(|c| {
let mut statement = c.prepare(
"SELECT peer_id, name, public_key, fingerprint, address, paired_at
FROM peers ORDER BY name, peer_id",
)?;
let rows = statement.query_map([], row_to_peer)?;
rows.collect()
})
}
/// Forget a peer and everything that depended on trusting it.
///
/// The baselines go with it deliberately: they describe an agreement with
/// a machine this one no longer trusts, and keeping them would let a
/// re-pairing silently continue from a state neither side verified.
pub fn remove_peer(&self, id: &PeerId) -> Result<bool, String> {
self.with(|c| {
c.execute("DELETE FROM baselines WHERE peer_id = ?1", params![id.as_str()])?;
c.execute(
"DELETE FROM baseline_seeded WHERE peer_id = ?1",
params![id.as_str()],
)?;
c.execute("DELETE FROM conflicts WHERE peer_id = ?1", params![id.as_str()])?;
c.execute("DELETE FROM resolutions WHERE peer_id = ?1", params![id.as_str()])?;
c.execute("DELETE FROM relationships WHERE peer_id = ?1", params![id.as_str()])?;
let removed = c.execute("DELETE FROM peers WHERE peer_id = ?1", params![id.as_str()])?;
Ok(removed > 0)
})
}
pub fn note_seen(&self, id: &PeerId, when: u64) -> Result<(), String> {
self.with(|c| {
c.execute(
"UPDATE peers SET last_seen = ?2 WHERE peer_id = ?1",
params![id.as_str(), when as i64],
)?;
Ok(())
})
}
pub fn last_seen(&self, id: &PeerId) -> Result<Option<u64>, String> {
self.with(|c| {
c.query_row(
"SELECT last_seen FROM peers WHERE peer_id = ?1",
params![id.as_str()],
|row| row.get::<_, Option<i64>>(0),
)
.optional()
.map(|value| value.flatten().map(|v| v as u64))
})
}
// ── relationships ──────────────────────────────────────────────────────
pub fn set_desired(
&self,
peer: &PeerId,
worktree: &SharedWorktreeId,
desired: Desired,
when: u64,
) -> Result<(), String> {
self.with(|c| {
c.execute(
"INSERT INTO relationships (peer_id, shared_worktree, desired, enabled_at)
VALUES (?1, ?2, ?3, ?4)
ON CONFLICT(peer_id, shared_worktree) DO UPDATE SET desired = excluded.desired",
params![peer.as_str(), worktree.as_str(), desired.as_str(), when as i64],
)?;
Ok(())
})
}
/// Which services run with one peer.
///
/// Absent rows are the default rather than an error: pairing writes no
/// service rows, and a machine paired before this table existed has none
/// either. The default is stated once, in the model.
pub fn services(&self, peer: &PeerId) -> Result<BTreeMap<Service, Switch>, String> {
let stored: Vec<(String, String)> = self.with(|c| {
let mut statement =
c.prepare("SELECT service, switch FROM peer_services WHERE peer_id = ?1")?;
let rows = statement.query_map(params![peer.as_str()], |row| {
Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
})?;
let mut out = Vec::new();
for row in rows {
out.push(row?);
}
Ok(out)
})?;
let mut services = BTreeMap::new();
// wsb's own services always appear; a plugin's appears once a switch
// for it has been written, and is off until then (see the model).
for service in Service::BUILT_IN {
let default = Switch::default_for(&service);
services.insert(service, default);
}
for (service, switch) in stored {
// A row naming a service this build does not have is a database
// from a later version. Ignored, not fatal: the services it does
// know about still answer.
let (Ok(service), Ok(switch)) = (Service::parse(&service), Switch::parse(&switch))
else {
continue;
};
services.insert(service, switch);
}
Ok(services)
}
/// Whether one service runs with one peer.
pub fn service(&self, peer: &PeerId, service: Service) -> Result<Switch, String> {
Ok(self
.services(peer)?
.get(&service)
.copied()
.unwrap_or_else(|| Switch::default_for(&service)))
}
pub fn set_service(
&self,
peer: &PeerId,
service: Service,
switch: Switch,
when: u64,
) -> Result<(), String> {
self.with(|c| {
c.execute(
"INSERT INTO peer_services (peer_id, service, switch, changed_at)
VALUES (?1, ?2, ?3, ?4)
ON CONFLICT(peer_id, service) DO UPDATE SET
switch = excluded.switch,
changed_at = excluded.changed_at",
params![peer.as_str(), service.as_str(), switch.as_str(), when as i64],
)?;
Ok(())
})
}
/// How this worktree is carried with this peer: by hand, or by itself.
pub fn mode(&self, peer: &PeerId, worktree: &SharedWorktreeId) -> Result<SyncMode, String> {
let stored: Option<String> = self.with(|c| {
c.query_row(
"SELECT mode FROM relationships WHERE peer_id = ?1 AND shared_worktree = ?2",
params![peer.as_str(), worktree.as_str()],
|row| row.get(0),
)
.optional()
})?;
Ok(stored
.as_deref()
.and_then(|raw| SyncMode::parse(raw).ok())
.unwrap_or_default())
}
/// Set the mode, whether or not the worktree is being carried yet.
///
/// A relationship row is created if there is none: choosing how a
/// worktree would be carried before choosing to carry it is an ordinary
/// order to do things in, and refusing it would make the workbench's two
/// switches depend on which was touched first.
pub fn set_mode(
&self,
peer: &PeerId,
worktree: &SharedWorktreeId,
mode: SyncMode,
when: u64,
) -> Result<(), String> {
self.with(|c| {
c.execute(
"INSERT INTO relationships (peer_id, shared_worktree, desired, enabled_at, mode)
VALUES (?1, ?2, ?3, ?4, ?5)
ON CONFLICT(peer_id, shared_worktree) DO UPDATE SET mode = excluded.mode",
params![
peer.as_str(),
worktree.as_str(),
Desired::Disabled.as_str(),
when as i64,
mode.as_str()
],
)?;
Ok(())
})
}
pub fn desired(&self, peer: &PeerId, worktree: &SharedWorktreeId) -> Result<Desired, String> {
let stored: Option<String> = self.with(|c| {
c.query_row(
"SELECT desired FROM relationships WHERE peer_id = ?1 AND shared_worktree = ?2",
params![peer.as_str(), worktree.as_str()],
|row| row.get(0),
)
.optional()
})?;
Ok(match stored.as_deref() {
Some("enabled") => Desired::Enabled,
Some("paused") => Desired::Paused,
// Never asked for, or explicitly turned off.
_ => Desired::Disabled,
})
}
/// Every relationship the operator has an opinion about.
pub fn relationships(&self) -> Result<Vec<(PeerId, SharedWorktreeId, Desired)>, String> {
let rows = self.with(|c| {
let mut statement = c.prepare(
"SELECT peer_id, shared_worktree, desired FROM relationships
ORDER BY peer_id, shared_worktree",
)?;
let rows = statement.query_map([], |row| {
let peer: String = row.get(0)?;
let worktree: String = row.get(1)?;
let desired: String = row.get(2)?;
Ok((peer, worktree, desired))
})?;
rows.collect::<Result<Vec<_>, _>>()
})?;
// A row whose ids do not parse is a database somebody edited: every
// id is written from a parsed one. Named, rather than skipped — a
// relationship that silently stopped existing is one nobody can find.
rows.into_iter()
.map(|(peer, worktree, desired)| {
let peer = PeerId::parse(&peer)
.map_err(|e| format!("machine database, relationships: {e}"))?;
let worktree = SharedWorktreeId::parse(&worktree)
.map_err(|e| format!("machine database, relationships: {e}"))?;
let desired = match desired.as_str() {
"enabled" => Desired::Enabled,
"paused" => Desired::Paused,
"disabled" => Desired::Disabled,
other => {
return Err(format!(
"machine database, relationship {peer}/{worktree}: '{other}' is not \
enabled, paused or disabled"
))
}
};
Ok((peer, worktree, desired))
})
.collect()
}
// ── baselines ──────────────────────────────────────────────────────────
pub fn baseline(
&self,
peer: &PeerId,
worktree: &SharedWorktreeId,
repository: &RepositoryId,
) -> Result<Baseline, String> {
self.with(|c| {
let mut statement = c.prepare(
"SELECT path, kind, hash, size, executable FROM baselines
WHERE peer_id = ?1 AND shared_worktree = ?2 AND repository = ?3",
)?;
let rows = statement.query_map(
params![peer.as_str(), worktree.as_str(), repository.as_str()],
|row| {
let path: String = row.get(0)?;
let kind: String = row.get(1)?;
Ok((
path,
Entry {
kind: if kind == "symlink" {
EntryKind::Symlink
} else {
EntryKind::File
},
hash: row.get(2)?,
size: row.get::<_, i64>(3)? as u64,
executable: row.get::<_, i64>(4)? != 0,
},
))
},
)?;
let mut baseline = Baseline::new();
for row in rows {
let (path, entry) = row?;
baseline.insert(path, entry);
}
Ok(baseline)
})
}
/// Replace one repository's baseline, in one transaction.
///
/// Whole rather than incremental: a baseline is the state both sides
/// agreed on at one moment, and a half-written one describes a moment that
/// never existed.
pub fn put_baseline(
&self,
peer: &PeerId,
worktree: &SharedWorktreeId,
repository: &RepositoryId,
baseline: &Baseline,
) -> Result<(), String> {
self.with(|c| {
let transaction = c.unchecked_transaction()?;
transaction.execute(
"DELETE FROM baselines WHERE peer_id = ?1 AND shared_worktree = ?2 AND repository = ?3",
params![peer.as_str(), worktree.as_str(), repository.as_str()],
)?;
{
let mut insert = transaction.prepare(
"INSERT INTO baselines
(peer_id, shared_worktree, repository, path, kind, hash, size, executable)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
)?;
for (path, entry) in baseline {
insert.execute(params![
peer.as_str(),
worktree.as_str(),
repository.as_str(),
path,
match entry.kind {
EntryKind::File => "file",
EntryKind::Symlink => "symlink",
},
entry.hash,
entry.size as i64,
i64::from(entry.executable),
])?;
}
}
transaction.commit()
})
}
/// Whether this repository's baseline has ever been established.
pub fn is_seeded(
&self,
peer: &PeerId,
worktree: &SharedWorktreeId,
repository: &RepositoryId,
) -> Result<bool, String> {
self.with(|c| {
c.query_row(
"SELECT 1 FROM baseline_seeded
WHERE peer_id = ?1 AND shared_worktree = ?2 AND repository = ?3",
params![peer.as_str(), worktree.as_str(), repository.as_str()],
|_| Ok(()),
)
.optional()
.map(|found| found.is_some())
})
}
pub fn mark_seeded(
&self,
peer: &PeerId,
worktree: &SharedWorktreeId,
repository: &RepositoryId,
when: u64,
) -> Result<(), String> {
self.with(|c| {
c.execute(
"INSERT OR REPLACE INTO baseline_seeded
(peer_id, shared_worktree, repository, seeded_at) VALUES (?1, ?2, ?3, ?4)",
params![
peer.as_str(),
worktree.as_str(),
repository.as_str(),
when as i64
],
)?;
Ok(())
})
}
// ── conflicts ──────────────────────────────────────────────────────────
pub fn record_conflict(
&self,
peer: &PeerId,
worktree: &SharedWorktreeId,
repository: &RepositoryId,
path: &str,
here: Option<&Entry>,
there: Option<&Entry>,
base: Option<&Entry>,
when: u64,
) -> Result<(), String> {
self.with(|c| {
c.execute(
"INSERT INTO conflicts
(peer_id, shared_worktree, repository, path, here_hash, there_hash, base_hash, detected_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
ON CONFLICT(peer_id, shared_worktree, repository, path) DO UPDATE SET
here_hash = excluded.here_hash,
there_hash = excluded.there_hash",
params![
peer.as_str(),
worktree.as_str(),
repository.as_str(),
path,
here.map(|e| e.hash.clone()),
there.map(|e| e.hash.clone()),
base.map(|e| e.hash.clone()),
when as i64,
],
)?;
Ok(())
})
}
pub fn conflicts(
&self,
peer: &PeerId,
worktree: &SharedWorktreeId,
) -> Result<Vec<ConflictRow>, String> {
self.with(|c| {
let mut statement = c.prepare(
"SELECT repository, path, here_hash, there_hash, base_hash, detected_at
FROM conflicts WHERE peer_id = ?1 AND shared_worktree = ?2
ORDER BY repository, path",
)?;
let rows = statement.query_map(params![peer.as_str(), worktree.as_str()], |row| {
Ok(ConflictRow {
repository: row.get(0)?,
path: row.get(1)?,
here_hash: row.get(2)?,
there_hash: row.get(3)?,
base_hash: row.get(4)?,
detected_at: row.get::<_, i64>(5)? as u64,
})
})?;
rows.collect()
})
}
/// Every unresolved conflict on this machine, counted by where it is.
///
/// One query rather than one per relationship: the count is read by the
/// workbench on every refresh, and asking per peer and per worktree would
/// be N queries to answer "is anything waiting for me".
pub fn conflict_counts(&self) -> Result<Vec<ConflictCount>, String> {
self.with(|c| {
let mut statement = c.prepare(
"SELECT shared_worktree, repository, peer_id, COUNT(*)
FROM conflicts
GROUP BY shared_worktree, repository, peer_id
ORDER BY shared_worktree, repository, peer_id",
)?;
let rows = statement.query_map([], |row| {
Ok(ConflictCount {
worktree: row.get(0)?,
repository: row.get(1)?,
peer: row.get(2)?,
conflicts: row.get::<_, i64>(3)? as usize,
})
})?;
rows.collect()
})
}
pub fn clear_conflict(
&self,
peer: &PeerId,
worktree: &SharedWorktreeId,
repository: &RepositoryId,
path: &str,
) -> Result<(), String> {
self.with(|c| {
c.execute(
"DELETE FROM conflicts
WHERE peer_id = ?1 AND shared_worktree = ?2 AND repository = ?3 AND path = ?4",
params![peer.as_str(), worktree.as_str(), repository.as_str(), path],
)?;
Ok(())
})
}
/// Record a person's decision about one conflicted path.
pub fn set_resolution(
&self,
peer: &PeerId,
worktree: &SharedWorktreeId,
repository: &RepositoryId,
path: &str,
keep: &str,
when: u64,
) -> Result<(), String> {
if keep != "here" && keep != "there" {
return Err(format!("'{keep}' is not a side to keep"));
}
self.with(|c| {
c.execute(
"INSERT OR REPLACE INTO resolutions
(peer_id, shared_worktree, repository, path, keep, decided_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
params![
peer.as_str(),
worktree.as_str(),
repository.as_str(),
path,
keep,
when as i64
],
)?;
Ok(())
})
}
/// The decisions waiting to be carried for one repository.
pub fn resolutions(
&self,
peer: &PeerId,
worktree: &SharedWorktreeId,
repository: &RepositoryId,
) -> Result<BTreeMap<String, String>, String> {
self.with(|c| {
let mut statement = c.prepare(
"SELECT path, keep FROM resolutions
WHERE peer_id = ?1 AND shared_worktree = ?2 AND repository = ?3",
)?;
let rows = statement.query_map(
params![peer.as_str(), worktree.as_str(), repository.as_str()],
|row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)),
)?;
let mut out = BTreeMap::new();
for row in rows {
let (path, keep) = row?;
out.insert(path, keep);
}
Ok(out)
})
}
pub fn clear_resolution(
&self,
peer: &PeerId,
worktree: &SharedWorktreeId,
repository: &RepositoryId,
path: &str,
) -> Result<(), String> {
self.with(|c| {
c.execute(
"DELETE FROM resolutions
WHERE peer_id = ?1 AND shared_worktree = ?2 AND repository = ?3 AND path = ?4",
params![peer.as_str(), worktree.as_str(), repository.as_str(), path],
)?;
Ok(())
})
}
// ── dismissals ─────────────────────────────────────────────────────────
/// Leave one difference alone, as it stands right now.
pub fn dismiss(
&self,
peer: &PeerId,
worktree: &SharedWorktreeId,
repository: &RepositoryId,
path: &str,
here_hash: Option<&str>,
there_hash: Option<&str>,
when: u64,
) -> Result<(), String> {
self.with(|c| {
c.execute(
"INSERT OR REPLACE INTO dismissals
(peer_id, shared_worktree, repository, path, here_hash, there_hash, dismissed_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
params![
peer.as_str(),
worktree.as_str(),
repository.as_str(),
path,
here_hash,
there_hash,
when as i64
],
)?;
Ok(())
})
}
/// The dismissals for one repository, by path, with the two hashes each
/// was made at.
pub fn dismissals(
&self,
peer: &PeerId,
worktree: &SharedWorktreeId,
repository: &RepositoryId,
) -> Result<BTreeMap<String, (Option<String>, Option<String>)>, String> {
self.with(|c| {
let mut statement = c.prepare(
"SELECT path, here_hash, there_hash FROM dismissals
WHERE peer_id = ?1 AND shared_worktree = ?2 AND repository = ?3",
)?;
let rows = statement.query_map(
params![peer.as_str(), worktree.as_str(), repository.as_str()],
|row| {
Ok((
row.get::<_, String>(0)?,
row.get::<_, Option<String>>(1)?,
row.get::<_, Option<String>>(2)?,
))
},
)?;
let mut out = BTreeMap::new();
for row in rows {
let (path, here, there) = row?;
out.insert(path, (here, there));
}
Ok(out)
})
}
pub fn clear_dismissal(
&self,
peer: &PeerId,
worktree: &SharedWorktreeId,
repository: &RepositoryId,
path: &str,
) -> Result<(), String> {
self.with(|c| {
c.execute(
"DELETE FROM dismissals
WHERE peer_id = ?1 AND shared_worktree = ?2 AND repository = ?3 AND path = ?4",
params![peer.as_str(), worktree.as_str(), repository.as_str(), path],
)?;
Ok(())
})
}
// ── worktrees ──────────────────────────────────────────────────────────
pub fn register_worktree(
&self,
worktree: &wsb::daemon::RegisteredWorktree,
) -> Result<(), String> {
self.with(|c| {
c.execute(
"INSERT INTO worktrees
(worktree_id, project, name, shared_worktree, super_root, root_commit, last_seen)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
ON CONFLICT(worktree_id) DO UPDATE SET
project = excluded.project,
name = excluded.name,
shared_worktree = excluded.shared_worktree,
super_root = excluded.super_root,
root_commit = excluded.root_commit,
last_seen = excluded.last_seen",
params![
worktree.id.as_str(),
worktree.project,
worktree.name,
worktree.shared.as_ref().map(SharedWorktreeId::as_str),
worktree.super_root.display().to_string(),
worktree.root_commit,
worktree.last_seen as i64,
],
)?;
Ok(())
})
}
/// Drop a worktree record.
///
/// Used to correct a record that should never have been written — see
/// `MachineState::forget_contained_worktrees`.
pub fn forget_worktree(&self, worktree: &wsb::daemon::WorktreeId) -> Result<(), String> {
self.with(|c| {
c.execute(
"DELETE FROM worktrees WHERE worktree_id = ?1",
params![worktree.as_str()],
)?;
Ok(())
})
}
/// Every worktree this machine has opened.
///
/// A row that does not read is an error naming it, not a row skipped:
/// every column is written from a parsed value, so one that does not
/// parse was edited by hand, and a list quietly missing a worktree is
/// the harder thing to explain.
pub fn worktrees(&self) -> Result<Vec<wsb::daemon::RegisteredWorktree>, String> {
let rows = self.with(|c| {
let mut statement = c.prepare(
"SELECT worktree_id, project, name, shared_worktree, super_root, root_commit, last_seen
FROM worktrees ORDER BY project, name, worktree_id",
)?;
let rows = statement.query_map([], |row| {
Ok((
row.get::<_, String>(0)?,
row.get::<_, Option<String>>(1)?,
row.get::<_, String>(2)?,
row.get::<_, Option<String>>(3)?,
row.get::<_, String>(4)?,
row.get::<_, Option<String>>(5)?,
row.get::<_, i64>(6)? as u64,
))
})?;
rows.collect::<Result<Vec<_>, _>>()
})?;
rows.into_iter()
.map(|(id, project, name, shared, super_root, root_commit, last_seen)| {
let id = wsb::daemon::WorktreeId::parse(&id)
.map_err(|e| format!("machine database, worktrees: {e}"))?;
let shared = shared
.map(|raw| SharedWorktreeId::parse(&raw))
.transpose()
.map_err(|e| format!("machine database, worktree {id}: {e}"))?;
let super_root = std::path::PathBuf::from(super_root);
Ok(wsb::daemon::RegisteredWorktree {
id,
project,
name,
shared,
available: super_root.is_dir(),
super_root,
root_commit,
last_seen,
})
})
.collect()
}
}
/// How many conflicts are waiting in one repository, with one peer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConflictCount {
pub worktree: String,
/// Worktree-relative; the superproject is the empty string.
pub repository: String,
pub peer: String,
pub conflicts: usize,
}
/// One unresolved conflict, as stored.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConflictRow {
pub repository: String,
pub path: String,
pub here_hash: Option<String>,
pub there_hash: Option<String>,
pub base_hash: Option<String>,
pub detected_at: u64,
}
fn row_to_peer(row: &rusqlite::Row<'_>) -> Result<PairedPeer, rusqlite::Error> {
let id: String = row.get(0)?;
Ok(PairedPeer {
// A row whose id does not parse cannot be turned into a peer, and a
// peer with an invented id would be a peer nothing can reach. The
// column is written only from a parsed id, so this is unreachable
// without hand-editing the database.
id: PeerId::parse(&id).map_err(|e| {
rusqlite::Error::FromSqlConversionFailure(0, rusqlite::types::Type::Text, e.into())
})?,
name: row.get(1)?,
public_key: row.get(2)?,
fingerprint: Fingerprint::from_stored(row.get::<_, String>(3)?),
address: row.get(4)?,
paired_at: row.get::<_, i64>(5)? as u64,
})
}
#[cfg(test)]
#[path = "store_tests.rs"]
mod tests;