fix: remove panics and unblock flows
This commit is contained in:
@@ -6,7 +6,7 @@ use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Error, anyhow, bail};
|
||||
use bitcoin_hashes::sha1::Hash as Sha1Hash;
|
||||
use gpui::{App, AppContext, AsyncApp, Context, Entity, EventEmitter, Global, Task, TaskExt};
|
||||
use gpui::{App, AppContext, AsyncApp, Context, Entity, EventEmitter, Global, Task};
|
||||
use nostr::event::IntoEventBuilder;
|
||||
use nostr::nips::nip19::Nip19Coordinate;
|
||||
use nostr_connect::prelude::*;
|
||||
@@ -26,6 +26,7 @@ use crate::state::{GitPushMode, GitPushPolicy, GitRef, PushStepStatus, SyncState
|
||||
|
||||
pub const USER_KEYRING: &str = "Signed Safe Storage";
|
||||
const PUMP_DEBOUNCE: Duration = Duration::from_millis(200);
|
||||
const MAX_SEEN_EVENT_IDS: usize = 65_536;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum BackendEvent {
|
||||
@@ -58,6 +59,8 @@ pub struct Backend {
|
||||
inbox: Entity<Inbox>,
|
||||
passphrase_required: bool,
|
||||
pushing_repos: Entity<HashSet<RepoAddr>>,
|
||||
/// Bumped by every explicit identity action, results from an older session are dropped.
|
||||
session: u64,
|
||||
}
|
||||
|
||||
struct GlobalBackend(Entity<Backend>);
|
||||
@@ -169,6 +172,7 @@ impl Backend {
|
||||
inbox: cx.new(|_| Inbox::default()),
|
||||
passphrase_required: false,
|
||||
pushing_repos: cx.new(|_| HashSet::new()),
|
||||
session: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,12 +183,17 @@ impl Backend {
|
||||
}
|
||||
|
||||
let user = cx.read_credentials(USER_KEYRING);
|
||||
let session = self.session;
|
||||
|
||||
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
||||
let content = match user.await {
|
||||
Ok(Some((_username, secret))) => String::from_utf8(secret)?,
|
||||
_ => {
|
||||
this.update(cx, |_this, cx| cx.emit(BackendEvent::SignerRequired))?;
|
||||
this.update(cx, |this, cx| {
|
||||
if this.session == session {
|
||||
cx.emit(BackendEvent::SignerRequired);
|
||||
}
|
||||
})?;
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
@@ -193,7 +202,7 @@ impl Backend {
|
||||
if content.starts_with("nsec1") {
|
||||
let keys = Keys::new(SecretKey::parse(&content)?);
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_signer(keys, cx);
|
||||
this.set_signer(keys, session, cx);
|
||||
})?;
|
||||
} else if content.starts_with("bunker://") {
|
||||
let (base, keys) = extract_master_key(&content)?;
|
||||
@@ -203,16 +212,20 @@ impl Backend {
|
||||
.build()?;
|
||||
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_signer(signer, cx);
|
||||
this.set_signer(signer, session, cx);
|
||||
})?;
|
||||
} else if content.starts_with("ncryptsec1") {
|
||||
this.update(cx, |this, cx| {
|
||||
this.passphrase_required = true;
|
||||
cx.emit(BackendEvent::PassphraseRequired);
|
||||
if this.session == session {
|
||||
this.passphrase_required = true;
|
||||
cx.emit(BackendEvent::PassphraseRequired);
|
||||
}
|
||||
})?;
|
||||
} else {
|
||||
this.update(cx, |_this, cx| {
|
||||
cx.emit(BackendEvent::SignerRequired);
|
||||
this.update(cx, |this, cx| {
|
||||
if this.session == session {
|
||||
cx.emit(BackendEvent::SignerRequired);
|
||||
}
|
||||
})?;
|
||||
}
|
||||
|
||||
@@ -221,9 +234,11 @@ impl Backend {
|
||||
.await;
|
||||
|
||||
if let Err(e) = result {
|
||||
this.update(cx, |_this, cx| {
|
||||
cx.emit(BackendEvent::error(e.to_string()));
|
||||
cx.emit(BackendEvent::SignerRequired);
|
||||
this.update(cx, |this, cx| {
|
||||
if this.session == session {
|
||||
cx.emit(BackendEvent::error(e.to_string()));
|
||||
cx.emit(BackendEvent::SignerRequired);
|
||||
}
|
||||
})?;
|
||||
}
|
||||
|
||||
@@ -237,6 +252,7 @@ impl Backend {
|
||||
password: &str,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Task<Result<PublicKey, Error>> {
|
||||
let session = self.supersede_session();
|
||||
let password = password.to_owned();
|
||||
let user = cx.read_credentials(USER_KEYRING);
|
||||
|
||||
@@ -260,7 +276,9 @@ impl Backend {
|
||||
let keys = decrypt_task.await?;
|
||||
let public_key = keys.public_key();
|
||||
|
||||
this.update(cx, |this, cx| this.set_signer(keys, cx))?;
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_signer(keys, session, cx);
|
||||
})?;
|
||||
|
||||
Ok(public_key)
|
||||
})
|
||||
@@ -283,6 +301,7 @@ impl Backend {
|
||||
}
|
||||
|
||||
let password = password.to_owned();
|
||||
let session = self.supersede_session();
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
let job = cx.background_spawn(async move {
|
||||
@@ -300,7 +319,9 @@ impl Backend {
|
||||
});
|
||||
write.await?;
|
||||
|
||||
this.update(cx, |this, cx| this.set_signer(keys, cx))?;
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_signer(keys, session, cx);
|
||||
})?;
|
||||
|
||||
Ok(public_key)
|
||||
})
|
||||
@@ -313,13 +334,13 @@ impl Backend {
|
||||
password: &str,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Task<Result<PublicKey, Error>> {
|
||||
let ncryptsec = ncryptsec.trim().to_owned();
|
||||
|
||||
if password.is_empty() {
|
||||
return Task::ready(Err(anyhow!("Passphrase must not be empty")));
|
||||
}
|
||||
|
||||
let ncryptsec = ncryptsec.trim().to_owned();
|
||||
let password = password.to_owned();
|
||||
let session = self.supersede_session();
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
let stored = ncryptsec.clone();
|
||||
@@ -337,7 +358,9 @@ impl Backend {
|
||||
});
|
||||
write.await?;
|
||||
|
||||
this.update(cx, |this, cx| this.set_signer(keys, cx))?;
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_signer(keys, session, cx);
|
||||
})?;
|
||||
|
||||
Ok(public_key)
|
||||
})
|
||||
@@ -359,6 +382,7 @@ impl Backend {
|
||||
let keys = Keys::generate();
|
||||
let credential = with_master_key(&uri_string, &keys);
|
||||
let write = cx.write_credentials(USER_KEYRING, "bunker", credential.as_bytes());
|
||||
let session = self.supersede_session();
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
let signer = NostrConnect::builder(connect_uri, keys)
|
||||
@@ -369,7 +393,9 @@ impl Backend {
|
||||
let public_key = signer.get_public_key_async().await?;
|
||||
write.await?;
|
||||
|
||||
this.update(cx, |this, cx| this.set_signer(signer, cx))?;
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_signer(signer, session, cx);
|
||||
})?;
|
||||
|
||||
Ok(public_key)
|
||||
})
|
||||
@@ -384,13 +410,15 @@ impl Backend {
|
||||
let name = name.trim().to_owned();
|
||||
let password = password.to_owned();
|
||||
|
||||
if name.is_empty() || name.len() > 255 {
|
||||
if name.is_empty() || name.chars().count() > 255 {
|
||||
return Task::ready(Err(anyhow!("Name must be 1-255 characters")));
|
||||
}
|
||||
if password.is_empty() {
|
||||
return Task::ready(Err(anyhow!("Passphrase must not be empty")));
|
||||
}
|
||||
|
||||
let session = self.supersede_session();
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
let job = cx.background_spawn(async move {
|
||||
let keys = Keys::generate();
|
||||
@@ -409,6 +437,9 @@ impl Backend {
|
||||
write.await?;
|
||||
|
||||
this.update(cx, |this, cx| {
|
||||
if this.session != session {
|
||||
return;
|
||||
}
|
||||
this.signer.swap_inner(keys);
|
||||
this.current_user = Some(public_key);
|
||||
this.bootstrap_user(public_key, cx);
|
||||
@@ -449,11 +480,13 @@ impl Backend {
|
||||
.map(|url| RelayUrl::parse(url).expect("valid relay URL"))
|
||||
.collect();
|
||||
|
||||
for builder in [
|
||||
let publishes = [
|
||||
RelayList::new(relays).into_event_builder(),
|
||||
metadata,
|
||||
GitUserGraspList { grasp_servers }.into_event_builder(),
|
||||
] {
|
||||
]
|
||||
.into_iter()
|
||||
.map(|builder| {
|
||||
let client = this.client.clone();
|
||||
let signer = this.signer.clone();
|
||||
cx.background_spawn(async move {
|
||||
@@ -472,8 +505,21 @@ impl Backend {
|
||||
|
||||
Ok::<(), anyhow::Error>(())
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
if let Err(error) = futures::future::try_join_all(publishes).await {
|
||||
this.update(cx, |_this, cx| {
|
||||
cx.emit(BackendEvent::error(format!(
|
||||
"identity created, but publishing it failed: {error}"
|
||||
)));
|
||||
})?;
|
||||
}
|
||||
|
||||
Ok::<(), anyhow::Error>(())
|
||||
})
|
||||
.detach();
|
||||
})?;
|
||||
|
||||
Ok(public_key)
|
||||
@@ -976,10 +1022,8 @@ impl Backend {
|
||||
});
|
||||
let events = events.await?;
|
||||
|
||||
this.update(cx, |this, cx| {
|
||||
this.retract_events(&events, cx);
|
||||
})
|
||||
.ok();
|
||||
let deletions = this.update(cx, |this, cx| this.retract_events(&events, cx))?;
|
||||
futures::future::try_join_all(deletions).await?;
|
||||
|
||||
Ok(())
|
||||
})
|
||||
@@ -1061,6 +1105,9 @@ impl Backend {
|
||||
}
|
||||
|
||||
pub fn sign_out(&mut self, cx: &mut Context<Self>) {
|
||||
self.supersede_session();
|
||||
// Nothing may be signed with the identity the user just left.
|
||||
self.signer.swap_inner(Keys::generate());
|
||||
self.current_user = None;
|
||||
self.passphrase_required = false;
|
||||
|
||||
@@ -1068,7 +1115,19 @@ impl Backend {
|
||||
inbox.reset(cx);
|
||||
});
|
||||
|
||||
cx.delete_credentials(USER_KEYRING).detach_and_log_err(cx);
|
||||
let delete = cx.delete_credentials(USER_KEYRING);
|
||||
cx.spawn(async move |this, cx| {
|
||||
if let Err(error) = delete.await {
|
||||
this.update(cx, |_this, cx| {
|
||||
cx.emit(BackendEvent::error(format!(
|
||||
"failed to remove the stored credential: {error}"
|
||||
)));
|
||||
})?;
|
||||
}
|
||||
|
||||
Ok::<(), Error>(())
|
||||
})
|
||||
.detach();
|
||||
cx.emit(BackendEvent::SignerChanged);
|
||||
cx.emit(BackendEvent::SignerRequired);
|
||||
cx.notify();
|
||||
@@ -1103,7 +1162,12 @@ impl Backend {
|
||||
});
|
||||
}
|
||||
|
||||
fn set_signer<T>(&mut self, new_signer: T, cx: &mut Context<Self>)
|
||||
fn supersede_session(&mut self) -> u64 {
|
||||
self.session += 1;
|
||||
self.session
|
||||
}
|
||||
|
||||
fn set_signer<T>(&mut self, new_signer: T, session: u64, cx: &mut Context<Self>)
|
||||
where
|
||||
T: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + 'static,
|
||||
<T as AsyncGetPublicKey>::Error: std::error::Error + Send + Sync + 'static,
|
||||
@@ -1114,6 +1178,9 @@ impl Backend {
|
||||
match new_signer.get_public_key_async().await {
|
||||
Ok(public_key) => {
|
||||
this.update(cx, |this, cx| {
|
||||
if this.session != session {
|
||||
return;
|
||||
}
|
||||
this.signer.swap_inner(new_signer);
|
||||
this.current_user = Some(public_key);
|
||||
this.passphrase_required = false;
|
||||
@@ -1243,24 +1310,31 @@ impl Backend {
|
||||
}
|
||||
|
||||
// Each target gets its own deletion event.
|
||||
fn retract_events(&mut self, events: &[Event], cx: &mut Context<Self>) {
|
||||
for event in events.iter().cloned() {
|
||||
let client = self.client.clone();
|
||||
let signer = self.signer.clone();
|
||||
fn retract_events(
|
||||
&mut self,
|
||||
events: &[Event],
|
||||
cx: &mut Context<Self>,
|
||||
) -> Vec<Task<Result<(), Error>>> {
|
||||
events
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|event| {
|
||||
let client = self.client.clone();
|
||||
let signer = self.signer.clone();
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let builder = EventDeletionRequest::new().id(event.id);
|
||||
let deletion = builder.finalize_async(&signer).await?;
|
||||
let output = client.send_event(&deletion).broadcast().await?;
|
||||
cx.background_spawn(async move {
|
||||
let builder = EventDeletionRequest::new().id(event.id);
|
||||
let deletion = builder.finalize_async(&signer).await?;
|
||||
let output = client.send_event(&deletion).broadcast().await?;
|
||||
|
||||
if output.success.is_empty() {
|
||||
bail!("deletion event not accepted by any relay");
|
||||
}
|
||||
if output.success.is_empty() {
|
||||
bail!("deletion event not accepted by any relay");
|
||||
}
|
||||
|
||||
Ok::<(), Error>(())
|
||||
Ok::<(), Error>(())
|
||||
})
|
||||
})
|
||||
.detach_and_log_err(cx);
|
||||
}
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1287,8 +1361,7 @@ fn build_announcement(
|
||||
}
|
||||
}
|
||||
|
||||
/// Announces a repository and pushes its state to grasp servers,
|
||||
/// or retracts the announcement if the push fails.
|
||||
/// Announces a repository and pushes its state to grasp, retracting the announcement on failure.
|
||||
async fn announce_and_push_or_retract<S, P>(
|
||||
client: &Client,
|
||||
signer: &S,
|
||||
@@ -1355,6 +1428,10 @@ impl UpdateEvent {
|
||||
};
|
||||
|
||||
if seen.insert(event.id) {
|
||||
// Bounded, so a long session does not keep every event id.
|
||||
if seen.len() >= MAX_SEEN_EVENT_IDS {
|
||||
seen.clear();
|
||||
}
|
||||
return Some(update);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -366,21 +366,11 @@ impl CheckoutsStore {
|
||||
let (statuses, push_statuses) =
|
||||
CheckoutsStore::compute_statuses(&associations, &requested, &push_requested, true);
|
||||
|
||||
Ok::<_, Error>((associations, statuses, push_statuses))
|
||||
(associations, statuses, push_statuses)
|
||||
});
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
let (associations, statuses, push_statuses) = match work.await {
|
||||
Ok(results) => results,
|
||||
Err(_) => {
|
||||
return this.update(cx, |this, cx| {
|
||||
this.refresh.abort();
|
||||
if poll {
|
||||
this.schedule_local_pass(cx);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
let (associations, statuses, push_statuses) = work.await;
|
||||
|
||||
let again = this.update(cx, |this, cx| {
|
||||
let associations_changed = this.by_repo != associations;
|
||||
@@ -412,7 +402,7 @@ impl CheckoutsStore {
|
||||
}
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
Ok::<(), Error>(())
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
@@ -480,15 +470,11 @@ impl CheckoutsStore {
|
||||
let push_requested: Vec<RepoAddr> = self.push_requested.iter().cloned().collect();
|
||||
|
||||
let work = cx.background_spawn(async move {
|
||||
let (statuses, push_statuses) =
|
||||
CheckoutsStore::compute_statuses(&associations, &requested, &push_requested, false);
|
||||
Ok::<_, Error>((statuses, push_statuses))
|
||||
CheckoutsStore::compute_statuses(&associations, &requested, &push_requested, false)
|
||||
});
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
let Ok((statuses, push_statuses)) = work.await else {
|
||||
return Ok(());
|
||||
};
|
||||
let (statuses, push_statuses) = work.await;
|
||||
|
||||
this.update(cx, |this, cx| {
|
||||
if this.refresh.running() || this.debounce_pending {
|
||||
|
||||
@@ -120,9 +120,7 @@ impl Inbox {
|
||||
|
||||
Ok((items, unread_count))
|
||||
}
|
||||
}
|
||||
|
||||
impl Inbox {
|
||||
fn inbox_state_d_tag(me: PublicKey) -> String {
|
||||
format!("signed-inbox-state:{}", me.to_hex())
|
||||
}
|
||||
@@ -147,8 +145,7 @@ impl Inbox {
|
||||
}
|
||||
}
|
||||
|
||||
// Signed with a random key: the state is local-only, authorship does not
|
||||
// matter and no key material needs to be kept.
|
||||
// Signed with a random key: the state is local-only, authorship does not matter.
|
||||
async fn save_state(
|
||||
client: &Client,
|
||||
me: PublicKey,
|
||||
|
||||
@@ -36,14 +36,57 @@ pub fn init(
|
||||
repos_root: impl Into<PathBuf>,
|
||||
scan_paths: Vec<PathBuf>,
|
||||
cx: &mut App,
|
||||
) {
|
||||
) -> anyhow::Result<()> {
|
||||
// rustls uses the `aws_lc_rs` provider by default.
|
||||
let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
|
||||
if rustls::crypto::aws_lc_rs::default_provider()
|
||||
.install_default()
|
||||
.is_err()
|
||||
{
|
||||
log::debug!("a crypto provider is already installed");
|
||||
}
|
||||
|
||||
let backend = cx
|
||||
let db_path = db_path.as_ref().to_path_buf();
|
||||
|
||||
let backend = match cx
|
||||
.foreground_executor()
|
||||
.block_on(async move { NostrBackend::open(db_path.as_ref()).await });
|
||||
let backend = backend.expect("failed to initialize nostr backend");
|
||||
.block_on(NostrBackend::open(&db_path))
|
||||
{
|
||||
Ok(backend) => backend,
|
||||
Err(error) => {
|
||||
// A damaged or locked database must not keep the app from starting.
|
||||
log::error!(
|
||||
"failed to open the nostr database {}: {error:#}",
|
||||
db_path.display()
|
||||
);
|
||||
|
||||
let fallback = std::env::temp_dir()
|
||||
.join("signed")
|
||||
.join(format!("nostr-fallback-{}", std::process::id()));
|
||||
|
||||
let backend = std::fs::create_dir_all(&fallback)
|
||||
.map_err(anyhow::Error::from)
|
||||
.and_then(|()| {
|
||||
cx.foreground_executor()
|
||||
.block_on(NostrBackend::open(&fallback))
|
||||
});
|
||||
|
||||
if backend.is_ok() {
|
||||
cx.show_system_notification(gpui::SystemNotification {
|
||||
tag: "signed-nostr-db".into(),
|
||||
title: "Nostr cache unavailable".into(),
|
||||
body: format!(
|
||||
"{} could not be opened; this session uses a temporary cache",
|
||||
db_path.display()
|
||||
)
|
||||
.into(),
|
||||
actions: Vec::new(),
|
||||
});
|
||||
}
|
||||
|
||||
backend?
|
||||
}
|
||||
};
|
||||
|
||||
let (client, signer) = (backend.client, backend.signer);
|
||||
|
||||
Mirrors::install(repos_root);
|
||||
@@ -53,4 +96,6 @@ pub fn init(
|
||||
LocalReposStore::set_global(cx.new(|cx| LocalReposStore::new(scan_paths, cx)), cx);
|
||||
CheckoutsStore::set_global(cx.new(CheckoutsStore::new), cx);
|
||||
SyncStatusStore::set_global(cx.new(SyncStatusStore::new), cx);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -100,33 +100,7 @@ impl LocalReposStore {
|
||||
|
||||
task.detach();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn local_repo_addr(repo: &LocalRepo) -> Option<RepoAddr> {
|
||||
let binding = repo.nip34.as_ref()?;
|
||||
let owner = binding.owner?;
|
||||
let identifier = binding.identifier.as_deref()?;
|
||||
|
||||
Some(RepoAddr::new(owner, identifier))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ResolvedLocalRepo {
|
||||
pub path: PathBuf,
|
||||
pub nip34: Option<Nip34Binding>,
|
||||
pub announcement: Option<Announcement>,
|
||||
}
|
||||
|
||||
impl ResolvedLocalRepo {
|
||||
pub fn name(&self) -> SharedString {
|
||||
self.path
|
||||
.file_name()
|
||||
.map(|name| SharedString::from(name.to_string_lossy().into_owned()))
|
||||
.unwrap_or_else(|| SharedString::from("Untitled"))
|
||||
}
|
||||
}
|
||||
|
||||
impl LocalReposStore {
|
||||
pub fn resolve(
|
||||
repos: &[LocalRepo],
|
||||
known: &[Announcement],
|
||||
@@ -164,66 +138,26 @@ impl LocalReposStore {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use nostr::prelude::*;
|
||||
use signed_git::{GraspSignals, Nip34Kind};
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ResolvedLocalRepo {
|
||||
pub path: PathBuf,
|
||||
pub nip34: Option<Nip34Binding>,
|
||||
pub announcement: Option<Announcement>,
|
||||
}
|
||||
|
||||
use super::*;
|
||||
|
||||
const KEY: &str = "0000000000000000000000000000000000000000000000000000000000000001";
|
||||
const OTHER_KEY: &str = "0000000000000000000000000000000000000000000000000000000000000002";
|
||||
|
||||
fn announcement(secret: &str, id: &str) -> Announcement {
|
||||
let keys = Keys::new(SecretKey::from_hex(secret).expect("secret"));
|
||||
let tag = Tag::parse(vec!["d", id]).expect("tag");
|
||||
let event = EventBuilder::new(Kind::GitRepoAnnouncement)
|
||||
.tags(vec![tag])
|
||||
.finalize(&keys)
|
||||
.expect("signed");
|
||||
|
||||
Announcement::from_event(&event).expect("parsed")
|
||||
}
|
||||
|
||||
fn owner(secret: &str) -> PublicKey {
|
||||
Keys::new(SecretKey::from_hex(secret).expect("secret")).public_key()
|
||||
}
|
||||
|
||||
fn bound(secret: &str, id: &str) -> LocalRepo {
|
||||
let binding = Nip34Binding {
|
||||
kind: Nip34Kind::Initialized,
|
||||
signals: GraspSignals {
|
||||
nip34_json: true,
|
||||
..Default::default()
|
||||
},
|
||||
owner: Some(owner(secret)),
|
||||
identifier: Some(id.to_owned()),
|
||||
grasp_urls: Vec::new(),
|
||||
};
|
||||
|
||||
LocalRepo {
|
||||
path: PathBuf::from(id),
|
||||
nip34: Some(binding),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_users_own_announcement_is_dropped() {
|
||||
let own = announcement(KEY, "mine");
|
||||
let repo = bound(KEY, "mine");
|
||||
|
||||
let own = std::slice::from_ref(&own);
|
||||
assert!(LocalReposStore::resolve(&[repo], own, own).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_owners_announcement_is_linked_and_kept() {
|
||||
let known = announcement(OTHER_KEY, "theirs");
|
||||
let repo = bound(OTHER_KEY, "theirs");
|
||||
|
||||
let resolved = LocalReposStore::resolve(&[repo], std::slice::from_ref(&known), &[]);
|
||||
|
||||
assert_eq!(resolved.len(), 1);
|
||||
assert_eq!(resolved[0].announcement.as_ref(), Some(&known));
|
||||
impl ResolvedLocalRepo {
|
||||
pub fn name(&self) -> SharedString {
|
||||
self.path
|
||||
.file_name()
|
||||
.map(|name| SharedString::from(name.to_string_lossy().into_owned()))
|
||||
.unwrap_or_else(|| SharedString::from("Untitled"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn local_repo_addr(repo: &LocalRepo) -> Option<RepoAddr> {
|
||||
let binding = repo.nip34.as_ref()?;
|
||||
let owner = binding.owner?;
|
||||
let identifier = binding.identifier.as_deref()?;
|
||||
|
||||
Some(RepoAddr::new(owner, identifier))
|
||||
}
|
||||
|
||||
@@ -55,8 +55,10 @@ pub struct RepoStore {
|
||||
// Covers NIP-22 comments and statuses without an `a` tag.
|
||||
root_fetches: HashSet<EventId>,
|
||||
synced_maintainers: HashSet<PublicKey>,
|
||||
// In-flight tasks, cancelled when the store drops.
|
||||
// Fire-and-forget publishes, reaped when the next one is queued.
|
||||
tasks: Vec<Task<Result<(), Error>>>,
|
||||
// The latest refresh; assigning it cancels the previous one.
|
||||
refresh_task: Option<Task<Result<(), Error>>>,
|
||||
_subscription: Option<Subscription>,
|
||||
}
|
||||
|
||||
@@ -108,6 +110,7 @@ impl RepoStore {
|
||||
root_fetches: HashSet::new(),
|
||||
synced_maintainers: HashSet::new(),
|
||||
tasks: Vec::new(),
|
||||
refresh_task: None,
|
||||
_subscription: Some(subscription),
|
||||
}
|
||||
}
|
||||
@@ -139,6 +142,7 @@ impl RepoStore {
|
||||
root_fetches: HashSet::new(),
|
||||
synced_maintainers: HashSet::new(),
|
||||
tasks: Vec::new(),
|
||||
refresh_task: None,
|
||||
_subscription: None,
|
||||
}
|
||||
}
|
||||
@@ -580,7 +584,7 @@ impl RepoStore {
|
||||
Ok(())
|
||||
});
|
||||
|
||||
self.tasks.push(task);
|
||||
self.refresh_task = Some(task);
|
||||
}
|
||||
|
||||
pub fn status_of(&self, root: &Event) -> RepoStatus {
|
||||
@@ -652,7 +656,7 @@ impl RepoStore {
|
||||
);
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[expect(clippy::too_many_arguments, reason = "mirrors the PR event")]
|
||||
pub fn open_pull_request(
|
||||
&mut self,
|
||||
subject: Option<String>,
|
||||
@@ -708,12 +712,13 @@ impl RepoStore {
|
||||
cx.notify();
|
||||
return Task::ready(Err(Error::msg(message)));
|
||||
};
|
||||
let author_npub = user.to_bech32().unwrap();
|
||||
|
||||
let author_npub = user.to_bech32().unwrap_or_else(|error| match error {});
|
||||
let owner = addr.public_key();
|
||||
let euc = self.announcement.as_ref().and_then(|a| a.euc.clone());
|
||||
let repo_id = addr.identifier().to_owned();
|
||||
let base_npub = owner.to_bech32().unwrap();
|
||||
let base_npub = owner.to_bech32().unwrap_or_else(|error| match error {});
|
||||
|
||||
let push_relays = self
|
||||
.announcement
|
||||
.as_ref()
|
||||
@@ -721,6 +726,7 @@ impl RepoStore {
|
||||
.unwrap_or_default();
|
||||
|
||||
// GRASP-06 hosting falls back to the settings defaults.
|
||||
//
|
||||
// That happens when the author has no published grasp list.
|
||||
let defaults: Vec<RelayUrl> = {
|
||||
let settings = settings::SettingsStore::global(cx).read(cx).settings();
|
||||
@@ -752,17 +758,18 @@ impl RepoStore {
|
||||
{
|
||||
Ok(event) => event,
|
||||
Err(e) => {
|
||||
return this.update(cx, |this, cx| {
|
||||
this.update(cx, |this, cx| {
|
||||
this.last_error = Some(e.to_string());
|
||||
cx.notify();
|
||||
});
|
||||
})?;
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
|
||||
// GRASP-06 pushes the tip to the author's own grasp servers at
|
||||
// `/prs/<author-npub>/<repo-id>.git`; contributing to another
|
||||
// project never depends on that project's servers. Resolve the
|
||||
// servers from the author's latest kind-10317 grasp list.
|
||||
// GRASP-06 pushes the tip to the author's own grasp servers at `/prs/<author-npub>/<repo-id>.git`.
|
||||
// Contributing to another project never depends on that project's servers.
|
||||
//
|
||||
// Resolve the servers from the author's latest grasp list.
|
||||
let author_servers = {
|
||||
let query_client = client.clone();
|
||||
let published = cx
|
||||
@@ -790,6 +797,7 @@ impl RepoStore {
|
||||
}
|
||||
targets
|
||||
};
|
||||
|
||||
let base_targets: Vec<(String, String)> = {
|
||||
let mut targets = Vec::new();
|
||||
for relay in &push_relays {
|
||||
@@ -909,10 +917,11 @@ impl RepoStore {
|
||||
let pr_event = match publish_result {
|
||||
Ok(event) => event,
|
||||
Err(e) => {
|
||||
return this.update(cx, |this, cx| {
|
||||
this.update(cx, |this, cx| {
|
||||
this.last_error = Some(e.to_string());
|
||||
cx.notify();
|
||||
});
|
||||
})?;
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -926,7 +935,7 @@ impl RepoStore {
|
||||
})
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[expect(clippy::too_many_arguments, reason = "mirrors the PR event")]
|
||||
pub fn open_pull_request_from_refs(
|
||||
&mut self,
|
||||
repo_path: PathBuf,
|
||||
@@ -939,8 +948,7 @@ impl RepoStore {
|
||||
cx: &mut Context<Self>,
|
||||
) -> Task<Result<(), Error>> {
|
||||
cx.spawn(async move |this, cx| {
|
||||
// Regenerate at submit time so the published patch covers the
|
||||
// current tip of the compare branch.
|
||||
// Regenerate at submit time so the published patch covers the current tip of the compare branch.
|
||||
let patch = cx
|
||||
.background_spawn({
|
||||
let repo_path = repo_path.clone();
|
||||
@@ -958,8 +966,9 @@ impl RepoStore {
|
||||
Err(error) => bail!("Failed to generate the patch: {error}"),
|
||||
};
|
||||
|
||||
let (done, finished) = flume::bounded::<Result<(), Error>>(1);
|
||||
this.update(cx, |this, cx| {
|
||||
let task = this.open_pull_request(
|
||||
let publish = this.open_pull_request(
|
||||
subject,
|
||||
description,
|
||||
branch_name,
|
||||
@@ -969,8 +978,20 @@ impl RepoStore {
|
||||
Some(repo_path),
|
||||
cx,
|
||||
);
|
||||
this.tasks.push(task);
|
||||
})
|
||||
|
||||
// The store owns the publish so it outlives the panel that requested it.
|
||||
this.tasks.push(cx.spawn(async move |_this, _cx| {
|
||||
if done.send(publish.await).is_err() {
|
||||
log::debug!("pull request publish finished after its panel closed");
|
||||
}
|
||||
Ok::<(), Error>(())
|
||||
}));
|
||||
})?;
|
||||
|
||||
finished
|
||||
.recv_async()
|
||||
.await
|
||||
.map_err(|_| anyhow::anyhow!("the pull request publish was dropped"))?
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1104,6 +1125,7 @@ impl RepoStore {
|
||||
|
||||
Ok(())
|
||||
});
|
||||
|
||||
self.tasks.push(task);
|
||||
}
|
||||
|
||||
@@ -1238,12 +1260,15 @@ impl RepoStore {
|
||||
cx.notify();
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
// Cancellation releases the busy flag too, not only completion.
|
||||
let guard = cx.on_drop(&this, |this, cx| {
|
||||
this.pushing = false;
|
||||
this.push_steps.clear();
|
||||
cx.notify();
|
||||
});
|
||||
let result = push.await;
|
||||
|
||||
this.update(cx, |this, cx| {
|
||||
this.pushing = false;
|
||||
this.push_steps.clear();
|
||||
|
||||
match &result {
|
||||
Ok(outcome) => {
|
||||
this.last_error = None;
|
||||
@@ -1273,6 +1298,7 @@ impl RepoStore {
|
||||
cx.notify();
|
||||
})?;
|
||||
|
||||
guard.abort();
|
||||
result.map(|_| ())
|
||||
})
|
||||
}
|
||||
@@ -1331,11 +1357,14 @@ impl RepoStore {
|
||||
};
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
// Cancellation releases the busy flag too, not only completion.
|
||||
let guard = cx.on_drop(&this, |this, cx| {
|
||||
this.cloning = false;
|
||||
cx.notify();
|
||||
});
|
||||
let result = clone.await;
|
||||
|
||||
this.update(cx, |this, cx| {
|
||||
this.cloning = false;
|
||||
|
||||
match &result {
|
||||
Ok(()) => {
|
||||
let checkouts = CheckoutsStore::global(cx);
|
||||
@@ -1351,6 +1380,8 @@ impl RepoStore {
|
||||
cx.notify();
|
||||
})?;
|
||||
|
||||
guard.abort();
|
||||
|
||||
result
|
||||
})
|
||||
}
|
||||
@@ -1410,6 +1441,7 @@ impl RepoStore {
|
||||
|
||||
Ok(())
|
||||
});
|
||||
|
||||
self.tasks.push(task);
|
||||
}
|
||||
}
|
||||
@@ -1453,7 +1485,7 @@ fn resolve_statuses(
|
||||
}
|
||||
|
||||
/// Publish a patch series as a sequence of `git/patch` events.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[expect(clippy::too_many_arguments, reason = "independent inputs")]
|
||||
async fn publish_patch_series<S>(
|
||||
client: &Client,
|
||||
signer: &S,
|
||||
|
||||
@@ -223,8 +223,7 @@ impl RepoListStore {
|
||||
}
|
||||
}
|
||||
|
||||
// Unbounded, unlike the windowed activity query above, so totals
|
||||
// are exact.
|
||||
// Unbounded, unlike the windowed activity query above, so totals are exact.
|
||||
let mut counts: HashMap<RepoAddr, RepoActivityCounts> = HashMap::new();
|
||||
let count_filter =
|
||||
Filter::new().kinds([Kind::GitIssue, Kind::GitPullRequest, Kind::GitPatch]);
|
||||
@@ -255,25 +254,33 @@ impl RepoListStore {
|
||||
cx.spawn(async move |this, cx| {
|
||||
let (announcements, last_activity, counts) = match work.await {
|
||||
Ok(results) => results,
|
||||
Err(_) => {
|
||||
return this.update(cx, |this, _cx| {
|
||||
this.refresh.abort();
|
||||
});
|
||||
Err(error) => {
|
||||
log::warn!("failed to refresh the repository list: {error}");
|
||||
return this.update(cx, |this, _cx| this.refresh.abort());
|
||||
}
|
||||
};
|
||||
|
||||
let again = this.update(cx, |this, cx| {
|
||||
let changed = *this.announcements != announcements
|
||||
|| *this.last_activity != last_activity
|
||||
|| *this.counts != counts;
|
||||
|
||||
this.announcements = Arc::new(announcements);
|
||||
this.last_activity = Arc::new(last_activity);
|
||||
this.counts = Arc::new(counts);
|
||||
this.sync_own_repo_states(cx);
|
||||
cx.notify();
|
||||
|
||||
if changed {
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
this.refresh.finish()
|
||||
})?;
|
||||
|
||||
if again {
|
||||
this.update(cx, |this, cx| this.refresh(cx))?;
|
||||
this.update(cx, |this, cx| {
|
||||
this.refresh(cx);
|
||||
})?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -282,7 +282,9 @@ impl SyncState {
|
||||
|
||||
if !missing.is_empty() {
|
||||
let (mode, policy) = (self.mode.clone(), self.policy);
|
||||
*self = Self::from_repo(&snapshot_path)?;
|
||||
*self = cx
|
||||
.background_spawn(async move { Self::from_repo(&snapshot_path) })
|
||||
.await?;
|
||||
self.mode = mode;
|
||||
self.policy = policy;
|
||||
}
|
||||
@@ -295,9 +297,7 @@ impl SyncState {
|
||||
Self::build(repo_id, &self.refs, self.head.as_deref())
|
||||
}
|
||||
|
||||
/// Push the state event and objects to the grasp servers.
|
||||
///
|
||||
/// Calling `on_step` for each step.
|
||||
/// Push the state event and objects to the grasp servers, calling `on_step` for each step.
|
||||
pub async fn push_to_grasps<P>(
|
||||
&self,
|
||||
client: &Client,
|
||||
@@ -446,9 +446,7 @@ impl SyncState {
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
/// Announce the repository and push the state and objects to the grasp servers.
|
||||
///
|
||||
/// Both events are signed by the caller, so a failure at the call site can retract the announcement by id.
|
||||
/// Announces the repository and pushes state and objects; the caller signs, so it can retract.
|
||||
pub async fn announce_and_push<P>(
|
||||
&self,
|
||||
client: &Client,
|
||||
|
||||
@@ -40,7 +40,9 @@ pub struct SyncStatusStore {
|
||||
pass_pending: bool,
|
||||
poll_pending: bool,
|
||||
sender: Sender<()>,
|
||||
tasks: Vec<Task<Result<(), Error>>>,
|
||||
_wake_task: Task<Result<(), Error>>,
|
||||
pass_task: Option<Task<Result<(), Error>>>,
|
||||
poll_task: Option<Task<Result<(), Error>>>,
|
||||
_subscriptions: Vec<Subscription>,
|
||||
}
|
||||
|
||||
@@ -96,7 +98,9 @@ impl SyncStatusStore {
|
||||
in_flight: false,
|
||||
pass_pending: false,
|
||||
poll_pending: false,
|
||||
tasks: vec![task],
|
||||
_wake_task: task,
|
||||
pass_task: None,
|
||||
poll_task: None,
|
||||
_subscriptions: subscriptions,
|
||||
}
|
||||
}
|
||||
@@ -204,7 +208,7 @@ impl SyncStatusStore {
|
||||
Ok::<_, Error>(updates)
|
||||
});
|
||||
|
||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||
self.pass_task = Some(cx.spawn(async move |this, cx| {
|
||||
// Reset the slot even on failure, or every later pass folds forever.
|
||||
let updates = match work.await {
|
||||
Ok(updates) => updates,
|
||||
@@ -240,7 +244,7 @@ impl SyncStatusStore {
|
||||
}
|
||||
self.poll_pending = true;
|
||||
|
||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||
self.poll_task = Some(cx.spawn(async move |this, cx| {
|
||||
cx.background_executor().timer(SYNC_POLL).await;
|
||||
|
||||
this.update(cx, |this, cx| {
|
||||
@@ -319,9 +323,7 @@ impl SyncStatusDirectory {
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Commit ids missing on Nostr, mapped to the checkout that holds them.
|
||||
///
|
||||
/// When `checkout` matches a tracked checkout, only that checkout contributes.
|
||||
/// Commit ids missing on Nostr, mapped to their checkout; restricted to `checkout` if tracked.
|
||||
pub fn ahead_commits_of(
|
||||
&self,
|
||||
addr: &RepoAddr,
|
||||
@@ -358,6 +360,10 @@ impl SyncStatusDirectory {
|
||||
}
|
||||
|
||||
fn queue(&self, addr: &RepoAddr, cx: &App) {
|
||||
if self.statuses.contains_key(addr) {
|
||||
return;
|
||||
}
|
||||
|
||||
if self.with_pending(|pending| pending.insert(addr.clone())) {
|
||||
let store = SyncStatusStore::global(cx);
|
||||
store.read(cx).probe([addr.clone()]);
|
||||
|
||||
Reference in New Issue
Block a user