message_handler.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2021 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * Javascript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.MessageHandler = void 0;
  27. var _util = require("./util.js");
  28. const CallbackKind = {
  29. UNKNOWN: 0,
  30. DATA: 1,
  31. ERROR: 2
  32. };
  33. const StreamKind = {
  34. UNKNOWN: 0,
  35. CANCEL: 1,
  36. CANCEL_COMPLETE: 2,
  37. CLOSE: 3,
  38. ENQUEUE: 4,
  39. ERROR: 5,
  40. PULL: 6,
  41. PULL_COMPLETE: 7,
  42. START_COMPLETE: 8
  43. };
  44. function wrapReason(reason) {
  45. if (!(reason instanceof Error || typeof reason === "object" && reason !== null)) {
  46. (0, _util.warn)('wrapReason: Expected "reason" to be a (possibly cloned) Error.');
  47. return reason;
  48. }
  49. switch (reason.name) {
  50. case "AbortException":
  51. return new _util.AbortException(reason.message);
  52. case "MissingPDFException":
  53. return new _util.MissingPDFException(reason.message);
  54. case "PasswordException":
  55. return new _util.PasswordException(reason.message, reason.code);
  56. case "UnexpectedResponseException":
  57. return new _util.UnexpectedResponseException(reason.message, reason.status);
  58. case "UnknownErrorException":
  59. return new _util.UnknownErrorException(reason.message, reason.details);
  60. default:
  61. return new _util.UnknownErrorException(reason.message, reason.toString());
  62. }
  63. }
  64. class MessageHandler {
  65. constructor(sourceName, targetName, comObj) {
  66. this.sourceName = sourceName;
  67. this.targetName = targetName;
  68. this.comObj = comObj;
  69. this.callbackId = 1;
  70. this.streamId = 1;
  71. this.streamSinks = Object.create(null);
  72. this.streamControllers = Object.create(null);
  73. this.callbackCapabilities = Object.create(null);
  74. this.actionHandler = Object.create(null);
  75. this._onComObjOnMessage = event => {
  76. const data = event.data;
  77. if (data.targetName !== this.sourceName) {
  78. return;
  79. }
  80. if (data.stream) {
  81. this._processStreamMessage(data);
  82. return;
  83. }
  84. if (data.callback) {
  85. const callbackId = data.callbackId;
  86. const capability = this.callbackCapabilities[callbackId];
  87. if (!capability) {
  88. throw new Error(`Cannot resolve callback ${callbackId}`);
  89. }
  90. delete this.callbackCapabilities[callbackId];
  91. if (data.callback === CallbackKind.DATA) {
  92. capability.resolve(data.data);
  93. } else if (data.callback === CallbackKind.ERROR) {
  94. capability.reject(wrapReason(data.reason));
  95. } else {
  96. throw new Error("Unexpected callback case");
  97. }
  98. return;
  99. }
  100. const action = this.actionHandler[data.action];
  101. if (!action) {
  102. throw new Error(`Unknown action from worker: ${data.action}`);
  103. }
  104. if (data.callbackId) {
  105. const cbSourceName = this.sourceName;
  106. const cbTargetName = data.sourceName;
  107. new Promise(function (resolve) {
  108. resolve(action(data.data));
  109. }).then(function (result) {
  110. comObj.postMessage({
  111. sourceName: cbSourceName,
  112. targetName: cbTargetName,
  113. callback: CallbackKind.DATA,
  114. callbackId: data.callbackId,
  115. data: result
  116. });
  117. }, function (reason) {
  118. comObj.postMessage({
  119. sourceName: cbSourceName,
  120. targetName: cbTargetName,
  121. callback: CallbackKind.ERROR,
  122. callbackId: data.callbackId,
  123. reason: wrapReason(reason)
  124. });
  125. });
  126. return;
  127. }
  128. if (data.streamId) {
  129. this._createStreamSink(data);
  130. return;
  131. }
  132. action(data.data);
  133. };
  134. comObj.addEventListener("message", this._onComObjOnMessage);
  135. }
  136. on(actionName, handler) {
  137. const ah = this.actionHandler;
  138. if (ah[actionName]) {
  139. throw new Error(`There is already an actionName called "${actionName}"`);
  140. }
  141. ah[actionName] = handler;
  142. }
  143. send(actionName, data, transfers) {
  144. this.comObj.postMessage({
  145. sourceName: this.sourceName,
  146. targetName: this.targetName,
  147. action: actionName,
  148. data
  149. }, transfers);
  150. }
  151. sendWithPromise(actionName, data, transfers) {
  152. const callbackId = this.callbackId++;
  153. const capability = (0, _util.createPromiseCapability)();
  154. this.callbackCapabilities[callbackId] = capability;
  155. try {
  156. this.comObj.postMessage({
  157. sourceName: this.sourceName,
  158. targetName: this.targetName,
  159. action: actionName,
  160. callbackId,
  161. data
  162. }, transfers);
  163. } catch (ex) {
  164. capability.reject(ex);
  165. }
  166. return capability.promise;
  167. }
  168. sendWithStream(actionName, data, queueingStrategy, transfers) {
  169. const streamId = this.streamId++,
  170. sourceName = this.sourceName,
  171. targetName = this.targetName,
  172. comObj = this.comObj;
  173. return new ReadableStream({
  174. start: controller => {
  175. const startCapability = (0, _util.createPromiseCapability)();
  176. this.streamControllers[streamId] = {
  177. controller,
  178. startCall: startCapability,
  179. pullCall: null,
  180. cancelCall: null,
  181. isClosed: false
  182. };
  183. comObj.postMessage({
  184. sourceName,
  185. targetName,
  186. action: actionName,
  187. streamId,
  188. data,
  189. desiredSize: controller.desiredSize
  190. }, transfers);
  191. return startCapability.promise;
  192. },
  193. pull: controller => {
  194. const pullCapability = (0, _util.createPromiseCapability)();
  195. this.streamControllers[streamId].pullCall = pullCapability;
  196. comObj.postMessage({
  197. sourceName,
  198. targetName,
  199. stream: StreamKind.PULL,
  200. streamId,
  201. desiredSize: controller.desiredSize
  202. });
  203. return pullCapability.promise;
  204. },
  205. cancel: reason => {
  206. (0, _util.assert)(reason instanceof Error, "cancel must have a valid reason");
  207. const cancelCapability = (0, _util.createPromiseCapability)();
  208. this.streamControllers[streamId].cancelCall = cancelCapability;
  209. this.streamControllers[streamId].isClosed = true;
  210. comObj.postMessage({
  211. sourceName,
  212. targetName,
  213. stream: StreamKind.CANCEL,
  214. streamId,
  215. reason: wrapReason(reason)
  216. });
  217. return cancelCapability.promise;
  218. }
  219. }, queueingStrategy);
  220. }
  221. _createStreamSink(data) {
  222. const streamId = data.streamId,
  223. sourceName = this.sourceName,
  224. targetName = data.sourceName,
  225. comObj = this.comObj;
  226. const self = this,
  227. action = this.actionHandler[data.action];
  228. const streamSink = {
  229. enqueue(chunk, size = 1, transfers) {
  230. if (this.isCancelled) {
  231. return;
  232. }
  233. const lastDesiredSize = this.desiredSize;
  234. this.desiredSize -= size;
  235. if (lastDesiredSize > 0 && this.desiredSize <= 0) {
  236. this.sinkCapability = (0, _util.createPromiseCapability)();
  237. this.ready = this.sinkCapability.promise;
  238. }
  239. comObj.postMessage({
  240. sourceName,
  241. targetName,
  242. stream: StreamKind.ENQUEUE,
  243. streamId,
  244. chunk
  245. }, transfers);
  246. },
  247. close() {
  248. if (this.isCancelled) {
  249. return;
  250. }
  251. this.isCancelled = true;
  252. comObj.postMessage({
  253. sourceName,
  254. targetName,
  255. stream: StreamKind.CLOSE,
  256. streamId
  257. });
  258. delete self.streamSinks[streamId];
  259. },
  260. error(reason) {
  261. (0, _util.assert)(reason instanceof Error, "error must have a valid reason");
  262. if (this.isCancelled) {
  263. return;
  264. }
  265. this.isCancelled = true;
  266. comObj.postMessage({
  267. sourceName,
  268. targetName,
  269. stream: StreamKind.ERROR,
  270. streamId,
  271. reason: wrapReason(reason)
  272. });
  273. },
  274. sinkCapability: (0, _util.createPromiseCapability)(),
  275. onPull: null,
  276. onCancel: null,
  277. isCancelled: false,
  278. desiredSize: data.desiredSize,
  279. ready: null
  280. };
  281. streamSink.sinkCapability.resolve();
  282. streamSink.ready = streamSink.sinkCapability.promise;
  283. this.streamSinks[streamId] = streamSink;
  284. new Promise(function (resolve) {
  285. resolve(action(data.data, streamSink));
  286. }).then(function () {
  287. comObj.postMessage({
  288. sourceName,
  289. targetName,
  290. stream: StreamKind.START_COMPLETE,
  291. streamId,
  292. success: true
  293. });
  294. }, function (reason) {
  295. comObj.postMessage({
  296. sourceName,
  297. targetName,
  298. stream: StreamKind.START_COMPLETE,
  299. streamId,
  300. reason: wrapReason(reason)
  301. });
  302. });
  303. }
  304. _processStreamMessage(data) {
  305. const streamId = data.streamId,
  306. sourceName = this.sourceName,
  307. targetName = data.sourceName,
  308. comObj = this.comObj;
  309. const streamController = this.streamControllers[streamId],
  310. streamSink = this.streamSinks[streamId];
  311. switch (data.stream) {
  312. case StreamKind.START_COMPLETE:
  313. if (data.success) {
  314. streamController.startCall.resolve();
  315. } else {
  316. streamController.startCall.reject(wrapReason(data.reason));
  317. }
  318. break;
  319. case StreamKind.PULL_COMPLETE:
  320. if (data.success) {
  321. streamController.pullCall.resolve();
  322. } else {
  323. streamController.pullCall.reject(wrapReason(data.reason));
  324. }
  325. break;
  326. case StreamKind.PULL:
  327. if (!streamSink) {
  328. comObj.postMessage({
  329. sourceName,
  330. targetName,
  331. stream: StreamKind.PULL_COMPLETE,
  332. streamId,
  333. success: true
  334. });
  335. break;
  336. }
  337. if (streamSink.desiredSize <= 0 && data.desiredSize > 0) {
  338. streamSink.sinkCapability.resolve();
  339. }
  340. streamSink.desiredSize = data.desiredSize;
  341. new Promise(function (resolve) {
  342. resolve(streamSink.onPull && streamSink.onPull());
  343. }).then(function () {
  344. comObj.postMessage({
  345. sourceName,
  346. targetName,
  347. stream: StreamKind.PULL_COMPLETE,
  348. streamId,
  349. success: true
  350. });
  351. }, function (reason) {
  352. comObj.postMessage({
  353. sourceName,
  354. targetName,
  355. stream: StreamKind.PULL_COMPLETE,
  356. streamId,
  357. reason: wrapReason(reason)
  358. });
  359. });
  360. break;
  361. case StreamKind.ENQUEUE:
  362. (0, _util.assert)(streamController, "enqueue should have stream controller");
  363. if (streamController.isClosed) {
  364. break;
  365. }
  366. streamController.controller.enqueue(data.chunk);
  367. break;
  368. case StreamKind.CLOSE:
  369. (0, _util.assert)(streamController, "close should have stream controller");
  370. if (streamController.isClosed) {
  371. break;
  372. }
  373. streamController.isClosed = true;
  374. streamController.controller.close();
  375. this._deleteStreamController(streamController, streamId);
  376. break;
  377. case StreamKind.ERROR:
  378. (0, _util.assert)(streamController, "error should have stream controller");
  379. streamController.controller.error(wrapReason(data.reason));
  380. this._deleteStreamController(streamController, streamId);
  381. break;
  382. case StreamKind.CANCEL_COMPLETE:
  383. if (data.success) {
  384. streamController.cancelCall.resolve();
  385. } else {
  386. streamController.cancelCall.reject(wrapReason(data.reason));
  387. }
  388. this._deleteStreamController(streamController, streamId);
  389. break;
  390. case StreamKind.CANCEL:
  391. if (!streamSink) {
  392. break;
  393. }
  394. new Promise(function (resolve) {
  395. resolve(streamSink.onCancel && streamSink.onCancel(wrapReason(data.reason)));
  396. }).then(function () {
  397. comObj.postMessage({
  398. sourceName,
  399. targetName,
  400. stream: StreamKind.CANCEL_COMPLETE,
  401. streamId,
  402. success: true
  403. });
  404. }, function (reason) {
  405. comObj.postMessage({
  406. sourceName,
  407. targetName,
  408. stream: StreamKind.CANCEL_COMPLETE,
  409. streamId,
  410. reason: wrapReason(reason)
  411. });
  412. });
  413. streamSink.sinkCapability.reject(wrapReason(data.reason));
  414. streamSink.isCancelled = true;
  415. delete this.streamSinks[streamId];
  416. break;
  417. default:
  418. throw new Error("Unexpected stream case");
  419. }
  420. }
  421. async _deleteStreamController(streamController, streamId) {
  422. await Promise.allSettled([streamController.startCall && streamController.startCall.promise, streamController.pullCall && streamController.pullCall.promise, streamController.cancelCall && streamController.cancelCall.promise]);
  423. delete this.streamControllers[streamId];
  424. }
  425. destroy() {
  426. this.comObj.removeEventListener("message", this._onComObjOnMessage);
  427. }
  428. }
  429. exports.MessageHandler = MessageHandler;