PeerTube/server/core/lib/job-queue/job-queue.ts

573 lines
19 KiB
TypeScript
Raw Normal View History

import { pick, timeoutPromise } from '@peertube/peertube-core-utils'
2020-04-23 02:32:53 -05:00
import {
ActivitypubFollowPayload,
ActivitypubHttpBroadcastPayload,
ActivitypubHttpFetcherPayload,
ActivitypubHttpUnicastPayload,
ActorKeysPayload,
Channel sync (#5135) * Add external channel URL for channel update / creation (#754) * Disallow synchronisation if user has no video quota (#754) * More constraints serverside (#754) * Disable sync if server configuration does not allow HTTP import (#754) * Working version synchronizing videos with a job (#754) TODO: refactoring, too much code duplication * More logs and try/catch (#754) * Fix eslint error (#754) * WIP: support synchronization time change (#754) * New frontend #754 * WIP: Create sync front (#754) * Enhance UI, sync creation form (#754) * Warning message when HTTP upload is disallowed * More consistent names (#754) * Binding Front with API (#754) * Add a /me API (#754) * Improve list UI (#754) * Implement creation and deletion routes (#754) * Lint (#754) * Lint again (#754) * WIP: UI for triggering import existing videos (#754) * Implement jobs for syncing and importing channels * Don't sync videos before sync creation + avoid concurrency issue (#754) * Cleanup (#754) * Cleanup: OpenAPI + API rework (#754) * Remove dead code (#754) * Eslint (#754) * Revert the mess with whitespaces in constants.ts (#754) * Some fixes after rebase (#754) * Several fixes after PR remarks (#754) * Front + API: Rename video-channels-sync to video-channel-syncs (#754) * Allow enabling channel sync through UI (#754) * getChannelInfo (#754) * Minor fixes: openapi + model + sql (#754) * Simplified API validators (#754) * Rename MChannelSync to MChannelSyncChannel (#754) * Add command for VideoChannelSync (#754) * Use synchronization.enabled config (#754) * Check parameters test + some fixes (#754) * Fix conflict mistake (#754) * Restrict access to video channel sync list API (#754) * Start adding unit test for synchronization (#754) * Continue testing (#754) * Tests finished + convertion of job to scheduler (#754) * Add lastSyncAt field (#754) * Fix externalRemoteUrl sort + creation date not well formatted (#754) * Small fix (#754) * Factorize addYoutubeDLImport and buildVideo (#754) * Check duplicates on channel not on users (#754) * factorize thumbnail generation (#754) * Fetch error should return status 400 (#754) * Separate video-channel-import and video-channel-sync-latest (#754) * Bump DB migration version after rebase (#754) * Prettier states in UI table (#754) * Add DefaultScope in VideoChannelSyncModel (#754) * Fix audit logs (#754) * Ensure user can upload when importing channel + minor fixes (#754) * Mark synchronization as failed on exception + typos (#754) * Change REST API for importing videos into channel (#754) * Add option for fully synchronize a chnanel (#754) * Return a whole sync object on creation to avoid tricks in Front (#754) * Various remarks (#754) * Single quotes by default (#754) * Rename synchronization to video_channel_synchronization * Add check.latest_videos_count and max_per_user options (#754) * Better channel rendering in list #754 * Allow sorting with channel name and state (#754) * Add missing tests for channel imports (#754) * Prefer using a parent job for channel sync * Styling * Client styling Co-authored-by: Chocobozzz <me@florianbigard.com>
2022-08-10 02:53:39 -05:00
AfterVideoChannelImportPayload,
2024-02-12 03:47:52 -06:00
CreateUserExportPayload,
DeleteResumableUploadMetaFilePayload,
EmailPayload,
2022-08-08 08:48:17 -05:00
FederateVideoPayload,
2023-06-01 07:51:16 -05:00
GenerateStoryboardPayload,
2024-02-12 03:47:52 -06:00
ImportUserArchivePayload,
2020-04-23 02:32:53 -05:00
JobState,
JobType,
ManageVideoTorrentPayload,
MoveStoragePayload,
2022-08-08 08:48:17 -05:00
NotifyPayload,
RefreshPayload,
TranscodingJobBuilderPayload,
Channel sync (#5135) * Add external channel URL for channel update / creation (#754) * Disallow synchronisation if user has no video quota (#754) * More constraints serverside (#754) * Disable sync if server configuration does not allow HTTP import (#754) * Working version synchronizing videos with a job (#754) TODO: refactoring, too much code duplication * More logs and try/catch (#754) * Fix eslint error (#754) * WIP: support synchronization time change (#754) * New frontend #754 * WIP: Create sync front (#754) * Enhance UI, sync creation form (#754) * Warning message when HTTP upload is disallowed * More consistent names (#754) * Binding Front with API (#754) * Add a /me API (#754) * Improve list UI (#754) * Implement creation and deletion routes (#754) * Lint (#754) * Lint again (#754) * WIP: UI for triggering import existing videos (#754) * Implement jobs for syncing and importing channels * Don't sync videos before sync creation + avoid concurrency issue (#754) * Cleanup (#754) * Cleanup: OpenAPI + API rework (#754) * Remove dead code (#754) * Eslint (#754) * Revert the mess with whitespaces in constants.ts (#754) * Some fixes after rebase (#754) * Several fixes after PR remarks (#754) * Front + API: Rename video-channels-sync to video-channel-syncs (#754) * Allow enabling channel sync through UI (#754) * getChannelInfo (#754) * Minor fixes: openapi + model + sql (#754) * Simplified API validators (#754) * Rename MChannelSync to MChannelSyncChannel (#754) * Add command for VideoChannelSync (#754) * Use synchronization.enabled config (#754) * Check parameters test + some fixes (#754) * Fix conflict mistake (#754) * Restrict access to video channel sync list API (#754) * Start adding unit test for synchronization (#754) * Continue testing (#754) * Tests finished + convertion of job to scheduler (#754) * Add lastSyncAt field (#754) * Fix externalRemoteUrl sort + creation date not well formatted (#754) * Small fix (#754) * Factorize addYoutubeDLImport and buildVideo (#754) * Check duplicates on channel not on users (#754) * factorize thumbnail generation (#754) * Fetch error should return status 400 (#754) * Separate video-channel-import and video-channel-sync-latest (#754) * Bump DB migration version after rebase (#754) * Prettier states in UI table (#754) * Add DefaultScope in VideoChannelSyncModel (#754) * Fix audit logs (#754) * Ensure user can upload when importing channel + minor fixes (#754) * Mark synchronization as failed on exception + typos (#754) * Change REST API for importing videos into channel (#754) * Add option for fully synchronize a chnanel (#754) * Return a whole sync object on creation to avoid tricks in Front (#754) * Various remarks (#754) * Single quotes by default (#754) * Rename synchronization to video_channel_synchronization * Add check.latest_videos_count and max_per_user options (#754) * Better channel rendering in list #754 * Allow sorting with channel name and state (#754) * Add missing tests for channel imports (#754) * Prefer using a parent job for channel sync * Styling * Client styling Co-authored-by: Chocobozzz <me@florianbigard.com>
2022-08-10 02:53:39 -05:00
VideoChannelImportPayload,
VideoFileImportPayload,
VideoImportPayload,
VideoLiveEndingPayload,
VideoRedundancyPayload,
2022-03-22 10:58:49 -05:00
VideoStudioEditionPayload,
2024-06-13 02:23:12 -05:00
VideoTranscodingPayload,
VideoTranscriptionPayload
} from '@peertube/peertube-models'
import { parseDurationToMs } from '@server/helpers/core-utils.js'
import { jobStates } from '@server/helpers/custom-validators/jobs.js'
import { CONFIG } from '@server/initializers/config.js'
import { processVideoRedundancy } from '@server/lib/job-queue/handlers/video-redundancy.js'
2024-06-13 02:23:12 -05:00
import {
FlowJob,
FlowProducer,
Job,
JobsOptions,
Queue,
QueueEvents,
QueueEventsOptions,
QueueOptions,
Worker,
WorkerOptions
} from 'bullmq'
import { logger } from '../../helpers/logger.js'
import { JOB_ATTEMPTS, JOB_CONCURRENCY, JOB_REMOVAL_OPTIONS, JOB_TTL, REPEAT_JOBS, WEBSERVER } from '../../initializers/constants.js'
import { Hooks } from '../plugins/hooks.js'
import { Redis } from '../redis.js'
import { processActivityPubCleaner } from './handlers/activitypub-cleaner.js'
import { processActivityPubFollow } from './handlers/activitypub-follow.js'
import {
processActivityPubHttpSequentialBroadcast,
processActivityPubParallelHttpBroadcast
} from './handlers/activitypub-http-broadcast.js'
import { processActivityPubHttpFetcher } from './handlers/activitypub-http-fetcher.js'
import { processActivityPubHttpUnicast } from './handlers/activitypub-http-unicast.js'
import { refreshAPObject } from './handlers/activitypub-refresher.js'
import { processActorKeys } from './handlers/actor-keys.js'
import { processAfterVideoChannelImport } from './handlers/after-video-channel-import.js'
2024-06-13 02:23:12 -05:00
import { processCreateUserExport } from './handlers/create-user-export.js'
import { processEmail } from './handlers/email.js'
import { processFederateVideo } from './handlers/federate-video.js'
import { processGenerateStoryboard } from './handlers/generate-storyboard.js'
2024-06-13 02:23:12 -05:00
import { processImportUserArchive } from './handlers/import-user-archive.js'
import { processManageVideoTorrent } from './handlers/manage-video-torrent.js'
2024-06-13 02:23:12 -05:00
import { onMoveToFileSystemFailure, processMoveToFileSystem } from './handlers/move-to-file-system.js'
import { onMoveToObjectStorageFailure, processMoveToObjectStorage } from './handlers/move-to-object-storage.js'
import { processNotify } from './handlers/notify.js'
import { processTranscodingJobBuilder } from './handlers/transcoding-job-builder.js'
import { processVideoChannelImport } from './handlers/video-channel-import.js'
import { processVideoFileImport } from './handlers/video-file-import.js'
import { processVideoImport } from './handlers/video-import.js'
import { processVideoLiveEnding } from './handlers/video-live-ending.js'
import { processVideoStudioEdition } from './handlers/video-studio-edition.js'
import { processVideoTranscoding } from './handlers/video-transcoding.js'
2024-06-13 02:23:12 -05:00
import { processVideoTranscription } from './handlers/video-transcription.js'
import { processVideosViewsStats } from './handlers/video-views-stats.js'
2022-08-08 08:48:17 -05:00
export type CreateJobArgument =
{ type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
2022-06-17 07:08:13 -05:00
{ type: 'activitypub-http-broadcast-parallel', payload: ActivitypubHttpBroadcastPayload } |
{ type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
{ type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
{ type: 'activitypub-cleaner', payload: {} } |
{ type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
{ type: 'video-file-import', payload: VideoFileImportPayload } |
{ type: 'video-transcoding', payload: VideoTranscodingPayload } |
{ type: 'email', payload: EmailPayload } |
{ type: 'transcoding-job-builder', payload: TranscodingJobBuilderPayload } |
2018-08-29 09:26:25 -05:00
{ type: 'video-import', payload: VideoImportPayload } |
{ type: 'activitypub-refresher', payload: RefreshPayload } |
{ type: 'videos-views-stats', payload: {} } |
{ type: 'video-live-ending', payload: VideoLiveEndingPayload } |
{ type: 'actor-keys', payload: ActorKeysPayload } |
Add support for saving video files to object storage (#4290) * Add support for saving video files to object storage * Add support for custom url generation on s3 stored files Uses two config keys to support url generation that doesn't directly go to (compatible s3). Can be used to generate urls to any cache server or CDN. * Upload files to s3 concurrently and delete originals afterwards * Only publish after move to object storage is complete * Use base url instead of url template * Fix mistyped config field * Add rudenmentary way to download before transcode * Implement Chocobozzz suggestions https://github.com/Chocobozzz/PeerTube/pull/4290#issuecomment-891670478 The remarks in question: Try to use objectStorage prefix instead of s3 prefix for your function/variables/config names Prefer to use a tree for the config: s3.streaming_playlists_bucket -> object_storage.streaming_playlists.bucket Use uppercase for config: S3.STREAMING_PLAYLISTS_BUCKETINFO.bucket -> OBJECT_STORAGE.STREAMING_PLAYLISTS.BUCKET (maybe BUCKET_NAME instead of BUCKET) I suggest to rename moveJobsRunning to pendingMovingJobs (or better, create a dedicated videoJobInfo table with a pendingMove & videoId columns so we could also use this table to track pending transcoding jobs) https://github.com/Chocobozzz/PeerTube/pull/4290/files#diff-3e26d41ca4bda1de8e1747af70ca2af642abcc1e9e0bfb94239ff2165acfbde5R19 uses a string instead of an integer I think we should store the origin object storage URL in fileUrl, without base_url injection. Instead, inject the base_url at "runtime" so admins can easily change this configuration without running a script to update DB URLs * Import correct function * Support multipart upload * Remove import of node 15.0 module stream/promises * Extend maximum upload job length Using the same value as for redundancy downloading seems logical * Use dynamic part size for really large uploads Also adds very small part size for local testing * Fix decreasePendingMove query * Resolve various PR comments * Move to object storage after optimize * Make upload size configurable and increase default * Prune webtorrent files that are stored in object storage * Move files after transcoding jobs * Fix federation * Add video path manager * Support move to external storage job in client * Fix live object storage tests Co-authored-by: Chocobozzz <me@florianbigard.com>
2021-08-17 01:26:20 -05:00
{ type: 'video-redundancy', payload: VideoRedundancyPayload } |
{ type: 'delete-resumable-upload-meta-file', payload: DeleteResumableUploadMetaFilePayload } |
2022-03-22 10:58:49 -05:00
{ type: 'video-studio-edition', payload: VideoStudioEditionPayload } |
{ type: 'manage-video-torrent', payload: ManageVideoTorrentPayload } |
{ type: 'move-to-object-storage', payload: MoveStoragePayload } |
{ type: 'move-to-file-system', payload: MoveStoragePayload } |
Channel sync (#5135) * Add external channel URL for channel update / creation (#754) * Disallow synchronisation if user has no video quota (#754) * More constraints serverside (#754) * Disable sync if server configuration does not allow HTTP import (#754) * Working version synchronizing videos with a job (#754) TODO: refactoring, too much code duplication * More logs and try/catch (#754) * Fix eslint error (#754) * WIP: support synchronization time change (#754) * New frontend #754 * WIP: Create sync front (#754) * Enhance UI, sync creation form (#754) * Warning message when HTTP upload is disallowed * More consistent names (#754) * Binding Front with API (#754) * Add a /me API (#754) * Improve list UI (#754) * Implement creation and deletion routes (#754) * Lint (#754) * Lint again (#754) * WIP: UI for triggering import existing videos (#754) * Implement jobs for syncing and importing channels * Don't sync videos before sync creation + avoid concurrency issue (#754) * Cleanup (#754) * Cleanup: OpenAPI + API rework (#754) * Remove dead code (#754) * Eslint (#754) * Revert the mess with whitespaces in constants.ts (#754) * Some fixes after rebase (#754) * Several fixes after PR remarks (#754) * Front + API: Rename video-channels-sync to video-channel-syncs (#754) * Allow enabling channel sync through UI (#754) * getChannelInfo (#754) * Minor fixes: openapi + model + sql (#754) * Simplified API validators (#754) * Rename MChannelSync to MChannelSyncChannel (#754) * Add command for VideoChannelSync (#754) * Use synchronization.enabled config (#754) * Check parameters test + some fixes (#754) * Fix conflict mistake (#754) * Restrict access to video channel sync list API (#754) * Start adding unit test for synchronization (#754) * Continue testing (#754) * Tests finished + convertion of job to scheduler (#754) * Add lastSyncAt field (#754) * Fix externalRemoteUrl sort + creation date not well formatted (#754) * Small fix (#754) * Factorize addYoutubeDLImport and buildVideo (#754) * Check duplicates on channel not on users (#754) * factorize thumbnail generation (#754) * Fetch error should return status 400 (#754) * Separate video-channel-import and video-channel-sync-latest (#754) * Bump DB migration version after rebase (#754) * Prettier states in UI table (#754) * Add DefaultScope in VideoChannelSyncModel (#754) * Fix audit logs (#754) * Ensure user can upload when importing channel + minor fixes (#754) * Mark synchronization as failed on exception + typos (#754) * Change REST API for importing videos into channel (#754) * Add option for fully synchronize a chnanel (#754) * Return a whole sync object on creation to avoid tricks in Front (#754) * Various remarks (#754) * Single quotes by default (#754) * Rename synchronization to video_channel_synchronization * Add check.latest_videos_count and max_per_user options (#754) * Better channel rendering in list #754 * Allow sorting with channel name and state (#754) * Add missing tests for channel imports (#754) * Prefer using a parent job for channel sync * Styling * Client styling Co-authored-by: Chocobozzz <me@florianbigard.com>
2022-08-10 02:53:39 -05:00
{ type: 'video-channel-import', payload: VideoChannelImportPayload } |
{ type: 'after-video-channel-import', payload: AfterVideoChannelImportPayload } |
2022-08-08 08:48:17 -05:00
{ type: 'notify', payload: NotifyPayload } |
2023-06-01 07:51:16 -05:00
{ type: 'federate-video', payload: FederateVideoPayload } |
2024-02-12 03:47:52 -06:00
{ type: 'create-user-export', payload: CreateUserExportPayload } |
{ type: 'generate-video-storyboard', payload: GenerateStoryboardPayload } |
2024-06-13 02:23:12 -05:00
{ type: 'import-user-archive', payload: ImportUserArchivePayload } |
{ type: 'video-transcription', payload: VideoTranscriptionPayload }
Add support for saving video files to object storage (#4290) * Add support for saving video files to object storage * Add support for custom url generation on s3 stored files Uses two config keys to support url generation that doesn't directly go to (compatible s3). Can be used to generate urls to any cache server or CDN. * Upload files to s3 concurrently and delete originals afterwards * Only publish after move to object storage is complete * Use base url instead of url template * Fix mistyped config field * Add rudenmentary way to download before transcode * Implement Chocobozzz suggestions https://github.com/Chocobozzz/PeerTube/pull/4290#issuecomment-891670478 The remarks in question: Try to use objectStorage prefix instead of s3 prefix for your function/variables/config names Prefer to use a tree for the config: s3.streaming_playlists_bucket -> object_storage.streaming_playlists.bucket Use uppercase for config: S3.STREAMING_PLAYLISTS_BUCKETINFO.bucket -> OBJECT_STORAGE.STREAMING_PLAYLISTS.BUCKET (maybe BUCKET_NAME instead of BUCKET) I suggest to rename moveJobsRunning to pendingMovingJobs (or better, create a dedicated videoJobInfo table with a pendingMove & videoId columns so we could also use this table to track pending transcoding jobs) https://github.com/Chocobozzz/PeerTube/pull/4290/files#diff-3e26d41ca4bda1de8e1747af70ca2af642abcc1e9e0bfb94239ff2165acfbde5R19 uses a string instead of an integer I think we should store the origin object storage URL in fileUrl, without base_url injection. Instead, inject the base_url at "runtime" so admins can easily change this configuration without running a script to update DB URLs * Import correct function * Support multipart upload * Remove import of node 15.0 module stream/promises * Extend maximum upload job length Using the same value as for redundancy downloading seems logical * Use dynamic part size for really large uploads Also adds very small part size for local testing * Fix decreasePendingMove query * Resolve various PR comments * Move to object storage after optimize * Make upload size configurable and increase default * Prune webtorrent files that are stored in object storage * Move files after transcoding jobs * Fix federation * Add video path manager * Support move to external storage job in client * Fix live object storage tests Co-authored-by: Chocobozzz <me@florianbigard.com>
2021-08-17 01:26:20 -05:00
export type CreateJobOptions = {
delay?: number
priority?: number
2023-05-02 06:51:06 -05:00
failParentOnFailure?: boolean
}
2021-08-27 07:32:44 -05:00
const handlers: { [id in JobType]: (job: Job) => Promise<any> } = {
'activitypub-cleaner': processActivityPubCleaner,
'activitypub-follow': processActivityPubFollow,
'activitypub-http-broadcast-parallel': processActivityPubParallelHttpBroadcast,
'activitypub-http-broadcast': processActivityPubHttpSequentialBroadcast,
'activitypub-http-fetcher': processActivityPubHttpFetcher,
'activitypub-http-unicast': processActivityPubHttpUnicast,
'activitypub-refresher': refreshAPObject,
'actor-keys': processActorKeys,
'after-video-channel-import': processAfterVideoChannelImport,
'email': processEmail,
'federate-video': processFederateVideo,
'transcoding-job-builder': processTranscodingJobBuilder,
'manage-video-torrent': processManageVideoTorrent,
'move-to-object-storage': processMoveToObjectStorage,
'move-to-file-system': processMoveToFileSystem,
'notify': processNotify,
'video-channel-import': processVideoChannelImport,
'video-file-import': processVideoFileImport,
2018-08-29 09:26:25 -05:00
'video-import': processVideoImport,
'video-live-ending': processVideoLiveEnding,
Add support for saving video files to object storage (#4290) * Add support for saving video files to object storage * Add support for custom url generation on s3 stored files Uses two config keys to support url generation that doesn't directly go to (compatible s3). Can be used to generate urls to any cache server or CDN. * Upload files to s3 concurrently and delete originals afterwards * Only publish after move to object storage is complete * Use base url instead of url template * Fix mistyped config field * Add rudenmentary way to download before transcode * Implement Chocobozzz suggestions https://github.com/Chocobozzz/PeerTube/pull/4290#issuecomment-891670478 The remarks in question: Try to use objectStorage prefix instead of s3 prefix for your function/variables/config names Prefer to use a tree for the config: s3.streaming_playlists_bucket -> object_storage.streaming_playlists.bucket Use uppercase for config: S3.STREAMING_PLAYLISTS_BUCKETINFO.bucket -> OBJECT_STORAGE.STREAMING_PLAYLISTS.BUCKET (maybe BUCKET_NAME instead of BUCKET) I suggest to rename moveJobsRunning to pendingMovingJobs (or better, create a dedicated videoJobInfo table with a pendingMove & videoId columns so we could also use this table to track pending transcoding jobs) https://github.com/Chocobozzz/PeerTube/pull/4290/files#diff-3e26d41ca4bda1de8e1747af70ca2af642abcc1e9e0bfb94239ff2165acfbde5R19 uses a string instead of an integer I think we should store the origin object storage URL in fileUrl, without base_url injection. Instead, inject the base_url at "runtime" so admins can easily change this configuration without running a script to update DB URLs * Import correct function * Support multipart upload * Remove import of node 15.0 module stream/promises * Extend maximum upload job length Using the same value as for redundancy downloading seems logical * Use dynamic part size for really large uploads Also adds very small part size for local testing * Fix decreasePendingMove query * Resolve various PR comments * Move to object storage after optimize * Make upload size configurable and increase default * Prune webtorrent files that are stored in object storage * Move files after transcoding jobs * Fix federation * Add video path manager * Support move to external storage job in client * Fix live object storage tests Co-authored-by: Chocobozzz <me@florianbigard.com>
2021-08-17 01:26:20 -05:00
'video-redundancy': processVideoRedundancy,
2022-08-08 08:48:17 -05:00
'video-studio-edition': processVideoStudioEdition,
'video-transcoding': processVideoTranscoding,
2023-06-01 07:51:16 -05:00
'videos-views-stats': processVideosViewsStats,
2024-02-12 03:47:52 -06:00
'generate-video-storyboard': processGenerateStoryboard,
'create-user-export': processCreateUserExport,
2024-06-13 02:23:12 -05:00
'import-user-archive': processImportUserArchive,
'video-transcription': processVideoTranscription
}
const errorHandlers: { [id in JobType]?: (job: Job, err: any) => Promise<any> } = {
'move-to-object-storage': onMoveToObjectStorageFailure,
'move-to-file-system': onMoveToFileSystemFailure
}
2018-07-10 10:02:20 -05:00
const jobTypes: JobType[] = [
'activitypub-cleaner',
2018-07-10 10:02:20 -05:00
'activitypub-follow',
2022-06-17 07:08:13 -05:00
'activitypub-http-broadcast-parallel',
'activitypub-http-broadcast',
2018-05-09 02:08:22 -05:00
'activitypub-http-fetcher',
2018-07-10 10:02:20 -05:00
'activitypub-http-unicast',
'activitypub-refresher',
'actor-keys',
'after-video-channel-import',
2018-07-10 10:02:20 -05:00
'email',
'federate-video',
2023-06-01 07:51:16 -05:00
'generate-video-storyboard',
'manage-video-torrent',
'move-to-object-storage',
'move-to-file-system',
'notify',
2023-06-01 07:51:16 -05:00
'transcoding-job-builder',
'video-channel-import',
'video-file-import',
2018-08-29 09:26:25 -05:00
'video-import',
Add support for saving video files to object storage (#4290) * Add support for saving video files to object storage * Add support for custom url generation on s3 stored files Uses two config keys to support url generation that doesn't directly go to (compatible s3). Can be used to generate urls to any cache server or CDN. * Upload files to s3 concurrently and delete originals afterwards * Only publish after move to object storage is complete * Use base url instead of url template * Fix mistyped config field * Add rudenmentary way to download before transcode * Implement Chocobozzz suggestions https://github.com/Chocobozzz/PeerTube/pull/4290#issuecomment-891670478 The remarks in question: Try to use objectStorage prefix instead of s3 prefix for your function/variables/config names Prefer to use a tree for the config: s3.streaming_playlists_bucket -> object_storage.streaming_playlists.bucket Use uppercase for config: S3.STREAMING_PLAYLISTS_BUCKETINFO.bucket -> OBJECT_STORAGE.STREAMING_PLAYLISTS.BUCKET (maybe BUCKET_NAME instead of BUCKET) I suggest to rename moveJobsRunning to pendingMovingJobs (or better, create a dedicated videoJobInfo table with a pendingMove & videoId columns so we could also use this table to track pending transcoding jobs) https://github.com/Chocobozzz/PeerTube/pull/4290/files#diff-3e26d41ca4bda1de8e1747af70ca2af642abcc1e9e0bfb94239ff2165acfbde5R19 uses a string instead of an integer I think we should store the origin object storage URL in fileUrl, without base_url injection. Instead, inject the base_url at "runtime" so admins can easily change this configuration without running a script to update DB URLs * Import correct function * Support multipart upload * Remove import of node 15.0 module stream/promises * Extend maximum upload job length Using the same value as for redundancy downloading seems logical * Use dynamic part size for really large uploads Also adds very small part size for local testing * Fix decreasePendingMove query * Resolve various PR comments * Move to object storage after optimize * Make upload size configurable and increase default * Prune webtorrent files that are stored in object storage * Move files after transcoding jobs * Fix federation * Add video path manager * Support move to external storage job in client * Fix live object storage tests Co-authored-by: Chocobozzz <me@florianbigard.com>
2021-08-17 01:26:20 -05:00
'video-live-ending',
'video-redundancy',
2022-08-08 08:48:17 -05:00
'video-studio-edition',
2024-06-13 02:23:12 -05:00
'video-transcription',
2024-02-12 03:47:52 -06:00
'videos-views-stats',
'create-user-export',
2024-06-13 02:23:12 -05:00
'import-user-archive',
'video-transcoding'
2018-05-09 02:08:22 -05:00
]
2022-05-18 05:01:02 -05:00
const silentFailure = new Set<JobType>([ 'activitypub-http-unicast' ])
class JobQueue {
private static instance: JobQueue
2022-08-08 03:42:08 -05:00
private workers: { [id in JobType]?: Worker } = {}
2021-08-27 07:32:44 -05:00
private queues: { [id in JobType]?: Queue } = {}
2022-08-08 03:42:08 -05:00
private queueEvents: { [id in JobType]?: QueueEvents } = {}
2022-08-08 08:48:17 -05:00
private flowProducer: FlowProducer
private initialized = false
private jobRedisPrefix: string
2020-01-31 09:56:52 -06:00
private constructor () {
}
init () {
// Already initialized
if (this.initialized === true) return
this.initialized = true
2019-04-11 04:33:44 -05:00
this.jobRedisPrefix = 'bull-' + WEBSERVER.HOST
2022-01-14 08:06:33 -06:00
2023-01-09 07:42:52 -06:00
for (const handlerName of Object.keys(handlers)) {
this.buildWorker(handlerName)
2022-08-08 03:42:08 -05:00
this.buildQueue(handlerName)
this.buildQueueEvent(handlerName)
2022-08-08 03:42:08 -05:00
}
2022-08-08 08:48:17 -05:00
this.flowProducer = new FlowProducer({
connection: Redis.getRedisClientOptions('FlowProducer'),
2022-08-08 08:48:17 -05:00
prefix: this.jobRedisPrefix
})
2022-08-11 04:30:06 -05:00
this.flowProducer.on('error', err => { logger.error('Error in flow producer', { err }) })
2022-08-08 08:48:17 -05:00
2022-08-08 03:42:08 -05:00
this.addRepeatableJobs()
}
private buildWorker (handlerName: JobType) {
2022-08-08 03:42:08 -05:00
const workerOptions: WorkerOptions = {
autorun: false,
2022-08-08 03:42:08 -05:00
concurrency: this.getJobConcurrency(handlerName),
prefix: this.jobRedisPrefix,
2023-02-16 07:10:11 -06:00
connection: Redis.getRedisClientOptions('Worker'),
maxStalledCount: 10
2018-07-10 10:02:20 -05:00
}
2018-01-30 06:27:07 -06:00
2022-08-08 03:42:08 -05:00
const handler = function (job: Job) {
const timeout = JOB_TTL[handlerName]
const p = handlers[handlerName](job)
2022-08-08 03:42:08 -05:00
if (!timeout) return p
2022-08-08 03:42:08 -05:00
return timeoutPromise(p, timeout)
}
2022-08-08 03:42:08 -05:00
const processor = async (jobArg: Job<any>) => {
const job = await Hooks.wrapObject(jobArg, 'filter:job-queue.process.params', { type: handlerName })
2022-08-02 08:29:00 -05:00
2022-08-08 03:42:08 -05:00
return Hooks.wrapPromiseFun(handler, job, 'filter:job-queue.process.result')
}
2018-08-03 02:27:30 -05:00
2022-08-08 03:42:08 -05:00
const worker = new Worker(handlerName, processor, workerOptions)
2022-05-18 05:01:02 -05:00
2022-08-08 03:42:08 -05:00
worker.on('failed', (job, err) => {
const logLevel = silentFailure.has(handlerName)
? 'debug'
: 'error'
2022-08-08 03:42:08 -05:00
logger.log(logLevel, 'Cannot execute job %s in queue %s.', job.id, handlerName, { payload: job.data, err })
2018-02-12 04:25:09 -06:00
2022-08-08 03:42:08 -05:00
if (errorHandlers[job.name]) {
errorHandlers[job.name](job, err)
.catch(err => logger.error('Cannot run error handler for job failure %d in queue %s.', job.id, handlerName, { err }))
}
})
2018-07-10 10:02:20 -05:00
2022-08-11 04:30:06 -05:00
worker.on('error', err => { logger.error('Error in job worker %s.', handlerName, { err }) })
2022-08-08 03:42:08 -05:00
this.workers[handlerName] = worker
}
private buildQueue (handlerName: JobType) {
const queueOptions: QueueOptions = {
connection: Redis.getRedisClientOptions('Queue'),
2022-08-08 03:42:08 -05:00
prefix: this.jobRedisPrefix
}
2018-08-29 09:26:25 -05:00
2022-08-11 04:30:06 -05:00
const queue = new Queue(handlerName, queueOptions)
queue.on('error', err => { logger.error('Error in job queue %s.', handlerName, { err }) })
this.queues[handlerName] = queue
2023-10-12 02:17:53 -05:00
queue.removeDeprecatedPriorityKey()
.catch(err => logger.error('Cannot remove bullmq deprecated priority keys of ' + handlerName, { err }))
2022-08-08 03:42:08 -05:00
}
private buildQueueEvent (handlerName: JobType) {
2022-08-08 03:42:08 -05:00
const queueEventsOptions: QueueEventsOptions = {
autorun: false,
connection: Redis.getRedisClientOptions('QueueEvent'),
2022-08-08 03:42:08 -05:00
prefix: this.jobRedisPrefix
2018-07-30 11:49:54 -05:00
}
2022-08-11 04:30:06 -05:00
const queueEvents = new QueueEvents(handlerName, queueEventsOptions)
queueEvents.on('error', err => { logger.error('Error in job queue events %s.', handlerName, { err }) })
this.queueEvents[handlerName] = queueEvents
2022-08-08 03:42:08 -05:00
}
2022-08-08 08:48:17 -05:00
// ---------------------------------------------------------------------------
2022-08-08 03:42:08 -05:00
async terminate () {
const promises = Object.keys(this.workers)
.map(handlerName => {
const worker: Worker = this.workers[handlerName]
const queue: Queue = this.queues[handlerName]
const queueEvent: QueueEvents = this.queueEvents[handlerName]
return Promise.all([
worker.close(false),
queue.close(),
queueEvent.close()
])
})
return Promise.all(promises)
2018-07-30 11:49:54 -05:00
}
start () {
const promises = Object.keys(this.workers)
.map(handlerName => {
const worker: Worker = this.workers[handlerName]
const queueEvent: QueueEvents = this.queueEvents[handlerName]
return Promise.all([
worker.run(),
queueEvent.run()
])
})
return Promise.all(promises)
}
async pause () {
2022-08-09 04:35:07 -05:00
for (const handlerName of Object.keys(this.workers)) {
const worker: Worker = this.workers[handlerName]
2022-08-08 03:42:08 -05:00
await worker.pause()
}
}
resume () {
2022-08-09 04:35:07 -05:00
for (const handlerName of Object.keys(this.workers)) {
const worker: Worker = this.workers[handlerName]
2022-08-08 03:42:08 -05:00
worker.resume()
}
}
2022-08-08 08:48:17 -05:00
// ---------------------------------------------------------------------------
createJobAsync (options: CreateJobArgument & CreateJobOptions): void {
this.createJob(options)
.catch(err => logger.error('Cannot create job.', { err, options }))
2020-01-31 09:56:52 -06:00
}
2023-12-27 03:39:09 -06:00
createJob (options: CreateJobArgument & CreateJobOptions | undefined) {
if (!options) return
2022-08-08 08:48:17 -05:00
const queue: Queue = this.queues[options.type]
2018-07-10 10:02:20 -05:00
if (queue === undefined) {
2022-08-08 08:48:17 -05:00
logger.error('Unknown queue %s: cannot create job.', options.type)
2020-01-31 09:56:52 -06:00
return
2018-07-10 10:02:20 -05:00
}
2022-08-08 08:48:17 -05:00
const jobOptions = this.buildJobOptions(options.type as JobType, pick(options, [ 'priority', 'delay' ]))
return queue.add('job', options.payload, jobOptions)
}
Channel sync (#5135) * Add external channel URL for channel update / creation (#754) * Disallow synchronisation if user has no video quota (#754) * More constraints serverside (#754) * Disable sync if server configuration does not allow HTTP import (#754) * Working version synchronizing videos with a job (#754) TODO: refactoring, too much code duplication * More logs and try/catch (#754) * Fix eslint error (#754) * WIP: support synchronization time change (#754) * New frontend #754 * WIP: Create sync front (#754) * Enhance UI, sync creation form (#754) * Warning message when HTTP upload is disallowed * More consistent names (#754) * Binding Front with API (#754) * Add a /me API (#754) * Improve list UI (#754) * Implement creation and deletion routes (#754) * Lint (#754) * Lint again (#754) * WIP: UI for triggering import existing videos (#754) * Implement jobs for syncing and importing channels * Don't sync videos before sync creation + avoid concurrency issue (#754) * Cleanup (#754) * Cleanup: OpenAPI + API rework (#754) * Remove dead code (#754) * Eslint (#754) * Revert the mess with whitespaces in constants.ts (#754) * Some fixes after rebase (#754) * Several fixes after PR remarks (#754) * Front + API: Rename video-channels-sync to video-channel-syncs (#754) * Allow enabling channel sync through UI (#754) * getChannelInfo (#754) * Minor fixes: openapi + model + sql (#754) * Simplified API validators (#754) * Rename MChannelSync to MChannelSyncChannel (#754) * Add command for VideoChannelSync (#754) * Use synchronization.enabled config (#754) * Check parameters test + some fixes (#754) * Fix conflict mistake (#754) * Restrict access to video channel sync list API (#754) * Start adding unit test for synchronization (#754) * Continue testing (#754) * Tests finished + convertion of job to scheduler (#754) * Add lastSyncAt field (#754) * Fix externalRemoteUrl sort + creation date not well formatted (#754) * Small fix (#754) * Factorize addYoutubeDLImport and buildVideo (#754) * Check duplicates on channel not on users (#754) * factorize thumbnail generation (#754) * Fetch error should return status 400 (#754) * Separate video-channel-import and video-channel-sync-latest (#754) * Bump DB migration version after rebase (#754) * Prettier states in UI table (#754) * Add DefaultScope in VideoChannelSyncModel (#754) * Fix audit logs (#754) * Ensure user can upload when importing channel + minor fixes (#754) * Mark synchronization as failed on exception + typos (#754) * Change REST API for importing videos into channel (#754) * Add option for fully synchronize a chnanel (#754) * Return a whole sync object on creation to avoid tricks in Front (#754) * Various remarks (#754) * Single quotes by default (#754) * Rename synchronization to video_channel_synchronization * Add check.latest_videos_count and max_per_user options (#754) * Better channel rendering in list #754 * Allow sorting with channel name and state (#754) * Add missing tests for channel imports (#754) * Prefer using a parent job for channel sync * Styling * Client styling Co-authored-by: Chocobozzz <me@florianbigard.com>
2022-08-10 02:53:39 -05:00
createSequentialJobFlow (...jobs: ((CreateJobArgument & CreateJobOptions) | undefined)[]) {
2022-08-08 08:48:17 -05:00
let lastJob: FlowJob
logger.debug('Creating jobs in local job queue', { jobs })
2022-08-08 08:48:17 -05:00
for (const job of jobs) {
if (!job) continue
lastJob = {
2022-08-09 02:09:31 -05:00
...this.buildJobFlowOption(job),
2022-08-08 08:48:17 -05:00
children: lastJob
? [ lastJob ]
: []
}
}
return this.flowProducer.add(lastJob)
}
Channel sync (#5135) * Add external channel URL for channel update / creation (#754) * Disallow synchronisation if user has no video quota (#754) * More constraints serverside (#754) * Disable sync if server configuration does not allow HTTP import (#754) * Working version synchronizing videos with a job (#754) TODO: refactoring, too much code duplication * More logs and try/catch (#754) * Fix eslint error (#754) * WIP: support synchronization time change (#754) * New frontend #754 * WIP: Create sync front (#754) * Enhance UI, sync creation form (#754) * Warning message when HTTP upload is disallowed * More consistent names (#754) * Binding Front with API (#754) * Add a /me API (#754) * Improve list UI (#754) * Implement creation and deletion routes (#754) * Lint (#754) * Lint again (#754) * WIP: UI for triggering import existing videos (#754) * Implement jobs for syncing and importing channels * Don't sync videos before sync creation + avoid concurrency issue (#754) * Cleanup (#754) * Cleanup: OpenAPI + API rework (#754) * Remove dead code (#754) * Eslint (#754) * Revert the mess with whitespaces in constants.ts (#754) * Some fixes after rebase (#754) * Several fixes after PR remarks (#754) * Front + API: Rename video-channels-sync to video-channel-syncs (#754) * Allow enabling channel sync through UI (#754) * getChannelInfo (#754) * Minor fixes: openapi + model + sql (#754) * Simplified API validators (#754) * Rename MChannelSync to MChannelSyncChannel (#754) * Add command for VideoChannelSync (#754) * Use synchronization.enabled config (#754) * Check parameters test + some fixes (#754) * Fix conflict mistake (#754) * Restrict access to video channel sync list API (#754) * Start adding unit test for synchronization (#754) * Continue testing (#754) * Tests finished + convertion of job to scheduler (#754) * Add lastSyncAt field (#754) * Fix externalRemoteUrl sort + creation date not well formatted (#754) * Small fix (#754) * Factorize addYoutubeDLImport and buildVideo (#754) * Check duplicates on channel not on users (#754) * factorize thumbnail generation (#754) * Fetch error should return status 400 (#754) * Separate video-channel-import and video-channel-sync-latest (#754) * Bump DB migration version after rebase (#754) * Prettier states in UI table (#754) * Add DefaultScope in VideoChannelSyncModel (#754) * Fix audit logs (#754) * Ensure user can upload when importing channel + minor fixes (#754) * Mark synchronization as failed on exception + typos (#754) * Change REST API for importing videos into channel (#754) * Add option for fully synchronize a chnanel (#754) * Return a whole sync object on creation to avoid tricks in Front (#754) * Various remarks (#754) * Single quotes by default (#754) * Rename synchronization to video_channel_synchronization * Add check.latest_videos_count and max_per_user options (#754) * Better channel rendering in list #754 * Allow sorting with channel name and state (#754) * Add missing tests for channel imports (#754) * Prefer using a parent job for channel sync * Styling * Client styling Co-authored-by: Chocobozzz <me@florianbigard.com>
2022-08-10 02:53:39 -05:00
createJobWithChildren (parent: CreateJobArgument & CreateJobOptions, children: (CreateJobArgument & CreateJobOptions)[]) {
2022-08-09 02:09:31 -05:00
return this.flowProducer.add({
...this.buildJobFlowOption(parent),
children: children.map(c => this.buildJobFlowOption(c))
})
}
private buildJobFlowOption (job: CreateJobArgument & CreateJobOptions): FlowJob {
2022-08-09 02:09:31 -05:00
return {
name: 'job',
data: job.payload,
queueName: job.type,
2023-05-02 06:51:06 -05:00
opts: {
failParentOnFailure: true,
...this.buildJobOptions(job.type as JobType, pick(job, [ 'priority', 'delay', 'failParentOnFailure' ]))
}
2022-08-09 02:09:31 -05:00
}
}
2022-08-08 08:48:17 -05:00
private buildJobOptions (type: JobType, options: CreateJobOptions = {}): JobsOptions {
return {
2018-07-10 10:02:20 -05:00
backoff: { delay: 60 * 1000, type: 'exponential' },
2022-08-08 08:48:17 -05:00
attempts: JOB_ATTEMPTS[type],
priority: options.priority,
delay: options.delay,
...this.buildJobRemovalOptions(type)
2018-07-10 10:02:20 -05:00
}
}
2022-08-08 08:48:17 -05:00
// ---------------------------------------------------------------------------
2019-12-04 07:49:59 -06:00
async listForApi (options: {
2020-12-14 05:00:35 -06:00
state?: JobState
2020-01-31 09:56:52 -06:00
start: number
count: number
asc?: boolean
2019-12-04 07:49:59 -06:00
jobType: JobType
2021-08-27 07:32:44 -05:00
}): Promise<Job[]> {
2020-12-14 05:00:35 -06:00
const { state, start, count, asc, jobType } = options
2022-08-09 04:35:07 -05:00
const states = this.buildStateFilter(state)
const filteredJobTypes = this.buildTypeFilter(jobType)
2022-08-09 04:35:07 -05:00
let results: Job[] = []
2019-12-04 07:49:59 -06:00
for (const jobType of filteredJobTypes) {
2022-08-08 03:42:08 -05:00
const queue: Queue = this.queues[jobType]
2018-07-10 10:02:20 -05:00
if (queue === undefined) {
logger.error('Unknown queue %s to list jobs.', jobType)
continue
}
2023-10-18 08:46:18 -05:00
let jobs = await queue.getJobs(states, 0, start + count, asc)
// FIXME: we have sometimes undefined values https://github.com/taskforcesh/bullmq/issues/248
jobs = jobs.filter(j => !!j)
2018-07-10 10:02:20 -05:00
results = results.concat(jobs)
}
2018-07-10 10:02:20 -05:00
results.sort((j1: any, j2: any) => {
if (j1.timestamp < j2.timestamp) return -1
else if (j1.timestamp === j2.timestamp) return 0
2018-07-10 10:02:20 -05:00
return 1
})
2018-07-10 10:02:20 -05:00
if (asc === false) results.reverse()
2018-07-10 10:02:20 -05:00
return results.slice(start, start + count)
}
2020-12-14 05:00:35 -06:00
async count (state: JobState, jobType?: JobType): Promise<number> {
2024-02-15 06:40:53 -06:00
const states = this.buildStateFilter(state)
2022-08-09 04:35:07 -05:00
const filteredJobTypes = this.buildTypeFilter(jobType)
2018-02-12 04:25:09 -06:00
2022-08-09 04:35:07 -05:00
let total = 0
2019-12-04 07:49:59 -06:00
for (const type of filteredJobTypes) {
2020-01-31 09:56:52 -06:00
const queue = this.queues[type]
2018-07-10 10:02:20 -05:00
if (queue === undefined) {
logger.error('Unknown queue %s to count jobs.', type)
continue
}
2018-02-12 04:25:09 -06:00
2018-07-10 10:02:20 -05:00
const counts = await queue.getJobCounts()
2018-02-12 04:25:09 -06:00
2020-12-13 12:27:25 -06:00
for (const s of states) {
total += counts[s]
}
2018-07-10 10:02:20 -05:00
}
2018-02-12 04:25:09 -06:00
2018-07-10 10:02:20 -05:00
return total
2018-02-12 04:25:09 -06:00
}
2022-08-09 04:35:07 -05:00
private buildStateFilter (state?: JobState) {
2023-10-12 02:17:53 -05:00
if (!state) return Array.from(jobStates)
2022-08-09 04:35:07 -05:00
const states = [ state ]
2023-10-12 02:17:53 -05:00
// Include parent and prioritized if filtering on waiting
if (state === 'waiting') {
states.push('waiting-children')
states.push('prioritized')
}
2022-08-09 04:35:07 -05:00
return states
}
private buildTypeFilter (jobType?: JobType) {
if (!jobType) return jobTypes
return jobTypes.filter(t => t === jobType)
}
2022-07-05 08:43:21 -05:00
async getStats () {
const promises = jobTypes.map(async t => ({ jobType: t, counts: await this.queues[t].getJobCounts() }))
return Promise.all(promises)
}
2022-08-08 08:48:17 -05:00
// ---------------------------------------------------------------------------
async removeOldJobs () {
2018-07-10 10:02:20 -05:00
for (const key of Object.keys(this.queues)) {
2022-08-08 03:42:08 -05:00
const queue: Queue = this.queues[key]
2022-11-28 08:16:06 -06:00
await queue.clean(parseDurationToMs('7 days'), 1000, 'completed')
await queue.clean(parseDurationToMs('7 days'), 1000, 'failed')
2018-07-10 10:02:20 -05:00
}
}
2018-08-29 09:26:25 -05:00
private addRepeatableJobs () {
2022-08-08 03:42:08 -05:00
this.queues['videos-views-stats'].add('job', {}, {
repeat: REPEAT_JOBS['videos-views-stats'],
...this.buildJobRemovalOptions('videos-views-stats')
2020-01-31 09:56:52 -06:00
}).catch(err => logger.error('Cannot add repeatable job.', { err }))
if (CONFIG.FEDERATION.VIDEOS.CLEANUP_REMOTE_INTERACTIONS) {
2022-08-08 03:42:08 -05:00
this.queues['activitypub-cleaner'].add('job', {}, {
repeat: REPEAT_JOBS['activitypub-cleaner'],
...this.buildJobRemovalOptions('activitypub-cleaner')
}).catch(err => logger.error('Cannot add repeatable job.', { err }))
}
2018-08-29 09:26:25 -05:00
}
private getJobConcurrency (jobType: JobType) {
if (jobType === 'video-transcoding') return CONFIG.TRANSCODING.CONCURRENCY
if (jobType === 'video-import') return CONFIG.IMPORT.VIDEOS.CONCURRENCY
return JOB_CONCURRENCY[jobType]
}
private buildJobRemovalOptions (queueName: string) {
return {
removeOnComplete: {
// Wants seconds
age: (JOB_REMOVAL_OPTIONS.SUCCESS[queueName] || JOB_REMOVAL_OPTIONS.SUCCESS.DEFAULT) / 1000,
count: JOB_REMOVAL_OPTIONS.COUNT
},
removeOnFail: {
// Wants seconds
age: (JOB_REMOVAL_OPTIONS.FAILURE[queueName] || JOB_REMOVAL_OPTIONS.FAILURE.DEFAULT) / 1000,
count: JOB_REMOVAL_OPTIONS.COUNT / 1000
}
}
}
static get Instance () {
return this.instance || (this.instance = new this())
}
}
// ---------------------------------------------------------------------------
export {
2024-06-13 02:23:12 -05:00
JobQueue, jobTypes
}