Skip to content

Commit

Permalink
#2 Initial version.
Browse files Browse the repository at this point in the history
  • Loading branch information
Mamoru1234 committed Apr 8, 2018
1 parent 50cc3f5 commit 5617ea4
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion src/main/caches/FSContentCache.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import Promise from 'bluebird';
import {createReadStream, createWriteStream, existsSync} from 'fs';
import {has} from 'lodash';
import {join} from 'path';
import {AutoReleaseSemaphore} from '../utils/Semaphore';
import {ContentCache} from './ContentCache';

export class FSContentCache implements ContentCache {
// FIXME implement file locks
private _locks: {[key: string]: AutoReleaseSemaphore} = {};

constructor(private _cacheDir: string) {}

Expand All @@ -12,11 +16,26 @@ export class FSContentCache implements ContentCache {
}

public getItem(itemKey: string): Promise<NodeJS.ReadableStream> {
if (has(this._locks, itemKey)) {
return this._locks[itemKey].acquire(() => {
return Promise.resolve(createReadStream(this._getItemPath(itemKey)));
});
}
return Promise.resolve(createReadStream(this._getItemPath(itemKey)));
}

public setItem(itemKey: string): Promise<NodeJS.WritableStream> {
return Promise.resolve(createWriteStream(this._getItemPath(itemKey)));
if (has(this._locks, itemKey)) {
throw new Error('How you get to this path?');
}
this._locks[itemKey] = new AutoReleaseSemaphore(1);
const writeStream = createWriteStream(this._getItemPath(itemKey));
this._locks[itemKey].acquire(() => new Promise((res) => {
writeStream.on('finish', () => {
res();
});
}));
return Promise.resolve(writeStream);
}

private _getItemPath(itemKey: string): string {
Expand Down

0 comments on commit 5617ea4

Please sign in to comment.