Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 | 1x 1x 1x 1x 1x 1x 1x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 46x 46x 46x 46x 46x 12x 12x 12x 12x 46x 36x 36x 36x 36x 36x 36x 46x 46x 46x 46x 46x 46x 46x 46x 46x 34x 34x 34x 46x 129x 129x 129x 250x 250x 129x 52x 52x 52x 52x 52x 52x 129x 46x 46x 46x 46x 46x 46x 46x 86x 45x 45x 86x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 1x 1x 1x 46x 46x 1x 1x 1x 46x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 40x 40x 40x 40x 40x 40x 40x 46x 46x 45x 46x 45x 46x 29x 29x 29x 45x 46x 46x 46x 45x 45x 45x 46x 36x 35x 35x 35x 36x 35x 35x | import { stat } from 'node:fs/promises'
import { basename } from 'node:path'
import type { Readable } from 'node:stream'
import debug from 'debug'
import pMap from 'p-map'
import type { OnSuccessPayload, UploadOptions } from 'tus-js-client'
import { Upload } from 'tus-js-client'
import type { AssemblyStatus } from './alphalib/types/assemblyStatus.ts'
import type { UploadProgress } from './Transloadit.ts'
const log = debug('transloadit')
const logWarn = debug('transloadit:warn')
export type UploadBehavior = 'await' | 'background' | 'none'
export interface Stream {
path?: string
stream: Readable
}
interface SendTusRequestOptions {
streamsMap: Record<string, Stream>
assembly: AssemblyStatus
requestedChunkSize: number
uploadConcurrency: number
onProgress: (options: UploadProgress) => void
signal?: AbortSignal
uploadUrls?: Record<string, string>
uploadBehavior?: UploadBehavior
}
export async function sendTusRequest({
streamsMap,
assembly,
requestedChunkSize,
uploadConcurrency,
onProgress,
signal,
uploadUrls,
uploadBehavior = 'await',
}: SendTusRequestOptions) {
const streamLabels = Object.keys(streamsMap)
let totalBytes = 0
let lastEmittedProgress = 0
const sizes: Record<string, number> = {}
const uploadUrlsResult: Record<string, string> = { ...(uploadUrls ?? {}) }
const haveUnknownLengthStreams = streamLabels.some((label) => !streamsMap[label]?.path)
// Initialize size data
await pMap(
streamLabels,
async (label) => {
// Check if aborted before each operation
if (signal?.aborted) throw new Error('Upload aborted')
const streamInfo = streamsMap[label]
if (!streamInfo) {
throw new Error(`Stream info not found for label: ${label}`)
}
const { path } = streamInfo
if (path) {
const { size } = await stat(path)
sizes[label] = size
totalBytes += size
}
},
{ concurrency: 5, signal },
)
const uploadProgresses: Record<string, number> = {}
const completionPromises: Array<Promise<void>> = []
const uploadUrlPromises: Array<Promise<void>> = []
async function uploadSingleStream(label: string) {
uploadProgresses[label] = 0
const streamInfo = streamsMap[label]
if (!streamInfo) {
throw new Error(`Stream info not found for label: ${label}`)
}
const { stream, path } = streamInfo
const size = sizes[label]
let chunkSize = requestedChunkSize
let uploadLengthDeferred: boolean
const isStreamLengthKnown = !!path
if (!isStreamLengthKnown) {
// tus-js-client requires these options to be set for unknown size streams
// https://github.com/tus/tus-js-client/blob/master/docs/api.md#uploadlengthdeferred
uploadLengthDeferred = true
if (chunkSize === Number.POSITIVE_INFINITY) chunkSize = 50e6
}
const onTusProgress = (bytesUploaded: number): void => {
uploadProgresses[label] = bytesUploaded
// get all uploaded bytes for all files
let uploadedBytes = 0
for (const l of streamLabels) {
uploadedBytes += uploadProgresses[l] ?? 0
}
// don't send redundant progress
if (lastEmittedProgress < uploadedBytes) {
lastEmittedProgress = uploadedBytes
// If we have any unknown length streams, we cannot trust totalBytes
// totalBytes should then be undefined to mimic behavior of form uploads.
onProgress({
uploadedBytes,
totalBytes: haveUnknownLengthStreams ? undefined : totalBytes,
})
}
}
const filename = path ? basename(path) : label
if (uploadBehavior === 'none' && uploadUrls?.[label]) {
uploadUrlsResult[label] = uploadUrls[label]
uploadUrlPromises.push(Promise.resolve())
completionPromises.push(Promise.resolve())
return
}
let urlResolved = false
let resolveUrl: () => void = () => {}
let rejectUrl: (err: Error) => void = () => {}
const uploadUrlPromise = new Promise<void>((resolve, reject) => {
resolveUrl = () => {
if (urlResolved) return
urlResolved = true
resolve()
}
rejectUrl = (err) => {
if (urlResolved) return
urlResolved = true
reject(err)
}
})
let resolveCompletion: () => void = () => {}
let rejectCompletion: (err: Error) => void = () => {}
const completionPromise = new Promise<void>((resolve, reject) => {
resolveCompletion = resolve
rejectCompletion = reject
})
uploadUrlPromises.push(uploadUrlPromise)
completionPromises.push(completionPromise)
if (uploadUrls?.[label]) {
uploadUrlsResult[label] = uploadUrls[label]
resolveUrl()
}
const startPromise = new Promise<void>((resolvePromise, rejectPromise) => {
if (!assembly.assembly_ssl_url) {
rejectPromise(new Error('assembly_ssl_url is not present in the assembly status'))
return
}
// Check if already aborted before starting
if (signal?.aborted) {
rejectPromise(new Error('Upload aborted'))
return
}
// Wrap resolve/reject to clean up abort listener
let abortHandler: (() => void) | undefined
const resolve = (_payload: OnSuccessPayload) => {
if (abortHandler) signal?.removeEventListener('abort', abortHandler)
resolveCompletion()
resolveUrl()
resolvePromise()
}
const reject = (err: unknown) => {
if (abortHandler) signal?.removeEventListener('abort', abortHandler)
rejectCompletion(err as Error)
rejectUrl(err as Error)
rejectPromise(err)
}
let tusUpload: Upload
const tusOptions: UploadOptions = {
endpoint: assembly.tus_url,
uploadUrl: uploadUrls?.[label],
metadata: {
assembly_url: assembly.assembly_ssl_url,
fieldname: label,
filename,
},
onError: reject,
onProgress: onTusProgress,
onSuccess: resolve,
onUploadUrlAvailable: () => {
const url = tusUpload?.url
if (url) {
uploadUrlsResult[label] = url
}
resolveUrl()
if (uploadBehavior === 'none') {
tusUpload.abort()
resolveCompletion()
}
},
}
// tus-js-client doesn't like undefined/null
if (size != null) tusOptions.uploadSize = size
if (chunkSize) tusOptions.chunkSize = chunkSize
if (uploadLengthDeferred) tusOptions.uploadLengthDeferred = uploadLengthDeferred
tusUpload = new Upload(stream, tusOptions)
// Handle abort signal
if (signal) {
abortHandler = () => {
tusUpload.abort()
reject(new Error('Upload aborted'))
}
signal.addEventListener('abort', abortHandler, { once: true })
}
tusUpload.start()
})
if (uploadBehavior === 'await') {
await startPromise
log(label, 'upload done')
return
}
startPromise.catch((err) => {
logWarn('Background upload failed', err)
})
await uploadUrlPromise
log(label, 'upload started')
}
await pMap(streamLabels, uploadSingleStream, { concurrency: uploadConcurrency, signal })
await Promise.all(uploadUrlPromises)
if (uploadBehavior === 'await') {
await Promise.all(completionPromises)
} else {
Promise.allSettled(completionPromises).catch((err) => {
logWarn('Background upload failed', err)
})
}
return { uploadUrls: uploadUrlsResult }
}
|