Browsers
solari-browser (library solari_browser) is the control plane: Client, the sessions / profiles / proxy namespaces, and the optional connect() helper. See the Rust SDK hub for install and configuration.
solari-browser = "0.6" # control plane
solari-browser = { version = "0.6", features = ["connect"] } # + connect()solari-browser is published to crates.io (source in the solari-sdk GitHub org).Contents
Client: Client::new(), sessions(), profiles(), proxy(), base_url()Sessions: create(), get(), list(), release(), replay_url(), download_replay()Profiles: list(), create(), save(), delete()Proxy: countries()ConnectedBrowser: connect(), connect_endpoint(), into_parts(), disconnect()Client::launch():LaunchOptions,LaunchedSession- Types:
ClientOptions,CreateSessionOptions,Session,SessionView,StorageState,ProxySpec,ProxyRequest,ProxyTier,ResolvedProxyConfig,ProxyCountries,Profile,ProfileSaveResult,ReplayUrl,SolariRegion,SolariError,SolariErrorCode
Client
The browser client. Creates sessions and manages profiles.
Constructors
Client::new()
fn new(opts: ClientOptions) -> Result<Client, SolariError>Creates a client. Does not open any connection.
Parameters:
optsClientOptions: see ClientOptions.
Returns: Result<Client, SolariError>
Errors: SolariError::Config if api_key or base_url is empty, or the HTTP client fails to build.
Example:
use solari_browser::{Client, ClientOptions};
let client = Client::new(ClientOptions::default_region(&api_key))?;
// Or point at a staging / self-hosted gateway:
let client = Client::new(ClientOptions::new(&api_key, "https://gw.example.com"))?;Debug is hand-written on ClientOptions and on the internal HttpTransport, so the key renders as "<redacted>". Client derives Debug, but its only field is that transport, so logging a client is safe too; the secret never reaches your logs.Methods
base_url()
fn base_url(&self) -> &strThe resolved API base URL, with any trailing slash stripped.
Returns: &str
Example:
assert_eq!(client.base_url(), "https://api.getsolari.com");Sessions
The session namespace. Obtain with client.sessions().
create()
async fn create(&self, options: CreateSessionOptions) -> Result<Session, SolariError>Acquires a browser session (POST /sessions). Unset options are omitted from the body entirely.
Parameters:
optionsCreateSessionOptions: see CreateSessionOptions.
Returns: Result<Session, SolariError>
Errors: SolariError::Api carrying status and the server code (e.g. FeatureRequiresPlan, ConcurrencyLimitExceeded); SolariError::Protocol if the response has no sessionId or wsEndpoint.
Example:
use solari_browser::{CreateSessionOptions, ProxySpec};
let session = client
.sessions()
.create(CreateSessionOptions::new().stealth(true).proxy(ProxySpec::country("us")))
.await?;
println!("{} expires {}", session.id, session.expires_at);.captcha(true) and any .proxy(…) request are rejected by the API unless .stealth(true) is also set.CreateSessionOptions has no allowed_domains(egress allowlist) field, so a session created from Rust is always unrestricted. The REST API and the Browserbase-compatible packages accept it; this crate does not send it.get()
async fn get(&self, id: &str) -> Result<SessionView, SolariError>Fetches a session’s current view (GET /sessions/:id). Every field is optional; unknown keys land in SessionView::extra.
Parameters:
id&str: session id.
Returns: Result<SessionView, SolariError>
Errors: SolariError::Api on a non-2xx status; SolariError::Protocol if the body is not JSON.
Example:
let view = client.sessions().get(&session.id).await?;
println!("{:?} {:?}", view.status, view.expires_at);The endpoint answers from gateway state with status one of active, released (ended by a release or server-side; terminal), expired, or unknown (owning pool not registered on the answering replica). A well-formed id from your own org never 404s; polling until released confirms a release. See the endpoint reference. Every SessionView field is Option and unknown keys are preserved, so a new status value never breaks deserialisation.
list()
async fn list(&self, options: ListSessionsOptions) -> Result<SessionList, SolariError>One page of your organisation’s sessions (GET /sessions). Rows are SessionSummary values (id, status, kind, created_at, expires_at, user_metadata) and never carry the websocket endpoints; call get() for those. Pass next_cursor back as cursor for the next page; it is None on the last one.
Parameters: ListSessionsOptions with limit, cursor, and metadata, a map that keeps only sessions whose user_metadata has all those string values (at most 10 pairs; keys and values cannot contain a single quote).
Errors: SolariError::Api on a non-2xx status; SolariError::Config for a metadata filter that breaks those rules.
use solari_browser::ListSessionsOptions;
let mut opts = ListSessionsOptions::default();
opts.metadata.insert("job".into(), "nightly".into());
let page = client.sessions().list(opts).await?;
for s in &page.sessions {
println!("{} {} {:?}", s.id, s.status, s.user_metadata);
}release()
async fn release(&self, id: &str) -> Result<(), SolariError>Releases a session and waits for confirmation (DELETE /sessions/:id). A bare 404 (the session already ended) is treated as success. A 404 carrying the code InvalidSessionId is an error: the gateway refused the id (malformed, forged, or another org’s) and released nothing.
Parameters:
id&str: session id.
Returns: Result<(), SolariError>
Errors: SolariError::Api on any non-404 error status, and on a 404 with InvalidSessionId.
Example:
client.sessions().release(&session.id).await?;
// the replay is available ~1-3s laterrelease() / releaseAndWait() split. This method is the equivalent of releaseAndWait. tokio::spawn it yourself if you do not want to await the round-trip.replay_url()
async fn replay_url(&self, id: &str) -> Result<ReplayUrl, SolariError>Presigned URL for a recorded session’s replay. Requires .recording(true) at create time; available ~1 to 3s after release().
Parameters:
id&str: session id.
Returns: Result<ReplayUrl, SolariError> with url, expires_in_seconds (0 when omitted), content_encoding: the actual encoding of the bytes url will serve ("identity" on GCP, "gzip" on AWS). Check this before decompressing.
Errors: SolariError::Api if the replay is not ready; SolariError::Protocol if the body carries no url.
Example:
let replay = client.sessions().replay_url(&session.id).await?;
println!("{} ({}s)", replay.url, replay.expires_in_seconds);download_replay()
async fn download_replay(&self, id: &str) -> Result<Vec<u8>, SolariError>Resolves the replay URL and downloads the bytes in one call. The bytes are whatever content_encoding on the resolved ReplayUrl says: plain NDJSON on GCP, gzipped on AWS. Check it before decompressing; this function does not decompress for you.
Parameters:
id&str: session id.
Returns: Result<Vec<u8>, SolariError>
Errors: everything replay_url() raises, plus SolariError::Api if the download itself is non-2xx.
Example:
let bytes = client.sessions().download_replay(&session.id).await?;
std::fs::write("replay.ndjson.gz", bytes)?;Profiles
Stored browser profiles (cookies + localStorage). Obtain with client.profiles().
list()
async fn list(&self) -> Result<Vec<Profile>, SolariError>Lists every profile on the account.
Returns: Result<Vec<Profile>, SolariError>
Errors: SolariError::Api on a non-2xx status; SolariError::Protocol on a malformed body.
Example:
for p in client.profiles().list().await? {
println!("{} {}", p.id, p.name);
}create()
async fn create(&self, name: impl Into<String>) -> Result<Profile, SolariError>Creates an empty profile. Attach it to a session with .profile_id(…) to persist cookies and localStorage.
Parameters:
nameimpl Into<String>: human-facing name.
Returns: Result<Profile, SolariError>
Errors: SolariError::Api with the server code on failure.
Example:
let profile = client.profiles().create("logged-in").await?;
let session = client
.sessions()
.create(CreateSessionOptions::new().profile_id(&profile.id))
.await?;save()
async fn save(
&self,
id: &str,
storage_state: &StorageState,
) -> Result<ProfileSaveResult, SolariError>Overwrites a profile with the given storage state (POST /profiles/:id/save).
Parameters:
id&str: profile id.storage_state&StorageState: cookies + origins.
Returns: Result<ProfileSaveResult, SolariError> with version and size_bytes, each 0 when the API omits them.
Errors: SolariError::Api on a non-2xx response.
Example:
use solari_browser::{Cookie, SameSite, StorageState};
let state = StorageState {
cookies: Some(vec![Cookie {
name: "sid".into(),
value: "abc".into(),
domain: Some(".example.com".into()),
same_site: Some(SameSite::Lax),
..Default::default()
}]),
..Default::default()
};
let saved = client.profiles().save(&profile.id, &state).await?;
println!("v{} ({} bytes)", saved.version, saved.size_bytes);delete()
async fn delete(&self, id: &str) -> Result<(), SolariError>Deletes a profile. Idempotent, so a 404 resolves successfully.
Parameters:
id&str: profile id.
Returns: Result<(), SolariError>
Errors: SolariError::Api on any non-404 error status.
Example:
client.profiles().delete(&profile.id).await?;Proxy
Managed proxy metadata. Obtain with client.proxy().
countries()
async fn countries(&self) -> Result<ProxyCountries, SolariError>Supported egress countries, and whether managed proxy egress is configured on this gateway at all.
Returns: Result<ProxyCountries, SolariError> with enabled, countries.
Errors: SolariError::Api on a non-2xx status.
Example:
let res = client.proxy().countries().await?;
if !res.enabled {
// sending a proxy spec would fail on this gateway
}
println!("{:?}", res.countries); // ["br", "de", "gb", "us"]ConnectedBrowser
A chromiumoxide Browser attached to a session over CDP, plus the spawned task pumping its event handler. Behind the connect feature.
Fields
browserchromiumoxide::Browser: the attached browser. Drive it with the usual chromiumoxide API.handlerJoinHandle<()>: the handler pump. It must keep running for as long as the browser is used. Everybrowsercall resolves through it. It does not stop whenbrowseris dropped; abort it (or call disconnect()).
ws_endpoint) path only. Attaching over raw CDP (which is what Rust does) bypasses that layer, so clicks are single-shot teleport-and-press. That is exactly the tell interaction-triggered anti-bots score. Expect lower pass rates on behaviourally-gated sites than the TypeScript SDK gets.Functions
connect()
async fn connect(session: &Session) -> Result<ConnectedBrowser, SolariError>Attaches to session.cdp_endpoint and spawns the handler pump. A free function on the crate root, not a method.
Parameters:
session&Session: the acquired session.
Returns: Result<ConnectedBrowser, SolariError>
Errors: SolariError::Connect if the CDP attach fails.
Example:
let session = client
.sessions()
.create(CreateSessionOptions::new().stealth(true))
.await?;
let connected = solari_browser::connect(&session).await?;
let page = connected.browser.new_page("https://example.com").await?;
println!("{:?}", page.url().await?);
connected.disconnect().await;
client.sessions().release(&session.id).await?;wss://. features = ["connect"] turns on a rustls backend for the WebSocket that chromiumoxide uses (solari-browser 0.5.0 and later), so you do not add a TLS dependency yourself. On 0.4 and earlier, connect() failed with "TLS support not compiled in" unless you added async-tungstenite with a TLS feature to your own Cargo.toml.connect_endpoint()
async fn connect_endpoint(cdp_endpoint: &str) -> Result<ConnectedBrowser, SolariError>Attaches to an explicit CDP endpoint. Use it when you persisted a session’s cdp_endpoint and no longer hold the Session.
Parameters:
cdp_endpoint&str: the upstream CDP URL.
Returns: Result<ConnectedBrowser, SolariError>
Errors: SolariError::Connect if the attach fails.
Example:
let connected = solari_browser::connect_endpoint(&saved_cdp_url).await?;into_parts()
fn into_parts(self) -> (Browser, JoinHandle<()>)Splits into the browser and its handler task, when you want to own the two separately. You then own the shutdown too: the handler task does not end by itself when the browser is dropped. It keeps pumping the open WebSocket, so awaiting it without aborting it first hangs forever. Use disconnect() unless you need the split.
Returns: (chromiumoxide::Browser, JoinHandle<()>)
Example:
let (browser, handler) = connected.into_parts();
// … drive the browser
drop(browser); // drop the browser first,
handler.abort(); // then stop the handler task; this closes the CDP connection
let _ = handler.await; // returns at once with a cancelled JoinError, ignore itdisconnect()
async fn disconnect(self)Drops the browser, aborts the handler task (which closes the CDP connection) and awaits it. Does not release the Solari session.
Returns: ()
Example:
connected.disconnect().await; // closes the connection
client.sessions().release(&session.id).await?; // frees the slotClient::launch()
async fn launch(&self, opts: LaunchOptions) -> Result<LaunchedSession, SolariError>One call that creates a session, attaches to it over CDP, seeds an attached profile’s cookies, health-probes the browser, retries the whole start on a transient failure, and releases the session when you close the handle. Behind the connect feature. It is a thin wrapper over connect(): you get the same chromiumoxide Browser and drive it yourself, not a Playwright object model.
LaunchOptions::new(CreateSessionOptions), then.retries(n)(extra attempts on a transient failure; default 0),.probe(bool)(default: probe only whenretries > 0) and.probe_timeout_ms(ms)(default 15000 from 0.6.1; 2000 in 0.6.0).LaunchedSession: thebrowserfield,session()for the underlying Session, andclose().await, which disconnects and releases. Dropping it without closing releases on a best-effort basis if a Tokio runtime is still running, so preferclose().- Only an attached profile’s cookies are seeded.
localStorageis not.
use solari_browser::{CreateSessionOptions, LaunchOptions};
let launched = client
.launch(LaunchOptions::new(CreateSessionOptions::new().stealth(true)).retries(2))
.await?;
let page = launched.browser.new_page("https://example.com").await?;
println!("{:?}", page.url().await?);
launched.close().await?; // disconnects and releases the session1) can take a few seconds on a stealth session that is still warming up. Version 0.6.0 bounded it at 2 s and could fail a healthy launch; from 0.6.1 the default probe_timeout_ms is 15000. On 0.6.0, raise .probe_timeout_ms(…) if launch() keeps failing with “health probe timed out”.Types
ClientOptions
Three constructors, then chainable builders. Reads no environment variables.
ClientOptions::new(api_key, base_url) // explicit gateway
ClientOptions::for_region(api_key, region) // a region's public API
ClientOptions::default_region(api_key) // SolariRegion::UsWest
ClientOptions::default_region(&api_key)
.max_attempts(3)
.backoff_ms(250)
.timeout_ms(30_000)api_keyString: required; empty is rejected.base_urlString: required; trailing slash stripped.max_attemptsu32: default2(one retry). Clamped to a minimum of 1.backoff_msu64: default500, fixed.timeout_msu64: default90_000, per attempt.
InsufficientCapacity, kept so the client is correct regardless of which gateway build it reaches. A response whose body says retryable: true is retried too, and one that says retryable: false never is. Every other non-2xx, including a 500, is returned immediately. ConcurrencyLimitExceeded (429) is not retried. Match on SolariError::Api and back off yourself.CreateSessionOptions
Builder-style. Falsy fields are omitted from the request body; if every field is falsy, no body is sent at all.
CreateSessionOptions::new()
.stealth(true)
.captcha(true)
.recording(true)
.profile_id("p_123")
.proxy(ProxySpec::country("us"))
.session_timeout_ms(600_000)
.keep_alive(true)profile_idOption<String>: attach a stored profile. Empty strings are omitted.recordingbool: record the session. Off by default.stealthbool: enable the runtime stealth shim. Off by default.captchabool: managed captcha solving. Requiresstealth.proxyOption<ProxySpec>: managed egress. Requiresstealth.session_timeout_msOption<u64>: end the session earlier than your plan’s maximum. The gateway counts whole seconds, so the value is rounded up (1001 ms is 2 s), and it refuses anything under 60 s. Unset or zero keeps the plan maximum. (The oldertimeout_secondsis deprecated; this one wins when both are set.)keep_alivebool: keep the session when the client disconnects, so it can reconnect. The hold endssession_timeout_msafter the session was created (an hour after creation when unset, never past the plan maximum) or when it is released;expires_atis the hard deadline, not the hold. A host can be replaced by scale-in or repair, which ends the sessions on it.user_metadataOption<serde_json::Map<String, Value>>: free-form JSON stored with the session. It comes back onSession::user_metadata, on SessionView from get() and on every row of list(), where you can also filter by it.
Session
idString: session id.ws_endpointString: Playwright wire-protocol endpoint.cdp_endpointString: raw CDP endpoint, the one to use from Rust. Derived fromws_endpoint(/ws/→/cdp/) when the API omits it.expires_atString: ISO 8601 UTC deadline; the session auto-releases then. Falls back to ~1h from now when the API omits it.storage_stateOption<Option<StorageState>>: tri-state; see below.proxyOption<ResolvedProxyConfig>: present only when a managed proxy was requested.user_metadataOption<Map<String, Value>>: an echo of what you sent at create;Nonewhen you sent none.
wsEndpoint / cdpEndpoint through a Node-side loopback proxy. This crate has no such indirection: both fields are the upstream gateway endpoints, reachable from anywhere with the session still live. You can persist them and hand them to another machine.storage_state is a serde double-option, mirroring the TypeScript storageState?: StorageState | null. It is only populated when a profile was requested:
match &session.storage_state {
None => {} // no profile attached to this session
Some(None) => {} // profile attached, but it has no saved state yet
Some(Some(state)) => { // the profile's state
println!("{} cookies", state.cookies.as_ref().map_or(0, |c| c.len()));
}
}SessionView
Returned by get(). Every field is optional because the API proxies the pool’s view through verbatim.
id,session_id(the older key for the same value),status,kind("fast"or"stealth"),org,created_at,expires_at, and, while the session is active,ws_endpointandcdp_endpoint: all Option<String>.user_metadataOption<Map<String, Value>>: what you sent at create;Nonewhen you sent none.extraMap<String, Value>:#[serde(flatten)]; every key the crate does not model survives here rather than being dropped.
StorageState
cookiesOption<Vec<Cookie>>: eachCookiehasname,value, and optionaldomain,path,expires,http_only,secure,same_site.originsOption<Vec<StorageOrigin>>: each hasoriginand optionallocal_storage(Vec<LocalStorageEntry>ofname/value).extraMap<String, Value>: flattened unknown keys.SameSite:Strict,Lax,None.
ProxySpec
The proxy field of a create request. Mirrors the TypeScript union string | ProxyRequest | "off" | "smart".
ProxySpec::country("us") // proxy: "us"
ProxySpec::off() // proxy: "off"
ProxySpec::smart() // proxy: "smart", gateway sweeps strategies on block
ProxySpec::from(ProxyRequest::country("us").tier(ProxyTier::Static))Shorthand(String): a country code, or the literals"off"/"smart".Request(ProxyRequest): a full egress request.From<ProxyRequest>is implemented, so.proxy(req)takes either directly.
ProxyRequest
Builder-style; unset fields are omitted from the wire.
ProxyRequest::country("us")
.tier(ProxyTier::Mobile)
.asn("21928")
.session("warm-1")
.session_duration(15)countryOption<String>: ISO-3166-1 alpha-2, lowercase. Defaults to"us"server-side.tierOption<ProxyTier>:Residential(default, rotating),Static(fixed ISP IP),Mobile(carrier IPs).asnOption<String>: pin egress to an ASN, e.g."20057"for AT&T Mobility.sessionOption<String>: sticky-session id (any label of 1 to 128 characters; the same label gets the same exit IP). Pins the egress IP.session_durationOption<u32>: sticky lifetime in minutes (1 to 30, default 10). Only withsession.state,cityOption<String>: US-only geo narrowing, e.g."california"/"los_angeles". State takes a name or a two-letter code; one the tier can’t serve returns a 400. See Picking a US state.
ResolvedProxyConfig
A coarse confirmation of the proxy the gateway chose. It carries no proxy address or credentials: egress is applied server-side, so you never dial the proxy. There are no server, username or password fields to read.
timezone_idString: timezone matching the egress IP.countryString,tierOption<ProxyTier>: what the gateway actually resolved.
ProxyCountries
enabledbool: false when managed proxy is unavailable; sending aproxyspec will then fail.countriesVec<String>: supported lowercase alpha-2 codes.
Profile / ProfileSaveResult
Profile:idString,nameString,versionu64 (increases on every save;0when omitted),extraMap<String, Value> (flattened unknown keys).ProfileSaveResult:versionu64,size_bytesu64. Both0when the API omits them.
ReplayUrl
urlString: presigned download URL.expires_in_secondsu64: URL lifetime;0when omitted.content_encodingString:"gzip"when omitted.
SolariRegion
UsWest(default): resolves tohttps://api.getsolari.com. The only region today; read it withregion.base_url().
SolariError
Every failure the crate raises. Derives thiserror::Error.
| Variant | Fields | Meaning |
|---|---|---|
Api | status, code, message | A non-2xx response from the API. |
Transport | message | Network failure, or retries exhausted. |
Protocol | message | A 2xx body missing required fields, or not JSON. |
Config | message | The client was constructed with invalid options. |
Connect | message | CDP attach failed. Only with the connect feature. |
Two accessors read across variants: .status() → Option<u16> and .code() → Option<&SolariErrorCode>, both None for non-Api variants.
SolariErrorCode
Parsed out of the API’s { "code": … } error body. Unknown codes are preserved in Other(String) rather than dropped, so the wire can grow new codes without breaking the crate.
FeatureRequiresPlan: the plan does not include the feature (e.g. captcha).ConcurrencyLimitExceeded: at the concurrent-session cap.PlanLimitExceeded: a plan quota is exhausted.BrowserUnhealthy: the acquired browser failed its health check.InvalidSessionId: the gateway refused a session id and acted on nothing (see release()).ProxyTierUnavailable: a 503 on create. A proxy tier you asked for explicitly cannot be served right now; no session was created, and the client does not retry it.Other(String): a code this crate does not know.
use solari_browser::{SolariError, SolariErrorCode};
match client.sessions().create(opts).await {
Ok(session) => { /* … */ }
Err(e) if e.code() == Some(&SolariErrorCode::FeatureRequiresPlan) => {
eprintln!("upgrade required: {:?}", e.status());
}
Err(SolariError::Transport { message }) => eprintln!("retry later: {message}"),
Err(e) => return Err(e),
}
