fix: enhance broadcast channel logic

This commit is contained in:
yassinedorbozgithub 2025-01-29 19:42:10 +01:00
parent 30c142f5b6
commit 961ca05d33
11 changed files with 211 additions and 284 deletions

View File

@ -21,13 +21,13 @@ import { Progress } from "@/app-components/displays/Progress";
import { useLogout } from "@/hooks/entities/auth-hooks"; import { useLogout } from "@/hooks/entities/auth-hooks";
import { useApiClient } from "@/hooks/useApiClient"; import { useApiClient } from "@/hooks/useApiClient";
import { CURRENT_USER_KEY, PUBLIC_PATHS } from "@/hooks/useAuth"; import { CURRENT_USER_KEY, PUBLIC_PATHS } from "@/hooks/useAuth";
import { useBroadcastChannel } from "@/hooks/useBroadcastChannel";
import { useTabUuid } from "@/hooks/useTabUuid";
import { useTranslate } from "@/hooks/useTranslate"; import { useTranslate } from "@/hooks/useTranslate";
import { RouterType } from "@/services/types"; import { RouterType } from "@/services/types";
import { IUser } from "@/types/user.types"; import { IUser } from "@/types/user.types";
import { getFromQuery } from "@/utils/URL"; import { getFromQuery } from "@/utils/URL";
import { useBroadcastChannel } from "./broadcast-channel.context";
export interface AuthContextValue { export interface AuthContextValue {
user: IUser | undefined; user: IUser | undefined;
isAuthenticated: boolean; isAuthenticated: boolean;
@ -109,11 +109,10 @@ export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => {
setIsReady(true); setIsReady(true);
}, []); }, []);
const tabUuidRef = useTabUuid(); const { subscribe } = useBroadcastChannel();
const { useBroadcast } = useBroadcastChannel();
useBroadcast("session", (e) => { subscribe((message) => {
if (e.data.value === "logout" && e.data.uuid !== tabUuidRef.current) { if (message.data === "logout") {
router.reload(); router.reload();
} }
}); });

View File

@ -6,43 +6,112 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/ */
import { createContext } from "react"; import {
createContext,
FC,
ReactNode,
useContext,
useEffect,
useMemo,
useRef,
} from "react";
import { useBroadcast } from "@/hooks/useBroadcastChannel"; import { useTabUuid } from "@/hooks/useTabUuid";
export interface IBroadcastChannelContext {
useBroadcast: (
channelName: string,
handleMessage?: (event: MessageEvent<BroadcastChannelData>) => void,
handleMessageError?: (event: MessageEvent<BroadcastChannelData>) => void,
) => (data: BroadcastChannelData) => void;
}
export type BroadcastChannelData = { export type BroadcastChannelData = {
uuid: string; tabId: string;
value: string | number | boolean | Record<string, unknown> | undefined | null; data: string | number | boolean | Record<string, unknown> | undefined | null;
}; };
export interface IBroadcastChannelProps { export interface IBroadcastChannelProps {
children?: React.ReactNode; channelName: string;
children?: ReactNode;
} }
export const BroadcastChannelContext = createContext<IBroadcastChannelContext>({ export const BroadcastChannelContext = createContext<{
useBroadcast: () => () => {}, subscribers: ((message: BroadcastChannelData) => void)[];
subscribe: (callback: (message: BroadcastChannelData) => void) => () => void;
postMessage: (message: BroadcastChannelData) => void;
}>({
subscribers: [],
subscribe: () => () => {},
postMessage: () => {},
}); });
export const BroadcastChannelProvider: React.FC<IBroadcastChannelProps> = ({ export const BroadcastChannelProvider: FC<IBroadcastChannelProps> = ({
channelName,
children, children,
}) => { }) => {
const channelRef = useRef<BroadcastChannel | null>(null);
const subscribersRef = useRef<Array<(message: BroadcastChannelData) => void>>(
[],
);
const tabUuidRef = useTabUuid();
useEffect(() => {
const channel = new BroadcastChannel(channelName);
channelRef.current = channel;
const handleMessage = (event: MessageEvent) => {
const { tabId, data } = event.data;
if (tabId === tabUuidRef.current) return;
subscribersRef.current.forEach((callback) => callback(data));
};
channel.addEventListener("message", handleMessage);
return () => {
channel.removeEventListener("message", handleMessage);
channel.close();
};
}, [channelName, tabUuidRef]);
const postMessage = (message: BroadcastChannelData) => {
channelRef.current?.postMessage({
tabId: tabUuidRef.current,
data: message,
});
};
const subscribe = (callback: (message: BroadcastChannelData) => void) => {
subscribersRef.current.push(callback);
return () => {
const index = subscribersRef.current.indexOf(callback);
if (index !== -1) {
subscribersRef.current.splice(index, 1);
}
};
};
const contextValue = useMemo(
() => ({
subscribers: subscribersRef.current,
subscribe,
postMessage,
}),
[],
);
return ( return (
<BroadcastChannelContext.Provider <BroadcastChannelContext.Provider value={contextValue}>
value={{
useBroadcast,
}}
>
{children} {children}
</BroadcastChannelContext.Provider> </BroadcastChannelContext.Provider>
); );
}; };
export default BroadcastChannelProvider; export default BroadcastChannelProvider;
export const useBroadcastChannel = () => {
const context = useContext(BroadcastChannelContext);
if (context === undefined) {
throw new Error(
"useBroadcastChannel must be used within a BroadcastChannelProvider",
);
}
return context;
};

View File

@ -9,6 +9,7 @@
import { useEffect } from "react"; import { useEffect } from "react";
import { useMutation, useQuery, useQueryClient } from "react-query"; import { useMutation, useQuery, useQueryClient } from "react-query";
import { useBroadcastChannel } from "@/contexts/broadcast-channel.context";
import { EntityType, TMutationOptions } from "@/services/types"; import { EntityType, TMutationOptions } from "@/services/types";
import { ILoginAttributes } from "@/types/auth/login.types"; import { ILoginAttributes } from "@/types/auth/login.types";
import { import {
@ -22,7 +23,6 @@ import { useSocket } from "@/websocket/socket-hooks";
import { useFind } from "../crud/useFind"; import { useFind } from "../crud/useFind";
import { useApiClient } from "../useApiClient"; import { useApiClient } from "../useApiClient";
import { CURRENT_USER_KEY, useAuth, useLogoutRedirection } from "../useAuth"; import { CURRENT_USER_KEY, useAuth, useLogoutRedirection } from "../useAuth";
import { useBroadcastChannel } from "../useBroadcastChannel";
import { useTabUuid } from "../useTabUuid"; import { useTabUuid } from "../useTabUuid";
import { useToast } from "../useToast"; import { useToast } from "../useToast";
import { useTranslate } from "../useTranslate"; import { useTranslate } from "../useTranslate";
@ -60,10 +60,8 @@ export const useLogout = (
const { logoutRedirection } = useLogoutRedirection(); const { logoutRedirection } = useLogoutRedirection();
const { toast } = useToast(); const { toast } = useToast();
const { t } = useTranslate(); const { t } = useTranslate();
const { useBroadcast } = useBroadcastChannel(); const { postMessage } = useBroadcastChannel();
const broadcastLogoutAcrossTabs = useBroadcast("session"); const uuid = useTabUuid();
const tabUuidRef = useTabUuid();
const tabUuid = tabUuidRef.current;
return useMutation({ return useMutation({
...options, ...options,
@ -74,10 +72,7 @@ export const useLogout = (
}, },
onSuccess: async () => { onSuccess: async () => {
queryClient.removeQueries([CURRENT_USER_KEY]); queryClient.removeQueries([CURRENT_USER_KEY]);
broadcastLogoutAcrossTabs({ postMessage({ data: "logout", tabId: uuid.current || "" });
value: "logout",
uuid: tabUuid || "",
});
await logoutRedirection(); await logoutRedirection();
toast.success(t("message.logout_success")); toast.success(t("message.logout_success"));
}, },

View File

@ -1,104 +0,0 @@
/*
* Copyright © 2024 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import * as React from "react";
import { useContext } from "react";
import {
BroadcastChannelContext,
BroadcastChannelData,
IBroadcastChannelContext,
} from "@/contexts/broadcast-channel.context";
export const useBroadcast = <
T extends BroadcastChannelData = BroadcastChannelData,
>(
channelName: string,
handleMessage?: (event: MessageEvent<T>) => void,
handleMessageError?: (event: MessageEvent<T>) => void,
): ((data: T) => void) => {
const channelRef = React.useRef<BroadcastChannel | null>(
typeof window !== "undefined" && "BroadcastChannel" in window
? new BroadcastChannel(channelName + "-channel")
: null,
);
useChannelEventListener(channelRef.current, "message", handleMessage);
useChannelEventListener(
channelRef.current,
"messageerror",
handleMessageError,
);
return (data: T) => channelRef.current?.postMessage(data);
};
export const useBroadcastState = <
T extends BroadcastChannelData = BroadcastChannelData,
>(
channelName: string,
initialState: T,
): [T, React.Dispatch<React.SetStateAction<T>>, boolean] => {
const [isPending, startTransition] = React.useTransition();
const [state, setState] = React.useState<T>(initialState);
const broadcast = useBroadcast<T>(channelName, (ev) => setState(ev.data));
const updateState: React.Dispatch<React.SetStateAction<T>> =
React.useCallback(
(input) => {
setState((prev) => {
const newState = typeof input === "function" ? input(prev) : input;
startTransition(() => broadcast(newState));
return newState;
});
},
[broadcast],
);
return [state, updateState, isPending];
};
const useChannelEventListener = <K extends keyof BroadcastChannelEventMap>(
channel: BroadcastChannel | null,
event: K,
handler?: (e: BroadcastChannelEventMap[K]) => void,
) => {
const callbackRef = React.useRef(handler);
if (callbackRef.current !== handler) {
callbackRef.current = handler;
}
React.useEffect(() => {
const callback = callbackRef.current;
if (!channel || !callback) {
return;
}
channel.addEventListener(event, callback);
return () => {
channel.close();
channel.removeEventListener(event, callback);
};
}, [channel, event]);
};
export const useBroadcastChannel = (): IBroadcastChannelContext => {
const context = useContext(BroadcastChannelContext);
if (!context) {
throw new Error(
"useBroadcastChannel must be used within an BroadcastChannelContext",
);
}
return context;
};

View File

@ -11,18 +11,20 @@ import { useRef } from "react";
import { generateId } from "@/utils/generateId"; import { generateId } from "@/utils/generateId";
const getOrCreateTabId = () => { const getOrCreateTabId = () => {
let tabId = sessionStorage.getItem("tab_uuid"); let storedTabId = sessionStorage.getItem("tab_uuid");
if (!tabId) { if (storedTabId) {
tabId = generateId(); return storedTabId;
sessionStorage.setItem("tab_uuid", tabId);
} }
return tabId; storedTabId = generateId();
sessionStorage.setItem("tab_uuid", storedTabId);
return storedTabId;
}; };
export const useTabUuid = () => { export const useTabUuid = () => {
const tabUuidRef = useRef<string | null>(getOrCreateTabId()); const tabUuidRef = useRef<string>(getOrCreateTabId());
return tabUuidRef; return tabUuidRef;
}; };

View File

@ -84,7 +84,7 @@ const App = ({ Component, pageProps }: TAppPropsWithLayout) => {
<QueryClientProvider client={queryClient}> <QueryClientProvider client={queryClient}>
<CssBaseline /> <CssBaseline />
<ApiClientProvider> <ApiClientProvider>
<BroadcastChannelProvider> <BroadcastChannelProvider channelName="main-channel">
<AuthProvider> <AuthProvider>
<PermissionProvider> <PermissionProvider>
<SettingsProvider> <SettingsProvider>

View File

@ -42,7 +42,7 @@ function UiChatWidget({
<SocketProvider> <SocketProvider>
<SettingsProvider> <SettingsProvider>
<ColorProvider> <ColorProvider>
<BroadcastChannelProvider> <BroadcastChannelProvider channelName="main-channel">
<WidgetProvider defaultScreen="chat"> <WidgetProvider defaultScreen="chat">
<ChatProvider <ChatProvider
defaultConnectionState={ConnectionState.connected} defaultConnectionState={ConnectionState.connected}

View File

@ -1,104 +0,0 @@
/*
* Copyright © 2024 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import * as React from "react";
import { useContext } from "react";
import {
BroadcastChannelContext,
BroadcastChannelData,
IBroadcastChannelContext,
} from "../providers/BroadcastChannelProvider";
export const useBroadcast = <
T extends BroadcastChannelData = BroadcastChannelData,
>(
channelName: string,
handleMessage?: (event: MessageEvent<T>) => void,
handleMessageError?: (event: MessageEvent<T>) => void,
): ((data: T) => void) => {
const channelRef = React.useRef<BroadcastChannel | null>(
typeof window !== "undefined" && "BroadcastChannel" in window
? new BroadcastChannel(channelName + "-channel")
: null,
);
useChannelEventListener(channelRef.current, "message", handleMessage);
useChannelEventListener(
channelRef.current,
"messageerror",
handleMessageError,
);
return (data: T) => channelRef.current?.postMessage(data);
};
export const useBroadcastState = <
T extends BroadcastChannelData = BroadcastChannelData,
>(
channelName: string,
initialState: T,
): [T, React.Dispatch<React.SetStateAction<T>>, boolean] => {
const [isPending, startTransition] = React.useTransition();
const [state, setState] = React.useState<T>(initialState);
const broadcast = useBroadcast<T>(channelName, (ev) => setState(ev.data));
const updateState: React.Dispatch<React.SetStateAction<T>> =
React.useCallback(
(input) => {
setState((prev) => {
const newState = typeof input === "function" ? input(prev) : input;
startTransition(() => broadcast(newState));
return newState;
});
},
[broadcast],
);
return [state, updateState, isPending];
};
const useChannelEventListener = <K extends keyof BroadcastChannelEventMap>(
channel: BroadcastChannel | null,
event: K,
handler?: (e: BroadcastChannelEventMap[K]) => void,
) => {
const callbackRef = React.useRef(handler);
if (callbackRef.current !== handler) {
callbackRef.current = handler;
}
React.useEffect(() => {
const callback = callbackRef.current;
if (!channel || !callback) {
return;
}
channel.addEventListener(event, callback);
return () => {
channel.close();
channel.removeEventListener(event, callback);
};
}, [channel, event]);
};
export const useBroadcastChannel = (): IBroadcastChannelContext => {
const context = useContext(BroadcastChannelContext);
if (!context) {
throw new Error(
"useBroadcastChannel must be used within an BroadcastChannelContext",
);
}
return context;
};

View File

@ -11,18 +11,20 @@ import { useRef } from "react";
import { generateId } from "../utils/generateId"; import { generateId } from "../utils/generateId";
const getOrCreateTabId = () => { const getOrCreateTabId = () => {
let tabId = sessionStorage.getItem("tab_uuid"); let storedTabId = sessionStorage.getItem("tab_uuid");
if (!tabId) { if (storedTabId) {
tabId = generateId(); return storedTabId;
sessionStorage.setItem("tab_uuid", tabId);
} }
return tabId; storedTabId = generateId();
sessionStorage.setItem("tab_uuid", storedTabId);
return storedTabId;
}; };
export const useTabUuid = () => { export const useTabUuid = () => {
const tabUuidRef = useRef<string | null>(getOrCreateTabId()); const tabUuidRef = useRef<string>(getOrCreateTabId());
return tabUuidRef; return tabUuidRef;
}; };

View File

@ -6,44 +6,114 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/ */
import { createContext, ReactNode } from "react"; import {
createContext,
FC,
ReactNode,
useContext,
useEffect,
useMemo,
useRef,
} from "react";
import { useBroadcast } from "../hooks/useBroadcastChannel"; import { useTabUuid } from "../hooks/useTabUuid";
export interface IBroadcastChannelContext {
useBroadcast: (
channelName: string,
handleMessage?: (event: MessageEvent<BroadcastChannelData>) => void,
handleMessageError?: (event: MessageEvent<BroadcastChannelData>) => void,
) => (data: BroadcastChannelData) => void;
}
export type BroadcastChannelData = { export type BroadcastChannelData = {
uuid: string; tabId: string;
value: string | number | boolean | Record<string, unknown> | undefined | null; data: string | number | boolean | Record<string, unknown> | undefined | null;
}; };
export interface IBroadcastChannelProps { export interface IBroadcastChannelProps {
channelName: string;
children?: ReactNode; children?: ReactNode;
} }
export const BroadcastChannelContext = createContext<IBroadcastChannelContext>({ export const BroadcastChannelContext = createContext<{
useBroadcast: () => () => {}, subscribers: ((message: BroadcastChannelData) => void)[];
subscribe: (callback: (message: BroadcastChannelData) => void) => () => void;
postMessage: (message: BroadcastChannelData) => void;
}>({
subscribers: [],
subscribe: () => () => {},
postMessage: () => {},
}); });
export const BroadcastChannelProvider: React.FC<IBroadcastChannelProps> = ({ export const BroadcastChannelProvider: FC<IBroadcastChannelProps> = ({
// eslint-disable-next-line react/prop-types
channelName,
// eslint-disable-next-line react/prop-types // eslint-disable-next-line react/prop-types
children, children,
}) => { }) => {
const channelRef = useRef<BroadcastChannel | null>(null);
const subscribersRef = useRef<Array<(message: BroadcastChannelData) => void>>(
[],
);
const tabUuidRef = useTabUuid();
useEffect(() => {
const channel = new BroadcastChannel(channelName);
channelRef.current = channel;
const handleMessage = (event: MessageEvent) => {
const { tabId, data } = event.data;
if (tabId === tabUuidRef.current) return;
subscribersRef.current.forEach((callback) => callback(data));
};
channel.addEventListener("message", handleMessage);
return () => {
channel.removeEventListener("message", handleMessage);
channel.close();
};
}, [channelName, tabUuidRef]);
const postMessage = (message: BroadcastChannelData) => {
channelRef.current?.postMessage({
tabId: tabUuidRef.current,
data: message,
});
};
const subscribe = (callback: (message: BroadcastChannelData) => void) => {
subscribersRef.current.push(callback);
return () => {
const index = subscribersRef.current.indexOf(callback);
if (index !== -1) {
subscribersRef.current.splice(index, 1);
}
};
};
const contextValue = useMemo(
() => ({
subscribers: subscribersRef.current,
subscribe,
postMessage,
}),
[],
);
return ( return (
<BroadcastChannelContext.Provider <BroadcastChannelContext.Provider value={contextValue}>
value={{
useBroadcast,
}}
>
{children} {children}
</BroadcastChannelContext.Provider> </BroadcastChannelContext.Provider>
); );
}; };
export default BroadcastChannelProvider; export default BroadcastChannelProvider;
export const useBroadcastChannel = () => {
const context = useContext(BroadcastChannelContext);
if (context === undefined) {
throw new Error(
"useBroadcastChannel must be used within a BroadcastChannelProvider",
);
}
return context;
};

View File

@ -16,8 +16,6 @@ import React, {
useState, useState,
} from "react"; } from "react";
import { useBroadcastChannel } from "../hooks/useBroadcastChannel";
import { useTabUuid } from "../hooks/useTabUuid";
import { StdEventType } from "../types/chat-io-messages.types"; import { StdEventType } from "../types/chat-io-messages.types";
import { import {
Direction, Direction,
@ -31,6 +29,7 @@ import {
} from "../types/message.types"; } from "../types/message.types";
import { ConnectionState, OutgoingMessageState } from "../types/state.types"; import { ConnectionState, OutgoingMessageState } from "../types/state.types";
import { useBroadcastChannel } from "./BroadcastChannelProvider";
import { useConfig } from "./ConfigProvider"; import { useConfig } from "./ConfigProvider";
import { useSettings } from "./SettingsProvider"; import { useSettings } from "./SettingsProvider";
import { useSocket, useSubscribe } from "./SocketProvider"; import { useSocket, useSubscribe } from "./SocketProvider";
@ -453,11 +452,10 @@ const ChatProvider: React.FC<{
setMessage, setMessage,
handleSubscription, handleSubscription,
}; };
const tabUuidRef = useTabUuid(); const { subscribe } = useBroadcastChannel();
const { useBroadcast } = useBroadcastChannel();
useBroadcast("session", ({ data }) => { subscribe(({ data }) => {
if (data.value === "logout" && data.uuid !== tabUuidRef.current) { if (data === "logout") {
socketCtx.socket.disconnect(); socketCtx.socket.disconnect();
} }
}); });