Compare commits
5 Commits
v2.0.0-bet
...
v2.0.0-bet
Author | SHA1 | Date | |
---|---|---|---|
68295c148d | |||
2a62c3d3ac | |||
1434036b42 | |||
88b0cb68d8 | |||
904b986e22 |
21
.drone.yml
Normal file
21
.drone.yml
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
kind: pipeline
|
||||||
|
type: docker
|
||||||
|
name: default
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Build with node
|
||||||
|
image: node:12
|
||||||
|
commands:
|
||||||
|
- npm install
|
||||||
|
- npm run build
|
||||||
|
- name: Publish to docker
|
||||||
|
image: plugins/docker
|
||||||
|
settings:
|
||||||
|
username:
|
||||||
|
from_secret: docker_username
|
||||||
|
password:
|
||||||
|
from_secret: docker_password
|
||||||
|
auto_tag: true
|
||||||
|
repo: hibas123.azurecr.io/realtimedb
|
||||||
|
registry: hibas123.azurecr.io
|
||||||
|
debug: true
|
@ -1,3 +1,5 @@
|
|||||||
|
[*]
|
||||||
charset = utf-8
|
charset = utf-8
|
||||||
indent_size = 3
|
indent_size = 3
|
||||||
indent_style = space
|
indent_style = space
|
||||||
|
insert_final_newline = true
|
2444
package-lock.json
generated
2444
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
36
package.json
36
package.json
@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@hibas123/realtimedb",
|
"name": "@hibas123/realtimedb",
|
||||||
"version": "2.0.0-beta.8",
|
"version": "2.0.0-beta.18",
|
||||||
"description": "",
|
"description": "",
|
||||||
"main": "lib/index.js",
|
"main": "lib/index.js",
|
||||||
"private": true,
|
"private": true,
|
||||||
@ -17,31 +17,31 @@
|
|||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/dotenv": "^8.2.0",
|
"@types/dotenv": "^8.2.0",
|
||||||
"@types/jsonwebtoken": "^8.3.5",
|
"@types/jsonwebtoken": "^8.3.8",
|
||||||
"@types/koa": "^2.0.51",
|
"@types/koa": "^2.11.2",
|
||||||
"@types/koa-router": "^7.0.42",
|
"@types/koa-router": "^7.4.0",
|
||||||
"@types/leveldown": "^4.0.1",
|
"@types/leveldown": "^4.0.2",
|
||||||
"@types/levelup": "^3.1.1",
|
"@types/levelup": "^4.3.0",
|
||||||
"@types/nanoid": "^2.1.0",
|
"@types/nanoid": "^2.1.0",
|
||||||
"@types/node": "^12.12.5",
|
"@types/node": "^13.9.3",
|
||||||
"@types/ws": "^6.0.3",
|
"@types/ws": "^7.2.3",
|
||||||
"concurrently": "^5.0.0",
|
"concurrently": "^5.1.0",
|
||||||
"nodemon": "^1.19.4",
|
"nodemon": "^2.0.2",
|
||||||
"typescript": "^3.6.4"
|
"typescript": "^3.8.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@hibas123/nodelogging": "^2.1.1",
|
"@hibas123/nodelogging": "^2.1.5",
|
||||||
"@hibas123/utils": "^2.1.1",
|
"@hibas123/utils": "^2.2.3",
|
||||||
"dotenv": "^8.2.0",
|
"dotenv": "^8.2.0",
|
||||||
"handlebars": "^4.5.1",
|
"handlebars": "^4.7.3",
|
||||||
"jsonwebtoken": "^8.5.1",
|
"jsonwebtoken": "^8.5.1",
|
||||||
"koa": "^2.11.0",
|
"koa": "^2.11.0",
|
||||||
"koa-body": "^4.1.1",
|
"koa-body": "^4.1.1",
|
||||||
"koa-router": "^7.4.0",
|
"koa-router": "^8.0.8",
|
||||||
"leveldown": "^5.4.1",
|
"leveldown": "^5.5.1",
|
||||||
"levelup": "^4.3.2",
|
"levelup": "^4.3.2",
|
||||||
"nanoid": "^2.1.6",
|
"nanoid": "^2.1.11",
|
||||||
"what-the-pack": "^2.0.3",
|
"what-the-pack": "^2.0.3",
|
||||||
"ws": "^7.2.0"
|
"ws": "^7.2.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,8 +1,8 @@
|
|||||||
import Logging from "@hibas123/nodelogging";
|
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, IQuery, ITypedQuery } from "./database/database";
|
import { DatabaseManager } from "./database/database";
|
||||||
import { CollectionQuery, DocumentQuery } 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 = require("nanoid");
|
||||||
@ -61,14 +61,22 @@ export class ConnectionManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const answer = (id: string, data: any, error: boolean = false) => {
|
const answer = (id: string, data: any, error: boolean = false) => {
|
||||||
|
if (error)
|
||||||
|
Logging.error(error as any);
|
||||||
socket.send(JSON.stringify({ ns: "message", data: { id, error, data } }));
|
socket.send(JSON.stringify({ ns: "message", data: { id, error, data } }));
|
||||||
}
|
}
|
||||||
|
|
||||||
const handler = new Map<string, ((data: any) => void)>();
|
const handler = new Map<string, ((data: any) => void)>();
|
||||||
|
|
||||||
handler.set("v2", async ({ id, query }: { id: string, query: IQuery }) => db.run(query, session)
|
handler.set("v2", async ({ id, query }) => db.run(Array.isArray(query) ? query : [query], session)
|
||||||
.then(res => answer(id, res))
|
.then(res => answer(id, res))
|
||||||
.catch(err => answer(id, undefined, err)));
|
.catch(err => answer(id, undefined, err))
|
||||||
|
);
|
||||||
|
|
||||||
|
// handler.set("bulk", async ({ id, query }) => db.run(query, session)
|
||||||
|
// .then(res => answer(id, res))
|
||||||
|
// .catch(err => answer(id, undefined, err))
|
||||||
|
// );
|
||||||
|
|
||||||
|
|
||||||
const SnapshotMap = new Map<string, string>();
|
const SnapshotMap = new Map<string, string>();
|
||||||
@ -106,10 +114,8 @@ export class ConnectionManager {
|
|||||||
|
|
||||||
socket.on("close", () => {
|
socket.on("close", () => {
|
||||||
Logging.log(`${session.id} has disconnected!`);
|
Logging.log(`${session.id} has disconnected!`);
|
||||||
session.queries.forEach((query: DocumentQuery | CollectionQuery) => {
|
session.subscriptions.forEach(unsubscribe => unsubscribe());
|
||||||
query.unsubscribe();
|
session.subscriptions.clear();
|
||||||
})
|
|
||||||
session.queries.clear();
|
|
||||||
socket.removeAllListeners();
|
socket.removeAllListeners();
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -1,29 +1,18 @@
|
|||||||
import { Rules } from "./rules";
|
import { Rules } from "./rules";
|
||||||
import Settings from "../settings";
|
import Settings from "../settings";
|
||||||
import getLevelDB, { LevelDB, deleteLevelDB } from "../storage";
|
import getLevelDB, { LevelDB, deleteLevelDB, resNull } from "../storage";
|
||||||
import DocumentLock from "./lock";
|
import DocumentLock from "./lock";
|
||||||
import { DocumentQuery, CollectionQuery, Query, QueryError } 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");
|
import nanoid = require("nanoid/generate");
|
||||||
|
import { Observable } from "@hibas123/utils";
|
||||||
|
|
||||||
type IWriteQueries = "set" | "update" | "delete" | "add";
|
const ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
||||||
type ICollectionQueries = "get" | "add" | "keys" | "delete-collection" | "list";
|
|
||||||
type IDocumentQueries = "get" | "set" | "update" | "delete";
|
|
||||||
|
|
||||||
export interface ITypedQuery<T> {
|
|
||||||
path: string[];
|
|
||||||
type: T;
|
|
||||||
data?: any;
|
|
||||||
options?: any;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ITransaction {
|
|
||||||
queries: ITypedQuery<IWriteQueries>[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export type IQuery = ITypedQuery<ICollectionQueries | IDocumentQueries>;
|
|
||||||
|
|
||||||
|
// interface ITransaction {
|
||||||
|
// queries: ITypedQuery<IWriteQueries>[];
|
||||||
|
// }
|
||||||
|
|
||||||
export class DatabaseManager {
|
export class DatabaseManager {
|
||||||
static databases = new Map<string, Database>();
|
static databases = new Map<string, Database>();
|
||||||
@ -66,12 +55,17 @@ export type ChangeTypes = "added" | "modified" | "deleted";
|
|||||||
export type Change = {
|
export type Change = {
|
||||||
data: any;
|
data: any;
|
||||||
document: string;
|
document: string;
|
||||||
|
collection: string;
|
||||||
type: ChangeTypes;
|
type: ChangeTypes;
|
||||||
sender: string;
|
sender: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export class Database {
|
export class Database {
|
||||||
|
public static getKey(collectionid: string, documentid?: string) {
|
||||||
|
return `${collectionid || ""}/${documentid || ""}`;
|
||||||
|
}
|
||||||
|
|
||||||
private level = getLevelDB(this.name);
|
private level = getLevelDB(this.name);
|
||||||
|
|
||||||
get data() {
|
get data() {
|
||||||
@ -84,10 +78,15 @@ export class Database {
|
|||||||
|
|
||||||
|
|
||||||
public rules: Rules;
|
public rules: Rules;
|
||||||
public locks = new DocumentLock()
|
private locks = new DocumentLock()
|
||||||
public collectionLocks = new DocumentLock()
|
public collectionLocks = new DocumentLock()
|
||||||
|
|
||||||
public changes = new Map<string, Set<(change: Change) => void>>();
|
public changeListener = new Map<string, Set<(change: Change[]) => void>>();
|
||||||
|
public collectionChangeListener = new Observable<{
|
||||||
|
key: string;
|
||||||
|
id: string;
|
||||||
|
type: "create" | "delete"
|
||||||
|
}>();
|
||||||
|
|
||||||
toJSON() {
|
toJSON() {
|
||||||
return {
|
return {
|
||||||
@ -124,14 +123,71 @@ export class Database {
|
|||||||
this.publickey = key;
|
this.publickey = key;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async resolve(path: string[], create = false): Promise<{ collection: string, document: string, collectionKey: string }> {
|
||||||
|
path = [...path]; // Create modifiable copy
|
||||||
|
let collectionID: string = undefined;
|
||||||
|
let documentKey = path.length % 2 === 0 ? path.pop() : undefined;
|
||||||
|
let key = path.join("/");
|
||||||
|
|
||||||
getQuery(path: string[], session: Session, type: "document" | "collection" | "any") {
|
const lock = await this.collectionLocks.lock(key);
|
||||||
if (type === "document")
|
|
||||||
return new DocumentQuery(this, path, session);
|
try {
|
||||||
else if (type === "collection")
|
collectionID = await this.collections.get(key).then(r => r.toString()).catch(resNull);
|
||||||
return new CollectionQuery(this, path, session);
|
if (!collectionID && create) {
|
||||||
else
|
collectionID = nanoid(ALPHABET, 32);
|
||||||
return new Query(this, path, session);
|
await this.collections.put(key, collectionID);
|
||||||
|
setImmediate(() => {
|
||||||
|
this.collectionChangeListener.send({
|
||||||
|
id: collectionID,
|
||||||
|
key,
|
||||||
|
type: "create"
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
lock();
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
collection: collectionID,
|
||||||
|
document: documentKey,
|
||||||
|
collectionKey: key
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private sendChanges(changes: Change[]) {
|
||||||
|
let col = new Map<string, Map<string, Change[]>>();
|
||||||
|
changes.forEach(change => {
|
||||||
|
let e = col.get(change.collection);
|
||||||
|
if (!e) {
|
||||||
|
e = new Map()
|
||||||
|
col.set(change.collection, e);
|
||||||
|
}
|
||||||
|
|
||||||
|
let d = e.get(change.document);
|
||||||
|
if (!d) {
|
||||||
|
d = [];
|
||||||
|
e.set(change.document, d);
|
||||||
|
}
|
||||||
|
|
||||||
|
d.push(change);
|
||||||
|
})
|
||||||
|
|
||||||
|
setImmediate(() => {
|
||||||
|
for (let [collection, documents] of col.entries()) {
|
||||||
|
let collectionChanges = [];
|
||||||
|
for (let [document, documentChanges] of documents.entries()) {
|
||||||
|
let s = this.changeListener.get(Database.getKey(collection, document));
|
||||||
|
if (s)
|
||||||
|
s.forEach(e => setImmediate(() => e(documentChanges)));
|
||||||
|
|
||||||
|
collectionChanges.push(...documentChanges);
|
||||||
|
}
|
||||||
|
let s = this.changeListener.get(Database.getKey(collection))
|
||||||
|
if (s)
|
||||||
|
s.forEach(e => setImmediate(() => e(collectionChanges)))
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
private validate(query: ITypedQuery<any>) {
|
private validate(query: ITypedQuery<any>) {
|
||||||
@ -146,80 +202,121 @@ export class Database {
|
|||||||
throw inv;
|
throw inv;
|
||||||
}
|
}
|
||||||
|
|
||||||
async run(query: IQuery, session: Session) {
|
async run(queries: IQuery[], session: Session) {
|
||||||
this.validate(query);
|
let resolve: { path: string[], create: boolean, resolved?: [string, string, string] }[] = [];
|
||||||
const isCollection = query.path.length % 2 === 1;
|
|
||||||
if (isCollection) {
|
const addToResolve = (path: string[], create?: boolean) => {
|
||||||
const q = new CollectionQuery(this, query.path, session);
|
let entry = resolve.find(e => { //TODO: Find may be slow...
|
||||||
let type = query.type as ICollectionQueries;
|
if (e.path.length !== path.length)
|
||||||
switch (type) {
|
return false;
|
||||||
case "add":
|
for (let i = 0; i < e.path.length; i++) {
|
||||||
return q.add(query.data);
|
if (e.path[i] !== path[i])
|
||||||
case "get":
|
return false;
|
||||||
const limit = (query.options || {}).limit;
|
|
||||||
if (limit)
|
|
||||||
q.limit = limit;
|
|
||||||
const where = (query.options || {}).where;
|
|
||||||
if (where)
|
|
||||||
q.where = where;
|
|
||||||
return q.get();
|
|
||||||
case "keys":
|
|
||||||
return q.keys();
|
|
||||||
case "list":
|
|
||||||
return q.collections();
|
|
||||||
case "delete-collection":
|
|
||||||
return q.deleteCollection();
|
|
||||||
default:
|
|
||||||
return Promise.reject(new Error("Invalid query!"));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
const q = new DocumentQuery(this, query.path, session);
|
|
||||||
let type = query.type as IDocumentQueries;
|
|
||||||
switch (type) {
|
|
||||||
case "get":
|
|
||||||
return q.get();
|
|
||||||
case "set":
|
|
||||||
return q.set(query.data, query.options || {});
|
|
||||||
case "update":
|
|
||||||
return q.update(query.data);
|
|
||||||
case "delete":
|
|
||||||
return q.delete();
|
|
||||||
default:
|
|
||||||
return Promise.reject(new Error("Invalid query!"));
|
|
||||||
}
|
}
|
||||||
|
return true;
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!entry) {
|
||||||
|
entry = {
|
||||||
|
path,
|
||||||
|
create
|
||||||
}
|
}
|
||||||
|
resolve.push(entry);
|
||||||
}
|
}
|
||||||
|
|
||||||
async snapshot(query: ITypedQuery<"snapshot">, session: Session, onchange: (change: any) => void) {
|
entry.create = entry.create || create;
|
||||||
this.validate(query);
|
|
||||||
|
|
||||||
const isCollection = query.path.length % 2 === 1;
|
return entry;
|
||||||
let q: DocumentQuery | CollectionQuery;
|
|
||||||
if (isCollection) {
|
|
||||||
q = new CollectionQuery(this, query.path, session);
|
|
||||||
const limit = (query.options || {}).limit;
|
|
||||||
if (limit)
|
|
||||||
q.limit = limit;
|
|
||||||
const where = (query.options || {}).where;
|
|
||||||
if (where)
|
|
||||||
q.where = where;
|
|
||||||
} else {
|
|
||||||
q = new DocumentQuery(this, query.path, session);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const id = nanoid(16);
|
const isBatch = queries.length > 1;
|
||||||
session.queries.set(id, q);
|
let parsed = queries.map(rawQuery => {
|
||||||
|
this.validate(rawQuery);
|
||||||
|
const isCollection = rawQuery.path.length % 2 === 1;
|
||||||
|
|
||||||
|
let query = isCollection
|
||||||
|
? new CollectionQuery(this, session, rawQuery)
|
||||||
|
: new DocumentQuery(this, session, rawQuery);
|
||||||
|
|
||||||
|
if (isBatch && !query.batchCompatible)
|
||||||
|
throw new Error("There are queries that are not batch compatible!");
|
||||||
|
|
||||||
|
let path = addToResolve(rawQuery.path, query.createCollection);
|
||||||
|
if (query.additionalLock)
|
||||||
|
addToResolve(query.additionalLock);
|
||||||
|
|
||||||
|
return {
|
||||||
|
path,
|
||||||
|
query
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
resolve = resolve.sort((a, b) => a.path.length - b.path.length);
|
||||||
|
|
||||||
|
let locks: (() => void)[] = [];
|
||||||
|
for (let e of resolve) {
|
||||||
|
let { collection, document, collectionKey } = await this.resolve(e.path, e.create);
|
||||||
|
e.resolved = [collection, document, collectionKey];
|
||||||
|
|
||||||
|
locks.push(
|
||||||
|
await this.locks.lock(collection, document)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let result = [];
|
||||||
|
try {
|
||||||
|
let batch = this.data.batch();
|
||||||
|
let changes: Change[] = [];
|
||||||
|
for (let e of parsed) {
|
||||||
|
result.push(
|
||||||
|
await e.query.run(e.path.resolved[0], e.path.resolved[1], batch, e.path.resolved[2])
|
||||||
|
);
|
||||||
|
changes.push(...e.query.changes);
|
||||||
|
}
|
||||||
|
if (batch.length > 0)
|
||||||
|
await batch.write();
|
||||||
|
|
||||||
|
this.sendChanges(changes);
|
||||||
|
} finally {
|
||||||
|
locks.forEach(lock => lock());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isBatch)
|
||||||
|
return result;
|
||||||
|
else
|
||||||
|
return result[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
async snapshot(rawQuery: ITypedQuery<"snapshot">, session: Session, onchange: (change: any) => void) {
|
||||||
|
Logging.debug("Snaphot request:", rawQuery.path);
|
||||||
|
this.validate(rawQuery);
|
||||||
|
|
||||||
|
if (rawQuery.type !== "snapshot")
|
||||||
|
throw new Error("Invalid query type!");
|
||||||
|
|
||||||
|
const isCollection = rawQuery.path.length % 2 === 1;
|
||||||
|
let query = isCollection
|
||||||
|
? new CollectionQuery(this, session, rawQuery, true)
|
||||||
|
: new DocumentQuery(this, session, rawQuery, true);
|
||||||
|
|
||||||
|
const {
|
||||||
|
unsubscribe,
|
||||||
|
value
|
||||||
|
} = await query.snapshot(onchange);
|
||||||
|
|
||||||
|
const id = nanoid(ALPHABET, 16);
|
||||||
|
session.subscriptions.set(id, unsubscribe);
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
snaphot: await q.snapshot(onchange)
|
snaphot: value
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async unsubscribe(id: string, session: Session) {
|
async unsubscribe(id: string, session: Session) {
|
||||||
let query: CollectionQuery | DocumentQuery = session.queries.get(id) as any;
|
let query = session.subscriptions.get(id);
|
||||||
if (query) {
|
if (query) {
|
||||||
query.unsubscribe();
|
query();
|
||||||
session.queries.delete(id);
|
session.subscriptions.delete(id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -8,6 +8,7 @@ export default class DocumentLock {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async lock(collection: string = "", document: string = "") {
|
async lock(collection: string = "", document: string = "") {
|
||||||
|
//TODO: Check collection locks
|
||||||
let key = collection + "/" + document;
|
let key = collection + "/" + document;
|
||||||
let l = this.locks.get(key);
|
let l = this.locks.get(key);
|
||||||
if (l)
|
if (l)
|
||||||
|
@ -4,87 +4,237 @@ import nanoid = require("nanoid/generate");
|
|||||||
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";
|
||||||
|
|
||||||
|
export type IWriteQueries = "set" | "update" | "delete" | "add";
|
||||||
|
export type ICollectionQueries =
|
||||||
|
| "get"
|
||||||
|
| "add"
|
||||||
|
| "keys"
|
||||||
|
| "delete-collection"
|
||||||
|
| "list";
|
||||||
|
export type IDocumentQueries = "get" | "set" | "update" | "delete";
|
||||||
|
|
||||||
|
export interface ITypedQuery<T> {
|
||||||
|
path: string[];
|
||||||
|
type: T;
|
||||||
|
data?: any;
|
||||||
|
options?: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type IQuery = ITypedQuery<
|
||||||
|
ICollectionQueries | IDocumentQueries | "snapshot"
|
||||||
|
>;
|
||||||
|
|
||||||
export const MP = MSGPack.initialize(2 ** 20);
|
export const MP = MSGPack.initialize(2 ** 20);
|
||||||
|
|
||||||
const ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
const ALPHABET =
|
||||||
|
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
||||||
|
|
||||||
const { encode, decode } = MP;
|
const { encode, decode } = MP;
|
||||||
|
|
||||||
export class Query {
|
type Runner = (
|
||||||
|
collection: string,
|
||||||
|
document: string,
|
||||||
|
batch: LevelUpChain,
|
||||||
|
collectionKey: string
|
||||||
|
) => any;
|
||||||
|
|
||||||
|
interface IPreparedQuery {
|
||||||
|
createCollection: boolean;
|
||||||
|
needDocument: boolean;
|
||||||
|
batchCompatible: boolean;
|
||||||
|
runner: Runner;
|
||||||
|
permission: "write" | "read";
|
||||||
|
additionalLock?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface DocRes {
|
||||||
|
id: string;
|
||||||
|
data: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export abstract class Query {
|
||||||
/**
|
/**
|
||||||
* Returns true if the path only contains valid characters and false if it doesn't
|
* Returns true if the path only contains valid characters and false if it doesn't
|
||||||
* @param path Path to be checked
|
* @param path Path to be checked
|
||||||
*/
|
*/
|
||||||
private validatePath(path: string[]) {
|
private validatePath(path: string[]) {
|
||||||
return path.every(e => (e.match(/[^a-zA-Z0-9_\-\<\>]/g) || []).length === 0);
|
return path.every(
|
||||||
|
e => (e.match(/[^a-zA-Z0-9_\-\<\>]/g) || []).length === 0
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
constructor(protected database: Database, protected path: string[], protected session: Session) {
|
public changes: Change[] = [];
|
||||||
if (path.length > 10) {
|
|
||||||
throw new QueryError("Path is to long. Path is only allowed to be 10 Layers deep!");
|
public readonly createCollection: boolean;
|
||||||
|
public readonly needDocument: boolean;
|
||||||
|
public readonly batchCompatible: boolean;
|
||||||
|
public readonly additionalLock?: string[];
|
||||||
|
public readonly permission: string;
|
||||||
|
private readonly _runner: Runner;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
protected database: Database,
|
||||||
|
protected session: Session,
|
||||||
|
protected query: IQuery,
|
||||||
|
snapshot = false
|
||||||
|
) {
|
||||||
|
if (query.path.length > 10) {
|
||||||
|
throw new QueryError(
|
||||||
|
"Path is to long. Path is only allowed to be 10 Layers deep!"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (!this.validatePath(path)) {
|
if (!this.validatePath(query.path)) {
|
||||||
throw new QueryError("Path can only contain a-z A-Z 0-9 '-' '-' '<' and '>' ");
|
throw new QueryError(
|
||||||
|
"Path can only contain a-z A-Z 0-9 '-' '-' '<' and '>' "
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!snapshot) {
|
||||||
|
let data = this.prepare(query);
|
||||||
|
this.createCollection = data.createCollection;
|
||||||
|
this.needDocument = data.needDocument;
|
||||||
|
this.batchCompatible = data.batchCompatible;
|
||||||
|
this.additionalLock = data.additionalLock;
|
||||||
|
this._runner = data.runner;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected abstract prepare(query: IQuery): IPreparedQuery;
|
||||||
protected async resolve(path: string[], create = false): Promise<{ collection: string, document: string, collectionKey: string }> {
|
|
||||||
path = [...path]; // Create modifiable copy
|
|
||||||
let collectionID: string = undefined;
|
|
||||||
let documentKey = path.length % 2 === 0 ? path.pop() : undefined;
|
|
||||||
let key = path.join("/");
|
|
||||||
|
|
||||||
const lock = await this.database.collectionLocks.lock(key);
|
|
||||||
|
|
||||||
try {
|
|
||||||
collectionID = await this.database.collections.get(key).then(r => r.toString()).catch(resNull);
|
|
||||||
if (!collectionID && create) {
|
|
||||||
collectionID = nanoid(ALPHABET, 32);
|
|
||||||
await this.database.collections.put(key, collectionID);
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
lock();
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
collection: collectionID,
|
|
||||||
document: documentKey,
|
|
||||||
collectionKey: key
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
protected getKey(collection: string, document?: string) {
|
|
||||||
return `${collection || ""}/${document || ""}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected getDoc(collection: string, document: string) {
|
protected getDoc(collection: string, document: string) {
|
||||||
return this.database.data
|
return this.database.data
|
||||||
.get(this.getKey(collection, document), { asBuffer: true })
|
.get(Database.getKey(collection, document), { asBuffer: true })
|
||||||
.then(res => decode<any>(res as Buffer)).catch(resNull);
|
.then(res => decode<any>(res as Buffer))
|
||||||
|
.catch(resNull);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected sendChange(collection: string, document: string, type: ChangeTypes, data: any) {
|
protected sendChange(
|
||||||
|
collection: string,
|
||||||
|
document: string,
|
||||||
|
type: ChangeTypes,
|
||||||
|
data: any
|
||||||
|
) {
|
||||||
let change: Change = {
|
let change: Change = {
|
||||||
type,
|
type,
|
||||||
document,
|
document,
|
||||||
|
collection,
|
||||||
data,
|
data,
|
||||||
sender: this.session.id
|
sender: this.session.id
|
||||||
|
};
|
||||||
|
|
||||||
|
this.changes.push(change);
|
||||||
}
|
}
|
||||||
|
|
||||||
let s = this.database.changes.get(this.getKey(collection, document))
|
protected static getConstructorParams(
|
||||||
|
query: Query
|
||||||
if (s)
|
): [Database, Session, IQuery] {
|
||||||
s.forEach(e => setImmediate(() => e(change)))
|
return [query.database, query.session, query.query];
|
||||||
s = this.database.changes.get(this.getKey(collection))
|
|
||||||
if (s)
|
|
||||||
s.forEach(e => setImmediate(() => e(change)))
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected static getConstructorParams(query: Query): [Database, string[], Session] {
|
protected abstract checkChange(change: Change): boolean;
|
||||||
return [query.database, query.path, query.session];
|
protected abstract firstSend(
|
||||||
|
collection: string,
|
||||||
|
document: string
|
||||||
|
): Promise<any>;
|
||||||
|
|
||||||
|
public run(
|
||||||
|
collection: string,
|
||||||
|
document: string,
|
||||||
|
batch: LevelUpChain,
|
||||||
|
collectionKey: string
|
||||||
|
) {
|
||||||
|
let perm = this.database.rules.hasPermission(
|
||||||
|
this.query.path,
|
||||||
|
this.session
|
||||||
|
);
|
||||||
|
if (this.permission === "read" && !perm.read) {
|
||||||
|
throw new QueryError("No permission!");
|
||||||
|
} else if (this.permission === "write" && !perm.write) {
|
||||||
|
throw new QueryError("No permission!");
|
||||||
|
}
|
||||||
|
return this._runner.call(
|
||||||
|
this,
|
||||||
|
collection,
|
||||||
|
document,
|
||||||
|
batch,
|
||||||
|
collectionKey
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async snapshot(
|
||||||
|
onChange: (change: (DocRes & { type: ChangeTypes })[]) => void
|
||||||
|
) {
|
||||||
|
let perm = this.database.rules.hasPermission(
|
||||||
|
this.query.path,
|
||||||
|
this.session
|
||||||
|
);
|
||||||
|
if (this.permission === "read" && !perm.read) {
|
||||||
|
throw new QueryError("No permission!");
|
||||||
|
}
|
||||||
|
|
||||||
|
const receivedChanges = (changes: Change[]) => {
|
||||||
|
let res = changes
|
||||||
|
.filter(change => this.checkChange(change))
|
||||||
|
.map(change => {
|
||||||
|
return {
|
||||||
|
id: change.document,
|
||||||
|
data: change.data,
|
||||||
|
type: change.type
|
||||||
|
};
|
||||||
|
});
|
||||||
|
if (res.length > 0) onChange(res);
|
||||||
|
};
|
||||||
|
|
||||||
|
const unsub = this.database.collectionChangeListener.subscribe(change => {
|
||||||
|
if (change.key === collectionKey) {
|
||||||
|
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(
|
||||||
|
this.query.path
|
||||||
|
);
|
||||||
|
let oldKey: string = undefined;
|
||||||
|
|
||||||
|
const removeSubscriber = () => {
|
||||||
|
if (!oldKey) return;
|
||||||
|
let s = this.database.changeListener.get(oldKey);
|
||||||
|
if (s) {
|
||||||
|
s.delete(receivedChanges);
|
||||||
|
if (s.size <= 0) this.database.changeListener.delete(oldKey);
|
||||||
|
}
|
||||||
|
oldKey = undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
const addSubscriber = (collection: string) => {
|
||||||
|
let key = Database.getKey(collection, document);
|
||||||
|
if (oldKey !== key) {
|
||||||
|
if (oldKey !== undefined) removeSubscriber();
|
||||||
|
|
||||||
|
let s = this.database.changeListener.get(key);
|
||||||
|
if (!s) {
|
||||||
|
s = new Set();
|
||||||
|
this.database.changeListener.set(key, s);
|
||||||
|
}
|
||||||
|
|
||||||
|
s.add(receivedChanges);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (collection) {
|
||||||
|
addSubscriber(collection);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
unsubscribe: () => {
|
||||||
|
unsub();
|
||||||
|
removeSubscriber();
|
||||||
|
},
|
||||||
|
value: await this.firstSend(collection, document)
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -92,62 +242,79 @@ interface UpdateData {
|
|||||||
[path: string]: {
|
[path: string]: {
|
||||||
type: "value" | "timestamp" | "increment" | "push";
|
type: "value" | "timestamp" | "increment" | "push";
|
||||||
value: any;
|
value: any;
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
export class DocumentQuery extends Query {
|
export class DocumentQuery extends Query {
|
||||||
constructor(database: Database, path: string[], session: Session) {
|
prepare(query: IQuery): IPreparedQuery {
|
||||||
super(database, path, session);
|
let type = query.type as IDocumentQueries;
|
||||||
this.onChange = this.onChange.bind(this);
|
switch (type) {
|
||||||
|
case "get":
|
||||||
|
return {
|
||||||
|
batchCompatible: false,
|
||||||
|
createCollection: false,
|
||||||
|
needDocument: false,
|
||||||
|
permission: "read",
|
||||||
|
runner: this.get
|
||||||
|
};
|
||||||
|
case "set":
|
||||||
|
return {
|
||||||
|
batchCompatible: true,
|
||||||
|
createCollection: true,
|
||||||
|
needDocument: true,
|
||||||
|
permission: "write",
|
||||||
|
runner: this.set
|
||||||
|
};
|
||||||
|
case "update":
|
||||||
|
return {
|
||||||
|
batchCompatible: true,
|
||||||
|
createCollection: true,
|
||||||
|
needDocument: true,
|
||||||
|
permission: "write",
|
||||||
|
runner: this.update
|
||||||
|
};
|
||||||
|
case "delete":
|
||||||
|
return {
|
||||||
|
batchCompatible: true,
|
||||||
|
createCollection: false,
|
||||||
|
needDocument: true,
|
||||||
|
permission: "write",
|
||||||
|
runner: this.delete
|
||||||
|
};
|
||||||
|
default:
|
||||||
|
throw new Error("Invalid query type: " + type);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async get() {
|
private async get(collection: string, document: string) {
|
||||||
let { collection, document } = await this.resolve(this.path);
|
|
||||||
|
|
||||||
if (!collection || !document) {
|
if (!collection || !document) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.getDoc(collection, document)
|
return this.getDoc(collection, document);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async set(data: any, { merge = false }) {
|
private async set(
|
||||||
if (data === null)
|
collection: string,
|
||||||
return this.delete();
|
document: string,
|
||||||
let { collection, document } = await this.resolve(this.path, true);
|
batch?: LevelUpChain
|
||||||
if (!collection) {
|
) {
|
||||||
throw new QueryError("There must be a collection!")
|
const { data, options } = this.query;
|
||||||
|
if (data === null) return this.delete(collection, document, batch);
|
||||||
|
|
||||||
|
let isNew = !(await this.getDoc(collection, document));
|
||||||
|
batch.put(Database.getKey(collection, document), encode(data));
|
||||||
|
this.sendChange(collection, document, isNew ? "added" : "modified", data);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!document) {
|
private async update(
|
||||||
throw new QueryError("There must be a document key!")
|
collection: string,
|
||||||
}
|
document: string,
|
||||||
|
batch?: LevelUpChain
|
||||||
|
) {
|
||||||
|
const updateData: UpdateData = this.query.data;
|
||||||
|
|
||||||
const lock = await this.database.locks.lock(collection, document);
|
|
||||||
|
|
||||||
let isNew = !(await this.getDoc(collection, document))
|
|
||||||
|
|
||||||
return this.database.data
|
|
||||||
.put(this.getKey(collection, document), encode(data))
|
|
||||||
.then(() => this.sendChange(collection, document, isNew ? "added" : "modified", data))
|
|
||||||
.finally(() => lock())
|
|
||||||
}
|
|
||||||
|
|
||||||
public async update(updateData: UpdateData) {
|
|
||||||
let { collection, document } = await this.resolve(this.path, true);
|
|
||||||
if (!collection) {
|
|
||||||
throw new QueryError("There must be a collection!")
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!document) {
|
|
||||||
throw new QueryError("There must be a document key!")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Logging.debug(updateData);
|
|
||||||
|
|
||||||
const lock = await this.database.locks.lock(collection, document);
|
|
||||||
try {
|
|
||||||
let data = await this.getDoc(collection, document);
|
let data = await this.getDoc(collection, document);
|
||||||
let isNew = false
|
let isNew = false;
|
||||||
if (!data) {
|
if (!data) {
|
||||||
isNew = true;
|
isNew = true;
|
||||||
data = {};
|
data = {};
|
||||||
@ -159,15 +326,12 @@ export class DocumentQuery extends Query {
|
|||||||
let parts = path.split(".");
|
let parts = path.split(".");
|
||||||
while (parts.length > 1) {
|
while (parts.length > 1) {
|
||||||
let seg = parts.shift();
|
let seg = parts.shift();
|
||||||
if (!data[seg])
|
if (!data[seg]) data[seg] = {};
|
||||||
data[seg] = {}
|
|
||||||
d = data[seg];
|
d = data[seg];
|
||||||
}
|
}
|
||||||
|
|
||||||
const last = parts[0];
|
const last = parts[0];
|
||||||
|
|
||||||
// Logging.debug(parts, last, d)
|
|
||||||
|
|
||||||
switch (toUpdate.type) {
|
switch (toUpdate.type) {
|
||||||
case "value":
|
case "value":
|
||||||
d[last] = toUpdate.value;
|
d[last] = toUpdate.value;
|
||||||
@ -198,82 +362,38 @@ export class DocumentQuery extends Query {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
this.database.data
|
if (batch) {
|
||||||
.put(this.getKey(collection, document), encode(data))
|
batch.put(Database.getKey(collection, document), encode(data));
|
||||||
.then(() => this.sendChange(collection, document, isNew ? "added" : "modified", data))
|
} else {
|
||||||
} finally {
|
await this.database.data.put(
|
||||||
lock();
|
Database.getKey(collection, document),
|
||||||
}
|
encode(data)
|
||||||
//TODO: Implement
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async delete() {
|
this.sendChange(collection, document, isNew ? "added" : "modified", data);
|
||||||
let { collection, document } = await this.resolve(this.path);
|
|
||||||
|
|
||||||
if (!collection) {
|
|
||||||
throw new QueryError("There must be a collection!")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!document) {
|
private async delete(
|
||||||
throw new QueryError("There must be a document key!")
|
collection: string,
|
||||||
|
document: string,
|
||||||
|
batch?: LevelUpChain
|
||||||
|
) {
|
||||||
|
if (batch) {
|
||||||
|
batch.del(Database.getKey(collection, document));
|
||||||
|
} else {
|
||||||
|
await this.database.data.del(Database.getKey(collection, document));
|
||||||
}
|
}
|
||||||
|
|
||||||
const lock = await this.database.locks.lock(collection, document);
|
this.sendChange(collection, document, "deleted", null);
|
||||||
|
|
||||||
return await this.database.data
|
|
||||||
.del(`${collection}/${document}`)
|
|
||||||
.then(() => this.sendChange(collection, document, "deleted", null))
|
|
||||||
.finally(() => lock())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
checkChange(change: Change) {
|
||||||
|
return true;
|
||||||
private subscription: {
|
|
||||||
key: string,
|
|
||||||
onChange: (change: DocRes & { type: ChangeTypes }) => void
|
|
||||||
};
|
|
||||||
|
|
||||||
async snapshot(onChange: (change: DocRes & { type: ChangeTypes }) => void) {
|
|
||||||
if (this.subscription)
|
|
||||||
throw new QueryError("This query is already subscribed!");
|
|
||||||
let { collection, document } = await this.resolve(this.path);
|
|
||||||
|
|
||||||
let data = await this.getDoc(collection, document);
|
|
||||||
let key = this.getKey(collection, document);
|
|
||||||
this.subscription = {
|
|
||||||
key,
|
|
||||||
onChange
|
|
||||||
}
|
|
||||||
let s = this.database.changes.get(key);
|
|
||||||
if (!s) {
|
|
||||||
s = new Set();
|
|
||||||
this.database.changes.set(key, s);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
s.add(this.onChange);
|
firstSend(collection: string, document: string) {
|
||||||
|
return this.get(collection, document);
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
onChange(change: Change) {
|
|
||||||
// if(change.sender === this.sender)
|
|
||||||
// return
|
|
||||||
this.subscription.onChange({
|
|
||||||
id: change.document,
|
|
||||||
data: change.data,
|
|
||||||
type: change.type
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
unsubscribe() {
|
|
||||||
if (!this.subscription)
|
|
||||||
return;
|
|
||||||
let s = this.database.changes.get(this.subscription.key);
|
|
||||||
s.delete(this.onChange);
|
|
||||||
if (s.size <= 0)
|
|
||||||
this.database.changes.delete(this.subscription.key);
|
|
||||||
|
|
||||||
this.subscription = undefined;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static fromQuery(query: Query) {
|
public static fromQuery(query: Query) {
|
||||||
@ -283,122 +403,176 @@ export class DocumentQuery extends Query {
|
|||||||
|
|
||||||
type FieldPath = string;
|
type FieldPath = string;
|
||||||
type WhereFilterOp =
|
type WhereFilterOp =
|
||||||
| '<'
|
| "<"
|
||||||
| '<='
|
| "<="
|
||||||
| '=='
|
| "=="
|
||||||
| '>='
|
| ">="
|
||||||
| '>'
|
| ">"
|
||||||
| 'array-contains'
|
| "array-contains"
|
||||||
| 'in'
|
| "in"
|
||||||
| 'array-contains-any';
|
| "array-contains-any";
|
||||||
|
|
||||||
interface IQueryWhereVerbose {
|
interface IQueryWhereVerbose {
|
||||||
fieldPath: FieldPath,
|
fieldPath: FieldPath;
|
||||||
opStr: WhereFilterOp,
|
opStr: WhereFilterOp;
|
||||||
value: any
|
value: any;
|
||||||
}
|
}
|
||||||
|
|
||||||
type IQueryWhereArray = [FieldPath, WhereFilterOp, any];
|
type IQueryWhereArray = [FieldPath, WhereFilterOp, any];
|
||||||
|
|
||||||
type IQueryWhere = IQueryWhereArray | IQueryWhereVerbose;
|
type IQueryWhere = IQueryWhereArray | IQueryWhereVerbose;
|
||||||
|
|
||||||
interface DocRes {
|
|
||||||
id: string;
|
|
||||||
data: any;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class CollectionQuery extends Query {
|
export class CollectionQuery extends Query {
|
||||||
constructor(database: Database, path: string[], session: Session) {
|
private _addId: string;
|
||||||
super(database, path, session);
|
|
||||||
this.onChange = this.onChange.bind(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
prepare(query): IPreparedQuery {
|
||||||
|
switch (query.type as ICollectionQueries) {
|
||||||
|
case "add":
|
||||||
|
this._addId = nanoid(ALPHABET, 32);
|
||||||
|
return {
|
||||||
|
batchCompatible: true,
|
||||||
|
createCollection: true,
|
||||||
|
needDocument: false,
|
||||||
|
runner: this.add,
|
||||||
|
permission: "write",
|
||||||
|
additionalLock: [...query.path, this._addId]
|
||||||
|
};
|
||||||
|
case "get":
|
||||||
|
const limit = (query.options || {}).limit;
|
||||||
|
if (limit) this.limit = limit;
|
||||||
|
const where = (query.options || {}).where;
|
||||||
|
if (where) this.where = where;
|
||||||
|
|
||||||
|
return {
|
||||||
|
batchCompatible: false,
|
||||||
|
createCollection: false,
|
||||||
|
needDocument: false,
|
||||||
|
permission: "read",
|
||||||
|
runner: this.get
|
||||||
|
};
|
||||||
|
case "keys":
|
||||||
|
return {
|
||||||
|
batchCompatible: false,
|
||||||
|
createCollection: false,
|
||||||
|
needDocument: false,
|
||||||
|
permission: "read",
|
||||||
|
runner: this.keys
|
||||||
|
};
|
||||||
|
case "list":
|
||||||
|
return {
|
||||||
|
batchCompatible: false,
|
||||||
|
createCollection: false,
|
||||||
|
needDocument: false,
|
||||||
|
permission: "read",
|
||||||
|
runner: this.keys
|
||||||
|
};
|
||||||
|
case "delete-collection":
|
||||||
|
return {
|
||||||
|
batchCompatible: false,
|
||||||
|
createCollection: false,
|
||||||
|
needDocument: false,
|
||||||
|
permission: "write",
|
||||||
|
runner: this.deleteCollection
|
||||||
|
};
|
||||||
|
// run = () => q.deleteCollection();
|
||||||
|
// break;
|
||||||
|
default:
|
||||||
|
throw new Error("Invalid 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))
|
if (!Array.isArray(value)) throw invalidWhere;
|
||||||
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)
|
if (cond.length !== 3) throw invalidWhere;
|
||||||
throw invalidWhere;
|
|
||||||
return cond;
|
return cond;
|
||||||
} else {
|
} else {
|
||||||
if (cond && typeof cond === "object" && "fieldPath" in cond && "opStr" in cond && "value" in cond) {
|
if (
|
||||||
|
cond &&
|
||||||
|
typeof cond === "object" &&
|
||||||
|
"fieldPath" in cond &&
|
||||||
|
"opStr" in cond &&
|
||||||
|
"value" in cond
|
||||||
|
) {
|
||||||
return [cond.fieldPath, cond.opStr, cond.value];
|
return [cond.fieldPath, cond.opStr, cond.value];
|
||||||
} else {
|
} else {
|
||||||
throw invalidWhere;
|
throw invalidWhere;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public limit: number = -1;
|
public limit: number = -1;
|
||||||
|
|
||||||
public async add(value: any) {
|
public async add(
|
||||||
let id = nanoid(ALPHABET, 32);
|
collection: string,
|
||||||
let q = new DocumentQuery(this.database, [...this.path, id], this.session);
|
document: string,
|
||||||
await q.set(value, {});
|
batch: LevelUpChain,
|
||||||
return id;
|
collectionKey: string
|
||||||
|
) {
|
||||||
|
let q = new DocumentQuery(this.database, this.session, {
|
||||||
|
type: "set",
|
||||||
|
path: this.additionalLock,
|
||||||
|
data: this.query.data,
|
||||||
|
options: this.query.options
|
||||||
|
});
|
||||||
|
await q.run(collection, this._addId, batch, collectionKey);
|
||||||
|
return this._addId;
|
||||||
}
|
}
|
||||||
|
|
||||||
private getStreamOptions(collection: string) {
|
private getStreamOptions(collection: string) {
|
||||||
let gt = Buffer.from(this.getKey(collection) + " ");
|
let gt = Buffer.from(Database.getKey(collection) + " ");
|
||||||
gt[gt.length - 1] = 0;
|
gt[gt.length - 1] = 0;
|
||||||
|
|
||||||
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;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
gt,
|
gt,
|
||||||
lt
|
lt
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
public async keys() {
|
public async keys(collection: string) {
|
||||||
let { collection, document } = await this.resolve(this.path);
|
if (!collection) return [];
|
||||||
if (document)
|
|
||||||
throw new QueryError("Keys only works on collections!");
|
|
||||||
if (!collection)
|
|
||||||
return []
|
|
||||||
|
|
||||||
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({
|
||||||
...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);
|
||||||
if (s.length > 1)
|
if (s.length > 1) keys.push(s[1]);
|
||||||
keys.push(s[1]);
|
|
||||||
});
|
});
|
||||||
stream.on("end", () => yes(keys));
|
stream.on("end", () => yes(keys));
|
||||||
stream.on("error", no);
|
stream.on("error", no);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private getFieldValue(data: any, path: FieldPath) {
|
private _getFieldValue(data: any, path: FieldPath) {
|
||||||
let parts = path.split(".");
|
let parts = path.split(".");
|
||||||
let d = data;
|
let d = data;
|
||||||
while (parts.length > 0) {
|
while (parts.length > 0) {
|
||||||
let seg = parts.shift();
|
let seg = parts.shift();
|
||||||
|
|
||||||
d = data[seg];
|
d = data[seg];
|
||||||
if (d === undefined || d === null)
|
if (d === undefined || d === null) break; // Undefined/Null has no other fields!
|
||||||
break; // Undefined/Null has no other fields!
|
|
||||||
}
|
}
|
||||||
return d;
|
return d;
|
||||||
}
|
}
|
||||||
|
|
||||||
private fitsWhere(data: any): boolean {
|
private _fitsWhere(data: any): boolean {
|
||||||
if (this._where.length > 0) {
|
if (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) {
|
||||||
case "<":
|
case "<":
|
||||||
return val < value;
|
return val < value;
|
||||||
@ -425,24 +599,20 @@ export class CollectionQuery extends Query {
|
|||||||
default:
|
default:
|
||||||
throw new QueryError("Invalid where operation " + opStr);
|
throw new QueryError("Invalid where operation " + opStr);
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
async get() {
|
async get(collection: string) {
|
||||||
let { collection, document } = await this.resolve(this.path);
|
if (!collection) return [];
|
||||||
if (document)
|
|
||||||
throw new QueryError("Keys only works on collections!");
|
|
||||||
if (!collection)
|
|
||||||
return [];
|
|
||||||
|
|
||||||
return new Promise<DocRes[]>((yes, no) => {
|
return new Promise<DocRes[]>((yes, no) => {
|
||||||
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[] = [];
|
||||||
|
|
||||||
@ -450,29 +620,26 @@ export class CollectionQuery extends Query {
|
|||||||
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
|
||||||
Logging.debug("Checked all!")
|
Logging.debug("Checked all!");
|
||||||
yes(values);
|
yes(values);
|
||||||
} else {
|
} else {
|
||||||
let s = key.split("/", 2);
|
let s = key.split("/", 2);
|
||||||
if (s.length <= 1)
|
if (s.length <= 1) return;
|
||||||
return;
|
|
||||||
|
|
||||||
const id = s[1];
|
const id = s[1];
|
||||||
|
|
||||||
let data = decode(value);
|
let data = decode(value);
|
||||||
if (this.fitsWhere(data)) {
|
if (this._fitsWhere(data)) {
|
||||||
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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -480,105 +647,62 @@ export class CollectionQuery extends Query {
|
|||||||
stream.next(onValue);
|
stream.next(onValue);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
stream.next(onValue);
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
private subscription: {
|
|
||||||
key: string,
|
|
||||||
onChange: (change: (DocRes & { type: ChangeTypes })[]) => void
|
|
||||||
};
|
};
|
||||||
|
|
||||||
async snapshot(onChange: (change: (DocRes & { type: ChangeTypes })[]) => void) {
|
stream.next(onValue);
|
||||||
if (this.subscription)
|
});
|
||||||
throw new QueryError("This query is already subscribed!");
|
|
||||||
let { collection, document } = await this.resolve(this.path, true);
|
|
||||||
|
|
||||||
let data = await this.get();
|
|
||||||
|
|
||||||
let key = this.getKey(collection, document);
|
|
||||||
this.subscription = {
|
|
||||||
key,
|
|
||||||
onChange
|
|
||||||
}
|
|
||||||
let s = this.database.changes.get(key);
|
|
||||||
if (!s) {
|
|
||||||
s = new Set();
|
|
||||||
this.database.changes.set(key, s);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
s.add(this.onChange);
|
checkChange(change: Change) {
|
||||||
|
return this._fitsWhere(change.data);
|
||||||
return data;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onChange(change: Change) {
|
firstSend(collection: string) {
|
||||||
// if(change.sender === this.sender)
|
return this.get(collection);
|
||||||
// return
|
|
||||||
|
|
||||||
if (this.fitsWhere(change.data)) {
|
|
||||||
this.subscription.onChange([{
|
|
||||||
id: change.document,
|
|
||||||
data: change.data,
|
|
||||||
type: change.type
|
|
||||||
}])
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
unsubscribe() {
|
|
||||||
if (!this.subscription)
|
|
||||||
return;
|
|
||||||
let s = this.database.changes.get(this.subscription.key);
|
|
||||||
s.delete(this.onChange);
|
|
||||||
if (s.size <= 0)
|
|
||||||
this.database.changes.delete(this.subscription.key);
|
|
||||||
|
|
||||||
this.subscription = undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
public async collections() {
|
public async collections() {
|
||||||
if (!this.session.root)
|
if (!this.session.root) throw new QueryError("No Permission!");
|
||||||
throw new QueryError("No Permission!");
|
|
||||||
|
|
||||||
return new Promise<string[]>((yes, no) => {
|
return new Promise<string[]>((yes, no) => {
|
||||||
let keys = [];
|
let keys = [];
|
||||||
const stream = this.database.data.createKeyStream({ keyAsBuffer: false })
|
const stream = this.database.data.createKeyStream({
|
||||||
|
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));
|
||||||
stream.on("error", no);
|
stream.on("error", no);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public async deleteCollection() {
|
public async deleteCollection(
|
||||||
if (!this.session.root)
|
collection: string,
|
||||||
throw new QueryError("No Permission!");
|
document: string,
|
||||||
|
_b: LevelUpChain,
|
||||||
const { collection, document, collectionKey } = await this.resolve(this.path);
|
collectionKey: string
|
||||||
|
) {
|
||||||
if (document) {
|
if (!this.session.root) throw new QueryError("No Permission!");
|
||||||
throw new QueryError("There can be no document defined on this operation");
|
|
||||||
}
|
|
||||||
|
|
||||||
//TODO: Lock whole collection!
|
//TODO: Lock whole collection!
|
||||||
|
|
||||||
let batch = this.database.data.batch();
|
let batch = this.database.data.batch();
|
||||||
try {
|
try {
|
||||||
if (collection) {
|
if (collection) {
|
||||||
let documents = await this.keys();
|
let documents = await this.keys(collection);
|
||||||
// Logging.debug("To delete:", documents)
|
// Logging.debug("To delete:", documents)
|
||||||
for (let document of documents) {
|
for (let document of documents) {
|
||||||
batch.del(this.getKey(collection, document));
|
batch.del(Database.getKey(collection, document));
|
||||||
}
|
}
|
||||||
await batch.write();
|
await batch.write();
|
||||||
batch = undefined;
|
batch = undefined;
|
||||||
await this.database.collections.del(collectionKey);
|
await this.database.collections.del(collectionKey);
|
||||||
|
this.database.collectionChangeListener.send({
|
||||||
|
id: collection,
|
||||||
|
key: collectionKey,
|
||||||
|
type: "delete"
|
||||||
|
});
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
if (batch)
|
if (batch) batch.clear();
|
||||||
batch.clear();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -2,13 +2,15 @@ import Session from "./session";
|
|||||||
import Logging from "@hibas123/nodelogging";
|
import Logging from "@hibas123/nodelogging";
|
||||||
|
|
||||||
interface IRule<T> {
|
interface IRule<T> {
|
||||||
".write"?: T
|
".write"?: T;
|
||||||
".read"?: T
|
".read"?: T;
|
||||||
}
|
}
|
||||||
|
|
||||||
type IRuleConfig<T> = {
|
type IRuleConfig<T> =
|
||||||
|
| IRule<T>
|
||||||
|
| {
|
||||||
[segment: string]: IRuleConfig<T>;
|
[segment: string]: IRuleConfig<T>;
|
||||||
} | IRule<T>;
|
};
|
||||||
|
|
||||||
type IRuleRaw = IRuleConfig<string>;
|
type IRuleRaw = IRuleConfig<string>;
|
||||||
type IRuleParsed = IRuleConfig<boolean>;
|
type IRuleParsed = IRuleConfig<boolean>;
|
||||||
@ -17,17 +19,16 @@ const resolve = (value: any) => {
|
|||||||
if (value === true) {
|
if (value === true) {
|
||||||
return true;
|
return true;
|
||||||
} else if (typeof value === "string") {
|
} else if (typeof value === "string") {
|
||||||
|
|
||||||
}
|
}
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
};
|
||||||
|
|
||||||
export class Rules {
|
export class Rules {
|
||||||
rules: IRuleParsed;
|
rules: IRuleParsed;
|
||||||
constructor(private config: string) {
|
constructor(private config: string) {
|
||||||
let parsed: IRuleRaw = JSON.parse(config);
|
let parsed: IRuleRaw = JSON.parse(config);
|
||||||
|
|
||||||
const analyze = (raw: IRuleRaw) => {
|
const analyse = (raw: IRuleRaw) => {
|
||||||
let r: IRuleParsed = {};
|
let r: IRuleParsed = {};
|
||||||
|
|
||||||
if (raw[".read"]) {
|
if (raw[".read"]) {
|
||||||
@ -47,18 +48,25 @@ export class Rules {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (let segment in raw) {
|
for (let segment in raw) {
|
||||||
if (segment.startsWith("."))
|
if (segment.startsWith(".")) continue;
|
||||||
continue;
|
|
||||||
|
|
||||||
r[segment] = analyze(raw[segment]);
|
r[segment] = analyse(raw[segment]);
|
||||||
}
|
}
|
||||||
return r;
|
return r;
|
||||||
|
};
|
||||||
|
|
||||||
|
this.rules = analyse(parsed);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.rules = analyze(parsed);
|
hasPermission(
|
||||||
}
|
path: string[],
|
||||||
|
session: Session
|
||||||
hasPermission(path: string[], session: Session): { read: boolean, write: boolean } {
|
): { read: boolean; write: boolean } {
|
||||||
|
if (session.root)
|
||||||
|
return {
|
||||||
|
read: true,
|
||||||
|
write: true
|
||||||
|
};
|
||||||
let read = this.rules[".read"] || false;
|
let read = this.rules[".read"] || false;
|
||||||
let write = this.rules[".write"] || false;
|
let write = this.rules[".write"] || false;
|
||||||
|
|
||||||
@ -77,22 +85,21 @@ export class Rules {
|
|||||||
.find(e => {
|
.find(e => {
|
||||||
switch (e) {
|
switch (e) {
|
||||||
case "$uid":
|
case "$uid":
|
||||||
if (segment === session.uid)
|
if (segment === session.uid) return true;
|
||||||
return true;
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
})
|
});
|
||||||
|
|
||||||
rules = (k ? rules[k] : undefined) || rules[segment] || rules["*"];
|
rules = (k ? rules[k] : undefined) || rules[segment] || rules["*"];
|
||||||
|
|
||||||
if (rules) {
|
if (rules) {
|
||||||
if (rules[".read"]) {
|
if (rules[".read"]) {
|
||||||
read = rules[".read"]
|
read = rules[".read"];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (rules[".write"]) {
|
if (rules[".write"]) {
|
||||||
read = rules[".write"]
|
read = rules[".write"];
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
break;
|
break;
|
||||||
@ -102,7 +109,7 @@ export class Rules {
|
|||||||
return {
|
return {
|
||||||
read: read as boolean,
|
read: read as boolean,
|
||||||
write: write as boolean
|
write: write as boolean
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
toJSON() {
|
toJSON() {
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
import { Query } from "./query";
|
|
||||||
|
|
||||||
export default class Session {
|
export default class Session {
|
||||||
constructor(private _sessionid: string) { }
|
constructor(private _sessionid: string) { }
|
||||||
@ -8,5 +7,5 @@ export default class Session {
|
|||||||
root: boolean = false;
|
root: boolean = false;
|
||||||
uid: string = undefined;
|
uid: string = undefined;
|
||||||
|
|
||||||
queries = new Map<string, Query>();
|
subscriptions = new Map<string, (() => void)>();
|
||||||
}
|
}
|
@ -1,7 +1,11 @@
|
|||||||
import * as Router from "koa-router";
|
import * as Router from "koa-router";
|
||||||
import AdminRoute from "./admin";
|
import AdminRoute from "./admin";
|
||||||
import { DatabaseManager } from "../../database/database";
|
import { DatabaseManager } from "../../database/database";
|
||||||
import { NotFoundError, NoPermissionError, BadRequestError } from "../helper/errors";
|
import {
|
||||||
|
NotFoundError,
|
||||||
|
NoPermissionError,
|
||||||
|
BadRequestError
|
||||||
|
} 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 = require("nanoid");
|
||||||
@ -28,7 +32,7 @@ V1.post("/db/:database/query", async ctx => {
|
|||||||
|
|
||||||
if (db.accesskey) {
|
if (db.accesskey) {
|
||||||
if (!accesskey || accesskey !== db.accesskey) {
|
if (!accesskey || accesskey !== db.accesskey) {
|
||||||
throw new NoPermissionError("");
|
throw new NoPermissionError("Invalid Access Key");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -36,7 +40,6 @@ V1.post("/db/:database/query", async ctx => {
|
|||||||
let res = await verifyJWT(authkey, db.publickey);
|
let res = await verifyJWT(authkey, db.publickey);
|
||||||
if (!res || !res.uid) {
|
if (!res || !res.uid) {
|
||||||
throw new BadRequestError("Invalid JWT");
|
throw new BadRequestError("Invalid JWT");
|
||||||
return;
|
|
||||||
} else {
|
} else {
|
||||||
session.uid = res.uid;
|
session.uid = res.uid;
|
||||||
}
|
}
|
||||||
@ -49,11 +52,11 @@ 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);
|
||||||
}
|
}
|
||||||
throw err;
|
throw err;
|
||||||
})
|
});
|
||||||
})
|
});
|
||||||
export default V1;
|
export default V1;
|
Reference in New Issue
Block a user