|
| 1 | +"""Node.js runtime management for floatCSEP Next.js dashboard.""" |
| 2 | + |
| 3 | +import logging |
| 4 | +import os |
| 5 | +import platform |
| 6 | +import re |
| 7 | +import shutil |
| 8 | +import stat |
| 9 | +import subprocess |
| 10 | +import tarfile |
| 11 | +import zipfile |
| 12 | +from dataclasses import dataclass |
| 13 | +from pathlib import Path |
| 14 | +from typing import List, Optional |
| 15 | +from urllib import request |
| 16 | + |
| 17 | +logger = logging.getLogger(__name__) |
| 18 | + |
| 19 | +MIN_NODE_VERSION = (18, 17, 0) |
| 20 | +BUNDLED_NODE_VERSION = "20.11.1" |
| 21 | + |
| 22 | + |
| 23 | +@dataclass |
| 24 | +class NodeRuntime: |
| 25 | + """Represents a runnable Node.js installation.""" |
| 26 | + |
| 27 | + node_path: Path |
| 28 | + npm_path: Path |
| 29 | + bin_dir: Path |
| 30 | + source: str |
| 31 | + |
| 32 | + def apply_to_env(self, env: dict) -> dict: |
| 33 | + """Return a copy of the environment with this runtime prepended to PATH.""" |
| 34 | + |
| 35 | + current_path = env.get("PATH", "") |
| 36 | + updated = env.copy() |
| 37 | + updated["PATH"] = ( |
| 38 | + f"{self.bin_dir}{os.pathsep}{current_path}" |
| 39 | + if current_path |
| 40 | + else str(self.bin_dir) |
| 41 | + ) |
| 42 | + return updated |
| 43 | + |
| 44 | + |
| 45 | +def parse_node_version(raw: str) -> Optional[tuple[int, int, int]]: |
| 46 | + match = re.match(r"v?(\d+)\.(\d+)\.(\d+)", raw.strip()) |
| 47 | + if not match: |
| 48 | + return None |
| 49 | + return tuple(int(part) for part in match.groups()) |
| 50 | + |
| 51 | + |
| 52 | +def get_system_node_runtime() -> Optional[NodeRuntime]: |
| 53 | + node_cmd = shutil.which("node") |
| 54 | + npm_cmd = shutil.which("npm") |
| 55 | + if not node_cmd or not npm_cmd: |
| 56 | + return None |
| 57 | + try: |
| 58 | + result = subprocess.run( |
| 59 | + [node_cmd, "--version"], capture_output=True, text=True, check=True |
| 60 | + ) |
| 61 | + except (subprocess.CalledProcessError, FileNotFoundError): |
| 62 | + return None |
| 63 | + version = parse_node_version(result.stdout) |
| 64 | + if not version or version < MIN_NODE_VERSION: |
| 65 | + return None |
| 66 | + return NodeRuntime( |
| 67 | + node_path=Path(node_cmd), |
| 68 | + npm_path=Path(npm_cmd), |
| 69 | + bin_dir=Path(node_cmd).parent, |
| 70 | + source="system", |
| 71 | + ) |
| 72 | + |
| 73 | + |
| 74 | +def _node_dist_name() -> tuple[str, str]: |
| 75 | + system = platform.system().lower() |
| 76 | + machine = platform.machine().lower() |
| 77 | + if system == "linux": |
| 78 | + if machine in ("x86_64", "amd64"): |
| 79 | + return "linux-x64", ".tar.xz" |
| 80 | + if machine in ("aarch64", "arm64"): |
| 81 | + return "linux-arm64", ".tar.xz" |
| 82 | + elif system == "darwin": |
| 83 | + if machine == "arm64": |
| 84 | + return "darwin-arm64", ".tar.xz" |
| 85 | + if machine in ("x86_64", "amd64"): |
| 86 | + return "darwin-x64", ".tar.xz" |
| 87 | + elif system == "windows": |
| 88 | + if machine in ("x86_64", "amd64"): |
| 89 | + return "win-x64", ".zip" |
| 90 | + raise RuntimeError( |
| 91 | + f"Unsupported platform '{platform.system()} {platform.machine()}'. " |
| 92 | + "Please install Node.js 20+ manually." |
| 93 | + ) |
| 94 | + |
| 95 | + |
| 96 | +def _download_node_archive(target: Path, url: str) -> None: |
| 97 | + logger.info("Downloading Node.js runtime from %s", url) |
| 98 | + target.parent.mkdir(parents=True, exist_ok=True) |
| 99 | + with request.urlopen(url) as response, open(target, "wb") as handle: |
| 100 | + shutil.copyfileobj(response, handle) |
| 101 | + |
| 102 | + |
| 103 | +def _extract_node_archive(archive: Path, destination: Path) -> Path: |
| 104 | + logger.info("Extracting Node.js runtime to %s", destination) |
| 105 | + destination.mkdir(parents=True, exist_ok=True) |
| 106 | + if archive.suffix == ".zip": |
| 107 | + with zipfile.ZipFile(archive) as zf: |
| 108 | + zf.extractall(destination) |
| 109 | + else: |
| 110 | + # Handles .tar.xz |
| 111 | + with tarfile.open(archive, mode="r:*") as tf: |
| 112 | + tf.extractall(destination) |
| 113 | + # Find the extracted directory (node-vXX-<platform>) |
| 114 | + for child in destination.iterdir(): |
| 115 | + if child.is_dir() and child.name.startswith(f"node-v{BUNDLED_NODE_VERSION}"): |
| 116 | + return child |
| 117 | + raise RuntimeError("Failed to locate extracted Node.js runtime") |
| 118 | + |
| 119 | + |
| 120 | +def ensure_bundled_node(nextjs_dir: Path) -> NodeRuntime: |
| 121 | + platform_tag, archive_ext = _node_dist_name() |
| 122 | + cache_dir = nextjs_dir / ".cache" / "node-runtime" |
| 123 | + extract_root = cache_dir / f"node-v{BUNDLED_NODE_VERSION}-{platform_tag}" |
| 124 | + if extract_root.exists(): |
| 125 | + logger.info("Using cached Node.js runtime at %s", extract_root) |
| 126 | + else: |
| 127 | + archive_name = f"node-v{BUNDLED_NODE_VERSION}-{platform_tag}{archive_ext}" |
| 128 | + download_url = ( |
| 129 | + f"https://nodejs.org/dist/v{BUNDLED_NODE_VERSION}/{archive_name}" |
| 130 | + ) |
| 131 | + archive_path = cache_dir / archive_name |
| 132 | + _download_node_archive(archive_path, download_url) |
| 133 | + extracted = _extract_node_archive(archive_path, cache_dir) |
| 134 | + extracted.rename(extract_root) |
| 135 | + archive_path.unlink(missing_ok=True) |
| 136 | + |
| 137 | + if platform.system().lower() == "windows": |
| 138 | + node_path = extract_root / "node.exe" |
| 139 | + npm_path = extract_root / "npm.cmd" |
| 140 | + bin_dir = extract_root |
| 141 | + else: |
| 142 | + bin_dir = extract_root / "bin" |
| 143 | + node_path = bin_dir / "node" |
| 144 | + npm_path = bin_dir / "npm" |
| 145 | + for path in (node_path, npm_path): |
| 146 | + if not path.exists(): |
| 147 | + raise RuntimeError(f"Bundled Node.js binary missing: {path}") |
| 148 | + mode = path.stat().st_mode |
| 149 | + path.chmod(mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) |
| 150 | + return NodeRuntime( |
| 151 | + node_path=node_path, npm_path=npm_path, bin_dir=bin_dir, source="bundled" |
| 152 | + ) |
| 153 | + |
| 154 | + |
| 155 | +def ensure_node_runtime(nextjs_dir: Path) -> NodeRuntime: |
| 156 | + runtime = get_system_node_runtime() |
| 157 | + if runtime: |
| 158 | + logger.info("Detected Node.js %s from system PATH", runtime.node_path) |
| 159 | + return runtime |
| 160 | + logger.warning( |
| 161 | + "Node.js %s or newer not found. Downloading a scoped runtime (v%s).", |
| 162 | + ".".join(str(part) for part in MIN_NODE_VERSION), |
| 163 | + BUNDLED_NODE_VERSION, |
| 164 | + ) |
| 165 | + return ensure_bundled_node(nextjs_dir) |
| 166 | + |
| 167 | + |
| 168 | +def ensure_nextjs_dependencies( |
| 169 | + nextjs_dir: Path, npm_cmd: List[str], env: dict |
| 170 | +) -> None: |
| 171 | + """Install Node dependencies if needed.""" |
| 172 | + node_modules = nextjs_dir / "node_modules" |
| 173 | + if node_modules.exists(): |
| 174 | + return |
| 175 | + logger.info("Installing Next.js dependencies (this may take a few minutes)...") |
| 176 | + try: |
| 177 | + subprocess.run( |
| 178 | + npm_cmd + ["install"], |
| 179 | + cwd=nextjs_dir, |
| 180 | + check=True, |
| 181 | + env=env, |
| 182 | + ) |
| 183 | + except subprocess.CalledProcessError as exc: |
| 184 | + logger.error("Failed to install dependencies: %s", exc) |
| 185 | + raise RuntimeError( |
| 186 | + "Could not install Next.js dependencies automatically. " |
| 187 | + "Please ensure network access is available or install them manually." |
| 188 | + ) |
0 commit comments