use std::collections::HashMap;
use solana_pubkey::Pubkey;
use pyra_types::{Cache, DriftUser, SpotMarket};
use crate::{RedisClient, RedisKey, RedisResult};
impl RedisClient {
pub async fn fetch_drift_user(&self, authority: &Pubkey) -> RedisResult<Option<DriftUser>> {
let key = RedisKey::drift_user(authority);
let cached: Option<Cache<DriftUser>> = self.get_json(key.as_str()).await?;
Ok(cached.map(|c| c.account))
}
pub async fn fetch_spot_market(&self, market_index: u16) -> RedisResult<Option<SpotMarket>> {
let key = RedisKey::drift_spot_market(market_index);
let cached: Option<Cache<SpotMarket>> = self.get_json(key.as_str()).await?;
Ok(cached.map(|c| c.account))
}
pub async fn fetch_spot_markets(
&self,
indices: &[u16],
) -> RedisResult<HashMap<u16, SpotMarket>> {
if indices.is_empty() {
return Ok(HashMap::new());
}
let keys: Vec<String> = indices
.iter()
.map(|&i| RedisKey::drift_spot_market(i).to_string())
.collect();
let values = self.mget(&keys).await?;
let mut result = HashMap::with_capacity(indices.len());
for (idx, val) in indices.iter().zip(values.into_iter()) {
if let Some(raw) = val {
if let Ok(cached) = serde_json::from_str::<Cache<SpotMarket>>(&raw) {
result.insert(*idx, cached.account);
}
}
}
Ok(result)
}
pub async fn fetch_all_spot_markets(&self) -> RedisResult<HashMap<u16, SpotMarket>> {
let pattern = RedisKey::pattern(RedisKey::DRIFT_SPOT_MARKET_PREFIX);
let keys = self.scan_keys(&pattern).await?;
if keys.is_empty() {
return Ok(HashMap::new());
}
let values = self.mget(&keys).await?;
let mut result = HashMap::with_capacity(keys.len());
for val in values.into_iter().flatten() {
if let Ok(cached) = serde_json::from_str::<Cache<SpotMarket>>(&val) {
result.insert(cached.account.market_index, cached.account);
}
}
Ok(result)
}
}