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.
@@ -48,7 +48,16 @@ import {
48
48
 
49
49
  import { generateEmbeddedManifestSource } from "../embeddedManifest.js";
50
50
  import { generateInvokeSupportHeader } from "../compiler/invokeGlue.js";
51
- import { runWithEmceptionLock } from "../compiler/emceptionNode.js";
51
+ import { getEmceptionCompileIdentity, runWithEmceptionLock } from "../compiler/emceptionNode.js";
52
+ import {
53
+ COMPILE_CACHE_FORMAT,
54
+ digestFiles,
55
+ digestOf,
56
+ getNativeClangIdentity,
57
+ getSdkCompileIdentity,
58
+ openCompileCache,
59
+ sha256Hex,
60
+ } from "../compiler/compileCache.js";
52
61
  import {
53
62
  assertPthreadArtifact,
54
63
  assertPthreadFlagsPresent,
@@ -395,7 +404,7 @@ async function loadDependencyFromDirectory(dir) {
395
404
  readFile(path.join(guestLinkDir, GUEST_LINK_OBJECT_FILENAME)),
396
405
  readFile(path.join(guestLinkDir, GUEST_LINK_METADATA_FILENAME), "utf8").then(JSON.parse),
397
406
  ]);
398
- return { objectBytes: new Uint8Array(objectBytes), metadata };
407
+ return { objectBytes: new Uint8Array(objectBytes), metadata, guestLinkDir };
399
408
  };
400
409
  try {
401
410
  entry.guestLink = await readGuestLink("guest-link");
@@ -409,9 +418,57 @@ async function loadDependencyFromDirectory(dir) {
409
418
  } catch {
410
419
  entry.guestLinkLinked = null;
411
420
  }
421
+ // Shared library objects the guest-link metadata lists (metadata.version 2):
422
+ // outside the try above, so a listed library that is missing or does not
423
+ // hash to its recorded sha256 fails the flow rather than dropping the module.
424
+ for (const guestLink of [entry.guestLink, entry.guestLinkLinked]) {
425
+ if (guestLink) guestLink.libraries = await readGuestLinkLibraries(guestLink, manifest.pluginId);
426
+ }
412
427
  return entry;
413
428
  }
414
429
 
430
+ async function readGuestLinkLibraries(guestLink, pluginId) {
431
+ const listed = guestLink.metadata?.libraries;
432
+ if (listed === undefined || listed === null) return [];
433
+ if (!Array.isArray(listed)) {
434
+ throw new Error(`Plugin "${pluginId}": guest-link metadata.libraries must be an array.`);
435
+ }
436
+ const libraries = [];
437
+ for (const library of listed) {
438
+ const file = String(library?.file ?? "");
439
+ const resolved = path.resolve(guestLink.guestLinkDir, file);
440
+ if (!file || !resolved.startsWith(guestLink.guestLinkDir + path.sep)) {
441
+ throw new Error(`Plugin "${pluginId}": guest-link library ${JSON.stringify(library?.name)} has no file inside its guest-link dir.`);
442
+ }
443
+ if (!/^sdm_lib_[A-Za-z0-9_]+_$/.test(String(library?.namespace ?? ""))) {
444
+ throw new Error(`Plugin "${pluginId}": guest-link library ${JSON.stringify(library?.name)} has no sdm_lib_ namespace.`);
445
+ }
446
+ const objectBytes = new Uint8Array(await readFile(resolved));
447
+ const sha256 = bytesToHex(await sha256Bytes(objectBytes));
448
+ if (sha256 !== library.sha256) {
449
+ throw new Error(
450
+ `Plugin "${pluginId}": guest-link library ${file} hashes to ${sha256}, but its metadata records ${library.sha256}.`,
451
+ );
452
+ }
453
+ libraries.push({ ...library, objectBytes });
454
+ }
455
+ return libraries;
456
+ }
457
+
458
+ // Each shared library namespace once, in first-use order. A namespace is the
459
+ // library's name, version and a digest of its source, defines, flags and
460
+ // toolchain kind, so two modules carrying the same namespace carry the same
461
+ // library and the flow links one copy of it.
462
+ function collectFlowLibraryObjects(linkedDependencies) {
463
+ const byNamespace = new Map();
464
+ for (const dependency of linkedDependencies) {
465
+ for (const library of dependency.guestLink?.libraries ?? []) {
466
+ if (!byNamespace.has(library.namespace)) byNamespace.set(library.namespace, library);
467
+ }
468
+ }
469
+ return Array.from(byNamespace.values());
470
+ }
471
+
415
472
  async function scanForDependencyDirs(root, found) {
416
473
  let entries;
417
474
  try {
@@ -3035,6 +3092,56 @@ async function linkFlowArtifactWithWasiThreads({
3035
3092
  }
3036
3093
  }
3037
3094
 
3095
+ // The flow link through the compile cache (src/compiler/compileCache.js): keyed
3096
+ // on every generated source, every dependency and library object, the link
3097
+ // mode, the toolchain identity, the SDK compiler identity and this file's
3098
+ // bytes (its compile and link flags). An unchanged flow is not relinked.
3099
+ const FLOW_COMPILER_SOURCE = new URL(import.meta.url);
3100
+ let flowCompilerDigestPromise = null;
3101
+
3102
+ async function linkFlowArtifactCached(link, threadModel, inputs) {
3103
+ const cache = openCompileCache();
3104
+ if (!cache) return link(inputs);
3105
+ flowCompilerDigestPromise ??= readFile(FLOW_COMPILER_SOURCE).then((bytes) => sha256Hex(bytes));
3106
+ let toolchain;
3107
+ if (threadModel === FLOW_THREAD_MODEL.SINGLE_THREAD) {
3108
+ toolchain = { kind: "emception", id: await getEmceptionCompileIdentity() };
3109
+ } else {
3110
+ const wasi = resolveWasiThreadsToolchain();
3111
+ toolchain = {
3112
+ kind: "wasi",
3113
+ id: await getNativeClangIdentity({
3114
+ drivers: [wasi.clangxx],
3115
+ toolchainArgs: wasi.toolchainArgs,
3116
+ roots: [wasi.sysroot, wasi.resourceDir],
3117
+ }),
3118
+ };
3119
+ }
3120
+ const key = digestOf({
3121
+ format: COMPILE_CACHE_FORMAT,
3122
+ step: "flow-link",
3123
+ sdk: await getSdkCompileIdentity(),
3124
+ flowCompiler: await flowCompilerDigestPromise,
3125
+ toolchain,
3126
+ threadModel,
3127
+ engineLinked: Boolean(inputs.engineLinked),
3128
+ sequential: Boolean(inputs.sequential),
3129
+ sources: digestFiles({
3130
+ "flow_runtime.cpp": inputs.runtimeSource,
3131
+ "space_data_module_invoke.h": inputs.invokeHeader,
3132
+ "flow_generated.inc": inputs.generatedInc,
3133
+ "flow-manifest-exports.cpp": inputs.manifestSource,
3134
+ "flow-program-exports.cpp": inputs.programSource,
3135
+ }),
3136
+ objects: inputs.dependencyObjects.map((bytes) => sha256Hex(bytes)),
3137
+ });
3138
+ const entry = await cache.get(key);
3139
+ if (entry?.blobs?.wasm) return entry.blobs.wasm;
3140
+ const wasmBytes = await link(inputs);
3141
+ await cache.put(key, { wasm: wasmBytes }, { step: "flow-link" });
3142
+ return wasmBytes;
3143
+ }
3144
+
3038
3145
  /**
3039
3146
  * Compile a validated flow document into the linked-direct flow bundle.
3040
3147
  * Returns { check, manifest, artifact, outputs, report }.
@@ -3129,13 +3236,16 @@ export async function compileFlowProgram({
3129
3236
  check.threadModel !== FLOW_THREAD_MODEL.SINGLE_THREAD
3130
3237
  ? linkFlowArtifactWithWasiThreads
3131
3238
  : linkFlowArtifactWithEmception;
3132
- let wasmBytes = await linkFlowArtifact({
3239
+ let wasmBytes = await linkFlowArtifactCached(linkFlowArtifact, check.threadModel, {
3133
3240
  runtimeSource,
3134
3241
  invokeHeader: generateInvokeSupportHeader(),
3135
3242
  generatedInc,
3136
3243
  manifestSource,
3137
3244
  programSource,
3138
- dependencyObjects: linkedDependencies.map((dependency) => dependency.guestLink.objectBytes),
3245
+ dependencyObjects: [
3246
+ ...linkedDependencies.map((dependency) => dependency.guestLink.objectBytes),
3247
+ ...collectFlowLibraryObjects(linkedDependencies).map((library) => library.objectBytes),
3248
+ ],
3139
3249
  engineLinked: Boolean(check.engineLinkage),
3140
3250
  sequential: check.threadModel === FLOW_THREAD_MODEL.WASI_SEQUENTIAL,
3141
3251
  });
@@ -3185,6 +3295,16 @@ export async function compileFlowProgram({
3185
3295
  publisher: dependency.artifactLock?.publisher ?? null,
3186
3296
  symbolPrefix: dependency.guestLink?.metadata?.symbolPrefix ?? null,
3187
3297
  methodSymbols: dependency.guestLink?.metadata?.methodSymbols ?? {},
3298
+ ...(dependency.guestLink?.libraries?.length
3299
+ ? {
3300
+ libraries: dependency.guestLink.libraries.map(({ name, version, namespace, sha256: librarySha256 }) => ({
3301
+ name,
3302
+ version,
3303
+ namespace,
3304
+ sha256: librarySha256,
3305
+ })),
3306
+ }
3307
+ : {}),
3188
3308
  });
3189
3309
  }
3190
3310
  for (const component of check.componentDependencies ?? []) {
package/src/index.d.ts CHANGED
@@ -993,6 +993,8 @@ export interface CompilationResult {
993
993
  tempDir: string | null;
994
994
  wasmBytes: Uint8Array;
995
995
  guestLink: GuestLinkArtifact | null;
996
+ /** Which compile steps the content cache answered. */
997
+ compileCache?: CompileCacheReport;
996
998
  manifestWarnings: string[];
997
999
  report: ComplianceReport;
998
1000
  }
@@ -1005,6 +1007,8 @@ export interface GuestLinkArtifact {
1005
1007
  threadModel: ModuleThreadModelName;
1006
1008
  capabilities: string[];
1007
1009
  objectBytes: Uint8Array;
1010
+ /** Present when the compile linked `libraries`. */
1011
+ libraries?: GuestLinkLibrary[];
1008
1012
  }
1009
1013
 
1010
1014
  /**
@@ -1081,12 +1085,101 @@ export function compileModuleFromSource(options: {
1081
1085
  guestLinkCapabilities?: string[];
1082
1086
  catalog?: StandardsEntry[];
1083
1087
  standardsRoot?: string;
1088
+ /**
1089
+ * The content-addressed compile cache. Default on, at
1090
+ * SPACE_DATA_MODULE_SDK_CACHE_DIR, else $XDG_CACHE_HOME/space-data-module-sdk,
1091
+ * else ~/.cache/space-data-module-sdk. `false` (or the environment
1092
+ * SPACE_DATA_MODULE_SDK_COMPILE_CACHE=0) compiles everything; `{ dir }`
1093
+ * names another cache directory.
1094
+ */
1095
+ compileCache?: boolean | { dir?: string };
1096
+ /**
1097
+ * Shared libraries compiled once into their own objects and linked by the
1098
+ * module (and once per flow): see GuestLinkLibrary. The module source
1099
+ * declares their functions; the library sources define them.
1100
+ */
1101
+ libraries?: ModuleLibrarySource[];
1084
1102
  }): Promise<CompilationResult>;
1085
1103
 
1104
+ export interface ModuleLibrarySource {
1105
+ /** Letters, digits, '.', '_', '-'; starts with a letter. */
1106
+ name: string;
1107
+ /** Letters, digits, '.', '_', '-' (e.g. "3.1.2", "vallado-2020"). */
1108
+ version: string;
1109
+ sourceCode: string;
1110
+ /** Default "c". */
1111
+ language?: "c" | "c++";
1112
+ /** NAME or NAME=VALUE, for this library's compile only. */
1113
+ defines?: string[];
1114
+ }
1115
+
1116
+ /**
1117
+ * A shared library object. Its strong global symbols are renamed into
1118
+ * `namespace` (sdm_lib_<name>_<version>_<digest>_, the digest covering its
1119
+ * source, defines, flags and toolchain kind); the module object's references
1120
+ * follow. A flow links each namespace once.
1121
+ */
1122
+ export interface GuestLinkLibrary {
1123
+ name: string;
1124
+ version: string;
1125
+ language: "c" | "c++";
1126
+ namespace: string;
1127
+ sha256: string;
1128
+ objectBytes: Uint8Array;
1129
+ }
1130
+
1131
+ /**
1132
+ * Write a compilation's guest-link files into `dir` (dist/guest-link):
1133
+ * module-link.o, libraries/<name>-<version>-<sha12>.o and metadata.json
1134
+ * (version 1 without libraries, 2 with a `libraries` list). `metadata` adds
1135
+ * fields to metadata.json.
1136
+ */
1137
+ export function writeGuestLinkFiles(
1138
+ compilation: CompilationResult,
1139
+ dir: string,
1140
+ metadata?: Record<string, unknown>,
1141
+ ): Promise<Record<string, unknown>>;
1142
+
1143
+ export interface CompileCacheReport {
1144
+ enabled: boolean;
1145
+ dir: string | null;
1146
+ /** Steps answered from the cache: "module", "manifest", "invoke", "link". */
1147
+ hits: string[];
1148
+ /** Steps that ran the toolchain. */
1149
+ misses: string[];
1150
+ /** Wall time of each step that ran, in ms. */
1151
+ stepMs: Record<string, number>;
1152
+ }
1153
+
1154
+ export function pruneCompileCache(options?: {
1155
+ dir?: string;
1156
+ maxBytes?: number;
1157
+ }): Promise<{ removedEntries: number; removedBytes: number; keptBytes: number }>;
1158
+
1159
+ export function resolveCompileCacheRoot(dir?: string): string;
1160
+
1086
1161
  export function cleanupCompilation(
1087
1162
  result: CompilationResult,
1088
1163
  ): Promise<void>;
1089
1164
 
1165
+ /**
1166
+ * The guest-link object of a compiled module object (module.o): every strong,
1167
+ * global symbol it defines with a C identifier for a name, and every manifest
1168
+ * method id, renamed to `<symbolPrefix><name>` in the object's symbol table.
1169
+ * compileModuleFromSource derives `guestLink.objectBytes` this way from its one
1170
+ * module compile.
1171
+ */
1172
+ export function deriveGuestLinkObject(options: {
1173
+ objectBytes: Uint8Array;
1174
+ pluginId: string;
1175
+ methodIds?: string[];
1176
+ }): {
1177
+ symbolPrefix: string;
1178
+ methodSymbols: Record<string, string>;
1179
+ renamedSymbols: string[];
1180
+ objectBytes: Uint8Array;
1181
+ };
1182
+
1090
1183
  export function protectModuleArtifact(options: {
1091
1184
  manifest: PluginManifest;
1092
1185
  wasmBytes?: Uint8Array;
@@ -19,6 +19,7 @@ import { fileURLToPath } from "node:url";
19
19
 
20
20
  import { createBrowserModuleHarness } from "../host/browserModuleHarness.js";
21
21
  import { loadModule } from "../host/isomorphicLoader.js";
22
+ import { analyzeWasmThreadFeatures } from "../compiler/pthreadArtifactGuard.js";
22
23
 
23
24
  export const STANDALONE_RUNTIME_KINDS = Object.freeze(["browser", "wasmedge"]);
24
25
 
@@ -40,6 +41,15 @@ export function isWasmEdgeAvailable() {
40
41
  return result.status === 0;
41
42
  }
42
43
 
44
+ function artifactNeedsThreads(wasmPath) {
45
+ try {
46
+ const features = analyzeWasmThreadFeatures(new Uint8Array(fs.readFileSync(wasmPath)));
47
+ return features.hasSharedMemory || features.hasWasiThreadSpawnImport;
48
+ } catch {
49
+ return false;
50
+ }
51
+ }
52
+
43
53
  export async function createStandaloneHarness(runtimeKind, wasmPath, options = {}) {
44
54
  const resolvedWasmPath = resolveWasmPath(wasmPath);
45
55
  if (runtimeKind === "browser") {
@@ -70,7 +80,11 @@ export async function createStandaloneHarness(runtimeKind, wasmPath, options = {
70
80
  wasmSource: resolvedWasmPath,
71
81
  runtimeKind: "wasmedge",
72
82
  surface: options.surface ?? "command",
73
- enableThreads: options.enableThreads ?? false,
83
+ // Unset, WasmEdge's threads proposal follows the artifact: on for a
84
+ // shared memory (wasi-threads, and wasi-sequential on
85
+ // wasm32-wasip1-threads) or a wasi thread-spawn import, which WasmEdge
86
+ // refuses to instantiate without it; off otherwise.
87
+ enableThreads: options.enableThreads ?? artifactNeedsThreads(resolvedWasmPath),
74
88
  wasmEdgeBinary: options.wasmEdgeBinary,
75
89
  wasmEdgeRunnerBinary: options.wasmEdgeRunnerBinary,
76
90
  args: options.args,