-
Notifications
You must be signed in to change notification settings - Fork 35
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
<!-- Thank you for your pull request. Please review below requirements. Bug fixes and new features should include tests and possibly benchmarks. Contributors guide: https://github.com/eggjs/egg/blob/master/CONTRIBUTING.md 感谢您贡献代码。请确认下列 checklist 的完成情况。 Bug 修复和新功能必须包含测试,必要时请附上性能测试。 Contributors guide: https://github.com/eggjs/egg/blob/master/CONTRIBUTING.md --> ##### Checklist <!-- Remove items that do not apply. For completed items, change [ ] to [x]. --> - [ ] `npm test` passes - [ ] tests and/or benchmarks are included - [ ] documentation is changed or added - [ ] commit message follows commit guidelines ##### Affected core subsystem(s) <!-- Provide affected core subsystem(s). --> ##### Description of change <!-- Provide a description of the change below this comment. --> <!-- - any feature? - close https://github.com/eggjs/egg/ISSUE_URL --> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Enhanced transaction management with the introduction of new lifecycle hooks and classes to ensure proper handling and isolation across various operations. - Added a new development dependency to support aspect-oriented programming techniques for transaction advice. - **Documentation** - Updated configuration files and added new SQL scripts to define database structures and queries. - **Tests** - Introduced comprehensive test cases for transaction management, covering various scenarios including successful and failed transactions. - Added a new test suite for `dal transaction runner` with assertions for different transaction scenarios. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
- Loading branch information
Showing
22 changed files
with
1,787 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
import assert from 'assert'; | ||
import { LifecycleHook, ModuleConfigHolder, Logger } from '@eggjs/tegg'; | ||
import { EggPrototype, EggPrototypeLifecycleContext } from '@eggjs/tegg-metadata'; | ||
import { PropagationType, TransactionMetaBuilder } from '@eggjs/tegg/transaction'; | ||
import { Pointcut } from '@eggjs/tegg/aop'; | ||
import { TransactionalAOP, TransactionalParams } from './TransactionalAOP'; | ||
import { MysqlDataSourceManager } from './MysqlDataSourceManager'; | ||
|
||
export class TransactionPrototypeHook implements LifecycleHook<EggPrototypeLifecycleContext, EggPrototype> { | ||
private readonly moduleConfigs: Record<string, ModuleConfigHolder>; | ||
private readonly logger: Logger; | ||
|
||
constructor(moduleConfigs: Record<string, ModuleConfigHolder>, logger: Logger) { | ||
this.moduleConfigs = moduleConfigs; | ||
this.logger = logger; | ||
} | ||
|
||
public async preCreate(ctx: EggPrototypeLifecycleContext): Promise<void> { | ||
const builder = new TransactionMetaBuilder(ctx.clazz); | ||
const transactionMetadataList = builder.build(); | ||
if (transactionMetadataList.length < 1) { | ||
return; | ||
} | ||
const moduleName = ctx.loadUnit.name; | ||
for (const transactionMetadata of transactionMetadataList) { | ||
const clazzName = `${moduleName}.${ctx.clazz.name}.${String(transactionMetadata.method)}`; | ||
const datasourceConfigs = (this.moduleConfigs[moduleName]?.config as any)?.dataSource || {}; | ||
|
||
let datasourceName: string; | ||
if (transactionMetadata.datasourceName) { | ||
assert(datasourceConfigs[transactionMetadata.datasourceName], `method ${clazzName} specified datasource ${transactionMetadata.datasourceName} not exists`); | ||
datasourceName = transactionMetadata.datasourceName; | ||
this.logger.info(`use datasource [${transactionMetadata.datasourceName}] for class ${clazzName}`); | ||
} else { | ||
const dataSources = Object.keys(datasourceConfigs); | ||
if (dataSources.length === 1) { | ||
datasourceName = dataSources[0]; | ||
} else { | ||
throw new Error(`method ${clazzName} not specified datasource, module ${moduleName} has multi datasource, should specify datasource name`); | ||
} | ||
this.logger.info(`use default datasource ${dataSources[0]} for class ${clazzName}`); | ||
} | ||
const adviceParams: TransactionalParams = { | ||
propagation: transactionMetadata.propagation, | ||
dataSourceGetter: () => { | ||
const mysqlDataSource = MysqlDataSourceManager.instance.get(moduleName, datasourceName); | ||
if (!mysqlDataSource) { | ||
throw new Error(`method ${clazzName} not found datasource ${datasourceName}`); | ||
} | ||
return mysqlDataSource; | ||
}, | ||
}; | ||
assert(adviceParams.propagation === PropagationType.REQUIRED, 'Transactional propagation only support required for now'); | ||
Pointcut(TransactionalAOP, { adviceParams })((ctx.clazz as any).prototype, transactionMetadata.method); | ||
} | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
import { Advice, AdviceContext, IAdvice } from '@eggjs/tegg/aop'; | ||
import { AccessLevel, EggProtoImplClass, ObjectInitType } from '@eggjs/tegg'; | ||
import { PropagationType } from '@eggjs/tegg/transaction'; | ||
import assert from 'node:assert'; | ||
import { MysqlDataSource } from '@eggjs/dal-runtime'; | ||
|
||
export interface TransactionalParams { | ||
propagation: PropagationType; | ||
dataSourceGetter: () => MysqlDataSource; | ||
} | ||
|
||
@Advice({ | ||
accessLevel: AccessLevel.PUBLIC, | ||
initType: ObjectInitType.SINGLETON, | ||
}) | ||
export class TransactionalAOP implements IAdvice<EggProtoImplClass, TransactionalParams> { | ||
public async around(ctx: AdviceContext<EggProtoImplClass, TransactionalParams>, next: () => Promise<any>): Promise<void> { | ||
const { propagation, dataSourceGetter } = ctx.adviceParams!; | ||
const dataSource = dataSourceGetter(); | ||
assert(propagation === PropagationType.REQUIRED, '事务注解目前只支持 REQUIRED 机制'); | ||
return await dataSource.beginTransactionScope(next); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
33 changes: 33 additions & 0 deletions
33
plugin/dal/test/fixtures/apps/dal-app/modules/dal/FooService.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
import { AccessLevel, Inject, SingletonProto } from '@eggjs/tegg'; | ||
import { Transactional } from '@eggjs/tegg/transaction'; | ||
import FooDAO from './dal/dao/FooDAO'; | ||
import { Foo } from './Foo'; | ||
|
||
@SingletonProto({ | ||
accessLevel: AccessLevel.PUBLIC, | ||
}) | ||
export class FooService { | ||
@Inject() | ||
private readonly fooDAO: FooDAO; | ||
|
||
@Transactional() | ||
async succeedTransaction() { | ||
const foo = Foo.buildObj(); | ||
foo.name = 'insert_succeed_transaction_1'; | ||
const foo2 = Foo.buildObj(); | ||
foo2.name = 'insert_succeed_transaction_2'; | ||
await this.fooDAO.insert(foo); | ||
await this.fooDAO.insert(foo2); | ||
} | ||
|
||
@Transactional() | ||
async failedTransaction() { | ||
const foo = Foo.buildObj(); | ||
foo.name = 'insert_failed_transaction_1'; | ||
const foo2 = Foo.buildObj(); | ||
foo2.name = 'insert_failed_transaction_2'; | ||
await this.fooDAO.insert(foo); | ||
await this.fooDAO.insert(foo2); | ||
throw new Error('mock error'); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,89 @@ | ||
import assert from 'assert'; | ||
import path from 'path'; | ||
import mm, { MockApplication } from 'egg-mock'; | ||
import FooDAO from './fixtures/apps/dal-app/modules/dal/dal/dao/FooDAO'; | ||
import { FooService } from './fixtures/apps/dal-app/modules/dal/FooService'; | ||
import { MysqlDataSourceManager } from '../lib/MysqlDataSourceManager'; | ||
|
||
describe('plugin/dal/test/transaction.test.ts', () => { | ||
let app: MockApplication; | ||
|
||
afterEach(async () => { | ||
mm.restore(); | ||
}); | ||
|
||
before(async () => { | ||
mm(process.env, 'EGG_TYPESCRIPT', true); | ||
mm(process, 'cwd', () => { | ||
return path.join(__dirname, '../'); | ||
}); | ||
app = mm.app({ | ||
baseDir: path.join(__dirname, './fixtures/apps/dal-app'), | ||
framework: require.resolve('egg'), | ||
}); | ||
await app.ready(); | ||
}); | ||
|
||
afterEach(async () => { | ||
const dataSource = MysqlDataSourceManager.instance.get('dal', 'foo')!; | ||
await dataSource.query('delete from egg_foo;'); | ||
}); | ||
|
||
after(() => { | ||
return app.close(); | ||
}); | ||
|
||
describe('succeed transaction', () => { | ||
it('should commit', async () => { | ||
await app.mockModuleContextScope(async () => { | ||
const fooService = await app.getEggObject(FooService); | ||
const fooDao = await app.getEggObject(FooDAO); | ||
await fooService.succeedTransaction(); | ||
const foo1 = await fooDao.findByName('insert_succeed_transaction_1'); | ||
const foo2 = await fooDao.findByName('insert_succeed_transaction_2'); | ||
assert(foo1.length); | ||
assert(foo2.length); | ||
}); | ||
}); | ||
}); | ||
|
||
describe('failed transaction', () => { | ||
it('should rollback', async () => { | ||
await app.mockModuleContextScope(async () => { | ||
const fooService = await app.getEggObject(FooService); | ||
const fooDao = await app.getEggObject(FooDAO); | ||
await assert.rejects(async () => { | ||
await fooService.failedTransaction(); | ||
}); | ||
const foo1 = await fooDao.findByName('insert_failed_transaction_1'); | ||
const foo2 = await fooDao.findByName('insert_failed_transaction_2'); | ||
assert(!foo1.length); | ||
assert(!foo2.length); | ||
}); | ||
}); | ||
}); | ||
|
||
describe('transaction should be isolated', () => { | ||
it('should rollback', async () => { | ||
await app.mockModuleContextScope(async () => { | ||
const fooService = await app.getEggObject(FooService); | ||
const fooDao = await app.getEggObject(FooDAO); | ||
const [ failedRes, succeedRes ] = await Promise.allSettled([ | ||
fooService.failedTransaction(), | ||
fooService.succeedTransaction(), | ||
]); | ||
assert.equal(failedRes.status, 'rejected'); | ||
assert.equal(succeedRes.status, 'fulfilled'); | ||
const foo1 = await fooDao.findByName('insert_failed_transaction_1'); | ||
const foo2 = await fooDao.findByName('insert_failed_transaction_2'); | ||
assert(!foo1.length); | ||
assert(!foo2.length); | ||
|
||
const foo3 = await fooDao.findByName('insert_succeed_transaction_1'); | ||
const foo4 = await fooDao.findByName('insert_succeed_transaction_2'); | ||
assert(foo3.length); | ||
assert(foo4.length); | ||
}); | ||
}); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.