Skip to content

Commit

Permalink
pyproject: update dependencies
Browse files Browse the repository at this point in the history
  • Loading branch information
maxmouchet committed Oct 28, 2023
1 parent 6cbe694 commit 020d735
Show file tree
Hide file tree
Showing 12 changed files with 2,120 additions and 1,820 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ jobs:
- uses: actions/checkout@v3
- uses: actions/setup-python@v4
with:
python-version: "3.10"
python-version: "3.x"
- uses: dioptra-io/setup-poetry-action@v1
- name: Start services
run: docker compose up -d -t 0 traefik clickhouse minio postgres redis
Expand Down Expand Up @@ -48,7 +48,7 @@ jobs:
- uses: actions/checkout@v3
- uses: actions/setup-python@v4
with:
python-version: "3.10"
python-version: "3.x"
- uses: dioptra-io/setup-poetry-action@v1
- name: Install package
run: poetry install
Expand Down
4 changes: 3 additions & 1 deletion iris/api/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,7 @@

if __name__ == "__main__":
# Equivalent to `python -m gunicorn --worker-class iris.api.uvicorn iris.api.main:app`.
sys.argv.extend(["--worker-class", "iris.api.uvicorn.Worker", "iris.api.main:app"])
sys.argv.extend(
["--worker-class", "iris.api.uvicorn.Worker", "iris.api.main:make_app"]
)
run()
109 changes: 55 additions & 54 deletions iris/api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,66 +11,46 @@
from iris.api import agents, maintenance, measurements, status, targets, users
from iris.api.authentication import current_superuser
from iris.api.settings import APISettings
from iris.commons.dependencies import get_settings

app = FastAPI(
title="🕸️ Iris",
description="""
Iris is a system to coordinate complex network measurements from multiple vantage points.<br/>
For more information, please visit our website at [iris.dioptra.io](https://iris.dioptra.io)
or browse the source code on [GitHub](https://github.com/dioptra-io/iris).
""",
version=__version__,
openapi_url="/openapi.json",
docs_url="/docs",
redoc_url=None,
contact={"email": "[email protected]"},
swagger_ui_parameters={
"displayRequestDuration": True,
"tryItOutEnabled": True,
},
)

def make_app(*args, settings: APISettings | None = None) -> FastAPI:
settings = settings or APISettings()

app.add_middleware(PrometheusMiddleware)
app.add_route("/metrics", handle_metrics)
app = FastAPI(
title="🕸️ Iris",
description="""
Iris is a system to coordinate complex network measurements from multiple vantage points.<br/>
For more information, please visit our website at [iris.dioptra.io](https://iris.dioptra.io)
or browse the source code on [GitHub](https://github.com/dioptra-io/iris).
""",
version=__version__,
openapi_url="/openapi.json",
docs_url="/docs",
redoc_url=None,
contact={"email": "[email protected]"},
swagger_ui_parameters={
"displayRequestDuration": True,
"tryItOutEnabled": True,
},
)

app.include_router(users.router)
app.include_router(agents.router, prefix="/agents", tags=["Agents"])
app.include_router(targets.router, prefix="/targets", tags=["Targets"])
app.include_router(measurements.router, prefix="/measurements", tags=["Measurements"])
app.include_router(status.router, prefix="/status", tags=["Status"])
app.include_router(
maintenance.router,
prefix="/maintenance",
tags=["Maintenance"],
dependencies=[Depends(current_superuser)],
)
app.add_middleware(PrometheusMiddleware)
app.add_route("/metrics", handle_metrics)

app.include_router(users.router)
app.include_router(agents.router, prefix="/agents", tags=["Agents"])
app.include_router(targets.router, prefix="/targets", tags=["Targets"])
app.include_router(
measurements.router, prefix="/measurements", tags=["Measurements"]
)
app.include_router(status.router, prefix="/status", tags=["Status"])
app.include_router(
maintenance.router,
prefix="/maintenance",
tags=["Maintenance"],
dependencies=[Depends(current_superuser)],
)

class ReadOnlyMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
if request.method not in ("GET", "HEAD", "OPTIONS"):
return JSONResponse(
dict(
detail="Iris is under maintenance. Write operations are not available."
),
status_code=HTTP_503_SERVICE_UNAVAILABLE,
)
return await call_next(request)


@app.exception_handler(botocore.exceptions.ClientError)
def botocore_exception_handler(request, exc):
if exc.response["Error"]["Code"] == "NoSuchKey":
return Response(status_code=HTTP_404_NOT_FOUND)
raise exc


@app.on_event("startup")
async def startup_event():
# Use overridden get_settings when running tests:
settings: APISettings = app.dependency_overrides.get(get_settings, get_settings)()
if settings.API_CORS_ALLOW_ORIGIN:
app.add_middleware(
CORSMiddleware,
Expand All @@ -79,5 +59,26 @@ async def startup_event():
allow_methods=["*"],
allow_headers=["*"],
)

if settings.API_READ_ONLY:
app.add_middleware(ReadOnlyMiddleware)

@app.exception_handler(botocore.exceptions.ClientError)
def botocore_exception_handler(request, exc):
if exc.response["Error"]["Code"] == "NoSuchKey":
return Response(status_code=HTTP_404_NOT_FOUND)
raise exc

return app


class ReadOnlyMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
if request.method not in ("GET", "HEAD", "OPTIONS"):
return JSONResponse(
dict(
detail="Iris is under maintenance. Write operations are not available."
),
status_code=HTTP_503_SERVICE_UNAVAILABLE,
)
return await call_next(request)
2 changes: 1 addition & 1 deletion iris/api/maintenance.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ async def post_dramatiq_message(
actor: str = "watch_measurement_agent",
kwargs: dict = Body(
...,
example={"measurement_uuid": "", "agent_uuid": ""},
examples=[{"measurement_uuid": "", "agent_uuid": ""}],
),
redis: Redis = Depends(get_redis),
):
Expand Down
30 changes: 17 additions & 13 deletions iris/api/measurements.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,16 +155,18 @@ async def get_measurements_public(
async def post_measurement(
measurement_body: MeasurementCreate = Body(
...,
example={
"tool": "diamond-miner",
"agents": [
{
"tag": "all",
"target_file": "prefixes.csv",
}
],
"tags": ["test"],
},
examples=[
{
"tool": "diamond-miner",
"agents": [
{
"tag": "all",
"target_file": "prefixes.csv",
}
],
"tags": ["test"],
}
],
),
user: User = Depends(current_verified_user),
redis: Redis = Depends(get_redis),
Expand Down Expand Up @@ -278,9 +280,11 @@ async def patch_measurement(
measurement_uuid: UUID,
measurement_body: MeasurementPatch = Body(
...,
example={
"tags": ["test"],
},
examples=[
{
"tags": ["test"],
}
],
),
user: User = Depends(current_verified_user),
session: Session = Depends(get_session),
Expand Down
4 changes: 2 additions & 2 deletions iris/commons/dependencies.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from contextlib import asynccontextmanager, contextmanager

from redis import asyncio as aioredis
from fastapi import Depends
from fastapi_users.db import SQLAlchemyUserDatabase
from fastapi_users_db_sqlalchemy.access_token import SQLAlchemyAccessTokenDatabase
from redis import asyncio as aioredis
from sqlalchemy import create_engine
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlmodel import Session
Expand Down Expand Up @@ -83,7 +83,7 @@ async def get_redis(settings=Depends(get_settings), logger=Depends(get_logger)):
try:
yield Redis(client, settings, logger)
finally:
await client.close()
await client.aclose()


def get_storage(settings=Depends(get_settings), logger=Depends(get_logger)):
Expand Down
Loading

0 comments on commit 020d735

Please sign in to comment.