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 } 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'
18 MStreamingPlaylistVideo,
22 MVideoRedundancyFileVideo,
23 MVideoRedundancyStreamingPlaylistVideo,
24 MVideoRedundancyVideo,
26 } from '@server/typings/models'
28 type CandidateToDuplicate = {
29 redundancy: VideosRedundancy,
30 video: MVideoWithAllFiles,
32 streamingPlaylists: MStreamingPlaylist[]
35 function isMVideoRedundancyFileVideo (
36 o: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo
37 ): o is MVideoRedundancyFileVideo {
38 return !!(o as MVideoRedundancyFileVideo).VideoFile
41 export class VideosRedundancyScheduler extends AbstractScheduler {
43 private static instance: AbstractScheduler
45 protected schedulerIntervalMs = CONFIG.REDUNDANCY.VIDEOS.CHECK_INTERVAL
47 private constructor () {
51 protected async internalExecute () {
52 for (const redundancyConfig of CONFIG.REDUNDANCY.VIDEOS.STRATEGIES) {
53 logger.info('Running redundancy scheduler for strategy %s.', redundancyConfig.strategy)
56 const videoToDuplicate = await this.findVideoToDuplicate(redundancyConfig)
57 if (!videoToDuplicate) continue
59 const candidateToDuplicate = {
60 video: videoToDuplicate,
61 redundancy: redundancyConfig,
62 files: videoToDuplicate.VideoFiles,
63 streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists
66 await this.purgeCacheIfNeeded(candidateToDuplicate)
68 if (await this.isTooHeavy(candidateToDuplicate)) {
69 logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url)
73 logger.info('Will duplicate video %s in redundancy scheduler "%s".', videoToDuplicate.url, redundancyConfig.strategy)
75 await this.createVideoRedundancies(candidateToDuplicate)
77 logger.error('Cannot run videos redundancy %s.', redundancyConfig.strategy, { err })
81 await this.extendsLocalExpiration()
83 await this.purgeRemoteExpired()
86 static get Instance () {
87 return this.instance || (this.instance = new this())
90 private async extendsLocalExpiration () {
91 const expired = await VideoRedundancyModel.listLocalExpired()
93 for (const redundancyModel of expired) {
95 const redundancyConfig = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
97 redundancy: redundancyConfig,
100 streamingPlaylists: []
103 // If the administrator disabled the redundancy or decreased the cache size, remove this redundancy instead of extending it
104 if (!redundancyConfig || await this.isTooHeavy(candidate)) {
105 logger.info('Destroying redundancy %s because the cache size %s is too heavy.', redundancyModel.url, redundancyModel.strategy)
106 await removeVideoRedundancy(redundancyModel)
108 await this.extendsRedundancy(redundancyModel)
112 'Cannot extend or remove expiration of %s video from our redundancy system.', this.buildEntryLogId(redundancyModel),
119 private async extendsRedundancy (redundancyModel: MVideoRedundancyVideo) {
120 const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
121 // Redundancy strategy disabled, remove our redundancy instead of extending expiration
123 await removeVideoRedundancy(redundancyModel)
127 await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime)
130 private async purgeRemoteExpired () {
131 const expired = await VideoRedundancyModel.listRemoteExpired()
133 for (const redundancyModel of expired) {
135 await removeVideoRedundancy(redundancyModel)
137 logger.error('Cannot remove redundancy %s from our redundancy system.', this.buildEntryLogId(redundancyModel))
142 private findVideoToDuplicate (cache: VideosRedundancy) {
143 if (cache.strategy === 'most-views') {
144 return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
147 if (cache.strategy === 'trending') {
148 return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
151 if (cache.strategy === 'recently-added') {
152 const minViews = cache.minViews
153 return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
157 private async createVideoRedundancies (data: CandidateToDuplicate) {
158 const video = await this.loadAndRefreshVideo(data.video.url)
161 logger.info('Video %s we want to duplicate does not existing anymore, skipping.', data.video.url)
166 for (const file of data.files) {
167 const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id)
168 if (existingRedundancy) {
169 await this.extendsRedundancy(existingRedundancy)
174 await this.createVideoFileRedundancy(data.redundancy, video, file)
177 for (const streamingPlaylist of data.streamingPlaylists) {
178 const existingRedundancy = await VideoRedundancyModel.loadLocalByStreamingPlaylistId(streamingPlaylist.id)
179 if (existingRedundancy) {
180 await this.extendsRedundancy(existingRedundancy)
185 await this.createStreamingPlaylistRedundancy(data.redundancy, video, streamingPlaylist)
189 private async createVideoFileRedundancy (redundancy: VideosRedundancy, video: MVideoAccountLight, fileArg: MVideoFile) {
190 const file = fileArg as MVideoFileVideo
193 const serverActor = await getServerActor()
195 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, redundancy.strategy)
197 const { baseUrlHttp, baseUrlWs } = video.getBaseUrls()
198 const magnetUri = video.generateMagnetUri(file, baseUrlHttp, baseUrlWs)
200 const tmpPath = await downloadWebTorrentVideo({ magnetUri }, VIDEO_IMPORT_TIMEOUT)
202 const destPath = join(CONFIG.STORAGE.REDUNDANCY_DIR, video.getVideoFilename(file))
203 await move(tmpPath, destPath, { overwrite: true })
205 const createdModel: MVideoRedundancyFileVideo = await VideoRedundancyModel.create({
206 expiresOn: this.buildNewExpiration(redundancy.minLifetime),
207 url: getVideoCacheFileActivityPubUrl(file),
208 fileUrl: video.getVideoRedundancyUrl(file, WEBSERVER.URL),
209 strategy: redundancy.strategy,
210 videoFileId: file.id,
211 actorId: serverActor.id
214 createdModel.VideoFile = file
216 await sendCreateCacheFile(serverActor, video, createdModel)
218 logger.info('Duplicated %s - %d -> %s.', video.url, file.resolution, createdModel.url)
221 private async createStreamingPlaylistRedundancy (
222 redundancy: VideosRedundancy,
223 video: MVideoAccountLight,
224 playlistArg: MStreamingPlaylist
226 const playlist = playlistArg as MStreamingPlaylistVideo
227 playlist.Video = video
229 const serverActor = await getServerActor()
231 logger.info('Duplicating %s streaming playlist in videos redundancy with "%s" strategy.', video.url, redundancy.strategy)
233 const destDirectory = join(HLS_REDUNDANCY_DIRECTORY, video.uuid)
234 await downloadPlaylistSegments(playlist.playlistUrl, destDirectory, VIDEO_IMPORT_TIMEOUT)
236 const createdModel: MVideoRedundancyStreamingPlaylistVideo = await VideoRedundancyModel.create({
237 expiresOn: this.buildNewExpiration(redundancy.minLifetime),
238 url: getVideoCacheStreamingPlaylistActivityPubUrl(video, playlist),
239 fileUrl: playlist.getVideoRedundancyUrl(WEBSERVER.URL),
240 strategy: redundancy.strategy,
241 videoStreamingPlaylistId: playlist.id,
242 actorId: serverActor.id
245 createdModel.VideoStreamingPlaylist = playlist
247 await sendCreateCacheFile(serverActor, video, createdModel)
249 logger.info('Duplicated playlist %s -> %s.', playlist.playlistUrl, createdModel.url)
252 private async extendsExpirationOf (redundancy: MVideoRedundancyVideo, expiresAfterMs: number) {
253 logger.info('Extending expiration of %s.', redundancy.url)
255 const serverActor = await getServerActor()
257 redundancy.expiresOn = this.buildNewExpiration(expiresAfterMs)
258 await redundancy.save()
260 await sendUpdateCacheFile(serverActor, redundancy)
263 private async purgeCacheIfNeeded (candidateToDuplicate: CandidateToDuplicate) {
264 while (this.isTooHeavy(candidateToDuplicate)) {
265 const redundancy = candidateToDuplicate.redundancy
266 const toDelete = await VideoRedundancyModel.loadOldestLocalExpired(redundancy.strategy, redundancy.minLifetime)
267 if (!toDelete) return
269 await removeVideoRedundancy(toDelete)
273 private async isTooHeavy (candidateToDuplicate: CandidateToDuplicate) {
274 const maxSize = candidateToDuplicate.redundancy.size
276 const totalDuplicated = await VideoRedundancyModel.getTotalDuplicated(candidateToDuplicate.redundancy.strategy)
277 const totalWillDuplicate = totalDuplicated + this.getTotalFileSizes(candidateToDuplicate.files, candidateToDuplicate.streamingPlaylists)
279 return totalWillDuplicate > maxSize
282 private buildNewExpiration (expiresAfterMs: number) {
283 return new Date(Date.now() + expiresAfterMs)
286 private buildEntryLogId (object: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo) {
287 if (isMVideoRedundancyFileVideo(object)) return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
289 return `${object.VideoStreamingPlaylist.playlistUrl}`
292 private getTotalFileSizes (files: MVideoFile[], playlists: MStreamingPlaylist[]) {
293 const fileReducer = (previous: number, current: MVideoFile) => previous + current.size
295 const totalSize = files.reduce(fileReducer, 0)
296 if (playlists.length === 0) return totalSize
298 return totalSize * playlists.length
301 private async loadAndRefreshVideo (videoUrl: string) {
302 // We need more attributes and check if the video still exists
303 const getVideoOptions = {
304 videoObject: videoUrl,
305 syncParam: { likes: false, dislikes: false, shares: false, comments: false, thumbnail: false, refreshVideo: true },
306 fetchType: 'all' as 'all'
308 const { video } = await getOrCreateVideoAndAccountAndChannel(getVideoOptions)