Skip to content
Open
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
33 changes: 28 additions & 5 deletions projects/fal/src/fal/toolkit/file/providers/fal.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from base64 import b64encode
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime, timezone
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any, Dict, Generator, Generic, TypeVar
from urllib.error import HTTPError, URLError
Expand Down Expand Up @@ -95,8 +95,21 @@ class FalV2Token:
base_upload_url: str
expires_at: datetime

def is_expired(self) -> bool:
return datetime.now(timezone.utc) >= self.expires_at
def is_expired(self, offset: timedelta | int | None = None) -> bool:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am thinking we may want to add a default value of 1h or smth

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That seems reasonable to me (though we'd probably want to add that on get_token rather than is_expired)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated

"""
Return whether the token has expired.

If `offset` is provided, return whether the token *will have* expired as of
`now + offset`, rather than whether it is *currently* expired. Offsets can be
either a number of seconds or a `timedelta` object.
"""
as_of = datetime.now(timezone.utc)
if offset is not None:
if isinstance(offset, timedelta):
as_of += offset
else:
as_of += timedelta(seconds=offset)
return as_of >= self.expires_at


class FalV3Token(FalV2Token):
Expand All @@ -117,9 +130,19 @@ def __init__(self):
)
self._lock: threading.Lock = threading.Lock()

def get_token(self) -> FalV2Token:
def get_token(
self,
valid_for: timedelta | int | None = timedelta(hours=1),
) -> FalV2Token:
"""
Get a valid authentication token.

If `valid_for` is specified, return a token that's guaranteed to remain valid
for the specified duration. Durations can be specified as an integer number of
seconds, or as a `timedelta` object.
"""
with self._lock:
if self._token.is_expired():
if self._token.is_expired(offset=valid_for):
self._refresh_token()
return self._token

Expand Down
Loading