|
2 | 2 |
|
3 | 3 | from __future__ import annotations
|
4 | 4 |
|
| 5 | +from asyncio import Lock |
5 | 6 | from datetime import datetime, timedelta, timezone
|
6 | 7 | from typing import TYPE_CHECKING, Any, cast
|
7 | 8 |
|
@@ -77,6 +78,29 @@ def __init__(
|
77 | 78 |
|
78 | 79 | self._total_opened_pages = 0
|
79 | 80 |
|
| 81 | + self._context_creation_lock: Lock | None = None |
| 82 | + |
| 83 | + |
| 84 | + async def _get_context_creation_lock(self) -> Lock: |
| 85 | + """Context checking and creation should be done with lock to prevent multiple attempts to create context.""" |
| 86 | + if self._context_creation_lock: |
| 87 | + return self._context_creation_lock |
| 88 | + self._context_creation_lock= Lock() |
| 89 | + return self._context_creation_lock |
| 90 | + |
| 91 | + async def ensure_browser_context(self, |
| 92 | + browser_new_context_options: Mapping[str, Any] | None = None, |
| 93 | + proxy_info: ProxyInfo | None = None, |
| 94 | + ) -> None: |
| 95 | + async with await self._get_context_creation_lock(): |
| 96 | + if not self._browser_context: |
| 97 | + self._browser_context = await self._create_browser_context( |
| 98 | + browser_new_context_options=browser_new_context_options, |
| 99 | + proxy_info=proxy_info, |
| 100 | + ) |
| 101 | + |
| 102 | + |
| 103 | + |
80 | 104 | @property
|
81 | 105 | @override
|
82 | 106 | def pages(self) -> list[Page]:
|
|
0 commit comments