@crawlee/core 4.0.0-beta.12 → 4.0.0-beta.121
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/README.md +17 -13
- package/autoscaling/autoscaled_pool.d.ts +67 -172
- package/autoscaling/autoscaled_pool.js +165 -320
- package/autoscaling/client_load_signal.d.ts +55 -0
- package/autoscaling/client_load_signal.js +73 -0
- package/autoscaling/concurrency_system.d.ts +268 -0
- package/autoscaling/concurrency_system.js +351 -0
- package/autoscaling/cpu_load_signal.d.ts +43 -0
- package/autoscaling/cpu_load_signal.js +47 -0
- package/autoscaling/event_loop_load_signal.d.ts +51 -0
- package/autoscaling/event_loop_load_signal.js +60 -0
- package/autoscaling/index.d.ts +6 -1
- package/autoscaling/index.js +6 -1
- package/autoscaling/load_signal.d.ts +99 -0
- package/autoscaling/load_signal.js +104 -0
- package/autoscaling/memory_load_signal.d.ts +47 -0
- package/autoscaling/memory_load_signal.js +106 -0
- package/autoscaling/snapshotter.d.ts +58 -163
- package/autoscaling/snapshotter.js +45 -263
- package/autoscaling/system_status.d.ts +62 -84
- package/autoscaling/system_status.js +92 -122
- package/autoscaling/weighted_avg.d.ts +5 -0
- package/autoscaling/weighted_avg.js +14 -0
- package/byte_utils.d.ts +17 -0
- package/byte_utils.js +42 -0
- package/configuration.d.ts +96 -223
- package/configuration.js +170 -222
- package/cookie_utils.d.ts +4 -3
- package/cookie_utils.js +22 -13
- package/crawlers/context_pipeline.d.ts +10 -1
- package/crawlers/context_pipeline.js +31 -8
- package/crawlers/crawler_commons.d.ts +90 -83
- package/crawlers/crawler_commons.js +1 -116
- package/crawlers/error_snapshotter.d.ts +2 -5
- package/crawlers/error_snapshotter.js +7 -8
- package/crawlers/error_tracker.d.ts +0 -1
- package/crawlers/error_tracker.js +0 -1
- package/crawlers/index.d.ts +1 -3
- package/crawlers/index.js +0 -3
- package/crawlers/internals/types.d.ts +0 -1
- package/crawlers/internals/types.js +0 -1
- package/crawlers/statistics.d.ts +143 -59
- package/crawlers/statistics.js +243 -153
- package/debug.d.ts +36 -0
- package/debug.js +70 -0
- package/enqueue_links/enqueue_links.d.ts +59 -68
- package/enqueue_links/enqueue_links.js +57 -62
- package/enqueue_links/index.d.ts +0 -1
- package/enqueue_links/index.js +0 -1
- package/enqueue_links/shared.d.ts +40 -27
- package/enqueue_links/shared.js +90 -68
- package/errors.d.ts +72 -4
- package/errors.js +89 -5
- package/events/event_manager.d.ts +35 -9
- package/events/event_manager.js +10 -12
- package/events/index.d.ts +0 -1
- package/events/index.js +0 -1
- package/events/local_event_manager.d.ts +15 -3
- package/events/local_event_manager.js +39 -13
- package/http.d.ts +9 -0
- package/http.js +28 -0
- package/index.d.ts +7 -4
- package/index.js +6 -3
- package/iterables.d.ts +79 -0
- package/iterables.js +134 -0
- package/log.d.ts +82 -3
- package/log.js +106 -1
- package/memory-storage/consts.d.ts +4 -0
- package/memory-storage/consts.js +4 -0
- package/memory-storage/index.d.ts +1 -0
- package/memory-storage/index.js +1 -0
- package/memory-storage/memory-storage.d.ts +38 -0
- package/memory-storage/memory-storage.js +130 -0
- package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
- package/memory-storage/resource-clients/common/base-client.js +6 -0
- package/memory-storage/resource-clients/dataset.d.ts +40 -0
- package/memory-storage/resource-clients/dataset.js +114 -0
- package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
- package/memory-storage/resource-clients/key-value-store.js +204 -0
- package/memory-storage/resource-clients/request-queue.d.ts +77 -0
- package/memory-storage/resource-clients/request-queue.js +422 -0
- package/memory-storage/utils.d.ts +16 -0
- package/memory-storage/utils.js +41 -0
- package/owned_or_injected.d.ts +58 -0
- package/owned_or_injected.js +98 -0
- package/package.json +13 -12
- package/proxy_configuration.d.ts +24 -132
- package/proxy_configuration.js +24 -143
- package/recoverable_state.d.ts +140 -0
- package/recoverable_state.js +212 -0
- package/request.d.ts +86 -17
- package/request.js +120 -41
- package/router.d.ts +193 -21
- package/router.js +188 -43
- package/serialization.d.ts +0 -1
- package/serialization.js +9 -11
- package/service_locator.d.ts +165 -0
- package/service_locator.js +253 -0
- package/session_pool/consts.d.ts +1 -2
- package/session_pool/consts.js +1 -2
- package/session_pool/errors.d.ts +0 -1
- package/session_pool/errors.js +0 -1
- package/session_pool/fingerprint.d.ts +9 -0
- package/session_pool/fingerprint.js +30 -0
- package/session_pool/index.d.ts +0 -2
- package/session_pool/index.js +0 -2
- package/session_pool/session.d.ts +35 -89
- package/session_pool/session.js +82 -142
- package/session_pool/session_pool.d.ts +69 -90
- package/session_pool/session_pool.js +151 -150
- package/storages/batched_adds.d.ts +37 -0
- package/storages/batched_adds.js +73 -0
- package/storages/dataset.d.ts +114 -54
- package/storages/dataset.js +285 -144
- package/storages/index.d.ts +10 -8
- package/storages/index.js +8 -8
- package/storages/key_value_store.d.ts +185 -42
- package/storages/key_value_store.js +424 -151
- package/storages/key_value_store_codec.d.ts +32 -0
- package/storages/key_value_store_codec.js +113 -0
- package/storages/request_dedup_cache.d.ts +22 -0
- package/storages/request_dedup_cache.js +48 -0
- package/storages/request_list.d.ts +52 -116
- package/storages/request_list.js +159 -133
- package/storages/request_loader.d.ts +101 -0
- package/storages/request_loader.js +1 -0
- package/storages/request_manager.d.ts +33 -0
- package/storages/request_manager.js +1 -0
- package/storages/request_manager_tandem.d.ts +97 -0
- package/storages/request_manager_tandem.js +197 -0
- package/storages/request_queue.d.ts +290 -47
- package/storages/request_queue.js +757 -216
- package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +37 -88
- package/storages/{sitemap_request_list.js → sitemap_request_loader.js} +137 -143
- package/storages/storage_instance_manager.d.ts +87 -0
- package/storages/storage_instance_manager.js +256 -0
- package/storages/storage_stats.d.ts +48 -0
- package/storages/storage_stats.js +29 -0
- package/storages/throttling_request_manager.d.ts +216 -0
- package/storages/throttling_request_manager.js +453 -0
- package/storages/transaction.d.ts +252 -0
- package/storages/transaction.js +251 -0
- package/storages/utils.d.ts +58 -11
- package/storages/utils.js +64 -13
- package/system-info/cpu-info.d.ts +67 -0
- package/system-info/cpu-info.js +216 -0
- package/system-info/memory-info.d.ts +31 -0
- package/system-info/memory-info.js +115 -0
- package/system-info/ps-tree.d.ts +17 -0
- package/system-info/ps-tree.js +144 -0
- package/system-info/runtime.d.ts +14 -0
- package/system-info/runtime.js +80 -0
- package/typedefs.d.ts +0 -6
- package/typedefs.js +0 -1
- package/url.d.ts +9 -0
- package/url.js +11 -0
- package/validators.d.ts +8 -1
- package/validators.js +10 -3
- package/autoscaling/autoscaled_pool.d.ts.map +0 -1
- package/autoscaling/autoscaled_pool.js.map +0 -1
- package/autoscaling/index.d.ts.map +0 -1
- package/autoscaling/index.js.map +0 -1
- package/autoscaling/snapshotter.d.ts.map +0 -1
- package/autoscaling/snapshotter.js.map +0 -1
- package/autoscaling/system_status.d.ts.map +0 -1
- package/autoscaling/system_status.js.map +0 -1
- package/configuration.d.ts.map +0 -1
- package/configuration.js.map +0 -1
- package/cookie_utils.d.ts.map +0 -1
- package/cookie_utils.js.map +0 -1
- package/crawlers/context_pipeline.d.ts.map +0 -1
- package/crawlers/context_pipeline.js.map +0 -1
- package/crawlers/crawler_commons.d.ts.map +0 -1
- package/crawlers/crawler_commons.js.map +0 -1
- package/crawlers/crawler_utils.d.ts +0 -10
- package/crawlers/crawler_utils.d.ts.map +0 -1
- package/crawlers/crawler_utils.js +0 -12
- package/crawlers/crawler_utils.js.map +0 -1
- package/crawlers/error_snapshotter.d.ts.map +0 -1
- package/crawlers/error_snapshotter.js.map +0 -1
- package/crawlers/error_tracker.d.ts.map +0 -1
- package/crawlers/error_tracker.js.map +0 -1
- package/crawlers/index.d.ts.map +0 -1
- package/crawlers/index.js.map +0 -1
- package/crawlers/internals/types.d.ts.map +0 -1
- package/crawlers/internals/types.js.map +0 -1
- package/crawlers/statistics.d.ts.map +0 -1
- package/crawlers/statistics.js.map +0 -1
- package/enqueue_links/enqueue_links.d.ts.map +0 -1
- package/enqueue_links/enqueue_links.js.map +0 -1
- package/enqueue_links/index.d.ts.map +0 -1
- package/enqueue_links/index.js.map +0 -1
- package/enqueue_links/shared.d.ts.map +0 -1
- package/enqueue_links/shared.js.map +0 -1
- package/errors.d.ts.map +0 -1
- package/errors.js.map +0 -1
- package/events/event_manager.d.ts.map +0 -1
- package/events/event_manager.js.map +0 -1
- package/events/index.d.ts.map +0 -1
- package/events/index.js.map +0 -1
- package/events/local_event_manager.d.ts.map +0 -1
- package/events/local_event_manager.js.map +0 -1
- package/http_clients/base-http-client.d.ts +0 -134
- package/http_clients/base-http-client.d.ts.map +0 -1
- package/http_clients/base-http-client.js +0 -33
- package/http_clients/base-http-client.js.map +0 -1
- package/http_clients/form-data-like.d.ts +0 -67
- package/http_clients/form-data-like.d.ts.map +0 -1
- package/http_clients/form-data-like.js +0 -5
- package/http_clients/form-data-like.js.map +0 -1
- package/http_clients/got-scraping-http-client.d.ts +0 -15
- package/http_clients/got-scraping-http-client.d.ts.map +0 -1
- package/http_clients/got-scraping-http-client.js +0 -69
- package/http_clients/got-scraping-http-client.js.map +0 -1
- package/http_clients/index.d.ts +0 -3
- package/http_clients/index.d.ts.map +0 -1
- package/http_clients/index.js +0 -3
- package/http_clients/index.js.map +0 -1
- package/index.d.ts.map +0 -1
- package/index.js.map +0 -1
- package/log.d.ts.map +0 -1
- package/log.js.map +0 -1
- package/proxy_configuration.d.ts.map +0 -1
- package/proxy_configuration.js.map +0 -1
- package/request.d.ts.map +0 -1
- package/request.js.map +0 -1
- package/router.d.ts.map +0 -1
- package/router.js.map +0 -1
- package/serialization.d.ts.map +0 -1
- package/serialization.js.map +0 -1
- package/session_pool/consts.d.ts.map +0 -1
- package/session_pool/consts.js.map +0 -1
- package/session_pool/errors.d.ts.map +0 -1
- package/session_pool/errors.js.map +0 -1
- package/session_pool/events.d.ts +0 -3
- package/session_pool/events.d.ts.map +0 -1
- package/session_pool/events.js +0 -3
- package/session_pool/events.js.map +0 -1
- package/session_pool/index.d.ts.map +0 -1
- package/session_pool/index.js.map +0 -1
- package/session_pool/session.d.ts.map +0 -1
- package/session_pool/session.js.map +0 -1
- package/session_pool/session_pool.d.ts.map +0 -1
- package/session_pool/session_pool.js.map +0 -1
- package/storages/access_checking.d.ts +0 -13
- package/storages/access_checking.d.ts.map +0 -1
- package/storages/access_checking.js +0 -14
- package/storages/access_checking.js.map +0 -1
- package/storages/dataset.d.ts.map +0 -1
- package/storages/dataset.js.map +0 -1
- package/storages/index.d.ts.map +0 -1
- package/storages/index.js.map +0 -1
- package/storages/key_value_store.d.ts.map +0 -1
- package/storages/key_value_store.js.map +0 -1
- package/storages/request_list.d.ts.map +0 -1
- package/storages/request_list.js.map +0 -1
- package/storages/request_provider.d.ts +0 -308
- package/storages/request_provider.d.ts.map +0 -1
- package/storages/request_provider.js +0 -555
- package/storages/request_provider.js.map +0 -1
- package/storages/request_queue.d.ts.map +0 -1
- package/storages/request_queue.js.map +0 -1
- package/storages/request_queue_v2.d.ts +0 -87
- package/storages/request_queue_v2.d.ts.map +0 -1
- package/storages/request_queue_v2.js +0 -438
- package/storages/request_queue_v2.js.map +0 -1
- package/storages/sitemap_request_list.d.ts.map +0 -1
- package/storages/sitemap_request_list.js.map +0 -1
- package/storages/storage_manager.d.ts +0 -58
- package/storages/storage_manager.d.ts.map +0 -1
- package/storages/storage_manager.js +0 -105
- package/storages/storage_manager.js.map +0 -1
- package/storages/utils.d.ts.map +0 -1
- package/storages/utils.js.map +0 -1
- package/tsconfig.build.tsbuildinfo +0 -1
- package/typedefs.d.ts.map +0 -1
- package/typedefs.js.map +0 -1
- package/validators.d.ts.map +0 -1
- package/validators.js.map +0 -1
|
@@ -1,42 +1,16 @@
|
|
|
1
|
-
import { readFile } from 'node:fs/promises';
|
|
2
|
-
import { join } from 'node:path';
|
|
3
|
-
import JSON5 from 'json5';
|
|
4
1
|
import ow, { ArgumentError } from 'ow';
|
|
5
2
|
import { KEY_VALUE_STORE_KEY_REGEX } from '@apify/consts';
|
|
6
|
-
import
|
|
7
|
-
import { jsonStringifyExtended } from '@apify/utilities';
|
|
3
|
+
import { tryCancel } from '@apify/timeout';
|
|
8
4
|
import { Configuration } from '../configuration.js';
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
*/
|
|
17
|
-
|
|
18
|
-
// If contentType is missing, value will be stringified to JSON
|
|
19
|
-
if (options.contentType === null || options.contentType === undefined) {
|
|
20
|
-
options.contentType = 'application/json; charset=utf-8';
|
|
21
|
-
try {
|
|
22
|
-
// Format JSON to simplify debugging, the overheads with compression is negligible
|
|
23
|
-
value = jsonStringifyExtended(value, null, 2);
|
|
24
|
-
}
|
|
25
|
-
catch (e) {
|
|
26
|
-
const error = e;
|
|
27
|
-
// Give more meaningful error message
|
|
28
|
-
if (error.message?.includes('Invalid string length')) {
|
|
29
|
-
error.message = 'Object is too large';
|
|
30
|
-
}
|
|
31
|
-
throw new Error(`The "value" parameter cannot be stringified to JSON: ${error.message}`);
|
|
32
|
-
}
|
|
33
|
-
if (value === undefined) {
|
|
34
|
-
throw new Error('The "value" parameter was stringified to JSON and returned undefined. ' +
|
|
35
|
-
"Make sure you're not trying to stringify an undefined value.");
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
return value;
|
|
39
|
-
};
|
|
5
|
+
import { serviceLocator } from '../service_locator.js';
|
|
6
|
+
import { activeStorageTransaction, operationRejectedInTransaction, rejectOperationInTransaction, snapshotValue, withDirectStorageAccess, } from './transaction.js';
|
|
7
|
+
import { parseValue, serializeValue } from './key_value_store_codec.js';
|
|
8
|
+
import { StorageStatsTracker } from './storage_stats.js';
|
|
9
|
+
import { resolveStorageIdentifier } from './storage_instance_manager.js';
|
|
10
|
+
import { createDualIterable, purgeDefaultStorages } from './utils.js';
|
|
11
|
+
import { isBuffer, isStream } from '../byte_utils.js';
|
|
12
|
+
/** @internal */
|
|
13
|
+
const KVS_KEYS_DEFAULT_LIMIT = 1000;
|
|
40
14
|
/**
|
|
41
15
|
* The `KeyValueStore` class represents a key-value store, a simple data storage that is used
|
|
42
16
|
* for saving and reading data records or files. Each data record is
|
|
@@ -94,23 +68,35 @@ export const maybeStringify = (value, options) => {
|
|
|
94
68
|
* @category Result Stores
|
|
95
69
|
*/
|
|
96
70
|
export class KeyValueStore {
|
|
97
|
-
|
|
71
|
+
configuration;
|
|
98
72
|
id;
|
|
99
73
|
name;
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
persistStateEventStarted = false;
|
|
74
|
+
// kept as TS-private: key_value_store tests spy on the backend directly
|
|
75
|
+
backend;
|
|
76
|
+
#persistStateEventStarted = false;
|
|
103
77
|
/** Cache for persistent (auto-saved) values. When we try to set such value, the cache will be updated automatically. */
|
|
104
|
-
cache = new Map();
|
|
78
|
+
#cache = new Map();
|
|
79
|
+
#statsTracker = new StorageStatsTracker({
|
|
80
|
+
readCount: 0,
|
|
81
|
+
writeCount: 0,
|
|
82
|
+
deleteCount: 0,
|
|
83
|
+
listCount: 0,
|
|
84
|
+
});
|
|
105
85
|
/**
|
|
106
86
|
* @internal
|
|
107
87
|
*/
|
|
108
|
-
constructor(options,
|
|
109
|
-
this.
|
|
110
|
-
this.id = options.id;
|
|
111
|
-
this.name = options.name;
|
|
112
|
-
this.
|
|
113
|
-
|
|
88
|
+
constructor(options, configuration = Configuration.getGlobalConfiguration()) {
|
|
89
|
+
this.configuration = configuration;
|
|
90
|
+
this.id = options.metadata.id;
|
|
91
|
+
this.name = options.metadata.name;
|
|
92
|
+
this.backend = options.backend;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Backend-independent usage counters tracked for this key-value store (read / write / delete /
|
|
96
|
+
* list operations issued to the underlying storage backend). Counted per backend call.
|
|
97
|
+
*/
|
|
98
|
+
get stats() {
|
|
99
|
+
return this.#statsTracker.current;
|
|
114
100
|
}
|
|
115
101
|
/**
|
|
116
102
|
* Gets a value from the key-value store.
|
|
@@ -145,10 +131,93 @@ export class KeyValueStore {
|
|
|
145
131
|
* on the MIME content type of the record, or `null` if the key is missing from the store.
|
|
146
132
|
*/
|
|
147
133
|
async getValue(key, defaultValue) {
|
|
148
|
-
|
|
134
|
+
tryCancel();
|
|
135
|
+
ow(key, ow.string.nonEmpty);
|
|
136
|
+
const record = await this.readRecord(key);
|
|
137
|
+
// A missing record falls back to the default; a record that parses to a falsy value (including
|
|
138
|
+
// a stored literal `null`) is returned verbatim, so callers can tell "stored null" from "absent".
|
|
139
|
+
if (!record) {
|
|
140
|
+
return defaultValue ?? null;
|
|
141
|
+
}
|
|
142
|
+
// Storage backends are byte transports — the value is raw bytes; the frontend parses it here.
|
|
143
|
+
return parseValue(record.value, record.contentType ?? null);
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* The active transaction's last buffered write per key for this store, derived from its journal.
|
|
147
|
+
* An entry with a `null` value is a tombstone (an in-transaction deletion).
|
|
148
|
+
*/
|
|
149
|
+
bufferedJournalEntries() {
|
|
150
|
+
const transaction = activeStorageTransaction();
|
|
151
|
+
if (!transaction)
|
|
152
|
+
return undefined;
|
|
153
|
+
const lastWritePerKey = new Map();
|
|
154
|
+
for (const entry of transaction.journal) {
|
|
155
|
+
if (entry.type === 'keyValueStore' && entry.participant === this) {
|
|
156
|
+
lastWritePerKey.set(entry.key, entry);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return lastWritePerKey;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* The single transaction-aware record read shared by `getValue`, `getRecord`, `recordExists` and the
|
|
163
|
+
* listing paths: buffered key → serialized through the standard codec (same fidelity as a real
|
|
164
|
+
* round-trip); tombstoned key → `null`; otherwise the backend.
|
|
165
|
+
*
|
|
166
|
+
* The per-key buffered lookup requires the whole journal to be reduced to a last-write-per-key map,
|
|
167
|
+
* which is O(journal). Single-record callers let it default (rebuilt per call); the listing paths,
|
|
168
|
+
* which read many keys, pass a map built once so the read stays O(1) per key instead of O(journal).
|
|
169
|
+
*/
|
|
170
|
+
async readRecord(key, buffered = this.bufferedJournalEntries()) {
|
|
171
|
+
const entry = buffered?.get(key);
|
|
172
|
+
if (entry) {
|
|
173
|
+
if (entry.value === null) {
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
const serialized = serializeValue(entry.value, entry.options?.contentType);
|
|
177
|
+
return {
|
|
178
|
+
value: normalizeSerializedValue(serialized.value),
|
|
179
|
+
contentType: serialized.contentType ?? null,
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
this.#statsTracker.add('readCount');
|
|
183
|
+
const record = await this.backend.getValue(key);
|
|
184
|
+
if (!record)
|
|
185
|
+
return null;
|
|
186
|
+
return {
|
|
187
|
+
value: record.value,
|
|
188
|
+
contentType: record.contentType ?? null,
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Reads a record from the key-value store without parsing the value.
|
|
193
|
+
*
|
|
194
|
+
* Use this when you need the raw bytes and the content type — for example, to run your own
|
|
195
|
+
* parser (`simdjson`, a custom XML library, etc.) or to forward the bytes verbatim.
|
|
196
|
+
*
|
|
197
|
+
* There is no symmetric `setRecord` method, because {@link KeyValueStore.setValue} already
|
|
198
|
+
* passes a `Buffer` (or `string` / `Stream`) through unchanged when an explicit `contentType`
|
|
199
|
+
* is provided. To write pre-serialized bytes, call
|
|
200
|
+
* `setValue(key, buffer, { contentType: 'application/json; charset=utf-8' })`.
|
|
201
|
+
*
|
|
202
|
+
* Returns `null` if the record does not exist.
|
|
203
|
+
*
|
|
204
|
+
* **Example usage:**
|
|
205
|
+
* ```javascript
|
|
206
|
+
* const store = await KeyValueStore.open();
|
|
207
|
+
* const record = await store.getRecord('huge.json');
|
|
208
|
+
* if (record) {
|
|
209
|
+
* const data = simdjson.parse(record.value);
|
|
210
|
+
* }
|
|
211
|
+
* ```
|
|
212
|
+
*
|
|
213
|
+
* @param key
|
|
214
|
+
* Unique key of the record. It can be at most 256 characters long and only consist
|
|
215
|
+
* of the following characters: `a`-`z`, `A`-`Z`, `0`-`9` and `!-_.'()`
|
|
216
|
+
*/
|
|
217
|
+
async getRecord(key) {
|
|
218
|
+
tryCancel();
|
|
149
219
|
ow(key, ow.string.nonEmpty);
|
|
150
|
-
|
|
151
|
-
return record?.value ?? defaultValue ?? null;
|
|
220
|
+
return this.readRecord(key);
|
|
152
221
|
}
|
|
153
222
|
/**
|
|
154
223
|
* Tests whether a record with the given key exists in the key-value store without retrieving its value.
|
|
@@ -157,45 +226,96 @@ export class KeyValueStore {
|
|
|
157
226
|
* @returns `true` if the record exists, `false` if it does not.
|
|
158
227
|
*/
|
|
159
228
|
async recordExists(key) {
|
|
160
|
-
|
|
229
|
+
tryCancel();
|
|
161
230
|
ow(key, ow.string.nonEmpty);
|
|
162
|
-
|
|
231
|
+
const entry = this.bufferedJournalEntries()?.get(key);
|
|
232
|
+
if (entry) {
|
|
233
|
+
return entry.value !== null;
|
|
234
|
+
}
|
|
235
|
+
return this.backend.recordExists(key);
|
|
163
236
|
}
|
|
164
237
|
async getAutoSavedValue(key, defaultValue = {}) {
|
|
165
|
-
|
|
166
|
-
if (this
|
|
167
|
-
return this
|
|
238
|
+
tryCancel();
|
|
239
|
+
if (this.#cache.has(key)) {
|
|
240
|
+
return this.#cache.get(key);
|
|
168
241
|
}
|
|
169
|
-
|
|
242
|
+
// Auto-saved state is deliberately *not* transactional. The direct read bypasses any active
|
|
243
|
+
// transaction - a buffered value seeded into this shared cache would survive a rollback forever.
|
|
244
|
+
const value = await withDirectStorageAccess(async () => this.getValue(key, defaultValue));
|
|
170
245
|
// The await above could have run in parallel with another call to this function. If the other call finished more quickly,
|
|
171
246
|
// the value will in cache at this point, and returning the new fetched value would introduce two different instances of
|
|
172
247
|
// the auto-saved object, and only the latter one would be persisted.
|
|
173
248
|
// Therefore we re-check the cache here, and if such race condition happened, we drop the fetched value and return the cached one.
|
|
174
|
-
if (this
|
|
175
|
-
return this
|
|
249
|
+
if (this.#cache.has(key)) {
|
|
250
|
+
return this.#cache.get(key);
|
|
176
251
|
}
|
|
177
|
-
this
|
|
252
|
+
this.#cache.set(key, value);
|
|
178
253
|
this.ensurePersistStateEvent();
|
|
179
254
|
return value;
|
|
180
255
|
}
|
|
181
256
|
ensurePersistStateEvent() {
|
|
182
|
-
if (this
|
|
257
|
+
if (this.#persistStateEventStarted) {
|
|
183
258
|
return;
|
|
184
259
|
}
|
|
185
|
-
|
|
186
|
-
const persistStateIntervalMillis = this.config.get('persistStateIntervalMillis');
|
|
187
|
-
const timeoutSecs = persistStateIntervalMillis / 2_000;
|
|
188
|
-
this.config.getEventManager().on('persistState', async () => {
|
|
260
|
+
serviceLocator.getEventManager().on('persistState', async () => {
|
|
189
261
|
const promises = [];
|
|
190
|
-
for (const [key, value] of this
|
|
191
|
-
promises.push(this.setValue(key, value
|
|
192
|
-
timeoutSecs,
|
|
193
|
-
doNotRetryTimeouts: true,
|
|
194
|
-
}).catch((error) => log.warning(`Failed to persist the state value to ${key}`, { error })));
|
|
262
|
+
for (const [key, value] of this.#cache) {
|
|
263
|
+
promises.push(this.setValue(key, value).catch((error) => serviceLocator.getLogger().warning(`Failed to persist the state value to ${key}`, { error })));
|
|
195
264
|
}
|
|
196
265
|
await Promise.all(promises);
|
|
197
266
|
});
|
|
198
|
-
this
|
|
267
|
+
this.#persistStateEventStarted = true;
|
|
268
|
+
}
|
|
269
|
+
async *fetchKeyValuePages(options, mapRecord) {
|
|
270
|
+
// Reduce the journal once for the whole iteration, not once per key inside `readRecord`.
|
|
271
|
+
const buffered = this.bufferedJournalEntries();
|
|
272
|
+
for await (const page of this.fetchKeyPages(options, buffered)) {
|
|
273
|
+
const results = [];
|
|
274
|
+
for (const item of page) {
|
|
275
|
+
// The shared transaction-aware read, so a key that exists only in the transaction resolves
|
|
276
|
+
// here instead of being dropped (`values()` would disagree with `keys()` on length).
|
|
277
|
+
const record = await this.readRecord(item.key, buffered);
|
|
278
|
+
if (record) {
|
|
279
|
+
const parsed = parseValue(record.value, record.contentType ?? null);
|
|
280
|
+
results.push(mapRecord(item.key, parsed));
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
yield results;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
async *fetchKeyPages(options, buffered = this.bufferedJournalEntries(), limit = KVS_KEYS_DEFAULT_LIMIT) {
|
|
287
|
+
// Buffered keys are emitted first, then the real pages with any buffered (or tombstoned) key
|
|
288
|
+
// skipped - a merge-join is not an option, since `listKeys` promises no sort order.
|
|
289
|
+
const shadowedKeys = new Set();
|
|
290
|
+
if (buffered) {
|
|
291
|
+
const bufferedItems = [];
|
|
292
|
+
for (const [key, entry] of buffered) {
|
|
293
|
+
shadowedKeys.add(key);
|
|
294
|
+
if (entry.value === null)
|
|
295
|
+
continue;
|
|
296
|
+
if (options.prefix !== undefined && !key.startsWith(options.prefix))
|
|
297
|
+
continue;
|
|
298
|
+
bufferedItems.push(bufferedKeyItemData(key, entry));
|
|
299
|
+
}
|
|
300
|
+
if (bufferedItems.length > 0) {
|
|
301
|
+
bufferedItems.sort((a, b) => (a.key < b.key ? -1 : 1));
|
|
302
|
+
yield bufferedItems;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
let exclusiveStartKey;
|
|
306
|
+
while (true) {
|
|
307
|
+
this.#statsTracker.add('listCount');
|
|
308
|
+
const { items, isTruncated, nextExclusiveStartKey } = await this.backend.listKeys({
|
|
309
|
+
...options,
|
|
310
|
+
exclusiveStartKey,
|
|
311
|
+
limit,
|
|
312
|
+
});
|
|
313
|
+
yield shadowedKeys.size > 0 ? items.filter((item) => !shadowedKeys.has(item.key)) : items;
|
|
314
|
+
if (!isTruncated)
|
|
315
|
+
break;
|
|
316
|
+
// Paginate from the raw backend cursor - it may reject a key it did not hand out.
|
|
317
|
+
exclusiveStartKey = nextExclusiveStartKey;
|
|
318
|
+
}
|
|
199
319
|
}
|
|
200
320
|
/**
|
|
201
321
|
* Saves or deletes a record in the key-value store.
|
|
@@ -241,73 +361,107 @@ export class KeyValueStore {
|
|
|
241
361
|
* @param [options] Record options.
|
|
242
362
|
*/
|
|
243
363
|
async setValue(key, value, options = {}) {
|
|
244
|
-
|
|
364
|
+
const transaction = activeStorageTransaction();
|
|
245
365
|
ow(key, 'key', ow.string.nonEmpty);
|
|
246
366
|
ow(key, ow.string.validate((k) => ({
|
|
247
367
|
validator: ow.isValid(k, ow.string.matches(KEY_VALUE_STORE_KEY_REGEX)),
|
|
248
368
|
message: `The "key" argument "${key}" must be at most 256 characters long and only contain the following characters: a-zA-Z0-9!-_.'()`,
|
|
249
369
|
})));
|
|
250
|
-
if (options.contentType &&
|
|
251
|
-
|
|
252
|
-
(ow.isValid(value, ow.object) && typeof value.pipe === 'function'))) {
|
|
253
|
-
throw new ArgumentError('The "value" parameter must be a String, Buffer or Stream when "options.contentType" is specified.', this.setValue);
|
|
370
|
+
if (options.contentType && !(typeof value === 'string' || isBuffer(value) || isStream(value))) {
|
|
371
|
+
throw new ArgumentError('The "value" parameter must be a String, Buffer, ArrayBuffer, TypedArray, or Stream when "options.contentType" is specified.', this.setValue);
|
|
254
372
|
}
|
|
255
373
|
ow(options, ow.object.exactShape({
|
|
256
374
|
contentType: ow.optional.string.nonEmpty,
|
|
257
|
-
timeoutSecs: ow.optional.number,
|
|
258
|
-
doNotRetryTimeouts: ow.optional.boolean,
|
|
259
375
|
}));
|
|
260
376
|
// Make copy of options, don't update what user passed.
|
|
261
377
|
const optionsCopy = { ...options };
|
|
378
|
+
// The whole transaction branch sits *above* the auto-saved cache update below, so a buffered
|
|
379
|
+
// write touches nothing outside the journal. That cache is shared, process-lifetime frontend
|
|
380
|
+
// state, so mutating it here would survive a rollback and later be persisted by `persistState`.
|
|
381
|
+
// The commit replay re-enters this method with no active transaction and updates it then.
|
|
382
|
+
if (transaction) {
|
|
383
|
+
if (isStream(value)) {
|
|
384
|
+
// A stream cannot serve both a read-your-own-writes read and the commit replay. The
|
|
385
|
+
// transaction is known-active here, so throw directly rather than via the conditional guard.
|
|
386
|
+
throw operationRejectedInTransaction(`KeyValueStore.setValue() with a stream value (key "${key}")`, 'a stream can only be consumed once, so it cannot be buffered until commit.');
|
|
387
|
+
}
|
|
388
|
+
// Validation only, result discarded: the journal snapshot (`structuredClone`) accepts values
|
|
389
|
+
// JSON cannot, which would otherwise only throw at a later read or at commit.
|
|
390
|
+
if (value !== null) {
|
|
391
|
+
serializeValue(value, optionsCopy.contentType);
|
|
392
|
+
}
|
|
393
|
+
// One snapshot serves both the reads and the commit replay; `null` is a tombstone.
|
|
394
|
+
transaction.recordJournalEntry({
|
|
395
|
+
type: 'keyValueStore',
|
|
396
|
+
participant: this,
|
|
397
|
+
storageId: this.id,
|
|
398
|
+
key,
|
|
399
|
+
value: value === null ? null : snapshotValue(value),
|
|
400
|
+
options: optionsCopy,
|
|
401
|
+
});
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
262
404
|
// If we try to set the value of a cached state to a different reference, we need to update the cache accordingly.
|
|
263
|
-
const cachedValue = this
|
|
405
|
+
const cachedValue = this.#cache.get(key);
|
|
264
406
|
if (cachedValue && cachedValue !== value) {
|
|
265
407
|
if (value === null) {
|
|
266
408
|
// Cached state can be only object, so a propagation of `null` means removing all its properties.
|
|
267
|
-
Object.keys(cachedValue).forEach((k) => this
|
|
409
|
+
Object.keys(cachedValue).forEach((k) => this.#cache.delete(k));
|
|
268
410
|
}
|
|
269
411
|
else if (typeof value === 'object') {
|
|
270
412
|
// We need to remove the keys that are no longer present in the new value.
|
|
271
413
|
Object.keys(cachedValue)
|
|
272
414
|
.filter((k) => !(k in value))
|
|
273
|
-
.forEach((k) => this
|
|
415
|
+
.forEach((k) => this.#cache.delete(k));
|
|
274
416
|
// And update the existing ones + add new ones.
|
|
275
417
|
Object.assign(cachedValue, value);
|
|
276
418
|
}
|
|
277
419
|
}
|
|
278
420
|
// In this case delete the record.
|
|
279
|
-
if (value === null)
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
421
|
+
if (value === null) {
|
|
422
|
+
this.#statsTracker.add('deleteCount');
|
|
423
|
+
return this.backend.deleteValue(key);
|
|
424
|
+
}
|
|
425
|
+
const serialized = serializeValue(value, optionsCopy.contentType);
|
|
426
|
+
this.#statsTracker.add('writeCount');
|
|
427
|
+
return this.backend.setValue({
|
|
283
428
|
key,
|
|
284
|
-
value,
|
|
285
|
-
contentType:
|
|
286
|
-
}, {
|
|
287
|
-
timeoutSecs: optionsCopy.timeoutSecs,
|
|
288
|
-
doNotRetryTimeouts: optionsCopy.doNotRetryTimeouts,
|
|
429
|
+
value: serialized.value,
|
|
430
|
+
contentType: serialized.contentType,
|
|
289
431
|
});
|
|
290
432
|
}
|
|
433
|
+
/** @internal */
|
|
434
|
+
async commitJournalEntries(entries) {
|
|
435
|
+
// One `setValue` per key, last write wins - idempotent under retry.
|
|
436
|
+
const lastWritePerKey = new Map();
|
|
437
|
+
for (const entry of entries) {
|
|
438
|
+
if (entry.type === 'keyValueStore') {
|
|
439
|
+
lastWritePerKey.set(entry.key, { value: entry.value, options: entry.options });
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
for (const [key, { value, options }] of lastWritePerKey) {
|
|
443
|
+
await this.setValue(key, value, options);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
291
446
|
/**
|
|
292
447
|
* Removes the key-value store either from the Apify cloud storage or from the local directory,
|
|
293
448
|
* depending on the mode of operation.
|
|
294
449
|
*/
|
|
295
450
|
async drop() {
|
|
296
|
-
|
|
297
|
-
await this.
|
|
298
|
-
|
|
299
|
-
manager.closeStorage(this);
|
|
451
|
+
rejectOperationInTransaction('KeyValueStore.drop()');
|
|
452
|
+
await this.backend.drop();
|
|
453
|
+
serviceLocator.getStorageInstanceManager().removeFromCache(this);
|
|
300
454
|
}
|
|
301
455
|
/** @internal */
|
|
302
456
|
clearCache() {
|
|
303
|
-
|
|
304
|
-
this
|
|
457
|
+
rejectOperationInTransaction('KeyValueStore.clearCache()');
|
|
458
|
+
this.#cache.clear();
|
|
305
459
|
}
|
|
306
460
|
/**
|
|
307
461
|
* Iterates over key-value store keys, yielding each in turn to an `iteratee` function.
|
|
308
462
|
* Each invocation of `iteratee` is called with three arguments: `(key, index, info)`, where `key`
|
|
309
463
|
* is the record key, `index` is a zero-based index of the key in the current iteration
|
|
310
|
-
*
|
|
464
|
+
* and `info` is an object that contains a single property `size`
|
|
311
465
|
* indicating size of the record in bytes.
|
|
312
466
|
*
|
|
313
467
|
* If the `iteratee` function returns a Promise then it is awaited before the next call.
|
|
@@ -325,30 +479,132 @@ export class KeyValueStore {
|
|
|
325
479
|
* @param [options] All `forEachKey()` parameters.
|
|
326
480
|
*/
|
|
327
481
|
async forEachKey(iteratee, options = {}) {
|
|
328
|
-
|
|
329
|
-
return this._forEachKey(iteratee, options);
|
|
330
|
-
}
|
|
331
|
-
async _forEachKey(iteratee, options = {}, index = 0) {
|
|
332
|
-
const { exclusiveStartKey } = options;
|
|
482
|
+
tryCancel();
|
|
333
483
|
ow(iteratee, ow.function);
|
|
334
484
|
ow(options, ow.object.exactShape({
|
|
335
|
-
|
|
485
|
+
prefix: ow.optional.string,
|
|
336
486
|
}));
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
487
|
+
let index = 0;
|
|
488
|
+
for await (const page of this.fetchKeyPages(options)) {
|
|
489
|
+
for (const item of page) {
|
|
490
|
+
await iteratee(item.key, index++, { size: item.size });
|
|
491
|
+
}
|
|
341
492
|
}
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* Returns key-value store keys.
|
|
496
|
+
*
|
|
497
|
+
* When awaited (`await store.keys()`), returns all keys as a flat `string[]` array.
|
|
498
|
+
* When used as an async iterable (`for await...of`), iterates over all keys across pages
|
|
499
|
+
* without loading everything into memory at once.
|
|
500
|
+
*
|
|
501
|
+
* **Example usage:**
|
|
502
|
+
* ```javascript
|
|
503
|
+
* const keyValueStore = await KeyValueStore.open();
|
|
504
|
+
*
|
|
505
|
+
* // Iterate over all keys (memory-efficient for large stores)
|
|
506
|
+
* for await (const key of keyValueStore.keys()) {
|
|
507
|
+
* console.log(key);
|
|
508
|
+
* }
|
|
509
|
+
*
|
|
510
|
+
* // Or fetch all keys at once
|
|
511
|
+
* const allKeys = await keyValueStore.keys();
|
|
512
|
+
* console.log(allKeys);
|
|
513
|
+
* ```
|
|
514
|
+
*
|
|
515
|
+
* @param options Options for the iteration.
|
|
516
|
+
*/
|
|
517
|
+
keys(options = {}) {
|
|
518
|
+
tryCancel();
|
|
519
|
+
return createDualIterable({
|
|
520
|
+
createPages: () => this.fetchKeyPages(options),
|
|
521
|
+
extractItems: (page) => page.map((item) => item.key),
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* Returns key-value store values.
|
|
526
|
+
*
|
|
527
|
+
* When awaited (`await store.values()`), returns all values as a flat `T[]` array.
|
|
528
|
+
* When used as an async iterable (`for await...of`), iterates over all values across pages
|
|
529
|
+
* without loading everything into memory at once.
|
|
530
|
+
*
|
|
531
|
+
* **Example usage:**
|
|
532
|
+
* ```javascript
|
|
533
|
+
* const keyValueStore = await KeyValueStore.open();
|
|
534
|
+
*
|
|
535
|
+
* // Iterate over all values (memory-efficient for large stores)
|
|
536
|
+
* for await (const value of keyValueStore.values()) {
|
|
537
|
+
* console.log(value);
|
|
538
|
+
* }
|
|
539
|
+
*
|
|
540
|
+
* // Or fetch all values at once
|
|
541
|
+
* const allValues = await keyValueStore.values();
|
|
542
|
+
* console.log(allValues);
|
|
543
|
+
* ```
|
|
544
|
+
*
|
|
545
|
+
* @param options Options for the iteration.
|
|
546
|
+
*/
|
|
547
|
+
values(options = {}) {
|
|
548
|
+
tryCancel();
|
|
549
|
+
return createDualIterable({
|
|
550
|
+
createPages: () => this.fetchKeyValuePages(options, (_key, value) => value),
|
|
551
|
+
extractItems: (page) => page,
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
/**
|
|
555
|
+
* Returns key-value store entries (key-value pairs).
|
|
556
|
+
*
|
|
557
|
+
* When awaited (`await store.entries()`), returns all entries as a flat `[key, value][]` array.
|
|
558
|
+
* When used as an async iterable (`for await...of`), iterates over all entries across pages
|
|
559
|
+
* without loading everything into memory at once.
|
|
560
|
+
*
|
|
561
|
+
* **Example usage:**
|
|
562
|
+
* ```javascript
|
|
563
|
+
* const keyValueStore = await KeyValueStore.open();
|
|
564
|
+
*
|
|
565
|
+
* // Iterate over all entries (memory-efficient for large stores)
|
|
566
|
+
* for await (const [key, value] of keyValueStore.entries()) {
|
|
567
|
+
* console.log(`${key}: ${value}`);
|
|
568
|
+
* }
|
|
569
|
+
*
|
|
570
|
+
* // Or fetch all entries at once
|
|
571
|
+
* const allEntries = await keyValueStore.entries();
|
|
572
|
+
* console.log(allEntries);
|
|
573
|
+
* ```
|
|
574
|
+
*
|
|
575
|
+
* @param options Options for the iteration.
|
|
576
|
+
*/
|
|
577
|
+
entries(options = {}) {
|
|
578
|
+
tryCancel();
|
|
579
|
+
return createDualIterable({
|
|
580
|
+
createPages: () => this.fetchKeyValuePages(options, (key, value) => [key, value]),
|
|
581
|
+
extractItems: (page) => page,
|
|
582
|
+
});
|
|
583
|
+
}
|
|
584
|
+
/**
|
|
585
|
+
* Default async iterator for the key-value store, iterating over entries (key-value pairs).
|
|
586
|
+
* Allows using the store directly in a `for await...of` loop.
|
|
587
|
+
*
|
|
588
|
+
* **Example usage:**
|
|
589
|
+
* ```javascript
|
|
590
|
+
* const keyValueStore = await KeyValueStore.open();
|
|
591
|
+
* for await (const [key, value] of keyValueStore) {
|
|
592
|
+
* console.log(`${key}: ${value}`);
|
|
593
|
+
* }
|
|
594
|
+
* ```
|
|
595
|
+
*/
|
|
596
|
+
async *[Symbol.asyncIterator]() {
|
|
597
|
+
yield* this.entries();
|
|
345
598
|
}
|
|
346
599
|
/**
|
|
347
600
|
* Returns a file URL for the given key.
|
|
601
|
+
*
|
|
602
|
+
* If the record does not exist or has no associated file path (i.e., it is not stored as a file), returns `undefined`.
|
|
603
|
+
*
|
|
604
|
+
* @param key The key of the record to generate the public URL for.
|
|
348
605
|
*/
|
|
349
|
-
getPublicUrl(key) {
|
|
350
|
-
|
|
351
|
-
return `file://${process.cwd()}/storage/key_value_stores/${name}/${key}`;
|
|
606
|
+
async getPublicUrl(key) {
|
|
607
|
+
return this.backend.getPublicUrl(key);
|
|
352
608
|
}
|
|
353
609
|
/**
|
|
354
610
|
* Opens a key-value store and returns a promise resolving to an instance of the {@link KeyValueStore} class.
|
|
@@ -359,23 +615,27 @@ export class KeyValueStore {
|
|
|
359
615
|
*
|
|
360
616
|
* For more details and code examples, see the {@link KeyValueStore} class.
|
|
361
617
|
*
|
|
362
|
-
* @param [
|
|
363
|
-
* ID or name of the key-value store to be opened. If
|
|
364
|
-
*
|
|
618
|
+
* @param [identifier]
|
|
619
|
+
* ID or name of the key-value store to be opened. If a string is provided, it will first be
|
|
620
|
+
* looked up as an ID; if no such storage exists, it will be treated as a name.
|
|
621
|
+
* If `null` or `undefined`, the function returns the default key-value store associated with the crawler run.
|
|
365
622
|
* @param [options] Storage manager options.
|
|
366
623
|
*/
|
|
367
|
-
static async open(
|
|
368
|
-
|
|
369
|
-
ow(storeIdOrName, ow.optional.any(ow.string, ow.null));
|
|
624
|
+
static async open(identifier, options = {}) {
|
|
625
|
+
tryCancel();
|
|
370
626
|
ow(options, ow.object.exactShape({
|
|
371
|
-
|
|
372
|
-
|
|
627
|
+
configuration: ow.optional.object.instanceOf(Configuration),
|
|
628
|
+
storageBackend: ow.optional.object,
|
|
373
629
|
}));
|
|
374
|
-
options.
|
|
375
|
-
options.
|
|
376
|
-
await purgeDefaultStorages({ onlyPurgeOnce: true,
|
|
377
|
-
const
|
|
378
|
-
return
|
|
630
|
+
options.configuration ??= Configuration.getGlobalConfiguration();
|
|
631
|
+
const storageBackend = options.storageBackend ?? serviceLocator.getStorageBackend();
|
|
632
|
+
await purgeDefaultStorages({ onlyPurgeOnce: true, storageBackend, configuration: options.configuration });
|
|
633
|
+
const resolved = await resolveStorageIdentifier(identifier, storageBackend, 'KeyValueStore');
|
|
634
|
+
return serviceLocator.getStorageInstanceManager().openStorage(this, {
|
|
635
|
+
...resolved,
|
|
636
|
+
backendOpener: () => storageBackend.createKeyValueStoreBackend(resolved),
|
|
637
|
+
backendCacheKey: storageBackend.getStorageBackendCacheKey?.() ?? storageBackend.constructor.name,
|
|
638
|
+
});
|
|
379
639
|
}
|
|
380
640
|
/**
|
|
381
641
|
* Gets a value from the default {@link KeyValueStore} associated with the current crawler run.
|
|
@@ -410,6 +670,22 @@ export class KeyValueStore {
|
|
|
410
670
|
const store = await this.open();
|
|
411
671
|
return store.getValue(key, defaultValue);
|
|
412
672
|
}
|
|
673
|
+
/**
|
|
674
|
+
* Reads a record from the default {@link KeyValueStore} associated with the current crawler run
|
|
675
|
+
* without parsing the value.
|
|
676
|
+
*
|
|
677
|
+
* This is just a convenient shortcut for {@link KeyValueStore.getRecord}. Returns `null` if the
|
|
678
|
+
* record does not exist.
|
|
679
|
+
*
|
|
680
|
+
* @param key
|
|
681
|
+
* Unique key of the record. It can be at most 256 characters long and only consist
|
|
682
|
+
* of the following characters: `a`-`z`, `A`-`Z`, `0`-`9` and `!-_.'()`
|
|
683
|
+
* @ignore
|
|
684
|
+
*/
|
|
685
|
+
static async getRecord(key) {
|
|
686
|
+
const store = await this.open();
|
|
687
|
+
return store.getRecord(key);
|
|
688
|
+
}
|
|
413
689
|
/**
|
|
414
690
|
* Tests whether a record with the given key exists in the default {@link KeyValueStore} associated with the current crawler run.
|
|
415
691
|
* @param key The queried record key.
|
|
@@ -460,8 +736,9 @@ export class KeyValueStore {
|
|
|
460
736
|
}
|
|
461
737
|
/**
|
|
462
738
|
* Gets the crawler input value from the default {@link KeyValueStore} associated with the current crawler run.
|
|
463
|
-
*
|
|
464
|
-
*
|
|
739
|
+
*
|
|
740
|
+
* The input is read from the default {@link KeyValueStore} under the configured input key
|
|
741
|
+
* (`CRAWLEE_INPUT_KEY`, default `INPUT`).
|
|
465
742
|
*
|
|
466
743
|
* Note that the `getInput()` function does not cache the value read from the key-value store.
|
|
467
744
|
* If you need to use the input multiple times in your crawler,
|
|
@@ -479,29 +756,25 @@ export class KeyValueStore {
|
|
|
479
756
|
*/
|
|
480
757
|
static async getInput() {
|
|
481
758
|
const store = await this.open();
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
}
|
|
493
|
-
catch {
|
|
494
|
-
continue;
|
|
495
|
-
}
|
|
496
|
-
// Attempt to parse as JSON, or return the input as is otherwise
|
|
497
|
-
try {
|
|
498
|
-
return JSON5.parse(input.toString());
|
|
499
|
-
}
|
|
500
|
-
catch {
|
|
501
|
-
return input;
|
|
502
|
-
}
|
|
503
|
-
}
|
|
504
|
-
return store.getValue(inputKey);
|
|
759
|
+
return store.getValue(store.configuration.inputKey);
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
/** Normalizes a codec-serialized value into the `Buffer | ArrayBuffer` shape raw record reads promise. */
|
|
763
|
+
function normalizeSerializedValue(value) {
|
|
764
|
+
if (typeof value === 'string') {
|
|
765
|
+
return Buffer.from(value);
|
|
766
|
+
}
|
|
767
|
+
if (ArrayBuffer.isView(value)) {
|
|
768
|
+
return Buffer.isBuffer(value) ? value : Buffer.from(value.buffer, value.byteOffset, value.byteLength);
|
|
505
769
|
}
|
|
770
|
+
return value;
|
|
771
|
+
}
|
|
772
|
+
/** Computes the key listing item (serialized byte size and content type) of a buffered entry. */
|
|
773
|
+
function bufferedKeyItemData(key, entry) {
|
|
774
|
+
const serialized = serializeValue(entry.value, entry.options?.contentType);
|
|
775
|
+
return {
|
|
776
|
+
key,
|
|
777
|
+
size: normalizeSerializedValue(serialized.value).byteLength,
|
|
778
|
+
contentType: serialized.contentType,
|
|
779
|
+
};
|
|
506
780
|
}
|
|
507
|
-
//# sourceMappingURL=key_value_store.js.map
|