97 lines
2.2 KiB
Rust
97 lines
2.2 KiB
Rust
use aws_sdk_s3::Client;
|
|
use aws_sdk_s3::primitives::ByteStream;
|
|
|
|
#[expect(dead_code)]
|
|
#[derive(Debug)]
|
|
pub enum GetError{
|
|
Get(aws_sdk_s3::error::SdkError<aws_sdk_s3::operation::get_object::GetObjectError>),
|
|
Collect(aws_sdk_s3::primitives::ByteStreamError),
|
|
}
|
|
impl std::fmt::Display for GetError{
|
|
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
|
write!(f,"{self:?}")
|
|
}
|
|
}
|
|
impl std::error::Error for GetError{}
|
|
|
|
#[expect(dead_code)]
|
|
#[derive(Debug)]
|
|
pub enum PutError{
|
|
Put(aws_sdk_s3::error::SdkError<aws_sdk_s3::operation::put_object::PutObjectError>),
|
|
}
|
|
impl std::fmt::Display for PutError{
|
|
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
|
write!(f,"{self:?}")
|
|
}
|
|
}
|
|
impl std::error::Error for PutError{}
|
|
|
|
pub struct S3Cache{
|
|
client:Client,
|
|
bucket:String,
|
|
}
|
|
|
|
impl S3Cache{
|
|
pub fn new(client:Client,bucket:String)->Self{
|
|
Self{client,bucket}
|
|
}
|
|
|
|
/// Try to get a cached object. Returns None if the key doesn't exist.
|
|
pub async fn get(&self,key:&str)->Result<Option<Vec<u8>>,GetError>{
|
|
match self.client.get_object()
|
|
.bucket(&self.bucket)
|
|
.key(key)
|
|
.send()
|
|
.await
|
|
{
|
|
Ok(output)=>{
|
|
let bytes=output.body.collect().await.map_err(GetError::Collect)?;
|
|
Ok(Some(bytes.to_vec()))
|
|
},
|
|
Err(e)=>{
|
|
// check if it's a NoSuchKey error
|
|
if let aws_sdk_s3::error::SdkError::ServiceError(ref service_err)=e{
|
|
if service_err.err().is_no_such_key(){
|
|
return Ok(None);
|
|
}
|
|
}
|
|
Err(GetError::Get(e))
|
|
},
|
|
}
|
|
}
|
|
|
|
/// Put an object into S3.
|
|
pub async fn put(&self,key:&str,data:Vec<u8>)->Result<(),PutError>{
|
|
self.client.put_object()
|
|
.bucket(&self.bucket)
|
|
.key(key)
|
|
.body(ByteStream::from(data))
|
|
.send()
|
|
.await
|
|
.map_err(PutError::Put)?;
|
|
Ok(())
|
|
}
|
|
|
|
// S3 key helpers
|
|
|
|
pub fn texture_raw_key(asset_id:u64)->String{
|
|
format!("assets/textures/{asset_id}.raw")
|
|
}
|
|
|
|
pub fn texture_dds_key(asset_id:u64)->String{
|
|
format!("assets/textures/{asset_id}.dds")
|
|
}
|
|
|
|
pub fn mesh_key(asset_id:u64)->String{
|
|
format!("assets/meshes/{asset_id}")
|
|
}
|
|
|
|
pub fn union_key(asset_id:u64)->String{
|
|
format!("assets/unions/{asset_id}")
|
|
}
|
|
|
|
pub fn snf_key(model_id:u64)->String{
|
|
format!("maps/{model_id}.snfm")
|
|
}
|
|
}
|