Repository navigation
Expand file tree
/
Copy pathworkspace.rs
More file actions
869 lines (860 loc) · 33.3 KB
/
Copy pathworkspace.rs
File metadata and controls
869 lines (860 loc) · 33.3 KB
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
//! TOML owns definitions; SQLite owns identity/inventory. No Git writes live here.
use crate::discovery::{self, DiscoveryOptions, Inventory};
use crate::domain::{digest, Issue, NativePath, ObjectId, RepositoryId, WorkspaceId, WorktreeId};
use crate::inspection::{self, Metadata, Snapshot};
use crate::{Error, ErrorKind, Result};
use rusqlite::{params, Connection, OptionalExtension};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fs::{self, File, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use uuid::Uuid;
#[cfg(all(unix, feature = "application-services"))]
mod migration_backup;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "application-services", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Workspace {
pub id: WorkspaceId,
pub name: String,
pub root: NativePath,
pub display_root: NativePath,
pub discovery: DiscoveryOptions,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "application-services", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
struct Config {
version: u32,
workspaces: Vec<Workspace>,
}
impl Default for Config {
fn default() -> Self {
Self {
version: 1,
workspaces: Vec::new(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "application-services", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum Availability {
Available,
Missing,
Unavailable,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "application-services", derive(schemars::JsonSchema))]
pub struct StoredWorktree {
pub id: WorktreeId,
pub repository_id: RepositoryId,
pub metadata: Metadata,
pub display_path: NativePath,
pub availability: Availability,
pub status: Option<Snapshot>,
pub issue: Option<Issue>,
pub untrusted: bool,
/// Historical identity replaced at the same path by a locally inspected identity.
#[serde(default)]
pub superseded_by: Option<WorktreeId>,
}
#[derive(Debug, Serialize)]
#[cfg_attr(feature = "application-services", derive(schemars::JsonSchema))]
pub struct WorkspaceInventory {
pub workspace_id: WorkspaceId,
pub scan: Inventory,
pub entries: Vec<StoredWorktree>,
}
pub(crate) mod recovery;
pub struct WorkspaceService {
pub(crate) session: String,
directory: PathBuf,
database: Connection,
config: Config,
_writer: crate::locking::ExclusiveLock,
scan_cursor: Option<(String, discovery::Cursor)>,
}
#[cfg(feature = "application-services")]
pub(crate) struct StatusPass {
pub(crate) workspace: WorkspaceId,
pub(crate) pending: std::collections::VecDeque<StoredWorktree>,
heads: BTreeMap<PathBuf, ObjectId>,
}
fn observed_heads(entries: &[StoredWorktree]) -> Result<BTreeMap<PathBuf, ObjectId>> {
entries
.iter()
.filter(|entry| {
matches!(entry.availability, Availability::Available) && entry.superseded_by.is_none()
})
.filter_map(|entry| {
entry.status.as_ref()?.head_oid.as_ref().map(|head| {
entry
.metadata
.root
.to_path()
.map(|path| (path, head.clone()))
})
})
.collect()
}
fn reflect_child_heads(
entry: &mut StoredWorktree,
heads: &BTreeMap<PathBuf, ObjectId>,
) -> Result<()> {
if !matches!(entry.availability, Availability::Available) || entry.superseded_by.is_some() {
return Ok(());
}
let root = entry.metadata.root.to_path()?;
let Some(status) = entry.status.as_mut() else {
return Ok(());
};
for link in status.index_gitlinks.as_deref().unwrap_or_default() {
let child = root.join(link.path.relative()?);
if heads.get(&child).is_none_or(|head| head == &link.oid) {
continue;
}
if let Some(change) = status
.changes
.iter_mut()
.find(|change| change.path == link.path)
{
if change.conflict || change.index_mode != "160000" {
continue;
}
if change.worktree == '.' {
status.counts.unstaged += 1;
}
change.worktree = 'M';
change.submodule = "SC..".into();
} else {
status.counts.unstaged += 1;
status.changes.push(inspection::Change {
path: link.path.clone(),
original_path: None,
index: '.',
worktree: 'M',
conflict: false,
submodule: "SC..".into(),
head_mode: "160000".into(),
index_mode: "160000".into(),
worktree_mode: "160000".into(),
});
}
}
Ok(())
}
fn storage(message: &str) -> Error {
Error::with_kind(ErrorKind::Storage, message)
}
fn private_create(path: &Path) -> Result<File> {
let mut options = OpenOptions::new();
options.create_new(true).write(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
Ok(options.open(path)?)
}
fn reject_symlink(path: &Path) -> Result<()> {
if let Ok(meta) = fs::symlink_metadata(path) {
if meta.is_symlink() || !meta.is_file() {
return Err(storage(
"Application state must be regular non-symlink files",
));
}
}
Ok(())
}
impl WorkspaceService {
pub fn open(directory: &Path) -> Result<Self> {
// Resolve aliases before creating descendants: a lexical parent can hide
// the checkout root when an alias targets a repository subdirectory.
let absolute = if directory.is_absolute() {
directory.to_path_buf()
} else {
std::env::current_dir()?.join(directory)
};
let mut existing = absolute.as_path();
let resolved = loop {
match fs::canonicalize(existing) {
Ok(path) => break path,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
existing = existing.parent().ok_or_else(|| {
Error::with_kind(
ErrorKind::InvalidPath,
"State directory has no existing ancestor",
)
})?;
}
Err(error) => return Err(error.into()),
}
};
for ancestor in resolved.ancestors() {
if ancestor.join(".git").exists() {
return Err(Error::with_kind(
ErrorKind::InvalidPath,
"Application state must be outside managed repositories",
));
}
}
fs::create_dir_all(directory)?;
let directory = fs::canonicalize(directory)?;
for ancestor in directory.ancestors() {
if ancestor.join(".git").exists() {
return Err(Error::with_kind(
ErrorKind::InvalidPath,
"Application state resolves inside a repository",
));
}
}
for name in [
"writer.lock",
"config.toml",
"state.db",
"state.db-journal",
"state.db-wal",
"state.db-shm",
] {
reject_symlink(&directory.join(name))?;
}
let mut open = OpenOptions::new();
open.read(true).write(true).create(true).truncate(false);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
open.mode(0o600);
}
let writer = open.open(directory.join("writer.lock"))?;
let writer = crate::locking::ExclusiveLock::acquire(
writer,
"GitFleet data directory already has a writer",
)?;
let config_path = directory.join("config.toml");
let config = if config_path.exists() {
let bytes = inspection::file_bytes(&config_path, 2 * 1024 * 1024)?;
let text = std::str::from_utf8(&bytes).map_err(|_| storage("Invalid TOML encoding"))?;
let value: toml::Value = toml::from_str(text)
.map_err(|_| storage("Invalid workspace TOML; original preserved"))?;
if value.get("version").and_then(toml::Value::as_integer) != Some(1) {
return Err(Error::with_kind(
ErrorKind::NewerSchema,
"Unsupported configuration version",
));
}
toml::from_str::<Config>(text)
.map_err(|_| storage("Invalid workspace configuration; original preserved"))?
} else {
Config::default()
};
validate_config(&config, &directory)?;
let database_path = directory.join("state.db");
let existed = database_path.exists();
let mut database = Connection::open(&database_path)?;
let version: u32 = database.pragma_query_value(None, "user_version", |row| row.get(0))?;
if version > 3 {
return Err(Error::with_kind(
ErrorKind::NewerSchema,
"SQLite schema is newer than this Core",
));
}
database.execute_batch(
"PRAGMA foreign_keys=ON; PRAGMA synchronous=FULL; PRAGMA journal_mode=DELETE;",
)?;
if version == 0 {
let tables:i64=database.query_row("SELECT count(*) FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'",[],|row|row.get(0))?;
if tables != 0 {
return Err(storage(
"Unversioned database has unknown tables; original preserved",
));
}
if existed {
fs::copy(
&database_path,
directory.join(format!("state.pre-v1-{}.db", Uuid::new_v4())),
)?;
}
let transaction = database.transaction()?;
transaction.execute_batch("CREATE TABLE repositories(id TEXT PRIMARY KEY,binding TEXT NOT NULL UNIQUE);
CREATE TABLE worktrees(id TEXT PRIMARY KEY,repository_id TEXT NOT NULL REFERENCES repositories(id),binding TEXT NOT NULL UNIQUE,metadata TEXT NOT NULL);
CREATE TABLE membership(workspace_id TEXT NOT NULL,worktree_id TEXT NOT NULL REFERENCES worktrees(id),availability TEXT NOT NULL,status TEXT,issue TEXT,PRIMARY KEY(workspace_id,worktree_id));
CREATE TABLE state(key TEXT PRIMARY KEY,value TEXT NOT NULL);
PRAGMA user_version=1;")?;
transaction.commit()?;
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&database_path, fs::Permissions::from_mode(0o600))?;
}
let mut service = Self {
directory,
session: Uuid::new_v4().to_string(),
_writer: writer,
database,
config,
scan_cursor: None,
};
service.reconcile()?;
Ok(service)
}
#[cfg(feature = "controlled-writes")]
pub(crate) fn connection(&mut self) -> &mut Connection {
&mut self.database
}
#[cfg(feature = "controlled-writes")]
pub(crate) fn data_directory(&self) -> &Path {
&self.directory
}
fn reconcile(&mut self) -> Result<()> {
let transaction = self.database.transaction()?;
let ids = self
.config
.workspaces
.iter()
.map(|w| w.id.0.as_str())
.collect::<Vec<_>>();
let stale = {
let mut statement =
transaction.prepare("SELECT DISTINCT workspace_id FROM membership")?;
let rows = statement.query_map([], |row| row.get::<_, String>(0))?;
rows.collect::<std::result::Result<Vec<_>, _>>()?
};
for id in stale {
if !ids.contains(&id.as_str()) {
transaction.execute("DELETE FROM membership WHERE workspace_id=?1", [id])?;
}
}
for workspace in &self.config.workspaces {
let key = format!("definition:{}", workspace.id.0);
let revision = digest(&serde_json::to_vec(&(
&workspace.root,
&workspace.discovery,
))?);
let previous: Option<String> = transaction
.query_row("SELECT value FROM state WHERE key=?1", [&key], |row| {
row.get(0)
})
.optional()?;
if previous.as_ref() != Some(&revision) {
transaction.execute(
"UPDATE membership SET availability='unavailable' WHERE workspace_id=?1",
[&workspace.id.0],
)?;
transaction.execute(
"DELETE FROM state WHERE key=?1",
[format!("scan:{}", workspace.id.0)],
)?;
}
transaction.execute(
"INSERT OR REPLACE INTO state(key,value) VALUES(?1,?2)",
params![key, revision],
)?;
}
let active: Option<String> = transaction
.query_row("SELECT value FROM state WHERE key='active'", [], |row| {
row.get(0)
})
.optional()?;
if active
.as_ref()
.is_some_and(|id| !ids.contains(&id.as_str()))
{
transaction.execute("DELETE FROM state WHERE key='active'", [])?;
}
transaction.execute(
"INSERT OR REPLACE INTO state(key,value) VALUES('config_revision',?1)",
[digest(&serde_json::to_vec(&self.config)?)],
)?;
transaction.commit()?;
Ok(())
}
fn save(&mut self, next: Config) -> Result<()> {
validate_config(&next, &self.directory)?;
let text = toml::to_string_pretty(&next)
.map_err(|_| storage("Cannot serialize workspace configuration"))?;
if text.len() > 2 * 1024 * 1024 {
return Err(storage(
"Workspace configuration exceeds its readable size limit",
));
}
let temporary = self
.directory
.join(format!("config-{}.tmp", Uuid::new_v4()));
let result = (|| -> Result<()> {
let mut file = private_create(&temporary)?;
file.write_all(text.as_bytes())?;
file.sync_all()?;
drop(file);
fs::rename(&temporary, self.directory.join("config.toml"))?;
File::open(&self.directory)?.sync_all()?;
Ok(())
})();
if result.is_err() {
let _ = fs::remove_file(&temporary);
}
result?;
self.config = next;
self.reconcile()
}
pub fn list(&self) -> &[Workspace] {
&self.config.workspaces
}
pub fn create(&mut self, name: &str, root: &Path) -> Result<Workspace> {
let display_root = NativePath::from_path(root);
let root = fs::canonicalize(root)
.map_err(|_| Error::with_kind(ErrorKind::Unavailable, "Workspace root unavailable"))?;
if !root.is_dir() {
return Err(Error::with_kind(
ErrorKind::InvalidPath,
"Workspace root must be a directory",
));
}
let workspace = Workspace {
id: WorkspaceId(Uuid::new_v4().to_string()),
name: name.to_owned(),
root: NativePath::from_path(&root),
display_root,
discovery: DiscoveryOptions::default(),
};
let mut next = self.config.clone();
next.workspaces.push(workspace.clone());
self.save(next)?;
Ok(workspace)
}
pub fn update(
&mut self,
id: &WorkspaceId,
name: Option<&str>,
root: Option<&Path>,
options: Option<DiscoveryOptions>,
) -> Result<()> {
let mut next = self.config.clone();
let workspace = next
.workspaces
.iter_mut()
.find(|w| &w.id == id)
.ok_or_else(|| Error::with_kind(ErrorKind::InvalidRequest, "Unknown workspace"))?;
if let Some(name) = name {
workspace.name = name.to_owned();
}
if let Some(root) = root {
workspace.display_root = NativePath::from_path(root);
let root = fs::canonicalize(root)?;
if !root.is_dir() {
return Err(Error::with_kind(
ErrorKind::InvalidPath,
"Workspace root must be a directory",
));
}
workspace.root = NativePath::from_path(&root);
}
if let Some(options) = options {
workspace.discovery = options;
}
let current = self.definition(id)?;
if current.root != workspace.root || current.discovery != workspace.discovery {
self.require_resolved(id)?;
}
self.save(next)
}
pub fn remove(&mut self, id: &WorkspaceId) -> Result<()> {
let mut next = self.config.clone();
self.definition(id)?;
self.require_resolved(id)?;
next.workspaces.retain(|w| &w.id != id);
self.save(next)
}
pub fn activate(&self, id: &WorkspaceId) -> Result<()> {
self.definition(id)?;
self.database.execute(
"INSERT OR REPLACE INTO state(key,value) VALUES('active',?1)",
[&id.0],
)?;
Ok(())
}
pub fn active(&self) -> Result<Option<WorkspaceId>> {
Ok(self
.database
.query_row("SELECT value FROM state WHERE key='active'", [], |row| {
row.get(0)
})
.optional()?
.map(WorkspaceId))
}
fn definition(&self, id: &WorkspaceId) -> Result<&Workspace> {
self.config
.workspaces
.iter()
.find(|w| &w.id == id)
.ok_or_else(|| Error::with_kind(ErrorKind::InvalidRequest, "Unknown workspace"))
}
pub fn scan(&mut self, id: &WorkspaceId) -> Result<WorkspaceInventory> {
self.scan_with_options(id, &inspection::ReadOptions::default())
}
pub fn scan_with_options(
&mut self,
id: &WorkspaceId,
options: &inspection::ReadOptions,
) -> Result<WorkspaceInventory> {
let workspace = self.definition(id)?.clone();
let cursor = discovery::Cursor::new(&workspace.root.to_path()?, &workspace.discovery)?;
self.advance_scan(id, cursor, &workspace.discovery, options)
}
pub fn can_continue_scan(&self, id: &WorkspaceId) -> bool {
self.scan_cursor
.as_ref()
.is_some_and(|(owner, _)| owner == &id.0)
}
pub fn continue_scan_with_options(
&mut self,
id: &WorkspaceId,
options: &inspection::ReadOptions,
) -> Result<WorkspaceInventory> {
let workspace = self.definition(id)?.clone();
let cursor = self
.scan_cursor
.as_ref()
.filter(|(owner, _)| owner == &id.0)
.map(|(_, cursor)| cursor.clone())
.ok_or_else(|| {
Error::with_kind(
ErrorKind::InvalidRequest,
"No active discovery continuation; run Rescan",
)
})?;
if !cursor.matches(&workspace.root.to_path()?, &workspace.discovery) {
self.scan_cursor = None;
return Err(Error::with_kind(
ErrorKind::StaleReview,
"Discovery root or exclusions changed; run Rescan",
));
}
self.advance_scan(id, cursor, &workspace.discovery, options)
}
fn advance_scan(
&mut self,
id: &WorkspaceId,
mut cursor: discovery::Cursor,
discovery: &DiscoveryOptions,
options: &inspection::ReadOptions,
) -> Result<WorkspaceInventory> {
let report = cursor.advance(discovery, options)?;
let result = self.store_scan(id, report)?;
self.scan_cursor = result
.scan
.progress
.as_ref()
.map(|_| (id.0.clone(), cursor));
Ok(result)
}
fn store_scan(&mut self, id: &WorkspaceId, report: Inventory) -> Result<WorkspaceInventory> {
let previous = self.inventory(id)?;
let transaction = self.database.transaction()?;
// A resumable scan has not checked every location yet. Absence from
// this slice is not evidence that a previously inspected repo failed.
// Entries actually inspected below still receive their current status.
if report.progress.is_none() {
transaction.execute(
"UPDATE membership SET availability=?2 WHERE workspace_id=?1",
params![
id.0,
if report.complete {
"missing"
} else {
"unavailable"
}
],
)?;
}
for entry in &report.repositories {
let metadata = &entry.metadata;
let repository_id: Option<String> = transaction
.query_row(
"SELECT id FROM repositories WHERE binding=?1",
[&metadata.common_binding],
|row| row.get(0),
)
.optional()?;
let repository_id = repository_id.unwrap_or_else(|| Uuid::new_v4().to_string());
transaction.execute(
"INSERT OR IGNORE INTO repositories(id,binding) VALUES(?1,?2)",
params![repository_id, metadata.common_binding],
)?;
let binding = digest(&serde_json::to_vec(&(
&metadata.root_binding,
&metadata.git_binding,
&metadata.common_binding,
))?);
let worktree_id: Option<String> = transaction
.query_row(
"SELECT id FROM worktrees WHERE binding=?1",
[&binding],
|row| row.get(0),
)
.optional()?;
let worktree_id = worktree_id.unwrap_or_else(|| Uuid::new_v4().to_string());
// A successful inspection establishes a current identity at this exact
// path. Keep old IDs and their state; never transfer authority or drafts.
if entry.status.is_some() {
transaction.execute(
"DELETE FROM state WHERE key=?1",
[format!("superseded:{}:{}", id.0, worktree_id)],
)?;
for old in &previous {
if old.id.0 != worktree_id && old.metadata.root == metadata.root {
transaction.execute(
"INSERT OR REPLACE INTO state(key,value) VALUES(?1,?2)",
params![
format!("superseded:{}:{}", id.0, old.id.0),
serde_json::to_string(&WorktreeId(worktree_id.clone()))?
],
)?;
}
}
}
let serialized = serde_json::to_string(metadata)?;
transaction.execute("INSERT INTO worktrees(id,repository_id,binding,metadata) VALUES(?1,?2,?3,?4) ON CONFLICT(binding) DO UPDATE SET metadata=excluded.metadata",params![worktree_id,repository_id,binding,serialized])?;
transaction.execute("INSERT OR REPLACE INTO membership(workspace_id,worktree_id,availability,status,issue) VALUES(?1,?2,?3,?4,?5)",params![id.0,worktree_id,if entry.status.is_some(){"available"}else{"unavailable"},entry.status.as_ref().map(serde_json::to_string).transpose()?,entry.issue.as_ref().map(serde_json::to_string).transpose()?])?;
}
let serialized = serde_json::to_string(&report)?;
if serialized.len() > 64 * 1024 * 1024 {
return Err(Error::with_kind(
ErrorKind::OutputLimit,
"Inventory cache exceeds budget",
));
}
transaction.execute(
"INSERT OR REPLACE INTO state(key,value) VALUES(?1,?2)",
params![format!("scan:{}", id.0), serialized],
)?;
transaction.commit()?;
Ok(WorkspaceInventory {
workspace_id: id.clone(),
scan: report,
entries: self.inventory(id)?,
})
}
#[cfg(feature = "application-services")]
pub(crate) fn record_failed_scan(&mut self, id: &WorkspaceId, error: Error) -> Result<()> {
let root = self.definition(id)?.root.clone();
let report = Inventory {
root: root.clone(),
complete: false,
repositories: Vec::new(),
relationships: Vec::new(),
issues: vec![discovery::ScanIssue {
path: root,
error: error.into(),
}],
skipped_caches: Vec::new(),
progress: None,
};
// A failed traversal supplies no evidence about previously observed members.
self.database.execute(
"INSERT OR REPLACE INTO state(key,value) VALUES(?1,?2)",
params![format!("scan:{}", id.0), serde_json::to_string(&report)?],
)?;
self.scan_cursor = None;
Ok(())
}
pub fn last_scan(&self, id: &WorkspaceId) -> Result<Option<Inventory>> {
self.definition(id)?;
let value: Option<String> = self
.database
.query_row(
"SELECT value FROM state WHERE key=?1",
[format!("scan:{}", id.0)],
|row| row.get(0),
)
.optional()?;
value
.map(|value| serde_json::from_str(&value).map_err(Error::from))
.transpose()
}
pub fn inventory(&self, id: &WorkspaceId) -> Result<Vec<StoredWorktree>> {
#[cfg(test)]
INVENTORY_WORK.with(|n| n.set((n.get().0 + 1, n.get().1)));
let workspace_root = self.definition(id)?.root.to_path()?;
let mut statement=self.database.prepare("SELECT w.id,w.repository_id,w.metadata,m.availability,m.status,m.issue,s.value FROM worktrees w JOIN membership m ON m.worktree_id=w.id LEFT JOIN state s ON s.key='superseded:'||m.workspace_id||':'||w.id WHERE m.workspace_id=?1 ORDER BY w.id")?;
let rows = statement.query_map([&id.0], |row| {
Ok((
row.get::<_, String>(0)?,
row.get::<_, String>(1)?,
row.get::<_, String>(2)?,
row.get::<_, String>(3)?,
row.get::<_, Option<String>>(4)?,
row.get::<_, Option<String>>(5)?,
row.get::<_, Option<String>>(6)?,
))
})?;
let mut entries = rows
.map(|row| {
let (id, repository_id, metadata, availability, status, issue, superseded) = row?;
#[cfg(test)]
INVENTORY_WORK.with(|n| n.set((n.get().0, n.get().1 + 1)));
let metadata: Metadata = serde_json::from_str(&metadata)?;
let root = metadata.root.to_path()?;
let display_path =
NativePath::from_path(root.strip_prefix(&workspace_root).unwrap_or(&root));
Ok(StoredWorktree {
display_path,
id: WorktreeId(id.clone()),
repository_id: RepositoryId(repository_id),
metadata,
availability: match availability.as_str() {
"available" => Availability::Available,
"missing" => Availability::Missing,
_ => Availability::Unavailable,
},
status: status.map(|s| serde_json::from_str(&s)).transpose()?,
issue: issue.map(|s| serde_json::from_str(&s)).transpose()?,
untrusted: true,
superseded_by: superseded
.map(|value| serde_json::from_str(&value))
.transpose()?,
})
})
.collect::<Result<Vec<_>>>()?;
let heads = observed_heads(&entries)?;
for entry in &mut entries {
reflect_child_heads(entry, &heads)?;
}
Ok(entries)
}
/// A targeted status refresh does not recursively rediscover the workspace.
pub fn refresh(&mut self, workspace: &WorkspaceId, id: &WorktreeId) -> Result<StoredWorktree> {
self.refresh_with_options(workspace, id, &inspection::ReadOptions::default())
}
pub fn refresh_with_options(
&mut self,
workspace: &WorkspaceId,
id: &WorktreeId,
options: &inspection::ReadOptions,
) -> Result<StoredWorktree> {
let entries = self.inventory(workspace)?;
let heads = observed_heads(&entries)?;
let old = entries
.into_iter()
.find(|entry| &entry.id == id)
.ok_or_else(|| Error::with_kind(ErrorKind::InvalidRequest, "Unknown worktree"))?;
self.refresh_entry(workspace, old, &heads, options)
}
#[cfg(feature = "application-services")]
pub(crate) fn status_pass(&self, workspace: &WorkspaceId) -> Result<StatusPass> {
let entries = self.inventory(workspace)?;
let heads = observed_heads(&entries)?;
Ok(StatusPass {
workspace: workspace.clone(),
heads,
pending: entries
.into_iter()
.filter(|e| e.superseded_by.is_none())
.collect(),
})
}
#[cfg(feature = "application-services")]
pub(crate) fn refresh_next(
&mut self,
pass: &mut StatusPass,
options: &inspection::ReadOptions,
) -> Result<()> {
let Some(old) = pass.pending.pop_front() else {
return Ok(());
};
let root = old.metadata.root.to_path()?;
match self.refresh_entry(&pass.workspace, old, &pass.heads, options) {
Ok(entry) => {
pass.heads.remove(&root);
if let Some(head) = entry.status.and_then(|s| s.head_oid) {
pass.heads.insert(root, head);
}
Ok(())
}
Err(error) => {
pass.heads.remove(&root);
Err(error)
}
}
}
fn refresh_entry(
&mut self,
workspace: &WorkspaceId,
old: StoredWorktree,
heads: &BTreeMap<PathBuf, ObjectId>,
options: &inspection::ReadOptions,
) -> Result<StoredWorktree> {
let id = &old.id;
if old.superseded_by.is_some() {
return Err(Error::with_kind(
ErrorKind::Unavailable,
"Historical repository identity; rescan to inspect the current repository",
));
}
let root = old.metadata.root.to_path()?;
let workspace_root = self.definition(workspace)?.root.to_path()?;
let refreshed = (|| -> Result<Snapshot> {
if !root.starts_with(&workspace_root) {
return Err(Error::with_kind(
ErrorKind::InvalidPath,
"Worktree is outside the updated workspace root; rescan required",
));
}
let actual = inspection::repository_metadata_with_options(&root, options)?;
if actual.root_binding != old.metadata.root_binding
|| actual.git_binding != old.metadata.git_binding
|| actual.common_binding != old.metadata.common_binding
{
return Err(Error::with_kind(
ErrorKind::ConcurrentChange,
"Worktree identity was replaced; rescan required",
));
}
inspection::snapshot_with_options(&root, options)
})();
let status = match refreshed {
Ok(status) => status,
Err(error) => {
let issue = Issue {
kind: error.kind,
message: error.to_string(),
};
self.database.execute("UPDATE membership SET availability='unavailable',issue=?3 WHERE workspace_id=?1 AND worktree_id=?2",params![workspace.0,id.0,serde_json::to_string(&issue)?])?;
return Err(error);
}
};
self.database.execute("UPDATE membership SET status=?3,issue=NULL,availability='available' WHERE workspace_id=?1 AND worktree_id=?2",params![workspace.0,id.0,serde_json::to_string(&status)?])?;
let mut entry = StoredWorktree {
status: Some(status),
availability: Availability::Available,
issue: None,
..old
};
reflect_child_heads(&mut entry, heads)?;
Ok(entry)
}
}
fn validate_config(config: &Config, directory: &Path) -> Result<()> {
let mut ids = std::collections::BTreeSet::new();
for workspace in &config.workspaces {
if Uuid::parse_str(&workspace.id.0).is_err()
|| !ids.insert(&workspace.id.0)
|| workspace.name.trim().is_empty()
{
return Err(storage("Invalid/duplicate workspace ID or empty name"));
}
let root = workspace.root.to_path()?;
if !root.is_absolute() || directory.starts_with(&root) {
return Err(Error::with_kind(
ErrorKind::InvalidPath,
"Workspace root must be absolute and outside application state",
));
}
workspace.discovery.validate()?;
}
Ok(())
}
#[cfg(test)]
thread_local! { pub(crate) static INVENTORY_WORK: std::cell::Cell<(usize,usize)> = const {std::cell::Cell::new((0,0))}; }