Skip to content

Commit

Permalink
Fix circular import in Azure function loop (#21)
Browse files Browse the repository at this point in the history
* Make all requests to the API simultaneously

* Async API

* Add an await to the async wrapper

* add nest_asyncio

* co-pilot take the wheel

* Attempt to fix circular import

* Fix views not showing on successful request

* test import app inside function

* Build app outside loop

* Fix circular import

---------

Co-authored-by: Reinder Vos de Wael <[email protected]>
  • Loading branch information
ReinderVosDeWael and ReinderVosDeWael authored Aug 9, 2023
1 parent 9ac0fca commit 3d23c6c
Show file tree
Hide file tree
Showing 6 changed files with 78 additions and 72 deletions.
3 changes: 2 additions & 1 deletion api/WrapperFunction/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@
import azure.functions as func
import nest_asyncio

from src.main import app
from src import builder

nest_asyncio.apply()


async def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
"""Each request is redirected to the ASGI handler."""
app = builder.build_app()
async with aiohttp.ClientSession():
loop = asyncio.get_running_loop()
return await loop.run_in_executor(
Expand Down
45 changes: 45 additions & 0 deletions api/src/builder.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"""Builder of the FastAPI application instance.
This is separate from main.py as the app needs to be created
inside the loop on Azure."""
import logging

import fastapi
from fastapi.middleware import cors

from src.core import settings
from src.routers.features import views as feature_views
from src.routers.surfaces import views as surface_views

config = settings.get_settings()
LOGGER_NAME = config.LOGGER_NAME


def build_app() -> fastapi.FastAPI:
"""Builds and returns a FastAPI application instance with the necessary
routers and middleware.
Returns:
fastapi.FastAPI: The FastAPI application instance.
"""
settings.initialize_logger()
logger = logging.getLogger(LOGGER_NAME)

api = fastapi.APIRouter(prefix="/api")
api.include_router(feature_views.router)
api.include_router(surface_views.router)

logger.info("Starting API.")
app = fastapi.FastAPI()
app.include_router(api)

logger.info("Adding CORS middleware.")
app.add_middleware(
cors.CORSMiddleware,
allow_origins="*",
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

return app
34 changes: 3 additions & 31 deletions api/src/main.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,4 @@
"""Main module for the API."""
import logging
"""Entrypoint for Uvicorn."""
from src import builder

import fastapi
from fastapi.middleware import cors

from src.core import settings
from src.routers.features import views as feature_views
from src.routers.surfaces import views as surface_views

config = settings.get_settings()
LOGGER_NAME = config.LOGGER_NAME

settings.initialize_logger()
logger = logging.getLogger(LOGGER_NAME)

api = fastapi.APIRouter(prefix="/api")
api.include_router(feature_views.router)
api.include_router(surface_views.router)

logger.info("Starting API.")
app = fastapi.FastAPI()
app.include_router(api)

logger.info("Adding CORS middleware.")
app.add_middleware(
cors.CORSMiddleware,
allow_origins="*",
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app = builder.build_app()
29 changes: 19 additions & 10 deletions frontend/src/components/viewer/ViewerSet.svelte
Original file line number Diff line number Diff line change
@@ -1,22 +1,17 @@
<script lang="ts">
import { onMount } from "svelte";
import type { Surface } from "brainviewer/src/brainViewer";
import { Shadow } from "svelte-loading-spinners";
import { getData } from "./fetch";
import { getData, type SurfaceData } from "./fetch";
import { Viewer } from "./client";
import { onDoubleClick, onUpdate } from "./events";
import Toggle from "svelte-toggle";
import Button from "../Button.svelte";
// @ts-ignore
import type * as THREE from "three";
import toast from "svelte-french-toast";
let cameraLock = true;
let surfaces: {
human_left: Surface;
human_right: Surface;
macaque_left: Surface;
macaque_right: Surface;
};
let surfaces: SurfaceData | null;
let div1: HTMLElement;
let div2: HTMLElement;
Expand All @@ -27,7 +22,19 @@
let lastTouchTime = new Date().getTime();
onMount(async () => {
surfaces = await getData();
surfaces = await getData()
.then((data) => {
return data;
})
.catch(() => {
toast.error("Something went wrong. Please try refreshing.");
return null;
});
if (!surfaces) {
return;
}
const viewers = [
new Viewer(div1, surfaces["human_left"], "human", "left"),
new Viewer(div2, surfaces["human_right"], "human", "right"),
Expand Down Expand Up @@ -58,6 +65,7 @@
viewer.viewer.addListener(
"touchstart",
(event: Event, intersects: THREE.Intersection) => {
event.preventDefault();
if (!(event instanceof MouseEvent || event instanceof TouchEvent)) {
return;
}
Expand All @@ -71,7 +79,6 @@
viewer.getSpecies(),
viewer.getSide()
);
event.preventDefault();
} else {
lastTouchTime = currentTime;
}
Expand Down Expand Up @@ -109,11 +116,13 @@
</div>
<Button text="Reset Camera" onClick={resetCamera} />
</div>

{#if !surfaces}
<div class="loading">
<Shadow size="30" color="#FF3E00" unit="px" duration="1s" />
</div>
{/if}

<div class="viewer-set">
<div id="div-viewer" bind:this={div1} />
<div id="div-viewer" bind:this={div2} />
Expand Down
10 changes: 9 additions & 1 deletion frontend/src/components/viewer/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,15 @@ function apiSurface2ViewerSurface (apiSurface: ApiSurface): SurfaceMesh {
)
}

export async function getData (): Promise<Record<string, Surface>> {
export interface SurfaceData {
human_left: Surface
human_right: Surface
macaque_left: Surface
macaque_right: Surface
}


export async function getData (): Promise<SurfaceData> {
const surfaceMeshPromises = {
human_left: getSurfaces('human', 'left'),
human_right: getSurfaces('human', 'right'),
Expand Down
29 changes: 0 additions & 29 deletions frontend/src/types/api.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,3 @@
export interface NiMareFeature {
name: string
correlation: number
}

export interface NiMareResponse {
features: NiMareFeature[]
}

export interface CrossSpeciesSimilarityResponse {
[key: string]: number[]
human_left: number[]
Expand All @@ -28,23 +19,3 @@ export interface ApiSurfaceResponse {
macaque_left: ApiSurface
macaque_right: ApiSurface
}

export interface PlotlySurface {
name: string
type: string
x: number[]
y: number[]
z: number[]
i: number[]
j: number[]
k: number[]
intensity: number[]
showscale?: boolean
cmin?: number
cmax?: number
colorscale?: string
colorbar?: any
lighting?: any
flatshading?: boolean
vertexnormals?: any
}

0 comments on commit 3d23c6c

Please sign in to comment.