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