1 import { move } from 'fs-extra'
2 import { join } from 'path'
3 import { getServerActor } from '@server/models/application/application'
4 import { TrackerModel } from '@server/models/server/tracker'
5 import { VideoModel } from '@server/models/video/video'
8 MStreamingPlaylistFiles,
9 MStreamingPlaylistVideo,
13 MVideoRedundancyFileVideo,
14 MVideoRedundancyStreamingPlaylistVideo,
15 MVideoRedundancyVideo,
17 } from '@server/types/models'
18 import { VideosRedundancyStrategy } from '../../../shared/models/redundancy'
19 import { logger } from '../../helpers/logger'
20 import { downloadWebTorrentVideo, generateMagnetUri } from '../../helpers/webtorrent'
21 import { CONFIG } from '../../initializers/config'
22 import { HLS_REDUNDANCY_DIRECTORY, REDUNDANCY, VIDEO_IMPORT_TIMEOUT } from '../../initializers/constants'
23 import { VideoRedundancyModel } from '../../models/redundancy/video-redundancy'
24 import { sendCreateCacheFile, sendUpdateCacheFile } from '../activitypub/send'
25 import { getLocalVideoCacheFileActivityPubUrl, getLocalVideoCacheStreamingPlaylistActivityPubUrl } from '../activitypub/url'
26 import { getOrCreateVideoAndAccountAndChannel } from '../activitypub/videos'
27 import { downloadPlaylistSegments } from '../hls'
28 import { removeVideoRedundancy } from '../redundancy'
29 import { generateHLSRedundancyUrl, generateWebTorrentRedundancyUrl } from '../video-paths'
30 import { AbstractScheduler } from './abstract-scheduler'
32 type CandidateToDuplicate = {
33 redundancy: VideosRedundancyStrategy
34 video: MVideoWithAllFiles
36 streamingPlaylists: MStreamingPlaylistFiles[]
39 function isMVideoRedundancyFileVideo (
40 o: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo
41 ): o is MVideoRedundancyFileVideo {
42 return !!(o as MVideoRedundancyFileVideo).VideoFile
45 export class VideosRedundancyScheduler extends AbstractScheduler {
47 private static instance: VideosRedundancyScheduler
49 protected schedulerIntervalMs = CONFIG.REDUNDANCY.VIDEOS.CHECK_INTERVAL
51 private constructor () {
55 async createManualRedundancy (videoId: number) {
56 const videoToDuplicate = await VideoModel.loadWithFiles(videoId)
58 if (!videoToDuplicate) {
59 logger.warn('Video to manually duplicate %d does not exist anymore.', videoId)
63 return this.createVideoRedundancies({
64 video: videoToDuplicate,
66 files: videoToDuplicate.VideoFiles,
67 streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists
71 protected async internalExecute () {
72 for (const redundancyConfig of CONFIG.REDUNDANCY.VIDEOS.STRATEGIES) {
73 logger.info('Running redundancy scheduler for strategy %s.', redundancyConfig.strategy)
76 const videoToDuplicate = await this.findVideoToDuplicate(redundancyConfig)
77 if (!videoToDuplicate) continue
79 const candidateToDuplicate = {
80 video: videoToDuplicate,
81 redundancy: redundancyConfig,
82 files: videoToDuplicate.VideoFiles,
83 streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists
86 await this.purgeCacheIfNeeded(candidateToDuplicate)
88 if (await this.isTooHeavy(candidateToDuplicate)) {
89 logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url)
93 logger.info('Will duplicate video %s in redundancy scheduler "%s".', videoToDuplicate.url, redundancyConfig.strategy)
95 await this.createVideoRedundancies(candidateToDuplicate)
97 logger.error('Cannot run videos redundancy %s.', redundancyConfig.strategy, { err })
101 await this.extendsLocalExpiration()
103 await this.purgeRemoteExpired()
106 static get Instance () {
107 return this.instance || (this.instance = new this())
110 private async extendsLocalExpiration () {
111 const expired = await VideoRedundancyModel.listLocalExpired()
113 for (const redundancyModel of expired) {
115 const redundancyConfig = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
116 const candidate: CandidateToDuplicate = {
117 redundancy: redundancyConfig,
120 streamingPlaylists: []
123 // If the administrator disabled the redundancy or decreased the cache size, remove this redundancy instead of extending it
124 if (!redundancyConfig || await this.isTooHeavy(candidate)) {
125 logger.info('Destroying redundancy %s because the cache size %s is too heavy.', redundancyModel.url, redundancyModel.strategy)
126 await removeVideoRedundancy(redundancyModel)
128 await this.extendsRedundancy(redundancyModel)
132 'Cannot extend or remove expiration of %s video from our redundancy system.', this.buildEntryLogId(redundancyModel),
139 private async extendsRedundancy (redundancyModel: MVideoRedundancyVideo) {
140 const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
141 // Redundancy strategy disabled, remove our redundancy instead of extending expiration
143 await removeVideoRedundancy(redundancyModel)
147 await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime)
150 private async purgeRemoteExpired () {
151 const expired = await VideoRedundancyModel.listRemoteExpired()
153 for (const redundancyModel of expired) {
155 await removeVideoRedundancy(redundancyModel)
157 logger.error('Cannot remove redundancy %s from our redundancy system.', this.buildEntryLogId(redundancyModel))
162 private findVideoToDuplicate (cache: VideosRedundancyStrategy) {
163 if (cache.strategy === 'most-views') {
164 return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
167 if (cache.strategy === 'trending') {
168 return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
171 if (cache.strategy === 'recently-added') {
172 const minViews = cache.minViews
173 return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
177 private async createVideoRedundancies (data: CandidateToDuplicate) {
178 const video = await this.loadAndRefreshVideo(data.video.url)
181 logger.info('Video %s we want to duplicate does not existing anymore, skipping.', data.video.url)
186 for (const file of data.files) {
187 const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id)
188 if (existingRedundancy) {
189 await this.extendsRedundancy(existingRedundancy)
194 await this.createVideoFileRedundancy(data.redundancy, video, file)
197 for (const streamingPlaylist of data.streamingPlaylists) {
198 const existingRedundancy = await VideoRedundancyModel.loadLocalByStreamingPlaylistId(streamingPlaylist.id)
199 if (existingRedundancy) {
200 await this.extendsRedundancy(existingRedundancy)
205 await this.createStreamingPlaylistRedundancy(data.redundancy, video, streamingPlaylist)
209 private async createVideoFileRedundancy (redundancy: VideosRedundancyStrategy | null, video: MVideoAccountLight, fileArg: MVideoFile) {
210 let strategy = 'manual'
211 let expiresOn: Date = null
214 strategy = redundancy.strategy
215 expiresOn = this.buildNewExpiration(redundancy.minLifetime)
218 const file = fileArg as MVideoFileVideo
221 const serverActor = await getServerActor()
223 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, strategy)
225 const trackerUrls = await TrackerModel.listUrlsByVideoId(video.id)
226 const magnetUri = generateMagnetUri(video, file, trackerUrls)
228 const tmpPath = await downloadWebTorrentVideo({ magnetUri }, VIDEO_IMPORT_TIMEOUT)
230 const destPath = join(CONFIG.STORAGE.REDUNDANCY_DIR, file.filename)
231 await move(tmpPath, destPath, { overwrite: true })
233 const createdModel: MVideoRedundancyFileVideo = await VideoRedundancyModel.create({
235 url: getLocalVideoCacheFileActivityPubUrl(file),
236 fileUrl: generateWebTorrentRedundancyUrl(file),
238 videoFileId: file.id,
239 actorId: serverActor.id
242 createdModel.VideoFile = file
244 await sendCreateCacheFile(serverActor, video, createdModel)
246 logger.info('Duplicated %s - %d -> %s.', video.url, file.resolution, createdModel.url)
249 private async createStreamingPlaylistRedundancy (
250 redundancy: VideosRedundancyStrategy,
251 video: MVideoAccountLight,
252 playlistArg: MStreamingPlaylist
254 let strategy = 'manual'
255 let expiresOn: Date = null
258 strategy = redundancy.strategy
259 expiresOn = this.buildNewExpiration(redundancy.minLifetime)
262 const playlist = playlistArg as MStreamingPlaylistVideo
263 playlist.Video = video
265 const serverActor = await getServerActor()
267 logger.info('Duplicating %s streaming playlist in videos redundancy with "%s" strategy.', video.url, strategy)
269 const destDirectory = join(HLS_REDUNDANCY_DIRECTORY, video.uuid)
270 await downloadPlaylistSegments(playlist.playlistUrl, destDirectory, VIDEO_IMPORT_TIMEOUT)
272 const createdModel: MVideoRedundancyStreamingPlaylistVideo = await VideoRedundancyModel.create({
274 url: getLocalVideoCacheStreamingPlaylistActivityPubUrl(video, playlist),
275 fileUrl: generateHLSRedundancyUrl(video, playlistArg),
277 videoStreamingPlaylistId: playlist.id,
278 actorId: serverActor.id
281 createdModel.VideoStreamingPlaylist = playlist
283 await sendCreateCacheFile(serverActor, video, createdModel)
285 logger.info('Duplicated playlist %s -> %s.', playlist.playlistUrl, createdModel.url)
288 private async extendsExpirationOf (redundancy: MVideoRedundancyVideo, expiresAfterMs: number) {
289 logger.info('Extending expiration of %s.', redundancy.url)
291 const serverActor = await getServerActor()
293 redundancy.expiresOn = this.buildNewExpiration(expiresAfterMs)
294 await redundancy.save()
296 await sendUpdateCacheFile(serverActor, redundancy)
299 private async purgeCacheIfNeeded (candidateToDuplicate: CandidateToDuplicate) {
300 while (await this.isTooHeavy(candidateToDuplicate)) {
301 const redundancy = candidateToDuplicate.redundancy
302 const toDelete = await VideoRedundancyModel.loadOldestLocalExpired(redundancy.strategy, redundancy.minLifetime)
303 if (!toDelete) return
305 const videoId = toDelete.VideoFile
306 ? toDelete.VideoFile.videoId
307 : toDelete.VideoStreamingPlaylist.videoId
309 const redundancies = await VideoRedundancyModel.listLocalByVideoId(videoId)
311 for (const redundancy of redundancies) {
312 await removeVideoRedundancy(redundancy)
317 private async isTooHeavy (candidateToDuplicate: CandidateToDuplicate) {
318 const maxSize = candidateToDuplicate.redundancy.size
320 const totalDuplicated = await VideoRedundancyModel.getTotalDuplicated(candidateToDuplicate.redundancy.strategy)
321 const totalWillDuplicate = totalDuplicated + this.getTotalFileSizes(candidateToDuplicate.files, candidateToDuplicate.streamingPlaylists)
323 return totalWillDuplicate > maxSize
326 private buildNewExpiration (expiresAfterMs: number) {
327 return new Date(Date.now() + expiresAfterMs)
330 private buildEntryLogId (object: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo) {
331 if (isMVideoRedundancyFileVideo(object)) return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
333 return `${object.VideoStreamingPlaylist.playlistUrl}`
336 private getTotalFileSizes (files: MVideoFile[], playlists: MStreamingPlaylistFiles[]) {
337 const fileReducer = (previous: number, current: MVideoFile) => previous + current.size
340 for (const p of playlists) {
341 allFiles = allFiles.concat(p.VideoFiles)
344 return allFiles.reduce(fileReducer, 0)
347 private async loadAndRefreshVideo (videoUrl: string) {
348 // We need more attributes and check if the video still exists
349 const getVideoOptions = {
350 videoObject: videoUrl,
351 syncParam: { likes: false, dislikes: false, shares: false, comments: false, thumbnail: false, refreshVideo: true },
352 fetchType: 'all' as 'all'
354 const { video } = await getOrCreateVideoAndAccountAndChannel(getVideoOptions)