-
Notifications
You must be signed in to change notification settings - Fork 22
feat: automated test isolation #952
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
Open
BobdenOs
wants to merge
24
commits into
main
Choose a base branch
from
feat/test-isolation
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 7 commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
48ca5ad
Initial isolation move to DatabaseService
BobdenOs 1ad0f7a
initial working state
BobdenOs 00fff1b
Switch to cds.deploy.data
BobdenOs c0631e2
Merge branch 'main' of https://github.com/cap-js/cds-dbs into feat/te…
BobdenOs fb00d34
Make failing read only depoyment more rebust
BobdenOs 412ac28
Merge branch 'main' of https://github.com/cap-js/cds-dbs into feat/te…
BobdenOs 5ff22f1
Migrate isolation logic to its own file
BobdenOs 30f543c
Merge branch 'main' of https://github.com/cap-js/cds-dbs into feat/te…
BobdenOs 01eae6e
When deployment failed make sure to clean up
BobdenOs c357473
Merge branch 'main' into feat/test-isolation
BobdenOs 11c7a25
Merge branch 'main' of https://github.com/cap-js/cds-dbs into feat/te…
BobdenOs da596ac
Fix complex parallel write requests
BobdenOs 0d58e1c
Reduce hanging test isolation steps
BobdenOs b060f78
Merge branch 'main' into feat/test-isolation
BobdenOs 2f80c82
Merge branch 'main' into feat/test-isolation
BobdenOs 6817349
Increase deployment timeout just in case
BobdenOs 78c01c1
Just trying things as it can't be debugged
BobdenOs 8aee8fe
Provide database service context again
BobdenOs 222b4af
Apply suggestions from code review
BobdenOs 4f2bd35
Merge branch 'main' of https://github.com/cap-js/cds-dbs into feat/te…
BobdenOs e61f009
Merge branch 'main' of https://github.com/cap-js/cds-dbs into feat/te…
BobdenOs 523ea0d
Merge branch 'main' of https://github.com/cap-js/cds-dbs into feat/te…
BobdenOs f2f6b9a
linting
BobdenOs b798a4d
Merge branch 'main' into feat/test-isolation
BobdenOs File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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,195 @@ | ||
const cds = require('@sap/cds') | ||
|
||
function getIsolate() { | ||
const { options = {} } = cds | ||
const fts = cds.requires.toggles && cds.resolve(cds.env.features.folders) | ||
const src = [options.from || '*', ...(fts || [])] | ||
|
||
const isolation = process.env.TRAVIS_JOB_ID || process.env.GITHUB_RUN_ID || require('os').userInfo().username || 'test_db' | ||
const srchash = hash([cds.root, ...src.flat()].join('/')) | ||
|
||
return { | ||
src, | ||
// Create one database for each overall test execution | ||
database: 'D' + hash(isolation), | ||
// Create one tenant for each model source definition | ||
tenant: 'T' + srchash, | ||
// Track source definition hash | ||
source: srchash, | ||
} | ||
} | ||
|
||
const hash = str => { | ||
const { createHash } = require('crypto') | ||
const hash = createHash('sha1') | ||
hash.update(str) | ||
return hash.digest('hex') | ||
} | ||
|
||
async function beforeWrite(dbs, isolate) { | ||
const { ten } = dbs | ||
const modified = isolate.modified = {} | ||
ten.before(['*'], async (req) => { | ||
if ( | ||
!req.query || | ||
req.query?.SELECT || | ||
(typeof req.query === 'string' && /^(BEGIN|COMMIT|ROLLBACK|SELECT)/i.test(req.query)) | ||
) return // Ignore reading requests | ||
if (req.target) modified[req.target.name] = true | ||
if (req.tx._isolating) return req.tx._isolating | ||
if (ten._writeable) return | ||
|
||
// Add modification tracking for deep-queries internal calls | ||
for (const fn of ['onSIMPLE', 'onUPDATE', 'onINSERT']) { | ||
const org = ten[fn] | ||
ten[fn] = function (req) { | ||
if (req.query?.target) modified[req.query.target.name] = true | ||
BobdenOs marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return org.apply(this, arguments) | ||
} | ||
} | ||
|
||
ten._writeable = true | ||
return (req.tx._isolating = req.tx.commit() | ||
.then(() => getWriteTenant(dbs, isolate)) | ||
.then(() => req.tx.begin())) | ||
}) | ||
} | ||
|
||
async function deploy(dbs, isolate) { | ||
console.log('DEPLOYING:', isolate.tenant) | ||
const { ten } = dbs | ||
await ten.tx(async () => { | ||
try { | ||
const src = isolate.src | ||
const { options = {} } = cds | ||
const m = await cds.load(src, options).then(cds.minify) | ||
// options.schema_evolution = 'auto' | ||
await cds.deploy(m).to(ten, options) | ||
} catch (err) { | ||
if (err.code === 'MODEL_NOT_FOUND' || err.code === 288) return | ||
throw err | ||
} | ||
}) | ||
} | ||
|
||
async function getReadTenant(dbs, isolate) { | ||
const { dat, ten } = dbs | ||
const { schemas } = dat.entities() | ||
const deployTimeout = 120 // seconds | ||
|
||
let isnew = false | ||
try { | ||
await dat.run(cds.ql.CREATE('schemas')).catch(() => { }) | ||
await dat.tx(async tx => { | ||
await tx.run(DELETE.from(schemas).where`tenant=${isolate.tenant} and available=${false} and seconds_between(started, $now) > ${deployTimeout}`) | ||
// If insert works the schema does not yet exist and this client has won the race and can deploy the contents | ||
await tx.run(INSERT({ tenant: isolate.tenant, source: isolate.source, available: false, started: new Date() }).into(schemas)) | ||
isnew = true | ||
}) | ||
} catch (err) { | ||
const query = cds.ql`SELECT FROM ${schemas} { | ||
(SELECT count(1) FROM ${schemas} WHERE tenant=${isolate.tenant} and available=${false} and seconds_between(started, $now) < ${deployTimeout}) as progress, | ||
(SELECT count(1) FROM ${schemas} WHERE tenant=${isolate.tenant} and available=${true}) as available, | ||
}` | ||
// If the schema already exists wait for the row to be updated with available=true | ||
await dat.tx(async tx => { | ||
let available = 0 | ||
let progress = 0 | ||
while (progress && !available) [{ progress, available }] = await tx.run(query) | ||
}) | ||
} | ||
|
||
await ten.database(isolate) | ||
await ten.tenant(isolate) | ||
|
||
if (isnew) { | ||
let err | ||
await deploy(dbs, isolate).catch(e => { err = e }) | ||
await dat.tx(async tx => { | ||
if (err) { | ||
await tx.run(DELETE(schemas).where`tenant=${isolate.tenant}`) | ||
} else { | ||
await tx.run(UPDATE(schemas).where`tenant=${isolate.tenant}`.with({ available: true })) | ||
} | ||
}) | ||
if (err) throw err | ||
} | ||
} | ||
|
||
async function getWriteTenant(dbs, isolate) { | ||
const { ten, dat } = dbs | ||
const { schemas } = dat.entities() | ||
// await this.database(isolate) | ||
|
||
let isnew = false | ||
await dat.tx(async tx => { | ||
const available = await tx.run(SELECT.from(schemas).where`tenant!=${isolate.tenant} and source=${isolate.source} and available=${true}`.forUpdate().limit(1)) | ||
if (available.length) { | ||
const tenant = isolate.tenant = available[0].tenant | ||
await tx.run(UPDATE(schemas).where`tenant=${tenant}`.with({ available: false, started: new Date() })) | ||
} else { | ||
isolate.tenant = 'T' + cds.utils.uuid() | ||
await tx.run(INSERT({ tenant: isolate.tenant, source: isolate.source, available: false, started: new Date() }).into(schemas)) | ||
isnew = true | ||
} | ||
}) | ||
|
||
console.log('USING:', isolate.tenant) | ||
|
||
await ten.database(isolate) | ||
await ten.tenant(isolate) | ||
|
||
if (isnew) await deploy(dbs, isolate) | ||
|
||
// Release schema for follow up test runs | ||
cds.on('shutdown', async () => { | ||
try { | ||
try { | ||
// Clean tenant entities | ||
await ten.tx(async tx => { | ||
await tx.begin() | ||
for (const entity in isolate.modified) { | ||
const query = DELETE(entity).where`true=true` | ||
if (!query.target._unresolved) await tx.onSIMPLE({ query }) // Skip deep delete | ||
} | ||
// UPSERT all data sources again | ||
await cds.deploy.data(tx, tx.model, { schema_evolution: 'auto' }) | ||
}) | ||
|
||
await dat.run(UPDATE(schemas).where`tenant=${isolate.tenant}`.with({ available: true })) | ||
} catch (err) { | ||
// Try to cleanup broken tenant isolation | ||
await ten.tenant(isolate, true) | ||
// Remove cleaned up schema | ||
await dat.run(DELETE(schemas).where`tenant=${isolate.tenant}`) | ||
} | ||
} catch (err) { | ||
// if an shutdown handler throws an error it goes into an infinite loop | ||
console.error(err) | ||
} | ||
}) | ||
} | ||
|
||
module.exports = async function (db) { | ||
const isolate = getIsolate() | ||
// Just deploy when the database doesn't have isolation implementations available | ||
if (typeof db.database !== 'function' || typeof db.tenant !== 'function') return deploy({ ten: db }, isolate) | ||
|
||
const dbs = { | ||
ten: db, | ||
sys: await cds.connect.to('db_sys', { ...cds.requires.db, isolate: false }), | ||
dat: await cds.connect.to('db_dat', { | ||
...cds.requires.db, isolate: false, | ||
model: await cds.load(cds.utils.path.join(__dirname, 'database')) | ||
}), | ||
} | ||
|
||
await dbs.dat.database(isolate) | ||
|
||
await getReadTenant(dbs, isolate) | ||
|
||
await db.database(isolate) | ||
await db.tenant(isolate) | ||
|
||
beforeWrite(dbs, isolate) | ||
} |
This file contains hidden or 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 |
---|---|---|
|
@@ -7,8 +7,14 @@ const cds = require('@sap/cds') | |
|
||
class DatabaseService extends cds.Service { | ||
|
||
init() { | ||
async init() { | ||
cds.on('shutdown', () => this.disconnect()) | ||
if (this.options.isolate !== false && ( | ||
Object.getOwnPropertyDescriptor(cds, 'test') || this.options.isolate | ||
)) { | ||
Comment on lines
+12
to
+14
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Just to ensure that I understand in which scenarios the new isolation happens (and how breaking this is)...
Is this correct? |
||
const isolation = require('./DatabaseIsolation') | ||
await isolation(this) | ||
} | ||
return super.init() | ||
} | ||
|
||
|
@@ -47,7 +53,7 @@ class DatabaseService extends cds.Service { | |
* transaction with `BEGIN` | ||
* @returns this | ||
*/ | ||
async begin (min) { | ||
async begin(min) { | ||
// We expect tx.begin() being called for an txed db service | ||
const ctx = this.context | ||
|
||
|
@@ -129,9 +135,9 @@ class DatabaseService extends cds.Service { | |
} | ||
|
||
// REVISIT: should happen automatically after a configurable time | ||
async disconnect (tenant) { | ||
async disconnect(tenant) { | ||
const tenants = tenant ? [tenant] : Object.keys(this.pools) | ||
await Promise.all (tenants.map (async t => { | ||
await Promise.all(tenants.map(async t => { | ||
const pool = this.pools[t]; if (!pool) return | ||
delete this.pools[t] | ||
await pool.drain() | ||
|
This file contains hidden or 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,6 @@ | ||
entity schemas { | ||
key tenant : String; | ||
source : String; | ||
available : Boolean; | ||
started : Timestamp; | ||
} |
This file contains hidden or 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 hidden or 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 hidden or 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 @@ | ||
[{"ID":1,"title":"1"},{"ID":2,"title":"2"},{"ID":3,"title":"3"},{"ID":4,"title":"4"}] |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.