scrapely-python 0.1.44__tar.gz → 0.1.45__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.44 → scrapely_python-0.1.45}/CHANGELOG.md +7 -0
  2. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/PKG-INFO +1 -1
  3. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/pyproject.toml +1 -1
  4. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/__init__.py +1 -1
  5. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/charging.py +100 -0
  6. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/storage/client.py +107 -3
  7. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely_python.egg-info/PKG-INFO +1 -1
  8. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/LICENSE +0 -0
  9. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/LICENSE-APACHE +0 -0
  10. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/MANIFEST.in +0 -0
  11. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/NOTICE +0 -0
  12. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/README.md +0 -0
  13. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/setup.cfg +0 -0
  14. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/_browser_locations.py +0 -0
  15. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/actor.py +0 -0
  16. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/browser_configuration.py +0 -0
  17. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/cdp_retry.py +0 -0
  18. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/charging_client.py +0 -0
  19. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/configuration.py +0 -0
  20. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/crypto/__init__.py +0 -0
  21. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/crypto/_secrets.py +0 -0
  22. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/errors.py +0 -0
  23. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/events/__init__.py +0 -0
  24. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/events/_types.py +0 -0
  25. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/events/event_manager.py +0 -0
  26. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/http/__init__.py +0 -0
  27. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/http/_capture.py +0 -0
  28. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/http/_client.py +0 -0
  29. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/http/_compat.py +0 -0
  30. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/http/_detect.py +0 -0
  31. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/http/_headers.py +0 -0
  32. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/http/_options.py +0 -0
  33. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/http/_policy.py +0 -0
  34. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/http/_profiles.py +0 -0
  35. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/http/_response.py +0 -0
  36. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/http/_stats.py +0 -0
  37. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/http/_transport.py +0 -0
  38. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/http/profiles.json +0 -0
  39. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/log.py +0 -0
  40. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/patch_browser_pool.py +0 -0
  41. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/pricing_types.py +0 -0
  42. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/proxy_configuration.py +0 -0
  43. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/py.typed +0 -0
  44. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/request_loaders/__init__.py +0 -0
  45. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/request_loaders/_scrapely_request_list.py +0 -0
  46. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/scrapy/__init__.py +0 -0
  47. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/scrapy/_actor_runner.py +0 -0
  48. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/scrapy/_async_thread.py +0 -0
  49. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/scrapy/_logging_config.py +0 -0
  50. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/scrapy/_serialization.py +0 -0
  51. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/scrapy/_warnings.py +0 -0
  52. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/scrapy/extensions/__init__.py +0 -0
  53. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/scrapy/extensions/_graceful_stop.py +0 -0
  54. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/scrapy/extensions/_httpcache.py +0 -0
  55. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/scrapy/middlewares/__init__.py +0 -0
  56. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/scrapy/middlewares/apify_proxy.py +0 -0
  57. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/scrapy/pipelines/__init__.py +0 -0
  58. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/scrapy/pipelines/actor_dataset_push.py +0 -0
  59. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/scrapy/requests.py +0 -0
  60. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/scrapy/scheduler.py +0 -0
  61. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/scrapy/utils.py +0 -0
  62. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/solver.py +0 -0
  63. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/storage/__init__.py +0 -0
  64. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/storage/_file_system/__init__.py +0 -0
  65. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/storage/_file_system/_key_value_store_client.py +0 -0
  66. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/storage/_file_system/_storage_client.py +0 -0
  67. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/storage/_metadata.py +0 -0
  68. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/storage/api_client.py +0 -0
  69. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/storage/patch_storage.py +0 -0
  70. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/storage/scrapely_dataset_client.py +0 -0
  71. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/storage/scrapely_kvs_client.py +0 -0
  72. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/storage/scrapely_rq_client.py +0 -0
  73. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/storage/scrapely_storage_client.py +0 -0
  74. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/storage/smart_scrapely_storage_client.py +0 -0
  75. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/storage/types.py +0 -0
  76. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/storage/utils.py +0 -0
  77. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/storage_clients/__init__.py +0 -0
  78. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/storages/__init__.py +0 -0
  79. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/types.py +0 -0
  80. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely/webhook.py +0 -0
  81. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely_python.egg-info/SOURCES.txt +0 -0
  82. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely_python.egg-info/dependency_links.txt +0 -0
  83. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely_python.egg-info/requires.txt +0 -0
  84. {scrapely_python-0.1.44 → scrapely_python-0.1.45}/src/scrapely_python.egg-info/top_level.txt +0 -0
@@ -4,6 +4,13 @@ All notable changes to this project will be documented in this file.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.1.45] - 2026-11-09
8
+
9
+ - **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.
10
+ - A charged push (`push_data(rows, charged_event_name=...)` or `charges={...}` per row) that big is charged and stored piece by piece, each piece as a push of its own: a piece is billed only when it was stored. If a piece fails, the earlier pieces stay stored and billed and the error is raised. A `charge_per='batch'` push is charged once; if one of its pieces fails, the charge is given back.
11
+ - An uncharged push whose later piece fails raises `DatasetPushIncompleteError` (an `ApiClientError`) with `stored_items`: the first `stored_items` rows were stored.
12
+ - A single item larger than one request (over 10 MiB as JSON) can never be stored. It now fails at once with `DatasetItemTooLargeError` (an `ApiClientError`, status `413`) naming the item's position, its size and the limit, for example "Dataset item at position 1 is 11010084 bytes as JSON, larger than the 10485760 bytes one push may hold, so it cannot be stored; nothing of this push was saved." Nothing of that push is sent or charged. Store large fields in the key-value store instead.
13
+
7
14
  ## [0.1.44] - 2026-11-08
8
15
 
9
16
  - 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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scrapely-python
3
- Version: 0.1.44
3
+ Version: 0.1.45
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.44"
7
+ version = "0.1.45"
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.44'
328
+ __version__ = '0.1.45'
329
329
  __all__ = [
330
330
  # Core
331
331
  'Actor',
@@ -1829,6 +1829,40 @@ def _assert_items_serializable(items: List[Any]) -> None:
1829
1829
  raise ValueError(f'Dataset item at index {index} is not serializable to JSON: {err}') from err
1830
1830
 
1831
1831
 
1832
+ def _push_groups(rows: List[Any]) -> Optional[List[List[Any]]]:
1833
+ """Rows of a push too big for one API request, split into pieces that fit.
1834
+
1835
+ ``None`` when the push fits one request (the usual case). A row larger than a
1836
+ request raises DatasetItemTooLargeError (status 413) before anything is
1837
+ charged or sent.
1838
+ """
1839
+ from .storage.client import DatasetItemTooLargeError, plan_dataset_push
1840
+
1841
+ try:
1842
+ _parts, ranges = plan_dataset_push(rows)
1843
+ except DatasetItemTooLargeError:
1844
+ raise
1845
+ except (TypeError, ValueError):
1846
+ # Not serializable: the push itself reports it, naming the item.
1847
+ return None
1848
+ if ranges is None:
1849
+ return None
1850
+ return [rows[start:end] for start, end in ranges]
1851
+
1852
+
1853
+ def _merge_group_results(results: List[ChargeResult]) -> ChargeResult:
1854
+ last = results[-1]
1855
+ covered: Dict[str, int] = {}
1856
+ for result in results:
1857
+ covered.update(result.covered_counts)
1858
+ return ChargeResult(
1859
+ chargeable_within_limit=last.chargeable_within_limit,
1860
+ charged_count=sum(result.charged_count for result in results),
1861
+ event_charge_limit_reached=any(result.event_charge_limit_reached for result in results),
1862
+ covered_counts=covered,
1863
+ )
1864
+
1865
+
1832
1866
  async def push_data_and_charge(
1833
1867
  charging_manager: ChargingManager,
1834
1868
  items: Union[Dict[str, Any], List[Dict[str, Any]]],
@@ -1838,6 +1872,31 @@ async def push_data_and_charge(
1838
1872
  ) -> ChargeResult:
1839
1873
  """Push data to dataset and charge for each item.
1840
1874
 
1875
+ A push larger than one API request (10 MiB of JSON) is charged and stored
1876
+ piece by piece (pieces of at most 9 MiB, in order), each piece atomically as
1877
+ a push of its own: a piece is billed only when it was stored. When a piece
1878
+ fails, the earlier pieces stay stored and billed and the error is raised.
1879
+ """
1880
+ 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)
1889
+
1890
+
1891
+ async def _push_data_and_charge_one(
1892
+ charging_manager: ChargingManager,
1893
+ items: Union[Dict[str, Any], List[Dict[str, Any]]],
1894
+ event_name: Optional[str],
1895
+ is_default_dataset: bool,
1896
+ push_fn: Any,
1897
+ ) -> ChargeResult:
1898
+ """Push data to dataset and charge for each item (one API request's worth).
1899
+
1841
1900
  Limits items to remaining budget before push (JS parity).
1842
1901
 
1843
1902
  Args:
@@ -2210,6 +2269,39 @@ async def push_data_with_charges(
2210
2269
  ) -> ChargeResult:
2211
2270
  """Push rows that each cost several events, atomically per row.
2212
2271
 
2272
+ A ``charge_per='row'`` push larger than one API request (10 MiB of JSON) is
2273
+ charged and stored piece by piece (at most 9 MiB each, in order), each piece
2274
+ as a push of its own: a piece is billed only when it was stored, and when a
2275
+ piece fails the earlier ones stay stored and billed and the error is raised.
2276
+ A ``'batch'`` push is charged once and sent in pieces by the storage client.
2277
+ See ``_push_data_with_charges_one`` for the per-push rules.
2278
+ """
2279
+ if charge_per == 'row':
2280
+ 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)
2290
+ return await _push_data_with_charges_one(
2291
+ charging_manager, items, charges, is_default_dataset, push_fn, charge_per
2292
+ )
2293
+
2294
+
2295
+ async def _push_data_with_charges_one(
2296
+ charging_manager: ChargingManager,
2297
+ items: Union[Dict[str, Any], List[Dict[str, Any]]],
2298
+ charges: Dict[str, int],
2299
+ is_default_dataset: bool,
2300
+ push_fn: Any,
2301
+ charge_per: str = 'row',
2302
+ ) -> ChargeResult:
2303
+ """Push rows that each cost several events, atomically per row.
2304
+
2213
2305
  ``charge_per='batch'``: ``charges`` are charged ONCE for the whole push (e.g. one
2214
2306
  ``document`` for all of its page rows). If every event is accepted all rows are
2215
2307
  stored, otherwise none (and nothing stays billed). The prepaid-row balance is
@@ -2434,6 +2526,14 @@ def _push_certainly_failed(err: BaseException) -> bool:
2434
2526
  """
2435
2527
  import httpx
2436
2528
 
2529
+ from .storage.client import DatasetPushIncompleteError
2530
+
2531
+ if isinstance(err, DatasetPushIncompleteError):
2532
+ # A push split by the storage client (only a charge_per='batch' push is
2533
+ # this big) failed part-way: give its charge back rather than bill items
2534
+ # that were not stored.
2535
+ return True
2536
+
2437
2537
  c: Optional[BaseException] = err
2438
2538
  for _ in range(4):
2439
2539
  if c is None:
@@ -6,6 +6,7 @@ Ports the patterns from the TypeScript ApiStorageClient.
6
6
 
7
7
  from __future__ import annotations
8
8
 
9
+ import json
9
10
  import os
10
11
  import logging
11
12
  import re
@@ -43,6 +44,89 @@ DEFAULT_LOCK_SECS = 180
43
44
  _RECLAIM_LOCK_SECS = 60
44
45
 
45
46
 
47
+ # The API's JSON body limit (scrapely-server MAX_JSON_BODY_BYTES). A push whose
48
+ # body is larger is refused whole with 413, so it is sent in pieces instead.
49
+ DATASET_PUSH_MAX_BODY_BYTES = 10 * 1024 * 1024
50
+ # Target size of each piece of a split push (the JS SDK's 9 MiB push chunks).
51
+ DATASET_PUSH_CHUNK_BYTES = 9 * 1024 * 1024
52
+
53
+
54
+ class DatasetItemTooLargeError(ApiClientError):
55
+ """A dataset item is larger than one push may be; nothing of the push was sent.
56
+
57
+ Carries status 413 like the API's own refusal, so callers (and the charging
58
+ code, which voids charges of a push that stored nothing) treat it the same.
59
+ """
60
+
61
+ def __init__(self, position: int, size: int, limit: int = DATASET_PUSH_MAX_BODY_BYTES):
62
+ super().__init__(
63
+ f'Dataset item at position {position} is {size} bytes as JSON, larger than the {limit} bytes '
64
+ 'one push may hold, so it cannot be stored; nothing of this push was saved. '
65
+ 'Make the item smaller (for example, store large fields in the key-value store).',
66
+ 413,
67
+ {'error': {'type': 'request-too-large', 'itemPosition': position, 'itemBytes': size, 'maxBytes': limit}},
68
+ )
69
+ self.position = position
70
+ self.size = size
71
+ self.limit = limit
72
+
73
+
74
+ class DatasetPushIncompleteError(ApiClientError):
75
+ """A split push failed part-way: its first ``stored_items`` items were stored, the rest not."""
76
+
77
+ def __init__(self, stored_items: int, total_items: int, cause: BaseException):
78
+ super().__init__(
79
+ f'Dataset push stored {stored_items} of {total_items} items before a part of it failed: {cause}',
80
+ getattr(cause, 'status_code', None) or 0,
81
+ getattr(cause, 'body', None),
82
+ )
83
+ self.stored_items = stored_items
84
+ self.total_items = total_items
85
+
86
+
87
+ def _json_bytes(value: Any) -> bytes:
88
+ # Same serialization as ApiClient.request, so sizes are the bytes really sent.
89
+ return json.dumps(value, ensure_ascii=False, default=str).encode('utf-8')
90
+
91
+
92
+ def _json_array(parts: Sequence[bytes]) -> bytes:
93
+ # Byte for byte what json.dumps writes for the list of these items.
94
+ return b'[' + b', '.join(parts) + b']'
95
+
96
+
97
+ def plan_dataset_push(
98
+ items: Sequence[Any],
99
+ chunk_bytes: int = DATASET_PUSH_CHUNK_BYTES,
100
+ max_body_bytes: int = DATASET_PUSH_MAX_BODY_BYTES,
101
+ ) -> Tuple[List[bytes], Optional[List[Tuple[int, int]]]]:
102
+ """Serialize a push's items and decide whether it must be split.
103
+
104
+ Returns each item's JSON and ``None`` when the whole push fits one request
105
+ body (at most ``max_body_bytes``). Otherwise also the ``(start, end)`` index
106
+ ranges of the pieces to send in order, each at most ``chunk_bytes`` (an item
107
+ too big for that goes alone, in a body of up to ``max_body_bytes``). An item
108
+ larger than one body raises DatasetItemTooLargeError before anything is sent.
109
+ """
110
+ parts = [_json_bytes(item) for item in items]
111
+ total = 2 + sum(len(part) for part in parts) + 2 * max(0, len(parts) - 1)
112
+ if total <= max_body_bytes:
113
+ return parts, None
114
+ for position, part in enumerate(parts):
115
+ if len(part) + 2 > max_body_bytes:
116
+ raise DatasetItemTooLargeError(position, len(part), max_body_bytes)
117
+ ranges: List[Tuple[int, int]] = []
118
+ start = 0
119
+ size = 2 # '[' and ']'
120
+ for index, part in enumerate(parts):
121
+ extra = len(part) + (2 if index > start else 0) # ', ' between items
122
+ if index > start and size + extra > chunk_bytes:
123
+ ranges.append((start, index))
124
+ start, size, extra = index, 2, len(part)
125
+ size += extra
126
+ ranges.append((start, len(parts)))
127
+ return parts, ranges
128
+
129
+
46
130
  def is_storage_uuid(value: str) -> bool:
47
131
  return bool(STORAGE_UUID_REGEX.match(value))
48
132
 
@@ -205,10 +289,30 @@ class ApiStorageClient:
205
289
  dataset_id: str,
206
290
  items: Sequence[Mapping[str, Any]],
207
291
  ) -> None:
208
- # One key per push, the same on every attempt: the API stores a re-sent
292
+ # One key per request, the same on every attempt: the API stores a re-sent
209
293
  # push once, so a push whose connection dropped can be retried.
210
- await self.api_client.post_json(
211
- f'/v2/datasets/{dataset_id}/items', list(items), idempotency_key=str(uuid.uuid4())
294
+ path = f'/v2/datasets/{dataset_id}/items'
295
+ rows = list(items)
296
+ parts, ranges = plan_dataset_push(rows)
297
+ if ranges is None:
298
+ await self._post_items(path, _json_array(parts))
299
+ return
300
+ # Over the API's body limit (the whole push would be refused with 413):
301
+ # send it in pieces of at most DATASET_PUSH_CHUNK_BYTES, in order.
302
+ for start, end in ranges:
303
+ try:
304
+ await self._post_items(path, _json_array(parts[start:end]))
305
+ except Exception as err:
306
+ if start:
307
+ raise DatasetPushIncompleteError(start, len(rows), err) from err
308
+ raise
309
+
310
+ async def _post_items(self, path: str, body: bytes) -> None:
311
+ await self.api_client.post(
312
+ path,
313
+ content=body,
314
+ headers={'Content-Type': 'application/json'},
315
+ idempotency_key=str(uuid.uuid4()),
212
316
  )
213
317
 
214
318
  async def dataset_list_items(
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scrapely-python
3
- Version: 0.1.44
3
+ Version: 0.1.45
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