connection.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. import { computed, ref, watch } from 'vue'
  3. import {
  4. consumer,
  5. reopenWebSocketConnection,
  6. } from '#shared/server/action_cable/consumer.ts'
  7. import log from '#shared/utils/log.ts'
  8. import {
  9. NotificationTypes,
  10. useNotifications,
  11. } from '#shared/components/CommonNotifications/index.ts'
  12. import { useApplicationLoaded } from '#shared/composables/useApplicationLoaded.ts'
  13. const wsConnectionState = ref(true)
  14. const wsReopening = ref(false)
  15. const { loaded } = useApplicationLoaded()
  16. window.setInterval(() => {
  17. wsConnectionState.value = !loaded.value || consumer.connection.isOpen()
  18. }, 1000)
  19. let connectionNotificationId: string
  20. const networkConnectionState = ref(true)
  21. const connected = computed(() => {
  22. return (
  23. (wsReopening.value || wsConnectionState.value) &&
  24. networkConnectionState.value
  25. )
  26. })
  27. const notifications = useNotifications()
  28. watch(
  29. () => connected.value,
  30. (connected) => {
  31. if (connected) {
  32. if (!connectionNotificationId) return
  33. log.debug('Application connection just came up.')
  34. notifications.removeNotification(connectionNotificationId)
  35. } else {
  36. log.debug('Application connection just went down.')
  37. connectionNotificationId = notifications.notify({
  38. message: __('The connection to the server was lost.'),
  39. type: NotificationTypes.Error,
  40. persistent: true,
  41. })
  42. }
  43. },
  44. )
  45. export const recordCommunicationSuccess = (): void => {
  46. networkConnectionState.value = true
  47. }
  48. export const recordCommunicationFailure = (): void => {
  49. networkConnectionState.value = false
  50. }
  51. export const triggerWebSocketReconnect = (): void => {
  52. wsReopening.value = true
  53. reopenWebSocketConnection()
  54. .then(() => {
  55. // Set this before setting wsReopening, otherwise it would be set later by the interval,
  56. // causing false positives.
  57. wsConnectionState.value = true
  58. })
  59. .finally(() => {
  60. wsReopening.value = false
  61. })
  62. }