Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix issue with import httpx wrapper instance #95

Merged
merged 6 commits into from
Jun 5, 2024
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
22 changes: 6 additions & 16 deletions src/nsls2api/cli/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@
from nsls2api.infrastructure.security import SpecialUsers


BASE_URL = "http://localhost:8080"

__logged_in_username = None
BASE_URL = "http://localhost:8000"

app = typer.Typer()

Expand All @@ -36,15 +34,15 @@ def config_from_file() -> Optional[str]:


@app.command()
def login():
def status():
# Let's see if there is a token in the local config file ?
token = config_from_file()
if token is None:
print("No API token found")
token = getpass.getpass(prompt="Please enter your API token:")
if len(token) == 0:
__logged_in_username: SpecialUsers = SpecialUsers.anonymous
print("Logged in as anonymous")
logged_in_username: SpecialUsers = SpecialUsers.anonymous
print("Authenticated as anonymous")
return

# Let's test this token
Expand All @@ -54,21 +52,13 @@ def login():
headers = {"Authorization": f"{token}"}
response = client.get(url, headers=headers)
response.raise_for_status()
__logged_in_username = response.json()
logged_in_username = response.json()
except httpx.RequestError as exc:
print(f"An error occurred while trying to login {exc}")
raise

print(f"Logged in as {__logged_in_username}")
print(f"Authenticated as {logged_in_username}")


@app.command()
def logout():
print("Logging you out...")


@app.command()
def status():
print(
f"You might be logged in as {__logged_in_username}, or you might not be - {rich.emoji.Emoji('person_shrugging')}"
)
3 changes: 1 addition & 2 deletions src/nsls2api/infrastructure/app_setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@
from nsls2api.infrastructure import mongodb_setup
from nsls2api.infrastructure.config import get_settings
from nsls2api.services import background_service
from nsls2api.services.helpers import HTTPXClientWrapper
from nsls2api.services.helpers import httpx_client_wrapper

settings = get_settings()
httpx_client_wrapper = HTTPXClientWrapper()

local_development_mode = False

Expand Down
5 changes: 3 additions & 2 deletions src/nsls2api/infrastructure/mongodb_setup.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import beanie
import click
import motor.motor_asyncio
from pydantic import MongoDsn

Expand All @@ -20,7 +21,7 @@ def create_connection_string(


async def init_connection(mongodb_dsn: MongoDsn):
logger.info(f"Attempting to connect to {str(mongodb_dsn)}")
logger.info(f"Attempting to connect to {click.style(str(mongodb_dsn), fg='green')}")

client = motor.motor_asyncio.AsyncIOMotorClient(
mongodb_dsn, uuidRepresentation="standard"
Expand All @@ -30,4 +31,4 @@ async def init_connection(mongodb_dsn: MongoDsn):
document_models=models.all_models,
)

logger.info(f"Connected to {client.get_default_database().name}")
logger.info(f"Connected to {click.style(client.get_default_database().name, fg='green')} database.")
9 changes: 9 additions & 0 deletions src/nsls2api/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import os
from pathlib import Path

import click
import fastapi
import uvicorn
from asgi_correlation_id import CorrelationIdMiddleware
Expand All @@ -23,6 +24,14 @@

settings = get_settings()

# Log the upstream service endpoints we are using
logger.info(
f"PASS Upstream API URL: {click.style(settings.pass_api_url, fg='magenta')}"
)
logger.info(
f"UPS Upstream API URL: {click.style(settings.universal_proposal_system_api_url, fg='magenta')}"
)

current_file = Path(__file__)
current_file_dir = current_file.parent
current_file_dir_absolute = current_file_dir.absolute()
Expand Down
2 changes: 1 addition & 1 deletion src/nsls2api/services/bnlpeople_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from nsls2api.services.helpers import _call_async_webservice_with_client
from nsls2api.api.models.person_model import BNLPerson
from nsls2api.infrastructure.app_setup import httpx_client_wrapper
from nsls2api.services.helpers import httpx_client_wrapper

base_url = "https://api.bnl.gov/BNLPeople"

Expand Down
9 changes: 6 additions & 3 deletions src/nsls2api/services/helpers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from functools import lru_cache
import click
import httpx
import httpx_socks
from httpx import Response
Expand All @@ -16,11 +16,12 @@ def start(self):
timeouts = httpx.Timeout(None, connect=30.0) # 30s timeout on connect, no other timeouts.
limits = httpx.Limits(max_keepalive_connections=5, max_connections=10)
self.async_client = httpx.AsyncClient(limits=limits, timeout=timeouts)
logger.info(f"HTTPXClientWrapper started. {id(self.async_client)}")
logger.info(f"HTTPXClientWrapper [{click.style(str(id(self.async_client)), fg='cyan')}] started.")

async def stop(self):
logger.info(f"HTTPXClientWrapper stopped. {id(self.async_client)}")
logger.info(f"HTTPXClientWrapper [{click.style(str(id(self.async_client)), fg='cyan')}] stopped.")
await self.async_client.aclose()
self.async_client = None

def __call__(self):
# logger.info(f"HTTPXClientWrapper called. {id(self.async_client)}")
Expand Down Expand Up @@ -60,3 +61,5 @@ async def _call_async_webservice_with_client(
resp.raise_for_status()
results = resp.json()
return results

httpx_client_wrapper = HTTPXClientWrapper()
2 changes: 1 addition & 1 deletion src/nsls2api/services/pass_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from nsls2api.api.models.facility_model import FacilityName
from nsls2api.infrastructure import config
from nsls2api.infrastructure.logging import logger
from nsls2api.infrastructure.app_setup import httpx_client_wrapper
from nsls2api.services.helpers import httpx_client_wrapper
from nsls2api.models.cycles import Cycle
from nsls2api.models.pass_models import (
PassAllocation,
Expand Down
12 changes: 5 additions & 7 deletions src/nsls2api/services/proposal_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@
from nsls2api.models.proposal_types import ProposalType
from nsls2api.models.proposals import Proposal, ProposalIdView, User
from nsls2api.services import (
bnlpeople_service,
beamline_service,
facility_service,
bnlpeople_service
)


Expand Down Expand Up @@ -385,9 +385,7 @@ async def directories(proposal_id: int):

groups_acl.append({"n2sn-right-dataadmin": "rw"})
groups_acl.append(
{
f"{await beamline_service.data_admin_group(beamline_tla)}": "rw"
}
{f"{await beamline_service.data_admin_group(beamline_tla)}": "rw"}
)

directory = {
Expand Down Expand Up @@ -487,23 +485,23 @@ async def generate_fake_test_proposal(
email=fake.email(),
bnl_id=user_bnl_id,
username=username,
is_pi=False if isinstance(add_specific_user, str) else is_pi
is_pi=False if isinstance(add_specific_user, str) else is_pi,
)
user_list.append(user)

# Real User(s)
# If there is a real user, make them the only PI using the above `is_pi` logic.
if isinstance(add_specific_user, str):
try:
person = await bnlpeople_service.get_person_by_username(add_specific_user)
person = await bnlpeople_service.get_person_by_username(add_specific_user)
if person:
user = User(
first_name=person.FirstName,
last_name=person.LastName,
email=person.BNLEmail,
bnl_id=person.EmployeeNumber,
username=add_specific_user,
is_pi=True
is_pi=True,
)
user_list.append(user)
except LookupError:
Expand Down