ActivityPub-federated video streaming platform using P2P directly in your web browser
Prevent memory leak in live segment sha store
Chocobozzzfe0da961a7a9
diff --git a/server/core/initializers/constants.ts b/server/core/initializers/constants.tsindex fad91be6c8..01b0143f22 100644--- a/server/core/initializers/constants.ts+++ b/server/core/initializers/constants.ts@@ -1109,6 +1109,9 @@ export const LRU_CACHE = {FILENAME_TO_PATH_PERMANENT_FILE_CACHE: {MAX_SIZE: 5000},+ LIVE_SEGMENT_SHA_REMOVED_SEGMENTS: {+ MAX_SIZE: 1000+ },STATIC_VIDEO_FILES_RIGHTS_CHECK: {MAX_SIZE: 5000,TTL: parseDurationToMs('10 seconds')diff --git a/server/core/lib/live/live-segment-sha-store.ts b/server/core/lib/live/live-segment-sha-store.tsindex a3b0cc7712..b282795aec 100644--- a/server/core/lib/live/live-segment-sha-store.ts+++ b/server/core/lib/live/live-segment-sha-store.ts@@ -1,10 +1,11 @@import { buildSUUID } from '@peertube/peertube-node-utils'import { mapToJSON } from '@server/helpers/core-utils.js'import { logger, loggerTagsFactory } from '@server/helpers/logger.js'+import { LRU_CACHE } from '@server/initializers/constants.js'import { MStreamingPlaylistVideo } from '@server/types/models/index.js'import { writeJson } from 'fs-extra/esm'import { rename } from 'fs/promises'-import PQueue from 'p-queue'+import { LRUCache } from 'lru-cache'import { basename, dirname, join } from 'path'import { buildSha256Segment } from '../hls.js'import { storeHLSFileFromPath } from '../object-storage/index.js'@@ -14,6 +15,8 @@ const lTags = loggerTagsFactory('live')class LiveSegmentShaStore {private readonly segmentsSha256 = new Map<string, string>()+ private readonly removedSegments = new LRUCache<string, true>({ max: LRU_CACHE.LIVE_SEGMENT_SHA_REMOVED_SEGMENTS.MAX_SIZE })+private readonly videoUUID: stringprivate readonly sha256Path: string@@ -21,7 +24,11 @@ class LiveSegmentShaStore {private readonly streamingPlaylist: MStreamingPlaylistVideoprivate readonly sendToObjectStorage: boolean- private readonly writeQueue = new PQueue({ concurrency: 1 })++ // Coalesce concurrent writeToDisk() calls into a single write of the latest map state+ // instead of queueing/running one full write per add/remove call+ private writeLoopPromise: Promise<void> | null = null+ private dirty = falseconstructor (options: {videoUUID: string@@ -39,53 +46,82 @@ class LiveSegmentShaStore {}async addSegmentSha (segmentPath: string) {+ const segmentName = basename(segmentPath)++ // This segment has already been removed (its "unlink" event ran before we finished hashing it)+ if (this.removedSegments.delete(segmentName)) {+ logger.debug('Segment %s was removed before its hash could be added, ignoring it.', segmentPath, lTags(this.videoUUID))+ return+ }+logger.debug('Adding live sha segment %s.', segmentPath, lTags(this.videoUUID))const shaResult = await buildSha256Segment(segmentPath)- const segmentName = basename(segmentPath)this.segmentsSha256.set(segmentName, shaResult)- try {- await this.writeToDisk()- } catch (err) {- logger.error('Cannot write sha segments to disk.', { err })- }+ await this.writeToDisk()}- async removeSegmentSha (segmentPath: string) {+ removeSegmentSha (segmentPath: string) {const segmentName = basename(segmentPath)logger.debug('Removing live sha segment %s.', segmentPath, lTags(this.videoUUID))if (!this.segmentsSha256.has(segmentName)) {- logger.warn(+ logger.debug('Unknown segment in live segment hash store for video %s and segment %s.',this.videoUUID,segmentPath,lTags(this.videoUUID))++ // Its hash may still be pending (addSegmentSha hasn't run yet)+ // Remember it so we discard the hash instead of leaking it+ this.removedSegments.set(segmentName, true)return}this.segmentsSha256.delete(segmentName)- await this.writeToDisk()+ // Don't write to disk: the next addSegmentSha() call will persist this removal}private writeToDisk () {- return this.writeQueue.add(async () => {- logger.debug(`Writing segment sha JSON ${this.sha256Path} of ${this.videoUUID} on disk.`, lTags(this.videoUUID))+ this.dirty = true- // Atomic write: use rename instead of move that is not atomic- // FIXME: jsonfile typings- await (writeJson(this.sha256PathTMP, mapToJSON(this.segmentsSha256), { flush: true } as any) as unknown as Promise<void>)- await rename(this.sha256PathTMP, this.sha256Path)+ if (this.writeLoopPromise === null) {+ this.writeLoopPromise = this.runWriteLoop()+ }++ return this.writeLoopPromise+ }- if (this.sendToObjectStorage) {- await storeHLSFileFromPath(this.streamingPlaylist.Video, this.sha256Path)+ private async runWriteLoop () {+ while (this.dirty) {+ this.dirty = false++ try {+ await this.writeOnce()+ } catch (err) {+ logger.error('Cannot write sha segments to disk.', { err })}- })+ }++ this.writeLoopPromise = null+ }++ private async writeOnce () {+ logger.debug(`Writing segment sha JSON ${this.sha256Path} of ${this.videoUUID} on disk.`, lTags(this.videoUUID))++ // Atomic write: use rename instead of move that is not atomic+ // FIXME: jsonfile typings+ await (writeJson(this.sha256PathTMP, mapToJSON(this.segmentsSha256), { flush: true } as any) as unknown as Promise<void>)+ await rename(this.sha256PathTMP, this.sha256Path)++ if (this.sendToObjectStorage) {+ await storeHLSFileFromPath(this.streamingPlaylist.Video, this.sha256Path)+ }}}diff --git a/server/core/lib/live/shared/muxing-session.ts b/server/core/lib/live/shared/muxing-session.tsindex d47312e70e..cc9c495220 100644--- a/server/core/lib/live/shared/muxing-session.ts+++ b/server/core/lib/live/shared/muxing-session.ts@@ -299,11 +299,7 @@ class MuxingSession extends EventEmitter implements MuxingSession {logger.debug('Live delete handler of TS file %s.', segmentPath, this.lTags())- try {- await this.liveSegmentShaStore.removeSegmentSha(segmentPath)- } catch (err) {- logger.warn('Cannot remove segment sha %s from sha store', segmentPath, { err, ...this.lTags() })- }+ this.liveSegmentShaStore.removeSegmentSha(segmentPath)if (this.streamingPlaylist.storage === FileStorage.OBJECT_STORAGE) {try {