exec.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. """Everything regarding execution of the built app."""
  2. from __future__ import annotations
  3. import hashlib
  4. import json
  5. import os
  6. import platform
  7. import re
  8. import subprocess
  9. import sys
  10. from pathlib import Path
  11. from typing import Sequence
  12. from urllib.parse import urljoin
  13. import psutil
  14. from reflex import constants
  15. from reflex.config import environment, get_config
  16. from reflex.constants.base import LogLevel
  17. from reflex.utils import console, path_ops
  18. from reflex.utils.prerequisites import get_web_dir
  19. # For uvicorn windows bug fix (#2335)
  20. frontend_process = None
  21. def detect_package_change(json_file_path: Path) -> str:
  22. """Calculates the SHA-256 hash of a JSON file and returns it as a hexadecimal string.
  23. Args:
  24. json_file_path: The path to the JSON file to be hashed.
  25. Returns:
  26. str: The SHA-256 hash of the JSON file as a hexadecimal string.
  27. Example:
  28. >>> detect_package_change("package.json")
  29. 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6a7b8c9d0e1f2'
  30. """
  31. with json_file_path.open("r") as file:
  32. json_data = json.load(file)
  33. # Calculate the hash
  34. json_string = json.dumps(json_data, sort_keys=True)
  35. hash_object = hashlib.sha256(json_string.encode())
  36. return hash_object.hexdigest()
  37. def kill(proc_pid: int):
  38. """Kills a process and all its child processes.
  39. Args:
  40. proc_pid (int): The process ID of the process to be killed.
  41. Example:
  42. >>> kill(1234)
  43. """
  44. process = psutil.Process(proc_pid)
  45. for proc in process.children(recursive=True):
  46. proc.kill()
  47. process.kill()
  48. def notify_backend():
  49. """Output a string notifying where the backend is running."""
  50. console.print(
  51. f"Backend running at: [bold green]http://0.0.0.0:{get_config().backend_port}[/bold green]"
  52. )
  53. # run_process_and_launch_url is assumed to be used
  54. # only to launch the frontend
  55. # If this is not the case, might have to change the logic
  56. def run_process_and_launch_url(
  57. run_command: list[str | None], backend_present: bool = True
  58. ):
  59. """Run the process and launch the URL.
  60. Args:
  61. run_command: The command to run.
  62. backend_present: Whether the backend is present.
  63. """
  64. from reflex.utils import processes
  65. json_file_path = get_web_dir() / constants.PackageJson.PATH
  66. last_hash = detect_package_change(json_file_path)
  67. process = None
  68. first_run = True
  69. while True:
  70. if process is None:
  71. kwargs = {}
  72. if constants.IS_WINDOWS and backend_present:
  73. kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # pyright: ignore [reportAttributeAccessIssue]
  74. process = processes.new_process(
  75. run_command,
  76. cwd=get_web_dir(),
  77. shell=constants.IS_WINDOWS,
  78. **kwargs,
  79. )
  80. global frontend_process
  81. frontend_process = process
  82. if process.stdout:
  83. for line in processes.stream_logs("Starting frontend", process):
  84. match = re.search(constants.Next.FRONTEND_LISTENING_REGEX, line)
  85. if match:
  86. if first_run:
  87. url = match.group(1)
  88. if get_config().frontend_path != "":
  89. url = urljoin(url, get_config().frontend_path)
  90. console.print(
  91. f"App running at: [bold green]{url}[/bold green]{' (Frontend-only mode)' if not backend_present else ''}"
  92. )
  93. if backend_present:
  94. notify_backend()
  95. first_run = False
  96. else:
  97. console.print("New packages detected: Updating app...")
  98. else:
  99. if any(
  100. x in line for x in ("bin executable does not exist on disk",)
  101. ):
  102. console.error(
  103. "Try setting `REFLEX_USE_NPM=1` and re-running `reflex init` and `reflex run` to use npm instead of bun:\n"
  104. "`REFLEX_USE_NPM=1 reflex init`\n"
  105. "`REFLEX_USE_NPM=1 reflex run`"
  106. )
  107. new_hash = detect_package_change(json_file_path)
  108. if new_hash != last_hash:
  109. last_hash = new_hash
  110. kill(process.pid)
  111. process = None
  112. break # for line in process.stdout
  113. if process is not None:
  114. break # while True
  115. def run_frontend(root: Path, port: str, backend_present: bool = True):
  116. """Run the frontend.
  117. Args:
  118. root: The root path of the project.
  119. port: The port to run the frontend on.
  120. backend_present: Whether the backend is present.
  121. """
  122. from reflex.utils import prerequisites
  123. # validate dependencies before run
  124. prerequisites.validate_frontend_dependencies(init=False)
  125. # Run the frontend in development mode.
  126. console.rule("[bold green]App Running")
  127. os.environ["PORT"] = str(get_config().frontend_port if port is None else port)
  128. run_process_and_launch_url(
  129. [
  130. *prerequisites.get_js_package_executor(raise_on_none=True)[0],
  131. "run",
  132. "dev",
  133. ],
  134. backend_present,
  135. )
  136. def run_frontend_prod(root: Path, port: str, backend_present: bool = True):
  137. """Run the frontend.
  138. Args:
  139. root: The root path of the project (to keep same API as run_frontend).
  140. port: The port to run the frontend on.
  141. backend_present: Whether the backend is present.
  142. """
  143. from reflex.utils import prerequisites
  144. # Set the port.
  145. os.environ["PORT"] = str(get_config().frontend_port if port is None else port)
  146. # validate dependencies before run
  147. prerequisites.validate_frontend_dependencies(init=False)
  148. # Run the frontend in production mode.
  149. console.rule("[bold green]App Running")
  150. run_process_and_launch_url(
  151. [*prerequisites.get_js_package_executor(raise_on_none=True)[0], "run", "prod"],
  152. backend_present,
  153. )
  154. def should_use_granian():
  155. """Whether to use Granian for backend.
  156. Returns:
  157. True if Granian should be used.
  158. """
  159. return environment.REFLEX_USE_GRANIAN.get()
  160. def get_app_module():
  161. """Get the app module for the backend.
  162. Returns:
  163. The app module for the backend.
  164. """
  165. return f"reflex.app_module_for_backend:{constants.CompileVars.APP}"
  166. def get_granian_target():
  167. """Get the Granian target for the backend.
  168. Returns:
  169. The Granian target for the backend.
  170. """
  171. import reflex
  172. app_module_path = Path(reflex.__file__).parent / "app_module_for_backend.py"
  173. return (
  174. f"{app_module_path!s}:{constants.CompileVars.APP}.{constants.CompileVars.API}"
  175. )
  176. def run_backend(
  177. host: str,
  178. port: int,
  179. loglevel: constants.LogLevel = constants.LogLevel.ERROR,
  180. frontend_present: bool = False,
  181. ):
  182. """Run the backend.
  183. Args:
  184. host: The app host
  185. port: The app port
  186. loglevel: The log level.
  187. frontend_present: Whether the frontend is present.
  188. """
  189. web_dir = get_web_dir()
  190. # Create a .nocompile file to skip compile for backend.
  191. if web_dir.exists():
  192. (web_dir / constants.NOCOMPILE_FILE).touch()
  193. if not frontend_present:
  194. notify_backend()
  195. # Run the backend in development mode.
  196. if should_use_granian():
  197. run_granian_backend(host, port, loglevel)
  198. else:
  199. run_uvicorn_backend(host, port, loglevel)
  200. def get_reload_paths() -> Sequence[Path]:
  201. """Get the reload paths for the backend.
  202. Returns:
  203. The reload paths for the backend.
  204. """
  205. config = get_config()
  206. reload_paths = [Path(config.app_name).parent]
  207. if config.app_module is not None and config.app_module.__file__:
  208. module_path = Path(config.app_module.__file__).resolve().parent
  209. while module_path.parent.name and any(
  210. sibling_file.name == "__init__.py"
  211. for sibling_file in module_path.parent.iterdir()
  212. ):
  213. # go up a level to find dir without `__init__.py`
  214. module_path = module_path.parent
  215. reload_paths = [module_path]
  216. include_dirs = tuple(
  217. map(Path.absolute, environment.REFLEX_HOT_RELOAD_INCLUDE_PATHS.get())
  218. )
  219. exclude_dirs = tuple(
  220. map(Path.absolute, environment.REFLEX_HOT_RELOAD_EXCLUDE_PATHS.get())
  221. )
  222. def is_excluded_by_default(path: Path) -> bool:
  223. if path.is_dir():
  224. if path.name.startswith("."):
  225. # exclude hidden directories
  226. return True
  227. if path.name.startswith("__"):
  228. # ignore things like __pycache__
  229. return True
  230. return path.name in (".gitignore", "uploaded_files")
  231. reload_paths = (
  232. tuple(
  233. path.absolute()
  234. for dir in reload_paths
  235. for path in dir.iterdir()
  236. if not is_excluded_by_default(path)
  237. )
  238. + include_dirs
  239. )
  240. if exclude_dirs:
  241. reload_paths = tuple(
  242. path
  243. for path in reload_paths
  244. if all(not path.samefile(exclude) for exclude in exclude_dirs)
  245. )
  246. console.debug(f"Reload paths: {list(map(str, reload_paths))}")
  247. return reload_paths
  248. def run_uvicorn_backend(host: str, port: int, loglevel: LogLevel):
  249. """Run the backend in development mode using Uvicorn.
  250. Args:
  251. host: The app host
  252. port: The app port
  253. loglevel: The log level.
  254. """
  255. import uvicorn
  256. uvicorn.run(
  257. app=f"{get_app_module()}.{constants.CompileVars.API}",
  258. host=host,
  259. port=port,
  260. log_level=loglevel.value,
  261. reload=True,
  262. reload_dirs=list(map(str, get_reload_paths())),
  263. )
  264. def run_granian_backend(host: str, port: int, loglevel: LogLevel):
  265. """Run the backend in development mode using Granian.
  266. Args:
  267. host: The app host
  268. port: The app port
  269. loglevel: The log level.
  270. """
  271. console.debug("Using Granian for backend")
  272. try:
  273. from granian.constants import Interfaces
  274. from granian.log import LogLevels
  275. from granian.server import Server as Granian
  276. Granian(
  277. target=get_granian_target(),
  278. address=host,
  279. port=port,
  280. interface=Interfaces.ASGI,
  281. log_level=LogLevels(loglevel.value),
  282. reload=True,
  283. reload_paths=get_reload_paths(),
  284. ).serve()
  285. except ImportError:
  286. console.error(
  287. 'InstallError: REFLEX_USE_GRANIAN is set but `granian` is not installed. (run `pip install "granian[reload]>=1.6.0"`)'
  288. )
  289. os._exit(1)
  290. def _get_backend_workers():
  291. from reflex.utils import processes
  292. config = get_config()
  293. return (
  294. processes.get_num_workers()
  295. if not config.gunicorn_workers
  296. else config.gunicorn_workers
  297. )
  298. def run_backend_prod(
  299. host: str,
  300. port: int,
  301. loglevel: constants.LogLevel = constants.LogLevel.ERROR,
  302. frontend_present: bool = False,
  303. ):
  304. """Run the backend.
  305. Args:
  306. host: The app host
  307. port: The app port
  308. loglevel: The log level.
  309. frontend_present: Whether the frontend is present.
  310. """
  311. if not frontend_present:
  312. notify_backend()
  313. if should_use_granian():
  314. run_granian_backend_prod(host, port, loglevel)
  315. else:
  316. run_uvicorn_backend_prod(host, port, loglevel)
  317. def run_uvicorn_backend_prod(host: str, port: int, loglevel: LogLevel):
  318. """Run the backend in production mode using Uvicorn.
  319. Args:
  320. host: The app host
  321. port: The app port
  322. loglevel: The log level.
  323. """
  324. from reflex.utils import processes
  325. config = get_config()
  326. app_module = get_app_module()
  327. command = (
  328. [
  329. "uvicorn",
  330. *(
  331. [
  332. "--limit-max-requests",
  333. str(config.gunicorn_max_requests),
  334. ]
  335. if config.gunicorn_max_requests > 0
  336. else []
  337. ),
  338. *("--timeout-keep-alive", str(config.timeout)),
  339. *("--host", host),
  340. *("--port", str(port)),
  341. *("--workers", str(_get_backend_workers())),
  342. app_module,
  343. ]
  344. if constants.IS_WINDOWS
  345. else [
  346. "gunicorn",
  347. *("--worker-class", config.gunicorn_worker_class),
  348. *(
  349. [
  350. "--max-requests",
  351. str(config.gunicorn_max_requests),
  352. "--max-requests-jitter",
  353. str(config.gunicorn_max_requests_jitter),
  354. ]
  355. if config.gunicorn_max_requests > 0
  356. else []
  357. ),
  358. "--preload",
  359. *("--timeout", str(config.timeout)),
  360. *("--bind", f"{host}:{port}"),
  361. *("--threads", str(_get_backend_workers())),
  362. f"{app_module}()",
  363. ]
  364. )
  365. command += [
  366. *("--log-level", loglevel.value),
  367. ]
  368. processes.new_process(
  369. command,
  370. run=True,
  371. show_logs=True,
  372. env={
  373. environment.REFLEX_SKIP_COMPILE.name: "true"
  374. }, # skip compile for prod backend
  375. )
  376. def run_granian_backend_prod(host: str, port: int, loglevel: LogLevel):
  377. """Run the backend in production mode using Granian.
  378. Args:
  379. host: The app host
  380. port: The app port
  381. loglevel: The log level.
  382. """
  383. from reflex.utils import processes
  384. try:
  385. from granian.constants import Interfaces
  386. command = [
  387. "granian",
  388. "--workers",
  389. str(_get_backend_workers()),
  390. "--log-level",
  391. "critical",
  392. "--host",
  393. host,
  394. "--port",
  395. str(port),
  396. "--interface",
  397. str(Interfaces.ASGI),
  398. get_granian_target(),
  399. ]
  400. processes.new_process(
  401. command,
  402. run=True,
  403. show_logs=True,
  404. env={
  405. environment.REFLEX_SKIP_COMPILE.name: "true"
  406. }, # skip compile for prod backend
  407. )
  408. except ImportError:
  409. console.error(
  410. 'InstallError: REFLEX_USE_GRANIAN is set but `granian` is not installed. (run `pip install "granian[reload]>=1.6.0"`)'
  411. )
  412. def output_system_info():
  413. """Show system information if the loglevel is in DEBUG."""
  414. if console._LOG_LEVEL > constants.LogLevel.DEBUG:
  415. return
  416. from reflex.utils import prerequisites
  417. config = get_config()
  418. try:
  419. config_file = sys.modules[config.__module__].__file__
  420. except Exception:
  421. config_file = None
  422. console.rule("System Info")
  423. console.debug(f"Config file: {config_file!r}")
  424. console.debug(f"Config: {config}")
  425. dependencies = [
  426. f"[Reflex {constants.Reflex.VERSION} with Python {platform.python_version()} (PATH: {sys.executable})]",
  427. f"[Node {prerequisites.get_node_version()} (Expected: {constants.Node.VERSION}) (PATH:{path_ops.get_node_path()})]",
  428. ]
  429. system = platform.system()
  430. dependencies.append(
  431. f"[Bun {prerequisites.get_bun_version()} (Expected: {constants.Bun.VERSION}) (PATH: {path_ops.get_bun_path()})]"
  432. )
  433. if system == "Linux":
  434. import distro # pyright: ignore[reportMissingImports]
  435. os_version = distro.name(pretty=True)
  436. else:
  437. os_version = platform.version()
  438. dependencies.append(f"[OS {platform.system()} {os_version}]")
  439. for dep in dependencies:
  440. console.debug(f"{dep}")
  441. console.debug(
  442. f"Using package installer at: {prerequisites.get_nodejs_compatible_package_managers(raise_on_none=False)}"
  443. )
  444. console.debug(
  445. f"Using package executer at: {prerequisites.get_js_package_executor(raise_on_none=False)}"
  446. )
  447. if system != "Windows":
  448. console.debug(f"Unzip path: {path_ops.which('unzip')}")
  449. def is_testing_env() -> bool:
  450. """Whether the app is running in a testing environment.
  451. Returns:
  452. True if the app is running in under pytest.
  453. """
  454. return constants.PYTEST_CURRENT_TEST in os.environ
  455. def is_in_app_harness() -> bool:
  456. """Whether the app is running in the app harness.
  457. Returns:
  458. True if the app is running in the app harness.
  459. """
  460. return constants.APP_HARNESS_FLAG in os.environ
  461. def is_prod_mode() -> bool:
  462. """Check if the app is running in production mode.
  463. Returns:
  464. True if the app is running in production mode or False if running in dev mode.
  465. """
  466. current_mode = environment.REFLEX_ENV_MODE.get()
  467. return current_mode == constants.Env.PROD
  468. def get_compile_context() -> constants.CompileContext:
  469. """Check if the app is compiled for deploy.
  470. Returns:
  471. Whether the app is being compiled for deploy.
  472. """
  473. return environment.REFLEX_COMPILE_CONTEXT.get()