Skip to content

Commit

Permalink
WIP - #305 locking
Browse files Browse the repository at this point in the history
  • Loading branch information
tegefaulkes committed Feb 21, 2022
1 parent 04b39ff commit 748ff8e
Show file tree
Hide file tree
Showing 4 changed files with 145 additions and 108 deletions.
22 changes: 13 additions & 9 deletions src/vaults/VaultInternal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import type { NodeConnectionManager } from '../nodes';
import type { ResourceAcquire } from '../utils';
import path from 'path';
import git from 'isomorphic-git';
import { Mutex } from 'async-mutex';
import Logger from '@matrixai/logger';
import {
CreateDestroyStartStop,
Expand Down Expand Up @@ -189,11 +188,16 @@ class VaultInternal {
protected vaultsNamesDomain: DBDomain;
protected efs: EncryptedFS;
protected efsVault: EncryptedFS;
protected _lock: Mutex = new Mutex();
protected _lock: RWLock = new RWLock();

public lock: ResourceAcquire<Mutex> = async () => {
const release = await this._lock.acquire();
return [async () => release(), this._lock];
public lockRead: ResourceAcquire = async () => {
const release = await this._lock.acquireRead();
return [async () => release()];
};

public lockWrite: ResourceAcquire = async () => {
const release = await this._lock.acquireWrite();
return [async () => release()];
};

constructor({
Expand Down Expand Up @@ -381,7 +385,7 @@ class VaultInternal {

@ready(new vaultsErrors.ErrorVaultNotRunning())
public async readF<T>(f: (fs: FileSystemReadable) => Promise<T>): Promise<T> {
return withF([this.lock], async () => {
return withF([this.lockRead], async () => {
return await f(this.efsVault);
});
}
Expand All @@ -391,7 +395,7 @@ class VaultInternal {
g: (fs: FileSystemReadable) => AsyncGenerator<T, TReturn, TNext>,
): AsyncGenerator<T, TReturn, TNext> {
const efsVault = this.efsVault;
return withG([this.lock], async function* () {
return withG([this.lockRead], async function* () {
return yield* g(efsVault);
});
}
Expand All @@ -413,7 +417,7 @@ class VaultInternal {
// Mirrored vaults are immutable
throw new vaultsErrors.ErrorVaultImmutable();
}
return withF([this.lock], async () => {
return withF([this.lockWrite], async () => {
await this.db.put(
this.vaultMetadataDbDomain,
VaultInternal.dirtyKey,
Expand Down Expand Up @@ -585,7 +589,7 @@ class VaultInternal {
const efsVault = this.efsVault;
const db = this.db;
const vaultDbDomain = this.vaultMetadataDbDomain;
return withG([this.lock], async function* () {
return withG([this.lockWrite], async function* () {
if ((await db.get(vaultDbDomain, VaultInternal.remoteKey)) != null) {
// Mirrored vaults are immutable
throw new vaultsErrors.ErrorVaultImmutable();
Expand Down
Loading

0 comments on commit 748ff8e

Please sign in to comment.