Make file download unavailable while caching is in progress

This commit is contained in:
Alice Gaudon 2020-11-20 13:38:32 +01:00
parent 9c185d3fd9
commit 00e21b27a5

View File

@ -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