This commit is contained in:
Daniel Hübleitner
2019-09-18 05:19:42 +02:00
parent 3cfbb3558f
commit ea18b22463
31 changed files with 174 additions and 1041 deletions
-20
View File
@@ -1,20 +0,0 @@
import { Socket } from './interfaces/Socket';
export declare class Client implements Socket {
port: number;
private server;
private tls;
private socket;
constructor(port: number, server: string, tls?: boolean);
hook(name: any, args: any): Socket;
unhook(name: any): Socket;
on(type: "error" | "close", f: (e?: any) => void): Socket;
destroy(): void;
close(): void;
call(rpcname: string, ...args: any[]): Promise<any>;
fire(rpcname: string, ...args: any[]): Promise<any>;
connect(): Promise<void>;
info(): Promise<any>;
private callGenerator;
private hookGenerator;
private unhookGenerator;
}
-88
View File
@@ -1,88 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var bsock = require('bsock');
//fix args with defaults like "force = true" -> "force"
function stripAfterEquals(str) {
return str.split("=")[0];
}
class Client {
constructor(port, server, tls = false) {
this.port = port;
this.server = server;
this.tls = tls;
}
hook(name, args) {
return this.socket.hook(name, args);
}
unhook(name) {
return this.socket.unhook(name);
}
on(type, f) {
return this.socket.on(type, name);
}
destroy() {
return this.socket.destroy();
}
close() {
return this.socket.close();
}
async call(rpcname, ...args) {
return await this.socket.call.apply(this.socket, [rpcname, ...args]);
}
async fire(rpcname, ...args) {
return await this.socket.fire.apply(this.socket, [rpcname, ...args]);
}
async connect() {
this.socket = await bsock.connect(this.port, this.server, this.tls);
const info = await this.info();
info.forEach(i => {
let f;
switch (i.type) {
case 'Call':
f = this.callGenerator(i.uniqueName, i.argNames);
break;
case 'Hook':
f = this.hookGenerator(i.uniqueName, i.argNames);
break;
case 'Unhook':
f = this.unhookGenerator(i.uniqueName, i.argNames);
break;
}
if (this[i.owner] == null)
this[i.owner] = {};
this[i.owner][i.name] = f;
this[i.owner][i.name].bind(this);
});
}
async info() {
return await this.socket.call('info');
}
callGenerator(fnName, fnArgs) {
const headerArgs = fnArgs.join(",");
const argParams = fnArgs.map(stripAfterEquals).join(",");
return eval('( () => async (' + headerArgs + ') => { return await this.socket.call("' + fnName + '", ' + argParams + ')} )()');
}
hookGenerator(fnName, fnArgs) {
const headerArgs = fnArgs.join(",");
const argParams = fnArgs.map(stripAfterEquals).join(",");
return eval(`( () => async (` + headerArgs + (headerArgs.length !== 0 ? "," : "") + ` callback) => {
const r = await this.socket.call("` + fnName + `", ` + argParams + `)
if(r.uid != null){
this.socket.hook(res.uid, callback)
}
return res
} )()`);
}
unhookGenerator(fnName, fnArgs) {
const headerArgs = fnArgs.join(",");
const argParams = fnArgs.map(stripAfterEquals).join(",");
if (fnArgs.length != 1)
console.error("UnhookFunction", fnName, "specified more than one argument: (" + headerArgs + ")");
return eval(`( () => async (` + headerArgs + `) => {
const r = await this.socket.call("` + fnName + `", ` + argParams + `)
this.socket.unhook(` + argParams + `)
return res
} )()`);
}
}
exports.Client = Client;
-17
View File
@@ -1,17 +0,0 @@
export declare type Outcome = "Success" | "Error";
export declare class Response {
message?: string | undefined;
constructor(message?: string | undefined);
}
export declare class SuccessResponse extends Response {
result: Outcome;
constructor(message?: string);
}
export declare class ErrorResponse extends Response {
result: Outcome;
constructor(message?: string);
}
export declare class SubscriptionResponse extends SuccessResponse {
uid: string;
constructor(uid: string, message?: string);
}
-30
View File
@@ -1,30 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/* Responses */
class Response {
constructor(message) {
this.message = message;
}
}
exports.Response = Response;
class SuccessResponse extends Response {
constructor(message) {
super(message);
this.result = "Success";
}
}
exports.SuccessResponse = SuccessResponse;
class ErrorResponse extends Response {
constructor(message = "Unknown error") {
super(message);
this.result = "Error";
}
}
exports.ErrorResponse = ErrorResponse;
class SubscriptionResponse extends SuccessResponse {
constructor(uid, message) {
super(message);
this.uid = uid;
}
}
exports.SubscriptionResponse = SubscriptionResponse;
-14
View File
@@ -1,14 +0,0 @@
import { SocketConf } from './Types';
import { Exporter } from './interfaces/Exporter';
import { Socket } from "./interfaces/Socket";
export declare class Server {
private port;
private rpcExporters;
private conf;
private io;
private wsServer;
constructor(port: number, rpcExporters?: Exporter[], conf?: SocketConf);
private startWebsocket;
protected initRPCs(socket: Socket): void;
protected initPublicRPCs(socket: Socket): void;
}
-58
View File
@@ -1,58 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const http = require("http");
const bsock = require("bsock");
const Util_1 = require("./Util");
class Server {
constructor(port, rpcExporters = [], conf = {
errorHandler: (socket) => (error) => { socket.destroy(); console.error(error); },
closeHandler: (socket) => () => { console.log("Socket closing"); },
connectionHandler: (socket) => { console.log("New websocket connection in port " + socket.port); },
visibility: "127.0.0.1"
}) {
this.port = port;
this.rpcExporters = rpcExporters;
this.conf = conf;
this.io = bsock.createServer();
this.wsServer = http.createServer();
this.startWebsocket();
}
startWebsocket() {
try {
this.io.attach(this.wsServer);
this.io.on('socket', (socket) => {
socket.on('error', this.conf.errorHandler(socket));
socket.on('close', this.conf.closeHandler(socket));
if (this.conf.visibility === "127.0.0.1")
this.initRPCs(socket);
else
this.initPublicRPCs(socket);
});
this.wsServer.listen(this.port, this.conf.visibility);
}
catch (e) {
//@ts-ignore
this.errorHandler(undefined)("Unable to connect to socket");
}
}
initRPCs(socket) {
const infoRPC = [
{
name: 'info',
type: 'Call',
func: async () => rpcInfos
}
];
const rpcInfos = [
...Util_1.rpcHooker(socket, "RPC", infoRPC, false),
...this.rpcExporters.flatMap(exporter => Util_1.rpcHooker(socket, exporter.name, [...exporter.exportPublicRPCs(), ...exporter.exportRPCs()]))
];
}
initPublicRPCs(socket) {
const rpcInfos = [
...Util_1.rpcHooker(socket, "Admin", adminRPCs, false),
...this.rpcExporters.flatMap(exporter => Util_1.rpcHooker(socket, exporter.name, exporter.exportPublicRPCs()))
];
}
}
exports.Server = Server;
-54
View File
@@ -1,54 +0,0 @@
import { SuccessResponse, ErrorResponse, SubscriptionResponse } from "./Response";
import { Socket } from "./interfaces/Socket";
export declare type Visibility = "127.0.0.1" | "0.0.0.0";
export declare type Name = string;
export declare type SocketConf = {
connectionHandler: (socket: Socket) => void;
errorHandler: (socket: Socket) => (error: any) => void;
closeHandler: (socket: Socket) => () => void;
visibility: Visibility;
};
export declare type rpcType = 'Hook' | 'Unhook' | 'Call';
export declare type BaseRPC = {
type: rpcType;
name: string;
};
export declare type HookRPC = BaseRPC & {
type: 'Hook';
func: CallbackFunction;
unhook: UnhookFunction;
};
export declare type UnhookRPC = BaseRPC & {
type: 'Unhook';
func: UnhookFunction;
};
export declare type CallRPC = BaseRPC & {
type: 'Call';
func: (...args: any[]) => Promise<any>;
};
export declare type SocketioRPC = CallRPC | UnhookRPC | HookRPC;
export declare type BaseInfo = {
owner: string;
argNames: string[];
};
export declare type HookInfo = BaseRPC & BaseInfo & {
type: 'Hook';
generator: (socket: any) => CallbackFunction;
unhook: UnhookFunction;
};
export declare type UnhookInfo = BaseRPC & BaseInfo & {
type: 'Unhook';
func: UnhookFunction;
};
export declare type CallInfo = BaseRPC & BaseInfo & {
type: 'Call';
func: AsyncFunction;
};
export declare type RpcInfo = HookInfo | UnhookInfo | CallInfo;
export declare type ExtendedRpcInfo = RpcInfo & {
uniqueName: string;
};
export declare type OnFunction = (type: 'error' | 'close', f: (e?: any) => void) => Socket;
export declare type UnhookFunction = (uid: string) => Promise<SuccessResponse | ErrorResponse>;
export declare type CallbackFunction = (...args: any[]) => Promise<SubscriptionResponse | ErrorResponse>;
export declare type AsyncFunction = (...args: any[]) => Promise<any>;
-2
View File
@@ -1,2 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
-4
View File
@@ -1,4 +0,0 @@
import { SocketioRPC, RpcInfo, ExtendedRpcInfo } from "./Types";
import { Socket } from "./interfaces/Socket";
export declare const rpcToRpcinfo: (rpc: SocketioRPC, owner: string) => RpcInfo;
export declare const rpcHooker: (socket: Socket, owner: string, RPCs: SocketioRPC[], makeUnique?: boolean) => ExtendedRpcInfo[];
-75
View File
@@ -1,75 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const uuid = require("uuid/v4");
exports.rpcToRpcinfo = (rpc, owner) => {
switch (rpc.type) {
case "Call":
return {
owner: owner,
argNames: extractArgs(rpc.func),
type: rpc.type,
name: rpc.name,
func: rpc.func,
};
case "Unhook":
return {
owner: owner,
argNames: extractArgs(rpc.func),
type: rpc.type,
name: rpc.name,
func: rpc.func,
};
case "Hook":
const generator = hookGenerator(rpc);
return {
owner: owner,
argNames: extractArgs(generator(undefined)),
type: rpc.type,
name: rpc.name,
unhook: rpc.unhook,
generator: generator,
};
}
};
exports.rpcHooker = (socket, owner, RPCs, makeUnique = true) => {
const suffix = makeUnique ? "-" + uuid().substr(0, 4) : "";
return RPCs.map(rpc => exports.rpcToRpcinfo(rpc, owner))
.map(info => {
const ret = info;
ret.uniqueName = info.name + suffix;
switch (info.type) {
case "Hook":
socket.hook(ret.uniqueName, info.generator(socket));
break;
default:
socket.hook(ret.uniqueName, info.func);
}
socket.on('close', () => socket.unhook(info.name));
return ret;
});
};
const hookGenerator = (rpc) => {
const argsArr = extractArgs(rpc.func);
argsArr.pop();
const args = argsArr.join(',');
return eval(`(socket) => async (` + args + `) => {
const res = await rpc.func(` + args + (args.length !== 0 ? ',' : '') + ` (x) => {
socket.call(res.uid, x)
})
if(res.result == 'Success'){
socket.on('close', async () => {
const unhookRes = await rpc.unhook(res.uid)
console.log("Specific close handler for", rpc.name, res.uid, unhookRes)
})
}
return res
}`);
};
const extractArgs = (f) => {
let fn = String(f);
let args = fn.substr(0, fn.indexOf(")"));
args = args.substr(fn.indexOf("(") + 1);
let ret = args.split(",");
return ret;
};
-97
View File
@@ -1,97 +0,0 @@
import { Socket } from "./RPCSocketServer";
declare type rpcType = 'hook' | 'unhook' | 'call';
export declare type Outcome = "Success" | "Error";
export declare type Visibility = "127.0.0.1" | "0.0.0.0";
export declare class Response {
message?: string | undefined;
constructor(message?: string | undefined);
}
export declare class SuccessResponse extends Response {
result: Outcome;
constructor(message?: string);
}
export declare class ErrorResponse extends Response {
result: Outcome;
constructor(message?: string);
}
export declare class SubscriptionResponse extends SuccessResponse {
uid: string;
constructor(uid: string, message?: string);
}
export declare type UnhookFunction = (uid: string) => Promise<SuccessResponse | ErrorResponse>;
export declare type callbackFunction = (...args: any[]) => Promise<SubscriptionResponse | ErrorResponse>;
export declare type AsyncFunction = (...args: any[]) => Promise<any>;
export interface RPCExporter {
name: string;
exportRPCs(): socketioRPC[];
exportPublicRPCs(): socketioRPC[];
}
declare type baseRPC = {
type: rpcType;
name: string;
};
declare type hookRPC = baseRPC & {
type: 'hook';
func: callbackFunction;
unhook: UnhookFunction;
};
declare type unhookRPC = baseRPC & {
type: 'unhook';
func: UnhookFunction;
};
declare type callRPC = baseRPC & {
type: 'call';
func: (...args: any[]) => Promise<any>;
};
export declare type socketioRPC = callRPC | unhookRPC | hookRPC;
export declare type baseInfo = {
owner: string;
argNames: string[];
};
declare type HookInfo = baseRPC & baseInfo & {
type: 'hook';
generator: (socket: any) => callbackFunction;
unhook: UnhookFunction;
};
declare type UnhookInfo = baseRPC & baseInfo & {
type: 'unhook';
func: UnhookFunction;
};
declare type CallInfo = baseRPC & baseInfo & {
type: 'call';
func: AsyncFunction;
};
declare type RpcInfo = HookInfo | UnhookInfo | CallInfo;
export declare type ExtendedRpcInfo = RpcInfo & {
uniqueName: string;
};
export declare const rpcToRpcinfo: (rpc: socketioRPC, owner: string) => RpcInfo;
declare type OnFunction = (type: 'error' | 'close', f: (e?: any) => void) => Socket;
export interface Socket {
port: number;
hook: (rpcname: string, ...args: any[]) => Socket;
unhook: (rpcname: string) => Socket;
call: (rpcname: string, ...args: any[]) => Promise<any>;
fire: (rpcname: string, ...args: any[]) => Promise<any>;
on: OnFunction;
destroy: () => void;
close: () => void;
}
export declare type RPCSocketConf = {
connectionHandler: (socket: Socket) => void;
errorHandler: (socket: Socket) => (error: any) => void;
closeHandler: (socket: Socket) => () => void;
};
export declare class RPCSocketServer {
private port;
private rpcExporters;
private visibility;
private conf;
private io;
private wsServer;
constructor(port: number, rpcExporters?: RPCExporter[], visibility?: Visibility, conf?: RPCSocketConf);
private startWebsocket;
protected initRPCs(socket: Socket): void;
protected initPublicRPCs(socket: Socket): void;
}
export {};
-153
View File
@@ -1,153 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const http = require("http");
const bsock = require("bsock");
const uuid = require("uuid/v4");
/* Responses */
class Response {
constructor(message) {
this.message = message;
}
}
exports.Response = Response;
class SuccessResponse extends Response {
constructor(message) {
super(message);
this.result = "Success";
}
}
exports.SuccessResponse = SuccessResponse;
class ErrorResponse extends Response {
constructor(message = "Unknown error") {
super(message);
this.result = "Error";
}
}
exports.ErrorResponse = ErrorResponse;
class SubscriptionResponse extends SuccessResponse {
constructor(uid, message) {
super(message);
this.uid = uid;
}
}
exports.SubscriptionResponse = SubscriptionResponse;
exports.rpcToRpcinfo = (rpc, owner) => {
switch (rpc.type) {
case "call":
return {
owner: owner,
argNames: extractArgs(rpc.func),
type: rpc.type,
name: rpc.name,
func: rpc.func,
};
case "unhook":
return {
owner: owner,
argNames: extractArgs(rpc.func),
type: rpc.type,
name: rpc.name,
func: rpc.func,
};
case "hook":
const generator = hookGenerator(rpc);
return {
owner: owner,
argNames: extractArgs(generator(undefined)),
type: rpc.type,
name: rpc.name,
unhook: rpc.unhook,
generator: generator,
};
}
};
function rpcHooker(socket, exporter, makeUnique = true) {
const owner = exporter.name;
const RPCs = [...exporter.exportPublicRPCs(), ...exporter.exportRPCs()];
const suffix = makeUnique ? "-" + uuid().substr(0, 4) : "";
return RPCs.map(rpc => exports.rpcToRpcinfo(rpc, owner))
.map(info => {
const ret = info;
ret.uniqueName = info.name + suffix;
switch (info.type) {
case "hook":
socket.hook(ret.uniqueName, info.generator(socket));
break;
default:
socket.hook(ret.uniqueName, info.func);
}
socket.on('close', () => socket.unhook(info.name));
return ret;
});
}
const hookGenerator = (rpc) => {
const argsArr = extractArgs(rpc.func);
argsArr.pop();
const args = argsArr.join(',');
return eval(`(socket) => async (` + args + `) => {
const res = await rpc.func(` + args + (args.length !== 0 ? ',' : '') + ` (x) => {
socket.call(res.uid, x)
})
if(res.result == 'Success'){
socket.on('close', async () => {
const unhookRes = await rpc.unhook(res.uid)
console.log("Specific close handler for", rpc.name, res.uid, unhookRes)
})
}
return res
}`);
};
const extractArgs = (f) => {
let fn = String(f);
let args = fn.substr(0, fn.indexOf(")"));
args = args.substr(fn.indexOf("(") + 1);
let ret = args.split(",");
return ret;
};
class RPCSocketServer {
constructor(port, rpcExporters = [], visibility = "127.0.0.1", conf = {
errorHandler: (socket) => (error) => { socket.destroy(); console.error(error); },
closeHandler: (socket) => () => { console.log("Socket closing"); },
connectionHandler: (socket) => { console.log("New websocket connection in port " + socket.port); }
}) {
this.port = port;
this.rpcExporters = rpcExporters;
this.visibility = visibility;
this.conf = conf;
this.io = bsock.createServer();
this.wsServer = http.createServer();
this.startWebsocket();
}
startWebsocket() {
try {
this.io.attach(this.wsServer);
this.io.on('socket', (socket) => {
socket.on('error', this.conf.errorHandler(socket));
socket.on('close', this.conf.closeHandler(socket));
if (this.visibility === "127.0.0.1")
this.initRPCs(socket);
else
this.initPublicRPCs(socket);
});
this.wsServer.listen(this.port, this.visibility);
}
catch (e) {
//@ts-ignore
this.errorHandler(undefined)("Unable to connect to socket");
}
}
initRPCs(socket) {
socket.hook('info', () => rpcInfos);
const rpcInfos = [
...this.rpcExporters.flatMap(exporter => rpcHooker(socket, exporter))
];
}
initPublicRPCs(socket) {
socket.hook('info', () => rpcInfos);
const rpcInfos = [
...this.rpcExporters.flatMap(exporter => rpcHooker(socket, exporter))
];
}
}
exports.RPCSocketServer = RPCSocketServer;
-6
View File
@@ -1,6 +0,0 @@
import { SocketioRPC, Name } from "../Types";
export interface Exporter {
name: Name;
exportRPCs(): SocketioRPC[];
exportPublicRPCs(): SocketioRPC[];
}
-2
View File
@@ -1,2 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
-11
View File
@@ -1,11 +0,0 @@
import { OnFunction } from "../Types";
export interface Socket {
port: number;
hook: (rpcname: string, ...args: any[]) => Socket;
unhook: (rpcname: string) => Socket;
call: (rpcname: string, ...args: any[]) => Promise<any>;
fire: (rpcname: string, ...args: any[]) => Promise<any>;
on: OnFunction;
destroy: () => void;
close: () => void;
}
-2
View File
@@ -1,2 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
-1
View File
@@ -1 +0,0 @@
export {};
-23
View File
@@ -1,23 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Server_1 = require("../src/Server");
//@ts-ignore
const Client_1 = require("../src/Client");
new Server_1.Server(20000, [{
name: "HelloWorldRPCGroup",
exportPublicRPCs: () => [],
exportRPCs: () => [{
type: 'call',
name: 'echo',
func: async (s) => s,
}],
}]);
<<<<<<< HEAD
const caller = new Client_1.Client(20000, 'localhost');
=======
const caller = new RPCSocket_1.RPCSocket(20000, 'localhost');
>>>>>>> 17dc58c5b3fd3c76113d592d895400498578affa
caller.connect().then(_ => {
caller.info().then(console.log);
caller["HelloWorldRPCGroup"].echo("x").then(console.log);
});