scrapely-python 0.1.2__tar.gz → 0.1.3__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 (58) hide show
  1. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/PKG-INFO +1 -1
  2. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/pyproject.toml +1 -1
  3. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/__init__.py +1 -1
  4. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/actor.py +5 -5
  5. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/charging.py +132 -1
  6. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/proxy_configuration.py +9 -3
  7. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely_python.egg-info/PKG-INFO +1 -1
  8. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/tests/test_charging_pending.py +202 -0
  9. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/tests/test_proxy_configuration.py +42 -0
  10. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/README.md +0 -0
  11. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/setup.cfg +0 -0
  12. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/_browser_locations.py +0 -0
  13. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/browser_configuration.py +0 -0
  14. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/charging_client.py +0 -0
  15. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/configuration.py +0 -0
  16. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/crypto/__init__.py +0 -0
  17. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/crypto/_secrets.py +0 -0
  18. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/errors.py +0 -0
  19. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/events/__init__.py +0 -0
  20. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/events/_types.py +0 -0
  21. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/events/event_manager.py +0 -0
  22. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/log.py +0 -0
  23. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/patch_browser_pool.py +0 -0
  24. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/pricing_types.py +0 -0
  25. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/py.typed +0 -0
  26. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/request_loaders/__init__.py +0 -0
  27. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/request_loaders/_scrapely_request_list.py +0 -0
  28. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/storage/__init__.py +0 -0
  29. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/storage/_file_system/__init__.py +0 -0
  30. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/storage/_file_system/_key_value_store_client.py +0 -0
  31. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/storage/_file_system/_storage_client.py +0 -0
  32. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/storage/_metadata.py +0 -0
  33. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/storage/api_client.py +0 -0
  34. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/storage/client.py +0 -0
  35. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/storage/patch_storage.py +0 -0
  36. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/storage/scrapely_dataset_client.py +0 -0
  37. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/storage/scrapely_kvs_client.py +0 -0
  38. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/storage/scrapely_rq_client.py +0 -0
  39. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/storage/scrapely_storage_client.py +0 -0
  40. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/storage/smart_scrapely_storage_client.py +0 -0
  41. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/storage/types.py +0 -0
  42. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/storage/utils.py +0 -0
  43. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/storage_clients/__init__.py +0 -0
  44. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/storages/__init__.py +0 -0
  45. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/types.py +0 -0
  46. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely/webhook.py +0 -0
  47. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely_python.egg-info/SOURCES.txt +0 -0
  48. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely_python.egg-info/dependency_links.txt +0 -0
  49. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely_python.egg-info/requires.txt +0 -0
  50. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/src/scrapely_python.egg-info/top_level.txt +0 -0
  51. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/tests/test_apify_parity.py +0 -0
  52. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/tests/test_browser_configuration.py +0 -0
  53. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/tests/test_charging_parity.py +0 -0
  54. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/tests/test_parity.py +0 -0
  55. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/tests/test_patch_browser_pool.py +0 -0
  56. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/tests/test_run_control.py +0 -0
  57. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/tests/test_secrets.py +0 -0
  58. {scrapely_python-0.1.2 → scrapely_python-0.1.3}/tests/test_storage.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scrapely-python
3
- Version: 0.1.2
3
+ Version: 0.1.3
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
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "scrapely-python"
7
- version = "0.1.2"
7
+ version = "0.1.3"
8
8
  description = "Scrapely Python SDK - A toolkit for building Actors on the Scrapely platform"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -132,7 +132,7 @@ from .errors import (
132
132
  raise_for_status,
133
133
  )
134
134
 
135
- __version__ = '0.1.2'
135
+ __version__ = '0.1.3'
136
136
  __all__ = [
137
137
  # Core
138
138
  'Actor',
@@ -1776,7 +1776,7 @@ class Actor(metaclass=_ActorMeta):
1776
1776
  """
1777
1777
  cls._ensure_initialized('create_proxy_configuration')
1778
1778
 
1779
- from .proxy_configuration import ProxyConfiguration, _input_use_platform_proxy
1779
+ from .proxy_configuration import ProxyConfiguration, _input_proxy_option, _input_use_platform_proxy
1780
1780
 
1781
1781
  # Handle actor_proxy_input (Node SDK normalizeProxyInput/createProxyConfiguration
1782
1782
  # parity): `useScrapelyProxy: false` (or the legacy `useApifyProxy: false`; a
@@ -1787,7 +1787,7 @@ class Actor(metaclass=_ActorMeta):
1787
1787
  # silently drop the user's own proxies and crawl on their real IPs. We only
1788
1788
  # bail when no custom proxies are given either. A MISSING key falls back to
1789
1789
  # platform mode when the server injected credentials — input like
1790
- # {apifyProxyGroups: [...]} must not silently disable proxying.
1790
+ # {scrapelyProxyGroups: [...]} must not silently disable proxying.
1791
1791
  if actor_proxy_input is not None:
1792
1792
  if _input_use_platform_proxy(actor_proxy_input) is False and not (
1793
1793
  proxy_urls
@@ -1799,9 +1799,9 @@ class Actor(metaclass=_ActorMeta):
1799
1799
  or actor_proxy_input.get('tieredProxyConfig')
1800
1800
  ):
1801
1801
  return None
1802
- country_code = country_code or actor_proxy_input.get('apifyProxyCountry')
1803
- subdivision_code = subdivision_code or actor_proxy_input.get('apifyProxySubdivision')
1804
- groups = groups or actor_proxy_input.get('apifyProxyGroups')
1802
+ country_code = country_code or _input_proxy_option(actor_proxy_input, 'Country')
1803
+ subdivision_code = subdivision_code or _input_proxy_option(actor_proxy_input, 'Subdivision')
1804
+ groups = groups or _input_proxy_option(actor_proxy_input, 'Groups')
1805
1805
  proxy_urls = proxy_urls or actor_proxy_input.get('proxyUrls')
1806
1806
  tiered_proxy_urls = tiered_proxy_urls or actor_proxy_input.get('tieredProxyUrls')
1807
1807
  tiered_proxy_config = tiered_proxy_config or actor_proxy_input.get('tieredProxyConfig')
@@ -195,6 +195,11 @@ class ChargingManager:
195
195
  self._pending_charge_keys: Dict[str, Dict[str, Any]] = {}
196
196
  # Optional local charging-log dataset (ACTOR_USE_CHARGING_LOG_DATASET).
197
197
  self._charging_log_dataset: Any = None
198
+ # Idempotency key of the last charge the platform accepted
199
+ # (push_data_and_charge voids it when the push then fails).
200
+ self._last_accepted_operation_id: Optional[str] = None
201
+ # Voids not yet confirmed by the platform; retried before the next push and at exit.
202
+ self._pending_voids: List[tuple[str, str, int]] = []
198
203
 
199
204
  def close(self) -> None:
200
205
  """Mark the manager closed; subsequent charge/push operations are rejected."""
@@ -429,6 +434,50 @@ class ChargingManager:
429
434
  self._total_charged_usd - event_price * Decimal(count),
430
435
  )
431
436
 
437
+ def _take_last_accepted_operation_id(self) -> Optional[str]:
438
+ op_id = self._last_accepted_operation_id
439
+ self._last_accepted_operation_id = None
440
+ return op_id
441
+
442
+ async def _void_charge(self, event_name: str, operation_id: str, reserved: int) -> bool:
443
+ """Reverse an accepted charge whose items were never stored, then unwind locally.
444
+
445
+ POST /v2/actor-runs/{run}/charge/void with the charge's Idempotency-Key.
446
+ The local reservation is released only once the platform confirms.
447
+ """
448
+ if self._client is None or not self._is_at_home or not self._actor_run_id:
449
+ return False
450
+ for attempt in range(self._POST_ATTEMPTS):
451
+ try:
452
+ await self._client.post(
453
+ f'/v2/actor-runs/{self._actor_run_id}/charge/void',
454
+ json_data={},
455
+ headers={'Idempotency-Key': operation_id},
456
+ )
457
+ self._unwind_reservation(event_name, reserved)
458
+ return True
459
+ except Exception as err: # noqa: BLE001
460
+ status = _http_status_of(err)
461
+ # 404: nothing to void; 409: already settled; 4xx auth: permanent.
462
+ if status is not None and 400 <= status < 500:
463
+ return False
464
+ if attempt + 1 < self._POST_ATTEMPTS:
465
+ await asyncio.sleep(0.25 * (attempt + 1))
466
+ # Outcome unknown: keep the reservation and retry before the next push / at exit.
467
+ self._pending_voids.append((event_name, operation_id, reserved))
468
+ logger.error('Void of charge %s (%r) not confirmed yet; will retry', operation_id, event_name)
469
+ return False
470
+
471
+ async def _retry_pending_voids(self) -> bool:
472
+ """Retry unconfirmed voids (caller holds the operation lock).
473
+
474
+ Returns False while any earlier void is still unconfirmed.
475
+ """
476
+ pending, self._pending_voids = self._pending_voids, []
477
+ for event_name, operation_id, reserved in pending:
478
+ await self._void_charge(event_name, operation_id, reserved)
479
+ return not self._pending_voids
480
+
432
481
  def _quarantine_stale_pending(self) -> None:
433
482
  """Remove intents older than the safe replay window (fail closed, no replay).
434
483
 
@@ -544,6 +593,7 @@ class ChargingManager:
544
593
  """Caller must hold _operation_lock."""
545
594
  if not self._is_at_home or self._client is None or not self._actor_run_id:
546
595
  return 0
596
+ await self._retry_pending_voids()
547
597
 
548
598
  import time
549
599
 
@@ -731,6 +781,8 @@ class ChargingManager:
731
781
  )
732
782
  if accepted is not None:
733
783
  self._drop_pending(idempotency_key)
784
+ if accepted > 0:
785
+ self._last_accepted_operation_id = idempotency_key
734
786
  if accepted < chargeable_count:
735
787
  self._unwind_reservation(event_name, chargeable_count - accepted)
736
788
  chargeable_count = accepted
@@ -1032,6 +1084,9 @@ async def push_data_and_charge(
1032
1084
  async with charging_manager._operation_lock:
1033
1085
  if charging_manager._closed:
1034
1086
  raise RuntimeError('ChargingManager is closed (actor is shutting down); charge rejected')
1087
+ # A void that did not go through for an earlier failed push must land
1088
+ # before this push charges again, or one unsaved result is billed twice.
1089
+ voids_confirmed = await charging_manager._retry_pending_voids()
1035
1090
  # Non-PPE actors push everything without charging (JS calculatePushDataLimits
1036
1091
  # parity: `if (!this.isPayPerEvent) return { limitedItems, eventsToCharge: {} }`).
1037
1092
  is_ppe = charging_manager._pricing_info is not None
@@ -1065,6 +1120,29 @@ async def push_data_and_charge(
1065
1120
  event_charge_limit_reached=len(items) > 0 and limited_count == 0,
1066
1121
  )
1067
1122
 
1123
+ # Every platform event this push would charge counts: the explicit event
1124
+ # and, on a default-dataset push, the configured default event. The
1125
+ # synthetic default-dataset event (local bookkeeping) and unpriced
1126
+ # events (never posted) do not.
1127
+ charged_names: List[str] = []
1128
+ if event_name:
1129
+ charged_names.append(event_name)
1130
+ if is_default_dataset:
1131
+ configured_default = charging_manager._config.get('default_dataset_item_event_name')
1132
+ if configured_default:
1133
+ charged_names.append(configured_default)
1134
+ if (
1135
+ not voids_confirmed
1136
+ and is_ppe
1137
+ and any(
1138
+ not is_default_dataset_item_event(name) and name in charging_manager._per_event_prices
1139
+ for name in charged_names
1140
+ )
1141
+ ):
1142
+ raise RuntimeError(
1143
+ 'An earlier charge for a failed dataset push could not be voided yet; retry the push'
1144
+ )
1145
+
1068
1146
  # Charge BEFORE persisting so a server cap/reject cannot leave unbilled
1069
1147
  # items in the dataset. Operation lock is held across both steps.
1070
1148
  if is_ppe and resolved_event:
@@ -1079,15 +1157,20 @@ async def push_data_and_charge(
1079
1157
 
1080
1158
  # Synthetic storage event first (local-only); then explicit billable event.
1081
1159
  reserved_in_op: list[tuple[str, int]] = []
1160
+ operation_ids: list[Optional[str]] = []
1082
1161
  try:
1083
1162
  if default_event:
1163
+ charging_manager._take_last_accepted_operation_id()
1084
1164
  r = await charging_manager._charge_exclusive(default_event, len(limited_items))
1085
1165
  results.append(r)
1086
1166
  reserved_in_op.append((default_event, r.charged_count))
1167
+ operation_ids.append(charging_manager._take_last_accepted_operation_id())
1087
1168
  if event_name and event_name != default_event:
1169
+ charging_manager._take_last_accepted_operation_id()
1088
1170
  r = await charging_manager._charge_exclusive(event_name, len(limited_items))
1089
1171
  results.append(r)
1090
1172
  reserved_in_op.append((event_name, r.charged_count))
1173
+ operation_ids.append(charging_manager._take_last_accepted_operation_id())
1091
1174
  except Exception:
1092
1175
  for name, reserved in reserved_in_op:
1093
1176
  if reserved > 0:
@@ -1118,11 +1201,27 @@ async def push_data_and_charge(
1118
1201
  try:
1119
1202
  await push_fn(limited_items[:accepted_for_items])
1120
1203
  except Exception as push_err:
1204
+ # A result is billed only if it was saved: void this
1205
+ # operation's platform charges and unwind local
1206
+ # reservations, then let the caller retry the push.
1121
1207
  logger.error(
1122
- 'Dataset push failed after charge accepted (items=%s): %s',
1208
+ 'Dataset push failed after charge accepted (items=%s): %s; voiding the charge',
1123
1209
  accepted_for_items,
1124
1210
  push_err,
1125
1211
  )
1212
+ # Only when the push certainly stored nothing (the storage API
1213
+ # answered with an error, or the request was never sent). A
1214
+ # timeout after sending may have stored the items.
1215
+ if not _push_certainly_failed(push_err):
1216
+ raise
1217
+ for (name, _), op_id in zip(reserved_in_op, operation_ids):
1218
+ kept = min(accepted_for_items, next(r.charged_count for n, r in charged_events if n == name))
1219
+ if kept <= 0:
1220
+ continue
1221
+ if op_id:
1222
+ await charging_manager._void_charge(name, op_id, kept)
1223
+ elif is_default_dataset_item_event(name):
1224
+ charging_manager._unwind_reservation(name, kept)
1126
1225
  raise
1127
1226
  return ChargeResult(
1128
1227
  chargeable_within_limit=charging_manager.compute_chargeable(),
@@ -1141,3 +1240,35 @@ async def push_data_and_charge(
1141
1240
  charged_count=0,
1142
1241
  event_charge_limit_reached=False,
1143
1242
  )
1243
+
1244
+
1245
+ def _http_status_of(err: BaseException) -> Optional[int]:
1246
+ status = getattr(err, 'status_code', None)
1247
+ if status is None:
1248
+ response = getattr(err, 'response', None)
1249
+ status = getattr(response, 'status_code', None) if response is not None else None
1250
+ try:
1251
+ return int(status) if status is not None else None
1252
+ except (TypeError, ValueError):
1253
+ return None
1254
+
1255
+
1256
+ def _push_certainly_failed(err: BaseException) -> bool:
1257
+ """True when a dataset push certainly stored nothing.
1258
+
1259
+ The storage API answered with an error status, or the connection was never
1260
+ made. Timeouts and resets after sending are not proof: the write may have landed.
1261
+ """
1262
+ import httpx
1263
+
1264
+ e: Optional[BaseException] = err
1265
+ for _ in range(4):
1266
+ if e is None:
1267
+ break
1268
+ status = _http_status_of(e)
1269
+ if status is not None:
1270
+ return status >= 400
1271
+ if isinstance(e, (httpx.ConnectError, ConnectionRefusedError)):
1272
+ return True
1273
+ e = e.__cause__ or e.__context__
1274
+ return False
@@ -121,6 +121,12 @@ def _input_use_platform_proxy(actor_proxy_input: Dict[str, Any]) -> Optional[boo
121
121
  return None
122
122
 
123
123
 
124
+ def _input_proxy_option(actor_proxy_input: Dict[str, Any], name: str) -> Any:
125
+ """`scrapelyProxy<name>` of the proxy input field when it is set, else the legacy `apifyProxy<name>`."""
126
+ value = actor_proxy_input.get(f'scrapelyProxy{name}')
127
+ return value if value is not None else actor_proxy_input.get(f'apifyProxy{name}')
128
+
129
+
124
130
  def _platform_env() -> Optional[Dict[str, Any]]:
125
131
  """Read platform proxy credentials from the environment (or None)."""
126
132
  hostname = os.environ.get('SCRAPELY_PROXY_HOSTNAME') or os.environ.get('APIFY_PROXY_HOSTNAME')
@@ -227,9 +233,9 @@ class ProxyConfiguration:
227
233
  # If actor_proxy_input is provided, extract settings from it
228
234
  if actor_proxy_input:
229
235
  if _input_use_platform_proxy(actor_proxy_input):
230
- self._groups = actor_proxy_input.get('apifyProxyGroups', []) or []
231
- self._country_code = actor_proxy_input.get('apifyProxyCountry')
232
- self._subdivision_code = actor_proxy_input.get('apifyProxySubdivision')
236
+ self._groups = _input_proxy_option(actor_proxy_input, 'Groups') or []
237
+ self._country_code = _input_proxy_option(actor_proxy_input, 'Country')
238
+ self._subdivision_code = _input_proxy_option(actor_proxy_input, 'Subdivision')
233
239
  else:
234
240
  self._proxy_urls = actor_proxy_input.get('proxyUrls', []) or []
235
241
  # Tiered lists may also arrive through actor input (future-proof
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scrapely-python
3
- Version: 0.1.2
3
+ Version: 0.1.3
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
@@ -457,3 +457,205 @@ async def test_dual_event_push_unwinds_synthetic_on_partial_explicit() -> None:
457
457
  assert len(pushed) == 1
458
458
  assert mgr.get_charged_event_count('page-open') == 1
459
459
  assert mgr.get_charged_event_count('apify-default-dataset-item') == 1
460
+
461
+
462
+ @pytest.mark.asyncio
463
+ async def test_push_failure_after_charge_voids_the_charge() -> None:
464
+ """A result is billed only if it was saved: a failed push voids its charge."""
465
+ client = FakeClient()
466
+ mgr = _make_manager(client)
467
+
468
+ class PushHttpError(Exception):
469
+ status_code = 503
470
+
471
+ async def failing_push(_items: Any) -> None:
472
+ raise PushHttpError('503 from dataset push')
473
+
474
+ with pytest.raises(PushHttpError, match='503'):
475
+ await push_data_and_charge(mgr, [{'a': 1}, {'a': 2}], 'page-open', False, failing_push)
476
+
477
+ charge_posts = [p for p in client.posts if p['path'].endswith('/charge')]
478
+ void_posts = [p for p in client.posts if p['path'].endswith('/charge/void')]
479
+ assert len(charge_posts) == 1
480
+ assert len(void_posts) == 1
481
+ assert void_posts[0]['path'] == '/v2/actor-runs/run-test-1/charge/void'
482
+ assert void_posts[0]['headers']['Idempotency-Key'] == charge_posts[0]['headers']['Idempotency-Key']
483
+ assert mgr.get_charged_event_count('page-open') == 0
484
+
485
+ pushed: List[Any] = []
486
+
487
+ async def ok_push(items: Any) -> None:
488
+ pushed.extend(items)
489
+
490
+ await push_data_and_charge(mgr, [{'a': 3}], 'page-open', False, ok_push)
491
+ assert len([p for p in client.posts if p['path'].endswith('/charge/void')]) == 1
492
+ assert mgr.get_charged_event_count('page-open') == 1
493
+ assert pushed == [{'a': 3}]
494
+
495
+
496
+
497
+ class VoidFlakyClient(FakeClient):
498
+ def __init__(self, void_failures: int = 0) -> None:
499
+ super().__init__()
500
+ self.void_failures = void_failures
501
+
502
+ async def post(self, path: str, json_data: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, **kwargs: Any) -> Dict[str, Any]:
503
+ if path.endswith('/charge/void') and self.void_failures > 0:
504
+ self.void_failures -= 1
505
+ self.posts.append({'path': path + '#failed', 'json': json_data, 'headers': headers or {}})
506
+ raise TimeoutError('void timed out')
507
+ return await super().post(path, json_data=json_data, headers=headers, **kwargs)
508
+
509
+
510
+ @pytest.mark.asyncio
511
+ async def test_push_timeout_after_send_keeps_the_charge() -> None:
512
+ client = FakeClient()
513
+ mgr = _make_manager(client)
514
+
515
+ async def reset_push(_items: Any) -> None:
516
+ raise TimeoutError('read timed out') # may have been stored
517
+
518
+ with pytest.raises(TimeoutError):
519
+ await push_data_and_charge(mgr, [{'a': 1}], 'page-open', False, reset_push)
520
+ assert not [p for p in client.posts if p['path'].endswith('/charge/void')]
521
+ assert mgr.get_charged_event_count('page-open') == 1
522
+
523
+
524
+ @pytest.mark.asyncio
525
+ async def test_unconfirmed_void_is_retried_before_next_charge() -> None:
526
+ client = VoidFlakyClient(void_failures=1)
527
+ mgr = _make_manager(client)
528
+
529
+ class PushHttpError(Exception):
530
+ status_code = 502
531
+
532
+ async def failing_push(_items: Any) -> None:
533
+ raise PushHttpError('bad gateway')
534
+
535
+ with pytest.raises(PushHttpError):
536
+ await push_data_and_charge(mgr, [{'a': 1}], 'page-open', False, failing_push)
537
+ assert mgr.get_charged_event_count('page-open') == 1 # void unconfirmed: reservation kept
538
+
539
+ async def ok_push(_items: Any) -> None:
540
+ return None
541
+
542
+ await push_data_and_charge(mgr, [{'a': 1}], 'page-open', False, ok_push)
543
+ paths = [p['path'].rsplit('/', 1)[-1] for p in client.posts]
544
+ assert paths == ['charge', 'void#failed', 'void', 'charge']
545
+ assert mgr.get_charged_event_count('page-open') == 1
546
+
547
+
548
+
549
+ @pytest.mark.asyncio
550
+ async def test_new_push_refused_while_earlier_void_unconfirmed() -> None:
551
+ client = VoidFlakyClient(void_failures=99)
552
+ mgr = _make_manager(client)
553
+
554
+ class PushHttpError(Exception):
555
+ status_code = 502
556
+
557
+ async def failing_push(_items: Any) -> None:
558
+ raise PushHttpError('bad gateway')
559
+
560
+ with pytest.raises(PushHttpError):
561
+ await push_data_and_charge(mgr, [{'a': 1}], 'page-open', False, failing_push)
562
+
563
+ async def ok_push(_items: Any) -> None:
564
+ return None
565
+
566
+ with pytest.raises(RuntimeError, match='could not be voided yet'):
567
+ await push_data_and_charge(mgr, [{'a': 1}], 'page-open', False, ok_push)
568
+ assert len([p for p in client.posts if p['path'].endswith('/charge')]) == 1
569
+
570
+
571
+ @pytest.mark.asyncio
572
+ async def test_uncharged_push_not_blocked_by_unconfirmed_void() -> None:
573
+ client = VoidFlakyClient(void_failures=99)
574
+ mgr = _make_manager(client)
575
+
576
+ class PushHttpError(Exception):
577
+ status_code = 502
578
+
579
+ async def failing_push(_items: Any) -> None:
580
+ raise PushHttpError('bad gateway')
581
+
582
+ with pytest.raises(PushHttpError):
583
+ await push_data_and_charge(mgr, [{'a': 1}], 'page-open', False, failing_push)
584
+
585
+ pushed: List[Any] = []
586
+
587
+ async def ok_push(items: Any) -> None:
588
+ pushed.append(items)
589
+
590
+ await push_data_and_charge(mgr, [{'b': 1}], None, False, ok_push)
591
+ assert len(pushed) == 1
592
+
593
+
594
+ @pytest.mark.asyncio
595
+ async def test_configured_platform_default_event_is_gated_by_unconfirmed_void() -> None:
596
+ client = VoidFlakyClient(void_failures=99)
597
+ mgr = _make_manager(client)
598
+
599
+ class PushHttpError(Exception):
600
+ status_code = 502
601
+
602
+ async def failing_push(_items: Any) -> None:
603
+ raise PushHttpError('bad gateway')
604
+
605
+ with pytest.raises(PushHttpError):
606
+ await push_data_and_charge(mgr, [{'a': 1}], 'page-open', False, failing_push)
607
+
608
+ # A configured default event that is a real platform event must be gated too.
609
+ mgr._config.get = MagicMock(side_effect=lambda key, default=None: 'page-open' if key == 'default_dataset_item_event_name' else None)
610
+
611
+ async def ok_push(_items: Any) -> None:
612
+ return None
613
+
614
+ with pytest.raises(RuntimeError, match='could not be voided yet'):
615
+ await push_data_and_charge(mgr, [{'b': 1}], None, True, ok_push)
616
+
617
+
618
+ @pytest.mark.asyncio
619
+ async def test_unpriced_configured_default_event_not_blocked() -> None:
620
+ client = VoidFlakyClient(void_failures=99)
621
+ mgr = _make_manager(client)
622
+
623
+ class PushHttpError(Exception):
624
+ status_code = 502
625
+
626
+ async def failing_push(_items: Any) -> None:
627
+ raise PushHttpError('bad gateway')
628
+
629
+ with pytest.raises(PushHttpError):
630
+ await push_data_and_charge(mgr, [{'a': 1}], 'page-open', False, failing_push)
631
+ mgr._config.get = MagicMock(side_effect=lambda key, default=None: 'not-priced' if key == 'default_dataset_item_event_name' else None)
632
+ pushed: List[Any] = []
633
+
634
+ async def ok_push(items: Any) -> None:
635
+ pushed.append(items)
636
+
637
+ await push_data_and_charge(mgr, [{'b': 1}], None, True, ok_push)
638
+ assert len(pushed) == 1
639
+
640
+
641
+ @pytest.mark.asyncio
642
+ async def test_unpriced_explicit_event_with_priced_default_is_gated() -> None:
643
+ client = VoidFlakyClient(void_failures=99)
644
+ mgr = _make_manager(client)
645
+
646
+ class PushHttpError(Exception):
647
+ status_code = 502
648
+
649
+ async def failing_push(_items: Any) -> None:
650
+ raise PushHttpError('bad gateway')
651
+
652
+ with pytest.raises(PushHttpError):
653
+ await push_data_and_charge(mgr, [{'a': 1}], 'page-open', False, failing_push)
654
+ # Configured default event is priced; the explicit event is not.
655
+ mgr._config.get = MagicMock(side_effect=lambda key, default=None: 'page-open' if key == 'default_dataset_item_event_name' else None)
656
+
657
+ async def ok_push(_items: Any) -> None:
658
+ return None
659
+
660
+ with pytest.raises(RuntimeError, match='could not be voided yet'):
661
+ await push_data_and_charge(mgr, [{'b': 1}], 'not-priced', True, ok_push)
@@ -663,6 +663,48 @@ def test_proxy_configuration_actor_input_use_scrapely_proxy() -> None:
663
663
  assert custom._groups == []
664
664
 
665
665
 
666
+ def test_proxy_configuration_actor_input_scrapely_proxy_options() -> None:
667
+ pc = ProxyConfiguration(actor_proxy_input={
668
+ 'useScrapelyProxy': True,
669
+ 'scrapelyProxyGroups': ['RESIDENTIAL'],
670
+ 'scrapelyProxyCountry': 'US',
671
+ 'scrapelyProxySubdivision': 'CA',
672
+ })
673
+ assert pc._groups == ['RESIDENTIAL']
674
+ assert pc._country_code == 'US'
675
+ assert pc._subdivision_code == 'CA'
676
+ both = ProxyConfiguration(actor_proxy_input={
677
+ 'useScrapelyProxy': True,
678
+ 'scrapelyProxyGroups': ['RESIDENTIAL'],
679
+ 'apifyProxyGroups': ['DATACENTER'],
680
+ 'apifyProxyCountry': 'DE',
681
+ })
682
+ assert both._groups == ['RESIDENTIAL']
683
+ assert both._country_code == 'DE'
684
+
685
+
686
+ async def test_actor_create_scrapely_proxy_groups_uses_platform(initialized_actor) -> None:
687
+ pc = await initialized_actor.create_proxy_configuration(
688
+ actor_proxy_input={'useScrapelyProxy': True, 'scrapelyProxyGroups': ['RESIDENTIAL'], 'scrapelyProxyCountry': 'US'},
689
+ check_access=False,
690
+ )
691
+ assert pc is not None
692
+ url = await pc.new_url()
693
+ assert 'groups-RESIDENTIAL' in url
694
+ assert 'country-US' in url
695
+
696
+
697
+ async def test_actor_create_legacy_apify_proxy_groups_still_work(initialized_actor) -> None:
698
+ pc = await initialized_actor.create_proxy_configuration(
699
+ actor_proxy_input={'useApifyProxy': True, 'apifyProxyGroups': ['RESIDENTIAL'], 'apifyProxyCountry': 'US'},
700
+ check_access=False,
701
+ )
702
+ assert pc is not None
703
+ url = await pc.new_url()
704
+ assert 'groups-RESIDENTIAL' in url
705
+ assert 'country-US' in url
706
+
707
+
666
708
  async def test_actor_create_no_options_without_env_returns_none(
667
709
  initialized_actor, monkeypatch: pytest.MonkeyPatch
668
710
  ) -> None: