Skip to main content

Send Telemetry to Datadog from WebAssembly in Bun

Observability in Datadog from WebAssembly

Overview

Enables the extraction of traces/spans from Wasm modules executing in a Bun runtime and emits them to a Datadog agent.

Installation

Install the Datadog Adapter via bun:

bun add @dylibso/observe-sdk-datadog

Example

A basic JavaScript program that loads a Wasm module and executes it using the native WebAssembly runtime.

import { DatadogAdapter } from "@dylibso/observe-sdk-datadog";
import { File, OpenFile, WASI } from "@bjorn3/browser_wasi_shim";

// create a new instance of the Observe SDK Datadog adapter
// this assumes you have a datadog agent running on localhost, you may also pass a config
const adapter = new DatadogAdapter();

// create an optional filter that instructs the adapter to throw away any
// spans below a configured threshold
const opts = {
spanFilter: {
minDurationMicroseconds: 100,
},
};

// fetch a wasm module and load up the bytes
const resp = await Bun.file("count_vowels.instr.wasm");
const bytes = await resp.arrayBuffer();

// start the adapter with the wasm module bytes and options
const traceContext = await adapter.start(bytes, opts);

// setup some files for stdin, stdout, and stderr
let fds = [
new OpenFile(
new File(
new TextEncoder("utf-8").encode(`count these vowels for me please`),
),
), // stdin
new OpenFile(new File([])), // stdout
new OpenFile(new File([])), // stderr
];

// instantiate the wasm module
let wasi = new WASI([], [], fds);
const instance = await WebAssembly.instantiate(bytes, {
"wasi_snapshot_preview1": wasi.wasiImport,
...traceContext.getImportObject(),
});

// execute the module
wasi.start(instance.instance);
let utf8decoder = new TextDecoder();
console.log(utf8decoder.decode(fds[1].file.data));

// instruct the adapter to stop the trace
traceContext.stop();

Adapter Configuration

You may modify the behavior of your adapter by passing in a configuration when initializing the adapter. A configuration has the following fields:

const config = {
// the URL of the Datadog agent
agentHost: new URL("https://locationofyourdatadogagent.com:8126"),
// the service name to group your observability data under
serviceName: "my-wasm-service",
// default metadata that apply to every trace
defaultTags: new Map<string, string>(),
// the type of trace being captured
traceType: DatadogTraceType.Web,
// how often to send new traces to the agent
emitTracesInterval: 1000,
// the maximum number of traces to send to the agent per request
traceBatchMax: 100,
};
const adapter = new DatadogAdapter(config);