scrapely-python 0.1.45__tar.gz → 0.1.47__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 (85) hide show
  1. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/CHANGELOG.md +10 -0
  2. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/PKG-INFO +1 -1
  3. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/pyproject.toml +1 -1
  4. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/__init__.py +1 -1
  5. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/actor.py +14 -0
  6. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/charging.py +107 -18
  7. scrapely_python-0.1.47/src/scrapely/resume_dedupe.py +259 -0
  8. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/solver.py +36 -0
  9. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely_python.egg-info/PKG-INFO +1 -1
  10. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely_python.egg-info/SOURCES.txt +1 -0
  11. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/LICENSE +0 -0
  12. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/LICENSE-APACHE +0 -0
  13. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/MANIFEST.in +0 -0
  14. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/NOTICE +0 -0
  15. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/README.md +0 -0
  16. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/setup.cfg +0 -0
  17. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/_browser_locations.py +0 -0
  18. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/browser_configuration.py +0 -0
  19. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/cdp_retry.py +0 -0
  20. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/charging_client.py +0 -0
  21. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/configuration.py +0 -0
  22. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/crypto/__init__.py +0 -0
  23. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/crypto/_secrets.py +0 -0
  24. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/errors.py +0 -0
  25. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/events/__init__.py +0 -0
  26. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/events/_types.py +0 -0
  27. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/events/event_manager.py +0 -0
  28. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/http/__init__.py +0 -0
  29. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/http/_capture.py +0 -0
  30. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/http/_client.py +0 -0
  31. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/http/_compat.py +0 -0
  32. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/http/_detect.py +0 -0
  33. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/http/_headers.py +0 -0
  34. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/http/_options.py +0 -0
  35. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/http/_policy.py +0 -0
  36. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/http/_profiles.py +0 -0
  37. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/http/_response.py +0 -0
  38. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/http/_stats.py +0 -0
  39. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/http/_transport.py +0 -0
  40. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/http/profiles.json +0 -0
  41. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/log.py +0 -0
  42. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/patch_browser_pool.py +0 -0
  43. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/pricing_types.py +0 -0
  44. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/proxy_configuration.py +0 -0
  45. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/py.typed +0 -0
  46. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/request_loaders/__init__.py +0 -0
  47. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/request_loaders/_scrapely_request_list.py +0 -0
  48. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/scrapy/__init__.py +0 -0
  49. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/scrapy/_actor_runner.py +0 -0
  50. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/scrapy/_async_thread.py +0 -0
  51. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/scrapy/_logging_config.py +0 -0
  52. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/scrapy/_serialization.py +0 -0
  53. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/scrapy/_warnings.py +0 -0
  54. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/scrapy/extensions/__init__.py +0 -0
  55. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/scrapy/extensions/_graceful_stop.py +0 -0
  56. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/scrapy/extensions/_httpcache.py +0 -0
  57. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/scrapy/middlewares/__init__.py +0 -0
  58. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/scrapy/middlewares/apify_proxy.py +0 -0
  59. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/scrapy/pipelines/__init__.py +0 -0
  60. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/scrapy/pipelines/actor_dataset_push.py +0 -0
  61. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/scrapy/requests.py +0 -0
  62. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/scrapy/scheduler.py +0 -0
  63. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/scrapy/utils.py +0 -0
  64. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/storage/__init__.py +0 -0
  65. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/storage/_file_system/__init__.py +0 -0
  66. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/storage/_file_system/_key_value_store_client.py +0 -0
  67. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/storage/_file_system/_storage_client.py +0 -0
  68. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/storage/_metadata.py +0 -0
  69. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/storage/api_client.py +0 -0
  70. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/storage/client.py +0 -0
  71. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/storage/patch_storage.py +0 -0
  72. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/storage/scrapely_dataset_client.py +0 -0
  73. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/storage/scrapely_kvs_client.py +0 -0
  74. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/storage/scrapely_rq_client.py +0 -0
  75. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/storage/scrapely_storage_client.py +0 -0
  76. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/storage/smart_scrapely_storage_client.py +0 -0
  77. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/storage/types.py +0 -0
  78. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/storage/utils.py +0 -0
  79. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/storage_clients/__init__.py +0 -0
  80. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/storages/__init__.py +0 -0
  81. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/types.py +0 -0
  82. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely/webhook.py +0 -0
  83. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely_python.egg-info/dependency_links.txt +0 -0
  84. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely_python.egg-info/requires.txt +0 -0
  85. {scrapely_python-0.1.45 → scrapely_python-0.1.47}/src/scrapely_python.egg-info/top_level.txt +0 -0
@@ -4,6 +4,16 @@ All notable changes to this project will be documented in this file.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.1.47] - 2026-11-10
8
+
9
+ - **A resurrected or rebooted run no longer charges again for results it had already saved.** Such a run keeps its default dataset, but the Actor's code starts from the beginning, and an Actor without its own progress state collects the results it saved before once more. On the first charged push to the default dataset of such a run, the SDK reads the result key of the rows already saved (one read of the dataset's `id` values; `id` by default). A charged row whose key is one of them is not saved and not charged again: the dataset already holds it and it was paid for when it was first saved. It counts as accepted in the push result (`charged_count`) and in `get_charged_event_count()`, so Actors that compare pushed and charged counts do not stop. The run's spending limit is not used by these rows.
10
+ - `Actor.set_result_key('id' | ['id', 'checkIn'] | None)` names the field(s) that identify one result row; `None` turns this off. `SCRAPELY_RESUME_DEDUPE=off` turns it off for a run.
11
+ - Nothing changes when the key does not identify a row: if the saved rows repeat a key, or the resumed run pushes one key twice (for example the same result from two different searches), every row is saved and charged as before. Nothing changes in a first run, a run that saved nothing yet, after a metamorph, for rows without the key, for named datasets or for pushes that are not charged per row. A first run reads only the dataset's item count once.
12
+
13
+ ## [0.1.46] - 2026-11-10
14
+
15
+ - `scrapely.solver.AkamaiSensor.report(session, verified)`: after `solve_sbsd()` or `solve_pixel()`, re-fetch the page and report whether the site let the session through (`True`) or still showed its bot check (`False`). The platform stores it on that solve, the same way `Solver.report()` does for step solves, so a site that starts refusing these answers shows up in solver health and in the refusal alerts. Best effort: it never raises, and a second report for the same answer is ignored. Needs a platform that sends `x-scrapely-solve-id` on compat answers; on an older one it does nothing.
16
+
7
17
  ## [0.1.45] - 2026-11-09
8
18
 
9
19
  - **Dataset pushes larger than the API's 10 MiB request limit are stored instead of failing.** The API refuses a request body over 10 MiB (10,485,760 bytes) with `413`. `Actor.push_data(rows)` (and `Dataset.push_data`, crawler `context.push_data`) used to send all rows in one request, so a few big rows that each fitted (for example videos with many subtitle tracks) failed the whole push, and an actor that retried it failed the same way each time. A push that fits one request is sent exactly as before. A larger one is now sent in pieces of at most 9 MiB, in order, as the JS SDK does.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scrapely-python
3
- Version: 0.1.45
3
+ Version: 0.1.47
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.45"
7
+ version = "0.1.47"
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.45'
328
+ __version__ = '0.1.47'
329
329
  __all__ = [
330
330
  # Core
331
331
  'Actor',
@@ -1010,6 +1010,20 @@ class Actor(metaclass=_ActorMeta):
1010
1010
  target.push_data,
1011
1011
  )
1012
1012
 
1013
+ @classmethod
1014
+ def set_result_key(cls, key: Union[str, List[str], None]) -> None:
1015
+ """Name the field(s) that identify one result row (default ``'id'``).
1016
+
1017
+ When a run is resurrected or rebooted, the Actor's code starts again and
1018
+ often collects results it already saved. A charged push to the default
1019
+ dataset then skips rows whose key the run saved before: they are not
1020
+ saved or charged again, and count as accepted. Use a list for a key made
1021
+ of several fields (``['id', 'checkIn']``) and ``None`` to turn this off.
1022
+ """
1023
+ from .resume_dedupe import get_resume_dedupe
1024
+
1025
+ get_resume_dedupe().set_result_key(key)
1026
+
1013
1027
  @classmethod
1014
1028
  async def get_value(cls, key: str, default_value: Any = None) -> Any:
1015
1029
  cls._ensure_initialized('get_value')
@@ -489,6 +489,9 @@ class ChargingManager:
489
489
  # lock): charges that came back short are collected here instead of being
490
490
  # logged, because the atomic push gives them back (see _ShortCharge).
491
491
  self._short_charges: Optional[List['_ShortCharge']] = None
492
+ # Rows of a resumed run that the run had already saved (and paid for)
493
+ # before: not saved or charged again, but counted as accepted (event -> count).
494
+ self._covered_earlier: Dict[str, int] = {}
492
495
 
493
496
  def close(self) -> None:
494
497
  """Mark the manager closed; subsequent charge/push operations are rejected."""
@@ -1608,12 +1611,24 @@ class ChargingManager:
1608
1611
  Returns:
1609
1612
  Number of events charged
1610
1613
  """
1614
+ # Rows a resumed run had already saved count as charged: they were paid
1615
+ # for when they were first saved (see resume_dedupe).
1611
1616
  if is_default_dataset_item_event(event_name):
1612
1617
  return (
1613
1618
  self._charged_events.get(APIFY_DEFAULT_DATASET_ITEM_EVENT, 0)
1614
1619
  + self._charged_events.get(SCRAPELY_DEFAULT_DATASET_ITEM_EVENT, 0)
1620
+ + self._covered_earlier.get(APIFY_DEFAULT_DATASET_ITEM_EVENT, 0)
1621
+ + self._covered_earlier.get(SCRAPELY_DEFAULT_DATASET_ITEM_EVENT, 0)
1615
1622
  )
1616
- return self._charged_events.get(event_name, 0)
1623
+ return self._charged_events.get(event_name, 0) + self._covered_earlier.get(event_name, 0)
1624
+
1625
+ def _note_covered_earlier(self, event_names: List[str], count: int) -> None:
1626
+ """Rows skipped because the resumed run saved them before: count them as accepted."""
1627
+ if count <= 0:
1628
+ return
1629
+ for name in dict.fromkeys(event_names):
1630
+ if name:
1631
+ self._covered_earlier[name] = self._covered_earlier.get(name, 0) + count
1617
1632
 
1618
1633
  def get_max_total_charge_usd(self) -> Decimal:
1619
1634
  """Get the configured maximum total charge.
@@ -1878,14 +1893,78 @@ async def push_data_and_charge(
1878
1893
  fails, the earlier pieces stay stored and billed and the error is raised.
1879
1894
  """
1880
1895
  rows = items if isinstance(items, list) else [items]
1881
- groups = _push_groups(rows)
1882
- if groups is None:
1883
- return await _push_data_and_charge_one(charging_manager, rows, event_name, is_default_dataset, push_fn)
1884
- results = [
1885
- await _push_data_and_charge_one(charging_manager, group, event_name, is_default_dataset, push_fn)
1886
- for group in groups
1887
- ]
1888
- return _merge_group_results(results)
1896
+
1897
+ async def push(rows: List[Any]) -> ChargeResult:
1898
+ groups = _push_groups(rows)
1899
+ if groups is None:
1900
+ return await _push_data_and_charge_one(charging_manager, rows, event_name, is_default_dataset, push_fn)
1901
+ results = [
1902
+ await _push_data_and_charge_one(charging_manager, group, event_name, is_default_dataset, push_fn)
1903
+ for group in groups
1904
+ ]
1905
+ return _merge_group_results(results)
1906
+
1907
+ if not (is_default_dataset and rows and _paid_row_events(charging_manager, {event_name: 1} if event_name else {})):
1908
+ return await push(rows)
1909
+ return await _skip_saved_rows(
1910
+ charging_manager, rows, _paid_row_events(charging_manager, {event_name: 1} if event_name else {}), push
1911
+ )
1912
+
1913
+
1914
+ def _paid_row_events(charging_manager: ChargingManager, charges: Dict[str, int]) -> List[str]:
1915
+ """Events a default-dataset push charges per row (empty: the push is not charged per row)."""
1916
+ if charging_manager._pricing_info is None:
1917
+ return []
1918
+ names = [name for name in charges if name]
1919
+ default_event = charging_manager._config.get('default_dataset_item_event_name') or (
1920
+ resolve_default_dataset_item_event_name(charging_manager._per_event_prices)
1921
+ )
1922
+ if default_event:
1923
+ names.append(default_event)
1924
+ paid = [n for n in names if (charging_manager._calculate_event_price(n) or Decimal('0')) > 0]
1925
+ if not paid:
1926
+ return []
1927
+ return list(dict.fromkeys(names))
1928
+
1929
+
1930
+ async def _skip_saved_rows(
1931
+ charging_manager: ChargingManager,
1932
+ rows: List[Any],
1933
+ event_names: List[str],
1934
+ push: Any,
1935
+ ) -> ChargeResult:
1936
+ """A charged default-dataset push of a resumed run: rows the run saved before are skipped.
1937
+
1938
+ See resume_dedupe. A skipped row is neither stored nor charged; it counts as
1939
+ accepted in the result and in get_charged_event_count.
1940
+ """
1941
+ from .resume_dedupe import get_resume_dedupe
1942
+
1943
+ dedupe = get_resume_dedupe()
1944
+ if not await dedupe.ensure(charging_manager):
1945
+ return await push(rows)
1946
+ async with dedupe.lock:
1947
+ kept, skipped, pushed = dedupe.plan(rows)
1948
+ if not skipped:
1949
+ result = await push(kept)
1950
+ dedupe.commit([], pushed[: max(0, result.charged_count)])
1951
+ return result
1952
+ if kept:
1953
+ result = await push(kept)
1954
+ else:
1955
+ result = ChargeResult(
1956
+ chargeable_within_limit=charging_manager.compute_chargeable(),
1957
+ charged_count=0,
1958
+ event_charge_limit_reached=charging_manager.is_charge_limit_reached(),
1959
+ )
1960
+ n = dedupe.commit(skipped, pushed[: max(0, result.charged_count)])
1961
+ charging_manager._note_covered_earlier(event_names, n)
1962
+ return ChargeResult(
1963
+ chargeable_within_limit=result.chargeable_within_limit,
1964
+ charged_count=result.charged_count + n,
1965
+ event_charge_limit_reached=result.event_charge_limit_reached,
1966
+ covered_counts=result.covered_counts,
1967
+ )
1889
1968
 
1890
1969
 
1891
1970
  async def _push_data_and_charge_one(
@@ -2278,15 +2357,25 @@ async def push_data_with_charges(
2278
2357
  """
2279
2358
  if charge_per == 'row':
2280
2359
  rows = items if isinstance(items, list) else [items]
2281
- groups = _push_groups(rows) if rows else None
2282
- if groups is not None:
2283
- results = [
2284
- await _push_data_with_charges_one(
2285
- charging_manager, group, charges, is_default_dataset, push_fn, charge_per
2286
- )
2287
- for group in groups
2288
- ]
2289
- return _merge_group_results(results)
2360
+
2361
+ async def push(rows: List[Any]) -> ChargeResult:
2362
+ groups = _push_groups(rows) if rows else None
2363
+ if groups is not None:
2364
+ results = [
2365
+ await _push_data_with_charges_one(
2366
+ charging_manager, group, charges, is_default_dataset, push_fn, charge_per
2367
+ )
2368
+ for group in groups
2369
+ ]
2370
+ return _merge_group_results(results)
2371
+ return await _push_data_with_charges_one(
2372
+ charging_manager, rows, charges, is_default_dataset, push_fn, charge_per
2373
+ )
2374
+
2375
+ paid = _paid_row_events(charging_manager, charges) if is_default_dataset and rows and isinstance(charges, dict) else []
2376
+ if paid:
2377
+ return await _skip_saved_rows(charging_manager, rows, paid, push)
2378
+ return await push(rows)
2290
2379
  return await _push_data_with_charges_one(
2291
2380
  charging_manager, items, charges, is_default_dataset, push_fn, charge_per
2292
2381
  )
@@ -0,0 +1,259 @@
1
+ """Results a resumed run already saved are not saved or charged again.
2
+
3
+ A resurrected or rebooted run keeps its default dataset, but the
4
+ Actor's code starts again from the beginning. An Actor that keeps no state of
5
+ its own (no request queue) then collects the results it saved before once more,
6
+ and each charged push would bill them a second time.
7
+
8
+ On the first charged push to the default dataset of such a run, the SDK reads
9
+ the result key (``id`` unless the Actor sets another with
10
+ ``Actor.set_result_key``) of the rows already saved. A later charged row whose
11
+ key is one of them is neither stored nor charged: the dataset already holds it
12
+ and it was paid for when it was first saved. It still counts as accepted, in
13
+ the push result and in ``get_charged_event_count``, so Actors that compare
14
+ what they pushed with what was charged do not read it as a refused charge.
15
+
16
+ The key must identify a row. When the saved rows repeat a key, or this run
17
+ pushes one key twice, it does not, and the run goes on as before: every row is
18
+ stored and charged. Nothing is skipped in a first run, in a run that saved
19
+ nothing yet, after a metamorph, or for pushes that are not charged per row.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import asyncio
25
+ import logging
26
+ import os
27
+ from typing import Any, Dict, Iterable, List, Optional, Sequence, Set, Tuple, Union
28
+
29
+ logger = logging.getLogger('scrapely.charging')
30
+
31
+ DEFAULT_RESULT_KEY: Tuple[str, ...] = ('id',)
32
+
33
+ # Saved rows read at most (keys only, ~a few MB of memory). A larger dataset
34
+ # is left as it is: reading it would delay the run's first push too long.
35
+ MAX_SAVED_ROWS = 200_000
36
+ _PAGE = 5_000
37
+
38
+ _OFF_VALUES = {'0', 'off', 'false', 'no'}
39
+
40
+ KeyValue = Tuple[Any, ...]
41
+
42
+
43
+ def _normalize_key(key: Union[str, Sequence[str], None]) -> Optional[Tuple[str, ...]]:
44
+ if key is None:
45
+ return None
46
+ if isinstance(key, str):
47
+ names: Tuple[str, ...] = (key,)
48
+ else:
49
+ names = tuple(key)
50
+ if not names or not all(isinstance(n, str) and n for n in names):
51
+ raise ValueError('result key must be a field name or a list of field names')
52
+ return names
53
+
54
+
55
+ def _scalar(value: Any) -> Any:
56
+ """A key part: a non-empty string or an integer (bool, float, None, objects are not keys)."""
57
+ if isinstance(value, bool):
58
+ return None
59
+ if isinstance(value, int):
60
+ return value
61
+ if isinstance(value, str) and value.strip():
62
+ return value
63
+ return None
64
+
65
+
66
+ def row_key(row: Any, fields: Tuple[str, ...]) -> Optional[KeyValue]:
67
+ """The row's key, or None when the row lacks a usable value for a key field."""
68
+ if not isinstance(row, dict):
69
+ return None
70
+ parts = []
71
+ for name in fields:
72
+ part = _scalar(row.get(name))
73
+ if part is None:
74
+ return None
75
+ # 123 and "123" are the same result.
76
+ parts.append(str(part))
77
+ return tuple(parts)
78
+
79
+
80
+ class ResumeDedupe:
81
+ """Per-process state: which saved rows a resumed run may skip."""
82
+
83
+ def __init__(self) -> None:
84
+ self._fields: Optional[Tuple[str, ...]] = DEFAULT_RESULT_KEY
85
+ self._state = 'unknown' # unknown | on | off
86
+ self._saved: Set[KeyValue] = set()
87
+ self._seen: Set[KeyValue] = set()
88
+ self._skipped = 0
89
+ self._announced = False
90
+ self._lock = asyncio.Lock()
91
+
92
+ # Actor API
93
+ def set_result_key(self, key: Union[str, Sequence[str], None]) -> None:
94
+ fields = _normalize_key(key)
95
+ if fields != self._fields:
96
+ self._fields = fields
97
+ # Keys read for the old fields are not valid for the new ones.
98
+ if self._state == 'on':
99
+ self._state = 'unknown'
100
+ self._saved = set()
101
+ self._seen = set()
102
+
103
+ @property
104
+ def skipped(self) -> int:
105
+ return self._skipped
106
+
107
+ @property
108
+ def active(self) -> bool:
109
+ return self._state == 'on'
110
+
111
+ def _off(self, reason: str) -> None:
112
+ if self._state == 'on':
113
+ logger.info(
114
+ 'Results this run saved before it was resumed are charged again from here on: %s', reason
115
+ )
116
+ self._state = 'off'
117
+ self._saved = set()
118
+ self._seen = set()
119
+
120
+ async def _load(self, manager: Any) -> None:
121
+ """Decide once whether this run is a resumed one with saved rows."""
122
+ if self._state != 'unknown':
123
+ return
124
+ self._state = 'off'
125
+ if self._fields is None:
126
+ return
127
+ if (os.environ.get('SCRAPELY_RESUME_DEDUPE') or '').strip().lower() in _OFF_VALUES:
128
+ return
129
+ client = getattr(manager, '_client', None)
130
+ run_id = getattr(manager, '_actor_run_id', None)
131
+ from .charging import default_dataset_id_from_env
132
+
133
+ dataset_id = default_dataset_id_from_env()
134
+ if not getattr(manager, '_is_at_home', False) or client is None or not run_id or not dataset_id:
135
+ return
136
+ try:
137
+ info = await client.get_json(f'/v2/datasets/{dataset_id}')
138
+ item_count = int((info or {}).get('itemCount') or 0)
139
+ if item_count <= 0:
140
+ return # first run, or nothing saved yet: nothing to skip
141
+ run = await client.get_json(f'/v2/actor-runs/{run_id}')
142
+ stats = (run or {}).get('stats') or {}
143
+ resumed = sum(int(stats.get(k) or 0) for k in ('resurrectCount', 'rebootCount'))
144
+ if resumed <= 0 or int(stats.get('metamorph') or 0) > 0:
145
+ return
146
+ if item_count > MAX_SAVED_ROWS:
147
+ logger.info(
148
+ 'This run was resumed with %s saved results, more than the %s the SDK reads to skip '
149
+ 'results saved before; every result is saved and charged as it comes',
150
+ item_count,
151
+ MAX_SAVED_ROWS,
152
+ )
153
+ return
154
+ saved: Set[KeyValue] = set()
155
+ keyed = 0
156
+ offset = 0
157
+ fields_param = ','.join(self._fields)
158
+ while offset < item_count:
159
+ page = await client.get_json(
160
+ f'/v2/datasets/{dataset_id}/items',
161
+ params={'fields': fields_param, 'offset': offset, 'limit': _PAGE},
162
+ )
163
+ rows = page if isinstance(page, list) else (page or {}).get('items') or []
164
+ if not rows:
165
+ break
166
+ for row in rows:
167
+ key = row_key(row, self._fields)
168
+ if key is None:
169
+ continue
170
+ keyed += 1
171
+ if key in saved:
172
+ logger.debug('Saved rows repeat their result key; resumed-run dedupe is off')
173
+ return
174
+ saved.add(key)
175
+ offset += len(rows)
176
+ if keyed < 2:
177
+ return
178
+ except Exception as err: # never fail a push over this
179
+ logger.debug('Could not read the saved results of the resumed run: %s', err)
180
+ return
181
+ self._saved = saved
182
+ self._seen = set()
183
+ self._state = 'on'
184
+
185
+ async def ensure(self, manager: Any) -> bool:
186
+ if self._state == 'unknown':
187
+ async with self._lock:
188
+ await self._load(manager)
189
+ return self._state == 'on'
190
+
191
+ @property
192
+ def lock(self) -> asyncio.Lock:
193
+ return self._lock
194
+
195
+ def plan(self, rows: List[Any]) -> Tuple[List[Any], List[KeyValue], List[Optional[KeyValue]]]:
196
+ """Split rows into (rows to push, keys of skipped rows, key of each row to push or None).
197
+
198
+ Nothing is recorded until ``commit``; the caller holds ``lock``.
199
+ """
200
+ if self._state != 'on' or self._fields is None:
201
+ return rows, [], []
202
+ kept: List[Any] = []
203
+ skipped: List[KeyValue] = []
204
+ pushed: List[Optional[KeyValue]] = []
205
+ batch: Set[KeyValue] = set()
206
+ for row in rows:
207
+ key = row_key(row, self._fields)
208
+ if key is None:
209
+ kept.append(row)
210
+ pushed.append(None)
211
+ continue
212
+ if key in self._seen or key in batch:
213
+ # This run pushes one key twice: the key does not identify a row,
214
+ # so nothing of this push is skipped either.
215
+ self._off('the result key repeats in this run')
216
+ return rows, [], []
217
+ batch.add(key)
218
+ if key in self._saved:
219
+ skipped.append(key)
220
+ else:
221
+ kept.append(row)
222
+ pushed.append(key)
223
+ return kept, skipped, pushed
224
+
225
+ def commit(self, skipped: Iterable[KeyValue], pushed: Iterable[Optional[KeyValue]]) -> int:
226
+ """Record a push that went through: ``pushed`` = keys of the rows it stored."""
227
+ n = 0
228
+ for key in skipped:
229
+ self._saved.discard(key)
230
+ self._seen.add(key)
231
+ n += 1
232
+ for key in pushed:
233
+ if key is not None:
234
+ self._seen.add(key)
235
+ if n:
236
+ self._skipped += n
237
+ if not self._announced:
238
+ self._announced = True
239
+ logger.info(
240
+ 'This run was resumed: results it saved before (same %s) are not saved or charged again',
241
+ ' + '.join(repr(f) for f in (self._fields or ())),
242
+ )
243
+ return n
244
+
245
+
246
+ _instance: Optional[ResumeDedupe] = None
247
+
248
+
249
+ def get_resume_dedupe() -> ResumeDedupe:
250
+ global _instance
251
+ if _instance is None:
252
+ _instance = ResumeDedupe()
253
+ return _instance
254
+
255
+
256
+ def reset_resume_dedupe() -> None:
257
+ """Tests: forget the per-process state."""
258
+ global _instance
259
+ _instance = None
@@ -95,6 +95,8 @@ DEGRADED_STATUS_MESSAGE = "Site protection temporarily unavailable, results may
95
95
  UNAVAILABLE_CODES = ("vendor_degraded", "vendor_down", "provider_unavailable", "vendor_unsupported", "solver_not_enabled")
96
96
 
97
97
  _COMPAT_SUFFIXES = ("/compat/v1",)
98
+ # Header of a compat solve answer: the id its verification is reported under (POST …/solves/<id>/outcome).
99
+ _SOLVE_ID_HEADER = "x-scrapely-solve-id"
98
100
  _STATUS_TTL_SECS = 15.0
99
101
  _MAX_BODY = 4 * 1024 * 1024
100
102
 
@@ -1117,6 +1119,10 @@ class AkamaiSensor:
1117
1119
  home = await session.get("https://www.example.com/")
1118
1120
  result = await akamai.solve(session, "https://www.example.com/", home.text)
1119
1121
  page = await session.get("https://www.example.com/item/1")
1122
+
1123
+ After an SBSD or pixel answer, tell the platform whether the site accepted it:
1124
+ ``await akamai.report(session, page_is_usable)``. That keeps the site's refusal rate visible in
1125
+ solver health and alerts.
1120
1126
  """
1121
1127
 
1122
1128
  def __init__(
@@ -1135,6 +1141,8 @@ class AkamaiSensor:
1135
1141
  self.max_rounds = max_rounds
1136
1142
  self.sessions = 0
1137
1143
  self.accepted = 0
1144
+ # The platform's id for the latest SBSD / pixel answer per session (see `report`).
1145
+ self._solve_ids: dict[int, str] = {}
1138
1146
 
1139
1147
  @staticmethod
1140
1148
  def _endpoint() -> tuple[str, str]:
@@ -1143,6 +1151,32 @@ class AkamaiSensor:
1143
1151
  raise VendorUnavailable("solver_not_enabled", "akamai", None, "the platform solver is not available to this run")
1144
1152
  return env
1145
1153
 
1154
+ # -- verification ------------------------------------------------------------
1155
+
1156
+ def _remember(self, session: Any, response: Any) -> None:
1157
+ solve_id = response.headers.get(_SOLVE_ID_HEADER)
1158
+ if solve_id:
1159
+ self._solve_ids[id(session)] = str(solve_id)[:64]
1160
+
1161
+ async def report(self, session: Any, verified: bool) -> None:
1162
+ """Report whether the site let `session` through after its latest SBSD or pixel answer.
1163
+
1164
+ Call it after you re-fetched the page: ``True`` when the page came back, ``False`` when the bot
1165
+ check was still there. The platform stores it on that solve, so a site that starts refusing these
1166
+ answers shows up in solver health and alerts. Best effort: never raises, and a second report for
1167
+ the same answer is ignored.
1168
+ """
1169
+ solve_id = self._solve_ids.pop(id(session), None)
1170
+ gw = _gateway()
1171
+ if not solve_id or gw is None:
1172
+ return
1173
+ base, key = gw
1174
+ try:
1175
+ async with httpx.AsyncClient(timeout=15) as api:
1176
+ await api.post(f"{base}/solves/{solve_id}/outcome", json={"verified": bool(verified)}, headers={"authorization": f"Bearer {key}"})
1177
+ except Exception: # noqa: BLE001 - reporting is best effort
1178
+ pass
1179
+
1146
1180
  # -- SBSD --------------------------------------------------------------------
1147
1181
 
1148
1182
  async def solve_sbsd(self, session: Any, url: str, html: str) -> bool:
@@ -1162,6 +1196,7 @@ class AkamaiSensor:
1162
1196
  json={"bundle": {"scriptSrc": src_attr, "source": source}, "document": {"url": url, "html": html, "cookieHeader": cookie_header}, "profile": {"id": self.profile_id}},
1163
1197
  )
1164
1198
  check_solver_response(r.status_code, r.text, r.headers.get("retry-after"))
1199
+ self._remember(session, r)
1165
1200
  data = _json(r.text)
1166
1201
  rows = sorted([s for s in data.get("submissions") or [] if isinstance(s, dict) and s.get("resolvedUrl")], key=lambda s: s.get("index", 0))
1167
1202
  if not rows:
@@ -1194,6 +1229,7 @@ class AkamaiSensor:
1194
1229
  "profile": {"id": self.profile_id}, "script": {"source": source, "url": collector}},
1195
1230
  )
1196
1231
  check_solver_response(r.status_code, r.text, r.headers.get("retry-after"))
1232
+ self._remember(session, r)
1197
1233
  data = _json(r.text)
1198
1234
  request = data.get("request") if isinstance(data.get("request"), dict) else {}
1199
1235
  if not data.get("ok") or not isinstance(request.get("body"), str):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scrapely-python
3
- Version: 0.1.45
3
+ Version: 0.1.47
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
@@ -19,6 +19,7 @@ src/scrapely/patch_browser_pool.py
19
19
  src/scrapely/pricing_types.py
20
20
  src/scrapely/proxy_configuration.py
21
21
  src/scrapely/py.typed
22
+ src/scrapely/resume_dedupe.py
22
23
  src/scrapely/solver.py
23
24
  src/scrapely/types.py
24
25
  src/scrapely/webhook.py