MCPcopy Create free account
hub / github.com/deepclause/agentvm / NetworkStack

Class NetworkStack

src/network.js:44–888  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

42const DHCP_OPT_END = 255;
43
44class NetworkStack extends EventEmitter {
45 constructor(options = {}) {
46 super();
47 this.gatewayIP = options.gatewayIP || '192.168.127.1';
48 this.vmIP = options.vmIP || '192.168.127.3';
49 this.gatewayMac = options.gatewayMac || Buffer.from([0x5a, 0x94, 0xef, 0xe4, 0x0c, 0xdd]);
50 this.vmMac = Buffer.from([0x02, 0x00, 0x00, 0x00, 0x00, 0x01]); // Default VM MAC
51
52 this.natTable = new Map(); // key -> { state, mySeq, myAck, ... } for TCP state tracking
53
54 // Network I/O via shared ring buffer for INCOMING data (main → worker)
55 // No more MessagePort polling for data!
56 this.ringReader = options.ringReader || null;
57
58 // MessagePort still needed for OUTGOING control messages (worker → main)
59 this.netPort = options.netPort || null;
60
61 // QEMU Framing Buffer
62 this.txBuffer = Buffer.alloc(0); // Data sending TO the VM (queued)
63 this.rxBuffer = Buffer.alloc(0); // Data received FROM the VM (buffering for full frame)
64
65 // TCP Flow Control: Maximum buffer before requesting pause
66 // Use larger buffers to reduce pause/resume cycle frequency and improve throughput
67 this.TX_BUFFER_HIGH_WATER = 256 * 1024; // 256KB - request pause
68 this.TX_BUFFER_LOW_WATER = 64 * 1024; // 64KB - request resume
69 this.txPaused = new Set(); // Set of TCP session keys that are paused
70 }
71
72 /**
73 * Check if there's network data available in the ring buffer
74 */
75 hasNetworkData() {
76 return this.ringReader && this.ringReader.hasNetworkData();
77 }
78
79 /**
80 * Poll for network responses from ring buffer (synchronous, no waiting)
81 * Call this during poll_oneoff to check for incoming data
82 */
83 pollNetResponses() {
84 if (!this.ringReader) return;
85
86 // Process more bytes per poll to improve throughput
87 // BUT: Always process control messages (END, ERROR, etc.) to avoid deadlocks!
88 const MAX_DATA_BYTES_PER_POLL = 512 * 1024; // 512KB max DATA per poll cycle
89 let dataBytesThisPoll = 0;
90 let hitDataLimit = false;
91 let messagesRead = 0;
92
93 // Read messages from ring buffer (no polling needed - direct memory access!)
94 let msg;
95 while ((msg = this.ringReader.readNetworkMessage())) {
96 messagesRead++;
97 if (msg.type === NET_MSG_UDP_RECV) {
98 const parsed = this.ringReader.parseUdpRecv(msg.payload);
99 this._handleUdpResponse(parsed);
100 } else if (msg.type === NET_MSG_TCP_CONNECTED) {
101 const key = this.ringReader.parseKey(msg.payload);

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected