@crawlee/core 4.0.0-beta.8 → 4.0.0-beta.81
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/README.md +17 -13
- package/autoscaling/autoscaled_pool.d.ts +14 -15
- package/autoscaling/autoscaled_pool.js +37 -36
- package/autoscaling/client_load_signal.d.ts +25 -0
- package/autoscaling/client_load_signal.js +36 -0
- package/autoscaling/cpu_load_signal.d.ts +28 -0
- package/autoscaling/cpu_load_signal.js +24 -0
- package/autoscaling/event_loop_load_signal.d.ts +23 -0
- package/autoscaling/event_loop_load_signal.js +35 -0
- package/autoscaling/index.d.ts +5 -1
- package/autoscaling/index.js +5 -1
- package/autoscaling/load_signal.d.ts +99 -0
- package/autoscaling/load_signal.js +135 -0
- package/autoscaling/memory_load_signal.d.ts +43 -0
- package/autoscaling/memory_load_signal.js +102 -0
- package/autoscaling/snapshotter.d.ts +29 -91
- package/autoscaling/snapshotter.js +65 -204
- package/autoscaling/system_status.d.ts +22 -37
- package/autoscaling/system_status.js +49 -87
- package/configuration.d.ts +88 -228
- package/configuration.js +162 -224
- package/cookie_utils.d.ts +4 -3
- package/cookie_utils.js +20 -13
- package/crawlers/context_pipeline.d.ts +70 -0
- package/crawlers/context_pipeline.js +122 -0
- package/crawlers/crawler_commons.d.ts +20 -30
- package/crawlers/crawler_commons.js +12 -21
- package/crawlers/crawler_utils.d.ts +2 -3
- package/crawlers/crawler_utils.js +1 -2
- package/crawlers/error_snapshotter.d.ts +3 -3
- package/crawlers/error_snapshotter.js +2 -3
- package/crawlers/error_tracker.d.ts +2 -2
- package/crawlers/error_tracker.js +0 -1
- package/crawlers/index.d.ts +1 -2
- package/crawlers/index.js +1 -2
- package/crawlers/internals/types.d.ts +7 -0
- package/crawlers/internals/types.js +1 -0
- package/crawlers/statistics.d.ts +28 -23
- package/crawlers/statistics.js +38 -34
- package/enqueue_links/enqueue_links.d.ts +44 -22
- package/enqueue_links/enqueue_links.js +51 -30
- package/enqueue_links/index.d.ts +0 -1
- package/enqueue_links/index.js +0 -1
- package/enqueue_links/shared.d.ts +25 -9
- package/enqueue_links/shared.js +69 -38
- package/errors.d.ts +53 -4
- package/errors.js +70 -5
- package/events/event_manager.d.ts +34 -8
- package/events/event_manager.js +8 -10
- package/events/index.d.ts +0 -1
- package/events/index.js +0 -1
- package/events/local_event_manager.d.ts +15 -5
- package/events/local_event_manager.js +37 -40
- package/index.d.ts +4 -3
- package/index.js +3 -2
- package/log.d.ts +82 -3
- package/log.js +102 -1
- package/memory-storage/consts.d.ts +4 -0
- package/memory-storage/consts.js +4 -0
- package/memory-storage/index.d.ts +1 -0
- package/memory-storage/index.js +1 -0
- package/memory-storage/memory-storage.d.ts +46 -0
- package/memory-storage/memory-storage.js +136 -0
- package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
- package/memory-storage/resource-clients/common/base-client.js +6 -0
- package/memory-storage/resource-clients/dataset.d.ts +40 -0
- package/memory-storage/resource-clients/dataset.js +113 -0
- package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
- package/memory-storage/resource-clients/key-value-store.js +203 -0
- package/memory-storage/resource-clients/request-queue.d.ts +96 -0
- package/memory-storage/resource-clients/request-queue.js +421 -0
- package/memory-storage/utils.d.ts +17 -0
- package/memory-storage/utils.js +42 -0
- package/package.json +12 -10
- package/proxy_configuration.d.ts +29 -152
- package/proxy_configuration.js +21 -173
- package/recoverable_state.d.ts +120 -0
- package/recoverable_state.js +141 -0
- package/request.d.ts +84 -13
- package/request.js +107 -28
- package/router.d.ts +118 -16
- package/router.js +124 -30
- package/serialization.d.ts +0 -1
- package/serialization.js +1 -2
- package/service_locator.d.ts +156 -0
- package/service_locator.js +238 -0
- package/session_pool/consts.d.ts +1 -2
- package/session_pool/consts.js +1 -2
- package/session_pool/errors.d.ts +0 -1
- package/session_pool/errors.js +0 -1
- package/session_pool/fingerprint.d.ts +9 -0
- package/session_pool/fingerprint.js +30 -0
- package/session_pool/index.d.ts +0 -2
- package/session_pool/index.js +0 -2
- package/session_pool/session.d.ts +37 -75
- package/session_pool/session.js +49 -102
- package/session_pool/session_pool.d.ts +85 -90
- package/session_pool/session_pool.js +131 -120
- package/storages/access_checking.d.ts +0 -1
- package/storages/access_checking.js +5 -2
- package/storages/dataset.d.ts +101 -51
- package/storages/dataset.js +168 -126
- package/storages/index.d.ts +8 -7
- package/storages/index.js +6 -7
- package/storages/key_value_store.d.ts +165 -36
- package/storages/key_value_store.js +269 -122
- package/storages/key_value_store_codec.d.ts +32 -0
- package/storages/key_value_store_codec.js +113 -0
- package/storages/request_dedup_cache.d.ts +23 -0
- package/storages/request_dedup_cache.js +48 -0
- package/storages/request_list.d.ts +53 -97
- package/storages/request_list.js +99 -75
- package/storages/request_loader.d.ts +96 -0
- package/storages/request_loader.js +1 -0
- package/storages/request_manager.d.ts +33 -0
- package/storages/request_manager.js +1 -0
- package/storages/request_manager_tandem.d.ts +106 -0
- package/storages/request_manager_tandem.js +197 -0
- package/storages/request_queue.d.ts +290 -47
- package/storages/request_queue.js +628 -215
- package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +28 -24
- package/storages/{sitemap_request_list.js → sitemap_request_loader.js} +49 -46
- package/storages/storage_instance_manager.d.ts +91 -0
- package/storages/storage_instance_manager.js +258 -0
- package/storages/storage_stats.d.ts +48 -0
- package/storages/storage_stats.js +29 -0
- package/storages/utils.d.ts +51 -6
- package/storages/utils.js +60 -9
- package/system-info/cpu-info.d.ts +67 -0
- package/system-info/cpu-info.js +216 -0
- package/system-info/memory-info.d.ts +31 -0
- package/system-info/memory-info.js +115 -0
- package/system-info/ps-tree.d.ts +17 -0
- package/system-info/ps-tree.js +144 -0
- package/system-info/runtime.d.ts +14 -0
- package/system-info/runtime.js +80 -0
- package/typedefs.d.ts +1 -2
- package/typedefs.js +0 -1
- package/validators.d.ts +8 -1
- package/validators.js +10 -3
- package/autoscaling/autoscaled_pool.d.ts.map +0 -1
- package/autoscaling/autoscaled_pool.js.map +0 -1
- package/autoscaling/index.d.ts.map +0 -1
- package/autoscaling/index.js.map +0 -1
- package/autoscaling/snapshotter.d.ts.map +0 -1
- package/autoscaling/snapshotter.js.map +0 -1
- package/autoscaling/system_status.d.ts.map +0 -1
- package/autoscaling/system_status.js.map +0 -1
- package/configuration.d.ts.map +0 -1
- package/configuration.js.map +0 -1
- package/cookie_utils.d.ts.map +0 -1
- package/cookie_utils.js.map +0 -1
- package/crawlers/crawler_commons.d.ts.map +0 -1
- package/crawlers/crawler_commons.js.map +0 -1
- package/crawlers/crawler_extension.d.ts +0 -12
- package/crawlers/crawler_extension.d.ts.map +0 -1
- package/crawlers/crawler_extension.js +0 -14
- package/crawlers/crawler_extension.js.map +0 -1
- package/crawlers/crawler_utils.d.ts.map +0 -1
- package/crawlers/crawler_utils.js.map +0 -1
- package/crawlers/error_snapshotter.d.ts.map +0 -1
- package/crawlers/error_snapshotter.js.map +0 -1
- package/crawlers/error_tracker.d.ts.map +0 -1
- package/crawlers/error_tracker.js.map +0 -1
- package/crawlers/index.d.ts.map +0 -1
- package/crawlers/index.js.map +0 -1
- package/crawlers/statistics.d.ts.map +0 -1
- package/crawlers/statistics.js.map +0 -1
- package/enqueue_links/enqueue_links.d.ts.map +0 -1
- package/enqueue_links/enqueue_links.js.map +0 -1
- package/enqueue_links/index.d.ts.map +0 -1
- package/enqueue_links/index.js.map +0 -1
- package/enqueue_links/shared.d.ts.map +0 -1
- package/enqueue_links/shared.js.map +0 -1
- package/errors.d.ts.map +0 -1
- package/errors.js.map +0 -1
- package/events/event_manager.d.ts.map +0 -1
- package/events/event_manager.js.map +0 -1
- package/events/index.d.ts.map +0 -1
- package/events/index.js.map +0 -1
- package/events/local_event_manager.d.ts.map +0 -1
- package/events/local_event_manager.js.map +0 -1
- package/http_clients/base-http-client.d.ts +0 -134
- package/http_clients/base-http-client.d.ts.map +0 -1
- package/http_clients/base-http-client.js +0 -33
- package/http_clients/base-http-client.js.map +0 -1
- package/http_clients/form-data-like.d.ts +0 -67
- package/http_clients/form-data-like.d.ts.map +0 -1
- package/http_clients/form-data-like.js +0 -5
- package/http_clients/form-data-like.js.map +0 -1
- package/http_clients/got-scraping-http-client.d.ts +0 -15
- package/http_clients/got-scraping-http-client.d.ts.map +0 -1
- package/http_clients/got-scraping-http-client.js +0 -69
- package/http_clients/got-scraping-http-client.js.map +0 -1
- package/http_clients/index.d.ts +0 -3
- package/http_clients/index.d.ts.map +0 -1
- package/http_clients/index.js +0 -3
- package/http_clients/index.js.map +0 -1
- package/index.d.ts.map +0 -1
- package/index.js.map +0 -1
- package/log.d.ts.map +0 -1
- package/log.js.map +0 -1
- package/proxy_configuration.d.ts.map +0 -1
- package/proxy_configuration.js.map +0 -1
- package/request.d.ts.map +0 -1
- package/request.js.map +0 -1
- package/router.d.ts.map +0 -1
- package/router.js.map +0 -1
- package/serialization.d.ts.map +0 -1
- package/serialization.js.map +0 -1
- package/session_pool/consts.d.ts.map +0 -1
- package/session_pool/consts.js.map +0 -1
- package/session_pool/errors.d.ts.map +0 -1
- package/session_pool/errors.js.map +0 -1
- package/session_pool/events.d.ts +0 -3
- package/session_pool/events.d.ts.map +0 -1
- package/session_pool/events.js +0 -3
- package/session_pool/events.js.map +0 -1
- package/session_pool/index.d.ts.map +0 -1
- package/session_pool/index.js.map +0 -1
- package/session_pool/session.d.ts.map +0 -1
- package/session_pool/session.js.map +0 -1
- package/session_pool/session_pool.d.ts.map +0 -1
- package/session_pool/session_pool.js.map +0 -1
- package/storages/access_checking.d.ts.map +0 -1
- package/storages/access_checking.js.map +0 -1
- package/storages/dataset.d.ts.map +0 -1
- package/storages/dataset.js.map +0 -1
- package/storages/index.d.ts.map +0 -1
- package/storages/index.js.map +0 -1
- package/storages/key_value_store.d.ts.map +0 -1
- package/storages/key_value_store.js.map +0 -1
- package/storages/request_list.d.ts.map +0 -1
- package/storages/request_list.js.map +0 -1
- package/storages/request_provider.d.ts +0 -307
- package/storages/request_provider.d.ts.map +0 -1
- package/storages/request_provider.js +0 -555
- package/storages/request_provider.js.map +0 -1
- package/storages/request_queue.d.ts.map +0 -1
- package/storages/request_queue.js.map +0 -1
- package/storages/request_queue_v2.d.ts +0 -87
- package/storages/request_queue_v2.d.ts.map +0 -1
- package/storages/request_queue_v2.js +0 -438
- package/storages/request_queue_v2.js.map +0 -1
- package/storages/sitemap_request_list.d.ts.map +0 -1
- package/storages/sitemap_request_list.js.map +0 -1
- package/storages/storage_manager.d.ts +0 -58
- package/storages/storage_manager.d.ts.map +0 -1
- package/storages/storage_manager.js +0 -105
- package/storages/storage_manager.js.map +0 -1
- package/storages/utils.d.ts.map +0 -1
- package/storages/utils.js.map +0 -1
- package/tsconfig.build.tsbuildinfo +0 -1
- package/typedefs.d.ts.map +0 -1
- package/typedefs.js.map +0 -1
- package/validators.d.ts.map +0 -1
- package/validators.js.map +0 -1
package/session_pool/session.js
CHANGED
|
@@ -1,10 +1,8 @@
|
|
|
1
|
-
import { EventEmitter } from 'node:events';
|
|
2
1
|
import ow from 'ow';
|
|
3
2
|
import { CookieJar } from 'tough-cookie';
|
|
4
3
|
import { cryptoRandomObjectId } from '@apify/utilities';
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { EVENT_SESSION_RETIRED } from './events.js';
|
|
4
|
+
import { getDefaultCookieExpirationDate } from '../cookie_utils.js';
|
|
5
|
+
import { serviceLocator } from '../service_locator.js';
|
|
8
6
|
/**
|
|
9
7
|
* Sessions are used to store information such as cookies and can be used for generating fingerprints and proxy sessions.
|
|
10
8
|
* You can imagine each session as a specific user, with its own cookies, IP (via proxy) and potentially a unique browser fingerprint.
|
|
@@ -13,7 +11,6 @@ import { EVENT_SESSION_RETIRED } from './events.js';
|
|
|
13
11
|
*/
|
|
14
12
|
export class Session {
|
|
15
13
|
id;
|
|
16
|
-
maxAgeSecs;
|
|
17
14
|
userData;
|
|
18
15
|
_maxErrorScore;
|
|
19
16
|
_errorScoreDecrement;
|
|
@@ -21,9 +18,11 @@ export class Session {
|
|
|
21
18
|
_expiresAt;
|
|
22
19
|
_usageCount;
|
|
23
20
|
_maxUsageCount;
|
|
24
|
-
sessionPool;
|
|
25
21
|
_errorScore;
|
|
22
|
+
_retired = false;
|
|
23
|
+
_proxyInfo;
|
|
26
24
|
_cookieJar;
|
|
25
|
+
_fingerprint;
|
|
27
26
|
log;
|
|
28
27
|
get errorScore() {
|
|
29
28
|
return this._errorScore;
|
|
@@ -49,14 +48,30 @@ export class Session {
|
|
|
49
48
|
get cookieJar() {
|
|
50
49
|
return this._cookieJar;
|
|
51
50
|
}
|
|
51
|
+
get proxyInfo() {
|
|
52
|
+
return this._proxyInfo;
|
|
53
|
+
}
|
|
54
|
+
get fingerprint() {
|
|
55
|
+
return this._fingerprint;
|
|
56
|
+
}
|
|
57
|
+
set fingerprint(fingerprint) {
|
|
58
|
+
this._fingerprint = fingerprint;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* `true` once {@link Session.retire|`retire()`} has been called. Retirement is terminal:
|
|
62
|
+
* a retired session is never picked by the pool and cannot be revived via `markGood()`.
|
|
63
|
+
*/
|
|
64
|
+
get retired() {
|
|
65
|
+
return this._retired;
|
|
66
|
+
}
|
|
52
67
|
/**
|
|
53
68
|
* Session configuration.
|
|
54
69
|
*/
|
|
55
|
-
constructor(options) {
|
|
70
|
+
constructor(options = {}) {
|
|
56
71
|
ow(options, ow.object.exactShape({
|
|
57
|
-
sessionPool: ow.object.instanceOf(EventEmitter),
|
|
58
72
|
id: ow.optional.string,
|
|
59
73
|
cookieJar: ow.optional.object,
|
|
74
|
+
proxyInfo: ow.optional.object,
|
|
60
75
|
maxAgeSecs: ow.optional.number,
|
|
61
76
|
userData: ow.optional.object,
|
|
62
77
|
maxErrorScore: ow.optional.number,
|
|
@@ -66,14 +81,17 @@ export class Session {
|
|
|
66
81
|
usageCount: ow.optional.number,
|
|
67
82
|
errorScore: ow.optional.number,
|
|
68
83
|
maxUsageCount: ow.optional.number,
|
|
84
|
+
retired: ow.optional.boolean,
|
|
69
85
|
log: ow.optional.object,
|
|
86
|
+
fingerprint: ow.optional.object,
|
|
70
87
|
}));
|
|
71
|
-
const {
|
|
88
|
+
const { id = `session_${cryptoRandomObjectId(10)}`, cookieJar = new CookieJar(), proxyInfo = undefined, maxAgeSecs = 3000, userData = {}, maxErrorScore = 3, errorScoreDecrement = 0.5, createdAt = new Date(), usageCount = 0, errorScore = 0, maxUsageCount = 50, retired = false, log = serviceLocator.getLogger(), fingerprint, } = options;
|
|
72
89
|
const { expiresAt = getDefaultCookieExpirationDate(maxAgeSecs) } = options;
|
|
73
90
|
this.log = log.child({ prefix: 'Session' });
|
|
74
91
|
this._cookieJar = cookieJar.setCookie ? cookieJar : CookieJar.fromJSON(JSON.stringify(cookieJar));
|
|
92
|
+
this._proxyInfo = proxyInfo;
|
|
93
|
+
this._fingerprint = fingerprint;
|
|
75
94
|
this.id = id;
|
|
76
|
-
this.maxAgeSecs = maxAgeSecs;
|
|
77
95
|
this.userData = userData;
|
|
78
96
|
this._maxErrorScore = maxErrorScore;
|
|
79
97
|
this._errorScoreDecrement = errorScoreDecrement;
|
|
@@ -83,7 +101,7 @@ export class Session {
|
|
|
83
101
|
this._usageCount = usageCount; // indicates how many times the session has been used
|
|
84
102
|
this._errorScore = errorScore; // indicates number of markBaded request with the session
|
|
85
103
|
this._maxUsageCount = maxUsageCount;
|
|
86
|
-
this.
|
|
104
|
+
this._retired = retired;
|
|
87
105
|
}
|
|
88
106
|
/**
|
|
89
107
|
* Indicates whether the session is blocked.
|
|
@@ -109,10 +127,10 @@ export class Session {
|
|
|
109
127
|
}
|
|
110
128
|
/**
|
|
111
129
|
* Indicates whether the session can be used for next requests.
|
|
112
|
-
* Session is usable when it is not expired, not blocked and the maximum usage count has not be reached.
|
|
130
|
+
* Session is usable when it is not retired, not expired, not blocked and the maximum usage count has not be reached.
|
|
113
131
|
*/
|
|
114
132
|
isUsable() {
|
|
115
|
-
return !this.isBlocked() && !this.isExpired() && !this.isMaxUsageCountReached();
|
|
133
|
+
return !this._retired && !this.isBlocked() && !this.isExpired() && !this.isMaxUsageCountReached();
|
|
116
134
|
}
|
|
117
135
|
/**
|
|
118
136
|
* This method should be called after a successful session usage.
|
|
@@ -123,7 +141,7 @@ export class Session {
|
|
|
123
141
|
if (this._errorScore > 0) {
|
|
124
142
|
this._errorScore -= this._errorScoreDecrement;
|
|
125
143
|
}
|
|
126
|
-
this.
|
|
144
|
+
this.maybeSelfRetire();
|
|
127
145
|
}
|
|
128
146
|
/**
|
|
129
147
|
* Gets session state for persistence in KeyValueStore.
|
|
@@ -133,7 +151,9 @@ export class Session {
|
|
|
133
151
|
return {
|
|
134
152
|
id: this.id,
|
|
135
153
|
cookieJar: this.cookieJar.toJSON(),
|
|
154
|
+
proxyInfo: this._proxyInfo,
|
|
136
155
|
userData: this.userData,
|
|
156
|
+
fingerprint: this._fingerprint,
|
|
137
157
|
maxErrorScore: this.maxErrorScore,
|
|
138
158
|
errorScoreDecrement: this.errorScoreDecrement,
|
|
139
159
|
expiresAt: this.expiresAt.toISOString(),
|
|
@@ -141,21 +161,22 @@ export class Session {
|
|
|
141
161
|
usageCount: this.usageCount,
|
|
142
162
|
maxUsageCount: this.maxUsageCount,
|
|
143
163
|
errorScore: this.errorScore,
|
|
164
|
+
retired: this._retired,
|
|
144
165
|
};
|
|
145
166
|
}
|
|
146
167
|
/**
|
|
147
|
-
*
|
|
148
|
-
*
|
|
149
|
-
*
|
|
150
|
-
*
|
|
151
|
-
*
|
|
168
|
+
* Permanently retires the session — `isUsable()` will return `false` from here on,
|
|
169
|
+
* and no `markGood()` / `markBad()` can revive it. Calling `retire()` again is a no-op.
|
|
170
|
+
*
|
|
171
|
+
* Use this when you're confident the session itself is the problem (e.g. a `403` response).
|
|
172
|
+
* For transient external failures (such as `5XX` responses), use `markBad()` instead.
|
|
152
173
|
*/
|
|
153
174
|
retire() {
|
|
154
|
-
|
|
175
|
+
if (this._retired)
|
|
176
|
+
return;
|
|
155
177
|
this._errorScore += this._maxErrorScore;
|
|
156
178
|
this._usageCount += 1;
|
|
157
|
-
|
|
158
|
-
this.sessionPool.emit(EVENT_SESSION_RETIRED, this);
|
|
179
|
+
this._retired = true;
|
|
159
180
|
}
|
|
160
181
|
/**
|
|
161
182
|
* Increases usage and error count.
|
|
@@ -164,66 +185,7 @@ export class Session {
|
|
|
164
185
|
markBad() {
|
|
165
186
|
this._errorScore += 1;
|
|
166
187
|
this._usageCount += 1;
|
|
167
|
-
this.
|
|
168
|
-
}
|
|
169
|
-
/**
|
|
170
|
-
* With certain status codes: `401`, `403` or `429` we can be certain
|
|
171
|
-
* that the target website is blocking us. This function helps to do this conveniently
|
|
172
|
-
* by retiring the session when such code is received. Optionally, the default status
|
|
173
|
-
* codes can be extended in the second parameter.
|
|
174
|
-
* @param statusCode HTTP status code.
|
|
175
|
-
* @returns Whether the session was retired.
|
|
176
|
-
*/
|
|
177
|
-
retireOnBlockedStatusCodes(statusCode) {
|
|
178
|
-
// eslint-disable-next-line dot-notation -- accessing private property
|
|
179
|
-
const isBlocked = this.sessionPool['blockedStatusCodes'].includes(statusCode);
|
|
180
|
-
if (isBlocked) {
|
|
181
|
-
this.retire();
|
|
182
|
-
}
|
|
183
|
-
return isBlocked;
|
|
184
|
-
}
|
|
185
|
-
/**
|
|
186
|
-
* Saves cookies from an HTTP response to be used with the session.
|
|
187
|
-
* It expects an object with a `headers` property that's either an `Object`
|
|
188
|
-
* (typical Node.js responses) or a `Function` (Puppeteer Response).
|
|
189
|
-
*
|
|
190
|
-
* It then parses and saves the cookies from the `set-cookie` header, if available.
|
|
191
|
-
*/
|
|
192
|
-
setCookiesFromResponse(response) {
|
|
193
|
-
try {
|
|
194
|
-
const cookies = getCookiesFromResponse(response).filter((c) => c);
|
|
195
|
-
this._setCookies(cookies, typeof response.url === 'function' ? response.url() : response.url);
|
|
196
|
-
}
|
|
197
|
-
catch (e) {
|
|
198
|
-
const err = e;
|
|
199
|
-
// if invalid Cookie header is provided just log the exception.
|
|
200
|
-
this.log.exception(err, 'Could not get cookies from response');
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
/**
|
|
204
|
-
* Saves an array with cookie objects to be used with the session.
|
|
205
|
-
* The objects should be in the format that
|
|
206
|
-
* [Puppeteer uses](https://pptr.dev/#?product=Puppeteer&version=v2.0.0&show=api-pagecookiesurls),
|
|
207
|
-
* but you can also use this function to set cookies manually:
|
|
208
|
-
*
|
|
209
|
-
* ```
|
|
210
|
-
* [
|
|
211
|
-
* { name: 'cookie1', value: 'my-cookie' },
|
|
212
|
-
* { name: 'cookie2', value: 'your-cookie' }
|
|
213
|
-
* ]
|
|
214
|
-
* ```
|
|
215
|
-
*/
|
|
216
|
-
setCookies(cookies, url) {
|
|
217
|
-
const normalizedCookies = cookies.map((c) => browserPoolCookieToToughCookie(c, this.maxAgeSecs));
|
|
218
|
-
this._setCookies(normalizedCookies, url);
|
|
219
|
-
}
|
|
220
|
-
/**
|
|
221
|
-
* Returns cookies in a format compatible with puppeteer/playwright and ready to be used with `page.setCookie`.
|
|
222
|
-
* @param url website url. Only cookies stored for this url will be returned
|
|
223
|
-
*/
|
|
224
|
-
getCookies(url) {
|
|
225
|
-
const cookies = this.cookieJar.getCookiesSync(url);
|
|
226
|
-
return cookies.map((c) => toughCookieToBrowserPoolCookie(c));
|
|
188
|
+
this.maybeSelfRetire();
|
|
227
189
|
}
|
|
228
190
|
/**
|
|
229
191
|
* Returns cookies saved with the session in the typical
|
|
@@ -238,34 +200,19 @@ export class Session {
|
|
|
238
200
|
* Sets a cookie within this session for the specific URL.
|
|
239
201
|
*/
|
|
240
202
|
setCookie(rawCookie, url) {
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
/**
|
|
244
|
-
* Sets cookies.
|
|
245
|
-
*/
|
|
246
|
-
_setCookies(cookies, url) {
|
|
247
|
-
const errorMessages = [];
|
|
248
|
-
for (const cookie of cookies) {
|
|
249
|
-
try {
|
|
250
|
-
this.cookieJar.setCookieSync(cookie, url, { ignoreError: false });
|
|
251
|
-
}
|
|
252
|
-
catch (e) {
|
|
253
|
-
const err = e;
|
|
254
|
-
errorMessages.push(err.message);
|
|
255
|
-
}
|
|
203
|
+
try {
|
|
204
|
+
this.cookieJar.setCookieSync(rawCookie, url);
|
|
256
205
|
}
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
this.log.debug('Could not set cookies.', { errorMessages });
|
|
206
|
+
catch (e) {
|
|
207
|
+
this.log.warning('Could not set cookie.', { url, error: e.message });
|
|
260
208
|
}
|
|
261
209
|
}
|
|
262
210
|
/**
|
|
263
211
|
* Checks if session is not usable. if it is not retires the session.
|
|
264
212
|
*/
|
|
265
|
-
|
|
213
|
+
maybeSelfRetire() {
|
|
266
214
|
if (!this.isUsable()) {
|
|
267
215
|
this.retire();
|
|
268
216
|
}
|
|
269
217
|
}
|
|
270
218
|
}
|
|
271
|
-
//# sourceMappingURL=session.js.map
|
|
@@ -1,24 +1,28 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import type { Log } from '@apify/log';
|
|
3
|
-
import { Configuration } from '../configuration.js';
|
|
1
|
+
import type { ISessionPool } from '@crawlee/types';
|
|
4
2
|
import type { PersistenceOptions } from '../crawlers/statistics.js';
|
|
5
|
-
import type {
|
|
6
|
-
import { KeyValueStore } from '../storages/key_value_store.js';
|
|
3
|
+
import type { CrawleeLogger } from '../log.js';
|
|
7
4
|
import type { SessionOptions } from './session.js';
|
|
8
5
|
import { Session } from './session.js';
|
|
6
|
+
declare const SESSION_REUSE_STRATEGIES: readonly ["random", "round-robin", "use-until-failure"];
|
|
7
|
+
export type SessionReuseStrategy = (typeof SESSION_REUSE_STRATEGIES)[number];
|
|
9
8
|
/**
|
|
10
9
|
* Factory user-function which creates customized {@link Session} instances.
|
|
11
10
|
*/
|
|
12
11
|
export interface CreateSession {
|
|
13
12
|
/**
|
|
14
|
-
* @param
|
|
15
|
-
* @param options
|
|
13
|
+
* @param options.sessionOptions Per-call session options already merged with the pool-wide defaults.
|
|
16
14
|
*/
|
|
17
|
-
(
|
|
15
|
+
(options?: {
|
|
18
16
|
sessionOptions?: SessionOptions;
|
|
19
17
|
}): Session | Promise<Session>;
|
|
20
18
|
}
|
|
21
19
|
export interface SessionPoolOptions {
|
|
20
|
+
/**
|
|
21
|
+
* Unique identifier for this session pool instance. Used to generate a unique
|
|
22
|
+
* persistence key when `persistStateKey` is not provided.
|
|
23
|
+
* If not provided, an auto-incrementing ID is used.
|
|
24
|
+
*/
|
|
25
|
+
id?: string | number;
|
|
22
26
|
/**
|
|
23
27
|
* Maximum size of the pool. Indicates how many sessions are rotated.
|
|
24
28
|
* @default 1000
|
|
@@ -29,24 +33,26 @@ export interface SessionPoolOptions {
|
|
|
29
33
|
/** Name or Id of `KeyValueStore` where is the `SessionPool` state stored. */
|
|
30
34
|
persistStateKeyValueStoreId?: string;
|
|
31
35
|
/**
|
|
32
|
-
* Session pool persists
|
|
33
|
-
* @default
|
|
36
|
+
* Session pool persists its state under this key in Key value store.
|
|
37
|
+
* @default CRAWLEE_SESSION_POOL_STATE_{id}
|
|
34
38
|
*/
|
|
35
39
|
persistStateKey?: string;
|
|
36
40
|
/**
|
|
37
|
-
* Custom function that should return `Session` instance.
|
|
38
|
-
* Any error thrown from this function will terminate the process.
|
|
39
|
-
*
|
|
41
|
+
* Custom function that should return a `Session` instance, or a promise resolving to such instance.
|
|
42
|
+
* Any error thrown from this function will terminate the process. Receives `{ sessionOptions }`
|
|
43
|
+
* already merged from the pool-wide defaults and the per-call overrides.
|
|
40
44
|
*/
|
|
41
45
|
createSessionFunction?: CreateSession;
|
|
42
46
|
/**
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
*
|
|
47
|
+
* Strategy for picking sessions from the pool.
|
|
48
|
+
* - `'random'` (default): fills the pool up to `maxPoolSize`, then picks a random usable session
|
|
49
|
+
* - `'round-robin'`: fills the pool up to `maxPoolSize`, then reuses sessions cycling through them in order
|
|
50
|
+
* - `'use-until-failure'`: always reuses the same session until it is retired, then moves to the next one
|
|
51
|
+
* @default 'random'
|
|
46
52
|
*/
|
|
47
|
-
|
|
53
|
+
sessionReuseStrategy?: SessionReuseStrategy;
|
|
48
54
|
/** @internal */
|
|
49
|
-
log?:
|
|
55
|
+
log?: CrawleeLogger;
|
|
50
56
|
/**
|
|
51
57
|
* Control how and when to persist the state of the session pool.
|
|
52
58
|
*/
|
|
@@ -58,20 +64,8 @@ export interface SessionPoolOptions {
|
|
|
58
64
|
* When some session is marked as blocked, it is removed and new one is created instead (the pool never returns an unusable session).
|
|
59
65
|
* Learn more in the {@doclink guides/session-management | Session management guide}.
|
|
60
66
|
*
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
* Session pool is already integrated into crawlers, and it can significantly improve your scraper
|
|
64
|
-
* performance with just 2 lines of code.
|
|
65
|
-
*
|
|
66
|
-
* **Example usage:**
|
|
67
|
-
*
|
|
68
|
-
* ```javascript
|
|
69
|
-
* const crawler = new CheerioCrawler({
|
|
70
|
-
* useSessionPool: true,
|
|
71
|
-
* persistCookiesPerSession: true,
|
|
72
|
-
* // ...
|
|
73
|
-
* })
|
|
74
|
-
* ```
|
|
67
|
+
* Session pool is already integrated into crawlers and is always active.
|
|
68
|
+
* All public methods are lazy-initialized — the pool initializes itself on first use.
|
|
75
69
|
*
|
|
76
70
|
* You can configure the pool with many options. See the {@link SessionPoolOptions}.
|
|
77
71
|
* Session pool is by default persisted in default {@link KeyValueStore}.
|
|
@@ -81,7 +75,7 @@ export interface SessionPoolOptions {
|
|
|
81
75
|
* **Advanced usage:**
|
|
82
76
|
*
|
|
83
77
|
* ```javascript
|
|
84
|
-
* const sessionPool =
|
|
78
|
+
* const sessionPool = new SessionPool({
|
|
85
79
|
* maxPoolSize: 25,
|
|
86
80
|
* sessionOptions:{
|
|
87
81
|
* maxAgeSecs: 10,
|
|
@@ -117,40 +111,40 @@ export interface SessionPoolOptions {
|
|
|
117
111
|
*
|
|
118
112
|
* @category Scaling
|
|
119
113
|
*/
|
|
120
|
-
export declare class SessionPool
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
114
|
+
export declare class SessionPool implements ISessionPool {
|
|
115
|
+
private static nextId;
|
|
116
|
+
readonly id: string;
|
|
117
|
+
private log;
|
|
118
|
+
private maxPoolSize;
|
|
119
|
+
private createSessionFunction;
|
|
120
|
+
private keyValueStore?;
|
|
121
|
+
private sessions;
|
|
122
|
+
private sessionMap;
|
|
123
|
+
private sessionOptions;
|
|
124
|
+
private persistStateKeyValueStoreId?;
|
|
125
|
+
private persistStateKey;
|
|
126
|
+
private listener?;
|
|
127
|
+
private events;
|
|
128
|
+
private persistenceOptions;
|
|
129
|
+
private sessionReuseStrategy;
|
|
130
|
+
private initPromise?;
|
|
136
131
|
private queue;
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
*/
|
|
140
|
-
constructor(options?: SessionPoolOptions, config?: Configuration);
|
|
132
|
+
private roundRobinIndex;
|
|
133
|
+
constructor(options?: SessionPoolOptions);
|
|
141
134
|
/**
|
|
142
135
|
* Gets count of usable sessions in the pool.
|
|
143
136
|
*/
|
|
144
|
-
|
|
137
|
+
usableSessionsCount(): Promise<number>;
|
|
145
138
|
/**
|
|
146
139
|
* Gets count of retired sessions in the pool.
|
|
147
140
|
*/
|
|
148
|
-
|
|
141
|
+
retiredSessionsCount(): Promise<number>;
|
|
149
142
|
/**
|
|
150
143
|
* Starts periodic state persistence and potentially loads SessionPool state from {@link KeyValueStore}.
|
|
151
|
-
*
|
|
144
|
+
* Called automatically on first use of any public method.
|
|
152
145
|
*/
|
|
153
|
-
|
|
146
|
+
private ensureInitialized;
|
|
147
|
+
private setupPool;
|
|
154
148
|
/**
|
|
155
149
|
* Adds a new session to the session pool. The pool automatically creates sessions up to the maximum size of the pool,
|
|
156
150
|
* but this allows you to add more sessions once the max pool size is reached.
|
|
@@ -158,17 +152,21 @@ export declare class SessionPool extends EventEmitter {
|
|
|
158
152
|
* @param [options] The configuration options for the session being added to the session pool.
|
|
159
153
|
*/
|
|
160
154
|
addSession(options?: Session | SessionOptions): Promise<void>;
|
|
155
|
+
/**
|
|
156
|
+
* Adds a new session to the session pool. The pool automatically creates sessions up to the maximum size of the pool,
|
|
157
|
+
* but this allows you to add more sessions once the max pool size is reached.
|
|
158
|
+
* This also allows you to add session with overridden session options (e.g. with specific session id).
|
|
159
|
+
* @param [options] The configuration options for the session being added to the session pool.
|
|
160
|
+
*/
|
|
161
|
+
newSession(sessionOptions?: SessionOptions): Promise<Session>;
|
|
161
162
|
/**
|
|
162
163
|
* Gets session.
|
|
163
164
|
* If there is space for new session, it creates and returns new session.
|
|
164
165
|
* If the session pool is full, it picks a session from the pool,
|
|
165
166
|
* If the picked session is usable it is returned, otherwise it creates and returns a new one.
|
|
167
|
+
* @param [sessionId] If provided, it returns the usable session with this id, `undefined` otherwise.
|
|
166
168
|
*/
|
|
167
|
-
getSession(): Promise<Session>;
|
|
168
|
-
/**
|
|
169
|
-
* Gets session based on the provided session id or `undefined.
|
|
170
|
-
*/
|
|
171
|
-
getSession(sessionId: string): Promise<Session>;
|
|
169
|
+
getSession(sessionId?: string): Promise<Session | undefined>;
|
|
172
170
|
/**
|
|
173
171
|
* @param options - Override the persistence options provided in the constructor
|
|
174
172
|
*/
|
|
@@ -177,12 +175,12 @@ export declare class SessionPool extends EventEmitter {
|
|
|
177
175
|
* Returns an object representing the internal state of the `SessionPool` instance.
|
|
178
176
|
* Note that the object's fields can change in future releases.
|
|
179
177
|
*/
|
|
180
|
-
getState(): {
|
|
178
|
+
getState(): Promise<{
|
|
181
179
|
usableSessionsCount: number;
|
|
182
180
|
retiredSessionsCount: number;
|
|
183
181
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
184
|
-
sessions: import("
|
|
185
|
-
}
|
|
182
|
+
sessions: import("@crawlee/types").SessionState[];
|
|
183
|
+
}>;
|
|
186
184
|
/**
|
|
187
185
|
* Persists the current state of the `SessionPool` into the default {@link KeyValueStore}.
|
|
188
186
|
* The state is persisted automatically in regular intervals.
|
|
@@ -194,58 +192,55 @@ export declare class SessionPool extends EventEmitter {
|
|
|
194
192
|
* This function should be called after you are done with using the `SessionPool` instance.
|
|
195
193
|
*/
|
|
196
194
|
teardown(): Promise<void>;
|
|
197
|
-
/**
|
|
198
|
-
* SessionPool should not work before initialization.
|
|
199
|
-
*/
|
|
200
|
-
protected _throwIfNotInitialized(): void;
|
|
201
195
|
/**
|
|
202
196
|
* Removes retired `Session` instances from `SessionPool`.
|
|
203
197
|
*/
|
|
204
|
-
|
|
198
|
+
private removeRetiredSessions;
|
|
205
199
|
/**
|
|
206
200
|
* Adds `Session` instance to `SessionPool`.
|
|
207
201
|
* @param newSession `Session` instance to be added.
|
|
208
202
|
*/
|
|
209
|
-
|
|
203
|
+
private registerSession;
|
|
210
204
|
/**
|
|
211
205
|
* Gets random index.
|
|
212
206
|
*/
|
|
213
|
-
|
|
207
|
+
private getRandomIndex;
|
|
214
208
|
/**
|
|
215
209
|
* Creates new session without any extra behavior.
|
|
216
|
-
* @param sessionPool
|
|
217
210
|
* @param [options]
|
|
218
211
|
* @param [options.sessionOptions] The configuration options for the session being created.
|
|
219
212
|
* @returns New session.
|
|
220
213
|
*/
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
214
|
+
private defaultCreateSessionFunction;
|
|
215
|
+
/**
|
|
216
|
+
* Invokes `createSessionFunction` with `sessionOptions` already merged from pool-wide defaults and
|
|
217
|
+
* the supplied per-call overrides, so custom implementations don't need to spread `pool.sessionOptions` themselves.
|
|
218
|
+
*
|
|
219
|
+
* A default {@link SessionFingerprint} is generated up front (host OS as
|
|
220
|
+
* `platform`, a random valid `browser`/`device` for that platform). Pool-wide
|
|
221
|
+
* and per-call options override it, and a persisted fingerprint coming
|
|
222
|
+
* through `maybeLoadSessionPool` naturally wins because it arrives in
|
|
223
|
+
* `perCallOptions`.
|
|
224
|
+
*/
|
|
225
|
+
private _invokeCreateSessionFunction;
|
|
224
226
|
/**
|
|
225
227
|
* Creates new session and adds it to the pool.
|
|
226
228
|
* @returns Newly created `Session` instance.
|
|
227
229
|
*/
|
|
228
|
-
|
|
230
|
+
private createSession;
|
|
229
231
|
/**
|
|
230
232
|
* Decides whether there is enough space for creating new session.
|
|
231
233
|
*/
|
|
232
|
-
|
|
234
|
+
private hasSpaceForSession;
|
|
233
235
|
/**
|
|
234
|
-
* Picks
|
|
235
|
-
*
|
|
236
|
+
* Picks a session from the `SessionPool` according to the configured `sessionReuseStrategy`.
|
|
237
|
+
* Returns `undefined` when no session should be reused and a new one should be created instead.
|
|
236
238
|
*/
|
|
237
|
-
|
|
239
|
+
private pickSession;
|
|
238
240
|
/**
|
|
239
241
|
* Potentially loads `SessionPool`.
|
|
240
242
|
* If the state was persisted it loads the `SessionPool` from the persisted state.
|
|
241
243
|
*/
|
|
242
|
-
|
|
243
|
-
/**
|
|
244
|
-
* Opens a SessionPool and returns a promise resolving to an instance
|
|
245
|
-
* of the {@link SessionPool} class that is already initialized.
|
|
246
|
-
*
|
|
247
|
-
* For more details and code examples, see the {@link SessionPool} class.
|
|
248
|
-
*/
|
|
249
|
-
static open(options?: SessionPoolOptions, config?: Configuration): Promise<SessionPool>;
|
|
244
|
+
private maybeLoadSessionPool;
|
|
250
245
|
}
|
|
251
|
-
|
|
246
|
+
export {};
|