Compare commits

..

20 Commits

Author SHA1 Message Date
08c1618ea8 1.1.51 2019-11-03 18:33:46 +01:00
eb181fa2f6 fix(core): update 2019-11-03 18:33:46 +01:00
c901ab75d3 1.1.50 2019-11-03 16:48:35 +01:00
075c59ed2c fix(core): update 2019-11-03 16:48:35 +01:00
8d358dd93d 1.1.49 2019-09-10 00:21:48 +02:00
e576d6058a fix(core): update 2019-09-10 00:21:47 +02:00
6546da2394 1.1.48 2019-09-09 23:58:32 +02:00
29597daba1 fix(core): update 2019-09-09 23:58:32 +02:00
c8b647d2fd 1.1.47 2019-09-09 16:20:43 +02:00
1fa4aca049 fix(core): update 2019-09-09 16:20:43 +02:00
2d4695de22 1.1.46 2019-09-01 18:07:53 +02:00
a3f4dcbc2a fix(core): update 2019-09-01 18:07:52 +02:00
d6e81288b4 1.1.45 2019-08-13 15:58:08 +02:00
c441d89596 fix(core): update 2019-08-13 15:58:08 +02:00
85b69e487a 1.1.44 2019-08-13 11:36:32 +02:00
0d94ed9345 fix(core): update 2019-08-13 11:36:31 +02:00
e188b18016 1.1.43 2019-08-13 09:37:23 +02:00
33c0fa3746 fix(core): update 2019-08-13 09:37:23 +02:00
52be1415ee 1.1.42 2019-08-12 22:46:57 +02:00
e75d5eabdb fix(core): update 2019-08-12 22:46:57 +02:00
14 changed files with 695 additions and 564 deletions

852
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{ {
"name": "@pushrocks/smartsocket", "name": "@pushrocks/smartsocket",
"version": "1.1.41", "version": "1.1.51",
"description": "easy and secure websocket communication", "description": "easy and secure websocket communication",
"main": "dist/index.js", "main": "dist/index.js",
"typings": "dist/index.d.ts", "typings": "dist/index.d.ts",
@ -19,26 +19,27 @@
}, },
"homepage": "https://gitlab.com/pushrocks/smartsocket#README", "homepage": "https://gitlab.com/pushrocks/smartsocket#README",
"dependencies": { "dependencies": {
"@pushrocks/lik": "^3.0.10", "@apiglobal/typedrequest-interfaces": "^1.0.7",
"@pushrocks/smartdelay": "^2.0.3", "@pushrocks/lik": "^3.0.11",
"@pushrocks/smartexpress": "^3.0.38", "@pushrocks/smartdelay": "^2.0.6",
"@pushrocks/smartexpress": "^3.0.52",
"@pushrocks/smarthash": "^2.0.6", "@pushrocks/smarthash": "^2.0.6",
"@pushrocks/smartlog": "^2.0.19", "@pushrocks/smartlog": "^2.0.21",
"@pushrocks/smartpromise": "^3.0.2", "@pushrocks/smartpromise": "^3.0.6",
"@types/shortid": "0.0.29", "@types/shortid": "0.0.29",
"@types/socket.io": "^2.1.2", "@types/socket.io": "^2.1.4",
"@types/socket.io-client": "^1.4.32", "@types/socket.io-client": "^1.4.32",
"shortid": "^2.2.14", "shortid": "^2.2.15",
"socket.io": "^2.2.0", "socket.io": "^2.3.0",
"socket.io-client": "^2.2.0" "socket.io-client": "^2.3.0"
}, },
"devDependencies": { "devDependencies": {
"@gitzone/tsbuild": "^2.1.11", "@gitzone/tsbuild": "^2.1.17",
"@gitzone/tsrun": "^1.2.8", "@gitzone/tsrun": "^1.2.8",
"@gitzone/tstest": "^1.0.24", "@gitzone/tstest": "^1.0.28",
"@pushrocks/tapbundle": "^3.0.11", "@pushrocks/tapbundle": "^3.0.13",
"@types/node": "^12.7.1", "@types/node": "^12.12.5",
"tslint": "^5.18.0", "tslint": "^5.20.0",
"tslint-config-prettier": "^1.18.0" "tslint-config-prettier": "^1.18.0"
}, },
"private": false, "private": false,

View File

@ -11,7 +11,7 @@ import smartsocket = require('../ts/index');
let testSmartsocket: smartsocket.Smartsocket; let testSmartsocket: smartsocket.Smartsocket;
let testSmartsocketClient: smartsocket.SmartsocketClient; let testSmartsocketClient: smartsocket.SmartsocketClient;
let testSocketRole1: smartsocket.SocketRole; let testSocketRole1: smartsocket.SocketRole;
let testSocketFunction1: smartsocket.SocketFunction; let testSocketFunction1: smartsocket.SocketFunction<any>;
let myseServer: smartexpress.Server; let myseServer: smartexpress.Server;
const testConfig = { const testConfig = {
@ -93,9 +93,7 @@ tap.test('should be able to make a functionCall from client to server', async ()
console.log(response); console.log(response);
}); });
tap.test('should be able to make a functionCall from server to client', async () => { tap.test('should be able to make a functionCall from server to client', async () => {});
});
// terminate // terminate
tap.test('should close the server', async () => { tap.test('should close the server', async () => {

View File

@ -9,8 +9,30 @@ import smartsocket = require('../ts/index');
let testSmartsocket: smartsocket.Smartsocket; let testSmartsocket: smartsocket.Smartsocket;
let testSmartsocketClient: smartsocket.SmartsocketClient; let testSmartsocketClient: smartsocket.SmartsocketClient;
let testSocketConnection: smartsocket.SocketConnection;
let testSocketRole1: smartsocket.SocketRole; let testSocketRole1: smartsocket.SocketRole;
let testSocketFunction1: smartsocket.SocketFunction; let testSocketFunctionForServer: smartsocket.SocketFunction<any>;
let testSocketFunctionClient: smartsocket.SocketFunction<any>;
export interface IReqResClient {
method: 'testFunction1';
request: {
value1: string;
};
response: {
value1: string;
};
}
export interface IReqResServer {
method: 'testFunction2';
request: {
hi: string;
};
response: {
hi: string
}
}
const testConfig = { const testConfig = {
port: 3000 port: 3000
@ -33,14 +55,23 @@ tap.test('should add a socketrole', async () => {
// class SocketFunction // class SocketFunction
tap.test('should register a new Function', async () => { tap.test('should register a new Function', async () => {
testSocketFunction1 = new smartsocket.SocketFunction({ testSocketFunctionForServer = new smartsocket.SocketFunction({
allowedRoles: [testSocketRole1], allowedRoles: [testSocketRole1],
funcDef: async (dataArg, socketConnectionArg) => { funcDef: async (dataArg, socketConnectionArg) => {
return dataArg; return dataArg;
}, },
funcName: 'testFunction1' funcName: 'testFunction1'
}); });
testSmartsocket.addSocketFunction(testSocketFunction1); testSmartsocket.addSocketFunction(testSocketFunctionForServer);
testSocketFunctionClient = new smartsocket.SocketFunction({
allowedRoles: [],
funcDef: async (dataArg, socketConnectionArg) => {
return dataArg;
},
funcName: 'testFunction2'
});
testSmartsocket.addSocketFunction(testSocketFunctionForServer);
console.log(testSmartsocket.socketFunctions); console.log(testSmartsocket.socketFunctions);
}); });
@ -57,33 +88,41 @@ tap.test('should react to a new websocket connection from client', async () => {
alias: 'testClient1', alias: 'testClient1',
role: 'testRole1' role: 'testRole1'
}); });
testSmartsocketClient.addSocketFunction(testSocketFunction1); testSmartsocketClient.addSocketFunction(testSocketFunctionClient);
console.log(testSmartsocketClient.socketFunctions); console.log(testSmartsocketClient.socketFunctions);
await testSmartsocketClient.connect(); await testSmartsocketClient.connect();
}); });
tap.test('client should disconnect and reconnect', async tools => {
await testSmartsocketClient.disconnect();
await tools.delayFor(100);
await testSmartsocketClient.connect();
});
tap.test('2 clients should connect in parallel', async () => { tap.test('2 clients should connect in parallel', async () => {
// TODO: implement parallel test // TODO: implement parallel test
}); });
tap.test('should be able to make a functionCall from client to server', async () => { tap.test('should be able to make a functionCall from client to server', async () => {
const response = await testSmartsocketClient.serverCall('testFunction1', { const response = await testSmartsocketClient.serverCall<IReqResClient>('testFunction1', {
value1: 'hello' value1: 'hello'
}); });
console.log(response); console.log(response);
expect(response.value1).to.equal('hello');
}); });
tap.test('should be able to make a functionCall from server to client', async () => { tap.test('should be able to make a functionCall from server to client', async () => {
const response = await testSmartsocketClient.serverCall('testFunction1', { const response = await testSmartsocket.clientCall<IReqResServer>(
hi: 'hi there from client' 'testFunction2',
}); {
hi: 'hi there from server'
},
testSmartsocket.socketConnections.find(socketConnection => {
return true;
})
);
console.log(response); console.log(response);
expect(response.hi).to.equal('hi there from server');
});
tap.test('client should disconnect and reconnect', async tools => {
await testSmartsocketClient.disconnect();
await tools.delayFor(100);
await testSmartsocketClient.connect();
}); });
// terminate // terminate

View File

@ -1,5 +1,3 @@
import * as plugins from './smartsocket.plugins';
// export main classes // export main classes
export * from './smartsocket.classes.smartsocket'; export * from './smartsocket.classes.smartsocket';
export * from './smartsocket.classes.smartsocketclient'; export * from './smartsocket.classes.smartsocketclient';

View File

@ -3,7 +3,7 @@ import * as plugins from './smartsocket.plugins';
// classes // classes
import { Objectmap } from '@pushrocks/lik'; import { Objectmap } from '@pushrocks/lik';
import { SocketConnection } from './smartsocket.classes.socketconnection'; import { SocketConnection } from './smartsocket.classes.socketconnection';
import { ISocketFunctionCall, SocketFunction } from './smartsocket.classes.socketfunction'; import { ISocketFunctionCallDataRequest, SocketFunction, ISocketFunctionCallDataResponse } from './smartsocket.classes.socketfunction';
import { SocketRequest } from './smartsocket.classes.socketrequest'; import { SocketRequest } from './smartsocket.classes.socketrequest';
import { SocketRole } from './smartsocket.classes.socketrole'; import { SocketRole } from './smartsocket.classes.socketrole';
import { SocketServer } from './smartsocket.classes.socketserver'; import { SocketServer } from './smartsocket.classes.socketserver';
@ -18,10 +18,10 @@ export interface ISmartsocketConstructorOptions {
export class Smartsocket { export class Smartsocket {
public options: ISmartsocketConstructorOptions; public options: ISmartsocketConstructorOptions;
public io: SocketIO.Server; public io: SocketIO.Server;
public openSockets = new Objectmap<SocketConnection>(); public socketConnections = new Objectmap<SocketConnection>();
public socketRoles = new Objectmap<SocketRole>(); public socketRoles = new Objectmap<SocketRole>();
public socketFunctions = new Objectmap<SocketFunction>(); public socketFunctions = new Objectmap<SocketFunction<any>>();
public socketRequests = new Objectmap<SocketRequest>(); public socketRequests = new Objectmap<SocketRequest<any>>();
private socketServer = new SocketServer(this); private socketServer = new SocketServer(this);
@ -50,14 +50,14 @@ export class Smartsocket {
*/ */
public async stop() { public async stop() {
await plugins.smartdelay.delayFor(1000); await plugins.smartdelay.delayFor(1000);
this.openSockets.forEach((socketObjectArg: SocketConnection) => { this.socketConnections.forEach((socketObjectArg: SocketConnection) => {
plugins.smartlog.defaultLogger.log( plugins.smartlog.defaultLogger.log(
'info', 'info',
`disconnect socket with >>alias ${socketObjectArg.alias}` `disconnect socket with >>alias ${socketObjectArg.alias}`
); );
socketObjectArg.socket.disconnect(); socketObjectArg.socket.disconnect();
}); });
this.openSockets.wipe(); this.socketConnections.wipe();
this.io.close(); this.io.close();
// stop the corresponging server // stop the corresponging server
@ -69,13 +69,12 @@ export class Smartsocket {
/** /**
* allows call to specific client. * allows call to specific client.
*/ */
public async clientCall( public async clientCall<T extends plugins.typedrequestInterfaces.ITypedRequest>(
functionNameArg: string, functionNameArg: T['method'],
dataArg: any, dataArg: T['request'],
targetSocketConnectionArg: SocketConnection targetSocketConnectionArg: SocketConnection
) { ): Promise<T['response']> {
const done = plugins.smartpromise.defer(); const socketRequest = new SocketRequest<T>(this, {
const socketRequest = new SocketRequest(this, {
funcCallData: { funcCallData: {
funcDataArg: dataArg, funcDataArg: dataArg,
funcName: functionNameArg funcName: functionNameArg
@ -84,10 +83,8 @@ export class Smartsocket {
shortId: plugins.shortid.generate(), shortId: plugins.shortid.generate(),
side: 'requesting' side: 'requesting'
}); });
socketRequest.dispatch().then((dataArg2: ISocketFunctionCall) => { const response: ISocketFunctionCallDataResponse<T> = await socketRequest.dispatch();
done.resolve(dataArg2.funcDataArg); const result = response.funcDataArg;
});
const result = await done.promise;
return result; return result;
} }
@ -101,14 +98,14 @@ export class Smartsocket {
return; return;
} }
public addSocketFunction(socketFunction: SocketFunction) { public addSocketFunction(socketFunction: SocketFunction<any>) {
this.socketFunctions.add(socketFunction); this.socketFunctions.add(socketFunction);
} }
/** /**
* the standard handler for new socket connections * the standard handler for new socket connections
*/ */
private _handleSocketConnection(socketArg) { private async _handleSocketConnection(socketArg: plugins.socketIo.Socket) {
const socketConnection: SocketConnection = new SocketConnection({ const socketConnection: SocketConnection = new SocketConnection({
alias: undefined, alias: undefined,
authenticated: false, authenticated: false,
@ -118,14 +115,8 @@ export class Smartsocket {
socket: socketArg socket: socketArg
}); });
plugins.smartlog.defaultLogger.log('info', 'Socket connected. Trying to authenticate...'); plugins.smartlog.defaultLogger.log('info', 'Socket connected. Trying to authenticate...');
this.openSockets.add(socketConnection); this.socketConnections.add(socketConnection);
socketConnection await socketConnection.authenticate();
.authenticate() await socketConnection.listenToFunctionRequests();
.then(() => {
return socketConnection.listenToFunctionRequests();
})
.catch(err => {
console.log(err);
});
} }
} }

View File

@ -1,7 +1,7 @@
import * as plugins from './smartsocket.plugins'; import * as plugins from './smartsocket.plugins';
import { SocketConnection } from './smartsocket.classes.socketconnection'; import { SocketConnection } from './smartsocket.classes.socketconnection';
import { ISocketFunctionCall, SocketFunction } from './smartsocket.classes.socketfunction'; import { ISocketFunctionCallDataRequest, SocketFunction } from './smartsocket.classes.socketfunction';
import { ISocketRequestDataObject, SocketRequest } from './smartsocket.classes.socketrequest'; import { ISocketRequestDataObject, SocketRequest } from './smartsocket.classes.socketrequest';
import { SocketRole } from './smartsocket.classes.socketrole'; import { SocketRole } from './smartsocket.classes.socketrole';
@ -18,26 +18,28 @@ export interface ISmartsocketClientOptions {
export class SmartsocketClient { export class SmartsocketClient {
public alias: string; public alias: string;
public role: string; public socketRole: SocketRole;
public socketConnection: SocketConnection; public socketConnection: SocketConnection;
public serverUrl: string; public serverUrl: string;
public serverPort: number; public serverPort: number;
public serverPassword: string;
public socketFunctions = new plugins.lik.Objectmap<SocketFunction>(); public socketFunctions = new plugins.lik.Objectmap<SocketFunction<any>>();
public socketRequests = new plugins.lik.Objectmap<SocketRequest>(); public socketRequests = new plugins.lik.Objectmap<SocketRequest<any>>();
public socketRoles = new plugins.lik.Objectmap<SocketRole>(); public socketRoles = new plugins.lik.Objectmap<SocketRole>();
constructor(optionsArg: ISmartsocketClientOptions) { constructor(optionsArg: ISmartsocketClientOptions) {
this.alias = optionsArg.alias; this.alias = optionsArg.alias;
this.role = optionsArg.role;
this.serverUrl = optionsArg.url; this.serverUrl = optionsArg.url;
this.serverPort = optionsArg.port; this.serverPort = optionsArg.port;
this.serverPassword = optionsArg.password; this.socketRole = new SocketRole({
name: optionsArg.role,
passwordHash: optionsArg.password
});
} }
public addSocketFunction(socketFunction: SocketFunction) { public addSocketFunction(socketFunction: SocketFunction<any>) {
this.socketFunctions.add(socketFunction); this.socketFunctions.add(socketFunction);
this.socketRole.allowedFunctions.add(socketFunction);
} }
/** /**
@ -50,40 +52,63 @@ export class SmartsocketClient {
this.socketConnection = new SocketConnection({ this.socketConnection = new SocketConnection({
alias: this.alias, alias: this.alias,
authenticated: false, authenticated: false,
role: undefined, role: this.socketRole,
side: 'client', side: 'client',
smartsocketHost: this, smartsocketHost: this,
socket: plugins.socketIoClient(socketUrl, { multiplex: false }) socket: plugins.socketIoClient(socketUrl, { multiplex: false })
}); });
this.socketConnection.socket.on('requestAuth', () => { this.socketConnection.socket.on('requestAuth', () => {
console.log('server requested authentication'); plugins.smartlog.defaultLogger.log('info', 'server requested authentication');
this.socketConnection.socket.emit('dataAuth', { this.socketConnection.socket.emit('dataAuth', {
role: this.role, role: this.socketRole.name,
password: this.serverPassword, password: this.socketRole.passwordHash,
alias: this.alias alias: this.alias
}); });
this.socketConnection.socket.on('authenticated', () => { this.socketConnection.socket.on('authenticated', () => {
console.log('client is authenticated'); plugins.smartlog.defaultLogger.log('info', 'client is authenticated');
this.socketConnection.authenticated = true; this.socketConnection.authenticated = true;
this.socketConnection.listenToFunctionRequests(); this.socketConnection.listenToFunctionRequests();
done.resolve(); done.resolve();
}); });
// handle errors
this.socketConnection.socket.on('reconnect_failed', async () => {
this.disconnect();
});
this.socketConnection.socket.on('connect_error', async () => {
this.disconnect();
});
}); });
return done.promise; return done.promise;
} }
public disconnect() { /**
const done = plugins.smartpromise.defer(); * disconnect from the server
this.socketConnection.socket.disconnect(); */
public async disconnect() {
if (this.socketConnection) {
this.socketConnection.socket.disconnect(true);
this.socketConnection = undefined; this.socketConnection = undefined;
plugins.smartlog.defaultLogger.log('ok', 'disconnected!'); plugins.smartlog.defaultLogger.log('ok', 'disconnected!');
done.resolve(); }
return done.promise;
} }
public serverCall(functionNameArg: string, dataArg: any) { /**
* try a reconnection
*/
public async tryDebouncedReconnect() {
await plugins.smartdelay.delayForRandom(10000, 60000);
await this.connect();
}
/**
* dispatches a server call
* @param functionNameArg
* @param dataArg
*/
public async serverCall<T extends plugins.typedrequestInterfaces.ITypedRequest>(functionNameArg: T['method'], dataArg: T['request']): Promise<T['response']> {
const done = plugins.smartpromise.defer(); const done = plugins.smartpromise.defer();
const socketRequest = new SocketRequest(this, { const socketRequest = new SocketRequest<T>(this, {
side: 'requesting', side: 'requesting',
originSocketConnection: this.socketConnection, originSocketConnection: this.socketConnection,
shortId: plugins.shortid.generate(), shortId: plugins.shortid.generate(),
@ -92,9 +117,8 @@ export class SmartsocketClient {
funcDataArg: dataArg funcDataArg: dataArg
} }
}); });
socketRequest.dispatch().then((dataArg2: ISocketFunctionCall) => { const response = await socketRequest.dispatch();
done.resolve(dataArg2.funcDataArg); const result = response.funcDataArg;
}); return result;
return done.promise;
} }
} }

View File

@ -5,10 +5,7 @@ import { Objectmap } from '@pushrocks/lik';
// import classes // import classes
import { Smartsocket } from './smartsocket.classes.smartsocket'; import { Smartsocket } from './smartsocket.classes.smartsocket';
import { SocketFunction } from './smartsocket.classes.socketfunction'; import { SocketFunction } from './smartsocket.classes.socketfunction';
import { import { SocketRequest, ISocketRequestDataObject } from './smartsocket.classes.socketrequest';
SocketRequest,
ISocketRequestDataObject,
} from './smartsocket.classes.socketrequest';
import { SocketRole } from './smartsocket.classes.socketrole'; import { SocketRole } from './smartsocket.classes.socketrole';
// socket.io // socket.io
@ -118,15 +115,15 @@ export class SocketConnection {
public listenToFunctionRequests() { public listenToFunctionRequests() {
const done = plugins.smartpromise.defer(); const done = plugins.smartpromise.defer();
if (this.authenticated) { if (this.authenticated) {
this.socket.on('function', (dataArg: ISocketRequestDataObject) => { this.socket.on('function', (dataArg: ISocketRequestDataObject<any>) => {
// check if requested function is available to the socket's scope // check if requested function is available to the socket's scope
plugins.smartlog.defaultLogger.log('info', 'function request received'); plugins.smartlog.defaultLogger.log('info', 'function request received');
const referencedFunction: SocketFunction = this.role.allowedFunctions.find( const referencedFunction: SocketFunction<any> = this.role.allowedFunctions.find(
socketFunctionArg => { socketFunctionArg => {
return socketFunctionArg.name === dataArg.funcCallData.funcName; return socketFunctionArg.name === dataArg.funcCallData.funcName;
} }
); );
if (referencedFunction !== undefined) { if (referencedFunction) {
plugins.smartlog.defaultLogger.log('ok', 'function in access scope'); plugins.smartlog.defaultLogger.log('ok', 'function in access scope');
const localSocketRequest = new SocketRequest(this.smartsocketRef, { const localSocketRequest = new SocketRequest(this.smartsocketRef, {
side: 'responding', side: 'responding',
@ -142,12 +139,15 @@ export class SocketConnection {
); );
} }
}); });
this.socket.on('functionResponse', (dataArg: ISocketRequestDataObject) => { this.socket.on('functionResponse', (dataArg: ISocketRequestDataObject<any>) => {
plugins.smartlog.defaultLogger.log( plugins.smartlog.defaultLogger.log(
'info', 'info',
`received response for request with id ${dataArg.shortId}` `received response for request with id ${dataArg.shortId}`
); );
const targetSocketRequest = SocketRequest.getSocketRequestById(this.smartsocketRef, dataArg.shortId); const targetSocketRequest = SocketRequest.getSocketRequestById(
this.smartsocketRef,
dataArg.shortId
);
targetSocketRequest.handleResponse(dataArg); targetSocketRequest.handleResponse(dataArg);
}); });
plugins.smartlog.defaultLogger.log( plugins.smartlog.defaultLogger.log(

View File

@ -12,34 +12,44 @@ import { SmartsocketClient } from './smartsocket.classes.smartsocketclient';
/** /**
* interface of the contructor options of class SocketFunction * interface of the contructor options of class SocketFunction
*/ */
export interface ISocketFunctionConstructorOptions { export interface ISocketFunctionConstructorOptions<T extends plugins.typedrequestInterfaces.ITypedRequest> {
funcName: string; funcName: T['method'];
funcDef: TFuncDef; funcDef: TFuncDef<T>;
allowedRoles: SocketRole[]; // all roles that are allowed to execute a SocketFunction allowedRoles: SocketRole[]; // all roles that are allowed to execute a SocketFunction
} }
/** /**
* interface of the Socket Function call, in other words the object that routes a call to a function * interface of the Socket Function call, in other words the object that routes a call to a function
*/ */
export interface ISocketFunctionCall { export interface ISocketFunctionCallDataRequest<T extends plugins.typedrequestInterfaces.ITypedRequest> {
funcName: string; funcName: T['method'];
funcDataArg: any; funcDataArg: T['request'];
}
/**
* interface of the Socket Function call, in other words the object that routes a call to a function
*/
export interface ISocketFunctionCallDataResponse<T extends plugins.typedrequestInterfaces.ITypedRequest> {
funcName: T['method'];
funcDataArg: T['response'];
} }
/** /**
* interface for function definition of SocketFunction * interface for function definition of SocketFunction
*/ */
export type TFuncDef = (dataArg: any, connectionArg: SocketConnection) => PromiseLike<any>; export type TFuncDef<T extends plugins.typedrequestInterfaces.ITypedRequest> = (dataArg: T['request'], connectionArg: SocketConnection) => PromiseLike<T['response']>;
// export classes // export classes
/** /**
* class that respresents a function that can be transparently called using a SocketConnection * class that respresents a function that can be transparently called using a SocketConnection
*/ */
export class SocketFunction { export class SocketFunction<T extends plugins.typedrequestInterfaces.ITypedRequest> {
// STATIC // STATIC
public static getSocketFunctionByName (smartsocketRefArg: Smartsocket | SmartsocketClient, functionNameArg: string): SocketFunction { public static getSocketFunctionByName<Q extends plugins.typedrequestInterfaces.ITypedRequest>(
console.log(smartsocketRefArg.socketFunctions); smartsocketRefArg: Smartsocket | SmartsocketClient,
functionNameArg: string
): SocketFunction<Q> {
return smartsocketRefArg.socketFunctions.find(socketFunctionArg => { return smartsocketRefArg.socketFunctions.find(socketFunctionArg => {
return socketFunctionArg.name === functionNameArg; return socketFunctionArg.name === functionNameArg;
}); });
@ -47,13 +57,13 @@ export class SocketFunction {
// INSTANCE // INSTANCE
public name: string; public name: string;
public funcDef: TFuncDef; public funcDef: TFuncDef<T>;
public roles: SocketRole[]; public roles: SocketRole[];
/** /**
* the constructor for SocketFunction * the constructor for SocketFunction
*/ */
constructor(optionsArg: ISocketFunctionConstructorOptions) { constructor(optionsArg: ISocketFunctionConstructorOptions<T>) {
this.name = optionsArg.funcName; this.name = optionsArg.funcName;
this.funcDef = optionsArg.funcDef; this.funcDef = optionsArg.funcDef;
this.roles = optionsArg.allowedRoles; this.roles = optionsArg.allowedRoles;
@ -65,20 +75,16 @@ export class SocketFunction {
/** /**
* invokes the function of this SocketFunction * invokes the function of this SocketFunction
*/ */
public invoke(dataArg: ISocketFunctionCall, socketConnectionArg: SocketConnection): Promise<any> { public async invoke(dataArg: ISocketFunctionCallDataRequest<T>, socketConnectionArg: SocketConnection): Promise<ISocketFunctionCallDataResponse<T>> {
const done = plugins.smartpromise.defer();
if (dataArg.funcName === this.name) { if (dataArg.funcName === this.name) {
this.funcDef(dataArg.funcDataArg, socketConnectionArg).then((resultData: any) => { const funcResponseData: ISocketFunctionCallDataResponse<T> = {
const funcResponseData: ISocketFunctionCall = {
funcName: this.name, funcName: this.name,
funcDataArg: resultData funcDataArg: await this.funcDef(dataArg.funcDataArg, socketConnectionArg)
}; };
done.resolve(funcResponseData); return funcResponseData;
});
} else { } else {
throw new Error("SocketFunction.name does not match the data argument's .name!"); throw new Error("SocketFunction.name does not match the data argument's .name!");
} }
return done.promise;
} }
/** /**

View File

@ -1,7 +1,7 @@
import * as plugins from './smartsocket.plugins'; import * as plugins from './smartsocket.plugins';
// import interfaces // import interfaces
import { SocketFunction, ISocketFunctionCall } from './smartsocket.classes.socketfunction'; import { SocketFunction, ISocketFunctionCallDataRequest, ISocketFunctionCallDataResponse } from './smartsocket.classes.socketfunction';
// import classes // import classes
import { Objectmap } from '@pushrocks/lik'; import { Objectmap } from '@pushrocks/lik';
@ -17,29 +17,29 @@ export type TSocketRequestSide = 'requesting' | 'responding';
/** /**
* interface of constructor of class SocketRequest * interface of constructor of class SocketRequest
*/ */
export interface SocketRequestConstructorOptions { export interface ISocketRequestConstructorOptions<T extends plugins.typedrequestInterfaces.ITypedRequest> {
side: TSocketRequestSide; side: TSocketRequestSide;
originSocketConnection: SocketConnection; originSocketConnection: SocketConnection;
shortId: string; shortId: string;
funcCallData?: ISocketFunctionCall; funcCallData?: ISocketFunctionCallDataRequest<T>;
} }
/** /**
* request object that is sent initially and may or may not receive a response * request object that is sent initially and may or may not receive a response
*/ */
export interface ISocketRequestDataObject { export interface ISocketRequestDataObject<T extends plugins.typedrequestInterfaces.ITypedRequest> {
funcCallData: ISocketFunctionCall; funcCallData: ISocketFunctionCallDataRequest<T> | ISocketFunctionCallDataResponse<T>;
shortId: string; shortId: string;
responseTimeout?: number; responseTimeout?: number;
} }
// export classes // export classes
export class SocketRequest { export class SocketRequest<T extends plugins.typedrequestInterfaces.ITypedRequest> {
// STATIC // STATIC
public static getSocketRequestById( public static getSocketRequestById(
smartsocketRef: Smartsocket | SmartsocketClient, smartsocketRef: Smartsocket | SmartsocketClient,
shortIdArg: string shortIdArg: string
): SocketRequest { ): SocketRequest<any> {
return smartsocketRef.socketRequests.find(socketRequestArg => { return smartsocketRef.socketRequests.find(socketRequestArg => {
return socketRequestArg.shortid === shortIdArg; return socketRequestArg.shortid === shortIdArg;
}); });
@ -50,13 +50,15 @@ export class SocketRequest {
public side: TSocketRequestSide; public side: TSocketRequestSide;
public shortid: string; public shortid: string;
public originSocketConnection: SocketConnection; public originSocketConnection: SocketConnection;
public funcCallData: ISocketFunctionCall; public funcCallData: ISocketFunctionCallDataRequest<T>;
public done = plugins.smartpromise.defer(); public done = plugins.smartpromise.defer<ISocketFunctionCallDataResponse<T>>();
public smartsocketRef: Smartsocket | SmartsocketClient; public smartsocketRef: Smartsocket | SmartsocketClient;
constructor(
constructor(smartsocketRefArg: Smartsocket | SmartsocketClient, optionsArg: SocketRequestConstructorOptions) { smartsocketRefArg: Smartsocket | SmartsocketClient,
optionsArg: ISocketRequestConstructorOptions<T>
) {
this.smartsocketRef = smartsocketRefArg; this.smartsocketRef = smartsocketRefArg;
this.side = optionsArg.side; this.side = optionsArg.side;
this.shortid = optionsArg.shortId; this.shortid = optionsArg.shortId;
@ -70,8 +72,8 @@ export class SocketRequest {
/** /**
* dispatches a socketrequest from the requesting to the receiving side * dispatches a socketrequest from the requesting to the receiving side
*/ */
public dispatch() { public dispatch(): Promise<ISocketFunctionCallDataResponse<T>> {
const requestData: ISocketRequestDataObject = { const requestData: ISocketRequestDataObject<T> = {
funcCallData: this.funcCallData, funcCallData: this.funcCallData,
shortId: this.shortid shortId: this.shortid
}; };
@ -82,7 +84,7 @@ export class SocketRequest {
/** /**
* handles the response that is received by the requesting side * handles the response that is received by the requesting side
*/ */
public handleResponse(responseDataArg: ISocketRequestDataObject) { public async handleResponse(responseDataArg: ISocketRequestDataObject<T>) {
plugins.smartlog.defaultLogger.log('info', 'handling response!'); plugins.smartlog.defaultLogger.log('info', 'handling response!');
this.done.resolve(responseDataArg.funcCallData); this.done.resolve(responseDataArg.funcCallData);
this.smartsocketRef.socketRequests.remove(this); this.smartsocketRef.socketRequests.remove(this);
@ -94,7 +96,7 @@ export class SocketRequest {
* creates the response on the responding side * creates the response on the responding side
*/ */
public async createResponse(): Promise<void> { public async createResponse(): Promise<void> {
const targetSocketFunction: SocketFunction = SocketFunction.getSocketFunctionByName( const targetSocketFunction: SocketFunction<T> = SocketFunction.getSocketFunctionByName(
this.smartsocketRef, this.smartsocketRef,
this.funcCallData.funcName this.funcCallData.funcName
); );
@ -110,11 +112,11 @@ export class SocketRequest {
plugins.smartlog.defaultLogger.log('info', `invoking ${targetSocketFunction.name}`); plugins.smartlog.defaultLogger.log('info', `invoking ${targetSocketFunction.name}`);
targetSocketFunction.invoke(this.funcCallData, this.originSocketConnection).then(resultData => { targetSocketFunction.invoke(this.funcCallData, this.originSocketConnection).then(resultData => {
plugins.smartlog.defaultLogger.log('info', 'got resultData. Sending it to requesting party.'); plugins.smartlog.defaultLogger.log('info', 'got resultData. Sending it to requesting party.');
const requestData: ISocketRequestDataObject = { const responseData: ISocketRequestDataObject<T> = {
funcCallData: resultData, funcCallData: resultData,
shortId: this.shortid shortId: this.shortid
}; };
this.originSocketConnection.socket.emit('functionResponse', requestData); this.originSocketConnection.socket.emit('functionResponse', responseData);
this.smartsocketRef.socketRequests.remove(this); this.smartsocketRef.socketRequests.remove(this);
}); });
} }

View File

@ -1,6 +1,5 @@
import * as plugins from './smartsocket.plugins'; import * as plugins from './smartsocket.plugins';
// import classes // import classes
import { Objectmap } from '@pushrocks/lik'; import { Objectmap } from '@pushrocks/lik';
import { SocketFunction } from './smartsocket.classes.socketfunction'; import { SocketFunction } from './smartsocket.classes.socketfunction';
@ -11,7 +10,7 @@ import { ISocketConnectionAuthenticationObject } from './smartsocket.classes.soc
/** /**
* interface for class SocketRole * interface for class SocketRole
*/ */
export interface SocketRoleOptions { export interface ISocketRoleOptions {
name: string; name: string;
passwordHash: string; passwordHash: string;
} }
@ -23,7 +22,7 @@ export class SocketRole {
// STATIC // STATIC
public static getSocketRoleByName( public static getSocketRoleByName(
referenceSmartsocket: Smartsocket | SmartsocketClient, referenceSmartsocket: Smartsocket | SmartsocketClient,
socketRoleNameArg: string, socketRoleNameArg: string
): SocketRole { ): SocketRole {
return referenceSmartsocket.socketRoles.find(socketRoleArg => { return referenceSmartsocket.socketRoles.find(socketRoleArg => {
return socketRoleArg.name === socketRoleNameArg; return socketRoleArg.name === socketRoleNameArg;
@ -34,7 +33,8 @@ export class SocketRole {
dataArg: ISocketConnectionAuthenticationObject, dataArg: ISocketConnectionAuthenticationObject,
referenceSmartsocket: Smartsocket | SmartsocketClient referenceSmartsocket: Smartsocket | SmartsocketClient
): boolean { ): boolean {
const targetPasswordHash = SocketRole.getSocketRoleByName(referenceSmartsocket, dataArg.role).passwordHash; const targetPasswordHash = SocketRole.getSocketRoleByName(referenceSmartsocket, dataArg.role)
.passwordHash;
const computedCompareHash = plugins.smarthash.sha256FromStringSync(dataArg.password); const computedCompareHash = plugins.smarthash.sha256FromStringSync(dataArg.password);
return targetPasswordHash === computedCompareHash; return targetPasswordHash === computedCompareHash;
} }
@ -42,12 +42,17 @@ export class SocketRole {
// INSTANCE // INSTANCE
public name: string; public name: string;
public passwordHash: string; public passwordHash: string;
public allowedFunctions = new Objectmap<SocketFunction>(); public allowedFunctions = new Objectmap<SocketFunction<any>>();
constructor(optionsArg: SocketRoleOptions) { constructor(optionsArg: ISocketRoleOptions) {
this.name = optionsArg.name; this.name = optionsArg.name;
this.passwordHash = optionsArg.passwordHash; this.passwordHash = optionsArg.passwordHash;
} }
public addSocketFunction(socketFunctionArg: SocketFunction) {
/**
* adds the socketfunction to the socketrole
* @param socketFunctionArg
*/
public addSocketFunction(socketFunctionArg: SocketFunction<any>) {
this.allowedFunctions.add(socketFunctionArg); this.allowedFunctions.add(socketFunctionArg);
} }
} }

View File

@ -2,6 +2,7 @@ import * as plugins from './smartsocket.plugins';
// used in case no other server is supplied // used in case no other server is supplied
import * as http from 'http'; import * as http from 'http';
import * as https from 'https';
import { Smartsocket } from './smartsocket.classes.smartsocket'; import { Smartsocket } from './smartsocket.classes.smartsocket';
/** /**
@ -10,7 +11,7 @@ import { Smartsocket } from './smartsocket.classes.smartsocket';
*/ */
export class SocketServer { export class SocketServer {
private smartsocket: Smartsocket; private smartsocket: Smartsocket;
private httpServer: http.Server; private httpServer: http.Server | https.Server;
// wether httpServer is standalone // wether httpServer is standalone
private standaloneServer = false; private standaloneServer = false;
private expressServer: any; private expressServer: any;
@ -54,11 +55,11 @@ export class SocketServer {
// in case an external server has been set "this.standaloneServer" should be false // in case an external server has been set "this.standaloneServer" should be false
if (this.httpServer && this.standaloneServer) { if (this.httpServer && this.standaloneServer) {
if (!this.smartsocket.options.port) { if (!this.smartsocket.options.port) {
console.log('there should be a port specifed for smartsocket!'); plugins.smartlog.defaultLogger.log('error', 'there should be a port specifed for smartsocket!');
throw new Error('there should be a port specified for smartsocket'); throw new Error('there should be a port specified for smartsocket');
} }
this.httpServer.listen(this.smartsocket.options.port, () => { this.httpServer.listen(this.smartsocket.options.port, () => {
console.log(`Server started in standalone mode on ${this.smartsocket.options.port}`); plugins.smartlog.defaultLogger.log('success', `Server started in standalone mode on ${this.smartsocket.options.port}`);
done.resolve(); done.resolve();
}); });
} else { } else {

View File

@ -1,12 +1,16 @@
// apiglobal scope
import * as typedrequestInterfaces from '@apiglobal/typedrequest-interfaces';
export {typedrequestInterfaces};
// pushrocks scope
import * as lik from '@pushrocks/lik'; import * as lik from '@pushrocks/lik';
import * as smartlog from '@pushrocks/smartlog'; import * as smartlog from '@pushrocks/smartlog';
import * as smarthash from '@pushrocks/smarthash'; import * as smarthash from '@pushrocks/smarthash';
import * as smartdelay from '@pushrocks/smartdelay'; import * as smartdelay from '@pushrocks/smartdelay';
import * as smartexpress from '@pushrocks/smartexpress'; import * as smartexpress from '@pushrocks/smartexpress';
import * as smartpromise from '@pushrocks/smartpromise'; import * as smartpromise from '@pushrocks/smartpromise';
import * as shortid from 'shortid';
import socketIo from 'socket.io';
import socketIoClient from 'socket.io-client';
export { export {
lik, lik,
@ -14,7 +18,15 @@ export {
smarthash, smarthash,
smartdelay, smartdelay,
smartexpress, smartexpress,
smartpromise, smartpromise
};
// third party scope
import * as shortid from 'shortid';
import socketIo from 'socket.io';
import socketIoClient from 'socket.io-client';
export {
shortid, shortid,
socketIo, socketIo,
socketIoClient socketIoClient