dataconnection.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. import { util } from "./util";
  2. import logger from "./logger";
  3. import { Negotiator } from "./negotiator";
  4. import {
  5. ConnectionType,
  6. ConnectionEventType,
  7. SerializationType,
  8. ServerMessageType
  9. } from "./enums";
  10. import { Peer } from "./peer";
  11. import { BaseConnection } from "./baseconnection";
  12. import { ServerMessage } from "./servermessage";
  13. import { EncodingQueue } from './encodingQueue';
  14. import { DataConnection as IDataConnection } from '../index';
  15. /**
  16. * Wraps a DataChannel between two Peers.
  17. */
  18. export class DataConnection extends BaseConnection implements IDataConnection {
  19. private static readonly ID_PREFIX = "dc_";
  20. private static readonly MAX_BUFFERED_AMOUNT = 8 * 1024 * 1024;
  21. private _negotiator: Negotiator;
  22. readonly label: string;
  23. readonly serialization: SerializationType;
  24. readonly reliable: boolean;
  25. jsonStringify: (data: any) => string = JSON.stringify;
  26. jsonParse: (data: string) => any = JSON.parse;
  27. get type() {
  28. return ConnectionType.Data;
  29. }
  30. private _buffer: any[] = [];
  31. private _bufferSize = 0;
  32. private _buffering = false;
  33. private _chunkedData: {
  34. [id: number]: {
  35. data: Blob[],
  36. count: number,
  37. total: number
  38. }
  39. } = {};
  40. private _dc: RTCDataChannel;
  41. private _encodingQueue = new EncodingQueue();
  42. get dataChannel(): RTCDataChannel {
  43. return this._dc;
  44. }
  45. get bufferSize(): number { return this._bufferSize; }
  46. constructor(peerId: string, provider: Peer, options: any) {
  47. super(peerId, provider, options);
  48. this.connectionId =
  49. this.options.connectionId || DataConnection.ID_PREFIX + util.randomToken();
  50. this.label = this.options.label || this.connectionId;
  51. this.serialization = this.options.serialization || SerializationType.Binary;
  52. this.reliable = !!this.options.reliable;
  53. this._encodingQueue.on('done', (ab: ArrayBuffer) => {
  54. this._bufferedSend(ab);
  55. });
  56. this._encodingQueue.on('error', () => {
  57. logger.error(`DC#${this.connectionId}: Error occured in encoding from blob to arraybuffer, close DC`);
  58. this.close();
  59. });
  60. this._negotiator = new Negotiator(this);
  61. this._negotiator.startConnection(
  62. this.options._payload || {
  63. originator: true
  64. }
  65. );
  66. }
  67. /** Called by the Negotiator when the DataChannel is ready. */
  68. initialize(dc: RTCDataChannel): void {
  69. this._dc = dc;
  70. this._configureDataChannel();
  71. }
  72. private _configureDataChannel(): void {
  73. if (!util.supports.binaryBlob || util.supports.reliable) {
  74. this.dataChannel.binaryType = "arraybuffer";
  75. }
  76. this.dataChannel.onopen = () => {
  77. logger.log(`DC#${this.connectionId} dc connection success`);
  78. this._open = true;
  79. this.emit(ConnectionEventType.Open);
  80. };
  81. this.dataChannel.onmessage = (e) => {
  82. logger.log(`DC#${this.connectionId} dc onmessage:`, e.data);
  83. this._handleDataMessage(e);
  84. };
  85. this.dataChannel.onclose = () => {
  86. logger.log(`DC#${this.connectionId} dc closed for:`, this.peer);
  87. this.close();
  88. };
  89. }
  90. // Handles a DataChannel message.
  91. private _handleDataMessage({ data }: { data: Blob | ArrayBuffer | string }): void {
  92. const datatype = data.constructor;
  93. const isBinarySerialization = this.serialization === SerializationType.Binary ||
  94. this.serialization === SerializationType.BinaryUTF8;
  95. let deserializedData: any = data;
  96. if (isBinarySerialization) {
  97. if (datatype === Blob) {
  98. // Datatype should never be blob
  99. util.blobToArrayBuffer(data as Blob, (ab) => {
  100. const unpackedData = util.unpack(ab);
  101. this.emit(ConnectionEventType.Data, unpackedData);
  102. });
  103. return;
  104. } else if (datatype === ArrayBuffer) {
  105. deserializedData = util.unpack(data as ArrayBuffer);
  106. } else if (datatype === String) {
  107. // String fallback for binary data for browsers that don't support binary yet
  108. const ab = util.binaryStringToArrayBuffer(data as string);
  109. deserializedData = util.unpack(ab);
  110. }
  111. } else if (this.serialization === SerializationType.JSON) {
  112. deserializedData = this.jsonParse(data as string);
  113. }
  114. // Check if we've chunked--if so, piece things back together.
  115. // We're guaranteed that this isn't 0.
  116. if (deserializedData.__peerData) {
  117. this._handleChunk(deserializedData);
  118. return;
  119. }
  120. super.emit(ConnectionEventType.Data, deserializedData);
  121. }
  122. private _handleChunk(data: { __peerData: number, n: number, total: number, data: Blob }): void {
  123. const id = data.__peerData;
  124. const chunkInfo = this._chunkedData[id] || {
  125. data: [],
  126. count: 0,
  127. total: data.total
  128. };
  129. chunkInfo.data[data.n] = data.data;
  130. chunkInfo.count++;
  131. this._chunkedData[id] = chunkInfo;
  132. if (chunkInfo.total === chunkInfo.count) {
  133. // Clean up before making the recursive call to `_handleDataMessage`.
  134. delete this._chunkedData[id];
  135. // We've received all the chunks--time to construct the complete data.
  136. const data = new Blob(chunkInfo.data);
  137. this._handleDataMessage({ data });
  138. }
  139. }
  140. /**
  141. * Exposed functionality for users.
  142. */
  143. /** Allows user to close connection. */
  144. close(): void {
  145. this._buffer = [];
  146. this._bufferSize = 0;
  147. this._chunkedData = {};
  148. if (this._negotiator) {
  149. this._negotiator.cleanup();
  150. this._negotiator = null;
  151. }
  152. if (this.provider) {
  153. this.provider._removeConnection(this);
  154. this.provider = null;
  155. }
  156. if (this.dataChannel) {
  157. this.dataChannel.onopen = null;
  158. this.dataChannel.onmessage = null;
  159. this.dataChannel.onclose = null;
  160. this._dc = null;
  161. }
  162. if (this._encodingQueue) {
  163. this._encodingQueue.destroy();
  164. this._encodingQueue.removeAllListeners();
  165. this._encodingQueue = null;
  166. }
  167. if (!this.open) {
  168. return;
  169. }
  170. this._open = false;
  171. super.emit(ConnectionEventType.Close);
  172. }
  173. /** Allows user to send data. */
  174. send(data: any, chunked?: boolean): void {
  175. if (!this.open) {
  176. super.emit(
  177. ConnectionEventType.Error,
  178. new Error(
  179. "Connection is not open. You should listen for the `open` event before sending messages."
  180. )
  181. );
  182. return;
  183. }
  184. if (this.serialization === SerializationType.JSON) {
  185. this._bufferedSend(this.jsonStringify(data));
  186. } else if (
  187. this.serialization === SerializationType.Binary ||
  188. this.serialization === SerializationType.BinaryUTF8
  189. ) {
  190. const blob = util.pack(data);
  191. if (!chunked && blob.size > util.chunkedMTU) {
  192. this._sendChunks(blob);
  193. return;
  194. }
  195. if (!util.supports.binaryBlob) {
  196. // We only do this if we really need to (e.g. blobs are not supported),
  197. // because this conversion is costly.
  198. this._encodingQueue.enque(blob);
  199. } else {
  200. this._bufferedSend(blob);
  201. }
  202. } else {
  203. this._bufferedSend(data);
  204. }
  205. }
  206. private _bufferedSend(msg: any): void {
  207. if (this._buffering || !this._trySend(msg)) {
  208. this._buffer.push(msg);
  209. this._bufferSize = this._buffer.length;
  210. }
  211. }
  212. // Returns true if the send succeeds.
  213. private _trySend(msg: any): boolean {
  214. if (!this.open) {
  215. return false;
  216. }
  217. if (this.dataChannel.bufferedAmount > DataConnection.MAX_BUFFERED_AMOUNT) {
  218. this._buffering = true;
  219. setTimeout(() => {
  220. this._buffering = false;
  221. this._tryBuffer();
  222. }, 50);
  223. return false;
  224. }
  225. try {
  226. this.dataChannel.send(msg);
  227. } catch (e) {
  228. logger.error(`DC#:${this.connectionId} Error when sending:`, e);
  229. this._buffering = true;
  230. this.close();
  231. return false;
  232. }
  233. return true;
  234. }
  235. // Try to send the first message in the buffer.
  236. private _tryBuffer(): void {
  237. if (!this.open) {
  238. return;
  239. }
  240. if (this._buffer.length === 0) {
  241. return;
  242. }
  243. const msg = this._buffer[0];
  244. if (this._trySend(msg)) {
  245. this._buffer.shift();
  246. this._bufferSize = this._buffer.length;
  247. this._tryBuffer();
  248. }
  249. }
  250. private _sendChunks(blob: Blob): void {
  251. const blobs = util.chunk(blob);
  252. logger.log(`DC#${this.connectionId} Try to send ${blobs.length} chunks...`);
  253. for (let blob of blobs) {
  254. this.send(blob, true);
  255. }
  256. }
  257. handleMessage(message: ServerMessage): void {
  258. const payload = message.payload;
  259. switch (message.type) {
  260. case ServerMessageType.Answer:
  261. this._negotiator.handleSDP(message.type, payload.sdp);
  262. break;
  263. case ServerMessageType.Candidate:
  264. this._negotiator.handleCandidate(payload.candidate);
  265. break;
  266. default:
  267. logger.warn(
  268. "Unrecognized message type:",
  269. message.type,
  270. "from peer:",
  271. this.peer
  272. );
  273. break;
  274. }
  275. }
  276. }