Preparing for other communication protocols
This commit is contained in:
parent
904b986e22
commit
7d3cc9f947
@ -1,3 +1,6 @@
|
||||
root=true
|
||||
[*]
|
||||
charset = utf-8
|
||||
indent_size = 3
|
||||
indent_style = space
|
||||
insert_final_newline = true
|
14
src/index.ts
14
src/index.ts
@ -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(() => {
|
||||
DatabaseManager.init()
|
||||
.then(() => {
|
||||
const http = createServer(Web.callback());
|
||||
ConnectionManager.bind(http);
|
||||
WebsocketConnectionManager.bind(http);
|
||||
const port = config.port || 5000;
|
||||
http.listen(port, () => Logging.log("Listening on port:", port))
|
||||
}).catch(err => {
|
||||
http.listen(port, () => Logging.log("WS: Listening on port:", port));
|
||||
})
|
||||
.catch((err) => {
|
||||
Logging.error(err);
|
||||
process.exit(-1);
|
||||
})
|
||||
});
|
||||
|
122
src/websocket.ts
Normal file
122
src/websocket.ts
Normal 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();
|
||||
})
|
||||
}
|
||||
}
|
@ -1,13 +1,18 @@
|
||||
<!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">
|
||||
<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">
|
||||
<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"
|
||||
/>
|
||||
|
||||
<script src="https://unpkg.com/handlebars/dist/handlebars.min.js"></script>
|
||||
|
||||
@ -16,7 +21,7 @@
|
||||
visibility: hidden;
|
||||
background-color: lightgreen;
|
||||
border: 1px solid lime;
|
||||
border-radius: .5rem;
|
||||
border-radius: 0.5rem;
|
||||
padding: 1rem;
|
||||
font-size: 1.5rem;
|
||||
margin-bottom: 1rem;
|
||||
@ -37,29 +42,30 @@
|
||||
border: 0;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<body>
|
||||
<div class="grid">
|
||||
<div style="border-right: 1px solid darkgrey; padding: 1rem;">
|
||||
<h2>Navigation: </h2>
|
||||
<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
|
||||
id="dbs"
|
||||
class="list list-clickable"
|
||||
style="margin: 1rem;"
|
||||
></div>
|
||||
</div>
|
||||
<div style="position:relative;">
|
||||
<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");
|
||||
@ -73,8 +79,7 @@
|
||||
url.searchParams.set(key, params[key]);
|
||||
|
||||
url.searchParams.set("key", key);
|
||||
if (view)
|
||||
url.searchParams.set("view", "true");
|
||||
if (view) url.searchParams.set("view", "true");
|
||||
|
||||
return url.href;
|
||||
}
|
||||
@ -83,30 +88,30 @@
|
||||
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 => `
|
||||
.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>
|
||||
|
||||
</body>
|
||||
</html>
|
@ -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 {
|
||||
|
@ -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 {
|
||||
|
Reference in New Issue
Block a user