Skip to content

Commit

Permalink
fix: use utcnow() for refresh calculation (#155)
Browse files Browse the repository at this point in the history
  • Loading branch information
jackwotherspoon authored Nov 8, 2023
1 parent 210ca07 commit e33366f
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
8 changes: 5 additions & 3 deletions google/cloud/alloydb/connector/refresh.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,17 @@
_refresh_buffer: int = 4 * 60 # 4 minutes


def _seconds_until_refresh(expiration: datetime, now: datetime = datetime.now()) -> int:
def _seconds_until_refresh(
expiration: datetime, now: datetime = datetime.utcnow()
) -> int:
"""
Calculates the duration to wait before starting the next refresh.
Usually the duration will be half of the time until certificate
expiration.
Args:
expiration (datetime.datetime): Time of certificate expiration.
now (datetime.datetime): Current time. Defaults to datetime.now()
now (datetime.datetime): Current time. Defaults to datetime.utcnow()
Returns:
int: Time in seconds to wait before performing next refresh.
"""
Expand Down Expand Up @@ -107,7 +109,7 @@ async def _is_valid(task: asyncio.Task) -> bool:
try:
result = await task
# valid if current time is before cert expiration
if datetime.now() < result.expiration:
if datetime.utcnow() < result.expiration:
return True
except Exception:
# suppress any errors from task
Expand Down
8 changes: 4 additions & 4 deletions tests/unit/mocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def __init__(self) -> None:
def refresh(self, request: Callable) -> None:
"""Refreshes the access token."""
self.token = "12345"
self.expiry = datetime.now() + timedelta(minutes=60)
self.expiry = datetime.utcnow() + timedelta(minutes=60)

@property
def expired(self) -> bool:
Expand Down Expand Up @@ -67,7 +67,7 @@ def generate_cert(
# generate private key
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
# calculate expiry time
now = datetime.now()
now = datetime.utcnow()
expiration = now + timedelta(minutes=expires_in)
# configure cert subject
subject = issuer = x509.Name(
Expand Down Expand Up @@ -103,8 +103,8 @@ def __init__(
name: str = "test-instance",
ip_address: str = "127.0.0.1",
server_name: str = "00000000-0000-0000-0000-000000000000.server.alloydb",
cert_before: datetime = datetime.now(),
cert_expiry: datetime = datetime.now() + timedelta(hours=1),
cert_before: datetime = datetime.utcnow(),
cert_expiry: datetime = datetime.utcnow() + timedelta(hours=1),
) -> None:
self.project = project
self.region = region
Expand Down

0 comments on commit e33366f

Please sign in to comment.