Skip to main content

apify_client/clients/
actor.rs

1//! Client for a single Actor (`/v2/actors/{actorId}`).
2
3use serde::Serialize;
4use serde_json::Value;
5
6use crate::client::ApifyClient;
7use crate::clients::actor_version::ActorVersionClient;
8use crate::clients::actor_version_collection::ActorVersionCollectionClient;
9use crate::clients::base::{
10    delete_resource, get_resource, post_with_body, update_resource, ResourceContext,
11};
12use crate::clients::build::BuildClient;
13use crate::clients::build_collection::BuildCollectionClient;
14use crate::clients::run::{LastRunOptions, RunClient};
15use crate::clients::run_collection::RunCollectionClient;
16use crate::clients::webhook_collection::WebhookCollectionClient;
17use crate::common::{parse_data_envelope, QueryParams};
18use crate::error::ApifyClientResult;
19use crate::http_client::HttpClient;
20use crate::models::{Actor, ActorRun, Build};
21
22/// Options shared by [`ActorClient::start`] and [`ActorClient::call`] (and the task
23/// equivalents).
24#[derive(Debug, Default, Clone)]
25pub struct ActorStartOptions {
26    /// Tag or number of the build to run (e.g. `latest`, `0.1.2`).
27    pub build: Option<String>,
28    /// Memory in megabytes allocated for the run.
29    pub memory_mbytes: Option<i64>,
30    /// Timeout for the run in seconds (`0` means no timeout).
31    pub timeout_secs: Option<i64>,
32    /// Maximum seconds to wait server-side for the run to finish (max 60).
33    pub wait_for_finish: Option<i64>,
34    /// Maximum number of dataset items to charge (pay-per-result Actors).
35    pub max_items: Option<i64>,
36    /// Maximum total charge in USD (pay-per-event Actors).
37    pub max_total_charge_usd: Option<f64>,
38    /// Content type of the input body. Defaults to `application/json`.
39    pub content_type: Option<String>,
40    /// Whether to restart the run if it fails.
41    pub restart_on_error: Option<bool>,
42    /// Override the Actor's permission level for this run.
43    pub force_permission_level: Option<String>,
44    /// Ad-hoc webhooks to attach to this run. Serialized to base64-encoded JSON as the
45    /// `webhooks` query parameter, matching the reference clients.
46    pub webhooks: Option<Vec<serde_json::Value>>,
47}
48
49impl ActorStartOptions {
50    /// Serializes these options into run-start query parameters. Shared by the Actor and
51    /// task start methods (DRY).
52    pub(crate) fn apply(&self, params: &mut QueryParams) {
53        params
54            .add_str("build", self.build.clone())
55            .add_int("memory", self.memory_mbytes)
56            .add_int("timeout", self.timeout_secs)
57            .add_int("waitForFinish", self.wait_for_finish)
58            .add_int("maxItems", self.max_items)
59            .add_float("maxTotalChargeUsd", self.max_total_charge_usd)
60            .add_bool("restartOnError", self.restart_on_error)
61            .add_str("forcePermissionLevel", self.force_permission_level.clone())
62            .add_str("webhooks", self.encoded_webhooks());
63    }
64
65    /// Encodes the `webhooks` array as base64-encoded JSON, as required by the API.
66    fn encoded_webhooks(&self) -> Option<String> {
67        use base64::Engine;
68        let webhooks = self.webhooks.as_ref()?;
69        let json = serde_json::to_vec(webhooks).ok()?;
70        Some(base64::engine::general_purpose::STANDARD.encode(json))
71    }
72}
73
74/// Options for building an Actor.
75#[derive(Debug, Default, Clone)]
76pub struct ActorBuildOptions {
77    /// If `true`, use beta versions of Apify packages.
78    pub beta_packages: Option<bool>,
79    /// Tag to apply to the build (e.g. `latest`).
80    pub tag: Option<String>,
81    /// Whether to use the Docker build cache (default `true`).
82    pub use_cache: Option<bool>,
83    /// Maximum seconds to wait server-side for the build to finish (max 60).
84    pub wait_for_finish: Option<i64>,
85}
86
87/// Client for a specific Actor.
88///
89/// Provides CRUD methods plus convenience helpers to start/call the Actor, build it,
90/// and access its runs, builds, versions and webhooks.
91#[derive(Debug, Clone)]
92pub struct ActorClient {
93    root: ApifyClient,
94    ctx: ResourceContext,
95    base_url: String,
96    id: String,
97}
98
99impl ActorClient {
100    pub(crate) fn new(root: ApifyClient, http: HttpClient, base_url: &str, id: &str) -> Self {
101        Self {
102            root,
103            ctx: ResourceContext::single(http, base_url, "actors", id),
104            base_url: base_url.to_string(),
105            id: id.to_string(),
106        }
107    }
108
109    /// Fetches the Actor object, or `None` if it does not exist.
110    pub async fn get(&self) -> ApifyClientResult<Option<Actor>> {
111        get_resource(&self.ctx, None, &QueryParams::new()).await
112    }
113
114    /// Updates the Actor with the given fields and returns the updated object.
115    pub async fn update<T: Serialize>(&self, new_fields: &T) -> ApifyClientResult<Actor> {
116        update_resource(&self.ctx, None, new_fields).await
117    }
118
119    /// Deletes the Actor.
120    pub async fn delete(&self) -> ApifyClientResult<()> {
121        delete_resource(&self.ctx, None).await
122    }
123
124    /// Starts the Actor and returns immediately with the created run.
125    ///
126    /// `input` is any JSON-serializable value (or `None` for no input).
127    pub async fn start<T: Serialize>(
128        &self,
129        input: Option<&T>,
130        options: ActorStartOptions,
131    ) -> ApifyClientResult<ActorRun> {
132        let mut params = QueryParams::new();
133        options.apply(&mut params);
134        let content_type = options
135            .content_type
136            .clone()
137            .unwrap_or_else(|| "application/json".to_string());
138        let body = match input {
139            Some(value) => Some(serde_json::to_vec(value)?),
140            None => None,
141        };
142        post_with_body(&self.ctx, Some("runs"), &params, body, &content_type).await
143    }
144
145    /// Starts the Actor and waits (client-side polling) for it to finish.
146    ///
147    /// `wait_secs` controls the wait budget:
148    /// - `None` polls indefinitely until the run reaches a terminal state.
149    /// - `Some(n)` bounds the wait to roughly `n` seconds; if the run has not finished by
150    ///   then, the **last fetched (still non-terminal) run is returned** rather than an
151    ///   error. Check `status` / `is_terminal()` on the result when using `Some`.
152    pub async fn call<T: Serialize>(
153        &self,
154        input: Option<&T>,
155        options: ActorStartOptions,
156        wait_secs: Option<i64>,
157    ) -> ApifyClientResult<ActorRun> {
158        let run = self.start(input, options).await?;
159        // Use the root client's run client so polling targets the canonical run route.
160        self.root.run(run.id).wait_for_finish(wait_secs).await
161    }
162
163    /// Builds the given version of the Actor and returns the created build.
164    pub async fn build(
165        &self,
166        version_number: &str,
167        options: ActorBuildOptions,
168    ) -> ApifyClientResult<Build> {
169        let mut params = QueryParams::new();
170        params
171            .add_str("version", Some(version_number.to_string()))
172            .add_bool("betaPackages", options.beta_packages)
173            .add_str("tag", options.tag)
174            .add_bool("useCache", options.use_cache)
175            .add_int("waitForFinish", options.wait_for_finish);
176        post_with_body(&self.ctx, Some("builds"), &params, None, "application/json").await
177    }
178
179    /// Resolves the Actor's default build and returns a client for it.
180    ///
181    /// `wait_for_finish` optionally bounds how long (in seconds) the API waits for the build
182    /// to finish before responding, matching the reference client's `defaultBuild(options)`.
183    pub async fn default_build(
184        &self,
185        wait_for_finish: Option<i64>,
186    ) -> ApifyClientResult<BuildClient> {
187        let mut params = QueryParams::new();
188        params.add_int("waitForFinish", wait_for_finish);
189        let url = params.apply_to_url(&self.ctx.url(Some("builds/default")));
190        let response = self
191            .ctx
192            .http
193            .call(crate::http_client::HttpRequest {
194                method: crate::http_client::HttpMethod::Get,
195                url,
196                headers: Default::default(),
197                body: None,
198                timeout: crate::clients::base::DEFAULT_REQUEST_TIMEOUT,
199            })
200            .await?;
201        let build: Build = parse_data_envelope(&response.body)?;
202        Ok(BuildClient::new(
203            self.ctx.http.clone(),
204            &self.base_url,
205            &build.id,
206        ))
207    }
208
209    /// Validates the given input against the Actor's input schema.
210    ///
211    /// Uses the Actor's default build for the input schema. To validate against a specific
212    /// build, use [`ActorClient::validate_input_for_build`].
213    pub async fn validate_input<T: Serialize>(&self, input: &T) -> ApifyClientResult<Value> {
214        self.validate_input_for_build(input, None).await
215    }
216
217    /// Validates the given input against the input schema of a specific Actor build.
218    ///
219    /// `build` is the optional tag or number of the Actor build whose input schema is used for
220    /// validation (e.g. `"latest"` or `"1.2.34"`); passing `None` uses the default build, which
221    /// is equivalent to [`ActorClient::validate_input`]. This maps to the spec's optional `build`
222    /// query parameter on `POST /v2/actors/{actorId}/validate-input`.
223    pub async fn validate_input_for_build<T: Serialize>(
224        &self,
225        input: &T,
226        build: Option<&str>,
227    ) -> ApifyClientResult<Value> {
228        let body = serde_json::to_vec(input)?;
229        let mut params = QueryParams::new();
230        params.add_str("build", build);
231        // `validate-input` returns a bare `{ "valid": ... }` object, *not* the usual
232        // `{ "data": ... }` envelope, so it must skip `parse_data_envelope`.
233        crate::clients::base::post_action_raw(
234            &self.ctx,
235            Some("validate-input"),
236            &params,
237            Some(body),
238            Some("application/json"),
239        )
240        .await
241    }
242
243    /// Returns a client for the last run of this Actor, optionally filtered by run status.
244    ///
245    /// `status` filters by run status (e.g. `"SUCCEEDED"`, `"FAILED"`, `"RUNNING"`); pass `None`
246    /// to leave it unfiltered. This maps to the `status` query parameter on
247    /// `GET /v2/actors/{actorId}/runs/last` and mirrors the reference client's `lastRun({ status })`.
248    /// To also filter by `origin`, use [`ActorClient::last_run_with_options`].
249    pub fn last_run(&self, status: Option<&str>) -> RunClient {
250        self.last_run_with_options(LastRunOptions {
251            status: status.map(str::to_owned),
252            origin: None,
253        })
254    }
255
256    /// Returns a client for the last run of this Actor, applying the given [`LastRunOptions`]
257    /// (e.g. [`LastRunOptions::status`] and/or [`LastRunOptions::origin`]).
258    ///
259    /// `status` filters by run status (e.g. `"SUCCEEDED"`, `"FAILED"`, `"RUNNING"`) and is the
260    /// spec's documented filter on `GET /v2/actors/{actorId}/runs/last`. `origin` filters by how
261    /// the run was started; accepted values are the platform's run origins (e.g. `"DEVELOPMENT"`,
262    /// `"WEB"`, `"API"`, `"SCHEDULER"`). `origin` is not declared by the OpenAPI spec and is sent
263    /// only for parity with the reference client's `lastRun({ status, origin })`. Both are sent as
264    /// query parameters; leave a field as `None` to omit it.
265    pub fn last_run_with_options(&self, options: LastRunOptions) -> RunClient {
266        let mut client = RunClient::new(
267            self.root.clone(),
268            self.ctx.http.clone(),
269            &self.ctx.url(None),
270            "runs",
271            "last",
272        );
273        if let Some(status) = options.status.as_deref() {
274            client.set_base_param("status", status);
275        }
276        if let Some(origin) = options.origin.as_deref() {
277            client.set_base_param("origin", origin);
278        }
279        client
280    }
281
282    /// Returns a client for this Actor's build collection.
283    pub fn builds(&self) -> BuildCollectionClient {
284        BuildCollectionClient::with_base(self.ctx.http.clone(), &self.ctx.url(None), "builds")
285    }
286
287    /// Returns a client for this Actor's run collection.
288    pub fn runs(&self) -> RunCollectionClient {
289        RunCollectionClient::new(self.ctx.http.clone(), &self.ctx.url(None), "runs")
290    }
291
292    /// Returns a client for a specific version of this Actor.
293    pub fn version(&self, version_number: &str) -> ActorVersionClient {
294        ActorVersionClient::new(self.ctx.http.clone(), &self.ctx.url(None), version_number)
295    }
296
297    /// Returns a client for this Actor's version collection.
298    pub fn versions(&self) -> ActorVersionCollectionClient {
299        ActorVersionCollectionClient::new(self.ctx.http.clone(), &self.ctx.url(None))
300    }
301
302    /// Returns a client for this Actor's webhook collection.
303    pub fn webhooks(&self) -> WebhookCollectionClient {
304        WebhookCollectionClient::with_base(self.ctx.http.clone(), &self.ctx.url(None))
305    }
306
307    /// The Actor's ID (or `username~name`) as provided.
308    pub fn id(&self) -> &str {
309        &self.id
310    }
311}