Skip to content

Commit

Permalink
segment validation
Browse files Browse the repository at this point in the history
  • Loading branch information
DimaDemchenko committed Feb 26, 2024
1 parent ba1a16f commit 3d7fb37
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 4 deletions.
5 changes: 4 additions & 1 deletion packages/p2p-media-loader-core/src/p2p/peer-protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import { Settings } from "../types";

export type PeerSettings = Pick<
Settings,
"p2pNotReceivingBytesTimeoutMs" | "webRtcMaxMessageSize" | "p2pErrorRetries"
| "p2pNotReceivingBytesTimeoutMs"
| "webRtcMaxMessageSize"
| "p2pErrorRetries"
| "validateP2Psegment"
>;

export class PeerProtocol {
Expand Down
13 changes: 10 additions & 3 deletions packages/p2p-media-loader-core/src/p2p/peer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export class Peer {
this.id = Peer.getPeerIdFromConnection(connection);
this.peerProtocol = new PeerProtocol(connection, settings, {
onSegmentChunkReceived: this.onSegmentChunkReceived,
// eslint-disable-next-line @typescript-eslint/no-misused-promises
onCommandReceived: this.onCommandReceived,
});

Expand All @@ -62,7 +63,7 @@ export class Peer {
if (this.httpLoadingSegments.has(externalId)) return "http-loading";
}

private onCommandReceived = (command: Command.PeerCommand) => {
private onCommandReceived = async (command: Command.PeerCommand) => {
switch (command.c) {
case PeerCommandType.SegmentsAnnouncement:
this.loadedSegments = new Set(command.l);
Expand Down Expand Up @@ -106,9 +107,15 @@ export class Peer {
return;
}

const isWrongBytes = request.loadedBytes !== request.totalBytes;
let isValid = true;
if (this.settings.validateP2Psegment) {
isValid = await this.settings.validateP2Psegment(
request.segment.url,
request.segment.byteRange,
);
}

if (isWrongBytes) {
if (!isValid) {
request.clearLoadedBytes();
this.cancelSegmentDownloading("peer-response-bytes-mismatch");
this.destroy();
Expand Down
1 change: 1 addition & 0 deletions packages/p2p-media-loader-core/src/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export type Settings = {
httpNotReceivingBytesTimeoutMs: number;
httpErrorRetries: number;
p2pErrorRetries: number;
validateP2Psegment?: (url: string, byteRange?: ByteRange) => Promise<boolean>;
};

export type CoreEventHandlers = {
Expand Down

0 comments on commit 3d7fb37

Please sign in to comment.