-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathSignalRContext.tsx
More file actions
177 lines (155 loc) · 6.37 KB
/
SignalRContext.tsx
File metadata and controls
177 lines (155 loc) · 6.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import * as signalR from '@microsoft/signalr'
import React, { createContext, FC, useContext, useEffect, useCallback, useState } from 'react'
import { AuthContext } from './AuthContext'
import { config } from 'config'
import { useMsal } from '@azure/msal-react'
/**
* SignalR provides asynchronous communication between backend and frontend. This
* context provides functions for establishing event listeners and for accessing
* the connection object, primarily to verify that a connection has been made.
*
* When registering an event handler using "registerEvent" an event name needs to be
* provided, which must correspond to the event name used on the backend. The event
* handler should receive a username and a message, though the username is typically
* not relevant for broadcasted messages.
*
* It is important to note that event handlers can only see the scope at which they
* are defined, which means that any React state will be outdated once they receive
* a message. It is therefore important to update React state within these handlers
* by passing functions in the setter functions. For instance instead of doing:
*
* setState({...state, newEntry})
*
* we must instead do:
*
* setState((oldState) => { return {...oldState, newEntry} })
*
* When accessing this context within another context, it is also important to make
* sure that the other context provider is nested within the signalR context
* provider.
*
* Objects are received as JSON strings. When parsing these it is important to note
* that enums are typically encoded as numbers on the backend, and may therefore
* need to be translated to string enums when making comparisons on the frontend.
*/
interface ISignalRContext {
registerEvent: (eventName: string, onMessageReceived: (username: string, message: string) => void) => void
connectionReady: boolean
}
interface Props {
children: React.ReactNode
}
const defaultSignalRInterface = {
registerEvent: () => {},
connectionReady: false,
}
const URL = config.BACKEND_API_SIGNALR_URL
const SignalRContext = createContext<ISignalRContext>(defaultSignalRInterface)
export const SignalRProvider: FC<Props> = ({ children }) => {
const [connection, setConnection] = useState<signalR.HubConnection | undefined>(undefined)
const [connectionReady, setConnectionReady] = useState<boolean>(defaultSignalRInterface.connectionReady)
const { getAccessToken } = useContext(AuthContext)
const { accounts, inProgress } = useMsal()
const createConnection = useCallback(() => {
console.log('Attempting to create signalR connection...')
const newConnection = new signalR.HubConnectionBuilder()
.withUrl(URL, {
accessTokenFactory: async () => {
try {
return await getAccessToken()
} catch (e) {
console.error('Failed to acquire access token for SignalR:', e)
return '' // causes auth to fail; connection will error/retry
}
},
transport:
signalR.HttpTransportType.WebSockets |
signalR.HttpTransportType.ServerSentEvents |
signalR.HttpTransportType.LongPolling,
})
.withAutomaticReconnect()
.configureLogging(signalR.LogLevel.Error)
.build()
newConnection.onclose((error) => {
console.log('SignalR connection closed:', error)
setConnectionReady(false)
})
newConnection.onreconnected(() => {
console.log('SignalR reconnected')
setConnectionReady(true)
})
newConnection.onreconnecting(() => {
console.log('SignalR reconnecting...')
setConnectionReady(false)
})
return newConnection
}, [getAccessToken])
const resetConnection = () => {
if (connection) {
connection.stop()
}
const newConnection = createConnection()
setConnection(newConnection)
newConnection
.start()
.then(() => {
console.log('SignalR connection made: ', newConnection)
setConnectionReady(true)
})
.catch((error) => {
console.error('SignalR connection failed:', error)
setConnectionReady(false)
})
return newConnection
}
useEffect(() => {
if (!accounts[0] || inProgress !== 'none') return
const newConnection = resetConnection()
return () => {
newConnection.stop()
}
}, [accounts, inProgress])
const registerEvent = (eventName: string, onMessageReceived: (username: string, message: string) => void) => {
if (connection)
connection.on(eventName, (username, message) => {
if (message === 'null') {
console.warn(`Received signalR message for event ${eventName} is 'null'`)
return
}
onMessageReceived(username, message)
})
}
return (
<SignalRContext.Provider
value={{
registerEvent,
connectionReady,
}}
>
{children}
</SignalRContext.Provider>
)
}
export const useSignalRContext = () => useContext(SignalRContext)
export enum SignalREventLabels {
missionRunUpdated = 'Mission run updated',
missionDefinitionCreated = 'Mission definition created',
missionDefinitionUpdated = 'Mission definition updated',
missionDefinitionDeleted = 'Mission definition deleted',
missionRunCreated = 'Mission run created',
missionRunDeleted = 'Mission run deleted',
missionRunFailed = 'Mission run failed',
inspectionAreaCreated = 'InspectionArea created',
inspectionAreaUpdated = 'InspectionArea updated',
inspectionAreaDeleted = 'InspectionArea deleted',
robotAdded = 'Robot added',
robotUpdated = 'Robot updated',
robotPropertyUpdated = 'Robot property updated',
robotTelemetryUpdated = 'Robot telemetry updated',
robotDeleted = 'Robot deleted',
inspectionUpdated = 'Inspection updated',
alert = 'Alert',
mediaStreamConfigReceived = 'Media stream config received',
inspectionVisualizationReady = 'Inspection Visulization Ready',
analysisResultReady = 'Analysis Result Ready',
}