UNPKG

@x5e/gink

Version:

an eventually consistent database

47 lines 2.4 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RoutingServerInstance = void 0; const Database_1 = require("./Database"); const LogBackedStore_1 = require("./LogBackedStore"); const Peer_1 = require("./Peer"); const buffer_1 = require("buffer"); const utils_1 = require("./utils"); class RoutingServerInstance extends Database_1.Database { constructor(filePath, identity, logger = console.log) { super(new LogBackedStore_1.LogBackedStore(filePath, false), identity, logger); this.filePath = filePath; this.logger = logger; } async onConnection(connection) { // Note: can't await before the connection is accepted, or you'll miss the greeting. this.logger(`Connection accepted for ${this.filePath}`); const sendFunc = (data) => connection.sendBytes(buffer_1.Buffer.from(data)); const closeFunc = () => { connection.close(); }; const connectionId = this.createConnectionId(); (0, utils_1.ensure)(typeof connectionId === "number" && connectionId > 0); const peer = new Peer_1.Peer(sendFunc, closeFunc); this.peers.set(connectionId, peer); connection.on("close", this.onClose.bind(this, connectionId)); connection.on("message", this.onMessage.bind(this, connectionId)); await this.ready; sendFunc(this.iHave.getGreetingMessageBytes()); } async onMessage(connectionId, webSocketMessage) { if (webSocketMessage.type === "utf8") { this.logger("Received Text Message: " + webSocketMessage.utf8Data); } else if (webSocketMessage.type === "binary") { this.logger(`Server for ${this.filePath} received binary message of ${webSocketMessage.binaryData.length} bytes from ${connectionId}`); await this.receiveMessage(webSocketMessage.binaryData, connectionId); } } onClose(connectionId, reasonCode, description) { // I'm intentionally leaving the peer object in the peers map just in case we get data from them. // thisClient.peers.delete(connectionId); // might still be processing data from peer this.logger(`Peer ${connectionId} disconnected from ${this.filePath} ${reasonCode}, ${description}`); } } exports.RoutingServerInstance = RoutingServerInstance; //# sourceMappingURL=RoutingServerInstance.js.map