|
| 1 | +import asyncio |
1 | 2 | import typing
|
| 3 | +from collections.abc import Coroutine |
2 | 4 |
|
3 | 5 | import wrapt
|
4 |
| -from aiopg.utils import _ContextManager, _PoolAcquireContextManager |
5 | 6 |
|
6 | 7 | from opentelemetry.instrumentation.dbapi import (
|
7 | 8 | CursorTracer,
|
@@ -150,3 +151,78 @@ async def callproc(self, *args, **kwargs):
|
150 | 151 | return result
|
151 | 152 |
|
152 | 153 | return AsyncCursorTracerProxy(cursor, *args, **kwargs)
|
| 154 | + |
| 155 | + |
| 156 | +class _ContextManager(Coroutine): |
| 157 | + __slots__ = ("_coro", "_obj") |
| 158 | + |
| 159 | + def __init__(self, coro): |
| 160 | + self._coro = coro |
| 161 | + self._obj = None |
| 162 | + |
| 163 | + def send(self, value): |
| 164 | + return self._coro.send(value) |
| 165 | + |
| 166 | + def throw(self, typ, val=None, tb=None): |
| 167 | + if val is None: |
| 168 | + return self._coro.throw(typ) |
| 169 | + if tb is None: |
| 170 | + return self._coro.throw(typ, val) |
| 171 | + return self._coro.throw(typ, val, tb) |
| 172 | + |
| 173 | + def close(self): |
| 174 | + return self._coro.close() |
| 175 | + |
| 176 | + @property |
| 177 | + def gi_frame(self): |
| 178 | + return self._coro.gi_frame |
| 179 | + |
| 180 | + @property |
| 181 | + def gi_running(self): |
| 182 | + return self._coro.gi_running |
| 183 | + |
| 184 | + @property |
| 185 | + def gi_code(self): |
| 186 | + return self._coro.gi_code |
| 187 | + |
| 188 | + def __next__(self): |
| 189 | + return self.send(None) |
| 190 | + |
| 191 | + def __await__(self): |
| 192 | + resp = self._coro.__await__() |
| 193 | + return resp |
| 194 | + |
| 195 | + async def __aenter__(self): |
| 196 | + self._obj = await self._coro |
| 197 | + return self._obj |
| 198 | + |
| 199 | + async def __aexit__(self, exc_type, exc, t_b): |
| 200 | + try: |
| 201 | + if asyncio.iscoroutinefunction(self._obj.close): |
| 202 | + await self._obj.close() |
| 203 | + else: |
| 204 | + self._obj.close() |
| 205 | + finally: |
| 206 | + self._obj = None |
| 207 | + |
| 208 | + |
| 209 | +class _PoolContextManager(_ContextManager): |
| 210 | + __slots__ = () |
| 211 | + |
| 212 | + async def __aexit__(self, exc_type, exc, tb): |
| 213 | + self._obj.close() |
| 214 | + await self._obj.wait_closed() |
| 215 | + self._obj = None |
| 216 | + |
| 217 | + |
| 218 | +class _PoolAcquireContextManager(_ContextManager): |
| 219 | + __slots__ = ("_coro", "_obj", "_pool") |
| 220 | + |
| 221 | + def __init__(self, coro, pool): |
| 222 | + super().__init__(coro) |
| 223 | + self._pool = pool |
| 224 | + |
| 225 | + async def __aexit__(self, exc_type, exc, tb): |
| 226 | + await self._pool.release(self._obj) |
| 227 | + self._pool = None |
| 228 | + self._obj = None |
0 commit comments