LiveQueryClient.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _CoreManager = _interopRequireDefault(require("./CoreManager"));
  7. var _EventEmitter = _interopRequireDefault(require("./EventEmitter"));
  8. var _ParseObject = _interopRequireDefault(require("./ParseObject"));
  9. var _LiveQuerySubscription = _interopRequireDefault(require("./LiveQuerySubscription"));
  10. var _promiseUtils = require("./promiseUtils");
  11. function _interopRequireDefault(obj) {
  12. return obj && obj.__esModule ? obj : {
  13. default: obj
  14. };
  15. }
  16. /**
  17. * Copyright (c) 2015-present, Parse, LLC.
  18. * All rights reserved.
  19. *
  20. * This source code is licensed under the BSD-style license found in the
  21. * LICENSE file in the root directory of this source tree. An additional grant
  22. * of patent rights can be found in the PATENTS file in the same directory.
  23. *
  24. */
  25. /* global WebSocket */
  26. // The LiveQuery client inner state
  27. const CLIENT_STATE = {
  28. INITIALIZED: 'initialized',
  29. CONNECTING: 'connecting',
  30. CONNECTED: 'connected',
  31. CLOSED: 'closed',
  32. RECONNECTING: 'reconnecting',
  33. DISCONNECTED: 'disconnected'
  34. }; // The event type the LiveQuery client should sent to server
  35. const OP_TYPES = {
  36. CONNECT: 'connect',
  37. SUBSCRIBE: 'subscribe',
  38. UNSUBSCRIBE: 'unsubscribe',
  39. ERROR: 'error'
  40. }; // The event we get back from LiveQuery server
  41. const OP_EVENTS = {
  42. CONNECTED: 'connected',
  43. SUBSCRIBED: 'subscribed',
  44. UNSUBSCRIBED: 'unsubscribed',
  45. ERROR: 'error',
  46. CREATE: 'create',
  47. UPDATE: 'update',
  48. ENTER: 'enter',
  49. LEAVE: 'leave',
  50. DELETE: 'delete'
  51. }; // The event the LiveQuery client should emit
  52. const CLIENT_EMMITER_TYPES = {
  53. CLOSE: 'close',
  54. ERROR: 'error',
  55. OPEN: 'open'
  56. }; // The event the LiveQuery subscription should emit
  57. const SUBSCRIPTION_EMMITER_TYPES = {
  58. OPEN: 'open',
  59. CLOSE: 'close',
  60. ERROR: 'error',
  61. CREATE: 'create',
  62. UPDATE: 'update',
  63. ENTER: 'enter',
  64. LEAVE: 'leave',
  65. DELETE: 'delete'
  66. };
  67. const generateInterval = k => {
  68. return Math.random() * Math.min(30, Math.pow(2, k) - 1) * 1000;
  69. };
  70. /**
  71. * Creates a new LiveQueryClient.
  72. * Extends events.EventEmitter
  73. * <a href="https://nodejs.org/api/events.html#events_class_eventemitter">cloud functions</a>.
  74. *
  75. * A wrapper of a standard WebSocket client. We add several useful methods to
  76. * help you connect/disconnect to LiveQueryServer, subscribe/unsubscribe a ParseQuery easily.
  77. *
  78. * javascriptKey and masterKey are used for verifying the LiveQueryClient when it tries
  79. * to connect to the LiveQuery server
  80. *
  81. * We expose three events to help you monitor the status of the LiveQueryClient.
  82. *
  83. * <pre>
  84. * let Parse = require('parse/node');
  85. * let LiveQueryClient = Parse.LiveQueryClient;
  86. * let client = new LiveQueryClient({
  87. * applicationId: '',
  88. * serverURL: '',
  89. * javascriptKey: '',
  90. * masterKey: ''
  91. * });
  92. * </pre>
  93. *
  94. * Open - When we establish the WebSocket connection to the LiveQuery server, you'll get this event.
  95. * <pre>
  96. * client.on('open', () => {
  97. *
  98. * });</pre>
  99. *
  100. * Close - When we lose the WebSocket connection to the LiveQuery server, you'll get this event.
  101. * <pre>
  102. * client.on('close', () => {
  103. *
  104. * });</pre>
  105. *
  106. * Error - When some network error or LiveQuery server error happens, you'll get this event.
  107. * <pre>
  108. * client.on('error', (error) => {
  109. *
  110. * });</pre>
  111. * @alias Parse.LiveQueryClient
  112. */
  113. class LiveQueryClient extends _EventEmitter.default {
  114. /*:: attempts: number;*/
  115. /*:: id: number;*/
  116. /*:: requestId: number;*/
  117. /*:: applicationId: string;*/
  118. /*:: serverURL: string;*/
  119. /*:: javascriptKey: ?string;*/
  120. /*:: masterKey: ?string;*/
  121. /*:: sessionToken: ?string;*/
  122. /*:: connectPromise: Promise;*/
  123. /*:: subscriptions: Map;*/
  124. /*:: socket: any;*/
  125. /*:: state: string;*/
  126. /**
  127. * @param {Object} options
  128. * @param {string} options.applicationId - applicationId of your Parse app
  129. * @param {string} options.serverURL - <b>the URL of your LiveQuery server</b>
  130. * @param {string} options.javascriptKey (optional)
  131. * @param {string} options.masterKey (optional) Your Parse Master Key. (Node.js only!)
  132. * @param {string} options.sessionToken (optional)
  133. */
  134. constructor({
  135. applicationId,
  136. serverURL,
  137. javascriptKey,
  138. masterKey,
  139. sessionToken
  140. }) {
  141. super();
  142. if (!serverURL || serverURL.indexOf('ws') !== 0) {
  143. throw new Error('You need to set a proper Parse LiveQuery server url before using LiveQueryClient');
  144. }
  145. this.reconnectHandle = null;
  146. this.attempts = 1;
  147. this.id = 0;
  148. this.requestId = 1;
  149. this.serverURL = serverURL;
  150. this.applicationId = applicationId;
  151. this.javascriptKey = javascriptKey;
  152. this.masterKey = masterKey;
  153. this.sessionToken = sessionToken;
  154. this.connectPromise = (0, _promiseUtils.resolvingPromise)();
  155. this.subscriptions = new Map();
  156. this.state = CLIENT_STATE.INITIALIZED;
  157. }
  158. shouldOpen()
  159. /*: any*/
  160. {
  161. return this.state === CLIENT_STATE.INITIALIZED || this.state === CLIENT_STATE.DISCONNECTED;
  162. }
  163. /**
  164. * Subscribes to a ParseQuery
  165. *
  166. * If you provide the sessionToken, when the LiveQuery server gets ParseObject's
  167. * updates from parse server, it'll try to check whether the sessionToken fulfills
  168. * the ParseObject's ACL. The LiveQuery server will only send updates to clients whose
  169. * sessionToken is fit for the ParseObject's ACL. You can check the LiveQuery protocol
  170. * <a href="https://github.com/parse-community/parse-server/wiki/Parse-LiveQuery-Protocol-Specification">here</a> for more details. The subscription you get is the same subscription you get
  171. * from our Standard API.
  172. *
  173. * @param {Object} query - the ParseQuery you want to subscribe to
  174. * @param {string} sessionToken (optional)
  175. * @return {Object} subscription
  176. */
  177. subscribe(query
  178. /*: Object*/
  179. , sessionToken
  180. /*: ?string*/
  181. )
  182. /*: Object*/
  183. {
  184. if (!query) {
  185. return;
  186. }
  187. const className = query.className;
  188. const queryJSON = query.toJSON();
  189. const where = queryJSON.where;
  190. const fields = queryJSON.keys ? queryJSON.keys.split(',') : undefined;
  191. const subscribeRequest = {
  192. op: OP_TYPES.SUBSCRIBE,
  193. requestId: this.requestId,
  194. query: {
  195. className,
  196. where,
  197. fields
  198. }
  199. };
  200. if (sessionToken) {
  201. subscribeRequest.sessionToken = sessionToken;
  202. }
  203. const subscription = new _LiveQuerySubscription.default(this.requestId, query, sessionToken);
  204. this.subscriptions.set(this.requestId, subscription);
  205. this.requestId += 1;
  206. this.connectPromise.then(() => {
  207. this.socket.send(JSON.stringify(subscribeRequest));
  208. });
  209. return subscription;
  210. }
  211. /**
  212. * After calling unsubscribe you'll stop receiving events from the subscription object.
  213. *
  214. * @param {Object} subscription - subscription you would like to unsubscribe from.
  215. */
  216. unsubscribe(subscription
  217. /*: Object*/
  218. ) {
  219. if (!subscription) {
  220. return;
  221. }
  222. this.subscriptions.delete(subscription.id);
  223. const unsubscribeRequest = {
  224. op: OP_TYPES.UNSUBSCRIBE,
  225. requestId: subscription.id
  226. };
  227. this.connectPromise.then(() => {
  228. this.socket.send(JSON.stringify(unsubscribeRequest));
  229. });
  230. }
  231. /**
  232. * After open is called, the LiveQueryClient will try to send a connect request
  233. * to the LiveQuery server.
  234. *
  235. */
  236. open() {
  237. const WebSocketImplementation = _CoreManager.default.getWebSocketController();
  238. if (!WebSocketImplementation) {
  239. this.emit(CLIENT_EMMITER_TYPES.ERROR, 'Can not find WebSocket implementation');
  240. return;
  241. }
  242. if (this.state !== CLIENT_STATE.RECONNECTING) {
  243. this.state = CLIENT_STATE.CONNECTING;
  244. }
  245. this.socket = new WebSocketImplementation(this.serverURL); // Bind WebSocket callbacks
  246. this.socket.onopen = () => {
  247. this._handleWebSocketOpen();
  248. };
  249. this.socket.onmessage = event => {
  250. this._handleWebSocketMessage(event);
  251. };
  252. this.socket.onclose = () => {
  253. this._handleWebSocketClose();
  254. };
  255. this.socket.onerror = error => {
  256. this._handleWebSocketError(error);
  257. };
  258. }
  259. resubscribe() {
  260. this.subscriptions.forEach((subscription, requestId) => {
  261. const query = subscription.query;
  262. const queryJSON = query.toJSON();
  263. const where = queryJSON.where;
  264. const fields = queryJSON.keys ? queryJSON.keys.split(',') : undefined;
  265. const className = query.className;
  266. const sessionToken = subscription.sessionToken;
  267. const subscribeRequest = {
  268. op: OP_TYPES.SUBSCRIBE,
  269. requestId,
  270. query: {
  271. className,
  272. where,
  273. fields
  274. }
  275. };
  276. if (sessionToken) {
  277. subscribeRequest.sessionToken = sessionToken;
  278. }
  279. this.connectPromise.then(() => {
  280. this.socket.send(JSON.stringify(subscribeRequest));
  281. });
  282. });
  283. }
  284. /**
  285. * This method will close the WebSocket connection to this LiveQueryClient,
  286. * cancel the auto reconnect and unsubscribe all subscriptions based on it.
  287. *
  288. */
  289. close() {
  290. if (this.state === CLIENT_STATE.INITIALIZED || this.state === CLIENT_STATE.DISCONNECTED) {
  291. return;
  292. }
  293. this.state = CLIENT_STATE.DISCONNECTED;
  294. this.socket.close(); // Notify each subscription about the close
  295. for (const subscription of this.subscriptions.values()) {
  296. subscription.emit(SUBSCRIPTION_EMMITER_TYPES.CLOSE);
  297. }
  298. this._handleReset();
  299. this.emit(CLIENT_EMMITER_TYPES.CLOSE);
  300. } // ensure we start with valid state if connect is called again after close
  301. _handleReset() {
  302. this.attempts = 1;
  303. this.id = 0;
  304. this.requestId = 1;
  305. this.connectPromise = (0, _promiseUtils.resolvingPromise)();
  306. this.subscriptions = new Map();
  307. }
  308. _handleWebSocketOpen() {
  309. this.attempts = 1;
  310. const connectRequest = {
  311. op: OP_TYPES.CONNECT,
  312. applicationId: this.applicationId,
  313. javascriptKey: this.javascriptKey,
  314. masterKey: this.masterKey,
  315. sessionToken: this.sessionToken
  316. };
  317. this.socket.send(JSON.stringify(connectRequest));
  318. }
  319. _handleWebSocketMessage(event
  320. /*: any*/
  321. ) {
  322. let data = event.data;
  323. if (typeof data === 'string') {
  324. data = JSON.parse(data);
  325. }
  326. let subscription = null;
  327. if (data.requestId) {
  328. subscription = this.subscriptions.get(data.requestId);
  329. }
  330. switch (data.op) {
  331. case OP_EVENTS.CONNECTED:
  332. if (this.state === CLIENT_STATE.RECONNECTING) {
  333. this.resubscribe();
  334. }
  335. this.emit(CLIENT_EMMITER_TYPES.OPEN);
  336. this.id = data.clientId;
  337. this.connectPromise.resolve();
  338. this.state = CLIENT_STATE.CONNECTED;
  339. break;
  340. case OP_EVENTS.SUBSCRIBED:
  341. if (subscription) {
  342. subscription.emit(SUBSCRIPTION_EMMITER_TYPES.OPEN);
  343. }
  344. break;
  345. case OP_EVENTS.ERROR:
  346. if (data.requestId) {
  347. if (subscription) {
  348. subscription.emit(SUBSCRIPTION_EMMITER_TYPES.ERROR, data.error);
  349. }
  350. } else {
  351. this.emit(CLIENT_EMMITER_TYPES.ERROR, data.error);
  352. }
  353. break;
  354. case OP_EVENTS.UNSUBSCRIBED:
  355. // We have already deleted subscription in unsubscribe(), do nothing here
  356. break;
  357. default:
  358. {
  359. // create, update, enter, leave, delete cases
  360. if (!subscription) {
  361. break;
  362. }
  363. let override = false;
  364. if (data.original) {
  365. override = true;
  366. delete data.original.__type; // Check for removed fields
  367. for (const field in data.original) {
  368. if (!(field in data.object)) {
  369. data.object[field] = undefined;
  370. }
  371. }
  372. data.original = _ParseObject.default.fromJSON(data.original, false);
  373. }
  374. delete data.object.__type;
  375. const parseObject = _ParseObject.default.fromJSON(data.object, override);
  376. subscription.emit(data.op, parseObject, data.original);
  377. const localDatastore = _CoreManager.default.getLocalDatastore();
  378. if (override && localDatastore.isEnabled) {
  379. localDatastore._updateObjectIfPinned(parseObject).then(() => {});
  380. }
  381. }
  382. }
  383. }
  384. _handleWebSocketClose() {
  385. if (this.state === CLIENT_STATE.DISCONNECTED) {
  386. return;
  387. }
  388. this.state = CLIENT_STATE.CLOSED;
  389. this.emit(CLIENT_EMMITER_TYPES.CLOSE); // Notify each subscription about the close
  390. for (const subscription of this.subscriptions.values()) {
  391. subscription.emit(SUBSCRIPTION_EMMITER_TYPES.CLOSE);
  392. }
  393. this._handleReconnect();
  394. }
  395. _handleWebSocketError(error
  396. /*: any*/
  397. ) {
  398. this.emit(CLIENT_EMMITER_TYPES.ERROR, error);
  399. for (const subscription of this.subscriptions.values()) {
  400. subscription.emit(SUBSCRIPTION_EMMITER_TYPES.ERROR);
  401. }
  402. this._handleReconnect();
  403. }
  404. _handleReconnect() {
  405. // if closed or currently reconnecting we stop attempting to reconnect
  406. if (this.state === CLIENT_STATE.DISCONNECTED) {
  407. return;
  408. }
  409. this.state = CLIENT_STATE.RECONNECTING;
  410. const time = generateInterval(this.attempts); // handle case when both close/error occur at frequent rates we ensure we do not reconnect unnecessarily.
  411. // we're unable to distinguish different between close/error when we're unable to reconnect therefore
  412. // we try to reonnect in both cases
  413. // server side ws and browser WebSocket behave differently in when close/error get triggered
  414. if (this.reconnectHandle) {
  415. clearTimeout(this.reconnectHandle);
  416. }
  417. this.reconnectHandle = setTimeout((() => {
  418. this.attempts++;
  419. this.connectPromise = (0, _promiseUtils.resolvingPromise)();
  420. this.open();
  421. }).bind(this), time);
  422. }
  423. }
  424. _CoreManager.default.setWebSocketController(require('ws'));
  425. var _default = LiveQueryClient;
  426. exports.default = _default;