rpc.rs

   1mod connection_pool;
   2
   3use crate::api::billing::find_or_create_billing_customer;
   4use crate::api::{CloudflareIpCountryHeader, SystemIdHeader};
   5use crate::db::billing_subscription::SubscriptionKind;
   6use crate::llm::db::LlmDatabase;
   7use crate::llm::{
   8    AGENT_EXTENDED_TRIAL_FEATURE_FLAG, BYPASS_ACCOUNT_AGE_CHECK_FEATURE_FLAG, LlmTokenClaims,
   9    MIN_ACCOUNT_AGE_FOR_LLM_USE,
  10};
  11use crate::stripe_client::StripeCustomerId;
  12use crate::{
  13    AppState, Error, Result, auth,
  14    db::{
  15        self, BufferId, Capability, Channel, ChannelId, ChannelRole, ChannelsForUser,
  16        CreatedChannelMessage, Database, InviteMemberResult, MembershipUpdated, MessageId,
  17        NotificationId, ProjectId, RejoinedProject, RemoveChannelMemberResult,
  18        RespondToChannelInvite, RoomId, ServerId, UpdatedChannelMessage, User, UserId,
  19    },
  20    executor::Executor,
  21};
  22use anyhow::{Context as _, anyhow, bail};
  23use async_tungstenite::tungstenite::{
  24    Message as TungsteniteMessage, protocol::CloseFrame as TungsteniteCloseFrame,
  25};
  26use axum::{
  27    Extension, Router, TypedHeader,
  28    body::Body,
  29    extract::{
  30        ConnectInfo, WebSocketUpgrade,
  31        ws::{CloseFrame as AxumCloseFrame, Message as AxumMessage},
  32    },
  33    headers::{Header, HeaderName},
  34    http::StatusCode,
  35    middleware,
  36    response::IntoResponse,
  37    routing::get,
  38};
  39use chrono::Utc;
  40use collections::{HashMap, HashSet};
  41pub use connection_pool::{ConnectionPool, ZedVersion};
  42use core::fmt::{self, Debug, Formatter};
  43use reqwest_client::ReqwestClient;
  44use rpc::proto::split_repository_update;
  45use supermaven_api::{CreateExternalUserRequest, SupermavenAdminApi};
  46
  47use futures::{
  48    FutureExt, SinkExt, StreamExt, TryStreamExt, channel::oneshot, future::BoxFuture,
  49    stream::FuturesUnordered,
  50};
  51use prometheus::{IntGauge, register_int_gauge};
  52use rpc::{
  53    Connection, ConnectionId, ErrorCode, ErrorCodeExt, ErrorExt, Peer, Receipt, TypedEnvelope,
  54    proto::{
  55        self, Ack, AnyTypedEnvelope, EntityMessage, EnvelopedMessage, LiveKitConnectionInfo,
  56        RequestMessage, ShareProject, UpdateChannelBufferCollaborators,
  57    },
  58};
  59use semantic_version::SemanticVersion;
  60use serde::{Serialize, Serializer};
  61use std::{
  62    any::TypeId,
  63    future::Future,
  64    marker::PhantomData,
  65    mem,
  66    net::SocketAddr,
  67    ops::{Deref, DerefMut},
  68    rc::Rc,
  69    sync::{
  70        Arc, OnceLock,
  71        atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
  72    },
  73    time::{Duration, Instant},
  74};
  75use time::OffsetDateTime;
  76use tokio::sync::{Semaphore, watch};
  77use tower::ServiceBuilder;
  78use tracing::{
  79    Instrument,
  80    field::{self},
  81    info_span, instrument,
  82};
  83
  84pub const RECONNECT_TIMEOUT: Duration = Duration::from_secs(30);
  85
  86// kubernetes gives terminated pods 10s to shutdown gracefully. After they're gone, we can clean up old resources.
  87pub const CLEANUP_TIMEOUT: Duration = Duration::from_secs(15);
  88
  89const MESSAGE_COUNT_PER_PAGE: usize = 100;
  90const MAX_MESSAGE_LEN: usize = 1024;
  91const NOTIFICATION_COUNT_PER_PAGE: usize = 50;
  92const MAX_CONCURRENT_CONNECTIONS: usize = 512;
  93
  94static CONCURRENT_CONNECTIONS: AtomicUsize = AtomicUsize::new(0);
  95
  96type MessageHandler =
  97    Box<dyn Send + Sync + Fn(Box<dyn AnyTypedEnvelope>, Session) -> BoxFuture<'static, ()>>;
  98
  99pub struct ConnectionGuard;
 100
 101impl ConnectionGuard {
 102    pub fn try_acquire() -> Result<Self, ()> {
 103        let current_connections = CONCURRENT_CONNECTIONS.fetch_add(1, SeqCst);
 104        if current_connections >= MAX_CONCURRENT_CONNECTIONS {
 105            CONCURRENT_CONNECTIONS.fetch_sub(1, SeqCst);
 106            tracing::error!(
 107                "too many concurrent connections: {}",
 108                current_connections + 1
 109            );
 110            return Err(());
 111        }
 112        Ok(ConnectionGuard)
 113    }
 114}
 115
 116impl Drop for ConnectionGuard {
 117    fn drop(&mut self) {
 118        CONCURRENT_CONNECTIONS.fetch_sub(1, SeqCst);
 119    }
 120}
 121
 122struct Response<R> {
 123    peer: Arc<Peer>,
 124    receipt: Receipt<R>,
 125    responded: Arc<AtomicBool>,
 126}
 127
 128impl<R: RequestMessage> Response<R> {
 129    fn send(self, payload: R::Response) -> Result<()> {
 130        self.responded.store(true, SeqCst);
 131        self.peer.respond(self.receipt, payload)?;
 132        Ok(())
 133    }
 134}
 135
 136#[derive(Clone, Debug)]
 137pub enum Principal {
 138    User(User),
 139    Impersonated { user: User, admin: User },
 140}
 141
 142impl Principal {
 143    fn user(&self) -> &User {
 144        match self {
 145            Principal::User(user) => user,
 146            Principal::Impersonated { user, .. } => user,
 147        }
 148    }
 149
 150    fn update_span(&self, span: &tracing::Span) {
 151        match &self {
 152            Principal::User(user) => {
 153                span.record("user_id", user.id.0);
 154                span.record("login", &user.github_login);
 155            }
 156            Principal::Impersonated { user, admin } => {
 157                span.record("user_id", user.id.0);
 158                span.record("login", &user.github_login);
 159                span.record("impersonator", &admin.github_login);
 160            }
 161        }
 162    }
 163}
 164
 165#[derive(Clone)]
 166struct Session {
 167    principal: Principal,
 168    connection_id: ConnectionId,
 169    db: Arc<tokio::sync::Mutex<DbHandle>>,
 170    peer: Arc<Peer>,
 171    connection_pool: Arc<parking_lot::Mutex<ConnectionPool>>,
 172    app_state: Arc<AppState>,
 173    supermaven_client: Option<Arc<SupermavenAdminApi>>,
 174    /// The GeoIP country code for the user.
 175    #[allow(unused)]
 176    geoip_country_code: Option<String>,
 177    system_id: Option<String>,
 178    _executor: Executor,
 179}
 180
 181impl Session {
 182    async fn db(&self) -> tokio::sync::MutexGuard<DbHandle> {
 183        #[cfg(test)]
 184        tokio::task::yield_now().await;
 185        let guard = self.db.lock().await;
 186        #[cfg(test)]
 187        tokio::task::yield_now().await;
 188        guard
 189    }
 190
 191    async fn connection_pool(&self) -> ConnectionPoolGuard<'_> {
 192        #[cfg(test)]
 193        tokio::task::yield_now().await;
 194        let guard = self.connection_pool.lock();
 195        ConnectionPoolGuard {
 196            guard,
 197            _not_send: PhantomData,
 198        }
 199    }
 200
 201    fn is_staff(&self) -> bool {
 202        match &self.principal {
 203            Principal::User(user) => user.admin,
 204            Principal::Impersonated { .. } => true,
 205        }
 206    }
 207
 208    fn user_id(&self) -> UserId {
 209        match &self.principal {
 210            Principal::User(user) => user.id,
 211            Principal::Impersonated { user, .. } => user.id,
 212        }
 213    }
 214
 215    pub fn email(&self) -> Option<String> {
 216        match &self.principal {
 217            Principal::User(user) => user.email_address.clone(),
 218            Principal::Impersonated { user, .. } => user.email_address.clone(),
 219        }
 220    }
 221}
 222
 223impl Debug for Session {
 224    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
 225        let mut result = f.debug_struct("Session");
 226        match &self.principal {
 227            Principal::User(user) => {
 228                result.field("user", &user.github_login);
 229            }
 230            Principal::Impersonated { user, admin } => {
 231                result.field("user", &user.github_login);
 232                result.field("impersonator", &admin.github_login);
 233            }
 234        }
 235        result.field("connection_id", &self.connection_id).finish()
 236    }
 237}
 238
 239struct DbHandle(Arc<Database>);
 240
 241impl Deref for DbHandle {
 242    type Target = Database;
 243
 244    fn deref(&self) -> &Self::Target {
 245        self.0.as_ref()
 246    }
 247}
 248
 249pub struct Server {
 250    id: parking_lot::Mutex<ServerId>,
 251    peer: Arc<Peer>,
 252    pub(crate) connection_pool: Arc<parking_lot::Mutex<ConnectionPool>>,
 253    app_state: Arc<AppState>,
 254    handlers: HashMap<TypeId, MessageHandler>,
 255    teardown: watch::Sender<bool>,
 256}
 257
 258pub(crate) struct ConnectionPoolGuard<'a> {
 259    guard: parking_lot::MutexGuard<'a, ConnectionPool>,
 260    _not_send: PhantomData<Rc<()>>,
 261}
 262
 263#[derive(Serialize)]
 264pub struct ServerSnapshot<'a> {
 265    peer: &'a Peer,
 266    #[serde(serialize_with = "serialize_deref")]
 267    connection_pool: ConnectionPoolGuard<'a>,
 268}
 269
 270pub fn serialize_deref<S, T, U>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
 271where
 272    S: Serializer,
 273    T: Deref<Target = U>,
 274    U: Serialize,
 275{
 276    Serialize::serialize(value.deref(), serializer)
 277}
 278
 279impl Server {
 280    pub fn new(id: ServerId, app_state: Arc<AppState>) -> Arc<Self> {
 281        let mut server = Self {
 282            id: parking_lot::Mutex::new(id),
 283            peer: Peer::new(id.0 as u32),
 284            app_state: app_state.clone(),
 285            connection_pool: Default::default(),
 286            handlers: Default::default(),
 287            teardown: watch::channel(false).0,
 288        };
 289
 290        server
 291            .add_request_handler(ping)
 292            .add_request_handler(create_room)
 293            .add_request_handler(join_room)
 294            .add_request_handler(rejoin_room)
 295            .add_request_handler(leave_room)
 296            .add_request_handler(set_room_participant_role)
 297            .add_request_handler(call)
 298            .add_request_handler(cancel_call)
 299            .add_message_handler(decline_call)
 300            .add_request_handler(update_participant_location)
 301            .add_request_handler(share_project)
 302            .add_message_handler(unshare_project)
 303            .add_request_handler(join_project)
 304            .add_message_handler(leave_project)
 305            .add_request_handler(update_project)
 306            .add_request_handler(update_worktree)
 307            .add_request_handler(update_repository)
 308            .add_request_handler(remove_repository)
 309            .add_message_handler(start_language_server)
 310            .add_message_handler(update_language_server)
 311            .add_message_handler(update_diagnostic_summary)
 312            .add_message_handler(update_worktree_settings)
 313            .add_request_handler(forward_read_only_project_request::<proto::GetHover>)
 314            .add_request_handler(forward_read_only_project_request::<proto::GetDefinition>)
 315            .add_request_handler(forward_read_only_project_request::<proto::GetTypeDefinition>)
 316            .add_request_handler(forward_read_only_project_request::<proto::GetReferences>)
 317            .add_request_handler(forward_find_search_candidates_request)
 318            .add_request_handler(forward_read_only_project_request::<proto::GetDocumentHighlights>)
 319            .add_request_handler(forward_read_only_project_request::<proto::GetDocumentSymbols>)
 320            .add_request_handler(forward_read_only_project_request::<proto::GetProjectSymbols>)
 321            .add_request_handler(forward_read_only_project_request::<proto::OpenBufferForSymbol>)
 322            .add_request_handler(forward_read_only_project_request::<proto::OpenBufferById>)
 323            .add_request_handler(forward_read_only_project_request::<proto::SynchronizeBuffers>)
 324            .add_request_handler(forward_read_only_project_request::<proto::InlayHints>)
 325            .add_request_handler(forward_read_only_project_request::<proto::ResolveInlayHint>)
 326            .add_request_handler(forward_read_only_project_request::<proto::GetColorPresentation>)
 327            .add_request_handler(forward_mutating_project_request::<proto::GetCodeLens>)
 328            .add_request_handler(forward_read_only_project_request::<proto::OpenBufferByPath>)
 329            .add_request_handler(forward_read_only_project_request::<proto::GitGetBranches>)
 330            .add_request_handler(forward_read_only_project_request::<proto::OpenUnstagedDiff>)
 331            .add_request_handler(forward_read_only_project_request::<proto::OpenUncommittedDiff>)
 332            .add_request_handler(forward_read_only_project_request::<proto::LspExtExpandMacro>)
 333            .add_request_handler(forward_read_only_project_request::<proto::LspExtOpenDocs>)
 334            .add_request_handler(forward_mutating_project_request::<proto::LspExtRunnables>)
 335            .add_request_handler(
 336                forward_read_only_project_request::<proto::LspExtSwitchSourceHeader>,
 337            )
 338            .add_request_handler(forward_read_only_project_request::<proto::LspExtGoToParentModule>)
 339            .add_request_handler(forward_read_only_project_request::<proto::LspExtCancelFlycheck>)
 340            .add_request_handler(forward_read_only_project_request::<proto::LspExtRunFlycheck>)
 341            .add_request_handler(forward_read_only_project_request::<proto::LspExtClearFlycheck>)
 342            .add_request_handler(
 343                forward_read_only_project_request::<proto::LanguageServerIdForName>,
 344            )
 345            .add_request_handler(forward_read_only_project_request::<proto::GetDocumentDiagnostics>)
 346            .add_request_handler(
 347                forward_mutating_project_request::<proto::RegisterBufferWithLanguageServers>,
 348            )
 349            .add_request_handler(forward_mutating_project_request::<proto::UpdateGitBranch>)
 350            .add_request_handler(forward_mutating_project_request::<proto::GetCompletions>)
 351            .add_request_handler(
 352                forward_mutating_project_request::<proto::ApplyCompletionAdditionalEdits>,
 353            )
 354            .add_request_handler(forward_mutating_project_request::<proto::OpenNewBuffer>)
 355            .add_request_handler(
 356                forward_mutating_project_request::<proto::ResolveCompletionDocumentation>,
 357            )
 358            .add_request_handler(forward_mutating_project_request::<proto::GetCodeActions>)
 359            .add_request_handler(forward_mutating_project_request::<proto::ApplyCodeAction>)
 360            .add_request_handler(forward_mutating_project_request::<proto::PrepareRename>)
 361            .add_request_handler(forward_mutating_project_request::<proto::PerformRename>)
 362            .add_request_handler(forward_mutating_project_request::<proto::ReloadBuffers>)
 363            .add_request_handler(forward_mutating_project_request::<proto::ApplyCodeActionKind>)
 364            .add_request_handler(forward_mutating_project_request::<proto::FormatBuffers>)
 365            .add_request_handler(forward_mutating_project_request::<proto::CreateProjectEntry>)
 366            .add_request_handler(forward_mutating_project_request::<proto::RenameProjectEntry>)
 367            .add_request_handler(forward_mutating_project_request::<proto::CopyProjectEntry>)
 368            .add_request_handler(forward_mutating_project_request::<proto::DeleteProjectEntry>)
 369            .add_request_handler(forward_mutating_project_request::<proto::ExpandProjectEntry>)
 370            .add_request_handler(
 371                forward_mutating_project_request::<proto::ExpandAllForProjectEntry>,
 372            )
 373            .add_request_handler(forward_mutating_project_request::<proto::OnTypeFormatting>)
 374            .add_request_handler(forward_mutating_project_request::<proto::SaveBuffer>)
 375            .add_request_handler(forward_mutating_project_request::<proto::BlameBuffer>)
 376            .add_request_handler(forward_mutating_project_request::<proto::MultiLspQuery>)
 377            .add_request_handler(forward_mutating_project_request::<proto::RestartLanguageServers>)
 378            .add_request_handler(forward_mutating_project_request::<proto::StopLanguageServers>)
 379            .add_request_handler(forward_mutating_project_request::<proto::LinkedEditingRange>)
 380            .add_message_handler(create_buffer_for_peer)
 381            .add_request_handler(update_buffer)
 382            .add_message_handler(broadcast_project_message_from_host::<proto::RefreshInlayHints>)
 383            .add_message_handler(broadcast_project_message_from_host::<proto::RefreshCodeLens>)
 384            .add_message_handler(broadcast_project_message_from_host::<proto::UpdateBufferFile>)
 385            .add_message_handler(broadcast_project_message_from_host::<proto::BufferReloaded>)
 386            .add_message_handler(broadcast_project_message_from_host::<proto::BufferSaved>)
 387            .add_message_handler(broadcast_project_message_from_host::<proto::UpdateDiffBases>)
 388            .add_message_handler(
 389                broadcast_project_message_from_host::<proto::PullWorkspaceDiagnostics>,
 390            )
 391            .add_request_handler(get_users)
 392            .add_request_handler(fuzzy_search_users)
 393            .add_request_handler(request_contact)
 394            .add_request_handler(remove_contact)
 395            .add_request_handler(respond_to_contact_request)
 396            .add_message_handler(subscribe_to_channels)
 397            .add_request_handler(create_channel)
 398            .add_request_handler(delete_channel)
 399            .add_request_handler(invite_channel_member)
 400            .add_request_handler(remove_channel_member)
 401            .add_request_handler(set_channel_member_role)
 402            .add_request_handler(set_channel_visibility)
 403            .add_request_handler(rename_channel)
 404            .add_request_handler(join_channel_buffer)
 405            .add_request_handler(leave_channel_buffer)
 406            .add_message_handler(update_channel_buffer)
 407            .add_request_handler(rejoin_channel_buffers)
 408            .add_request_handler(get_channel_members)
 409            .add_request_handler(respond_to_channel_invite)
 410            .add_request_handler(join_channel)
 411            .add_request_handler(join_channel_chat)
 412            .add_message_handler(leave_channel_chat)
 413            .add_request_handler(send_channel_message)
 414            .add_request_handler(remove_channel_message)
 415            .add_request_handler(update_channel_message)
 416            .add_request_handler(get_channel_messages)
 417            .add_request_handler(get_channel_messages_by_id)
 418            .add_request_handler(get_notifications)
 419            .add_request_handler(mark_notification_as_read)
 420            .add_request_handler(move_channel)
 421            .add_request_handler(reorder_channel)
 422            .add_request_handler(follow)
 423            .add_message_handler(unfollow)
 424            .add_message_handler(update_followers)
 425            .add_request_handler(get_private_user_info)
 426            .add_request_handler(get_llm_api_token)
 427            .add_request_handler(accept_terms_of_service)
 428            .add_message_handler(acknowledge_channel_message)
 429            .add_message_handler(acknowledge_buffer_version)
 430            .add_request_handler(get_supermaven_api_key)
 431            .add_request_handler(forward_mutating_project_request::<proto::OpenContext>)
 432            .add_request_handler(forward_mutating_project_request::<proto::CreateContext>)
 433            .add_request_handler(forward_mutating_project_request::<proto::SynchronizeContexts>)
 434            .add_request_handler(forward_mutating_project_request::<proto::Stage>)
 435            .add_request_handler(forward_mutating_project_request::<proto::Unstage>)
 436            .add_request_handler(forward_mutating_project_request::<proto::Commit>)
 437            .add_request_handler(forward_mutating_project_request::<proto::GitInit>)
 438            .add_request_handler(forward_read_only_project_request::<proto::GetRemotes>)
 439            .add_request_handler(forward_read_only_project_request::<proto::GitShow>)
 440            .add_request_handler(forward_read_only_project_request::<proto::LoadCommitDiff>)
 441            .add_request_handler(forward_read_only_project_request::<proto::GitReset>)
 442            .add_request_handler(forward_read_only_project_request::<proto::GitCheckoutFiles>)
 443            .add_request_handler(forward_mutating_project_request::<proto::SetIndexText>)
 444            .add_request_handler(forward_mutating_project_request::<proto::ToggleBreakpoint>)
 445            .add_message_handler(broadcast_project_message_from_host::<proto::BreakpointsForFile>)
 446            .add_request_handler(forward_mutating_project_request::<proto::OpenCommitMessageBuffer>)
 447            .add_request_handler(forward_mutating_project_request::<proto::GitDiff>)
 448            .add_request_handler(forward_mutating_project_request::<proto::GitCreateBranch>)
 449            .add_request_handler(forward_mutating_project_request::<proto::GitChangeBranch>)
 450            .add_request_handler(forward_mutating_project_request::<proto::CheckForPushedCommits>)
 451            .add_message_handler(broadcast_project_message_from_host::<proto::AdvertiseContexts>)
 452            .add_message_handler(update_context);
 453
 454        Arc::new(server)
 455    }
 456
 457    pub async fn start(&self) -> Result<()> {
 458        let server_id = *self.id.lock();
 459        let app_state = self.app_state.clone();
 460        let peer = self.peer.clone();
 461        let timeout = self.app_state.executor.sleep(CLEANUP_TIMEOUT);
 462        let pool = self.connection_pool.clone();
 463        let livekit_client = self.app_state.livekit_client.clone();
 464
 465        let span = info_span!("start server");
 466        self.app_state.executor.spawn_detached(
 467            async move {
 468                tracing::info!("waiting for cleanup timeout");
 469                timeout.await;
 470                tracing::info!("cleanup timeout expired, retrieving stale rooms");
 471
 472                app_state
 473                    .db
 474                    .delete_stale_channel_chat_participants(
 475                        &app_state.config.zed_environment,
 476                        server_id,
 477                    )
 478                    .await
 479                    .trace_err();
 480
 481                if let Some((room_ids, channel_ids)) = app_state
 482                    .db
 483                    .stale_server_resource_ids(&app_state.config.zed_environment, server_id)
 484                    .await
 485                    .trace_err()
 486                {
 487                    tracing::info!(stale_room_count = room_ids.len(), "retrieved stale rooms");
 488                    tracing::info!(
 489                        stale_channel_buffer_count = channel_ids.len(),
 490                        "retrieved stale channel buffers"
 491                    );
 492
 493                    for channel_id in channel_ids {
 494                        if let Some(refreshed_channel_buffer) = app_state
 495                            .db
 496                            .clear_stale_channel_buffer_collaborators(channel_id, server_id)
 497                            .await
 498                            .trace_err()
 499                        {
 500                            for connection_id in refreshed_channel_buffer.connection_ids {
 501                                peer.send(
 502                                    connection_id,
 503                                    proto::UpdateChannelBufferCollaborators {
 504                                        channel_id: channel_id.to_proto(),
 505                                        collaborators: refreshed_channel_buffer
 506                                            .collaborators
 507                                            .clone(),
 508                                    },
 509                                )
 510                                .trace_err();
 511                            }
 512                        }
 513                    }
 514
 515                    for room_id in room_ids {
 516                        let mut contacts_to_update = HashSet::default();
 517                        let mut canceled_calls_to_user_ids = Vec::new();
 518                        let mut livekit_room = String::new();
 519                        let mut delete_livekit_room = false;
 520
 521                        if let Some(mut refreshed_room) = app_state
 522                            .db
 523                            .clear_stale_room_participants(room_id, server_id)
 524                            .await
 525                            .trace_err()
 526                        {
 527                            tracing::info!(
 528                                room_id = room_id.0,
 529                                new_participant_count = refreshed_room.room.participants.len(),
 530                                "refreshed room"
 531                            );
 532                            room_updated(&refreshed_room.room, &peer);
 533                            if let Some(channel) = refreshed_room.channel.as_ref() {
 534                                channel_updated(channel, &refreshed_room.room, &peer, &pool.lock());
 535                            }
 536                            contacts_to_update
 537                                .extend(refreshed_room.stale_participant_user_ids.iter().copied());
 538                            contacts_to_update
 539                                .extend(refreshed_room.canceled_calls_to_user_ids.iter().copied());
 540                            canceled_calls_to_user_ids =
 541                                mem::take(&mut refreshed_room.canceled_calls_to_user_ids);
 542                            livekit_room = mem::take(&mut refreshed_room.room.livekit_room);
 543                            delete_livekit_room = refreshed_room.room.participants.is_empty();
 544                        }
 545
 546                        {
 547                            let pool = pool.lock();
 548                            for canceled_user_id in canceled_calls_to_user_ids {
 549                                for connection_id in pool.user_connection_ids(canceled_user_id) {
 550                                    peer.send(
 551                                        connection_id,
 552                                        proto::CallCanceled {
 553                                            room_id: room_id.to_proto(),
 554                                        },
 555                                    )
 556                                    .trace_err();
 557                                }
 558                            }
 559                        }
 560
 561                        for user_id in contacts_to_update {
 562                            let busy = app_state.db.is_user_busy(user_id).await.trace_err();
 563                            let contacts = app_state.db.get_contacts(user_id).await.trace_err();
 564                            if let Some((busy, contacts)) = busy.zip(contacts) {
 565                                let pool = pool.lock();
 566                                let updated_contact = contact_for_user(user_id, busy, &pool);
 567                                for contact in contacts {
 568                                    if let db::Contact::Accepted {
 569                                        user_id: contact_user_id,
 570                                        ..
 571                                    } = contact
 572                                    {
 573                                        for contact_conn_id in
 574                                            pool.user_connection_ids(contact_user_id)
 575                                        {
 576                                            peer.send(
 577                                                contact_conn_id,
 578                                                proto::UpdateContacts {
 579                                                    contacts: vec![updated_contact.clone()],
 580                                                    remove_contacts: Default::default(),
 581                                                    incoming_requests: Default::default(),
 582                                                    remove_incoming_requests: Default::default(),
 583                                                    outgoing_requests: Default::default(),
 584                                                    remove_outgoing_requests: Default::default(),
 585                                                },
 586                                            )
 587                                            .trace_err();
 588                                        }
 589                                    }
 590                                }
 591                            }
 592                        }
 593
 594                        if let Some(live_kit) = livekit_client.as_ref() {
 595                            if delete_livekit_room {
 596                                live_kit.delete_room(livekit_room).await.trace_err();
 597                            }
 598                        }
 599                    }
 600                }
 601
 602                app_state
 603                    .db
 604                    .delete_stale_channel_chat_participants(
 605                        &app_state.config.zed_environment,
 606                        server_id,
 607                    )
 608                    .await
 609                    .trace_err();
 610
 611                app_state
 612                    .db
 613                    .clear_old_worktree_entries(server_id)
 614                    .await
 615                    .trace_err();
 616
 617                app_state
 618                    .db
 619                    .delete_stale_servers(&app_state.config.zed_environment, server_id)
 620                    .await
 621                    .trace_err();
 622            }
 623            .instrument(span),
 624        );
 625        Ok(())
 626    }
 627
 628    pub fn teardown(&self) {
 629        self.peer.teardown();
 630        self.connection_pool.lock().reset();
 631        let _ = self.teardown.send(true);
 632    }
 633
 634    #[cfg(test)]
 635    pub fn reset(&self, id: ServerId) {
 636        self.teardown();
 637        *self.id.lock() = id;
 638        self.peer.reset(id.0 as u32);
 639        let _ = self.teardown.send(false);
 640    }
 641
 642    #[cfg(test)]
 643    pub fn id(&self) -> ServerId {
 644        *self.id.lock()
 645    }
 646
 647    fn add_handler<F, Fut, M>(&mut self, handler: F) -> &mut Self
 648    where
 649        F: 'static + Send + Sync + Fn(TypedEnvelope<M>, Session) -> Fut,
 650        Fut: 'static + Send + Future<Output = Result<()>>,
 651        M: EnvelopedMessage,
 652    {
 653        let prev_handler = self.handlers.insert(
 654            TypeId::of::<M>(),
 655            Box::new(move |envelope, session| {
 656                let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
 657                let received_at = envelope.received_at;
 658                tracing::info!("message received");
 659                let start_time = Instant::now();
 660                let future = (handler)(*envelope, session);
 661                async move {
 662                    let result = future.await;
 663                    let total_duration_ms = received_at.elapsed().as_micros() as f64 / 1000.0;
 664                    let processing_duration_ms = start_time.elapsed().as_micros() as f64 / 1000.0;
 665                    let queue_duration_ms = total_duration_ms - processing_duration_ms;
 666                    let payload_type = M::NAME;
 667
 668                    match result {
 669                        Err(error) => {
 670                            tracing::error!(
 671                                ?error,
 672                                total_duration_ms,
 673                                processing_duration_ms,
 674                                queue_duration_ms,
 675                                payload_type,
 676                                "error handling message"
 677                            )
 678                        }
 679                        Ok(()) => tracing::info!(
 680                            total_duration_ms,
 681                            processing_duration_ms,
 682                            queue_duration_ms,
 683                            "finished handling message"
 684                        ),
 685                    }
 686                }
 687                .boxed()
 688            }),
 689        );
 690        if prev_handler.is_some() {
 691            panic!("registered a handler for the same message twice");
 692        }
 693        self
 694    }
 695
 696    fn add_message_handler<F, Fut, M>(&mut self, handler: F) -> &mut Self
 697    where
 698        F: 'static + Send + Sync + Fn(M, Session) -> Fut,
 699        Fut: 'static + Send + Future<Output = Result<()>>,
 700        M: EnvelopedMessage,
 701    {
 702        self.add_handler(move |envelope, session| handler(envelope.payload, session));
 703        self
 704    }
 705
 706    fn add_request_handler<F, Fut, M>(&mut self, handler: F) -> &mut Self
 707    where
 708        F: 'static + Send + Sync + Fn(M, Response<M>, Session) -> Fut,
 709        Fut: Send + Future<Output = Result<()>>,
 710        M: RequestMessage,
 711    {
 712        let handler = Arc::new(handler);
 713        self.add_handler(move |envelope, session| {
 714            let receipt = envelope.receipt();
 715            let handler = handler.clone();
 716            async move {
 717                let peer = session.peer.clone();
 718                let responded = Arc::new(AtomicBool::default());
 719                let response = Response {
 720                    peer: peer.clone(),
 721                    responded: responded.clone(),
 722                    receipt,
 723                };
 724                match (handler)(envelope.payload, response, session).await {
 725                    Ok(()) => {
 726                        if responded.load(std::sync::atomic::Ordering::SeqCst) {
 727                            Ok(())
 728                        } else {
 729                            Err(anyhow!("handler did not send a response"))?
 730                        }
 731                    }
 732                    Err(error) => {
 733                        let proto_err = match &error {
 734                            Error::Internal(err) => err.to_proto(),
 735                            _ => ErrorCode::Internal.message(format!("{error}")).to_proto(),
 736                        };
 737                        peer.respond_with_error(receipt, proto_err)?;
 738                        Err(error)
 739                    }
 740                }
 741            }
 742        })
 743    }
 744
 745    pub fn handle_connection(
 746        self: &Arc<Self>,
 747        connection: Connection,
 748        address: String,
 749        principal: Principal,
 750        zed_version: ZedVersion,
 751        geoip_country_code: Option<String>,
 752        system_id: Option<String>,
 753        send_connection_id: Option<oneshot::Sender<ConnectionId>>,
 754        executor: Executor,
 755        connection_guard: Option<ConnectionGuard>,
 756    ) -> impl Future<Output = ()> + use<> {
 757        let this = self.clone();
 758        let span = info_span!("handle connection", %address,
 759            connection_id=field::Empty,
 760            user_id=field::Empty,
 761            login=field::Empty,
 762            impersonator=field::Empty,
 763            geoip_country_code=field::Empty
 764        );
 765        principal.update_span(&span);
 766        if let Some(country_code) = geoip_country_code.as_ref() {
 767            span.record("geoip_country_code", country_code);
 768        }
 769
 770        let mut teardown = self.teardown.subscribe();
 771        async move {
 772            if *teardown.borrow() {
 773                tracing::error!("server is tearing down");
 774                return
 775            }
 776
 777            let (connection_id, handle_io, mut incoming_rx) = this
 778                .peer
 779                .add_connection(connection, {
 780                    let executor = executor.clone();
 781                    move |duration| executor.sleep(duration)
 782                });
 783            tracing::Span::current().record("connection_id", format!("{}", connection_id));
 784
 785            tracing::info!("connection opened");
 786
 787            let user_agent = format!("Zed Server/{}", env!("CARGO_PKG_VERSION"));
 788            let http_client = match ReqwestClient::user_agent(&user_agent) {
 789                Ok(http_client) => Arc::new(http_client),
 790                Err(error) => {
 791                    tracing::error!(?error, "failed to create HTTP client");
 792                    return;
 793                }
 794            };
 795
 796            let supermaven_client = this.app_state.config.supermaven_admin_api_key.clone().map(|supermaven_admin_api_key| Arc::new(SupermavenAdminApi::new(
 797                    supermaven_admin_api_key.to_string(),
 798                    http_client.clone(),
 799                )));
 800
 801            let session = Session {
 802                principal: principal.clone(),
 803                connection_id,
 804                db: Arc::new(tokio::sync::Mutex::new(DbHandle(this.app_state.db.clone()))),
 805                peer: this.peer.clone(),
 806                connection_pool: this.connection_pool.clone(),
 807                app_state: this.app_state.clone(),
 808                geoip_country_code,
 809                system_id,
 810                _executor: executor.clone(),
 811                supermaven_client,
 812            };
 813
 814            if let Err(error) = this.send_initial_client_update(connection_id, zed_version, send_connection_id, &session).await {
 815                tracing::error!(?error, "failed to send initial client update");
 816                return;
 817            }
 818            drop(connection_guard);
 819
 820            let handle_io = handle_io.fuse();
 821            futures::pin_mut!(handle_io);
 822
 823            // Handlers for foreground messages are pushed into the following `FuturesUnordered`.
 824            // This prevents deadlocks when e.g., client A performs a request to client B and
 825            // client B performs a request to client A. If both clients stop processing further
 826            // messages until their respective request completes, they won't have a chance to
 827            // respond to the other client's request and cause a deadlock.
 828            //
 829            // This arrangement ensures we will attempt to process earlier messages first, but fall
 830            // back to processing messages arrived later in the spirit of making progress.
 831            let mut foreground_message_handlers = FuturesUnordered::new();
 832            let concurrent_handlers = Arc::new(Semaphore::new(256));
 833            loop {
 834                let next_message = async {
 835                    let permit = concurrent_handlers.clone().acquire_owned().await.unwrap();
 836                    let message = incoming_rx.next().await;
 837                    (permit, message)
 838                }.fuse();
 839                futures::pin_mut!(next_message);
 840                futures::select_biased! {
 841                    _ = teardown.changed().fuse() => return,
 842                    result = handle_io => {
 843                        if let Err(error) = result {
 844                            tracing::error!(?error, "error handling I/O");
 845                        }
 846                        break;
 847                    }
 848                    _ = foreground_message_handlers.next() => {}
 849                    next_message = next_message => {
 850                        let (permit, message) = next_message;
 851                        if let Some(message) = message {
 852                            let type_name = message.payload_type_name();
 853                            // note: we copy all the fields from the parent span so we can query them in the logs.
 854                            // (https://github.com/tokio-rs/tracing/issues/2670).
 855                            let span = tracing::info_span!("receive message", %connection_id, %address, type_name,
 856                                user_id=field::Empty,
 857                                login=field::Empty,
 858                                impersonator=field::Empty,
 859                            );
 860                            principal.update_span(&span);
 861                            let span_enter = span.enter();
 862                            if let Some(handler) = this.handlers.get(&message.payload_type_id()) {
 863                                let is_background = message.is_background();
 864                                let handle_message = (handler)(message, session.clone());
 865                                drop(span_enter);
 866
 867                                let handle_message = async move {
 868                                    handle_message.await;
 869                                    drop(permit);
 870                                }.instrument(span);
 871                                if is_background {
 872                                    executor.spawn_detached(handle_message);
 873                                } else {
 874                                    foreground_message_handlers.push(handle_message);
 875                                }
 876                            } else {
 877                                tracing::error!("no message handler");
 878                            }
 879                        } else {
 880                            tracing::info!("connection closed");
 881                            break;
 882                        }
 883                    }
 884                }
 885            }
 886
 887            drop(foreground_message_handlers);
 888            tracing::info!("signing out");
 889            if let Err(error) = connection_lost(session, teardown, executor).await {
 890                tracing::error!(?error, "error signing out");
 891            }
 892
 893        }.instrument(span)
 894    }
 895
 896    async fn send_initial_client_update(
 897        &self,
 898        connection_id: ConnectionId,
 899        zed_version: ZedVersion,
 900        mut send_connection_id: Option<oneshot::Sender<ConnectionId>>,
 901        session: &Session,
 902    ) -> Result<()> {
 903        self.peer.send(
 904            connection_id,
 905            proto::Hello {
 906                peer_id: Some(connection_id.into()),
 907            },
 908        )?;
 909        tracing::info!("sent hello message");
 910        if let Some(send_connection_id) = send_connection_id.take() {
 911            let _ = send_connection_id.send(connection_id);
 912        }
 913
 914        match &session.principal {
 915            Principal::User(user) | Principal::Impersonated { user, admin: _ } => {
 916                if !user.connected_once {
 917                    self.peer.send(connection_id, proto::ShowContacts {})?;
 918                    self.app_state
 919                        .db
 920                        .set_user_connected_once(user.id, true)
 921                        .await?;
 922                }
 923
 924                update_user_plan(session).await?;
 925
 926                let contacts = self.app_state.db.get_contacts(user.id).await?;
 927
 928                {
 929                    let mut pool = self.connection_pool.lock();
 930                    pool.add_connection(connection_id, user.id, user.admin, zed_version);
 931                    self.peer.send(
 932                        connection_id,
 933                        build_initial_contacts_update(contacts, &pool),
 934                    )?;
 935                }
 936
 937                if should_auto_subscribe_to_channels(zed_version) {
 938                    subscribe_user_to_channels(user.id, session).await?;
 939                }
 940
 941                if let Some(incoming_call) =
 942                    self.app_state.db.incoming_call_for_user(user.id).await?
 943                {
 944                    self.peer.send(connection_id, incoming_call)?;
 945                }
 946
 947                update_user_contacts(user.id, session).await?;
 948            }
 949        }
 950
 951        Ok(())
 952    }
 953
 954    pub async fn invite_code_redeemed(
 955        self: &Arc<Self>,
 956        inviter_id: UserId,
 957        invitee_id: UserId,
 958    ) -> Result<()> {
 959        if let Some(user) = self.app_state.db.get_user_by_id(inviter_id).await? {
 960            if let Some(code) = &user.invite_code {
 961                let pool = self.connection_pool.lock();
 962                let invitee_contact = contact_for_user(invitee_id, false, &pool);
 963                for connection_id in pool.user_connection_ids(inviter_id) {
 964                    self.peer.send(
 965                        connection_id,
 966                        proto::UpdateContacts {
 967                            contacts: vec![invitee_contact.clone()],
 968                            ..Default::default()
 969                        },
 970                    )?;
 971                    self.peer.send(
 972                        connection_id,
 973                        proto::UpdateInviteInfo {
 974                            url: format!("{}{}", self.app_state.config.invite_link_prefix, &code),
 975                            count: user.invite_count as u32,
 976                        },
 977                    )?;
 978                }
 979            }
 980        }
 981        Ok(())
 982    }
 983
 984    pub async fn invite_count_updated(self: &Arc<Self>, user_id: UserId) -> Result<()> {
 985        if let Some(user) = self.app_state.db.get_user_by_id(user_id).await? {
 986            if let Some(invite_code) = &user.invite_code {
 987                let pool = self.connection_pool.lock();
 988                for connection_id in pool.user_connection_ids(user_id) {
 989                    self.peer.send(
 990                        connection_id,
 991                        proto::UpdateInviteInfo {
 992                            url: format!(
 993                                "{}{}",
 994                                self.app_state.config.invite_link_prefix, invite_code
 995                            ),
 996                            count: user.invite_count as u32,
 997                        },
 998                    )?;
 999                }
1000            }
1001        }
1002        Ok(())
1003    }
1004
1005    pub async fn update_plan_for_user(self: &Arc<Self>, user_id: UserId) -> Result<()> {
1006        let user = self
1007            .app_state
1008            .db
1009            .get_user_by_id(user_id)
1010            .await?
1011            .context("user not found")?;
1012
1013        let update_user_plan = make_update_user_plan_message(
1014            &user,
1015            user.admin,
1016            &self.app_state.db,
1017            self.app_state.llm_db.clone(),
1018        )
1019        .await?;
1020
1021        let pool = self.connection_pool.lock();
1022        for connection_id in pool.user_connection_ids(user_id) {
1023            self.peer
1024                .send(connection_id, update_user_plan.clone())
1025                .trace_err();
1026        }
1027
1028        Ok(())
1029    }
1030
1031    pub async fn refresh_llm_tokens_for_user(self: &Arc<Self>, user_id: UserId) {
1032        let pool = self.connection_pool.lock();
1033        for connection_id in pool.user_connection_ids(user_id) {
1034            self.peer
1035                .send(connection_id, proto::RefreshLlmToken {})
1036                .trace_err();
1037        }
1038    }
1039
1040    pub async fn snapshot(self: &Arc<Self>) -> ServerSnapshot {
1041        ServerSnapshot {
1042            connection_pool: ConnectionPoolGuard {
1043                guard: self.connection_pool.lock(),
1044                _not_send: PhantomData,
1045            },
1046            peer: &self.peer,
1047        }
1048    }
1049}
1050
1051impl Deref for ConnectionPoolGuard<'_> {
1052    type Target = ConnectionPool;
1053
1054    fn deref(&self) -> &Self::Target {
1055        &self.guard
1056    }
1057}
1058
1059impl DerefMut for ConnectionPoolGuard<'_> {
1060    fn deref_mut(&mut self) -> &mut Self::Target {
1061        &mut self.guard
1062    }
1063}
1064
1065impl Drop for ConnectionPoolGuard<'_> {
1066    fn drop(&mut self) {
1067        #[cfg(test)]
1068        self.check_invariants();
1069    }
1070}
1071
1072fn broadcast<F>(
1073    sender_id: Option<ConnectionId>,
1074    receiver_ids: impl IntoIterator<Item = ConnectionId>,
1075    mut f: F,
1076) where
1077    F: FnMut(ConnectionId) -> anyhow::Result<()>,
1078{
1079    for receiver_id in receiver_ids {
1080        if Some(receiver_id) != sender_id {
1081            if let Err(error) = f(receiver_id) {
1082                tracing::error!("failed to send to {:?} {}", receiver_id, error);
1083            }
1084        }
1085    }
1086}
1087
1088pub struct ProtocolVersion(u32);
1089
1090impl Header for ProtocolVersion {
1091    fn name() -> &'static HeaderName {
1092        static ZED_PROTOCOL_VERSION: OnceLock<HeaderName> = OnceLock::new();
1093        ZED_PROTOCOL_VERSION.get_or_init(|| HeaderName::from_static("x-zed-protocol-version"))
1094    }
1095
1096    fn decode<'i, I>(values: &mut I) -> Result<Self, axum::headers::Error>
1097    where
1098        Self: Sized,
1099        I: Iterator<Item = &'i axum::http::HeaderValue>,
1100    {
1101        let version = values
1102            .next()
1103            .ok_or_else(axum::headers::Error::invalid)?
1104            .to_str()
1105            .map_err(|_| axum::headers::Error::invalid())?
1106            .parse()
1107            .map_err(|_| axum::headers::Error::invalid())?;
1108        Ok(Self(version))
1109    }
1110
1111    fn encode<E: Extend<axum::http::HeaderValue>>(&self, values: &mut E) {
1112        values.extend([self.0.to_string().parse().unwrap()]);
1113    }
1114}
1115
1116pub struct AppVersionHeader(SemanticVersion);
1117impl Header for AppVersionHeader {
1118    fn name() -> &'static HeaderName {
1119        static ZED_APP_VERSION: OnceLock<HeaderName> = OnceLock::new();
1120        ZED_APP_VERSION.get_or_init(|| HeaderName::from_static("x-zed-app-version"))
1121    }
1122
1123    fn decode<'i, I>(values: &mut I) -> Result<Self, axum::headers::Error>
1124    where
1125        Self: Sized,
1126        I: Iterator<Item = &'i axum::http::HeaderValue>,
1127    {
1128        let version = values
1129            .next()
1130            .ok_or_else(axum::headers::Error::invalid)?
1131            .to_str()
1132            .map_err(|_| axum::headers::Error::invalid())?
1133            .parse()
1134            .map_err(|_| axum::headers::Error::invalid())?;
1135        Ok(Self(version))
1136    }
1137
1138    fn encode<E: Extend<axum::http::HeaderValue>>(&self, values: &mut E) {
1139        values.extend([self.0.to_string().parse().unwrap()]);
1140    }
1141}
1142
1143pub fn routes(server: Arc<Server>) -> Router<(), Body> {
1144    Router::new()
1145        .route("/rpc", get(handle_websocket_request))
1146        .layer(
1147            ServiceBuilder::new()
1148                .layer(Extension(server.app_state.clone()))
1149                .layer(middleware::from_fn(auth::validate_header)),
1150        )
1151        .route("/metrics", get(handle_metrics))
1152        .layer(Extension(server))
1153}
1154
1155pub async fn handle_websocket_request(
1156    TypedHeader(ProtocolVersion(protocol_version)): TypedHeader<ProtocolVersion>,
1157    app_version_header: Option<TypedHeader<AppVersionHeader>>,
1158    ConnectInfo(socket_address): ConnectInfo<SocketAddr>,
1159    Extension(server): Extension<Arc<Server>>,
1160    Extension(principal): Extension<Principal>,
1161    country_code_header: Option<TypedHeader<CloudflareIpCountryHeader>>,
1162    system_id_header: Option<TypedHeader<SystemIdHeader>>,
1163    ws: WebSocketUpgrade,
1164) -> axum::response::Response {
1165    if protocol_version != rpc::PROTOCOL_VERSION {
1166        return (
1167            StatusCode::UPGRADE_REQUIRED,
1168            "client must be upgraded".to_string(),
1169        )
1170            .into_response();
1171    }
1172
1173    let Some(version) = app_version_header.map(|header| ZedVersion(header.0.0)) else {
1174        return (
1175            StatusCode::UPGRADE_REQUIRED,
1176            "no version header found".to_string(),
1177        )
1178            .into_response();
1179    };
1180
1181    if !version.can_collaborate() {
1182        return (
1183            StatusCode::UPGRADE_REQUIRED,
1184            "client must be upgraded".to_string(),
1185        )
1186            .into_response();
1187    }
1188
1189    let socket_address = socket_address.to_string();
1190
1191    // Acquire connection guard before WebSocket upgrade
1192    let connection_guard = match ConnectionGuard::try_acquire() {
1193        Ok(guard) => guard,
1194        Err(()) => {
1195            return (
1196                StatusCode::SERVICE_UNAVAILABLE,
1197                "Too many concurrent connections",
1198            )
1199                .into_response();
1200        }
1201    };
1202
1203    ws.on_upgrade(move |socket| {
1204        let socket = socket
1205            .map_ok(to_tungstenite_message)
1206            .err_into()
1207            .with(|message| async move { to_axum_message(message) });
1208        let connection = Connection::new(Box::pin(socket));
1209        async move {
1210            server
1211                .handle_connection(
1212                    connection,
1213                    socket_address,
1214                    principal,
1215                    version,
1216                    country_code_header.map(|header| header.to_string()),
1217                    system_id_header.map(|header| header.to_string()),
1218                    None,
1219                    Executor::Production,
1220                    Some(connection_guard),
1221                )
1222                .await;
1223        }
1224    })
1225}
1226
1227pub async fn handle_metrics(Extension(server): Extension<Arc<Server>>) -> Result<String> {
1228    static CONNECTIONS_METRIC: OnceLock<IntGauge> = OnceLock::new();
1229    let connections_metric = CONNECTIONS_METRIC
1230        .get_or_init(|| register_int_gauge!("connections", "number of connections").unwrap());
1231
1232    let connections = server
1233        .connection_pool
1234        .lock()
1235        .connections()
1236        .filter(|connection| !connection.admin)
1237        .count();
1238    connections_metric.set(connections as _);
1239
1240    static SHARED_PROJECTS_METRIC: OnceLock<IntGauge> = OnceLock::new();
1241    let shared_projects_metric = SHARED_PROJECTS_METRIC.get_or_init(|| {
1242        register_int_gauge!(
1243            "shared_projects",
1244            "number of open projects with one or more guests"
1245        )
1246        .unwrap()
1247    });
1248
1249    let shared_projects = server.app_state.db.project_count_excluding_admins().await?;
1250    shared_projects_metric.set(shared_projects as _);
1251
1252    let encoder = prometheus::TextEncoder::new();
1253    let metric_families = prometheus::gather();
1254    let encoded_metrics = encoder
1255        .encode_to_string(&metric_families)
1256        .map_err(|err| anyhow!("{err}"))?;
1257    Ok(encoded_metrics)
1258}
1259
1260#[instrument(err, skip(executor))]
1261async fn connection_lost(
1262    session: Session,
1263    mut teardown: watch::Receiver<bool>,
1264    executor: Executor,
1265) -> Result<()> {
1266    session.peer.disconnect(session.connection_id);
1267    session
1268        .connection_pool()
1269        .await
1270        .remove_connection(session.connection_id)?;
1271
1272    session
1273        .db()
1274        .await
1275        .connection_lost(session.connection_id)
1276        .await
1277        .trace_err();
1278
1279    futures::select_biased! {
1280        _ = executor.sleep(RECONNECT_TIMEOUT).fuse() => {
1281
1282            log::info!("connection lost, removing all resources for user:{}, connection:{:?}", session.user_id(), session.connection_id);
1283            leave_room_for_session(&session, session.connection_id).await.trace_err();
1284            leave_channel_buffers_for_session(&session)
1285                .await
1286                .trace_err();
1287
1288            if !session
1289                .connection_pool()
1290                .await
1291                .is_user_online(session.user_id())
1292            {
1293                let db = session.db().await;
1294                if let Some(room) = db.decline_call(None, session.user_id()).await.trace_err().flatten() {
1295                    room_updated(&room, &session.peer);
1296                }
1297            }
1298
1299            update_user_contacts(session.user_id(), &session).await?;
1300        },
1301        _ = teardown.changed().fuse() => {}
1302    }
1303
1304    Ok(())
1305}
1306
1307/// Acknowledges a ping from a client, used to keep the connection alive.
1308async fn ping(_: proto::Ping, response: Response<proto::Ping>, _session: Session) -> Result<()> {
1309    response.send(proto::Ack {})?;
1310    Ok(())
1311}
1312
1313/// Creates a new room for calling (outside of channels)
1314async fn create_room(
1315    _request: proto::CreateRoom,
1316    response: Response<proto::CreateRoom>,
1317    session: Session,
1318) -> Result<()> {
1319    let livekit_room = nanoid::nanoid!(30);
1320
1321    let live_kit_connection_info = util::maybe!(async {
1322        let live_kit = session.app_state.livekit_client.as_ref();
1323        let live_kit = live_kit?;
1324        let user_id = session.user_id().to_string();
1325
1326        let token = live_kit
1327            .room_token(&livekit_room, &user_id.to_string())
1328            .trace_err()?;
1329
1330        Some(proto::LiveKitConnectionInfo {
1331            server_url: live_kit.url().into(),
1332            token,
1333            can_publish: true,
1334        })
1335    })
1336    .await;
1337
1338    let room = session
1339        .db()
1340        .await
1341        .create_room(session.user_id(), session.connection_id, &livekit_room)
1342        .await?;
1343
1344    response.send(proto::CreateRoomResponse {
1345        room: Some(room.clone()),
1346        live_kit_connection_info,
1347    })?;
1348
1349    update_user_contacts(session.user_id(), &session).await?;
1350    Ok(())
1351}
1352
1353/// Join a room from an invitation. Equivalent to joining a channel if there is one.
1354async fn join_room(
1355    request: proto::JoinRoom,
1356    response: Response<proto::JoinRoom>,
1357    session: Session,
1358) -> Result<()> {
1359    let room_id = RoomId::from_proto(request.id);
1360
1361    let channel_id = session.db().await.channel_id_for_room(room_id).await?;
1362
1363    if let Some(channel_id) = channel_id {
1364        return join_channel_internal(channel_id, Box::new(response), session).await;
1365    }
1366
1367    let joined_room = {
1368        let room = session
1369            .db()
1370            .await
1371            .join_room(room_id, session.user_id(), session.connection_id)
1372            .await?;
1373        room_updated(&room.room, &session.peer);
1374        room.into_inner()
1375    };
1376
1377    for connection_id in session
1378        .connection_pool()
1379        .await
1380        .user_connection_ids(session.user_id())
1381    {
1382        session
1383            .peer
1384            .send(
1385                connection_id,
1386                proto::CallCanceled {
1387                    room_id: room_id.to_proto(),
1388                },
1389            )
1390            .trace_err();
1391    }
1392
1393    let live_kit_connection_info = if let Some(live_kit) = session.app_state.livekit_client.as_ref()
1394    {
1395        live_kit
1396            .room_token(
1397                &joined_room.room.livekit_room,
1398                &session.user_id().to_string(),
1399            )
1400            .trace_err()
1401            .map(|token| proto::LiveKitConnectionInfo {
1402                server_url: live_kit.url().into(),
1403                token,
1404                can_publish: true,
1405            })
1406    } else {
1407        None
1408    };
1409
1410    response.send(proto::JoinRoomResponse {
1411        room: Some(joined_room.room),
1412        channel_id: None,
1413        live_kit_connection_info,
1414    })?;
1415
1416    update_user_contacts(session.user_id(), &session).await?;
1417    Ok(())
1418}
1419
1420/// Rejoin room is used to reconnect to a room after connection errors.
1421async fn rejoin_room(
1422    request: proto::RejoinRoom,
1423    response: Response<proto::RejoinRoom>,
1424    session: Session,
1425) -> Result<()> {
1426    let room;
1427    let channel;
1428    {
1429        let mut rejoined_room = session
1430            .db()
1431            .await
1432            .rejoin_room(request, session.user_id(), session.connection_id)
1433            .await?;
1434
1435        response.send(proto::RejoinRoomResponse {
1436            room: Some(rejoined_room.room.clone()),
1437            reshared_projects: rejoined_room
1438                .reshared_projects
1439                .iter()
1440                .map(|project| proto::ResharedProject {
1441                    id: project.id.to_proto(),
1442                    collaborators: project
1443                        .collaborators
1444                        .iter()
1445                        .map(|collaborator| collaborator.to_proto())
1446                        .collect(),
1447                })
1448                .collect(),
1449            rejoined_projects: rejoined_room
1450                .rejoined_projects
1451                .iter()
1452                .map(|rejoined_project| rejoined_project.to_proto())
1453                .collect(),
1454        })?;
1455        room_updated(&rejoined_room.room, &session.peer);
1456
1457        for project in &rejoined_room.reshared_projects {
1458            for collaborator in &project.collaborators {
1459                session
1460                    .peer
1461                    .send(
1462                        collaborator.connection_id,
1463                        proto::UpdateProjectCollaborator {
1464                            project_id: project.id.to_proto(),
1465                            old_peer_id: Some(project.old_connection_id.into()),
1466                            new_peer_id: Some(session.connection_id.into()),
1467                        },
1468                    )
1469                    .trace_err();
1470            }
1471
1472            broadcast(
1473                Some(session.connection_id),
1474                project
1475                    .collaborators
1476                    .iter()
1477                    .map(|collaborator| collaborator.connection_id),
1478                |connection_id| {
1479                    session.peer.forward_send(
1480                        session.connection_id,
1481                        connection_id,
1482                        proto::UpdateProject {
1483                            project_id: project.id.to_proto(),
1484                            worktrees: project.worktrees.clone(),
1485                        },
1486                    )
1487                },
1488            );
1489        }
1490
1491        notify_rejoined_projects(&mut rejoined_room.rejoined_projects, &session)?;
1492
1493        let rejoined_room = rejoined_room.into_inner();
1494
1495        room = rejoined_room.room;
1496        channel = rejoined_room.channel;
1497    }
1498
1499    if let Some(channel) = channel {
1500        channel_updated(
1501            &channel,
1502            &room,
1503            &session.peer,
1504            &*session.connection_pool().await,
1505        );
1506    }
1507
1508    update_user_contacts(session.user_id(), &session).await?;
1509    Ok(())
1510}
1511
1512fn notify_rejoined_projects(
1513    rejoined_projects: &mut Vec<RejoinedProject>,
1514    session: &Session,
1515) -> Result<()> {
1516    for project in rejoined_projects.iter() {
1517        for collaborator in &project.collaborators {
1518            session
1519                .peer
1520                .send(
1521                    collaborator.connection_id,
1522                    proto::UpdateProjectCollaborator {
1523                        project_id: project.id.to_proto(),
1524                        old_peer_id: Some(project.old_connection_id.into()),
1525                        new_peer_id: Some(session.connection_id.into()),
1526                    },
1527                )
1528                .trace_err();
1529        }
1530    }
1531
1532    for project in rejoined_projects {
1533        for worktree in mem::take(&mut project.worktrees) {
1534            // Stream this worktree's entries.
1535            let message = proto::UpdateWorktree {
1536                project_id: project.id.to_proto(),
1537                worktree_id: worktree.id,
1538                abs_path: worktree.abs_path.clone(),
1539                root_name: worktree.root_name,
1540                updated_entries: worktree.updated_entries,
1541                removed_entries: worktree.removed_entries,
1542                scan_id: worktree.scan_id,
1543                is_last_update: worktree.completed_scan_id == worktree.scan_id,
1544                updated_repositories: worktree.updated_repositories,
1545                removed_repositories: worktree.removed_repositories,
1546            };
1547            for update in proto::split_worktree_update(message) {
1548                session.peer.send(session.connection_id, update)?;
1549            }
1550
1551            // Stream this worktree's diagnostics.
1552            for summary in worktree.diagnostic_summaries {
1553                session.peer.send(
1554                    session.connection_id,
1555                    proto::UpdateDiagnosticSummary {
1556                        project_id: project.id.to_proto(),
1557                        worktree_id: worktree.id,
1558                        summary: Some(summary),
1559                    },
1560                )?;
1561            }
1562
1563            for settings_file in worktree.settings_files {
1564                session.peer.send(
1565                    session.connection_id,
1566                    proto::UpdateWorktreeSettings {
1567                        project_id: project.id.to_proto(),
1568                        worktree_id: worktree.id,
1569                        path: settings_file.path,
1570                        content: Some(settings_file.content),
1571                        kind: Some(settings_file.kind.to_proto().into()),
1572                    },
1573                )?;
1574            }
1575        }
1576
1577        for repository in mem::take(&mut project.updated_repositories) {
1578            for update in split_repository_update(repository) {
1579                session.peer.send(session.connection_id, update)?;
1580            }
1581        }
1582
1583        for id in mem::take(&mut project.removed_repositories) {
1584            session.peer.send(
1585                session.connection_id,
1586                proto::RemoveRepository {
1587                    project_id: project.id.to_proto(),
1588                    id,
1589                },
1590            )?;
1591        }
1592    }
1593
1594    Ok(())
1595}
1596
1597/// leave room disconnects from the room.
1598async fn leave_room(
1599    _: proto::LeaveRoom,
1600    response: Response<proto::LeaveRoom>,
1601    session: Session,
1602) -> Result<()> {
1603    leave_room_for_session(&session, session.connection_id).await?;
1604    response.send(proto::Ack {})?;
1605    Ok(())
1606}
1607
1608/// Updates the permissions of someone else in the room.
1609async fn set_room_participant_role(
1610    request: proto::SetRoomParticipantRole,
1611    response: Response<proto::SetRoomParticipantRole>,
1612    session: Session,
1613) -> Result<()> {
1614    let user_id = UserId::from_proto(request.user_id);
1615    let role = ChannelRole::from(request.role());
1616
1617    let (livekit_room, can_publish) = {
1618        let room = session
1619            .db()
1620            .await
1621            .set_room_participant_role(
1622                session.user_id(),
1623                RoomId::from_proto(request.room_id),
1624                user_id,
1625                role,
1626            )
1627            .await?;
1628
1629        let livekit_room = room.livekit_room.clone();
1630        let can_publish = ChannelRole::from(request.role()).can_use_microphone();
1631        room_updated(&room, &session.peer);
1632        (livekit_room, can_publish)
1633    };
1634
1635    if let Some(live_kit) = session.app_state.livekit_client.as_ref() {
1636        live_kit
1637            .update_participant(
1638                livekit_room.clone(),
1639                request.user_id.to_string(),
1640                livekit_api::proto::ParticipantPermission {
1641                    can_subscribe: true,
1642                    can_publish,
1643                    can_publish_data: can_publish,
1644                    hidden: false,
1645                    recorder: false,
1646                },
1647            )
1648            .await
1649            .trace_err();
1650    }
1651
1652    response.send(proto::Ack {})?;
1653    Ok(())
1654}
1655
1656/// Call someone else into the current room
1657async fn call(
1658    request: proto::Call,
1659    response: Response<proto::Call>,
1660    session: Session,
1661) -> Result<()> {
1662    let room_id = RoomId::from_proto(request.room_id);
1663    let calling_user_id = session.user_id();
1664    let calling_connection_id = session.connection_id;
1665    let called_user_id = UserId::from_proto(request.called_user_id);
1666    let initial_project_id = request.initial_project_id.map(ProjectId::from_proto);
1667    if !session
1668        .db()
1669        .await
1670        .has_contact(calling_user_id, called_user_id)
1671        .await?
1672    {
1673        return Err(anyhow!("cannot call a user who isn't a contact"))?;
1674    }
1675
1676    let incoming_call = {
1677        let (room, incoming_call) = &mut *session
1678            .db()
1679            .await
1680            .call(
1681                room_id,
1682                calling_user_id,
1683                calling_connection_id,
1684                called_user_id,
1685                initial_project_id,
1686            )
1687            .await?;
1688        room_updated(room, &session.peer);
1689        mem::take(incoming_call)
1690    };
1691    update_user_contacts(called_user_id, &session).await?;
1692
1693    let mut calls = session
1694        .connection_pool()
1695        .await
1696        .user_connection_ids(called_user_id)
1697        .map(|connection_id| session.peer.request(connection_id, incoming_call.clone()))
1698        .collect::<FuturesUnordered<_>>();
1699
1700    while let Some(call_response) = calls.next().await {
1701        match call_response.as_ref() {
1702            Ok(_) => {
1703                response.send(proto::Ack {})?;
1704                return Ok(());
1705            }
1706            Err(_) => {
1707                call_response.trace_err();
1708            }
1709        }
1710    }
1711
1712    {
1713        let room = session
1714            .db()
1715            .await
1716            .call_failed(room_id, called_user_id)
1717            .await?;
1718        room_updated(&room, &session.peer);
1719    }
1720    update_user_contacts(called_user_id, &session).await?;
1721
1722    Err(anyhow!("failed to ring user"))?
1723}
1724
1725/// Cancel an outgoing call.
1726async fn cancel_call(
1727    request: proto::CancelCall,
1728    response: Response<proto::CancelCall>,
1729    session: Session,
1730) -> Result<()> {
1731    let called_user_id = UserId::from_proto(request.called_user_id);
1732    let room_id = RoomId::from_proto(request.room_id);
1733    {
1734        let room = session
1735            .db()
1736            .await
1737            .cancel_call(room_id, session.connection_id, called_user_id)
1738            .await?;
1739        room_updated(&room, &session.peer);
1740    }
1741
1742    for connection_id in session
1743        .connection_pool()
1744        .await
1745        .user_connection_ids(called_user_id)
1746    {
1747        session
1748            .peer
1749            .send(
1750                connection_id,
1751                proto::CallCanceled {
1752                    room_id: room_id.to_proto(),
1753                },
1754            )
1755            .trace_err();
1756    }
1757    response.send(proto::Ack {})?;
1758
1759    update_user_contacts(called_user_id, &session).await?;
1760    Ok(())
1761}
1762
1763/// Decline an incoming call.
1764async fn decline_call(message: proto::DeclineCall, session: Session) -> Result<()> {
1765    let room_id = RoomId::from_proto(message.room_id);
1766    {
1767        let room = session
1768            .db()
1769            .await
1770            .decline_call(Some(room_id), session.user_id())
1771            .await?
1772            .context("declining call")?;
1773        room_updated(&room, &session.peer);
1774    }
1775
1776    for connection_id in session
1777        .connection_pool()
1778        .await
1779        .user_connection_ids(session.user_id())
1780    {
1781        session
1782            .peer
1783            .send(
1784                connection_id,
1785                proto::CallCanceled {
1786                    room_id: room_id.to_proto(),
1787                },
1788            )
1789            .trace_err();
1790    }
1791    update_user_contacts(session.user_id(), &session).await?;
1792    Ok(())
1793}
1794
1795/// Updates other participants in the room with your current location.
1796async fn update_participant_location(
1797    request: proto::UpdateParticipantLocation,
1798    response: Response<proto::UpdateParticipantLocation>,
1799    session: Session,
1800) -> Result<()> {
1801    let room_id = RoomId::from_proto(request.room_id);
1802    let location = request.location.context("invalid location")?;
1803
1804    let db = session.db().await;
1805    let room = db
1806        .update_room_participant_location(room_id, session.connection_id, location)
1807        .await?;
1808
1809    room_updated(&room, &session.peer);
1810    response.send(proto::Ack {})?;
1811    Ok(())
1812}
1813
1814/// Share a project into the room.
1815async fn share_project(
1816    request: proto::ShareProject,
1817    response: Response<proto::ShareProject>,
1818    session: Session,
1819) -> Result<()> {
1820    let (project_id, room) = &*session
1821        .db()
1822        .await
1823        .share_project(
1824            RoomId::from_proto(request.room_id),
1825            session.connection_id,
1826            &request.worktrees,
1827            request.is_ssh_project,
1828        )
1829        .await?;
1830    response.send(proto::ShareProjectResponse {
1831        project_id: project_id.to_proto(),
1832    })?;
1833    room_updated(room, &session.peer);
1834
1835    Ok(())
1836}
1837
1838/// Unshare a project from the room.
1839async fn unshare_project(message: proto::UnshareProject, session: Session) -> Result<()> {
1840    let project_id = ProjectId::from_proto(message.project_id);
1841    unshare_project_internal(project_id, session.connection_id, &session).await
1842}
1843
1844async fn unshare_project_internal(
1845    project_id: ProjectId,
1846    connection_id: ConnectionId,
1847    session: &Session,
1848) -> Result<()> {
1849    let delete = {
1850        let room_guard = session
1851            .db()
1852            .await
1853            .unshare_project(project_id, connection_id)
1854            .await?;
1855
1856        let (delete, room, guest_connection_ids) = &*room_guard;
1857
1858        let message = proto::UnshareProject {
1859            project_id: project_id.to_proto(),
1860        };
1861
1862        broadcast(
1863            Some(connection_id),
1864            guest_connection_ids.iter().copied(),
1865            |conn_id| session.peer.send(conn_id, message.clone()),
1866        );
1867        if let Some(room) = room {
1868            room_updated(room, &session.peer);
1869        }
1870
1871        *delete
1872    };
1873
1874    if delete {
1875        let db = session.db().await;
1876        db.delete_project(project_id).await?;
1877    }
1878
1879    Ok(())
1880}
1881
1882/// Join someone elses shared project.
1883async fn join_project(
1884    request: proto::JoinProject,
1885    response: Response<proto::JoinProject>,
1886    session: Session,
1887) -> Result<()> {
1888    let project_id = ProjectId::from_proto(request.project_id);
1889
1890    tracing::info!(%project_id, "join project");
1891
1892    let db = session.db().await;
1893    let (project, replica_id) = &mut *db
1894        .join_project(
1895            project_id,
1896            session.connection_id,
1897            session.user_id(),
1898            request.committer_name.clone(),
1899            request.committer_email.clone(),
1900        )
1901        .await?;
1902    drop(db);
1903    tracing::info!(%project_id, "join remote project");
1904    let collaborators = project
1905        .collaborators
1906        .iter()
1907        .filter(|collaborator| collaborator.connection_id != session.connection_id)
1908        .map(|collaborator| collaborator.to_proto())
1909        .collect::<Vec<_>>();
1910    let project_id = project.id;
1911    let guest_user_id = session.user_id();
1912
1913    let worktrees = project
1914        .worktrees
1915        .iter()
1916        .map(|(id, worktree)| proto::WorktreeMetadata {
1917            id: *id,
1918            root_name: worktree.root_name.clone(),
1919            visible: worktree.visible,
1920            abs_path: worktree.abs_path.clone(),
1921        })
1922        .collect::<Vec<_>>();
1923
1924    let add_project_collaborator = proto::AddProjectCollaborator {
1925        project_id: project_id.to_proto(),
1926        collaborator: Some(proto::Collaborator {
1927            peer_id: Some(session.connection_id.into()),
1928            replica_id: replica_id.0 as u32,
1929            user_id: guest_user_id.to_proto(),
1930            is_host: false,
1931            committer_name: request.committer_name.clone(),
1932            committer_email: request.committer_email.clone(),
1933        }),
1934    };
1935
1936    for collaborator in &collaborators {
1937        session
1938            .peer
1939            .send(
1940                collaborator.peer_id.unwrap().into(),
1941                add_project_collaborator.clone(),
1942            )
1943            .trace_err();
1944    }
1945
1946    // First, we send the metadata associated with each worktree.
1947    response.send(proto::JoinProjectResponse {
1948        project_id: project.id.0 as u64,
1949        worktrees: worktrees.clone(),
1950        replica_id: replica_id.0 as u32,
1951        collaborators: collaborators.clone(),
1952        language_servers: project.language_servers.clone(),
1953        role: project.role.into(),
1954    })?;
1955
1956    for (worktree_id, worktree) in mem::take(&mut project.worktrees) {
1957        // Stream this worktree's entries.
1958        let message = proto::UpdateWorktree {
1959            project_id: project_id.to_proto(),
1960            worktree_id,
1961            abs_path: worktree.abs_path.clone(),
1962            root_name: worktree.root_name,
1963            updated_entries: worktree.entries,
1964            removed_entries: Default::default(),
1965            scan_id: worktree.scan_id,
1966            is_last_update: worktree.scan_id == worktree.completed_scan_id,
1967            updated_repositories: worktree.legacy_repository_entries.into_values().collect(),
1968            removed_repositories: Default::default(),
1969        };
1970        for update in proto::split_worktree_update(message) {
1971            session.peer.send(session.connection_id, update.clone())?;
1972        }
1973
1974        // Stream this worktree's diagnostics.
1975        for summary in worktree.diagnostic_summaries {
1976            session.peer.send(
1977                session.connection_id,
1978                proto::UpdateDiagnosticSummary {
1979                    project_id: project_id.to_proto(),
1980                    worktree_id: worktree.id,
1981                    summary: Some(summary),
1982                },
1983            )?;
1984        }
1985
1986        for settings_file in worktree.settings_files {
1987            session.peer.send(
1988                session.connection_id,
1989                proto::UpdateWorktreeSettings {
1990                    project_id: project_id.to_proto(),
1991                    worktree_id: worktree.id,
1992                    path: settings_file.path,
1993                    content: Some(settings_file.content),
1994                    kind: Some(settings_file.kind.to_proto() as i32),
1995                },
1996            )?;
1997        }
1998    }
1999
2000    for repository in mem::take(&mut project.repositories) {
2001        for update in split_repository_update(repository) {
2002            session.peer.send(session.connection_id, update)?;
2003        }
2004    }
2005
2006    for language_server in &project.language_servers {
2007        session.peer.send(
2008            session.connection_id,
2009            proto::UpdateLanguageServer {
2010                project_id: project_id.to_proto(),
2011                language_server_id: language_server.id,
2012                variant: Some(
2013                    proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
2014                        proto::LspDiskBasedDiagnosticsUpdated {},
2015                    ),
2016                ),
2017            },
2018        )?;
2019    }
2020
2021    Ok(())
2022}
2023
2024/// Leave someone elses shared project.
2025async fn leave_project(request: proto::LeaveProject, session: Session) -> Result<()> {
2026    let sender_id = session.connection_id;
2027    let project_id = ProjectId::from_proto(request.project_id);
2028    let db = session.db().await;
2029
2030    let (room, project) = &*db.leave_project(project_id, sender_id).await?;
2031    tracing::info!(
2032        %project_id,
2033        "leave project"
2034    );
2035
2036    project_left(project, &session);
2037    if let Some(room) = room {
2038        room_updated(room, &session.peer);
2039    }
2040
2041    Ok(())
2042}
2043
2044/// Updates other participants with changes to the project
2045async fn update_project(
2046    request: proto::UpdateProject,
2047    response: Response<proto::UpdateProject>,
2048    session: Session,
2049) -> Result<()> {
2050    let project_id = ProjectId::from_proto(request.project_id);
2051    let (room, guest_connection_ids) = &*session
2052        .db()
2053        .await
2054        .update_project(project_id, session.connection_id, &request.worktrees)
2055        .await?;
2056    broadcast(
2057        Some(session.connection_id),
2058        guest_connection_ids.iter().copied(),
2059        |connection_id| {
2060            session
2061                .peer
2062                .forward_send(session.connection_id, connection_id, request.clone())
2063        },
2064    );
2065    if let Some(room) = room {
2066        room_updated(room, &session.peer);
2067    }
2068    response.send(proto::Ack {})?;
2069
2070    Ok(())
2071}
2072
2073/// Updates other participants with changes to the worktree
2074async fn update_worktree(
2075    request: proto::UpdateWorktree,
2076    response: Response<proto::UpdateWorktree>,
2077    session: Session,
2078) -> Result<()> {
2079    let guest_connection_ids = session
2080        .db()
2081        .await
2082        .update_worktree(&request, session.connection_id)
2083        .await?;
2084
2085    broadcast(
2086        Some(session.connection_id),
2087        guest_connection_ids.iter().copied(),
2088        |connection_id| {
2089            session
2090                .peer
2091                .forward_send(session.connection_id, connection_id, request.clone())
2092        },
2093    );
2094    response.send(proto::Ack {})?;
2095    Ok(())
2096}
2097
2098async fn update_repository(
2099    request: proto::UpdateRepository,
2100    response: Response<proto::UpdateRepository>,
2101    session: Session,
2102) -> Result<()> {
2103    let guest_connection_ids = session
2104        .db()
2105        .await
2106        .update_repository(&request, session.connection_id)
2107        .await?;
2108
2109    broadcast(
2110        Some(session.connection_id),
2111        guest_connection_ids.iter().copied(),
2112        |connection_id| {
2113            session
2114                .peer
2115                .forward_send(session.connection_id, connection_id, request.clone())
2116        },
2117    );
2118    response.send(proto::Ack {})?;
2119    Ok(())
2120}
2121
2122async fn remove_repository(
2123    request: proto::RemoveRepository,
2124    response: Response<proto::RemoveRepository>,
2125    session: Session,
2126) -> Result<()> {
2127    let guest_connection_ids = session
2128        .db()
2129        .await
2130        .remove_repository(&request, session.connection_id)
2131        .await?;
2132
2133    broadcast(
2134        Some(session.connection_id),
2135        guest_connection_ids.iter().copied(),
2136        |connection_id| {
2137            session
2138                .peer
2139                .forward_send(session.connection_id, connection_id, request.clone())
2140        },
2141    );
2142    response.send(proto::Ack {})?;
2143    Ok(())
2144}
2145
2146/// Updates other participants with changes to the diagnostics
2147async fn update_diagnostic_summary(
2148    message: proto::UpdateDiagnosticSummary,
2149    session: Session,
2150) -> Result<()> {
2151    let guest_connection_ids = session
2152        .db()
2153        .await
2154        .update_diagnostic_summary(&message, session.connection_id)
2155        .await?;
2156
2157    broadcast(
2158        Some(session.connection_id),
2159        guest_connection_ids.iter().copied(),
2160        |connection_id| {
2161            session
2162                .peer
2163                .forward_send(session.connection_id, connection_id, message.clone())
2164        },
2165    );
2166
2167    Ok(())
2168}
2169
2170/// Updates other participants with changes to the worktree settings
2171async fn update_worktree_settings(
2172    message: proto::UpdateWorktreeSettings,
2173    session: Session,
2174) -> Result<()> {
2175    let guest_connection_ids = session
2176        .db()
2177        .await
2178        .update_worktree_settings(&message, session.connection_id)
2179        .await?;
2180
2181    broadcast(
2182        Some(session.connection_id),
2183        guest_connection_ids.iter().copied(),
2184        |connection_id| {
2185            session
2186                .peer
2187                .forward_send(session.connection_id, connection_id, message.clone())
2188        },
2189    );
2190
2191    Ok(())
2192}
2193
2194/// Notify other participants that a language server has started.
2195async fn start_language_server(
2196    request: proto::StartLanguageServer,
2197    session: Session,
2198) -> Result<()> {
2199    let guest_connection_ids = session
2200        .db()
2201        .await
2202        .start_language_server(&request, session.connection_id)
2203        .await?;
2204
2205    broadcast(
2206        Some(session.connection_id),
2207        guest_connection_ids.iter().copied(),
2208        |connection_id| {
2209            session
2210                .peer
2211                .forward_send(session.connection_id, connection_id, request.clone())
2212        },
2213    );
2214    Ok(())
2215}
2216
2217/// Notify other participants that a language server has changed.
2218async fn update_language_server(
2219    request: proto::UpdateLanguageServer,
2220    session: Session,
2221) -> Result<()> {
2222    let project_id = ProjectId::from_proto(request.project_id);
2223    let project_connection_ids = session
2224        .db()
2225        .await
2226        .project_connection_ids(project_id, session.connection_id, true)
2227        .await?;
2228    broadcast(
2229        Some(session.connection_id),
2230        project_connection_ids.iter().copied(),
2231        |connection_id| {
2232            session
2233                .peer
2234                .forward_send(session.connection_id, connection_id, request.clone())
2235        },
2236    );
2237    Ok(())
2238}
2239
2240/// forward a project request to the host. These requests should be read only
2241/// as guests are allowed to send them.
2242async fn forward_read_only_project_request<T>(
2243    request: T,
2244    response: Response<T>,
2245    session: Session,
2246) -> Result<()>
2247where
2248    T: EntityMessage + RequestMessage,
2249{
2250    let project_id = ProjectId::from_proto(request.remote_entity_id());
2251    let host_connection_id = session
2252        .db()
2253        .await
2254        .host_for_read_only_project_request(project_id, session.connection_id)
2255        .await?;
2256    let payload = session
2257        .peer
2258        .forward_request(session.connection_id, host_connection_id, request)
2259        .await?;
2260    response.send(payload)?;
2261    Ok(())
2262}
2263
2264async fn forward_find_search_candidates_request(
2265    request: proto::FindSearchCandidates,
2266    response: Response<proto::FindSearchCandidates>,
2267    session: Session,
2268) -> Result<()> {
2269    let project_id = ProjectId::from_proto(request.remote_entity_id());
2270    let host_connection_id = session
2271        .db()
2272        .await
2273        .host_for_read_only_project_request(project_id, session.connection_id)
2274        .await?;
2275    let payload = session
2276        .peer
2277        .forward_request(session.connection_id, host_connection_id, request)
2278        .await?;
2279    response.send(payload)?;
2280    Ok(())
2281}
2282
2283/// forward a project request to the host. These requests are disallowed
2284/// for guests.
2285async fn forward_mutating_project_request<T>(
2286    request: T,
2287    response: Response<T>,
2288    session: Session,
2289) -> Result<()>
2290where
2291    T: EntityMessage + RequestMessage,
2292{
2293    let project_id = ProjectId::from_proto(request.remote_entity_id());
2294
2295    let host_connection_id = session
2296        .db()
2297        .await
2298        .host_for_mutating_project_request(project_id, session.connection_id)
2299        .await?;
2300    let payload = session
2301        .peer
2302        .forward_request(session.connection_id, host_connection_id, request)
2303        .await?;
2304    response.send(payload)?;
2305    Ok(())
2306}
2307
2308/// Notify other participants that a new buffer has been created
2309async fn create_buffer_for_peer(
2310    request: proto::CreateBufferForPeer,
2311    session: Session,
2312) -> Result<()> {
2313    session
2314        .db()
2315        .await
2316        .check_user_is_project_host(
2317            ProjectId::from_proto(request.project_id),
2318            session.connection_id,
2319        )
2320        .await?;
2321    let peer_id = request.peer_id.context("invalid peer id")?;
2322    session
2323        .peer
2324        .forward_send(session.connection_id, peer_id.into(), request)?;
2325    Ok(())
2326}
2327
2328/// Notify other participants that a buffer has been updated. This is
2329/// allowed for guests as long as the update is limited to selections.
2330async fn update_buffer(
2331    request: proto::UpdateBuffer,
2332    response: Response<proto::UpdateBuffer>,
2333    session: Session,
2334) -> Result<()> {
2335    let project_id = ProjectId::from_proto(request.project_id);
2336    let mut capability = Capability::ReadOnly;
2337
2338    for op in request.operations.iter() {
2339        match op.variant {
2340            None | Some(proto::operation::Variant::UpdateSelections(_)) => {}
2341            Some(_) => capability = Capability::ReadWrite,
2342        }
2343    }
2344
2345    let host = {
2346        let guard = session
2347            .db()
2348            .await
2349            .connections_for_buffer_update(project_id, session.connection_id, capability)
2350            .await?;
2351
2352        let (host, guests) = &*guard;
2353
2354        broadcast(
2355            Some(session.connection_id),
2356            guests.clone(),
2357            |connection_id| {
2358                session
2359                    .peer
2360                    .forward_send(session.connection_id, connection_id, request.clone())
2361            },
2362        );
2363
2364        *host
2365    };
2366
2367    if host != session.connection_id {
2368        session
2369            .peer
2370            .forward_request(session.connection_id, host, request.clone())
2371            .await?;
2372    }
2373
2374    response.send(proto::Ack {})?;
2375    Ok(())
2376}
2377
2378async fn update_context(message: proto::UpdateContext, session: Session) -> Result<()> {
2379    let project_id = ProjectId::from_proto(message.project_id);
2380
2381    let operation = message.operation.as_ref().context("invalid operation")?;
2382    let capability = match operation.variant.as_ref() {
2383        Some(proto::context_operation::Variant::BufferOperation(buffer_op)) => {
2384            if let Some(buffer_op) = buffer_op.operation.as_ref() {
2385                match buffer_op.variant {
2386                    None | Some(proto::operation::Variant::UpdateSelections(_)) => {
2387                        Capability::ReadOnly
2388                    }
2389                    _ => Capability::ReadWrite,
2390                }
2391            } else {
2392                Capability::ReadWrite
2393            }
2394        }
2395        Some(_) => Capability::ReadWrite,
2396        None => Capability::ReadOnly,
2397    };
2398
2399    let guard = session
2400        .db()
2401        .await
2402        .connections_for_buffer_update(project_id, session.connection_id, capability)
2403        .await?;
2404
2405    let (host, guests) = &*guard;
2406
2407    broadcast(
2408        Some(session.connection_id),
2409        guests.iter().chain([host]).copied(),
2410        |connection_id| {
2411            session
2412                .peer
2413                .forward_send(session.connection_id, connection_id, message.clone())
2414        },
2415    );
2416
2417    Ok(())
2418}
2419
2420/// Notify other participants that a project has been updated.
2421async fn broadcast_project_message_from_host<T: EntityMessage<Entity = ShareProject>>(
2422    request: T,
2423    session: Session,
2424) -> Result<()> {
2425    let project_id = ProjectId::from_proto(request.remote_entity_id());
2426    let project_connection_ids = session
2427        .db()
2428        .await
2429        .project_connection_ids(project_id, session.connection_id, false)
2430        .await?;
2431
2432    broadcast(
2433        Some(session.connection_id),
2434        project_connection_ids.iter().copied(),
2435        |connection_id| {
2436            session
2437                .peer
2438                .forward_send(session.connection_id, connection_id, request.clone())
2439        },
2440    );
2441    Ok(())
2442}
2443
2444/// Start following another user in a call.
2445async fn follow(
2446    request: proto::Follow,
2447    response: Response<proto::Follow>,
2448    session: Session,
2449) -> Result<()> {
2450    let room_id = RoomId::from_proto(request.room_id);
2451    let project_id = request.project_id.map(ProjectId::from_proto);
2452    let leader_id = request.leader_id.context("invalid leader id")?.into();
2453    let follower_id = session.connection_id;
2454
2455    session
2456        .db()
2457        .await
2458        .check_room_participants(room_id, leader_id, session.connection_id)
2459        .await?;
2460
2461    let response_payload = session
2462        .peer
2463        .forward_request(session.connection_id, leader_id, request)
2464        .await?;
2465    response.send(response_payload)?;
2466
2467    if let Some(project_id) = project_id {
2468        let room = session
2469            .db()
2470            .await
2471            .follow(room_id, project_id, leader_id, follower_id)
2472            .await?;
2473        room_updated(&room, &session.peer);
2474    }
2475
2476    Ok(())
2477}
2478
2479/// Stop following another user in a call.
2480async fn unfollow(request: proto::Unfollow, session: Session) -> Result<()> {
2481    let room_id = RoomId::from_proto(request.room_id);
2482    let project_id = request.project_id.map(ProjectId::from_proto);
2483    let leader_id = request.leader_id.context("invalid leader id")?.into();
2484    let follower_id = session.connection_id;
2485
2486    session
2487        .db()
2488        .await
2489        .check_room_participants(room_id, leader_id, session.connection_id)
2490        .await?;
2491
2492    session
2493        .peer
2494        .forward_send(session.connection_id, leader_id, request)?;
2495
2496    if let Some(project_id) = project_id {
2497        let room = session
2498            .db()
2499            .await
2500            .unfollow(room_id, project_id, leader_id, follower_id)
2501            .await?;
2502        room_updated(&room, &session.peer);
2503    }
2504
2505    Ok(())
2506}
2507
2508/// Notify everyone following you of your current location.
2509async fn update_followers(request: proto::UpdateFollowers, session: Session) -> Result<()> {
2510    let room_id = RoomId::from_proto(request.room_id);
2511    let database = session.db.lock().await;
2512
2513    let connection_ids = if let Some(project_id) = request.project_id {
2514        let project_id = ProjectId::from_proto(project_id);
2515        database
2516            .project_connection_ids(project_id, session.connection_id, true)
2517            .await?
2518    } else {
2519        database
2520            .room_connection_ids(room_id, session.connection_id)
2521            .await?
2522    };
2523
2524    // For now, don't send view update messages back to that view's current leader.
2525    let peer_id_to_omit = request.variant.as_ref().and_then(|variant| match variant {
2526        proto::update_followers::Variant::UpdateView(payload) => payload.leader_id,
2527        _ => None,
2528    });
2529
2530    for connection_id in connection_ids.iter().cloned() {
2531        if Some(connection_id.into()) != peer_id_to_omit && connection_id != session.connection_id {
2532            session
2533                .peer
2534                .forward_send(session.connection_id, connection_id, request.clone())?;
2535        }
2536    }
2537    Ok(())
2538}
2539
2540/// Get public data about users.
2541async fn get_users(
2542    request: proto::GetUsers,
2543    response: Response<proto::GetUsers>,
2544    session: Session,
2545) -> Result<()> {
2546    let user_ids = request
2547        .user_ids
2548        .into_iter()
2549        .map(UserId::from_proto)
2550        .collect();
2551    let users = session
2552        .db()
2553        .await
2554        .get_users_by_ids(user_ids)
2555        .await?
2556        .into_iter()
2557        .map(|user| proto::User {
2558            id: user.id.to_proto(),
2559            avatar_url: format!("https://github.com/{}.png?size=128", user.github_login),
2560            github_login: user.github_login,
2561            name: user.name,
2562        })
2563        .collect();
2564    response.send(proto::UsersResponse { users })?;
2565    Ok(())
2566}
2567
2568/// Search for users (to invite) buy Github login
2569async fn fuzzy_search_users(
2570    request: proto::FuzzySearchUsers,
2571    response: Response<proto::FuzzySearchUsers>,
2572    session: Session,
2573) -> Result<()> {
2574    let query = request.query;
2575    let users = match query.len() {
2576        0 => vec![],
2577        1 | 2 => session
2578            .db()
2579            .await
2580            .get_user_by_github_login(&query)
2581            .await?
2582            .into_iter()
2583            .collect(),
2584        _ => session.db().await.fuzzy_search_users(&query, 10).await?,
2585    };
2586    let users = users
2587        .into_iter()
2588        .filter(|user| user.id != session.user_id())
2589        .map(|user| proto::User {
2590            id: user.id.to_proto(),
2591            avatar_url: format!("https://github.com/{}.png?size=128", user.github_login),
2592            github_login: user.github_login,
2593            name: user.name,
2594        })
2595        .collect();
2596    response.send(proto::UsersResponse { users })?;
2597    Ok(())
2598}
2599
2600/// Send a contact request to another user.
2601async fn request_contact(
2602    request: proto::RequestContact,
2603    response: Response<proto::RequestContact>,
2604    session: Session,
2605) -> Result<()> {
2606    let requester_id = session.user_id();
2607    let responder_id = UserId::from_proto(request.responder_id);
2608    if requester_id == responder_id {
2609        return Err(anyhow!("cannot add yourself as a contact"))?;
2610    }
2611
2612    let notifications = session
2613        .db()
2614        .await
2615        .send_contact_request(requester_id, responder_id)
2616        .await?;
2617
2618    // Update outgoing contact requests of requester
2619    let mut update = proto::UpdateContacts::default();
2620    update.outgoing_requests.push(responder_id.to_proto());
2621    for connection_id in session
2622        .connection_pool()
2623        .await
2624        .user_connection_ids(requester_id)
2625    {
2626        session.peer.send(connection_id, update.clone())?;
2627    }
2628
2629    // Update incoming contact requests of responder
2630    let mut update = proto::UpdateContacts::default();
2631    update
2632        .incoming_requests
2633        .push(proto::IncomingContactRequest {
2634            requester_id: requester_id.to_proto(),
2635        });
2636    let connection_pool = session.connection_pool().await;
2637    for connection_id in connection_pool.user_connection_ids(responder_id) {
2638        session.peer.send(connection_id, update.clone())?;
2639    }
2640
2641    send_notifications(&connection_pool, &session.peer, notifications);
2642
2643    response.send(proto::Ack {})?;
2644    Ok(())
2645}
2646
2647/// Accept or decline a contact request
2648async fn respond_to_contact_request(
2649    request: proto::RespondToContactRequest,
2650    response: Response<proto::RespondToContactRequest>,
2651    session: Session,
2652) -> Result<()> {
2653    let responder_id = session.user_id();
2654    let requester_id = UserId::from_proto(request.requester_id);
2655    let db = session.db().await;
2656    if request.response == proto::ContactRequestResponse::Dismiss as i32 {
2657        db.dismiss_contact_notification(responder_id, requester_id)
2658            .await?;
2659    } else {
2660        let accept = request.response == proto::ContactRequestResponse::Accept as i32;
2661
2662        let notifications = db
2663            .respond_to_contact_request(responder_id, requester_id, accept)
2664            .await?;
2665        let requester_busy = db.is_user_busy(requester_id).await?;
2666        let responder_busy = db.is_user_busy(responder_id).await?;
2667
2668        let pool = session.connection_pool().await;
2669        // Update responder with new contact
2670        let mut update = proto::UpdateContacts::default();
2671        if accept {
2672            update
2673                .contacts
2674                .push(contact_for_user(requester_id, requester_busy, &pool));
2675        }
2676        update
2677            .remove_incoming_requests
2678            .push(requester_id.to_proto());
2679        for connection_id in pool.user_connection_ids(responder_id) {
2680            session.peer.send(connection_id, update.clone())?;
2681        }
2682
2683        // Update requester with new contact
2684        let mut update = proto::UpdateContacts::default();
2685        if accept {
2686            update
2687                .contacts
2688                .push(contact_for_user(responder_id, responder_busy, &pool));
2689        }
2690        update
2691            .remove_outgoing_requests
2692            .push(responder_id.to_proto());
2693
2694        for connection_id in pool.user_connection_ids(requester_id) {
2695            session.peer.send(connection_id, update.clone())?;
2696        }
2697
2698        send_notifications(&pool, &session.peer, notifications);
2699    }
2700
2701    response.send(proto::Ack {})?;
2702    Ok(())
2703}
2704
2705/// Remove a contact.
2706async fn remove_contact(
2707    request: proto::RemoveContact,
2708    response: Response<proto::RemoveContact>,
2709    session: Session,
2710) -> Result<()> {
2711    let requester_id = session.user_id();
2712    let responder_id = UserId::from_proto(request.user_id);
2713    let db = session.db().await;
2714    let (contact_accepted, deleted_notification_id) =
2715        db.remove_contact(requester_id, responder_id).await?;
2716
2717    let pool = session.connection_pool().await;
2718    // Update outgoing contact requests of requester
2719    let mut update = proto::UpdateContacts::default();
2720    if contact_accepted {
2721        update.remove_contacts.push(responder_id.to_proto());
2722    } else {
2723        update
2724            .remove_outgoing_requests
2725            .push(responder_id.to_proto());
2726    }
2727    for connection_id in pool.user_connection_ids(requester_id) {
2728        session.peer.send(connection_id, update.clone())?;
2729    }
2730
2731    // Update incoming contact requests of responder
2732    let mut update = proto::UpdateContacts::default();
2733    if contact_accepted {
2734        update.remove_contacts.push(requester_id.to_proto());
2735    } else {
2736        update
2737            .remove_incoming_requests
2738            .push(requester_id.to_proto());
2739    }
2740    for connection_id in pool.user_connection_ids(responder_id) {
2741        session.peer.send(connection_id, update.clone())?;
2742        if let Some(notification_id) = deleted_notification_id {
2743            session.peer.send(
2744                connection_id,
2745                proto::DeleteNotification {
2746                    notification_id: notification_id.to_proto(),
2747                },
2748            )?;
2749        }
2750    }
2751
2752    response.send(proto::Ack {})?;
2753    Ok(())
2754}
2755
2756fn should_auto_subscribe_to_channels(version: ZedVersion) -> bool {
2757    version.0.minor() < 139
2758}
2759
2760async fn current_plan(db: &Arc<Database>, user_id: UserId, is_staff: bool) -> Result<proto::Plan> {
2761    if is_staff {
2762        return Ok(proto::Plan::ZedPro);
2763    }
2764
2765    let subscription = db.get_active_billing_subscription(user_id).await?;
2766    let subscription_kind = subscription.and_then(|subscription| subscription.kind);
2767
2768    let plan = if let Some(subscription_kind) = subscription_kind {
2769        match subscription_kind {
2770            SubscriptionKind::ZedPro => proto::Plan::ZedPro,
2771            SubscriptionKind::ZedProTrial => proto::Plan::ZedProTrial,
2772            SubscriptionKind::ZedFree => proto::Plan::Free,
2773        }
2774    } else {
2775        proto::Plan::Free
2776    };
2777
2778    Ok(plan)
2779}
2780
2781async fn make_update_user_plan_message(
2782    user: &User,
2783    is_staff: bool,
2784    db: &Arc<Database>,
2785    llm_db: Option<Arc<LlmDatabase>>,
2786) -> Result<proto::UpdateUserPlan> {
2787    let feature_flags = db.get_user_flags(user.id).await?;
2788    let plan = current_plan(db, user.id, is_staff).await?;
2789    let billing_customer = db.get_billing_customer_by_user_id(user.id).await?;
2790    let billing_preferences = db.get_billing_preferences(user.id).await?;
2791
2792    let (subscription_period, usage) = if let Some(llm_db) = llm_db {
2793        let subscription = db.get_active_billing_subscription(user.id).await?;
2794
2795        let subscription_period =
2796            crate::db::billing_subscription::Model::current_period(subscription, is_staff);
2797
2798        let usage = if let Some((period_start_at, period_end_at)) = subscription_period {
2799            llm_db
2800                .get_subscription_usage_for_period(user.id, period_start_at, period_end_at)
2801                .await?
2802        } else {
2803            None
2804        };
2805
2806        (subscription_period, usage)
2807    } else {
2808        (None, None)
2809    };
2810
2811    let bypass_account_age_check = feature_flags
2812        .iter()
2813        .any(|flag| flag == BYPASS_ACCOUNT_AGE_CHECK_FEATURE_FLAG);
2814    let account_too_young = !matches!(plan, proto::Plan::ZedPro)
2815        && !bypass_account_age_check
2816        && user.account_age() < MIN_ACCOUNT_AGE_FOR_LLM_USE;
2817
2818    Ok(proto::UpdateUserPlan {
2819        plan: plan.into(),
2820        trial_started_at: billing_customer
2821            .as_ref()
2822            .and_then(|billing_customer| billing_customer.trial_started_at)
2823            .map(|trial_started_at| trial_started_at.and_utc().timestamp() as u64),
2824        is_usage_based_billing_enabled: if is_staff {
2825            Some(true)
2826        } else {
2827            billing_preferences.map(|preferences| preferences.model_request_overages_enabled)
2828        },
2829        subscription_period: subscription_period.map(|(started_at, ended_at)| {
2830            proto::SubscriptionPeriod {
2831                started_at: started_at.timestamp() as u64,
2832                ended_at: ended_at.timestamp() as u64,
2833            }
2834        }),
2835        account_too_young: Some(account_too_young),
2836        has_overdue_invoices: billing_customer
2837            .map(|billing_customer| billing_customer.has_overdue_invoices),
2838        usage: usage.map(|usage| {
2839            let plan = match plan {
2840                proto::Plan::Free => zed_llm_client::Plan::ZedFree,
2841                proto::Plan::ZedPro => zed_llm_client::Plan::ZedPro,
2842                proto::Plan::ZedProTrial => zed_llm_client::Plan::ZedProTrial,
2843            };
2844
2845            let model_requests_limit = match plan.model_requests_limit() {
2846                zed_llm_client::UsageLimit::Limited(limit) => {
2847                    let limit = if plan == zed_llm_client::Plan::ZedProTrial
2848                        && feature_flags
2849                            .iter()
2850                            .any(|flag| flag == AGENT_EXTENDED_TRIAL_FEATURE_FLAG)
2851                    {
2852                        1_000
2853                    } else {
2854                        limit
2855                    };
2856
2857                    zed_llm_client::UsageLimit::Limited(limit)
2858                }
2859                zed_llm_client::UsageLimit::Unlimited => zed_llm_client::UsageLimit::Unlimited,
2860            };
2861
2862            proto::SubscriptionUsage {
2863                model_requests_usage_amount: usage.model_requests as u32,
2864                model_requests_usage_limit: Some(proto::UsageLimit {
2865                    variant: Some(match model_requests_limit {
2866                        zed_llm_client::UsageLimit::Limited(limit) => {
2867                            proto::usage_limit::Variant::Limited(proto::usage_limit::Limited {
2868                                limit: limit as u32,
2869                            })
2870                        }
2871                        zed_llm_client::UsageLimit::Unlimited => {
2872                            proto::usage_limit::Variant::Unlimited(proto::usage_limit::Unlimited {})
2873                        }
2874                    }),
2875                }),
2876                edit_predictions_usage_amount: usage.edit_predictions as u32,
2877                edit_predictions_usage_limit: Some(proto::UsageLimit {
2878                    variant: Some(match plan.edit_predictions_limit() {
2879                        zed_llm_client::UsageLimit::Limited(limit) => {
2880                            proto::usage_limit::Variant::Limited(proto::usage_limit::Limited {
2881                                limit: limit as u32,
2882                            })
2883                        }
2884                        zed_llm_client::UsageLimit::Unlimited => {
2885                            proto::usage_limit::Variant::Unlimited(proto::usage_limit::Unlimited {})
2886                        }
2887                    }),
2888                }),
2889            }
2890        }),
2891    })
2892}
2893
2894async fn update_user_plan(session: &Session) -> Result<()> {
2895    let db = session.db().await;
2896
2897    let update_user_plan = make_update_user_plan_message(
2898        session.principal.user(),
2899        session.is_staff(),
2900        &db.0,
2901        session.app_state.llm_db.clone(),
2902    )
2903    .await?;
2904
2905    session
2906        .peer
2907        .send(session.connection_id, update_user_plan)
2908        .trace_err();
2909
2910    Ok(())
2911}
2912
2913async fn subscribe_to_channels(_: proto::SubscribeToChannels, session: Session) -> Result<()> {
2914    subscribe_user_to_channels(session.user_id(), &session).await?;
2915    Ok(())
2916}
2917
2918async fn subscribe_user_to_channels(user_id: UserId, session: &Session) -> Result<(), Error> {
2919    let channels_for_user = session.db().await.get_channels_for_user(user_id).await?;
2920    let mut pool = session.connection_pool().await;
2921    for membership in &channels_for_user.channel_memberships {
2922        pool.subscribe_to_channel(user_id, membership.channel_id, membership.role)
2923    }
2924    session.peer.send(
2925        session.connection_id,
2926        build_update_user_channels(&channels_for_user),
2927    )?;
2928    session.peer.send(
2929        session.connection_id,
2930        build_channels_update(channels_for_user),
2931    )?;
2932    Ok(())
2933}
2934
2935/// Creates a new channel.
2936async fn create_channel(
2937    request: proto::CreateChannel,
2938    response: Response<proto::CreateChannel>,
2939    session: Session,
2940) -> Result<()> {
2941    let db = session.db().await;
2942
2943    let parent_id = request.parent_id.map(ChannelId::from_proto);
2944    let (channel, membership) = db
2945        .create_channel(&request.name, parent_id, session.user_id())
2946        .await?;
2947
2948    let root_id = channel.root_id();
2949    let channel = Channel::from_model(channel);
2950
2951    response.send(proto::CreateChannelResponse {
2952        channel: Some(channel.to_proto()),
2953        parent_id: request.parent_id,
2954    })?;
2955
2956    let mut connection_pool = session.connection_pool().await;
2957    if let Some(membership) = membership {
2958        connection_pool.subscribe_to_channel(
2959            membership.user_id,
2960            membership.channel_id,
2961            membership.role,
2962        );
2963        let update = proto::UpdateUserChannels {
2964            channel_memberships: vec![proto::ChannelMembership {
2965                channel_id: membership.channel_id.to_proto(),
2966                role: membership.role.into(),
2967            }],
2968            ..Default::default()
2969        };
2970        for connection_id in connection_pool.user_connection_ids(membership.user_id) {
2971            session.peer.send(connection_id, update.clone())?;
2972        }
2973    }
2974
2975    for (connection_id, role) in connection_pool.channel_connection_ids(root_id) {
2976        if !role.can_see_channel(channel.visibility) {
2977            continue;
2978        }
2979
2980        let update = proto::UpdateChannels {
2981            channels: vec![channel.to_proto()],
2982            ..Default::default()
2983        };
2984        session.peer.send(connection_id, update.clone())?;
2985    }
2986
2987    Ok(())
2988}
2989
2990/// Delete a channel
2991async fn delete_channel(
2992    request: proto::DeleteChannel,
2993    response: Response<proto::DeleteChannel>,
2994    session: Session,
2995) -> Result<()> {
2996    let db = session.db().await;
2997
2998    let channel_id = request.channel_id;
2999    let (root_channel, removed_channels) = db
3000        .delete_channel(ChannelId::from_proto(channel_id), session.user_id())
3001        .await?;
3002    response.send(proto::Ack {})?;
3003
3004    // Notify members of removed channels
3005    let mut update = proto::UpdateChannels::default();
3006    update
3007        .delete_channels
3008        .extend(removed_channels.into_iter().map(|id| id.to_proto()));
3009
3010    let connection_pool = session.connection_pool().await;
3011    for (connection_id, _) in connection_pool.channel_connection_ids(root_channel) {
3012        session.peer.send(connection_id, update.clone())?;
3013    }
3014
3015    Ok(())
3016}
3017
3018/// Invite someone to join a channel.
3019async fn invite_channel_member(
3020    request: proto::InviteChannelMember,
3021    response: Response<proto::InviteChannelMember>,
3022    session: Session,
3023) -> Result<()> {
3024    let db = session.db().await;
3025    let channel_id = ChannelId::from_proto(request.channel_id);
3026    let invitee_id = UserId::from_proto(request.user_id);
3027    let InviteMemberResult {
3028        channel,
3029        notifications,
3030    } = db
3031        .invite_channel_member(
3032            channel_id,
3033            invitee_id,
3034            session.user_id(),
3035            request.role().into(),
3036        )
3037        .await?;
3038
3039    let update = proto::UpdateChannels {
3040        channel_invitations: vec![channel.to_proto()],
3041        ..Default::default()
3042    };
3043
3044    let connection_pool = session.connection_pool().await;
3045    for connection_id in connection_pool.user_connection_ids(invitee_id) {
3046        session.peer.send(connection_id, update.clone())?;
3047    }
3048
3049    send_notifications(&connection_pool, &session.peer, notifications);
3050
3051    response.send(proto::Ack {})?;
3052    Ok(())
3053}
3054
3055/// remove someone from a channel
3056async fn remove_channel_member(
3057    request: proto::RemoveChannelMember,
3058    response: Response<proto::RemoveChannelMember>,
3059    session: Session,
3060) -> Result<()> {
3061    let db = session.db().await;
3062    let channel_id = ChannelId::from_proto(request.channel_id);
3063    let member_id = UserId::from_proto(request.user_id);
3064
3065    let RemoveChannelMemberResult {
3066        membership_update,
3067        notification_id,
3068    } = db
3069        .remove_channel_member(channel_id, member_id, session.user_id())
3070        .await?;
3071
3072    let mut connection_pool = session.connection_pool().await;
3073    notify_membership_updated(
3074        &mut connection_pool,
3075        membership_update,
3076        member_id,
3077        &session.peer,
3078    );
3079    for connection_id in connection_pool.user_connection_ids(member_id) {
3080        if let Some(notification_id) = notification_id {
3081            session
3082                .peer
3083                .send(
3084                    connection_id,
3085                    proto::DeleteNotification {
3086                        notification_id: notification_id.to_proto(),
3087                    },
3088                )
3089                .trace_err();
3090        }
3091    }
3092
3093    response.send(proto::Ack {})?;
3094    Ok(())
3095}
3096
3097/// Toggle the channel between public and private.
3098/// Care is taken to maintain the invariant that public channels only descend from public channels,
3099/// (though members-only channels can appear at any point in the hierarchy).
3100async fn set_channel_visibility(
3101    request: proto::SetChannelVisibility,
3102    response: Response<proto::SetChannelVisibility>,
3103    session: Session,
3104) -> Result<()> {
3105    let db = session.db().await;
3106    let channel_id = ChannelId::from_proto(request.channel_id);
3107    let visibility = request.visibility().into();
3108
3109    let channel_model = db
3110        .set_channel_visibility(channel_id, visibility, session.user_id())
3111        .await?;
3112    let root_id = channel_model.root_id();
3113    let channel = Channel::from_model(channel_model);
3114
3115    let mut connection_pool = session.connection_pool().await;
3116    for (user_id, role) in connection_pool
3117        .channel_user_ids(root_id)
3118        .collect::<Vec<_>>()
3119        .into_iter()
3120    {
3121        let update = if role.can_see_channel(channel.visibility) {
3122            connection_pool.subscribe_to_channel(user_id, channel_id, role);
3123            proto::UpdateChannels {
3124                channels: vec![channel.to_proto()],
3125                ..Default::default()
3126            }
3127        } else {
3128            connection_pool.unsubscribe_from_channel(&user_id, &channel_id);
3129            proto::UpdateChannels {
3130                delete_channels: vec![channel.id.to_proto()],
3131                ..Default::default()
3132            }
3133        };
3134
3135        for connection_id in connection_pool.user_connection_ids(user_id) {
3136            session.peer.send(connection_id, update.clone())?;
3137        }
3138    }
3139
3140    response.send(proto::Ack {})?;
3141    Ok(())
3142}
3143
3144/// Alter the role for a user in the channel.
3145async fn set_channel_member_role(
3146    request: proto::SetChannelMemberRole,
3147    response: Response<proto::SetChannelMemberRole>,
3148    session: Session,
3149) -> Result<()> {
3150    let db = session.db().await;
3151    let channel_id = ChannelId::from_proto(request.channel_id);
3152    let member_id = UserId::from_proto(request.user_id);
3153    let result = db
3154        .set_channel_member_role(
3155            channel_id,
3156            session.user_id(),
3157            member_id,
3158            request.role().into(),
3159        )
3160        .await?;
3161
3162    match result {
3163        db::SetMemberRoleResult::MembershipUpdated(membership_update) => {
3164            let mut connection_pool = session.connection_pool().await;
3165            notify_membership_updated(
3166                &mut connection_pool,
3167                membership_update,
3168                member_id,
3169                &session.peer,
3170            )
3171        }
3172        db::SetMemberRoleResult::InviteUpdated(channel) => {
3173            let update = proto::UpdateChannels {
3174                channel_invitations: vec![channel.to_proto()],
3175                ..Default::default()
3176            };
3177
3178            for connection_id in session
3179                .connection_pool()
3180                .await
3181                .user_connection_ids(member_id)
3182            {
3183                session.peer.send(connection_id, update.clone())?;
3184            }
3185        }
3186    }
3187
3188    response.send(proto::Ack {})?;
3189    Ok(())
3190}
3191
3192/// Change the name of a channel
3193async fn rename_channel(
3194    request: proto::RenameChannel,
3195    response: Response<proto::RenameChannel>,
3196    session: Session,
3197) -> Result<()> {
3198    let db = session.db().await;
3199    let channel_id = ChannelId::from_proto(request.channel_id);
3200    let channel_model = db
3201        .rename_channel(channel_id, session.user_id(), &request.name)
3202        .await?;
3203    let root_id = channel_model.root_id();
3204    let channel = Channel::from_model(channel_model);
3205
3206    response.send(proto::RenameChannelResponse {
3207        channel: Some(channel.to_proto()),
3208    })?;
3209
3210    let connection_pool = session.connection_pool().await;
3211    let update = proto::UpdateChannels {
3212        channels: vec![channel.to_proto()],
3213        ..Default::default()
3214    };
3215    for (connection_id, role) in connection_pool.channel_connection_ids(root_id) {
3216        if role.can_see_channel(channel.visibility) {
3217            session.peer.send(connection_id, update.clone())?;
3218        }
3219    }
3220
3221    Ok(())
3222}
3223
3224/// Move a channel to a new parent.
3225async fn move_channel(
3226    request: proto::MoveChannel,
3227    response: Response<proto::MoveChannel>,
3228    session: Session,
3229) -> Result<()> {
3230    let channel_id = ChannelId::from_proto(request.channel_id);
3231    let to = ChannelId::from_proto(request.to);
3232
3233    let (root_id, channels) = session
3234        .db()
3235        .await
3236        .move_channel(channel_id, to, session.user_id())
3237        .await?;
3238
3239    let connection_pool = session.connection_pool().await;
3240    for (connection_id, role) in connection_pool.channel_connection_ids(root_id) {
3241        let channels = channels
3242            .iter()
3243            .filter_map(|channel| {
3244                if role.can_see_channel(channel.visibility) {
3245                    Some(channel.to_proto())
3246                } else {
3247                    None
3248                }
3249            })
3250            .collect::<Vec<_>>();
3251        if channels.is_empty() {
3252            continue;
3253        }
3254
3255        let update = proto::UpdateChannels {
3256            channels,
3257            ..Default::default()
3258        };
3259
3260        session.peer.send(connection_id, update.clone())?;
3261    }
3262
3263    response.send(Ack {})?;
3264    Ok(())
3265}
3266
3267async fn reorder_channel(
3268    request: proto::ReorderChannel,
3269    response: Response<proto::ReorderChannel>,
3270    session: Session,
3271) -> Result<()> {
3272    let channel_id = ChannelId::from_proto(request.channel_id);
3273    let direction = request.direction();
3274
3275    let updated_channels = session
3276        .db()
3277        .await
3278        .reorder_channel(channel_id, direction, session.user_id())
3279        .await?;
3280
3281    if let Some(root_id) = updated_channels.first().map(|channel| channel.root_id()) {
3282        let connection_pool = session.connection_pool().await;
3283        for (connection_id, role) in connection_pool.channel_connection_ids(root_id) {
3284            let channels = updated_channels
3285                .iter()
3286                .filter_map(|channel| {
3287                    if role.can_see_channel(channel.visibility) {
3288                        Some(channel.to_proto())
3289                    } else {
3290                        None
3291                    }
3292                })
3293                .collect::<Vec<_>>();
3294
3295            if channels.is_empty() {
3296                continue;
3297            }
3298
3299            let update = proto::UpdateChannels {
3300                channels,
3301                ..Default::default()
3302            };
3303
3304            session.peer.send(connection_id, update.clone())?;
3305        }
3306    }
3307
3308    response.send(Ack {})?;
3309    Ok(())
3310}
3311
3312/// Get the list of channel members
3313async fn get_channel_members(
3314    request: proto::GetChannelMembers,
3315    response: Response<proto::GetChannelMembers>,
3316    session: Session,
3317) -> Result<()> {
3318    let db = session.db().await;
3319    let channel_id = ChannelId::from_proto(request.channel_id);
3320    let limit = if request.limit == 0 {
3321        u16::MAX as u64
3322    } else {
3323        request.limit
3324    };
3325    let (members, users) = db
3326        .get_channel_participant_details(channel_id, &request.query, limit, session.user_id())
3327        .await?;
3328    response.send(proto::GetChannelMembersResponse { members, users })?;
3329    Ok(())
3330}
3331
3332/// Accept or decline a channel invitation.
3333async fn respond_to_channel_invite(
3334    request: proto::RespondToChannelInvite,
3335    response: Response<proto::RespondToChannelInvite>,
3336    session: Session,
3337) -> Result<()> {
3338    let db = session.db().await;
3339    let channel_id = ChannelId::from_proto(request.channel_id);
3340    let RespondToChannelInvite {
3341        membership_update,
3342        notifications,
3343    } = db
3344        .respond_to_channel_invite(channel_id, session.user_id(), request.accept)
3345        .await?;
3346
3347    let mut connection_pool = session.connection_pool().await;
3348    if let Some(membership_update) = membership_update {
3349        notify_membership_updated(
3350            &mut connection_pool,
3351            membership_update,
3352            session.user_id(),
3353            &session.peer,
3354        );
3355    } else {
3356        let update = proto::UpdateChannels {
3357            remove_channel_invitations: vec![channel_id.to_proto()],
3358            ..Default::default()
3359        };
3360
3361        for connection_id in connection_pool.user_connection_ids(session.user_id()) {
3362            session.peer.send(connection_id, update.clone())?;
3363        }
3364    };
3365
3366    send_notifications(&connection_pool, &session.peer, notifications);
3367
3368    response.send(proto::Ack {})?;
3369
3370    Ok(())
3371}
3372
3373/// Join the channels' room
3374async fn join_channel(
3375    request: proto::JoinChannel,
3376    response: Response<proto::JoinChannel>,
3377    session: Session,
3378) -> Result<()> {
3379    let channel_id = ChannelId::from_proto(request.channel_id);
3380    join_channel_internal(channel_id, Box::new(response), session).await
3381}
3382
3383trait JoinChannelInternalResponse {
3384    fn send(self, result: proto::JoinRoomResponse) -> Result<()>;
3385}
3386impl JoinChannelInternalResponse for Response<proto::JoinChannel> {
3387    fn send(self, result: proto::JoinRoomResponse) -> Result<()> {
3388        Response::<proto::JoinChannel>::send(self, result)
3389    }
3390}
3391impl JoinChannelInternalResponse for Response<proto::JoinRoom> {
3392    fn send(self, result: proto::JoinRoomResponse) -> Result<()> {
3393        Response::<proto::JoinRoom>::send(self, result)
3394    }
3395}
3396
3397async fn join_channel_internal(
3398    channel_id: ChannelId,
3399    response: Box<impl JoinChannelInternalResponse>,
3400    session: Session,
3401) -> Result<()> {
3402    let joined_room = {
3403        let mut db = session.db().await;
3404        // If zed quits without leaving the room, and the user re-opens zed before the
3405        // RECONNECT_TIMEOUT, we need to make sure that we kick the user out of the previous
3406        // room they were in.
3407        if let Some(connection) = db.stale_room_connection(session.user_id()).await? {
3408            tracing::info!(
3409                stale_connection_id = %connection,
3410                "cleaning up stale connection",
3411            );
3412            drop(db);
3413            leave_room_for_session(&session, connection).await?;
3414            db = session.db().await;
3415        }
3416
3417        let (joined_room, membership_updated, role) = db
3418            .join_channel(channel_id, session.user_id(), session.connection_id)
3419            .await?;
3420
3421        let live_kit_connection_info =
3422            session
3423                .app_state
3424                .livekit_client
3425                .as_ref()
3426                .and_then(|live_kit| {
3427                    let (can_publish, token) = if role == ChannelRole::Guest {
3428                        (
3429                            false,
3430                            live_kit
3431                                .guest_token(
3432                                    &joined_room.room.livekit_room,
3433                                    &session.user_id().to_string(),
3434                                )
3435                                .trace_err()?,
3436                        )
3437                    } else {
3438                        (
3439                            true,
3440                            live_kit
3441                                .room_token(
3442                                    &joined_room.room.livekit_room,
3443                                    &session.user_id().to_string(),
3444                                )
3445                                .trace_err()?,
3446                        )
3447                    };
3448
3449                    Some(LiveKitConnectionInfo {
3450                        server_url: live_kit.url().into(),
3451                        token,
3452                        can_publish,
3453                    })
3454                });
3455
3456        response.send(proto::JoinRoomResponse {
3457            room: Some(joined_room.room.clone()),
3458            channel_id: joined_room
3459                .channel
3460                .as_ref()
3461                .map(|channel| channel.id.to_proto()),
3462            live_kit_connection_info,
3463        })?;
3464
3465        let mut connection_pool = session.connection_pool().await;
3466        if let Some(membership_updated) = membership_updated {
3467            notify_membership_updated(
3468                &mut connection_pool,
3469                membership_updated,
3470                session.user_id(),
3471                &session.peer,
3472            );
3473        }
3474
3475        room_updated(&joined_room.room, &session.peer);
3476
3477        joined_room
3478    };
3479
3480    channel_updated(
3481        &joined_room.channel.context("channel not returned")?,
3482        &joined_room.room,
3483        &session.peer,
3484        &*session.connection_pool().await,
3485    );
3486
3487    update_user_contacts(session.user_id(), &session).await?;
3488    Ok(())
3489}
3490
3491/// Start editing the channel notes
3492async fn join_channel_buffer(
3493    request: proto::JoinChannelBuffer,
3494    response: Response<proto::JoinChannelBuffer>,
3495    session: Session,
3496) -> Result<()> {
3497    let db = session.db().await;
3498    let channel_id = ChannelId::from_proto(request.channel_id);
3499
3500    let open_response = db
3501        .join_channel_buffer(channel_id, session.user_id(), session.connection_id)
3502        .await?;
3503
3504    let collaborators = open_response.collaborators.clone();
3505    response.send(open_response)?;
3506
3507    let update = UpdateChannelBufferCollaborators {
3508        channel_id: channel_id.to_proto(),
3509        collaborators: collaborators.clone(),
3510    };
3511    channel_buffer_updated(
3512        session.connection_id,
3513        collaborators
3514            .iter()
3515            .filter_map(|collaborator| Some(collaborator.peer_id?.into())),
3516        &update,
3517        &session.peer,
3518    );
3519
3520    Ok(())
3521}
3522
3523/// Edit the channel notes
3524async fn update_channel_buffer(
3525    request: proto::UpdateChannelBuffer,
3526    session: Session,
3527) -> Result<()> {
3528    let db = session.db().await;
3529    let channel_id = ChannelId::from_proto(request.channel_id);
3530
3531    let (collaborators, epoch, version) = db
3532        .update_channel_buffer(channel_id, session.user_id(), &request.operations)
3533        .await?;
3534
3535    channel_buffer_updated(
3536        session.connection_id,
3537        collaborators.clone(),
3538        &proto::UpdateChannelBuffer {
3539            channel_id: channel_id.to_proto(),
3540            operations: request.operations,
3541        },
3542        &session.peer,
3543    );
3544
3545    let pool = &*session.connection_pool().await;
3546
3547    let non_collaborators =
3548        pool.channel_connection_ids(channel_id)
3549            .filter_map(|(connection_id, _)| {
3550                if collaborators.contains(&connection_id) {
3551                    None
3552                } else {
3553                    Some(connection_id)
3554                }
3555            });
3556
3557    broadcast(None, non_collaborators, |peer_id| {
3558        session.peer.send(
3559            peer_id,
3560            proto::UpdateChannels {
3561                latest_channel_buffer_versions: vec![proto::ChannelBufferVersion {
3562                    channel_id: channel_id.to_proto(),
3563                    epoch: epoch as u64,
3564                    version: version.clone(),
3565                }],
3566                ..Default::default()
3567            },
3568        )
3569    });
3570
3571    Ok(())
3572}
3573
3574/// Rejoin the channel notes after a connection blip
3575async fn rejoin_channel_buffers(
3576    request: proto::RejoinChannelBuffers,
3577    response: Response<proto::RejoinChannelBuffers>,
3578    session: Session,
3579) -> Result<()> {
3580    let db = session.db().await;
3581    let buffers = db
3582        .rejoin_channel_buffers(&request.buffers, session.user_id(), session.connection_id)
3583        .await?;
3584
3585    for rejoined_buffer in &buffers {
3586        let collaborators_to_notify = rejoined_buffer
3587            .buffer
3588            .collaborators
3589            .iter()
3590            .filter_map(|c| Some(c.peer_id?.into()));
3591        channel_buffer_updated(
3592            session.connection_id,
3593            collaborators_to_notify,
3594            &proto::UpdateChannelBufferCollaborators {
3595                channel_id: rejoined_buffer.buffer.channel_id,
3596                collaborators: rejoined_buffer.buffer.collaborators.clone(),
3597            },
3598            &session.peer,
3599        );
3600    }
3601
3602    response.send(proto::RejoinChannelBuffersResponse {
3603        buffers: buffers.into_iter().map(|b| b.buffer).collect(),
3604    })?;
3605
3606    Ok(())
3607}
3608
3609/// Stop editing the channel notes
3610async fn leave_channel_buffer(
3611    request: proto::LeaveChannelBuffer,
3612    response: Response<proto::LeaveChannelBuffer>,
3613    session: Session,
3614) -> Result<()> {
3615    let db = session.db().await;
3616    let channel_id = ChannelId::from_proto(request.channel_id);
3617
3618    let left_buffer = db
3619        .leave_channel_buffer(channel_id, session.connection_id)
3620        .await?;
3621
3622    response.send(Ack {})?;
3623
3624    channel_buffer_updated(
3625        session.connection_id,
3626        left_buffer.connections,
3627        &proto::UpdateChannelBufferCollaborators {
3628            channel_id: channel_id.to_proto(),
3629            collaborators: left_buffer.collaborators,
3630        },
3631        &session.peer,
3632    );
3633
3634    Ok(())
3635}
3636
3637fn channel_buffer_updated<T: EnvelopedMessage>(
3638    sender_id: ConnectionId,
3639    collaborators: impl IntoIterator<Item = ConnectionId>,
3640    message: &T,
3641    peer: &Peer,
3642) {
3643    broadcast(Some(sender_id), collaborators, |peer_id| {
3644        peer.send(peer_id, message.clone())
3645    });
3646}
3647
3648fn send_notifications(
3649    connection_pool: &ConnectionPool,
3650    peer: &Peer,
3651    notifications: db::NotificationBatch,
3652) {
3653    for (user_id, notification) in notifications {
3654        for connection_id in connection_pool.user_connection_ids(user_id) {
3655            if let Err(error) = peer.send(
3656                connection_id,
3657                proto::AddNotification {
3658                    notification: Some(notification.clone()),
3659                },
3660            ) {
3661                tracing::error!(
3662                    "failed to send notification to {:?} {}",
3663                    connection_id,
3664                    error
3665                );
3666            }
3667        }
3668    }
3669}
3670
3671/// Send a message to the channel
3672async fn send_channel_message(
3673    request: proto::SendChannelMessage,
3674    response: Response<proto::SendChannelMessage>,
3675    session: Session,
3676) -> Result<()> {
3677    // Validate the message body.
3678    let body = request.body.trim().to_string();
3679    if body.len() > MAX_MESSAGE_LEN {
3680        return Err(anyhow!("message is too long"))?;
3681    }
3682    if body.is_empty() {
3683        return Err(anyhow!("message can't be blank"))?;
3684    }
3685
3686    // TODO: adjust mentions if body is trimmed
3687
3688    let timestamp = OffsetDateTime::now_utc();
3689    let nonce = request.nonce.context("nonce can't be blank")?;
3690
3691    let channel_id = ChannelId::from_proto(request.channel_id);
3692    let CreatedChannelMessage {
3693        message_id,
3694        participant_connection_ids,
3695        notifications,
3696    } = session
3697        .db()
3698        .await
3699        .create_channel_message(
3700            channel_id,
3701            session.user_id(),
3702            &body,
3703            &request.mentions,
3704            timestamp,
3705            nonce.clone().into(),
3706            request.reply_to_message_id.map(MessageId::from_proto),
3707        )
3708        .await?;
3709
3710    let message = proto::ChannelMessage {
3711        sender_id: session.user_id().to_proto(),
3712        id: message_id.to_proto(),
3713        body,
3714        mentions: request.mentions,
3715        timestamp: timestamp.unix_timestamp() as u64,
3716        nonce: Some(nonce),
3717        reply_to_message_id: request.reply_to_message_id,
3718        edited_at: None,
3719    };
3720    broadcast(
3721        Some(session.connection_id),
3722        participant_connection_ids.clone(),
3723        |connection| {
3724            session.peer.send(
3725                connection,
3726                proto::ChannelMessageSent {
3727                    channel_id: channel_id.to_proto(),
3728                    message: Some(message.clone()),
3729                },
3730            )
3731        },
3732    );
3733    response.send(proto::SendChannelMessageResponse {
3734        message: Some(message),
3735    })?;
3736
3737    let pool = &*session.connection_pool().await;
3738    let non_participants =
3739        pool.channel_connection_ids(channel_id)
3740            .filter_map(|(connection_id, _)| {
3741                if participant_connection_ids.contains(&connection_id) {
3742                    None
3743                } else {
3744                    Some(connection_id)
3745                }
3746            });
3747    broadcast(None, non_participants, |peer_id| {
3748        session.peer.send(
3749            peer_id,
3750            proto::UpdateChannels {
3751                latest_channel_message_ids: vec![proto::ChannelMessageId {
3752                    channel_id: channel_id.to_proto(),
3753                    message_id: message_id.to_proto(),
3754                }],
3755                ..Default::default()
3756            },
3757        )
3758    });
3759    send_notifications(pool, &session.peer, notifications);
3760
3761    Ok(())
3762}
3763
3764/// Delete a channel message
3765async fn remove_channel_message(
3766    request: proto::RemoveChannelMessage,
3767    response: Response<proto::RemoveChannelMessage>,
3768    session: Session,
3769) -> Result<()> {
3770    let channel_id = ChannelId::from_proto(request.channel_id);
3771    let message_id = MessageId::from_proto(request.message_id);
3772    let (connection_ids, existing_notification_ids) = session
3773        .db()
3774        .await
3775        .remove_channel_message(channel_id, message_id, session.user_id())
3776        .await?;
3777
3778    broadcast(
3779        Some(session.connection_id),
3780        connection_ids,
3781        move |connection| {
3782            session.peer.send(connection, request.clone())?;
3783
3784            for notification_id in &existing_notification_ids {
3785                session.peer.send(
3786                    connection,
3787                    proto::DeleteNotification {
3788                        notification_id: (*notification_id).to_proto(),
3789                    },
3790                )?;
3791            }
3792
3793            Ok(())
3794        },
3795    );
3796    response.send(proto::Ack {})?;
3797    Ok(())
3798}
3799
3800async fn update_channel_message(
3801    request: proto::UpdateChannelMessage,
3802    response: Response<proto::UpdateChannelMessage>,
3803    session: Session,
3804) -> Result<()> {
3805    let channel_id = ChannelId::from_proto(request.channel_id);
3806    let message_id = MessageId::from_proto(request.message_id);
3807    let updated_at = OffsetDateTime::now_utc();
3808    let UpdatedChannelMessage {
3809        message_id,
3810        participant_connection_ids,
3811        notifications,
3812        reply_to_message_id,
3813        timestamp,
3814        deleted_mention_notification_ids,
3815        updated_mention_notifications,
3816    } = session
3817        .db()
3818        .await
3819        .update_channel_message(
3820            channel_id,
3821            message_id,
3822            session.user_id(),
3823            request.body.as_str(),
3824            &request.mentions,
3825            updated_at,
3826        )
3827        .await?;
3828
3829    let nonce = request.nonce.clone().context("nonce can't be blank")?;
3830
3831    let message = proto::ChannelMessage {
3832        sender_id: session.user_id().to_proto(),
3833        id: message_id.to_proto(),
3834        body: request.body.clone(),
3835        mentions: request.mentions.clone(),
3836        timestamp: timestamp.assume_utc().unix_timestamp() as u64,
3837        nonce: Some(nonce),
3838        reply_to_message_id: reply_to_message_id.map(|id| id.to_proto()),
3839        edited_at: Some(updated_at.unix_timestamp() as u64),
3840    };
3841
3842    response.send(proto::Ack {})?;
3843
3844    let pool = &*session.connection_pool().await;
3845    broadcast(
3846        Some(session.connection_id),
3847        participant_connection_ids,
3848        |connection| {
3849            session.peer.send(
3850                connection,
3851                proto::ChannelMessageUpdate {
3852                    channel_id: channel_id.to_proto(),
3853                    message: Some(message.clone()),
3854                },
3855            )?;
3856
3857            for notification_id in &deleted_mention_notification_ids {
3858                session.peer.send(
3859                    connection,
3860                    proto::DeleteNotification {
3861                        notification_id: (*notification_id).to_proto(),
3862                    },
3863                )?;
3864            }
3865
3866            for notification in &updated_mention_notifications {
3867                session.peer.send(
3868                    connection,
3869                    proto::UpdateNotification {
3870                        notification: Some(notification.clone()),
3871                    },
3872                )?;
3873            }
3874
3875            Ok(())
3876        },
3877    );
3878
3879    send_notifications(pool, &session.peer, notifications);
3880
3881    Ok(())
3882}
3883
3884/// Mark a channel message as read
3885async fn acknowledge_channel_message(
3886    request: proto::AckChannelMessage,
3887    session: Session,
3888) -> Result<()> {
3889    let channel_id = ChannelId::from_proto(request.channel_id);
3890    let message_id = MessageId::from_proto(request.message_id);
3891    let notifications = session
3892        .db()
3893        .await
3894        .observe_channel_message(channel_id, session.user_id(), message_id)
3895        .await?;
3896    send_notifications(
3897        &*session.connection_pool().await,
3898        &session.peer,
3899        notifications,
3900    );
3901    Ok(())
3902}
3903
3904/// Mark a buffer version as synced
3905async fn acknowledge_buffer_version(
3906    request: proto::AckBufferOperation,
3907    session: Session,
3908) -> Result<()> {
3909    let buffer_id = BufferId::from_proto(request.buffer_id);
3910    session
3911        .db()
3912        .await
3913        .observe_buffer_version(
3914            buffer_id,
3915            session.user_id(),
3916            request.epoch as i32,
3917            &request.version,
3918        )
3919        .await?;
3920    Ok(())
3921}
3922
3923/// Get a Supermaven API key for the user
3924async fn get_supermaven_api_key(
3925    _request: proto::GetSupermavenApiKey,
3926    response: Response<proto::GetSupermavenApiKey>,
3927    session: Session,
3928) -> Result<()> {
3929    let user_id: String = session.user_id().to_string();
3930    if !session.is_staff() {
3931        return Err(anyhow!("supermaven not enabled for this account"))?;
3932    }
3933
3934    let email = session.email().context("user must have an email")?;
3935
3936    let supermaven_admin_api = session
3937        .supermaven_client
3938        .as_ref()
3939        .context("supermaven not configured")?;
3940
3941    let result = supermaven_admin_api
3942        .try_get_or_create_user(CreateExternalUserRequest { id: user_id, email })
3943        .await?;
3944
3945    response.send(proto::GetSupermavenApiKeyResponse {
3946        api_key: result.api_key,
3947    })?;
3948
3949    Ok(())
3950}
3951
3952/// Start receiving chat updates for a channel
3953async fn join_channel_chat(
3954    request: proto::JoinChannelChat,
3955    response: Response<proto::JoinChannelChat>,
3956    session: Session,
3957) -> Result<()> {
3958    let channel_id = ChannelId::from_proto(request.channel_id);
3959
3960    let db = session.db().await;
3961    db.join_channel_chat(channel_id, session.connection_id, session.user_id())
3962        .await?;
3963    let messages = db
3964        .get_channel_messages(channel_id, session.user_id(), MESSAGE_COUNT_PER_PAGE, None)
3965        .await?;
3966    response.send(proto::JoinChannelChatResponse {
3967        done: messages.len() < MESSAGE_COUNT_PER_PAGE,
3968        messages,
3969    })?;
3970    Ok(())
3971}
3972
3973/// Stop receiving chat updates for a channel
3974async fn leave_channel_chat(request: proto::LeaveChannelChat, session: Session) -> Result<()> {
3975    let channel_id = ChannelId::from_proto(request.channel_id);
3976    session
3977        .db()
3978        .await
3979        .leave_channel_chat(channel_id, session.connection_id, session.user_id())
3980        .await?;
3981    Ok(())
3982}
3983
3984/// Retrieve the chat history for a channel
3985async fn get_channel_messages(
3986    request: proto::GetChannelMessages,
3987    response: Response<proto::GetChannelMessages>,
3988    session: Session,
3989) -> Result<()> {
3990    let channel_id = ChannelId::from_proto(request.channel_id);
3991    let messages = session
3992        .db()
3993        .await
3994        .get_channel_messages(
3995            channel_id,
3996            session.user_id(),
3997            MESSAGE_COUNT_PER_PAGE,
3998            Some(MessageId::from_proto(request.before_message_id)),
3999        )
4000        .await?;
4001    response.send(proto::GetChannelMessagesResponse {
4002        done: messages.len() < MESSAGE_COUNT_PER_PAGE,
4003        messages,
4004    })?;
4005    Ok(())
4006}
4007
4008/// Retrieve specific chat messages
4009async fn get_channel_messages_by_id(
4010    request: proto::GetChannelMessagesById,
4011    response: Response<proto::GetChannelMessagesById>,
4012    session: Session,
4013) -> Result<()> {
4014    let message_ids = request
4015        .message_ids
4016        .iter()
4017        .map(|id| MessageId::from_proto(*id))
4018        .collect::<Vec<_>>();
4019    let messages = session
4020        .db()
4021        .await
4022        .get_channel_messages_by_id(session.user_id(), &message_ids)
4023        .await?;
4024    response.send(proto::GetChannelMessagesResponse {
4025        done: messages.len() < MESSAGE_COUNT_PER_PAGE,
4026        messages,
4027    })?;
4028    Ok(())
4029}
4030
4031/// Retrieve the current users notifications
4032async fn get_notifications(
4033    request: proto::GetNotifications,
4034    response: Response<proto::GetNotifications>,
4035    session: Session,
4036) -> Result<()> {
4037    let notifications = session
4038        .db()
4039        .await
4040        .get_notifications(
4041            session.user_id(),
4042            NOTIFICATION_COUNT_PER_PAGE,
4043            request.before_id.map(db::NotificationId::from_proto),
4044        )
4045        .await?;
4046    response.send(proto::GetNotificationsResponse {
4047        done: notifications.len() < NOTIFICATION_COUNT_PER_PAGE,
4048        notifications,
4049    })?;
4050    Ok(())
4051}
4052
4053/// Mark notifications as read
4054async fn mark_notification_as_read(
4055    request: proto::MarkNotificationRead,
4056    response: Response<proto::MarkNotificationRead>,
4057    session: Session,
4058) -> Result<()> {
4059    let database = &session.db().await;
4060    let notifications = database
4061        .mark_notification_as_read_by_id(
4062            session.user_id(),
4063            NotificationId::from_proto(request.notification_id),
4064        )
4065        .await?;
4066    send_notifications(
4067        &*session.connection_pool().await,
4068        &session.peer,
4069        notifications,
4070    );
4071    response.send(proto::Ack {})?;
4072    Ok(())
4073}
4074
4075/// Get the current users information
4076async fn get_private_user_info(
4077    _request: proto::GetPrivateUserInfo,
4078    response: Response<proto::GetPrivateUserInfo>,
4079    session: Session,
4080) -> Result<()> {
4081    let db = session.db().await;
4082
4083    let metrics_id = db.get_user_metrics_id(session.user_id()).await?;
4084    let user = db
4085        .get_user_by_id(session.user_id())
4086        .await?
4087        .context("user not found")?;
4088    let flags = db.get_user_flags(session.user_id()).await?;
4089
4090    response.send(proto::GetPrivateUserInfoResponse {
4091        metrics_id,
4092        staff: user.admin,
4093        flags,
4094        accepted_tos_at: user.accepted_tos_at.map(|t| t.and_utc().timestamp() as u64),
4095    })?;
4096    Ok(())
4097}
4098
4099/// Accept the terms of service (tos) on behalf of the current user
4100async fn accept_terms_of_service(
4101    _request: proto::AcceptTermsOfService,
4102    response: Response<proto::AcceptTermsOfService>,
4103    session: Session,
4104) -> Result<()> {
4105    let db = session.db().await;
4106
4107    let accepted_tos_at = Utc::now();
4108    db.set_user_accepted_tos_at(session.user_id(), Some(accepted_tos_at.naive_utc()))
4109        .await?;
4110
4111    response.send(proto::AcceptTermsOfServiceResponse {
4112        accepted_tos_at: accepted_tos_at.timestamp() as u64,
4113    })?;
4114    Ok(())
4115}
4116
4117async fn get_llm_api_token(
4118    _request: proto::GetLlmToken,
4119    response: Response<proto::GetLlmToken>,
4120    session: Session,
4121) -> Result<()> {
4122    let db = session.db().await;
4123
4124    let flags = db.get_user_flags(session.user_id()).await?;
4125
4126    let user_id = session.user_id();
4127    let user = db
4128        .get_user_by_id(user_id)
4129        .await?
4130        .with_context(|| format!("user {user_id} not found"))?;
4131
4132    if user.accepted_tos_at.is_none() {
4133        Err(anyhow!("terms of service not accepted"))?
4134    }
4135
4136    let stripe_client = session
4137        .app_state
4138        .stripe_client
4139        .as_ref()
4140        .context("failed to retrieve Stripe client")?;
4141
4142    let stripe_billing = session
4143        .app_state
4144        .stripe_billing
4145        .as_ref()
4146        .context("failed to retrieve Stripe billing object")?;
4147
4148    let billing_customer = if let Some(billing_customer) =
4149        db.get_billing_customer_by_user_id(user.id).await?
4150    {
4151        billing_customer
4152    } else {
4153        let customer_id = stripe_billing
4154            .find_or_create_customer_by_email(user.email_address.as_deref())
4155            .await?;
4156
4157        find_or_create_billing_customer(&session.app_state, stripe_client.as_ref(), &customer_id)
4158            .await?
4159            .context("billing customer not found")?
4160    };
4161
4162    let billing_subscription =
4163        if let Some(billing_subscription) = db.get_active_billing_subscription(user.id).await? {
4164            billing_subscription
4165        } else {
4166            let stripe_customer_id =
4167                StripeCustomerId(billing_customer.stripe_customer_id.clone().into());
4168
4169            let stripe_subscription = stripe_billing
4170                .subscribe_to_zed_free(stripe_customer_id)
4171                .await?;
4172
4173            db.create_billing_subscription(&db::CreateBillingSubscriptionParams {
4174                billing_customer_id: billing_customer.id,
4175                kind: Some(SubscriptionKind::ZedFree),
4176                stripe_subscription_id: stripe_subscription.id.to_string(),
4177                stripe_subscription_status: stripe_subscription.status.into(),
4178                stripe_cancellation_reason: None,
4179                stripe_current_period_start: Some(stripe_subscription.current_period_start),
4180                stripe_current_period_end: Some(stripe_subscription.current_period_end),
4181            })
4182            .await?
4183        };
4184
4185    let billing_preferences = db.get_billing_preferences(user.id).await?;
4186
4187    let token = LlmTokenClaims::create(
4188        &user,
4189        session.is_staff(),
4190        billing_customer,
4191        billing_preferences,
4192        &flags,
4193        billing_subscription,
4194        session.system_id.clone(),
4195        &session.app_state.config,
4196    )?;
4197    response.send(proto::GetLlmTokenResponse { token })?;
4198    Ok(())
4199}
4200
4201fn to_axum_message(message: TungsteniteMessage) -> anyhow::Result<AxumMessage> {
4202    let message = match message {
4203        TungsteniteMessage::Text(payload) => AxumMessage::Text(payload.as_str().to_string()),
4204        TungsteniteMessage::Binary(payload) => AxumMessage::Binary(payload.into()),
4205        TungsteniteMessage::Ping(payload) => AxumMessage::Ping(payload.into()),
4206        TungsteniteMessage::Pong(payload) => AxumMessage::Pong(payload.into()),
4207        TungsteniteMessage::Close(frame) => AxumMessage::Close(frame.map(|frame| AxumCloseFrame {
4208            code: frame.code.into(),
4209            reason: frame.reason.as_str().to_owned().into(),
4210        })),
4211        // We should never receive a frame while reading the message, according
4212        // to the `tungstenite` maintainers:
4213        //
4214        // > It cannot occur when you read messages from the WebSocket, but it
4215        // > can be used when you want to send the raw frames (e.g. you want to
4216        // > send the frames to the WebSocket without composing the full message first).
4217        // >
4218        // > — https://github.com/snapview/tungstenite-rs/issues/268
4219        TungsteniteMessage::Frame(_) => {
4220            bail!("received an unexpected frame while reading the message")
4221        }
4222    };
4223
4224    Ok(message)
4225}
4226
4227fn to_tungstenite_message(message: AxumMessage) -> TungsteniteMessage {
4228    match message {
4229        AxumMessage::Text(payload) => TungsteniteMessage::Text(payload.into()),
4230        AxumMessage::Binary(payload) => TungsteniteMessage::Binary(payload.into()),
4231        AxumMessage::Ping(payload) => TungsteniteMessage::Ping(payload.into()),
4232        AxumMessage::Pong(payload) => TungsteniteMessage::Pong(payload.into()),
4233        AxumMessage::Close(frame) => {
4234            TungsteniteMessage::Close(frame.map(|frame| TungsteniteCloseFrame {
4235                code: frame.code.into(),
4236                reason: frame.reason.as_ref().into(),
4237            }))
4238        }
4239    }
4240}
4241
4242fn notify_membership_updated(
4243    connection_pool: &mut ConnectionPool,
4244    result: MembershipUpdated,
4245    user_id: UserId,
4246    peer: &Peer,
4247) {
4248    for membership in &result.new_channels.channel_memberships {
4249        connection_pool.subscribe_to_channel(user_id, membership.channel_id, membership.role)
4250    }
4251    for channel_id in &result.removed_channels {
4252        connection_pool.unsubscribe_from_channel(&user_id, channel_id)
4253    }
4254
4255    let user_channels_update = proto::UpdateUserChannels {
4256        channel_memberships: result
4257            .new_channels
4258            .channel_memberships
4259            .iter()
4260            .map(|cm| proto::ChannelMembership {
4261                channel_id: cm.channel_id.to_proto(),
4262                role: cm.role.into(),
4263            })
4264            .collect(),
4265        ..Default::default()
4266    };
4267
4268    let mut update = build_channels_update(result.new_channels);
4269    update.delete_channels = result
4270        .removed_channels
4271        .into_iter()
4272        .map(|id| id.to_proto())
4273        .collect();
4274    update.remove_channel_invitations = vec![result.channel_id.to_proto()];
4275
4276    for connection_id in connection_pool.user_connection_ids(user_id) {
4277        peer.send(connection_id, user_channels_update.clone())
4278            .trace_err();
4279        peer.send(connection_id, update.clone()).trace_err();
4280    }
4281}
4282
4283fn build_update_user_channels(channels: &ChannelsForUser) -> proto::UpdateUserChannels {
4284    proto::UpdateUserChannels {
4285        channel_memberships: channels
4286            .channel_memberships
4287            .iter()
4288            .map(|m| proto::ChannelMembership {
4289                channel_id: m.channel_id.to_proto(),
4290                role: m.role.into(),
4291            })
4292            .collect(),
4293        observed_channel_buffer_version: channels.observed_buffer_versions.clone(),
4294        observed_channel_message_id: channels.observed_channel_messages.clone(),
4295    }
4296}
4297
4298fn build_channels_update(channels: ChannelsForUser) -> proto::UpdateChannels {
4299    let mut update = proto::UpdateChannels::default();
4300
4301    for channel in channels.channels {
4302        update.channels.push(channel.to_proto());
4303    }
4304
4305    update.latest_channel_buffer_versions = channels.latest_buffer_versions;
4306    update.latest_channel_message_ids = channels.latest_channel_messages;
4307
4308    for (channel_id, participants) in channels.channel_participants {
4309        update
4310            .channel_participants
4311            .push(proto::ChannelParticipants {
4312                channel_id: channel_id.to_proto(),
4313                participant_user_ids: participants.into_iter().map(|id| id.to_proto()).collect(),
4314            });
4315    }
4316
4317    for channel in channels.invited_channels {
4318        update.channel_invitations.push(channel.to_proto());
4319    }
4320
4321    update
4322}
4323
4324fn build_initial_contacts_update(
4325    contacts: Vec<db::Contact>,
4326    pool: &ConnectionPool,
4327) -> proto::UpdateContacts {
4328    let mut update = proto::UpdateContacts::default();
4329
4330    for contact in contacts {
4331        match contact {
4332            db::Contact::Accepted { user_id, busy } => {
4333                update.contacts.push(contact_for_user(user_id, busy, pool));
4334            }
4335            db::Contact::Outgoing { user_id } => update.outgoing_requests.push(user_id.to_proto()),
4336            db::Contact::Incoming { user_id } => {
4337                update
4338                    .incoming_requests
4339                    .push(proto::IncomingContactRequest {
4340                        requester_id: user_id.to_proto(),
4341                    })
4342            }
4343        }
4344    }
4345
4346    update
4347}
4348
4349fn contact_for_user(user_id: UserId, busy: bool, pool: &ConnectionPool) -> proto::Contact {
4350    proto::Contact {
4351        user_id: user_id.to_proto(),
4352        online: pool.is_user_online(user_id),
4353        busy,
4354    }
4355}
4356
4357fn room_updated(room: &proto::Room, peer: &Peer) {
4358    broadcast(
4359        None,
4360        room.participants
4361            .iter()
4362            .filter_map(|participant| Some(participant.peer_id?.into())),
4363        |peer_id| {
4364            peer.send(
4365                peer_id,
4366                proto::RoomUpdated {
4367                    room: Some(room.clone()),
4368                },
4369            )
4370        },
4371    );
4372}
4373
4374fn channel_updated(
4375    channel: &db::channel::Model,
4376    room: &proto::Room,
4377    peer: &Peer,
4378    pool: &ConnectionPool,
4379) {
4380    let participants = room
4381        .participants
4382        .iter()
4383        .map(|p| p.user_id)
4384        .collect::<Vec<_>>();
4385
4386    broadcast(
4387        None,
4388        pool.channel_connection_ids(channel.root_id())
4389            .filter_map(|(channel_id, role)| {
4390                role.can_see_channel(channel.visibility)
4391                    .then_some(channel_id)
4392            }),
4393        |peer_id| {
4394            peer.send(
4395                peer_id,
4396                proto::UpdateChannels {
4397                    channel_participants: vec![proto::ChannelParticipants {
4398                        channel_id: channel.id.to_proto(),
4399                        participant_user_ids: participants.clone(),
4400                    }],
4401                    ..Default::default()
4402                },
4403            )
4404        },
4405    );
4406}
4407
4408async fn update_user_contacts(user_id: UserId, session: &Session) -> Result<()> {
4409    let db = session.db().await;
4410
4411    let contacts = db.get_contacts(user_id).await?;
4412    let busy = db.is_user_busy(user_id).await?;
4413
4414    let pool = session.connection_pool().await;
4415    let updated_contact = contact_for_user(user_id, busy, &pool);
4416    for contact in contacts {
4417        if let db::Contact::Accepted {
4418            user_id: contact_user_id,
4419            ..
4420        } = contact
4421        {
4422            for contact_conn_id in pool.user_connection_ids(contact_user_id) {
4423                session
4424                    .peer
4425                    .send(
4426                        contact_conn_id,
4427                        proto::UpdateContacts {
4428                            contacts: vec![updated_contact.clone()],
4429                            remove_contacts: Default::default(),
4430                            incoming_requests: Default::default(),
4431                            remove_incoming_requests: Default::default(),
4432                            outgoing_requests: Default::default(),
4433                            remove_outgoing_requests: Default::default(),
4434                        },
4435                    )
4436                    .trace_err();
4437            }
4438        }
4439    }
4440    Ok(())
4441}
4442
4443async fn leave_room_for_session(session: &Session, connection_id: ConnectionId) -> Result<()> {
4444    let mut contacts_to_update = HashSet::default();
4445
4446    let room_id;
4447    let canceled_calls_to_user_ids;
4448    let livekit_room;
4449    let delete_livekit_room;
4450    let room;
4451    let channel;
4452
4453    if let Some(mut left_room) = session.db().await.leave_room(connection_id).await? {
4454        contacts_to_update.insert(session.user_id());
4455
4456        for project in left_room.left_projects.values() {
4457            project_left(project, session);
4458        }
4459
4460        room_id = RoomId::from_proto(left_room.room.id);
4461        canceled_calls_to_user_ids = mem::take(&mut left_room.canceled_calls_to_user_ids);
4462        livekit_room = mem::take(&mut left_room.room.livekit_room);
4463        delete_livekit_room = left_room.deleted;
4464        room = mem::take(&mut left_room.room);
4465        channel = mem::take(&mut left_room.channel);
4466
4467        room_updated(&room, &session.peer);
4468    } else {
4469        return Ok(());
4470    }
4471
4472    if let Some(channel) = channel {
4473        channel_updated(
4474            &channel,
4475            &room,
4476            &session.peer,
4477            &*session.connection_pool().await,
4478        );
4479    }
4480
4481    {
4482        let pool = session.connection_pool().await;
4483        for canceled_user_id in canceled_calls_to_user_ids {
4484            for connection_id in pool.user_connection_ids(canceled_user_id) {
4485                session
4486                    .peer
4487                    .send(
4488                        connection_id,
4489                        proto::CallCanceled {
4490                            room_id: room_id.to_proto(),
4491                        },
4492                    )
4493                    .trace_err();
4494            }
4495            contacts_to_update.insert(canceled_user_id);
4496        }
4497    }
4498
4499    for contact_user_id in contacts_to_update {
4500        update_user_contacts(contact_user_id, session).await?;
4501    }
4502
4503    if let Some(live_kit) = session.app_state.livekit_client.as_ref() {
4504        live_kit
4505            .remove_participant(livekit_room.clone(), session.user_id().to_string())
4506            .await
4507            .trace_err();
4508
4509        if delete_livekit_room {
4510            live_kit.delete_room(livekit_room).await.trace_err();
4511        }
4512    }
4513
4514    Ok(())
4515}
4516
4517async fn leave_channel_buffers_for_session(session: &Session) -> Result<()> {
4518    let left_channel_buffers = session
4519        .db()
4520        .await
4521        .leave_channel_buffers(session.connection_id)
4522        .await?;
4523
4524    for left_buffer in left_channel_buffers {
4525        channel_buffer_updated(
4526            session.connection_id,
4527            left_buffer.connections,
4528            &proto::UpdateChannelBufferCollaborators {
4529                channel_id: left_buffer.channel_id.to_proto(),
4530                collaborators: left_buffer.collaborators,
4531            },
4532            &session.peer,
4533        );
4534    }
4535
4536    Ok(())
4537}
4538
4539fn project_left(project: &db::LeftProject, session: &Session) {
4540    for connection_id in &project.connection_ids {
4541        if project.should_unshare {
4542            session
4543                .peer
4544                .send(
4545                    *connection_id,
4546                    proto::UnshareProject {
4547                        project_id: project.id.to_proto(),
4548                    },
4549                )
4550                .trace_err();
4551        } else {
4552            session
4553                .peer
4554                .send(
4555                    *connection_id,
4556                    proto::RemoveProjectCollaborator {
4557                        project_id: project.id.to_proto(),
4558                        peer_id: Some(session.connection_id.into()),
4559                    },
4560                )
4561                .trace_err();
4562        }
4563    }
4564}
4565
4566pub trait ResultExt {
4567    type Ok;
4568
4569    fn trace_err(self) -> Option<Self::Ok>;
4570}
4571
4572impl<T, E> ResultExt for Result<T, E>
4573where
4574    E: std::fmt::Debug,
4575{
4576    type Ok = T;
4577
4578    #[track_caller]
4579    fn trace_err(self) -> Option<T> {
4580        match self {
4581            Ok(value) => Some(value),
4582            Err(error) => {
4583                tracing::error!("{:?}", error);
4584                None
4585            }
4586        }
4587    }
4588}