forge
Explore
Log in

Don't you dare go Hollow

in

Clone
★ 0

0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits

uploads.rs342 lines, 13.6 KiBHistoryRawDownload
1//! Resumable uploads: the rows that track an upload from its first request to its finish, and the
2//! transactions that decide its fate.
3//!
4//! The quota is promised, not spent, while an upload is open. Creating an upload checks the headroom
5//! inside the write transaction, with the declared sizes of the owner's other live uploads counted
6//! against it, so two creates that would together exceed the quota cannot both succeed. Finishing
7//! checks again, in the transaction that inserts the file row and marks the upload `done`. Bytes never
8//! change here: the chunks live on disk (`staging.rs`), and the blob is put before the finish commits.
9
10use turso::{Connection, Row};
11
12use crate::error::{Error, Result};
13use crate::quota;
14use crate::store::files::{File, NewFile, insert_file_in};
15use crate::store::folders::live_folder;
16use crate::store::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish};
17use crate::time::now_stamp;
18
19/// Most uploads one person may have open (active and not expired) at once. A create past it is
20/// `Conflict("too_many_uploads")`, so an account cannot hold thousands of empty uploads at no cost.
21pub const MAX_OPEN_UPLOADS: i64 = 64;
22
23/// Column list for [`map_upload`]. Keep the two in step.
24pub const UPLOAD_COLS: &str =
25 "id, owner, folder_id, name, size, chunk_size, state, file_id, created_at, expires_at";
26
27/// One row of the `uploads` table.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct Upload {
30 /// Upload id (a lower-case ULID). It names the staging directory.
31 pub id: String,
32 /// The person who started the upload.
33 pub owner: String,
34 /// Destination folder, or `None` for the top level.
35 pub folder_id: Option<String>,
36 /// The cleaned file name the finished file gets (a postfix is added at finish if it is taken).
37 pub name: String,
38 /// Declared size in bytes. Every chunk is checked against it.
39 pub size: i64,
40 /// Chunk size in bytes the upload was started with.
41 pub chunk_size: i64,
42 /// `active`, `done` or `aborted`.
43 pub state: String,
44 /// The file the upload became, once it is `done`.
45 pub file_id: Option<String>,
46 /// When the upload was started.
47 pub created_at: String,
48 /// When the upload expires: 24 hours after its last chunk.
49 pub expires_at: String,
50}
51
52impl Upload {
53 /// Whether the upload may still take chunks or finish at `now`: active and not yet expired.
54 pub fn is_open(&self, now: &str) -> bool {
55 self.state == "active" && self.expires_at.as_str() > now
56 }
57}
58
59/// What a new upload needs. The name is already cleaned by the caller.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct NewUpload {
62 /// Id, made by the caller with `store::new_id`, so the staging directory can be named first.
63 pub id: String,
64 /// The person who starts the upload.
65 pub owner: String,
66 /// Destination folder, or `None` for the top level.
67 pub folder: Option<String>,
68 /// The cleaned file name.
69 pub name: String,
70 /// Declared size in bytes.
71 pub size: i64,
72 /// Chunk size in bytes.
73 pub chunk_size: i64,
74 /// Expiry stamp: now plus 24 hours.
75 pub expires_at: String,
76}
77
78/// Maps a row selected with [`UPLOAD_COLS`].
79pub 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/// An upload of `owner` by id. Foreign ids find nothing, so they look missing.
95async 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/// The bytes the owner's open uploads have declared, except the upload named `except`. Those bytes are
106/// promised to be written, so a new upload or a finish cannot take them.
107async 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
119impl Store {
120 /// The bytes the owner's open uploads have declared. A new upload or a direct upload must leave them room.
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 /// An upload of `owner` by id, or `None` when there is no such upload for that person.
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 /// Whether an upload with this id is still active. The sweeper keeps the staging directory of an active
133 /// upload whatever its age, because the upload may still receive chunks.
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 /// Starts an upload. In one transaction: the folder must be a live folder of the owner, the size
147 /// must not be above `max_size`, and it must fit the headroom after the other open uploads' declared
148 /// sizes. A refusal for size is `Invalid("too_large")`, one for quota is `Conflict("quota_exceeded")`,
149 /// and one for too many open uploads ([`MAX_OPEN_UPLOADS`]) is `Conflict("too_many_uploads")`.
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 /// Moves the expiry of an open upload of `owner` to `expires_at`. Returns `false` when the upload is
209 /// not open for that person any more.
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 /// Cancels an open upload of `owner`. Returns `false` when it was not open (already finished,
223 /// already cancelled, or not theirs). The staging directory is the caller's to remove.
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 /// Turns an open upload into a file. The blob must already be stored under the key of `file.id`.
237 /// In one transaction: the upload must still be open, `file.size` must equal the declared size, the
238 /// quota is checked against the owner's other open uploads, the row is inserted with the upload's own
239 /// folder and name, and the upload becomes `done`. A refused finish leaves the upload open.
240 /// `file.folder`, `file.name` and `file.staged_claims` are ignored: the upload row decides them.
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 /// Deletes the upload rows that expired at or before `now`, in one transaction, and returns their
278 /// ids so the caller can remove their staging directories. The rows go in the same transaction that
279 /// reads the ids, so an upload that was extended in between is not removed.
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)]
305mod 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}