Skip to main content

simploxide_client/
ffi.rs

1//! FFI backend that embeds the SimpleX-Chat library in-process via native Rust bindings.
2//!
3//! Use [`BotBuilder`] to initialise the FFI runtime and get a ready-to-use [`Bot`].
4//! For lower-level access, [`init`] and [`init_with_config`] return a [`Client`] and an
5//! [`EventStream`](crate::EventStream) directly.
6//!
7//! Requires AGPL-3.0 and additional build configuration. See `simploxide-sxcrt-sys`.
8
9pub use simploxide_ffi_core::{
10    CallError, DbOpts, DefaultUser, Event as CoreEvent, InitError as CoreInitError, RawClient,
11    Result as CoreResult, SimplexVersion, VersionError, WorkerConfig,
12};
13
14use simploxide_api_types::{
15    Preferences, Profile,
16    client_api::{ExtractResponse as _, FfiResponseShape},
17    events::{Event, EventKind},
18};
19use simploxide_core::{MAX_SUPPORTED_VERSION, MIN_SUPPORTED_VERSION};
20
21use std::sync::Arc;
22
23use crate::{
24    BadResponseError, ClientApi, ClientApiError, EventParser,
25    bot::{BotProfileSettings, BotSettings},
26    id::UserId,
27    preview::ImagePreview,
28    util,
29};
30
31pub type EventResult = CoreResult<CoreEvent>;
32pub type EventStream = crate::EventStream<EventResult>;
33pub type ClientResult<T = ()> = ::std::result::Result<T, ClientError>;
34
35#[cfg(not(feature = "xftp"))]
36pub type Bot = crate::bot::Bot<Client>;
37
38#[cfg(feature = "xftp")]
39pub type Bot = crate::bot::Bot<crate::xftp::XftpClient<Client>>;
40
41#[cfg(feature = "farm")]
42pub type FarmBot = crate::bot::farm::FarmBot<Client>;
43
44#[cfg(feature = "farm")]
45pub type InitFarm = crate::bot::farm::InitFarm<Client, EventResult>;
46
47#[cfg(feature = "farm")]
48pub type RunningFarm = crate::bot::farm::RunningFarm<Client, EventResult>;
49
50pub async fn init(
51    default_user: DefaultUser,
52    db_opts: DbOpts,
53) -> Result<(Client, EventStream), InitError> {
54    init_with_config(default_user, db_opts, WorkerConfig::default()).await
55}
56
57pub async fn init_with_config(
58    default_user: DefaultUser,
59    db_opts: DbOpts,
60    config: WorkerConfig,
61) -> Result<(Client, EventStream), InitError> {
62    let (raw_client, raw_event_queue) =
63        simploxide_ffi_core::init_with_config(default_user, db_opts, config).await?;
64
65    let version = raw_client
66        .version()
67        .await
68        .map_err(InitError::VersionError)?;
69
70    if !version.is_supported() {
71        return Err(InitError::VersionMismatch(version));
72    }
73
74    Ok((
75        Client::from(raw_client),
76        EventStream::from(raw_event_queue.into_receiver()),
77    ))
78}
79
80/// A cheaply clonable high-level FFI client implementing [`ClientApi`]
81#[derive(Clone)]
82pub struct Client {
83    inner: RawClient,
84}
85
86impl From<RawClient> for Client {
87    fn from(inner: RawClient) -> Self {
88        Self { inner }
89    }
90}
91
92/// A high level SimpleX-Chat client which provides typed API methods with automatic command
93/// serialization and response deserialization.
94impl Client {
95    pub fn version(&self) -> impl Future<Output = Result<SimplexVersion, VersionError>> {
96        self.inner.version()
97    }
98
99    /// Initiates a graceful shutdown for the underlying web socket connection. See
100    /// [`simploxide_ffi_core::RawClient::disconnect`] for details.
101    pub fn disconnect(self) -> impl Future<Output = ()> {
102        self.inner.disconnect()
103    }
104}
105
106impl ClientApi for Client {
107    type ResponseShape<'de, T>
108        = FfiResponseShape<T>
109    where
110        T: 'de + serde::Deserialize<'de>;
111
112    type Error = ClientError;
113
114    async fn send_raw(&self, command: String) -> Result<String, Self::Error> {
115        self.inner
116            .send(command)
117            .await
118            .map_err(ClientError::FfiFailure)
119    }
120}
121
122impl EventParser for EventResult {
123    type Error = ClientError;
124
125    fn parse_kind(&self) -> Result<EventKind, Self::Error> {
126        match parse_data::<util::TypeField<'_>>(self) {
127            Ok(f) => Ok(EventKind::from_type_str(f.typ)),
128            // FFI chat error shapes are the same for events and responses which confuses the parser therefore
129            // chat errors must be handled manually
130            Err(ClientError::BadResponse(BadResponseError::ChatError(_))) => {
131                Ok(EventKind::ChatError)
132            }
133            Err(ClientError::BadResponse(BadResponseError::Undocumented(_))) => {
134                Ok(EventKind::Undocumented)
135            }
136            Err(e) => Err(e),
137        }
138    }
139
140    fn parse_user_id(&self) -> Result<Option<UserId>, Self::Error> {
141        match parse_data::<util::UserField>(self) {
142            Ok(f) => Ok(UserId::try_from(f.user.user_id).ok()),
143            Err(ClientError::BadResponse(_)) => Ok(None),
144            Err(e) => Err(e),
145        }
146    }
147
148    fn parse_event(&self) -> Result<Event, Self::Error> {
149        match parse_data(self) {
150            Ok(ev) => Ok(ev),
151            // FFI chat error shapes are the same for events and responses which confuses the parser therefore
152            // chat errors must be handled manually
153            Err(ClientError::BadResponse(BadResponseError::ChatError(err))) => Ok(
154                Event::ChatError(Arc::new(simploxide_api_types::events::ChatError {
155                    chat_error: err.as_ref().clone(),
156                    undocumented: Default::default(),
157                })),
158            ),
159            Err(ClientError::BadResponse(BadResponseError::Undocumented(json))) => {
160                Ok(Event::Undocumented(json))
161            }
162            Err(e) => Err(e),
163        }
164    }
165}
166
167fn parse_data<'de, 'r: 'de, D: 'de + serde::Deserialize<'de>>(
168    result: &'r EventResult,
169) -> Result<D, ClientError> {
170    result
171        .as_ref()
172        .map_err(|e| ClientError::FfiFailure(e.clone()))
173        .and_then(|ev| {
174            serde_json::from_str::<FfiResponseShape<D>>(ev)
175                .map_err(BadResponseError::InvalidJson)
176                .and_then(|shape| shape.extract_response())
177                .map_err(ClientError::BadResponse)
178        })
179}
180
181/// Builder for an FFI-backed [`Bot`].
182#[derive(Clone)]
183pub struct BotBuilder {
184    display_name: String,
185    db_opts: DbOpts,
186    default_user: Option<DefaultUser>,
187    auto_accept: Option<String>,
188    profile: Option<Profile>,
189    preferences: Option<Preferences>,
190    avatar: Option<ImagePreview>,
191    worker_config: WorkerConfig,
192}
193
194impl BotBuilder {
195    /// Build a bot account (default).
196    pub fn new(name: impl Into<String>, db_opts: DbOpts) -> Self {
197        Self {
198            display_name: name.into(),
199            db_opts,
200            default_user: None,
201            auto_accept: None,
202            profile: None,
203            preferences: None,
204            avatar: None,
205            worker_config: WorkerConfig::default(),
206        }
207    }
208
209    /// Override the default user created for empty databases.
210    ///
211    /// By default the default user name matches the bot name. This setting allows to create a user
212    /// different from an active bot
213    pub fn with_default_user(mut self, user: DefaultUser) -> Self {
214        self.default_user = Some(user);
215        self
216    }
217
218    /// Create public address and auto accept users
219    pub fn auto_accept(mut self) -> Self {
220        self.auto_accept = Some(String::default());
221        self
222    }
223
224    /// [Self::auto_accept] with a welcome message
225    pub fn auto_accept_with(mut self, welcome_message: impl Into<String>) -> Self {
226        self.auto_accept = Some(welcome_message.into());
227        self
228    }
229
230    /// Set the bot avatar during initialisation
231    pub fn with_avatar(mut self, avatar: ImagePreview) -> Self {
232        self.avatar = Some(avatar);
233        self
234    }
235
236    /// Update/create the whole bot profile on launch
237    pub fn with_profile(mut self, profile: Profile) -> Self {
238        self.profile = Some(profile);
239        self
240    }
241
242    /// Apply these preferences to the bot's profile during initialisation.
243    pub fn with_preferences(mut self, prefs: Preferences) -> Self {
244        self.preferences = Some(prefs);
245        self
246    }
247
248    /// Set max permissible event latency. See [`WorkerConfig::max_event_latency`] for details
249    pub fn max_event_latency(mut self, latency: std::time::Duration) -> Self {
250        self.worker_config.max_event_latency = Some(latency);
251        self
252    }
253
254    /// Set max concurrent SimpleX-Chat instances. See [`WorkerConfig::max_instances`] for details
255    pub fn max_instances(mut self, instances: usize) -> Self {
256        self.worker_config.max_instances = Some(instances);
257        self
258    }
259
260    /// Initialise the SimpleX FFI runtime and return a ready-to-use bot.
261    pub async fn launch(self) -> Result<(Bot, EventStream), BotInitError> {
262        let default_user = self
263            .default_user
264            .unwrap_or_else(|| DefaultUser::bot(&self.display_name));
265
266        let (client, events) = init_with_config(default_user, self.db_opts, self.worker_config)
267            .await
268            .map_err(BotInitError::Init)?;
269
270        #[cfg(feature = "xftp")]
271        let (client, events) = events.hook_xftp(client);
272
273        let settings = BotSettings {
274            display_name: self.display_name,
275            auto_accept: self.auto_accept,
276            profile_settings: match (self.profile, self.preferences) {
277                (Some(mut profile), Some(preferences)) => {
278                    profile.preferences = Some(preferences);
279                    Some(BotProfileSettings::FullProfile(profile))
280                }
281                (Some(profile), None) => Some(BotProfileSettings::FullProfile(profile)),
282                (None, Some(preferences)) => Some(BotProfileSettings::Preferences(preferences)),
283                (None, None) => None,
284            },
285            avatar: self.avatar,
286        };
287
288        let bot = Bot::init(client, settings).await?;
289
290        let mut events = events;
291        events.set_owner(bot.user_id());
292
293        Ok((bot, events))
294    }
295}
296
297#[cfg(feature = "farm")]
298#[derive(Clone)]
299pub struct BotFarmBuilder {
300    display_name: String,
301    db_opts: DbOpts,
302    default_user: Option<DefaultUser>,
303    worker_config: WorkerConfig,
304}
305
306#[cfg(feature = "farm")]
307impl BotFarmBuilder {
308    pub fn new(name: impl Into<String>, db_opts: DbOpts) -> Self {
309        Self {
310            display_name: name.into(),
311            db_opts,
312            default_user: None,
313            worker_config: WorkerConfig::default(),
314        }
315    }
316
317    /// Override the default user created for empty databases.
318    ///
319    /// By default the default user name matches the bot name. This setting allows to create a user
320    /// different from an active bot
321    pub fn with_default_user(mut self, user: DefaultUser) -> Self {
322        self.default_user = Some(user);
323        self
324    }
325
326    /// Set max permissible event latency. See [`WorkerConfig::max_event_latency`] for details
327    pub fn max_event_latency(mut self, latency: std::time::Duration) -> Self {
328        self.worker_config.max_event_latency = Some(latency);
329        self
330    }
331
332    /// Set max concurrent SimpleX-Chat instances. See [`WorkerConfig::max_instances`] for details
333    pub fn max_instances(mut self, instances: usize) -> Self {
334        self.worker_config.max_instances = Some(instances);
335        self
336    }
337
338    /// Initialise the SimpleX FFI runtime and return a farm
339    pub async fn launch(self) -> Result<InitFarm, BotInitError> {
340        let default_user = self
341            .default_user
342            .unwrap_or_else(|| DefaultUser::bot(&self.display_name));
343
344        let (client, events) = init_with_config(default_user, self.db_opts, self.worker_config)
345            .await
346            .map_err(BotInitError::Init)?;
347
348        let bot = crate::bot::BotFarm::init(self.display_name, client, events).await?;
349        Ok(bot)
350    }
351}
352
353/// See [`crate::client_api::AllowUndocumentedResponses`] if you don't want to trigger an error
354/// when you receive undocumeted responses(you usually receive undocumented responses when your
355/// simplex-chat version is not compatible with the current simploxide-client version. Keep an eye
356/// on the [Version compatability table](https://github.com/a1akris/simploxide?tab=readme-ov-file#version-compatability-table))
357#[derive(Debug)]
358pub enum ClientError {
359    FfiFailure(Arc<CallError>),
360    BadResponse(BadResponseError),
361}
362
363impl std::error::Error for ClientError {
364    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
365        match self {
366            Self::FfiFailure(error) => Some(error),
367            Self::BadResponse(error) => Some(error),
368        }
369    }
370}
371
372impl std::fmt::Display for ClientError {
373    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
374        match self {
375            ClientError::FfiFailure(err) => writeln!(f, "FFI error: {err}"),
376            ClientError::BadResponse(err) => err.fmt(f),
377        }
378    }
379}
380
381impl From<BadResponseError> for ClientError {
382    fn from(err: BadResponseError) -> Self {
383        Self::BadResponse(err)
384    }
385}
386
387impl ClientApiError for ClientError {
388    fn bad_response(&self) -> Option<&BadResponseError> {
389        if let Self::BadResponse(resp) = self {
390            Some(resp)
391        } else {
392            None
393        }
394    }
395
396    fn bad_response_mut(&mut self) -> Option<&mut BadResponseError> {
397        if let Self::BadResponse(resp) = self {
398            Some(resp)
399        } else {
400            None
401        }
402    }
403}
404
405#[derive(Debug)]
406pub enum InitError {
407    /// Failure to init the FFI instance
408    Ffi(CoreInitError),
409    /// Failure to get the backend version
410    VersionError(VersionError),
411    /// Unsupported backend version
412    VersionMismatch(SimplexVersion),
413}
414
415impl InitError {
416    pub fn is_ffi(&self) -> bool {
417        matches!(self, Self::Ffi(_))
418    }
419
420    pub fn is_version_mismatch(&self) -> bool {
421        matches!(self, Self::VersionMismatch(_))
422    }
423}
424
425impl From<CoreInitError> for InitError {
426    fn from(value: CoreInitError) -> Self {
427        Self::Ffi(value)
428    }
429}
430
431impl std::fmt::Display for InitError {
432    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
433        match self {
434            Self::Ffi(error) => write!(f, "Cannot initialize the FFI backend: {error}"),
435            Self::VersionError(error) => write!(f, "Cannot get FFI version {error}"),
436            Self::VersionMismatch(v) => write!(
437                f,
438                "Version {v} is unsupported by the current client. Supported versions are {MIN_SUPPORTED_VERSION}..{MAX_SUPPORTED_VERSION}"
439            ),
440        }
441    }
442}
443
444impl std::error::Error for InitError {
445    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
446        match self {
447            Self::Ffi(error) => Some(error),
448            Self::VersionError(error) => Some(error),
449            Self::VersionMismatch(_) => None,
450        }
451    }
452}
453
454/// Error returned by [`BotBuilder::launch`].
455#[derive(Debug)]
456pub enum BotInitError {
457    Init(InitError),
458    Api(ClientError),
459}
460
461impl std::fmt::Display for BotInitError {
462    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
463        match self {
464            Self::Init(e) => write!(f, "SimpleX FFI init failed: {e}"),
465            Self::Api(e) => write!(f, "SimpleX API error during init: {e}"),
466        }
467    }
468}
469
470impl std::error::Error for BotInitError {
471    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
472        match self {
473            Self::Init(e) => Some(e),
474            Self::Api(e) => Some(e),
475        }
476    }
477}
478
479impl From<ClientError> for BotInitError {
480    fn from(e: ClientError) -> Self {
481        Self::Api(e)
482    }
483}