Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat: use TUS for file uploads in dashboard (#28030)

Alaister Youngb897d51a53a9
diff --git a/apps/studio/lib/mime.ts b/apps/studio/lib/mime.ts
new file mode 100644
index 00000000000..2e08f3c02d1
--- /dev/null
+++ b/apps/studio/lib/mime.ts
@@ -0,0 +1,20 @@
+import db from 'mime-db'
+
+// [Alaister]: This is going to be moved to the server side
+// so can be removed once the server side is ready
+
+export const MIME_TYPES_BY_EXTENSION = Object.fromEntries(
+ Object.entries(db)
+ .filter(([, { extensions }]) => extensions !== undefined)
+ .flatMap(([mime, { extensions }]) =>
+ extensions!.map((extension) => [extension.toLowerCase(), mime])
+ )
+)
+
+export function lookupMime(extension?: string): string | undefined {
+ if (extension === undefined) {
+ return undefined
+ }
+
+ return MIME_TYPES_BY_EXTENSION[extension.toLowerCase()]
+}
diff --git a/apps/studio/localStores/storageExplorer/StorageExplorerStore.tsx b/apps/studio/localStores/storageExplorer/StorageExplorerStore.tsx
index db987c90349..73bf4d548f7 100644
--- a/apps/studio/localStores/storageExplorer/StorageExplorerStore.tsx
+++ b/apps/studio/localStores/storageExplorer/StorageExplorerStore.tsx
@@ -3,7 +3,7 @@ import { BlobReader, BlobWriter, ZipWriter } from '@zip.js/zip.js'
import { chunk, compact, find, findIndex, has, isEqual, isObject, uniq, uniqBy } from 'lodash'
import { makeAutoObservable } from 'mobx'
import toast from 'react-hot-toast'
-import { toast as UiToast } from 'ui'
+import * as tus from 'tus-js-client'
import {
STORAGE_ROW_STATUS,
@@ -31,7 +31,9 @@ import { StorageObject, listBucketObjects } from 'data/storage/bucket-objects-li
import { Bucket } from 'data/storage/buckets-query'
import { moveStorageObject } from 'data/storage/object-move-mutation'
import { IS_PLATFORM } from 'lib/constants'
+import { lookupMime } from 'lib/mime'
import { PROJECT_ENDPOINT_PROTOCOL } from 'pages/api/constants'
+import { toast as UiToast } from 'ui'
type CachedFile = { id: string; fetchedAt: number; expiresIn: number; url: string }
@@ -75,6 +77,9 @@ class StorageExplorerStore {
sortBy: { column: this.sortBy, order: this.sortByOrder },
}
+ private resumableUploadUrl: string = ''
+ private serviceKey: string = ''
+
/* Supabase client, will get initialized immediately after constructing the instance */
supabaseClient: SupabaseClient<any, 'public', any> = null as any as SupabaseClient<
any,
@@ -86,7 +91,7 @@ class StorageExplorerStore {
private filePreviewCache: CachedFile[] = []
/* For file uploads, from 0 to 1 */
- private uploadProgress: number = 0
+ private uploadProgresses: number[] = []
/* Controllers to abort API calls */
private abortController: AbortController | null = null
@@ -107,6 +112,8 @@ class StorageExplorerStore {
protocol: string = PROJECT_ENDPOINT_PROTOCOL
) {
this.projectRef = projectRef
+ this.resumableUploadUrl = `${IS_PLATFORM ? 'https' : protocol}://${url}/storage/v1/upload/resumable`
+ this.serviceKey = serviceKey
if (serviceKey !== undefined) this.initializeSupabaseClient(serviceKey, url, protocol)
}
@@ -474,6 +481,20 @@ class StorageExplorerStore {
}
}
+ onUploadProgress(toastId?: string) {
+ const totalFiles = this.uploadProgresses.length
+ const progress = this.uploadProgresses.reduce((acc, progress) => acc + progress, 0) / totalFiles
+
+ return toast.loading(
+ <ToastLoader
+ progress={progress * 100}
+ message={`Uploading ${totalFiles} file${totalFiles > 1 ? 's' : ''}...`}
+ description={STORAGE_PROGRESS_INFO_TEXT}
+ />,
+ { id: toastId }
+ )
+ }
+
uploadFiles = async (
files: FileList | DataTransferItemList,
columnIndex: number,
@@ -525,6 +546,23 @@ class StorageExplorerStore {
if (numberOfFilesRejected === filesToUpload.length) return
}
+ const filesWithNonZeroSize = filesWithinUploadLimit.filter((file) => file.size > 0)
+ if (filesWithNonZeroSize.length < filesWithinUploadLimit.length) {
+ const numberOfFilesRejected = filesWithinUploadLimit.length - filesWithNonZeroSize.length
+ toast.error(
+ <div className="flex flex-col gap-y-1">
+ <p className="text-foreground">
+ Failed to upload {numberOfFilesRejected} file{numberOfFilesRejected > 1 ? 's' : ''} as{' '}
+ {numberOfFilesRejected > 1 ? 'their' : 'its'} size
+ {numberOfFilesRejected > 1 ? 's are' : ' is'} 0.
+ </p>
+ </div>,
+ { duration: 8000 }
+ )
+
+ if (numberOfFilesRejected === filesWithinUploadLimit.length) return
+ }
+
// If we're uploading a folder which name already exists in the same folder that we're uploading to
// We sanitize the folder name and let all file uploads through. (This is only via drag drop)
const topLevelFolders: string[] = (this.columns?.[derivedColumnIndex]?.items ?? [])
@@ -551,7 +589,7 @@ class StorageExplorerStore {
return file
})
- this.uploadProgress = 0
+ this.uploadProgresses = new Array(formattedFilesToUpload.length).fill(0)
const uploadedTopLevelFolders: string[] = []
const numberOfFilesToUpload = formattedFilesToUpload.length
let numberOfFilesUploadedSuccess = 0
@@ -562,20 +600,16 @@ class StorageExplorerStore {
.map((folder) => folder.name)
.join('/')
- const toastId = toast.loading(
- <ToastLoader
- progress={0}
- message={`Uploading ${formattedFilesToUpload.length} file${
- formattedFilesToUpload.length > 1 ? 's' : ''
- }...`}
- description={STORAGE_PROGRESS_INFO_TEXT}
- />
- )
+ const toastId = this.onUploadProgress()
// Upload files in batches
- const promises = formattedFilesToUpload.map((file) => {
- const fileOptions = { cacheControl: '3600' }
- const metadata = { mimetype: file.type, size: file.size } as StorageItemMetadata
+ const promises = formattedFilesToUpload.map((file, index) => {
+ const extension = file.name.split('.').pop()
+ const metadata = {
+ mimetype: (file.type || lookupMime(extension)) ?? '',
+ size: file.size,
+ } as StorageItemMetadata
+ const fileOptions = { cacheControl: '3600', contentType: metadata.mimetype }
const isWithinFolder = (file?.path ?? '').split('/').length > 1
const fileName = !isWithinFolder
@@ -586,14 +620,10 @@ class StorageExplorerStore {
/**
* Storage maintains a list of allowed characters, which excludes
* characters such as the narrow no-break space used in Mac screenshots.
- * To preempt errors, replace all non-word characters with underscores.
- * [Joshen] Except backslashes as this will indicate a folder path, and paranthesis
- * since our UI appends them to make duplicate names unique
- */
- const formattedFileName = (unsanitizedFormattedFileName ?? 'unknown').replace(
- /[^\w.-\/()]/g,
- '_'
- )
+ * [Joshen] Am limiting to just replacing nbsp with a blank space instead of
+ * all non-word characters per before
+ * */
+ const formattedFileName = (unsanitizedFormattedFileName ?? 'unknown').replaceAll(/\xA0/g, ' ')
const formattedPathToFile =
pathToFile.length > 0 ? `${pathToFile}/${formattedFileName}` : (formattedFileName as string)
@@ -620,21 +650,46 @@ class StorageExplorerStore {
}
return () => {
- return new Promise<void>(async (resolve) => {
- const { error } = await this.supabaseClient.storage
- .from(this.selectedBucket.name)
- .upload(formattedPathToFile, file, fileOptions)
-
- this.uploadProgress = this.uploadProgress + 1 / formattedFilesToUpload.length
-
- if (error) {
- numberOfFilesUploadedFail += 1
- toast.error(`Failed to upload ${file.name}: ${error.message}`)
- resolve()
- } else {
- numberOfFilesUploadedSuccess += 1
- resolve()
- }
+ return new Promise<void>(async (resolve, reject) => {
+ const upload = new tus.Upload(file, {
+ endpoint: this.resumableUploadUrl,
+ retryDelays: [0, 3000, 5000, 10000, 20000],
+ headers: {
+ authorization: `Bearer ${this.serviceKey}`,
+ },
+ uploadDataDuringCreation: true,
+ removeFingerprintOnSuccess: true,
+ metadata: {
+ bucketName: this.selectedBucket.name,
+ objectName: formattedPathToFile,
+ ...fileOptions,
+ },
+ chunkSize: 6 * 1024 * 1024, // NOTE: it must be set to 6MB
+ onError(error) {
+ numberOfFilesUploadedFail += 1
+ toast.error(`Failed to upload ${file.name}: ${error.message}`)
+ reject(error)
+ },
+ onProgress: (bytesUploaded, bytesTotal) => {
+ const percentage = bytesTotal === 0 ? 0 : bytesUploaded / bytesTotal
+ this.uploadProgresses[index] = percentage
+ this.onUploadProgress(toastId)
+ },
+ onSuccess() {
+ numberOfFilesUploadedSuccess += 1
+ resolve()
+ },
+ })
+
+ // Check if there are any previous uploads to continue.
+ return upload.findPreviousUploads().then(function (previousUploads) {
+ // Found previous uploads so we select the first one.
+ if (previousUploads.length) {
+ upload.resumeFromPreviousUpload(previousUploads[0])
+ }
+
+ upload.start()
+ })
})
}
})
@@ -648,16 +703,7 @@ class StorageExplorerStore {
await batchedPromises.reduce(async (previousPromise, nextBatch) => {
await previousPromise
await Promise.allSettled(nextBatch.map((batch) => batch()))
- toast.loading(
- <ToastLoader
- progress={this.uploadProgress * 100}
- message={`Uploading ${formattedFilesToUpload.length} file${
- formattedFilesToUpload.length > 1 ? 's' : ''
- }...`}
- description={STORAGE_PROGRESS_INFO_TEXT}
- />,
- { id: toastId }
- )
+ this.onUploadProgress(toastId)
}, Promise.resolve())
if (numberOfFilesUploadedSuccess > 0) {
diff --git a/apps/studio/package.json b/apps/studio/package.json
index cdfbeef20c7..66d38335de8 100644
--- a/apps/studio/package.json
+++ b/apps/studio/package.json
@@ -64,6 +64,7 @@
"lodash": "^4.17.21",
"lucide-react": "^0.338.0",
"markdown-table": "^3.0.3",
+ "mime-db": "^1.53.0",
"mobx": "^6.10.2",
"mobx-react-lite": "^4.0.5",
"monaco-editor": "0.33.0",
@@ -102,6 +103,7 @@
"shared-data": "*",
"sql-formatter": "^13.1.0",
"sqlstring": "^2.3.2",
+ "tus-js-client": "^4.1.0",
"ui": "*",
"ui-patterns": "*",
"uuid": "^9.0.1",
@@ -127,6 +129,7 @@
"@types/json-logic-js": "^1.2.1",
"@types/lodash": "^4.14.172",
"@types/markdown-table": "^3.0.0",
+ "@types/mime-db": "^1.43.5",
"@types/papaparse": "^5.3.1",
"@types/randombytes": "^2.0.3",
"@types/react": "^18.2.24",
diff --git a/package-lock.json b/package-lock.json
index 191997e238d..f3f55c9efb2 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1247,6 +1247,7 @@
"lodash": "^4.17.21",
"lucide-react": "^0.338.0",
"markdown-table": "^3.0.3",
+ "mime-db": "^1.53.0",
"mobx": "^6.10.2",
"mobx-react-lite": "^4.0.5",
"monaco-editor": "0.33.0",
@@ -1285,6 +1286,7 @@
"shared-data": "*",
"sql-formatter": "^13.1.0",
"sqlstring": "^2.3.2",
+ "tus-js-client": "^4.1.0",
"ui": "*",
"ui-patterns": "*",
"uuid": "^9.0.1",
@@ -1310,6 +1312,7 @@
"@types/json-logic-js": "^1.2.1",
"@types/lodash": "^4.14.172",
"@types/markdown-table": "^3.0.0",
+ "@types/mime-db": "^1.43.5",
"@types/papaparse": "^5.3.1",
"@types/randombytes": "^2.0.3",
"@types/react": "^18.2.24",
@@ -2309,6 +2312,14 @@
"node": ">=10"
}
},
+ "apps/studio/node_modules/mime-db": {
+ "version": "1.53.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.53.0.tgz",
+ "integrity": "sha512-oHlN/w+3MQ3rba9rqFr6V/ypF10LSkdwUysQL7GkXoTgIWeV+tcXGA852TBxH+gsh8UWoyhR1hKcoMJTuWflpg==",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
"apps/studio/node_modules/openapi-fetch": {
"version": "0.6.2",
"resolved": "https://registry.npmjs.org/openapi-fetch/-/openapi-fetch-0.6.2.tgz",
@@ -14753,6 +14764,12 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@types/mime-db": {
+ "version": "1.43.5",
+ "resolved": "https://registry.npmjs.org/@types/mime-db/-/mime-db-1.43.5.tgz",
+ "integrity": "sha512-/bfTiIUTNPUBnwnYvUxXAre5MhD88jgagLEQiQtIASjU+bwxd8kS/ASDA4a8ufd8m0Lheu6eeMJHEUpLHoJ28A==",
+ "dev": true
+ },
"node_modules/@types/ms": {
"version": "0.7.32",
"license": "MIT"
@@ -17886,6 +17903,15 @@
"version": "0.4.5",
"license": "MIT"
},
+ "node_modules/combine-errors": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/combine-errors/-/combine-errors-3.0.3.tgz",
+ "integrity": "sha512-C8ikRNRMygCwaTx+Ek3Yr+OuZzgZjduCOfSQBjbM8V3MfgcjSTeto/GXP6PAwKvJz/v15b7GHZvx5rOlczFw/Q==",
+ "dependencies": {
+ "custom-error-instance": "2.1.1",
+ "lodash.uniqby": "4.5.0"
+ }
+ },
"node_modules/combined-stream": {
"version": "1.0.8",
"license": "MIT",
@@ -18414,6 +18440,11 @@
"version": "3.1.2",
"license": "MIT"
},
+ "node_modules/custom-error-instance": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/custom-error-instance/-/custom-error-instance-2.1.1.tgz",
+ "integrity": "sha512-p6JFxJc3M4OTD2li2qaHkDCw9SfMw82Ldr6OC9Je1aXiGfhx2W8p3GaoeaGrPJTUN9NirTM/KTxHWMUdR1rsUg=="
+ },
"node_modules/cytoscape": {
"version": "3.26.0",
"license": "MIT",
@@ -24108,7 +24139,6 @@
},
"node_modules/is-stream": {
"version": "2.0.1",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -26091,6 +26121,11 @@
}
}
},
+ "node_modules/js-base64": {
+ "version": "3.7.7",
+ "resolved": "https://registry.npmjs.org/js-base64/-/js-base64-3.7.7.tgz",
+ "integrity": "sha512-7rCnleh0z2CkXhH67J8K1Ytz0b2Y+yxTPL+/KOJoa20hfnVQ/3/T6W/KflYI4bRHRagNeXeU2bkNGI3v1oS/lw=="
+ },
"node_modules/js-cookie": {
"version": "2.2.1",
"license": "MIT"
@@ -26653,10 +26688,50 @@
"version": "4.17.21",
"license": "MIT"
},
+ "node_modules/lodash._baseiteratee": {
+ "version": "4.7.0",
+ "resolved": "https://registry.npmjs.org/lodash._baseiteratee/-/lodash._baseiteratee-4.7.0.tgz",
+ "integrity": "sha512-nqB9M+wITz0BX/Q2xg6fQ8mLkyfF7MU7eE+MNBNjTHFKeKaZAPEzEg+E8LWxKWf1DQVflNEn9N49yAuqKh2mWQ==",
+ "dependencies": {
+ "lodash._stringtopath": "~4.8.0"
+ }
+ },
+ "node_modules/lodash._basetostring": {
+ "version": "4.12.0",
+ "resolved": "https://registry.npmjs.org/lodash._basetostring/-/lodash._basetostring-4.12.0.tgz",
+ "integrity": "sha512-SwcRIbyxnN6CFEEK4K1y+zuApvWdpQdBHM/swxP962s8HIxPO3alBH5t3m/dl+f4CMUug6sJb7Pww8d13/9WSw=="
+ },
+ "node_modules/lodash._baseuniq": {
+ "version": "4.6.0",
+ "resolved": "https://registry.npmjs.org/lodash._baseuniq/-/lodash._baseuniq-4.6.0.tgz",
+ "integrity": "sha512-Ja1YevpHZctlI5beLA7oc5KNDhGcPixFhcqSiORHNsp/1QTv7amAXzw+gu4YOvErqVlMVyIJGgtzeepCnnur0A==",
+ "dependencies": {
+ "lodash._createset": "~4.0.0",
+ "lodash._root": "~3.0.0"
+ }
+ },
+ "node_modules/lodash._createset": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/lodash._createset/-/lodash._createset-4.0.3.tgz",
+ "integrity": "sha512-GTkC6YMprrJZCYU3zcqZj+jkXkrXzq3IPBcF/fIPpNEAB4hZEtXU8zp/RwKOvZl43NUmwDbyRk3+ZTbeRdEBXA=="
+ },
"node_modules/lodash._reinterpolate": {
"version": "3.0.0",
"license": "MIT"
},
+ "node_modules/lodash._root": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/lodash._root/-/lodash._root-3.0.1.tgz",
+ "integrity": "sha512-O0pWuFSK6x4EXhM1dhZ8gchNtG7JMqBtrHdoUFUWXD7dJnNSUze1GuyQr5sOs0aCvgGeI3o/OJW8f4ca7FDxmQ=="
+ },
+ "node_modules/lodash._stringtopath": {
+ "version": "4.8.0",
+ "resolved": "https://registry.npmjs.org/lodash._stringtopath/-/lodash._stringtopath-4.8.0.tgz",
+ "integrity": "sha512-SXL66C731p0xPDC5LZg4wI5H+dJo/EO4KTqOMwLYCH3+FmmfAKJEZCm6ohGpI+T1xwsDsJCfL4OnhorllvlTPQ==",
+ "dependencies": {
+ "lodash._basetostring": "~4.12.0"
+ }
+ },
"node_modules/lodash.camelcase": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz",
@@ -26736,6 +26811,20 @@
"lodash._reinterpolate": "^3.0.0"
}
},
+ "node_modules/lodash.throttle": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/lodash.throttle/-/lodash.throttle-4.1.1.tgz",
+ "integrity": "sha512-wIkUCfVKpVsWo3JSZlc+8MB5it+2AN5W8J7YVMST30UrvcQNZ1Okbj+rbVniijTWE6FGYy4XJq/rHkas8qJMLQ=="
+ },
+ "node_modules/lodash.uniqby": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/lodash.uniqby/-/lodash.uniqby-4.5.0.tgz",
+ "integrity": "sha512-IRt7cfTtHy6f1aRVA5n7kT8rgN3N1nH6MOWLcHfpWG2SH19E3JksLK38MktLxZDhlAjCP9jpIXkOnRXlu6oByQ==",
+ "dependencies": {
+ "lodash._baseiteratee": "~4.7.0",
+ "lodash._baseuniq": "~4.6.0"
+ }
+ },
"node_modules/long": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/long/-/long-5.2.3.tgz",
@@ -34151,6 +34240,21 @@
"react-is": "^16.13.1"
}
},
+ "node_modules/proper-lockfile": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/proper-lockfile/-/proper-lockfile-4.1.2.tgz",
+ "integrity": "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==",
+ "dependencies": {
+ "graceful-fs": "^4.2.4",
+ "retry": "^0.12.0",
+ "signal-exit": "^3.0.2"
+ }
+ },
+ "node_modules/proper-lockfile/node_modules/signal-exit": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",
+ "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="
+ },
"node_modules/properties": {
"version": "1.2.1",
"dev": true,
@@ -34314,7 +34418,6 @@
},
"node_modules/querystringify": {
"version": "2.2.0",
- "devOptional": true,
"license": "MIT"
},
"node_modules/queue-microtask": {
@@ -37176,7 +37279,6 @@
},
"node_modules/requires-port": {
"version": "1.0.0",
- "devOptional": true,
"license": "MIT"
},
"node_modules/resize-observer-polyfill": {
@@ -40501,6 +40603,23 @@
"win32"
]
},
+ "node_modules/tus-js-client": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/tus-js-client/-/tus-js-client-4.1.0.tgz",
+ "integrity": "sha512-e/nC/kJahvNYBcnwcqzuhFIvVELMMpbVXIoOOKdUn74SdQCvJd2JjqV2jZLv2EFOVbV4qLiO0lV7BxBXF21b6Q==",
+ "dependencies": {
+ "buffer-from": "^1.1.2",
+ "combine-errors": "^3.0.3",
+ "is-stream": "^2.0.0",
+ "js-base64": "^3.7.2",
+ "lodash.throttle": "^4.1.1",
+ "proper-lockfile": "^4.1.2",
+ "url-parse": "^1.5.7"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/typanion": {
"version": "3.14.0",
"resolved": "https://registry.npmjs.org/typanion/-/typanion-3.14.0.tgz",
@@ -41101,7 +41220,6 @@
},
"node_modules/url-parse": {
"version": "1.5.10",
- "devOptional": true,
"license": "MIT",
"dependencies": {
"querystringify": "^2.1.1",