use super::client::WgpuClient;
use super::device::WgpuDevice;
use std::collections::HashMap;
#[cfg(feature = "wgpu-raw-interop")]
use std::collections::hash_map::Entry;
use std::sync::{Mutex, OnceLock};
static CLIENT_CACHE: OnceLock<Mutex<HashMap<usize, WgpuClient>>> = OnceLock::new();
pub(super) fn get_cached_client(device: &WgpuDevice) -> Option<WgpuClient> {
let cache = CLIENT_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
let cache_guard = cache.lock().unwrap_or_else(|e| e.into_inner());
cache_guard.get(&device.index).cloned()
}
pub(super) fn insert_or_get_client(client: WgpuClient) -> WgpuClient {
let cache = CLIENT_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
let mut cache_guard = cache.lock().unwrap_or_else(|e| e.into_inner());
cache_guard
.entry(client.device_id.index)
.or_insert(client)
.clone()
}
pub(super) fn get_or_create_client(
device: &WgpuDevice,
) -> Result<WgpuClient, super::device::WgpuError> {
let cache = CLIENT_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
#[cfg(not(target_arch = "wasm32"))]
let mut cache_guard = cache.lock().unwrap_or_else(|e| e.into_inner());
#[cfg(target_arch = "wasm32")]
let cache_guard = cache.lock().unwrap_or_else(|e| e.into_inner());
if let Some(client) = cache_guard.get(&device.index) {
return Ok(client.clone());
}
#[cfg(not(target_arch = "wasm32"))]
{
let client = WgpuClient::new_uncached(device.clone())?;
cache_guard.insert(device.index, client.clone());
Ok(client)
}
#[cfg(target_arch = "wasm32")]
{
Err(super::device::WgpuError::DeviceError(
"WgpuClient must be initialized with WgpuClient::new_async(device).await on wasm32 \
before allocating tensors or dispatching operations"
.into(),
))
}
}
#[cfg(feature = "wgpu-raw-interop")]
pub(super) fn install_client(client: WgpuClient) -> Result<WgpuClient, super::device::WgpuError> {
let cache = CLIENT_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
let mut cache_guard = cache.lock().unwrap_or_else(|e| e.into_inner());
let index = client.device_id.index;
match cache_guard.entry(index) {
Entry::Occupied(_) => Err(super::device::WgpuError::IndexInUse { index }),
Entry::Vacant(slot) => {
slot.insert(client.clone());
Ok(client)
}
}
}