Skip to content

Commit

Permalink
⚡️🗑️💥🚧Cleaned up tornado stuffs
Browse files Browse the repository at this point in the history
And replaced it with `AssetsEndpoint`
  • Loading branch information
carefree0910 committed Apr 21, 2023
1 parent 3e9c189 commit 2ba60c9
Show file tree
Hide file tree
Showing 14 changed files with 229 additions and 353 deletions.
5 changes: 3 additions & 2 deletions cfdraw/app/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ def __init__(self) -> None:
PluginsEndpoint(self),
WebsocketEndpoint(self),
]
if self.config.use_unified:
self.endpoints.append(AssetsEndpoint(self))
for endpoint in self.endpoints:
endpoint.register()
self.hash = random_hash()
Expand Down Expand Up @@ -65,8 +67,7 @@ def add_events(self) -> None:
@self.api.on_event("startup")
async def startup() -> None:
def info(msg: str) -> None:
if not self.config.use_tornado:
print_info(msg)
print_info(msg)

self.hash = random_hash()
info(f"🚀 Starting Backend Server at {self.config.api_url} ...")
Expand Down
1 change: 1 addition & 0 deletions cfdraw/app/endpoints/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from .base import *
from .assets import *
from .upload import *
from .plugins import *
from .project import *
Expand Down
27 changes: 27 additions & 0 deletions cfdraw/app/endpoints/assets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles

from cfdraw import constants
from cfdraw.app.schema import IApp
from cfdraw.app.endpoints.base import IEndpoint


def add_assets(app: IApp) -> None:
@app.api.get("/", response_class=HTMLResponse)
async def root() -> str:
index_file = build_dir / "index.html"
with open(index_file, "r", encoding="utf-8") as f:
return f.read()

build_dir = constants.WEB_ROOT / "dist"
app.api.mount("/assets", StaticFiles(directory=str(build_dir / "assets")), "assets")


class AssetsEndpoint(IEndpoint):
def register(self) -> None:
add_assets(self.app)


__all__ = [
"AssetsEndpoint",
]
14 changes: 5 additions & 9 deletions cfdraw/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,18 +27,18 @@ def run(
help="The log level to use.",
),
prod: bool = typer.Option(False, help="Whether to run in production mode."),
tornado: bool = typer.Option(False, help="Whether use tornado to unify servers."),
unified: bool = typer.Option(False, help="Whether use unified servers."),
) -> None:
sys.path.insert(0, os.getcwd())
if tornado:
if unified:
if not prod:
console.print(
"[bold orange1]Tornado is only available in production mode, "
"[bold orange1]`--unified` is only available in production mode, "
"so `--prod` flag will be forced."
)
prod = True
constants.set_env(constants.Env.PROD if prod else constants.Env.DEV)
constants.set_tornado(tornado)
constants.set_unified(unified)
# fetch config
config = get_config()
# fetch module
Expand All @@ -53,21 +53,17 @@ def run(
# execute
frontend_port = config.frontend_port
backend_port = config.backend_port
tornado_port = config.tornado_port
if not no_frontend and processes.is_process_on_port(frontend_port):
frontend_port = processes.change_or_terminate_port(frontend_port, "frontend")
if not no_backend and processes.is_process_on_port(backend_port):
backend_port = processes.change_or_terminate_port(backend_port, "backend")
if tornado and not no_backend and processes.is_process_on_port(tornado_port):
tornado_port = processes.change_or_terminate_port(tornado_port, "tornado")
config.frontend_port = frontend_port
config.backend_port = backend_port
config.tornado_port = tornado_port
if not prod:
frontend_fn, backend_fn = exec.run_frontend, exec.run_backend
else:
frontend_fn = exec.run_frontend_prod
backend_fn = exec.run_tornado if tornado else exec.run_backend
backend_fn = exec.run_backend_prod
try:
if not no_frontend:
frontend_fn()
Expand Down
11 changes: 7 additions & 4 deletions cfdraw/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ class Config:
frontend_port: str = constants.FRONTEND_PORT
# api
backend_port: str = constants.BACKEND_PORT
tornado_port: str = constants.TORNADO_PORT
backend_hosting_url: Optional[str] = None # this must be provided for hosting
# upload
upload_root: str = str(constants.UPLOAD_ROOT)
Expand All @@ -29,12 +28,12 @@ def prod(self) -> bool:
return constants.get_env() == constants.Env.PROD

@property
def use_tornado(self) -> bool:
return constants.use_tornado()
def use_unified(self) -> bool:
return constants.use_unified()

@property
def api_port(self) -> str:
return self.tornado_port if self.use_tornado else self.backend_port
return self.backend_port

@property
def api_url(self) -> str:
Expand All @@ -48,6 +47,10 @@ def api_url(self) -> str:
api_url = f"http://localhost:{self.api_port}"
return api_url.rstrip("/").rstrip("\\")

@property
def frontend_url(self) -> str:
return f"http://localhost:{self.frontend_port}"

@property
def upload_root_path(self) -> Path:
return Path(self.upload_root).absolute()
Expand Down
11 changes: 5 additions & 6 deletions cfdraw/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
# api
ERR_CODE = 406
BACKEND_PORT = "8123"
TORNADO_PORT = "8234"
DEV_BACKEND_HOST = "0.0.0.0"
API_URL_KEY = "CFDRAW_API_URL"

Expand All @@ -33,7 +32,7 @@ def __str__(self) -> str:

# misc
ENV_KEY = "CFDRAW_ENV"
TORNADO_KEY = "CFDRAW_TORNADO"
UNIFIED_KEY = "CFDRAW_UNIFIED"


class Env(str, Enum):
Expand All @@ -49,12 +48,12 @@ def set_env(env: Env) -> None:
os.environ[ENV_KEY] = env.value


def use_tornado() -> bool:
return os.environ.get(TORNADO_KEY, None) == "enabled"
def use_unified() -> bool:
return os.environ.get(UNIFIED_KEY, None) == "enabled"


def set_tornado(enable: bool) -> None:
os.environ[TORNADO_KEY] = "enabled" if enable else "disabled"
def set_unified(enable: bool) -> None:
os.environ[UNIFIED_KEY] = "enabled" if enable else "disabled"


class LogLevel(str, Enum):
Expand Down
44 changes: 0 additions & 44 deletions cfdraw/server/__init__.py

This file was deleted.

42 changes: 0 additions & 42 deletions cfdraw/server/http.py

This file was deleted.

17 changes: 0 additions & 17 deletions cfdraw/server/index.py

This file was deleted.

45 changes: 0 additions & 45 deletions cfdraw/server/socket.py

This file was deleted.

36 changes: 16 additions & 20 deletions cfdraw/utils/exec.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
from cfdraw.utils import console
from cfdraw.utils import prerequisites
from cfdraw.config import get_config
from cfdraw.config import Config
from cfdraw.server import launch_server


def setup_frontend() -> None:
Expand All @@ -31,14 +29,13 @@ def run_frontend() -> None:
stdout=subprocess.DEVNULL,
stderr=subprocess.STDOUT,
)
frontend_url = f"http://localhost:{get_config().frontend_port}"
print_info(f"👌 Your app will be ready at {frontend_url} soon...")
print_info(f"👌 Your app will be ready at {get_config().frontend_url} soon...")


def run_frontend_prod() -> None:
setup_frontend()
config = get_config()
if config.use_tornado:
if config.use_unified:
print_info(f"👀 Your app codes are being compiled, please wait for a while...")
subprocess.run(
[prerequisites.get_yarn(), "build"],
Expand All @@ -57,8 +54,14 @@ def run_frontend_prod() -> None:
)


def run_backend(module: str, *, log_level: constants.LogLevel) -> None:
console.rule("[bold green]Launching Backend")
def run_backend(
module: str,
*,
log_level: constants.LogLevel,
verbose: bool = True,
) -> None:
if verbose:
console.rule("[bold green]Launching Backend")
config = get_config()
# I'm not familiar with production stuffs of `uvicorn`, so currently
# only the `reload` flag is different.
Expand All @@ -71,16 +74,9 @@ def run_backend(module: str, *, log_level: constants.LogLevel) -> None:
)


def run_tornado(module: str, *, log_level: constants.LogLevel) -> None:
def before_launch(config: Config) -> None:
cmd = [
"uvicorn",
f"{module}:{config.entry}.{constants.API_VAR}",
f"--host={constants.DEV_BACKEND_HOST}",
f"--port={config.backend_port}",
f"--log-level={log_level}",
]
subprocess.Popen(cmd)

console.rule("[bold green]Launching Tornado Backend")
launch_server(before_launch)
def run_backend_prod(module: str, *, log_level: constants.LogLevel) -> None:
console.rule("[bold green]Launching Production Backend")
config = get_config()
if config.use_unified:
print_info(f"👌 Your app will be ready at {config.api_url} soon...")
run_backend(module, log_level=log_level, verbose=False)

0 comments on commit 2ba60c9

Please sign in to comment.