PeerTube/server/lib/live/live-segment-sha-store.ts

83 lines
2.5 KiB
TypeScript
Raw Normal View History

import { writeJson } from 'fs-extra'
2021-06-16 08:14:41 -05:00
import { basename } from 'path'
import { mapToJSON } from '@server/helpers/core-utils'
2021-06-16 08:14:41 -05:00
import { logger, loggerTagsFactory } from '@server/helpers/logger'
import { MStreamingPlaylistVideo } from '@server/types/models'
2021-06-16 08:14:41 -05:00
import { buildSha256Segment } from '../hls'
import { storeHLSFileFromPath } from '../object-storage'
import PQueue from 'p-queue'
2021-06-16 08:14:41 -05:00
const lTags = loggerTagsFactory('live')
class LiveSegmentShaStore {
private readonly segmentsSha256 = new Map<string, string>()
private readonly videoUUID: string
private readonly sha256Path: string
private readonly streamingPlaylist: MStreamingPlaylistVideo
private readonly sendToObjectStorage: boolean
private readonly writeQueue = new PQueue({ concurrency: 1 })
constructor (options: {
videoUUID: string
sha256Path: string
streamingPlaylist: MStreamingPlaylistVideo
sendToObjectStorage: boolean
}) {
this.videoUUID = options.videoUUID
this.sha256Path = options.sha256Path
this.streamingPlaylist = options.streamingPlaylist
this.sendToObjectStorage = options.sendToObjectStorage
2021-06-16 08:14:41 -05:00
}
async addSegmentSha (segmentPath: string) {
logger.debug('Adding live sha segment %s.', segmentPath, lTags(this.videoUUID))
2021-06-16 08:14:41 -05:00
const shaResult = await buildSha256Segment(segmentPath)
const segmentName = basename(segmentPath)
this.segmentsSha256.set(segmentName, shaResult)
2021-06-16 08:14:41 -05:00
try {
await this.writeToDisk()
} catch (err) {
logger.error('Cannot write sha segments to disk.', { err })
}
2021-06-16 08:14:41 -05:00
}
async removeSegmentSha (segmentPath: string) {
2021-06-16 08:14:41 -05:00
const segmentName = basename(segmentPath)
logger.debug('Removing live sha segment %s.', segmentPath, lTags(this.videoUUID))
2021-06-16 08:14:41 -05:00
if (!this.segmentsSha256.has(segmentName)) {
logger.warn('Unknown segment in files map for video %s and segment %s.', this.videoUUID, segmentPath, lTags(this.videoUUID))
2021-06-16 08:14:41 -05:00
return
}
this.segmentsSha256.delete(segmentName)
2021-06-16 08:14:41 -05:00
await this.writeToDisk()
2021-06-16 08:14:41 -05:00
}
private writeToDisk () {
return this.writeQueue.add(async () => {
await writeJson(this.sha256Path, mapToJSON(this.segmentsSha256))
2021-06-16 08:14:41 -05:00
if (this.sendToObjectStorage) {
const url = await storeHLSFileFromPath(this.streamingPlaylist, this.sha256Path)
if (this.streamingPlaylist.segmentsSha256Url !== url) {
this.streamingPlaylist.segmentsSha256Url = url
await this.streamingPlaylist.save()
}
}
})
2021-06-16 08:14:41 -05:00
}
}
export {
LiveSegmentShaStore
}