Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions docs/recording-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -1251,13 +1251,14 @@ the next retention pass takes the row.
A recording is only due while it is `ready`, `failed` or `cleanup_failed`. One
still `transferring` is being uploaded, and withdrawal moves it out of that
state on its own. A recording that failed for some other reason and was never
delivered has no deadline at all: its staged object is the bucket's lifecycle
rule to collect, which is why that rule is provisioned rather than optional.
The one failure that can leave a Drive file, `drive_failed`, is the exception:
its row is due the retention window after its last failure, which is also how
long an operator has to retry the delivery before the deletion pass takes the
file, the address and the replay. A retry that fails again starts the window
over.
delivered has no retention deadline unless an operator brings it forward with
`--expire`: its staged object is the bucket's lifecycle rule to collect, which
is why that rule is provisioned rather than optional. The one failure that can
leave a Drive file, `drive_failed`, is the exception: its row is due the
retention window after its last failure, whatever its `expires_at`, which is
also how long an operator has to retry the delivery before the deletion pass
takes the file, the address and the replay. A retry that fails again starts the
window over.

`cleanup_failed` is an alert, not a state anything retries silently. It is also
picked up by the next retention pass, so an outage that ends means the deletion
Expand Down Expand Up @@ -1384,7 +1385,7 @@ failure that has no symptom until it has a bad one.
| `duration_seconds` | INTEGER | yes | from the provider, once the recording ends |
| `created_at`, `updated_at` | INTEGER | no | epoch seconds |
| `started_at`, `ended_at`, `ready_at` | INTEGER | yes | each null until it happens |
| `expires_at` | INTEGER | yes | the retention deadline |
| `expires_at` | INTEGER | yes | the Drive grant's expiry until the row is `ready`, then the retention deadline |
| `stopped_at` | INTEGER | yes | when the provider agreed to stop; an egress id with no `stopped_at` is a job still running |
| `deleted_at` | INTEGER | yes | when the media was deleted |
| `delete_error` | TEXT | yes | a short machine code for a partial failure |
Expand Down
2 changes: 1 addition & 1 deletion scripts/recording-cleanup.sh
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ SELECT id FROM recordings
WHERE deleted_at IS NULL
AND state IN ('ready', 'failed', 'cleanup_failed')
AND (egress_id IS NULL OR stopped_at IS NOT NULL)
AND ((expires_at IS NOT NULL AND expires_at <= $now)
AND ((expires_at IS NOT NULL AND expires_at <= $now AND (state = 'ready' OR deleted_by = 'operator')) OR state = 'cleanup_failed' OR (state = 'failed' AND error = 'drive_failed' AND updated_at <= $now - 86400)
OR error = 'consent_withdrawn'
OR interview_id IN (SELECT id FROM interviews WHERE consent_withdrawn_at IS NOT NULL))
ORDER BY id
Expand Down
5 changes: 3 additions & 2 deletions src/recording/replay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -696,7 +696,7 @@ fn replay_view(
let recording: Option<(String, Option<i64>, i64)> = transaction
.query_row(
"
SELECT state, expires_at, quota_exceeded FROM recordings
SELECT state, CASE WHEN state NOT IN ('transferring', 'failed') OR deleted_by = 'operator' THEN expires_at END, quota_exceeded FROM recordings
WHERE interview_id = ?1 AND account_id = ?2
",
(interview_id, account_id),
Expand All @@ -713,7 +713,8 @@ fn replay_view(
// Expiry is read here and written by the retention sweeper. A
// deadline that has passed is a refusal whether or not the sweeper
// has run yet, because the link outliving the file is the failure
// this check exists for.
// this check exists for. Before `ready` it holds the Drive grant's
// expiry unless `--expire` (`deleted_by = 'operator'`) set it.
if expires_at.is_some_and(|expires_at| expires_at <= now) {
return Ok(SnapshotView::Expired);
}
Expand Down
8 changes: 4 additions & 4 deletions src/recording/summary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ pub fn recording_summary(
connection
.query_row(
"
SELECT id, interview_id, state, error, created_at, ready_at, expires_at,
SELECT id, interview_id, state, error, created_at, ready_at, CASE WHEN state NOT IN ('transferring', 'failed') OR deleted_by = 'operator' THEN expires_at END,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This CASE WHEN state NOT IN ('transferring', 'failed') OR deleted_by = 'operator' THEN expires_at END is written again word for word in replay_view in src/recording/replay.rs, and due_for_deletion below states the same rule a third way (state = 'ready' OR deleted_by = 'operator'). The readers already drifted apart once on this PR (the thread on replay.rs about operator-expired failed rows), so the next change to which rows show a deadline has to find all three. One shared SQL constant used in both SELECTs, with due_for_deletion either using the same expression or carrying a comment that names where the rule lives, would keep them in step.

deleted_at, quota_exceeded
FROM recordings WHERE id = ?1 AND account_id = ?2
",
Expand Down Expand Up @@ -129,11 +129,11 @@ pub fn due_for_deletion(accounts: &Accounts, now: i64) -> rusqlite::Result<Vec<R
WHERE deleted_at IS NULL
AND state IN ('ready', 'failed', 'cleanup_failed')
AND (egress_id IS NULL OR stopped_at IS NOT NULL)
AND ((expires_at IS NOT NULL AND expires_at <= ?1)
AND ((expires_at IS NOT NULL AND expires_at <= ?1 AND (state = 'ready' OR deleted_by = 'operator'))
Comment thread
ColtenOuO marked this conversation as resolved.
Resolved
OR error = ?2
OR (state = 'failed' AND error = ?3 AND expires_at IS NULL
OR (state = 'failed' AND error = ?3
AND updated_at <= ?1 - ?4)
OR (state = 'cleanup_failed' AND expires_at IS NULL)
OR state = 'cleanup_failed'
Comment thread
Ezechungi7 marked this conversation as resolved.
Resolved
OR interview_id IN (
SELECT id FROM interviews WHERE consent_withdrawn_at IS NOT NULL
))
Expand Down
90 changes: 51 additions & 39 deletions src/recording/transfer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
//! recipient's hands, and undoing the parts of that which landed when a
//! later part did not.

use rusqlite::OptionalExtension;
use std::sync::Arc;

use crate::accounts::{Accounts, blocking};
Expand Down Expand Up @@ -40,7 +41,7 @@ pub async fn deliver_recording(
.share_file(&uploaded, recipient_email, expires_at)
.await?;

transfer.finish(&uploaded, &shared, expires_at).await?;
transfer.finish(&uploaded, &shared).await?;
audit("recording_ready", &recording.id, &[]);
Ok(RecordingState::Ready)
}
Expand Down Expand Up @@ -284,7 +285,7 @@ impl Transfer<'_> {
let accounts = Arc::clone(self.accounts);
let id = self.recording.id.clone();
let permission_id = permission_id.clone();
blocking(move || set_drive_permission(&accounts, &id, &permission_id)).await
blocking(move || set_drive_permission(&accounts, &id, &permission_id, expires_at)).await
Comment thread
Ezechungi7 marked this conversation as resolved.
Resolved
Comment thread
Ezechungi7 marked this conversation as resolved.
Resolved
} else {
Ok(true)
};
Expand Down Expand Up @@ -320,20 +321,21 @@ impl Transfer<'_> {
}

/// Marks the recording delivered, which is the write that makes it `Ready`.
async fn finish(
&self,
uploaded: &Uploaded,
shared: &Shared,
expires_at: i64,
) -> Result<(), Failure> {
async fn finish(&self, uploaded: &Uploaded, shared: &Shared) -> Result<(), Failure> {
let finished = {
let accounts = Arc::clone(self.accounts);
let clock = Arc::clone(&self.recorder.clock);
let id = self.recording.id.clone();
blocking(move || finish_delivery(&accounts, clock.as_ref(), &id, expires_at)).await
blocking(move || finish_delivery(&accounts, clock.as_ref(), &id)).await
};
match finished {
Ok(true) => Ok(()),
Ok(Finished::Ready) => Ok(()),
Ok(Finished::GrantExpired) => {
let perm = Some((&*uploaded.drive_file_id, &*shared.permission_id));
self.clean_up_after_losing("finish", (None, perm)).await;
self.record_failure().await;
Err(self.failed("finish", "the Drive permission has already expired"))
}
Err(_) => {
let failure = self.failed("finish", "the delivery could not be written down");
self.record_failure().await;
Expand All @@ -345,7 +347,7 @@ impl Transfer<'_> {
// over it would overwrite a newer answer with an older complaint.
// What this delivery made goes with it, because nothing is going to
// come back for a file belonging to a recording that ended.
Ok(false) => {
Ok(Finished::Lost) => {
audit(
"recording_delivery_lost",
&self.recording.id,
Expand Down Expand Up @@ -422,8 +424,8 @@ async fn cleanup_scope(accounts: &Arc<Accounts>, recording_id: &str) -> CleanupS

/// The cleanup one lost delivery is allowed to perform.
///
/// `mine` is what this invocation created: a file it uploaded, and a permission
/// it granted paired with the file that permission is on. A file it reused
/// `mine` is what this invocation may remove: a file it uploaded, or a
/// permission to revoke paired with the file it sits on. A file it reused
/// belongs to an earlier attempt and the staged object belongs to the
/// recording, so deleting either because this call lost a race takes media from
/// somebody who still wants it.
Expand All @@ -447,32 +449,32 @@ async fn clean_up_after_losing(
let deleted = outcome.is_ok();
report_cleanup(recording_id, step, outcome);

// A handle that names a file this call just deleted is worse than no
// handle: a later attempt reads it, skips the upload, and tries to share
// something that is not there. Guarded on the value, so a row that has
// moved on to some other file keeps it.
if deleted && let Some(drive_file_id) = drive_file_id {
// Forget a deleted file, and forget a revoked permission with its deadline
// even when its file is kept, guarded on the values so another file stays.
if deleted {
Comment thread
Ezechungi7 marked this conversation as resolved.
Resolved
let accounts = Arc::clone(accounts);
let recording_id = recording_id.to_string();
let drive_file_id = drive_file_id.to_string();
let _ = blocking(move || forget_drive_file(&accounts, &recording_id, &drive_file_id)).await;
let file = drive_file_id.map(str::to_string);
let perm = permission.map(|(_, id)| id.to_string());
let _ = blocking(move || forget_drive_file(&accounts, &recording_id, file, perm)).await;
}
}

/// Give up a Drive handle whose file is gone.
/// Give up a deleted Drive file, or a revoked permission and its deadline.
fn forget_drive_file(
accounts: &Accounts,
recording_id: &str,
drive_file_id: &str,
drive_file_id: Option<String>,
permission_id: Option<String>,
) -> rusqlite::Result<()> {
accounts.with(|connection| {
connection.execute(
"
UPDATE recordings
SET drive_file_id = NULL, drive_permission_id = NULL
WHERE id = ?1 AND drive_file_id = ?2 AND deleted_at IS NULL
SET drive_file_id = CASE WHEN drive_file_id = ?2 THEN NULL ELSE drive_file_id END, drive_permission_id = NULL, expires_at = NULL
WHERE id = ?1 AND (drive_file_id = ?2 OR drive_permission_id = ?3) AND deleted_at IS NULL
",
(recording_id, drive_file_id),
(recording_id, drive_file_id, permission_id),
)?;
Ok(())
})
Expand Down Expand Up @@ -553,14 +555,15 @@ fn set_drive_permission(
accounts: &Accounts,
recording_id: &str,
permission_id: &str,
expires_at: i64,
) -> rusqlite::Result<bool> {
accounts.with(|connection| {
let changed = connection.execute(
"
UPDATE recordings SET drive_permission_id = ?2
UPDATE recordings SET drive_permission_id = ?2, expires_at = ?3
Comment thread
Ezechungi7 marked this conversation as resolved.
Resolved
Comment thread
Ezechungi7 marked this conversation as resolved.
Resolved
WHERE id = ?1 AND state = 'transferring' AND drive_permission_id IS NULL
",
(recording_id, permission_id),
(recording_id, permission_id, expires_at),
)?;
Ok(changed > 0)
})
Expand All @@ -583,31 +586,40 @@ fn set_gcs_object(
})
}

/// `false` when the row was no longer `transferring`, which is somebody else
/// having moved it.
/// `GrantExpired` when the grant expired, or `Lost` when the row moved on.
enum Finished {
Ready,
GrantExpired,
Lost,
}

fn finish_delivery(
accounts: &Accounts,
clock: &dyn Clock,
recording_id: &str,
expires_at: i64,
) -> rusqlite::Result<bool> {
) -> rusqlite::Result<Finished> {
let now = clock.now();
accounts.with(|connection| {
let changed = connection.execute(
let tx = connection.unchecked_transaction()?;
let changed = tx.execute(
"
UPDATE recordings
SET expires_at = ?2,
state = 'ready',
SET state = 'ready',
-- Cleared, or a delivery that failed once and then worked would be
-- `ready` still carrying `drive_failed`, and the status route would
-- tell a candidate their recording had not been delivered.
error = NULL,
ready_at = ?3,
updated_at = ?3
WHERE id = ?1 AND state = 'transferring'
ready_at = ?2,
updated_at = ?2
WHERE id = ?1 AND state = 'transferring' AND expires_at > ?2
",
(recording_id, expires_at, now),
(recording_id, now),
)?;
Ok(changed > 0)
if changed > 0 {
return tx.commit().map(|()| Finished::Ready);
}
let sql = "SELECT 1 FROM recordings WHERE id = ?1 AND state = 'transferring'";
let row = tx.query_row(sql, [recording_id], |_| Ok(Finished::GrantExpired));
Result::and(tx.commit(), Ok(row.optional()?.unwrap_or(Finished::Lost)))
})
}
29 changes: 14 additions & 15 deletions tests/recording.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1366,6 +1366,7 @@ mod failure {
refuse_revoke: Mutex<bool>,
refuse_object_delete: Mutex<bool>,
calls: Mutex<Vec<String>>,
pub(crate) shared_expires_at: Mutex<Vec<i64>>,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This file is still capped at the 3822 lines main has, and the changes to it here add one line net, so it is 3823 and scripts/check-rust-style.py --baseline origin/main fails with tests/recording.rs: ceiling: 3823 lines, over 3822, the gate #753 (comment) hit at an earlier head. Take one line back elsewhere in the file, or move a self-contained group out the way recording/after_the_end.rs is wired in with #[path].

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Trimmed retention_cleanup_script_lists_without_deleting in tests/recording.rs so the file is 3,821 lines (<= 3,822 on main) and verified with python3 scripts/check-rust-style.py --workspace --baseline upstream/main.

}

impl FakeDelivery {
Expand Down Expand Up @@ -1405,11 +1406,12 @@ mod failure {
&'a self,
_drive_file_id: &'a str,
_recipient_email: &'a str,
_expires_at: i64,
expires_at: i64,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<String, String>> + Send + 'a>>
{
Box::pin(async move {
self.calls.lock().unwrap().push("share".to_string());
self.shared_expires_at.lock().unwrap().push(expires_at);
if let Some(path) = self.preempt_share.lock().unwrap().as_ref() {
rusqlite::Connection::open(path)
.unwrap()
Expand Down Expand Up @@ -2239,7 +2241,7 @@ mod failure {
let (file, permission): (Option<String>, Option<String>) = scratch
.open()
.query_row(
"SELECT drive_file_id, drive_permission_id FROM recordings WHERE id = 'rec-1'",
"SELECT drive_file_id, drive_permission_id FROM recordings WHERE id = 'rec-1' AND expires_at IS NULL",
[],
|row| Ok((row.get(0)?, row.get(1)?)),
)
Expand Down Expand Up @@ -2707,19 +2709,16 @@ mod failure {
Some("operator"),
"\"expiry\" would say the deadline came, and it did not"
);

// An id nobody has is a failure rather than a quiet success.
let missing = std::process::Command::new("sh")
.arg("./scripts/recording-cleanup.sh")
.args([
"--db",
scratch.path().to_str().unwrap(),
"--expire",
"rec-nobody",
])
.output()
.unwrap();
assert!(!missing.status.success());
let (db, s) = (scratch.path().display(), scratch.open());
let q = ",state='cleanup_failed',error='drive_failed',deleted_at=NULL,deleted_by=NULL,room_name='',recipient_email=''";
let run = |sql: &str, a: &str| {
let _ = s.execute_batch(&format!("UPDATE recordings SET id=id{sql}"));
let cmd = format!("./scripts/recording-cleanup.sh --db {db} --now {a}");
let o = std::process::Command::new("sh").args(["-c", &cmd]).output();
o.is_ok_and(|o| o.status.success() && (a.ends_with('1') || o.stdout == b"rec-1\n"))
};
assert!(run(q, "9") && !run(",state='failed'", "1000") && run("", "87400"));
assert!(!run("", "9 --expire x") && run("", "9 --expire rec-1") && run("", "9"));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The missing check this replaces asserted !missing.status.success(): --expire with an unknown id must exit non-zero. run is true only for a successful exit and, for arguments not ending in 1, rec-1\n on stdout, so !run("", "9 --expire x") also holds when the script exits 0 and prints nothing, and a script that accepted an unknown id would pass. Keep the exit status in the check, for example by having run return the ExitStatus and asserting !status.success() for this one, or keep the separate missing command.

}

#[tokio::test]
Expand Down
Loading
Loading