| 1 |
import math |
| 2 |
import trio |
| 3 |
|
| 4 |
from ..ldapconnection import BaseLDAPConnection, LDAPSearchScope |
| 5 |
from ..errors import NotAllowedOnNonleaf, TimeoutError |
| 6 |
|
| 7 |
|
| 8 |
class TrioLDAPConnection(BaseLDAPConnection): |
| 9 |
""" |
| 10 |
Asynchronous LDAP connection object that works with trio. |
| 11 |
It has the same methods and properties as :class:`bonsai.LDAPConnection`, but |
| 12 |
with the exception of :meth:`bonsai.LDAPConnection.close` and |
| 13 |
:meth:`bonsai.LDAPConnection.fileno` all of them are awaitable. |
| 14 |
|
| 15 |
:param LDAPClient client: a client object. |
| 16 |
""" |
| 17 |
|
| 18 |
def __init__(self, client): |
| 19 |
self.__open_coro = None |
| 20 |
super().__init__(client, is_async=True) |
| 21 |
|
| 22 |
async def __aenter__(self): |
| 23 |
"""Async context manager entry point.""" |
| 24 |
return await self.__open_coro |
| 25 |
|
| 26 |
async def __aexit__(self, type, value, traceback): |
| 27 |
"""Async context manager exit point.""" |
| 28 |
self.close() |
| 29 |
|
| 30 |
def __await__(self): |
| 31 |
return self.__open_coro.__await__() |
| 32 |
|
| 33 |
def open(self, timeout=None): |
| 34 |
self.__open_coro = super().open(timeout) |
| 35 |
return self |
| 36 |
|
| 37 |
async def _poll(self, msg_id, timeout=None): |
| 38 |
tout_sec = timeout if timeout is not None else math.inf |
| 39 |
with trio.move_on_after(tout_sec): |
| 40 |
while True: |
| 41 |
await trio.lowlevel.wait_writable(self) |
| 42 |
await trio.lowlevel.wait_readable(self) |
| 43 |
res = super().get_result(msg_id) |
| 44 |
if res is not None: |
| 45 |
return res |
| 46 |
raise TimeoutError("Timeout is exceeded") |
| 47 |
|
| 48 |
def _evaluate(self, msg_id, timeout=None): |
| 49 |
return self._poll(msg_id, timeout) |
| 50 |
|
| 51 |
async def delete(self, dname, timeout=None, recursive=False): |
| 52 |
try: |
| 53 |
return await super().delete(dname, timeout, recursive) |
| 54 |
except NotAllowedOnNonleaf as exc: |
| 55 |
if recursive: |
| 56 |
results = await self.search( |
| 57 |
dname, LDAPSearchScope.ONELEVEL, attrlist=["1.1"], timeout=timeout |
| 58 |
) |
| 59 |
for res in results: |
| 60 |
await self.delete(res.dn, timeout, True) |
| 61 |
return await self.delete(dname, timeout, False) |
| 62 |
else: |
| 63 |
raise exc |
| 64 |
|
| 65 |
async def _search_iter_anext(self, search_iter): |
| 66 |
try: |
| 67 |
return next(search_iter) |
| 68 |
except StopIteration: |
| 69 |
msgid = search_iter.acquire_next_page() |
| 70 |
if msgid is None: |
| 71 |
raise StopAsyncIteration from None |
| 72 |
search_iter = await self._evaluate(msgid) |
| 73 |
return next(search_iter) |
| 74 |
|
| 75 |
async def get_result(self, msg_id, timeout=None): |
| 76 |
return await self._evaluate(msg_id, timeout) |