1use std::collections::BTreeMap;
14use std::path::{Path, PathBuf};
15
16use serde::{Deserialize, Serialize};
17
18use crate::env::Env;
19use crate::error::{CoreError, ErrorCode};
20use crate::fs::Fs;
21use crate::model::SCHEMA_VERSION;
22use crate::remote::config::{RemoteConfig, RemoteKind, RemotesFile};
23use crate::remote::folder::{self, PullReport, PushOutcome};
24use crate::remote::git::{self, GitCli, GitPush, Runner};
25use crate::remote::manifest::MachineManifest;
26use crate::remote::unc::UncResolver;
27use crate::store::diff::{ChangeKind, EntityChange};
28use crate::store::{CommitId, Machine, Store, utc_datetime};
29
30pub const STATUS_FILE: &str = "remote-status.toml";
32const INCOMING_LIMIT: usize = 1000;
34
35pub struct SyncEnv<'a> {
37 pub unc: &'a dyn UncResolver,
38 pub runner: &'a dyn Runner,
39 pub helper: Option<PathBuf>,
41 pub app_version: &'a str,
43}
44
45impl SyncEnv<'_> {
46 fn git(&self, store: &Store<'_>) -> Result<GitCli<'_>, CoreError> {
47 GitCli::from_env(store.env(), store.fs(), self.runner, self.helper.clone())
48 }
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum Pushed {
54 Folder(PushOutcome),
55 Git(GitPush),
56}
57
58pub type PushResult = (String, Result<Pushed, CoreError>);
60pub type PullResult = (String, Result<PullReport, CoreError>);
62
63#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
65pub struct RecordedError {
66 pub code: ErrorCode,
67 pub message: String,
68 pub at: String,
70}
71
72#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
74pub struct RemoteRecord {
75 #[serde(default, skip_serializing_if = "Option::is_none")]
77 pub pushed_at: Option<String>,
78 #[serde(default, skip_serializing_if = "Option::is_none")]
79 pub pushed_head: Option<String>,
80 #[serde(default, skip_serializing_if = "Option::is_none")]
82 pub pulled_at: Option<String>,
83 #[serde(default, skip_serializing_if = "Option::is_none")]
85 pub error: Option<RecordedError>,
86}
87
88#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
90pub struct StatusFile {
91 pub schema: i64,
92 #[serde(default, rename = "remote")]
93 pub remotes: BTreeMap<String, RemoteRecord>,
94 #[serde(flatten)]
95 pub extra: toml::Table,
96}
97
98impl Default for StatusFile {
99 fn default() -> Self {
100 Self {
101 schema: SCHEMA_VERSION,
102 remotes: BTreeMap::new(),
103 extra: toml::Table::new(),
104 }
105 }
106}
107
108impl StatusFile {
109 pub fn load(fs: &dyn Fs, state_dir: &Path) -> Self {
112 fs.read_to_string(&state_dir.join(STATUS_FILE))
113 .ok()
114 .and_then(|text| toml::from_str::<Self>(&text).ok())
115 .filter(|file| file.schema == SCHEMA_VERSION)
116 .unwrap_or_default()
117 }
118
119 pub fn save(&self, fs: &dyn Fs, state_dir: &Path) -> Result<(), CoreError> {
122 let path = state_dir.join(STATUS_FILE);
123 if crate::versions::written_by_newer(
124 fs,
125 &path,
126 crate::versions::Format::Toml,
127 SCHEMA_VERSION,
128 ) {
129 return Ok(());
130 }
131 let text = toml::to_string_pretty(self).map_err(|err| {
132 CoreError::new(
133 ErrorCode::InvalidValue,
134 format!("cannot write remote status: {err}"),
135 )
136 })?;
137 crate::apply::write_atomic(fs, &path, text.as_bytes())
138 }
139
140 fn retain(&mut self, remotes: &RemotesFile) {
142 self.remotes.retain(|name, _| remotes.get(name).is_some());
143 }
144}
145
146fn now(env: &Env) -> String {
147 utc_datetime(env.now()).to_string()
148}
149
150fn record_error(env: &Env, err: &CoreError) -> RecordedError {
151 RecordedError {
152 code: err.code(),
153 message: err.message().to_owned(),
154 at: now(env),
155 }
156}
157
158fn save_records(store: &Store<'_>, remotes: &RemotesFile, update: impl FnOnce(&mut StatusFile)) {
161 let mut file = StatusFile::load(store.fs(), store.state_dir());
162 update(&mut file);
163 file.retain(remotes);
164 let _ = file.save(store.fs(), store.state_dir());
165}
166
167pub fn push_to(
171 store: &Store<'_>,
172 remotes: &RemotesFile,
173 name: Option<&str>,
174 sx: &SyncEnv<'_>,
175 progress: &mut dyn FnMut(&str, &str),
176) -> Result<Vec<PushResult>, CoreError> {
177 let results: Vec<PushResult> = remotes
178 .select(name)?
179 .into_iter()
180 .map(|remote| {
181 let result = push_one(store, remote, sx, &mut |line| progress(&remote.name, line));
182 (remote.name.clone(), result)
183 })
184 .collect();
185 let env = store.env();
186 save_records(store, remotes, |file| {
187 for (name, result) in &results {
188 let record = file.remotes.entry(name.clone()).or_default();
189 match result {
190 Ok(pushed) => {
191 record.pushed_at = Some(now(env));
192 record.pushed_head = Some(
193 match pushed {
194 Pushed::Folder(outcome) => &outcome.head,
195 Pushed::Git(outcome) => &outcome.head,
196 }
197 .to_string(),
198 );
199 record.error = None;
200 }
201 Err(err) => record.error = Some(record_error(env, err)),
202 }
203 }
204 });
205 Ok(results)
206}
207
208fn push_one(
209 store: &Store<'_>,
210 remote: &RemoteConfig,
211 sx: &SyncEnv<'_>,
212 progress: &mut dyn FnMut(&str),
213) -> Result<Pushed, CoreError> {
214 match remote.kind {
215 RemoteKind::Folder => {
216 folder::push(store, remote, sx.unc, sx.app_version).map(Pushed::Folder)
217 }
218 RemoteKind::Git => {
219 let cli = sx.git(store)?;
220 git::push(store, &cli, remote, progress).map(Pushed::Git)
221 }
222 }
223}
224
225pub fn pull_from(
228 store: &Store<'_>,
229 remotes: &RemotesFile,
230 name: Option<&str>,
231 sx: &SyncEnv<'_>,
232 progress: &mut dyn FnMut(&str, &str),
233) -> Result<Vec<PullResult>, CoreError> {
234 let mut results = Vec::new();
235 for remote in remotes.select(name)? {
236 let report = match remote.kind {
237 RemoteKind::Folder => folder::pull(store, remote, sx.unc),
238 RemoteKind::Git => sx.git(store).and_then(|cli| {
239 git::pull(store, &cli, remote, &mut |line| {
240 progress(&remote.name, line)
241 })
242 }),
243 };
244 results.push((remote.name.clone(), report));
245 }
246 let env = store.env();
247 save_records(store, remotes, |file| {
248 for (name, result) in &results {
249 let record = file.remotes.entry(name.clone()).or_default();
250 match result {
251 Ok(_) => {
252 record.pulled_at = Some(now(env));
253 record.error = None;
254 }
255 Err(err) => record.error = Some(record_error(env, err)),
256 }
257 }
258 });
259 Ok(results)
260}
261
262pub fn changed_by_pull(store: &Store<'_>, report: &PullReport) -> (usize, usize) {
264 if report.head_before == report.head_after {
265 return (0, 0);
266 }
267 let changes: Vec<EntityChange> = store
268 .semantic_diff(Some(&report.head_before), &report.head_after)
269 .unwrap_or_default();
270 let mut servers: Vec<&str> = Vec::new();
271 let mut skills: Vec<&str> = Vec::new();
272 for change in &changes {
273 if change.kind == ChangeKind::Changed && change.fields.is_empty() && change.text.is_none() {
274 continue;
275 }
276 let list = if change.entity.starts_with("server/") {
277 &mut servers
278 } else if change.entity.starts_with("skill/") {
279 &mut skills
280 } else {
281 continue;
282 };
283 if !list.contains(&change.entity.as_str()) {
284 list.push(&change.entity);
285 }
286 }
287 (servers.len(), skills.len())
288}
289
290#[derive(Debug, Clone, PartialEq, Eq)]
292pub struct RemoteStatus {
293 pub name: String,
294 pub reachable: Option<bool>,
297 pub pushed_head: Option<CommitId>,
299 pub pushed_at: Option<String>,
300 pub pulled_at: Option<String>,
301 pub ahead: Option<usize>,
304 pub behind: Option<usize>,
307 pub last_error: Option<RecordedError>,
308}
309
310pub fn status(
313 env: &Env,
314 fs: &dyn Fs,
315 unc: &dyn UncResolver,
316 state_dir: &Path,
317 store: Option<&Store<'_>>,
318 remote: &RemoteConfig,
319) -> RemoteStatus {
320 let record = StatusFile::load(fs, state_dir)
321 .remotes
322 .remove(&remote.name)
323 .unwrap_or_default();
324 let mut status = RemoteStatus {
325 name: remote.name.clone(),
326 reachable: None,
327 pushed_head: record
328 .pushed_head
329 .as_deref()
330 .and_then(|id| CommitId::from_text(id).ok()),
331 pushed_at: record.pushed_at,
332 pulled_at: record.pulled_at,
333 ahead: None,
334 behind: None,
335 last_error: record.error,
336 };
337 match remote.kind {
338 RemoteKind::Folder => folder_status(env, fs, unc, state_dir, store, remote, &mut status),
339 RemoteKind::Git => git_status(store, remote, &mut status),
340 }
341 status
342}
343
344fn folder_status(
345 env: &Env,
346 fs: &dyn Fs,
347 unc: &dyn UncResolver,
348 state_dir: &Path,
349 store: Option<&Store<'_>>,
350 remote: &RemoteConfig,
351 status: &mut RemoteStatus,
352) {
353 let Ok(root) = folder::reachable_root(fs, env.os(), unc, remote) else {
354 status.reachable = Some(false);
355 return;
356 };
357 status.reachable = Some(true);
358 let Some(store) = store else {
359 return;
360 };
361 let Ok(Some(machine)) = Machine::load(fs, state_dir) else {
362 return;
363 };
364 let own = MachineManifest::load(fs, &root.join(store.store_id()).join(&machine.id));
367 status.pushed_head = own
368 .as_ref()
369 .and_then(|manifest| manifest.head.as_deref())
370 .and_then(|id| CommitId::from_text(id).ok());
371 if let Some(manifest) = &own {
372 status.pushed_at = Some(manifest.pushed_at.clone());
373 }
374 status.ahead = ahead(store, status.pushed_head.as_ref());
375 let Ok(listing) = folder::list(fs, &root, Some(store.store_id())) else {
376 return;
377 };
378 let mut behind = 0;
379 for sibling in &listing.machines {
380 if sibling.machine_id == machine.id || !sibling.has_repo(fs) {
381 continue;
382 }
383 let Some(head) = sibling.manifest.head.as_deref() else {
384 continue;
385 };
386 behind += store
388 .bare_incoming(&sibling.dir.join("store.git"), head, INCOMING_LIMIT)
389 .unwrap_or(0);
390 }
391 status.behind = Some(behind);
392}
393
394fn git_status(store: Option<&Store<'_>>, remote: &RemoteConfig, status: &mut RemoteStatus) {
395 let Some(store) = store else {
396 return;
397 };
398 let tracking = store
399 .reference_target(&format!("refs/remotes/{}/main", remote.name))
400 .ok()
401 .flatten();
402 let known: Vec<CommitId> = [status.pushed_head.clone(), tracking.clone()]
407 .into_iter()
408 .flatten()
409 .collect();
410 let head = store.head().ok();
411 status.ahead = head
412 .as_ref()
413 .and_then(|head| store.count_not_in(head, &known).ok().flatten());
414 status.behind = match (&tracking, &head) {
415 (Some(fetched), Some(head)) => store
416 .ahead_behind(head, fetched)
417 .ok()
418 .map(|(_, behind)| behind),
419 _ => status.ahead.map(|_| 0),
420 };
421}
422
423fn ahead(store: &Store<'_>, upstream: Option<&CommitId>) -> Option<usize> {
425 let upstream = upstream?;
426 if !store.contains(upstream) {
427 return None;
428 }
429 let head = store.head().ok()?;
430 store
431 .ahead_behind(&head, upstream)
432 .ok()
433 .map(|(ahead, _)| ahead)
434}