solari-browser 0.2.2__tar.gz → 0.3.0__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: solari-browser
3
- Version: 0.2.2
3
+ Version: 0.3.0
4
4
  Summary: Python SDK for Solari Browser — managed, stealthy remote Chromium over the Playwright wire protocol / raw CDP.
5
5
  Project-URL: Homepage, https://getsolari.com
6
6
  Author: Solari
@@ -24,6 +24,9 @@ it one-for-one (snake_case where TS uses camelCase).
24
24
  The browser runs remotely on Solari's pool — `pip install` pulls the driver only;
25
25
  you do **not** run `patchright install chromium` locally.
26
26
 
27
+ Feature coverage across all five languages is on the
28
+ [SDK feature matrix](https://docs.getsolari.com/sdk-capabilities).
29
+
27
30
  ## Install
28
31
 
29
32
  ```sh
@@ -61,6 +64,22 @@ await solari.close()
61
64
  `Solari(...)` accepts `api_key`, `region` (default `us-west`), and `base_url`
62
65
  (default `https://api.getsolari.com`).
63
66
 
67
+ ### Timeout, keep-alive and metadata
68
+
69
+ ```python
70
+ session = await solari.sessions.create(
71
+ session_timeout_ms=600_000, # end earlier than the plan maximum, in ms (at least 60 000)
72
+ keep_alive=True, # hold the session if the client drops, until its deadline or release
73
+ user_metadata={"job": "nightly-42"}, # stored with the session
74
+ )
75
+ ```
76
+
77
+ Every duration option is in milliseconds (`timeout_ms`, `backoff_ms`,
78
+ `session_timeout_ms`, `probe_timeout_ms`). `session_timeout_ms` is rounded up to whole
79
+ seconds for the gateway (1001 ms is 2 s); the gateway refuses anything under 60 s;
80
+ `None` or `0` leaves the plan maximum, and a negative, fractional or non-int value
81
+ raises `SolariError` before any request. `launch()` accepts the same options.
82
+
64
83
  ## Docs
65
84
 
66
85
  Full reference and language guides: <https://getsolari.com>
@@ -8,6 +8,9 @@ it one-for-one (snake_case where TS uses camelCase).
8
8
  The browser runs remotely on Solari's pool — `pip install` pulls the driver only;
9
9
  you do **not** run `patchright install chromium` locally.
10
10
 
11
+ Feature coverage across all five languages is on the
12
+ [SDK feature matrix](https://docs.getsolari.com/sdk-capabilities).
13
+
11
14
  ## Install
12
15
 
13
16
  ```sh
@@ -45,6 +48,22 @@ await solari.close()
45
48
  `Solari(...)` accepts `api_key`, `region` (default `us-west`), and `base_url`
46
49
  (default `https://api.getsolari.com`).
47
50
 
51
+ ### Timeout, keep-alive and metadata
52
+
53
+ ```python
54
+ session = await solari.sessions.create(
55
+ session_timeout_ms=600_000, # end earlier than the plan maximum, in ms (at least 60 000)
56
+ keep_alive=True, # hold the session if the client drops, until its deadline or release
57
+ user_metadata={"job": "nightly-42"}, # stored with the session
58
+ )
59
+ ```
60
+
61
+ Every duration option is in milliseconds (`timeout_ms`, `backoff_ms`,
62
+ `session_timeout_ms`, `probe_timeout_ms`). `session_timeout_ms` is rounded up to whole
63
+ seconds for the gateway (1001 ms is 2 s); the gateway refuses anything under 60 s;
64
+ `None` or `0` leaves the plan maximum, and a negative, fractional or non-int value
65
+ raises `SolariError` before any request. `launch()` accepts the same options.
66
+
48
67
  ## Docs
49
68
 
50
69
  Full reference and language guides: <https://getsolari.com>
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "solari-browser"
7
- version = "0.2.2"
7
+ version = "0.3.0"
8
8
  description = "Python SDK for Solari Browser — managed, stealthy remote Chromium over the Playwright wire protocol / raw CDP."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -37,7 +37,7 @@ from .types import (
37
37
  Session,
38
38
  )
39
39
 
40
- __version__ = "0.2.2"
40
+ __version__ = "0.3.0"
41
41
 
42
42
  __all__ = [
43
43
  "Solari",
@@ -81,19 +81,23 @@ def _says_retryable(res: httpx.Response) -> bool:
81
81
  return False
82
82
  return isinstance(body, dict) and body.get("retryable") is True
83
83
 
84
- # A few 503s are answers, not outages: retrying cannot change them, and swallowing the body would hide the
85
- # code from the caller. `ProxyTierUnavailable` (explicitly requested proxy tier not servable) is one.
84
+ # Some 5xx are answers, not outages: retrying cannot change them, and swallowing the body would hide the
85
+ # code from the caller. The gateway says so itself with `retryable: false` (502 `PoolResponseUnparseable`:
86
+ # the session may already exist, so a retry creates a second one; 503 `EgressBlockPeekUnsupportedOnFlavor`).
87
+ # `ProxyTierUnavailable` (explicitly requested proxy tier not servable) is also terminal, whatever its flag.
86
88
  _TERMINAL_503_CODES = frozenset({"ProxyTierUnavailable"})
87
89
 
88
90
 
89
- def _is_terminal_503(res: httpx.Response) -> bool:
90
- if res.status_code != 503:
91
- return False
91
+ def _is_terminal(res: httpx.Response) -> bool:
92
92
  try:
93
93
  body = res.json()
94
94
  except Exception: # noqa: BLE001 - non-JSON body is an ordinary outage
95
95
  return False
96
- return isinstance(body, dict) and body.get("code") in _TERMINAL_503_CODES
96
+ if not isinstance(body, dict):
97
+ return False
98
+ if body.get("retryable") is False:
99
+ return True
100
+ return res.status_code == 503 and body.get("code") in _TERMINAL_503_CODES
97
101
 
98
102
 
99
103
  # Mirrors `isLikelyTransientConnect`: which connect failures are worth relaunching.
@@ -104,6 +108,20 @@ _TRANSIENT_CONNECT = re.compile(
104
108
  )
105
109
 
106
110
 
111
+ def session_timeout_seconds(ms: Optional[int]) -> Optional[int]:
112
+ """The gateway's `timeoutSeconds` for a `session_timeout_ms`: rounded UP to whole
113
+ seconds (1001 -> 2). None or 0 means "omit". Raises SolariError for a negative,
114
+ NaN, infinite, fractional or non-int value. Not clamped: the gateway still
115
+ answers 400 under 60 s."""
116
+ if ms is None or ms == 0:
117
+ return None
118
+ if isinstance(ms, bool) or not isinstance(ms, int) or ms < 0:
119
+ raise SolariError(
120
+ f"Solari: session_timeout_ms must be a non-negative int number of milliseconds, got {ms!r}"
121
+ )
122
+ return -(-ms // 1000) # ceil division
123
+
124
+
107
125
  def derive_cdp_from_ws(ws_endpoint: str) -> str:
108
126
  """`/ws/<id>` -> `/cdp/<id>`. Mirrors `deriveCdpFromWs`.
109
127
 
@@ -163,10 +181,21 @@ class _Sessions:
163
181
  stealth: bool = False,
164
182
  captcha: bool = False,
165
183
  proxy: Optional[ProxySpec] = None,
184
+ session_timeout_ms: Optional[int] = None,
185
+ keep_alive: bool = False,
186
+ user_metadata: Optional[Dict[str, Any]] = None,
166
187
  ) -> Session:
167
188
  """Create a browser session.
168
189
 
169
190
  captcha and proxy require stealth=True (enforced gateway-side).
191
+
192
+ session_timeout_ms ends the session earlier than the plan maximum, in
193
+ milliseconds. The gateway counts whole seconds, so it is rounded up (1001 ms
194
+ is 2 s), and it refuses anything under 60 s (a 400 is passed through, not
195
+ clamped). None or 0 leaves the plan maximum; a negative, NaN, infinite,
196
+ fractional or non-int value raises SolariError before any request.
197
+ keep_alive holds the session after the client disconnects, until its deadline
198
+ or release. user_metadata is a JSON object stored with the session.
170
199
  """
171
200
  body: Dict[str, Any] = {}
172
201
  if profile_id:
@@ -179,6 +208,13 @@ class _Sessions:
179
208
  body["captcha"] = True
180
209
  if proxy is not None:
181
210
  body["proxy"] = proxy.to_wire() if isinstance(proxy, ProxyRequest) else proxy
211
+ timeout_seconds = session_timeout_seconds(session_timeout_ms)
212
+ if timeout_seconds is not None:
213
+ body["timeoutSeconds"] = timeout_seconds
214
+ if keep_alive:
215
+ body["keepAlive"] = True
216
+ if user_metadata is not None:
217
+ body["userMetadata"] = user_metadata
182
218
 
183
219
  # An empty body is sent as no body at all, matching the TS SDK.
184
220
  # A create allocates a slot and launches a browser before it can answer,
@@ -234,6 +270,8 @@ class _Sessions:
234
270
 
235
271
  if data.get("proxy"):
236
272
  session.proxy = ResolvedProxyConfig.from_wire(data["proxy"])
273
+ if isinstance(data.get("userMetadata"), dict):
274
+ session.user_metadata = data["userMetadata"]
237
275
  return session
238
276
 
239
277
  async def release(self, session_id: str) -> None:
@@ -486,11 +524,13 @@ class Solari:
486
524
  res = await self._http.request(
487
525
  method, url, headers=headers, content=payload
488
526
  )
489
- retry_this = (res.status_code in _RETRYABLE_STATUS and not _is_terminal_503(res)) or (
527
+ retry_this = (res.status_code in _RETRYABLE_STATUS and not _is_terminal(res)) or (
490
528
  _is_safe_to_replay(method, idempotency_key)
491
529
  and _says_retryable(res)
492
530
  )
493
- if res.status_code < 400 or not retry_this:
531
+ # Out of attempts: hand the last response back so the caller maps its
532
+ # status and `code` like any other error, not a status-less "exhausted".
533
+ if res.status_code < 400 or not retry_this or attempt == self._max_attempts:
494
534
  return res
495
535
  last_err = SolariError(f"Solari {method} {path}: {res.status_code}", res.status_code)
496
536
  except Exception as err: # noqa: BLE001 - all transport errors are retryable
@@ -513,6 +553,9 @@ class Solari:
513
553
  stealth: bool = False,
514
554
  captcha: bool = False,
515
555
  proxy: Optional[ProxySpec] = None,
556
+ session_timeout_ms: Optional[int] = None,
557
+ keep_alive: bool = False,
558
+ user_metadata: Optional[Dict[str, Any]] = None,
516
559
  retries: int = 0,
517
560
  probe: Optional[bool] = None,
518
561
  probe_timeout_ms: int = 2_000,
@@ -540,6 +583,9 @@ class Solari:
540
583
  stealth=stealth,
541
584
  captcha=captcha,
542
585
  proxy=proxy,
586
+ session_timeout_ms=session_timeout_ms,
587
+ keep_alive=keep_alive,
588
+ user_metadata=user_metadata,
543
589
  )
544
590
  browser = None
545
591
  try:
@@ -133,6 +133,8 @@ class Session:
133
133
  expires_at: str # ISO 8601 UTC; session auto-releases at this point
134
134
  storage_state: Union[StorageState, None, _Unset] = UNSET
135
135
  proxy: Optional[ResolvedProxyConfig] = None
136
+ #: Echo of the `user_metadata` sent at create; None when none was sent.
137
+ user_metadata: Optional[Dict[str, Any]] = None
136
138
 
137
139
 
138
140
  @dataclass
@@ -286,16 +286,26 @@ async def test_does_not_retry_400(gw):
286
286
 
287
287
 
288
288
  @sync
289
- async def test_exhausting_attempts_raises(gw):
289
+ async def test_exhausting_attempts_on_5xx_keeps_the_status(gw):
290
290
  gw.route("POST", "/sessions", 503, {"error": "no capacity"})
291
291
  c = client(gw, backoff_ms=1, max_attempts=2)
292
292
  with pytest.raises(SolariError) as ei:
293
293
  await c.sessions.create()
294
294
  await c.close()
295
- assert "exhausted 2 attempts" in str(ei.value)
295
+ assert ei.value.status == 503
296
296
  assert len(gw.seen) == 2
297
297
 
298
298
 
299
+ @sync
300
+ async def test_exhausting_attempts_on_transport_error_raises_exhausted():
301
+ c = Solari(api_key="slr_live_test", base_url="http://127.0.0.1:1", backoff_ms=1, max_attempts=2)
302
+ with pytest.raises(SolariError) as ei:
303
+ await c.sessions.create()
304
+ await c.close()
305
+ assert "exhausted 2 attempts" in str(ei.value)
306
+ assert ei.value.status is None
307
+
308
+
299
309
  # ---- release / replay ---------------------------------------------------------
300
310
 
301
311
 
@@ -115,3 +115,52 @@ def test_ordinary_503_is_still_retried(gw): # noqa: F811
115
115
 
116
116
  create()
117
117
  assert len(gw.seen) == 2
118
+
119
+
120
+ def test_pool_response_unparseable_502_is_not_retried_and_keeps_its_code(gw): # noqa: F811
121
+ # The pool may already have created the session, so a retry would leave a second one behind.
122
+ gw.route("POST", "/sessions", 502,
123
+ {"error": "Pool returned an invalid response", "code": "PoolResponseUnparseable", "retryable": False})
124
+ gw.route("POST", "/sessions", 201, {"sessionId": "s-1", "wsEndpoint": "ws://127.0.0.1:1/ws"})
125
+
126
+ c = client(gw, backoff_ms=1)
127
+
128
+ @sync
129
+ async def create():
130
+ return await c.sessions.create()
131
+
132
+ with pytest.raises(SolariError) as info:
133
+ create()
134
+ assert info.value.code == "PoolResponseUnparseable"
135
+ assert info.value.status == 502
136
+ assert len(gw.seen) == 1, "retryable:false must not be retried"
137
+
138
+
139
+ def test_bare_502_is_still_retried(gw): # noqa: F811
140
+ gw.route("POST", "/sessions", 502, {"error": "bad gateway"})
141
+ gw.route("POST", "/sessions", 201, {"sessionId": "s-1", "wsEndpoint": "ws://127.0.0.1:1/ws"})
142
+
143
+ c = client(gw, backoff_ms=1)
144
+
145
+ @sync
146
+ async def create():
147
+ return await c.sessions.create()
148
+
149
+ create()
150
+ assert len(gw.seen) == 2
151
+
152
+
153
+ def test_final_5xx_keeps_its_status_and_code(gw): # noqa: F811
154
+ gw.route("POST", "/sessions", 503, {"error": "browser unhealthy", "code": "BrowserUnhealthy"})
155
+
156
+ c = client(gw, backoff_ms=1)
157
+
158
+ @sync
159
+ async def create():
160
+ return await c.sessions.create()
161
+
162
+ with pytest.raises(SolariError) as info:
163
+ create()
164
+ assert info.value.status == 503
165
+ assert info.value.code == "BrowserUnhealthy"
166
+ assert len(gw.seen) == 2, "both attempts are still made"
@@ -0,0 +1,78 @@
1
+ """session_timeout_ms, keep_alive and user_metadata on create.
2
+
3
+ The gateway's wire field stays `timeoutSeconds`; the SDK takes milliseconds and rounds
4
+ UP to whole seconds. Bad values are rejected in the SDK, before any request.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+
11
+ import pytest
12
+
13
+ from solari_browser import SolariError
14
+
15
+ from test_client import client, gw, sync # noqa: F401 - gw is a fixture
16
+
17
+ OK = {"sessionId": "s-1", "wsEndpoint": "ws://127.0.0.1:1/ws/s-1"}
18
+
19
+
20
+ @sync
21
+ async def _create(c, **kw):
22
+ return await c.sessions.create(**kw)
23
+
24
+
25
+ @pytest.mark.parametrize("ms,want", [(1000, 1), (1001, 2), (59_999, 60), (60_000, 60), (61_001, 62), (1, 1)])
26
+ def test_session_timeout_ms_is_sent_as_whole_seconds_rounded_up(gw, ms, want): # noqa: F811
27
+ gw.route("POST", "/sessions", 201, OK)
28
+ _create(client(gw), session_timeout_ms=ms)
29
+ body = gw.seen[0]["body"]
30
+ assert body["timeoutSeconds"] == want
31
+ assert "session_timeout_ms" not in body and "sessionTimeoutMs" not in body
32
+
33
+
34
+ @pytest.mark.parametrize("kw", [{}, {"session_timeout_ms": None}, {"session_timeout_ms": 0}, {"keep_alive": False}])
35
+ def test_zero_unset_and_false_send_no_body(gw, kw): # noqa: F811
36
+ gw.route("POST", "/sessions", 201, OK)
37
+ _create(client(gw), **kw)
38
+ assert gw.seen[0]["body"] is None
39
+
40
+
41
+ @pytest.mark.parametrize("bad", [-1, math.nan, math.inf, -math.inf, 1500.5, "60000", True])
42
+ def test_bad_session_timeout_ms_is_rejected_before_any_request(gw, bad): # noqa: F811
43
+ gw.route("POST", "/sessions", 201, OK)
44
+ with pytest.raises(SolariError, match="session_timeout_ms"):
45
+ _create(client(gw), session_timeout_ms=bad)
46
+ assert gw.seen == []
47
+
48
+
49
+ def test_under_60_seconds_is_not_clamped_and_the_gateway_400_reaches_the_caller(gw): # noqa: F811
50
+ gw.route("POST", "/sessions", 400,
51
+ {"error": "Invalid `timeoutSeconds`", "code": "ValidationError", "field": "timeoutSeconds"})
52
+ with pytest.raises(SolariError) as info:
53
+ _create(client(gw, backoff_ms=1), session_timeout_ms=30_000)
54
+ assert info.value.status == 400 and info.value.code == "ValidationError"
55
+ assert len(gw.seen) == 1, "a 400 is not retried"
56
+ assert gw.seen[0]["body"]["timeoutSeconds"] == 30
57
+
58
+
59
+ def test_keep_alive_and_user_metadata_go_out_and_the_metadata_comes_back(gw): # noqa: F811
60
+ gw.route("POST", "/sessions", 201, {**OK, "userMetadata": {"job": "j-7"}})
61
+ session = _create(client(gw), keep_alive=True, user_metadata={"job": "j-7"})
62
+ body = gw.seen[0]["body"]
63
+ assert body["keepAlive"] is True
64
+ assert body["userMetadata"] == {"job": "j-7"}
65
+ assert session.user_metadata == {"job": "j-7"}
66
+
67
+
68
+ def test_a_session_without_metadata_has_none(gw): # noqa: F811
69
+ gw.route("POST", "/sessions", 201, OK)
70
+ assert _create(client(gw)).user_metadata is None
71
+
72
+
73
+ def test_a_400_on_user_metadata_keeps_its_code(gw): # noqa: F811
74
+ gw.route("POST", "/sessions", 400,
75
+ {"error": "Invalid `userMetadata`", "code": "ValidationError", "field": "userMetadata"})
76
+ with pytest.raises(SolariError) as info:
77
+ _create(client(gw), user_metadata={"a": "b"})
78
+ assert info.value.status == 400 and info.value.code == "ValidationError"