forge
Explore
Log in

Don't you dare go Hollow

in_old

Clone
★ 0

0 watching0 forksRustGPL-3.01.1 MiB218b775Tahinli2 months ago90 commits

upload.rs228 lines, 8.3 KiBHistoryRawDownload
1//! The chunked-upload protocol.
2//!
3//! Five owner-only JSON calls, all UTF-8: `POST /api/upload/start`
4//! `{folder_id, name, size_bytes}` answers `{id, chunk_size}` with the
5//! server-fixed 8 MiB chunk size (`Refusal::QuotaExceeded` when the quota
6//! says no — the account quota is the only size limit); `GET /api/upload/{id}`
7//! answers the session with the indexes already staged, so an interrupted
8//! upload resumes instead of starting over; `PUT /api/upload/{id}/{index}`
9//! takes one raw chunk (32 MiB cap, layered in `main.rs`);
10//! `POST /api/upload/{id}/finish` assembles the
11//! staged chunks, sniffs the mime, moves the bytes to `files/<new file id>`
12//! and answers with the created file id; `POST /api/upload/{id}/abort`
13//! drops the session and its staged bytes. Quota is enforced at start *and*
14//! at finish. The UI picks this path at 8 MiB and over; below that it posts
15//! straight to `POST /files`.
16//!
17//! Answers are `200` JSON throughout — `{ok: ...}` or `{err: <refusal>}` —
18//! because the caller is script, not a form: there is no page to redirect
19//! back to, and the progress bar reads the refusal straight off the body.
20
21use in_core::store::StoreError;
22use topcoat::Result;
23use topcoat::context::Cx;
24use topcoat::router::content::Json;
25use topcoat::router::request::{Bytes, uri};
26use topcoat::router::{path_param, route};
27
28use crate::server::{Refusal, app, require_user};
29
30path_param!(id);
31
32/// What the script side reads: the value, or the refusal it failed with.
33/// Serialises as `{"ok":...}` / `{"err":...}` — a hand-rolled enum because
34/// serde's own `Result` would say `Ok`/`Err`, which the UI script does not
35/// read.
36enum Answer<T> {
37 Ok(T),
38 Err(Refusal),
39}
40
41impl<T: serde::Serialize> serde::Serialize for Answer<T> {
42 fn serialize<S: serde::Serializer>(
43 &self,
44 serializer: S,
45 ) -> std::result::Result<S::Ok, S::Error> {
46 use serde::ser::SerializeMap;
47 let mut map = serializer.serialize_map(Some(1))?;
48 match self {
49 Answer::Ok(value) => map.serialize_entry("ok", value)?,
50 Answer::Err(refusal) => map.serialize_entry("err", refusal)?,
51 }
52 map.end()
53 }
54}
55
56/// A [`StoreError`] in the upload's own words. Another owner's session id
57/// answers [`Refusal::NotFound`]: the id space is not theirs to probe.
58fn store_refusal(error: StoreError) -> Refusal {
59 match error {
60 StoreError::QuotaExceeded => Refusal::QuotaExceeded,
61 StoreError::UploadExpired => Refusal::UploadExpired,
62 StoreError::BadChunk => Refusal::BadChunk,
63 StoreError::NotFound | StoreError::CrossOwner => Refusal::NotFound,
64 _ => Refusal::Unavailable,
65 }
66}
67
68/// The owned, active session the call names, or the refusal its answer
69/// carries. Another owner's session is not found rather than forbidden.
70async fn owned_session(
71 cx: &Cx,
72 id: &str,
73) -> std::result::Result<in_core::store::UploadSession, Refusal> {
74 let user = require_user(cx).await?;
75 let store = app(cx).store.clone();
76 match store.upload_session(id).await {
77 Ok(Some(session)) if session.owner_id == user.id => Ok(session),
78 Ok(_) => Err(Refusal::NotFound),
79 Err(_) => Err(Refusal::Unavailable),
80 }
81}
82
83#[derive(serde::Deserialize)]
84struct StartIn {
85 folder_id: Option<String>,
86 name: String,
87 size_bytes: u64,
88}
89
90#[derive(serde::Serialize)]
91struct StartOut {
92 id: String,
93 chunk_size: u64,
94}
95
96/// Opens an upload session after the quota pre-check: the declared total
97/// must fit the remaining quota, or the browser learns before sending a
98/// single chunk.
99#[route(POST "/api/upload/start")]
100async fn start(cx: &Cx, Json(input): Json<StartIn>) -> Result<Json<Answer<StartOut>>> {
101 let user = match require_user(cx).await {
102 Ok(user) => user,
103 Err(refusal) => return Ok(Json(Answer::Err(refusal))),
104 };
105 let store = app(cx).store.clone();
106 let folder = input.folder_id.as_deref().filter(|id| !id.is_empty());
107 if let Some(id) = folder {
108 match store.folder(id).await {
109 Ok(Some(row)) if row.owner_id == user.id && row.deleted_at.is_none() => {}
110 Ok(_) => return Ok(Json(Answer::Err(Refusal::NotFound))),
111 Err(_) => return Ok(Json(Answer::Err(Refusal::Unavailable))),
112 }
113 }
114 match store
115 .create_upload_session(&user.id, folder, &input.name, input.size_bytes)
116 .await
117 {
118 Ok(session) => Ok(Json(Answer::Ok(StartOut {
119 id: session.id,
120 chunk_size: session.chunk_size,
121 }))),
122 Err(error) => Ok(Json(Answer::Err(store_refusal(error)))),
123 }
124}
125
126#[derive(serde::Serialize)]
127struct ChunkOut {
128 received_bytes: u64,
129 size_bytes: u64,
130}
131
132/// Stages one raw chunk. The store refuses a wrong-sized or out-of-range
133/// piece with [`StoreError::BadChunk`] and an expired session with
134/// [`StoreError::UploadExpired`]; this layer only gates the owner.
135#[route(PUT "/api/upload/{id}/{index}")]
136async fn chunk(cx: &Cx, body: Bytes) -> Result<Json<Answer<ChunkOut>>> {
137 let id: &str = path_param::<Id>(cx);
138 let index: u64 = match uri(cx)
139 .path()
140 .rsplit('/')
141 .next()
142 .and_then(|raw| raw.parse().ok())
143 {
144 Some(index) => index,
145 None => return Ok(Json(Answer::Err(Refusal::BadChunk))),
146 };
147 let session = match owned_session(cx, id).await {
148 Ok(session) => session,
149 Err(refusal) => return Ok(Json(Answer::Err(refusal))),
150 };
151 let store = app(cx).store.clone();
152 match store.record_chunk(&session.id, index, &body).await {
153 Ok(session) => Ok(Json(Answer::Ok(ChunkOut {
154 received_bytes: session.received_bytes,
155 size_bytes: session.size_bytes,
156 }))),
157 Err(error) => Ok(Json(Answer::Err(store_refusal(error)))),
158 }
159}
160
161#[derive(serde::Serialize)]
162struct StatusOut {
163 id: String,
164 chunk_size: u64,
165 size_bytes: u64,
166 name: String,
167 folder_id: Option<String>,
168 uploaded: Vec<u64>,
169}
170
171/// The session and the indexes already staged, for a resuming uploader:
172/// the client skips every index in `uploaded` and sends only what is
173/// missing. An expired session still answers — the chunks it holds are
174/// real until the sweep takes them — so the client reads the expiry off
175/// `chunk`'s refusal, not here.
176#[route(GET "/api/upload/{id}")]
177async fn status(cx: &Cx) -> Result<Json<Answer<StatusOut>>> {
178 let id: &str = path_param::<Id>(cx);
179 let session = match owned_session(cx, id).await {
180 Ok(session) => session,
181 Err(refusal) => return Ok(Json(Answer::Err(refusal))),
182 };
183 let store = app(cx).store.clone();
184 match store.uploaded_chunks(&session.id).await {
185 Ok(uploaded) => Ok(Json(Answer::Ok(StatusOut {
186 id: session.id,
187 chunk_size: session.chunk_size,
188 size_bytes: session.size_bytes,
189 name: session.name,
190 folder_id: session.folder_id,
191 uploaded,
192 }))),
193 Err(error) => Ok(Json(Answer::Err(store_refusal(error)))),
194 }
195}
196
197/// Assembles the staged chunks — rechecking the quota, sniffing the mime
198/// off the bytes, attempting the thumbnail — and answers the created file
199/// id. The chunks stay staged on refusal, so the browser may retry.
200#[route(POST "/api/upload/{id}/finish")]
201async fn finish(cx: &Cx) -> Result<Json<Answer<String>>> {
202 let id: &str = path_param::<Id>(cx);
203 let session = match owned_session(cx, id).await {
204 Ok(session) => session,
205 Err(refusal) => return Ok(Json(Answer::Err(refusal))),
206 };
207 let store = app(cx).store.clone();
208 match store.finish_upload(&session.id).await {
209 Ok(file) => Ok(Json(Answer::Ok(file.id))),
210 Err(error) => Ok(Json(Answer::Err(store_refusal(error)))),
211 }
212}
213
214/// Aborts a session: the row says `aborted` and the staged chunks go.
215/// Aborting twice — or aborting nothing — is not an error.
216#[route(POST "/api/upload/{id}/abort")]
217async fn abort(cx: &Cx) -> Result<Json<Answer<()>>> {
218 let id: &str = path_param::<Id>(cx);
219 let session = match owned_session(cx, id).await {
220 Ok(session) => session,
221 Err(refusal) => return Ok(Json(Answer::Err(refusal))),
222 };
223 let store = app(cx).store.clone();
224 match store.abort_upload(&session.id).await {
225 Ok(_) => Ok(Json(Answer::Ok(()))),
226 Err(error) => Ok(Json(Answer::Err(store_refusal(error)))),
227 }
228}