Attachment storage in in: object client, mover with migration both ways, proxied reads, idempotent deletes
Browse files at this commit5346e822a5234e2e6aaa558b4d8711562d3d173dParent: cc5a8a0- feat
- attachment storage in in: object client, mover with migration both ways, proxied reads, idempotent deletes
23 changed files +1835 -155
- config/iz.example.toml +3 -1
- crates/iz-core/migrations/0005_blob_deletions_by_place.sql +17 -0
- crates/iz-core/src/config.rs +28 -2
- crates/iz-core/src/store/attachments.rs +157 -18
- crates/iz-core/src/store/migrate.rs +4 -0
- crates/iz-core/src/store/mod.rs +1 -1
- crates/iz-web/src/attachments.rs +153 -16
- crates/iz-web/src/boot.rs +14 -0
- crates/iz-web/src/family.rs +2 -0
- crates/iz-web/src/i18n/shell.rs +12 -0
- crates/iz-web/src/i18n/structure.rs +35 -0
- crates/iz-web/src/in_store.rs +493 -0
- crates/iz-web/src/main.rs +2 -0
- crates/iz-web/src/mover.rs +418 -0
- crates/iz-web/src/oidc.rs +17 -9
- crates/iz-web/src/pages/admin.rs +1 -0
- crates/iz-web/src/pages/files.rs +48 -7
- crates/iz-web/src/pages/settings.rs +81 -3
- crates/iz-web/src/serve.rs +266 -59
- crates/iz-web/src/state.rs +7 -0
- crates/iz-web/src/sweeper.rs +4 -38
- crates/iz-web/src/views/admin.rs +4 -1
- crates/iz-web/src/views/structure.rs +68 -0
config/iz.example.tomlmodified+3 -1
| @@ -19,9 +19,11 @@ trusted_proxies = [] | |||
| 19 | # client_id = "iz" | 19 | # client_id = "iz" |
| 20 | # client_secret_file = "data/oidc_client_secret" | 20 | # client_secret_file = "data/oidc_client_secret" |
| 21 | 21 | ||
| 22 | -# Attachments in the external Files service instead of local disk. | 22 | +# The external Files service (`in`) that may hold attachments. The storage choice is made in /settings. |
| 23 | +# It needs sign-in (the [oidc] section), because `in` is reached with a token from `im`. | ||
| 23 | [in_store] | 24 | [in_store] |
| 24 | enabled = false | 25 | enabled = false |
| 26 | +# url = "https://in.example.com" | ||
| 25 | 27 | ||
| 26 | # Scheduled backups. Uncomment to enable. | 28 | # Scheduled backups. Uncomment to enable. |
| 27 | # [backup] | 29 | # [backup] |
crates/iz-core/migrations/0005_blob_deletions_by_place.sqladded+17 -0
| @@ -0,0 +1,17 @@ | |||
| 1 | +-- 0005: a deletion records the copy it still owes per place, so a row that was moving can owe bytes in both | ||
| 2 | +-- places. The key becomes (attachment_id, location). Rows of 0003 carry over unchanged. A record's location | ||
| 3 | +-- says which copy the deleter removes: 'local' is a file under data_dir/attachments, 'in' is an object at | ||
| 4 | +-- the Files service. | ||
| 5 | +CREATE TABLE blob_deletions_by_place ( | ||
| 6 | + attachment_id TEXT NOT NULL CHECK (length(attachment_id) = 26), | ||
| 7 | + location TEXT NOT NULL CHECK (location IN ('local', 'in')), | ||
| 8 | + attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0), | ||
| 9 | + next_attempt_at TEXT NOT NULL, | ||
| 10 | + created_at TEXT NOT NULL, | ||
| 11 | + PRIMARY KEY (attachment_id, location) | ||
| 12 | +); | ||
| 13 | +INSERT INTO blob_deletions_by_place (attachment_id, location, attempts, next_attempt_at, created_at) | ||
| 14 | + SELECT attachment_id, location, attempts, next_attempt_at, created_at FROM blob_deletions; | ||
| 15 | +DROP TABLE blob_deletions; | ||
| 16 | +ALTER TABLE blob_deletions_by_place RENAME TO blob_deletions; | ||
| 17 | +CREATE INDEX blob_deletions_due ON blob_deletions(next_attempt_at); | ||
crates/iz-core/src/config.rsmodified+28 -2
| @@ -56,13 +56,18 @@ pub struct OidcConfig { | |||
| 56 | pub client_secret_file: PathBuf, | 56 | pub client_secret_file: PathBuf, |
| 57 | } | 57 | } |
| 58 | 58 | ||
| 59 | -/// Switch for storing attachments in the external Files service. | 59 | +/// The external Files service (`in`) that may hold attachments. The storage choice itself is the admin's |
| 60 | +/// setting; this section says whether `in` may be chosen at all and where it is. | ||
| 60 | #[derive(Debug, Clone, Default, Deserialize)] | 61 | #[derive(Debug, Clone, Default, Deserialize)] |
| 61 | #[serde(deny_unknown_fields)] | 62 | #[serde(deny_unknown_fields)] |
| 62 | pub struct InStoreConfig { | 63 | pub struct InStoreConfig { |
| 63 | - /// Whether the Files service is enabled. Defaults to off. | 64 | + /// Whether the Files service may be used for attachments. Defaults to off. |
| 64 | #[serde(default)] | 65 | #[serde(default)] |
| 65 | pub enabled: bool, | 66 | pub enabled: bool, |
| 67 | + /// Public origin of `in`, for example `https://in.example.com`. No trailing slash. Required when | ||
| 68 | + /// `enabled` is set. Must be https, or http on loopback. | ||
| 69 | + #[serde(default)] | ||
| 70 | + pub url: Option<String>, | ||
| 66 | } | 71 | } |
| 67 | 72 | ||
| 68 | /// Scheduled backup policy. | 73 | /// Scheduled backup policy. |
| @@ -182,6 +187,12 @@ impl Config { | |||
| 182 | )); | 187 | )); |
| 183 | } | 188 | } |
| 184 | } | 189 | } |
| 190 | + if self.in_store.enabled { | ||
| 191 | + let url = self.in_store.url.as_deref().ok_or_else(|| { | ||
| 192 | + Error::Config("in_store.url is required when in_store.enabled is set".into()) | ||
| 193 | + })?; | ||
| 194 | + validate_in_url(url)?; | ||
| 195 | + } | ||
| 185 | if let Some(backup) = &self.backup { | 196 | if let Some(backup) = &self.backup { |
| 186 | if backup.dir.as_os_str().is_empty() { | 197 | if backup.dir.as_os_str().is_empty() { |
| 187 | return Err(Error::Config("backup.dir must not be empty".into())); | 198 | return Err(Error::Config("backup.dir must not be empty".into())); |
| @@ -206,6 +217,21 @@ impl Config { | |||
| 206 | } | 217 | } |
| 207 | } | 218 | } |
| 208 | 219 | ||
| 220 | +/// The origin of `in` must be https, or http on loopback, with no trailing slash. | ||
| 221 | +fn validate_in_url(url: &str) -> Result<()> { | ||
| 222 | + if url.ends_with('/') { | ||
| 223 | + return Err(Error::Config("in_store.url must not end with /".into())); | ||
| 224 | + } | ||
| 225 | + let loopback = url.starts_with("http://127.0.0.1") || url.starts_with("http://localhost"); | ||
| 226 | + if url.starts_with("https://") || loopback { | ||
| 227 | + Ok(()) | ||
| 228 | + } else { | ||
| 229 | + Err(Error::Config( | ||
| 230 | + "in_store.url must be an https URL (http only for loopback)".into(), | ||
| 231 | + )) | ||
| 232 | + } | ||
| 233 | +} | ||
| 234 | + | ||
| 209 | /// An issuer must be https. Plain http is allowed only for loopback, which is how a local | 235 | /// An issuer must be https. Plain http is allowed only for loopback, which is how a local |
| 210 | /// identity provider is reached in development. | 236 | /// identity provider is reached in development. |
| 211 | fn validate_issuer(issuer: &str) -> Result<()> { | 237 | fn validate_issuer(issuer: &str) -> Result<()> { |
crates/iz-core/src/store/attachments.rsmodified+157 -18
| @@ -25,6 +25,14 @@ use std::time::Duration; | |||
| 25 | pub const SETTING_LIMIT_MIB: &str = "attachment_limit_mib"; | 25 | pub const SETTING_LIMIT_MIB: &str = "attachment_limit_mib"; |
| 26 | /// The setting that holds the allowed extensions, separated by spaces or commas. | 26 | /// The setting that holds the allowed extensions, separated by spaces or commas. |
| 27 | pub const SETTING_EXTENSIONS: &str = "attachment_extensions"; | 27 | pub const SETTING_EXTENSIONS: &str = "attachment_extensions"; |
| 28 | +/// The setting that holds where new and existing attachments belong: `local` (default) or `in`. | ||
| 29 | +pub const SETTING_LOCATION: &str = "attachment_location"; | ||
| 30 | +/// Where the bytes of an attachment are, as its row says: this disk, the Files service, or in between. | ||
| 31 | +pub const LOCATION_LOCAL: &str = "local"; | ||
| 32 | +/// See [`LOCATION_LOCAL`]. | ||
| 33 | +pub const LOCATION_IN: &str = "in"; | ||
| 34 | +/// A move between the two places is under way. Only the mover sets and clears it. | ||
| 35 | +pub const LOCATION_MOVING: &str = "moving"; | ||
| 28 | /// The extensions allowed when the setting is unset. Reason: office documents, images, audio, video, text. | 36 | /// The extensions allowed when the setting is unset. Reason: office documents, images, audio, video, text. |
| 29 | pub const DEFAULT_EXTENSIONS: &[&str] = &[ | 37 | pub const DEFAULT_EXTENSIONS: &[&str] = &[ |
| 30 | "pdf", "png", "jpg", "jpeg", "gif", "webp", "heic", "txt", "md", "csv", "xlsx", "ods", "pptx", | 38 | "pdf", "png", "jpg", "jpeg", "gif", "webp", "heic", "txt", "md", "csv", "xlsx", "ods", "pptx", |
| @@ -61,6 +69,8 @@ pub struct Attachment { | |||
| 61 | pub uploaded_by: String, | 69 | pub uploaded_by: String, |
| 62 | /// UTC stamp of the upload. | 70 | /// UTC stamp of the upload. |
| 63 | pub created_at: String, | 71 | pub created_at: String, |
| 72 | + /// Where the bytes are: `local`, `in` or `moving` (see [`LOCATION_LOCAL`]). | ||
| 73 | + pub location: String, | ||
| 64 | } | 74 | } |
| 65 | 75 | ||
| 66 | /// What an upload stores. The task and the board are given separately, by the caller's checks. | 76 | /// What an upload stores. The task and the board are given separately, by the caller's checks. |
| @@ -82,7 +92,7 @@ pub struct NewAttachment { | |||
| 82 | 92 | ||
| 83 | /// Columns of an attachment, prefixed for the joins that filter by task. | 93 | /// Columns of an attachment, prefixed for the joins that filter by task. |
| 84 | const ATTACHMENT_COLS: &str = | 94 | const ATTACHMENT_COLS: &str = |
| 85 | - "a.id, a.task_id, a.name, a.mime, a.size, a.sha256, a.uploaded_by, a.created_at"; | 95 | + "a.id, a.task_id, a.name, a.mime, a.size, a.sha256, a.uploaded_by, a.created_at, a.location"; |
| 86 | 96 | ||
| 87 | fn map_attachment(row: &turso::Row) -> Result<Attachment> { | 97 | fn map_attachment(row: &turso::Row) -> Result<Attachment> { |
| 88 | Ok(Attachment { | 98 | Ok(Attachment { |
| @@ -94,6 +104,7 @@ fn map_attachment(row: &turso::Row) -> Result<Attachment> { | |||
| 94 | sha256: col_text(row, 5)?, | 104 | sha256: col_text(row, 5)?, |
| 95 | uploaded_by: col_text(row, 6)?, | 105 | uploaded_by: col_text(row, 6)?, |
| 96 | created_at: col_text(row, 7)?, | 106 | created_at: col_text(row, 7)?, |
| 107 | + location: col_text(row, 8)?, | ||
| 97 | }) | 108 | }) |
| 98 | } | 109 | } |
| 99 | 110 | ||
| @@ -187,6 +198,7 @@ impl Store { | |||
| 187 | sha256: new.sha256.clone(), | 198 | sha256: new.sha256.clone(), |
| 188 | uploaded_by: new.uploaded_by.clone(), | 199 | uploaded_by: new.uploaded_by.clone(), |
| 189 | created_at: created_at.clone(), | 200 | created_at: created_at.clone(), |
| 201 | + location: LOCATION_LOCAL.to_owned(), | ||
| 190 | }; | 202 | }; |
| 191 | let conn = self.inner.conn.lock().await; | 203 | let conn = self.inner.conn.lock().await; |
| 192 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; | 204 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| @@ -324,13 +336,21 @@ impl Store { | |||
| 324 | ) | 336 | ) |
| 325 | .await | 337 | .await |
| 326 | .map_err(db_err)?; | 338 | .map_err(db_err)?; |
| 327 | - tx.execute( | 339 | + // A moving row may have a copy in each place, so both are owed. A settled row has one copy. |
| 328 | - "INSERT INTO blob_deletions (attachment_id, location, attempts, next_attempt_at, created_at) \ | 340 | + let owed: &[&str] = match current.location.as_str() { |
| 329 | - VALUES (?1, 'local', 0, ?2, ?3)", | 341 | + LOCATION_LOCAL => &[LOCATION_LOCAL], |
| 330 | - (attachment_id.to_owned(), now.clone(), now), | 342 | + LOCATION_IN => &[LOCATION_IN], |
| 331 | - ) | 343 | + _ => &[LOCATION_LOCAL, LOCATION_IN], |
| 332 | - .await | 344 | + }; |
| 333 | - .map_err(db_err)?; | 345 | + for place in owed { |
| 346 | + tx.execute( | ||
| 347 | + "INSERT INTO blob_deletions (attachment_id, location, attempts, next_attempt_at, created_at) \ | ||
| 348 | + VALUES (?1, ?2, 0, ?3, ?4)", | ||
| 349 | + (attachment_id.to_owned(), (*place).to_owned(), now.clone(), now.clone()), | ||
| 350 | + ) | ||
| 351 | + .await | ||
| 352 | + .map_err(db_err)?; | ||
| 353 | + } | ||
| 334 | activity::record( | 354 | activity::record( |
| 335 | &tx, | 355 | &tx, |
| 336 | NewActivity { | 356 | NewActivity { |
| @@ -348,25 +368,26 @@ impl Store { | |||
| 348 | finish(tx, outcome).await | 368 | finish(tx, outcome).await |
| 349 | } | 369 | } |
| 350 | 370 | ||
| 351 | - /// Bytes owed to deletion whose next attempt is due, oldest first: `(attachment id, attempts so far)`. | 371 | + /// Bytes owed to deletion whose next attempt is due, oldest first: `(attachment id, location, attempts so |
| 352 | - pub async fn due_blob_deletions(&self, limit: i64) -> Result<Vec<(String, i64)>> { | 372 | + /// far)`. The location names the copy to remove: `local` or `in`. |
| 373 | + pub async fn due_blob_deletions(&self, limit: i64) -> Result<Vec<(String, String, i64)>> { | ||
| 353 | let conn = self.read_conn().await; | 374 | let conn = self.read_conn().await; |
| 354 | fetch_all( | 375 | fetch_all( |
| 355 | &conn, | 376 | &conn, |
| 356 | - "SELECT attachment_id, attempts FROM blob_deletions WHERE next_attempt_at <= ?1 \ | 377 | + "SELECT attachment_id, location, attempts FROM blob_deletions WHERE next_attempt_at <= ?1 \ |
| 357 | - ORDER BY next_attempt_at, attachment_id LIMIT ?2", | 378 | + ORDER BY next_attempt_at, attachment_id, location LIMIT ?2", |
| 358 | (now_stamp(), limit), | 379 | (now_stamp(), limit), |
| 359 | - |row| Ok((col_text(row, 0)?, col_int(row, 1)?)), | 380 | + |row| Ok((col_text(row, 0)?, col_text(row, 1)?, col_int(row, 2)?)), |
| 360 | ) | 381 | ) |
| 361 | .await | 382 | .await |
| 362 | } | 383 | } |
| 363 | 384 | ||
| 364 | /// Clears a deletion once its bytes are confirmed gone. | 385 | /// Clears a deletion once its bytes are confirmed gone. |
| 365 | - pub async fn finish_blob_deletion(&self, attachment_id: &str) -> Result<()> { | 386 | + pub async fn finish_blob_deletion(&self, attachment_id: &str, location: &str) -> Result<()> { |
| 366 | let conn = self.inner.conn.lock().await; | 387 | let conn = self.inner.conn.lock().await; |
| 367 | conn.execute( | 388 | conn.execute( |
| 368 | - "DELETE FROM blob_deletions WHERE attachment_id = ?1", | 389 | + "DELETE FROM blob_deletions WHERE attachment_id = ?1 AND location = ?2", |
| 369 | - (attachment_id.to_owned(),), | 390 | + (attachment_id.to_owned(), location.to_owned()), |
| 370 | ) | 391 | ) |
| 371 | .await | 392 | .await |
| 372 | .map_err(db_err)?; | 393 | .map_err(db_err)?; |
| @@ -377,18 +398,136 @@ impl Store { | |||
| 377 | pub async fn defer_blob_deletion( | 398 | pub async fn defer_blob_deletion( |
| 378 | &self, | 399 | &self, |
| 379 | attachment_id: &str, | 400 | attachment_id: &str, |
| 401 | + location: &str, | ||
| 380 | attempts: i64, | 402 | attempts: i64, |
| 381 | delay: Duration, | 403 | delay: Duration, |
| 382 | ) -> Result<()> { | 404 | ) -> Result<()> { |
| 383 | let conn = self.inner.conn.lock().await; | 405 | let conn = self.inner.conn.lock().await; |
| 384 | conn.execute( | 406 | conn.execute( |
| 385 | - "UPDATE blob_deletions SET attempts = ?2, next_attempt_at = ?3 WHERE attachment_id = ?1", | 407 | + "UPDATE blob_deletions SET attempts = ?3, next_attempt_at = ?4 \ |
| 386 | - (attachment_id.to_owned(), attempts + 1, stamp_after(delay)), | 408 | + WHERE attachment_id = ?1 AND location = ?2", |
| 409 | + ( | ||
| 410 | + attachment_id.to_owned(), | ||
| 411 | + location.to_owned(), | ||
| 412 | + attempts + 1, | ||
| 413 | + stamp_after(delay), | ||
| 414 | + ), | ||
| 387 | ) | 415 | ) |
| 388 | .await | 416 | .await |
| 389 | .map_err(db_err)?; | 417 | .map_err(db_err)?; |
| 390 | Ok(()) | 418 | Ok(()) |
| 391 | } | 419 | } |
| 420 | + | ||
| 421 | + /// Sets the next attempt of a deletion `delay` from now, without counting a failure (the copy is busy, | ||
| 422 | + /// not broken). | ||
| 423 | + pub async fn postpone_blob_deletion( | ||
| 424 | + &self, | ||
| 425 | + attachment_id: &str, | ||
| 426 | + location: &str, | ||
| 427 | + delay: Duration, | ||
| 428 | + ) -> Result<()> { | ||
| 429 | + let conn = self.inner.conn.lock().await; | ||
| 430 | + conn.execute( | ||
| 431 | + "UPDATE blob_deletions SET next_attempt_at = ?3 WHERE attachment_id = ?1 AND location = ?2", | ||
| 432 | + (attachment_id.to_owned(), location.to_owned(), stamp_after(delay)), | ||
| 433 | + ) | ||
| 434 | + .await | ||
| 435 | + .map_err(db_err)?; | ||
| 436 | + Ok(()) | ||
| 437 | + } | ||
| 438 | + | ||
| 439 | + /// Owes the deleter a copy of attachment `attachment_id` in `location`. Recording it twice is harmless. | ||
| 440 | + pub async fn owe_blob_deletion(&self, attachment_id: &str, location: &str) -> Result<()> { | ||
| 441 | + let now = now_stamp(); | ||
| 442 | + let conn = self.inner.conn.lock().await; | ||
| 443 | + conn.execute( | ||
| 444 | + "INSERT OR IGNORE INTO blob_deletions (attachment_id, location, attempts, next_attempt_at, created_at) \ | ||
| 445 | + VALUES (?1, ?2, 0, ?3, ?3)", | ||
| 446 | + (attachment_id.to_owned(), location.to_owned(), now), | ||
| 447 | + ) | ||
| 448 | + .await | ||
| 449 | + .map_err(db_err)?; | ||
| 450 | + Ok(()) | ||
| 451 | + } | ||
| 452 | + | ||
| 453 | + /// The location of an attachment row, or `None` when the row is gone. Used by the mover and the deleter, | ||
| 454 | + /// which work on ids and need no task. | ||
| 455 | + pub async fn attachment_location(&self, attachment_id: &str) -> Result<Option<String>> { | ||
| 456 | + let conn = self.read_conn().await; | ||
| 457 | + fetch_opt( | ||
| 458 | + &conn, | ||
| 459 | + "SELECT location FROM attachments WHERE id = ?1", | ||
| 460 | + (attachment_id.to_owned(),), | ||
| 461 | + |row| col_text(row, 0), | ||
| 462 | + ) | ||
| 463 | + .await | ||
| 464 | + } | ||
| 465 | + | ||
| 466 | + /// Rows in `location`, oldest first: the candidates the mover picks from. | ||
| 467 | + pub async fn attachments_in_location( | ||
| 468 | + &self, | ||
| 469 | + location: &str, | ||
| 470 | + limit: i64, | ||
| 471 | + ) -> Result<Vec<Attachment>> { | ||
| 472 | + let conn = self.read_conn().await; | ||
| 473 | + fetch_all( | ||
| 474 | + &conn, | ||
| 475 | + &format!( | ||
| 476 | + "SELECT {ATTACHMENT_COLS} FROM attachments a WHERE a.location = ?1 \ | ||
| 477 | + ORDER BY a.created_at, a.id LIMIT ?2" | ||
| 478 | + ), | ||
| 479 | + (location.to_owned(), limit), | ||
| 480 | + map_attachment, | ||
| 481 | + ) | ||
| 482 | + .await | ||
| 483 | + } | ||
| 484 | + | ||
| 485 | + /// Moves a row from `from` to `to` only if it is still in `from`. `true` when this call did it. The mover | ||
| 486 | + /// claims a row this way (`from` to `moving`) and settles it the same way, so two movers never pick the | ||
| 487 | + /// same row, and a row deleted meanwhile is simply not found. | ||
| 488 | + pub async fn set_location_if(&self, attachment_id: &str, from: &str, to: &str) -> Result<bool> { | ||
| 489 | + let conn = self.inner.conn.lock().await; | ||
| 490 | + let changed = conn | ||
| 491 | + .execute( | ||
| 492 | + "UPDATE attachments SET location = ?3 WHERE id = ?1 AND location = ?2", | ||
| 493 | + (attachment_id.to_owned(), from.to_owned(), to.to_owned()), | ||
| 494 | + ) | ||
| 495 | + .await | ||
| 496 | + .map_err(db_err)?; | ||
| 497 | + Ok(changed > 0) | ||
| 498 | + } | ||
| 499 | + | ||
| 500 | + /// The ids of rows left in `moving` by a crash. Read once at boot. | ||
| 501 | + pub async fn moving_attachment_ids(&self) -> Result<Vec<String>> { | ||
| 502 | + let conn = self.read_conn().await; | ||
| 503 | + fetch_all( | ||
| 504 | + &conn, | ||
| 505 | + "SELECT id FROM attachments WHERE location = 'moving'", | ||
| 506 | + (), | ||
| 507 | + |row| col_text(row, 0), | ||
| 508 | + ) | ||
| 509 | + .await | ||
| 510 | + } | ||
| 511 | + | ||
| 512 | + /// How many rows are in each location, as `(location, count)`. Shows the progress of a migration. | ||
| 513 | + pub async fn attachment_location_counts(&self) -> Result<Vec<(String, i64)>> { | ||
| 514 | + let conn = self.read_conn().await; | ||
| 515 | + fetch_all( | ||
| 516 | + &conn, | ||
| 517 | + "SELECT location, COUNT(*) FROM attachments GROUP BY location", | ||
| 518 | + (), | ||
| 519 | + |row| Ok((col_text(row, 0)?, col_int(row, 1)?)), | ||
| 520 | + ) | ||
| 521 | + .await | ||
| 522 | + } | ||
| 523 | + | ||
| 524 | + /// Where attachments belong: the `attachment_location` setting, `local` when unset or unknown. | ||
| 525 | + pub async fn attachment_target(&self) -> Result<String> { | ||
| 526 | + Ok(match self.get_setting(SETTING_LOCATION).await?.as_deref() { | ||
| 527 | + Some(LOCATION_IN) => LOCATION_IN.to_owned(), | ||
| 528 | + _ => LOCATION_LOCAL.to_owned(), | ||
| 529 | + }) | ||
| 530 | + } | ||
| 392 | } | 531 | } |
| 393 | 532 | ||
| 394 | /// A live attachment of a live task of `board_id`, read on the writer so it is part of the transaction. | 533 | /// A live attachment of a live task of `board_id`, read on the writer so it is part of the transaction. |
crates/iz-core/src/store/migrate.rsmodified+4 -0
| @@ -16,6 +16,10 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ | |||
| 16 | ), | 16 | ), |
| 17 | (3, include_str!("../../migrations/0003_blob_deletions.sql")), | 17 | (3, include_str!("../../migrations/0003_blob_deletions.sql")), |
| 18 | (4, include_str!("../../migrations/0004_mail_events.sql")), | 18 | (4, include_str!("../../migrations/0004_mail_events.sql")), |
| 19 | + ( | ||
| 20 | + 5, | ||
| 21 | + include_str!("../../migrations/0005_blob_deletions_by_place.sql"), | ||
| 22 | + ), | ||
| 19 | ]; | 23 | ]; |
| 20 | 24 | ||
| 21 | fn migration_err(e: turso::Error) -> Error { | 25 | fn migration_err(e: turso::Error) -> Error { |
crates/iz-core/src/store/mod.rsmodified+1 -1
| @@ -403,7 +403,7 @@ mod tests { | |||
| 403 | }) | 403 | }) |
| 404 | .await | 404 | .await |
| 405 | .unwrap(); | 405 | .unwrap(); |
| 406 | - assert_eq!(versions, vec![1, 2, 3, 4]); | 406 | + assert_eq!(versions, vec![1, 2, 3, 4, 5]); |
| 407 | } | 407 | } |
| 408 | 408 | ||
| 409 | #[tokio::test] | 409 | #[tokio::test] |
crates/iz-web/src/attachments.rsmodified+153 -16
| @@ -1,14 +1,23 @@ | |||
| 1 | -//! The attachments' disk work that runs outside a request: the deleter. A deleted attachment's row is gone at | 1 | +//! The deleter: the attachments' disk and Files-service work that runs outside a request. A deleted |
| 2 | -//! once (the transaction in `iz-core` records the bytes in `blob_deletions`); this worker removes the bytes | 2 | +//! attachment's row is gone at once (the transaction in `iz-core` records the copies it owes in |
| 3 | -//! afterwards and retries with a backoff until they are gone, then clears the record. It runs until the stop | 3 | +//! `blob_deletions`, one record per place); this worker removes them and retries with a backoff until they are |
| 4 | -//! flag is set, like every worker (`docs/architecture.md` section 8). | 4 | +//! gone, then clears the record. It runs until the stop flag is set, like every worker |
| 5 | +//! (`docs/architecture.md` section 8). | ||
| 5 | //! | 6 | //! |
| 6 | -//! The bytes are only ever removed through `iz_core::staging::remove_blob`, which builds the path from the | 7 | +//! The rules that keep a live copy safe are the same ones the mover follows (`mover.rs`). Every step that |
| 7 | -//! validated attachment id. | 8 | +//! touches a copy, or the row that says where the bytes are, holds `AppState::blob_lock`. Under that lock, a |
| 9 | +//! record is judged against the row as it is then: | ||
| 10 | +//! - the row is `moving`: a move is under way, so the record waits; | ||
| 11 | +//! - the row is in the record's own place: the record is stale, and the copy is the live one, so nothing is removed; | ||
| 12 | +//! - the row is gone, or is in the other place: the owed copy is removed. | ||
| 13 | +//! | ||
| 14 | +//! Local copies are removed only through `iz_core::staging::remove_blob`, which builds the path from the validated | ||
| 15 | +//! attachment id. Files-service copies are removed with `DELETE`, which counts a missing object as done. | ||
| 8 | 16 | ||
| 9 | use std::time::Duration; | 17 | use std::time::Duration; |
| 10 | 18 | ||
| 11 | use iz_core::staging::remove_blob; | 19 | use iz_core::staging::remove_blob; |
| 20 | +use iz_core::store::attachments::{LOCATION_IN, LOCATION_LOCAL, LOCATION_MOVING}; | ||
| 12 | use tokio::sync::watch; | 21 | use tokio::sync::watch; |
| 13 | 22 | ||
| 14 | use crate::state::AppState; | 23 | use crate::state::AppState; |
| @@ -22,7 +31,7 @@ const SWEEP_EVERY: Duration = Duration::from_secs(5); | |||
| 22 | const SWEEP_BATCH: i64 = 50; | 31 | const SWEEP_BATCH: i64 = 50; |
| 23 | /// The first retry delay, in seconds. Doubles with each failed attempt. | 32 | /// The first retry delay, in seconds. Doubles with each failed attempt. |
| 24 | const RETRY_BASE_SECS: u64 = 5; | 33 | const RETRY_BASE_SECS: u64 = 5; |
| 25 | -/// The longest retry delay, in seconds. Reason: a file that cannot be removed is looked at every ten minutes. | 34 | +/// The longest retry delay, in seconds. Reason: a copy that cannot be removed is looked at every ten minutes. |
| 26 | const RETRY_CAP_SECS: u64 = 600; | 35 | const RETRY_CAP_SECS: u64 = 600; |
| 27 | 36 | ||
| 28 | /// The delay before the next attempt after `attempts` failures. | 37 | /// The delay before the next attempt after `attempts` failures. |
| @@ -45,8 +54,19 @@ pub fn spawn(state: AppState, mut stop: watch::Receiver<bool>) { | |||
| 45 | }); | 54 | }); |
| 46 | } | 55 | } |
| 47 | 56 | ||
| 48 | -/// One pass over the due deletions. A failure is logged and retried later; it never stops the worker. | 57 | +/// What one owed copy came to on this pass. |
| 49 | -async fn sweep(state: &AppState) { | 58 | +enum Step { |
| 59 | + /// The copy is gone, or was never needed. The record is cleared. | ||
| 60 | + Done, | ||
| 61 | + /// A move is under way for this row. Looked at again soon, without a failed attempt counted. | ||
| 62 | + Later, | ||
| 63 | + /// The removal failed. The record is retried with the backoff. | ||
| 64 | + Failed(String), | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +/// One pass over the due deletions. A failure is logged and retried later; it never stops the worker. Also | ||
| 68 | +/// run by the sweeper as a backstop. | ||
| 69 | +pub async fn sweep(state: &AppState) { | ||
| 50 | let due = match state.store.due_blob_deletions(SWEEP_BATCH).await { | 70 | let due = match state.store.due_blob_deletions(SWEEP_BATCH).await { |
| 51 | Ok(due) => due, | 71 | Ok(due) => due, |
| 52 | Err(error) => { | 72 | Err(error) => { |
| @@ -54,18 +74,37 @@ async fn sweep(state: &AppState) { | |||
| 54 | return; | 74 | return; |
| 55 | } | 75 | } |
| 56 | }; | 76 | }; |
| 57 | - for (id, attempts) in due { | 77 | + // Once a Files-service call fails, the rest of this pass leaves the Files copies for the next one: each call |
| 58 | - match remove_blob(&state.config.data_dir, &id).await { | 78 | + // may wait for the connection, and the blob lock is held meanwhile. |
| 59 | - Ok(()) => { | 79 | + let mut files_down = false; |
| 60 | - if let Err(error) = state.store.finish_blob_deletion(&id).await { | 80 | + for (id, location, attempts) in due { |
| 81 | + if files_down && location == LOCATION_IN { | ||
| 82 | + continue; | ||
| 83 | + } | ||
| 84 | + let step = remove_owed(state, &id, &location).await; | ||
| 85 | + if matches!(step, Step::Failed(_)) && location == LOCATION_IN { | ||
| 86 | + files_down = true; | ||
| 87 | + } | ||
| 88 | + match step { | ||
| 89 | + Step::Done => { | ||
| 90 | + if let Err(error) = state.store.finish_blob_deletion(&id, &location).await { | ||
| 61 | tracing::warn!(error = %error, "clearing a finished attachment deletion failed"); | 91 | tracing::warn!(error = %error, "clearing a finished attachment deletion failed"); |
| 62 | } | 92 | } |
| 63 | } | 93 | } |
| 64 | - Err(error) => { | 94 | + Step::Later => { |
| 65 | - tracing::warn!(attempts, error = %error, "removing attachment bytes failed; retrying"); | ||
| 66 | if let Err(error) = state | 95 | if let Err(error) = state |
| 67 | .store | 96 | .store |
| 68 | - .defer_blob_deletion(&id, attempts, retry_delay(attempts)) | 97 | + .postpone_blob_deletion(&id, &location, Duration::from_secs(RETRY_BASE_SECS)) |
| 98 | + .await | ||
| 99 | + { | ||
| 100 | + tracing::warn!(error = %error, "postponing an attachment deletion failed"); | ||
| 101 | + } | ||
| 102 | + } | ||
| 103 | + Step::Failed(reason) => { | ||
| 104 | + tracing::warn!(attempts, location = %location, reason, "removing an attachment copy failed; retrying"); | ||
| 105 | + if let Err(error) = state | ||
| 106 | + .store | ||
| 107 | + .defer_blob_deletion(&id, &location, attempts, retry_delay(attempts)) | ||
| 69 | .await | 108 | .await |
| 70 | { | 109 | { |
| 71 | tracing::warn!(error = %error, "scheduling an attachment deletion retry failed"); | 110 | tracing::warn!(error = %error, "scheduling an attachment deletion retry failed"); |
| @@ -75,6 +114,36 @@ async fn sweep(state: &AppState) { | |||
| 75 | } | 114 | } |
| 76 | } | 115 | } |
| 77 | 116 | ||
| 117 | +/// Removes one owed copy, judged against the row under the blob lock (see the module comment). | ||
| 118 | +async fn remove_owed(state: &AppState, id: &str, location: &str) -> Step { | ||
| 119 | + let _guard = state.blob_lock.lock().await; | ||
| 120 | + let here = match state.store.attachment_location(id).await { | ||
| 121 | + Ok(here) => here, | ||
| 122 | + Err(error) => return Step::Failed(error.to_string()), | ||
| 123 | + }; | ||
| 124 | + match here.as_deref() { | ||
| 125 | + Some(LOCATION_MOVING) => return Step::Later, | ||
| 126 | + Some(current) if current == location => return Step::Done, | ||
| 127 | + _ => {} | ||
| 128 | + } | ||
| 129 | + if location == LOCATION_LOCAL { | ||
| 130 | + return match remove_blob(&state.config.data_dir, id).await { | ||
| 131 | + Ok(()) => Step::Done, | ||
| 132 | + Err(error) => Step::Failed(error.to_string()), | ||
| 133 | + }; | ||
| 134 | + } | ||
| 135 | + if location != LOCATION_IN { | ||
| 136 | + return Step::Failed(format!("unknown location {location}")); | ||
| 137 | + } | ||
| 138 | + let Some(in_store) = state.in_store.as_ref() else { | ||
| 139 | + return Step::Failed("the Files service is not configured".into()); | ||
| 140 | + }; | ||
| 141 | + match in_store.delete(id).await { | ||
| 142 | + Ok(()) => Step::Done, | ||
| 143 | + Err(error) => Step::Failed(error.to_string()), | ||
| 144 | + } | ||
| 145 | +} | ||
| 146 | + | ||
| 78 | #[cfg(test)] | 147 | #[cfg(test)] |
| 79 | mod tests { | 148 | mod tests { |
| 80 | use super::*; | 149 | use super::*; |
| @@ -88,3 +157,71 @@ mod tests { | |||
| 88 | assert_eq!(retry_delay(-3), Duration::from_secs(5)); | 157 | assert_eq!(retry_delay(-3), Duration::from_secs(5)); |
| 89 | } | 158 | } |
| 90 | } | 159 | } |
| 160 | + | ||
| 161 | +#[cfg(test)] | ||
| 162 | +mod delete_tests { | ||
| 163 | + use std::sync::Arc; | ||
| 164 | + | ||
| 165 | + use iz_core::authz::{Actor, Role}; | ||
| 166 | + use iz_core::staging::blob_path; | ||
| 167 | + use iz_core::store::attachments::{LOCATION_IN, LOCATION_LOCAL}; | ||
| 168 | + | ||
| 169 | + use super::*; | ||
| 170 | + use crate::boot::test_state; | ||
| 171 | + use crate::in_store::InStore; | ||
| 172 | + use crate::in_store::test_support::{fake_in, reply, seed_attachment}; | ||
| 173 | + | ||
| 174 | + /// A DELETE that the Files service answers `404` for is already done: the record is cleared, not retried. | ||
| 175 | + #[tokio::test] | ||
| 176 | + async fn a_404_at_the_files_service_counts_as_deleted() { | ||
| 177 | + let (_dir, mut state) = test_state().await; | ||
| 178 | + let base = fake_in(|req| { | ||
| 179 | + if req.method == "DELETE" { | ||
| 180 | + reply(404, b"{}") | ||
| 181 | + } else { | ||
| 182 | + reply(405, b"") | ||
| 183 | + } | ||
| 184 | + }) | ||
| 185 | + .await; | ||
| 186 | + state.in_store = Some(Arc::new(InStore::for_tests(&base))); | ||
| 187 | + let row = seed_attachment(&state, "a.png", "image/png", b"pixels").await; | ||
| 188 | + // The row has moved: its bytes are at the Files service and the local copy is gone. | ||
| 189 | + assert!( | ||
| 190 | + state | ||
| 191 | + .store | ||
| 192 | + .set_location_if(&row.id, LOCATION_LOCAL, LOCATION_IN) | ||
| 193 | + .await | ||
| 194 | + .expect("move") | ||
| 195 | + ); | ||
| 196 | + std::fs::remove_file(blob_path(&state.config.data_dir, &row.id).expect("path")) | ||
| 197 | + .expect("local copy removed"); | ||
| 198 | + let board = state.store.ensure_board("IZ").await.expect("board"); | ||
| 199 | + let uploader = Actor::Member { | ||
| 200 | + sub: "bo".into(), | ||
| 201 | + role: Role::Member, | ||
| 202 | + im_admin: false, | ||
| 203 | + disabled: false, | ||
| 204 | + }; | ||
| 205 | + state | ||
| 206 | + .store | ||
| 207 | + .delete_attachment(&board.id, &row.id, &uploader) | ||
| 208 | + .await | ||
| 209 | + .expect("delete"); | ||
| 210 | + assert_eq!( | ||
| 211 | + state.store.due_blob_deletions(10).await.expect("due").len(), | ||
| 212 | + 1 | ||
| 213 | + ); | ||
| 214 | + | ||
| 215 | + sweep(&state).await; | ||
| 216 | + | ||
| 217 | + assert!( | ||
| 218 | + state | ||
| 219 | + .store | ||
| 220 | + .due_blob_deletions(10) | ||
| 221 | + .await | ||
| 222 | + .expect("due") | ||
| 223 | + .is_empty(), | ||
| 224 | + "a 404 counts as deleted" | ||
| 225 | + ); | ||
| 226 | + } | ||
| 227 | +} | ||
crates/iz-web/src/boot.rsmodified+14 -0
| @@ -20,7 +20,9 @@ use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService | |||
| 20 | 20 | ||
| 21 | use crate::attachments; | 21 | use crate::attachments; |
| 22 | use crate::directory; | 22 | use crate::directory; |
| 23 | +use crate::in_store::InStore; | ||
| 23 | use crate::live::LiveHub; | 24 | use crate::live::LiveHub; |
| 25 | +use crate::mover; | ||
| 24 | use crate::oidc; | 26 | use crate::oidc; |
| 25 | use crate::pages::not_found::NotFoundLayer; | 27 | use crate::pages::not_found::NotFoundLayer; |
| 26 | use crate::security::{self, SecurityHeaders}; | 28 | use crate::security::{self, SecurityHeaders}; |
| @@ -55,6 +57,7 @@ pub async fn serve(config_path: &Path) -> iz_core::Result<()> { | |||
| 55 | let (stop_tx, stop_rx) = watch::channel(false); | 57 | let (stop_tx, stop_rx) = watch::channel(false); |
| 56 | directory::spawn(state.clone(), stop_rx.clone()); | 58 | directory::spawn(state.clone(), stop_rx.clone()); |
| 57 | attachments::spawn(state.clone(), stop_rx.clone()); | 59 | attachments::spawn(state.clone(), stop_rx.clone()); |
| 60 | + mover::spawn(state.clone(), stop_rx.clone()); | ||
| 58 | crate::mail::spawn(state.clone(), stop_rx.clone()); | 61 | crate::mail::spawn(state.clone(), stop_rx.clone()); |
| 59 | crate::family::spawn(state.clone(), stop_rx.clone()); | 62 | crate::family::spawn(state.clone(), stop_rx.clone()); |
| 60 | crate::backup::spawn(state.clone(), stop_rx.clone()); | 63 | crate::backup::spawn(state.clone(), stop_rx.clone()); |
| @@ -104,6 +107,13 @@ async fn open_state(config: Config) -> iz_core::Result<AppState> { | |||
| 104 | } | 107 | } |
| 105 | None => None, | 108 | None => None, |
| 106 | }; | 109 | }; |
| 110 | + let in_store = match (&config.in_store, &oidc) { | ||
| 111 | + (in_config, Some(client)) if in_config.enabled => match &in_config.url { | ||
| 112 | + Some(url) => Some(Arc::new(InStore::new(url, client.clone())?)), | ||
| 113 | + None => None, | ||
| 114 | + }, | ||
| 115 | + _ => None, | ||
| 116 | + }; | ||
| 107 | Ok(AppState { | 117 | Ok(AppState { |
| 108 | config: Arc::new(config), | 118 | config: Arc::new(config), |
| 109 | store, | 119 | store, |
| @@ -111,6 +121,8 @@ async fn open_state(config: Config) -> iz_core::Result<AppState> { | |||
| 111 | live: Arc::new(LiveHub::default()), | 121 | live: Arc::new(LiveHub::default()), |
| 112 | oidc, | 122 | oidc, |
| 113 | family: Arc::default(), | 123 | family: Arc::default(), |
| 124 | + in_store, | ||
| 125 | + blob_lock: Arc::default(), | ||
| 114 | }) | 126 | }) |
| 115 | } | 127 | } |
| 116 | 128 | ||
| @@ -188,6 +200,8 @@ mod tests { | |||
| 188 | live: Arc::new(LiveHub::default()), | 200 | live: Arc::new(LiveHub::default()), |
| 189 | oidc: None, | 201 | oidc: None, |
| 190 | family: Arc::default(), | 202 | family: Arc::default(), |
| 203 | + in_store: None, | ||
| 204 | + blob_lock: Arc::default(), | ||
| 191 | }; | 205 | }; |
| 192 | (dir, state) | 206 | (dir, state) |
| 193 | } | 207 | } |
crates/iz-web/src/family.rsmodified+2 -0
| @@ -235,6 +235,8 @@ mod tests { | |||
| 235 | live: std::sync::Arc::default(), | 235 | live: std::sync::Arc::default(), |
| 236 | oidc: None, | 236 | oidc: None, |
| 237 | family: std::sync::Arc::default(), | 237 | family: std::sync::Arc::default(), |
| 238 | + in_store: None, | ||
| 239 | + blob_lock: std::sync::Arc::default(), | ||
| 238 | }; | 240 | }; |
| 239 | let request = http::Request::get("/no/such/page") | 241 | let request = http::Request::get("/no/such/page") |
| 240 | .header(http::header::ACCEPT, "text/html") | 242 | .header(http::header::ACCEPT, "text/html") |
crates/iz-web/src/i18n/shell.rsmodified+12 -0
| @@ -28,6 +28,10 @@ pub enum K { | |||
| 28 | SignInUnavailableTitle, | 28 | SignInUnavailableTitle, |
| 29 | /// The sentence under that title. | 29 | /// The sentence under that title. |
| 30 | SignInUnavailableBody, | 30 | SignInUnavailableBody, |
| 31 | + /// The title of the page that says a file cannot be sent right now. | ||
| 32 | + FilesUnavailableTitle, | ||
| 33 | + /// The sentence under that title. | ||
| 34 | + FilesUnavailableBody, | ||
| 31 | /// The title of the 404 page. | 35 | /// The title of the 404 page. |
| 32 | NotFoundTitle, | 36 | NotFoundTitle, |
| 33 | /// The sentence on the signed-out start page. | 37 | /// The sentence on the signed-out start page. |
| @@ -68,6 +72,14 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 68 | (K::SignInUnavailableBody, Lang::Tr) => { | 72 | (K::SignInUnavailableBody, Lang::Tr) => { |
| 69 | "Hesap servisine şu anda ulaşılamıyor. Birkaç dakika sonra tekrar deneyin." | 73 | "Hesap servisine şu anda ulaşılamıyor. Birkaç dakika sonra tekrar deneyin." |
| 70 | } | 74 | } |
| 75 | + (K::FilesUnavailableTitle, Lang::En) => "The file cannot be opened right now", | ||
| 76 | + (K::FilesUnavailableTitle, Lang::Tr) => "Dosya şu an açılamıyor", | ||
| 77 | + (K::FilesUnavailableBody, Lang::En) => { | ||
| 78 | + "The file is kept in the Files service, which cannot be reached right now. Try again in a few minutes." | ||
| 79 | + } | ||
| 80 | + (K::FilesUnavailableBody, Lang::Tr) => { | ||
| 81 | + "Bu dosya dış dosya hizmetinde saklanıyor ve şu anda o hizmete ulaşılamıyor. Birkaç dakika sonra tekrar deneyin." | ||
| 82 | + } | ||
| 71 | (K::NoAccessTitle, Lang::En) => "No access to this board", | 83 | (K::NoAccessTitle, Lang::En) => "No access to this board", |
| 72 | (K::NoAccessTitle, Lang::Tr) => "Bu panoya erişiminiz yok", | 84 | (K::NoAccessTitle, Lang::Tr) => "Bu panoya erişiminiz yok", |
| 73 | (K::NoAccessBody, Lang::En) => { | 85 | (K::NoAccessBody, Lang::En) => { |
crates/iz-web/src/i18n/structure.rsmodified+35 -0
| @@ -120,6 +120,15 @@ pub enum K { | |||
| 120 | LimitExtensions, | 120 | LimitExtensions, |
| 121 | /// Button that saves the limits. | 121 | /// Button that saves the limits. |
| 122 | LimitsSave, | 122 | LimitsSave, |
| 123 | + StorageHeading, | ||
| 124 | + StorageHelp, | ||
| 125 | + StorageCounts, | ||
| 126 | + StorageMigrating, | ||
| 127 | + StorageLocalOption, | ||
| 128 | + StorageInOption, | ||
| 129 | + StorageInUnavailable, | ||
| 130 | + StorageSave, | ||
| 131 | + NoticeStorageSaved, | ||
| 123 | /// Settings section: server information. | 132 | /// Settings section: server information. |
| 124 | ServerHeading, | 133 | ServerHeading, |
| 125 | /// Help text of the server section. | 134 | /// Help text of the server section. |
| @@ -304,6 +313,32 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 304 | (K::LimitMib, Tr) => "Ek boyutu sınırı (MiB)", | 313 | (K::LimitMib, Tr) => "Ek boyutu sınırı (MiB)", |
| 305 | (K::LimitExtensions, En) => "Allowed extensions", | 314 | (K::LimitExtensions, En) => "Allowed extensions", |
| 306 | (K::LimitExtensions, Tr) => "İzin verilen uzantılar", | 315 | (K::LimitExtensions, Tr) => "İzin verilen uzantılar", |
| 316 | + (K::StorageHeading, En) => "Attachment storage", | ||
| 317 | + (K::StorageHeading, Tr) => "Ek depolama", | ||
| 318 | + (K::StorageHelp, En) => { | ||
| 319 | + "New attachments are written here first. With the Files service chosen, they move there in the background; with this server chosen, they move back. A move resumes after a restart." | ||
| 320 | + } | ||
| 321 | + (K::StorageHelp, Tr) => { | ||
| 322 | + "Yeni ekler önce burada yazılır. Dosya hizmeti seçiliyse arka planda oraya taşınır; bu sunucu seçiliyse geri taşınır. Taşıma yeniden başlatmadan sonra kaldığı yerden sürer." | ||
| 323 | + } | ||
| 324 | + (K::StorageCounts, En) => "{} on this server, {} in the Files service, {} moving.", | ||
| 325 | + (K::StorageCounts, Tr) => "Bu sunucuda {}, dosya hizmetinde {}, taşınan {}.", | ||
| 326 | + (K::StorageMigrating, En) => "{} files are waiting to move to {}.", | ||
| 327 | + (K::StorageMigrating, Tr) => "{} dosya {} taşınmayı bekliyor.", | ||
| 328 | + (K::StorageLocalOption, En) => "Keep attachments on this server", | ||
| 329 | + (K::StorageLocalOption, Tr) => "Ekleri bu sunucuda tut", | ||
| 330 | + (K::StorageInOption, En) => "Keep attachments in the Files service", | ||
| 331 | + (K::StorageInOption, Tr) => "Ekleri dosya hizmetinde tut", | ||
| 332 | + (K::StorageInUnavailable, En) => { | ||
| 333 | + "The Files service is not set up on this server. It needs [in_store] enabled with a url in the config file, and sign-in with im." | ||
| 334 | + } | ||
| 335 | + (K::StorageInUnavailable, Tr) => { | ||
| 336 | + "Dosya hizmeti bu sunucuda kurulu değil. Yapılandırma dosyasında [in_store] etkin ve bir url ile tanımlanmalı, im ile oturum açılabilmeli." | ||
| 337 | + } | ||
| 338 | + (K::StorageSave, En) => "Save storage", | ||
| 339 | + (K::StorageSave, Tr) => "Depolamayı kaydet", | ||
| 340 | + (K::NoticeStorageSaved, En) => "Attachment storage saved. Files move in the background.", | ||
| 341 | + (K::NoticeStorageSaved, Tr) => "Ek depolama kaydedildi. Dosyalar arka planda taşınır.", | ||
| 307 | (K::LimitsSave, En) => "Save limits", | 342 | (K::LimitsSave, En) => "Save limits", |
| 308 | (K::LimitsSave, Tr) => "Sınırları kaydet", | 343 | (K::LimitsSave, Tr) => "Sınırları kaydet", |
| 309 | (K::ServerHeading, En) => "Server", | 344 | (K::ServerHeading, En) => "Server", |
crates/iz-web/src/in_store.rsadded+493 -0
| @@ -0,0 +1,493 @@ | |||
| 1 | +//! The client of `in`'s object API (contracts.md 5): the attachments that live at the Files service. | ||
| 2 | +//! | ||
| 3 | +//! Every call carries a client-credentials token for `aud = in` and scope `files.service`. It comes from the | ||
| 4 | +//! same `im` client as the sign-in, cached under its own key (`OidcClient::client_token`), so it never | ||
| 5 | +//! replaces the directory token. | ||
| 6 | +//! | ||
| 7 | +//! Two HTTP clients. Uploads and deletes are bounded by [`WRITE_TIMEOUT`] for the whole call. Reads have | ||
| 8 | +//! no whole-call bound, because a large download is streamed and may take longer; they have a stall bound | ||
| 9 | +//! ([`READ_STALL`]) instead. Neither client follows | ||
| 10 | +//! redirects: a redirect would carry the bearer token to another host. | ||
| 11 | +//! | ||
| 12 | +//! The answers are checked here and never trusted blindly. A `PUT` must answer with the size and digest | ||
| 13 | +//! the caller sent; a `GET` must answer the status the range asked for. | ||
| 14 | + | ||
| 15 | +use std::path::Path; | ||
| 16 | +use std::sync::Arc; | ||
| 17 | +use std::time::Duration; | ||
| 18 | + | ||
| 19 | +use bytes::Bytes; | ||
| 20 | +use futures_util::Stream; | ||
| 21 | +use http::header::{CONTENT_LENGTH, CONTENT_TYPE, RANGE}; | ||
| 22 | +use serde_json::Value; | ||
| 23 | +use tokio::io::AsyncReadExt; | ||
| 24 | + | ||
| 25 | +use crate::oidc::OidcClient; | ||
| 26 | + | ||
| 27 | +/// The audience of every object call: the family key of `in`. | ||
| 28 | +pub const IN_AUDIENCE: &str = "in"; | ||
| 29 | +/// The scope that stores and reads a family service's own objects at `in`. | ||
| 30 | +pub const FILES_SCOPE: &str = "files.service"; | ||
| 31 | +/// The longest an upload or a delete may take, end to end. Reason: the spec for this client; a slow link | ||
| 32 | +/// retries with backoff instead of holding the mover. | ||
| 33 | +pub const WRITE_TIMEOUT: Duration = Duration::from_secs(60); | ||
| 34 | +/// The longest a connection may take to open. Applies to every call. | ||
| 35 | +const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); | ||
| 36 | +/// The longest a read may stall: between two chunks of a download, or before the answer's first byte. Reason: | ||
| 37 | +/// a download may be long, but a stalled one must not hold a request or the mover forever. | ||
| 38 | +const READ_STALL: Duration = Duration::from_secs(30); | ||
| 39 | +/// Bytes read from a local file per upload frame. | ||
| 40 | +const UPLOAD_FRAME: usize = 64 * 1024; | ||
| 41 | +/// The longest `X-Object-Name` sent, in bytes. `in` refuses longer names. | ||
| 42 | +const NAME_MAX_BYTES: usize = 255; | ||
| 43 | +/// The largest JSON answer of a PUT that is read. | ||
| 44 | +const PUT_ANSWER_MAX: u64 = 4096; | ||
| 45 | + | ||
| 46 | +/// Why a call to `in` did not give its answer. | ||
| 47 | +#[derive(Debug, thiserror::Error)] | ||
| 48 | +pub enum InError { | ||
| 49 | + /// `in` or the token service could not be reached, or did not answer in time. | ||
| 50 | + #[error("the Files service cannot be reached: {0}")] | ||
| 51 | + Unavailable(String), | ||
| 52 | + /// `in` answered with a status that is not a success for this call. | ||
| 53 | + #[error("the Files service answered {0}")] | ||
| 54 | + Refused(u16), | ||
| 55 | + /// `in` answered, but not in the form the contract gives, or with other bytes than were sent. | ||
| 56 | + #[error("the Files service answered in an unexpected way: {0}")] | ||
| 57 | + BadResponse(String), | ||
| 58 | + /// A local file could not be read to be sent. | ||
| 59 | + #[error("a local file could not be read: {0}")] | ||
| 60 | + Local(#[from] std::io::Error), | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +/// The result of a call to `in`. | ||
| 64 | +pub type InResult<T> = std::result::Result<T, InError>; | ||
| 65 | + | ||
| 66 | +/// What `in` says it stored after a PUT (contracts.md 5). | ||
| 67 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 68 | +pub struct Stored { | ||
| 69 | + /// Length in bytes. | ||
| 70 | + pub size: u64, | ||
| 71 | + /// Lowercase hex SHA-256. | ||
| 72 | + pub sha256: String, | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +/// Where the bearer token comes from: the `im` client in production. | ||
| 76 | +enum Tokens { | ||
| 77 | + Oidc(Arc<OidcClient>), | ||
| 78 | + #[cfg(test)] | ||
| 79 | + Fixed(String), | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +/// The Files service of this instance: its origin and the way to reach it. | ||
| 83 | +pub struct InStore { | ||
| 84 | + base: String, | ||
| 85 | + write_http: reqwest::Client, | ||
| 86 | + read_http: reqwest::Client, | ||
| 87 | + tokens: Tokens, | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +impl InStore { | ||
| 91 | + /// Builds the client for the origin `base_url` (no trailing slash), with tokens from `oidc`. | ||
| 92 | + pub fn new(base_url: &str, oidc: Arc<OidcClient>) -> iz_core::Result<Self> { | ||
| 93 | + Ok(Self { | ||
| 94 | + base: base_url.trim_end_matches('/').to_owned(), | ||
| 95 | + write_http: clients(true)?, | ||
| 96 | + read_http: clients(false)?, | ||
| 97 | + tokens: Tokens::Oidc(oidc), | ||
| 98 | + }) | ||
| 99 | + } | ||
| 100 | + | ||
| 101 | + /// The URL of object `id` at `in`. | ||
| 102 | + fn object_url(&self, id: &str) -> String { | ||
| 103 | + format!("{}/api/v1/objects/{id}", self.base) | ||
| 104 | + } | ||
| 105 | + | ||
| 106 | + /// The bearer token for an object call. | ||
| 107 | + async fn token(&self) -> InResult<String> { | ||
| 108 | + match &self.tokens { | ||
| 109 | + Tokens::Oidc(oidc) => oidc | ||
| 110 | + .client_token(IN_AUDIENCE, FILES_SCOPE) | ||
| 111 | + .await | ||
| 112 | + .map_err(|error| InError::Unavailable(error.to_string())), | ||
| 113 | + #[cfg(test)] | ||
| 114 | + Tokens::Fixed(token) => Ok(token.clone()), | ||
| 115 | + } | ||
| 116 | + } | ||
| 117 | + | ||
| 118 | + /// Stores the file at `path` as object `id`, with the stored `mime` and the display `name`. The file is | ||
| 119 | + /// streamed from disk. The answer must carry the same size and digest the caller sent, or the call fails. | ||
| 120 | + pub async fn put( | ||
| 121 | + &self, | ||
| 122 | + id: &str, | ||
| 123 | + path: &Path, | ||
| 124 | + size: u64, | ||
| 125 | + mime: &str, | ||
| 126 | + name: &str, | ||
| 127 | + sha256: &str, | ||
| 128 | + ) -> InResult<Stored> { | ||
| 129 | + let token = self.token().await?; | ||
| 130 | + let file = tokio::fs::File::open(path).await?; | ||
| 131 | + let response = self | ||
| 132 | + .write_http | ||
| 133 | + .put(self.object_url(id)) | ||
| 134 | + .bearer_auth(token) | ||
| 135 | + .header(CONTENT_TYPE, mime) | ||
| 136 | + .header(CONTENT_LENGTH, size) | ||
| 137 | + .header("X-Object-Name", encode_name(name)) | ||
| 138 | + .body(reqwest::Body::wrap_stream(file_frames(file))) | ||
| 139 | + .send() | ||
| 140 | + .await | ||
| 141 | + .map_err(transport)?; | ||
| 142 | + let status = response.status().as_u16(); | ||
| 143 | + if status != 200 && status != 201 { | ||
| 144 | + return Err(InError::Refused(status)); | ||
| 145 | + } | ||
| 146 | + let text = response.bytes().await.map_err(transport)?; | ||
| 147 | + if u64::try_from(text.len()).unwrap_or(u64::MAX) > PUT_ANSWER_MAX { | ||
| 148 | + return Err(InError::BadResponse("the PUT answer is too large".into())); | ||
| 149 | + } | ||
| 150 | + let answer: Value = serde_json::from_slice(&text) | ||
| 151 | + .map_err(|error| InError::BadResponse(format!("the PUT answer: {error}")))?; | ||
| 152 | + let stored = Stored { | ||
| 153 | + size: answer | ||
| 154 | + .get("size") | ||
| 155 | + .and_then(Value::as_u64) | ||
| 156 | + .unwrap_or(u64::MAX), | ||
| 157 | + sha256: answer | ||
| 158 | + .get("sha256") | ||
| 159 | + .and_then(Value::as_str) | ||
| 160 | + .unwrap_or_default() | ||
| 161 | + .to_owned(), | ||
| 162 | + }; | ||
| 163 | + if stored.size != size || stored.sha256 != sha256 { | ||
| 164 | + return Err(InError::BadResponse( | ||
| 165 | + "the stored size or digest is not the one sent".into(), | ||
| 166 | + )); | ||
| 167 | + } | ||
| 168 | + Ok(stored) | ||
| 169 | + } | ||
| 170 | + | ||
| 171 | + /// Reads object `id`, or the bytes of `range` (`first` and `last`, both inclusive) when one is given. The | ||
| 172 | + /// response is returned unread: the caller streams it. Only `200` (whole) or `206` (range) are accepted. | ||
| 173 | + pub async fn get(&self, id: &str, range: Option<(u64, u64)>) -> InResult<reqwest::Response> { | ||
| 174 | + let token = self.token().await?; | ||
| 175 | + let mut request = self.read_http.get(self.object_url(id)).bearer_auth(token); | ||
| 176 | + if let Some((first, last)) = range { | ||
| 177 | + request = request.header(RANGE, format!("bytes={first}-{last}")); | ||
| 178 | + } | ||
| 179 | + let response = request.send().await.map_err(transport)?; | ||
| 180 | + let status = response.status().as_u16(); | ||
| 181 | + if status == 200 || status == 206 { | ||
| 182 | + Ok(response) | ||
| 183 | + } else { | ||
| 184 | + Err(InError::Refused(status)) | ||
| 185 | + } | ||
| 186 | + } | ||
| 187 | + | ||
| 188 | + /// Deletes object `id`. An object that is already gone counts as deleted (contracts.md 5). | ||
| 189 | + pub async fn delete(&self, id: &str) -> InResult<()> { | ||
| 190 | + let token = self.token().await?; | ||
| 191 | + let response = self | ||
| 192 | + .write_http | ||
| 193 | + .delete(self.object_url(id)) | ||
| 194 | + .bearer_auth(token) | ||
| 195 | + .send() | ||
| 196 | + .await | ||
| 197 | + .map_err(transport)?; | ||
| 198 | + let status = response.status().as_u16(); | ||
| 199 | + if (200..300).contains(&status) || status == 404 { | ||
| 200 | + Ok(()) | ||
| 201 | + } else { | ||
| 202 | + Err(InError::Refused(status)) | ||
| 203 | + } | ||
| 204 | + } | ||
| 205 | +} | ||
| 206 | + | ||
| 207 | +/// A client with the bounds of its kind: writes have the whole-call timeout, reads only the connect bound. | ||
| 208 | +fn clients(write: bool) -> iz_core::Result<reqwest::Client> { | ||
| 209 | + let mut builder = reqwest::Client::builder() | ||
| 210 | + .connect_timeout(CONNECT_TIMEOUT) | ||
| 211 | + .read_timeout(READ_STALL) | ||
| 212 | + .redirect(reqwest::redirect::Policy::none()) | ||
| 213 | + .user_agent(concat!("iz/", env!("CARGO_PKG_VERSION"))); | ||
| 214 | + if write { | ||
| 215 | + builder = builder.timeout(WRITE_TIMEOUT); | ||
| 216 | + } | ||
| 217 | + builder | ||
| 218 | + .build() | ||
| 219 | + .map_err(|error| iz_core::Error::Config(format!("cannot build the Files client: {error}"))) | ||
| 220 | +} | ||
| 221 | + | ||
| 222 | +/// A connection-level failure as an [`InError`]. | ||
| 223 | +fn transport(error: reqwest::Error) -> InError { | ||
| 224 | + InError::Unavailable(error.to_string()) | ||
| 225 | +} | ||
| 226 | + | ||
| 227 | +/// The file as a stream of frames, read in [`UPLOAD_FRAME`] pieces, so a large upload is never held whole. | ||
| 228 | +fn file_frames( | ||
| 229 | + file: tokio::fs::File, | ||
| 230 | +) -> impl Stream<Item = std::io::Result<Bytes>> + Send + 'static { | ||
| 231 | + futures_util::stream::try_unfold(file, |mut file| async move { | ||
| 232 | + let mut buf = vec![0u8; UPLOAD_FRAME]; | ||
| 233 | + let read = file.read(&mut buf).await?; | ||
| 234 | + if read == 0 { | ||
| 235 | + return Ok(None); | ||
| 236 | + } | ||
| 237 | + buf.truncate(read); | ||
| 238 | + Ok(Some((Bytes::from(buf), file))) | ||
| 239 | + }) | ||
| 240 | +} | ||
| 241 | + | ||
| 242 | +/// The `X-Object-Name` value: the name cut to [`NAME_MAX_BYTES`] at a character boundary, then percent-encoded | ||
| 243 | +/// as UTF-8 (every byte outside the unreserved set is escaped, so `+` and `%` cannot be misread). | ||
| 244 | +pub fn encode_name(name: &str) -> String { | ||
| 245 | + let mut end = name.len().min(NAME_MAX_BYTES); | ||
| 246 | + while !name.is_char_boundary(end) { | ||
| 247 | + end -= 1; | ||
| 248 | + } | ||
| 249 | + let mut out = String::with_capacity(end); | ||
| 250 | + for &byte in &name.as_bytes()[..end] { | ||
| 251 | + if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) { | ||
| 252 | + out.push(char::from(byte)); | ||
| 253 | + } else { | ||
| 254 | + out.push_str(&format!("%{byte:02X}")); | ||
| 255 | + } | ||
| 256 | + } | ||
| 257 | + out | ||
| 258 | +} | ||
| 259 | + | ||
| 260 | +#[cfg(test)] | ||
| 261 | +impl InStore { | ||
| 262 | + /// A client for `base` with a fixed token, for the tests that run a fake `in`. | ||
| 263 | + pub fn for_tests(base: &str) -> Self { | ||
| 264 | + Self { | ||
| 265 | + base: base.trim_end_matches('/').to_owned(), | ||
| 266 | + write_http: clients(true).expect("client"), | ||
| 267 | + read_http: clients(false).expect("client"), | ||
| 268 | + tokens: Tokens::Fixed("test-token".into()), | ||
| 269 | + } | ||
| 270 | + } | ||
| 271 | +} | ||
| 272 | + | ||
| 273 | +#[cfg(test)] | ||
| 274 | +mod tests { | ||
| 275 | + use super::*; | ||
| 276 | + | ||
| 277 | + #[test] | ||
| 278 | + fn names_are_escaped_and_cut_to_the_limit() { | ||
| 279 | + assert_eq!(encode_name("a b+c.pdf"), "a%20b%2Bc.pdf"); | ||
| 280 | + assert_eq!(encode_name("ü.txt"), "%C3%BC.txt"); | ||
| 281 | + let long = "é".repeat(200); | ||
| 282 | + assert!(encode_name(&long).len() <= NAME_MAX_BYTES * 3); | ||
| 283 | + let plain = "x".repeat(300); | ||
| 284 | + assert_eq!(encode_name(&plain).len(), NAME_MAX_BYTES); | ||
| 285 | + } | ||
| 286 | +} | ||
| 287 | + | ||
| 288 | +/// A fake `in` for the tests: a loopback listener that answers each request with a closure, and a seeder that | ||
| 289 | +/// writes a local attachment through the store's own calls. | ||
| 290 | +#[cfg(test)] | ||
| 291 | +pub(crate) mod test_support { | ||
| 292 | + use std::sync::Arc; | ||
| 293 | + | ||
| 294 | + use iz_core::authz::Role; | ||
| 295 | + use iz_core::staging::blob_path; | ||
| 296 | + use iz_core::store::attachments::{Attachment, NewAttachment, new_attachment_id}; | ||
| 297 | + use iz_core::store::members::DirectoryMember; | ||
| 298 | + use iz_core::store::tasks::NewTask; | ||
| 299 | + use sha2::{Digest, Sha256}; | ||
| 300 | + use tokio::io::{AsyncReadExt, AsyncWriteExt}; | ||
| 301 | + use tokio::net::{TcpListener, TcpStream}; | ||
| 302 | + | ||
| 303 | + use crate::state::AppState; | ||
| 304 | + | ||
| 305 | + /// A request the fake received. | ||
| 306 | + #[derive(Debug, Clone)] | ||
| 307 | + pub struct Req { | ||
| 308 | + /// The method, as sent. | ||
| 309 | + pub method: String, | ||
| 310 | + /// The headers, names as sent. | ||
| 311 | + pub headers: Vec<(String, String)>, | ||
| 312 | + /// The body, cut to its `Content-Length`. | ||
| 313 | + pub body: Vec<u8>, | ||
| 314 | + } | ||
| 315 | + | ||
| 316 | + impl Req { | ||
| 317 | + /// The first value of a header, compared without regard to case. | ||
| 318 | + pub fn header(&self, name: &str) -> Option<&str> { | ||
| 319 | + self.headers | ||
| 320 | + .iter() | ||
| 321 | + .find(|(n, _)| n.eq_ignore_ascii_case(name)) | ||
| 322 | + .map(|(_, v)| v.as_str()) | ||
| 323 | + } | ||
| 324 | + } | ||
| 325 | + | ||
| 326 | + /// The fake's answer: status, extra headers, and the body. | ||
| 327 | + #[derive(Debug, Clone)] | ||
| 328 | + pub struct Reply { | ||
| 329 | + /// The status code. | ||
| 330 | + pub status: u16, | ||
| 331 | + /// Extra headers, sent as given. `Content-Length` is added by the fake. | ||
| 332 | + pub headers: Vec<(String, String)>, | ||
| 333 | + /// The body. | ||
| 334 | + pub body: Vec<u8>, | ||
| 335 | + } | ||
| 336 | + | ||
| 337 | + /// An answer with `status` and `body` and no extra headers. | ||
| 338 | + pub fn reply(status: u16, body: &[u8]) -> Reply { | ||
| 339 | + Reply { | ||
| 340 | + status, | ||
| 341 | + headers: Vec::new(), | ||
| 342 | + body: body.to_vec(), | ||
| 343 | + } | ||
| 344 | + } | ||
| 345 | + | ||
| 346 | + /// Starts a fake `in` on a free loopback port, answering each request with `handler`. Returns its origin. | ||
| 347 | + pub async fn fake_in(handler: impl Fn(&Req) -> Reply + Send + Sync + 'static) -> String { | ||
| 348 | + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); | ||
| 349 | + let addr = listener.local_addr().expect("address"); | ||
| 350 | + let handler = Arc::new(handler); | ||
| 351 | + tokio::spawn(async move { | ||
| 352 | + while let Ok((socket, _)) = listener.accept().await { | ||
| 353 | + let handler = handler.clone(); | ||
| 354 | + tokio::spawn(answer(socket, handler)); | ||
| 355 | + } | ||
| 356 | + }); | ||
| 357 | + format!("http://{addr}") | ||
| 358 | + } | ||
| 359 | + | ||
| 360 | + /// Reads one request from `socket`, answers it, and closes the connection. | ||
| 361 | + async fn answer(mut socket: TcpStream, handler: Arc<dyn Fn(&Req) -> Reply + Send + Sync>) { | ||
| 362 | + let Some(request) = read_request(&mut socket).await else { | ||
| 363 | + return; | ||
| 364 | + }; | ||
| 365 | + let reply = handler(&request); | ||
| 366 | + let mut head = format!( | ||
| 367 | + "HTTP/1.1 {} Test\r\nContent-Length: {}\r\nConnection: close\r\n", | ||
| 368 | + reply.status, | ||
| 369 | + reply.body.len() | ||
| 370 | + ); | ||
| 371 | + for (name, value) in &reply.headers { | ||
| 372 | + head.push_str(&format!("{name}: {value}\r\n")); | ||
| 373 | + } | ||
| 374 | + head.push_str("\r\n"); | ||
| 375 | + let _ = socket.write_all(head.as_bytes()).await; | ||
| 376 | + let _ = socket.write_all(&reply.body).await; | ||
| 377 | + let _ = socket.shutdown().await; | ||
| 378 | + } | ||
| 379 | + | ||
| 380 | + /// Reads a request head and its `Content-Length` body. | ||
| 381 | + async fn read_request(socket: &mut TcpStream) -> Option<Req> { | ||
| 382 | + let mut buf: Vec<u8> = Vec::new(); | ||
| 383 | + let head_end = loop { | ||
| 384 | + if let Some(at) = buf.windows(4).position(|w| w == b"\r\n\r\n") { | ||
| 385 | + break at + 4; | ||
| 386 | + } | ||
| 387 | + let mut chunk = [0u8; 4096]; | ||
| 388 | + let read = socket.read(&mut chunk).await.ok()?; | ||
| 389 | + if read == 0 { | ||
| 390 | + return None; | ||
| 391 | + } | ||
| 392 | + buf.extend_from_slice(&chunk[..read]); | ||
| 393 | + }; | ||
| 394 | + let head = String::from_utf8_lossy(&buf[..head_end]).into_owned(); | ||
| 395 | + let mut lines = head.split("\r\n"); | ||
| 396 | + let mut parts = lines.next()?.split(' '); | ||
| 397 | + let method = parts.next()?.to_owned(); | ||
| 398 | + let headers: Vec<(String, String)> = lines | ||
| 399 | + .filter_map(|line| line.split_once(':')) | ||
| 400 | + .map(|(name, value)| (name.trim().to_owned(), value.trim().to_owned())) | ||
| 401 | + .collect(); | ||
| 402 | + let length = headers | ||
| 403 | + .iter() | ||
| 404 | + .find(|(name, _)| name.eq_ignore_ascii_case("content-length")) | ||
| 405 | + .and_then(|(_, value)| value.parse::<usize>().ok()) | ||
| 406 | + .unwrap_or(0); | ||
| 407 | + let mut body = buf[head_end..].to_vec(); | ||
| 408 | + while body.len() < length { | ||
| 409 | + let mut chunk = [0u8; 8192]; | ||
| 410 | + let read = socket.read(&mut chunk).await.ok()?; | ||
| 411 | + if read == 0 { | ||
| 412 | + break; | ||
| 413 | + } | ||
| 414 | + body.extend_from_slice(&chunk[..read]); | ||
| 415 | + } | ||
| 416 | + body.truncate(length); | ||
| 417 | + Some(Req { | ||
| 418 | + method, | ||
| 419 | + headers, | ||
| 420 | + body, | ||
| 421 | + }) | ||
| 422 | + } | ||
| 423 | + | ||
| 424 | + /// Seeds two members, a board, a task and one attachment of `bytes` stored locally, all through the store's | ||
| 425 | + /// own calls. The bytes are written where the upload would put them. | ||
| 426 | + pub async fn seed_attachment( | ||
| 427 | + state: &AppState, | ||
| 428 | + name: &str, | ||
| 429 | + mime: &str, | ||
| 430 | + bytes: &[u8], | ||
| 431 | + ) -> Attachment { | ||
| 432 | + let store = &state.store; | ||
| 433 | + for (sub, role) in [("ada", Role::Admin), ("bo", Role::Member)] { | ||
| 434 | + let member = DirectoryMember { | ||
| 435 | + sub: sub.into(), | ||
| 436 | + email: format!("{sub}@example.com"), | ||
| 437 | + name: sub.into(), | ||
| 438 | + im_admin: false, | ||
| 439 | + disabled: false, | ||
| 440 | + locale: None, | ||
| 441 | + zoneinfo: "UTC".into(), | ||
| 442 | + picture_version: 0, | ||
| 443 | + }; | ||
| 444 | + store | ||
| 445 | + .apply_directory_member(&member, role) | ||
| 446 | + .await | ||
| 447 | + .expect("member"); | ||
| 448 | + } | ||
| 449 | + let board = store.ensure_board("IZ").await.expect("board"); | ||
| 450 | + let column = store.columns(&board.id).await.expect("columns")[0] | ||
| 451 | + .id | ||
| 452 | + .clone(); | ||
| 453 | + let tag = store.tags(&board.id).await.expect("tags")[0].id.clone(); | ||
| 454 | + let task = store | ||
| 455 | + .create_task( | ||
| 456 | + &board.id, | ||
| 457 | + NewTask { | ||
| 458 | + title: "Task".into(), | ||
| 459 | + description: String::new(), | ||
| 460 | + column_id: column, | ||
| 461 | + tag_id: tag, | ||
| 462 | + deadline: None, | ||
| 463 | + meeting_at: None, | ||
| 464 | + assignees: Vec::new(), | ||
| 465 | + parent_id: None, | ||
| 466 | + link: None, | ||
| 467 | + }, | ||
| 468 | + "bo", | ||
| 469 | + ) | ||
| 470 | + .await | ||
| 471 | + .expect("task"); | ||
| 472 | + let id = new_attachment_id(); | ||
| 473 | + let path = blob_path(&state.config.data_dir, &id).expect("path"); | ||
| 474 | + std::fs::create_dir_all(path.parent().expect("parent")).expect("attachments dir"); | ||
| 475 | + std::fs::write(&path, bytes).expect("bytes"); | ||
| 476 | + let sha256 = hex::encode(Sha256::digest(bytes)); | ||
| 477 | + store | ||
| 478 | + .add_attachment( | ||
| 479 | + &board.id, | ||
| 480 | + &task.id, | ||
| 481 | + NewAttachment { | ||
| 482 | + id, | ||
| 483 | + name: name.into(), | ||
| 484 | + mime: mime.into(), | ||
| 485 | + size: bytes.len() as u64, | ||
| 486 | + sha256, | ||
| 487 | + uploaded_by: "bo".into(), | ||
| 488 | + }, | ||
| 489 | + ) | ||
| 490 | + .await | ||
| 491 | + .expect("attachment") | ||
| 492 | + } | ||
| 493 | +} | ||
crates/iz-web/src/main.rsmodified+2 -0
| @@ -17,8 +17,10 @@ mod directory; | |||
| 17 | mod family; | 17 | mod family; |
| 18 | mod health; | 18 | mod health; |
| 19 | mod i18n; | 19 | mod i18n; |
| 20 | +mod in_store; | ||
| 20 | mod live; | 21 | mod live; |
| 21 | mod mail; | 22 | mod mail; |
| 23 | +mod mover; | ||
| 22 | mod oidc; | 24 | mod oidc; |
| 23 | mod pages; | 25 | mod pages; |
| 24 | mod security; | 26 | mod security; |
crates/iz-web/src/mover.rsadded+418 -0
| @@ -0,0 +1,418 @@ | |||
| 1 | +//! The mover: moves attachment bytes between this disk and the Files service (`in`), in both directions. | ||
| 2 | +//! | ||
| 3 | +//! The row says where the bytes are (`local`, `in` or `moving`). Which direction runs is the setting | ||
| 4 | +//! `attachment_location`: with `in`, rows that are `local` go to `in`; with `local`, rows that are `in` come back. | ||
| 5 | +//! So a fresh upload, a switch of the setting and a restart in the middle of a migration are all the same | ||
| 6 | +//! work: the mover looks at the rows and moves what is not where the setting says. Nothing is kept in | ||
| 7 | +//! memory that a restart would lose, except the backoff of a row that failed (a restart retries at once). | ||
| 8 | +//! | ||
| 9 | +//! A move is one row at a time, with at most [`LANES`] rows in flight: | ||
| 10 | +//! 1. claim the row (`from` to `moving`) under the blob lock, so no other lane takes it; | ||
| 11 | +//! 2. copy the bytes, outside the lock (a `PUT` of the local file, or a `GET` into a staged file that is | ||
| 12 | +//! checked against the row's size and digest); | ||
| 13 | +//! 3. flip the row to its new place under the blob lock, and remove the old copy in the same critical section. | ||
| 14 | +//! | ||
| 15 | +//! The old copy is removed only after the row says the new place, so the bytes are never without a copy. A | ||
| 16 | +//! failure before the flip puts the row back where it was and keeps its old copy. A failure after the flip | ||
| 17 | +//! (the old copy's removal, or the Files copy's `DELETE`) is owed to the deleter, so it is retried until done. | ||
| 18 | +//! | ||
| 19 | +//! At boot, rows left `moving` by a crash are settled from the disk: a local file that is there is complete | ||
| 20 | +//! (files are renamed into place only when whole), so the row is `local`; otherwise the bytes are in `in`. | ||
| 21 | + | ||
| 22 | +use std::collections::HashMap; | ||
| 23 | +use std::sync::Arc; | ||
| 24 | +use std::time::{Duration, Instant}; | ||
| 25 | + | ||
| 26 | +use futures_util::StreamExt; | ||
| 27 | +use iz_core::staging::{StagedFile, blob_path, install_blob, remove_blob}; | ||
| 28 | +use iz_core::store::attachments::{Attachment, LOCATION_IN, LOCATION_LOCAL, LOCATION_MOVING}; | ||
| 29 | +use tokio::sync::{Mutex, watch}; | ||
| 30 | + | ||
| 31 | +use crate::attachments::retry_delay; | ||
| 32 | +use crate::in_store::InStore; | ||
| 33 | +use crate::state::AppState; | ||
| 34 | + | ||
| 35 | +/// Rows moved at the same time. Reason: bounds the load on this disk and on `in`. | ||
| 36 | +pub const LANES: usize = 2; | ||
| 37 | +/// How long a lane waits when it found no row to move. Reason: a new upload should be moved within seconds. | ||
| 38 | +const POLL: Duration = Duration::from_secs(2); | ||
| 39 | +/// Rows fetched per look at the candidates, so a row in backoff does not hide the others. | ||
| 40 | +const CANDIDATES: i64 = 20; | ||
| 41 | + | ||
| 42 | +/// The backoff of a row whose move failed: how many times, and when it may be tried again. | ||
| 43 | +#[derive(Clone, Copy)] | ||
| 44 | +struct Backoff { | ||
| 45 | + attempts: i64, | ||
| 46 | + not_before: Instant, | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +/// Failures of a move, as text for the log. They never reach a page. | ||
| 50 | +type MoveResult = std::result::Result<(), String>; | ||
| 51 | + | ||
| 52 | +/// Starts the mover: settles rows left moving by a crash, then runs [`LANES`] lanes until the stop flag is set. | ||
| 53 | +pub fn spawn(state: AppState, stop: watch::Receiver<bool>) { | ||
| 54 | + tokio::spawn(async move { | ||
| 55 | + recover(&state).await; | ||
| 56 | + let backoff: Arc<Mutex<HashMap<String, Backoff>>> = Arc::default(); | ||
| 57 | + let mut lanes = Vec::with_capacity(LANES); | ||
| 58 | + for _ in 0..LANES { | ||
| 59 | + lanes.push(tokio::spawn(lane( | ||
| 60 | + state.clone(), | ||
| 61 | + stop.clone(), | ||
| 62 | + backoff.clone(), | ||
| 63 | + ))); | ||
| 64 | + } | ||
| 65 | + for lane in lanes { | ||
| 66 | + let _ = lane.await; | ||
| 67 | + } | ||
| 68 | + tracing::info!("attachment mover stopped"); | ||
| 69 | + }); | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +/// Settles the rows a crash left moving. See the module comment for the rule. The copy that the rule does not | ||
| 73 | +/// keep is owed to the deleter, so a leftover Files object is removed. | ||
| 74 | +async fn recover(state: &AppState) { | ||
| 75 | + let ids = match state.store.moving_attachment_ids().await { | ||
| 76 | + Ok(ids) => ids, | ||
| 77 | + Err(error) => { | ||
| 78 | + tracing::warn!(error = %error, "reading the rows left moving failed"); | ||
| 79 | + return; | ||
| 80 | + } | ||
| 81 | + }; | ||
| 82 | + for id in ids { | ||
| 83 | + let _guard = state.blob_lock.lock().await; | ||
| 84 | + let Ok(path) = blob_path(&state.config.data_dir, &id) else { | ||
| 85 | + continue; | ||
| 86 | + }; | ||
| 87 | + let on_disk = tokio::fs::try_exists(&path).await.unwrap_or(false); | ||
| 88 | + let settled = if on_disk { LOCATION_LOCAL } else { LOCATION_IN }; | ||
| 89 | + match state | ||
| 90 | + .store | ||
| 91 | + .set_location_if(&id, LOCATION_MOVING, settled) | ||
| 92 | + .await | ||
| 93 | + { | ||
| 94 | + Ok(true) => { | ||
| 95 | + tracing::info!(attachment = %id, location = settled, "settled a move left by a crash"); | ||
| 96 | + if on_disk { | ||
| 97 | + owe(state, &id, LOCATION_IN).await; | ||
| 98 | + } | ||
| 99 | + } | ||
| 100 | + Ok(false) => {} | ||
| 101 | + Err(error) => tracing::warn!(error = %error, "settling a move left by a crash failed"), | ||
| 102 | + } | ||
| 103 | + } | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +/// One lane: move one row, then look again at once; with nothing to move, wait for [`POLL`] or the stop flag. | ||
| 107 | +async fn lane( | ||
| 108 | + state: AppState, | ||
| 109 | + mut stop: watch::Receiver<bool>, | ||
| 110 | + backoff: Arc<Mutex<HashMap<String, Backoff>>>, | ||
| 111 | +) { | ||
| 112 | + loop { | ||
| 113 | + if *stop.borrow() { | ||
| 114 | + break; | ||
| 115 | + } | ||
| 116 | + let moved = match step(&state, &backoff).await { | ||
| 117 | + Ok(moved) => moved, | ||
| 118 | + Err(reason) => { | ||
| 119 | + tracing::warn!(reason, "the attachment mover could not look for rows"); | ||
| 120 | + false | ||
| 121 | + } | ||
| 122 | + }; | ||
| 123 | + if moved { | ||
| 124 | + continue; | ||
| 125 | + } | ||
| 126 | + tokio::select! { | ||
| 127 | + () = tokio::time::sleep(POLL) => {} | ||
| 128 | + _ = stop.wait_for(|stopped| *stopped) => break, | ||
| 129 | + } | ||
| 130 | + } | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +/// Moves one row toward the place the setting names. `Ok(true)` when a row was tried (or another lane took it). | ||
| 134 | +async fn step( | ||
| 135 | + state: &AppState, | ||
| 136 | + backoff: &Mutex<HashMap<String, Backoff>>, | ||
| 137 | +) -> std::result::Result<bool, String> { | ||
| 138 | + let Some(in_store) = state.in_store.clone() else { | ||
| 139 | + // Without the Files service nothing can move: `in` cannot be reached, and nothing is copied to it. | ||
| 140 | + return Ok(false); | ||
| 141 | + }; | ||
| 142 | + let target = state | ||
| 143 | + .store | ||
| 144 | + .attachment_target() | ||
| 145 | + .await | ||
| 146 | + .map_err(|e| e.to_string())?; | ||
| 147 | + let (from, to) = if target == LOCATION_IN { | ||
| 148 | + (LOCATION_LOCAL, LOCATION_IN) | ||
| 149 | + } else { | ||
| 150 | + (LOCATION_IN, LOCATION_LOCAL) | ||
| 151 | + }; | ||
| 152 | + let candidates = state | ||
| 153 | + .store | ||
| 154 | + .attachments_in_location(from, CANDIDATES) | ||
| 155 | + .await | ||
| 156 | + .map_err(|e| e.to_string())?; | ||
| 157 | + let now = Instant::now(); | ||
| 158 | + let picked = { | ||
| 159 | + let waiting = backoff.lock().await; | ||
| 160 | + candidates.into_iter().find(|row| { | ||
| 161 | + waiting | ||
| 162 | + .get(&row.id) | ||
| 163 | + .is_none_or(|retry| retry.not_before <= now) | ||
| 164 | + }) | ||
| 165 | + }; | ||
| 166 | + let Some(row) = picked else { | ||
| 167 | + return Ok(false); | ||
| 168 | + }; | ||
| 169 | + if !claim(state, &row.id, from, LOCATION_MOVING) | ||
| 170 | + .await | ||
| 171 | + .map_err(|e| e.to_string())? | ||
| 172 | + { | ||
| 173 | + // Another lane, or a deletion, got there first. | ||
| 174 | + return Ok(true); | ||
| 175 | + } | ||
| 176 | + let result = if to == LOCATION_IN { | ||
| 177 | + move_to_in(state, &in_store, &row).await | ||
| 178 | + } else { | ||
| 179 | + move_to_local(state, &in_store, &row).await | ||
| 180 | + }; | ||
| 181 | + match result { | ||
| 182 | + Ok(()) => { | ||
| 183 | + backoff.lock().await.remove(&row.id); | ||
| 184 | + } | ||
| 185 | + Err(reason) => { | ||
| 186 | + tracing::warn!(attachment = %row.id, reason, "moving an attachment failed; retrying"); | ||
| 187 | + // The move failed before its flip, so the row goes back and keeps its copy. | ||
| 188 | + if let Err(error) = state | ||
| 189 | + .store | ||
| 190 | + .set_location_if(&row.id, LOCATION_MOVING, from) | ||
| 191 | + .await | ||
| 192 | + { | ||
| 193 | + tracing::error!(error = %error, "putting a row back after a failed move failed"); | ||
| 194 | + } | ||
| 195 | + let mut waiting = backoff.lock().await; | ||
| 196 | + let attempts = waiting.get(&row.id).map_or(0, |retry| retry.attempts) + 1; | ||
| 197 | + waiting.insert( | ||
| 198 | + row.id.clone(), | ||
| 199 | + Backoff { | ||
| 200 | + attempts, | ||
| 201 | + not_before: Instant::now() + retry_delay(attempts), | ||
| 202 | + }, | ||
| 203 | + ); | ||
| 204 | + } | ||
| 205 | + } | ||
| 206 | + Ok(true) | ||
| 207 | +} | ||
| 208 | + | ||
| 209 | +/// Flips a row from `from` to `to` under the blob lock. `true` when it did. | ||
| 210 | +async fn claim(state: &AppState, id: &str, from: &str, to: &str) -> iz_core::Result<bool> { | ||
| 211 | + let _guard = state.blob_lock.lock().await; | ||
| 212 | + state.store.set_location_if(id, from, to).await | ||
| 213 | +} | ||
| 214 | + | ||
| 215 | +/// Owes the deleter a copy of `id` in `place`. A failure to record it is logged; the copy then stays until | ||
| 216 | +/// the next move or boot settles it, which is the best a broken database allows. | ||
| 217 | +async fn owe(state: &AppState, id: &str, place: &str) { | ||
| 218 | + if let Err(error) = state.store.owe_blob_deletion(id, place).await { | ||
| 219 | + tracing::error!(error = %error, attachment = %id, place, "recording an owed copy failed"); | ||
| 220 | + } | ||
| 221 | +} | ||
| 222 | + | ||
| 223 | +/// Copies a local row to the Files service, then flips it to `in`, then removes the local file. | ||
| 224 | +async fn move_to_in(state: &AppState, in_store: &InStore, row: &Attachment) -> MoveResult { | ||
| 225 | + let path = blob_path(&state.config.data_dir, &row.id).map_err(|e| e.to_string())?; | ||
| 226 | + let put = in_store | ||
| 227 | + .put(&row.id, &path, row.size, &row.mime, &row.name, &row.sha256) | ||
| 228 | + .await; | ||
| 229 | + if let Err(error) = put { | ||
| 230 | + // A PUT that failed may still have stored the object. It is owed, so it does not outlive the row. | ||
| 231 | + owe(state, &row.id, LOCATION_IN).await; | ||
| 232 | + return Err(error.to_string()); | ||
| 233 | + } | ||
| 234 | + let guard = state.blob_lock.lock().await; | ||
| 235 | + let flipped = state | ||
| 236 | + .store | ||
| 237 | + .set_location_if(&row.id, LOCATION_MOVING, LOCATION_IN) | ||
| 238 | + .await | ||
| 239 | + .map_err(|e| e.to_string())?; | ||
| 240 | + if flipped { | ||
| 241 | + if let Err(error) = remove_blob(&state.config.data_dir, &row.id).await { | ||
| 242 | + tracing::warn!(error = %error, attachment = %row.id, "removing the local copy failed; owed"); | ||
| 243 | + owe(state, &row.id, LOCATION_LOCAL).await; | ||
| 244 | + } | ||
| 245 | + } else { | ||
| 246 | + // The row was deleted while its bytes were on their way. The deletion owed the local copy already; | ||
| 247 | + // the object just stored is owed here. | ||
| 248 | + owe(state, &row.id, LOCATION_IN).await; | ||
| 249 | + } | ||
| 250 | + drop(guard); | ||
| 251 | + Ok(()) | ||
| 252 | +} | ||
| 253 | + | ||
| 254 | +/// Copies an `in` row back to this disk, checks it against the row, flips it to `local`, then removes the | ||
| 255 | +/// Files copy. The download is staged and digested before anything is installed. | ||
| 256 | +async fn move_to_local(state: &AppState, in_store: &InStore, row: &Attachment) -> MoveResult { | ||
| 257 | + let data_dir = state.config.data_dir.as_path(); | ||
| 258 | + let staged = StagedFile::create(data_dir, row.size) | ||
| 259 | + .await | ||
| 260 | + .map_err(|e| e.to_string())?; | ||
| 261 | + let done = download(in_store, &row.id, staged).await?; | ||
| 262 | + if done.size != row.size || done.sha256 != row.sha256 { | ||
| 263 | + // The staged copy is left for the sweeper's stale-temp pass; nothing outside attachments/ is removed here. | ||
| 264 | + return Err("the Files copy is not the bytes of the row".into()); | ||
| 265 | + } | ||
| 266 | + let guard = state.blob_lock.lock().await; | ||
| 267 | + if let Err(error) = install_blob(data_dir, &row.id, &done.path).await { | ||
| 268 | + return Err(error.to_string()); | ||
| 269 | + } | ||
| 270 | + let flipped = match state | ||
| 271 | + .store | ||
| 272 | + .set_location_if(&row.id, LOCATION_MOVING, LOCATION_LOCAL) | ||
| 273 | + .await | ||
| 274 | + { | ||
| 275 | + Ok(flipped) => flipped, | ||
| 276 | + Err(error) => { | ||
| 277 | + // The local copy is installed but the row still says `in`: the copy is owed, so it is removed. | ||
| 278 | + owe(state, &row.id, LOCATION_LOCAL).await; | ||
| 279 | + return Err(error.to_string()); | ||
| 280 | + } | ||
| 281 | + }; | ||
| 282 | + if flipped { | ||
| 283 | + // The Files copy goes under the same lock as the flip, so no new move of this id can start in between. | ||
| 284 | + if let Err(error) = in_store.delete(&row.id).await { | ||
| 285 | + tracing::warn!(error = %error, attachment = %row.id, "removing the Files copy failed; owed"); | ||
| 286 | + owe(state, &row.id, LOCATION_IN).await; | ||
| 287 | + } | ||
| 288 | + } else { | ||
| 289 | + // Deleted while downloading: the deletion owed both copies. Remove the local one now, owe the other. | ||
| 290 | + if let Err(error) = remove_blob(data_dir, &row.id).await { | ||
| 291 | + tracing::warn!(error = %error, "removing the local copy of a deleted row failed; owed"); | ||
| 292 | + owe(state, &row.id, LOCATION_LOCAL).await; | ||
| 293 | + } | ||
| 294 | + owe(state, &row.id, LOCATION_IN).await; | ||
| 295 | + } | ||
| 296 | + drop(guard); | ||
| 297 | + Ok(()) | ||
| 298 | +} | ||
| 299 | + | ||
| 300 | +/// Reads the whole object into `staged`. On any failure the staged file is removed and the reason is returned. | ||
| 301 | +async fn download( | ||
| 302 | + in_store: &InStore, | ||
| 303 | + id: &str, | ||
| 304 | + mut staged: StagedFile, | ||
| 305 | +) -> std::result::Result<iz_core::staging::Staged, String> { | ||
| 306 | + let response = match in_store.get(id, None).await { | ||
| 307 | + Ok(response) => response, | ||
| 308 | + Err(error) => { | ||
| 309 | + staged.abort().await; | ||
| 310 | + return Err(error.to_string()); | ||
| 311 | + } | ||
| 312 | + }; | ||
| 313 | + let mut chunks = response.bytes_stream(); | ||
| 314 | + while let Some(chunk) = chunks.next().await { | ||
| 315 | + let written = match chunk { | ||
| 316 | + Ok(bytes) => staged.write(&bytes).await.map_err(|e| e.to_string()), | ||
| 317 | + Err(error) => Err(error.to_string()), | ||
| 318 | + }; | ||
| 319 | + if let Err(reason) = written { | ||
| 320 | + staged.abort().await; | ||
| 321 | + return Err(reason); | ||
| 322 | + } | ||
| 323 | + } | ||
| 324 | + staged.finish().await.map_err(|e| e.to_string()) | ||
| 325 | +} | ||
| 326 | + | ||
| 327 | +#[cfg(test)] | ||
| 328 | +mod tests { | ||
| 329 | + use std::sync::atomic::{AtomicBool, Ordering}; | ||
| 330 | + | ||
| 331 | + use iz_core::staging::blob_path; | ||
| 332 | + use iz_core::store::attachments::SETTING_LOCATION; | ||
| 333 | + | ||
| 334 | + use super::*; | ||
| 335 | + use crate::boot::test_state; | ||
| 336 | + use crate::in_store::test_support::{fake_in, reply, seed_attachment}; | ||
| 337 | + | ||
| 338 | + #[tokio::test] | ||
| 339 | + async fn a_failed_put_keeps_the_local_copy_and_the_row_local() { | ||
| 340 | + let (_dir, mut state) = test_state().await; | ||
| 341 | + state | ||
| 342 | + .store | ||
| 343 | + .set_setting(SETTING_LOCATION, LOCATION_IN) | ||
| 344 | + .await | ||
| 345 | + .expect("target"); | ||
| 346 | + let base = fake_in(|_| reply(500, b"")).await; | ||
| 347 | + state.in_store = Some(Arc::new(InStore::for_tests(&base))); | ||
| 348 | + let row = seed_attachment(&state, "a.png", "image/png", b"pixels").await; | ||
| 349 | + let backoff = Mutex::new(HashMap::new()); | ||
| 350 | + | ||
| 351 | + assert!(step(&state, &backoff).await.expect("a row was tried")); | ||
| 352 | + | ||
| 353 | + let path = blob_path(&state.config.data_dir, &row.id).expect("path"); | ||
| 354 | + assert_eq!(std::fs::read(&path).expect("local copy"), b"pixels"); | ||
| 355 | + assert_eq!( | ||
| 356 | + state | ||
| 357 | + .store | ||
| 358 | + .attachment_location(&row.id) | ||
| 359 | + .await | ||
| 360 | + .expect("row") | ||
| 361 | + .as_deref(), | ||
| 362 | + Some(LOCATION_LOCAL) | ||
| 363 | + ); | ||
| 364 | + assert!( | ||
| 365 | + backoff.lock().await.contains_key(&row.id), | ||
| 366 | + "the failure backs off" | ||
| 367 | + ); | ||
| 368 | + } | ||
| 369 | + | ||
| 370 | + #[tokio::test] | ||
| 371 | + async fn a_move_removes_the_local_copy_after_the_row_says_in() { | ||
| 372 | + let (_dir, mut state) = test_state().await; | ||
| 373 | + state | ||
| 374 | + .store | ||
| 375 | + .set_setting(SETTING_LOCATION, LOCATION_IN) | ||
| 376 | + .await | ||
| 377 | + .expect("target"); | ||
| 378 | + let row = seed_attachment(&state, "a.png", "image/png", b"pixels").await; | ||
| 379 | + let path = blob_path(&state.config.data_dir, &row.id).expect("path"); | ||
| 380 | + let local_then = Arc::new(AtomicBool::new(false)); | ||
| 381 | + let body_ok = Arc::new(AtomicBool::new(false)); | ||
| 382 | + let (local_flag, body_flag) = (local_then.clone(), body_ok.clone()); | ||
| 383 | + let (sha, size, source) = (row.sha256.clone(), row.size, path.clone()); | ||
| 384 | + let base = fake_in(move |req| { | ||
| 385 | + if req.method != "PUT" { | ||
| 386 | + return reply(404, b""); | ||
| 387 | + } | ||
| 388 | + // The local copy is still there while the bytes are sent; the row is changed afterwards. | ||
| 389 | + local_flag.store(source.exists(), Ordering::SeqCst); | ||
| 390 | + body_flag.store(req.body == b"pixels", Ordering::SeqCst); | ||
| 391 | + let answer = format!( | ||
| 392 | + "{{\"external_id\":\"x\",\"size\":{size},\"sha256\":\"{sha}\",\"content_type\":\"image/png\",\"created_at\":\"now\"}}" | ||
| 393 | + ); | ||
| 394 | + reply(201, answer.as_bytes()) | ||
| 395 | + }) | ||
| 396 | + .await; | ||
| 397 | + state.in_store = Some(Arc::new(InStore::for_tests(&base))); | ||
| 398 | + let backoff = Mutex::new(HashMap::new()); | ||
| 399 | + | ||
| 400 | + assert!(step(&state, &backoff).await.expect("a row was moved")); | ||
| 401 | + | ||
| 402 | + assert!( | ||
| 403 | + local_then.load(Ordering::SeqCst), | ||
| 404 | + "the local copy existed during the PUT" | ||
| 405 | + ); | ||
| 406 | + assert!(body_ok.load(Ordering::SeqCst), "the PUT carried the bytes"); | ||
| 407 | + assert_eq!( | ||
| 408 | + state | ||
| 409 | + .store | ||
| 410 | + .attachment_location(&row.id) | ||
| 411 | + .await | ||
| 412 | + .expect("row") | ||
| 413 | + .as_deref(), | ||
| 414 | + Some(LOCATION_IN) | ||
| 415 | + ); | ||
| 416 | + assert!(!path.exists(), "the local copy goes once the row says in"); | ||
| 417 | + } | ||
| 418 | +} | ||
crates/iz-web/src/oidc.rsmodified+17 -9
| @@ -213,7 +213,8 @@ pub struct OidcClient { | |||
| 213 | stream_http: reqwest::Client, | 213 | stream_http: reqwest::Client, |
| 214 | discovery: Mutex<Option<(Instant, Arc<Discovery>)>>, | 214 | discovery: Mutex<Option<(Instant, Arc<Discovery>)>>, |
| 215 | keys: Mutex<KeyCache>, | 215 | keys: Mutex<KeyCache>, |
| 216 | - service: Mutex<Option<(Instant, String)>>, | 216 | + /// Client-credentials tokens by `(audience, scope)`. Each target has its own entry. |
| 217 | + service: Mutex<HashMap<(String, String), (Instant, String)>>, | ||
| 217 | } | 218 | } |
| 218 | 219 | ||
| 219 | #[derive(Default)] | 220 | #[derive(Default)] |
| @@ -255,7 +256,7 @@ impl OidcClient { | |||
| 255 | stream_http, | 256 | stream_http, |
| 256 | discovery: Mutex::new(None), | 257 | discovery: Mutex::new(None), |
| 257 | keys: Mutex::new(KeyCache::default()), | 258 | keys: Mutex::new(KeyCache::default()), |
| 258 | - service: Mutex::new(None), | 259 | + service: Mutex::new(HashMap::new()), |
| 259 | }) | 260 | }) |
| 260 | } | 261 | } |
| 261 | 262 | ||
| @@ -417,11 +418,18 @@ impl OidcClient { | |||
| 417 | self.post_token(&discovery.token_endpoint, &form).await | 418 | self.post_token(&discovery.token_endpoint, &form).await |
| 418 | } | 419 | } |
| 419 | 420 | ||
| 420 | - /// A client-credentials token for `scope` and `audience`, cached until 60 seconds before it | 421 | + /// The client-credentials token for the directory at `im` (`aud = im`, `directory.read`). |
| 421 | - /// expires (contracts.md 2.6). | ||
| 422 | pub async fn service_token(&self) -> ImResult<String> { | 422 | pub async fn service_token(&self) -> ImResult<String> { |
| 423 | - let mut slot = self.service.lock().await; | 423 | + self.client_token(IM_AUDIENCE, DIRECTORY_SCOPE).await |
| 424 | - if let Some((until, token)) = slot.as_ref() | 424 | + } |
| 425 | + | ||
| 426 | + /// A client-credentials token for `scope` at the family service `audience`, cached until 60 seconds | ||
| 427 | + /// before it expires (contracts.md 2.6). Each `(audience, scope)` pair has its own cache entry, so the | ||
| 428 | + /// token for `in` never replaces the one for `im`. | ||
| 429 | + pub async fn client_token(&self, audience: &str, scope: &str) -> ImResult<String> { | ||
| 430 | + let key = (audience.to_owned(), scope.to_owned()); | ||
| 431 | + let mut slots = self.service.lock().await; | ||
| 432 | + if let Some((until, token)) = slots.get(&key) | ||
| 425 | && Instant::now() < *until | 433 | && Instant::now() < *until |
| 426 | { | 434 | { |
| 427 | return Ok(token.clone()); | 435 | return Ok(token.clone()); |
| @@ -429,8 +437,8 @@ impl OidcClient { | |||
| 429 | let discovery = self.discovery().await?; | 437 | let discovery = self.discovery().await?; |
| 430 | let form = [ | 438 | let form = [ |
| 431 | ("grant_type", "client_credentials"), | 439 | ("grant_type", "client_credentials"), |
| 432 | - ("scope", DIRECTORY_SCOPE), | 440 | + ("scope", scope), |
| 433 | - ("audience", IM_AUDIENCE), | 441 | + ("audience", audience), |
| 434 | ]; | 442 | ]; |
| 435 | let response = self.post_token(&discovery.token_endpoint, &form).await?; | 443 | let response = self.post_token(&discovery.token_endpoint, &form).await?; |
| 436 | let token = response | 444 | let token = response |
| @@ -439,7 +447,7 @@ impl OidcClient { | |||
| 439 | .ok_or_else(|| ImError::BadResponse("the token answer has no access token".into()))?; | 447 | .ok_or_else(|| ImError::BadResponse("the token answer has no access token".into()))?; |
| 440 | let lifetime = Duration::from_secs(response.expires_in.unwrap_or(0)); | 448 | let lifetime = Duration::from_secs(response.expires_in.unwrap_or(0)); |
| 441 | let until = Instant::now() + lifetime.saturating_sub(SERVICE_TOKEN_MARGIN); | 449 | let until = Instant::now() + lifetime.saturating_sub(SERVICE_TOKEN_MARGIN); |
| 442 | - *slot = Some((until, token.clone())); | 450 | + slots.insert(key, (until, token.clone())); |
| 443 | Ok(token) | 451 | Ok(token) |
| 444 | } | 452 | } |
| 445 | 453 | ||
crates/iz-web/src/pages/admin.rsmodified+1 -0
| @@ -55,6 +55,7 @@ pub fn notice_text(lang: Lang, code: &str, queued: Option<&str>) -> Option<Strin | |||
| 55 | "retried" => t(lang, K::NoticeRetried).to_owned(), | 55 | "retried" => t(lang, K::NoticeRetried).to_owned(), |
| 56 | "role_set" => structure_t(lang, StructureK::NoticeRoleSet).to_owned(), | 56 | "role_set" => structure_t(lang, StructureK::NoticeRoleSet).to_owned(), |
| 57 | "limits" => structure_t(lang, StructureK::NoticeLimitsSaved).to_owned(), | 57 | "limits" => structure_t(lang, StructureK::NoticeLimitsSaved).to_owned(), |
| 58 | + "storage" => structure_t(lang, StructureK::NoticeStorageSaved).to_owned(), | ||
| 58 | "tag_added" | "tag_renamed" | "tag_coloured" | "tag_deleted" | "tag_moved" => { | 59 | "tag_added" | "tag_renamed" | "tag_coloured" | "tag_deleted" | "tag_moved" => { |
| 59 | return crate::pages::tags::tag_notice(lang, code); | 60 | return crate::pages::tags::tag_notice(lang, code); |
| 60 | } | 61 | } |
crates/iz-web/src/pages/files.rsmodified+48 -7
| @@ -24,7 +24,7 @@ use iz_core::slides::{Slide, read_deck}; | |||
| 24 | use iz_core::sniff::sniff; | 24 | use iz_core::sniff::sniff; |
| 25 | use iz_core::staging::{StagedFile, blob_path, install_blob, remove_blob}; | 25 | use iz_core::staging::{StagedFile, blob_path, install_blob, remove_blob}; |
| 26 | use iz_core::store::attachments::{ | 26 | use iz_core::store::attachments::{ |
| 27 | - Attachment, NewAttachment, Policy, clean_name, extension_allowed, extension_of, | 27 | + Attachment, LOCATION_IN, NewAttachment, Policy, clean_name, extension_allowed, extension_of, |
| 28 | new_attachment_id, | 28 | new_attachment_id, |
| 29 | }; | 29 | }; |
| 30 | use jiff::tz::TimeZone; | 30 | use jiff::tz::TimeZone; |
| @@ -35,21 +35,25 @@ use topcoat::context::{Cx, app_context}; | |||
| 35 | use topcoat::router::content::Form; | 35 | use topcoat::router::content::Form; |
| 36 | use topcoat::router::content::multipart::{Field, Multipart}; | 36 | use topcoat::router::content::multipart::{Field, Multipart}; |
| 37 | use topcoat::router::error::{forbidden, see_other}; | 37 | use topcoat::router::error::{forbidden, see_other}; |
| 38 | +use topcoat::router::request::headers; | ||
| 38 | use topcoat::router::response::Response; | 39 | use topcoat::router::response::Response; |
| 39 | -use topcoat::router::{path_param_segment, route}; | 40 | +use topcoat::router::{StatusCode, path_param_segment, route}; |
| 40 | use topcoat::view::view; | 41 | use topcoat::view::view; |
| 41 | 42 | ||
| 42 | use crate::auth::{ | 43 | use crate::auth::{ |
| 43 | CurrentMember, Need, percent_encode, query_param, require_csrf, require_role, safe_next, | 44 | CurrentMember, Need, percent_encode, query_param, require_csrf, require_role, safe_next, |
| 44 | }; | 45 | }; |
| 45 | use crate::i18n::lang; | 46 | use crate::i18n::lang; |
| 47 | +use crate::i18n::shell::{K as ShellK, t as shell_t}; | ||
| 46 | use crate::i18n::task::{K, t}; | 48 | use crate::i18n::task::{K, t}; |
| 47 | use crate::pages::board::{BoardPage, the_board}; | 49 | use crate::pages::board::{BoardPage, the_board}; |
| 48 | use crate::pages::task::{Draft, FileRow, back, bump, core_err, local_text, modal_url, refuse}; | 50 | use crate::pages::task::{Draft, FileRow, back, bump, core_err, local_text, modal_url, refuse}; |
| 49 | -use crate::serve::{ByteAnswer, ByteSource, Disposition, inline_safe, serve_file}; | 51 | +use crate::serve::{ |
| 52 | + ByteSource, Disposition, inline_safe, into_response, serve_local, serve_remote, | ||
| 53 | +}; | ||
| 50 | use crate::state::AppState; | 54 | use crate::state::AppState; |
| 51 | use crate::views::files::file_page; | 55 | use crate::views::files::file_page; |
| 52 | -use crate::views::{ViewerInfo, respond, shell}; | 56 | +use crate::views::{ViewerInfo, message_page, respond, shell}; |
| 53 | 57 | ||
| 54 | /// Longest text field of the upload form (the csrf token, the return path), in bytes. | 58 | /// Longest text field of the upload form (the csrf token, the return path), in bytes. |
| 55 | const FIELD_MAX_BYTES: usize = 2048; | 59 | const FIELD_MAX_BYTES: usize = 2048; |
| @@ -210,7 +214,11 @@ pub async fn load_view( | |||
| 210 | ) -> Result<FileView> { | 214 | ) -> Result<FileView> { |
| 211 | let path = blob_path(&state.config.data_dir, &attachment.id)?; | 215 | let path = blob_path(&state.config.data_dir, &attachment.id)?; |
| 212 | let kind = kind_of(attachment); | 216 | let kind = kind_of(attachment); |
| 217 | + // A parser reads the bytes from this disk. A file that is only in the Files service cannot be parsed here, so | ||
| 218 | + // the viewer says it cannot show it. Images, media and PDFs are shown by the byte route, which proxies. | ||
| 219 | + let on_disk = tokio::fs::try_exists(&path).await.unwrap_or(false); | ||
| 213 | let body = match kind { | 220 | let body = match kind { |
| 221 | + Kind::Text | Kind::Workbook | Kind::Csv | Kind::Deck if !on_disk => ViewBody::Refused, | ||
| 214 | Kind::Image => ViewBody::Image, | 222 | Kind::Image => ViewBody::Image, |
| 215 | Kind::Video => ViewBody::Video, | 223 | Kind::Video => ViewBody::Video, |
| 216 | Kind::Audio => ViewBody::Audio, | 224 | Kind::Audio => ViewBody::Audio, |
| @@ -579,9 +587,11 @@ async fn delete_file(cx: &Cx, form: Option<Form<DeleteForm>>) -> Result<Response | |||
| 579 | } | 587 | } |
| 580 | 588 | ||
| 581 | /// `GET /files/{id}`: the bytes of a file, through the byte rules: shown when the type allows it, saved as a file | 589 | /// `GET /files/{id}`: the bytes of a file, through the byte rules: shown when the type allows it, saved as a file |
| 582 | -/// otherwise and always with `?dl=1`. | 590 | +/// otherwise and always with `?dl=1`. The bytes come from this disk when the row says so, and from the Files |
| 591 | +/// service otherwise; the Files answer is proxied with this server's headers only. When neither can answer, the | ||
| 592 | +/// page says so with `503`. | ||
| 583 | #[route(GET "/files/{id}")] | 593 | #[route(GET "/files/{id}")] |
| 584 | -async fn file_bytes(cx: &Cx) -> Result<ByteAnswer> { | 594 | +async fn file_bytes(cx: &Cx) -> Result<Response> { |
| 585 | let state = app_context::<AppState>(cx); | 595 | let state = app_context::<AppState>(cx); |
| 586 | require_role(cx, Need::Viewer).await?; | 596 | require_role(cx, Need::Viewer).await?; |
| 587 | let id = path_param_segment(cx, "id").to_owned(); | 597 | let id = path_param_segment(cx, "id").to_owned(); |
| @@ -605,7 +615,37 @@ async fn file_bytes(cx: &Cx) -> Result<ByteAnswer> { | |||
| 605 | } else { | 615 | } else { |
| 606 | Disposition::Inline | 616 | Disposition::Inline |
| 607 | }; | 617 | }; |
| 608 | - serve_file(cx, &source, disposition).await | 618 | + let request = headers(cx); |
| 619 | + if attachment.location != LOCATION_IN | ||
| 620 | + && let Some(answer) = serve_local(request, &source, disposition).await? | ||
| 621 | + { | ||
| 622 | + return Ok(into_response(answer)); | ||
| 623 | + } | ||
| 624 | + if let Some(in_store) = state.in_store.as_deref() { | ||
| 625 | + match serve_remote(request, &source, disposition, in_store, &attachment.id).await { | ||
| 626 | + Ok(answer) => return Ok(into_response(answer)), | ||
| 627 | + Err(error) => tracing::warn!( | ||
| 628 | + error = %error, | ||
| 629 | + attachment = %attachment.id, | ||
| 630 | + "the Files service could not send an attachment" | ||
| 631 | + ), | ||
| 632 | + } | ||
| 633 | + } | ||
| 634 | + unavailable_page(cx).await | ||
| 635 | +} | ||
| 636 | + | ||
| 637 | +/// The page for a file that neither this disk nor the Files service can send now: `503` in the usual shell. | ||
| 638 | +async fn unavailable_page(cx: &Cx) -> Result<Response> { | ||
| 639 | + let lang = lang(cx, None); | ||
| 640 | + let document = view! { | ||
| 641 | + cx => | ||
| 642 | + shell(title: shell_t(lang, ShellK::FilesUnavailableTitle), lang: lang, viewer: None, page_script: None, | ||
| 643 | + (StatusCode::SERVICE_UNAVAILABLE) | ||
| 644 | + message_page(lang: lang, title: ShellK::FilesUnavailableTitle, | ||
| 645 | + body: ShellK::FilesUnavailableBody, detail: None) | ||
| 646 | + ) | ||
| 647 | + }; | ||
| 648 | + respond(cx, document).await | ||
| 609 | } | 649 | } |
| 610 | 650 | ||
| 611 | /// The viewer's own page, `GET /tasks/{key}/files/{id}/view`. The file must belong to the task with `key`. | 651 | /// The viewer's own page, `GET /tasks/{key}/files/{id}/view`. The file must belong to the task with `key`. |
| @@ -661,6 +701,7 @@ mod tests { | |||
| 661 | sha256: "0".repeat(64), | 701 | sha256: "0".repeat(64), |
| 662 | uploaded_by: "u".into(), | 702 | uploaded_by: "u".into(), |
| 663 | created_at: "x".into(), | 703 | created_at: "x".into(), |
| 704 | + location: "local".into(), | ||
| 664 | } | 705 | } |
| 665 | } | 706 | } |
| 666 | 707 | ||
crates/iz-web/src/pages/settings.rsmodified+81 -3
| @@ -29,11 +29,14 @@ use crate::pages::admin::{CsrfForm, REFUSED, back, notice_text, user_text, viewe | |||
| 29 | use crate::pages::board::the_board; | 29 | use crate::pages::board::the_board; |
| 30 | use crate::state::AppState; | 30 | use crate::state::AppState; |
| 31 | use crate::views::admin::{SenderForm, SettingsView, settings_content}; | 31 | use crate::views::admin::{SenderForm, SettingsView, settings_content}; |
| 32 | -use crate::views::structure::{MemberRow, ServerInfo}; | 32 | +use crate::views::structure::{MemberRow, ServerInfo, StorageInfo}; |
| 33 | use crate::views::{ViewerInfo, respond, shell}; | 33 | use crate::views::{ViewerInfo, respond, shell}; |
| 34 | use iz_core::authz::Role; | 34 | use iz_core::authz::Role; |
| 35 | use iz_core::limits::{ATTACHMENT_LIMIT_MIB_MAX, ATTACHMENT_LIMIT_MIB_MIN}; | 35 | use iz_core::limits::{ATTACHMENT_LIMIT_MIB_MAX, ATTACHMENT_LIMIT_MIB_MIN}; |
| 36 | -use iz_core::store::attachments::{SETTING_EXTENSIONS, SETTING_LIMIT_MIB, parse_extensions}; | 36 | +use iz_core::store::attachments::{ |
| 37 | + LOCATION_IN, LOCATION_LOCAL, SETTING_EXTENSIONS, SETTING_LIMIT_MIB, SETTING_LOCATION, | ||
| 38 | + parse_extensions, | ||
| 39 | +}; | ||
| 37 | use iz_core::store::audit::AuditEntry; | 40 | use iz_core::store::audit::AuditEntry; |
| 38 | use topcoat::router::path_param_segment; | 41 | use topcoat::router::path_param_segment; |
| 39 | 42 | ||
| @@ -104,6 +107,7 @@ async fn settings_view( | |||
| 104 | let mut sender = form.unwrap_or_else(|| sender_form(&stored)); | 107 | let mut sender = form.unwrap_or_else(|| sender_form(&stored)); |
| 105 | sender.password_set = stored.password_set; | 108 | sender.password_set = stored.password_set; |
| 106 | let policy = state.store.policy().await?; | 109 | let policy = state.store.policy().await?; |
| 110 | + let storage = storage_info(state).await?; | ||
| 107 | let members = state | 111 | let members = state |
| 108 | .store | 112 | .store |
| 109 | .list_members() | 113 | .list_members() |
| @@ -132,11 +136,13 @@ async fn settings_view( | |||
| 132 | limit_mib, | 136 | limit_mib, |
| 133 | extensions, | 137 | extensions, |
| 134 | server: server_info(state).await?, | 138 | server: server_info(state).await?, |
| 139 | + storage, | ||
| 135 | }) | 140 | }) |
| 136 | } | 141 | } |
| 137 | 142 | ||
| 138 | /// The read-only server facts of the settings page. | 143 | /// The read-only server facts of the settings page. |
| 139 | async fn server_info(state: &AppState) -> Result<ServerInfo> { | 144 | async fn server_info(state: &AppState) -> Result<ServerInfo> { |
| 145 | + let storage_in = state.store.attachment_target().await? == LOCATION_IN; | ||
| 140 | Ok(ServerInfo { | 146 | Ok(ServerInfo { |
| 141 | base_url: state.config.base_url.clone(), | 147 | base_url: state.config.base_url.clone(), |
| 142 | listen: state.config.listen.to_string(), | 148 | listen: state.config.listen.to_string(), |
| @@ -145,10 +151,35 @@ async fn server_info(state: &AppState) -> Result<ServerInfo> { | |||
| 145 | schema: state.store.schema_version().await?, | 151 | schema: state.store.schema_version().await?, |
| 146 | build: env!("IZ_BUILD_SHA").to_owned(), | 152 | build: env!("IZ_BUILD_SHA").to_owned(), |
| 147 | sign_in: state.oidc.is_some(), | 153 | sign_in: state.oidc.is_some(), |
| 148 | - storage_in: state.config.in_store.enabled, | 154 | + storage_in, |
| 149 | }) | 155 | }) |
| 150 | } | 156 | } |
| 151 | 157 | ||
| 158 | +/// The attachment storage form: the place the admin chose, `local` or `in`. | ||
| 159 | +#[derive(Debug, Default, Deserialize)] | ||
| 160 | +#[serde(default)] | ||
| 161 | +struct StorageSubmit { | ||
| 162 | + csrf: String, | ||
| 163 | + location: String, | ||
| 164 | +} | ||
| 165 | + | ||
| 166 | +/// The storage section's data: the chosen place, whether the Files service is set up, and the row counts. | ||
| 167 | +async fn storage_info(state: &AppState) -> Result<StorageInfo> { | ||
| 168 | + let mut info = StorageInfo { | ||
| 169 | + target: state.store.attachment_target().await?, | ||
| 170 | + in_available: state.in_store.is_some(), | ||
| 171 | + ..StorageInfo::default() | ||
| 172 | + }; | ||
| 173 | + for (location, count) in state.store.attachment_location_counts().await? { | ||
| 174 | + match location.as_str() { | ||
| 175 | + LOCATION_LOCAL => info.local = count, | ||
| 176 | + LOCATION_IN => info.in_files = count, | ||
| 177 | + _ => info.moving += count, | ||
| 178 | + } | ||
| 179 | + } | ||
| 180 | + Ok(info) | ||
| 181 | +} | ||
| 182 | + | ||
| 152 | /// The members-and-roles form: the role word of one member. | 183 | /// The members-and-roles form: the role word of one member. |
| 153 | #[derive(Debug, Default, Deserialize)] | 184 | #[derive(Debug, Default, Deserialize)] |
| 154 | #[serde(default)] | 185 | #[serde(default)] |
| @@ -459,6 +490,53 @@ async fn save_role(cx: &Cx, form: Option<Form<RoleSubmit>>) -> Result<Response> | |||
| 459 | } | 490 | } |
| 460 | } | 491 | } |
| 461 | 492 | ||
| 493 | +/// `POST /settings/attachments`: where attachments are kept. Saving only records the choice; the mover brings the | ||
| 494 | +/// files over in the background. `in` needs the Files service to be set up on this server. | ||
| 495 | +#[route(POST "/settings/attachments")] | ||
| 496 | +async fn save_storage(cx: &Cx, form: Option<Form<StorageSubmit>>) -> Result<Response> { | ||
| 497 | + let state = app_context::<AppState>(cx); | ||
| 498 | + let form = form.map(|Form(form)| form).unwrap_or_default(); | ||
| 499 | + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; | ||
| 500 | + let language = lang(cx, me.member.locale_override.as_deref()); | ||
| 501 | + let outcome: iz_core::Result<&str> = match form.location.as_str() { | ||
| 502 | + LOCATION_LOCAL => Ok(LOCATION_LOCAL), | ||
| 503 | + LOCATION_IN if state.in_store.is_some() => Ok(LOCATION_IN), | ||
| 504 | + LOCATION_IN => Err(iz_core::Error::Invalid( | ||
| 505 | + "the Files service is not set up on this server".into(), | ||
| 506 | + )), | ||
| 507 | + _ => Err(iz_core::Error::Invalid( | ||
| 508 | + "choose this server or the Files service".into(), | ||
| 509 | + )), | ||
| 510 | + }; | ||
| 511 | + let outcome = match outcome { | ||
| 512 | + Ok(place) => state.store.set_setting(SETTING_LOCATION, place).await, | ||
| 513 | + Err(error) => Err(error), | ||
| 514 | + }; | ||
| 515 | + match outcome { | ||
| 516 | + Ok(()) => { | ||
| 517 | + state | ||
| 518 | + .store | ||
| 519 | + .audit(AuditEntry { | ||
| 520 | + actor: Some(&me.member.sub), | ||
| 521 | + actor_kind: "admin", | ||
| 522 | + action: "attachments.location", | ||
| 523 | + target_kind: "settings", | ||
| 524 | + target_id: None, | ||
| 525 | + ip: None, | ||
| 526 | + data: serde_json::json!({ "location": form.location }), | ||
| 527 | + }) | ||
| 528 | + .await; | ||
| 529 | + state.live.bump(&Topic::Admin(AdminSection::Settings)); | ||
| 530 | + back("/settings?notice=storage") | ||
| 531 | + } | ||
| 532 | + Err(error) => { | ||
| 533 | + let message = user_text(error)?; | ||
| 534 | + let page = settings_view(state, language, None, None, Some(message)).await?; | ||
| 535 | + render(cx, &me, page, REFUSED).await | ||
| 536 | + } | ||
| 537 | + } | ||
| 538 | +} | ||
| 539 | + | ||
| 462 | /// `POST /settings/limits`: the attachment size (1 to 500 MiB) and the allowed extensions. | 540 | /// `POST /settings/limits`: the attachment size (1 to 500 MiB) and the allowed extensions. |
| 463 | #[route(POST "/settings/limits")] | 541 | #[route(POST "/settings/limits")] |
| 464 | async fn save_limits(cx: &Cx, form: Option<Form<LimitsSubmit>>) -> Result<Response> { | 542 | async fn save_limits(cx: &Cx, form: Option<Form<LimitsSubmit>>) -> Result<Response> { |
crates/iz-web/src/serve.rsmodified+266 -59
| @@ -17,6 +17,7 @@ use std::io::{self, SeekFrom}; | |||
| 17 | use std::path::Path; | 17 | use std::path::Path; |
| 18 | 18 | ||
| 19 | use bytes::Bytes; | 19 | use bytes::Bytes; |
| 20 | +use futures_util::StreamExt; | ||
| 20 | use http::header::{ | 21 | use http::header::{ |
| 21 | ACCEPT_RANGES, CACHE_CONTROL, CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_RANGE, | 22 | ACCEPT_RANGES, CACHE_CONTROL, CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_RANGE, |
| 22 | CONTENT_SECURITY_POLICY, CONTENT_TYPE, ETAG, IF_NONE_MATCH, IF_RANGE, RANGE, | 23 | CONTENT_SECURITY_POLICY, CONTENT_TYPE, ETAG, IF_NONE_MATCH, IF_RANGE, RANGE, |
| @@ -25,11 +26,11 @@ use http::header::{ | |||
| 25 | use http_body::Frame; | 26 | use http_body::Frame; |
| 26 | use http_body_util::StreamBody; | 27 | use http_body_util::StreamBody; |
| 27 | use tokio::io::{AsyncReadExt, AsyncSeekExt}; | 28 | use tokio::io::{AsyncReadExt, AsyncSeekExt}; |
| 28 | -use topcoat::Result; | 29 | +use topcoat::router::response::Response; |
| 29 | -use topcoat::context::Cx; | ||
| 30 | -use topcoat::router::request::headers; | ||
| 31 | use topcoat::router::{Body, HeaderMap, HeaderName, HeaderValue, StatusCode}; | 30 | use topcoat::router::{Body, HeaderMap, HeaderName, HeaderValue, StatusCode}; |
| 32 | 31 | ||
| 32 | +use crate::in_store::{InError, InResult, InStore}; | ||
| 33 | + | ||
| 33 | /// What a browser may do with a byte response: show it in the page, or save it. | 34 | /// What a browser may do with a byte response: show it in the page, or save it. |
| 34 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] | 35 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 35 | pub enum Disposition { | 36 | pub enum Disposition { |
| @@ -57,9 +58,17 @@ pub struct ByteSource<'a> { | |||
| 57 | pub name: &'a str, | 58 | pub name: &'a str, |
| 58 | } | 59 | } |
| 59 | 60 | ||
| 60 | -/// The status, headers and body of a byte response. Handlers return it as they are. | 61 | +/// The status, headers and body of a byte response. |
| 61 | pub type ByteAnswer = (StatusCode, HeaderMap, Body); | 62 | pub type ByteAnswer = (StatusCode, HeaderMap, Body); |
| 62 | 63 | ||
| 64 | +/// Turns a byte answer into the response a handler returns. | ||
| 65 | +pub fn into_response((status, headers, body): ByteAnswer) -> Response { | ||
| 66 | + let mut response = http::Response::new(body); | ||
| 67 | + *response.status_mut() = status; | ||
| 68 | + *response.headers_mut() = headers; | ||
| 69 | + response | ||
| 70 | +} | ||
| 71 | + | ||
| 63 | /// `Content-Security-Policy` of every byte response. The sandbox makes the document opaque, and | 72 | /// `Content-Security-Policy` of every byte response. The sandbox makes the document opaque, and |
| 64 | /// `default-src 'none'` stops it from loading anything but its own image, media or style. Only a page of this | 73 | /// `default-src 'none'` stops it from loading anything but its own image, media or style. Only a page of this |
| 65 | /// origin may frame the bytes (the viewer). | 74 | /// origin may frame the bytes (the viewer). |
| @@ -282,95 +291,201 @@ fn insert(headers: &mut HeaderMap, name: http::HeaderName, value: &str) { | |||
| 282 | } | 291 | } |
| 283 | } | 292 | } |
| 284 | 293 | ||
| 285 | -/// The `416` answer: no body, and the length the client may ask again within. | 294 | +/// The bytes a `200` or `206` sends: `length` bytes from `start`. |
| 286 | -fn unsatisfiable(etag: &str, len: u64, mime: &str) -> ByteAnswer { | 295 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 287 | - let mut headers = common_headers(etag, mime); | 296 | +pub struct Span { |
| 288 | - insert(&mut headers, CONTENT_RANGE, &format!("bytes */{len}")); | 297 | + /// First byte, from the start of the file. |
| 289 | - (StatusCode::RANGE_NOT_SATISFIABLE, headers, Body::empty()) | 298 | + pub start: u64, |
| 299 | + /// Number of bytes. | ||
| 300 | + pub length: u64, | ||
| 301 | + /// Whether the answer is a `206` for one range (the upstream must then answer a range too). | ||
| 302 | + pub ranged: bool, | ||
| 290 | } | 303 | } |
| 291 | 304 | ||
| 292 | -/// Sends the bytes of `source` for the request in `cx`. | 305 | +/// The status and headers of a byte answer, and the bytes it sends. The headers are made here, from the row: |
| 293 | -/// | 306 | +/// nothing of the bytes' origin is copied into them. |
| 294 | -/// `disposition` is the caller's wish. It becomes [`Disposition::Attachment`] unless the type is in | 307 | +#[derive(Debug)] |
| 295 | -/// [`inline_safe`]. The body streams from the file from the first byte the answer needs. A file that cannot be | 308 | +pub struct Plan { |
| 296 | -/// opened is an error, which the router answers as a `500`: the row names bytes that are not there. | 309 | + /// The status of the answer. |
| 297 | -pub async fn serve_file( | 310 | + pub status: StatusCode, |
| 298 | - cx: &Cx, | 311 | + /// The headers of the answer. |
| 299 | - source: &ByteSource<'_>, | 312 | + pub headers: HeaderMap, |
| 300 | - disposition: Disposition, | 313 | + /// The bytes to send, or `None` when the answer has no body (`304`, `416`). |
| 301 | -) -> Result<ByteAnswer> { | 314 | + pub span: Option<Span>, |
| 302 | - let request = headers(cx); | 315 | +} |
| 316 | + | ||
| 317 | +impl Plan { | ||
| 318 | + /// The answer with `body` (empty when the plan sends no bytes). | ||
| 319 | + fn answer(self, body: Body) -> ByteAnswer { | ||
| 320 | + (self.status, self.headers, body) | ||
| 321 | + } | ||
| 322 | +} | ||
| 323 | + | ||
| 324 | +/// Decides the answer for the request headers `request` and a file described by `source`: the status, the | ||
| 325 | +/// headers, and which bytes to send. Reads nothing from disk or from the network. | ||
| 326 | +pub fn plan(request: &HeaderMap, source: &ByteSource<'_>, disposition: Disposition) -> Plan { | ||
| 303 | let etag = format!("\"{}\"", source.sha256); | 327 | let etag = format!("\"{}\"", source.sha256); |
| 304 | let disposition = match disposition { | 328 | let disposition = match disposition { |
| 305 | Disposition::Inline if inline_safe(source.mime) => Disposition::Inline, | 329 | Disposition::Inline if inline_safe(source.mime) => Disposition::Inline, |
| 306 | _ => Disposition::Attachment, | 330 | _ => Disposition::Attachment, |
| 307 | }; | 331 | }; |
| 308 | - let mut answer_headers = common_headers(&etag, source.mime); | 332 | + let mut headers = common_headers(&etag, source.mime); |
| 309 | insert( | 333 | insert( |
| 310 | - &mut answer_headers, | 334 | + &mut headers, |
| 311 | CONTENT_DISPOSITION, | 335 | CONTENT_DISPOSITION, |
| 312 | &content_disposition(disposition, source.name), | 336 | &content_disposition(disposition, source.name), |
| 313 | ); | 337 | ); |
| 314 | - insert( | 338 | + insert(&mut headers, CONTENT_TYPE, &content_type_value(source.mime)); |
| 315 | - &mut answer_headers, | ||
| 316 | - CONTENT_TYPE, | ||
| 317 | - &content_type_value(source.mime), | ||
| 318 | - ); | ||
| 319 | 339 | ||
| 320 | if none_match_hits(request, &etag) { | 340 | if none_match_hits(request, &etag) { |
| 321 | - return Ok((StatusCode::NOT_MODIFIED, answer_headers, Body::empty())); | 341 | + return Plan { |
| 342 | + status: StatusCode::NOT_MODIFIED, | ||
| 343 | + headers, | ||
| 344 | + span: None, | ||
| 345 | + }; | ||
| 322 | } | 346 | } |
| 323 | 347 | ||
| 324 | match requested_range(request, &etag, source.size) { | 348 | match requested_range(request, &etag, source.size) { |
| 325 | - Ranged::Unsatisfiable => Ok(unsatisfiable(&etag, source.size, source.mime)), | 349 | + Ranged::Unsatisfiable => { |
| 326 | - Ranged::Full => { | 350 | + let mut unsatisfiable = common_headers(&etag, source.mime); |
| 327 | insert( | 351 | insert( |
| 328 | - &mut answer_headers, | 352 | + &mut unsatisfiable, |
| 329 | - CONTENT_LENGTH, | 353 | + CONTENT_RANGE, |
| 330 | - &source.size.to_string(), | 354 | + &format!("bytes */{}", source.size), |
| 331 | ); | 355 | ); |
| 332 | - let body = open_streamed(source.path, 0, source.size).await?; | 356 | + Plan { |
| 333 | - Ok((StatusCode::OK, answer_headers, body)) | 357 | + status: StatusCode::RANGE_NOT_SATISFIABLE, |
| 358 | + headers: unsatisfiable, | ||
| 359 | + span: None, | ||
| 360 | + } | ||
| 361 | + } | ||
| 362 | + Ranged::Full => { | ||
| 363 | + insert(&mut headers, CONTENT_LENGTH, &source.size.to_string()); | ||
| 364 | + Plan { | ||
| 365 | + status: StatusCode::OK, | ||
| 366 | + headers, | ||
| 367 | + span: Some(Span { | ||
| 368 | + start: 0, | ||
| 369 | + length: source.size, | ||
| 370 | + ranged: false, | ||
| 371 | + }), | ||
| 372 | + } | ||
| 334 | } | 373 | } |
| 335 | Ranged::Part { start, end } => { | 374 | Ranged::Part { start, end } => { |
| 336 | let length = end - start + 1; | 375 | let length = end - start + 1; |
| 337 | - insert(&mut answer_headers, CONTENT_LENGTH, &length.to_string()); | 376 | + insert(&mut headers, CONTENT_LENGTH, &length.to_string()); |
| 338 | insert( | 377 | insert( |
| 339 | - &mut answer_headers, | 378 | + &mut headers, |
| 340 | CONTENT_RANGE, | 379 | CONTENT_RANGE, |
| 341 | &format!("bytes {start}-{end}/{}", source.size), | 380 | &format!("bytes {start}-{end}/{}", source.size), |
| 342 | ); | 381 | ); |
| 343 | - let body = open_streamed(source.path, start, length).await?; | 382 | + Plan { |
| 344 | - Ok((StatusCode::PARTIAL_CONTENT, answer_headers, body)) | 383 | + status: StatusCode::PARTIAL_CONTENT, |
| 384 | + headers, | ||
| 385 | + span: Some(Span { | ||
| 386 | + start, | ||
| 387 | + length, | ||
| 388 | + ranged: true, | ||
| 389 | + }), | ||
| 390 | + } | ||
| 345 | } | 391 | } |
| 346 | } | 392 | } |
| 347 | } | 393 | } |
| 348 | 394 | ||
| 349 | -/// Opens `path`, seeks to `start` and streams `length` bytes from there. | 395 | +/// Answers from the file on this disk. `Ok(None)` when the file is not there (the row may have moved to the |
| 350 | -async fn open_streamed(path: &Path, start: u64, length: u64) -> Result<Body> { | 396 | +/// Files service in the meantime), so the caller can try the other place. Any other failure is an error. |
| 351 | - let mut file = tokio::fs::File::open(path).await?; | 397 | +pub async fn serve_local( |
| 352 | - if start > 0 { | 398 | + request: &HeaderMap, |
| 353 | - file.seek(SeekFrom::Start(start)).await?; | 399 | + source: &ByteSource<'_>, |
| 400 | + disposition: Disposition, | ||
| 401 | +) -> io::Result<Option<ByteAnswer>> { | ||
| 402 | + let plan = plan(request, source, disposition); | ||
| 403 | + let Some(span) = plan.span else { | ||
| 404 | + return Ok(Some(plan.answer(Body::empty()))); | ||
| 405 | + }; | ||
| 406 | + match open_streamed(source.path, span).await { | ||
| 407 | + Ok(body) => Ok(Some(plan.answer(body))), | ||
| 408 | + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None), | ||
| 409 | + Err(error) => Err(error), | ||
| 354 | } | 410 | } |
| 355 | - let frames = futures_util::stream::try_unfold((file, length), |(mut file, left)| async move { | 411 | +} |
| 356 | - if left == 0 { | 412 | + |
| 357 | - return Ok(None); | 413 | +/// Answers from the Files service: the same headers as [`serve_local`], and the bytes streamed from `in` |
| 358 | - } | 414 | +/// (with the same range). `in`'s own headers are never copied. The upstream's status and length must match |
| 359 | - let want = left.min(FRAME_BYTES as u64) as usize; | 415 | +/// what the plan expects, or the answer is an error and nothing is sent. |
| 360 | - let mut buf = vec![0u8; want]; | 416 | +pub async fn serve_remote( |
| 361 | - let read = file.read(&mut buf).await?; | 417 | + request: &HeaderMap, |
| 362 | - if read == 0 { | 418 | + source: &ByteSource<'_>, |
| 419 | + disposition: Disposition, | ||
| 420 | + store: &InStore, | ||
| 421 | + object_id: &str, | ||
| 422 | +) -> InResult<ByteAnswer> { | ||
| 423 | + let plan = plan(request, source, disposition); | ||
| 424 | + let Some(span) = plan.span else { | ||
| 425 | + return Ok(plan.answer(Body::empty())); | ||
| 426 | + }; | ||
| 427 | + let range = span | ||
| 428 | + .ranged | ||
| 429 | + .then(|| (span.start, span.start + span.length - 1)); | ||
| 430 | + let response = store.get(object_id, range).await?; | ||
| 431 | + let expected = if span.ranged { 206 } else { 200 }; | ||
| 432 | + if response.status().as_u16() != expected { | ||
| 433 | + return Err(InError::BadResponse(format!( | ||
| 434 | + "the object answered {} for a {expected}", | ||
| 435 | + response.status().as_u16() | ||
| 436 | + ))); | ||
| 437 | + } | ||
| 438 | + if response | ||
| 439 | + .content_length() | ||
| 440 | + .is_some_and(|len| len != span.length) | ||
| 441 | + { | ||
| 442 | + return Err(InError::BadResponse( | ||
| 443 | + "the object has another length than the record".into(), | ||
| 444 | + )); | ||
| 445 | + } | ||
| 446 | + let limit = span.length; | ||
| 447 | + let mut sent: u64 = 0; | ||
| 448 | + let frames = response.bytes_stream().map(move |chunk| { | ||
| 449 | + let chunk = chunk.map_err(io::Error::other)?; | ||
| 450 | + sent += chunk.len() as u64; | ||
| 451 | + if sent > limit { | ||
| 363 | return Err(io::Error::new( | 452 | return Err(io::Error::new( |
| 364 | - io::ErrorKind::UnexpectedEof, | 453 | + io::ErrorKind::InvalidData, |
| 365 | - "the file is shorter than its record", | 454 | + "the object is longer than its record", |
| 366 | )); | 455 | )); |
| 367 | } | 456 | } |
| 368 | - buf.truncate(read); | 457 | + Ok(Frame::data(chunk)) |
| 369 | - Ok(Some(( | ||
| 370 | - Frame::data(Bytes::from(buf)), | ||
| 371 | - (file, left - read as u64), | ||
| 372 | - ))) | ||
| 373 | }); | 458 | }); |
| 459 | + Ok(plan.answer(Body::new(StreamBody::new(frames)))) | ||
| 460 | +} | ||
| 461 | + | ||
| 462 | +/// Opens `path`, seeks to the span's start and streams its bytes. The open is the error that matters: a file | ||
| 463 | +/// that is not there is `NotFound`. | ||
| 464 | +async fn open_streamed(path: &Path, span: Span) -> io::Result<Body> { | ||
| 465 | + let mut file = tokio::fs::File::open(path).await?; | ||
| 466 | + if span.start > 0 { | ||
| 467 | + file.seek(SeekFrom::Start(span.start)).await?; | ||
| 468 | + } | ||
| 469 | + let frames = | ||
| 470 | + futures_util::stream::try_unfold((file, span.length), |(mut file, left)| async move { | ||
| 471 | + if left == 0 { | ||
| 472 | + return Ok(None); | ||
| 473 | + } | ||
| 474 | + let want = left.min(FRAME_BYTES as u64) as usize; | ||
| 475 | + let mut buf = vec![0u8; want]; | ||
| 476 | + let read = file.read(&mut buf).await?; | ||
| 477 | + if read == 0 { | ||
| 478 | + return Err(io::Error::new( | ||
| 479 | + io::ErrorKind::UnexpectedEof, | ||
| 480 | + "the file is shorter than its record", | ||
| 481 | + )); | ||
| 482 | + } | ||
| 483 | + buf.truncate(read); | ||
| 484 | + Ok(Some(( | ||
| 485 | + Frame::data(Bytes::from(buf)), | ||
| 486 | + (file, left - read as u64), | ||
| 487 | + ))) | ||
| 488 | + }); | ||
| 374 | Ok(Body::new(StreamBody::new(frames))) | 489 | Ok(Body::new(StreamBody::new(frames))) |
| 375 | } | 490 | } |
| 376 | 491 | ||
| @@ -462,4 +577,96 @@ mod tests { | |||
| 462 | ); | 577 | ); |
| 463 | assert!(content_disposition(Disposition::Attachment, "").contains("filename=\"download\"")); | 578 | assert!(content_disposition(Disposition::Attachment, "").contains("filename=\"download\"")); |
| 464 | } | 579 | } |
| 580 | + | ||
| 581 | + /// A file in the Files service is proxied with this server's headers only, and with the requested range. | ||
| 582 | + #[tokio::test] | ||
| 583 | + async fn a_row_in_the_files_service_is_sent_with_our_headers_only() { | ||
| 584 | + use crate::boot::test_state; | ||
| 585 | + use crate::in_store::InStore; | ||
| 586 | + use crate::in_store::test_support::{Reply, fake_in}; | ||
| 587 | + use std::sync::Arc; | ||
| 588 | + use topcoat::router::to_bytes; | ||
| 589 | + | ||
| 590 | + let data = b"hello world"; | ||
| 591 | + let base = fake_in(move |req| { | ||
| 592 | + if req.method != "GET" { | ||
| 593 | + return Reply { | ||
| 594 | + status: 405, | ||
| 595 | + headers: Vec::new(), | ||
| 596 | + body: Vec::new(), | ||
| 597 | + }; | ||
| 598 | + } | ||
| 599 | + let headers = vec![ | ||
| 600 | + ("Content-Security-Policy".into(), "default-src *".into()), | ||
| 601 | + ("Set-Cookie".into(), "sid=stolen".into()), | ||
| 602 | + ( | ||
| 603 | + "Content-Disposition".into(), | ||
| 604 | + "attachment; filename=evil".into(), | ||
| 605 | + ), | ||
| 606 | + ("X-Frame-Options".into(), "ALLOWALL".into()), | ||
| 607 | + ]; | ||
| 608 | + match req.header("range").and_then(|r| r.strip_prefix("bytes=")) { | ||
| 609 | + Some(spec) => { | ||
| 610 | + let (first, last) = spec.split_once('-').expect("range"); | ||
| 611 | + let (first, last): (usize, usize) = | ||
| 612 | + (first.parse().expect("first"), last.parse().expect("last")); | ||
| 613 | + Reply { | ||
| 614 | + status: 206, | ||
| 615 | + headers, | ||
| 616 | + body: data[first..=last].to_vec(), | ||
| 617 | + } | ||
| 618 | + } | ||
| 619 | + None => Reply { | ||
| 620 | + status: 200, | ||
| 621 | + headers, | ||
| 622 | + body: data.to_vec(), | ||
| 623 | + }, | ||
| 624 | + } | ||
| 625 | + }) | ||
| 626 | + .await; | ||
| 627 | + let (_dir, mut state) = test_state().await; | ||
| 628 | + state.in_store = Some(Arc::new(InStore::for_tests(&base))); | ||
| 629 | + let source = ByteSource { | ||
| 630 | + path: Path::new("/does/not/exist"), | ||
| 631 | + size: data.len() as u64, | ||
| 632 | + sha256: "0000000000000000000000000000000000000000000000000000000000000000", | ||
| 633 | + mime: "image/png", | ||
| 634 | + name: "a.png", | ||
| 635 | + }; | ||
| 636 | + let store = state.in_store.as_deref().expect("client"); | ||
| 637 | + | ||
| 638 | + let mut ranged = HeaderMap::new(); | ||
| 639 | + ranged.insert(RANGE, HeaderValue::from_static("bytes=0-4")); | ||
| 640 | + let (status, headers, body) = serve_remote( | ||
| 641 | + &ranged, | ||
| 642 | + &source, | ||
| 643 | + Disposition::Inline, | ||
| 644 | + store, | ||
| 645 | + "01HZ0000000000000000000000", | ||
| 646 | + ) | ||
| 647 | + .await | ||
| 648 | + .expect("answer"); | ||
| 649 | + assert_eq!(status, StatusCode::PARTIAL_CONTENT); | ||
| 650 | + assert_eq!(to_bytes(body, 1024).await.expect("body").as_ref(), b"hello"); | ||
| 651 | + assert_eq!(headers.get_all(CONTENT_SECURITY_POLICY).iter().count(), 1); | ||
| 652 | + assert_eq!(headers[CONTENT_SECURITY_POLICY], BYTES_CSP); | ||
| 653 | + assert!(headers.get(http::header::SET_COOKIE).is_none()); | ||
| 654 | + assert_eq!( | ||
| 655 | + headers[CONTENT_DISPOSITION], | ||
| 656 | + content_disposition(Disposition::Inline, "a.png").as_str() | ||
| 657 | + ); | ||
| 658 | + assert_eq!(headers[CONTENT_RANGE], "bytes 0-4/11"); | ||
| 659 | + | ||
| 660 | + let (status, _, body) = serve_remote( | ||
| 661 | + &HeaderMap::new(), | ||
| 662 | + &source, | ||
| 663 | + Disposition::Inline, | ||
| 664 | + store, | ||
| 665 | + "01HZ0000000000000000000000", | ||
| 666 | + ) | ||
| 667 | + .await | ||
| 668 | + .expect("answer"); | ||
| 669 | + assert_eq!(status, StatusCode::OK); | ||
| 670 | + assert_eq!(to_bytes(body, 1024).await.expect("body").as_ref(), data); | ||
| 671 | + } | ||
| 465 | } | 672 | } |
crates/iz-web/src/state.rsmodified+7 -0
| @@ -6,6 +6,7 @@ use iz_core::config::Config; | |||
| 6 | use iz_core::store::Store; | 6 | use iz_core::store::Store; |
| 7 | 7 | ||
| 8 | use crate::family::FamilyCache; | 8 | use crate::family::FamilyCache; |
| 9 | +use crate::in_store::InStore; | ||
| 9 | use crate::live::LiveHub; | 10 | use crate::live::LiveHub; |
| 10 | use crate::oidc::OidcClient; | 11 | use crate::oidc::OidcClient; |
| 11 | 12 | ||
| @@ -25,4 +26,10 @@ pub struct AppState { | |||
| 25 | pub oidc: Option<Arc<OidcClient>>, | 26 | pub oidc: Option<Arc<OidcClient>>, |
| 26 | /// The family service list that the topbar switcher shows. Filled by the `family` worker. | 27 | /// The family service list that the topbar switcher shows. Filled by the `family` worker. |
| 27 | pub family: Arc<FamilyCache>, | 28 | pub family: Arc<FamilyCache>, |
| 29 | + /// The Files service (`in`). `None` unless `[in_store]` is enabled with a URL and sign-in gives the token. | ||
| 30 | + pub in_store: Option<Arc<InStore>>, | ||
| 31 | + /// Held around every step that changes where attachment bytes are: a row's claim, flip or removal, a | ||
| 32 | + /// local copy's removal, and a Files copy's deletion. The mover and the deleter take it, so a stale record | ||
| 33 | + /// can never remove the live copy (see `attachments.rs`). | ||
| 34 | + pub blob_lock: Arc<tokio::sync::Mutex<()>>, | ||
| 28 | } | 35 | } |
crates/iz-web/src/sweeper.rsmodified+4 -38
| @@ -1,6 +1,6 @@ | |||
| 1 | //! The sweeper worker: housekeeping that is not urgent. It runs once at start and then every hour until the | 1 | //! The sweeper worker: housekeeping that is not urgent. It runs once at start and then every hour until the |
| 2 | //! stop flag is set. Each run deletes expired sessions and expired logout-token records, retries the | 2 | //! stop flag is set. Each run deletes expired sessions and expired logout-token records, retries the |
| 3 | -//! attachment bytes still owed (the deleter in `attachments.rs` does this too, every few seconds; this pass | 3 | +//! attachment copies still owed (the deleter in `attachments.rs` does this too, every few seconds; this pass |
| 4 | //! is the backstop), deletes activity and mail-ledger rows older than `RETENTION_DAYS`, and removes staged | 4 | //! is the backstop), deletes activity and mail-ledger rows older than `RETENTION_DAYS`, and removes staged |
| 5 | //! uploads left in `data_dir/tmp` by a crash. | 5 | //! uploads left in `data_dir/tmp` by a crash. |
| 6 | //! | 6 | //! |
| @@ -11,12 +11,12 @@ use std::future::Future; | |||
| 11 | use std::path::Path; | 11 | use std::path::Path; |
| 12 | use std::time::{Duration, SystemTime}; | 12 | use std::time::{Duration, SystemTime}; |
| 13 | 13 | ||
| 14 | -use iz_core::staging::{TMP_DIR, remove_blob}; | 14 | +use iz_core::staging::TMP_DIR; |
| 15 | use iz_core::store::sweep::RETENTION_DAYS; | 15 | use iz_core::store::sweep::RETENTION_DAYS; |
| 16 | use jiff::{SignedDuration, Timestamp}; | 16 | use jiff::{SignedDuration, Timestamp}; |
| 17 | use tokio::sync::watch; | 17 | use tokio::sync::watch; |
| 18 | 18 | ||
| 19 | -use crate::attachments::retry_delay; | 19 | +use crate::attachments; |
| 20 | use crate::state::AppState; | 20 | use crate::state::AppState; |
| 21 | 21 | ||
| 22 | /// How often the sweeper runs after its first pass. Reason: none of this is urgent. | 22 | /// How often the sweeper runs after its first pass. Reason: none of this is urgent. |
| @@ -44,7 +44,7 @@ pub fn spawn(state: AppState, mut stop: watch::Receiver<bool>) { | |||
| 44 | async fn sweep(state: &AppState) { | 44 | async fn sweep(state: &AppState) { |
| 45 | note("expired sessions", state.store.sweep_sessions().await); | 45 | note("expired sessions", state.store.sweep_sessions().await); |
| 46 | note("expired logout tokens", state.store.sweep_jti().await); | 46 | note("expired logout tokens", state.store.sweep_jti().await); |
| 47 | - retry_blob_deletions(state).await; | 47 | + attachments::sweep(state).await; |
| 48 | match Timestamp::now().checked_sub(SignedDuration::from_hours(24 * RETENTION_DAYS)) { | 48 | match Timestamp::now().checked_sub(SignedDuration::from_hours(24 * RETENTION_DAYS)) { |
| 49 | Ok(cutoff) => { | 49 | Ok(cutoff) => { |
| 50 | drain("activity", |batch| { | 50 | drain("activity", |batch| { |
| @@ -105,40 +105,6 @@ where | |||
| 105 | note(what, Ok(total)); | 105 | note(what, Ok(total)); |
| 106 | } | 106 | } |
| 107 | 107 | ||
| 108 | -/// Retries the attachment bytes that are owed and due. A removal that fails is scheduled again with the | ||
| 109 | -/// same backoff the deleter uses. Returns nothing; the deleter logs its own failures. | ||
| 110 | -async fn retry_blob_deletions(state: &AppState) { | ||
| 111 | - let due = match state.store.due_blob_deletions(BATCH).await { | ||
| 112 | - Ok(due) => due, | ||
| 113 | - Err(error) => { | ||
| 114 | - tracing::warn!(error = %error, "reading the due attachment deletions failed"); | ||
| 115 | - return; | ||
| 116 | - } | ||
| 117 | - }; | ||
| 118 | - let mut removed: u64 = 0; | ||
| 119 | - for (id, attempts) in due { | ||
| 120 | - match remove_blob(&state.config.data_dir, &id).await { | ||
| 121 | - Ok(()) => match state.store.finish_blob_deletion(&id).await { | ||
| 122 | - Ok(()) => removed += 1, | ||
| 123 | - Err(error) => { | ||
| 124 | - tracing::warn!(error = %error, "clearing a finished attachment deletion failed"); | ||
| 125 | - } | ||
| 126 | - }, | ||
| 127 | - Err(error) => { | ||
| 128 | - tracing::warn!(attempts, error = %error, "removing attachment bytes failed; retrying"); | ||
| 129 | - if let Err(error) = state | ||
| 130 | - .store | ||
| 131 | - .defer_blob_deletion(&id, attempts, retry_delay(attempts)) | ||
| 132 | - .await | ||
| 133 | - { | ||
| 134 | - tracing::warn!(error = %error, "scheduling an attachment deletion retry failed"); | ||
| 135 | - } | ||
| 136 | - } | ||
| 137 | - } | ||
| 138 | - } | ||
| 139 | - note("attachment bytes removed", Ok(removed)); | ||
| 140 | -} | ||
| 141 | - | ||
| 142 | /// Removes regular files in `data_dir/tmp` that were last changed more than [`TEMP_MAX_AGE`] ago. A missing | 108 | /// Removes regular files in `data_dir/tmp` that were last changed more than [`TEMP_MAX_AGE`] ago. A missing |
| 143 | /// staging directory means there is nothing to remove. Links and directories are left alone. | 109 | /// staging directory means there is nothing to remove. Links and directories are left alone. |
| 144 | async fn remove_stale_temp_files(data_dir: &Path) -> iz_core::Result<u64> { | 110 | async fn remove_stale_temp_files(data_dir: &Path) -> iz_core::Result<u64> { |
crates/iz-web/src/views/admin.rsmodified+4 -1
| @@ -12,7 +12,7 @@ use crate::i18n::Lang; | |||
| 12 | use crate::i18n::admin::{K, t}; | 12 | use crate::i18n::admin::{K, t}; |
| 13 | use crate::i18n::structure::{K as StructureK, t as structure_t}; | 13 | use crate::i18n::structure::{K as StructureK, t as structure_t}; |
| 14 | use crate::views::board::flag; | 14 | use crate::views::board::flag; |
| 15 | -use crate::views::structure::{limits_section, members_section, server_section}; | 15 | +use crate::views::structure::{limits_section, members_section, server_section, storage_section}; |
| 16 | use crate::views::{alert, notice}; | 16 | use crate::views::{alert, notice}; |
| 17 | 17 | ||
| 18 | /// The sender form as it is shown. The password is never here, only `password_set`. | 18 | /// The sender form as it is shown. The password is never here, only `password_set`. |
| @@ -136,6 +136,8 @@ pub struct SettingsView { | |||
| 136 | pub extensions: String, | 136 | pub extensions: String, |
| 137 | /// Read-only facts about the server. | 137 | /// Read-only facts about the server. |
| 138 | pub server: crate::views::structure::ServerInfo, | 138 | pub server: crate::views::structure::ServerInfo, |
| 139 | + /// Where attachments are kept and how far the move between places has got. | ||
| 140 | + pub storage: crate::views::structure::StorageInfo, | ||
| 139 | } | 141 | } |
| 140 | 142 | ||
| 141 | /// The rules page: the list, the form (new or editing), and the choices of the form. | 143 | /// The rules page: the list, the form (new or editing), and the choices of the form. |
| @@ -311,6 +313,7 @@ pub async fn settings_content(page: &SettingsView, csrf: &str) -> Result<impl Vi | |||
| 311 | </form> | 313 | </form> |
| 312 | </section> | 314 | </section> |
| 313 | members_section(lang: lang, members: &page.members, csrf: csrf) | 315 | members_section(lang: lang, members: &page.members, csrf: csrf) |
| 316 | + storage_section(lang: lang, info: &page.storage, csrf: csrf) | ||
| 314 | limits_section(lang: lang, limit_mib: page.limit_mib.as_str(), extensions: page.extensions.as_str(), csrf: csrf) | 317 | limits_section(lang: lang, limit_mib: page.limit_mib.as_str(), extensions: page.extensions.as_str(), csrf: csrf) |
| 315 | server_section(lang: lang, info: &page.server) | 318 | server_section(lang: lang, info: &page.server) |
| 316 | }) | 319 | }) |
crates/iz-web/src/views/structure.rsmodified+68 -0
| @@ -106,6 +106,74 @@ pub struct ServerInfo { | |||
| 106 | pub storage_in: bool, | 106 | pub storage_in: bool, |
| 107 | } | 107 | } |
| 108 | 108 | ||
| 109 | +/// Where attachments are kept, and how far a move between the two places has got. Read from the store for the | ||
| 110 | +/// settings page; `in_available` says whether the Files service can be chosen at all. | ||
| 111 | +#[derive(Debug, Clone, Default)] | ||
| 112 | +pub struct StorageInfo { | ||
| 113 | + /// The chosen place: `local` or `in`. | ||
| 114 | + pub target: String, | ||
| 115 | + /// Whether the Files service is set up (configured, and a token can be had). | ||
| 116 | + pub in_available: bool, | ||
| 117 | + /// Rows whose bytes are on this server. | ||
| 118 | + pub local: i64, | ||
| 119 | + /// Rows whose bytes are in the Files service. | ||
| 120 | + pub in_files: i64, | ||
| 121 | + /// Rows being moved right now. | ||
| 122 | + pub moving: i64, | ||
| 123 | +} | ||
| 124 | + | ||
| 125 | +/// The attachment storage section of `/settings`: the chosen place, the counts, and the migration still to do. | ||
| 126 | +#[component] | ||
| 127 | +pub async fn storage_section(lang: Lang, info: &StorageInfo, csrf: &str) -> Result<impl View> { | ||
| 128 | + let in_chosen = info.target == "in"; | ||
| 129 | + let counts = fill( | ||
| 130 | + t(lang, K::StorageCounts), | ||
| 131 | + &[ | ||
| 132 | + &info.local.to_string(), | ||
| 133 | + &info.in_files.to_string(), | ||
| 134 | + &info.moving.to_string(), | ||
| 135 | + ], | ||
| 136 | + ); | ||
| 137 | + // Rows not yet where the setting says: the ones the mover still has to bring over, plus any mid-move. | ||
| 138 | + let waiting = if in_chosen { | ||
| 139 | + info.local + info.moving | ||
| 140 | + } else { | ||
| 141 | + info.in_files + info.moving | ||
| 142 | + }; | ||
| 143 | + let target_word = if in_chosen { | ||
| 144 | + t(lang, K::StorageIn) | ||
| 145 | + } else { | ||
| 146 | + t(lang, K::StorageLocal) | ||
| 147 | + }; | ||
| 148 | + let migrating = (waiting > 0).then(|| { | ||
| 149 | + fill( | ||
| 150 | + t(lang, K::StorageMigrating), | ||
| 151 | + &[&waiting.to_string(), target_word], | ||
| 152 | + ) | ||
| 153 | + }); | ||
| 154 | + Ok(view! { | ||
| 155 | + <section class="card" id="storage"> | ||
| 156 | + <h2>(t(lang, K::StorageHeading))</h2> | ||
| 157 | + <p class="field-hint">(t(lang, K::StorageHelp))</p> | ||
| 158 | + <p>(counts.as_str())</p> | ||
| 159 | + if let Some(line) = &migrating { | ||
| 160 | + <p class="field-hint">(line.as_str())</p> | ||
| 161 | + } | ||
| 162 | + <form method="post" action="/settings/attachments" class="stack"> | ||
| 163 | + <input type="hidden" name="csrf" value=(csrf)> | ||
| 164 | + <div class="field"> | ||
| 165 | + <label><input type="radio" name="location" value="local" checked=(flag(!in_chosen))> (t(lang, K::StorageLocalOption))</label> | ||
| 166 | + <label><input type="radio" name="location" value="in" checked=(flag(in_chosen)) disabled=(flag(!info.in_available))> (t(lang, K::StorageInOption))</label> | ||
| 167 | + if !info.in_available { | ||
| 168 | + <p class="field-hint">(t(lang, K::StorageInUnavailable))</p> | ||
| 169 | + } | ||
| 170 | + </div> | ||
| 171 | + <button class="button" type="submit">(t(lang, K::StorageSave))</button> | ||
| 172 | + </form> | ||
| 173 | + </section> | ||
| 174 | + }) | ||
| 175 | +} | ||
| 176 | + | ||
| 109 | /// The projects page body. | 177 | /// The projects page body. |
| 110 | #[component] | 178 | #[component] |
| 111 | pub async fn tags_content(page: &TagsView, csrf: &str) -> Result<impl View> { | 179 | pub async fn tags_content(page: &TagsView, csrf: &str) -> Result<impl View> { |