Skip to content

Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.

feat(files): batch active task polling

johavene36af62b4946
diff --git a/backend/src/applications/files/constants/routes.ts b/backend/src/applications/files/constants/routes.ts
index 965ba6f2..d234a0d5 100644
--- a/backend/src/applications/files/constants/routes.ts
+++ b/backend/src/applications/files/constants/routes.ts
@@ -8,6 +8,7 @@ export const FILES_ROUTE = {
TASKS: 'tasks',
TASKS_CANCEL: 'cancel',
TASKS_DOWNLOAD: 'download',
+ TASKS_POLL: 'poll',
RECENTS: 'recents',
SEARCH: 'search',
INDEXING: 'indexing',
@@ -26,6 +27,7 @@ export const API_FILES_TASK_OPERATION_DECOMPRESS = `${API_FILES_TASK_OPERATION}/
export const API_FILES_TASKS = `${FILES_ROUTE.BASE}/${FILES_ROUTE.TASKS}`
export const API_FILES_TASKS_CANCEL = `${API_FILES_TASKS}/${FILES_ROUTE.TASKS_CANCEL}`
export const API_FILES_TASKS_DOWNLOAD = `${FILES_ROUTE.BASE}/${FILES_ROUTE.TASKS}/${FILES_ROUTE.TASKS_DOWNLOAD}`
+export const API_FILES_TASKS_POLL = `${API_FILES_TASKS}/${FILES_ROUTE.TASKS_POLL}`
export const API_FILES_RECENTS = `${FILES_ROUTE.BASE}/${FILES_ROUTE.RECENTS}`
export const API_FILES_SEARCH = `${FILES_ROUTE.BASE}/${FILES_ROUTE.SEARCH}`
export const API_FILES_INDEXING = `${FILES_ROUTE.BASE}/${FILES_ROUTE.INDEXING}`
diff --git a/backend/src/applications/files/dto/file-tasks-poll.dto.ts b/backend/src/applications/files/dto/file-tasks-poll.dto.ts
new file mode 100644
index 00000000..b800edb2
--- /dev/null
+++ b/backend/src/applications/files/dto/file-tasks-poll.dto.ts
@@ -0,0 +1,7 @@
+import { IsArray, IsString } from 'class-validator'
+
+export class FileTasksPollDto {
+ @IsArray()
+ @IsString({ each: true })
+ trackedIds: string[]
+}
diff --git a/backend/src/applications/files/files-tasks.controller.spec.ts b/backend/src/applications/files/files-tasks.controller.spec.ts
index 95334eb1..0b49579d 100644
--- a/backend/src/applications/files/files-tasks.controller.spec.ts
+++ b/backend/src/applications/files/files-tasks.controller.spec.ts
@@ -7,11 +7,12 @@ import { Mock } from 'vitest'
describe(FilesTasksController.name, () => {
let controller: FilesTasksController
- let filesTasksManager: { getTasks: Mock; deleteTasks: Mock; downloadArchive: Mock }
+ let filesTasksManager: { getTasks: Mock; pollTasks: Mock; deleteTasks: Mock; downloadArchive: Mock }
beforeAll(async () => {
filesTasksManager = {
getTasks: vi.fn(),
+ pollTasks: vi.fn(),
deleteTasks: vi.fn(),
downloadArchive: vi.fn()
}
@@ -66,8 +67,22 @@ describe(FilesTasksController.name, () => {
expect(result).toBe(expected)
})
+ it('pollTasks should delegate tracked task ids to FilesTasksManager', () => {
+ const user = { id: 'user-3' } as any
+ const dto = { trackedIds: ['task-a', 'task-b'] }
+ const expected = { active: [], ended: [], missingIds: ['task-a', 'task-b'] }
+
+ filesTasksManager.pollTasks.mockReturnValueOnce(expected)
+
+ const result = controller.pollTasks(user, dto)
+
+ expect(filesTasksManager.pollTasks).toHaveBeenCalledTimes(1)
+ expect(filesTasksManager.pollTasks).toHaveBeenCalledWith('user-3', dto.trackedIds)
+ expect(result).toBe(expected)
+ })
+
it('deleteTasks should call FilesTasksManager.deleteTasks with user and taskId and return the value', () => {
- const user = { id: 'user-3', name: 'Alice' } as any
+ const user = { id: 'user-4', name: 'Alice' } as any
const taskId = 'task-del-1'
const expected = { deleted: true }
@@ -81,7 +96,7 @@ describe(FilesTasksController.name, () => {
})
it('deleteTasks without taskId must pass undefined', () => {
- const user = { id: 'user-4' } as any
+ const user = { id: 'user-5' } as any
const expected = { deletedAll: true }
filesTasksManager.deleteTasks.mockReturnValueOnce(expected)
@@ -94,7 +109,7 @@ describe(FilesTasksController.name, () => {
})
it('downloadTaskFile should delegate to FilesTasksManager.downloadArchive and return the StreamableFile', async () => {
- const user = { id: 'user-5' } as any
+ const user = { id: 'user-6' } as any
const taskId = 'task-dl-42'
const req = {} as any
const res = {} as any
diff --git a/backend/src/applications/files/files-tasks.controller.ts b/backend/src/applications/files/files-tasks.controller.ts
index b67d5fd6..862ac07f 100644
--- a/backend/src/applications/files/files-tasks.controller.ts
+++ b/backend/src/applications/files/files-tasks.controller.ts
@@ -1,9 +1,11 @@
-import { Controller, Delete, Get, Param, Post, Req, Res, StreamableFile } from '@nestjs/common'
+import { Body, Controller, Delete, Get, Param, Post, Req, Res, StreamableFile } from '@nestjs/common'
import { FastifyReply } from 'fastify'
import { FastifySpaceRequest } from '../spaces/interfaces/space-request.interface'
import { GetUser } from '../users/decorators/user.decorator'
import { UserModel } from '../users/models/user.model'
import { API_FILES_TASKS, FILES_ROUTE } from './constants/routes'
+import { FileTasksPollDto } from './dto/file-tasks-poll.dto'
+import type { FileTasksPollResponse } from './interfaces/file-task.interface'
import { FilesTasksManager } from './services/files-tasks-manager.service'
@Controller(API_FILES_TASKS)
@@ -15,6 +17,11 @@ export class FilesTasksController {
return this.filesTasksManager.getTasks(user.id, taskId)
}
+ @Post(FILES_ROUTE.TASKS_POLL)
+ pollTasks(@GetUser() user: UserModel, @Body() fileTasksPollDto: FileTasksPollDto): Promise<FileTasksPollResponse> {
+ return this.filesTasksManager.pollTasks(user.id, fileTasksPollDto.trackedIds)
+ }
+
@Delete(':id?')
deleteTasks(@GetUser() user: UserModel, @Param('id') taskId?: string) {
return this.filesTasksManager.deleteTasks(user, taskId)
diff --git a/backend/src/applications/files/interfaces/file-task.interface.ts b/backend/src/applications/files/interfaces/file-task.interface.ts
new file mode 100644
index 00000000..6cdb7c1e
--- /dev/null
+++ b/backend/src/applications/files/interfaces/file-task.interface.ts
@@ -0,0 +1,7 @@
+import type { FileTask } from '../models/file-task'
+
+export interface FileTasksPollResponse {
+ active: FileTask[]
+ ended: FileTask[]
+ missingIds: string[]
+}
diff --git a/backend/src/applications/files/services/files-tasks-manager.service.spec.ts b/backend/src/applications/files/services/files-tasks-manager.service.spec.ts
index 420749c9..f9854927 100644
--- a/backend/src/applications/files/services/files-tasks-manager.service.spec.ts
+++ b/backend/src/applications/files/services/files-tasks-manager.service.spec.ts
@@ -393,6 +393,45 @@ describe(FilesTasksManager.name, () => {
expect(tasks).toEqual([{ id: 'task-1' }, { id: 'task-2' }])
})
+ it('should ignore tasks that expire between cache key lookup and batch loading', async () => {
+ cache.keys.mockResolvedValueOnce([`${CACHE_TASK_PREFIX}-16-task-1`, `${CACHE_TASK_PREFIX}-16-expired`])
+ cache.mget.mockResolvedValueOnce([{ id: 'task-1' }, undefined])
+
+ const tasks = await filesTasksManager.getTasks(16)
+
+ expect(tasks).toEqual([{ id: 'task-1' }])
+ })
+
+ it('should classify active, ended and missing tracked tasks when polling', async () => {
+ cacheStore.set(`${CACHE_TASK_PREFIX}-17-task-pending`, {
+ id: 'task-pending',
+ status: FileTaskStatus.PENDING
+ })
+ cacheStore.set(`${CACHE_TASK_PREFIX}-17-task-queued`, {
+ id: 'task-queued',
+ status: FileTaskStatus.QUEUED
+ })
+ cacheStore.set(`${CACHE_TASK_PREFIX}-17-task-success`, {
+ id: 'task-success',
+ status: FileTaskStatus.SUCCESS
+ })
+ cacheStore.set(`${CACHE_TASK_PREFIX}-17-task-untracked`, {
+ id: 'task-untracked',
+ status: FileTaskStatus.ERROR
+ })
+
+ const result = await filesTasksManager.pollTasks(17, ['task-pending', 'task-success', 'task-missing'])
+
+ expect(result).toEqual({
+ active: [
+ { id: 'task-pending', status: FileTaskStatus.PENDING },
+ { id: 'task-queued', status: FileTaskStatus.QUEUED }
+ ],
+ ended: [{ id: 'task-success', status: FileTaskStatus.SUCCESS }],
+ missingIds: ['task-missing']
+ })
+ })
+
it('should delete completed task, remove archive file and delete cache entry', async () => {
const removeFilesSpy = vi.spyOn(filesUtils, 'removeFiles').mockResolvedValueOnce(undefined)
const stopWatchSpy = vi.spyOn(filesTasksManager as any, 'stopWatch').mockResolvedValueOnce(undefined)
diff --git a/backend/src/applications/files/services/files-tasks-manager.service.ts b/backend/src/applications/files/services/files-tasks-manager.service.ts
index dbd9890c..9f057e02 100644
--- a/backend/src/applications/files/services/files-tasks-manager.service.ts
+++ b/backend/src/applications/files/services/files-tasks-manager.service.ts
@@ -11,6 +11,7 @@ import { CACHE_TASK_CANCEL_PREFIX, CACHE_TASK_PREFIX, CACHE_TASK_TTL } from '../
import { FILE_OPERATION } from '../constants/operations'
import { FileTaskEvent } from '../events/file-events'
import type { FileTaskQueueItem } from '../interfaces/file-task-queue.interface'
+import type { FileTasksPollResponse } from '../interfaces/file-task.interface'
import { FileTask, FileTaskProps, FileTaskStatus } from '../models/file-task'
import { countDirEntries, dirName, fileName, fileSize, isPathExists, isPathIsDir, removeFiles } from '../utils/files'
import { SendFile } from '../utils/send-file'
@@ -69,10 +70,27 @@ export class FilesTasksManager implements OnModuleDestroy {
throw new HttpException('Task not found', HttpStatus.NOT_FOUND)
} else {
const keys = await this.cache.keys(cacheKey)
- return keys.length ? await this.cache.mget(keys) : []
+ const tasks: FileTask[] = keys.length ? await this.cache.mget(keys) : []
+ return tasks.filter((task: FileTask | null | undefined): task is FileTask => task != null)
}
}
+ async pollTasks(userId: number, trackedIds: string[]): Promise<FileTasksPollResponse> {
+ const tasks = (await this.getTasks(userId)) as FileTask[]
+ const trackedTaskIds = new Set(trackedIds)
+ const active: FileTask[] = []
+ const ended: FileTask[] = []
+ for (const task of tasks) {
+ if (this.isActiveStatus(task.status)) {
+ active.push(task)
+ } else if (trackedTaskIds.has(task.id)) {
+ ended.push(task)
+ }
+ trackedTaskIds.delete(task.id)
+ }
+ return { active, ended, missingIds: [...trackedTaskIds] }
+ }
+
async deleteTasks(user: UserModel, taskId?: string): Promise<void> {
const cacheKey = FilesTasksManager.getCacheKey(user.id, taskId)
const keys: string[] = taskId ? [cacheKey] : await this.cache.keys(cacheKey)
@@ -179,11 +197,11 @@ export class FilesTasksManager implements OnModuleDestroy {
.then((data: any) => {
this.logger.debug({ tag: this.runTask.name, msg: `${task.task.name} : ${task.method} done` })
this.completeTask(task.user.id, task.cacheKey, FileTaskStatus.SUCCESS, data).catch((e: Error) =>
- this.logger.error({ tag: this.runTask.name, msg: `${e}` })
+ this.logger.warn({ tag: this.runTask.name, msg: `${e}` })
)
})
.catch((e: HttpException | any) => {
- this.logger.error({ tag: this.runTask.name, msg: `${task.task.name} : ${task.method} : ${e}` })
+ this.logger.warn({ tag: this.runTask.name, msg: `${task.task.name} : ${task.method} : ${e}` })
this.completeTask(
task.user.id,
task.cacheKey,
diff --git a/frontend/src/app/applications/files/services/files-tasks.service.ts b/frontend/src/app/applications/files/services/files-tasks.service.ts
index 6558703a..1a21c272 100644
--- a/frontend/src/app/applications/files/services/files-tasks.service.ts
+++ b/frontend/src/app/applications/files/services/files-tasks.service.ts
@@ -1,12 +1,13 @@
import { HttpClient, HttpErrorResponse } from '@angular/common/http'
import { inject, Injectable } from '@angular/core'
import { FILE_OPERATION } from '@sync-in-server/backend/src/applications/files/constants/operations'
-import { API_FILES_TASKS, API_FILES_TASKS_CANCEL } from '@sync-in-server/backend/src/applications/files/constants/routes'
+import { API_FILES_TASKS, API_FILES_TASKS_CANCEL, API_FILES_TASKS_POLL } from '@sync-in-server/backend/src/applications/files/constants/routes'
+import type { FileTasksPollResponse } from '@sync-in-server/backend/src/applications/files/interfaces/file-task.interface'
import { FileTask, FileTaskStatus } from '@sync-in-server/backend/src/applications/files/models/file-task'
import { SPACE_REPOSITORY } from '@sync-in-server/backend/src/applications/spaces/constants/spaces'
import { currentTimeStamp } from '@sync-in-server/backend/src/common/shared'
-import { Subscription, timer } from 'rxjs'
-import { tap } from 'rxjs/operators'
+import { EMPTY, Observable, Subscription, timer } from 'rxjs'
+import { catchError, exhaustMap, map, tap } from 'rxjs/operators'
import { genRandomUUID } from '../../../common/utils/functions'
import { escapeRegexp } from '../../../common/utils/regexp'
import { TAB_MENU } from '../../../layout/layout.interfaces'
@@ -55,12 +56,20 @@ export class FilesTasksService {
private currentUserId: number
private cancellingTasks = new Set<string>()
private uploadCancellationHandlers = new Map<string, () => void>()
+ private loadSubscription: Subscription = null
private watcher: Subscription = null
- private watch = timer(1000, 1000).pipe(tap(() => this.doWatch()))
+ private readonly watch = timer(1000, 1000).pipe(
+ exhaustMap(() => this.fetchActiveTasks()),
+ tap(({ activeTasks, endedTasks }) => this.reconcileServerTasks(activeTasks, endedTasks))
+ )
constructor() {
this.store.user.subscribe((u: UserType) => {
- if (u && this.currentUserId !== u?.id) {
+ if (this.currentUserId !== u?.id) {
+ this.loadSubscription?.unsubscribe()
+ this.stopWatch(false)
+ }
+ if (u && this.currentUserId !== u.id) {
// Load tasks when the user is defined and has changed to prevent interceptor redirects
this.loadAll()
}
@@ -70,10 +79,10 @@ export class FilesTasksService {
addTask(task: FileTask) {
if (this.isActiveStatus(task.status)) {
- this.store.filesActiveTasks.next([task, ...this.store.filesActiveTasks.getValue()])
+ this.store.filesActiveTasks.next(this.prependUniqueTasks(this.store.filesActiveTasks.getValue(), [task]))
this.startWatch()
} else {
- this.store.filesEndedTasks.next([task, ...this.store.filesEndedTasks.getValue()])
+ this.store.filesEndedTasks.next(this.prependUniqueTasks(this.store.filesEndedTasks.getValue(), [task]))
}
}
@@ -81,8 +90,8 @@ export class FilesTasksService {
const task = new FileTask(genRandomUUID(), FILE_OPERATION.UPLOAD, path, name)
task.status = FileTaskStatus.QUEUED
task.startedAt = currentTimeStamp(null, true)
- task.props = { progress: 1, size: 0, totalSize: totalSize }
- this.store.filesActiveTasks.next([task, ...this.store.filesActiveTasks.getValue()])
+ task.props = { progress: 1, size: 0, totalSize }
+ this.store.filesActiveTasks.next(this.prependUniqueTasks(this.store.filesActiveTasks.getValue(), [task]))
this.layout.showRSideBarTab(TAB_MENU.TASKS, true)
return task
}
@@ -153,20 +162,25 @@ export class FilesTasksService {
}
private loadAll() {
- this.http.get<FileTask[]>(API_FILES_TASKS).subscribe({
- next: (fileTasks: FileTask[]) => fileTasks.forEach((task: FileTask) => this.addTask(task)),
+ this.loadSubscription = this.http.get<FileTask[]>(API_FILES_TASKS).subscribe({
+ next: (fileTasks: FileTask[]) => {
+ const activeTasks: FileTask[] = []
+ const endedTasks: FileTask[] = []
+ for (const task of fileTasks) {
+ const target = this.isActiveStatus(task.status) ? activeTasks : endedTasks
+ target.push(task)
+ }
+ const uploads = this.store.filesActiveTasks.getValue().filter((task: FileTask) => task.type === FILE_OPERATION.UPLOAD)
+ this.store.filesActiveTasks.next([...uploads, ...activeTasks])
+ this.store.filesEndedTasks.next(endedTasks)
+ if (activeTasks.length) {
+ this.startWatch()
+ }
+ },
error: (e) => console.error(e)
})
}
- private doWatch() {
- if (this.store.filesActiveTasks.getValue().length) {
- this.fetchActiveTasks()
- } else {
- this.stopWatch()
- }
- }
-
private startWatch() {
if (!this.watcher || this.watcher.closed) {
this.layout.showRSideBarTab(TAB_MENU.TASKS, true)
@@ -174,33 +188,76 @@ export class FilesTasksService {
}
}
- private stopWatch() {
+ private stopWatch(hideSidebar = true) {
if (!this.watcher || this.watcher.closed) return
- this.layout.hideRSideBarTab(TAB_MENU.TASKS, 3000)
+ if (hideSidebar) {
+ this.layout.hideRSideBarTab(TAB_MENU.TASKS, 3000)
+ }
this.watcher.unsubscribe()
}
- private fetchActiveTasks() {
- for (const task of this.store.filesActiveTasks.getValue().filter((task: FileTask) => task.type !== FILE_OPERATION.UPLOAD)) {
- this.http.get<FileTask>(`${API_FILES_TASKS}/${task.id}`).subscribe({
- next: (task: FileTask) => this.updateTask(task),
- error: (e) => {
- if (e.status === 404) {
- task.result = e.error.message
- task.status = FileTaskStatus.ERROR
- this.updateTask(task)
- }
- console.warn(e)
- }
- })
+ private fetchActiveTasks(): Observable<{ activeTasks: FileTask[]; endedTasks: FileTask[] }> {
+ const currentServerTasks = this.store.filesActiveTasks.getValue().filter((task: FileTask) => task.type !== FILE_OPERATION.UPLOAD)
+ if (!currentServerTasks.length) {
+ this.stopWatch(false)
+ return EMPTY
}
+ return this.http
+ .post<FileTasksPollResponse>(API_FILES_TASKS_POLL, {
+ trackedIds: currentServerTasks.map((task: FileTask) => task.id)
+ })
+ .pipe(
+ map(({ active, ended, missingIds }: FileTasksPollResponse) => {
+ const currentTasksById = new Map(currentServerTasks.map((task: FileTask) => [task.id, task]))
+ const missingTasks = missingIds
+ .map((taskId: string) => currentTasksById.get(taskId))
+ .filter((task: FileTask | undefined): task is FileTask => task !== undefined)
+ .map((task: FileTask) => ({
+ ...task,
+ result: 'Task not found',
+ status: FileTaskStatus.ERROR
+ }))
+ return { activeTasks: active, endedTasks: [...ended, ...missingTasks] }
+ }),
+ catchError((e) => {
+ console.warn(e)
+ return EMPTY
+ })
+ )
}
- private findTask(taskId: string, active: boolean): FileTask {
- if (active) {
- return this.store.filesActiveTasks.getValue().find((task: FileTask) => task.id === taskId)
+ private reconcileServerTasks(activeTasks: FileTask[], endedTasks: FileTask[]) {
+ const currentTasks = this.store.filesActiveTasks.getValue()
+ const activeTasksById = new Map(activeTasks.map((task: FileTask) => [task.id, task]))
+ const nextTasks: FileTask[] = []
+ for (const task of currentTasks) {
+ if (task.type === FILE_OPERATION.UPLOAD) {
+ nextTasks.push(task)
+ continue
+ }
+ const updatedTask = activeTasksById.get(task.id)
+ if (updatedTask) {
+ Object.assign(task, updatedTask)
+ nextTasks.push(task)
+ activeTasksById.delete(task.id)
+ }
+ }
+ nextTasks.push(...activeTasksById.values())
+ this.store.filesActiveTasks.next(nextTasks)
+
+ if (endedTasks.length) {
+ for (const task of endedTasks) {
+ this.cancellingTasks.delete(task.id)
+ }
+ this.store.filesEndedTasks.next(this.prependUniqueTasks(this.store.filesEndedTasks.getValue(), endedTasks))
+ for (const task of endedTasks) {
+ this.taskDone(task)
+ }
+ }
+ const hasServerTasks = nextTasks.some((task: FileTask) => task.type !== FILE_OPERATION.UPLOAD)
+ if (!hasServerTasks) {
+ this.stopWatch(nextTasks.length === 0)
}
- return this.store.filesEndedTasks.getValue().find((task: FileTask) => task.id === taskId)
}
private isActiveStatus(status: FileTaskStatus): boolean {
@@ -209,12 +266,18 @@ export class FilesTasksService {
private updateActiveTask(task: FileTask) {
const activeTasks = this.store.filesActiveTasks.getValue()
- const currentTask = this.findTask(task.id, true)
+ const currentTask = activeTasks.find((activeTask: FileTask) => activeTask.id === task.id)
if (!currentTask) return
Object.assign(currentTask, task)
this.store.filesActiveTasks.next([...activeTasks])
}
+ private prependUniqueTasks(currentTasks: FileTask[], tasks: FileTask[]): FileTask[] {
+ if (!tasks.length) return currentTasks
+ const taskIds = new Set(tasks.map((task: FileTask) => task.id))
+ return [...tasks, ...currentTasks.filter((task: FileTask) => !taskIds.has(task.id))]
+ }
+
private deleteTask(taskId: string, active: boolean) {
if (active) {
this.store.filesActiveTasks.next(this.store.filesActiveTasks.getValue().filter((task: FileTask) => task.id !== taskId))