Compare commits

..

11 Commits

Author SHA1 Message Date
7bc404ba21 1.0.25 2019-01-31 02:52:18 +01:00
ac2a1559b0 fix(core): update 2019-01-31 02:52:18 +01:00
57b37cb327 1.0.24 2019-01-30 11:01:49 +01:00
8b17e814cc fix(dependencies): update 2019-01-30 11:01:48 +01:00
f4b8cde347 fix(dependencies): update 2019-01-30 10:56:31 +01:00
3189d4d274 1.0.23 2018-05-30 16:34:07 +02:00
c2d134a6ea fix(websocket): switch to all websocket infrastructure 2018-05-30 16:34:06 +02:00
7552dc1e9f 1.0.22 2018-05-28 12:07:26 +02:00
fe91459510 fix(core): update to transparent universe 2018-05-28 12:07:25 +02:00
0e0ffb7634 1.0.21 2018-05-26 13:44:32 +02:00
37bb052774 fix(UniverseMessage / UniverseChannel): better authentication for of messages for channels 2018-05-26 13:44:32 +02:00
19 changed files with 1786 additions and 1197 deletions

View File

@ -3,7 +3,7 @@ image: hosttoday/ht-docker-node:npmci
cache: cache:
paths: paths:
- .yarn/ - .npmci_cache/
key: "$CI_BUILD_STAGE" key: "$CI_BUILD_STAGE"
stages: stages:
@ -26,31 +26,47 @@ mirror:
snyk: snyk:
stage: security stage: security
script: script:
- npmci command yarn global add snyk - npmci npm prepare
- npmci command yarn install --ignore-scripts - npmci command npm install -g snyk
- npmci command npm install --ignore-scripts
- npmci command snyk test - npmci command snyk test
tags: tags:
- docker - docker
- notpriv - notpriv
sast:
stage: security
image: registry.gitlab.com/hosttoday/ht-docker-dbase:npmci
variables:
DOCKER_DRIVER: overlay2
allow_failure: true
services:
- docker:stable-dind
script:
- npmci npm prepare
- npmci npm install
- npmci command npm run build
- export SP_VERSION=$(echo "$CI_SERVER_VERSION" | sed 's/^\([0-9]*\)\.\([0-9]*\).*/\1-\2-stable/')
- docker run
--env SAST_CONFIDENCE_LEVEL="${SAST_CONFIDENCE_LEVEL:-3}"
--volume "$PWD:/code"
--volume /var/run/docker.sock:/var/run/docker.sock
"registry.gitlab.com/gitlab-org/security-products/sast:$SP_VERSION" /app/bin/run /code
artifacts:
reports:
sast: gl-sast-report.json
tags:
- docker
- priv
# ==================== # ====================
# test stage # test stage
# ==================== # ====================
testLEGACY:
stage: test
script:
- npmci node install legacy
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
- notpriv
allow_failure: true
testLTS: testLTS:
stage: test stage: test
script: script:
- npmci npm prepare
- npmci node install lts - npmci node install lts
- npmci npm install - npmci npm install
- npmci npm test - npmci npm test
@ -62,6 +78,7 @@ testLTS:
testSTABLE: testSTABLE:
stage: test stage: test
script: script:
- npmci npm prepare
- npmci node install stable - npmci node install stable
- npmci npm install - npmci npm install
- npmci npm test - npmci npm test
@ -117,8 +134,10 @@ pages:
image: hosttoday/ht-docker-node:npmci image: hosttoday/ht-docker-node:npmci
stage: metadata stage: metadata
script: script:
- npmci command yarn global add npmpage - npmci command npm install -g typedoc typescript
- npmci command npmpage - npmci npm prepare
- npmci npm install
- npmci command typedoc --module "commonjs" --target "ES2016" --out public/ ts/
tags: tags:
- docker - docker
- notpriv - notpriv
@ -128,3 +147,4 @@ pages:
expire_in: 1 week expire_in: 1 week
paths: paths:
- public - public
allow_failure: true

View File

@ -1,4 +1,15 @@
{ {
"gitzone": {
"module": {
"githost": "gitlab.com",
"gitscope": "pushrocks",
"gitrepo": "smartuniverse",
"shortDescription": "messaging service for micro services",
"npmPackagename": "@pushrocks/smartuniverse",
"license": "MIT",
"projectDomain": "push.rocks"
}
},
"npmci": { "npmci": {
"npmGlobalTools": [ "npmGlobalTools": [
"@gitzone/npmts", "@gitzone/npmts",

2362
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{ {
"name": "@pushrocks/smartuniverse", "name": "@pushrocks/smartuniverse",
"version": "1.0.20", "version": "1.0.25",
"private": false, "private": false,
"description": "messaging service for your micro services", "description": "messaging service for your micro services",
"main": "dist/index.js", "main": "dist/index.js",
@ -8,28 +8,31 @@
"author": "Lossless GmbH", "author": "Lossless GmbH",
"license": "MIT", "license": "MIT",
"scripts": { "scripts": {
"test": "(ts-node -O '{\"lib\": [ \"es2015\" ]}' test/test.ts)", "test": "(tstest test/)",
"build": "(npmts)", "build": "(npmts)",
"format": "(gitzone format)" "format": "(gitzone format)"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^9.6.0", "@gitzone/tsbuild": "^2.1.8",
"tapbundle": "^2.0.0", "@gitzone/tstest": "^1.0.18",
"ts-node": "^6.0.3", "@pushrocks/tapbundle": "^3.0.7",
"typescript": "^2.8.3" "@types/node": "^10.12.20",
"tslint": "^5.12.1",
"tslint-config-prettier": "^1.17.0"
},
"peerDependencies": {
"rxjs": "*"
}, },
"dependencies": { "dependencies": {
"@pushrocks/smartcli": "^3.0.1", "@pushrocks/lik": "^3.0.4",
"lik": "^2.0.5", "@pushrocks/smartdelay": "^2.0.2",
"nodehash": "^1.0.4", "@pushrocks/smartexpress": "^3.0.10",
"rxjs": "^5.5.8", "@pushrocks/smartfile": "^6.0.12",
"smartdelay": "^1.0.4", "@pushrocks/smarthash": "^2.0.4",
"smartexpress": "^1.0.21", "@pushrocks/smartpromise": "^2.0.5",
"smartfile": "^4.2.28", "@pushrocks/smartrequest": "^1.1.14",
"smartq": "^1.1.8", "@pushrocks/smartrx": "^2.0.3",
"smartrequest": "^1.0.8", "@pushrocks/smartsocket": "^1.1.27",
"smartrx": "^1.0.5", "@pushrocks/smarttime": "^3.0.5"
"smartsocket": "^1.1.19",
"smarttime": "^2.0.0"
} }
} }

View File

@ -1,33 +1,28 @@
# smartuniverse # @pushrocks/smartuniverse
messaging service for micro services
messaging service for your micro services ## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@pushrocks/smartuniverse)
## Availabililty * [gitlab.com (source)](https://gitlab.com/pushrocks/smartuniverse)
* [github.com (source mirror)](https://github.com/pushrocks/smartuniverse)
[![npm](https://pushrocks.gitlab.io/assets/repo-button-npm.svg)](https://www.npmjs.com/package/@pushrocks/smartuniverse) * [docs (typedoc)](https://pushrocks.gitlab.io/smartuniverse/)
[![git](https://pushrocks.gitlab.io/assets/repo-button-git.svg)](https://GitLab.com/pushrocks/smartuniverse)
[![git](https://pushrocks.gitlab.io/assets/repo-button-mirror.svg)](https://github.com/pushrocks/smartuniverse)
[![docs](https://pushrocks.gitlab.io/assets/repo-button-docs.svg)](https://pushrocks.gitlab.io/smartuniverse/)
## Status for master ## Status for master
[![build status](https://gitlab.com/pushrocks/smartuniverse/badges/master/build.svg)](https://gitlab.com/pushrocks/smartuniverse/commits/master)
[![build status](https://GitLab.com/pushrocks/smartuniverse/badges/master/build.svg)](https://GitLab.com/pushrocks/smartuniverse/commits/master) [![coverage report](https://gitlab.com/pushrocks/smartuniverse/badges/master/coverage.svg)](https://gitlab.com/pushrocks/smartuniverse/commits/master)
[![coverage report](https://GitLab.com/pushrocks/smartuniverse/badges/master/coverage.svg)](https://GitLab.com/pushrocks/smartuniverse/commits/master)
[![npm downloads per month](https://img.shields.io/npm/dm/@pushrocks/smartuniverse.svg)](https://www.npmjs.com/package/@pushrocks/smartuniverse) [![npm downloads per month](https://img.shields.io/npm/dm/@pushrocks/smartuniverse.svg)](https://www.npmjs.com/package/@pushrocks/smartuniverse)
[![bitHound Dependencies](https://www.bithound.io/github/pushrocks/smartuniverse/badges/dependencies.svg)](https://www.bithound.io/github/pushrocks/smartuniverse/master/dependencies/npm)
[![bitHound Code](https://www.bithound.io/github/pushrocks/smartuniverse/badges/code.svg)](https://www.bithound.io/github/pushrocks/smartuniverse)
[![Known Vulnerabilities](https://snyk.io/test/npm/@pushrocks/smartuniverse/badge.svg)](https://snyk.io/test/npm/@pushrocks/smartuniverse) [![Known Vulnerabilities](https://snyk.io/test/npm/@pushrocks/smartuniverse/badge.svg)](https://snyk.io/test/npm/@pushrocks/smartuniverse)
[![TypeScript](https://img.shields.io/badge/TypeScript-2.x-blue.svg)](https://nodejs.org/dist/latest-v6.x/docs/api/) [![TypeScript](https://img.shields.io/badge/TypeScript->=%203.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
[![node](https://img.shields.io/badge/node->=%206.x.x-blue.svg)](https://nodejs.org/dist/latest-v6.x/docs/api/) [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
[![JavaScript Style Guide](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/) [![JavaScript Style Guide](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/)
## Usage ## Usage
Use TypeScript for best in class instellisense. Use TypeScript for best in class instellisense.
For further information read the linked docs at the top of this README. For further information read the linked docs at the top of this readme.
> licensed | **©** [Lossless GmbH](https://lossless.gmbh) > MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
> | By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy.html) | By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy.html)
[![repo-footer](https://pushrocks.gitlab.io/assets/repo-footer.svg)](https://push.rocks) [![repo-footer](https://pushrocks.gitlab.io/assets/repo-footer.svg)](https://maintainedby.lossless.com)

View File

@ -1,12 +1,12 @@
// tslint:disable-next-line:no-implicit-dependencies // tslint:disable-next-line:no-implicit-dependencies
import { expect, tap } from 'tapbundle'; import { expect, tap } from '@pushrocks/tapbundle';
import * as smartuniverse from '../ts/index'; import * as smartuniverse from '../ts/index';
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
let testUniverse: smartuniverse.Universe; let testUniverse: smartuniverse.Universe;
let testUniverseClient: smartuniverse.UniverseClient; let testUniverseClient: smartuniverse.ClientUniverse;
let testMessageObservable: Observable<smartuniverse.UniverseMessage>; let testClientChannel: smartuniverse.ClientUniverseChannel;
tap.test('first test', async () => { tap.test('first test', async () => {
testUniverse = new smartuniverse.Universe({ testUniverse = new smartuniverse.Universe({
@ -20,10 +20,19 @@ tap.test('add a message to the SmartUniverse', async () => {
// testing message handling // testing message handling
tap.test('create smartuniverse client', async () => { tap.test('create smartuniverse client', async () => {
testUniverseClient = new smartuniverse.UniverseClient({ testUniverseClient = new smartuniverse.ClientUniverse({
serverAddress: 'http://localhost:8765' serverAddress: 'http://localhost:8765'
}); });
expect(testUniverseClient).to.be.instanceof(smartuniverse.UniverseClient); expect(testUniverseClient).to.be.instanceof(smartuniverse.ClientUniverse);
});
tap.test('should add a channel to the universe', async () => {
await testUniverse.addChannel('testChannel', 'testPassword');
});
tap.test('should get a observable correctly', async () => {
testClientChannel = await testUniverseClient.getChannel('testChannel');
expect(testClientChannel).to.be.instanceof(smartuniverse.ClientUniverseChannel);
}); });
tap.test('should send a message correctly', async () => { tap.test('should send a message correctly', async () => {
@ -32,10 +41,6 @@ tap.test('should send a message correctly', async () => {
}); });
}); });
tap.test('should get a observable correctly', async () => {
testMessageObservable = testUniverseClient.getMessageObservable();
});
tap.test('should receive a message correctly', async () => {}); tap.test('should receive a message correctly', async () => {});
tap.test('should disconnect the client correctly', async () => { tap.test('should disconnect the client correctly', async () => {

View File

@ -1,3 +1,10 @@
// Client classes
export * from './smartuniverse.classes.clientuniverse';
export * from './smartuniverse.classes.clientuniversechannel';
// Server classes
export * from './smartuniverse.classes.universe'; export * from './smartuniverse.classes.universe';
export * from './smartuniverse.classes.universeclient'; export * from './smartuniverse.classes.universecache';
export * from './smartuniverse.classes.universechannel';
export * from './smartuniverse.classes.universemessage'; export * from './smartuniverse.classes.universemessage';
export * from './smartuniverse.interfaces';

View File

@ -1,14 +1,16 @@
import * as plugins from './smartuniverse.plugins'; import * as plugins from './smartuniverse.plugins';
import { Objectmap } from '@pushrocks/lik';
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
import { Smartsocket, SmartsocketClient } from 'smartsocket'; import { Smartsocket, SmartsocketClient } from '@pushrocks/smartsocket';
import * as url from 'url'; import * as url from 'url';
import { import {
ClientUniverseChannel,
IServerGetMessagesRequestBody, IServerGetMessagesRequestBody,
IServerPutMessageRequestBody IServerPutMessageRequestBody,
} from './smartuniverse.classes.universe'; UniverseMessage
import { UniverseMessage } from './smartuniverse.classes.universemessage'; } from './';
export interface IClientOptions { export interface IClientOptions {
serverAddress: string; serverAddress: string;
@ -18,10 +20,12 @@ export interface IClientOptions {
* this class is for client side only!!! * this class is for client side only!!!
* allows connecting to a universe server * allows connecting to a universe server
*/ */
export class UniverseClient { export class ClientUniverse {
public options; public options;
private socketClient: plugins.smartsocket.SmartsocketClient; public socketClient: plugins.smartsocket.SmartsocketClient;
private observableIntake: plugins.smartrx.ObservableIntake<UniverseMessage>; public observableIntake: plugins.smartrx.ObservableIntake<UniverseMessage>;
public channelCache = new Objectmap<ClientUniverseChannel>();
constructor(optionsArg: IClientOptions) { constructor(optionsArg: IClientOptions) {
this.options = optionsArg; this.options = optionsArg;
@ -33,12 +37,26 @@ export class UniverseClient {
payload: payloadArg payload: payloadArg
}; };
// TODO: User websocket connection if available // TODO: User websocket connection if available
await plugins.smartrequest.post(this.options.serverAddress, { await plugins.smartrequest.postJson(this.options.serverAddress, {
requestBody requestBody
}); });
} }
public getMessageObservable() { public async getChannel(channelName: string): Promise<ClientUniverseChannel> {
await this.checkConnection();
const clientUniverseChannel = await ClientUniverseChannel.createClientUniverseChannel(
this,
channelName
);
this.channelCache.add(clientUniverseChannel);
return clientUniverseChannel;
}
public close() {
this.socketClient.disconnect();
}
private async checkConnection() {
if (!this.socketClient && !this.observableIntake) { if (!this.socketClient && !this.observableIntake) {
const parsedURL = url.parse(this.options.serverAddress); const parsedURL = url.parse(this.options.serverAddress);
this.socketClient = new SmartsocketClient({ this.socketClient = new SmartsocketClient({
@ -51,10 +69,5 @@ export class UniverseClient {
this.observableIntake = new plugins.smartrx.ObservableIntake(); this.observableIntake = new plugins.smartrx.ObservableIntake();
this.socketClient.connect(); this.socketClient.connect();
} }
return this.observableIntake.observable;
}
public close() {
this.socketClient.disconnect();
} }
} }

View File

@ -0,0 +1,34 @@
import * as plugins from './smartuniverse.plugins';
import { ClientUniverse, IUniverseChannel } from './';
export class ClientUniverseChannel implements IUniverseChannel {
// ======
// STATIC
// ======
public static async createClientUniverseChannel(
clientUniverseArg: ClientUniverse,
channelName: string
): Promise<ClientUniverseChannel> {
const clientChannel = new ClientUniverseChannel(clientUniverseArg);
await clientChannel.transmitSubscription();
return clientChannel;
}
// ========
// INSTANCE
// ========
public clientUniverse: ClientUniverse;
constructor(clientUniverseArg: ClientUniverse) {
this.clientUniverse = clientUniverseArg;
}
/**
* tells the universe about this instances interest into a channel
*/
public async transmitSubscription() {
this.clientUniverse.socketClient;
}
}

View File

@ -0,0 +1,15 @@
import * as plugins from './smartuniverse.plugins';
import { IUniverseMessage } from './';
export class ClientUniverseMessage implements IUniverseMessage {
// ======
// STATIC
// ======
createMessage(messageArg: string, payloadArg: any) {}
// ========
// INSTANCE
// ========
constructor(messageArg, payloadArg) {}
}

View File

@ -1,9 +1,7 @@
import * as plugins from './smartuniverse.plugins'; import * as plugins from './smartuniverse.plugins';
import { Handler, Route, Server } from 'smartexpress'; import { Handler, Route, Server } from '@pushrocks/smartexpress';
import { UniverseChannel } from './smartuniverse.classes.universechannel'; import { UniverseCache, UniverseChannel, UniverseMessage } from './';
import { UniverseMessage } from './smartuniverse.classes.universemessage';
import { UniverseStore } from './smartuniverse.classes.universestore';
import * as paths from './smartuniverse.paths'; import * as paths from './smartuniverse.paths';
@ -32,7 +30,7 @@ export interface IServerPutMessageRequestBody {
*/ */
export class Universe { export class Universe {
// subinstances // subinstances
public universeStore: UniverseStore; public universeCache: UniverseCache;
// options // options
private options: ISmartUniverseConstructorOptions; private options: ISmartUniverseConstructorOptions;
@ -54,7 +52,15 @@ export class Universe {
constructor(optionsArg: ISmartUniverseConstructorOptions) { constructor(optionsArg: ISmartUniverseConstructorOptions) {
this.options = optionsArg; this.options = optionsArg;
this.universeStore = new UniverseStore(this.options.messageExpiryInMilliseconds); this.universeCache = new UniverseCache(this.options.messageExpiryInMilliseconds);
}
/**
* adds a channel to the Universe
*/
public async addChannel(nameArg: string, passphraseArg: string) {
const newChannel = new UniverseChannel(this.universeCache, nameArg, passphraseArg);
this.universeCache.channelMap.add(newChannel);
} }
/** /**
@ -63,46 +69,33 @@ export class Universe {
public async initServer(portArg: number | string) { public async initServer(portArg: number | string) {
this.smartexpressServer = new plugins.smartexpress.Server({ this.smartexpressServer = new plugins.smartexpress.Server({
cors: true, cors: true,
defaultAnswer: `smartuniverse server ${this.universeVersion}`, defaultAnswer: async () => {
return `smartuniverse server ${this.universeVersion}`;
},
forceSsl: false, forceSsl: false,
port: portArg port: portArg
}); });
// message handling
// adds messages
const addMessageHandler = new Handler('PUT', request => {
const requestBody: IServerPutMessageRequestBody = request.body;
const message = new UniverseMessage(requestBody.message, requestBody.channel, requestBody.passphrase, requestBody.payload);
this.universeStore.addMessage(message);
console.log(requestBody);
return true;
});
// gets messages
const readMessageHandler = new Handler('GET', request => {
const done = plugins.smartq.defer<UniverseMessage[]>();
const requestBody = request.body;
const messageObservable = this.universeStore.readMessagesYoungerThan(requestBody.since);
messageObservable.toArray().subscribe(universeMessageArrayArg => {
done.resolve(universeMessageArrayArg);
});
return done.promise;
});
// create new Route for messages
const messageRoute = new Route(this.smartexpressServer, 'message');
messageRoute.addHandler(addMessageHandler);
messageRoute.addHandler(readMessageHandler);
const leaderElectionRoute = new Route(this.smartexpressServer, 'leadelection');
// TODO: implement Handlers for leader election
// add websocket upgrade // add websocket upgrade
this.smartsocket = new plugins.smartsocket.Smartsocket({ this.smartsocket = new plugins.smartsocket.Smartsocket({
port: 12345 // fix this within smartsocket port: 12345 // fix this within smartsocket
}); });
this.smartsocket.setExternalServer('express', this.smartexpressServer as any); // should work with express as well const ClientRole = new plugins.smartsocket.SocketRole({
name: 'clientuniverse',
passwordHash: 'clientuniverse' // authentication happens on another level
});
this.smartsocket.addSocketRoles([ClientRole]);
const SubscriptionSocketFunction = new plugins.smartsocket.SocketFunction({
allowedRoles: [ClientRole],
funcName: 'channelSubscription',
funcDef: () => {}
});
this.smartsocket.setExternalServer('express', this.smartexpressServer as any);
// should work with express as well
this.smartsocket.start(); this.smartsocket.start();
await this.smartexpressServer.start(); await this.smartexpressServer.start();

View File

@ -0,0 +1,63 @@
import * as plugins from './smartuniverse.plugins';
import { UniverseChannel } from './smartuniverse.classes.universechannel';
import { UniverseMessage } from './smartuniverse.classes.universemessage';
import { Objectmap } from '@pushrocks/lik';
import { Observable, from } from 'rxjs';
import { filter } from 'rxjs/operators';
import { rxjs } from '@pushrocks/smartrx';
/**
* universe store handles the creation, storage and retrieval of messages.
*/
export class UniverseCache {
// ========
// INSTANCE
// ========
public standardMessageExpiry: number;
public destructionTime: number = 60000;
/**
* stores messages for this instance
*/
public messageMap = new Objectmap<UniverseMessage>();
/**
* stores the channels that are available within the universe
*/
public channelMap = new Objectmap<UniverseChannel>();
/**
* allows messages to be processed in a blacklist mode for further analysis
*/
public blackListChannel = new UniverseChannel(this, 'blacklist', 'nada');
constructor(standardMessageExpiryArg: number) {
this.standardMessageExpiry = standardMessageExpiryArg;
}
/**
* add a message to the UniverseStore
* @param messageArg
* @param attachedPayloadArg
*/
public async addMessage(messageArg: UniverseMessage) {
messageArg.setUniverseCache(this);
UniverseChannel.authorizeAMessageForAChannel(this, messageArg);
this.messageMap.add(messageArg);
}
/**
* Read a message from the UniverseStore
*/
public readMessagesYoungerThan(unixTimeArg?: number): Observable<UniverseMessage> {
const messageObservable = from(this.messageMap.getArray()).pipe(
filter(messageArg => {
return messageArg.timestamp.isYoungerThanMilliSeconds(this.destructionTime);
})
);
return messageObservable;
}
}

View File

@ -1,61 +1,62 @@
import * as plugins from './smartuniverse.plugins'; import * as plugins from './smartuniverse.plugins';
import { Objectmap } from 'lik'; import { Objectmap } from '@pushrocks/lik';
import { UniverseCache } from './smartuniverse.classes.universecache';
import { UniverseMessage } from './smartuniverse.classes.universemessage';
/** /**
* enables messages to stay within a certain scope. * enables messages to stay within a certain scope.
*/ */
export class UniverseChannel { export class UniverseChannel {
// ====== // ======
// STATIC // STATIC
// ====== // ======
/**
* stores the channels that are available within the universe
*/
public static channelStore = new Objectmap<UniverseChannel>();
/**
* allows messages to be processed in a blacklist mode for further analysis
*/
public static blackListChannel = new UniverseChannel('blacklist', 'nada');
/** /**
* creates new channels * creates new channels
* @param channelArg the name of the topic * @param channelArg the name of the topic
* @param passphraseArg the secret thats used for a certain topic. * @param passphraseArg the secret thats used for a certain topic.
*/ */
public static createChannel (channelNameArg: string, passphraseArg: string) { public static createChannel(
const newChannel = new UniverseChannel(channelNameArg, passphraseArg); universeCacheArg: UniverseCache,
channelNameArg: string,
passphraseArg: string
) {
const newChannel = new UniverseChannel(universeCacheArg, channelNameArg, passphraseArg);
return newChannel; return newChannel;
}; }
/** /**
* returns boolean wether certain channel exists * returns boolean wether certain channel exists
*/ */
public static async doesChannelExists (channelNameArg: string) { public static async doesChannelExists(universeCacheArg: UniverseCache, channelNameArg: string) {
const channel = this.channelStore.find(channelArg => { const channel = universeCacheArg.channelMap.find(channelArg => {
return channelArg.name === channelNameArg; return channelArg.name === channelNameArg;
}); });
if(channel) { if (channel) {
return true; return true;
} else { } else {
return false; return false;
} }
} }
public static authorizeForChannel (channelNameArg: string, passphraseArg: string) { public static authorizeAMessageForAChannel(
const foundChannel = this.channelStore.find(universeChannel => { universeCacheArg: UniverseCache,
const result = universeChannel.authenticate(channelNameArg, passphraseArg); universeMessageArg: UniverseMessage
) {
const foundChannel = universeCacheArg.channelMap.find(universeChannel => {
const result = universeChannel.authenticate(universeMessageArg);
return result; return result;
}); });
if(foundChannel) { if (foundChannel) {
universeMessageArg.authenticated = true;
universeMessageArg.universeChannelList.add(foundChannel);
return foundChannel; return foundChannel;
} else { } else {
return this.blackListChannel; universeMessageArg.authenticated = false;
universeMessageArg.universeChannelList.add(universeCacheArg.blackListChannel);
}
} }
};
// ======== // ========
// INSTANCE // INSTANCE
@ -64,22 +65,27 @@ export class UniverseChannel {
* the name of the channel * the name of the channel
*/ */
public name: string; public name: string;
public universeCacheInstance: UniverseCache;
/** /**
* the passphrase for the channel * the passphrase for the channel
*/ */
public passphrase: string; public passphrase: string;
constructor(channelNameArg: string, passphraseArg: string) { constructor(universeCacheArg: UniverseCache, channelNameArg: string, passphraseArg: string) {
this.name = channelNameArg; this.name = channelNameArg;
this.passphrase = passphraseArg; this.passphrase = passphraseArg;
UniverseChannel.channelStore.add(this);
} }
/** /**
* authenticates a client on the server side * authenticates a client on the server side
*/ */
public authenticate(channelNameArg: string, passphraseArg: string): boolean { public authenticate(universeMessageArg: UniverseMessage): boolean {
return (this.name === channelNameArg && this.passphrase === passphraseArg); return (
this.name === universeMessageArg.requestedChannelName &&
this.passphrase === universeMessageArg.requestedChannelPassphrase
);
} }
public pushToClients(messageArg: UniverseMessage) {}
} }

View File

@ -1,12 +1,15 @@
import * as plugins from './smartuniverse.plugins'; import * as plugins from './smartuniverse.plugins';
import { Timer, TimeStamp } from 'smarttime'; import { Objectmap } from '@pushrocks/lik';
import { UniverseChannel } from './smartuniverse.classes.universechannel';
import { UniverseStore } from './smartuniverse.classes.universestore'; import { Timer, TimeStamp } from '@pushrocks/smarttime';
import { Universe } from './smartuniverse.classes.universe'; import { Universe } from './smartuniverse.classes.universe';
import { UniverseChannel } from './smartuniverse.classes.universechannel';
import { UniverseCache } from './smartuniverse.classes.universecache';
/** /**
* represents a message within a universe * represents a message within a universe
* acts as a container to save message states like authentication status
*/ */
export class UniverseMessage { export class UniverseMessage {
/** /**
@ -18,13 +21,25 @@ export class UniverseMessage {
public id: number; public id: number;
/** /**
* the universe store the message is attached to * the UniverseCache the message is attached to
*/ */
public universeStore: UniverseStore; public universeCache: UniverseCache;
/**
* requestedChannelName
*/
public requestedChannelName: string;
public requestedChannelPassphrase: string;
/** /**
* enables unprotected grouping of messages for efficiency purposes. * enables unprotected grouping of messages for efficiency purposes.
*/ */
public universeChannel: UniverseChannel; public universeChannelList = new Objectmap<UniverseChannel>();
/**
* wether the message is authenticated
*/
public authenticated: boolean = null;
/** /**
* time of creation * time of creation
@ -47,16 +62,23 @@ export class UniverseMessage {
* @param messageArg * @param messageArg
* @param attachedPayloadArg * @param attachedPayloadArg
*/ */
constructor(messageArg: string, channelNameArg: string, passphraseArg: string, attachedPayloadArg: any) { constructor(
messageArg: string,
requestedChannelNameArg: string,
passphraseArg: string,
attachedPayloadArg: any
) {
this.timestamp = new TimeStamp(); this.timestamp = new TimeStamp();
this.message = messageArg; this.message = messageArg;
this.universeChannel = UniverseChannel.authorizeForChannel(channelNameArg, passphraseArg); this.requestedChannelName = requestedChannelNameArg;
this.requestedChannelPassphrase = passphraseArg;
this.attachedPayload = attachedPayloadArg; this.attachedPayload = attachedPayloadArg;
// prevent memory issues
this.fallBackDestruction(); this.fallBackDestruction();
} }
public setUniverseStore(universeStoreArg: UniverseStore) { public setUniverseCache(universeCacheArg: UniverseCache) {
this.universeStore = universeStoreArg; this.universeCache = universeCacheArg;
} }
public setDestructionTimer(selfdestructAfterArg: number) { public setDestructionTimer(selfdestructAfterArg: number) {
@ -64,15 +86,22 @@ export class UniverseMessage {
this.destructionTimer = new Timer(selfdestructAfterArg); this.destructionTimer = new Timer(selfdestructAfterArg);
this.destructionTimer.start(); this.destructionTimer.start();
// set up self destruction by removing this from the parent messageStore // set up self destruction by removing this from the parent messageCache
this.destructionTimer.completed.then(async () => { this.destructionTimer.completed.then(async () => {
this.universeStore.messageStore.remove(this); this.universeCache.messageMap.remove(this);
}); });
} else { } else {
this.fallBackDestruction(); this.fallBackDestruction();
} }
} }
/**
* handles bad messages for further analysis
*/
handleAsBadMessage() {
console.log('received a bad message');
}
/** /**
* prevents memory leaks if channels have no default * prevents memory leaks if channels have no default
*/ */

View File

@ -1,43 +0,0 @@
import * as plugins from './smartuniverse.plugins';
import { UniverseMessage } from './smartuniverse.classes.universemessage';
import { Objectmap } from 'lik';
import { Observable } from 'rxjs';
import { rxjs } from 'smartrx';
/**
* universe store handles the creation, storage and retrieval of messages.
*/
export class UniverseStore {
public standardMessageExpiry: number;
public destructionTime: number = 60000;
public messageStore = new Objectmap<UniverseMessage>();
private lastId: number = 0; // stores the last id
constructor(standardMessageExpiryArg: number) {
this.standardMessageExpiry = standardMessageExpiryArg;
}
/**
* add a message to the UniverseStore
* @param messageArg
* @param attachedPayloadArg
*/
public addMessage(messageArg: UniverseMessage) {
this.messageStore.add(messageArg);
}
/**
* Read a message from the UniverseStore
*/
public readMessagesYoungerThan(unixTimeArg?: number): Observable<UniverseMessage> {
const messageObservable = rxjs.Observable.from(this.messageStore.getArray()).filter(
messageArg => {
return messageArg.timestamp.isYoungerThanMilliSeconds(this.destructionTime);
}
);
return messageObservable;
}
}

View File

@ -1,14 +0,0 @@
import * as plugins from './smartuniverse.plugins';
import { Universe } from './index';
process.env.CLI = 'true';
const universeCli = new plugins.smartcli.Smartcli();
universeCli.standardTask().subscribe(async argvArg => {
const standardUniverse = new Universe({
messageExpiryInMilliseconds: 60000
});
await standardUniverse.initServer(8765);
});

View File

@ -0,0 +1,3 @@
export interface IUniverseChannel {}
export interface IUniverseMessage {}

View File

@ -1,25 +1,27 @@
import * as smartcli from '@pushrocks/smartcli'; // node native
import * as lik from 'lik';
import * as nodehash from 'nodehash';
import * as path from 'path'; import * as path from 'path';
import * as smartdelay from 'smartdelay';
import * as smartexpress from 'smartexpress'; export { path };
import * as smartfile from 'smartfile';
import * as smartq from 'smartq'; // pushrocks scope
import * as smartrequest from 'smartrequest'; import * as lik from '@pushrocks/lik';
import * as smartrx from 'smartrx'; import * as smarthash from '@pushrocks/smarthash';
import * as smartsocket from 'smartsocket'; import * as smartdelay from '@pushrocks/smartdelay';
import * as smarttime from 'smarttime'; import * as smartexpress from '@pushrocks/smartexpress';
import * as smartfile from '@pushrocks/smartfile';
import * as smartpromise from '@pushrocks/smartpromise';
import * as smartrequest from '@pushrocks/smartrequest';
import * as smartrx from '@pushrocks/smartrx';
import * as smartsocket from '@pushrocks/smartsocket';
import * as smarttime from '@pushrocks/smarttime';
export { export {
lik, lik,
nodehash, smarthash,
path,
smartcli,
smartdelay, smartdelay,
smartexpress, smartexpress,
smartfile, smartfile,
smartq, smartpromise,
smartrx, smartrx,
smartrequest, smartrequest,
smartsocket, smartsocket,

View File

@ -1,12 +1,17 @@
{ {
"extends": [ "extends": ["tslint:latest", "tslint-config-prettier"],
"tslint:latest",
"tslint-config-prettier"
],
"rules": { "rules": {
"semicolon": [ "semicolon": [true, "always"],
true, "no-console": false,
"always" "ordered-imports": false,
"object-literal-sort-keys": false,
"member-ordering": {
"options":{
"order": [
"static-method"
] ]
} }
}
},
"defaultSeverity": "warning"
} }