1use crate::{Client, Connection, Credentials, EstablishConnectionError, UserStore};
2use anyhow::{anyhow, Result};
3use futures::{stream::BoxStream, StreamExt};
4use gpui::{BackgroundExecutor, Context, Model, TestAppContext};
5use parking_lot::Mutex;
6use rpc::{
7 proto::{self, GetPrivateUserInfo, GetPrivateUserInfoResponse},
8 ConnectionId, Peer, Receipt, TypedEnvelope,
9};
10use std::sync::Arc;
11
12pub struct FakeServer {
13 peer: Arc<Peer>,
14 state: Arc<Mutex<FakeServerState>>,
15 user_id: u64,
16 executor: BackgroundExecutor,
17}
18
19#[derive(Default)]
20struct FakeServerState {
21 incoming: Option<BoxStream<'static, Box<dyn proto::AnyTypedEnvelope>>>,
22 connection_id: Option<ConnectionId>,
23 forbid_connections: bool,
24 auth_count: usize,
25 access_token: usize,
26}
27
28impl FakeServer {
29 pub async fn for_client(
30 client_user_id: u64,
31 client: &Arc<Client>,
32 cx: &TestAppContext,
33 ) -> Self {
34 let server = Self {
35 peer: Peer::new(0),
36 state: Default::default(),
37 user_id: client_user_id,
38 executor: cx.executor(),
39 };
40
41 client
42 .override_authenticate({
43 let state = Arc::downgrade(&server.state);
44 move |cx| {
45 let state = state.clone();
46 cx.spawn(move |_| async move {
47 let state = state.upgrade().ok_or_else(|| anyhow!("server dropped"))?;
48 let mut state = state.lock();
49 state.auth_count += 1;
50 let access_token = state.access_token.to_string();
51 Ok(Credentials {
52 user_id: client_user_id,
53 access_token,
54 })
55 })
56 }
57 })
58 .override_establish_connection({
59 let peer = Arc::downgrade(&server.peer);
60 let state = Arc::downgrade(&server.state);
61 move |credentials, cx| {
62 let peer = peer.clone();
63 let state = state.clone();
64 let credentials = credentials.clone();
65 cx.spawn(move |cx| async move {
66 let state = state.upgrade().ok_or_else(|| anyhow!("server dropped"))?;
67 let peer = peer.upgrade().ok_or_else(|| anyhow!("server dropped"))?;
68 if state.lock().forbid_connections {
69 Err(EstablishConnectionError::Other(anyhow!(
70 "server is forbidding connections"
71 )))?
72 }
73
74 assert_eq!(credentials.user_id, client_user_id);
75
76 if credentials.access_token != state.lock().access_token.to_string() {
77 Err(EstablishConnectionError::Unauthorized)?
78 }
79
80 let (client_conn, server_conn, _) =
81 Connection::in_memory(cx.background_executor().clone());
82 let (connection_id, io, incoming) =
83 peer.add_test_connection(server_conn, cx.background_executor().clone());
84 cx.background_executor().spawn(io).detach();
85 {
86 let mut state = state.lock();
87 state.connection_id = Some(connection_id);
88 state.incoming = Some(incoming);
89 }
90 peer.send(
91 connection_id,
92 proto::Hello {
93 peer_id: Some(connection_id.into()),
94 },
95 )
96 .unwrap();
97
98 Ok(client_conn)
99 })
100 }
101 });
102
103 client
104 .authenticate_and_connect(false, &cx.to_async())
105 .await
106 .unwrap();
107
108 server
109 }
110
111 pub fn disconnect(&self) {
112 if self.state.lock().connection_id.is_some() {
113 self.peer.disconnect(self.connection_id());
114 let mut state = self.state.lock();
115 state.connection_id.take();
116 state.incoming.take();
117 }
118 }
119
120 pub fn auth_count(&self) -> usize {
121 self.state.lock().auth_count
122 }
123
124 pub fn roll_access_token(&self) {
125 self.state.lock().access_token += 1;
126 }
127
128 pub fn forbid_connections(&self) {
129 self.state.lock().forbid_connections = true;
130 }
131
132 pub fn allow_connections(&self) {
133 self.state.lock().forbid_connections = false;
134 }
135
136 pub fn send<T: proto::EnvelopedMessage>(&self, message: T) {
137 self.peer.send(self.connection_id(), message).unwrap();
138 }
139
140 #[allow(clippy::await_holding_lock)]
141 pub async fn receive<M: proto::EnvelopedMessage>(&self) -> Result<TypedEnvelope<M>> {
142 self.executor.start_waiting();
143
144 loop {
145 let message = self
146 .state
147 .lock()
148 .incoming
149 .as_mut()
150 .expect("not connected")
151 .next()
152 .await
153 .ok_or_else(|| anyhow!("other half hung up"))?;
154 self.executor.finish_waiting();
155 let type_name = message.payload_type_name();
156 let message = message.into_any();
157
158 if message.is::<TypedEnvelope<M>>() {
159 return Ok(*message.downcast().unwrap());
160 }
161
162 if message.is::<TypedEnvelope<GetPrivateUserInfo>>() {
163 self.respond(
164 message
165 .downcast::<TypedEnvelope<GetPrivateUserInfo>>()
166 .unwrap()
167 .receipt(),
168 GetPrivateUserInfoResponse {
169 metrics_id: "the-metrics-id".into(),
170 staff: false,
171 flags: Default::default(),
172 },
173 );
174 continue;
175 }
176
177 panic!(
178 "fake server received unexpected message type: {:?}",
179 type_name
180 );
181 }
182 }
183
184 pub fn respond<T: proto::RequestMessage>(&self, receipt: Receipt<T>, response: T::Response) {
185 self.peer.respond(receipt, response).unwrap()
186 }
187
188 fn connection_id(&self) -> ConnectionId {
189 self.state.lock().connection_id.expect("not connected")
190 }
191
192 pub async fn build_user_store(
193 &self,
194 client: Arc<Client>,
195 cx: &mut TestAppContext,
196 ) -> Model<UserStore> {
197 let user_store = cx.new_model(|cx| UserStore::new(client, cx));
198 assert_eq!(
199 self.receive::<proto::GetUsers>()
200 .await
201 .unwrap()
202 .payload
203 .user_ids,
204 &[self.user_id]
205 );
206 user_store
207 }
208}
209
210impl Drop for FakeServer {
211 fn drop(&mut self) {
212 self.disconnect();
213 }
214}