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