Milestone 7: the app normal people install (macOS)
A Tauri menu-bar app runs the same sync engine as `lunesync run`. It connects from the website with no code typed (lune://join and lune://pair links), shows status in the menu bar, and lets a person resolve held secrets, held big changes and kept-both notes side by side. Uninstall shares and hands over first, then removes only what Lune created. Releases are signed on the hub that holds the key (`lunehub release keygen/publish`); other hubs `release import` them. Apps verify the signature and the signed version. Clients older than the previous release are asked to update and keep saving locally. A device can now be on several hubs at once (own and workplace), each with its own key; the CLI takes --team when it matters. The supervisor and status summary moved into core, shared by the CLI and the app. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -15,9 +15,13 @@ pub struct Config {
|
||||
/// Where vaults from the hub are placed (default ~/Vaults).
|
||||
#[serde(default)]
|
||||
pub vaults_dir: Option<PathBuf>,
|
||||
/// This device's hub sign-in, once it has joined or logged in.
|
||||
/// This device's hub sign-ins: one per team it belongs to (a person's own hub, a workplace hub).
|
||||
#[serde(default)]
|
||||
pub hub: Option<crate::hub::HubLink>,
|
||||
pub hubs: Vec<crate::hub::HubLink>,
|
||||
/// Before M7 a device had one hub, stored as `[hub]`; read once and moved into `hubs`.
|
||||
#[serde(default, rename = "hub", skip_serializing)]
|
||||
#[doc(hidden)]
|
||||
pub legacy_hub: Option<crate::hub::HubLink>,
|
||||
#[serde(default, rename = "vault")]
|
||||
pub vaults: Vec<VaultConfig>,
|
||||
}
|
||||
@@ -28,9 +32,12 @@ pub struct VaultConfig {
|
||||
pub path: PathBuf,
|
||||
pub remote: String,
|
||||
pub branch: String,
|
||||
/// The hub's id for this vault, when it syncs through the hub.
|
||||
/// The hub's id for this vault, when it syncs through a hub.
|
||||
#[serde(default)]
|
||||
pub hub_vault: Option<i64>,
|
||||
/// Which hub that is (ids are per hub).
|
||||
#[serde(default)]
|
||||
pub hub_url: Option<String>,
|
||||
}
|
||||
|
||||
/// Directory holding `config.toml`. `LUNE_HOME` overrides it (handy for running two devices on one machine).
|
||||
@@ -50,7 +57,18 @@ impl Config {
|
||||
pub fn load() -> Result<Config> {
|
||||
let path = Self::path()?;
|
||||
match std::fs::read_to_string(&path) {
|
||||
Ok(text) => toml::from_str(&text).with_context(|| format!("can't read {}", path.display())),
|
||||
Ok(text) => {
|
||||
let mut c: Config = toml::from_str(&text).with_context(|| format!("can't read {}", path.display()))?;
|
||||
if let Some(h) = c.legacy_hub.take() {
|
||||
for v in c.vaults.iter_mut().filter(|v| v.hub_vault.is_some() && v.hub_url.is_none()) {
|
||||
v.hub_url = Some(h.url.clone());
|
||||
}
|
||||
if !c.hubs.iter().any(|x| x.url == h.url) {
|
||||
c.hubs.insert(0, h);
|
||||
}
|
||||
}
|
||||
Ok(c)
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Config::default()),
|
||||
Err(e) => Err(e).with_context(|| format!("can't read {}", path.display())),
|
||||
}
|
||||
@@ -77,10 +95,34 @@ impl Config {
|
||||
.unwrap_or_else(|| dirs::home_dir().unwrap_or_default().join("Vaults"))
|
||||
}
|
||||
|
||||
/// Makes the hub's device key available to Git requests in this process.
|
||||
/// Makes each hub's device key available to Git requests in this process.
|
||||
pub fn use_hub_credentials(&self) {
|
||||
if let Some(h) = &self.hub {
|
||||
crate::remote::set_hub(h.clone());
|
||||
crate::remote::set_hubs(&self.hubs);
|
||||
}
|
||||
|
||||
pub fn hub(&self, url: &str) -> Option<&crate::hub::HubLink> {
|
||||
self.hubs.iter().find(|h| h.url == url)
|
||||
}
|
||||
|
||||
/// The hub a vault syncs through, if any.
|
||||
pub fn hub_of(&self, v: &VaultConfig) -> Option<&crate::hub::HubLink> {
|
||||
v.hub_vault?;
|
||||
self.hub(v.hub_url.as_deref()?)
|
||||
}
|
||||
|
||||
/// Picks a hub: the one whose address contains `sel` (e.g. its host name), else the only one.
|
||||
pub fn pick_hub(&self, sel: Option<&str>) -> Result<&crate::hub::HubLink> {
|
||||
match (sel, self.hubs.as_slice()) {
|
||||
(_, []) => bail!("this device isn't on a hub yet — `lunesync join <invite link>` or `lunesync login`"),
|
||||
(Some(s), all) => all
|
||||
.iter()
|
||||
.find(|h| h.url.contains(s))
|
||||
.with_context(|| format!("this device isn't on a hub matching \"{s}\"")),
|
||||
(None, [only]) => Ok(only),
|
||||
(None, all) => {
|
||||
let names: Vec<&str> = all.iter().map(|h| h.url.as_str()).collect();
|
||||
bail!("this device is on several hubs ({}) — say which with --team <host>", names.join(", "))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -97,6 +97,7 @@ fn agent() -> ureq::Agent {
|
||||
ureq::Agent::config_builder()
|
||||
.http_status_as_error(false)
|
||||
.timeout_global(Some(Duration::from_secs(30)))
|
||||
.user_agent(crate::remote::user_agent())
|
||||
.build()
|
||||
.into()
|
||||
}
|
||||
|
||||
@@ -11,5 +11,7 @@ pub mod remote;
|
||||
pub mod runner;
|
||||
pub mod secrets;
|
||||
pub mod state;
|
||||
pub mod status;
|
||||
pub mod supervisor;
|
||||
pub mod tidy;
|
||||
pub mod vault;
|
||||
|
||||
@@ -7,36 +7,69 @@ use crate::secrets;
|
||||
use crate::state;
|
||||
use crate::vault::{self, Vault};
|
||||
use anyhow::{Result, bail};
|
||||
use std::path::Path;
|
||||
use serde::Serialize;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// What a leaving note gets instead of a secret: the secret itself is never sent or kept (P1).
|
||||
const REDACTED: &str = "[secret removed when leaving]";
|
||||
|
||||
/// New vaults arrive, same-named local vaults move onto the hub, roles refresh, and vaults whose access
|
||||
/// ended are handed over and leave. Returns what happened, in plain words.
|
||||
/// For every hub this device is on: new vaults arrive, same-named local vaults move onto the hub, roles
|
||||
/// refresh, and vaults whose access ended are handed over and leave. Returns what happened, in plain words.
|
||||
/// One hub failing doesn't stop the others; the first error comes back after the rest have run.
|
||||
pub fn arrive(config: &mut Config) -> Result<Vec<String>> {
|
||||
let Some(h) = config.hub.clone() else { return Ok(vec![]) };
|
||||
let mut said = vec![];
|
||||
let mut failed = None;
|
||||
for (_, result) in arrive_each(config) {
|
||||
match result {
|
||||
Ok(mut msgs) => said.append(&mut msgs),
|
||||
Err(e) => failed = failed.or(Some(e)),
|
||||
}
|
||||
}
|
||||
match failed {
|
||||
Some(e) if said.is_empty() => Err(e),
|
||||
Some(e) => {
|
||||
said.push(format!("can't check the hub: {e:#}"));
|
||||
Ok(said)
|
||||
}
|
||||
None => Ok(said),
|
||||
}
|
||||
}
|
||||
|
||||
/// `arrive`, hub by hub: (hub address, what happened there).
|
||||
pub fn arrive_each(config: &mut Config) -> Vec<(String, Result<Vec<String>>)> {
|
||||
let several = config.hubs.len() > 1;
|
||||
let mut out = vec![];
|
||||
for h in config.hubs.clone() {
|
||||
let result = arrive_from(config, &h).map_err(|e| if several { e.context(h.url.clone()) } else { e });
|
||||
out.push((h.url, result));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn arrive_from(config: &mut Config, h: &HubLink) -> Result<Vec<String>> {
|
||||
let me = match h.me() {
|
||||
Ok(me) => me,
|
||||
Err(e) if format!("{e}").contains("isn't signed in") => {
|
||||
// The hub no longer knows this device: it was removed and has nothing left to hand over.
|
||||
config.hub = None;
|
||||
config.vaults.retain(|v| v.hub_vault.is_none());
|
||||
config.hubs.retain(|x| x.url != h.url);
|
||||
config.vaults.retain(|v| v.hub_url.as_deref() != Some(&h.url));
|
||||
config.save()?;
|
||||
return Ok(vec!["This device was removed from the hub. Vaults on other remotes keep syncing.".into()]);
|
||||
return Ok(vec![format!("This device was removed from the hub at {}. Other vaults keep syncing.", h.url)]);
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let label = config.device_label();
|
||||
let mine = |v: &crate::config::VaultConfig, id: i64| v.hub_vault == Some(id) && v.hub_url.as_deref() == Some(&h.url);
|
||||
let mut said = vec![];
|
||||
|
||||
for d in &me.leaving {
|
||||
said.push(leave(config, &h, d)?);
|
||||
said.push(leave(config, h, d)?);
|
||||
}
|
||||
if me.nudge {
|
||||
// Each vault's runner sees this and shares at once.
|
||||
for vc in config.vaults.iter().filter(|v| v.hub_vault.is_some()) {
|
||||
// Each of this hub's vault runners sees this and shares at once.
|
||||
for vc in config.vaults.iter().filter(|v| v.hub_vault.is_some() && v.hub_url.as_deref() == Some(&h.url)) {
|
||||
let dir = state::lune_dir(&vc.path.join(".git"));
|
||||
if dir.exists() {
|
||||
std::fs::write(dir.join("nudge"), "")?;
|
||||
@@ -46,7 +79,7 @@ pub fn arrive(config: &mut Config) -> Result<Vec<String>> {
|
||||
}
|
||||
|
||||
for hv in me.vaults {
|
||||
if let Some(vc) = config.vaults.iter().find(|v| v.hub_vault == Some(hv.id)) {
|
||||
if let Some(vc) = config.vaults.iter().find(|v| mine(v, hv.id)) {
|
||||
let v = Vault::open(vc, &label)?;
|
||||
state::write_role(&v.git_dir, &hv.role)?;
|
||||
continue;
|
||||
@@ -59,17 +92,25 @@ pub fn arrive(config: &mut Config) -> Result<Vec<String>> {
|
||||
v.join_unrelated()?;
|
||||
vc.remote = hv.git_url.clone();
|
||||
vc.hub_vault = Some(hv.id);
|
||||
vc.hub_url = Some(h.url.clone());
|
||||
config.save()?;
|
||||
said.push(format!("{} now syncs through the hub", hv.name));
|
||||
continue;
|
||||
}
|
||||
let path = config.vaults_dir().join(&hv.name);
|
||||
// Two teams can each have a "Notes": the second one gets the team's address in its folder name.
|
||||
let mut path = config.vaults_dir().join(&hv.name);
|
||||
let real = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
|
||||
if config.vaults.iter().any(|v| real(&v.path) == real(&path)) {
|
||||
let host = h.url.split("://").last().unwrap_or(&h.url).replace([':', '/'], "-");
|
||||
path = config.vaults_dir().join(format!("{} ({host})", hv.name));
|
||||
}
|
||||
if path.exists() && std::fs::read_dir(&path)?.next().is_some() && !path.join(".git").exists() {
|
||||
said.push(format!("{} can't arrive: {} already has other files in it", hv.name, path.display()));
|
||||
continue;
|
||||
}
|
||||
let (mut cfg, _, err) = vault::add(&hv.name, &path, &hv.git_url, &label)?;
|
||||
cfg.hub_vault = Some(hv.id);
|
||||
cfg.hub_url = Some(h.url.clone());
|
||||
state::write_role(&path.join(".git"), &hv.role)?;
|
||||
config.vaults.push(cfg);
|
||||
config.save()?;
|
||||
@@ -82,29 +123,36 @@ pub fn arrive(config: &mut Config) -> Result<Vec<String>> {
|
||||
Ok(said)
|
||||
}
|
||||
|
||||
/// Tells the hub how each of this device's hub vaults is doing (M6 freshness).
|
||||
/// Tells each hub how this device's vaults on it are doing (M6 freshness).
|
||||
pub fn report(config: &Config) -> Result<()> {
|
||||
let Some(h) = &config.hub else { return Ok(()) };
|
||||
let label = config.device_label();
|
||||
let mut out = vec![];
|
||||
for vc in config.vaults.iter().filter(|v| v.hub_vault.is_some()) {
|
||||
let Ok(v) = Vault::open(vc, &label) else { continue };
|
||||
out.push(hub::VaultHealth {
|
||||
vault_id: vc.hub_vault.unwrap(),
|
||||
last_synced: state::SyncState::load(&v.git_dir).last_synced,
|
||||
waiting: v.waiting_files().unwrap_or(0),
|
||||
held_secrets: v.secret_holds().map(|n| n.len()).unwrap_or(0),
|
||||
holding: !crate::guard::load(&v.git_dir).is_empty(),
|
||||
});
|
||||
let mut failed = None;
|
||||
for h in &config.hubs {
|
||||
let mut out = vec![];
|
||||
for vc in config.vaults.iter().filter(|v| v.hub_vault.is_some() && v.hub_url.as_deref() == Some(&h.url)) {
|
||||
let Ok(v) = Vault::open(vc, &label) else { continue };
|
||||
out.push(hub::VaultHealth {
|
||||
vault_id: vc.hub_vault.unwrap(),
|
||||
last_synced: state::SyncState::load(&v.git_dir).last_synced,
|
||||
waiting: v.waiting_files().unwrap_or(0),
|
||||
held_secrets: v.secret_holds().map(|n| n.len()).unwrap_or(0),
|
||||
holding: !crate::guard::load(&v.git_dir).is_empty(),
|
||||
});
|
||||
}
|
||||
if let Err(e) = h.report(&out) {
|
||||
failed = Some(e);
|
||||
}
|
||||
}
|
||||
h.report(&out)
|
||||
failed.map_or(Ok(()), Err)
|
||||
}
|
||||
|
||||
/// Leaves one vault: stop syncing, save, make read-only, hand over what wasn't shared, and once the
|
||||
/// hub has it, delete the folder if the app created it.
|
||||
pub fn leave(config: &mut Config, link: &HubLink, d: &Departure) -> Result<String> {
|
||||
let label = config.device_label();
|
||||
let Some(vc) = config.vaults.iter().find(|v| v.hub_vault == Some(d.vault_id)).cloned() else {
|
||||
let Some(vc) =
|
||||
config.vaults.iter().find(|v| v.hub_vault == Some(d.vault_id) && v.hub_url.as_deref() == Some(&link.url)).cloned()
|
||||
else {
|
||||
link.departure_done(d.id, None)?;
|
||||
return Ok(format!("Access to {} ended (it wasn't on this device)", d.vault));
|
||||
};
|
||||
@@ -162,6 +210,117 @@ pub fn leave(config: &mut Config, link: &HubLink, d: &Departure) -> Result<Strin
|
||||
}
|
||||
}
|
||||
|
||||
/// What uninstalling did, in plain words.
|
||||
#[derive(Debug, Default, Serialize)]
|
||||
pub struct Uninstalled {
|
||||
/// Folders deleted.
|
||||
pub removed: Vec<String>,
|
||||
/// Folders left in place, each with why ("path — reason").
|
||||
pub kept: Vec<String>,
|
||||
/// Set when the hub couldn't be told this device is gone.
|
||||
pub hub_problem: Option<String>,
|
||||
}
|
||||
|
||||
/// Uninstall (D5). Every runner must already be stopped (`runner::STOP`). Shares what it can, hands the rest
|
||||
/// over through the hub (A6) and signs this device out, then deletes the vault folders Lune created. A folder
|
||||
/// still holding work that is neither shared nor handed over stays, and so does one the person added (A9).
|
||||
pub fn uninstall(config: &mut Config) -> Result<Uninstalled> {
|
||||
let label = config.device_label();
|
||||
let all = config.vaults.clone();
|
||||
let mut out = Uninstalled::default();
|
||||
let mut unshared: HashMap<PathBuf, String> = HashMap::new();
|
||||
|
||||
for vc in &all {
|
||||
let Ok(v) = Vault::open(vc, &label) else { continue };
|
||||
wait_for_runner(&v)?;
|
||||
let _op = state::op_lock(&v.git_dir)?;
|
||||
let _ = v.save_changes(None, &HashSet::new());
|
||||
if v.role().is_none_or(|r| hub::can_edit(&r)) {
|
||||
let _ = v.sync();
|
||||
}
|
||||
if let Some(why) = unshared_work(&v) {
|
||||
unshared.insert(vc.path.clone(), why);
|
||||
}
|
||||
}
|
||||
|
||||
for link in config.hubs.clone() {
|
||||
let signed_out = link.remove_device(&label, None).and_then(|_| link.me());
|
||||
match signed_out {
|
||||
Ok(me) => {
|
||||
for d in &me.leaving {
|
||||
match leave(config, &link, d) {
|
||||
// Whatever wasn't shared is with the vault's managers now.
|
||||
Ok(_) => {
|
||||
let left = all.iter().find(|v| v.hub_vault == Some(d.vault_id) && v.hub_url.as_deref() == Some(&link.url));
|
||||
if let Some(vc) = left {
|
||||
unshared.remove(&vc.path);
|
||||
}
|
||||
}
|
||||
Err(e) => out.hub_problem = Some(format!("couldn't hand over {}: {e:#}", d.vault)),
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
out.hub_problem = Some(format!(
|
||||
"couldn't reach the hub at {} ({e:#}) — this device still shows on its canvas; remove it there",
|
||||
link.url
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for vc in &all {
|
||||
let shown = vc.path.display().to_string();
|
||||
if !vc.path.exists() {
|
||||
out.removed.push(shown);
|
||||
continue;
|
||||
}
|
||||
let _ = set_read_only(&vc.path, false);
|
||||
let created =
|
||||
state::read_marker(&vc.path.join(".git")).is_some_and(|m| m.created_folder && m.managed_by == "lune");
|
||||
if let Some(why) = unshared.get(&vc.path) {
|
||||
out.kept.push(format!("{shown} — {why}"));
|
||||
} else if !created {
|
||||
out.kept.push(format!("{shown} — you added this folder yourself"));
|
||||
} else {
|
||||
// remove_dir_all removes links themselves, never what they point to (A9).
|
||||
std::fs::remove_dir_all(&vc.path)?;
|
||||
out.removed.push(shown);
|
||||
}
|
||||
}
|
||||
config.vaults.clear();
|
||||
config.hubs.clear();
|
||||
config.save()?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Waits until the vault's runner has let go of it.
|
||||
fn wait_for_runner(v: &Vault) -> Result<()> {
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
while state::try_run_lock(&v.git_dir)?.is_none() {
|
||||
if Instant::now() > deadline {
|
||||
bail!("{} is still busy syncing; try again in a moment", v.name);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(250));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Why a vault still holds work nobody else has, if it does.
|
||||
fn unshared_work(v: &Vault) -> Option<String> {
|
||||
if !v.secret_holds().unwrap_or_default().is_empty() {
|
||||
return Some("a note was held back as a possible secret".into());
|
||||
}
|
||||
if !crate::guard::load(&v.git_dir).is_empty() {
|
||||
return Some("a big change is waiting for you to confirm it".into());
|
||||
}
|
||||
match v.waiting_files().unwrap_or(0) {
|
||||
0 => None,
|
||||
n if v.role().is_some_and(|r| !hub::can_edit(&r)) => Some(format!("{n} changed notes you can't share (read access)")),
|
||||
n => Some(format!("{n} changed notes couldn't be shared (offline?)")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds or removes write permission on everything in the vault folder except `.git`.
|
||||
fn set_read_only(root: &Path, read_only: bool) -> Result<()> {
|
||||
fn walk(dir: &Path, read_only: bool, top: bool) -> Result<()> {
|
||||
|
||||
@@ -4,17 +4,57 @@ use git2::{Cred, CredentialType, ErrorClass, ErrorCode, RemoteCallbacks};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::RwLock;
|
||||
|
||||
static HUB: RwLock<Option<crate::hub::HubLink>> = RwLock::new(None);
|
||||
static HUBS: RwLock<Vec<crate::hub::HubLink>> = RwLock::new(Vec::new());
|
||||
static VERSION: RwLock<Option<String>> = RwLock::new(None);
|
||||
|
||||
/// Git requests to this hub sign in with the device key.
|
||||
/// What the hub says to a client too old to sync (D3).
|
||||
pub const TOO_OLD: &str = "update Lune to keep syncing";
|
||||
|
||||
/// Sets the version this client tells the hub (the desktop app's own version; the crate version otherwise).
|
||||
pub fn set_client_version(version: &str) {
|
||||
*VERSION.write().unwrap() = Some(version.to_string());
|
||||
set_git_user_agent();
|
||||
}
|
||||
|
||||
pub fn client_version() -> String {
|
||||
VERSION.read().unwrap().clone().unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_string())
|
||||
}
|
||||
|
||||
/// `lune/<version>`: how every request says which client it is, so the hub can turn away versions it no
|
||||
/// longer supports.
|
||||
pub fn user_agent() -> String {
|
||||
format!("lune/{}", client_version())
|
||||
}
|
||||
|
||||
/// Git requests carry the same User-Agent (libgit2 can't add headers to every request, but it can name itself).
|
||||
pub fn set_git_user_agent() {
|
||||
let product = std::ffi::CString::new(user_agent()).unwrap();
|
||||
// SAFETY: a documented libgit2 option; libgit2 copies the string.
|
||||
unsafe {
|
||||
libgit2_sys::init();
|
||||
libgit2_sys::git_libgit2_opts(libgit2_sys::GIT_OPT_SET_USER_AGENT_PRODUCT as std::ffi::c_int, product.as_ptr());
|
||||
}
|
||||
}
|
||||
|
||||
/// Git requests to this hub sign in with this device key (replacing any earlier key for the same hub).
|
||||
pub fn set_hub(link: crate::hub::HubLink) {
|
||||
*HUB.write().unwrap() = Some(link);
|
||||
set_git_user_agent();
|
||||
let mut hubs = HUBS.write().unwrap();
|
||||
hubs.retain(|h| h.url != link.url);
|
||||
hubs.push(link);
|
||||
}
|
||||
|
||||
/// Git requests to each of these hubs sign in with that hub's device key.
|
||||
pub fn set_hubs(links: &[crate::hub::HubLink]) {
|
||||
set_git_user_agent();
|
||||
*HUBS.write().unwrap() = links.to_vec();
|
||||
}
|
||||
|
||||
fn hub_credentials(url: &str) -> Option<(String, String)> {
|
||||
let hub = HUB.read().unwrap();
|
||||
let h = hub.as_ref()?;
|
||||
url.starts_with(&h.url).then(|| (h.device_id.clone(), h.key.clone()))
|
||||
let hubs = HUBS.read().unwrap();
|
||||
// The longest matching address wins (two hubs could share a host).
|
||||
let h = hubs.iter().filter(|h| url.starts_with(&format!("{}/", h.url))).max_by_key(|h| h.url.len())?;
|
||||
Some((h.device_id.clone(), h.key.clone()))
|
||||
}
|
||||
|
||||
pub fn callbacks<'a>() -> RemoteCallbacks<'a> {
|
||||
@@ -67,6 +107,9 @@ fn default_key_files() -> Vec<PathBuf> {
|
||||
/// Turns a remote failure into plain words for `status` and the run log.
|
||||
pub fn describe_error(e: &anyhow::Error) -> String {
|
||||
if let Some(g) = e.downcast_ref::<git2::Error>() {
|
||||
if g.message().contains("status code: 426") {
|
||||
return TOO_OLD.into();
|
||||
}
|
||||
if g.message().contains("status code: 403") {
|
||||
return "the hub says this device has no access to this vault (if access ended, it will leave shortly)".into();
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ use anyhow::{Result, bail};
|
||||
use notify::{EventKind, RecursiveMode, Watcher};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
@@ -71,6 +72,9 @@ impl Burst {
|
||||
|
||||
pub type Log<'a> = &'a (dyn Fn(&str, &str) + Sync);
|
||||
|
||||
/// Set to stop every runner in this process (the desktop app uninstalling); each lets go of its vault.
|
||||
pub static STOP: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// Runs forever for one vault. `log(vault, message)` prints progress.
|
||||
pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log: Log) -> Result<()> {
|
||||
let vault = Vault::open(cfg, label)?;
|
||||
@@ -101,6 +105,9 @@ pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log:
|
||||
say("access to this vault ended — stopped syncing it");
|
||||
return Ok(());
|
||||
}
|
||||
if STOP.load(Ordering::Relaxed) {
|
||||
return Ok(());
|
||||
}
|
||||
if nudge.exists() {
|
||||
// Nudged from the canvas: save what has settled and share right away.
|
||||
let _ = std::fs::remove_file(&nudge);
|
||||
|
||||
136
core/src/status.rs
Normal file
136
core/src/status.rs
Normal file
@@ -0,0 +1,136 @@
|
||||
//! How a vault is doing on this device, in plain words: for `lunesync status` and the desktop app.
|
||||
|
||||
use crate::config::VaultConfig;
|
||||
use crate::state::{self, SyncState};
|
||||
use crate::vault::Vault;
|
||||
use crate::{guard, hub, remote, tidy};
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct VaultStatus {
|
||||
pub name: String,
|
||||
pub path: String,
|
||||
/// The hub's address, for vaults that sync through one.
|
||||
pub team: Option<String>,
|
||||
/// current, behind, offline or secret: the status colours (X6).
|
||||
pub level: &'static str,
|
||||
pub headline: String,
|
||||
pub last_synced: Option<i64>,
|
||||
pub waiting: usize,
|
||||
pub read_only: bool,
|
||||
pub running: bool,
|
||||
pub held: Vec<HeldChange>,
|
||||
pub secrets: Vec<HeldSecret>,
|
||||
pub tidy: Vec<ToTidy>,
|
||||
pub case_clashes: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct HeldChange {
|
||||
pub message: String,
|
||||
pub removed: usize,
|
||||
pub rewritten: usize,
|
||||
pub total: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct HeldSecret {
|
||||
pub path: String,
|
||||
/// "line 3: possible AWS access key (AKIA…7Q)"
|
||||
pub found: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct ToTidy {
|
||||
pub note: String,
|
||||
pub copy: String,
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
/// The order status colours are worst-first in: one red dot outranks everything.
|
||||
pub fn worst<'a>(levels: impl IntoIterator<Item = &'a str>) -> &'static str {
|
||||
let rank = |l: &str| match l {
|
||||
"secret" => 3,
|
||||
"behind" => 2,
|
||||
"offline" => 1,
|
||||
_ => 0,
|
||||
};
|
||||
match levels.into_iter().map(rank).max().unwrap_or(0) {
|
||||
3 => "secret",
|
||||
2 => "behind",
|
||||
1 => "offline",
|
||||
_ => "current",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn of(cfg: &VaultConfig, label: &str) -> VaultStatus {
|
||||
let mut out = VaultStatus {
|
||||
name: cfg.name.clone(),
|
||||
path: cfg.path.display().to_string(),
|
||||
team: cfg.hub_url.clone(),
|
||||
level: "behind",
|
||||
headline: String::new(),
|
||||
last_synced: None,
|
||||
waiting: 0,
|
||||
read_only: false,
|
||||
running: false,
|
||||
held: vec![],
|
||||
secrets: vec![],
|
||||
tidy: vec![],
|
||||
case_clashes: vec![],
|
||||
};
|
||||
let v = match Vault::open(cfg, label) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
out.headline = format!("Can't open: {e:#}");
|
||||
return out;
|
||||
}
|
||||
};
|
||||
let st = SyncState::load(&v.git_dir);
|
||||
out.last_synced = st.last_synced;
|
||||
out.read_only = v.role().is_some_and(|r| !hub::can_edit(&r));
|
||||
out.running = state::is_running(&v.git_dir);
|
||||
out.waiting = v.waiting_files().unwrap_or(0);
|
||||
out.case_clashes = st.case_clashes.clone();
|
||||
out.held = guard::load(&v.git_dir)
|
||||
.into_iter()
|
||||
.map(|h| HeldChange { message: h.message, removed: h.removed, rewritten: h.rewritten, total: h.total })
|
||||
.collect();
|
||||
out.secrets = v
|
||||
.secret_holds()
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|n| HeldSecret {
|
||||
found: n.hits.iter().map(|h| format!("line {}: possible {} ({})", h.line, h.rule, h.hint)).collect(),
|
||||
path: n.path,
|
||||
})
|
||||
.collect();
|
||||
out.tidy = tidy::list(&v)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|k| ToTidy { note: k.note, copy: k.copy, label: k.label })
|
||||
.collect();
|
||||
|
||||
let waiting = out.waiting;
|
||||
let changes = format!("{waiting} change{}", if waiting == 1 { "" } else { "s" });
|
||||
let (level, headline) = match &st.last_error {
|
||||
None if out.read_only && waiting > 0 => ("current", format!("Up to date · {changes} kept here, not shared (you have read access)")),
|
||||
None if out.read_only => ("current", "Up to date (read access)".to_string()),
|
||||
Some(e) if e == remote::TOO_OLD => ("behind", format!("Update Lune to keep syncing · {changes} saved here")),
|
||||
Some(e) if e.starts_with("offline") => ("offline", format!("Offline · waiting to sync · {changes}")),
|
||||
Some(e) => ("behind", format!("Can't sync: {e}{}", if waiting > 0 { format!(" · {changes} waiting") } else { String::new() })),
|
||||
None if waiting > 0 => ("behind", format!("Waiting to sync · {changes}")),
|
||||
None if st.last_synced.is_some() => ("current", "Synced".to_string()),
|
||||
None => ("behind", "Not synced yet".to_string()),
|
||||
};
|
||||
out.level = if !out.secrets.is_empty() {
|
||||
"secret"
|
||||
} else if (!out.held.is_empty() || !out.tidy.is_empty()) && level == "current" {
|
||||
// Waiting for a decision is amber too (X6).
|
||||
"behind"
|
||||
} else {
|
||||
level
|
||||
};
|
||||
out.headline = headline;
|
||||
out
|
||||
}
|
||||
95
core/src/supervisor.rs
Normal file
95
core/src/supervisor.rs
Normal file
@@ -0,0 +1,95 @@
|
||||
//! Keeps every vault in the config syncing: one runner thread per vault, vaults added meanwhile picked up,
|
||||
//! and the hub checked every 30 s (memberships, departures, nudges, health). Used by `lunesync run` and the
|
||||
//! desktop app.
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::membership;
|
||||
use crate::runner::{self, STOP, Timing};
|
||||
use anyhow::Result;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Set to check the hub on the next round instead of waiting up to 30 s (just connected).
|
||||
pub static CHECK_HUB: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// Runs until `runner::STOP` is set. `log(vault, message)` reports what happens; "hub" for hub messages.
|
||||
pub fn supervise(log: fn(&str, &str)) -> Result<()> {
|
||||
let mut started: HashSet<PathBuf> = HashSet::new();
|
||||
let mut hub_check = Instant::now();
|
||||
// Each hub's last complaint, so an unreachable hub isn't logged every 30 s.
|
||||
let mut hub_said: HashMap<String, String> = HashMap::new();
|
||||
while !STOP.load(Ordering::Relaxed) {
|
||||
let mut config = Config::load()?;
|
||||
config.use_hub_credentials();
|
||||
if CHECK_HUB.swap(false, Ordering::Relaxed) {
|
||||
hub_check = Instant::now();
|
||||
}
|
||||
if !config.hubs.is_empty() && Instant::now() >= hub_check {
|
||||
hub_check = Instant::now() + Duration::from_secs(30);
|
||||
for (url, result) in membership::arrive_each(&mut config) {
|
||||
match result {
|
||||
Ok(msgs) => {
|
||||
hub_said.remove(&url);
|
||||
msgs.iter().for_each(|m| log("hub", m));
|
||||
}
|
||||
Err(e) => {
|
||||
let msg = format!("can't check the hub: {e:#}");
|
||||
if hub_said.get(&url) != Some(&msg) {
|
||||
log("hub", &msg);
|
||||
hub_said.insert(url, msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
match membership::report(&config) {
|
||||
Ok(()) => {
|
||||
hub_said.remove("report");
|
||||
}
|
||||
Err(e) => {
|
||||
let msg = format!("couldn't report health: {e:#}");
|
||||
if hub_said.get("report") != Some(&msg) {
|
||||
log("hub", &msg);
|
||||
hub_said.insert("report".into(), msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// A vault that left (access ended) can come back later at the same place.
|
||||
started.retain(|p| config.vaults.iter().any(|v| &v.path == p));
|
||||
for cfg in &config.vaults {
|
||||
if !started.insert(cfg.path.clone()) {
|
||||
continue;
|
||||
}
|
||||
let (cfg, label, poll) = (cfg.clone(), config.device_label(), config.poll_interval());
|
||||
std::thread::spawn(move || {
|
||||
while !STOP.load(Ordering::Relaxed) {
|
||||
match runner::run(&cfg, &label, poll, Timing::default(), &log) {
|
||||
Ok(()) => return,
|
||||
Err(e) if format!("{e}").contains("already being synced") => {
|
||||
log(&cfg.name, &format!("{e:#}"));
|
||||
return;
|
||||
}
|
||||
Err(e) => {
|
||||
log(&cfg.name, &format!("stopped: {e:#} — retrying in 30 s"));
|
||||
std::thread::sleep(Duration::from_secs(30));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
std::thread::sleep(Duration::from_secs(2));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Asks every running vault to save what has settled and share now (the menu's "Share now").
|
||||
pub fn share_now(config: &Config) {
|
||||
for vc in &config.vaults {
|
||||
let dir = crate::state::lune_dir(&vc.path.join(".git"));
|
||||
if dir.exists() {
|
||||
let _ = std::fs::write(dir.join("nudge"), "");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -768,7 +768,7 @@ pub fn add(name: &str, path: &Path, remote_url: &str, label: &str) -> Result<(Va
|
||||
state::write_marker(&git_dir, name, !existed)?;
|
||||
drop(repo);
|
||||
|
||||
let cfg = VaultConfig { name: name.into(), path: path.clone(), remote: remote_url.into(), branch, hub_vault: None };
|
||||
let cfg = VaultConfig { name: name.into(), path: path.clone(), remote: remote_url.into(), branch, hub_vault: None, hub_url: None };
|
||||
let vault = Vault::open(&cfg, label)?;
|
||||
let _op = state::op_lock(&git_dir)?;
|
||||
vault.save_changes(Some(&format!("Added the vault on {label}")), &HashSet::new())?;
|
||||
|
||||
Reference in New Issue
Block a user