Skip to main content

apify_client/clients/
run.rs

1//! Client for a single Actor run (`/v2/actor-runs/{runId}` and nested routes).
2
3use serde::Serialize;
4
5use crate::clients::base::{
6    delete_resource, get_resource, post_action, post_with_body, update_resource, wait_for_finish,
7    ResourceContext,
8};
9use crate::clients::dataset::DatasetClient;
10use crate::clients::key_value_store::KeyValueStoreClient;
11use crate::clients::log::LogClient;
12use crate::clients::request_queue::RequestQueueClient;
13use crate::common::{to_safe_id, QueryParams};
14use crate::error::ApifyClientResult;
15use crate::http_client::HttpClient;
16use crate::models::ActorRun;
17
18/// Header the API uses to deduplicate charge requests (matching the reference client).
19const CHARGE_IDEMPOTENCY_HEADER: &str = "idempotency-key";
20
21/// Options for fetching an Actor's or task's last run
22/// ([`crate::clients::actor::ActorClient::last_run_with_options`] /
23/// [`crate::clients::task::TaskClient::last_run_with_options`]).
24///
25/// Both are sent as query parameters to the last-run endpoints
26/// (`GET /v2/actors/{actorId}/runs/last`, `GET /v2/actor-tasks/{actorTaskId}/runs/last`).
27/// `status` and `origin` are both documented optional filters on those endpoints and match the
28/// reference client's `lastRun({ status, origin })`.
29#[derive(Debug, Default, Clone)]
30pub struct LastRunOptions {
31    /// Filter by run status (e.g. `"SUCCEEDED"`, `"FAILED"`, `"RUNNING"`). `None` leaves it
32    /// unfiltered.
33    pub status: Option<String>,
34    /// Filter by how the run was started; accepted values are the platform's run origins
35    /// (e.g. `"DEVELOPMENT"`, `"WEB"`, `"API"`, `"SCHEDULER"`). `None` leaves it unfiltered.
36    pub origin: Option<String>,
37}
38
39/// Options for resurrecting a finished run.
40#[derive(Debug, Default, Clone)]
41pub struct RunResurrectOptions {
42    /// Build tag/number to use; defaults to the original run's build.
43    pub build: Option<String>,
44    /// Memory in megabytes.
45    pub memory_mbytes: Option<i64>,
46    /// Timeout in seconds.
47    pub timeout_secs: Option<i64>,
48    /// Maximum number of dataset items to charge (pay-per-result Actors).
49    pub max_items: Option<i64>,
50    /// Maximum total charge in USD (pay-per-event Actors).
51    pub max_total_charge_usd: Option<f64>,
52    /// If `true`, restart the run automatically when it fails.
53    pub restart_on_error: Option<bool>,
54}
55
56/// Options for transforming a run into another Actor's run (metamorph).
57#[derive(Debug, Default, Clone)]
58pub struct RunMetamorphOptions {
59    /// Build tag/number of the target Actor to use (defaults to the target's default build).
60    pub build: Option<String>,
61    /// Content type of the input body. Defaults to `application/json` when unset.
62    pub content_type: Option<String>,
63}
64
65/// Options for charging a pay-per-event run via [`RunClient::charge`].
66#[derive(Debug, Default, Clone)]
67pub struct RunChargeOptions {
68    /// Name of the event to charge for. Required.
69    pub event_name: String,
70    /// Number of times to charge the event (defaults to `1`).
71    pub count: Option<i64>,
72    /// Idempotency key deduplicating the charge across retries. If `None`, one is
73    /// auto-generated as `{runId}-{eventName}-{timestampMillis}-{random}`, matching the
74    /// reference client, so a transport-retried charge is applied at most once.
75    pub idempotency_key: Option<String>,
76}
77
78/// Client for a specific Actor run.
79///
80/// In addition to CRUD-style operations, this client exposes the run's lifecycle
81/// actions (abort, metamorph, reboot, resurrect, charge) and provides access to the
82/// run's default dataset, key-value store, request queue and log.
83#[derive(Debug, Clone)]
84pub struct RunClient {
85    ctx: ResourceContext,
86    /// The run ID, retained so `charge` can build a per-run idempotency key.
87    id: String,
88}
89
90impl RunClient {
91    pub(crate) fn new(
92        _root: crate::client::ApifyClient,
93        http: HttpClient,
94        base_url: &str,
95        resource_path: &str,
96        id: &str,
97    ) -> Self {
98        Self {
99            ctx: ResourceContext::single(http, base_url, resource_path, id),
100            id: id.to_string(),
101        }
102    }
103
104    /// Adds a base query parameter to this run client, inherited by its requests (used by
105    /// `actor.last_run` / `task.last_run` to thread the `status` and `origin` filters).
106    pub(crate) fn set_base_param(&mut self, key: &str, value: &str) {
107        self.ctx
108            .base_params
109            .push_raw(key.to_string(), value.to_string());
110    }
111
112    /// Fetches the run object, or `None` if it does not exist.
113    pub async fn get(&self) -> ApifyClientResult<Option<ActorRun>> {
114        get_resource(&self.ctx, None, &QueryParams::new()).await
115    }
116
117    /// Updates the run (e.g. its status message) and returns the updated object.
118    pub async fn update<T: Serialize>(&self, new_fields: &T) -> ApifyClientResult<ActorRun> {
119        update_resource(&self.ctx, None, new_fields).await
120    }
121
122    /// Deletes the run.
123    pub async fn delete(&self) -> ApifyClientResult<()> {
124        delete_resource(&self.ctx, None).await
125    }
126
127    /// Aborts the run. `gracefully` is optional, matching the reference client's optional
128    /// `gracefully` option and the Go sibling's `Option<bool>`: `Some(true)` lets the run
129    /// perform cleanup first, `Some(false)` aborts immediately, and `None` omits the parameter
130    /// entirely so the server applies its default (immediate abort).
131    pub async fn abort(&self, gracefully: Option<bool>) -> ApifyClientResult<ActorRun> {
132        let mut params = QueryParams::new();
133        params.add_bool("gracefully", gracefully);
134        post_action(&self.ctx, Some("abort"), &params, None, None).await
135    }
136
137    /// Transforms the run into a run of another Actor (metamorph).
138    ///
139    /// `options.content_type` sets the content type of the input body (defaulting to
140    /// `application/json`), matching the reference client's `metamorph(..., { contentType })`.
141    pub async fn metamorph<T: Serialize>(
142        &self,
143        target_actor_id: &str,
144        input: Option<&T>,
145        options: RunMetamorphOptions,
146    ) -> ApifyClientResult<ActorRun> {
147        let mut params = QueryParams::new();
148        params
149            .add_str("targetActorId", Some(to_safe_id(target_actor_id)))
150            .add_str("build", options.build);
151        let body = match input {
152            Some(value) => Some(serde_json::to_vec(value)?),
153            None => None,
154        };
155        let content_type = options
156            .content_type
157            .as_deref()
158            .unwrap_or("application/json");
159        post_with_body(&self.ctx, Some("metamorph"), &params, body, content_type).await
160    }
161
162    /// Reboots the run (restarts its container, preserving the run ID and storages).
163    pub async fn reboot(&self) -> ApifyClientResult<ActorRun> {
164        post_action(&self.ctx, Some("reboot"), &QueryParams::new(), None, None).await
165    }
166
167    /// Resurrects a finished run, starting it again with (optionally overridden) settings.
168    pub async fn resurrect(&self, options: RunResurrectOptions) -> ApifyClientResult<ActorRun> {
169        let mut params = QueryParams::new();
170        params
171            .add_str("build", options.build)
172            .add_int("memory", options.memory_mbytes)
173            .add_int("timeout", options.timeout_secs)
174            .add_int("maxItems", options.max_items)
175            .add_float("maxTotalChargeUsd", options.max_total_charge_usd)
176            .add_bool("restartOnError", options.restart_on_error);
177        post_action(&self.ctx, Some("resurrect"), &params, None, None).await
178    }
179
180    /// Charges the run for a pay-per-event run, recording occurrences of a named event.
181    ///
182    /// An idempotency key is always sent (auto-generated when `options.idempotency_key` is
183    /// `None`), so a charge that is retried by the transport is applied at most once — matching
184    /// the reference client and preventing double-charging.
185    ///
186    /// The charge endpoint returns an empty body on success, so this issues the request
187    /// directly and treats any 2xx response as success (errors still surface normally).
188    pub async fn charge(&self, options: RunChargeOptions) -> ApifyClientResult<()> {
189        let count = options.count.unwrap_or(1);
190        let idempotency_key = options
191            .idempotency_key
192            .unwrap_or_else(|| self.generate_idempotency_key(&options.event_name));
193        let body = serde_json::json!({ "eventName": options.event_name, "count": count });
194        let body_bytes = serde_json::to_vec(&body)?;
195        let url = self.ctx.url(Some("charge"));
196        let mut headers = std::collections::HashMap::new();
197        headers.insert("Content-Type".to_string(), "application/json".to_string());
198        headers.insert(CHARGE_IDEMPOTENCY_HEADER.to_string(), idempotency_key);
199        // A successful `HttpClient::call` already guarantees a 2xx status; the (empty) body
200        // is intentionally ignored rather than parsed as a `data` envelope.
201        self.ctx
202            .http
203            .call(crate::http_client::HttpRequest {
204                method: crate::http_client::HttpMethod::Post,
205                url,
206                headers,
207                body: Some(body_bytes),
208                timeout: crate::clients::base::DEFAULT_REQUEST_TIMEOUT,
209            })
210            .await?;
211        Ok(())
212    }
213
214    /// Builds a per-charge idempotency key of the form
215    /// `{runId}-{eventName}-{timestampMillis}-{random}`, matching the reference client. The
216    /// suffix only needs to be unique enough to avoid collisions within the same millisecond;
217    /// it is derived from the sub-millisecond part of the current time (no crypto needed).
218    fn generate_idempotency_key(&self, event_name: &str) -> String {
219        let now = std::time::SystemTime::now()
220            .duration_since(std::time::UNIX_EPOCH)
221            .unwrap_or_default();
222        let millis = now.as_millis();
223        // Sub-millisecond nanos give a cheap, non-crypto "random" suffix (cf. JS Math.random()).
224        let random_suffix = now.subsec_nanos() % 1_000_000;
225        format!("{}-{event_name}-{millis}-{random_suffix}", self.id)
226    }
227
228    /// Waits (by client-side polling) for the run to reach a terminal state.
229    ///
230    /// `wait_secs` controls the wait budget:
231    /// - `None` polls indefinitely until the run reaches a terminal state.
232    /// - `Some(n)` bounds the wait to roughly `n` seconds; if the run has not finished by
233    ///   then, the **last fetched (still non-terminal) run is returned** rather than an
234    ///   error. Check `status` / `is_terminal()` on the result when using `Some`.
235    pub async fn wait_for_finish(&self, wait_secs: Option<i64>) -> ApifyClientResult<ActorRun> {
236        wait_for_finish(&self.ctx, wait_secs, |r: &ActorRun| r.is_terminal()).await
237    }
238
239    /// Returns a client for the run's default dataset.
240    pub fn dataset(&self) -> DatasetClient {
241        DatasetClient::nested(self.ctx.http.clone(), &self.ctx.url(None), "dataset")
242    }
243
244    /// Returns a client for the run's default key-value store.
245    pub fn key_value_store(&self) -> KeyValueStoreClient {
246        KeyValueStoreClient::nested(
247            self.ctx.http.clone(),
248            &self.ctx.url(None),
249            "key-value-store",
250        )
251    }
252
253    /// Returns a client for the run's default request queue.
254    pub fn request_queue(&self) -> RequestQueueClient {
255        RequestQueueClient::nested(self.ctx.http.clone(), &self.ctx.url(None), "request-queue")
256    }
257
258    /// Returns a client for the run's log.
259    pub fn log(&self) -> LogClient {
260        LogClient::nested(self.ctx.http.clone(), &self.ctx.url(None), "log")
261    }
262
263    /// Opens a live stream of the run's log for redirection.
264    ///
265    /// Convenience equivalent to `run.log().stream()` (mirrors the reference client's
266    /// `getStreamedLog`): yields log chunks as they arrive, so callers can forward them to
267    /// their own logger/stdout while the run is in progress.
268    pub async fn get_streamed_log(
269        &self,
270    ) -> ApifyClientResult<impl futures_util::Stream<Item = ApifyClientResult<Vec<u8>>>> {
271        self.log().stream().await
272    }
273
274    /// Opens a live stream of the run's log for redirection, applying the given
275    /// [`LogOptions`] (e.g. [`LogOptions::raw`] to stream the unprocessed log, which is the
276    /// form the JS reference's log redirection consumes internally).
277    ///
278    /// This is a Rust-specific convenience that simply forwards `LogOptions` to
279    /// [`LogClient::stream_with_options`]; it is not a 1:1 mirror of the JS `getStreamedLog`
280    /// method's signature (which takes redirect options and returns a `StreamedLog` object).
281    pub async fn get_streamed_log_with_options(
282        &self,
283        options: crate::clients::log::LogOptions,
284    ) -> ApifyClientResult<impl futures_util::Stream<Item = ApifyClientResult<Vec<u8>>>> {
285        self.log().stream_with_options(options).await
286    }
287}