upload-progress.mjs 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. import { createReadStream, createWriteStream } from "node:fs";
  2. import { chmod } from "node:fs/promises";
  3. import { join } from "node:path";
  4. const executableModeMask = 0o777;
  5. const progressCompletePercent = 100;
  6. const uploadProgressIntervalMs = 200;
  7. export const fileMode = (stats) => stats.mode & executableModeMask;
  8. export const formatBytes = (bytes) => {
  9. if (bytes < 1024) return `${bytes} B`;
  10. const units = ["KB", "MB", "GB"];
  11. let value = bytes / 1024;
  12. for (const unit of units) {
  13. if (value < 1024) return `${value.toFixed(1)} ${unit}`;
  14. value /= 1024;
  15. }
  16. return `${value.toFixed(1)} TB`;
  17. };
  18. export const createConsoleProgressReporter = ({ stdout = process.stdout } = {}) => {
  19. let lastProgressAt = 0;
  20. let lastLineLength = 0;
  21. let lastNonTtyPercent = -1;
  22. const writeProgressLine = (line) => {
  23. if (!stdout.isTTY) {
  24. stdout.write(`${line}\n`);
  25. return;
  26. }
  27. const padded = line.padEnd(lastLineLength, " ");
  28. stdout.write(`\r${padded}`);
  29. lastLineLength = line.length;
  30. };
  31. const finishTtyLine = () => {
  32. if (stdout.isTTY && lastLineLength > 0) {
  33. stdout.write("\n");
  34. lastLineLength = 0;
  35. }
  36. };
  37. return (event) => {
  38. if (event.type === "file-start") {
  39. writeProgressLine(`[upload] ${event.index}/${event.totalFiles} ${event.fileName} starting`);
  40. return;
  41. }
  42. if (event.type === "progress") {
  43. const now = Date.now();
  44. const percent =
  45. event.totalBytes === 0
  46. ? progressCompletePercent
  47. : Math.floor((event.totalCopiedBytes / event.totalBytes) * progressCompletePercent);
  48. if (!stdout.isTTY && percent < lastNonTtyPercent + 10 && percent < progressCompletePercent) {
  49. return;
  50. }
  51. if (stdout.isTTY && now - lastProgressAt < uploadProgressIntervalMs) return;
  52. lastProgressAt = now;
  53. lastNonTtyPercent = percent;
  54. writeProgressLine(
  55. `[upload] ${event.index}/${event.totalFiles} ${event.fileName} ` +
  56. `${formatBytes(event.fileCopiedBytes)}/${formatBytes(event.fileSize)} ` +
  57. `total ${formatBytes(event.totalCopiedBytes)}/${formatBytes(event.totalBytes)} ` +
  58. `${percent}%`,
  59. );
  60. return;
  61. }
  62. if (event.type === "file-complete") {
  63. writeProgressLine(`[upload] ${event.index}/${event.totalFiles} ${event.fileName} complete`);
  64. return;
  65. }
  66. if (event.type === "complete") {
  67. finishTtyLine();
  68. stdout.write(
  69. `[upload] complete: ${event.totalFiles} files, ${formatBytes(event.totalCopiedBytes)}\n`,
  70. );
  71. }
  72. };
  73. };
  74. const copyFileWithProgress = async ({
  75. aggregate,
  76. destination,
  77. file,
  78. index,
  79. onProgress,
  80. totalFiles,
  81. }) =>
  82. new Promise((resolveCopy, rejectCopy) => {
  83. let fileCopiedBytes = 0;
  84. const readStream = createReadStream(file.source);
  85. const writeStream = createWriteStream(destination, {
  86. mode: file.mode,
  87. });
  88. const rejectOnce = (error) => {
  89. readStream.destroy();
  90. writeStream.destroy();
  91. rejectCopy(error);
  92. };
  93. readStream.on("data", (chunk) => {
  94. fileCopiedBytes += chunk.length;
  95. aggregate.copiedBytes += chunk.length;
  96. onProgress({
  97. fileCopiedBytes,
  98. fileName: file.fileName,
  99. fileSize: file.size,
  100. index,
  101. totalBytes: aggregate.totalBytes,
  102. totalCopiedBytes: aggregate.copiedBytes,
  103. totalFiles,
  104. type: "progress",
  105. });
  106. });
  107. readStream.on("error", rejectOnce);
  108. writeStream.on("error", rejectOnce);
  109. writeStream.on("finish", () => {
  110. chmod(destination, file.mode)
  111. .catch(() => undefined)
  112. .then(resolveCopy, rejectCopy);
  113. });
  114. readStream.pipe(writeStream);
  115. });
  116. export const copyReleaseFiles = async ({ files, onProgress, stagingDirectory }) => {
  117. const aggregate = {
  118. copiedBytes: 0,
  119. totalBytes: files.reduce((sum, file) => sum + file.size, 0),
  120. };
  121. onProgress({
  122. totalBytes: aggregate.totalBytes,
  123. totalFiles: files.length,
  124. type: "start",
  125. });
  126. for (const [index, file] of files.entries()) {
  127. const fileIndex = index + 1;
  128. onProgress({
  129. fileName: file.fileName,
  130. fileSize: file.size,
  131. index: fileIndex,
  132. totalBytes: aggregate.totalBytes,
  133. totalFiles: files.length,
  134. type: "file-start",
  135. });
  136. await copyFileWithProgress({
  137. aggregate,
  138. destination: join(stagingDirectory, file.fileName),
  139. file,
  140. index: fileIndex,
  141. onProgress,
  142. totalFiles: files.length,
  143. });
  144. onProgress({
  145. fileName: file.fileName,
  146. fileSize: file.size,
  147. index: fileIndex,
  148. totalBytes: aggregate.totalBytes,
  149. totalCopiedBytes: aggregate.copiedBytes,
  150. totalFiles: files.length,
  151. type: "file-complete",
  152. });
  153. }
  154. onProgress({
  155. totalBytes: aggregate.totalBytes,
  156. totalCopiedBytes: aggregate.copiedBytes,
  157. totalFiles: files.length,
  158. type: "complete",
  159. });
  160. return aggregate;
  161. };