Skip to content

Commit

Permalink
add mutex to file database to avoid race conditions
Browse files Browse the repository at this point in the history
  • Loading branch information
TheKhanj committed Jan 5, 2024
1 parent 6775444 commit 7662b41
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
13 changes: 11 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "moxyjs",
"version": "0.0.10",
"version": "0.0.11",
"description": "Distributed transparent proxy with traffic control facilities",
"author": "Pooyan Khanjankhani <[email protected]>",
"license": "MIT",
Expand Down Expand Up @@ -33,6 +33,7 @@
"@nestjs/common": "^10.2.10",
"@nestjs/core": "^10.2.10",
"@nestjs/mongoose": "^10.0.2",
"async-mutex": "^0.4.0",
"minimist": "^1.2.8",
"mongoose": "^8.0.2",
"typescript": "^5.3.2",
Expand Down
8 changes: 7 additions & 1 deletion src/database/database.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as fs from "fs";
import * as fsp from "fs/promises";
import { Mutex } from "async-mutex";
import { promisify } from "util";
import { Inject, Injectable, Logger } from "@nestjs/common";

Expand Down Expand Up @@ -41,6 +42,8 @@ export class MemoryDatabase implements Database {
type FileContent = IUserStats[];

export class FileDatabase implements Database {
private readonly mutex = new Mutex();

public constructor(private readonly filePath: string) {}

public async get(key: string): Promise<UserStats> {
Expand Down Expand Up @@ -77,7 +80,10 @@ export class FileDatabase implements Database {
}

private async write(content: FileContent) {
await fsp.writeFile(this.filePath, JSON.stringify(content, null, 2));
const release = await this.mutex.acquire();
await fsp
.writeFile(this.filePath, JSON.stringify(content, null, 2))
.finally(() => release());
}

private async getAll(): Promise<FileContent> {
Expand Down

0 comments on commit 7662b41

Please sign in to comment.