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
6// work around not yet having https://github.com/mozilla/uniffi-rs/pull/2963.
7#![allow(const_evaluatable_unchecked)]
8
9use std::sync::{Arc, OnceLock};
10
11use crate::{ClientSettings, Request, Response, Result, ViaductError};
12
13#[uniffi::export(with_foreign)]
14#[async_trait::async_trait]
15pub trait Backend: Send + Sync + 'static {
16    async fn send_request(&self, request: Request, settings: ClientSettings) -> Result<Response>;
17}
18
19static REGISTERED_BACKEND: OnceLock<Arc<dyn Backend>> = OnceLock::new();
20
21#[uniffi::export]
22pub fn init_backend(backend: Arc<dyn Backend>) {
23    if REGISTERED_BACKEND.set(backend).is_err() {
24        error_support::report_error!(
25            "viaduct-multiple-init-backend",
26            "init_backend called multiple times"
27        );
28    }
29}
30
31pub fn get_backend() -> Result<&'static Arc<dyn Backend>> {
32    REGISTERED_BACKEND
33        .get()
34        .ok_or(ViaductError::BackendNotInitialized)
35}