exec.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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(run_command: list[str], backend_present=True):
  56. """Run the process and launch the URL.
  57. Args:
  58. run_command: The command to run.
  59. backend_present: Whether the backend is present.
  60. """
  61. from reflex.utils import processes
  62. json_file_path = get_web_dir() / constants.PackageJson.PATH
  63. last_hash = detect_package_change(json_file_path)
  64. process = None
  65. first_run = True
  66. while True:
  67. if process is None:
  68. kwargs = {}
  69. if constants.IS_WINDOWS and backend_present:
  70. kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore
  71. process = processes.new_process(
  72. run_command,
  73. cwd=get_web_dir(),
  74. shell=constants.IS_WINDOWS,
  75. **kwargs,
  76. )
  77. global frontend_process
  78. frontend_process = process
  79. if process.stdout:
  80. for line in processes.stream_logs("Starting frontend", process):
  81. match = re.search(constants.Next.FRONTEND_LISTENING_REGEX, line)
  82. if match:
  83. if first_run:
  84. url = match.group(1)
  85. if get_config().frontend_path != "":
  86. url = urljoin(url, get_config().frontend_path)
  87. console.print(
  88. f"App running at: [bold green]{url}[/bold green]{' (Frontend-only mode)' if not backend_present else ''}"
  89. )
  90. if backend_present:
  91. notify_backend()
  92. first_run = False
  93. else:
  94. console.print(f"New packages detected: Updating app... {line}")
  95. else:
  96. if any(
  97. x in line for x in ("bin executable does not exist on disk",)
  98. ):
  99. console.error(
  100. "Try setting `REFLEX_USE_NPM=1` and re-running `reflex init` and `reflex run` to use npm instead of bun:\n"
  101. "`REFLEX_USE_NPM=1 reflex init`\n"
  102. "`REFLEX_USE_NPM=1 reflex run`"
  103. )
  104. new_hash = detect_package_change(json_file_path)
  105. if new_hash != last_hash:
  106. last_hash = new_hash
  107. console.print("Reloading app...")
  108. kill(process.pid)
  109. process = None
  110. break # for line in process.stdout
  111. else:
  112. console.print(f"No change: {line}")
  113. if process is not None:
  114. break # while True
  115. def run_frontend(root: Path, port: str, backend_present=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"], # type: ignore
  130. backend_present,
  131. )
  132. def run_frontend_prod(root: Path, port: str, backend_present=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"], # type: ignore
  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 run_uvicorn_backend(host, port, loglevel: LogLevel):
  197. """Run the backend in development mode using Uvicorn.
  198. Args:
  199. host: The app host
  200. port: The app port
  201. loglevel: The log level.
  202. """
  203. import uvicorn
  204. uvicorn.run(
  205. app=f"{get_app_module()}.{constants.CompileVars.API}",
  206. host=host,
  207. port=port,
  208. log_level=loglevel.value,
  209. reload=True,
  210. reload_dirs=[get_config().app_name],
  211. )
  212. def run_granian_backend(host, port, loglevel: LogLevel):
  213. """Run the backend in development mode using Granian.
  214. Args:
  215. host: The app host
  216. port: The app port
  217. loglevel: The log level.
  218. """
  219. console.debug("Using Granian for backend")
  220. try:
  221. from granian import Granian # type: ignore
  222. from granian.constants import Interfaces # type: ignore
  223. from granian.log import LogLevels # type: ignore
  224. Granian(
  225. target=get_granian_target(),
  226. address=host,
  227. port=port,
  228. interface=Interfaces.ASGI,
  229. log_level=LogLevels(loglevel.value),
  230. reload=True,
  231. reload_paths=[Path(get_config().app_name)],
  232. reload_ignore_dirs=[".web"],
  233. ).serve()
  234. except ImportError:
  235. console.error(
  236. 'InstallError: REFLEX_USE_GRANIAN is set but `granian` is not installed. (run `pip install "granian[reload]>=1.6.0"`)'
  237. )
  238. os._exit(1)
  239. def _get_backend_workers():
  240. from reflex.utils import processes
  241. config = get_config()
  242. return (
  243. processes.get_num_workers()
  244. if not config.gunicorn_workers
  245. else config.gunicorn_workers
  246. )
  247. def run_backend_prod(
  248. host: str,
  249. port: int,
  250. loglevel: constants.LogLevel = constants.LogLevel.ERROR,
  251. frontend_present: bool = False,
  252. ):
  253. """Run the backend.
  254. Args:
  255. host: The app host
  256. port: The app port
  257. loglevel: The log level.
  258. frontend_present: Whether the frontend is present.
  259. """
  260. if not frontend_present:
  261. notify_backend()
  262. if should_use_granian():
  263. run_granian_backend_prod(host, port, loglevel)
  264. else:
  265. run_uvicorn_backend_prod(host, port, loglevel)
  266. def run_uvicorn_backend_prod(host, port, loglevel):
  267. """Run the backend in production mode using Uvicorn.
  268. Args:
  269. host: The app host
  270. port: The app port
  271. loglevel: The log level.
  272. """
  273. from reflex.utils import processes
  274. config = get_config()
  275. app_module = get_app_module()
  276. 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()
  277. RUN_BACKEND_PROD_WINDOWS = f"uvicorn --limit-max-requests {config.gunicorn_max_requests} --timeout-keep-alive {config.timeout}".split()
  278. command = (
  279. [
  280. *RUN_BACKEND_PROD_WINDOWS,
  281. "--host",
  282. host,
  283. "--port",
  284. str(port),
  285. app_module,
  286. ]
  287. if constants.IS_WINDOWS
  288. else [
  289. *RUN_BACKEND_PROD,
  290. "--bind",
  291. f"{host}:{port}",
  292. "--threads",
  293. str(_get_backend_workers()),
  294. f"{app_module}()",
  295. ]
  296. )
  297. command += [
  298. "--log-level",
  299. loglevel.value,
  300. "--workers",
  301. str(_get_backend_workers()),
  302. ]
  303. processes.new_process(
  304. command,
  305. run=True,
  306. show_logs=True,
  307. env={
  308. environment.REFLEX_SKIP_COMPILE.name: "true"
  309. }, # skip compile for prod backend
  310. )
  311. def run_granian_backend_prod(host, port, loglevel):
  312. """Run the backend in production mode using Granian.
  313. Args:
  314. host: The app host
  315. port: The app port
  316. loglevel: The log level.
  317. """
  318. from reflex.utils import processes
  319. try:
  320. from granian.constants import Interfaces # type: ignore
  321. command = [
  322. "granian",
  323. "--workers",
  324. str(_get_backend_workers()),
  325. "--log-level",
  326. "critical",
  327. "--host",
  328. host,
  329. "--port",
  330. str(port),
  331. "--interface",
  332. str(Interfaces.ASGI),
  333. get_granian_target(),
  334. ]
  335. processes.new_process(
  336. command,
  337. run=True,
  338. show_logs=True,
  339. env={
  340. environment.REFLEX_SKIP_COMPILE.name: "true"
  341. }, # skip compile for prod backend
  342. )
  343. except ImportError:
  344. console.error(
  345. 'InstallError: REFLEX_USE_GRANIAN is set but `granian` is not installed. (run `pip install "granian[reload]>=1.6.0"`)'
  346. )
  347. def output_system_info():
  348. """Show system information if the loglevel is in DEBUG."""
  349. if console._LOG_LEVEL > constants.LogLevel.DEBUG:
  350. return
  351. from reflex.utils import prerequisites
  352. config = get_config()
  353. try:
  354. config_file = sys.modules[config.__module__].__file__
  355. except Exception:
  356. config_file = None
  357. console.rule("System Info")
  358. console.debug(f"Config file: {config_file!r}")
  359. console.debug(f"Config: {config}")
  360. dependencies = [
  361. f"[Reflex {constants.Reflex.VERSION} with Python {platform.python_version()} (PATH: {sys.executable})]",
  362. f"[Node {prerequisites.get_node_version()} (Expected: {constants.Node.VERSION}) (PATH:{path_ops.get_node_path()})]",
  363. ]
  364. system = platform.system()
  365. if system != "Windows" or (
  366. system == "Windows" and prerequisites.is_windows_bun_supported()
  367. ):
  368. dependencies.extend(
  369. [
  370. f"[FNM {prerequisites.get_fnm_version()} (Expected: {constants.Fnm.VERSION}) (PATH: {constants.Fnm.EXE})]",
  371. f"[Bun {prerequisites.get_bun_version()} (Expected: {constants.Bun.VERSION}) (PATH: {config.bun_path})]",
  372. ],
  373. )
  374. else:
  375. dependencies.append(
  376. f"[FNM {prerequisites.get_fnm_version()} (Expected: {constants.Fnm.VERSION}) (PATH: {constants.Fnm.EXE})]",
  377. )
  378. if system == "Linux":
  379. import distro # type: ignore
  380. os_version = distro.name(pretty=True)
  381. else:
  382. os_version = platform.version()
  383. dependencies.append(f"[OS {platform.system()} {os_version}]")
  384. for dep in dependencies:
  385. console.debug(f"{dep}")
  386. console.debug(
  387. f"Using package installer at: {prerequisites.get_install_package_manager(on_failure_return_none=True)}" # type: ignore
  388. )
  389. console.debug(
  390. f"Using package executer at: {prerequisites.get_package_manager(on_failure_return_none=True)}"
  391. ) # type: ignore
  392. if system != "Windows":
  393. console.debug(f"Unzip path: {path_ops.which('unzip')}")
  394. def is_testing_env() -> bool:
  395. """Whether the app is running in a testing environment.
  396. Returns:
  397. True if the app is running in under pytest.
  398. """
  399. return constants.PYTEST_CURRENT_TEST in os.environ
  400. def is_prod_mode() -> bool:
  401. """Check if the app is running in production mode.
  402. Returns:
  403. True if the app is running in production mode or False if running in dev mode.
  404. """
  405. current_mode = environment.REFLEX_ENV_MODE.get()
  406. return current_mode == constants.Env.PROD
  407. def is_frontend_only() -> bool:
  408. """Check if the app is running in frontend-only mode.
  409. Returns:
  410. True if the app is running in frontend-only mode.
  411. """
  412. console.deprecate(
  413. "is_frontend_only() is deprecated and will be removed in a future release.",
  414. reason="Use `environment.REFLEX_FRONTEND_ONLY.get()` instead.",
  415. deprecation_version="0.6.5",
  416. removal_version="0.7.0",
  417. )
  418. return environment.REFLEX_FRONTEND_ONLY.get()
  419. def is_backend_only() -> bool:
  420. """Check if the app is running in backend-only mode.
  421. Returns:
  422. True if the app is running in backend-only mode.
  423. """
  424. console.deprecate(
  425. "is_backend_only() is deprecated and will be removed in a future release.",
  426. reason="Use `environment.REFLEX_BACKEND_ONLY.get()` instead.",
  427. deprecation_version="0.6.5",
  428. removal_version="0.7.0",
  429. )
  430. return environment.REFLEX_BACKEND_ONLY.get()
  431. def should_skip_compile() -> bool:
  432. """Whether the app should skip compile.
  433. Returns:
  434. True if the app should skip compile.
  435. """
  436. console.deprecate(
  437. "should_skip_compile() is deprecated and will be removed in a future release.",
  438. reason="Use `environment.REFLEX_SKIP_COMPILE.get()` instead.",
  439. deprecation_version="0.6.5",
  440. removal_version="0.7.0",
  441. )
  442. return environment.REFLEX_SKIP_COMPILE.get()