space-data-module-sdk 0.9.10 → 0.9.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "space-data-module-sdk",
3
- "version": "0.9.10",
3
+ "version": "0.9.12",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Module SDK for building, validating, signing, and deploying WebAssembly modules on the Space Data Network.",
6
6
  "type": "module",
@@ -0,0 +1,495 @@
1
+ // Content-addressed compile cache.
2
+ //
3
+ // Every compile and link step of compileModuleFromSource (and of the
4
+ // precompiled headers and library objects it builds) is keyed on what decides
5
+ // its output:
6
+ //
7
+ // - the input bytes: the translation unit, every header the SDK stages beside
8
+ // it, and every other header the compiler read (recorded from its depfile
9
+ // and checked again on each lookup: path, size, mtime, and sha256 when the
10
+ // stat differs);
11
+ // - the exact command and flags (temp-dir paths normalized away);
12
+ // - the toolchain identity (driver, version, binary and sysroot stats, or the
13
+ // emception package fingerprint);
14
+ // - the SDK identity (package version and the bytes of src/compiler/*.js).
15
+ //
16
+ // A hit returns the stored output bytes without starting a toolchain. Entries
17
+ // are single files written to a temp name and renamed into place, so any number
18
+ // of concurrent builds can share one cache: a reader sees a complete entry or
19
+ // none, and every blob is checked against its sha256 before it is used.
20
+ //
21
+ // Location: SPACE_DATA_MODULE_SDK_CACHE_DIR, else $XDG_CACHE_HOME/space-data-module-sdk,
22
+ // else ~/.cache/space-data-module-sdk. SPACE_DATA_MODULE_SDK_COMPILE_CACHE=0 (or
23
+ // off/false/no) or the compile option `compileCache: false` turns it off.
24
+
25
+ import os from "node:os";
26
+ import path from "node:path";
27
+ import { createHash, randomBytes } from "node:crypto";
28
+ import { execFile } from "node:child_process";
29
+ import { promisify } from "node:util";
30
+ import {
31
+ mkdir,
32
+ readdir,
33
+ readFile,
34
+ realpath,
35
+ rename,
36
+ rm,
37
+ stat,
38
+ utimes,
39
+ writeFile,
40
+ } from "node:fs/promises";
41
+ import { createRequire } from "node:module";
42
+ import { fileURLToPath } from "node:url";
43
+
44
+ const execFileAsync = promisify(execFile);
45
+ const require = createRequire(import.meta.url);
46
+
47
+ // Bump when the entry layout or the meaning of a key changes.
48
+ export const COMPILE_CACHE_FORMAT = "sdm-compile-cache-v1";
49
+ const ENTRY_MAGIC = new TextEncoder().encode("SDMCC1\n");
50
+ const ENTRY_SUFFIX = ".entry";
51
+ const DISABLED_VALUES = new Set(["0", "off", "false", "no", "disabled"]);
52
+ const DEFAULT_MAX_BYTES = 4 * 1024 ** 3;
53
+
54
+ export function resolveCompileCacheRoot(explicitDir) {
55
+ if (explicitDir) return path.resolve(explicitDir);
56
+ if (process.env.SPACE_DATA_MODULE_SDK_CACHE_DIR) {
57
+ return path.resolve(process.env.SPACE_DATA_MODULE_SDK_CACHE_DIR);
58
+ }
59
+ const base = process.env.XDG_CACHE_HOME
60
+ ? path.resolve(process.env.XDG_CACHE_HOME)
61
+ : path.join(os.homedir(), ".cache");
62
+ return path.join(base, "space-data-module-sdk");
63
+ }
64
+
65
+ /**
66
+ * Resolve the compile option `compileCache` (`undefined`, `true`, `false`, or
67
+ * `{ dir }`) and the environment into a cache handle, or null when caching is
68
+ * off.
69
+ */
70
+ export function openCompileCache(option) {
71
+ if (option === false) return null;
72
+ const envSetting = String(process.env.SPACE_DATA_MODULE_SDK_COMPILE_CACHE ?? "").trim().toLowerCase();
73
+ if (option === undefined || option === null || option === true) {
74
+ if (DISABLED_VALUES.has(envSetting)) return null;
75
+ }
76
+ const dir = typeof option === "object" && option !== null ? option.dir : undefined;
77
+ return new CompileCache(resolveCompileCacheRoot(dir));
78
+ }
79
+
80
+ export function sha256Hex(bytes) {
81
+ return createHash("sha256").update(bytes).digest("hex");
82
+ }
83
+
84
+ // A stable digest of a JSON-able value (object keys sorted).
85
+ export function digestOf(value) {
86
+ return sha256Hex(stableStringify(value));
87
+ }
88
+
89
+ function stableStringify(value) {
90
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
91
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
92
+ const keys = Object.keys(value).filter((key) => value[key] !== undefined).sort();
93
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
94
+ }
95
+
96
+ function toBytes(content) {
97
+ if (content instanceof Uint8Array) return content;
98
+ return new TextEncoder().encode(String(content));
99
+ }
100
+
101
+ // The digest of a set of named files ({ relativePath: string | Uint8Array }).
102
+ export function digestFiles(files) {
103
+ const hash = createHash("sha256");
104
+ for (const name of Object.keys(files).sort()) {
105
+ const bytes = toBytes(files[name]);
106
+ hash.update(`${name}\0${bytes.length}\0`);
107
+ hash.update(bytes);
108
+ hash.update("\0");
109
+ }
110
+ return hash.digest("hex");
111
+ }
112
+
113
+ function encodeEntry(meta, blobs) {
114
+ const names = Object.keys(blobs).sort();
115
+ const header = {
116
+ format: COMPILE_CACHE_FORMAT,
117
+ meta,
118
+ blobs: names.map((name) => ({ name, size: blobs[name].length, sha256: sha256Hex(blobs[name]) })),
119
+ };
120
+ const headerBytes = new TextEncoder().encode(JSON.stringify(header));
121
+ const lengthBytes = new Uint8Array(4);
122
+ new DataView(lengthBytes.buffer).setUint32(0, headerBytes.length, true);
123
+ return Buffer.concat([ENTRY_MAGIC, lengthBytes, headerBytes, ...names.map((name) => blobs[name])]);
124
+ }
125
+
126
+ function decodeEntry(bytes) {
127
+ if (bytes.length < ENTRY_MAGIC.length + 4) return null;
128
+ for (let index = 0; index < ENTRY_MAGIC.length; index += 1) {
129
+ if (bytes[index] !== ENTRY_MAGIC[index]) return null;
130
+ }
131
+ const headerLength = new DataView(bytes.buffer, bytes.byteOffset + ENTRY_MAGIC.length, 4).getUint32(0, true);
132
+ const headerStart = ENTRY_MAGIC.length + 4;
133
+ const header = JSON.parse(new TextDecoder().decode(bytes.subarray(headerStart, headerStart + headerLength)));
134
+ if (header?.format !== COMPILE_CACHE_FORMAT || !Array.isArray(header.blobs)) return null;
135
+ const blobs = {};
136
+ let offset = headerStart + headerLength;
137
+ for (const { name, size, sha256 } of header.blobs) {
138
+ const blob = new Uint8Array(bytes.subarray(offset, offset + size));
139
+ if (blob.length !== size || sha256Hex(blob) !== sha256) return null;
140
+ blobs[name] = blob;
141
+ offset += size;
142
+ }
143
+ if (offset !== bytes.length) return null;
144
+ return { meta: header.meta ?? {}, blobs };
145
+ }
146
+
147
+ // Header dependencies outside the staged build dir: each is recorded with its
148
+ // size, mtime and sha256, and a lookup accepts the entry only while every one
149
+ // still has those bytes (a changed stat is re-hashed, so a touch is no miss).
150
+ export async function describeExternalDependencies(paths) {
151
+ const unique = Array.from(new Set(paths)).sort();
152
+ const deps = [];
153
+ for (const file of unique) {
154
+ const info = await stat(file);
155
+ if (!info.isFile()) continue;
156
+ deps.push({ path: file, size: info.size, mtimeMs: info.mtimeMs, sha256: sha256Hex(await readFile(file)) });
157
+ }
158
+ return deps;
159
+ }
160
+
161
+ async function externalDependenciesUnchanged(deps) {
162
+ for (const dep of Array.isArray(deps) ? deps : []) {
163
+ let info;
164
+ try {
165
+ info = await stat(dep.path);
166
+ } catch {
167
+ return false;
168
+ }
169
+ if (info.size === dep.size && info.mtimeMs === dep.mtimeMs) continue;
170
+ if (info.size !== dep.size) return false;
171
+ try {
172
+ if (sha256Hex(await readFile(dep.path)) !== dep.sha256) return false;
173
+ } catch {
174
+ return false;
175
+ }
176
+ }
177
+ return true;
178
+ }
179
+
180
+ /**
181
+ * Parse a Makefile-style depfile (clang -MD -MF) into its prerequisite paths.
182
+ */
183
+ export function parseDepfile(text) {
184
+ const joined = String(text).replace(/\\\r?\n/g, " ");
185
+ const colon = joined.search(/:(\s|$)/);
186
+ const body = colon >= 0 ? joined.slice(colon + 1) : joined;
187
+ const paths = [];
188
+ let current = "";
189
+ for (let index = 0; index < body.length; index += 1) {
190
+ const char = body[index];
191
+ if (char === "\\" && body[index + 1] === " ") {
192
+ current += " ";
193
+ index += 1;
194
+ } else if (char === "$" && body[index + 1] === "$") {
195
+ current += "$";
196
+ index += 1;
197
+ } else if (/\s/.test(char)) {
198
+ if (current) paths.push(current);
199
+ current = "";
200
+ } else {
201
+ current += char;
202
+ }
203
+ }
204
+ if (current) paths.push(current);
205
+ return paths;
206
+ }
207
+
208
+ export class CompileCache {
209
+ constructor(root) {
210
+ this.root = root;
211
+ this.entriesDir = path.join(root, "entries");
212
+ this.stats = { hits: 0, misses: 0, stores: 0 };
213
+ }
214
+
215
+ entryPath(key) {
216
+ return path.join(this.entriesDir, key.slice(0, 2), `${key}${ENTRY_SUFFIX}`);
217
+ }
218
+
219
+ /** The stored entry for `key` ({ meta, blobs }), or null. */
220
+ async get(key) {
221
+ const file = this.entryPath(key);
222
+ let bytes;
223
+ try {
224
+ bytes = await readFile(file);
225
+ } catch {
226
+ this.stats.misses += 1;
227
+ return null;
228
+ }
229
+ let entry = null;
230
+ try {
231
+ entry = decodeEntry(new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.length));
232
+ } catch {
233
+ entry = null;
234
+ }
235
+ if (!entry || entry.meta?.key !== key || !(await externalDependenciesUnchanged(entry.meta?.externalDeps))) {
236
+ this.stats.misses += 1;
237
+ return null;
238
+ }
239
+ // Recency for pruning; best effort.
240
+ const now = new Date();
241
+ await utimes(file, now, now).catch(() => {});
242
+ this.stats.hits += 1;
243
+ return entry;
244
+ }
245
+
246
+ /** Store `blobs` ({ name: Uint8Array }) under `key`, atomically. */
247
+ async put(key, blobs, meta = {}) {
248
+ const file = this.entryPath(key);
249
+ const dir = path.dirname(file);
250
+ try {
251
+ await mkdir(dir, { recursive: true });
252
+ const temp = path.join(dir, `.${key}.${process.pid}-${randomBytes(6).toString("hex")}.tmp`);
253
+ await writeFile(temp, encodeEntry({ ...meta, key }, blobs));
254
+ try {
255
+ await rename(temp, file);
256
+ } catch (error) {
257
+ await rm(temp, { force: true });
258
+ throw error;
259
+ }
260
+ this.stats.stores += 1;
261
+ } catch {
262
+ // A cache that cannot be written (read-only home, full disk) never fails a build.
263
+ return;
264
+ }
265
+ await autoPrune(this.root);
266
+ }
267
+ }
268
+
269
+ // Once per process, after its first store: keep the cache under
270
+ // SPACE_DATA_MODULE_SDK_CACHE_MAX_BYTES (default 4 GiB), least recently used first.
271
+ const prunedRoots = new Set();
272
+ async function autoPrune(root) {
273
+ if (prunedRoots.has(root)) return;
274
+ prunedRoots.add(root);
275
+ const configured = Number(process.env.SPACE_DATA_MODULE_SDK_CACHE_MAX_BYTES);
276
+ const maxBytes = Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_MAX_BYTES;
277
+ await pruneCompileCache({ dir: root, maxBytes }).catch(() => {});
278
+ }
279
+
280
+ /**
281
+ * Remove least-recently-used entries until the cache holds at most `maxBytes`
282
+ * (default 4 GiB), and any temp file older than an hour. Returns
283
+ * { removedEntries, removedBytes, keptBytes }.
284
+ */
285
+ export async function pruneCompileCache({ dir, maxBytes = DEFAULT_MAX_BYTES } = {}) {
286
+ const root = resolveCompileCacheRoot(dir);
287
+ const entriesDir = path.join(root, "entries");
288
+ const files = [];
289
+ let shards = [];
290
+ try {
291
+ shards = await readdir(entriesDir);
292
+ } catch {
293
+ return { removedEntries: 0, removedBytes: 0, keptBytes: 0 };
294
+ }
295
+ const hourAgo = Date.now() - 3600 * 1000;
296
+ for (const shard of shards) {
297
+ const shardDir = path.join(entriesDir, shard);
298
+ let names = [];
299
+ try {
300
+ names = await readdir(shardDir);
301
+ } catch {
302
+ continue;
303
+ }
304
+ for (const name of names) {
305
+ const file = path.join(shardDir, name);
306
+ const info = await stat(file).catch(() => null);
307
+ if (!info?.isFile()) continue;
308
+ if (name.endsWith(".tmp")) {
309
+ if (info.mtimeMs < hourAgo) await rm(file, { force: true });
310
+ continue;
311
+ }
312
+ files.push({ file, size: info.size, mtimeMs: info.mtimeMs });
313
+ }
314
+ }
315
+ files.sort((a, b) => b.mtimeMs - a.mtimeMs);
316
+ let kept = 0;
317
+ let removedEntries = 0;
318
+ let removedBytes = 0;
319
+ for (const entry of files) {
320
+ if (kept + entry.size <= maxBytes) {
321
+ kept += entry.size;
322
+ continue;
323
+ }
324
+ await rm(entry.file, { force: true });
325
+ removedEntries += 1;
326
+ removedBytes += entry.size;
327
+ }
328
+ return { removedEntries, removedBytes, keptBytes: kept };
329
+ }
330
+
331
+ // --- identities ------------------------------------------------------------
332
+
333
+ let sdkIdentityPromise = null;
334
+
335
+ /**
336
+ * The SDK half of every key: the package version and the bytes of the compiler
337
+ * sources (so an unreleased edit of the compile pipeline never reuses entries).
338
+ */
339
+ export function getSdkCompileIdentity() {
340
+ sdkIdentityPromise ??= (async () => {
341
+ const compilerDir = path.dirname(fileURLToPath(import.meta.url));
342
+ const packageJson = JSON.parse(
343
+ await readFile(path.join(compilerDir, "..", "..", "package.json"), "utf8"),
344
+ );
345
+ const files = {};
346
+ for (const name of (await readdir(compilerDir)).filter((entry) => entry.endsWith(".js")).sort()) {
347
+ files[name] = await readFile(path.join(compilerDir, name));
348
+ }
349
+ return { sdkVersion: String(packageJson.version), compilerSources: digestFiles(files) };
350
+ })();
351
+ return sdkIdentityPromise;
352
+ }
353
+
354
+ async function statIdentity(file) {
355
+ try {
356
+ const resolved = await realpath(file);
357
+ const info = await stat(resolved);
358
+ return { path: resolved, size: info.size, mtimeMs: info.mtimeMs };
359
+ } catch {
360
+ return { path: file, missing: true };
361
+ }
362
+ }
363
+
364
+ async function whichExecutable(command) {
365
+ if (command.includes("/")) return command;
366
+ for (const dir of String(process.env.PATH ?? "").split(path.delimiter)) {
367
+ if (!dir) continue;
368
+ const candidate = path.join(dir, command);
369
+ try {
370
+ const info = await stat(candidate);
371
+ if (info.isFile()) return candidate;
372
+ } catch {
373
+ // keep looking
374
+ }
375
+ }
376
+ return command;
377
+ }
378
+
379
+ const toolchainIdentityCache = new Map();
380
+
381
+ /**
382
+ * Identity of a native clang driver (the wasi toolchain): its --version text,
383
+ * the resolved driver and clang binary (path, size, mtime), and the given
384
+ * toolchain args and roots (sysroot, resource dir) with stats of their
385
+ * libraries.
386
+ */
387
+ export function getNativeClangIdentity({ drivers, toolchainArgs = [], roots = [] }) {
388
+ const cacheKey = JSON.stringify({ drivers, toolchainArgs, roots });
389
+ if (!toolchainIdentityCache.has(cacheKey)) {
390
+ toolchainIdentityCache.set(cacheKey, (async () => {
391
+ const driverIds = [];
392
+ for (const driver of drivers) {
393
+ const { stdout } = await execFileAsync(driver, ["--version"], { maxBuffer: 1024 * 1024 });
394
+ const installedDir = /InstalledDir:\s*(.+)/.exec(stdout)?.[1]?.trim();
395
+ driverIds.push({
396
+ driver: await statIdentity(await whichExecutable(driver)),
397
+ version: stdout.trim(),
398
+ clang: installedDir ? await statIdentity(path.join(installedDir, "clang")) : null,
399
+ });
400
+ }
401
+ const rootIds = [];
402
+ for (const root of roots.filter(Boolean)) {
403
+ rootIds.push({ root, libs: await describeLibraries(root) });
404
+ }
405
+ return digestOf({ kind: "native-clang", driverIds, toolchainArgs, rootIds });
406
+ })());
407
+ }
408
+ return toolchainIdentityCache.get(cacheKey);
409
+ }
410
+
411
+ // Stats of the static libraries under a toolchain root (libc, libc++, compiler-rt):
412
+ // a reinstall that changes them changes the identity.
413
+ async function describeLibraries(root) {
414
+ const out = [];
415
+ const walk = async (dir, depth) => {
416
+ if (depth > 4) return;
417
+ let entries = [];
418
+ try {
419
+ entries = await readdir(dir, { withFileTypes: true });
420
+ } catch {
421
+ return;
422
+ }
423
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
424
+ const full = path.join(dir, entry.name);
425
+ if (entry.isDirectory()) {
426
+ await walk(full, depth + 1);
427
+ } else if (entry.name.endsWith(".a")) {
428
+ const info = await stat(full).catch(() => null);
429
+ if (info) out.push([path.relative(root, full), info.size, info.mtimeMs]);
430
+ }
431
+ }
432
+ };
433
+ await walk(path.join(root, "lib"), 0);
434
+ return out;
435
+ }
436
+
437
+ /** Identity of a system Emscripten (em++ / emcc on PATH). */
438
+ export function getSystemEmscriptenIdentity(commands) {
439
+ const cacheKey = JSON.stringify({ emscripten: commands });
440
+ if (!toolchainIdentityCache.has(cacheKey)) {
441
+ toolchainIdentityCache.set(cacheKey, (async () => {
442
+ const ids = [];
443
+ for (const command of commands) {
444
+ const { stdout } = await execFileAsync(command, ["--version"], { maxBuffer: 1024 * 1024 });
445
+ ids.push({ command: await statIdentity(await whichExecutable(command)), version: stdout.trim() });
446
+ }
447
+ return digestOf({ kind: "system-emscripten", ids, emsdk: process.env.EMSDK ?? null });
448
+ })());
449
+ }
450
+ return toolchainIdentityCache.get(cacheKey);
451
+ }
452
+
453
+ /**
454
+ * Identity of the vendored sdn-emception: its package version and the path,
455
+ * size and mtime of every file it ships (a stat walk, not a hash of 160 MB).
456
+ */
457
+ export function getEmceptionPackageIdentity(extra = "") {
458
+ const cacheKey = `emception\0${extra}`;
459
+ if (!toolchainIdentityCache.has(cacheKey)) {
460
+ toolchainIdentityCache.set(cacheKey, (async () => {
461
+ const root = path.dirname(require.resolve("sdn-emception"));
462
+ let packageRoot = root;
463
+ let version = "unknown";
464
+ for (;;) {
465
+ try {
466
+ const pkg = JSON.parse(await readFile(path.join(packageRoot, "package.json"), "utf8"));
467
+ if (pkg?.name === "sdn-emception") {
468
+ version = String(pkg.version);
469
+ break;
470
+ }
471
+ } catch {
472
+ // keep walking up
473
+ }
474
+ const parent = path.dirname(packageRoot);
475
+ if (parent === packageRoot) break;
476
+ packageRoot = parent;
477
+ }
478
+ const files = [];
479
+ const walk = async (dir) => {
480
+ const entries = await readdir(dir, { withFileTypes: true });
481
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
482
+ const full = path.join(dir, entry.name);
483
+ if (entry.isDirectory()) await walk(full);
484
+ else if (entry.isFile()) {
485
+ const info = await stat(full);
486
+ files.push([path.relative(root, full), info.size, info.mtimeMs]);
487
+ }
488
+ }
489
+ };
490
+ await walk(root);
491
+ return digestOf({ kind: "emception", version, files, extra });
492
+ })());
493
+ }
494
+ return toolchainIdentityCache.get(cacheKey);
495
+ }