1 /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
4 import * as chai from 'chai'
5 import { readdir } from 'fs-extra'
6 import * as magnetUtil from 'magnet-uri'
7 import { join } from 'path'
10 checkVideoFilesWereRemoved,
12 createMultipleServers,
18 setAccessTokensToServers,
21 } from '@shared/extra-utils'
22 import { HttpStatusCode, VideoPrivacy, VideoRedundancyStrategy, VideoRedundancyStrategyWithManual } from '@shared/models'
24 const expect = chai.expect
26 let servers: PeerTubeServer[] = []
27 let video1Server2UUID: string
28 let video1Server2Id: number
30 function checkMagnetWebseeds (file: { magnetUri: string, resolution: { id: number } }, baseWebseeds: string[], server: PeerTubeServer) {
31 const parsed = magnetUtil.decode(file.magnetUri)
33 for (const ws of baseWebseeds) {
34 const found = parsed.urlList.find(url => url === `${ws}-${file.resolution.id}.mp4`)
35 expect(found, `Webseed ${ws} not found in ${file.magnetUri} on server ${server.url}`).to.not.be.undefined
38 expect(parsed.urlList).to.have.lengthOf(baseWebseeds.length)
41 async function createSingleServers (strategy: VideoRedundancyStrategy | null, additionalParams: any = {}, withWebtorrent = true) {
42 const strategies: any[] = []
44 if (strategy !== null) {
47 min_lifetime: '1 hour',
59 enabled: withWebtorrent
67 check_interval: '5 seconds',
73 servers = await createMultipleServers(3, config)
75 // Get the access tokens
76 await setAccessTokensToServers(servers)
79 const { uuid, id } = await servers[1].videos.upload({ attributes: { name: 'video 1 server 2' } })
80 video1Server2UUID = uuid
83 await servers[1].videos.view({ id: video1Server2UUID })
86 await waitJobs(servers)
88 // Server 1 and server 2 follow each other
89 await doubleFollow(servers[0], servers[1])
90 // Server 1 and server 3 follow each other
91 await doubleFollow(servers[0], servers[2])
92 // Server 2 and server 3 follow each other
93 await doubleFollow(servers[1], servers[2])
95 await waitJobs(servers)
98 async function check1WebSeed (videoUUID?: string) {
99 if (!videoUUID) videoUUID = video1Server2UUID
102 `http://localhost:${servers[1].port}/static/webseed/${videoUUID}`
105 for (const server of servers) {
106 // With token to avoid issues with video follow constraints
107 const video = await server.videos.getWithToken({ id: videoUUID })
109 for (const f of video.files) {
110 checkMagnetWebseeds(f, webseeds, server)
115 async function check2Webseeds (videoUUID?: string) {
116 if (!videoUUID) videoUUID = video1Server2UUID
119 `http://localhost:${servers[0].port}/static/redundancy/${videoUUID}`,
120 `http://localhost:${servers[1].port}/static/webseed/${videoUUID}`
123 for (const server of servers) {
124 const video = await server.videos.get({ id: videoUUID })
126 for (const file of video.files) {
127 checkMagnetWebseeds(file, webseeds, server)
129 await makeGetRequest({
131 expectedStatus: HttpStatusCode.OK_200,
132 path: '/static/redundancy/' + `${videoUUID}-${file.resolution.id}.mp4`,
135 await makeGetRequest({
137 expectedStatus: HttpStatusCode.OK_200,
138 path: `/static/webseed/${videoUUID}-${file.resolution.id}.mp4`,
144 const directories = [
145 'test' + servers[0].internalServerNumber + '/redundancy',
146 'test' + servers[1].internalServerNumber + '/videos'
149 for (const directory of directories) {
150 const files = await readdir(join(root(), directory))
151 expect(files).to.have.length.at.least(4)
153 for (const resolution of [ 240, 360, 480, 720 ]) {
154 expect(files.find(f => f === `${videoUUID}-${resolution}.mp4`)).to.not.be.undefined
159 async function check0PlaylistRedundancies (videoUUID?: string) {
160 if (!videoUUID) videoUUID = video1Server2UUID
162 for (const server of servers) {
163 // With token to avoid issues with video follow constraints
164 const video = await server.videos.getWithToken({ id: videoUUID })
166 expect(video.streamingPlaylists).to.be.an('array')
167 expect(video.streamingPlaylists).to.have.lengthOf(1)
168 expect(video.streamingPlaylists[0].redundancies).to.have.lengthOf(0)
172 async function check1PlaylistRedundancies (videoUUID?: string) {
173 if (!videoUUID) videoUUID = video1Server2UUID
175 for (const server of servers) {
176 const video = await server.videos.get({ id: videoUUID })
178 expect(video.streamingPlaylists).to.have.lengthOf(1)
179 expect(video.streamingPlaylists[0].redundancies).to.have.lengthOf(1)
181 const redundancy = video.streamingPlaylists[0].redundancies[0]
183 expect(redundancy.baseUrl).to.equal(servers[0].url + '/static/redundancy/hls/' + videoUUID)
186 const baseUrlPlaylist = servers[1].url + '/static/streaming-playlists/hls'
187 const baseUrlSegment = servers[0].url + '/static/redundancy/hls'
189 const video = await servers[0].videos.get({ id: videoUUID })
190 const hlsPlaylist = video.streamingPlaylists[0]
192 for (const resolution of [ 240, 360, 480, 720 ]) {
193 await checkSegmentHash({ server: servers[1], baseUrlPlaylist, baseUrlSegment, videoUUID, resolution, hlsPlaylist })
196 const directories = [
197 'test' + servers[0].internalServerNumber + '/redundancy/hls',
198 'test' + servers[1].internalServerNumber + '/streaming-playlists/hls'
201 for (const directory of directories) {
202 const files = await readdir(join(root(), directory, videoUUID))
203 expect(files).to.have.length.at.least(4)
205 for (const resolution of [ 240, 360, 480, 720 ]) {
206 const filename = `${videoUUID}-${resolution}-fragmented.mp4`
208 expect(files.find(f => f === filename)).to.not.be.undefined
213 async function checkStatsGlobal (strategy: VideoRedundancyStrategyWithManual) {
214 let totalSize: number = null
217 if (strategy !== 'manual') {
222 const data = await servers[0].stats.get()
223 expect(data.videosRedundancy).to.have.lengthOf(statsLength)
225 const stat = data.videosRedundancy[0]
226 expect(stat.strategy).to.equal(strategy)
227 expect(stat.totalSize).to.equal(totalSize)
232 async function checkStatsWith1Redundancy (strategy: VideoRedundancyStrategyWithManual, onlyHls = false) {
233 const stat = await checkStatsGlobal(strategy)
235 expect(stat.totalUsed).to.be.at.least(1).and.below(409601)
236 expect(stat.totalVideoFiles).to.equal(onlyHls ? 4 : 8)
237 expect(stat.totalVideos).to.equal(1)
240 async function checkStatsWithoutRedundancy (strategy: VideoRedundancyStrategyWithManual) {
241 const stat = await checkStatsGlobal(strategy)
243 expect(stat.totalUsed).to.equal(0)
244 expect(stat.totalVideoFiles).to.equal(0)
245 expect(stat.totalVideos).to.equal(0)
248 async function findServerFollows () {
249 const body = await servers[0].follows.getFollowings({ start: 0, count: 5, sort: '-createdAt' })
250 const follows = body.data
251 const server2 = follows.find(f => f.following.host === `localhost:${servers[1].port}`)
252 const server3 = follows.find(f => f.following.host === `localhost:${servers[2].port}`)
254 return { server2, server3 }
257 async function enableRedundancyOnServer1 () {
258 await servers[0].redundancy.updateRedundancy({ host: servers[1].host, redundancyAllowed: true })
260 const { server2, server3 } = await findServerFollows()
262 expect(server3).to.not.be.undefined
263 expect(server3.following.hostRedundancyAllowed).to.be.false
265 expect(server2).to.not.be.undefined
266 expect(server2.following.hostRedundancyAllowed).to.be.true
269 async function disableRedundancyOnServer1 () {
270 await servers[0].redundancy.updateRedundancy({ host: servers[1].host, redundancyAllowed: false })
272 const { server2, server3 } = await findServerFollows()
274 expect(server3).to.not.be.undefined
275 expect(server3.following.hostRedundancyAllowed).to.be.false
277 expect(server2).to.not.be.undefined
278 expect(server2.following.hostRedundancyAllowed).to.be.false
281 describe('Test videos redundancy', function () {
283 describe('With most-views strategy', function () {
284 const strategy = 'most-views'
289 return createSingleServers(strategy)
292 it('Should have 1 webseed on the first video', async function () {
293 await check1WebSeed()
294 await check0PlaylistRedundancies()
295 await checkStatsWithoutRedundancy(strategy)
298 it('Should enable redundancy on server 1', function () {
299 return enableRedundancyOnServer1()
302 it('Should have 2 webseeds on the first video', async function () {
305 await waitJobs(servers)
306 await servers[0].servers.waitUntilLog('Duplicated ', 5)
307 await waitJobs(servers)
309 await check2Webseeds()
310 await check1PlaylistRedundancies()
311 await checkStatsWith1Redundancy(strategy)
314 it('Should undo redundancy on server 1 and remove duplicated videos', async function () {
317 await disableRedundancyOnServer1()
319 await waitJobs(servers)
322 await check1WebSeed()
323 await check0PlaylistRedundancies()
325 await checkVideoFilesWereRemoved(video1Server2UUID, servers[0], [ 'videos', join('playlists', 'hls') ])
328 after(async function () {
329 return cleanupTests(servers)
333 describe('With trending strategy', function () {
334 const strategy = 'trending'
339 return createSingleServers(strategy)
342 it('Should have 1 webseed on the first video', async function () {
343 await check1WebSeed()
344 await check0PlaylistRedundancies()
345 await checkStatsWithoutRedundancy(strategy)
348 it('Should enable redundancy on server 1', function () {
349 return enableRedundancyOnServer1()
352 it('Should have 2 webseeds on the first video', async function () {
355 await waitJobs(servers)
356 await servers[0].servers.waitUntilLog('Duplicated ', 5)
357 await waitJobs(servers)
359 await check2Webseeds()
360 await check1PlaylistRedundancies()
361 await checkStatsWith1Redundancy(strategy)
364 it('Should unfollow on server 1 and remove duplicated videos', async function () {
367 await servers[0].follows.unfollow({ target: servers[1] })
369 await waitJobs(servers)
372 await check1WebSeed()
373 await check0PlaylistRedundancies()
375 await checkVideoFilesWereRemoved(video1Server2UUID, servers[0], [ 'videos' ])
378 after(async function () {
379 await cleanupTests(servers)
383 describe('With recently added strategy', function () {
384 const strategy = 'recently-added'
389 return createSingleServers(strategy, { min_views: 3 })
392 it('Should have 1 webseed on the first video', async function () {
393 await check1WebSeed()
394 await check0PlaylistRedundancies()
395 await checkStatsWithoutRedundancy(strategy)
398 it('Should enable redundancy on server 1', function () {
399 return enableRedundancyOnServer1()
402 it('Should still have 1 webseed on the first video', async function () {
405 await waitJobs(servers)
407 await waitJobs(servers)
409 await check1WebSeed()
410 await check0PlaylistRedundancies()
411 await checkStatsWithoutRedundancy(strategy)
414 it('Should view 2 times the first video to have > min_views config', async function () {
417 await servers[0].videos.view({ id: video1Server2UUID })
418 await servers[2].videos.view({ id: video1Server2UUID })
421 await waitJobs(servers)
424 it('Should have 2 webseeds on the first video', async function () {
427 await waitJobs(servers)
428 await servers[0].servers.waitUntilLog('Duplicated ', 5)
429 await waitJobs(servers)
431 await check2Webseeds()
432 await check1PlaylistRedundancies()
433 await checkStatsWith1Redundancy(strategy)
436 it('Should remove the video and the redundancy files', async function () {
439 await servers[1].videos.remove({ id: video1Server2UUID })
441 await waitJobs(servers)
443 for (const server of servers) {
444 await checkVideoFilesWereRemoved(video1Server2UUID, server)
448 after(async function () {
449 await cleanupTests(servers)
453 describe('With only HLS files', function () {
454 const strategy = 'recently-added'
456 before(async function () {
459 await createSingleServers(strategy, { min_views: 3 }, false)
462 it('Should have 0 playlist redundancy on the first video', async function () {
463 await check1WebSeed()
464 await check0PlaylistRedundancies()
467 it('Should enable redundancy on server 1', function () {
468 return enableRedundancyOnServer1()
471 it('Should still have 0 redundancy on the first video', async function () {
474 await waitJobs(servers)
476 await waitJobs(servers)
478 await check0PlaylistRedundancies()
479 await checkStatsWithoutRedundancy(strategy)
482 it('Should have 1 redundancy on the first video', async function () {
485 await servers[0].videos.view({ id: video1Server2UUID })
486 await servers[2].videos.view({ id: video1Server2UUID })
489 await waitJobs(servers)
491 await waitJobs(servers)
492 await servers[0].servers.waitUntilLog('Duplicated ', 1)
493 await waitJobs(servers)
495 await check1PlaylistRedundancies()
496 await checkStatsWith1Redundancy(strategy, true)
499 it('Should remove the video and the redundancy files', async function () {
502 await servers[1].videos.remove({ id: video1Server2UUID })
504 await waitJobs(servers)
506 for (const server of servers) {
507 await checkVideoFilesWereRemoved(video1Server2UUID, server)
511 after(async function () {
512 await cleanupTests(servers)
516 describe('With manual strategy', function () {
520 return createSingleServers(null)
523 it('Should have 1 webseed on the first video', async function () {
524 await check1WebSeed()
525 await check0PlaylistRedundancies()
526 await checkStatsWithoutRedundancy('manual')
529 it('Should create a redundancy on first video', async function () {
530 await servers[0].redundancy.addVideo({ videoId: video1Server2Id })
533 it('Should have 2 webseeds on the first video', async function () {
536 await waitJobs(servers)
537 await servers[0].servers.waitUntilLog('Duplicated ', 5)
538 await waitJobs(servers)
540 await check2Webseeds()
541 await check1PlaylistRedundancies()
542 await checkStatsWith1Redundancy('manual')
545 it('Should manually remove redundancies on server 1 and remove duplicated videos', async function () {
548 const body = await servers[0].redundancy.listVideos({ target: 'remote-videos' })
550 const videos = body.data
551 expect(videos).to.have.lengthOf(1)
553 const video = videos[0]
555 for (const r of video.redundancies.files.concat(video.redundancies.streamingPlaylists)) {
556 await servers[0].redundancy.removeVideo({ redundancyId: r.id })
559 await waitJobs(servers)
562 await check1WebSeed()
563 await check0PlaylistRedundancies()
565 await checkVideoFilesWereRemoved(video1Server2UUID, servers[0], [ 'videos' ])
568 after(async function () {
569 await cleanupTests(servers)
573 describe('Test expiration', function () {
574 const strategy = 'recently-added'
576 async function checkContains (servers: PeerTubeServer[], str: string) {
577 for (const server of servers) {
578 const video = await server.videos.get({ id: video1Server2UUID })
580 for (const f of video.files) {
581 expect(f.magnetUri).to.contain(str)
586 async function checkNotContains (servers: PeerTubeServer[], str: string) {
587 for (const server of servers) {
588 const video = await server.videos.get({ id: video1Server2UUID })
590 for (const f of video.files) {
591 expect(f.magnetUri).to.not.contain(str)
596 before(async function () {
599 await createSingleServers(strategy, { min_lifetime: '7 seconds', min_views: 0 })
601 await enableRedundancyOnServer1()
604 it('Should still have 2 webseeds after 10 seconds', async function () {
610 await checkContains(servers, 'http%3A%2F%2Flocalhost%3A' + servers[0].port)
612 // Maybe a server deleted a redundancy in the scheduler
615 await checkContains(servers, 'http%3A%2F%2Flocalhost%3A' + servers[0].port)
619 it('Should stop server 1 and expire video redundancy', async function () {
622 await killallServers([ servers[0] ])
626 await checkNotContains([ servers[1], servers[2] ], 'http%3A%2F%2Flocalhost%3A' + servers[0].port)
629 after(async function () {
630 await cleanupTests(servers)
634 describe('Test file replacement', function () {
635 let video2Server2UUID: string
636 const strategy = 'recently-added'
638 before(async function () {
641 await createSingleServers(strategy, { min_lifetime: '7 seconds', min_views: 0 })
643 await enableRedundancyOnServer1()
645 await waitJobs(servers)
646 await servers[0].servers.waitUntilLog('Duplicated ', 5)
647 await waitJobs(servers)
649 await check2Webseeds(video1Server2UUID)
650 await check1PlaylistRedundancies(video1Server2UUID)
651 await checkStatsWith1Redundancy(strategy)
653 const { uuid } = await servers[1].videos.upload({ attributes: { name: 'video 2 server 2', privacy: VideoPrivacy.PRIVATE } })
654 video2Server2UUID = uuid
656 // Wait transcoding before federation
657 await waitJobs(servers)
659 await servers[1].videos.update({ id: video2Server2UUID, attributes: { privacy: VideoPrivacy.PUBLIC } })
662 it('Should cache video 2 webseeds on the first video', async function () {
665 await waitJobs(servers)
669 while (checked === false) {
673 await check1WebSeed(video1Server2UUID)
674 await check0PlaylistRedundancies(video1Server2UUID)
676 await check2Webseeds(video2Server2UUID)
677 await check1PlaylistRedundancies(video2Server2UUID)
686 it('Should disable strategy and remove redundancies', async function () {
689 await waitJobs(servers)
691 await killallServers([ servers[0] ])
692 await servers[0].run({
695 check_interval: '1 second',
701 await waitJobs(servers)
703 await checkVideoFilesWereRemoved(video1Server2UUID, servers[0], [ join('redundancy', 'hls') ])
706 after(async function () {
707 await cleanupTests(servers)