Skip to content

Commit

Permalink
feat: automatically pass X-Fal-Object-Lifecycle-Preference as a header
Browse files Browse the repository at this point in the history
  • Loading branch information
turbo1912 committed Apr 30, 2024
1 parent e53028a commit f8d71e1
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
19 changes: 19 additions & 0 deletions projects/fal/src/fal/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from fal.api import RouteSignature
from fal.logging import get_logger
from fal._serialization import include_modules_from

REALTIME_APP_REQUIREMENTS = ["websockets", "msgpack"]

EndpointT = TypeVar("EndpointT", bound=Callable[..., Any])
Expand Down Expand Up @@ -123,6 +124,24 @@ async def provide_hints_headers(request, call_next):
)
return response

@app.middleware("http")
async def set_global_object_preference(request, call_next):
response = await call_next(request)
try:
from fal.toolkit.file.providers import fal

fal.GLOBAL_LIFECYCLE_PREFERENCE = request.headers[
"X-Fal-Object-Lifecycle-Preference"
]
except Exception:
from fastapi.logger import logger

logger.exception(
"Failed set a global lifecycle preference %s",
self.__class__.__name__,
)
return response

def provide_hints(self) -> list[str]:
"""Provide hints for routing the application."""
raise NotImplementedError
Expand Down
24 changes: 22 additions & 2 deletions projects/fal/src/fal/toolkit/file/providers/fal.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import datetime
import json
import os
from base64 import b64encode
Expand All @@ -14,6 +15,16 @@
_FAL_CDN = "https://fal.media"


@dataclass
class ObjectLifecyclePreference:
expriation_days: datetime.timedelta


GLOBAL_LIFECYCLE_PREFERENCE = ObjectLifecyclePreference(
expriation_days=datetime.timedelta(days=2)
)


@dataclass
class FalFileRepository(FileRepository):
def save(self, file: FileData) -> str:
Expand Down Expand Up @@ -70,17 +81,26 @@ def _upload_file(self, upload_url: str, file: FileData):

@dataclass
class InMemoryRepository(FileRepository):
def save(self, file: FileData) -> str:
def save(
self,
file: FileData,
) -> str:
return f'data:{file.content_type};base64,{b64encode(file.data).decode("utf-8")}'


@dataclass
class FalCDNFileRepository(FileRepository):
def save(self, file: FileData) -> str:
def save(
self,
file: FileData,
) -> str:
headers = {
**self.auth_headers,
"Accept": "application/json",
"Content-Type": file.content_type,
"X-Fal-Object-Lifecycle-Preference": json.dumps(
GLOBAL_LIFECYCLE_PREFERENCE
),
}

url = os.getenv("FAL_CDN_HOST", _FAL_CDN) + "/files/upload"
Expand Down

0 comments on commit f8d71e1

Please sign in to comment.