exec.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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. [prerequisites.get_package_manager(), "run", "dev"],
  130. backend_present,
  131. )
  132. def run_frontend_prod(root: Path, port: str, backend_present: bool = True):
  133. """Run the frontend.
  134. Args:
  135. root: The root path of the project (to keep same API as run_frontend).
  136. port: The port to run the frontend on.
  137. backend_present: Whether the backend is present.
  138. """
  139. from reflex.utils import prerequisites
  140. # Set the port.
  141. os.environ["PORT"] = str(get_config().frontend_port if port is None else port)
  142. # validate dependencies before run
  143. prerequisites.validate_frontend_dependencies(init=False)
  144. # Run the frontend in production mode.
  145. console.rule("[bold green]App Running")
  146. run_process_and_launch_url(
  147. [prerequisites.get_package_manager(), "run", "prod"],
  148. backend_present,
  149. )
  150. def should_use_granian():
  151. """Whether to use Granian for backend.
  152. Returns:
  153. True if Granian should be used.
  154. """
  155. return environment.REFLEX_USE_GRANIAN.get()
  156. def get_app_module():
  157. """Get the app module for the backend.
  158. Returns:
  159. The app module for the backend.
  160. """
  161. return f"reflex.app_module_for_backend:{constants.CompileVars.APP}"
  162. def get_granian_target():
  163. """Get the Granian target for the backend.
  164. Returns:
  165. The Granian target for the backend.
  166. """
  167. import reflex
  168. app_module_path = Path(reflex.__file__).parent / "app_module_for_backend.py"
  169. return (
  170. f"{app_module_path!s}:{constants.CompileVars.APP}.{constants.CompileVars.API}"
  171. )
  172. def run_backend(
  173. host: str,
  174. port: int,
  175. loglevel: constants.LogLevel = constants.LogLevel.ERROR,
  176. frontend_present: bool = False,
  177. ):
  178. """Run the backend.
  179. Args:
  180. host: The app host
  181. port: The app port
  182. loglevel: The log level.
  183. frontend_present: Whether the frontend is present.
  184. """
  185. web_dir = get_web_dir()
  186. # Create a .nocompile file to skip compile for backend.
  187. if web_dir.exists():
  188. (web_dir / constants.NOCOMPILE_FILE).touch()
  189. if not frontend_present:
  190. notify_backend()
  191. # Run the backend in development mode.
  192. if should_use_granian():
  193. run_granian_backend(host, port, loglevel)
  194. else:
  195. run_uvicorn_backend(host, port, loglevel)
  196. def get_reload_paths() -> Sequence[Path]:
  197. """Get the reload paths for the backend.
  198. Returns:
  199. The reload paths for the backend.
  200. """
  201. config = get_config()
  202. reload_paths = [Path(config.app_name).parent]
  203. if config.app_module is not None and config.app_module.__file__:
  204. module_path = Path(config.app_module.__file__).resolve().parent
  205. while module_path.parent.name and any(
  206. sibling_file.name == "__init__.py"
  207. for sibling_file in module_path.parent.iterdir()
  208. ):
  209. # go up a level to find dir without `__init__.py`
  210. module_path = module_path.parent
  211. reload_paths = [module_path]
  212. include_dirs = tuple(
  213. map(Path.absolute, environment.REFLEX_HOT_RELOAD_INCLUDE_PATHS.get())
  214. )
  215. exclude_dirs = tuple(
  216. map(Path.absolute, environment.REFLEX_HOT_RELOAD_EXCLUDE_PATHS.get())
  217. )
  218. def is_excluded_by_default(path: Path) -> bool:
  219. if path.is_dir():
  220. if path.name.startswith("."):
  221. # exclude hidden directories
  222. return True
  223. if path.name.startswith("__"):
  224. # ignore things like __pycache__
  225. return True
  226. return path.name in (".gitignore", "uploaded_files")
  227. reload_paths = (
  228. tuple(
  229. path.absolute()
  230. for dir in reload_paths
  231. for path in dir.iterdir()
  232. if not is_excluded_by_default(path)
  233. )
  234. + include_dirs
  235. )
  236. if exclude_dirs:
  237. reload_paths = tuple(
  238. path
  239. for path in reload_paths
  240. if all(not path.samefile(exclude) for exclude in exclude_dirs)
  241. )
  242. console.debug(f"Reload paths: {list(map(str, reload_paths))}")
  243. return reload_paths
  244. def run_uvicorn_backend(host: str, port: int, loglevel: LogLevel):
  245. """Run the backend in development mode using Uvicorn.
  246. Args:
  247. host: The app host
  248. port: The app port
  249. loglevel: The log level.
  250. """
  251. import uvicorn
  252. uvicorn.run(
  253. app=f"{get_app_module()}.{constants.CompileVars.API}",
  254. host=host,
  255. port=port,
  256. log_level=loglevel.value,
  257. reload=True,
  258. reload_dirs=list(map(str, get_reload_paths())),
  259. )
  260. def run_granian_backend(host: str, port: int, loglevel: LogLevel):
  261. """Run the backend in development mode using Granian.
  262. Args:
  263. host: The app host
  264. port: The app port
  265. loglevel: The log level.
  266. """
  267. console.debug("Using Granian for backend")
  268. try:
  269. from granian import Granian # pyright: ignore [reportMissingImports]
  270. from granian.constants import ( # pyright: ignore [reportMissingImports]
  271. Interfaces,
  272. )
  273. from granian.log import LogLevels # pyright: ignore [reportMissingImports]
  274. Granian(
  275. target=get_granian_target(),
  276. address=host,
  277. port=port,
  278. interface=Interfaces.ASGI,
  279. log_level=LogLevels(loglevel.value),
  280. reload=True,
  281. reload_paths=get_reload_paths(),
  282. ).serve()
  283. except ImportError:
  284. console.error(
  285. 'InstallError: REFLEX_USE_GRANIAN is set but `granian` is not installed. (run `pip install "granian[reload]>=1.6.0"`)'
  286. )
  287. os._exit(1)
  288. def _get_backend_workers():
  289. from reflex.utils import processes
  290. config = get_config()
  291. return (
  292. processes.get_num_workers()
  293. if not config.gunicorn_workers
  294. else config.gunicorn_workers
  295. )
  296. def run_backend_prod(
  297. host: str,
  298. port: int,
  299. loglevel: constants.LogLevel = constants.LogLevel.ERROR,
  300. frontend_present: bool = False,
  301. ):
  302. """Run the backend.
  303. Args:
  304. host: The app host
  305. port: The app port
  306. loglevel: The log level.
  307. frontend_present: Whether the frontend is present.
  308. """
  309. if not frontend_present:
  310. notify_backend()
  311. if should_use_granian():
  312. run_granian_backend_prod(host, port, loglevel)
  313. else:
  314. run_uvicorn_backend_prod(host, port, loglevel)
  315. def run_uvicorn_backend_prod(host: str, port: int, loglevel: LogLevel):
  316. """Run the backend in production mode using Uvicorn.
  317. Args:
  318. host: The app host
  319. port: The app port
  320. loglevel: The log level.
  321. """
  322. from reflex.utils import processes
  323. config = get_config()
  324. app_module = get_app_module()
  325. command = (
  326. [
  327. "uvicorn",
  328. *(
  329. [
  330. "--limit-max-requests",
  331. str(config.gunicorn_max_requests),
  332. ]
  333. if config.gunicorn_max_requests > 0
  334. else []
  335. ),
  336. *("--timeout-keep-alive", str(config.timeout)),
  337. *("--host", host),
  338. *("--port", str(port)),
  339. *("--workers", str(_get_backend_workers())),
  340. app_module,
  341. ]
  342. if constants.IS_WINDOWS
  343. else [
  344. "gunicorn",
  345. *("--worker-class", config.gunicorn_worker_class),
  346. *(
  347. [
  348. "--max-requests",
  349. str(config.gunicorn_max_requests),
  350. "--max-requests-jitter",
  351. str(config.gunicorn_max_requests_jitter),
  352. ]
  353. if config.gunicorn_max_requests > 0
  354. else []
  355. ),
  356. "--preload",
  357. *("--timeout", str(config.timeout)),
  358. *("--bind", f"{host}:{port}"),
  359. *("--threads", str(_get_backend_workers())),
  360. f"{app_module}()",
  361. ]
  362. )
  363. command += [
  364. *("--log-level", loglevel.value),
  365. ]
  366. processes.new_process(
  367. command,
  368. run=True,
  369. show_logs=True,
  370. env={
  371. environment.REFLEX_SKIP_COMPILE.name: "true"
  372. }, # skip compile for prod backend
  373. )
  374. def run_granian_backend_prod(host: str, port: int, loglevel: LogLevel):
  375. """Run the backend in production mode using Granian.
  376. Args:
  377. host: The app host
  378. port: The app port
  379. loglevel: The log level.
  380. """
  381. from reflex.utils import processes
  382. try:
  383. from granian.constants import ( # pyright: ignore [reportMissingImports]
  384. Interfaces,
  385. )
  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. fnm_info = f"[FNM {prerequisites.get_fnm_version()} (Expected: {constants.Fnm.VERSION}) (PATH: {constants.Fnm.EXE})]"
  431. if system != "Windows" or (
  432. system == "Windows" and prerequisites.is_windows_bun_supported()
  433. ):
  434. dependencies.extend(
  435. [
  436. fnm_info,
  437. f"[Bun {prerequisites.get_bun_version()} (Expected: {constants.Bun.VERSION}) (PATH: {path_ops.get_bun_path()})]",
  438. ],
  439. )
  440. else:
  441. dependencies.append(fnm_info)
  442. if system == "Linux":
  443. import distro # pyright: ignore[reportMissingImports]
  444. os_version = distro.name(pretty=True)
  445. else:
  446. os_version = platform.version()
  447. dependencies.append(f"[OS {platform.system()} {os_version}]")
  448. for dep in dependencies:
  449. console.debug(f"{dep}")
  450. console.debug(
  451. f"Using package installer at: {prerequisites.get_install_package_manager(on_failure_return_none=True)}"
  452. )
  453. console.debug(
  454. f"Using package executer at: {prerequisites.get_package_manager(on_failure_return_none=True)}"
  455. )
  456. if system != "Windows":
  457. console.debug(f"Unzip path: {path_ops.which('unzip')}")
  458. def is_testing_env() -> bool:
  459. """Whether the app is running in a testing environment.
  460. Returns:
  461. True if the app is running in under pytest.
  462. """
  463. return constants.PYTEST_CURRENT_TEST in os.environ
  464. def is_in_app_harness() -> bool:
  465. """Whether the app is running in the app harness.
  466. Returns:
  467. True if the app is running in the app harness.
  468. """
  469. return constants.APP_HARNESS_FLAG in os.environ
  470. def is_prod_mode() -> bool:
  471. """Check if the app is running in production mode.
  472. Returns:
  473. True if the app is running in production mode or False if running in dev mode.
  474. """
  475. current_mode = environment.REFLEX_ENV_MODE.get()
  476. return current_mode == constants.Env.PROD