viaduct/
backend.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3*
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5
6use std::sync::{Arc, OnceLock};
7
8use crate::{ClientSettings, Request, Response, Result, ViaductError};
9
10#[uniffi::export(with_foreign)]
11#[async_trait::async_trait]
12pub trait Backend: Send + Sync + 'static {
13    async fn send_request(&self, request: Request, settings: ClientSettings) -> Result<Response>;
14}
15
16static REGISTERED_BACKEND: OnceLock<Arc<dyn Backend>> = OnceLock::new();
17
18#[uniffi::export]
19pub fn init_backend(backend: Arc<dyn Backend>) {
20    if REGISTERED_BACKEND.set(backend).is_err() {
21        error_support::report_error!(
22            "viaduct-multiple-init-backend",
23            "init_backend called multiple times"
24        );
25    }
26}
27
28pub fn get_backend() -> Result<&'static Arc<dyn Backend>> {
29    REGISTERED_BACKEND
30        .get()
31        .ok_or(ViaductError::BackendNotInitialized)
32}