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'
7 MStreamingPlaylistFiles,
11 MVideoRedundancyFileVideo,
12 MVideoRedundancyStreamingPlaylistVideo,
13 MVideoRedundancyVideo,
15 } from '@server/types/models'
16 import { VideosRedundancyStrategy } from '../../../shared/models/redundancy'
17 import { logger } from '../../helpers/logger'
18 import { downloadWebTorrentVideo, generateMagnetUri } from '../../helpers/webtorrent'
19 import { CONFIG } from '../../initializers/config'
20 import { HLS_REDUNDANCY_DIRECTORY, REDUNDANCY, VIDEO_IMPORT_TIMEOUT } from '../../initializers/constants'
21 import { VideoRedundancyModel } from '../../models/redundancy/video-redundancy'
22 import { sendCreateCacheFile, sendUpdateCacheFile } from '../activitypub/send'
23 import { getLocalVideoCacheFileActivityPubUrl, getLocalVideoCacheStreamingPlaylistActivityPubUrl } from '../activitypub/url'
24 import { getOrCreateAPVideo } from '../activitypub/videos'
25 import { downloadPlaylistSegments } from '../hls'
26 import { removeVideoRedundancy } from '../redundancy'
27 import { generateHLSRedundancyUrl, generateWebTorrentRedundancyUrl } from '../video-urls'
28 import { AbstractScheduler } from './abstract-scheduler'
30 type CandidateToDuplicate = {
31 redundancy: VideosRedundancyStrategy
32 video: MVideoWithAllFiles
34 streamingPlaylists: MStreamingPlaylistFiles[]
37 function isMVideoRedundancyFileVideo (
38 o: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo
39 ): o is MVideoRedundancyFileVideo {
40 return !!(o as MVideoRedundancyFileVideo).VideoFile
43 export class VideosRedundancyScheduler extends AbstractScheduler {
45 private static instance: VideosRedundancyScheduler
47 protected schedulerIntervalMs = CONFIG.REDUNDANCY.VIDEOS.CHECK_INTERVAL
49 private constructor () {
53 async createManualRedundancy (videoId: number) {
54 const videoToDuplicate = await VideoModel.loadWithFiles(videoId)
56 if (!videoToDuplicate) {
57 logger.warn('Video to manually duplicate %d does not exist anymore.', videoId)
61 return this.createVideoRedundancies({
62 video: videoToDuplicate,
64 files: videoToDuplicate.VideoFiles,
65 streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists
69 protected async internalExecute () {
70 for (const redundancyConfig of CONFIG.REDUNDANCY.VIDEOS.STRATEGIES) {
71 logger.info('Running redundancy scheduler for strategy %s.', redundancyConfig.strategy)
74 const videoToDuplicate = await this.findVideoToDuplicate(redundancyConfig)
75 if (!videoToDuplicate) continue
77 const candidateToDuplicate = {
78 video: videoToDuplicate,
79 redundancy: redundancyConfig,
80 files: videoToDuplicate.VideoFiles,
81 streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists
84 await this.purgeCacheIfNeeded(candidateToDuplicate)
86 if (await this.isTooHeavy(candidateToDuplicate)) {
87 logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url)
91 logger.info('Will duplicate video %s in redundancy scheduler "%s".', videoToDuplicate.url, redundancyConfig.strategy)
93 await this.createVideoRedundancies(candidateToDuplicate)
95 logger.error('Cannot run videos redundancy %s.', redundancyConfig.strategy, { err })
99 await this.extendsLocalExpiration()
101 await this.purgeRemoteExpired()
104 static get Instance () {
105 return this.instance || (this.instance = new this())
108 private async extendsLocalExpiration () {
109 const expired = await VideoRedundancyModel.listLocalExpired()
111 for (const redundancyModel of expired) {
113 const redundancyConfig = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
114 const candidate: CandidateToDuplicate = {
115 redundancy: redundancyConfig,
118 streamingPlaylists: []
121 // If the administrator disabled the redundancy or decreased the cache size, remove this redundancy instead of extending it
122 if (!redundancyConfig || await this.isTooHeavy(candidate)) {
123 logger.info('Destroying redundancy %s because the cache size %s is too heavy.', redundancyModel.url, redundancyModel.strategy)
124 await removeVideoRedundancy(redundancyModel)
126 await this.extendsRedundancy(redundancyModel)
130 'Cannot extend or remove expiration of %s video from our redundancy system.', this.buildEntryLogId(redundancyModel),
137 private async extendsRedundancy (redundancyModel: MVideoRedundancyVideo) {
138 const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
139 // Redundancy strategy disabled, remove our redundancy instead of extending expiration
141 await removeVideoRedundancy(redundancyModel)
145 await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime)
148 private async purgeRemoteExpired () {
149 const expired = await VideoRedundancyModel.listRemoteExpired()
151 for (const redundancyModel of expired) {
153 await removeVideoRedundancy(redundancyModel)
155 logger.error('Cannot remove redundancy %s from our redundancy system.', this.buildEntryLogId(redundancyModel))
160 private findVideoToDuplicate (cache: VideosRedundancyStrategy) {
161 if (cache.strategy === 'most-views') {
162 return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
165 if (cache.strategy === 'trending') {
166 return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
169 if (cache.strategy === 'recently-added') {
170 const minViews = cache.minViews
171 return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
175 private async createVideoRedundancies (data: CandidateToDuplicate) {
176 const video = await this.loadAndRefreshVideo(data.video.url)
179 logger.info('Video %s we want to duplicate does not existing anymore, skipping.', data.video.url)
184 for (const file of data.files) {
185 const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id)
186 if (existingRedundancy) {
187 await this.extendsRedundancy(existingRedundancy)
192 await this.createVideoFileRedundancy(data.redundancy, video, file)
195 for (const streamingPlaylist of data.streamingPlaylists) {
196 const existingRedundancy = await VideoRedundancyModel.loadLocalByStreamingPlaylistId(streamingPlaylist.id)
197 if (existingRedundancy) {
198 await this.extendsRedundancy(existingRedundancy)
203 await this.createStreamingPlaylistRedundancy(data.redundancy, video, streamingPlaylist)
207 private async createVideoFileRedundancy (redundancy: VideosRedundancyStrategy | null, video: MVideoAccountLight, fileArg: MVideoFile) {
208 let strategy = 'manual'
209 let expiresOn: Date = null
212 strategy = redundancy.strategy
213 expiresOn = this.buildNewExpiration(redundancy.minLifetime)
216 const file = fileArg as MVideoFileVideo
219 const serverActor = await getServerActor()
221 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, strategy)
223 const trackerUrls = await TrackerModel.listUrlsByVideoId(video.id)
224 const magnetUri = generateMagnetUri(video, file, trackerUrls)
226 const tmpPath = await downloadWebTorrentVideo({ magnetUri }, VIDEO_IMPORT_TIMEOUT)
228 const destPath = join(CONFIG.STORAGE.REDUNDANCY_DIR, file.filename)
229 await move(tmpPath, destPath, { overwrite: true })
231 const createdModel: MVideoRedundancyFileVideo = await VideoRedundancyModel.create({
233 url: getLocalVideoCacheFileActivityPubUrl(file),
234 fileUrl: generateWebTorrentRedundancyUrl(file),
236 videoFileId: file.id,
237 actorId: serverActor.id
240 createdModel.VideoFile = file
242 await sendCreateCacheFile(serverActor, video, createdModel)
244 logger.info('Duplicated %s - %d -> %s.', video.url, file.resolution, createdModel.url)
247 private async createStreamingPlaylistRedundancy (
248 redundancy: VideosRedundancyStrategy,
249 video: MVideoAccountLight,
250 playlistArg: MStreamingPlaylistFiles
252 let strategy = 'manual'
253 let expiresOn: Date = null
256 strategy = redundancy.strategy
257 expiresOn = this.buildNewExpiration(redundancy.minLifetime)
260 const playlist = Object.assign(playlistArg, { Video: video })
261 const serverActor = await getServerActor()
263 logger.info('Duplicating %s streaming playlist in videos redundancy with "%s" strategy.', video.url, strategy)
265 const destDirectory = join(HLS_REDUNDANCY_DIRECTORY, video.uuid)
266 const masterPlaylistUrl = playlist.getMasterPlaylistUrl(video)
268 const maxSizeKB = this.getTotalFileSizes([], [ playlist ]) / 1000
269 const toleranceKB = maxSizeKB + ((5 * maxSizeKB) / 100) // 5% more tolerance
270 await downloadPlaylistSegments(masterPlaylistUrl, destDirectory, VIDEO_IMPORT_TIMEOUT, toleranceKB)
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.', masterPlaylistUrl, 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 { totalUsed } = await VideoRedundancyModel.getStats(candidateToDuplicate.redundancy.strategy)
321 const totalWillDuplicate = totalUsed + 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.getMasterPlaylistUrl(object.VideoStreamingPlaylist.Video)}`
336 private getTotalFileSizes (files: MVideoFile[], playlists: MStreamingPlaylistFiles[]): number {
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 getOrCreateAPVideo(getVideoOptions)