1 import { AbstractScheduler } from './abstract-scheduler'
2 import { CONFIG, JOB_TTL, REDUNDANCY } from '../../initializers'
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 { rename } from 'fs-extra'
10 import { getServerActor } from '../../helpers/utils'
11 import { sendCreateCacheFile, sendUpdateCacheFile } from '../activitypub/send'
12 import { VideoModel } from '../../models/video/video'
13 import { getVideoCacheFileActivityPubUrl } from '../activitypub/url'
14 import { removeVideoRedundancy } from '../redundancy'
15 import { getOrCreateVideoAndAccountAndChannel } from '../activitypub'
17 export class VideosRedundancyScheduler extends AbstractScheduler {
19 private static instance: AbstractScheduler
20 private executing = false
22 protected schedulerIntervalMs = CONFIG.REDUNDANCY.VIDEOS.CHECK_INTERVAL
24 private constructor () {
29 if (this.executing) return
33 for (const obj of CONFIG.REDUNDANCY.VIDEOS.STRATEGIES) {
34 logger.info('Running redundancy scheduler for strategy %s.', obj.strategy)
37 const videoToDuplicate = await this.findVideoToDuplicate(obj)
38 if (!videoToDuplicate) continue
40 const videoFiles = videoToDuplicate.VideoFiles
41 videoFiles.forEach(f => f.Video = videoToDuplicate)
43 await this.purgeCacheIfNeeded(obj, videoFiles)
45 if (await this.isTooHeavy(obj, videoFiles)) {
46 logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url)
50 logger.info('Will duplicate video %s in redundancy scheduler "%s".', videoToDuplicate.url, obj.strategy)
52 await this.createVideoRedundancy(obj, videoFiles)
54 logger.error('Cannot run videos redundancy %s.', obj.strategy, { err })
58 await this.extendsLocalExpiration()
60 await this.purgeRemoteExpired()
62 this.executing = false
65 static get Instance () {
66 return this.instance || (this.instance = new this())
69 private async extendsLocalExpiration () {
70 const expired = await VideoRedundancyModel.listLocalExpired()
72 for (const redundancyModel of expired) {
74 const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
75 await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime)
77 logger.error('Cannot extend expiration of %s video from our redundancy system.', this.buildEntryLogId(redundancyModel))
82 private async purgeRemoteExpired () {
83 const expired = await VideoRedundancyModel.listRemoteExpired()
85 for (const redundancyModel of expired) {
87 await removeVideoRedundancy(redundancyModel)
89 logger.error('Cannot remove redundancy %s from our redundancy system.', this.buildEntryLogId(redundancyModel))
94 private findVideoToDuplicate (cache: VideosRedundancy) {
95 if (cache.strategy === 'most-views') {
96 return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
99 if (cache.strategy === 'trending') {
100 return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
103 if (cache.strategy === 'recently-added') {
104 const minViews = cache.minViews
105 return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
109 private async createVideoRedundancy (redundancy: VideosRedundancy, filesToDuplicate: VideoFileModel[]) {
110 const serverActor = await getServerActor()
112 for (const file of filesToDuplicate) {
113 // We need more attributes and check if the video still exists
114 const getVideoOptions = {
115 videoObject: file.Video.url,
116 syncParam: { likes: false, dislikes: false, shares: false, comments: false, thumbnail: false, refreshVideo: true },
117 fetchType: 'only-video' as 'only-video'
119 const { video } = await getOrCreateVideoAndAccountAndChannel(getVideoOptions)
121 const existing = await VideoRedundancyModel.loadLocalByFileId(file.id)
124 await this.extendsExpirationOf(existing, redundancy.minLifetime)
126 logger.info('Destroying existing redundancy %s, because the associated video does not exist anymore.', existing.url)
128 await existing.destroy()
135 logger.info('Video %s we want to duplicate does not existing anymore, skipping.', file.Video.url)
140 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, redundancy.strategy)
142 const { baseUrlHttp, baseUrlWs } = video.getBaseUrls()
143 const magnetUri = video.generateMagnetUri(file, baseUrlHttp, baseUrlWs)
145 const tmpPath = await downloadWebTorrentVideo({ magnetUri }, JOB_TTL['video-import'])
147 const destPath = join(CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename(file))
148 await rename(tmpPath, destPath)
150 const createdModel = await VideoRedundancyModel.create({
151 expiresOn: this.buildNewExpiration(redundancy.minLifetime),
152 url: getVideoCacheFileActivityPubUrl(file),
153 fileUrl: video.getVideoFileUrl(file, CONFIG.WEBSERVER.URL),
154 strategy: redundancy.strategy,
155 videoFileId: file.id,
156 actorId: serverActor.id
158 createdModel.VideoFile = file
160 await sendCreateCacheFile(serverActor, createdModel)
164 private async extendsExpirationOf (redundancy: VideoRedundancyModel, expiresAfterMs: number) {
165 logger.info('Extending expiration of %s.', redundancy.url)
167 const serverActor = await getServerActor()
169 redundancy.expiresOn = this.buildNewExpiration(expiresAfterMs)
170 await redundancy.save()
172 await sendUpdateCacheFile(serverActor, redundancy)
175 private async purgeCacheIfNeeded (redundancy: VideosRedundancy, filesToDuplicate: VideoFileModel[]) {
176 while (this.isTooHeavy(redundancy, filesToDuplicate)) {
177 const toDelete = await VideoRedundancyModel.loadOldestLocalThatAlreadyExpired(redundancy.strategy, redundancy.minLifetime)
178 if (!toDelete) return
180 await removeVideoRedundancy(toDelete)
184 private async isTooHeavy (redundancy: VideosRedundancy, filesToDuplicate: VideoFileModel[]) {
185 const maxSize = redundancy.size - this.getTotalFileSizes(filesToDuplicate)
187 const totalDuplicated = await VideoRedundancyModel.getTotalDuplicated(redundancy.strategy)
189 return totalDuplicated > maxSize
192 private buildNewExpiration (expiresAfterMs: number) {
193 return new Date(Date.now() + expiresAfterMs)
196 private buildEntryLogId (object: VideoRedundancyModel) {
197 return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
200 private getTotalFileSizes (files: VideoFileModel[]) {
201 const fileReducer = (previous: number, current: VideoFileModel) => previous + current.size
203 return files.reduce(fileReducer, 0)