-
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 (#171)
* 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 * Use existing env variables for latitude domain and subdomain and disable websockets until infra is ready
- Loading branch information
1 parent
2c8576e
commit 1295d48
Showing
44 changed files
with
2,414 additions
and
1,065 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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -56,6 +56,7 @@ export const environment = pulumi | |
{ name: 'GATEWAY_SSL', value: 'true' }, | ||
{ name: 'LATITUDE_DOMAIN', value: 'latitude.so' }, | ||
{ name: 'LATITUDE_URL', value: 'https://app.latitude.so' }, | ||
{ name: 'WEBSOCKETS_SERVER', value: 'ws.latitude.so' }, | ||
{ name: 'FROM_MAILER_EMAIL', value: '[email protected]' }, | ||
{ name: 'MAILER_API_KEY', value: mailerApiKey }, | ||
{ name: 'SENTRY_DSN', value: sentryDsn }, | ||
|
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
74 changes: 74 additions & 0 deletions
74
...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,74 @@ | ||
'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 { 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() | ||
|
||
// FIXME: Remove this line when infra is ready | ||
// @ts-ignore | ||
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) | ||
} | ||
} | ||
}, []) | ||
|
||
// TODO: Implement websockets infra | ||
// 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
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 | ||
{ | ||
// FIXME: Remove this line when infra is ready | ||
autoConnect: false, | ||
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 | ||
} |
Oops, something went wrong.