scrapely-python 0.1.42__py3-none-any.whl → 0.1.44__py3-none-any.whl

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.
scrapely/__init__.py CHANGED
@@ -10,95 +10,114 @@ Usage:
10
10
  await Actor.push_data({'url': actor_input['url']})
11
11
  """
12
12
 
13
- from typing import TYPE_CHECKING, Any
13
+ from __future__ import annotations
14
+
15
+ # ``typing`` is not imported at run time (see below): this package loads at
16
+ # every interpreter start in actor images.
17
+ TYPE_CHECKING = False
18
+ if TYPE_CHECKING:
19
+ from typing import Any
14
20
 
15
21
  # Side-effect: patch browser launches (Crawlee BrowserPool, PlaywrightCrawler,
16
22
  # raw Playwright, Camoufox, pyppeteer) to use the remote CDP browser (CDP_URL).
17
23
  # Must run on package import so `from scrapely import Actor` enables the patch
18
- # before any browser is launched (Node SDK parity). It does not import Crawlee:
19
- # the Crawlee patches are applied when Crawlee's browser modules load.
24
+ # before any browser is launched (Node SDK parity). It imports none of those
25
+ # libraries: each patch is applied the moment its library finishes loading.
20
26
  from .patch_browser_pool import set_cdp_url # noqa: F401
21
27
 
22
- # Crawlee is NOT imported here: it costs ~1 s per run on the platform and many
23
- # actors never touch it. Everything that needs Crawlee (the re-exported Crawlee
24
- # classes, storage clients, events, request loaders) is resolved on first
25
- # attribute access by ``__getattr__`` below; ``Actor`` imports what it needs on
26
- # first use. Every ``from scrapely import X`` that worked before still works.
27
- from .actor import Actor
28
- from .configuration import Configuration
29
- from .charging_client import (
30
- USES_PUSH_DATA_INTERCEPTION,
31
- create_charging_client,
32
- push_data_charging_context,
33
- )
34
- from .proxy_configuration import ProxyConfiguration
35
- from .browser_configuration import BrowserConfiguration
36
- from .charging import (
37
- ChargingManager,
38
- ChargeUncertainError,
39
- ChargeRejectedError,
40
- has_default_dataset_item_event_in_pricing,
41
- is_default_dataset_item_event,
42
- merge_charge_results,
43
- push_data_and_charge,
44
- resolve_default_dataset_item_event_name,
45
- APIFY_DEFAULT_DATASET_ITEM_EVENT,
46
- SCRAPELY_DEFAULT_DATASET_ITEM_EVENT,
47
- DEFAULT_DATASET_ITEM_EVENT,
48
- )
49
-
50
- from .types import (
51
- ActorInput,
52
- ActorPermissionLevel,
53
- ActorRun,
54
- ApifyEnv,
55
- AbortOptions,
56
- CallOptions,
57
- ExitOptions,
58
- InitOptions,
59
- MetamorphOptions,
60
- OpenStorageOptions,
61
- ProxyInfo,
62
- RebootOptions,
63
- RecordOptions,
64
- SetStatusMessageOptions,
65
- StartOptions,
66
- WebhookOptions,
67
- )
28
+ # Nothing else is imported here. The base images' sitecustomize imports
29
+ # ``scrapely.patch_browser_pool`` (and so this package) in EVERY Python process
30
+ # of an actor image; loading the whole SDK there cost ~0.75 s per interpreter
31
+ # start at 1 CPU (5.7 s at 0.25 CPU). Every public name is resolved on first
32
+ # attribute access by ``__getattr__`` below and cached in the module namespace,
33
+ # so every ``from scrapely import X`` that worked before still works.
68
34
 
69
- from .webhook import (
70
- Webhook,
71
- WebhookEventType,
72
- )
73
- from .pricing_types import (
74
- PricingModel,
75
- FreeActorPricingInfo,
76
- FlatPricePerMonthActorPricingInfo,
77
- PricePerDatasetItemActorPricingInfo,
78
- PayPerEventActorPricingInfo,
79
- PricingPerEvent,
80
- ActorPricingInfo,
81
- ActorChargeEvent,
82
- ChargeResult,
83
- ActorPricingInfoResult,
84
- )
85
- from .errors import (
86
- ScrapelyClientError,
87
- ScrapelyApiError,
88
- InvalidResponseBodyError,
89
- InvalidRequestError,
90
- UnauthorizedError,
91
- ForbiddenError,
92
- NotFoundError,
93
- ConflictError,
94
- RateLimitError,
95
- ServerError,
96
- raise_for_status,
97
- )
98
-
99
- # Public name -> (module, attribute) for names that need Crawlee. Loaded on
100
- # first access and cached in the module namespace.
35
+ # Public name -> (module, attribute). Loaded on first access.
101
36
  _LAZY_ATTRS = {
37
+ 'Actor': ('scrapely.actor', 'Actor'),
38
+ 'Configuration': ('scrapely.configuration', 'Configuration'),
39
+ 'ProxyConfiguration': ('scrapely.proxy_configuration', 'ProxyConfiguration'),
40
+ 'BrowserConfiguration': ('scrapely.browser_configuration', 'BrowserConfiguration'),
41
+ # Charging client
42
+ **{
43
+ name: ('scrapely.charging_client', name)
44
+ for name in ('USES_PUSH_DATA_INTERCEPTION', 'create_charging_client', 'push_data_charging_context')
45
+ },
46
+ # Charging
47
+ **{
48
+ name: ('scrapely.charging', name)
49
+ for name in (
50
+ 'ChargingManager',
51
+ 'ChargeUncertainError',
52
+ 'ChargeRejectedError',
53
+ 'has_default_dataset_item_event_in_pricing',
54
+ 'is_default_dataset_item_event',
55
+ 'merge_charge_results',
56
+ 'push_data_and_charge',
57
+ 'resolve_default_dataset_item_event_name',
58
+ 'APIFY_DEFAULT_DATASET_ITEM_EVENT',
59
+ 'SCRAPELY_DEFAULT_DATASET_ITEM_EVENT',
60
+ 'DEFAULT_DATASET_ITEM_EVENT',
61
+ )
62
+ },
63
+ # Types
64
+ **{
65
+ name: ('scrapely.types', name)
66
+ for name in (
67
+ 'ActorInput',
68
+ 'ActorPermissionLevel',
69
+ 'ActorRun',
70
+ 'ApifyEnv',
71
+ 'AbortOptions',
72
+ 'CallOptions',
73
+ 'ExitOptions',
74
+ 'InitOptions',
75
+ 'MetamorphOptions',
76
+ 'OpenStorageOptions',
77
+ 'ProxyInfo',
78
+ 'RebootOptions',
79
+ 'RecordOptions',
80
+ 'SetStatusMessageOptions',
81
+ 'StartOptions',
82
+ 'WebhookOptions',
83
+ )
84
+ },
85
+ # Webhook
86
+ 'Webhook': ('scrapely.webhook', 'Webhook'),
87
+ 'WebhookEventType': ('scrapely.webhook', 'WebhookEventType'),
88
+ # Pricing
89
+ **{
90
+ name: ('scrapely.pricing_types', name)
91
+ for name in (
92
+ 'PricingModel',
93
+ 'FreeActorPricingInfo',
94
+ 'FlatPricePerMonthActorPricingInfo',
95
+ 'PricePerDatasetItemActorPricingInfo',
96
+ 'PayPerEventActorPricingInfo',
97
+ 'PricingPerEvent',
98
+ 'ActorPricingInfo',
99
+ 'ActorChargeEvent',
100
+ 'ChargeResult',
101
+ 'ActorPricingInfoResult',
102
+ )
103
+ },
104
+ # Errors
105
+ **{
106
+ name: ('scrapely.errors', name)
107
+ for name in (
108
+ 'ScrapelyClientError',
109
+ 'ScrapelyApiError',
110
+ 'InvalidResponseBodyError',
111
+ 'InvalidRequestError',
112
+ 'UnauthorizedError',
113
+ 'ForbiddenError',
114
+ 'NotFoundError',
115
+ 'ConflictError',
116
+ 'RateLimitError',
117
+ 'ServerError',
118
+ 'raise_for_status',
119
+ )
120
+ },
102
121
  # Crawlee re-exports
103
122
  'Request': ('crawlee', 'Request'),
104
123
  'RequestLoader': ('crawlee.request_loaders', 'RequestLoader'),
@@ -150,15 +169,28 @@ _LAZY_ATTRS = {
150
169
  }
151
170
 
152
171
  # Submodules that used to be loaded (and so bound as attributes) by this
153
- # package's eager imports; ``scrapely.events`` etc. keep working without an
154
- # explicit ``import scrapely.events``.
172
+ # package's eager imports; ``scrapely.actor``, ``scrapely.events`` etc. keep
173
+ # working without an explicit ``import scrapely.<name>``.
155
174
  _LAZY_SUBMODULES = frozenset({
175
+ '_browser_locations',
176
+ 'actor',
177
+ 'browser_configuration',
178
+ 'cdp_retry',
179
+ 'charging',
180
+ 'charging_client',
181
+ 'configuration',
182
+ 'crypto',
183
+ 'errors',
156
184
  'events',
157
185
  'log',
186
+ 'pricing_types',
187
+ 'proxy_configuration',
158
188
  'request_loaders',
159
189
  'storage',
160
190
  'storage_clients',
161
191
  'storages',
192
+ 'types',
193
+ 'webhook',
162
194
  })
163
195
 
164
196
 
@@ -193,6 +225,40 @@ if TYPE_CHECKING: # Static analysers and IDEs see the lazy names as plain impor
193
225
  from crawlee.storage_clients.models import DatasetItemsListPage
194
226
  from crawlee.storages import Dataset, KeyValueStore, RequestQueue
195
227
 
228
+ from .actor import Actor
229
+ from .browser_configuration import BrowserConfiguration
230
+ from .charging import (
231
+ APIFY_DEFAULT_DATASET_ITEM_EVENT,
232
+ DEFAULT_DATASET_ITEM_EVENT,
233
+ SCRAPELY_DEFAULT_DATASET_ITEM_EVENT,
234
+ ChargeRejectedError,
235
+ ChargeUncertainError,
236
+ ChargingManager,
237
+ has_default_dataset_item_event_in_pricing,
238
+ is_default_dataset_item_event,
239
+ merge_charge_results,
240
+ push_data_and_charge,
241
+ resolve_default_dataset_item_event_name,
242
+ )
243
+ from .charging_client import (
244
+ USES_PUSH_DATA_INTERCEPTION,
245
+ create_charging_client,
246
+ push_data_charging_context,
247
+ )
248
+ from .configuration import Configuration
249
+ from .errors import (
250
+ ConflictError,
251
+ ForbiddenError,
252
+ InvalidRequestError,
253
+ InvalidResponseBodyError,
254
+ NotFoundError,
255
+ RateLimitError,
256
+ ScrapelyApiError,
257
+ ScrapelyClientError,
258
+ ServerError,
259
+ UnauthorizedError,
260
+ raise_for_status,
261
+ )
196
262
  from .events import (
197
263
  AbortingEvent,
198
264
  ActorEventTypes,
@@ -216,6 +282,19 @@ if TYPE_CHECKING: # Static analysers and IDEs see the lazy names as plain impor
216
282
  SystemInfoEventData,
217
283
  UnknownEvent,
218
284
  )
285
+ from .pricing_types import (
286
+ ActorChargeEvent,
287
+ ActorPricingInfo,
288
+ ActorPricingInfoResult,
289
+ ChargeResult,
290
+ FlatPricePerMonthActorPricingInfo,
291
+ FreeActorPricingInfo,
292
+ PayPerEventActorPricingInfo,
293
+ PricePerDatasetItemActorPricingInfo,
294
+ PricingModel,
295
+ PricingPerEvent,
296
+ )
297
+ from .proxy_configuration import ProxyConfiguration
219
298
  from .request_loaders import ScrapelyRequestList
220
299
  from .storage import (
221
300
  ApiStorageClient,
@@ -226,8 +305,27 @@ if TYPE_CHECKING: # Static analysers and IDEs see the lazy names as plain impor
226
305
  StorageClient,
227
306
  set_api_storage,
228
307
  )
308
+ from .types import (
309
+ AbortOptions,
310
+ ActorInput,
311
+ ActorPermissionLevel,
312
+ ActorRun,
313
+ ApifyEnv,
314
+ CallOptions,
315
+ ExitOptions,
316
+ InitOptions,
317
+ MetamorphOptions,
318
+ OpenStorageOptions,
319
+ ProxyInfo,
320
+ RebootOptions,
321
+ RecordOptions,
322
+ SetStatusMessageOptions,
323
+ StartOptions,
324
+ WebhookOptions,
325
+ )
326
+ from .webhook import Webhook, WebhookEventType
229
327
 
230
- __version__ = '0.1.41'
328
+ __version__ = '0.1.44'
231
329
  __all__ = [
232
330
  # Core
233
331
  'Actor',
scrapely/charging.py CHANGED
@@ -17,7 +17,7 @@ import re
17
17
  import time
18
18
  import uuid
19
19
  from datetime import datetime, timezone
20
- from decimal import Decimal
20
+ from decimal import Decimal, InvalidOperation
21
21
  from threading import RLock
22
22
  from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
23
23
 
@@ -228,6 +228,85 @@ def has_default_dataset_item_event_in_pricing(per_event_prices: dict) -> bool:
228
228
  hasDefaultDatasetItemEventInPricing = has_default_dataset_item_event_in_pricing
229
229
 
230
230
 
231
+ # The SDK's line for a charge the platform accepted only in part. Outside an
232
+ # atomic push it is true (the N events stay charged). Keep the wording: actors
233
+ # read N from it (e.g. a logging.Filter on the 'scrapely.charging' logger).
234
+ _LEGACY_SHORT_CHARGE_LINE = "Charging %s %s of '%s' event would exceed %s - only %s events were charged"
235
+
236
+
237
+ class _ShortCharge:
238
+ """A charge of an atomic push that the limit accepted only in part (then given back)."""
239
+
240
+ __slots__ = ('event_name', 'requested', 'covered', 'limit', 'taken_by_filter')
241
+
242
+ def __init__(self, *, event_name: str, requested: int, covered: int, limit: str, taken_by_filter: bool) -> None:
243
+ self.event_name = event_name
244
+ self.requested = requested
245
+ self.covered = covered
246
+ self.limit = limit
247
+ self.taken_by_filter = taken_by_filter
248
+
249
+
250
+ def _offer_to_log_filters(msg: str, args: tuple) -> bool:
251
+ """Show a log record to the 'scrapely.charging' logger's filters only; never print it.
252
+
253
+ Before 0.1.44 an atomic push logged the short-charge line (``only N events were
254
+ charged``) although it then gave that charge back. Actors that read N from that
255
+ line with a filter on this logger keep getting it, unchanged, while nobody sees
256
+ the untrue text. Returns True when a filter dropped the record: that actor then
257
+ reports the refusal itself, as it did before.
258
+ """
259
+ if not logger.filters or not logger.isEnabledFor(logging.INFO):
260
+ return False
261
+ try:
262
+ record = logger.makeRecord(logger.name, logging.INFO, __file__, 0, msg, args, None, func='_charge_exclusive')
263
+ return not logger.filter(record)
264
+ except Exception: # noqa: BLE001 - an actor's filter must never break a push
265
+ return False
266
+
267
+
268
+ def _items_phrase(count: int) -> tuple[str, str, str]:
269
+ """('this item', 'it was', 'it') or ('these 3 items', 'they were', 'them')."""
270
+ if count == 1:
271
+ return 'this item', 'it was', 'it'
272
+ return f'these {count} items', 'they were', 'them'
273
+
274
+
275
+ def _log_atomic_refusal(
276
+ shorts: List[_ShortCharge], rows_pushed: int, rows_saved: int, given_back: bool
277
+ ) -> None:
278
+ """Log what an atomic push whose charge came back short really did."""
279
+ if not shorts or any(s.taken_by_filter for s in shorts):
280
+ return
281
+ first = shorts[0]
282
+ limit = re.sub(r'^the end of ', '', first.limit)
283
+ what, were, them = _items_phrase(rows_pushed)
284
+ head = (
285
+ f"Saving {what} needs {first.requested} '{first.event_name}' event(s), "
286
+ f'but {limit} covers only {first.covered}'
287
+ )
288
+ if rows_saved <= 0:
289
+ if given_back:
290
+ logger.info('%s: %s not saved and nothing was charged for %s.', head, were, them)
291
+ else:
292
+ logger.info(
293
+ '%s: %s not saved, but the %s event(s) charged for %s could not be given back yet '
294
+ '(see the warning about it).',
295
+ head, were, first.covered, them,
296
+ )
297
+ return
298
+ left = rows_pushed - rows_saved
299
+ _, left_were, left_them = _items_phrase(left)
300
+ tail = (
301
+ f'nothing was charged for {left_them}' if given_back
302
+ else f'what was charged for {left_them} could not be given back yet (see the warning about it)'
303
+ )
304
+ logger.info(
305
+ '%s: saved the first %s item(s), charged in full; the other %s %s not saved and %s.',
306
+ head, rows_saved, left, left_were.split()[-1], tail,
307
+ )
308
+
309
+
231
310
  def merge_charge_results(a: ChargeResult, b: ChargeResult) -> ChargeResult:
232
311
  """Merge two :class:`ChargeResult` objects (Node SDK ``mergeChargeResults`` parity).
233
312
 
@@ -301,6 +380,23 @@ class ChargeRejectedError(Exception):
301
380
  self.max_items = max_items
302
381
 
303
382
 
383
+ def _spending_limit_usd(value: Any) -> Optional[Decimal]:
384
+ """The run's spending limit (max_total_charge_usd), or None when uncapped.
385
+
386
+ 0 is a real limit (no fees), the same as on the platform; only a missing
387
+ or non-numeric value means uncapped.
388
+ """
389
+ if value is None or value == '':
390
+ return None
391
+ try:
392
+ usd = Decimal(str(value))
393
+ except (InvalidOperation, ValueError):
394
+ return None
395
+ if not usd.is_finite() or usd < 0:
396
+ return None
397
+ return usd
398
+
399
+
304
400
  class ChargingManager:
305
401
  """Manages charging for pay-per-event Actors.
306
402
 
@@ -389,6 +485,10 @@ class ChargingManager:
389
485
  # definitively refused to void (event -> count): they stay billed, so the
390
486
  # next push of that event uses them instead of charging again.
391
487
  self._void_refused_credit: Dict[str, int] = {}
488
+ # Set by push_data_with_charges while it runs (it holds the operation
489
+ # lock): charges that came back short are collected here instead of being
490
+ # logged, because the atomic push gives them back (see _ShortCharge).
491
+ self._short_charges: Optional[List['_ShortCharge']] = None
392
492
 
393
493
  def close(self) -> None:
394
494
  """Mark the manager closed; subsequent charge/push operations are rejected."""
@@ -655,9 +755,8 @@ class ChargingManager:
655
755
 
656
756
  pricing_data = await self._fetch_pricing_data()
657
757
 
658
- # Load max total charge (absent/zero means no cap — JS `|| Infinity` parity).
659
- max_charge = pricing_data.get('max_total_charge_usd')
660
- self._max_total_charge_usd = Decimal(str(max_charge)) if max_charge else None
758
+ # Load max total charge (absent means no cap; 0 is a real limit, as on the platform).
759
+ self._max_total_charge_usd = _spending_limit_usd(pricing_data.get('max_total_charge_usd'))
661
760
 
662
761
  # Load pricing info (env when complete, otherwise the run API at home).
663
762
  pricing_info_raw = pricing_data.get('pricing_info')
@@ -1399,15 +1498,21 @@ class ChargingManager:
1399
1498
 
1400
1499
  if chargeable_count < count:
1401
1500
  subject = 'instance' if count == 1 else 'instances'
1402
- logger.info(
1403
- "Charging %s %s of '%s' event would exceed %s - "
1404
- 'only %s events were charged',
1405
- count,
1406
- subject,
1407
- event_name,
1408
- self._limit_name(),
1409
- chargeable_count,
1410
- )
1501
+ legacy_args = (count, subject, event_name, self._limit_name(), chargeable_count)
1502
+ sink = getattr(self, '_short_charges', None)
1503
+ if sink is not None:
1504
+ # Inside an atomic push: this charge is given back unless the row
1505
+ # is saved, so "only N events were charged" would not be true.
1506
+ # push_data_with_charges logs what really happened instead.
1507
+ sink.append(_ShortCharge(
1508
+ event_name=event_name,
1509
+ requested=count,
1510
+ covered=chargeable_count,
1511
+ limit=self._limit_name(),
1512
+ taken_by_filter=_offer_to_log_filters(_LEGACY_SHORT_CHARGE_LINE, legacy_args),
1513
+ ))
1514
+ else:
1515
+ logger.info(_LEGACY_SHORT_CHARGE_LINE, *legacy_args)
1411
1516
 
1412
1517
  return result
1413
1518
 
@@ -1516,8 +1621,8 @@ class ChargingManager:
1516
1621
  Returns:
1517
1622
  Maximum total charge in USD
1518
1623
  """
1519
- # No configured cap (or zero) means unlimited — JS returns Infinity.
1520
- return self._max_total_charge_usd if self._max_total_charge_usd else Decimal('Infinity')
1624
+ # No configured cap means unlimited — JS returns Infinity.
1625
+ return self._max_total_charge_usd if self._max_total_charge_usd is not None else Decimal('Infinity')
1521
1626
 
1522
1627
  def get_pricing_info(self) -> ActorPricingInfoResult:
1523
1628
  """Retrieve detailed pricing information for the current Actor run.
@@ -2164,8 +2269,13 @@ async def push_data_with_charges(
2164
2269
  rows = min(rows, max(0, int(remaining / row_cost)))
2165
2270
 
2166
2271
  ops: List[tuple] = [] # (event, charged, op_id, uncertain, paid_from_credit)
2272
+ # Charges of this push that came back short: given back, and logged once
2273
+ # the outcome is known (_log_atomic_refusal), not as "only N were charged".
2274
+ shorts: List[_ShortCharge] = []
2275
+ given_back = True
2167
2276
 
2168
2277
  async def undo(entries: List[tuple]) -> None:
2278
+ nonlocal given_back
2169
2279
  for name, charged, op_id, uncertain, credit in entries:
2170
2280
  if charged <= 0:
2171
2281
  continue
@@ -2175,58 +2285,68 @@ async def push_data_with_charges(
2175
2285
  charging_manager._unwind_reservation(name, charged)
2176
2286
  else:
2177
2287
  # Cancel / void; a refused void stays billed and becomes credit.
2178
- await charging_manager._void_or_credit(name, op_id, charged, uncertain)
2179
-
2180
- for _attempt in range(6):
2181
- if rows <= 0:
2182
- break
2183
- ops = []
2184
- short_to: Optional[int] = None
2185
- for name, n in sorted(per_row.items(), key=lambda kv: (is_default_dataset_item_event(kv[0]), kv[0])):
2186
- want = n * rows
2187
- charging_manager._take_last_accepted_operation_id()
2188
- if charging_manager._take_void_credit(name, want):
2189
- # Paid by an earlier charge whose results were not stored (void refused).
2190
- ops.append((name, want, None, False, True))
2191
- continue
2192
- try:
2193
- r = await charging_manager._charge_exclusive(name, want)
2194
- op_id = charging_manager._take_last_accepted_operation_id()
2195
- ops.append((name, r.charged_count, op_id, False, False))
2196
- got = r.charged_count
2197
- except ChargeUncertainError as unconfirmed:
2198
- # Not confirmed: the intent stays pending and is re-posted at exit,
2199
- # so it counts as accepted (items stored, billed once).
2200
- ops.append((name, unconfirmed.count, unconfirmed.operation_id, True, False))
2201
- got = unconfirmed.count
2202
- if got < want:
2203
- short_to = got // n
2288
+ if await charging_manager._void_or_credit(name, op_id, charged, uncertain) != 'voided':
2289
+ given_back = False
2290
+
2291
+ def covered_counts() -> Dict[str, int]:
2292
+ # Per event: how many events the limit covered in its last short answer.
2293
+ return {short.event_name: short.covered for short in shorts}
2294
+
2295
+ charging_manager._short_charges = shorts
2296
+ try:
2297
+ for _attempt in range(6):
2298
+ if rows <= 0:
2204
2299
  break
2205
- if short_to is None:
2206
- break
2207
- # Some event came back short: void this attempt in full and retry with
2208
- # the whole rows the budget covers at the FULL per-row cost. Sizing
2209
- # from the short event alone ignores the other events of the row, so
2210
- # the retry came back short again (appstore 64df0a3608d74af88: 20
2211
- # details -> 14, retry sized 14, app-item short, 0 saved). What this
2212
- # attempt was accepted is budget the void gives back; with the
2213
- # platform's remainingBudgetNd the local budget also knows the rest.
2214
- attempt_spent = sum(
2215
- (charging_manager._calculate_event_price(name) or Decimal('0')) * Decimal(charged)
2216
- for name, charged, _op, _unc, _credit in ops
2217
- )
2218
- await undo(ops)
2219
- ops = []
2220
- fit = int(attempt_spent / row_cost) if row_cost > 0 else 0
2221
- if charging_manager._platform_budget_seen and charging_manager._max_total_charge_usd is not None and row_cost > 0:
2222
- fit = max(fit, int(charging_manager._remaining_budget_usd() / row_cost))
2223
- # At least one more single-row try: without the platform's remaining
2224
- # budget the leftover after the short answer is unknown, and the last
2225
- # affordable row may still fit.
2226
- rows = min(rows - 1, max(fit, 1))
2300
+ ops = []
2301
+ short_to: Optional[int] = None
2302
+ for name, n in sorted(per_row.items(), key=lambda kv: (is_default_dataset_item_event(kv[0]), kv[0])):
2303
+ want = n * rows
2304
+ charging_manager._take_last_accepted_operation_id()
2305
+ if charging_manager._take_void_credit(name, want):
2306
+ # Paid by an earlier charge whose results were not stored (void refused).
2307
+ ops.append((name, want, None, False, True))
2308
+ continue
2309
+ try:
2310
+ r = await charging_manager._charge_exclusive(name, want)
2311
+ op_id = charging_manager._take_last_accepted_operation_id()
2312
+ ops.append((name, r.charged_count, op_id, False, False))
2313
+ got = r.charged_count
2314
+ except ChargeUncertainError as unconfirmed:
2315
+ # Not confirmed: the intent stays pending and is re-posted at exit,
2316
+ # so it counts as accepted (items stored, billed once).
2317
+ ops.append((name, unconfirmed.count, unconfirmed.operation_id, True, False))
2318
+ got = unconfirmed.count
2319
+ if got < want:
2320
+ short_to = got // n
2321
+ break
2322
+ if short_to is None:
2323
+ break
2324
+ # Some event came back short: void this attempt in full and retry with
2325
+ # the whole rows the budget covers at the FULL per-row cost. Sizing
2326
+ # from the short event alone ignores the other events of the row, so
2327
+ # the retry came back short again (appstore 64df0a3608d74af88: 20
2328
+ # details -> 14, retry sized 14, app-item short, 0 saved). What this
2329
+ # attempt was accepted is budget the void gives back; with the
2330
+ # platform's remainingBudgetNd the local budget also knows the rest.
2331
+ attempt_spent = sum(
2332
+ (charging_manager._calculate_event_price(name) or Decimal('0')) * Decimal(charged)
2333
+ for name, charged, _op, _unc, _credit in ops
2334
+ )
2335
+ await undo(ops)
2336
+ ops = []
2337
+ fit = int(attempt_spent / row_cost) if row_cost > 0 else 0
2338
+ if charging_manager._platform_budget_seen and charging_manager._max_total_charge_usd is not None and row_cost > 0:
2339
+ fit = max(fit, int(charging_manager._remaining_budget_usd() / row_cost))
2340
+ # At least one more single-row try: without the platform's remaining
2341
+ # budget the leftover after the short answer is unknown, and the last
2342
+ # affordable row may still fit.
2343
+ rows = min(rows - 1, max(fit, 1))
2344
+ finally:
2345
+ charging_manager._short_charges = None
2227
2346
 
2228
2347
  if rows <= 0 or not ops:
2229
2348
  await undo(ops)
2349
+ _log_atomic_refusal(shorts, len(rows_in), 0, given_back)
2230
2350
  charging_manager._mark_charge_limit_hit()
2231
2351
  if is_default_dataset:
2232
2352
  charging_manager._note_refused_default_dataset_items(len(rows_in))
@@ -2234,6 +2354,7 @@ async def push_data_with_charges(
2234
2354
  chargeable_within_limit=charging_manager.compute_chargeable(),
2235
2355
  charged_count=0,
2236
2356
  event_charge_limit_reached=True,
2357
+ covered_counts=covered_counts(),
2237
2358
  )
2238
2359
 
2239
2360
  kept = rows_in if batch else rows_in[:rows]
@@ -2248,10 +2369,12 @@ async def push_data_with_charges(
2248
2369
  if _push_certainly_failed(push_err):
2249
2370
  await undo(ops)
2250
2371
  raise
2372
+ _log_atomic_refusal(shorts, len(rows_in), len(kept), given_back)
2251
2373
  return ChargeResult(
2252
2374
  chargeable_within_limit=charging_manager.compute_chargeable(),
2253
2375
  charged_count=len(kept),
2254
2376
  event_charge_limit_reached=len(kept) < len(rows_in) or charging_manager.is_charge_limit_reached(),
2377
+ covered_counts=covered_counts(),
2255
2378
  )
2256
2379
 
2257
2380
 
@@ -11,15 +11,29 @@ from __future__ import annotations
11
11
 
12
12
  from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Sequence
13
13
 
14
- from scrapely_client import ApifyClientAsync
14
+ if TYPE_CHECKING:
15
+ from scrapely_client import USES_PUSH_DATA_INTERCEPTION, ApifyClientAsync, push_data_charging_context
16
+
17
+ from .charging import ChargingManager
15
18
 
19
+ # ``scrapely_client`` (219 pydantic models) loads only when a client is created
20
+ # or one of its names below is used: ``Actor`` imports this module, and most
21
+ # runs never create an API client.
22
+ #
16
23
  # Re-exported so the SDK and the client share one marker attribute and one
17
24
  # context var. Identity matters: the client's intercepted ``push_items()``
18
25
  # reads/writes these, and the SDK detects interception via the attribute.
19
- from scrapely_client import USES_PUSH_DATA_INTERCEPTION, push_data_charging_context
26
+ _CLIENT_NAMES = frozenset({'ApifyClientAsync', 'USES_PUSH_DATA_INTERCEPTION', 'push_data_charging_context'})
20
27
 
21
- if TYPE_CHECKING:
22
- from .charging import ChargingManager
28
+
29
+ def __getattr__(name: str) -> Any:
30
+ if name in _CLIENT_NAMES:
31
+ import scrapely_client
32
+
33
+ value = getattr(scrapely_client, name)
34
+ globals()[name] = value
35
+ return value
36
+ raise AttributeError(f'module {__name__!r} has no attribute {name!r}')
23
37
 
24
38
  __all__ = [
25
39
  'USES_PUSH_DATA_INTERCEPTION',
@@ -81,7 +95,7 @@ def create_charging_client(
81
95
  charging_manager: Optional['ChargingManager'] = None,
82
96
  default_dataset_id: Optional[str] = None,
83
97
  **kwargs: Any,
84
- ) -> ApifyClientAsync:
98
+ ) -> 'ApifyClientAsync':
85
99
  """Create an ``ApifyClientAsync`` configured with the SDK's charging hooks.
86
100
 
87
101
  Args:
@@ -101,6 +115,8 @@ def create_charging_client(
101
115
  if api_public_url:
102
116
  kwargs['api_public_url'] = api_public_url
103
117
 
118
+ from scrapely_client import ApifyClientAsync
119
+
104
120
  charging_hooks = _ChargingManagerHooks(charging_manager) if charging_manager is not None else None
105
121
 
106
122
  return ApifyClientAsync(
@@ -30,11 +30,11 @@ Mirrors the Node SDK ``patch-browser-pool.ts``:
30
30
  sandbox-safe Chromium args when running on the platform.
31
31
  - Soft no-op when Playwright/Crawlee browsers are not installed (e.g. HTTP-only
32
32
  actors).
33
- - Crawlee is never imported by this module (it costs ~1 s on the platform). The
34
- Crawlee patches are applied at once when Crawlee's browser / Playwright
35
- crawler modules are already loaded, otherwise by a post-import hook the
36
- moment those modules finish loading — before actor code can use the classes.
37
- The Playwright, Camoufox and pyppeteer patches are applied eagerly on import.
33
+ - Neither Crawlee, Playwright, Camoufox nor pyppeteer is imported by this
34
+ module (the base images import it at every interpreter start). Each patch is
35
+ applied at once when its module is already loaded, otherwise by a
36
+ post-import hook the moment that module finishes loading — before actor code
37
+ can use what it patches.
38
38
 
39
39
  Location and proxy handling (the remote browser never takes a proxy):
40
40
 
@@ -67,19 +67,79 @@ Location and proxy handling (the remote browser never takes a proxy):
67
67
  from __future__ import annotations
68
68
 
69
69
  import contextvars
70
- import functools
71
- import importlib.abc
72
- import logging
73
70
  import os
74
- import re
75
71
  import sys
76
- from typing import Any, List, Optional, Tuple
77
- from urllib.parse import SplitResult, parse_qsl, unquote, urlencode, urlsplit, urlunsplit
78
72
 
79
- from ._browser_locations import subdivision_to_state_name
80
- from .cdp_retry import connect_with_retry_async, wrap_connect_over_cdp
73
+ # This module is imported at EVERY interpreter start in actor images (base
74
+ # image sitecustomize), before any actor code: it imports only builtin modules
75
+ # at load time. Everything else (typing, logging, re, urllib.parse, functools,
76
+ # asyncio via cdp_retry, the browser location table) loads on first use.
77
+ TYPE_CHECKING = False
78
+ if TYPE_CHECKING:
79
+ from typing import Any, List, Optional, Tuple
80
+ from urllib.parse import SplitResult
81
81
 
82
- logger = logging.getLogger(__name__)
82
+
83
+ class _LazyLogger:
84
+ """``logging.getLogger(__name__)``, imported on first use."""
85
+
86
+ def __getattr__(self, name: str) -> Any:
87
+ import logging
88
+
89
+ return getattr(logging.getLogger(__name__), name)
90
+
91
+
92
+ logger = _LazyLogger()
93
+
94
+
95
+ def urlsplit(*args: Any, **kwargs: Any) -> Any:
96
+ from urllib.parse import urlsplit as _urlsplit
97
+
98
+ return _urlsplit(*args, **kwargs)
99
+
100
+
101
+ def urlunsplit(*args: Any, **kwargs: Any) -> Any:
102
+ from urllib.parse import urlunsplit as _urlunsplit
103
+
104
+ return _urlunsplit(*args, **kwargs)
105
+
106
+
107
+ def parse_qsl(*args: Any, **kwargs: Any) -> Any:
108
+ from urllib.parse import parse_qsl as _parse_qsl
109
+
110
+ return _parse_qsl(*args, **kwargs)
111
+
112
+
113
+ def urlencode(*args: Any, **kwargs: Any) -> Any:
114
+ from urllib.parse import urlencode as _urlencode
115
+
116
+ return _urlencode(*args, **kwargs)
117
+
118
+
119
+ def unquote(*args: Any, **kwargs: Any) -> Any:
120
+ from urllib.parse import unquote as _unquote
121
+
122
+ return _unquote(*args, **kwargs)
123
+
124
+
125
+ # ``cdp_retry`` pulls in asyncio and ``_browser_locations`` is a large table;
126
+ # both are only needed once a browser is actually launched.
127
+ def subdivision_to_state_name(country: Optional[str], subdivision: Optional[str]) -> Optional[str]:
128
+ from ._browser_locations import subdivision_to_state_name as _subdivision_to_state_name
129
+
130
+ return _subdivision_to_state_name(country, subdivision)
131
+
132
+
133
+ def wrap_connect_over_cdp(*args: Any, **kwargs: Any) -> Any:
134
+ from .cdp_retry import wrap_connect_over_cdp as _wrap_connect_over_cdp
135
+
136
+ return _wrap_connect_over_cdp(*args, **kwargs)
137
+
138
+
139
+ async def connect_with_retry_async(*args: Any, **kwargs: Any) -> Any:
140
+ from .cdp_retry import connect_with_retry_async as _connect_with_retry_async
141
+
142
+ return await _connect_with_retry_async(*args, **kwargs)
83
143
 
84
144
  _cdp_url: Optional[str] = None
85
145
 
@@ -219,7 +279,7 @@ def _redact_proxy_url(proxy_url: str) -> str:
219
279
  return f'{parts.scheme or "http"}://{userinfo}{parts.hostname}{port}'
220
280
 
221
281
 
222
- _COUNTRY_FRAGMENT_RE = re.compile(r'^country-([A-Za-z]{2})(?:_([A-Za-z0-9]{1,3}))?$')
282
+ _COUNTRY_FRAGMENT_PATTERN = r'^country-([A-Za-z]{2})(?:_([A-Za-z0-9]{1,3}))?$'
223
283
 
224
284
 
225
285
  def _parse_proxy_url_location(proxy_url: Optional[str]) -> Tuple[Optional[str], Optional[str]]:
@@ -229,8 +289,10 @@ def _parse_proxy_url_location(proxy_url: Optional[str]) -> Tuple[Optional[str],
229
289
  parts = _parse_proxy_url(str(proxy_url))
230
290
  if not parts or not parts.username:
231
291
  return None, None
292
+ import re
293
+
232
294
  for fragment in unquote(parts.username).split(','):
233
- match = _COUNTRY_FRAGMENT_RE.match(fragment.strip())
295
+ match = re.match(_COUNTRY_FRAGMENT_PATTERN, fragment.strip())
234
296
  if match:
235
297
  subdivision = match.group(2)
236
298
  return match.group(1).upper(), subdivision.upper() if subdivision else None
@@ -475,6 +537,8 @@ def _apply_crawler_patch() -> None:
475
537
  if getattr(PlaywrightCrawler, '_scrapely_browser_config_patched', False):
476
538
  return
477
539
 
540
+ import functools
541
+
478
542
  _orig_init = PlaywrightCrawler.__init__
479
543
 
480
544
  @functools.wraps(_orig_init)
@@ -784,39 +848,46 @@ class _AsyncPlaywrightContextManagerProxy:
784
848
  return await self._cm.__aexit__(*exc)
785
849
 
786
850
 
787
- def _apply_raw_playwright_patch() -> None:
788
- """Wrap playwright's sync/async entry points to redirect raw launches to CDP."""
851
+ def _apply_raw_playwright_async_patch() -> None:
852
+ """Wrap ``playwright.async_api.async_playwright`` to redirect raw launches to CDP."""
789
853
  try:
790
854
  import playwright.async_api as playwright_async_api
791
855
  except ImportError:
792
- playwright_async_api = None # type: ignore[assignment]
856
+ return
793
857
 
794
- if playwright_async_api is not None and not getattr(
795
- playwright_async_api, '_scrapely_raw_cdp_patched', False
796
- ):
797
- orig_async = playwright_async_api.async_playwright
858
+ if getattr(playwright_async_api, '_scrapely_raw_cdp_patched', False):
859
+ return
860
+ orig_async = playwright_async_api.async_playwright
861
+
862
+ def async_playwright_patched() -> Any:
863
+ return _AsyncPlaywrightContextManagerProxy(orig_async())
798
864
 
799
- def async_playwright_patched() -> Any:
800
- return _AsyncPlaywrightContextManagerProxy(orig_async())
865
+ playwright_async_api.async_playwright = async_playwright_patched
866
+ playwright_async_api._scrapely_raw_cdp_patched = True # type: ignore[attr-defined]
801
867
 
802
- playwright_async_api.async_playwright = async_playwright_patched
803
- playwright_async_api._scrapely_raw_cdp_patched = True # type: ignore[attr-defined]
804
868
 
869
+ def _apply_raw_playwright_sync_patch() -> None:
870
+ """Wrap ``playwright.sync_api.sync_playwright`` to redirect raw launches to CDP."""
805
871
  try:
806
872
  import playwright.sync_api as playwright_sync_api
807
873
  except ImportError:
808
- playwright_sync_api = None # type: ignore[assignment]
874
+ return
809
875
 
810
- if playwright_sync_api is not None and not getattr(
811
- playwright_sync_api, '_scrapely_raw_cdp_patched', False
812
- ):
813
- orig_sync = playwright_sync_api.sync_playwright
876
+ if getattr(playwright_sync_api, '_scrapely_raw_cdp_patched', False):
877
+ return
878
+ orig_sync = playwright_sync_api.sync_playwright
814
879
 
815
- def sync_playwright_patched() -> Any:
816
- return _SyncPlaywrightContextManagerProxy(orig_sync())
880
+ def sync_playwright_patched() -> Any:
881
+ return _SyncPlaywrightContextManagerProxy(orig_sync())
817
882
 
818
- playwright_sync_api.sync_playwright = sync_playwright_patched
819
- playwright_sync_api._scrapely_raw_cdp_patched = True # type: ignore[attr-defined]
883
+ playwright_sync_api.sync_playwright = sync_playwright_patched
884
+ playwright_sync_api._scrapely_raw_cdp_patched = True # type: ignore[attr-defined]
885
+
886
+
887
+ def _apply_raw_playwright_patch() -> None:
888
+ """Wrap playwright's sync/async entry points to redirect raw launches to CDP."""
889
+ _apply_raw_playwright_async_patch()
890
+ _apply_raw_playwright_sync_patch()
820
891
 
821
892
 
822
893
  def _apply_pyppeteer_patch() -> None:
@@ -874,31 +945,59 @@ def _apply_pyppeteer_patch() -> None:
874
945
  pyppeteer_mod._scrapely_cdp_patched = True
875
946
 
876
947
 
877
- # ─── Crawlee patches without importing Crawlee ───────────────────────────────
948
+ # ─── Patches applied when their library loads ────────────────────────────────
878
949
  #
879
- # Importing Crawlee costs ~1 s per run on the platform, so this module never
880
- # imports it. The Crawlee patches mutate classes in place, so they only have to
881
- # run before actor code uses those classes: they are applied immediately when
882
- # the defining modules are already loaded, otherwise by a post-import hook the
883
- # moment they finish executing (``import crawlee.browsers``,
884
- # ``from crawlee.crawlers import PlaywrightCrawler``, a PlaywrightCrawler built
885
- # by any template...). Behaviour is the same as applying them eagerly.
950
+ # This module is imported at every interpreter start in actor images (base
951
+ # image sitecustomize), so it never imports Crawlee, Playwright, Camoufox or
952
+ # pyppeteer itself: importing them up front cost ~1 s per process on the
953
+ # platform even when the actor never opens a browser. Every patch mutates a
954
+ # module or class in place, so it only has to run before actor code can use
955
+ # what it patches: it is applied at once when the defining module is already
956
+ # loaded, otherwise by a post-import hook the moment that module finishes
957
+ # executing, before the import statement that loaded it returns
958
+ # (``import crawlee.browsers``, ``from crawlee.crawlers import
959
+ # PlaywrightCrawler``, ``from playwright.async_api import async_playwright``, a
960
+ # PlaywrightCrawler built by any template...). Behaviour is the same as
961
+ # applying them eagerly.
886
962
 
887
963
  # Module name -> patch functions to run once that module has finished loading.
888
964
  # ``crawlee.browsers`` imports BrowserPool, PlaywrightBrowserController and
889
965
  # PlaywrightBrowserPlugin in its ``__init__``; any import of one of those
890
- # submodules runs that ``__init__`` to completion first.
891
- _CRAWLEE_POST_IMPORT_PATCHES: dict = {
966
+ # submodules runs that ``__init__`` to completion first. Likewise importing
967
+ # ``pyppeteer.launcher`` runs the ``pyppeteer`` package first, and the
968
+ # ``camoufox`` package defines the ``AsyncNewBrowser`` the patch replaces.
969
+ _POST_IMPORT_PATCHES: dict = {
892
970
  'crawlee.browsers': (_apply_patch,),
893
971
  'crawlee.crawlers._playwright._playwright_crawler': (_apply_crawler_patch,),
972
+ 'playwright.async_api': (_apply_raw_playwright_async_patch,),
973
+ 'playwright.sync_api': (_apply_raw_playwright_sync_patch,),
974
+ 'camoufox': (_apply_camoufox_patch,),
975
+ 'pyppeteer': (_apply_pyppeteer_patch,),
894
976
  }
977
+ # Kept under its old name for code that inspects it.
978
+ _CRAWLEE_POST_IMPORT_PATCHES = _POST_IMPORT_PATCHES
979
+
980
+
981
+ def _run_patches(module_name: str, patches: tuple) -> None:
982
+ """Run the patches for a loaded module; a failing patch never breaks the actor's import."""
983
+ for patch in patches:
984
+ try:
985
+ patch()
986
+ except Exception as exc: # pragma: no cover - defensive (incompatible library version)
987
+ logger.warning(
988
+ '[scrapely] Could not patch %s for the remote browser (%s: %s)',
989
+ module_name,
990
+ type(exc).__name__,
991
+ exc,
992
+ )
895
993
 
896
994
 
897
- class _PostImportLoader(importlib.abc.Loader):
995
+ class _PostImportLoader:
898
996
  """Delegating loader that runs the Scrapely patches after the module executes."""
899
997
 
900
- def __init__(self, loader: Any, patches: tuple) -> None:
998
+ def __init__(self, loader: Any, fullname: str, patches: tuple) -> None:
901
999
  self._loader = loader
1000
+ self._fullname = fullname
902
1001
  self._patches = patches
903
1002
 
904
1003
  def create_module(self, spec: Any) -> Any:
@@ -914,22 +1013,25 @@ class _PostImportLoader(importlib.abc.Loader):
914
1013
  except Exception:
915
1014
  pass
916
1015
  self._loader.exec_module(module)
917
- for patch in self._patches:
918
- patch()
1016
+ # The module loaded: patch it now, once. A failed load (the exception
1017
+ # above) keeps the hook, so a later successful import is patched too.
1018
+ if _POST_IMPORT_PATCHES.get(self._fullname) is self._patches:
1019
+ _POST_IMPORT_PATCHES.pop(self._fullname, None)
1020
+ _run_patches(self._fullname, self._patches)
919
1021
 
920
1022
  def __getattr__(self, name: str) -> Any:
921
1023
  return getattr(self._loader, name)
922
1024
 
923
1025
 
924
- class _CrawleePostImportFinder(importlib.abc.MetaPathFinder):
925
- """Meta path finder that hooks the Crawlee modules in ``_CRAWLEE_POST_IMPORT_PATCHES``."""
1026
+ class _PostImportFinder:
1027
+ """Meta path finder that hooks the modules in ``_POST_IMPORT_PATCHES``."""
926
1028
 
927
1029
  def find_spec(self, fullname: str, path: Any = None, target: Any = None) -> Any:
928
- patches = _CRAWLEE_POST_IMPORT_PATCHES.get(fullname)
1030
+ patches = _POST_IMPORT_PATCHES.get(fullname)
929
1031
  if patches is None:
930
1032
  return None
931
1033
  for finder in sys.meta_path:
932
- if finder is self or isinstance(finder, _CrawleePostImportFinder):
1034
+ if finder is self or isinstance(finder, _PostImportFinder):
933
1035
  continue
934
1036
  find_spec = getattr(finder, 'find_spec', None)
935
1037
  if find_spec is None:
@@ -941,25 +1043,25 @@ class _CrawleePostImportFinder(importlib.abc.MetaPathFinder):
941
1043
  return None
942
1044
  if spec.loader is None or not hasattr(spec.loader, 'exec_module'):
943
1045
  return spec
944
- # One-shot: the patches are idempotent, but a module loads only once.
945
- _CRAWLEE_POST_IMPORT_PATCHES.pop(fullname, None)
946
- spec.loader = _PostImportLoader(spec.loader, patches)
1046
+ # The hook stays registered until the module has really loaded
1047
+ # (``importlib.util.find_spec`` availability checks do not consume it).
1048
+ spec.loader = _PostImportLoader(spec.loader, fullname, patches)
947
1049
  return spec
948
1050
 
949
1051
 
950
- def _install_crawlee_patches() -> None:
951
- """Apply the Crawlee patches now if Crawlee is loaded, else when it loads."""
952
- for module_name in list(_CRAWLEE_POST_IMPORT_PATCHES):
1052
+ # Kept under its old name for code that inspects ``sys.meta_path``.
1053
+ _CrawleePostImportFinder = _PostImportFinder
1054
+
1055
+
1056
+ def _install_post_import_patches() -> None:
1057
+ """Apply each patch now if its module is loaded, else when it loads."""
1058
+ for module_name in list(_POST_IMPORT_PATCHES):
953
1059
  if module_name in sys.modules:
954
- for patch in _CRAWLEE_POST_IMPORT_PATCHES.pop(module_name):
955
- patch()
956
- if _CRAWLEE_POST_IMPORT_PATCHES and not any(
957
- isinstance(finder, _CrawleePostImportFinder) for finder in sys.meta_path
958
- ):
959
- sys.meta_path.insert(0, _CrawleePostImportFinder())
960
-
961
-
962
- _install_crawlee_patches()
963
- _apply_camoufox_patch()
964
- _apply_raw_playwright_patch()
965
- _apply_pyppeteer_patch()
1060
+ _run_patches(module_name, _POST_IMPORT_PATCHES.pop(module_name))
1061
+ if _POST_IMPORT_PATCHES and not any(isinstance(finder, _PostImportFinder) for finder in sys.meta_path):
1062
+ sys.meta_path.insert(0, _PostImportFinder())
1063
+
1064
+
1065
+ _install_crawlee_patches = _install_post_import_patches
1066
+
1067
+ _install_post_import_patches()
scrapely/pricing_types.py CHANGED
@@ -126,6 +126,16 @@ class ChargeResult(BaseModel):
126
126
  alias='eventChargeLimitReached',
127
127
  description='If true, no more events of this type can be charged within the limit.'
128
128
  )
129
+ covered_counts: Dict[str, int] = Field(
130
+ default_factory=dict,
131
+ alias='coveredCounts',
132
+ description=(
133
+ "push_data(..., charges={...}) only: for each event whose charge came back short, how many "
134
+ "events the limit (account balance, maxTotalChargeUsd, maxItems) covered. A row is saved "
135
+ "only when all of its events are charged, so those events were given back, not charged. "
136
+ "Empty when no charge came back short."
137
+ ),
138
+ )
129
139
 
130
140
 
131
141
  class ActorPricingInfoResult(BaseModel):
scrapely/solver.py CHANGED
@@ -612,11 +612,44 @@ def _checked(req: dict, target_url: str) -> dict:
612
612
  return req
613
613
 
614
614
 
615
+ # Session libraries whose responses can be streamed (httpx: .stream(); the others: stream=True).
616
+ _STREAM_LIBS = ("requests", "curl_cffi")
617
+
618
+
619
+ def _session_lib(session: Any) -> str:
620
+ return type(session).__module__.split(".")[0]
621
+
622
+
623
+ def _capped_text(buf: bytearray, encoding: str | None) -> str:
624
+ return bytes(buf[: _MAX_BODY + 1]).decode(encoding or "utf-8", errors="replace")
625
+
626
+
615
627
  def _send_sync(session: Any, req: dict, timeout: float) -> tuple[int, str]:
616
628
  body = req.get("body")
617
629
  kwargs: dict[str, Any] = {"headers": req.get("headers") or {}, "timeout": timeout}
618
630
  if body is not None:
619
631
  kwargs["content" if _is_httpx(session) else "data"] = body.encode() if isinstance(body, str) else body
632
+ # A step answer is read up to _MAX_BODY + 1 bytes: the target site decides its size.
633
+ lib = _session_lib(session)
634
+ if lib == "httpx":
635
+ with session.stream(req["method"], req["url"], **kwargs) as r:
636
+ buf = bytearray()
637
+ for chunk in r.iter_bytes():
638
+ buf += chunk
639
+ if len(buf) > _MAX_BODY:
640
+ break
641
+ return int(r.status_code), _capped_text(buf, r.encoding)
642
+ if lib in _STREAM_LIBS:
643
+ r = session.request(req["method"], req["url"], stream=True, **kwargs)
644
+ try:
645
+ buf = bytearray()
646
+ for chunk in r.iter_content(65536):
647
+ buf += chunk
648
+ if len(buf) > _MAX_BODY:
649
+ break
650
+ return int(r.status_code), _capped_text(buf, r.encoding)
651
+ finally:
652
+ r.close()
620
653
  r = session.request(req["method"], req["url"], **kwargs)
621
654
  return _status_body(r)
622
655
 
@@ -626,6 +659,26 @@ async def _send_async(session: Any, req: dict, timeout: float) -> tuple[int, str
626
659
  kwargs: dict[str, Any] = {"headers": req.get("headers") or {}, "timeout": timeout}
627
660
  if body is not None:
628
661
  kwargs["content" if _is_httpx(session) else "data"] = body.encode() if isinstance(body, str) else body
662
+ lib = _session_lib(session)
663
+ if lib == "httpx":
664
+ async with session.stream(req["method"], req["url"], **kwargs) as r:
665
+ buf = bytearray()
666
+ async for chunk in r.aiter_bytes():
667
+ buf += chunk
668
+ if len(buf) > _MAX_BODY:
669
+ break
670
+ return int(r.status_code), _capped_text(buf, r.encoding)
671
+ if lib == "curl_cffi":
672
+ r = await session.request(req["method"], req["url"], stream=True, **kwargs)
673
+ try:
674
+ buf = bytearray()
675
+ async for chunk in r.aiter_content():
676
+ buf += chunk
677
+ if len(buf) > _MAX_BODY:
678
+ break
679
+ return int(r.status_code), _capped_text(buf, r.encoding)
680
+ finally:
681
+ await r.aclose()
629
682
  r = await session.request(req["method"], req["url"], **kwargs)
630
683
  return _status_body(r)
631
684
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scrapely-python
3
- Version: 0.1.42
3
+ Version: 0.1.44
4
4
  Summary: Scrapely Python SDK - A toolkit for building Actors on the Scrapely platform
5
5
  Author-email: Scrapely <hello@scrape.ly>
6
6
  License-Expression: MIT AND Apache-2.0
@@ -1,18 +1,18 @@
1
- scrapely/__init__.py,sha256=5ifQCxUm8btxkp_9q1u6UPSgimx-D63FCey6Nydp6SM,9668
1
+ scrapely/__init__.py,sha256=pMEB6jkA8FTAE3mT-3t6H5l6LXfElFtZVyyTJb8LGBw,13040
2
2
  scrapely/_browser_locations.py,sha256=8QVVnkms2bDn3_LDYgYDR59MvFx8757l_JYnZ7xb3oI,145269
3
3
  scrapely/actor.py,sha256=nT-4xWfqx2Cd8swQ6DFkT8n8xYCoPy9a4dbA1bB-1GI,94391
4
4
  scrapely/browser_configuration.py,sha256=jAZapNSHLFW05B96df4wNBtcyiiU9DA3ml0yTL1FwfA,5770
5
5
  scrapely/cdp_retry.py,sha256=hdTJEAIKhApM7IOk1DrQEl8NoflSJSmqd4RbNJ2IsgI,8540
6
- scrapely/charging.py,sha256=qnlqSjKeaJnWepUl9alLytHooihRIVU2CruIYGlFcnk,106445
7
- scrapely/charging_client.py,sha256=-4q-Ww7gu9EZXpM9QIn1Vd4vwAXmgL_WEKqaQIx3ViA,3961
6
+ scrapely/charging.py,sha256=N-OPi0xxwl_SHfJA6rzmRvqS2ZMHR8IiPPNLm3FZ30s,112252
7
+ scrapely/charging_client.py,sha256=RitzAfgJui0dQKenWz_aFc0HeA1qKvzcDpk2bC7K8C0,4567
8
8
  scrapely/configuration.py,sha256=ONnzw4mhtrY2jVvoVUQ48dMgmMWnx3Gv7fXrT4pY9z8,16919
9
9
  scrapely/errors.py,sha256=V8JBCGSyqrbwMD9GDv6ahWhZ92n2cb8AWxkxth6mcI8,4062
10
10
  scrapely/log.py,sha256=H3SoBvmNNRp8ChD9qv_J-hG0Nc5qDy3RldLQcTTgWa8,1635
11
- scrapely/patch_browser_pool.py,sha256=eZck-JSOvCuXdoGQaX6xUsKVGzolDlB4uKiBSBrFyr8,42190
12
- scrapely/pricing_types.py,sha256=yy2nXmCxL0BvUXRtWnznwhoInYeVdWObMRT5Fo0fc4I,5083
11
+ scrapely/patch_browser_pool.py,sha256=c3tmWoUg9hLyQCNLHaB5BcEBbgNnSlJ_RZCCTxi47Yg,45737
12
+ scrapely/pricing_types.py,sha256=DYHSK1vhOe1eyqryPM8huuj_yChyAoF1th8rfT6erbE,5589
13
13
  scrapely/proxy_configuration.py,sha256=YAg2xm8eK4B14vCRWsSJxgtMIxdDJXbM66pZDx-HShk,39018
14
14
  scrapely/py.typed,sha256=XtWlywqUjc6x_M2gAXlDtYXbAsYkCjKZEjFyJvaHvm4,105
15
- scrapely/solver.py,sha256=9wVldJmye1P1f4c4bfZAMoRMRYB_CzmGY0Y2ZkI1nLI,55358
15
+ scrapely/solver.py,sha256=3b33PJVFG1ktqe5hkzpiB3Q7uGFbNlCZBY5VGAdc9AM,57381
16
16
  scrapely/types.py,sha256=2yGedPfb5786UNqnlnRG5Cw4Pbyc4EPBiYeoU2kix3I,8812
17
17
  scrapely/webhook.py,sha256=GUpQXQ1UYCKi3WZPJ9reztpilBXvwqYInXJxUax36M8,2823
18
18
  scrapely/crypto/__init__.py,sha256=MbMPs7Eq_fGSVjOZxNts_JckDCUtxCVqdkHU0VCfN4M,481
@@ -68,10 +68,10 @@ scrapely/storage/_file_system/_key_value_store_client.py,sha256=1C22qY-RWlARzMyW
68
68
  scrapely/storage/_file_system/_storage_client.py,sha256=QHa3IULEb6AmgRFwpBqHD2OUTmtA_gl3lId-j6QdSFo,2027
69
69
  scrapely/storage_clients/__init__.py,sha256=q2pC-Rwe-BfHl018OyN_P0EDSx4-hNdxbk3pOCLLd4U,618
70
70
  scrapely/storages/__init__.py,sha256=kDNtd9VodjdHd4u7GzruJo0aB2HeiBN2_-HrkeqjmFg,139
71
- scrapely_python-0.1.42.dist-info/licenses/LICENSE,sha256=pQGY0XwjIYh-a2HfawxHq1en53bXkFkDj2Q70jKWHr4,1088
72
- scrapely_python-0.1.42.dist-info/licenses/LICENSE-APACHE,sha256=N8m0FzMq8i4UbTgXZvKEZJSD-27OF8pWZYS_atz4kTU,11355
73
- scrapely_python-0.1.42.dist-info/licenses/NOTICE,sha256=1ltrzKk2ez7x2BPNpXeyvOlTty5AfABYDBlwNilpORk,788
74
- scrapely_python-0.1.42.dist-info/METADATA,sha256=sZW9HkpiYLFvgRsQ-DVb-ZcfqUSH5zodw9nNMMw8wgM,4914
75
- scrapely_python-0.1.42.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
76
- scrapely_python-0.1.42.dist-info/top_level.txt,sha256=T4B9UMrs4q99QSAFyD1zdXhl40KnLhBKqrDkPhOTsmY,9
77
- scrapely_python-0.1.42.dist-info/RECORD,,
71
+ scrapely_python-0.1.44.dist-info/licenses/LICENSE,sha256=pQGY0XwjIYh-a2HfawxHq1en53bXkFkDj2Q70jKWHr4,1088
72
+ scrapely_python-0.1.44.dist-info/licenses/LICENSE-APACHE,sha256=N8m0FzMq8i4UbTgXZvKEZJSD-27OF8pWZYS_atz4kTU,11355
73
+ scrapely_python-0.1.44.dist-info/licenses/NOTICE,sha256=1ltrzKk2ez7x2BPNpXeyvOlTty5AfABYDBlwNilpORk,788
74
+ scrapely_python-0.1.44.dist-info/METADATA,sha256=3HXKnsRm9XwmwmWWmhFgDmUwG8jqTfyRtXm00r-mgjI,4914
75
+ scrapely_python-0.1.44.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
76
+ scrapely_python-0.1.44.dist-info/top_level.txt,sha256=T4B9UMrs4q99QSAFyD1zdXhl40KnLhBKqrDkPhOTsmY,9
77
+ scrapely_python-0.1.44.dist-info/RECORD,,