@crawlee/core 4.0.0-beta.11 → 4.0.0-beta.111

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.
Files changed (271) hide show
  1. package/README.md +17 -13
  2. package/autoscaling/autoscaled_pool.d.ts +67 -172
  3. package/autoscaling/autoscaled_pool.js +165 -320
  4. package/autoscaling/client_load_signal.d.ts +55 -0
  5. package/autoscaling/client_load_signal.js +73 -0
  6. package/autoscaling/concurrency_system.d.ts +268 -0
  7. package/autoscaling/concurrency_system.js +351 -0
  8. package/autoscaling/cpu_load_signal.d.ts +43 -0
  9. package/autoscaling/cpu_load_signal.js +46 -0
  10. package/autoscaling/event_loop_load_signal.d.ts +51 -0
  11. package/autoscaling/event_loop_load_signal.js +60 -0
  12. package/autoscaling/index.d.ts +6 -1
  13. package/autoscaling/index.js +6 -1
  14. package/autoscaling/load_signal.d.ts +99 -0
  15. package/autoscaling/load_signal.js +104 -0
  16. package/autoscaling/memory_load_signal.d.ts +47 -0
  17. package/autoscaling/memory_load_signal.js +105 -0
  18. package/autoscaling/snapshotter.d.ts +58 -163
  19. package/autoscaling/snapshotter.js +45 -263
  20. package/autoscaling/system_status.d.ts +62 -84
  21. package/autoscaling/system_status.js +92 -122
  22. package/autoscaling/weighted_avg.d.ts +5 -0
  23. package/autoscaling/weighted_avg.js +14 -0
  24. package/byte_utils.d.ts +17 -0
  25. package/byte_utils.js +42 -0
  26. package/configuration.d.ts +96 -223
  27. package/configuration.js +170 -222
  28. package/cookie_utils.d.ts +4 -3
  29. package/cookie_utils.js +22 -13
  30. package/crawlers/context_pipeline.d.ts +10 -1
  31. package/crawlers/context_pipeline.js +31 -8
  32. package/crawlers/crawler_commons.d.ts +90 -83
  33. package/crawlers/crawler_commons.js +1 -116
  34. package/crawlers/error_snapshotter.d.ts +1 -4
  35. package/crawlers/error_snapshotter.js +3 -6
  36. package/crawlers/error_tracker.d.ts +0 -1
  37. package/crawlers/error_tracker.js +0 -1
  38. package/crawlers/index.d.ts +1 -3
  39. package/crawlers/index.js +0 -3
  40. package/crawlers/internals/types.d.ts +0 -1
  41. package/crawlers/internals/types.js +0 -1
  42. package/crawlers/statistics.d.ts +91 -41
  43. package/crawlers/statistics.js +83 -72
  44. package/debug.d.ts +36 -0
  45. package/debug.js +70 -0
  46. package/enqueue_links/enqueue_links.d.ts +59 -68
  47. package/enqueue_links/enqueue_links.js +57 -62
  48. package/enqueue_links/index.d.ts +0 -1
  49. package/enqueue_links/index.js +0 -1
  50. package/enqueue_links/shared.d.ts +40 -27
  51. package/enqueue_links/shared.js +90 -68
  52. package/errors.d.ts +41 -4
  53. package/errors.js +50 -5
  54. package/events/event_manager.d.ts +34 -8
  55. package/events/event_manager.js +8 -10
  56. package/events/index.d.ts +0 -1
  57. package/events/index.js +0 -1
  58. package/events/local_event_manager.d.ts +15 -3
  59. package/events/local_event_manager.js +37 -11
  60. package/index.d.ts +6 -4
  61. package/index.js +5 -3
  62. package/iterables.d.ts +79 -0
  63. package/iterables.js +134 -0
  64. package/log.d.ts +82 -3
  65. package/log.js +106 -1
  66. package/memory-storage/consts.d.ts +4 -0
  67. package/memory-storage/consts.js +4 -0
  68. package/memory-storage/index.d.ts +1 -0
  69. package/memory-storage/index.js +1 -0
  70. package/memory-storage/memory-storage.d.ts +42 -0
  71. package/memory-storage/memory-storage.js +136 -0
  72. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  73. package/memory-storage/resource-clients/common/base-client.js +6 -0
  74. package/memory-storage/resource-clients/dataset.d.ts +40 -0
  75. package/memory-storage/resource-clients/dataset.js +114 -0
  76. package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
  77. package/memory-storage/resource-clients/key-value-store.js +204 -0
  78. package/memory-storage/resource-clients/request-queue.d.ts +77 -0
  79. package/memory-storage/resource-clients/request-queue.js +422 -0
  80. package/memory-storage/utils.d.ts +16 -0
  81. package/memory-storage/utils.js +41 -0
  82. package/owned_or_injected.d.ts +58 -0
  83. package/owned_or_injected.js +98 -0
  84. package/package.json +13 -12
  85. package/proxy_configuration.d.ts +27 -152
  86. package/proxy_configuration.js +27 -179
  87. package/recoverable_state.d.ts +111 -0
  88. package/recoverable_state.js +143 -0
  89. package/request.d.ts +86 -17
  90. package/request.js +117 -41
  91. package/router.d.ts +193 -21
  92. package/router.js +188 -43
  93. package/serialization.d.ts +0 -1
  94. package/serialization.js +9 -11
  95. package/service_locator.d.ts +147 -0
  96. package/service_locator.js +244 -0
  97. package/session_pool/consts.d.ts +1 -2
  98. package/session_pool/consts.js +1 -2
  99. package/session_pool/errors.d.ts +0 -1
  100. package/session_pool/errors.js +0 -1
  101. package/session_pool/fingerprint.d.ts +9 -0
  102. package/session_pool/fingerprint.js +30 -0
  103. package/session_pool/index.d.ts +0 -2
  104. package/session_pool/index.js +0 -2
  105. package/session_pool/session.d.ts +37 -86
  106. package/session_pool/session.js +85 -138
  107. package/session_pool/session_pool.d.ts +77 -91
  108. package/session_pool/session_pool.js +159 -147
  109. package/storages/dataset.d.ts +114 -54
  110. package/storages/dataset.js +285 -144
  111. package/storages/index.d.ts +9 -8
  112. package/storages/index.js +7 -8
  113. package/storages/key_value_store.d.ts +185 -42
  114. package/storages/key_value_store.js +424 -151
  115. package/storages/key_value_store_codec.d.ts +32 -0
  116. package/storages/key_value_store_codec.js +113 -0
  117. package/storages/request_dedup_cache.d.ts +22 -0
  118. package/storages/request_dedup_cache.js +48 -0
  119. package/storages/request_list.d.ts +52 -116
  120. package/storages/request_list.js +158 -133
  121. package/storages/request_loader.d.ts +96 -0
  122. package/storages/request_loader.js +1 -0
  123. package/storages/request_manager.d.ts +33 -0
  124. package/storages/request_manager.js +1 -0
  125. package/storages/request_manager_tandem.d.ts +97 -0
  126. package/storages/request_manager_tandem.js +197 -0
  127. package/storages/request_queue.d.ts +290 -47
  128. package/storages/request_queue.js +825 -216
  129. package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +37 -88
  130. package/storages/{sitemap_request_list.js → sitemap_request_loader.js} +136 -143
  131. package/storages/storage_instance_manager.d.ts +87 -0
  132. package/storages/storage_instance_manager.js +256 -0
  133. package/storages/storage_stats.d.ts +48 -0
  134. package/storages/storage_stats.js +29 -0
  135. package/storages/transaction.d.ts +252 -0
  136. package/storages/transaction.js +251 -0
  137. package/storages/utils.d.ts +54 -9
  138. package/storages/utils.js +64 -13
  139. package/system-info/cpu-info.d.ts +67 -0
  140. package/system-info/cpu-info.js +216 -0
  141. package/system-info/memory-info.d.ts +31 -0
  142. package/system-info/memory-info.js +115 -0
  143. package/system-info/ps-tree.d.ts +17 -0
  144. package/system-info/ps-tree.js +144 -0
  145. package/system-info/runtime.d.ts +14 -0
  146. package/system-info/runtime.js +80 -0
  147. package/typedefs.d.ts +0 -6
  148. package/typedefs.js +0 -1
  149. package/validators.d.ts +8 -1
  150. package/validators.js +10 -3
  151. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  152. package/autoscaling/autoscaled_pool.js.map +0 -1
  153. package/autoscaling/index.d.ts.map +0 -1
  154. package/autoscaling/index.js.map +0 -1
  155. package/autoscaling/snapshotter.d.ts.map +0 -1
  156. package/autoscaling/snapshotter.js.map +0 -1
  157. package/autoscaling/system_status.d.ts.map +0 -1
  158. package/autoscaling/system_status.js.map +0 -1
  159. package/configuration.d.ts.map +0 -1
  160. package/configuration.js.map +0 -1
  161. package/cookie_utils.d.ts.map +0 -1
  162. package/cookie_utils.js.map +0 -1
  163. package/crawlers/context_pipeline.d.ts.map +0 -1
  164. package/crawlers/context_pipeline.js.map +0 -1
  165. package/crawlers/crawler_commons.d.ts.map +0 -1
  166. package/crawlers/crawler_commons.js.map +0 -1
  167. package/crawlers/crawler_utils.d.ts +0 -10
  168. package/crawlers/crawler_utils.d.ts.map +0 -1
  169. package/crawlers/crawler_utils.js +0 -12
  170. package/crawlers/crawler_utils.js.map +0 -1
  171. package/crawlers/error_snapshotter.d.ts.map +0 -1
  172. package/crawlers/error_snapshotter.js.map +0 -1
  173. package/crawlers/error_tracker.d.ts.map +0 -1
  174. package/crawlers/error_tracker.js.map +0 -1
  175. package/crawlers/index.d.ts.map +0 -1
  176. package/crawlers/index.js.map +0 -1
  177. package/crawlers/internals/types.d.ts.map +0 -1
  178. package/crawlers/internals/types.js.map +0 -1
  179. package/crawlers/statistics.d.ts.map +0 -1
  180. package/crawlers/statistics.js.map +0 -1
  181. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  182. package/enqueue_links/enqueue_links.js.map +0 -1
  183. package/enqueue_links/index.d.ts.map +0 -1
  184. package/enqueue_links/index.js.map +0 -1
  185. package/enqueue_links/shared.d.ts.map +0 -1
  186. package/enqueue_links/shared.js.map +0 -1
  187. package/errors.d.ts.map +0 -1
  188. package/errors.js.map +0 -1
  189. package/events/event_manager.d.ts.map +0 -1
  190. package/events/event_manager.js.map +0 -1
  191. package/events/index.d.ts.map +0 -1
  192. package/events/index.js.map +0 -1
  193. package/events/local_event_manager.d.ts.map +0 -1
  194. package/events/local_event_manager.js.map +0 -1
  195. package/http_clients/base-http-client.d.ts +0 -134
  196. package/http_clients/base-http-client.d.ts.map +0 -1
  197. package/http_clients/base-http-client.js +0 -33
  198. package/http_clients/base-http-client.js.map +0 -1
  199. package/http_clients/form-data-like.d.ts +0 -67
  200. package/http_clients/form-data-like.d.ts.map +0 -1
  201. package/http_clients/form-data-like.js +0 -5
  202. package/http_clients/form-data-like.js.map +0 -1
  203. package/http_clients/got-scraping-http-client.d.ts +0 -15
  204. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  205. package/http_clients/got-scraping-http-client.js +0 -69
  206. package/http_clients/got-scraping-http-client.js.map +0 -1
  207. package/http_clients/index.d.ts +0 -3
  208. package/http_clients/index.d.ts.map +0 -1
  209. package/http_clients/index.js +0 -3
  210. package/http_clients/index.js.map +0 -1
  211. package/index.d.ts.map +0 -1
  212. package/index.js.map +0 -1
  213. package/log.d.ts.map +0 -1
  214. package/log.js.map +0 -1
  215. package/proxy_configuration.d.ts.map +0 -1
  216. package/proxy_configuration.js.map +0 -1
  217. package/request.d.ts.map +0 -1
  218. package/request.js.map +0 -1
  219. package/router.d.ts.map +0 -1
  220. package/router.js.map +0 -1
  221. package/serialization.d.ts.map +0 -1
  222. package/serialization.js.map +0 -1
  223. package/session_pool/consts.d.ts.map +0 -1
  224. package/session_pool/consts.js.map +0 -1
  225. package/session_pool/errors.d.ts.map +0 -1
  226. package/session_pool/errors.js.map +0 -1
  227. package/session_pool/events.d.ts +0 -3
  228. package/session_pool/events.d.ts.map +0 -1
  229. package/session_pool/events.js +0 -3
  230. package/session_pool/events.js.map +0 -1
  231. package/session_pool/index.d.ts.map +0 -1
  232. package/session_pool/index.js.map +0 -1
  233. package/session_pool/session.d.ts.map +0 -1
  234. package/session_pool/session.js.map +0 -1
  235. package/session_pool/session_pool.d.ts.map +0 -1
  236. package/session_pool/session_pool.js.map +0 -1
  237. package/storages/access_checking.d.ts +0 -13
  238. package/storages/access_checking.d.ts.map +0 -1
  239. package/storages/access_checking.js +0 -14
  240. package/storages/access_checking.js.map +0 -1
  241. package/storages/dataset.d.ts.map +0 -1
  242. package/storages/dataset.js.map +0 -1
  243. package/storages/index.d.ts.map +0 -1
  244. package/storages/index.js.map +0 -1
  245. package/storages/key_value_store.d.ts.map +0 -1
  246. package/storages/key_value_store.js.map +0 -1
  247. package/storages/request_list.d.ts.map +0 -1
  248. package/storages/request_list.js.map +0 -1
  249. package/storages/request_provider.d.ts +0 -308
  250. package/storages/request_provider.d.ts.map +0 -1
  251. package/storages/request_provider.js +0 -555
  252. package/storages/request_provider.js.map +0 -1
  253. package/storages/request_queue.d.ts.map +0 -1
  254. package/storages/request_queue.js.map +0 -1
  255. package/storages/request_queue_v2.d.ts +0 -87
  256. package/storages/request_queue_v2.d.ts.map +0 -1
  257. package/storages/request_queue_v2.js +0 -438
  258. package/storages/request_queue_v2.js.map +0 -1
  259. package/storages/sitemap_request_list.d.ts.map +0 -1
  260. package/storages/sitemap_request_list.js.map +0 -1
  261. package/storages/storage_manager.d.ts +0 -58
  262. package/storages/storage_manager.d.ts.map +0 -1
  263. package/storages/storage_manager.js +0 -105
  264. package/storages/storage_manager.js.map +0 -1
  265. package/storages/utils.d.ts.map +0 -1
  266. package/storages/utils.js.map +0 -1
  267. package/tsconfig.build.tsbuildinfo +0 -1
  268. package/typedefs.d.ts.map +0 -1
  269. package/typedefs.js.map +0 -1
  270. package/validators.d.ts.map +0 -1
  271. package/validators.js.map +0 -1
@@ -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 { browserPoolCookieToToughCookie, getCookiesFromResponse, getDefaultCookieExpirationDate, toughCookieToBrowserPoolCookie, } from '../cookie_utils.js';
6
- import { log as defaultLog } from '../log.js';
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,50 +11,67 @@ import { EVENT_SESSION_RETIRED } from './events.js';
13
11
  */
14
12
  export class Session {
15
13
  id;
16
- maxAgeSecs;
17
14
  userData;
18
- _maxErrorScore;
19
- _errorScoreDecrement;
20
- _createdAt;
21
- _expiresAt;
22
- _usageCount;
23
- _maxUsageCount;
24
- sessionPool;
25
- _errorScore;
26
- _cookieJar;
27
- log;
15
+ #maxErrorScore;
16
+ #errorScoreDecrement;
17
+ #createdAt;
18
+ #expiresAt;
19
+ #usageCount;
20
+ #maxUsageCount;
21
+ #errorScore;
22
+ #retired = false;
23
+ #proxyInfo;
24
+ #cookieJar;
25
+ #fingerprint;
26
+ #log;
28
27
  get errorScore() {
29
- return this._errorScore;
28
+ return this.#errorScore;
30
29
  }
31
30
  get usageCount() {
32
- return this._usageCount;
31
+ return this.#usageCount;
33
32
  }
34
33
  get maxErrorScore() {
35
- return this._maxErrorScore;
34
+ return this.#maxErrorScore;
36
35
  }
37
36
  get errorScoreDecrement() {
38
- return this._errorScoreDecrement;
37
+ return this.#errorScoreDecrement;
39
38
  }
40
39
  get expiresAt() {
41
- return this._expiresAt;
40
+ return this.#expiresAt;
42
41
  }
43
42
  get createdAt() {
44
- return this._createdAt;
43
+ return this.#createdAt;
45
44
  }
46
45
  get maxUsageCount() {
47
- return this._maxUsageCount;
46
+ return this.#maxUsageCount;
48
47
  }
49
48
  get cookieJar() {
50
- return this._cookieJar;
49
+ return this.#cookieJar;
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;
51
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,24 +81,27 @@ 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 { sessionPool, id = `session_${cryptoRandomObjectId(10)}`, cookieJar = new CookieJar(), maxAgeSecs = 3000, userData = {}, maxErrorScore = 3, errorScoreDecrement = 0.5, createdAt = new Date(), usageCount = 0, errorScore = 0, maxUsageCount = 50, log = defaultLog, } = options;
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
- this.log = log.child({ prefix: 'Session' });
74
- this._cookieJar = cookieJar.setCookie ? cookieJar : CookieJar.fromJSON(JSON.stringify(cookieJar));
90
+ this.#log = log.child({ prefix: 'Session' });
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
- this._maxErrorScore = maxErrorScore;
79
- this._errorScoreDecrement = errorScoreDecrement;
96
+ this.#maxErrorScore = maxErrorScore;
97
+ this.#errorScoreDecrement = errorScoreDecrement;
80
98
  // Internal
81
- this._expiresAt = expiresAt;
82
- this._createdAt = createdAt;
83
- this._usageCount = usageCount; // indicates how many times the session has been used
84
- this._errorScore = errorScore; // indicates number of markBaded request with the session
85
- this._maxUsageCount = maxUsageCount;
86
- this.sessionPool = sessionPool;
99
+ this.#expiresAt = expiresAt;
100
+ this.#createdAt = createdAt;
101
+ this.#usageCount = usageCount; // indicates how many times the session has been used
102
+ this.#errorScore = errorScore; // indicates number of markBaded request with the session
103
+ this.#maxUsageCount = maxUsageCount;
104
+ this.#retired = retired;
87
105
  }
88
106
  /**
89
107
  * Indicates whether the session is blocked.
@@ -109,21 +127,21 @@ 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.
119
137
  * It increases `usageCount` and potentially lowers the `errorScore` by the `errorScoreDecrement`.
120
138
  */
121
139
  markGood() {
122
- this._usageCount += 1;
123
- if (this._errorScore > 0) {
124
- this._errorScore -= this._errorScoreDecrement;
140
+ this.#usageCount += 1;
141
+ if (this.#errorScore > 0) {
142
+ this.#errorScore -= this.#errorScoreDecrement;
125
143
  }
126
- this._maybeSelfRetire();
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,89 +161,31 @@ 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
- * Marks session as blocked and emits event on the `SessionPool`
148
- * This method should be used if the session usage was unsuccessful
149
- * and you are sure that it is because of the session configuration and not any external matters.
150
- * For example when server returns 403 status code.
151
- * If the session does not work due to some external factors as server error such as 5XX you probably want to use `markBad` method.
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
- // mark it as an invalid by increasing the error score count.
155
- this._errorScore += this._maxErrorScore;
156
- this._usageCount += 1;
157
- // emit event so we can retire browser in puppeteer pool
158
- this.sessionPool.emit(EVENT_SESSION_RETIRED, this);
175
+ if (this.#retired)
176
+ return;
177
+ this.#errorScore += this.#maxErrorScore;
178
+ this.#usageCount += 1;
179
+ this.#retired = true;
159
180
  }
160
181
  /**
161
182
  * Increases usage and error count.
162
183
  * Should be used when the session has been used unsuccessfully. For example because of timeouts.
163
184
  */
164
185
  markBad() {
165
- this._errorScore += 1;
166
- this._usageCount += 1;
167
- this._maybeSelfRetire();
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));
186
+ this.#errorScore += 1;
187
+ this.#usageCount += 1;
188
+ this.maybeSelfRetire();
227
189
  }
228
190
  /**
229
191
  * Returns cookies saved with the session in the typical
@@ -231,41 +193,26 @@ export class Session {
231
193
  * a cookie header or elsewhere.
232
194
  * @returns Represents `Cookie` header.
233
195
  */
234
- getCookieString(url) {
235
- return this.cookieJar.getCookieStringSync(url, {});
196
+ async getCookieString(url) {
197
+ return this.cookieJar.getCookieString(url, {});
236
198
  }
237
199
  /**
238
200
  * Sets a cookie within this session for the specific URL.
239
201
  */
240
- setCookie(rawCookie, url) {
241
- this.cookieJar.setCookieSync(rawCookie, url);
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
- }
202
+ async setCookie(rawCookie, url) {
203
+ try {
204
+ await this.cookieJar.setCookie(rawCookie, url);
256
205
  }
257
- // if invalid cookies are provided just log the exception. No need to retry the request automatically.
258
- if (errorMessages.length) {
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
- _maybeSelfRetire() {
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 { EventEmitter } from 'node:events';
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 { EventManager } from '../events/event_manager.js';
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 sessionPool Pool requesting the new session.
15
- * @param options
13
+ * @param options.sessionOptions Per-call session options already merged with the pool-wide defaults.
16
14
  */
17
- (sessionPool: SessionPool, options?: {
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 it's state under this key in Key value store.
33
- * @default SESSION_POOL_STATE
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
- * Function receives `SessionPool` instance as a parameter
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
- * Specifies which response status codes are considered as blocked.
44
- * Session connected to such request will be marked as retired.
45
- * @default [401, 403, 429]
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
- blockedStatusCodes?: number[];
53
+ sessionReuseStrategy?: SessionReuseStrategy;
48
54
  /** @internal */
49
- log?: 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
- * You can create one by calling the {@link SessionPool.open} function.
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 = await SessionPool.open({
78
+ * const sessionPool = new SessionPool({
85
79
  * maxPoolSize: 25,
86
80
  * sessionOptions:{
87
81
  * maxAgeSecs: 10,
@@ -117,40 +111,31 @@ export interface SessionPoolOptions {
117
111
  *
118
112
  * @category Scaling
119
113
  */
120
- export declare class SessionPool extends EventEmitter {
121
- readonly config: Configuration;
122
- protected log: Log;
123
- protected maxPoolSize: number;
124
- protected createSessionFunction: CreateSession;
125
- protected keyValueStore: KeyValueStore;
126
- protected sessions: Session[];
127
- protected sessionMap: Map<string, Session>;
128
- protected sessionOptions: SessionOptions;
129
- protected persistStateKeyValueStoreId?: string;
130
- protected persistStateKey: string;
131
- protected _listener: () => Promise<void>;
132
- protected events: EventManager;
133
- protected readonly blockedStatusCodes: number[];
134
- protected persistenceOptions: PersistenceOptions;
135
- protected isInitialized: boolean;
136
- private queue;
137
- /**
138
- * @internal
139
- */
140
- constructor(options?: SessionPoolOptions, config?: Configuration);
114
+ export declare class SessionPool implements ISessionPool {
115
+ #private;
116
+ readonly id: string;
117
+ private maxPoolSize;
118
+ private createSessionFunction;
119
+ private keyValueStore?;
120
+ private sessionMap;
121
+ private sessionOptions;
122
+ private persistStateKeyValueStoreId?;
123
+ private persistStateKey;
124
+ constructor(options?: SessionPoolOptions);
141
125
  /**
142
126
  * Gets count of usable sessions in the pool.
143
127
  */
144
- get usableSessionsCount(): number;
128
+ usableSessionsCount(): Promise<number>;
145
129
  /**
146
130
  * Gets count of retired sessions in the pool.
147
131
  */
148
- get retiredSessionsCount(): number;
132
+ retiredSessionsCount(): Promise<number>;
149
133
  /**
150
134
  * Starts periodic state persistence and potentially loads SessionPool state from {@link KeyValueStore}.
151
- * It is called automatically by the {@link SessionPool.open} function.
135
+ * Called automatically on first use of any public method.
152
136
  */
153
- initialize(): Promise<void>;
137
+ private ensureInitialized;
138
+ private setupPool;
154
139
  /**
155
140
  * Adds a new session to the session pool. The pool automatically creates sessions up to the maximum size of the pool,
156
141
  * but this allows you to add more sessions once the max pool size is reached.
@@ -158,17 +143,21 @@ export declare class SessionPool extends EventEmitter {
158
143
  * @param [options] The configuration options for the session being added to the session pool.
159
144
  */
160
145
  addSession(options?: Session | SessionOptions): Promise<void>;
146
+ /**
147
+ * Adds a new session to the session pool. The pool automatically creates sessions up to the maximum size of the pool,
148
+ * but this allows you to add more sessions once the max pool size is reached.
149
+ * This also allows you to add session with overridden session options (e.g. with specific session id).
150
+ * @param [options] The configuration options for the session being added to the session pool.
151
+ */
152
+ newSession(sessionOptions?: SessionOptions): Promise<Session>;
161
153
  /**
162
154
  * Gets session.
163
155
  * If there is space for new session, it creates and returns new session.
164
156
  * If the session pool is full, it picks a session from the pool,
165
157
  * If the picked session is usable it is returned, otherwise it creates and returns a new one.
158
+ * @param [sessionId] If provided, it returns the usable session with this id, `undefined` otherwise.
166
159
  */
167
- getSession(): Promise<Session>;
168
- /**
169
- * Gets session based on the provided session id or `undefined.
170
- */
171
- getSession(sessionId: string): Promise<Session>;
160
+ getSession(sessionId?: string): Promise<Session | undefined>;
172
161
  /**
173
162
  * @param options - Override the persistence options provided in the constructor
174
163
  */
@@ -177,12 +166,12 @@ export declare class SessionPool extends EventEmitter {
177
166
  * Returns an object representing the internal state of the `SessionPool` instance.
178
167
  * Note that the object's fields can change in future releases.
179
168
  */
180
- getState(): {
169
+ getState(): Promise<{
181
170
  usableSessionsCount: number;
182
171
  retiredSessionsCount: number;
183
172
  // @ts-ignore optional peer dependency or compatibility with es2022
184
- sessions: import("./session.js").SessionState[];
185
- };
173
+ sessions: import("@crawlee/types").SessionState[];
174
+ }>;
186
175
  /**
187
176
  * Persists the current state of the `SessionPool` into the default {@link KeyValueStore}.
188
177
  * The state is persisted automatically in regular intervals.
@@ -194,58 +183,55 @@ export declare class SessionPool extends EventEmitter {
194
183
  * This function should be called after you are done with using the `SessionPool` instance.
195
184
  */
196
185
  teardown(): Promise<void>;
197
- /**
198
- * SessionPool should not work before initialization.
199
- */
200
- protected _throwIfNotInitialized(): void;
201
186
  /**
202
187
  * Removes retired `Session` instances from `SessionPool`.
203
188
  */
204
- protected _removeRetiredSessions(): void;
189
+ private removeRetiredSessions;
205
190
  /**
206
191
  * Adds `Session` instance to `SessionPool`.
207
192
  * @param newSession `Session` instance to be added.
208
193
  */
209
- protected _addSession(newSession: Session): void;
194
+ private registerSession;
210
195
  /**
211
196
  * Gets random index.
212
197
  */
213
- protected _getRandomIndex(): number;
198
+ private getRandomIndex;
214
199
  /**
215
200
  * Creates new session without any extra behavior.
216
- * @param sessionPool
217
201
  * @param [options]
218
202
  * @param [options.sessionOptions] The configuration options for the session being created.
219
203
  * @returns New session.
220
204
  */
221
- protected _defaultCreateSessionFunction(sessionPool: SessionPool, options?: {
222
- sessionOptions?: SessionOptions;
223
- }): Session;
205
+ private defaultCreateSessionFunction;
206
+ /**
207
+ * Invokes `createSessionFunction` with `sessionOptions` already merged from pool-wide defaults and
208
+ * the supplied per-call overrides, so custom implementations don't need to spread `pool.sessionOptions` themselves.
209
+ *
210
+ * A default {@link SessionFingerprint} is generated up front (host OS as
211
+ * `platform`, a random valid `browser`/`device` for that platform). Pool-wide
212
+ * and per-call options override it, and a persisted fingerprint coming
213
+ * through `maybeLoadSessionPool` naturally wins because it arrives in
214
+ * `perCallOptions`.
215
+ */
216
+ private invokeCreateSessionFunction;
224
217
  /**
225
218
  * Creates new session and adds it to the pool.
226
219
  * @returns Newly created `Session` instance.
227
220
  */
228
- protected _createSession(): Promise<Session>;
221
+ private createSession;
229
222
  /**
230
223
  * Decides whether there is enough space for creating new session.
231
224
  */
232
- protected _hasSpaceForSession(): boolean;
225
+ private hasSpaceForSession;
233
226
  /**
234
- * Picks random session from the `SessionPool`.
235
- * @returns Picked `Session`.
227
+ * Picks a session from the `SessionPool` according to the configured `sessionReuseStrategy`.
228
+ * Returns `undefined` when no session should be reused and a new one should be created instead.
236
229
  */
237
- protected _pickSession(): Session;
230
+ private pickSession;
238
231
  /**
239
232
  * Potentially loads `SessionPool`.
240
233
  * If the state was persisted it loads the `SessionPool` from the persisted state.
241
234
  */
242
- protected _maybeLoadSessionPool(): Promise<void>;
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>;
235
+ private maybeLoadSessionPool;
250
236
  }
251
- //# sourceMappingURL=session_pool.d.ts.map
237
+ export {};