From 768c3f2cf65f8bb5a494c054fd8db595a7657005 Mon Sep 17 00:00:00 2001 From: Cizz22 Date: Fri, 15 Aug 2025 13:47:33 +0700 Subject: [PATCH] fix --- src/auth/service.py | 19 ++++--- src/calculation_target_reliability/service.py | 54 ++++++++++++++++++- 2 files changed, 64 insertions(+), 9 deletions(-) diff --git a/src/auth/service.py b/src/auth/service.py index 16f9c53..034e87b 100644 --- a/src/auth/service.py +++ b/src/auth/service.py @@ -5,11 +5,13 @@ from typing import Annotated, Optional import requests from fastapi import Depends, HTTPException, Request from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer +from sqlalchemy.sql.expression import false import src.config as config from .model import UserBase from .util import extract_template +from tomlkit.items import Bool class JWTBearer(HTTPBearer): def __init__(self, auto_error: bool = True): @@ -31,12 +33,13 @@ class JWTBearer(HTTPBearer): 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: + message = message.get("message", "Invalid token or expired token.") raise HTTPException( - status_code=403, detail="Invalid token or expired token." + status_code=403, detail=message ) request.state.user = user_info @@ -44,23 +47,23 @@ class JWTBearer(HTTPBearer): else: 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: 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}"}, ) if not response.ok: - return None + return False, response.json() user_data = response.json() - return UserBase(**user_data["data"]) + return True, UserBase(**user_data["data"]) except Exception as e: print(f"Token verification error: {str(e)}") - return None + return False, str(e) # Create dependency to get current user from request state diff --git a/src/calculation_target_reliability/service.py b/src/calculation_target_reliability/service.py index 3ba4194..5651389 100644 --- a/src/calculation_target_reliability/service.py +++ b/src/calculation_target_reliability/service.py @@ -1,7 +1,7 @@ from typing import Optional from sqlalchemy import Delete, Select - +import httpx from src.auth.service import CurrentUser from src.database.core import DbSession # 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 bisect import bisect_left 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( # *, db_session: DbSession, scope_name: str, eaf_threshold: float = 100.0 # ): @@ -184,7 +190,53 @@ from collections import defaultdict # 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]: """