Skip to content
Merged
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
145 changes: 107 additions & 38 deletions engine/packages/api-public/src/migration/candidates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
//! V2 applies no eligibility rule. It returns raw facts so policy such as the minimum sleep age
//! or the largest copy stays in the migrator's configuration.

use std::time::{Duration, Instant};

use anyhow::{Context, Result};
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use futures_util::{StreamExt, TryStreamExt};
Expand All @@ -17,8 +19,9 @@ use crate::{ctx::ApiCtx, errors};

const DEFAULT_LIMIT: usize = 200;
const MAX_LIMIT: usize = 500;
/// Actors whose facts are read concurrently within the page's transaction.
/// Actors whose facts are read concurrently within one transaction.
const READ_CONCURRENCY: usize = 32;
const EARLY_TXN_TIMEOUT: Duration = Duration::from_millis(2500);

pub async fn candidates(ctx: ApiCtx, namespace: String, query: CandidatesQuery) -> Result<Vec<u8>> {
let namespace_id = authorize(&ctx, &namespace).await?;
Expand Down Expand Up @@ -78,12 +81,18 @@ pub async fn candidates(ctx: ApiCtx, namespace: String, query: CandidatesQuery)
.hibernating_request_eligible_threshold(),
);
let udb = ctx.pools().udb()?;
let response = udb
.txn("migration_candidates", |tx| {

// The index scan and the facts reads run in separate transactions, so a page of actors never
// shares one transaction's time limit.
let (index_rows, last_key, has_more) = udb
.txn("migration_candidates_index", |tx| {
let after = after.clone();
let range_start = range_start.clone();
let range_end = range_end.clone();
async move {
let start = Instant::now();
let tx = tx.with_subspace(keys::subspace());

// The cursor is the last returned key, so the page starts just after it.
let begin = match after {
Some(mut after) => {
Expand All @@ -93,46 +102,106 @@ pub async fn candidates(ctx: ApiCtx, namespace: String, query: CandidatesQuery)
None => range_start,
};

let index_rows = tx
.get_ranges_keyvalues(
universaldb::RangeOption {
limit: Some(limit),
mode: StreamingMode::WantAll,
..(begin, range_end).into()
},
Snapshot,
)
.map(|entry| {
let entry = entry?;
let key = tx
.with_subspace(keys::subspace())
.unpack::<keys::ns::ActiveActorKey>(entry.key())?;
Ok::<_, anyhow::Error>((entry.key().to_vec(), key.actor_id))
})
.try_collect::<Vec<_>>()
.await?;

let next = if index_rows.len() == limit {
index_rows.last().map(|(raw_key, _)| raw_key.clone())
} else {
None
};
let mut stream = tx.get_ranges_keyvalues(
universaldb::RangeOption {
limit: Some(limit),
mode: StreamingMode::Iterator,
..(begin, range_end).into()
},
Snapshot,
);

let mut index_rows = Vec::new();
let mut last_key = None;
let mut scanned = 0;
let mut timed_out = false;

while let Some(entry) = stream.try_next().await? {
scanned += 1;
last_key = Some(entry.key().to_vec());

match tx.unpack::<keys::ns::ActiveActorKey>(entry.key()) {
Ok(key) => index_rows.push((entry.key().to_vec(), key.actor_id)),
Err(err) => {
tracing::error!(
?err,
"failed to unpack active actor index key, skipping"
);
}
}

if start.elapsed() > EARLY_TXN_TIMEOUT {
tracing::warn!("timed out scanning migration candidates");
timed_out = true;
break;
}
}

let candidates = futures_util::stream::iter(index_rows)
.map(|(raw_key, actor_id)| {
let tx = tx.clone();
async move { read_candidate(&tx, actor_id, raw_key, hibernating_since_ts).await }
})
.buffered(READ_CONCURRENCY)
.try_filter_map(|candidate| async move { Ok(candidate) })
.try_collect::<Vec<_>>()
.await?;

Ok(proto::CandidatesResponse { candidates, next })
Ok((index_rows, last_key, timed_out || scanned == limit))
}
})
.await?;

// Reads facts in as many transactions as it takes. Each one resumes at the first actor the
// previous one did not read.
let mut candidates = Vec::new();
let mut read_count = 0;
while read_count < index_rows.len() {
let (chunk, chunk_read_count) = udb
.txn("migration_candidates_facts", |tx| {
let pending = &index_rows[read_count..];
async move {
let start = Instant::now();
let mut stream = futures_util::stream::iter(pending.iter().cloned())
.map(|(raw_key, actor_id)| {
let tx = tx.clone();
async move {
let candidate =
read_candidate(&tx, actor_id, raw_key, hibernating_since_ts)
.await;
(actor_id, candidate)
}
})
.buffered(READ_CONCURRENCY);

let mut chunk = Vec::new();
let mut chunk_read_count = 0;
while let Some((actor_id, candidate)) = stream.next().await {
chunk_read_count += 1;

// One actor that fails to read must not fail the page, or the migrator
// would retry the same cursor forever. A skipped actor is listed again on
// the next pass.
match candidate {
Ok(Some(candidate)) => chunk.push(candidate),
Ok(None) => {}
Err(err) => {
tracing::error!(
?actor_id,
?err,
"failed to read migration candidate, skipping"
);
}
}

if start.elapsed() > EARLY_TXN_TIMEOUT {
tracing::warn!("timed out reading migration candidate facts");
break;
}
}

Ok((chunk, chunk_read_count))
}
})
.await?;

candidates.extend(chunk);
read_count += chunk_read_count;
}

let next = if has_more { last_key } else { None };
let response = proto::CandidatesResponse { candidates, next };

let next = response
.next
.as_ref()
Expand Down
135 changes: 92 additions & 43 deletions engine/packages/api-public/src/migration/parked.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
//! and the destroy ends the workflow. Every step is idempotent, so a caller retries a failed
//! delete with the same request.

use std::time::{Duration, Instant};

use anyhow::{Context, Result, bail};
use axum::body::Bytes;
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
Expand All @@ -33,6 +35,7 @@ use crate::{ctx::ApiCtx, errors};

const DEFAULT_LIMIT: usize = 200;
const MAX_LIMIT: usize = 500;
const EARLY_TXN_TIMEOUT: Duration = Duration::from_millis(2500);

/// 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.
Expand Down Expand Up @@ -60,10 +63,14 @@ pub async fn list(ctx: ApiCtx, namespace: String, query: ParkedQuery) -> Result<
};

let udb = ctx.pools().udb()?;
let response = udb
.txn("migration_parked_list", |tx| {

// The scan and the namespace reads run in separate transactions, so a page of records never
// shares one transaction's time limit.
let (rows, last_key, has_more) = udb
.txn("migration_parked_list_scan", |tx| {
let after = after.clone();
async move {
let start = Instant::now();
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 {
Expand All @@ -74,55 +81,95 @@ pub async fn list(ctx: ApiCtx, namespace: String, query: ParkedQuery) -> Result<
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::<Vec<_>>()
.await?;

let next = if rows.len() == limit {
rows.last().map(|(raw_key, _)| raw_key.clone())
} else {
None
};
let mut stream = tx.get_ranges_keyvalues(
universaldb::RangeOption {
limit: Some(limit),
mode: StreamingMode::Iterator,
..(begin, range_end).into()
},
Snapshot,
);

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 mut rows = Vec::new();
let mut last_key = None;
let mut scanned = 0;
let mut timed_out = false;

while let Some(entry) = stream.try_next().await? {
scanned += 1;
last_key = Some(entry.key().to_vec());

match mkeys::parked_actor_id(entry.key()) {
Some(actor_id) => {
rows.push((entry.key().to_vec(), actor_id, entry.value().to_vec()))
}
None => tracing::error!("failed to unpack parked record key, skipping"),
}

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,
});
if start.elapsed() > EARLY_TXN_TIMEOUT {
tracing::warn!("timed out scanning parked records");
timed_out = true;
break;
}
}

Ok(proto::ParkedResponse { actors, next })
Ok((rows, last_key, timed_out || scanned == limit))
}
})
.await?;

// Reads each record's namespace in as many transactions as it takes. Each one resumes at the
// first record the previous one did not read.
let mut actors = Vec::new();
let mut read_count = 0;
while read_count < rows.len() {
let (chunk, chunk_read_count) = udb
.txn("migration_parked_list_namespaces", |tx| {
let pending = &rows[read_count..];
async move {
let start = Instant::now();
let pb = tx.with_subspace(keys::subspace());
let mut chunk = Vec::new();
let mut chunk_read_count = 0;

for (raw_key, actor_id, raw_value) in pending {
chunk_read_count += 1;

let actor_namespace_id = pb
.read_opt(&keys::actor::NamespaceIdKey::new(*actor_id), Snapshot)
.await?;
if actor_namespace_id == Some(namespace_id) {
let record = facts::decode_parked(raw_value)?;
chunk.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.clone(),
});
}

if start.elapsed() > EARLY_TXN_TIMEOUT {
tracing::warn!("timed out reading parked record namespaces");
break;
}
}

Ok((chunk, chunk_read_count))
}
})
.await?;

actors.extend(chunk);
read_count += chunk_read_count;
}

let next = if has_more { last_key } else { None };
let response = proto::ParkedResponse { actors, next };

proto::encode(&response)
}

Expand Down Expand Up @@ -427,14 +474,16 @@ async fn authorize_delete(ctx: &ApiCtx, namespace: &str) -> Result<()> {
.await
}

/// A cursor is any key in the parked subspace, not only a readable parked record key: a page that
/// ends on a record key it skipped as unreadable returns that key as `next`.
fn decode_cursor(cursor: &str) -> Result<Vec<u8>> {
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() {
if !raw.starts_with(mkeys::parked_subspace().bytes()) {
return Err(errors::Migration::InvalidRequest {
message: "after is not a parked actor cursor".to_string(),
}
Expand Down
Loading