-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathsocketBroker.ts
More file actions
187 lines (159 loc) · 5.37 KB
/
Copy pathsocketBroker.ts
File metadata and controls
187 lines (159 loc) · 5.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
178
179
180
181
182
183
184
185
186
187
import pLimit from 'p-limit';
import { IAdminForth, IWebSocketBroker, IWebSocketClient } from "../types/Back.js";
import { AdminUser } from "../types/Common.js";
import { afLogger } from '../modules/logger.js';
const PUBLISH_FILTER_CONCURRENCY = 10;
export default class SocketBroker implements IWebSocketBroker {
clients: IWebSocketClient[] = [];
topics: { [key: string]: IWebSocketClient[] } = {};
adminforth: IAdminForth;
deadCheckerRunning = false;
constructor(adminforth: IAdminForth) {
this.adminforth = adminforth;
}
async startChecker() {
if (this.deadCheckerRunning) {
return;
}
this.deadCheckerRunning = true;
while (true) {
await this.checkDeadClients();
await new Promise((resolve) => setTimeout(resolve, 10_000));
}
}
async checkDeadClients() {
const now = Date.now();
const deadClients = [];
for (const client of this.clients) {
if (now - client.lastPing > 30_000) {
deadClients.push(client);
}
}
deadClients.forEach(client => {
client.close();
delete this.clients[client.id];
});
}
deleteClientFromTopic(client: IWebSocketClient, topic: string) {
if (!this.topics[topic]) {
return;
}
this.topics[topic] = this.topics[topic].filter(c => c !== client);
}
cleanupTopicIfEmpty(topic: string) {
if (!this.topics[topic]) {
return;
}
if (this.topics[topic].length === 0) {
delete this.topics[topic];
}
}
registerWsClient(client: IWebSocketClient): void {
this.startChecker();
if (!this.clients[client.id]) {
this.clients[client.id] = client;
}
client.onMessage(async (message) => {
const messageText = message.toString();
if (!messageText.trim()) {
return;
}
if (messageText === 'ping') {
client.send('pong');
client.lastPing = Date.now();
return;
}
let data: unknown;
try {
data = JSON.parse(messageText);
} catch (e) {
client.send(JSON.stringify({ type: 'error', message: 'Invalid websocket message JSON' }));
return;
}
if (!data || typeof data !== 'object' || Array.isArray(data)) {
client.send(JSON.stringify({ type: 'error', message: 'Invalid websocket message format' }));
return;
}
const payload = data as { type?: unknown; topic?: unknown };
if (payload.type !== 'subscribe' && payload.type !== 'unsubscribe') {
client.send(JSON.stringify({ type: 'error', message: 'Unknown websocket message type' }));
return;
}
if (typeof payload.topic !== 'string' || !payload.topic) {
client.send(JSON.stringify({ type: 'error', message: 'No topic provided' }));
return;
}
const topic = payload.topic;
if (payload.type === 'subscribe') {
if (!topic.startsWith('/opentopic/')) {
if (this.adminforth.config.auth.websocketTopicAuth) {
let authResult = false;
try {
authResult = await this.adminforth.config.auth.websocketTopicAuth(topic, client.adminUser);
} catch (e) {
afLogger.error(`Error in websocketTopicAuth, assuming connection not allowed ${e}`);
}
if (!authResult) {
client.send(JSON.stringify({ type: 'error', message: 'Unauthorized' }));
return;
}
}
}
if (!this.topics[topic]) {
this.topics[topic] = [];
}
if (!this.topics[topic].includes(client)) {
this.topics[topic].push(client);
}
client.topics.add(topic);
if (this.adminforth.config.auth.websocketSubscribed) {
(async () => {
try {
await this.adminforth.config.auth.websocketSubscribed(topic, client.adminUser);
} catch (e) {
afLogger.error(`Error in websocketSubscribed for topic ${topic}, ${e}`);
}
})(); // run in background
}
return;
}
this.deleteClientFromTopic(client, topic);
this.cleanupTopicIfEmpty(topic);
client.topics.delete(topic);
});
client.onClose(() => {
for (const topic of client.topics) {
this.deleteClientFromTopic(client, topic);
this.cleanupTopicIfEmpty(topic);
}
delete this.clients[client.id];
});
// send ready message
client.send(JSON.stringify({ type: 'ready' }));
}
async publish(topic: string, data: any, filterUsers?: (adminUser: AdminUser) => Promise<boolean>): Promise<void> {
if (!this.topics[topic]) {
afLogger.trace(`No clients subscribed to topic ${topic}`);
return;
}
const message = JSON.stringify({ type: 'message', topic, data });
if (!filterUsers) {
for (const client of this.topics[topic]) {
afLogger.trace(`Sending data to socket ${topic} ${JSON.stringify(data)}`);
client.send(message);
}
return;
}
const limit = pLimit(PUBLISH_FILTER_CONCURRENCY);
await Promise.all(
this.topics[topic].map((client) => limit(async () => {
if (! (await filterUsers(client.adminUser)) ) {
afLogger.trace(`Client not authorized to receive message ${topic} ${client.adminUser}`);
return;
}
afLogger.trace(`Sending data to socket ${topic} ${JSON.stringify(data)}`);
client.send(message);
}))
);
}
}