Skip to content
Merged
Show file tree
Hide file tree
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
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,6 @@ TASK_DATA_FILE=tasks.json # File name to store tasks

# Data retrieval configuration
FMP_API_KEY=

# To skip configuration validation on startup set this to true
VALIDATION_SKIP=
17 changes: 14 additions & 3 deletions allocator_bot/api.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import json
import logging
import os
from contextlib import asynccontextmanager

import pandas as pd
import pandas as pd # type: ignore
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse
Expand All @@ -14,8 +15,18 @@
from .config import config
from .storage import load_allocations, load_tasks
from .utils import validate_api_key
from .validation import validate_environment

app = FastAPI()

@asynccontextmanager
async def lifespan(app: FastAPI):
"""App lifespan: run startup validations before serving."""
await validate_environment(config)
logging.info("Startup complete")
yield


app = FastAPI(lifespan=lifespan)

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

Expand Down Expand Up @@ -48,7 +59,7 @@ async def get_current_user(token: str = Depends(oauth2_scheme)):
allow_headers=["*"],
)

logging.info("Startup complete")
logging.info("API module loaded")


@app.get("/", openapi_extra={"widget_config": {"exclude": True}})
Expand Down
1 change: 1 addition & 0 deletions allocator_bot/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import re
import string
import time

from openbb_ai.models import LlmMessage # type: ignore[import-untyped]


Expand Down
149 changes: 149 additions & 0 deletions allocator_bot/validation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
import asyncio
import logging
import os
from datetime import datetime, timedelta, timezone

import aiohttp
import boto3 # type: ignore
from botocore.exceptions import ClientError # type: ignore
from openbb_fmp import FMPEquityHistoricalFetcher

from .models import AppConfig


async def check_openrouter(api_key: str) -> None:
"""Validate OpenRouter reachability and API key.

Performs a lightweight GET to the models endpoint. Raises RuntimeError on failure.
"""
if not api_key:
raise RuntimeError("OPENROUTER_API_KEY is missing.")

# Ensure downstream libs that rely on env var can see it
os.environ["OPENROUTER_API_KEY"] = api_key

timeout = aiohttp.ClientTimeout(total=5)
headers = {"Authorization": f"Bearer {api_key}"}
url = "https://openrouter.ai/api/v1/key"
try:
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.get(url, headers=headers) as resp:
if resp.status == 200:
return
if resp.status in (401, 403):
raise RuntimeError(
"OpenRouter validation failed: unauthorized. Check OPENROUTER_API_KEY."
)
raise RuntimeError(
f"OpenRouter validation failed: HTTP {resp.status}. Service may be unavailable."
)
except asyncio.TimeoutError as e:
raise RuntimeError("OpenRouter validation failed: request timed out.") from e
except aiohttp.ClientError as e:
raise RuntimeError(f"OpenRouter validation failed: {e}") from e


def check_s3(endpoint: str, access_key: str, secret_key: str, bucket: str) -> None:
"""Validate S3/compatible storage credentials and bucket access.

Calls head_bucket and a zero-key list to confirm access. Raises RuntimeError on failure.
"""
try:
s3 = boto3.client(
"s3",
endpoint_url=endpoint,
aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
)
# Existence and access
s3.head_bucket(Bucket=bucket)
# Minimal read attempt
s3.list_objects_v2(Bucket=bucket, MaxKeys=0)
except ClientError as e:
code = e.response.get("Error", {}).get("Code", "Unknown")
msg = e.response.get("Error", {}).get("Message", str(e))
raise RuntimeError(f"S3 validation failed: {code} - {msg}") from e
except Exception as e: # pragma: no cover - safety net
raise RuntimeError(f"S3 validation failed: {e}") from e


def check_local_storage(path: str) -> None:
"""Ensure local storage path exists and is writable.

Creates the folder if missing and performs a write test.
"""
if not path:
raise RuntimeError("DATA_FOLDER_PATH must be set when S3 is disabled.")

try:
os.makedirs(path, exist_ok=True)
except OSError as e:
raise RuntimeError(f"Failed to create data folder at '{path}': {e}") from e

test_file = os.path.join(path, ".allocator_bot_write_test")
try:
with open(test_file, "w") as f:
f.write("ok")
os.remove(test_file)
except OSError as e:
raise RuntimeError(f"Data folder is not writable at '{path}': {e}") from e


async def check_fmp(key: str) -> None:
"""Validate FMP key by fetching a tiny slice of data.

Uses OpenBB FMP fetcher for a single symbol and short date window.
"""
if not key:
raise RuntimeError("FMP_API_KEY is missing.")

end_date = datetime.now(timezone.utc).date()
start_date = end_date - timedelta(days=5)

try:
data = await FMPEquityHistoricalFetcher.fetch_data(
params={
"symbol": "AAPL",
"start_date": start_date.isoformat(),
"end_date": end_date.isoformat(),
},
credentials={"fmp_api_key": key},
)
# Some accounts may have limited history; consider any non-exception as success
if data is None:
raise RuntimeError("FMP validation failed: empty response.")
except Exception as e:
raise RuntimeError(
"FMP validation failed: invalid key or network error."
) from e


async def validate_environment(config: AppConfig) -> None:
"""Run all environment validations. Raises on first failure.

Set VALIDATION_SKIP=true to bypass in development environments.
"""
if os.getenv("VALIDATION_SKIP", "false").lower() == "true":
logging.warning("VALIDATION_SKIP=true: Skipping external credential checks.")
return

# OpenRouter
await check_openrouter(config.openrouter_api_key)

# Storage
if config.s3_enabled:
check_s3(
endpoint=str(config.s3_endpoint),
access_key=str(config.s3_access_key),
secret_key=str(config.s3_secret_key),
bucket=str(config.s3_bucket_name),
)
else:
if config.data_folder_path is None:
raise RuntimeError("DATA_FOLDER_PATH must be set when S3 is not enabled.")
check_local_storage(config.data_folder_path)

# FMP
await check_fmp(str(config.fmp_api_key))

logging.info("Environment validation succeeded.")
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ classifiers = [
]

dependencies = [
"aiohttp>=3.9.0",
"boto3>=1.34.0",
"magentic>=0.40.0",
"openbb-ai>=1.5.0",
"openbb-ai>=1.7.4",
"openbb-fmp>=1.3.5",
"openbb-platform-api>=1.1.10",
"pandas>=2.2.3",
Expand Down
Loading