server connections handling

This commit is contained in:
Jan Prochazka
2020-05-01 11:41:18 +02:00
parent 44c19ad277
commit ca7eea8a05
11 changed files with 284 additions and 71 deletions

View File

@@ -1,24 +1,31 @@
const connections = require('./connections');
const socket = require('../utility/socket');
const { fork } = require('child_process');
const _ = require('lodash');
module.exports = {
opened: [],
closed: [],
handle_databases(conid, { databases }) {
const existing = this.opened.find(x => x.conid == conid);
const existing = this.opened.find((x) => x.conid == conid);
if (!existing) return;
existing.databases = databases;
socket.emitChanged(`database-list-changed-${conid}`);
},
handle_status(conid, { status }) {
const existing = this.opened.find((x) => x.conid == conid);
if (!existing) return;
existing.status = status;
socket.emitChanged(`server-status-changed`);
},
handle_error(conid, { error }) {
console.log(`Error in server connection ${conid}: ${error}`);
},
handle_ping() {
},
handle_ping() {},
async ensureOpened(conid) {
const existing = this.opened.find(x => x.conid == conid);
const existing = this.opened.find((x) => x.conid == conid);
if (existing) return existing;
const connection = await connections.get({ conid });
const subprocess = fork(process.argv[1], ['serverConnectionProcess']);
@@ -27,19 +34,75 @@ module.exports = {
subprocess,
databases: [],
connection,
status: {
name: 'pending',
},
disconnected: false,
};
this.opened.push(newOpened);
this.closed = this.closed.filter((x) => x != conid);
socket.emitChanged(`server-status-changed`);
// @ts-ignore
subprocess.on('message', ({ msgtype, ...message }) => {
if (newOpened.disconnected) return;
this[`handle_${msgtype}`](conid, message);
});
subprocess.on('exit', () => {
if (newOpened.disconnected) return;
this.opened = this.opened.filter((x) => x.conid != conid);
this.closed.push(conid);
socket.emitChanged(`server-status-changed`);
});
subprocess.send({ msgtype: 'connect', ...connection });
return newOpened;
},
close(conid) {
const existing = this.opened.find((x) => x.conid == conid);
if (existing) {
existing.disconnected = true;
existing.subprocess.kill();
this.opened = this.opened.filter((x) => x.conid != conid);
this.closed.push(conid);
}
},
listDatabases_meta: 'get',
async listDatabases({ conid }) {
const opened = await this.ensureOpened(conid);
return opened.databases;
},
serverStatus_meta: 'get',
async serverStatus() {
return {
...this.closed.reduce(
(res, conid) => ({
...res,
[conid]: {
name: 'error',
},
}),
{}
),
..._.mapValues(_.keyBy(this.opened, 'conid'), 'status'),
};
},
ping_meta: 'post',
async ping({ connections }) {
for (const conid of connections) {
const opened = await this.ensureOpened(conid);
opened.subprocess.send({ msgtype: 'ping' });
}
return { status: 'ok' };
},
refresh_meta: 'post',
async refresh({ conid }) {
this.close(conid);
await this.ensureOpened(conid);
return { status: 'ok' };
},
};