chore: restructure backend
This commit is contained in:
+133
-127
@@ -11,7 +11,7 @@ use nostr::event::IntoEventBuilder;
|
||||
use nostr::nips::nip19::Nip19Coordinate;
|
||||
use nostr_connect::prelude::*;
|
||||
use nostr_sdk::prelude::*;
|
||||
use signed_core::{Announcement, Filters, RepoAddr, filters};
|
||||
use signed_core::{Announcement, Filters, RepoAddr};
|
||||
use signed_git::{GitCache, Repo};
|
||||
use signed_nostr::{SignedAuthUrlHandler, UniversalSigner, Update};
|
||||
|
||||
@@ -52,6 +52,54 @@ impl BackendEvent {
|
||||
}
|
||||
}
|
||||
|
||||
enum UpdateEvent {
|
||||
Profile(PublicKey),
|
||||
Grasp(PublicKey),
|
||||
Repo(Update),
|
||||
}
|
||||
|
||||
impl UpdateEvent {
|
||||
async fn next(
|
||||
notifications: &mut (impl futures::Stream<Item = ClientNotification> + Unpin),
|
||||
seen: &mut HashSet<EventId>,
|
||||
) -> Option<Self> {
|
||||
loop {
|
||||
match notifications.next().await {
|
||||
Some(ClientNotification::Message { message, .. }) => {
|
||||
let RelayMessage::Event { event, .. } = *message else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let update = match event.kind {
|
||||
Kind::Metadata => UpdateEvent::Profile(event.pubkey),
|
||||
Kind::GitUserGraspList => UpdateEvent::Grasp(event.pubkey),
|
||||
kind if Filters::is_repo_kind(kind) => {
|
||||
UpdateEvent::Repo(Update::from_event(&event))
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
Some(_) => continue,
|
||||
None => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EventEmitter<BackendEvent> for Backend {}
|
||||
|
||||
struct GlobalBackend(Entity<Backend>);
|
||||
|
||||
impl Global for GlobalBackend {}
|
||||
|
||||
pub struct Backend {
|
||||
client: Client,
|
||||
signer: UniversalSigner,
|
||||
@@ -61,14 +109,9 @@ pub struct Backend {
|
||||
pushing_repos: Entity<HashSet<RepoAddr>>,
|
||||
/// Bumped by every explicit identity action, results from an older session are dropped.
|
||||
session: u64,
|
||||
_pump: Task<Result<(), Error>>,
|
||||
}
|
||||
|
||||
struct GlobalBackend(Entity<Backend>);
|
||||
|
||||
impl Global for GlobalBackend {}
|
||||
|
||||
impl EventEmitter<BackendEvent> for Backend {}
|
||||
|
||||
impl Backend {
|
||||
pub fn global(cx: &App) -> Entity<Self> {
|
||||
cx.global::<GlobalBackend>().0.clone()
|
||||
@@ -105,7 +148,6 @@ impl Backend {
|
||||
|
||||
loop {
|
||||
let now = Instant::now();
|
||||
|
||||
if now >= deadline {
|
||||
break;
|
||||
}
|
||||
@@ -156,8 +198,6 @@ impl Backend {
|
||||
Ok(())
|
||||
});
|
||||
|
||||
pump.detach();
|
||||
|
||||
cx.defer(move |cx| {
|
||||
weak.update(cx, |this, cx| {
|
||||
this.restore_session(cx);
|
||||
@@ -173,6 +213,7 @@ impl Backend {
|
||||
passphrase_required: false,
|
||||
pushing_repos: cx.new(|_| HashSet::new()),
|
||||
session: 0,
|
||||
_pump: pump,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,7 +246,7 @@ impl Backend {
|
||||
this.set_signer(keys, session, cx);
|
||||
})?;
|
||||
} else if content.starts_with("bunker://") {
|
||||
let (base, keys) = extract_master_key(&content)?;
|
||||
let (base, keys) = Self::extract_master_key(&content)?;
|
||||
let uri = NostrConnectUri::parse(base)?;
|
||||
let signer = NostrConnect::builder(uri, keys)
|
||||
.auth_url_handler(Arc::new(SignedAuthUrlHandler))
|
||||
@@ -380,7 +421,7 @@ impl Backend {
|
||||
};
|
||||
|
||||
let keys = Keys::generate();
|
||||
let credential = with_master_key(&uri_string, &keys);
|
||||
let credential = Self::with_master_key(&uri_string, &keys);
|
||||
let write = cx.write_credentials(USER_KEYRING, "bunker", credential.as_bytes());
|
||||
let session = self.supersede_session();
|
||||
|
||||
@@ -611,7 +652,7 @@ impl Backend {
|
||||
let commit = work.await?;
|
||||
let commit_sha = Sha1Hash::from_str(&commit).map_err(|_| anyhow!("invalid id"))?;
|
||||
|
||||
let announcement = build_announcement(
|
||||
let announcement = Self::build_announcement(
|
||||
&repo_id,
|
||||
&name,
|
||||
&description,
|
||||
@@ -641,9 +682,15 @@ impl Backend {
|
||||
Ok::<(), Error>(())
|
||||
};
|
||||
|
||||
let event =
|
||||
announce_and_push_or_retract(&client, &signer, &state, announcement, cx, on_step)
|
||||
.await?;
|
||||
let event = Self::announce_and_push_or_retract(
|
||||
&client,
|
||||
&signer,
|
||||
&state,
|
||||
announcement,
|
||||
cx,
|
||||
on_step,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let announcement = Announcement::from_event(&event)
|
||||
.ok_or_else(|| anyhow!("failed to parse announcement"))?;
|
||||
@@ -723,7 +770,8 @@ impl Backend {
|
||||
}
|
||||
|
||||
let euc = euc.and_then(|commit: String| Sha1Hash::from_str(&commit).ok());
|
||||
let ann = build_announcement(&repo_id, &name, &description, &owner, &servers, euc);
|
||||
let ann =
|
||||
Self::build_announcement(&repo_id, &name, &description, &owner, &servers, euc);
|
||||
|
||||
let on_step = &mut |status: PushStepStatus, cx: &mut AsyncApp| {
|
||||
this.update(cx, |_, cx| {
|
||||
@@ -736,7 +784,8 @@ impl Backend {
|
||||
};
|
||||
|
||||
let event =
|
||||
announce_and_push_or_retract(&client, &signer, &state, ann, cx, on_step).await?;
|
||||
Self::announce_and_push_or_retract(&client, &signer, &state, ann, cx, on_step)
|
||||
.await?;
|
||||
|
||||
if let Some(base) = servers.first().and_then(grasp_base_url) {
|
||||
let url = format!("{base}/{owner}/{repo_id}.git");
|
||||
@@ -1296,7 +1345,6 @@ impl Backend {
|
||||
Ok(_) => {
|
||||
this.update(cx, |_this, cx| {
|
||||
cx.emit(BackendEvent::Synced);
|
||||
cx.notify();
|
||||
})?;
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -1336,124 +1384,82 @@ impl Backend {
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn build_announcement(
|
||||
repo_id: &str,
|
||||
name: &str,
|
||||
description: &str,
|
||||
owner: &str,
|
||||
servers: &[RelayUrl],
|
||||
euc: Option<Sha1Hash>,
|
||||
) -> GitRepositoryAnnouncement {
|
||||
GitRepositoryAnnouncement {
|
||||
id: repo_id.to_owned(),
|
||||
name: Some(name.to_owned()),
|
||||
description: (!description.is_empty()).then(|| description.to_owned()),
|
||||
web: Vec::new(),
|
||||
clone: servers
|
||||
.iter()
|
||||
.filter_map(|relay| grasp_clone_url(relay, owner, repo_id))
|
||||
.collect(),
|
||||
relays: servers.to_vec(),
|
||||
euc,
|
||||
maintainers: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
state: &SyncState,
|
||||
announcement: GitRepositoryAnnouncement,
|
||||
cx: &mut AsyncApp,
|
||||
on_step: &mut P,
|
||||
) -> Result<Event, Error>
|
||||
where
|
||||
S: AsyncGetPublicKey + AsyncSignEvent + ?Sized,
|
||||
P: FnMut(PushStepStatus, &mut AsyncApp) -> Result<(), Error>,
|
||||
{
|
||||
let state_event = state
|
||||
.state_event(&announcement.id)
|
||||
.finalize_async(signer)
|
||||
.await?;
|
||||
let announcement_event = announcement.finalize_async(signer).await?;
|
||||
|
||||
match state
|
||||
.announce_and_push(client, announcement_event.clone(), state_event, cx, on_step)
|
||||
.await
|
||||
{
|
||||
Ok(event) => Ok(event),
|
||||
Err(e) => {
|
||||
let retracted =
|
||||
SyncState::retract_announcement(client, signer, announcement_event.id).await;
|
||||
let retraction = match retracted {
|
||||
Ok(()) => "The announcement has been retracted".to_owned(),
|
||||
Err(error) => format!(
|
||||
"Retracting the announcement failed: {error}; delete the repository to clean it up"
|
||||
),
|
||||
};
|
||||
|
||||
bail!("{e}. {retraction}");
|
||||
fn build_announcement(
|
||||
repo_id: &str,
|
||||
name: &str,
|
||||
description: &str,
|
||||
owner: &str,
|
||||
servers: &[RelayUrl],
|
||||
euc: Option<Sha1Hash>,
|
||||
) -> GitRepositoryAnnouncement {
|
||||
GitRepositoryAnnouncement {
|
||||
id: repo_id.to_owned(),
|
||||
name: Some(name.to_owned()),
|
||||
description: (!description.is_empty()).then(|| description.to_owned()),
|
||||
web: Vec::new(),
|
||||
clone: servers
|
||||
.iter()
|
||||
.filter_map(|relay| grasp_clone_url(relay, owner, repo_id))
|
||||
.collect(),
|
||||
relays: servers.to_vec(),
|
||||
euc,
|
||||
maintainers: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum UpdateEvent {
|
||||
Profile(PublicKey),
|
||||
Grasp(PublicKey),
|
||||
Repo(Update),
|
||||
}
|
||||
/// 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,
|
||||
state: &SyncState,
|
||||
announcement: GitRepositoryAnnouncement,
|
||||
cx: &mut AsyncApp,
|
||||
on_step: &mut P,
|
||||
) -> Result<Event, Error>
|
||||
where
|
||||
S: AsyncGetPublicKey + AsyncSignEvent + ?Sized,
|
||||
P: FnMut(PushStepStatus, &mut AsyncApp) -> Result<(), Error>,
|
||||
{
|
||||
let state_event = state
|
||||
.state_event(&announcement.id)
|
||||
.finalize_async(signer)
|
||||
.await?;
|
||||
let announcement_event = announcement.finalize_async(signer).await?;
|
||||
|
||||
impl UpdateEvent {
|
||||
async fn next(
|
||||
notifications: &mut (impl futures::Stream<Item = ClientNotification> + Unpin),
|
||||
seen: &mut HashSet<EventId>,
|
||||
) -> Option<Self> {
|
||||
loop {
|
||||
match notifications.next().await {
|
||||
Some(ClientNotification::Message { message, .. }) => {
|
||||
let RelayMessage::Event { event, .. } = *message else {
|
||||
continue;
|
||||
};
|
||||
match state
|
||||
.announce_and_push(client, announcement_event.clone(), state_event, cx, on_step)
|
||||
.await
|
||||
{
|
||||
Ok(event) => Ok(event),
|
||||
Err(e) => {
|
||||
let retracted =
|
||||
SyncState::retract_announcement(client, signer, announcement_event.id).await;
|
||||
let retraction = match retracted {
|
||||
Ok(()) => "The announcement has been retracted".to_owned(),
|
||||
Err(error) => format!(
|
||||
"Retracting the announcement failed: {error}; delete the repository to clean it up"
|
||||
),
|
||||
};
|
||||
|
||||
let update = match event.kind {
|
||||
Kind::Metadata => UpdateEvent::Profile(event.pubkey),
|
||||
Kind::GitUserGraspList => UpdateEvent::Grasp(event.pubkey),
|
||||
kind if filters::is_repo_kind(kind) => {
|
||||
UpdateEvent::Repo(Update::from_event(&event))
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
Some(_) => continue,
|
||||
None => return None,
|
||||
bail!("{e}. {retraction}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_master_key(credential: &str) -> Result<(&str, Keys), Error> {
|
||||
match credential.split_once("master=") {
|
||||
Some((base, nsec)) => {
|
||||
let keys = Keys::new(SecretKey::parse(nsec)?);
|
||||
Ok((base.trim_end_matches(['?', '&']), keys))
|
||||
fn extract_master_key(credential: &str) -> Result<(&str, Keys), Error> {
|
||||
match credential.split_once("master=") {
|
||||
Some((base, nsec)) => {
|
||||
let keys = Keys::new(SecretKey::parse(nsec)?);
|
||||
Ok((base.trim_end_matches(['?', '&']), keys))
|
||||
}
|
||||
None => Ok((credential, Keys::generate())),
|
||||
}
|
||||
None => Ok((credential, Keys::generate())),
|
||||
}
|
||||
|
||||
fn with_master_key(uri: &str, keys: &Keys) -> String {
|
||||
let separator = if uri.contains('?') { '&' } else { '?' };
|
||||
let nsec = keys.secret_key().to_bech32().expect("infallible");
|
||||
format!("{uri}{separator}master={nsec}")
|
||||
}
|
||||
}
|
||||
|
||||
fn with_master_key(uri: &str, keys: &Keys) -> String {
|
||||
let separator = if uri.contains('?') { '&' } else { '?' };
|
||||
let nsec = keys.secret_key().to_bech32().expect("infallible");
|
||||
format!("{uri}{separator}master={nsec}")
|
||||
}
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use anyhow::Error;
|
||||
use gpui::{App, AppContext, Context, Entity, Global, Subscription};
|
||||
use nostr::prelude::*;
|
||||
use settings::{CheckoutRecord, CheckoutsSettings, SettingsStore};
|
||||
use signed_core::{Announcement, RepoAddr};
|
||||
use signed_git::Repo;
|
||||
@@ -17,28 +16,11 @@ use crate::refresh::{RefreshGate, RefreshRequest};
|
||||
use crate::repos::RepoListStore;
|
||||
|
||||
const REFRESH_DEBOUNCE: Duration = Duration::from_millis(300);
|
||||
const MAX_STATUS_CHECKOUTS: usize = 8;
|
||||
const LOCAL_POLL: Duration = Duration::from_secs(2);
|
||||
const STATUS_POLL: Duration = Duration::from_secs(15);
|
||||
const PUSH_POLL: Duration = Duration::from_secs(60);
|
||||
|
||||
struct GlobalCheckoutsStore(Entity<CheckoutsStore>);
|
||||
|
||||
impl Global for GlobalCheckoutsStore {}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CheckoutStatus {
|
||||
pub path: PathBuf,
|
||||
/// A detached checkout is idle and yields no status.
|
||||
pub branch: String,
|
||||
/// For tip-based PR dedupe.
|
||||
pub head: String,
|
||||
/// `refs/remotes/origin/<branch>`, else `origin/HEAD` for new branches.
|
||||
pub base: String,
|
||||
/// Zero-ahead checkouts are dropped, so always above zero.
|
||||
pub ahead: u32,
|
||||
}
|
||||
|
||||
struct Remembered {
|
||||
path: PathBuf,
|
||||
addr: RepoAddr,
|
||||
@@ -94,15 +76,8 @@ impl Remembered {
|
||||
|
||||
pub struct CheckoutsStore {
|
||||
by_repo: HashMap<RepoAddr, Vec<PathBuf>>,
|
||||
statuses: HashMap<RepoAddr, Vec<CheckoutStatus>>,
|
||||
status_requested: HashSet<RepoAddr>,
|
||||
push_requested: HashSet<RepoAddr>,
|
||||
push_statuses: HashMap<RepoAddr, Vec<CheckoutStatus>>,
|
||||
requested_head: HashMap<RepoAddr, Option<String>>,
|
||||
refresh: RefreshGate,
|
||||
debounce_pending: bool,
|
||||
local_pending: bool,
|
||||
last_full_sync: Option<Instant>,
|
||||
checkouts_settings: CheckoutsSettings,
|
||||
_subscriptions: Vec<Subscription>,
|
||||
}
|
||||
@@ -146,15 +121,14 @@ impl CheckoutsStore {
|
||||
this.refresh(cx);
|
||||
}));
|
||||
|
||||
// Another identity's repositories must not keep the old statuses alive.
|
||||
// Another identity's repositories must not keep the old associations alive.
|
||||
subscriptions.push(cx.subscribe(&backend, |this, _backend, event, cx| {
|
||||
if matches!(event, BackendEvent::SignerChanged) {
|
||||
this.status_requested.clear();
|
||||
this.push_requested.clear();
|
||||
this.requested_head.clear();
|
||||
this.statuses.clear();
|
||||
this.push_statuses.clear();
|
||||
cx.notify();
|
||||
let had_state = !this.by_repo.is_empty();
|
||||
this.by_repo.clear();
|
||||
if had_state {
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
this.refresh(cx);
|
||||
}
|
||||
@@ -173,15 +147,8 @@ impl CheckoutsStore {
|
||||
|
||||
Self {
|
||||
by_repo: HashMap::new(),
|
||||
statuses: HashMap::new(),
|
||||
status_requested: HashSet::new(),
|
||||
push_requested: HashSet::new(),
|
||||
push_statuses: HashMap::new(),
|
||||
requested_head: HashMap::new(),
|
||||
refresh: RefreshGate::default(),
|
||||
debounce_pending: false,
|
||||
local_pending: false,
|
||||
last_full_sync: None,
|
||||
checkouts_settings,
|
||||
_subscriptions: subscriptions,
|
||||
}
|
||||
@@ -221,60 +188,7 @@ impl CheckoutsStore {
|
||||
self.by_repo.get(addr).cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn request_statuses(
|
||||
&mut self,
|
||||
addr: &RepoAddr,
|
||||
announced_head: Option<String>,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
self.status_requested.insert(addr.clone());
|
||||
if announced_head != self.requested_head.get(addr).cloned().flatten() {
|
||||
self.requested_head.insert(addr.clone(), announced_head);
|
||||
}
|
||||
self.refresh(cx);
|
||||
}
|
||||
|
||||
pub fn ready_statuses_of(&self, addr: &RepoAddr) -> Vec<CheckoutStatus> {
|
||||
self.statuses.get(addr).cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn request_push_statuses(&mut self, addr: &RepoAddr, cx: &mut Context<Self>) {
|
||||
self.push_requested.insert(addr.clone());
|
||||
self.refresh(cx);
|
||||
}
|
||||
|
||||
pub fn checkout_pushed(&mut self, addr: &RepoAddr, path: &Path, cx: &mut Context<Self>) {
|
||||
let mut removed = false;
|
||||
|
||||
if let Some(statuses) = self.push_statuses.get_mut(addr) {
|
||||
let before = statuses.len();
|
||||
statuses.retain(|status| status.path.as_path() != path);
|
||||
removed = statuses.len() != before;
|
||||
|
||||
if removed && statuses.is_empty() {
|
||||
self.push_statuses.remove(addr);
|
||||
}
|
||||
}
|
||||
|
||||
if removed {
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
self.request_push_statuses(addr, cx);
|
||||
}
|
||||
|
||||
pub fn push_statuses_of(&self, addr: &RepoAddr) -> Vec<CheckoutStatus> {
|
||||
self.push_statuses.get(addr).cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn unpushed(&self, addr: &RepoAddr) -> usize {
|
||||
self.push_statuses
|
||||
.get(addr)
|
||||
.map(|list| list.iter().map(|status| status.ahead as usize).sum())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
pub fn refresh(&mut self, cx: &mut Context<Self>) {
|
||||
fn refresh(&mut self, cx: &mut Context<Self>) {
|
||||
if self.debounce_pending || self.refresh.request() != RefreshRequest::Schedule {
|
||||
return;
|
||||
}
|
||||
@@ -315,26 +229,11 @@ impl CheckoutsStore {
|
||||
let scanned = LocalReposStore::global(cx).read(cx).repos.clone();
|
||||
let cache_root = Mirrors::root().canonicalize().ok();
|
||||
|
||||
let requested: Vec<(RepoAddr, Option<String>)> = self
|
||||
.status_requested
|
||||
.iter()
|
||||
.map(|addr| {
|
||||
(
|
||||
addr.clone(),
|
||||
self.requested_head.get(addr).cloned().flatten(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let push_requested: Vec<RepoAddr> = self.push_requested.iter().cloned().collect();
|
||||
let poll = !self.status_requested.is_empty() || !self.push_requested.is_empty();
|
||||
|
||||
let work = cx.background_spawn(async move {
|
||||
let mut facts: Vec<(PathBuf, Option<String>, Option<String>)> = Vec::new();
|
||||
let mut facts = Vec::new();
|
||||
for scanned in scanned.iter() {
|
||||
let path = &scanned.path;
|
||||
|
||||
// The browser's mirror clones are not user checkouts.
|
||||
if cache_root
|
||||
.as_ref()
|
||||
.is_some_and(|root| path.starts_with(root))
|
||||
@@ -342,15 +241,13 @@ impl CheckoutsStore {
|
||||
continue;
|
||||
}
|
||||
|
||||
let origin = Repo::open(path)
|
||||
.and_then(|repo| repo.origin_url())
|
||||
.ok()
|
||||
.flatten();
|
||||
|
||||
let root = Repo::open(path)
|
||||
.and_then(|repo| repo.root_commit())
|
||||
.ok()
|
||||
.flatten();
|
||||
let (origin, root) = match Repo::open(path) {
|
||||
Ok(repo) => (
|
||||
repo.origin_url().ok().flatten(),
|
||||
repo.root_commit().ok().flatten(),
|
||||
),
|
||||
Err(_) => (None, None),
|
||||
};
|
||||
|
||||
facts.push((path.clone(), origin, root));
|
||||
}
|
||||
@@ -358,283 +255,31 @@ impl CheckoutsStore {
|
||||
let associations =
|
||||
Remembered::resolve_associations(&remembered, &facts, announcements.iter());
|
||||
|
||||
let associations: HashMap<RepoAddr, Vec<PathBuf>> = associations
|
||||
associations
|
||||
.into_iter()
|
||||
.map(|(addr, paths)| (addr, paths.into_iter().filter(|p| p.is_dir()).collect()))
|
||||
.collect();
|
||||
|
||||
let (statuses, push_statuses) =
|
||||
CheckoutsStore::compute_statuses(&associations, &requested, &push_requested, true);
|
||||
|
||||
(associations, statuses, push_statuses)
|
||||
.collect::<HashMap<RepoAddr, Vec<PathBuf>>>()
|
||||
});
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
let (associations, statuses, push_statuses) = work.await;
|
||||
|
||||
let associations = work.await;
|
||||
let again = this.update(cx, |this, cx| {
|
||||
let associations_changed = this.by_repo != associations;
|
||||
let statuses_changed = this.statuses != statuses;
|
||||
let push_statuses_changed = this.push_statuses != push_statuses;
|
||||
|
||||
let changed = this.by_repo != associations;
|
||||
this.by_repo = associations;
|
||||
this.statuses = statuses;
|
||||
this.push_statuses = push_statuses;
|
||||
|
||||
// Notify only when something actually changed.
|
||||
if associations_changed || statuses_changed || push_statuses_changed {
|
||||
if changed {
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
this.last_full_sync = Some(Instant::now());
|
||||
this.refresh.finish()
|
||||
})?;
|
||||
|
||||
if again {
|
||||
this.update(cx, |this, cx| {
|
||||
this.refresh(cx);
|
||||
})?;
|
||||
this.update(cx, |this, cx| this.refresh(cx))?;
|
||||
}
|
||||
|
||||
this.update(cx, |this, cx| {
|
||||
if poll {
|
||||
this.schedule_local_pass(cx);
|
||||
}
|
||||
})?;
|
||||
|
||||
Ok::<(), Error>(())
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
fn schedule_local_pass(&mut self, cx: &mut Context<Self>) {
|
||||
if self.local_pending {
|
||||
return;
|
||||
}
|
||||
self.local_pending = true;
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
cx.background_executor().timer(LOCAL_POLL).await;
|
||||
this.update(cx, |this, cx| {
|
||||
this.local_pending = false;
|
||||
this.local_tick(cx);
|
||||
})
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
fn local_tick(&mut self, cx: &mut Context<Self>) {
|
||||
if self.status_requested.is_empty() && self.push_requested.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
if self.refresh.running() || self.debounce_pending {
|
||||
self.schedule_local_pass(cx);
|
||||
return;
|
||||
}
|
||||
|
||||
let cadence = if self.status_requested.is_empty() {
|
||||
PUSH_POLL
|
||||
} else {
|
||||
STATUS_POLL
|
||||
};
|
||||
|
||||
let full_due = self
|
||||
.last_full_sync
|
||||
.is_none_or(|sync| sync.elapsed() >= cadence);
|
||||
|
||||
if full_due {
|
||||
self.last_full_sync = Some(Instant::now());
|
||||
self.refresh(cx);
|
||||
} else {
|
||||
self.run_local_statuses(cx);
|
||||
}
|
||||
|
||||
self.schedule_local_pass(cx);
|
||||
}
|
||||
|
||||
fn run_local_statuses(&mut self, cx: &mut Context<Self>) {
|
||||
let associations = self.by_repo.clone();
|
||||
|
||||
let requested: Vec<(RepoAddr, Option<String>)> = self
|
||||
.status_requested
|
||||
.iter()
|
||||
.map(|addr| {
|
||||
(
|
||||
addr.clone(),
|
||||
self.requested_head.get(addr).cloned().flatten(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let push_requested: Vec<RepoAddr> = self.push_requested.iter().cloned().collect();
|
||||
|
||||
let work = cx.background_spawn(async move {
|
||||
CheckoutsStore::compute_statuses(&associations, &requested, &push_requested, false)
|
||||
});
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
let (statuses, push_statuses) = work.await;
|
||||
|
||||
this.update(cx, |this, cx| {
|
||||
if this.refresh.running() || this.debounce_pending {
|
||||
return;
|
||||
}
|
||||
|
||||
let statuses_changed = this.statuses != statuses;
|
||||
let push_statuses_changed = this.push_statuses != push_statuses;
|
||||
|
||||
this.statuses = statuses;
|
||||
this.push_statuses = push_statuses;
|
||||
|
||||
if statuses_changed || push_statuses_changed {
|
||||
cx.notify();
|
||||
}
|
||||
})?;
|
||||
|
||||
Ok::<(), anyhow::Error>(())
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
fn checkout_status(path: &Path, announced_head: Option<&str>) -> Option<CheckoutStatus> {
|
||||
let repo = Repo::try_open(path)?;
|
||||
let branches = repo.branches().ok()?;
|
||||
|
||||
if branches.is_empty() || repo.is_dirty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let branch = repo.current_branch()?;
|
||||
let head = repo.head()?;
|
||||
let base = announced_head
|
||||
.filter(|name| branches.iter().any(|b| b == name))
|
||||
.map(str::to_owned)
|
||||
.or_else(|| branches.iter().find(|b| *b == "main").cloned())
|
||||
.or_else(|| branches.first().cloned())?;
|
||||
|
||||
if base == branch {
|
||||
return None;
|
||||
}
|
||||
|
||||
let ahead = repo.commits_ahead(&base, &branch);
|
||||
(ahead > 0).then_some(CheckoutStatus {
|
||||
path: path.to_path_buf(),
|
||||
branch,
|
||||
head,
|
||||
base,
|
||||
ahead,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns checkouts that are ahead of their remote tracking branch.
|
||||
fn checkout_push_status(path: &Path, fetch: bool) -> Option<CheckoutStatus> {
|
||||
let repo = Repo::try_open(path)?;
|
||||
if repo.is_dirty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let branch = repo.current_branch()?;
|
||||
let head = repo.head()?;
|
||||
let origin = repo.origin_url().ok().flatten()?;
|
||||
|
||||
if fetch && let Err(e) = repo.fetch_refs(&[origin], "+refs/heads/*:refs/remotes/origin/*") {
|
||||
log::warn!("failed to fetch refs for {path:?}: {e}");
|
||||
}
|
||||
|
||||
let remote = format!("refs/remotes/origin/{branch}");
|
||||
|
||||
// If the branch is new and has no remote tracking branch, fall back to origin/HEAD.
|
||||
let base = if repo.ref_exists(&remote) {
|
||||
remote
|
||||
} else if repo.ref_exists("refs/remotes/origin/HEAD") {
|
||||
"refs/remotes/origin/HEAD".to_owned()
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
|
||||
let ahead = repo.commits_ahead(&base, &branch);
|
||||
|
||||
(ahead > 0).then_some(CheckoutStatus {
|
||||
path: path.to_path_buf(),
|
||||
branch,
|
||||
head,
|
||||
base,
|
||||
ahead,
|
||||
})
|
||||
}
|
||||
|
||||
fn compute_statuses(
|
||||
associations: &HashMap<RepoAddr, Vec<PathBuf>>,
|
||||
requested: &[(RepoAddr, Option<String>)],
|
||||
push_requested: &[RepoAddr],
|
||||
fetch: bool,
|
||||
) -> (
|
||||
HashMap<RepoAddr, Vec<CheckoutStatus>>,
|
||||
HashMap<RepoAddr, Vec<CheckoutStatus>>,
|
||||
) {
|
||||
let mut statuses: HashMap<RepoAddr, Vec<CheckoutStatus>> = HashMap::new();
|
||||
for (addr, announced_head) in requested {
|
||||
let Some(paths) = associations.get(addr) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let list: Vec<CheckoutStatus> = paths
|
||||
.iter()
|
||||
.take(MAX_STATUS_CHECKOUTS)
|
||||
.filter_map(|path| Self::checkout_status(path, announced_head.as_deref()))
|
||||
.collect();
|
||||
|
||||
if !list.is_empty() {
|
||||
statuses.insert(addr.clone(), list);
|
||||
}
|
||||
}
|
||||
|
||||
let mut push_statuses: HashMap<RepoAddr, Vec<CheckoutStatus>> = HashMap::new();
|
||||
for addr in push_requested {
|
||||
let Some(paths) = associations.get(addr) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let list: Vec<CheckoutStatus> = paths
|
||||
.iter()
|
||||
.take(MAX_STATUS_CHECKOUTS)
|
||||
.filter_map(|path| Self::checkout_push_status(path, fetch))
|
||||
.collect();
|
||||
|
||||
if !list.is_empty() {
|
||||
push_statuses.insert(addr.clone(), list);
|
||||
}
|
||||
}
|
||||
|
||||
(statuses, push_statuses)
|
||||
}
|
||||
|
||||
pub fn pr_proposes_checkout(
|
||||
pr: &Event,
|
||||
open: bool,
|
||||
user: PublicKey,
|
||||
checkout: &CheckoutStatus,
|
||||
) -> bool {
|
||||
if pr.kind != Kind::GitPullRequest || !open || pr.pubkey != user {
|
||||
return false;
|
||||
}
|
||||
|
||||
let branch_matches = pr
|
||||
.tags
|
||||
.iter()
|
||||
.find(|t| t.kind() == "branch-name")
|
||||
.and_then(|t| t.content())
|
||||
.is_some_and(|name| name == checkout.branch);
|
||||
|
||||
// A renamed branch falls back to the proposed tip commit.
|
||||
let tip_matches = pr
|
||||
.tags
|
||||
.iter()
|
||||
.find(|t| t.kind() == "c")
|
||||
.and_then(|t| t.content())
|
||||
.is_some_and(|tip| tip == checkout.head);
|
||||
|
||||
branch_matches || tip_matches
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,14 +33,18 @@ impl Inbox {
|
||||
self.loaded = false;
|
||||
cx.notify();
|
||||
|
||||
let backend = Backend::global(cx);
|
||||
let backend = Backend::global(cx).downgrade();
|
||||
let work = cx.background_spawn(async move { Self::load_state(&client, me).await });
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
let loaded = work.await;
|
||||
|
||||
this.update(cx, |this, cx| {
|
||||
if backend.read(cx).current_user() != Some(me) {
|
||||
let matches = backend
|
||||
.read_with(cx, |backend, _| backend.current_user() == Some(me))
|
||||
.unwrap_or(false);
|
||||
|
||||
if !matches {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -60,9 +64,13 @@ impl Inbox {
|
||||
}
|
||||
|
||||
pub(crate) fn reset(&mut self, cx: &mut Context<Self>) {
|
||||
let changed = self.loaded || self.state != InboxReadState::default();
|
||||
self.state = InboxReadState::default();
|
||||
self.loaded = false;
|
||||
cx.notify();
|
||||
|
||||
if changed {
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
fn persist(&mut self, cx: &mut Context<Self>) {
|
||||
|
||||
@@ -16,7 +16,7 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
pub use backend::{Backend, BackendEvent};
|
||||
pub use bootstrap::{sync_bootstrap_only, user_grasp_list_servers};
|
||||
pub use checkouts::{CheckoutStatus, CheckoutsStore};
|
||||
pub use checkouts::CheckoutsStore;
|
||||
pub use git_store::Mirrors;
|
||||
use gpui::{App, AppContext};
|
||||
pub use inbox::Inbox;
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::sync::Arc;
|
||||
use anyhow::Error;
|
||||
use gpui::{App, AppContext, Context, Entity, Global, SharedString, Task};
|
||||
use signed_core::{Announcement, RepoAddr};
|
||||
use signed_git::{LocalRepo, Nip34Binding, find_git_repos};
|
||||
use signed_git::{LocalRepo, Nip34Binding};
|
||||
|
||||
struct GlobalLocalReposStore(Entity<LocalReposStore>);
|
||||
|
||||
@@ -44,13 +44,19 @@ impl LocalReposStore {
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, path: &Path, cx: &mut Context<Self>) {
|
||||
self.repos = Arc::new(
|
||||
self.repos
|
||||
.iter()
|
||||
.filter(|repo| repo.path.as_path() != path)
|
||||
.cloned()
|
||||
.collect(),
|
||||
);
|
||||
let Some(index) = self
|
||||
.repos
|
||||
.iter()
|
||||
.position(|repo| repo.path.as_path() == path)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
let mut repos = (*self.repos).clone();
|
||||
repos.remove(index);
|
||||
|
||||
self.repos = Arc::new(repos);
|
||||
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
@@ -72,7 +78,7 @@ impl LocalReposStore {
|
||||
let work = cx.background_spawn(async move {
|
||||
let mut repos = Vec::new();
|
||||
for root in roots.iter() {
|
||||
repos.extend(find_git_repos(root));
|
||||
repos.extend(LocalRepo::find_all(root));
|
||||
}
|
||||
repos.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
repos.dedup_by(|a, b| a.path == b.path);
|
||||
@@ -101,6 +107,14 @@ impl LocalReposStore {
|
||||
task.detach();
|
||||
}
|
||||
|
||||
fn 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))
|
||||
}
|
||||
|
||||
pub fn resolve(
|
||||
repos: &[LocalRepo],
|
||||
known: &[Announcement],
|
||||
@@ -111,7 +125,7 @@ impl LocalReposStore {
|
||||
repos
|
||||
.iter()
|
||||
.filter_map(|repo| {
|
||||
let addr = local_repo_addr(repo);
|
||||
let addr = Self::repo_addr(repo);
|
||||
|
||||
if let Some(addr) = &addr
|
||||
&& shown.contains(addr)
|
||||
@@ -153,11 +167,3 @@ impl ResolvedLocalRepo {
|
||||
.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))
|
||||
}
|
||||
|
||||
@@ -30,21 +30,21 @@ impl PatchSeries {
|
||||
pub(crate) fn tip_commit(&self) -> Option<Sha1Hash> {
|
||||
self.parts
|
||||
.last()
|
||||
.and_then(|part| patch_current_commit(part))
|
||||
.and_then(|part| Self::current_commit(part))
|
||||
.and_then(|hex| hex.parse::<Sha1Hash>().ok())
|
||||
}
|
||||
|
||||
pub(crate) fn commit_of(&self, index: usize) -> Option<&str> {
|
||||
self.parts
|
||||
.get(index)
|
||||
.and_then(|part| patch_current_commit(part))
|
||||
.and_then(|part| Self::current_commit(part))
|
||||
.filter(|hex| hex.len() == 40)
|
||||
}
|
||||
}
|
||||
|
||||
/// The `From <commit>` header on the first line.
|
||||
fn patch_current_commit(patch: &str) -> Option<&str> {
|
||||
let line = patch.lines().next()?;
|
||||
let hex = line.strip_prefix("From ")?;
|
||||
hex.split_whitespace().next().filter(|hex| hex.len() == 40)
|
||||
/// The `From <commit>` header on the first line.
|
||||
fn current_commit(patch: &str) -> Option<&str> {
|
||||
let line = patch.lines().next()?;
|
||||
let hex = line.strip_prefix("From ")?;
|
||||
hex.split_whitespace().next().filter(|hex| hex.len() == 40)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,44 +1,6 @@
|
||||
use nostr::prelude::Url;
|
||||
use nostr_sdk::prelude::*;
|
||||
|
||||
/// `ws://` grasp servers, like ngit, use `http(s)://<host>`.
|
||||
pub(crate) fn grasp_base_url(relay: &RelayUrl) -> Option<String> {
|
||||
let parsed = Url::parse(relay.as_str()).ok()?;
|
||||
let host = parsed.host_str()?;
|
||||
let port = parsed
|
||||
.port()
|
||||
.map(|port| format!(":{port}"))
|
||||
.unwrap_or_default();
|
||||
let scheme = if relay.scheme().is_secure() {
|
||||
"https"
|
||||
} else {
|
||||
"http"
|
||||
};
|
||||
Some(format!("{scheme}://{host}{port}"))
|
||||
}
|
||||
|
||||
pub(crate) fn grasp_clone_url(relay: &RelayUrl, owner: &str, repo_id: &str) -> Option<Url> {
|
||||
let base = grasp_base_url(relay)?;
|
||||
Url::parse(&format!("{base}/{owner}/{repo_id}.git")).ok()
|
||||
}
|
||||
|
||||
/// GRASP-06 contributor namespace URL of a pull request tip.
|
||||
pub(crate) fn grasp06_prs_url(base_url: &str, npub: &str, repo_id: &str) -> String {
|
||||
format!("{base_url}/prs/{npub}/{repo_id}.git")
|
||||
}
|
||||
|
||||
/// The author's GRASP-06 `/prs/` URLs come first.
|
||||
pub(crate) fn pr_clone_urls(prs_urls: Vec<Url>, base_clone_urls: Vec<Url>) -> Vec<Url> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut urls = Vec::new();
|
||||
for url in prs_urls.into_iter().chain(base_clone_urls) {
|
||||
if seen.insert(url.to_string()) {
|
||||
urls.push(url);
|
||||
}
|
||||
}
|
||||
urls
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct GraspServer {
|
||||
relay: RelayUrl,
|
||||
@@ -112,3 +74,43 @@ impl PushOutcome {
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// `ws://` grasp servers, like ngit, use `http(s)://<host>`.
|
||||
pub(crate) fn grasp_base_url(relay: &RelayUrl) -> Option<String> {
|
||||
let parsed = Url::parse(relay.as_str()).ok()?;
|
||||
let host = parsed.host_str()?;
|
||||
let port = parsed
|
||||
.port()
|
||||
.map(|port| format!(":{port}"))
|
||||
.unwrap_or_default();
|
||||
|
||||
let scheme = if relay.scheme().is_secure() {
|
||||
"https"
|
||||
} else {
|
||||
"http"
|
||||
};
|
||||
|
||||
Some(format!("{scheme}://{host}{port}"))
|
||||
}
|
||||
|
||||
pub(crate) fn grasp_clone_url(relay: &RelayUrl, owner: &str, repo_id: &str) -> Option<Url> {
|
||||
let base = grasp_base_url(relay)?;
|
||||
Url::parse(&format!("{base}/{owner}/{repo_id}.git")).ok()
|
||||
}
|
||||
|
||||
/// GRASP-06 contributor namespace URL of a pull request tip.
|
||||
pub(crate) fn grasp06_prs_url(base_url: &str, npub: &str, repo_id: &str) -> String {
|
||||
format!("{base_url}/prs/{npub}/{repo_id}.git")
|
||||
}
|
||||
|
||||
/// The author's GRASP-06 `/prs/` URLs come first.
|
||||
pub(crate) fn pr_clone_urls(prs_urls: Vec<Url>, base_clone_urls: Vec<Url>) -> Vec<Url> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut urls = Vec::new();
|
||||
for url in prs_urls.into_iter().chain(base_clone_urls) {
|
||||
if seen.insert(url.to_string()) {
|
||||
urls.push(url);
|
||||
}
|
||||
}
|
||||
urls
|
||||
}
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
#[derive(Debug, Default)]
|
||||
pub struct RefreshGate {
|
||||
running: bool,
|
||||
dirty: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RefreshRequest {
|
||||
Schedule,
|
||||
Fold,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct RefreshGate {
|
||||
running: bool,
|
||||
dirty: bool,
|
||||
}
|
||||
|
||||
impl RefreshGate {
|
||||
pub fn running(&self) -> bool {
|
||||
self.running
|
||||
|
||||
+166
-198
@@ -3,7 +3,7 @@ use std::collections::{HashMap, HashSet};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{Error, bail};
|
||||
use gpui::{App, AppContext, Context, SharedString, Subscription, Task};
|
||||
use gpui::{App, AppContext, Context, Subscription, Task};
|
||||
use nostr::event::IntoEventBuilder;
|
||||
use nostr_sdk::prelude::*;
|
||||
use settings::{EventFetchingStrategy, SettingsStore};
|
||||
@@ -231,14 +231,6 @@ impl RepoStore {
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
pub fn name(&self) -> SharedString {
|
||||
self.announcement
|
||||
.as_ref()
|
||||
.map_or(SharedString::default(), |a| {
|
||||
SharedString::from(a.name.as_deref().unwrap_or("Unknown"))
|
||||
})
|
||||
}
|
||||
|
||||
fn repo_filters(addr: &RepoAddr) -> Vec<Filter> {
|
||||
let mut filters = vec![
|
||||
Filter::new()
|
||||
@@ -446,18 +438,18 @@ impl RepoStore {
|
||||
.unwrap_or_default();
|
||||
|
||||
let status_by_root =
|
||||
resolve_statuses(&issues, &patches, &pull_requests, &statuses, &maintainers);
|
||||
Self::resolve_statuses(&issues, &patches, &pull_requests, &statuses, &maintainers);
|
||||
|
||||
let open_issue_count = issues
|
||||
.iter()
|
||||
.filter(|issue| status_of(&status_by_root, issue) == RepoStatus::Open)
|
||||
.filter(|issue| Self::status_in(&status_by_root, issue) == RepoStatus::Open)
|
||||
.count();
|
||||
|
||||
let open_pr_count = pull_requests
|
||||
.iter()
|
||||
.filter(|pr| {
|
||||
pr.kind == Kind::GitPullRequest
|
||||
&& status_of(&status_by_root, pr) == RepoStatus::Open
|
||||
&& Self::status_in(&status_by_root, pr) == RepoStatus::Open
|
||||
})
|
||||
.count();
|
||||
|
||||
@@ -588,7 +580,7 @@ impl RepoStore {
|
||||
}
|
||||
|
||||
pub fn status_of(&self, root: &Event) -> RepoStatus {
|
||||
status_of(&self.status_by_root, root)
|
||||
Self::status_in(&self.status_by_root, root)
|
||||
}
|
||||
|
||||
pub fn issue_count(&self) -> usize {
|
||||
@@ -655,10 +647,10 @@ impl RepoStore {
|
||||
.cloned();
|
||||
|
||||
let task = self.publish(
|
||||
comment_builder(root, parent, relay_hint.as_ref(), &addr, content),
|
||||
Self::comment_builder(root, parent, relay_hint.as_ref(), &addr, content),
|
||||
cx,
|
||||
);
|
||||
self.tasks.push(task);
|
||||
self.track_task(task);
|
||||
}
|
||||
|
||||
#[expect(clippy::too_many_arguments, reason = "mirrors the PR event")]
|
||||
@@ -749,7 +741,7 @@ impl RepoStore {
|
||||
};
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
let root_patch = match publish_patch_series(
|
||||
let root_patch = match Self::publish_patch_series(
|
||||
&client,
|
||||
&signer,
|
||||
&addr,
|
||||
@@ -985,12 +977,13 @@ impl RepoStore {
|
||||
);
|
||||
|
||||
// The store owns the publish so it outlives the panel that requested it.
|
||||
this.tasks.push(cx.spawn(async move |_this, _cx| {
|
||||
let task = 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>(())
|
||||
}));
|
||||
});
|
||||
this.track_task(task);
|
||||
})?;
|
||||
|
||||
finished
|
||||
@@ -1066,7 +1059,7 @@ impl RepoStore {
|
||||
.unwrap_or_default();
|
||||
|
||||
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
||||
if let Err(e) = publish_patch_series(
|
||||
if let Err(e) = Self::publish_patch_series(
|
||||
&client,
|
||||
&signer,
|
||||
&addr,
|
||||
@@ -1131,7 +1124,7 @@ impl RepoStore {
|
||||
Ok(())
|
||||
});
|
||||
|
||||
self.tasks.push(task);
|
||||
self.track_task(task);
|
||||
}
|
||||
|
||||
fn set_status(&mut self, root: &Event, status: RepoStatus, cx: &mut Context<Self>) {
|
||||
@@ -1173,7 +1166,7 @@ impl RepoStore {
|
||||
]);
|
||||
|
||||
let task = self.publish(builder, cx);
|
||||
self.tasks.push(task);
|
||||
self.track_task(task);
|
||||
}
|
||||
|
||||
fn action_announcement(&self, cx: &App) -> Option<Announcement> {
|
||||
@@ -1250,13 +1243,18 @@ impl RepoStore {
|
||||
backend.push_checkout_commit(announcement, path.clone(), head, commit, cx)
|
||||
});
|
||||
|
||||
self.run_push(push, Some((addr, path)), cx)
|
||||
self.run_push(push, Some(addr), cx)
|
||||
}
|
||||
|
||||
fn track_task(&mut self, task: Task<Result<(), Error>>) {
|
||||
self.tasks.retain(|task| !task.is_ready());
|
||||
self.tasks.push(task);
|
||||
}
|
||||
|
||||
fn run_push(
|
||||
&mut self,
|
||||
push: Task<Result<PushOutcome, Error>>,
|
||||
pushed_checkout: Option<(RepoAddr, PathBuf)>,
|
||||
pushed_checkout: Option<RepoAddr>,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Task<Result<(), Error>> {
|
||||
self.pushing = true;
|
||||
@@ -1283,20 +1281,10 @@ impl RepoStore {
|
||||
this.last_error = None;
|
||||
this.last_push_warning = outcome.partial_warning();
|
||||
|
||||
if let Some((addr, path)) = &pushed_checkout {
|
||||
let checkouts = CheckoutsStore::global(cx);
|
||||
checkouts.update(cx, |store, cx| {
|
||||
store.checkout_pushed(addr, path, cx);
|
||||
});
|
||||
}
|
||||
|
||||
let sync_status = SyncStatusStore::global(cx);
|
||||
let addr = pushed_checkout
|
||||
.as_ref()
|
||||
.map(|(addr, _)| addr.clone())
|
||||
.or_else(|| this.addr.clone());
|
||||
let addr = pushed_checkout.clone().or_else(|| this.addr.clone());
|
||||
|
||||
sync_status.read(cx).probe(addr);
|
||||
sync_status.update(cx, |store, _| store.probe(addr));
|
||||
}
|
||||
Err(e) => {
|
||||
this.last_error = Some(format!("Push failed: {e}"));
|
||||
@@ -1458,176 +1446,156 @@ impl RepoStore {
|
||||
|
||||
task
|
||||
}
|
||||
}
|
||||
|
||||
fn status_of(status_by_root: &HashMap<EventId, RepoStatus>, root: &Event) -> RepoStatus {
|
||||
status_by_root
|
||||
.get(&root.id)
|
||||
.copied()
|
||||
.unwrap_or(RepoStatus::Open)
|
||||
}
|
||||
|
||||
fn resolve_statuses(
|
||||
issues: &[Event],
|
||||
patches: &[Event],
|
||||
pull_requests: &[Event],
|
||||
statuses: &[Event],
|
||||
maintainers: &[PublicKey],
|
||||
) -> HashMap<EventId, RepoStatus> {
|
||||
let mut by_root: HashMap<EventId, Vec<&Event>> = HashMap::new();
|
||||
for event in statuses {
|
||||
for tag in event.tags.iter() {
|
||||
if matches!(tag.kind(), "e" | "E")
|
||||
&& let Some(id) = tag.content().and_then(|hex| EventId::from_hex(hex).ok())
|
||||
{
|
||||
by_root.entry(id).or_default().push(event);
|
||||
}
|
||||
}
|
||||
fn status_in(status_by_root: &HashMap<EventId, RepoStatus>, root: &Event) -> RepoStatus {
|
||||
status_by_root
|
||||
.get(&root.id)
|
||||
.copied()
|
||||
.unwrap_or(RepoStatus::Open)
|
||||
}
|
||||
|
||||
issues
|
||||
.iter()
|
||||
.chain(patches)
|
||||
.chain(pull_requests)
|
||||
.map(|root| {
|
||||
let events = by_root.get(&root.id).map(Vec::as_slice).unwrap_or(&[]);
|
||||
let status =
|
||||
signed_core::RepoStatus::resolve(events.iter().copied(), &root.pubkey, maintainers);
|
||||
(root.id, status)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
fn resolve_statuses(
|
||||
issues: &[Event],
|
||||
patches: &[Event],
|
||||
pull_requests: &[Event],
|
||||
statuses: &[Event],
|
||||
maintainers: &[PublicKey],
|
||||
) -> HashMap<EventId, RepoStatus> {
|
||||
let mut by_root: HashMap<EventId, Vec<&Event>> = HashMap::new();
|
||||
for event in statuses {
|
||||
for tag in event.tags.iter() {
|
||||
if matches!(tag.kind(), "e" | "E")
|
||||
&& let Some(id) = tag.content().and_then(|hex| EventId::from_hex(hex).ok())
|
||||
{
|
||||
by_root.entry(id).or_default().push(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Publish a patch series as a sequence of `git/patch` events.
|
||||
#[expect(clippy::too_many_arguments, reason = "independent inputs")]
|
||||
async fn publish_patch_series<S>(
|
||||
client: &Client,
|
||||
signer: &S,
|
||||
addr: &RepoAddr,
|
||||
owner: PublicKey,
|
||||
euc: Option<&str>,
|
||||
series: &PatchSeries,
|
||||
first_marker: &str,
|
||||
reply_to: Option<EventId>,
|
||||
) -> Result<Event, Error>
|
||||
where
|
||||
S: AsyncGetPublicKey + AsyncSignEvent + ?Sized,
|
||||
{
|
||||
let mut root: Option<Event> = None;
|
||||
let mut previous = reply_to;
|
||||
issues
|
||||
.iter()
|
||||
.chain(patches)
|
||||
.chain(pull_requests)
|
||||
.map(|root| {
|
||||
let events = by_root.get(&root.id).map(Vec::as_slice).unwrap_or(&[]);
|
||||
let status = signed_core::RepoStatus::resolve(
|
||||
events.iter().copied(),
|
||||
&root.pubkey,
|
||||
maintainers,
|
||||
);
|
||||
(root.id, status)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
for (ix, part) in series.parts.iter().enumerate() {
|
||||
let Some(commit) = series.commit_of(ix) else {
|
||||
return Err(anyhow::anyhow!(
|
||||
"patch {} of the series has no `From <commit-id>` header",
|
||||
ix + 1
|
||||
));
|
||||
/// Publish a patch series as a sequence of `git/patch` events.
|
||||
#[expect(clippy::too_many_arguments, reason = "independent inputs")]
|
||||
async fn publish_patch_series<S>(
|
||||
client: &Client,
|
||||
signer: &S,
|
||||
addr: &RepoAddr,
|
||||
owner: PublicKey,
|
||||
euc: Option<&str>,
|
||||
series: &PatchSeries,
|
||||
first_marker: &str,
|
||||
reply_to: Option<EventId>,
|
||||
) -> Result<Event, Error>
|
||||
where
|
||||
S: AsyncGetPublicKey + AsyncSignEvent + ?Sized,
|
||||
{
|
||||
let mut root: Option<Event> = None;
|
||||
let mut previous = reply_to;
|
||||
|
||||
for (ix, part) in series.parts.iter().enumerate() {
|
||||
let Some(commit) = series.commit_of(ix) else {
|
||||
return Err(anyhow::anyhow!(
|
||||
"patch {} of the series has no `From <commit-id>` header",
|
||||
ix + 1
|
||||
));
|
||||
};
|
||||
|
||||
let mut tags = vec![
|
||||
Tag::coordinate(addr.clone().into(), None),
|
||||
Tag::public_key(owner),
|
||||
];
|
||||
|
||||
if ix == 0 {
|
||||
if let Ok(tag) = Tag::parse(["t", first_marker]) {
|
||||
tags.push(tag);
|
||||
}
|
||||
if let Some(root_id) = reply_to
|
||||
&& let Ok(tag) = Tag::parse(["e", &root_id.to_hex(), "", "reply"])
|
||||
{
|
||||
tags.push(tag);
|
||||
}
|
||||
} else if let Some(previous) = previous
|
||||
&& let Ok(tag) = Tag::parse(["e", &previous.to_hex(), "", "reply"])
|
||||
{
|
||||
tags.push(tag);
|
||||
}
|
||||
|
||||
if let Some(euc) = euc
|
||||
&& let Ok(tag) = Tag::parse(["r", euc])
|
||||
{
|
||||
tags.push(tag);
|
||||
}
|
||||
|
||||
if let Ok(tag) = Tag::parse(["commit", commit]) {
|
||||
tags.push(tag);
|
||||
}
|
||||
|
||||
if let Ok(tag) = Tag::parse(["r", commit]) {
|
||||
tags.push(tag);
|
||||
}
|
||||
|
||||
let builder = EventBuilder::new(Kind::GitPatch)
|
||||
.content(part.clone())
|
||||
.tags(tags);
|
||||
|
||||
let event = builder.finalize_async(signer).await?;
|
||||
let output = client.send_event(&event).broadcast().await?;
|
||||
|
||||
if output.success.is_empty() && !output.failed.is_empty() {
|
||||
let reasons = output
|
||||
.failed
|
||||
.values()
|
||||
.cloned()
|
||||
.collect::<Vec<String>>()
|
||||
.join(", ");
|
||||
bail!("event not accepted by any relay: {reasons}");
|
||||
}
|
||||
|
||||
if root.is_none() {
|
||||
root = Some(event.clone());
|
||||
}
|
||||
previous = Some(event.id);
|
||||
}
|
||||
|
||||
root.ok_or_else(|| anyhow::anyhow!("patch series is empty"))
|
||||
}
|
||||
|
||||
fn comment_builder(
|
||||
root: &Event,
|
||||
parent: Option<&Event>,
|
||||
relay_hint: Option<&RelayUrl>,
|
||||
addr: &RepoAddr,
|
||||
content: String,
|
||||
) -> EventBuilder {
|
||||
let target = |event: &Event| {
|
||||
CommentTarget::event(
|
||||
event.id,
|
||||
event.kind,
|
||||
Some(event.pubkey),
|
||||
relay_hint.cloned().map(Cow::Owned),
|
||||
)
|
||||
};
|
||||
|
||||
let mut tags = vec![
|
||||
Tag::coordinate(addr.clone().into(), None),
|
||||
Tag::public_key(owner),
|
||||
];
|
||||
let root_target = target(root);
|
||||
let parent_target = parent.map(target).unwrap_or_else(|| root_target.clone());
|
||||
|
||||
if ix == 0 {
|
||||
if let Ok(tag) = Tag::parse(["t", first_marker]) {
|
||||
tags.push(tag);
|
||||
}
|
||||
if let Some(root_id) = reply_to
|
||||
&& let Ok(tag) = Tag::parse(["e", &root_id.to_hex(), "", "reply"])
|
||||
{
|
||||
tags.push(tag);
|
||||
}
|
||||
} else if let Some(previous) = previous
|
||||
&& let Ok(tag) = Tag::parse(["e", &previous.to_hex(), "", "reply"])
|
||||
{
|
||||
tags.push(tag);
|
||||
}
|
||||
|
||||
if let Some(euc) = euc
|
||||
&& let Ok(tag) = Tag::parse(["r", euc])
|
||||
{
|
||||
tags.push(tag);
|
||||
}
|
||||
|
||||
if let Ok(tag) = Tag::parse(["commit", commit]) {
|
||||
tags.push(tag);
|
||||
}
|
||||
|
||||
if let Ok(tag) = Tag::parse(["r", commit]) {
|
||||
tags.push(tag);
|
||||
}
|
||||
|
||||
let builder = EventBuilder::new(Kind::GitPatch)
|
||||
.content(part.clone())
|
||||
.tags(tags);
|
||||
|
||||
let event = builder.finalize_async(signer).await?;
|
||||
let output = client.send_event(&event).broadcast().await?;
|
||||
|
||||
if output.success.is_empty() && !output.failed.is_empty() {
|
||||
let reasons = output
|
||||
.failed
|
||||
.values()
|
||||
.cloned()
|
||||
.collect::<Vec<String>>()
|
||||
.join(", ");
|
||||
bail!("event not accepted by any relay: {reasons}");
|
||||
}
|
||||
|
||||
if root.is_none() {
|
||||
root = Some(event.clone());
|
||||
}
|
||||
previous = Some(event.id);
|
||||
}
|
||||
|
||||
root.ok_or_else(|| anyhow::anyhow!("patch series is empty"))
|
||||
}
|
||||
|
||||
fn comment_builder(
|
||||
root: &Event,
|
||||
parent: Option<&Event>,
|
||||
relay_hint: Option<&RelayUrl>,
|
||||
addr: &RepoAddr,
|
||||
content: String,
|
||||
) -> EventBuilder {
|
||||
let target = |event: &Event| {
|
||||
CommentTarget::event(
|
||||
event.id,
|
||||
event.kind,
|
||||
Some(event.pubkey),
|
||||
relay_hint.cloned().map(Cow::Owned),
|
||||
)
|
||||
};
|
||||
|
||||
let root_target = target(root);
|
||||
let parent_target = parent.map(target).unwrap_or_else(|| root_target.clone());
|
||||
|
||||
CommentBuilder::new(content, parent_target)
|
||||
.root(root_target)
|
||||
.into_event_builder()
|
||||
.tags([Tag::coordinate(addr.clone().into(), None)])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::anyhow;
|
||||
use gpui::{AppContext as _, Task, TestAppContext};
|
||||
|
||||
use super::RepoStore;
|
||||
|
||||
#[gpui::test]
|
||||
fn a_finished_push_releases_the_busy_flag(cx: &mut TestAppContext) {
|
||||
let store = cx.new(|_| RepoStore::new_local(PathBuf::from("repo"), None));
|
||||
|
||||
let push = store.update(cx, |store, cx| {
|
||||
store.run_push(Task::ready(Err(anyhow!("push refused"))), None, cx)
|
||||
});
|
||||
cx.run_until_parked();
|
||||
|
||||
assert!(push.is_ready());
|
||||
assert!(!cx.update(|app| store.read(app).pushing));
|
||||
CommentBuilder::new(content, parent_target)
|
||||
.root(root_target)
|
||||
.into_event_builder()
|
||||
.tags([Tag::coordinate(addr.clone().into(), None)])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,25 +11,6 @@ use signed_git::Repo;
|
||||
|
||||
use crate::push::{GraspServer, PushOutcome, grasp_base_url};
|
||||
|
||||
/// A git ref with the commit it points at.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct GitRef {
|
||||
/// Full ref name, like `refs/heads/main` or `refs/tags/v1.0`.
|
||||
pub name: String,
|
||||
pub commit: Sha1Hash,
|
||||
}
|
||||
|
||||
impl GitRef {
|
||||
pub fn new(name: impl Into<String>, commit: &str) -> Result<Self, Error> {
|
||||
let commit = Sha1Hash::from_str(commit).map_err(|_| anyhow!("invalid commit: {commit}"))?;
|
||||
|
||||
Ok(Self {
|
||||
name: name.into(),
|
||||
commit,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// How much to push to the grasp servers.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
pub enum GitPushMode {
|
||||
@@ -52,16 +33,6 @@ pub enum GitPushPolicy {
|
||||
ResetRemote,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SyncState {
|
||||
pub refs: Vec<GitRef>,
|
||||
pub head: Option<String>,
|
||||
/// Local repository to push from; `None` for states parsed from events.
|
||||
pub path: Option<PathBuf>,
|
||||
pub mode: GitPushMode,
|
||||
pub policy: GitPushPolicy,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum PushStep {
|
||||
AnnounceRepository,
|
||||
@@ -102,6 +73,35 @@ impl PushStepStatus {
|
||||
}
|
||||
}
|
||||
|
||||
/// A git ref with the commit it points at.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct GitRef {
|
||||
/// Full ref name, like `refs/heads/main` or `refs/tags/v1.0`.
|
||||
pub name: String,
|
||||
pub commit: Sha1Hash,
|
||||
}
|
||||
|
||||
impl GitRef {
|
||||
pub fn new(name: impl Into<String>, commit: &str) -> Result<Self, Error> {
|
||||
let commit = Sha1Hash::from_str(commit).map_err(|_| anyhow!("invalid commit: {commit}"))?;
|
||||
|
||||
Ok(Self {
|
||||
name: name.into(),
|
||||
commit,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SyncState {
|
||||
pub refs: Vec<GitRef>,
|
||||
pub head: Option<String>,
|
||||
/// Local repository to push from; `None` for states parsed from events.
|
||||
pub path: Option<PathBuf>,
|
||||
pub mode: GitPushMode,
|
||||
pub policy: GitPushPolicy,
|
||||
}
|
||||
|
||||
impl SyncState {
|
||||
pub fn build(id: &str, refs: &[GitRef], head: Option<&str>) -> EventBuilder {
|
||||
let mut tags: Vec<Tag> = vec![Tag::identifier(id.to_owned())];
|
||||
@@ -397,11 +397,11 @@ impl SyncState {
|
||||
repo.push_refspecs(&base, &owner, &repo_id, &[refspec.as_str()])
|
||||
}
|
||||
GitPushMode::All => {
|
||||
let mut refspecs = force_refspecs();
|
||||
let mut refspecs = Self::force_refspecs();
|
||||
if policy == GitPushPolicy::ResetRemote {
|
||||
let url = format!("{base}/{owner}/{repo_id}.git");
|
||||
let server_refs = repo.ls_remote(&url)?;
|
||||
refspecs.extend(deletion_refspecs(&declared, &server_refs));
|
||||
refspecs.extend(Self::deletion_refspecs(&declared, &server_refs));
|
||||
}
|
||||
|
||||
let refspecs = refspecs.iter().map(String::as_str).collect::<Vec<_>>();
|
||||
@@ -526,21 +526,21 @@ impl SyncState {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Refspecs to force push all heads and tags to the grasp servers.
|
||||
fn force_refspecs() -> Vec<String> {
|
||||
vec![
|
||||
"+refs/heads/*:refs/heads/*".to_owned(),
|
||||
"+refs/tags/*:refs/tags/*".to_owned(),
|
||||
]
|
||||
}
|
||||
/// Refspecs to force push all heads and tags to the grasp servers.
|
||||
fn force_refspecs() -> Vec<String> {
|
||||
vec![
|
||||
"+refs/heads/*:refs/heads/*".to_owned(),
|
||||
"+refs/tags/*:refs/tags/*".to_owned(),
|
||||
]
|
||||
}
|
||||
|
||||
/// Refspecs to delete server-only refs from the grasp servers.
|
||||
fn deletion_refspecs(declared: &[String], server_refs: &[(String, String)]) -> Vec<String> {
|
||||
server_refs
|
||||
.iter()
|
||||
.filter(|(name, _)| !declared.contains(name))
|
||||
.map(|(name, _)| format!(":{name}"))
|
||||
.collect()
|
||||
/// Refspecs to delete server-only refs from the grasp servers.
|
||||
fn deletion_refspecs(declared: &[String], server_refs: &[(String, String)]) -> Vec<String> {
|
||||
server_refs
|
||||
.iter()
|
||||
.filter(|(name, _)| !declared.contains(name))
|
||||
.map(|(name, _)| format!(":{name}"))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
@@ -16,6 +15,12 @@ use crate::state::SyncState;
|
||||
const SYNC_POLL: Duration = Duration::from_secs(180);
|
||||
const MAX_SYNC_CHECKOUTS: usize = 8;
|
||||
|
||||
/// Statuses for these repositories may have changed; empty on signer change.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum SyncEvent {
|
||||
Updated(Vec<(RepoAddr, Vec<CheckoutSyncStatus>)>),
|
||||
}
|
||||
|
||||
struct GlobalSyncStatusStore(Entity<SyncStatusStore>);
|
||||
|
||||
impl Global for GlobalSyncStatusStore {}
|
||||
@@ -27,15 +32,12 @@ pub struct CheckoutSyncStatus {
|
||||
pub status: RepoSyncStatus,
|
||||
}
|
||||
|
||||
/// Statuses for these repositories may have changed; empty on signer change.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum SyncEvent {
|
||||
Updated(Vec<(RepoAddr, Vec<CheckoutSyncStatus>)>),
|
||||
}
|
||||
|
||||
/// Probes tracked repositories and broadcasts results. Holds no statuses.
|
||||
pub struct SyncStatusStore {
|
||||
active: RefCell<HashSet<RepoAddr>>,
|
||||
// Addresses a live directory still renders, with one count per directory.
|
||||
active: HashMap<RepoAddr, usize>,
|
||||
// One-shot probes that should not keep the repository on the poll.
|
||||
requested: HashSet<RepoAddr>,
|
||||
in_flight: bool,
|
||||
pass_pending: bool,
|
||||
poll_pending: bool,
|
||||
@@ -93,7 +95,8 @@ impl SyncStatusStore {
|
||||
});
|
||||
|
||||
Self {
|
||||
active: RefCell::new(HashSet::new()),
|
||||
active: HashMap::new(),
|
||||
requested: HashSet::new(),
|
||||
sender,
|
||||
in_flight: false,
|
||||
pass_pending: false,
|
||||
@@ -105,10 +108,37 @@ impl SyncStatusStore {
|
||||
}
|
||||
}
|
||||
|
||||
/// Queue a probe pass; folded into any pass already in flight.
|
||||
pub fn probe(&self, addrs: impl IntoIterator<Item = RepoAddr>) {
|
||||
self.active.borrow_mut().extend(addrs);
|
||||
/// Requests a one-shot probe pass; folded into any pass already in flight.
|
||||
pub fn probe(&mut self, addrs: impl IntoIterator<Item = RepoAddr>) {
|
||||
self.requested.extend(addrs);
|
||||
self.wake();
|
||||
}
|
||||
|
||||
/// Keeps these addresses on the periodic poll until released.
|
||||
pub fn track(&mut self, addrs: impl IntoIterator<Item = RepoAddr>) {
|
||||
for addr in addrs {
|
||||
*self.active.entry(addr).or_default() += 1;
|
||||
}
|
||||
self.wake();
|
||||
}
|
||||
|
||||
/// Drops one directory's interest in these addresses.
|
||||
pub fn untrack(&mut self, addrs: impl IntoIterator<Item = RepoAddr>) {
|
||||
for addr in addrs {
|
||||
let remove = match self.active.get_mut(&addr) {
|
||||
Some(count) => {
|
||||
*count = count.saturating_sub(1);
|
||||
*count == 0
|
||||
}
|
||||
None => false,
|
||||
};
|
||||
if remove {
|
||||
self.active.remove(&addr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn wake(&self) {
|
||||
if let Err(e) = self.sender.send(()) {
|
||||
log::warn!("failed to queue sync status probe: {e}");
|
||||
}
|
||||
@@ -116,8 +146,8 @@ impl SyncStatusStore {
|
||||
|
||||
// Keeps the in-flight pass so its completion releases the slot exactly once.
|
||||
fn clear(&mut self, cx: &mut Context<Self>) {
|
||||
let had_addrs = !self.active.borrow().is_empty();
|
||||
self.active.borrow_mut().clear();
|
||||
let had_addrs = !self.active.is_empty() || !self.requested.is_empty();
|
||||
self.requested.clear();
|
||||
self.pass_pending = false;
|
||||
|
||||
if had_addrs {
|
||||
@@ -136,29 +166,36 @@ impl SyncStatusStore {
|
||||
}
|
||||
|
||||
let backend = Backend::global(cx);
|
||||
let client = backend.read(cx).client();
|
||||
|
||||
if backend.read(cx).current_user().is_none() {
|
||||
self.clear(cx);
|
||||
return;
|
||||
}
|
||||
|
||||
if self.active.borrow().is_empty() {
|
||||
if self.active.is_empty() && self.requested.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
self.in_flight = true;
|
||||
self.schedule_poll(cx);
|
||||
let poll = !self.active.is_empty();
|
||||
if poll {
|
||||
self.schedule_poll(cx);
|
||||
}
|
||||
|
||||
let mut targets: Vec<RepoAddr> = self.active.keys().cloned().collect();
|
||||
targets.extend(self.requested.drain());
|
||||
targets.sort();
|
||||
targets.dedup();
|
||||
|
||||
let client = backend.read(cx).client();
|
||||
let targets: Vec<(RepoAddr, Vec<PathBuf>)> = {
|
||||
let active = self.active.borrow();
|
||||
let checkouts = CheckoutsStore::global(cx);
|
||||
|
||||
active
|
||||
.iter()
|
||||
targets
|
||||
.into_iter()
|
||||
.map(|addr| {
|
||||
let paths = checkouts.read(cx).associations_of(addr);
|
||||
(addr.clone(), paths)
|
||||
let paths = checkouts.read(cx).associations_of(&addr);
|
||||
(addr, paths)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
@@ -260,7 +297,8 @@ impl SyncStatusStore {
|
||||
/// Sync status cache bound to one panel or screen.
|
||||
pub struct SyncStatusDirectory {
|
||||
statuses: HashMap<RepoAddr, Vec<CheckoutSyncStatus>>,
|
||||
pending: RefCell<HashSet<RepoAddr>>,
|
||||
pending: HashSet<RepoAddr>,
|
||||
tracked: HashSet<RepoAddr>,
|
||||
_subscriptions: Vec<Subscription>,
|
||||
}
|
||||
|
||||
@@ -275,10 +313,20 @@ impl SyncStatusDirectory {
|
||||
SyncEvent::Updated(updates) => this.apply(updates.clone(), cx),
|
||||
});
|
||||
|
||||
let release = cx.on_release(|this: &mut Self, cx| {
|
||||
let tracked = std::mem::take(&mut this.tracked);
|
||||
if tracked.is_empty() {
|
||||
return;
|
||||
}
|
||||
let store = SyncStatusStore::global(cx);
|
||||
store.update(cx, |store, _| store.untrack(tracked));
|
||||
});
|
||||
|
||||
Self {
|
||||
statuses: HashMap::new(),
|
||||
pending: RefCell::new(HashSet::new()),
|
||||
_subscriptions: vec![subscription],
|
||||
pending: HashSet::new(),
|
||||
tracked: HashSet::new(),
|
||||
_subscriptions: vec![subscription, release],
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -289,7 +337,8 @@ impl SyncStatusDirectory {
|
||||
.into_iter()
|
||||
.filter(|addr| {
|
||||
!self.statuses.contains_key(addr)
|
||||
&& !self.with_pending(|pending| pending.contains(addr))
|
||||
&& !self.pending.contains(addr)
|
||||
&& !self.tracked.contains(addr)
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -297,30 +346,18 @@ impl SyncStatusDirectory {
|
||||
return;
|
||||
}
|
||||
|
||||
self.with_pending(|pending| pending.extend(missing.iter().cloned()));
|
||||
self.pending.extend(missing.iter().cloned());
|
||||
self.tracked.extend(missing.iter().cloned());
|
||||
|
||||
let store = SyncStatusStore::global(cx);
|
||||
store.read(cx).probe(missing);
|
||||
store.update(cx, |store, _| {
|
||||
store.track(missing);
|
||||
});
|
||||
}
|
||||
|
||||
/// Statuses for a repo, or empty; a miss queues a probe.
|
||||
pub fn statuses_of(&self, addr: &RepoAddr, cx: &App) -> Vec<CheckoutSyncStatus> {
|
||||
self.queue(addr, cx);
|
||||
self.statuses.get(addr).cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Commits available locally but missing on Nostr.
|
||||
pub fn unsynced(&self, addr: &RepoAddr, cx: &App) -> usize {
|
||||
self.queue(addr, cx);
|
||||
|
||||
self.statuses
|
||||
.get(addr)
|
||||
.map(|list| {
|
||||
list.iter()
|
||||
.map(|checkout| checkout.status.ahead_total)
|
||||
.sum()
|
||||
})
|
||||
.unwrap_or(0)
|
||||
/// Statuses for a repo, or empty.
|
||||
pub fn statuses_of(&self, addr: &RepoAddr) -> &[CheckoutSyncStatus] {
|
||||
self.statuses.get(addr).map(Vec::as_slice).unwrap_or(&[])
|
||||
}
|
||||
|
||||
/// Commit ids missing on Nostr, mapped to their checkout; restricted to `checkout` if tracked.
|
||||
@@ -328,10 +365,7 @@ impl SyncStatusDirectory {
|
||||
&self,
|
||||
addr: &RepoAddr,
|
||||
checkout: Option<&Path>,
|
||||
cx: &App,
|
||||
) -> HashMap<String, PathBuf> {
|
||||
self.queue(addr, cx);
|
||||
|
||||
let Some(statuses) = self.statuses.get(addr) else {
|
||||
return HashMap::new();
|
||||
};
|
||||
@@ -359,22 +393,11 @@ impl SyncStatusDirectory {
|
||||
commits
|
||||
}
|
||||
|
||||
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()]);
|
||||
}
|
||||
}
|
||||
|
||||
fn apply(&mut self, updates: Vec<(RepoAddr, Vec<CheckoutSyncStatus>)>, cx: &mut Context<Self>) {
|
||||
if updates.is_empty() {
|
||||
let changed = !self.statuses.is_empty();
|
||||
self.statuses.clear();
|
||||
self.with_pending(|pending| pending.clear());
|
||||
self.pending.clear();
|
||||
|
||||
if changed {
|
||||
cx.notify();
|
||||
@@ -387,7 +410,8 @@ impl SyncStatusDirectory {
|
||||
|
||||
for (addr, list) in updates {
|
||||
let relevant = self.statuses.contains_key(&addr)
|
||||
|| self.with_pending(|pending| pending.remove(&addr));
|
||||
|| self.pending.remove(&addr)
|
||||
|| self.tracked.contains(&addr);
|
||||
|
||||
if !relevant {
|
||||
continue;
|
||||
@@ -403,9 +427,4 @@ impl SyncStatusDirectory {
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
fn with_pending<R>(&self, then: impl FnOnce(&mut HashSet<RepoAddr>) -> R) -> R {
|
||||
let mut pending = self.pending.borrow_mut();
|
||||
then(&mut pending)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user