versioned-prefix.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. import { randomUUID } from 'node:crypto';
  2. import {
  3. chmodSync,
  4. existsSync,
  5. mkdirSync,
  6. readdirSync,
  7. readFileSync,
  8. renameSync,
  9. rmSync,
  10. writeFileSync,
  11. } from 'node:fs';
  12. import path from 'node:path';
  13. import type { McodeNpmPackageName } from './install-source.js';
  14. import {
  15. readMcodePrefixPackageMetadata,
  16. type McodePrefixPackageMetadata,
  17. } from './prefix-update.js';
  18. const RELEASES_DIRECTORY = 'releases';
  19. const CURRENT_FILE = 'current';
  20. const UPDATE_LOCK_DIRECTORY = '.mcode-update.lock';
  21. const LAYOUT_VERSION = 2;
  22. type McodePlatformPath = typeof path.posix | typeof path.win32;
  23. export interface McodeVersionedPrefixActivation {
  24. readonly stagingPrefix: string;
  25. readonly activePrefix: string;
  26. readonly packageName: McodeNpmPackageName;
  27. readonly expectedVersion: string;
  28. readonly runtimeExecutable: string;
  29. readonly npmExecutable: string;
  30. readonly registry: string;
  31. }
  32. export function createMcodeVersionedPrefixStagingPrefix(
  33. activePrefix: string,
  34. version: string,
  35. platform: NodeJS.Platform = process.platform,
  36. ): string {
  37. const platformPath = platformPathFor(platform);
  38. return platformPath.join(
  39. activePrefix,
  40. RELEASES_DIRECTORY,
  41. `.staging-${version}-${process.pid}-${randomUUID()}`,
  42. );
  43. }
  44. export function prepareMcodeVersionedPrefixStaging(stagingPrefix: string): void {
  45. mkdirSync(stagingPrefix, { recursive: true, mode: 0o700 });
  46. }
  47. export function acquireMcodeVersionedPrefixUpdateLock(activePrefix: string): () => void {
  48. const lockDirectory = path.join(activePrefix, UPDATE_LOCK_DIRECTORY);
  49. mkdirSync(lockDirectory, { recursive: true, mode: 0o700 });
  50. const claimName = `${String(process.pid)}-${randomUUID()}.claim`;
  51. const claimFile = path.join(lockDirectory, claimName);
  52. writeFileSync(claimFile, 'choosing\n', { flag: 'wx', mode: 0o600 });
  53. try {
  54. const ticket =
  55. Math.max(0, ...readLiveUpdateClaims(lockDirectory).map((claim) => claim.ticket ?? 0)) + 1;
  56. writeAtomicText(claimFile, `${String(ticket)}\n`, 0o600);
  57. const blocked = readLiveUpdateClaims(lockDirectory).some(
  58. (claim) =>
  59. claim.name !== claimName &&
  60. (claim.ticket === undefined ||
  61. claim.ticket < ticket ||
  62. (claim.ticket === ticket &&
  63. (claim.pid < process.pid ||
  64. (claim.pid === process.pid && claim.name.localeCompare(claimName) < 0)))),
  65. );
  66. if (blocked) throw new Error('Another MCode update is already running.');
  67. } catch (error) {
  68. rmSync(claimFile, { force: true });
  69. throw error;
  70. }
  71. let released = false;
  72. return () => {
  73. if (released) return;
  74. released = true;
  75. rmSync(claimFile, { force: true });
  76. };
  77. }
  78. export function activateMcodeVersionedPrefixInstall(
  79. activation: McodeVersionedPrefixActivation,
  80. platform: NodeJS.Platform = process.platform,
  81. ): string {
  82. const platformPath = platformPathFor(platform);
  83. const releasesRoot = platformPath.join(activation.activePrefix, RELEASES_DIRECTORY);
  84. const stagingMetadata = readExpectedMetadata(activation.stagingPrefix, activation, platform);
  85. // A release is complete before it becomes visible under releases/<release-key>.
  86. // Launchers use paths relative to the release root so the staged directory can be renamed.
  87. writeVersionedReleaseLaunchers(
  88. activation.stagingPrefix,
  89. stagingMetadata,
  90. activation.runtimeExecutable,
  91. platform,
  92. );
  93. assertVersionedRelease(activation.stagingPrefix, activation, platform);
  94. mkdirSync(releasesRoot, { recursive: true, mode: 0o700 });
  95. let releaseKey = activation.expectedVersion;
  96. let releasePrefix = platformPath.join(releasesRoot, releaseKey);
  97. if (existsSync(releasePrefix)) {
  98. // Never select bytes that did not pass this update attempt's full staging validation.
  99. releaseKey = `${activation.expectedVersion}-repair-${randomUUID()}`;
  100. releasePrefix = platformPath.join(releasesRoot, releaseKey);
  101. }
  102. renameSync(activation.stagingPrefix, releasePrefix);
  103. assertVersionedRelease(releasePrefix, activation, platform);
  104. writeVersionedInstallReceipt(activation, platform);
  105. if (!versionedRootLaunchersAreValid(activation.activePrefix, platform)) {
  106. writeVersionedRootLaunchers(activation.activePrefix, platform);
  107. }
  108. // The pointer is the commit point and is written only after the selected release and root
  109. // launchers are complete.
  110. writeAtomicText(
  111. platformPath.join(activation.activePrefix, CURRENT_FILE),
  112. `${releaseKey}\n`,
  113. 0o600,
  114. );
  115. return releasePrefix;
  116. }
  117. function readExpectedMetadata(
  118. prefix: string,
  119. activation: McodeVersionedPrefixActivation,
  120. platform: NodeJS.Platform,
  121. ): McodePrefixPackageMetadata {
  122. const metadata = readMcodePrefixPackageMetadata(prefix, activation.packageName, platform);
  123. if (metadata.version !== activation.expectedVersion) {
  124. throw new Error(
  125. `MCode release contains ${metadata.version}; expected ${activation.expectedVersion}.`,
  126. );
  127. }
  128. return metadata;
  129. }
  130. function assertVersionedRelease(
  131. releasePrefix: string,
  132. activation: McodeVersionedPrefixActivation,
  133. platform: NodeJS.Platform,
  134. ): void {
  135. const metadata = readExpectedMetadata(releasePrefix, activation, platform);
  136. const expected = versionedReleaseLauncherContents(
  137. releasePrefix,
  138. metadata,
  139. activation.runtimeExecutable,
  140. platform,
  141. );
  142. for (const [file, contents] of expected) {
  143. if (readFileSync(file, 'utf8') !== contents) {
  144. throw new Error(`MCode release launcher is invalid: ${file}`);
  145. }
  146. }
  147. }
  148. function writeVersionedReleaseLaunchers(
  149. releasePrefix: string,
  150. metadata: McodePrefixPackageMetadata,
  151. runtimeExecutable: string,
  152. platform: NodeJS.Platform,
  153. ): void {
  154. for (const [file, contents] of versionedReleaseLauncherContents(
  155. releasePrefix,
  156. metadata,
  157. runtimeExecutable,
  158. platform,
  159. )) {
  160. writeAtomicText(file, contents, 0o700);
  161. }
  162. }
  163. function versionedReleaseLauncherContents(
  164. releasePrefix: string,
  165. metadata: McodePrefixPackageMetadata,
  166. runtimeExecutable: string,
  167. platform: NodeJS.Platform,
  168. ): ReadonlyMap<string, string> {
  169. const platformPath = platformPathFor(platform);
  170. const launchers = new Map<string, string>();
  171. if (!existsSync(runtimeExecutable)) {
  172. throw new Error('MCode versioned launcher runtime is missing.');
  173. }
  174. for (const command of versionedCommands(metadata)) {
  175. if (!command.binEntry) {
  176. throw new Error(`MCode versioned ${command.name} package entry is missing.`);
  177. }
  178. const entryFile = platformPath.join(metadata.packageRoot, ...command.binEntry.split('/'));
  179. const relativeEntry = platformPath.relative(releasePrefix, entryFile);
  180. if (
  181. !relativeEntry ||
  182. relativeEntry.startsWith('..') ||
  183. platformPath.isAbsolute(relativeEntry) ||
  184. !existsSync(entryFile)
  185. ) {
  186. throw new Error(`MCode versioned ${command.name} launcher path is invalid.`);
  187. }
  188. if (platform === 'win32') {
  189. launchers.set(
  190. platformPath.join(releasePrefix, `${command.releaseLauncher}.cmd`),
  191. `@ECHO off\r\n"${escapeBatch(runtimeExecutable)}" "%~dp0${escapeBatch(relativeEntry)}" %*\r\nEXIT /B %ERRORLEVEL%\r\n`,
  192. );
  193. launchers.set(
  194. platformPath.join(releasePrefix, `${command.releaseLauncher}.ps1`),
  195. `#!/usr/bin/env pwsh\r\n& '${escapePowerShell(runtimeExecutable)}' (Join-Path $PSScriptRoot '${escapePowerShell(relativeEntry)}') @args\r\nexit $LASTEXITCODE\r\n`,
  196. );
  197. continue;
  198. }
  199. launchers.set(
  200. platformPath.join(releasePrefix, command.releaseLauncher),
  201. `#!/bin/sh\nset -eu\nroot=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)\nexec ${quoteShell(runtimeExecutable)} "$root/${escapeDoubleQuoted(relativeEntry)}" "$@"\n`,
  202. );
  203. }
  204. return launchers;
  205. }
  206. function writeVersionedRootLaunchers(activePrefix: string, platform: NodeJS.Platform): void {
  207. for (const [file, contents] of versionedRootLauncherContents(activePrefix, platform)) {
  208. writeAtomicText(file, contents, 0o700);
  209. }
  210. }
  211. function versionedRootLaunchersAreValid(activePrefix: string, platform: NodeJS.Platform): boolean {
  212. try {
  213. for (const [file, contents] of versionedRootLauncherContents(activePrefix, platform)) {
  214. if (readFileSync(file, 'utf8') !== contents) return false;
  215. }
  216. return true;
  217. } catch {
  218. return false;
  219. }
  220. }
  221. function versionedRootLauncherContents(
  222. activePrefix: string,
  223. platform: NodeJS.Platform,
  224. ): ReadonlyMap<string, string> {
  225. const platformPath = platformPathFor(platform);
  226. const launchers = new Map<string, string>();
  227. if (platform === 'win32') {
  228. for (const command of versionedCommands()) {
  229. launchers.set(
  230. platformPath.join(activePrefix, `${command.name}.cmd`),
  231. `@ECHO off\r\nSETLOCAL\r\nSET /P MCODE_RELEASE=<"%~dp0current"\r\nECHO(%MCODE_RELEASE%| %SystemRoot%\\System32\\findstr.exe /R /X "[0-9A-Za-z][0-9A-Za-z._-]*" >NUL || EXIT /B 1\r\nCALL "%~dp0releases\\%MCODE_RELEASE%\\${command.releaseLauncher}.cmd" %*\r\nEXIT /B %ERRORLEVEL%\r\n`,
  232. );
  233. launchers.set(
  234. platformPath.join(activePrefix, `${command.name}.ps1`),
  235. `#!/usr/bin/env pwsh\r\n$release = (Get-Content -LiteralPath (Join-Path $PSScriptRoot 'current') -Raw).Trim()\r\nif ($release -notmatch '^[0-9A-Za-z][0-9A-Za-z._-]*$') { throw 'Invalid MCode current release pointer.' }\r\n& (Join-Path $PSScriptRoot "releases\\$release\\${command.releaseLauncher}.ps1") @args\r\nexit $LASTEXITCODE\r\n`,
  236. );
  237. }
  238. return launchers;
  239. }
  240. for (const command of versionedCommands()) {
  241. launchers.set(
  242. platformPath.join(activePrefix, 'bin', command.name),
  243. `#!/bin/sh\nset -eu\nroot=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd -P)\nrelease=$(tr -d "\\r\\n" < "$root/current")\ncase "$release" in ""|*[!0-9A-Za-z._-]*) echo "Invalid MCode current release pointer." >&2; exit 1;; esac\nexec "$root/releases/$release/${command.releaseLauncher}" "$@"\n`,
  244. );
  245. }
  246. return launchers;
  247. }
  248. interface McodeVersionedCommand {
  249. readonly name: 'mcode' | 'mcode-tools';
  250. readonly releaseLauncher: '.mcode-launcher' | '.mcode-tools-launcher';
  251. readonly binEntry?: string;
  252. }
  253. function versionedCommands(
  254. metadata?: McodePrefixPackageMetadata,
  255. ): readonly McodeVersionedCommand[] {
  256. return [
  257. {
  258. name: 'mcode',
  259. releaseLauncher: '.mcode-launcher',
  260. ...(metadata ? { binEntry: metadata.binEntry } : {}),
  261. },
  262. {
  263. name: 'mcode-tools',
  264. releaseLauncher: '.mcode-tools-launcher',
  265. ...(metadata ? { binEntry: metadata.mcodeToolsBinEntry } : {}),
  266. },
  267. ];
  268. }
  269. function writeVersionedInstallReceipt(
  270. activation: McodeVersionedPrefixActivation,
  271. platform: NodeJS.Platform,
  272. ): void {
  273. const platformPath = platformPathFor(platform);
  274. const receipt = {
  275. schemaVersion: 2,
  276. product: 'minimax-code',
  277. updateOwner: 'npm-prefix',
  278. packageManager: 'npm',
  279. packageName: activation.packageName,
  280. registry: new URL(activation.registry).href,
  281. distTag: 'latest',
  282. npmExecutable: activation.npmExecutable,
  283. nodeExecutable: activation.runtimeExecutable,
  284. prefix: activation.activePrefix,
  285. layoutVersion: LAYOUT_VERSION,
  286. releasesDirectory: RELEASES_DIRECTORY,
  287. currentFile: CURRENT_FILE,
  288. };
  289. writeAtomicText(
  290. platformPath.join(activation.activePrefix, 'install.json'),
  291. `${JSON.stringify(receipt, null, 2)}\n`,
  292. 0o600,
  293. );
  294. }
  295. function writeAtomicText(file: string, contents: string, mode: number): void {
  296. const temporaryFile = `${file}.tmp-${process.pid}-${randomUUID()}`;
  297. mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
  298. try {
  299. writeFileSync(temporaryFile, contents, { mode });
  300. chmodSync(temporaryFile, mode);
  301. renameSync(temporaryFile, file);
  302. } catch (error) {
  303. rmSync(temporaryFile, { force: true });
  304. throw error;
  305. }
  306. }
  307. function readLiveUpdateClaims(
  308. lockDirectory: string,
  309. ): readonly { readonly name: string; readonly pid: number; readonly ticket?: number }[] {
  310. const claims: { name: string; pid: number; ticket?: number }[] = [];
  311. for (const name of readdirSync(lockDirectory)) {
  312. const match = /^(\d+)-.+\.claim$/u.exec(name);
  313. if (!match) continue;
  314. const pid = Number(match[1]);
  315. if (!Number.isSafeInteger(pid) || pid <= 0 || !isProcessAlive(pid)) continue;
  316. try {
  317. const rawTicket = readFileSync(path.join(lockDirectory, name), 'utf8').trim();
  318. const ticket = /^\d+$/u.test(rawTicket) ? Number(rawTicket) : undefined;
  319. claims.push({ name, pid, ...(ticket && Number.isSafeInteger(ticket) ? { ticket } : {}) });
  320. } catch {
  321. // A claim that disappeared was released before this snapshot completed.
  322. }
  323. }
  324. return claims;
  325. }
  326. function isProcessAlive(pid: number): boolean {
  327. try {
  328. process.kill(pid, 0);
  329. return true;
  330. } catch (error) {
  331. return (error as NodeJS.ErrnoException).code === 'EPERM';
  332. }
  333. }
  334. function platformPathFor(platform: NodeJS.Platform): McodePlatformPath {
  335. return platform === 'win32' ? path.win32 : path.posix;
  336. }
  337. function quoteShell(value: string): string {
  338. return `'${value.replaceAll("'", `'"'"'`)}'`;
  339. }
  340. function escapeDoubleQuoted(value: string): string {
  341. return value
  342. .replaceAll('\\', '/')
  343. .replaceAll('"', '\\"')
  344. .replaceAll('$', '\\$')
  345. .replaceAll('`', '\\`');
  346. }
  347. function escapeBatch(value: string): string {
  348. return value.replaceAll('%', '%%');
  349. }
  350. function escapePowerShell(value: string): string {
  351. return value.replaceAll("'", "''");
  352. }