Save uncommitted changes
Build / Lint & Test (push) Successful in 28s

This commit is contained in:
PickleRick committed 2026-09-21 23:38:34 +02:00
1 parent b85759e27c
commit 7ee5a5bc48
6 files changed
+72 -145

No files matched your search

+62 -95
View File
@@ -2,122 +2,90 @@
const fs = require('fs'); const fs = require('fs');
const copyWithProgress = async ({ const MAX_RETRIES = 2;
source, const RETRY_DELAY_MS = 1000;
destination, const PROGRESS_INTERVAL_MS = 250;
jobLog,
updateProgress,
label,
copyMethod = 'auto',
bufferSizeMb = 16,
maxRetries = 2,
retryDelayMs = 1000,
}) => {
const sourceSize = fs.statSync(source).size;
const sourceSizeMb = (sourceSize / 1024 / 1024).toFixed(1);
const normalizedBufferSizeMb = Math.min(
Math.max(Number.parseInt(bufferSizeMb, 10) || 16, 1),
128,
);
const bufferSize = normalizedBufferSizeMb * 1024 * 1024;
const report = (percent, message) => { const sleep = (milliseconds) => new Promise((resolve) => {
const boundedPercent = Math.min(Math.max(percent, 0), 100); setTimeout(resolve, milliseconds);
if (typeof updateProgress === 'function') {
updateProgress({
progress: boundedPercent,
jobLog: message,
}); });
const copyWithProgress = async ({ source, destination, jobLog, updateProgress, label }) => {
const sourceSize = fs.statSync(source).size;
const sourceSizeMb = sourceSize / 1024 / 1024;
let lastError;
const report = (progress, message) => {
if (typeof updateProgress === 'function') {
updateProgress({ progress, jobLog: message });
} }
if (typeof jobLog === 'function') jobLog(`${message}\n`); if (typeof jobLog === 'function') jobLog(`${message}\n`);
}; };
const copyOnceWithStream = () => new Promise((resolve, reject) => { for (let attempt = 0; attempt <= MAX_RETRIES; attempt += 1) {
const startMs = Date.now(); if (attempt > 0) {
let copiedBytes = 0; report(0, `[${label}] Retrying copy (${attempt}/${MAX_RETRIES})...`);
let lastReportedPercent = -1; await sleep(RETRY_DELAY_MS);
const rd = fs.createReadStream(source, { highWaterMark: bufferSize }); }
const wr = fs.createWriteStream(destination, { highWaterMark: bufferSize });
let settled = false;
const fail = (error) => {
if (settled) return;
settled = true;
rd.destroy();
wr.destroy();
reject(error);
};
rd.on('error', fail);
wr.on('error', fail);
wr.on('finish', () => {
if (settled) return;
settled = true;
resolve(((Date.now() - startMs) / 1000).toFixed(1));
});
rd.on('data', (chunk) => {
copiedBytes += chunk.length;
const percent = sourceSize === 0 ? 100 : Math.floor((copiedBytes / sourceSize) * 100);
if (percent <= lastReportedPercent || percent >= 100) return;
const elapsedSeconds = Math.max((Date.now() - startMs) / 1000, 0.1);
report(
percent,
`[${label}] Progress: ${Math.min(percent, 100)}% `
+ `(${(copiedBytes / 1024 / 1024).toFixed(1)}/${sourceSizeMb} MB, `
+ `${(copiedBytes / 1024 / 1024 / elapsedSeconds).toFixed(1)} MB/s)`,
);
lastReportedPercent = percent;
});
rd.pipe(wr);
});
const copyOnceWithNative = () => new Promise((resolve, reject) => { try {
const startMs = Date.now(); if (fs.existsSync(destination)) fs.unlinkSync(destination);
let settled = false;
const startedAt = Date.now();
let lastReportedPercent = -1; let lastReportedPercent = -1;
let previousBytes = 0;
let previousAt = startedAt;
let copying = true;
const progressTimer = setInterval(() => { const progressTimer = setInterval(() => {
if (settled || !fs.existsSync(destination)) return; if (!copying || !fs.existsSync(destination)) return;
const copiedBytes = fs.statSync(destination).size; let copiedBytes;
const elapsedSeconds = Math.max((Date.now() - startMs) / 1000, 0.1); try {
copiedBytes = fs.statSync(destination).size;
} catch (error) {
if (error.code === 'ENOENT') return;
return;
}
const percent = sourceSize === 0 const percent = sourceSize === 0
? 99 ? 99
: Math.min(Math.floor((copiedBytes / sourceSize) * 100), 99); : Math.min(Math.floor((copiedBytes / sourceSize) * 100), 99);
if (percent <= lastReportedPercent) return; if (percent <= lastReportedPercent) return;
lastReportedPercent = percent;
const now = Date.now();
const intervalSeconds = Math.max((now - previousAt) / 1000, 0.001);
const intervalSpeed = (copiedBytes - previousBytes) / 1024 / 1024 / intervalSeconds;
report( report(
percent, percent,
`[${label}] Progress: ${percent}% ` `[${label}] Progress: ${percent}% `
+ `(${(copiedBytes / 1024 / 1024).toFixed(1)}/${sourceSizeMb} MB, ` + `(${(copiedBytes / 1024 / 1024).toFixed(1)}/${sourceSizeMb.toFixed(1)} MB, `
+ `${(copiedBytes / 1024 / 1024 / elapsedSeconds).toFixed(1)} MB/s)`, + `${intervalSpeed.toFixed(1)} MB/s)`,
); );
}, 1000); lastReportedPercent = percent;
fs.promises.copyFile(source, destination).then(() => { previousBytes = copiedBytes;
settled = true; previousAt = now;
clearInterval(progressTimer); }, PROGRESS_INTERVAL_MS);
resolve(((Date.now() - startMs) / 1000).toFixed(1));
}).catch((error) => {
settled = true;
clearInterval(progressTimer);
reject(error);
});
});
const copyOnce = copyMethod === 'stream' ? copyOnceWithStream : copyOnceWithNative;
let lastError;
for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
if (attempt > 0) {
report(0, `[${label}] Retrying copy (${attempt}/${maxRetries})...`);
await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
}
try { try {
if (fs.existsSync(destination)) fs.unlinkSync(destination); await fs.promises.copyFile(source, destination);
const elapsed = await copyOnce(); } finally {
copying = false;
clearInterval(progressTimer);
}
const destinationSize = fs.statSync(destination).size; const destinationSize = fs.statSync(destination).size;
if (destinationSize !== sourceSize) { if (destinationSize !== sourceSize) {
throw new Error( throw new Error(
`Copy size mismatch: expected ${sourceSize} bytes, got ${destinationSize}`, `Copy size mismatch: expected ${sourceSize} bytes, got ${destinationSize}`,
); );
} }
report(100, `[${label}] Done: ${sourceSizeMb} MB copied in ${elapsed}s`);
const elapsedSeconds = Math.max((Date.now() - startedAt) / 1000, 0.001);
const averageSpeed = sourceSize / 1024 / 1024 / elapsedSeconds;
report(
100,
`[${label}] Done: ${sourceSizeMb.toFixed(1)} MB copied in `
+ `${elapsedSeconds.toFixed(1)}s (${averageSpeed.toFixed(1)} MB/s average)`,
);
return; return;
} catch (error) { } catch (error) {
lastError = error; lastError = error;
@@ -128,15 +96,14 @@ const copyWithProgress = async ({
`${error.message}; could not remove partial copy: ${cleanupError.message}`, `${error.message}; could not remove partial copy: ${cleanupError.message}`,
); );
} }
if (attempt === maxRetries) break; if (attempt < MAX_RETRIES && typeof jobLog === 'function') {
if (typeof jobLog === 'function') { jobLog(`[${label}] Copy attempt ${attempt + 1} failed: ${lastError.message}\n`);
jobLog(`[${label}] Copy attempt ${attempt + 1} failed: ${error.message}\n`);
} }
} }
} }
throw new Error( throw new Error(
`[${label}] Copy failed after ${maxRetries + 1} attempts: ${lastError.message}`, `[${label}] Copy failed after ${MAX_RETRIES + 1} attempts: ${lastError.message}`,
); );
}; };
@@ -25,22 +25,6 @@ const details = () => ({
inputUI: { type: 'dropdown', options: ['true', 'false'] }, inputUI: { type: 'dropdown', options: ['true', 'false'] },
tooltip: 'Skip when the source is already inside workDir.', tooltip: 'Skip when the source is already inside workDir.',
}, },
{
label: 'Copy method',
name: 'copyMethod',
type: 'string',
defaultValue: 'auto',
inputUI: { type: 'dropdown', options: ['auto', 'native', 'stream'] },
tooltip: 'Auto uses the operating system copy API; stream is a fallback for problematic mounts.',
},
{
label: 'Stream buffer size (MB)',
name: 'bufferSizeMb',
type: 'string',
defaultValue: '16',
inputUI: { type: 'dropdown', options: ['4', '16', '64'] },
tooltip: 'Used only with stream copy; larger values can improve high-latency SMB mounts.',
},
], ],
outputs: [{ number: 1, tooltip: 'File is ready in workDir — continue to next plugin' }], outputs: [{ number: 1, tooltip: 'File is ready in workDir — continue to next plugin' }],
}); });
@@ -73,8 +57,6 @@ const plugin = async (args) => {
jobLog, jobLog,
updateProgress: args.updateProgress, updateProgress: args.updateProgress,
label: 'copyToWorkDir', label: 'copyToWorkDir',
copyMethod: args.inputs.copyMethod || 'auto',
bufferSizeMb: args.inputs.bufferSizeMb || '16',
}); });
return { return {
@@ -25,22 +25,6 @@ const details = () => ({
inputUI: { type: 'dropdown', options: ['true', 'false'] }, inputUI: { type: 'dropdown', options: ['true', 'false'] },
tooltip: 'Delete the processed file after it has replaced the original.', tooltip: 'Delete the processed file after it has replaced the original.',
}, },
{
label: 'Copy method',
name: 'copyMethod',
type: 'string',
defaultValue: 'auto',
inputUI: { type: 'dropdown', options: ['auto', 'native', 'stream'] },
tooltip: 'Auto uses the operating system copy API; stream is a fallback for problematic mounts.',
},
{
label: 'Stream buffer size (MB)',
name: 'bufferSizeMb',
type: 'string',
defaultValue: '16',
inputUI: { type: 'dropdown', options: ['4', '16', '64'] },
tooltip: 'Used only with stream copy; larger values can improve high-latency SMB mounts.',
},
], ],
outputs: [{ number: 1, tooltip: 'Original file replaced — continue to next plugin' }], outputs: [{ number: 1, tooltip: 'Original file replaced — continue to next plugin' }],
}); });
@@ -78,8 +62,6 @@ const plugin = async (args) => {
jobLog, jobLog,
updateProgress: args.updateProgress, updateProgress: args.updateProgress,
label: 'replaceOriginalFile', label: 'replaceOriginalFile',
copyMethod: args.inputs.copyMethod || 'auto',
bufferSizeMb: args.inputs.bufferSizeMb || '16',
}); });
if (fs.existsSync(destination)) { if (fs.existsSync(destination)) {
+3 -4
View File
@@ -279,10 +279,9 @@ Performs 2-pass libx265 encoding using VBV parameters from `args.variables`.
Streams the source file to the worker's local `workDir`, verifies the byte count, Streams the source file to the worker's local `workDir`, verifies the byte count,
reports throttled copy progress, and retries failed writes twice after removing reports throttled copy progress, and retries failed writes twice after removing
the partial destination. Its `Copy method` input defaults to `auto` (the the partial destination. Its `Copy method` uses the operating system's native file-copy path, reports interval speed,
operating system's native file-copy path) and offers `stream` as a fallback verifies the destination size, and retries failed writes. It stores the
for problematic mounts. The stream fallback defaults to a 16 MB buffer and original library path in
offers 4 MB or 64 MB alternatives. It stores the original library path in
`variables.originalLibraryFile` for `replaceOriginalFile`. `variables.originalLibraryFile` for `replaceOriginalFile`.
### 9. `replaceOriginalFile` — Replace Original File ### 9. `replaceOriginalFile` — Replace Original File
+2 -3
View File
@@ -123,9 +123,8 @@ a network share. Place it before the first analysis/transcode node; it records
the library path for `replaceOriginalFile` 2.0.0. the library path for `replaceOriginalFile` 2.0.0.
Both progress-enabled copy operations verify the destination size and retry Both progress-enabled copy operations verify the destination size and retry
failed writes twice after removing the partial destination. Their `Copy method` failed writes twice after removing the partial destination. Their `Copy method`
input defaults to `auto` (the operating system's native file-copy path), with uses the operating system's native file-copy path, reports interval speed,
`stream` available as a fallback for problematic SMB/CIFS mounts. Stream mode verifies the destination size, and retries failed writes.
supports 4 MB, 16 MB, and 64 MB buffers.
Both progress-enabled plugins require Both progress-enabled plugins require
`FlowHelpers/1.0.0/copyWithProgress.js`; the installer downloads it `FlowHelpers/1.0.0/copyWithProgress.js`; the installer downloads it
automatically. automatically.
+5 -7
View File
@@ -219,16 +219,14 @@ const AUDIO_INPUTS = {
ok(replacePluginV1Code.includes('copyAndVerify'), 'replaceOriginalFile v1 verifies the copied file'); ok(replacePluginV1Code.includes('copyAndVerify'), 'replaceOriginalFile v1 verifies the copied file');
ok(!replacePluginV1Code.includes('updateProgress'), 'replaceOriginalFile v1 has no progress callback'); ok(!replacePluginV1Code.includes('updateProgress'), 'replaceOriginalFile v1 has no progress callback');
const copyHelperCode = require('fs').readFileSync(path.join(ROOT, 'FlowHelpers/1.0.0/copyWithProgress.js'), 'utf8'); const copyHelperCode = require('fs').readFileSync(path.join(ROOT, 'FlowHelpers/1.0.0/copyWithProgress.js'), 'utf8');
ok(copyHelperCode.includes('maxRetries = 2'), 'copy helper retries failed writes'); ok(copyHelperCode.includes('MAX_RETRIES = 2'), 'copy helper retries failed writes');
ok(copyHelperCode.includes('Copy size mismatch'), 'copy helper verifies destination size'); ok(copyHelperCode.includes('Copy size mismatch'), 'copy helper verifies destination size');
ok(copyHelperCode.includes('fs.unlinkSync(destination)'), 'copy helper removes partial copies before retrying'); ok(copyHelperCode.includes('fs.unlinkSync(destination)'), 'copy helper removes partial copies before retrying');
ok(copyHelperCode.includes('fs.promises.copyFile(source, destination)'), 'copy helper uses native file copying'); ok(copyHelperCode.includes('fs.promises.copyFile(source, destination)'), 'copy helper uses native file copying');
ok(copyHelperCode.includes("copyMethod = 'auto'"), 'copy helper defaults to automatic copy selection'); ok(copyHelperCode.includes('PROGRESS_INTERVAL_MS = 250'), 'copy helper polls progress frequently');
ok(copyHelperCode.includes("copyMethod === 'stream'"), 'copy helper supports stream fallback'); ok(copyHelperCode.includes('intervalSpeed'), 'copy helper reports interval speed');
ok(copyHelperCode.includes('bufferSizeMb = 16'), 'copy helper defaults stream buffer to 16 MB'); ok(!copyPluginV2Code.includes('copyMethod'), 'copyToWorkDir v2 has no copy method setting');
ok(copyHelperCode.includes('128'), 'copy helper caps stream buffer size'); ok(!replacePluginCode.includes('bufferSizeMb'), 'replaceOriginalFile v2 has no buffer setting');
ok(copyHelperCode.includes('Math.min(Math.floor((copiedBytes / sourceSize) * 100), 99)'), 'native progress reserves 100% for completed copy');
ok(copyHelperCode.includes('percent <= lastReportedPercent'), 'copy helper reports each progress percentage once');
// ── Summary ─────────────────────────────────────────────────────────────── // ── Summary ───────────────────────────────────────────────────────────────
console.log(`\n${'='.repeat(55)}`); console.log(`\n${'='.repeat(55)}`);