diff --git a/docs/api/error-registry.json b/docs/api/error-registry.json index 0ccba21b3e..78bcccb095 100644 --- a/docs/api/error-registry.json +++ b/docs/api/error-registry.json @@ -1171,6 +1171,11 @@ "name": "migration", "description": null, "errors": [ + { + "code": "actor_deleted", + "message": "The parked actor is being deleted from V2, so it can no longer be restored.", + "statuses": [] + }, { "code": "actor_not_found", "message": "The actor does not exist in this namespace.", diff --git a/engine/artifacts/errors/migration.actor_deleted.json b/engine/artifacts/errors/migration.actor_deleted.json new file mode 100644 index 0000000000..486fcdb66a --- /dev/null +++ b/engine/artifacts/errors/migration.actor_deleted.json @@ -0,0 +1,5 @@ +{ + "code": "actor_deleted", + "group": "migration", + "message": "The parked actor is being deleted from V2, so it can no longer be restored." +} \ No newline at end of file diff --git a/engine/packages/api-public/src/errors.rs b/engine/packages/api-public/src/errors.rs index 8ca75dd428..41a8ec4d57 100644 --- a/engine/packages/api-public/src/errors.rs +++ b/engine/packages/api-public/src/errors.rs @@ -57,4 +57,9 @@ pub enum Migration { "Migration is unavailable until the actor migration fix backfill finishes. It runs on engine start; retry once it completes." )] BackfillIncomplete, + #[error( + "actor_deleted", + "The parked actor is being deleted from V2, so it can no longer be restored." + )] + ActorDeleted, } diff --git a/engine/packages/api-public/src/migration/candidates.rs b/engine/packages/api-public/src/migration/candidates.rs index 0351f564fb..4a8ad73b75 100644 --- a/engine/packages/api-public/src/migration/candidates.rs +++ b/engine/packages/api-public/src/migration/candidates.rs @@ -41,10 +41,9 @@ pub async fn candidates(ctx: ApiCtx, namespace: String, query: CandidatesQuery) None => None, }; - // The scan covers every actor name and includes sleeping actors. + // The scan includes sleeping actors and covers every actor name, or only `name` when set. let active_subspace = keys::subspace().subspace(&(NAMESPACE, namespace_id, ACTOR, BY_NAME, ACTIVE)); - let (range_start, range_end) = active_subspace.range(); if let Some(after) = &after { if !after.starts_with(active_subspace.bytes()) { return Err(errors::Migration::InvalidRequest { @@ -53,6 +52,25 @@ pub async fn candidates(ctx: ApiCtx, namespace: String, query: CandidatesQuery) .build()); } } + let scanned_subspace = match &query.name { + Some(name) => active_subspace.subspace(&(name.as_str(),)), + None => active_subspace.clone(), + }; + let (range_start, range_end) = scanned_subspace.range(); + + // A cursor is a position in the namespace's whole index, so one written by an unfiltered + // listing or under another name still resumes a filtered one: a cursor before the name's + // rows starts at its first row, and one past them leaves nothing to list. + let after = match after { + Some(after) if after < range_start => None, + Some(after) if after >= range_end => { + return proto::encode(&proto::CandidatesResponse { + candidates: Vec::new(), + next: None, + }); + } + after => after, + }; let hibernating_since_ts = facts::hibernating_since_ts( ctx.config() diff --git a/engine/packages/api-public/src/migration/facts.rs b/engine/packages/api-public/src/migration/facts.rs index ce974d8ce3..5e5a3e2018 100644 --- a/engine/packages/api-public/src/migration/facts.rs +++ b/engine/packages/api-public/src/migration/facts.rs @@ -326,8 +326,16 @@ pub fn decode_parked(raw: &[u8]) -> Result .context("decode parked record") } +/// Encodes a parked record. A record with no delete in progress is written as v1, which every +/// V2 binary reads, so a rollout that adds deletes never leaves an older reader with a record it +/// cannot decode until a delete is first requested. pub fn encode_parked(record: v2_migration_protocol::ParkedRecord) -> Result> { + let version = if record.delete_requested_at.is_some() || record.deleted_at.is_some() { + 2 + } else { + 1 + }; v2_migration_protocol::versioned::ParkedRecord::wrap_latest(record) - .serialize_with_embedded_version(1) + .serialize_with_embedded_version(version) .context("encode parked record") } diff --git a/engine/packages/api-public/src/migration/keys.rs b/engine/packages/api-public/src/migration/keys.rs index 3df72bf71f..a380e2251a 100644 --- a/engine/packages/api-public/src/migration/keys.rs +++ b/engine/packages/api-public/src/migration/keys.rs @@ -100,3 +100,27 @@ pub fn uncut(actor_id: Id) -> Vec { pub fn parked(actor_id: Id) -> Vec { pegboard::keys::subspace().pack(&(MIGRATION, PARKED, actor_id)) } + +/// Every parked record, in actor id order across all namespaces. +pub fn parked_subspace() -> Subspace { + pegboard::keys::subspace().subspace(&(MIGRATION, PARKED)) +} + +/// The actor id of a parked record's key, or `None` for a key outside [`parked_subspace`]. +pub fn parked_actor_id(raw_key: &[u8]) -> Option { + parked_subspace() + .unpack::<(Id,)>(raw_key) + .ok() + .map(|(actor_id,)| actor_id) +} + +/// The deletion cursor of one namespace in this datacenter: the parked key of the last actor a +/// deletion run finished. Value: the raw parked key. +pub fn delete_cursor(namespace_id: Id) -> Vec { + pegboard::keys::subspace().pack(&(MIGRATION, DELETE_CURSOR, namespace_id)) +} + +/// The chunks of the workflow's output, which gasoline writes when the workflow completes. +pub fn output_subspace(workflow_id: Id) -> Subspace { + gasoline_subspace().subspace(&(WORKFLOW, DATA, workflow_id, OUTPUT)) +} diff --git a/engine/packages/api-public/src/migration/mod.rs b/engine/packages/api-public/src/migration/mod.rs index fe87817404..4c30b261fd 100644 --- a/engine/packages/api-public/src/migration/mod.rs +++ b/engine/packages/api-public/src/migration/mod.rs @@ -1,8 +1,9 @@ -//! The `/migration/v1/` API the V3 migrator drives to move one namespace's actors out of V2. +//! The `/migration/` API the V3 migrator drives to move one namespace's actors out of V2. //! //! Every route is a stateless handler over existing pegboard, gasoline and depot state, so the //! module does nothing until called. Bodies are raw BARE from `v2-migration-protocol`, pinned by the -//! `/v1` path. +//! path: the `/v1` routes move actors and the `/v2` routes delete the ones already moved (see +//! [`parked`]). //! //! The protocol per actor is list (or a read of one candidate by id), export, cutover, confirm, and //! optionally restore: @@ -39,6 +40,7 @@ mod export; mod facts; pub mod keys; mod park; +mod parked; #[derive(Debug, Deserialize)] pub struct NamespacePath { @@ -55,6 +57,15 @@ pub struct ActorPath { pub struct CandidatesQuery { pub after: Option, pub limit: Option, + /// Lists only actors with this name, oldest first. + pub name: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ParkedQuery { + pub after: Option, + pub limit: Option, } #[derive(Debug, Deserialize)] @@ -124,6 +135,38 @@ pub async fn restore( respond(park::restore(ctx, path.actor_id, query.namespace, body).await) } +pub async fn parked( + Extension(ctx): Extension, + Path(path): Path, + Query(query): Query, +) -> Response { + respond(parked::list(ctx, path.namespace, query).await) +} + +pub async fn get_delete_cursor( + Extension(ctx): Extension, + Path(path): Path, +) -> Response { + respond(parked::get_delete_cursor(ctx, path.namespace).await) +} + +pub async fn put_delete_cursor( + Extension(ctx): Extension, + Path(path): Path, + body: Bytes, +) -> Response { + respond(parked::put_delete_cursor(ctx, path.namespace, body).await) +} + +pub async fn delete( + Extension(ctx): Extension, + Path(path): Path, + Query(query): Query, + body: Bytes, +) -> Response { + respond(parked::delete(ctx, path.actor_id, query.namespace, body).await) +} + fn respond(result: Result>) -> Response { match result { Ok(body) => ( diff --git a/engine/packages/api-public/src/migration/park.rs b/engine/packages/api-public/src/migration/park.rs index 9c2087fa54..39ccedea78 100644 --- a/engine/packages/api-public/src/migration/park.rs +++ b/engine/packages/api-public/src/migration/park.rs @@ -259,6 +259,8 @@ async fn park( workflow_name, wake_deadline_ts: actor.wake_deadline_ts, wake_signals, + delete_requested_at: None, + deleted_at: None, }; tx.set( &mkeys::parked(actor.actor_id), @@ -290,6 +292,9 @@ pub async fn restore(ctx: ApiCtx, actor_id: Id, namespace: String, body: Bytes) return Ok(proto::RestoreResponse::NotParked); }; let parked = facts::decode_parked(&raw)?; + if parked.delete_requested_at.is_some() { + return Err(errors::Migration::ActorDeleted.build()); + } if request .cutover_ts .is_some_and(|cutover_ts| cutover_ts != parked.cutover_ts) diff --git a/engine/packages/api-public/src/migration/parked.rs b/engine/packages/api-public/src/migration/parked.rs new file mode 100644 index 0000000000..1a91ceffee --- /dev/null +++ b/engine/packages/api-public/src/migration/parked.rs @@ -0,0 +1,460 @@ +//! The `/migration/v2/` routes that delete actors V2 parked after migrating them to V3. +//! +//! A parked record stays after its actor is deleted, so the parked records are the list of what +//! a migration moved out of V2 and how far its deletion got. A deletion run lists a namespace's +//! parked actors, deletes each one, and saves its progress in the namespace's delete cursor so a +//! later run resumes where it stopped. +//! +//! **Delete** destroys a parked actor through its own workflow, so V2's destroy steps clear its +//! state, indexes, KV and SQLite. A parked workflow is silenced and has no listen rows, but a +//! signal sent to it while parked still waits as a pending signal, and gasoline's listen handles +//! the oldest pending signal across every name it listens for. Delete therefore sends the destroy +//! signal while the workflow is still silenced, silences every other pending signal, and only +//! then, in one transaction that sees no other pending signal, writes the destroy listen row, +//! clears the workflow's silence and wakes it. A signal sent after that sorts after the destroy, +//! and the destroy ends the workflow. Every step is idempotent, so a caller retries a failed +//! delete with the same request. + +use anyhow::{Context, Result, bail}; +use axum::body::Bytes; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use futures_util::TryStreamExt; +use gas::db::{Database, debug::DatabaseDebug}; +use pegboard::keys; +use rivet_util::Id; +use universaldb::{ + options::StreamingMode, + utils::IsolationLevel::{Serializable, Snapshot}, +}; +use v2_migration_protocol as proto; + +use super::{ParkedQuery, authorize, decode_body, ensure_local, facts, keys as mkeys}; +use crate::{ctx::ApiCtx, errors}; + +const DEFAULT_LIMIT: usize = 200; +const MAX_LIMIT: usize = 500; + +/// Times a delete silences newly arrived signals before it gives up and leaves the retry to the +/// caller. Each round only finds signals sent during the previous one. +const MAX_ARM_ROUNDS: usize = 8; + +/// `GET /migration/v2/namespaces/{namespace}/parked`: one page of the namespace's parked actors +/// in this datacenter, deleted ones included. +/// +/// Parked records are keyed by actor id alone, so a page scans `limit` records of every namespace +/// and returns the ones in this namespace. A page can therefore be short or empty while `next` is +/// set. +pub async fn list(ctx: ApiCtx, namespace: String, query: ParkedQuery) -> Result> { + let namespace_id = authorize(&ctx, &namespace).await?; + + let limit = query.limit.unwrap_or(DEFAULT_LIMIT); + if limit == 0 || limit > MAX_LIMIT { + return Err(errors::Migration::InvalidRequest { + message: format!("limit must be between 1 and {MAX_LIMIT}"), + } + .build()); + } + let after = match &query.after { + Some(after) => Some(decode_cursor(after)?), + None => None, + }; + + let udb = ctx.pools().udb()?; + let response = udb + .txn("migration_parked_list", |tx| { + let after = after.clone(); + async move { + let (range_start, range_end) = mkeys::parked_subspace().range(); + // The cursor is the last scanned key, so the page starts just after it. + let begin = match after { + Some(mut after) => { + after.push(0x00); + after + } + None => range_start, + }; + + let rows = tx + .get_ranges_keyvalues( + universaldb::RangeOption { + limit: Some(limit), + mode: StreamingMode::WantAll, + ..(begin, range_end).into() + }, + Snapshot, + ) + .map_ok(|entry| (entry.key().to_vec(), entry.value().to_vec())) + .try_collect::>() + .await?; + + let next = if rows.len() == limit { + rows.last().map(|(raw_key, _)| raw_key.clone()) + } else { + None + }; + + let pb = tx.with_subspace(keys::subspace()); + let mut actors = Vec::new(); + for (raw_key, raw_value) in rows { + let actor_id = mkeys::parked_actor_id(&raw_key) + .context("parked record key has no actor id")?; + let actor_namespace_id = pb + .read_opt(&keys::actor::NamespaceIdKey::new(actor_id), Snapshot) + .await?; + if actor_namespace_id != Some(namespace_id) { + continue; + } + + let record = facts::decode_parked(&raw_value)?; + actors.push(proto::ParkedActor { + actor_id: actor_id.as_bytes(), + v3_actor_id: record.v3_actor_id, + generation: record.generation, + cutover_ts: record.cutover_ts, + parked_at: record.parked_at, + delete_requested_at: record.delete_requested_at, + deleted_at: record.deleted_at, + cursor: raw_key, + }); + } + + Ok(proto::ParkedResponse { actors, next }) + } + }) + .await?; + + proto::encode(&response) +} + +/// `GET /migration/v2/namespaces/{namespace}/parked/delete-cursor`. +pub async fn get_delete_cursor(ctx: ApiCtx, namespace: String) -> Result> { + let namespace_id = authorize(&ctx, &namespace).await?; + + let udb = ctx.pools().udb()?; + let cursor = udb + .txn("migration_delete_cursor_get", |tx| async move { + let raw = tx + .get(&mkeys::delete_cursor(namespace_id), Serializable) + .await?; + Ok(raw.map(|raw| raw.to_vec()).filter(|raw| !raw.is_empty())) + }) + .await?; + + proto::encode(&proto::DeleteCursor { cursor }) +} + +/// `PUT /migration/v2/namespaces/{namespace}/parked/delete-cursor`. An unset cursor clears it. +pub async fn put_delete_cursor(ctx: ApiCtx, namespace: String, body: Bytes) -> Result> { + let namespace_id = authorize(&ctx, &namespace).await?; + authorize_delete(&ctx, &namespace).await?; + let request = decode_body::(&body)?; + if let Some(cursor) = &request.cursor + && mkeys::parked_actor_id(cursor).is_none() + { + return Err(errors::Migration::InvalidRequest { + message: "cursor is not a parked actor cursor".to_string(), + } + .build()); + } + + let udb = ctx.pools().udb()?; + udb.txn("migration_delete_cursor_put", |tx| { + let cursor = request.cursor.clone(); + async move { + let key = mkeys::delete_cursor(namespace_id); + match cursor { + Some(cursor) => tx.set(&key, &cursor), + None => tx.clear(&key), + } + Ok(()) + } + }) + .await?; + + proto::encode(&request) +} + +/// What one delete request found in the parked record. +enum DeleteStep { + NotParked, + Deleted, + /// The destroy is armed: the workflow is awake or already destroying the actor. + Armed, + /// A delete was requested but the workflow is still parked, so the destroy still has to be + /// armed. + Arm { + workflow_id: Id, + workflow_name: String, + }, +} + +/// `POST /migration/v2/actors/{actor_id}/delete`. +pub async fn delete(ctx: ApiCtx, actor_id: Id, namespace: String, body: Bytes) -> Result> { + ensure_local(&ctx, actor_id)?; + let namespace_id = authorize(&ctx, &namespace).await?; + authorize_delete(&ctx, &namespace).await?; + let request = decode_body::(&body)?; + + let step = request_delete(&ctx, actor_id, namespace_id, &request).await?; + let response = match step { + DeleteStep::NotParked => proto::DeleteResponse::NotParked, + DeleteStep::Deleted => proto::DeleteResponse::Deleted, + DeleteStep::Armed => proto::DeleteResponse::Deleting, + DeleteStep::Arm { + workflow_id, + workflow_name, + } => { + arm_destroy(&ctx, actor_id, workflow_id, &workflow_name).await?; + proto::DeleteResponse::Deleting + } + }; + + proto::encode(&response) +} + +/// Records the delete request in the parked record, or reports how far an earlier one got. Marks +/// the actor deleted once its workflow finished. +async fn request_delete( + ctx: &ApiCtx, + actor_id: Id, + namespace_id: Id, + request: &proto::DeleteRequest, +) -> Result { + let udb = ctx.pools().udb()?; + udb.txn("migration_delete_request", |tx| async move { + let pb = tx.with_subspace(keys::subspace()); + let actor_namespace_id = pb + .read_opt(&keys::actor::NamespaceIdKey::new(actor_id), Serializable) + .await?; + if actor_namespace_id != Some(namespace_id) { + return Err(errors::Migration::ActorNotFound.build()); + } + + let Some(raw) = tx.get(&mkeys::parked(actor_id), Serializable).await? else { + return Ok(DeleteStep::NotParked); + }; + let mut record = facts::decode_parked(&raw)?; + if request.v3_actor_id[..] != record.v3_actor_id[..] { + return Err(errors::Migration::InvalidRequest { + message: "the parked actor was migrated to a different V3 actor".to_string(), + } + .build()); + } + if record.deleted_at.is_some() { + return Ok(DeleteStep::Deleted); + } + + let workflow_id = Id::from_slice(&record.workflow_id).context("parked workflow id")?; + let workflow_name = record.workflow_name.clone(); + + if record.delete_requested_at.is_none() { + // Only an actor still held by its cutover is parked. The destroy rewrites the + // destroy timestamp, so this holds only before the first delete request. + let destroy_ts = pb + .read_opt(&keys::actor::DestroyTsKey::new(actor_id), Serializable) + .await?; + if destroy_ts != Some(record.cutover_ts) { + bail!( + "parked actor {actor_id} has destroy timestamp {destroy_ts:?}, not its cutover {}", + record.cutover_ts + ); + } + + record.delete_requested_at = Some(rivet_util::timestamp::now()); + tx.set(&mkeys::parked(actor_id), &facts::encode_parked(record)?); + return Ok(DeleteStep::Arm { + workflow_id, + workflow_name, + }); + } + + // The silence stays until the destroy is armed, so a silenced workflow still needs it. + if tx + .get(&mkeys::silence_ts(workflow_id), Serializable) + .await? + .is_some() + { + return Ok(DeleteStep::Arm { + workflow_id, + workflow_name, + }); + } + + if first_row(&tx, &mkeys::output_subspace(workflow_id)).await? { + record.deleted_at = Some(rivet_util::timestamp::now()); + tx.set(&mkeys::parked(actor_id), &facts::encode_parked(record)?); + return Ok(DeleteStep::Deleted); + } + + Ok(DeleteStep::Armed) + }) + .await +} + +/// Sends the destroy signal to the silenced workflow, silences every other pending signal, then +/// wakes the workflow with the destroy as its only pending signal. +async fn arm_destroy( + ctx: &ApiCtx, + actor_id: Id, + workflow_id: Id, + workflow_name: &str, +) -> Result<()> { + let destroy_name = ::NAME; + let db = gas::db::DatabaseKv::new(ctx.config().clone(), ctx.pools().clone()).await?; + + if pending_signals(ctx, workflow_id) + .await? + .iter() + .all(|(signal_name, _)| signal_name != destroy_name) + { + ctx.signal(pegboard::workflows::actor2::Destroy {}) + .to_workflow_id(workflow_id) + .send() + .await + .context("send destroy signal to parked actor workflow")?; + } + + for _ in 0..MAX_ARM_ROUNDS { + let others = pending_signals(ctx, workflow_id) + .await? + .into_iter() + .filter(|(signal_name, _)| signal_name != destroy_name) + .map(|(_, signal_id)| signal_id) + .collect::>(); + if !others.is_empty() { + tracing::info!( + ?actor_id, + count = others.len(), + "silencing signals sent to a parked actor before deleting it" + ); + DatabaseDebug::silence_signals(&*db, others).await?; + } + + if wake_for_destroy(ctx, workflow_id, workflow_name, destroy_name).await? { + return Ok(()); + } + } + + bail!("signals kept arriving for parked actor {actor_id}; retry the delete") +} + +/// Wakes the workflow when the destroy is its only pending signal, in one transaction that a new +/// pending signal conflicts with. Returns `false` when another signal arrived first. +async fn wake_for_destroy( + ctx: &ApiCtx, + workflow_id: Id, + workflow_name: &str, + destroy_name: &str, +) -> Result { + let udb = ctx.pools().udb()?; + udb.txn("migration_delete_arm", |tx| async move { + let pending = tx + .get_ranges_keyvalues( + universaldb::RangeOption { + mode: StreamingMode::WantAll, + ..(&mkeys::pending_signal_subspace(workflow_id)).into() + }, + Serializable, + ) + .map_ok(|entry| entry.key().to_vec()) + .try_collect::>() + .await?; + let mut has_destroy = false; + for raw_key in &pending { + let (signal_name, _ts, _signal_id) = mkeys::pending_signal_subspace(workflow_id) + .unpack::<(String, i64, Id)>(raw_key) + .context("unpack pending signal key")?; + if signal_name != destroy_name { + return Ok(false); + } + has_destroy = true; + } + if !has_destroy { + bail!("the destroy signal of workflow {workflow_id} is no longer pending"); + } + + let listen_row = mkeys::wake_signal_subspace(workflow_id).pack(&(destroy_name,)); + tx.set(&listen_row, &[]); + tx.clear(&mkeys::silence_ts(workflow_id)); + tx.set( + &mkeys::immediate_wake_row(workflow_name, workflow_id, rivet_util::timestamp::now()), + &mkeys::wake_row_nonce(), + ); + + Ok(true) + }) + .await +} + +/// The workflow's pending signals as `(name, signal id)`. +async fn pending_signals(ctx: &ApiCtx, workflow_id: Id) -> Result> { + let udb = ctx.pools().udb()?; + udb.txn("migration_delete_pending_signals", |tx| async move { + let subspace = mkeys::pending_signal_subspace(workflow_id); + let keys = tx + .get_ranges_keyvalues( + universaldb::RangeOption { + mode: StreamingMode::WantAll, + ..(&subspace).into() + }, + Serializable, + ) + .map_ok(|entry| entry.key().to_vec()) + .try_collect::>() + .await?; + + keys.iter() + .map(|raw_key| { + let (signal_name, _ts, signal_id) = subspace + .unpack::<(String, i64, Id)>(raw_key) + .context("unpack pending signal key")?; + Ok((signal_name, signal_id)) + }) + .collect() + }) + .await +} + +/// Deleting destroys actors, so it also needs a token that may delete every actor in the +/// namespace. +async fn authorize_delete(ctx: &ApiCtx, namespace: &str) -> Result<()> { + ctx.auth( + rivet_auth::AccessNamespaceScope::Name(namespace.to_string()), + rivet_auth::ResourceKind::Actor, + rivet_auth::TargetScope::Any, + rivet_auth::OperationKind::Delete, + ) + .await +} + +fn decode_cursor(cursor: &str) -> Result> { + let raw = URL_SAFE_NO_PAD.decode(cursor).map_err(|_| { + errors::Migration::InvalidRequest { + message: "after is not a valid cursor".to_string(), + } + .build() + })?; + if mkeys::parked_actor_id(&raw).is_none() { + return Err(errors::Migration::InvalidRequest { + message: "after is not a parked actor cursor".to_string(), + } + .build()); + } + Ok(raw) +} + +async fn first_row( + tx: &universaldb::Transaction, + subspace: &universaldb::utils::Subspace, +) -> Result { + let mut stream = tx.get_ranges_keyvalues( + universaldb::RangeOption { + limit: Some(1), + mode: StreamingMode::Small, + ..subspace.into() + }, + Serializable, + ); + + Ok(stream.try_next().await?.is_some()) +} diff --git a/engine/packages/api-public/src/router.rs b/engine/packages/api-public/src/router.rs index 069d35eba2..4cef8716f4 100644 --- a/engine/packages/api-public/src/router.rs +++ b/engine/packages/api-public/src/router.rs @@ -164,6 +164,18 @@ pub async fn router( "/migration/v1/actors/{actor_id}/restore", axum::routing::post(migration::restore), ) + .route( + "/migration/v2/namespaces/{namespace}/parked", + axum::routing::get(migration::parked), + ) + .route( + "/migration/v2/namespaces/{namespace}/parked/delete-cursor", + axum::routing::get(migration::get_delete_cursor).put(migration::put_delete_cursor), + ) + .route( + "/migration/v2/actors/{actor_id}/delete", + axum::routing::post(migration::delete), + ) // MARK: Middleware (must go after all routes) // Add CORS layer that mirrors the request origin .layer( diff --git a/engine/packages/engine/tests/v2_migration_api.rs b/engine/packages/engine/tests/v2_migration_api.rs index 84b3f17b55..09f22a9c5a 100644 --- a/engine/packages/engine/tests/v2_migration_api.rs +++ b/engine/packages/engine/tests/v2_migration_api.rs @@ -1095,3 +1095,375 @@ async fn export_running_kv(dc: &common::TestDatacenter, actor_id: Id) -> Vec<(Ve .unwrap(); keys.into_iter().zip(values).collect() } + +// MARK: Parked actor deletion + +fn url_v2(dc: &common::TestDatacenter, path: &str) -> String { + format!("http://127.0.0.1:{}/migration/v2/{path}", dc.guard_port()) +} + +async fn send_v2( + dc: &common::TestDatacenter, + method: reqwest::Method, + path: &str, + body: Vec, +) -> Result> { + let res = reqwest::Client::new() + .request(method, url_v2(dc, path)) + .bearer_auth(common::TEST_ADMIN_TOKEN) + .body(body) + .send() + .await?; + let status = res.status(); + let body = res.bytes().await?.to_vec(); + if !status.is_success() { + bail!( + "{path} returned {status}: {}", + String::from_utf8_lossy(&body) + ); + } + Ok(body) +} + +async fn parked_page( + dc: &common::TestDatacenter, + namespace: &str, + query: &str, +) -> proto::ParkedResponse { + let body = send_v2( + dc, + reqwest::Method::GET, + &format!("namespaces/{namespace}/parked?{query}"), + Vec::new(), + ) + .await + .unwrap(); + proto::decode(&body).unwrap() +} + +async fn delete_cursor(dc: &common::TestDatacenter, namespace: &str) -> Option> { + let body = send_v2( + dc, + reqwest::Method::GET, + &format!("namespaces/{namespace}/parked/delete-cursor"), + Vec::new(), + ) + .await + .unwrap(); + proto::decode::(&body).unwrap().cursor +} + +async fn put_delete_cursor(dc: &common::TestDatacenter, namespace: &str, cursor: Option>) { + send_v2( + dc, + reqwest::Method::PUT, + &format!("namespaces/{namespace}/parked/delete-cursor"), + proto::encode(&proto::DeleteCursor { cursor }).unwrap(), + ) + .await + .unwrap(); +} + +async fn delete_parked( + dc: &common::TestDatacenter, + namespace: &str, + actor_id: Id, +) -> proto::DeleteResponse { + let body = send_v2( + dc, + reqwest::Method::POST, + &format!("actors/{actor_id}/delete?namespace={namespace}"), + proto::encode(&proto::DeleteRequest { + v3_actor_id: actor_id.as_bytes(), + }) + .unwrap(), + ) + .await + .unwrap(); + proto::decode(&body).unwrap() +} + +async fn actor_namespace_id(dc: &common::TestDatacenter, actor_id: Id) -> Id { + dc.workflow_ctx + .udb() + .unwrap() + .txn("test_read_namespace_id", |tx| async move { + tx.with_subspace(pegboard::keys::subspace()) + .read( + &pegboard::keys::actor::NamespaceIdKey::new(actor_id), + Serializable, + ) + .await + }) + .await + .unwrap() +} + +/// Cuts over and confirms a seeded actor, so V2 parks it with the actor's own id as its V3 id. +async fn park_seeded(dc: &common::TestDatacenter, seeded: &Seeded) -> i64 { + let actor_id = seeded.actor_id; + let namespace = &seeded.namespace; + let c = candidate(dc, namespace, actor_id).await; + let cutover_ts = rivet_util::timestamp::now(); + let cut: proto::CutoverResponse = post( + dc, + &format!("actors/{actor_id}/cutover?namespace={namespace}"), + &proto::CutoverRequest { + generation: 1, + cutover_ts, + }, + ) + .await + .unwrap(); + assert_eq!(cut, proto::CutoverResponse::Cut); + let confirmed: proto::ConfirmResponse = post( + dc, + &format!("actors/{actor_id}/confirm?namespace={namespace}"), + &proto::ConfirmRequest { + generation: 1, + sleep_ts: c.sleep_ts.unwrap(), + wake_deadline_ts: c.wake_deadline_ts, + cutover_ts, + horizon_ms: 0, + v3_actor_id: actor_id.as_bytes(), + }, + ) + .await + .unwrap(); + assert_eq!(confirmed, proto::ConfirmResponse::Confirmed); + cutover_ts +} + +/// The name filter lists only that name's actors, and clamps a cursor from the namespace's whole +/// index order: one before the name's rows starts at its first row, one past them lists nothing. +#[test] +fn migration_lists_candidates_of_one_name() { + common::run( + common::TestOpts::new(1).with_timeout(60), + |ctx| async move { + let dc = ctx.leader_dc(); + let seeded = seed_sleeping_actor(dc, 3_600_000).await; + let actor_id = seeded.actor_id; + let namespace = seeded.namespace.clone(); + let namespace_id = actor_namespace_id(dc, actor_id).await; + + let list = |query: String| { + let namespace = namespace.clone(); + async move { + let body = get_bytes(dc, &format!("namespaces/{namespace}/candidates?{query}")) + .await + .unwrap(); + proto::decode::(&body).unwrap() + } + }; + let ids = |page: &proto::CandidatesResponse| { + page.candidates + .iter() + .map(|c| c.actor_id.clone()) + .collect::>() + }; + + let named = list(format!("limit=500&name={ACTOR_NAME}")).await; + assert_eq!(ids(&named), vec![actor_id.as_bytes()]); + assert_eq!(named.next, None); + let other = list("limit=500&name=other-actor".to_string()).await; + assert!(other.candidates.is_empty()); + + // Cursors from rows of other names, as an unfiltered listing would have written. + let row = |name: &str| { + pegboard::keys::subspace().pack(&pegboard::keys::ns::ActiveActorKey::new( + namespace_id, + name.to_string(), + 0, + Id::new_v1(dc.config.dc_label()), + )) + }; + let encode = + |raw: Vec| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(raw); + + let before = list(format!( + "limit=500&name={ACTOR_NAME}&after={}", + encode(row("a-actor")) + )) + .await; + assert_eq!( + ids(&before), + vec![actor_id.as_bytes()], + "a cursor before the name's rows starts at its first row" + ); + + let past = list(format!( + "limit=500&name={ACTOR_NAME}&after={}", + encode(row("z-actor")) + )) + .await; + assert!(past.candidates.is_empty()); + assert_eq!( + past.next, None, + "a cursor past the name's rows ends the listing" + ); + + // The actor's own cursor still resumes right after it. + let own = list(format!( + "limit=500&name={ACTOR_NAME}&after={}", + encode(named.candidates[0].cursor.clone()) + )) + .await; + assert!(own.candidates.is_empty()); + + drop(seeded.envoy); + }, + ); +} + +/// A parked actor is listed, deleted through its own workflow with its KV, and stays listed as +/// deleted. A signal sent while it was parked must not wake it in V2, and restore is refused. +#[test] +fn migration_deletes_a_parked_real_actor2() { + common::run( + common::TestOpts::new(1).with_timeout(120), + |ctx| async move { + let dc = ctx.leader_dc(); + let mut seeded = seed_sleeping_actor(dc, 3_600_000).await; + let actor_id = seeded.actor_id; + let workflow_id = seeded.workflow_id; + let namespace = seeded.namespace.clone(); + let cutover_ts = park_seeded(dc, &seeded).await; + + // A record without a delete is written as v1, which older V2 binaries read. + let raw = dc + .workflow_ctx + .udb() + .unwrap() + .txn("test_read_parked", |tx| async move { + Ok(tx + .get(&mkeys::parked(actor_id), Serializable) + .await? + .map(|raw| raw.to_vec())) + }) + .await + .unwrap() + .expect("parked record"); + assert_eq!(u16::from_le_bytes([raw[0], raw[1]]), 1); + let record = + ::deserialize_with_embedded_version(&raw) + .unwrap(); + assert_eq!(record.cutover_ts, cutover_ts); + assert_eq!( + (record.delete_requested_at, record.deleted_at), + (None, None) + ); + + // The listing shows the actor in its namespace only. + let page = parked_page(dc, &namespace, "limit=500").await; + let listed = page + .actors + .iter() + .find(|a| a.actor_id == actor_id.as_bytes()) + .expect("parked actor should be listed"); + assert_eq!(listed.cutover_ts, cutover_ts); + assert_eq!(listed.delete_requested_at, None); + let (other_namespace, _) = common::setup_test_namespace(dc).await; + let other = parked_page(dc, &other_namespace, "limit=500").await; + assert!( + other + .actors + .iter() + .all(|a| a.actor_id != actor_id.as_bytes()) + ); + + // The delete cursor round-trips and clears. + assert_eq!(delete_cursor(dc, &namespace).await, None); + put_delete_cursor(dc, &namespace, Some(listed.cursor.clone())).await; + assert_eq!( + delete_cursor(dc, &namespace).await, + Some(listed.cursor.clone()) + ); + let after = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&listed.cursor); + let resumed = parked_page(dc, &namespace, &format!("limit=500&after={after}")).await; + assert!( + resumed + .actors + .iter() + .all(|a| a.actor_id != actor_id.as_bytes()) + ); + put_delete_cursor(dc, &namespace, None).await; + assert_eq!(delete_cursor(dc, &namespace).await, None); + + // A wake sent while parked waits as a pending signal without waking the workflow. + dc.workflow_ctx + .signal(pegboard::workflows::actor2::Wake {}) + .to_workflow_id(workflow_id) + .send() + .await + .unwrap(); + assert_eq!( + raw_subspace_len(dc, mkeys::pending_signal_subspace(workflow_id)).await, + 1 + ); + + assert_eq!( + delete_parked(dc, &namespace, actor_id).await, + proto::DeleteResponse::Deleting + ); + assert!(!raw_exists(dc, mkeys::silence_ts(workflow_id)).await); + + common::wait_with_poll(Duration::from_secs(30), Duration::from_millis(200), || { + let namespace = namespace.clone(); + async move { + match delete_parked(dc, &namespace, actor_id).await { + proto::DeleteResponse::Deleted => Some(()), + proto::DeleteResponse::Deleting => None, + proto::DeleteResponse::NotParked => panic!("the parked record went away"), + } + } + }) + .await + .expect("the parked actor should be deleted"); + + // The workflow destroyed the actor in V2 without starting it, and cleared its KV. + assert_eq!( + wait_for_start(&mut seeded.lifecycle_rx, actor_id, Duration::from_secs(2)).await, + None, + "the stray wake must not start the actor" + ); + assert!( + raw_subspace_len(dc, mkeys::output_subspace(workflow_id)).await > 0, + "the workflow completed" + ); + assert_ne!(destroy_ts(dc, actor_id).await, Some(cutover_ts)); + assert!(export_running_kv(dc, actor_id).await.is_empty()); + + // The record stays as the record of the delete, written as v2. + let page = parked_page(dc, &namespace, "limit=500").await; + let listed = page + .actors + .iter() + .find(|a| a.actor_id == actor_id.as_bytes()) + .expect("a deleted actor stays listed"); + assert!(listed.delete_requested_at.is_some()); + assert!(listed.deleted_at.is_some()); + assert_eq!( + delete_parked(dc, &namespace, actor_id).await, + proto::DeleteResponse::Deleted + ); + + let restore = post::<_, proto::RestoreResponse>( + dc, + &format!("actors/{actor_id}/restore?namespace={namespace}"), + &proto::RestoreRequest { + cutover_ts: Some(cutover_ts), + v3_actor_id: Some(actor_id.as_bytes()), + }, + ) + .await + .unwrap_err(); + assert!( + restore.to_string().contains("actor_deleted"), + "restore after delete: {restore:#}" + ); + + drop(seeded.envoy); + }, + ); +} diff --git a/engine/packages/universaldb/src/utils/keys.rs b/engine/packages/universaldb/src/utils/keys.rs index fca23c3c5e..0c0195484c 100644 --- a/engine/packages/universaldb/src/utils/keys.rs +++ b/engine/packages/universaldb/src/utils/keys.rs @@ -173,4 +173,5 @@ define_keys! { (145, MIGRATION, "migration"), (146, PARKED, "parked"), (147, UNCUT, "uncut"), + (148, DELETE_CURSOR, "delete_cursor"), } diff --git a/engine/sdks/rust/v2-migration-protocol/src/lib.rs b/engine/sdks/rust/v2-migration-protocol/src/lib.rs index 98f48277f1..bea40d90de 100644 --- a/engine/sdks/rust/v2-migration-protocol/src/lib.rs +++ b/engine/sdks/rust/v2-migration-protocol/src/lib.rs @@ -1,14 +1,16 @@ -//! Wire types for the V2 public API's `/migration/v1/` routes. +//! Wire types for the V2 public API's `/migration/` routes. //! -//! Request and response bodies are raw BARE: the `/v1` path pins the schema version for both peers. -//! The parked record is persisted, so it alone carries a vbare version header (see [`versioned`]). +//! Request and response bodies are raw BARE: a route's path pins the schema version of its bodies +//! for both peers. The `/migration/v1/` routes keep the types they had in v1, which are +//! byte-identical in v2, and the routes added with v2 live under `/migration/v2/`. The parked +//! record is persisted, so it alone carries a vbare version header (see [`versioned`]). use anyhow::{Context, Result, bail}; pub mod generated; pub mod versioned; -pub use generated::v1::*; +pub use generated::v2::*; /// Content type of the streamed export response. pub const EXPORT_CONTENT_TYPE: &str = "application/x-rivet-v2-migration"; diff --git a/engine/sdks/rust/v2-migration-protocol/src/versioned.rs b/engine/sdks/rust/v2-migration-protocol/src/versioned.rs index 4cc2cc6bdc..a9b7d047fb 100644 --- a/engine/sdks/rust/v2-migration-protocol/src/versioned.rs +++ b/engine/sdks/rust/v2-migration-protocol/src/versioned.rs @@ -3,28 +3,31 @@ use anyhow::{Result, bail}; use vbare::OwnedVersionedData; -use crate::generated::v1; +use crate::generated::{v1, v2}; pub enum ParkedRecord { V1(v1::ParkedRecord), + V2(v2::ParkedRecord), } impl OwnedVersionedData for ParkedRecord { - type Latest = v1::ParkedRecord; + type Latest = v2::ParkedRecord; - fn wrap_latest(latest: v1::ParkedRecord) -> Self { - ParkedRecord::V1(latest) + fn wrap_latest(latest: v2::ParkedRecord) -> Self { + ParkedRecord::V2(latest) } fn unwrap_latest(self) -> Result { match self { - ParkedRecord::V1(data) => Ok(data), + ParkedRecord::V2(data) => Ok(data), + ParkedRecord::V1(_) => bail!("version not latest"), } } fn deserialize_version(payload: &[u8], version: u16) -> Result { match version { 1 => Ok(ParkedRecord::V1(serde_bare::from_slice(payload)?)), + 2 => Ok(ParkedRecord::V2(serde_bare::from_slice(payload)?)), _ => bail!("invalid parked record version: {version}"), } } @@ -32,14 +35,59 @@ impl OwnedVersionedData for ParkedRecord { fn serialize_version(self, _version: u16) -> Result> { match self { ParkedRecord::V1(data) => serde_bare::to_vec(&data).map_err(Into::into), + ParkedRecord::V2(data) => serde_bare::to_vec(&data).map_err(Into::into), } } fn deserialize_converters() -> Vec Result> { - vec![Ok] + vec![Self::v1_to_v2] } fn serialize_converters() -> Vec Result> { - vec![Ok] + vec![Self::v2_to_v1] + } +} + +impl ParkedRecord { + /// A record parked before deletes existed has no delete in progress. + fn v1_to_v2(self) -> Result { + match self { + ParkedRecord::V1(record) => Ok(ParkedRecord::V2(v2::ParkedRecord { + generation: record.generation, + cutover_ts: record.cutover_ts, + parked_at: record.parked_at, + v3_actor_id: record.v3_actor_id, + workflow_id: record.workflow_id, + workflow_name: record.workflow_name, + wake_deadline_ts: record.wake_deadline_ts, + wake_signals: record.wake_signals, + delete_requested_at: None, + deleted_at: None, + })), + ParkedRecord::V2(_) => bail!("unexpected parked record version"), + } + } + + /// A v1 record has no delete fields, so a record with a delete in progress cannot be written + /// as v1. + fn v2_to_v1(self) -> Result { + match self { + ParkedRecord::V2(record) => { + if record.delete_requested_at.is_some() || record.deleted_at.is_some() { + bail!("a parked record with a delete in progress has no v1 form"); + } + Ok(ParkedRecord::V1(v1::ParkedRecord { + generation: record.generation, + cutover_ts: record.cutover_ts, + parked_at: record.parked_at, + v3_actor_id: record.v3_actor_id, + workflow_id: record.workflow_id, + workflow_name: record.workflow_name, + wake_deadline_ts: record.wake_deadline_ts, + wake_signals: record.wake_signals, + })) + } + ParkedRecord::V1(_) => bail!("unexpected parked record version"), + } } } diff --git a/engine/sdks/schemas/v2-migration-protocol/v2.bare b/engine/sdks/schemas/v2-migration-protocol/v2.bare new file mode 100644 index 0000000000..fc877634be --- /dev/null +++ b/engine/sdks/schemas/v2-migration-protocol/v2.bare @@ -0,0 +1,295 @@ +# V2 to V3 actor migration protocol. +# +# Every request and response body of the V2 public API's `/migration/v1/` routes is one of these +# types. The route's path pins the schema version of its bodies, so request and response bodies +# carry no version header: the `/migration/v1/` routes use the types they had in v1, and the routes +# added with this version live under `/migration/v2/`. V3's migrator holds a copy of this file. +# `ParkedRecord` is persisted in V2 and is the one type stored with a vbare version header. + +# MARK: Candidates + +type Candidate struct { + actorId: data + workflowId: data + name: str + key: optional + poolName: str + createTs: i64 + # 1 is the old actor workflow, 2 is actor2. + version: u8 + # 0 when the actor has never been allocated. + generation: u32 + sleepTs: optional + # An envoy key or a connectable marker is present. + allocated: bool + destroyTs: optional + # The workflow's wake deadline: an alarm or a retry. + wakeDeadlineTs: optional + hibernating: bool + # The actor's SQLite still lives in the KV-backed v1 format, or its v1 import is unfinished. + sqliteV1: bool + # The actor was already migrated and parked. + parked: bool + # Pages in the published SQLite v2 head, 0 when the actor has none. + dbSizePages: u32 + # The datastore's sampled estimate of the actor's KV bytes. Small actors may read as 0. + kvBytesEstimate: u64 + # Exclusive cursor that resumes the listing right after this candidate, so a caller that admits + # only part of a page continues from the last candidate it handled. Empty for a read by id. + cursor: data +} + +type CandidatesResponse struct { + candidates: list + # Exclusive cursor for the next page. None means the listing reached the end. + next: optional +} + +# MARK: Export + +type SqliteHead struct { + headTxid: u64 + dbSizePages: u32 + pageSize: u32 +} + +type ExportHeader struct { + generation: u32 + sleepTs: i64 + wakeDeadlineTs: optional + name: str + key: optional + poolName: str + createTs: i64 + kvBytesEstimate: u64 + sqlite: optional +} + +type KvEntry struct { + key: data + value: data + version: data + updateTs: i64 +} + +type KvBatch struct { + entries: list +} + +type PageBatch struct { + firstPgno: u32 + pages: list +} + +# Emitted after each internal transaction. `cursor` is an encoded `ExportCursor` the client passes +# back as `resume` to continue a broken stream. +type ExportFence struct { + cursor: data +} + +type ExportEnd struct { + kvEntries: u64 + kvBytes: u64 + pages: u32 + # Chained xxh3-128 over every KvBatch and PageBatch frame, in stream order. + digest: data +} + +type AbortReason enum { + FENCE_MOVED + DESTROYED + INELIGIBLE +} + +type ExportAbort struct { + reason: AbortReason +} + +type Frame union { + ExportHeader | + KvBatch | + PageBatch | + ExportFence | + ExportEnd | + ExportAbort +} + +# Opaque to the client. The server checks the fence it carries before resuming. +type ExportCursor struct { + generation: u32 + sleepTs: i64 + headTxid: optional + # The last KV key already sent. None means no KV entry was sent yet. + afterKvKey: optional + kvDone: bool + # The next SQLite page to send. + nextPgno: u32 + digest: data + kvEntries: u64 + kvBytes: u64 + pages: u32 +} + +# MARK: Cutover + +type CutoverRequest struct { + generation: u32 + cutoverTs: i64 +} + +type IneligibleReason enum { + NOT_SLEEPING + ALLOCATED + HIBERNATING + ACTOR_V1 + SQLITE_V1 +} + +type Cut void + +type AlreadyCut void + +type Woke void + +type Destroyed void + +type Ineligible struct { + reason: IneligibleReason +} + +type CutoverResponse union { + Cut | + AlreadyCut | + Woke | + Destroyed | + Ineligible +} + +# MARK: Confirm + +type ConfirmRequest struct { + generation: u32 + sleepTs: i64 + wakeDeadlineTs: optional + cutoverTs: i64 + horizonMs: i64 + v3ActorId: data +} + +type WokeReason enum { + NOT_CUT + GENERATION_MOVED + SLEEP_MOVED + ALLOCATED + HIBERNATING + WORKER_RUNNING + PENDING_SIGNAL + DEADLINE_MOVED + DEADLINE_SOON + SILENCED +} + +type Confirmed void + +type AlreadyConfirmed void + +type ConfirmWoke struct { + reason: WokeReason +} + +type ConfirmResponse union { + Confirmed | + AlreadyConfirmed | + ConfirmWoke | + Destroyed +} + +# MARK: Restore + +# `cutoverTs` must match the parked record when set. Unset restores whatever is parked, for +# recovery, which knows the actor but not its cutover. +type RestoreRequest struct { + cutoverTs: optional + # When set, restore refuses unless the parked record names this V3 actor. + v3ActorId: optional +} + +type Restored void + +type NotParked void + +type RestoreResponse union { + Restored | + NotParked +} + +# MARK: Parked list + +# One actor of a namespace that V2 parked after migrating it to V3. Returned by +# `GET /migration/v2/namespaces/{namespace}/parked`. +type ParkedActor struct { + actorId: data + v3ActorId: data + # The generation the actor was parked at, which names the export V3 copied and backed up. + generation: u32 + cutoverTs: i64 + parkedAt: i64 + # Set by the first delete request. + deleteRequestedAt: optional + # Set once the actor's workflow finished destroying it. + deletedAt: optional + # Exclusive cursor that resumes the listing right after this actor. + cursor: data +} + +type ParkedResponse struct { + actors: list + # Exclusive cursor for the next page. None means the listing reached the end. + next: optional +} + +# The deletion cursor V2 keeps per namespace and datacenter for a deletion run to resume from: +# the `cursor` of the last parked actor the run finished, which a listing passes as `after`. +# Read with `GET` and written with `PUT` on +# `/migration/v2/namespaces/{namespace}/parked/delete-cursor`. +type DeleteCursor struct { + cursor: optional +} + +# MARK: Delete + +# `POST /migration/v2/actors/{actor_id}/delete`: destroys a parked actor in V2, with its KV and +# SQLite data. The first request clears every signal sent while it was parked and sends the +# workflow a destroy signal; later requests report whether the destroy finished. +type DeleteRequest struct { + # Refused unless the parked record names this V3 actor. + v3ActorId: data +} + +type Deleting void + +type Deleted void + +type DeleteResponse union { + Deleting | + Deleted | + NotParked +} + +# MARK: Parked record + +# Stored at `[MIGRATION, PARKED, actor_id]` with a vbare version header. Holds the wake index rows +# that park removed so restore can write them back, and the progress of a delete. Restore refuses +# once a delete was requested. +type ParkedRecord struct { + generation: u32 + cutoverTs: i64 + parkedAt: i64 + v3ActorId: data + workflowId: data + workflowName: str + wakeDeadlineTs: optional + wakeSignals: list + deleteRequestedAt: optional + deletedAt: optional +}