text
stringlengths
0
1.47k
def sessions() -> dict[str, Session]:
return _SESSIONS
def _record(sid: str, hid: str, org: str, workspace: str, allow: list[str], deny: list[str], d: dict,
reserved: float) -> dict:
now = time.time()
return {"sid": sid, "hid": hid, "org": org, "workspace": workspace, "allow": list(allow), "deny": list(deny),
"vendor_id": str(d["id"]), "cdp_url": str(d["cdpUrl"]), "live_url": str(d.get("liveUrl") or ""),
"created": now, "last_used": now, "calls": 0, "screenshots": 0, "blocked": [],
"reserved": float(reserved)}
async def _connect(cdp_url: str):
global _pw
if connector is not None:
return await connector(cdp_url)
from playwright.async_api import async_playwright
if _pw is None:
_pw = await async_playwright().start()
return await _pw.chromium.connect_over_cdp(cdp_url, timeout=30000)
async def _allowed(s: Session, url: str) -> str | None:
"""Why this URL may not be requested from this session, or None; resolved once per host."""
try:
u = urllib.parse.urlsplit(url)
except ValueError:
return "not a valid address"
if u.scheme not in ("http", "https"):
return f"a {u.scheme or 'non-web'} address" if u.scheme not in ("about", "data", "blob") else None
host = u.hostname or ""
own = not s.vendor_id # the operator's own browser, on the operator's own network
why = host_policy(host, s.allow, s.deny, private_ok=own)
if why:
return why
if own:
return None
if host not in s.host_cache:
s.host_cache[host] = await resolves_private(host)
return "a private or local address" if s.host_cache[host] else None
async def open_session(sid: str, hid: str, org: str, workspace: str, allow: list[str], deny: list[str],
reserved: float = 0.0) -> Session:
"""The session's browser, attached here: the recorded one when there is one, else a new one at
the vendor, recorded for every process first. One opener at a time across processes: the
others wait for its record. `opened` on the result says this call made the browser."""
if not configured():
raise BrowserRefused("not_configured", "The browser service is not set up on this deployment. Tell the person.")
rec = await registry.get(sid)
locked = False
if rec is None:
for _ in range(60):
if await registry.lock(sid, 30):
locked = True
break
await asyncio.sleep(0.5)
rec = await registry.get(sid)
if rec is not None:
break
else:
raise BrowserRefused("busy", "The browser is still being started. Try again in a moment.")
opened = False
try:
if rec is None:
live = await registry.all()
if sum(1 for x in live if x.get("org") == org) >= ORG_SESSIONS:
raise BrowserRefused("org_busy", f"This account already has {ORG_SESSIONS} browsers open. Try again when one of them finishes.")
if len(live) >= MAX_SESSIONS:
raise BrowserRefused("busy", "Every browser is in use right now. Try again in a minute.")
d = await vendor_create(SESSION_CAP_MIN, {"harness": hid, "session": sid})
rec = _record(sid, hid, org, workspace, allow, deny, d, reserved)
if await registry.create(sid, rec):
opened = True
else:
# Made elsewhere between the lock and here (a lock the store could not keep): theirs stands.
try:
await vendor_stop(rec["vendor_id"])
except Exception: # noqa: BLE001
pass
rec = await registry.get(sid)
if rec is None:
raise BrowserRefused("busy", "The browser could not be started. Try again.")
finally:
if locked:
await registry.unlock(sid)
try:
s = await attach(rec)
except Exception:
if opened: # a browser nobody can reach: not left for the reaper
await registry.delete(sid)
try:
await vendor_stop(rec["vendor_id"])
except Exception: # noqa: BLE001
pass
raise
s.opened = opened
return s