1 import { move } from 'fs-extra'
2 import { join } from 'path'
3 import { getServerActor } from '@server/models/application/application'
4 import { VideoModel } from '@server/models/video/video'
7 MStreamingPlaylistFiles,
8 MStreamingPlaylistVideo,
12 MVideoRedundancyFileVideo,
13 MVideoRedundancyStreamingPlaylistVideo,
14 MVideoRedundancyVideo,
16 } from '@server/types/models'
17 import { VideosRedundancyStrategy } from '../../../shared/models/redundancy'
18 import { logger } from '../../helpers/logger'
19 import { downloadWebTorrentVideo, generateMagnetUri } from '../../helpers/webtorrent'
20 import { CONFIG } from '../../initializers/config'
21 import { HLS_REDUNDANCY_DIRECTORY, REDUNDANCY, VIDEO_IMPORT_TIMEOUT, WEBSERVER } from '../../initializers/constants'
22 import { VideoRedundancyModel } from '../../models/redundancy/video-redundancy'
23 import { sendCreateCacheFile, sendUpdateCacheFile } from '../activitypub/send'
24 import { getLocalVideoCacheFileActivityPubUrl, getLocalVideoCacheStreamingPlaylistActivityPubUrl } from '../activitypub/url'
25 import { getOrCreateVideoAndAccountAndChannel } from '../activitypub/videos'
26 import { downloadPlaylistSegments } from '../hls'
27 import { removeVideoRedundancy } from '../redundancy'
28 import { getVideoFilename } from '../video-paths'
29 import { AbstractScheduler } from './abstract-scheduler'
31 type CandidateToDuplicate = {
32 redundancy: VideosRedundancyStrategy
33 video: MVideoWithAllFiles
35 streamingPlaylists: MStreamingPlaylistFiles[]
38 function isMVideoRedundancyFileVideo (
39 o: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo
40 ): o is MVideoRedundancyFileVideo {
41 return !!(o as MVideoRedundancyFileVideo).VideoFile
44 export class VideosRedundancyScheduler extends AbstractScheduler {
46 private static instance: VideosRedundancyScheduler
48 protected schedulerIntervalMs = CONFIG.REDUNDANCY.VIDEOS.CHECK_INTERVAL
50 private constructor () {
54 async createManualRedundancy (videoId: number) {
55 const videoToDuplicate = await VideoModel.loadWithFiles(videoId)
57 if (!videoToDuplicate) {
58 logger.warn('Video to manually duplicate %d does not exist anymore.', videoId)
62 return this.createVideoRedundancies({
63 video: videoToDuplicate,
65 files: videoToDuplicate.VideoFiles,
66 streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists
70 protected async internalExecute () {
71 for (const redundancyConfig of CONFIG.REDUNDANCY.VIDEOS.STRATEGIES) {
72 logger.info('Running redundancy scheduler for strategy %s.', redundancyConfig.strategy)
75 const videoToDuplicate = await this.findVideoToDuplicate(redundancyConfig)
76 if (!videoToDuplicate) continue
78 const candidateToDuplicate = {
79 video: videoToDuplicate,
80 redundancy: redundancyConfig,
81 files: videoToDuplicate.VideoFiles,
82 streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists
85 await this.purgeCacheIfNeeded(candidateToDuplicate)
87 if (await this.isTooHeavy(candidateToDuplicate)) {
88 logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url)
92 logger.info('Will duplicate video %s in redundancy scheduler "%s".', videoToDuplicate.url, redundancyConfig.strategy)
94 await this.createVideoRedundancies(candidateToDuplicate)
96 logger.error('Cannot run videos redundancy %s.', redundancyConfig.strategy, { err })
100 await this.extendsLocalExpiration()
102 await this.purgeRemoteExpired()
105 static get Instance () {
106 return this.instance || (this.instance = new this())
109 private async extendsLocalExpiration () {
110 const expired = await VideoRedundancyModel.listLocalExpired()
112 for (const redundancyModel of expired) {
114 const redundancyConfig = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
115 const candidate: CandidateToDuplicate = {
116 redundancy: redundancyConfig,
119 streamingPlaylists: []
122 // If the administrator disabled the redundancy or decreased the cache size, remove this redundancy instead of extending it
123 if (!redundancyConfig || await this.isTooHeavy(candidate)) {
124 logger.info('Destroying redundancy %s because the cache size %s is too heavy.', redundancyModel.url, redundancyModel.strategy)
125 await removeVideoRedundancy(redundancyModel)
127 await this.extendsRedundancy(redundancyModel)
131 'Cannot extend or remove expiration of %s video from our redundancy system.', this.buildEntryLogId(redundancyModel),
138 private async extendsRedundancy (redundancyModel: MVideoRedundancyVideo) {
139 const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
140 // Redundancy strategy disabled, remove our redundancy instead of extending expiration
142 await removeVideoRedundancy(redundancyModel)
146 await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime)
149 private async purgeRemoteExpired () {
150 const expired = await VideoRedundancyModel.listRemoteExpired()
152 for (const redundancyModel of expired) {
154 await removeVideoRedundancy(redundancyModel)
156 logger.error('Cannot remove redundancy %s from our redundancy system.', this.buildEntryLogId(redundancyModel))
161 private findVideoToDuplicate (cache: VideosRedundancyStrategy) {
162 if (cache.strategy === 'most-views') {
163 return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
166 if (cache.strategy === 'trending') {
167 return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
170 if (cache.strategy === 'recently-added') {
171 const minViews = cache.minViews
172 return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
176 private async createVideoRedundancies (data: CandidateToDuplicate) {
177 const video = await this.loadAndRefreshVideo(data.video.url)
180 logger.info('Video %s we want to duplicate does not existing anymore, skipping.', data.video.url)
185 for (const file of data.files) {
186 const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id)
187 if (existingRedundancy) {
188 await this.extendsRedundancy(existingRedundancy)
193 await this.createVideoFileRedundancy(data.redundancy, video, file)
196 for (const streamingPlaylist of data.streamingPlaylists) {
197 const existingRedundancy = await VideoRedundancyModel.loadLocalByStreamingPlaylistId(streamingPlaylist.id)
198 if (existingRedundancy) {
199 await this.extendsRedundancy(existingRedundancy)
204 await this.createStreamingPlaylistRedundancy(data.redundancy, video, streamingPlaylist)
208 private async createVideoFileRedundancy (redundancy: VideosRedundancyStrategy | null, video: MVideoAccountLight, fileArg: MVideoFile) {
209 let strategy = 'manual'
210 let expiresOn: Date = null
213 strategy = redundancy.strategy
214 expiresOn = this.buildNewExpiration(redundancy.minLifetime)
217 const file = fileArg as MVideoFileVideo
220 const serverActor = await getServerActor()
222 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, strategy)
224 const { baseUrlHttp, baseUrlWs } = video.getBaseUrls()
225 const magnetUri = generateMagnetUri(video, file, baseUrlHttp, baseUrlWs)
227 const tmpPath = await downloadWebTorrentVideo({ magnetUri }, VIDEO_IMPORT_TIMEOUT)
229 const destPath = join(CONFIG.STORAGE.REDUNDANCY_DIR, getVideoFilename(video, file))
230 await move(tmpPath, destPath, { overwrite: true })
232 const createdModel: MVideoRedundancyFileVideo = await VideoRedundancyModel.create({
234 url: getLocalVideoCacheFileActivityPubUrl(file),
235 fileUrl: video.getVideoRedundancyUrl(file, WEBSERVER.URL),
237 videoFileId: file.id,
238 actorId: serverActor.id
241 createdModel.VideoFile = file
243 await sendCreateCacheFile(serverActor, video, createdModel)
245 logger.info('Duplicated %s - %d -> %s.', video.url, file.resolution, createdModel.url)
248 private async createStreamingPlaylistRedundancy (
249 redundancy: VideosRedundancyStrategy,
250 video: MVideoAccountLight,
251 playlistArg: MStreamingPlaylist
253 let strategy = 'manual'
254 let expiresOn: Date = null
257 strategy = redundancy.strategy
258 expiresOn = this.buildNewExpiration(redundancy.minLifetime)
261 const playlist = playlistArg as MStreamingPlaylistVideo
262 playlist.Video = video
264 const serverActor = await getServerActor()
266 logger.info('Duplicating %s streaming playlist in videos redundancy with "%s" strategy.', video.url, strategy)
268 const destDirectory = join(HLS_REDUNDANCY_DIRECTORY, video.uuid)
269 await downloadPlaylistSegments(playlist.playlistUrl, destDirectory, VIDEO_IMPORT_TIMEOUT)
271 const createdModel: MVideoRedundancyStreamingPlaylistVideo = await VideoRedundancyModel.create({
273 url: getLocalVideoCacheStreamingPlaylistActivityPubUrl(video, playlist),
274 fileUrl: playlist.getVideoRedundancyUrl(WEBSERVER.URL),
276 videoStreamingPlaylistId: playlist.id,
277 actorId: serverActor.id
280 createdModel.VideoStreamingPlaylist = playlist
282 await sendCreateCacheFile(serverActor, video, createdModel)
284 logger.info('Duplicated playlist %s -> %s.', playlist.playlistUrl, createdModel.url)
287 private async extendsExpirationOf (redundancy: MVideoRedundancyVideo, expiresAfterMs: number) {
288 logger.info('Extending expiration of %s.', redundancy.url)
290 const serverActor = await getServerActor()
292 redundancy.expiresOn = this.buildNewExpiration(expiresAfterMs)
293 await redundancy.save()
295 await sendUpdateCacheFile(serverActor, redundancy)
298 private async purgeCacheIfNeeded (candidateToDuplicate: CandidateToDuplicate) {
299 while (await this.isTooHeavy(candidateToDuplicate)) {
300 const redundancy = candidateToDuplicate.redundancy
301 const toDelete = await VideoRedundancyModel.loadOldestLocalExpired(redundancy.strategy, redundancy.minLifetime)
302 if (!toDelete) return
304 await removeVideoRedundancy(toDelete)
308 private async isTooHeavy (candidateToDuplicate: CandidateToDuplicate) {
309 const maxSize = candidateToDuplicate.redundancy.size
311 const totalDuplicated = await VideoRedundancyModel.getTotalDuplicated(candidateToDuplicate.redundancy.strategy)
312 const totalWillDuplicate = totalDuplicated + this.getTotalFileSizes(candidateToDuplicate.files, candidateToDuplicate.streamingPlaylists)
314 return totalWillDuplicate > maxSize
317 private buildNewExpiration (expiresAfterMs: number) {
318 return new Date(Date.now() + expiresAfterMs)
321 private buildEntryLogId (object: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo) {
322 if (isMVideoRedundancyFileVideo(object)) return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
324 return `${object.VideoStreamingPlaylist.playlistUrl}`
327 private getTotalFileSizes (files: MVideoFile[], playlists: MStreamingPlaylistFiles[]) {
328 const fileReducer = (previous: number, current: MVideoFile) => previous + current.size
331 for (const p of playlists) {
332 allFiles = allFiles.concat(p.VideoFiles)
335 return allFiles.reduce(fileReducer, 0)
338 private async loadAndRefreshVideo (videoUrl: string) {
339 // We need more attributes and check if the video still exists
340 const getVideoOptions = {
341 videoObject: videoUrl,
342 syncParam: { likes: false, dislikes: false, shares: false, comments: false, thumbnail: false, refreshVideo: true },
343 fetchType: 'all' as 'all'
345 const { video } = await getOrCreateVideoAndAccountAndChannel(getVideoOptions)