fix race condition opening file

This commit is contained in:
Ben Irvin 2022-12-12 21:01:29 +01:00
parent a94ba8d31e
commit aa22bd243d

View File

@ -1,6 +1,6 @@
import type { Readable } from 'stream'; import type { Readable } from 'stream';
import fs from 'fs'; import { createReadStream } from 'fs-extra';
import zip from 'zlib'; import zip from 'zlib';
import tar from 'tar'; import tar from 'tar';
import { keyBy } from 'lodash/fp'; import { keyBy } from 'lodash/fp';
@ -48,6 +48,8 @@ class LocalFileSourceProvider implements ISourceProvider {
options: ILocalFileSourceProviderOptions; options: ILocalFileSourceProviderOptions;
#filestream?: Readable;
constructor(options: ILocalFileSourceProviderOptions) { constructor(options: ILocalFileSourceProviderOptions) {
this.options = options; this.options = options;
@ -59,17 +61,13 @@ class LocalFileSourceProvider implements ISourceProvider {
} }
/** /**
* Pre flight checks regarding the provided options (making sure that the provided path is correct, etc...) * Pre flight checks regarding the provided options, opening the file
*/ */
bootstrap() { async bootstrap() {
const { path } = this.options.file; try {
const isValidBackupPath = fs.existsSync(path); this.#filestream = createReadStream(this.options.file.path);
} catch (e) {
// Check if the provided path exists throw new Error(`Could not read backup file path provided at "${this.options.file.path}"`);
if (!isValidBackupPath) {
throw new Error(
`Invalid backup file path provided. "${path}" does not exist on the filesystem.`
);
} }
} }
@ -104,10 +102,14 @@ class LocalFileSourceProvider implements ISourceProvider {
} }
#getBackupStream() { #getBackupStream() {
const { file, encryption, compression } = this.options; const { encryption, compression } = this.options;
const fileStream = fs.createReadStream(file.path); // This should be impossible as long as bootstrap was called first
const streams: StreamItemArray = [fileStream]; if (!this.#filestream) {
throw new Error('Could not read file stream');
}
const streams: StreamItemArray = [this.#filestream];
if (encryption.enabled && encryption.key) { if (encryption.enabled && encryption.key) {
streams.push(createDecryptionCipher(encryption.key)); streams.push(createDecryptionCipher(encryption.key));