space-data-module-sdk 0.9.2 → 0.9.4

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.
@@ -43,6 +43,7 @@ import {
43
43
  import {
44
44
  ADAPTER_CAPABILITIES,
45
45
  ADAPTER_OPERATIONS,
46
+ IPFS_ADAPTER_OPERATIONS,
46
47
  callServiceAdapter,
47
48
  normalizePluginConfig,
48
49
  resolveServiceAdapters,
@@ -112,6 +113,7 @@ export const NodeHostSupportedOperations = Object.freeze([
112
113
  "ipfs.invoke",
113
114
  "ipfs.add",
114
115
  "ipfs.cat",
116
+ ...IPFS_ADAPTER_OPERATIONS,
115
117
  "protocol_handle.register",
116
118
  "protocol_handle.unregister",
117
119
  "protocol_dial.dial",
@@ -2077,6 +2079,12 @@ export class NodeHost {
2077
2079
  this.#withCapability("ipfs", "ipfs.cat", async () =>
2078
2080
  invokeAdapterMethod(this._ipfsAdapter, "cat", params, "ipfs"),
2079
2081
  ),
2082
+ // ls, pin_add, pin_rm, pin_ls, dag_get, id, swarm_peers, name_resolve, name_publish, pubsub_publish
2083
+ ...Object.fromEntries(IPFS_ADAPTER_OPERATIONS.map((operation) => [operation.slice(5), async (params = {}) =>
2084
+ this.#withCapability("ipfs", operation, async () =>
2085
+ invokeAdapterMethod(this._ipfsAdapter, operation.slice(5), params, "ipfs"),
2086
+ ),
2087
+ ])),
2080
2088
  });
2081
2089
 
2082
2090
  this.protocolHandle = Object.freeze({
@@ -2392,6 +2400,9 @@ export class NodeHost {
2392
2400
  if (ADAPTER_OPERATIONS[normalized]) {
2393
2401
  return this.serveAdapterOperation(normalized, params);
2394
2402
  }
2403
+ if (IPFS_ADAPTER_OPERATIONS.includes(normalized)) {
2404
+ return this.ipfs[normalized.slice(5)](params);
2405
+ }
2395
2406
  throw new Error(`Unknown Node host operation "${normalized}".`);
2396
2407
  }
2397
2408
  }
@@ -11,7 +11,7 @@ import {
11
11
  encodeSqlValues,
12
12
  } from "../standards/runtimeContracts.js";
13
13
  import * as hostOps from "../generated/runtime/aligned/HostOps_aligned.js";
14
- import { deliverMode, reconcileKind, sandboxWant } from "../generated/runtime/aligned/HostOps_enums.js";
14
+ import { cryptoAlgorithm, deliverMode, reconcileKind, sandboxWant } from "../generated/runtime/aligned/HostOps_enums.js";
15
15
  import { base64ToBytes, bytesToBase64 } from "../utils/encoding.js";
16
16
 
17
17
  const textDecoder = new TextDecoder();
@@ -248,6 +248,58 @@ function pnmEntry(e) {
248
248
  });
249
249
  }
250
250
  const p2pRecords = (v) => (binary(v?.records) ? { records: binary(v.records) } : {});
251
+
252
+ // ---- keyslot, ipfs, pubsub, protocol: the Go node's request maps (bytes as base64) and answers ----------------------
253
+ // the HostOps cryptoAlgorithm enum -> the handlers' algorithm names (the Go node's cryptoAlgorithmNames; "" = default)
254
+ const KEYSLOT_ALGORITHMS = {
255
+ Default: "", Ed25519: "ed25519", Secp256k1: "secp256k1", X25519: "x25519", Sha256: "sha256", Sha512: "sha512", Aes256Gcm: "aes-256-gcm", HkdfSha256: "hkdf-sha256",
256
+ };
257
+ const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
258
+ /**
259
+ * A handler's binary answer (the Go node's bytesOf): bytes (Uint8Array, a typed view, an ArrayBuffer), base64 text or
260
+ * {__type: "bytes", base64}; undefined when it is none of them.
261
+ */
262
+ function answerBytes(v) {
263
+ const b = binary(v);
264
+ if (b) return b;
265
+ const encoded = typeof v === "string" ? v : v && typeof v === "object" && v.__type === "bytes" ? str(v.base64) : undefined;
266
+ if (encoded === undefined || !BASE64.test(encoded)) return undefined;
267
+ return base64ToBytes(encoded);
268
+ }
269
+ /** The bytes as one raw port (the Go node's dataAnswer / fieldBytes): no bytes is a failure. */
270
+ function bytesAnswer(port, field) {
271
+ return (v, { op }) => {
272
+ const value = field === undefined ? v : v && typeof v === "object" && !binary(v) ? v[field] : undefined;
273
+ const bytes = answerBytes(value);
274
+ if (!bytes) throw failed(`${op}: the host answered no ${field ?? "bytes"}`);
275
+ return { raw: { [port]: bytes } };
276
+ };
277
+ }
278
+ /** A raw port's bytes as base64 under `key` when the module sent it (the Go node's rawB64). */
279
+ function rawBase64(request, key, raw, port) {
280
+ if (raw[port] !== undefined) request[key] = bytesToBase64(raw[port]);
281
+ return request;
282
+ }
283
+ const intOf = (v) => { const n = Number(v); return Number.isFinite(n) ? Math.trunc(n) : 0; };
284
+ /** The answer's `field` (a list) as sorted text items (the Go node's listOfText). */
285
+ const textListOf = (field) => (v) => ({ lists: { items: (Array.isArray(v?.[field]) ? v[field] : []).map(str).sort().map((value) => ({ VALUE: value })) } });
286
+ const GO_DURATION_UNITS = { ns: 1e-6, us: 1e-3, "µs": 1e-3, "μs": 1e-3, ms: 1, s: 1000, m: 60_000, h: 3_600_000 };
287
+ /** A Go duration ("1h2m3.5s", "350µs", "-12ms") in milliseconds; 0 when unreadable (time.ParseDuration's error). */
288
+ function goDurationMs(v) {
289
+ const s = str(v);
290
+ if (s === "0") return 0;
291
+ const m = /^([-+]?)((?:(?:\d+\.?\d*|\.\d+)(?:ns|us|µs|μs|ms|s|m|h))+)$/.exec(s);
292
+ if (!m) return 0;
293
+ let total = 0;
294
+ for (const [, n, unit] of m[2].matchAll(/(\d+\.?\d*|\.\d+)(ns|us|µs|μs|ms|s|m|h)/g)) total += Number(n) * GO_DURATION_UNITS[unit];
295
+ return m[1] === "-" ? -total : total;
296
+ }
297
+ /** encoding/json's Marshal of a decoded JSON value: object keys sorted, <, >, & and U+2028 / U+2029 escaped. */
298
+ function goJson(v) {
299
+ const sortKeys = (x) => (Array.isArray(x) ? x.map(sortKeys) : x && typeof x === "object" ? Object.fromEntries(Object.keys(x).sort().map((k) => [k, sortKeys(x[k])])) : x);
300
+ return JSON.stringify(sortKeys(v) ?? null).replace(/[<>&\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
301
+ }
302
+ const objectOf = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {});
251
303
  const p2pRequest = ({ params }) => withDeliver(lower(params), params);
252
304
  const objects = (v) => (Array.isArray(v) ? v.filter((x) => x && typeof x === "object") : []);
253
305
 
@@ -484,6 +536,66 @@ const ADAPTERS = {
484
536
  return { result, raw: binary(serving.stream) ? { stream: binary(serving.stream) } : {} };
485
537
  },
486
538
  },
539
+ // keyslot: the host's crypto oracle takes and answers base64 ({signature} / {plaintext})
540
+ "keyslot.sign": {
541
+ in: ({ params, raw }) => {
542
+ const request = { slotId: str(params?.SLOT_ID) };
543
+ const algorithm = KEYSLOT_ALGORITHMS[enumName(cryptoAlgorithm, params?.ALGORITHM)];
544
+ if (algorithm) request.algorithm = algorithm;
545
+ return rawBase64(request, "payload", raw, "payload");
546
+ },
547
+ out: bytesAnswer("data", "signature"),
548
+ },
549
+ "keyslot.unwrap": {
550
+ in: ({ params, raw }) => {
551
+ const request = { slotId: str(params?.SLOT_ID) };
552
+ rawBase64(request, "ephemeralPublicKey", raw, "ephemeral_public_key");
553
+ rawBase64(request, "nonce", raw, "nonce");
554
+ return rawBase64(request, "ciphertext", raw, "ciphertext");
555
+ },
556
+ out: bytesAnswer("data", "plaintext"),
557
+ },
558
+ // protocol: {target, protocolId, timeoutMs, payloadBase64} -> the peer's answer bytes
559
+ "protocol.request": {
560
+ in: ({ params, raw }) => {
561
+ const request = { target: str(params?.TARGET), protocolId: str(params?.PROTOCOL_ID) };
562
+ if (Number(params?.TIMEOUT_MS) > 0) request.timeoutMs = Number(params.TIMEOUT_MS);
563
+ return rawBase64(request, "payloadBase64", raw, "payload");
564
+ },
565
+ out: bytesAnswer("data"),
566
+ },
567
+ "pubsub.list_topics": { in: () => ({}), out: textListOf("topics") },
568
+ // ipfs: the record's set fields as lower-case keys; Kubo's answers ({Objects: [{Links}]}, {Pins}, {Keys}, {ID, ...})
569
+ "ipfs.cat": { in: ({ params }) => lower(params), out: bytesAnswer("data") },
570
+ // the DAG node as Kubo encodes it (dag-json); bytes pass as they are
571
+ "ipfs.dag_get": { in: ({ params }) => lower(params), out: (v) => ({ raw: { data: binary(v) ?? textEncoder.encode(goJson(v)) } }) },
572
+ "ipfs.ls": {
573
+ in: ({ params }) => lower(params),
574
+ out: (v) => ({ lists: { links: objects(objectOf(v).Objects).flatMap((o) => objects(o.Links)).map((l) => fit("IpfsLink", { NAME: str(l.Name), CID: str(l.Hash), SIZE: intOf(l.Size), TYPE: intOf(l.Type) })) } }),
575
+ },
576
+ "ipfs.pin_add": { in: ({ params }) => lower(params), out: textListOf("Pins") },
577
+ "ipfs.pin_rm": { in: ({ params }) => lower(params), out: textListOf("Pins") },
578
+ "ipfs.pin_ls": {
579
+ in: ({ params }) => lower(params),
580
+ out: (v) => {
581
+ const keys = objectOf(objectOf(v).Keys);
582
+ return { lists: { pins: Object.keys(keys).sort().map((cid) => fit("IpfsPin", { CID: cid, TYPE: str(objectOf(keys[cid]).Type) })) } };
583
+ },
584
+ },
585
+ "ipfs.name_resolve": { in: ({ params }) => lower(params), out: (v) => ({ result: fit("IpfsResult", { VALUE: str(v?.Path) }) }) },
586
+ "ipfs.name_publish": { in: ({ params }) => lower(params), out: (v) => ({ result: fit("IpfsResult", { NAME: str(v?.Name), VALUE: str(v?.Value) }) }) },
587
+ "ipfs.id": {
588
+ in: () => ({}),
589
+ out: (v) => ({
590
+ result: fit("IpfsResult", { NAME: str(v?.ID), VALUE: str(v?.PublicKey), AGENT_VERSION: str(v?.AgentVersion), PROTOCOL_VERSION: str(v?.ProtocolVersion) }),
591
+ lists: { addresses: (Array.isArray(v?.Addresses) ? v.Addresses : []).map((a) => ({ VALUE: str(a) })) },
592
+ }),
593
+ },
594
+ "ipfs.swarm_peers": {
595
+ in: () => ({}),
596
+ out: (v) => ({ lists: { peers: objects(objectOf(v).Peers).map((p) => fit("IpfsSwarmPeer", { PEER_ID: str(p.Peer), ADDRESS: str(p.Addr), LATENCY_MS: goDurationMs(p.Latency) })) } }),
597
+ },
598
+ "ipfs.pubsub_publish": { in: ({ params, raw }) => rawBase64({ topic: str(params?.TOPIC) }, "base64", raw, "data"), out: () => ({}) },
487
599
  // node status and activity
488
600
  "node_status_read.status": {
489
601
  in: () => ({}),
@@ -133,7 +133,8 @@ function entryOf(key, value) {
133
133
  else throw new Error(`ModuleConfig: ${key} has no config value kind (${value === null ? "null" : typeof value})`);
134
134
  return e;
135
135
  }
136
- const entriesOf = (object) => Object.keys(object || {}).filter((k) => object[k] !== undefined).sort().map((k) => entryOf(k, object[k]));
136
+ // A key whose value is null or undefined is left out, as the Go node does: "not configured".
137
+ const entriesOf = (object) => Object.keys(object || {}).filter((k) => object[k] !== undefined && object[k] !== null).sort().map((k) => entryOf(k, object[k]));
137
138
  function valueOf(e) {
138
139
  switch (e.KIND) {
139
140
  case configValueKind.String: return e.STRING_VALUE || "";
@@ -34,7 +34,6 @@ RUN set -eux; \
34
34
  ENV PATH="/opt/wasmedge/bin:${PATH}" \
35
35
  LD_LIBRARY_PATH="/opt/wasmedge/lib64:/opt/wasmedge/lib"
36
36
 
37
- COPY native/wasmedge_wasi_threads_runner.c /tmp/sdm-wasi-threads-runner.c
38
37
  # The SDN WasmEdge 0.16.4 patch series, byte-identical to SDN's testdata/
39
38
  # (sdn-server/internal/wasmrt/SUBSTRATE.md): 01-atomic-wait, 02-stop-token,
40
39
  # 03-fault-jmp, 04-atomic-memarg-offset. Order matters (02 and 04 both touch
@@ -69,6 +68,9 @@ RUN git clone --depth 1 --branch 0.16.4 https://github.com/WasmEdge/WasmEdge.git
69
68
  && cmake --install /tmp/wasmedge-build \
70
69
  && rm -rf /tmp/wasmedge-source /tmp/wasmedge-build \
71
70
  /tmp/01-atomic-wait.patch /tmp/02-stop-token.patch /tmp/03-fault-jmp.patch /tmp/04-atomic-memarg-offset.patch
71
+ # The runner (thread spawn + the hostcall bridge) last, so a runner change
72
+ # reuses the patched WasmEdge build layer above.
73
+ COPY native/wasmedge_wasi_threads_runner.c /tmp/sdm-wasi-threads-runner.c
72
74
  RUN cc /tmp/sdm-wasi-threads-runner.c -std=c11 -O2 -pthread -Wall -Wextra -Werror \
73
75
  -I/opt/sdm-wasmedge/include -L/opt/sdm-wasmedge/lib64 -L/opt/sdm-wasmedge/lib -lwasmedge \
74
76
  -Wl,--disable-new-dtags,-rpath,/opt/sdm-wasmedge/lib64,-rpath,/opt/sdm-wasmedge/lib \
@@ -2,6 +2,11 @@
2
2
  // CLI enables atomics but does not implement wasi.thread-spawn. Like the SDN
3
3
  // Go host, use a fresh instance per worker, shared memory, and ONE executor:
4
4
  // atomic.wait/notify waiters belong to the executor in this runtime revision.
5
+ // It also serves the typed hostcall bridge (space_data_module_host.call /
6
+ // response_len / read_response) of a module that imports it, single-threaded
7
+ // or not: the parity orchestrator stages the $PIV answers (plugin.getConfig ->
8
+ // the case's ModuleConfig, every other operation STATUS FAILED "unsupported"),
9
+ // encoded by the SDK's own encoder, and this runner replays them.
5
10
  #define _POSIX_C_SOURCE 200809L
6
11
  #include <wasmedge/wasmedge.h>
7
12
  #include <pthread.h>
@@ -31,6 +36,15 @@ typedef struct {
31
36
  bool exited;
32
37
  } Threads;
33
38
 
39
+ typedef struct {
40
+ uint8_t *data;
41
+ uint32_t size;
42
+ } Bytes;
43
+
44
+ // The staged answers; each thread reads back the answer to its own last call.
45
+ static Bytes hostcall_config, hostcall_unsupported;
46
+ static _Thread_local const Bytes *hostcall_response;
47
+
34
48
  static WasmEdge_String name(const char *s) {
35
49
  return WasmEdge_StringWrap(s, (uint32_t)strlen(s));
36
50
  }
@@ -150,6 +164,121 @@ static WasmEdge_ModuleInstanceContext *memory_import(Threads *g) {
150
164
  return env;
151
165
  }
152
166
 
167
+ static Bytes read_answer(const char *path) {
168
+ FILE *file = fopen(path, "rb");
169
+ if (!file) { fprintf(stderr, "cannot open hostcall answer %s\n", path); exit(2); }
170
+ Bytes bytes = {0};
171
+ if (fseek(file, 0, SEEK_END) != 0) exit(2);
172
+ long size = ftell(file);
173
+ if (size <= 0 || size > (1L << 30) || fseek(file, 0, SEEK_SET) != 0) { fprintf(stderr, "bad hostcall answer %s\n", path); exit(2); }
174
+ bytes.size = (uint32_t)size;
175
+ bytes.data = malloc(bytes.size);
176
+ if (!bytes.data || fread(bytes.data, 1, bytes.size, file) != bytes.size) { fprintf(stderr, "cannot read hostcall answer %s\n", path); exit(2); }
177
+ fclose(file);
178
+ return bytes;
179
+ }
180
+
181
+ // call(op_ptr, op_len, payload_ptr, payload_len) -> status: the answer is chosen by the operation name.
182
+ static WasmEdge_Result hostcall_call(void *data,
183
+ const WasmEdge_CallingFrameContext *frame, const WasmEdge_Value *in,
184
+ WasmEdge_Value *out) {
185
+ (void)data;
186
+ static const char config_op[] = "plugin.getConfig";
187
+ WasmEdge_MemoryInstanceContext *memory = WasmEdge_CallingFrameGetMemoryInstance(frame, 0);
188
+ uint32_t op_ptr = (uint32_t)WasmEdge_ValueGetI32(in[0]);
189
+ uint32_t op_len = (uint32_t)WasmEdge_ValueGetI32(in[1]);
190
+ const uint8_t *op = memory && op_len ? WasmEdge_MemoryInstanceGetPointerConst(memory, op_ptr, op_len) : NULL;
191
+ bool config = op && op_len == sizeof(config_op) - 1 && memcmp(op, config_op, op_len) == 0;
192
+ hostcall_response = config ? &hostcall_config : &hostcall_unsupported;
193
+ out[0] = WasmEdge_ValueGenI32(0);
194
+ return WasmEdge_Result_Success;
195
+ }
196
+
197
+ static WasmEdge_Result hostcall_response_len(void *data,
198
+ const WasmEdge_CallingFrameContext *frame, const WasmEdge_Value *in,
199
+ WasmEdge_Value *out) {
200
+ (void)data; (void)frame; (void)in;
201
+ out[0] = WasmEdge_ValueGenI32(hostcall_response ? (int32_t)hostcall_response->size : 0);
202
+ return WasmEdge_Result_Success;
203
+ }
204
+
205
+ // read_response(dst_ptr, dst_len) -> bytes copied (out of bounds traps, as in the JS bridge).
206
+ static WasmEdge_Result hostcall_read_response(void *data,
207
+ const WasmEdge_CallingFrameContext *frame, const WasmEdge_Value *in,
208
+ WasmEdge_Value *out) {
209
+ (void)data;
210
+ WasmEdge_MemoryInstanceContext *memory = WasmEdge_CallingFrameGetMemoryInstance(frame, 0);
211
+ int32_t dst_len = WasmEdge_ValueGetI32(in[1]);
212
+ uint32_t size = hostcall_response ? hostcall_response->size : 0;
213
+ if (dst_len < 0) return WasmEdge_Result_Fail;
214
+ uint32_t n = (uint32_t)dst_len < size ? (uint32_t)dst_len : size;
215
+ if (n) {
216
+ if (!memory) return WasmEdge_Result_Fail;
217
+ WasmEdge_Result result = WasmEdge_MemoryInstanceSetData(memory, hostcall_response->data, (uint32_t)WasmEdge_ValueGetI32(in[0]), n);
218
+ if (!WasmEdge_ResultOK(result)) return result;
219
+ }
220
+ out[0] = WasmEdge_ValueGenI32((int32_t)n);
221
+ return WasmEdge_Result_Success;
222
+ }
223
+
224
+ static WasmEdge_Result hostcall_clear_response(void *data,
225
+ const WasmEdge_CallingFrameContext *frame, const WasmEdge_Value *in,
226
+ WasmEdge_Value *out) {
227
+ (void)data; (void)frame; (void)in;
228
+ hostcall_response = NULL;
229
+ out[0] = WasmEdge_ValueGenI32(0);
230
+ return WasmEdge_Result_Success;
231
+ }
232
+
233
+ static WasmEdge_Result hostcall_last_status(void *data,
234
+ const WasmEdge_CallingFrameContext *frame, const WasmEdge_Value *in,
235
+ WasmEdge_Value *out) {
236
+ (void)data; (void)frame; (void)in;
237
+ out[0] = WasmEdge_ValueGenI32(0);
238
+ return WasmEdge_Result_Success;
239
+ }
240
+
241
+ static void add_host_function(WasmEdge_ModuleInstanceContext *module, const char *field,
242
+ uint32_t params, WasmEdge_HostFunc_t function) {
243
+ WasmEdge_ValType i32[4] = {WasmEdge_ValTypeGenI32(), WasmEdge_ValTypeGenI32(),
244
+ WasmEdge_ValTypeGenI32(), WasmEdge_ValTypeGenI32()};
245
+ WasmEdge_FunctionTypeContext *type = WasmEdge_FunctionTypeCreate(i32, params, i32, 1);
246
+ WasmEdge_FunctionInstanceContext *instance = WasmEdge_FunctionInstanceCreate(type, function, NULL, 0);
247
+ WasmEdge_FunctionTypeDelete(type);
248
+ if (!instance) exit(1);
249
+ WasmEdge_ModuleInstanceAddFunction(module, name(field), instance);
250
+ }
251
+
252
+ // The bridge, registered when the module imports space_data_module_host; NULL otherwise.
253
+ static WasmEdge_ModuleInstanceContext *hostcall_import(Threads *g,
254
+ const char *config_path, const char *unsupported_path) {
255
+ uint32_t count = WasmEdge_ASTModuleListImportsLength(g->ast);
256
+ const WasmEdge_ImportTypeContext **imports = calloc(count, sizeof(*imports));
257
+ if (count && !imports) exit(1);
258
+ WasmEdge_ASTModuleListImports(g->ast, imports, count);
259
+ bool bridged = false;
260
+ for (uint32_t i = 0; i < count; ++i) {
261
+ if (WasmEdge_StringIsEqual(WasmEdge_ImportTypeGetModuleName(imports[i]), name("space_data_module_host"))) bridged = true;
262
+ }
263
+ free(imports);
264
+ if (!bridged) return NULL;
265
+ if (!config_path || !unsupported_path) {
266
+ fprintf(stderr, "module imports space_data_module_host: pass --sdm-hostcall-config and --sdm-hostcall-unsupported\n");
267
+ exit(2);
268
+ }
269
+ hostcall_config = read_answer(config_path);
270
+ hostcall_unsupported = read_answer(unsupported_path);
271
+ WasmEdge_ModuleInstanceContext *host = WasmEdge_ModuleInstanceCreate(name("space_data_module_host"));
272
+ if (!host) exit(1);
273
+ add_host_function(host, "call", 4, hostcall_call);
274
+ add_host_function(host, "response_len", 0, hostcall_response_len);
275
+ add_host_function(host, "read_response", 2, hostcall_read_response);
276
+ add_host_function(host, "clear_response", 0, hostcall_clear_response);
277
+ add_host_function(host, "last_status_code", 0, hostcall_last_status);
278
+ require_result("register hostcall bridge", WasmEdge_ExecutorRegisterImport(g->executor, g->store, host));
279
+ return host;
280
+ }
281
+
153
282
  // Direct calls use the same PIV request/response bytes as commands. Stage the
154
283
  // request through the public allocator, then monitor the direct call with the
155
284
  // same worker-group lifecycle as _start. No guest ABI is reimplemented. The
@@ -217,7 +346,7 @@ int main(int argc, char **argv) {
217
346
  return 2;
218
347
  }
219
348
  if (argc == 2 && strcmp(argv[1], "--version") == 0) {
220
- printf("wasmedge version %s\nsdm-wasi-threads-runner 1\n",
349
+ printf("wasmedge version %s\nsdm-wasi-threads-runner 2\n",
221
350
  WasmEdge_VersionGet());
222
351
  return 0;
223
352
  }
@@ -229,11 +358,20 @@ int main(int argc, char **argv) {
229
358
  uint32_t env_count = 0;
230
359
  bool stats = false;
231
360
  bool force_direct = false;
361
+ const char *hostcall_config_path = NULL, *hostcall_unsupported_path = NULL;
232
362
  int first = 1;
233
363
  for (; first < argc; ++first) {
234
364
  if (strcmp(argv[first], "--enable-threads") == 0) continue;
235
365
  if (strcmp(argv[first], "--sdm-thread-stats") == 0) { stats = true; continue; }
236
366
  if (strcmp(argv[first], "--sdm-direct") == 0) { force_direct = true; continue; }
367
+ if (strcmp(argv[first], "--sdm-hostcall-config") == 0 && first + 1 < argc) {
368
+ hostcall_config_path = argv[++first];
369
+ continue;
370
+ }
371
+ if (strcmp(argv[first], "--sdm-hostcall-unsupported") == 0 && first + 1 < argc) {
372
+ hostcall_unsupported_path = argv[++first];
373
+ continue;
374
+ }
237
375
  if (strcmp(argv[first], "--env") == 0 && first + 1 < argc) {
238
376
  envs[env_count++] = argv[++first];
239
377
  continue;
@@ -241,7 +379,7 @@ int main(int argc, char **argv) {
241
379
  break;
242
380
  }
243
381
  if (first >= argc || argv[first][0] == '-') {
244
- fprintf(stderr, "usage: %s [--sdm-direct] [--env NAME=VALUE] module.wasm [args...]\n", argv[0]);
382
+ fprintf(stderr, "usage: %s [--sdm-direct] [--sdm-hostcall-config FILE --sdm-hostcall-unsupported FILE] [--env NAME=VALUE] module.wasm [args...]\n", argv[0]);
245
383
  free(envs);
246
384
  return 2;
247
385
  }
@@ -262,6 +400,7 @@ int main(int argc, char **argv) {
262
400
  require_result("register WASI", WasmEdge_ExecutorRegisterImport(
263
401
  g.executor, g.store, wasi));
264
402
  WasmEdge_ModuleInstanceContext *env = memory_import(&g);
403
+ WasmEdge_ModuleInstanceContext *host = hostcall_import(&g, hostcall_config_path, hostcall_unsupported_path);
265
404
  WasmEdge_ModuleInstanceContext *threads = WasmEdge_ModuleInstanceCreate(name("wasi"));
266
405
  WasmEdge_ValType i32 = WasmEdge_ValTypeGenI32();
267
406
  WasmEdge_FunctionTypeContext *type = WasmEdge_FunctionTypeCreate(&i32, 1, &i32, 1);
@@ -341,6 +480,9 @@ int main(int argc, char **argv) {
341
480
  WasmEdge_ModuleInstanceDelete(instance);
342
481
  WasmEdge_ModuleInstanceDelete(threads);
343
482
  if (env) WasmEdge_ModuleInstanceDelete(env);
483
+ if (host) WasmEdge_ModuleInstanceDelete(host);
484
+ free(hostcall_config.data);
485
+ free(hostcall_unsupported.data);
344
486
  WasmEdge_ModuleInstanceDelete(wasi);
345
487
  WasmEdge_StoreDelete(g.store);
346
488
  WasmEdge_ASTModuleDelete(g.ast);
@@ -7,12 +7,13 @@
7
7
  * realities, which is exactly what this lane exists to catch.
8
8
  *
9
9
  * Protocol with the lane server (same origin):
10
- * GET /plan -> {threadEnvVar, cases:[{id, stdinBase64, env, args, threadCounts}]}
10
+ * GET /plan -> {threadEnvVar, cases:[{id, stdinBase64, env, args, threadCounts, config}]}
11
11
  * GET /module.wasm -> the ONE isomorphic artifact
12
12
  * POST /done -> {runs:[...]} on completion or {fatal} on runner failure
13
13
  */
14
14
 
15
15
  import { createBrowserModuleHarness } from "../host/browserModuleHarness.js";
16
+ import { parityHostcallDispatch } from "./parityHostcalls.js";
16
17
 
17
18
  const OK = "ok";
18
19
  const GUEST_ERROR = "guest-error";
@@ -107,6 +108,9 @@ export async function runParityPlanInBrowser({ baseUrl = "" } = {}) {
107
108
  maxThreads: threadCount,
108
109
  wasiThreadWorkerUrl: new URL("/wasi-thread-worker.js", globalThis.location.href).href,
109
110
  args: planCase.args,
111
+ // the hostcall bridge (an artifact that imports it): plugin.getConfig answers the case's config, any other
112
+ // operation is unsupported - the answers the WasmEdge lanes' runner replays
113
+ hostcallDispatch: parityHostcallDispatch(planCase.config),
110
114
  env: {
111
115
  ...planCase.env,
112
116
  [plan.threadEnvVar]: String(threadCount),
@@ -162,6 +162,14 @@ function normalizeEnv(env, label) {
162
162
  return normalized;
163
163
  }
164
164
 
165
+ function normalizeConfig(config, label) {
166
+ if (config === undefined || config === null) return null;
167
+ if (typeof config !== "object" || Array.isArray(config)) {
168
+ throw new Error(`Parity fixture ${label}: config must be an object.`);
169
+ }
170
+ return Object.freeze(structuredClone(config));
171
+ }
172
+
165
173
  function normalizeExpect(expect, label) {
166
174
  if (expect === undefined || expect === null) return null;
167
175
  const value = String(expect);
@@ -208,9 +216,14 @@ function normalizeThreadCounts(threadCounts, label) {
208
216
  * id,
209
217
  * request?: {methodId, inputs:[{portId, payloadFile|payloadBase64|payloadHex|payloadUtf8, typeRef?}], ...},
210
218
  * stdinFile? | stdinBase64? | stdinHex? | stdinUtf8?,
211
- * env?, args?, expect?: "ok"|"guest-error"|"trap", threadCounts?
212
- * }]
219
+ * env?, args?, expect?: "ok"|"guest-error"|"trap", threadCounts?,
220
+ * config?
221
+ * }],
222
+ * config?
213
223
  * }
224
+ *
225
+ * config (an object; the case's replaces the fixture's, default {}) is what
226
+ * the module's plugin.getConfig hostcall answers in every lane.
214
227
  */
215
228
  export async function normalizeParityFixture(fixture, options = {}) {
216
229
  if (!fixture || typeof fixture !== "object") {
@@ -222,6 +235,7 @@ export async function normalizeParityFixture(fixture, options = {}) {
222
235
  const fixtureThreadCounts =
223
236
  normalizeThreadCounts(fixture.threadCounts, name) ?? DEFAULT_THREAD_COUNTS;
224
237
  const fixtureEnv = normalizeEnv(fixture.env, name);
238
+ const fixtureConfig = normalizeConfig(fixture.config, name) ?? {};
225
239
  const fixtureArgs = Array.isArray(fixture.args)
226
240
  ? fixture.args.map(String)
227
241
  : [];
@@ -281,6 +295,7 @@ export async function normalizeParityFixture(fixture, options = {}) {
281
295
  Array.isArray(caseSpec.args) ? caseSpec.args.map(String) : fixtureArgs,
282
296
  ),
283
297
  expect: normalizeExpect(caseSpec.expect, label),
298
+ config: normalizeConfig(caseSpec.config, label) ?? fixtureConfig,
284
299
  threadCounts:
285
300
  normalizeThreadCounts(caseSpec.threadCounts, label) ??
286
301
  fixtureThreadCounts,
@@ -0,0 +1,40 @@
1
+ // The typed hostcall bridge (space_data_module_host.call / response_len / read_response, src/host/cpp/typedHostcall.hpp)
2
+ // as every parity lane serves it: plugin.getConfig answers the case's config as one ModuleConfig on raw "config" - the
3
+ // answer the SDK JS hosts give (typedDispatch.js) - and every other operation a STATUS FAILED "unsupported" $PIV
4
+ // answer. The browser lane dispatches through answerTypedHostCall; the WasmEdge lanes' runner replays these bytes,
5
+ // encoded here by the SDK's own encoder and staged beside the module.
6
+ import { DEFAULT_HOSTCALL_IMPORT_MODULE } from "../host/abi.js";
7
+ import { hostcallErrorCode, typedResultOf } from "../host/typedDispatch.js";
8
+ import { encodeHostCallResult } from "../standards/runtimeContracts.js";
9
+
10
+ export const PARITY_HOSTCALL_MODULE = DEFAULT_HOSTCALL_IMPORT_MODULE;
11
+ export const PARITY_UNSUPPORTED_MESSAGE = "the parity harness serves only plugin.getConfig";
12
+ /** The staged answers' file names (the WasmEdge runner's --sdm-hostcall-config / --sdm-hostcall-unsupported). */
13
+ export const PARITY_HOSTCALL_FILES = Object.freeze({ config: "sdm-hostcall-config.piv", unsupported: "sdm-hostcall-unsupported.piv" });
14
+
15
+ const unsupported = () => Object.assign(new Error(PARITY_UNSUPPORTED_MESSAGE), { hostcallCode: "unsupported" });
16
+
17
+ /** Whether a compiled module imports the hostcall bridge. */
18
+ export function importsHostcallBridge(wasmModule) {
19
+ return WebAssembly.Module.imports(wasmModule).some((entry) => entry.module === PARITY_HOSTCALL_MODULE);
20
+ }
21
+
22
+ /** The bridge's dispatch for one case (the browser lane): plugin.getConfig -> the config; anything else unsupported. */
23
+ export function parityHostcallDispatch(config) {
24
+ return (operation) => {
25
+ if (operation === "plugin.getConfig") return config ?? {};
26
+ throw unsupported();
27
+ };
28
+ }
29
+
30
+ /** The $PIV answers the WasmEdge runner replays for one case: {config, unsupported} bytes. */
31
+ export function encodeParityHostcallAnswers(config) {
32
+ const failure = (error) => encodeHostCallResult({ ok: false, error: { code: hostcallErrorCode(error), message: String(error?.message ?? error) } });
33
+ let answer;
34
+ try {
35
+ answer = encodeHostCallResult({ ok: true, op: "plugin.getConfig", ...typedResultOf({ op: "plugin.getConfig" }, config ?? {}) });
36
+ } catch (error) {
37
+ answer = failure(error);
38
+ }
39
+ return { config: answer, unsupported: failure(unsupported()) };
40
+ }
@@ -32,6 +32,7 @@ import { ExitClass, assertWasmEdgeVersionMatchesPin } from "./parityHarness.js";
32
32
  import { normalizeWasmEdgeOutcome } from "./wasmedgeOutput.js";
33
33
  import { isWasiThreadsModule } from "../host/wasiThreadHost.js";
34
34
  import { resolveWasmEdgeWasiThreadsRunner } from "./buildWasmEdgeRunner.js";
35
+ import { PARITY_HOSTCALL_FILES, encodeParityHostcallAnswers, importsHostcallBridge } from "./parityHostcalls.js";
35
36
 
36
37
  const execFile = promisify(execFileCallback);
37
38
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -134,9 +135,9 @@ function wasmedgeInvocationArgs(planCase, plan, threadCount) {
134
135
  // direct surface of an artifact with a command entry; the WasmEdge CLI runs
135
136
  // `_start` or nothing, so a direct-surface comparison on it would silently
136
137
  // compare two different surfaces.
137
- function surfaceArgs(context, threaded, lane) {
138
+ function surfaceArgs(context, useRunner, lane) {
138
139
  if (context.surface !== "direct") return [];
139
- if (!threaded) {
140
+ if (!useRunner) {
140
141
  throw new Error(
141
142
  `${lane}: the WasmEdge CLI serves only the command surface of a single-thread artifact; ` +
142
143
  "it cannot take part in a direct-surface parity run.",
@@ -145,6 +146,24 @@ function surfaceArgs(context, threaded, lane) {
145
146
  return ["--sdm-direct"];
146
147
  }
147
148
 
149
+ // How a WasmEdge lane runs the artifact. The plain CLI provides no host imports,
150
+ // so an artifact that imports the hostcall bridge (space_data_module_host) runs
151
+ // on the SDK runner too, threaded or not; the runner replays the staged answers.
152
+ async function wasmEdgeArtifact(context) {
153
+ const wasmModule = await WebAssembly.compile(context.loadableBytes ?? context.wasmBytes);
154
+ const threaded = isWasiThreadsModule(wasmModule);
155
+ const bridged = importsHostcallBridge(wasmModule);
156
+ return { threaded, bridged, useRunner: threaded || bridged };
157
+ }
158
+
159
+ // Stage the case's hostcall answers beside the module; the runner flags that name them.
160
+ async function stageHostcallAnswers(workdir, planCase) {
161
+ const answers = encodeParityHostcallAnswers(planCase.config ?? {});
162
+ await writeFile(path.join(workdir, PARITY_HOSTCALL_FILES.config), answers.config);
163
+ await writeFile(path.join(workdir, PARITY_HOSTCALL_FILES.unsupported), answers.unsupported);
164
+ return ["--sdm-hostcall-config", PARITY_HOSTCALL_FILES.config, "--sdm-hostcall-unsupported", PARITY_HOSTCALL_FILES.unsupported];
165
+ }
166
+
148
167
  async function stageModuleWorkdir(context, label) {
149
168
  const workdir = await mkdtemp(path.join(os.tmpdir(), `sdm-parity-${label}-`));
150
169
  // Stage the canonical loadable bytes (publication records stripped by the
@@ -179,8 +198,8 @@ export async function resolveWasmEdgeBinary(context = {}) {
179
198
  }
180
199
 
181
200
  export async function runNativeWasmEdgeLane(context) {
182
- const threaded = isWasiThreadsModule(await WebAssembly.compile(context.loadableBytes ?? context.wasmBytes));
183
- const binary = threaded
201
+ const { threaded, bridged, useRunner } = await wasmEdgeArtifact(context);
202
+ const binary = useRunner
184
203
  ? await resolveWasmEdgeWasiThreadsRunner(context)
185
204
  : await resolveWasmEdgeBinary(context);
186
205
  let versionOutput;
@@ -198,16 +217,18 @@ export async function runNativeWasmEdgeLane(context) {
198
217
  `native binary ${binary}`,
199
218
  );
200
219
 
201
- const directArgs = surfaceArgs(context, threaded, "native WasmEdge lane");
220
+ const directArgs = surfaceArgs(context, useRunner, "native WasmEdge lane");
202
221
  const workdir = await stageModuleWorkdir(context, "native");
203
222
  const runs = [];
204
223
  try {
205
224
  for (const planCase of context.plan.cases) {
225
+ const hostcallArgs = bridged ? await stageHostcallAnswers(workdir, planCase) : [];
206
226
  for (const threadCount of planCase.threadCounts) {
207
227
  const outcome = await spawnWithStdin(
208
228
  binary,
209
229
  [...(threaded ? ["--sdm-thread-stats"] : []),
210
230
  ...directArgs,
231
+ ...hostcallArgs,
211
232
  ...wasmedgeInvocationArgs(planCase, context.plan, threadCount)],
212
233
  {
213
234
  cwd: workdir,
@@ -295,8 +316,8 @@ export async function ensureDockerParityImage(context) {
295
316
  }
296
317
 
297
318
  export async function runDockerWasmEdgeLane(context) {
298
- const threaded = isWasiThreadsModule(await WebAssembly.compile(context.loadableBytes ?? context.wasmBytes));
299
- if (threaded) context = { ...context, pin: { ...context.pin, dockerImage: context.pin.dockerRunnerImage } };
319
+ const { threaded, bridged, useRunner } = await wasmEdgeArtifact(context);
320
+ if (useRunner) context = { ...context, pin: { ...context.pin, dockerImage: context.pin.dockerRunnerImage } };
300
321
  const dockerBinary = context.dockerBinary ?? "docker";
301
322
  try {
302
323
  await execFile(dockerBinary, ["--version"]);
@@ -305,13 +326,14 @@ export async function runDockerWasmEdgeLane(context) {
305
326
  `docker WasmEdge lane: cannot execute "${dockerBinary}" (${error.message}).`,
306
327
  );
307
328
  }
308
- const directArgs = surfaceArgs(context, threaded, "docker WasmEdge lane");
329
+ const directArgs = surfaceArgs(context, useRunner, "docker WasmEdge lane");
309
330
  const image = await ensureDockerParityImage(context);
310
331
 
311
332
  const workdir = await stageModuleWorkdir(context, "docker");
312
333
  const runs = [];
313
334
  try {
314
335
  for (const planCase of context.plan.cases) {
336
+ const hostcallArgs = bridged ? await stageHostcallAnswers(workdir, planCase) : [];
315
337
  for (const threadCount of planCase.threadCounts) {
316
338
  const dockerArgs = [
317
339
  "run",
@@ -327,11 +349,12 @@ export async function runDockerWasmEdgeLane(context) {
327
349
  if (context.dockerPlatform) {
328
350
  dockerArgs.push("--platform", String(context.dockerPlatform));
329
351
  }
330
- if (threaded) dockerArgs.push("--entrypoint", "/opt/wasmedge/bin/sdm-wasi-threads-runner");
352
+ if (useRunner) dockerArgs.push("--entrypoint", "/opt/wasmedge/bin/sdm-wasi-threads-runner");
331
353
  dockerArgs.push(
332
354
  image,
333
355
  ...(threaded ? ["--sdm-thread-stats"] : []),
334
356
  ...directArgs,
357
+ ...hostcallArgs,
335
358
  ...wasmedgeInvocationArgs(planCase, context.plan, threadCount),
336
359
  );
337
360
  const outcome = await spawnWithStdin(dockerBinary, dockerArgs, {
@@ -422,6 +445,7 @@ function browserPlanPayload(context) {
422
445
  env: planCase.env,
423
446
  args: [MODULE_BASENAME, ...planCase.args],
424
447
  threadCounts: planCase.threadCounts,
448
+ config: planCase.config ?? {},
425
449
  })),
426
450
  });
427
451
  }