diff --git a/docs/allowed-differences.md b/docs/allowed-differences.md index 8ebc2b7..e80b1f4 100644 --- a/docs/allowed-differences.md +++ b/docs/allowed-differences.md @@ -59,6 +59,10 @@ These differences exist to make runs cheaper or faster. later. Updates are sent one at a time in the order they were made, and an update is dropped when a later one was sent already (in JS, concurrent updates can land in any order); `exit` waits for them before the terminal status message. +- **A Server Actor run fetches its Actor while it reads the run.** In standby, the JS SDK starts + fetching both in `init`, and its charging manager waits for the run before it asks for the + Actor. Here charging fetches them at once. Both are kept: `Actor::get_current_run` returns the + run that charging read, as `Actor.getCurrentRun()` does. ## Configuration @@ -98,6 +102,9 @@ These differences exist to make runs cheaper or faster. `pushDataWithSchemaRepair` of `@apify/actor-utils` (logged; the items that cannot be repaired are given back), or dropped (logged). The other items are stored and charged; rejected items are not charged. +- **A charge count cannot be negative.** `ChargeOptions::count` is a `u64`. A count of 0 is + ignored as JS ignores a non-positive one: nothing is sent or counted, and its idempotency key + is not kept. - **Shared request queues can prolong locks.** `extend_request_processing_time` prolongs the platform lock of a request in progress; the JS SDK never prolongs locks. diff --git a/src/actor.rs b/src/actor.rs index 0506604..5e1e6e3 100644 --- a/src/actor.rs +++ b/src/actor.rs @@ -477,7 +477,7 @@ impl Actor { } child_runs?; charging?; - if state.charging.is_pay_per_event() && state.smart.is_none() { + if state.charging.is_pay_per_event() && !state.charging.is_multi_tenant() && state.smart.is_none() { tracing::warn!( "Items pushed to the default dataset will not be charged for, because this run does not use Apify \ storage - the platform only counts items it stores itself." @@ -780,11 +780,20 @@ impl Actor { &state().charging } - /// Charges for `count` events of `event_name` (see [`ChargingManager::charge`]). + /// Charges for `count` events of `event_name` (see [`ChargingManager::charge`]). In a + /// multi-tenant Server Actor run, set [`ChargeOptions::request_id`] to the + /// `X-Actor-Request-ID` header of the incoming request. pub async fn charge(options: ChargeOptions) -> Result { state().charging.charge(options).await } + /// The current Actor run from the Apify API. It is fetched once and kept for the lifetime of + /// the Actor, so use `Actor::client().run(id).get()` for fresh data such as the run status. + /// `None` when not running on the Apify platform. + pub async fn get_current_run() -> Result, apify_client::ApifyClientError> { + state().charging.current_run().await + } + /// Pushes one item (an object) or several (an array) to the default dataset. Under /// pay-per-event pricing, only as many items are stored as the budget allows, each charged as /// an `apify-default-dataset-item` event. @@ -794,6 +803,8 @@ impl Actor { /// Pushes items to the default dataset and charges `event_name` for each, as many as the /// budget allows (`Actor.pushData(items, eventName)` in JS). + /// Not supported in multi-tenant Server Actor runs, which charge per request with + /// [`charge`](Self::charge). pub async fn push_data_and_charge( data: &T, event_name: &str, @@ -804,7 +815,8 @@ impl Actor { /// Pushes items to the default dataset and charges each of `events` for each item, as many /// items as the budget allows for all of them. An event listed `n` times is charged `n` times /// for each item, with one call. `event_charge_limit_reached` is set when the budget allows no - /// more of one of the events. + /// more of one of the events. Not supported in multi-tenant Server Actor runs, which charge per + /// request with [`charge`](Self::charge). pub async fn push_data_and_charge_events( data: &T, events: &[&str], @@ -830,6 +842,8 @@ impl Actor { /// [`push_data_and_charge`](Self::push_data_and_charge), buffered as /// [`push_data_buffered`](Self::push_data_buffered) is. + /// Not supported in multi-tenant Server Actor runs, which charge per request with + /// [`charge`](Self::charge). pub fn push_data_and_charge_buffered( data: &T, event_name: &str, @@ -905,8 +919,12 @@ impl Actor { if let Some(event) = events.iter().find(|event| event.starts_with("apify-")) { return Err(ChargingError::SyntheticEvent((*event).to_owned())); } - let mut items = serialize_items(data)?; let charging = &state().charging; + // A multi-tenant run charges per request, with `Actor::charge` and the request's ID. + if !events.is_empty() && charging.is_multi_tenant() { + return Err(ChargingError::PushInMultiTenantRun); + } + let mut items = serialize_items(data)?; let is_default_dataset = state().smart.is_some(); let limit = charging.reserve_items(items.len(), &events, is_default_dataset); let reached = !items.is_empty() && limit < items.len() @@ -918,7 +936,10 @@ impl Actor { items.truncate(limit); let charge = ChargeResult { event_charge_limit_reached: charging.is_pay_per_event() && reached, - charged_count: if !charging.is_pay_per_event() || (events.is_empty() && !is_default_dataset) { + charged_count: if !charging.is_pay_per_event() + || charging.is_multi_tenant() + || (events.is_empty() && !is_default_dataset) + { 0 } else { limit as u64 @@ -983,7 +1004,8 @@ impl Actor { /// The input of the run, as it was stored. Locally, the input may instead be an `INPUT` or /// `INPUT.json` file in the working directory; a storage backend that does not read the default /// key-value store's directory (in-memory) also gets the file `apify run` writes there. Input - /// found in more than one place is an error. + /// found in more than one place is an error. Google Sheets sharing links in `requestsFromUrl` + /// entries are replaced with the links of their CSV exports. pub async fn get_input_raw() -> Result { let configuration = &state().configuration; let key = &configuration.input_key; @@ -1038,7 +1060,18 @@ impl Actor { )); }; let input = Self::decrypt_secrets(input)?; - Ok(Self::with_schema_defaults(input)) + Ok(Self::fix_google_sheets_urls(Self::with_schema_defaults(input))) + } + + /// Google Sheets sharing links in `requestsFromUrl` entries (from the "Link remote text file" + /// option) are replaced with the links of their CSV exports. + fn fix_google_sheets_urls(input: Input) -> Input { + match input { + Input::Json(Value::Object(object)) if !object.is_empty() => { + Input::Json(Value::Object(crate::google_sheets::fix_google_sheets_urls(object))) + } + input => input, + } } /// Decrypts the secret fields, when the platform passed the key. diff --git a/src/charging.rs b/src/charging.rs index 94dfa15..48e01cc 100644 --- a/src/charging.rs +++ b/src/charging.rs @@ -7,10 +7,16 @@ //! A charge is counted against the budget at once, in one short critical section, and then sent //! to the platform without holding anything: concurrent charges and pushes do not wait for each //! other's API calls, and cannot together spend more than the budget. +//! +//! A multi-tenant Server Actor run (a standby deployment shared by its callers) charges each +//! caller per request: [`ChargeOptions::request_id`] names the request, and the platform prices, +//! limits and deduplicates the charges. Nothing is counted locally there, and pushed items are +//! not charged. use std::collections::HashMap; use std::sync::Arc; +use apify_client::models::{Actor as ActorResource, ActorRun}; use apify_client::{ApifyClient, ApifyClientError, RunChargeOptions}; use async_trait::async_trait; use crawlee::core::StorageResult; @@ -42,12 +48,20 @@ pub struct ChargeOptions { pub count: u64, /// Keeps a retried operation from being charged twice: a charge repeated under the same key /// within three minutes is not made again (see [`ChargingManager::charge`]). + /// + /// The key is scoped to the whole run, not to `request_id`. In a multi-tenant Server Actor + /// run, a key reused across requests charges only the first caller, so it must be globally + /// unique (for example, derived from `request_id`). pub idempotency_key: Option, + /// ID of the Server Actor request being charged, from the `X-Actor-Request-ID` header of the + /// incoming request. Required in multi-tenant Server Actor runs, where it maps the charge to + /// the caller's account instead of the account that started the run. Sent along elsewhere. + pub request_id: Option, } impl ChargeOptions { pub fn new(event_name: impl Into, count: u64) -> Self { - ChargeOptions { event_name: event_name.into(), count, idempotency_key: None } + ChargeOptions { event_name: event_name.into(), count, idempotency_key: None, request_id: None } } } @@ -76,6 +90,18 @@ pub enum ChargingError { NotInitialized, #[error("Cannot charge for synthetic event '{0}' manually")] SyntheticEvent(String), + #[error("Cannot charge for synthetic event '{0}' in a multi-tenant Server Actor run")] + SyntheticEventMultiTenant(String), + #[error( + "Charging for '{0}' in a multi-tenant Server Actor run requires `request_id` - pass the value of the incoming \ + request's X-Actor-Request-ID header to Actor::charge()." + )] + MissingRequestId(String), + #[error( + "Charging for pushed items is not supported in a multi-tenant Server Actor run - use Actor::charge() with the \ + `request_id` of the incoming request instead." + )] + PushInMultiTenantRun, #[error("{0}")] Invalid(String), #[error(transparent)] @@ -106,6 +132,9 @@ const IDEMPOTENCY_KEY_TTL: Duration = Duration::from_secs(3 * 60); #[derive(Default)] struct State { initialized: bool, + /// A multi-tenant Server Actor run: no pricing snapshot on the run, and the platform prices, + /// limits and deduplicates per caller. + multi_tenant: bool, pricing_model: Option, max_total_charge_usd: f64, prices: IndexMap, @@ -163,6 +192,29 @@ impl Drop for IdempotentChargeInFlight<'_> { } } +/// The standby deployment of a multi-tenant Server Actor run starts with this. +const MULTI_TENANT_DEPLOYMENT_PREFIX: &str = "MULTI_TENANT"; + +/// The pricing in effect now: the latest entry of the Actor's pricing history with +/// `startedAt <= now`, as the history includes scheduled changes. An entry without a valid +/// `startedAt` is never in effect, as `new Date(...) <= now` is false in JS. +/// +/// Resolved once at init on purpose. A change kicking in mid-run only affects local event titles +/// and "unknown event" warnings; the platform prices each charge from its own current pricing. +fn effective_pricing_info(pricing_infos: &[Value], now: chrono::DateTime) -> Option<&Value> { + let started_at = |info: &Value| { + let started_at = info.get("startedAt")?.as_str()?; + chrono::DateTime::parse_from_rfc3339(started_at).ok().map(|at| at.with_timezone(&chrono::Utc)) + }; + // `max_by_key` keeps the last of equal entries, as JS's stable sort and `.at(-1)` do. + pricing_infos + .iter() + .filter_map(|info| Some((started_at(info)?, info))) + .filter(|(started_at, _)| *started_at <= now) + .max_by_key(|(started_at, _)| *started_at) + .map(|(_, info)| info) +} + /// `f64` counts (possibly infinite) as optional integers. fn limit(count: f64) -> Option { count.is_finite().then(|| count.max(0.0) as u64) @@ -180,6 +232,9 @@ pub struct ChargingManager { client: ApifyClient, state: Mutex, log_dataset: tokio::sync::OnceCell, + /// The run and the Actor from the API, fetched once. A failed fetch is tried again next time. + current_run: tokio::sync::OnceCell>, + current_actor: tokio::sync::OnceCell>, } impl std::fmt::Debug for ChargingManager { @@ -196,9 +251,30 @@ impl ChargingManager { client, state: Mutex::new(State { max_total_charge_usd, ..State::default() }), log_dataset: tokio::sync::OnceCell::new(), + current_run: tokio::sync::OnceCell::new(), + current_actor: tokio::sync::OnceCell::new(), } } + /// The current Actor run from the API, fetched once (see [`Actor::get_current_run`](crate::Actor::get_current_run)). + /// `None` when not running on the Apify platform. + pub async fn current_run(&self) -> Result, ApifyClientError> { + let Some(run_id) = self.configuration.actor_run_id.clone() else { return Ok(None) }; + self.current_run.get_or_try_init(|| async { self.client.run(run_id).get().await }).await.cloned() + } + + /// The current Actor from the API, fetched once. `None` without an Actor ID. + async fn current_actor(&self) -> Result, ApifyClientError> { + let Some(actor_id) = self.configuration.actor_id.clone() else { return Ok(None) }; + self.current_actor.get_or_try_init(|| async { self.client.actor(actor_id).get().await }).await.cloned() + } + + /// True in a multi-tenant Server Actor run, which charges per request with + /// [`ChargeOptions::request_id`] only. + pub fn is_multi_tenant(&self) -> bool { + self.state.lock().multi_tenant + } + /// Loads the pricing and what was charged so far (by an earlier incarnation of the run), from /// the environment or the API. `storage` holds the local charging log dataset. pub async fn init(&self, storage: &dyn StorageBackend) -> Result<(), ChargingError> { @@ -218,9 +294,10 @@ impl ChargingManager { )); } - let (pricing_info, charged_counts, max_total_charge_usd) = self.fetch_pricing_info().await?; + let (pricing_info, charged_counts, max_total_charge_usd, multi_tenant) = self.fetch_pricing_info().await?; let is_ppe = { let mut state = self.state.lock(); + state.multi_tenant = multi_tenant; let run_model = pricing_info.get("pricingModel").and_then(Value::as_str).map(str::to_owned); state.pricing_model = if configuration.test_pay_per_event { Some(PAY_PER_EVENT.to_owned()) } else { run_model.clone() }; @@ -253,8 +330,9 @@ impl ChargingManager { Ok(()) } - /// Pricing info (JSON), charged counts, and the budget. - async fn fetch_pricing_info(&self) -> Result<(Value, IndexMap, f64), ChargingError> { + /// Pricing info (JSON), charged counts, the budget, and whether the run is a multi-tenant + /// Server Actor run. + async fn fetch_pricing_info(&self) -> Result<(Value, IndexMap, f64, bool), ChargingError> { let configuration = &self.configuration; let counts = |value: Option<&Value>| -> IndexMap { value @@ -266,18 +344,34 @@ impl ChargingManager { { let pricing: Value = serde_json::from_str(pricing)?; let charged: Value = serde_json::from_str(charged)?; - return Ok((pricing, counts(Some(&charged)), configuration.max_total_charge_usd)); + return Ok((pricing, counts(Some(&charged)), configuration.max_total_charge_usd, false)); } if configuration.is_at_home { - let run_id = configuration.actor_run_id.clone().ok_or_else(|| { - ChargingError::Invalid("Actor run ID not found even though the Actor is running on Apify".to_owned()) - })?; - let run = self - .client - .run(run_id) - .get() - .await? - .ok_or_else(|| ChargingError::Invalid("Actor run not found".to_owned()))?; + if configuration.actor_run_id.is_none() { + return Err(ChargingError::Invalid( + "Actor run ID not found even though the Actor is running on Apify".to_owned(), + )); + } + // A Server Actor run lives long enough to make fetching the Actor worth it up front: + // a multi-tenant one needs it, and it is fetched at the same time as the run. + let is_standby = configuration.meta_origin.as_deref() == Some("STANDBY"); + let (run, actor) = tokio::join!(self.current_run(), async { + if is_standby { Some(self.current_actor().await) } else { None } + }); + let run = run?.ok_or_else(|| ChargingError::Invalid("Actor run not found".to_owned()))?; + let deployment = run.extra.get("standby").and_then(|standby| standby.get("deployment")); + if deployment.and_then(Value::as_str).is_some_and(|d| d.starts_with(MULTI_TENANT_DEPLOYMENT_PREFIX)) { + let actor = match actor { + Some(actor) => actor, + None => self.current_actor().await, + }; + let actor = actor?.ok_or_else(|| ChargingError::Invalid("Actor not found".to_owned()))?; + let pricing_infos = actor.extra.get("pricingInfos").and_then(Value::as_array); + let pricing = + effective_pricing_info(pricing_infos.map_or(&[], Vec::as_slice), chrono::Utc::now()).cloned(); + // The run's counts mix all callers, and the platform prices and limits per caller. + return Ok((pricing.unwrap_or(Value::Null), IndexMap::new(), f64::INFINITY, true)); + } let max = run .extra .get("options") @@ -286,9 +380,9 @@ impl ChargingManager { .filter(|&max| max != 0.0) .unwrap_or(f64::INFINITY); let pricing = run.extra.get("pricingInfo").cloned().unwrap_or(Value::Null); - return Ok((pricing, counts(run.extra.get("chargedEventCounts")), max)); + return Ok((pricing, counts(run.extra.get("chargedEventCounts")), max, false)); } - Ok((Value::Null, IndexMap::new(), configuration.max_total_charge_usd)) + Ok((Value::Null, IndexMap::new(), configuration.max_total_charge_usd, false)) } pub fn is_initialized(&self) -> bool { @@ -340,10 +434,22 @@ impl ChargingManager { chargeable_within_limit: self.chargeable_within_limit_of(&state), }); } + if self.is_multi_tenant() { + return self.charge_server_request(options).await; + } + // As the Python SDK: no charge of nothing reaches the platform or the charging state, and + // its idempotency key is not remembered. + if options.count == 0 { + return Ok(ChargeResult { + event_charge_limit_reached: false, + charged_count: 0, + chargeable_within_limit: self.chargeable_within_limit(), + }); + } if !self.is_initialized() { return Err(ChargingError::NotInitialized); } - let ChargeOptions { event_name, count, idempotency_key } = options; + let ChargeOptions { event_name, count, idempotency_key, request_id } = options; let (charged_count, mut in_flight) = 'charge: loop { let mut in_flight_done = 'wait: { let mut state = self.state.lock(); @@ -392,7 +498,7 @@ impl ChargingManager { let _ = in_flight_done.changed().await; }; if charged_count > 0 - && let Err(err) = self.send_charge(&event_name, charged_count, idempotency_key.clone()).await + && let Err(err) = self.send_charge(&event_name, charged_count, idempotency_key.clone(), request_id).await { // Counted only once made, so that a failed charge retried under its key is counted once. self.add_charged(&mut self.state.lock(), &event_name, -(charged_count as i64)); @@ -422,6 +528,42 @@ impl ChargingManager { }) } + /// A charge in a multi-tenant Server Actor run. The platform prices, limits and deduplicates + /// each caller's charges itself, so nothing is counted or enforced locally, and every call is + /// sent: the platform discards a repeat under an idempotency key used earlier in the run, even + /// by another caller. + async fn charge_server_request(&self, options: ChargeOptions) -> Result { + let ChargeOptions { event_name, count, idempotency_key, request_id } = options; + if event_name.starts_with("apify-") { + return Err(ChargingError::SyntheticEventMultiTenant(event_name)); + } + let Some(request_id) = request_id.filter(|id| !id.is_empty()) else { + return Err(ChargingError::MissingRequestId(event_name)); + }; + let known = self.state.lock().prices.contains_key(&event_name); + let mut charged_count = 0; + if count == 0 { + // Nothing to charge. + } else if !known { + tracing::warn!("Attempting to charge for an unknown event '{event_name}'"); + } else { + let run_id = self.configuration.actor_run_id.clone().unwrap_or_default(); + let charge = RunChargeOptions { + event_name, + count: Some(count as i64), + idempotency_key, + request_id: Some(request_id), + }; + self.client.run(run_id).charge(charge).await?; + charged_count = count; + } + Ok(ChargeResult { + event_charge_limit_reached: false, + charged_count, + chargeable_within_limit: self.chargeable_within_limit(), + }) + } + /// Counts up to `count` events as charged, as far as the budget allows (one more when it /// allows fewer, unless already over it), and returns how many. fn reserve(&self, state: &mut State, event_name: &str, count: u64) -> u64 { @@ -459,7 +601,7 @@ impl ChargingManager { pub(crate) fn reserve_items(&self, items_count: usize, events: &[&str], is_default_dataset: bool) -> usize { let mut state = self.state.lock(); let limit = self.push_data_limit_of(&state, items_count, events, is_default_dataset); - if state.pricing_model.as_deref() == Some(PAY_PER_EVENT) { + if state.pricing_model.as_deref() == Some(PAY_PER_EVENT) && !state.multi_tenant { for event in Self::item_events(events, is_default_dataset) { self.add_charged(&mut state, event, limit as i64); } @@ -471,7 +613,7 @@ impl ChargingManager { /// not stored. pub(crate) fn unreserve_items(&self, events: &[&str], is_default_dataset: bool, items_count: usize) { let mut state = self.state.lock(); - if state.pricing_model.as_deref() == Some(PAY_PER_EVENT) { + if state.pricing_model.as_deref() == Some(PAY_PER_EVENT) && !state.multi_tenant { for event in Self::item_events(events, is_default_dataset) { self.add_charged(&mut state, event, -(items_count as i64)); } @@ -485,7 +627,7 @@ impl ChargingManager { is_default_dataset: bool, items_count: usize, ) -> Result<(), ChargingError> { - if !self.is_pay_per_event() || items_count == 0 { + if !self.is_pay_per_event() || self.is_multi_tenant() || items_count == 0 { return Ok(()); } // An event listed more than once goes in one call, as many times per item. @@ -494,7 +636,7 @@ impl ChargingManager { *counts.entry(event).or_default() += items_count as u64; } for (event, count) in counts { - self.send_charge(event, count, None).await?; + self.send_charge(event, count, None, None).await?; } Ok(()) } @@ -516,6 +658,7 @@ impl ChargingManager { event_name: &str, count: u64, idempotency_key: Option, + request_id: Option, ) -> Result<(), ChargingError> { let (known, title, price) = { let state = self.state.lock(); @@ -537,7 +680,7 @@ impl ChargingManager { event_name: event_name.to_owned(), count: Some(count as i64), idempotency_key: idempotency_key.clone(), - request_id: None, + request_id: request_id.clone(), }; self.client.run(run_id).charge(charge).await?; } else { @@ -554,6 +697,9 @@ impl ChargingManager { if let Some(key) = idempotency_key { entry["idempotencyKey"] = Value::String(key); } + if let Some(request_id) = request_id { + entry["requestId"] = Value::String(request_id); + } entry["timestamp"] = Value::String(crawlee::core::now_iso()); dataset.push_data(&entry).await?; } @@ -662,9 +808,11 @@ impl DatasetBackend for ChargingDataset { let charging = &self.charging; // Datasets also work before the Actor is initialized, with nothing to charge. Items the // Actor reserved the charges of are stored as they are. + // Multi-tenant runs charge per request only, so dataset writes charge nothing there. if items.is_empty() || !charging.is_initialized() || !charging.is_pay_per_event() + || charging.is_multi_tenant() || ITEMS_RESERVED.try_with(|_| ()).is_ok() { return self.inner.push_data(items).await; @@ -772,6 +920,45 @@ mod tests { ChargingManager::new(Arc::new(configuration), client) } + #[tokio::test] + async fn a_charge_of_nothing_changes_nothing_and_keeps_no_key() { + let manager = manager(10.0, &[(DEFAULT_DATASET_ITEM_EVENT, 1.0)], &[]); + // A synthetic event, which is counted without an API call. + manager.init(&crawlee::core::MemoryStorageBackend::new()).await.unwrap(); + assert_eq!(manager.charge(ChargeOptions::new(DEFAULT_DATASET_ITEM_EVENT, 2)).await.unwrap().charged_count, 2); + let keyed = |count: u64| ChargeOptions { + idempotency_key: Some("k".to_owned()), + ..ChargeOptions::new(DEFAULT_DATASET_ITEM_EVENT, count) + }; + let nothing = manager.charge(keyed(0)).await.unwrap(); + assert_eq!(nothing.charged_count, 0); + assert!(!nothing.event_charge_limit_reached); + assert_eq!(manager.charged_event_count(DEFAULT_DATASET_ITEM_EVENT), 2); + // The key of a charge of nothing is not remembered: a charge under it is made. + assert_eq!(manager.charge(keyed(1)).await.unwrap().charged_count, 1); + assert_eq!(manager.charged_event_count(DEFAULT_DATASET_ITEM_EVENT), 3); + } + + #[test] + fn the_effective_pricing_is_the_latest_one_started() { + let now = chrono::DateTime::parse_from_rfc3339("2026-06-01T00:00:00Z").unwrap().with_timezone(&chrono::Utc); + let info = |n: u64, started_at: &str| serde_json::json!({ "n": n, "startedAt": started_at }); + let history = [ + info(1, "2021-01-01T00:00:00.000Z"), + info(2, "2999-01-01T00:00:00.000Z"), + info(3, "2020-01-01T00:00:00.000Z"), + info(4, "2026-06-01T00:00:00.000Z"), + info(5, "not a date"), + ]; + assert_eq!(effective_pricing_info(&history, now).unwrap()["n"], 4, "started exactly now"); + assert_eq!(effective_pricing_info(&history[..3], now).unwrap()["n"], 1, "not the last, nor a future one"); + // Of entries started at the same time, the last one, as JS's stable sort keeps it. + let ties = [info(1, "2020-01-01T00:00:00Z"), info(2, "2020-01-01T00:00:00.000Z")]; + assert_eq!(effective_pricing_info(&ties, now).unwrap()["n"], 2); + assert!(effective_pricing_info(&history[1..2], now).is_none()); + assert!(effective_pricing_info(&[], now).is_none()); + } + #[tokio::test] async fn a_charge_repeated_under_its_idempotency_key_counts_once() { let manager = manager(10.0, &[("page", 1.0), ("apify-default-dataset-item", 0.5)], &[]); diff --git a/src/google_sheets.rs b/src/google_sheets.rs new file mode 100644 index 0000000..9f9aa44 --- /dev/null +++ b/src/google_sheets.rs @@ -0,0 +1,113 @@ +//! Google Sheets sharing links in the `requestsFromUrl` entries of the input, replaced with the +//! links of their CSV exports, as the JS SDK's `getInput` does (`google_sheets.ts`). + +use std::sync::LazyLock; + +use regex::Regex; +use serde_json::{Map, Value}; + +/// A sheet's link, its ID, and whether it already points at an export (`/gviz/...`, `/export...`). +/// JS writes the ID as `(?!e\/)(?:\w|-)+`: links published to the web +/// (`/spreadsheets/d/e//pub?output=csv`) are downloadable as they are. The `regex` crate has +/// no lookahead, so [`to_google_sheets_csv_url`] checks for them itself. +static GOOGLE_SHEETS_URL: LazyLock = LazyLock::new(|| { + Regex::new(r"^(https://docs\.google\.com/spreadsheets/d/([A-Za-z0-9_-]+))(/(?:gviz|export)(?-u:\b))?").unwrap() +}); + +/// The link of the CSV export of a Google Sheets sharing link. Other URLs are returned unchanged. +pub fn to_google_sheets_csv_url(url: &str) -> String { + let Some(captures) = GOOGLE_SHEETS_URL.captures(url) else { return url.to_owned() }; + let sheet = &captures[1]; + let published = &captures[2] == "e" && url[sheet.len()..].starts_with('/'); + if published || captures.get(3).is_some() { + return url.to_owned(); + } + format!("{sheet}/gviz/tq?tqx=out:csv") +} + +/// Replaces Google Sheets sharing links in the `requestsFromUrl` entries of the input's array +/// fields (as the "Link remote text file" option of the `requestListSources` editor makes them) +/// with the links of their CSV exports. +pub fn fix_google_sheets_urls(mut input: Map) -> Map { + for value in input.values_mut() { + let Value::Array(items) = value else { continue }; + for item in items { + if let Some(Value::String(url)) = item.get_mut("requestsFromUrl") { + *url = to_google_sheets_csv_url(url); + } + } + } + input +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + const ID: &str = "11UGSBOSXy5Ov2WEP9nr4kSIxQJmH18zh-5onKtBsovU"; + + fn csv_url() -> String { + format!("https://docs.google.com/spreadsheets/d/{ID}/gviz/tq?tqx=out:csv") + } + + #[test] + fn rewrites_sharing_links_to_the_csv_export() { + for suffix in ["", "/", "/edit?usp=sharing", "/123123132", "/?q=blablabla", "/edit#gid=0"] { + let url = format!("https://docs.google.com/spreadsheets/d/{ID}{suffix}"); + assert_eq!(to_google_sheets_csv_url(&url), csv_url(), "{url}"); + } + } + + #[test] + fn keeps_published_and_export_links_and_other_urls() { + for url in [ + "https://docs.google.com/spreadsheets/d/e/2PACX-1vSabc_DEF-123/pub?gid=0&single=true&output=csv".to_owned(), + format!("https://docs.google.com/spreadsheets/d/{ID}/gviz/tq?tqx=out:csv&sheet=Second"), + format!("https://docs.google.com/spreadsheets/d/{ID}/export?format=csv&gid=123"), + "https://example.com/urls.txt".to_owned(), + ] { + assert_eq!(to_google_sheets_csv_url(&url), url); + } + } + + #[test] + fn an_id_that_only_starts_with_e_is_rewritten() { + // `(?!e\/)` only rejects the `e/` of a published link. + let url = "https://docs.google.com/spreadsheets/d/eabc/edit"; + assert_eq!(to_google_sheets_csv_url(url), "https://docs.google.com/spreadsheets/d/eabc/gviz/tq?tqx=out:csv"); + // `/exports` is no export link: `\b` needs the word to end there. + let url = format!("https://docs.google.com/spreadsheets/d/{ID}/exports"); + assert_eq!(to_google_sheets_csv_url(&url), csv_url()); + } + + #[test] + fn rewrites_only_the_requests_from_url_entries_of_array_fields() { + let sharing_url = format!("https://docs.google.com/spreadsheets/d/{ID}/edit?usp=sharing"); + let input = json!({ + "startUrls": [ + { "url": sharing_url }, + { "requestsFromUrl": sharing_url, "method": "POST", "userData": { "label": "LIST" } }, + { "requestsFromUrl": "https://example.com/urls.txt" }, + "https://example.com", + ], + "sheetUrl": sharing_url, + "nested": { "requestsFromUrl": sharing_url }, + }); + let Value::Object(input) = input else { unreachable!() }; + assert_eq!( + Value::Object(fix_google_sheets_urls(input)), + json!({ + "startUrls": [ + { "url": sharing_url }, + { "requestsFromUrl": csv_url(), "method": "POST", "userData": { "label": "LIST" } }, + { "requestsFromUrl": "https://example.com/urls.txt" }, + "https://example.com", + ], + "sheetUrl": sharing_url, + "nested": { "requestsFromUrl": sharing_url }, + }) + ); + } +} diff --git a/src/lib.rs b/src/lib.rs index 614614b..32b4719 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -11,6 +11,7 @@ pub mod configuration; #[cfg(feature = "cpu-profile")] pub mod cpu_profile; pub mod events; +pub mod google_sheets; pub mod input; pub mod input_secrets; pub mod js; diff --git a/tests/actor.rs b/tests/actor.rs index a45e19c..cfce6aa 100644 --- a/tests/actor.rs +++ b/tests/actor.rs @@ -77,6 +77,65 @@ async fn input_and_output_on_the_platform() { assert!(!dir.path().join("storage").exists(), "nothing is stored locally"); } +/// Google Sheets sharing links in `requestsFromUrl` entries come as the links of their CSV exports. +#[tokio::test] +async fn the_input_has_google_sheets_csv_export_links() { + let api = FakeApi::start().await; + let input = json!({ + "startUrls": [{ "requestsFromUrl": "https://docs.google.com/spreadsheets/d/abc-123/edit?usp=sharing" }], + }); + api.put_record(DEFAULT_STORE, "INPUT", input.to_string().as_bytes(), "application/json; charset=utf-8"); + let dir = tempfile::tempdir().unwrap(); + + let output = run_child("echo", &platform_env(&api, None), dir.path()).await; + assert_exit(&output, 0); + let expected = json!({ + "startUrls": [{ "requestsFromUrl": "https://docs.google.com/spreadsheets/d/abc-123/gviz/tq?tqx=out:csv" }], + }); + assert_eq!(api.dataset_items(DEFAULT_DATASET), [json!({ "echo": expected })]); +} + +/// A multi-tenant Server Actor run charges per request: items pushed with an event are refused, +/// and the other items are not charged. +#[tokio::test] +async fn a_multi_tenant_run_charges_per_request_only() { + let api = FakeApi::start().await; + api.put_run(json!({ + "id": "run-1", + "standby": { "deployment": "MULTI_TENANT_PAYING_USERS" }, + "options": {}, + "chargedEventCounts": {}, + })); + let pricing = json!({ + "pricingModel": "PAY_PER_EVENT", + "startedAt": "2020-01-01T00:00:00.000Z", + "pricingPerEvent": { "actorChargeEvents": { + "test-event": { "eventTitle": "Test", "eventPriceUsd": 1 }, + "apify-default-dataset-item": { "eventTitle": "Item", "eventPriceUsd": 0.001 }, + }}, + }); + api.put_actor(json!({ "id": "actor-1", "pricingInfos": [pricing] })); + let mut vars = platform_env(&api, None); + vars.push(("APIFY_META_ORIGIN", "STANDBY".to_owned())); + vars.push(("ACTOR_ID", "actor-1".to_owned())); + let dir = tempfile::tempdir().unwrap(); + + let output = run_child("multi-tenant", &vars, dir.path()).await; + assert_exit(&output, 0); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("CURRENT RUN run-1"), "{stdout}"); + assert!(stdout.contains("PUSH AND CHARGE Charging for pushed items is not supported"), "{stdout}"); + assert_eq!(api.dataset_items(DEFAULT_DATASET), [json!({ "id": 3 })]); + let charges: Vec = api + .platform_calls() + .into_iter() + .filter(|(path, _, _)| path.ends_with("/charge")) + .map(|(_, _, body)| body) + .collect(); + assert_eq!(charges, [json!({ "eventName": "test-event", "count": 1, "requestId": "some-request-id" })]); + assert_eq!(api.count_calls("GET /v2/actor-runs/run-1"), 1, "the run is fetched once"); +} + #[tokio::test] async fn a_failing_user_function_exits_with_91() { let api = FakeApi::start().await; @@ -905,6 +964,27 @@ fn child() { }) .await } + "multi-tenant" => { + Actor::main(|| async move { + let run = Actor::get_current_run().await?.expect("a run on the platform"); + println!("CURRENT RUN {}", run.id); + // Rejected before anything is stored or charged. + let err = Actor::push_data_and_charge(&json!({ "id": 1 }), "test-event").await.unwrap_err(); + println!("PUSH AND CHARGE {err}"); + let options = apify::PushOptions { charge_events: vec!["test-event".to_owned()], ..Default::default() }; + assert!(Actor::push_data_buffered_with(&json!({ "id": 2 }), &options).is_err()); + // Stored, and charged nothing: the platform charges per request. + let pushed = Actor::push_data(&json!({ "id": 3 })).await?; + assert_eq!(pushed.charged_count, 0); + let charge = apify::charging::ChargeOptions { + request_id: Some("some-request-id".to_owned()), + ..apify::charging::ChargeOptions::new("test-event", 1) + }; + assert_eq!(Actor::charge(charge).await?.charged_count, 1); + Ok(()) + }) + .await + } "echo-stdout" => { Actor::main(|| async move { let input: Value = Actor::get_input().await?; diff --git a/tests/charging.rs b/tests/charging.rs index 2618beb..58cb65a 100644 --- a/tests/charging.rs +++ b/tests/charging.rs @@ -6,9 +6,9 @@ use std::sync::Arc; use std::time::Duration; use apify::Configuration; -use apify::charging::{ChargeOptions, ChargingManager}; +use apify::charging::{ChargeOptions, ChargingError, ChargingManager}; use axum::http::StatusCode; -use serde_json::json; +use serde_json::{Value, json}; use common::{FakeApi, TOKEN}; @@ -86,3 +86,134 @@ async fn the_idempotency_key_is_sent_with_the_charge() { assert_eq!(api.charge_idempotency_keys(), [Some("key".to_owned())]); } + +/// A multi-tenant Server Actor run whose Actor has the pricing history `pricing_infos`. +async fn multi_tenant_manager(api: &FakeApi, pricing_infos: Value, charged_event_counts: Value) -> ChargingManager { + api.put_run(json!({ + "id": "run-1", + "standby": { "deployment": "MULTI_TENANT_PAYING_USERS" }, + "options": {}, + "chargedEventCounts": charged_event_counts, + })); + api.put_actor(json!({ "id": "actor-1", "pricingInfos": pricing_infos })); + let configuration = Configuration { + is_at_home: true, + token: Some(TOKEN.to_owned()), + api_base_url: api.url.clone(), + api_public_base_url: api.url.clone(), + actor_run_id: Some("run-1".to_owned()), + actor_id: Some("actor-1".to_owned()), + meta_origin: Some("STANDBY".to_owned()), + ..Configuration::default() + }; + let client = apify::new_client(&configuration, None, Default::default()); + let manager = ChargingManager::new(Arc::new(configuration), client); + manager.init(&crawlee::core::MemoryStorageBackend::new()).await.unwrap(); + manager +} + +fn ppe(price: f64, started_at: &str) -> Value { + json!({ + "pricingModel": "PAY_PER_EVENT", + "startedAt": started_at, + "pricingPerEvent": { "actorChargeEvents": { "test-event": { "eventTitle": "Test Event", "eventPriceUsd": price } } }, + }) +} + +fn for_request(event: &str, request_id: Option<&str>) -> ChargeOptions { + ChargeOptions { request_id: request_id.map(str::to_owned), ..ChargeOptions::new(event, 1) } +} + +/// The bodies of the charge calls, in order. +fn charge_bodies(api: &FakeApi) -> Vec { + api.platform_calls().into_iter().filter(|(path, _, _)| path.ends_with("/charge")).map(|(_, _, body)| body).collect() +} + +#[tokio::test] +async fn a_multi_tenant_run_charges_by_the_actor_pricing_and_requires_the_request_id() { + let api = FakeApi::start().await; + // Shared-pool runs carry no pricing snapshot: the pricing comes from the Actor's history. + let history = json!([ + ppe(1.0, "2020-01-01T00:00:00.000Z"), + ppe(2.0, "2021-01-01T00:00:00.000Z"), + ppe(3.0, "2999-01-01T00:00:00.000Z"), + ]); + let manager = multi_tenant_manager(&api, history, json!({})).await; + + assert!(manager.is_multi_tenant()); + // The latest entry with `startedAt <= now`, not the last one (a scheduled change). + let pricing = manager.pricing_info().unwrap(); + assert!(pricing.is_pay_per_event); + assert_eq!(pricing.max_total_charge_usd, f64::INFINITY); + assert_eq!(pricing.per_event_prices.into_iter().collect::>(), [("test-event".to_owned(), 2.0)]); + + for request_id in [None, Some("")] { + let err = manager.charge(for_request("test-event", request_id)).await.unwrap_err(); + assert!(matches!(err, ChargingError::MissingRequestId(_)), "{err}"); + assert!(err.to_string().contains("request_id"), "{err}"); + } + assert_eq!(api.count_calls(CHARGE), 0); + + let err = manager.charge(for_request("apify-default-dataset-item", Some("some-request-id"))).await.unwrap_err(); + assert!(err.to_string().contains("synthetic"), "{err}"); + + let result = manager.charge(for_request("test-event", Some("some-request-id"))).await.unwrap(); + assert_eq!(result.charged_count, 1); + assert_eq!(charge_bodies(&api), [json!({ "eventName": "test-event", "count": 1, "requestId": "some-request-id" })]); + // Fetched once, at init. + assert_eq!(api.count_calls("GET /v2/actor-runs/run-1"), 1); + assert_eq!(api.count_calls("GET /v2/actors/actor-1"), 1); + assert_eq!(manager.current_run().await.unwrap().unwrap().id, "run-1"); + assert_eq!(api.count_calls("GET /v2/actor-runs/run-1"), 1, "the run is kept"); +} + +#[tokio::test] +async fn a_multi_tenant_run_leaves_counting_and_deduplication_to_the_platform() { + let api = FakeApi::start().await; + // The run-wide counts mix all callers, so they are not this run's counts. + let manager = + multi_tenant_manager(&api, json!([ppe(1.0, "2020-01-01T00:00:00.000Z")]), json!({ "test-event": 7 })).await; + + for request_id in ["request-a", "request-b"] { + let options = ChargeOptions { + idempotency_key: Some("shared-key".to_owned()), + ..for_request("test-event", Some(request_id)) + }; + assert_eq!(manager.charge(options).await.unwrap().charged_count, 1); + } + assert_eq!(api.count_calls(CHARGE), 2); + assert_eq!(api.charge_idempotency_keys(), [Some("shared-key".to_owned()), Some("shared-key".to_owned())]); + assert_eq!(manager.charged_event_count("test-event"), 0); + // Nothing charged is nothing sent. + let nothing = ChargeOptions { count: 0, ..for_request("test-event", Some("request-c")) }; + assert_eq!(manager.charge(nothing).await.unwrap().charged_count, 0); + assert_eq!(api.count_calls(CHARGE), 2); +} + +#[tokio::test] +async fn a_multi_tenant_run_without_pay_per_event_pricing_ignores_charges() { + let api = FakeApi::start().await; + let manager = multi_tenant_manager(&api, json!([]), json!({})).await; + + assert!(!manager.is_pay_per_event()); + assert_eq!(manager.charge(for_request("test-event", None)).await.unwrap().charged_count, 0); + assert_eq!(api.count_calls(CHARGE), 0); +} + +#[tokio::test] +async fn the_request_id_is_sent_with_the_charge_of_a_run_of_one_tenant() { + let api = FakeApi::start().await; + let manager = manager(&api).await; + assert!(!manager.is_multi_tenant()); + + assert_eq!(manager.charge(ChargeOptions::new("page", 1)).await.unwrap().charged_count, 1); + let options = ChargeOptions { request_id: Some("some-request-id".to_owned()), ..ChargeOptions::new("page", 1) }; + assert_eq!(manager.charge(options).await.unwrap().charged_count, 1); + assert_eq!( + charge_bodies(&api), + [ + json!({ "eventName": "page", "count": 1 }), + json!({ "eventName": "page", "count": 1, "requestId": "some-request-id" }), + ] + ); +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 0c67683..ee8383f 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -85,6 +85,8 @@ struct Data { run_logs: HashMap, /// The `idempotency-key` headers of charges, in order. charge_idempotency_keys: Vec>, + /// Actors the API returns, by id, in place of a bare one. + actors: HashMap, /// Runs the API answers 404 for, as if removed. removed_runs: std::collections::HashSet, /// Statuses a run's next GETs return, one per GET, the last one kept. @@ -266,6 +268,18 @@ impl FakeApi { self.shared.data.lock().run_logs.insert(id.to_owned(), log.to_owned()); } + /// Adds a run (or replaces one) as the API returns it, by its `id`. + pub fn put_run(&self, run: Value) { + let id = run["id"].as_str().expect("a run id").to_owned(); + self.shared.data.lock().runs.insert(id, run); + } + + /// Sets the Actor the API returns for its `id`. + pub fn put_actor(&self, actor: Value) { + let id = actor["id"].as_str().expect("an Actor id").to_owned(); + self.shared.data.lock().actors.insert(id, actor); + } + /// Sets the status of a run started through the API. pub fn set_run_status(&self, id: &str, status: &str) { self.shared.data.lock().runs.get_mut(id).expect("a started run")["status"] = json!(status); @@ -819,7 +833,10 @@ async fn get_run_log(State(shared): State, Path(id): Path) -> Re (StatusCode::OK, [(header::CONTENT_TYPE, "text/plain")], log).into_response() } -async fn get_actor(Path(id): Path) -> Response { +async fn get_actor(State(shared): State, Path(id): Path) -> Response { + if let Some(actor) = shared.data.lock().actors.get(&id) { + return envelope(StatusCode::OK, actor.clone()); + } let name = id.rsplit('~').next().unwrap_or_default().to_owned(); envelope(StatusCode::OK, json!({ "id": id, "name": name })) }