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
8 changes: 5 additions & 3 deletions docs/allowed-differences.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,11 @@ These differences exist to make runs cheaper or faster.
`init` starts reading the metadata of the default dataset and key-value store (which opening
them reads), the input record, the tracked child runs and the records of
`InitOptions::prefetch_records` in the background, and the first read of each takes what was
read. What is written through the SDK before it is read (a record, items of the dataset) is
read again; what another client changes in the meantime is not. The JS SDK reads each when
asked.
read. The records other than the input are read after one listing of the store's keys, and
only when listed: the first read of one that is not is `None` without an API call (each is
read when the store cannot be listed or holds over 1,000 keys, one page of the listing). What is written through the
SDK before it is read (a record, items of the dataset) is read again; what another client
changes in the meantime is not. The JS SDK reads each when asked.
- **Status messages can be set in the background.** `Actor::set_status_message_in_background` is
`Actor.setStatusMessage(...)` without `await`: the message is logged at once and the run updated
later. Updates are sent one at a time in the order they were made, and an update is dropped when
Expand Down
11 changes: 8 additions & 3 deletions src/actor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,11 @@ pub struct InitOptions {
pub graceful_shutdown_delay: Duration,
/// Records of the default key-value store to read in the background during `init`, on the
/// platform, so that their first reads do not wait for the API (the input and the tracked
/// child runs are always read ahead). A record written before it is read is read again.
/// child runs are always read ahead). The store's keys are listed once, and only the records
/// it holds are read, once listed: in a fresh run, where most of these records (state saved
/// by an earlier container of the run) do not exist yet, the first read of each is `None`
/// without an API call. When the store cannot be listed, or holds over 1,000 keys (one page of the listing), each
/// record is read. A record written or deleted before it is read is read again.
pub prefetch_records: Vec<String>,
/// On the platform, the run's default request queue is kept in memory for this long, and then
/// moved to the platform with what it holds, so that a short run makes one request queue API
Expand Down Expand Up @@ -339,8 +343,9 @@ impl Actor {
.request_queue_access(options.request_queue_access)
.spill_default_request_queue_after(options.spill_request_queue_after);
// What every run reads first, read while the run connects to the platform: the
// default storages' metadata (which opening them reads), the input, the child runs,
// and whether the default request queue holds requests already (a resumed run).
// default storages' metadata (which opening them reads), the input, the child runs
// and the records asked for (those the store's listing finds), and whether the
// default request queue holds requests already (a resumed run).
if configuration.is_at_home && !configuration.default_key_value_store_id.is_empty() {
let keys = [configuration.input_key.as_str(), crate::child_runs::CHILD_RUNS_KVS_KEY];
let keys = keys.into_iter().chain(options.prefetch_records.iter().map(String::as_str));
Expand Down
55 changes: 51 additions & 4 deletions src/storage/key_value_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use crawlee::core::storage::backend::{
KeyValueStoreListKeysResult, KeyValueStoreRecord,
};

use std::collections::HashSet;
use std::sync::Arc;

use super::prefetch::Prefetched;
Expand All @@ -34,21 +35,67 @@ pub(crate) struct PrefetchedStores {
pub(crate) records: Prefetched<(String, String), Option<KeyValueStoreRecord>>,
}

/// The keys of a store, listed once for all the records read ahead of it; `None` when they could
/// not be listed, or the store holds too many to list.
type Listing = Arc<tokio::sync::OnceCell<Option<HashSet<String>>>>;

/// The keys the listing reads, in one page: the most the API returns at once. A store holding more
/// has its records read one by one (in parallel), rather than listed page after page.
const LISTING_PAGE_SIZE: i64 = 1000;

impl PrefetchedStores {
/// Starts reading the metadata of the store of `client` (whose id is `store_id`) and its
/// records `keys`.
/// records `keys`: `read_at_once` (the input, which a run nearly always has) at once, the others
/// once a listing of the store's keys finds them there. Those it does not find are read as
/// missing without asking the API: in a fresh run, most records read ahead are (state an
/// earlier container of the run would have saved). When the store cannot be listed, or holds
/// more keys than one page of the listing ([`LISTING_PAGE_SIZE`]), each record is read.
pub(crate) fn prefetch<'a>(
&self,
client: &KeyValueStoreClient,
store_id: &str,
keys: impl IntoIterator<Item = &'a str>,
read_at_once: Option<&str>,
) {
let store = client.clone();
self.metadata.start(store_id.to_owned(), async move { get_metadata(&store).await });
let listing = Listing::default();
for key in keys {
let (store, owned_key) = (client.clone(), key.to_owned());
self.records
.start((store_id.to_owned(), key.to_owned()), async move { get_record(&store, &owned_key).await });
let (store, owned_key, listing) = (client.clone(), key.to_owned(), listing.clone());
let listed = read_at_once != Some(key);
self.records.start((store_id.to_owned(), key.to_owned()), async move {
// The first of these reads lists the keys, and the others wait for that listing.
if listed
&& let Some(keys) = listing.get_or_init(|| list_all_keys(&store)).await
&& !keys.contains(&owned_key)
{
return Ok(None);
}
get_record(&store, &owned_key).await
});
}
}
}

/// All the keys of the store of `client`, or `None` when it holds more than one page of them
/// ([`LISTING_PAGE_SIZE`]) or the listing fails.
///
/// The listing is complete: on the Apify platform, a record is stored before its write is
/// answered, and listed from then on (unlike a request queue's head, which lags behind), so the
/// records an earlier container of the run wrote are listed.
async fn list_all_keys(client: &KeyValueStoreClient) -> Option<HashSet<String>> {
let options = ListKeysOptions { limit: Some(LISTING_PAGE_SIZE), ..ListKeysOptions::default() };
match client.list_keys(options).await {
Ok(page) if page.is_truncated => {
tracing::debug!(
"The key-value store holds more than {LISTING_PAGE_SIZE} keys, reading each record instead"
);
None
}
Ok(page) => Some(page.items.into_iter().map(|item| item.key).collect()),
Err(err) => {
tracing::debug!("Listing the keys of the key-value store failed, reading each record instead: {err}");
None
}
}
}
Expand Down
11 changes: 8 additions & 3 deletions src/storage/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,10 +199,15 @@ impl ApifyStorageBackend {

/// Starts reading the metadata of the key-value store `store_id` and its records `keys` in the
/// background, so that the first reads of each take what was read instead of waiting for the
/// API (opening a storage reads its metadata). A record written or deleted before it is read
/// is read again, and so is the metadata of a store written to.
/// API (opening a storage reads its metadata). The store's keys are listed once, and only the
/// records listed are read (the input record of the default store is read at once, beside the
/// listing): the first read of one that is not listed is `None`, without an API call. When the
/// keys cannot be listed, or are too many (over 1,000, one page of the listing), each record is read. A record written
/// or deleted before it is read is read again, and so is the metadata of a store written to.
pub fn prefetch_key_value_store<'a>(&self, store_id: &str, keys: impl IntoIterator<Item = &'a str>) {
self.prefetched_stores.prefetch(&self.client.key_value_store(store_id), store_id, keys);
let input_key = (store_id == self.configuration.default_key_value_store_id)
.then_some(self.configuration.input_key.as_str());
self.prefetched_stores.prefetch(&self.client.key_value_store(store_id), store_id, keys, input_key);
}

/// Starts reading the metadata of the dataset `dataset_id` in the background, like
Expand Down
7 changes: 5 additions & 2 deletions tests/actor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -807,7 +807,8 @@ async fn init_makes_its_calls_at_once_and_reads_records_ahead() {
api.put_record(DEFAULT_STORE, "INPUT", br#"{"greeting":"hi"}"#, "application/json; charset=utf-8");
api.put_record(DEFAULT_STORE, "STATE", br#"{"count":1}"#, "application/json; charset=utf-8");
let slow = Duration::from_millis(500);
// The run, for its pricing, the storages and the records: one after another, they would take 3 s.
// The run, for its pricing, the storages, the listing of the store's keys and the records: one
// after another, they would take 3.5 s. A record the store holds is read once it is listed.
api.delay("GET /v2/actor-runs/run-1", slow);
api.delay("GET /v2/key-value-stores", slow);
api.delay("GET /v2/datasets", slow);
Expand All @@ -822,7 +823,9 @@ async fn init_makes_its_calls_at_once_and_reads_records_ahead() {
let stdout = String::from_utf8_lossy(&output.stdout);
let elapsed: u64 =
stdout.split("ELAPSED ").nth(1).and_then(|rest| rest.split_whitespace().next()).unwrap().parse().unwrap();
assert!(elapsed < 1000, "init and the reads took {elapsed} ms:\n{stdout}");
// The listing, then the record: the two round trips the reads wait for, the rest made meanwhile.
assert!(elapsed < 1500, "init and the reads took {elapsed} ms:\n{stdout}");
assert_eq!(api.count_calls("GET /v2/key-value-stores/default-store/keys"), 1);
assert_eq!(api.count_calls("GET /v2/key-value-stores/default-store/records/INPUT"), 1);
assert_eq!(api.count_calls("GET /v2/datasets/default-dataset"), 1);
assert_eq!(queue_calls(&api), [QUEUE_CHECK], "checked once, and the queue kept in memory:\n{stdout}");
Expand Down
115 changes: 115 additions & 0 deletions tests/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,121 @@ async fn key_value_store_records_keep_their_bytes_and_content_type() {
assert_eq!(url, format!("{}/v2/key-value-stores/{DEFAULT_STORE}/records/OUTPUT", api.url));
}

/// Records an Actor may have saved in an earlier container of its run, read ahead.
const STATE_KEYS: [&str; 10] =
["STATE-0", "STATE-1", "STATE-2", "STATE-3", "STATE-4", "STATE-5", "STATE-6", "STATE-7", "STATE-8", "STATE-9"];

/// The default store, with the input and [`STATE_KEYS`] read ahead as `Actor::init` reads them.
async fn prefetched_store(api: &FakeApi) -> crawlee::KeyValueStore {
let backend = ApifyStorageBackend::new(configuration(api, true));
backend.prefetch_key_value_store(DEFAULT_STORE, std::iter::once("INPUT").chain(STATE_KEYS));
Services::new(Arc::new(backend)).open_key_value_store(&StorageIdentifier::Default).await.unwrap()
}

/// The key-value store calls made so far, sorted.
fn store_calls(api: &FakeApi) -> Vec<String> {
let mut calls: Vec<String> =
api.calls().into_iter().filter(|call| call.contains("/v2/key-value-stores/")).collect();
calls.sort();
calls
}

const LISTING: &str = "GET /v2/key-value-stores/default-store/keys";

#[tokio::test]
async fn a_fresh_run_lists_the_store_once_instead_of_reading_each_missing_record() {
let api = FakeApi::start().await;
api.put_record(DEFAULT_STORE, "INPUT", br#"{"a":1}"#, "application/json");
let store = prefetched_store(&api).await;

assert_eq!(store.get_value::<Value>("INPUT").await.unwrap(), Some(json!({ "a": 1 })));
for key in STATE_KEYS {
assert_eq!(store.get_value::<Value>(key).await.unwrap(), None, "{key}");
}
let expected =
["GET /v2/key-value-stores/default-store", LISTING, "GET /v2/key-value-stores/default-store/records/INPUT"];
assert_eq!(store_calls(&api), expected);
}

#[tokio::test]
async fn the_listed_records_are_read_at_once_after_the_listing_and_the_others_answered_locally() {
let api = FakeApi::start().await;
api.put_record(DEFAULT_STORE, "STATE-3", b"3", "text/plain");
api.put_record(DEFAULT_STORE, "STATE-7", b"7", "text/plain");
let slow = std::time::Duration::from_millis(300);
api.delay(LISTING, slow);
api.delay("GET /v2/key-value-stores/default-store/records/STATE", slow);
let started = std::time::Instant::now();
let store = prefetched_store(&api).await;

for key in STATE_KEYS {
let expected = ["STATE-3", "STATE-7"].contains(&key).then(|| key[6..].to_owned());
assert_eq!(store.get_text(key).await.unwrap(), expected, "{key}");
}
// The listing, then both reads at the same time: 600 ms, where one after another takes 900.
let elapsed = started.elapsed();
assert!(elapsed < std::time::Duration::from_millis(850), "{elapsed:?}");
let calls = api.calls();
let listed_at = calls.iter().position(|call| call == LISTING).unwrap();
let reads: Vec<usize> =
calls.iter().enumerate().filter(|(_, call)| call.contains("/records/STATE")).map(|(at, _)| at).collect();
assert_eq!(reads.len(), 2, "{calls:?}");
assert!(reads.iter().all(|&at| at > listed_at), "{calls:?}");
// The input, not in the store, was read too, and nothing else.
assert_eq!(api.count_calls("GET /v2/key-value-stores/default-store/records/"), 3, "{calls:?}");
}

#[tokio::test]
async fn a_record_written_or_deleted_after_the_listing_is_read_from_the_api() {
let api = FakeApi::start().await;
api.put_record(DEFAULT_STORE, "STATE-1", b"1", "text/plain");
let store = prefetched_store(&api).await;
// Answered from the listing.
assert_eq!(store.get_text("STATE-2").await.unwrap(), None);

store.set_text("STATE-0", "0").await.unwrap();
assert_eq!(store.get_text("STATE-0").await.unwrap().as_deref(), Some("0"));
store.delete_value("STATE-1").await.unwrap();
assert_eq!(store.get_text("STATE-1").await.unwrap(), None);
assert_eq!(api.count_calls("GET /v2/key-value-stores/default-store/records/STATE-0"), 1);
assert_eq!(api.count_calls(LISTING), 1);
}

#[tokio::test]
async fn a_failing_listing_falls_back_to_reading_each_record() {
let api = FakeApi::start().await;
api.put_record(DEFAULT_STORE, "STATE-3", b"3", "text/plain");
api.fail_next(LISTING, 1, axum::http::StatusCode::FORBIDDEN);
let store = prefetched_store(&api).await;

for key in STATE_KEYS {
let expected = (key == "STATE-3").then(|| "3".to_owned());
assert_eq!(store.get_text(key).await.unwrap(), expected, "{key}");
let read = format!("GET /v2/key-value-stores/default-store/records/{key}");
assert_eq!(api.count_calls(&read), 1, "{key}");
}
assert_eq!(api.count_calls(LISTING), 1);
}

#[tokio::test]
async fn a_store_with_more_keys_than_the_listing_covers_falls_back_to_reading_each_record() {
let api = FakeApi::start().await;
// More than the one page of a thousand keys the listing reads.
for n in 0..1_000 {
api.put_record(DEFAULT_STORE, &format!("item-{n:05}"), b"x", "text/plain");
}
api.put_record(DEFAULT_STORE, "STATE-3", b"3", "text/plain");
let store = prefetched_store(&api).await;

for key in STATE_KEYS {
let expected = (key == "STATE-3").then(|| "3".to_owned());
assert_eq!(store.get_text(key).await.unwrap(), expected, "{key}");
let read = format!("GET /v2/key-value-stores/default-store/records/{key}");
assert_eq!(api.count_calls(&read), 1, "{key}");
}
assert_eq!(api.count_calls(LISTING), 1, "one page, not the next ones");
}

#[tokio::test]
async fn names_and_aliases_resolve_to_platform_storages() {
let api = FakeApi::start().await;
Expand Down
Loading