/
events.gateway.ts
298 lines (256 loc) · 8.22 KB
/
events.gateway.ts
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import { debounce, uniqBy } from 'lodash'
import SocketIO from 'socket.io'
import type {
GatewayMetadata,
OnGatewayConnection,
OnGatewayDisconnect,
} from '@nestjs/websockets'
import type { BroadcastOperator, Emitter } from '@socket.io/redis-emitter'
import type {
DecorateAcknowledgementsWithMultipleResponses,
DefaultEventsMap,
} from 'socket.io/dist/typed-events'
import type { SocketType } from '../gateway.service'
import type { EventGatewayHooks } from './hook.interface'
import {
ConnectedSocket,
MessageBody,
SubscribeMessage,
WebSocketGateway,
WebSocketServer,
} from '@nestjs/websockets'
import { BusinessEvents } from '~/constants/business-event.constant'
import { RedisKeys } from '~/constants/cache.constant'
import { CacheService } from '~/processors/redis/cache.service'
import { scheduleManager } from '~/utils'
import { getRedisKey } from '~/utils/redis.util'
import { getShortDate } from '~/utils/time.util'
import { BroadcastBaseGateway } from '../base.gateway'
import { GatewayService } from '../gateway.service'
import { MessageEventDto, SupportedMessageEvent } from './dtos/message'
declare module '~/types/socket-meta' {
interface SocketMetadata {
sessionId: string
roomJoinedAtMap: Record<string, number>
}
}
const namespace = 'web'
// @UseGuards(WsExtendThrottlerGuard)
@WebSocketGateway<GatewayMetadata>({
namespace,
})
export class WebEventsGateway
extends BroadcastBaseGateway
implements OnGatewayConnection, OnGatewayDisconnect
{
constructor(
private readonly cacheService: CacheService,
private readonly gatewayService: GatewayService,
) {
super()
}
private hooks: EventGatewayHooks = {
onConnected: [],
onDisconnected: [],
onMessage: [],
onJoinRoom: [],
onLeaveRoom: [],
}
public registerHook<T extends keyof EventGatewayHooks>(
type: T,
callback: EventGatewayHooks[T][number],
) {
// @ts-expect-error
this.hooks[type].push(callback)
return () => {
// @ts-expect-error
this.hooks[type] = this.hooks[type].filter((fn) => fn !== callback)
}
}
@WebSocketServer()
private namespace: SocketIO.Namespace
async sendOnlineNumber() {
return {
online: await this.getCurrentClientCount(),
timestamp: new Date().toISOString(),
}
}
async getCurrentClientCount() {
const server = this.namespace.server
const socketsMeta = await Promise.all(
await server
.of(`/${namespace}`)
.fetchSockets()
.then((sockets) => {
return sockets.map((socket) =>
this.gatewayService.getSocketMetadata(socket),
)
}),
)
// // 这里用 web socket id 作为同一用户,一般 web 用 userId 或者 local storage sessionId 作为 socket session id
// return uniqBy(socketsMeta, async (x) => {
// const meta = await this.gatewayService.getSocketMetadata(x)
// console.log(meta, 'meta', x.id, 'x.id')
// return meta?.sessionId || true
// }).length
return uniqBy(socketsMeta, (x) => x?.sessionId).length
}
@SubscribeMessage('message')
async handleMessageEvent(
@MessageBody() data: MessageEventDto,
@ConnectedSocket() socket: SocketIO.Socket,
) {
const { payload, type } = data
// logger.debug('Received message', { type, payload })
switch (type) {
case SupportedMessageEvent.Join: {
const { roomName } = payload as { roomName: string }
if (roomName) {
socket.join(roomName)
this.hooks.onJoinRoom.forEach((fn) => fn(socket, roomName))
const roomJoinedAtMap = await this.getSocketRoomJoinedAtMap(socket)
roomJoinedAtMap[roomName] = Date.now()
await this.gatewayService.setSocketMetadata(socket, {
roomJoinedAtMap,
})
}
break
}
case SupportedMessageEvent.Leave: {
const { roomName } = payload as { roomName: string }
if (roomName) {
socket.leave(roomName)
this.hooks.onLeaveRoom.forEach((fn) => fn(socket, roomName))
const roomJoinedAtMap = await this.getSocketRoomJoinedAtMap(socket)
delete roomJoinedAtMap[roomName]
await this.gatewayService.setSocketMetadata(socket, {
roomJoinedAtMap,
})
}
break
}
case SupportedMessageEvent.UpdateSid: {
const { sessionId } = payload as { sessionId: string }
if (sessionId) {
await this.gatewayService.setSocketMetadata(socket, { sessionId })
this.whenUserOnline()
}
}
}
this.hooks.onMessage.forEach((fn) => fn(socket, data))
}
async handleConnection(socket: SocketIO.Socket) {
const webSessionId =
socket.handshake.headers['x-socket-session-id'] ||
socket.handshake.query['socket_session_id'] ||
// fallback sid
socket.id
// logger.debug('webSessionId', webSessionId)
await this.gatewayService.setSocketMetadata(socket, {
sessionId: webSessionId,
})
this.whenUserOnline()
super.handleConnect(socket)
this.hooks.onConnected.forEach((fn) => fn(socket))
}
whenUserOnline = debounce(
async () => {
this.broadcast(
BusinessEvents.VISITOR_ONLINE,
await this.sendOnlineNumber(),
)
scheduleManager.schedule(async () => {
const redisClient = this.cacheService.getClient()
const dateFormat = getShortDate(new Date())
// get and store max_online_count
const maxOnlineCount =
+(await redisClient.hget(
getRedisKey(RedisKeys.MaxOnlineCount),
dateFormat,
))! || 0
await redisClient.hset(
getRedisKey(RedisKeys.MaxOnlineCount),
dateFormat,
Math.max(maxOnlineCount, await this.getCurrentClientCount()),
)
const key = getRedisKey(RedisKeys.MaxOnlineCount, 'total')
const totalCount = +(await redisClient.hget(key, dateFormat))! || 0
await redisClient.hset(key, dateFormat, totalCount + 1)
})
},
1000,
{
leading: false,
},
)
async handleDisconnect(socket: SocketIO.Socket) {
super.handleDisconnect(socket)
this.broadcast(BusinessEvents.VISITOR_OFFLINE, {
...(await this.sendOnlineNumber()),
sessionId: (await this.gatewayService.getSocketMetadata(socket))
?.sessionId,
})
this.hooks.onDisconnected.forEach((fn) => fn(socket))
this.gatewayService.clearSocketMetadata(socket)
socket.rooms.forEach((roomName) => {
this.hooks.onLeaveRoom.forEach((fn) => fn(socket, roomName))
})
}
override broadcast(
event: BusinessEvents,
data: any,
options?: {
rooms?: string[]
exclude?: string[]
},
) {
const emitter = this.cacheService.emitter
let socket = emitter.of(`/${namespace}`) as
| Emitter<DefaultEventsMap>
| BroadcastOperator<DefaultEventsMap>
const rooms = options?.rooms
const exclude = options?.exclude
if (rooms && rooms.length > 0) {
socket = socket.in(rooms)
}
if (exclude && exclude.length > 0) {
socket = socket.except(exclude)
}
socket.emit('message', this.gatewayMessageFormat(event, data))
}
public async getSocketsOfRoom(
roomName: string,
): Promise<
| SocketIO.Socket[]
| SocketIO.RemoteSocket<
DecorateAcknowledgementsWithMultipleResponses<DefaultEventsMap>,
any
>[]
> {
return this.namespace.in(roomName).fetchSockets()
}
// private isValidBizRoomName(roomName: string) {
// return roomName.split('-').length === 2
// }
public async getAllRooms() {
const sockets = await this.namespace.fetchSockets()
const roomToSocketsMap = {} as Record<string, (typeof sockets)[number][]>
for (const socket of sockets) {
socket.rooms.forEach((roomName) => {
if (roomName === socket.id) return
if (!roomToSocketsMap[roomName]) {
roomToSocketsMap[roomName] = []
}
roomToSocketsMap[roomName].push(socket)
})
}
return roomToSocketsMap
}
public async getSocketRoomJoinedAtMap(socket: SocketType) {
const roomJoinedAtMap =
(await this.gatewayService.getSocketMetadata(socket))?.roomJoinedAtMap ||
{}
return roomJoinedAtMap
}
}