// Resumable chunked uploads for the studio page. // // Each file is sent in parts with File.slice(), so the browser never reads a whole // file into memory. Upload ids are remembered in localStorage: after a reload, // picking the same file again sends only the missing parts. const CONCURRENCY = 3 const MAX_ATTEMPTS = 8 const STALL_MS = 120000 const STORE_PREFIX = 'privatestudio.upload.' class FatalError extends Error {} class HttpError extends Error { constructor (status, data) { super((data && data.detail) || `The server returned HTTP ${status}`) this.status = status this.code = data && data.code } } const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) const retryable = (error) => !(error instanceof FatalError) && (!(error instanceof HttpError) || [0, 408, 429, 500, 502, 503, 504].includes(error.status)) function store (action, key, value) { try { if (action === 'get') return JSON.parse(window.localStorage.getItem(STORE_PREFIX + key)) if (action === 'set') window.localStorage.setItem(STORE_PREFIX + key, JSON.stringify(value)) if (action === 'remove') window.localStorage.removeItem(STORE_PREFIX + key) } catch (e) { // Storage can be unavailable (private windows, blocked site data). Resuming then // starts over, which is still correct. } return null } function formatBytes (bytes) { const units = ['B', 'KB', 'MB', 'GB', 'TB'] let i = 0 while (bytes >= 1024 && i < units.length - 1) { bytes /= 1024; i++ } return `${bytes.toFixed(i ? 1 : 0)} ${units[i]}` } // One XMLHttpRequest. XHR is used because fetch() has no portable upload progress. function request (method, url, { body = null, csrf, onProgress, xhrs } = {}) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest() let stallTimer const stalled = () => { clearTimeout(stallTimer) stallTimer = setTimeout(() => xhr.abort(), STALL_MS) } const finish = () => { clearTimeout(stallTimer); if (xhrs) xhrs.delete(xhr) } xhr.open(method, url) xhr.setRequestHeader('X-CSRFToken', csrf) xhr.setRequestHeader('Accept', 'application/json') if (body !== null && !(body instanceof Blob)) xhr.setRequestHeader('Content-Type', 'application/json') xhr.upload.onprogress = (event) => { stalled(); if (onProgress) onProgress(event.loaded) } xhr.onload = () => { finish() let data = null try { data = xhr.responseText ? JSON.parse(xhr.responseText) : null } catch (e) { data = null } if (xhr.status >= 200 && xhr.status < 300) resolve(data) else reject(new HttpError(xhr.status, data)) } xhr.onerror = xhr.onabort = () => { finish(); reject(new HttpError(0, { detail: 'The connection failed' })) } if (xhrs) xhrs.add(xhr) stalled() xhr.send(body === null || body instanceof Blob ? body : JSON.stringify(body)) }) } class FileUpload { constructor (uploader, file, folder) { this.uploader = uploader this.file = file this.folder = folder this.cancelled = false this.xhrs = new Set() this.inFlight = new Map() this.done = 0 this.storeKey = [uploader.userId, uploader.bucket, folder, file.name, file.size, file.lastModified].join('|') this.renderRow() } renderRow () { const row = document.createElement('li') row.className = 'list-group-item' row.innerHTML = `
` row.querySelector('.fw-semibold').textContent = this.folder ? `${this.folder}/${this.file.name}` : this.file.name this.row = row this.bar = row.querySelector('.progress-bar') this.status = row.querySelector('small') this.retryButton = row.querySelector('[data-action=retry]') this.cancelButton = row.querySelector('[data-action=cancel]') this.retryButton.addEventListener('click', () => this.uploader.enqueue(this)) this.cancelButton.addEventListener('click', () => this.cancel()) this.uploader.list.prepend(row) this.setStatus('Waiting') } setStatus (text, style = '') { this.status.textContent = text this.status.className = style ? `text-${style}` : 'text-body-secondary' } setProgress (bytes) { const percent = this.file.size ? Math.min(100, (bytes / this.file.size) * 100) : 100 this.bar.style.width = `${percent}%` this.bar.parentElement.setAttribute('aria-valuenow', Math.round(percent)) } call (method, url, options = {}) { if (this.cancelled) return Promise.reject(new FatalError('Cancelled')) return request(method, url, { csrf: this.uploader.csrf, xhrs: this.xhrs, ...options }) } // Retry network failures and server errors with exponential backoff. async withRetry (action) { for (let attempt = 1; ; attempt++) { try { return await action() } catch (error) { if (this.cancelled) throw new FatalError('Cancelled') if (!retryable(error) || attempt >= MAX_ATTEMPTS) throw error await sleep(Math.min(30000, 1000 * 2 ** (attempt - 1)) * (0.5 + Math.random() / 2)) } } } async run () { this.retryButton.classList.add('d-none') this.bar.classList.remove('bg-danger', 'bg-success') this.cancelButton.disabled = false this.cancelled = false try { const upload = await this.start() if (upload.status !== 'completed') { await this.sendParts(upload) await this.complete(upload) } store('remove', this.storeKey) this.setProgress(this.file.size) this.bar.classList.add('bg-success') this.setStatus(`Uploaded ${formatBytes(this.file.size)}`, 'success') this.cancelButton.classList.add('d-none') document.body.dispatchEvent(new CustomEvent('assets-changed')) } catch (error) { if (this.cancelled) return this.bar.classList.add('bg-danger') let message = error.message if (error instanceof HttpError && error.status === 403) { message += '. If you signed in again in another tab, reload this page and pick the file again to resume.' } this.setStatus(message, 'danger') this.retryButton.classList.remove('d-none') } } // Resume a remembered upload of this file, or start a new one. async start () { const remembered = store('get', this.storeKey) if (remembered) { try { const upload = await this.withRetry(() => this.call('GET', remembered.url)) if (upload.status === 'active' || upload.status === 'completed') return upload } catch (error) { if (!(error instanceof HttpError) || error.status !== 404) throw error } store('remove', this.storeKey) } const body = { filename: this.file.name, folder: this.folder, size: this.file.size, last_modified: this.file.lastModified, overwrite: false } let upload try { upload = await this.withRetry(() => this.call('POST', this.uploader.createUrl, { body })) } catch (error) { if (!(error instanceof HttpError) || error.code !== 'ObjectExists') throw error if (!window.confirm(`${body.folder ? body.folder + '/' : ''}${this.file.name} already exists. Replace it?`)) { throw new FatalError('Not uploaded: a file with this name already exists') } body.overwrite = true upload = await this.withRetry(() => this.call('POST', this.uploader.createUrl, { body })) } store('set', this.storeKey, { url: upload.url }) return upload } async sendParts (upload) { const received = new Set(upload.received) const pending = [] for (let n = 1; n <= upload.part_count; n++) { if (!received.has(n)) pending.push(n) } const partBytes = (n) => Math.min(upload.part_size, this.file.size - (n - 1) * upload.part_size) this.done = this.file.size - pending.reduce((sum, n) => sum + partBytes(n), 0) this.inFlight.clear() const started = Date.now() const doneAtStart = this.done const showProgress = () => { let sending = 0 for (const bytes of this.inFlight.values()) sending += bytes const sent = this.done + sending this.setProgress(sent) const seconds = (Date.now() - started) / 1000 const rate = seconds > 1 ? (sent - doneAtStart) / seconds : 0 const speed = rate ? `, ${formatBytes(rate)}/s` : '' this.setStatus(`${formatBytes(sent)} of ${formatBytes(this.file.size)}${speed}`) } showProgress() const worker = async () => { while (pending.length) { const n = pending.shift() const start = (n - 1) * upload.part_size const blob = this.file.slice(start, start + partBytes(n)) await this.withRetry(() => { this.inFlight.set(n, 0) return this.call('PUT', `${upload.url}parts/${n}/`, { body: blob, onProgress: (loaded) => { this.inFlight.set(n, loaded); showProgress() } }) }) this.inFlight.delete(n) this.done += blob.size showProgress() } } // If one worker fails, stop the others so the failure is reported once. try { await Promise.all(Array.from({ length: Math.min(CONCURRENCY, pending.length) }, worker)) } catch (error) { pending.length = 0 for (const xhr of this.xhrs) xhr.abort() throw error } } // Joining a large file takes time. If the request is cut off, check the // upload's status, then ask again. async complete (upload) { this.setStatus('Finalizing…') this.bar.classList.add('progress-bar-striped', 'progress-bar-animated') let overwrite = false let failures = 0 const deadline = Date.now() + 60 * 60 * 1000 try { while (true) { try { return await this.call('POST', `${upload.url}complete/`, { body: { overwrite } }) } catch (error) { if (this.cancelled) throw new FatalError('Cancelled') if (error.code === 'ObjectExists' && !overwrite) { if (!window.confirm(`${upload.key} was created by someone else meanwhile. Replace it?`)) { throw new FatalError('Not uploaded: a file with this name already exists. Retry to choose again.') } overwrite = true continue } const busy = error.status === 409 && error.code === 'Busy' if (!busy && (!retryable(error) || ++failures >= MAX_ATTEMPTS)) throw error if (Date.now() > deadline) throw error await sleep(3000) try { const current = await this.call('GET', upload.url) if (current.status === 'completed') return current } catch (e) { // Try completing again below. } } } } finally { this.bar.classList.remove('progress-bar-striped', 'progress-bar-animated') } } async cancel () { this.cancelled = true for (const xhr of this.xhrs) xhr.abort() this.uploader.dequeue(this) this.cancelButton.disabled = true this.retryButton.classList.add('d-none') this.setStatus('Cancelling…') const remembered = store('get', this.storeKey) store('remove', this.storeKey) if (remembered) { try { await request('DELETE', remembered.url, { csrf: this.uploader.csrf }) } catch (error) { // The server removes abandoned uploads later. } } this.setStatus('Cancelled', 'warning') this.bar.classList.add('bg-secondary') } } // Files upload one after another; each sends several parts at once. class Uploader { constructor (form) { this.form = form this.createUrl = form.dataset.createUrl this.bucket = form.dataset.bucket this.userId = form.dataset.userId this.csrf = form.querySelector('[name=csrfmiddlewaretoken]').value this.list = form.querySelector('[data-upload-list]') this.fileInput = form.querySelector('input[type=file]') this.folderInput = form.querySelector('[name=folder]') this.queue = [] this.active = null form.querySelector('button[type=submit]').disabled = false form.addEventListener('submit', (event) => { event.preventDefault() const folder = this.folderInput.value.trim().replace(/^\/+|\/+$/g, '') for (const file of this.fileInput.files) this.enqueue(new FileUpload(this, file, folder)) this.fileInput.value = '' }) window.addEventListener('beforeunload', (event) => { if (this.active || this.queue.length) { event.preventDefault() event.returnValue = '' } }) } enqueue (upload) { if (!this.queue.includes(upload) && this.active !== upload) { upload.setStatus('Waiting') this.queue.push(upload) } this.next() } dequeue (upload) { this.queue = this.queue.filter((item) => item !== upload) } async next () { if (this.active || !this.queue.length) return this.active = this.queue.shift() try { await this.active.run() } finally { this.active = null this.next() } } } export function initUploaders () { for (const form of document.querySelectorAll('form[data-uploader]')) new Uploader(form) // eslint-disable-line no-new }