ctb_workspace_ipc/multiplex/
blob_store.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//! Simple blob store utilities used by blob-backed streams.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use crate::error::Error;
30use crate::error::to_ipc_error;
31use anyhow::anyhow;
32use async_trait::async_trait;
33use bytes::Bytes;
34use ctb_utilities::shared_memory::BlobToken;
35use std::collections::HashMap;
36
37/// Simple blob store interface used for blob-backed flows.
38///
39/// In production this would map to a real data plane (shared memory, file,
40/// socket, etc). For now it is used for integration tests.
41#[async_trait]
42pub trait BlobStore: Send + Sync {
43    async fn put(&self, token: BlobToken, bytes: Bytes) -> Result<(), Error>;
44
45    async fn take(&self, token: &BlobToken) -> Result<Bytes, Error>;
46
47    async fn len(&self) -> Result<usize, Error>;
48}
49
50/// In-memory `BlobStore` used by tests (and as a reference implementation).
51#[derive(Debug, Default)]
52pub struct InMemoryBlobStore {
53    inner: tokio::sync::Mutex<HashMap<BlobToken, Bytes>>,
54}
55
56#[async_trait]
57impl BlobStore for InMemoryBlobStore {
58    async fn put(&self, token: BlobToken, bytes: Bytes) -> Result<(), Error> {
59        let mut guard = self.inner.lock().await;
60        guard.insert(token, bytes);
61        Ok(())
62    }
63
64    async fn take(&self, token: &BlobToken) -> Result<Bytes, Error> {
65        let mut guard = self.inner.lock().await;
66        let Some(bytes) = guard.remove(token) else {
67            return Err(to_ipc_error(anyhow!("unknown blob token")));
68        };
69        Ok(bytes)
70    }
71
72    async fn len(&self) -> Result<usize, Error> {
73        let guard = self.inner.lock().await;
74        Ok(guard.len())
75    }
76}