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.

fix: don't check record existence in getPublicUrl() (#4086)

Noahe872b81fdb22
diff --git a/packages/core/src/storages/key_value_store.ts b/packages/core/src/storages/key_value_store.ts
index 20033b4ea..9b075fa54 100644
--- a/packages/core/src/storages/key_value_store.ts
+++ b/packages/core/src/storages/key_value_store.ts
@@ -779,7 +779,9 @@ export class KeyValueStore {
/**
* Returns a file URL for the given key.
*
- * If the record does not exist or has no associated file path (i.e., it is not stored as a file), returns `undefined`.
+ * The URL is derived from the key, so it is also returned for a record that does not exist (yet) —
+ * including one written earlier in an uncommitted storage transaction. Returns `undefined` only when
+ * the storage has no file URLs at all (e.g. the in-memory storage).
*
* @param key The key of the record to generate the public URL for.
*/
diff --git a/packages/fs-storage/package.json b/packages/fs-storage/package.json
index 233207eaf..35414342f 100644
--- a/packages/fs-storage/package.json
+++ b/packages/fs-storage/package.json
@@ -42,7 +42,7 @@
"access": "public"
},
"dependencies": {
- "@crawlee/fs-storage-native": "0.2.0",
+ "@crawlee/fs-storage-native": ">=0.2.1-beta.0 <0.3",
"@crawlee/types": "workspace:*",
"@crawlee/utils": "workspace:*",
"zod": "catalog:"
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 c129c4675..dc17c767e 100644
--- a/packages/fs-storage/src/resource-clients/key-value-store.ts
+++ b/packages/fs-storage/src/resource-clients/key-value-store.ts
@@ -181,20 +181,17 @@ export class KeyValueStoreBackend extends CachedIdClient implements storage.KeyV
/**
* Generates a public `file://` URL for accessing a specific record in the key-value store.
*
- * Returns `undefined` if the record does not exist.
+ * The native `getPublicUrl` derives the URL from the key without probing bare-file extensions, so
+ * an `INPUT` that lives on disk as a hand-placed `INPUT.json` is resolved first. Nothing on disk
+ * means nothing to resolve — the requested key is used as-is, and the URL is the one the record will
+ * have once written.
* @param key The key of the record to generate the public URL for.
*/
async getPublicUrl(key: string): Promise<string | undefined> {
parseArgument(key, keySchema);
- // 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.#nativeBackend.getPublicUrl(resolvedKey)) ?? undefined;
+ const resolvedKey = (await this.resolveExistingKey(key)) ?? key;
+ return this.#nativeBackend.getPublicUrl(resolvedKey);
}
/**
diff --git a/packages/fs-storage/test/fs-fallback.test.ts b/packages/fs-storage/test/fs-fallback.test.ts
index a3c2f7436..4406027f8 100644
--- a/packages/fs-storage/test/fs-fallback.test.ts
+++ b/packages/fs-storage/test/fs-fallback.test.ts
@@ -176,10 +176,11 @@ describe('fallback to fs for reading', () => {
// `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.
+ // probing that would resolve a bare `INPUT` is never attempted for other keys. `getPublicUrl`
+ // is existence-agnostic, so it still answers — with the extensionless key, not the bare file.
expect(await nonInputStore.getValue('some-key')).toBeUndefined();
expect(await nonInputStore.recordExists('some-key')).toBe(false);
- expect(await nonInputStore.getPublicUrl('some-key')).toBeUndefined();
+ expect(await nonInputStore.getPublicUrl('some-key')).toMatch(/^file:\/\/.*\/some-key$/);
// `listKeys` only surfaces bare files for the run-input keys, so `some-key` is not enumerated.
const { items } = await nonInputStore.listKeys();
@@ -263,7 +264,9 @@ describe('run-input bare-file reachability (one variant per store)', () => {
expect(await store.getValue(key)).toBeUndefined();
expect(await store.recordExists(key)).toBe(false);
- expect(await store.getPublicUrl(key)).toBeUndefined();
+ // Existence-agnostic: the URL falls back to the requested key rather than resolving to a
+ // sibling variant's file.
+ expect(await store.getPublicUrl(key)).toMatch(new RegExp(`^file://.*/${key.replace('.', '\\.')}$`));
});
});
});
diff --git a/packages/types/src/storages.ts b/packages/types/src/storages.ts
index f8453cf4a..d57ff19ef 100644
--- a/packages/types/src/storages.ts
+++ b/packages/types/src/storages.ts
@@ -206,7 +206,14 @@ export interface KeyValueStoreBackend {
*/
listKeys(options?: KeyValueStoreListKeysOptions): Promise<KeyValueStoreListKeysResult>;
- /** Get the public URL for a record, or `undefined` if unavailable. */
+ /**
+ * Get the public URL a record with this key has, or `undefined` if the backend exposes no public
+ * URLs at all.
+ *
+ * The URL is derived from the key; implementations MUST NOT check that the record exists. Callers
+ * legitimately ask for the URL of a record that is not on the backend yet — most notably one
+ * buffered in an uncommitted storage transaction — and existence is `recordExists`'s job.
+ */
getPublicUrl(key: string): Promise<string | undefined>;
/** Check whether a record with the given key exists. */
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 540b3d434..51a3987ee 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -854,8 +854,8 @@ importers:
packages/fs-storage:
dependencies:
'@crawlee/fs-storage-native':
- specifier: 0.2.0
- version: 0.2.0
+ specifier: '>=0.2.1-beta.0 <0.3'
+ version: 0.2.1-beta.0
'@crawlee/types':
specifier: workspace:*
version: link:../types
@@ -2339,60 +2339,60 @@ packages:
resolution: {integrity: sha512-TzlTVpKPjaqW6qOYjQcYUDuGsLCNsvFHVBXkYGTAnf5V37jCWrE5haKNXzz0WZUtVHjrpV76L1buANjwXMfT8w==}
engines: {node: '>=22'}
- '@crawlee/[email protected]':
- resolution: {integrity: sha512-Jg4OjQVZWqQz6QCQ939iY/EJA55zAg2ZhB5JtTy0okhkfPc8kYHN43DRP2FswDHRACaftOEy8NaI1H3+V4Z4KQ==}
+ '@crawlee/[email protected]':
+ resolution: {integrity: sha512-Ra0bQfxAGbfhDOwZ32GJuHTGc1WrIyE23mE1sLKNnZ4ukPnDSyy//ZO23LIkZ9i6YxyLsA6X3SwmZ/TFpewVVg==}
engines: {node: '>= 20'}
cpu: [arm64]
os: [darwin]
- '@crawlee/[email protected]':
- resolution: {integrity: sha512-BnBgAVygRAaEBFcyTgSNr9DrquUuIe4O/jtgSPctQ/oUiZ+PkK2DKk+OEtpMXpC+wVzLsBWnSs2aFnFIf78PYA==}
+ '@crawlee/[email protected]':
+ resolution: {integrity: sha512-Uf+hMZBrKMyKrJLUAer6V4W1xkyuABzgtsh2iByJE0CgPsyOS3mY4RdQBnKgS++XMQs5w94/DbfSWA90xV54Nw==}
engines: {node: '>= 20'}
cpu: [x64]
os: [darwin]
- '@crawlee/[email protected]':
- resolution: {integrity: sha512-YWJEgDHLaN11chIGAvRJOkqgdxPmzkRTeEGG1ptg0VYQbNzNdXvq6ykiq1njDwWwgUzXTqjeRFF2/U44Hc4xXw==}
+ '@crawlee/[email protected]':
+ resolution: {integrity: sha512-P+Be5g8YxnA7f93GOnnm+5jpFb5uhI0iFXcWzm1aLpQU0fhE6hZOuiYSxKYRqn2AU6yPLjqwHm0eKuRm/UO83A==}
engines: {node: '>= 20'}
cpu: [arm64]
os: [linux]
libc: [glibc]
- '@crawlee/[email protected]':
- resolution: {integrity: sha512-C+ED04FlzKNxECIl3miisbX9eC3pSV/yrFboCrUAycA8Vh01fRTfeREzS+hMOsCQsRXeCdQ5Ifihi1T/nJwUwQ==}
+ '@crawlee/[email protected]':
+ resolution: {integrity: sha512-X8U+aS00umhQ+8gHJdQg7j40J20hLvbb9pvOP9gb0Y6PdZt/jAbivIyGP871wGViJ+fwF1QQQtFO1HP5IzE8+w==}
engines: {node: '>= 20'}
cpu: [arm64]
os: [linux]
libc: [musl]
- '@crawlee/[email protected]':
- resolution: {integrity: sha512-NlZ3Ud9dBiqkXwFEJbEVOg6PcnYdUF+C+gR3LvD/H4FOr5noLn48Kp8ikbEMbGlPdyPtLvdsMp2MCQPlQEPYYw==}
+ '@crawlee/[email protected]':
+ resolution: {integrity: sha512-u0yUDlk5rg51c4eTOyk6lnWiYaoUw1Z53VnlmXYDMFSUW7tGQHLdy0aQBL+RWBmD0+mLMRiBDJjYoxsrKYYCLg==}
engines: {node: '>= 20'}
cpu: [x64]
os: [linux]
libc: [glibc]
- '@crawlee/[email protected]':
- resolution: {integrity: sha512-Jb78RXko15FIXQgyb7pdTgYVc8oLN+ltEDJt9QprJUh65kUrVmPc/d2kXJhtvkH7CGEYR6/QLjfRKvoD1eeWyg==}
+ '@crawlee/[email protected]':
+ resolution: {integrity: sha512-T/9ZPPt6eGm3qUwhnEy7SGbilH9Bvku+afdsXxIoDDza5Uib7PnwFTjI+stnY4Y5xQ+GAcmfwkRRM3oZ2UK6ZA==}
engines: {node: '>= 20'}
cpu: [x64]
os: [linux]
libc: [musl]
- '@crawlee/[email protected]':
- resolution: {integrity: sha512-UPX2/G67OmUzqAnhKnUjMwxxhJzrmUEug8gSgIGLqYAV/B6wsCU7e5a59Ekc4vroVSZxmBJ3ahNu6lXL7oMhBA==}
+ '@crawlee/[email protected]':
+ resolution: {integrity: sha512-p8D+XSskEZ2FMGXlrzVQrkFozkS3Md6invEvTiWEPC6/Z6mvNbwJ9z8NVSRNx4Trwb1l85i0+rLJI9OqzYOa4Q==}
engines: {node: '>= 20'}
cpu: [arm64]
os: [win32]
- '@crawlee/[email protected]':
- resolution: {integrity: sha512-jMafrxiPm/nU6rmW1PXVj5O5mnK8oz2nnf2aRaV6bpwWS9XJ7pHIJOo208o54pkNz0m7E6IKRaA248So8ei3KA==}
+ '@crawlee/[email protected]':
+ resolution: {integrity: sha512-ChmVNKYjlskX9WKPsQumbF3H0MEU1MumfkZxou6FjFLtgQ14rt03qld8n1EUzQXBApyqg5RSQCKdDoTIiehmCA==}
engines: {node: '>= 20'}
cpu: [x64]
os: [win32]
- '@crawlee/[email protected]':
- resolution: {integrity: sha512-fLFhUZBBvgY2KmKaOcvJK1QaiwxoDt9XGaCbgG3xGxIZJfZW1OS71FKjAdxIv9QjcRWtUxD1QwD9kFHlpb5P2g==}
+ '@crawlee/[email protected]':
+ resolution: {integrity: sha512-SpQQj/4Jb7NT4mPL4e97loOixjg3Sb2UZPQUtZ3558I94BmKUh2+P35VKpzkMj3wnGU1QCcUOYIeNGPoH80Xgw==}
engines: {node: '>= 20'}
'@crawlee/[email protected]':
@@ -14830,40 +14830,40 @@ snapshots:
'@conventional-changelog/[email protected]': {}
- '@crawlee/[email protected]':
+ '@crawlee/[email protected]':
optional: true
- '@crawlee/[email protected]':
+ '@crawlee/[email protected]':
optional: true
- '@crawlee/[email protected]':
+ '@crawlee/[email protected]':
optional: true
- '@crawlee/[email protected]':
+ '@crawlee/[email protected]':
optional: true
- '@crawlee/[email protected]':
+ '@crawlee/[email protected]':
optional: true
- '@crawlee/[email protected]':
+ '@crawlee/[email protected]':
optional: true
- '@crawlee/[email protected]':
+ '@crawlee/[email protected]':
optional: true
- '@crawlee/[email protected]':
+ '@crawlee/[email protected]':
optional: true
- '@crawlee/[email protected]':
+ '@crawlee/[email protected]':
optionalDependencies:
- '@crawlee/fs-storage-native-darwin-arm64': 0.2.0
- '@crawlee/fs-storage-native-darwin-x64': 0.2.0
- '@crawlee/fs-storage-native-linux-arm64-gnu': 0.2.0
- '@crawlee/fs-storage-native-linux-arm64-musl': 0.2.0
- '@crawlee/fs-storage-native-linux-x64-gnu': 0.2.0
- '@crawlee/fs-storage-native-linux-x64-musl': 0.2.0
- '@crawlee/fs-storage-native-win32-arm64-msvc': 0.2.0
- '@crawlee/fs-storage-native-win32-x64-msvc': 0.2.0
+ '@crawlee/fs-storage-native-darwin-arm64': 0.2.1-beta.0
+ '@crawlee/fs-storage-native-darwin-x64': 0.2.1-beta.0
+ '@crawlee/fs-storage-native-linux-arm64-gnu': 0.2.1-beta.0
+ '@crawlee/fs-storage-native-linux-arm64-musl': 0.2.1-beta.0
+ '@crawlee/fs-storage-native-linux-x64-gnu': 0.2.1-beta.0
+ '@crawlee/fs-storage-native-linux-x64-musl': 0.2.1-beta.0
+ '@crawlee/fs-storage-native-win32-arm64-msvc': 0.2.1-beta.0
+ '@crawlee/fs-storage-native-win32-x64-msvc': 0.2.1-beta.0
'@crawlee/[email protected]':
dependencies:
diff --git a/test/core/storages/key_value_store_public_url_transaction.test.ts b/test/core/storages/key_value_store_public_url_transaction.test.ts
new file mode 100644
index 000000000..80cffcaab
--- /dev/null
+++ b/test/core/storages/key_value_store_public_url_transaction.test.ts
@@ -0,0 +1,127 @@
+import { readFile } from 'node:fs/promises';
+import { resolve } from 'node:path';
+
+import { KeyValueStore, MemoryStorageBackend, serviceLocator, withStorageTransaction } from '@crawlee/core';
+import { FileSystemStorageBackend } from '@crawlee/fs-storage';
+import { ensureDir, rm } from 'fs-extra';
+
+import { cryptoRandomObjectId } from '@apify/utilities';
+
+/**
+ * `getPublicUrl()` derives the URL from the key without checking that the record exists, so a record
+ * written earlier in an uncommitted transaction — buffered in the journal, absent from the backend —
+ * already resolves to the URL it will have after commit (apify/crawlee#4075).
+ *
+ * Each test asserts that the in-transaction URL equals the committed one *and* that its path is the
+ * value file on disk, which is what makes the derived URL more than a plausible-looking string.
+ */
+describe('KeyValueStore.getPublicUrl() inside a storage transaction (fs-storage)', () => {
+ // A fresh directory per test keeps the suite order-independent.
+ let localStorageDir: string;
+
+ beforeEach(async () => {
+ serviceLocator.reset();
+ localStorageDir = resolve(import.meta.dirname, '..', 'tmp', 'fs-kvs-public-url-txn', cryptoRandomObjectId(10));
+ await ensureDir(localStorageDir);
+ serviceLocator.setStorageBackend(new FileSystemStorageBackend({ localDataDirectory: localStorageDir }));
+ });
+
+ afterEach(async () => {
+ serviceLocator.getStorageInstanceManager().clearCache();
+ await rm(localStorageDir, { force: true, recursive: true });
+ });
+
+ // The storage directory is spliced into the URL unencoded and the file is named by the *encoded*
+ // key, so the URL's path is a literal filesystem path — not a percent-decoded one.
+ const pathOf = (url: string) => url.slice('file://'.length);
+
+ const writeInTransaction = async (store: KeyValueStore, key: string) => {
+ let urlInside: string | undefined;
+ await withStorageTransaction(async () => {
+ await store.setValue(key, { hello: 'world' });
+ urlInside = await store.getPublicUrl(key);
+ });
+
+ const urlAfterCommit = await store.getPublicUrl(key);
+ expect(urlAfterCommit).toBeDefined();
+ expect(urlInside).toBe(urlAfterCommit);
+
+ return urlAfterCommit!;
+ };
+
+ test('returns the committed URL for a record written earlier in the same transaction', async () => {
+ const store = await KeyValueStore.open();
+ const url = await writeInTransaction(store, 'record');
+
+ expect(JSON.parse(await readFile(pathOf(url), 'utf8'))).toStrictEqual({ hello: 'world' });
+ });
+
+ // A key with characters `encodeURIComponent` leaves alone (`!'()`) exercises the extra encoding pass;
+ // a plain alphanumeric key would not.
+ test('encodes a special-character key the way the value file is named', async () => {
+ const store = await KeyValueStore.open();
+ const url = await writeInTransaction(store, "re-cord_1.v2!'()");
+
+ expect(url).toContain('re-cord_1.v2%21%27%28%29');
+ expect(JSON.parse(await readFile(pathOf(url), 'utf8'))).toStrictEqual({ hello: 'world' });
+ });
+
+ // The directory path is spliced in unencoded, so a space in it must be reproduced verbatim rather
+ // than percent-encoded.
+ test('resolves to the value file when the storage directory path contains a space', async () => {
+ serviceLocator.reset();
+ const dirWithSpace = resolve(localStorageDir, 'with space');
+ await ensureDir(dirWithSpace);
+ serviceLocator.setStorageBackend(new FileSystemStorageBackend({ localDataDirectory: dirWithSpace }));
+
+ const store = await KeyValueStore.open();
+ const url = await writeInTransaction(store, 'record');
+
+ expect(pathOf(url)).toContain('with space');
+ expect(JSON.parse(await readFile(pathOf(url), 'utf8'))).toStrictEqual({ hello: 'world' });
+ });
+
+ // The flip side of deriving URLs from keys: they never imply existence, not even for a record
+ // tombstoned in the current transaction. Callers that need existence ask `recordExists()`.
+ test('returns a URL for a record that does not exist', async () => {
+ const store = await KeyValueStore.open();
+ await store.setValue('record', { hello: 'world' });
+
+ const committedUrl = await store.getPublicUrl('record');
+ expect(await store.getPublicUrl('never-written')).toBeDefined();
+
+ await withStorageTransaction(async () => {
+ await store.setValue('record', null);
+ expect(await store.getPublicUrl('record')).toBe(committedUrl);
+ });
+
+ expect(await store.recordExists('record')).toBe(false);
+ expect(await store.getPublicUrl('record')).toBe(committedUrl);
+ });
+});
+
+// A URL-less backend must stay URL-less: nothing about the key-derived contract makes the in-memory
+// storage fabricate a file URL for a buffered record.
+describe('KeyValueStore.getPublicUrl() inside a storage transaction (memory-storage)', () => {
+ beforeEach(() => {
+ serviceLocator.reset();
+ serviceLocator.setStorageBackend(new MemoryStorageBackend());
+ });
+
+ afterEach(() => {
+ serviceLocator.getStorageInstanceManager().clearCache();
+ });
+
+ test('returns undefined for a record buffered in a transaction on a URL-less backend', async () => {
+ const store = await KeyValueStore.open();
+
+ let urlInside: string | undefined = 'sentinel';
+ await withStorageTransaction(async () => {
+ await store.setValue('record', { hello: 'world' });
+ urlInside = await store.getPublicUrl('record');
+ });
+
+ expect(urlInside).toBeUndefined();
+ expect(await store.getPublicUrl('record')).toBeUndefined();
+ });
+});