dockge/backend/socket-handlers/agent-proxy-socket-handler.ts

48 lines
2 KiB
TypeScript
Raw Normal View History

2023-12-19 17:48:20 +00:00
import { SocketHandler } from "../socket-handler.js";
import { DockgeServer } from "../dockge-server";
import { log } from "../log";
import { checkLogin, DockgeSocket } from "../util-server";
import { AgentSocket } from "../../common/agent-socket";
2023-12-20 02:11:00 +00:00
import { ALL_ENDPOINTS } from "../../common/util-common";
2023-12-19 17:48:20 +00:00
export class AgentProxySocketHandler extends SocketHandler {
create2(socket : DockgeSocket, server : DockgeServer, agentSocket : AgentSocket) {
// Agent - proxying requests if needed
socket.on("agent", async (endpoint : unknown, eventName : unknown, ...args : unknown[]) => {
try {
checkLogin(socket);
// Check Type
if (typeof(endpoint) !== "string") {
2023-12-20 02:11:00 +00:00
throw new Error("Endpoint must be a string: " + endpoint);
2023-12-19 17:48:20 +00:00
}
if (typeof(eventName) !== "string") {
throw new Error("Event name must be a string");
}
2023-12-20 02:11:00 +00:00
if (endpoint === ALL_ENDPOINTS) { // Send to all endpoints
log.debug("agent", "Sending to all endpoints: " + eventName);
socket.instanceManager.emitToAllEndpoints(eventName, ...args);
2023-12-19 17:48:20 +00:00
2023-12-20 02:11:00 +00:00
} else if (!endpoint || endpoint === socket.endpoint) { // Direct connection or matching endpoint
log.debug("agent", "Matched endpoint: " + eventName);
2023-12-19 17:48:20 +00:00
agentSocket.call(eventName, ...args);
2023-12-20 02:11:00 +00:00
2023-12-19 17:48:20 +00:00
} else {
2023-12-20 02:11:00 +00:00
log.debug("agent", "Proxying request to " + endpoint + " for " + eventName);
2023-12-25 19:18:56 +00:00
await socket.instanceManager.emitToEndpoint(endpoint, eventName, ...args);
2023-12-19 17:48:20 +00:00
}
} catch (e) {
if (e instanceof Error) {
log.warn("agent", e.message);
}
}
});
}
create(socket : DockgeSocket, server : DockgeServer) {
throw new Error("Method not implemented. Please use create2 instead.");
}
}