1 /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
3 import * as chai from 'chai'
5 import { VideoDetails } from '../../../../shared/models/videos'
8 checkVideoFilesWereRemoved,
11 flushAndRunMultipleServers,
12 getFollowingListPaginationAndSort,
22 setAccessTokensToServers,
28 } from '../../../../shared/extra-utils'
29 import { waitJobs } from '../../../../shared/extra-utils/server/jobs'
31 import * as magnetUtil from 'magnet-uri'
34 listVideoRedundancies,
35 removeVideoRedundancy,
37 } from '../../../../shared/extra-utils/server/redundancy'
38 import { ActorFollow } from '../../../../shared/models/actors'
39 import { readdir } from 'fs-extra'
40 import { join } from 'path'
41 import { VideoRedundancy, VideoRedundancyStrategy, VideoRedundancyStrategyWithManual } from '../../../../shared/models/redundancy'
42 import { getStats } from '../../../../shared/extra-utils/server/stats'
43 import { ServerStats } from '../../../../shared/models/server/server-stats.model'
44 import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
46 const expect = chai.expect
48 let servers: ServerInfo[] = []
49 let video1Server2UUID: string
50 let video1Server2Id: number
52 function checkMagnetWebseeds (file: { magnetUri: string, resolution: { id: number } }, baseWebseeds: string[], server: ServerInfo) {
53 const parsed = magnetUtil.decode(file.magnetUri)
55 for (const ws of baseWebseeds) {
56 const found = parsed.urlList.find(url => url === `${ws}-${file.resolution.id}.mp4`)
57 expect(found, `Webseed ${ws} not found in ${file.magnetUri} on server ${server.url}`).to.not.be.undefined
60 expect(parsed.urlList).to.have.lengthOf(baseWebseeds.length)
63 async function flushAndRunServers (strategy: VideoRedundancyStrategy | null, additionalParams: any = {}) {
64 const strategies: any[] = []
66 if (strategy !== null) {
69 min_lifetime: '1 hour',
84 check_interval: '5 seconds',
90 servers = await flushAndRunMultipleServers(3, config)
92 // Get the access tokens
93 await setAccessTokensToServers(servers)
96 const res = await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'video 1 server 2' })
97 video1Server2UUID = res.body.video.uuid
98 video1Server2Id = res.body.video.id
100 await viewVideo(servers[1].url, video1Server2UUID)
103 await waitJobs(servers)
105 // Server 1 and server 2 follow each other
106 await doubleFollow(servers[0], servers[1])
107 // Server 1 and server 3 follow each other
108 await doubleFollow(servers[0], servers[2])
109 // Server 2 and server 3 follow each other
110 await doubleFollow(servers[1], servers[2])
112 await waitJobs(servers)
115 async function check1WebSeed (videoUUID?: string) {
116 if (!videoUUID) videoUUID = video1Server2UUID
119 `http://localhost:${servers[1].port}/static/webseed/${videoUUID}`
122 for (const server of servers) {
123 // With token to avoid issues with video follow constraints
124 const res = await getVideoWithToken(server.url, server.accessToken, videoUUID)
126 const video: VideoDetails = res.body
127 for (const f of video.files) {
128 checkMagnetWebseeds(f, webseeds, server)
133 async function check2Webseeds (videoUUID?: string) {
134 if (!videoUUID) videoUUID = video1Server2UUID
137 `http://localhost:${servers[0].port}/static/redundancy/${videoUUID}`,
138 `http://localhost:${servers[1].port}/static/webseed/${videoUUID}`
141 for (const server of servers) {
142 const res = await getVideo(server.url, videoUUID)
144 const video: VideoDetails = res.body
146 for (const file of video.files) {
147 checkMagnetWebseeds(file, webseeds, server)
149 await makeGetRequest({
151 statusCodeExpected: HttpStatusCode.OK_200,
152 path: '/static/redundancy/' + `${videoUUID}-${file.resolution.id}.mp4`,
155 await makeGetRequest({
157 statusCodeExpected: HttpStatusCode.OK_200,
158 path: `/static/webseed/${videoUUID}-${file.resolution.id}.mp4`,
164 const directories = [
165 'test' + servers[0].internalServerNumber + '/redundancy',
166 'test' + servers[1].internalServerNumber + '/videos'
169 for (const directory of directories) {
170 const files = await readdir(join(root(), directory))
171 expect(files).to.have.length.at.least(4)
173 for (const resolution of [ 240, 360, 480, 720 ]) {
174 expect(files.find(f => f === `${videoUUID}-${resolution}.mp4`)).to.not.be.undefined
179 async function check0PlaylistRedundancies (videoUUID?: string) {
180 if (!videoUUID) videoUUID = video1Server2UUID
182 for (const server of servers) {
183 // With token to avoid issues with video follow constraints
184 const res = await getVideoWithToken(server.url, server.accessToken, videoUUID)
185 const video: VideoDetails = res.body
187 expect(video.streamingPlaylists).to.be.an('array')
188 expect(video.streamingPlaylists).to.have.lengthOf(1)
189 expect(video.streamingPlaylists[0].redundancies).to.have.lengthOf(0)
193 async function check1PlaylistRedundancies (videoUUID?: string) {
194 if (!videoUUID) videoUUID = video1Server2UUID
196 for (const server of servers) {
197 const res = await getVideo(server.url, videoUUID)
198 const video: VideoDetails = res.body
200 expect(video.streamingPlaylists).to.have.lengthOf(1)
201 expect(video.streamingPlaylists[0].redundancies).to.have.lengthOf(1)
203 const redundancy = video.streamingPlaylists[0].redundancies[0]
205 expect(redundancy.baseUrl).to.equal(servers[0].url + '/static/redundancy/hls/' + videoUUID)
208 const baseUrlPlaylist = servers[1].url + '/static/streaming-playlists/hls'
209 const baseUrlSegment = servers[0].url + '/static/redundancy/hls'
211 const res = await getVideo(servers[0].url, videoUUID)
212 const hlsPlaylist = (res.body as VideoDetails).streamingPlaylists[0]
214 for (const resolution of [ 240, 360, 480, 720 ]) {
215 await checkSegmentHash(baseUrlPlaylist, baseUrlSegment, videoUUID, resolution, hlsPlaylist)
218 const directories = [
219 'test' + servers[0].internalServerNumber + '/redundancy/hls',
220 'test' + servers[1].internalServerNumber + '/streaming-playlists/hls'
223 for (const directory of directories) {
224 const files = await readdir(join(root(), directory, videoUUID))
225 expect(files).to.have.length.at.least(4)
227 for (const resolution of [ 240, 360, 480, 720 ]) {
228 const filename = `${videoUUID}-${resolution}-fragmented.mp4`
230 expect(files.find(f => f === filename)).to.not.be.undefined
235 async function checkStatsGlobal (strategy: VideoRedundancyStrategyWithManual) {
236 let totalSize: number = null
239 if (strategy !== 'manual') {
244 const res = await getStats(servers[0].url)
245 const data: ServerStats = res.body
247 expect(data.videosRedundancy).to.have.lengthOf(statsLength)
249 const stat = data.videosRedundancy[0]
250 expect(stat.strategy).to.equal(strategy)
251 expect(stat.totalSize).to.equal(totalSize)
256 async function checkStatsWith2Webseed (strategy: VideoRedundancyStrategyWithManual) {
257 const stat = await checkStatsGlobal(strategy)
259 expect(stat.totalUsed).to.be.at.least(1).and.below(409601)
260 expect(stat.totalVideoFiles).to.equal(4)
261 expect(stat.totalVideos).to.equal(1)
264 async function checkStatsWith1Webseed (strategy: VideoRedundancyStrategyWithManual) {
265 const stat = await checkStatsGlobal(strategy)
267 expect(stat.totalUsed).to.equal(0)
268 expect(stat.totalVideoFiles).to.equal(0)
269 expect(stat.totalVideos).to.equal(0)
272 async function enableRedundancyOnServer1 () {
273 await updateRedundancy(servers[0].url, servers[0].accessToken, servers[1].host, true)
275 const res = await getFollowingListPaginationAndSort({ url: servers[0].url, start: 0, count: 5, sort: '-createdAt' })
276 const follows: ActorFollow[] = res.body.data
277 const server2 = follows.find(f => f.following.host === `localhost:${servers[1].port}`)
278 const server3 = follows.find(f => f.following.host === `localhost:${servers[2].port}`)
280 expect(server3).to.not.be.undefined
281 expect(server3.following.hostRedundancyAllowed).to.be.false
283 expect(server2).to.not.be.undefined
284 expect(server2.following.hostRedundancyAllowed).to.be.true
287 async function disableRedundancyOnServer1 () {
288 await updateRedundancy(servers[0].url, servers[0].accessToken, servers[1].host, false)
290 const res = await getFollowingListPaginationAndSort({ url: servers[0].url, start: 0, count: 5, sort: '-createdAt' })
291 const follows: ActorFollow[] = res.body.data
292 const server2 = follows.find(f => f.following.host === `localhost:${servers[1].port}`)
293 const server3 = follows.find(f => f.following.host === `localhost:${servers[2].port}`)
295 expect(server3).to.not.be.undefined
296 expect(server3.following.hostRedundancyAllowed).to.be.false
298 expect(server2).to.not.be.undefined
299 expect(server2.following.hostRedundancyAllowed).to.be.false
302 describe('Test videos redundancy', function () {
304 describe('With most-views strategy', function () {
305 const strategy = 'most-views'
310 return flushAndRunServers(strategy)
313 it('Should have 1 webseed on the first video', async function () {
314 await check1WebSeed()
315 await check0PlaylistRedundancies()
316 await checkStatsWith1Webseed(strategy)
319 it('Should enable redundancy on server 1', function () {
320 return enableRedundancyOnServer1()
323 it('Should have 2 webseeds on the first video', async function () {
326 await waitJobs(servers)
327 await waitUntilLog(servers[0], 'Duplicated ', 5)
328 await waitJobs(servers)
330 await check2Webseeds()
331 await check1PlaylistRedundancies()
332 await checkStatsWith2Webseed(strategy)
335 it('Should undo redundancy on server 1 and remove duplicated videos', async function () {
338 await disableRedundancyOnServer1()
340 await waitJobs(servers)
343 await check1WebSeed()
344 await check0PlaylistRedundancies()
346 await checkVideoFilesWereRemoved(video1Server2UUID, servers[0].internalServerNumber, [ 'videos', join('playlists', 'hls') ])
349 after(async function () {
350 return cleanupTests(servers)
354 describe('With trending strategy', function () {
355 const strategy = 'trending'
360 return flushAndRunServers(strategy)
363 it('Should have 1 webseed on the first video', async function () {
364 await check1WebSeed()
365 await check0PlaylistRedundancies()
366 await checkStatsWith1Webseed(strategy)
369 it('Should enable redundancy on server 1', function () {
370 return enableRedundancyOnServer1()
373 it('Should have 2 webseeds on the first video', async function () {
376 await waitJobs(servers)
377 await waitUntilLog(servers[0], 'Duplicated ', 5)
378 await waitJobs(servers)
380 await check2Webseeds()
381 await check1PlaylistRedundancies()
382 await checkStatsWith2Webseed(strategy)
385 it('Should unfollow on server 1 and remove duplicated videos', async function () {
388 await unfollow(servers[0].url, servers[0].accessToken, servers[1])
390 await waitJobs(servers)
393 await check1WebSeed()
394 await check0PlaylistRedundancies()
396 await checkVideoFilesWereRemoved(video1Server2UUID, servers[0].internalServerNumber, [ 'videos' ])
399 after(async function () {
400 await cleanupTests(servers)
404 describe('With recently added strategy', function () {
405 const strategy = 'recently-added'
410 return flushAndRunServers(strategy, { min_views: 3 })
413 it('Should have 1 webseed on the first video', async function () {
414 await check1WebSeed()
415 await check0PlaylistRedundancies()
416 await checkStatsWith1Webseed(strategy)
419 it('Should enable redundancy on server 1', function () {
420 return enableRedundancyOnServer1()
423 it('Should still have 1 webseed on the first video', async function () {
426 await waitJobs(servers)
428 await waitJobs(servers)
430 await check1WebSeed()
431 await check0PlaylistRedundancies()
432 await checkStatsWith1Webseed(strategy)
435 it('Should view 2 times the first video to have > min_views config', async function () {
438 await viewVideo(servers[0].url, video1Server2UUID)
439 await viewVideo(servers[2].url, video1Server2UUID)
442 await waitJobs(servers)
445 it('Should have 2 webseeds on the first video', async function () {
448 await waitJobs(servers)
449 await waitUntilLog(servers[0], 'Duplicated ', 5)
450 await waitJobs(servers)
452 await check2Webseeds()
453 await check1PlaylistRedundancies()
454 await checkStatsWith2Webseed(strategy)
457 it('Should remove the video and the redundancy files', async function () {
460 await removeVideo(servers[1].url, servers[1].accessToken, video1Server2UUID)
462 await waitJobs(servers)
464 for (const server of servers) {
465 await checkVideoFilesWereRemoved(video1Server2UUID, server.internalServerNumber)
469 after(async function () {
470 await cleanupTests(servers)
474 describe('With manual strategy', function () {
478 return flushAndRunServers(null)
481 it('Should have 1 webseed on the first video', async function () {
482 await check1WebSeed()
483 await check0PlaylistRedundancies()
484 await checkStatsWith1Webseed('manual')
487 it('Should create a redundancy on first video', async function () {
488 await addVideoRedundancy({
490 accessToken: servers[0].accessToken,
491 videoId: video1Server2Id
495 it('Should have 2 webseeds on the first video', async function () {
498 await waitJobs(servers)
499 await waitUntilLog(servers[0], 'Duplicated ', 5)
500 await waitJobs(servers)
502 await check2Webseeds()
503 await check1PlaylistRedundancies()
504 await checkStatsWith2Webseed('manual')
507 it('Should manually remove redundancies on server 1 and remove duplicated videos', async function () {
510 const res = await listVideoRedundancies({
512 accessToken: servers[0].accessToken,
513 target: 'remote-videos'
516 const videos = res.body.data as VideoRedundancy[]
517 expect(videos).to.have.lengthOf(1)
519 const video = videos[0]
520 for (const r of video.redundancies.files.concat(video.redundancies.streamingPlaylists)) {
521 await removeVideoRedundancy({
523 accessToken: servers[0].accessToken,
528 await waitJobs(servers)
531 await check1WebSeed()
532 await check0PlaylistRedundancies()
534 await checkVideoFilesWereRemoved(video1Server2UUID, servers[0].serverNumber, [ 'videos' ])
537 after(async function () {
538 await cleanupTests(servers)
542 describe('Test expiration', function () {
543 const strategy = 'recently-added'
545 async function checkContains (servers: ServerInfo[], str: string) {
546 for (const server of servers) {
547 const res = await getVideo(server.url, video1Server2UUID)
548 const video: VideoDetails = res.body
550 for (const f of video.files) {
551 expect(f.magnetUri).to.contain(str)
556 async function checkNotContains (servers: ServerInfo[], str: string) {
557 for (const server of servers) {
558 const res = await getVideo(server.url, video1Server2UUID)
559 const video: VideoDetails = res.body
561 for (const f of video.files) {
562 expect(f.magnetUri).to.not.contain(str)
567 before(async function () {
570 await flushAndRunServers(strategy, { min_lifetime: '7 seconds', min_views: 0 })
572 await enableRedundancyOnServer1()
575 it('Should still have 2 webseeds after 10 seconds', async function () {
581 await checkContains(servers, 'http%3A%2F%2Flocalhost%3A' + servers[0].port)
583 // Maybe a server deleted a redundancy in the scheduler
586 await checkContains(servers, 'http%3A%2F%2Flocalhost%3A' + servers[0].port)
590 it('Should stop server 1 and expire video redundancy', async function () {
593 killallServers([ servers[0] ])
597 await checkNotContains([ servers[1], servers[2] ], 'http%3A%2F%2Flocalhost%3A' + servers[0].port)
600 after(async function () {
601 await cleanupTests(servers)
605 describe('Test file replacement', function () {
606 let video2Server2UUID: string
607 const strategy = 'recently-added'
609 before(async function () {
612 await flushAndRunServers(strategy, { min_lifetime: '7 seconds', min_views: 0 })
614 await enableRedundancyOnServer1()
616 await waitJobs(servers)
617 await waitUntilLog(servers[0], 'Duplicated ', 5)
618 await waitJobs(servers)
620 await check2Webseeds()
621 await check1PlaylistRedundancies()
622 await checkStatsWith2Webseed(strategy)
624 const res = await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'video 2 server 2' })
625 video2Server2UUID = res.body.video.uuid
628 it('Should cache video 2 webseeds on the first video', async function () {
631 await waitJobs(servers)
635 while (checked === false) {
639 await check1WebSeed(video1Server2UUID)
640 await check0PlaylistRedundancies(video1Server2UUID)
641 await check2Webseeds(video2Server2UUID)
642 await check1PlaylistRedundancies(video2Server2UUID)
651 it('Should disable strategy and remove redundancies', async function () {
654 await waitJobs(servers)
656 killallServers([ servers[0] ])
657 await reRunServer(servers[0], {
660 check_interval: '1 second',
666 await waitJobs(servers)
668 await checkVideoFilesWereRemoved(video1Server2UUID, servers[0].internalServerNumber, [ join('redundancy', 'hls') ])
671 after(async function () {
672 await cleanupTests(servers)