Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: asyncpg socket callback #923

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions google/cloud/sql/connector/asyncpg.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@
See the License for the specific language governing permissions and
limitations under the License.
"""
import asyncio
import contextvars
import functools
import socket
import ssl
from typing import Any, TYPE_CHECKING

Expand All @@ -22,6 +26,10 @@
import asyncpg


def sock_func(ip_address: str) -> socket.socket:
return socket.create_connection((ip_address, SERVER_PROXY_PORT))


async def connect(
ip_address: str, ctx: ssl.SSLContext, **kwargs: Any
) -> "asyncpg.Connection":
Expand All @@ -48,6 +56,14 @@ async def connect(
raise ImportError(
'Unable to import module "asyncpg." Please install and try again.'
)

async def async_sock_func() -> socket.socket:
# TODO: switch to asyncio.to_thread once Python 3.8 support is dropped
loop = asyncio.get_running_loop()
ctx_vars = contextvars.copy_context()
func_call = functools.partial(ctx_vars.run, sock_func, ip_address)
return await loop.run_in_executor(None, func_call) # type: ignore

user = kwargs.pop("user")
db = kwargs.pop("db")
passwd = kwargs.pop("password", None)
Expand All @@ -56,9 +72,7 @@ async def connect(
user=user,
database=db,
password=passwd,
host=ip_address,
port=SERVER_PROXY_PORT,
ssl=ctx,
direct_tls=True,
socket_callback=async_sock_func,
**kwargs,
)
2 changes: 1 addition & 1 deletion requirements-test.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@ types-mock==5.1.0.3
twine==4.0.2
PyMySQL==1.1.0
pg8000==1.30.3
asyncpg==0.29.0
git+https://github.com/jackwotherspoon/asyncpg.git@ff82aab23435d86ddccb0b553c2f116be11013a9
python-tds==1.13.0
aioresponses==0.7.6