@crawlee/core 4.0.0-beta.118 → 4.0.0-beta.119

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/errors.d.ts CHANGED
@@ -14,6 +14,16 @@ export declare class CriticalError extends NonRetryableError {
14
14
  */
15
15
  export declare class MissingRouteError extends CriticalError {
16
16
  }
17
+ /**
18
+ * A schema validation issue, structurally compatible with `StandardSchemaV1.Issue`. Declared here so that
19
+ * error types do not have to depend on `@standard-schema/spec`.
20
+ */
21
+ export interface SchemaIssue {
22
+ readonly message: string;
23
+ readonly path?: readonly (PropertyKey | {
24
+ key: PropertyKey;
25
+ })[];
26
+ }
17
27
  /**
18
28
  * Thrown when a request's `userData` does not match the {@link RouteSchemas|Standard Schema} registered for its label.
19
29
  *
@@ -21,18 +31,19 @@ export declare class MissingRouteError extends CriticalError {
21
31
  */
22
32
  export declare class RequestValidationError extends NonRetryableError {
23
33
  readonly label: string | symbol;
24
- readonly issues: readonly {
25
- readonly message: string;
26
- readonly path?: readonly (PropertyKey | {
27
- key: PropertyKey;
28
- })[];
29
- }[];
30
- constructor(label: string | symbol, issues: readonly {
31
- readonly message: string;
32
- readonly path?: readonly (PropertyKey | {
33
- key: PropertyKey;
34
- })[];
35
- }[]);
34
+ readonly issues: readonly SchemaIssue[];
35
+ constructor(label: string | symbol, issues: readonly SchemaIssue[]);
36
+ }
37
+ /**
38
+ * Thrown by {@link RecoverableState} when a persisted state record does not match its `stateSchema`.
39
+ *
40
+ * Whether a corrupt record should abort the run or be discarded in favour of the defaults depends on what the
41
+ * state is for, so {@link RecoverableState.initialize} always throws and leaves the choice to the caller.
42
+ */
43
+ export declare class StateValidationError extends Error {
44
+ readonly persistStateKey: string;
45
+ readonly issues: readonly SchemaIssue[];
46
+ constructor(persistStateKey: string, issues: readonly SchemaIssue[]);
36
47
  }
37
48
  /**
38
49
  * Errors of `RetryRequestError` type will always be retried by the crawler.
package/errors.js CHANGED
@@ -15,6 +15,16 @@ export class CriticalError extends NonRetryableError {
15
15
  */
16
16
  export class MissingRouteError extends CriticalError {
17
17
  }
18
+ function formatIssues(issues) {
19
+ return issues
20
+ .map((issue) => {
21
+ const path = (issue.path ?? [])
22
+ .map((segment) => (typeof segment === 'object' ? segment.key : segment))
23
+ .join('.');
24
+ return `- ${path ? `${path}: ` : ''}${issue.message}`;
25
+ })
26
+ .join('\n');
27
+ }
18
28
  /**
19
29
  * Thrown when a request's `userData` does not match the {@link RouteSchemas|Standard Schema} registered for its label.
20
30
  *
@@ -24,19 +34,26 @@ export class RequestValidationError extends NonRetryableError {
24
34
  label;
25
35
  issues;
26
36
  constructor(label, issues) {
27
- const details = issues
28
- .map((issue) => {
29
- const path = (issue.path ?? [])
30
- .map((segment) => (typeof segment === 'object' ? segment.key : segment))
31
- .join('.');
32
- return `- ${path ? `${path}: ` : ''}${issue.message}`;
33
- })
34
- .join('\n');
35
- super(`Request userData for label '${String(label)}' failed schema validation:\n${details}`);
37
+ super(`Request userData for label '${String(label)}' failed schema validation:\n${formatIssues(issues)}`);
36
38
  this.label = label;
37
39
  this.issues = issues;
38
40
  }
39
41
  }
42
+ /**
43
+ * Thrown by {@link RecoverableState} when a persisted state record does not match its `stateSchema`.
44
+ *
45
+ * Whether a corrupt record should abort the run or be discarded in favour of the defaults depends on what the
46
+ * state is for, so {@link RecoverableState.initialize} always throws and leaves the choice to the caller.
47
+ */
48
+ export class StateValidationError extends Error {
49
+ persistStateKey;
50
+ issues;
51
+ constructor(persistStateKey, issues) {
52
+ super(`State persisted under key '${persistStateKey}' failed schema validation:\n${formatIssues(issues)}`);
53
+ this.persistStateKey = persistStateKey;
54
+ this.issues = issues;
55
+ }
56
+ }
40
57
  /**
41
58
  * Errors of `RetryRequestError` type will always be retried by the crawler.
42
59
  *
@@ -21,17 +21,13 @@ export declare class MemoryStorageBackend implements storage.StorageBackend {
21
21
  * cache partitions in the storage backend cache.
22
22
  */
23
23
  getStorageBackendCacheKey(): string;
24
- private static resolveStorageKey;
25
24
  createDatasetBackend(options?: storage.StorageIdentifier): Promise<storage.DatasetBackend>;
26
25
  createKeyValueStoreBackend(options?: storage.StorageIdentifier): Promise<storage.KeyValueStoreBackend>;
27
26
  createRequestQueueBackend(options?: storage.StorageIdentifier): Promise<RequestQueueBackend>;
28
27
  storageExists(id: string, type: 'Dataset' | 'KeyValueStore' | 'RequestQueue'): Promise<boolean>;
29
28
  /**
30
- * Cleans up the default storages before the run starts. For the in-memory storage this simply
31
- * resets the in-memory state of the cached default dataset, key-value store and request queue.
32
- *
33
- * As with `FileSystemStorageBackend`, the run's input (the `INPUT` key in the default key-value
34
- * store) is preserved — only the rest of the default storages is cleared.
29
+ * Cleans up the run-scoped storages before the run starts. For the in-memory storage this simply
30
+ * resets the in-memory state of the cached backends.
35
31
  */
36
32
  purge(): Promise<void>;
37
33
  /**
@@ -2,6 +2,8 @@ import { randomUUID } from 'node:crypto';
2
2
  import { DatasetBackend } from './resource-clients/dataset.js';
3
3
  import { KeyValueStoreBackend } from './resource-clients/key-value-store.js';
4
4
  import { RequestQueueBackend } from './resource-clients/request-queue.js';
5
+ /** The alias the default (unnamed) storage is opened under. */
6
+ const DEFAULT_STORAGE_ALIAS = '__default__';
5
7
  export class MemoryStorageBackend {
6
8
  logger;
7
9
  /**
@@ -22,22 +24,24 @@ export class MemoryStorageBackend {
22
24
  getStorageBackendCacheKey() {
23
25
  return this.#instanceCacheKey;
24
26
  }
25
- static resolveStorageKey(options) {
26
- const isAlias = 'alias' in options && !!options.alias;
27
- const rawKey = isAlias ? options.alias : (options.name ?? options.id);
27
+ static #resolveStorageKey(options) {
28
+ // No identifier at all means the default storage, which is opened under the reserved alias
29
+ // same rule as `resolveStorageIdentifier` in the storage frontends, so that a backend used
30
+ // directly lands on the very storage the frontends would have opened.
31
+ const alias = options.alias || (!options.id && !options.name ? DEFAULT_STORAGE_ALIAS : undefined);
32
+ // `alias` covers the identifier-less case, so one of the three is always set.
33
+ const rawKey = alias ?? options.name ?? options.id;
28
34
  // Normalize the internal __default__ alias to the user-facing 'default' name.
29
- const cacheKey = rawKey === '__default__' ? 'default' : rawKey;
30
- return { isAlias, cacheKey };
35
+ const cacheKey = rawKey === DEFAULT_STORAGE_ALIAS ? 'default' : rawKey;
36
+ return { isAlias: alias !== undefined, cacheKey };
31
37
  }
32
38
  async createDatasetBackend(options = {}) {
33
- const { isAlias, cacheKey } = MemoryStorageBackend.resolveStorageKey(options);
34
- if (cacheKey) {
35
- const found = this.datasetBackendCache.find((store) => store.id === cacheKey ||
36
- store.name?.toLowerCase() === cacheKey.toLowerCase() ||
37
- store.cacheKey.toLowerCase() === cacheKey.toLowerCase());
38
- if (found) {
39
- return found;
40
- }
39
+ const { isAlias, cacheKey } = MemoryStorageBackend.#resolveStorageKey(options);
40
+ const found = this.datasetBackendCache.find((store) => store.id === cacheKey ||
41
+ store.name?.toLowerCase() === cacheKey.toLowerCase() ||
42
+ store.cacheKey.toLowerCase() === cacheKey.toLowerCase());
43
+ if (found) {
44
+ return found;
41
45
  }
42
46
  const newStore = new DatasetBackend({
43
47
  name: isAlias ? undefined : cacheKey,
@@ -48,14 +52,12 @@ export class MemoryStorageBackend {
48
52
  return newStore;
49
53
  }
50
54
  async createKeyValueStoreBackend(options = {}) {
51
- const { isAlias, cacheKey } = MemoryStorageBackend.resolveStorageKey(options);
52
- if (cacheKey) {
53
- const found = this.keyValueStoreBackendCache.find((store) => store.id === cacheKey ||
54
- store.name?.toLowerCase() === cacheKey.toLowerCase() ||
55
- store.cacheKey.toLowerCase() === cacheKey.toLowerCase());
56
- if (found) {
57
- return found;
58
- }
55
+ const { isAlias, cacheKey } = MemoryStorageBackend.#resolveStorageKey(options);
56
+ const found = this.keyValueStoreBackendCache.find((store) => store.id === cacheKey ||
57
+ store.name?.toLowerCase() === cacheKey.toLowerCase() ||
58
+ store.cacheKey.toLowerCase() === cacheKey.toLowerCase());
59
+ if (found) {
60
+ return found;
59
61
  }
60
62
  const newStore = new KeyValueStoreBackend({
61
63
  name: isAlias ? undefined : cacheKey,
@@ -66,14 +68,12 @@ export class MemoryStorageBackend {
66
68
  return newStore;
67
69
  }
68
70
  async createRequestQueueBackend(options = {}) {
69
- const { isAlias, cacheKey } = MemoryStorageBackend.resolveStorageKey(options);
70
- if (cacheKey) {
71
- const found = this.requestQueueBackendCache.find((queue) => queue.id === cacheKey ||
72
- queue.name?.toLowerCase() === cacheKey.toLowerCase() ||
73
- queue.cacheKey.toLowerCase() === cacheKey.toLowerCase());
74
- if (found) {
75
- return found;
76
- }
71
+ const { isAlias, cacheKey } = MemoryStorageBackend.#resolveStorageKey(options);
72
+ const found = this.requestQueueBackendCache.find((queue) => queue.id === cacheKey ||
73
+ queue.name?.toLowerCase() === cacheKey.toLowerCase() ||
74
+ queue.cacheKey.toLowerCase() === cacheKey.toLowerCase());
75
+ if (found) {
76
+ return found;
77
77
  }
78
78
  const newStore = new RequestQueueBackend({
79
79
  name: isAlias ? undefined : cacheKey,
@@ -102,28 +102,22 @@ export class MemoryStorageBackend {
102
102
  return backends.some((store) => store.id === id);
103
103
  }
104
104
  /**
105
- * Cleans up the default storages before the run starts. For the in-memory storage this simply
106
- * resets the in-memory state of the cached default dataset, key-value store and request queue.
107
- *
108
- * As with `FileSystemStorageBackend`, the run's input (the `INPUT` key in the default key-value
109
- * store) is preserved — only the rest of the default storages is cleared.
105
+ * Cleans up the run-scoped storages before the run starts. For the in-memory storage this simply
106
+ * resets the in-memory state of the cached backends.
110
107
  */
111
108
  async purge() {
112
- // The run default is opened via `{ alias: '__default__' }`, which `resolveStorageKey`
113
- // normalizes to `cacheKey === 'default'` (with `name === undefined`) that is the clause
114
- // that actually matches it. The `name === 'default'` clause additionally covers a store a user
115
- // explicitly opened via `{ name: 'default' }`. (`'__default__'` never reaches `cacheKey`,
116
- // as it is always normalized to `'default'` first, so it does not need to be checked here.)
109
+ // `#resolveStorageKey` leaves `name` unset for the default and alias-keyed storages, which is what
110
+ // marks them as run-scoped. `'default'` is the exceptionit collapses onto the default storage.
111
+ const isRunScoped = (store) => store.name === undefined || store.name === 'default';
117
112
  const isDefault = (store) => store.name === 'default' || store.cacheKey === 'default';
118
- const purgeDefaults = async (cache, purgeStore) => {
119
- await Promise.all(cache.filter(isDefault).map(async (store) => purgeStore(store)));
113
+ const purgeRunScoped = async (cache, purgeStore) => {
114
+ await Promise.all(cache.filter(isRunScoped).map(async (store) => purgeStore(store)));
120
115
  };
121
116
  await Promise.all([
122
- // Preserve the run input (INPUT) when purging the default key-value store, matching
123
- // `FileSystemStorageBackend`.
124
- purgeDefaults(this.keyValueStoreBackendCache, async (store) => store.purgeExceptInput()),
125
- purgeDefaults(this.datasetBackendCache, async (store) => store.purge()),
126
- purgeDefaults(this.requestQueueBackendCache, async (store) => store.purge()),
117
+ // Only the default store holds the run input, so it is the only one that keeps `INPUT`.
118
+ purgeRunScoped(this.keyValueStoreBackendCache, async (store) => isDefault(store) ? store.purgeExceptInput() : store.purge()),
119
+ purgeRunScoped(this.datasetBackendCache, async (store) => store.purge()),
120
+ purgeRunScoped(this.requestQueueBackendCache, async (store) => store.purge()),
127
121
  ]);
128
122
  }
129
123
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crawlee/core",
3
- "version": "4.0.0-beta.118",
3
+ "version": "4.0.0-beta.119",
4
4
  "description": "The scalable web crawling and scraping library for JavaScript/Node.js. Enables development of data extraction and web automation jobs (not only) with headless Chrome and Puppeteer.",
5
5
  "engines": {
6
6
  "node": ">=22.0.0"
@@ -52,9 +52,9 @@
52
52
  "@apify/log": "^2.5.18",
53
53
  "@apify/timeout": "^0.4.4",
54
54
  "@apify/utilities": "^2.15.5",
55
- "@crawlee/fs-storage": "4.0.0-beta.118",
56
- "@crawlee/types": "4.0.0-beta.118",
57
- "@crawlee/utils": "4.0.0-beta.118",
55
+ "@crawlee/fs-storage": "4.0.0-beta.119",
56
+ "@crawlee/types": "4.0.0-beta.119",
57
+ "@crawlee/utils": "4.0.0-beta.119",
58
58
  "@sapphire/async-queue": "^1.5.5",
59
59
  "@sapphire/shapeshift": "^4.0.0",
60
60
  "@vladfrangu/async_event_emitter": "^2.4.6",
@@ -78,5 +78,5 @@
78
78
  }
79
79
  }
80
80
  },
81
- "gitHead": "7306bd05a126662898a4f2fe7779f6b53425cadf"
81
+ "gitHead": "552fe2371a3c6e9e9f3514010536ea6abdc27eb4"
82
82
  }
@@ -1,4 +1,16 @@
1
1
  import type { Configuration, CrawleeLogger } from '@crawlee/core';
2
+ import { KeyValueStore } from '@crawlee/core';
3
+ import type { Awaitable } from '@crawlee/types';
4
+ import type { StandardSchemaV1 } from '@standard-schema/spec';
5
+ /**
6
+ * One direction of the conversion between the state model and its persisted form - either a plain function, or a
7
+ * [Standard Schema](https://standardschema.dev) whose validated output is the result.
8
+ *
9
+ * A schema that fails to validate makes {@link RecoverableState} throw a {@link StateValidationError}. Zod
10
+ * codecs work directly, as their validation *is* the decode direction; use `(state) => codec.encode(state)` for the
11
+ * other one.
12
+ */
13
+ export type StateConversion<TFrom, TTo> = ((value: TFrom) => Awaitable<TTo>) | StandardSchemaV1<TFrom, TTo>;
2
14
  export interface RecoverableStatePersistenceOptions {
3
15
  /**
4
16
  * The key under which the state is stored in the KeyValueStore
@@ -9,44 +21,45 @@ export interface RecoverableStatePersistenceOptions {
9
21
  */
10
22
  persistenceEnabled?: boolean;
11
23
  /**
12
- * The name of the KeyValueStore to use for persistence.
13
- * If neither a name nor an id are supplied, the default store will be used.
24
+ * The KeyValueStore to persist into, defaulting to the default store. Accepts a pending
25
+ * {@link KeyValueStore.open} so that callers do not have to be async to point at a specific store.
14
26
  */
15
- persistStateKvsName?: string;
27
+ keyValueStore?: KeyValueStore | PromiseLike<KeyValueStore>;
16
28
  /**
17
- * The identifier of the KeyValueStore to use for persistence.
18
- * If neither a name nor an id are supplied, the default store will be used.
29
+ * Time limit for a single load or save of the state, in milliseconds.
30
+ * @default 60_000
19
31
  */
20
- persistStateKvsId?: string;
32
+ persistenceTimeoutMillis?: number;
21
33
  }
22
34
  /**
23
35
  * Options for configuring the RecoverableState
24
36
  */
25
- export interface RecoverableStateOptions<TStateModel = Record<string, unknown>> extends RecoverableStatePersistenceOptions {
37
+ export interface RecoverableStateOptions<TStateModel = Record<string, unknown>, TPersistedState = TStateModel> extends RecoverableStatePersistenceOptions {
26
38
  /**
27
- * The default state used if no persisted state is found.
28
- * A deep copy is made each time the state is used.
39
+ * The state used when no persisted state is found, and the state {@link RecoverableState.reset} restores.
40
+ *
41
+ * A plain value is deep-copied with `structuredClone` each time it is used, so pass a factory for a state
42
+ * that `structuredClone` cannot rebuild - one holding class instances, say, or one derived from a schema.
29
43
  */
30
- defaultState: TStateModel;
44
+ defaultState: TStateModel | (() => TStateModel);
31
45
  /**
32
46
  * A logger instance for logging operations related to state persistence
33
47
  */
34
48
  logger?: CrawleeLogger;
35
49
  /**
36
- * Configuration instance to use
50
+ * Configuration instance to use when opening the KeyValueStore
37
51
  */
38
52
  configuration?: Configuration;
39
53
  /**
40
- * Optional function to transform the state to a JSON string before persistence.
41
- * If not provided, JSON.stringify will be used.
54
+ * Optional conversion of the state to a plain JSON-serializable value before it is persisted.
55
+ * If not provided, the state is persisted as is.
42
56
  */
43
- serialize?: (state: TStateModel) => string;
57
+ serialize?: StateConversion<TStateModel, TPersistedState>;
44
58
  /**
45
- * Optional function to transform a JSON-serialized object back to the state model.
46
- * If not provided, JSON.parse is used.
47
- * It is advisable to perform validation in this function and to throw an exception if it fails.
59
+ * Optional conversion of a persisted value back to the state model, and the place to validate a record before
60
+ * trusting it. If not provided, the persisted value is used as is.
48
61
  */
49
- deserialize?: (serializedState: string) => TStateModel;
62
+ deserialize?: StateConversion<TPersistedState, TStateModel>;
50
63
  }
51
64
  /**
52
65
  * A class for managing persistent recoverable state using a plain JavaScript object.
@@ -58,19 +71,23 @@ export interface RecoverableStateOptions<TStateModel = Record<string, unknown>>
58
71
  * The state is represented by a plain JavaScript object that can be serialized to and deserialized from JSON.
59
72
  * The class automatically hooks into the event system to persist state when needed.
60
73
  */
61
- export declare class RecoverableState<TStateModel = Record<string, unknown>> {
74
+ export declare class RecoverableState<TStateModel = Record<string, unknown>, TPersistedState = TStateModel> {
62
75
  #private;
63
76
  /**
64
77
  * Initialize a new recoverable state object.
65
78
  *
66
79
  * @param options Configuration options for the recoverable state
67
80
  */
68
- constructor(options: RecoverableStateOptions<TStateModel>);
81
+ constructor(options: RecoverableStateOptions<TStateModel, TPersistedState>);
69
82
  /**
70
83
  * Initialize the recoverable state.
71
84
  *
72
- * This method must be called before using the recoverable state. It loads the saved state
73
- * if persistence is enabled and registers the object to listen for PERSIST_STATE events.
85
+ * If persistence is enabled, this method loads the saved state and registers the object to listen for
86
+ * PERSIST_STATE events. A state established beforehand by {@link RecoverableState.reset} survives if there
87
+ * is no record to restore.
88
+ *
89
+ * Calling this again after a {@link RecoverableState.teardown} starts a new persistence window - the
90
+ * listener is registered again and the record reloaded.
74
91
  *
75
92
  * @returns The loaded state object
76
93
  */
@@ -79,33 +96,45 @@ export declare class RecoverableState<TStateModel = Record<string, unknown>> {
79
96
  * Clean up resources used by the recoverable state.
80
97
  *
81
98
  * If persistence is enabled, this method deregisters the object from PERSIST_STATE events
82
- * and persists the current state one last time.
99
+ * and persists the current state one last time, warning rather than throwing if that write fails - cleanup
100
+ * runs when the work is already done, and failing it would bury whatever the caller was doing. The in-memory
101
+ * state is left alone, and {@link RecoverableState.initialize} can be called again to open a new
102
+ * persistence window.
83
103
  */
84
104
  teardown(): Promise<void>;
85
105
  /**
86
106
  * Get the current state.
107
+ *
108
+ * Throws until the state has been established, by either {@link RecoverableState.initialize} or the
109
+ * synchronous {@link RecoverableState.reset} - the latter being how a caller that cannot await in its
110
+ * constructor gets a usable state right away.
87
111
  */
88
112
  get currentValue(): TStateModel;
89
113
  /**
90
- * Reset the state to the default values and clear any persisted state.
114
+ * Reset the in-memory state to the default values, leaving any persisted record alone.
91
115
  *
92
- * Resets the current state to the default state and, if persistence is enabled,
93
- * clears the persisted state from the KeyValueStore.
116
+ * Use {@link RecoverableState.resetStore} to clear the persisted record as well.
94
117
  */
95
- reset(): Promise<void>;
118
+ reset(): void;
119
+ /**
120
+ * Clear the persisted state record, leaving the in-memory state alone.
121
+ *
122
+ * This is a between-lifecycles operation - its point is to stop the next {@link RecoverableState.initialize}
123
+ * from restoring the record, so it throws while PERSIST_STATE events are still being handled, where the next
124
+ * one would write the record straight back. Use {@link RecoverableState.reset} to reset the state itself,
125
+ * or {@link RecoverableState.teardown} before clearing the record.
126
+ *
127
+ * A no-op if persistence is disabled or no KeyValueStore is available yet.
128
+ */
129
+ resetStore(): Promise<void>;
96
130
  /**
97
131
  * Persist the current state to the KeyValueStore.
98
132
  *
99
133
  * This method is typically called in response to a PERSIST_STATE event, but can also be called
100
- * directly when needed.
134
+ * directly when needed. It is a no-op if persistence is disabled, if no KeyValueStore is available yet, or if
135
+ * there is no state to write. A failed write only rejects here - the periodic and teardown ones warn instead.
101
136
  *
102
137
  * @param eventData Optional data associated with a PERSIST_STATE event
103
138
  */
104
- persistState(eventData?: {
105
- isMigrating: boolean;
106
- }): Promise<void>;
107
- /**
108
- * Load the saved state from the KeyValueStore
109
- */
110
- private loadSavedState;
139
+ persistState(eventData?: Record<string, unknown>): Promise<void>;
111
140
  }
@@ -1,4 +1,6 @@
1
- import { EventType, KeyValueStore, serviceLocator } from '@crawlee/core';
1
+ import { addTimeoutToPromise, storage as timeoutStorage } from '@apify/timeout';
2
+ import { EventType, KeyValueStore, serviceLocator, StateValidationError } from '@crawlee/core';
3
+ const DEFAULT_PERSISTENCE_TIMEOUT_MILLIS = 60_000;
2
4
  /**
3
5
  * A class for managing persistent recoverable state using a plain JavaScript object.
4
6
  *
@@ -12,132 +14,199 @@ import { EventType, KeyValueStore, serviceLocator } from '@crawlee/core';
12
14
  export class RecoverableState {
13
15
  #defaultState;
14
16
  #state = null;
17
+ #initialized = false;
18
+ #listening = false;
15
19
  #persistenceEnabled;
16
20
  #persistStateKey;
17
- #persistStateKvsName;
18
- #persistStateKvsId;
19
- #keyValueStore = null;
21
+ #persistenceTimeoutMillis;
22
+ #configuration;
23
+ #keyValueStore;
20
24
  #log;
21
25
  #serialize;
22
26
  #deserialize;
27
+ #persistStateQuietly;
23
28
  /**
24
29
  * Initialize a new recoverable state object.
25
30
  *
26
31
  * @param options Configuration options for the recoverable state
27
32
  */
28
33
  constructor(options) {
29
- this.#defaultState = options.defaultState;
34
+ const { defaultState } = options;
35
+ this.#defaultState =
36
+ typeof defaultState === 'function'
37
+ ? defaultState
38
+ : () => structuredClone(defaultState);
30
39
  this.#persistStateKey = options.persistStateKey;
31
40
  this.#persistenceEnabled = options.persistenceEnabled ?? false;
32
- this.#persistStateKvsName = options.persistStateKvsName;
33
- this.#persistStateKvsId = options.persistStateKvsId;
41
+ this.#persistenceTimeoutMillis = options.persistenceTimeoutMillis ?? DEFAULT_PERSISTENCE_TIMEOUT_MILLIS;
42
+ this.#configuration = options.configuration;
43
+ this.#keyValueStore = options.keyValueStore ?? null;
34
44
  this.#log = options.logger ?? serviceLocator.getLogger().child({ prefix: 'RecoverableState' });
35
- this.#serialize = options.serialize ?? JSON.stringify;
36
- this.#deserialize = options.deserialize ?? JSON.parse;
37
- this.persistState = this.persistState.bind(this);
45
+ this.#serialize = this.#toConversion(options.serialize);
46
+ this.#deserialize = this.#toConversion(options.deserialize);
47
+ // The automatic persists, where a rejection has nowhere useful to go - the event manager does not catch
48
+ // listener errors, and throwing from teardown would bury the outcome of the work it cleans up after.
49
+ this.#persistStateQuietly = async (eventData) => this.persistState(eventData).catch((error) => this.#log.warning(`Failed to persist the state under key '${this.#persistStateKey}'.`, { error }));
50
+ }
51
+ /** Normalizes a conversion option into a function. Absent conversions pass the value through unchanged. */
52
+ #toConversion(conversion) {
53
+ if (conversion === undefined) {
54
+ return async (value) => value;
55
+ }
56
+ if (typeof conversion === 'function') {
57
+ return async (value) => conversion(value);
58
+ }
59
+ return async (value) => {
60
+ const result = await conversion['~standard'].validate(value);
61
+ if (result.issues) {
62
+ throw new StateValidationError(this.#persistStateKey, result.issues);
63
+ }
64
+ return result.value;
65
+ };
38
66
  }
39
67
  /**
40
68
  * Initialize the recoverable state.
41
69
  *
42
- * This method must be called before using the recoverable state. It loads the saved state
43
- * if persistence is enabled and registers the object to listen for PERSIST_STATE events.
70
+ * If persistence is enabled, this method loads the saved state and registers the object to listen for
71
+ * PERSIST_STATE events. A state established beforehand by {@link RecoverableState.reset} survives if there
72
+ * is no record to restore.
73
+ *
74
+ * Calling this again after a {@link RecoverableState.teardown} starts a new persistence window - the
75
+ * listener is registered again and the record reloaded.
44
76
  *
45
77
  * @returns The loaded state object
46
78
  */
47
79
  async initialize() {
48
- if (this.#state !== null && this.#state !== undefined) {
80
+ if (this.#initialized) {
49
81
  return this.currentValue;
50
82
  }
51
- if (!this.#persistenceEnabled) {
52
- this.#state = this.#deserialize(this.#serialize(this.#defaultState));
53
- return this.currentValue;
54
- }
55
- let kvsIdentifier = null;
56
- if (this.#persistStateKvsName) {
57
- kvsIdentifier = { name: this.#persistStateKvsName };
58
- }
59
- else if (this.#persistStateKvsId) {
60
- kvsIdentifier = { id: this.#persistStateKvsId };
83
+ if (this.#persistenceEnabled) {
84
+ this.#keyValueStore ??= KeyValueStore.open(null, {
85
+ configuration: this.#configuration ?? serviceLocator.getConfiguration(),
86
+ });
87
+ await this.#resolveKeyValueStore();
88
+ serviceLocator.getEventManager().on(EventType.PERSIST_STATE, this.#persistStateQuietly);
89
+ this.#listening = true;
61
90
  }
62
- this.#keyValueStore = await KeyValueStore.open(kvsIdentifier, {
63
- configuration: serviceLocator.getConfiguration(),
64
- });
65
- await this.loadSavedState();
66
- // Register for persist state events
67
- const eventManager = serviceLocator.getEventManager();
68
- eventManager.on(EventType.PERSIST_STATE, this.persistState);
91
+ // Flipped before the record is loaded, so that a caller catching a `StateValidationError` is left with a
92
+ // fully wired object running on the default state rather than a half-initialized one.
93
+ this.#initialized = true;
94
+ this.#state ??= this.#defaultState();
95
+ await this.#loadSavedState();
69
96
  return this.currentValue;
70
97
  }
71
98
  /**
72
99
  * Clean up resources used by the recoverable state.
73
100
  *
74
101
  * If persistence is enabled, this method deregisters the object from PERSIST_STATE events
75
- * and persists the current state one last time.
102
+ * and persists the current state one last time, warning rather than throwing if that write fails - cleanup
103
+ * runs when the work is already done, and failing it would bury whatever the caller was doing. The in-memory
104
+ * state is left alone, and {@link RecoverableState.initialize} can be called again to open a new
105
+ * persistence window.
76
106
  */
77
107
  async teardown() {
78
- if (!this.#persistenceEnabled || !this.persistState) {
108
+ this.#initialized = false;
109
+ if (!this.#persistenceEnabled) {
79
110
  return;
80
111
  }
81
- const eventManager = serviceLocator.getEventManager();
82
- eventManager.off(EventType.PERSIST_STATE, this.persistState);
83
- await this.persistState();
112
+ serviceLocator.getEventManager().off(EventType.PERSIST_STATE, this.#persistStateQuietly);
113
+ this.#listening = false;
114
+ await this.#persistStateQuietly();
84
115
  }
85
116
  /**
86
117
  * Get the current state.
118
+ *
119
+ * Throws until the state has been established, by either {@link RecoverableState.initialize} or the
120
+ * synchronous {@link RecoverableState.reset} - the latter being how a caller that cannot await in its
121
+ * constructor gets a usable state right away.
87
122
  */
88
123
  get currentValue() {
89
124
  if (this.#state === null) {
90
- throw new Error('Recoverable state has not yet been loaded');
125
+ throw new Error('Recoverable state has not yet been loaded - call initialize() or reset() first');
91
126
  }
92
127
  return this.#state;
93
128
  }
94
129
  /**
95
- * Reset the state to the default values and clear any persisted state.
130
+ * Reset the in-memory state to the default values, leaving any persisted record alone.
96
131
  *
97
- * Resets the current state to the default state and, if persistence is enabled,
98
- * clears the persisted state from the KeyValueStore.
132
+ * Use {@link RecoverableState.resetStore} to clear the persisted record as well.
99
133
  */
100
- async reset() {
101
- this.#state = this.#deserialize(this.#serialize(this.#defaultState));
102
- if (this.#persistenceEnabled) {
103
- if (this.#keyValueStore === null) {
104
- throw new Error('Recoverable state has not yet been initialized');
105
- }
106
- await this.#keyValueStore.setValue(this.#persistStateKey, null);
134
+ reset() {
135
+ this.#state = this.#defaultState();
136
+ }
137
+ /**
138
+ * Clear the persisted state record, leaving the in-memory state alone.
139
+ *
140
+ * This is a between-lifecycles operation - its point is to stop the next {@link RecoverableState.initialize}
141
+ * from restoring the record, so it throws while PERSIST_STATE events are still being handled, where the next
142
+ * one would write the record straight back. Use {@link RecoverableState.reset} to reset the state itself,
143
+ * or {@link RecoverableState.teardown} before clearing the record.
144
+ *
145
+ * A no-op if persistence is disabled or no KeyValueStore is available yet.
146
+ */
147
+ async resetStore() {
148
+ if (this.#listening) {
149
+ throw new Error(`Cannot clear the state persisted under key '${this.#persistStateKey}' while it is still being persisted periodically - the next PERSIST_STATE event would write it straight back. Use reset() to reset the state itself, or teardown() before clearing the record.`);
150
+ }
151
+ if (!this.#persistenceEnabled) {
152
+ return;
153
+ }
154
+ const keyValueStore = await this.#resolveKeyValueStore();
155
+ if (keyValueStore === null) {
156
+ return;
107
157
  }
158
+ await this.#withTimeout(async () => keyValueStore.setValue(this.#persistStateKey, null), 'Clearing the persisted state');
108
159
  }
109
160
  /**
110
161
  * Persist the current state to the KeyValueStore.
111
162
  *
112
163
  * This method is typically called in response to a PERSIST_STATE event, but can also be called
113
- * directly when needed.
164
+ * directly when needed. It is a no-op if persistence is disabled, if no KeyValueStore is available yet, or if
165
+ * there is no state to write. A failed write only rejects here - the periodic and teardown ones warn instead.
114
166
  *
115
167
  * @param eventData Optional data associated with a PERSIST_STATE event
116
168
  */
117
169
  async persistState(eventData) {
118
- this.#log.debug(`Persisting state of the RecoverableState (eventData=${JSON.stringify(eventData)}).`);
119
- if (this.#keyValueStore === null || this.#state === null) {
120
- throw new Error('Recoverable state has not yet been initialized');
170
+ if (!this.#persistenceEnabled || this.#state === null) {
171
+ return;
121
172
  }
122
- if (this.#persistenceEnabled) {
123
- await this.#keyValueStore.setValue(this.#persistStateKey, this.#serialize(this.#state), {
124
- contentType: 'text/plain', // HACK - the result is expected to be JSON, but we do this to avoid the implicit JSON.parse in `KeyValueStore.getValue`
125
- });
173
+ const keyValueStore = await this.#resolveKeyValueStore();
174
+ if (keyValueStore === null) {
175
+ return;
126
176
  }
177
+ this.#log.debug(`Persisting state of the RecoverableState (eventData=${JSON.stringify(eventData)}).`);
178
+ const serializedState = await this.#serialize(this.currentValue);
179
+ await this.#withTimeout(async () => keyValueStore.setValue(this.#persistStateKey, serializedState), 'Persisting the state');
180
+ }
181
+ /** Awaits a store handed over as a pending `open()`, keeping the resolved instance for later calls. */
182
+ async #resolveKeyValueStore() {
183
+ if (this.#keyValueStore === null) {
184
+ return null;
185
+ }
186
+ this.#keyValueStore = await this.#keyValueStore;
187
+ return this.#keyValueStore;
127
188
  }
128
189
  /**
129
- * Load the saved state from the KeyValueStore
190
+ * Load the saved state from the KeyValueStore. Leaves the current state alone if there is no record to load.
130
191
  */
131
- async loadSavedState() {
132
- if (this.#keyValueStore === null) {
133
- throw new Error('Recoverable state has not yet been initialized');
192
+ async #loadSavedState() {
193
+ if (!this.#persistenceEnabled) {
194
+ return;
134
195
  }
135
- const storedState = await this.#keyValueStore.getValue(this.#persistStateKey);
136
- if (storedState === null || storedState === undefined) {
137
- this.#state = this.#deserialize(this.#serialize(this.#defaultState));
196
+ const keyValueStore = await this.#resolveKeyValueStore();
197
+ if (keyValueStore === null) {
198
+ return;
138
199
  }
139
- else {
140
- this.#state = this.#deserialize(storedState);
200
+ const storedState = await this.#withTimeout(async () => keyValueStore.getValue(this.#persistStateKey), 'Loading the persisted state');
201
+ if (storedState === null || storedState === undefined) {
202
+ return;
141
203
  }
204
+ this.#state = await this.#deserialize(storedState);
205
+ }
206
+ async #withTimeout(operation, description) {
207
+ // `@apify/timeout` shares one `AbortController` across nested frames and `KeyValueStore` checks it on
208
+ // every operation, so a teardown-time persist running inside an already-expired request handler timeout
209
+ // would be aborted before it started. Hence a fresh timeout context.
210
+ return timeoutStorage.exit(async () => addTimeoutToPromise(operation, this.#persistenceTimeoutMillis, `${description} under key '${this.#persistStateKey}' timed out after ${this.#persistenceTimeoutMillis / 1000} seconds.`));
142
211
  }
143
212
  }
@@ -66,7 +66,7 @@ export interface ThrottlingRequestManagerOptions<T extends IRequestManager = IRe
66
66
  *
67
67
  * A domain that keeps answering 429 for this long is not going to be crawled by waiting longer - the
68
68
  * concurrency is too high for it, or it has blocked us outright. Its requests are deliberately left in
69
- * their queue, so re-running the crawl without purging storages picks them up once the domain recovers.
69
+ * their queue, so re-running the crawl with `purgeOnStart` disabled picks them up once the domain recovers.
70
70
  *
71
71
  * A crawler running with `keepAlive` is exempt - outliving a domain that will not let us through is the
72
72
  * whole point there.
@@ -119,9 +119,9 @@ export declare class ThrottlingRequestManager<T extends IRequestManager = IReque
119
119
  private readonly subManagers;
120
120
  private readonly log;
121
121
  /**
122
- * Sub-managers are keyed by a stable alias, so they outlive the process. They must therefore be reopened
123
- * for every configured domain rather than created on first insert - otherwise a restart sees an empty map,
124
- * reports the crawl finished, and strands whatever the previous run left in them.
122
+ * Sub-managers are keyed by a stable alias, so with `purgeOnStart` disabled they outlive the process. They
123
+ * must therefore be reopened for every configured domain rather than created on first insert - otherwise a
124
+ * restart sees an empty map, reports the crawl finished, and strands whatever the previous run left in them.
125
125
  */
126
126
  private subManagersReady?;
127
127
  /** Batches still being added in the background; keeps {@link ThrottlingRequestManager.isFinished} honest. */
@@ -62,9 +62,9 @@ export class ThrottlingRequestManager {
62
62
  subManagers = new Map();
63
63
  log;
64
64
  /**
65
- * Sub-managers are keyed by a stable alias, so they outlive the process. They must therefore be reopened
66
- * for every configured domain rather than created on first insert - otherwise a restart sees an empty map,
67
- * reports the crawl finished, and strands whatever the previous run left in them.
65
+ * Sub-managers are keyed by a stable alias, so with `purgeOnStart` disabled they outlive the process. They
66
+ * must therefore be reopened for every configured domain rather than created on first insert - otherwise a
67
+ * restart sees an empty map, reports the crawl finished, and strands whatever the previous run left in them.
68
68
  */
69
69
  subManagersReady;
70
70
  /** Batches still being added in the background; keeps {@link ThrottlingRequestManager.isFinished} honest. */
@@ -14,7 +14,8 @@ interface PurgeDefaultStorageOptions {
14
14
  }
15
15
  /**
16
16
  * Cleans up the local storage folder (defaults to `./storage`) created when running code locally.
17
- * Purging will remove all the files in all storages except for INPUT.json in the default KV store.
17
+ * Purging empties the storages that belong to a single run the default one and every alias-keyed one —
18
+ * keeping only INPUT.json in the default KV store. Named storages persist across runs and are not touched.
18
19
  *
19
20
  * Purging of storages is happening automatically when we run our crawler (or when we open some storage
20
21
  * explicitly, e.g. via `RequestList.open()`). We can disable that via `purgeOnStart` {@link Configuration}
@@ -28,7 +29,8 @@ interface PurgeDefaultStorageOptions {
28
29
  export declare function purgeDefaultStorages(options?: PurgeDefaultStorageOptions): Promise<void>;
29
30
  /**
30
31
  * Cleans up the local storage folder (defaults to `./storage`) created when running code locally.
31
- * Purging will remove all the files in all storages except for INPUT.json in the default KV store.
32
+ * Purging empties the storages that belong to a single run the default one and every alias-keyed one —
33
+ * keeping only INPUT.json in the default KV store. Named storages persist across runs and are not touched.
32
34
  *
33
35
  * Purging of storages is happening automatically when we run our crawler (or when we open some storage
34
36
  * explicitly, e.g. via `RequestList.open()`). We can disable that via `purgeOnStart` {@link Configuration}