UNPKG

@pureweb/platform-streaming-agent

Version:

The PureWeb platform streaming agent enables your game to communicate and stream through the PureWeb Platform

75 lines (74 loc) 3.17 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.EnvironmentServer = void 0; const sidecar_pb_1 = require("./proto/sidecar_pb"); const Log_1 = __importDefault(require("../../Log")); const ConnectionStates_1 = require("../../ConnectionStates"); class EnvironmentServer { constructor(agent, heartRate = EnvironmentServer.DEFAULT_HEART_RATE, timeout = EnvironmentServer.DEFAULT_TIMEOUT) { this.agent = agent; this.heartRate = heartRate; this.timeout = timeout; this.currentState = ConnectionStates_1.ConnectionStates.GRPC_READY; // Setup timeout if required if (timeout && timeout > 0) { setTimeout(() => { if (this.currentState !== ConnectionStates_1.ConnectionStates.GRPC_CONNECTED && this.connectionStateChangedCallback) { this.connectionStateChangedCallback(ConnectionStates_1.ConnectionStates.GRPC_TIMEOUT); } }, timeout); } } onStateChanged(handler) { this.connectionStateChangedCallback = handler; } get currentStatus() { return this.currentState; } /** gRPC Clients call this to open the heartbeat stream. * Once the stream is open the server will regularly send heartbeat messages to verify that the stream is still open. */ heartBeat(call) { if (this.currentState !== ConnectionStates_1.ConnectionStates.GRPC_CONNECTED) { this.currentState = ConnectionStates_1.ConnectionStates.GRPC_CONNECTED; if (this.connectionStateChangedCallback) { this.connectionStateChangedCallback(this.currentState); } } this.pulse = setInterval(() => this.sendHeartbeat(call), this.heartRate); } sendHeartbeat(call) { if (!call || call.cancelled) { this.stopHeartbeat(); } const response = new sidecar_pb_1.HeartBeatResponse(); const agentData = new sidecar_pb_1.Agent(); const environmentData = new sidecar_pb_1.AgentEnvironment(); agentData.setId(this.agent.id); environmentData.setId(this.agent.agentEnvironment.id); response.setAgent(agentData); response.setEnvironment(environmentData); call.write(response, (error) => { if (error) { this.stopHeartbeat(); Log_1.default.info(`GRPC client disconnected for agent ${this.agent.id}`); } else { Log_1.default.silly(`GRPC heartbeat sent for agent ${this.agent.id}`); } }); } stopHeartbeat() { clearInterval(this.pulse); this.currentState = ConnectionStates_1.ConnectionStates.GRPC_DISCONNECTED; if (this.connectionStateChangedCallback) { this.connectionStateChangedCallback(this.currentState); } } } exports.EnvironmentServer = EnvironmentServer; EnvironmentServer.DEFAULT_HEART_RATE = 5000; EnvironmentServer.DEFAULT_TIMEOUT = 0;