Skip to content

Commit

Permalink
clean up PR
Browse files Browse the repository at this point in the history
  • Loading branch information
aarushik93 committed Nov 20, 2024
1 parent 7379d0e commit 141bc46
Show file tree
Hide file tree
Showing 6 changed files with 134 additions and 122 deletions.
40 changes: 22 additions & 18 deletions autogpt_platform/autogpt_libs/autogpt_libs/feature_flag/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from .config import settings

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)

P = ParamSpec("P")
T = TypeVar("T")
Expand All @@ -23,14 +24,17 @@ def get_client() -> LDClient:


def initialize_launchdarkly() -> None:
if not settings.SDK_KEY:
sdk_key = settings.SDK_KEY
logger.debug(f"Initializing LaunchDarkly with SDK key: {'present' if sdk_key else 'missing'}")

if not sdk_key:
logger.warning("LaunchDarkly SDK key not configured")
return

config = Config(settings.SDK_KEY)
config = Config(sdk_key)
ldclient.set_config(config)

if get_client().is_initialized():
if ldclient.get().is_initialized():
logger.info("LaunchDarkly client initialized successfully")
else:
logger.error("LaunchDarkly client failed to initialize")
Expand All @@ -57,42 +61,42 @@ def feature_flag(
):
"""
Decorator for feature flag protected endpoints.
Handles both synchronous and asynchronous functions.
Can extract user_id from either a string parameter or FastAPI Request object.
"""

def decorator(
func: Callable[Concatenate[str | Request, P], T]
) -> Callable[Concatenate[str | Request, P], T]:
func: Callable[P, T]
) -> Callable[P, T]:
@wraps(func)
async def async_wrapper(first_arg: str | Request, *args: P.args, **kwargs: P.kwargs) -> T:
async def async_wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
try:
# Extract user_id from either string or Request
user_id = first_arg if isinstance(first_arg, str) else first_arg.state.user_id
# Get user_id from kwargs since FastAPI injects it
user_id = kwargs.get('user_id')
logger.debug(f"Checking flag '{flag_key}' for user '{user_id}'")

if not get_client().is_initialized():
logger.warning(f"LaunchDarkly not initialized, using default={default}")
is_enabled = default
else:
context = create_context(user_id)
logger.debug(f"Created context for user: {context}")
is_enabled = get_client().variation(flag_key, context, default)
logger.debug(f"Flag '{flag_key}' evaluation result: {is_enabled}")

if not is_enabled:
logger.debug(f"Feature '{flag_key}' disabled, returning unauthorized response")
if unauthorized_response is not None:
return cast(T, unauthorized_response)
raise HTTPException(status_code=404, detail="Feature not available")

return await func(first_arg, *args, **kwargs)
logger.debug(f"Feature '{flag_key}' enabled, executing function")
return await func(*args, **kwargs)
except Exception as e:
logger.error(f"Error evaluating feature flag {flag_key}: {e}")
logger.error(f"Error evaluating feature flag {flag_key}: {e}", exc_info=True)
return cast(T, unauthorized_response) if unauthorized_response else None

@wraps(func)
def sync_wrapper(first_arg: str | Request, *args: P.args, **kwargs: P.kwargs) -> T:
def sync_wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
try:
user_id = first_arg if isinstance(first_arg, str) else first_arg.state.user_id

user_id = kwargs.get('user_id')
if not get_client().is_initialized():
logger.warning(f"LaunchDarkly not initialized, using default={default}")
is_enabled = default
Expand All @@ -105,7 +109,7 @@ def sync_wrapper(first_arg: str | Request, *args: P.args, **kwargs: P.kwargs) ->
return cast(T, unauthorized_response)
raise HTTPException(status_code=404, detail="Feature not available")

return func(first_arg, *args, **kwargs)
return func(*args, **kwargs)
except Exception as e:
logger.error(f"Error evaluating feature flag {flag_key}: {e}")
return cast(T, unauthorized_response) if unauthorized_response else None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@


class Settings:
SDK_KEY: str = os.getenv("SDK_KEY", "")
SDK_KEY: str = os.getenv("LAUNCH_DARKLY_SDK_KEY", "")


settings = Settings()
1 change: 1 addition & 0 deletions autogpt_platform/backend/backend/server/rest_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
settings = backend.util.settings.Settings()
logger = logging.getLogger(__name__)

logging.getLogger('autogpt_libs').setLevel(logging.DEBUG)

@contextlib.asynccontextmanager
async def lifespan_context(app: fastapi.FastAPI):
Expand Down
14 changes: 7 additions & 7 deletions autogpt_platform/backend/backend/server/routers/v1.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import asyncio
import logging
from collections import defaultdict
from typing import Annotated, Any, Dict, List
from typing import Annotated, Any, Dict, List, Union

import pydantic
from autogpt_libs.auth.middleware import auth_middleware
Expand Down Expand Up @@ -555,7 +555,7 @@ async def update_configuration(

@v1_router.post(
"/api-keys",
response_model=CreateAPIKeyResponse,
response_model=Union[List[CreateAPIKeyResponse], Dict[str, str]],
tags=["api-keys"],
dependencies=[Depends(auth_middleware)],
)
Expand Down Expand Up @@ -583,7 +583,7 @@ async def create_api_key(

@v1_router.get(
"/api-keys",
response_model=List[APIKeyWithoutHash],
response_model=Union[List[APIKeyWithoutHash], Dict[str, str]],
tags=["api-keys"],
dependencies=[Depends(auth_middleware)],
)
Expand All @@ -605,7 +605,7 @@ async def get_api_keys(

@v1_router.get(
"/api-keys/{key_id}",
response_model=APIKeyWithoutHash,
response_model=Union[List[APIKeyWithoutHash], Dict[str, str]],
tags=["api-keys"],
dependencies=[Depends(auth_middleware)],
)
Expand All @@ -630,7 +630,7 @@ async def get_api_key(

@v1_router.delete(
"/api-keys/{key_id}",
response_model=APIKeyWithoutHash,
response_model=Union[List[APIKeyWithoutHash], Dict[str, str]],
tags=["api-keys"],
dependencies=[Depends(auth_middleware)],
)
Expand All @@ -656,7 +656,7 @@ async def delete_api_key(

@v1_router.post(
"/api-keys/{key_id}/suspend",
response_model=APIKeyWithoutHash,
response_model=Union[List[APIKeyWithoutHash], Dict[str, str]],
tags=["api-keys"],
dependencies=[Depends(auth_middleware)],
)
Expand All @@ -682,7 +682,7 @@ async def suspend_key(

@v1_router.put(
"/api-keys/{key_id}/permissions",
response_model=APIKeyWithoutHash,
response_model=Union[List[APIKeyWithoutHash], Dict[str, str]],
tags=["api-keys"],
dependencies=[Depends(auth_middleware)],
)
Expand Down
Loading

0 comments on commit 141bc46

Please sign in to comment.