Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache bucket locations #15

Merged
merged 10 commits into from
Jul 18, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
change cache impl
  • Loading branch information
henrikskog committed Jul 15, 2024
commit 7f3bf06e70c55247d10c026c4421c65de7d2b7c2
95 changes: 0 additions & 95 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 0 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,10 @@ dirs = "5.0.1"
humansize = "2.1.3"
itertools = "0.13.0"
itsuki = "0.2.0"
moka = { version = "0.12.8", features = ["sync"] }
once_cell = "1.19.0"
open = "5.2.0"
ratatui = { version = "0.27.0", features = ["unstable-widget-ref"] }
serde = { version = "1.0.204", features = ["derive"] }
serde_json = "=1.0.1"
syntect = { version = "5.2.0", default-features = false, features = [
"default-fancy",
] }
Expand Down
82 changes: 35 additions & 47 deletions src/cache.rs
Original file line number Diff line number Diff line change
@@ -1,86 +1,74 @@
use moka::sync::Cache;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
use std::fs::File;
use std::fs::OpenOptions;
use std::io::Read;
use std::io::{self, Write};
use std::num::NonZeroUsize;
use std::sync::RwLock;

#[derive(Serialize, Deserialize)]
struct CacheEntry<T> {
key: String,
value: T,
}

pub struct SyncMokaCache<T> {
pub cache: Cache<String, T>,
pub struct SimpleStringCache {
pub cache: RwLock<HashMap<String, String>>,
pub file_path: String,
}

impl<T> fmt::Debug for SyncMokaCache<T>
where
T: fmt::Debug + Clone + Send + Sync + 'static, // Added 'static bound
{
impl fmt::Debug for SimpleStringCache {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SyncMokaCache")
let cache = self.cache.read().unwrap();
f.debug_struct("SimpleCache")
.field("file_path", &self.file_path)
.field("cache", &self.cache.iter().collect::<Vec<_>>())
.field("cache", &*cache)
.finish()
}
}

impl<T> SyncMokaCache<T>
where
T: Serialize + for<'de> Deserialize<'de> + Clone + Send + Sync + 'static,
{
pub fn new(size: NonZeroUsize, file_path: String) -> io::Result<Self>
where
T: for<'de> Deserialize<'de>,
{
println!("Initializing cache with size: {} at {}", size, file_path);
let cache = Cache::builder().max_capacity(size.get() as u64).build();
impl SimpleStringCache {
pub fn new(file_path: String) -> io::Result<Self> {
println!("Initializing cache at {}", file_path);
let mut cache = HashMap::new();

if let Ok(mut file) = File::open(&file_path) {
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let entries: Vec<CacheEntry<T>> = serde_json::from_str(&contents)?;
for entry in entries {
cache.insert(entry.key, entry.value);
for line in contents.lines() {
let parts: Vec<&str> = line.split(',').collect();
if parts.len() == 2 {
cache.insert(parts[0].to_string(), parts[1].to_string());
}
}
}

Ok(SyncMokaCache { cache, file_path })
Ok(SimpleStringCache {
cache: RwLock::new(cache),
file_path,
})
}

pub fn put(&self, key: String, value: T) -> io::Result<()> {
self.cache.insert(key.clone(), value);
self.sync_to_file()?;
pub fn put(&self, key: String, value: String) -> io::Result<()> {
{
let mut cache = self.cache.write().unwrap();
cache.insert(key.clone(), value);
}
Ok(())
}

pub fn get(&self, key: &str) -> Option<T> {
self.cache.get(key)
pub fn get(&self, key: &str) -> Option<String> {
let cache = self.cache.read().unwrap();
cache.get(key).cloned()
}

fn sync_to_file(&self) -> io::Result<()> {
pub fn write_cache(&self) -> io::Result<()> {
let temp_file_path = format!("{}.tmp", self.file_path);
let mut file = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(&temp_file_path)?;
let entries: Vec<CacheEntry<T>> = self
.cache
.iter()
.map(|(k, v)| CacheEntry {
key: k.to_string(),
value: v.clone(),
})
.collect();

let json = serde_json::to_string(&entries)?;
file.write_all(json.as_bytes())?;
let cache = self.cache.read().unwrap();
for (key, value) in &*cache {
writeln!(file, "{},{}", key, value)?;
}

std::fs::rename(temp_file_path, &self.file_path)?;
Ok(())
}
Expand Down
15 changes: 7 additions & 8 deletions src/client.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use std::{fmt::Debug, num::NonZero};
use std::fmt::Debug;

use aws_config::{meta::region::RegionProviderChain, BehaviorVersion};
use aws_sdk_s3::{config::Region, operation::list_objects_v2::ListObjectsV2Output};
use chrono::TimeZone;

use crate::{
cache::SyncMokaCache,
cache::SimpleStringCache,
config::Config,
error::{AppError, Result},
object::{BucketItem, FileDetail, FileVersion, ObjectItem, RawObject},
Expand All @@ -17,7 +17,7 @@ const DEFAULT_REGION: &str = "ap-northeast-1";
pub struct Client {
pub client: aws_sdk_s3::Client,
region: String,
bucket_region_cache: SyncMokaCache<String>,
bucket_region_cache: SimpleStringCache,
}

impl Debug for Client {
Expand Down Expand Up @@ -58,11 +58,8 @@ impl Client {
Client {
client,
region,
bucket_region_cache: SyncMokaCache::new(
NonZero::new(1000).unwrap(),
Config::cache_file_path().unwrap(),
)
.unwrap(),
bucket_region_cache: SimpleStringCache::new(Config::cache_file_path().unwrap())
.unwrap(),
}
}

Expand Down Expand Up @@ -92,6 +89,8 @@ impl Client {
}
}

self.bucket_region_cache.write_cache().unwrap();

Ok(buckets_in_region)
}

Expand Down