Skip to content

Commit

Permalink
Converting byte-buffer package into @runejs/core
Browse files Browse the repository at this point in the history
  • Loading branch information
TheBlackParade committed Oct 24, 2020
1 parent bac7d54 commit 672aa14
Show file tree
Hide file tree
Showing 9 changed files with 226 additions and 41 deletions.
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
# RuneJS Byte Buffer
[![RuneJS Discord Server](https://img.shields.io/discord/678751302297059336?label=RuneJS%20Discord&logo=discord)](https://discord.gg/5P74nSh)

A customized implementation of a NodeJS Buffer.

![RuneJS](https://i.imgur.com/osF9OSD.png)

# @runejs/core

Core functionality for RuneJS applications.
78 changes: 50 additions & 28 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 13 additions & 10 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@runejs/byte-buffer",
"version": "1.0.8",
"description": "A customized implementation of a NodeJS Buffer.",
"name": "@runejs/core",
"version": "1.0.0-beta.0",
"description": "Core functionality for RuneJS applications.",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
Expand All @@ -10,20 +10,23 @@
},
"repository": {
"type": "git",
"url": "git+ssh://[email protected]/rune-js/byte-buffer.git"
"url": "git+ssh://[email protected]/rune-js/core.git"
},
"author": "TheBlackParade",
"license": "GPL-3.0",
"bugs": {
"url": "https://github.com/rune-js/byte-buffer/issues"
"url": "https://github.com/rune-js/core/issues"
},
"homepage": "https://github.com/rune-js/byte-buffer#readme",
"homepage": "https://github.com/rune-js/core#readme",
"dependencies": {
"@runejs/logger": "^1.0.0",
"typescript": "^3.7.2"
"colors": "^1.4.0",
"js-yaml": "^3.14.0",
"moment": "^2.29.1",
"tslib": "^2.0.3",
"typescript": "^4.0.3"
},
"devDependencies": {
"@types/node": "^12.12.6",
"ts-node": "^8.5.4"
"@types/node": "^14.14.2",
"ts-node": "^9.0.0"
}
}
File renamed without changes.
5 changes: 4 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
export { ByteBuffer } from './byte-buffer';
export { ByteBuffer } from './buffer/byte-buffer';
export { logger, setLoggerDateFormat } from './logger/logger';
export * from './net/socket-server';
export { parseServerConfig } from './net/server-config';
28 changes: 28 additions & 0 deletions src/logger/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import moment from 'moment';
import { gray, red, yellow, cyan } from 'colors';

let runeJsLoggerDateFormat = 'YYYY-MM-DDTHH:mm:ss';

export const setLoggerDateFormat = (format: string) => runeJsLoggerDateFormat = format;

const log = (consoleType: string, ...args: any[]): void => {
const date = moment().format(runeJsLoggerDateFormat);
args.forEach(msg => {
if(consoleType === 'debug') {
msg = cyan(msg);
} else if(consoleType === 'warn') {
msg = yellow(msg);
} else if(consoleType === 'error') {
msg = red(msg);
}
const str = gray(`[${date}]: `) + msg;
console[consoleType](str);
});
};

export const logger = {
info: (...message: any[]) => log('info', ...message),
debug: (...message: any[]) => log('info', ...message),
warn: (...message: any[]) => log('warn', ...message),
error: (...message: any[]) => log('error', ...message)
};
51 changes: 51 additions & 0 deletions src/net/server-config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { logger } from '..';
import { JSON_SCHEMA, safeLoad } from 'js-yaml';
import { readFileSync } from 'fs';

interface ServerConfigOptions {
useDefault?: boolean;
configDir?: string;
configFileName?: string;
}

export function parseServerConfig<T>(options?: ServerConfigOptions): T {
if(!options) {
options = {
useDefault: false,
configDir: 'data/config',
configFileName: 'server-config'
};
} else {
if(!options.configDir) {
options.configDir = 'data/config';
}
if(!options.configFileName) {
options.configFileName = 'server-config';
}
}

try {
const config = safeLoad(readFileSync(
`${options.configDir}/${options.configFileName}${options.useDefault ? '.example' : ''}.yaml`, 'utf8'),
{ schema: JSON_SCHEMA }) as T;

if(!config) {
if(!options.useDefault) {
logger.warn('Server config not provided, using default...');
return parseServerConfig({ useDefault: true });
} else {
throw new Error('Syntax Error');
}
}

return config;
} catch(error) {
if(!options.useDefault) {
logger.warn('Server config not provided, using default...');
return parseServerConfig({ useDefault: true });
} else {
logger.error('Error parsing server config: ' + error);
return null;
}
}
}
48 changes: 48 additions & 0 deletions src/net/socket-server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { createServer, Socket } from 'net';
import { ByteBuffer } from '..';
import { logger } from '..';

export abstract class SocketConnectionHandler {

protected constructor() {
}

abstract async dataReceived(data: ByteBuffer): Promise<void>;
abstract connectionDestroyed(): void;

}

function socketError<T extends SocketConnectionHandler>(socket: Socket, connectionHandler: T, error): void {
connectionHandler.connectionDestroyed();
logger.error('Socket destroyed due to connection error.');
logger.error(error?.message || '[no message]');
socket.destroy();
}

export function registerSocket<T extends SocketConnectionHandler>(socket: Socket, connectionHandlerFactory: (socket: Socket) => T): void {
socket.setNoDelay(true);
socket.setKeepAlive(true);
socket.setTimeout(30000);

const connection: T = connectionHandlerFactory(socket);

socket.on('data', async data => {
try {
await connection.dataReceived(new ByteBuffer(data));
} catch(e) {
logger.error(e);
socket.destroy();
}
});

socket.on('close', () => {
// @TODO socket close event
});

socket.on('error', error => socketError(socket, connection, error));
}

export function openServer<T extends SocketConnectionHandler>(name: string, host: string, port: number, connectionHandlerFactory: (socket: Socket) => T): void {
createServer(socket => registerSocket<T>(socket, connectionHandlerFactory)).listen(port, host);
logger.info(`${ name } listening @ ${ host }:${ port }.`);
}
25 changes: 25 additions & 0 deletions src/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { openServer, SocketConnectionHandler, logger, setLoggerDateFormat, ByteBuffer } from './index';
import { Socket } from 'net';

class TestConnectionHandler extends SocketConnectionHandler {

public constructor(private readonly socket: Socket) {
super();
}

async dataReceived(data: ByteBuffer): Promise<void> {
logger.info(`Data received:`, data);
}

connectionDestroyed(): void {
logger.info(`Connection destroyed.`);
}

}

function launchTestServer() {
setLoggerDateFormat('HH:mm:ss');
openServer('Test Server', '0.0.0.0', 43586, socket => new TestConnectionHandler(socket));
}

launchTestServer();

0 comments on commit 672aa14

Please sign in to comment.