@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.
Files changed (279) hide show
  1. package/README.md +17 -13
  2. package/autoscaling/autoscaled_pool.d.ts +67 -172
  3. package/autoscaling/autoscaled_pool.js +165 -320
  4. package/autoscaling/client_load_signal.d.ts +55 -0
  5. package/autoscaling/client_load_signal.js +73 -0
  6. package/autoscaling/concurrency_system.d.ts +268 -0
  7. package/autoscaling/concurrency_system.js +351 -0
  8. package/autoscaling/cpu_load_signal.d.ts +43 -0
  9. package/autoscaling/cpu_load_signal.js +47 -0
  10. package/autoscaling/event_loop_load_signal.d.ts +51 -0
  11. package/autoscaling/event_loop_load_signal.js +60 -0
  12. package/autoscaling/index.d.ts +6 -1
  13. package/autoscaling/index.js +6 -1
  14. package/autoscaling/load_signal.d.ts +99 -0
  15. package/autoscaling/load_signal.js +104 -0
  16. package/autoscaling/memory_load_signal.d.ts +47 -0
  17. package/autoscaling/memory_load_signal.js +106 -0
  18. package/autoscaling/snapshotter.d.ts +58 -163
  19. package/autoscaling/snapshotter.js +45 -263
  20. package/autoscaling/system_status.d.ts +62 -84
  21. package/autoscaling/system_status.js +92 -122
  22. package/autoscaling/weighted_avg.d.ts +5 -0
  23. package/autoscaling/weighted_avg.js +14 -0
  24. package/byte_utils.d.ts +17 -0
  25. package/byte_utils.js +42 -0
  26. package/configuration.d.ts +96 -223
  27. package/configuration.js +170 -222
  28. package/cookie_utils.d.ts +4 -3
  29. package/cookie_utils.js +22 -13
  30. package/crawlers/context_pipeline.d.ts +10 -1
  31. package/crawlers/context_pipeline.js +31 -8
  32. package/crawlers/crawler_commons.d.ts +90 -83
  33. package/crawlers/crawler_commons.js +1 -116
  34. package/crawlers/error_snapshotter.d.ts +2 -5
  35. package/crawlers/error_snapshotter.js +7 -8
  36. package/crawlers/error_tracker.d.ts +0 -1
  37. package/crawlers/error_tracker.js +0 -1
  38. package/crawlers/index.d.ts +1 -3
  39. package/crawlers/index.js +0 -3
  40. package/crawlers/internals/types.d.ts +0 -1
  41. package/crawlers/internals/types.js +0 -1
  42. package/crawlers/statistics.d.ts +143 -59
  43. package/crawlers/statistics.js +243 -153
  44. package/debug.d.ts +36 -0
  45. package/debug.js +70 -0
  46. package/enqueue_links/enqueue_links.d.ts +59 -68
  47. package/enqueue_links/enqueue_links.js +57 -62
  48. package/enqueue_links/index.d.ts +0 -1
  49. package/enqueue_links/index.js +0 -1
  50. package/enqueue_links/shared.d.ts +40 -27
  51. package/enqueue_links/shared.js +90 -68
  52. package/errors.d.ts +72 -4
  53. package/errors.js +89 -5
  54. package/events/event_manager.d.ts +35 -9
  55. package/events/event_manager.js +10 -12
  56. package/events/index.d.ts +0 -1
  57. package/events/index.js +0 -1
  58. package/events/local_event_manager.d.ts +15 -3
  59. package/events/local_event_manager.js +39 -13
  60. package/http.d.ts +9 -0
  61. package/http.js +28 -0
  62. package/index.d.ts +7 -4
  63. package/index.js +6 -3
  64. package/iterables.d.ts +79 -0
  65. package/iterables.js +134 -0
  66. package/log.d.ts +82 -3
  67. package/log.js +106 -1
  68. package/memory-storage/consts.d.ts +4 -0
  69. package/memory-storage/consts.js +4 -0
  70. package/memory-storage/index.d.ts +1 -0
  71. package/memory-storage/index.js +1 -0
  72. package/memory-storage/memory-storage.d.ts +38 -0
  73. package/memory-storage/memory-storage.js +130 -0
  74. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  75. package/memory-storage/resource-clients/common/base-client.js +6 -0
  76. package/memory-storage/resource-clients/dataset.d.ts +40 -0
  77. package/memory-storage/resource-clients/dataset.js +114 -0
  78. package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
  79. package/memory-storage/resource-clients/key-value-store.js +204 -0
  80. package/memory-storage/resource-clients/request-queue.d.ts +77 -0
  81. package/memory-storage/resource-clients/request-queue.js +422 -0
  82. package/memory-storage/utils.d.ts +16 -0
  83. package/memory-storage/utils.js +41 -0
  84. package/owned_or_injected.d.ts +58 -0
  85. package/owned_or_injected.js +98 -0
  86. package/package.json +13 -12
  87. package/proxy_configuration.d.ts +24 -132
  88. package/proxy_configuration.js +24 -143
  89. package/recoverable_state.d.ts +140 -0
  90. package/recoverable_state.js +212 -0
  91. package/request.d.ts +86 -17
  92. package/request.js +120 -41
  93. package/router.d.ts +193 -21
  94. package/router.js +188 -43
  95. package/serialization.d.ts +0 -1
  96. package/serialization.js +9 -11
  97. package/service_locator.d.ts +165 -0
  98. package/service_locator.js +253 -0
  99. package/session_pool/consts.d.ts +1 -2
  100. package/session_pool/consts.js +1 -2
  101. package/session_pool/errors.d.ts +0 -1
  102. package/session_pool/errors.js +0 -1
  103. package/session_pool/fingerprint.d.ts +9 -0
  104. package/session_pool/fingerprint.js +30 -0
  105. package/session_pool/index.d.ts +0 -2
  106. package/session_pool/index.js +0 -2
  107. package/session_pool/session.d.ts +35 -89
  108. package/session_pool/session.js +82 -142
  109. package/session_pool/session_pool.d.ts +69 -90
  110. package/session_pool/session_pool.js +151 -150
  111. package/storages/batched_adds.d.ts +37 -0
  112. package/storages/batched_adds.js +73 -0
  113. package/storages/dataset.d.ts +114 -54
  114. package/storages/dataset.js +285 -144
  115. package/storages/index.d.ts +10 -8
  116. package/storages/index.js +8 -8
  117. package/storages/key_value_store.d.ts +185 -42
  118. package/storages/key_value_store.js +424 -151
  119. package/storages/key_value_store_codec.d.ts +32 -0
  120. package/storages/key_value_store_codec.js +113 -0
  121. package/storages/request_dedup_cache.d.ts +22 -0
  122. package/storages/request_dedup_cache.js +48 -0
  123. package/storages/request_list.d.ts +52 -116
  124. package/storages/request_list.js +159 -133
  125. package/storages/request_loader.d.ts +101 -0
  126. package/storages/request_loader.js +1 -0
  127. package/storages/request_manager.d.ts +33 -0
  128. package/storages/request_manager.js +1 -0
  129. package/storages/request_manager_tandem.d.ts +97 -0
  130. package/storages/request_manager_tandem.js +197 -0
  131. package/storages/request_queue.d.ts +290 -47
  132. package/storages/request_queue.js +757 -216
  133. package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +37 -88
  134. package/storages/{sitemap_request_list.js → sitemap_request_loader.js} +137 -143
  135. package/storages/storage_instance_manager.d.ts +87 -0
  136. package/storages/storage_instance_manager.js +256 -0
  137. package/storages/storage_stats.d.ts +48 -0
  138. package/storages/storage_stats.js +29 -0
  139. package/storages/throttling_request_manager.d.ts +216 -0
  140. package/storages/throttling_request_manager.js +453 -0
  141. package/storages/transaction.d.ts +252 -0
  142. package/storages/transaction.js +251 -0
  143. package/storages/utils.d.ts +58 -11
  144. package/storages/utils.js +64 -13
  145. package/system-info/cpu-info.d.ts +67 -0
  146. package/system-info/cpu-info.js +216 -0
  147. package/system-info/memory-info.d.ts +31 -0
  148. package/system-info/memory-info.js +115 -0
  149. package/system-info/ps-tree.d.ts +17 -0
  150. package/system-info/ps-tree.js +144 -0
  151. package/system-info/runtime.d.ts +14 -0
  152. package/system-info/runtime.js +80 -0
  153. package/typedefs.d.ts +0 -6
  154. package/typedefs.js +0 -1
  155. package/url.d.ts +9 -0
  156. package/url.js +11 -0
  157. package/validators.d.ts +8 -1
  158. package/validators.js +10 -3
  159. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  160. package/autoscaling/autoscaled_pool.js.map +0 -1
  161. package/autoscaling/index.d.ts.map +0 -1
  162. package/autoscaling/index.js.map +0 -1
  163. package/autoscaling/snapshotter.d.ts.map +0 -1
  164. package/autoscaling/snapshotter.js.map +0 -1
  165. package/autoscaling/system_status.d.ts.map +0 -1
  166. package/autoscaling/system_status.js.map +0 -1
  167. package/configuration.d.ts.map +0 -1
  168. package/configuration.js.map +0 -1
  169. package/cookie_utils.d.ts.map +0 -1
  170. package/cookie_utils.js.map +0 -1
  171. package/crawlers/context_pipeline.d.ts.map +0 -1
  172. package/crawlers/context_pipeline.js.map +0 -1
  173. package/crawlers/crawler_commons.d.ts.map +0 -1
  174. package/crawlers/crawler_commons.js.map +0 -1
  175. package/crawlers/crawler_utils.d.ts +0 -10
  176. package/crawlers/crawler_utils.d.ts.map +0 -1
  177. package/crawlers/crawler_utils.js +0 -12
  178. package/crawlers/crawler_utils.js.map +0 -1
  179. package/crawlers/error_snapshotter.d.ts.map +0 -1
  180. package/crawlers/error_snapshotter.js.map +0 -1
  181. package/crawlers/error_tracker.d.ts.map +0 -1
  182. package/crawlers/error_tracker.js.map +0 -1
  183. package/crawlers/index.d.ts.map +0 -1
  184. package/crawlers/index.js.map +0 -1
  185. package/crawlers/internals/types.d.ts.map +0 -1
  186. package/crawlers/internals/types.js.map +0 -1
  187. package/crawlers/statistics.d.ts.map +0 -1
  188. package/crawlers/statistics.js.map +0 -1
  189. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  190. package/enqueue_links/enqueue_links.js.map +0 -1
  191. package/enqueue_links/index.d.ts.map +0 -1
  192. package/enqueue_links/index.js.map +0 -1
  193. package/enqueue_links/shared.d.ts.map +0 -1
  194. package/enqueue_links/shared.js.map +0 -1
  195. package/errors.d.ts.map +0 -1
  196. package/errors.js.map +0 -1
  197. package/events/event_manager.d.ts.map +0 -1
  198. package/events/event_manager.js.map +0 -1
  199. package/events/index.d.ts.map +0 -1
  200. package/events/index.js.map +0 -1
  201. package/events/local_event_manager.d.ts.map +0 -1
  202. package/events/local_event_manager.js.map +0 -1
  203. package/http_clients/base-http-client.d.ts +0 -134
  204. package/http_clients/base-http-client.d.ts.map +0 -1
  205. package/http_clients/base-http-client.js +0 -33
  206. package/http_clients/base-http-client.js.map +0 -1
  207. package/http_clients/form-data-like.d.ts +0 -67
  208. package/http_clients/form-data-like.d.ts.map +0 -1
  209. package/http_clients/form-data-like.js +0 -5
  210. package/http_clients/form-data-like.js.map +0 -1
  211. package/http_clients/got-scraping-http-client.d.ts +0 -15
  212. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  213. package/http_clients/got-scraping-http-client.js +0 -69
  214. package/http_clients/got-scraping-http-client.js.map +0 -1
  215. package/http_clients/index.d.ts +0 -3
  216. package/http_clients/index.d.ts.map +0 -1
  217. package/http_clients/index.js +0 -3
  218. package/http_clients/index.js.map +0 -1
  219. package/index.d.ts.map +0 -1
  220. package/index.js.map +0 -1
  221. package/log.d.ts.map +0 -1
  222. package/log.js.map +0 -1
  223. package/proxy_configuration.d.ts.map +0 -1
  224. package/proxy_configuration.js.map +0 -1
  225. package/request.d.ts.map +0 -1
  226. package/request.js.map +0 -1
  227. package/router.d.ts.map +0 -1
  228. package/router.js.map +0 -1
  229. package/serialization.d.ts.map +0 -1
  230. package/serialization.js.map +0 -1
  231. package/session_pool/consts.d.ts.map +0 -1
  232. package/session_pool/consts.js.map +0 -1
  233. package/session_pool/errors.d.ts.map +0 -1
  234. package/session_pool/errors.js.map +0 -1
  235. package/session_pool/events.d.ts +0 -3
  236. package/session_pool/events.d.ts.map +0 -1
  237. package/session_pool/events.js +0 -3
  238. package/session_pool/events.js.map +0 -1
  239. package/session_pool/index.d.ts.map +0 -1
  240. package/session_pool/index.js.map +0 -1
  241. package/session_pool/session.d.ts.map +0 -1
  242. package/session_pool/session.js.map +0 -1
  243. package/session_pool/session_pool.d.ts.map +0 -1
  244. package/session_pool/session_pool.js.map +0 -1
  245. package/storages/access_checking.d.ts +0 -13
  246. package/storages/access_checking.d.ts.map +0 -1
  247. package/storages/access_checking.js +0 -14
  248. package/storages/access_checking.js.map +0 -1
  249. package/storages/dataset.d.ts.map +0 -1
  250. package/storages/dataset.js.map +0 -1
  251. package/storages/index.d.ts.map +0 -1
  252. package/storages/index.js.map +0 -1
  253. package/storages/key_value_store.d.ts.map +0 -1
  254. package/storages/key_value_store.js.map +0 -1
  255. package/storages/request_list.d.ts.map +0 -1
  256. package/storages/request_list.js.map +0 -1
  257. package/storages/request_provider.d.ts +0 -308
  258. package/storages/request_provider.d.ts.map +0 -1
  259. package/storages/request_provider.js +0 -555
  260. package/storages/request_provider.js.map +0 -1
  261. package/storages/request_queue.d.ts.map +0 -1
  262. package/storages/request_queue.js.map +0 -1
  263. package/storages/request_queue_v2.d.ts +0 -87
  264. package/storages/request_queue_v2.d.ts.map +0 -1
  265. package/storages/request_queue_v2.js +0 -438
  266. package/storages/request_queue_v2.js.map +0 -1
  267. package/storages/sitemap_request_list.d.ts.map +0 -1
  268. package/storages/sitemap_request_list.js.map +0 -1
  269. package/storages/storage_manager.d.ts +0 -58
  270. package/storages/storage_manager.d.ts.map +0 -1
  271. package/storages/storage_manager.js +0 -105
  272. package/storages/storage_manager.js.map +0 -1
  273. package/storages/utils.d.ts.map +0 -1
  274. package/storages/utils.js.map +0 -1
  275. package/tsconfig.build.tsbuildinfo +0 -1
  276. package/typedefs.d.ts.map +0 -1
  277. package/typedefs.js.map +0 -1
  278. package/validators.d.ts.map +0 -1
  279. 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 log from '@apify/log';
7
- import { jsonStringifyExtended } from '@apify/utilities';
3
+ import { tryCancel } from '@apify/timeout';
8
4
  import { Configuration } from '../configuration.js';
9
- import { checkStorageAccess } from './access_checking.js';
10
- import { StorageManager } from './storage_manager.js';
11
- import { purgeDefaultStorages } from './utils.js';
12
- /**
13
- * Helper function to possibly stringify value if options.contentType is not set.
14
- *
15
- * @ignore
16
- */
17
- export const maybeStringify = (value, options) => {
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
- config;
71
+ configuration;
98
72
  id;
99
73
  name;
100
- storageObject;
101
- client;
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, config = Configuration.getGlobalConfig()) {
109
- this.config = config;
110
- this.id = options.id;
111
- this.name = options.name;
112
- this.storageObject = options.storageObject;
113
- this.client = options.client.keyValueStore(this.id);
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
- checkStorageAccess();
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
- const record = await this.client.getRecord(key);
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
- checkStorageAccess();
229
+ tryCancel();
161
230
  ow(key, ow.string.nonEmpty);
162
- return this.client.recordExists(key);
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
- checkStorageAccess();
166
- if (this.cache.has(key)) {
167
- return this.cache.get(key);
238
+ tryCancel();
239
+ if (this.#cache.has(key)) {
240
+ return this.#cache.get(key);
168
241
  }
169
- const value = await this.getValue(key, defaultValue);
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.cache.has(key)) {
175
- return this.cache.get(key);
249
+ if (this.#cache.has(key)) {
250
+ return this.#cache.get(key);
176
251
  }
177
- this.cache.set(key, value);
252
+ this.#cache.set(key, value);
178
253
  this.ensurePersistStateEvent();
179
254
  return value;
180
255
  }
181
256
  ensurePersistStateEvent() {
182
- if (this.persistStateEventStarted) {
257
+ if (this.#persistStateEventStarted) {
183
258
  return;
184
259
  }
185
- // use half the interval of `persistState` to avoid race conditions
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.cache) {
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.persistStateEventStarted = true;
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
- checkStorageAccess();
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
- !(ow.isValid(value, ow.any(ow.string, ow.uint8Array)) ||
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.cache.get(key);
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.cache.delete(k));
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.cache.delete(k));
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
- return this.client.deleteRecord(key);
281
- value = maybeStringify(value, optionsCopy);
282
- return this.client.setRecord({
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: optionsCopy.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
- checkStorageAccess();
297
- await this.client.delete();
298
- const manager = StorageManager.getManager(KeyValueStore, this.config);
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
- checkStorageAccess();
304
- this.cache.clear();
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
- * (regardless of `options.exclusiveStartKey`) and `info` is an object that contains a single property `size`
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
- checkStorageAccess();
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
- exclusiveStartKey: ow.optional.string,
485
+ prefix: ow.optional.string,
336
486
  }));
337
- const response = await this.client.listKeys({ exclusiveStartKey });
338
- const { nextExclusiveStartKey, isTruncated, items } = response;
339
- for (const item of items) {
340
- await iteratee(item.key, index++, { size: item.size });
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
- return isTruncated
343
- ? this._forEachKey(iteratee, { exclusiveStartKey: nextExclusiveStartKey }, index)
344
- : undefined; // [].forEach() returns undefined.
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
- const name = this.name ?? this.config.get('defaultKeyValueStoreId');
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 [storeIdOrName]
363
- * ID or name of the key-value store to be opened. If `null` or `undefined`,
364
- * the function returns the default key-value store associated with the crawler run.
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(storeIdOrName, options = {}) {
368
- checkStorageAccess();
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
- config: ow.optional.object.instanceOf(Configuration),
372
- storageClient: ow.optional.object,
627
+ configuration: ow.optional.object.instanceOf(Configuration),
628
+ storageBackend: ow.optional.object,
373
629
  }));
374
- options.config ??= Configuration.getGlobalConfig();
375
- options.storageClient ??= options.config.getStorageClient();
376
- await purgeDefaultStorages({ onlyPurgeOnce: true, client: options.storageClient, config: options.config });
377
- const manager = StorageManager.getManager(this, options.config);
378
- return manager.openStorage(storeIdOrName, options.storageClient);
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
- * By default, it will try to find root input files (either extension-less, `.json` or `.txt`),
464
- * or alternatively read the input from the default {@link KeyValueStore}.
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
- const inputKey = store.config.get('inputKey');
483
- const cwd = process.cwd();
484
- const possibleExtensions = ['', '.json', '.txt'];
485
- // Attempt to read input from root file instead of key-value store
486
- for (const extension of possibleExtensions) {
487
- const inputFile = join(cwd, `${inputKey}${extension}`);
488
- let input;
489
- // Try getting the file from the file system
490
- try {
491
- input = await readFile(inputFile);
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