auth-yes/archive/.forum/poc-g2/protobuf_poc.ts

159 lines
4.3 KiB
TypeScript

import { assertEquals } from "https://deno.land/std@0.224.0/testing/asserts.ts";
import {
dirname,
fromFileUrl,
join,
} from "https://deno.land/std@0.224.0/path/mod.ts";
import { requireTool } from "./sys_exec.ts";
/**
* Proof of Concept: Protocol Buffers (Gen 2)
*
* Demonstrates serializing and deserializing agent state using actual
* protoc CLI instead of a JS library mock, showing high-performance
* I/O for vector math and state passing using native host tooling.
*/
const protoDefinition = `
syntax = "proto3";
message AgentState {
string agentId = 1;
string status = 2;
int32 memoryUsage = 3;
}
`;
async function run() {
const hasProtoc = await requireTool(
"protoc",
"sudo apt-get install protobuf-compiler",
);
if (!hasProtoc) {
console.warn(
"⚠️ Protocol Buffers PoC skipped due to missing host dependency.",
);
return;
}
const currentDir = dirname(fromFileUrl(import.meta.url));
const TEMP_PROTO = join(currentDir, "dummy_agent.proto");
const TEMP_DATA = join(currentDir, "dummy_data.txt");
const TEMP_BIN = join(currentDir, "dummy_encoded.bin");
try {
await Deno.writeTextFile(TEMP_PROTO, protoDefinition);
const payload = {
agentId: "adversary-01",
status: "active",
memoryUsage: 1024,
};
// Write text format for protoc to consume
const textData = `agentId: "${payload.agentId}"
status: "${payload.status}"
memoryUsage: ${payload.memoryUsage}
`;
await Deno.writeTextFile(TEMP_DATA, textData);
// Encode
const encodeCommand = new Deno.Command("protoc", {
args: [
"--encode=AgentState",
`--proto_path=${currentDir}`,
"dummy_agent.proto",
],
stdin: "piped",
stdout: "piped",
stderr: "piped",
});
const encodeProcess = encodeCommand.spawn();
const encodeWriter = encodeProcess.stdin.getWriter();
await encodeWriter.write(new TextEncoder().encode(textData));
await encodeWriter.close();
const encodeOutput = await encodeProcess.output();
if (encodeOutput.code !== 0) {
throw new Error(
`protoc encode failed: ${
new TextDecoder().decode(encodeOutput.stderr)
}`,
);
}
const buffer = encodeOutput.stdout;
await Deno.writeFile(TEMP_BIN, buffer);
console.log(`Original Data:`, payload);
console.log(`Serialized Size: ${buffer.length} bytes (binary)`);
// Decode
const decodeCommand = new Deno.Command("protoc", {
args: [
"--decode=AgentState",
`--proto_path=${currentDir}`,
"dummy_agent.proto",
],
stdin: "piped",
stdout: "piped",
stderr: "piped",
});
const decodeProcess = decodeCommand.spawn();
const decodeWriter = decodeProcess.stdin.getWriter();
await decodeWriter.write(buffer);
await decodeWriter.close();
const decodeOutput = await decodeProcess.output();
if (decodeOutput.code !== 0) {
throw new Error(
`protoc decode failed: ${
new TextDecoder().decode(decodeOutput.stderr)
}`,
);
}
const decodedString = new TextDecoder().decode(decodeOutput.stdout);
// Parse text format back to object for assertion
// deno-lint-ignore no-explicit-any
const deserialized: any = {};
decodedString.trim().split("\n").forEach((line) => {
const [key, val] = line.split(":").map((s) => s.trim());
if (key && val) {
if (val.startsWith('"') && val.endsWith('"')) {
deserialized[key] = val.slice(1, -1);
} else {
deserialized[key] = parseInt(val, 10);
}
}
});
console.log("Deserialized Data:", deserialized);
assertEquals(deserialized.agentId, payload.agentId);
assertEquals(deserialized.status, payload.status);
assertEquals(deserialized.memoryUsage, payload.memoryUsage);
console.log(
"✅ Protocol Buffers PoC (Gen 2) successful: Real protoc CLI serialization/deserialization worked.",
);
} catch (err) {
console.error("❌ Protocol Buffers PoC (Gen 2) failed:", err);
Deno.exit(1);
} finally {
try {
await Deno.remove(TEMP_PROTO);
await Deno.remove(TEMP_DATA);
await Deno.remove(TEMP_BIN);
} catch {
// ignore
}
}
}
if (import.meta.main) {
console.log("Running Protocol Buffers PoC (Gen 2) tests...");
run();
}