Changes
2 changed files (+313/-3)
-
-
@@ -7,9 +7,191 @@ // Version 2.0 at LICENSES/Apache-2.0.txt. You may also obtain a copy of the Apache License, Version// 2.0 at <https://www.apache.org/licenses/LICENSE-2.0> // // SPDX-License-Identifier: 0BSD OR Apache-2.0 // // === // // This example searches Roon Core on computer's subnet then print found one's information on // stdout. (Bun does not have simply write to stderr. console.error forces text color to be red) // // You can run this example by running "bun ./examples/basic.js" from repository root. // You need Bun (JavaScript runtime) and built ".wasm" file generated by "zig build wasm". // // While this works, you should use the official roon-node-api. This is only for demonstration // purpose. // // Unlike basic.zig and basic.c, this example does not retry. import dgram from "node:dgram"; const wasm = Bun.file(new URL("../zig-out/bin/sood.wasm", import.meta.url)); const { instance } = await WebAssembly.instantiate(await wasm.arrayBuffer()); console.log(instance.exports.sood_add(1, 2)); // Using short alias for brevity. const x = instance.exports; const sock = dgram.createSocket({ type: "udp4" }); sock.on("error", err => { console.error(err); }); // As there is no standard for "string" type, every WASM module have to come up with // their own definition. This module represents strings in "address to UTF8 string // and its byte size." Every string getters consists of two functions suffixed with // "_ptr" and "_len". For example, getters for getting "bar" field from "foo" struct // will be "get_foo_bar_ptr(foo_ptr)" and "get_foo_bar_len(foo_ptr)". // // MEMORY: | |'b'|'a'|'z'| | | // ^ ^ // get_foo_bar_ptr (end) // get_foo_bar_len = (end) - get_foo_bar_ptr // // After you know the address and length on the WASM linear memory, converts the byte // array to UTF-8 string with your platform API/programming language. In this JavaScript // example, we're using the standard "TextDecoder" web API for parsing the byte array // (Uint8Array) to JavaScript string (UTF-16). const utf8Decoder = new TextDecoder(); sock.on("message", (msg, { address }) => { // This "dgram" module is of Node.js, hence type of "msg" is non-standard Buffer type. // For compability, we're converting it to the standard Uint8Array. const messageBuffer = new Uint8Array(msg); let responsePtr = null; let bytesPtr = null; try { // In order to pass non-primitive data between WASM host and guest, we need to allocate // space at WASM linear memory then fill-in the data to the allocated space. // Our "sood.wasm" exports[0] internal memory via "exports.memory". // This line calls our allocator and returns the address of the space. // [0] ... Actually LLVM automatically exports the memory object. bytesPtr = x.allocate_bytes(messageBuffer.length); // Once allocated, copy the data byte-to-byte to the WASM linear memory. // This procedure differs by your platform/programming language. const bytesBuffer = new Uint8Array(x.memory.buffer, bytesPtr, messageBuffer.length); bytesBuffer.set(messageBuffer); // Allocate a struct to hold parsed result. Since "sood.wasm" knows how many bytes required // for the struct, we don't have to specify a size. responsePtr = x.allocate_discovery_response(); // Parse "bytesBuffer", which is copy of "messageBuffer" ("msg"), then fill-in data // onto the previously allocated discovery response struct ("allocate_discovery_response"). // If "result" is non-zero (= error), the discovery response struct remains empty. const result = x.parse_discovery_response_into( responsePtr, bytesPtr, messageBuffer.length, ); // "sood.wasm" is not designed to use for reusing allocated space: // don't use pointer returned by allocator functions more than once. // // [DON'T] // const ptr = allocate_discovery_response(); // x.parse_discovery_response_into(ptr, bytes1Ptr, bytes1Len); // x.parse_discovery_response_into(ptr, bytes2Ptr, bytes2Len); // // [DO] // const ptr1 = allocate_discovery_response(); // x.parse_discovery_response_into(ptr1, bytes1Ptr, bytes1Len); // const ptr2 = allocate_discovery_response(); // x.parse_discovery_response_into(ptr2, bytes2Ptr, bytes2Len); // See definition for "WasmResultCode" in "wasm.zig" for each result codes. // Like most of the program, 0 means success. if (result !== 0) { console.log("Non 0 result received:"); // If you don't have dedicated handlings for individual errors, use // "result_code_string_ptr/len" function to get the human readable name for // the error code. console.log(utf8Decoder.decode( new Uint8Array( x.memory.buffer, x.result_code_string_ptr(result), x.result_code_string_len(result), ), )); return; } // "get_discovery_response_*" functions retrieve corresponding fields. const name = utf8Decoder.decode( new Uint8Array( x.memory.buffer, x.get_discovery_response_name_ptr(responsePtr), x.get_discovery_response_name_len(responsePtr), ), ); const displayVersion = utf8Decoder.decode( new Uint8Array( x.memory.buffer, x.get_discovery_response_display_version_ptr(responsePtr), x.get_discovery_response_display_version_len(responsePtr), ), ); const uniqueId = utf8Decoder.decode( new Uint8Array( x.memory.buffer, x.get_discovery_response_unique_id_ptr(responsePtr), x.get_discovery_response_unique_id_len(responsePtr), ), ); console.log(`Name: \t\t${name}`); console.log(`Version: \t${displayVersion}`); console.log(`Unique ID: \t${uniqueId}`); // SOOD message does not include IP address of the Roon Server. You have to use // UDP message's sender IP address. console.log(`Address: \t${address}`); // HTTP port is unsigned 16-bit integer, therefore simply use the returned value. console.log(`HTTP Port: \t${x.get_discovery_response_http_port(responsePtr)}`); sock.close(); } catch (err) { console.error(err); } finally { // Each strings in a parsed data refers to the source bytes, in this example, "bytesBuffer". // Because of this, use should free parsed data (discovery response, message, iterator) first // then the source bytes. if (typeof responsePtr === "number") { x.free_discovery_response(responsePtr); } // Size of bytes are not known in compile time. You have to pass the size. if (typeof bytesPtr === "number") { x.free_bytes(bytesPtr, messageBuffer.length); } } }); const prebuilt = new Uint8Array( x.memory.buffer, x.prebuilt_discovery_query_ptr(), x.prebuilt_discovery_query_len(), ); // Node.js dgram module takes IP address in string form. // If you're using API that takes network byte order 32-bit IP address, just reads // from the address as Uint32 Big Endian. // // const view = new DataView(x.memory.buffer); // const multicastAddr = view.getUint32(x.get_discovery_multicast_ipv4_address(), false); const multicastIpAddr = Array.from( new Uint8Array(x.memory.buffer, x.get_discovery_multicast_ipv4_address(), 4), ).map(n => n.toString(10)).join("."); sock.bind({ port: 0 }, () => { // This is what the official roon-node-api. I don't know how important this is. sock.setMulticastTTL(1); sock.send(prebuilt, 0, prebuilt.length, x.get_discovery_server_udp_port(), multicastIpAddr); });
-
-
-
@@ -11,7 +11,135 @@ //// === // // WebAssembly API. // // This module does not export constants, because Zig has no support for WebAssembly // Globals yet. Exporting const results in a pointer for the value in LLVM and compile // error in self-hosted backend. // <https://github.com/ziglang/zig/issues/4866>. // // For binary size and maintenance cost, WebAssembly API only expose high-level response // parsing API. Low-level APIs such as Message.parse and Message.iterator are not included. export fn sood_add(a: i32, b: i32) i32 { return a + b; const std = @import("std"); const sood = @import("lib.zig"); // Shared result code constants. const WasmResultCode = enum(u32) { OK = 0, ITERATOR_DONE = 1, ERR_PARSE_HEADER_SIZE_MISMATCH = 2, ERR_PARSE_INVALID_SIGNATURE = 3, ERR_PARSE_EMPTY_KEY = 4, ERR_PARSE_KEY_SIZE_MISMATCH = 5, ERR_PARSE_NON_UTF8_KEY = 6, ERR_PARSE_VALUE_SIZE_CORRUPTED = 7, ERR_PARSE_VALUE_SIZE_MISMATCH = 8, ERR_PARSE_NON_UTF8_VALUE = 9, ERR_VALIDATE_MISSING_REQUIRED_PROPERTY = 10, ERR_VALIDATE_UNEXPECTED_VALUE_TYPE = 11, ERR_VALIDATE_UNEXPECTED_MESSAGE_KIND = 12, }; const LibError = sood.Message.HeaderParseError || sood.Message.PropertyParseError || sood.discovery.Response.SchemaError; inline fn errorsToCode(err: LibError) WasmResultCode { return switch (err) { sood.Message.HeaderParseError.InvalidSignature => .ERR_PARSE_INVALID_SIGNATURE, sood.Message.HeaderParseError.InvalidHeaderSize => .ERR_PARSE_HEADER_SIZE_MISMATCH, sood.Message.PropertyParseError.EmptyKey => .ERR_PARSE_EMPTY_KEY, sood.Message.PropertyParseError.IncompleteKey => .ERR_PARSE_KEY_SIZE_MISMATCH, sood.Message.PropertyParseError.NonUTF8Key => .ERR_PARSE_NON_UTF8_KEY, sood.Message.PropertyParseError.InvalidValueSizeField => .ERR_PARSE_VALUE_SIZE_CORRUPTED, sood.Message.PropertyParseError.IncompleteValue => .ERR_PARSE_VALUE_SIZE_MISMATCH, sood.Message.PropertyParseError.NonUTF8Value => .ERR_PARSE_NON_UTF8_VALUE, sood.discovery.Response.SchemaError.MissingRequiredProperty => .ERR_VALIDATE_MISSING_REQUIRED_PROPERTY, sood.discovery.Response.SchemaError.UnexpectedPropertyValue => .ERR_VALIDATE_UNEXPECTED_VALUE_TYPE, sood.discovery.Response.SchemaError.NonResponseKindMessage => .ERR_VALIDATE_UNEXPECTED_MESSAGE_KIND, }; } export fn result_code_string_ptr(code: WasmResultCode) [*]const u8 { return @tagName(code).ptr; } export fn result_code_string_len(code: WasmResultCode) usize { return @tagName(code).len; } export fn allocate_bytes(len: usize) [*]const u8 { return (std.heap.wasm_allocator.alloc(u8, len) catch @trap()).ptr; } export fn free_bytes(ptr: [*]const u8, len: usize) void { std.heap.wasm_allocator.free(ptr[0..len]); } export fn get_discovery_multicast_ipv4_address() [*]const u8 { return &sood.discovery.multicast_ipv4_address; } export fn get_discovery_server_udp_port() u16 { return sood.discovery.udp_port; } export fn prebuilt_discovery_query_ptr() [*]const u8 { return sood.discovery.Query.prebuilt.ptr; } export fn prebuilt_discovery_query_len() usize { return sood.discovery.Query.prebuilt.len; } export fn allocate_discovery_response() *sood.discovery.Response { return std.heap.wasm_allocator.create(sood.discovery.Response) catch @trap(); } export fn free_discovery_response(ptr: *sood.discovery.Response) void { std.heap.wasm_allocator.destroy(ptr); } export fn parse_discovery_response_into( dst: *sood.discovery.Response, bytes_ptr: [*]const u8, bytes_len: usize, ) WasmResultCode { const resp = sood.discovery.Response.parse(bytes_ptr[0..bytes_len]) catch |err| { return errorsToCode(err); }; dst.http_port = resp.http_port; dst.name = resp.name; dst.display_version = resp.display_version; dst.unique_id = resp.unique_id; return .OK; } export fn get_discovery_response_http_port(resp: *const sood.discovery.Response) u16 { return resp.http_port; } export fn get_discovery_response_name_ptr(resp: *const sood.discovery.Response) [*]const u8 { return resp.name.ptr; } export fn get_discovery_response_name_len(resp: *const sood.discovery.Response) usize { return resp.name.len; } export fn get_discovery_response_display_version_ptr(resp: *const sood.discovery.Response) [*]const u8 { return resp.display_version.ptr; } export fn get_discovery_response_display_version_len(resp: *const sood.discovery.Response) usize { return resp.display_version.len; } export fn get_discovery_response_unique_id_ptr(resp: *const sood.discovery.Response) [*]const u8 { return resp.unique_id.ptr; } export fn get_discovery_response_unique_id_len(resp: *const sood.discovery.Response) usize { return resp.unique_id.len; }
-