Skip to content

Commit

Permalink
Allow passing app server and Vite server ports as params for nm.App
Browse files Browse the repository at this point in the history
  • Loading branch information
toni-neurosc committed Nov 28, 2024
1 parent f5f810d commit f571c50
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 17 deletions.
4 changes: 2 additions & 2 deletions gui_dev/src/utils/getBackendURL.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export const getBackendURL = (route) => {
return "http://localhost:50001" + route;
}
return "http://localhost:" + import.meta.env.VITE_BACKEND_PORT + route;
};
9 changes: 6 additions & 3 deletions py_neuromodulation/gui/backend/app_backend.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
from email import errors
import logging
import asyncio
import importlib.metadata
from datetime import datetime
from pathlib import Path
Expand Down Expand Up @@ -34,6 +32,7 @@ def __init__(
pynm_state: app_pynm.PyNMState,
debug=False,
dev=True,
dev_port: int | None = None,
fastapi_kwargs: dict = {},
) -> None:
super().__init__(debug=debug, **fastapi_kwargs)
Expand All @@ -45,10 +44,14 @@ def __init__(
self.logger = logging.getLogger("uvicorn.error")
self.logger.warning(PYNM_DIR)

cors_origins = (
["http://localhost:" + str(dev_port)] if dev_port is not None else []
)

# Configure CORS
self.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:54321"],
allow_origins=cors_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
Expand Down
42 changes: 30 additions & 12 deletions py_neuromodulation/gui/backend/app_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@

if TYPE_CHECKING:
from multiprocessing.synchronize import Event
from .app_backend import PyNMBackend


# Shared memory configuration
Expand All @@ -22,21 +21,32 @@
DEV_SERVER_PORT = 54321


def create_backend() -> "PyNMBackend":
def create_backend():
"""Factory function passed to Uvicorn to create the web application instance.
:return: The web application instance.
:rtype: PyNMBackend
"""
from .app_pynm import PyNMState
from .app_backend import PyNMBackend

debug = os.environ.get("PYNM_DEBUG", "False").lower() == "true"
dev = os.environ.get("PYNM_DEV", "True").lower() == "true"
dev_port = os.environ.get("PYNM_DEV_PORT", str(DEV_SERVER_PORT))

return PyNMBackend(pynm_state=PyNMState(), debug=debug, dev=dev)
return PyNMBackend(
pynm_state=PyNMState(),
debug=debug,
dev=dev,
dev_port=int(dev_port),
)


def run_vite(
shutdown_event: "Event",
debug: bool = False,
scan: bool = False,
dev_port: int = DEV_SERVER_PORT,
backend_port: int = SERVER_PORT,
) -> None:
"""Run Vite in a separate shell"""
import subprocess
Expand All @@ -49,7 +59,7 @@ def run_vite(
logging.DEBUG if debug else logging.INFO,
)

os.environ["VITE_REACT_SCAN"] = "true" if scan else "false"
os.environ["VITE_BACKEND_PORT"] = str(backend_port)

def output_reader(shutdown_event: "Event", process: subprocess.Popen):
logger.debug("Initialized output stream")
Expand Down Expand Up @@ -116,7 +126,9 @@ def read_stream(stream, stream_name):
logger.info("Development server stopped")


def run_uvicorn(debug: bool = False, reload=False) -> None:
def run_uvicorn(
debug: bool = False, reload=False, server_port: int = SERVER_PORT
) -> None:
from uvicorn.server import Server
from uvicorn.config import LOGGING_CONFIG, Config

Expand All @@ -141,7 +153,7 @@ def run_uvicorn(debug: bool = False, reload=False) -> None:
host="localhost",
reload=reload,
factory=True,
port=50001,
port=server_port,
log_level="debug" if debug else "info",
log_config=log_config,
)
Expand Down Expand Up @@ -170,17 +182,23 @@ def restart(self) -> None:


def run_backend(
shutdown_event: "Event", debug: bool = False, reload: bool = True, dev: bool = True
shutdown_event: "Event",
dev: bool = True,
debug: bool = False,
reload: bool = True,
server_port: int = SERVER_PORT,
dev_port: int = DEV_SERVER_PORT,
) -> None:
signal.signal(signal.SIGINT, signal.SIG_IGN)

# Pass create_backend parameters through environment variables
os.environ["PYNM_DEBUG"] = str(debug)
os.environ["PYNM_DEV"] = str(dev)
os.environ["PYNM_DEV_PORT"] = str(dev_port)

server_process = mp.Process(
target=run_uvicorn,
kwargs={"debug": debug, "reload": reload},
kwargs={"debug": debug, "reload": reload, "server_port": server_port},
name="Server",
)
server_process.start()
Expand All @@ -196,7 +214,6 @@ def __init__(
debug: bool = False,
dev: bool = True,
run_in_webview=False,
scan=False,
server_port=SERVER_PORT,
dev_port=DEV_SERVER_PORT,
) -> None:
Expand All @@ -213,7 +230,6 @@ def __init__(
self.debug = debug
self.dev = dev
self.run_in_webview = run_in_webview
self.scan = scan
self.server_port = server_port
self.dev_port = dev_port

Expand Down Expand Up @@ -293,8 +309,8 @@ def launch(self) -> None:
kwargs={
"shutdown_event": self.shutdown_event,
"debug": self.debug,
"scan": self.scan,
"dev_port": self.dev_port,
"backend_port": self.server_port,
},
name="Vite",
)
Expand All @@ -307,6 +323,8 @@ def launch(self) -> None:
"debug": self.debug,
"reload": self.dev,
"dev": self.dev,
"server_port": self.server_port,
"dev_port": self.dev_port,
},
name="Backend",
)
Expand Down

0 comments on commit f571c50

Please sign in to comment.