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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ version = "0.1.0"
edition = "2024"
rust-version = "1.88"
license = "Apache-2.0"
repository = "https://github.com/apify-projects/apify-sdk-rs"
repository = "https://github.com/apify/apify-sdk-rs"
authors = ["Apify Technologies s.r.o."]
publish = false

Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# Apify SDK for Rust

Run [crawlee-rs](https://github.com/apify-projects/crawlee-rs) crawlers as Actors on the
Run [crawlee-rs](https://github.com/apify/crawlee-rs) crawlers as Actors on the
[Apify platform](https://apify.com). A port of the [JS SDK](https://github.com/apify/apify-sdk-js),
using the Rust [Apify API client](https://github.com/apify/apify-client-rust).

**Status: feature-complete port, not yet published or run on the platform.** See
**Status: feature-complete port, running Actors on the platform; not yet published to crates.io.** See
[docs/plan.md](docs/plan.md) for the scope, and
[docs/allowed-differences.md](docs/allowed-differences.md) for deliberate differences from the JS
SDK.
Expand Down
4 changes: 2 additions & 2 deletions docs/plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,10 +123,10 @@ The crawlee-rs changes 1 to 3 above are done (`EventManager::stop_periodic_persi

| Milestone | State |
|---|---|
| M1: runs real Actors | Done. Verified locally and against the fake API; not yet run on the platform |
| M1: runs real Actors | Done. Runs Actors on the platform (the Instagram Actors of instagram-rs) |
| M2: platform API | Done, including shared request queues |
| M3: monetization and input | Done: pay-per-event charging, input secrets, pseudo-URL filters |
| M4: hardening | Golden tests against the JS SDK, live and e2e harnesses, CI and docs done. The live and e2e suites wait for an Apify token (`APIFY_TOKEN` secret in CI). Not published |
| M4: hardening | Golden tests against the JS SDK, live and e2e harnesses, CI and docs done. The live suite runs on pushes to `master`, the e2e suite when started by hand. Not published |

Changes made to crawlee-rs for the SDK: `Event::Custom`, `EventManager::stop_periodic_persist_state`,
`Services::is_global_set`, a public `Configuration::from_sources`, `crawlee::VERSION`, and input
Expand Down
48 changes: 15 additions & 33 deletions src/actor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,9 @@ use crate::child_runs::ChildRunTracker;
use crate::client::{RateLimitCounter, new_client};
use crate::configuration::Configuration;
use crate::input::{ActorInputError, ActorInputErrorCode, Input, InputSchema};
use crate::push::{PushError, PushOptions, PushResult};
use crate::push_buffer::{BufferedPush, PushBuffer};
use crate::schema_validation::{
Entry, PushError, PushOptions, PushResult, Rejected, charge_of_stored, store_validated,
};
use crate::schema_validation::{Entry, Rejected, charge_of_stored, store_validated};
use crate::storage::{ApifyStorageBackend, RequestQueueAccess, SmartStorageBackend};

/// Exit codes of an Actor run (`EXIT_CODES` in `@apify/consts`).
Expand Down Expand Up @@ -936,9 +935,13 @@ impl Actor {
data: &T,
events: &[&str],
) -> Result<ChargeResult, ChargingError> {
// Serialized once, straight from `data`: the items are not built as a `Value` tree first.
let mut items = serialize_items(data)?;
// Opened first, so that a failure to open it leaves no charges reserved.
let dataset = state().services.open_dataset(&StorageIdentifier::Default).await?;
let options = PushOptions {
charge_events: events.iter().map(|event| (*event).to_owned()).collect(),
..Default::default()
};
let (items, _, is_default_dataset, charge) = Self::reserve_push(data, &options)?;
let charging = &state().charging;
if !charging.is_pay_per_event() {
let count = items.len() as u64;
Expand All @@ -948,39 +951,18 @@ impl Actor {
for event in events {
result = Some(charging.charge(ChargeOptions::new(*event, count)).await?);
}
return Ok(result.unwrap_or_else(|| ChargeResult {
event_charge_limit_reached: false,
charged_count: 0,
chargeable_within_limit: charging.chargeable_within_limit(),
}));
return Ok(result.unwrap_or(charge));
}
// Storing an item also charges the per-item event when the dataset is the Actor's own.
let is_default_dataset = state().smart.is_some();
let limit = charging.reserve_items(items.len(), events, is_default_dataset);
if limit == 0 {
return Ok(ChargeResult {
event_charge_limit_reached: !items.is_empty(),
charged_count: 0,
chargeable_within_limit: charging.chargeable_within_limit(),
});
if items.is_empty() {
return Ok(charge);
}
items.truncate(limit);
let stored = items.len();
if let Err(err) = ChargingManager::with_items_reserved(dataset.push_items(items)).await {
charging.unreserve_items(events, is_default_dataset, limit);
charging.unreserve_items(events, is_default_dataset, stored);
return Err(err.into());
}
charging.send_item_charges(events, is_default_dataset, limit).await?;
let reached = if events.is_empty() {
charging.is_event_charge_limit_reached(DEFAULT_DATASET_ITEM_EVENT)
} else {
events.iter().any(|event| charging.is_event_charge_limit_reached(event))
};
Ok(ChargeResult {
event_charge_limit_reached: reached,
// Without the default dataset item event, `push_data` charges nothing.
charged_count: if events.is_empty() && !is_default_dataset { 0 } else { limit as u64 },
chargeable_within_limit: charging.chargeable_within_limit(),
})
charging.send_item_charges(events, is_default_dataset, stored).await?;
Ok(charge)
}

/// A value of the default key-value store.
Expand Down
5 changes: 3 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Apify SDK for Rust: run [crawlee-rs](https://github.com/apify-projects/crawlee-rs) crawlers as
//! Apify SDK for Rust: run [crawlee-rs](https://github.com/apify/crawlee-rs) crawlers as
//! Actors on the [Apify platform](https://apify.com), a port of the JS SDK (`apify` on npm).
//!
//! See `docs/plan.md` for the scope and the milestones.
Expand All @@ -16,6 +16,7 @@ pub mod input_secrets;
pub mod log;
pub mod platform;
pub mod proxy;
pub mod push;
pub mod push_buffer;
mod run_log;
mod schema_repair;
Expand All @@ -34,8 +35,8 @@ pub use crate::platform::{
AbortOptions, ApifyEnv, CallOptions, MetamorphOptions, ResurrectOptions, RunLog, RunTimeout, WebhookOptions,
};
pub use crate::proxy::{ProxyConfiguration, ProxyConfigurationOptions};
pub use crate::push::{InvalidItem, OnInvalidItems, PushError, PushOptions, PushResult};
pub use crate::push_buffer::BufferedPush;
pub use crate::schema_validation::{InvalidItem, OnInvalidItems, PushError, PushOptions, PushResult};
pub use crate::storage::{ApifyStorageBackend, RequestQueueAccess, SmartStorageBackend};

pub use apify_client::{ApiError, ApifyClient, ApifyClientError, ApifyClientResult};
Expand Down
2 changes: 1 addition & 1 deletion src/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
//! through `log` in JS. The crates underneath (the HTTP stack) log at `info` at most. `RUST_LOG`,
//! when set, replaces all of that until [`set_level`].
//!
//! An Actor that reads its log level from its input knows it only after [`Actor::init`]
//! An Actor that reads its log level from its input knows it only after [`Actor::init`](crate::Actor::init)
//! (crate::Actor::init), whose debug lines (its API calls, for one) would be lost.
//! [`LogOptions::buffer_startup_debug`] keeps them until the level is set: [`set_level`] at debug
//! logs them, with the time they were made, and any other level, or
Expand Down
74 changes: 74 additions & 0 deletions src/push.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
//! The options and results of the pushes to the default dataset (see
//! [`Actor::push_data_with`](crate::Actor::push_data_with)).

use std::sync::Arc;

use crawlee::core::StorageError;
use crawlee::core::storage::backend::DatasetItem;
use serde_json::Value;

use crate::charging::{ChargeResult, ChargingError};

/// What happens to the items of a push that the dataset's schema rejects. The other items are
/// stored either way.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum OnInvalidItems {
/// They come back in [`PushResult::invalid_items`].
#[default]
Return,
/// They are repaired and pushed again, as `pushDataWithSchemaRepair` of `@apify/actor-utils`
/// repairs them: a field that fails the schema is removed, a missing required field gets an
/// empty placeholder (`""`, `[]`, `{}` or `null`), and a property the schema does not allow
/// is removed. No other value is made up. The repairs are logged; the items that cannot be
/// repaired come back in [`PushResult::invalid_items`], with the errors that kept them from it.
Repair,
/// They are dropped, which is logged.
Drop,
}

/// Options of [`Actor::push_data_with`](crate::Actor::push_data_with) and
/// [`Actor::push_data_buffered_with`](crate::Actor::push_data_buffered_with).
#[derive(Clone, Debug, Default)]
pub struct PushOptions {
/// The events to charge for each item, as
/// [`Actor::push_data_and_charge_events`](crate::Actor::push_data_and_charge_events) charges
/// them. An event listed `n` times is charged `n` times for each item, as an add-on priced by
/// the item's parts is.
pub charge_events: Vec<String>,
pub on_invalid_items: OnInvalidItems,
}

/// What a push stored and charged.
#[derive(Debug)]
pub struct PushResult {
/// The charges of the stored items: the items over the budget were left out, and the items
/// the dataset's schema rejected are not charged.
pub charge: ChargeResult,
/// The items the dataset's schema rejected that were not stored, as the push asked
/// ([`OnInvalidItems`]). The other items were stored.
pub invalid_items: Vec<InvalidItem>,
}

/// Why the items of a push were not stored, or not charged.
#[derive(Debug, thiserror::Error)]
pub enum PushError {
/// None of the items of the push were stored.
#[error("Storing the pushed items failed: {0}")]
Failed(Arc<StorageError>),
/// The items were not charged: the event cannot be charged, or charging for the stored items
/// failed.
#[error("Charging for the pushed items failed: {0}")]
Charge(Arc<ChargingError>),
}

/// An item the dataset's schema rejected.
#[derive(Debug)]
pub struct InvalidItem {
/// Its index in the items of the push.
pub index: usize,
/// The item, as it was pushed.
pub item: DatasetItem,
/// Why, as the platform reports it: `instancePath`, `keyword`, `params`, `message`, ...
/// For an item that could not be repaired, the errors that kept it from it.
pub validation_errors: Vec<Value>,
}
5 changes: 2 additions & 3 deletions src/push_buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,8 @@ use parking_lot::Mutex;
use tokio::sync::{mpsc, oneshot};

use crate::charging::{ChargeResult, ChargingError, ChargingManager, DEFAULT_DATASET_ITEM_EVENT};
use crate::schema_validation::{
Entry, OnInvalidItems, PushError, PushResult, Rejected, charge_of_stored, store_validated,
};
use crate::push::{OnInvalidItems, PushError, PushResult};
use crate::schema_validation::{Entry, Rejected, charge_of_stored, store_validated};

/// The most bytes of items in one request, below the platform's payload limit.
const MAX_BATCH_BYTES: usize = 9_000_000;
Expand Down
68 changes: 2 additions & 66 deletions src/schema_validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@
//! or dropped), and the others are pushed again.

use std::collections::BTreeSet;
use std::sync::Arc;

use apify_client::ApifyClientError;
use crawlee::Dataset;
use crawlee::core::StorageError;
use crawlee::core::storage::backend::DatasetItem;
use serde_json::Value;

use crate::charging::{ChargeResult, ChargingError, ChargingManager};
use crate::charging::{ChargeResult, ChargingManager};
use crate::push::{InvalidItem, OnInvalidItems};
use crate::schema_repair::{RepairedItem, field_issue, format_fields};

/// How many times the items are pushed again after the dataset's schema rejected some. Repairs
Expand All @@ -25,70 +25,6 @@ const MAX_VALIDATION_ROUNDS: usize = 5;
/// The error type of the platform when a dataset's schema rejects items.
const SCHEMA_VALIDATION_ERROR: &str = "schema-validation-error";

/// What happens to the items of a push that the dataset's schema rejects. The other items are
/// stored either way.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum OnInvalidItems {
/// They come back in [`PushResult::invalid_items`].
#[default]
Return,
/// They are repaired and pushed again, as `pushDataWithSchemaRepair` of `@apify/actor-utils`
/// repairs them: a field that fails the schema is removed, a missing required field gets an
/// empty placeholder (`""`, `[]`, `{}` or `null`), and a property the schema does not allow
/// is removed. No other value is made up. The repairs are logged; the items that cannot be
/// repaired come back in [`PushResult::invalid_items`], with the errors that kept them from it.
Repair,
/// They are dropped, which is logged.
Drop,
}

/// Options of [`Actor::push_data_with`](crate::Actor::push_data_with) and
/// [`Actor::push_data_buffered_with`](crate::Actor::push_data_buffered_with).
#[derive(Clone, Debug, Default)]
pub struct PushOptions {
/// The events to charge for each item, as
/// [`Actor::push_data_and_charge_events`](crate::Actor::push_data_and_charge_events) charges
/// them. An event listed `n` times is charged `n` times for each item, as an add-on priced by
/// the item's parts is.
pub charge_events: Vec<String>,
pub on_invalid_items: OnInvalidItems,
}

/// What a push stored and charged.
#[derive(Debug)]
pub struct PushResult {
/// The charges of the stored items: the items over the budget were left out, and the items
/// the dataset's schema rejected are not charged.
pub charge: ChargeResult,
/// The items the dataset's schema rejected that were not stored, as the push asked
/// ([`OnInvalidItems`]). The other items were stored.
pub invalid_items: Vec<InvalidItem>,
}

/// Why the items of a push were not stored, or not charged.
#[derive(Debug, thiserror::Error)]
pub enum PushError {
/// None of the items of the push were stored.
#[error("Storing the pushed items failed: {0}")]
Failed(Arc<StorageError>),
/// The items were not charged: the event cannot be charged, or charging for the stored items
/// failed.
#[error("Charging for the pushed items failed: {0}")]
Charge(Arc<ChargingError>),
}

/// An item the dataset's schema rejected.
#[derive(Debug)]
pub struct InvalidItem {
/// Its index in the items of the push.
pub index: usize,
/// The item, as it was pushed.
pub item: DatasetItem,
/// Why, as the platform reports it: `instancePath`, `keyword`, `params`, `message`, ...
/// For an item that could not be repaired, the errors that kept it from it.
pub validation_errors: Vec<Value>,
}

/// An item to store.
pub(crate) struct Entry {
/// The push it comes from, and its index there.
Expand Down
Loading