/* eslint-disable no-console */ import { Readable } from "stream"; // import TempFileService, { LocalFile } from "./TempFileService.js"; import Inject, { ServiceProvider } from "@entity-access/entity-access/dist/di/di.js"; import SocialMailContext from "../model/SocialMailContext.js"; import CryptoService from "../services/CryptoService.js"; import { globalServices } from "../../globalServices.js"; import FileTagService from "../services/tags/FileTagService.js"; import AppFile from "../model/entities/AppFile.js"; import sleep from "../../common/sleep.js"; import EntityAccessError from "@entity-access/entity-access/dist/common/EntityAccessError.js"; import GZip from "./compression/gz.js"; import { FileType } from "../../common/FileType.js"; import { areFilesEqual } from "../../common/FileApi.js"; import type FileContent from "../model/entities/FileContent.js"; import AVService from "./volume/av/AVService.js"; import { LocalFile } from "@entity-access/server-pages/dist/core/LocalFile.js"; import { SessionUser } from "@entity-access/server-pages/dist/core/SessionUser.js"; import DbLockService from "../services/db-lock/DbLockService.js"; import DateTime from "@entity-access/entity-access/dist/types/DateTime.js"; import DiskCacheService from "../services/cache/DiskCacheService.js"; import { tempDiskCache } from "./tempDiskCache.js"; import { globalEnv } from "../../common/globalEnv.js"; export type ISourceFile = { sourceUrl: string, file: never } | { sourceUrl: never, file: LocalFile }; export default abstract class BaseStorage { @Inject protected cryptoService: CryptoService; @Inject private tagService: FileTagService; @Inject private dbLockService: DbLockService; @Inject private diskCache: DiskCacheService; abstract verify(): Promise; abstract createFile(cloudPath: string, file: LocalFile): Promise; abstract deleteFile(cloudPath: string): Promise; abstract streamFile(cloudPath: string): Promise<{ contentType: string, stream: Readable }>; async getContentHash(file: LocalFile) { return await this.cryptoService.hashBuffer(file.openRead()); } async saveFileContent(file: LocalFile, scope?:ServiceProvider, compress: boolean = FileType.canBeCompressed(file)) { const disposeScope = scope; scope ??= globalServices.createScope(); try { const contentHash = await this.cryptoService.hashBuffer(file.openRead()); // avoid video if above 200MB if (/audio|video/i.test(file.contentType)) { if (file.contentSize < 200*1024*1024) { await AVService.scan(file, contentHash); } } else { await AVService.scan(file, contentHash); } const db = scope.resolve(SocialMailContext); // db.raiseEvents = false; db.verifyFilters = false; const compression = compress ? "gz" : void 0; const { contentType, contentSize } = file; const fc = await this.getFileContent(db, file, { compression, contentType, contentSize, contentHash}); if(!fc.cloudPath) { const cloudPath = `files/${fc.fileContentID}/${fc.contentHash}`; // first we will save he file to cloud if (compression === "gz") { using tfs = tempDiskCache.newFolder("gz-comp"); const zipped = await tfs.createFrom("file.zip", GZip.zip(file.openRead()), "application/octet-stream"); await this.createFile(cloudPath, zipped); } else { await this.createFile(cloudPath, file); } // then we will update cloud path // so readers will understand that the file isn't saved yet. // also getFileContent can wait for desired lock time // before checking for hash collision fc.cloudPath = cloudPath; fc.compression = compression; await db.fileContents.where(fc, (x, p) => x.fileContentID === p.fileContentID) .update(fc, (x, p) => ({ cloudPath: p.cloudPath, compression: p.compression })); } return fc; } finally { if (!disposeScope) { scope.dispose(); } } } async downloadFile({ cloudPath, contentHash, compression}: FileContent) { return await this.diskCache.getOrCreateAsync(cloudPath, async (cf) => { let { stream } = await this.streamFile(cloudPath); if(compression) { switch(compression) { case "gz": stream = GZip.unzipStream(stream); break; default: throw new EntityAccessError(`Unknown compression algorithm ${compression}`); } } await cf.writeAll(stream); } ); // const linkedFile = await this.diskCache.link(originalFile, originalFile.fileName, originalFile.contentType); // return linkedFile; // const cachedPath = path.join(cachePath , contentHash); // const { dir } = path.parse(cachedPath); // if (!existsSync(dir)) { // mkdirSync(dir, { recursive: true }); // } // let tries = 10; // while (tries > 0) { // using lock = await LockFile.lock(cloudPath); // if (existsSync(cachedPath)) { // break; // } // const { stream } = await this.streamFile(cloudPath); // try { // if(!compression) { // await fsp.writeFile(cachedPath, stream); // } else { // if (compression !== "gz") { // throw new EntityAccessError(`Unknown compression algorithm ${compression}`); // } // await GZip.unzipFile(stream, cachedPath); // } // break; // } catch (error) { // // multiple file write might throw an exception.. // await sleep(1000); // tries--; // if (tries===0) { // throw new EntityAccessError(`Failed to write file due to error ${error.stack ?? error}`); // } // } // } // return cachedPath; } async updateFile(appFile: AppFile, file: LocalFile) { const fc = await this.saveFileContent(file, void 0, FileType.canBeCompressed(file)); appFile.fileContentID = fc.fileContentID; } async saveFile(file: LocalFile, extra?: Partial) { using scope = ServiceProvider.createScope(this); scope.resolve(SessionUser).roles ??= ["Administrator"]; const db = scope.resolve(SocialMailContext); db.verifyFilters = false; const fileContent = await this.saveFileContent(file, scope , FileType.canBeCompressed(file)); const name = extra?.name ?? file.fileName; const parentID = extra?.parentID; let appFile: AppFile; if (parentID && name) { appFile = await db.appFiles .where({ parentID, name }, (x, p) => x.parentID === p.parentID && x.name === p.name) .include((x) => x.tags) .first(); } // get tags... const tags = await this.tagService.getTags(file.fileName, file.contentType); // check if file exists under the given parent appFile ??= db.appFiles.add({ name, tags: [] }); appFile.fileContent = fileContent; appFile.fileContentID = fileContent.fileContentID; if (extra) { extra.fileContentID = fileContent.fileContentID; extra.fileContent = fileContent; } appFile.fileSize = file.contentSize; appFile.contentType = file.contentType; appFile.isDeleted = false; if (extra) { for (const key in extra) { if (Object.hasOwn(extra, key)) { const element = extra[key]; appFile[key] = element; } } } const fileTags = appFile.tags ??=[]; for (const { tagID } of tags) { if (fileTags.find((t) => t.tagID === tagID)) { continue; } fileTags.push(db.appFileTags.add({ tagID })); } await db.saveChanges(); return appFile; } private async getFileContent( db: SocialMailContext, file: LocalFile, { contentSize, contentHash, contentType, compression}) { /** * The following logic detects existing file content by matching hash, * however there is a high probability that same file is being saved by * two different instances, and cloudPath may not be set till the file * is saved remotely. * * This will create two problems, * 1. If one file isn't saved but cloud path is saved correctly, * it will lead to incorrect assumption that file was saved to the cloud * and all subsequent save operations will be ignored. * 2. If the file is partially saved, and partially loaded, and in * worst case scenario, hash matches, two files with different * content might be saved. When save is successful, hash will * be different. * * Solution: * 1. To avoid this issue, saving of file content will not set * cloudPath field till the file is saved successfully to the could. * 2. We will wait for upto 5 seconds, for 60 times, that is 5 minutes * before we can conclude that hash collision has occurred. * 3. This has a side effect one large files would be identified as * hash collision even if the content is same, that is because * checking of hash will wait only for 5 minutes. */ for(let n = 0; n<60; n++) { const fileContents = await db.fileContents .where({ contentHash}, (x, p) => x.contentHash === p.contentHash) .toArray(); if (fileContents.length === 0) { break; } await using _dbLock = await this.dbLockService.lock(`file-content-lock-${contentHash}-${contentSize}`, DateTime.now.addMinutes(15)); for (const iterator of fileContents) { if (!iterator.cloudPath) { await sleep(5000); continue; } const localFile = await this.downloadFile(iterator); if (await areFilesEqual(file.path, localFile.path)) { return iterator; } /** Probability of sha256 hash collision is very low, * however, since we are storing variety of files and * each file has different size, in case if collision * is ever detected, a wrong file content would be saved. * * So we need to check for the worst. Even if the collision * occurs, fileContentID is a unique number that references * the data, not the hash. */ // We have found the hash collision // lets spread the word console.warn(JSON.stringify({ serverID: globalEnv.serverID, warning: "File corruption or hash collision", path: iterator.cloudPath })); break; } } const fc = await db.fileContents.statements.insert({ contentType, contentSize, contentHash, compression }); return fc; } }