apify 4.0.0-beta.15 → 4.0.0-beta.150

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +28 -2
  2. package/dist/actor.d.ts +416 -281
  3. package/dist/actor.js +743 -417
  4. package/dist/apify_dataset_backend.d.ts +22 -0
  5. package/dist/apify_dataset_backend.js +77 -0
  6. package/dist/apify_file_system_storage_backend.d.ts +34 -0
  7. package/dist/apify_file_system_storage_backend.js +41 -0
  8. package/dist/apify_key_value_store_backend.d.ts +26 -0
  9. package/dist/apify_key_value_store_backend.js +57 -0
  10. package/dist/apify_request_queue_backend.d.ts +88 -0
  11. package/dist/apify_request_queue_backend.js +123 -0
  12. package/dist/apify_request_queue_shared_backend.d.ts +31 -0
  13. package/dist/apify_request_queue_shared_backend.js +201 -0
  14. package/dist/apify_request_queue_single_backend.d.ts +43 -0
  15. package/dist/apify_request_queue_single_backend.js +265 -0
  16. package/dist/apify_storage_backend.d.ts +95 -0
  17. package/dist/apify_storage_backend.js +219 -0
  18. package/dist/charging.d.ts +77 -47
  19. package/dist/charging.js +348 -226
  20. package/dist/charging_storage_backend.d.ts +53 -0
  21. package/dist/charging_storage_backend.js +109 -0
  22. package/dist/child_run_tracker.d.ts +110 -0
  23. package/dist/child_run_tracker.js +333 -0
  24. package/dist/configuration.d.ts +48 -28
  25. package/dist/configuration.js +66 -12
  26. package/dist/enqueue_links_filters.d.ts +29 -0
  27. package/dist/enqueue_links_filters.js +52 -0
  28. package/dist/errors.d.ts +31 -0
  29. package/dist/errors.js +22 -0
  30. package/dist/google_sheets.d.ts +12 -0
  31. package/dist/google_sheets.js +26 -0
  32. package/dist/index.d.ts +13 -4
  33. package/dist/index.js +8 -3
  34. package/dist/input-schemas.d.ts +1 -1
  35. package/dist/platform_event_manager.d.ts +24 -9
  36. package/dist/platform_event_manager.js +213 -43
  37. package/dist/proxy_configuration.d.ts +32 -21
  38. package/dist/proxy_configuration.js +137 -79
  39. package/dist/smart_apify_storage_backend.d.ts +52 -0
  40. package/dist/smart_apify_storage_backend.js +73 -0
  41. package/dist/storage.d.ts +6 -26
  42. package/dist/storage.js +1 -79
  43. package/dist/utils.d.ts +28 -3
  44. package/dist/utils.js +59 -17
  45. package/package.json +38 -44
  46. package/dist/apify_storage_client.d.ts +0 -54
  47. package/dist/apify_storage_client.js +0 -152
  48. package/dist/key_value_store.d.ts +0 -21
  49. package/dist/key_value_store.js +0 -41
@@ -0,0 +1,22 @@
1
+ import type { DatasetBackend, DatasetBackendListOptions, DatasetInfo, Dictionary, PaginatedList } from '@crawlee/types';
2
+ import type { DatasetClient, DatasetResource } from 'apify-client';
3
+ /** {@link DatasetInfo} extended with the fields the Apify platform reports. */
4
+ export interface ApifyDatasetInfo extends DatasetInfo, Omit<DatasetResource, keyof DatasetInfo> {
5
+ }
6
+ /**
7
+ * Implements crawlee v4's {@link DatasetBackend} interface on top of `apify-client`'s
8
+ * dataset API. Mostly a thin method-mapping wrapper (`getMetadata`/`get`, `drop`/`delete`,
9
+ * `getData`/`listItems`), except `pushData`, which also splits large pushes into chunks
10
+ * fitting the API's payload size limit.
11
+ *
12
+ * @internal
13
+ */
14
+ export declare class ApifyDatasetBackend implements DatasetBackend {
15
+ #private;
16
+ constructor(client: DatasetClient);
17
+ getMetadata(): Promise<ApifyDatasetInfo>;
18
+ drop(): Promise<void>;
19
+ purge(): Promise<void>;
20
+ pushData(items: Dictionary[]): Promise<void>;
21
+ getData(options?: DatasetBackendListOptions): Promise<PaginatedList<Dictionary>>;
22
+ }
@@ -0,0 +1,77 @@
1
+ import { MAX_PAYLOAD_SIZE_BYTES } from '@apify/consts';
2
+ /** Slight reduction of the API's 9MB payload limit, to stay safely below it. */
3
+ const SAFETY_BUFFER_PERCENT = 0.01 / 100; // 0.01%
4
+ const EFFECTIVE_LIMIT_BYTES = MAX_PAYLOAD_SIZE_BYTES - Math.ceil(MAX_PAYLOAD_SIZE_BYTES * SAFETY_BUFFER_PERCENT);
5
+ /** Per-item ceiling — 2 bytes under the chunk limit, so even a lone item fits its `[]` wrapper. */
6
+ const MAX_ITEM_BYTES = EFFECTIVE_LIMIT_BYTES - 2;
7
+ /**
8
+ * Implements crawlee v4's {@link DatasetBackend} interface on top of `apify-client`'s
9
+ * dataset API. Mostly a thin method-mapping wrapper (`getMetadata`/`get`, `drop`/`delete`,
10
+ * `getData`/`listItems`), except `pushData`, which also splits large pushes into chunks
11
+ * fitting the API's payload size limit.
12
+ *
13
+ * @internal
14
+ */
15
+ export class ApifyDatasetBackend {
16
+ #client;
17
+ constructor(client) {
18
+ this.#client = client;
19
+ }
20
+ async getMetadata() {
21
+ const metadata = await this.#client.get();
22
+ if (!metadata) {
23
+ throw new Error('Dataset not found or has been deleted.');
24
+ }
25
+ return { ...metadata, name: metadata.name ?? undefined };
26
+ }
27
+ async drop() {
28
+ await this.#client.delete();
29
+ }
30
+ async purge() {
31
+ throw new Error('Purging a dataset is not supported on the Apify platform. ' +
32
+ 'Use `drop()` to delete the dataset entirely, or open a new dataset instead.');
33
+ }
34
+ async pushData(items) {
35
+ // The platform API rejects payloads over 9MB — split the items into chunks
36
+ // that fit, pushed sequentially to preserve item order.
37
+ const payloads = items.map((item, index) => serializeToSizeLimit(item, index));
38
+ for (const chunk of chunkBySize(payloads, EFFECTIVE_LIMIT_BYTES)) {
39
+ await this.#client.pushItems(chunk);
40
+ }
41
+ }
42
+ async getData(options) {
43
+ return await this.#client.listItems(options);
44
+ }
45
+ }
46
+ /** Serializes a dataset item, throwing if it alone exceeds the payload size limit. */
47
+ function serializeToSizeLimit(item, index) {
48
+ const payload = JSON.stringify(item);
49
+ const bytes = Buffer.byteLength(payload);
50
+ if (bytes > MAX_ITEM_BYTES) {
51
+ throw new Error(`Data item at index ${index} is too large (size: ${bytes} bytes, limit: ${MAX_ITEM_BYTES} bytes)`);
52
+ }
53
+ return payload;
54
+ }
55
+ /**
56
+ * Takes an array of JSON-serialized items and groups them into JSON array strings
57
+ * of at most `limitBytes` each, preserving item order. Assumes (and does not
58
+ * validate) that no single item exceeds the limit.
59
+ */
60
+ function chunkBySize(payloads, limitBytes) {
61
+ const chunks = [];
62
+ let chunkBytes = Infinity; // Forces the first item to open a new chunk.
63
+ for (const payload of payloads) {
64
+ const bytes = Buffer.byteLength(payload);
65
+ if (chunkBytes + bytes + 1 <= limitBytes) {
66
+ // Fits into the current chunk — add 1 byte for the ',' separator.
67
+ chunks[chunks.length - 1].push(payload);
68
+ chunkBytes += bytes + 1;
69
+ }
70
+ else {
71
+ // Open a new chunk — add 2 bytes for the '[]' wrapper.
72
+ chunks.push([payload]);
73
+ chunkBytes = bytes + 2;
74
+ }
75
+ }
76
+ return chunks.map((chunk) => `[${chunk.join(',')}]`);
77
+ }
@@ -0,0 +1,34 @@
1
+ import type { AdoptionCandidate, FileSystemStorageOptions, KeyValueStoreHookOptions, PurgeableKeyValueStoreBackend } from '@crawlee/fs-storage';
2
+ import { FileSystemStorageBackend } from '@crawlee/fs-storage';
3
+ export interface ApifyFileSystemStorageOptions extends FileSystemStorageOptions {
4
+ /**
5
+ * The key the Actor input is read from — `Configuration.inputKey` (`ACTOR_INPUT_KEY`).
6
+ *
7
+ * `INPUT` is treated as an input key regardless of this setting, so a project's `INPUT.json` stays
8
+ * intact when the Apify CLI redirects the run to a temporary key.
9
+ *
10
+ * @default 'INPUT'
11
+ */
12
+ inputKey?: string;
13
+ }
14
+ /**
15
+ * Crawlee's file-system storage backend, aware of the Actor input.
16
+ *
17
+ * Locally the input arrives in the default key-value store as a bare `INPUT` or `INPUT.json` file with
18
+ * no metadata sidecar — written by the Apify CLI, a project template, or by hand. This backend adopts
19
+ * such a file as the record under the input key when the store is opened (both files present fails the
20
+ * open), and keeps the input keys when the default store is purged on start. Everything else is
21
+ * inherited from {@link FileSystemStorageBackend}.
22
+ *
23
+ * `Actor` installs it as the local backend; pass an instance to `Actor.init({ storage })` only if you
24
+ * need to construct it yourself.
25
+ */
26
+ export declare class ApifyFileSystemStorageBackend extends FileSystemStorageBackend {
27
+ /** `INPUT` plus the configured input key, deduplicated. */
28
+ private readonly inputKeys;
29
+ constructor(options: ApifyFileSystemStorageOptions);
30
+ /** Claims a bare `<key>` or `<key>.json` in the default store for each input key, ahead of the generic sweep. */
31
+ protected keyValueStoreAdoptionCandidates(options: KeyValueStoreHookOptions): AdoptionCandidate[];
32
+ /** Spares the input keys in the default store; every other run-scoped store is emptied. */
33
+ protected purgeKeyValueStore(store: PurgeableKeyValueStoreBackend, options: KeyValueStoreHookOptions): Promise<void>;
34
+ }
@@ -0,0 +1,41 @@
1
+ import { FileSystemStorageBackend } from '@crawlee/fs-storage';
2
+ import { KEY_VALUE_STORE_KEYS } from '@apify/consts';
3
+ import { BINARY_CONTENT_TYPE, JSON_CONTENT_TYPE } from './utils.js';
4
+ /**
5
+ * Crawlee's file-system storage backend, aware of the Actor input.
6
+ *
7
+ * Locally the input arrives in the default key-value store as a bare `INPUT` or `INPUT.json` file with
8
+ * no metadata sidecar — written by the Apify CLI, a project template, or by hand. This backend adopts
9
+ * such a file as the record under the input key when the store is opened (both files present fails the
10
+ * open), and keeps the input keys when the default store is purged on start. Everything else is
11
+ * inherited from {@link FileSystemStorageBackend}.
12
+ *
13
+ * `Actor` installs it as the local backend; pass an instance to `Actor.init({ storage })` only if you
14
+ * need to construct it yourself.
15
+ */
16
+ export class ApifyFileSystemStorageBackend extends FileSystemStorageBackend {
17
+ /** `INPUT` plus the configured input key, deduplicated. */
18
+ inputKeys;
19
+ constructor(options) {
20
+ const { inputKey = KEY_VALUE_STORE_KEYS.INPUT, ...fileSystemOptions } = options;
21
+ super(fileSystemOptions);
22
+ this.inputKeys = [...new Set([KEY_VALUE_STORE_KEYS.INPUT, inputKey])];
23
+ }
24
+ /** Claims a bare `<key>` or `<key>.json` in the default store for each input key, ahead of the generic sweep. */
25
+ keyValueStoreAdoptionCandidates(options) {
26
+ const inputCandidates = options.isDefaultStore
27
+ ? this.inputKeys.map((key) => ({
28
+ key,
29
+ files: [
30
+ { filename: key, contentType: BINARY_CONTENT_TYPE },
31
+ { filename: `${key}.json`, contentType: JSON_CONTENT_TYPE },
32
+ ],
33
+ }))
34
+ : [];
35
+ return [...inputCandidates, ...super.keyValueStoreAdoptionCandidates(options)];
36
+ }
37
+ /** Spares the input keys in the default store; every other run-scoped store is emptied. */
38
+ async purgeKeyValueStore(store, options) {
39
+ await (options.isDefaultStore ? store.purgeExcept([...this.inputKeys]) : store.purge());
40
+ }
41
+ }
@@ -0,0 +1,26 @@
1
+ import type { KeyValueStoreBackend, KeyValueStoreInfo, KeyValueStoreInputRecord, KeyValueStoreListKeysOptions, KeyValueStoreListKeysResult, KeyValueStoreRecord } from '@crawlee/types';
2
+ import type { KeyValueStoreClient, KeyValueStoreResource } from 'apify-client';
3
+ /** {@link KeyValueStoreInfo} extended with the fields the Apify platform reports. */
4
+ export interface ApifyKeyValueStoreInfo extends KeyValueStoreInfo, Omit<KeyValueStoreResource, keyof KeyValueStoreInfo> {
5
+ }
6
+ /**
7
+ * Implements crawlee v4's {@link KeyValueStoreBackend} interface on top of `apify-client`'s
8
+ * key-value store API. Mostly a method-mapping wrapper (`getValue`/`getRecord`,
9
+ * `setValue`/`setRecord`, `drop`/`delete`, ...); the one semantic difference is that storage
10
+ * backends are byte transports, so records are read unparsed (see {@link getValue}).
11
+ *
12
+ * @internal
13
+ */
14
+ export declare class ApifyKeyValueStoreBackend implements KeyValueStoreBackend {
15
+ #private;
16
+ constructor(client: KeyValueStoreClient);
17
+ getMetadata(): Promise<ApifyKeyValueStoreInfo>;
18
+ drop(): Promise<void>;
19
+ purge(): Promise<void>;
20
+ getValue(key: string): Promise<KeyValueStoreRecord | undefined>;
21
+ setValue(record: KeyValueStoreInputRecord): Promise<void>;
22
+ deleteValue(key: string): Promise<void>;
23
+ listKeys(options?: KeyValueStoreListKeysOptions): Promise<KeyValueStoreListKeysResult>;
24
+ getPublicUrl(key: string): Promise<string | undefined>;
25
+ recordExists(key: string): Promise<boolean>;
26
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Implements crawlee v4's {@link KeyValueStoreBackend} interface on top of `apify-client`'s
3
+ * key-value store API. Mostly a method-mapping wrapper (`getValue`/`getRecord`,
4
+ * `setValue`/`setRecord`, `drop`/`delete`, ...); the one semantic difference is that storage
5
+ * backends are byte transports, so records are read unparsed (see {@link getValue}).
6
+ *
7
+ * @internal
8
+ */
9
+ export class ApifyKeyValueStoreBackend {
10
+ #client;
11
+ constructor(client) {
12
+ this.#client = client;
13
+ }
14
+ async getMetadata() {
15
+ const metadata = await this.#client.get();
16
+ if (!metadata) {
17
+ throw new Error('Key-value store not found or has been deleted.');
18
+ }
19
+ return { ...metadata, name: metadata.name ?? undefined };
20
+ }
21
+ async drop() {
22
+ await this.#client.delete();
23
+ }
24
+ async purge() {
25
+ throw new Error('Purging a key-value store is not supported on the Apify platform. ' +
26
+ 'Use `drop()` to delete the store entirely, or open a new store instead.');
27
+ }
28
+ async getValue(key) {
29
+ // Storage backends are byte transports — the KeyValueStore frontend parses values
30
+ // according to their content type, so the record must be returned unparsed.
31
+ // The client may type the bytes as a `Uint8Array`; in Node.js they are always a `Buffer`.
32
+ return this.#client.getRecord(key, { buffer: true });
33
+ }
34
+ async setValue(record) {
35
+ await this.#client.setRecord(record);
36
+ }
37
+ async deleteValue(key) {
38
+ await this.#client.deleteRecord(key);
39
+ }
40
+ async listKeys(options) {
41
+ const result = await this.#client.listKeys(options);
42
+ // The API does not report a content type for listed keys; crawlee's item shape
43
+ // requires the field, so it is left undefined via the cast.
44
+ return {
45
+ ...result,
46
+ exclusiveStartKey: result.exclusiveStartKey ?? undefined,
47
+ nextExclusiveStartKey: result.nextExclusiveStartKey ?? undefined,
48
+ items: result.items.map(({ key, size }) => ({ key, size })),
49
+ };
50
+ }
51
+ async getPublicUrl(key) {
52
+ return this.#client.getRecordPublicUrl(key);
53
+ }
54
+ async recordExists(key) {
55
+ return this.#client.recordExists(key);
56
+ }
57
+ }
@@ -0,0 +1,88 @@
1
+ import type { AbortableOptions, BatchAddRequestsResult, QueueOperationInfo, RequestQueueBackend, RequestQueueInfo, RequestQueueOperationOptions, RequestSchema, UpdateRequestSchema } from '@crawlee/types';
2
+ import type { RequestQueueClient as ApifyRequestQueueApiClient, RequestQueueResource } from 'apify-client';
3
+ /**
4
+ * Determines how an Apify platform request queue is consumed.
5
+ *
6
+ * - `'single'` — optimized for a single consumer. The client keeps a local estimate of the queue
7
+ * head and never locks requests, which means fewer API calls, better performance and lower cost.
8
+ * Multiple producers may still add requests concurrently, but only one client may *consume*
9
+ * (fetch and process) them.
10
+ * - `'shared'` — safe for multiple concurrent consumers (e.g. several Actor runs processing one
11
+ * queue). Requests are locked server-side while they are being processed, at the cost of more
12
+ * API calls.
13
+ */
14
+ export type RequestQueueAccessMode = 'single' | 'shared';
15
+ /**
16
+ * Derives a request id from its unique key, exactly as the Apify platform does
17
+ * (`sha256(uniqueKey)` → base64 → strip `+`/`/`/`=` → first 15 chars). Lets us
18
+ * address a request by unique key without an extra round-trip.
19
+ */
20
+ export declare function uniqueKeyToRequestId(uniqueKey: string): string;
21
+ /** {@link RequestQueueInfo} extended with the fields the Apify platform reports. */
22
+ export interface ApifyRequestQueueInfo extends RequestQueueInfo, Omit<RequestQueueResource, keyof RequestQueueInfo> {
23
+ }
24
+ /**
25
+ * Common base of the Apify platform implementations of Crawlee v4's stateful, pull-based
26
+ * {@link RequestQueueBackend} interface, built on top of `apify-client`'s REST request-queue API.
27
+ *
28
+ * The mode-specific consumption logic lives in the subclasses:
29
+ * {@link ApifyRequestQueueSingleBackend} (single consumer, no locking) and
30
+ * {@link ApifyRequestQueueSharedBackend} (multiple consumers, server-side locking).
31
+ * Modeled on the Apify Python SDK's request-queue clients.
32
+ *
33
+ * @internal
34
+ */
35
+ export declare abstract class ApifyRequestQueueBackend implements RequestQueueBackend {
36
+ protected readonly client: ApifyRequestQueueApiClient;
37
+ /**
38
+ * Local estimates of the queue counters, updated as this client adds/handles requests. The API
39
+ * counters can lag behind by a few seconds, so {@link getMetadata} reports whichever is higher.
40
+ */
41
+ protected estimatedTotalRequestCount: number;
42
+ protected estimatedHandledRequestCount: number;
43
+ constructor(client: ApifyRequestQueueApiClient);
44
+ abstract addBatchOfRequests(requests: RequestSchema[], options?: RequestQueueOperationOptions): Promise<BatchAddRequestsResult>;
45
+ abstract getRequest(uniqueKey: string): Promise<UpdateRequestSchema | undefined>;
46
+ abstract fetchNextRequest(options?: AbortableOptions): Promise<UpdateRequestSchema | undefined>;
47
+ abstract markRequestAsHandled(request: UpdateRequestSchema, options?: AbortableOptions): Promise<QueueOperationInfo | undefined>;
48
+ abstract reclaimRequest(request: UpdateRequestSchema, options?: RequestQueueOperationOptions): Promise<QueueOperationInfo | undefined>;
49
+ abstract isEmpty(): Promise<boolean>;
50
+ abstract isFinished(): Promise<boolean>;
51
+ setExpectedRequestProcessingTime(_processingTimeSecs: number): Promise<void>;
52
+ getMetadata(): Promise<ApifyRequestQueueInfo>;
53
+ drop(): Promise<void>;
54
+ purge(): Promise<void>;
55
+ protected requestIdFromUniqueKey(uniqueKey: string): string;
56
+ /**
57
+ * Fetches the full request record by id.
58
+ *
59
+ * The apify-client return type understates the payload (the API returns the complete request
60
+ * record including `userData`, `payload`, `handledAt`, ...), hence the cast.
61
+ */
62
+ protected getRequestById(id: string, signal?: AbortSignal): Promise<UpdateRequestSchema | undefined>;
63
+ /**
64
+ * Adds new requests to the platform queue. The API assigns ids itself, so any incoming id is
65
+ * stripped to pass its strict input validation. `apify-client` internally chunks the batch and
66
+ * retries transient failures.
67
+ */
68
+ protected sendBatch(requests: RequestSchema[], forefront?: boolean, signal?: AbortSignal): Promise<BatchAddRequestsResult>;
69
+ /** Updates a request record on the platform and maps the result to crawlee's shape. */
70
+ protected updateRequestOnPlatform(request: UpdateRequestSchema, forefront?: boolean, signal?: AbortSignal): Promise<QueueOperationInfo>;
71
+ /**
72
+ * Counts freshly added requests from an add-batch result into the local metadata estimates, then
73
+ * throws if the platform did not take them all.
74
+ *
75
+ * What `apify-client` reports as unprocessed is never safe to skip: requests still rate-limited
76
+ * after its retries, or a batch whose API call failed (it logs that error instead of throwing).
77
+ * Called last, so the requests that were added are on record and a retry only re-sends the rest.
78
+ */
79
+ protected finishBatchAdd(result: BatchAddRequestsResult): void;
80
+ }
81
+ /**
82
+ * A minimal FIFO mutex — serializes the async critical sections passed to {@link runExclusive}.
83
+ * @internal
84
+ */
85
+ export declare class AsyncLock {
86
+ #private;
87
+ runExclusive<T>(fn: () => Promise<T>): Promise<T>;
88
+ }
@@ -0,0 +1,123 @@
1
+ import { createHash } from 'node:crypto';
2
+ /** Apify request IDs are the first 15 chars of a base64 SHA-256 of the unique key. */
3
+ const REQUEST_ID_LENGTH = 15;
4
+ /**
5
+ * Derives a request id from its unique key, exactly as the Apify platform does
6
+ * (`sha256(uniqueKey)` → base64 → strip `+`/`/`/`=` → first 15 chars). Lets us
7
+ * address a request by unique key without an extra round-trip.
8
+ */
9
+ export function uniqueKeyToRequestId(uniqueKey) {
10
+ const hash = createHash('sha256').update(uniqueKey).digest('base64').replace(/[+/=]/g, '');
11
+ return hash.slice(0, REQUEST_ID_LENGTH);
12
+ }
13
+ /**
14
+ * Common base of the Apify platform implementations of Crawlee v4's stateful, pull-based
15
+ * {@link RequestQueueBackend} interface, built on top of `apify-client`'s REST request-queue API.
16
+ *
17
+ * The mode-specific consumption logic lives in the subclasses:
18
+ * {@link ApifyRequestQueueSingleBackend} (single consumer, no locking) and
19
+ * {@link ApifyRequestQueueSharedBackend} (multiple consumers, server-side locking).
20
+ * Modeled on the Apify Python SDK's request-queue clients.
21
+ *
22
+ * @internal
23
+ */
24
+ export class ApifyRequestQueueBackend {
25
+ client;
26
+ /**
27
+ * Local estimates of the queue counters, updated as this client adds/handles requests. The API
28
+ * counters can lag behind by a few seconds, so {@link getMetadata} reports whichever is higher.
29
+ */
30
+ estimatedTotalRequestCount = 0;
31
+ estimatedHandledRequestCount = 0;
32
+ constructor(client) {
33
+ this.client = client;
34
+ }
35
+ async setExpectedRequestProcessingTime(_processingTimeSecs) {
36
+ // Only relevant for backends that reserve requests via locking; see the shared backend.
37
+ }
38
+ async getMetadata() {
39
+ const metadata = await this.client.get();
40
+ if (!metadata) {
41
+ throw new Error('Request queue not found or has been deleted.');
42
+ }
43
+ return {
44
+ ...metadata,
45
+ name: metadata.name ?? undefined,
46
+ totalRequestCount: Math.max(metadata.totalRequestCount, this.estimatedTotalRequestCount),
47
+ handledRequestCount: Math.max(metadata.handledRequestCount, this.estimatedHandledRequestCount),
48
+ };
49
+ }
50
+ async drop() {
51
+ await this.client.delete();
52
+ }
53
+ async purge() {
54
+ throw new Error('Purging a request queue is not supported on the Apify platform. ' +
55
+ 'Use `drop()` to delete the queue entirely, or open a new queue instead.');
56
+ }
57
+ requestIdFromUniqueKey(uniqueKey) {
58
+ return uniqueKeyToRequestId(uniqueKey);
59
+ }
60
+ /**
61
+ * Fetches the full request record by id.
62
+ *
63
+ * The apify-client return type understates the payload (the API returns the complete request
64
+ * record including `userData`, `payload`, `handledAt`, ...), hence the cast.
65
+ */
66
+ async getRequestById(id, signal) {
67
+ const request = await this.client.getRequest(id, { signal });
68
+ return request ?? undefined;
69
+ }
70
+ /**
71
+ * Adds new requests to the platform queue. The API assigns ids itself, so any incoming id is
72
+ * stripped to pass its strict input validation. `apify-client` internally chunks the batch and
73
+ * retries transient failures.
74
+ */
75
+ async sendBatch(requests, forefront, signal) {
76
+ const apiRequests = requests.map((request) => {
77
+ const { id: _id, ...rest } = request;
78
+ return rest;
79
+ });
80
+ const result = await this.client.batchAddRequests(apiRequests, { forefront, signal });
81
+ return result;
82
+ }
83
+ /** Updates a request record on the platform and maps the result to crawlee's shape. */
84
+ async updateRequestOnPlatform(request, forefront, signal) {
85
+ const result = await this.client.updateRequest(request, { forefront, signal });
86
+ return {
87
+ requestId: result.requestId,
88
+ wasAlreadyPresent: result.wasAlreadyPresent,
89
+ wasAlreadyHandled: result.wasAlreadyHandled,
90
+ };
91
+ }
92
+ /**
93
+ * Counts freshly added requests from an add-batch result into the local metadata estimates, then
94
+ * throws if the platform did not take them all.
95
+ *
96
+ * What `apify-client` reports as unprocessed is never safe to skip: requests still rate-limited
97
+ * after its retries, or a batch whose API call failed (it logs that error instead of throwing).
98
+ * Called last, so the requests that were added are on record and a retry only re-sends the rest.
99
+ */
100
+ finishBatchAdd(result) {
101
+ const newRequestCount = result.processedRequests.filter((request) => !request.wasAlreadyPresent && !request.wasAlreadyHandled).length;
102
+ this.estimatedTotalRequestCount += newRequestCount;
103
+ const { unprocessedRequests } = result;
104
+ if (unprocessedRequests.length > 0) {
105
+ const sample = unprocessedRequests.slice(0, 3).map((request) => request.url);
106
+ throw new Error(`Failed to add ${unprocessedRequests.length} request(s) to the request queue, e.g. ${sample.join(', ')}. ` +
107
+ 'See the preceding ApifyClient log for the cause.');
108
+ }
109
+ }
110
+ }
111
+ /**
112
+ * A minimal FIFO mutex — serializes the async critical sections passed to {@link runExclusive}.
113
+ * @internal
114
+ */
115
+ export class AsyncLock {
116
+ #tail = Promise.resolve();
117
+ async runExclusive(fn) {
118
+ const run = this.#tail.then(fn);
119
+ // Keep the chain alive even when the critical section throws.
120
+ this.#tail = run.catch(() => { });
121
+ return run;
122
+ }
123
+ }
@@ -0,0 +1,31 @@
1
+ import type { AbortableOptions, BatchAddRequestsResult, QueueOperationInfo, RequestQueueOperationOptions, RequestSchema, UpdateRequestSchema } from '@crawlee/types';
2
+ import { ApifyRequestQueueBackend } from './apify_request_queue_backend.js';
3
+ /**
4
+ * Request queue backend safe for multi-consumer scenarios on the Apify platform.
5
+ *
6
+ * Requests fetched via {@link fetchNextRequest} are locked server-side (`listAndLockHead`), so any
7
+ * number of clients — including other Actor runs — can process the same queue concurrently without
8
+ * handing out a request twice. The lock is held until the request is marked as handled or
9
+ * reclaimed, and its duration follows the consumer's expected processing time
10
+ * (see {@link setExpectedRequestProcessingTime}). This consistency costs roughly one extra API
11
+ * call per processed request compared to the single-consumer backend.
12
+ *
13
+ * @internal
14
+ */
15
+ export declare class ApifyRequestQueueSharedBackend extends ApifyRequestQueueBackend {
16
+ #private;
17
+ setExpectedRequestProcessingTime(processingTimeSecs: number): Promise<void>;
18
+ addBatchOfRequests(requests: RequestSchema[], options?: RequestQueueOperationOptions): Promise<BatchAddRequestsResult>;
19
+ getRequest(uniqueKey: string): Promise<UpdateRequestSchema | undefined>;
20
+ fetchNextRequest({ signal }?: AbortableOptions): Promise<UpdateRequestSchema | undefined>;
21
+ markRequestAsHandled(request: UpdateRequestSchema, { signal }?: AbortableOptions): Promise<QueueOperationInfo | undefined>;
22
+ reclaimRequest(request: UpdateRequestSchema, options?: RequestQueueOperationOptions): Promise<QueueOperationInfo | undefined>;
23
+ isEmpty(): Promise<boolean>;
24
+ isFinished(): Promise<boolean>;
25
+ /** Must be called with the head lock held. */
26
+ private ensureHeadIsNonEmpty;
27
+ /** Must be called with the head lock held. */
28
+ private listAndLockHead;
29
+ private isKnownOrExists;
30
+ private cacheRequestInfo;
31
+ }