@crawlee/fs-storage 4.0.0-beta.100
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +201 -0
- package/README.md +153 -0
- package/file-system-storage.d.ts +87 -0
- package/file-system-storage.js +229 -0
- package/index.d.ts +1 -0
- package/index.js +1 -0
- package/package.json +57 -0
- package/resource-clients/cached-id-client.d.ts +11 -0
- package/resource-clients/cached-id-client.js +13 -0
- package/resource-clients/dataset.d.ts +36 -0
- package/resource-clients/dataset.js +75 -0
- package/resource-clients/key-value-store.d.ts +81 -0
- package/resource-clients/key-value-store.js +239 -0
- package/resource-clients/request-queue.d.ts +51 -0
- package/resource-clients/request-queue.js +119 -0
- package/utils.d.ts +1 -0
- package/utils.js +5 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "{}"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2018 Apify Technologies s.r.o.
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
<h1 align="center">
|
|
2
|
+
<a href="https://crawlee.dev">
|
|
3
|
+
<picture>
|
|
4
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-dark.svg?sanitize=true" />
|
|
5
|
+
<img alt="Crawlee" src="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-light.svg?sanitize=true" width="500" />
|
|
6
|
+
</picture>
|
|
7
|
+
</a>
|
|
8
|
+
<br />
|
|
9
|
+
<small>A web scraping and browser automation library</small>
|
|
10
|
+
</h1>
|
|
11
|
+
|
|
12
|
+
<p align="center">
|
|
13
|
+
<a href="https://trendshift.io/repositories/5179" target="_blank"><img src="https://trendshift.io/api/badge/repositories/5179" alt="apify%2Fcrawlee | Trendshift" width="250" height="55"/></a>
|
|
14
|
+
</p>
|
|
15
|
+
|
|
16
|
+
<p align="center">
|
|
17
|
+
<a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/v/@crawlee/core.svg" alt="NPM latest version" data-canonical-src="https://img.shields.io/npm/v/@crawlee/core/next.svg" /></a>
|
|
18
|
+
<a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/dm/@crawlee/core.svg" alt="Downloads" data-canonical-src="https://img.shields.io/npm/dm/@crawlee/core.svg" /></a>
|
|
19
|
+
<a href="https://discord.gg/jyEM2PRvMU" rel="nofollow"><img src="https://img.shields.io/discord/801163717915574323?label=discord" alt="Chat on discord" data-canonical-src="https://img.shields.io/discord/801163717915574323?label=discord" /></a>
|
|
20
|
+
<a href="https://github.com/apify/crawlee/actions/workflows/test-ci.yml"><img src="https://github.com/apify/crawlee/actions/workflows/test-ci.yml/badge.svg?branch=master" alt="Build Status" /></a>
|
|
21
|
+
</p>
|
|
22
|
+
|
|
23
|
+
Crawlee covers your crawling and scraping end-to-end and **helps you build reliable scrapers. Fast.**
|
|
24
|
+
|
|
25
|
+
Your crawlers will appear human-like and fly under the radar of modern bot protections even with the default configuration. Crawlee gives you the tools to crawl the web for links, scrape data, and store it to disk or cloud while staying configurable to suit your project's needs.
|
|
26
|
+
|
|
27
|
+
Crawlee is available as the [`crawlee`](https://www.npmjs.com/package/crawlee) NPM package.
|
|
28
|
+
|
|
29
|
+
> 👉 **View full documentation, guides and examples on the [Crawlee project website](https://crawlee.dev)** 👈
|
|
30
|
+
|
|
31
|
+
> Do you prefer 🐍 Python instead of JavaScript? [👉 Checkout Crawlee for Python 👈](https://github.com/apify/crawlee-python).
|
|
32
|
+
|
|
33
|
+
## Installation
|
|
34
|
+
|
|
35
|
+
We recommend visiting the [Introduction tutorial](https://crawlee.dev/js/docs/introduction) in Crawlee documentation for more information.
|
|
36
|
+
|
|
37
|
+
> Crawlee requires **Node.js 16 or higher**.
|
|
38
|
+
|
|
39
|
+
### With Crawlee CLI
|
|
40
|
+
|
|
41
|
+
The fastest way to try Crawlee out is to use the **Crawlee CLI** and choose the **Getting started example**. The CLI will install all the necessary dependencies and add boilerplate code for you to play with.
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
npx crawlee create my-crawler
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
cd my-crawler
|
|
49
|
+
npm start
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### Manual installation
|
|
53
|
+
If you prefer adding Crawlee **into your own project**, try the example below. Because it uses `PlaywrightCrawler` we also need to install [Playwright](https://playwright.dev). It's not bundled with Crawlee to reduce install size.
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
npm install crawlee playwright
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
```js
|
|
60
|
+
import { PlaywrightCrawler, Dataset } from 'crawlee';
|
|
61
|
+
|
|
62
|
+
// PlaywrightCrawler crawls the web using a headless
|
|
63
|
+
// browser controlled by the Playwright library.
|
|
64
|
+
const crawler = new PlaywrightCrawler({
|
|
65
|
+
// Use the requestHandler to process each of the crawled pages.
|
|
66
|
+
async requestHandler({ request, page, enqueueLinks, log }) {
|
|
67
|
+
const title = await page.title();
|
|
68
|
+
log.info(`Title of ${request.loadedUrl} is '${title}'`);
|
|
69
|
+
|
|
70
|
+
// Save results as JSON to ./storage/datasets/default
|
|
71
|
+
await Dataset.pushData({ title, url: request.loadedUrl });
|
|
72
|
+
|
|
73
|
+
// Extract links from the current page
|
|
74
|
+
// and add them to the crawling queue.
|
|
75
|
+
await enqueueLinks();
|
|
76
|
+
},
|
|
77
|
+
// Uncomment this option to see the browser window.
|
|
78
|
+
// headless: false,
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
// Add first URL to the queue and start the crawl.
|
|
82
|
+
await crawler.run(['https://crawlee.dev']);
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
By default, Crawlee stores data to `./storage` in the current working directory. You can override this directory via Crawlee configuration. For details, see [Configuration guide](https://crawlee.dev/js/docs/guides/configuration), [Request storage](https://crawlee.dev/js/docs/guides/request-storage) and [Result storage](https://crawlee.dev/js/docs/guides/result-storage).
|
|
86
|
+
|
|
87
|
+
### Installing pre-release versions
|
|
88
|
+
|
|
89
|
+
We provide automated beta builds for every merged code change in Crawlee. You can find them in the npm [list of releases](https://www.npmjs.com/package/crawlee?activeTab=versions). If you want to test new features or bug fixes before we release them, feel free to install a beta build like this:
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
npm install crawlee@next
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
If you also use the [Apify SDK](https://github.com/apify/apify-sdk-js), you need to specify dependency overrides in your `package.json` file so that you don't end up with multiple versions of Crawlee installed:
|
|
96
|
+
|
|
97
|
+
```json
|
|
98
|
+
{
|
|
99
|
+
"overrides": {
|
|
100
|
+
"apify": {
|
|
101
|
+
"@crawlee/core": "$crawlee",
|
|
102
|
+
"@crawlee/types": "$crawlee",
|
|
103
|
+
"@crawlee/utils": "$crawlee"
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## 🛠 Features
|
|
110
|
+
|
|
111
|
+
- Single interface for **HTTP and headless browser** crawling
|
|
112
|
+
- Persistent **queue** for URLs to crawl (breadth & depth first)
|
|
113
|
+
- Pluggable **storage** of both tabular data and files
|
|
114
|
+
- Automatic **scaling** with available system resources
|
|
115
|
+
- Integrated **proxy rotation** and session management
|
|
116
|
+
- Lifecycles customizable with **hooks**
|
|
117
|
+
- **CLI** to bootstrap your projects
|
|
118
|
+
- Configurable **routing**, **error handling** and **retries**
|
|
119
|
+
- **Dockerfiles** ready to deploy
|
|
120
|
+
- Written in **TypeScript** with generics
|
|
121
|
+
|
|
122
|
+
### 👾 HTTP crawling
|
|
123
|
+
|
|
124
|
+
- Zero config **HTTP2 support**, even for proxies
|
|
125
|
+
- Automatic generation of **browser-like headers**
|
|
126
|
+
- Replication of browser **TLS fingerprints**
|
|
127
|
+
- Integrated fast **HTML parsers**. Cheerio and JSDOM
|
|
128
|
+
- Yes, you can scrape **JSON APIs** as well
|
|
129
|
+
|
|
130
|
+
### 💻 Real browser crawling
|
|
131
|
+
|
|
132
|
+
- JavaScript **rendering** and **screenshots**
|
|
133
|
+
- **Headless** and **headful** support
|
|
134
|
+
- Zero-config generation of **human-like fingerprints**
|
|
135
|
+
- Automatic **browser management**
|
|
136
|
+
- Use **Playwright** and **Puppeteer** with the same interface
|
|
137
|
+
- **Chrome**, **Firefox**, **Webkit** and many others
|
|
138
|
+
|
|
139
|
+
## Usage on the Apify platform
|
|
140
|
+
|
|
141
|
+
Crawlee is open-source and runs anywhere, but since it's developed by [Apify](https://apify.com), it's easy to set up on the Apify platform and run in the cloud. Visit the [Apify SDK website](https://sdk.apify.com) to learn more about deploying Crawlee to the Apify platform.
|
|
142
|
+
|
|
143
|
+
## Support
|
|
144
|
+
|
|
145
|
+
If you find any bug or issue with Crawlee, please [submit an issue on GitHub](https://github.com/apify/crawlee/issues). For questions, you can ask on [Stack Overflow](https://stackoverflow.com/questions/tagged/apify), in GitHub Discussions or you can join our [Discord server](https://discord.com/invite/jyEM2PRvMU).
|
|
146
|
+
|
|
147
|
+
## Contributing
|
|
148
|
+
|
|
149
|
+
Your code contributions are welcome, and you'll be praised to eternity! If you have any ideas for improvements, either submit an issue or create a pull request. For contribution guidelines and the code of conduct, see [CONTRIBUTING.md](https://github.com/apify/crawlee/blob/master/CONTRIBUTING.md).
|
|
150
|
+
|
|
151
|
+
## License
|
|
152
|
+
|
|
153
|
+
This project is licensed under the Apache License 2.0 - see the [LICENSE.md](https://github.com/apify/crawlee/blob/master/LICENSE.md) file for details.
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import type * as storage from '@crawlee/types';
|
|
2
|
+
import type { CrawleeLogger } from '@crawlee/types';
|
|
3
|
+
import { DatasetBackend } from './resource-clients/dataset.js';
|
|
4
|
+
import { KeyValueStoreBackend } from './resource-clients/key-value-store.js';
|
|
5
|
+
import { RequestQueueBackend } from './resource-clients/request-queue.js';
|
|
6
|
+
export interface FileSystemStorageOptions {
|
|
7
|
+
/**
|
|
8
|
+
* Path to directory where the data will be saved.
|
|
9
|
+
*/
|
|
10
|
+
localDataDirectory: string;
|
|
11
|
+
/**
|
|
12
|
+
* Optional logger for FileSystemStorageBackend warnings.
|
|
13
|
+
*/
|
|
14
|
+
logger?: CrawleeLogger;
|
|
15
|
+
/**
|
|
16
|
+
* How the on-disk request queues opened by this backend are expected to be accessed.
|
|
17
|
+
*
|
|
18
|
+
* With `'single'` (the default), this process asserts it is the *sole* consumer of every request
|
|
19
|
+
* queue it opens: on open, any requests that a previous run left *in progress* (e.g. after a
|
|
20
|
+
* crash) are reclaimed immediately, so they become fetchable again right away. This is the right
|
|
21
|
+
* behavior for the common single-process crawl.
|
|
22
|
+
*
|
|
23
|
+
* Use `'shared'` if multiple processes share the same on-disk request queue concurrently (for
|
|
24
|
+
* example, the {@link parallel scraping setup | "Parallel Scraping Guide"}). In that mode an
|
|
25
|
+
* in-progress request is treated as a potential live peer's lock and is only reclaimed once that
|
|
26
|
+
* lock expires on the wall clock, so two workers won't process the same request at once.
|
|
27
|
+
*
|
|
28
|
+
* @default 'single'
|
|
29
|
+
*/
|
|
30
|
+
requestQueueAccess?: 'single' | 'shared';
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* A file-system storage backend backed by the native `@crawlee/fs-storage-native` Rust extension.
|
|
34
|
+
*
|
|
35
|
+
* The native extension owns the on-disk format, timestamps, item counting, request-queue locking and
|
|
36
|
+
* state persistence. This class is responsible for resolving the user-facing `id` / `name` / `alias`
|
|
37
|
+
* identifiers to native storages, caching the opened backends (so that `storageExists`, `purge` and
|
|
38
|
+
* `teardown` can operate over them), and exposing them through the `@crawlee/types` interfaces.
|
|
39
|
+
*/
|
|
40
|
+
export declare class FileSystemStorageBackend implements storage.StorageBackend {
|
|
41
|
+
readonly localDataDirectory: string;
|
|
42
|
+
readonly datasetsDirectory: string;
|
|
43
|
+
readonly keyValueStoresDirectory: string;
|
|
44
|
+
readonly requestQueuesDirectory: string;
|
|
45
|
+
readonly logger?: CrawleeLogger;
|
|
46
|
+
readonly requestQueueAccess: 'single' | 'shared';
|
|
47
|
+
readonly keyValueStoreBackendCache: KeyValueStoreBackend[];
|
|
48
|
+
readonly datasetBackendCache: DatasetBackend[];
|
|
49
|
+
readonly requestQueueBackendCache: RequestQueueBackend[];
|
|
50
|
+
constructor(options: FileSystemStorageOptions);
|
|
51
|
+
/**
|
|
52
|
+
* Return a cache key that includes the resolved storage directory, so that two
|
|
53
|
+
* `FileSystemStorageBackend` instances pointing at different directories get separate cache
|
|
54
|
+
* partitions, by including the storage directory in the cache key.
|
|
55
|
+
*/
|
|
56
|
+
getStorageBackendCacheKey(): string;
|
|
57
|
+
private static resolveStorageKey;
|
|
58
|
+
createDatasetBackend(options?: storage.StorageIdentifier): Promise<storage.DatasetBackend>;
|
|
59
|
+
createKeyValueStoreBackend(options?: storage.StorageIdentifier): Promise<storage.KeyValueStoreBackend>;
|
|
60
|
+
createRequestQueueBackend(options?: storage.StorageIdentifier): Promise<storage.RequestQueueBackend>;
|
|
61
|
+
storageExists(id: string, type: 'Dataset' | 'KeyValueStore' | 'RequestQueue'): Promise<boolean>;
|
|
62
|
+
/**
|
|
63
|
+
* Resolve the real `id` of the on-disk storage identified by `entryNameOrId` under `baseDirectory`,
|
|
64
|
+
* or `undefined` if none matches. The storage's real id lives in its directory's
|
|
65
|
+
* `__metadata__.json`; the directory itself is named after the storage's `name ?? id`. So this
|
|
66
|
+
* first tries the directory named exactly `entryNameOrId` (reading its metadata id), then falls
|
|
67
|
+
* back to scanning sibling directories for one whose metadata id equals `entryNameOrId` (the case
|
|
68
|
+
* of a storage opened by name and later looked up by its auto-assigned id).
|
|
69
|
+
*/
|
|
70
|
+
private static resolveStorageIdOnDisk;
|
|
71
|
+
/** Read the `id` field from a storage directory's `__metadata__.json`, or `undefined` if absent. */
|
|
72
|
+
private static readMetadataId;
|
|
73
|
+
/**
|
|
74
|
+
* Cleans up the default storages before the run starts:
|
|
75
|
+
* - the default dataset;
|
|
76
|
+
* - all records from the default key-value store, except for the "INPUT" key;
|
|
77
|
+
* - the default request queue.
|
|
78
|
+
*/
|
|
79
|
+
purge(): Promise<void>;
|
|
80
|
+
/**
|
|
81
|
+
* This method should be called at the end of the process, to ensure all data is saved.
|
|
82
|
+
*
|
|
83
|
+
* It persists the state of every opened request queue so that requests fetched but not yet handled
|
|
84
|
+
* are not stuck (until their lock expires) for the next consumer of the same on-disk queue.
|
|
85
|
+
*/
|
|
86
|
+
teardown(): Promise<void>;
|
|
87
|
+
}
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { opendir, readFile } from 'node:fs/promises';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { s } from '@sapphire/shapeshift';
|
|
4
|
+
import { FileSystemDatasetClient as NativeDatasetBackend, FileSystemKeyValueStoreClient as NativeKeyValueStoreBackend, FileSystemRequestQueueClient as NativeRequestQueueBackend, } from '@crawlee/fs-storage-native';
|
|
5
|
+
import { DatasetBackend } from './resource-clients/dataset.js';
|
|
6
|
+
import { KeyValueStoreBackend } from './resource-clients/key-value-store.js';
|
|
7
|
+
import { RequestQueueBackend } from './resource-clients/request-queue.js';
|
|
8
|
+
/**
|
|
9
|
+
* A file-system storage backend backed by the native `@crawlee/fs-storage-native` Rust extension.
|
|
10
|
+
*
|
|
11
|
+
* The native extension owns the on-disk format, timestamps, item counting, request-queue locking and
|
|
12
|
+
* state persistence. This class is responsible for resolving the user-facing `id` / `name` / `alias`
|
|
13
|
+
* identifiers to native storages, caching the opened backends (so that `storageExists`, `purge` and
|
|
14
|
+
* `teardown` can operate over them), and exposing them through the `@crawlee/types` interfaces.
|
|
15
|
+
*/
|
|
16
|
+
export class FileSystemStorageBackend {
|
|
17
|
+
localDataDirectory;
|
|
18
|
+
datasetsDirectory;
|
|
19
|
+
keyValueStoresDirectory;
|
|
20
|
+
requestQueuesDirectory;
|
|
21
|
+
logger;
|
|
22
|
+
requestQueueAccess;
|
|
23
|
+
keyValueStoreBackendCache = [];
|
|
24
|
+
datasetBackendCache = [];
|
|
25
|
+
requestQueueBackendCache = [];
|
|
26
|
+
constructor(options) {
|
|
27
|
+
s.object({
|
|
28
|
+
localDataDirectory: s.string(),
|
|
29
|
+
requestQueueAccess: s.enum(['single', 'shared']).optional(),
|
|
30
|
+
}).parse(options);
|
|
31
|
+
this.logger = options.logger;
|
|
32
|
+
this.requestQueueAccess = options.requestQueueAccess ?? 'single';
|
|
33
|
+
this.localDataDirectory = options.localDataDirectory;
|
|
34
|
+
this.datasetsDirectory = resolve(this.localDataDirectory, 'datasets');
|
|
35
|
+
this.keyValueStoresDirectory = resolve(this.localDataDirectory, 'key_value_stores');
|
|
36
|
+
this.requestQueuesDirectory = resolve(this.localDataDirectory, 'request_queues');
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Return a cache key that includes the resolved storage directory, so that two
|
|
40
|
+
* `FileSystemStorageBackend` instances pointing at different directories get separate cache
|
|
41
|
+
* partitions, by including the storage directory in the cache key.
|
|
42
|
+
*/
|
|
43
|
+
getStorageBackendCacheKey() {
|
|
44
|
+
return `FileSystemStorageBackend:${resolve(this.localDataDirectory)}`;
|
|
45
|
+
}
|
|
46
|
+
static resolveStorageKey(options) {
|
|
47
|
+
const isAlias = 'alias' in options && !!options.alias;
|
|
48
|
+
const rawKey = isAlias ? options.alias : (options.name ?? options.id);
|
|
49
|
+
// Normalize the internal __default__ alias to the user-facing 'default' name.
|
|
50
|
+
const cacheKey = rawKey === '__default__' ? 'default' : rawKey;
|
|
51
|
+
return { id: options.id, name: options.name, alias: options.alias, cacheKey };
|
|
52
|
+
}
|
|
53
|
+
async createDatasetBackend(options = {}) {
|
|
54
|
+
const { id, name, alias, cacheKey } = FileSystemStorageBackend.resolveStorageKey(options);
|
|
55
|
+
if (cacheKey) {
|
|
56
|
+
const found = this.datasetBackendCache.find((store) => store.id === cacheKey ||
|
|
57
|
+
store.name?.toLowerCase() === cacheKey.toLowerCase() ||
|
|
58
|
+
store.cacheKey.toLowerCase() === cacheKey.toLowerCase());
|
|
59
|
+
if (found) {
|
|
60
|
+
return found;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
const nativeBackend = await NativeDatasetBackend.open(id, name, alias, this.localDataDirectory);
|
|
64
|
+
const newStore = await DatasetBackend.create({
|
|
65
|
+
name: alias ? undefined : (name ?? cacheKey),
|
|
66
|
+
cacheKey: cacheKey ?? '',
|
|
67
|
+
nativeBackend,
|
|
68
|
+
logger: this.logger,
|
|
69
|
+
});
|
|
70
|
+
this.datasetBackendCache.push(newStore);
|
|
71
|
+
return newStore;
|
|
72
|
+
}
|
|
73
|
+
async createKeyValueStoreBackend(options = {}) {
|
|
74
|
+
const { id, name, alias, cacheKey } = FileSystemStorageBackend.resolveStorageKey(options);
|
|
75
|
+
if (cacheKey) {
|
|
76
|
+
const found = this.keyValueStoreBackendCache.find((store) => store.id === cacheKey ||
|
|
77
|
+
store.name?.toLowerCase() === cacheKey.toLowerCase() ||
|
|
78
|
+
store.cacheKey.toLowerCase() === cacheKey.toLowerCase());
|
|
79
|
+
if (found) {
|
|
80
|
+
return found;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
const nativeBackend = await NativeKeyValueStoreBackend.open(id, name, alias, this.localDataDirectory);
|
|
84
|
+
const newStore = await KeyValueStoreBackend.create({
|
|
85
|
+
name: alias ? undefined : (name ?? cacheKey),
|
|
86
|
+
cacheKey: cacheKey ?? '',
|
|
87
|
+
nativeBackend,
|
|
88
|
+
logger: this.logger,
|
|
89
|
+
});
|
|
90
|
+
this.keyValueStoreBackendCache.push(newStore);
|
|
91
|
+
return newStore;
|
|
92
|
+
}
|
|
93
|
+
async createRequestQueueBackend(options = {}) {
|
|
94
|
+
const { id, name, alias, cacheKey } = FileSystemStorageBackend.resolveStorageKey(options);
|
|
95
|
+
if (cacheKey) {
|
|
96
|
+
const found = this.requestQueueBackendCache.find((queue) => queue.id === cacheKey ||
|
|
97
|
+
queue.name?.toLowerCase() === cacheKey.toLowerCase() ||
|
|
98
|
+
queue.cacheKey.toLowerCase() === cacheKey.toLowerCase());
|
|
99
|
+
if (found) {
|
|
100
|
+
return found;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const nativeBackend = await NativeRequestQueueBackend.open(id, name, alias, this.localDataDirectory,
|
|
104
|
+
// useTestClock — always real wall-clock outside of native tests.
|
|
105
|
+
undefined, this.requestQueueAccess);
|
|
106
|
+
const newStore = await RequestQueueBackend.create({
|
|
107
|
+
name: alias ? undefined : (name ?? cacheKey),
|
|
108
|
+
cacheKey: cacheKey ?? '',
|
|
109
|
+
nativeBackend,
|
|
110
|
+
logger: this.logger,
|
|
111
|
+
});
|
|
112
|
+
this.requestQueueBackendCache.push(newStore);
|
|
113
|
+
return newStore;
|
|
114
|
+
}
|
|
115
|
+
async storageExists(id, type) {
|
|
116
|
+
let backends;
|
|
117
|
+
let baseDir;
|
|
118
|
+
switch (type) {
|
|
119
|
+
case 'Dataset':
|
|
120
|
+
backends = this.datasetBackendCache;
|
|
121
|
+
baseDir = this.datasetsDirectory;
|
|
122
|
+
break;
|
|
123
|
+
case 'KeyValueStore':
|
|
124
|
+
backends = this.keyValueStoreBackendCache;
|
|
125
|
+
baseDir = this.keyValueStoresDirectory;
|
|
126
|
+
break;
|
|
127
|
+
case 'RequestQueue':
|
|
128
|
+
backends = this.requestQueueBackendCache;
|
|
129
|
+
baseDir = this.requestQueuesDirectory;
|
|
130
|
+
break;
|
|
131
|
+
default:
|
|
132
|
+
return false;
|
|
133
|
+
}
|
|
134
|
+
// Check the in-memory cache by actual storage ID first.
|
|
135
|
+
if (backends.some((store) => store.id === id)) {
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
// Otherwise, resolve any on-disk storage that matches the queried string — either by its
|
|
139
|
+
// directory name, or (for a storage opened by name, whose directory is named after the name)
|
|
140
|
+
// by scanning the `__metadata__.json` files for a matching id.
|
|
141
|
+
//
|
|
142
|
+
// A directory-name match does NOT by itself prove the string is the storage's *id*: the
|
|
143
|
+
// directory is named after `name ?? id`, so `named-storage`/`on-disk` (a name or alias) also
|
|
144
|
+
// has a matching directory. We therefore read the real id from the metadata and only report
|
|
145
|
+
// existence when it equals the queried string. This matches upstream PR #3800/#3808 and
|
|
146
|
+
// prevents a named storage from being re-resolved as `{ id: name }` on a subsequent run.
|
|
147
|
+
const resolvedId = await FileSystemStorageBackend.resolveStorageIdOnDisk(baseDir, id);
|
|
148
|
+
return resolvedId === id;
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Resolve the real `id` of the on-disk storage identified by `entryNameOrId` under `baseDirectory`,
|
|
152
|
+
* or `undefined` if none matches. The storage's real id lives in its directory's
|
|
153
|
+
* `__metadata__.json`; the directory itself is named after the storage's `name ?? id`. So this
|
|
154
|
+
* first tries the directory named exactly `entryNameOrId` (reading its metadata id), then falls
|
|
155
|
+
* back to scanning sibling directories for one whose metadata id equals `entryNameOrId` (the case
|
|
156
|
+
* of a storage opened by name and later looked up by its auto-assigned id).
|
|
157
|
+
*/
|
|
158
|
+
static async resolveStorageIdOnDisk(baseDirectory, entryNameOrId) {
|
|
159
|
+
// Directory named exactly after the string: return its real (metadata) id, which may differ
|
|
160
|
+
// from the string when the string is a name rather than an id.
|
|
161
|
+
const directId = await FileSystemStorageBackend.readMetadataId(resolve(baseDirectory, entryNameOrId));
|
|
162
|
+
if (directId !== undefined) {
|
|
163
|
+
return directId;
|
|
164
|
+
}
|
|
165
|
+
// No such directory — scan siblings for one whose metadata id matches the string.
|
|
166
|
+
let directories;
|
|
167
|
+
try {
|
|
168
|
+
directories = await opendir(baseDirectory);
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
return undefined;
|
|
172
|
+
}
|
|
173
|
+
for await (const directory of directories) {
|
|
174
|
+
if (!directory.isDirectory()) {
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
const metadataId = await FileSystemStorageBackend.readMetadataId(resolve(baseDirectory, directory.name));
|
|
178
|
+
if (metadataId === entryNameOrId) {
|
|
179
|
+
return metadataId;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return undefined;
|
|
183
|
+
}
|
|
184
|
+
/** Read the `id` field from a storage directory's `__metadata__.json`, or `undefined` if absent. */
|
|
185
|
+
static async readMetadataId(storageDirectory) {
|
|
186
|
+
try {
|
|
187
|
+
const fileContent = await readFile(resolve(storageDirectory, '__metadata__.json'), 'utf8');
|
|
188
|
+
return JSON.parse(fileContent).id;
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
// Directory missing, or no/unreadable metadata file — no id to report.
|
|
192
|
+
return undefined;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Cleans up the default storages before the run starts:
|
|
197
|
+
* - the default dataset;
|
|
198
|
+
* - all records from the default key-value store, except for the "INPUT" key;
|
|
199
|
+
* - the default request queue.
|
|
200
|
+
*/
|
|
201
|
+
async purge() {
|
|
202
|
+
// Resolve the default stores up front so leftover on-disk records are purged even when the
|
|
203
|
+
// store has not been opened in this process yet (e.g. a fresh run over a pre-existing
|
|
204
|
+
// directory). Opening caches the backend, so the subsequent purge operates on a real backend.
|
|
205
|
+
// The default store is opened via the internal `__default__` alias (see resolveStorageIdentifier
|
|
206
|
+
// in @crawlee/core), which resolves to the `default` cache key — match that here so we purge the
|
|
207
|
+
// very backend the default open would return rather than creating a divergent one.
|
|
208
|
+
const [defaultKeyValueStore, defaultDataset, defaultRequestQueue] = await Promise.all([
|
|
209
|
+
this.createKeyValueStoreBackend({ alias: '__default__' }),
|
|
210
|
+
this.createDatasetBackend({ alias: '__default__' }),
|
|
211
|
+
this.createRequestQueueBackend({ alias: '__default__' }),
|
|
212
|
+
]);
|
|
213
|
+
await Promise.all([
|
|
214
|
+
// Preserve the run input (INPUT) when purging the default key-value store.
|
|
215
|
+
defaultKeyValueStore.purgeExceptInput(),
|
|
216
|
+
defaultDataset.purge(),
|
|
217
|
+
defaultRequestQueue.purge(),
|
|
218
|
+
]);
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* This method should be called at the end of the process, to ensure all data is saved.
|
|
222
|
+
*
|
|
223
|
+
* It persists the state of every opened request queue so that requests fetched but not yet handled
|
|
224
|
+
* are not stuck (until their lock expires) for the next consumer of the same on-disk queue.
|
|
225
|
+
*/
|
|
226
|
+
async teardown() {
|
|
227
|
+
await Promise.all(this.requestQueueBackendCache.map(async (queue) => queue.persistState()));
|
|
228
|
+
}
|
|
229
|
+
}
|