You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DefaultConnectionStateHandler.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. /*
  2. * Copyright 2000-2018 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.client.communication;
  17. import java.util.logging.Logger;
  18. import com.google.gwt.core.client.JavaScriptObject;
  19. import com.google.gwt.core.shared.GWT;
  20. import com.google.gwt.http.client.Request;
  21. import com.google.gwt.http.client.Response;
  22. import com.google.gwt.regexp.shared.MatchResult;
  23. import com.google.gwt.regexp.shared.RegExp;
  24. import com.google.gwt.user.client.Timer;
  25. import com.vaadin.client.ApplicationConnection;
  26. import com.vaadin.client.ApplicationConnection.ApplicationStoppedEvent;
  27. import com.vaadin.client.WidgetUtil;
  28. import com.vaadin.client.communication.AtmospherePushConnection.AtmosphereResponse;
  29. import com.vaadin.shared.ui.ui.UIState.ReconnectDialogConfigurationState;
  30. import elemental.json.JsonObject;
  31. /**
  32. * Default implementation of the connection state handler.
  33. * <p>
  34. * Handles temporary errors by showing a reconnect dialog to the user while
  35. * trying to re-establish the connection to the server and re-send the pending
  36. * message.
  37. * <p>
  38. * Handles permanent errors by showing a critical system notification to the
  39. * user
  40. *
  41. * @since 7.6
  42. * @author Vaadin Ltd
  43. */
  44. public class DefaultConnectionStateHandler implements ConnectionStateHandler {
  45. private ApplicationConnection connection;
  46. private ReconnectDialog reconnectDialog = GWT.create(ReconnectDialog.class);
  47. private int reconnectAttempt = 0;
  48. private Type reconnectionCause = null;
  49. private Timer scheduledReconnect;
  50. private Timer dialogShowTimer = new Timer() {
  51. @Override
  52. public void run() {
  53. showDialog();
  54. }
  55. };
  56. protected enum Type {
  57. HEARTBEAT(0), PUSH(1), XHR(2);
  58. private int priority;
  59. private Type(int priority) {
  60. this.priority = priority;
  61. }
  62. public boolean isMessage() {
  63. return this == PUSH || this == XHR;
  64. }
  65. /**
  66. * Checks if this type is of higher priority than the given type.
  67. *
  68. * @param type
  69. * the type to compare to
  70. * @return true if this type has higher priority than the given type,
  71. * false otherwise
  72. */
  73. public boolean isHigherPriorityThan(Type type) {
  74. return priority > type.priority;
  75. }
  76. }
  77. @Override
  78. public void setConnection(ApplicationConnection connection) {
  79. this.connection = connection;
  80. connection.addHandler(ApplicationStoppedEvent.TYPE,
  81. event -> {
  82. if (isReconnecting()) {
  83. giveUp();
  84. }
  85. if (scheduledReconnect != null
  86. && scheduledReconnect.isRunning()) {
  87. scheduledReconnect.cancel();
  88. }
  89. });
  90. // Allow dialog to cache needed resources to make them available when we
  91. // are offline
  92. reconnectDialog.preload(connection);
  93. };
  94. /**
  95. * Checks if we are currently trying to reconnect
  96. *
  97. * @return true if we have noted a problem and are trying to re-establish
  98. * server connection, false otherwise
  99. */
  100. private boolean isReconnecting() {
  101. return reconnectionCause != null;
  102. }
  103. private static Logger getLogger() {
  104. return Logger.getLogger(DefaultConnectionStateHandler.class.getName());
  105. }
  106. /**
  107. * Returns the connection this handler is connected to.
  108. *
  109. * @return the connection for this handler
  110. */
  111. protected ApplicationConnection getConnection() {
  112. return connection;
  113. }
  114. @Override
  115. public void xhrException(XhrConnectionError xhrConnectionError) {
  116. debug("xhrException");
  117. handleRecoverableError(Type.XHR, xhrConnectionError.getPayload());
  118. }
  119. @Override
  120. public void heartbeatException(Request request, Throwable exception) {
  121. getLogger().severe("Heartbeat exception: " + exception.getMessage());
  122. handleRecoverableError(Type.HEARTBEAT, null);
  123. }
  124. @Override
  125. public void heartbeatInvalidStatusCode(Request request, Response response) {
  126. int statusCode = response.getStatusCode();
  127. getLogger().warning("Heartbeat request returned " + statusCode);
  128. if (response.getStatusCode() == Response.SC_GONE) {
  129. // Session expired
  130. getConnection().showSessionExpiredError(null);
  131. stopApplication();
  132. } else if (response.getStatusCode() == Response.SC_NOT_FOUND) {
  133. // UI closed, do nothing as the UI will react to this
  134. // Should not trigger reconnect dialog as this will prevent user
  135. // input
  136. } else {
  137. handleRecoverableError(Type.HEARTBEAT, null);
  138. }
  139. }
  140. @Override
  141. public void heartbeatOk() {
  142. debug("heartbeatOk");
  143. if (isReconnecting()) {
  144. resolveTemporaryError(Type.HEARTBEAT);
  145. }
  146. }
  147. private void debug(String msg) {
  148. if (false) {
  149. getLogger().warning(msg);
  150. }
  151. }
  152. /**
  153. * Called whenever an error occurs in communication which should be handled
  154. * by showing the reconnect dialog and retrying communication until
  155. * successful again.
  156. *
  157. * @param type
  158. * The type of failure detected
  159. * @param payload
  160. * The message which did not reach the server, or null if no
  161. * message was involved (heartbeat or push connection failed)
  162. */
  163. protected void handleRecoverableError(Type type, final JsonObject payload) {
  164. debug("handleTemporaryError(" + type + ")");
  165. if (!connection.isApplicationRunning()) {
  166. return;
  167. }
  168. if (!isReconnecting()) {
  169. // First problem encounter
  170. reconnectionCause = type;
  171. getLogger().warning("Reconnecting because of " + type + " failure");
  172. // Precaution only as there should never be a dialog at this point
  173. // and no timer running
  174. stopDialogTimer();
  175. if (isDialogVisible()) {
  176. hideDialog();
  177. }
  178. // Show dialog after grace period, still continue to try to
  179. // reconnect even before it is shown
  180. dialogShowTimer.schedule(getConfiguration().dialogGracePeriod);
  181. } else {
  182. // We are currently trying to reconnect
  183. // Priority is HEARTBEAT -> PUSH -> XHR
  184. // If a higher priority issues is resolved, we can assume the lower
  185. // one will be also
  186. if (type.isHigherPriorityThan(reconnectionCause)) {
  187. getLogger().warning(
  188. "Now reconnecting because of " + type + " failure");
  189. reconnectionCause = type;
  190. }
  191. }
  192. if (reconnectionCause != type) {
  193. return;
  194. }
  195. reconnectAttempt++;
  196. getLogger()
  197. .info("Reconnect attempt " + reconnectAttempt + " for " + type);
  198. if (reconnectAttempt >= getConfiguration().reconnectAttempts) {
  199. // Max attempts reached, stop trying
  200. giveUp();
  201. } else {
  202. updateDialog();
  203. scheduleReconnect(payload);
  204. }
  205. }
  206. /**
  207. * Called after a problem occurred.
  208. *
  209. * This method is responsible for re-sending the payload to the server (if
  210. * not null) or re-send a heartbeat request at some point
  211. *
  212. * @param payload
  213. * the payload that did not reach the server, null if the problem
  214. * was detected by a heartbeat
  215. */
  216. protected void scheduleReconnect(final JsonObject payload) {
  217. // Here and not in timer to avoid TB for getting in between
  218. // The request is still open at this point to avoid interference, so we
  219. // do not need to start a new one
  220. if (reconnectAttempt == 1) {
  221. // Try once immediately
  222. doReconnect(payload);
  223. } else {
  224. scheduledReconnect = new Timer() {
  225. @Override
  226. public void run() {
  227. scheduledReconnect = null;
  228. doReconnect(payload);
  229. }
  230. };
  231. scheduledReconnect.schedule(getConfiguration().reconnectInterval);
  232. }
  233. }
  234. /**
  235. * Re-sends the payload to the server (if not null) or re-sends a heartbeat
  236. * request immediately.
  237. *
  238. * @param payload
  239. * the payload that did not reach the server, null if the problem
  240. * was detected by a heartbeat
  241. */
  242. protected void doReconnect(JsonObject payload) {
  243. if (!connection.isApplicationRunning()) {
  244. // This should not happen as nobody should call this if the
  245. // application has been stopped
  246. getLogger().warning(
  247. "Trying to reconnect after application has been stopped. Giving up");
  248. return;
  249. }
  250. if (payload != null) {
  251. getLogger().info("Re-sending last message to the server...");
  252. getConnection().getMessageSender().send(payload);
  253. } else {
  254. // Use heartbeat
  255. getLogger().info("Trying to re-establish server connection...");
  256. getConnection().getHeartbeat().send();
  257. }
  258. }
  259. /**
  260. * Called whenever a reconnect attempt fails to allow updating of dialog
  261. * contents.
  262. */
  263. protected void updateDialog() {
  264. reconnectDialog.setText(getDialogText(reconnectAttempt));
  265. }
  266. /**
  267. * Called when we should give up trying to reconnect and let the user decide
  268. * how to continue.
  269. *
  270. */
  271. protected void giveUp() {
  272. reconnectionCause = null;
  273. endRequest();
  274. stopDialogTimer();
  275. if (!isDialogVisible()) {
  276. // It SHOULD always be visible at this point, unless you have a
  277. // really strange configuration (grace time longer than total
  278. // reconnect time)
  279. showDialog();
  280. }
  281. reconnectDialog.setText(getDialogTextGaveUp(reconnectAttempt));
  282. reconnectDialog.setReconnecting(false);
  283. // Stopping the application stops heartbeats and push
  284. connection.setApplicationRunning(false);
  285. }
  286. /**
  287. * Ensures the reconnect dialog does not popup some time from now
  288. */
  289. private void stopDialogTimer() {
  290. if (dialogShowTimer.isRunning()) {
  291. dialogShowTimer.cancel();
  292. }
  293. }
  294. /**
  295. * Checks if the reconnect dialog is visible to the user.
  296. *
  297. * @return true if the user can see the dialog, false otherwise
  298. */
  299. protected boolean isDialogVisible() {
  300. return reconnectDialog.isVisible();
  301. }
  302. /**
  303. * Called when the reconnect dialog should be shown. This is typically when
  304. * N seconds has passed since a problem with the connection has been
  305. * detected
  306. */
  307. protected void showDialog() {
  308. reconnectDialog.setReconnecting(true);
  309. reconnectDialog.show(connection);
  310. // We never want to show loading indicator and reconnect dialog at the
  311. // same time
  312. connection.getLoadingIndicator().hide();
  313. }
  314. /**
  315. * Called when the reconnect dialog should be hidden.
  316. */
  317. protected void hideDialog() {
  318. reconnectDialog.setReconnecting(false);
  319. reconnectDialog.hide();
  320. }
  321. /**
  322. * Gets the text to show in the reconnect dialog after giving up (reconnect
  323. * limit reached).
  324. *
  325. * @param reconnectAttempt
  326. * The number of the current reconnection attempt
  327. * @return The text to show in the reconnect dialog after giving up
  328. */
  329. protected String getDialogTextGaveUp(int reconnectAttempt) {
  330. return getConfiguration().dialogTextGaveUp.replace("{0}",
  331. reconnectAttempt + "");
  332. }
  333. /**
  334. * Gets the text to show in the reconnect dialog.
  335. *
  336. * @param reconnectAttempt
  337. * The number of the current reconnection attempt
  338. * @return The text to show in the reconnect dialog
  339. */
  340. protected String getDialogText(int reconnectAttempt) {
  341. return getConfiguration().dialogText.replace("{0}",
  342. reconnectAttempt + "");
  343. }
  344. @Override
  345. public void configurationUpdated() {
  346. // All other properties are fetched directly from the state when needed
  347. reconnectDialog.setModal(getConfiguration().dialogModal);
  348. }
  349. private ReconnectDialogConfigurationState getConfiguration() {
  350. return connection.getUIConnector()
  351. .getState().reconnectDialogConfiguration;
  352. }
  353. @Override
  354. public void xhrInvalidContent(XhrConnectionError xhrConnectionError) {
  355. debug("xhrInvalidContent");
  356. endRequest();
  357. String responseText = xhrConnectionError.getResponse().getText();
  358. /*
  359. * A servlet filter or equivalent may have intercepted the request and
  360. * served non-UIDL content (for instance, a login page if the session
  361. * has expired.) If the response contains a magic substring, do a
  362. * synchronous refresh. See #8241.
  363. */
  364. MatchResult refreshToken = RegExp
  365. .compile(ApplicationConnection.UIDL_REFRESH_TOKEN
  366. + "(:\\s*(.*?))?(\\s|$)")
  367. .exec(responseText);
  368. if (refreshToken != null) {
  369. WidgetUtil.redirect(getConnection()
  370. .translateVaadinUri(refreshToken.getGroup(2)));
  371. } else {
  372. handleUnrecoverableCommunicationError(
  373. "Invalid JSON response from server: " + responseText,
  374. xhrConnectionError);
  375. }
  376. }
  377. @Override
  378. public void pushInvalidContent(PushConnection pushConnection,
  379. String message) {
  380. debug("pushInvalidContent");
  381. if (pushConnection.isBidirectional()) {
  382. // We can't be sure that what was pushed was actually a response but
  383. // at this point it should not really matter, as something is
  384. // seriously broken.
  385. endRequest();
  386. }
  387. // Do nothing special for now. Should likely do the same as
  388. // xhrInvalidContent
  389. handleUnrecoverableCommunicationError(
  390. "Invalid JSON from server: " + message, null);
  391. }
  392. @Override
  393. public void xhrInvalidStatusCode(XhrConnectionError xhrConnectionError) {
  394. debug("xhrInvalidStatusCode");
  395. Response response = xhrConnectionError.getResponse();
  396. int statusCode = response.getStatusCode();
  397. getLogger().warning("Server returned " + statusCode + " for xhr");
  398. if (statusCode == 401) {
  399. // Authentication/authorization failed, no need to re-try
  400. endRequest();
  401. handleUnauthorized(xhrConnectionError);
  402. return;
  403. } else {
  404. // 404, 408 and other 4xx codes CAN be temporary when you have a
  405. // proxy between the client and the server and e.g. restart the
  406. // server
  407. // 5xx codes may or may not be temporary
  408. handleRecoverableError(Type.XHR, xhrConnectionError.getPayload());
  409. }
  410. }
  411. private void endRequest() {
  412. getConnection().getMessageSender().endRequest();
  413. }
  414. protected void handleUnauthorized(XhrConnectionError xhrConnectionError) {
  415. /*
  416. * Authorization has failed (401). Could be that the session has timed
  417. * out.
  418. */
  419. connection.showAuthenticationError("");
  420. stopApplication();
  421. }
  422. private void stopApplication() {
  423. // Consider application not running any more and prevent all
  424. // future requests
  425. connection.setApplicationRunning(false);
  426. }
  427. private void handleUnrecoverableCommunicationError(String details,
  428. XhrConnectionError xhrConnectionError) {
  429. int statusCode = -1;
  430. if (xhrConnectionError != null) {
  431. Response response = xhrConnectionError.getResponse();
  432. if (response != null) {
  433. statusCode = response.getStatusCode();
  434. }
  435. }
  436. connection.handleCommunicationError(details, statusCode);
  437. stopApplication();
  438. }
  439. @Override
  440. public void xhrOk() {
  441. debug("xhrOk");
  442. if (isReconnecting()) {
  443. resolveTemporaryError(Type.XHR);
  444. }
  445. }
  446. private void resolveTemporaryError(Type type) {
  447. debug("resolveTemporaryError(" + type + ")");
  448. if (reconnectionCause != type) {
  449. // Waiting for some other problem to be resolved
  450. return;
  451. }
  452. reconnectionCause = null;
  453. reconnectAttempt = 0;
  454. // IF reconnect happens during grace period, make sure the dialog is not
  455. // shown and does not popup later
  456. stopDialogTimer();
  457. hideDialog();
  458. getLogger().info("Re-established connection to server");
  459. }
  460. @Override
  461. public void pushOk(PushConnection pushConnection) {
  462. debug("pushOk()");
  463. if (isReconnecting()) {
  464. resolveTemporaryError(Type.PUSH);
  465. }
  466. }
  467. @Override
  468. public void pushScriptLoadError(String resourceUrl) {
  469. connection.handleCommunicationError(
  470. resourceUrl + " could not be loaded. Push will not work.", 0);
  471. }
  472. @Override
  473. public void pushNotConnected(JsonObject payload) {
  474. debug("pushNotConnected()");
  475. handleRecoverableError(Type.PUSH, payload);
  476. }
  477. @Override
  478. public void pushReconnectPending(PushConnection pushConnection) {
  479. debug("pushReconnectPending(" + pushConnection.getTransportType()
  480. + ")");
  481. getLogger().info("Reopening push connection");
  482. if (pushConnection.isBidirectional()) {
  483. // Lost connection for a connection which will tell us when the
  484. // connection is available again
  485. handleRecoverableError(Type.PUSH, null);
  486. } else {
  487. // Lost connection for a connection we do not necessarily know when
  488. // it is available again (long polling behind proxy). Do nothing and
  489. // show reconnect dialog if the user does something and the XHR
  490. // fails
  491. }
  492. }
  493. @Override
  494. public void pushError(PushConnection pushConnection,
  495. JavaScriptObject response) {
  496. debug("pushError()");
  497. connection.handleCommunicationError("Push connection using "
  498. + ((AtmosphereResponse) response).getTransport() + " failed!",
  499. -1);
  500. }
  501. @Override
  502. public void pushClientTimeout(PushConnection pushConnection,
  503. JavaScriptObject response) {
  504. debug("pushClientTimeout()");
  505. // TODO Reconnect, allowing client timeout to be set
  506. // https://dev.vaadin.com/ticket/18429
  507. connection.handleCommunicationError(
  508. "Client unexpectedly disconnected. Ensure client timeout is disabled.",
  509. -1);
  510. }
  511. @Override
  512. public void pushClosed(PushConnection pushConnection,
  513. JavaScriptObject response) {
  514. debug("pushClosed()");
  515. getLogger().info("Push connection closed");
  516. }
  517. }