2121from datetime import timedelta
2222from datetime import timezone
2323import logging
24- import re
2524
2625import aiohttp
2726
2827from google .cloud .sql .connector .client import CloudSQLClient
2928from google .cloud .sql .connector .connection_info import ConnectionInfo
29+ from google .cloud .sql .connector .connection_name import _parse_instance_connection_name
3030from google .cloud .sql .connector .exceptions import RefreshNotValidError
3131from google .cloud .sql .connector .rate_limiter import AsyncRateLimiter
3232from google .cloud .sql .connector .refresh_utils import _is_valid
3636
3737APPLICATION_NAME = "cloud-sql-python-connector"
3838
39- # Instance connection name is the format <PROJECT>:<REGION>:<INSTANCE>
40- # Additionally, we have to support legacy "domain-scoped" projects
41- # (e.g. "google.com:PROJECT")
42- CONN_NAME_REGEX = re .compile (("([^:]+(:[^:]+)?):([^:]+):([^:]+)" ))
43-
44-
45- def _parse_instance_connection_name (connection_name : str ) -> tuple [str , str , str ]:
46- if CONN_NAME_REGEX .fullmatch (connection_name ) is None :
47- raise ValueError (
48- "Arg `instance_connection_string` must have "
49- "format: PROJECT:REGION:INSTANCE, "
50- f"got { connection_name } ."
51- )
52- connection_name_split = CONN_NAME_REGEX .split (connection_name )
53- return connection_name_split [1 ], connection_name_split [3 ], connection_name_split [4 ]
54-
5539
5640class RefreshAheadCache :
5741 """Cache that refreshes connection info in the background prior to expiration.
@@ -81,10 +65,13 @@ def __init__(
8165 connections.
8266 """
8367 # validate and parse instance connection name
84- self ._project , self ._region , self ._instance = _parse_instance_connection_name (
85- instance_connection_string
68+ conn_name = _parse_instance_connection_name (instance_connection_string )
69+ self ._project , self ._region , self ._instance = (
70+ conn_name .project ,
71+ conn_name .region ,
72+ conn_name .instance_name ,
8673 )
87- self ._instance_connection_string = instance_connection_string
74+ self ._conn_name = conn_name
8875
8976 self ._enable_iam_auth = enable_iam_auth
9077 self ._keys = keys
@@ -121,8 +108,7 @@ async def _perform_refresh(self) -> ConnectionInfo:
121108 """
122109 self ._refresh_in_progress .set ()
123110 logger .debug (
124- f"['{ self ._instance_connection_string } ']: Connection info refresh "
125- "operation started"
111+ f"['{ self ._conn_name } ']: Connection info refresh " "operation started"
126112 )
127113
128114 try :
@@ -135,17 +121,16 @@ async def _perform_refresh(self) -> ConnectionInfo:
135121 self ._enable_iam_auth ,
136122 )
137123 logger .debug (
138- f"['{ self ._instance_connection_string } ']: Connection info "
139- "refresh operation complete"
124+ f"['{ self ._conn_name } ']: Connection info " "refresh operation complete"
140125 )
141126 logger .debug (
142- f"['{ self ._instance_connection_string } ']: Current certificate "
127+ f"['{ self ._conn_name } ']: Current certificate "
143128 f"expiration = { connection_info .expiration .isoformat ()} "
144129 )
145130
146131 except aiohttp .ClientResponseError as e :
147132 logger .debug (
148- f"['{ self ._instance_connection_string } ']: Connection info "
133+ f"['{ self ._conn_name } ']: Connection info "
149134 f"refresh operation failed: { str (e )} "
150135 )
151136 if e .status == 403 :
@@ -154,7 +139,7 @@ async def _perform_refresh(self) -> ConnectionInfo:
154139
155140 except Exception as e :
156141 logger .debug (
157- f"['{ self ._instance_connection_string } ']: Connection info "
142+ f"['{ self ._conn_name } ']: Connection info "
158143 f"refresh operation failed: { str (e )} "
159144 )
160145 raise
@@ -188,18 +173,17 @@ async def _refresh_task(self: RefreshAheadCache, delay: int) -> ConnectionInfo:
188173 # check that refresh is valid
189174 if not await _is_valid (refresh_task ):
190175 raise RefreshNotValidError (
191- f"['{ self ._instance_connection_string } ']: Invalid refresh operation. Certficate appears to be expired."
176+ f"['{ self ._conn_name } ']: Invalid refresh operation. Certficate appears to be expired."
192177 )
193178 except asyncio .CancelledError :
194179 logger .debug (
195- f"['{ self ._instance_connection_string } ']: Scheduled refresh"
196- " operation cancelled"
180+ f"['{ self ._conn_name } ']: Scheduled refresh" " operation cancelled"
197181 )
198182 raise
199183 # bad refresh attempt
200184 except Exception as e :
201185 logger .exception (
202- f"['{ self ._instance_connection_string } ']: "
186+ f"['{ self ._conn_name } ']: "
203187 "An error occurred while performing refresh. "
204188 "Scheduling another refresh attempt immediately" ,
205189 exc_info = e ,
@@ -216,7 +200,7 @@ async def _refresh_task(self: RefreshAheadCache, delay: int) -> ConnectionInfo:
216200 # calculate refresh delay based on certificate expiration
217201 delay = _seconds_until_refresh (refresh_data .expiration )
218202 logger .debug (
219- f"['{ self ._instance_connection_string } ']: Connection info refresh"
203+ f"['{ self ._conn_name } ']: Connection info refresh"
220204 " operation scheduled for "
221205 f"{ (datetime .now (timezone .utc ) + timedelta (seconds = delay )).isoformat (timespec = 'seconds' )} "
222206 f"(now + { timedelta (seconds = delay )} )"
@@ -240,7 +224,7 @@ async def close(self) -> None:
240224 graceful exit.
241225 """
242226 logger .debug (
243- f"['{ self ._instance_connection_string } ']: Canceling connection info "
227+ f"['{ self ._conn_name } ']: Canceling connection info "
244228 "refresh operation tasks"
245229 )
246230 self ._current .cancel ()
0 commit comments