Skip to content

Commit d7434c2

Browse files
authored
Merge pull request #707 from devforth/ws-authorization-work
fix: execute filterUsers callback in websocket publish in parallel
2 parents b5d837d + ed52bd9 commit d7434c2

3 files changed

Lines changed: 39 additions & 7 deletions

File tree

adminforth/modules/socketBroker.ts

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
1+
import pLimit from 'p-limit';
12
import { IAdminForth, IWebSocketBroker, IWebSocketClient } from "../types/Back.js";
23
import { AdminUser } from "../types/Common.js";
34
import { afLogger } from '../modules/logger.js';
45

6+
const PUBLISH_FILTER_CONCURRENCY = 10;
7+
58
export default class SocketBroker implements IWebSocketBroker {
69
clients: IWebSocketClient[] = [];
710
topics: { [key: string]: IWebSocketClient[] } = {};
@@ -158,16 +161,27 @@ export default class SocketBroker implements IWebSocketBroker {
158161
afLogger.trace(`No clients subscribed to topic ${topic}`);
159162
return;
160163
}
161-
for (const client of this.topics[topic]) {
162-
if (filterUsers) {
164+
const message = JSON.stringify({ type: 'message', topic, data });
165+
166+
if (!filterUsers) {
167+
for (const client of this.topics[topic]) {
168+
afLogger.trace(`Sending data to socket ${topic} ${JSON.stringify(data)}`);
169+
client.send(message);
170+
}
171+
return;
172+
}
173+
174+
const limit = pLimit(PUBLISH_FILTER_CONCURRENCY);
175+
await Promise.all(
176+
this.topics[topic].map((client) => limit(async () => {
163177
if (! (await filterUsers(client.adminUser)) ) {
164178
afLogger.trace(`Client not authorized to receive message ${topic} ${client.adminUser}`);
165-
continue;
179+
return;
166180
}
167-
}
168-
afLogger.trace(`Sending data to socket ${topic} ${JSON.stringify(data)}`);
169-
client.send(JSON.stringify({ type: 'message', topic, data }));
170-
}
181+
afLogger.trace(`Sending data to socket ${topic} ${JSON.stringify(data)}`);
182+
client.send(message);
183+
}))
184+
);
171185
}
172186

173187
}

adminforth/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@
109109
"listr2": "^8.2.5",
110110
"multer": "^2.1.1",
111111
"node-fetch": "^3.3.2",
112+
"p-limit": "^7.3.1",
112113
"pino": "^10.1.0",
113114
"pino-pretty": "^13.1.3",
114115
"private-ip": "^3.0.2",

adminforth/pnpm-lock.yaml

Lines changed: 17 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)