-
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
2c8576e
commit 6ece440
Showing
43 changed files
with
2,423 additions
and
1,064 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 |
---|---|---|
@@ -1,14 +1,31 @@ | ||
'use server' | ||
|
||
import { type TokenType } from '@latitude-data/core/websockets/constants' | ||
import { authProcedure } from '$/actions/procedures' | ||
import { removeSession } from '$/services/auth/removeSession' | ||
import { ROUTES } from '$/services/routes' | ||
import { ReadonlyRequestCookies } from 'next/dist/server/web/spec-extension/adapters/request-cookies' | ||
import { redirect } from 'next/navigation' | ||
|
||
function removeSocketCookie({ | ||
name, | ||
cookies, | ||
}: { | ||
name: TokenType | ||
cookies: ReadonlyRequestCookies | ||
}) { | ||
cookies.delete(name) | ||
} | ||
|
||
export const logoutAction = authProcedure | ||
.createServerAction() | ||
.handler(async ({ ctx }) => { | ||
removeSession({ session: ctx.session }) | ||
const { cookies: getCookies } = await import('next/headers') | ||
|
||
const cookies = getCookies() | ||
removeSocketCookie({ name: 'websocket', cookies }) | ||
removeSocketCookie({ name: 'websocketRefresh', cookies }) | ||
|
||
redirect(ROUTES.auth.login) | ||
}) |
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,31 @@ | ||
'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: { user, workspace } }) => { | ||
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
73 changes: 73 additions & 0 deletions
73
...evaluations/[evaluationId]/_components/EvaluationResults/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,73 @@ | ||
'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' | ||
|
||
const DISAPERING_IN_MS = 1500 | ||
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) | ||
}) | ||
}, DISAPERING_IN_MS) | ||
} | ||
|
||
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
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
108 changes: 108 additions & 0 deletions
108
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,108 @@ | ||
'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) => { | ||
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 | ||
} |
Oops, something went wrong.