forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

media.rs449 lines, 16.6 KiBHistoryRawDownload
1//! Media routes: POST /media stores a raw upload, and GET /media/{file} serves it back with
2//! HTTP Range support, so audio and video can seek. GET /media/rec/{session} serves a recording
3//! take, and GET /media/live takes the audio of a recording over a WebSocket.
4
5use std::io::SeekFrom;
6use std::path::Path;
7use std::pin::Pin;
8use std::sync::Arc;
9use std::task::{Context, Poll};
10use std::time::Duration;
11
12use bytes::Bytes;
13use http_body::Frame;
14use tokio::io::{AsyncRead, AsyncSeekExt, AsyncWriteExt, ReadBuf};
15use tokio::sync::oneshot;
16use topcoat::{
17 Result,
18 context::{Cx, app_context},
19 router::{
20 Body, Method, StatusCode, header, path_param, query_params,
21 content::websocket::{Message, WebSocket, WebSocketUpgrade},
22 error::{content_too_large, not_found},
23 request::{headers, method},
24 response::Response,
25 route,
26 },
27};
28
29use crate::hub::{Attachment, Detach, Hub};
30use crate::media::{MAX_BYTES, Media, StoreError, content_type, ext_of, part_file, take_bytes, valid_name, valid_session};
31use crate::store::Store;
32
33/// Bytes read from disk per response frame.
34const CHUNK_SIZE: usize = 64 * 1024;
35/// Largest frame a recording socket takes: a chunk can grow large after a long retry.
36const MAX_FRAME: usize = 16 << 20;
37/// Silence after which a recording socket counts as disconnected.
38const FRAME_WAIT: Duration = Duration::from_secs(5);
39/// Cache-Control of a stored file, which never changes under its name.
40const IMMUTABLE: &str = "public, max-age=31536000, immutable";
41
42/// The `name` parameter of an upload: the original file name.
43#[query_params(error = bad_request)]
44pub struct MediaQuery {
45 /// The file's name as the user chose it. Only its extension is kept.
46 pub name: Option<String>,
47}
48
49/// The parameters of a recording socket. `part` is text so a bad one is refused on the socket.
50#[query_params(error = bad_request)]
51pub struct LiveQuery {
52 /// A note to start a new take of.
53 pub note: Option<String>,
54 /// A take to continue, or to reconnect to with `part`.
55 pub session: Option<String>,
56 /// The part of `session` to reconnect to.
57 pub part: Option<String>,
58}
59
60path_param!(file);
61path_param!(session);
62
63/// POST /media?name=...: stores the raw request body and answers with its URL.
64#[route(POST "/media")]
65pub async fn upload_media(cx: &Cx, body: Body) -> Result<String> {
66 let media = app_context::<Arc<Media>>(cx);
67 let name = query_params::<MediaQuery>(cx)?.name.clone().unwrap_or_default();
68 match media.store(&ext_of(&name), body).await {
69 Ok(file) => Ok(format!("/media/{file}")),
70 Err(StoreError::TooLarge) => Err(content_too_large().into()),
71 Err(StoreError::Failed(err)) => Err(topcoat::Error::from_anyhow(err)),
72 }
73}
74
75/// GET /media/{file}: a stored file, inline when its type is safe to show and a download
76/// otherwise. HEAD gets the headers alone.
77#[route(GET "/media/{file}")]
78pub async fn serve_media(cx: &Cx) -> Result<Response> {
79 let media = app_context::<Arc<Media>>(cx);
80 let name = path_param::<File>(cx);
81 if !valid_name(name) {
82 return Err(not_found().into());
83 }
84 let Some((_, ext)) = name.split_once('.') else {
85 return Err(not_found().into());
86 };
87 file_response(cx, &media.path(name), ext, IMMUTABLE, None).await
88}
89
90/// GET /media/rec/{session}: a take, its closed parts joined into one WebM. Parts a socket is
91/// still writing are left out, and the answer is revalidated against the join key.
92#[route(GET "/media/rec/{session}")]
93pub async fn serve_take(cx: &Cx) -> Result<Response> {
94 let media = app_context::<Arc<Media>>(cx);
95 let hub = app_context::<Arc<Hub>>(cx);
96 let id = path_param::<Session>(cx);
97 if !valid_session(id) {
98 return take_missing();
99 }
100 let joined = media
101 .joined_take(id, &hub.attached(id))
102 .await
103 .map_err(topcoat::Error::from_anyhow)?;
104 let Some((path, key)) = joined else {
105 return take_missing();
106 };
107 let etag = format!("\"{}\"", blake3::hash(key.as_bytes()).to_hex());
108 if not_modified(cx, &etag) {
109 return Ok(Response::builder()
110 .status(StatusCode::NOT_MODIFIED)
111 .header(header::CACHE_CONTROL, "no-cache")
112 .header(header::ETAG, etag)
113 .body(Body::empty())?);
114 }
115 file_response(cx, &path, "weba", "no-cache", Some(&etag)).await
116}
117
118/// The 404 of a take with no audio to serve. Not cached, since audio may arrive.
119fn take_missing() -> Result<Response> {
120 Ok(Response::builder()
121 .status(StatusCode::NOT_FOUND)
122 .header(header::CACHE_CONTROL, "no-store")
123 .header("x-content-type-options", "nosniff")
124 .header("content-security-policy", "sandbox; default-src 'none'")
125 .body(Body::empty())?)
126}
127
128/// Whether the request's `If-None-Match` names `etag`.
129fn not_modified(cx: &Cx, etag: &str) -> bool {
130 headers(cx)
131 .get(header::IF_NONE_MATCH)
132 .and_then(|v| v.to_str().ok())
133 .is_some_and(|list| list.split(',').map(str::trim).any(|tag| tag == etag || tag == "*"))
134}
135
136/// GET /media/live: the audio of a recording. `?note=` starts a take, `?session=` continues one
137/// with a new part, and `?session=&part=` reconnects to a part. The socket is upgraded first, so a
138/// refusal arrives as a `reject` frame and is not mistaken for the server being offline.
139#[route(GET "/media/live")]
140pub async fn recording_socket(cx: &Cx, upgrade: WebSocketUpgrade) -> Result<Response> {
141 let store = app_context::<Arc<Store>>(cx).clone();
142 let hub = app_context::<Arc<Hub>>(cx).clone();
143 let media = app_context::<Arc<Media>>(cx).clone();
144 let (note, session, part) = {
145 let query = query_params::<LiveQuery>(cx)?;
146 (query.note.clone(), query.session.clone(), query.part.clone())
147 };
148 upgrade
149 .max_message_size(MAX_FRAME)
150 .max_frame_size(MAX_FRAME)
151 .on_upgrade(move |socket| async move {
152 serve_recording(store, hub, media, note, session, part, socket).await;
153 })
154}
155
156/// Whether `note` is an id of a note that exists.
157async fn note_exists(store: &Store, note: &str) -> bool {
158 super::is_note_id(note) && matches!(store.get_note(note).await, Ok(Some(_)))
159}
160
161/// The take and part a recording socket asks for, as `(note, session, part)`. `None` when the
162/// request is refused: a bad or missing id, an unknown note, or a bad part number. A new take is
163/// created here, with `part` None.
164async fn recording_target(
165 store: &Store,
166 media: &Media,
167 note: Option<String>,
168 session: Option<String>,
169 part: Option<String>,
170) -> Option<(String, String, Option<u32>)> {
171 if let Some(session) = session {
172 if !valid_session(&session) {
173 return None;
174 }
175 let note = session.split('.').next()?.to_owned();
176 if !note_exists(store, &note).await {
177 return None;
178 }
179 let part = part.map(|p| p.parse::<u32>()).transpose().ok()?;
180 return Some((note, session, part));
181 }
182 let note = note?;
183 if !note_exists(store, &note).await {
184 return None;
185 }
186 let session = media.new_take(&note).await.ok()?;
187 Some((note, session, None))
188}
189
190/// Drives one recording socket: attaches it to a part, then stores the chunks it sends.
191async fn serve_recording(
192 store: Arc<Store>,
193 hub: Arc<Hub>,
194 media: Arc<Media>,
195 note: Option<String>,
196 session: Option<String>,
197 part: Option<String>,
198 mut socket: WebSocket,
199) {
200 let Some((note, session, part)) = recording_target(&store, &media, note, session, part).await else {
201 return refuse(socket).await;
202 };
203 let dir = media.take_dir(&session);
204 let Attachment { part, token, mut stop } = match hub.attach(&note, &session, part, &dir) {
205 Ok(Some(attachment)) => attachment,
206 _ => return refuse(socket).await,
207 };
208 let (mut file, len) = match open_part(&part_file(&dir, part)).await {
209 Ok(opened) => opened,
210 Err(err) => {
211 eprintln!("opening part {part} of take {session} failed: {err:#}");
212 hub.detach(&note, &session, part, token, Detach::Lost);
213 return refuse(socket).await;
214 }
215 };
216 if socket.send(Message::text(format!("ready {session} {part} {len}"))).await.is_err() {
217 hub.detach(&note, &session, part, token, Detach::Lost);
218 return;
219 }
220 match receive_part(&mut socket, &mut file, &dir, len, &mut stop).await {
221 Exit::Ended => {
222 let _ = socket.send(Message::text("done")).await;
223 hub.detach(&note, &session, part, token, Detach::Ended);
224 }
225 Exit::Refused => {
226 let _ = socket.send(Message::text("reject")).await;
227 hub.detach(&note, &session, part, token, Detach::Lost);
228 }
229 // A socket that was taken over no longer matches its token, so this detaches nothing.
230 Exit::Lost | Exit::Taken => hub.detach(&note, &session, part, token, Detach::Lost),
231 }
232 let _ = socket.close().await;
233}
234
235/// How a part's socket came to an end.
236enum Exit {
237 /// The client sent `end`.
238 Ended,
239 /// The socket closed, broke, or went quiet for [`FRAME_WAIT`].
240 Lost,
241 /// Another socket took the part over.
242 Taken,
243 /// A chunk could not be stored, or the take is full.
244 Refused,
245}
246
247/// Refuses a recording socket: `reject`, then close.
248async fn refuse(mut socket: WebSocket) {
249 let _ = socket.send(Message::text("reject")).await;
250 let _ = socket.close().await;
251}
252
253/// Opens a part for writing, with its length.
254async fn open_part(path: &Path) -> std::io::Result<(tokio::fs::File, u64)> {
255 let file = tokio::fs::OpenOptions::new().write(true).open(path).await?;
256 let len = file.metadata().await?.len();
257 Ok((file, len))
258}
259
260/// Stores the binary chunks of a part from `len` on, acking each one, until the client sends
261/// `end`, goes quiet, or another socket takes the part over.
262async fn receive_part(
263 socket: &mut WebSocket,
264 file: &mut tokio::fs::File,
265 dir: &Path,
266 mut len: u64,
267 stop: &mut oneshot::Receiver<()>,
268) -> Exit {
269 loop {
270 let message = tokio::select! {
271 _ = &mut *stop => return Exit::Taken,
272 message = tokio::time::timeout(FRAME_WAIT, socket.recv()) => message,
273 };
274 let message = match message {
275 Ok(Some(Ok(message))) => message,
276 _ => return Exit::Lost,
277 };
278 match message {
279 Message::Binary(chunk) => {
280 if write_chunk(file, dir, len, &chunk).await.is_err() {
281 return Exit::Refused;
282 }
283 len += chunk.len() as u64;
284 if socket.send(Message::text(format!("ack {len}"))).await.is_err() {
285 return Exit::Lost;
286 }
287 }
288 Message::Text(text) if text.as_str() == "end" => return Exit::Ended,
289 Message::Close(_) => return Exit::Lost,
290 _ => {}
291 }
292 }
293}
294
295/// Writes `chunk` at `len` and syncs it. A take that would pass [`MAX_BYTES`] is refused, and a
296/// failed write cuts the part back to `len`.
297async fn write_chunk(file: &mut tokio::fs::File, dir: &Path, len: u64, chunk: &[u8]) -> std::io::Result<()> {
298 if take_bytes(dir)? + chunk.len() as u64 > MAX_BYTES {
299 return Err(std::io::Error::other("the take is larger than the limit"));
300 }
301 let result = write_at(file, len, chunk).await;
302 if result.is_err() {
303 let _ = file.set_len(len).await;
304 }
305 result
306}
307
308async fn write_at(file: &mut tokio::fs::File, len: u64, chunk: &[u8]) -> std::io::Result<()> {
309 file.seek(SeekFrom::Start(len)).await?;
310 file.write_all(chunk).await?;
311 file.sync_data().await
312}
313
314/// Answers a GET or HEAD for the file at `path`: the whole file, or the range the request asks
315/// for. `cache` is the Cache-Control value, and `etag` the ETag when there is one.
316async fn file_response(cx: &Cx, path: &Path, ext: &str, cache: &str, etag: Option<&str>) -> Result<Response> {
317 let mut file = match tokio::fs::File::open(path).await {
318 Ok(file) => file,
319 Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Err(not_found().into()),
320 Err(err) => return Err(topcoat::Error::from_anyhow(err.into())),
321 };
322 let meta = file.metadata().await.map_err(|err| topcoat::Error::from_anyhow(err.into()))?;
323 if !meta.is_file() {
324 return Err(not_found().into());
325 }
326 let len = meta.len();
327
328 let (status, start, count, content_range) = match headers(cx).get(header::RANGE).and_then(|v| v.to_str().ok()) {
329 Some(range) => match span(range, len) {
330 Span::Whole => (StatusCode::OK, 0, len, None),
331 Span::Part(start, end) => (
332 StatusCode::PARTIAL_CONTENT,
333 start,
334 end - start + 1,
335 Some(format!("bytes {start}-{end}/{len}")),
336 ),
337 Span::Unsatisfiable => (StatusCode::RANGE_NOT_SATISFIABLE, 0, 0, Some(format!("bytes */{len}"))),
338 },
339 None => (StatusCode::OK, 0, len, None),
340 };
341
342 let (mime, disposition) = match content_type(ext) {
343 Some(mime) => (mime, "inline"),
344 None => ("application/octet-stream", "attachment"),
345 };
346 let mut builder = Response::builder()
347 .status(status)
348 .header(header::CONTENT_TYPE, mime)
349 .header(header::CONTENT_LENGTH, count.to_string())
350 .header(header::CONTENT_DISPOSITION, disposition)
351 .header(header::ACCEPT_RANGES, "bytes")
352 .header(header::CACHE_CONTROL, cache)
353 .header("x-content-type-options", "nosniff");
354 if let Some(etag) = etag {
355 builder = builder.header(header::ETAG, etag);
356 }
357 // Browsers refuse to show a PDF in a sandbox, and a PDF cannot run script on this origin.
358 if ext != "pdf" {
359 builder = builder.header("content-security-policy", "sandbox; default-src 'none'");
360 }
361 if let Some(range) = content_range {
362 builder = builder.header(header::CONTENT_RANGE, range);
363 }
364 let body = if count == 0 || method(cx) == Method::HEAD {
365 Body::empty()
366 } else {
367 file.seek(SeekFrom::Start(start))
368 .await
369 .map_err(|err| topcoat::Error::from_anyhow(err.into()))?;
370 Body::new(FileBody { file, remaining: count })
371 };
372 Ok(builder.body(body)?)
373}
374
375/// What a `Range` header asks for, against a file of some length.
376#[derive(Debug, PartialEq)]
377enum Span {
378 /// No range the server honours: the whole file.
379 Whole,
380 /// The bytes `start..=end`.
381 Part(u64, u64),
382 /// No byte of the file is asked for.
383 Unsatisfiable,
384}
385
386/// Reads one `bytes=a-b`, `bytes=a-` or `bytes=-n` range against a file of `len` bytes.
387/// Multiple ranges and malformed headers are ignored, and the whole file is served.
388fn span(value: &str, len: u64) -> Span {
389 let Some((first, last)) = value.trim().strip_prefix("bytes=").and_then(|s| s.split_once('-')) else {
390 return Span::Whole;
391 };
392 let (first, last) = (first.trim(), last.trim());
393 if first.is_empty() {
394 // The last `n` bytes.
395 let Ok(n) = last.parse::<u64>() else { return Span::Whole };
396 if n == 0 || len == 0 {
397 return Span::Unsatisfiable;
398 }
399 return Span::Part(len.saturating_sub(n), len - 1);
400 }
401 let Ok(start) = first.parse::<u64>() else { return Span::Whole };
402 if start >= len {
403 return Span::Unsatisfiable;
404 }
405 let end = if last.is_empty() {
406 len - 1
407 } else {
408 match last.parse::<u64>() {
409 Ok(end) if end >= start => end.min(len - 1),
410 _ => return Span::Whole,
411 }
412 };
413 Span::Part(start, end)
414}
415
416/// Streams the next `remaining` bytes of an open file, a chunk at a time.
417struct FileBody {
418 file: tokio::fs::File,
419 remaining: u64,
420}
421
422impl http_body::Body for FileBody {
423 type Data = Bytes;
424 type Error = std::io::Error;
425
426 fn poll_frame(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<std::io::Result<Frame<Bytes>>>> {
427 let this = self.get_mut();
428 if this.remaining == 0 {
429 return Poll::Ready(None);
430 }
431 let want = this.remaining.min(CHUNK_SIZE as u64) as usize;
432 let mut chunk = vec![0u8; want];
433 let mut buf = ReadBuf::new(&mut chunk);
434 match Pin::new(&mut this.file).poll_read(cx, &mut buf) {
435 Poll::Pending => Poll::Pending,
436 Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))),
437 Poll::Ready(Ok(())) => {
438 let n = buf.filled().len();
439 if n == 0 {
440 let err = std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "media file is shorter than its length");
441 return Poll::Ready(Some(Err(err)));
442 }
443 chunk.truncate(n);
444 this.remaining -= n as u64;
445 Poll::Ready(Some(Ok(Frame::data(Bytes::from(chunk)))))
446 }
447 }
448 }
449}