scrapely-python 0.1.9__py3-none-any.whl → 0.1.11__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
@@ -132,7 +132,7 @@ from .errors import (
132
132
  raise_for_status,
133
133
  )
134
134
 
135
- __version__ = '0.1.9'
135
+ __version__ = '0.1.11'
136
136
  __all__ = [
137
137
  # Core
138
138
  'Actor',
scrapely/actor.py CHANGED
@@ -24,7 +24,12 @@ from crawlee.configuration import Configuration as CrawleeConfiguration
24
24
  from crawlee.storage_clients._base import StorageClient
25
25
  from crawlee.storages import Dataset, KeyValueStore, RequestQueue
26
26
 
27
- from .charging import ChargingManager, is_default_dataset_item_event, push_data_and_charge
27
+ from .charging import (
28
+ ChargingManager,
29
+ is_default_dataset_item_event,
30
+ push_data_and_charge,
31
+ set_active_charging_manager,
32
+ )
28
33
  from .configuration import Configuration
29
34
  from .crypto import decrypt_secret_inputs
30
35
  from .proxy_configuration import with_proxy_key_aliases
@@ -515,6 +520,7 @@ class Actor(metaclass=_ActorMeta):
515
520
  # Clear charging + patched client so a second Actor lifecycle cannot
516
521
  # post charges to the previous run_id / credentials.
517
522
  cls._charging_manager = None
523
+ set_active_charging_manager(None)
518
524
  cls._apify_client_instance = None
519
525
 
520
526
  cls._default_dataset = None
@@ -1222,6 +1228,8 @@ class Actor(metaclass=_ActorMeta):
1222
1228
  # Prefer the storage factory client (same URL/token/run as API storage).
1223
1229
  client = cls._client if cls._client is not None else cls.new_client()
1224
1230
  cls._charging_manager = ChargingManager(config, client)
1231
+ # Storage clients refuse default-dataset writes past this run's limit.
1232
+ set_active_charging_manager(cls._charging_manager)
1225
1233
  return cls._charging_manager
1226
1234
 
1227
1235
 
scrapely/charging.py CHANGED
@@ -9,7 +9,9 @@ never treated as retries of a previous operation.
9
9
  from __future__ import annotations
10
10
 
11
11
  import asyncio
12
+ import contextvars
12
13
  import json
14
+ import os
13
15
  import logging
14
16
  import time
15
17
  import uuid
@@ -63,6 +65,50 @@ _RETRY_BUDGET_SECS = 60.0
63
65
  LOCAL_CHARGING_LOG_DATASET_NAME = 'charging_log'
64
66
 
65
67
 
68
+ # Charge-limit safety net for the default dataset.
69
+ #
70
+ # Once a pay-per-event run has used up its spending limit (maxTotalChargeUsd),
71
+ # rows written to the run's default dataset would go out unbilled. The SDK then
72
+ # refuses such writes: nothing is stored, one warning is logged and
73
+ # ``ChargingManager.is_charge_limit_reached()`` turns True. Pushes made by
74
+ # ``push_data_and_charge`` (``Actor.push_data``) are decided there and marked
75
+ # with this context variable, so the storage client does not check them twice.
76
+ _charge_gated_push: contextvars.ContextVar[bool] = contextvars.ContextVar(
77
+ 'scrapely_charge_gated_push', default=False
78
+ )
79
+
80
+ # The charging manager of the running Actor (set by ``Actor``); storage clients
81
+ # consult it before writing to the default dataset.
82
+ _active_charging_manager: Optional['ChargingManager'] = None
83
+
84
+
85
+ def set_active_charging_manager(manager: Optional['ChargingManager']) -> None:
86
+ """Register the charging manager whose limit guards default-dataset writes."""
87
+ global _active_charging_manager
88
+ _active_charging_manager = manager
89
+
90
+
91
+ def default_dataset_id_from_env() -> Optional[str]:
92
+ """The run's default dataset ID, as the platform passes it."""
93
+ return os.environ.get('ACTOR_DEFAULT_DATASET_ID') or os.environ.get('APIFY_DEFAULT_DATASET_ID')
94
+
95
+
96
+ def refuse_default_dataset_push(item_count: int) -> bool:
97
+ """True when a write of ``item_count`` rows to the default dataset must be dropped.
98
+
99
+ Called by storage clients for writes that did not go through
100
+ ``push_data_and_charge`` (``Actor.open_dataset().push_data()``, crawler
101
+ ``context.push_data``, ...). Non-PPE runs and runs below their limit are
102
+ never refused.
103
+ """
104
+ if _charge_gated_push.get():
105
+ return False
106
+ manager = _active_charging_manager
107
+ if manager is None:
108
+ return False
109
+ return manager._refuse_default_dataset_push(item_count)
110
+
111
+
66
112
  def is_default_dataset_item_event(event_name: str) -> bool:
67
113
  """Check if event name is a default dataset item event."""
68
114
  return event_name in (APIFY_DEFAULT_DATASET_ITEM_EVENT, SCRAPELY_DEFAULT_DATASET_ITEM_EVENT)
@@ -209,10 +255,69 @@ class ChargingManager:
209
255
  self._last_accepted_operation_id: Optional[str] = None
210
256
  # Voids not yet confirmed by the platform; retried before the next push and at exit.
211
257
  self._pending_voids: List[tuple[str, str, int, bool]] = []
258
+ # Sticky: the platform refused or capped a charge (HTTP 402 / fewer
259
+ # events accepted) or the local budget gate trimmed one.
260
+ self._charge_limit_hit = False
261
+ # Default-dataset rows refused after the limit (one warning, then a count).
262
+ self._refused_default_dataset_items = 0
212
263
 
213
264
  def close(self) -> None:
214
265
  """Mark the manager closed; subsequent charge/push operations are rejected."""
215
266
  self._closed = True
267
+ if self._refused_default_dataset_items:
268
+ logger.warning(
269
+ '%s result(s) pushed to the default dataset after the spending limit was '
270
+ 'reached were not saved',
271
+ self._refused_default_dataset_items,
272
+ )
273
+
274
+ def is_charge_limit_reached(self) -> bool:
275
+ """Whether this pay-per-event run has used up its spending limit.
276
+
277
+ True once a charge was refused or capped by the limit (the platform's
278
+ HTTP 402 or a partial acceptance, or the local budget gate), or once the
279
+ remaining budget cannot pay for even one event of the cheapest priced
280
+ type. From then on, pushes to the default dataset that are not paid
281
+ for are refused. Always False for actors without pay-per-event
282
+ pricing, without a limit, or with only free events.
283
+ """
284
+ if self._pricing_info is None:
285
+ return False
286
+ if self._charge_limit_hit:
287
+ return True
288
+ if self._max_total_charge_usd is None:
289
+ return False
290
+ prices = [price for price in self._per_event_prices.values() if price > 0]
291
+ if not prices:
292
+ return False
293
+ return self._max_total_charge_usd - self._total_charged_usd < min(prices)
294
+
295
+ def _mark_charge_limit_hit(self) -> None:
296
+ if self._pricing_info is not None:
297
+ self._charge_limit_hit = True
298
+
299
+ def _note_refused_default_dataset_items(self, count: int) -> None:
300
+ """Count rows dropped because of the limit; warn on the first one only."""
301
+ if count <= 0:
302
+ return
303
+ if not self._refused_default_dataset_items:
304
+ limit = (
305
+ f'${self._max_total_charge_usd}' if self._max_total_charge_usd is not None else 'the limit'
306
+ )
307
+ logger.warning(
308
+ 'The spending limit of this run (maxTotalChargeUsd = %s) has been reached: '
309
+ 'results pushed to the default dataset are no longer saved. The Actor should '
310
+ 'stop now (check ChargeResult.event_charge_limit_reached or '
311
+ 'Actor.get_charging_manager().is_charge_limit_reached()).',
312
+ limit,
313
+ )
314
+ self._refused_default_dataset_items += count
315
+
316
+ def _refuse_default_dataset_push(self, item_count: int) -> bool:
317
+ if item_count <= 0 or not self.is_charge_limit_reached():
318
+ return False
319
+ self._note_refused_default_dataset_items(item_count)
320
+ return True
216
321
 
217
322
  @property
218
323
  def charge_lock(self) -> RLock:
@@ -688,6 +793,8 @@ class ChargingManager:
688
793
  deadline=deadline,
689
794
  )
690
795
  except ChargeRejectedError as err:
796
+ if _is_charge_limit_rejection(err):
797
+ self._mark_charge_limit_hit()
691
798
  self._unwind_reservation(event_name, count)
692
799
  self._drop_pending(idempotency_key)
693
800
  logger.warning(
@@ -699,6 +806,7 @@ class ChargingManager:
699
806
  continue
700
807
  if accepted is not None:
701
808
  if accepted < count:
809
+ self._mark_charge_limit_hit()
702
810
  self._unwind_reservation(event_name, count - accepted)
703
811
  self._drop_pending(idempotency_key)
704
812
  confirmed += 1
@@ -784,6 +892,9 @@ class ChargingManager:
784
892
  else 0
785
893
  )
786
894
 
895
+ if chargeable_count < count:
896
+ self._mark_charge_limit_hit()
897
+
787
898
  if chargeable_count <= 0:
788
899
  return ChargeResult(
789
900
  chargeable_within_limit=self._compute_chargeable(),
@@ -835,7 +946,9 @@ class ChargingManager:
835
946
  count=chargeable_count,
836
947
  idempotency_key=idempotency_key,
837
948
  )
838
- except ChargeRejectedError:
949
+ except ChargeRejectedError as rejected:
950
+ if _is_charge_limit_rejection(rejected):
951
+ self._mark_charge_limit_hit()
839
952
  # Server definitively rejected: unwind local reservation.
840
953
  self._drop_pending(idempotency_key)
841
954
  self._unwind_reservation(event_name, chargeable_count)
@@ -849,6 +962,8 @@ class ChargingManager:
849
962
  if accepted > 0:
850
963
  self._last_accepted_operation_id = idempotency_key
851
964
  if accepted < chargeable_count:
965
+ # The platform capped the charge at the run's limit.
966
+ self._mark_charge_limit_hit()
852
967
  self._unwind_reservation(event_name, chargeable_count - accepted)
853
968
  chargeable_count = accepted
854
969
  result = ChargeResult(
@@ -1066,6 +1181,15 @@ class ChargingManager:
1066
1181
 
1067
1182
 
1068
1183
 
1184
+ def _is_charge_limit_rejection(err: ChargeRejectedError) -> bool:
1185
+ """Whether a rejected charge was refused because the run's limit is used up."""
1186
+ return (
1187
+ err.status_code == 402
1188
+ or err.reason == 'charge-limit-exceeded'
1189
+ or 'charge-limit-exceeded' in str(err).lower()
1190
+ )
1191
+
1192
+
1069
1193
  def _read_accepted_count(body: Any, fallback: int) -> int:
1070
1194
  if not isinstance(body, dict):
1071
1195
  return fallback
@@ -1166,6 +1290,24 @@ async def push_data_and_charge(
1166
1290
  if fallback_event:
1167
1291
  resolved_event = fallback_event
1168
1292
 
1293
+ # Charge-limit safety net: once the run's spending limit is used up, a
1294
+ # default-dataset push that does not pay per row (no event, or only
1295
+ # free events) stores nothing. Paid pushes go on below, where the
1296
+ # budget cap stores only the rows that are actually charged.
1297
+ if (
1298
+ is_ppe
1299
+ and is_default_dataset
1300
+ and items
1301
+ and charging_manager.is_charge_limit_reached()
1302
+ and not _push_is_paid_per_item(charging_manager, event_name, resolved_event)
1303
+ ):
1304
+ charging_manager._note_refused_default_dataset_items(len(items))
1305
+ return ChargeResult(
1306
+ chargeable_within_limit=charging_manager.compute_chargeable(),
1307
+ charged_count=0,
1308
+ event_charge_limit_reached=True,
1309
+ )
1310
+
1169
1311
  limited_count = len(items)
1170
1312
  if is_ppe and resolved_event:
1171
1313
  # Keep the explicit event separate from the implicit default-dataset
@@ -1177,6 +1319,10 @@ async def push_data_and_charge(
1177
1319
  )
1178
1320
 
1179
1321
  limited_items = items[:limited_count] if limited_count < len(items) else items
1322
+ if is_ppe and is_default_dataset and limited_count < len(items):
1323
+ # Rows beyond what the budget can pay for are dropped.
1324
+ charging_manager._mark_charge_limit_hit()
1325
+ charging_manager._note_refused_default_dataset_items(len(items) - limited_count)
1180
1326
 
1181
1327
  if not limited_items:
1182
1328
  return ChargeResult(
@@ -1302,9 +1448,13 @@ async def push_data_and_charge(
1302
1448
  await charging_manager._cancel_uncertain_charge(name, op_id, reserved)
1303
1449
  else:
1304
1450
  await charging_manager._void_charge(name, op_id, reserved)
1451
+ if is_default_dataset and accepted_for_items < len(limited_items):
1452
+ charging_manager._note_refused_default_dataset_items(
1453
+ len(limited_items) - accepted_for_items
1454
+ )
1305
1455
  if accepted_for_items > 0:
1306
1456
  try:
1307
- await push_fn(limited_items[:accepted_for_items])
1457
+ await _gated_push(push_fn, limited_items[:accepted_for_items])
1308
1458
  except Exception as push_err:
1309
1459
  # A result is billed only if it was saved: void this
1310
1460
  # operation's platform charges and unwind local
@@ -1333,7 +1483,9 @@ async def push_data_and_charge(
1333
1483
  raise
1334
1484
  return ChargeResult(
1335
1485
  chargeable_within_limit=charging_manager.compute_chargeable(),
1336
- charged_count=accepted_for_items * len(results) if results else 0,
1486
+ # Rows charged, as Apify reports it for the pushed event; the
1487
+ # implicit default-dataset event is not counted on top.
1488
+ charged_count=accepted_for_items,
1337
1489
  event_charge_limit_reached=any(
1338
1490
  result.event_charge_limit_reached for result in results
1339
1491
  )
@@ -1342,7 +1494,7 @@ async def push_data_and_charge(
1342
1494
 
1343
1495
 
1344
1496
  # No billable events — still persist the budget-limited items.
1345
- await push_fn(limited_items)
1497
+ await _gated_push(push_fn, limited_items)
1346
1498
  return ChargeResult(
1347
1499
  chargeable_within_limit=charging_manager.compute_chargeable(),
1348
1500
  charged_count=0,
@@ -1350,6 +1502,23 @@ async def push_data_and_charge(
1350
1502
  )
1351
1503
 
1352
1504
 
1505
+ def _push_is_paid_per_item(
1506
+ charging_manager: ChargingManager, event_name: Optional[str], resolved_event: Optional[str]
1507
+ ) -> bool:
1508
+ """Whether every row of this push is charged a positive price."""
1509
+ names = {name for name in (event_name, resolved_event) if name}
1510
+ return any((charging_manager._calculate_event_price(name) or Decimal('0')) > 0 for name in names)
1511
+
1512
+
1513
+ async def _gated_push(push_fn: Any, items: List[Dict[str, Any]]) -> Any:
1514
+ """Run a push already decided by push_data_and_charge (storage skips its own check)."""
1515
+ token = _charge_gated_push.set(True)
1516
+ try:
1517
+ return await push_fn(items)
1518
+ finally:
1519
+ _charge_gated_push.reset(token)
1520
+
1521
+
1353
1522
  def _http_status_of(err: BaseException) -> Optional[int]:
1354
1523
  status = getattr(err, 'status_code', None)
1355
1524
  if status is None:
@@ -43,7 +43,11 @@ class _ChargingManagerHooks:
43
43
  from .charging import has_default_dataset_item_event_in_pricing
44
44
 
45
45
  pricing_info = self._charging_manager.get_pricing_info()
46
- return has_default_dataset_item_event_in_pricing(pricing_info.per_event_prices or {})
46
+ # Past the spending limit, route default-dataset pushes through
47
+ # push_data_and_charge too, which refuses rows nobody pays for.
48
+ return has_default_dataset_item_event_in_pricing(
49
+ pricing_info.per_event_prices or {}
50
+ ) or bool(getattr(self._charging_manager, 'is_charge_limit_reached', lambda: False)())
47
51
 
48
52
  async def push_and_charge(
49
53
  self,
@@ -99,6 +99,12 @@ class ScrapelyDatasetClient(DatasetClient):
99
99
  items = [data]
100
100
  else:
101
101
  items = list(data)
102
+ # Charge-limit safety net: a pay-per-event run past its spending limit
103
+ # must not store unbilled rows in its default dataset.
104
+ from ..charging import default_dataset_id_from_env, refuse_default_dataset_push
105
+
106
+ if self._metadata.id == default_dataset_id_from_env() and refuse_default_dataset_push(len(items)):
107
+ return
102
108
  await self._api.dataset_push_items(self._metadata.id, items)
103
109
 
104
110
  @override
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scrapely-python
3
- Version: 0.1.9
3
+ Version: 0.1.11
4
4
  Summary: Scrapely Python SDK - A toolkit for building Actors on the Scrapely platform
5
5
  Author-email: Scrapely <support@scrape.ly>
6
6
  License-Expression: MIT AND Apache-2.0
@@ -1,10 +1,10 @@
1
- scrapely/__init__.py,sha256=3LP91mpUIJywB0w8vwL1kKhrMnuYE3eHZP_Bj9QjylI,5745
1
+ scrapely/__init__.py,sha256=RxtELQHc6mWoQhDgFu_EK_jFjuPOMlKEcDEZizk1vxQ,5746
2
2
  scrapely/_browser_locations.py,sha256=8QVVnkms2bDn3_LDYgYDR59MvFx8757l_JYnZ7xb3oI,145269
3
- scrapely/actor.py,sha256=cQl9RM1MUZWWR8uNF7q6Pjd8vpB1MCoDp6KM5ITJq5I,77479
3
+ scrapely/actor.py,sha256=2nWeaEIo11-XO0w3QAzA1lbn4Gm1MvjStsiNdOvk_tc,77721
4
4
  scrapely/browser_configuration.py,sha256=jAZapNSHLFW05B96df4wNBtcyiiU9DA3ml0yTL1FwfA,5770
5
5
  scrapely/cdp_retry.py,sha256=hdTJEAIKhApM7IOk1DrQEl8NoflSJSmqd4RbNJ2IsgI,8540
6
- scrapely/charging.py,sha256=bwJ6VPJOdxpo0ZHOTrMAe8NCTXeRBuxHN0EDyXbGXss,59138
7
- scrapely/charging_client.py,sha256=tDtlPwLSVFvoRa2NBgNjyfHkAUM77SSIyYT2ACgpDm8,3710
6
+ scrapely/charging.py,sha256=41KG60D-YM9oi-1qbSKRfZbw92pFWi1yvvc2c2L6V5k,66862
7
+ scrapely/charging_client.py,sha256=-4q-Ww7gu9EZXpM9QIn1Vd4vwAXmgL_WEKqaQIx3ViA,3961
8
8
  scrapely/configuration.py,sha256=GjMr3YsxM16HYjAOTUzWZKG2E8FuMzAoFXmkn5dbDPM,16396
9
9
  scrapely/errors.py,sha256=DCAlVvE3jToZuPEG2HVDL7i8D8hLboomQ5JpSOcsXoQ,4107
10
10
  scrapely/log.py,sha256=iVKoQdMLQXEWz1STzbSXrNUxsS_FNwiIdqoEg7CzeqU,1440
@@ -26,7 +26,7 @@ scrapely/storage/_metadata.py,sha256=WWawBnVN0b1iK2K-SlxZXUc6czb5wXWf8iC_0tzkgAQ
26
26
  scrapely/storage/api_client.py,sha256=jqfBOOHo97DeTzJQlh0bBTn0EjjK184VtnxFIs20rbg,16649
27
27
  scrapely/storage/client.py,sha256=Ln_NA8nJz62nXldkcj54PFZopX5P3Lp8HGot_8friNM,22015
28
28
  scrapely/storage/patch_storage.py,sha256=o3Fv0BByeZ1T9HhkzhY6bjolOFsIQcnqBoHq1EdG8Fw,8758
29
- scrapely/storage/scrapely_dataset_client.py,sha256=gRvlCDw9c0yO5GE5LQOa1xAyXc9pnb-E37Eq7fHqHCM,10338
29
+ scrapely/storage/scrapely_dataset_client.py,sha256=u5dnXxe1BAsq7rh-haR5W1ChE7UZ_k7B9ShR8YtwFkg,10695
30
30
  scrapely/storage/scrapely_kvs_client.py,sha256=ItQhe2rcSl20NkSmegfqHiRyKncH4Qg9BjQVpF6jHfk,7403
31
31
  scrapely/storage/scrapely_rq_client.py,sha256=gA4nMDuWyrh6QfbnMv1y7ZgcwFGWIPXGE5Y4OsWA1qI,18920
32
32
  scrapely/storage/scrapely_storage_client.py,sha256=N-p2ISICuKQ8RNzmN-JiXcj_lTttULLOGl9lpLl62qI,6567
@@ -38,10 +38,10 @@ scrapely/storage/_file_system/_key_value_store_client.py,sha256=4Ipgbh4qEqAkwQJ9
38
38
  scrapely/storage/_file_system/_storage_client.py,sha256=aaGJ4P0QAtIgEMl6yHpuobeWFD5M4rMC5HwhOOvuGuo,1794
39
39
  scrapely/storage_clients/__init__.py,sha256=cs1YX7JV2_GKBXeiiJgkQFali08b5_y_jH6Yw7iROAA,656
40
40
  scrapely/storages/__init__.py,sha256=4PAELhJNZ3exJ7Uouicn-bCQ58NafKjhLBixQ8ATQc4,173
41
- scrapely_python-0.1.9.dist-info/licenses/LICENSE,sha256=pQGY0XwjIYh-a2HfawxHq1en53bXkFkDj2Q70jKWHr4,1088
42
- scrapely_python-0.1.9.dist-info/licenses/LICENSE-APACHE,sha256=N8m0FzMq8i4UbTgXZvKEZJSD-27OF8pWZYS_atz4kTU,11355
43
- scrapely_python-0.1.9.dist-info/licenses/NOTICE,sha256=DEsNrw6UdSIqdYYqMWVFgJnyt6jUivTD7iFU6YM_e1A,1122
44
- scrapely_python-0.1.9.dist-info/METADATA,sha256=E_rdzHW3bC3asqFegdYfxL27jTuGhIm1uXvVpGFm_-o,3486
45
- scrapely_python-0.1.9.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
46
- scrapely_python-0.1.9.dist-info/top_level.txt,sha256=T4B9UMrs4q99QSAFyD1zdXhl40KnLhBKqrDkPhOTsmY,9
47
- scrapely_python-0.1.9.dist-info/RECORD,,
41
+ scrapely_python-0.1.11.dist-info/licenses/LICENSE,sha256=pQGY0XwjIYh-a2HfawxHq1en53bXkFkDj2Q70jKWHr4,1088
42
+ scrapely_python-0.1.11.dist-info/licenses/LICENSE-APACHE,sha256=N8m0FzMq8i4UbTgXZvKEZJSD-27OF8pWZYS_atz4kTU,11355
43
+ scrapely_python-0.1.11.dist-info/licenses/NOTICE,sha256=DEsNrw6UdSIqdYYqMWVFgJnyt6jUivTD7iFU6YM_e1A,1122
44
+ scrapely_python-0.1.11.dist-info/METADATA,sha256=TjBOSZzW9n2wrL0IQQQ6Qxp-T_SCsjPsOAP1I_lCTEc,3487
45
+ scrapely_python-0.1.11.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
46
+ scrapely_python-0.1.11.dist-info/top_level.txt,sha256=T4B9UMrs4q99QSAFyD1zdXhl40KnLhBKqrDkPhOTsmY,9
47
+ scrapely_python-0.1.11.dist-info/RECORD,,