[Add] Pipes (experimental)
Some checks failed
CI / checks (push) Failing after 1m51s

This commit is contained in:
Alex Emmet 2026-07-15 01:42:54 +02:00
commit 089def45d1
37 changed files with 2792 additions and 225 deletions

1
example/.gitignore vendored
View file

@ -11,5 +11,6 @@ web-client/public/host_public_key_bundle.hex
web-client/public/mtp_dev_cert_hash.txt
web-client/dist/
client.id
*.mk
*.mpkb

6
example/Cargo.lock generated
View file

@ -208,6 +208,7 @@ name = "client"
version = "0.1.0"
dependencies = [
"mtp",
"rand 0.8.6",
"tokio",
]
@ -902,6 +903,7 @@ dependencies = [
"mtp-crypto",
"mtp-files",
"mtp-host",
"mtp-transport",
"mtp-type-map",
]
@ -915,6 +917,7 @@ dependencies = [
"mtp-transport",
"rand 0.8.6",
"tokio",
"tracing",
]
[[package]]
@ -984,9 +987,11 @@ dependencies = [
"log",
"mtp-codec",
"mtp-common",
"rcgen",
"rustls",
"rustls-native-certs",
"tokio",
"tracing",
"wtransport",
]
@ -1574,6 +1579,7 @@ dependencies = [
"mtp",
"rcgen",
"serde_json",
"time",
"tokio",
]

1
example/client.id Normal file
View file

@ -0,0 +1 @@
1000

View file

@ -8,5 +8,6 @@ name = "client"
path = "src/main.rs"
[dependencies]
mtp = { version = "0.1.0", path = "../../", features = ["client", "crypto", "files"] }
mtp = { version = "0.1.0", path = "../../", features = ["client", "crypto", "files", "pipes"] }
tokio = { version = "1", features = ["full"] }
rand = "0.8"

View file

@ -1,5 +1,6 @@
mod auth;
mod messages;
mod pipes;
use std::fs;
use std::path::Path;
@ -38,6 +39,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let (conn, keyring) = auth::connect_or_register(config, host_public_key, "client").await?;
messages::send_and_receive(&conn, &keyring, &server_bundle).await?;
println!("\n--- Pipe demo ---");
pipes::run_pipe_demo(&conn, 1).await?;
conn.sender.close();
println!("\nDone");
Ok(())
}

View file

@ -96,13 +96,12 @@ pub async fn send_and_receive(
println!("Sending: {msg}");
conn.sender.send(&msg).await?;
match conn.receiver.receive().await {
match conn.receive().await {
Ok(resp) => {
println!("Received: {resp}");
}
Err(e) => eprintln!("Receive error: {e}"),
}
conn.sender.close();
Ok(())
}

137
example/client/src/pipes.rs Normal file
View file

@ -0,0 +1,137 @@
use mtp::client::MTPConnection;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::sync::oneshot;
use tokio::time::{Duration, Instant};
pub async fn run_pipe_demo(
conn: &MTPConnection,
iterations: usize,
) -> Result<(), Box<dyn std::error::Error>> {
let sizes = [64, 256, 1024, 4096];
let mut all_elapsed = Vec::with_capacity(sizes.len() * iterations);
let mut all_data_only = Vec::with_capacity(sizes.len() * iterations);
for (i, &size) in sizes.iter().enumerate() {
let mut size_elapsed = Vec::with_capacity(iterations);
let mut size_data_only = Vec::with_capacity(iterations);
for run in 0..iterations {
let random_bytes: Vec<u8> = (0..size).map(|_| rand::random::<u8>()).collect();
let description = format!("pipe-demo-{i}-run{run}");
println!(" [pipe {i}.{run}] creating pipe ({size} bytes): {description}");
let handle = conn.create_pipe(&description).await?;
let pipe_id = handle.pipe_id();
println!(" [pipe {i}.{run}] create_pipe returned (pipe_id={pipe_id})");
// Overall timer starts before any I/O
let overall_start = Instant::now();
// Channel to capture the instant the writer actually starts writing
let (write_start_tx, write_start_rx) = oneshot::channel();
let write_bytes = random_bytes.clone();
let writer_handle = tokio::spawn(async move {
println!(" [pipe {i}.{run}] writer: waiting for server accept ...");
match handle.wait().await {
Ok(Some(mut writer)) => {
// Record the instant we begin writing
let _ = write_start_tx.send(Instant::now());
println!(
" [pipe {i}.{run}] writer: pipe accepted (pipe_id={pipe_id}), writing {} bytes ...",
write_bytes.len()
);
writer
.write_all(&write_bytes)
.await
.map_err(|e| mtp::common::PipeError::IoError(e.to_string()))?;
writer
.finish()
.await
.map_err(|e| mtp::common::PipeError::IoError(e.to_string()))?;
println!(" [pipe {i}.{run}] writer: data sent and finished");
Ok::<(), mtp::common::PipeError>(())
}
Ok(None) => {
eprintln!(" [pipe {i}.{run}] writer: pipe denied by server");
Err(mtp::common::PipeError::Rejected)
}
Err(e) => {
eprintln!(" [pipe {i}.{run}] writer: error: {e}");
Err(e)
}
}
});
println!(" [pipe {i}.{run}] waiting for server's return pipe via receive_pipe() ...");
let pipe_req = conn.receive_pipe().await?;
println!(
" [pipe {i}.{run}] received return pipe: id={} desc={:?}",
pipe_req.id(),
pipe_req.description()
);
let mut reader = pipe_req.accept().await?;
println!(" [pipe {i}.{run}] return pipe accepted, reading data ...");
let mut buf = Vec::new();
reader.read_to_end(&mut buf).await?;
let overall_elapsed = overall_start.elapsed();
// Receive the instant the writer started writing
let data_start = write_start_rx.await?;
let data_only_elapsed = Instant::now() - data_start;
match writer_handle.await {
Ok(Ok(())) => {}
Ok(Err(e)) => eprintln!(" [pipe {i}.{run}] writer error: {e}"),
Err(e) => eprintln!(" [pipe {i}.{run}] writer task panicked: {e}"),
}
let matches = buf == random_bytes;
println!(
" [pipe {i}.{run}] round-trip: {} bytes, \
total={:.3}ms, data-only={:.3}ms, match={matches}",
size,
overall_elapsed.as_secs_f64() * 1000.0,
data_only_elapsed.as_secs_f64() * 1000.0,
);
size_elapsed.push(overall_elapsed);
size_data_only.push(data_only_elapsed);
all_elapsed.push(overall_elapsed);
all_data_only.push(data_only_elapsed);
}
// ---- per-size averages ----
let avg_total = average_duration(&size_elapsed);
let avg_data = average_duration(&size_data_only);
println!(
" [pipe {i}] AVERAGE for size {size}: \
total={avg_total:.3}ms, data-only={avg_data:.3}ms \
(over {iterations} runs)"
);
}
// ---- overall averages ----
let overall_total = average_duration(&all_elapsed);
let overall_data = average_duration(&all_data_only);
println!(
" [summary] OVERALL AVERAGE loopback time: \
total={overall_total:.3}ms, data-only={overall_data:.3}ms \
({} measurements)",
all_elapsed.len()
);
Ok(())
}
/// Helper: average a slice of Durations without overflowing.
fn average_duration(durations: &[Duration]) -> f64 {
if durations.is_empty() {
return 0.0;
}
let sum_ms: f64 = durations.iter().map(|d| d.as_secs_f64() * 1000.0).sum();
sum_ms / durations.len() as f64
}

View file

@ -8,9 +8,10 @@ name = "server"
path = "src/main.rs"
[dependencies]
mtp = { version = "0.1.0", path = "../../", features = ["crypto", "host", "files"] }
mtp = { version = "0.1.0", path = "../../", features = ["crypto", "host", "files", "pipes"] }
rcgen = "0.14"
tokio = { version = "1", features = ["full"] }
serde_json = { version = "1" }
hex = "0.4"
base64 = "0.22"
time = "0.3"

View file

@ -4,7 +4,6 @@ mod keys;
mod tls;
use mtp::host::{AuthenticationPolicy, HostConfig, MTPHost};
use mtp::type_map::TypeMap;
use std::future::Future;
use std::path::Path;
@ -28,6 +27,54 @@ fn dev_cert_paths() -> (String, String) {
(cert, key)
}
async fn handle_pipe_loopback(
conn: &mtp::host::MTPConnection,
req: mtp::host::PipeRequest,
) -> Result<(), Box<dyn std::error::Error>> {
let pipe_id = req.id();
println!(
" [loopback] Pipe request: id={pipe_id} description={:?}",
req.description()
);
println!(" [loopback] Calling accept() for pipe {pipe_id} ...");
let mut reader = req.accept().await?;
println!(" [loopback] Pipe {pipe_id} accepted, reading data ...");
let mut buf = Vec::new();
tokio::io::AsyncReadExt::read_to_end(&mut reader, &mut buf).await?;
println!(
" [loopback] Pipe {pipe_id} read {} bytes, creating return pipe ...",
buf.len()
);
let handle = conn.create_pipe("loopback").await?;
println!(
" [loopback] Return pipe created (id={}), waiting for client ...",
handle.pipe_id()
);
match handle.wait().await? {
Some(mut writer) => {
println!(
" [loopback] Client accepted return pipe, writing {} bytes ...",
buf.len()
);
tokio::io::AsyncWriteExt::write_all(&mut writer, &buf).await?;
writer.finish().await?;
println!(
" [loopback] Pipe {pipe_id} loopback complete ({} bytes)",
buf.len()
);
}
None => {
eprintln!(" [loopback] Return pipe denied by client for pipe {pipe_id}");
}
}
Ok(())
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let (cert_path, key_path) = dev_cert_paths();
@ -39,8 +86,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let (_host_id, host_keyring) = keys::load_or_generate_host_keys("host.mk")?;
keys::export_host_public_keys(&host_keyring)?;
// The keyring is moved into the host config; keep a copy for decrypting the
// demo payloads clients encrypt to our KEM public key.
let decrypt_keyring = mtp::crypto::Keyring::from_bytes(&host_keyring.to_bytes())
.expect("re-load host keyring for decryption");
@ -116,20 +161,47 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let tm: &TypeMap = conn.codec.registry().get(&conn.version).unwrap();
match conn.receiver.receive().await {
Ok(msg) => {
println!("Received: {msg}");
let response = handlers::process_and_respond(
&msg,
tm,
conn.client_public_key.as_ref(),
&decrypt_keyring,
);
println!("Sending: {response}");
conn.sender.send(&response).await?;
}
Err(e) => {
eprintln!("Receive error: {e}");
println!("Waiting for messages / pipe requests ...");
loop {
tokio::select! {
biased;
pipe_req = conn.receive_pipe() => {
match pipe_req {
Ok(req) => {
println!(" Pipe request: id={} desc={:?}", req.id(), req.description());
if let Err(e) = handle_pipe_loopback(&conn, req).await {
eprintln!(" Pipe loopback error: {e}");
}
}
Err(e) => {
println!("Pipe channel closed: {e}");
break;
}
}
}
msg = conn.receive() => {
match msg {
Ok(msg) => {
println!("Received: {msg}");
let response = handlers::process_and_respond(
&msg,
tm,
conn.client_public_key.as_ref(),
&decrypt_keyring,
);
println!("Sending: {response}");
if let Err(e) = conn.sender.send(&response).await {
eprintln!("Send error: {e}");
break;
}
}
Err(e) => {
println!("Connection ended: {e}");
break;
}
}
}
}
}

View file

@ -1,7 +1,9 @@
use std::fs;
use std::path::Path;
use base64::Engine;
use rcgen::{CertificateParams, ExtendedKeyUsagePurpose, IsCa, KeyPair, KeyUsagePurpose, SanType};
use std::fs;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::path::Path;
use time::{Duration, OffsetDateTime};
pub fn load_or_generate_tls(
cert_path: &str,
@ -19,8 +21,26 @@ pub fn load_or_generate_tls(
if let Some(parent) = Path::new(key_path).parent() {
fs::create_dir_all(parent)?;
}
let key_pair = rcgen::KeyPair::generate()?;
let params = rcgen::CertificateParams::new(vec!["localhost".into(), "127.0.0.1".into()])?;
let key_pair = KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256)?;
let mut params = CertificateParams::new(vec!["localhost".into()])?;
params.not_before = OffsetDateTime::now_utc() - Duration::minutes(5);
params.not_after = OffsetDateTime::now_utc() + Duration::days(13);
params
.subject_alt_names
.push(SanType::IpAddress(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))));
params
.subject_alt_names
.push(SanType::IpAddress(IpAddr::V6(Ipv6Addr::new(
0, 0, 0, 0, 0, 0, 0, 1,
))));
params.key_usages = vec![KeyUsagePurpose::DigitalSignature];
params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth];
params.is_ca = IsCa::NoCa;
let cert = params.self_signed(&key_pair)?;
let cert_str = cert.pem();

View file

@ -1,39 +1,89 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>MTP Web Client</title>
<style>
body { background: #111; color: #eee; font-family: "Public Sans", sans-serif; }
label, input, textarea { display: block; margin-bottom: 0.5rem; }
input, textarea, button { font-family: "Public Sans", sans-serif; }
input, textarea { background: #222; color: #eee; }
#status, #key-status { white-space: pre-wrap; }
.state { color: #ff0; }
.received { color: #0ff; }
.error { color: #f00; }
</style>
</head>
<body>
<h1>MTP WebTransport Client</h1>
<label for="server-url">Server URL</label>
<input id="server-url" value="https://127.0.0.1:8080" />
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>MTP Web Client</title>
<style>
body {
background: #111;
color: #eee;
font-family: "Public Sans", sans-serif;
}
label,
input,
textarea {
display: block;
margin-bottom: 0.5rem;
}
input,
textarea,
button {
font-family: "Public Sans", sans-serif;
}
input,
textarea {
background: #222;
color: #eee;
}
#status,
#key-status {
white-space: pre-wrap;
}
.state {
color: #ff0;
}
.received {
color: #0ff;
}
.error {
color: #f00;
}
.pipe {
color: #0f0;
}
hr {
border-color: #444;
margin: 1.5rem 0;
}
</style>
</head>
<body>
<h1>MTP WebTransport Client</h1>
<label for="server-url">Server URL</label>
<input id="server-url" value="https://localhost:8080" />
<label for="host-public-key">Host public key bundle hex</label>
<textarea id="host-public-key" placeholder="Paste PublicKeyBundle bytes as hex"></textarea>
<label for="host-public-key">Host public key bundle hex</label>
<textarea
id="host-public-key"
placeholder="Paste PublicKeyBundle bytes as hex"
></textarea>
<label for="client-credentials">Saved SDK credentials</label>
<textarea id="client-credentials" readonly></textarea>
<label for="client-credentials">Saved SDK credentials</label>
<textarea id="client-credentials" readonly></textarea>
<div>
<button id="generate-keypair" type="button">Use new credentials</button>
<button id="connect" type="button" disabled>Connect</button>
<button id="clear-keys" type="button">Clear saved keys</button>
</div>
<div>
<button id="generate-keypair" type="button">
Use new credentials
</button>
<button id="connect" type="button" disabled>Connect</button>
<button id="clear-keys" type="button">Clear saved keys</button>
</div>
<div id="key-status">Initializing...</div>
<div id="status"></div>
<script type="module" src="/src/main.ts"></script>
</body>
<hr />
<h2>Pipe Demo</h2>
<div>
<button id="stream-mic" type="button" disabled>
Stream Microphone (pipe loopback)
</button>
<button id="stop-mic" type="button" disabled>
Stop Microphone
</button>
</div>
<div id="pipe-status"></div>
<div id="key-status">Initializing...</div>
<div id="status"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

View file

@ -1,14 +1,28 @@
import { MTPClient } from "mtp";
import type { MTPCredentialStorage, MTPLogEvent, ParsedFrame } from "mtp";
import type {
MTPCredentialStorage,
MTPLogEvent,
MTPPipeReader,
ParsedFrame,
} from "mtp";
const STATUS = document.getElementById("status")!;
const KEY_STATUS = document.getElementById("key-status")!;
const SERVER_URL = document.getElementById("server-url") as HTMLInputElement;
const HOST_PUBLIC_KEY = document.getElementById("host-public-key") as HTMLTextAreaElement;
const CLIENT_CREDENTIALS = document.getElementById("client-credentials") as HTMLTextAreaElement;
const GENERATE_KEYPAIR = document.getElementById("generate-keypair") as HTMLButtonElement;
const HOST_PUBLIC_KEY = document.getElementById(
"host-public-key",
) as HTMLTextAreaElement;
const CLIENT_CREDENTIALS = document.getElementById(
"client-credentials",
) as HTMLTextAreaElement;
const GENERATE_KEYPAIR = document.getElementById(
"generate-keypair",
) as HTMLButtonElement;
const CONNECT = document.getElementById("connect") as HTMLButtonElement;
const CLEAR_KEYS = document.getElementById("clear-keys") as HTMLButtonElement;
const STREAM_MIC = document.getElementById("stream-mic") as HTMLButtonElement;
const STOP_MIC = document.getElementById("stop-mic") as HTMLButtonElement;
const PIPE_STATUS = document.getElementById("pipe-status")!;
const CREDENTIALS_KEY = "mtp-web-client-credentials";
const HOST_PUBLIC_KEY_KEY = "mtp-web-client-host-public-key";
@ -22,6 +36,13 @@ type SavedKeys = {
let clientId: bigint | null = null;
let devCertHash = "";
let activeClient: ReturnType<typeof createClient> extends Promise<infer T>
? T
: never;
let micStream: MediaStream | null = null;
let mediaRecorder: MediaRecorder | null = null;
let pipeSendCount = 0;
let pendingPipeReaders: MTPPipeReader[] = [];
const credentialStorage: MTPCredentialStorage = {
getItem: (key) => localStorage.getItem(key),
@ -36,6 +57,13 @@ function log(msg: string, cls = "") {
STATUS.appendChild(line);
}
function pipeLog(msg: string, cls = "pipe") {
const line = document.createElement("div");
line.textContent = msg;
if (cls) line.className = cls;
PIPE_STATUS.appendChild(line);
}
function renderStructured(value: unknown): string {
return JSON.stringify(value, (_key, item) => {
if (typeof item === "bigint") {
@ -70,13 +98,16 @@ function setKeyStatus(msg: string) {
}
function bytesToHex(bytes: Uint8Array): string {
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(
"",
);
}
function hexToBytes(value: string): Uint8Array {
const hex = value.replace(/[^0-9a-fA-F]/g, "");
if (hex.length === 0) throw new Error("host public key is required");
if (hex.length % 2 !== 0) throw new Error("host public key hex has an odd length");
if (hex.length % 2 !== 0)
throw new Error("host public key hex has an odd length");
const bytes = new Uint8Array(hex.length / 2);
for (let i = 0; i < bytes.length; i += 1) {
@ -87,7 +118,10 @@ function hexToBytes(value: string): Uint8Array {
function saveHostPublicKey() {
try {
localStorage.setItem(HOST_PUBLIC_KEY_KEY, bytesToHex(hexToBytes(HOST_PUBLIC_KEY.value)));
localStorage.setItem(
HOST_PUBLIC_KEY_KEY,
bytesToHex(hexToBytes(HOST_PUBLIC_KEY.value)),
);
} catch {
localStorage.removeItem(HOST_PUBLIC_KEY_KEY);
}
@ -102,7 +136,9 @@ function loadKeys() {
if (!raw) {
CLIENT_CREDENTIALS.value = "";
setKeyStatus("No saved SDK credentials. The next connection will generate and store a reusable keyring.");
setKeyStatus(
"No saved SDK credentials. The next connection will generate and store a reusable keyring.",
);
return;
}
@ -127,11 +163,13 @@ function loadKeys() {
async function loadHostPublicKey() {
try {
const response = await fetch("/host_public_key_bundle.hex", { cache: "no-store" });
const response = await fetch("/host_public_key_bundle.hex", {
cache: "no-store",
});
if (!response.ok) return;
const hostPublicKey = (await response.text()).trim();
if (!hostPublicKey) return;
if (!hostPublicKey || !/^[0-9a-f]+$/i.test(hostPublicKey)) return;
HOST_PUBLIC_KEY.value = hostPublicKey;
saveHostPublicKey();
@ -143,11 +181,14 @@ async function loadHostPublicKey() {
async function loadDevCertHash() {
try {
const response = await fetch("/mtp_dev_cert_hash.txt", { cache: "no-store" });
const response = await fetch(`/mtp_dev_cert_hash.txt?t=${Date.now()}`, {
cache: "no-store",
});
if (!response.ok) return;
devCertHash = (await response.text()).trim();
if (devCertHash) {
const hash = (await response.text()).trim();
if (/^[0-9a-f]{64}$/i.test(hash)) {
devCertHash = hash;
log(`Loaded WebTransport certificate hash: ${devCertHash}`);
}
} catch {
@ -157,14 +198,47 @@ async function loadDevCertHash() {
async function initWasm() {
log("Loading WASM module...");
await MTPClient.create({ url: SERVER_URL.value, storage: credentialStorage, credentialsStorageKey: CREDENTIALS_KEY });
await MTPClient.create({
url: SERVER_URL.value,
storage: credentialStorage,
credentialsStorageKey: CREDENTIALS_KEY,
});
const supported = MTPClient.isSupported();
log(`WASM loaded. WebTransport supported: ${supported}`);
CONNECT.disabled = !supported;
}
async function createClient() {
const hostPk = hexToBytes(HOST_PUBLIC_KEY.value);
await loadDevCertHash();
const serverUrl = SERVER_URL.value.trim();
const serverCertificateHashes = devCertHash ? [devCertHash] : undefined;
const client = await MTPClient.create({
url: serverUrl,
hostPublicKey: hostPk,
storage: credentialStorage,
credentialsStorageKey: CREDENTIALS_KEY,
serverCertificateHashes,
pings: { intervalMs: 30_000 },
logger(event) {
log(
renderLoggerEvent(event),
event.hint === "error"
? "error"
: event.type === "state"
? "state"
: "",
);
},
});
return client;
}
async function connect() {
STATUS.textContent = "";
PIPE_STATUS.textContent = "";
if (!MTPClient.isSupported()) {
log("WebTransport is not supported in this browser.", "error");
@ -175,25 +249,19 @@ async function connect() {
await loadDevCertHash();
const serverUrl = SERVER_URL.value.trim();
const serverCertificateHashes = devCertHash ? [`sha-256:${devCertHash}`] : undefined;
const serverCertificateHashes = devCertHash ? [devCertHash] : undefined;
if (serverCertificateHashes) {
log(`Pinning WebTransport certificate hash: ${serverCertificateHashes[0]}`);
} else {
log("No WebTransport certificate hash loaded; relying on browser trust store.", "state");
log(
"No WebTransport certificate hash loaded; relying on browser trust store.",
"state",
);
}
try {
const client = await MTPClient.create({
url: serverUrl,
hostPublicKey: hostPk,
storage: credentialStorage,
credentialsStorageKey: CREDENTIALS_KEY,
serverCertificateHashes,
pings: { intervalMs: 30_000 },
logger(event) {
log(renderLoggerEvent(event), event.hint === "error" ? "error" : event.type === "state" ? "state" : "");
},
});
const client = await createClient();
activeClient = client;
client.subscribe("Pong", (frame: ParsedFrame) => {
log(`Subscribed Pong: ${formatParsedFrame(frame)}`, "received");
@ -205,31 +273,164 @@ async function connect() {
log(`Connected as client ${activeClientId}`);
log("\nSending typed Ping...");
await client.send("Ping", {
Description: "MTP web client send ping",
Timestamp: BigInt(Date.now()),
}, { sender: activeClientId });
await client.send(
"Ping",
{
Description: "MTP web client send ping",
Timestamp: BigInt(Date.now()),
},
{ sender: activeClientId },
);
log("Typed Ping sent.");
log("\nRequesting Pong by Ping frame id...");
const response = await client.request("Ping", {
Description: "MTP web client request ping",
Timestamp: BigInt(Date.now()),
}, { sender: activeClientId, responseType: "Pong" });
const response = await client.request(
"Ping",
{
Description: "MTP web client request ping",
Timestamp: BigInt(Date.now()),
},
{ sender: activeClientId, responseType: "Pong" },
);
log(`Request response: ${formatParsedFrame(response)}`, "received");
log("\nClient running. Waiting for incoming messages...");
STREAM_MIC.disabled = false;
log("\nPipe demo ready. Click 'Stream Microphone' to start.", "pipe");
} catch (error) {
log(`[error] ${error}`, "error");
}
}
async function startMicStreaming() {
if (!activeClient) {
pipeLog("No active client connection.", "error");
return;
}
try {
micStream = await navigator.mediaDevices.getUserMedia({ audio: true });
} catch (e) {
pipeLog(`Microphone access denied: ${e}`, "error");
return;
}
STREAM_MIC.disabled = true;
STOP_MIC.disabled = false;
pipeLog("Microphone acquired. Creating pipe ...");
const handle = await activeClient.createPipe("mic-audio");
pipeLog(
`Pipe created (id=${handle.pipeId}). Waiting for server to accept ...`,
);
// Handle incoming pipe requests from the server (loopback return pipes)
activeClient.setOnPipeRequest(async (request) => {
pipeLog(
`Incoming return pipe: id=${request.pipeId} desc=${request.description}`,
);
try {
const reader = await activeClient!.acceptPipe(request.pipeId);
pendingPipeReaders.push(reader);
readLoopbackPipe(reader);
} catch (e) {
pipeLog(`Failed to accept return pipe: ${e}`, "error");
}
});
const writer = await handle.wait();
if (!writer) {
pipeLog("Pipe denied by server.", "error");
stopMicStreaming();
return;
}
pipeLog(`Pipe accepted. Streaming microphone (pipe id=${writer.pipeId}) ...`);
// Stream microphone audio via MediaRecorder
const mimeType = MediaRecorder.isTypeSupported("audio/webm;codecs=opus")
? "audio/webm;codecs=opus"
: "audio/webm";
mediaRecorder = new MediaRecorder(micStream, { mimeType });
mediaRecorder.ondataavailable = async (event) => {
if (event.data.size === 0 || !activeClient) return;
const startTime = performance.now();
pipeSendCount++;
const chunkNum = pipeSendCount;
try {
const buffer = await event.data.arrayBuffer();
const data = new Uint8Array(buffer);
await writer.write(data);
pipeLog(
` [chunk ${chunkNum}] sent ${data.length} bytes (${(performance.now() - startTime).toFixed(1)}ms write)`,
);
} catch (e) {
pipeLog(` [chunk ${chunkNum}] send error: ${e}`, "error");
}
};
mediaRecorder.start(200); // emit data every 200ms
pipeLog("Streaming started (200ms chunks).");
}
async function readLoopbackPipe(reader: MTPPipeReader) {
const startTime = performance.now();
let totalBytes = 0;
let chunkCount = 0;
try {
while (true) {
const data = await reader.read();
if (data == null) break; // EOF
totalBytes += data.length;
chunkCount++;
}
} catch (e) {
pipeLog(` Return pipe read error: ${e}`, "error");
return;
}
const elapsed = performance.now() - startTime;
pipeLog(
` Return pipe complete: ${chunkCount} chunks, ${totalBytes} bytes, ` +
`delay=${elapsed.toFixed(1)}ms`,
);
// Clean up the reader from the pending list
const idx = pendingPipeReaders.indexOf(reader);
if (idx >= 0) pendingPipeReaders.splice(idx, 1);
}
async function stopMicStreaming() {
if (mediaRecorder && mediaRecorder.state !== "inactive") {
mediaRecorder.stop();
mediaRecorder = null;
}
if (micStream) {
micStream.getTracks().forEach((track) => track.stop());
micStream = null;
}
// Close pending pipe readers
pendingPipeReaders = [];
STREAM_MIC.disabled = false;
STOP_MIC.disabled = true;
pipeLog("Microphone streaming stopped.");
}
GENERATE_KEYPAIR.addEventListener("click", () => {
try {
clientId = null;
localStorage.removeItem(CREDENTIALS_KEY);
CLIENT_CREDENTIALS.value = "";
setKeyStatus("Cleared saved credentials. The next connection will generate a new reusable keyring.");
setKeyStatus(
"Cleared saved credentials. The next connection will generate a new reusable keyring.",
);
log("Cleared saved SDK credentials.");
} catch (e) {
log(`Credential reset failed: ${e}`, "error");
@ -257,6 +458,17 @@ CLEAR_KEYS.addEventListener("click", () => {
log("Cleared saved SDK credentials and host public key.");
});
STREAM_MIC.addEventListener("click", () => {
startMicStreaming().catch((e) => {
pipeLog(`Pipe streaming error: ${e}`, "error");
console.error(e);
});
});
STOP_MIC.addEventListener("click", () => {
stopMicStreaming();
});
HOST_PUBLIC_KEY.addEventListener("change", saveHostPublicKey);
initWasm()

View file

@ -1,16 +1,41 @@
import { defineConfig } from 'vite';
import { defineConfig, type Plugin } from 'vite';
import fs from 'fs';
import path from 'path';
import { mtp } from 'mtp/vite';
const devCertDir = path.resolve(__dirname, '../dev-cert');
const exampleDir = path.resolve(__dirname, '..');
const devCertDir = path.join(exampleDir, 'dev-cert');
const certPath = process.env.MTP_DEV_CERT ?? path.join(devCertDir, 'cert.pem');
const keyPath = process.env.MTP_DEV_KEY ?? path.join(devCertDir, 'key.pem');
const hasDevCert = fs.existsSync(certPath) && fs.existsSync(keyPath);
const devFiles: Record<string, string> = {
'/host_public_key_bundle.hex': path.join(exampleDir, 'host_public_key_bundle.hex'),
'/mtp_dev_cert_hash.txt': path.join(devCertDir, 'sha256.txt'),
};
function devFileServe(): Plugin {
return {
name: 'dev-file-serve',
configureServer(server) {
server.middlewares.use((req, res, next) => {
const target = devFiles[req.url?.split('?')[0] ?? ''];
if (!target) return next();
fs.readFile(target, (err, data) => {
if (err) return next();
res.setHeader('Content-Type', 'text/plain');
res.setHeader('Cache-Control', 'no-store');
res.end(data);
});
});
},
};
}
export default defineConfig({
plugins: [mtp({ typeMaps: '../../example/type-maps.yaml' })],
plugins: [mtp({ typeMaps: '../../example/type-maps.yaml' }), devFileServe()],
server: {
https: hasDevCert
? {