1 import { AbstractScheduler } from './abstract-scheduler'
2 import { HLS_REDUNDANCY_DIRECTORY, REDUNDANCY, VIDEO_IMPORT_TIMEOUT, WEBSERVER } from '../../initializers/constants'
3 import { logger } from '../../helpers/logger'
4 import { VideosRedundancy } from '../../../shared/models/redundancy'
5 import { VideoRedundancyModel } from '../../models/redundancy/video-redundancy'
6 import { downloadWebTorrentVideo, generateMagnetUri } from '../../helpers/webtorrent'
7 import { join } from 'path'
8 import { move } from 'fs-extra'
9 import { getServerActor } from '../../helpers/utils'
10 import { sendCreateCacheFile, sendUpdateCacheFile } from '../activitypub/send'
11 import { getVideoCacheFileActivityPubUrl, getVideoCacheStreamingPlaylistActivityPubUrl } from '../activitypub/url'
12 import { removeVideoRedundancy } from '../redundancy'
13 import { getOrCreateVideoAndAccountAndChannel } from '../activitypub'
14 import { downloadPlaylistSegments } from '../hls'
15 import { CONFIG } from '../../initializers/config'
17 MStreamingPlaylist, MStreamingPlaylistFiles,
18 MStreamingPlaylistVideo,
22 MVideoRedundancyFileVideo,
23 MVideoRedundancyStreamingPlaylistVideo,
24 MVideoRedundancyVideo,
26 } from '@server/typings/models'
27 import { getVideoFilename } from '../video-paths'
29 type CandidateToDuplicate = {
30 redundancy: VideosRedundancy,
31 video: MVideoWithAllFiles,
33 streamingPlaylists: MStreamingPlaylistFiles[]
36 function isMVideoRedundancyFileVideo (
37 o: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo
38 ): o is MVideoRedundancyFileVideo {
39 return !!(o as MVideoRedundancyFileVideo).VideoFile
42 export class VideosRedundancyScheduler extends AbstractScheduler {
44 private static instance: AbstractScheduler
46 protected schedulerIntervalMs = CONFIG.REDUNDANCY.VIDEOS.CHECK_INTERVAL
48 private constructor () {
52 protected async internalExecute () {
53 for (const redundancyConfig of CONFIG.REDUNDANCY.VIDEOS.STRATEGIES) {
54 logger.info('Running redundancy scheduler for strategy %s.', redundancyConfig.strategy)
57 const videoToDuplicate = await this.findVideoToDuplicate(redundancyConfig)
58 if (!videoToDuplicate) continue
60 const candidateToDuplicate = {
61 video: videoToDuplicate,
62 redundancy: redundancyConfig,
63 files: videoToDuplicate.VideoFiles,
64 streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists
67 await this.purgeCacheIfNeeded(candidateToDuplicate)
69 if (await this.isTooHeavy(candidateToDuplicate)) {
70 logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url)
74 logger.info('Will duplicate video %s in redundancy scheduler "%s".', videoToDuplicate.url, redundancyConfig.strategy)
76 await this.createVideoRedundancies(candidateToDuplicate)
78 logger.error('Cannot run videos redundancy %s.', redundancyConfig.strategy, { err })
82 await this.extendsLocalExpiration()
84 await this.purgeRemoteExpired()
87 static get Instance () {
88 return this.instance || (this.instance = new this())
91 private async extendsLocalExpiration () {
92 const expired = await VideoRedundancyModel.listLocalExpired()
94 for (const redundancyModel of expired) {
96 const redundancyConfig = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
98 redundancy: redundancyConfig,
101 streamingPlaylists: []
104 // If the administrator disabled the redundancy or decreased the cache size, remove this redundancy instead of extending it
105 if (!redundancyConfig || await this.isTooHeavy(candidate)) {
106 logger.info('Destroying redundancy %s because the cache size %s is too heavy.', redundancyModel.url, redundancyModel.strategy)
107 await removeVideoRedundancy(redundancyModel)
109 await this.extendsRedundancy(redundancyModel)
113 'Cannot extend or remove expiration of %s video from our redundancy system.', this.buildEntryLogId(redundancyModel),
120 private async extendsRedundancy (redundancyModel: MVideoRedundancyVideo) {
121 const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
122 // Redundancy strategy disabled, remove our redundancy instead of extending expiration
124 await removeVideoRedundancy(redundancyModel)
128 await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime)
131 private async purgeRemoteExpired () {
132 const expired = await VideoRedundancyModel.listRemoteExpired()
134 for (const redundancyModel of expired) {
136 await removeVideoRedundancy(redundancyModel)
138 logger.error('Cannot remove redundancy %s from our redundancy system.', this.buildEntryLogId(redundancyModel))
143 private findVideoToDuplicate (cache: VideosRedundancy) {
144 if (cache.strategy === 'most-views') {
145 return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
148 if (cache.strategy === 'trending') {
149 return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
152 if (cache.strategy === 'recently-added') {
153 const minViews = cache.minViews
154 return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
158 private async createVideoRedundancies (data: CandidateToDuplicate) {
159 const video = await this.loadAndRefreshVideo(data.video.url)
162 logger.info('Video %s we want to duplicate does not existing anymore, skipping.', data.video.url)
167 for (const file of data.files) {
168 const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id)
169 if (existingRedundancy) {
170 await this.extendsRedundancy(existingRedundancy)
175 await this.createVideoFileRedundancy(data.redundancy, video, file)
178 for (const streamingPlaylist of data.streamingPlaylists) {
179 const existingRedundancy = await VideoRedundancyModel.loadLocalByStreamingPlaylistId(streamingPlaylist.id)
180 if (existingRedundancy) {
181 await this.extendsRedundancy(existingRedundancy)
186 await this.createStreamingPlaylistRedundancy(data.redundancy, video, streamingPlaylist)
190 private async createVideoFileRedundancy (redundancy: VideosRedundancy, video: MVideoAccountLight, fileArg: MVideoFile) {
191 const file = fileArg as MVideoFileVideo
194 const serverActor = await getServerActor()
196 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, redundancy.strategy)
198 const { baseUrlHttp, baseUrlWs } = video.getBaseUrls()
199 const magnetUri = generateMagnetUri(video, file, baseUrlHttp, baseUrlWs)
201 const tmpPath = await downloadWebTorrentVideo({ magnetUri }, VIDEO_IMPORT_TIMEOUT)
203 const destPath = join(CONFIG.STORAGE.REDUNDANCY_DIR, getVideoFilename(video, file))
204 await move(tmpPath, destPath, { overwrite: true })
206 const createdModel: MVideoRedundancyFileVideo = await VideoRedundancyModel.create({
207 expiresOn: this.buildNewExpiration(redundancy.minLifetime),
208 url: getVideoCacheFileActivityPubUrl(file),
209 fileUrl: video.getVideoRedundancyUrl(file, WEBSERVER.URL),
210 strategy: redundancy.strategy,
211 videoFileId: file.id,
212 actorId: serverActor.id
215 createdModel.VideoFile = file
217 await sendCreateCacheFile(serverActor, video, createdModel)
219 logger.info('Duplicated %s - %d -> %s.', video.url, file.resolution, createdModel.url)
222 private async createStreamingPlaylistRedundancy (
223 redundancy: VideosRedundancy,
224 video: MVideoAccountLight,
225 playlistArg: MStreamingPlaylist
227 const playlist = playlistArg as MStreamingPlaylistVideo
228 playlist.Video = video
230 const serverActor = await getServerActor()
232 logger.info('Duplicating %s streaming playlist in videos redundancy with "%s" strategy.', video.url, redundancy.strategy)
234 const destDirectory = join(HLS_REDUNDANCY_DIRECTORY, video.uuid)
235 await downloadPlaylistSegments(playlist.playlistUrl, destDirectory, VIDEO_IMPORT_TIMEOUT)
237 const createdModel: MVideoRedundancyStreamingPlaylistVideo = await VideoRedundancyModel.create({
238 expiresOn: this.buildNewExpiration(redundancy.minLifetime),
239 url: getVideoCacheStreamingPlaylistActivityPubUrl(video, playlist),
240 fileUrl: playlist.getVideoRedundancyUrl(WEBSERVER.URL),
241 strategy: redundancy.strategy,
242 videoStreamingPlaylistId: playlist.id,
243 actorId: serverActor.id
246 createdModel.VideoStreamingPlaylist = playlist
248 await sendCreateCacheFile(serverActor, video, createdModel)
250 logger.info('Duplicated playlist %s -> %s.', playlist.playlistUrl, createdModel.url)
253 private async extendsExpirationOf (redundancy: MVideoRedundancyVideo, expiresAfterMs: number) {
254 logger.info('Extending expiration of %s.', redundancy.url)
256 const serverActor = await getServerActor()
258 redundancy.expiresOn = this.buildNewExpiration(expiresAfterMs)
259 await redundancy.save()
261 await sendUpdateCacheFile(serverActor, redundancy)
264 private async purgeCacheIfNeeded (candidateToDuplicate: CandidateToDuplicate) {
265 while (await this.isTooHeavy(candidateToDuplicate)) {
266 const redundancy = candidateToDuplicate.redundancy
267 const toDelete = await VideoRedundancyModel.loadOldestLocalExpired(redundancy.strategy, redundancy.minLifetime)
268 if (!toDelete) return
270 await removeVideoRedundancy(toDelete)
274 private async isTooHeavy (candidateToDuplicate: CandidateToDuplicate) {
275 const maxSize = candidateToDuplicate.redundancy.size
277 const totalDuplicated = await VideoRedundancyModel.getTotalDuplicated(candidateToDuplicate.redundancy.strategy)
278 const totalWillDuplicate = totalDuplicated + this.getTotalFileSizes(candidateToDuplicate.files, candidateToDuplicate.streamingPlaylists)
280 return totalWillDuplicate > maxSize
283 private buildNewExpiration (expiresAfterMs: number) {
284 return new Date(Date.now() + expiresAfterMs)
287 private buildEntryLogId (object: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo) {
288 if (isMVideoRedundancyFileVideo(object)) return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
290 return `${object.VideoStreamingPlaylist.playlistUrl}`
293 private getTotalFileSizes (files: MVideoFile[], playlists: MStreamingPlaylistFiles[]) {
294 const fileReducer = (previous: number, current: MVideoFile) => previous + current.size
297 for (const p of playlists) {
298 allFiles = allFiles.concat(p.VideoFiles)
301 return allFiles.reduce(fileReducer, 0)
304 private async loadAndRefreshVideo (videoUrl: string) {
305 // We need more attributes and check if the video still exists
306 const getVideoOptions = {
307 videoObject: videoUrl,
308 syncParam: { likes: false, dislikes: false, shares: false, comments: false, thumbnail: false, refreshVideo: true },
309 fetchType: 'all' as 'all'
311 const { video } = await getOrCreateVideoAndAccountAndChannel(getVideoOptions)