exec.py 16 KB

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