Skip to content

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

Add self-remediation for orphan prefixes and refactor delete objects to be a singular request (#38753)

Joshen Limf2ba7f027054
diff --git a/apps/studio/data/storage/bucket-prefix-delete-mutation.ts b/apps/studio/data/storage/bucket-prefix-delete-mutation.ts
new file mode 100644
index 00000000000..d2b7d37f1ae
--- /dev/null
+++ b/apps/studio/data/storage/bucket-prefix-delete-mutation.ts
@@ -0,0 +1,36 @@
+import { executeSql } from 'data/sql/execute-sql-query'
+
+/**
+ * [Joshen] JFYI this is solely being used in storage-explorer.tsx and hence doesn't have a useMutation hook
+ * It's solely supposed to aid users to self-remediate a known issue with orphan prefixes so the condition to
+ * clean the prefix from the storage.prefixes is intentionally strict here (e.g only level 1)
+ *
+ * We can make this a bit more loose if needed, but ideal case is that this issue is addressed at the storage level
+ */
+
+type DeleteBucketPrefixParams = {
+ projectRef?: string
+ connectionString?: string
+ bucketId?: string
+ prefix?: string
+}
+export const deleteBucketPrefix = async (
+ { projectRef, connectionString, bucketId, prefix }: DeleteBucketPrefixParams,
+ signal?: AbortSignal
+) => {
+ if (!projectRef) throw new Error('projectRef is required')
+ if (!connectionString) throw new Error('connectionString is required')
+ if (!bucketId) throw new Error('bucketId is required')
+ if (!prefix) throw new Error('prefix is required')
+
+ const sql = /* SQL */ `
+select storage.delete_prefix('${bucketId}', '${prefix}');
+`.trim()
+
+ const { result } = await executeSql(
+ { projectRef, connectionString, sql, queryKey: ['delete-bucket-prefix'] },
+ signal
+ )
+
+ return result
+}
diff --git a/apps/studio/state/storage-explorer.tsx b/apps/studio/state/storage-explorer.tsx
index ece6faa3fb4..fbeb9a547be 100644
--- a/apps/studio/state/storage-explorer.tsx
+++ b/apps/studio/state/storage-explorer.tsx
@@ -44,6 +44,7 @@ import { getQueryClient } from 'data/query-client'
import { deleteBucketObject } from 'data/storage/bucket-object-delete-mutation'
import { downloadBucketObject } from 'data/storage/bucket-object-download-mutation'
import { listBucketObjects, StorageObject } from 'data/storage/bucket-objects-list-mutation'
+import { deleteBucketPrefix } from 'data/storage/bucket-prefix-delete-mutation'
import { Bucket } from 'data/storage/buckets-query'
import { moveStorageObject } from 'data/storage/object-move-mutation'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
@@ -79,10 +80,12 @@ if (typeof window !== 'undefined') {
function createStorageExplorerState({
projectRef,
+ connectionString,
resumableUploadUrl,
supabaseClient,
}: {
projectRef: string
+ connectionString: string
resumableUploadUrl: string
supabaseClient?: () => Promise<SupabaseClient<any, 'public', any>>
}) {
@@ -93,6 +96,7 @@ function createStorageExplorerState({
const state = proxy({
projectRef,
+ connectionString,
supabaseClient,
resumableUploadUrl,
uploadProgresses: [] as UploadProgress[],
@@ -591,7 +595,18 @@ function createStorageExplorerState({
try {
const isDeleteFolder = true
const files = await state.getAllItemsAlongFolder(folder)
- await state.deleteFiles({ files: files as any[], isDeleteFolder })
+
+ if (files.length === 0) {
+ // [Joshen] This is to self-remediate orphan prefixes
+ await deleteBucketPrefix({
+ projectRef: state.projectRef,
+ connectionString: state.connectionString,
+ bucketId: state.selectedBucket.id,
+ prefix: folder.path,
+ })
+ } else {
+ await state.deleteFiles({ files: files as any[], isDeleteFolder })
+ }
state.popColumnAtIndex(folder.columnIndex)
state.popOpenedFoldersAtIndex(folder.columnIndex - 1)
@@ -607,7 +622,6 @@ function createStorageExplorerState({
await state.refetchAllOpenedFolders()
state.setSelectedItemsToDelete([])
-
toast.success(`Successfully deleted ${folder.name}`)
} catch (error: any) {
toast.error(`Failed to delete folder: ${error.message}`)
@@ -1411,7 +1425,6 @@ function createStorageExplorerState({
isDeleteFolder?: boolean
}) => {
state.setSelectedFilePreview(undefined)
- let progress = 0
// If every file has the 'prefix' property, then just construct the prefix
// directly (from delete folder). Otherwise go by the opened folders.
@@ -1429,38 +1442,14 @@ function createStorageExplorerState({
state.clearSelectedItems()
- const toastId = toast(
- <SonnerProgress progress={0} message={`Deleting ${prefixes.length} file(s)...`} />,
- { closeButton: false, position: 'top-right' }
- )
+ const toastId = toast.loading(`Deleting ${prefixes.length} file(s)...`)
- // batch BATCH_SIZE prefixes per request
- const batches = chunk(prefixes, BATCH_SIZE).map((batch) => () => {
- progress = progress + batch.length / prefixes.length
- return deleteBucketObject({
- projectRef: state.projectRef,
- bucketId: state.selectedBucket.id,
- paths: batch as string[],
- })
+ await deleteBucketObject({
+ projectRef: state.projectRef,
+ bucketId: state.selectedBucket.id,
+ paths: prefixes,
})
- // make BATCH_SIZE requests at the same time
- await chunk(batches, BATCH_SIZE).reduce(async (previousPromise, nextBatch) => {
- await previousPromise
- await Promise.all(nextBatch.map((batch) => batch()))
- toast(
- <SonnerProgress
- progress={progress * 100}
- message={`Deleting ${prefixes.length} file(s)...`}
- />,
- {
- id: toastId,
- closeButton: false,
- position: 'top-right',
- }
- )
- }, Promise.resolve())
-
if (!isDeleteFolder) {
// If parent folders are empty, reinstate .emptyFolderPlaceholder to persist them
const parentFolderPrefixes = uniq(
@@ -1790,6 +1779,7 @@ type StorageExplorerState = ReturnType<typeof createStorageExplorerState>
const DEFAULT_STATE_CONFIG = {
projectRef: '',
+ connectionString: '',
resumableUploadUrl: '',
supabaseClient: undefined,
}
@@ -1823,6 +1813,7 @@ export const StorageExplorerStateContextProvider = ({ children }: PropsWithChild
setState(
createStorageExplorerState({
projectRef: project?.ref ?? '',
+ connectionString: project.connectionString ?? '',
supabaseClient: async () => {
try {
const data = await getTemporaryAPIKey({ projectRef: project.ref })