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 { VideoFileModel } from '../../models/video/video-file'
7 import { downloadWebTorrentVideo } from '../../helpers/webtorrent'
8 import { join } from 'path'
9 import { move } from 'fs-extra'
10 import { getServerActor } from '../../helpers/utils'
11 import { sendCreateCacheFile, sendUpdateCacheFile } from '../activitypub/send'
12 import { getVideoCacheFileActivityPubUrl, getVideoCacheStreamingPlaylistActivityPubUrl } from '../activitypub/url'
13 import { removeVideoRedundancy } from '../redundancy'
14 import { getOrCreateVideoAndAccountAndChannel } from '../activitypub'
15 import { VideoStreamingPlaylistModel } from '../../models/video/video-streaming-playlist'
16 import { VideoModel } from '../../models/video/video'
17 import { downloadPlaylistSegments } from '../hls'
18 import { CONFIG } from '../../initializers/config'
20 type CandidateToDuplicate = {
21 redundancy: VideosRedundancy,
23 files: VideoFileModel[],
24 streamingPlaylists: VideoStreamingPlaylistModel[]
27 export class VideosRedundancyScheduler extends AbstractScheduler {
29 private static instance: AbstractScheduler
31 protected schedulerIntervalMs = CONFIG.REDUNDANCY.VIDEOS.CHECK_INTERVAL
33 private constructor () {
37 protected async internalExecute () {
38 for (const redundancyConfig of CONFIG.REDUNDANCY.VIDEOS.STRATEGIES) {
39 logger.info('Running redundancy scheduler for strategy %s.', redundancyConfig.strategy)
42 const videoToDuplicate = await this.findVideoToDuplicate(redundancyConfig)
43 if (!videoToDuplicate) continue
45 const candidateToDuplicate = {
46 video: videoToDuplicate,
47 redundancy: redundancyConfig,
48 files: videoToDuplicate.VideoFiles,
49 streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists
52 await this.purgeCacheIfNeeded(candidateToDuplicate)
54 if (await this.isTooHeavy(candidateToDuplicate)) {
55 logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url)
59 logger.info('Will duplicate video %s in redundancy scheduler "%s".', videoToDuplicate.url, redundancyConfig.strategy)
61 await this.createVideoRedundancies(candidateToDuplicate)
63 logger.error('Cannot run videos redundancy %s.', redundancyConfig.strategy, { err })
67 await this.extendsLocalExpiration()
69 await this.purgeRemoteExpired()
72 static get Instance () {
73 return this.instance || (this.instance = new this())
76 private async extendsLocalExpiration () {
77 const expired = await VideoRedundancyModel.listLocalExpired()
79 for (const redundancyModel of expired) {
81 const redundancyConfig = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
83 redundancy: redundancyConfig,
86 streamingPlaylists: []
89 // If the administrator disabled the redundancy or decreased the cache size, remove this redundancy instead of extending it
90 if (!redundancyConfig || await this.isTooHeavy(candidate)) {
91 logger.info('Destroying redundancy %s because the cache size %s is too heavy.', redundancyModel.url, redundancyModel.strategy)
92 await removeVideoRedundancy(redundancyModel)
94 await this.extendsRedundancy(redundancyModel)
98 'Cannot extend or remove expiration of %s video from our redundancy system.', this.buildEntryLogId(redundancyModel),
105 private async extendsRedundancy (redundancyModel: VideoRedundancyModel) {
106 const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
107 // Redundancy strategy disabled, remove our redundancy instead of extending expiration
109 await removeVideoRedundancy(redundancyModel)
113 await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime)
116 private async purgeRemoteExpired () {
117 const expired = await VideoRedundancyModel.listRemoteExpired()
119 for (const redundancyModel of expired) {
121 await removeVideoRedundancy(redundancyModel)
123 logger.error('Cannot remove redundancy %s from our redundancy system.', this.buildEntryLogId(redundancyModel))
128 private findVideoToDuplicate (cache: VideosRedundancy) {
129 if (cache.strategy === 'most-views') {
130 return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
133 if (cache.strategy === 'trending') {
134 return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
137 if (cache.strategy === 'recently-added') {
138 const minViews = cache.minViews
139 return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
143 private async createVideoRedundancies (data: CandidateToDuplicate) {
144 const video = await this.loadAndRefreshVideo(data.video.url)
147 logger.info('Video %s we want to duplicate does not existing anymore, skipping.', data.video.url)
152 for (const file of data.files) {
153 const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id)
154 if (existingRedundancy) {
155 await this.extendsRedundancy(existingRedundancy)
160 await this.createVideoFileRedundancy(data.redundancy, video, file)
163 for (const streamingPlaylist of data.streamingPlaylists) {
164 const existingRedundancy = await VideoRedundancyModel.loadLocalByStreamingPlaylistId(streamingPlaylist.id)
165 if (existingRedundancy) {
166 await this.extendsRedundancy(existingRedundancy)
171 await this.createStreamingPlaylistRedundancy(data.redundancy, video, streamingPlaylist)
175 private async createVideoFileRedundancy (redundancy: VideosRedundancy, video: VideoModel, file: VideoFileModel) {
178 const serverActor = await getServerActor()
180 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, redundancy.strategy)
182 const { baseUrlHttp, baseUrlWs } = video.getBaseUrls()
183 const magnetUri = video.generateMagnetUri(file, baseUrlHttp, baseUrlWs)
185 const tmpPath = await downloadWebTorrentVideo({ magnetUri }, VIDEO_IMPORT_TIMEOUT)
187 const destPath = join(CONFIG.STORAGE.REDUNDANCY_DIR, video.getVideoFilename(file))
188 await move(tmpPath, destPath, { overwrite: true })
190 const createdModel = await VideoRedundancyModel.create({
191 expiresOn: this.buildNewExpiration(redundancy.minLifetime),
192 url: getVideoCacheFileActivityPubUrl(file),
193 fileUrl: video.getVideoRedundancyUrl(file, WEBSERVER.URL),
194 strategy: redundancy.strategy,
195 videoFileId: file.id,
196 actorId: serverActor.id
199 createdModel.VideoFile = file
201 await sendCreateCacheFile(serverActor, video, createdModel)
203 logger.info('Duplicated %s - %d -> %s.', video.url, file.resolution, createdModel.url)
206 private async createStreamingPlaylistRedundancy (redundancy: VideosRedundancy, video: VideoModel, playlist: VideoStreamingPlaylistModel) {
207 playlist.Video = video
209 const serverActor = await getServerActor()
211 logger.info('Duplicating %s streaming playlist in videos redundancy with "%s" strategy.', video.url, redundancy.strategy)
213 const destDirectory = join(HLS_REDUNDANCY_DIRECTORY, video.uuid)
214 await downloadPlaylistSegments(playlist.playlistUrl, destDirectory, VIDEO_IMPORT_TIMEOUT)
216 const createdModel = await VideoRedundancyModel.create({
217 expiresOn: this.buildNewExpiration(redundancy.minLifetime),
218 url: getVideoCacheStreamingPlaylistActivityPubUrl(video, playlist),
219 fileUrl: playlist.getVideoRedundancyUrl(WEBSERVER.URL),
220 strategy: redundancy.strategy,
221 videoStreamingPlaylistId: playlist.id,
222 actorId: serverActor.id
225 createdModel.VideoStreamingPlaylist = playlist
227 await sendCreateCacheFile(serverActor, video, createdModel)
229 logger.info('Duplicated playlist %s -> %s.', playlist.playlistUrl, createdModel.url)
232 private async extendsExpirationOf (redundancy: VideoRedundancyModel, expiresAfterMs: number) {
233 logger.info('Extending expiration of %s.', redundancy.url)
235 const serverActor = await getServerActor()
237 redundancy.expiresOn = this.buildNewExpiration(expiresAfterMs)
238 await redundancy.save()
240 await sendUpdateCacheFile(serverActor, redundancy)
243 private async purgeCacheIfNeeded (candidateToDuplicate: CandidateToDuplicate) {
244 while (await this.isTooHeavy(candidateToDuplicate)) {
245 const redundancy = candidateToDuplicate.redundancy
246 const toDelete = await VideoRedundancyModel.loadOldestLocalThatAlreadyExpired(redundancy.strategy, redundancy.minLifetime)
247 if (!toDelete) return
249 await removeVideoRedundancy(toDelete)
253 private async isTooHeavy (candidateToDuplicate: CandidateToDuplicate) {
254 const maxSize = candidateToDuplicate.redundancy.size
256 const totalDuplicated = await VideoRedundancyModel.getTotalDuplicated(candidateToDuplicate.redundancy.strategy)
257 const totalWillDuplicate = totalDuplicated + this.getTotalFileSizes(candidateToDuplicate.files, candidateToDuplicate.streamingPlaylists)
259 return totalWillDuplicate > maxSize
262 private buildNewExpiration (expiresAfterMs: number) {
263 return new Date(Date.now() + expiresAfterMs)
266 private buildEntryLogId (object: VideoRedundancyModel) {
267 if (object.VideoFile) return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
269 return `${object.VideoStreamingPlaylist.playlistUrl}`
272 private getTotalFileSizes (files: VideoFileModel[], playlists: VideoStreamingPlaylistModel[]) {
273 const fileReducer = (previous: number, current: VideoFileModel) => previous + current.size
275 const totalSize = files.reduce(fileReducer, 0)
276 if (playlists.length === 0) return totalSize
278 return totalSize * playlists.length
281 private async loadAndRefreshVideo (videoUrl: string) {
282 // We need more attributes and check if the video still exists
283 const getVideoOptions = {
284 videoObject: videoUrl,
285 syncParam: { likes: false, dislikes: false, shares: false, comments: false, thumbnail: false, refreshVideo: true },
286 fetchType: 'all' as 'all'
288 const { video } = await getOrCreateVideoAndAccountAndChannel(getVideoOptions)