-
Notifications
You must be signed in to change notification settings - Fork 284
Expand file tree
/
Copy pathbridge.js
More file actions
106 lines (93 loc) · 3.41 KB
/
bridge.js
File metadata and controls
106 lines (93 loc) · 3.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import net from "net";
import {Parser} from 'pickleparser';
const HOST = "127.0.0.1";
const PORT = 57570;
const MAX_MSG_SIZE = 10 * 1024 * 1024;
const TIMEOUT = 30_000; // 30秒超时
/**
* Node.js -> Python 请求包(保持 JSON 格式,Python 端需要 json.loads)
*/
function encodePacket(obj) {
const jsonStr = JSON.stringify(obj);
const payload = Buffer.from(jsonStr, "utf-8");
const header = Buffer.alloc(4);
header.writeUInt32BE(payload.length, 0);
return Buffer.concat([header, payload]);
}
/**
* Python -> Node.js 响应包(pickle 解码)
*/
function decodePacket(buffer) {
const parser = new Parser();
return parser.parse(buffer);
}
export async function netCallPythonMethod(script_path, methodName, env, ...args) {
return new Promise((resolve, reject) => {
const client = new net.Socket();
let recvBuffer = Buffer.alloc(0);
let expectedLength = null;
// 超时处理
const timer = setTimeout(() => {
client.destroy();
reject(new Error("Python守护进程响应超时"));
}, TIMEOUT);
client.connect(PORT, HOST, () => {
const req = {
script_path,
method_name: methodName,
env,
args,
};
const packet = encodePacket(req);
client.write(packet);
});
client.on("data", (chunk) => {
recvBuffer = Buffer.concat([recvBuffer, chunk]);
while (true) {
if (expectedLength === null) {
if (recvBuffer.length >= 4) {
expectedLength = recvBuffer.readUInt32BE(0);
recvBuffer = recvBuffer.slice(4);
if (expectedLength <= 0 || expectedLength > MAX_MSG_SIZE) {
clearTimeout(timer);
client.destroy();
return reject(new Error("Invalid packet length"));
}
} else {
break;
}
}
if (expectedLength !== null && recvBuffer.length >= expectedLength) {
const payload = recvBuffer.slice(0, expectedLength);
recvBuffer = recvBuffer.slice(expectedLength);
expectedLength = null;
try {
const resp = decodePacket(payload);
clearTimeout(timer);
client.destroy();
if (resp && typeof resp === "object" && resp.error) {
reject(new Error(`Python错误: ${resp.error}\n${resp.traceback || ""}`));
} else if (resp && typeof resp === "object" && "result" in resp) {
resolve(resp.result);
} else {
resolve(resp);
}
} catch (e) {
clearTimeout(timer);
client.destroy();
reject(e);
}
} else {
break;
}
}
});
client.on("error", (err) => {
clearTimeout(timer);
reject(err);
});
client.on("close", () => {
clearTimeout(timer);
});
});
}