sea-runtime-tools.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. import assert from "node:assert/strict";
  2. import { createHash } from "node:crypto";
  3. import { chmod, readdir, readFile, stat, writeFile } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { mkdtemp, rm } from "node:fs/promises";
  7. import test from "node:test";
  8. import { ensureSeaRuntimeTools, type SeaRuntimeModule } from "../src/sea-runtime-tools.js";
  9. type ToolFixture = {
  10. binaryName: string;
  11. bytes: Buffer;
  12. id: "bfs" | "ripgrep" | "ugrep";
  13. version: string;
  14. };
  15. test("does nothing outside a SEA runtime", async () => {
  16. const result = await ensureSeaRuntimeTools({
  17. sea: {
  18. getAsset: () => {
  19. throw new Error("unexpected manifest read");
  20. },
  21. getRawAsset: () => {
  22. throw new Error("unexpected asset read");
  23. },
  24. isSea: () => false,
  25. },
  26. });
  27. assert.deepEqual(result, {});
  28. });
  29. test("extracts target tools into version and hash addressed cache directories", async () => {
  30. const storageRoot = await mkdtemp(join(tmpdir(), "zcode-sea-runtime-cache-"));
  31. const fixture = createSeaFixture({
  32. target: "darwin-arm64",
  33. tools: defaultToolFixtures(),
  34. });
  35. try {
  36. const runtimeEnv = await ensureSeaRuntimeTools({
  37. arch: "arm64",
  38. platform: "darwin",
  39. sea: fixture.sea,
  40. storageRoot,
  41. });
  42. for (const tool of fixture.tools) {
  43. const envVar = envVarFor(tool.id);
  44. const binaryPath = runtimeEnv[envVar];
  45. assert.ok(binaryPath);
  46. assert.equal(
  47. binaryPath,
  48. join(
  49. storageRoot,
  50. "cache",
  51. "runtime_tools",
  52. "darwin-arm64",
  53. tool.id,
  54. `${tool.version}-${tool.sha256}`,
  55. tool.binaryName,
  56. ),
  57. );
  58. assert.deepEqual(await readFile(binaryPath), tool.bytes);
  59. assert.notEqual((await stat(binaryPath)).mode & 0o111, 0);
  60. }
  61. } finally {
  62. await rm(storageRoot, { force: true, recursive: true });
  63. }
  64. });
  65. test("reuses unchanged tools when another tool changes", async () => {
  66. const storageRoot = await mkdtemp(join(tmpdir(), "zcode-sea-runtime-reuse-"));
  67. const firstFixture = createSeaFixture({
  68. target: "darwin-arm64",
  69. tools: defaultToolFixtures(),
  70. });
  71. const changedFixtures = defaultToolFixtures().map((tool) =>
  72. tool.id === "ugrep" ? { ...tool, bytes: Buffer.from("ugrep-next") } : tool,
  73. );
  74. const secondFixture = createSeaFixture({
  75. target: "darwin-arm64",
  76. tools: changedFixtures,
  77. });
  78. try {
  79. const first = await ensureSeaRuntimeTools({
  80. arch: "arm64",
  81. platform: "darwin",
  82. sea: firstFixture.sea,
  83. storageRoot,
  84. });
  85. const firstBfsStat = await stat(assertPath(first.ZCODE_BFS_BINARY));
  86. const second = await ensureSeaRuntimeTools({
  87. arch: "arm64",
  88. platform: "darwin",
  89. sea: secondFixture.sea,
  90. storageRoot,
  91. });
  92. const secondBfsStat = await stat(assertPath(second.ZCODE_BFS_BINARY));
  93. assert.equal(second.ZCODE_BFS_BINARY, first.ZCODE_BFS_BINARY);
  94. assert.equal(secondBfsStat.ino, firstBfsStat.ino);
  95. assert.notEqual(second.ZCODE_UGREP_BINARY, first.ZCODE_UGREP_BINARY);
  96. } finally {
  97. await rm(storageRoot, { force: true, recursive: true });
  98. }
  99. });
  100. test("repairs caches with invalid size, hash, marker, or executable mode", async () => {
  101. const storageRoot = await mkdtemp(join(tmpdir(), "zcode-sea-runtime-repair-"));
  102. const fixture = createSeaFixture({
  103. target: "darwin-arm64",
  104. tools: defaultToolFixtures(),
  105. });
  106. const options = {
  107. arch: "arm64",
  108. platform: "darwin" as const,
  109. sea: fixture.sea,
  110. storageRoot,
  111. };
  112. try {
  113. const first = await ensureSeaRuntimeTools(options);
  114. await chmod(assertPath(first.ZCODE_BFS_BINARY), 0o644);
  115. await writeFile(assertPath(first.ZCODE_RG_BINARY), "short");
  116. await writeFile(
  117. join(assertPath(first.ZCODE_UGREP_BINARY), "..", ".zcode-runtime-tool.json"),
  118. "{}",
  119. );
  120. const repaired = await ensureSeaRuntimeTools(options);
  121. assert.notEqual((await stat(assertPath(repaired.ZCODE_BFS_BINARY))).mode & 0o111, 0);
  122. for (const tool of fixture.tools) {
  123. assert.deepEqual(await readFile(assertPath(repaired[envVarFor(tool.id)])), tool.bytes);
  124. }
  125. await writeFile(assertPath(repaired.ZCODE_RG_BINARY), "corrupt");
  126. const hashRepaired = await ensureSeaRuntimeTools(options);
  127. assert.deepEqual(
  128. await readFile(assertPath(hashRepaired.ZCODE_RG_BINARY)),
  129. Buffer.from("ripgrep"),
  130. );
  131. } finally {
  132. await rm(storageRoot, { force: true, recursive: true });
  133. }
  134. });
  135. test("concurrent first runs converge without temporary cache residue", async () => {
  136. const storageRoot = await mkdtemp(join(tmpdir(), "zcode-sea-runtime-race-"));
  137. const fixture = createSeaFixture({
  138. target: "darwin-arm64",
  139. tools: defaultToolFixtures(),
  140. });
  141. const options = {
  142. arch: "arm64",
  143. platform: "darwin" as const,
  144. sea: fixture.sea,
  145. storageRoot,
  146. };
  147. try {
  148. const results = await Promise.all(
  149. Array.from({ length: 8 }, () => ensureSeaRuntimeTools(options)),
  150. );
  151. for (const result of results.slice(1)) assert.deepEqual(result, results[0]);
  152. const runtimeRoot = join(storageRoot, "cache", "runtime_tools", "darwin-arm64");
  153. const entries = await collectEntries(runtimeRoot);
  154. assert.equal(
  155. entries.some((entry) => entry.includes(".tmp-")),
  156. false,
  157. );
  158. } finally {
  159. await rm(storageRoot, { force: true, recursive: true });
  160. }
  161. });
  162. test("preserves explicit runtime tool overrides", async () => {
  163. const storageRoot = await mkdtemp(join(tmpdir(), "zcode-sea-runtime-override-"));
  164. const fixture = createSeaFixture({
  165. target: "darwin-arm64",
  166. tools: defaultToolFixtures(),
  167. });
  168. try {
  169. const runtimeEnv = await ensureSeaRuntimeTools({
  170. arch: "arm64",
  171. env: { ZCODE_BFS_BINARY: "/custom/bfs" },
  172. platform: "darwin",
  173. sea: fixture.sea,
  174. storageRoot,
  175. });
  176. assert.equal(runtimeEnv.ZCODE_BFS_BINARY, undefined);
  177. assert.ok(runtimeEnv.ZCODE_RG_BINARY);
  178. assert.ok(runtimeEnv.ZCODE_UGREP_BINARY);
  179. } finally {
  180. await rm(storageRoot, { force: true, recursive: true });
  181. }
  182. });
  183. test("extracts Windows SEA tools using the win target and executable name", async () => {
  184. const storageRoot = await mkdtemp(join(tmpdir(), "zcode-sea-runtime-win-"));
  185. const fixture = createSeaFixture({
  186. target: "win-x64",
  187. tools: [
  188. {
  189. binaryName: "rg.exe",
  190. bytes: Buffer.from("windows-rg"),
  191. id: "ripgrep",
  192. version: "14.1.1",
  193. },
  194. {
  195. binaryName: "ugrep.exe",
  196. bytes: Buffer.from("windows-ugrep"),
  197. id: "ugrep",
  198. version: "7.8.4",
  199. },
  200. ],
  201. });
  202. try {
  203. const runtimeEnv = await ensureSeaRuntimeTools({
  204. arch: "x64",
  205. platform: "win32",
  206. sea: fixture.sea,
  207. storageRoot,
  208. });
  209. assert.match(assertPath(runtimeEnv.ZCODE_RG_BINARY), /runtime_tools[/\\]win-x64[/\\]ripgrep/u);
  210. assert.equal(assertPath(runtimeEnv.ZCODE_RG_BINARY).endsWith("rg.exe"), true);
  211. assert.match(assertPath(runtimeEnv.ZCODE_UGREP_BINARY), /runtime_tools[/\\]win-x64[/\\]ugrep/u);
  212. assert.equal(assertPath(runtimeEnv.ZCODE_UGREP_BINARY).endsWith("ugrep.exe"), true);
  213. } finally {
  214. await rm(storageRoot, { force: true, recursive: true });
  215. }
  216. });
  217. test("rejects corrupt assets and target mismatches", async () => {
  218. const storageRoot = await mkdtemp(join(tmpdir(), "zcode-sea-runtime-invalid-"));
  219. const fixture = createSeaFixture({
  220. target: "darwin-arm64",
  221. tools: defaultToolFixtures(),
  222. });
  223. const corruptSea: SeaRuntimeModule = {
  224. ...fixture.sea,
  225. getRawAsset: (key) =>
  226. key.includes("/bfs/") ? toArrayBuffer(Buffer.from("bad")) : fixture.sea.getRawAsset(key),
  227. };
  228. try {
  229. await assert.rejects(
  230. ensureSeaRuntimeTools({
  231. arch: "arm64",
  232. platform: "darwin",
  233. sea: corruptSea,
  234. storageRoot,
  235. }),
  236. /SEA runtime tool hash mismatch for bfs/,
  237. );
  238. await assert.rejects(
  239. ensureSeaRuntimeTools({
  240. arch: "x64",
  241. platform: "darwin",
  242. sea: fixture.sea,
  243. storageRoot,
  244. }),
  245. /SEA runtime tool target mismatch/,
  246. );
  247. } finally {
  248. await rm(storageRoot, { force: true, recursive: true });
  249. }
  250. });
  251. function defaultToolFixtures(): ToolFixture[] {
  252. return [
  253. { binaryName: "bfs", bytes: Buffer.from("bfs"), id: "bfs", version: "4.1.1" },
  254. {
  255. binaryName: "rg",
  256. bytes: Buffer.from("ripgrep"),
  257. id: "ripgrep",
  258. version: "14.1.1",
  259. },
  260. { binaryName: "ugrep", bytes: Buffer.from("ugrep"), id: "ugrep", version: "7.8.4" },
  261. ];
  262. }
  263. function createSeaFixture(input: { target: string; tools: ToolFixture[] }): {
  264. sea: SeaRuntimeModule;
  265. tools: Array<ToolFixture & { assetKey: string; sha256: string }>;
  266. } {
  267. const assets = new Map<string, Buffer>();
  268. const tools = input.tools.map((tool) => {
  269. const sha256 = createHash("sha256").update(tool.bytes).digest("hex");
  270. const assetKey = `zcode-runtime-tools/${tool.id}/${sha256}/${tool.binaryName}`;
  271. assets.set(assetKey, tool.bytes);
  272. return { ...tool, assetKey, sha256 };
  273. });
  274. const manifestTools = tools.map((tool) => ({
  275. binaryName: tool.binaryName,
  276. id: tool.id,
  277. sha256: tool.sha256,
  278. size: tool.bytes.byteLength,
  279. version: tool.version,
  280. }));
  281. const manifest = JSON.stringify({
  282. target: input.target,
  283. tools: manifestTools,
  284. version: 1,
  285. });
  286. return {
  287. sea: {
  288. getAsset: () => manifest,
  289. getRawAsset: (key) => {
  290. const bytes = assets.get(key);
  291. if (!bytes) throw new Error(`missing fake SEA asset ${key}`);
  292. return toArrayBuffer(bytes);
  293. },
  294. isSea: () => true,
  295. },
  296. tools,
  297. };
  298. }
  299. function envVarFor(toolId: ToolFixture["id"]): string {
  300. switch (toolId) {
  301. case "bfs":
  302. return "ZCODE_BFS_BINARY";
  303. case "ripgrep":
  304. return "ZCODE_RG_BINARY";
  305. case "ugrep":
  306. return "ZCODE_UGREP_BINARY";
  307. }
  308. }
  309. function assertPath(value: string | undefined): string {
  310. assert.ok(value);
  311. return value;
  312. }
  313. function toArrayBuffer(bytes: Buffer): ArrayBuffer {
  314. return Uint8Array.from(bytes).buffer;
  315. }
  316. async function collectEntries(root: string): Promise<string[]> {
  317. const entries: string[] = [];
  318. for (const entry of await readdir(root, { withFileTypes: true })) {
  319. const path = join(root, entry.name);
  320. entries.push(path);
  321. if (entry.isDirectory()) entries.push(...(await collectEntries(path)));
  322. }
  323. return entries;
  324. }