ctb_network/
network.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Networking service managing WebRTC connections and remote syncing.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29#[allow(
30    unused_imports,
31    clippy::wildcard_imports,
32    reason = "Standard workspace prelude"
33)]
34pub use ctb_utilities::ipc::service_prelude::*;
35
36use async_trait::async_trait;
37use ctb_utilities::ipc::service_traits::ChildIpcContext;
38use std::sync::{Arc, OnceLock};
39
40// pub mod webrtc;
41
42#[ipc_method]
43/// Echo bytes back.
44pub async fn echo(bytes: Vec<u8>) -> Result<Vec<u8>> {
45    Ok(bytes.clone())
46}
47
48#[ipc_method]
49/// Fetch bytes from a URL.
50pub async fn fetch(url: String) -> Result<Vec<u8>> {
51    if url.starts_with("https://") {
52        return backend()?.fetch_https(&url).await;
53    }
54
55    if url.starts_with("http://") {
56        return backend()?.fetch_http(&url).await;
57    }
58
59    bail!("unsupported scheme for url {url}");
60}
61
62#[ipc_method]
63/// Read a file into memory.
64pub async fn read_file(path: String) -> Result<Vec<u8>> {
65    backend()?.read_file(path).await
66}
67
68pub async fn get_url(key: &str) -> Result<Vec<u8>> {
69    fetch(key.to_string()).await
70}
71
72static NETWORK_BACKEND: OnceLock<Arc<dyn NetworkBackend>> = OnceLock::new();
73
74/// Initialize the network backend used by registry-based IPC methods.
75///
76/// This is intended to be called once by the network subprocess during
77/// startup.
78pub fn init_backend(backend: &Arc<dyn NetworkBackend>) -> Result<()> {
79    if NETWORK_BACKEND.set(Arc::clone(backend)).is_err() {
80        return Ok(());
81    }
82    Ok(())
83}
84
85fn backend() -> Result<&'static Arc<dyn NetworkBackend>> {
86    NETWORK_BACKEND
87        .get()
88        .ok_or_else(|| anyhow::anyhow!("network backend not initialized"))
89}
90
91/// Networking backend that the IPC layer depends on.
92#[async_trait]
93pub trait NetworkBackend: Send + Sync {
94    /// Fetch bytes over HTTP.
95    async fn fetch_http(&self, url: &str) -> Result<Vec<u8>>;
96
97    /// Fetch bytes over HTTPS.
98    async fn fetch_https(&self, url: &str) -> Result<Vec<u8>>;
99
100    /// Read a local file into memory.
101    async fn read_file(&self, path: String) -> Result<Vec<u8>>;
102}
103
104/// Default implementation. This will eventually include APIs for a
105/// WebRTC transport, but for now returns clear errors for unimplemented paths.
106#[derive(Debug, Default)]
107pub struct DefaultNetworkBackend;
108
109#[async_trait]
110impl NetworkBackend for DefaultNetworkBackend {
111    async fn fetch_http(&self, url: &str) -> Result<Vec<u8>> {
112        https::get_success(url)
113            .await
114            .with_context(|| format!("http(s) GET {url}"))
115    }
116
117    async fn fetch_https(&self, url: &str) -> Result<Vec<u8>> {
118        return self.fetch_http(url).await;
119    }
120
121    async fn read_file(&self, path: String) -> Result<Vec<u8>> {
122        tokio::fs::read(&path)
123            .await
124            .with_context(|| format!("read file at {path}"))
125    }
126}
127
128#[derive(Debug, Default)]
129pub struct MockNetworkBackend;
130#[async_trait]
131impl NetworkBackend for MockNetworkBackend {
132    async fn fetch_http(&self, url: &str) -> Result<Vec<u8>> {
133        if url == "http://example.com" {
134            return Ok(b"Example HTTP Fetch".to_vec());
135        }
136        bail!(
137            "MockNetworkingBackend only supports http and https fetches of http://example.com"
138        );
139    }
140
141    async fn fetch_https(&self, url: &str) -> Result<Vec<u8>> {
142        if url == "https://example.com" {
143            return Ok(b"Example HTTPS Fetch".to_vec());
144        }
145        bail!(
146            "MockNetworkingBackend only supports http and https fetches of https://example.com"
147        );
148    }
149
150    async fn read_file(&self, path: String) -> Result<Vec<u8>> {
151        if path == "/tmp/example/file.txt" {
152            return Ok(b"Example File Read".to_vec());
153        }
154        bail!("MockNetworkingBackend only provides /tmp/example/file.txt");
155    }
156}
157
158#[cfg(test)]
159#[allow(
160    clippy::panic,
161    clippy::expect_used,
162    clippy::unwrap_used,
163    clippy::unwrap_in_result,
164    clippy::panic_in_result_fn,
165    clippy::indexing_slicing,
166    clippy::arithmetic_side_effects,
167    reason = "Standard repository test boilerplate"
168)]
169mod tests {}