|
| 1 | +import type { ProtobufMessage } from '@improbable-eng/grpc-web/dist/typings/message'; |
| 2 | +import { ConnectionClosedError } from './connection-closed-error'; |
| 3 | + |
| 4 | +export class BaseChannel { |
| 5 | + public readonly ready: Promise<unknown>; |
| 6 | + |
| 7 | + private readonly peerConn: RTCPeerConnection; |
| 8 | + private readonly dataChannel: RTCDataChannel; |
| 9 | + private pResolve: ((value: unknown) => void) | undefined; |
| 10 | + private pReject: ((reason?: unknown) => void) | undefined; |
| 11 | + |
| 12 | + private closed = false; |
| 13 | + private closedReason: Error | undefined; |
| 14 | + |
| 15 | + protected maxDataChannelSize = 65_535; |
| 16 | + |
| 17 | + constructor(peerConn: RTCPeerConnection, dataChannel: RTCDataChannel) { |
| 18 | + this.peerConn = peerConn; |
| 19 | + this.dataChannel = dataChannel; |
| 20 | + |
| 21 | + this.ready = new Promise<unknown>((resolve, reject) => { |
| 22 | + this.pResolve = resolve; |
| 23 | + this.pReject = reject; |
| 24 | + }); |
| 25 | + |
| 26 | + dataChannel.addEventListener('open', () => this.onChannelOpen()); |
| 27 | + dataChannel.addEventListener('close', () => this.onChannelClose()); |
| 28 | + dataChannel.addEventListener('error', (ev) => { |
| 29 | + this.onChannelError(ev); |
| 30 | + }); |
| 31 | + |
| 32 | + peerConn.addEventListener('iceconnectionstatechange', () => { |
| 33 | + const state = peerConn.iceConnectionState; |
| 34 | + if ( |
| 35 | + !(state === 'failed' || state === 'disconnected' || state === 'closed') |
| 36 | + ) { |
| 37 | + return; |
| 38 | + } |
| 39 | + this.pReject?.(new Error(`ICE connection failed with state: ${state}`)); |
| 40 | + }); |
| 41 | + } |
| 42 | + |
| 43 | + public close() { |
| 44 | + this.closeWithReason(undefined); |
| 45 | + } |
| 46 | + |
| 47 | + public isClosed() { |
| 48 | + return this.closed; |
| 49 | + } |
| 50 | + |
| 51 | + public isClosedReason() { |
| 52 | + return this.closedReason; |
| 53 | + } |
| 54 | + |
| 55 | + protected closeWithReason(err?: Error) { |
| 56 | + if (this.closed) { |
| 57 | + return; |
| 58 | + } |
| 59 | + this.closed = true; |
| 60 | + this.closedReason = err; |
| 61 | + this.pReject?.(err); |
| 62 | + this.peerConn.close(); |
| 63 | + } |
| 64 | + |
| 65 | + private onChannelOpen() { |
| 66 | + this.pResolve?.(undefined); |
| 67 | + } |
| 68 | + |
| 69 | + private onChannelClose() { |
| 70 | + this.closeWithReason(new ConnectionClosedError('data channel closed')); |
| 71 | + } |
| 72 | + |
| 73 | + private onChannelError(ev: any) { |
| 74 | + console.error('channel error', ev); |
| 75 | + this.closeWithReason(new Error(ev)); |
| 76 | + } |
| 77 | + |
| 78 | + protected write(msg: ProtobufMessage) { |
| 79 | + this.dataChannel.send(msg.serializeBinary()); |
| 80 | + } |
| 81 | +} |
0 commit comments