-
Notifications
You must be signed in to change notification settings - Fork 62
fix: adapt SDK storage layer to crawlee v4 StorageClient interface #595
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
B4nan
wants to merge
12
commits into
fix/event-manager-v4-adapt
Choose a base branch
from
fix/storage-client-v4-adapt
base: fix/event-manager-v4-adapt
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
9ff3e79
fix: adapt SDK storage layer to crawlee v4 StorageClient interface
B4nan 087e117
test: migrate MemoryStorageEmulator to crawlee v4 service locator
B4nan bbce3fc
chore: fix import sort in actor.ts after ApifyStorageClient addition
B4nan 412f46b
chore: prettier
B4nan b6689cc
test: also reset SDK Configuration.globalConfig and Actor singleton o…
B4nan 037eb7d
test: align actor.test.ts mocks/expectations with v4 StorageClient ad…
B4nan b8d0098
test: clear Configuration AsyncLocalStorage between tests (Node 22 fix)
B4nan 7e4ad7d
test: replace Configuration.storage with fresh AsyncLocalStorage on r…
B4nan 7d50a74
test: use Actor.resetGlobalState() in MemoryStorageEmulator instead o…
B4nan ae0cf99
fix(storage): adapt to crawlee v4 beta.56 storage rename
B4nan 70ea49c
test: use the resetGlobalState() helper in MemoryStorageEmulator
B4nan 0352234
fix(storage): implement storageExists on ApifyStorageClient
B4nan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| import type { | ||
| CreateDatasetClientOptions, | ||
| CreateKeyValueStoreClientOptions, | ||
| CreateRequestQueueClientOptions, | ||
| DatasetClient, | ||
| KeyValueStoreClient, | ||
| RequestQueueClient, | ||
| StorageClient, | ||
| } from '@crawlee/types'; | ||
| import type { ApifyClient } from 'apify-client'; | ||
|
|
||
| type StorageType = 'Dataset' | 'KeyValueStore' | 'RequestQueue'; | ||
|
|
||
| /** | ||
| * Bridges `apify-client`'s synchronous resource accessors (`dataset(id)`, | ||
| * `keyValueStore(id)`, `requestQueue(id, options?)`) to crawlee v4's | ||
| * `StorageClient` interface (async factory methods accepting either an `id` | ||
| * or a `name`). | ||
| * | ||
| * `storageExists()` is implemented so that `Dataset.open(idOrName)` and friends | ||
| * resolve a string argument to an id first (when one with that id exists on | ||
| * the platform) and fall back to a name otherwise — without this, crawlee's | ||
| * `resolveStorageIdentifier` would treat every string as a name and the SDK | ||
| * would silently create a brand-new storage whose name equals the passed-in id. | ||
| * | ||
| * When only a `name` is provided to a `create*Client` method, it is resolved | ||
| * to a concrete id via `getOrCreate(name)` — same behaviour the SDK relied on | ||
| * in v3. | ||
| */ | ||
| export class ApifyStorageClient implements StorageClient { | ||
| constructor(private readonly client: ApifyClient) {} | ||
|
|
||
| async storageExists(id: string, type: StorageType): Promise<boolean> { | ||
| // Apify's `GET /v2/{kind}/{idOrName}` endpoint matches by either id or | ||
| // name. Confirm it was an *id* match — otherwise crawlee should fall | ||
| // through to the `{ name }` branch. | ||
| const info = await this.resourceClient(id, type).get(); | ||
| return info?.id === id; | ||
| } | ||
|
|
||
| async createDatasetClient( | ||
| options?: CreateDatasetClientOptions, | ||
| ): Promise<DatasetClient> { | ||
| const id = await this.resolveId(options, 'Dataset'); | ||
| // apify-client's resource clients overlap with `@crawlee/types`' shapes | ||
| // but don't yet implement the v4-added members (`getMetadata`, | ||
| // `getRecordPublicUrl`). Cast through for now; a follow-up should | ||
| // bring apify-client into structural alignment. | ||
| return this.client.dataset(id) as unknown as DatasetClient; | ||
| } | ||
|
|
||
| async createKeyValueStoreClient( | ||
| options?: CreateKeyValueStoreClientOptions, | ||
| ): Promise<KeyValueStoreClient> { | ||
| const id = await this.resolveId(options, 'KeyValueStore'); | ||
| return this.client.keyValueStore(id) as unknown as KeyValueStoreClient; | ||
| } | ||
|
|
||
| async createRequestQueueClient( | ||
| options?: CreateRequestQueueClientOptions, | ||
| ): Promise<RequestQueueClient> { | ||
| const id = await this.resolveId(options, 'RequestQueue'); | ||
| return this.client.requestQueue( | ||
| id, | ||
| options?.clientKey ? { clientKey: options.clientKey } : undefined, | ||
| ) as unknown as RequestQueueClient; | ||
| } | ||
|
|
||
| private async resolveId( | ||
| options: { id?: string; name?: string } | undefined, | ||
| type: StorageType, | ||
| ): Promise<string> { | ||
| if (options?.id) return options.id; | ||
| if (options?.name) { | ||
| return (await this.collectionClient(type).getOrCreate(options.name)) | ||
| .id; | ||
| } | ||
| return ''; | ||
| } | ||
|
|
||
| private resourceClient(id: string, type: StorageType) { | ||
| if (type === 'Dataset') return this.client.dataset(id); | ||
| if (type === 'KeyValueStore') return this.client.keyValueStore(id); | ||
| return this.client.requestQueue(id); | ||
| } | ||
|
|
||
| private collectionClient(type: StorageType) { | ||
| if (type === 'Dataset') return this.client.datasets(); | ||
| if (type === 'KeyValueStore') return this.client.keyValueStores(); | ||
| return this.client.requestQueues(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,12 +1,18 @@ | ||
| import type { StorageManagerOptions } from '@crawlee/core'; | ||
| import type { StorageOpenOptions } from '@crawlee/core'; | ||
| import { KeyValueStore as CoreKeyValueStore } from '@crawlee/core'; | ||
| import type { KeyValueStoreInfo } from '@crawlee/types'; | ||
|
|
||
| import { createHmacSignature } from '@apify/utilities'; | ||
|
|
||
| import type { Configuration } from './configuration.js'; | ||
|
|
||
| // @ts-ignore newer crawlee versions already declare this method in core | ||
| const { getPublicUrl } = CoreKeyValueStore.prototype; | ||
| // crawlee v4 dropped the `storageObject` cache from `KeyValueStore`, so the | ||
| // per-store `urlSigningSecretKey` (which is part of the platform's metadata | ||
| // response but not declared on `@crawlee/types`' `KeyValueStoreInfo`) has to | ||
| // be fetched on demand and accessed through a structural-typed augmentation. | ||
| type ApifyKeyValueStoreInfo = KeyValueStoreInfo & { | ||
| urlSigningSecretKey?: string; | ||
| }; | ||
|
|
||
| /** | ||
| * @inheritDoc | ||
|
|
@@ -15,24 +21,35 @@ export class KeyValueStore extends CoreKeyValueStore { | |
| /** | ||
| * Returns a URL for the given key that may be used to publicly | ||
| * access the value in the remote key-value store. | ||
| * | ||
| * On the Apify platform the URL is signed with the store's | ||
| * `urlSigningSecretKey` so that anyone with the URL can read the record | ||
| * without authentication. Locally we delegate to crawlee's default | ||
| * implementation (which produces a `file://` URL or returns `undefined`). | ||
| */ | ||
| override getPublicUrl(key: string): string { | ||
| override async getPublicUrl(key: string): Promise<string | undefined> { | ||
| const config = this.config as Configuration; | ||
| if (!config.isAtHome && getPublicUrl) { | ||
| return getPublicUrl.call(this, key); | ||
| if (!config.isAtHome) { | ||
| return super.getPublicUrl(key); | ||
| } | ||
|
|
||
| const publicUrl = new URL( | ||
| `${config.apiPublicBaseUrl}/v2/key-value-stores/${this.id}/records/${key}`, | ||
| ); | ||
|
|
||
| if (this.storageObject?.urlSigningSecretKey) { | ||
| // `client` is `private` on `CoreKeyValueStore`; bypass the visibility | ||
| // check to fetch the per-store secret. There is no public crawlee API | ||
| // surface for this yet — track upstream exposure as a follow-up. | ||
|
Comment on lines
+40
to
+42
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good point, please create the issue in Crawlee (I see that |
||
| const metadata = (await ( | ||
| this as unknown as { | ||
| client: { getMetadata(): Promise<KeyValueStoreInfo> }; | ||
| } | ||
| ).client.getMetadata()) as ApifyKeyValueStoreInfo; | ||
|
|
||
| if (metadata?.urlSigningSecretKey) { | ||
| publicUrl.searchParams.append( | ||
| 'signature', | ||
| createHmacSignature( | ||
| this.storageObject.urlSigningSecretKey as string, | ||
| key, | ||
| ), | ||
| createHmacSignature(metadata.urlSigningSecretKey, key), | ||
| ); | ||
| } | ||
|
|
||
|
|
@@ -44,11 +61,8 @@ export class KeyValueStore extends CoreKeyValueStore { | |
| */ | ||
| static override async open( | ||
| storeIdOrName?: string | null, | ||
| options: StorageManagerOptions = {}, | ||
| options: StorageOpenOptions = {}, | ||
| ): Promise<KeyValueStore> { | ||
| return super.open(storeIdOrName, options) as unknown as KeyValueStore; | ||
| } | ||
| } | ||
|
|
||
| // @ts-ignore newer crawlee versions already declare this method in core | ||
| CoreKeyValueStore.prototype.getPublicUrl = KeyValueStore.prototype.getPublicUrl; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe this change closes this issue - I'm not sure if the renaming was a requirement, or a way to make this BC.