From f8662dddb104c7c154edf71cc9b4d8a49066b0bc Mon Sep 17 00:00:00 2001 From: jessop Date: Tue, 26 Feb 2019 01:56:44 -0500 Subject: [PATCH] replaces wait-on --- changelog.md | 0 server/controllers/api/claim/get/index.js | 16 ++++++++------ server/utils/awaitFileSize.js | 27 +++++++++++++++++++++++ 3 files changed, 36 insertions(+), 7 deletions(-) create mode 100644 changelog.md create mode 100644 server/utils/awaitFileSize.js diff --git a/changelog.md b/changelog.md new file mode 100644 index 00000000..e69de29b diff --git a/server/controllers/api/claim/get/index.js b/server/controllers/api/claim/get/index.js index 94914810..89a9523c 100644 --- a/server/controllers/api/claim/get/index.js +++ b/server/controllers/api/claim/get/index.js @@ -1,11 +1,13 @@ const { getClaim } = require('../../../../lbrynet'); -const { createFileRecordDataAfterGet } = require('../../../../models/utils/createFileRecordData.js'); +const { + createFileRecordDataAfterGet, +} = require('../../../../models/utils/createFileRecordData.js'); const { handleErrorResponse } = require('../../../utils/errorHandlers.js'); const getClaimData = require('server/utils/getClaimData'); const chainquery = require('chainquery').default; const db = require('../../../../models'); -const waitOn = require('wait-on'); const logger = require('winston'); +const awaitFileSize = require('server/utils/awaitFileSize'); /* @@ -36,11 +38,11 @@ const claimGet = async ({ ip, originalUrl, params }, res) => { if (!claimData) { throw new Error('claim/get: getClaimData failed to get file blobs'); } - await waitOn({ - resources: [ lbrynetResult.download_path ], - timeout : 10000, // 10 seconds - window : 500, - }); + let fileReady = await awaitFileSize(lbrynetResult.download_path, 2000000, 10000, 250); + + if (fileReady !== 'ready') { + throw new Error('claim/get: failed to get file after 10 seconds'); + } const fileData = await createFileRecordDataAfterGet(claimData, lbrynetResult); if (!fileData) { throw new Error('claim/get: createFileRecordDataAfterGet failed to create file in time'); diff --git a/server/utils/awaitFileSize.js b/server/utils/awaitFileSize.js new file mode 100644 index 00000000..73ce5af1 --- /dev/null +++ b/server/utils/awaitFileSize.js @@ -0,0 +1,27 @@ +const fs = require('fs'); +const { promisify } = require('util'); + +const fsstat = promisify(fs.stat); +const awaitFileSize = (path, sizeInBytes, timeout, interval) => { + return new Promise((resolve, reject) => { + let totalTime = 0; + let timer = setInterval(() => { + totalTime = totalTime + interval; + fsstat(path) + .then(stats => { + if (stats.size > sizeInBytes) { + clearInterval(interval); + resolve('ready'); + } + if (totalTime > timeout) { + const error = new Error('File did not arrive in time'); + error.name = 'FILE_NOT_ARRIVED'; + reject(error); + } + }) + .catch(); + }, interval); + }); +}; + +module.exports = awaitFileSize;