-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathvalkeyEpics.ts
More file actions
261 lines (230 loc) · 8.35 KB
/
valkeyEpics.ts
File metadata and controls
261 lines (230 loc) · 8.35 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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
import { merge, timer, EMPTY } from "rxjs"
import { ignoreElements, tap, delay, switchMap, catchError, filter } from "rxjs/operators"
import * as R from "ramda"
import { DISCONNECTED, LOCAL_STORAGE, NOT_CONNECTED, RETRY_CONFIG, retryDelay } from "@common/src/constants.ts"
import { toast } from "sonner"
import { getSocket } from "./wsEpics"
import {
standaloneConnectFulfilled,
clusterConnectFulfilled,
connectPending,
deleteConnection,
connectRejected,
startRetry,
stopRetry,
updateConnectionDetails
} from "../valkey-features/connection/connectionSlice"
import { sendRequested } from "../valkey-features/command/commandSlice"
import { setData } from "../valkey-features/info/infoSlice"
import { action$, select } from "../middleware/rxjsMiddleware/rxjsMiddlware"
import { setClusterData } from "../valkey-features/cluster/clusterSlice"
import { connectFulfilled as wsConnectFulfilled } from "../wsconnection/wsConnectionSlice"
import { hotKeysRequested } from "../valkey-features/hotkeys/hotKeysSlice.ts"
import history from "../../history.ts"
import type { Store } from "@reduxjs/toolkit"
export const connectionEpic = (store: Store) =>
merge(
action$.pipe(
select(connectPending),
tap((action) => {
const socket = getSocket()
console.log("Sending message to server from connecting epic...")
socket.next(action)
}),
ignoreElements(),
),
action$.pipe(
select(standaloneConnectFulfilled),
tap(({ payload }) => {
try {
const currentConnections = R.pipe(
(v: string) => localStorage.getItem(v),
(s) => (s === null ? {} : JSON.parse(s)),
)(LOCAL_STORAGE.VALKEY_CONNECTIONS)
// for getting the full connection state from redux (which includes alias)
const state = store.getState()
const connection = state.valkeyConnection?.connections?.[payload.connectionId]
R.pipe(
(p) => ({
connectionDetails: connection?.connectionDetails || p.connectionDetails,
status: NOT_CONNECTED,
}),
(connectionToSave) => ({ ...currentConnections, [payload.connectionId]: connectionToSave }),
JSON.stringify,
(updated) => localStorage.setItem(LOCAL_STORAGE.VALKEY_CONNECTIONS, updated),
)(payload)
toast.success("Connected to server successfully!")
} catch (e) {
toast.error("Connection to server failed!")
console.error(e)
}
}),
),
action$.pipe(
select(connectRejected),
tap(({ payload: { connectionId, errorMessage } }) => {
console.error("Connection rejected for", connectionId, ":", errorMessage)
}),
ignoreElements(),
),
)
// Valkey connection retry epic
export const valkeyRetryEpic = (store: Store) =>
action$.pipe(
select(connectRejected),
switchMap(({ payload: { connectionId } }) => {
const state = store.getState()
const connection = state.valkeyConnection?.connections?.[connectionId]
if (!connection) {
console.log(`No connection found for ${connectionId}, skipping retry`)
return EMPTY
}
const currentAttempt = (connection.reconnect?.currentAttempt || 0) + 1
// to see if we should retry
if (currentAttempt > RETRY_CONFIG.MAX_RETRIES) {
console.log(`Max retries reached for ${connectionId}`)
store.dispatch(stopRetry({ connectionId }))
toast.error("Unable to reconnect to Valkey instance")
return EMPTY
}
const nextDelay = retryDelay(currentAttempt - 1)
store.dispatch(startRetry({
connectionId,
attempt: currentAttempt,
maxRetries: RETRY_CONFIG.MAX_RETRIES,
nextRetryDelay: nextDelay,
}))
console.log(`Retrying connection ${connectionId} (attempt ${currentAttempt}/${RETRY_CONFIG.MAX_RETRIES}) in ${nextDelay}ms`)
return timer(nextDelay).pipe(
tap(() => {
const { host, port, username, password, alias } = connection.connectionDetails
console.log(`Attempting retry ${currentAttempt} for ${connectionId}`)
store.dispatch(connectPending({
connectionId,
host,
port,
username,
password,
alias,
isRetry: true,
}))
}),
catchError((err) => {
console.error(`Error during retry for ${connectionId}:`, err)
return EMPTY
}),
ignoreElements(),
)
}),
)
// reconnect epic
export const autoReconnectEpic = (store: Store) =>
action$.pipe(
select(wsConnectFulfilled),
delay(500), // Small delay to ensure WebSocket is fully connected
tap(() => {
const state = store.getState()
const connections = state.valkeyConnection?.connections || {}
// disconnected Valkey connections
const disconnectedConnections = Object.entries(connections)
.filter(([, connection]) => connection.status === DISCONNECTED)
if (disconnectedConnections.length > 0) {
console.log(`Auto-reconnecting ${disconnectedConnections.length} connection(s)`)
toast.info(`Reconnecting ${disconnectedConnections.length} connection(s)...`)
// reconnect each disconnected connection
disconnectedConnections.forEach(([connectionId, connection]) => {
const { host, port, username, password, alias } = connection.connectionDetails
console.log(`Attempting to reconnect ${connectionId}`)
store.dispatch(connectPending({
connectionId,
host,
port,
username,
password,
alias,
}))
})
}
}),
ignoreElements(),
)
export const deleteConnectionEpic = () =>
action$.pipe(
select(deleteConnection),
// TODO: extract reused logic into separate method
tap(({ payload: { connectionId } }) => {
try {
const currentConnections = R.pipe(
(v: string) => localStorage.getItem(v),
(s) => (s === null ? {} : JSON.parse(s)),
)(LOCAL_STORAGE.VALKEY_CONNECTIONS)
R.pipe(
R.dissoc(connectionId),
JSON.stringify,
(updated) => localStorage.setItem(LOCAL_STORAGE.VALKEY_CONNECTIONS, updated),
() => toast.success("Connection removed successfully!"),
)(currentConnections)
} catch (e) {
toast.error("Failed to remove connection!")
console.error(e)
}
}),
)
// for updating connection details: this will presist the edits
export const updateConnectionDetailsEpic = (store: Store) =>
action$.pipe(
select(updateConnectionDetails),
tap(({ payload: { connectionId } }) => {
try {
const currentConnections = R.pipe(
(v: string) => localStorage.getItem(v),
(s) => (s === null ? {} : JSON.parse(s)),
)(LOCAL_STORAGE.VALKEY_CONNECTIONS)
const state = store.getState()
const connection = state.valkeyConnection?.connections?.[connectionId]
if (connection && currentConnections[connectionId]) {
currentConnections[connectionId].connectionDetails = connection.connectionDetails
localStorage.setItem(LOCAL_STORAGE.VALKEY_CONNECTIONS, JSON.stringify(currentConnections))
}
} catch (e) {
console.error(e)
}
}),
ignoreElements(),
)
export const sendRequestEpic = () =>
action$.pipe(
select(sendRequested),
tap((action) => {
const socket = getSocket()
socket.next(action)
}),
)
export const setDataEpic = () =>
action$.pipe(
filter(
({ type }) =>
type === standaloneConnectFulfilled.type ||
type === clusterConnectFulfilled.type,
),
tap((action) => {
const socket = getSocket()
const { clusterId, connectionId } = action.payload
if (action.type === clusterConnectFulfilled.type) {
socket.next({ type: setClusterData.type, payload: { clusterId, connectionId } })
}
socket.next({ type: setData.type, payload: { connectionId } })
const dashboardPath = clusterId
? `/${clusterId}/${connectionId}/dashboard`
: `/${connectionId}/dashboard`
history.navigate(dashboardPath)
}),
)
export const getHotKeysEpic = () =>
action$.pipe(
select(hotKeysRequested),
tap((action) => {
const socket = getSocket()
socket.next(action)
}),
)