Skip to content

Commit

Permalink
perf(Concurrency): Be sure that only one read or one write can be don…
Browse files Browse the repository at this point in the history
…e at the same time
  • Loading branch information
Belphemur committed Sep 9, 2022
1 parent daae2bb commit 1cf0038
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
6 changes: 4 additions & 2 deletions src/JsonDB.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,10 @@ export class JsonDB {
* @param dataPath path of the data to retrieve
*/
public getData(dataPath: string): Promise<any> {
const path = this.processDataPath(dataPath)
return this.retrieveData(path, false)
return this.lock.acquire(this.lockKey, async () => {
const path = this.processDataPath(dataPath)
return this.retrieveData(path, false)
});
}

/**
Expand Down
24 changes: 19 additions & 5 deletions test/06-concurrency.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ async function addData(db: JsonDB) {
}

describe('Concurrency', () => {
const db = new JsonDB(new Config('test-concurrent'));
const db = new JsonDB(new Config('test-concurrent-write'));
db.resetData({});
describe('Multi write', () => {
describe('Multi push', () => {
test('shouldn\'t corrupt the data', async () => {
let promiseList = [];
for (let i = 0; i < 10; i++) {
Expand All @@ -40,9 +40,23 @@ describe('Concurrency', () => {
})

});
describe('Mutli-read', () => {
test('should be able to set own adapter with config', async () => {

describe('Mutli getData', () => {
const db = new JsonDB(new Config('test-concurrent-read'));
db.resetData({});
test('should be blocking and wait for push to finish', async () => {
let counter = 1;
let record = {
strval: `value ${counter}`,
intval: counter
};
//We don't await the promise directly, to trigger a concurrent case
const pushPromise = db.push(`/test/key${counter}`, record, false);
const data = await db.getData("/test")

await pushPromise;

expect(data).toHaveProperty(`key${counter}`)
expect(data[`key${counter}`]).toEqual(record);
});
});
})

0 comments on commit 1cf0038

Please sign in to comment.