Skip to content

Commit

Permalink
fix: 2.x conflict 能力 (#449)
Browse files Browse the repository at this point in the history
* fix circular bug

* feat: lifecycle onReady add container

* fix bug

* fix bug

* add test case node module

* add srcPath

* fix case bug

* add conflict check

* add empty namespace test case

* add test case

* add srcPath def

* fix pipeline bug and lifecycle request ready bug

* add test case

* fix test case bug

* modified
  • Loading branch information
kurten authored Mar 30, 2020
1 parent 108677c commit 6064ecf
Show file tree
Hide file tree
Showing 36 changed files with 321 additions and 53 deletions.
10 changes: 9 additions & 1 deletion packages/midway-core/src/common/util.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { dirname, resolve, sep } from 'path';
import { dirname, resolve, sep, extname } from 'path';
import { MAIN_MODULE_KEY } from '../interface';

export const safeRequire = p => {
Expand Down Expand Up @@ -79,3 +79,11 @@ export function parsePrefix(provideId: string) {
}
return provideId;
}

export function isPathEqual(one: string, two: string) {
if (!one || !two) {
return false;
}
const ext = extname(one);
return one.replace(ext, '') === two;
}
13 changes: 8 additions & 5 deletions packages/midway-core/src/context/applicationContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
import { ObjectProperties } from '../definitions/properties';
import { ManagedResolverFactory } from './managedResolverFactory';
import { NotFoundError } from '../common/notFoundError';
import { parsePrefix } from '../common/util';
import { parsePrefix, isPathEqual } from '../common/util';

const PREFIX = '_id_default_';

Expand Down Expand Up @@ -105,7 +105,7 @@ export class BaseApplicationContext implements IApplicationContext, IObjectFacto
baseDir: string = null;
parent: IApplicationContext = null;
messageSource: IMessageSource = null;
disableClassConflict = false;
disableConflictCheck = false;

constructor(baseDir = '', parent?: IApplicationContext) {
this.parent = parent;
Expand Down Expand Up @@ -225,9 +225,12 @@ export class BaseApplicationContext implements IApplicationContext, IObjectFacto
* @param {IObjectDefinition} definition
*/
registerDefinition(identifier: ObjectIdentifier, definition: IObjectDefinition) {
// if (!this.disableClassConflict && this.registry.hasDefinition(identifier)) {
// throw new Error(`${identifier} is exist!`);
// }
if (!this.disableConflictCheck && this.registry.hasDefinition(identifier)) {
const def = this.registry.getDefinition(identifier);
if (!isPathEqual(definition.srcPath, def.srcPath)) {
throw new Error(`${identifier} path = ${definition.srcPath} is exist (${def.srcPath})!`);
}
}
this.registry.registerDefinition(identifier, definition);
this.createObjectDependencyTree(identifier, definition);
}
Expand Down
17 changes: 9 additions & 8 deletions packages/midway-core/src/context/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export class ContainerConfiguration implements IContainerConfiguration {
let loadDir;
if (pkg) {
if (this.namespace !== MAIN_MODULE_KEY) {
this.namespace = pkg.midwayNamespace ? pkg.midwayNamespace : pkg.name;
this.namespace = pkg.midwayNamespace !== undefined ? pkg.midwayNamespace : pkg.name;
}
if (pkg.main && !isSubDir) {
packageBaseDir = dirname(join(packageBaseDir, pkg.main));
Expand All @@ -103,10 +103,10 @@ export class ContainerConfiguration implements IContainerConfiguration {
}
debug('packageName => %s namespace => %s configuration file => %s.',
packageName, this.namespace, configuration ? true : false);
this.loadConfiguration(configuration, packageBaseDir);
this.loadConfiguration(configuration, packageBaseDir, cfgFile);
}

loadConfiguration(configuration, baseDir) {
loadConfiguration(configuration, baseDir, filePath?: string) {
if (configuration) {
// 可能导出多个
const configurationExports = this.getConfigurationExport(configuration);
Expand All @@ -121,7 +121,7 @@ export class ContainerConfiguration implements IContainerConfiguration {
this.namespace = configurationOptions.namespace;
}

if (this.container.containsConfiguration(this.namespace)) {
if (this.container.containsConfiguration(this.namespace) && this.namespace !== '') {
debug(`configuration ${this.namespace} exist than ignore.`);
return;
} else {
Expand All @@ -131,11 +131,12 @@ export class ContainerConfiguration implements IContainerConfiguration {
this.addImports(configurationOptions.imports, baseDir);
this.addImportObjects(configurationOptions.importObjects);
this.addImportConfigs(configurationOptions.importConfigs, baseDir);
this.bindConfigurationClass(configurationExport);
this.bindConfigurationClass(configurationExport, filePath);
}
}
} else {
if (this.container.containsConfiguration(this.namespace)) {

if (this.container.containsConfiguration(this.namespace) && this.namespace !== '') {
debug(`configuration ${this.namespace} exist than ignore.`);
return;
} else {
Expand All @@ -148,11 +149,11 @@ export class ContainerConfiguration implements IContainerConfiguration {
* 用于 ready 或者 stop 时处理 lifecycle 实现
* @param clzz configuration class
*/
bindConfigurationClass(clzz) {
bindConfigurationClass(clzz, filePath?: string) {
const clzzName = `${LIFECYCLE_IDENTIFIER_PREFIX}${classNamed(clzz.name)}`;
const id = generateProvideId(clzzName, this.namespace);
saveProviderId(id, clzz, true);
this.container.bind(id, clzz, { namespace: this.namespace });
this.container.bind(id, clzz, { namespace: this.namespace, srcPath: filePath });
saveModule(CONFIGURATION_KEY, clzz);
}

Expand Down
1 change: 1 addition & 0 deletions packages/midway-core/src/context/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export class Container extends BaseApplicationContext implements IContainer {

definition.path = target;
definition.id = identifier;
definition.srcPath = options ? options.srcPath : null;
definition.namespace = options ? options.namespace : '';

debug(`=> bind and build definition, id = [${definition.id}]`);
Expand Down
58 changes: 36 additions & 22 deletions packages/midway-core/src/context/midwayContainer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ export class MidwayContainer extends Container implements IMidwayContainer {
ctx = {};
readyBindModules: Map<string, Set<any>> = new Map();
configurationMap: Map<string, IContainerConfiguration> = new Map();
// 特殊处理,按照 main 加载
likeMainConfiguration: IContainerConfiguration[] = [];
configService: IConfigService;
environmentService: IEnvironmentService;

Expand Down Expand Up @@ -102,19 +104,10 @@ export class MidwayContainer extends Container implements IMidwayContainer {
continue;
}

const subDirs = containerConfiguration.getImportDirectory();
if (subDirs && subDirs.length > 0) {
debug('load configuration dir => %j, namespace => %s.',
subDirs, namespace);
this.loadDirectory({
...opts,
loadDir: subDirs,
namespace
});
}

this.registerImportObjects(containerConfiguration.getImportObjects(),
containerConfiguration.namespace);
this.loadConfiguration(opts, containerConfiguration);
}
for (const containerConfiguration of this.likeMainConfiguration) {
this.loadConfiguration(opts, containerConfiguration);
}
}

Expand Down Expand Up @@ -143,32 +136,32 @@ export class MidwayContainer extends Container implements IMidwayContainer {
debug(`binding file => ${file}, namespace => ${opts.namespace}`);
const exports = require(file);
// add module to set
this.bindClass(exports, opts.namespace);
this.bindClass(exports, opts.namespace, file);
}
}
}

bindClass(exports, namespace = '') {
bindClass(exports, namespace = '', filePath?: string) {
if (is.class(exports) || is.function(exports)) {
this.bindModule(exports, namespace);
this.bindModule(exports, namespace, filePath);
} else {
for (const m in exports) {
const module = exports[m];
if (is.class(module) || is.function(module)) {
this.bindModule(module, namespace);
this.bindModule(module, namespace, filePath);
}
}
}
}

protected bindModule(module, namespace = '') {
protected bindModule(module, namespace = '', filePath?: string) {
if (is.class(module)) {
const providerId = getProviderId(module);
if (providerId) {
this.bind(
generateProvideId(providerId, namespace),
module,
{ namespace }
{ namespace, srcPath: filePath }
);
} else {
// no provide or js class must be skip
Expand All @@ -190,7 +183,8 @@ export class MidwayContainer extends Container implements IMidwayContainer {
{
scope: info.scope,
isAutowire: info.isAutowire,
namespace
namespace,
srcPath: filePath
}
);
}
Expand Down Expand Up @@ -292,7 +286,7 @@ export class MidwayContainer extends Container implements IMidwayContainer {
if (prop.propertyName) {
Object.defineProperty(instance, prop.propertyName, {
get: () => getterHandler(prop.key, instance),
configurable: false,
configurable: true, // 继承对象有可能会有相同属性,这里需要配置成 true
enumerable: true,
});
}
Expand Down Expand Up @@ -337,7 +331,11 @@ export class MidwayContainer extends Container implements IMidwayContainer {
}

addConfiguration(configuration: IContainerConfiguration) {
this.configurationMap.set(configuration.namespace, configuration);
if (configuration.namespace === '') {
this.likeMainConfiguration.push(configuration);
} else {
this.configurationMap.set(configuration.namespace, configuration);
}
}

containsConfiguration(namespace: string): boolean {
Expand Down Expand Up @@ -410,6 +408,22 @@ export class MidwayContainer extends Container implements IMidwayContainer {
this.bindModule(pipelineFactory);
}

private loadConfiguration(opts: any, containerConfiguration: IContainerConfiguration) {
const subDirs = containerConfiguration.getImportDirectory();
if (subDirs && subDirs.length > 0) {
debug('load configuration dir => %j, namespace => %s.',
subDirs, containerConfiguration.namespace);
this.loadDirectory({
...opts,
loadDir: subDirs,
namespace: containerConfiguration.namespace
});
}

this.registerImportObjects(containerConfiguration.getImportObjects(),
containerConfiguration.namespace);
}

private async loadAndReadyLifeCycles() {
const cycles = listModule(CONFIGURATION_KEY);
debug('load lifecycle length => %s.', cycles && cycles.length);
Expand Down
22 changes: 16 additions & 6 deletions packages/midway-core/src/context/requestContainer.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { MidwayContainer } from './midwayContainer';
import { REQUEST_CTX_KEY } from '../interface';
import { parsePrefix } from '../common/util';
import { PIPELINE_IDENTIFIER } from '@midwayjs/decorator';

export class MidwayRequestContainer extends MidwayContainer {

Expand All @@ -24,9 +25,11 @@ export class MidwayRequestContainer extends MidwayContainer {
return this.registry.getObject(identifier);
}
const definition = this.applicationContext.registry.getDefinition(identifier);
if (definition && definition.isRequestScope()) {
// create object from applicationContext definition for requestScope
return this.getManagedResolverFactory().create({ definition, args });
if (definition) {
if (definition.isRequestScope() || definition.id === PIPELINE_IDENTIFIER) {
// create object from applicationContext definition for requestScope
return this.getManagedResolverFactory().create({ definition, args });
}
}

if (this.parent) {
Expand All @@ -46,9 +49,11 @@ export class MidwayRequestContainer extends MidwayContainer {
}

const definition = this.applicationContext.registry.getDefinition(identifier);
if (definition && definition.isRequestScope()) {
// create object from applicationContext definition for requestScope
return this.getManagedResolverFactory().createAsync({ definition, args });
if (definition) {
if (definition.isRequestScope() || definition.id === PIPELINE_IDENTIFIER) {
// create object from applicationContext definition for requestScope
return this.getManagedResolverFactory().createAsync({ definition, args });
}
}

if (this.parent) {
Expand All @@ -59,4 +64,9 @@ export class MidwayRequestContainer extends MidwayContainer {
initService() {
// do nothing
}

async ready() {
this.readied = true;
// ignore other things
}
}
1 change: 1 addition & 0 deletions packages/midway-core/src/definitions/functionDefinition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export class FunctionDefinition implements IObjectDefinition {
id: string;
name: string;
initMethod: string;
srcPath: string;
path: any;
properties: IProperties;
namespace = '';
Expand Down
1 change: 1 addition & 0 deletions packages/midway-core/src/definitions/objectDefinition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export class ObjectDefinition implements IObjectDefinition {
destroyMethod: string = null;
constructMethod: string = null;
constructorArgs: any[] = [];
srcPath: string;
path: any = null;
export: string = null;
dependsOn: ObjectIdentifier[] = [];
Expand Down
7 changes: 4 additions & 3 deletions packages/midway-core/src/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export interface IObjectDefinition {
initMethod: string;
destroyMethod: string;
constructMethod: string;
srcPath: string;
path: any;
export: string;
dependsOn: ObjectIdentifier[];
Expand Down Expand Up @@ -133,7 +134,7 @@ export interface IResource {
* IoC上下文抽象
*/
export interface IApplicationContext extends IObjectFactory {
disableClassConflict: boolean;
disableConflictCheck: boolean;
baseDir: string;
parent: IApplicationContext;
props: IProperties;
Expand Down Expand Up @@ -191,10 +192,10 @@ export interface IContainerConfiguration {
addImportObjects(importObjects: any[]);
addImportConfigs(importConfigs: string[], baseDir: string);
load(packageName: string);
loadConfiguration(configuration: IContainerConfiguration, baseDir: string);
loadConfiguration(configuration: IContainerConfiguration, baseDir: string, filePath?: string);
getImportDirectory(): string[];
getImportObjects(): any;
bindConfigurationClass(clzz: any);
bindConfigurationClass(clzz: any, filePath?: string);
}

export interface IMidwayContainer extends IContainer {
Expand Down
5 changes: 4 additions & 1 deletion packages/midway-core/src/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,19 @@ export class ContainerLoader {
applicationContext: MidwayContainer;
isTsMode;
preloadModules;
disableConflictCheck: boolean;

constructor({baseDir, isTsMode = true, preloadModules = []}) {
constructor({baseDir, isTsMode = true, preloadModules = [], disableConflictCheck = false}) {
this.baseDir = baseDir;
this.isTsMode = isTsMode;
this.preloadModules = preloadModules;
this.disableConflictCheck = disableConflictCheck;
}

initialize() {
this.pluginContext = new Container(this.baseDir);
this.applicationContext = new MidwayContainer(this.baseDir, undefined);
this.applicationContext.disableConflictCheck = this.disableConflictCheck;
this.applicationContext.registerObject('baseDir', this.baseDir);
this.applicationContext.registerObject('isTsMode', this.isTsMode);
}
Expand Down
3 changes: 3 additions & 0 deletions packages/midway-core/test/context/requestContainer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,9 @@ describe('/test/context/requestContainer.test.ts', () => {
appCtx.bind('tracer', Tracer);

const reqCtx1 = new RequestContainer({}, appCtx);
await reqCtx1.ready();
expect(reqCtx1.isReady).true;

reqCtx1.registerObject('tracer', new ChildTracer());
const reqCtx2 = new RequestContainer({}, appCtx);
reqCtx2.registerObject('tracer', new ChildTracer());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import { Configuration } from '@midwayjs/decorator';
imports: [
'../../midway-plugin-mock/src',
'../../midway-plugin-ok/src',
'../../midway-plugin-empty/src',
'../../midway-plugin-emptytwo/src',
'midway-plugin-mod',
'@midwayjs/midway-plugin-atmod',
'@midwayjs/midway-plugin-btmod',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ export class BaseService {
@Inject()
userManager;

@Inject('articleManager')
articleManager1;

@Inject('articleManagera')
articleManager2;

@Inject('@midway-plugin-mock')
articleManager;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"name": "midway-plugin-empty",
"main": "src/index.ts",
"midwayNamespace": ""
}
Loading

0 comments on commit 6064ecf

Please sign in to comment.