1use 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#[derive(Debug, Default, Clone)]
25pub struct ActorStartOptions {
26 pub build: Option<String>,
28 pub memory_mbytes: Option<i64>,
30 pub timeout_secs: Option<i64>,
32 pub wait_for_finish: Option<i64>,
34 pub max_items: Option<i64>,
36 pub max_total_charge_usd: Option<f64>,
38 pub content_type: Option<String>,
40 pub restart_on_error: Option<bool>,
42 pub force_permission_level: Option<String>,
44 pub webhooks: Option<Vec<serde_json::Value>>,
47}
48
49impl ActorStartOptions {
50 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 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#[derive(Debug, Default, Clone)]
76pub struct ActorBuildOptions {
77 pub beta_packages: Option<bool>,
79 pub tag: Option<String>,
81 pub use_cache: Option<bool>,
83 pub wait_for_finish: Option<i64>,
85}
86
87#[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 pub async fn get(&self) -> ApifyClientResult<Option<Actor>> {
111 get_resource(&self.ctx, None, &QueryParams::new()).await
112 }
113
114 pub async fn update<T: Serialize>(&self, new_fields: &T) -> ApifyClientResult<Actor> {
116 update_resource(&self.ctx, None, new_fields).await
117 }
118
119 pub async fn delete(&self) -> ApifyClientResult<()> {
121 delete_resource(&self.ctx, None).await
122 }
123
124 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"), ¶ms, body, &content_type).await
143 }
144
145 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 self.root.run(run.id).wait_for_finish(wait_secs).await
161 }
162
163 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"), ¶ms, None, "application/json").await
177 }
178
179 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 pub async fn validate_input<T: Serialize>(&self, input: &T) -> ApifyClientResult<Value> {
214 self.validate_input_for_build(input, None).await
215 }
216
217 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 crate::clients::base::post_action_raw(
234 &self.ctx,
235 Some("validate-input"),
236 ¶ms,
237 Some(body),
238 Some("application/json"),
239 )
240 .await
241 }
242
243 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 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 pub fn builds(&self) -> BuildCollectionClient {
284 BuildCollectionClient::with_base(self.ctx.http.clone(), &self.ctx.url(None), "builds")
285 }
286
287 pub fn runs(&self) -> RunCollectionClient {
289 RunCollectionClient::new(self.ctx.http.clone(), &self.ctx.url(None), "runs")
290 }
291
292 pub fn version(&self, version_number: &str) -> ActorVersionClient {
294 ActorVersionClient::new(self.ctx.http.clone(), &self.ctx.url(None), version_number)
295 }
296
297 pub fn versions(&self) -> ActorVersionCollectionClient {
299 ActorVersionCollectionClient::new(self.ctx.http.clone(), &self.ctx.url(None))
300 }
301
302 pub fn webhooks(&self) -> WebhookCollectionClient {
304 WebhookCollectionClient::with_base(self.ctx.http.clone(), &self.ctx.url(None))
305 }
306
307 pub fn id(&self) -> &str {
309 &self.id
310 }
311}