Compare commits
29 Commits
v2.0.0-bet
...
v2.0.0-bet
Author | SHA1 | Date | |
---|---|---|---|
b220c223ef | |||
5c2934495e | |||
f45746984f | |||
fcf8845664 | |||
25f2bd2ae4 | |||
9674807093 | |||
a6e6a01cd0 | |||
24e46922c9 | |||
ff468410ad | |||
cb67258ef3 | |||
39a613a3f1 | |||
22cb90b6f6 | |||
b3465ea96d | |||
c2cea4c15a | |||
c48212cc17 | |||
bb291c207d | |||
5cbc445597 | |||
794820e1d3 | |||
16e5753fc6 | |||
8e4bce1dbf | |||
8d8ac89ddf | |||
8a2abcc543 | |||
f1d475580c | |||
d6a565b2cb | |||
7fe18a0037 | |||
7d3cc9f947 | |||
0bfdbce908 | |||
68295c148d | |||
2a62c3d3ac |
@ -4,8 +4,9 @@ name: default
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Build with node
|
- name: Build with node
|
||||||
image: node:12
|
image: node:14
|
||||||
commands:
|
commands:
|
||||||
|
- npm config set registry https://npm.hibas123.de
|
||||||
- npm install
|
- npm install
|
||||||
- npm run build
|
- npm run build
|
||||||
- name: Publish to docker
|
- name: Publish to docker
|
||||||
@ -19,3 +20,5 @@ steps:
|
|||||||
repo: hibas123.azurecr.io/realtimedb
|
repo: hibas123.azurecr.io/realtimedb
|
||||||
registry: hibas123.azurecr.io
|
registry: hibas123.azurecr.io
|
||||||
debug: true
|
debug: true
|
||||||
|
when:
|
||||||
|
branch: [master]
|
||||||
|
@ -1,5 +1,8 @@
|
|||||||
|
root=true
|
||||||
[*]
|
[*]
|
||||||
charset = utf-8
|
charset = utf-8
|
||||||
indent_size = 3
|
indent_size = 3
|
||||||
indent_style = space
|
indent_style = space
|
||||||
insert_final_newline = true
|
insert_final_newline = true
|
||||||
|
[*.yml]
|
||||||
|
indent_size = 2
|
||||||
|
2
.env
2
.env
@ -1,4 +1,4 @@
|
|||||||
PORT = 5000
|
PORT = 5000
|
||||||
ADMIN_KEY = test
|
ADMIN_KEY = test
|
||||||
ACCESS_LOG = true
|
ACCESS_LOG = true
|
||||||
DEV = true
|
DEV = true
|
||||||
|
20
.vscode/launch.json
vendored
Normal file
20
.vscode/launch.json
vendored
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
// Use IntelliSense to learn about possible attributes.
|
||||||
|
// Hover to view descriptions of existing attributes.
|
||||||
|
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||||
|
"version": "0.2.0",
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"type": "pwa-node",
|
||||||
|
"request": "launch",
|
||||||
|
"name": "Launch Program",
|
||||||
|
"skipFiles": [
|
||||||
|
"<node_internals>/**"
|
||||||
|
],
|
||||||
|
"program": "${workspaceFolder}\\lib\\index.js",
|
||||||
|
"outFiles": [
|
||||||
|
"${workspaceFolder}/**/*.js"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
FROM node:12
|
FROM node:14
|
||||||
|
|
||||||
LABEL maintainer="Fabian Stamm <dev@fabianstamm.de>"
|
LABEL maintainer="Fabian Stamm <dev@fabianstamm.de>"
|
||||||
|
|
||||||
@ -8,6 +8,8 @@ LABEL maintainer="Fabian Stamm <dev@fabianstamm.de>"
|
|||||||
RUN mkdir -p /usr/src/app
|
RUN mkdir -p /usr/src/app
|
||||||
WORKDIR /usr/src/app
|
WORKDIR /usr/src/app
|
||||||
|
|
||||||
|
RUN npm config set registry https://npm.hibas123.de/
|
||||||
|
|
||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
|
|
||||||
COPY ["package.json", "package-lock.json", "/usr/src/app/"]
|
COPY ["package.json", "package-lock.json", "/usr/src/app/"]
|
||||||
@ -20,4 +22,4 @@ VOLUME [ "/usr/src/app/databases", "/usr/src/app/logs" ]
|
|||||||
|
|
||||||
EXPOSE 5000/tcp
|
EXPOSE 5000/tcp
|
||||||
|
|
||||||
CMD ["npm", "run", "start"]
|
CMD ["npm", "run", "start"]
|
||||||
|
1418
package-lock.json
generated
1418
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
89
package.json
89
package.json
@ -1,47 +1,46 @@
|
|||||||
{
|
{
|
||||||
"name": "@hibas123/realtimedb",
|
"name": "@hibas123/realtimedb",
|
||||||
"version": "2.0.0-beta.9",
|
"version": "2.0.0-beta.22",
|
||||||
"description": "",
|
"description": "",
|
||||||
"main": "lib/index.js",
|
"main": "lib/index.js",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "node lib/index.js",
|
"start": "node lib/index.js",
|
||||||
"build": "tsc",
|
"build": "tsc",
|
||||||
"watch-ts": "tsc -w",
|
"watch": "nodemon -e ts --exec ts-node src/index.ts",
|
||||||
"watch-node": "nodemon --ignore *.ts lib/index.js",
|
"build-docker": "npm run build && docker build -t realtimedb .",
|
||||||
"watch": "concurrently \"npm:watch-*\"",
|
"prepublishOnly": "tsc"
|
||||||
"build-docker": "npm run build && docker build -t realtimedb .",
|
},
|
||||||
"prepublishOnly": "tsc"
|
"author": "Fabian Stamm <dev@fabianstamm.de>",
|
||||||
},
|
"license": "ISC",
|
||||||
"author": "Fabian Stamm <dev@fabianstamm.de>",
|
"devDependencies": {
|
||||||
"license": "ISC",
|
"@types/dotenv": "^8.2.0",
|
||||||
"devDependencies": {
|
"@types/jsonwebtoken": "^8.5.0",
|
||||||
"@types/dotenv": "^8.2.0",
|
"@types/koa": "^2.11.6",
|
||||||
"@types/jsonwebtoken": "^8.3.8",
|
"@types/koa-router": "^7.4.1",
|
||||||
"@types/koa": "^2.11.2",
|
"@types/leveldown": "^4.0.2",
|
||||||
"@types/koa-router": "^7.4.0",
|
"@types/levelup": "^4.3.0",
|
||||||
"@types/leveldown": "^4.0.2",
|
"@types/nanoid": "^2.1.0",
|
||||||
"@types/levelup": "^4.3.0",
|
"@types/node": "^14.14.5",
|
||||||
"@types/nanoid": "^2.1.0",
|
"@types/ws": "^7.2.8",
|
||||||
"@types/node": "^13.9.3",
|
"concurrently": "^5.3.0",
|
||||||
"@types/ws": "^7.2.3",
|
"nodemon": "^2.0.6",
|
||||||
"concurrently": "^5.1.0",
|
"ts-node": "^9.0.0",
|
||||||
"nodemon": "^2.0.2",
|
"typescript": "^4.0.5"
|
||||||
"typescript": "^3.8.3"
|
},
|
||||||
},
|
"dependencies": {
|
||||||
"dependencies": {
|
"@hibas123/nodelogging": "^2.4.5",
|
||||||
"@hibas123/nodelogging": "^2.1.5",
|
"@hibas123/utils": "^2.2.16",
|
||||||
"@hibas123/utils": "^2.2.3",
|
"dotenv": "^8.2.0",
|
||||||
"dotenv": "^8.2.0",
|
"handlebars": "^4.7.6",
|
||||||
"handlebars": "^4.7.3",
|
"jsonwebtoken": "^8.5.1",
|
||||||
"jsonwebtoken": "^8.5.1",
|
"koa": "^2.13.0",
|
||||||
"koa": "^2.11.0",
|
"koa-body": "^4.2.0",
|
||||||
"koa-body": "^4.1.1",
|
"koa-router": "^9.4.0",
|
||||||
"koa-router": "^8.0.8",
|
"leveldown": "^5.6.0",
|
||||||
"leveldown": "^5.5.1",
|
"levelup": "^4.4.0",
|
||||||
"levelup": "^4.3.2",
|
"nanoid": "^3.1.16",
|
||||||
"nanoid": "^2.1.11",
|
"what-the-pack": "^2.0.3",
|
||||||
"what-the-pack": "^2.0.3",
|
"ws": "^7.3.1"
|
||||||
"ws": "^7.2.3"
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -1,25 +1,24 @@
|
|||||||
import Logging from "@hibas123/nodelogging";
|
import Logging from "@hibas123/nodelogging";
|
||||||
import * as dotenv from "dotenv";
|
import * as dotenv from "dotenv";
|
||||||
import { LoggingTypes } from "@hibas123/logging";
|
import { LoggingTypes } from "@hibas123/logging";
|
||||||
dotenv.config()
|
dotenv.config();
|
||||||
|
|
||||||
|
|
||||||
interface IConfig {
|
interface IConfig {
|
||||||
port: number;
|
port: number;
|
||||||
admin: string;
|
admin: string;
|
||||||
access_log: boolean;
|
access_log: boolean;
|
||||||
dev: boolean
|
dev: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const config: IConfig = {
|
const config: IConfig = {
|
||||||
port: Number(process.env.PORT),
|
port: Number(process.env.PORT),
|
||||||
access_log: (process.env.ACCESS_LOG || "").toLowerCase() === "true",
|
access_log: (process.env.ACCESS_LOG || "").toLowerCase() === "true",
|
||||||
admin: process.env.ADMIN_KEY,
|
admin: process.env.ADMIN_KEY,
|
||||||
dev: (process.env.DEV || "").toLowerCase() === "true"
|
dev: (process.env.DEV || "").toLowerCase() === "true",
|
||||||
}
|
};
|
||||||
|
|
||||||
if (config.dev) {
|
if (config.dev) {
|
||||||
Logging.logLevel = LoggingTypes.Log;
|
Logging.logLevel = LoggingTypes.Log;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default config;
|
export default config;
|
||||||
|
@ -1,14 +1,27 @@
|
|||||||
import { Rules } from "./rules";
|
|
||||||
import Settings from "../settings";
|
import Settings from "../settings";
|
||||||
import getLevelDB, { LevelDB, deleteLevelDB, resNull } from "../storage";
|
import getLevelDB, { deleteLevelDB, resNull } from "../storage";
|
||||||
import DocumentLock from "./lock";
|
import DocumentLock from "./lock";
|
||||||
import { DocumentQuery, CollectionQuery, Query, QueryError, ITypedQuery, IQuery } from "./query";
|
import {
|
||||||
|
DocumentQuery,
|
||||||
|
CollectionQuery,
|
||||||
|
Query,
|
||||||
|
QueryError,
|
||||||
|
ITypedQuery,
|
||||||
|
IQuery,
|
||||||
|
} from "./query";
|
||||||
import Logging from "@hibas123/nodelogging";
|
import Logging from "@hibas123/nodelogging";
|
||||||
import Session from "./session";
|
import Session from "./session";
|
||||||
import nanoid = require("nanoid/generate");
|
import nanoid = require("nanoid");
|
||||||
import { Observable } from "@hibas123/utils";
|
import { Observable } from "@hibas123/utils";
|
||||||
|
import { RuleRunner } from "../rules/compile";
|
||||||
|
import compileRule from "../rules";
|
||||||
|
import { RuleError } from "../rules/error";
|
||||||
|
|
||||||
const ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
const ALPHABET =
|
||||||
|
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
||||||
|
|
||||||
|
const longNanoId = nanoid.customAlphabet(ALPHABET, 32);
|
||||||
|
const shortNanoId = nanoid.customAlphabet(ALPHABET, 16);
|
||||||
|
|
||||||
// interface ITransaction {
|
// interface ITransaction {
|
||||||
// queries: ITypedQuery<IWriteQueries>[];
|
// queries: ITypedQuery<IWriteQueries>[];
|
||||||
@ -20,15 +33,20 @@ export class DatabaseManager {
|
|||||||
static async init() {
|
static async init() {
|
||||||
let databases = await Settings.getDatabases();
|
let databases = await Settings.getDatabases();
|
||||||
|
|
||||||
databases.forEach(dbconfig => {
|
databases.forEach((dbconfig) => {
|
||||||
let db = new Database(dbconfig.name, dbconfig.accesskey, dbconfig.rules, dbconfig.publickey, dbconfig.rootkey);
|
let db = new Database(
|
||||||
|
dbconfig.name,
|
||||||
|
dbconfig.accesskey,
|
||||||
|
dbconfig.rules,
|
||||||
|
dbconfig.publickey,
|
||||||
|
dbconfig.rootkey
|
||||||
|
);
|
||||||
this.databases.set(dbconfig.name, db);
|
this.databases.set(dbconfig.name, db);
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
static async addDatabase(name: string) {
|
static async addDatabase(name: string) {
|
||||||
if (this.databases.has(name))
|
if (this.databases.has(name)) throw new Error("Database already exists!");
|
||||||
throw new Error("Database already exists!");
|
|
||||||
|
|
||||||
await Settings.addDatabase(name);
|
await Settings.addDatabase(name);
|
||||||
let database = new Database(name);
|
let database = new Database(name);
|
||||||
@ -41,11 +59,11 @@ export class DatabaseManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static async deleteDatabase(name: string) {
|
static async deleteDatabase(name: string) {
|
||||||
let db = this.databases.get(name)
|
let db = this.databases.get(name);
|
||||||
if (db) {
|
if (db) {
|
||||||
await Settings.deleteDatabase(name);
|
await Settings.deleteDatabase(name);
|
||||||
await db.stop();
|
await db.stop();
|
||||||
await deleteLevelDB(db.name)
|
await deleteLevelDB(db.name);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -58,34 +76,44 @@ export type Change = {
|
|||||||
collection: string;
|
collection: string;
|
||||||
type: ChangeTypes;
|
type: ChangeTypes;
|
||||||
sender: string;
|
sender: string;
|
||||||
}
|
};
|
||||||
|
|
||||||
|
|
||||||
export class Database {
|
export class Database {
|
||||||
public static getKey(collectionid: string, documentid?: string) {
|
public static getKey(collectionid: string, documentid?: string) {
|
||||||
return `${collectionid || ""}/${documentid || ""}`;
|
return `${collectionid || ""}/${documentid || ""}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
private level = getLevelDB(this.name);
|
#level = getLevelDB(this.name);
|
||||||
|
|
||||||
get data() {
|
get data() {
|
||||||
return this.level.data;
|
return this.#level.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
get collections() {
|
get collections() {
|
||||||
return this.level.collection;
|
return this.#level.collection;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#rules: RuleRunner;
|
||||||
|
#rawRules?: string;
|
||||||
|
|
||||||
public rules: Rules;
|
get rawRules() {
|
||||||
private locks = new DocumentLock()
|
return this.#rawRules;
|
||||||
public collectionLocks = new DocumentLock()
|
}
|
||||||
|
|
||||||
|
get rules() {
|
||||||
|
return this.#rules;
|
||||||
|
}
|
||||||
|
|
||||||
|
public connections = 0;
|
||||||
|
|
||||||
|
private locks = new DocumentLock();
|
||||||
|
public collectionLocks = new DocumentLock();
|
||||||
|
|
||||||
public changeListener = new Map<string, Set<(change: Change[]) => void>>();
|
public changeListener = new Map<string, Set<(change: Change[]) => void>>();
|
||||||
public collectionChangeListener = new Observable<{
|
public collectionChangeListener = new Observable<{
|
||||||
key: string;
|
key: string;
|
||||||
id: string;
|
id: string;
|
||||||
type: "create" | "delete"
|
type: "create" | "delete";
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
toJSON() {
|
toJSON() {
|
||||||
@ -93,19 +121,48 @@ export class Database {
|
|||||||
name: this.name,
|
name: this.name,
|
||||||
accesskey: this.accesskey,
|
accesskey: this.accesskey,
|
||||||
publickey: this.publickey,
|
publickey: this.publickey,
|
||||||
rules: this.rules
|
rules: this.#rules,
|
||||||
}
|
connections: this.connections,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
constructor(public name: string, public accesskey?: string, rawRules?: string, public publickey?: string, public rootkey?: string) {
|
constructor(
|
||||||
if (rawRules)
|
public name: string,
|
||||||
this.rules = new Rules(rawRules);
|
public accesskey?: string,
|
||||||
|
rawRules?: string,
|
||||||
|
public publickey?: string,
|
||||||
|
public rootkey?: string
|
||||||
|
) {
|
||||||
|
if (rawRules) this.applyRules(rawRules);
|
||||||
|
}
|
||||||
|
|
||||||
|
private applyRules(rawRules: string): undefined | RuleError {
|
||||||
|
try {
|
||||||
|
JSON.parse(rawRules);
|
||||||
|
Logging.warning(
|
||||||
|
"Found old rule! Replacing with a 100% permissive one!"
|
||||||
|
);
|
||||||
|
rawRules =
|
||||||
|
"service realtimedb {\n match /* {\n allow read, write, list: if false; \n }\n}";
|
||||||
|
// still json, so switching to
|
||||||
|
} catch (err) {}
|
||||||
|
|
||||||
|
let { runner, error } = compileRule(rawRules);
|
||||||
|
if (error) {
|
||||||
|
Logging.warning("Found error in existing config!", error);
|
||||||
|
runner = compileRule("service realtimesb {}").runner;
|
||||||
|
}
|
||||||
|
this.#rules = runner;
|
||||||
|
this.#rawRules = rawRules;
|
||||||
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
async setRules(rawRules: string) {
|
async setRules(rawRules: string) {
|
||||||
let rules = new Rules(rawRules);
|
const { runner, error } = compileRule(rawRules);
|
||||||
|
if (error) return error;
|
||||||
await Settings.setDatabaseRules(this.name, rawRules);
|
await Settings.setDatabaseRules(this.name, rawRules);
|
||||||
this.rules = rules;
|
this.#rules = runner;
|
||||||
|
this.#rawRules = rawRules;
|
||||||
}
|
}
|
||||||
|
|
||||||
async setAccessKey(key: string) {
|
async setAccessKey(key: string) {
|
||||||
@ -123,7 +180,10 @@ export class Database {
|
|||||||
this.publickey = key;
|
this.publickey = key;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async resolve(path: string[], create = false): Promise<{ collection: string, document: string, collectionKey: string }> {
|
public async resolve(
|
||||||
|
path: string[],
|
||||||
|
create = false
|
||||||
|
): Promise<{ collection: string; document: string; collectionKey: string }> {
|
||||||
path = [...path]; // Create modifiable copy
|
path = [...path]; // Create modifiable copy
|
||||||
let collectionID: string = undefined;
|
let collectionID: string = undefined;
|
||||||
let documentKey = path.length % 2 === 0 ? path.pop() : undefined;
|
let documentKey = path.length % 2 === 0 ? path.pop() : undefined;
|
||||||
@ -132,17 +192,20 @@ export class Database {
|
|||||||
const lock = await this.collectionLocks.lock(key);
|
const lock = await this.collectionLocks.lock(key);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
collectionID = await this.collections.get(key).then(r => r.toString()).catch(resNull);
|
collectionID = await this.collections
|
||||||
|
.get(key)
|
||||||
|
.then((r) => r.toString())
|
||||||
|
.catch(resNull);
|
||||||
if (!collectionID && create) {
|
if (!collectionID && create) {
|
||||||
collectionID = nanoid(ALPHABET, 32);
|
collectionID = longNanoId();
|
||||||
await this.collections.put(key, collectionID);
|
await this.collections.put(key, collectionID);
|
||||||
setImmediate(() => {
|
setImmediate(() => {
|
||||||
this.collectionChangeListener.send({
|
this.collectionChangeListener.send({
|
||||||
id: collectionID,
|
id: collectionID,
|
||||||
key,
|
key,
|
||||||
type: "create"
|
type: "create",
|
||||||
})
|
});
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
lock();
|
lock();
|
||||||
@ -151,16 +214,16 @@ export class Database {
|
|||||||
return {
|
return {
|
||||||
collection: collectionID,
|
collection: collectionID,
|
||||||
document: documentKey,
|
document: documentKey,
|
||||||
collectionKey: key
|
collectionKey: key,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private sendChanges(changes: Change[]) {
|
private sendChanges(changes: Change[]) {
|
||||||
let col = new Map<string, Map<string, Change[]>>();
|
let col = new Map<string, Map<string, Change[]>>();
|
||||||
changes.forEach(change => {
|
changes.forEach((change) => {
|
||||||
let e = col.get(change.collection);
|
let e = col.get(change.collection);
|
||||||
if (!e) {
|
if (!e) {
|
||||||
e = new Map()
|
e = new Map();
|
||||||
col.set(change.collection, e);
|
col.set(change.collection, e);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -171,66 +234,67 @@ export class Database {
|
|||||||
}
|
}
|
||||||
|
|
||||||
d.push(change);
|
d.push(change);
|
||||||
})
|
});
|
||||||
|
|
||||||
setImmediate(() => {
|
setImmediate(() => {
|
||||||
for (let [collection, documents] of col.entries()) {
|
for (let [collection, documents] of col.entries()) {
|
||||||
let collectionChanges = [];
|
let collectionChanges = [];
|
||||||
for (let [document, documentChanges] of documents.entries()) {
|
for (let [document, documentChanges] of documents.entries()) {
|
||||||
let s = this.changeListener.get(Database.getKey(collection, document));
|
let s = this.changeListener.get(
|
||||||
if (s)
|
Database.getKey(collection, document)
|
||||||
s.forEach(e => setImmediate(() => e(documentChanges)));
|
);
|
||||||
|
if (s) s.forEach((e) => setImmediate(() => e(documentChanges)));
|
||||||
|
|
||||||
collectionChanges.push(...documentChanges);
|
collectionChanges.push(...documentChanges);
|
||||||
}
|
}
|
||||||
let s = this.changeListener.get(Database.getKey(collection))
|
let s = this.changeListener.get(Database.getKey(collection));
|
||||||
if (s)
|
if (s) s.forEach((e) => setImmediate(() => e(collectionChanges)));
|
||||||
s.forEach(e => setImmediate(() => e(collectionChanges)))
|
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private validate(query: ITypedQuery<any>) {
|
private validate(query: ITypedQuery<any>) {
|
||||||
const inv = new QueryError("Malformed query!");
|
const inv = new QueryError("Malformed query!");
|
||||||
if (!query || typeof query !== "object")
|
if (!query || typeof query !== "object") throw inv;
|
||||||
throw inv;
|
|
||||||
|
|
||||||
if (!query.type)
|
if (!query.type) throw inv;
|
||||||
throw inv;
|
|
||||||
|
|
||||||
if (!query.path)
|
if (!query.path) throw inv;
|
||||||
throw inv;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async run(queries: IQuery[], session: Session) {
|
async run(queries: IQuery[], session: Session) {
|
||||||
let resolve: { path: string[], create: boolean, resolved?: [string, string, string] }[] = [];
|
let resolve: {
|
||||||
|
path: string[];
|
||||||
|
create: boolean;
|
||||||
|
resolved?: [string, string, string];
|
||||||
|
}[] = [];
|
||||||
|
|
||||||
const addToResolve = (path: string[], create?: boolean) => {
|
const addToResolve = (path: string[], create?: boolean) => {
|
||||||
let entry = resolve.find(e => { //TODO: Find may be slow...
|
let entry = resolve.find((e) => {
|
||||||
if (e.path.length !== path.length)
|
//TODO: Find may be slow...
|
||||||
return false;
|
if (e.path.length !== path.length) return false;
|
||||||
for (let i = 0; i < e.path.length; i++) {
|
for (let i = 0; i < e.path.length; i++) {
|
||||||
if (e.path[i] !== path[i])
|
if (e.path[i] !== path[i]) return false;
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
})
|
});
|
||||||
|
|
||||||
if (!entry) {
|
if (!entry) {
|
||||||
entry = {
|
entry = {
|
||||||
path,
|
path,
|
||||||
create
|
create,
|
||||||
}
|
};
|
||||||
resolve.push(entry);
|
resolve.push(entry);
|
||||||
}
|
}
|
||||||
|
|
||||||
entry.create = entry.create || create;
|
entry.create = entry.create || create;
|
||||||
|
|
||||||
return entry;
|
return entry;
|
||||||
}
|
};
|
||||||
|
|
||||||
const isBatch = queries.length > 1;
|
const isBatch = queries.length > 1;
|
||||||
let parsed = queries.map(rawQuery => {
|
let parsed = queries.map((rawQuery) => {
|
||||||
|
Logging.debug("Running query:", rawQuery.type);
|
||||||
this.validate(rawQuery);
|
this.validate(rawQuery);
|
||||||
const isCollection = rawQuery.path.length % 2 === 1;
|
const isCollection = rawQuery.path.length % 2 === 1;
|
||||||
|
|
||||||
@ -242,12 +306,11 @@ export class Database {
|
|||||||
throw new Error("There are queries that are not batch compatible!");
|
throw new Error("There are queries that are not batch compatible!");
|
||||||
|
|
||||||
let path = addToResolve(rawQuery.path, query.createCollection);
|
let path = addToResolve(rawQuery.path, query.createCollection);
|
||||||
if (query.additionalLock)
|
if (query.additionalLock) addToResolve(query.additionalLock);
|
||||||
addToResolve(query.additionalLock);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
path,
|
path,
|
||||||
query
|
query,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -255,12 +318,13 @@ export class Database {
|
|||||||
|
|
||||||
let locks: (() => void)[] = [];
|
let locks: (() => void)[] = [];
|
||||||
for (let e of resolve) {
|
for (let e of resolve) {
|
||||||
let { collection, document, collectionKey } = await this.resolve(e.path, e.create);
|
let { collection, document, collectionKey } = await this.resolve(
|
||||||
|
e.path,
|
||||||
|
e.create
|
||||||
|
);
|
||||||
e.resolved = [collection, document, collectionKey];
|
e.resolved = [collection, document, collectionKey];
|
||||||
|
|
||||||
locks.push(
|
locks.push(await this.locks.lock(collection, document));
|
||||||
await this.locks.lock(collection, document)
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let result = [];
|
let result = [];
|
||||||
@ -269,46 +333,48 @@ export class Database {
|
|||||||
let changes: Change[] = [];
|
let changes: Change[] = [];
|
||||||
for (let e of parsed) {
|
for (let e of parsed) {
|
||||||
result.push(
|
result.push(
|
||||||
await e.query.run(e.path.resolved[0], e.path.resolved[1], batch, e.path.resolved[2])
|
await e.query.run(
|
||||||
|
e.path.resolved[0],
|
||||||
|
e.path.resolved[1],
|
||||||
|
batch,
|
||||||
|
e.path.resolved[2]
|
||||||
|
)
|
||||||
);
|
);
|
||||||
changes.push(...e.query.changes);
|
changes.push(...e.query.changes);
|
||||||
}
|
}
|
||||||
if (batch.length > 0)
|
if (batch.length > 0) await batch.write();
|
||||||
await batch.write();
|
|
||||||
|
|
||||||
this.sendChanges(changes);
|
this.sendChanges(changes);
|
||||||
} finally {
|
} finally {
|
||||||
locks.forEach(lock => lock());
|
locks.forEach((lock) => lock());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isBatch)
|
if (isBatch) return result;
|
||||||
return result;
|
else return result[0];
|
||||||
else
|
|
||||||
return result[0]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async snapshot(rawQuery: ITypedQuery<"snapshot">, session: Session, onchange: (change: any) => void) {
|
async snapshot(
|
||||||
|
rawQuery: ITypedQuery<"snapshot">,
|
||||||
|
session: Session,
|
||||||
|
onchange: (change: any) => void
|
||||||
|
) {
|
||||||
Logging.debug("Snaphot request:", rawQuery.path);
|
Logging.debug("Snaphot request:", rawQuery.path);
|
||||||
this.validate(rawQuery);
|
this.validate(rawQuery);
|
||||||
|
|
||||||
if (rawQuery.type !== "snapshot")
|
if (rawQuery.type !== "snapshot") throw new Error("Invalid query type!");
|
||||||
throw new Error("Invalid query type!");
|
|
||||||
|
|
||||||
const isCollection = rawQuery.path.length % 2 === 1;
|
const isCollection = rawQuery.path.length % 2 === 1;
|
||||||
let query = isCollection
|
let query = isCollection
|
||||||
? new CollectionQuery(this, session, rawQuery, true)
|
? new CollectionQuery(this, session, rawQuery, true)
|
||||||
: new DocumentQuery(this, session, rawQuery, true);
|
: new DocumentQuery(this, session, rawQuery, true);
|
||||||
|
|
||||||
const {
|
const { unsubscribe, value } = await query.snapshot(onchange);
|
||||||
unsubscribe,
|
|
||||||
value
|
|
||||||
} = await query.snapshot(onchange);
|
|
||||||
|
|
||||||
const id = nanoid(ALPHABET, 16);
|
const id = shortNanoId();
|
||||||
session.subscriptions.set(id, unsubscribe);
|
session.subscriptions.set(id, unsubscribe);
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
snaphot: value
|
snaphot: value,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -328,39 +394,39 @@ export class Database {
|
|||||||
const should = await new Promise<Set<string>>((yes, no) => {
|
const should = await new Promise<Set<string>>((yes, no) => {
|
||||||
const stream = this.collections.iterator({
|
const stream = this.collections.iterator({
|
||||||
keyAsBuffer: false,
|
keyAsBuffer: false,
|
||||||
valueAsBuffer: false
|
valueAsBuffer: false,
|
||||||
})
|
});
|
||||||
|
|
||||||
const collections = new Set<string>();
|
const collections = new Set<string>();
|
||||||
const onValue = (err: Error, key: string, value: string) => {
|
const onValue = (err: Error, key: string, value: string) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
Logging.error(err);
|
Logging.error(err);
|
||||||
stream.end((err) => Logging.error(err))
|
stream.end((err) => Logging.error(err));
|
||||||
no(err);
|
no(err);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!key && !value) {
|
if (!key && !value) {
|
||||||
yes(collections);
|
yes(collections);
|
||||||
} else {
|
} else {
|
||||||
collections.add(value)
|
collections.add(value);
|
||||||
stream.next(onValue);
|
stream.next(onValue);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
stream.next(onValue);
|
stream.next(onValue);
|
||||||
})
|
});
|
||||||
|
|
||||||
const existing = await new Promise<Set<string>>((yes, no) => {
|
const existing = await new Promise<Set<string>>((yes, no) => {
|
||||||
const stream = this.data.iterator({
|
const stream = this.data.iterator({
|
||||||
keyAsBuffer: false,
|
keyAsBuffer: false,
|
||||||
values: false
|
values: false,
|
||||||
})
|
});
|
||||||
|
|
||||||
const collections = new Set<string>();
|
const collections = new Set<string>();
|
||||||
const onValue = (err: Error, key: string, value: Buffer) => {
|
const onValue = (err: Error, key: string, value: Buffer) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
Logging.error(err);
|
Logging.error(err);
|
||||||
stream.end((err) => Logging.error(err))
|
stream.end((err) => Logging.error(err));
|
||||||
no(err);
|
no(err);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -368,19 +434,18 @@ export class Database {
|
|||||||
yes(collections);
|
yes(collections);
|
||||||
} else {
|
} else {
|
||||||
let coll = key.split("/")[0];
|
let coll = key.split("/")[0];
|
||||||
collections.add(coll)
|
collections.add(coll);
|
||||||
stream.next(onValue);
|
stream.next(onValue);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
stream.next(onValue);
|
stream.next(onValue);
|
||||||
})
|
});
|
||||||
|
|
||||||
const toDelete = new Set<string>();
|
const toDelete = new Set<string>();
|
||||||
existing.forEach(collection => {
|
existing.forEach((collection) => {
|
||||||
if (!should.has(collection))
|
if (!should.has(collection)) toDelete.add(collection);
|
||||||
toDelete.add(collection);
|
});
|
||||||
})
|
|
||||||
|
|
||||||
for (let collection of toDelete) {
|
for (let collection of toDelete) {
|
||||||
const batch = this.data.batch();
|
const batch = this.data.batch();
|
||||||
@ -390,20 +455,20 @@ export class Database {
|
|||||||
|
|
||||||
let lt = Buffer.alloc(gt.length);
|
let lt = Buffer.alloc(gt.length);
|
||||||
lt.set(gt);
|
lt.set(gt);
|
||||||
lt[gt.length - 1] = 0xFF;
|
lt[gt.length - 1] = 0xff;
|
||||||
|
|
||||||
await new Promise<void>((yes, no) => {
|
await new Promise<void>((yes, no) => {
|
||||||
const stream = this.data.iterator({
|
const stream = this.data.iterator({
|
||||||
keyAsBuffer: false,
|
keyAsBuffer: false,
|
||||||
values: false,
|
values: false,
|
||||||
gt,
|
gt,
|
||||||
lt
|
lt,
|
||||||
})
|
});
|
||||||
|
|
||||||
const onValue = (err: Error, key: string, value: Buffer) => {
|
const onValue = (err: Error, key: string, value: Buffer) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
Logging.error(err);
|
Logging.error(err);
|
||||||
stream.end((err) => Logging.error(err))
|
stream.end((err) => Logging.error(err));
|
||||||
no(err);
|
no(err);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -413,15 +478,14 @@ export class Database {
|
|||||||
batch.del(key);
|
batch.del(key);
|
||||||
stream.next(onValue);
|
stream.next(onValue);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
stream.next(onValue);
|
stream.next(onValue);
|
||||||
})
|
});
|
||||||
|
|
||||||
await batch.write();
|
await batch.write();
|
||||||
}
|
}
|
||||||
|
|
||||||
return Array.from(toDelete.values());
|
return Array.from(toDelete.values());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -4,7 +4,7 @@ export default class DocumentLock {
|
|||||||
private locks = new Map<string, (() => void)[]>();
|
private locks = new Map<string, (() => void)[]>();
|
||||||
|
|
||||||
getLocks() {
|
getLocks() {
|
||||||
return Array.from(this.locks.keys())
|
return Array.from(this.locks.keys());
|
||||||
}
|
}
|
||||||
|
|
||||||
async lock(collection: string = "", document: string = "") {
|
async lock(collection: string = "", document: string = "") {
|
||||||
@ -12,17 +12,18 @@ export default class DocumentLock {
|
|||||||
let key = collection + "/" + document;
|
let key = collection + "/" + document;
|
||||||
let l = this.locks.get(key);
|
let l = this.locks.get(key);
|
||||||
if (l)
|
if (l)
|
||||||
await new Promise(resolve => { l.push(resolve); this.locks.set(key, l) });
|
await new Promise((resolve) => {
|
||||||
|
l.push(resolve);
|
||||||
|
this.locks.set(key, l);
|
||||||
|
});
|
||||||
else {
|
else {
|
||||||
l = [];
|
l = [];
|
||||||
this.locks.set(key, l);
|
this.locks.set(key, l);
|
||||||
}
|
}
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
if (l.length > 0)
|
if (l.length > 0) setImmediate(() => l.shift()());
|
||||||
setImmediate(() => l.shift()());
|
else this.locks.delete(key);
|
||||||
else
|
};
|
||||||
this.locks.delete(key)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,10 +1,11 @@
|
|||||||
import { Database, Change, ChangeTypes } from "./database";
|
import { Database, Change, ChangeTypes } from "./database";
|
||||||
import { resNull } from "../storage";
|
import { resNull } from "../storage";
|
||||||
import nanoid = require("nanoid/generate");
|
import * as nanoid from "nanoid";
|
||||||
import Logging from "@hibas123/nodelogging";
|
import Logging from "@hibas123/nodelogging";
|
||||||
import * as MSGPack from "what-the-pack";
|
import * as MSGPack from "what-the-pack";
|
||||||
import Session from "./session";
|
import Session from "./session";
|
||||||
import { LevelUpChain } from "levelup";
|
import { LevelUpChain } from "levelup";
|
||||||
|
import { Operations } from "../rules/parser";
|
||||||
|
|
||||||
export type IWriteQueries = "set" | "update" | "delete" | "add";
|
export type IWriteQueries = "set" | "update" | "delete" | "add";
|
||||||
export type ICollectionQueries =
|
export type ICollectionQueries =
|
||||||
@ -31,6 +32,8 @@ export const MP = MSGPack.initialize(2 ** 20);
|
|||||||
const ALPHABET =
|
const ALPHABET =
|
||||||
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
||||||
|
|
||||||
|
const longNanoID = nanoid.customAlphabet(ALPHABET, 32);
|
||||||
|
|
||||||
const { encode, decode } = MP;
|
const { encode, decode } = MP;
|
||||||
|
|
||||||
type Runner = (
|
type Runner = (
|
||||||
@ -45,7 +48,7 @@ interface IPreparedQuery {
|
|||||||
needDocument: boolean;
|
needDocument: boolean;
|
||||||
batchCompatible: boolean;
|
batchCompatible: boolean;
|
||||||
runner: Runner;
|
runner: Runner;
|
||||||
permission: "write" | "read";
|
permission: Operations;
|
||||||
additionalLock?: string[];
|
additionalLock?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -61,7 +64,7 @@ export abstract class Query {
|
|||||||
*/
|
*/
|
||||||
private validatePath(path: string[]) {
|
private validatePath(path: string[]) {
|
||||||
return path.every(
|
return path.every(
|
||||||
e => (e.match(/[^a-zA-Z0-9_\-\<\>]/g) || []).length === 0
|
(e) => (e.match(/[^a-zA-Z0-9_\-\<\>]/g) || []).length === 0
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -71,7 +74,7 @@ export abstract class Query {
|
|||||||
public readonly needDocument: boolean;
|
public readonly needDocument: boolean;
|
||||||
public readonly batchCompatible: boolean;
|
public readonly batchCompatible: boolean;
|
||||||
public readonly additionalLock?: string[];
|
public readonly additionalLock?: string[];
|
||||||
public readonly permission: string;
|
public readonly permission: Operations;
|
||||||
private readonly _runner: Runner;
|
private readonly _runner: Runner;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
@ -97,6 +100,7 @@ export abstract class Query {
|
|||||||
this.needDocument = data.needDocument;
|
this.needDocument = data.needDocument;
|
||||||
this.batchCompatible = data.batchCompatible;
|
this.batchCompatible = data.batchCompatible;
|
||||||
this.additionalLock = data.additionalLock;
|
this.additionalLock = data.additionalLock;
|
||||||
|
this.permission = data.permission;
|
||||||
this._runner = data.runner;
|
this._runner = data.runner;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -106,7 +110,7 @@ export abstract class Query {
|
|||||||
protected getDoc(collection: string, document: string) {
|
protected getDoc(collection: string, document: string) {
|
||||||
return this.database.data
|
return this.database.data
|
||||||
.get(Database.getKey(collection, document), { asBuffer: true })
|
.get(Database.getKey(collection, document), { asBuffer: true })
|
||||||
.then(res => decode<any>(res as Buffer))
|
.then((res) => decode<any>(res as Buffer))
|
||||||
.catch(resNull);
|
.catch(resNull);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -121,9 +125,11 @@ export abstract class Query {
|
|||||||
document,
|
document,
|
||||||
collection,
|
collection,
|
||||||
data,
|
data,
|
||||||
sender: this.session.id
|
sender: this.session.id,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
Logging.debug("Sending change:", change);
|
||||||
|
|
||||||
this.changes.push(change);
|
this.changes.push(change);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -147,13 +153,13 @@ export abstract class Query {
|
|||||||
) {
|
) {
|
||||||
let perm = this.database.rules.hasPermission(
|
let perm = this.database.rules.hasPermission(
|
||||||
this.query.path,
|
this.query.path,
|
||||||
|
this.permission,
|
||||||
this.session
|
this.session
|
||||||
);
|
);
|
||||||
if (this.permission === "read" && !perm.read) {
|
|
||||||
throw new QueryError("No permission!");
|
if (!perm) throw new QueryError("No permission!");
|
||||||
} else if (this.permission === "write" && !perm.write) {
|
|
||||||
throw new QueryError("No permission!");
|
// this.query.path = perm.path;
|
||||||
}
|
|
||||||
return this._runner.call(
|
return this._runner.call(
|
||||||
this,
|
this,
|
||||||
collection,
|
collection,
|
||||||
@ -168,31 +174,34 @@ export abstract class Query {
|
|||||||
) {
|
) {
|
||||||
let perm = this.database.rules.hasPermission(
|
let perm = this.database.rules.hasPermission(
|
||||||
this.query.path,
|
this.query.path,
|
||||||
|
"read",
|
||||||
this.session
|
this.session
|
||||||
);
|
);
|
||||||
if (this.permission === "read" && !perm.read) {
|
if (!perm) {
|
||||||
throw new QueryError("No permission!");
|
throw new QueryError("No permission!");
|
||||||
}
|
}
|
||||||
|
|
||||||
const receivedChanges = (changes: Change[]) => {
|
const receivedChanges = (changes: Change[]) => {
|
||||||
let res = changes
|
let res = changes
|
||||||
.filter(change => this.checkChange(change))
|
.filter((change) => this.checkChange(change))
|
||||||
.map(change => {
|
.map((change) => {
|
||||||
return {
|
return {
|
||||||
id: change.document,
|
id: change.document,
|
||||||
data: change.data,
|
data: change.data,
|
||||||
type: change.type
|
type: change.type,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
if (res.length > 0) onChange(res);
|
if (res.length > 0) onChange(res);
|
||||||
};
|
};
|
||||||
|
|
||||||
const unsub = this.database.collectionChangeListener.subscribe(change => {
|
const unsub = this.database.collectionChangeListener.subscribe(
|
||||||
if (change.key === collectionKey) {
|
(change) => {
|
||||||
if (change.type === "create") addSubscriber(change.id);
|
if (change.key === collectionKey) {
|
||||||
else removeSubscriber(); // Send delete for all elements (Don't know how to do this...)
|
if (change.type === "create") addSubscriber(change.id);
|
||||||
|
else removeSubscriber(); // Send delete for all elements (Don't know how to do this...)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
);
|
||||||
|
|
||||||
let { collection, document, collectionKey } = await this.database.resolve(
|
let { collection, document, collectionKey } = await this.database.resolve(
|
||||||
this.query.path
|
this.query.path
|
||||||
@ -209,7 +218,7 @@ export abstract class Query {
|
|||||||
oldKey = undefined;
|
oldKey = undefined;
|
||||||
};
|
};
|
||||||
|
|
||||||
const addSubscriber = () => {
|
const addSubscriber = (collection: string) => {
|
||||||
let key = Database.getKey(collection, document);
|
let key = Database.getKey(collection, document);
|
||||||
if (oldKey !== key) {
|
if (oldKey !== key) {
|
||||||
if (oldKey !== undefined) removeSubscriber();
|
if (oldKey !== undefined) removeSubscriber();
|
||||||
@ -225,7 +234,7 @@ export abstract class Query {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (collection) {
|
if (collection) {
|
||||||
addSubscriber();
|
addSubscriber(collection);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@ -233,7 +242,7 @@ export abstract class Query {
|
|||||||
unsub();
|
unsub();
|
||||||
removeSubscriber();
|
removeSubscriber();
|
||||||
},
|
},
|
||||||
value: await this.firstSend(collection, document)
|
value: await this.firstSend(collection, document),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -254,7 +263,7 @@ export class DocumentQuery extends Query {
|
|||||||
createCollection: false,
|
createCollection: false,
|
||||||
needDocument: false,
|
needDocument: false,
|
||||||
permission: "read",
|
permission: "read",
|
||||||
runner: this.get
|
runner: this.get,
|
||||||
};
|
};
|
||||||
case "set":
|
case "set":
|
||||||
return {
|
return {
|
||||||
@ -262,7 +271,7 @@ export class DocumentQuery extends Query {
|
|||||||
createCollection: true,
|
createCollection: true,
|
||||||
needDocument: true,
|
needDocument: true,
|
||||||
permission: "write",
|
permission: "write",
|
||||||
runner: this.set
|
runner: this.set,
|
||||||
};
|
};
|
||||||
case "update":
|
case "update":
|
||||||
return {
|
return {
|
||||||
@ -270,7 +279,7 @@ export class DocumentQuery extends Query {
|
|||||||
createCollection: true,
|
createCollection: true,
|
||||||
needDocument: true,
|
needDocument: true,
|
||||||
permission: "write",
|
permission: "write",
|
||||||
runner: this.update
|
runner: this.update,
|
||||||
};
|
};
|
||||||
case "delete":
|
case "delete":
|
||||||
return {
|
return {
|
||||||
@ -278,7 +287,7 @@ export class DocumentQuery extends Query {
|
|||||||
createCollection: false,
|
createCollection: false,
|
||||||
needDocument: true,
|
needDocument: true,
|
||||||
permission: "write",
|
permission: "write",
|
||||||
runner: this.delete
|
runner: this.delete,
|
||||||
};
|
};
|
||||||
default:
|
default:
|
||||||
throw new Error("Invalid query type: " + type);
|
throw new Error("Invalid query type: " + type);
|
||||||
@ -428,14 +437,14 @@ export class CollectionQuery extends Query {
|
|||||||
prepare(query): IPreparedQuery {
|
prepare(query): IPreparedQuery {
|
||||||
switch (query.type as ICollectionQueries) {
|
switch (query.type as ICollectionQueries) {
|
||||||
case "add":
|
case "add":
|
||||||
this._addId = nanoid(ALPHABET, 32);
|
this._addId = longNanoID();
|
||||||
return {
|
return {
|
||||||
batchCompatible: true,
|
batchCompatible: true,
|
||||||
createCollection: true,
|
createCollection: true,
|
||||||
needDocument: false,
|
needDocument: false,
|
||||||
runner: this.add,
|
runner: this.add,
|
||||||
permission: "write",
|
permission: "write",
|
||||||
additionalLock: [...query.path, this._addId]
|
additionalLock: [...query.path, this._addId],
|
||||||
};
|
};
|
||||||
case "get":
|
case "get":
|
||||||
const limit = (query.options || {}).limit;
|
const limit = (query.options || {}).limit;
|
||||||
@ -448,15 +457,15 @@ export class CollectionQuery extends Query {
|
|||||||
createCollection: false,
|
createCollection: false,
|
||||||
needDocument: false,
|
needDocument: false,
|
||||||
permission: "read",
|
permission: "read",
|
||||||
runner: this.get
|
runner: this.get,
|
||||||
};
|
};
|
||||||
case "keys":
|
case "keys":
|
||||||
return {
|
return {
|
||||||
batchCompatible: false,
|
batchCompatible: false,
|
||||||
createCollection: false,
|
createCollection: false,
|
||||||
needDocument: false,
|
needDocument: false,
|
||||||
permission: "read",
|
permission: "list",
|
||||||
runner: this.keys
|
runner: this.keys,
|
||||||
};
|
};
|
||||||
case "list":
|
case "list":
|
||||||
return {
|
return {
|
||||||
@ -464,7 +473,7 @@ export class CollectionQuery extends Query {
|
|||||||
createCollection: false,
|
createCollection: false,
|
||||||
needDocument: false,
|
needDocument: false,
|
||||||
permission: "read",
|
permission: "read",
|
||||||
runner: this.keys
|
runner: this.keys,
|
||||||
};
|
};
|
||||||
case "delete-collection":
|
case "delete-collection":
|
||||||
return {
|
return {
|
||||||
@ -472,7 +481,7 @@ export class CollectionQuery extends Query {
|
|||||||
createCollection: false,
|
createCollection: false,
|
||||||
needDocument: false,
|
needDocument: false,
|
||||||
permission: "write",
|
permission: "write",
|
||||||
runner: this.deleteCollection
|
runner: this.deleteCollection,
|
||||||
};
|
};
|
||||||
// run = () => q.deleteCollection();
|
// run = () => q.deleteCollection();
|
||||||
// break;
|
// break;
|
||||||
@ -481,12 +490,12 @@ export class CollectionQuery extends Query {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private _where: IQueryWhereArray[] = [];
|
private _where: IQueryWhereArray[];
|
||||||
public set where(value: IQueryWhere[]) {
|
public set where(value: IQueryWhere[]) {
|
||||||
const invalidWhere = new QueryError("Invalid Where");
|
const invalidWhere = new QueryError("Invalid Where");
|
||||||
if (!Array.isArray(value)) throw invalidWhere;
|
if (!Array.isArray(value)) throw invalidWhere;
|
||||||
let c = [];
|
let c = [];
|
||||||
this._where = value.map(cond => {
|
this._where = value.map((cond) => {
|
||||||
Logging.debug("Query Condition", cond);
|
Logging.debug("Query Condition", cond);
|
||||||
if (Array.isArray(cond)) {
|
if (Array.isArray(cond)) {
|
||||||
if (cond.length !== 3) throw invalidWhere;
|
if (cond.length !== 3) throw invalidWhere;
|
||||||
@ -519,9 +528,10 @@ export class CollectionQuery extends Query {
|
|||||||
type: "set",
|
type: "set",
|
||||||
path: this.additionalLock,
|
path: this.additionalLock,
|
||||||
data: this.query.data,
|
data: this.query.data,
|
||||||
options: this.query.options
|
options: this.query.options,
|
||||||
});
|
});
|
||||||
await q.run(collection, this._addId, batch, collectionKey);
|
await q.run(collection, this._addId, batch, collectionKey);
|
||||||
|
this.changes = q.changes;
|
||||||
return this._addId;
|
return this._addId;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -535,7 +545,7 @@ export class CollectionQuery extends Query {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
gt,
|
gt,
|
||||||
lt
|
lt,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -546,7 +556,7 @@ export class CollectionQuery extends Query {
|
|||||||
let keys = [];
|
let keys = [];
|
||||||
const stream = this.database.data.createKeyStream({
|
const stream = this.database.data.createKeyStream({
|
||||||
...this.getStreamOptions(collection),
|
...this.getStreamOptions(collection),
|
||||||
keyAsBuffer: false
|
keyAsBuffer: false,
|
||||||
});
|
});
|
||||||
stream.on("data", (key: string) => {
|
stream.on("data", (key: string) => {
|
||||||
let s = key.split("/", 2);
|
let s = key.split("/", 2);
|
||||||
@ -570,7 +580,7 @@ export class CollectionQuery extends Query {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private _fitsWhere(data: any): boolean {
|
private _fitsWhere(data: any): boolean {
|
||||||
if (this._where.length > 0) {
|
if (this._where && this._where.length > 0) {
|
||||||
return this._where.every(([fieldPath, opStr, value]) => {
|
return this._where.every(([fieldPath, opStr, value]) => {
|
||||||
let val = this._getFieldValue(data, fieldPath);
|
let val = this._getFieldValue(data, fieldPath);
|
||||||
switch (opStr) {
|
switch (opStr) {
|
||||||
@ -586,7 +596,7 @@ export class CollectionQuery extends Query {
|
|||||||
return val > value;
|
return val > value;
|
||||||
case "array-contains":
|
case "array-contains":
|
||||||
if (Array.isArray(val)) {
|
if (Array.isArray(val)) {
|
||||||
return val.some(e => e === value);
|
return val.some((e) => e === value);
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
@ -611,7 +621,7 @@ export class CollectionQuery extends Query {
|
|||||||
const stream = this.database.data.iterator({
|
const stream = this.database.data.iterator({
|
||||||
...this.getStreamOptions(collection),
|
...this.getStreamOptions(collection),
|
||||||
keyAsBuffer: false,
|
keyAsBuffer: false,
|
||||||
valueAsBuffer: true
|
valueAsBuffer: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
let values: DocRes[] = [];
|
let values: DocRes[] = [];
|
||||||
@ -619,7 +629,7 @@ export class CollectionQuery extends Query {
|
|||||||
const onValue = (err: Error, key: string, value: Buffer) => {
|
const onValue = (err: Error, key: string, value: Buffer) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
no(err);
|
no(err);
|
||||||
stream.end(err => Logging.error(err));
|
stream.end((err) => Logging.error(err));
|
||||||
} else {
|
} else {
|
||||||
if (!key && !value) {
|
if (!key && !value) {
|
||||||
// END
|
// END
|
||||||
@ -636,10 +646,10 @@ export class CollectionQuery extends Query {
|
|||||||
if (this.limit < 0 || values.length < this.limit) {
|
if (this.limit < 0 || values.length < this.limit) {
|
||||||
values.push({
|
values.push({
|
||||||
id,
|
id,
|
||||||
data
|
data,
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
stream.end(err => (err ? no(err) : yes(values)));
|
stream.end((err) => (err ? no(err) : yes(values)));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -667,7 +677,7 @@ export class CollectionQuery extends Query {
|
|||||||
return new Promise<string[]>((yes, no) => {
|
return new Promise<string[]>((yes, no) => {
|
||||||
let keys = [];
|
let keys = [];
|
||||||
const stream = this.database.data.createKeyStream({
|
const stream = this.database.data.createKeyStream({
|
||||||
keyAsBuffer: false
|
keyAsBuffer: false,
|
||||||
});
|
});
|
||||||
stream.on("data", (key: string) => keys.push(key.split("/")));
|
stream.on("data", (key: string) => keys.push(key.split("/")));
|
||||||
stream.on("end", () => yes(keys));
|
stream.on("end", () => yes(keys));
|
||||||
@ -698,7 +708,7 @@ export class CollectionQuery extends Query {
|
|||||||
this.database.collectionChangeListener.send({
|
this.database.collectionChangeListener.send({
|
||||||
id: collection,
|
id: collection,
|
||||||
key: collectionKey,
|
key: collectionKey,
|
||||||
type: "delete"
|
type: "delete",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
|
@ -1,118 +0,0 @@
|
|||||||
import Session from "./session";
|
|
||||||
import Logging from "@hibas123/nodelogging";
|
|
||||||
|
|
||||||
interface IRule<T> {
|
|
||||||
".write"?: T;
|
|
||||||
".read"?: T;
|
|
||||||
}
|
|
||||||
|
|
||||||
type IRuleConfig<T> =
|
|
||||||
| IRule<T>
|
|
||||||
| {
|
|
||||||
[segment: string]: IRuleConfig<T>;
|
|
||||||
};
|
|
||||||
|
|
||||||
type IRuleRaw = IRuleConfig<string>;
|
|
||||||
type IRuleParsed = IRuleConfig<boolean>;
|
|
||||||
|
|
||||||
const resolve = (value: any) => {
|
|
||||||
if (value === true) {
|
|
||||||
return true;
|
|
||||||
} else if (typeof value === "string") {
|
|
||||||
}
|
|
||||||
return undefined;
|
|
||||||
};
|
|
||||||
|
|
||||||
export class Rules {
|
|
||||||
rules: IRuleParsed;
|
|
||||||
constructor(private config: string) {
|
|
||||||
let parsed: IRuleRaw = JSON.parse(config);
|
|
||||||
|
|
||||||
const analyse = (raw: IRuleRaw) => {
|
|
||||||
let r: IRuleParsed = {};
|
|
||||||
|
|
||||||
if (raw[".read"]) {
|
|
||||||
let res = resolve(raw[".read"]);
|
|
||||||
if (res) {
|
|
||||||
r[".read"] = res;
|
|
||||||
}
|
|
||||||
delete raw[".read"];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (raw[".write"]) {
|
|
||||||
let res = resolve(raw[".write"]);
|
|
||||||
if (res) {
|
|
||||||
r[".write"] = res;
|
|
||||||
}
|
|
||||||
delete raw[".write"];
|
|
||||||
}
|
|
||||||
|
|
||||||
for (let segment in raw) {
|
|
||||||
if (segment.startsWith(".")) continue;
|
|
||||||
|
|
||||||
r[segment] = analyse(raw[segment]);
|
|
||||||
}
|
|
||||||
return r;
|
|
||||||
};
|
|
||||||
|
|
||||||
this.rules = analyse(parsed);
|
|
||||||
}
|
|
||||||
|
|
||||||
hasPermission(
|
|
||||||
path: string[],
|
|
||||||
session: Session
|
|
||||||
): { read: boolean; write: boolean } {
|
|
||||||
if (session.root)
|
|
||||||
return {
|
|
||||||
read: true,
|
|
||||||
write: true
|
|
||||||
};
|
|
||||||
let read = this.rules[".read"] || false;
|
|
||||||
let write = this.rules[".write"] || false;
|
|
||||||
|
|
||||||
let rules = this.rules;
|
|
||||||
|
|
||||||
for (let segment of path) {
|
|
||||||
if (segment.startsWith("$") || segment.startsWith(".")) {
|
|
||||||
read = false;
|
|
||||||
write = false;
|
|
||||||
Logging.log("Invalid query path (started with '$' or '.'):", path);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
let k = Object.keys(rules)
|
|
||||||
.filter(e => e.startsWith("$"))
|
|
||||||
.find(e => {
|
|
||||||
switch (e) {
|
|
||||||
case "$uid":
|
|
||||||
if (segment === session.uid) return true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
});
|
|
||||||
|
|
||||||
rules = (k ? rules[k] : undefined) || rules[segment] || rules["*"];
|
|
||||||
|
|
||||||
if (rules) {
|
|
||||||
if (rules[".read"]) {
|
|
||||||
read = rules[".read"];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (rules[".write"]) {
|
|
||||||
read = rules[".write"];
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
read: read as boolean,
|
|
||||||
write: write as boolean
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
toJSON() {
|
|
||||||
return this.config;
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,11 +1,10 @@
|
|||||||
|
|
||||||
export default class Session {
|
export default class Session {
|
||||||
constructor(private _sessionid: string) { }
|
constructor(private _sessionid: string) {}
|
||||||
get id() {
|
get id() {
|
||||||
return this._sessionid;
|
return this._sessionid;
|
||||||
}
|
}
|
||||||
root: boolean = false;
|
root: boolean = false;
|
||||||
uid: string = undefined;
|
uid: string = null;
|
||||||
|
|
||||||
subscriptions = new Map<string, (() => void)>();
|
subscriptions = new Map<string, () => void>();
|
||||||
}
|
}
|
||||||
|
22
src/index.ts
22
src/index.ts
@ -3,7 +3,7 @@ import Web from "./web";
|
|||||||
import config from "./config";
|
import config from "./config";
|
||||||
import { DatabaseManager } from "./database/database";
|
import { DatabaseManager } from "./database/database";
|
||||||
import { createServer } from "http";
|
import { createServer } from "http";
|
||||||
import { ConnectionManager } from "./connection";
|
import { WebsocketConnectionManager } from "./websocket";
|
||||||
import { LoggingTypes } from "@hibas123/logging";
|
import { LoggingTypes } from "@hibas123/logging";
|
||||||
import { readFileSync } from "fs";
|
import { readFileSync } from "fs";
|
||||||
|
|
||||||
@ -13,12 +13,14 @@ const version = JSON.parse(readFileSync("./package.json").toString()).version;
|
|||||||
|
|
||||||
Logging.log("Starting Database version:", version);
|
Logging.log("Starting Database version:", version);
|
||||||
|
|
||||||
DatabaseManager.init().then(() => {
|
DatabaseManager.init()
|
||||||
const http = createServer(Web.callback());
|
.then(() => {
|
||||||
ConnectionManager.bind(http);
|
const http = createServer(Web.callback());
|
||||||
const port = config.port || 5000;
|
WebsocketConnectionManager.bind(http);
|
||||||
http.listen(port, () => Logging.log("Listening on port:", port))
|
const port = config.port || 5000;
|
||||||
}).catch(err => {
|
http.listen(port, () => Logging.log("WS: Listening on port:", port));
|
||||||
Logging.error(err);
|
})
|
||||||
process.exit(-1);
|
.catch((err) => {
|
||||||
})
|
Logging.error(err);
|
||||||
|
process.exit(-1);
|
||||||
|
});
|
||||||
|
293
src/rules/compile.ts
Normal file
293
src/rules/compile.ts
Normal file
@ -0,0 +1,293 @@
|
|||||||
|
import {
|
||||||
|
Node,
|
||||||
|
MatchStatement,
|
||||||
|
Operations,
|
||||||
|
ServiceStatement,
|
||||||
|
Expression,
|
||||||
|
ValueStatement,
|
||||||
|
Operators,
|
||||||
|
} from "./parser";
|
||||||
|
|
||||||
|
export class CompilerError extends Error {
|
||||||
|
node: Node;
|
||||||
|
constructor(message: string, node: Node) {
|
||||||
|
super(message);
|
||||||
|
this.node = node;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type Variables = { [key: string]: string | Variables };
|
||||||
|
|
||||||
|
class Variable {
|
||||||
|
#name: string;
|
||||||
|
constructor(name: string) {
|
||||||
|
this.#name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
getValue(variables: Variables) {
|
||||||
|
const parts = this.#name.split(".");
|
||||||
|
let current = variables as any;
|
||||||
|
while (parts.length > 0) {
|
||||||
|
const name = parts.shift();
|
||||||
|
if (current && typeof current == "object") current = current[name];
|
||||||
|
}
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Value {
|
||||||
|
#value: any;
|
||||||
|
constructor(value: any) {
|
||||||
|
this.#value = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
get value() {
|
||||||
|
return this.#value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type ConditionParameters = Value | ConditionMatcher | Variable;
|
||||||
|
class ConditionMatcher {
|
||||||
|
#left: ConditionParameters;
|
||||||
|
#right: ConditionParameters;
|
||||||
|
#operator: Operators;
|
||||||
|
constructor(
|
||||||
|
left: ConditionParameters,
|
||||||
|
right: ConditionParameters,
|
||||||
|
operator: Operators
|
||||||
|
) {
|
||||||
|
this.#left = left;
|
||||||
|
this.#right = right;
|
||||||
|
this.#operator = operator;
|
||||||
|
}
|
||||||
|
|
||||||
|
test(variables: Variables): boolean {
|
||||||
|
let leftValue: any;
|
||||||
|
if (this.#left instanceof Value) {
|
||||||
|
leftValue = this.#left.value;
|
||||||
|
} else if (this.#left instanceof Variable) {
|
||||||
|
leftValue = this.#left.getValue(variables);
|
||||||
|
} else {
|
||||||
|
leftValue = this.#left.test(variables);
|
||||||
|
}
|
||||||
|
|
||||||
|
let rightValue: any;
|
||||||
|
if (this.#right instanceof Value) {
|
||||||
|
rightValue = this.#right.value;
|
||||||
|
} else if (this.#right instanceof Variable) {
|
||||||
|
rightValue = this.#right.getValue(variables);
|
||||||
|
} else {
|
||||||
|
rightValue = this.#right.test(variables);
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (this.#operator) {
|
||||||
|
case "==":
|
||||||
|
return leftValue == rightValue;
|
||||||
|
case "!=":
|
||||||
|
return leftValue != rightValue;
|
||||||
|
case ">=":
|
||||||
|
return leftValue >= rightValue;
|
||||||
|
case "<=":
|
||||||
|
return leftValue <= rightValue;
|
||||||
|
case ">":
|
||||||
|
return leftValue > rightValue;
|
||||||
|
case "<":
|
||||||
|
return leftValue < rightValue;
|
||||||
|
case "&&":
|
||||||
|
return leftValue && rightValue;
|
||||||
|
case "||":
|
||||||
|
return leftValue || rightValue;
|
||||||
|
default:
|
||||||
|
throw new Error("Invalid operator " + this.#operator);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Rule {
|
||||||
|
#operation: Operations;
|
||||||
|
|
||||||
|
#condition: ConditionParameters;
|
||||||
|
|
||||||
|
get operation() {
|
||||||
|
return this.#operation;
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(operation: Operations, condition: ConditionParameters) {
|
||||||
|
this.#operation = operation;
|
||||||
|
this.#condition = condition;
|
||||||
|
}
|
||||||
|
|
||||||
|
test(variables: Variables): boolean {
|
||||||
|
if (this.#condition instanceof Value) {
|
||||||
|
return Boolean(this.#condition.value);
|
||||||
|
} else if (this.#condition instanceof Variable) {
|
||||||
|
return Boolean(this.#condition.getValue(variables));
|
||||||
|
} else {
|
||||||
|
return this.#condition.test(variables);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Segment {
|
||||||
|
#name: string;
|
||||||
|
#variable: boolean;
|
||||||
|
get name() {
|
||||||
|
return this.#name;
|
||||||
|
}
|
||||||
|
constructor(name: string, variable = false) {
|
||||||
|
this.#name = name;
|
||||||
|
this.#variable = variable;
|
||||||
|
}
|
||||||
|
|
||||||
|
match(segment: string): { match: boolean; variable?: string } {
|
||||||
|
return {
|
||||||
|
match: this.#name === segment || this.#variable,
|
||||||
|
variable: this.#variable && this.#name,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Match {
|
||||||
|
#submatches: Match[];
|
||||||
|
#rules: Rule[];
|
||||||
|
|
||||||
|
#segments: Segment[];
|
||||||
|
#wildcard: boolean;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
segments: Segment[],
|
||||||
|
rules: Rule[],
|
||||||
|
wildcard: boolean,
|
||||||
|
submatches: Match[]
|
||||||
|
) {
|
||||||
|
this.#segments = segments;
|
||||||
|
this.#rules = rules;
|
||||||
|
this.#wildcard = wildcard;
|
||||||
|
this.#submatches = submatches;
|
||||||
|
}
|
||||||
|
|
||||||
|
match(
|
||||||
|
segments: string[],
|
||||||
|
operation: Operations,
|
||||||
|
variables: Variables
|
||||||
|
): boolean {
|
||||||
|
let localVars = { ...variables };
|
||||||
|
if (segments.length >= this.#segments.length) {
|
||||||
|
for (let i = 0; i < this.#segments.length; i++) {
|
||||||
|
const match = this.#segments[i].match(segments[i]);
|
||||||
|
if (match.match) {
|
||||||
|
if (match.variable) {
|
||||||
|
localVars[match.variable] = segments[i];
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let remaining = segments.slice(this.#segments.length);
|
||||||
|
if (remaining.length > 0 && !this.#wildcard) {
|
||||||
|
for (const match of this.#submatches) {
|
||||||
|
const res = match.match(remaining, operation, localVars);
|
||||||
|
if (res) return true;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (const rule of this.#rules) {
|
||||||
|
if (rule.operation === operation) {
|
||||||
|
if (rule.test(localVars)) return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class RuleRunner {
|
||||||
|
#root_matches: Match[];
|
||||||
|
constructor(root_matches: Match[]) {
|
||||||
|
this.#root_matches = root_matches;
|
||||||
|
}
|
||||||
|
|
||||||
|
hasPermission(path: string[], operation: Operations, request: any): boolean {
|
||||||
|
if (request.root) return true;
|
||||||
|
for (const match of this.#root_matches) {
|
||||||
|
const res = match.match(path, operation, { request });
|
||||||
|
if (res) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getRuleRunner(service: ServiceStatement) {
|
||||||
|
const createMatch = (s_match: MatchStatement) => {
|
||||||
|
let wildcard = false;
|
||||||
|
let segments = s_match.path.segments
|
||||||
|
.map((segment, idx, arr) => {
|
||||||
|
if (typeof segment === "string") {
|
||||||
|
if (segment === "*") {
|
||||||
|
if (idx === arr.length - 1) {
|
||||||
|
wildcard = true;
|
||||||
|
return null;
|
||||||
|
} else {
|
||||||
|
throw new CompilerError("Invalid path wildcard!", s_match);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return new Segment(segment, false);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return new Segment(segment.name, true);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.filter((e) => e !== null);
|
||||||
|
|
||||||
|
const resolveParameter = (e: Expression | ValueStatement) => {
|
||||||
|
let val: Value | ConditionMatcher | Variable;
|
||||||
|
if (e.type === "value") {
|
||||||
|
const c = e;
|
||||||
|
if (c.isFalse) {
|
||||||
|
val = new Value(false);
|
||||||
|
} else if (c.isTrue) {
|
||||||
|
val = new Value(true);
|
||||||
|
} else if (c.isNull) {
|
||||||
|
val = new Value(null);
|
||||||
|
} else if (c.isNumber) {
|
||||||
|
val = new Value(Number(c.value));
|
||||||
|
} else if (c.isString) {
|
||||||
|
val = new Value(String(c.value));
|
||||||
|
} else if (c.isVariable) {
|
||||||
|
val = new Variable(String(c.value));
|
||||||
|
} else {
|
||||||
|
throw new CompilerError("Invalid value type!", e);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
val = createCondition(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
return val;
|
||||||
|
};
|
||||||
|
|
||||||
|
const createCondition = (cond: Expression): ConditionMatcher => {
|
||||||
|
let left: ConditionParameters = resolveParameter(cond.left);
|
||||||
|
let right: ConditionParameters = resolveParameter(cond.right);
|
||||||
|
|
||||||
|
return new ConditionMatcher(left, right, cond.operator);
|
||||||
|
};
|
||||||
|
|
||||||
|
const rules: Rule[] = s_match.rules
|
||||||
|
.map((rule) => {
|
||||||
|
const condition = resolveParameter(rule.condition);
|
||||||
|
return rule.operations.map((op) => new Rule(op, condition));
|
||||||
|
})
|
||||||
|
.flat(1);
|
||||||
|
const submatches = s_match.matches.map((sub) => createMatch(sub));
|
||||||
|
const match = new Match(segments, rules, wildcard, submatches);
|
||||||
|
|
||||||
|
return match;
|
||||||
|
};
|
||||||
|
|
||||||
|
const root_matches = service.matches.map((match) => createMatch(match));
|
||||||
|
|
||||||
|
const runner = new RuleRunner(root_matches);
|
||||||
|
|
||||||
|
return runner;
|
||||||
|
}
|
36
src/rules/error.ts
Normal file
36
src/rules/error.ts
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
export interface RuleError {
|
||||||
|
line: number;
|
||||||
|
column: number;
|
||||||
|
message: string;
|
||||||
|
original_err: Error;
|
||||||
|
}
|
||||||
|
|
||||||
|
function indexToLineAndCol(src: string, index: number) {
|
||||||
|
let line = 1;
|
||||||
|
let col = 1;
|
||||||
|
for (let i = 0; i < index; i++) {
|
||||||
|
if (src.charAt(i) === "\n") {
|
||||||
|
line++;
|
||||||
|
col = 1;
|
||||||
|
} else {
|
||||||
|
col++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { line, col };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function transformError(
|
||||||
|
err: Error,
|
||||||
|
data: string,
|
||||||
|
idx: number
|
||||||
|
): RuleError {
|
||||||
|
let loc = indexToLineAndCol(data, idx);
|
||||||
|
|
||||||
|
return {
|
||||||
|
line: loc.line,
|
||||||
|
column: loc.col,
|
||||||
|
message: err.message,
|
||||||
|
original_err: err,
|
||||||
|
};
|
||||||
|
}
|
29
src/rules/index.ts
Normal file
29
src/rules/index.ts
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
import { RuleError, transformError } from "./error";
|
||||||
|
import parse, { ParserError } from "./parser";
|
||||||
|
import tokenize, { TokenizerError } from "./tokenise";
|
||||||
|
import { getRuleRunner, RuleRunner } from "./compile";
|
||||||
|
import { inspect } from "util";
|
||||||
|
|
||||||
|
export default function compileRule(rule: string) {
|
||||||
|
let runner: RuleRunner | undefined;
|
||||||
|
let error: RuleError | undefined;
|
||||||
|
try {
|
||||||
|
const tokenised = tokenize(rule);
|
||||||
|
const parsed = parse(tokenised);
|
||||||
|
const dbservice = parsed.find((e) => e.name === "realtimedb");
|
||||||
|
|
||||||
|
if (!dbservice) throw new Error("No realtimedb service available!");
|
||||||
|
|
||||||
|
runner = getRuleRunner(dbservice);
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof TokenizerError) {
|
||||||
|
error = transformError(err, rule, err.index);
|
||||||
|
} else if (err instanceof ParserError) {
|
||||||
|
error = transformError(err, rule, err.token.startIdx);
|
||||||
|
} else {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { runner, error };
|
||||||
|
}
|
349
src/rules/parser.ts
Normal file
349
src/rules/parser.ts
Normal file
@ -0,0 +1,349 @@
|
|||||||
|
import { Token } from "./tokenise";
|
||||||
|
|
||||||
|
export interface Node {
|
||||||
|
type: string;
|
||||||
|
idx: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PathStatement extends Node {
|
||||||
|
type: "path";
|
||||||
|
segments: (string | { type: "variable"; name: string })[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ValueStatement extends Node {
|
||||||
|
type: "value";
|
||||||
|
isNull: boolean;
|
||||||
|
isTrue: boolean;
|
||||||
|
isFalse: boolean;
|
||||||
|
isNumber: boolean;
|
||||||
|
isString: boolean;
|
||||||
|
isVariable: boolean;
|
||||||
|
|
||||||
|
value?: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Operators = "&&" | "||" | "==" | "<=" | ">=" | "!=" | ">" | "<";
|
||||||
|
|
||||||
|
export interface Expression extends Node {
|
||||||
|
type: "expression";
|
||||||
|
|
||||||
|
left: ValueStatement | Expression;
|
||||||
|
operator: Operators;
|
||||||
|
right: ValueStatement | Expression;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Operations = "read" | "write" | "list"; // | "update" | "create" | "delete" | "list";
|
||||||
|
|
||||||
|
export interface AllowStatement extends Node {
|
||||||
|
type: "permission";
|
||||||
|
operations: Operations[];
|
||||||
|
condition: Expression | ValueStatement;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MatchStatement extends Node {
|
||||||
|
type: "match";
|
||||||
|
path: PathStatement;
|
||||||
|
matches: MatchStatement[];
|
||||||
|
rules: AllowStatement[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ServiceStatement extends Node {
|
||||||
|
type: "service";
|
||||||
|
name: string;
|
||||||
|
matches: MatchStatement[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ParserError extends Error {
|
||||||
|
token: Token;
|
||||||
|
constructor(message: string, token: Token) {
|
||||||
|
super(message);
|
||||||
|
this.token = token;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function parse(tokens: Token[]) {
|
||||||
|
const tokenIterator = tokens[Symbol.iterator]();
|
||||||
|
let currentToken: Token = tokenIterator.next().value;
|
||||||
|
let nextToken: Token = tokenIterator.next().value;
|
||||||
|
|
||||||
|
const eatToken = (value?: string) => {
|
||||||
|
if (value && value !== currentToken.value) {
|
||||||
|
throw new ParserError(
|
||||||
|
`Unexpected token value, expected '${value}', received '${currentToken.value}'`,
|
||||||
|
currentToken
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let idx = currentToken.startIdx;
|
||||||
|
currentToken = nextToken;
|
||||||
|
nextToken = tokenIterator.next().value;
|
||||||
|
return idx;
|
||||||
|
};
|
||||||
|
|
||||||
|
const eatText = (): [string, number] => {
|
||||||
|
checkTypes("text");
|
||||||
|
let val = currentToken.value;
|
||||||
|
let idx = currentToken.startIdx;
|
||||||
|
eatToken();
|
||||||
|
return [val, idx];
|
||||||
|
};
|
||||||
|
const eatNumber = (): number => {
|
||||||
|
checkTypes("number");
|
||||||
|
let val = Number(currentToken.value);
|
||||||
|
if (Number.isNaN(val)) {
|
||||||
|
throw new ParserError(
|
||||||
|
`Value cannot be parsed as number! ${currentToken.value}`,
|
||||||
|
currentToken
|
||||||
|
);
|
||||||
|
}
|
||||||
|
eatToken();
|
||||||
|
return val;
|
||||||
|
};
|
||||||
|
|
||||||
|
const checkTypes = (...types: string[]) => {
|
||||||
|
if (types.indexOf(currentToken.type) < 0) {
|
||||||
|
throw new ParserError(
|
||||||
|
`Unexpected token value, expected ${types.join(" | ")}, received '${
|
||||||
|
currentToken.value
|
||||||
|
}'`,
|
||||||
|
currentToken
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const parsePathStatement = (): PathStatement => {
|
||||||
|
const segments: (string | { name: string; type: "variable" })[] = [];
|
||||||
|
const idx = currentToken.startIdx;
|
||||||
|
let next = currentToken.type === "slash";
|
||||||
|
while (next) {
|
||||||
|
eatToken("/");
|
||||||
|
if (currentToken.type === "curly_open" && nextToken.type === "text") {
|
||||||
|
eatToken("{");
|
||||||
|
const [name] = eatText();
|
||||||
|
segments.push({
|
||||||
|
type: "variable",
|
||||||
|
name,
|
||||||
|
});
|
||||||
|
eatToken("}");
|
||||||
|
} else if (currentToken.type === "text") {
|
||||||
|
const [name] = eatText();
|
||||||
|
segments.push(name);
|
||||||
|
}
|
||||||
|
next = currentToken.type === "slash";
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: "path",
|
||||||
|
idx,
|
||||||
|
segments,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseValue = (): ValueStatement => {
|
||||||
|
const idx = currentToken.startIdx;
|
||||||
|
|
||||||
|
let isTrue = false;
|
||||||
|
let isFalse = false;
|
||||||
|
let isNull = false;
|
||||||
|
let isVariable = false;
|
||||||
|
let isNumber = false;
|
||||||
|
let isString = false;
|
||||||
|
let value: any = undefined;
|
||||||
|
if (currentToken.type === "keyword") {
|
||||||
|
if (currentToken.value === "true") isTrue = true;
|
||||||
|
else if (currentToken.value === "false") isFalse = true;
|
||||||
|
else if (currentToken.value === "null") isNull = true;
|
||||||
|
else {
|
||||||
|
throw new ParserError(
|
||||||
|
`Invalid keyword at this position ${currentToken.value}`,
|
||||||
|
currentToken
|
||||||
|
);
|
||||||
|
}
|
||||||
|
eatToken();
|
||||||
|
} else if (currentToken.type === "string") {
|
||||||
|
isString = true;
|
||||||
|
value = currentToken.value.slice(1, currentToken.value.length - 1);
|
||||||
|
eatToken();
|
||||||
|
} else if (currentToken.type === "number") {
|
||||||
|
isNumber = true;
|
||||||
|
value = eatNumber();
|
||||||
|
} else if (currentToken.type === "text") {
|
||||||
|
isVariable = true;
|
||||||
|
[value] = eatText();
|
||||||
|
} else {
|
||||||
|
throw new ParserError(
|
||||||
|
`Expected value got ${currentToken.type}`,
|
||||||
|
currentToken
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: "value",
|
||||||
|
isFalse,
|
||||||
|
isNull,
|
||||||
|
isNumber,
|
||||||
|
isString,
|
||||||
|
isTrue,
|
||||||
|
isVariable,
|
||||||
|
value,
|
||||||
|
idx,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseCondition = (): Expression | ValueStatement => {
|
||||||
|
// let running = true;
|
||||||
|
let res: Expression | ValueStatement;
|
||||||
|
let left: Expression | ValueStatement | undefined;
|
||||||
|
|
||||||
|
// while (running) {
|
||||||
|
const idx = currentToken.startIdx;
|
||||||
|
|
||||||
|
if (!left) {
|
||||||
|
if (currentToken.type === "bracket_open") {
|
||||||
|
eatToken("(");
|
||||||
|
left = parseCondition();
|
||||||
|
eatToken(")");
|
||||||
|
} else {
|
||||||
|
left = parseValue();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentToken.type === "comparison_operator") {
|
||||||
|
const operator = currentToken.value;
|
||||||
|
|
||||||
|
eatToken();
|
||||||
|
|
||||||
|
let right: Expression | ValueStatement;
|
||||||
|
|
||||||
|
let ct = currentToken; //Quick hack because of TypeScript
|
||||||
|
if (ct.type === "bracket_open") {
|
||||||
|
eatToken("(");
|
||||||
|
right = parseCondition();
|
||||||
|
eatToken(")");
|
||||||
|
} else {
|
||||||
|
right = parseValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
res = {
|
||||||
|
type: "expression",
|
||||||
|
left,
|
||||||
|
right,
|
||||||
|
operator: operator as Operators,
|
||||||
|
idx,
|
||||||
|
};
|
||||||
|
} else if (currentToken.type === "logic_operator") {
|
||||||
|
const operator = currentToken.value;
|
||||||
|
|
||||||
|
eatToken();
|
||||||
|
|
||||||
|
const right = parseCondition();
|
||||||
|
|
||||||
|
res = {
|
||||||
|
type: "expression",
|
||||||
|
left,
|
||||||
|
operator: operator as Operators,
|
||||||
|
right,
|
||||||
|
idx,
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
res = left;
|
||||||
|
}
|
||||||
|
|
||||||
|
// let ct = currentToken;
|
||||||
|
// if (
|
||||||
|
// ct.type === "comparison_operator" ||
|
||||||
|
// ct.type === "logic_operator"
|
||||||
|
// ) {
|
||||||
|
// left = res;
|
||||||
|
// } else {
|
||||||
|
// running = false;
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
return res;
|
||||||
|
};
|
||||||
|
|
||||||
|
const parsePermissionStatement = (): AllowStatement => {
|
||||||
|
const idx = eatToken("allow");
|
||||||
|
|
||||||
|
const operations: Operations[] = [];
|
||||||
|
let next = currentToken.type !== "colon";
|
||||||
|
while (next) {
|
||||||
|
const [operation] = eatText();
|
||||||
|
operations.push(operation as Operations);
|
||||||
|
if (currentToken.type === "comma") {
|
||||||
|
next = true;
|
||||||
|
eatToken(",");
|
||||||
|
} else {
|
||||||
|
next = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
eatToken(":");
|
||||||
|
|
||||||
|
eatToken("if");
|
||||||
|
|
||||||
|
const condition = parseCondition();
|
||||||
|
|
||||||
|
eatToken(";");
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: "permission",
|
||||||
|
idx,
|
||||||
|
operations,
|
||||||
|
condition,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseMatchStatement = (): MatchStatement => {
|
||||||
|
const idx = eatToken("match");
|
||||||
|
const path = parsePathStatement();
|
||||||
|
|
||||||
|
eatToken("{");
|
||||||
|
const matches: MatchStatement[] = [];
|
||||||
|
const permissions: AllowStatement[] = [];
|
||||||
|
while (currentToken.type !== "curly_close") {
|
||||||
|
if (currentToken.value === "match") {
|
||||||
|
matches.push(parseMatchStatement());
|
||||||
|
} else if (currentToken.value === "allow") {
|
||||||
|
permissions.push(parsePermissionStatement());
|
||||||
|
} else {
|
||||||
|
throw new ParserError(
|
||||||
|
`Unexpected token value, expected 'match' or 'allow', received '${currentToken.value}'`,
|
||||||
|
currentToken
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
eatToken("}");
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: "match",
|
||||||
|
path,
|
||||||
|
idx,
|
||||||
|
matches,
|
||||||
|
rules: permissions,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseServiceStatement = (): ServiceStatement => {
|
||||||
|
const idx = eatToken("service");
|
||||||
|
let [name] = eatText();
|
||||||
|
eatToken("{");
|
||||||
|
const matches: MatchStatement[] = [];
|
||||||
|
while (currentToken.value === "match") {
|
||||||
|
matches.push(parseMatchStatement());
|
||||||
|
}
|
||||||
|
eatToken("}");
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: "service",
|
||||||
|
name: name,
|
||||||
|
idx,
|
||||||
|
matches,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const nodes: ServiceStatement[] = [];
|
||||||
|
while (currentToken) {
|
||||||
|
nodes.push(parseServiceStatement());
|
||||||
|
}
|
||||||
|
return nodes;
|
||||||
|
}
|
98
src/rules/tokenise.ts
Normal file
98
src/rules/tokenise.ts
Normal file
@ -0,0 +1,98 @@
|
|||||||
|
export type TokenTypes =
|
||||||
|
| "space"
|
||||||
|
| "comment"
|
||||||
|
| "string"
|
||||||
|
| "keyword"
|
||||||
|
| "colon"
|
||||||
|
| "semicolon"
|
||||||
|
| "comma"
|
||||||
|
| "comparison_operator"
|
||||||
|
| "logic_operator"
|
||||||
|
| "equals"
|
||||||
|
| "slash"
|
||||||
|
| "bracket_open"
|
||||||
|
| "bracket_close"
|
||||||
|
| "curly_open"
|
||||||
|
| "curly_close"
|
||||||
|
| "array"
|
||||||
|
| "questionmark"
|
||||||
|
| "number"
|
||||||
|
| "text";
|
||||||
|
|
||||||
|
export type Token = {
|
||||||
|
type: TokenTypes;
|
||||||
|
value: string;
|
||||||
|
startIdx: number;
|
||||||
|
endIdx: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Matcher = (input: string, index: number) => undefined | Token;
|
||||||
|
|
||||||
|
export class TokenizerError extends Error {
|
||||||
|
index: number;
|
||||||
|
constructor(message: string, index: number) {
|
||||||
|
super(message);
|
||||||
|
this.index = index;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function regexMatcher(regex: string | RegExp, type: TokenTypes): Matcher {
|
||||||
|
if (typeof regex === "string") regex = new RegExp(regex);
|
||||||
|
|
||||||
|
return (input: string, index: number) => {
|
||||||
|
let matches = input.substring(index).match(regex as RegExp);
|
||||||
|
if (!matches || matches.length <= 0) return undefined;
|
||||||
|
|
||||||
|
return {
|
||||||
|
type,
|
||||||
|
value: matches[0],
|
||||||
|
startIdx: index,
|
||||||
|
endIdx: index + matches[0].length,
|
||||||
|
} as Token;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const matcher = [
|
||||||
|
regexMatcher(/^\s+/, "space"),
|
||||||
|
regexMatcher(/^\/\/.+/, "comment"),
|
||||||
|
regexMatcher(/^#.+/, "comment"),
|
||||||
|
regexMatcher(/^".*?"/, "string"),
|
||||||
|
// regexMatcher(/(?<=^")(.*?)(?=")/, "string"),
|
||||||
|
regexMatcher(/^(service|match|allow|if|true|false|null)/, "keyword"),
|
||||||
|
regexMatcher(/^\:/, "colon"),
|
||||||
|
regexMatcher(/^\;/, "semicolon"),
|
||||||
|
regexMatcher(/^\,/, "comma"),
|
||||||
|
regexMatcher(/^(\=\=|\!\=|\<\=|\>\=|\>|\<)/, "comparison_operator"),
|
||||||
|
regexMatcher(/^(&&|\|\|)/, "logic_operator"),
|
||||||
|
regexMatcher(/^\=/, "equals"),
|
||||||
|
regexMatcher(/^\//, "slash"),
|
||||||
|
regexMatcher(/^\(/, "bracket_open"),
|
||||||
|
regexMatcher(/^\)/, "bracket_close"),
|
||||||
|
regexMatcher(/^{/, "curly_open"),
|
||||||
|
regexMatcher(/^}/, "curly_close"),
|
||||||
|
regexMatcher(/^\[\]/, "array"),
|
||||||
|
regexMatcher(/^\?/, "questionmark"),
|
||||||
|
regexMatcher(/^[0-9]+(\.[0-9]+)?/, "number"),
|
||||||
|
regexMatcher(/^[a-zA-Z_\*]([a-zA-Z0-9_\.\*]?)+/, "text"),
|
||||||
|
];
|
||||||
|
|
||||||
|
export default function tokenize(input: string) {
|
||||||
|
let index = 0;
|
||||||
|
let tokens: Token[] = [];
|
||||||
|
while (index < input.length) {
|
||||||
|
const matches = matcher.map((m) => m(input, index)).filter((e) => !!e);
|
||||||
|
let match = matches[0];
|
||||||
|
if (match) {
|
||||||
|
if (match.type !== "space" && match.type !== "comment") {
|
||||||
|
tokens.push(match);
|
||||||
|
}
|
||||||
|
index += match.value.length;
|
||||||
|
} else {
|
||||||
|
throw new TokenizerError(
|
||||||
|
`Unexpected token '${input.substring(index, index + 1)}'`,
|
||||||
|
index
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return tokens;
|
||||||
|
}
|
@ -2,19 +2,29 @@ import { getTemplate } from "./hb";
|
|||||||
import { Context } from "vm";
|
import { Context } from "vm";
|
||||||
|
|
||||||
interface IFormConfigField {
|
interface IFormConfigField {
|
||||||
type: "text" | "number" | "boolean" | "textarea";
|
type: "text" | "number" | "boolean" | "textarea" | "codemirror";
|
||||||
label: string;
|
label: string;
|
||||||
value?: string;
|
value?: string;
|
||||||
|
disabled?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
type IFormConfig = { [name: string]: IFormConfigField }
|
type IFormConfig = { [name: string]: IFormConfigField };
|
||||||
|
|
||||||
export default function getForm(url: string, title: string, fieldConfig: IFormConfig): (ctx: Context) => void {
|
export default function getForm(
|
||||||
let fields = Object.keys(fieldConfig).map(name => ({ name, ...fieldConfig[name] }))
|
url: string,
|
||||||
|
title: string,
|
||||||
|
fieldConfig: IFormConfig
|
||||||
|
): (ctx: Context) => void {
|
||||||
|
let fields = Object.keys(fieldConfig).map((name) => ({
|
||||||
|
name,
|
||||||
|
...fieldConfig[name],
|
||||||
|
disabled: fieldConfig.disabled ? "disabled" : "",
|
||||||
|
}));
|
||||||
|
|
||||||
return ctx => ctx.body = getTemplate("forms")({
|
return (ctx) =>
|
||||||
url,
|
(ctx.body = getTemplate("forms")({
|
||||||
title,
|
url,
|
||||||
fields
|
title,
|
||||||
});
|
fields,
|
||||||
}
|
}));
|
||||||
|
}
|
||||||
|
@ -2,7 +2,11 @@ import * as Router from "koa-router";
|
|||||||
import Settings from "../../settings";
|
import Settings from "../../settings";
|
||||||
import getForm from "../helper/form";
|
import getForm from "../helper/form";
|
||||||
import getTable from "../helper/table";
|
import getTable from "../helper/table";
|
||||||
import { BadRequestError, NoPermissionError } from "../helper/errors";
|
import {
|
||||||
|
BadRequestError,
|
||||||
|
NoPermissionError,
|
||||||
|
NotFoundError,
|
||||||
|
} from "../helper/errors";
|
||||||
import { DatabaseManager } from "../../database/database";
|
import { DatabaseManager } from "../../database/database";
|
||||||
import { MP } from "../../database/query";
|
import { MP } from "../../database/query";
|
||||||
import config from "../../config";
|
import config from "../../config";
|
||||||
@ -13,146 +17,140 @@ const AdminRoute = new Router();
|
|||||||
|
|
||||||
AdminRoute.use(async (ctx, next) => {
|
AdminRoute.use(async (ctx, next) => {
|
||||||
const { key } = ctx.query;
|
const { key } = ctx.query;
|
||||||
if (key !== config.admin)
|
if (key !== config.admin) throw new NoPermissionError("No permission!");
|
||||||
throw new NoPermissionError("No permission!");
|
|
||||||
return next();
|
return next();
|
||||||
})
|
});
|
||||||
|
|
||||||
AdminRoute.get("/", async ctx => {
|
AdminRoute.get("/", async (ctx) => {
|
||||||
//TODO: Main Interface
|
//TODO: Main Interface
|
||||||
ctx.body = getView("admin");
|
ctx.body = getView("admin");
|
||||||
});
|
});
|
||||||
|
|
||||||
AdminRoute.get("/settings", async ctx => {
|
AdminRoute.get("/settings", async (ctx) => {
|
||||||
let res = await new Promise<string[][]>((yes, no) => {
|
let res = await new Promise<string[][]>((yes, no) => {
|
||||||
const stream = Settings.db.createReadStream({
|
const stream = Settings.db.createReadStream({
|
||||||
keys: true,
|
keys: true,
|
||||||
values: true,
|
values: true,
|
||||||
valueAsBuffer: true
|
valueAsBuffer: true,
|
||||||
});
|
});
|
||||||
let res = [["key", "value"]];
|
let res = [["key", "value"]];
|
||||||
stream.on("data", ({ key, value }) => {
|
stream.on("data", ({ key, value }) => {
|
||||||
res.push([key, value]);
|
res.push([key, value]);
|
||||||
})
|
});
|
||||||
|
|
||||||
stream.on("error", no);
|
stream.on("error", no);
|
||||||
stream.on("end", () => yes(res))
|
stream.on("end", () => yes(res));
|
||||||
})
|
});
|
||||||
|
|
||||||
if (ctx.query.view) {
|
if (ctx.query.view) {
|
||||||
return getTable("Settings", res, ctx);
|
return getTable("Settings", res, ctx);
|
||||||
} else {
|
} else {
|
||||||
ctx.body = res;
|
ctx.body = res;
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
|
|
||||||
AdminRoute.get("/data", async ctx => {
|
AdminRoute.get("/data", async (ctx) => {
|
||||||
const { database } = ctx.query;
|
const { database } = ctx.query;
|
||||||
let db = DatabaseManager.getDatabase(database);
|
let db = DatabaseManager.getDatabase(database);
|
||||||
if (!db)
|
if (!db) throw new BadRequestError("Database not found");
|
||||||
throw new BadRequestError("Database not found");
|
|
||||||
let res = await new Promise<string[][]>((yes, no) => {
|
let res = await new Promise<string[][]>((yes, no) => {
|
||||||
|
|
||||||
const stream = db.data.createReadStream({
|
const stream = db.data.createReadStream({
|
||||||
keys: true,
|
keys: true,
|
||||||
values: true,
|
values: true,
|
||||||
valueAsBuffer: true,
|
valueAsBuffer: true,
|
||||||
keyAsBuffer: false,
|
keyAsBuffer: false,
|
||||||
limit: 1000
|
limit: 1000,
|
||||||
});
|
});
|
||||||
let res = [["key", "value"]];
|
let res = [["key", "value"]];
|
||||||
stream.on("data", ({ key, value }: { key: string, value: Buffer }) => {
|
stream.on("data", ({ key, value }: { key: string; value: Buffer }) => {
|
||||||
res.push([key, key.split("/").length > 2 ? value.toString() : JSON.stringify(MP.decode(value))]);
|
res.push([
|
||||||
})
|
key,
|
||||||
|
key.split("/").length > 2
|
||||||
|
? value.toString()
|
||||||
|
: JSON.stringify(MP.decode(value)),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
stream.on("error", no);
|
stream.on("error", no);
|
||||||
stream.on("end", () => yes(res))
|
stream.on("end", () => yes(res));
|
||||||
})
|
});
|
||||||
|
|
||||||
if (ctx.query.view) {
|
if (ctx.query.view) {
|
||||||
return getTable("Data from " + database, res, ctx);
|
return getTable("Data from " + database, res, ctx);
|
||||||
} else {
|
} else {
|
||||||
ctx.body = res;
|
ctx.body = res;
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
|
|
||||||
AdminRoute
|
AdminRoute.get("/database", (ctx) => {
|
||||||
.get("/database", ctx => {
|
const isFull = ctx.query.full === "true" || ctx.query.full === "1";
|
||||||
const isFull = ctx.query.full === "true" || ctx.query.full === "1";
|
let res;
|
||||||
let res;
|
if (isFull) {
|
||||||
if (isFull) {
|
//TODO: Better than JSON.parse / JSON.stringify
|
||||||
//TODO: Better than JSON.parse / JSON.stringify
|
res = Array.from(DatabaseManager.databases.entries()).map(
|
||||||
res = Array.from(DatabaseManager.databases.entries()).map(([name, config]) => ({ name, ...(JSON.parse(JSON.stringify(config))) }));
|
([name, config]) => ({
|
||||||
} else {
|
name,
|
||||||
res = Array.from(DatabaseManager.databases.keys());
|
...JSON.parse(JSON.stringify(config)),
|
||||||
}
|
})
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
res = Array.from(DatabaseManager.databases.keys());
|
||||||
|
}
|
||||||
|
|
||||||
if (ctx.query.view) {
|
if (ctx.query.view) {
|
||||||
return getTable("Databases" + (isFull ? "" : " small"), res, ctx);
|
return getTable("Databases" + (isFull ? "" : " small"), res, ctx);
|
||||||
} else {
|
} else {
|
||||||
ctx.body = res;
|
ctx.body = res;
|
||||||
}
|
}
|
||||||
})
|
}).post("/database", async (ctx) => {
|
||||||
.post("/database", async ctx => {
|
const { name, rules, publickey, accesskey, rootkey } = ctx.request.body;
|
||||||
const { name, rules, publickey, accesskey, rootkey } = ctx.request.body;
|
|
||||||
|
|
||||||
if (!name)
|
if (!name) throw new BadRequestError("Name must be set!");
|
||||||
throw new BadRequestError("Name must be set!");
|
|
||||||
|
|
||||||
let db = DatabaseManager.getDatabase(name);
|
let db = DatabaseManager.getDatabase(name);
|
||||||
if (!db)
|
if (!db) db = await DatabaseManager.addDatabase(name);
|
||||||
db = await DatabaseManager.addDatabase(name);
|
|
||||||
|
|
||||||
if (publickey)
|
if (publickey) await db.setPublicKey(publickey);
|
||||||
await db.setPublicKey(publickey);
|
|
||||||
|
|
||||||
if (rules)
|
if (rules) await db.setRules(rules);
|
||||||
await db.setRules(rules);
|
|
||||||
|
|
||||||
if (accesskey)
|
if (accesskey) await db.setAccessKey(accesskey);
|
||||||
await db.setAccessKey(accesskey);
|
|
||||||
|
|
||||||
|
if (rootkey) await db.setRootKey(rootkey);
|
||||||
|
|
||||||
if (rootkey)
|
ctx.body = "Success";
|
||||||
await db.setRootKey(rootkey);
|
});
|
||||||
|
|
||||||
|
AdminRoute.get("/collections", async (ctx) => {
|
||||||
ctx.body = "Success";
|
|
||||||
})
|
|
||||||
|
|
||||||
AdminRoute.get("/collections", async ctx => {
|
|
||||||
const { database } = ctx.query;
|
const { database } = ctx.query;
|
||||||
let db = DatabaseManager.getDatabase(database);
|
let db = DatabaseManager.getDatabase(database);
|
||||||
if (!db)
|
if (!db) throw new BadRequestError("Database not found");
|
||||||
throw new BadRequestError("Database not found");
|
|
||||||
|
|
||||||
let res = await new Promise<string[]>((yes, no) => {
|
let res = await new Promise<string[]>((yes, no) => {
|
||||||
|
|
||||||
const stream = db.collections.createKeyStream({
|
const stream = db.collections.createKeyStream({
|
||||||
keyAsBuffer: false,
|
keyAsBuffer: false,
|
||||||
limit: 1000
|
limit: 1000,
|
||||||
});
|
});
|
||||||
let res = [];
|
let res = [];
|
||||||
stream.on("data", (key: string) => {
|
stream.on("data", (key: string) => {
|
||||||
res.push(key);
|
res.push(key);
|
||||||
})
|
});
|
||||||
|
|
||||||
stream.on("error", no);
|
stream.on("error", no);
|
||||||
stream.on("end", () => yes(res))
|
stream.on("end", () => yes(res));
|
||||||
})
|
});
|
||||||
|
|
||||||
if (ctx.query.view) {
|
if (ctx.query.view) {
|
||||||
return getTable("Databases", res, ctx);
|
return getTable("Databases", res, ctx);
|
||||||
} else {
|
} else {
|
||||||
ctx.body = res;
|
ctx.body = res;
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
|
|
||||||
AdminRoute.get("/collections/cleanup", async ctx => {
|
AdminRoute.get("/collections/cleanup", async (ctx) => {
|
||||||
const { database } = ctx.query;
|
const { database } = ctx.query;
|
||||||
let db = DatabaseManager.getDatabase(database);
|
let db = DatabaseManager.getDatabase(database);
|
||||||
if (!db)
|
if (!db) throw new BadRequestError("Database not found");
|
||||||
throw new BadRequestError("Database not found");
|
|
||||||
|
|
||||||
let deleted = await db.runCleanup();
|
let deleted = await db.runCleanup();
|
||||||
if (ctx.query.view) {
|
if (ctx.query.view) {
|
||||||
@ -160,14 +158,55 @@ AdminRoute.get("/collections/cleanup", async ctx => {
|
|||||||
} else {
|
} else {
|
||||||
ctx.body = deleted;
|
ctx.body = deleted;
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
|
|
||||||
AdminRoute.get("/database/new", getForm("/v1/admin/database", "New/Change Database", {
|
AdminRoute.get(
|
||||||
name: { label: "Name", type: "text", },
|
"/database/new",
|
||||||
accesskey: { label: "Access Key", type: "text" },
|
getForm("/v1/admin/database", "New Database", {
|
||||||
rootkey: { label: "Root access key", type: "text" },
|
name: { label: "Name", type: "text" },
|
||||||
rules: { label: "Rules", type: "textarea", value: `{\n ".write": true, \n ".read": true \n}` },
|
accesskey: { label: "Access Key", type: "text" },
|
||||||
publickey: { label: "Public Key", type: "textarea" }
|
rootkey: { label: "Root access key", type: "text" },
|
||||||
}))
|
rules: {
|
||||||
|
label: "Rules",
|
||||||
|
type: "codemirror",
|
||||||
|
value: `{\n ".write": true, \n ".read": true \n}`,
|
||||||
|
},
|
||||||
|
publickey: { label: "Public Key", type: "textarea" },
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
export default AdminRoute;
|
AdminRoute.get("/database/update", async (ctx) => {
|
||||||
|
const { database } = ctx.query;
|
||||||
|
let db = DatabaseManager.getDatabase(database);
|
||||||
|
if (!db) throw new NotFoundError("Database not found!");
|
||||||
|
getForm("/v1/admin/database", "Change Database", {
|
||||||
|
name: {
|
||||||
|
label: "Name",
|
||||||
|
type: "text",
|
||||||
|
value: db.name,
|
||||||
|
disabled: true,
|
||||||
|
},
|
||||||
|
accesskey: {
|
||||||
|
label: "Access Key",
|
||||||
|
type: "text",
|
||||||
|
value: db.accesskey,
|
||||||
|
},
|
||||||
|
rootkey: {
|
||||||
|
label: "Root access key",
|
||||||
|
type: "text",
|
||||||
|
value: db.rootkey,
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
label: "Rules",
|
||||||
|
type: "codemirror",
|
||||||
|
value: db.rawRules,
|
||||||
|
},
|
||||||
|
publickey: {
|
||||||
|
label: "Public Key",
|
||||||
|
type: "textarea",
|
||||||
|
value: db.publickey,
|
||||||
|
},
|
||||||
|
})(ctx);
|
||||||
|
});
|
||||||
|
|
||||||
|
export default AdminRoute;
|
||||||
|
@ -4,18 +4,18 @@ import { DatabaseManager } from "../../database/database";
|
|||||||
import {
|
import {
|
||||||
NotFoundError,
|
NotFoundError,
|
||||||
NoPermissionError,
|
NoPermissionError,
|
||||||
BadRequestError
|
BadRequestError,
|
||||||
} from "../helper/errors";
|
} from "../helper/errors";
|
||||||
import Logging from "@hibas123/nodelogging";
|
import Logging from "@hibas123/nodelogging";
|
||||||
import Session from "../../database/session";
|
import Session from "../../database/session";
|
||||||
import nanoid = require("nanoid");
|
import { nanoid } from "nanoid";
|
||||||
import { verifyJWT } from "../../helper/jwt";
|
import { verifyJWT } from "../../helper/jwt";
|
||||||
import { QueryError } from "../../database/query";
|
import { QueryError } from "../../database/query";
|
||||||
const V1 = new Router({ prefix: "/v1" });
|
const V1 = new Router({ prefix: "/v1" });
|
||||||
|
|
||||||
V1.use("/admin", AdminRoute.routes(), AdminRoute.allowedMethods());
|
V1.use("/admin", AdminRoute.routes(), AdminRoute.allowedMethods());
|
||||||
|
|
||||||
V1.post("/db/:database/query", async ctx => {
|
V1.post("/db/:database/query", async (ctx) => {
|
||||||
const { database } = ctx.params;
|
const { database } = ctx.params;
|
||||||
const { accesskey, authkey, rootkey } = ctx.query;
|
const { accesskey, authkey, rootkey } = ctx.query;
|
||||||
|
|
||||||
@ -38,6 +38,7 @@ V1.post("/db/:database/query", async ctx => {
|
|||||||
|
|
||||||
if (authkey && db.publickey) {
|
if (authkey && db.publickey) {
|
||||||
let res = await verifyJWT(authkey, db.publickey);
|
let res = await verifyJWT(authkey, db.publickey);
|
||||||
|
if (res && !res.uid && res.user) res.uid = res.user;
|
||||||
if (!res || !res.uid) {
|
if (!res || !res.uid) {
|
||||||
throw new BadRequestError("Invalid JWT");
|
throw new BadRequestError("Invalid JWT");
|
||||||
} else {
|
} else {
|
||||||
@ -52,7 +53,7 @@ V1.post("/db/:database/query", async ctx => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx.body = await db.run([query], session).catch(err => {
|
ctx.body = await db.run([query], session).catch((err) => {
|
||||||
if (err instanceof QueryError) {
|
if (err instanceof QueryError) {
|
||||||
throw new BadRequestError(err.message);
|
throw new BadRequestError(err.message);
|
||||||
}
|
}
|
||||||
|
@ -2,12 +2,17 @@ import Logging from "@hibas123/nodelogging";
|
|||||||
import { IncomingMessage, Server } from "http";
|
import { IncomingMessage, Server } from "http";
|
||||||
import * as WebSocket from "ws";
|
import * as WebSocket from "ws";
|
||||||
import { DatabaseManager } from "./database/database";
|
import { DatabaseManager } from "./database/database";
|
||||||
import { CollectionQuery, DocumentQuery, IQuery, ITypedQuery } from "./database/query";
|
import {
|
||||||
|
CollectionQuery,
|
||||||
|
DocumentQuery,
|
||||||
|
IQuery,
|
||||||
|
ITypedQuery,
|
||||||
|
} from "./database/query";
|
||||||
import Session from "./database/session";
|
import Session from "./database/session";
|
||||||
import { verifyJWT } from "./helper/jwt";
|
import { verifyJWT } from "./helper/jwt";
|
||||||
import nanoid = require("nanoid");
|
import { nanoid } from "nanoid";
|
||||||
|
|
||||||
export class ConnectionManager {
|
export class WebsocketConnectionManager {
|
||||||
static server: WebSocket.Server;
|
static server: WebSocket.Server;
|
||||||
|
|
||||||
static bind(server: Server) {
|
static bind(server: Server) {
|
||||||
@ -17,7 +22,14 @@ export class ConnectionManager {
|
|||||||
|
|
||||||
private static async onConnection(socket: WebSocket, req: IncomingMessage) {
|
private static async onConnection(socket: WebSocket, req: IncomingMessage) {
|
||||||
Logging.log("New Connection:");
|
Logging.log("New Connection:");
|
||||||
const sendError = (error: string) => socket.send(JSON.stringify({ ns: "error_msg", data: error }));
|
|
||||||
|
socket.on("error", (err) => {
|
||||||
|
Logging.error(err);
|
||||||
|
socket.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
const sendError = (error: string) =>
|
||||||
|
socket.send(JSON.stringify({ ns: "error_msg", data: error }));
|
||||||
|
|
||||||
const session = new Session(nanoid());
|
const session = new Session(nanoid());
|
||||||
|
|
||||||
@ -43,6 +55,7 @@ export class ConnectionManager {
|
|||||||
const authkey = query.get("authkey");
|
const authkey = query.get("authkey");
|
||||||
if (authkey && db.publickey) {
|
if (authkey && db.publickey) {
|
||||||
let res = await verifyJWT(authkey, db.publickey);
|
let res = await verifyJWT(authkey, db.publickey);
|
||||||
|
if (res && !res.uid && res.user) res.uid = res.user;
|
||||||
if (!res || !res.uid) {
|
if (!res || !res.uid) {
|
||||||
sendError("Invalid JWT");
|
sendError("Invalid JWT");
|
||||||
socket.close();
|
socket.close();
|
||||||
@ -60,17 +73,30 @@ export class ConnectionManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const answer = (id: string, data: any, error: boolean = false) => {
|
const answer = (id: string, data: any, err?: Error | string) => {
|
||||||
if (error)
|
let error = false;
|
||||||
Logging.error(error as any);
|
if (err) {
|
||||||
socket.send(JSON.stringify({ ns: "message", data: { id, error, data } }));
|
Logging.error(err);
|
||||||
}
|
if (err instanceof Error) {
|
||||||
|
data = err.message;
|
||||||
|
} else {
|
||||||
|
data = err;
|
||||||
|
}
|
||||||
|
|
||||||
const handler = new Map<string, ((data: any) => void)>();
|
error = true;
|
||||||
|
}
|
||||||
|
socket.send(
|
||||||
|
JSON.stringify({ ns: "message", data: { id, error, data } })
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
handler.set("v2", async ({ id, query }) => db.run(Array.isArray(query) ? query : [query], session)
|
const handler = new Map<string, (data: any) => void>();
|
||||||
.then(res => answer(id, res))
|
|
||||||
.catch(err => answer(id, undefined, err))
|
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)
|
// handler.set("bulk", async ({ id, query }) => db.run(query, session)
|
||||||
@ -78,18 +104,32 @@ export class ConnectionManager {
|
|||||||
// .catch(err => answer(id, undefined, err))
|
// .catch(err => answer(id, undefined, err))
|
||||||
// );
|
// );
|
||||||
|
|
||||||
|
|
||||||
const SnapshotMap = new Map<string, string>();
|
const SnapshotMap = new Map<string, string>();
|
||||||
handler.set("snapshot", async ({ id, query }: { id: string, query: ITypedQuery<"snapshot"> }) => {
|
handler.set(
|
||||||
db.snapshot(query, session, (data => {
|
"snapshot",
|
||||||
socket.send(JSON.stringify({
|
async ({
|
||||||
ns: "snapshot", data: { id, data }
|
id,
|
||||||
}));
|
query,
|
||||||
})).then(s => {
|
}: {
|
||||||
answer(id, s.snaphot);
|
id: string;
|
||||||
SnapshotMap.set(id, s.id);
|
query: ITypedQuery<"snapshot">;
|
||||||
}).catch(err => answer(id, undefined, err));
|
}) => {
|
||||||
})
|
db.snapshot(query, session, (data) => {
|
||||||
|
Logging.debug("Sending snapshot");
|
||||||
|
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 }) => {
|
handler.set("unsubscribe", async ({ id }) => {
|
||||||
let i = SnapshotMap.get(id);
|
let i = SnapshotMap.get(id);
|
||||||
@ -97,11 +137,11 @@ export class ConnectionManager {
|
|||||||
db.unsubscribe(i, session);
|
db.unsubscribe(i, session);
|
||||||
SnapshotMap.delete(i);
|
SnapshotMap.delete(i);
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
|
|
||||||
socket.on("message", async (rawData: string) => {
|
socket.on("message", async (rawData: string) => {
|
||||||
try {
|
try {
|
||||||
let message: { ns: string, data: any } = JSON.parse(rawData);
|
let message: { ns: string; data: any } = JSON.parse(rawData);
|
||||||
let h = handler.get(message.ns);
|
let h = handler.get(message.ns);
|
||||||
if (h) {
|
if (h) {
|
||||||
h(message.data);
|
h(message.data);
|
||||||
@ -110,13 +150,14 @@ export class ConnectionManager {
|
|||||||
Logging.errorMessage("Unknown Error:");
|
Logging.errorMessage("Unknown Error:");
|
||||||
Logging.error(err);
|
Logging.error(err);
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
|
db.connections++;
|
||||||
socket.on("close", () => {
|
socket.on("close", () => {
|
||||||
|
db.connections--;
|
||||||
Logging.log(`${session.id} has disconnected!`);
|
Logging.log(`${session.id} has disconnected!`);
|
||||||
session.subscriptions.forEach(unsubscribe => unsubscribe());
|
session.subscriptions.forEach((unsubscribe) => unsubscribe());
|
||||||
session.subscriptions.clear();
|
session.subscriptions.clear();
|
||||||
socket.removeAllListeners();
|
socket.removeAllListeners();
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,21 +1,17 @@
|
|||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
/* Basic Options */
|
/* Basic Options */
|
||||||
"target": "es2017", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
|
"target": "es2019" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
|
||||||
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
|
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
|
||||||
"declaration": true, /* Generates corresponding '.d.ts' file. */
|
"declaration": true /* Generates corresponding '.d.ts' file. */,
|
||||||
"sourceMap": true, /* Generates corresponding '.map' file. */
|
"sourceMap": true /* Generates corresponding '.map' file. */,
|
||||||
"outDir": "./lib", /* Redirect output structure to the directory. */
|
"outDir": "./lib" /* Redirect output structure to the directory. */,
|
||||||
"strict": false, /* Enable all strict type-checking options. */
|
"strict": false /* Enable all strict type-checking options. */,
|
||||||
"preserveWatchOutput": true,
|
"preserveWatchOutput": true,
|
||||||
"experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
|
"experimentalDecorators": true /* Enables experimental support for ES7 decorators. */,
|
||||||
"emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
|
"emitDecoratorMetadata": true /* Enables experimental support for emitting type metadata for decorators. */,
|
||||||
"resolveJsonModule": true
|
"resolveJsonModule": true
|
||||||
},
|
},
|
||||||
"exclude": [
|
"exclude": ["node_modules/"],
|
||||||
"node_modules/"
|
"include": ["./src"]
|
||||||
],
|
}
|
||||||
"include": [
|
|
||||||
"./src"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
189
views/admin.html
189
views/admin.html
@ -1,112 +1,125 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<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>
|
<script src="https://unpkg.com/handlebars/dist/handlebars.min.js"></script>
|
||||||
<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>
|
<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>
|
.grid {
|
||||||
#message {
|
display: grid;
|
||||||
visibility: hidden;
|
height: 100vh;
|
||||||
background-color: lightgreen;
|
grid-template-columns: 360px auto;
|
||||||
border: 1px solid lime;
|
}
|
||||||
border-radius: .5rem;
|
|
||||||
padding: 1rem;
|
|
||||||
font-size: 1.5rem;
|
|
||||||
margin-bottom: 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.grid {
|
#navigation {
|
||||||
display: grid;
|
height: 100vh;
|
||||||
height: 100vh;
|
overflow: auto;
|
||||||
grid-template-columns: 360px auto;
|
border-right: 1px solid darkgrey;
|
||||||
}
|
padding: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
#content {
|
#content {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
top: 0;
|
top: 0;
|
||||||
left: 0;
|
left: 0;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 100%;
|
height: 100vh;
|
||||||
border: 0;
|
border: 0;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</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>
|
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<div class="grid">
|
||||||
|
<div id="navigation">
|
||||||
|
<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>
|
||||||
<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>
|
function getUrl(name, params, view = true) {
|
||||||
const key = new URL(window.location.href).searchParams.get("key");
|
const url = new URL(window.location.href);
|
||||||
const content = document.getElementById("content");
|
url.pathname = "/v1/admin/" + name;
|
||||||
const base = new URL(window.location.href).host;
|
for (let key in params || {})
|
||||||
|
url.searchParams.set(key, params[key]);
|
||||||
|
|
||||||
function getUrl(name, params, view = true) {
|
url.searchParams.set("key", key);
|
||||||
const url = new URL(window.location.href);
|
if (view) url.searchParams.set("view", "true");
|
||||||
url.pathname = "/v1/admin/" + name;
|
|
||||||
for (let key in params || {})
|
|
||||||
url.searchParams.set(key, params[key]);
|
|
||||||
|
|
||||||
url.searchParams.set("key", key);
|
return url.href;
|
||||||
if (view)
|
}
|
||||||
url.searchParams.set("view", "true");
|
|
||||||
|
|
||||||
return url.href;
|
function loadView(name, params) {
|
||||||
}
|
content.src = getUrl(name, params);
|
||||||
|
}
|
||||||
|
|
||||||
function loadView(name, params) {
|
loadView("settings");
|
||||||
content.src = getUrl(name, params);
|
|
||||||
}
|
|
||||||
|
|
||||||
loadView("settings")
|
const dbsul = document.getElementById("dbs");
|
||||||
|
function reloadDBs() {
|
||||||
const dbsul = document.getElementById("dbs");
|
fetch(getUrl("database", {}, false))
|
||||||
function reloadDBs() {
|
.then((res) => res.json())
|
||||||
fetch(getUrl("database", {}, false))
|
.then((databases) =>
|
||||||
.then(res => res.json())
|
databases.map(
|
||||||
.then(databases => databases.map(database => `
|
(database) => `
|
||||||
<div class="card margin elv-4">
|
<div class="card margin elv-4">
|
||||||
<h3>${database}</h3>
|
<h3>${database}</h3>
|
||||||
<button class=btn onclick="loadView('data', {database:'${database}'})">Data</button>
|
<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', {database:'${database}'})">Collections</button>
|
||||||
|
<button class=btn onclick="loadView('database/update', {database:'${database}'})">Change</button>
|
||||||
<button class=btn onclick="loadView('collections/cleanup', {database:'${database}'})">Clean</button>
|
<button class=btn onclick="loadView('collections/cleanup', {database:'${database}'})">Clean</button>
|
||||||
</div>`
|
</div>`
|
||||||
))
|
)
|
||||||
.then(d => d.join("\n"))
|
)
|
||||||
.then(d => dbsul.innerHTML = d)
|
.then((d) => d.join("\n"))
|
||||||
.catch(console.error)
|
.then((d) => (dbsul.innerHTML = d))
|
||||||
|
.catch(console.error);
|
||||||
|
}
|
||||||
|
|
||||||
|
reloadDBs();
|
||||||
}
|
setInterval(reloadDBs, 5000);
|
||||||
|
</script>
|
||||||
reloadDBs();
|
</body>
|
||||||
setInterval(reloadDBs, 5000);
|
</html>
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
|
|
||||||
</html>
|
|
||||||
|
@ -6,8 +6,9 @@
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<meta http-equiv="X-UA-Compatible" content="ie=edge">
|
<meta http-equiv="X-UA-Compatible" content="ie=edge">
|
||||||
<title>{{title}}</title>
|
<title>{{title}}</title>
|
||||||
<link rel="stylesheet" href="https://unpkg.com/@hibas123/theme/out/base.css">
|
<link rel="stylesheet" href="https://unpkg.com/@hibas123/theme@1/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/light.css">
|
||||||
|
<link rel="stylesheet" href="https://unpkg.com/codemirror@5.58.2/lib/codemirror.css">
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
#message {
|
#message {
|
||||||
@ -32,19 +33,23 @@
|
|||||||
<div class="input-group">
|
<div class="input-group">
|
||||||
<label>{{label}}</label>
|
<label>{{label}}</label>
|
||||||
{{#ifCond type "===" "text"}}
|
{{#ifCond type "===" "text"}}
|
||||||
<input type="text" placeholder="{{label}}" name="{{name}}" value="{{value}}" />
|
<input type="text" placeholder="{{label}}" name="{{name}}" value="{{value}}" {{disabled}} />
|
||||||
{{/ifCond}}
|
{{/ifCond}}
|
||||||
|
|
||||||
{{#ifCond type "===" "number"}}
|
{{#ifCond type "===" "number"}}
|
||||||
<input type="number" placeholder="{{label}}" name="{{name}}" value="{{value}}" />
|
<input type="number" placeholder="{{label}}" name="{{name}}" value="{{value}}" {{disabled}} />
|
||||||
{{/ifCond}}
|
{{/ifCond}}
|
||||||
|
|
||||||
{{#ifCond type "===" "boolean"}}
|
{{#ifCond type "===" "boolean"}}
|
||||||
<input type="checkbox" name="{{name}}" checked="{{value}}" />
|
<input type="checkbox" name="{{name}}" checked="{{value}}" {{disabled}} />
|
||||||
{{/ifCond}}
|
{{/ifCond}}
|
||||||
|
|
||||||
{{#ifCond type "===" "textarea"}}
|
{{#ifCond type "===" "textarea"}}
|
||||||
<textarea class="inp" name="{{name}}" rows="20">{{value}}</textarea>
|
<textarea class="inp" name="{{name}}" rows="20" {{disabled}}>{{value}}</textarea>
|
||||||
|
{{/ifCond}}
|
||||||
|
|
||||||
|
{{#ifCond type "===" "codemirror"}}
|
||||||
|
<textarea codemirror class="inp" name="{{name}}" rows="20" {{disabled}}>{{value}}</textarea>
|
||||||
{{/ifCond}}
|
{{/ifCond}}
|
||||||
</div>
|
</div>
|
||||||
{{/each}}
|
{{/each}}
|
||||||
@ -81,6 +86,19 @@
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
<script src="https://unpkg.com/codemirror@5.58.2/lib/codemirror.js"></script>
|
||||||
|
<script>
|
||||||
|
document.querySelectorAll("textarea[codemirror]").forEach(elm => {
|
||||||
|
const cm = CodeMirror.fromTextArea(elm, {
|
||||||
|
lineNumbers: true,
|
||||||
|
indentUnit: 3,
|
||||||
|
tabSize: 3,
|
||||||
|
})
|
||||||
|
|
||||||
|
cm.on("change", () => cm.save())
|
||||||
|
})
|
||||||
|
</script>
|
||||||
</body>
|
</body>
|
||||||
|
|
||||||
</html>
|
</html>
|
||||||
|
@ -6,8 +6,8 @@
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<meta http-equiv="X-UA-Compatible" content="ie=edge">
|
<meta http-equiv="X-UA-Compatible" content="ie=edge">
|
||||||
<title>{{title}}</title>
|
<title>{{title}}</title>
|
||||||
<link rel="stylesheet" href="https://unpkg.com/@hibas123/theme/out/base.css">
|
<link rel="stylesheet" href="https://unpkg.com/@hibas123/theme@1/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/light.css">
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
table {
|
table {
|
||||||
@ -37,18 +37,18 @@
|
|||||||
<div class="margin" style="margin-top: 4rem;">
|
<div class="margin" style="margin-top: 4rem;">
|
||||||
<h1>{{title}}</h1>
|
<h1>{{title}}</h1>
|
||||||
{{#if empty}}
|
{{#if empty}}
|
||||||
<h3>No Data available!</h3>
|
<h3>No Data available!</h3>
|
||||||
{{else}}
|
{{else}}
|
||||||
|
|
||||||
<table style="overflow-x: auto">
|
<table style="overflow-x: auto">
|
||||||
{{#each table as |row|}}
|
{{#each table as |row|}}
|
||||||
<tr>
|
<tr>
|
||||||
{{#each row as |col|}}
|
{{#each row as |col|}}
|
||||||
<td>{{col}}</td>
|
<td>{{col}}</td>
|
||||||
{{/each}}
|
|
||||||
</tr>
|
|
||||||
{{/each}}
|
{{/each}}
|
||||||
</table>
|
</tr>
|
||||||
|
{{/each}}
|
||||||
|
</table>
|
||||||
{{/if}}
|
{{/if}}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
Reference in New Issue
Block a user