dataconnection.ts 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. import { concatArrayBuffers, util } from "./util";
  2. import logger from "./logger";
  3. import { Negotiator } from "./negotiator";
  4. import { ConnectionType, SerializationType, ServerMessageType } from "./enums";
  5. import { Peer } from "./peer";
  6. import { BaseConnection } from "./baseconnection";
  7. import { ServerMessage } from "./servermessage";
  8. import { EncodingQueue } from "./encodingQueue";
  9. import type { DataConnection as IDataConnection } from "./dataconnection";
  10. export type DataConnectionEvents = {
  11. /**
  12. * Emitted when data is received from the remote peer.
  13. *
  14. * ```ts
  15. * dataConnection.on('data', (data) => { ... });
  16. * ```
  17. */
  18. data: (data: unknown) => void;
  19. /**
  20. * Emitted when the connection is established and ready-to-use.
  21. *
  22. * ```ts
  23. * dataConnection.on('open', () => { ... });
  24. * ```
  25. */
  26. open: () => void;
  27. };
  28. /**
  29. * Wraps WebRTC's DataChannel.
  30. * To get one, use {@apilink Peer.connect} or listen for the {@apilink PeerEvents | `connect`} event.
  31. */
  32. export class DataConnection
  33. extends BaseConnection<DataConnectionEvents>
  34. implements IDataConnection
  35. {
  36. private static readonly ID_PREFIX = "dc_";
  37. private static readonly MAX_BUFFERED_AMOUNT = 8 * 1024 * 1024;
  38. private _negotiator: Negotiator<DataConnectionEvents, DataConnection>;
  39. readonly label: string;
  40. /**
  41. * The serialization format of the data sent over the connection.
  42. * {@apilink SerializationType | possible values}
  43. */
  44. readonly serialization: SerializationType;
  45. /**
  46. * Whether the underlying data channels are reliable; defined when the connection was initiated.
  47. */
  48. readonly reliable: boolean;
  49. stringify: (data: any) => string = JSON.stringify;
  50. parse: (data: string) => any = JSON.parse;
  51. get type() {
  52. return ConnectionType.Data;
  53. }
  54. private _buffer: any[] = [];
  55. /**
  56. * The number of messages queued to be sent once the browser buffer is no longer full.
  57. */
  58. private _bufferSize = 0;
  59. private _buffering = false;
  60. private _chunkedData: {
  61. [id: number]: {
  62. data: Uint8Array[];
  63. count: number;
  64. total: number;
  65. };
  66. } = {};
  67. private _dc: RTCDataChannel;
  68. private _encodingQueue = new EncodingQueue();
  69. /**
  70. * A reference to the RTCDataChannel object associated with the connection.
  71. */
  72. get dataChannel(): RTCDataChannel {
  73. return this._dc;
  74. }
  75. get bufferSize(): number {
  76. return this._bufferSize;
  77. }
  78. constructor(peerId: string, provider: Peer, options: any) {
  79. super(peerId, provider, options);
  80. this.connectionId =
  81. this.options.connectionId ||
  82. DataConnection.ID_PREFIX + util.randomToken();
  83. this.label = this.options.label || this.connectionId;
  84. this.serialization = this.options.serialization || SerializationType.Binary;
  85. this.reliable = !!this.options.reliable;
  86. this._encodingQueue.on("done", (ab: ArrayBuffer) => {
  87. this._bufferedSend(ab);
  88. });
  89. this._encodingQueue.on("error", () => {
  90. logger.error(
  91. `DC#${this.connectionId}: Error occured in encoding from blob to arraybuffer, close DC`,
  92. );
  93. this.close();
  94. });
  95. this._negotiator = new Negotiator(this);
  96. this._negotiator.startConnection(
  97. this.options._payload || {
  98. originator: true,
  99. },
  100. );
  101. }
  102. /** Called by the Negotiator when the DataChannel is ready. */
  103. override _initializeDataChannel(dc: RTCDataChannel): void {
  104. this._dc = dc;
  105. this.dataChannel.binaryType = "arraybuffer";
  106. this.dataChannel.onopen = () => {
  107. logger.log(`DC#${this.connectionId} dc connection success`);
  108. this._open = true;
  109. this.emit("open");
  110. };
  111. this.dataChannel.onmessage = (e) => {
  112. logger.log(`DC#${this.connectionId} dc onmessage:`, e.data);
  113. this._handleDataMessage(e);
  114. };
  115. this.dataChannel.onclose = () => {
  116. logger.log(`DC#${this.connectionId} dc closed for:`, this.peer);
  117. this.close();
  118. };
  119. }
  120. // Handles a DataChannel message.
  121. private _handleDataMessage({
  122. data,
  123. }: {
  124. data: Blob | ArrayBuffer | string;
  125. }): void {
  126. const datatype = data.constructor;
  127. const isBinarySerialization =
  128. this.serialization === SerializationType.Binary ||
  129. this.serialization === SerializationType.BinaryUTF8;
  130. let deserializedData: any = data;
  131. if (isBinarySerialization) {
  132. if (datatype === Blob) {
  133. // Datatype should never be blob
  134. util.blobToArrayBuffer(data as Blob, (ab) => {
  135. const unpackedData = util.unpack(ab);
  136. this.emit("data", unpackedData);
  137. });
  138. return;
  139. } else if (datatype === ArrayBuffer) {
  140. deserializedData = util.unpack(data as ArrayBuffer);
  141. } else if (datatype === String) {
  142. // String fallback for binary data for browsers that don't support binary yet
  143. const ab = util.binaryStringToArrayBuffer(data as string);
  144. deserializedData = util.unpack(ab);
  145. }
  146. } else if (this.serialization === SerializationType.JSON) {
  147. deserializedData = this.parse(data as string);
  148. }
  149. // PeerJS specific message
  150. const peerData = deserializedData["__peerData"];
  151. if (peerData) {
  152. if (peerData.type === "close") {
  153. this.close();
  154. return;
  155. }
  156. // Chunked data -- piece things back together.
  157. this._handleChunk(deserializedData);
  158. return;
  159. }
  160. super.emit("data", deserializedData);
  161. }
  162. private _handleChunk(data: {
  163. __peerData: number;
  164. n: number;
  165. total: number;
  166. data: ArrayBuffer;
  167. }): void {
  168. const id = data.__peerData;
  169. const chunkInfo = this._chunkedData[id] || {
  170. data: [],
  171. count: 0,
  172. total: data.total,
  173. };
  174. chunkInfo.data[data.n] = new Uint8Array(data.data);
  175. chunkInfo.count++;
  176. this._chunkedData[id] = chunkInfo;
  177. if (chunkInfo.total === chunkInfo.count) {
  178. // Clean up before making the recursive call to `_handleDataMessage`.
  179. delete this._chunkedData[id];
  180. // We've received all the chunks--time to construct the complete data.
  181. const data = concatArrayBuffers(chunkInfo.data);
  182. this.emit("data", util.unpack(data));
  183. }
  184. }
  185. /**
  186. * Exposed functionality for users.
  187. */
  188. /** Allows user to close connection. */
  189. close(options?: { flush?: boolean }) {
  190. if (options?.flush) {
  191. this.send({
  192. __peerData: {
  193. type: "close",
  194. },
  195. });
  196. return;
  197. }
  198. this._buffer = [];
  199. this._bufferSize = 0;
  200. this._chunkedData = {};
  201. if (this._negotiator) {
  202. this._negotiator.cleanup();
  203. this._negotiator = null;
  204. }
  205. if (this.provider) {
  206. this.provider._removeConnection(this);
  207. this.provider = null;
  208. }
  209. if (this.dataChannel) {
  210. this.dataChannel.onopen = null;
  211. this.dataChannel.onmessage = null;
  212. this.dataChannel.onclose = null;
  213. this._dc = null;
  214. }
  215. if (this._encodingQueue) {
  216. this._encodingQueue.destroy();
  217. this._encodingQueue.removeAllListeners();
  218. this._encodingQueue = null;
  219. }
  220. if (!this.open) {
  221. return;
  222. }
  223. this._open = false;
  224. super.emit("close");
  225. }
  226. /**
  227. * `data` is serialized and sent to the remote peer.
  228. * @param data You can send any type of data, including objects, strings, and blobs.
  229. * @returns
  230. */
  231. send(data: any, chunked?: boolean): void {
  232. if (!this.open) {
  233. super.emit(
  234. "error",
  235. new Error(
  236. "Connection is not open. You should listen for the `open` event before sending messages.",
  237. ),
  238. );
  239. return;
  240. }
  241. if (data instanceof Blob) {
  242. data.arrayBuffer().then((ab) => this.send(ab));
  243. return;
  244. }
  245. if (this.serialization === SerializationType.JSON) {
  246. this._bufferedSend(this.stringify(data));
  247. } else if (
  248. this.serialization === SerializationType.Binary ||
  249. this.serialization === SerializationType.BinaryUTF8
  250. ) {
  251. const blob = util.pack(data);
  252. if (!chunked && blob.byteLength > util.chunkedMTU) {
  253. this._sendChunks(blob);
  254. return;
  255. }
  256. this._bufferedSend(blob);
  257. } else {
  258. this._bufferedSend(data);
  259. }
  260. }
  261. private _bufferedSend(msg: any): void {
  262. if (this._buffering || !this._trySend(msg)) {
  263. this._buffer.push(msg);
  264. this._bufferSize = this._buffer.length;
  265. }
  266. }
  267. // Returns true if the send succeeds.
  268. private _trySend(msg: any): boolean {
  269. if (!this.open) {
  270. return false;
  271. }
  272. if (this.dataChannel.bufferedAmount > DataConnection.MAX_BUFFERED_AMOUNT) {
  273. this._buffering = true;
  274. setTimeout(() => {
  275. this._buffering = false;
  276. this._tryBuffer();
  277. }, 50);
  278. return false;
  279. }
  280. try {
  281. this.dataChannel.send(msg);
  282. } catch (e) {
  283. logger.error(`DC#:${this.connectionId} Error when sending:`, e);
  284. this._buffering = true;
  285. this.close();
  286. return false;
  287. }
  288. return true;
  289. }
  290. // Try to send the first message in the buffer.
  291. private _tryBuffer(): void {
  292. if (!this.open) {
  293. return;
  294. }
  295. if (this._buffer.length === 0) {
  296. return;
  297. }
  298. const msg = this._buffer[0];
  299. if (this._trySend(msg)) {
  300. this._buffer.shift();
  301. this._bufferSize = this._buffer.length;
  302. this._tryBuffer();
  303. }
  304. }
  305. private _sendChunks(blob: ArrayBuffer): void {
  306. const blobs = util.chunk(blob);
  307. logger.log(`DC#${this.connectionId} Try to send ${blobs.length} chunks...`);
  308. for (const blob of blobs) {
  309. this.send(blob, true);
  310. }
  311. }
  312. /**
  313. * @internal
  314. */
  315. handleMessage(message: ServerMessage): void {
  316. const payload = message.payload;
  317. switch (message.type) {
  318. case ServerMessageType.Answer:
  319. this._negotiator.handleSDP(message.type, payload.sdp);
  320. break;
  321. case ServerMessageType.Candidate:
  322. this._negotiator.handleCandidate(payload.candidate);
  323. break;
  324. default:
  325. logger.warn(
  326. "Unrecognized message type:",
  327. message.type,
  328. "from peer:",
  329. this.peer,
  330. );
  331. break;
  332. }
  333. }
  334. }