Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.
TypeScript apifyautomationcrawlercrawlingheadlessheadless-chromejavascriptnodejsnpmplaywrightpuppeteerscraperscrapingtypescriptweb-crawlerweb-crawlingweb-scraping
feat: Fully-fledged support for custom (de)serializers in RecoverableState (#4131)
Jan Buchard9c57223413b
diff --git a/docs/public-api/crawlee-core.api.md b/docs/public-api/crawlee-core.api.mdindex 1e7295c88..e44dfa09d 100644--- a/docs/public-api/crawlee-core.api.md+++ b/docs/public-api/crawlee-core.api.md@@ -680,14 +680,20 @@ export class RecoverableState<TStateModel = Record<string, unknown>, TPersistedS}// @public-export interface RecoverableStateOptions<TStateModel = Record<string, unknown>, TPersistedState = TStateModel> extends RecoverableStatePersistenceOptions {+export interface RecoverableStateBaseOptions<TStateModel = Record<string, unknown>, TPersistedState = TStateModel> extends RecoverableStatePersistenceOptions {configuration?: Configuration;+ contentType?: string;defaultState: TStateModel | (() => TStateModel);deserialize?: StateConversion<TPersistedState, TStateModel>;logger?: CrawleeLogger;serialize?: StateConversion<TStateModel, TPersistedState>;}+// @public+export type RecoverableStateOptions<TStateModel = Record<string, unknown>, TPersistedState = TStateModel> = RecoverableStateBaseOptions<TStateModel, TPersistedState> & ({+ contentType?: undefined;+} | Required<Pick<RecoverableStateBaseOptions<TStateModel, TPersistedState>, 'serialize' | 'deserialize' | 'contentType'>>);+// @public (undocumented)export interface RecoverableStatePersistenceOptions {keyValueStore?: KeyValueStore | PromiseLike<KeyValueStore>;diff --git a/packages/core/src/recoverable_state.ts b/packages/core/src/recoverable_state.tsindex b8f2f5b19..f177f30fa 100644--- a/packages/core/src/recoverable_state.ts+++ b/packages/core/src/recoverable_state.ts@@ -1,3 +1,5 @@+import { Readable } from 'node:stream';+import { addTimeoutToPromise, storage as timeoutStorage } from '@apify/timeout';import type { Configuration } from './configuration.js';import { StateValidationError } from './errors.js';@@ -84,9 +86,9 @@ export interface RecoverableStatePersistenceOptions {}/**- * Options for configuring the RecoverableState+ * The fields of {@apilink RecoverableStateOptions}, without the constraint tying `contentType` to the conversions.*/-export interface RecoverableStateOptions<+export interface RecoverableStateBaseOptions<TStateModel = Record<string, unknown>,TPersistedState = TStateModel,> extends RecoverableStatePersistenceOptions {@@ -111,16 +113,48 @@ export interface RecoverableStateOptions</*** Optional conversion of the state to a plain JSON-serializable value before it is persisted.* If not provided, the state is persisted as is.+ *+ * With {@apilink RecoverableStateBaseOptions.contentType} set, it has to produce what+ * {@apilink KeyValueStore.setValue} accepts alongside an explicit content type - a `string`, a `Buffer` or a+ * stream.*/serialize?: StateConversion<TStateModel, TPersistedState>;/*** Optional conversion of a persisted value back to the state model, and the place to validate a record before* trusting it. If not provided, the persisted value is used as is.+ *+ * With {@apilink RecoverableStateBaseOptions.contentType} set, it receives a `Readable` of the record bytes+ * instead of a parsed value.*/deserialize?: StateConversion<TPersistedState, TStateModel>;++ /**+ * Content type of the persisted record. Setting it hands the record encoding over to+ * {@apilink RecoverableStateBaseOptions.serialize} and {@apilink RecoverableStateBaseOptions.deserialize}, both of+ * which are then required - the default JSON codec is bypassed in both directions. Meant for a state too large+ * for `JSON.stringify`, which `serialize` can then stream out instead.+ */+ contentType?: string;}+/**+ * Options for configuring the RecoverableState+ */+export type RecoverableStateOptions<+ TStateModel = Record<string, unknown>,+ TPersistedState = TStateModel,+> = RecoverableStateBaseOptions<TStateModel, TPersistedState> &+ (+ | { contentType?: undefined }+ | Required<+ Pick<+ RecoverableStateBaseOptions<TStateModel, TPersistedState>,+ 'serialize' | 'deserialize' | 'contentType'+ >+ >+ );+/*** A class for managing persistent recoverable state using a plain JavaScript object.*@@ -145,6 +179,7 @@ export class RecoverableState<TStateModel = Record<string, unknown>, TPersistedSreadonly #log: CrawleeLogger;readonly #serialize: (state: TStateModel) => Promise<TPersistedState>;readonly #deserialize: (persistedState: TPersistedState) => Promise<TStateModel>;+ readonly #contentType?: string;readonly #persistStateQuietly: (eventData?: Record<string, unknown>) => Promise<void>;/**@@ -165,6 +200,14 @@ export class RecoverableState<TStateModel = Record<string, unknown>, TPersistedSthis.#configuration = options.configuration;this.#keyValueStore = options.keyValueStore ?? null;this.#log = options.logger ?? serviceLocator.getLogger().child({ prefix: 'RecoverableState' });+ this.#contentType = options.contentType;++ if (this.#contentType !== undefined && (options.serialize === undefined || options.deserialize === undefined)) {+ throw new Error(+ `A 'contentType' for the state persisted under key '${this.#persistStateKey}' requires both 'serialize' and 'deserialize' - the record is no longer JSON the default codec can handle.`,+ );+ }+this.#serialize = this.#toConversion(options.serialize);this.#deserialize = this.#toConversion(options.deserialize);@@ -340,7 +383,12 @@ export class RecoverableState<TStateModel = Record<string, unknown>, TPersistedSconst serializedState = await this.#serialize(this.currentValue);await this.#withTimeout(- async () => keyValueStore.setValue(this.#persistStateKey, serializedState),+ async () =>+ this.#contentType === undefined+ ? keyValueStore.setValue(this.#persistStateKey, serializedState)+ : keyValueStore.setValue(this.#persistStateKey, serializedState, {+ contentType: this.#contentType,+ }),'Persisting the state',);}@@ -379,10 +427,21 @@ export class RecoverableState<TStateModel = Record<string, unknown>, TPersistedSreturn;}- const storedState = await this.#withTimeout(- async () => keyValueStore.getValue(this.#persistStateKey),- 'Loading the persisted state',- );+ // With a content type, the record is whatever `serialize` produced, so the codec's parse is skipped and+ // `deserialize` gets the bytes as a stream - the shape a streaming parser wants.+ // TODO: read the record as a stream instead of buffering it and wrapping (https://github.com/apify/crawlee/issues/2929).+ const storedState = await this.#withTimeout(async () => {+ if (this.#contentType === undefined) {+ return keyValueStore.getValue(this.#persistStateKey);+ }++ const record = await keyValueStore.getRecord(this.#persistStateKey);+ if (record === null) {+ return null;+ }++ return Readable.from(Buffer.isBuffer(record.value) ? record.value : Buffer.from(record.value));+ }, 'Loading the persisted state');if (storedState === null || storedState === undefined) {return;diff --git a/test/core/recoverable_state.test.ts b/test/core/recoverable_state.test.tsindex 4d165ab75..dae193811 100644--- a/test/core/recoverable_state.test.ts+++ b/test/core/recoverable_state.test.ts@@ -1,3 +1,5 @@+import { Readable } from 'node:stream';+import { text } from 'node:stream/consumers';import { setTimeout as sleep } from 'node:timers/promises';import { beforeEach, describe, expect, test, vi } from 'vitest';@@ -344,6 +346,51 @@ describe('RecoverableState', () => {expect(restored.currentValue.data.value).toBe('updated');});+ test('should hand the record encoding over to the conversions when a contentType is set', async () => {+ // Streams both ways: the point of the option is a state too large for a single string.+ const serialize = vi.fn((state: TestState) => Readable.from([Buffer.from(JSON.stringify(state))]));+ const deserialize = vi.fn(async (bytes: Readable): Promise<TestState> => JSON.parse(await text(bytes)));++ const build = () =>+ new RecoverableState<TestState, Readable>({+ defaultState,+ persistStateKey: 'test-key',+ persistenceEnabled: true,+ contentType: 'application/json; charset=utf-8',+ serialize,+ deserialize,+ });++ const recoverableState = build();+ await recoverableState.initialize();+ recoverableState.currentValue.counter = 42;+ await recoverableState.persistState();++ const record = await (await KeyValueStore.open()).getRecord('test-key');+ expect(record?.contentType).toBe('application/json; charset=utf-8');++ const restored = build();+ await restored.initialize();++ expect(deserialize).toHaveBeenCalledWith(expect.any(Readable));+ expect(restored.currentValue).toEqual({ ...defaultState, counter: 42 });+ });++ test('should refuse a contentType without both conversions', () => {+ const options = {+ defaultState,+ persistStateKey: 'test-key',+ persistenceEnabled: true,+ contentType: 'text/plain',+ };++ // The types reject both; the runtime check is for callers that get past them.+ // @ts-expect-error+ expect(() => new RecoverableState({ ...options, serialize: JSON.stringify })).toThrow(/'deserialize'/);+ // @ts-expect-error+ expect(() => new RecoverableState({ ...options, deserialize: JSON.parse })).toThrow(/'serialize'/);+ });+test('should call a defaultState factory afresh for every reset', async () => {const defaultStateFactory = vi.fn(() => ({ items: new Map([['a', 1]]) }));