Skip to content

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.

refactor!: Rewrite the FilesystemStorageClient to use apify/crawlee-storage (#3762)

Jan Buchar2944b32a84e9
diff --git a/REBASE-DEFERRED.md b/REBASE-DEFERRED.md
index c46b0cb26..78198a37d 100644
--- a/REBASE-DEFERRED.md
+++ b/REBASE-DEFERRED.md
@@ -441,3 +441,31 @@ no longer exists. The equivalent already-migrated test in
`packages/fs-storage/test/request-queue/handledRequestCount-should-update.test.ts`
(from an earlier commit in this same rebase) had already dropped this exact
test for the same reason — did the same here for consistency.
+
+**Commit `8a422628f` (Rewrite the FilesystemStorageClient to use
+apify/crawlee-storage) — took theirs' side wholesale, dropping my manual
+path-traversal hardening in `@crawlee/fs-storage`**: this commit replaces the
+entire hand-rolled TypeScript filesystem implementation (`cache-helpers.ts`,
+`fs/key-value-store/fs.ts`, and the dataset/kvs/request-queue resource
+clients) with thin adapters around a native Rust extension
+(`@crawlee/fs-storage-native`). `cache-helpers.ts` and `fs/key-value-store/fs.ts`
+are deleted outright — accepted the deletion (`git rm`) since their
+responsibilities (directory resolution, path safety, file I/O) move into the
+native library. For the resource-client content conflicts
+(`dataset.ts`/`key-value-store.ts`/`request-queue.ts`/`utils.ts`), took theirs
+wholesale rather than re-porting the `resolveWithinDirectory` hardening
+(documented earlier in this log, under the `a9b972294` and `39f689f33`
+entries) — checked `v4-reverse` first per the established practice for
+architecture-level collisions, and its equivalent files (a later rename to
+`DatasetBackend`/`FileSystemStorageBackend` etc., but structurally identical)
+also drop the manual TS-level hardening entirely, confirming the native
+package is expected to own path safety internally rather than the TS adapter
+layer re-implementing it.
+
+**Follow-up needed once the rebase is done**: I have not verified that
+`@crawlee/fs-storage-native` actually rejects path-traversal storage
+names/record keys the way `resolveWithinDirectory` did. This should be
+checked directly (either by reading the native crate's source if vendored, or
+by a quick escape-attempt test against the new `FileSystemStorageClient`)
+before considering the `a04c29766` security fix's guarantees intact
+post-rewrite.
diff --git a/docs/guides/parallel-scraping/parallel-scraper.mjs b/docs/guides/parallel-scraping/parallel-scraper.mjs
index 78162002c..08683a4a4 100644
--- a/docs/guides/parallel-scraping/parallel-scraper.mjs
+++ b/docs/guides/parallel-scraping/parallel-scraper.mjs
@@ -1,5 +1,6 @@
import { fork } from 'node:child_process';
+import { FileSystemStorageClient } from '@crawlee/fs-storage';
import { Configuration, Dataset, PlaywrightCrawler, log } from 'crawlee';
import { router } from './routes.mjs';
@@ -76,13 +77,18 @@ if (!process.env.IN_WORKER_THREAD) {
// Get the request queue
const requestQueue = await getOrInitQueue(false);
- // Disable the automatic purge on start and configure crawlee to store the worker-specific data in a separate directory
- // (needs to be done AFTER the queue is initialized when running locally)
+ // Disable the automatic purge on start, so we don't lose the queue we prepared
const config = new Configuration({
purgeOnStart: false,
- storageClientOptions: {
- localDataDirectory: `./storage/worker-${process.env.WORKER_INDEX}`,
- },
+ });
+
+ // Store the worker's own internal state (its default dataset, key-value store, etc.) in a separate
+ // directory so the workers don't collide with each other. This directory is private to a single
+ // worker, so we set `requestQueueAccess: 'single'` — the concurrency-safe locking only matters for
+ // the shared `shop-urls` queue, which gets its own storage client in `requestQueue.mjs`.
+ const storageClient = new FileSystemStorageClient({
+ localDataDirectory: `./storage/worker-${process.env.WORKER_INDEX}`,
+ requestQueueAccess: 'single',
});
workerLogger.debug('Setting up crawler.');
@@ -98,6 +104,10 @@ if (!process.env.IN_WORKER_THREAD) {
// highlight-end
// Let's also limit the crawler's concurrency, we don't want to overload a single process 🐌
maxConcurrency: 5,
+ // Use the worker-specific, concurrency-safe storage client we created above
+ // highlight-start
+ storageClient,
+ // highlight-end
},
config,
);
diff --git a/docs/guides/parallel-scraping/parallel-scraping.mdx b/docs/guides/parallel-scraping/parallel-scraping.mdx
index a22284a6f..ca7cc571e 100644
--- a/docs/guides/parallel-scraping/parallel-scraping.mdx
+++ b/docs/guides/parallel-scraping/parallel-scraping.mdx
@@ -60,6 +60,16 @@ The first step in our conversion process will be creating a common file (let's c
The exported function, `getOrInitQueue`, might seem like it does a lot. In essence, it just ensures the request queue is initialized, and if requested, ensures it starts off with an empty state.
+:::caution Make the shared queue concurrency-safe with `requestQueueAccess: 'shared'`
+
+Because every worker process opens this same `shop-urls` queue at the same time, it **must** use the concurrency-safe locking behavior of `FileSystemStorageClient`. That's why `getOrInitQueue` opens the queue with a storage client constructed with `requestQueueAccess: 'shared'`.
+
+By default, `FileSystemStorageClient` assumes it is the *sole* consumer of a queue (`requestQueueAccess: 'single'`). On open it immediately reclaims any requests left *in progress* — great for a single-process crawl recovering after a crash, but disastrous when workers run side by side: each worker would happily grab requests another worker is still processing, so the same URL gets scraped multiple times.
+
+Setting `requestQueueAccess: 'shared'` tells the client to treat an in-progress request as a potential live peer's lock and only reclaim it once the lock expires on the wall clock, so two workers never process the same request at once.
+
+:::
+
### Adapting our previous scraper to enqueue the product URLs to the new queue
In the `src/routes.mjs` file of the scraper we previously built, we have a handler for the `CATEGORY` label. Let's adapt that handler to enqueue the product URLs to the new queue we created.
@@ -122,34 +132,44 @@ This will check how the script is executed as. If this value has _any_ value, it
We use this to ensure the parent process stays alive until all the worker processes exit. Otherwise, the worker processes would just get spawned, and lose the ability to communicate with the parent. You might not need this depending on your use case (maybe you just need to spawn workers and let them process).
-#### What's with all those `Configuration` calls?
+#### What's with all the `Configuration` and storage client setup?
-There are three steps we want to do for the worker processes:
+There are two things we want to do for the worker processes:
-- get the queue that supports locking from the same location as the parent process
-- ensure the default storages do **not** get purged on start, as otherwise we'd lose the queue we prepared, and initialize a special storage for worker processes so they do not collide with each other
+- get the shared queue from the same location as the parent process (it already comes with the concurrency-safe storage client we set up in `requestQueue.mjs`)
+- ensure the default storages do **not** get purged on start, as otherwise we'd lose the queue we prepared, and give each worker its own private storage directory for its internal state so the workers don't collide with each other
In order, that's what these lines do:
```javascript title="src/parallel-scraper.mjs"
-// Get the request queue from the parent process (step 1)
+import { FileSystemStorageClient } from '@crawlee/fs-storage';
+
+// Get the shared request queue from the parent process (step 1)
const requestQueue = await getOrInitQueue(false);
-// Disable the automatic purge on start and configure crawlee to store the worker-specific data
-// in a separate directory (needs to be done AFTER the queue is initialized when running locally) (step 2)
-const config = new Configuration({
- purgeOnStart: false,
- storageClientOptions: {
- localDataDirectory: `./storage/worker-${process.env.WORKER_INDEX}`,
- },
+// Disable the automatic purge on start, so we don't lose the queue we prepared (step 2)
+const config = new Configuration({ purgeOnStart: false });
+
+// Store the worker's own internal state in a separate directory so workers don't collide (step 2,
+// cont.). This directory is private to a single worker, so we explicitly set
+// `requestQueueAccess: 'single'`.
+const storageClient = new FileSystemStorageClient({
+ localDataDirectory: `./storage/worker-${process.env.WORKER_INDEX}`,
+ requestQueueAccess: 'single',
});
```
+:::note Why no `requestQueueAccess: 'shared'` here?
+
+Each worker's `./storage/worker-N` directory is private to that single worker — nothing else opens it — so the default `requestQueueAccess: 'single'` is exactly right. The concurrency-safe locking only matters for storage that is genuinely shared across processes, which is the `shop-urls` queue in `requestQueue.mjs`, not this per-worker internal state.
+
+:::
+
#### Telling the crawler to use the worker configuration
You might have noticed several lines highlighted in the code above. Those show how you provide the shared request queue to the crawler.
-You might have also noticed we passed in a second parameter to the constructor of the crawler, the `config` variable we created earlier. This is needed to ensure the crawler uses the worker-specific storages for internal states, and that they do not collide with each other.
+You might have also noticed we passed in the `config` and `storageClient` we created earlier to the crawler. These ensure the crawler uses the worker-specific storages for its own internal state (so the workers do not collide with each other), while still consuming the shared, concurrency-safe `shop-urls` queue we provided explicitly.
#### Why do we use `process.send` instead of `context.pushData`?
diff --git a/docs/guides/parallel-scraping/shared.mjs b/docs/guides/parallel-scraping/shared.mjs
index 0233e37fa..573f97481 100644
--- a/docs/guides/parallel-scraping/shared.mjs
+++ b/docs/guides/parallel-scraping/shared.mjs
@@ -1,8 +1,19 @@
+import { FileSystemStorageClient } from '@crawlee/fs-storage';
import { RequestQueue } from 'crawlee';
// The request queue shared by all the parallel workers
let queue;
+// The `shop-urls` queue is opened concurrently by every worker process, so it must use the
+// concurrency-safe locking behavior. With `requestQueueAccess: 'shared'`, a request another worker
+// is still processing is treated as a live peer's lock and is not handed out again until that lock
+// expires — so two workers never scrape the same URL at once. (We point at the `./storage`
+// location, which is where this shared queue lives.)
+const sharedStorageClient = new FileSystemStorageClient({
+ localDataDirectory: './storage',
+ requestQueueAccess: 'shared',
+});
+
/**
* @param {boolean} makeFresh Whether the queue should be cleared before returning it
* @returns The queue
@@ -12,11 +23,11 @@ export async function getOrInitQueue(makeFresh = false) {
return queue;
}
- queue = await RequestQueue.open('shop-urls');
+ queue = await RequestQueue.open('shop-urls', { storageClient: sharedStorageClient });
if (makeFresh) {
await queue.drop();
- queue = await RequestQueue.open('shop-urls');
+ queue = await RequestQueue.open('shop-urls', { storageClient: sharedStorageClient });
}
return queue;
diff --git a/docs/public-api/crawlee-core.api.md b/docs/public-api/crawlee-core.api.md
index 812b33e80..843cbc2f2 100644
--- a/docs/public-api/crawlee-core.api.md
+++ b/docs/public-api/crawlee-core.api.md
@@ -294,6 +294,7 @@ export const crawleeConfigFields: {
disableBrowserSandbox: ConfigField<z.ZodDefault<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodBoolean>>>;
logLevel: ConfigField<z.ZodOptional<z.ZodPipe<z.ZodTransform<{} | null | undefined, unknown>, z.ZodEnum<typeof LogLevel>>>>;
persistStorage: ConfigField<z.ZodDefault<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodBoolean>>>;
+ storageDir: ConfigField<z.ZodDefault<z.ZodString>>;
containerized: ConfigField<z.ZodOptional<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodBoolean>>>;
};
diff --git a/docs/public-api/crawlee-fs-storage.api.md b/docs/public-api/crawlee-fs-storage.api.md
index f5d0c539d..67745a529 100644
--- a/docs/public-api/crawlee-fs-storage.api.md
+++ b/docs/public-api/crawlee-fs-storage.api.md
@@ -6,11 +6,14 @@
import type { CrawleeLogger } from '@crawlee/types';
import type { Dictionary } from '@crawlee/types';
+import type { FileSystemDatasetClient } from '@crawlee/fs-storage-native';
+import type { FileSystemKeyValueStoreClient } from '@crawlee/fs-storage-native';
+import type { FileSystemRequestQueueClient } from '@crawlee/fs-storage-native';
import type * as storage from '@crawlee/types';
-// @public (undocumented)
+// @public
export class FileSystemStorageClient implements storage.StorageClient {
- constructor(options?: FileSystemStorageOptions);
+ constructor(options: FileSystemStorageOptions);
// (undocumented)
createDatasetClient(options?: storage.CreateDatasetClientOptions): Promise<storage.DatasetClient>;
// (undocumented)
@@ -32,6 +35,8 @@ export class FileSystemStorageClient implements storage.StorageClient {
readonly logger?: CrawleeLogger;
purge(): Promise<void>;
// (undocumented)
+ readonly requestQueueAccess: 'single' | 'shared';
+ // (undocumented)
readonly requestQueueCache: RequestQueueClient[];
// (undocumented)
readonly requestQueuesDirectory: string;
@@ -40,15 +45,13 @@ export class FileSystemStorageClient implements storage.StorageClient {
// (undocumented)
storageExists(id: string, type: 'Dataset' | 'KeyValueStore' | 'RequestQueue'): Promise<boolean>;
teardown(): Promise<void>;
- // (undocumented)
- readonly writeMetadata: boolean;
}
// @public (undocumented)
export interface FileSystemStorageOptions {
- localDataDirectory?: string;
+ localDataDirectory: string;
logger?: CrawleeLogger;
- writeMetadata?: boolean;
+ requestQueueAccess?: 'single' | 'shared';
}
// (No @packageDocumentation comment for this package)
diff --git a/docs/upgrading/upgrading_v4.md b/docs/upgrading/upgrading_v4.md
index 8468bb54e..a1ed70767 100644
--- a/docs/upgrading/upgrading_v4.md
+++ b/docs/upgrading/upgrading_v4.md
@@ -687,18 +687,41 @@ import { FileSystemStorageClient } from '@crawlee/fs-storage';
import { MemoryStorageClient } from '@crawlee/core';
// Persists to disk (the old default behavior):
-const storageClient = new FileSystemStorageClient();
+const storageClient = new FileSystemStorageClient({ localDataDirectory: './storage' });
// Or keep everything in memory only (the old `persistStorage: false`):
const inMemory = new MemoryStorageClient();
```
-The `localDataDirectory`, `persistStorage`, and `writeMetadata` options are still accepted by `MemoryStorageClient` for source compatibility, but they are ignored — in-memory storage has nowhere to write. `FileSystemStorageClient` honors `localDataDirectory` and `writeMetadata`; it always persists, so it has no `persistStorage` option.
+`MemoryStorageClient` no longer takes the `localDataDirectory`, `persistStorage`, or `writeMetadata` options — in-memory storage has nowhere to write, so they had no meaning. `FileSystemStorageClient` honors `localDataDirectory`; it always persists, so it has no `persistStorage` option, and the `writeMetadata` option has been removed there too (see [`writeMetadata` option removed](#writemetadata-option-removed)).
### No request lock expiry in `MemoryStorageClient`
Because the in-memory queue lives entirely within a single process and is never shared with another consumer, `MemoryStorageClient`'s request queue no longer uses an expiring, cross-process lock. A fetched request simply stays *in progress* until it is handled or reclaimed; it never becomes fetchable again on its own after a timeout. `setExpectedRequestProcessingTimeSecs()` is therefore a no-op for in-memory storage. (Disk-backed `FileSystemStorageClient` keeps the lock-with-expiry behavior.)
+### `writeMetadata` option removed
+
+`FileSystemStorageClient` no longer accepts the `writeMetadata` option. The underlying file-system storage now always writes metadata files (`__metadata__.json` for each storage and a `<key>.__metadata__.json` sidecar for each key-value record), so the toggle no longer had any effect. Remove it from your storage client options:
+
+```diff
+ import { FileSystemStorageClient } from '@crawlee/fs-storage';
+
+ const storageClient = new FileSystemStorageClient({
+ localDataDirectory: './storage',
+- writeMetadata: true,
+ });
+```
+
+`MemoryStorageClient` never accepted `writeMetadata` (it has no on-disk format to begin with), so there is nothing to change there.
+
+### Out-of-band key-value files (e.g. a hand-placed `INPUT.json`)
+
+`FileSystemStorageClient` only fully tracks records it wrote itself (those have a `<key>.__metadata__.json` sidecar). It still reads a value file placed in the store directory out-of-band — such as a hand-written or platform-provided `INPUT.json` — by probing the requested key plus the `.json` and `.txt` extensions. A few behaviors around these "bare" files changed in v4:
+
+- **Extensionless bare files report `application/octet-stream`.** In v3 a bare value file with no extension was read as `text/plain`. In v4 the client is a plain byte transport and only infers a content type from a real extension, so an extensionless file now comes back as `application/octet-stream`. Give the file a `.json` or `.txt` extension if you need a more specific type.
+- **Malformed bare files are no longer silently swallowed.** In v3 a bare `INPUT.json` containing invalid JSON was treated as a missing record (`getValue` returned `undefined`). In v4 the raw bytes are returned verbatim and parsing happens in the `KeyValueStore` frontend, so a malformed value now surfaces a parse error at read time instead of looking absent.
+- **Bare files are enumerated by `listKeys` under their actual on-disk name.** A bare `INPUT.json` (or `.txt`/`.bin`) shows up in `listKeys` as `INPUT.json` and reads back cleanly under that key via `getValue` / `recordExists` / `getPublicUrl`; the logical `INPUT` lookup keeps resolving the same file as well. An extensionless bare file is listed as `INPUT`. If both a tracked `INPUT` record and a bare `INPUT.json` exist, the tracked record wins and the bare variant is not listed. Everything `listKeys` needs is read from the filesystem index, so this no longer triggers the per-read O(n) directory scans the v3 fallback performed.
+
## Multiple crawler instances use separate default request queues
In v3, every `BasicCrawler` (or subclass) that didn't receive an explicit `requestQueue` option would open the same default request queue. If you created two crawlers in the same process, they would silently share a queue — leading to request collisions and hard-to-debug deduplication issues.
diff --git a/packages/core/src/configuration.ts b/packages/core/src/configuration.ts
index fa2e275a7..88358785a 100644
--- a/packages/core/src/configuration.ts
+++ b/packages/core/src/configuration.ts
@@ -82,6 +82,8 @@ export const crawleeConfigFields = {
logLevel: field(logLevelSchema.optional(), 'CRAWLEE_LOG_LEVEL'),
/** @default true */
persistStorage: field(coerceBoolean.default(true), 'CRAWLEE_PERSIST_STORAGE'),
+ /** @default './storage' */
+ storageDir: field(z.string().default('./storage'), 'CRAWLEE_STORAGE_DIR'),
containerized: field(coerceBoolean.optional(), 'CRAWLEE_CONTAINERIZED'),
};
@@ -155,6 +157,7 @@ export interface Configuration extends ResolvedConfigValues {}
* `persistStateIntervalMillis` | `CRAWLEE_PERSIST_STATE_INTERVAL_MILLIS` | `60_000`
* `purgeOnStart` | `CRAWLEE_PURGE_ON_START` | `true`
* `persistStorage` | `CRAWLEE_PERSIST_STORAGE` | `true`
+ * `storageDir` | `CRAWLEE_STORAGE_DIR` | `'./storage'`
*
* ## Advanced Configuration Options
*
diff --git a/packages/core/src/service_locator.ts b/packages/core/src/service_locator.ts
index 903bce18d..e2891fea1 100644
--- a/packages/core/src/service_locator.ts
+++ b/packages/core/src/service_locator.ts
@@ -220,6 +220,7 @@ export class ServiceLocator implements ServiceLocatorInterface {
const config = this.getConfiguration();
this.storageClient = config.persistStorage
? new FileSystemStorageClient({
+ localDataDirectory: config.storageDir,
logger: this.getLogger().child({ prefix: 'FileSystemStorageClient' }),
})
: new MemoryStorageClient({
diff --git a/packages/core/src/storages/key_value_store.ts b/packages/core/src/storages/key_value_store.ts
index 596e24aa8..99f69bd06 100644
--- a/packages/core/src/storages/key_value_store.ts
+++ b/packages/core/src/storages/key_value_store.ts
@@ -1,8 +1,4 @@
-import { readFile } from 'node:fs/promises';
-import { join } from 'node:path';
-
import type { Dictionary, KeyValueStoreClient, KeyValueStoreItemData } from '@crawlee/types';
-import JSON5 from 'json5';
import ow, { ArgumentError } from 'ow';
import { KEY_VALUE_STORE_KEY_REGEX } from '@apify/consts';
@@ -855,8 +851,9 @@ export class KeyValueStore {
/**
* Gets the crawler input value from the default {@apilink KeyValueStore} associated with the current crawler run.
- * By default, it will try to find root input files (either extension-less, `.json` or `.txt`),
- * or alternatively read the input from the default {@apilink KeyValueStore}.
+ *
+ * The input is read from the default {@apilink KeyValueStore} under the configured input key
+ * (`CRAWLEE_INPUT_KEY`, default `INPUT`).
*
* Note that the `getInput()` function does not cache the value read from the key-value store.
* If you need to use the input multiple times in your crawler,
@@ -874,32 +871,7 @@ export class KeyValueStore {
*/
static async getInput<T = Dictionary | string | Buffer>(): Promise<T | null> {
const store = await this.open();
- const inputKey = store.config.inputKey;
-
- const cwd = process.cwd();
- const possibleExtensions = ['', '.json', '.txt'];
-
- // Attempt to read input from root file instead of key-value store
- for (const extension of possibleExtensions) {
- const inputFile = join(cwd, `${inputKey}${extension}`);
- let input: Buffer;
-
- // Try getting the file from the file system
- try {
- input = await readFile(inputFile);
- } catch {
- continue;
- }
-
- // Attempt to parse as JSON, or return the input as is otherwise
- try {
- return JSON5.parse(input.toString()) as T;
- } catch {
- return input as unknown as T;
- }
- }
-
- return store.getValue<T>(inputKey);
+ return store.getValue<T>(store.config.inputKey);
}
}
diff --git a/packages/fs-storage/package.json b/packages/fs-storage/package.json
index 75915cba8..79142db4c 100644
--- a/packages/fs-storage/package.json
+++ b/packages/fs-storage/package.json
@@ -42,15 +42,8 @@
"access": "public"
},
"dependencies": {
+ "@crawlee/fs-storage-native": "0.1.5-beta.18",
"@crawlee/types": "workspace:*",
- "@crawlee/utils": "workspace:*",
- "@sapphire/async-queue": "^1.5.5",
- "@sapphire/shapeshift": "^4.0.0",
- "content-type": "^1.0.5",
- "fs-extra": "^11.3.0",
- "json5": "^2.2.3",
- "mime-types": "^3.0.1",
- "proper-lockfile": "^4.1.2",
- "tslib": "^2.8.1"
+ "@sapphire/shapeshift": "^4.0.0"
}
}
diff --git a/packages/fs-storage/src/background-handler/fs-utils.ts b/packages/fs-storage/src/background-handler/fs-utils.ts
deleted file mode 100644
index 2dc1e1ea8..000000000
--- a/packages/fs-storage/src/background-handler/fs-utils.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-import { writeFile } from 'node:fs';
-import { writeFile as writeFileP } from 'node:fs/promises';
-import { resolve } from 'node:path';
-import { setTimeout } from 'node:timers/promises';
-
-import type { CrawleeLogger } from '@crawlee/types';
-import { ensureDir } from 'fs-extra/esm';
-import { lock } from 'proper-lockfile';
-
-import type { BackgroundHandlerReceivedMessage, BackgroundHandlerUpdateMetadataMessage } from '../utils.js';
-
-export async function handleMessage(message: BackgroundHandlerReceivedMessage, logger?: CrawleeLogger) {
- switch (message.action) {
- case 'update-metadata':
- await updateMetadata(message);
- break;
- default:
- // We're keeping this to make eslint happy + in the event we add a new action without adding checks for it
- // we should be aware of them
- logger?.warning(
- `Unknown background handler message action ${(message as BackgroundHandlerReceivedMessage).action}`,
- );
- }
-}
-
-async function updateMetadata(message: BackgroundHandlerUpdateMetadataMessage) {
- // Skip writing the actual metadata file. This is done after ensuring the directory exists so we have the directory present
- if (!message.writeMetadata) {
- return;
- }
-
- // Ensure the directory for the entity exists
- const dir = message.entityDirectory;
- await ensureDir(dir);
-
- // Write the metadata to the file
- const filePath = resolve(dir, '__metadata__.json');
- await writeFileP(filePath, JSON.stringify(message.data, null, '\t'));
-}
-
-export async function lockAndWrite(
- filePath: string,
- data: unknown,
- stringify = true,
- retry = 10,
- timeout = 10,
-): Promise<void> {
- await lockAndCallback(
- filePath,
- async () => {
- await new Promise<void>((pResolve, reject) => {
- writeFile(filePath, stringify ? JSON.stringify(data, null, '\t') : (data as Buffer), (err) => {
- if (err) {
- reject(err);
- } else {
- pResolve();
- }
- });
- });
- },
- retry,
- timeout,
- );
-}
-
-export async function lockAndCallback<Callback extends () => Promise<any>>(
- filePath: string,
- callback: Callback,
- retry = 10,
- timeout = 10,
-): Promise<Awaited<ReturnType<Callback>>> {
- let release: (() => Promise<void>) | null = null;
- try {
- release = await lock(filePath, { realpath: false });
-
- return await callback();
- } catch (e: any) {
- if (e.code === 'ELOCKED' && retry > 0) {
- await setTimeout(timeout);
- return lockAndCallback(filePath, callback, retry - 1, timeout * 2);
- }
-
- throw e;
- } finally {
- if (release) {
- await release();
- }
- }
-}
diff --git a/packages/fs-storage/src/background-handler/index.ts b/packages/fs-storage/src/background-handler/index.ts
deleted file mode 100644
index 007a98e03..000000000
--- a/packages/fs-storage/src/background-handler/index.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { randomUUID } from 'node:crypto';
-
-import type { CrawleeLogger } from '@crawlee/types';
-
-import type { BackgroundHandlerReceivedMessage } from '../utils.js';
-import { handleMessage } from './fs-utils.js';
-
-/**
- * A map of promises that are created when a background task is scheduled.
- * This is used in FileSystemStorageClient#teardown to wait for all tasks to finish executing before exiting the process.
- * @internal
- */
-export const promiseMap: Map<
- string,
- {
- promise: Promise<void>;
- resolve: () => void;
- }
-> = new Map();
-
-export function scheduleBackgroundTask(message: BackgroundHandlerReceivedMessage, logger?: CrawleeLogger) {
- const id = randomUUID();
-
- let promiseResolve: () => void;
- const promise = new Promise<void>((res) => {
- promiseResolve = res;
- });
-
- promiseMap.set(id, {
- promise,
- resolve: promiseResolve!,
- });
-
- void handleBackgroundMessage(
- {
- ...message,
- messageId: id,
- },
- logger,
- );
-}
-
-async function handleBackgroundMessage(
- message: BackgroundHandlerReceivedMessage & { messageId: string },
- logger?: CrawleeLogger,
-) {
- await handleMessage(message, logger);
-
- promiseMap.get(message.messageId)?.resolve();
- promiseMap.delete(message.messageId);
-}
diff --git a/packages/fs-storage/src/body-parser.ts b/packages/fs-storage/src/body-parser.ts
deleted file mode 100644
index 92c6ce172..000000000
--- a/packages/fs-storage/src/body-parser.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import contentTypeParser from 'content-type';
-import JSON5 from 'json5';
-
-const CONTENT_TYPE_JSON = 'application/json';
-const STRINGIFIABLE_CONTENT_TYPE_RXS = [new RegExp(`^${CONTENT_TYPE_JSON}$`, 'i'), /^application\/.*xml$/i, /^text\//i];
-
-/**
- * Parses a Buffer or ArrayBuffer using the provided content type header.
- *
- * - application/json is returned as a parsed object.
- * - application/*xml and text/* are returned as strings.
- * - everything else is returned as original body.
- *
- * If the header includes a charset, the body will be stringified only
- * if the charset represents a known encoding to Node.js or Browser.
- */
-export function maybeParseBody(
- body: Buffer | ArrayBuffer,
- contentTypeHeader: string,
-): string | Buffer | ArrayBuffer | Record<string, unknown> {
- let contentType: string;
- let charset: BufferEncoding;
- try {
- const result = contentTypeParser.parse(contentTypeHeader);
- contentType = result.type;
- charset = result.parameters.charset as BufferEncoding;
- } catch {
- // can't parse, keep original body
- return body;
- }
-
- // If we can't successfully parse it, we return
- // the original buffer rather than a mangled string.
- if (!areDataStringifiable(contentType, charset)) return body;
- const dataString = isomorphicBufferToString(body, charset);
-
- return contentType === CONTENT_TYPE_JSON ? JSON5.parse(dataString) : dataString;
-}
-
-function isomorphicBufferToString(buffer: Buffer | ArrayBuffer, encoding: BufferEncoding): string {
- if (buffer.constructor.name !== ArrayBuffer.name) {
- return buffer.toString(encoding);
- }
-
- // Browser decoding only works with UTF-8.
- const utf8decoder = new TextDecoder();
- return utf8decoder.decode(new Uint8Array(buffer));
-}
-
-function isCharsetStringifiable(charset: string): charset is BufferEncoding {
- if (!charset) return true; // hope that it's utf-8
- return Buffer.isEncoding(charset);
-}
-
-function isContentTypeStringifiable(contentType: string): boolean {
- if (!contentType) return false; // keep buffer
- return STRINGIFIABLE_CONTENT_TYPE_RXS.some((rx) => rx.test(contentType));
-}
-
-function areDataStringifiable(contentType: string, charset: string): boolean {
- return isContentTypeStringifiable(contentType) && isCharsetStringifiable(charset);
-}
diff --git a/packages/fs-storage/src/cache-helpers.ts b/packages/fs-storage/src/cache-helpers.ts
deleted file mode 100644
index 640c413b0..000000000
--- a/packages/fs-storage/src/cache-helpers.ts
+++ /dev/null
@@ -1,466 +0,0 @@
-import { access, opendir, readFile } from 'node:fs/promises';
-import { extname, resolve } from 'node:path';
-
-import type * as storage from '@crawlee/types';
-import json5 from 'json5';
-import mimeTypes from 'mime-types';
-
-import { DatasetFileSystemEntry } from './fs/dataset/fs.js';
-import { KeyValueFileSystemEntry } from './fs/key-value-store/fs.js';
-import { RequestQueueFileSystemEntry } from './fs/request-queue/fs.js';
-import { type FileSystemStorageClient } from './file-system-storage.js';
-
-const uuidRegex = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
-
-/**
- * A named storage is persisted in a directory named after its *name*, while its *id* lives inside
- * that directory's `__metadata__.json`. Looking a storage up by id therefore cannot rely on the
- * directory name — this scans the sibling directories under `baseDirectory` and returns the name of
- * the directory whose metadata `id` matches, so callers can resolve `Dataset.open("<id>")` (and
- * `storageExists("<id>")`) for a storage that was originally opened by name.
- */
-async function resolveDirNameByMetadataId(baseDirectory: string, id: string): Promise<string | undefined> {
- let directories;
- try {
- directories = await opendir(baseDirectory);
- } catch {
- return undefined;
- }
-
- for await (const directory of directories) {
- if (!directory.isDirectory()) {
- continue;
- }
-
- try {
- const fileContent = await readFile(resolve(baseDirectory, directory.name, '__metadata__.json'), 'utf8');
- if ((JSON.parse(fileContent) as { id?: string }).id === id) {
- return directory.name;
- }
- } catch {
- // No metadata file (or unreadable) — this directory can't be matched by id.
- }
- }
-
- return undefined;
-}
-
-export async function findOrCacheDatasetByPossibleId(client: FileSystemStorageClient, entryNameOrId: string) {
- // First check memory cache — match by id, name, or directoryName (which covers alias lookups)
- const found = client.datasetClientCache.find(
- (store) =>
- store.id === entryNameOrId ||
- store.name?.toLowerCase() === entryNameOrId.toLowerCase() ||
- store.directoryName.toLowerCase() === entryNameOrId.toLowerCase(),
- );
-
- if (found) {
- return found;
- }
-
- let datasetDir = resolveWithinDirectory(client.datasetsDirectory, entryNameOrId);
-
- try {
- // Check if directory exists
- await access(datasetDir);
- } catch {
- // No directory named after the string — it may be an id of a storage opened by name, whose
- // directory is named after the name. Fall back to matching the id inside the metadata files.
- const dirName = await resolveDirNameByMetadataId(client.datasetsDirectory, entryNameOrId);
- if (dirName === undefined) {
- return undefined;
- }
- datasetDir = resolve(client.datasetsDirectory, dirName);
- }
-
- // Access the dataset folder
- const directoryEntries = await opendir(datasetDir);
-
- let id: string | undefined;
- let name: string | undefined;
- let itemCount = 0;
-
- const entries = new Set<string>();
-
- let createdAt = new Date();
- let accessedAt = new Date();
- let modifiedAt = new Date();
-
- let hasSeenMetadataFile = false;
-
- for await (const entry of directoryEntries) {
- if (entry.isFile()) {
- if (entry.name === '__metadata__.json') {
- hasSeenMetadataFile = true;
-
- // we have found the store metadata file, build out information based on it
- const fileContent = await readFile(resolve(datasetDir, entry.name), 'utf8');
- if (!fileContent) continue;
-
- const metadata = JSON.parse(fileContent) as storage.DatasetInfo;
- id = metadata.id;
- name = metadata.name;
- itemCount = metadata.itemCount;
- createdAt = new Date(metadata.createdAt);
- accessedAt = new Date(metadata.accessedAt);
- modifiedAt = new Date(metadata.modifiedAt);
-
- continue;
- }
-
- const entryName = entry.name.split('.')[0];
- entries.add(entryName);
-
- if (!hasSeenMetadataFile) {
- itemCount++;
- }
- }
- }
-
- if (id === undefined && name === undefined) {
- const isUuid = uuidRegex.test(entryNameOrId);
-
- if (isUuid) {
- id = entryNameOrId;
- } else {
- name = entryNameOrId;
- }
- }
-
- const newClient = new DatasetClient({
- baseStorageDirectory: client.datasetsDirectory,
- client,
- id,
- name,
- });
-
- // Overwrite properties
- newClient.accessedAt = accessedAt;
- newClient.createdAt = createdAt;
- newClient.modifiedAt = modifiedAt;
- newClient.itemCount = itemCount;
-
- for (const entryId of entries.values()) {
- // We create a file system entry instead of possibly making an in-memory one to allow the pre-included data to be used on demand
- const entry = new DatasetFileSystemEntry({
- storeDirectory: datasetDir,
- entityId: entryId,
- });
-
- // eslint-disable-next-line dot-notation
- newClient['datasetEntries'].set(entryId, entry);
- }
-
- client.datasetClientCache.push(newClient);
-
- return newClient;
-}
-
-export async function findOrCacheKeyValueStoreByPossibleId(client: FileSystemStorageClient, entryNameOrId: string) {
- // First check memory cache — match by id, name, or directoryName (which covers alias lookups)
- const found = client.keyValueStoreCache.find(
- (store) =>
- store.id === entryNameOrId ||
- store.name?.toLowerCase() === entryNameOrId.toLowerCase() ||
- store.directoryName.toLowerCase() === entryNameOrId.toLowerCase(),
- );
-
- if (found) {
- return found;
- }
-
- let keyValueStoreDir = resolveWithinDirectory(client.keyValueStoresDirectory, entryNameOrId);
-
- try {
- // Check if directory exists
- await access(keyValueStoreDir);
- } catch {
- // No directory named after the string — it may be an id of a storage opened by name, whose
- // directory is named after the name. Fall back to matching the id inside the metadata files.
- const dirName = await resolveDirNameByMetadataId(client.keyValueStoresDirectory, entryNameOrId);
- if (dirName === undefined) {
- return undefined;
- }
- keyValueStoreDir = resolve(client.keyValueStoresDirectory, dirName);
- }
-
- // Access the key value store folder
- const directoryEntries = await opendir(keyValueStoreDir);
-
- let id: string | undefined;
- let name: string | undefined;
- let createdAt = new Date();
- let accessedAt = new Date();
- let modifiedAt = new Date();
-
- type FsRecord = Omit<InternalKeyRecord, 'value'>;
- const internalRecords = new Map<string, FsRecord>();
- let hasSeenMetadataForEntry = false;
-
- for await (const entry of directoryEntries) {
- if (entry.isFile()) {
- if (entry.name === '__metadata__.json') {
- // we have found the store metadata file, build out information based on it
- const fileContent = await readFile(resolve(keyValueStoreDir, entry.name), 'utf8');
- if (!fileContent) continue;
-
- const metadata = JSON.parse(fileContent) as storage.KeyValueStoreInfo;
- id = metadata.id;
- name = metadata.name;
- createdAt = new Date(metadata.createdAt);
- accessedAt = new Date(metadata.accessedAt);
- modifiedAt = new Date(metadata.modifiedAt);
-
- continue;
- }
-
- if (entry.name.includes('.__metadata__.')) {
- hasSeenMetadataForEntry = true;
-
- // This is an entry's metadata file, we can use it to create/extend the record
- const fileContent = await readFile(resolve(keyValueStoreDir, entry.name), 'utf8');
- if (!fileContent) continue;
-
- const metadata = JSON.parse(fileContent) as FsRecord;
-
- const newRecord = {
- ...internalRecords.get(metadata.key),
- ...metadata,
- } as FsRecord;
-
- internalRecords.set(metadata.key, newRecord);
-
- continue;
- }
-
- // This is an entry in the store, we can use it to create/extend the record
- const fileContent = await readFile(resolve(keyValueStoreDir, entry.name));
- const fileExtension = extname(entry.name);
- const contentType = mimeTypes.contentType(entry.name) || 'text/plain';
- const extension = mimeTypes.extension(contentType) as string;
-
- // This is kept for backwards compatibility / to ignore invalid JSON files
- if (contentType.includes('application/json')) {
- const stringifiedJson = fileContent.toString('utf8');
-
- try {
- json5.parse(stringifiedJson);
- } catch {
- client.logger?.warning(
- `Key-value entry "${entry.name}" for store ${entryNameOrId} has invalid JSON content and will be ignored from the store.`,
- );
- continue;
- }
- }
-
- const nameSplit = entry.name.split('.');
-
- if (fileExtension) {
- nameSplit.pop();
- }
-
- const key = nameSplit.join('.');
-
- const newRecord = {
- key,
- extension,
- contentType,
- ...internalRecords.get(key),
- } satisfies FsRecord;
-
- internalRecords.set(key, newRecord);
- }
- }
-
- if (id === undefined && name === undefined) {
- const isUuid = uuidRegex.test(entryNameOrId);
-
- if (isUuid) {
- id = entryNameOrId;
- } else {
- name = entryNameOrId;
- }
- }
-
- const newClient = new KeyValueStoreClient({
- baseStorageDirectory: client.keyValueStoresDirectory,
- client,
- id,
- name,
- });
-
- // Overwrite properties
- newClient.accessedAt = accessedAt;
- newClient.createdAt = createdAt;
- newClient.modifiedAt = modifiedAt;
-
- for (const [key, record] of internalRecords) {
- // We create a file system entry instead of possibly making an in-memory one to allow the pre-included data to be used on demand
- const entry = new KeyValueFileSystemEntry({
- storeDirectory: keyValueStoreDir,
- writeMetadata: hasSeenMetadataForEntry,
- logger: client.logger,
- });
-
- // eslint-disable-next-line dot-notation
- entry['rawRecord'] = { ...record };
- // eslint-disable-next-line dot-notation
- entry['filePath'] = resolve(keyValueStoreDir, `${record.key}.${record.extension}`);
- // eslint-disable-next-line dot-notation
- entry['fileMetadataPath'] = resolve(keyValueStoreDir, `${record.key}.__metadata__.json`);
-
- // eslint-disable-next-line dot-notation
- newClient['keyValueEntries'].set(key, entry);
- }
-
- client.keyValueStoreCache.push(newClient);
-
- return newClient;
-}
-
-export async function findRequestQueueByPossibleId(client: FileSystemStorageClient, entryNameOrId: string) {
- // First check memory cache — match by id, name, or directoryName (which covers alias lookups)
- const found = client.requestQueueCache.find(
- (store) =>
- store.id === entryNameOrId ||
- store.name?.toLowerCase() === entryNameOrId.toLowerCase() ||
- store.directoryName.toLowerCase() === entryNameOrId.toLowerCase(),
- );
-
- if (found) {
- return found;
- }
-
- let requestQueueDir = resolveWithinDirectory(client.requestQueuesDirectory, entryNameOrId);
-
- try {
- // Check if directory exists
- await access(requestQueueDir);
- } catch {
- // No directory named after the string — it may be an id of a storage opened by name, whose
- // directory is named after the name. Fall back to matching the id inside the metadata files.
- const dirName = await resolveDirNameByMetadataId(client.requestQueuesDirectory, entryNameOrId);
- if (dirName === undefined) {
- return undefined;
- }
- requestQueueDir = resolve(client.requestQueuesDirectory, dirName);
- }
-
- // Access the request queue folder
- const directoryEntries = await opendir(requestQueueDir);
-
- let id: string | undefined;
- let name: string | undefined;
- let createdAt = new Date();
- let accessedAt = new Date();
- let modifiedAt = new Date();
- const entries = new Set<string>();
- let forefrontRequestIds: string[] = [];
-
- // The request counts are derived from the request files actually present on disk rather than read
- // from the metadata file: metadata is only persisted when `writeMetadata` is enabled (off by
- // default), whereas request files are always persisted. Trusting the metadata counts would reset
- // them to 0 on reload whenever `writeMetadata` is off, even though the requests survive on disk.
- let pendingRequestCount = 0;
- let handledRequestCount = 0;
-
- for await (const entry of directoryEntries) {
- if (entry.isFile()) {
- switch (entry.name) {
- case '__metadata__.json': {
- // we have found the store metadata file, build out information based on it
- const fileContent = await readFile(resolve(requestQueueDir, entry.name), 'utf8');
- if (!fileContent) continue;
-
- const metadata = JSON.parse(fileContent) as storage.RequestQueueInfo;
-
- id = metadata.id;
- name = metadata.name;
- createdAt = new Date(metadata.createdAt);
- accessedAt = new Date(metadata.accessedAt);
- modifiedAt = new Date(metadata.modifiedAt);
- forefrontRequestIds = (metadata as any)?.forefrontRequestIds ?? [];
-
- break;
- }
- default: {
- // Skip non-JSON and files that start with a dot
- if (entry.name.startsWith('.') || !entry.name.endsWith('.json')) {
- continue;
- }
-
- const entryName = entry.name.split('.')[0];
-
- try {
- // Try parsing the file to ensure it's even valid to begin with
- const fileContent = await readFile(resolve(requestQueueDir, entry.name), 'utf8');
- const parsed = JSON.parse(fileContent) as { orderNo?: number | null };
-
- entries.add(entryName);
-
- // A handled request has `orderNo === null`; anything else is still pending.
- if (parsed.orderNo === null) {
- handledRequestCount += 1;
- } else {
- pendingRequestCount += 1;
- }
- } catch {
- client.logger?.warning(
- `Request queue entry "${entry.name}" for store ${entryNameOrId} has invalid JSON content and will be ignored from the store.`,
- );
- }
- }
- }
- }
- }
-
- if (id === undefined && name === undefined) {
- const isUuid = uuidRegex.test(entryNameOrId);
-
- if (isUuid) {
- id = entryNameOrId;
- } else {
- name = entryNameOrId;
- }
- }
-
- const newClient = new RequestQueueClient({
- baseStorageDirectory: client.requestQueuesDirectory,
- client,
- id,
- name,
- });
-
- // Overwrite properties
- newClient.accessedAt = accessedAt;
- newClient.createdAt = createdAt;
- newClient.modifiedAt = modifiedAt;
- newClient.pendingRequestCount = pendingRequestCount;
- newClient.handledRequestCount = handledRequestCount;
- // Drop any persisted forefront ids whose request file is missing or unparseable on disk (and was
- // therefore not added to `entries`). Keeping them would leave a dangling id in `forefrontRequestIds`
- // that `listPendingHead` would resolve to a missing request and dereference as `undefined`.
- // @ts-expect-error - Assigning to private property
- newClient.forefrontRequestIds = forefrontRequestIds.filter((requestId) => entries.has(requestId));
-
- for (const requestId of entries) {
- const entry = new RequestQueueFileSystemEntry({
- requestId,
- storeDirectory: requestQueueDir,
- });
-
- // eslint-disable-next-line dot-notation
- newClient['requests'].set(requestId, entry);
- }
-
- client.requestQueueCache.push(newClient);
-
- return newClient;
-}
-
-/* eslint-disable import/first -- Fixing circulars */
-import { DatasetClient } from './resource-clients/dataset.js';
-import type { InternalKeyRecord } from './resource-clients/key-value-store.js';
-import { KeyValueStoreClient } from './resource-clients/key-value-store.js';
-import { RequestQueueClient } from './resource-clients/request-queue.js';
-import { resolveWithinDirectory } from './utils.js';
diff --git a/packages/fs-storage/src/consts.ts b/packages/fs-storage/src/consts.ts
deleted file mode 100644
index db8b29760..000000000
--- a/packages/fs-storage/src/consts.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-/**
- * Length of id property of a Request instance in characters.
- */
-export const REQUEST_ID_LENGTH = 15;
diff --git a/packages/fs-storage/src/file-system-storage.ts b/packages/fs-storage/src/file-system-storage.ts
index fc9e41ff7..217e9d918 100644
--- a/packages/fs-storage/src/file-system-storage.ts
+++ b/packages/fs-storage/src/file-system-storage.ts
@@ -1,18 +1,15 @@
-/* eslint-disable import/no-duplicates */
-import { readdir, rm } from 'node:fs/promises';
+import { opendir, readFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import type * as storage from '@crawlee/types';
import type { CrawleeLogger } from '@crawlee/types';
import { s } from '@sapphire/shapeshift';
-import { ensureDirSync, move, moveSync, pathExistsSync } from 'fs-extra/esm';
-import { promiseMap, scheduleBackgroundTask } from './background-handler/index.js';
import {
- findOrCacheDatasetByPossibleId,
- findOrCacheKeyValueStoreByPossibleId,
- findRequestQueueByPossibleId,
-} from './cache-helpers.js';
+ FileSystemDatasetClient as NativeDatasetClient,
+ FileSystemKeyValueStoreClient as NativeKeyValueStoreClient,
+ FileSystemRequestQueueClient as NativeRequestQueueClient,
+} from '@crawlee/fs-storage-native';
import { DatasetClient } from './resource-clients/dataset.js';
import { KeyValueStoreClient } from './resource-clients/key-value-store.js';
import { RequestQueueClient } from './resource-clients/request-queue.js';
@@ -20,407 +17,316 @@ import { RequestQueueClient } from './resource-clients/request-queue.js';
export interface FileSystemStorageOptions {
/**
* Path to directory where the data will be saved.
- * @default process.env.CRAWLEE_STORAGE_DIR ?? './storage'
*/
- localDataDirectory?: string;
+ localDataDirectory: string;
/**
- * Whether to also write optional metadata files when storing to disk.
- * @default process.env.DEBUG?.includes('*') ?? process.env.DEBUG?.includes('crawlee:memory-storage') ?? false
+ * Optional logger for FileSystemStorageClient warnings.
*/
- writeMetadata?: boolean;
+ logger?: CrawleeLogger;
/**
- * Optional logger for FileSystemStorageClient warnings.
+ * How the on-disk request queues opened by this client are expected to be accessed.
+ *
+ * With `'single'` (the default), this process asserts it is the *sole* consumer of every request
+ * queue it opens: on open, any requests that a previous run left *in progress* (e.g. after a
+ * crash) are reclaimed immediately, so they become fetchable again right away. This is the right
+ * behavior for the common single-process crawl.
+ *
+ * Use `'shared'` if multiple processes share the same on-disk request queue concurrently (for
+ * example, the {@apilink parallel scraping setup | "Parallel Scraping Guide"}). In that mode an
+ * in-progress request is treated as a potential live peer's lock and is only reclaimed once that
+ * lock expires on the wall clock, so two workers won't process the same request at once.
+ *
+ * @default 'single'
*/
- logger?: CrawleeLogger;
+ requestQueueAccess?: 'single' | 'shared';
}
+/**
+ * A file-system storage client backed by the native `@crawlee/fs-storage-native` Rust extension.
+ *
+ * The native extension owns the on-disk format, timestamps, item counting, request-queue locking and
+ * state persistence. This class is responsible for resolving the user-facing `id` / `name` / `alias`
+ * identifiers to native storages, caching the opened clients (so that `storageExists`, `purge` and
+ * `teardown` can operate over them), and exposing them through the `@crawlee/types` interfaces.
+ */
export class FileSystemStorageClient implements storage.StorageClient {
readonly localDataDirectory: string;
readonly datasetsDirectory: string;
readonly keyValueStoresDirectory: string;
readonly requestQueuesDirectory: string;
- readonly writeMetadata: boolean;
readonly logger?: CrawleeLogger;
+ readonly requestQueueAccess: 'single' | 'shared';
readonly keyValueStoreCache: KeyValueStoreClient[] = [];
readonly datasetClientCache: DatasetClient[] = [];
readonly requestQueueCache: RequestQueueClient[] = [];
- constructor(options: FileSystemStorageOptions = {}) {
+ constructor(options: FileSystemStorageOptions) {
s.object({
- localDataDirectory: s.string().optional(),
- writeMetadata: s.boolean().optional(),
+ localDataDirectory: s.string(),
+ requestQueueAccess: s.enum(['single', 'shared']).optional(),
}).parse(options);
this.logger = options.logger;
+ this.requestQueueAccess = options.requestQueueAccess ?? 'single';
- // v3.0.0 used `crawlee_storage` as the default, we changed this in v3.0.1 to just `storage`,
- // this function handles it without making BC breaks - it respects existing `crawlee_storage`
- // directories, and uses the `storage` only if it's not there.
- const defaultStorageDir = () => {
- if (pathExistsSync(resolve('./crawlee_storage'))) {
- return './crawlee_storage';
- }
-
- return './storage';
- };
-
- this.localDataDirectory = options.localDataDirectory ?? process.env.CRAWLEE_STORAGE_DIR ?? defaultStorageDir();
+ this.localDataDirectory = options.localDataDirectory;
this.datasetsDirectory = resolve(this.localDataDirectory, 'datasets');
this.keyValueStoresDirectory = resolve(this.localDataDirectory, 'key_value_stores');
this.requestQueuesDirectory = resolve(this.localDataDirectory, 'request_queues');
- this.writeMetadata =
- options.writeMetadata ??
- process.env.DEBUG?.includes('*') ??
- process.env.DEBUG?.includes('crawlee:memory-storage') ??
- false;
}
/**
- * Return a cache key that includes the resolved storage directory, so that
- * two `FileSystemStorageClient` instances pointing at different directories get separate
- * cache partitions. Mirrors crawlee-python's `FileSystemStorageClient` which
- * includes `configuration.storage_dir` in its cache key.
+ * Return a cache key that includes the resolved storage directory, so that two
+ * `FileSystemStorageClient` instances pointing at different directories get separate cache
+ * partitions, by including the storage directory in the cache key.
*/
getStorageClientCacheKey(): string {
return `FileSystemStorageClient:${resolve(this.localDataDirectory)}`;
}
private static resolveStorageKey(options: { id?: string; name?: string; alias?: string }): {
- isAlias: boolean;
- directoryKey: string | undefined;
+ id?: string;
+ name?: string;
+ alias?: string;
+ cacheKey: string | undefined;
} {
const isAlias = 'alias' in options && !!options.alias;
const rawKey = isAlias ? options.alias : (options.name ?? options.id);
// Normalize the internal __default__ alias to the user-facing 'default' name.
- const directoryKey = rawKey === '__default__' ? 'default' : rawKey;
- return { isAlias, directoryKey };
+ const cacheKey = rawKey === '__default__' ? 'default' : rawKey;
+ return { id: options.id, name: options.name, alias: options.alias, cacheKey };
}
async createDatasetClient(options: storage.CreateDatasetClientOptions = {}): Promise<storage.DatasetClient> {
- const { isAlias, directoryKey } = FileSystemStorageClient.resolveStorageKey(options);
-
- if (directoryKey) {
- const found = await findOrCacheDatasetByPossibleId(this, directoryKey);
+ const { id, name, alias, cacheKey } = FileSystemStorageClient.resolveStorageKey(options);
+
+ if (cacheKey) {
+ const found = this.datasetClientCache.find(
+ (store) =>
+ store.id === cacheKey ||
+ store.name?.toLowerCase() === cacheKey.toLowerCase() ||
+ store.cacheKey.toLowerCase() === cacheKey.toLowerCase(),
+ );
if (found) {
return found;
}
}
- const newStore = new DatasetClient({
- name: isAlias ? undefined : directoryKey,
- directoryName: directoryKey,
- baseStorageDirectory: this.datasetsDirectory,
- client: this,
+ const nativeClient = await NativeDatasetClient.open(id, name, alias, this.localDataDirectory);
+ const newStore = await DatasetClient.create({
+ name: alias ? undefined : (name ?? cacheKey),
+ cacheKey: cacheKey ?? '',
+ nativeClient,
+ logger: this.logger,
});
this.datasetClientCache.push(newStore);
- // Schedule the worker to write to the disk
- const datasetInfo = newStore.toDatasetInfo();
-
- scheduleBackgroundTask(
- {
- action: 'update-metadata',
- entityType: 'datasets',
- entityDirectory: newStore.datasetDirectory,
- id: datasetInfo.name ?? datasetInfo.id,
- data: datasetInfo,
- writeMetadata: this.writeMetadata,
- },
- this.logger,
- );
-
return newStore;
}
async createKeyValueStoreClient(
options: storage.CreateKeyValueStoreClientOptions = {},
): Promise<storage.KeyValueStoreClient> {
- const { isAlias, directoryKey } = FileSystemStorageClient.resolveStorageKey(options);
-
- if (directoryKey) {
- const found = await findOrCacheKeyValueStoreByPossibleId(this, directoryKey);
+ const { id, name, alias, cacheKey } = FileSystemStorageClient.resolveStorageKey(options);
+
+ if (cacheKey) {
+ const found = this.keyValueStoreCache.find(
+ (store) =>
+ store.id === cacheKey ||
+ store.name?.toLowerCase() === cacheKey.toLowerCase() ||
+ store.cacheKey.toLowerCase() === cacheKey.toLowerCase(),
+ );
if (found) {
return found;
}
}
- const newStore = new KeyValueStoreClient({
- name: isAlias ? undefined : directoryKey,
- directoryName: directoryKey,
- baseStorageDirectory: this.keyValueStoresDirectory,
- client: this,
+ const nativeClient = await NativeKeyValueStoreClient.open(id, name, alias, this.localDataDirectory);
+ const newStore = await KeyValueStoreClient.create({
+ name: alias ? undefined : (name ?? cacheKey),
+ cacheKey: cacheKey ?? '',
+ nativeClient,
+ logger: this.logger,
});
this.keyValueStoreCache.push(newStore);
- // Schedule the worker to write to the disk
- const kvStoreInfo = newStore.toKeyValueStoreInfo();
-
- scheduleBackgroundTask(
- {
- action: 'update-metadata',
- entityType: 'keyValueStores',
- entityDirectory: newStore.keyValueStoreDirectory,
- id: kvStoreInfo.name ?? kvStoreInfo.id,
- data: kvStoreInfo,
- writeMetadata: this.writeMetadata,
- },
- this.logger,
- );
-
return newStore;
}
async createRequestQueueClient(
options: storage.CreateRequestQueueClientOptions = {},
): Promise<storage.RequestQueueClient> {
- const { isAlias, directoryKey } = FileSystemStorageClient.resolveStorageKey(options);
-
- if (directoryKey) {
- const found = await findRequestQueueByPossibleId(this, directoryKey);
+ const { id, name, alias, cacheKey } = FileSystemStorageClient.resolveStorageKey(options);
+
+ if (cacheKey) {
+ const found = this.requestQueueCache.find(
+ (queue) =>
+ queue.id === cacheKey ||
+ queue.name?.toLowerCase() === cacheKey.toLowerCase() ||
+ queue.cacheKey.toLowerCase() === cacheKey.toLowerCase(),
+ );
if (found) {
return found;
}
}
- const newStore = new RequestQueueClient({
- name: isAlias ? undefined : directoryKey,
- directoryName: directoryKey,
- baseStorageDirectory: this.requestQueuesDirectory,
- client: this,
+ const nativeClient = await NativeRequestQueueClient.open(
+ id,
+ name,
+ alias,
+ this.localDataDirectory,
+ // useTestClock — always real wall-clock outside of native tests.
+ undefined,
+ this.requestQueueAccess,
+ );
+ const newStore = await RequestQueueClient.create({
+ name: alias ? undefined : (name ?? cacheKey),
+ cacheKey: cacheKey ?? '',
+ nativeClient,
+ logger: this.logger,
});
this.requestQueueCache.push(newStore);
- // Schedule the worker to write to the disk
- const queueInfo = newStore.toRequestQueueInfo();
-
- scheduleBackgroundTask(
- {
- action: 'update-metadata',
- entityType: 'requestQueues',
- entityDirectory: newStore.requestQueueDirectory,
- id: queueInfo.name ?? queueInfo.id,
- data: queueInfo,
- writeMetadata: this.writeMetadata,
- },
- this.logger,
- );
-
return newStore;
}
async storageExists(id: string, type: 'Dataset' | 'KeyValueStore' | 'RequestQueue'): Promise<boolean> {
- let clients: { id: string }[];
- let findByPossibleId: (
- client: FileSystemStorageClient,
- entryNameOrId: string,
- ) => Promise<{ id: string } | undefined>;
+ let clients: (KeyValueStoreClient | DatasetClient | RequestQueueClient)[];
+ let baseDir: string;
switch (type) {
case 'Dataset':
clients = this.datasetClientCache;
- findByPossibleId = findOrCacheDatasetByPossibleId;
+ baseDir = this.datasetsDirectory;
break;
case 'KeyValueStore':
clients = this.keyValueStoreCache;
- findByPossibleId = findOrCacheKeyValueStoreByPossibleId;
+ baseDir = this.keyValueStoresDirectory;
break;
case 'RequestQueue':
clients = this.requestQueueCache;
- findByPossibleId = findRequestQueueByPossibleId;
+ baseDir = this.requestQueuesDirectory;
break;
default:
return false;
}
- // Check in-memory cache by actual storage ID
+ // Check the in-memory cache by actual storage ID first.
if (clients.some((store) => store.id === id)) {
return true;
}
- // Resolve any on-disk directory that matches the queried string (by directory name).
- // The directory is named after the storage's `name ?? id`, so a match does not by itself
- // prove that the string is the storage's ID — it could just be its name (or an alias).
- // Read the actual stored metadata and only treat the string as an ID if it equals the
- // resolved storage's real ID. This prevents a named storage opened via the legacy
- // `open(idOrName)` signature from being re-resolved as `{ id: name }` on a subsequent run.
- const resolved = await findByPossibleId(this, id);
- return resolved?.id === id;
- }
-
- async setStatusMessage(message: string, options: storage.SetStatusMessageOptions = {}): Promise<void> {
- s.string().parse(message);
- s.object({
- isStatusMessageTerminal: s.boolean().optional(),
- }).parse(options);
-
- return Promise.resolve();
+ // Otherwise, resolve any on-disk storage that matches the queried string — either by its
+ // directory name, or (for a storage opened by name, whose directory is named after the name)
+ // by scanning the `__metadata__.json` files for a matching id.
+ //
+ // A directory-name match does NOT by itself prove the string is the storage's *id*: the
+ // directory is named after `name ?? id`, so `named-storage`/`on-disk` (a name or alias) also
+ // has a matching directory. We therefore read the real id from the metadata and only report
+ // existence when it equals the queried string. This matches upstream PR #3800/#3808 and
+ // prevents a named storage from being re-resolved as `{ id: name }` on a subsequent run.
+ const resolvedId = await FileSystemStorageClient.resolveStorageIdOnDisk(baseDir, id);
+ return resolvedId === id;
}
/**
- * Cleans up the default storage directories before the run starts:
- * - local directory containing the default dataset;
- * - all records from the default key-value store in the local directory, except for the "INPUT" key;
- * - local directory containing the default request queue.
+ * Resolve the real `id` of the on-disk storage identified by `entryNameOrId` under `baseDirectory`,
+ * or `undefined` if none matches. The storage's real id lives in its directory's
+ * `__metadata__.json`; the directory itself is named after the storage's `name ?? id`. So this
+ * first tries the directory named exactly `entryNameOrId` (reading its metadata id), then falls
+ * back to scanning sibling directories for one whose metadata id equals `entryNameOrId` (the case
+ * of a storage opened by name and later looked up by its auto-assigned id).
*/
- async purge(): Promise<void> {
- // Key-value stores
- const keyValueStores = await readdir(this.keyValueStoresDirectory).catch(() => []);
- const keyValueStorePromises: Promise<void>[] = [];
-
- for (const keyValueStoreFolder of keyValueStores) {
- if (keyValueStoreFolder.startsWith('__CRAWLEE_TEMPORARY') || keyValueStoreFolder.startsWith('__OLD')) {
- keyValueStorePromises.push(
- (await this.batchRemoveFiles(resolve(this.keyValueStoresDirectory, keyValueStoreFolder)))(),
- );
- } else if (keyValueStoreFolder === 'default' || keyValueStoreFolder === '__default__') {
- keyValueStorePromises.push(
- this.handleDefaultKeyValueStore(resolve(this.keyValueStoresDirectory, keyValueStoreFolder))(),
- );
- }
+ private static async resolveStorageIdOnDisk(
+ baseDirectory: string,
+ entryNameOrId: string,
+ ): Promise<string | undefined> {
+ // Directory named exactly after the string: return its real (metadata) id, which may differ
+ // from the string when the string is a name rather than an id.
+ const directId = await FileSystemStorageClient.readMetadataId(resolve(baseDirectory, entryNameOrId));
+ if (directId !== undefined) {
+ return directId;
}
- void Promise.allSettled(keyValueStorePromises);
-
- // Datasets
- const datasets = await readdir(this.datasetsDirectory).catch(() => []);
- const datasetPromises: Promise<void>[] = [];
+ // No such directory — scan siblings for one whose metadata id matches the string.
+ let directories;
+ try {
+ directories = await opendir(baseDirectory);
+ } catch {
+ return undefined;
+ }
- for (const datasetFolder of datasets) {
- if (
- datasetFolder === 'default' ||
- datasetFolder === '__default__' ||
- datasetFolder.startsWith('__CRAWLEE_TEMPORARY')
- ) {
- datasetPromises.push((await this.batchRemoveFiles(resolve(this.datasetsDirectory, datasetFolder)))());
+ for await (const directory of directories) {
+ if (!directory.isDirectory()) {
+ continue;
}
- }
- void Promise.allSettled(datasetPromises);
-
- // Request queues
- const requestQueues = await readdir(this.requestQueuesDirectory).catch(() => []);
- const requestQueuePromises: Promise<void>[] = [];
-
- for (const requestQueueFolder of requestQueues) {
- if (
- requestQueueFolder === 'default' ||
- requestQueueFolder === '__default__' ||
- requestQueueFolder.startsWith('__CRAWLEE_TEMPORARY')
- ) {
- requestQueuePromises.push(
- (await this.batchRemoveFiles(resolve(this.requestQueuesDirectory, requestQueueFolder)))(),
- );
+ const metadataId = await FileSystemStorageClient.readMetadataId(resolve(baseDirectory, directory.name));
+ if (metadataId === entryNameOrId) {
+ return metadataId;
}
}
- void Promise.allSettled(requestQueuePromises);
- }
-
- /**
- * This method should be called at the end of the process, to ensure all data is saved.
- */
- async teardown(): Promise<void> {
- // Release any request locks this process still holds so that requests fetched but not yet
- // handled are not stuck (until their lock expires) for the next consumer of the same on-disk
- // queue. Other storage backends don't need this: the Apify platform releases a run's locks
- // automatically, and the file-system storage doesn't lock at all.
- await Promise.all(this.requestQueueCache.map(async (queue) => queue.releaseOwnLocks()));
-
- const promises = [...promiseMap.values()].map(async ({ promise }) => promise);
-
- await Promise.all(promises);
+ return undefined;
}
- private handleDefaultKeyValueStore(folder: string): () => Promise<void> {
- const storagePathExists = pathExistsSync(folder);
- const temporaryPath = resolve(folder, '../__CRAWLEE_MIGRATING_KEY_VALUE_STORE__');
-
- // For optimization, we want to only attempt to copy a few files from the default key-value store
- const possibleInputKeys = ['INPUT', 'INPUT.json', 'INPUT.bin', 'INPUT.txt'];
-
- if (storagePathExists) {
- // Create temporary folder to save important files in
- ensureDirSync(temporaryPath);
-
- // Go through each file and save the ones that are important
- for (const entity of possibleInputKeys) {
- const originalFilePath = resolve(folder, entity);
- const tempFilePath = resolve(temporaryPath, entity);
-
- try {
- moveSync(originalFilePath, tempFilePath);
- } catch {
- // Ignore
- }
- }
-
- // Remove the original folder and all its content
- let counter = 0;
- let tempPathForOldFolder = resolve(folder, `../__OLD_DEFAULT_${counter}__`);
- let done = false;
-
- while (!done) {
- try {
- moveSync(folder, tempPathForOldFolder);
- done = true;
- } catch {
- tempPathForOldFolder = resolve(folder, `../__OLD_DEFAULT_${++counter}__`);
- }
- }
-
- // Replace the temporary folder with the original folder
- moveSync(temporaryPath, folder);
-
- // Remove the old folder
- return async () => (await this.batchRemoveFiles(tempPathForOldFolder))();
+ /** Read the `id` field from a storage directory's `__metadata__.json`, or `undefined` if absent. */
+ private static async readMetadataId(storageDirectory: string): Promise<string | undefined> {
+ try {
+ const fileContent = await readFile(resolve(storageDirectory, '__metadata__.json'), 'utf8');
+ return (JSON.parse(fileContent) as { id?: string }).id;
+ } catch {
+ // Directory missing, or no/unreadable metadata file — no id to report.
+ return undefined;
}
-
- return async () => Promise.resolve();
}
- private async batchRemoveFiles(folder: string, counter = 0): Promise<() => Promise<void>> {
- const folderExists = pathExistsSync(folder);
-
- if (folderExists) {
- const temporaryFolder = resolve(folder, `../__CRAWLEE_TEMPORARY_${counter}__`);
-
- try {
- // Rename the old folder to the new one to allow background deletions
- await move(folder, temporaryFolder);
- } catch {
- // Folder exists already, try again with an incremented counter
- return this.batchRemoveFiles(folder, ++counter);
- }
-
- return async () => {
- // Read all files in the folder
- const entries = await readdir(temporaryFolder);
-
- let processed = 0;
- let promises: Promise<void>[] = [];
-
- for (const entry of entries) {
- processed++;
- promises.push(rm(resolve(temporaryFolder, entry), { force: true }));
-
- // Every 2000 files, delete them
- if (processed % 2000 === 0) {
- await Promise.allSettled(promises);
- promises = [];
- }
- }
+ async setStatusMessage(message: string, options: storage.SetStatusMessageOptions = {}): Promise<void> {
+ s.string().parse(message);
+ s.object({
+ isStatusMessageTerminal: s.boolean().optional(),
+ }).parse(options);
- // Ensure last promises are handled
- await Promise.allSettled(promises);
+ return Promise.resolve();
+ }
- // Delete the folder itself
- await rm(temporaryFolder, { force: true, recursive: true });
- };
- }
+ /**
+ * Cleans up the default storages before the run starts:
+ * - the default dataset;
+ * - all records from the default key-value store, except for the "INPUT" key;
+ * - the default request queue.
+ */
+ async purge(): Promise<void> {
+ // Resolve the default stores up front so leftover on-disk records are purged even when the
+ // store has not been opened in this process yet (e.g. a fresh run over a pre-existing
+ // directory). Opening caches the client, so the subsequent purge operates on a real client.
+ // The default store is opened via the internal `__default__` alias (see resolveStorageIdentifier
+ // in @crawlee/core), which resolves to the `default` cache key — match that here so we purge the
+ // very client the default open would return rather than creating a divergent one.
+ const [defaultKeyValueStore, defaultDataset, defaultRequestQueue] = await Promise.all([
+ this.createKeyValueStoreClient({ alias: '__default__' }) as Promise<KeyValueStoreClient>,
+ this.createDatasetClient({ alias: '__default__' }) as Promise<DatasetClient>,
+ this.createRequestQueueClient({ alias: '__default__' }) as Promise<RequestQueueClient>,
+ ]);
+
+ await Promise.all([
+ // Preserve the run input (INPUT) when purging the default key-value store.
+ defaultKeyValueStore.purgeExceptInput(),
+ defaultDataset.purge(),
+ defaultRequestQueue.purge(),
+ ]);
+ }
- return async () => Promise.resolve();
+ /**
+ * This method should be called at the end of the process, to ensure all data is saved.
+ *
+ * It persists the state of every opened request queue so that requests fetched but not yet handled
+ * are not stuck (until their lock expires) for the next consumer of the same on-disk queue.
+ */
+ async teardown(): Promise<void> {
+ await Promise.all(this.requestQueueCache.map(async (queue) => queue.persistState()));
}
}
diff --git a/packages/fs-storage/src/fs/common.ts b/packages/fs-storage/src/fs/common.ts
deleted file mode 100644
index 1a26019fe..000000000
--- a/packages/fs-storage/src/fs/common.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-export interface StorageImplementation<T> {
- get(force?: boolean): Promise<T>;
- update(data: T): void | Promise<void>;
- delete(): void | Promise<void>;
-}
diff --git a/packages/fs-storage/src/fs/dataset/fs.ts b/packages/fs-storage/src/fs/dataset/fs.ts
deleted file mode 100644
index bf66d2d5e..000000000
--- a/packages/fs-storage/src/fs/dataset/fs.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { readFile, rm } from 'node:fs/promises';
-import { dirname, resolve } from 'node:path';
-
-import { AsyncQueue } from '@sapphire/async-queue';
-import { ensureDir } from 'fs-extra/esm';
-
-import { lockAndWrite } from '../../background-handler/fs-utils.js';
-import type { StorageImplementation } from '../common.js';
-import type { CreateStorageImplementationOptions } from './index.js';
-
-export class DatasetFileSystemEntry<Data> implements StorageImplementation<Data> {
- private filePath: string;
- private fsQueue = new AsyncQueue();
-
- constructor(options: CreateStorageImplementationOptions) {
- this.filePath = resolve(options.storeDirectory, `${options.entityId}.json`);
- }
-
- async get() {
- await this.fsQueue.wait();
- try {
- return JSON.parse(await readFile(this.filePath, 'utf-8'));
- } finally {
- this.fsQueue.shift();
- }
- }
-
- async update(data: Data) {
- await this.fsQueue.wait();
- try {
- await ensureDir(dirname(this.filePath));
- await lockAndWrite(this.filePath, data);
- } finally {
- this.fsQueue.shift();
- }
- }
-
- async delete() {
- await this.fsQueue.wait();
- await rm(this.filePath, { force: true });
- this.fsQueue.shift();
- }
-}
diff --git a/packages/fs-storage/src/fs/dataset/index.ts b/packages/fs-storage/src/fs/dataset/index.ts
deleted file mode 100644
index bd1f71cee..000000000
--- a/packages/fs-storage/src/fs/dataset/index.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import type { Dictionary } from '@crawlee/types';
-
-import type { StorageImplementation } from '../common.js';
-import { DatasetFileSystemEntry } from './fs.js';
-
-export function createDatasetStorageImplementation<Data extends Dictionary>(
- options: CreateStorageImplementationOptions,
-): StorageImplementation<Data> {
- return new DatasetFileSystemEntry<Data>(options);
-}
-
-export interface CreateStorageImplementationOptions {
- storeDirectory: string;
- /** The actual id of the file to save */
- entityId: string;
-}
diff --git a/packages/fs-storage/src/fs/key-value-store/fs.ts b/packages/fs-storage/src/fs/key-value-store/fs.ts
deleted file mode 100644
index 03ff48ae6..000000000
--- a/packages/fs-storage/src/fs/key-value-store/fs.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-import { readFile, rm } from 'node:fs/promises';
-import { basename, dirname } from 'node:path';
-
-import type { CrawleeLogger } from '@crawlee/types';
-import { AsyncQueue } from '@sapphire/async-queue';
-import { ensureDir } from 'fs-extra/esm';
-import mime from 'mime-types';
-
-import { lockAndWrite } from '../../background-handler/fs-utils.js';
-import type { InternalKeyRecord } from '../../resource-clients/key-value-store.js';
-import { resolveWithinDirectory } from '../../utils.js';
-import type { StorageImplementation } from '../common.js';
-import type { CreateStorageImplementationOptions } from './index.js';
-
-export class KeyValueFileSystemEntry implements StorageImplementation<InternalKeyRecord> {
- private storeDirectory: string;
- private writeMetadata: boolean;
- private logger?: CrawleeLogger;
-
- private filePath!: string;
- private fileMetadataPath!: string;
- private rawRecord!: Omit<InternalKeyRecord, 'value'>;
- private fsQueue = new AsyncQueue();
-
- constructor(options: CreateStorageImplementationOptions) {
- this.storeDirectory = options.storeDirectory;
- this.writeMetadata = options.writeMetadata;
- this.logger = options.logger;
- }
-
- async get(): Promise<InternalKeyRecord> {
- await this.fsQueue.wait();
- let file: Buffer;
-
- try {
- file = await readFile(this.filePath);
- } catch {
- try {
- const noExtFilePath = resolveWithinDirectory(this.storeDirectory, this.rawRecord.key);
- // Try without extension. Keep the raw bytes — interpretation (text vs. JSON) is the
- // KeyValueStore frontend's job; this client is a plain byte transport.
- file = await readFile(noExtFilePath);
- this.logger?.warning(
- [
- `Key-value entry "${this.rawRecord.key}" for store ${basename(
- this.storeDirectory,
- )} does not have a file extension, assuming it as text.`,
- 'If you want to have correct interpretation of the file, you should add a file extension to the entry.',
- ].join('\n'),
- );
- this.filePath = noExtFilePath;
- } catch {
- // This is impossible to happen, but just in case
- throw new Error(`Could not find file at ${this.filePath}`);
- }
- } finally {
- this.fsQueue.shift();
- }
-
- return {
- ...this.rawRecord,
- value: file,
- filePath: this.filePath,
- };
- }
-
- async update(data: InternalKeyRecord) {
- await this.fsQueue.wait();
- const contentType = mime.contentType(data.key);
- const fileName =
- // the content type might include charset, e.g. `text/html; charset=utf-8`, so we check via `startsWith` instead of `===`
- contentType && data.contentType && contentType.startsWith(data.contentType)
- ? data.key
- : `${data.key}.${data.extension}`;
-
- this.filePath ??= resolveWithinDirectory(this.storeDirectory, fileName);
- this.fileMetadataPath ??= resolveWithinDirectory(this.storeDirectory, `${data.key}.__metadata__.json`);
-
- const { value, ...rest } = data;
- this.rawRecord = rest;
-
- try {
- await ensureDir(dirname(this.filePath));
- await lockAndWrite(this.filePath, value, false);
-
- if (this.writeMetadata) {
- await lockAndWrite(this.fileMetadataPath, JSON.stringify(rest), true);
- }
- } finally {
- this.fsQueue.shift();
- }
- }
-
- async delete() {
- await this.fsQueue.wait();
- await rm(this.filePath, { force: true });
- await rm(this.fileMetadataPath, { force: true });
- this.fsQueue.shift();
- }
-}
diff --git a/packages/fs-storage/src/fs/key-value-store/index.ts b/packages/fs-storage/src/fs/key-value-store/index.ts
deleted file mode 100644
index 789d15d2f..000000000
--- a/packages/fs-storage/src/fs/key-value-store/index.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import type { CrawleeLogger } from '@crawlee/types';
-
-import type { InternalKeyRecord } from '../../resource-clients/key-value-store.js';
-import type { StorageImplementation } from '../common.js';
-import { KeyValueFileSystemEntry } from './fs.js';
-
-export function createKeyValueStorageImplementation(
- options: CreateStorageImplementationOptions,
-): StorageImplementation<InternalKeyRecord> {
- return new KeyValueFileSystemEntry(options);
-}
-
-export interface CreateStorageImplementationOptions {
- storeDirectory: string;
- writeMetadata: boolean;
- logger?: CrawleeLogger;
-}
diff --git a/packages/fs-storage/src/fs/request-queue/fs.ts b/packages/fs-storage/src/fs/request-queue/fs.ts
deleted file mode 100644
index 87dde6a21..000000000
--- a/packages/fs-storage/src/fs/request-queue/fs.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-import { readFile, rm } from 'node:fs/promises';
-import { dirname, resolve } from 'node:path';
-
-import { AsyncQueue } from '@sapphire/async-queue';
-import { ensureDir } from 'fs-extra/esm';
-
-import { lockAndCallback, lockAndWrite } from '../../background-handler/fs-utils.js';
-import type { InternalRequest } from '../../resource-clients/request-queue.js';
-import type { StorageImplementation } from '../common.js';
-import type { CreateStorageImplementationOptions } from './index.js';
-
-export class RequestQueueFileSystemEntry implements StorageImplementation<InternalRequest> {
- private filePath: string;
- private fsQueue = new AsyncQueue();
- private data?: InternalRequest;
- private directoryExists = false;
-
- /**
- * A "sweep" timeout that is created/refreshed whenever this entry is accessed/updated.
- * It exists to ensure that the entry is not kept in memory indefinitely, by sweeping it after 60 seconds of inactivity (in order to keep memory usage low)
- */
- private sweepTimeout?: NodeJS.Timeout;
-
- public orderNo?: number | null;
-
- constructor(options: CreateStorageImplementationOptions) {
- this.filePath = resolve(options.storeDirectory, `${options.requestId}.json`);
- }
-
- async get(force = false) {
- await this.fsQueue.wait();
- this.setOrRefreshSweepTimeout();
-
- if (this.data && !force) {
- this.fsQueue.shift();
- return this.data;
- }
-
- try {
- return await lockAndCallback(this.filePath, async () => {
- const req = JSON.parse(await readFile(this.filePath, 'utf-8'));
- this.data = req;
-
- this.orderNo = req.orderNo;
-
- return req;
- });
- } finally {
- this.fsQueue.shift();
- }
- }
-
- async update(data: InternalRequest) {
- await this.fsQueue.wait();
- this.data = data;
-
- try {
- if (!this.directoryExists) {
- await ensureDir(dirname(this.filePath));
- this.directoryExists = true;
- }
-
- await lockAndWrite(this.filePath, data);
-
- this.orderNo = data.orderNo;
- } finally {
- this.setOrRefreshSweepTimeout();
- this.fsQueue.shift();
- }
- }
-
- async delete() {
- await this.fsQueue.wait();
- await rm(this.filePath, { force: true });
- this.fsQueue.shift();
- }
-
- private setOrRefreshSweepTimeout() {
- if (this.sweepTimeout) {
- this.sweepTimeout.refresh();
- } else {
- this.sweepTimeout = setTimeout(() => {
- this.sweepTimeout = undefined;
- this.data = undefined;
- }, 60_000).unref();
- }
- }
-}
diff --git a/packages/fs-storage/src/fs/request-queue/index.ts b/packages/fs-storage/src/fs/request-queue/index.ts
deleted file mode 100644
index 995c399ad..000000000
--- a/packages/fs-storage/src/fs/request-queue/index.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { RequestQueueFileSystemEntry } from './fs.js';
-
-export function createRequestQueueStorageImplementation(options: CreateStorageImplementationOptions) {
- return new RequestQueueFileSystemEntry(options);
-}
-
-export interface CreateStorageImplementationOptions {
- storeDirectory: string;
- requestId: string;
-}
diff --git a/packages/fs-storage/src/resource-clients/cached-id-client.ts b/packages/fs-storage/src/resource-clients/cached-id-client.ts
new file mode 100644
index 000000000..fb8dd5e5a
--- /dev/null
+++ b/packages/fs-storage/src/resource-clients/cached-id-client.ts
@@ -0,0 +1,14 @@
+/**
+ * Shared base for the file-system resource clients. The native id is read once from the native
+ * metadata at construction time (in each client's `create()`), so the synchronous `id` getter —
+ * required by `FileSystemStorageClient.storageExists` and the cache lookups — does not have to await.
+ */
+export abstract class CachedIdClient {
+ /** The storage id assigned by the native client. Set once by the subclass `create()`. */
+ protected _cachedId!: string;
+
+ /** The storage id assigned by the native client. */
+ get id(): string {
+ return this._cachedId;
+ }
+}
diff --git a/packages/fs-storage/src/resource-clients/common/base-client.ts b/packages/fs-storage/src/resource-clients/common/base-client.ts
deleted file mode 100644
index 72a994c2d..000000000
--- a/packages/fs-storage/src/resource-clients/common/base-client.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-export class BaseClient {
- id: string;
-
- constructor(id: string) {
- this.id = id;
- }
-}
diff --git a/packages/fs-storage/src/resource-clients/dataset.ts b/packages/fs-storage/src/resource-clients/dataset.ts
index 20ec7baa2..c999b4100 100644
--- a/packages/fs-storage/src/resource-clients/dataset.ts
+++ b/packages/fs-storage/src/resource-clients/dataset.ts
@@ -1,105 +1,96 @@
-/* eslint-disable import/no-duplicates */
-import { randomUUID } from 'node:crypto';
-import { rm } from 'node:fs/promises';
-import { resolve } from 'node:path';
-
import type * as storage from '@crawlee/types';
-import type { Dictionary } from '@crawlee/types';
+import type { CrawleeLogger, Dictionary } from '@crawlee/types';
import { s } from '@sapphire/shapeshift';
-import { scheduleBackgroundTask } from '../background-handler/index.js';
-import type { StorageImplementation } from '../fs/common.js';
-import { createDatasetStorageImplementation } from '../fs/dataset/index.js';
-import type { FileSystemStorageClient } from '../index.js';
-import { resolveWithinDirectory } from '../utils.js';
-import { BaseClient } from './common/base-client.js';
+import type { FileSystemDatasetClient as NativeFileSystemDatasetClient } from '@crawlee/fs-storage-native';
-/**
- * This is what API returns in the x-apify-pagination-limit
- * header when no limit query parameter is used.
- */
-const LIST_ITEMS_LIMIT = 999_999_999_999;
+import { CachedIdClient } from './cached-id-client.js';
/**
- * Number of characters of the dataset item file names.
- * E.g.: 000000019.json - 9 digits
+ * `getData` options accepted by the high-level `Dataset` frontend but not supported by the native
+ * file-system backend (it can only paginate raw items by `offset`/`limit`/`desc`). They are silently
+ * ignored, so we warn once if a caller passes any of them.
+ *
+ * Implementing these in the native client is tracked in
+ * https://github.com/apify/crawlee-storage/issues/8.
*/
-const LOCAL_ENTRY_NAME_DIGITS = 9;
+const UNSUPPORTED_GET_DATA_OPTIONS = ['clean', 'fields', 'omit', 'skipHidden', 'skipEmpty'] as const;
export interface DatasetClientOptions {
- id?: string;
+ /** The user-facing storage name, or `undefined` for unnamed (alias / default) storages. */
name?: string;
/**
- * The directory name to use on disk. When provided, takes precedence over `name` and `id`
- * for the directory path. This allows alias-opened storages to have a directory name
- * that differs from their metadata `name` (which is `undefined` for unnamed storages).
+ * The key used for cache lookup in {@link FileSystemStorageClient}. For named storages this equals
+ * the name; for alias (unnamed) storages it is the alias string. Falls back to the storage id.
*/
- directoryName?: string;
- baseStorageDirectory: string;
- client: FileSystemStorageClient;
+ cacheKey: string;
+ nativeClient: NativeFileSystemDatasetClient;
+ logger?: CrawleeLogger;
}
+/**
+ * A file-system dataset client backed by the native `@crawlee/fs-storage-native` Rust extension.
+ *
+ * This class is a thin adapter: it forwards each operation to the native client (which owns the
+ * on-disk format, timestamps and item counting) and converts results into the shapes expected by
+ * the `@crawlee/types` interfaces.
+ */
export class DatasetClient<Data extends Dictionary = Dictionary>
- extends BaseClient
+ extends CachedIdClient
implements storage.DatasetClient<Data>
{
- name?: string;
- /**
- * The key used for directory naming and cache lookup. For named storages, this equals
- * the name. For alias (unnamed) storages, this is the alias string. Falls back to id.
- */
- directoryName: string;
- createdAt = new Date();
- accessedAt = new Date();
- modifiedAt = new Date();
- itemCount = 0;
- datasetDirectory: string;
+ readonly name?: string;
+ readonly cacheKey: string;
- private readonly datasetEntries = new Map<string, StorageImplementation<Data>>();
- private readonly client: FileSystemStorageClient;
+ private readonly nativeClient: NativeFileSystemDatasetClient;
+ private readonly logger?: CrawleeLogger;
constructor(options: DatasetClientOptions) {
- super(options.id ?? randomUUID());
+ super();
this.name = options.name;
- this.directoryName = options.directoryName ?? this.name ?? this.id;
- this.datasetDirectory = resolveWithinDirectory(options.baseStorageDirectory, this.directoryName);
- this.client = options.client;
+ this.cacheKey = options.cacheKey;
+ this.nativeClient = options.nativeClient;
+ this.logger = options.logger;
}
- async getMetadata(): Promise<storage.DatasetInfo> {
- this.updateTimestamps(false);
- return this.toDatasetInfo();
+ get datasetDirectory(): string {
+ return this.nativeClient.pathToDataset;
}
- async drop(): Promise<void> {
- const storeIndex = this.client.datasetClientCache.findIndex((store) => store.id === this.id);
+ static async create<Data extends Dictionary = Dictionary>(
+ options: DatasetClientOptions,
+ ): Promise<DatasetClient<Data>> {
+ const client = new DatasetClient<Data>(options);
+ client._cachedId = (await options.nativeClient.getMetadata()).id;
+ return client;
+ }
- if (storeIndex !== -1) {
- const [oldClient] = this.client.datasetClientCache.splice(storeIndex, 1);
- oldClient.itemCount = 0;
- oldClient.datasetEntries.clear();
+ async getMetadata(): Promise<storage.DatasetInfo> {
+ return this.nativeClient.getMetadata();
+ }
- await rm(oldClient.datasetDirectory, { recursive: true, force: true });
- }
+ async drop(): Promise<void> {
+ await this.nativeClient.dropStorage();
}
async purge(): Promise<void> {
- this.itemCount = 0;
- this.datasetEntries.clear();
-
- // Remove item files from disk but keep the directory
- const { readdir } = await import('node:fs/promises');
- const entries = await readdir(this.datasetDirectory).catch(() => []);
- for (const entry of entries) {
- if (entry !== '__metadata__.json') {
- await rm(resolve(this.datasetDirectory, entry), { force: true });
- }
- }
+ await this.nativeClient.purge();
+ }
- this.updateTimestamps(true);
+ async pushData(items: Data[]): Promise<void> {
+ await this.nativeClient.pushData(items);
}
- getData(options: storage.DatasetClientListOptions = {}): Promise<storage.PaginatedList<Data>> {
+ async getData(options: storage.DatasetClientListOptions = {}): Promise<storage.PaginatedList<Data>> {
+ const passedOptions = options as Record<string, unknown>;
+ const ignored = UNSUPPORTED_GET_DATA_OPTIONS.filter((key) => passedOptions[key] !== undefined);
+ if (ignored.length > 0) {
+ this.logger?.warning?.(
+ `getData() options [${ignored.join(', ')}] are not supported by the file-system dataset ` +
+ `and were ignored. Only "offset", "limit" and "desc" are honored.`,
+ );
+ }
+
const { desc, limit, offset } = s
.object({
desc: s.boolean().optional(),
@@ -108,95 +99,15 @@ export class DatasetClient<Data extends Dictionary = Dictionary>
})
.parse(options);
- return this.getDataPage({
- desc,
- offset: offset ?? 0,
- limit: Math.min(limit ?? LIST_ITEMS_LIMIT, LIST_ITEMS_LIMIT),
- });
- }
-
- private async getDataPage(options: storage.DatasetClientListOptions = {}): Promise<storage.PaginatedList<Data>> {
- const { limit = LIST_ITEMS_LIMIT, offset = 0, desc } = options;
-
- const [start, end] = this.getStartAndEndIndexes(
- desc ? Math.max(this.itemCount - offset - limit, 0) : offset,
- limit,
- );
-
- const items: Data[] = [];
-
- for (let idx = start; idx < end; idx++) {
- const entryNumber = this.generateLocalEntryName(idx);
- items.push(await this.datasetEntries.get(entryNumber)!.get());
- }
-
- this.updateTimestamps(false);
+ const page = await this.nativeClient.getData(offset ?? 0, limit, desc ?? false, false);
return {
- count: items.length,
- desc: desc ?? false,
- items: desc ? items.reverse() : items,
- limit,
- offset,
- total: this.itemCount,
+ count: page.count,
+ desc: page.desc,
+ items: page.items as Data[],
+ limit: page.limit,
+ offset: page.offset,
+ total: page.total,
};
}
-
- async pushData(items: Data[]): Promise<void> {
- for (const entry of items) {
- const idx = this.generateLocalEntryName(++this.itemCount);
- const storageEntry = createDatasetStorageImplementation({
- entityId: idx,
- storeDirectory: this.datasetDirectory,
- });
-
- await storageEntry.update(entry);
-
- this.datasetEntries.set(idx, storageEntry);
- }
-
- this.updateTimestamps(true);
- }
-
- toDatasetInfo(): storage.DatasetInfo {
- return {
- id: this.id,
- accessedAt: this.accessedAt,
- createdAt: this.createdAt,
- itemCount: this.itemCount,
- modifiedAt: this.modifiedAt,
- name: this.name,
- };
- }
-
- private generateLocalEntryName(idx: number): string {
- return idx.toString().padStart(LOCAL_ENTRY_NAME_DIGITS, '0');
- }
-
- private getStartAndEndIndexes(offset: number, limit = this.itemCount) {
- const start = offset + 1;
- const end = Math.min(offset + limit, this.itemCount) + 1;
- return [start, end] as const;
- }
-
- private updateTimestamps(hasBeenModified: boolean) {
- this.accessedAt = new Date();
-
- if (hasBeenModified) {
- this.modifiedAt = new Date();
- }
-
- const data = this.toDatasetInfo();
- scheduleBackgroundTask(
- {
- action: 'update-metadata',
- data,
- entityType: 'datasets',
- entityDirectory: this.datasetDirectory,
- id: this.name ?? this.id,
- writeMetadata: this.client.writeMetadata,
- },
- this.client.logger,
- );
- }
}
diff --git a/packages/fs-storage/src/resource-clients/key-value-store.ts b/packages/fs-storage/src/resource-clients/key-value-store.ts
index 1b3c07d8b..fd7af062e 100644
--- a/packages/fs-storage/src/resource-clients/key-value-store.ts
+++ b/packages/fs-storage/src/resource-clients/key-value-store.ts
@@ -1,89 +1,131 @@
-import { randomUUID } from 'node:crypto';
-import { rm } from 'node:fs/promises';
-import { pathToFileURL } from 'node:url';
+import { Readable } from 'node:stream';
import type * as storage from '@crawlee/types';
+import type { CrawleeLogger } from '@crawlee/types';
import { s } from '@sapphire/shapeshift';
-import { scheduleBackgroundTask } from '../background-handler/index.js';
-import type { StorageImplementation } from '../fs/common.js';
-import { createKeyValueStorageImplementation } from '../fs/key-value-store/index.js';
-import type { FileSystemStorageClient } from '../index.js';
-import { isStream, resolveWithinDirectory, toBuffer } from '../utils.js';
-import { BaseClient } from './common/base-client.js';
-import mime from 'mime-types';
-
-const DEFAULT_LOCAL_FILE_EXTENSION = 'bin';
+import type {
+ FileSystemKeyValueStoreClient as NativeFileSystemKeyValueStoreClient,
+ ListBareFallback,
+} from '@crawlee/fs-storage-native';
+import { isStream } from '../utils.js';
+import { CachedIdClient } from './cached-id-client.js';
+
+/**
+ * Out-of-band ("bare") value-file fallbacks tried when the {@link ALLOWED_BARE_FILES} lookup misses the tracked
+ * record, so a lookup for `INPUT` also matches a hand-placed `INPUT.json`/`.txt`/`.bin`. Passed to the
+ * native `resolveValue`/`resolveExistingKey`, which do the probing and re-keying.
+ *
+ * Each entry declares the content type to report on a match — the native client does no MIME
+ * inference. An empty `contentType` is its sentinel for "keep the synthesized
+ * `application/octet-stream`", used for the extensionless key and `.bin`.
+ */
+const BARE_FILE_FALLBACKS: { extension: string; contentType: string }[] = [
+ { extension: '', contentType: '' },
+ { extension: '.json', contentType: 'application/json; charset=utf-8' },
+ { extension: '.txt', contentType: 'text/plain; charset=utf-8' },
+ { extension: '.bin', contentType: '' },
+];
+
+const ALLOWED_BARE_FILES = ['INPUT'];
+
+/**
+ * The out-of-band ("bare") files to surface from the native `listKeys`, derived from
+ * {@link ALLOWED_BARE_FILES} × {@link BARE_FILE_FALLBACKS}. Each native {@link ListBareFallback}
+ * `name` is the literal on-disk filename to probe (e.g. `INPUT.json`), and the native lists a match
+ * under that same `name` — which is exactly the key we return, so a listed bare file round-trips
+ * through `getValue`/`recordExists` (see {@link BARE_FILE_CONTENT_TYPES}).
+ */
+const LIST_BARE_FALLBACKS: ListBareFallback[] = ALLOWED_BARE_FILES.flatMap((key) =>
+ BARE_FILE_FALLBACKS.map(({ extension, contentType }) => ({ name: `${key}${extension}`, contentType })),
+);
+
+/**
+ * Lookup from a bare file's literal on-disk name (e.g. `INPUT.json`) to the content type to report
+ * for it, used to read a listed bare key back directly (`getValue('INPUT.json')`). The empty-extension
+ * entry (`INPUT`) is intentionally excluded: an extensionless `INPUT` lookup goes through the
+ * `resolveValue` fallback probing instead, which already covers the extensionless file.
+ */
+const BARE_FILE_CONTENT_TYPES = new Map(
+ ALLOWED_BARE_FILES.flatMap((key) =>
+ BARE_FILE_FALLBACKS.filter(({ extension }) => extension !== '').map(
+ ({ extension, contentType }) => [`${key}${extension}`, contentType] as const,
+ ),
+ ),
+);
+
+/** Maps a bare file's on-disk name (e.g. `INPUT.json`) to its logical key (e.g. `INPUT`), for dedup. */
+const BARE_FILE_LOGICAL_KEYS = new Map(
+ ALLOWED_BARE_FILES.flatMap((key) =>
+ BARE_FILE_FALLBACKS.map(({ extension }) => [`${key}${extension}`, key] as const),
+ ),
+);
export interface KeyValueStoreClientOptions {
+ /** The user-facing storage name, or `undefined` for unnamed (alias / default) storages. */
name?: string;
- id?: string;
/**
- * The directory name to use on disk. When provided, takes precedence over `name` and `id`
- * for the directory path. This allows alias-opened storages to have a directory name
- * that differs from their metadata `name` (which is `undefined` for unnamed storages).
+ * The key used for cache lookup in {@link FileSystemStorageClient}. For named storages this equals
+ * the name; for alias (unnamed) storages it is the alias string. Falls back to the storage id.
*/
- directoryName?: string;
- baseStorageDirectory: string;
- client: FileSystemStorageClient;
+ cacheKey: string;
+ nativeClient: NativeFileSystemKeyValueStoreClient;
+ logger?: CrawleeLogger;
}
-export interface InternalKeyRecord {
- key: string;
- value: Buffer | string;
- contentType?: string;
- extension: string;
- filePath?: string;
-}
+/**
+ * A file-system key-value store client backed by the native `@crawlee/fs-storage-native` Rust
+ * extension.
+ *
+ * This adapter is a plain byte transport: values are written and read verbatim as `Buffer`s with a
+ * content type carried alongside them. Serializing arbitrary values into bytes and parsing them back
+ * is the {@apilink KeyValueStore} frontend codec's job, not this client's.
+ */
+export class KeyValueStoreClient extends CachedIdClient implements storage.KeyValueStoreClient {
+ readonly name?: string;
+ readonly cacheKey: string;
-export class KeyValueStoreClient extends BaseClient implements storage.KeyValueStoreClient {
- name?: string;
- /**
- * The key used for directory naming and cache lookup. For named storages, this equals
- * the name. For alias (unnamed) storages, this is the alias string. Falls back to id.
- */
- directoryName: string;
- createdAt = new Date();
- accessedAt = new Date();
- modifiedAt = new Date();
- keyValueStoreDirectory: string;
-
- private readonly keyValueEntries = new Map<string, StorageImplementation<InternalKeyRecord>>();
- private readonly client: FileSystemStorageClient;
+ private readonly nativeClient: NativeFileSystemKeyValueStoreClient;
constructor(options: KeyValueStoreClientOptions) {
- super(options.id ?? randomUUID());
+ super();
this.name = options.name;
- this.directoryName = options.directoryName ?? this.name ?? this.id;
- this.keyValueStoreDirectory = resolveWithinDirectory(options.baseStorageDirectory, this.directoryName);
- this.client = options.client;
+ this.cacheKey = options.cacheKey;
+ this.nativeClient = options.nativeClient;
}
- async getMetadata(): Promise<storage.KeyValueStoreInfo> {
- this.updateTimestamps(false);
- return this.toKeyValueStoreInfo();
+ get keyValueStoreDirectory(): string {
+ return this.nativeClient.pathToKvs;
}
- async drop(): Promise<void> {
- const storeIndex = this.client.keyValueStoreCache.findIndex((store) => store.id === this.id);
+ static async create(options: KeyValueStoreClientOptions): Promise<KeyValueStoreClient> {
+ const client = new KeyValueStoreClient(options);
+ client._cachedId = (await options.nativeClient.getMetadata()).id;
+ return client;
+ }
- if (storeIndex !== -1) {
- const [oldClient] = this.client.keyValueStoreCache.splice(storeIndex, 1);
- oldClient.keyValueEntries.clear();
+ async getMetadata(): Promise<storage.KeyValueStoreInfo> {
+ return this.nativeClient.getMetadata();
+ }
- await rm(oldClient.keyValueStoreDirectory, { recursive: true, force: true });
- }
+ async drop(): Promise<void> {
+ await this.nativeClient.dropStorage();
}
async purge(): Promise<void> {
- // Delete all entries
- const entriesToDelete = [...this.keyValueEntries.entries()];
- for (const [key, entry] of entriesToDelete) {
- this.keyValueEntries.delete(key);
- await entry.delete();
- }
+ await this.nativeClient.purge();
+ }
- this.updateTimestamps(true);
+ /**
+ * Remove every record from the store except the run input. Used by
+ * {@link FileSystemStorageClient.purge} to clean the default key-value store at the start of a run
+ * while preserving the run's input, matching the historical file-system storage behavior.
+ *
+ * The native `purge` keep-list matches by exact key with no extension globbing, so we pass every
+ * filename the input might live under (`INPUT`, `INPUT.json`, `INPUT.txt`, `INPUT.bin`).
+ */
+ async purgeExceptInput(): Promise<void> {
+ await this.nativeClient.purge(BARE_FILE_FALLBACKS.flatMap(({ extension }) => `INPUT${extension}`));
}
async listKeys(options: storage.KeyValueStoreListKeysOptions = {}): Promise<storage.KeyValueStoreListKeysResult> {
@@ -95,202 +137,174 @@ export class KeyValueStoreClient extends BaseClient implements storage.KeyValueS
})
.parse(options);
- const items: storage.KeyValueStoreItemData[] = [];
-
- for (const storageEntry of this.keyValueEntries.values()) {
- const record = await storageEntry.get();
-
- const size = Buffer.byteLength(record.value);
- items.push({
- key: record.key,
- size,
- contentType: record.contentType ?? (mime.contentType(record.extension) || 'application/octet-stream'),
- });
- }
-
- // Lexically sort to emulate API.
- items.sort((a, b) => a.key.localeCompare(b.key));
-
- let filteredItems = items.filter((item) => !prefix || item.key.startsWith(prefix));
-
- if (exclusiveStartKey) {
- const keyPos = filteredItems.findIndex((item) => item.key === exclusiveStartKey);
- if (keyPos === -1) {
- throw new Error(
- `exclusiveStartKey "${exclusiveStartKey}" was not found in the key-value store. ` +
- `This is likely a bug — the key may have been deleted between paginated listKeys calls.`,
- );
- }
- filteredItems = filteredItems.slice(keyPos + 1);
- }
-
- const isTruncated = limit !== undefined && filteredItems.length > limit;
- const pageItems = isTruncated ? filteredItems.slice(0, limit) : filteredItems;
- const nextExclusiveStartKey = isTruncated ? pageItems[pageItems.length - 1].key : undefined;
-
- this.updateTimestamps(false);
+ // Pass the bare-file fallbacks so out-of-band value files (e.g. a hand-placed `INPUT.json`)
+ // are enumerated alongside tracked records, under their actual on-disk name. The native reads
+ // everything it needs off the filesystem index — no per-file reads — so this stays cheap.
+ // The native `listKeys` already returns a self-describing page (items + pagination cursors)
+ // matching the `KeyValueStoreListKeysResult` contract, so we only post-process the items.
+ const page = await this.nativeClient.listKeys(exclusiveStartKey, limit, prefix, LIST_BARE_FALLBACKS);
+
+ const presentKeys = new Set(page.items.map((record) => record.key));
+
+ // A bare value file is listed under its actual name (`INPUT.json`), which already round-trips
+ // through `getValue`/`recordExists`. The only collision is a tracked record occupying the
+ // logical key itself (`INPUT`): it shadows the extension-bearing bare variants (`INPUT.json`
+ // etc.) for the same logical key, so drop those. The extensionless bare file *is* the logical
+ // key, so it is never a separate duplicate.
+ const items = page.items.filter((record) => {
+ const logicalKey = BARE_FILE_LOGICAL_KEYS.get(record.key);
+ const isExtensionBearingBareFile = logicalKey !== undefined && logicalKey !== record.key;
+ return !(isExtensionBearingBareFile && presentKeys.has(logicalKey));
+ });
return {
- items: pageItems,
- count: pageItems.length,
- limit: limit ?? pageItems.length,
- exclusiveStartKey,
- isTruncated,
- nextExclusiveStartKey,
+ items,
+ count: items.length,
+ limit: page.limit,
+ exclusiveStartKey: page.exclusiveStartKey,
+ isTruncated: page.isTruncated,
+ nextExclusiveStartKey: page.nextExclusiveStartKey,
};
}
/**
* Generates a public `file://` URL for accessing a specific record in the key-value store.
*
- * Returns `undefined` if the record does not exist or has no associated file path (i.e., it is not stored as a file).
+ * Returns `undefined` if the record does not exist.
* @param key The key of the record to generate the public URL for.
*/
async getPublicUrl(key: string): Promise<string | undefined> {
s.string().parse(key);
- const storageEntry = await this.keyValueEntries.get(key)?.get();
-
- return storageEntry?.filePath ? pathToFileURL(storageEntry.filePath).href : undefined;
+ // The native `getPublicUrl` stats the encoded path but does not probe bare-file extensions,
+ // so we resolve the on-disk key first (handling e.g. `INPUT` -> `INPUT.json`) and normalize
+ // the native `null`-for-missing result to the historical `undefined` contract.
+ const resolvedKey = await this.resolveExistingKey(key);
+ if (resolvedKey === undefined) {
+ return undefined;
+ }
+ return (await this.nativeClient.getPublicUrl(resolvedKey)) ?? undefined;
}
/**
- * Tests whether a record with the given key exists in the key-value store without retrieving its value.
+ * Tests whether a record with the given key exists without retrieving its value.
*
* @param key The queried record key.
- * @returns `true` if the record exists, `false` if it does not.
+ * @returns `true` if the record exists, `false` otherwise.
*/
async recordExists(key: string): Promise<boolean> {
s.string().parse(key);
-
- return this.keyValueEntries.has(key);
+ return (await this.resolveExistingKey(key)) !== undefined;
}
async getValue(key: string): Promise<storage.KeyValueStoreRecord | undefined> {
s.string().parse(key);
- const storageEntry = this.keyValueEntries.get(key);
+ const fallbacks = this.bareFallbacksFor(key);
+ const record = fallbacks
+ ? await this.nativeClient.resolveValue(key, fallbacks)
+ : await this.nativeClient.getValue(key);
- if (!storageEntry) {
- return undefined;
+ if (record) {
+ return {
+ key: record.key,
+ value: record.value,
+ contentType: record.contentType,
+ };
}
- const entry = await storageEntry.get();
-
- // Return raw bytes + verbatim content type. Parsing is the frontend's job (see the
- // KeyValueStore codec); this client is a plain byte transport. The mime fallback
- // reconstructs the content type for on-disk records that lack one.
- const record: storage.KeyValueStoreRecord = {
- key: entry.key,
- value: typeof entry.value === 'string' ? Buffer.from(entry.value, 'utf-8') : entry.value,
- // mime.contentType returns `false` for unknown extensions; fall back to undefined so the
- // frontend treats it as "no content type" rather than a bogus value.
- contentType: entry.contentType ?? (mime.contentType(entry.extension) || undefined),
- };
-
- this.updateTimestamps(false);
-
- return record;
+ return undefined;
}
async setValue(record: storage.KeyValueStoreInputRecord): Promise<void> {
+ // By the time a value reaches the client the frontend (KeyValueStore codec) has already
+ // serialized it: non-bytes become a `string`, everything else is a `Buffer`/typed array or a
+ // stream. So we only accept those shapes here — there is no JSON inference or `String(value)`
+ // coercion left to do.
s.object({
key: s.string().lengthGreaterThan(0),
value: s.union([
- s.null(),
s.string(),
- s.number(),
s.instance(Buffer),
s.instance(ArrayBuffer),
s.typedArray(),
- // disabling validation will make shapeshift only check the object given is an actual object, not null, nor array
+ // A stream is an object; disabling validation makes shapeshift only check it is a
+ // non-null, non-array object (the stream guard below does the real check).
s.object({}).setValidationEnabled(false),
]),
contentType: s.string().lengthGreaterThan(0).optional(),
}).parse(record);
- const { key } = record;
- let { value } = record;
- // The frontend (KeyValueStore codec) serializes the value and resolves its content type
- // before it reaches the client. We only need it here for on-disk extension bookkeeping.
+ const { key, value } = record;
+ // The frontend resolves the content type before it reaches the client; this client is a plain
+ // byte transport and does not infer content types.
const contentType = record.contentType ?? 'application/octet-stream';
- const extension = mime.extension(contentType) || DEFAULT_LOCAL_FILE_EXTENSION;
-
- // Draining a stream into a Buffer for storage is the client's responsibility.
+ // Stream the value straight to disk without buffering it all into memory. The native client
+ // consumes a Web `ReadableStream`, so convert the Node `Readable` we get from the frontend.
if (isStream(value)) {
- const chunks = [];
- for await (const chunk of value) {
- chunks.push(chunk);
- }
- value = Buffer.concat(chunks as Buffer[]);
+ const webStream = Readable.toWeb(value as Readable) as ReadableStream<Uint8Array>;
+ await this.nativeClient.setValueStream(key, webStream, contentType);
+ return;
}
- // The on-disk record holds raw bytes (or a string). Streams were drained above, so any
- // remaining non-string value is byte-like; normalize ArrayBuffer / typed-array views to Buffer.
- const normalizedValue: Buffer | string =
- typeof value === 'string' ? value : toBuffer(value as Buffer | ArrayBuffer | ArrayBufferView);
-
- const _record = {
- extension,
- key,
- value: normalizedValue,
- contentType,
- } satisfies InternalKeyRecord;
-
- const entry = createKeyValueStorageImplementation({
- storeDirectory: this.keyValueStoreDirectory,
- writeMetadata: this.client.writeMetadata,
- logger: this.client.logger,
- });
-
- await entry.update(_record);
-
- this.keyValueEntries.set(key, entry);
+ // Normalize the remaining (already-serialized) value into a Buffer for the native client.
+ const buffer = Buffer.isBuffer(value)
+ ? value
+ : value instanceof ArrayBuffer
+ ? Buffer.from(value)
+ : ArrayBuffer.isView(value)
+ ? Buffer.from(value.buffer, value.byteOffset, value.byteLength)
+ : Buffer.from(value as string);
- this.updateTimestamps(true);
+ await this.nativeClient.setValue(key, buffer, contentType);
}
async deleteValue(key: string): Promise<void> {
s.string().parse(key);
-
- const entry = this.keyValueEntries.get(key);
-
- if (entry) {
- this.keyValueEntries.delete(key);
- this.updateTimestamps(true);
- await entry.delete();
- }
+ await this.nativeClient.deleteValue(key);
}
- toKeyValueStoreInfo(): storage.KeyValueStoreInfo {
- return {
- id: this.id,
- name: this.name,
- accessedAt: this.accessedAt,
- createdAt: this.createdAt,
- modifiedAt: this.modifiedAt,
- };
+ /**
+ * Resolve `key` to the on-disk key that actually exists, or `undefined` if nothing does. Every
+ * key is checked against its tracked record; the run-input keys additionally fall back to
+ * out-of-band bare files, in which case the matched on-disk key is returned so callers like
+ * `getPublicUrl` point at the file that exists. Two run-input shapes are handled (see
+ * {@link bareFallbacksFor}): the logical `INPUT`, which probes the conventional extensions, and a
+ * literal bare filename such as `INPUT.json` as listed by `listKeys`, which resolves itself.
+ */
+ private async resolveExistingKey(key: string): Promise<string | undefined> {
+ const fallbacks = this.bareFallbacksFor(key);
+ if (fallbacks) {
+ return (
+ (await this.nativeClient.resolveExistingKey(
+ key,
+ fallbacks.map(({ extension }) => extension),
+ )) ?? undefined
+ );
+ }
+ return (await this.nativeClient.recordExists(key)) ? key : undefined;
}
- private updateTimestamps(hasBeenModified: boolean) {
- this.accessedAt = new Date();
-
- if (hasBeenModified) {
- this.modifiedAt = new Date();
+ /**
+ * The native `resolveValue`/`resolveExistingKey` bare-file fallbacks to use for `key`, or
+ * `undefined` if `key` is a plain tracked-record lookup with no bare-file probing.
+ *
+ * - The logical run-input key (`INPUT`) probes the full extension ladder (`INPUT`, `INPUT.json`,
+ * `INPUT.txt`, `INPUT.bin`), matching how Crawlee reads run input.
+ * - A literal bare filename as surfaced by `listKeys` (`INPUT.json`/`.txt`/`.bin`) resolves itself:
+ * the tracked record first, then the bare file at that exact name (a single empty-extension
+ * fallback), so a listed key round-trips through `getValue`/`recordExists`.
+ */
+ // eslint-disable-next-line class-methods-use-this
+ private bareFallbacksFor(key: string): { extension: string; contentType: string }[] | undefined {
+ if (ALLOWED_BARE_FILES.includes(key)) {
+ return BARE_FILE_FALLBACKS;
}
-
- const data = this.toKeyValueStoreInfo();
- scheduleBackgroundTask(
- {
- action: 'update-metadata',
- data,
- entityType: 'keyValueStores',
- entityDirectory: this.keyValueStoreDirectory,
- id: this.name ?? this.id,
- writeMetadata: this.client.writeMetadata,
- },
- this.client.logger,
- );
+ const contentType = BARE_FILE_CONTENT_TYPES.get(key);
+ if (contentType !== undefined) {
+ return [{ extension: '', contentType }];
+ }
+ return undefined;
}
}
diff --git a/packages/fs-storage/src/resource-clients/request-queue.ts b/packages/fs-storage/src/resource-clients/request-queue.ts
index e67c2fac1..494f7006a 100644
--- a/packages/fs-storage/src/resource-clients/request-queue.ts
+++ b/packages/fs-storage/src/resource-clients/request-queue.ts
@@ -1,17 +1,10 @@
-import { randomUUID } from 'node:crypto';
-import { rm } from 'node:fs/promises';
-import { resolve } from 'node:path';
-
import type * as storage from '@crawlee/types';
-import { AsyncQueue } from '@sapphire/async-queue';
+import type { CrawleeLogger } from '@crawlee/types';
import { s } from '@sapphire/shapeshift';
-import type { RequestQueueFileSystemEntry } from '../fs/request-queue/fs.js';
-import { scheduleBackgroundTask } from '../background-handler/index.js';
-import { createRequestQueueStorageImplementation } from '../fs/request-queue/index.js';
-import type { FileSystemStorageClient } from '../index.js';
-import { purgeNullsFromObject, resolveWithinDirectory, uniqueKeyToRequestId } from '../utils.js';
-import { BaseClient } from './common/base-client.js';
+import type { FileSystemRequestQueueClient as NativeFileSystemRequestQueueClient } from '@crawlee/fs-storage-native';
+
+import { CachedIdClient } from './cached-id-client.js';
const requestShape = s
.object({
@@ -25,7 +18,6 @@ const requestShape = s
.passthrough();
const requestShapeWithoutId = requestShape.omit(['id']);
-
const batchRequestShapeWithoutId = requestShapeWithoutId.array();
const requestOptionsShape = s.object({
@@ -33,294 +25,65 @@ const requestOptionsShape = s.object({
});
export interface RequestQueueClientOptions {
+ /** The user-facing storage name, or `undefined` for unnamed (alias / default) storages. */
name?: string;
- id?: string;
/**
- * The directory name to use on disk. When provided, takes precedence over `name` and `id`
- * for the directory path. This allows alias-opened storages to have a directory name
- * that differs from their metadata `name` (which is `undefined` for unnamed storages).
+ * The key used for cache lookup in {@link FileSystemStorageClient}. For named storages this equals
+ * the name; for alias (unnamed) storages it is the alias string. Falls back to the storage id.
*/
- directoryName?: string;
- baseStorageDirectory: string;
- client: FileSystemStorageClient;
-}
-
-export interface InternalRequest {
- id: string;
- orderNo: number | null;
- url: string;
- uniqueKey: string;
- method: storage.RequestSchema['method'];
- retryCount: number;
- json: string;
+ cacheKey: string;
+ nativeClient: NativeFileSystemRequestQueueClient;
+ logger?: CrawleeLogger;
}
/**
- * Default time (in seconds) for which a request fetched via {@link RequestQueueClient.fetchNextRequest}
- * stays locked (in progress) before it becomes available again. Aligns with the historical request queue
- * locking default. A consumer (e.g. a crawler) can raise this per queue via
- * {@link RequestQueueClient.setExpectedRequestProcessingTimeSecs}.
+ * A file-system request queue client backed by the native `@crawlee/fs-storage-native` Rust
+ * extension.
+ *
+ * Request ordering, in-progress locking and state persistence are all owned by the native client.
+ * This adapter forwards each operation and converts result shapes to the `@crawlee/types` interfaces.
*/
-const DEFAULT_REQUEST_LOCK_SECS = 3 * 60;
-
-/**
- * A request is "locked" (in progress) when its `orderNo` is pushed beyond the current time. The sign of
- * `orderNo` is preserved so the original forefront / normal ordering is restored once the lock expires
- * or the request is reclaimed.
- */
-function isRequestLocked(orderNo: number | null, now: number): boolean {
- return orderNo !== null && Math.abs(orderNo) > now;
-}
-
-export class RequestQueueClient extends BaseClient implements storage.RequestQueueClient {
- name?: string;
- /**
- * The key used for directory naming and cache lookup. For named storages, this equals
- * the name. For alias (unnamed) storages, this is the alias string. Falls back to id.
- */
- directoryName: string;
- createdAt = new Date();
- accessedAt = new Date();
- modifiedAt = new Date();
- handledRequestCount = 0;
- pendingRequestCount = 0;
- requestQueueDirectory: string;
- /**
- * Serializes every operation that reads-then-writes this client's shared queue state — the
- * `requests` map, the `forefrontRequestIds` array, the `inProgressRequestIds` set and the request
- * counts. Those mutations span `await` points (disk/storage I/O), so without this lock a concurrent
- * operation could interleave and corrupt them (e.g. a head scan pruning `forefrontRequestIds` while
- * `addBatchOfRequests` pushes to it). Held by every mutating method as well as by `isEmpty`/
- * `isFinished`, whose head scan also prunes `forefrontRequestIds`.
- */
- private readonly queueStateMutex = new AsyncQueue();
- private forefrontRequestIds: string[] = [];
-
- /**
- * IDs of requests this client has locked (fetched but not yet handled or reclaimed). Used by
- * {@link releaseOwnLocks} to free our own in-progress requests on process termination, so that
- * a crashed/migrated consumer does not block its requests for the full lock duration.
- */
- private readonly inProgressRequestIds = new Set<string>();
+export class RequestQueueClient extends CachedIdClient implements storage.RequestQueueClient {
+ readonly name?: string;
+ readonly cacheKey: string;
- private readonly requests = new Map<string, RequestQueueFileSystemEntry>();
- private readonly client: FileSystemStorageClient;
-
- /**
- * How long (in seconds) a request fetched from this client stays locked (in progress). Defaults to
- * {@link DEFAULT_REQUEST_LOCK_SECS} and is overridable via {@link setExpectedRequestProcessingTimeSecs}.
- */
- private lockSecs = DEFAULT_REQUEST_LOCK_SECS;
+ private readonly nativeClient: NativeFileSystemRequestQueueClient;
constructor(options: RequestQueueClientOptions) {
- super(options.id ?? randomUUID());
+ super();
this.name = options.name;
- this.directoryName = options.directoryName ?? this.name ?? this.id;
- this.requestQueueDirectory = resolveWithinDirectory(options.baseStorageDirectory, this.directoryName);
- this.client = options.client;
+ this.cacheKey = options.cacheKey;
+ this.nativeClient = options.nativeClient;
+ }
+
+ get requestQueueDirectory(): string {
+ return this.nativeClient.pathToRq;
+ }
+
+ static async create(options: RequestQueueClientOptions): Promise<RequestQueueClient> {
+ const client = new RequestQueueClient(options);
+ client._cachedId = (await options.nativeClient.getMetadata()).id;
+ return client;
}
/**
- * Applies how long {@link fetchNextRequest} locks a request before it becomes available again. The
- * caller (the `RequestQueue` frontend) owns the policy of what this value should be — this method
- * just applies it.
+ * Tells the native client how long (in seconds) a fetched request stays locked before it becomes
+ * available again.
*/
async setExpectedRequestProcessingTimeSecs(secs: number): Promise<void> {
- this.lockSecs = secs;
+ await this.nativeClient.setExpectedRequestProcessingTime(secs);
}
async getMetadata(): Promise<storage.RequestQueueInfo> {
- this.updateTimestamps(false);
- return this.toRequestQueueInfo();
+ return this.nativeClient.getMetadata();
}
async drop(): Promise<void> {
- // Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so a concurrent
- // operation cannot observe half-cleared state — e.g. a forefront id whose request has already been
- // removed, which `listPendingHead` would then dereference as `undefined`.
- await this.queueStateMutex.wait();
-
- try {
- const storeIndex = this.client.requestQueueCache.findIndex((queue) => queue.id === this.id);
-
- if (storeIndex !== -1) {
- const [oldClient] = this.client.requestQueueCache.splice(storeIndex, 1);
- oldClient.pendingRequestCount = 0;
- // Clear all in-memory state, consistent with `purge`. Clearing `requests` alone would
- // leave dangling ids in `forefrontRequestIds`/`inProgressRequestIds`, which a later head
- // scan would resolve to a missing request and dereference.
- oldClient.requests.clear();
- oldClient.forefrontRequestIds = [];
- oldClient.inProgressRequestIds.clear();
-
- await rm(oldClient.requestQueueDirectory, { recursive: true, force: true });
- }
- } finally {
- this.queueStateMutex.shift();
- }
+ await this.nativeClient.dropStorage();
}
async purge(): Promise<void> {
- // Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so a concurrent
- // operation cannot observe or repopulate half-cleared state across the `await` below.
- await this.queueStateMutex.wait();
-
- try {
- // Clear all in-memory state
- this.requests.clear();
- this.forefrontRequestIds = [];
- this.inProgressRequestIds.clear();
- this.handledRequestCount = 0;
- this.pendingRequestCount = 0;
-
- // Reset the lock duration back to the default so a value raised via
- // `setExpectedRequestProcessingTimeSecs` in an earlier run does not leak into a later one
- this.lockSecs = DEFAULT_REQUEST_LOCK_SECS;
-
- // Remove request files from disk but keep the directory
- const { readdir } = await import('node:fs/promises');
- const entries = await readdir(this.requestQueueDirectory).catch(() => []);
- for (const entry of entries) {
- if (entry !== '__metadata__.json') {
- await rm(resolve(this.requestQueueDirectory, entry), { force: true });
- }
- }
-
- this.updateTimestamps(true);
- } finally {
- this.queueStateMutex.shift();
- }
- }
-
- private *requestKeyIterator(): IterableIterator<string> {
- for (let i = this.forefrontRequestIds.length - 1; i >= 0; i--) {
- yield this.forefrontRequestIds[i];
- }
-
- for (const key of this.requests.keys()) {
- yield key;
- }
- }
-
- /**
- * Scans the queue and returns the pending head — requests that are neither handled nor currently
- * locked (in progress) — ordered by `orderNo`, deduplicated.
- *
- * When `detectLockedRequests` is set, the result also carries a `hasLockedRequests` flag telling
- * whether any unhandled-but-locked request was skipped along the way. This mirrors the Apify
- * platform shared client's `queueHasLockedRequests` signal: it lets {@link isFinished} distinguish
- * "no work left at all" from "work remains, but it is currently locked by some consumer (possibly
- * another process)". Without it, a consumer would consider the queue finished and let the crawler
- * shut down while another consumer still holds the last requests.
- *
- * Computing the flag is expensive: because a lock may sit anywhere in the queue, it forces a scan
- * of every pending entry even when only `limit` items are wanted. Callers that only need the head
- * (e.g. {@link fetchNextRequest}, {@link isEmpty}) leave it off so the scan can stop as soon as the
- * page is filled, keeping those calls O(head) instead of O(N).
- *
- * Lock state lives in the persisted `orderNo` (see {@link isRequestLocked}), so that processes
- * sharing the same on-disk queue observe each other's locks. We therefore re-read entries from
- * storage to obtain fresh lock state, except for entries we can cheaply rule out as permanently
- * handled via their cached `orderNo === null`.
- */
- private async listPendingHead(
- limit: number,
- detectLockedRequests = false,
- ): Promise<{ items: InternalRequest[]; hasLockedRequests?: boolean }> {
- const now = Date.now();
- const items: InternalRequest[] = [];
- let hasLockedRequests = false;
-
- // Tracks processed request IDs to avoid duplicates (request in both `forefrontRequestIds` and `requests`).
- const seenRequestIds = new Set<string>();
- // Tracks handled request IDs from `forefrontRequestIds` to be removed.
- const handledForefrontIds = new Set<string>();
-
- for (const requestId of this.requestKeyIterator()) {
- // Once the requested page is filled we can stop — unless the caller asked us to detect locked
- // requests and we have not yet seen one, in which case we must keep scanning to find them.
- if (items.length >= limit && (!detectLockedRequests || hasLockedRequests)) {
- break;
- }
-
- if (seenRequestIds.has(requestId)) {
- continue;
- }
-
- seenRequestIds.add(requestId);
-
- const storageEntry = this.requests.get(requestId)!;
-
- // Cheap rejection of permanently-handled requests using the cached `orderNo` (handled is a
- // terminal state, so the cached value can be trusted without re-reading from storage).
- if (storageEntry.orderNo === null) {
- if (this.forefrontRequestIds.includes(requestId)) {
- handledForefrontIds.add(requestId);
- }
- continue;
- }
-
- // Re-read from storage to get fresh lock state — another process may have locked (or handled)
- // this request since we last cached it.
- const request = await storageEntry.get(true);
-
- // Handled in the meantime.
- if (request.orderNo === null) {
- if (this.forefrontRequestIds.includes(requestId)) {
- handledForefrontIds.add(requestId);
- }
- continue;
- }
-
- // Locked (in progress) by us or another process — skip until the lock expires, but remember
- // that the queue is not truly empty.
- if (isRequestLocked(request.orderNo, now)) {
- hasLockedRequests = true;
- continue;
- }
-
- if (items.length < limit) {
- items.push(request);
- }
- }
-
- this.forefrontRequestIds = this.forefrontRequestIds.filter((id) => !handledForefrontIds.has(id));
-
- return {
- items: items.sort((a, b) => a.orderNo! - b.orderNo!),
- hasLockedRequests: detectLockedRequests ? hasLockedRequests : undefined,
- };
- }
-
- async fetchNextRequest(): Promise<storage.UpdateRequestSchema | undefined> {
- this.updateTimestamps(false);
-
- await this.queueStateMutex.wait();
-
- try {
- const {
- items: [head],
- } = await this.listPendingHead(1);
-
- if (!head) {
- return undefined;
- }
-
- // Lock the request by pushing its `orderNo` beyond the lock expiry, preserving the sign so
- // its original (forefront / normal) position is restored once the lock expires. The lock is
- // persisted so other processes sharing this queue will not fetch the same request.
- const lockExpiresAt = Date.now() + this.lockSecs * 1000;
- head.orderNo = lockExpiresAt * (head.orderNo! > 0 ? 1 : -1);
- await this.requests.get(head.id)!.update(head);
-
- // Remember that this client owns the lock, so we can release it on process termination
- // (see `releaseOwnLocks`) instead of leaving the request stuck until the lock expires.
- this.inProgressRequestIds.add(head.id);
-
- return this._jsonToRequest(head.json) ?? undefined;
- } finally {
- this.queueStateMutex.shift();
- }
+ await this.nativeClient.purge();
}
async addBatchOfRequests(
@@ -330,134 +93,37 @@ export class RequestQueueClient extends BaseClient implements storage.RequestQue
batchRequestShapeWithoutId.parse(requests);
requestOptionsShape.parse(options);
- // Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so that the
- // shared `requests` map, `forefrontRequestIds` array and request counts are not corrupted by a
- // concurrent operation interleaving at one of the `await` points below.
- await this.queueStateMutex.wait();
-
- try {
- const result: storage.BatchAddRequestsResult = {
- processedRequests: [],
- unprocessedRequests: [],
- };
-
- for (const model of requests) {
- const requestModel = this._createInternalRequest(model, options.forefront);
-
- const existingRequestWithIdEntry = this.requests.get(requestModel.id);
-
- if (existingRequestWithIdEntry) {
- const existingRequestWithId = await existingRequestWithIdEntry.get();
-
- result.processedRequests.push({
- requestId: existingRequestWithId.id,
- uniqueKey: existingRequestWithId.uniqueKey,
- wasAlreadyHandled: existingRequestWithId.orderNo === null,
- wasAlreadyPresent: true,
- });
-
- continue;
- }
-
- const newEntry = createRequestQueueStorageImplementation({
- requestId: requestModel.id,
- storeDirectory: this.requestQueueDirectory,
- });
-
- await newEntry.update(requestModel);
-
- this.requests.set(requestModel.id, newEntry);
-
- if (requestModel.orderNo) {
- this.pendingRequestCount += 1;
- } else {
- this.handledRequestCount += 1;
- }
-
- if (options.forefront) {
- this.forefrontRequestIds.push(requestModel.id);
- }
-
- result.processedRequests.push({
- requestId: requestModel.id,
- uniqueKey: requestModel.uniqueKey,
- // We return wasAlreadyHandled: false even though the request may
- // have been added as handled, because that's how API behaves.
- wasAlreadyHandled: false,
- wasAlreadyPresent: false,
- });
- }
-
- this.updateTimestamps(true);
+ const response = await this.nativeClient.addBatchOfRequests(
+ requests as unknown as Record<string, unknown>[],
+ options.forefront ?? false,
+ );
- return result;
- } finally {
- this.queueStateMutex.shift();
- }
+ // `processedRequests` is structurally identical between the native and `storage` types, so it
+ // passes through unchanged. `unprocessedRequests` only differs in that the native `method` is
+ // a plain `string`, hence the cast to the narrower `AllowedHttpMethods` union.
+ return {
+ processedRequests: response.processedRequests,
+ unprocessedRequests: response.unprocessedRequests as storage.BatchAddRequestsResult['unprocessedRequests'],
+ };
}
async getRequest(uniqueKey: string): Promise<storage.UpdateRequestSchema | undefined> {
s.string().parse(uniqueKey);
- this.updateTimestamps(false);
- const id = uniqueKeyToRequestId(uniqueKey);
- const json = (await this.requests.get(id)?.get())?.json;
- return this._jsonToRequest(json);
+ // The native client tags requests with an internal `orderNo`; it's harmless to leak, so we
+ // hand the request back as-is rather than copying it just to drop one undeclared property.
+ // The native client already returns `undefined` for a missing request, matching this contract.
+ return (await this.nativeClient.getRequest(uniqueKey)) as storage.UpdateRequestSchema | undefined;
+ }
+
+ async fetchNextRequest(): Promise<storage.UpdateRequestSchema | undefined> {
+ return (await this.nativeClient.fetchNextRequest()) as storage.UpdateRequestSchema | undefined;
}
async markRequestAsHandled(request: storage.UpdateRequestSchema): Promise<storage.QueueOperationInfo | undefined> {
requestShape.parse(request);
- this.updateTimestamps(false);
-
- // Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so the shared
- // `requests` map, `inProgressRequestIds` set and request counts stay consistent across the
- // `await` points below.
- await this.queueStateMutex.wait();
-
- try {
- const id = uniqueKeyToRequestId(request.uniqueKey);
-
- const existingEntry = this.requests.get(id);
- const existingRequest = await existingEntry?.get();
-
- // The request must exist to be marked as handled. We intentionally do NOT require it to still
- // be locked: a consumer whose processing outlived the lock (slow handler, GC/event-loop pause,
- // a low `setExpectedRequestProcessingTimeSecs`) must still be able to mark its request handled,
- // otherwise the request would be handed out again forever and the queue would never finish.
- if (!existingRequest) {
- return undefined;
- }
-
- // A handled request has `orderNo === null`. Marking it again is an idempotent no-op.
- const wasAlreadyHandled = existingRequest.orderNo === null;
-
- const handledAt = request.handledAt ?? new Date().toISOString();
- const requestModel = this._createInternalRequest({ ...request, handledAt }, false);
-
- const newEntry = createRequestQueueStorageImplementation({
- requestId: id,
- storeDirectory: this.requestQueueDirectory,
- });
- await newEntry.update(requestModel);
- this.requests.set(id, newEntry);
-
- // The request is no longer in progress for this client.
- this.inProgressRequestIds.delete(id);
-
- if (!wasAlreadyHandled) {
- this.pendingRequestCount -= 1;
- this.handledRequestCount += 1;
- }
-
- this.updateTimestamps(true);
-
- return {
- requestId: id,
- wasAlreadyHandled,
- wasAlreadyPresent: true,
- };
- } finally {
- this.queueStateMutex.shift();
- }
+ return (
+ (await this.nativeClient.markRequestAsHandled(request as unknown as Record<string, unknown>)) ?? undefined
+ );
}
async reclaimRequest(
@@ -466,214 +132,28 @@ export class RequestQueueClient extends BaseClient implements storage.RequestQue
): Promise<storage.QueueOperationInfo | undefined> {
requestShape.parse(request);
requestOptionsShape.parse(options);
- this.updateTimestamps(false);
-
- // Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so the shared
- // `requests` map, `forefrontRequestIds` array and `inProgressRequestIds` set stay consistent
- // across the `await` points below.
- await this.queueStateMutex.wait();
-
- try {
- const id = uniqueKeyToRequestId(request.uniqueKey);
-
- const existingEntry = this.requests.get(id);
- const existingRequest = await existingEntry?.get();
-
- // The request must exist and not already be handled to be reclaimed. As with
- // `markRequestAsHandled`, we do NOT require it to still be locked — a consumer that failed
- // after its lock expired must still be able to return the request to the queue (e.g. to honor
- // a `forefront` reorder), rather than have the reclaim silently dropped.
- if (!existingRequest || existingRequest.orderNo === null) {
- return undefined;
- }
-
- // Reclaiming resets the `orderNo` to a fresh timestamp, releasing the lock and restoring the
- // request to the queue (at the front if `forefront`).
- const requestModel = this._createInternalRequest(request, options.forefront);
-
- const newEntry = createRequestQueueStorageImplementation({
- requestId: id,
- storeDirectory: this.requestQueueDirectory,
- });
- await newEntry.update(requestModel);
- this.requests.set(id, newEntry);
-
- // The request is no longer in progress for this client.
- this.inProgressRequestIds.delete(id);
-
- if (options.forefront) {
- this.forefrontRequestIds.push(id);
- }
-
- this.updateTimestamps(true);
-
- return {
- requestId: id,
- wasAlreadyHandled: false,
- wasAlreadyPresent: true,
- };
- } finally {
- this.queueStateMutex.shift();
- }
+ return (
+ (await this.nativeClient.reclaimRequest(
+ request as unknown as Record<string, unknown>,
+ options.forefront ?? false,
+ )) ?? undefined
+ );
}
async isEmpty(): Promise<boolean> {
- this.updateTimestamps(false);
-
- // "Empty" means there is nothing left to fetch right now — i.e. the next `fetchNextRequest`
- // would return `null`. Requests that are currently locked (in progress) are intentionally NOT
- // counted here: they are not fetchable, so the queue is empty from a consumer's point of view.
- // Whether those in-progress requests mean crawling is not yet done is a separate question,
- // answered by `isFinished`.
- //
- // `listPendingHead` prunes `forefrontRequestIds` as it scans, so we must hold the queue-state mutex to avoid
- // racing a concurrent mutator (e.g. `addBatchOfRequests`) at its `await` points.
- await this.queueStateMutex.wait();
-
- try {
- const { items } = await this.listPendingHead(1);
- return items.length === 0;
- } finally {
- this.queueStateMutex.shift();
- }
+ return this.nativeClient.isEmpty();
}
async isFinished(): Promise<boolean> {
- this.updateTimestamps(false);
-
- // The queue is finished only when there is nothing left to fetch AND nothing currently locked
- // (in progress) by any consumer. Counting locked requests is what allows a crawler to keep
- // waiting while another consumer (possibly another process sharing this on-disk queue) still
- // holds the last requests, instead of finishing prematurely. This mirrors the Apify platform
- // shared client's `queueHasLockedRequests` signal.
- //
- // Detecting locked requests requires a full scan, hence the `detectLockedRequests` flag — unlike
- // `fetchNextRequest`/`isEmpty`, which only need the head and can stop early.
- //
- // `listPendingHead` prunes `forefrontRequestIds` as it scans, so we must hold the queue-state mutex to avoid
- // racing a concurrent mutator (e.g. `addBatchOfRequests`) at its `await` points.
- await this.queueStateMutex.wait();
-
- try {
- const { items, hasLockedRequests } = await this.listPendingHead(1, true);
- return items.length === 0 && !hasLockedRequests;
- } finally {
- this.queueStateMutex.shift();
- }
+ return this.nativeClient.isFinished();
}
/**
- * Release the locks of all requests this client currently has in progress, returning them to the
- * queue so they can be fetched again immediately.
- *
- * On the Apify platform, a run's locks are released automatically when it migrates or aborts. This
- * client, however, persists fake locks via `orderNo`, so it needs to clean up after itself.
- * `FileSystemStorageClient.teardown()` calls this for every cached queue at the end of the process so that
- * a fetched-but-unhandled request is not stuck (waiting for its lock to expire) for the next consumer
- * of the same on-disk queue.
+ * Persist the native client's in-memory state to disk. Called by
+ * {@link FileSystemStorageClient.teardown} so that fetched-but-unhandled requests are not stuck
+ * for the next consumer of the same on-disk queue.
*/
- async releaseOwnLocks(): Promise<void> {
- if (this.inProgressRequestIds.size === 0) {
- return;
- }
-
- await this.queueStateMutex.wait();
-
- try {
- const now = Date.now();
-
- for (const id of this.inProgressRequestIds) {
- const entry = this.requests.get(id);
- const request = await entry?.get(true);
-
- // Skip requests that were handled or whose lock already expired/changed — we only undo
- // locks we still hold.
- if (!request || !isRequestLocked(request.orderNo, now)) {
- continue;
- }
-
- // Reset the lock to a fresh timestamp, preserving the sign so the request keeps its
- // original (forefront / normal) ordering once unlocked.
- request.orderNo = now * (request.orderNo! > 0 ? 1 : -1);
- await entry!.update(request);
- }
-
- this.inProgressRequestIds.clear();
- this.updateTimestamps(true);
- } finally {
- this.queueStateMutex.shift();
- }
- }
-
- toRequestQueueInfo(): storage.RequestQueueInfo {
- return {
- accessedAt: this.accessedAt,
- createdAt: this.createdAt,
- handledRequestCount: this.handledRequestCount,
- id: this.id,
- modifiedAt: this.modifiedAt,
- name: this.name,
- pendingRequestCount: this.pendingRequestCount,
- totalRequestCount: this.requests.size,
- };
- }
-
- private updateTimestamps(hasBeenModified: boolean) {
- this.accessedAt = new Date();
-
- if (hasBeenModified) {
- this.modifiedAt = new Date();
- }
-
- const data = {
- ...this.toRequestQueueInfo(),
- forefrontRequestIds: this.forefrontRequestIds,
- };
-
- scheduleBackgroundTask(
- {
- action: 'update-metadata',
- data,
- entityType: 'requestQueues',
- entityDirectory: this.requestQueueDirectory,
- id: this.name ?? this.id,
- writeMetadata: this.client.writeMetadata,
- },
- this.client.logger,
- );
- }
-
- private _jsonToRequest<T>(requestJson?: string): T | undefined {
- if (!requestJson) return undefined;
- const request = JSON.parse(requestJson);
- return purgeNullsFromObject(request);
- }
-
- private _createInternalRequest(request: storage.RequestSchema, forefront?: boolean): InternalRequest {
- const orderNo = this._calculateOrderNo(request, forefront);
- const id = uniqueKeyToRequestId(request.uniqueKey);
-
- if (request.id && request.id !== id) {
- throw new Error('Request ID does not match its uniqueKey.');
- }
-
- const json = JSON.stringify({ ...request, id });
- return {
- id,
- json,
- method: request.method,
- orderNo,
- retryCount: request.retryCount ?? 0,
- uniqueKey: request.uniqueKey,
- url: request.url,
- };
- }
-
- private _calculateOrderNo(request: storage.RequestSchema, forefront?: boolean) {
- if (request.handledAt) return null;
-
- const timestamp = Date.now();
-
- return forefront ? -timestamp : timestamp;
+ async persistState(): Promise<void> {
+ await this.nativeClient.persistState();
}
}
diff --git a/packages/fs-storage/src/utils.ts b/packages/fs-storage/src/utils.ts
index e4695949f..834b07606 100644
--- a/packages/fs-storage/src/utils.ts
+++ b/packages/fs-storage/src/utils.ts
@@ -1,72 +1,7 @@
-import { createHash } from 'node:crypto';
-import { resolve, sep } from 'node:path';
-
-import type * as storage from '@crawlee/types';
-import { isBuffer, isStream, toBuffer } from '@crawlee/utils';
-
-import { REQUEST_ID_LENGTH } from './consts.js';
-
-/**
- * Resolves `segment` against `baseDirectory` and ensures the result stays within `baseDirectory`.
- * Storage names and record keys are used as filesystem path components, so a value containing `..`
- * or an absolute path could otherwise escape the intended directory.
- */
-export function resolveWithinDirectory(baseDirectory: string, segment: string): string {
- const base = resolve(baseDirectory);
- const resolved = resolve(base, segment);
-
- if (resolved !== base && !resolved.startsWith(`${base}${sep}`)) {
- throw new Error(
- `"${segment}" is not allowed because it would resolve outside of the storage directory. ` +
- `Storage names and record keys must not contain path traversal segments ("..") or absolute paths.`,
- );
- }
-
- return resolved;
-}
-
-/**
- * Removes all properties with a null value
- * from the provided object.
- */
-export function purgeNullsFromObject<T>(object: T): T {
- if (object && typeof object === 'object' && !Array.isArray(object)) {
- for (const [key, value] of Object.entries(object)) {
- if (value === null) Reflect.deleteProperty(object as Record<string, unknown>, key);
- }
- }
-
- return object;
-}
-
-/**
- * Creates a standard request ID (same as Platform).
- */
-export function uniqueKeyToRequestId(uniqueKey: string): string {
- const str = createHash('sha256')
- .update(uniqueKey)
- .digest('base64')
- .replace(/(\+|\/|=)/g, '');
-
- return str.length > REQUEST_ID_LENGTH ? str.slice(0, REQUEST_ID_LENGTH) : str;
-}
-
-export { isBuffer, isStream, toBuffer };
-
-export type BackgroundHandlerReceivedMessage = BackgroundHandlerUpdateMetadataMessage;
-
-export type BackgroundHandlerUpdateMetadataMessage =
- | MetadataUpdate<'datasets', storage.DatasetInfo>
- | MetadataUpdate<'keyValueStores', storage.KeyValueStoreInfo>
- | MetadataUpdate<'requestQueues', storage.RequestQueueInfo>;
-
-type EntityType = 'datasets' | 'keyValueStores' | 'requestQueues';
-
-interface MetadataUpdate<Type extends EntityType, DataType> {
- entityType: Type;
- id: string;
- action: 'update-metadata';
- entityDirectory: string;
- data: DataType;
- writeMetadata: boolean;
+export function isStream(value: any): boolean {
+ return (
+ typeof value === 'object' &&
+ value &&
+ ['on', 'pipe'].every((key) => key in value && typeof value[key] === 'function')
+ );
}
diff --git a/packages/fs-storage/test/__shared__.ts b/packages/fs-storage/test/__shared__.ts
deleted file mode 100644
index 5a2769b87..000000000
--- a/packages/fs-storage/test/__shared__.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { access } from 'node:fs/promises';
-import { setTimeout } from 'node:timers/promises';
-
-export async function waitTillWrittenToDisk(path: string): Promise<void> {
- try {
- await access(path);
- return undefined;
- } catch {
- await setTimeout(50);
- return waitTillWrittenToDisk(path);
- }
-}
diff --git a/packages/fs-storage/test/async-iteration.test.ts b/packages/fs-storage/test/async-iteration.test.ts
index 7cd551641..5cbf0cc69 100644
--- a/packages/fs-storage/test/async-iteration.test.ts
+++ b/packages/fs-storage/test/async-iteration.test.ts
@@ -71,7 +71,8 @@ describe('Async iteration support', () => {
kvStore = await storage.createKeyValueStoreClient({ name: 'async-iteration-kvs' });
for (const key of keys) {
- // The client is a byte-transport: pass serialized bytes + content type.
+ // The client is a byte transport: values arrive already serialized from the frontend
+ // codec, so pass a string + content type rather than a raw object.
await kvStore.setValue({
key,
value: JSON.stringify({ data: key }),
diff --git a/packages/fs-storage/test/fs-fallback.test.ts b/packages/fs-storage/test/fs-fallback.test.ts
index 56d42f3da..e8ecb2177 100644
--- a/packages/fs-storage/test/fs-fallback.test.ts
+++ b/packages/fs-storage/test/fs-fallback.test.ts
@@ -1,11 +1,23 @@
import { randomUUID } from 'node:crypto';
-import { rm, writeFile } from 'node:fs/promises';
+import { mkdir, rm, writeFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import { FileSystemStorageClient } from '@crawlee/fs-storage';
import type { KeyValueStoreRecord } from '@crawlee/types';
-import { ensureDir } from 'fs-extra/esm';
+// The storage is backed by the native `@crawlee/fs-storage-native` extension, which only serves
+// key-value records it has written itself (tracked via per-record metadata sidecars). The
+// `KeyValueStoreClient` adapter layers a fallback on top so that value files placed into the store
+// directory out-of-band — e.g. a hand-written or platform-provided `INPUT.json` — are still readable.
+// These tests pin both the store-identity metadata fallback and that bare-file fallback.
+//
+// The client is a plain byte transport: bare-file reads return the raw bytes plus a content type
+// inferred from the file extension (falling back to the native `application/octet-stream` when there
+// is none). Parsing those bytes — and surfacing any error from a malformed value — is the
+// `KeyValueStore` frontend's job, so the client does not validate them. Bare files are readable by
+// known key and are also enumerated by `listKeys` under their actual on-disk name (e.g. a bare
+// `INPUT.json` is listed as `INPUT.json` and reads back under that key), while the logical `INPUT`
+// lookup keeps resolving the same bare file.
describe('fallback to fs for reading', () => {
const tmpLocation = resolve(import.meta.dirname, './tmp/fs-fallback');
const storage = new FileSystemStorageClient({
@@ -15,8 +27,8 @@ describe('fallback to fs for reading', () => {
const expectedFsDate = new Date(2022, 0, 1);
beforeAll(async () => {
- // Create "default" key-value store and give it an entry
- await ensureDir(resolve(storage.keyValueStoresDirectory, 'default'));
+ // "default" store: metadata file + a bare INPUT.json (no per-record metadata sidecar).
+ await mkdir(resolve(storage.keyValueStoresDirectory, 'default'), { recursive: true });
await writeFile(
resolve(storage.keyValueStoresDirectory, 'default/__metadata__.json'),
JSON.stringify({
@@ -32,29 +44,38 @@ describe('fallback to fs for reading', () => {
JSON.stringify({ foo: 'bar but from fs' }),
);
- await ensureDir(resolve(storage.keyValueStoresDirectory, 'other'));
+ // "other" store: a bare INPUT.json with no store metadata file at all.
+ await mkdir(resolve(storage.keyValueStoresDirectory, 'other'), { recursive: true });
await writeFile(
resolve(storage.keyValueStoresDirectory, 'other/INPUT.json'),
JSON.stringify({ foo: 'bar but from fs' }),
);
- await ensureDir(resolve(storage.keyValueStoresDirectory, 'no-ext'));
+ // "no-ext" store: a value file with no extension — loaded as raw text.
+ await mkdir(resolve(storage.keyValueStoresDirectory, 'no-ext'), { recursive: true });
await writeFile(
resolve(storage.keyValueStoresDirectory, 'no-ext/INPUT'),
JSON.stringify({ foo: 'bar but from fs' }),
);
- await ensureDir(resolve(storage.keyValueStoresDirectory, 'invalid-json'));
+ // "invalid-json" store: a malformed INPUT.json — ignored.
+ await mkdir(resolve(storage.keyValueStoresDirectory, 'invalid-json'), { recursive: true });
await writeFile(resolve(storage.keyValueStoresDirectory, 'invalid-json/INPUT.json'), '{');
+
+ // "non-input" store: a bare value file under a non-INPUT key. The bare-file fallback is scoped
+ // to the run input, so this file is NOT readable out-of-band — only `INPUT`-keyed bare files are.
+ await mkdir(resolve(storage.keyValueStoresDirectory, 'non-input'), { recursive: true });
+ await writeFile(
+ resolve(storage.keyValueStoresDirectory, 'non-input/some-key.json'),
+ JSON.stringify({ foo: 'bar but from fs' }),
+ );
});
afterAll(async () => {
await rm(tmpLocation, { force: true, recursive: true });
});
- // POST INIT //
-
- test('attempting to read "default" key value store with "__metadata__" present should read from fs', async () => {
+ test('reads store identity from the on-disk metadata, and a bare INPUT.json value', async () => {
const defaultStore = await storage.createKeyValueStoreClient({ name: 'default' });
const defaultStoreInfo = await defaultStore.getMetadata();
@@ -71,7 +92,7 @@ describe('fallback to fs for reading', () => {
});
});
- test('attempting to read "other" key value store with no "__metadata__" present should read from fs, even if accessed without generating id first', async () => {
+ test('reads a bare INPUT.json even with no store metadata present', async () => {
const otherStore = await storage.createKeyValueStoreClient({ name: 'other' });
// Byte transport: raw bytes out, parsing is the frontend's job.
@@ -83,28 +104,210 @@ describe('fallback to fs for reading', () => {
});
});
- test('attempting to read "default_2" key value store that has no data on disk should still be accessible after creation', async () => {
+ test('a store with no data on disk is still accessible after creation', async () => {
const default2Store = await storage.createKeyValueStoreClient({ name: 'default_2' });
const info = await default2Store.getMetadata();
expect(info.name).toEqual('default_2');
});
- test('attempting to read "no-ext" key value store should load the missing extension file correctly', async () => {
+ test('loads a value file with no extension as raw bytes with a generic content type', async () => {
const noExtStore = await storage.createKeyValueStoreClient({ name: 'no-ext' });
- // Byte transport: the no-extension fallback also returns raw bytes now, not a decoded string.
+ // Byte transport: the no-extension fallback returns raw bytes. With no extension to infer a
+ // content type from, the native client reports the generic `application/octet-stream`.
const input = await noExtStore.getValue('INPUT');
expect(input).toStrictEqual<KeyValueStoreRecord>({
key: 'INPUT',
value: Buffer.from(JSON.stringify({ foo: 'bar but from fs' })),
- contentType: 'text/plain',
+ contentType: 'application/octet-stream',
});
});
- test('attempting to read "invalid-json" key value store should ignore the invalid "INPUT" json file', async () => {
+ test('returns an invalid-JSON bare value file verbatim', async () => {
const invalidJsonStore = await storage.createKeyValueStoreClient({ name: 'invalid-json' });
+ // Byte transport: the client no longer validates parseability. Malformed JSON is returned
+ // verbatim as raw bytes; parsing (and any resulting error) is the KeyValueStore frontend's job.
const input = await invalidJsonStore.getValue('INPUT');
- expect(input).toBeUndefined();
+ expect(input).toStrictEqual<KeyValueStoreRecord>({
+ key: 'INPUT',
+ value: Buffer.from('{'),
+ contentType: 'application/json; charset=utf-8',
+ });
+ });
+
+ test('bare files are visible to recordExists, getPublicUrl, and listKeys', async () => {
+ const otherStore = await storage.createKeyValueStoreClient({ name: 'other' });
+
+ expect(await otherStore.recordExists('INPUT')).toBe(true);
+ expect(await otherStore.recordExists('does-not-exist')).toBe(false);
+
+ const url = await otherStore.getPublicUrl('INPUT');
+ expect(url).toMatch(/^file:\/\/.*INPUT\.json$/);
+
+ // A bare `INPUT.json` is enumerated under its actual on-disk name, not the logical `INPUT`.
+ const { items } = await otherStore.listKeys();
+ expect(items.map((item) => item.key)).toContain('INPUT.json');
+ });
+
+ test('a listed bare key round-trips through getValue / recordExists / getPublicUrl', async () => {
+ const otherStore = await storage.createKeyValueStoreClient({ name: 'other' });
+
+ // The key `listKeys` reports for a bare file must be readable back verbatim, while the logical
+ // `INPUT` lookup keeps resolving the same bare file (matching how Crawlee reads run input).
+ const [listed] = (await otherStore.listKeys()).items.map((item) => item.key);
+ expect(listed).toBe('INPUT.json');
+
+ const expected: KeyValueStoreRecord = {
+ key: 'INPUT.json',
+ value: Buffer.from(JSON.stringify({ foo: 'bar but from fs' })),
+ contentType: 'application/json; charset=utf-8',
+ };
+ expect(await otherStore.getValue('INPUT.json')).toStrictEqual(expected);
+ expect(await otherStore.recordExists('INPUT.json')).toBe(true);
+ expect(await otherStore.getPublicUrl('INPUT.json')).toMatch(/^file:\/\/.*INPUT\.json$/);
+
+ // The logical key still resolves the same underlying file (reported under the requested key).
+ expect(await otherStore.getValue('INPUT')).toStrictEqual({ ...expected, key: 'INPUT' });
+ });
+
+ test('the bare-file fallback is scoped to INPUT: a non-INPUT bare file is ignored', async () => {
+ const nonInputStore = await storage.createKeyValueStoreClient({ name: 'non-input' });
+
+ // `some-key.json` sits on disk with no metadata sidecar. Only `INPUT` keys probe bare files,
+ // so this is invisible to every read path: it has no tracked record, and the `.json` extension
+ // probing that would resolve a bare `INPUT` is never attempted for other keys.
+ expect(await nonInputStore.getValue('some-key')).toBeUndefined();
+ expect(await nonInputStore.recordExists('some-key')).toBe(false);
+ expect(await nonInputStore.getPublicUrl('some-key')).toBeUndefined();
+
+ // `listKeys` only surfaces bare files for the run-input keys, so `some-key` is not enumerated.
+ const { items } = await nonInputStore.listKeys();
+ expect(items.map((item) => item.key)).not.toContain('some-key');
+ });
+
+ test('a tracked INPUT record shadows the bare INPUT.json variant in listKeys', async () => {
+ const collisionStore = await storage.createKeyValueStoreClient({ name: 'input-collision' });
+
+ // Write a tracked `INPUT` record (value file + metadata sidecar), then drop a sidecar-less bare
+ // `INPUT.json` next to it. Both belong to the logical key `INPUT`; the tracked record wins, so
+ // only `INPUT` is listed and the bare `INPUT.json` variant is suppressed.
+ await collisionStore.setValue({ key: 'INPUT', value: 'tracked', contentType: 'text/plain; charset=utf-8' });
+ await writeFile(
+ resolve(storage.keyValueStoresDirectory, 'input-collision/INPUT.json'),
+ JSON.stringify({ foo: 'bare' }),
+ );
+
+ const keys = (await collisionStore.listKeys()).items.map((item) => item.key);
+ expect(keys).toContain('INPUT');
+ expect(keys).not.toContain('INPUT.json');
+ });
+});
+
+// For each run-input bare file: the on-disk filename, the literal key that reads it directly, the
+// content type the client reports (`.json`/`.txt` infer from the extension; the extensionless `INPUT`
+// and `.bin` report the synthesized `application/octet-stream`), and a unique payload so a read can be
+// proven to have returned *this* file and not a sibling.
+const BARE_VARIANTS = [
+ { file: 'INPUT', literalKey: 'INPUT', contentType: 'application/octet-stream' },
+ { file: 'INPUT.json', literalKey: 'INPUT.json', contentType: 'application/json; charset=utf-8' },
+ { file: 'INPUT.txt', literalKey: 'INPUT.txt', contentType: 'text/plain; charset=utf-8' },
+ { file: 'INPUT.bin', literalKey: 'INPUT.bin', contentType: 'application/octet-stream' },
+].map((variant) => ({ ...variant, payload: `payload of ${variant.file}` }));
+
+// Each run-input bare file must be reachable by exactly two keys — the logical `INPUT` (which probes
+// the `['', '.json', '.txt', '.bin']` ladder, first match wins) and its own literal on-disk name — and
+// NOT via a *different* extension's literal name (a bare `INPUT.txt` is not `INPUT.json`). Here each
+// variant lives in its own store so the logical-`INPUT` lookup resolves it unambiguously.
+describe('run-input bare-file reachability (one variant per store)', () => {
+ const tmpLocation = resolve(import.meta.dirname, './tmp/fs-reachability-isolated');
+ const storage = new FileSystemStorageClient({ localDataDirectory: tmpLocation });
+
+ const storeNameFor = (file: string) => `reach-${file.toLowerCase().replace('.', '-')}`;
+
+ beforeAll(async () => {
+ for (const { file, payload } of BARE_VARIANTS) {
+ const dir = resolve(storage.keyValueStoresDirectory, storeNameFor(file));
+ await mkdir(dir, { recursive: true });
+ await writeFile(resolve(dir, file), payload);
+ }
+ });
+
+ afterAll(async () => {
+ await rm(tmpLocation, { force: true, recursive: true });
+ });
+
+ describe.each(BARE_VARIANTS)('a bare $file', ({ file, literalKey, contentType, payload }) => {
+ // Keys that should resolve this variant: the logical `INPUT` and the file's own literal name
+ // (deduplicated — the extensionless variant's literal key *is* `INPUT`).
+ const reachableKeys = [...new Set(['INPUT', literalKey])];
+ // The literal names of the *other* extensions, which must never resolve this variant.
+ const unreachableKeys = BARE_VARIANTS.map((variant) => variant.literalKey).filter(
+ (key) => !reachableKeys.includes(key),
+ );
+
+ test.each(reachableKeys)('is reachable via %s', async (key) => {
+ const store = await storage.createKeyValueStoreClient({ name: storeNameFor(file) });
+
+ expect(await store.getValue(key)).toStrictEqual<KeyValueStoreRecord>({
+ key,
+ value: Buffer.from(payload),
+ contentType,
+ });
+ expect(await store.recordExists(key)).toBe(true);
+ expect(await store.getPublicUrl(key)).toMatch(new RegExp(`^file://.*${file.replace('.', '\\.')}$`));
+ });
+
+ test.each(unreachableKeys)('is not reachable via %s', async (key) => {
+ const store = await storage.createKeyValueStoreClient({ name: storeNameFor(file) });
+
+ expect(await store.getValue(key)).toBeUndefined();
+ expect(await store.recordExists(key)).toBe(false);
+ expect(await store.getPublicUrl(key)).toBeUndefined();
+ });
+ });
+});
+
+// The sharper cross-talk check: with *all four* variants in one store, each literal key must read back
+// its own bytes (never a sibling's), and the logical `INPUT` must resolve the first ladder match — the
+// extensionless `INPUT`. This is what fails if literal-name probing ever widens to other extensions.
+describe('run-input bare-file reachability (all variants in one store)', () => {
+ const tmpLocation = resolve(import.meta.dirname, './tmp/fs-reachability-shared');
+ const storage = new FileSystemStorageClient({ localDataDirectory: tmpLocation });
+
+ beforeAll(async () => {
+ const dir = resolve(storage.keyValueStoresDirectory, 'all-variants');
+ await mkdir(dir, { recursive: true });
+ for (const { file, payload } of BARE_VARIANTS) {
+ await writeFile(resolve(dir, file), payload);
+ }
+ });
+
+ afterAll(async () => {
+ await rm(tmpLocation, { force: true, recursive: true });
+ });
+
+ test.each(BARE_VARIANTS)(
+ 'the literal key $literalKey reads its own file, not a sibling',
+ async ({ literalKey, contentType, payload }) => {
+ const store = await storage.createKeyValueStoreClient({ name: 'all-variants' });
+
+ expect(await store.getValue(literalKey)).toStrictEqual<KeyValueStoreRecord>({
+ key: literalKey,
+ value: Buffer.from(payload),
+ contentType,
+ });
+ },
+ );
+
+ test('the logical INPUT key resolves the extensionless file (first ladder match)', async () => {
+ const store = await storage.createKeyValueStoreClient({ name: 'all-variants' });
+
+ const extensionless = BARE_VARIANTS.find((variant) => variant.file === 'INPUT')!;
+ expect(await store.getValue('INPUT')).toStrictEqual<KeyValueStoreRecord>({
+ key: 'INPUT',
+ value: Buffer.from(extensionless.payload),
+ contentType: extensionless.contentType,
+ });
});
});
diff --git a/packages/fs-storage/test/key-value-store/special-keys.test.ts b/packages/fs-storage/test/key-value-store/special-keys.test.ts
new file mode 100644
index 000000000..3d4311372
--- /dev/null
+++ b/packages/fs-storage/test/key-value-store/special-keys.test.ts
@@ -0,0 +1,55 @@
+import { rm } from 'node:fs/promises';
+import { resolve } from 'node:path';
+
+import { FileSystemStorageClient } from '@crawlee/fs-storage';
+
+// Keys may contain characters that are unsafe in a file name (e.g. `.` or `/`). The adapter must
+// round-trip such keys correctly through `setValue` / `getValue` / `listKeys` regardless of how the
+// underlying native client encodes them on disk. The concrete on-disk filenames are the native
+// client's concern and are not asserted here.
+//
+// The resource client is a plain byte transport — value serialization/parsing lives in the
+// `KeyValueStore` frontend codec, not here. These tests therefore pass already-serialized bytes in
+// and expect raw bytes back out, exercising only what this layer is responsible for.
+describe('KeyValueStore handles keys with file-name-unsafe characters', () => {
+ const tmpLocation = resolve(import.meta.dirname, '../tmp/special-keys');
+
+ afterAll(async () => {
+ await rm(tmpLocation, { force: true, recursive: true });
+ });
+
+ test('round-trips a key containing a dot', async () => {
+ const storage = new FileSystemStorageClient({ localDataDirectory: tmpLocation });
+ const store = await storage.createKeyValueStoreClient({ name: 'dotted' });
+
+ const body = '<html lang="en"><body>Hi there!</body></html>';
+ await store.setValue({
+ key: 'jibberish2.html',
+ value: body,
+ contentType: 'text/html',
+ });
+
+ const record = await store.getValue('jibberish2.html');
+ expect(record?.value).toStrictEqual(Buffer.from(body));
+ expect(record?.contentType).toBe('text/html');
+
+ expect(await store.recordExists('jibberish2.html')).toBe(true);
+ const { items } = await store.listKeys();
+ expect(items.map((item) => item.key)).toContain('jibberish2.html');
+ });
+
+ test('round-trips a key containing a slash', async () => {
+ const storage = new FileSystemStorageClient({ localDataDirectory: tmpLocation });
+ const store = await storage.createKeyValueStoreClient({ name: 'slashed' });
+
+ const body = JSON.stringify({ ok: true });
+ await store.setValue({ key: 'nested/key', value: body, contentType: 'application/json; charset=utf-8' });
+
+ const record = await store.getValue('nested/key');
+ expect(record?.value).toStrictEqual(Buffer.from(body));
+
+ expect(await store.recordExists('nested/key')).toBe(true);
+ const { items } = await store.listKeys();
+ expect(items.map((item) => item.key)).toContain('nested/key');
+ });
+});
diff --git a/packages/fs-storage/test/key-value-store/stream.test.ts b/packages/fs-storage/test/key-value-store/stream.test.ts
index 0b4ff7709..85d2743c3 100644
--- a/packages/fs-storage/test/key-value-store/stream.test.ts
+++ b/packages/fs-storage/test/key-value-store/stream.test.ts
@@ -1,12 +1,19 @@
+import { rm } from 'node:fs/promises';
+import { resolve } from 'node:path';
import { Readable } from 'node:stream';
import { FileSystemStorageClient } from '@crawlee/fs-storage';
describe('KeyValueStore should drain streams when setting records', () => {
- const storage = new FileSystemStorageClient({});
+ const localDataDirectory = resolve(__dirname, './tmp/stream');
+ const storage = new FileSystemStorageClient({ localDataDirectory });
const fsStream = Readable.from([Buffer.from('hello'), Buffer.from('world')]);
+ afterAll(async () => {
+ await rm(localDataDirectory, { force: true, recursive: true });
+ });
+
test('should drain stream', async () => {
const defaultStore = await storage.createKeyValueStoreClient({ name: 'default' });
diff --git a/packages/fs-storage/test/key-value-store/with-extension.test.ts b/packages/fs-storage/test/key-value-store/with-extension.test.ts
deleted file mode 100644
index 30f0061fc..000000000
--- a/packages/fs-storage/test/key-value-store/with-extension.test.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { existsSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { emptyDirSync } from 'fs-extra/esm';
-
-import { createKeyValueStorageImplementation } from '../../src/fs/key-value-store/index.js';
-
-describe('KeyValueStore should append extension only when needed', () => {
- const mockImageBuffer = Buffer.from('This is a test image', 'utf8');
-
- afterAll(() => emptyDirSync('tmp'));
-
- test('should append extension when needed (jpg)', async () => {
- const testDir = resolve('tmp', 'test_no_extension');
- const storage = createKeyValueStorageImplementation({
- storeDirectory: testDir,
- writeMetadata: true,
- });
- await storage.update({
- key: 'jibberish',
- value: mockImageBuffer,
- contentType: 'image/jpeg',
- extension: 'jpeg',
- });
-
- expect(existsSync(resolve(testDir, 'jibberish.jpeg'))).toBeTruthy();
- expect(existsSync(resolve(testDir, 'jibberish'))).toBeFalsy();
- });
-
- test('should append extension when needed (html)', async () => {
- const testDir = resolve('tmp', 'test_no_extension');
- const storage = createKeyValueStorageImplementation({
- storeDirectory: testDir,
- writeMetadata: true,
- });
- await storage.update({
- key: 'jibberish2',
- value: '<html lang="en"><body>Hi there!</body></html>',
- contentType: 'text/html',
- extension: 'html',
- });
-
- expect(existsSync(resolve(testDir, 'jibberish2.html'))).toBeTruthy();
- expect(existsSync(resolve(testDir, 'jibberish2'))).toBeFalsy();
- });
-
- test('should not append extension when already available', async () => {
- const testDir = resolve('tmp', 'test_extension');
- const storage = createKeyValueStorageImplementation({
- storeDirectory: testDir,
- writeMetadata: true,
- });
- await storage.update({
- key: 'jibberish.jpg',
- value: mockImageBuffer,
- contentType: 'image/jpeg',
- extension: 'jpeg',
- });
-
- expect(existsSync(resolve(testDir, 'jibberish.jpg'))).toBeTruthy();
- expect(existsSync(resolve(testDir, 'jibberish.jpg.jpeg'))).toBeFalsy();
- });
-
- test('should not append extension when already available', async () => {
- const testDir = resolve('tmp', 'test_extension');
- const storage = createKeyValueStorageImplementation({
- storeDirectory: testDir,
- writeMetadata: true,
- });
- await storage.update({
- key: 'jibberish2.html',
- value: '<html lang="en"><body>Hi there!</body></html>',
- contentType: 'text/html',
- extension: 'html',
- });
-
- expect(existsSync(resolve(testDir, 'jibberish2.html'))).toBeTruthy();
- expect(existsSync(resolve(testDir, 'jibberish2.html.html'))).toBeFalsy();
- });
-});
diff --git a/packages/fs-storage/test/no-crash-on-big-buffers.test.ts b/packages/fs-storage/test/no-crash-on-big-buffers.test.ts
index 0ecdd4bdf..aa1ad7d5a 100644
--- a/packages/fs-storage/test/no-crash-on-big-buffers.test.ts
+++ b/packages/fs-storage/test/no-crash-on-big-buffers.test.ts
@@ -1,5 +1,8 @@
-// https://github.com/apify/crawlee/issues/1732
-// https://github.com/apify/crawlee/issues/1710
+// Regression guard for https://github.com/apify/crawlee/issues/1732 and
+// https://github.com/apify/crawlee/issues/1710 — storing a large binary value must not crash (the old
+// pure-TS implementation overflowed the stack on big buffers). The native client does the actual
+// write; the adapter passes a `Buffer` straight through. Here we verify a large buffer round-trips
+// through `setValue` / `getValue` via the public API.
import { rm } from 'node:fs/promises';
import { resolve } from 'node:path';
@@ -7,11 +10,9 @@ import { resolve } from 'node:path';
import { FileSystemStorageClient } from '@crawlee/fs-storage';
import type { KeyValueStoreClient } from '@crawlee/types';
-describe('FileSystemStorageClient should not crash when saving a big buffer', () => {
+describe('KeyValueStore round-trips a large binary value', () => {
const tmpLocation = resolve(import.meta.dirname, './tmp/no-buffer-crash');
- const storage = new FileSystemStorageClient({
- localDataDirectory: tmpLocation,
- });
+ const storage = new FileSystemStorageClient({ localDataDirectory: tmpLocation });
let store: KeyValueStoreClient;
@@ -23,21 +24,19 @@ describe('FileSystemStorageClient should not crash when saving a big buffer', ()
await rm(tmpLocation, { force: true, recursive: true });
});
- test('should not crash when saving a big buffer', async () => {
- let zip: Buffer;
-
- if (process.env.CRAWLEE_DIFFICULT_TESTS) {
- const numbers = Array.from([...Array(18_100_000).keys()].map((i) => i * 3_000_000));
-
- zip = Buffer.from([...numbers]);
- } else {
- zip = Buffer.from([...Array(100_000)].map((i) => i * 8));
+ test('stores and reads back a large buffer without crashing', async () => {
+ const size = process.env.CRAWLEE_DIFFICULT_TESTS ? 50_000_000 : 1_000_000;
+ const zip = Buffer.alloc(size);
+ // Fill with a non-trivial, verifiable pattern.
+ for (let i = 0; i < size; i += 1) {
+ zip[i] = i % 256;
}
- try {
- await store.setValue({ key: 'owo.zip', value: zip });
- } catch (err) {
- expect(err).not.toBeDefined();
- }
+ await store.setValue({ key: 'owo.zip', value: zip, contentType: 'application/zip' });
+
+ const record = await store.getValue('owo.zip');
+ expect(Buffer.isBuffer(record?.value)).toBe(true);
+ expect((record!.value as Buffer).length).toBe(size);
+ expect(record!.value.equals(zip)).toBe(true);
});
});
diff --git a/packages/fs-storage/test/request-queue/adapter.test.ts b/packages/fs-storage/test/request-queue/adapter.test.ts
new file mode 100644
index 000000000..d4e39b636
--- /dev/null
+++ b/packages/fs-storage/test/request-queue/adapter.test.ts
@@ -0,0 +1,142 @@
+import { rm } from 'node:fs/promises';
+import { resolve } from 'node:path';
+
+import { FileSystemStorageClient } from '@crawlee/fs-storage';
+import type { RequestQueueClient } from '@crawlee/types';
+
+// The request-queue ordering, locking and finished-ness semantics are owned (and exhaustively tested)
+// by the native `@crawlee/fs-storage-native` extension. These tests cover what the *adapter* adds on
+// top: mapping requests and operation results between the native shapes and the `@crawlee/types`
+// interfaces, and a thin lifecycle smoke test to catch wiring regressions.
+describe('RequestQueueClient adapter', () => {
+ const tmpLocation = resolve(import.meta.dirname, './tmp/adapter');
+
+ let requestQueue: RequestQueueClient;
+ let testIndex = 0;
+
+ beforeEach(async () => {
+ // Isolate each test with its own storage directory and queue so persisted counts/requests from
+ // one test cannot leak into the next.
+ const storage = new FileSystemStorageClient({ localDataDirectory: resolve(tmpLocation, `${testIndex++}`) });
+ requestQueue = await storage.createRequestQueueClient({ name: 'adapter' });
+ });
+
+ afterAll(async () => {
+ await rm(tmpLocation, { force: true, recursive: true });
+ });
+
+ test('fetchNextRequest returns a request with its fields preserved', async () => {
+ await requestQueue.addBatchOfRequests([
+ { url: 'http://example.com/1', uniqueKey: '1', userData: { foo: 'bar' } },
+ ]);
+
+ const request = await requestQueue.fetchNextRequest();
+
+ expect(request).toBeDefined();
+ expect(request!.url).toBe('http://example.com/1');
+ expect(request!.uniqueKey).toBe('1');
+ expect(request!.userData).toStrictEqual({ foo: 'bar' });
+ // `id` is a real request field and is surfaced.
+ expect(typeof request!.id).toBe('string');
+ });
+
+ test('getRequest looks up by uniqueKey', async () => {
+ await requestQueue.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
+
+ const request = await requestQueue.getRequest('1');
+
+ expect(request?.url).toBe('http://example.com/1');
+ expect(await requestQueue.getRequest('does-not-exist')).toBeUndefined();
+ });
+
+ test('addBatchOfRequests maps the native response into BatchAddRequestsResult', async () => {
+ const result = await requestQueue.addBatchOfRequests([
+ { url: 'http://example.com/1', uniqueKey: '1' },
+ { url: 'http://example.com/1', uniqueKey: '1' }, // duplicate uniqueKey
+ ]);
+
+ expect(result.unprocessedRequests).toStrictEqual([]);
+ expect(result.processedRequests).toHaveLength(2);
+
+ const [first, second] = result.processedRequests;
+ expect(first).toMatchObject({ uniqueKey: '1', wasAlreadyPresent: false, wasAlreadyHandled: false });
+ expect(typeof first.requestId).toBe('string');
+ // The second one is deduplicated by uniqueKey.
+ expect(second).toMatchObject({ uniqueKey: '1', wasAlreadyPresent: true });
+ });
+
+ test('markRequestAsHandled maps the native result into QueueOperationInfo', async () => {
+ await requestQueue.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
+ const request = await requestQueue.fetchNextRequest();
+
+ const info = await requestQueue.markRequestAsHandled({ ...request!, id: request!.id! });
+
+ expect(info).toMatchObject({ requestId: request!.id, wasAlreadyHandled: true, wasAlreadyPresent: true });
+ });
+
+ test('getMetadata maps native metadata into RequestQueueInfo (Date timestamps, counts)', async () => {
+ await requestQueue.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
+ const request = await requestQueue.fetchNextRequest();
+ await requestQueue.markRequestAsHandled({ ...request!, id: request!.id! });
+
+ const metadata = await requestQueue.getMetadata();
+
+ // Native count fields are surfaced...
+ expect(metadata.handledRequestCount).toBe(1);
+ expect(metadata.pendingRequestCount).toBe(0);
+ expect(metadata.totalRequestCount).toBe(1);
+ // ...ISO-string timestamps are converted to `Date`...
+ expect(metadata.createdAt).toBeInstanceOf(Date);
+ expect(metadata.modifiedAt).toBeInstanceOf(Date);
+ expect(metadata.accessedAt).toBeInstanceOf(Date);
+ // ...and the adapter synthesizes the framework-shape fields.
+ expect(metadata.id).toEqual(expect.any(String));
+ });
+
+ test('a request added as already-handled counts toward handledRequestCount', async () => {
+ // Regression guard: re-inserting an already-handled request must not be counted as pending.
+ await requestQueue.addBatchOfRequests([
+ { url: 'http://example.com/1', uniqueKey: '1', handledAt: new Date().toISOString() },
+ ]);
+
+ const metadata = await requestQueue.getMetadata();
+ expect(metadata.handledRequestCount).toBe(1);
+ expect(metadata.pendingRequestCount).toBe(0);
+ });
+
+ test('forwards `forefront` so a later request can be served first', async () => {
+ await requestQueue.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
+ await requestQueue.addBatchOfRequests([{ url: 'http://example.com/2', uniqueKey: '2' }], { forefront: true });
+
+ // We only assert that the `forefront` flag reaches the native client (the forefront request is
+ // served before the regular one); the exact ordering algorithm is the native client's concern.
+ const first = await requestQueue.fetchNextRequest();
+ expect(first!.uniqueKey).toBe('2');
+ });
+
+ test('lifecycle: fetch marks in-progress, handle empties and finishes the queue', async () => {
+ await requestQueue.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
+ expect(await requestQueue.isEmpty()).toBe(false);
+
+ const request = await requestQueue.fetchNextRequest();
+ // Fetched (in-progress): nothing left to fetch, but not finished until handled.
+ expect(await requestQueue.isEmpty()).toBe(true);
+ expect(await requestQueue.isFinished()).toBe(false);
+ // While in progress it is not handed out again.
+ expect(await requestQueue.fetchNextRequest()).toBeUndefined();
+
+ await requestQueue.markRequestAsHandled({ ...request!, id: request!.id! });
+ expect(await requestQueue.isFinished()).toBe(true);
+ });
+
+ test('reclaimRequest returns an in-progress request to the queue', async () => {
+ await requestQueue.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
+
+ const first = await requestQueue.fetchNextRequest();
+ const info = await requestQueue.reclaimRequest({ ...first!, id: first!.id! });
+ expect(info).toMatchObject({ requestId: first!.id, wasAlreadyHandled: false });
+
+ const again = await requestQueue.fetchNextRequest();
+ expect(again!.uniqueKey).toBe('1');
+ });
+});
diff --git a/packages/fs-storage/test/request-queue/dangling-forefront-on-reload.test.ts b/packages/fs-storage/test/request-queue/dangling-forefront-on-reload.test.ts
deleted file mode 100644
index 032fb799e..000000000
--- a/packages/fs-storage/test/request-queue/dangling-forefront-on-reload.test.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import { randomUUID } from 'node:crypto';
-import { rm, writeFile } from 'node:fs/promises';
-import { resolve } from 'node:path';
-
-import { FileSystemStorageClient } from '@crawlee/fs-storage';
-import type { InternalRequest } from '@crawlee/fs-storage/src/resource-clients/request-queue';
-import type { RequestSchema } from '@crawlee/types';
-import { ensureDir } from 'fs-extra/esm';
-
-/**
- * On reload, `forefrontRequestIds` is restored verbatim from the persisted metadata, while the
- * `requests` map is rebuilt only from request files actually found and parseable on disk. If a
- * persisted forefront id has no backing request file (deleted, never written, or corrupt JSON), it
- * would dangle: a later head scan resolves it to a missing request and dereferences `undefined`.
- * The reload must drop such ids so head scans stay safe.
- */
-describe('Request queue reload drops dangling forefront ids without a backing request file', () => {
- const tmpLocation = resolve(import.meta.dirname, './tmp/req-queue-dangling-forefront');
-
- const writeMetadata = async (storage: FileSystemStorageClient, forefrontRequestIds: string[]) => {
- await ensureDir(resolve(storage.requestQueuesDirectory, 'default'));
- await writeFile(
- resolve(storage.requestQueuesDirectory, 'default/__metadata__.json'),
- JSON.stringify({
- id: randomUUID(),
- name: 'default',
- createdAt: new Date(2022, 0, 1),
- accessedAt: new Date(2022, 0, 1),
- modifiedAt: new Date(2022, 0, 1),
- pendingRequestCount: 1,
- handledRequestCount: 0,
- forefrontRequestIds,
- }),
- );
- };
-
- const writeValidRequest = async (storage: FileSystemStorageClient, id: string, url: string, uniqueKey: string) => {
- await writeFile(
- resolve(storage.requestQueuesDirectory, `default/${id}.json`),
- JSON.stringify({
- id,
- orderNo: -1,
- url,
- uniqueKey,
- method: 'GET',
- retryCount: 0,
- json: JSON.stringify({ id, url, uniqueKey } satisfies RequestSchema),
- } satisfies InternalRequest),
- );
- };
-
- afterEach(async () => {
- await rm(tmpLocation, { force: true, recursive: true });
- });
-
- test('a forefront id with no request file on disk does not crash a later head scan', async () => {
- const storage = new FileSystemStorageClient({ localDataDirectory: tmpLocation });
-
- // The metadata references a forefront id 'missing' for which no request file exists on disk.
- await writeMetadata(storage, ['missing']);
-
- const queue = await storage.createRequestQueueClient({ name: 'default' });
-
- // None of these head scans must throw, and an empty/finished queue must be reported.
- await expect(queue.isEmpty()).resolves.toBe(true);
- await expect(queue.isFinished()).resolves.toBe(true);
- await expect(queue.fetchNextRequest()).resolves.toBeUndefined();
- });
-
- test('a valid forefront request is still served while a dangling sibling id is dropped', async () => {
- const storage = new FileSystemStorageClient({ localDataDirectory: tmpLocation });
-
- // Two forefront ids in metadata: one backed by a real file, one dangling.
- await writeMetadata(storage, ['missing', '123']);
- await writeValidRequest(storage, '123', 'http://example.com', 'owo');
-
- const queue = await storage.createRequestQueueClient({ name: 'default' });
-
- // The dangling id is dropped; the valid forefront request is still fetchable.
- const first = await queue.fetchNextRequest();
- expect(first).not.toBeNull();
- expect(first!.url).toEqual('http://example.com');
-
- expect(await queue.fetchNextRequest()).toBeUndefined();
- });
-});
diff --git a/packages/fs-storage/test/request-queue/forefront.test.ts b/packages/fs-storage/test/request-queue/forefront.test.ts
deleted file mode 100644
index 4608f6477..000000000
--- a/packages/fs-storage/test/request-queue/forefront.test.ts
+++ /dev/null
@@ -1,266 +0,0 @@
-import { rm } from 'node:fs/promises';
-import { resolve } from 'node:path';
-import { setTimeout as sleep } from 'node:timers/promises';
-
-import { FileSystemStorageClient } from '@crawlee/fs-storage';
-import type { RequestQueueClient } from '@crawlee/types';
-
-/**
- * Drains the queue via `fetchNextRequest`, marking each request as handled, and returns the
- * pathnames in the order they were served.
- */
-async function fetchOrder(client: RequestQueueClient): Promise<string[]> {
- const order: string[] = [];
-
- for (let request = await client.fetchNextRequest(); request != null; request = await client.fetchNextRequest()) {
- order.push(new URL(request.url).pathname);
- await client.markRequestAsHandled({ ...request, id: request.id! });
- }
-
- return order;
-}
-
-describe('RequestQueue respects `forefront` when fetching requests', () => {
- const storage = new FileSystemStorageClient({});
-
- let requestQueue: RequestQueueClient;
-
- beforeEach(async () => {
- requestQueue = await storage.createRequestQueueClient({ name: 'forefront' });
- });
-
- afterEach(async () => {
- await requestQueue.drop();
- });
-
- test('requests without `forefront` respect sequential order', async () => {
- await requestQueue.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
- // Waiting a few ms is required since we use Date.now() to compute orderNo
- await sleep(2);
- await requestQueue.addBatchOfRequests([{ url: 'http://example.com/2', uniqueKey: '2' }]);
-
- expect(await fetchOrder(requestQueue)).toEqual(['/1', '/2']);
- });
-
- test('`forefront` requests are prioritized', async () => {
- await requestQueue.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
- // Waiting a few ms is required since we use Date.now() to compute orderNo
- await sleep(2);
- await requestQueue.addBatchOfRequests([{ url: 'http://example.com/2', uniqueKey: '2' }], { forefront: true });
-
- expect(await fetchOrder(requestQueue)).toEqual(['/2', '/1']);
- });
-
- test('global `forefront` ordering is preserved across several inserts', async () => {
- await requestQueue.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
- await sleep(2);
- await requestQueue.addBatchOfRequests([{ url: 'http://example.com/2', uniqueKey: '2' }], { forefront: true });
- await sleep(2);
- await requestQueue.addBatchOfRequests([{ url: 'http://example.com/3', uniqueKey: '3' }], { forefront: true });
-
- expect(await fetchOrder(requestQueue)).toEqual(['/3', '/2', '/1']);
- });
-
- test('`addBatchOfRequests` respects `forefront`', async () => {
- await requestQueue.addBatchOfRequests([{ url: 'http://example.com/3', uniqueKey: '3' }]);
-
- await sleep(2);
-
- await requestQueue.addBatchOfRequests(
- [
- { url: 'http://example.com/1', uniqueKey: '1' },
- { url: 'http://example.com/2', uniqueKey: '2' },
- ],
- { forefront: true },
- );
-
- const order = await fetchOrder(requestQueue);
- expect(order).toHaveLength(3);
- // Both forefront requests come before the original; their relative order is arbitrary.
- expect(order[2]).toEqual('/3');
- expect([
- ['/2', '/1', '/3'],
- ['/1', '/2', '/3'],
- ]).toContainEqual(order);
- });
-
- test('a reclaimed request is served again', async () => {
- await requestQueue.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
-
- const first = await requestQueue.fetchNextRequest();
- expect(first!.url).toEqual('http://example.com/1');
-
- // Reclaiming a fetched (in-progress) request returns it to the queue.
- await requestQueue.reclaimRequest({ ...first!, id: first!.id! });
-
- const second = await requestQueue.fetchNextRequest();
- expect(second!.url).toEqual('http://example.com/1');
- });
-
- test('a reclaimed `forefront` request jumps to the front', async () => {
- await requestQueue.addBatchOfRequests([
- { url: 'http://example.com/1', uniqueKey: '1' },
- { url: 'http://example.com/2', uniqueKey: '2' },
- ]);
-
- const first = await requestQueue.fetchNextRequest();
- expect(first!.url).toEqual('http://example.com/1');
-
- await requestQueue.reclaimRequest({ ...first!, id: first!.id! }, { forefront: true });
-
- const next = await requestQueue.fetchNextRequest();
- expect(next!.url).toEqual('http://example.com/1');
- });
-
- test('handling all requests empties the queue', async () => {
- await requestQueue.addBatchOfRequests([
- { url: 'http://example.com/1', uniqueKey: '1' },
- { url: 'http://example.com/2', uniqueKey: '2' },
- { url: 'http://example.com/3', uniqueKey: '3' },
- ]);
-
- expect(await requestQueue.isEmpty()).toBe(false);
-
- await fetchOrder(requestQueue);
-
- expect(await requestQueue.isEmpty()).toBe(true);
- expect(await requestQueue.fetchNextRequest()).toBeUndefined();
- });
-
- test('a fetched (locked) request leaves the queue empty but unfinished until it is handled', async () => {
- await requestQueue.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
-
- const request = await requestQueue.fetchNextRequest();
- expect(request).not.toBeNull();
-
- // The request is locked (in progress), not handled. There is nothing left to fetch, so the
- // queue is empty — but it is not finished. The "not finished" signal is what stops a crawler
- // from shutting down while a request is still being processed by some consumer.
- expect(await requestQueue.isEmpty()).toBe(true);
- expect(await requestQueue.isFinished()).toBe(false);
-
- await requestQueue.markRequestAsHandled({ ...request!, id: request!.id! });
- expect(await requestQueue.isEmpty()).toBe(true);
- expect(await requestQueue.isFinished()).toBe(true);
- });
-});
-
-describe('RequestQueue locks fetched requests', () => {
- const storage = new FileSystemStorageClient({});
-
- let requestQueue: RequestQueueClient;
-
- beforeEach(async () => {
- requestQueue = await storage.createRequestQueueClient({ name: 'locking' });
- });
-
- afterEach(async () => {
- await requestQueue.drop();
- });
-
- test('a fetched request becomes available again after its lock expires', async () => {
- vitest.useFakeTimers();
-
- try {
- await requestQueue.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
-
- const first = await requestQueue.fetchNextRequest();
- expect(first!.uniqueKey).toBe('1');
-
- // While locked, the request is not handed out again.
- expect(await requestQueue.fetchNextRequest()).toBeUndefined();
-
- // After the lock expires (default 3 minutes), the request is fetchable again — this is what
- // prevents a crashed consumer from blocking its requests forever.
- vitest.advanceTimersByTime(3 * 60 * 1000 + 1000);
-
- const retried = await requestQueue.fetchNextRequest();
- expect(retried!.uniqueKey).toBe('1');
- } finally {
- vitest.useRealTimers();
- }
- });
-});
-
-describe('RequestQueue locking is visible across clients sharing on-disk storage', () => {
- const tmpLocation = resolve(import.meta.dirname, './tmp/req-queue-cross-process');
- // Two independent storage instances over the same directory emulate two separate processes.
- const storageA = new FileSystemStorageClient({ localDataDirectory: tmpLocation });
- const storageB = new FileSystemStorageClient({ localDataDirectory: tmpLocation });
-
- afterAll(async () => {
- await rm(tmpLocation, { force: true, recursive: true });
- });
-
- test('two clients on the same queue never fetch the same request', async () => {
- const clientA = await storageA.createRequestQueueClient({ name: 'shared' });
- await clientA.addBatchOfRequests([
- { url: 'http://example.com/1', uniqueKey: '1' },
- { url: 'http://example.com/2', uniqueKey: '2' },
- ]);
-
- const clientB = await storageB.createRequestQueueClient({ name: 'shared' });
-
- const fromA = await clientA.fetchNextRequest();
- const fromB = await clientB.fetchNextRequest();
-
- expect(fromA).not.toBeNull();
- expect(fromB).not.toBeNull();
- // The lock written by one client is observed by the other, so they get distinct requests.
- expect(fromA!.uniqueKey).not.toBe(fromB!.uniqueKey);
-
- // Both requests are now locked, so neither client can fetch anything more.
- expect(await clientA.fetchNextRequest()).toBeUndefined();
- expect(await clientB.fetchNextRequest()).toBeUndefined();
-
- await clientA.drop();
- });
-
- test('a client does not report the queue finished while another client holds the last request', async () => {
- const clientA = await storageA.createRequestQueueClient({ name: 'shared-is-empty' });
- await clientA.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
-
- const clientB = await storageB.createRequestQueueClient({ name: 'shared-is-empty' });
-
- // Client A fetches (and thus locks) the only request.
- const fromA = await clientA.fetchNextRequest();
- expect(fromA).not.toBeNull();
-
- // Client B has nothing it can fetch right now, so from its point of view the queue is empty...
- expect(await clientB.fetchNextRequest()).toBeUndefined();
- expect(await clientB.isEmpty()).toBe(true);
- // ...but the request still exists and is merely locked by A, so B must NOT consider the queue
- // finished — otherwise the crawler driving B could shut down while A is still processing.
- expect(await clientB.isFinished()).toBe(false);
-
- // Once A handles the request, it is gone for good and B sees a finished queue.
- await clientA.markRequestAsHandled({ ...fromA!, id: fromA!.id! });
- expect(await clientB.isEmpty()).toBe(true);
- expect(await clientB.isFinished()).toBe(true);
-
- await clientA.drop();
- });
-
- test('teardown releases this client locks so another client can fetch immediately', async () => {
- const clientA = await storageA.createRequestQueueClient({ name: 'shared-teardown' });
- await clientA.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
-
- // Client A fetches (locks) the request, then the process tears down without handling it.
- const fromA = await clientA.fetchNextRequest();
- expect(fromA).not.toBeNull();
-
- const clientB = await storageB.createRequestQueueClient({ name: 'shared-teardown' });
- // While A holds the lock, B cannot fetch the request.
- expect(await clientB.fetchNextRequest()).toBeUndefined();
-
- // Tearing down A's storage releases its locks (instead of leaving them until the 3-minute
- // expiry), so B can pick the request up right away.
- await storageA.teardown();
-
- const fromB = await clientB.fetchNextRequest();
- expect(fromB).not.toBeNull();
- expect(fromB!.uniqueKey).toBe('1');
-
- await clientB.drop();
- });
-});
diff --git a/packages/fs-storage/test/request-queue/handledRequestCount-should-update.test.ts b/packages/fs-storage/test/request-queue/handledRequestCount-should-update.test.ts
deleted file mode 100644
index eff5934d0..000000000
--- a/packages/fs-storage/test/request-queue/handledRequestCount-should-update.test.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { rm } from 'node:fs/promises';
-import { resolve } from 'node:path';
-
-import { FileSystemStorageClient } from '@crawlee/fs-storage';
-import type { RequestQueueClient } from '@crawlee/types';
-
-describe('RequestQueue handledRequestCount should update', () => {
- // Use an isolated storage directory so persisted request files from a previous run cannot leak
- // into this one (a handled request surviving on disk would be deduplicated on the next add).
- const localDataDirectory = resolve(import.meta.dirname, './tmp/handled-request-count');
- const storage = new FileSystemStorageClient({ localDataDirectory });
-
- let requestQueue: RequestQueueClient;
-
- beforeAll(async () => {
- requestQueue = await storage.createRequestQueueClient({ name: 'handledRequestCount' });
- });
-
- afterAll(async () => {
- await rm(localDataDirectory, { force: true, recursive: true });
- });
-
- test('after marking a request as handled, it should increment the handledRequestCount', async () => {
- await requestQueue.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
-
- const request = await requestQueue.fetchNextRequest();
- expect(request).not.toBeNull();
-
- await requestQueue.markRequestAsHandled({
- url: 'http://example.com/1',
- uniqueKey: '1',
- id: request!.id!,
- });
-
- const updatedStatistics = await requestQueue.getMetadata();
- expect(updatedStatistics.handledRequestCount).toEqual(1);
- });
-
- test('adding an already handled request should increment the handledRequestCount', async () => {
- await requestQueue.addBatchOfRequests([
- {
- url: 'http://example.com/2',
- uniqueKey: '2',
- handledAt: new Date().toISOString(),
- },
- ]);
-
- const updatedStatistics = await requestQueue.getMetadata();
- expect(updatedStatistics.handledRequestCount).toEqual(2);
- });
-});
diff --git a/packages/fs-storage/test/request-queue/ignore-non-json-files.test.ts b/packages/fs-storage/test/request-queue/ignore-non-json-files.test.ts
deleted file mode 100644
index bae333e81..000000000
--- a/packages/fs-storage/test/request-queue/ignore-non-json-files.test.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { randomUUID } from 'node:crypto';
-import { rm, writeFile } from 'node:fs/promises';
-import { resolve } from 'node:path';
-
-import { FileSystemStorageClient } from '@crawlee/fs-storage';
-import type { InternalRequest } from '@crawlee/fs-storage/src/resource-clients/request-queue';
-import type { RequestSchema } from '@crawlee/types';
-import { ensureDir } from 'fs-extra/esm';
-
-describe('when falling back to fs, Request queue should ignore non-JSON files', () => {
- const tmpLocation = resolve(import.meta.dirname, './tmp/req-queue-ignore-non-json');
- const storage = new FileSystemStorageClient({
- localDataDirectory: tmpLocation,
- });
-
- beforeAll(async () => {
- // Create "default" request queue and give it faulty entries
- await ensureDir(resolve(storage.requestQueuesDirectory, 'default'));
- await writeFile(
- resolve(storage.requestQueuesDirectory, 'default/__metadata__.json'),
- JSON.stringify({
- id: randomUUID(),
- name: 'default',
- createdAt: new Date(2022, 0, 1),
- accessedAt: new Date(2022, 0, 1),
- modifiedAt: new Date(2022, 0, 1),
- }),
- );
-
- await writeFile(
- resolve(storage.requestQueuesDirectory, 'default/123.json'),
- JSON.stringify({
- id: '123',
- orderNo: 1,
- url: 'http://example.com',
- uniqueKey: 'owo',
- method: 'GET',
- retryCount: 0,
- json: JSON.stringify({
- uniqueKey: 'owo',
- url: 'http://example.com',
- id: '123',
- } satisfies RequestSchema),
- } satisfies InternalRequest),
- );
-
- await writeFile(resolve(storage.requestQueuesDirectory, 'default/.DS_Store'), 'owo');
- await writeFile(resolve(storage.requestQueuesDirectory, 'default/invalid.txt'), 'owo');
- });
-
- afterAll(async () => {
- await rm(tmpLocation, { force: true, recursive: true });
- });
-
- test('attempting to list "default" request queue should ignore non-JSON files', async () => {
- const defaultQueue = await storage.createRequestQueueClient({ name: 'default' });
- const defaultQueueInfo = await defaultQueue.getMetadata();
-
- expect(defaultQueueInfo.name).toEqual('default');
-
- // Only the single valid JSON-backed request should be fetchable; the non-JSON files are ignored.
- const first = await defaultQueue.fetchNextRequest();
- expect(first).not.toBeNull();
- expect(first!.url).toEqual('http://example.com');
-
- const second = await defaultQueue.fetchNextRequest();
- expect(second).toBeUndefined();
- });
-});
diff --git a/packages/fs-storage/test/request-queue/reload-persistence.test.ts b/packages/fs-storage/test/request-queue/reload-persistence.test.ts
new file mode 100644
index 000000000..8714ed730
--- /dev/null
+++ b/packages/fs-storage/test/request-queue/reload-persistence.test.ts
@@ -0,0 +1,43 @@
+import { rm } from 'node:fs/promises';
+import { resolve } from 'node:path';
+
+import { FileSystemStorageClient } from '@crawlee/fs-storage';
+
+// The native client owns request-queue persistence; what this test exercises is the *adapter* wiring
+// that drives it: `FileSystemStorageClient.teardown()` must flush every opened queue's state via
+// `persistState()`, and reopening through a fresh `FileSystemStorageClient` over the same directory
+// must restore the pending requests (with the adapter's request mapping intact).
+describe('Request queue persists across reopen via teardown', () => {
+ const tmpLocation = resolve(import.meta.dirname, './tmp/req-queue-reload');
+
+ afterEach(async () => {
+ await rm(tmpLocation, { force: true, recursive: true });
+ });
+
+ test('requests added and persisted are restored when the queue is reopened', async () => {
+ const storage = new FileSystemStorageClient({ localDataDirectory: tmpLocation });
+ const queue = await storage.createRequestQueueClient({ name: 'default' });
+
+ await queue.addBatchOfRequests([
+ { url: 'http://example.com/1', uniqueKey: '1' },
+ { url: 'http://example.com/2', uniqueKey: '2' },
+ ]);
+
+ // `teardown` flushes the native client state to disk.
+ await storage.teardown();
+
+ // Reopen over the same directory, emulating a fresh process.
+ const reopenedStorage = new FileSystemStorageClient({ localDataDirectory: tmpLocation });
+ const reopenedQueue = await reopenedStorage.createRequestQueueClient({ name: 'default' });
+
+ const metadata = await reopenedQueue.getMetadata();
+ expect(metadata.pendingRequestCount).toBe(2);
+ expect(metadata.totalRequestCount).toBe(2);
+
+ const first = await reopenedQueue.fetchNextRequest();
+ const second = await reopenedQueue.fetchNextRequest();
+
+ expect([first?.url, second?.url].sort()).toStrictEqual(['http://example.com/1', 'http://example.com/2']);
+ expect(await reopenedQueue.fetchNextRequest()).toBeUndefined();
+ });
+});
diff --git a/packages/fs-storage/test/request-queue/request-queue-access.test.ts b/packages/fs-storage/test/request-queue/request-queue-access.test.ts
new file mode 100644
index 000000000..ec05d3450
--- /dev/null
+++ b/packages/fs-storage/test/request-queue/request-queue-access.test.ts
@@ -0,0 +1,85 @@
+import { rm } from 'node:fs/promises';
+import { resolve } from 'node:path';
+
+import { FileSystemStorageClient } from '@crawlee/fs-storage';
+
+// `requestQueueAccess` controls how the native `@crawlee/fs-storage-native` extension treats requests
+// left *in progress* by a previous run (a dangling `orderNo` lock on disk) when a queue is reopened.
+// The reclaim/respect-peer-lock semantics are owned by the native extension; these tests verify the
+// adapter's contract on top of it: the option defaults to `'single'`, is honored when set to
+// `'shared'`, and that the resulting behavior reaches all the way down to the native queue.
+describe('FileSystemStorageClient requestQueueAccess', () => {
+ const tmpLocation = resolve(import.meta.dirname, './tmp/request-queue-access');
+
+ afterEach(async () => {
+ await rm(tmpLocation, { force: true, recursive: true });
+ });
+
+ test("defaults to 'single'", () => {
+ const storage = new FileSystemStorageClient({ localDataDirectory: tmpLocation });
+ expect(storage.requestQueueAccess).toBe('single');
+ });
+
+ test("respects an explicit 'shared'", () => {
+ const storage = new FileSystemStorageClient({ localDataDirectory: tmpLocation, requestQueueAccess: 'shared' });
+ expect(storage.requestQueueAccess).toBe('shared');
+ });
+
+ // Seed a queue with two requests, fetch (lock) one without handling it or tearing down — leaving a
+ // dangling in-progress lock on disk, exactly the "process died mid-flight" situation.
+ async function seedQueueWithDanglingLock(dir: string) {
+ const storage = new FileSystemStorageClient({ localDataDirectory: dir });
+ const queue = await storage.createRequestQueueClient({ name: 'default' });
+ await queue.addBatchOfRequests([
+ { url: 'http://example.com/1', uniqueKey: '1' },
+ { url: 'http://example.com/2', uniqueKey: '2' },
+ ]);
+ const locked = await queue.fetchNextRequest();
+ expect(locked).toBeDefined();
+ // Intentionally NO markRequestAsHandled and NO teardown/persistState — the lock is left dangling.
+ return locked!;
+ }
+
+ test("'single' (default): reopening preserves contents but relinquishes the dangling lock", async () => {
+ const dir = resolve(tmpLocation, 'single');
+ const locked = await seedQueueWithDanglingLock(dir);
+
+ // Reopen the same directory as sole owner, without purging.
+ const reopened = new FileSystemStorageClient({ localDataDirectory: dir, requestQueueAccess: 'single' });
+ const queue = await reopened.createRequestQueueClient({ name: 'default' });
+
+ // Contents preserved: both requests still present, none handled.
+ const metadata = await queue.getMetadata();
+ expect(metadata.totalRequestCount).toBe(2);
+ expect(metadata.handledRequestCount).toBe(0);
+ expect(metadata.pendingRequestCount).toBe(2);
+
+ // Lock relinquished: BOTH requests are fetchable again, including the one locked before.
+ const a = await queue.fetchNextRequest();
+ const b = await queue.fetchNextRequest();
+ expect([a?.uniqueKey, b?.uniqueKey].sort()).toStrictEqual(['1', '2']);
+ // The previously-locked request survived with its data intact.
+ const reFetched = await queue.getRequest(locked.uniqueKey);
+ expect(reFetched?.url).toBe(locked.url);
+ });
+
+ test("'shared': reopening keeps the dangling lock (concurrency-safe mode)", async () => {
+ const dir = resolve(tmpLocation, 'shared');
+ await seedQueueWithDanglingLock(dir);
+
+ // Reopen in concurrency-safe mode: an in-progress request is treated as a potential live peer's
+ // lock and is NOT reclaimed until it expires.
+ const reopened = new FileSystemStorageClient({ localDataDirectory: dir, requestQueueAccess: 'shared' });
+ const queue = await reopened.createRequestQueueClient({ name: 'default' });
+
+ // Contents are still preserved...
+ const metadata = await queue.getMetadata();
+ expect(metadata.totalRequestCount).toBe(2);
+ expect(metadata.pendingRequestCount).toBe(2);
+
+ // ...but only the un-locked request is handed out; the locked one stays in progress.
+ const a = await queue.fetchNextRequest();
+ expect(a?.uniqueKey).toBe('2');
+ expect(await queue.fetchNextRequest()).toBeUndefined();
+ });
+});
diff --git a/packages/fs-storage/test/write-metadata.test.ts b/packages/fs-storage/test/write-metadata.test.ts
deleted file mode 100644
index 901224935..000000000
--- a/packages/fs-storage/test/write-metadata.test.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import { readdir, rm } from 'node:fs/promises';
-import { resolve } from 'node:path';
-
-import { FileSystemStorageClient } from '@crawlee/fs-storage';
-
-import { waitTillWrittenToDisk } from './__shared__.js';
-
-describe('writeMetadata option', () => {
- const tmpLocation = resolve(import.meta.dirname, './tmp/write-metadata-tests');
-
- afterAll(async () => {
- await rm(tmpLocation, { force: true, recursive: true });
- });
-
- describe('when false', () => {
- const localDataDirectory = resolve(tmpLocation, './no-metadata');
- const storage = new FileSystemStorageClient({
- localDataDirectory,
- writeMetadata: false,
- });
-
- test('creating a data store should not write __metadata__.json file', async () => {
- const keyValueStore = await storage.createKeyValueStoreClient();
- const info = await keyValueStore.getMetadata();
- const expectedPath = resolve(storage.keyValueStoresDirectory, info.id);
-
- // We check that reading the directory for the store throws an error, which means it wasn't created on disk
- await expect(async () => readdir(expectedPath)).rejects.toThrow();
- });
-
- test('creating a key-value pair in a key-value store should not write __metadata__.json file for the value', async () => {
- const keyValueStore = await storage.createKeyValueStoreClient();
- // The client is a byte-transport: pass the content type so the on-disk extension is `txt`.
- await keyValueStore.setValue({ key: 'foo', value: 'test', contentType: 'text/plain; charset=utf-8' });
-
- const keyValueStoreInfo = await keyValueStore.getMetadata();
- const expectedFilePath = resolve(storage.keyValueStoresDirectory, `${keyValueStoreInfo.id}/foo.txt`);
- await waitTillWrittenToDisk(expectedFilePath);
-
- const directoryFiles = await readdir(resolve(storage.keyValueStoresDirectory, keyValueStoreInfo.id));
-
- expect(directoryFiles).toHaveLength(1);
- });
- });
-
- describe('when true', () => {
- const localDataDirectory = resolve(tmpLocation, './metadata');
- const storage = new FileSystemStorageClient({
- localDataDirectory,
- writeMetadata: true,
- });
-
- test('creating a data store should write __metadata__.json file', async () => {
- const keyValueStore = await storage.createKeyValueStoreClient();
- const info = await keyValueStore.getMetadata();
- const expectedPath = resolve(storage.keyValueStoresDirectory, info.id);
- await waitTillWrittenToDisk(expectedPath);
-
- const directoryFiles = await readdir(expectedPath);
-
- expect(directoryFiles).toHaveLength(1);
- });
-
- test('creating a key-value pair in a key-value store should write __metadata__.json file for the value', async () => {
- const keyValueStore = await storage.createKeyValueStoreClient();
- // The client is a byte-transport: pass the content type so the on-disk extension is `txt`.
- await keyValueStore.setValue({ key: 'foo', value: 'test', contentType: 'text/plain; charset=utf-8' });
-
- const keyValueStoreInfo = await keyValueStore.getMetadata();
- const expectedFilePath = resolve(storage.keyValueStoresDirectory, `${keyValueStoreInfo.id}/foo.txt`);
- const expectedMetadataPath = resolve(
- storage.keyValueStoresDirectory,
- `${keyValueStoreInfo.id}/foo.__metadata__.json`,
- );
- await Promise.all([waitTillWrittenToDisk(expectedFilePath), waitTillWrittenToDisk(expectedMetadataPath)]);
-
- const directoryFiles = await readdir(resolve(storage.keyValueStoresDirectory, keyValueStoreInfo.id));
-
- expect(directoryFiles).toHaveLength(3);
- });
- });
-});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c57c2f0a2..435dc953e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -588,36 +588,15 @@ importers:
packages/fs-storage:
dependencies:
+ '@crawlee/fs-storage-native':
+ specifier: 0.1.5-beta.18
+ version: 0.1.5-beta.18
'@crawlee/types':
specifier: workspace:*
version: link:../types
- '@crawlee/utils':
- specifier: workspace:*
- version: link:../utils
- '@sapphire/async-queue':
- specifier: ^1.5.5
- version: 1.5.5
'@sapphire/shapeshift':
specifier: ^4.0.0
version: 4.0.0
- content-type:
- specifier: ^1.0.5
- version: 1.0.5
- fs-extra:
- specifier: ^11.3.0
- version: 11.3.4
- json5:
- specifier: ^2.2.3
- version: 2.2.3
- mime-types:
- specifier: ^3.0.1
- version: 3.0.2
- proper-lockfile:
- specifier: ^4.1.2
- version: 4.1.2
- tslib:
- specifier: ^2.8.1
- version: 2.8.1
packages/got-scraping-client:
dependencies:
@@ -2035,6 +2014,35 @@ packages:
conventional-commits-parser:
optional: true
+ '@crawlee/[email protected]':
+ resolution: {integrity: sha512-fYZbU61GoMw+3q1JXRvARa8f/A8qZo0BxBpGogzq8duhiOChs4v+uHjffuZjL4E6goFR5qjX2kwOAJzoEp2kZQ==}
+ engines: {node: '>= 20'}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@crawlee/[email protected]':
+ resolution: {integrity: sha512-Wb/d6PLor34790ixEFsRADvTUXKzR846/1E2LUaDTLA3KQ5QUCwjQhs7VpfrgY9AzzgM/s8G+3TO2UI6L3eYkw==}
+ engines: {node: '>= 20'}
+ cpu: [x64]
+ os: [darwin]
+
+ '@crawlee/[email protected]':
+ resolution: {integrity: sha512-J8qfCkj3i6ic87fiD4f05WSXLXaAFLZlboXeeH9nDhJv/6RLxjiwTqec/Ig9H3yon+v4VQUbSHIh3Mm6B0g3XQ==}
+ engines: {node: '>= 20'}
+ cpu: [x64]
+ os: [linux]
+ libc: [glibc]
+
+ '@crawlee/[email protected]':
+ resolution: {integrity: sha512-76uxjzcsD2E+mWqZ+HENpcSpJJAZVdWf3osKR3pA3wld+yzR9o0cckRysu4QTDhUeNtzL1KIq2NzOF1GPNLqiw==}
+ engines: {node: '>= 20'}
+ cpu: [x64]
+ os: [win32]
+
+ '@crawlee/[email protected]':
+ resolution: {integrity: sha512-G5+Alb5GDAZomtu+0mB8oeYA0BCMqOQIqNoTPtZxh2wLcb17CpMfJJvq6D/nT8vANAaBkrMR49bbrodtROV2ug==}
+ engines: {node: '>= 20'}
+
'@crawlee/[email protected]':
resolution: {integrity: sha512-CcIM+JDVx4gzQzMPl+9RJiEeqdzTrx2RLPA7y4IMJSyfZm3J/VrEunielKA3NQrk095j9OuvS/rQL2y8mBV1qw==}
engines: {node: '>=16.0.0'}
@@ -10689,9 +10697,6 @@ packages:
resolution: {integrity: sha512-vGrhOavPSTz4QVNuBNdcNXePNdNMaO1xj9yBeH1ScQPjk/rhg9sSlCXPhMkFuaNNW/syTvYqsnbIJxMBfRbbag==}
engines: {node: '>= 8'}
- resolution: {integrity: sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==}
-
resolution: {integrity: sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==}
@@ -14084,6 +14089,25 @@ snapshots:
optionalDependencies:
conventional-commits-parser: 6.4.0
+ '@crawlee/[email protected]':
+ optional: true
+
+ '@crawlee/[email protected]':
+ optional: true
+
+ '@crawlee/[email protected]':
+ optional: true
+
+ '@crawlee/[email protected]':
+ optional: true
+
+ '@crawlee/[email protected]':
+ optionalDependencies:
+ '@crawlee/fs-storage-native-darwin-arm64': 0.1.5-beta.18
+ '@crawlee/fs-storage-native-darwin-x64': 0.1.5-beta.18
+ '@crawlee/fs-storage-native-linux-x64-gnu': 0.1.5-beta.18
+ '@crawlee/fs-storage-native-win32-x64-msvc': 0.1.5-beta.18
+
'@crawlee/[email protected]':
dependencies:
tslib: 2.8.1
@@ -24731,12 +24755,6 @@ snapshots:
- dependencies:
- graceful-fs: 4.2.11
- retry: 0.12.0
- signal-exit: 3.0.7
-
diff --git a/test/core/enqueue_links/click_elements.test.ts b/test/core/enqueue_links/click_elements.test.ts
index 667c66a42..42c58e173 100644
--- a/test/core/enqueue_links/click_elements.test.ts
+++ b/test/core/enqueue_links/click_elements.test.ts
@@ -14,6 +14,7 @@ import type { Browser as PWBrowser, Page as PWPage } from 'playwright';
// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), we only import types, so its alllll gooooood
import type { Browser as PPBrowser, Target } from 'puppeteer';
import { runExampleComServer } from '../../shared/_helper.js';
+import { MemoryStorageEmulator } from '../../shared/MemoryStorageEmulator.js';
function isPuppeteerBrowser(browser: PPBrowser | PWBrowser): browser is PPBrowser {
return (browser as PPBrowser).targets !== undefined;
@@ -57,6 +58,7 @@ const testCases = [
testCases.forEach(({ caseName, launchBrowser, clickElements, utils }) => {
describe(`${caseName}: enqueueLinksByClickingElements()`, () => {
+ const localStorageEmulator = new MemoryStorageEmulator();
let browser: PPBrowser | PWBrowser;
let server: Server;
@@ -73,9 +75,11 @@ testCases.forEach(({ caseName, launchBrowser, clickElements, utils }) => {
afterAll(async () => {
await browser.close();
server.close();
+ await localStorageEmulator.destroy();
});
beforeEach(async () => {
+ await localStorageEmulator.init();
page = await browser.newPage();
});
diff --git a/test/core/enqueue_links/enqueue_links.test.ts b/test/core/enqueue_links/enqueue_links.test.ts
index 0f1616795..a90750eaf 100644
--- a/test/core/enqueue_links/enqueue_links.test.ts
+++ b/test/core/enqueue_links/enqueue_links.test.ts
@@ -17,6 +17,8 @@ import type { Browser as PuppeteerBrowser, Page as PuppeteerPage } from 'puppete
import log from '@apify/log';
+import { MemoryStorageEmulator } from '../../shared/MemoryStorageEmulator.js';
+
const HTML = `
<html>
<head>
@@ -62,14 +64,20 @@ async function createRequestQueueMock() {
}
describe('enqueueLinks()', () => {
+ const localStorageEmulator = new MemoryStorageEmulator();
let ll: number;
beforeAll(() => {
ll = log.getLevel();
log.setLevel(log.LEVELS.ERROR);
});
- afterAll(() => {
+ beforeEach(async () => {
+ await localStorageEmulator.init();
+ });
+
+ afterAll(async () => {
log.setLevel(ll);
+ await localStorageEmulator.destroy();
});
describe.each([[launchPuppeteer], [launchPlaywright]] as const)('using %s', (method) => {
diff --git a/test/core/storages/storage_aliases.test.ts b/test/core/storages/storage_aliases.test.ts
index 64d0d5347..d2932160d 100644
--- a/test/core/storages/storage_aliases.test.ts
+++ b/test/core/storages/storage_aliases.test.ts
@@ -181,12 +181,11 @@ describe('storage aliases', () => {
});
test('a storage opened by name can be re-opened by its auto-assigned id after a reset', async () => {
- // `writeMetadata` persists the auto-assigned id to disk so it survives a reset. The
- // directory is named after the storage's name, not its id.
+ // The native storage always persists the auto-assigned id to disk (in `__metadata__.json`)
+ // so it survives a reset. The directory is named after the storage's name, not its id.
serviceLocator.reset();
const firstClient = new FileSystemStorageClient({
localDataDirectory: localStorageDir,
- writeMetadata: true,
});
serviceLocator.setStorageClient(firstClient);
@@ -200,7 +199,7 @@ describe('storage aliases', () => {
// Simulate a fresh process: only the on-disk directory survives.
serviceLocator.reset();
- const client = new FileSystemStorageClient({ localDataDirectory: localStorageDir, writeMetadata: true });
+ const client = new FileSystemStorageClient({ localDataDirectory: localStorageDir });
serviceLocator.setStorageClient(client);
// Opening by the persisted id must find the storage, even though its directory is named
diff --git a/vitest.config.mts b/vitest.config.mts
index b31ed8f6f..4915f6563 100644
--- a/vitest.config.mts
+++ b/vitest.config.mts
@@ -39,8 +39,12 @@ const baseConfig = defineConfig({
{ find: '@crawlee/playwright', replacement: resolve(__dirname, './packages/playwright-crawler/src') },
{ find: '@crawlee/puppeteer', replacement: resolve(__dirname, './packages/puppeteer-crawler/src') },
{ find: '@crawlee/stagehand', replacement: resolve(__dirname, './packages/stagehand-crawler/src') },
- { find: /^@crawlee\/(.*)\/(.*)$/, replacement: resolve(__dirname, './packages/$1/$2') },
- { find: /^@crawlee\/(.*)$/, replacement: resolve(__dirname, './packages/$1/src') },
+ // The generic `@crawlee/*` aliases below map specifiers to workspace package sources. They
+ // exclude `@crawlee/fs-storage-native` via a negative lookahead, since it is a real external
+ // (npm) dependency with no `packages/fs-storage-native` source — letting it resolve normally
+ // through node_modules.
+ { find: /^@crawlee\/(?!fs-storage-native)(.*)\/(.*)$/, replacement: resolve(__dirname, './packages/$1/$2') },
+ { find: /^@crawlee\/(?!fs-storage-native)(.*)$/, replacement: resolve(__dirname, './packages/$1/src') },
{ find: /^test\/(.*)$/, replacement: resolve(__dirname, './test/$1') },
],
retry: process.env.RETRY_TESTS ? 3 : 0,