ActivityPub-federated video streaming platform using P2P directly in your web browser
Fix live cleanup race issue
Chocobozzz41de1d2956e1
diff --git a/server/core/lib/live/live-manager.ts b/server/core/lib/live/live-manager.tsindex 6a5feb7ad7..e9abf85db3 100644--- a/server/core/lib/live/live-manager.ts+++ b/server/core/lib/live/live-manager.ts@@ -20,7 +20,7 @@ import { VideoLiveSessionModel } from '@server/models/video/video-live-session.jimport { VideoLiveModel } from '@server/models/video/video-live.js'import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist.js'import { VideoModel } from '@server/models/video/video.js'-import { MUser, MVideo, MVideoLiveSession, MVideoLiveVideo, MVideoLiveVideoWithSetting } from '@server/types/models/index.js'+import { MUser, MVideo, MVideoLiveVideo, MVideoLiveVideoWithSetting } from '@server/types/models/index.js'import { FfprobeData } from 'fluent-ffmpeg'import { pathExists } from 'fs-extra/esm'import { readFile, readdir } from 'fs/promises'@@ -187,7 +187,7 @@ class LiveManager {return this.getContext().sessions.has(sessionId)}- stopSessionOfVideo (options: {+ async stopSessionOfVideo (options: {videoUUID: stringerror: LiveVideoErrorType | null@@ -210,12 +210,19 @@ class LiveManager {return}+ this.videoSessions.delete(videoUUID)+logger.info('Stopping live session of video %s', videoUUID, { error, ...lTags(sessionId, videoUUID) })- this.saveEndingSession(options)- .catch(err => logger.error('Cannot save ending session.', { err, ...lTags(sessionId, videoUUID) }))+ // Await the ending session write before tearing down: abortSession() triggers ffmpeg shutdown,+ // which eventually fires 'after-cleanup' and onAfterMuxingCleanup() reading this same row+ // So this write must be committed first to avoid two unsynchronized writers racing on it+ try {+ await this.saveEndingSession(options)+ } catch (err) {+ logger.error('Cannot save ending session.', { err, ...lTags(sessionId, videoUUID) })+ }- this.videoSessions.delete(videoUUID)this.abortSession(sessionId)}@@ -448,6 +455,11 @@ class LiveManager {muxingSession.on('live-ready', () => this.publishAndFederateLive({ live: videoLive, ratio, audioOnlyOutput, localLTags }))+ const safeStopSession = (error: LiveVideoErrorType) => {+ this.stopSessionOfVideo({ videoUUID, error })+ .catch(err => logger.error('Cannot stop session of video ' + videoUUID, { err, ...localLTags }))+ }+muxingSession.on('bad-socket-health', ({ videoUUID }) => {logger.error('Too much data in client socket stream (ffmpeg is too slow to transcode the video).' +@@ -456,23 +468,23 @@ class LiveManager {localLTags)- this.stopSessionOfVideo({ videoUUID, error: LiveVideoError.BAD_SOCKET_HEALTH })+ safeStopSession(LiveVideoError.BAD_SOCKET_HEALTH)})muxingSession.on('duration-exceeded', ({ videoUUID }) => {logger.info('Stopping session of %s: max duration exceeded.', videoUUID, localLTags)- this.stopSessionOfVideo({ videoUUID, error: LiveVideoError.DURATION_EXCEEDED })+ safeStopSession(LiveVideoError.DURATION_EXCEEDED)})muxingSession.on('quota-exceeded', ({ videoUUID }) => {logger.info('Stopping session of %s: user quota exceeded.', videoUUID, localLTags)- this.stopSessionOfVideo({ videoUUID, error: LiveVideoError.QUOTA_EXCEEDED })+ safeStopSession(LiveVideoError.QUOTA_EXCEEDED)})muxingSession.on('transcoding-error', ({ videoUUID }) => {- this.stopSessionOfVideo({ videoUUID, error: LiveVideoError.FFMPEG_ERROR })+ safeStopSession(LiveVideoError.FFMPEG_ERROR)})muxingSession.on('transcoding-end', ({ videoUUID }) => {@@ -486,7 +498,7 @@ class LiveManager {muxingSession.destroy()- return this.onAfterMuxingCleanup({ videoUUID, liveSession })+ return this.onAfterMuxingCleanup({ videoUUID, liveSessionId: liveSession.id }).catch(err => logger.error('Error in end transmuxing.', { err, ...localLTags }))})@@ -503,7 +515,7 @@ class LiveManager {videoUUID,error: err.liveVideoErrorCode || LiveVideoError.UNKNOWN_ERROR,errorOnReplay: true // Replay cannot be processed as muxing session failed directly- })+ }).catch(stopErr => logger.error('Cannot stop session of video %s.', videoUUID, { err: stopErr, ...localLTags }))})}@@ -561,10 +573,10 @@ class LiveManager {private async onAfterMuxingCleanup (options: {videoUUID: string- liveSession?: MVideoLiveSession+ liveSessionId?: numbercleanupNow?: boolean // Default false}) {- const { videoUUID, liveSession: liveSessionArg, cleanupNow = false } = options+ const { videoUUID, liveSessionId, cleanupNow = false } = optionslogger.debug('Live of video %s has been cleaned up. Moving to its next state.', videoUUID, lTags(videoUUID))@@ -574,7 +586,10 @@ class LiveManager {const live = await VideoLiveModel.loadByVideoId(fullVideo.id)- const liveSession = liveSessionArg ?? await VideoLiveSessionModel.findLatestSessionOf(fullVideo.id)+ // Always reload from DB instead of reusing a caller-held instance to prevent concurrency issues+ const liveSession = liveSessionId+ ? await VideoLiveSessionModel.load(liveSessionId)+ : await VideoLiveSessionModel.findLatestSessionOf(fullVideo.id)// On server restart during a liveif (!liveSession.endDate) {diff --git a/server/core/lib/live/live-quota-store.ts b/server/core/lib/live/live-quota-store.tsindex 464bc6b033..065027646a 100644--- a/server/core/lib/live/live-quota-store.ts+++ b/server/core/lib/live/live-quota-store.ts@@ -18,15 +18,17 @@ class LiveQuotaStore {}removeLive (userId: number, sessionId: string) {- const newLivesPerUser = this.livesPerUser.get(userId)- .filter(o => o.sessionId !== sessionId)+ const livesOfUser = this.livesPerUser.get(userId)+ if (!livesOfUser) return- this.livesPerUser.set(userId, newLivesPerUser)+ this.livesPerUser.set(userId, livesOfUser.filter(o => o.sessionId !== sessionId))}addQuotaTo (userId: number, sessionId: string, size: number) {const lives = this.livesPerUser.get(userId)- const live = lives.find(l => l.sessionId === sessionId)+ const live = lives?.find(l => l.sessionId === sessionId)+ // The live may have already ended (and been removed) if this is a late/out-of-order call+ if (!live) returnlive.size += size}diff --git a/server/core/lib/runners/job-handlers/live-rtmp-hls-transcoding-job-handler.ts b/server/core/lib/runners/job-handlers/live-rtmp-hls-transcoding-job-handler.tsindex 5960ddcf56..b9612577a8 100644--- a/server/core/lib/runners/job-handlers/live-rtmp-hls-transcoding-job-handler.ts+++ b/server/core/lib/runners/job-handlers/live-rtmp-hls-transcoding-job-handler.ts@@ -172,7 +172,7 @@ export class LiveRTMPHLSTranscodingJobHandlervideoUUID: privatePayload.videoUUID,expectedSessionId: privatePayload.sessionId,error: errorType[type]- })+ }).catch(err => logger.error('Cannot stop session of video %s.', videoUUID, { err, ...this.lTags(runnerJob.uuid, videoUUID) }))logger.info('Runner live RTMP to HLS job %s for video %s %s.', runnerJob.uuid, videoUUID, type, this.lTags(runnerJob.uuid, videoUUID))}diff --git a/server/core/lib/video-blacklist.ts b/server/core/lib/video-blacklist.tsindex b021b2b629..0188cb0993 100644--- a/server/core/lib/video-blacklist.ts+++ b/server/core/lib/video-blacklist.ts@@ -85,6 +85,7 @@ export async function blacklistVideo (videoInstance: MVideoAccountLight, optionsif (videoInstance.isLive) {LiveManager.Instance.stopSessionOfVideo({ videoUUID: videoInstance.uuid, error: LiveVideoError.BLACKLISTED })+ .catch(err => logger.error('Cannot stop session of video %s.', videoInstance.uuid, { err }))}Notifier.Instance.notifyOnVideoBlacklist(blacklist)diff --git a/server/core/models/video/video.ts b/server/core/models/video/video.tsindex 3b0be58f4c..c750572bd9 100644--- a/server/core/models/video/video.ts+++ b/server/core/models/video/video.ts@@ -863,6 +863,7 @@ export class VideoModel extends SequelizeModel<VideoModel> {logger.info('Stopping live of video %s after video deletion.', instance.uuid)LiveManager.Instance.stopSessionOfVideo({ videoUUID: instance.uuid, error: null })+ .catch(err => logger.error('Cannot stop session of video %s.', instance.uuid, { err }))}static invalidateCache (instance: MVideo) {