feature/reliability_stat
Cizz22 5 months ago
parent 290b74d827
commit 768c3f2cf6

@ -5,11 +5,13 @@ from typing import Annotated, Optional
import requests import requests
from fastapi import Depends, HTTPException, Request from fastapi import Depends, HTTPException, Request
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.sql.expression import false
import src.config as config import src.config as config
from .model import UserBase from .model import UserBase
from .util import extract_template from .util import extract_template
from tomlkit.items import Bool
class JWTBearer(HTTPBearer): class JWTBearer(HTTPBearer):
def __init__(self, auto_error: bool = True): def __init__(self, auto_error: bool = True):
@ -31,12 +33,13 @@ class JWTBearer(HTTPBearer):
path = extract_template(request.url.path, request.path_params) path = extract_template(request.url.path, request.path_params)
endpoint = f"/optimumoh/{path}" endpoint = f"/optimumoh{path}"
user_info = self.verify_jwt(credentials.credentials, method, endpoint) user_info, message = self.verify_jwt(credentials.credentials, method, endpoint)
if not user_info: if not user_info:
message = message.get("message", "Invalid token or expired token.")
raise HTTPException( raise HTTPException(
status_code=403, detail="Invalid token or expired token." status_code=403, detail=message
) )
request.state.user = user_info request.state.user = user_info
@ -44,23 +47,23 @@ class JWTBearer(HTTPBearer):
else: else:
raise HTTPException(status_code=403, detail="Invalid authorization code.") raise HTTPException(status_code=403, detail="Invalid authorization code.")
def verify_jwt(self, jwtoken: str, method: str, endpoint: str) -> Optional[UserBase]: def verify_jwt(self, jwtoken: str, method: str, endpoint: str):
try: try:
response = requests.get( response = requests.get(
f"{config.AUTH_SERVICE_API}/verify-token", f"{config.AUTH_SERVICE_API}/verify-token?method={method}&endpoint={endpoint}",
headers={"Authorization": f"Bearer {jwtoken}"}, headers={"Authorization": f"Bearer {jwtoken}"},
) )
if not response.ok: if not response.ok:
return None return False, response.json()
user_data = response.json() user_data = response.json()
return UserBase(**user_data["data"]) return True, UserBase(**user_data["data"])
except Exception as e: except Exception as e:
print(f"Token verification error: {str(e)}") print(f"Token verification error: {str(e)}")
return None return False, str(e)
# Create dependency to get current user from request state # Create dependency to get current user from request state

@ -1,7 +1,7 @@
from typing import Optional from typing import Optional
from sqlalchemy import Delete, Select from sqlalchemy import Delete, Select
import httpx
from src.auth.service import CurrentUser from src.auth.service import CurrentUser
from src.database.core import DbSession from src.database.core import DbSession
# from src.scope_equipment.model import ScopeEquipment # from src.scope_equipment.model import ScopeEquipment
@ -14,6 +14,12 @@ from .utils import generate_down_periods
from src.overhaul_scope.service import get as get_overhaul from src.overhaul_scope.service import get as get_overhaul
from bisect import bisect_left from bisect import bisect_left
from collections import defaultdict from collections import defaultdict
import asyncio
RBD_SERVICE_API = "https://example.com/api"
client = httpx.AsyncClient(timeout=300.0)
# async def get_all_target_reliability( # async def get_all_target_reliability(
# *, db_session: DbSession, scope_name: str, eaf_threshold: float = 100.0 # *, db_session: DbSession, scope_name: str, eaf_threshold: float = 100.0
# ): # ):
@ -184,7 +190,53 @@ from collections import defaultdict
# return results # return results
async def run_rbd_simulation(*, sim_hours: int, token):
sim_data = {
"SimulationName": "Simulation OH Reliability Target",
"SchematicName": "- TJB - Unit 3 -",
"SimSeed": 1,
"SimDuration": sim_hours,
"DurationUnit": "UHour",
}
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
rbd_simulation_url = f"{RBD_SERVICE_API}/aeros/simulation/run"
async with httpx.AsyncClient(timeout=300.0) as client:
response = await client.post(rbd_simulation_url, json=sim_data, headers=headers)
response.raise_for_status()
return response.json()
async def get_simulation_results(*, simulation_id: str, token: str):
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
calc_result_url = f"{RBD_SERVICE_API}/aeros/simulation/result/calc/{simulation_id}"
plot_result_url = f"{RBD_SERVICE_API}/aeros/simulation/result/plot/{simulation_id}"
async with httpx.AsyncClient(timeout=300.0) as client:
calc_task = client.get(calc_result_url, headers=headers)
plot_task = client.get(plot_result_url, headers=headers)
# Run both requests concurrently
calc_response, plot_response = await asyncio.gather(calc_task, plot_task)
calc_response.raise_for_status()
plot_response.raise_for_status()
calc_data = calc_response.json()["data"]
plot_data = plot_response.json()["data"]
return {
"calc_result": calc_data,
"plot_result": plot_data
}
async def get_eaf_timeline(*, db_session, eaf_input: float, oh_session_id: str, oh_duration = 8000) -> List[dict]: async def get_eaf_timeline(*, db_session, eaf_input: float, oh_session_id: str, oh_duration = 8000) -> List[dict]:
""" """

Loading…
Cancel
Save