|
| 1 | +use std::{fmt, fs, io::Write, path::PathBuf, time::Duration}; |
| 2 | + |
| 3 | +use actix_multipart::Field; |
| 4 | +use futures::StreamExt; |
| 5 | +use opendal::{services::S3, Operator}; |
| 6 | + |
| 7 | +use crate::{appstate::AppState, config::Config, errors::AtomicServerResult}; |
| 8 | + |
| 9 | +#[derive(Clone, Debug, PartialEq)] |
| 10 | +pub enum FileStore { |
| 11 | + S3(S3Config), |
| 12 | + FS(FSConfig), |
| 13 | +} |
| 14 | + |
| 15 | +#[derive(Clone, Debug, PartialEq)] |
| 16 | +pub struct S3Config { |
| 17 | + pub bucket: String, |
| 18 | + pub path: String, |
| 19 | + pub endpoint: Option<String>, |
| 20 | + pub region: Option<String>, |
| 21 | +} |
| 22 | + |
| 23 | +#[derive(Clone, Debug, PartialEq)] |
| 24 | +pub struct FSConfig { |
| 25 | + pub path: PathBuf, |
| 26 | +} |
| 27 | + |
| 28 | +impl FileStore { |
| 29 | + const S3_PREFIX: &'static str = "s3:"; |
| 30 | + const FS_PREFIX: &'static str = "fs:"; |
| 31 | + |
| 32 | + pub fn init_fs_from_config(config: &Config) -> FileStore { |
| 33 | + FileStore::FS(FSConfig { |
| 34 | + path: config.uploads_path.clone(), |
| 35 | + }) |
| 36 | + } |
| 37 | + |
| 38 | + pub fn init_from_config(config: &Config, fs_file_store: FileStore) -> FileStore { |
| 39 | + let opts = &config.opts; |
| 40 | + if let Some(bucket) = &opts.s3_bucket { |
| 41 | + let config = S3Config { |
| 42 | + bucket: bucket.clone(), |
| 43 | + endpoint: opts.s3_endpoint.clone(), |
| 44 | + region: opts.s3_region.clone(), |
| 45 | + path: opts.s3_path.clone().unwrap_or("uploads".to_string()), |
| 46 | + }; |
| 47 | + FileStore::S3(config) |
| 48 | + } else { |
| 49 | + fs_file_store |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + pub fn get_subject_file_store<'a>(appstate: &'a AppState, subject: &str) -> &'a FileStore { |
| 54 | + if subject.contains(Self::S3_PREFIX) { |
| 55 | + &appstate.file_store |
| 56 | + } else { |
| 57 | + &appstate.fs_file_store |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + pub fn get_fs_file_path(&self, file_id: &str) -> AtomicServerResult<PathBuf> { |
| 62 | + if let FileStore::FS(config) = self { |
| 63 | + let fs_file_id = file_id.strip_prefix(Self::FS_PREFIX).unwrap_or(file_id); |
| 64 | + let mut file_path = config.path.clone(); |
| 65 | + file_path.push(fs_file_id.to_string()); |
| 66 | + Ok(file_path) |
| 67 | + } else { |
| 68 | + Err("Wrong FileStore passed to get_fs_file_path".into()) |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + pub fn prefix(&self) -> &str { |
| 73 | + match self { |
| 74 | + Self::S3(_) => Self::S3_PREFIX, |
| 75 | + Self::FS(_) => Self::FS_PREFIX, |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + pub fn encoded(&self) -> String { |
| 80 | + urlencoding::encode(self.prefix()).into_owned() |
| 81 | + } |
| 82 | + |
| 83 | + pub async fn upload_file(&self, file_id: &str, field: Field) -> AtomicServerResult<i64> { |
| 84 | + match self { |
| 85 | + FileStore::S3(_) => s3_upload(self, &file_id, field).await, |
| 86 | + FileStore::FS(config) => fs_upload(self, &config, &file_id, field).await, |
| 87 | + } |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | +impl fmt::Display for FileStore { |
| 92 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 93 | + write!(f, "{}", self.prefix()) |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +async fn fs_upload( |
| 98 | + file_store: &FileStore, |
| 99 | + config: &FSConfig, |
| 100 | + file_id: &str, |
| 101 | + mut field: Field, |
| 102 | +) -> AtomicServerResult<i64> { |
| 103 | + std::fs::create_dir_all(config.path.clone())?; |
| 104 | + |
| 105 | + let mut file = fs::File::create(file_store.get_fs_file_path(file_id)?)?; |
| 106 | + |
| 107 | + let byte_count: i64 = file |
| 108 | + .metadata()? |
| 109 | + .len() |
| 110 | + .try_into() |
| 111 | + .map_err(|_e| "Too large")?; |
| 112 | + |
| 113 | + // Field in turn is stream of *Bytes* object |
| 114 | + while let Some(chunk) = field.next().await { |
| 115 | + let data = chunk.map_err(|e| format!("Error while reading multipart data. {}", e))?; |
| 116 | + // TODO: Update a SHA256 hash here for checksum |
| 117 | + file.write_all(&data)?; |
| 118 | + } |
| 119 | + |
| 120 | + Ok(byte_count) |
| 121 | +} |
| 122 | + |
| 123 | +async fn s3_upload( |
| 124 | + file_store: &FileStore, |
| 125 | + file_id: &str, |
| 126 | + mut field: Field, |
| 127 | +) -> AtomicServerResult<i64> { |
| 128 | + let mut builder = S3::default(); |
| 129 | + |
| 130 | + if let FileStore::S3(config) = file_store { |
| 131 | + builder.bucket(&config.bucket); |
| 132 | + builder.root(&config.path); |
| 133 | + config.region.as_ref().map(|r| builder.region(&r)); |
| 134 | + config.endpoint.as_ref().map(|e| builder.endpoint(&e)); |
| 135 | + } else { |
| 136 | + return Err("Uploading to S3 but no S3 config provided".into()); |
| 137 | + } |
| 138 | + |
| 139 | + let op: Operator = Operator::new(builder)?.finish(); |
| 140 | + let mut w = op.writer(file_id).await?; |
| 141 | + let mut len = 0; |
| 142 | + while let Some(chunk) = field.next().await { |
| 143 | + let data = chunk.map_err(|e| format!("Error while reading multipart data. {}", e))?; |
| 144 | + len = len + data.len(); |
| 145 | + w.write(data).await?; |
| 146 | + } |
| 147 | + |
| 148 | + let byte_length: i64 = len.try_into().map_err(|_e| "Too large")?; |
| 149 | + w.close().await?; |
| 150 | + Ok(byte_length) |
| 151 | +} |
| 152 | + |
| 153 | +pub async fn get_s3_signed_url( |
| 154 | + file_store: &FileStore, |
| 155 | + duration: Duration, |
| 156 | + file_id: &str, |
| 157 | +) -> AtomicServerResult<String> { |
| 158 | + let mut builder = S3::default(); |
| 159 | + |
| 160 | + if let FileStore::S3(config) = file_store { |
| 161 | + builder.bucket(&config.bucket); |
| 162 | + builder.root(&config.path); |
| 163 | + config.region.as_ref().map(|r| builder.region(&r)); |
| 164 | + config.endpoint.as_ref().map(|e| builder.endpoint(&e)); |
| 165 | + } else { |
| 166 | + return Err("Downloading from S3 but no S3 config provided".into()); |
| 167 | + } |
| 168 | + |
| 169 | + let op: Operator = Operator::new(builder)?.finish(); |
| 170 | + |
| 171 | + let uri = op.presign_read(file_id, duration).await?.uri().to_string(); |
| 172 | + |
| 173 | + Ok(uri) |
| 174 | +} |
0 commit comments