| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | use turso::{Connection, Row}; |
| 11 | |
| 12 | use crate::error::{Error, Result}; |
| 13 | use crate::quota; |
| 14 | use crate::store::files::{File, NewFile, insert_file_in}; |
| 15 | use crate::store::folders::live_folder; |
| 16 | use crate::store::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish}; |
| 17 | use crate::time::now_stamp; |
| 18 | |
| 19 | |
| 20 | |
| 21 | pub const MAX_OPEN_UPLOADS: i64 = 64; |
| 22 | |
| 23 | |
| 24 | pub const UPLOAD_COLS: &str = |
| 25 | "id, owner, folder_id, name, size, chunk_size, state, file_id, created_at, expires_at"; |
| 26 | |
| 27 | |
| 28 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 29 | pub struct Upload { |
| 30 | |
| 31 | pub id: String, |
| 32 | |
| 33 | pub owner: String, |
| 34 | |
| 35 | pub folder_id: Option<String>, |
| 36 | |
| 37 | pub name: String, |
| 38 | |
| 39 | pub size: i64, |
| 40 | |
| 41 | pub chunk_size: i64, |
| 42 | |
| 43 | pub state: String, |
| 44 | |
| 45 | pub file_id: Option<String>, |
| 46 | |
| 47 | pub created_at: String, |
| 48 | |
| 49 | pub expires_at: String, |
| 50 | } |
| 51 | |
| 52 | impl Upload { |
| 53 | |
| 54 | pub fn is_open(&self, now: &str) -> bool { |
| 55 | self.state == "active" && self.expires_at.as_str() > now |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | |
| 60 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 61 | pub struct NewUpload { |
| 62 | |
| 63 | pub id: String, |
| 64 | |
| 65 | pub owner: String, |
| 66 | |
| 67 | pub folder: Option<String>, |
| 68 | |
| 69 | pub name: String, |
| 70 | |
| 71 | pub size: i64, |
| 72 | |
| 73 | pub chunk_size: i64, |
| 74 | |
| 75 | pub expires_at: String, |
| 76 | } |
| 77 | |
| 78 | |
| 79 | pub fn map_upload(row: &Row) -> Result<Upload> { |
| 80 | Ok(Upload { |
| 81 | id: col_text(row, 0)?, |
| 82 | owner: col_text(row, 1)?, |
| 83 | folder_id: col_opt_text(row, 2)?, |
| 84 | name: col_text(row, 3)?, |
| 85 | size: col_int(row, 4)?, |
| 86 | chunk_size: col_int(row, 5)?, |
| 87 | state: col_text(row, 6)?, |
| 88 | file_id: col_opt_text(row, 7)?, |
| 89 | created_at: col_text(row, 8)?, |
| 90 | expires_at: col_text(row, 9)?, |
| 91 | }) |
| 92 | } |
| 93 | |
| 94 | |
| 95 | async fn upload_of(conn: &Connection, owner: &str, id: &str) -> Result<Option<Upload>> { |
| 96 | fetch_opt( |
| 97 | conn, |
| 98 | &format!("SELECT {UPLOAD_COLS} FROM uploads WHERE id = ?1 AND owner = ?2"), |
| 99 | (id.to_string(), owner.to_string()), |
| 100 | map_upload, |
| 101 | ) |
| 102 | .await |
| 103 | } |
| 104 | |
| 105 | |
| 106 | |
| 107 | async fn declared_claims(conn: &Connection, owner: &str, now: &str, except: &str) -> Result<i64> { |
| 108 | fetch_opt( |
| 109 | conn, |
| 110 | "SELECT COALESCE(SUM(size), 0) FROM uploads \ |
| 111 | WHERE owner = ?1 AND state = 'active' AND expires_at > ?2 AND id <> ?3", |
| 112 | (owner.to_string(), now.to_string(), except.to_string()), |
| 113 | |row| col_int(row, 0), |
| 114 | ) |
| 115 | .await |
| 116 | .map(|sum| sum.unwrap_or(0)) |
| 117 | } |
| 118 | |
| 119 | impl Store { |
| 120 | |
| 121 | pub async fn declared_claims_of(&self, owner: &str) -> Result<i64> { |
| 122 | let conn = self.read_conn().await; |
| 123 | declared_claims(&conn, owner, &now_stamp(), "").await |
| 124 | } |
| 125 | |
| 126 | |
| 127 | pub async fn upload(&self, owner: &str, id: &str) -> Result<Option<Upload>> { |
| 128 | let conn = self.read_conn().await; |
| 129 | upload_of(&conn, owner, id).await |
| 130 | } |
| 131 | |
| 132 | |
| 133 | |
| 134 | pub async fn upload_is_open(&self, id: &str) -> Result<bool> { |
| 135 | let conn = self.read_conn().await; |
| 136 | Ok(fetch_opt( |
| 137 | &conn, |
| 138 | "SELECT 1 FROM uploads WHERE id = ?1 AND state = 'active'", |
| 139 | (id.to_string(),), |
| 140 | |row| col_int(row, 0), |
| 141 | ) |
| 142 | .await? |
| 143 | .is_some()) |
| 144 | } |
| 145 | |
| 146 | |
| 147 | |
| 148 | |
| 149 | |
| 150 | pub async fn create_upload(&self, new: NewUpload, max_size: i64) -> Result<Upload> { |
| 151 | if new.size < 0 || new.size > max_size { |
| 152 | return Err(Error::Invalid("too_large".into())); |
| 153 | } |
| 154 | let now = now_stamp(); |
| 155 | let conn = self.inner.conn.lock().await; |
| 156 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 157 | let outcome: Result<Upload> = async { |
| 158 | if let Some(f) = new.folder.as_deref() { |
| 159 | live_folder(&tx, &new.owner, f).await?; |
| 160 | } |
| 161 | let (quota, used) = fetch_opt( |
| 162 | &tx, |
| 163 | "SELECT quota_bytes, used_bytes FROM members WHERE sub = ?1", |
| 164 | (new.owner.clone(),), |
| 165 | |row| Ok((col_int(row, 0)?, col_int(row, 1)?)), |
| 166 | ) |
| 167 | .await? |
| 168 | .ok_or(Error::NotFound)?; |
| 169 | let open: i64 = fetch_opt( |
| 170 | &tx, |
| 171 | "SELECT COUNT(*) FROM uploads WHERE owner = ?1 AND state = 'active' AND expires_at > ?2", |
| 172 | (new.owner.clone(), now.clone()), |
| 173 | |row| col_int(row, 0), |
| 174 | ) |
| 175 | .await? |
| 176 | .unwrap_or(0); |
| 177 | if open >= MAX_OPEN_UPLOADS { |
| 178 | return Err(Error::Conflict("too_many_uploads".into())); |
| 179 | } |
| 180 | let claims = declared_claims(&tx, &new.owner, &now, "").await?; |
| 181 | if !quota::fits(new.size, quota::headroom(quota, used, claims)) { |
| 182 | return Err(Error::Conflict("quota_exceeded".into())); |
| 183 | } |
| 184 | tx.execute( |
| 185 | "INSERT INTO uploads (id, owner, folder_id, name, size, chunk_size, state, created_at, \ |
| 186 | expires_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'active', ?7, ?8)", |
| 187 | ( |
| 188 | new.id.clone(), |
| 189 | new.owner.clone(), |
| 190 | new.folder.clone(), |
| 191 | new.name.clone(), |
| 192 | new.size, |
| 193 | new.chunk_size, |
| 194 | now.clone(), |
| 195 | new.expires_at.clone(), |
| 196 | ), |
| 197 | ) |
| 198 | .await |
| 199 | .map_err(db_err)?; |
| 200 | upload_of(&tx, &new.owner, &new.id) |
| 201 | .await? |
| 202 | .ok_or(Error::NotFound) |
| 203 | } |
| 204 | .await; |
| 205 | finish(tx, outcome).await |
| 206 | } |
| 207 | |
| 208 | |
| 209 | |
| 210 | pub async fn touch_upload(&self, owner: &str, id: &str, expires_at: &str) -> Result<bool> { |
| 211 | let conn = self.inner.conn.lock().await; |
| 212 | let changed = conn |
| 213 | .execute( |
| 214 | "UPDATE uploads SET expires_at = ?3 WHERE id = ?1 AND owner = ?2 AND state = 'active'", |
| 215 | (id.to_string(), owner.to_string(), expires_at.to_string()), |
| 216 | ) |
| 217 | .await |
| 218 | .map_err(db_err)?; |
| 219 | Ok(changed == 1) |
| 220 | } |
| 221 | |
| 222 | |
| 223 | |
| 224 | pub async fn abort_upload(&self, owner: &str, id: &str) -> Result<bool> { |
| 225 | let conn = self.inner.conn.lock().await; |
| 226 | let changed = conn |
| 227 | .execute( |
| 228 | "UPDATE uploads SET state = 'aborted' WHERE id = ?1 AND owner = ?2 AND state = 'active'", |
| 229 | (id.to_string(), owner.to_string()), |
| 230 | ) |
| 231 | .await |
| 232 | .map_err(db_err)?; |
| 233 | Ok(changed == 1) |
| 234 | } |
| 235 | |
| 236 | |
| 237 | |
| 238 | |
| 239 | |
| 240 | |
| 241 | pub async fn finish_upload(&self, owner: &str, id: &str, file: NewFile) -> Result<File> { |
| 242 | let now = now_stamp(); |
| 243 | let conn = self.inner.conn.lock().await; |
| 244 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 245 | let outcome: Result<File> = async { |
| 246 | let upload = upload_of(&tx, owner, id).await?.ok_or(Error::NotFound)?; |
| 247 | if !upload.is_open(&now) { |
| 248 | return Err(Error::Conflict("upload_not_active".into())); |
| 249 | } |
| 250 | if file.size != upload.size { |
| 251 | return Err(Error::Invalid("size_mismatch".into())); |
| 252 | } |
| 253 | let claims = declared_claims(&tx, owner, &now, id).await?; |
| 254 | let row = insert_file_in( |
| 255 | &tx, |
| 256 | NewFile { |
| 257 | folder: upload.folder_id.clone(), |
| 258 | name: upload.name.clone(), |
| 259 | staged_claims: claims, |
| 260 | owner: owner.to_owned(), |
| 261 | ..file |
| 262 | }, |
| 263 | ) |
| 264 | .await?; |
| 265 | tx.execute( |
| 266 | "UPDATE uploads SET state = 'done', file_id = ?2 WHERE id = ?1", |
| 267 | (id.to_string(), row.id.clone()), |
| 268 | ) |
| 269 | .await |
| 270 | .map_err(db_err)?; |
| 271 | Ok(row) |
| 272 | } |
| 273 | .await; |
| 274 | finish(tx, outcome).await |
| 275 | } |
| 276 | |
| 277 | |
| 278 | |
| 279 | |
| 280 | pub async fn expire_uploads(&self, now: &str) -> Result<Vec<String>> { |
| 281 | let conn = self.inner.conn.lock().await; |
| 282 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 283 | let outcome: Result<Vec<String>> = async { |
| 284 | let ids = fetch_all( |
| 285 | &tx, |
| 286 | "SELECT id FROM uploads WHERE expires_at <= ?1", |
| 287 | (now.to_string(),), |
| 288 | |row| col_text(row, 0), |
| 289 | ) |
| 290 | .await?; |
| 291 | tx.execute( |
| 292 | "DELETE FROM uploads WHERE expires_at <= ?1", |
| 293 | (now.to_string(),), |
| 294 | ) |
| 295 | .await |
| 296 | .map_err(db_err)?; |
| 297 | Ok(ids) |
| 298 | } |
| 299 | .await; |
| 300 | finish(tx, outcome).await |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | #[cfg(test)] |
| 305 | mod tests { |
| 306 | use super::*; |
| 307 | use crate::store::new_id; |
| 308 | use crate::store::test_support::store_with_member; |
| 309 | use crate::time::stamp_after; |
| 310 | use std::time::Duration; |
| 311 | |
| 312 | fn new_upload(size: i64) -> NewUpload { |
| 313 | NewUpload { |
| 314 | id: new_id(), |
| 315 | owner: "ann".into(), |
| 316 | folder: None, |
| 317 | name: "big.bin".into(), |
| 318 | size, |
| 319 | chunk_size: 8, |
| 320 | expires_at: stamp_after(Duration::from_secs(24 * 3600)), |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | #[tokio::test] |
| 325 | async fn parallel_creates_cannot_together_exceed_the_quota() { |
| 326 | let (_dir, store) = store_with_member("ann").await; |
| 327 | store.set_quota("ann", 100).await.unwrap(); |
| 328 | let (first, second) = tokio::join!( |
| 329 | store.create_upload(new_upload(60), 1000), |
| 330 | store.create_upload(new_upload(60), 1000), |
| 331 | ); |
| 332 | let refused: Vec<&Result<Upload>> = [&first, &second] |
| 333 | .into_iter() |
| 334 | .filter(|outcome| outcome.is_err()) |
| 335 | .collect(); |
| 336 | assert_eq!(refused.len(), 1, "exactly one of the two may be accepted"); |
| 337 | match refused[0] { |
| 338 | Err(Error::Conflict(word)) => assert_eq!(word, "quota_exceeded"), |
| 339 | other => panic!("expected quota_exceeded, got {other:?}"), |
| 340 | } |
| 341 | } |
| 342 | } |