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