MessageQueue.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @flow
  8. * @format
  9. */
  10. 'use strict';
  11. const ErrorUtils = require('../vendor/core/ErrorUtils');
  12. const Systrace = require('../Performance/Systrace');
  13. const deepFreezeAndThrowOnMutationInDev = require('../Utilities/deepFreezeAndThrowOnMutationInDev');
  14. const invariant = require('invariant');
  15. const stringifySafe = require('../Utilities/stringifySafe').default;
  16. const warnOnce = require('../Utilities/warnOnce');
  17. export type SpyData = {
  18. type: number,
  19. module: ?string,
  20. method: string | number,
  21. args: any[],
  22. ...
  23. };
  24. const TO_JS = 0;
  25. const TO_NATIVE = 1;
  26. const MODULE_IDS = 0;
  27. const METHOD_IDS = 1;
  28. const PARAMS = 2;
  29. const MIN_TIME_BETWEEN_FLUSHES_MS = 5;
  30. // eslint-disable-next-line no-bitwise
  31. const TRACE_TAG_REACT_APPS = 1 << 17;
  32. const DEBUG_INFO_LIMIT = 32;
  33. class MessageQueue {
  34. _lazyCallableModules: {[key: string]: (void) => Object, ...};
  35. _queue: [number[], number[], any[], number];
  36. _successCallbacks: Map<number, ?Function>;
  37. _failureCallbacks: Map<number, ?Function>;
  38. _callID: number;
  39. _lastFlush: number;
  40. _eventLoopStartTime: number;
  41. _immediatesCallback: ?() => void;
  42. _debugInfo: {[number]: [number, number], ...};
  43. _remoteModuleTable: {[number]: string, ...};
  44. _remoteMethodTable: {[number]: $ReadOnlyArray<string>, ...};
  45. __spy: ?(data: SpyData) => void;
  46. constructor() {
  47. this._lazyCallableModules = {};
  48. this._queue = [[], [], [], 0];
  49. this._successCallbacks = new Map();
  50. this._failureCallbacks = new Map();
  51. this._callID = 0;
  52. this._lastFlush = 0;
  53. this._eventLoopStartTime = Date.now();
  54. this._immediatesCallback = null;
  55. if (__DEV__) {
  56. this._debugInfo = {};
  57. this._remoteModuleTable = {};
  58. this._remoteMethodTable = {};
  59. }
  60. (this: any).callFunctionReturnFlushedQueue = this.callFunctionReturnFlushedQueue.bind(
  61. this,
  62. );
  63. (this: any).flushedQueue = this.flushedQueue.bind(this);
  64. (this: any).invokeCallbackAndReturnFlushedQueue = this.invokeCallbackAndReturnFlushedQueue.bind(
  65. this,
  66. );
  67. }
  68. /**
  69. * Public APIs
  70. */
  71. static spy(spyOrToggle: boolean | ((data: SpyData) => void)) {
  72. if (spyOrToggle === true) {
  73. MessageQueue.prototype.__spy = info => {
  74. console.log(
  75. `${info.type === TO_JS ? 'N->JS' : 'JS->N'} : ` +
  76. `${info.module ? info.module + '.' : ''}${info.method}` +
  77. `(${JSON.stringify(info.args)})`,
  78. );
  79. };
  80. } else if (spyOrToggle === false) {
  81. MessageQueue.prototype.__spy = null;
  82. } else {
  83. MessageQueue.prototype.__spy = spyOrToggle;
  84. }
  85. }
  86. callFunctionReturnFlushedQueue(
  87. module: string,
  88. method: string,
  89. args: any[],
  90. ): null | [Array<number>, Array<number>, Array<any>, number] {
  91. this.__guard(() => {
  92. this.__callFunction(module, method, args);
  93. });
  94. return this.flushedQueue();
  95. }
  96. // Deprecated. T61834641: Remove me once native clients have updated
  97. callFunctionReturnResultAndFlushedQueue(
  98. module: string,
  99. method: string,
  100. args: any[],
  101. ): void {}
  102. invokeCallbackAndReturnFlushedQueue(
  103. cbID: number,
  104. args: any[],
  105. ): null | [Array<number>, Array<number>, Array<any>, number] {
  106. this.__guard(() => {
  107. this.__invokeCallback(cbID, args);
  108. });
  109. return this.flushedQueue();
  110. }
  111. flushedQueue(): null | [Array<number>, Array<number>, Array<any>, number] {
  112. this.__guard(() => {
  113. this.__callImmediates();
  114. });
  115. const queue = this._queue;
  116. this._queue = [[], [], [], this._callID];
  117. return queue[0].length ? queue : null;
  118. }
  119. getEventLoopRunningTime(): number {
  120. return Date.now() - this._eventLoopStartTime;
  121. }
  122. registerCallableModule(name: string, module: Object) {
  123. this._lazyCallableModules[name] = () => module;
  124. }
  125. registerLazyCallableModule(name: string, factory: void => Object) {
  126. let module: Object;
  127. let getValue: ?(void) => Object = factory;
  128. this._lazyCallableModules[name] = () => {
  129. if (getValue) {
  130. module = getValue();
  131. getValue = null;
  132. }
  133. return module;
  134. };
  135. }
  136. getCallableModule(name: string): any | null {
  137. const getValue = this._lazyCallableModules[name];
  138. return getValue ? getValue() : null;
  139. }
  140. callNativeSyncHook(
  141. moduleID: number,
  142. methodID: number,
  143. params: any[],
  144. onFail: ?Function,
  145. onSucc: ?Function,
  146. ): any {
  147. if (__DEV__) {
  148. invariant(
  149. global.nativeCallSyncHook,
  150. 'Calling synchronous methods on native ' +
  151. 'modules is not supported in Chrome.\n\n Consider providing alternative ' +
  152. 'methods to expose this method in debug mode, e.g. by exposing constants ' +
  153. 'ahead-of-time.',
  154. );
  155. }
  156. this.processCallbacks(moduleID, methodID, params, onFail, onSucc);
  157. return global.nativeCallSyncHook(moduleID, methodID, params);
  158. }
  159. processCallbacks(
  160. moduleID: number,
  161. methodID: number,
  162. params: any[],
  163. onFail: ?Function,
  164. onSucc: ?Function,
  165. ) {
  166. if (onFail || onSucc) {
  167. if (__DEV__) {
  168. this._debugInfo[this._callID] = [moduleID, methodID];
  169. if (this._callID > DEBUG_INFO_LIMIT) {
  170. delete this._debugInfo[this._callID - DEBUG_INFO_LIMIT];
  171. }
  172. if (this._successCallbacks.size > 500) {
  173. const info = {};
  174. this._successCallbacks.forEach((_, callID) => {
  175. const debug = this._debugInfo[callID];
  176. const module = debug && this._remoteModuleTable[debug[0]];
  177. const method = debug && this._remoteMethodTable[debug[0]][debug[1]];
  178. info[callID] = {module, method};
  179. });
  180. warnOnce(
  181. 'excessive-number-of-pending-callbacks',
  182. `Please report: Excessive number of pending callbacks: ${
  183. this._successCallbacks.size
  184. }. Some pending callbacks that might have leaked by never being called from native code: ${stringifySafe(
  185. info,
  186. )}`,
  187. );
  188. }
  189. }
  190. // Encode callIDs into pairs of callback identifiers by shifting left and using the rightmost bit
  191. // to indicate fail (0) or success (1)
  192. // eslint-disable-next-line no-bitwise
  193. onFail && params.push(this._callID << 1);
  194. // eslint-disable-next-line no-bitwise
  195. onSucc && params.push((this._callID << 1) | 1);
  196. this._successCallbacks.set(this._callID, onSucc);
  197. this._failureCallbacks.set(this._callID, onFail);
  198. }
  199. if (__DEV__) {
  200. global.nativeTraceBeginAsyncFlow &&
  201. global.nativeTraceBeginAsyncFlow(
  202. TRACE_TAG_REACT_APPS,
  203. 'native',
  204. this._callID,
  205. );
  206. }
  207. this._callID++;
  208. }
  209. enqueueNativeCall(
  210. moduleID: number,
  211. methodID: number,
  212. params: any[],
  213. onFail: ?Function,
  214. onSucc: ?Function,
  215. ) {
  216. this.processCallbacks(moduleID, methodID, params, onFail, onSucc);
  217. this._queue[MODULE_IDS].push(moduleID);
  218. this._queue[METHOD_IDS].push(methodID);
  219. if (__DEV__) {
  220. // Validate that parameters passed over the bridge are
  221. // folly-convertible. As a special case, if a prop value is a
  222. // function it is permitted here, and special-cased in the
  223. // conversion.
  224. const isValidArgument = val => {
  225. const t = typeof val;
  226. if (
  227. t === 'undefined' ||
  228. t === 'null' ||
  229. t === 'boolean' ||
  230. t === 'string'
  231. ) {
  232. return true;
  233. }
  234. if (t === 'number') {
  235. return isFinite(val);
  236. }
  237. if (t === 'function' || t !== 'object') {
  238. return false;
  239. }
  240. if (Array.isArray(val)) {
  241. return val.every(isValidArgument);
  242. }
  243. for (const k in val) {
  244. if (typeof val[k] !== 'function' && !isValidArgument(val[k])) {
  245. return false;
  246. }
  247. }
  248. return true;
  249. };
  250. // Replacement allows normally non-JSON-convertible values to be
  251. // seen. There is ambiguity with string values, but in context,
  252. // it should at least be a strong hint.
  253. const replacer = (key, val) => {
  254. const t = typeof val;
  255. if (t === 'function') {
  256. return '<<Function ' + val.name + '>>';
  257. } else if (t === 'number' && !isFinite(val)) {
  258. return '<<' + val.toString() + '>>';
  259. } else {
  260. return val;
  261. }
  262. };
  263. // Note that JSON.stringify
  264. invariant(
  265. isValidArgument(params),
  266. '%s is not usable as a native method argument',
  267. JSON.stringify(params, replacer),
  268. );
  269. // The params object should not be mutated after being queued
  270. deepFreezeAndThrowOnMutationInDev((params: any));
  271. }
  272. this._queue[PARAMS].push(params);
  273. const now = Date.now();
  274. if (
  275. global.nativeFlushQueueImmediate &&
  276. now - this._lastFlush >= MIN_TIME_BETWEEN_FLUSHES_MS
  277. ) {
  278. const queue = this._queue;
  279. this._queue = [[], [], [], this._callID];
  280. this._lastFlush = now;
  281. global.nativeFlushQueueImmediate(queue);
  282. }
  283. Systrace.counterEvent('pending_js_to_native_queue', this._queue[0].length);
  284. if (__DEV__ && this.__spy && isFinite(moduleID)) {
  285. this.__spy({
  286. type: TO_NATIVE,
  287. module: this._remoteModuleTable[moduleID],
  288. method: this._remoteMethodTable[moduleID][methodID],
  289. args: params,
  290. });
  291. } else if (this.__spy) {
  292. this.__spy({
  293. type: TO_NATIVE,
  294. module: moduleID + '',
  295. method: methodID,
  296. args: params,
  297. });
  298. }
  299. }
  300. createDebugLookup(
  301. moduleID: number,
  302. name: string,
  303. methods: ?$ReadOnlyArray<string>,
  304. ) {
  305. if (__DEV__) {
  306. this._remoteModuleTable[moduleID] = name;
  307. this._remoteMethodTable[moduleID] = methods || [];
  308. }
  309. }
  310. // For JSTimers to register its callback. Otherwise a circular dependency
  311. // between modules is introduced. Note that only one callback may be
  312. // registered at a time.
  313. setImmediatesCallback(fn: () => void) {
  314. this._immediatesCallback = fn;
  315. }
  316. /**
  317. * Private methods
  318. */
  319. __guard(fn: () => void) {
  320. if (this.__shouldPauseOnThrow()) {
  321. fn();
  322. } else {
  323. try {
  324. fn();
  325. } catch (error) {
  326. ErrorUtils.reportFatalError(error);
  327. }
  328. }
  329. }
  330. // MessageQueue installs a global handler to catch all exceptions where JS users can register their own behavior
  331. // This handler makes all exceptions to be propagated from inside MessageQueue rather than by the VM at their origin
  332. // This makes stacktraces to be placed at MessageQueue rather than at where they were launched
  333. // The parameter DebuggerInternal.shouldPauseOnThrow is used to check before catching all exceptions and
  334. // can be configured by the VM or any Inspector
  335. __shouldPauseOnThrow(): boolean {
  336. return (
  337. // $FlowFixMe
  338. typeof DebuggerInternal !== 'undefined' &&
  339. DebuggerInternal.shouldPauseOnThrow === true // eslint-disable-line no-undef
  340. );
  341. }
  342. __callImmediates() {
  343. Systrace.beginEvent('JSTimers.callImmediates()');
  344. if (this._immediatesCallback != null) {
  345. this._immediatesCallback();
  346. }
  347. Systrace.endEvent();
  348. }
  349. __callFunction(module: string, method: string, args: any[]): void {
  350. this._lastFlush = Date.now();
  351. this._eventLoopStartTime = this._lastFlush;
  352. if (__DEV__ || this.__spy) {
  353. Systrace.beginEvent(`${module}.${method}(${stringifySafe(args)})`);
  354. } else {
  355. Systrace.beginEvent(`${module}.${method}(...)`);
  356. }
  357. if (this.__spy) {
  358. this.__spy({type: TO_JS, module, method, args});
  359. }
  360. const moduleMethods = this.getCallableModule(module);
  361. invariant(
  362. !!moduleMethods,
  363. 'Module %s is not a registered callable module (calling %s)',
  364. module,
  365. method,
  366. );
  367. invariant(
  368. !!moduleMethods[method],
  369. 'Method %s does not exist on module %s',
  370. method,
  371. module,
  372. );
  373. moduleMethods[method].apply(moduleMethods, args);
  374. Systrace.endEvent();
  375. }
  376. __invokeCallback(cbID: number, args: any[]) {
  377. this._lastFlush = Date.now();
  378. this._eventLoopStartTime = this._lastFlush;
  379. // The rightmost bit of cbID indicates fail (0) or success (1), the other bits are the callID shifted left.
  380. // eslint-disable-next-line no-bitwise
  381. const callID = cbID >>> 1;
  382. // eslint-disable-next-line no-bitwise
  383. const isSuccess = cbID & 1;
  384. const callback = isSuccess
  385. ? this._successCallbacks.get(callID)
  386. : this._failureCallbacks.get(callID);
  387. if (__DEV__) {
  388. const debug = this._debugInfo[callID];
  389. const module = debug && this._remoteModuleTable[debug[0]];
  390. const method = debug && this._remoteMethodTable[debug[0]][debug[1]];
  391. invariant(
  392. callback,
  393. `No callback found with cbID ${cbID} and callID ${callID} for ` +
  394. (method
  395. ? ` ${module}.${method} - most likely the callback was already invoked`
  396. : `module ${module || '<unknown>'}`) +
  397. `. Args: '${stringifySafe(args)}'`,
  398. );
  399. const profileName = debug
  400. ? '<callback for ' + module + '.' + method + '>'
  401. : cbID;
  402. if (callback && this.__spy) {
  403. this.__spy({type: TO_JS, module: null, method: profileName, args});
  404. }
  405. Systrace.beginEvent(
  406. `MessageQueue.invokeCallback(${profileName}, ${stringifySafe(args)})`,
  407. );
  408. }
  409. if (!callback) {
  410. return;
  411. }
  412. this._successCallbacks.delete(callID);
  413. this._failureCallbacks.delete(callID);
  414. callback(...args);
  415. if (__DEV__) {
  416. Systrace.endEvent();
  417. }
  418. }
  419. }
  420. module.exports = MessageQueue;