solari-browser 0.2.3__tar.gz → 0.4.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.3
3
+ Version: 0.4.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,37 @@ 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
+ ### Get and list sessions
68
+
69
+ ```python
70
+ view = await solari.sessions.get(session.id) # raw dict: status, kind, userMetadata, endpoints while active
71
+ page = await solari.sessions.list(limit=50, metadata={"job": "nightly-42"})
72
+ # page.sessions, page.next_cursor (None on the last page)
73
+ ```
74
+
75
+ `list` never returns the websocket endpoints (they are bearer capabilities): call `get`
76
+ for a single session's. Pass `page.next_cursor` as `cursor=` for the next page.
77
+
78
+ Every REST error carries the gateway's `code` when it sends one, so you can branch on
79
+ `e.code` whichever call failed: `"ReplayPending"` (a replay still uploading; wait and call
80
+ again), `"SessionNotFound"`, `"InvalidSessionId"`, `"PlanLimitExceeded"` and so on.
81
+
82
+ ### Timeout, keep-alive and metadata
83
+
84
+ ```python
85
+ session = await solari.sessions.create(
86
+ session_timeout_ms=600_000, # end earlier than the plan maximum, in ms (at least 60 000)
87
+ keep_alive=True, # hold the session if the client drops, until its deadline or release
88
+ user_metadata={"job": "nightly-42"}, # stored with the session
89
+ )
90
+ ```
91
+
92
+ Every duration option is in milliseconds (`timeout_ms`, `backoff_ms`,
93
+ `session_timeout_ms`, `probe_timeout_ms`). `session_timeout_ms` is rounded up to whole
94
+ seconds for the gateway (1001 ms is 2 s); the gateway refuses anything under 60 s;
95
+ `None` or `0` leaves the plan maximum, and a negative, fractional or non-int value
96
+ raises `SolariError` before any request. `launch()` accepts the same options.
97
+
64
98
  ## Docs
65
99
 
66
100
  Full reference and language guides: <https://getsolari.com>
@@ -0,0 +1,84 @@
1
+ # solari-browser (Python)
2
+
3
+ Python SDK for **Solari Browser** — managed, stealth-hardened remote Chromium as
4
+ an API, driven over the Playwright wire protocol (or raw CDP). A faithful port of
5
+ the TypeScript `@solarisdk/browser` package; class, method, and field names match
6
+ it one-for-one (snake_case where TS uses camelCase).
7
+
8
+ The browser runs remotely on Solari's pool — `pip install` pulls the driver only;
9
+ you do **not** run `patchright install chromium` locally.
10
+
11
+ Feature coverage across all five languages is on the
12
+ [SDK feature matrix](https://docs.getsolari.com/sdk-capabilities).
13
+
14
+ ## Install
15
+
16
+ ```sh
17
+ pip install solari-browser
18
+ ```
19
+
20
+ ## Quickstart
21
+
22
+ ```python
23
+ import asyncio, os
24
+ from solari_browser import Solari
25
+
26
+ async def main():
27
+ solari = Solari(api_key=os.environ["SOLARI_API_KEY"])
28
+ browser = await solari.launch(stealth=True) # managed, stealth-hardened Chromium
29
+ page = await browser.new_page()
30
+ await page.goto("https://example.com")
31
+ print(await page.title())
32
+ await browser.close()
33
+
34
+ asyncio.run(main())
35
+ ```
36
+
37
+ ## Sessions
38
+
39
+ Drive a session yourself instead of `launch()`:
40
+
41
+ ```python
42
+ solari = Solari(api_key=os.environ["SOLARI_API_KEY"])
43
+ session = await solari.sessions.create(stealth=True, proxy="smart")
44
+ # ... connect over the session's CDP/WS endpoint ...
45
+ await solari.close()
46
+ ```
47
+
48
+ `Solari(...)` accepts `api_key`, `region` (default `us-west`), and `base_url`
49
+ (default `https://api.getsolari.com`).
50
+
51
+ ### Get and list sessions
52
+
53
+ ```python
54
+ view = await solari.sessions.get(session.id) # raw dict: status, kind, userMetadata, endpoints while active
55
+ page = await solari.sessions.list(limit=50, metadata={"job": "nightly-42"})
56
+ # page.sessions, page.next_cursor (None on the last page)
57
+ ```
58
+
59
+ `list` never returns the websocket endpoints (they are bearer capabilities): call `get`
60
+ for a single session's. Pass `page.next_cursor` as `cursor=` for the next page.
61
+
62
+ Every REST error carries the gateway's `code` when it sends one, so you can branch on
63
+ `e.code` whichever call failed: `"ReplayPending"` (a replay still uploading; wait and call
64
+ again), `"SessionNotFound"`, `"InvalidSessionId"`, `"PlanLimitExceeded"` and so on.
65
+
66
+ ### Timeout, keep-alive and metadata
67
+
68
+ ```python
69
+ session = await solari.sessions.create(
70
+ session_timeout_ms=600_000, # end earlier than the plan maximum, in ms (at least 60 000)
71
+ keep_alive=True, # hold the session if the client drops, until its deadline or release
72
+ user_metadata={"job": "nightly-42"}, # stored with the session
73
+ )
74
+ ```
75
+
76
+ Every duration option is in milliseconds (`timeout_ms`, `backoff_ms`,
77
+ `session_timeout_ms`, `probe_timeout_ms`). `session_timeout_ms` is rounded up to whole
78
+ seconds for the gateway (1001 ms is 2 s); the gateway refuses anything under 60 s;
79
+ `None` or `0` leaves the plan maximum, and a negative, fractional or non-int value
80
+ raises `SolariError` before any request. `launch()` accepts the same options.
81
+
82
+ ## Docs
83
+
84
+ 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.3"
7
+ version = "0.4.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"
@@ -35,15 +35,19 @@ from .types import (
35
35
  ResolvedProxyConfig,
36
36
  SaveResult,
37
37
  Session,
38
+ SessionList,
39
+ SessionSummary,
38
40
  )
39
41
 
40
- __version__ = "0.2.3"
42
+ __version__ = "0.4.0"
41
43
 
42
44
  __all__ = [
43
45
  "Solari",
44
46
  "BrowserSession",
45
47
  "SolariError",
46
48
  "Session",
49
+ "SessionList",
50
+ "SessionSummary",
47
51
  "Profile",
48
52
  "ProxyCountries",
49
53
  "ProxyRequest",
@@ -4,6 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  import asyncio
6
6
  import json
7
+ import urllib.parse
7
8
  import uuid
8
9
  import logging
9
10
  import re
@@ -20,6 +21,7 @@ from .types import (
20
21
  Profile,
21
22
  ProxyRequest,
22
23
  ProxySpec,
24
+ SessionList,
23
25
  ReplayUrl,
24
26
  ProxyCountries,
25
27
  ResolvedProxyConfig,
@@ -108,6 +110,54 @@ _TRANSIENT_CONNECT = re.compile(
108
110
  )
109
111
 
110
112
 
113
+ def _api_error(what: str, res: httpx.Response) -> SolariError:
114
+ """The error for a non-ok API response: status, body in the message, and the
115
+ gateway's `code` (ReplayPending, SessionNotFound, InvalidSessionId, ...) when
116
+ the body is JSON with a string `code`. Every REST call uses this so callers can
117
+ branch on `e.code` whichever endpoint failed."""
118
+ text = res.text or ""
119
+ return SolariError(
120
+ f"Solari {what} failed: {res.status_code} {text}",
121
+ res.status_code,
122
+ None,
123
+ code_from_body(text),
124
+ )
125
+
126
+
127
+ _MAX_METADATA_CLAUSES = 10
128
+
129
+
130
+ def _metadata_filter(metadata: Dict[str, str]) -> str:
131
+ """The gateway's list filter grammar, in key order. Raises SolariError for a pair
132
+ it cannot express (nothing is sent)."""
133
+ if len(metadata) > _MAX_METADATA_CLAUSES:
134
+ raise SolariError(f"Solari: at most {_MAX_METADATA_CLAUSES} metadata filter pairs")
135
+ clauses = []
136
+ for k in sorted(metadata):
137
+ v = metadata[k]
138
+ if not k or len(k) > 128 or "'" in k or "'" in v:
139
+ raise SolariError(
140
+ f"Solari: metadata filter key {k!r} or its value cannot be expressed "
141
+ "(1-128 characters, no single quote)"
142
+ )
143
+ clauses.append(f"user_metadata['{k}']:'{v}'")
144
+ return " AND ".join(clauses)
145
+
146
+
147
+ def session_timeout_seconds(ms: Optional[int]) -> Optional[int]:
148
+ """The gateway's `timeoutSeconds` for a `session_timeout_ms`: rounded UP to whole
149
+ seconds (1001 -> 2). None or 0 means "omit". Raises SolariError for a negative,
150
+ NaN, infinite, fractional or non-int value. Not clamped: the gateway still
151
+ answers 400 under 60 s."""
152
+ if ms is None or ms == 0:
153
+ return None
154
+ if isinstance(ms, bool) or not isinstance(ms, int) or ms < 0:
155
+ raise SolariError(
156
+ f"Solari: session_timeout_ms must be a non-negative int number of milliseconds, got {ms!r}"
157
+ )
158
+ return -(-ms // 1000) # ceil division
159
+
160
+
111
161
  def derive_cdp_from_ws(ws_endpoint: str) -> str:
112
162
  """`/ws/<id>` -> `/cdp/<id>`. Mirrors `deriveCdpFromWs`.
113
163
 
@@ -167,10 +217,21 @@ class _Sessions:
167
217
  stealth: bool = False,
168
218
  captcha: bool = False,
169
219
  proxy: Optional[ProxySpec] = None,
220
+ session_timeout_ms: Optional[int] = None,
221
+ keep_alive: bool = False,
222
+ user_metadata: Optional[Dict[str, Any]] = None,
170
223
  ) -> Session:
171
224
  """Create a browser session.
172
225
 
173
226
  captcha and proxy require stealth=True (enforced gateway-side).
227
+
228
+ session_timeout_ms ends the session earlier than the plan maximum, in
229
+ milliseconds. The gateway counts whole seconds, so it is rounded up (1001 ms
230
+ is 2 s), and it refuses anything under 60 s (a 400 is passed through, not
231
+ clamped). None or 0 leaves the plan maximum; a negative, NaN, infinite,
232
+ fractional or non-int value raises SolariError before any request.
233
+ keep_alive holds the session after the client disconnects, until its deadline
234
+ or release. user_metadata is a JSON object stored with the session.
174
235
  """
175
236
  body: Dict[str, Any] = {}
176
237
  if profile_id:
@@ -183,6 +244,13 @@ class _Sessions:
183
244
  body["captcha"] = True
184
245
  if proxy is not None:
185
246
  body["proxy"] = proxy.to_wire() if isinstance(proxy, ProxyRequest) else proxy
247
+ timeout_seconds = session_timeout_seconds(session_timeout_ms)
248
+ if timeout_seconds is not None:
249
+ body["timeoutSeconds"] = timeout_seconds
250
+ if keep_alive:
251
+ body["keepAlive"] = True
252
+ if user_metadata is not None:
253
+ body["userMetadata"] = user_metadata
186
254
 
187
255
  # An empty body is sent as no body at all, matching the TS SDK.
188
256
  # A create allocates a slot and launches a browser before it can answer,
@@ -238,6 +306,8 @@ class _Sessions:
238
306
 
239
307
  if data.get("proxy"):
240
308
  session.proxy = ResolvedProxyConfig.from_wire(data["proxy"])
309
+ if isinstance(data.get("userMetadata"), dict):
310
+ session.user_metadata = data["userMetadata"]
241
311
  return session
242
312
 
243
313
  async def release(self, session_id: str) -> None:
@@ -278,21 +348,40 @@ class _Sessions:
278
348
  """Raw session view from the gateway."""
279
349
  res = await self._client.request("GET", f"/sessions/{_q(session_id)}")
280
350
  if res.status_code >= 400:
281
- raise SolariError(
282
- f"Solari GET /sessions/{session_id} failed: {res.status_code} {res.text}",
283
- res.status_code,
284
- )
351
+ raise _api_error(f"GET /sessions/{session_id}", res)
285
352
  return _json(res, f"/sessions/{session_id}")
286
353
 
354
+ async def list(
355
+ self,
356
+ *,
357
+ limit: Optional[int] = None,
358
+ cursor: Optional[str] = None,
359
+ metadata: Optional[Dict[str, str]] = None,
360
+ ) -> SessionList:
361
+ """One page of the organisation's sessions (``GET /sessions``). Rows never carry
362
+ the websocket endpoints (they are bearer capabilities): use ``get(id)`` for those.
363
+ ``metadata`` keeps sessions whose ``user_metadata`` has all these string values
364
+ (at most 10 pairs; keys and values cannot contain a single quote)."""
365
+ params: Dict[str, str] = {}
366
+ if limit is not None and limit > 0:
367
+ params["limit"] = str(limit)
368
+ if cursor:
369
+ params["cursor"] = cursor
370
+ if metadata:
371
+ params["q"] = _metadata_filter(metadata)
372
+ path = "/sessions"
373
+ if params:
374
+ path += "?" + urllib.parse.urlencode(params)
375
+ res = await self._client.request("GET", path)
376
+ if res.status_code >= 400:
377
+ raise _api_error("GET /sessions", res)
378
+ return SessionList.from_wire(_json(res, "/sessions"))
379
+
287
380
  async def get_replay_url(self, session_id: str) -> ReplayUrl:
288
381
  """Presigned replay URL. Available ~1-3s after `release_and_wait`."""
289
382
  res = await self._client.request("GET", f"/sessions/{_q(session_id)}/replay-url")
290
383
  if res.status_code >= 400:
291
- raise SolariError(
292
- f"Solari GET /sessions/{session_id}/replay-url failed: "
293
- f"{res.status_code} {res.text}",
294
- res.status_code,
295
- )
384
+ raise _api_error(f"GET /sessions/{session_id}/replay-url", res)
296
385
  data = _json(res, "replay-url")
297
386
  if not data.get("url"):
298
387
  raise SolariError(f"Solari: unexpected replay-url response: {json.dumps(data)}")
@@ -338,9 +427,7 @@ class _Profiles:
338
427
  async def list(self) -> List[Profile]:
339
428
  res = await self._client.request("GET", "/profiles")
340
429
  if res.status_code >= 400:
341
- raise SolariError(
342
- f"Solari GET /profiles failed: {res.status_code} {res.text}", res.status_code
343
- )
430
+ raise _api_error("GET /profiles", res)
344
431
  data = _json(res, "/profiles")
345
432
  items = data if isinstance(data, list) else data.get("profiles", [])
346
433
  return [Profile.from_wire(p) for p in items]
@@ -349,10 +436,7 @@ class _Profiles:
349
436
  """Delete a profile. A 404 is success — it's already gone."""
350
437
  res = await self._client.request("DELETE", f"/profiles/{_q(profile_id)}")
351
438
  if res.status_code >= 400 and res.status_code != 404:
352
- raise SolariError(
353
- f"Solari DELETE /profiles/{profile_id} failed: {res.status_code} {res.text}",
354
- res.status_code,
355
- )
439
+ raise _api_error(f"DELETE /profiles/{profile_id}", res)
356
440
 
357
441
  async def save(self, profile_id: str, storage_state: StorageState) -> SaveResult:
358
442
  """Persist a Playwright storage state into the profile."""
@@ -360,10 +444,7 @@ class _Profiles:
360
444
  "POST", f"/profiles/{_q(profile_id)}/save", {"storageState": storage_state}
361
445
  )
362
446
  if res.status_code >= 400:
363
- raise SolariError(
364
- f"Solari POST /profiles/{profile_id}/save failed: {res.status_code} {res.text}",
365
- res.status_code,
366
- )
447
+ raise _api_error(f"POST /profiles/{profile_id}/save", res)
367
448
  data = _json(res, "profiles/save")
368
449
  return SaveResult(
369
450
  version=data.get("version") or 0,
@@ -381,10 +462,7 @@ class _Proxy:
381
462
  """``GET /proxy/countries`` — supported egress countries + residential status."""
382
463
  res = await self._client.request("GET", "/proxy/countries")
383
464
  if res.status_code >= 400:
384
- raise SolariError(
385
- f"Solari GET /proxy/countries failed: {res.status_code} {res.text}",
386
- res.status_code,
387
- )
465
+ raise _api_error("GET /proxy/countries", res)
388
466
  return ProxyCountries.from_wire(_json(res, "/proxy/countries"))
389
467
 
390
468
 
@@ -519,6 +597,9 @@ class Solari:
519
597
  stealth: bool = False,
520
598
  captcha: bool = False,
521
599
  proxy: Optional[ProxySpec] = None,
600
+ session_timeout_ms: Optional[int] = None,
601
+ keep_alive: bool = False,
602
+ user_metadata: Optional[Dict[str, Any]] = None,
522
603
  retries: int = 0,
523
604
  probe: Optional[bool] = None,
524
605
  probe_timeout_ms: int = 2_000,
@@ -546,6 +627,9 @@ class Solari:
546
627
  stealth=stealth,
547
628
  captcha=captcha,
548
629
  proxy=proxy,
630
+ session_timeout_ms=session_timeout_ms,
631
+ keep_alive=keep_alive,
632
+ user_metadata=user_metadata,
549
633
  )
550
634
  browser = None
551
635
  try:
@@ -133,6 +133,48 @@ 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
138
+
139
+
140
+ @dataclass
141
+ class SessionSummary:
142
+ """One row of ``sessions.list()``. Never carries the websocket endpoints."""
143
+
144
+ id: str
145
+ status: str
146
+ kind: Optional[str] = None
147
+ created_at: Optional[str] = None
148
+ expires_at: Optional[str] = None
149
+ user_metadata: Optional[Dict[str, Any]] = None
150
+
151
+ @staticmethod
152
+ def from_wire(d: Dict[str, Any]) -> "SessionSummary":
153
+ um = d.get("userMetadata")
154
+ return SessionSummary(
155
+ id=d["id"],
156
+ status=d.get("status") or "",
157
+ kind=d.get("kind"),
158
+ created_at=d.get("createdAt"),
159
+ expires_at=d.get("expiresAt"),
160
+ user_metadata=um if isinstance(um, dict) else None,
161
+ )
162
+
163
+
164
+ @dataclass
165
+ class SessionList:
166
+ """One page of ``sessions.list()``."""
167
+
168
+ sessions: List[SessionSummary] = field(default_factory=list)
169
+ #: None on the last page; pass it as ``cursor=`` for the next one.
170
+ next_cursor: Optional[str] = None
171
+
172
+ @staticmethod
173
+ def from_wire(d: Any) -> "SessionList":
174
+ rows = d.get("sessions") if isinstance(d, dict) else None
175
+ out = [SessionSummary.from_wire(r) for r in (rows or []) if isinstance(r, dict) and r.get("id")]
176
+ cur = d.get("nextCursor") if isinstance(d, dict) else None
177
+ return SessionList(sessions=out, next_cursor=cur if isinstance(cur, str) and cur else None)
136
178
 
137
179
 
138
180
  @dataclass
@@ -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"
@@ -0,0 +1,125 @@
1
+ """sessions.list, and the gateway's `code` on every non-create error path.
2
+
3
+ bug2's live data (staging): replay-url on a released recorded session whose upload is not done is
4
+ 404 {"error":"Replay upload is still in flight","code":"ReplayPending","retryable":true,"sessionId":...};
5
+ a young session can get 404 {"code":"SessionNotFound"}; a bogus id is 404 {"code":"InvalidSessionId"}.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import urllib.parse
11
+
12
+ import pytest
13
+
14
+ from solari_browser import SolariError
15
+
16
+ from test_client import client, gw, sync # noqa: F401 - gw is a fixture
17
+
18
+
19
+ @sync
20
+ async def _list(c, **kw):
21
+ return await c.sessions.list(**kw)
22
+
23
+
24
+ @sync
25
+ async def _get(c, sid):
26
+ return await c.sessions.get(sid)
27
+
28
+
29
+ @sync
30
+ async def _replay(c, sid):
31
+ return await c.sessions.get_replay_url(sid)
32
+
33
+
34
+ def test_list_sends_paging_and_sorted_metadata_filter_and_parses_the_page(gw): # noqa: F811
35
+ path = "/sessions?" + urllib.parse.urlencode({
36
+ "limit": "2", "cursor": "cur1",
37
+ "q": "user_metadata['env']:'prod' AND user_metadata['team']:'x'",
38
+ })
39
+ gw.route("GET", path, 200, {
40
+ "sessions": [
41
+ {"id": "s1", "status": "active", "kind": "fast", "userMetadata": {"team": "x"}},
42
+ {"id": "s2", "status": "released"},
43
+ {"status": "no-id"},
44
+ ],
45
+ "nextCursor": "cur2",
46
+ })
47
+ page = _list(client(gw), limit=2, cursor="cur1", metadata={"team": "x", "env": "prod"})
48
+ seen = gw.seen[0]
49
+ qs = urllib.parse.parse_qs(urllib.parse.urlparse(seen["path"]).query)
50
+ assert qs["limit"] == ["2"] and qs["cursor"] == ["cur1"]
51
+ assert qs["q"] == ["user_metadata['env']:'prod' AND user_metadata['team']:'x'"]
52
+ assert [s.id for s in page.sessions] == ["s1", "s2"], "rows without an id are skipped"
53
+ assert page.sessions[0].user_metadata == {"team": "x"} and page.sessions[0].kind == "fast"
54
+ assert page.sessions[1].status == "released"
55
+ assert page.next_cursor == "cur2"
56
+
57
+
58
+ def test_list_with_no_options_is_a_bare_path_and_an_empty_page_has_no_cursor(gw): # noqa: F811
59
+ gw.route("GET", "/sessions", 200, {"sessions": []})
60
+ page = _list(client(gw))
61
+ assert gw.seen[0]["path"] == "/sessions"
62
+ assert page.sessions == [] and page.next_cursor is None
63
+
64
+
65
+ @pytest.mark.parametrize("bad", [{"k": "it's"}, {"k'": "v"}, {"": "v"}, {f"k{i}": "v" for i in range(11)}])
66
+ def test_a_filter_the_grammar_cannot_express_is_refused_before_any_request(gw, bad): # noqa: F811
67
+ gw.route("GET", "/sessions", 200, {"sessions": []})
68
+ with pytest.raises(SolariError):
69
+ _list(client(gw), metadata=bad)
70
+ assert gw.seen == []
71
+
72
+
73
+ def test_a_gateway_400_on_the_list_filter_keeps_its_code(gw): # noqa: F811
74
+ gw.route("GET", "/sessions", 400, {"error": "Invalid q", "code": "ValidationError", "field": "q"})
75
+ with pytest.raises(SolariError) as info:
76
+ _list(client(gw))
77
+ assert info.value.status == 400 and info.value.code == "ValidationError"
78
+
79
+
80
+ def test_get_on_a_bogus_id_keeps_404_and_invalid_session_id(gw): # noqa: F811
81
+ gw.route("GET", "/sessions/nope", 404, {"error": "Not Found", "code": "InvalidSessionId"})
82
+ with pytest.raises(SolariError) as info:
83
+ _get(client(gw), "nope")
84
+ assert info.value.status == 404 and info.value.code == "InvalidSessionId"
85
+
86
+
87
+ @pytest.mark.parametrize("body", [
88
+ {"error": "Replay upload is still in flight", "code": "ReplayPending", "retryable": True, "sessionId": "s1"},
89
+ {"error": "Session not found", "code": "SessionNotFound"},
90
+ {"error": "No replay available for this session", "code": "ReplayUnavailable"},
91
+ ])
92
+ def test_replay_url_404_exposes_its_code(gw, body): # noqa: F811
93
+ # retryable:true is retried once by the shared loop, so serve it on every attempt.
94
+ gw.route("GET", "/sessions/s1/replay-url", 404, body)
95
+ gw.route("GET", "/sessions/s1/replay-url", 404, body)
96
+ with pytest.raises(SolariError) as info:
97
+ _replay(client(gw, backoff_ms=1), "s1")
98
+ assert info.value.status == 404 and info.value.code == body["code"]
99
+
100
+
101
+ def test_profiles_and_proxy_errors_keep_the_gateway_code(gw): # noqa: F811
102
+ c = client(gw)
103
+
104
+ @sync
105
+ async def calls():
106
+ out = []
107
+ for fn in (lambda: c.profiles.list(), lambda: c.profiles.save("p1", {"cookies": []}),
108
+ lambda: c.profiles.delete("p1"), lambda: c.proxy.countries()):
109
+ try:
110
+ await fn()
111
+ except SolariError as e:
112
+ out.append((e.status, e.code))
113
+ return out
114
+
115
+ for path, method in (("/profiles", "GET"), ("/profiles/p1/save", "POST"),
116
+ ("/profiles/p1", "DELETE"), ("/proxy/countries", "GET")):
117
+ gw.route(method, path, 403, {"error": "quota", "code": "PlanLimitExceeded"})
118
+ assert calls() == [(403, "PlanLimitExceeded")] * 4
119
+
120
+
121
+ def test_a_non_json_error_body_gives_a_status_and_no_code(gw): # noqa: F811
122
+ gw.route("GET", "/sessions/s1/replay-url", 404, None)
123
+ with pytest.raises(SolariError) as info:
124
+ _replay(client(gw), "s1")
125
+ assert info.value.status == 404 and info.value.code is None
@@ -1,50 +0,0 @@
1
- # solari-browser (Python)
2
-
3
- Python SDK for **Solari Browser** — managed, stealth-hardened remote Chromium as
4
- an API, driven over the Playwright wire protocol (or raw CDP). A faithful port of
5
- the TypeScript `@solarisdk/browser` package; class, method, and field names match
6
- it one-for-one (snake_case where TS uses camelCase).
7
-
8
- The browser runs remotely on Solari's pool — `pip install` pulls the driver only;
9
- you do **not** run `patchright install chromium` locally.
10
-
11
- ## Install
12
-
13
- ```sh
14
- pip install solari-browser
15
- ```
16
-
17
- ## Quickstart
18
-
19
- ```python
20
- import asyncio, os
21
- from solari_browser import Solari
22
-
23
- async def main():
24
- solari = Solari(api_key=os.environ["SOLARI_API_KEY"])
25
- browser = await solari.launch(stealth=True) # managed, stealth-hardened Chromium
26
- page = await browser.new_page()
27
- await page.goto("https://example.com")
28
- print(await page.title())
29
- await browser.close()
30
-
31
- asyncio.run(main())
32
- ```
33
-
34
- ## Sessions
35
-
36
- Drive a session yourself instead of `launch()`:
37
-
38
- ```python
39
- solari = Solari(api_key=os.environ["SOLARI_API_KEY"])
40
- session = await solari.sessions.create(stealth=True, proxy="smart")
41
- # ... connect over the session's CDP/WS endpoint ...
42
- await solari.close()
43
- ```
44
-
45
- `Solari(...)` accepts `api_key`, `region` (default `us-west`), and `base_url`
46
- (default `https://api.getsolari.com`).
47
-
48
- ## Docs
49
-
50
- Full reference and language guides: <https://getsolari.com>