buffer_store.rs

   1use crate::{
   2    ProjectItem as _, ProjectPath,
   3    lsp_store::OpenLspBufferHandle,
   4    search::SearchQuery,
   5    worktree_store::{WorktreeStore, WorktreeStoreEvent},
   6};
   7use anyhow::{Context as _, Result, anyhow};
   8use client::Client;
   9use collections::{HashMap, HashSet, hash_map};
  10use fs::Fs;
  11use futures::{Future, FutureExt as _, StreamExt, channel::oneshot, future::Shared};
  12use gpui::{
  13    App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, Subscription, Task, WeakEntity,
  14};
  15use language::{
  16    Buffer, BufferEvent, Capability, DiskState, File as _, Language, Operation,
  17    proto::{
  18        deserialize_line_ending, deserialize_version, serialize_line_ending, serialize_version,
  19        split_operations,
  20    },
  21};
  22use rpc::{
  23    AnyProtoClient, ErrorCode, ErrorExt as _, TypedEnvelope,
  24    proto::{self},
  25};
  26use smol::channel::Receiver;
  27use std::{io, pin::pin, sync::Arc, time::Instant};
  28use text::{BufferId, ReplicaId};
  29use util::{ResultExt as _, TryFutureExt, debug_panic, maybe, rel_path::RelPath};
  30use worktree::{File, PathChange, ProjectEntryId, Worktree, WorktreeId};
  31
  32/// A set of open buffers.
  33pub struct BufferStore {
  34    state: BufferStoreState,
  35    #[allow(clippy::type_complexity)]
  36    loading_buffers: HashMap<ProjectPath, Shared<Task<Result<Entity<Buffer>, Arc<anyhow::Error>>>>>,
  37    worktree_store: Entity<WorktreeStore>,
  38    opened_buffers: HashMap<BufferId, OpenBuffer>,
  39    path_to_buffer_id: HashMap<ProjectPath, BufferId>,
  40    downstream_client: Option<(AnyProtoClient, u64)>,
  41    shared_buffers: HashMap<proto::PeerId, HashMap<BufferId, SharedBuffer>>,
  42    non_searchable_buffers: HashSet<BufferId>,
  43}
  44
  45#[derive(Hash, Eq, PartialEq, Clone)]
  46struct SharedBuffer {
  47    buffer: Entity<Buffer>,
  48    lsp_handle: Option<OpenLspBufferHandle>,
  49}
  50
  51enum BufferStoreState {
  52    Local(LocalBufferStore),
  53    Remote(RemoteBufferStore),
  54}
  55
  56struct RemoteBufferStore {
  57    shared_with_me: HashSet<Entity<Buffer>>,
  58    upstream_client: AnyProtoClient,
  59    project_id: u64,
  60    loading_remote_buffers_by_id: HashMap<BufferId, Entity<Buffer>>,
  61    remote_buffer_listeners:
  62        HashMap<BufferId, Vec<oneshot::Sender<anyhow::Result<Entity<Buffer>>>>>,
  63    worktree_store: Entity<WorktreeStore>,
  64}
  65
  66struct LocalBufferStore {
  67    local_buffer_ids_by_entry_id: HashMap<ProjectEntryId, BufferId>,
  68    worktree_store: Entity<WorktreeStore>,
  69    _subscription: Subscription,
  70}
  71
  72enum OpenBuffer {
  73    Complete { buffer: WeakEntity<Buffer> },
  74    Operations(Vec<Operation>),
  75}
  76
  77pub enum BufferStoreEvent {
  78    BufferAdded(Entity<Buffer>),
  79    BufferOpened {
  80        buffer: Entity<Buffer>,
  81        project_path: ProjectPath,
  82    },
  83    SharedBufferClosed(proto::PeerId, BufferId),
  84    BufferDropped(BufferId),
  85    BufferChangedFilePath {
  86        buffer: Entity<Buffer>,
  87        old_file: Option<Arc<dyn language::File>>,
  88    },
  89}
  90
  91#[derive(Default, Debug, Clone)]
  92pub struct ProjectTransaction(pub HashMap<Entity<Buffer>, language::Transaction>);
  93
  94impl PartialEq for ProjectTransaction {
  95    fn eq(&self, other: &Self) -> bool {
  96        self.0.len() == other.0.len()
  97            && self.0.iter().all(|(buffer, transaction)| {
  98                other.0.get(buffer).is_some_and(|t| t.id == transaction.id)
  99            })
 100    }
 101}
 102
 103impl EventEmitter<BufferStoreEvent> for BufferStore {}
 104
 105impl RemoteBufferStore {
 106    pub fn wait_for_remote_buffer(
 107        &mut self,
 108        id: BufferId,
 109        cx: &mut Context<BufferStore>,
 110    ) -> Task<Result<Entity<Buffer>>> {
 111        let (tx, rx) = oneshot::channel();
 112        self.remote_buffer_listeners.entry(id).or_default().push(tx);
 113
 114        cx.spawn(async move |this, cx| {
 115            if let Some(buffer) = this
 116                .read_with(cx, |buffer_store, _| buffer_store.get(id))
 117                .ok()
 118                .flatten()
 119            {
 120                return Ok(buffer);
 121            }
 122
 123            cx.background_spawn(async move { rx.await? }).await
 124        })
 125    }
 126
 127    fn save_remote_buffer(
 128        &self,
 129        buffer_handle: Entity<Buffer>,
 130        new_path: Option<proto::ProjectPath>,
 131        cx: &Context<BufferStore>,
 132    ) -> Task<Result<()>> {
 133        let buffer = buffer_handle.read(cx);
 134        let buffer_id = buffer.remote_id().into();
 135        let version = buffer.version();
 136        let rpc = self.upstream_client.clone();
 137        let project_id = self.project_id;
 138        cx.spawn(async move |_, cx| {
 139            let response = rpc
 140                .request(proto::SaveBuffer {
 141                    project_id,
 142                    buffer_id,
 143                    new_path,
 144                    version: serialize_version(&version),
 145                })
 146                .await?;
 147            let version = deserialize_version(&response.version);
 148            let mtime = response.mtime.map(|mtime| mtime.into());
 149
 150            buffer_handle.update(cx, |buffer, cx| {
 151                buffer.did_save(version.clone(), mtime, cx);
 152            })?;
 153
 154            Ok(())
 155        })
 156    }
 157
 158    pub fn handle_create_buffer_for_peer(
 159        &mut self,
 160        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
 161        replica_id: ReplicaId,
 162        capability: Capability,
 163        cx: &mut Context<BufferStore>,
 164    ) -> Result<Option<Entity<Buffer>>> {
 165        match envelope.payload.variant.context("missing variant")? {
 166            proto::create_buffer_for_peer::Variant::State(mut state) => {
 167                let buffer_id = BufferId::new(state.id)?;
 168
 169                let buffer_result = maybe!({
 170                    let mut buffer_file = None;
 171                    if let Some(file) = state.file.take() {
 172                        let worktree_id = worktree::WorktreeId::from_proto(file.worktree_id);
 173                        let worktree = self
 174                            .worktree_store
 175                            .read(cx)
 176                            .worktree_for_id(worktree_id, cx)
 177                            .with_context(|| {
 178                                format!("no worktree found for id {}", file.worktree_id)
 179                            })?;
 180                        buffer_file = Some(Arc::new(File::from_proto(file, worktree, cx)?)
 181                            as Arc<dyn language::File>);
 182                    }
 183                    Buffer::from_proto(replica_id, capability, state, buffer_file)
 184                });
 185
 186                match buffer_result {
 187                    Ok(buffer) => {
 188                        let buffer = cx.new(|_| buffer);
 189                        self.loading_remote_buffers_by_id.insert(buffer_id, buffer);
 190                    }
 191                    Err(error) => {
 192                        if let Some(listeners) = self.remote_buffer_listeners.remove(&buffer_id) {
 193                            for listener in listeners {
 194                                listener.send(Err(anyhow!(error.cloned()))).ok();
 195                            }
 196                        }
 197                    }
 198                }
 199            }
 200            proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
 201                let buffer_id = BufferId::new(chunk.buffer_id)?;
 202                let buffer = self
 203                    .loading_remote_buffers_by_id
 204                    .get(&buffer_id)
 205                    .cloned()
 206                    .with_context(|| {
 207                        format!(
 208                            "received chunk for buffer {} without initial state",
 209                            chunk.buffer_id
 210                        )
 211                    })?;
 212
 213                let result = maybe!({
 214                    let operations = chunk
 215                        .operations
 216                        .into_iter()
 217                        .map(language::proto::deserialize_operation)
 218                        .collect::<Result<Vec<_>>>()?;
 219                    buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx));
 220                    anyhow::Ok(())
 221                });
 222
 223                if let Err(error) = result {
 224                    self.loading_remote_buffers_by_id.remove(&buffer_id);
 225                    if let Some(listeners) = self.remote_buffer_listeners.remove(&buffer_id) {
 226                        for listener in listeners {
 227                            listener.send(Err(error.cloned())).ok();
 228                        }
 229                    }
 230                } else if chunk.is_last {
 231                    self.loading_remote_buffers_by_id.remove(&buffer_id);
 232                    if self.upstream_client.is_via_collab() {
 233                        // retain buffers sent by peers to avoid races.
 234                        self.shared_with_me.insert(buffer.clone());
 235                    }
 236
 237                    if let Some(senders) = self.remote_buffer_listeners.remove(&buffer_id) {
 238                        for sender in senders {
 239                            sender.send(Ok(buffer.clone())).ok();
 240                        }
 241                    }
 242                    return Ok(Some(buffer));
 243                }
 244            }
 245        }
 246        Ok(None)
 247    }
 248
 249    pub fn incomplete_buffer_ids(&self) -> Vec<BufferId> {
 250        self.loading_remote_buffers_by_id
 251            .keys()
 252            .copied()
 253            .collect::<Vec<_>>()
 254    }
 255
 256    pub fn deserialize_project_transaction(
 257        &self,
 258        message: proto::ProjectTransaction,
 259        push_to_history: bool,
 260        cx: &mut Context<BufferStore>,
 261    ) -> Task<Result<ProjectTransaction>> {
 262        cx.spawn(async move |this, cx| {
 263            let mut project_transaction = ProjectTransaction::default();
 264            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
 265            {
 266                let buffer_id = BufferId::new(buffer_id)?;
 267                let buffer = this
 268                    .update(cx, |this, cx| this.wait_for_remote_buffer(buffer_id, cx))?
 269                    .await?;
 270                let transaction = language::proto::deserialize_transaction(transaction)?;
 271                project_transaction.0.insert(buffer, transaction);
 272            }
 273
 274            for (buffer, transaction) in &project_transaction.0 {
 275                buffer
 276                    .update(cx, |buffer, _| {
 277                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
 278                    })?
 279                    .await?;
 280
 281                if push_to_history {
 282                    buffer.update(cx, |buffer, _| {
 283                        buffer.push_transaction(transaction.clone(), Instant::now());
 284                        buffer.finalize_last_transaction();
 285                    })?;
 286                }
 287            }
 288
 289            Ok(project_transaction)
 290        })
 291    }
 292
 293    fn open_buffer(
 294        &self,
 295        path: Arc<RelPath>,
 296        worktree: Entity<Worktree>,
 297        cx: &mut Context<BufferStore>,
 298    ) -> Task<Result<Entity<Buffer>>> {
 299        let worktree_id = worktree.read(cx).id().to_proto();
 300        let project_id = self.project_id;
 301        let client = self.upstream_client.clone();
 302        cx.spawn(async move |this, cx| {
 303            let response = client
 304                .request(proto::OpenBufferByPath {
 305                    project_id,
 306                    worktree_id,
 307                    path: path.to_proto(),
 308                })
 309                .await?;
 310            let buffer_id = BufferId::new(response.buffer_id)?;
 311
 312            let buffer = this
 313                .update(cx, {
 314                    |this, cx| this.wait_for_remote_buffer(buffer_id, cx)
 315                })?
 316                .await?;
 317
 318            Ok(buffer)
 319        })
 320    }
 321
 322    fn create_buffer(
 323        &self,
 324        project_searchable: bool,
 325        cx: &mut Context<BufferStore>,
 326    ) -> Task<Result<Entity<Buffer>>> {
 327        let create = self.upstream_client.request(proto::OpenNewBuffer {
 328            project_id: self.project_id,
 329        });
 330        cx.spawn(async move |this, cx| {
 331            let response = create.await?;
 332            let buffer_id = BufferId::new(response.buffer_id)?;
 333
 334            this.update(cx, |this, cx| {
 335                if !project_searchable {
 336                    this.non_searchable_buffers.insert(buffer_id);
 337                }
 338                this.wait_for_remote_buffer(buffer_id, cx)
 339            })?
 340            .await
 341        })
 342    }
 343
 344    fn reload_buffers(
 345        &self,
 346        buffers: HashSet<Entity<Buffer>>,
 347        push_to_history: bool,
 348        cx: &mut Context<BufferStore>,
 349    ) -> Task<Result<ProjectTransaction>> {
 350        let request = self.upstream_client.request(proto::ReloadBuffers {
 351            project_id: self.project_id,
 352            buffer_ids: buffers
 353                .iter()
 354                .map(|buffer| buffer.read(cx).remote_id().to_proto())
 355                .collect(),
 356        });
 357
 358        cx.spawn(async move |this, cx| {
 359            let response = request.await?.transaction.context("missing transaction")?;
 360            this.update(cx, |this, cx| {
 361                this.deserialize_project_transaction(response, push_to_history, cx)
 362            })?
 363            .await
 364        })
 365    }
 366}
 367
 368impl LocalBufferStore {
 369    fn save_local_buffer(
 370        &self,
 371        buffer_handle: Entity<Buffer>,
 372        worktree: Entity<Worktree>,
 373        path: Arc<RelPath>,
 374        mut has_changed_file: bool,
 375        cx: &mut Context<BufferStore>,
 376    ) -> Task<Result<()>> {
 377        let buffer = buffer_handle.read(cx);
 378
 379        let text = buffer.as_rope().clone();
 380        let line_ending = buffer.line_ending();
 381        let version = buffer.version();
 382        let buffer_id = buffer.remote_id();
 383        let file = buffer.file().cloned();
 384        if file
 385            .as_ref()
 386            .is_some_and(|file| file.disk_state() == DiskState::New)
 387        {
 388            has_changed_file = true;
 389        }
 390
 391        let save = worktree.update(cx, |worktree, cx| {
 392            worktree.write_file(path, text, line_ending, cx)
 393        });
 394
 395        cx.spawn(async move |this, cx| {
 396            let new_file = save.await?;
 397            let mtime = new_file.disk_state().mtime();
 398            this.update(cx, |this, cx| {
 399                if let Some((downstream_client, project_id)) = this.downstream_client.clone() {
 400                    if has_changed_file {
 401                        downstream_client
 402                            .send(proto::UpdateBufferFile {
 403                                project_id,
 404                                buffer_id: buffer_id.to_proto(),
 405                                file: Some(language::File::to_proto(&*new_file, cx)),
 406                            })
 407                            .log_err();
 408                    }
 409                    downstream_client
 410                        .send(proto::BufferSaved {
 411                            project_id,
 412                            buffer_id: buffer_id.to_proto(),
 413                            version: serialize_version(&version),
 414                            mtime: mtime.map(|time| time.into()),
 415                        })
 416                        .log_err();
 417                }
 418            })?;
 419            buffer_handle.update(cx, |buffer, cx| {
 420                if has_changed_file {
 421                    buffer.file_updated(new_file, cx);
 422                }
 423                buffer.did_save(version.clone(), mtime, cx);
 424            })
 425        })
 426    }
 427
 428    fn subscribe_to_worktree(
 429        &mut self,
 430        worktree: &Entity<Worktree>,
 431        cx: &mut Context<BufferStore>,
 432    ) {
 433        cx.subscribe(worktree, |this, worktree, event, cx| {
 434            if worktree.read(cx).is_local()
 435                && let worktree::Event::UpdatedEntries(changes) = event
 436            {
 437                Self::local_worktree_entries_changed(this, &worktree, changes, cx);
 438            }
 439        })
 440        .detach();
 441    }
 442
 443    fn local_worktree_entries_changed(
 444        this: &mut BufferStore,
 445        worktree_handle: &Entity<Worktree>,
 446        changes: &[(Arc<RelPath>, ProjectEntryId, PathChange)],
 447        cx: &mut Context<BufferStore>,
 448    ) {
 449        let snapshot = worktree_handle.read(cx).snapshot();
 450        for (path, entry_id, _) in changes {
 451            Self::local_worktree_entry_changed(
 452                this,
 453                *entry_id,
 454                path,
 455                worktree_handle,
 456                &snapshot,
 457                cx,
 458            );
 459        }
 460    }
 461
 462    fn local_worktree_entry_changed(
 463        this: &mut BufferStore,
 464        entry_id: ProjectEntryId,
 465        path: &Arc<RelPath>,
 466        worktree: &Entity<worktree::Worktree>,
 467        snapshot: &worktree::Snapshot,
 468        cx: &mut Context<BufferStore>,
 469    ) -> Option<()> {
 470        let project_path = ProjectPath {
 471            worktree_id: snapshot.id(),
 472            path: path.clone(),
 473        };
 474
 475        let buffer_id = this
 476            .as_local_mut()
 477            .and_then(|local| local.local_buffer_ids_by_entry_id.get(&entry_id))
 478            .copied()
 479            .or_else(|| this.path_to_buffer_id.get(&project_path).copied())?;
 480
 481        let buffer = if let Some(buffer) = this.get(buffer_id) {
 482            Some(buffer)
 483        } else {
 484            this.opened_buffers.remove(&buffer_id);
 485            this.non_searchable_buffers.remove(&buffer_id);
 486            None
 487        };
 488
 489        let buffer = if let Some(buffer) = buffer {
 490            buffer
 491        } else {
 492            this.path_to_buffer_id.remove(&project_path);
 493            let this = this.as_local_mut()?;
 494            this.local_buffer_ids_by_entry_id.remove(&entry_id);
 495            return None;
 496        };
 497
 498        let events = buffer.update(cx, |buffer, cx| {
 499            let file = buffer.file()?;
 500            let old_file = File::from_dyn(Some(file))?;
 501            if old_file.worktree != *worktree {
 502                return None;
 503            }
 504
 505            let snapshot_entry = old_file
 506                .entry_id
 507                .and_then(|entry_id| snapshot.entry_for_id(entry_id))
 508                .or_else(|| snapshot.entry_for_path(old_file.path.as_ref()));
 509
 510            let new_file = if let Some(entry) = snapshot_entry {
 511                File {
 512                    disk_state: match entry.mtime {
 513                        Some(mtime) => DiskState::Present { mtime },
 514                        None => old_file.disk_state,
 515                    },
 516                    is_local: true,
 517                    entry_id: Some(entry.id),
 518                    path: entry.path.clone(),
 519                    worktree: worktree.clone(),
 520                    is_private: entry.is_private,
 521                }
 522            } else {
 523                File {
 524                    disk_state: DiskState::Deleted,
 525                    is_local: true,
 526                    entry_id: old_file.entry_id,
 527                    path: old_file.path.clone(),
 528                    worktree: worktree.clone(),
 529                    is_private: old_file.is_private,
 530                }
 531            };
 532
 533            if new_file == *old_file {
 534                return None;
 535            }
 536
 537            let mut events = Vec::new();
 538            if new_file.path != old_file.path {
 539                this.path_to_buffer_id.remove(&ProjectPath {
 540                    path: old_file.path.clone(),
 541                    worktree_id: old_file.worktree_id(cx),
 542                });
 543                this.path_to_buffer_id.insert(
 544                    ProjectPath {
 545                        worktree_id: new_file.worktree_id(cx),
 546                        path: new_file.path.clone(),
 547                    },
 548                    buffer_id,
 549                );
 550                events.push(BufferStoreEvent::BufferChangedFilePath {
 551                    buffer: cx.entity(),
 552                    old_file: buffer.file().cloned(),
 553                });
 554            }
 555            let local = this.as_local_mut()?;
 556            if new_file.entry_id != old_file.entry_id {
 557                if let Some(entry_id) = old_file.entry_id {
 558                    local.local_buffer_ids_by_entry_id.remove(&entry_id);
 559                }
 560                if let Some(entry_id) = new_file.entry_id {
 561                    local
 562                        .local_buffer_ids_by_entry_id
 563                        .insert(entry_id, buffer_id);
 564                }
 565            }
 566
 567            if let Some((client, project_id)) = &this.downstream_client {
 568                client
 569                    .send(proto::UpdateBufferFile {
 570                        project_id: *project_id,
 571                        buffer_id: buffer_id.to_proto(),
 572                        file: Some(new_file.to_proto(cx)),
 573                    })
 574                    .ok();
 575            }
 576
 577            buffer.file_updated(Arc::new(new_file), cx);
 578            Some(events)
 579        })?;
 580
 581        for event in events {
 582            cx.emit(event);
 583        }
 584
 585        None
 586    }
 587
 588    fn save_buffer(
 589        &self,
 590        buffer: Entity<Buffer>,
 591        cx: &mut Context<BufferStore>,
 592    ) -> Task<Result<()>> {
 593        let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
 594            return Task::ready(Err(anyhow!("buffer doesn't have a file")));
 595        };
 596        let worktree = file.worktree.clone();
 597        self.save_local_buffer(buffer, worktree, file.path.clone(), false, cx)
 598    }
 599
 600    fn save_buffer_as(
 601        &self,
 602        buffer: Entity<Buffer>,
 603        path: ProjectPath,
 604        cx: &mut Context<BufferStore>,
 605    ) -> Task<Result<()>> {
 606        let Some(worktree) = self
 607            .worktree_store
 608            .read(cx)
 609            .worktree_for_id(path.worktree_id, cx)
 610        else {
 611            return Task::ready(Err(anyhow!("no such worktree")));
 612        };
 613        self.save_local_buffer(buffer, worktree, path.path, true, cx)
 614    }
 615
 616    fn open_buffer(
 617        &self,
 618        path: Arc<RelPath>,
 619        worktree: Entity<Worktree>,
 620        cx: &mut Context<BufferStore>,
 621    ) -> Task<Result<Entity<Buffer>>> {
 622        let load_buffer = worktree.update(cx, |worktree, cx| {
 623            let load_file = worktree.load_file(path.as_ref(), cx);
 624            let reservation = cx.reserve_entity();
 625            let buffer_id = BufferId::from(reservation.entity_id().as_non_zero_u64());
 626            cx.spawn(async move |_, cx| {
 627                let loaded = load_file.await?;
 628                let text_buffer = cx
 629                    .background_spawn(async move {
 630                        text::Buffer::new(ReplicaId::LOCAL, buffer_id, loaded.text)
 631                    })
 632                    .await;
 633                cx.insert_entity(reservation, |_| {
 634                    Buffer::build(text_buffer, Some(loaded.file), Capability::ReadWrite)
 635                })
 636            })
 637        });
 638
 639        cx.spawn(async move |this, cx| {
 640            let buffer = match load_buffer.await {
 641                Ok(buffer) => Ok(buffer),
 642                Err(error) if is_not_found_error(&error) => cx.new(|cx| {
 643                    let buffer_id = BufferId::from(cx.entity_id().as_non_zero_u64());
 644                    let text_buffer = text::Buffer::new(ReplicaId::LOCAL, buffer_id, "");
 645                    Buffer::build(
 646                        text_buffer,
 647                        Some(Arc::new(File {
 648                            worktree,
 649                            path,
 650                            disk_state: DiskState::New,
 651                            entry_id: None,
 652                            is_local: true,
 653                            is_private: false,
 654                        })),
 655                        Capability::ReadWrite,
 656                    )
 657                }),
 658                Err(e) => Err(e),
 659            }?;
 660            this.update(cx, |this, cx| {
 661                this.add_buffer(buffer.clone(), cx)?;
 662                let buffer_id = buffer.read(cx).remote_id();
 663                if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 664                    this.path_to_buffer_id.insert(
 665                        ProjectPath {
 666                            worktree_id: file.worktree_id(cx),
 667                            path: file.path.clone(),
 668                        },
 669                        buffer_id,
 670                    );
 671                    let this = this.as_local_mut().unwrap();
 672                    if let Some(entry_id) = file.entry_id {
 673                        this.local_buffer_ids_by_entry_id
 674                            .insert(entry_id, buffer_id);
 675                    }
 676                }
 677
 678                anyhow::Ok(())
 679            })??;
 680
 681            Ok(buffer)
 682        })
 683    }
 684
 685    fn create_buffer(
 686        &self,
 687        project_searchable: bool,
 688        cx: &mut Context<BufferStore>,
 689    ) -> Task<Result<Entity<Buffer>>> {
 690        cx.spawn(async move |buffer_store, cx| {
 691            let buffer =
 692                cx.new(|cx| Buffer::local("", cx).with_language(language::PLAIN_TEXT.clone(), cx))?;
 693            buffer_store.update(cx, |buffer_store, cx| {
 694                buffer_store.add_buffer(buffer.clone(), cx).log_err();
 695                if !project_searchable {
 696                    buffer_store
 697                        .non_searchable_buffers
 698                        .insert(buffer.read(cx).remote_id());
 699                }
 700            })?;
 701            Ok(buffer)
 702        })
 703    }
 704
 705    fn reload_buffers(
 706        &self,
 707        buffers: HashSet<Entity<Buffer>>,
 708        push_to_history: bool,
 709        cx: &mut Context<BufferStore>,
 710    ) -> Task<Result<ProjectTransaction>> {
 711        cx.spawn(async move |_, cx| {
 712            let mut project_transaction = ProjectTransaction::default();
 713            for buffer in buffers {
 714                let transaction = buffer.update(cx, |buffer, cx| buffer.reload(cx))?.await?;
 715                buffer.update(cx, |buffer, cx| {
 716                    if let Some(transaction) = transaction {
 717                        if !push_to_history {
 718                            buffer.forget_transaction(transaction.id);
 719                        }
 720                        project_transaction.0.insert(cx.entity(), transaction);
 721                    }
 722                })?;
 723            }
 724
 725            Ok(project_transaction)
 726        })
 727    }
 728}
 729
 730impl BufferStore {
 731    pub fn init(client: &AnyProtoClient) {
 732        client.add_entity_message_handler(Self::handle_buffer_reloaded);
 733        client.add_entity_message_handler(Self::handle_buffer_saved);
 734        client.add_entity_message_handler(Self::handle_update_buffer_file);
 735        client.add_entity_request_handler(Self::handle_save_buffer);
 736        client.add_entity_request_handler(Self::handle_reload_buffers);
 737    }
 738
 739    /// Creates a buffer store, optionally retaining its buffers.
 740    pub fn local(worktree_store: Entity<WorktreeStore>, cx: &mut Context<Self>) -> Self {
 741        Self {
 742            state: BufferStoreState::Local(LocalBufferStore {
 743                local_buffer_ids_by_entry_id: Default::default(),
 744                worktree_store: worktree_store.clone(),
 745                _subscription: cx.subscribe(&worktree_store, |this, _, event, cx| {
 746                    if let WorktreeStoreEvent::WorktreeAdded(worktree) = event {
 747                        let this = this.as_local_mut().unwrap();
 748                        this.subscribe_to_worktree(worktree, cx);
 749                    }
 750                }),
 751            }),
 752            downstream_client: None,
 753            opened_buffers: Default::default(),
 754            path_to_buffer_id: Default::default(),
 755            shared_buffers: Default::default(),
 756            loading_buffers: Default::default(),
 757            non_searchable_buffers: Default::default(),
 758            worktree_store,
 759        }
 760    }
 761
 762    pub fn remote(
 763        worktree_store: Entity<WorktreeStore>,
 764        upstream_client: AnyProtoClient,
 765        remote_id: u64,
 766        _cx: &mut Context<Self>,
 767    ) -> Self {
 768        Self {
 769            state: BufferStoreState::Remote(RemoteBufferStore {
 770                shared_with_me: Default::default(),
 771                loading_remote_buffers_by_id: Default::default(),
 772                remote_buffer_listeners: Default::default(),
 773                project_id: remote_id,
 774                upstream_client,
 775                worktree_store: worktree_store.clone(),
 776            }),
 777            downstream_client: None,
 778            opened_buffers: Default::default(),
 779            path_to_buffer_id: Default::default(),
 780            loading_buffers: Default::default(),
 781            shared_buffers: Default::default(),
 782            non_searchable_buffers: Default::default(),
 783            worktree_store,
 784        }
 785    }
 786
 787    fn as_local_mut(&mut self) -> Option<&mut LocalBufferStore> {
 788        match &mut self.state {
 789            BufferStoreState::Local(state) => Some(state),
 790            _ => None,
 791        }
 792    }
 793
 794    fn as_remote_mut(&mut self) -> Option<&mut RemoteBufferStore> {
 795        match &mut self.state {
 796            BufferStoreState::Remote(state) => Some(state),
 797            _ => None,
 798        }
 799    }
 800
 801    fn as_remote(&self) -> Option<&RemoteBufferStore> {
 802        match &self.state {
 803            BufferStoreState::Remote(state) => Some(state),
 804            _ => None,
 805        }
 806    }
 807
 808    pub fn open_buffer(
 809        &mut self,
 810        project_path: ProjectPath,
 811        cx: &mut Context<Self>,
 812    ) -> Task<Result<Entity<Buffer>>> {
 813        if let Some(buffer) = self.get_by_path(&project_path) {
 814            cx.emit(BufferStoreEvent::BufferOpened {
 815                buffer: buffer.clone(),
 816                project_path,
 817            });
 818
 819            return Task::ready(Ok(buffer));
 820        }
 821
 822        let task = match self.loading_buffers.entry(project_path.clone()) {
 823            hash_map::Entry::Occupied(e) => e.get().clone(),
 824            hash_map::Entry::Vacant(entry) => {
 825                let path = project_path.path.clone();
 826                let Some(worktree) = self
 827                    .worktree_store
 828                    .read(cx)
 829                    .worktree_for_id(project_path.worktree_id, cx)
 830                else {
 831                    return Task::ready(Err(anyhow!("no such worktree")));
 832                };
 833                let load_buffer = match &self.state {
 834                    BufferStoreState::Local(this) => this.open_buffer(path, worktree, cx),
 835                    BufferStoreState::Remote(this) => this.open_buffer(path, worktree, cx),
 836                };
 837
 838                entry
 839                    .insert(
 840                        cx.spawn(async move |this, cx| {
 841                            let load_result = load_buffer.await;
 842                            this.update(cx, |this, cx| {
 843                                // Record the fact that the buffer is no longer loading.
 844                                this.loading_buffers.remove(&project_path);
 845
 846                                let buffer = load_result.map_err(Arc::new)?;
 847                                cx.emit(BufferStoreEvent::BufferOpened {
 848                                    buffer: buffer.clone(),
 849                                    project_path,
 850                                });
 851
 852                                Ok(buffer)
 853                            })?
 854                        })
 855                        .shared(),
 856                    )
 857                    .clone()
 858            }
 859        };
 860
 861        cx.background_spawn(async move {
 862            task.await.map_err(|e| {
 863                if e.error_code() != ErrorCode::Internal {
 864                    anyhow!(e.error_code())
 865                } else {
 866                    anyhow!("{e}")
 867                }
 868            })
 869        })
 870    }
 871
 872    pub fn create_buffer(
 873        &mut self,
 874        project_searchable: bool,
 875        cx: &mut Context<Self>,
 876    ) -> Task<Result<Entity<Buffer>>> {
 877        match &self.state {
 878            BufferStoreState::Local(this) => this.create_buffer(project_searchable, cx),
 879            BufferStoreState::Remote(this) => this.create_buffer(project_searchable, cx),
 880        }
 881    }
 882
 883    pub fn save_buffer(
 884        &mut self,
 885        buffer: Entity<Buffer>,
 886        cx: &mut Context<Self>,
 887    ) -> Task<Result<()>> {
 888        match &mut self.state {
 889            BufferStoreState::Local(this) => this.save_buffer(buffer, cx),
 890            BufferStoreState::Remote(this) => this.save_remote_buffer(buffer, None, cx),
 891        }
 892    }
 893
 894    pub fn save_buffer_as(
 895        &mut self,
 896        buffer: Entity<Buffer>,
 897        path: ProjectPath,
 898        cx: &mut Context<Self>,
 899    ) -> Task<Result<()>> {
 900        let old_file = buffer.read(cx).file().cloned();
 901        let task = match &self.state {
 902            BufferStoreState::Local(this) => this.save_buffer_as(buffer.clone(), path, cx),
 903            BufferStoreState::Remote(this) => {
 904                this.save_remote_buffer(buffer.clone(), Some(path.to_proto()), cx)
 905            }
 906        };
 907        cx.spawn(async move |this, cx| {
 908            task.await?;
 909            this.update(cx, |_, cx| {
 910                cx.emit(BufferStoreEvent::BufferChangedFilePath { buffer, old_file });
 911            })
 912        })
 913    }
 914
 915    fn add_buffer(&mut self, buffer_entity: Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
 916        let buffer = buffer_entity.read(cx);
 917        let remote_id = buffer.remote_id();
 918        let path = File::from_dyn(buffer.file()).map(|file| ProjectPath {
 919            path: file.path.clone(),
 920            worktree_id: file.worktree_id(cx),
 921        });
 922        let is_remote = buffer.replica_id().is_remote();
 923        let open_buffer = OpenBuffer::Complete {
 924            buffer: buffer_entity.downgrade(),
 925        };
 926
 927        let handle = cx.entity().downgrade();
 928        buffer_entity.update(cx, move |_, cx| {
 929            cx.on_release(move |buffer, cx| {
 930                handle
 931                    .update(cx, |_, cx| {
 932                        cx.emit(BufferStoreEvent::BufferDropped(buffer.remote_id()))
 933                    })
 934                    .ok();
 935            })
 936            .detach()
 937        });
 938        let _expect_path_to_exist;
 939        match self.opened_buffers.entry(remote_id) {
 940            hash_map::Entry::Vacant(entry) => {
 941                entry.insert(open_buffer);
 942                _expect_path_to_exist = false;
 943            }
 944            hash_map::Entry::Occupied(mut entry) => {
 945                if let OpenBuffer::Operations(operations) = entry.get_mut() {
 946                    buffer_entity.update(cx, |b, cx| b.apply_ops(operations.drain(..), cx));
 947                } else if entry.get().upgrade().is_some() {
 948                    if is_remote {
 949                        return Ok(());
 950                    } else {
 951                        debug_panic!("buffer {remote_id} was already registered");
 952                        anyhow::bail!("buffer {remote_id} was already registered");
 953                    }
 954                }
 955                entry.insert(open_buffer);
 956                _expect_path_to_exist = true;
 957            }
 958        }
 959
 960        if let Some(path) = path {
 961            self.path_to_buffer_id.insert(path, remote_id);
 962        }
 963
 964        cx.subscribe(&buffer_entity, Self::on_buffer_event).detach();
 965        cx.emit(BufferStoreEvent::BufferAdded(buffer_entity));
 966        Ok(())
 967    }
 968
 969    pub fn buffers(&self) -> impl '_ + Iterator<Item = Entity<Buffer>> {
 970        self.opened_buffers
 971            .values()
 972            .filter_map(|buffer| buffer.upgrade())
 973    }
 974
 975    pub fn loading_buffers(
 976        &self,
 977    ) -> impl Iterator<Item = (&ProjectPath, impl Future<Output = Result<Entity<Buffer>>>)> {
 978        self.loading_buffers.iter().map(|(path, task)| {
 979            let task = task.clone();
 980            (path, async move {
 981                task.await.map_err(|e| {
 982                    if e.error_code() != ErrorCode::Internal {
 983                        anyhow!(e.error_code())
 984                    } else {
 985                        anyhow!("{e}")
 986                    }
 987                })
 988            })
 989        })
 990    }
 991
 992    pub fn buffer_id_for_project_path(&self, project_path: &ProjectPath) -> Option<&BufferId> {
 993        self.path_to_buffer_id.get(project_path)
 994    }
 995
 996    pub fn get_by_path(&self, path: &ProjectPath) -> Option<Entity<Buffer>> {
 997        self.path_to_buffer_id
 998            .get(path)
 999            .and_then(|buffer_id| self.get(*buffer_id))
1000    }
1001
1002    pub fn get(&self, buffer_id: BufferId) -> Option<Entity<Buffer>> {
1003        self.opened_buffers.get(&buffer_id)?.upgrade()
1004    }
1005
1006    pub fn get_existing(&self, buffer_id: BufferId) -> Result<Entity<Buffer>> {
1007        self.get(buffer_id)
1008            .with_context(|| format!("unknown buffer id {buffer_id}"))
1009    }
1010
1011    pub fn get_possibly_incomplete(&self, buffer_id: BufferId) -> Option<Entity<Buffer>> {
1012        self.get(buffer_id).or_else(|| {
1013            self.as_remote()
1014                .and_then(|remote| remote.loading_remote_buffers_by_id.get(&buffer_id).cloned())
1015        })
1016    }
1017
1018    pub fn buffer_version_info(&self, cx: &App) -> (Vec<proto::BufferVersion>, Vec<BufferId>) {
1019        let buffers = self
1020            .buffers()
1021            .map(|buffer| {
1022                let buffer = buffer.read(cx);
1023                proto::BufferVersion {
1024                    id: buffer.remote_id().into(),
1025                    version: language::proto::serialize_version(&buffer.version),
1026                }
1027            })
1028            .collect();
1029        let incomplete_buffer_ids = self
1030            .as_remote()
1031            .map(|remote| remote.incomplete_buffer_ids())
1032            .unwrap_or_default();
1033        (buffers, incomplete_buffer_ids)
1034    }
1035
1036    pub fn disconnected_from_host(&mut self, cx: &mut App) {
1037        for open_buffer in self.opened_buffers.values_mut() {
1038            if let Some(buffer) = open_buffer.upgrade() {
1039                buffer.update(cx, |buffer, _| buffer.give_up_waiting());
1040            }
1041        }
1042
1043        for buffer in self.buffers() {
1044            buffer.update(cx, |buffer, cx| {
1045                buffer.set_capability(Capability::ReadOnly, cx)
1046            });
1047        }
1048
1049        if let Some(remote) = self.as_remote_mut() {
1050            // Wake up all futures currently waiting on a buffer to get opened,
1051            // to give them a chance to fail now that we've disconnected.
1052            remote.remote_buffer_listeners.clear()
1053        }
1054    }
1055
1056    pub fn shared(&mut self, remote_id: u64, downstream_client: AnyProtoClient, _cx: &mut App) {
1057        self.downstream_client = Some((downstream_client, remote_id));
1058    }
1059
1060    pub fn unshared(&mut self, _cx: &mut Context<Self>) {
1061        self.downstream_client.take();
1062        self.forget_shared_buffers();
1063    }
1064
1065    pub fn discard_incomplete(&mut self) {
1066        self.opened_buffers
1067            .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
1068    }
1069
1070    fn buffer_changed_file(&mut self, buffer: Entity<Buffer>, cx: &mut App) -> Option<()> {
1071        let file = File::from_dyn(buffer.read(cx).file())?;
1072
1073        let remote_id = buffer.read(cx).remote_id();
1074        if let Some(entry_id) = file.entry_id {
1075            if let Some(local) = self.as_local_mut() {
1076                match local.local_buffer_ids_by_entry_id.get(&entry_id) {
1077                    Some(_) => {
1078                        return None;
1079                    }
1080                    None => {
1081                        local
1082                            .local_buffer_ids_by_entry_id
1083                            .insert(entry_id, remote_id);
1084                    }
1085                }
1086            }
1087            self.path_to_buffer_id.insert(
1088                ProjectPath {
1089                    worktree_id: file.worktree_id(cx),
1090                    path: file.path.clone(),
1091                },
1092                remote_id,
1093            );
1094        };
1095
1096        Some(())
1097    }
1098
1099    pub fn find_search_candidates(
1100        &mut self,
1101        query: &SearchQuery,
1102        mut limit: usize,
1103        fs: Arc<dyn Fs>,
1104        cx: &mut Context<Self>,
1105    ) -> Receiver<Entity<Buffer>> {
1106        let (tx, rx) = smol::channel::unbounded();
1107        let mut open_buffers = HashSet::default();
1108        let mut unnamed_buffers = Vec::new();
1109        for handle in self.buffers() {
1110            let buffer = handle.read(cx);
1111            if self.non_searchable_buffers.contains(&buffer.remote_id()) {
1112                continue;
1113            } else if let Some(entry_id) = buffer.entry_id(cx) {
1114                open_buffers.insert(entry_id);
1115            } else {
1116                limit = limit.saturating_sub(1);
1117                unnamed_buffers.push(handle)
1118            };
1119        }
1120
1121        const MAX_CONCURRENT_BUFFER_OPENS: usize = 64;
1122        let project_paths_rx = self
1123            .worktree_store
1124            .update(cx, |worktree_store, cx| {
1125                worktree_store.find_search_candidates(query.clone(), limit, open_buffers, fs, cx)
1126            })
1127            .chunks(MAX_CONCURRENT_BUFFER_OPENS);
1128
1129        cx.spawn(async move |this, cx| {
1130            for buffer in unnamed_buffers {
1131                tx.send(buffer).await.ok();
1132            }
1133
1134            let mut project_paths_rx = pin!(project_paths_rx);
1135            while let Some(project_paths) = project_paths_rx.next().await {
1136                let buffers = this.update(cx, |this, cx| {
1137                    project_paths
1138                        .into_iter()
1139                        .map(|project_path| this.open_buffer(project_path, cx))
1140                        .collect::<Vec<_>>()
1141                })?;
1142                for buffer_task in buffers {
1143                    if let Some(buffer) = buffer_task.await.log_err()
1144                        && tx.send(buffer).await.is_err()
1145                    {
1146                        return anyhow::Ok(());
1147                    }
1148                }
1149            }
1150            anyhow::Ok(())
1151        })
1152        .detach();
1153        rx
1154    }
1155
1156    fn on_buffer_event(
1157        &mut self,
1158        buffer: Entity<Buffer>,
1159        event: &BufferEvent,
1160        cx: &mut Context<Self>,
1161    ) {
1162        match event {
1163            BufferEvent::FileHandleChanged => {
1164                self.buffer_changed_file(buffer, cx);
1165            }
1166            BufferEvent::Reloaded => {
1167                let Some((downstream_client, project_id)) = self.downstream_client.as_ref() else {
1168                    return;
1169                };
1170                let buffer = buffer.read(cx);
1171                downstream_client
1172                    .send(proto::BufferReloaded {
1173                        project_id: *project_id,
1174                        buffer_id: buffer.remote_id().to_proto(),
1175                        version: serialize_version(&buffer.version()),
1176                        mtime: buffer.saved_mtime().map(|t| t.into()),
1177                        line_ending: serialize_line_ending(buffer.line_ending()) as i32,
1178                    })
1179                    .log_err();
1180            }
1181            BufferEvent::LanguageChanged => {}
1182            _ => {}
1183        }
1184    }
1185
1186    pub async fn handle_update_buffer(
1187        this: Entity<Self>,
1188        envelope: TypedEnvelope<proto::UpdateBuffer>,
1189        mut cx: AsyncApp,
1190    ) -> Result<proto::Ack> {
1191        let payload = envelope.payload;
1192        let buffer_id = BufferId::new(payload.buffer_id)?;
1193        let ops = payload
1194            .operations
1195            .into_iter()
1196            .map(language::proto::deserialize_operation)
1197            .collect::<Result<Vec<_>, _>>()?;
1198        this.update(&mut cx, |this, cx| {
1199            match this.opened_buffers.entry(buffer_id) {
1200                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
1201                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
1202                    OpenBuffer::Complete { buffer, .. } => {
1203                        if let Some(buffer) = buffer.upgrade() {
1204                            buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx));
1205                        }
1206                    }
1207                },
1208                hash_map::Entry::Vacant(e) => {
1209                    e.insert(OpenBuffer::Operations(ops));
1210                }
1211            }
1212            Ok(proto::Ack {})
1213        })?
1214    }
1215
1216    pub fn register_shared_lsp_handle(
1217        &mut self,
1218        peer_id: proto::PeerId,
1219        buffer_id: BufferId,
1220        handle: OpenLspBufferHandle,
1221    ) {
1222        if let Some(shared_buffers) = self.shared_buffers.get_mut(&peer_id)
1223            && let Some(buffer) = shared_buffers.get_mut(&buffer_id)
1224        {
1225            buffer.lsp_handle = Some(handle);
1226            return;
1227        }
1228        debug_panic!("tried to register shared lsp handle, but buffer was not shared")
1229    }
1230
1231    pub fn handle_synchronize_buffers(
1232        &mut self,
1233        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
1234        cx: &mut Context<Self>,
1235        client: Arc<Client>,
1236    ) -> Result<proto::SynchronizeBuffersResponse> {
1237        let project_id = envelope.payload.project_id;
1238        let mut response = proto::SynchronizeBuffersResponse {
1239            buffers: Default::default(),
1240        };
1241        let Some(guest_id) = envelope.original_sender_id else {
1242            anyhow::bail!("missing original_sender_id on SynchronizeBuffers request");
1243        };
1244
1245        self.shared_buffers.entry(guest_id).or_default().clear();
1246        for buffer in envelope.payload.buffers {
1247            let buffer_id = BufferId::new(buffer.id)?;
1248            let remote_version = language::proto::deserialize_version(&buffer.version);
1249            if let Some(buffer) = self.get(buffer_id) {
1250                self.shared_buffers
1251                    .entry(guest_id)
1252                    .or_default()
1253                    .entry(buffer_id)
1254                    .or_insert_with(|| SharedBuffer {
1255                        buffer: buffer.clone(),
1256                        lsp_handle: None,
1257                    });
1258
1259                let buffer = buffer.read(cx);
1260                response.buffers.push(proto::BufferVersion {
1261                    id: buffer_id.into(),
1262                    version: language::proto::serialize_version(&buffer.version),
1263                });
1264
1265                let operations = buffer.serialize_ops(Some(remote_version), cx);
1266                let client = client.clone();
1267                if let Some(file) = buffer.file() {
1268                    client
1269                        .send(proto::UpdateBufferFile {
1270                            project_id,
1271                            buffer_id: buffer_id.into(),
1272                            file: Some(file.to_proto(cx)),
1273                        })
1274                        .log_err();
1275                }
1276
1277                // TODO(max): do something
1278                // client
1279                //     .send(proto::UpdateStagedText {
1280                //         project_id,
1281                //         buffer_id: buffer_id.into(),
1282                //         diff_base: buffer.diff_base().map(ToString::to_string),
1283                //     })
1284                //     .log_err();
1285
1286                client
1287                    .send(proto::BufferReloaded {
1288                        project_id,
1289                        buffer_id: buffer_id.into(),
1290                        version: language::proto::serialize_version(buffer.saved_version()),
1291                        mtime: buffer.saved_mtime().map(|time| time.into()),
1292                        line_ending: language::proto::serialize_line_ending(buffer.line_ending())
1293                            as i32,
1294                    })
1295                    .log_err();
1296
1297                cx.background_spawn(
1298                    async move {
1299                        let operations = operations.await;
1300                        for chunk in split_operations(operations) {
1301                            client
1302                                .request(proto::UpdateBuffer {
1303                                    project_id,
1304                                    buffer_id: buffer_id.into(),
1305                                    operations: chunk,
1306                                })
1307                                .await?;
1308                        }
1309                        anyhow::Ok(())
1310                    }
1311                    .log_err(),
1312                )
1313                .detach();
1314            }
1315        }
1316        Ok(response)
1317    }
1318
1319    pub fn handle_create_buffer_for_peer(
1320        &mut self,
1321        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
1322        replica_id: ReplicaId,
1323        capability: Capability,
1324        cx: &mut Context<Self>,
1325    ) -> Result<()> {
1326        let remote = self
1327            .as_remote_mut()
1328            .context("buffer store is not a remote")?;
1329
1330        if let Some(buffer) =
1331            remote.handle_create_buffer_for_peer(envelope, replica_id, capability, cx)?
1332        {
1333            self.add_buffer(buffer, cx)?;
1334        }
1335
1336        Ok(())
1337    }
1338
1339    pub async fn handle_update_buffer_file(
1340        this: Entity<Self>,
1341        envelope: TypedEnvelope<proto::UpdateBufferFile>,
1342        mut cx: AsyncApp,
1343    ) -> Result<()> {
1344        let buffer_id = envelope.payload.buffer_id;
1345        let buffer_id = BufferId::new(buffer_id)?;
1346
1347        this.update(&mut cx, |this, cx| {
1348            let payload = envelope.payload.clone();
1349            if let Some(buffer) = this.get_possibly_incomplete(buffer_id) {
1350                let file = payload.file.context("invalid file")?;
1351                let worktree = this
1352                    .worktree_store
1353                    .read(cx)
1354                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
1355                    .context("no such worktree")?;
1356                let file = File::from_proto(file, worktree, cx)?;
1357                let old_file = buffer.update(cx, |buffer, cx| {
1358                    let old_file = buffer.file().cloned();
1359                    let new_path = file.path.clone();
1360
1361                    buffer.file_updated(Arc::new(file), cx);
1362                    if old_file.as_ref().is_none_or(|old| *old.path() != new_path) {
1363                        Some(old_file)
1364                    } else {
1365                        None
1366                    }
1367                });
1368                if let Some(old_file) = old_file {
1369                    cx.emit(BufferStoreEvent::BufferChangedFilePath { buffer, old_file });
1370                }
1371            }
1372            if let Some((downstream_client, project_id)) = this.downstream_client.as_ref() {
1373                downstream_client
1374                    .send(proto::UpdateBufferFile {
1375                        project_id: *project_id,
1376                        buffer_id: buffer_id.into(),
1377                        file: envelope.payload.file,
1378                    })
1379                    .log_err();
1380            }
1381            Ok(())
1382        })?
1383    }
1384
1385    pub async fn handle_save_buffer(
1386        this: Entity<Self>,
1387        envelope: TypedEnvelope<proto::SaveBuffer>,
1388        mut cx: AsyncApp,
1389    ) -> Result<proto::BufferSaved> {
1390        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1391        let (buffer, project_id) = this.read_with(&cx, |this, _| {
1392            anyhow::Ok((
1393                this.get_existing(buffer_id)?,
1394                this.downstream_client
1395                    .as_ref()
1396                    .map(|(_, project_id)| *project_id)
1397                    .context("project is not shared")?,
1398            ))
1399        })??;
1400        buffer
1401            .update(&mut cx, |buffer, _| {
1402                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
1403            })?
1404            .await?;
1405        let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id())?;
1406
1407        if let Some(new_path) = envelope.payload.new_path
1408            && let Some(new_path) = ProjectPath::from_proto(new_path)
1409        {
1410            this.update(&mut cx, |this, cx| {
1411                this.save_buffer_as(buffer.clone(), new_path, cx)
1412            })?
1413            .await?;
1414        } else {
1415            this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))?
1416                .await?;
1417        }
1418
1419        buffer.read_with(&cx, |buffer, _| proto::BufferSaved {
1420            project_id,
1421            buffer_id: buffer_id.into(),
1422            version: serialize_version(buffer.saved_version()),
1423            mtime: buffer.saved_mtime().map(|time| time.into()),
1424        })
1425    }
1426
1427    pub async fn handle_close_buffer(
1428        this: Entity<Self>,
1429        envelope: TypedEnvelope<proto::CloseBuffer>,
1430        mut cx: AsyncApp,
1431    ) -> Result<()> {
1432        let peer_id = envelope.sender_id;
1433        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1434        this.update(&mut cx, |this, cx| {
1435            if let Some(shared) = this.shared_buffers.get_mut(&peer_id)
1436                && shared.remove(&buffer_id).is_some()
1437            {
1438                cx.emit(BufferStoreEvent::SharedBufferClosed(peer_id, buffer_id));
1439                if shared.is_empty() {
1440                    this.shared_buffers.remove(&peer_id);
1441                }
1442                return;
1443            }
1444            debug_panic!(
1445                "peer_id {} closed buffer_id {} which was either not open or already closed",
1446                peer_id,
1447                buffer_id
1448            )
1449        })
1450    }
1451
1452    pub async fn handle_buffer_saved(
1453        this: Entity<Self>,
1454        envelope: TypedEnvelope<proto::BufferSaved>,
1455        mut cx: AsyncApp,
1456    ) -> Result<()> {
1457        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1458        let version = deserialize_version(&envelope.payload.version);
1459        let mtime = envelope.payload.mtime.clone().map(|time| time.into());
1460        this.update(&mut cx, move |this, cx| {
1461            if let Some(buffer) = this.get_possibly_incomplete(buffer_id) {
1462                buffer.update(cx, |buffer, cx| {
1463                    buffer.did_save(version, mtime, cx);
1464                });
1465            }
1466
1467            if let Some((downstream_client, project_id)) = this.downstream_client.as_ref() {
1468                downstream_client
1469                    .send(proto::BufferSaved {
1470                        project_id: *project_id,
1471                        buffer_id: buffer_id.into(),
1472                        mtime: envelope.payload.mtime,
1473                        version: envelope.payload.version,
1474                    })
1475                    .log_err();
1476            }
1477        })
1478    }
1479
1480    pub async fn handle_buffer_reloaded(
1481        this: Entity<Self>,
1482        envelope: TypedEnvelope<proto::BufferReloaded>,
1483        mut cx: AsyncApp,
1484    ) -> Result<()> {
1485        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1486        let version = deserialize_version(&envelope.payload.version);
1487        let mtime = envelope.payload.mtime.clone().map(|time| time.into());
1488        let line_ending = deserialize_line_ending(
1489            proto::LineEnding::from_i32(envelope.payload.line_ending)
1490                .context("missing line ending")?,
1491        );
1492        this.update(&mut cx, |this, cx| {
1493            if let Some(buffer) = this.get_possibly_incomplete(buffer_id) {
1494                buffer.update(cx, |buffer, cx| {
1495                    buffer.did_reload(version, line_ending, mtime, cx);
1496                });
1497            }
1498
1499            if let Some((downstream_client, project_id)) = this.downstream_client.as_ref() {
1500                downstream_client
1501                    .send(proto::BufferReloaded {
1502                        project_id: *project_id,
1503                        buffer_id: buffer_id.into(),
1504                        mtime: envelope.payload.mtime,
1505                        version: envelope.payload.version,
1506                        line_ending: envelope.payload.line_ending,
1507                    })
1508                    .log_err();
1509            }
1510        })
1511    }
1512
1513    pub fn reload_buffers(
1514        &self,
1515        buffers: HashSet<Entity<Buffer>>,
1516        push_to_history: bool,
1517        cx: &mut Context<Self>,
1518    ) -> Task<Result<ProjectTransaction>> {
1519        if buffers.is_empty() {
1520            return Task::ready(Ok(ProjectTransaction::default()));
1521        }
1522        match &self.state {
1523            BufferStoreState::Local(this) => this.reload_buffers(buffers, push_to_history, cx),
1524            BufferStoreState::Remote(this) => this.reload_buffers(buffers, push_to_history, cx),
1525        }
1526    }
1527
1528    async fn handle_reload_buffers(
1529        this: Entity<Self>,
1530        envelope: TypedEnvelope<proto::ReloadBuffers>,
1531        mut cx: AsyncApp,
1532    ) -> Result<proto::ReloadBuffersResponse> {
1533        let sender_id = envelope.original_sender_id().unwrap_or_default();
1534        let reload = this.update(&mut cx, |this, cx| {
1535            let mut buffers = HashSet::default();
1536            for buffer_id in &envelope.payload.buffer_ids {
1537                let buffer_id = BufferId::new(*buffer_id)?;
1538                buffers.insert(this.get_existing(buffer_id)?);
1539            }
1540            anyhow::Ok(this.reload_buffers(buffers, false, cx))
1541        })??;
1542
1543        let project_transaction = reload.await?;
1544        let project_transaction = this.update(&mut cx, |this, cx| {
1545            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
1546        })?;
1547        Ok(proto::ReloadBuffersResponse {
1548            transaction: Some(project_transaction),
1549        })
1550    }
1551
1552    pub fn create_buffer_for_peer(
1553        &mut self,
1554        buffer: &Entity<Buffer>,
1555        peer_id: proto::PeerId,
1556        cx: &mut Context<Self>,
1557    ) -> Task<Result<()>> {
1558        let buffer_id = buffer.read(cx).remote_id();
1559        let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
1560        if shared_buffers.contains_key(&buffer_id) {
1561            return Task::ready(Ok(()));
1562        }
1563        shared_buffers.insert(
1564            buffer_id,
1565            SharedBuffer {
1566                buffer: buffer.clone(),
1567                lsp_handle: None,
1568            },
1569        );
1570
1571        let Some((client, project_id)) = self.downstream_client.clone() else {
1572            return Task::ready(Ok(()));
1573        };
1574
1575        cx.spawn(async move |this, cx| {
1576            let Some(buffer) = this.read_with(cx, |this, _| this.get(buffer_id))? else {
1577                return anyhow::Ok(());
1578            };
1579
1580            let operations = buffer.update(cx, |b, cx| b.serialize_ops(None, cx))?;
1581            let operations = operations.await;
1582            let state = buffer.update(cx, |buffer, cx| buffer.to_proto(cx))?;
1583
1584            let initial_state = proto::CreateBufferForPeer {
1585                project_id,
1586                peer_id: Some(peer_id),
1587                variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
1588            };
1589
1590            if client.send(initial_state).log_err().is_some() {
1591                let client = client.clone();
1592                cx.background_spawn(async move {
1593                    let mut chunks = split_operations(operations).peekable();
1594                    while let Some(chunk) = chunks.next() {
1595                        let is_last = chunks.peek().is_none();
1596                        client.send(proto::CreateBufferForPeer {
1597                            project_id,
1598                            peer_id: Some(peer_id),
1599                            variant: Some(proto::create_buffer_for_peer::Variant::Chunk(
1600                                proto::BufferChunk {
1601                                    buffer_id: buffer_id.into(),
1602                                    operations: chunk,
1603                                    is_last,
1604                                },
1605                            )),
1606                        })?;
1607                    }
1608                    anyhow::Ok(())
1609                })
1610                .await
1611                .log_err();
1612            }
1613            Ok(())
1614        })
1615    }
1616
1617    pub fn forget_shared_buffers(&mut self) {
1618        self.shared_buffers.clear();
1619    }
1620
1621    pub fn forget_shared_buffers_for(&mut self, peer_id: &proto::PeerId) {
1622        self.shared_buffers.remove(peer_id);
1623    }
1624
1625    pub fn update_peer_id(&mut self, old_peer_id: &proto::PeerId, new_peer_id: proto::PeerId) {
1626        if let Some(buffers) = self.shared_buffers.remove(old_peer_id) {
1627            self.shared_buffers.insert(new_peer_id, buffers);
1628        }
1629    }
1630
1631    pub fn has_shared_buffers(&self) -> bool {
1632        !self.shared_buffers.is_empty()
1633    }
1634
1635    pub fn create_local_buffer(
1636        &mut self,
1637        text: &str,
1638        language: Option<Arc<Language>>,
1639        project_searchable: bool,
1640        cx: &mut Context<Self>,
1641    ) -> Entity<Buffer> {
1642        let buffer = cx.new(|cx| {
1643            Buffer::local(text, cx)
1644                .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
1645        });
1646
1647        self.add_buffer(buffer.clone(), cx).log_err();
1648        let buffer_id = buffer.read(cx).remote_id();
1649        if !project_searchable {
1650            self.non_searchable_buffers.insert(buffer_id);
1651        }
1652
1653        if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
1654            self.path_to_buffer_id.insert(
1655                ProjectPath {
1656                    worktree_id: file.worktree_id(cx),
1657                    path: file.path.clone(),
1658                },
1659                buffer_id,
1660            );
1661            let this = self
1662                .as_local_mut()
1663                .expect("local-only method called in a non-local context");
1664            if let Some(entry_id) = file.entry_id {
1665                this.local_buffer_ids_by_entry_id
1666                    .insert(entry_id, buffer_id);
1667            }
1668        }
1669        buffer
1670    }
1671
1672    pub fn deserialize_project_transaction(
1673        &mut self,
1674        message: proto::ProjectTransaction,
1675        push_to_history: bool,
1676        cx: &mut Context<Self>,
1677    ) -> Task<Result<ProjectTransaction>> {
1678        if let Some(this) = self.as_remote_mut() {
1679            this.deserialize_project_transaction(message, push_to_history, cx)
1680        } else {
1681            debug_panic!("not a remote buffer store");
1682            Task::ready(Err(anyhow!("not a remote buffer store")))
1683        }
1684    }
1685
1686    pub fn wait_for_remote_buffer(
1687        &mut self,
1688        id: BufferId,
1689        cx: &mut Context<BufferStore>,
1690    ) -> Task<Result<Entity<Buffer>>> {
1691        if let Some(this) = self.as_remote_mut() {
1692            this.wait_for_remote_buffer(id, cx)
1693        } else {
1694            debug_panic!("not a remote buffer store");
1695            Task::ready(Err(anyhow!("not a remote buffer store")))
1696        }
1697    }
1698
1699    pub fn serialize_project_transaction_for_peer(
1700        &mut self,
1701        project_transaction: ProjectTransaction,
1702        peer_id: proto::PeerId,
1703        cx: &mut Context<Self>,
1704    ) -> proto::ProjectTransaction {
1705        let mut serialized_transaction = proto::ProjectTransaction {
1706            buffer_ids: Default::default(),
1707            transactions: Default::default(),
1708        };
1709        for (buffer, transaction) in project_transaction.0 {
1710            self.create_buffer_for_peer(&buffer, peer_id, cx)
1711                .detach_and_log_err(cx);
1712            serialized_transaction
1713                .buffer_ids
1714                .push(buffer.read(cx).remote_id().into());
1715            serialized_transaction
1716                .transactions
1717                .push(language::proto::serialize_transaction(&transaction));
1718        }
1719        serialized_transaction
1720    }
1721}
1722
1723impl OpenBuffer {
1724    fn upgrade(&self) -> Option<Entity<Buffer>> {
1725        match self {
1726            OpenBuffer::Complete { buffer, .. } => buffer.upgrade(),
1727            OpenBuffer::Operations(_) => None,
1728        }
1729    }
1730}
1731
1732fn is_not_found_error(error: &anyhow::Error) -> bool {
1733    error
1734        .root_cause()
1735        .downcast_ref::<io::Error>()
1736        .is_some_and(|err| err.kind() == io::ErrorKind::NotFound)
1737}