Spaces:
Running
Running
Commit ·
e44f847
1
Parent(s): 0df49d6
feat(sync): replace polling-based WebRTC with high-performance unified SignalR-bridge UDP WebRTC sync
Browse filesFiles changed (4)
7 unmodified lines8910111213563 unmodified lines577578579580581582793 unmodified lines137613771378137913801381698 unmodified lines20802081208220832084208533 unmodified lines211921202121212221232124899 unmodified lines302430253026302730283029146 unmodified lines317631773178317931803181318231833184318531863187318831893190319180 unmodified lines327232733274327532763277128 unmodified lines34063407340834093410341113 unmodified lines34253426342734283429343035 unmodified lines34663467346834693470347190 unmodified lines35623563356435653566356720 unmodified lines3588358935903591359235937 unmodified lines"name": "flowweb","version": "0.0.0","dependencies": {"@react-oauth/google": "^0.13.5","@xyflow/react": "^12.10.2","axios": "^1.16.1",563 unmodified lines"@jridgewell/sourcemap-codec": "^1.4.14"}},"node_modules/@napi-rs/wasm-runtime": {"version": "1.1.4","resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.4.tgz",793 unmodified lines"d3-zoom": "^3.0.0"}},"node_modules/acorn": {"version": "8.16.0","resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",698 unmodified lines"node": ">=0.10.0"}},"node_modules/fast-deep-equal": {"version": "3.1.3","resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",33 unmodified lines}}},"node_modules/file-entry-cache": {"version": "8.0.0","resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",899 unmodified lines"dev": true,"license": "MIT"},"node_modules/node-releases": {"version": "2.0.38","resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.38.tgz",146 unmodified lines"node": ">=10"}},"node_modules/punycode": {"version": "2.3.1","resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz","integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==","dev": true,"license": "MIT","engines": {"node": ">=6"}},"node_modules/react": {"version": "19.2.6","resolved": "https://registry.npmjs.org/react/-/react-19.2.6.tgz",80 unmodified lines"react-dom": ">=18"}},"node_modules/rolldown": {"version": "1.0.0-rc.18","resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-rc.18.tgz",128 unmodified lines"url": "https://github.com/sponsors/SuperchupuDev"}},"node_modules/tslib": {"version": "2.8.1","resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",13 unmodified lines"node": ">= 0.8.0"}},"node_modules/update-browserslist-db": {"version": "1.2.3","resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",35 unmodified lines"punycode": "^2.1.0"}},"node_modules/use-sync-external-store": {"version": "1.6.0","resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz",90 unmodified lines"node": ">=0.10.0"}},"node_modules/which": {"version": "2.0.2","resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",20 unmodified lines"node": ">=0.10.0"}},"node_modules/yallist": {"version": "3.1.1","resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",7 unmodified lines891011121314563 unmodified lines578579580581582583584585586587588589590591592593594595596793 unmodified lines139013911392139313941395139613971398139914001401140214031404140514061407698 unmodified lines21062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212933 unmodified lines2163216421652166216721682169217021712172217321742175217621772178899 unmodified lines30783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103146 unmodified lines32503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328280 unmodified lines336333643365336633673368336933703371337233733374128 unmodified lines35033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352913 unmodified lines35433544354535463547354835493550355135523553355435553556355735 unmodified lines359335943595359635973598359936003601360236033604360536063607360890 unmodified lines369937003701370237033704370537063707370837093710371137123713371437153716371737183719372020 unmodified lines3741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637677 unmodified lines"name": "flowweb","version": "0.0.0","dependencies": {"@microsoft/signalr": "^10.0.0","@react-oauth/google": "^0.13.5","@xyflow/react": "^12.10.2","axios": "^1.16.1",563 unmodified lines"@jridgewell/sourcemap-codec": "^1.4.14"}},"node_modules/@microsoft/signalr": {"version": "10.0.0","resolved": "https://registry.npmjs.org/@microsoft/signalr/-/signalr-10.0.0.tgz","integrity": "sha512-0BRqz/uCx3JdrOqiqgFhih/+hfTERaUfCZXFB52uMaZJrKaPRzHzMuqVsJC/V3pt7NozcNXGspjKiQEK+X7P2w==","license": "MIT","dependencies": {"abort-controller": "^3.0.0","eventsource": "^2.0.2","fetch-cookie": "^2.0.3","node-fetch": "^2.6.7","ws": "^7.5.10"}},"node_modules/@napi-rs/wasm-runtime": {"version": "1.1.4","resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.4.tgz",793 unmodified lines"d3-zoom": "^3.0.0"}},"node_modules/abort-controller": {"version": "3.0.0","resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz","integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==","license": "MIT","dependencies": {"event-target-shim": "^5.0.0"},"engines": {"node": ">=6.5"}},"node_modules/acorn": {"version": "8.16.0","resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",698 unmodified lines"node": ">=0.10.0"}},"node_modules/event-target-shim": {"version": "5.0.1","resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz","integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==","license": "MIT","engines": {"node": ">=6"}},"node_modules/eventsource": {"version": "2.0.2","resolved": "https://registry.npmjs.org/eventsource/-/eventsource-2.0.2.tgz","integrity": "sha512-IzUmBGPR3+oUG9dUeXynyNmf91/3zUSJg1lCktzKw47OXuhco54U3r9B7O4XX+Rb1Itm9OZ2b0RkTs10bICOxA==","license": "MIT","engines": {"node": ">=12.0.0"}},"node_modules/fast-deep-equal": {"version": "3.1.3","resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",33 unmodified lines}}},"node_modules/fetch-cookie": {"version": "2.2.0","resolved": "https://registry.npmjs.org/fetch-cookie/-/fetch-cookie-2.2.0.tgz","integrity": "sha512-h9AgfjURuCgA2+2ISl8GbavpUdR+WGAM2McW/ovn4tVccegp8ZqCKWSBR8uRdM8dDNlx5WdKRWxBYUwteLDCNQ==","license": "Unlicense","dependencies": {"set-cookie-parser": "^2.4.8","tough-cookie": "^4.0.0"}},"node_modules/file-entry-cache": {"version": "8.0.0","resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",899 unmodified lines"dev": true,"license": "MIT"},"node_modules/node-fetch": {"version": "2.7.0","resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz","integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==","license": "MIT","dependencies": {"whatwg-url": "^5.0.0"},"engines": {"node": "4.x || >=6.0.0"},"peerDependencies": {"encoding": "^0.1.0"},"peerDependenciesMeta": {"encoding": {"optional": true}}},"node_modules/node-releases": {"version": "2.0.38","resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.38.tgz",146 unmodified lines"node": ">=10"}},"node_modules/psl": {"version": "1.15.0","resolved": "https://registry.npmjs.org/psl/-/psl-1.15.0.tgz","integrity": "sha512-JZd3gMVBAVQkSs6HdNZo9Sdo0LNcQeMNP3CozBJb3JYC/QUYZTnKxP+f8oWRX4rHP5EurWxqAHTSwUCjlNKa1w==","license": "MIT","dependencies": {"punycode": "^2.3.1"},"funding": {"url": "https://github.com/sponsors/lupomontero"}},"node_modules/punycode": {"version": "2.3.1","resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz","integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==","license": "MIT","engines": {"node": ">=6"}},"node_modules/querystringify": {"version": "2.2.0","resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz","integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==","license": "MIT"},"node_modules/react": {"version": "19.2.6","resolved": "https://registry.npmjs.org/react/-/react-19.2.6.tgz",80 unmodified lines"react-dom": ">=18"}},"node_modules/requires-port": {"version": "1.0.0","resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz","integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==","license": "MIT"},"node_modules/rolldown": {"version": "1.0.0-rc.18","resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-rc.18.tgz",128 unmodified lines"url": "https://github.com/sponsors/SuperchupuDev"}},"node_modules/tough-cookie": {"version": "4.1.4","resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.4.tgz","integrity": "sha512-Loo5UUvLD9ScZ6jh8beX1T6sO1w2/MpCRpEP7V280GKMVUQ0Jzar2U3UJPsrdbziLEMMhu3Ujnq//rhiFuIeag==","license": "BSD-3-Clause","dependencies": {"psl": "^1.1.33","punycode": "^2.1.1","universalify": "^0.2.0","url-parse": "^1.5.3"},"engines": {"node": ">=6"}},"node_modules/tr46": {"version": "0.0.3","resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz","integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==","license": "MIT"},"node_modules/tslib": {"version": "2.8.1","resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",13 unmodified lines"node": ">= 0.8.0"}},"node_modules/universalify": {"version": "0.2.0","resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz","integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==","license": "MIT","engines": {"node": ">= 4.0.0"}},"node_modules/update-browserslist-db": {"version": "1.2.3","resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",35 unmodified lines"punycode": "^2.1.0"}},"node_modules/url-parse": {"version": "1.5.10","resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz","integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==","license": "MIT","dependencies": {"querystringify": "^2.1.1","requires-port": "^1.0.0"}},"node_modules/use-sync-external-store": {"version": "1.6.0","resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz",90 unmodified lines"node": ">=0.10.0"}},"node_modules/webidl-conversions": {"version": "3.0.1","resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz","integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==","license": "BSD-2-Clause"},"node_modules/whatwg-url": {"version": "5.0.0","resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz","integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==","license": "MIT","dependencies": {"tr46": "~0.0.3","webidl-conversions": "^3.0.0"}},"node_modules/which": {"version": "2.0.2","resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",20 unmodified lines"node": ">=0.10.0"}},"node_modules/ws": {"version": "7.5.10","resolved": "https://registry.npmjs.org/ws/-/ws-7.5.10.tgz","integrity": "sha512-+dbF1tHwZpXcbOJdVOkzLDxZP1ailvSxM6ZweXTegylPny803bFhA+vqBYw4s31NSAk4S2Qz+AKXK9a4wkdjcQ==","license": "MIT","engines": {"node": ">=8.3.0"},"peerDependencies": {"bufferutil": "^4.0.1","utf-8-validate": "^5.0.2"},"peerDependenciesMeta": {"bufferutil": {"optional": true},"utf-8-validate": {"optional": true}}},"node_modules/yallist": {"version": "3.1.1","resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
9 unmodified lines1011121314159 unmodified lines"preview": "vite preview"},"dependencies": {"@react-oauth/google": "^0.13.5","@xyflow/react": "^12.10.2","axios": "^1.16.1",9 unmodified lines101112131415169 unmodified lines"preview": "vite preview"},"dependencies": {"@microsoft/signalr": "^10.0.0","@react-oauth/google": "^0.13.5","@xyflow/react": "^12.10.2","axios": "^1.16.1",
10 unmodified lines11121314151617228 unmodified lines24624724824925025125225310 unmodified linesgetIncomers,useReactFlow,} from '@xyflow/react';import { useWebRTC } from './useWebRTC';export const getConditionSourceHandle = (sourceNode, condition) => {if (!sourceNode) return null;228 unmodified lines}}, [setNodes, setEdges, updateNodeDataCallback]);// Hook up WebRTC Data Channelsconst { peers, activeUsers, broadcastMessage } = useWebRTC(projectId, user, onRemoteMessage);// Sync activeUsers to the Ref for safe use inside onRemoteMessage callbacks without dependency cyclesuseEffect(() => {10 unmodified lines11121314151617228 unmodified lines24624724824925025125225310 unmodified linesgetIncomers,useReactFlow,} from '@xyflow/react';import { useSignalR } from './useSignalR';export const getConditionSourceHandle = (sourceNode, condition) => {if (!sourceNode) return null;228 unmodified lines}}, [setNodes, setEdges, updateNodeDataCallback]);// Hook up SignalR Hub connection for real-time collaborationconst { peers, activeUsers, broadcastMessage } = useSignalR(projectId, user, onRemoteMessage);// Sync activeUsers to the Ref for safe use inside onRemoteMessage callbacks without dependency cyclesuseEffect(() => {
12345678910111213143 unmodified lines181920212223242526272829303132333414 unmodified lines49505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210 unmodified lines11311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015122 unmodified lines1741751761771781791801811821831841854 unmodified lines1901911921931941951964 unmodified lines2012022032042052062073 unmodified lines211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352import { useEffect, useRef, useState } from 'react';import axios from 'axios';export const useWebRTC = (projectId, user, onRemoteMessage) => {const [peers, setPeers] = useState({});const [activeUsers, setActiveUsers] = useState([]);const peerConnectionsRef = useRef({}); // userId -> RTCPeerConnectionconst dataChannelsRef = useRef({}); // userId -> RTCDataChannelconst activeUsersRef = useRef([]);const pendingCandidatesRef = useRef({}); // userId -> RTCIceCandidate[]const onRemoteMessageRef = useRef(onRemoteMessage);useEffect(() => {3 unmodified linesconst API_URL = import.meta.env.VITE_API_URL;const token = localStorage.getItem('token') || '';// Standard RTC Configuration with public Google STUN servers for local/NAT traversingconst rtcConfig = {iceServers: [// Standard Google STUN{ urls: 'stun:stun.l.google.com:19302' },{ urls: 'stun:stun1.l.google.com:19302' },{ urls: 'stun:stun2.l.google.com:19302' },{ urls: 'stun:stun3.l.google.com:19302' },{ urls: 'stun:stun4.l.google.com:19302' },// OpenRelay Public STUN/TURN (relays WebRTC traffic through firewalls/NATs){ urls: 'stun:openrelay.metered.ca:80' },{urls: 'turn:openrelay.metered.ca:80',14 unmodified linesiceCandidatePoolSize: 10};// Helper to get authenticated headersconst getHeaders = () => ({headers: {Authorization: `Bearer ${token}`}});// --- 1. Heartbeat Presence & Poll Online Users ---useEffect(() => {if (!projectId || !user || !user.id || !token) return;const runPresenceCycle = async () => {try {// Register local presenceawait axios.post(`${API_URL}/sync/${projectId}/presence`, {}, getHeaders());// Get active users in the projectconst res = await axios.get(`${API_URL}/sync/${projectId}/presence`, getHeaders());const onlineUsers = res.data.filter(u => u.userId !== user.id); // exclude selfsetActiveUsers(onlineUsers);activeUsersRef.current = onlineUsers;// Check if any peer has gone offline and clean upconst onlineUserIds = new Set(onlineUsers.map(u => u.userId));Object.keys(peerConnectionsRef.current).forEach(peerId => {if (!onlineUserIds.has(peerId)) {console.log(`Peer ${peerId} went offline. Cleaning up.`);cleanupPeer(peerId);}});} catch (err) {console.error('Error in WebRTC presence cycle', err);}};// Run immediately and then every 3 secondsrunPresenceCycle();const interval = setInterval(runPresenceCycle, 3000);return () => {clearInterval(interval);// Clean up all peer connections on unmountObject.keys(peerConnectionsRef.current).forEach(cleanupPeer);};}, [projectId, user, token, API_URL]);// --- 2. Clean Up Specific Peer Connection ---const cleanupPeer = (peerId) => {if (dataChannelsRef.current[peerId]) {try { dataChannelsRef.current[peerId].close(); } catch (e) {}10 unmodified lines});};// --- 3. Send Signal to Peer via Backend ---const sendSignal = async (receiverId, type, data) => {try {await axios.post(`${API_URL}/sync/${projectId}/signal`, {receiverId,type,data: JSON.stringify(data)}, getHeaders());} catch (err) {console.error(`Failed to send signal ${type} to ${receiverId}`, err);}};// --- 4. Setup Local RTCPeerConnection Event Handlers ---const createPeerConnection = (peerId, info) => {if (peerConnectionsRef.current[peerId]) {return peerConnectionsRef.current[peerId];}console.log(`Creating RTCPeerConnection for peer ${peerId}`);const pc = new RTCPeerConnection(rtcConfig);peerConnectionsRef.current[peerId] = pc;// Handle ICE Candidatespc.onicecandidate = (event) => {if (event.candidate) {sendSignal(peerId, 'candidate', event.candidate);}};// Monitor Connection Statepc.onconnectionstatechange = () => {console.log(`Connection state with peer ${peerId}: ${pc.connectionState}`);if (pc.connectionState === 'disconnected' || pc.connectionState === 'failed') {cleanupPeer(peerId);} else {22 unmodified linesreturn pc;};// --- 5. Configure Data Channel Events ---const setupDataChannel = (peerId, channel) => {dataChannelsRef.current[peerId] = channel;channel.onopen = () => {console.log(`RTC Data Channel opened with peer ${peerId}`);setPeers(prev => ({...prev,[peerId]: {4 unmodified lines};channel.onclose = () => {console.log(`RTC Data Channel closed with peer ${peerId}`);setPeers(prev => ({...prev,[peerId]: {4 unmodified lines};channel.onerror = (err) => {console.error(`RTC Data Channel error with peer ${peerId}`, err);};channel.onmessage = (event) => {3 unmodified linesonRemoteMessageRef.current(peerId, message);}} catch (e) {console.error('Failed to parse WebRTC incoming message', e);}};};// --- 6. Active Connection Initiator Logic ---// A tie-breaker initiates connection: the user with the lexicographically higher ID initiates!useEffect(() => {if (activeUsers.length === 0 || !user || !user.id) return;activeUsers.forEach(async (peer) => {const peerId = peer.userId;// If we are the initiator (our ID is greater) and connection doesn't exist yetif (user.id > peerId && !peerConnectionsRef.current[peerId]) {console.log(`Initiating WebRTC connection to peer ${peerId}`);const pc = createPeerConnection(peerId, peer);// Create the outgoing P2P Data Channelconst channel = pc.createDataChannel('taskflow-sync-channel', {ordered: true});setupDataChannel(peerId, channel);try {const offer = await pc.createOffer();await pc.setLocalDescription(offer);await sendSignal(peerId, 'offer', offer);} catch (err) {console.error(`Failed to create offer for ${peerId}`, err);}}});}, [activeUsers, user]);// --- 7. Poll Backend Signaling for Incoming Signaling Packets ---useEffect(() => {if (!projectId || !user || !user.id || !token) return;const processPendingCandidates = async (peerId, pc) => {const candidates = pendingCandidatesRef.current[peerId];if (candidates && candidates.length > 0) {console.log(`Applying ${candidates.length} queued ICE candidates for peer ${peerId}`);while (candidates.length > 0) {const cand = candidates.shift();try {await pc.addIceCandidate(new RTCIceCandidate(cand));} catch (e) {console.error('Error adding queued ICE candidate', e);}}}};const pollSignals = async () => {try {const res = await axios.get(`${API_URL}/sync/${projectId}/signal`, getHeaders());const signals = res.data;for (const signal of signals) {const peerId = signal.senderId;const type = signal.type;// Guard: Never process own signalsif (peerId === user.id) {continue;}const signalData = JSON.parse(signal.data);const peerInfo = activeUsersRef.current.find(u => u.userId === peerId);if (type === 'offer') {console.log(`Received WebRTC SDP Offer from peer ${peerId}`);const pc = createPeerConnection(peerId, peerInfo);// Set up receiving Data Channel when offeredpc.ondatachannel = (event) => {setupDataChannel(peerId, event.channel);};await pc.setRemoteDescription(new RTCSessionDescription(signalData));await processPendingCandidates(peerId, pc);const answer = await pc.createAnswer();await pc.setLocalDescription(answer);await sendSignal(peerId, 'answer', answer);}else if (type === 'answer') {console.log(`Received WebRTC SDP Answer from peer ${peerId}`);const pc = peerConnectionsRef.current[peerId];if (pc) {await pc.setRemoteDescription(new RTCSessionDescription(signalData));await processPendingCandidates(peerId, pc);}}else if (type === 'candidate') {console.log(`Received WebRTC ICE Candidate from peer ${peerId}`);const pc = peerConnectionsRef.current[peerId];if (pc && pc.remoteDescription) {try {await pc.addIceCandidate(new RTCIceCandidate(signalData));} catch (e) {console.error('Error adding received ICE candidate', e);}} else {if (!pendingCandidatesRef.current[peerId]) {pendingCandidatesRef.current[peerId] = [];}pendingCandidatesRef.current[peerId].push(signalData);console.log(`Queued ICE candidate for peer ${peerId} (remoteDescription is null)`);}}}} catch (err) {console.error('Error polling WebRTC signals', err);}};// Poll signals aggressively every 1.5 seconds for instant room joinsconst interval = setInterval(pollSignals, 1500);return () => clearInterval(interval);}, [projectId, user, token, API_URL]);// --- 8. Broadcast Message to All Connected Peers ---const broadcastMessage = (msg) => {const payload = JSON.stringify(msg);Object.keys(dataChannelsRef.current).forEach(peerId => {const channel = dataChannelsRef.current[peerId];if (channel && channel.readyState === 'open') {try {channel.send(payload);} catch (e) {console.error(`Failed to broadcast message to peer ${peerId}`, e);}}});};return {1234567891011121314153 unmodified lines19202122232425262728293031323314 unmodified lines4849505152535410 unmodified lines656667686970717273747576777879808182838485868788899091929394959697989910022 unmodified lines1231241251261271281291301311321331344 unmodified lines1391401411421431441454 unmodified lines1501511521531541551563 unmodified lines160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442import { useEffect, useRef, useState } from 'react';import * as signalR from '@microsoft/signalr';export const useSignalR = (projectId, user, onRemoteMessage) => {const [peers, setPeers] = useState({});const [activeUsers, setActiveUsers] = useState([]);const connectionRef = useRef(null);const peerConnectionsRef = useRef({}); // userId -> RTCPeerConnectionconst dataChannelsRef = useRef({}); // userId -> RTCDataChannelconst pendingCandidatesRef = useRef({}); // userId -> RTCIceCandidate[]const activeUsersRef = useRef([]);const onRemoteMessageRef = useRef(onRemoteMessage);useEffect(() => {3 unmodified linesconst API_URL = import.meta.env.VITE_API_URL;const token = localStorage.getItem('token') || '';// Standard RTC Configuration with public Google STUN and openrelay TURN servers for robust NAT traversingconst rtcConfig = {iceServers: [{ urls: 'stun:stun.l.google.com:19302' },{ urls: 'stun:stun1.l.google.com:19302' },{ urls: 'stun:stun2.l.google.com:19302' },{ urls: 'stun:stun3.l.google.com:19302' },{ urls: 'stun:stun4.l.google.com:19302' },{ urls: 'stun:openrelay.metered.ca:80' },{urls: 'turn:openrelay.metered.ca:80',14 unmodified linesiceCandidatePoolSize: 10};// Clean Up Specific Peer Connectionconst cleanupPeer = (peerId) => {if (dataChannelsRef.current[peerId]) {try { dataChannelsRef.current[peerId].close(); } catch (e) {}10 unmodified lines});};// Send WebRTC Signaling Packet to Peer via SignalR BoardHubconst sendSignal = async (connection, receiverId, type, data) => {if (!connection || connection.state !== signalR.HubConnectionState.Connected) return;try {await connection.invoke('SendSignal', projectId, receiverId, type, JSON.stringify(data));} catch (err) {console.error(`[WebRTC] Failed to send signal ${type} to ${receiverId}`, err);}};// Setup Local RTCPeerConnection Event Handlersconst createPeerConnection = (connection, peerId, info) => {if (peerConnectionsRef.current[peerId]) {return peerConnectionsRef.current[peerId];}console.log(`[WebRTC] Creating RTCPeerConnection for peer ${peerId}`);const pc = new RTCPeerConnection(rtcConfig);peerConnectionsRef.current[peerId] = pc;// Handle ICE Candidatespc.onicecandidate = (event) => {if (event.candidate) {sendSignal(connection, peerId, 'candidate', event.candidate);}};// Monitor Connection Statepc.onconnectionstatechange = () => {console.log(`[WebRTC] Connection state with peer ${peerId}: ${pc.connectionState}`);if (pc.connectionState === 'disconnected' || pc.connectionState === 'failed') {cleanupPeer(peerId);} else {22 unmodified linesreturn pc;};// Configure Data Channel Eventsconst setupDataChannel = (peerId, channel) => {dataChannelsRef.current[peerId] = channel;channel.onopen = () => {console.log(`[WebRTC] RTC Data Channel opened with peer ${peerId}`);setPeers(prev => ({...prev,[peerId]: {4 unmodified lines};channel.onclose = () => {console.log(`[WebRTC] RTC Data Channel closed with peer ${peerId}`);setPeers(prev => ({...prev,[peerId]: {4 unmodified lines};channel.onerror = (err) => {console.error(`[WebRTC] RTC Data Channel error with peer ${peerId}`, err);};channel.onmessage = (event) => {3 unmodified linesonRemoteMessageRef.current(peerId, message);}} catch (e) {console.error('[WebRTC] Failed to parse incoming message', e);}};};useEffect(() => {if (!projectId || !user || !user.id || !token) return;const hubUrl = API_URL.replace(/\/api$/, '') + '/hubs/board';console.log('[SignalR] Connecting to hub at:', hubUrl);const connection = new signalR.HubConnectionBuilder().withUrl(hubUrl, {accessTokenFactory: () => token,skipNegotiation: true,transport: signalR.HttpTransportType.WebSockets}).withAutomaticReconnect().build();connectionRef.current = connection;// Presence updatesconnection.on('PresenceUpdated', (uniquePresences) => {console.log('[SignalR] Presence updated:', uniquePresences);const onlineUsers = uniquePresences.filter(u => u.userId !== user.id);setActiveUsers(onlineUsers);activeUsersRef.current = onlineUsers;// 1. Clean up offline peersconst onlineUserIds = new Set(onlineUsers.map(u => u.userId));Object.keys(peerConnectionsRef.current).forEach(peerId => {if (!onlineUserIds.has(peerId)) {console.log(`[WebRTC] Peer ${peerId} went offline. Cleaning up.`);cleanupPeer(peerId);}});// 2. Initiate connection with peers where we are the initiator (tie-breaker: our user ID is lexicographically greater)onlineUsers.forEach(async (peer) => {const peerId = peer.userId;if (user.id > peerId && !peerConnectionsRef.current[peerId]) {console.log(`[WebRTC] Initiating connection to peer ${peerId}`);const pc = createPeerConnection(connection, peerId, peer);// Create outgoing data channelconst channel = pc.createDataChannel('taskflow-sync-channel', {ordered: true});setupDataChannel(peerId, channel);try {const offer = await pc.createOffer();await pc.setLocalDescription(offer);await sendSignal(connection, peerId, 'offer', offer);} catch (err) {console.error(`[WebRTC] Failed to create offer for ${peerId}`, err);}}});});// WebRTC Signaling Bridge receiverconnection.on('ReceiveSignal', async (senderUserId, type, dataJson) => {try {const signalData = JSON.parse(dataJson);const peerInfo = activeUsersRef.current.find(u => u.userId === senderUserId);const processPendingCandidates = async (peerId, pc) => {const candidates = pendingCandidatesRef.current[peerId];if (candidates && candidates.length > 0) {console.log(`[WebRTC] Applying ${candidates.length} queued ICE candidates for peer ${peerId}`);while (candidates.length > 0) {const cand = candidates.shift();try {await pc.addIceCandidate(new RTCIceCandidate(cand));} catch (e) {console.error('[WebRTC] Error adding queued ICE candidate', e);}}}};if (type === 'offer') {console.log(`[WebRTC] Received SDP Offer from peer ${senderUserId}`);const pc = createPeerConnection(connection, senderUserId, peerInfo);// Capture incoming data channelpc.ondatachannel = (event) => {setupDataChannel(senderUserId, event.channel);};await pc.setRemoteDescription(new RTCSessionDescription(signalData));await processPendingCandidates(senderUserId, pc);const answer = await pc.createAnswer();await pc.setLocalDescription(answer);await sendSignal(connection, senderUserId, 'answer', answer);}else if (type === 'answer') {console.log(`[WebRTC] Received SDP Answer from peer ${senderUserId}`);const pc = peerConnectionsRef.current[senderUserId];if (pc) {await pc.setRemoteDescription(new RTCSessionDescription(signalData));await processPendingCandidates(senderUserId, pc);}}else if (type === 'candidate') {console.log(`[WebRTC] Received ICE Candidate from peer ${senderUserId}`);const pc = peerConnectionsRef.current[senderUserId];if (pc && pc.remoteDescription) {try {await pc.addIceCandidate(new RTCIceCandidate(signalData));} catch (e) {console.error('[WebRTC] Error adding received ICE candidate', e);}} else {if (!pendingCandidatesRef.current[senderUserId]) {pendingCandidatesRef.current[senderUserId] = [];}pendingCandidatesRef.current[senderUserId].push(signalData);console.log(`[WebRTC] Queued ICE candidate for peer ${senderUserId} (remoteDescription is null)`);}}} catch (err) {console.error('[WebRTC] Error handling received signal', err);}});// Cursorsconnection.on('CursorMoved', (connectionId, senderId, x, y) => {if (senderId === user.id) return;onRemoteMessageRef.current(senderId, {type: 'CURSOR_MOVE',payload: { x, y }});});// Live nodes/edges updatesconnection.on('NodeMoved', (nodeId, x, y) => {onRemoteMessageRef.current('', {type: 'NODE_MOVE',payload: { id: nodeId, position: { x, y } }});});connection.on('NodeDataUpdated', (nodeId, newDataJson) => {try {const newData = JSON.parse(newDataJson);onRemoteMessageRef.current('', {type: 'NODE_DATA',payload: { id: nodeId, newData }});} catch (e) {console.error(e);}});connection.on('NodeAdded', (nodeJson) => {try {const node = JSON.parse(nodeJson);onRemoteMessageRef.current('', {type: 'NODE_ADD',payload: node});} catch (e) {console.error(e);}});connection.on('NodeDeleted', (nodeId) => {onRemoteMessageRef.current('', {type: 'NODE_DELETE',payload: { id: nodeId }});});connection.on('EdgeAdded', (edgeJson) => {try {const edge = JSON.parse(edgeJson);onRemoteMessageRef.current('', {type: 'EDGE_ADD',payload: edge});} catch (e) {console.error(e);}});connection.on('EdgeDeleted', (edgeId) => {onRemoteMessageRef.current('', {type: 'EDGE_DELETE',payload: { id: edgeId }});});// Access authorization check failedconnection.on('AccessDenied', () => {alert("У вас немає прав для доступу до цієї дошки.");window.location.href = '/dashboard';});const startConnection = async () => {try {await connection.start();console.log('[SignalR] Connected to BoardHub successfully.');await connection.invoke('JoinBoard', projectId);} catch (err) {console.error('[SignalR] Connection failed: ', err);}};startConnection();return () => {// Clean up all peer connections on unmountObject.keys(peerConnectionsRef.current).forEach(cleanupPeer);connection.stop().then(() => console.log('[SignalR] Connection stopped.')).catch(err => console.error('[SignalR] Error stopping connection:', err));};}, [projectId, user, token, API_URL]);const broadcastMessage = async (msg) => {const connection = connectionRef.current;// Determine if we should send high-frequency updates via WebRTC P2P Data Channelconst isHighFrequency = msg.type === 'CURSOR_MOVE' || msg.type === 'NODE_MOVE';let sentP2P = false;if (isHighFrequency) {const payload = JSON.stringify(msg);// Attempt to send to all peers with open WebRTC data channelsObject.keys(dataChannelsRef.current).forEach(peerId => {const channel = dataChannelsRef.current[peerId];if (channel && channel.readyState === 'open') {try {channel.send(payload);sentP2P = true;} catch (e) {console.error(`[WebRTC] Failed to send message to peer ${peerId}`, e);}}});}// Fallback/Standard logic via SignalR Hub if not sent via P2Pif (!sentP2P) {if (!connection || connection.state !== signalR.HubConnectionState.Connected) {return;}try {if (msg.type === 'CURSOR_MOVE') {const { x, y } = msg.payload;await connection.invoke('SendCursor', projectId, x, y);} else if (msg.type === 'NODE_MOVE') {const { id, position } = msg.payload;await connection.invoke('MoveNode', projectId, id, position.x, position.y);} else if (msg.type === 'NODE_DATA') {const { id, newData } = msg.payload;await connection.invoke('UpdateNodeData', projectId, id, JSON.stringify(newData));} else if (msg.type === 'NODE_ADD') {await connection.invoke('AddNode', projectId, JSON.stringify(msg.payload));} else if (msg.type === 'NODE_DELETE') {await connection.invoke('DeleteNode', projectId, msg.payload.id);} else if (msg.type === 'EDGE_ADD') {await connection.invoke('AddEdge', projectId, JSON.stringify(msg.payload));} else if (msg.type === 'EDGE_DELETE') {await connection.invoke('DeleteEdge', projectId, msg.payload.id);}} catch (err) {console.error('[SignalR] Failed to invoke hub method:', err);}}};return {
package-lock.json+175-1
package.json+1
src/features/canvas/hooks/useCanvasLogic.js+3-3
src/features/canvas/hooks/useWebRTC.js → src/features/canvas/hooks/useSignalR.jsRenamed+266-176