-
Notifications
You must be signed in to change notification settings - Fork 60
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Setup websockets communication between web and workers
We want to keep the client informed when evaluations are running. How many logs are created and how many logs fail. This PR setup a new Express server that setup a Socket.IO websocket server with 2 endpoints /websocket and worker-websocket. The one for web has secure cookies token auth and the one for workers share a secret token between Sockets server and workers. I think this setup makes sense
- Loading branch information
1 parent
e5353a6
commit 61e7179
Showing
40 changed files
with
2,340 additions
and
1,050 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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,32 @@ | ||
'use server' | ||
|
||
import { verifyWebsocketToken } from '@latitude-data/core/websockets/utils' | ||
import { setWebsocketSessionCookie } from '$/services/auth/setSession' | ||
|
||
import { authProcedure } from '../procedures' | ||
|
||
export const refreshWebesocketTokenAction = authProcedure | ||
.createServerAction() | ||
.handler(async ({ ctx: { session, user, workspace } }) => { | ||
debugger | ||
const { cookies } = await import('next/headers') | ||
const refreshWebsocketCookie = cookies().get('websocketRefresh') | ||
const refreshToken = refreshWebsocketCookie?.value | ||
const result = await verifyWebsocketToken({ | ||
token: refreshToken, | ||
type: 'websocket', | ||
}) | ||
|
||
if (!result.error) return { success: true } | ||
|
||
await setWebsocketSessionCookie({ | ||
name: 'websocket', | ||
sessionData: { user, workspace }, | ||
}) | ||
await setWebsocketSessionCookie({ | ||
name: 'websocketRefresh', | ||
sessionData: { user, workspace }, | ||
}) | ||
|
||
return { success: true } | ||
}) |
This file contains 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
This file contains 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
72 changes: 72 additions & 0 deletions
72
...ts/[documentUuid]/evaluations/[evaluationId]/_components/EvaluationStatusBanner/index.tsx
This file contains 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,72 @@ | ||
'use client' | ||
|
||
import { useCallback, useEffect, useRef, useState } from 'react' | ||
|
||
import { EvaluationDto } from '@latitude-data/core/browser' | ||
import { ProgressIndicator, useCurrentDocument } from '@latitude-data/web-ui' | ||
import { | ||
useSockets, | ||
type EventArgs, | ||
} from '$/components/Providers/WebsocketsProvider/useSockets' | ||
|
||
export function EvaluationStatusBanner({ | ||
evaluation, | ||
}: { | ||
evaluation: EvaluationDto | ||
}) { | ||
const timeoutRef = useRef<number | null>(null) | ||
const [jobs, setJobs] = useState<EventArgs<'evaluationStatus'>[]>([]) | ||
const document = useCurrentDocument() | ||
const onMessage = useCallback( | ||
(args: EventArgs<'evaluationStatus'>) => { | ||
if (evaluation.id !== args.evaluationId) return | ||
if (document.documentUuid !== args.documentUuid) return | ||
|
||
setJobs((prevJobs) => { | ||
const jobIndex = prevJobs.findIndex( | ||
(job) => job.batchId === args.batchId, | ||
) | ||
|
||
if (jobIndex === -1) { | ||
return [...prevJobs, args] | ||
} else { | ||
const newJobs = [...prevJobs] | ||
newJobs[jobIndex] = args | ||
|
||
if (args.status && args.status === 'finished') { | ||
setTimeout(() => { | ||
setJobs((currentJobs) => { | ||
return currentJobs.filter((job) => job.batchId !== args.batchId) | ||
}) | ||
}, 500) | ||
} | ||
|
||
return newJobs | ||
} | ||
}) | ||
}, | ||
[evaluation.id, document.documentUuid], | ||
) | ||
useEffect(() => { | ||
return () => { | ||
if (timeoutRef.current) { | ||
clearTimeout(timeoutRef.current) | ||
} | ||
} | ||
}, []) | ||
|
||
useSockets({ event: 'evaluationStatus', onMessage }) | ||
|
||
return ( | ||
<> | ||
{jobs.map((job) => ( | ||
<ProgressIndicator | ||
key={job.batchId} | ||
state={job.status === 'finished' ? 'completed' : 'running'} | ||
> | ||
{`Generating batch evaluation (ID: ${job.batchId}) ${job.completed}/${job.initialTotal}`} | ||
</ProgressIndicator> | ||
))} | ||
</> | ||
) | ||
} |
This file contains 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
110 changes: 110 additions & 0 deletions
110
apps/web/src/components/Providers/WebsocketsProvider/index.tsx
This file contains 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,110 @@ | ||
'use client' | ||
|
||
import { | ||
createContext, | ||
ReactNode, | ||
useCallback, | ||
useContext, | ||
useEffect, | ||
} from 'react' | ||
|
||
import { | ||
WebClientToServerEvents, | ||
WebServerToClientEvents, | ||
} from '@latitude-data/core/browser' | ||
import { useSession, useToast } from '@latitude-data/web-ui' | ||
import { refreshWebesocketTokenAction } from '$/actions/user/refreshWebsocketTokenAction' | ||
import useCurrentWorkspace from '$/stores/currentWorkspace' | ||
import { IoProvider, useSocket } from 'socket.io-react-hook' | ||
|
||
export const SocketIOProvider = ({ children }: { children: ReactNode }) => { | ||
return <IoProvider>{children}</IoProvider> | ||
} | ||
|
||
function useJoinWorkspace({ connection }: { connection: IWebsocketConfig }) { | ||
const { currentUser } = useSession() | ||
const { data: workspace } = useCurrentWorkspace() | ||
return useCallback(() => { | ||
connection.socket.emit('joinWorkspace', { | ||
workspaceId: workspace.id, | ||
userId: currentUser.id, | ||
}) | ||
}, [workspace.id, connection.socket, connection.connected]) | ||
} | ||
|
||
export function useSocketConnection({ | ||
socketServer, | ||
}: { | ||
socketServer: string | ||
}) { | ||
const { toast } = useToast() | ||
const connection = useSocket< | ||
WebServerToClientEvents, | ||
WebClientToServerEvents | ||
>( | ||
`${socketServer}/web`, // namespace | ||
{ | ||
path: '/websocket', // Socket server endpoint | ||
withCredentials: true, // Cookies cross-origin | ||
transports: ['websocket'], | ||
}, | ||
) | ||
|
||
connection.socket.on('connect_error', async (error) => { | ||
console.error('Connection error:', error.message) | ||
|
||
if (error.message.startsWith('AUTH_ERROR')) { | ||
const [data] = await refreshWebesocketTokenAction() | ||
|
||
if (data && data.success) { | ||
connection.socket.connect() | ||
} else { | ||
toast({ | ||
title: 'We have a problem reconnecting to the server', | ||
description: 'Try logout and login again', | ||
variant: 'destructive', | ||
}) | ||
} | ||
} | ||
}) | ||
|
||
return connection | ||
} | ||
|
||
type IWebsocketConfig = ReturnType<typeof useSocketConnection> | ||
const WebsocketConfigContext = createContext<IWebsocketConfig>( | ||
{} as IWebsocketConfig, | ||
) | ||
|
||
export const LatitudeWebsocketsProvider = ({ | ||
children, | ||
socketServer, | ||
}: { | ||
children: ReactNode | ||
socketServer: string | ||
}) => { | ||
const connection = useSocketConnection({ socketServer }) | ||
const joinWorkspace = useJoinWorkspace({ connection }) | ||
useEffect(() => { | ||
if (connection.connected) return | ||
|
||
joinWorkspace() | ||
}, [connection.connected, joinWorkspace]) | ||
return ( | ||
<WebsocketConfigContext.Provider value={connection}> | ||
{children} | ||
</WebsocketConfigContext.Provider> | ||
) | ||
} | ||
|
||
export const useWebsocketConfig = () => { | ||
const context = useContext(WebsocketConfigContext) | ||
|
||
if (!context) { | ||
throw new Error( | ||
'useWebsocketConfig must be used within a WebsocketProvider', | ||
) | ||
} | ||
|
||
return context | ||
} |
22 changes: 22 additions & 0 deletions
22
apps/web/src/components/Providers/WebsocketsProvider/useSockets.ts
This file contains 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,22 @@ | ||
import { WebServerToClientEvents } from '@latitude-data/core/browser' | ||
import { useSocketEvent } from 'socket.io-react-hook' | ||
|
||
import { useWebsocketConfig } from './index' | ||
|
||
type ServerEventType = keyof WebServerToClientEvents | ||
export type EventArgs<T extends ServerEventType> = Parameters< | ||
WebServerToClientEvents[T] | ||
>[0] | ||
export function useSockets<SEName extends ServerEventType>({ | ||
event, | ||
onMessage, | ||
}: { | ||
event: SEName | ||
onMessage: (args: EventArgs<SEName>) => void | ||
}) { | ||
const connection = useWebsocketConfig() | ||
useSocketEvent<EventArgs<SEName>>(connection.socket, event, { | ||
onMessage, | ||
}) | ||
return connection.socket | ||
} |
This file contains 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
This file contains 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 |
---|---|---|
|
@@ -131,4 +131,3 @@ export const fontMono = localFont({ | |
], | ||
variable: '--font-mono', | ||
}) | ||
|
Oops, something went wrong.