Skip to content

Commit

Permalink
refactor: lock
Browse files Browse the repository at this point in the history
  • Loading branch information
kukhariev committed Sep 1, 2021
1 parent b36495a commit 22c2955
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 3 deletions.
5 changes: 5 additions & 0 deletions packages/core/src/handlers/base-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,11 @@ export abstract class BaseHandler<TFile extends Readonly<File>>
if ('status' in file && file.status) {
this.log('[%s]: %s', file.status, file.name);
this.listenerCount(file.status) && this.emit(file.status, file);
if (file.lockedBy instanceof Function) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
file.lockedBy();
return;
}
if (file.status === 'completed') {
req['_body'] = true;
req['body'] = file;
Expand Down
9 changes: 6 additions & 3 deletions packages/core/src/storages/disk-storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import { LocalMetaStorage, LocalMetaStorageOptions } from './local-meta-storage'
const INVALID_OFFSET = -1;

export interface DiskFile extends File {
lock: (lockFn: () => any) => Promise<any>;
move: (dest: string) => Promise<any>;
copy: (dest: string) => Promise<any>;
delete: () => Promise<any>;
Expand Down Expand Up @@ -68,7 +67,10 @@ export class DiskStorage extends BaseStorage<DiskFile> {

buildCompletedFile(file: DiskFile): DiskFile {
const completed = { ...file };
completed.lock = async lockFn => Promise.resolve('TODO:');
completed.lock = async lockFn => {
completed.lockedBy = lockFn;
return Promise.resolve(completed.lockedBy);
};
completed.delete = () => this.delete(file.name);
completed.hash = (algorithm?: 'sha1' | 'md5', encoding?: 'hex' | 'base64') =>
fileChecksum(this.getFilePath(file.name), algorithm, encoding);
Expand All @@ -91,8 +93,9 @@ export class DiskStorage extends BaseStorage<DiskFile> {

async write(part: FilePart): Promise<DiskFile> {
const file = await this.getMeta(part.name);
await this.checkIfExpired(file);
if (file.status === 'completed') return file;
if (file.lockedBy) return file;
await this.checkIfExpired(file);
if (!isValidPart(part, file)) return fail(ERRORS.FILE_CONFLICT);
try {
file.bytesWritten = await this._write({ ...file, ...part });
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/storages/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ export class File implements FileInit {
userId?;
expiredAt?: string | Date | number;
createdAt?: string | Date | number;
lock!: (onLocked: () => any) => Promise<any>;
lockedBy?: (() => any) | unknown;

constructor({ metadata = {}, originalName, contentType, size, userId }: FileInit) {
this.metadata = metadata;
Expand Down

0 comments on commit 22c2955

Please sign in to comment.