-
Notifications
You must be signed in to change notification settings - Fork 96
feat: add websocket client module #41
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
0xdevcollins
merged 3 commits into
boundlessfi:main
from
DioChuks:feature/websocket-client
Jan 25, 2026
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| 'use client'; | ||
|
|
||
| import { useEffect, useState } from 'react'; | ||
| import { useQueryClient } from '@tanstack/react-query'; | ||
| import { socket } from '@/lib/socket/client'; | ||
| import { setupSocketSync } from '@/lib/query/sync/socket-sync'; | ||
| import { authClient } from '@/lib/auth-client'; | ||
|
|
||
| export function useSocketSync() { | ||
| const queryClient = useQueryClient(); | ||
| const { data: session, isPending: isSessionLoading } = authClient.useSession(); | ||
| const [isConnected, setIsConnected] = useState(socket.connected); | ||
|
|
||
| useEffect(() => { | ||
| const onConnect = () => setIsConnected(true); | ||
| const onDisconnect = () => setIsConnected(false); | ||
|
|
||
| socket.on('connect', onConnect); | ||
| socket.on('disconnect', onDisconnect); | ||
|
|
||
| return () => { | ||
| socket.off('connect', onConnect); | ||
| socket.off('disconnect', onDisconnect); | ||
| }; | ||
| }, []); | ||
|
|
||
| useEffect(() => { | ||
| if (isSessionLoading) return; | ||
|
|
||
| // Connect socket if authenticated | ||
| if (session) { | ||
| console.log('[Socket] Connecting...'); | ||
| socket.connect(); | ||
|
|
||
| // Setup synchronization listeners | ||
| const cleanupSync = setupSocketSync(queryClient); | ||
|
|
||
| return () => { | ||
| console.log('[Socket] Disconnecting...'); | ||
| cleanupSync(); | ||
| socket.disconnect(); | ||
| }; | ||
| } else { | ||
| // Ensure socket is disconnected if session is lost | ||
| if (socket.connected) { | ||
| socket.disconnect(); | ||
| } | ||
| } | ||
| }, [session, isSessionLoading, queryClient]); | ||
|
|
||
| return { | ||
| socket, | ||
| isConnected, | ||
| }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| import { QueryClient } from '@tanstack/react-query'; | ||
| import { Bounty, PaginatedResponse } from '@/lib/api'; | ||
| import { bountyKeys } from '@/hooks/use-bounties'; | ||
|
|
||
| export function handleBountyCreated(queryClient: QueryClient, bounty: Bounty) { | ||
| console.log('[Sync] Handling bounty.created:', bounty.id); | ||
|
|
||
| // Update lists | ||
| queryClient.setQueriesData<PaginatedResponse<Bounty>>( | ||
| { queryKey: bountyKeys.lists() }, | ||
| (oldData) => { | ||
| if (!oldData) return oldData; | ||
| return { | ||
| ...oldData, | ||
| data: [bounty, ...oldData.data], | ||
| pagination: { | ||
| ...oldData.pagination, | ||
| total: oldData.pagination.total + 1, | ||
| }, | ||
| }; | ||
| } | ||
| ); | ||
|
|
||
| // Set detail cache | ||
| queryClient.setQueryData(bountyKeys.detail(bounty.id), bounty); | ||
| } | ||
|
|
||
| export function handleBountyUpdated(queryClient: QueryClient, bounty: Bounty) { | ||
| console.log('[Sync] Handling bounty.updated:', bounty.id); | ||
|
|
||
| // Update lists | ||
| queryClient.setQueriesData<PaginatedResponse<Bounty>>( | ||
| { queryKey: bountyKeys.lists() }, | ||
| (oldData) => { | ||
| if (!oldData) return oldData; | ||
| return { | ||
| ...oldData, | ||
| data: oldData.data.map((b) => (b.id === bounty.id ? bounty : b)), | ||
| }; | ||
| } | ||
| ); | ||
|
|
||
| // Update detail cache | ||
| queryClient.setQueryData(bountyKeys.detail(bounty.id), bounty); | ||
| } | ||
|
|
||
| export function handleBountyDeleted(queryClient: QueryClient, bountyId: string) { | ||
| console.log('[Sync] Handling bounty.deleted:', bountyId); | ||
|
|
||
| // Update lists | ||
| queryClient.setQueriesData<PaginatedResponse<Bounty>>( | ||
| { queryKey: bountyKeys.lists() }, | ||
| (oldData) => { | ||
| if (!oldData) return oldData; | ||
| return { | ||
| ...oldData, | ||
| data: oldData.data.filter((b) => b.id !== bountyId), | ||
| pagination: { | ||
| ...oldData.pagination, | ||
| total: Math.max(0, oldData.pagination.total - 1), | ||
| }, | ||
| }; | ||
| } | ||
| ); | ||
|
|
||
| // Invalidate or remove detail cache | ||
| queryClient.removeQueries({ queryKey: bountyKeys.detail(bountyId) }); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| import { QueryClient } from '@tanstack/react-query'; | ||
| import { socket } from '@/lib/socket/client'; | ||
| import * as handlers from './handlers'; | ||
|
|
||
| export function setupSocketSync(queryClient: QueryClient) { | ||
| console.log('[Sync] Setting up socket listeners...'); | ||
|
|
||
| // Bounties | ||
| socket.on('bounty.created', (payload) => { | ||
| handlers.handleBountyCreated(queryClient, payload); | ||
| }); | ||
|
|
||
| socket.on('bounty.updated', (payload) => { | ||
| handlers.handleBountyUpdated(queryClient, payload); | ||
| }); | ||
|
|
||
| socket.on('bounty.deleted', (payload) => { | ||
| // payload might be the ID string or an object with id | ||
| const bountyId = typeof payload === 'string' ? payload : payload.id; | ||
| handlers.handleBountyDeleted(queryClient, bountyId); | ||
| }); | ||
|
|
||
| // Add more entity listeners here as needed | ||
|
|
||
| return () => { | ||
| console.log('[Sync] Removing socket listeners...'); | ||
| socket.off('bounty.created'); | ||
| socket.off('bounty.updated'); | ||
| socket.off('bounty.deleted'); | ||
| }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| import { io, Socket } from 'socket.io-client'; | ||
|
|
||
| const SOCKET_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000'; | ||
|
|
||
| export const socket: Socket = io(SOCKET_URL, { | ||
| autoConnect: false, | ||
| reconnection: true, | ||
| reconnectionAttempts: 5, | ||
| reconnectionDelay: 1000, | ||
| reconnectionDelayMax: 5000, | ||
| timeout: 20000, | ||
| withCredentials: true, // Useful if the server uses cookies for auth | ||
| transports: ['websocket'], // Prefer WebSockets for better performance | ||
| }); | ||
|
|
||
| let lastPingTime: number; | ||
|
|
||
| // Logging and Event Handlers | ||
| socket.on('connect', () => { | ||
| console.log('[Socket] Connected to server:', socket.id); | ||
|
|
||
| // Observe Engine.IO packets for heartbeat/latency monitoring (Socket.IO v4+) | ||
| const engine = socket.io.engine; | ||
|
|
||
| engine.on('packet', (packet) => { | ||
| if (packet.type === 'ping') { | ||
| lastPingTime = Date.now(); | ||
| console.debug('[Socket] Heartbeat ping (sent)'); | ||
| } else if (packet.type === 'pong') { | ||
| const latency = Date.now() - lastPingTime; | ||
| console.debug('[Socket] Heartbeat pong (received), latency:', latency, 'ms'); | ||
| } | ||
| }); | ||
| }); | ||
|
|
||
| socket.on('disconnect', (reason) => { | ||
| console.log('[Socket] Disconnected:', reason); | ||
| if (reason === 'io server disconnect') { | ||
| // The disconnection was initiated by the server, you need to reconnect manually | ||
| socket.connect(); | ||
| } | ||
| }); | ||
|
|
||
| socket.on('connect_error', (error) => { | ||
| console.error('[Socket] Connection error:', error); | ||
| }); | ||
|
|
||
| socket.on('reconnect', (attemptNumber) => { | ||
| console.log('[Socket] Reconnected after', attemptNumber, 'attempts'); | ||
| }); | ||
|
|
||
| socket.on('reconnect_attempt', (attemptNumber) => { | ||
| console.log('[Socket] Reconnection attempt:', attemptNumber); | ||
| }); | ||
|
|
||
| socket.on('reconnect_error', (error) => { | ||
| console.error('[Socket] Reconnection error:', error); | ||
| }); | ||
|
|
||
| socket.on('reconnect_failed', () => { | ||
| console.error('[Socket] Reconnection failed'); | ||
| }); | ||
|
|
||
| export default socket; |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.