scrapely-python 0.1.43__tar.gz → 0.1.44__tar.gz

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 (84) hide show
  1. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/CHANGELOG.md +8 -0
  2. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/PKG-INFO +1 -1
  3. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/pyproject.toml +1 -1
  4. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/__init__.py +1 -1
  5. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/charging.py +186 -63
  6. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/pricing_types.py +10 -0
  7. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/solver.py +53 -0
  8. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely_python.egg-info/PKG-INFO +1 -1
  9. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/LICENSE +0 -0
  10. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/LICENSE-APACHE +0 -0
  11. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/MANIFEST.in +0 -0
  12. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/NOTICE +0 -0
  13. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/README.md +0 -0
  14. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/setup.cfg +0 -0
  15. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/_browser_locations.py +0 -0
  16. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/actor.py +0 -0
  17. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/browser_configuration.py +0 -0
  18. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/cdp_retry.py +0 -0
  19. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/charging_client.py +0 -0
  20. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/configuration.py +0 -0
  21. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/crypto/__init__.py +0 -0
  22. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/crypto/_secrets.py +0 -0
  23. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/errors.py +0 -0
  24. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/events/__init__.py +0 -0
  25. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/events/_types.py +0 -0
  26. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/events/event_manager.py +0 -0
  27. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/http/__init__.py +0 -0
  28. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/http/_capture.py +0 -0
  29. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/http/_client.py +0 -0
  30. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/http/_compat.py +0 -0
  31. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/http/_detect.py +0 -0
  32. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/http/_headers.py +0 -0
  33. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/http/_options.py +0 -0
  34. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/http/_policy.py +0 -0
  35. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/http/_profiles.py +0 -0
  36. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/http/_response.py +0 -0
  37. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/http/_stats.py +0 -0
  38. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/http/_transport.py +0 -0
  39. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/http/profiles.json +0 -0
  40. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/log.py +0 -0
  41. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/patch_browser_pool.py +0 -0
  42. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/proxy_configuration.py +0 -0
  43. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/py.typed +0 -0
  44. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/request_loaders/__init__.py +0 -0
  45. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/request_loaders/_scrapely_request_list.py +0 -0
  46. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/scrapy/__init__.py +0 -0
  47. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/scrapy/_actor_runner.py +0 -0
  48. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/scrapy/_async_thread.py +0 -0
  49. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/scrapy/_logging_config.py +0 -0
  50. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/scrapy/_serialization.py +0 -0
  51. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/scrapy/_warnings.py +0 -0
  52. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/scrapy/extensions/__init__.py +0 -0
  53. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/scrapy/extensions/_graceful_stop.py +0 -0
  54. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/scrapy/extensions/_httpcache.py +0 -0
  55. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/scrapy/middlewares/__init__.py +0 -0
  56. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/scrapy/middlewares/apify_proxy.py +0 -0
  57. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/scrapy/pipelines/__init__.py +0 -0
  58. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/scrapy/pipelines/actor_dataset_push.py +0 -0
  59. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/scrapy/requests.py +0 -0
  60. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/scrapy/scheduler.py +0 -0
  61. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/scrapy/utils.py +0 -0
  62. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/storage/__init__.py +0 -0
  63. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/storage/_file_system/__init__.py +0 -0
  64. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/storage/_file_system/_key_value_store_client.py +0 -0
  65. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/storage/_file_system/_storage_client.py +0 -0
  66. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/storage/_metadata.py +0 -0
  67. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/storage/api_client.py +0 -0
  68. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/storage/client.py +0 -0
  69. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/storage/patch_storage.py +0 -0
  70. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/storage/scrapely_dataset_client.py +0 -0
  71. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/storage/scrapely_kvs_client.py +0 -0
  72. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/storage/scrapely_rq_client.py +0 -0
  73. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/storage/scrapely_storage_client.py +0 -0
  74. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/storage/smart_scrapely_storage_client.py +0 -0
  75. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/storage/types.py +0 -0
  76. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/storage/utils.py +0 -0
  77. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/storage_clients/__init__.py +0 -0
  78. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/storages/__init__.py +0 -0
  79. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/types.py +0 -0
  80. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely/webhook.py +0 -0
  81. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely_python.egg-info/SOURCES.txt +0 -0
  82. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely_python.egg-info/dependency_links.txt +0 -0
  83. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely_python.egg-info/requires.txt +0 -0
  84. {scrapely_python-0.1.43 → scrapely_python-0.1.44}/src/scrapely_python.egg-info/top_level.txt +0 -0
@@ -4,6 +4,14 @@ All notable changes to this project will be documented in this file.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.1.44] - 2026-11-08
8
+
9
+ - An atomic multi-event push (`Actor.push_data(rows, charges={...})`) whose charge the limit covers only in part no longer shows "Charging 5 instances of 'audio-minute' event would exceed the end of the account balance - only 3 events were charged". A row is saved only when all of its events are charged, so the SDK gives those 3 back and nothing is charged: the line was untrue. It now says what happened: "Saving this item needs 5 'audio-minute' event(s), but the account balance covers only 3: it was not saved and nothing was charged for it." When some rows still fit, it names how many were saved and charged in full, and when giving a charge back is not confirmed it says so instead of "nothing was charged". A plain `Actor.charge()` that comes back short keeps its line: those events do stay charged.
10
+ - `ChargeResult.covered_counts` (alias `coveredCounts`, from `push_data(rows, charges={...})`): for each event whose charge came back short, how many events the limit covered (given back, not charged), e.g. `{'audio-minute': 3}`. Actors can cut a row to what the limit covers without reading the log.
11
+ - Compatibility: actors that read N from the old line with a `logging.Filter` on the `scrapely.charging` logger still receive that exact line during the push. It is shown to the logger's filters only and never printed; when such a filter drops it, the SDK leaves the refusal message to the actor, as before. What is charged and saved does not change.
12
+ - A spending limit of $0 (`max_total_charge_usd = 0`) is a real limit, the same as on the platform. It used to be read as "no limit". A missing or non-numeric value still means no limit.
13
+ - `scrapely.solver`: a challenge step's answer is read as a stream and stops at the body size limit (httpx, requests and curl_cffi sessions), so a target site cannot make the step download an unbounded body.
14
+
7
15
  ## [0.1.43] - 2026-11-05
8
16
 
9
17
  - **Python actor processes start without loading the SDK.** The base images import `scrapely.patch_browser_pool` (from `sitecustomize`) in every Python process. Until now that loaded the whole SDK at each interpreter start: `scrapely.actor`, charging, the `scrapely_client` models and Playwright. On `actor-python:3.11-0.1.42`, `python -c pass` took 0.89-0.95 s of CPU, which is 4.2 s of wall time at a 0.25-core quota. It now takes 0.016 s. Each import below gets the same start-up cut:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scrapely-python
3
- Version: 0.1.43
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
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "scrapely-python"
7
- version = "0.1.43"
7
+ version = "0.1.44"
8
8
  description = "Scrapely Python SDK - A toolkit for building Actors on the Scrapely platform"
9
9
  readme = "README.md"
10
10
  license = "MIT AND Apache-2.0"
@@ -325,7 +325,7 @@ if TYPE_CHECKING: # Static analysers and IDEs see the lazy names as plain impor
325
325
  )
326
326
  from .webhook import Webhook, WebhookEventType
327
327
 
328
- __version__ = '0.1.43'
328
+ __version__ = '0.1.44'
329
329
  __all__ = [
330
330
  # Core
331
331
  'Actor',
@@ -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
 
@@ -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):
@@ -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.43
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