|
| 1 | +# Copyright 2024 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import asyncio |
| 16 | +from datetime import datetime |
| 17 | +from datetime import timedelta |
| 18 | +from datetime import timezone |
| 19 | +import logging |
| 20 | +from typing import Optional |
| 21 | + |
| 22 | +from google.cloud.sql.connector.client import CloudSQLClient |
| 23 | +from google.cloud.sql.connector.connection_info import ConnectionInfo |
| 24 | +from google.cloud.sql.connector.instance import _parse_instance_connection_name |
| 25 | +from google.cloud.sql.connector.refresh_utils import _refresh_buffer |
| 26 | + |
| 27 | +logger = logging.getLogger(name=__name__) |
| 28 | + |
| 29 | + |
| 30 | +class LazyRefreshCache: |
| 31 | + """Cache that refreshes connection info when a caller requests a connection. |
| 32 | +
|
| 33 | + Only refreshes the cache when a new connection is requested and the current |
| 34 | + certificate is close to or already expired. |
| 35 | +
|
| 36 | + This is the recommended option for serverless environments. |
| 37 | + """ |
| 38 | + |
| 39 | + def __init__( |
| 40 | + self, |
| 41 | + instance_connection_string: str, |
| 42 | + client: CloudSQLClient, |
| 43 | + keys: asyncio.Future, |
| 44 | + enable_iam_auth: bool = False, |
| 45 | + ) -> None: |
| 46 | + """Initializes a LazyRefreshCache instance. |
| 47 | +
|
| 48 | + Args: |
| 49 | + instance_connection_string (str): The Cloud SQL Instance's |
| 50 | + connection string (also known as an instance connection name). |
| 51 | + client (CloudSQLClient): The Cloud SQL Client instance. |
| 52 | + keys (asyncio.Future): A future to the client's public-private key |
| 53 | + pair. |
| 54 | + enable_iam_auth (bool): Enables automatic IAM database authentication |
| 55 | + (Postgres and MySQL) as the default authentication method for all |
| 56 | + connections. |
| 57 | + """ |
| 58 | + # validate and parse instance connection name |
| 59 | + self._project, self._region, self._instance = _parse_instance_connection_name( |
| 60 | + instance_connection_string |
| 61 | + ) |
| 62 | + self._instance_connection_string = instance_connection_string |
| 63 | + |
| 64 | + self._enable_iam_auth = enable_iam_auth |
| 65 | + self._keys = keys |
| 66 | + self._client = client |
| 67 | + self._lock = asyncio.Lock() |
| 68 | + self._cached: Optional[ConnectionInfo] = None |
| 69 | + self._needs_refresh = False |
| 70 | + |
| 71 | + async def force_refresh(self) -> None: |
| 72 | + """ |
| 73 | + Invalidates the cache and configures the next call to |
| 74 | + connect_info() to retrieve a fresh ConnectionInfo instance. |
| 75 | + """ |
| 76 | + async with self._lock: |
| 77 | + self._needs_refresh = True |
| 78 | + |
| 79 | + async def connect_info(self) -> ConnectionInfo: |
| 80 | + """Retrieves ConnectionInfo instance for establishing a secure |
| 81 | + connection to the Cloud SQL instance. |
| 82 | + """ |
| 83 | + async with self._lock: |
| 84 | + # If connection info is cached, check expiration. |
| 85 | + # Pad expiration with a buffer to give the client plenty of time to |
| 86 | + # establish a connection to the server with the certificate. |
| 87 | + if ( |
| 88 | + self._cached |
| 89 | + and not self._needs_refresh |
| 90 | + and datetime.now(timezone.utc) |
| 91 | + < (self._cached.expiration - timedelta(seconds=_refresh_buffer)) |
| 92 | + ): |
| 93 | + logger.debug( |
| 94 | + f"['{self._instance_connection_string}']: Connection info " |
| 95 | + "is still valid, using cached info" |
| 96 | + ) |
| 97 | + return self._cached |
| 98 | + logger.debug( |
| 99 | + f"['{self._instance_connection_string}']: Connection info " |
| 100 | + "refresh operation started" |
| 101 | + ) |
| 102 | + try: |
| 103 | + conn_info = await self._client.get_connection_info( |
| 104 | + self._project, |
| 105 | + self._region, |
| 106 | + self._instance, |
| 107 | + self._keys, |
| 108 | + self._enable_iam_auth, |
| 109 | + ) |
| 110 | + except Exception as e: |
| 111 | + logger.debug( |
| 112 | + f"['{self._instance_connection_string}']: Connection info " |
| 113 | + f"refresh operation failed: {str(e)}" |
| 114 | + ) |
| 115 | + raise |
| 116 | + logger.debug( |
| 117 | + f"['{self._instance_connection_string}']: Connection info " |
| 118 | + "refresh operation completed successfully" |
| 119 | + ) |
| 120 | + logger.debug( |
| 121 | + f"['{self._instance_connection_string}']: Current certificate " |
| 122 | + f"expiration = {str(conn_info.expiration)}" |
| 123 | + ) |
| 124 | + self._cached = conn_info |
| 125 | + self._needs_refresh = False |
| 126 | + return conn_info |
| 127 | + |
| 128 | + async def close(self) -> None: |
| 129 | + """Close is a no-op and provided purely for a consistent interface with |
| 130 | + other cache types. |
| 131 | + """ |
| 132 | + pass |
0 commit comments