Preparing for other communication protocols

This commit is contained in:
Fabian Stamm 2020-06-16 09:50:08 +02:00
parent 904b986e22
commit 7d3cc9f947
6 changed files with 246 additions and 114 deletions

View File

@ -1,3 +1,6 @@
root=true
[*]
charset = utf-8
indent_size = 3
indent_style = space
indent_style = space
insert_final_newline = true

View File

@ -3,7 +3,7 @@ import Web from "./web";
import config from "./config";
import { DatabaseManager } from "./database/database";
import { createServer } from "http";
import { ConnectionManager } from "./connection";
import { WebsocketConnectionManager } from "./websocket";
import { LoggingTypes } from "@hibas123/logging";
import { readFileSync } from "fs";
@ -13,12 +13,14 @@ const version = JSON.parse(readFileSync("./package.json").toString()).version;
Logging.log("Starting Database version:", version);
DatabaseManager.init().then(() => {
const http = createServer(Web.callback());
ConnectionManager.bind(http);
const port = config.port || 5000;
http.listen(port, () => Logging.log("Listening on port:", port))
}).catch(err => {
Logging.error(err);
process.exit(-1);
})
DatabaseManager.init()
.then(() => {
const http = createServer(Web.callback());
WebsocketConnectionManager.bind(http);
const port = config.port || 5000;
http.listen(port, () => Logging.log("WS: Listening on port:", port));
})
.catch((err) => {
Logging.error(err);
process.exit(-1);
});

122
src/websocket.ts Normal file
View File

@ -0,0 +1,122 @@
import Logging from "@hibas123/nodelogging";
import { IncomingMessage, Server } from "http";
import * as WebSocket from "ws";
import { DatabaseManager } from "./database/database";
import { CollectionQuery, DocumentQuery, IQuery, ITypedQuery } from "./database/query";
import Session from "./database/session";
import { verifyJWT } from "./helper/jwt";
import nanoid = require("nanoid");
export class WebsocketConnectionManager {
static server: WebSocket.Server;
static bind(server: Server) {
this.server = new WebSocket.Server({ server });
this.server.on("connection", this.onConnection.bind(this));
}
private static async onConnection(socket: WebSocket, req: IncomingMessage) {
Logging.log("New Connection:");
const sendError = (error: string) => socket.send(JSON.stringify({ ns: "error_msg", data: error }));
const session = new Session(nanoid());
const query = new URL(req.url, "http://localhost").searchParams;
const database = query.get("database");
const db = DatabaseManager.getDatabase(database);
if (!db) {
sendError("Invalid Database!");
socket.close();
return;
}
const accesskey = query.get("accesskey");
if (db.accesskey) {
if (!accesskey || accesskey !== db.accesskey) {
sendError("Unauthorized!");
socket.close();
return;
}
}
const authkey = query.get("authkey");
if (authkey && db.publickey) {
let res = await verifyJWT(authkey, db.publickey);
if (!res || !res.uid) {
sendError("Invalid JWT");
socket.close();
return;
} else {
session.uid = res.uid;
}
}
const rootkey = query.get("rootkey");
if (rootkey && db.rootkey) {
if (rootkey === db.rootkey) {
session.root = true;
Logging.warning(`Somebody logged into ${database} via rootkey`);
}
}
const answer = (id: string, data: any, error: boolean = false) => {
if (error)
Logging.error(error as any);
socket.send(JSON.stringify({ ns: "message", data: { id, error, data } }));
}
const handler = new Map<string, ((data: any) => void)>();
handler.set("v2", async ({ id, query }) => db.run(Array.isArray(query) ? query : [query], session)
.then(res => answer(id, res))
.catch(err => answer(id, undefined, err))
);
// handler.set("bulk", async ({ id, query }) => db.run(query, session)
// .then(res => answer(id, res))
// .catch(err => answer(id, undefined, err))
// );
const SnapshotMap = new Map<string, string>();
handler.set("snapshot", async ({ id, query }: { id: string, query: ITypedQuery<"snapshot"> }) => {
db.snapshot(query, session, (data => {
socket.send(JSON.stringify({
ns: "snapshot", data: { id, data }
}));
})).then(s => {
answer(id, s.snaphot);
SnapshotMap.set(id, s.id);
}).catch(err => answer(id, undefined, err));
})
handler.set("unsubscribe", async ({ id }) => {
let i = SnapshotMap.get(id);
if (i) {
db.unsubscribe(i, session);
SnapshotMap.delete(i);
}
})
socket.on("message", async (rawData: string) => {
try {
let message: { ns: string, data: any } = JSON.parse(rawData);
let h = handler.get(message.ns);
if (h) {
h(message.data);
}
} catch (err) {
Logging.errorMessage("Unknown Error:");
Logging.error(err);
}
})
socket.on("close", () => {
Logging.log(`${session.id} has disconnected!`);
session.subscriptions.forEach(unsubscribe => unsubscribe());
session.subscriptions.clear();
socket.removeAllListeners();
})
}
}

View File

@ -1,112 +1,117 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Admin Interface</title>
<link
rel="stylesheet"
href="https://unpkg.com/@hibas123/theme@1/out/base.css"
/>
<link
rel="stylesheet"
href="https://unpkg.com/@hibas123/theme@1/out/light.css"
/>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Admin Interface</title>
<link rel="stylesheet" href="https://unpkg.com/@hibas123/theme/out/base.css">
<link rel="stylesheet" href="https://unpkg.com/@hibas123/theme/out/light.css">
<script src="https://unpkg.com/handlebars/dist/handlebars.min.js"></script>
<script src="https://unpkg.com/handlebars/dist/handlebars.min.js"></script>
<style>
#message {
visibility: hidden;
background-color: lightgreen;
border: 1px solid lime;
border-radius: 0.5rem;
padding: 1rem;
font-size: 1.5rem;
margin-bottom: 1rem;
}
<style>
#message {
visibility: hidden;
background-color: lightgreen;
border: 1px solid lime;
border-radius: .5rem;
padding: 1rem;
font-size: 1.5rem;
margin-bottom: 1rem;
}
.grid {
display: grid;
height: 100vh;
grid-template-columns: 360px auto;
}
.grid {
display: grid;
height: 100vh;
grid-template-columns: 360px auto;
}
#content {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border: 0;
}
</style>
</head>
<body>
<div class="grid">
<div style="border-right: 1px solid darkgrey; padding: 1rem;">
<h2>Navigation: </h2>
<ul class="list list-clickable">
<li onclick="loadView('settings');">Settings</li>
<li onclick="loadView('database', {full:true});">Databases</li>
<li onclick="loadView('database/new');">New Database</li>
</ul>
Databases:
<div id="dbs" class="list list-clickable" style="margin: 1rem;"></div>
#content {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border: 0;
}
</style>
</head>
<body>
<div class="grid">
<div style="border-right: 1px solid darkgrey; padding: 1rem;">
<h2>Navigation:</h2>
<ul class="list list-clickable">
<li onclick="loadView('settings');">Settings</li>
<li onclick="loadView('database', {full:true});">Databases</li>
<li onclick="loadView('database/new');">New Database</li>
</ul>
Databases:
<div
id="dbs"
class="list list-clickable"
style="margin: 1rem;"
></div>
</div>
<div style="position: relative;">
<iframe id="content"></iframe>
</div>
</div>
<div style="position:relative;">
<iframe id="content"></iframe>
</div>
</div>
<template>
<template> </template>
</template>
<script>
const key = new URL(window.location.href).searchParams.get("key");
const content = document.getElementById("content");
const base = new URL(window.location.href).host;
<script>
const key = new URL(window.location.href).searchParams.get("key");
const content = document.getElementById("content");
const base = new URL(window.location.href).host;
function getUrl(name, params, view = true) {
const url = new URL(window.location.href);
url.pathname = "/v1/admin/" + name;
for (let key in params || {})
url.searchParams.set(key, params[key]);
function getUrl(name, params, view = true) {
const url = new URL(window.location.href);
url.pathname = "/v1/admin/" + name;
for (let key in params || {})
url.searchParams.set(key, params[key]);
url.searchParams.set("key", key);
if (view) url.searchParams.set("view", "true");
url.searchParams.set("key", key);
if (view)
url.searchParams.set("view", "true");
return url.href;
}
return url.href;
}
function loadView(name, params) {
content.src = getUrl(name, params);
}
function loadView(name, params) {
content.src = getUrl(name, params);
}
loadView("settings");
loadView("settings")
const dbsul = document.getElementById("dbs");
function reloadDBs() {
fetch(getUrl("database", {}, false))
.then(res => res.json())
.then(databases => databases.map(database => `
const dbsul = document.getElementById("dbs");
function reloadDBs() {
fetch(getUrl("database", {}, false))
.then((res) => res.json())
.then((databases) =>
databases.map(
(database) => `
<div class="card margin elv-4">
<h3>${database}</h3>
<button class=btn onclick="loadView('data', {database:'${database}'})">Data</button>
<button class=btn onclick="loadView('collections', {database:'${database}'})">Collections</button>
<button class=btn onclick="loadView('collections/cleanup', {database:'${database}'})">Clean</button>
</div>`
))
.then(d => d.join("\n"))
.then(d => dbsul.innerHTML = d)
.catch(console.error)
)
)
.then((d) => d.join("\n"))
.then((d) => (dbsul.innerHTML = d))
.catch(console.error);
}
}
reloadDBs();
setInterval(reloadDBs, 5000);
</script>
</body>
</html>
reloadDBs();
setInterval(reloadDBs, 5000);
</script>
</body>
</html>

View File

@ -6,8 +6,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>{{title}}</title>
<link rel="stylesheet" href="https://unpkg.com/@hibas123/theme/out/base.css">
<link rel="stylesheet" href="https://unpkg.com/@hibas123/theme/out/light.css">
<link rel="stylesheet" href="https://unpkg.com/@hibas123/theme@/out/base.css">
<link rel="stylesheet" href="https://unpkg.com/@hibas123/theme@/out/light.css">
<style>
#message {
@ -83,4 +83,4 @@
</script>
</body>
</html>
</html>

View File

@ -6,8 +6,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>{{title}}</title>
<link rel="stylesheet" href="https://unpkg.com/@hibas123/theme/out/base.css">
<link rel="stylesheet" href="https://unpkg.com/@hibas123/theme/out/light.css">
<link rel="stylesheet" href="https://unpkg.com/@hibas123/theme@1/out/base.css">
<link rel="stylesheet" href="https://unpkg.com/@hibas123/theme@1/out/light.css">
<style>
table {
@ -37,18 +37,18 @@
<div class="margin" style="margin-top: 4rem;">
<h1>{{title}}</h1>
{{#if empty}}
<h3>No Data available!</h3>
<h3>No Data available!</h3>
{{else}}
<table style="overflow-x: auto">
{{#each table as |row|}}
<tr>
{{#each row as |col|}}
<td>{{col}}</td>
{{/each}}
</tr>
<table style="overflow-x: auto">
{{#each table as |row|}}
<tr>
{{#each row as |col|}}
<td>{{col}}</td>
{{/each}}
</table>
</tr>
{{/each}}
</table>
{{/if}}
</div>
</div>