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

feat: add midway gRPC framework #786

Merged
merged 23 commits into from
Jan 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
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
5 changes: 5 additions & 0 deletions packages/bootstrap/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
IMidwayContainer,
IConfigurationOptions,
MidwayFrameworkType,
MidwayContextLogger
} from '@midwayjs/core';
import { clearAllLoggers } from '@midwayjs/logger';
import { join } from 'path';
Expand Down Expand Up @@ -90,6 +91,10 @@ class TestFrameworkUnit implements IMidwayFramework<any, MockConfigurationOption
getFrameworkName() {
return 'midway:mock'
}

getDefaultContextLoggerClass() {
return MidwayContextLogger
}
}

describe('/test/index.test.ts', () => {
Expand Down
4 changes: 2 additions & 2 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
"typings": "dist/index.d.ts",
"scripts": {
"build": "midway-bin build -c",
"test": "midway-bin test --ts --forceExit",
"cov": "midway-bin cov --ts --forceExit",
"test": "midway-bin test --ts",
"cov": "midway-bin cov --ts",
"link": "npm link"
},
"keywords": [
Expand Down
77 changes: 66 additions & 11 deletions packages/core/src/baseFramework.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
ILifeCycle,
IMidwayApplication,
IMidwayBootstrapOptions,
IMidwayContainer,
IMidwayContainer, IMidwayContext,
IMidwayFramework,
MidwayFrameworkType,
MidwayProcessTypeEnum,
Expand All @@ -16,10 +16,11 @@ import {
listModule,
LOGGER_KEY,
} from '@midwayjs/decorator';
import { ILogger, loggers, LoggerOptions } from '@midwayjs/logger';
import { ILogger, loggers, LoggerOptions, IMidwayLogger } from '@midwayjs/logger';
import { isAbsolute, join, dirname } from 'path';
import { createMidwayLogger } from './logger';
import { createMidwayLogger, MidwayContextLogger } from './logger';
import { safeRequire } from './util';
import { MidwayRequestContainer } from './context/requestContainer';

function buildLoadDir(baseDir, dir) {
if (!isAbsolute(dir)) {
Expand All @@ -33,21 +34,27 @@ function setupAppDir(baseDir: string) {
}

export abstract class BaseFramework<
APP extends IMidwayApplication,
T extends IConfigurationOptions
> implements IMidwayFramework<APP, T> {
APP extends IMidwayApplication<CTX>,
CTX extends IMidwayContext,
OPT extends IConfigurationOptions,
> implements IMidwayFramework<APP, OPT> {
protected isTsMode = true;
protected baseDir: string;
protected appDir: string;
protected applicationContext: IMidwayContainer;
protected logger: ILogger;
protected appLogger: ILogger;
public configurationOptions: T;
public configurationOptions: OPT;
public app: APP;
protected pkg: object;
protected defaultContext = {};
protected BaseContextLoggerClass: any;

public configure(options: T): BaseFramework<APP, T> {
public configure(options: OPT): BaseFramework<APP, CTX, OPT> {
this.configurationOptions = options;
this.BaseContextLoggerClass = options.ContextLoggerClass || this.getDefaultContextLoggerClass();
this.logger = options.logger;
this.appLogger = options.appLogger;
return this;
}

Expand Down Expand Up @@ -107,12 +114,13 @@ export abstract class BaseFramework<

protected async initializeLogger(options: IMidwayBootstrapOptions) {
if (!this.logger) {
this.logger = createMidwayLogger(this, 'coreLogger');
this.logger = new Proxy(createMidwayLogger(this, 'coreLogger'), {});
(this.logger as IMidwayLogger).updateDefaultLabel(this.getFrameworkName());
}
if (!this.appLogger) {
this.appLogger = createMidwayLogger(this, 'logger', {
fileLogName: 'midway-app.log',
});
}) as IMidwayLogger;
}
}

Expand Down Expand Up @@ -214,6 +222,15 @@ export abstract class BaseFramework<

public abstract run(): Promise<void>;

protected setContextLoggerClass(BaseContextLogger: any) {
this.BaseContextLoggerClass = BaseContextLogger;
}

protected createContextLogger(ctx: CTX, name?: string): ILogger {
const appLogger = this.getLogger(name);
return new this.BaseContextLoggerClass(ctx, appLogger);
}

public async stop(): Promise<void> {
await this.beforeStop();
await this.containerStop();
Expand All @@ -227,7 +244,8 @@ export abstract class BaseFramework<
return this.baseDir;
}

protected defineApplicationProperties(applicationProperties: object = {}) {
protected defineApplicationProperties(applicationProperties: object = {}, whiteList = []) {
const self = this;
const defaultApplicationProperties = {
getBaseDir: () => {
return this.baseDir;
Expand Down Expand Up @@ -276,7 +294,35 @@ export abstract class BaseFramework<
getProjectName: () => {
return this.getProjectName();
},

createAnonymousContext(extendCtx?: CTX) {
const ctx = extendCtx || Object.create(self.defaultContext);
if (!ctx.startTime) {
ctx.startTime = Date.now();
}
if (!ctx.logger) {
ctx.logger = self.createContextLogger(ctx);
}
if (!ctx.requestContext) {
ctx.requestContext = new MidwayRequestContainer(ctx, this.getApplicationContext());
ctx.requestContext.ready();
}
if (!ctx.getLogger) {
ctx.getLogger = (name) => {
return self.createContextLogger(ctx, name);
};
}
return ctx;
},

setContextLoggerClass(BaseContextLogger: any) {
return self.setContextLoggerClass(BaseContextLogger);
},

};
for (const method of whiteList) {
delete defaultApplicationProperties[method];
}
Object.assign(
this.app,
defaultApplicationProperties,
Expand Down Expand Up @@ -354,4 +400,13 @@ export abstract class BaseFramework<
public getProjectName() {
return this.pkg?.['name'] || '';
}

public getFrameworkName() {
return this.getFrameworkType().toString();
}

public getDefaultContextLoggerClass(): any {
return MidwayContextLogger;
}

}
2 changes: 1 addition & 1 deletion packages/core/src/context/applicationContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ export class BaseApplicationContext
const def = this.registry.getDefinition(identifier);
if (!isPathEqual(definition.srcPath, def.srcPath)) {
throw new Error(
`${identifier} path = ${definition.srcPath} is exist (${def.srcPath})!`
`${identifier} path = ${definition.srcPath} already exist (${def.srcPath})!`
);
}
}
Expand Down
31 changes: 22 additions & 9 deletions packages/core/src/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,18 @@ export enum MidwayProcessTypeEnum {
*/
export interface IMidwayLogger extends ILogger {}

export interface IMidwayApplication {
export interface IMidwayContext {
/**
* Custom properties.
*/
[key: string]: any;
requestContext: IMidwayContainer;
logger: ILogger;
getLogger(name?: string): ILogger;
startTime: number;
}

export interface IMidwayApplication<T extends IMidwayContext = IMidwayContext> {
getBaseDir(): string;
getAppDir(): string;
getEnv(): string;
Expand All @@ -304,12 +315,8 @@ export interface IMidwayApplication {
getCoreLogger(): ILogger;
createLogger(name: string, options: LoggerOptions): ILogger;
getProjectName(): string;
}

export interface IMidwayContext {
getRequestContext?(): IMidwayContainer;
requestContext: IMidwayContainer;
logger: ILogger;
createAnonymousContext(...args): T;
setContextLoggerClass(BaseContextLoggerClass: any): void;
}

/**
Expand All @@ -331,7 +338,11 @@ export interface IMidwayBootstrapOptions {
disableConflictCheck?: boolean;
}

export interface IConfigurationOptions {}
export interface IConfigurationOptions {
logger?: ILogger;
appLogger?: ILogger;
ContextLoggerClass?: any;
}

export interface IMidwayFramework<APP extends IMidwayApplication, T extends IConfigurationOptions> {
app: APP;
Expand All @@ -345,12 +356,14 @@ export interface IMidwayFramework<APP extends IMidwayApplication, T extends ICon
getConfiguration(key?: string): any;
getCurrentEnvironment(): string;
getFrameworkType(): MidwayFrameworkType;
getFrameworkName(): string;
getAppDir(): string;
getBaseDir(): string;
getLogger(name?: string): ILogger;
getCoreLogger(): ILogger;
createLogger(name: string, options: LoggerOptions): ILogger;
getProjectName(): string;
getDefaultContextLoggerClass(): any;
}

export enum MidwayFrameworkType {
Expand All @@ -359,7 +372,7 @@ export enum MidwayFrameworkType {
WEB_EXPRESS = '@midwayjs/express',
FAAS = '@midwayjs/faas',
MS_HSF = '',
MS_GRPC = '',
MS_GRPC = '@midwayjs/grpc',
MS_RABBITMQ = '@midwayjs/rabbitmq',
WS_IO = '@midwayjs/socketio',
WSS = '',
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export class MidwayContextLogger<T> {
protected contextLogger: ILogger;
public ctx: T;

constructor(ctx, contextLogger: ILogger) {
constructor(ctx, contextLogger: ILogger, contextLabelHandler?) {
this.ctx = ctx;
this.contextLogger = contextLogger;
}
Expand Down
17 changes: 16 additions & 1 deletion packages/core/test/baseFramework.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import * as path from 'path';
import {
clearAllModule,
clearContainerCache,
MidwayContextLogger,
MidwayRequestContainer,
} from '../src';
import * as mm from 'mm';
Expand Down Expand Up @@ -244,7 +245,7 @@ describe('/test/baseFramework.test.ts', () => {
// __dirname,
// './fixtures/app-with-conflict/base-app-decorator/src/lib/'
// );
// const s = `baseService path = ${p}/userManager.ts is exist (${p}/service.ts)!`;
// const s = `baseService path = ${p}/userManager.ts already exist (${p}/service.ts)!`;
// assert.ok(callback.withArgs(s).calledOnce);
// });

Expand Down Expand Up @@ -593,6 +594,20 @@ describe('/test/baseFramework.test.ts', () => {
expect(framework.getApplication().getFrameworkType()).toEqual(framework.getFrameworkType());
expect(framework.getApplication().getProjectName()).toEqual(framework.getProjectName());

// test context
class CustomContextLogger extends MidwayContextLogger<any> {
formatContextLabel(): string {
return 'bbbb';
}
}
framework.getApplication().setContextLoggerClass(CustomContextLogger);
expect(framework.getApplication().createAnonymousContext().startTime).toBeDefined();
const ctxLogger = framework.getApplication().createAnonymousContext().getLogger();
ctxLogger.info('ctx logger');

expect(framework.getApplication().createAnonymousContext().requestContext).toBeDefined();
expect(framework.getApplication().createAnonymousContext().logger).toBeDefined();

await framework.stop();
});
});
10 changes: 10 additions & 0 deletions packages/core/test/context/midwayContainer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,4 +208,14 @@ describe('/test/context/midwayContainer.test.ts', () => {
expect(sapp.getConfig().a).to.equal(3);
});

it('should test autoload', async () => {
const container = new MidwayContainer();
container.load({
loadDir: path.join(__dirname, '../fixtures/base-app-autoload/src'),
});

await container.ready();
assert((container.registry as unknown as Map<string, any>).has('userService'));
});

});
3 changes: 3 additions & 0 deletions packages/core/test/fixtures/base-app-autoload/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"name": "ali-demo-aspect"
}
17 changes: 17 additions & 0 deletions packages/core/test/fixtures/base-app-autoload/src/home.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Autoload, Init, Provide, Scope, ScopeEnum } from '@midwayjs/decorator';

@Autoload()
@Provide()
@Scope(ScopeEnum.Singleton)
export class UserService {

idx = 0;

@Init()
async initService() {
this.idx++;
}

async getUser() {
}
}
2 changes: 1 addition & 1 deletion packages/core/test/loader.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -409,7 +409,7 @@ describe('/test/loader.test.ts', () => {
__dirname,
'./fixtures/app-with-conflict/base-app-decorator/src/lib/'
);
const s = `baseService path = ${p}/userManager.ts is exist (${p}/service.ts)!`;
const s = `baseService path = ${p}/userManager.ts already exist (${p}/service.ts)!`;
assert.ok(callback.withArgs(s).calledOnce);
});

Expand Down
8 changes: 6 additions & 2 deletions packages/core/test/util.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { BaseFramework, IMidwayApplication, IMidwayBootstrapOptions, MidwayFrameworkType } from '../src';
import { BaseFramework, IMidwayApplication, IMidwayBootstrapOptions, MidwayFrameworkType, IMidwayContext } from '../src';

type mockApp = {} & IMidwayApplication;
type mockAppOptions = {};
type mockContext = IMidwayContext;

export class MockFramework extends BaseFramework<mockApp, mockAppOptions> {
export class MockFramework extends BaseFramework<mockApp, mockContext, mockAppOptions> {

getApplication(): mockApp {
return this.app;
Expand All @@ -21,4 +22,7 @@ export class MockFramework extends BaseFramework<mockApp, mockAppOptions> {
this.app = {} as IMidwayApplication;
}

getDefaultContextLoggerClass() {
return super.getDefaultContextLoggerClass();
}
}
6 changes: 3 additions & 3 deletions packages/decorator/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@
"typings": "dist/index.d.ts",
"scripts": {
"build": "midway-bin build -c",
"test": "midway-bin test --ts --forceExit",
"cov": "midway-bin cov --ts --forceExit",
"test": "midway-bin test --ts",
"cov": "midway-bin cov --ts",
"ci": "npm run test",
"link": "npm link"
},
"dependencies": {
"@types/express": "^4.17.8",
"@types/koa": "^2.11.4",
"camelcase": "^5.0.0",
"camelcase": "^6.2.0",
"class-transformer": "^0.3.1",
"joi": "^17.2.1",
"reflect-metadata": "^0.1.13"
Expand Down
7 changes: 7 additions & 0 deletions packages/decorator/src/annotation/autoload.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { savePreloadModule } from '../common/decoratorManager';

export function Autoload() {
return function (target) {
savePreloadModule(target);
};
}
Loading