chore: simplify events backend and signal hook

Signed-off-by: Heikki Hellgren <heikki.hellgren@op.fi>
This commit is contained in:
Heikki Hellgren
2023-12-14 15:47:29 +02:00
parent 3b6b645d93
commit 0b21422604
2 changed files with 23 additions and 26 deletions
+16 -22
View File
@@ -37,7 +37,6 @@ import { LoggerService } from '@backstage/backend-plugin-api';
/** @public */
export class SignalService implements EventSubscriber {
private readonly serverId: string;
private connections: Map<string, SignalConnection> = new Map<
string,
SignalConnection
@@ -58,7 +57,6 @@ export class SignalService implements EventSubscriber {
identity: this.identity,
} = options);
this.serverId = uuid();
this.server = new WebSocketServer({
noServer: true,
clientTracking: false,
@@ -199,6 +197,21 @@ export class SignalService implements EventSubscriber {
return;
}
// If there is event broker, use that to publish the message to
// all signal services, including this one.
if (this.eventBroker && !brokedEvent) {
await this.eventBroker.publish({
topic: 'signals',
eventPayload: {
recipients,
message,
topic,
},
});
return;
}
// Actual websocket message sending
this.connections.forEach(conn => {
if (!conn.subscriptions.has(topic)) {
return;
@@ -217,29 +230,10 @@ export class SignalService implements EventSubscriber {
conn.ws.send(jsonMessage);
});
// If this event has not been broadcasted to all servers, then use
// EventBroker to do that
if (this.eventBroker && !brokedEvent) {
await this.eventBroker.publish({
topic: 'signals',
eventPayload: {
recipients,
message,
topic,
},
metadata: { server: this.serverId },
});
}
}
async onEvent(params: EventParams<SignalEventBrokerPayload>): Promise<void> {
const { eventPayload, metadata } = params;
// Discard message from same server to prevent duplicate messages
if (!metadata?.server || metadata.server === this.serverId) {
return;
}
const { eventPayload } = params;
if (
!eventPayload?.recipients ||
!eventPayload.topic ||
@@ -14,7 +14,7 @@
* limitations under the License.
*/
import { signalApiRef } from '../api';
import { useApi } from '@backstage/core-plugin-api';
import { useApiHolder } from '@backstage/core-plugin-api';
import { JsonObject } from '@backstage/types';
import { useEffect, useState } from 'react';
@@ -23,10 +23,13 @@ export const useSignalApi = (
topic: string,
onMessage: (message: JsonObject) => void,
) => {
const signals = useApi(signalApiRef);
const apiHolder = useApiHolder();
// Use apiHolder instead useApi in case signalApi is not available in the
// backstage instance this is used
const signals = apiHolder.get(signalApiRef);
const [subscription, setSubscription] = useState<null | string>(null);
useEffect(() => {
if (!subscription) {
if (signals && !subscription) {
const sub = signals.subscribe(topic, onMessage);
setSubscription(sub);
}
@@ -34,7 +37,7 @@ export const useSignalApi = (
useEffect(() => {
return () => {
if (subscription) {
if (signals && subscription) {
signals.unsubscribe(subscription);
}
};