1use std::path::{Path, PathBuf};
4use std::sync::{Arc, Mutex, PoisonError};
5use std::thread::JoinHandle;
6use std::time::Duration;
7
8use crossbeam_channel::{Receiver, Sender, bounded};
9use simplex_client::engine::{Clock, SystemClock};
10use zaun_community_protocol::client::member::InvitePayload;
11use zaun_community_protocol::client::owner::{HostInfo, generate_root_key};
12use zaun_community_protocol::client::{Response, Session};
13use zaun_community_protocol::command::Body;
14use zaun_community_protocol::crypto::SecretKey;
15use zaun_community_protocol::ids::{ChannelId, CommunityId, MemberId};
16use zaun_community_protocol::keys::PublicKey;
17
18use crate::builder::ClientBuilder;
19use crate::cache::CommunityData;
20use crate::driver::{self, Request, Shared};
21use crate::error::{Error, Result};
22use crate::events::Event;
23use crate::objects::Community;
24use crate::store::Store;
25
26const EVENT_QUEUE: usize = 4096;
29
30#[derive(Clone)]
33pub struct Client {
34 inner: Arc<Inner>,
35}
36
37struct Inner {
38 requests: Sender<Request>,
39 events: Receiver<crate::event::Event>,
40 cache: Shared,
41 pins: crate::pins::Book,
43 simplex: simplex_client::Client,
44 driver: Mutex<Option<JoinHandle<()>>>,
45 timeout: Duration,
46 join_timeout: Duration,
47 pub(crate) dir: PathBuf,
48 pub(crate) transfer_timeout: Duration,
49 pub(crate) upload_servers: Vec<simplex_client::xftp::XftpServer>,
51 voice: crate::voice::Routes,
53}
54
55impl Drop for Inner {
56 fn drop(&mut self) {
57 let _ = self.requests.send(Request::Stop);
58 if let Some(h) = self
59 .driver
60 .lock()
61 .unwrap_or_else(PoisonError::into_inner)
62 .take()
63 {
64 let _ = h.join();
65 }
66 self.simplex.close();
67 }
68}
69
70pub(crate) use crate::error::refused;
71
72impl Client {
73 pub fn builder(dir: impl AsRef<Path>) -> ClientBuilder {
75 ClientBuilder::new(dir.as_ref().to_owned())
76 }
77
78 pub(crate) fn start(b: ClientBuilder) -> Result<Self> {
79 let simplex = b.simplex.start()?;
80 let (requests, rx) = crossbeam_channel::unbounded();
81 let (out, events) = bounded(EVENT_QUEUE);
82 let cache: Shared = Arc::default();
83 let pins = crate::pins::Book::default();
84 let voice = crate::voice::Routes::default();
85 let millis = |d: Duration| u64::try_from(d.as_millis()).unwrap_or(u64::MAX);
86 let handle = driver::spawn(
87 simplex.clone(),
88 Store::new(&b.dir),
89 driver::Shares {
90 cache: Arc::clone(&cache),
91 pins: Arc::clone(&pins),
92 voice: Arc::clone(&voice),
93 },
94 out,
95 rx,
96 millis(b.join_timeout),
97 )
98 .map_err(|e| Error::Store(format!("thread: {e}")))?;
99 Ok(Self {
100 inner: Arc::new(Inner {
101 requests,
102 events,
103 cache,
104 pins,
105 simplex,
106 driver: Mutex::new(Some(handle)),
107 timeout: b.timeout,
108 join_timeout: b.join_timeout,
109 dir: b.dir.clone(),
110 transfer_timeout: b.transfer_timeout,
111 upload_servers: crate::files::upload_servers(&b.relays),
112 voice,
113 }),
114 })
115 }
116
117 pub fn events(&self) -> impl Iterator<Item = Event> + Send + 'static {
119 let client = Arc::downgrade(&self.inner);
121 self.inner
122 .events
123 .clone()
124 .into_iter()
125 .map_while(move |e| client.upgrade().map(|inner| Self { inner }.wrap(e)))
126 }
127
128 #[must_use]
130 pub fn next_event(&self, timeout: Duration) -> Option<Event> {
131 let e = self.inner.events.recv_timeout(timeout).ok()?;
132 Some(self.wrap(e))
133 }
134
135 #[must_use]
137 pub fn simplex(&self) -> &simplex_client::Client {
138 &self.inner.simplex
139 }
140
141 #[must_use]
143 pub fn now_ms(&self) -> u64 {
144 u64::try_from(SystemClock.wall_ms()).unwrap_or(0)
145 }
146
147 #[must_use]
149 pub fn communities(&self) -> Vec<Community> {
150 let ids: Vec<CommunityId> = self.lock().keys().copied().collect();
151 ids.into_iter().map(|id| self.community(id)).collect()
152 }
153
154 #[must_use]
156 pub fn community(&self, id: CommunityId) -> Community {
157 Community {
158 client: self.clone(),
159 id,
160 }
161 }
162
163 pub(crate) fn data(&self, id: &CommunityId) -> Option<CommunityData> {
165 self.lock().get(id).cloned()
166 }
167
168 pub(crate) fn read<T>(
171 &self,
172 id: &CommunityId,
173 f: impl FnOnce(&CommunityData) -> T,
174 ) -> Option<T> {
175 self.lock().get(id).map(f)
176 }
177
178 fn loaded(&self, id: CommunityId) -> Community {
181 let deadline =
182 self.now_ms() + u64::try_from(self.inner.join_timeout.as_millis()).unwrap_or(0);
183 while self.now_ms() < deadline && self.read(&id, |c| c.loaded) != Some(true) {
184 std::thread::sleep(Duration::from_millis(20));
185 }
186 self.community(id)
187 }
188
189 pub(crate) fn host_attachments(
191 &self,
192 community: &CommunityId,
193 ) -> Option<zaun_community_protocol::command::session::HostAttachments> {
194 self.lock()
195 .get(community)
196 .and_then(|c| c.attachments.clone())
197 }
198
199 fn lock(
200 &self,
201 ) -> std::sync::MutexGuard<'_, std::collections::BTreeMap<CommunityId, CommunityData>> {
202 self.inner
203 .cache
204 .lock()
205 .unwrap_or_else(PoisonError::into_inner)
206 }
207
208 pub(crate) fn shared_cache(&self) -> &Shared {
210 &self.inner.cache
211 }
212
213 pub(crate) fn with_cache<T>(
214 &self,
215 f: impl FnOnce(&mut std::collections::BTreeMap<CommunityId, CommunityData>) -> T,
216 ) -> T {
217 f(&mut self.lock())
218 }
219
220 pub(crate) fn ask<T>(
221 &self,
222 make: impl FnOnce(Sender<Result<T>>) -> Request,
223 wait: Duration,
224 what: &'static str,
225 ) -> Result<T> {
226 let (tx, rx) = bounded(1);
227 self.inner
228 .requests
229 .send(make(tx))
230 .map_err(|_| Error::Closed)?;
231 rx.recv_timeout(wait).map_err(|e| match e {
232 crossbeam_channel::RecvTimeoutError::Timeout => Error::Timeout(what),
233 crossbeam_channel::RecvTimeoutError::Disconnected => Error::Closed,
234 })?
235 }
236
237 pub(crate) fn tell(&self, request: Request) -> Result<()> {
239 self.inner.requests.send(request).map_err(|_| Error::Closed)
240 }
241
242 pub(crate) fn inner_dir(&self) -> PathBuf {
243 self.inner.dir.clone()
244 }
245
246 pub(crate) fn command_timeout(&self) -> Duration {
247 self.inner.timeout
248 }
249
250 pub(crate) fn join_timeout(&self) -> Duration {
251 self.inner.join_timeout
252 }
253
254 pub(crate) fn transfer_timeout(&self) -> Duration {
255 self.inner.transfer_timeout
256 }
257
258 pub(crate) fn upload_servers(&self) -> &[simplex_client::xftp::XftpServer] {
259 &self.inner.upload_servers
260 }
261
262 pub(crate) fn pinned(
264 &self,
265 community: &CommunityId,
266 member: &MemberId,
267 ) -> Option<crate::pins::KeyHash> {
268 self.inner
269 .pins
270 .lock()
271 .unwrap_or_else(PoisonError::into_inner)
272 .get(community)?
273 .get(member)
274 .copied()
275 }
276
277 pub(crate) fn voice_routes(&self) -> crate::voice::Routes {
278 Arc::clone(&self.inner.voice)
279 }
280
281 pub(crate) fn send_request(&self, request: Request) {
282 let _ = self.inner.requests.send(request);
283 }
284
285 pub fn join(&self, link: &str, display_name: &str) -> Result<Community> {
292 let link = InvitePayload::parse(link.trim()).map_err(|_| Error::BadLink)?;
293 let name = display_name.to_owned();
294 let id = self.ask(
295 |reply| Request::Join {
296 link: Box::new(link),
297 name,
298 reply,
299 },
300 self.inner.join_timeout,
301 "the join",
302 )?;
303 Ok(self.loaded(id))
304 }
305
306 pub fn create_community(
314 &self,
315 host_address: &str,
316 host_key: PublicKey,
317 name: &str,
318 display_name: &str,
319 ) -> Result<Community> {
320 let root = generate_root_key().map_err(|_| Error::Protocol("no randomness".into()))?;
321 self.create_community_with_root(host_address, host_key, name, display_name, root)
322 }
323
324 pub fn create_community_with_root(
330 &self,
331 host_address: &str,
332 host_key: PublicKey,
333 name: &str,
334 display_name: &str,
335 root: SecretKey,
336 ) -> Result<Community> {
337 let host = HostInfo::new(host_key, vec![host_address.to_owned()]);
338 let (name, display_name) = (name.to_owned(), display_name.to_owned());
339 let id = self.ask(
340 |reply| Request::Create {
341 host,
342 name,
343 display_name,
344 root,
345 reply,
346 },
347 self.inner.join_timeout,
348 "the community creation",
349 )?;
350 Ok(self.loaded(id))
351 }
352
353 pub fn command<B>(
359 &self,
360 community: CommunityId,
361 channel: Option<ChannelId>,
362 body: B,
363 ) -> Result<B::Response>
364 where
365 B: Body + Send + 'static,
366 B::Response: serde::de::DeserializeOwned,
367 {
368 let send: driver::SendFn =
369 Box::new(move |s: &mut Session, now| s.send(&body, Some(community), channel, now));
370 let r: Response = self.ask(
371 |reply| Request::Command {
372 community,
373 send,
374 reply,
375 },
376 self.inner.timeout,
377 B::NAME,
378 )?;
379 r.decode::<B>().map_err(|e| refused(B::NAME, e))
380 }
381
382 pub fn command_named(
393 &self,
394 community: CommunityId,
395 channel: Option<ChannelId>,
396 name: &str,
397 body: serde_json::Value,
398 ) -> Result<serde_json::Value> {
399 let (send, kind) =
400 crate::named::named(name, body, community, channel).map_err(Error::Protocol)?;
401 let r: Response = self.ask(
402 |reply| Request::Command {
403 community,
404 send,
405 reply,
406 },
407 self.inner.timeout,
408 kind,
409 )?;
410 crate::named::answer(kind, r)
411 }
412
413 pub(crate) fn command_json<B>(
415 &self,
416 community: CommunityId,
417 channel: Option<ChannelId>,
418 body: serde_json::Value,
419 ) -> Result<B::Response>
420 where
421 B: Body + Send + 'static,
422 B::Response: serde::de::DeserializeOwned,
423 {
424 let body: B = serde_json::from_value(body)
425 .map_err(|e| Error::Protocol(format!("{}: {e}", B::NAME)))?;
426 self.command(community, channel, body)
427 }
428
429 pub fn close(&self) {
431 let _ = self.inner.requests.send(Request::Stop);
432 if let Some(h) = self
433 .inner
434 .driver
435 .lock()
436 .unwrap_or_else(PoisonError::into_inner)
437 .take()
438 {
439 let _ = h.join();
440 }
441 self.inner.simplex.close();
442 }
443}