Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/cluster #9

Merged
merged 1 commit into from
Oct 10, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,25 @@
## 1.0.1-rc.5 (2020-10-10)


### Bug Fixes

* add useExisting for custom provider ([ea84c42](https://github.com/augejs/module-core/commit/ea84c4274d2a9de53724024d72e1de556d9d0488))
* refactor from hook util ([#1](https://github.com/augejs/module-core/issues/1)) ([f2b8046](https://github.com/augejs/module-core/commit/f2b804637cf82589079d5a8aef2dbe3108368b69))
* refactor life cycle hook ([#4](https://github.com/augejs/module-core/issues/4)) ([1f078ab](https://github.com/augejs/module-core/commit/1f078ab9b7a95a9cff79f6d2bea87e53c55219cb))
* refactor life cycle hook ([#4](https://github.com/augejs/module-core/issues/4)) ([#5](https://github.com/augejs/module-core/issues/5)) ([b8fd4a2](https://github.com/augejs/module-core/commit/b8fd4a2385497e8a258f7b880ff976e5f8228e32))
* refactor life cycle hook ([#4](https://github.com/augejs/module-core/issues/4)) ([#5](https://github.com/augejs/module-core/issues/5)) ([#6](https://github.com/augejs/module-core/issues/6)) ([557c6b1](https://github.com/augejs/module-core/commit/557c6b1a0e046c8b50ec5550c211d1c7293aec0b))
* update @augejs/provider-scanner ver ([92a0dcc](https://github.com/augejs/module-core/commit/92a0dcce98de97ba010607419f567e3fda0fa87e))
* update ver to 0.0.33 ([d1f1f34](https://github.com/augejs/module-core/commit/d1f1f34dad9b981ff2f900ddc88dc8d6a41657ea))


### Features

* add cluster feature ([ef011c6](https://github.com/augejs/module-core/commit/ef011c6ba086faaadcbcc76907368d0c4bbfd4e5))
* add cluster feature ([#8](https://github.com/augejs/module-core/issues/8)) ([260da2f](https://github.com/augejs/module-core/commit/260da2f482571f7629dc7c4319f7308665128ded))
* release for 1.0.0-rc.3 ([#7](https://github.com/augejs/module-core/issues/7)) ([72c6e87](https://github.com/augejs/module-core/commit/72c6e87fe05675e1ffec1fd0189cc2519620496e))



## 1.0.1-rc.4 (2020-10-07)

### Bug Fixes
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
{
"name": "@augejs/module-core",
"version": "1.0.1-rc.4",
"version": "1.0.1-rc.5",
"description": "`@augejs/module-core` is a module framework which support using `dependency injection` way to composite kinds of `Modules` and `Providers` to complex application.",
"main": "dist/main.js",
"directories": {
"doc": "docs"
},
"scripts": {
"build": "rimraf dist && tsc --build ./tsconfig.json",
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0",
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s",
"deploy": "npm run build && npm publish --access public",
"test": "jest",
"test:watch": "jest --watch",
Expand Down
130 changes: 89 additions & 41 deletions src/decorators/Cluster.decorator.ts
Original file line number Diff line number Diff line change
@@ -1,67 +1,115 @@
import os from 'os';
import cluster, { Worker } from 'cluster';

import { IScanNode, Metadata } from '@augejs/provider-scanner';
import { ScanHook } from './ScanHook.decorator';
import { LifecycleOnAppWillCloseHook, Lifecycle__onAppReady__Hook } from './LifecycleHook.decorator';
import { Logger } from '../logger';
import { Module } from './Module.decorator';

const logger = Logger.getLogger('cluster');

type ClusterOptions = {
workers: number
disabled?: boolean
enable?: boolean
clusterModule?: Function
};

export function Cluster (opts?:ClusterOptions):ClassDecorator {
@Module()
export class DefaultClusterModule {}

export function Cluster(opts?:ClusterOptions): ClassDecorator {
opts = {
workers: 0,
enable: true,
...opts,
};

return function(target: Function) {
Cluster.defineMetadata(target, opts!);
}
}

Cluster.hasMetadata = (target: Object): boolean => {
return Metadata.hasMetadata(Cluster, target)
}

Cluster.defineMetadata = (target: Object, opts: ClusterOptions)=> {
Metadata.defineMetadata(Cluster, opts, target);
}

Cluster.getMetadata = (target: object):ClusterOptions => {
return Metadata.getMetadata(Cluster, target) || {
workers: 0
};
}

Cluster.DefaultClusterModule = DefaultClusterModule;

Cluster.ClusterMasterClassDecorator = function (opts?:ClusterOptions):ClassDecorator {
opts = {
workers: 0,
disabled: false,
...opts,
};

return function(target: Function) {
Metadata.decorate([
ScanHook(async (scanNode: IScanNode, next: Function) => {
if (opts!.disabled) return;

if (cluster.isMaster) {
const cpuCount: number = os.cpus().length;
let workers: number = opts?.workers || 0;
if (workers < 0) {
workers = Math.abs(Math.trunc(workers));
workers = Math.min(workers, cpuCount);
} else if (workers > 0) {
workers = workers;
} else {
workers = cpuCount;
}
Lifecycle__onAppReady__Hook(async (scanNode: IScanNode, next: Function) => {
const cpuCount: number = os.cpus().length;
let workers: number = opts?.workers || parseInt(process.env.WORKERS || '0') || 0;
if (workers < 0) {
workers = Math.abs(Math.trunc(workers));
workers = Math.min(workers, cpuCount);
} else if (workers > 0) {
workers = workers;
} else {
workers = cpuCount;
}

for(let i = 0; i < workers; i++) {
await Promise.all(
Array.from(new Array(workers)).map(()=>{
return new Promise((resolve: Function, reject: Function) => {
const worker = cluster.fork()
.once('exit', (code: number, signal: string) => {
reject(new Error(`worker(pid: ${worker.process.pid}) Boot Error`));
})
.once('message', (message: any)=> {
if (message?.cmd === '__onAppReady__') {
worker.removeAllListeners('exit');
resolve();
}
})
})
})
)

cluster.on('exit', (worker: Worker, code: number, signal: string) => {
if (!worker.exitedAfterDisconnect) {
logger.info(`worker(pid: [${worker.process.pid}]) is exit. code: ${code} signal: ${signal} and will be forked new process`);
cluster.fork();
}
});
await next();
}),

cluster.on('exit', (worker: Worker, code: number, signal: string) => {
if (code !== 0 && !worker.exitedAfterDisconnect) {
cluster.fork();
LifecycleOnAppWillCloseHook(async (scanNode: IScanNode, next: Function) => {
cluster.removeAllListeners('exit');
await Promise.all(Object.values(cluster.workers).map((worker?: Worker) => {
return new Promise((resolve: Function) => {
if (!worker) {
resolve();
return;
}
})
// end of master
}
worker.once('exit', ()=>{
logger.warn(`worker(pid: [${worker.process.pid}]) is exited with signal: SIGTERM`);
resolve();
});

if (cluster.worker) {
worker.process.kill('SIGTERM');
logger.info(`worker(pid: [${worker.process.pid}]) is killed with signal: SIGTERM`);
})
}))

}
await next();
})
], target);
Cluster.defineMetadata(target, opts!);
}
}

Cluster.defineMetadata = (target: Object, opts: ClusterOptions)=> {
Metadata.defineMergeObjectMetadata(Cluster, opts, target);
}

Cluster.hasMetadata = (target: Object): boolean => {
return Metadata.hasMetadata(Cluster, target)
}

Cluster.getMetadata = (target: object):ClusterOptions => {
return Metadata.getMetadata(Cluster, target) || {};
}
7 changes: 7 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
typeof (process as any)?.pkg !== 'undefined' && (process.env.NODE_ENV = process.env.NODE_ENV || 'production');

import path from 'path';

export * from './decorators';
export * from './ioc';
export * from './logger';
export * from './utils';

export const __appRootDirName: string = process.env.APP_ROOT_DIR_NAME ||
(process.env.NODE_ENV === 'production' ? path.join(require.main!.filename, '..') : process.cwd());

export {
hookUtil,
Metadata,
Expand Down
68 changes: 36 additions & 32 deletions src/utils/boot.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { argv } from 'yargs';
import cluster from 'cluster';

import { argv } from 'yargs';
import { scan, IScanNode, IScanContext, hookUtil, HookMetadata, Metadata } from '@augejs/provider-scanner';
import { getConfigAccessPath } from './config.util';
import { objectPath, objectExtend } from './object.util';
import { BindingScopeEnum, Container, Injectable } from '../ioc';
import { Config, ConfigLoader } from '../decorators';
import { BindingScopeEnum, Container } from '../ioc';
import { Cluster, Config, ConfigLoader } from '../decorators';
import { ILogger, Logger, ConsoleLogTransport } from '../logger';
import { Cluster } from '../decorators/Cluster.decorator';

const DefaultLifeCyclePhases =
{
Expand Down Expand Up @@ -40,16 +39,20 @@ export const boot = async (appModule:Function, options?:IBootOptions): Promise<I
...(options?.containerOptions || {})
};

const isClusterMaster = cluster.isMaster && Cluster.hasMetadata(appModule) && !Cluster.getMetadata(appModule).disabled;
let rootModule: any = appModule;
if (isClusterMaster) {
@Cluster(Cluster.getMetadata(appModule))
@Injectable()
class ClusterModule {}
rootModule = ClusterModule;
if (cluster.isMaster && Cluster.hasMetadata(appModule)) {
const clusterOptions = Cluster.getMetadata(appModule);
if (clusterOptions.enable) {
const clusterModule = clusterOptions.clusterModule || Cluster.DefaultClusterModule;
Metadata.decorate([
Cluster.ClusterMasterClassDecorator({
workers: clusterOptions.workers,
})
], clusterModule);
appModule = clusterModule;
}
}

return await scan(rootModule, {
return await scan(appModule, {
// context level hooks.
contextScanHook: hookUtil.nestHooks([
async (context: IScanContext, next: Function) => {
Expand All @@ -61,6 +64,7 @@ export const boot = async (appModule:Function, options?:IBootOptions): Promise<I
if (Logger.getTransportCount() === 0) {
Logger.addTransport(new ConsoleLogTransport());
}
process.exit(1);
}
},
bootSetupEnv(containerOptions),
Expand Down Expand Up @@ -152,7 +156,7 @@ function bootLifeCyclePhases() {
const lifeCyclePhases: {[key: string]: string[]} = DefaultLifeCyclePhases;
return async (context: IScanContext, next: Function) => {
await next();

// last step
Object.keys(lifeCyclePhases).forEach((lifeCyclePhaseName: string) => {
const lifeCycleNames:string[] = lifeCyclePhases[lifeCyclePhaseName];
context.lifeCyclePhasesHooks[lifeCyclePhaseName] = hookUtil.sequenceHooks(lifeCycleNames.map((lifecycleName:string) => {
Expand All @@ -177,31 +181,31 @@ function bootLifeCyclePhases() {
const lifeCyclePhasesHooks: {[key: string]: Function} = context.lifeCyclePhasesHooks;

await lifeCyclePhasesHooks.startupLifecyclePhase();
process.nextTick(() => {
(async () => {
try {
// add default log transport.
if (Logger.getTransportCount() === 0) {
Logger.addTransport(new ConsoleLogTransport());
}
await lifeCyclePhasesHooks.readyLifecyclePhase();
} catch(err:any) {
logger.error('Ready Error \n' + err);
process.nextTick(async () => {
try {
// add default log transport.
if (Logger.getTransportCount() === 0) {
Logger.addTransport(new ConsoleLogTransport());
}
})()
// report the container self is ready
process.send?.({cmd: '__onAppReady__'});

await lifeCyclePhasesHooks.readyLifecyclePhase();
} catch(err:any) {
logger.error('Ready Error \n' + err);
}
})

//shutdown
// https://hackernoon.com/graceful-shutdown-in-nodejs-2f8f59d1c357
// https://blog.risingstack.com/graceful-shutdown-node-js-kubernetes/
process.on('exit', () => {
(async () => {
try {
await lifeCyclePhasesHooks.shutdownLifecyclePhase();
} catch(err:any) {
logger.error('ShutDown Error \n' + err);
}
})()
process.once('SIGTERM', async () => {
try {
await lifeCyclePhasesHooks.shutdownLifecyclePhase();
} catch(err:any) {
logger.error('ShutDown Error \n' + err);
}
process.exit();
})
}
}
Expand Down