exec.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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. console.print(
  65. f"DETECT_PACKAGE_CHANGE init {last_hash}, {json.dumps(json.loads(json_file_path.read_text()))}"
  66. )
  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 # type: ignore
  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(f"New packages detected: Updating app... {line}")
  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. console.print("Reloading app due to new content...")
  110. new_content = json.dumps(json.loads(json_file_path.read_text()))
  111. console.print(
  112. f"DETECT_PACKAGE_CHANGE hit {last_hash} != {new_hash} (new), {new_content}"
  113. )
  114. last_hash = new_hash
  115. kill(process.pid)
  116. process = None
  117. break # for line in process.stdout
  118. if process is not None:
  119. break # while True
  120. def run_frontend(root: Path, port: str, backend_present=True):
  121. """Run the frontend.
  122. Args:
  123. root: The root path of the project.
  124. port: The port to run the frontend on.
  125. backend_present: Whether the backend is present.
  126. """
  127. from reflex.utils import prerequisites
  128. # validate dependencies before run
  129. prerequisites.validate_frontend_dependencies(init=False)
  130. # Run the frontend in development mode.
  131. console.rule("[bold green]App Running")
  132. os.environ["PORT"] = str(get_config().frontend_port if port is None else port)
  133. run_process_and_launch_url(
  134. [prerequisites.get_package_manager(), "run", "dev"], # type: ignore
  135. backend_present,
  136. )
  137. def run_frontend_prod(root: Path, port: str, backend_present=True):
  138. """Run the frontend.
  139. Args:
  140. root: The root path of the project (to keep same API as run_frontend).
  141. port: The port to run the frontend on.
  142. backend_present: Whether the backend is present.
  143. """
  144. from reflex.utils import prerequisites
  145. # Set the port.
  146. os.environ["PORT"] = str(get_config().frontend_port if port is None else port)
  147. # validate dependencies before run
  148. prerequisites.validate_frontend_dependencies(init=False)
  149. # Run the frontend in production mode.
  150. console.rule("[bold green]App Running")
  151. run_process_and_launch_url(
  152. [prerequisites.get_package_manager(), "run", "prod"], # type: ignore
  153. backend_present,
  154. )
  155. def should_use_granian():
  156. """Whether to use Granian for backend.
  157. Returns:
  158. True if Granian should be used.
  159. """
  160. return environment.REFLEX_USE_GRANIAN.get()
  161. def get_app_module():
  162. """Get the app module for the backend.
  163. Returns:
  164. The app module for the backend.
  165. """
  166. return f"reflex.app_module_for_backend:{constants.CompileVars.APP}"
  167. def get_granian_target():
  168. """Get the Granian target for the backend.
  169. Returns:
  170. The Granian target for the backend.
  171. """
  172. import reflex
  173. app_module_path = Path(reflex.__file__).parent / "app_module_for_backend.py"
  174. return (
  175. f"{app_module_path!s}:{constants.CompileVars.APP}.{constants.CompileVars.API}"
  176. )
  177. def run_backend(
  178. host: str,
  179. port: int,
  180. loglevel: constants.LogLevel = constants.LogLevel.ERROR,
  181. frontend_present: bool = False,
  182. ):
  183. """Run the backend.
  184. Args:
  185. host: The app host
  186. port: The app port
  187. loglevel: The log level.
  188. frontend_present: Whether the frontend is present.
  189. """
  190. web_dir = get_web_dir()
  191. # Create a .nocompile file to skip compile for backend.
  192. if web_dir.exists():
  193. (web_dir / constants.NOCOMPILE_FILE).touch()
  194. if not frontend_present:
  195. notify_backend()
  196. # Run the backend in development mode.
  197. if should_use_granian():
  198. run_granian_backend(host, port, loglevel)
  199. else:
  200. run_uvicorn_backend(host, port, loglevel)
  201. def run_uvicorn_backend(host, port, loglevel: LogLevel):
  202. """Run the backend in development mode using Uvicorn.
  203. Args:
  204. host: The app host
  205. port: The app port
  206. loglevel: The log level.
  207. """
  208. import uvicorn
  209. uvicorn.run(
  210. app=f"{get_app_module()}.{constants.CompileVars.API}",
  211. host=host,
  212. port=port,
  213. log_level=loglevel.value,
  214. reload=True,
  215. reload_dirs=[get_config().app_name],
  216. )
  217. def run_granian_backend(host, port, loglevel: LogLevel):
  218. """Run the backend in development mode using Granian.
  219. Args:
  220. host: The app host
  221. port: The app port
  222. loglevel: The log level.
  223. """
  224. console.debug("Using Granian for backend")
  225. try:
  226. from granian import Granian # type: ignore
  227. from granian.constants import Interfaces # type: ignore
  228. from granian.log import LogLevels # type: ignore
  229. Granian(
  230. target=get_granian_target(),
  231. address=host,
  232. port=port,
  233. interface=Interfaces.ASGI,
  234. log_level=LogLevels(loglevel.value),
  235. reload=True,
  236. reload_paths=[Path(get_config().app_name)],
  237. reload_ignore_dirs=[".web"],
  238. ).serve()
  239. except ImportError:
  240. console.error(
  241. 'InstallError: REFLEX_USE_GRANIAN is set but `granian` is not installed. (run `pip install "granian[reload]>=1.6.0"`)'
  242. )
  243. os._exit(1)
  244. def _get_backend_workers():
  245. from reflex.utils import processes
  246. config = get_config()
  247. return (
  248. processes.get_num_workers()
  249. if not config.gunicorn_workers
  250. else config.gunicorn_workers
  251. )
  252. def run_backend_prod(
  253. host: str,
  254. port: int,
  255. loglevel: constants.LogLevel = constants.LogLevel.ERROR,
  256. frontend_present: bool = False,
  257. ):
  258. """Run the backend.
  259. Args:
  260. host: The app host
  261. port: The app port
  262. loglevel: The log level.
  263. frontend_present: Whether the frontend is present.
  264. """
  265. if not frontend_present:
  266. notify_backend()
  267. if should_use_granian():
  268. run_granian_backend_prod(host, port, loglevel)
  269. else:
  270. run_uvicorn_backend_prod(host, port, loglevel)
  271. def run_uvicorn_backend_prod(host, port, loglevel):
  272. """Run the backend in production mode using Uvicorn.
  273. Args:
  274. host: The app host
  275. port: The app port
  276. loglevel: The log level.
  277. """
  278. from reflex.utils import processes
  279. config = get_config()
  280. app_module = get_app_module()
  281. 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()
  282. RUN_BACKEND_PROD_WINDOWS = f"uvicorn --limit-max-requests {config.gunicorn_max_requests} --timeout-keep-alive {config.timeout}".split()
  283. command = (
  284. [
  285. *RUN_BACKEND_PROD_WINDOWS,
  286. "--host",
  287. host,
  288. "--port",
  289. str(port),
  290. app_module,
  291. ]
  292. if constants.IS_WINDOWS
  293. else [
  294. *RUN_BACKEND_PROD,
  295. "--bind",
  296. f"{host}:{port}",
  297. "--threads",
  298. str(_get_backend_workers()),
  299. f"{app_module}()",
  300. ]
  301. )
  302. command += [
  303. "--log-level",
  304. loglevel.value,
  305. "--workers",
  306. str(_get_backend_workers()),
  307. ]
  308. processes.new_process(
  309. command,
  310. run=True,
  311. show_logs=True,
  312. env={
  313. environment.REFLEX_SKIP_COMPILE.name: "true"
  314. }, # skip compile for prod backend
  315. )
  316. def run_granian_backend_prod(host, port, loglevel):
  317. """Run the backend in production mode using Granian.
  318. Args:
  319. host: The app host
  320. port: The app port
  321. loglevel: The log level.
  322. """
  323. from reflex.utils import processes
  324. try:
  325. from granian.constants import Interfaces # type: ignore
  326. command = [
  327. "granian",
  328. "--workers",
  329. str(_get_backend_workers()),
  330. "--log-level",
  331. "critical",
  332. "--host",
  333. host,
  334. "--port",
  335. str(port),
  336. "--interface",
  337. str(Interfaces.ASGI),
  338. get_granian_target(),
  339. ]
  340. processes.new_process(
  341. command,
  342. run=True,
  343. show_logs=True,
  344. env={
  345. environment.REFLEX_SKIP_COMPILE.name: "true"
  346. }, # skip compile for prod backend
  347. )
  348. except ImportError:
  349. console.error(
  350. 'InstallError: REFLEX_USE_GRANIAN is set but `granian` is not installed. (run `pip install "granian[reload]>=1.6.0"`)'
  351. )
  352. def output_system_info():
  353. """Show system information if the loglevel is in DEBUG."""
  354. if console._LOG_LEVEL > constants.LogLevel.DEBUG:
  355. return
  356. from reflex.utils import prerequisites
  357. config = get_config()
  358. try:
  359. config_file = sys.modules[config.__module__].__file__
  360. except Exception:
  361. config_file = None
  362. console.rule("System Info")
  363. console.debug(f"Config file: {config_file!r}")
  364. console.debug(f"Config: {config}")
  365. dependencies = [
  366. f"[Reflex {constants.Reflex.VERSION} with Python {platform.python_version()} (PATH: {sys.executable})]",
  367. f"[Node {prerequisites.get_node_version()} (Expected: {constants.Node.VERSION}) (PATH:{path_ops.get_node_path()})]",
  368. ]
  369. system = platform.system()
  370. if system != "Windows" or (
  371. system == "Windows" and prerequisites.is_windows_bun_supported()
  372. ):
  373. dependencies.extend(
  374. [
  375. f"[FNM {prerequisites.get_fnm_version()} (Expected: {constants.Fnm.VERSION}) (PATH: {constants.Fnm.EXE})]",
  376. f"[Bun {prerequisites.get_bun_version()} (Expected: {constants.Bun.VERSION}) (PATH: {config.bun_path})]",
  377. ],
  378. )
  379. else:
  380. dependencies.append(
  381. f"[FNM {prerequisites.get_fnm_version()} (Expected: {constants.Fnm.VERSION}) (PATH: {constants.Fnm.EXE})]",
  382. )
  383. if system == "Linux":
  384. import distro # type: ignore
  385. os_version = distro.name(pretty=True)
  386. else:
  387. os_version = platform.version()
  388. dependencies.append(f"[OS {platform.system()} {os_version}]")
  389. for dep in dependencies:
  390. console.debug(f"{dep}")
  391. console.debug(
  392. f"Using package installer at: {prerequisites.get_install_package_manager(on_failure_return_none=True)}" # type: ignore
  393. )
  394. console.debug(
  395. f"Using package executer at: {prerequisites.get_package_manager(on_failure_return_none=True)}"
  396. ) # type: ignore
  397. if system != "Windows":
  398. console.debug(f"Unzip path: {path_ops.which('unzip')}")
  399. def is_testing_env() -> bool:
  400. """Whether the app is running in a testing environment.
  401. Returns:
  402. True if the app is running in under pytest.
  403. """
  404. return constants.PYTEST_CURRENT_TEST in os.environ
  405. def is_prod_mode() -> bool:
  406. """Check if the app is running in production mode.
  407. Returns:
  408. True if the app is running in production mode or False if running in dev mode.
  409. """
  410. current_mode = environment.REFLEX_ENV_MODE.get()
  411. return current_mode == constants.Env.PROD
  412. def is_frontend_only() -> bool:
  413. """Check if the app is running in frontend-only mode.
  414. Returns:
  415. True if the app is running in frontend-only mode.
  416. """
  417. console.deprecate(
  418. "is_frontend_only() is deprecated and will be removed in a future release.",
  419. reason="Use `environment.REFLEX_FRONTEND_ONLY.get()` instead.",
  420. deprecation_version="0.6.5",
  421. removal_version="0.7.0",
  422. )
  423. return environment.REFLEX_FRONTEND_ONLY.get()
  424. def is_backend_only() -> bool:
  425. """Check if the app is running in backend-only mode.
  426. Returns:
  427. True if the app is running in backend-only mode.
  428. """
  429. console.deprecate(
  430. "is_backend_only() is deprecated and will be removed in a future release.",
  431. reason="Use `environment.REFLEX_BACKEND_ONLY.get()` instead.",
  432. deprecation_version="0.6.5",
  433. removal_version="0.7.0",
  434. )
  435. return environment.REFLEX_BACKEND_ONLY.get()
  436. def should_skip_compile() -> bool:
  437. """Whether the app should skip compile.
  438. Returns:
  439. True if the app should skip compile.
  440. """
  441. console.deprecate(
  442. "should_skip_compile() is deprecated and will be removed in a future release.",
  443. reason="Use `environment.REFLEX_SKIP_COMPILE.get()` instead.",
  444. deprecation_version="0.6.5",
  445. removal_version="0.7.0",
  446. )
  447. return environment.REFLEX_SKIP_COMPILE.get()