1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
//! Client for a single request queue (`/v2/request-queues/{queueId}` and variants).
use serde::Serialize;
use crate::clients::base::{
delete_resource, delete_with_body, get_resource, get_resource_required, post_action,
post_with_body, update_resource, ResourceContext,
};
use crate::common::{encode_path_segment, QueryParams};
use crate::error::ApifyClientResult;
use crate::http_client::{HttpClient, HttpMethod, HttpRequest};
use crate::models::{
RequestQueue, RequestQueueHead, RequestQueueOperationInfo, RequestQueueRequest,
};
/// Maximum number of requests the API accepts in a single `requests/batch` call. Larger
/// inputs are split into chunks of this size (matching the reference client).
const MAX_REQUESTS_PER_BATCH_OPERATION: usize = 25;
/// Appends the array under `key` in `chunk_result` (if present) onto `acc`. Used to merge the
/// per-chunk `processedRequests` / `unprocessedRequests` arrays of a chunked batch-add.
fn merge_request_array(
acc: &mut Vec<serde_json::Value>,
chunk_result: &serde_json::Value,
key: &str,
) {
if let Some(items) = chunk_result.get(key).and_then(|v| v.as_array()) {
acc.extend(items.iter().cloned());
}
}
/// Options for [`RequestQueueClient::list_requests`].
///
/// Covers the spec query parameters of `GET /v2/request-queues/{queueId}/requests`.
#[derive(Debug, Default, Clone)]
pub struct ListRequestsOptions {
/// Maximum number of requests to return.
pub limit: Option<i64>,
/// Start listing after this request ID (exclusive).
pub exclusive_start_id: Option<String>,
/// Opaque pagination cursor returned by a previous call.
pub cursor: Option<String>,
/// Restrict the returned requests to the given states. The spec defines this as an array of
/// the enum values `"locked"` and `"pending"`; multiple values are sent comma-joined (matching
/// the JS reference, which serializes `filter: Array<'locked' | 'pending'>` via `join(',')`).
pub filter: Option<Vec<String>>,
}
/// Client for a specific request queue.
#[derive(Debug, Clone)]
pub struct RequestQueueClient {
ctx: ResourceContext,
client_key: Option<String>,
}
impl RequestQueueClient {
pub(crate) fn new(http: HttpClient, base_url: &str, resource_path: &str, id: &str) -> Self {
Self {
ctx: ResourceContext::single(http, base_url, resource_path, id),
client_key: None,
}
}
/// Creates an RQ client for a run's default queue (nested path, no ID).
pub(crate) fn nested(http: HttpClient, base_url: &str, sub_path: &str) -> Self {
Self {
ctx: ResourceContext::collection(http, base_url, sub_path),
client_key: None,
}
}
/// Sets the `clientKey` used to identify this client across requests (for locking).
pub fn with_client_key(mut self, client_key: impl Into<String>) -> Self {
self.client_key = Some(client_key.into());
self
}
fn base_params(&self) -> QueryParams {
let mut params = QueryParams::new();
params.add_str("clientKey", self.client_key.clone());
params
}
/// Fetches the queue metadata, or `None` if it does not exist.
pub async fn get(&self) -> ApifyClientResult<Option<RequestQueue>> {
get_resource(&self.ctx, None, &QueryParams::new()).await
}
/// Updates the queue metadata (e.g. `name`, `title`).
pub async fn update<T: Serialize>(&self, new_fields: &T) -> ApifyClientResult<RequestQueue> {
update_resource(&self.ctx, None, new_fields).await
}
/// Deletes the queue.
pub async fn delete(&self) -> ApifyClientResult<()> {
delete_resource(&self.ctx, None).await
}
/// Lists requests from the head of the queue (without locking them).
pub async fn list_head(&self, limit: Option<i64>) -> ApifyClientResult<RequestQueueHead> {
let mut params = self.base_params();
params.add_int("limit", limit);
get_resource_required(&self.ctx, Some("head"), ¶ms).await
}
/// Adds a single request to the queue. If `forefront` is true, adds it to the front.
pub async fn add_request(
&self,
request: &RequestQueueRequest,
forefront: bool,
) -> ApifyClientResult<RequestQueueOperationInfo> {
let mut params = self.base_params();
params.add_bool("forefront", Some(forefront));
let body = serde_json::to_vec(request)?;
post_with_body(
&self.ctx,
Some("requests"),
¶ms,
Some(body),
"application/json",
)
.await
}
/// Gets a request by ID, or `None` if it does not exist.
pub async fn get_request(&self, id: &str) -> ApifyClientResult<Option<RequestQueueRequest>> {
get_resource(
&self.ctx,
Some(&format!("requests/{}", encode_path_segment(id))),
&self.base_params(),
)
.await
}
/// Updates a request (which must include its `id`).
pub async fn update_request(
&self,
request: &RequestQueueRequest,
forefront: bool,
) -> ApifyClientResult<RequestQueueOperationInfo> {
let id = request.id.clone().ok_or_else(|| {
crate::error::ApifyClientError::InvalidArgument(
"request.id is required to update a request".to_string(),
)
})?;
let mut params = self.base_params();
params.add_bool("forefront", Some(forefront));
let url = params.apply_to_url(
&self
.ctx
.url(Some(&format!("requests/{}", encode_path_segment(&id)))),
);
let body = serde_json::to_vec(request)?;
let mut headers = std::collections::HashMap::new();
headers.insert("Content-Type".to_string(), "application/json".to_string());
let response = self
.ctx
.http
.call(HttpRequest {
method: HttpMethod::Put,
url,
headers,
body: Some(body),
timeout: crate::clients::base::DEFAULT_REQUEST_TIMEOUT,
})
.await?;
crate::common::parse_data_envelope(&response.body)
}
/// Deletes a request by ID.
pub async fn delete_request(&self, id: &str) -> ApifyClientResult<()> {
let params = self.base_params();
let url = params.apply_to_url(
&self
.ctx
.url(Some(&format!("requests/{}", encode_path_segment(id)))),
);
self.ctx
.http
.call(HttpRequest {
method: HttpMethod::Delete,
url,
headers: Default::default(),
body: None,
timeout: crate::clients::base::DEFAULT_REQUEST_TIMEOUT,
})
.await?;
Ok(())
}
/// Lists and locks requests from the head of the queue for `lock_secs` seconds.
pub async fn list_and_lock_head(
&self,
lock_secs: i64,
limit: Option<i64>,
) -> ApifyClientResult<serde_json::Value> {
let mut params = self.base_params();
params
.add_int("lockSecs", Some(lock_secs))
.add_int("limit", limit);
post_action(&self.ctx, Some("head/lock"), ¶ms, None, None).await
}
/// Adds multiple requests to the queue, automatically splitting the input into chunks of
/// at most [`MAX_REQUESTS_PER_BATCH_OPERATION`] requests per API call (the API rejects
/// larger batches). The per-chunk responses are merged into a single result whose
/// `processedRequests` / `unprocessedRequests` arrays concatenate every chunk's, matching
/// the reference client's client-side chunking.
pub async fn batch_add_requests(
&self,
requests: &[RequestQueueRequest],
forefront: bool,
) -> ApifyClientResult<serde_json::Value> {
let mut processed: Vec<serde_json::Value> = Vec::new();
let mut unprocessed: Vec<serde_json::Value> = Vec::new();
for chunk in requests.chunks(MAX_REQUESTS_PER_BATCH_OPERATION) {
let chunk_result = self.batch_add_chunk(chunk, forefront).await?;
merge_request_array(&mut processed, &chunk_result, "processedRequests");
merge_request_array(&mut unprocessed, &chunk_result, "unprocessedRequests");
}
Ok(serde_json::json!({
"processedRequests": processed,
"unprocessedRequests": unprocessed,
}))
}
/// Posts a single chunk of requests (at most [`MAX_REQUESTS_PER_BATCH_OPERATION`]).
async fn batch_add_chunk(
&self,
requests: &[RequestQueueRequest],
forefront: bool,
) -> ApifyClientResult<serde_json::Value> {
let mut params = self.base_params();
params.add_bool("forefront", Some(forefront));
let body = serde_json::to_vec(requests)?;
post_with_body(
&self.ctx,
Some("requests/batch"),
¶ms,
Some(body),
"application/json",
)
.await
}
/// Deletes multiple requests in a single batch operation.
pub async fn batch_delete_requests<T: Serialize>(
&self,
requests: &[T],
) -> ApifyClientResult<serde_json::Value> {
delete_with_body(
&self.ctx,
Some("requests/batch"),
&self.base_params(),
&requests,
)
.await
}
/// Lists requests in the queue.
///
/// Supports pagination via `limit`/`exclusive_start_id` and the spec's `cursor`/`filter`
/// parameters (see [`ListRequestsOptions`]).
pub async fn list_requests(
&self,
options: ListRequestsOptions,
) -> ApifyClientResult<serde_json::Value> {
let mut params = self.base_params();
params
.add_int("limit", options.limit)
.add_str("exclusiveStartId", options.exclusive_start_id)
.add_str("cursor", options.cursor)
.add_csv("filter", options.filter.as_deref());
get_resource_required(&self.ctx, Some("requests"), ¶ms).await
}
/// Prolongs the lock on a request for another `lock_secs` seconds.
///
/// If `forefront` is `true`, the request moves to the front of the queue when its lock
/// later expires.
pub async fn prolong_request_lock(
&self,
id: &str,
lock_secs: i64,
forefront: bool,
) -> ApifyClientResult<serde_json::Value> {
let mut params = self.base_params();
params
.add_int("lockSecs", Some(lock_secs))
.add_bool("forefront", Some(forefront));
let url = params.apply_to_url(
&self
.ctx
.url(Some(&format!("requests/{}/lock", encode_path_segment(id)))),
);
let response = self
.ctx
.http
.call(HttpRequest {
method: HttpMethod::Put,
url,
headers: Default::default(),
body: None,
timeout: crate::clients::base::MEDIUM_REQUEST_TIMEOUT,
})
.await?;
crate::common::parse_data_envelope(&response.body)
}
/// Releases the lock on a request so other clients can process it.
///
/// If `forefront` is `true`, the request moves to the front of the queue.
pub async fn delete_request_lock(&self, id: &str, forefront: bool) -> ApifyClientResult<()> {
let mut params = self.base_params();
params.add_bool("forefront", Some(forefront));
let url = params.apply_to_url(
&self
.ctx
.url(Some(&format!("requests/{}/lock", encode_path_segment(id)))),
);
self.ctx
.http
.call(HttpRequest {
method: HttpMethod::Delete,
url,
headers: Default::default(),
body: None,
timeout: crate::clients::base::SMALL_REQUEST_TIMEOUT,
})
.await?;
Ok(())
}
/// Lazily paginates over all requests in the queue, fetching pages on demand.
///
/// Returns a [`RequestQueueRequestsIterator`]; call its `next()` to get one request at a
/// time. Pagination uses the API's opaque `nextCursor` token: the first page may be
/// anchored with `exclusiveStartId`, but every subsequent page is fetched with `cursor`
/// (matching the JS reference). `cursor` and `exclusiveStartId` are mutually exclusive.
pub fn paginate_requests(&self, page_limit: Option<i64>) -> RequestQueueRequestsIterator {
RequestQueueRequestsIterator {
client: self.clone(),
page_limit,
buffer: std::collections::VecDeque::new(),
next_cursor: None,
exhausted: false,
}
}
/// Unlocks all requests currently locked by this client (identified by `client_key`).
pub async fn unlock_requests(&self) -> ApifyClientResult<serde_json::Value> {
post_action(
&self.ctx,
Some("requests/unlock"),
&self.base_params(),
None,
None,
)
.await
}
}
/// A lazy, page-fetching iterator over the requests in a queue.
///
/// Created by [`RequestQueueClient::paginate_requests`]. Each call to [`next`](Self::next)
/// returns the next request, fetching another page from the API when the local buffer is
/// exhausted, until all requests have been yielded.
pub struct RequestQueueRequestsIterator {
client: RequestQueueClient,
page_limit: Option<i64>,
buffer: std::collections::VecDeque<RequestQueueRequest>,
/// Opaque pagination token returned by the previous page, fed back as `cursor`.
next_cursor: Option<String>,
exhausted: bool,
}
impl RequestQueueRequestsIterator {
/// Returns the next request, or `None` when all requests have been yielded.
pub async fn next(&mut self) -> ApifyClientResult<Option<RequestQueueRequest>> {
if let Some(item) = self.buffer.pop_front() {
return Ok(Some(item));
}
if self.exhausted {
return Ok(None);
}
// The first page may be anchored by exclusiveStartId; every later page is fetched
// with the opaque `cursor` token (mutually exclusive with exclusiveStartId), matching
// the JS reference. Here we only ever paginate from the queue head, so the first page
// uses neither and subsequent pages use `cursor`.
let page = self
.client
.list_requests(ListRequestsOptions {
limit: self.page_limit,
cursor: self.next_cursor.clone(),
..Default::default()
})
.await?;
// Parse the items and the next cursor from the (untyped) page.
let items: Vec<RequestQueueRequest> = page
.get("items")
.map(|v| serde_json::from_value(v.clone()))
.transpose()?
.unwrap_or_default();
if items.is_empty() {
self.exhausted = true;
return Ok(None);
}
// Advance the cursor; stop when the API stops returning one.
match page.get("nextCursor").and_then(|v| v.as_str()) {
Some(cursor) if !cursor.is_empty() => self.next_cursor = Some(cursor.to_string()),
_ => self.exhausted = true,
}
self.buffer.extend(items);
Ok(self.buffer.pop_front())
}
}