diff --git a/README.md b/README.md index e938c47..da1d670 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,7 @@ input schema. Copy it and `apify push`. | **Request queues** | Single-consumer mode (local head estimate, no locks) and shared mode (platform locks, prolonged for long requests) | | **Events** | The platform websocket (reopened when it drops) relayed as crawlee-rs events: system info for autoscaling, `migrating` (state saved, run rebooted), `aborting` (graceful exit) | | **Input** | `get_input` from the store or `INPUT(.json)`, schema defaults applied locally, secret fields decrypted | -| **Platform API** | `call` (the run's log redirected into this one's), `start`, `call_task`, `start_task`, `resurrect`, `abort`, `metamorph`, `add_webhook`, `set_status_message` (crawler status forwarded), `get_env`, `use_state`; named child runs (`run_name`, `child_runs`) that survive a migration or resurrection | +| **Platform API** | `call` (the run's log redirected into this one's), `start`, `call_task`, `start_task`, `resurrect`, `abort`, `metamorph`, `add_webhook`, `set_status_message` (crawler status forwarded), `get_env`, `use_state`; named child runs (`run_name`, `child_runs`) that survive a migration or resurrection; starts that wait for memory and Actor jobs on the account (`wait_for_capacity`, as `apify-orchestrator`) | | **Proxy** | Apify Proxy (groups, country, password from the account, access check) and custom proxies, for crawlers | | **Charging** | Pay-per-event: budget limits, the `apify-default-dataset-item` event charged as items are stored, `push_data_and_charge`, the local charging log | | **URL filters** | Globs and pseudo-URLs with request options, as Actor inputs send them | diff --git a/src/actor.rs b/src/actor.rs index ec8c8bb..351882e 100644 --- a/src/actor.rs +++ b/src/actor.rs @@ -418,6 +418,10 @@ impl Actor { events.on(EventKind::Aborting, |_| async { Self::child_run_tracker().abort_runs_with_parent(Self::client()).await }); + // No start waiting for capacity goes out once this run is shutting down. + for kind in [EventKind::Aborting, EventKind::Migrating, EventKind::Exit] { + events.on(kind, |_| async { Self::child_run_tracker().capacity.close() }); + } { let mut listeners = LISTENERS.lock(); let pending = std::mem::take(&mut listeners.pending); diff --git a/src/child_runs.rs b/src/child_runs.rs index a00f6ba..cde3fc5 100644 --- a/src/child_runs.rs +++ b/src/child_runs.rs @@ -39,6 +39,15 @@ pub const ABORT_WITH_PARENT_TIMEOUT: Duration = Duration::from_secs(10); /// The status of a tracked run the platform no longer returns (removed or expired). const LOST: &str = "LOST"; +/// The API's refusals of a start for lack of memory or Actor jobs on the account, which +/// [`CapacityQueue`] retries. +const CAPACITY_ERROR_TYPES: [&str; 2] = ["actor-memory-limit-exceeded", "concurrent-runs-limit-exceeded"]; +/// How long no start is tried after one was refused for lack of capacity (`MAIN_LOOP_COOLDOWN_MS` +/// of `apify-orchestrator`). +const CAPACITY_COOLDOWN: Duration = Duration::from_secs(10); +/// How often a waiting start checks whether it can go (`MAIN_LOOP_INTERVAL_MS`). +const CAPACITY_CHECK_INTERVAL: Duration = Duration::from_secs(1); + /// A child run as tracked. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -144,6 +153,8 @@ pub(crate) struct ChildRunTracker { /// Set once this run is being gracefully aborted, after which no run with `abort_with_parent` /// is started. is_parent_aborting: AtomicBool, + /// The starts that wait for capacity. + pub(crate) capacity: CapacityQueue, } impl ChildRunTracker { @@ -155,6 +166,7 @@ impl ChildRunTracker { clients: Mutex::default(), locks: Mutex::default(), is_parent_aborting: AtomicBool::new(false), + capacity: CapacityQueue::default(), } } @@ -379,10 +391,146 @@ impl ChildRunTracker { } } +/// The starts of [`CallOptions::wait_for_capacity`](crate::CallOptions::wait_for_capacity), as +/// `apify-orchestrator` schedules them: one at a time. A start refused for lack of memory or Actor +/// jobs on the account is tried again every second once [`CAPACITY_COOLDOWN`] has passed, in which +/// no other start goes either. Once this run is shutting down (aborting, migrating or exiting), no +/// start goes out. +#[derive(Default)] +pub(crate) struct CapacityQueue { + lock: tokio::sync::Mutex<()>, + cooldown_until: Mutex>, + closed: AtomicBool, +} + +impl CapacityQueue { + /// Starts no more runs: the waiting starts fail. + pub(crate) fn close(&self) { + self.closed.store(true, Ordering::Release); + } + + /// Runs `start` until the account has capacity for the run it starts. + pub(crate) async fn start(&self, mut start: F) -> ApifyClientResult + where + F: FnMut() -> Fut, + Fut: Future>, + { + loop { + { + let _exclusive = self.lock.lock().await; + if self.closed.load(Ordering::Acquire) { + return Err(ApifyClientError::InvalidArgument( + "The run was not started, because this run is shutting down.".to_owned(), + )); + } + let cooling_down = self.cooldown_until.lock().is_some_and(|until| tokio::time::Instant::now() < until); + if !cooling_down { + match start().await { + Err(err) if is_capacity_error(&err) => { + *self.cooldown_until.lock() = Some(tokio::time::Instant::now() + CAPACITY_COOLDOWN); + tracing::warn!( + "Not enough capacity to start a run, retrying in {}s: {err}", + CAPACITY_COOLDOWN.as_secs() + ); + } + result => return result, + } + } + } + tokio::time::sleep(CAPACITY_CHECK_INTERVAL).await; + } + } +} + +fn is_capacity_error(err: &ApifyClientError) -> bool { + err.as_api_error() + .and_then(|err| err.error_type.as_deref()) + .is_some_and(|error_type| CAPACITY_ERROR_TYPES.contains(&error_type)) +} + #[cfg(test)] mod tests { + use std::sync::atomic::AtomicUsize; + use super::*; + fn refusal(error_type: &str) -> ApifyClientError { + ApifyClientError::Api(Box::new(apify_client::ApiError { + status_code: 402, + error_type: Some(error_type.to_owned()), + message: error_type.to_owned(), + attempt: 1, + http_method: Some("POST".to_owned()), + path: Some("/v2/acts/user~a/runs".to_owned()), + data: None, + })) + } + + fn run(id: &str) -> ActorRun { + serde_json::from_value(serde_json::json!({ "id": id, "actId": "a", "status": "READY" })).unwrap() + } + + #[tokio::test(start_paused = true)] + async fn a_start_refused_for_capacity_is_retried_after_the_cooldown() { + let queue = CapacityQueue::default(); + let calls = AtomicUsize::new(0); + let started = tokio::time::Instant::now(); + let result = queue + .start(|| async { + match calls.fetch_add(1, Ordering::SeqCst) { + 0 => Err(refusal("actor-memory-limit-exceeded")), + 1 => Err(refusal("concurrent-runs-limit-exceeded")), + _ => Ok(run("child-1")), + } + }) + .await; + assert_eq!(result.unwrap().id, "child-1"); + assert_eq!(calls.load(Ordering::SeqCst), 3); + assert!(started.elapsed() >= 2 * CAPACITY_COOLDOWN, "{:?}", started.elapsed()); + } + + #[tokio::test(start_paused = true)] + async fn starts_go_one_at_a_time_and_other_errors_are_not_retried() { + let queue = CapacityQueue::default(); + let (in_flight, peak) = (AtomicUsize::new(0), AtomicUsize::new(0)); + let start = || async { + peak.fetch_max(in_flight.fetch_add(1, Ordering::SeqCst) + 1, Ordering::SeqCst); + tokio::time::sleep(Duration::from_millis(100)).await; + in_flight.fetch_sub(1, Ordering::SeqCst); + Ok(run("child")) + }; + let (a, b) = tokio::join!(queue.start(start), queue.start(start)); + assert!(a.is_ok() && b.is_ok()); + assert_eq!(peak.load(Ordering::SeqCst), 1); + + let calls = AtomicUsize::new(0); + let failed = queue + .start(|| async { + calls.fetch_add(1, Ordering::SeqCst); + Err(refusal("actor-not-found")) + }) + .await; + assert!(failed.is_err()); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + #[tokio::test(start_paused = true)] + async fn no_start_goes_out_once_the_run_shuts_down() { + let queue = CapacityQueue::default(); + let calls = AtomicUsize::new(0); + let waiting = queue.start(|| async { + calls.fetch_add(1, Ordering::SeqCst); + Err(refusal("actor-memory-limit-exceeded")) + }); + let close = async { + tokio::time::sleep(Duration::from_secs(5)).await; + queue.close(); + }; + let (result, ()) = tokio::join!(waiting, close); + assert!(result.is_err()); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + #[test] fn the_checksum_ignores_key_order_and_an_absent_input() { let request = |input: Option| ChildRunRequest { kind: "actor", id: "user/a".to_owned(), input }; diff --git a/src/platform.rs b/src/platform.rs index c9167ec..ef253ee 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -59,6 +59,12 @@ pub struct CallOptions { /// A run started with a custom `token` is aborted with that token, except for a run started /// before a migration or resurrection of this run, which is aborted with the default client. pub abort_with_parent: bool, + /// Wait for memory and Actor jobs on the account, as `apify-orchestrator` does, instead of + /// failing when the platform refuses the start for lack of them. The starts with this option + /// go one at a time. A refused one is tried again every second once 10 seconds have passed, + /// during which none of them goes. Once this run is aborting, migrating or exiting, they fail + /// instead. + pub wait_for_capacity: bool, /// Where `call` puts the log of the Actor run it started. pub log: RunLog, } @@ -269,10 +275,18 @@ impl Actor { } let client = Self::client_for(options.token.as_deref()); let start = Self::start_options(options); - let start_new = |start: ActorStartOptions| async { + let client_ref = &client; + let start_once = move |start: ActorStartOptions| async move { match kind { - "task" => client.task(id).start(input, task_start_options(start)).await, - _ => client.actor(id).start(input, start).await, + "task" => client_ref.task(id).start(input, task_start_options(start)).await, + _ => client_ref.actor(id).start(input, start).await, + } + }; + let start_new = |start: ActorStartOptions| async move { + if options.wait_for_capacity { + Self::child_run_tracker().capacity.start(|| start_once(start.clone())).await + } else { + start_once(start).await } }; let Some(run_name) = &options.run_name else { return Ok((start_new(start).await?, false)) }; @@ -300,7 +314,7 @@ impl Actor { ) -> ApifyClientResult { let client = Self::client_for(options.token.as_deref()); let wait = options.wait.map(|wait| wait.as_secs() as i64); - if kind == "task" && options.run_name.is_none() { + if kind == "task" && options.run_name.is_none() && !options.wait_for_capacity { return client.task(id).call(input, task_start_options(Self::start_options(&options)), wait).await; } let (run, resumed) = Self::start_run(kind, id, input, &options).await?; diff --git a/tests/storage.rs b/tests/storage.rs index 276d5da..a6abfde 100644 --- a/tests/storage.rs +++ b/tests/storage.rs @@ -103,15 +103,18 @@ async fn names_and_aliases_resolve_to_platform_storages() { // Unless the storage was deleted in the meantime. api.delete_dataset(&scratch_id); - let fresh = Services::new(Arc::new(ApifyStorageBackend::new(configuration(&api, true)))); + let fresh_backend = Arc::new(ApifyStorageBackend::new(configuration(&api, true))); + let fresh = Services::new(fresh_backend.clone()); let recreated = fresh.open_dataset(&StorageIdentifier::alias("scratch")).await.unwrap(); assert_ne!(recreated.get_info().await.unwrap().id, scratch_id); - // Also when it was deleted after this process resolved it. + // Also when it was deleted after this process resolved it. `Services` hands back the instance it + // already opened, as `StorageInstanceManager` does in JS, so ask the backend. + use crawlee::core::StorageBackend as _; let recreated_id = recreated.get_info().await.unwrap().id; api.delete_dataset(&recreated_id); - let reopened = fresh.open_dataset(&StorageIdentifier::alias("scratch")).await.unwrap(); - assert_ne!(reopened.get_info().await.unwrap().id, recreated_id); + let reopened = fresh_backend.create_dataset_backend(&StorageIdentifier::alias("scratch")).await.unwrap(); + assert_ne!(reopened.get_metadata().await.unwrap().id, recreated_id); // `__default__` is the default storage. let default = fresh.open_dataset(&StorageIdentifier::alias("__default__")).await.unwrap(); @@ -166,17 +169,19 @@ async fn aliases_declared_in_the_actor_schema_and_off_the_platform() { ..(*configuration(&api, true)).clone() })))); let replacement = replaced.open_dataset(&StorageIdentifier::alias("products")).await.unwrap(); - assert_ne!(replacement.get_info().await.unwrap().id, DEFAULT_DATASET); + let replacement_id = replacement.get_info().await.unwrap().id; + assert_ne!(replacement_id, DEFAULT_DATASET); // Off the platform (a `force_cloud` storage), aliases are not remembered. + let mapping = api.record(DEFAULT_STORE, "__STORAGE_ALIASES_MAPPING"); let local = Services::new(Arc::new(ApifyStorageBackend::new(configuration(&api, false)))); local.open_dataset(&StorageIdentifier::alias("scratch")).await.unwrap(); - assert!(api.record(DEFAULT_STORE, "__STORAGE_ALIASES_MAPPING").is_none()); + assert_eq!(api.record(DEFAULT_STORE, "__STORAGE_ALIASES_MAPPING"), mapping); let backend = ApifyStorageBackend::new(configuration(&api, false)); use crawlee::core::StorageBackend as _; - assert!(backend.storage_exists(DEFAULT_DATASET, StorageKind::Dataset).await.unwrap()); - assert!(!backend.storage_exists("nope", StorageKind::Dataset).await.unwrap()); + assert!(backend.storage_exists(&replacement_id, StorageKind::Dataset).await.unwrap()); + assert!(!backend.storage_exists(DEFAULT_DATASET, StorageKind::Dataset).await.unwrap()); } #[tokio::test]