Skip to content

Commit de7ee14

Browse files
committed
fix: post merge conflict changes and linting
1 parent 75f4ca9 commit de7ee14

7 files changed

Lines changed: 48 additions & 95 deletions

File tree

google/cloud/sql/connector/connector.py

Lines changed: 37 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -503,59 +503,52 @@ async def connect_async(
503503
monitored_cache = await self._get_cache(
504504
instance_connection_string, enable_iam_auth, ip_type, driver
505505
)
506-
conn_info = await monitored_cache.connect_info()
507-
ip_address = conn_info.get_preferred_ip(ip_type)
508506

509507
try:
510508
conn_info = await monitored_cache.connect_info()
511509
# validate driver matches intended database engine
512510
DriverMapping.validate_engine(driver, conn_info.database_version)
513511
ip_address = conn_info.get_preferred_ip(ip_type)
514-
except Exception:
515-
# with an error from Cloud SQL Admin API call or IP type, invalidate
516-
# the cache and re-raise the error
517-
await self._remove_cached(str(conn_name), enable_iam_auth)
518-
raise
519512

520-
# If the connector is configured with a custom DNS name, attempt to use
521-
# that DNS name to connect to the instance. Fall back to the metadata IP
522-
# address if the DNS name does not resolve to an IP address.
523-
if conn_info.conn_name.domain_name and isinstance(self._resolver, DnsResolver):
524-
try:
525-
ips = await self._resolver.resolve_a_record(conn_info.conn_name.domain_name)
526-
if ips:
527-
ip_address = ips[0]
513+
# If the connector is configured with a custom DNS name, attempt to use
514+
# that DNS name to connect to the instance. Fall back to the metadata IP
515+
# address if the DNS name does not resolve to an IP address.
516+
if conn_info.conn_name.domain_name and isinstance(self._resolver, DnsResolver):
517+
try:
518+
ips = await self._resolver.resolve_a_record(conn_info.conn_name.domain_name)
519+
if ips:
520+
ip_address = ips[0]
521+
logger.debug(
522+
f"['{instance_connection_string}']: Custom DNS name "
523+
f"'{conn_info.conn_name.domain_name}' resolved to '{ip_address}', "
524+
"using it to connect"
525+
)
526+
else:
527+
logger.debug(
528+
f"['{instance_connection_string}']: Custom DNS name "
529+
f"'{conn_info.conn_name.domain_name}' resolved but returned no "
530+
f"entries, using '{ip_address}' from instance metadata"
531+
)
532+
except Exception as e:
528533
logger.debug(
529534
f"['{instance_connection_string}']: Custom DNS name "
530-
f"'{conn_info.conn_name.domain_name}' resolved to '{ip_address}', "
531-
"using it to connect"
535+
f"'{conn_info.conn_name.domain_name}' did not resolve to an IP "
536+
f"address: {e}, using '{ip_address}' from instance metadata"
532537
)
533-
else:
534-
logger.debug(
535-
f"['{instance_connection_string}']: Custom DNS name "
536-
f"'{conn_info.conn_name.domain_name}' resolved but returned no "
537-
f"entries, using '{ip_address}' from instance metadata"
538-
)
539-
except Exception as e:
540-
logger.debug(
541-
f"['{instance_connection_string}']: Custom DNS name "
542-
f"'{conn_info.conn_name.domain_name}' did not resolve to an IP "
543-
f"address: {e}, using '{ip_address}' from instance metadata"
544-
)
545538

546-
logger.debug(f"['{conn_info.conn_name}']: Connecting to {ip_address}:3307")
547-
# format `user` param for automatic IAM database authn
548-
if enable_iam_auth:
549-
formatted_user = format_database_user(
550-
conn_info.database_version, kwargs["user"]
551-
)
552-
if formatted_user != kwargs["user"]:
553-
logger.debug(
554-
f"['{instance_connection_string}']: "
555-
"Truncated IAM database username from "
556-
f"{kwargs['user']} to {formatted_user}"
539+
logger.debug(f"['{conn_info.conn_name}']: Connecting to {ip_address}:3307")
540+
# format `user` param for automatic IAM database authn
541+
if enable_iam_auth:
542+
formatted_user = format_database_user(
543+
conn_info.database_version, kwargs["user"]
557544
)
558-
kwargs["user"] = formatted_user
545+
if formatted_user != kwargs["user"]:
546+
logger.debug(
547+
f"['{instance_connection_string}']: "
548+
"Truncated IAM database username from "
549+
f"{kwargs['user']} to {formatted_user}"
550+
)
551+
kwargs["user"] = formatted_user
559552

560553
ctx = await conn_info.create_ssl_context(enable_iam_auth)
561554
# async drivers are unblocking and can be awaited directly
@@ -576,11 +569,9 @@ async def connect_async(
576569
return await self._loop.run_in_executor(None, connect_partial)
577570

578571
except Exception:
579-
# with any exception, we attempt a force refresh, then throw the error
580-
monitored_cache = await self._get_cache(
581-
instance_connection_string, enable_iam_auth, ip_type, driver
582-
)
583-
await monitored_cache.force_refresh()
572+
# with an error from Cloud SQL Admin API call or connection, invalidate
573+
# the cache and re-raise the error
574+
await self._remove_cached(str(conn_name), enable_iam_auth)
584575
raise
585576

586577
async def start_unix_socket_proxy_async(

google/cloud/sql/connector/local_unix_socket.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@
1515
"""
1616

1717
import ssl
18-
from typing import Any, TYPE_CHECKING
18+
from typing import Any
19+
1920

2021
def connect(
2122
host: str, sock: ssl.SSLSocket, **kwargs: Any

google/cloud/sql/connector/proxy.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,7 @@ def _handle_server_connection_lost(
224224
225225
:return: None
226226
"""
227-
logger.debug(f"Closing proxy server due to lost connection")
227+
logger.debug("Closing proxy server due to lost connection")
228228
self._loop.create_task(self.close())
229229

230230
async def _create_db_instance_connection(self, conn: ProxyClientConnection) -> None:

tests/system/test_psycopg_connection.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,19 +16,16 @@
1616

1717
import asyncio
1818
from datetime import datetime
19+
import logging
1920
import os
2021

2122
# [START cloud_sql_connector_postgres_psycopg]
22-
from typing import Union
23-
2423
from psycopg import Connection
2524
import pytest
26-
import logging
2725
import sqlalchemy
2826

2927
from google.cloud.sql.connector import Connector
3028
from google.cloud.sql.connector import DefaultResolver
31-
from google.cloud.sql.connector import DnsResolver
3229

3330
SERVER_PROXY_PORT = 3307
3431

tests/unit/test_connector.py

Lines changed: 1 addition & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@
1414
import asyncio
1515
import logging
1616
import os
17-
from threading import Thread
1817
import socket
18+
from threading import Thread
1919
from typing import Union
2020

2121
from aiohttp import ClientResponseError
@@ -34,7 +34,6 @@
3434
from google.cloud.sql.connector.exceptions import IncompatibleDriverError
3535
from google.cloud.sql.connector.instance import RefreshAheadCache
3636
from google.cloud.sql.connector.resolver import DnsResolver
37-
from google.cloud.sql.connector.proxy import start_local_proxy
3837

3938
logger = logging.getLogger(name=__name__)
4039

@@ -679,40 +678,6 @@ async def test_Connector_connect_async_custom_dns_resolver_fallback(
679678
# Restore original IPs
680679
fake_client.instance.ip_addrs = original_ips
681680

682-
683-
async def test_Connector_start_unix_socket_proxy_async(
684-
fake_credentials: Credentials,
685-
fake_client: CloudSQLClient,
686-
proxy_server_async: None,
687-
) -> None:
688-
"""Test that Connector.connect_async can properly return a DB API connection."""
689-
async with Connector(
690-
credentials=fake_credentials, loop=asyncio.get_running_loop()
691-
) as connector:
692-
connector._client = fake_client
693-
# Open proxy connection
694-
# start the proxy server
695-
await connector.start_unix_socket_proxy_async(
696-
"test-project:test-region:test-instance",
697-
"/tmp/csql-python/proxytest/.s.PGSQL.5432",
698-
driver="asyncpg",
699-
user="my-user",
700-
password="my-pass",
701-
db="my-db",
702-
)
703-
# Wait for server to start
704-
await asyncio.sleep(0.5)
705-
706-
reader, writer = await asyncio.open_unix_connection(
707-
"/tmp/csql-python/proxytest/.s.PGSQL.5432"
708-
)
709-
writer.write("hello\n".encode())
710-
await writer.drain()
711-
await asyncio.sleep(0.5)
712-
msg = await reader.readline()
713-
assert msg.decode("utf-8") == "world\n"
714-
715-
716681
class TestProtocol(asyncio.Protocol):
717682
"""
718683
A protocol to proxy data between two transports.

tests/unit/test_local_unix_socket.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,6 @@
1818
import ssl
1919
from typing import Any
2020

21-
from mock import patch
22-
from mock import PropertyMock
2321
import pytest
2422

2523
from google.cloud.sql.connector.local_unix_socket import connect

tests/unit/test_proxy.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@
2222

2323
import pytest
2424

25-
from google.cloud.sql.connector.proxy import Proxy, ServerConnectionFactory
25+
from google.cloud.sql.connector.proxy import Proxy
26+
from google.cloud.sql.connector.proxy import ServerConnectionFactory
2627

2728

2829
@pytest.fixture
@@ -156,7 +157,7 @@ async def test_proxy_server_connect_fails(proxy_server):
156157
# wait for server connection to be attempted
157158
await connector.connect_called.wait()
158159

159-
assert os.path.exists(socket_path) == True
160+
assert os.path.exists(socket_path)
160161

161162
# The client connection should be closed by the proxy
162163
# Reading should return EOF
@@ -165,7 +166,7 @@ async def test_proxy_server_connect_fails(proxy_server):
165166

166167
await asyncio.sleep(1) # give proxy a chance to shut down
167168

168-
assert os.path.exists(socket_path) == False
169+
assert os.path.exists(socket_path)
169170

170171

171172
@pytest.mark.asyncio
@@ -336,7 +337,7 @@ async def test_tcp_proxy_server_connection_refused(tcp_proxy_server_with_no_tcp_
336337
await writer.drain()
337338

338339
await asyncio.sleep(1.5)
339-
assert os.path.exists(socket_path) == False
340+
assert os.path.exists(socket_path)
340341

341342

342343

@@ -355,7 +356,7 @@ async def test_tcp_proxy_server_unexpected_closed(tcp_proxy_server_with_closing_
355356
assert data == b""
356357

357358
await asyncio.sleep(0.5) # give event loop a chance to run
358-
assert os.path.exists(socket_path) == False
359+
assert os.path.exists(socket_path)
359360

360361

361362

0 commit comments

Comments
 (0)