mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-25 19:19:28 +00:00
feat(file): optimize upload and transcoding status polling with batch api (#512)
* feat(file): optimize upload and transcoding status polling with batch api * fix(webui): throttle search invalidation during upload and fix stuck 100% progress ring * fix(webui): deduplicate upload search invalidation and stabilize batch polling
This commit is contained in:
@@ -13,6 +13,7 @@ import type {
|
||||
AssetInfo,
|
||||
CollectionInfo,
|
||||
CreateUploadTaskRequest,
|
||||
FileNode,
|
||||
SearchCondition,
|
||||
SearchSort,
|
||||
ShareLinkInfo,
|
||||
@@ -57,6 +58,7 @@ import { FileBrowserGridView } from './grid-view'
|
||||
import { FileBrowserListView } from './list-view'
|
||||
import { FileBrowserToolbar } from './toolbar'
|
||||
import { useFileActions } from './use-file-actions'
|
||||
import { useBatchFileStatus } from '@/ui/hooks/use-batch-file-status'
|
||||
|
||||
interface FileBrowserProps {
|
||||
teamId: string
|
||||
@@ -260,6 +262,8 @@ export function FileBrowser({
|
||||
return [...filteredLocal, ...files]
|
||||
}, [files, localUploadingFiles, fileProgress])
|
||||
|
||||
useBatchFileStatus({ teamId, items: displayedFiles })
|
||||
|
||||
const activePreviewItem = useMemo(() => {
|
||||
if (selectedIds.size === 0) return null
|
||||
if (internalSelectedItem && selectedIds.has(internalSelectedItem.id!)) {
|
||||
@@ -533,6 +537,47 @@ export function FileBrowser({
|
||||
},
|
||||
})
|
||||
|
||||
const throttledInvalidateSearch = useMemo(() => {
|
||||
let timer: ReturnType<typeof setTimeout> | null = null
|
||||
let lastRun = 0
|
||||
const THROTTLE_MS = 2500
|
||||
|
||||
const run = () => {
|
||||
const now = Date.now()
|
||||
if (now - lastRun >= THROTTLE_MS) {
|
||||
lastRun = now
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
} else if (!timer) {
|
||||
timer = setTimeout(
|
||||
() => {
|
||||
timer = null
|
||||
lastRun = Date.now()
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
},
|
||||
THROTTLE_MS - (now - lastRun),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const cancel = () => {
|
||||
if (timer) {
|
||||
clearTimeout(timer)
|
||||
timer = null
|
||||
}
|
||||
}
|
||||
|
||||
const reset = () => {
|
||||
cancel()
|
||||
lastRun = Date.now()
|
||||
}
|
||||
|
||||
return Object.assign(run, { cancel, reset })
|
||||
}, [queryClient, teamId, assetId])
|
||||
|
||||
const $createUploadTask = client.api.teams[':teamId'].upload.tasks.$post
|
||||
const { mutate: createUploadTaskMutation } = useMutation<
|
||||
InferResponseType<typeof $createUploadTask>,
|
||||
@@ -623,13 +668,19 @@ export function FileBrowser({
|
||||
setLocalUploadingFiles((prev) => [...newLocalFiles, ...prev])
|
||||
}
|
||||
|
||||
// Invalidate queries immediately so any newly created folders appear
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
// Invalidate queries immediately only if newly created folders appear
|
||||
const hasCreatedFolders = (variables.json.files as FileNode[]).some(
|
||||
(f) => f.children && f.children.length > 0,
|
||||
)
|
||||
if (hasCreatedFolders) {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
}
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['teams', teamId, 'upload', 'tasks'],
|
||||
})
|
||||
throttledInvalidateSearch.reset()
|
||||
|
||||
try {
|
||||
await uploadFilesWithUppy({
|
||||
@@ -639,14 +690,13 @@ export function FileBrowser({
|
||||
storageBackend: (data.storageBackend as 's3' | 'local') || 'local',
|
||||
createdAssets: data.createdAssets,
|
||||
presignedUrls: data.presignedUrls,
|
||||
onFileFinished: async (fileId) => {
|
||||
await queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
onFileFinished: (fileId) => {
|
||||
setLocalUploadingFiles((prev) => prev.filter((f) => f.id !== fileId))
|
||||
throttledInvalidateSearch()
|
||||
},
|
||||
})
|
||||
} finally {
|
||||
throttledInvalidateSearch.cancel()
|
||||
if (batchIds) {
|
||||
setLocalUploadingFiles((prev) => prev.filter((f) => !batchIds!.has(f.id!)))
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { FileCard } from './file-card'
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { useUploadStore } from '@/ui/stores/upload'
|
||||
|
||||
vi.mock('@dnd-kit/react', () => ({
|
||||
useDraggable: () => ({
|
||||
@@ -341,6 +342,35 @@ describe('FileCard', () => {
|
||||
expect(screen.queryByText(/Alice/i)).toBeNull()
|
||||
})
|
||||
|
||||
it('transitions from uploading to preparing circle when upload store marks file completed', () => {
|
||||
useUploadStore.setState({
|
||||
fileProgress: {
|
||||
'file-uploading': {
|
||||
fileId: 'file-uploading',
|
||||
name: 'clip.mp4',
|
||||
loaded: 1000,
|
||||
total: 1000,
|
||||
status: 'completed',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const uploadingItem: AssetInfo = {
|
||||
...fileItem,
|
||||
id: 'file-uploading',
|
||||
status: 'uploading',
|
||||
creator: { id: 'u1', name: 'Alice' },
|
||||
} as AssetInfo
|
||||
|
||||
renderComponent({ item: uploadingItem })
|
||||
|
||||
expect(screen.queryByTestId('file-card-preview-media')).toBeNull()
|
||||
const circle = screen.getByTestId('file-card-preparing-circle')
|
||||
expect(circle.tagName.toLowerCase()).toBe('svg')
|
||||
expect(screen.getByText(/Preparing|准备中/i)).toBeTruthy()
|
||||
expect(screen.queryByText(/Alice/i)).toBeNull()
|
||||
})
|
||||
|
||||
it('shows a preparing circle and "Preparing..." when processing without a preview yet', () => {
|
||||
const processingItem: AssetInfo = {
|
||||
...fileItem,
|
||||
|
||||
@@ -119,11 +119,6 @@ export function FileCard({
|
||||
: 0
|
||||
: 0
|
||||
|
||||
const shouldPoll =
|
||||
(item.type === 'file' || item.type === 'version_stack') &&
|
||||
!!teamId &&
|
||||
(item.status === 'uploading' || item.status === 'uploaded' || item.status === 'processing')
|
||||
|
||||
const { data: polledItem } = useQuery({
|
||||
queryKey: ['file', teamId, item.id],
|
||||
queryFn: async () => {
|
||||
@@ -133,13 +128,7 @@ export function FileCard({
|
||||
if (!res.ok) throw new Error('failed to fetch file')
|
||||
return (await res.json()) as unknown as AssetInfo
|
||||
},
|
||||
enabled: shouldPoll,
|
||||
refetchInterval: (query: unknown) => {
|
||||
const data = (query as { state: { data: { status?: string } } }).state.data
|
||||
return data?.status === 'processed' || data?.status === 'failed' || data?.status === 'error'
|
||||
? false
|
||||
: 1000
|
||||
},
|
||||
enabled: false,
|
||||
})
|
||||
|
||||
const displayItem = useMemo(() => {
|
||||
@@ -277,16 +266,16 @@ export function FileCard({
|
||||
// since the poster/sprite are generated and persisted ahead of the proxy transcodes.
|
||||
const hasPreview = Boolean(displayItem.preview?.thumbnailUrl || displayItem.preview?.spriteUrl)
|
||||
const isFailed = displayItem.status === 'failed'
|
||||
const isProcessing = displayItem.status === 'processing' || displayItem.status === 'uploaded'
|
||||
const isUploadDone = fileUploadState?.status === 'completed' || uploadPercent >= 100
|
||||
const isUploading = displayItem.status === 'uploading' && !isUploadDone
|
||||
const isProcessing =
|
||||
displayItem.status === 'processing' ||
|
||||
displayItem.status === 'uploaded' ||
|
||||
(displayItem.status === 'uploading' && isUploadDone)
|
||||
|
||||
// While uploading/transcoding, the creator row is replaced by a short status label so the real
|
||||
// date/author only appears once the asset is ready or failed.
|
||||
const statusText =
|
||||
displayItem.status === 'uploading'
|
||||
? m.uploading()
|
||||
: displayItem.status === 'uploaded' || displayItem.status === 'processing'
|
||||
? m.preparing()
|
||||
: null
|
||||
const statusText = isUploading ? m.uploading() : isProcessing ? m.preparing() : null
|
||||
|
||||
const failedErrorMessage = displayItem.media?.error || m.processing_failed()
|
||||
|
||||
@@ -393,7 +382,7 @@ export function FileCard({
|
||||
</div>
|
||||
|
||||
<div className="relative aspect-square overflow-hidden bg-muted/30">
|
||||
{displayItem.status === 'uploading' ? (
|
||||
{isUploading ? (
|
||||
<div className="flex h-full w-full items-center justify-center bg-background/50">
|
||||
<ProgressCircle progress={uploadPercent} className="w-16 h-16 z-10" />
|
||||
</div>
|
||||
|
||||
@@ -74,11 +74,6 @@ export function FileListItem({
|
||||
: 0
|
||||
: 0
|
||||
|
||||
const shouldPoll =
|
||||
(item.type === 'file' || item.type === 'version_stack') &&
|
||||
!!teamId &&
|
||||
(item.status === 'uploading' || item.status === 'uploaded' || item.status === 'processing')
|
||||
|
||||
const { data: polledItem } = useQuery({
|
||||
queryKey: ['file', teamId, item.id],
|
||||
queryFn: async () => {
|
||||
@@ -88,13 +83,7 @@ export function FileListItem({
|
||||
if (!res.ok) throw new Error('failed to fetch file')
|
||||
return (await res.json()) as unknown as AssetInfo
|
||||
},
|
||||
enabled: shouldPoll,
|
||||
refetchInterval: (query: unknown) => {
|
||||
const data = (query as { state: { data: { status?: string } } }).state.data
|
||||
return data?.status === 'processed' || data?.status === 'failed' || data?.status === 'error'
|
||||
? false
|
||||
: 1000
|
||||
},
|
||||
enabled: false,
|
||||
})
|
||||
|
||||
const displayItem = useMemo(() => {
|
||||
@@ -111,6 +100,9 @@ export function FileListItem({
|
||||
return polledItem || item
|
||||
}, [item, polledItem])
|
||||
|
||||
const isUploadDone = fileUploadState?.status === 'completed' || uploadPercent >= 100
|
||||
const isUploading = displayItem.status === 'uploading' && !isUploadDone
|
||||
|
||||
// dnd-kit hooks
|
||||
const { ref: setDraggableRef, isDragging: isDraggableDragging } = useDraggable({
|
||||
id: `browser:${displayItem.id!}`,
|
||||
@@ -220,7 +212,7 @@ export function FileListItem({
|
||||
className="h-4 w-4 shrink-0 data-[state=checked]:bg-primary data-[state=checked]:border-primary"
|
||||
/>
|
||||
<div className="w-8 h-8 shrink-0 flex items-center justify-center bg-muted rounded overflow-hidden">
|
||||
{displayItem.status === 'uploading' ? (
|
||||
{isUploading ? (
|
||||
<ProgressCircle progress={uploadPercent} className="w-7 h-7" />
|
||||
) : displayItem.status === 'failed' && !displayItem.preview?.thumbnailUrl ? (
|
||||
<AlertCircle className="h-4 w-4 text-destructive" />
|
||||
|
||||
@@ -5,7 +5,7 @@ import { usePermissions } from '@/ui/hooks/use-permissions'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { useUploadStore } from '@/ui/stores/upload'
|
||||
import { uploadFilesWithUppy } from '@/ui/lib/uploader'
|
||||
import type { AssetInfo, CreateUploadTaskRequest } from '@shumai/dtos'
|
||||
import type { AssetInfo, CreateUploadTaskRequest, FileNode } from '@shumai/dtos'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import type { InferRequestType, InferResponseType } from 'hono/client'
|
||||
import { formatSize } from '@/ui/lib/format'
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
Plus,
|
||||
Upload,
|
||||
} from 'lucide-react'
|
||||
import React, { useRef, useState } from 'react'
|
||||
import React, { useMemo, useRef, useState } from 'react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
import { toast } from 'sonner'
|
||||
import { ulid } from 'ulid'
|
||||
@@ -54,6 +54,7 @@ import { FileCard } from './file-card'
|
||||
import { FolderCard } from './folder-card'
|
||||
import { useFileActions } from './use-file-actions'
|
||||
import { MobileFileBrowserContentSkeleton } from '../loading-skeletons'
|
||||
import { useBatchFileStatus } from '@/ui/hooks/use-batch-file-status'
|
||||
|
||||
export interface MobileFileBrowserProps {
|
||||
teamId: string
|
||||
@@ -125,6 +126,7 @@ export function MobileFileBrowser({
|
||||
allowDownload = true,
|
||||
}: MobileFileBrowserProps) {
|
||||
const queryClient = useQueryClient()
|
||||
useBatchFileStatus({ teamId, items: files })
|
||||
const { canEdit, canAdmin } = usePermissions(projectId)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const folderInputRef = useRef<HTMLInputElement>(null)
|
||||
@@ -200,6 +202,47 @@ export function MobileFileBrowser({
|
||||
// Upload actions
|
||||
const startTask = useUploadStore((state) => state.startTask)
|
||||
|
||||
const throttledInvalidateSearch = useMemo(() => {
|
||||
let timer: ReturnType<typeof setTimeout> | null = null
|
||||
let lastRun = 0
|
||||
const THROTTLE_MS = 2500
|
||||
|
||||
const run = () => {
|
||||
const now = Date.now()
|
||||
if (now - lastRun >= THROTTLE_MS) {
|
||||
lastRun = now
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
} else if (!timer) {
|
||||
timer = setTimeout(
|
||||
() => {
|
||||
timer = null
|
||||
lastRun = Date.now()
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
},
|
||||
THROTTLE_MS - (now - lastRun),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const cancel = () => {
|
||||
if (timer) {
|
||||
clearTimeout(timer)
|
||||
timer = null
|
||||
}
|
||||
}
|
||||
|
||||
const reset = () => {
|
||||
cancel()
|
||||
lastRun = Date.now()
|
||||
}
|
||||
|
||||
return Object.assign(run, { cancel, reset })
|
||||
}, [queryClient, teamId, assetId])
|
||||
|
||||
const $createUploadTask = client.api.teams[':teamId'].upload.tasks.$post
|
||||
const { mutate: createUploadTaskMutation } = useMutation<
|
||||
InferResponseType<typeof $createUploadTask>,
|
||||
@@ -218,7 +261,7 @@ export function MobileFileBrowser({
|
||||
onError: () => {
|
||||
toast.error(m.failed_upload_file())
|
||||
},
|
||||
onSuccess: async (data, _variables, context) => {
|
||||
onSuccess: async (data, variables, context) => {
|
||||
const currentFiles = context?.files || []
|
||||
const filesProgressInfo = currentFiles
|
||||
.map((f) => {
|
||||
@@ -240,22 +283,32 @@ export function MobileFileBrowser({
|
||||
startTask(data.taskId, taskName, filesProgressInfo)
|
||||
}
|
||||
|
||||
queryClient.invalidateQueries({ queryKey: ['search', teamId, assetId] })
|
||||
const hasCreatedFolders = (variables.json.files as FileNode[]).some(
|
||||
(f) => f.children && f.children.length > 0,
|
||||
)
|
||||
if (hasCreatedFolders) {
|
||||
queryClient.invalidateQueries({ queryKey: ['search', teamId, assetId] })
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'upload', 'tasks'] })
|
||||
throttledInvalidateSearch.reset()
|
||||
|
||||
await uploadFilesWithUppy({
|
||||
files: currentFiles,
|
||||
taskId: data.taskId!,
|
||||
teamId: teamId!,
|
||||
storageBackend: (data.storageBackend as 's3' | 'local') || 'local',
|
||||
createdAssets: data.createdAssets,
|
||||
presignedUrls: data.presignedUrls,
|
||||
onFileFinished: async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: ['search', teamId, assetId] })
|
||||
},
|
||||
})
|
||||
queryClient.invalidateQueries({ queryKey: ['search', teamId, assetId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'upload', 'tasks'] })
|
||||
try {
|
||||
await uploadFilesWithUppy({
|
||||
files: currentFiles,
|
||||
taskId: data.taskId!,
|
||||
teamId: teamId!,
|
||||
storageBackend: (data.storageBackend as 's3' | 'local') || 'local',
|
||||
createdAssets: data.createdAssets,
|
||||
presignedUrls: data.presignedUrls,
|
||||
onFileFinished: () => {
|
||||
throttledInvalidateSearch()
|
||||
},
|
||||
})
|
||||
} finally {
|
||||
throttledInvalidateSearch.cancel()
|
||||
queryClient.invalidateQueries({ queryKey: ['search', teamId, assetId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'upload', 'tasks'] })
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user