From 00e21b27a56d682bcdac938fe488ff2e1c8ea2be Mon Sep 17 00:00:00 2001 From: Alice Gaudon Date: Fri, 20 Nov 2020 13:38:32 +0100 Subject: [PATCH] Make file download unavailable while caching is in progress --- src/controllers/GiteaRepoLatestReleaseController.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/controllers/GiteaRepoLatestReleaseController.ts b/src/controllers/GiteaRepoLatestReleaseController.ts index 7312285..2837eab 100644 --- a/src/controllers/GiteaRepoLatestReleaseController.ts +++ b/src/controllers/GiteaRepoLatestReleaseController.ts @@ -3,7 +3,7 @@ import {NextFunction, Request, Response} from "express"; import * as https from "https"; import config from "config"; import {log} from "swaf/Logger"; -import {NotFoundHttpError} from "swaf/HttpError"; +import {NotFoundHttpError, ServiceUnavailableHttpError} from "swaf/HttpError"; import * as fs from "fs"; import {promisify} from "util"; import path from "path"; @@ -85,10 +85,15 @@ export default class GiteaRepoLatestReleaseController extends Controller { } const assetPath = path.resolve(ASSETS_BASE_DIR, '' + downloadProperties.asset.id); + const tmpAssetPath = assetPath + '.tmp'; // Download asset if it doesn't exist if (!await promisify(fs.exists)(assetPath)) { - const file = fs.createWriteStream(assetPath); + if (await promisify(fs.exists)(tmpAssetPath)) { + throw new ServiceUnavailableHttpError('This file is currently being cached. Please try again later.'); + } + + const file = fs.createWriteStream(tmpAssetPath); await new Promise((resolve, reject) => { const httpRequest = https.get(downloadProperties.asset.url, res => { res.on('end', () => { @@ -102,6 +107,7 @@ export default class GiteaRepoLatestReleaseController extends Controller { httpRequest.end(); }); file.close(); + await promisify(fs.rename)(tmpAssetPath, assetPath); } // Respond