@crawlee/core 4.0.0-beta.99 → 4.0.0-rc.0
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.
- package/autoscaling/autoscaled_pool.d.ts +3 -21
- package/autoscaling/autoscaled_pool.js +105 -97
- package/autoscaling/concurrency_system.d.ts +7 -22
- package/autoscaling/concurrency_system.js +112 -100
- package/autoscaling/cpu_load_signal.d.ts +1 -2
- package/autoscaling/cpu_load_signal.js +11 -10
- package/autoscaling/event_loop_load_signal.d.ts +1 -4
- package/autoscaling/event_loop_load_signal.js +18 -18
- package/autoscaling/index.d.ts +1 -1
- package/autoscaling/index.js +1 -1
- package/autoscaling/load_signal.d.ts +8 -7
- package/autoscaling/load_signal.js +14 -12
- package/autoscaling/memory_load_signal.d.ts +3 -12
- package/autoscaling/memory_load_signal.js +41 -41
- package/autoscaling/snapshotter.d.ts +7 -10
- package/autoscaling/snapshotter.js +18 -18
- package/autoscaling/{client_load_signal.d.ts → storage_backend_load_signal.d.ts} +14 -17
- package/autoscaling/{client_load_signal.js → storage_backend_load_signal.js} +27 -27
- package/autoscaling/system_status.d.ts +9 -11
- package/autoscaling/system_status.js +13 -13
- package/configuration.d.ts +16 -16
- package/configuration.js +6 -6
- package/crawlers/context_pipeline.js +6 -6
- package/crawlers/crawler_commons.d.ts +14 -112
- package/crawlers/crawler_commons.js +1 -107
- package/crawlers/error_snapshotter.d.ts +2 -4
- package/crawlers/error_snapshotter.js +5 -5
- package/crawlers/index.d.ts +1 -1
- package/crawlers/index.js +0 -1
- package/crawlers/statistics.d.ts +164 -45
- package/crawlers/statistics.js +339 -153
- package/debug.js +4 -4
- package/enqueue_links/enqueue_links.d.ts +51 -159
- package/enqueue_links/enqueue_links.js +38 -231
- package/enqueue_links/shared.d.ts +34 -24
- package/enqueue_links/shared.js +54 -36
- package/errors.d.ts +43 -12
- package/errors.js +48 -9
- package/events/event_manager.d.ts +2 -2
- package/events/event_manager.js +7 -6
- package/events/local_event_manager.d.ts +1 -1
- package/events/local_event_manager.js +5 -5
- package/http.d.ts +9 -0
- package/http.js +28 -0
- package/index.d.ts +1 -1
- package/index.js +1 -1
- package/log.js +5 -1
- package/memory-storage/memory-storage.d.ts +3 -11
- package/memory-storage/memory-storage.js +42 -48
- package/memory-storage/resource-clients/dataset.d.ts +1 -1
- package/memory-storage/resource-clients/dataset.js +8 -13
- package/memory-storage/resource-clients/key-value-store.d.ts +1 -1
- package/memory-storage/resource-clients/key-value-store.js +36 -38
- package/memory-storage/resource-clients/request-queue.d.ts +4 -23
- package/memory-storage/resource-clients/request-queue.js +68 -80
- package/owned_or_injected.d.ts +1 -3
- package/owned_or_injected.js +17 -17
- package/package.json +8 -9
- package/proxy_configuration.d.ts +1 -3
- package/proxy_configuration.js +18 -14
- package/recoverable_state.d.ts +80 -45
- package/recoverable_state.js +163 -75
- package/request.d.ts +3 -4
- package/request.js +57 -44
- package/router.d.ts +6 -9
- package/router.js +23 -23
- package/serialization.js +14 -13
- package/service_locator.d.ts +19 -10
- package/service_locator.js +57 -48
- package/session_pool/session.d.ts +3 -14
- package/session_pool/session.js +76 -74
- package/session_pool/session_pool.d.ts +6 -12
- package/session_pool/session_pool.js +85 -77
- package/storages/batched_adds.d.ts +37 -0
- package/storages/batched_adds.js +73 -0
- package/storages/dataset.d.ts +12 -1
- package/storages/dataset.js +133 -32
- package/storages/index.d.ts +2 -1
- package/storages/index.js +2 -1
- package/storages/key_value_store.d.ts +19 -4
- package/storages/key_value_store.js +204 -75
- package/storages/request_dedup_cache.d.ts +1 -2
- package/storages/request_dedup_cache.js +9 -9
- package/storages/request_list.d.ts +4 -23
- package/storages/request_list.js +103 -96
- package/storages/request_loader.d.ts +5 -0
- package/storages/request_manager_tandem.d.ts +1 -10
- package/storages/request_manager_tandem.js +27 -27
- package/storages/request_queue.d.ts +21 -18
- package/storages/request_queue.js +318 -177
- package/storages/sitemap_request_loader.d.ts +22 -70
- package/storages/sitemap_request_loader.js +122 -116
- package/storages/storage_instance_manager.d.ts +1 -2
- package/storages/storage_instance_manager.js +17 -17
- package/storages/storage_stats.d.ts +1 -1
- package/storages/storage_stats.js +4 -4
- package/storages/throttling_request_manager.d.ts +239 -0
- package/storages/throttling_request_manager.js +646 -0
- package/storages/transaction.d.ts +252 -0
- package/storages/transaction.js +251 -0
- package/storages/utils.d.ts +6 -3
- package/storages/utils.js +11 -2
- package/system-info/runtime.js +7 -7
- package/url.d.ts +9 -0
- package/url.js +11 -0
- package/validators.d.ts +22 -25
- package/validators.js +13 -25
- package/storages/access_checking.d.ts +0 -12
- package/storages/access_checking.js +0 -17
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import type { Awaitable, Dictionary } from '@crawlee/types';
|
|
2
|
+
import type { RecordOptions } from './key_value_store.js';
|
|
3
|
+
/**
|
|
4
|
+
* Governs whether writes of a given storage type performed inside a {@link StorageTransaction} are
|
|
5
|
+
* applied immediately (`writeThrough`) or recorded and replayed on commit (`deferred`).
|
|
6
|
+
*/
|
|
7
|
+
export type StorageWriteMode = 'deferred' | 'writeThrough';
|
|
8
|
+
/**
|
|
9
|
+
* Per-storage-type write policy of a {@link StorageTransaction}. Datasets and key-value stores are
|
|
10
|
+
* always `deferred` and not configurable — deferring is the only safe mode for non-idempotent writes,
|
|
11
|
+
* and {@link withDirectStorageAccess} covers one-off immediate writes.
|
|
12
|
+
*/
|
|
13
|
+
export interface StorageWritePolicy {
|
|
14
|
+
/**
|
|
15
|
+
* Write mode for request queue additions. Note that this is a *write policy* for the queue, not the
|
|
16
|
+
* queue instance itself (which is the top-level `requestQueue` crawler option).
|
|
17
|
+
*
|
|
18
|
+
* - `writeThrough` (default): requests are added immediately and are **not** rolled back with the
|
|
19
|
+
* transaction. This is safe (additions are deduplicated by `uniqueKey`, so a retry is idempotent)
|
|
20
|
+
* and keeps new requests visible to the crawler while the handler still runs.
|
|
21
|
+
* - `deferred`: requests are only added when the transaction commits — strict all-or-nothing
|
|
22
|
+
* semantics, at the cost of the crawler not seeing them until the handler finishes.
|
|
23
|
+
*/
|
|
24
|
+
requestQueue: StorageWriteMode;
|
|
25
|
+
}
|
|
26
|
+
export type StorageTransactionState = 'open' | 'committing' | 'committed' | 'failed' | 'rolledBack';
|
|
27
|
+
/**
|
|
28
|
+
* A storage frontend that can record operations in a transaction journal.
|
|
29
|
+
* @internal
|
|
30
|
+
*/
|
|
31
|
+
export interface TransactionParticipant {
|
|
32
|
+
/**
|
|
33
|
+
* Replay the given buffered journal entries (all recorded by this participant) into the real storage
|
|
34
|
+
* backend. Called during commit, with the transaction already in the `committing` state, so the
|
|
35
|
+
* replayed operations pass through.
|
|
36
|
+
*/
|
|
37
|
+
commitJournalEntries(entries: JournalEntry[]): Promise<void>;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* A single dataset write (`pushData`) recorded in a transaction journal.
|
|
41
|
+
*/
|
|
42
|
+
export interface DatasetJournalEntry {
|
|
43
|
+
type: 'dataset';
|
|
44
|
+
/** @internal **/
|
|
45
|
+
participant: TransactionParticipant;
|
|
46
|
+
storageId: string;
|
|
47
|
+
/** The pushed items, captured by `structuredClone` at write time. */
|
|
48
|
+
items: Dictionary[];
|
|
49
|
+
recordedAt: Date;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* A single key-value store write (`setValue`) recorded in a transaction journal.
|
|
53
|
+
*/
|
|
54
|
+
export interface KeyValueStoreJournalEntry {
|
|
55
|
+
type: 'keyValueStore';
|
|
56
|
+
/** @internal **/
|
|
57
|
+
participant: TransactionParticipant;
|
|
58
|
+
storageId: string;
|
|
59
|
+
key: string;
|
|
60
|
+
/** The original, pre-serialization value captured by `structuredClone`; `null` denotes a deletion. */
|
|
61
|
+
value: unknown;
|
|
62
|
+
options?: RecordOptions;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* A request recorded in a transaction journal.
|
|
66
|
+
*/
|
|
67
|
+
export interface JournaledRequest {
|
|
68
|
+
url: string;
|
|
69
|
+
uniqueKey: string;
|
|
70
|
+
label?: string;
|
|
71
|
+
/**
|
|
72
|
+
* A full JSON snapshot of the request for the commit replay. Only present for buffered additions —
|
|
73
|
+
* deduplicated and write-through ones are journaled for introspection only.
|
|
74
|
+
*/
|
|
75
|
+
snapshot?: Dictionary;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* A batch of request queue additions recorded in a transaction journal.
|
|
79
|
+
*/
|
|
80
|
+
export interface RequestQueueJournalEntry {
|
|
81
|
+
type: 'requestQueue';
|
|
82
|
+
/** @internal **/
|
|
83
|
+
participant: TransactionParticipant;
|
|
84
|
+
requests: JournaledRequest[];
|
|
85
|
+
forefront: boolean;
|
|
86
|
+
/** Write-through entries were applied immediately; they are never replayed. */
|
|
87
|
+
writeThrough: boolean;
|
|
88
|
+
}
|
|
89
|
+
export type JournalEntry = DatasetJournalEntry | KeyValueStoreJournalEntry | RequestQueueJournalEntry;
|
|
90
|
+
/**
|
|
91
|
+
* A read-only view of a {@link StorageTransaction}: only the journal-backed introspection accessors,
|
|
92
|
+
* without the lifecycle methods. The accessors are synchronous and expose the original pre-serialization
|
|
93
|
+
* values. They cover every write recorded while the transaction was open, under either write policy —
|
|
94
|
+
* with the one exception noted on {@link StorageTransactionView.enqueuedUrls|`enqueuedUrls`}. A view
|
|
95
|
+
* is valid until the transaction is disposed.
|
|
96
|
+
*/
|
|
97
|
+
export interface StorageTransactionView {
|
|
98
|
+
readonly state: StorageTransactionState;
|
|
99
|
+
/** Items pushed to datasets during the transaction, in push order. */
|
|
100
|
+
readonly datasetItems: {
|
|
101
|
+
item: Dictionary;
|
|
102
|
+
datasetId: string;
|
|
103
|
+
}[];
|
|
104
|
+
/**
|
|
105
|
+
* URLs enqueued to request queues during the transaction, under either write policy. Recorded as
|
|
106
|
+
* requested, so duplicate, already-present and backend-rejected URLs are included.
|
|
107
|
+
*
|
|
108
|
+
* One gap: unless a caller of `addRequestsBatched()` waits for every chunk
|
|
109
|
+
* (`waitForAllRequestsToBeAdded` or `maxNewRequests`, both of which {@link enqueueLinks} sets when
|
|
110
|
+
* a crawl limit applies), the chunks after the first are added by a background writer that outlives
|
|
111
|
+
* the transaction and is not recorded here.
|
|
112
|
+
*/
|
|
113
|
+
readonly enqueuedUrls: {
|
|
114
|
+
url: string;
|
|
115
|
+
label?: string;
|
|
116
|
+
}[];
|
|
117
|
+
/** Key-value store changes made during the transaction, keyed by store id, last write per key. */
|
|
118
|
+
readonly keyValueStoreChanges: Record<string, Record<string, {
|
|
119
|
+
changedValue: unknown;
|
|
120
|
+
options?: RecordOptions;
|
|
121
|
+
}>>;
|
|
122
|
+
}
|
|
123
|
+
export interface StorageTransactionOptions {
|
|
124
|
+
/** Overrides of the per-storage-type write policy. See {@link StorageWritePolicy}. */
|
|
125
|
+
policy?: Partial<StorageWritePolicy>;
|
|
126
|
+
/**
|
|
127
|
+
* How long a commit may take before it fails, in milliseconds. There is no automatic retry — the
|
|
128
|
+
* replay of dataset items is not idempotent.
|
|
129
|
+
* @default 300000
|
|
130
|
+
*/
|
|
131
|
+
commitTimeoutMillis?: number;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* A storage transaction scoped to a request's lifecycle. Writes made through the storage frontends
|
|
135
|
+
* ({@link Dataset}, {@link KeyValueStore}, {@link RequestQueue}) while the transaction is active
|
|
136
|
+
* are recorded rather than applied; on {@link StorageTransaction.commit|`commit()`} they are replayed
|
|
137
|
+
* into real storage, on {@link StorageTransaction.rollback|`rollback()`} they are dropped. Reads consult
|
|
138
|
+
* the recorded writes first, so a handler sees its own writes.
|
|
139
|
+
*
|
|
140
|
+
* Create one with {@link createStorageTransaction} (explicit commit/rollback) or
|
|
141
|
+
* {@link withStorageTransaction} (scoped sugar). Crawlers open one automatically around every request
|
|
142
|
+
* handler unless `transactionalStorage: false` is set.
|
|
143
|
+
*/
|
|
144
|
+
export declare class StorageTransaction implements StorageTransactionView {
|
|
145
|
+
#private;
|
|
146
|
+
/** The ordered, append-only journal — the source of truth for commit, introspection and reads. */
|
|
147
|
+
readonly journal: JournalEntry[];
|
|
148
|
+
/** Per-storage-type write policy. */
|
|
149
|
+
readonly policy: StorageWritePolicy;
|
|
150
|
+
/** @internal */
|
|
151
|
+
constructor(options?: StorageTransactionOptions);
|
|
152
|
+
get state(): StorageTransactionState;
|
|
153
|
+
/**
|
|
154
|
+
* `true` only while `state === 'open'`. This is the single predicate every storage operation
|
|
155
|
+
* consults — operations performed after the transaction is closed pass through to the real backend.
|
|
156
|
+
*/
|
|
157
|
+
get isActive(): boolean;
|
|
158
|
+
/** Runs `callback` with this transaction installed in the async context. */
|
|
159
|
+
run<T>(callback: () => Awaitable<T>): Promise<T>;
|
|
160
|
+
/**
|
|
161
|
+
* Records a write operation in the journal.
|
|
162
|
+
* @internal
|
|
163
|
+
*/
|
|
164
|
+
recordJournalEntry(entry: JournalEntry): void;
|
|
165
|
+
/**
|
|
166
|
+
* Replays the journaled writes into real storage. A no-op unless the transaction is `open`.
|
|
167
|
+
*
|
|
168
|
+
* The transaction transitions to `committing` *before* anything is flushed, so a commit that throws
|
|
169
|
+
* partway lands in `failed` (never back in `open`) and subsequent storage operations pass through
|
|
170
|
+
* rather than recording into a dead transaction. Delivery is at-least-once — a commit that fails
|
|
171
|
+
* partway may have applied some of the writes already.
|
|
172
|
+
*/
|
|
173
|
+
commit(): Promise<void>;
|
|
174
|
+
private flush;
|
|
175
|
+
/**
|
|
176
|
+
* Discards the journaled writes. A no-op unless the transaction is `open` — in particular, calling it
|
|
177
|
+
* after a successful `commit()` (which the crawler's error handling can legitimately do) does nothing
|
|
178
|
+
* and never throws.
|
|
179
|
+
*/
|
|
180
|
+
rollback(): void;
|
|
181
|
+
/**
|
|
182
|
+
* Releases the journal and the write-time snapshots it holds. Must be called for *every* terminal
|
|
183
|
+
* state, `failed` included. Idempotent, never throws, and does not change `state`. Any
|
|
184
|
+
* {@link StorageTransactionView} of this transaction is only valid until this is called.
|
|
185
|
+
*/
|
|
186
|
+
dispose(): void;
|
|
187
|
+
get datasetItems(): {
|
|
188
|
+
item: Dictionary;
|
|
189
|
+
datasetId: string;
|
|
190
|
+
}[];
|
|
191
|
+
get enqueuedUrls(): {
|
|
192
|
+
url: string;
|
|
193
|
+
label?: string;
|
|
194
|
+
}[];
|
|
195
|
+
get keyValueStoreChanges(): Record<string, Record<string, {
|
|
196
|
+
changedValue: unknown;
|
|
197
|
+
options?: RecordOptions;
|
|
198
|
+
}>>;
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Opens a {@link StorageTransaction} without running anything yet. The caller owns the outcome:
|
|
202
|
+
* `run()`, then `commit()` or `rollback()`, and always `dispose()` when done. For the common
|
|
203
|
+
* open-run-commit flow, prefer {@link withStorageTransaction}.
|
|
204
|
+
*/
|
|
205
|
+
export declare function createStorageTransaction(options?: StorageTransactionOptions): StorageTransaction;
|
|
206
|
+
/**
|
|
207
|
+
* Runs `callback` inside a new {@link StorageTransaction}: storage writes made in the callback are
|
|
208
|
+
* committed when it returns and rolled back when it throws. If a transaction is already active in the
|
|
209
|
+
* current async context, it is reused and its outcome is left to its owner (and `options` are ignored)
|
|
210
|
+
* — there are no nested transaction semantics.
|
|
211
|
+
*/
|
|
212
|
+
export declare function withStorageTransaction<T>(callback: (transaction: StorageTransaction) => Awaitable<T>, options?: StorageTransactionOptions): Promise<T>;
|
|
213
|
+
/**
|
|
214
|
+
* Runs `callback` outside of any storage transaction — the per-call-site escape hatch. Storage operations
|
|
215
|
+
* made inside it hit the real backend directly, are not rolled back, and operations that a transaction
|
|
216
|
+
* rejects (`drop`, stream-valued `setValue`, request queue internals, ...) are permitted.
|
|
217
|
+
*/
|
|
218
|
+
export declare function withDirectStorageAccess<T>(callback: () => Awaitable<T>): Promise<T>;
|
|
219
|
+
/**
|
|
220
|
+
* The per-operation hook consulted by every storage frontend method: performs the cancellation check
|
|
221
|
+
* that aborts storage operations when the request handler times out, and returns the active storage
|
|
222
|
+
* transaction. Returns `undefined` when there is no transaction in the async context *or* when it is no
|
|
223
|
+
* longer open — operations on a closed transaction deliberately pass through to the real backend.
|
|
224
|
+
* @internal
|
|
225
|
+
*/
|
|
226
|
+
export declare function activeStorageTransaction(): StorageTransaction | undefined;
|
|
227
|
+
/**
|
|
228
|
+
* Returns the transaction installed in the current async context, regardless of its state. Used by the
|
|
229
|
+
* crawler to drive the outcome of the transaction it opened.
|
|
230
|
+
* @internal
|
|
231
|
+
*/
|
|
232
|
+
export declare function currentStorageTransaction(): StorageTransaction | undefined;
|
|
233
|
+
/**
|
|
234
|
+
* Captures a value at write time, so that later mutations of the caller's object affect neither the
|
|
235
|
+
* read-your-own-writes reads nor the commit replay. `structuredClone` for fidelity (`Date`, `Map`, `Set`,
|
|
236
|
+
* typed arrays, `undefined`); values it cannot handle fall back to the JSON round-trip the storage
|
|
237
|
+
* backends perform anyway.
|
|
238
|
+
* @internal
|
|
239
|
+
*/
|
|
240
|
+
export declare function snapshotValue<T>(value: T): T;
|
|
241
|
+
/**
|
|
242
|
+
* The guard for operations that cannot be performed inside a storage transaction: throws when one is
|
|
243
|
+
* active, and performs the per-operation cancellation check either way.
|
|
244
|
+
* @internal
|
|
245
|
+
*/
|
|
246
|
+
export declare function rejectOperationInTransaction(operation: string, reason?: string): void;
|
|
247
|
+
/**
|
|
248
|
+
* Builds the "operation not allowed in a transaction" error, for a call site that has already
|
|
249
|
+
* established a transaction is active and so wants to `throw` unconditionally.
|
|
250
|
+
* @internal
|
|
251
|
+
*/
|
|
252
|
+
export declare function operationRejectedInTransaction(operation: string, reason?: string): Error;
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
import { addTimeoutToPromise, storage as timeoutStorage, tryCancel } from '@apify/timeout';
|
|
3
|
+
import { serviceLocator } from '../service_locator.js';
|
|
4
|
+
const DEFAULT_STORAGE_WRITE_POLICY = { requestQueue: 'writeThrough' };
|
|
5
|
+
const DEFAULT_COMMIT_TIMEOUT_MILLIS = 300_000;
|
|
6
|
+
const transactionStorage = new AsyncLocalStorage();
|
|
7
|
+
const COMMIT_ORDER = ['keyValueStore', 'requestQueue', 'dataset'];
|
|
8
|
+
/**
|
|
9
|
+
* A storage transaction scoped to a request's lifecycle. Writes made through the storage frontends
|
|
10
|
+
* ({@link Dataset}, {@link KeyValueStore}, {@link RequestQueue}) while the transaction is active
|
|
11
|
+
* are recorded rather than applied; on {@link StorageTransaction.commit|`commit()`} they are replayed
|
|
12
|
+
* into real storage, on {@link StorageTransaction.rollback|`rollback()`} they are dropped. Reads consult
|
|
13
|
+
* the recorded writes first, so a handler sees its own writes.
|
|
14
|
+
*
|
|
15
|
+
* Create one with {@link createStorageTransaction} (explicit commit/rollback) or
|
|
16
|
+
* {@link withStorageTransaction} (scoped sugar). Crawlers open one automatically around every request
|
|
17
|
+
* handler unless `transactionalStorage: false` is set.
|
|
18
|
+
*/
|
|
19
|
+
export class StorageTransaction {
|
|
20
|
+
/** The ordered, append-only journal — the source of truth for commit, introspection and reads. */
|
|
21
|
+
journal = [];
|
|
22
|
+
/** Per-storage-type write policy. */
|
|
23
|
+
policy;
|
|
24
|
+
#commitTimeoutMillis;
|
|
25
|
+
#state = 'open';
|
|
26
|
+
#disposed = false;
|
|
27
|
+
/** @internal */
|
|
28
|
+
constructor(options = {}) {
|
|
29
|
+
this.policy = { ...DEFAULT_STORAGE_WRITE_POLICY, ...options.policy };
|
|
30
|
+
this.#commitTimeoutMillis = options.commitTimeoutMillis ?? DEFAULT_COMMIT_TIMEOUT_MILLIS;
|
|
31
|
+
}
|
|
32
|
+
get state() {
|
|
33
|
+
return this.#state;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* `true` only while `state === 'open'`. This is the single predicate every storage operation
|
|
37
|
+
* consults — operations performed after the transaction is closed pass through to the real backend.
|
|
38
|
+
*/
|
|
39
|
+
get isActive() {
|
|
40
|
+
return this.#state === 'open';
|
|
41
|
+
}
|
|
42
|
+
/** Runs `callback` with this transaction installed in the async context. */
|
|
43
|
+
async run(callback) {
|
|
44
|
+
return transactionStorage.run(this, async () => callback());
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Records a write operation in the journal.
|
|
48
|
+
* @internal
|
|
49
|
+
*/
|
|
50
|
+
recordJournalEntry(entry) {
|
|
51
|
+
if (!this.isActive) {
|
|
52
|
+
throw new Error(`Cannot record a journal entry on a transaction in the '${this.#state}' state`);
|
|
53
|
+
}
|
|
54
|
+
this.journal.push(entry);
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Replays the journaled writes into real storage. A no-op unless the transaction is `open`.
|
|
58
|
+
*
|
|
59
|
+
* The transaction transitions to `committing` *before* anything is flushed, so a commit that throws
|
|
60
|
+
* partway lands in `failed` (never back in `open`) and subsequent storage operations pass through
|
|
61
|
+
* rather than recording into a dead transaction. Delivery is at-least-once — a commit that fails
|
|
62
|
+
* partway may have applied some of the writes already.
|
|
63
|
+
*/
|
|
64
|
+
async commit() {
|
|
65
|
+
if (this.#state !== 'open') {
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
this.#state = 'committing';
|
|
69
|
+
try {
|
|
70
|
+
// The replay re-drives the frontend write path, which checks for cancellation (`tryCancel`)
|
|
71
|
+
// on every operation - and `@apify/timeout` shares one `AbortController` across nested
|
|
72
|
+
// frames, so a request-handler timeout that already fired would abort the commit of a
|
|
73
|
+
// handler that succeeded. Hence a fresh timeout context, which also provides the time bound.
|
|
74
|
+
await timeoutStorage.exit(async () => addTimeoutToPromise(async () => this.flush(), this.#commitTimeoutMillis, `Committing the storage transaction timed out after ${this.#commitTimeoutMillis / 1000} seconds.`));
|
|
75
|
+
this.#state = 'committed';
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
this.#state = 'failed';
|
|
79
|
+
throw error;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
async flush() {
|
|
83
|
+
// Each participating frontend replays all of its buffered entries in one call. Frontends are
|
|
84
|
+
// ordered by storage type: key-value stores and request queues first (idempotent under retry),
|
|
85
|
+
// datasets last (not idempotent), minimizing the blast radius of a partial commit failure.
|
|
86
|
+
const groups = new Map();
|
|
87
|
+
for (const entry of this.journal) {
|
|
88
|
+
if (entry.type === 'requestQueue' && entry.writeThrough)
|
|
89
|
+
continue;
|
|
90
|
+
const group = groups.get(entry.participant);
|
|
91
|
+
if (group)
|
|
92
|
+
group.push(entry);
|
|
93
|
+
else
|
|
94
|
+
groups.set(entry.participant, [entry]);
|
|
95
|
+
}
|
|
96
|
+
// A participant only records entries of its own storage type, so the first entry determines
|
|
97
|
+
// the group's place in the commit order.
|
|
98
|
+
const orderedGroups = [...groups.values()].sort((a, b) => COMMIT_ORDER.indexOf(a[0].type) - COMMIT_ORDER.indexOf(b[0].type));
|
|
99
|
+
for (const entries of orderedGroups) {
|
|
100
|
+
await entries[0].participant.commitJournalEntries(entries);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Discards the journaled writes. A no-op unless the transaction is `open` — in particular, calling it
|
|
105
|
+
* after a successful `commit()` (which the crawler's error handling can legitimately do) does nothing
|
|
106
|
+
* and never throws.
|
|
107
|
+
*/
|
|
108
|
+
rollback() {
|
|
109
|
+
if (this.#state !== 'open') {
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
this.#state = 'rolledBack';
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Releases the journal and the write-time snapshots it holds. Must be called for *every* terminal
|
|
116
|
+
* state, `failed` included. Idempotent, never throws, and does not change `state`. Any
|
|
117
|
+
* {@link StorageTransactionView} of this transaction is only valid until this is called.
|
|
118
|
+
*/
|
|
119
|
+
dispose() {
|
|
120
|
+
if (this.#disposed) {
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
if (this.#state === 'open') {
|
|
124
|
+
// Disposing an open transaction is an internal invariant violation - roll back first.
|
|
125
|
+
try {
|
|
126
|
+
serviceLocator
|
|
127
|
+
.getLogger()
|
|
128
|
+
.warning('Internal error: a storage transaction was disposed while still open; rolling it back.');
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
// Never throw from dispose.
|
|
132
|
+
}
|
|
133
|
+
this.rollback();
|
|
134
|
+
}
|
|
135
|
+
this.#disposed = true;
|
|
136
|
+
this.journal.length = 0;
|
|
137
|
+
}
|
|
138
|
+
get datasetItems() {
|
|
139
|
+
return this.journal.flatMap((entry) => entry.type === 'dataset' ? entry.items.map((item) => ({ item, datasetId: entry.storageId })) : []);
|
|
140
|
+
}
|
|
141
|
+
get enqueuedUrls() {
|
|
142
|
+
return this.journal.flatMap((entry) => entry.type === 'requestQueue' ? entry.requests.map(({ url, label }) => ({ url, label })) : []);
|
|
143
|
+
}
|
|
144
|
+
get keyValueStoreChanges() {
|
|
145
|
+
const result = {};
|
|
146
|
+
for (const entry of this.journal) {
|
|
147
|
+
if (entry.type !== 'keyValueStore')
|
|
148
|
+
continue;
|
|
149
|
+
result[entry.storageId] ??= {};
|
|
150
|
+
result[entry.storageId][entry.key] = { changedValue: entry.value, options: entry.options };
|
|
151
|
+
}
|
|
152
|
+
return result;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Opens a {@link StorageTransaction} without running anything yet. The caller owns the outcome:
|
|
157
|
+
* `run()`, then `commit()` or `rollback()`, and always `dispose()` when done. For the common
|
|
158
|
+
* open-run-commit flow, prefer {@link withStorageTransaction}.
|
|
159
|
+
*/
|
|
160
|
+
export function createStorageTransaction(options = {}) {
|
|
161
|
+
return new StorageTransaction(options);
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Runs `callback` inside a new {@link StorageTransaction}: storage writes made in the callback are
|
|
165
|
+
* committed when it returns and rolled back when it throws. If a transaction is already active in the
|
|
166
|
+
* current async context, it is reused and its outcome is left to its owner (and `options` are ignored)
|
|
167
|
+
* — there are no nested transaction semantics.
|
|
168
|
+
*/
|
|
169
|
+
export async function withStorageTransaction(callback, options = {}) {
|
|
170
|
+
const existing = transactionStorage.getStore();
|
|
171
|
+
if (existing?.isActive) {
|
|
172
|
+
return callback(existing);
|
|
173
|
+
}
|
|
174
|
+
const transaction = createStorageTransaction(options);
|
|
175
|
+
try {
|
|
176
|
+
const result = await transaction.run(async () => callback(transaction));
|
|
177
|
+
await transaction.commit();
|
|
178
|
+
return result;
|
|
179
|
+
}
|
|
180
|
+
catch (error) {
|
|
181
|
+
transaction.rollback();
|
|
182
|
+
throw error;
|
|
183
|
+
}
|
|
184
|
+
finally {
|
|
185
|
+
transaction.dispose();
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Runs `callback` outside of any storage transaction — the per-call-site escape hatch. Storage operations
|
|
190
|
+
* made inside it hit the real backend directly, are not rolled back, and operations that a transaction
|
|
191
|
+
* rejects (`drop`, stream-valued `setValue`, request queue internals, ...) are permitted.
|
|
192
|
+
*/
|
|
193
|
+
export async function withDirectStorageAccess(callback) {
|
|
194
|
+
return transactionStorage.exit(async () => callback());
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* The per-operation hook consulted by every storage frontend method: performs the cancellation check
|
|
198
|
+
* that aborts storage operations when the request handler times out, and returns the active storage
|
|
199
|
+
* transaction. Returns `undefined` when there is no transaction in the async context *or* when it is no
|
|
200
|
+
* longer open — operations on a closed transaction deliberately pass through to the real backend.
|
|
201
|
+
* @internal
|
|
202
|
+
*/
|
|
203
|
+
export function activeStorageTransaction() {
|
|
204
|
+
tryCancel();
|
|
205
|
+
const transaction = transactionStorage.getStore();
|
|
206
|
+
return transaction?.isActive ? transaction : undefined;
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Returns the transaction installed in the current async context, regardless of its state. Used by the
|
|
210
|
+
* crawler to drive the outcome of the transaction it opened.
|
|
211
|
+
* @internal
|
|
212
|
+
*/
|
|
213
|
+
export function currentStorageTransaction() {
|
|
214
|
+
return transactionStorage.getStore();
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Captures a value at write time, so that later mutations of the caller's object affect neither the
|
|
218
|
+
* read-your-own-writes reads nor the commit replay. `structuredClone` for fidelity (`Date`, `Map`, `Set`,
|
|
219
|
+
* typed arrays, `undefined`); values it cannot handle fall back to the JSON round-trip the storage
|
|
220
|
+
* backends perform anyway.
|
|
221
|
+
* @internal
|
|
222
|
+
*/
|
|
223
|
+
export function snapshotValue(value) {
|
|
224
|
+
try {
|
|
225
|
+
return structuredClone(value);
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
return JSON.parse(JSON.stringify(value));
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* The guard for operations that cannot be performed inside a storage transaction: throws when one is
|
|
233
|
+
* active, and performs the per-operation cancellation check either way.
|
|
234
|
+
* @internal
|
|
235
|
+
*/
|
|
236
|
+
export function rejectOperationInTransaction(operation, reason = 'it cannot be rolled back.') {
|
|
237
|
+
if (activeStorageTransaction() === undefined) {
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
throw operationRejectedInTransaction(operation, reason);
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Builds the "operation not allowed in a transaction" error, for a call site that has already
|
|
244
|
+
* established a transaction is active and so wants to `throw` unconditionally.
|
|
245
|
+
* @internal
|
|
246
|
+
*/
|
|
247
|
+
export function operationRejectedInTransaction(operation, reason = 'it cannot be rolled back.') {
|
|
248
|
+
return new Error(`${operation} cannot be used inside a storage transaction: ${reason} ` +
|
|
249
|
+
'If you really need it, wrap the call in withDirectStorageAccess(() => ...) - operations ' +
|
|
250
|
+
'performed there are applied immediately and are not rolled back.');
|
|
251
|
+
}
|
package/storages/utils.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type { BaseHttpClient
|
|
1
|
+
import type { BaseHttpClient } from '@crawlee/http-client';
|
|
2
|
+
import type { Dictionary, StorageBackend } from '@crawlee/types';
|
|
2
3
|
import { Configuration } from '../configuration.js';
|
|
3
4
|
import type { IProxyConfiguration } from '../proxy_configuration.js';
|
|
4
5
|
/**
|
|
@@ -14,7 +15,8 @@ interface PurgeDefaultStorageOptions {
|
|
|
14
15
|
}
|
|
15
16
|
/**
|
|
16
17
|
* Cleans up the local storage folder (defaults to `./storage`) created when running code locally.
|
|
17
|
-
* Purging
|
|
18
|
+
* Purging empties the storages that belong to a single run — the default one and every alias-keyed one —
|
|
19
|
+
* keeping only INPUT.json in the default KV store. Named storages persist across runs and are not touched.
|
|
18
20
|
*
|
|
19
21
|
* Purging of storages is happening automatically when we run our crawler (or when we open some storage
|
|
20
22
|
* explicitly, e.g. via `RequestList.open()`). We can disable that via `purgeOnStart` {@link Configuration}
|
|
@@ -28,7 +30,8 @@ interface PurgeDefaultStorageOptions {
|
|
|
28
30
|
export declare function purgeDefaultStorages(options?: PurgeDefaultStorageOptions): Promise<void>;
|
|
29
31
|
/**
|
|
30
32
|
* Cleans up the local storage folder (defaults to `./storage`) created when running code locally.
|
|
31
|
-
* Purging
|
|
33
|
+
* Purging empties the storages that belong to a single run — the default one and every alias-keyed one —
|
|
34
|
+
* keeping only INPUT.json in the default KV store. Named storages persist across runs and are not touched.
|
|
32
35
|
*
|
|
33
36
|
* Purging of storages is happening automatically when we run our crawler (or when we open some storage
|
|
34
37
|
* explicitly, e.g. via `RequestList.open()`). We can disable that via `purgeOnStart` {@link Configuration}
|
package/storages/utils.js
CHANGED
|
@@ -12,11 +12,20 @@ export async function purgeDefaultStorages(configurationOrOptions, storageBacken
|
|
|
12
12
|
const { configuration = serviceLocator.getConfiguration(), onlyPurgeOnce = false } = options;
|
|
13
13
|
({ storageBackend = serviceLocator.getStorageBackend() } = options);
|
|
14
14
|
const casted = storageBackend;
|
|
15
|
+
const runPurge = async () => {
|
|
16
|
+
try {
|
|
17
|
+
await casted.purge?.();
|
|
18
|
+
}
|
|
19
|
+
catch (e) {
|
|
20
|
+
casted.__purged = undefined;
|
|
21
|
+
throw e;
|
|
22
|
+
}
|
|
23
|
+
};
|
|
15
24
|
// if `onlyPurgeOnce` is true, will purge anytime this function is called, otherwise - only on start
|
|
16
25
|
if (!onlyPurgeOnce || (configuration.purgeOnStart && !casted.__purged)) {
|
|
17
|
-
casted.__purged =
|
|
18
|
-
await casted.purge?.();
|
|
26
|
+
casted.__purged = runPurge();
|
|
19
27
|
}
|
|
28
|
+
await casted.__purged;
|
|
20
29
|
}
|
|
21
30
|
/**
|
|
22
31
|
* Easily create and manage state values. All state values are automatically persisted.
|
package/system-info/runtime.js
CHANGED
|
@@ -50,31 +50,31 @@ export async function isContainerized() {
|
|
|
50
50
|
export function isLambda() {
|
|
51
51
|
return !!process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE;
|
|
52
52
|
}
|
|
53
|
-
let
|
|
53
|
+
let cgroupsVersion;
|
|
54
54
|
/**
|
|
55
55
|
* gets the cgroup version by checking for a file at /sys/fs/cgroup/memory
|
|
56
56
|
* @returns "V1" or "V2" for the version of cgroup or null if cgroup is not found.
|
|
57
57
|
*/
|
|
58
58
|
export async function getCgroupsVersion(forceReset) {
|
|
59
59
|
// Parameter forceReset is just internal for unit tests.
|
|
60
|
-
if (
|
|
61
|
-
return
|
|
60
|
+
if (cgroupsVersion !== undefined && !forceReset) {
|
|
61
|
+
return cgroupsVersion;
|
|
62
62
|
}
|
|
63
63
|
try {
|
|
64
64
|
// If this directory does not exists, cgroups are not available
|
|
65
65
|
await fs.access('/sys/fs/cgroup/');
|
|
66
66
|
}
|
|
67
67
|
catch (e) {
|
|
68
|
-
|
|
68
|
+
cgroupsVersion = null;
|
|
69
69
|
return null;
|
|
70
70
|
}
|
|
71
|
-
|
|
71
|
+
cgroupsVersion = 'V1';
|
|
72
72
|
try {
|
|
73
73
|
// If this directory does not exists, assume the container is using cgroups V2
|
|
74
74
|
await fs.access('/sys/fs/cgroup/memory/');
|
|
75
75
|
}
|
|
76
76
|
catch (e) {
|
|
77
|
-
|
|
77
|
+
cgroupsVersion = 'V2';
|
|
78
78
|
}
|
|
79
|
-
return
|
|
79
|
+
return cgroupsVersion;
|
|
80
80
|
}
|
package/url.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The canonical form of a hostname: lower-case, punycode, and without the optional root dot.
|
|
3
|
+
*
|
|
4
|
+
* Pass both sides of a hostname comparison through this, so that a domain written as `háčky.cz` still matches the
|
|
5
|
+
* `xn--hky-ela4t.cz` that `URL` reports.
|
|
6
|
+
*
|
|
7
|
+
* @internal
|
|
8
|
+
*/
|
|
9
|
+
export declare function normalizeHostname(hostname: string): string;
|
package/url.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The canonical form of a hostname: lower-case, punycode, and without the optional root dot.
|
|
3
|
+
*
|
|
4
|
+
* Pass both sides of a hostname comparison through this, so that a domain written as `háčky.cz` still matches the
|
|
5
|
+
* `xn--hky-ela4t.cz` that `URL` reports.
|
|
6
|
+
*
|
|
7
|
+
* @internal
|
|
8
|
+
*/
|
|
9
|
+
export function normalizeHostname(hostname) {
|
|
10
|
+
return hostname.toLowerCase().replace(/\.$/, '');
|
|
11
|
+
}
|
package/validators.d.ts
CHANGED
|
@@ -1,28 +1,25 @@
|
|
|
1
|
-
|
|
1
|
+
export { ArgumentValidationError, parseArgument } from '@crawlee/utils';
|
|
2
|
+
export { schemas } from '@crawlee/utils/internal';
|
|
2
3
|
/** @internal */
|
|
3
4
|
export declare const validators: {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
sessionPool: (value: Dictionary) => {
|
|
25
|
-
validator: boolean;
|
|
26
|
-
message: (label: string) => string;
|
|
27
|
-
};
|
|
5
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
6
|
+
browserPage: import("zod").ZodType<import("@crawlee/types").Dictionary, unknown, import("zod/v4/core").$ZodTypeInternals<import("@crawlee/types").Dictionary, unknown>>;
|
|
7
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
8
|
+
proxyConfiguration: import("zod").ZodType<import("@crawlee/types").Dictionary, unknown, import("zod/v4/core").$ZodTypeInternals<import("@crawlee/types").Dictionary, unknown>>;
|
|
9
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
10
|
+
requestList: import("zod").ZodType<import("@crawlee/types").Dictionary, unknown, import("zod/v4/core").$ZodTypeInternals<import("@crawlee/types").Dictionary, unknown>>;
|
|
11
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
12
|
+
requestQueue: import("zod").ZodType<import("@crawlee/types").Dictionary, unknown, import("zod/v4/core").$ZodTypeInternals<import("@crawlee/types").Dictionary, unknown>>;
|
|
13
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
14
|
+
browserPool: import("zod").ZodType<import("@crawlee/types").Dictionary, unknown, import("zod/v4/core").$ZodTypeInternals<import("@crawlee/types").Dictionary, unknown>>;
|
|
15
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
16
|
+
sessionPool: import("zod").ZodType<import("@crawlee/types").Dictionary, unknown, import("zod/v4/core").$ZodTypeInternals<import("@crawlee/types").Dictionary, unknown>>;
|
|
17
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
18
|
+
requestManager: import("zod").ZodType<import("@crawlee/types").Dictionary, unknown, import("zod/v4/core").$ZodTypeInternals<import("@crawlee/types").Dictionary, unknown>>;
|
|
19
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
20
|
+
storageBackend: import("zod").ZodType<import("@crawlee/types").Dictionary, unknown, import("zod/v4/core").$ZodTypeInternals<import("@crawlee/types").Dictionary, unknown>>;
|
|
21
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
22
|
+
logger: import("zod").ZodType<import("@crawlee/types").Dictionary, unknown, import("zod/v4/core").$ZodTypeInternals<import("@crawlee/types").Dictionary, unknown>>;
|
|
23
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
24
|
+
httpClient: import("zod").ZodCustom<import("@crawlee/http-client").BaseHttpClient, import("@crawlee/http-client").BaseHttpClient>;
|
|
28
25
|
};
|