Skip to content

Commit

Permalink
fix: stream logs only when stack is running
Browse files Browse the repository at this point in the history
  • Loading branch information
Trugamr committed Jan 14, 2024
1 parent a652a84 commit 827b467
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 25 deletions.
2 changes: 1 addition & 1 deletion app/components/stack-logs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { Stack } from '~/lib/stack.server'
import { cn } from '~/lib/utils'

type StackLogs = {
stack: Pick<Stack, 'name'>
stack: Pick<Stack, 'name' | 'status'>
className?: string
} & Pick<UseStackLogsOptions, 'initialLogs'>

Expand Down
20 changes: 0 additions & 20 deletions app/lib/hooks/use-event-source.ts

This file was deleted.

21 changes: 17 additions & 4 deletions app/lib/hooks/use-stack-logs.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { useReducer } from 'react'
import { useEffect, useReducer } from 'react'
import type { Stack } from '~/lib/stack.server'
import { useEventSource } from '~/lib/hooks/use-event-source'

export type UseStackLogsOptions = {
initialLogs?: string[]
Expand All @@ -10,7 +9,7 @@ const defaultUseStackLogsOptions: UseStackLogsOptions = {}
const defaultInitialLogs: string[] = []

export function useStackLogs(
stack: Pick<Stack, 'name'>,
stack: Pick<Stack, 'name' | 'status'>,
{ initialLogs = defaultInitialLogs }: UseStackLogsOptions = defaultUseStackLogsOptions,
) {
const [logs, push] = useReducer((logs: string[], log: MessageEvent) => {
Expand All @@ -20,7 +19,21 @@ export function useStackLogs(
return logs
}, initialLogs)

useEventSource(`/api/stacks/${stack.name}/logs`, push)
useEffect(() => {
// We don't want to listen for logs if the stack is not running
if (stack.status !== 'running') {
return
}

// Open a new stream of logs
const source = new EventSource(`/api/stacks/${stack.name}/logs`)
source.addEventListener('message', push)

return () => {
source.removeEventListener('message', push)
source.close()
}
}, [stack.name, stack.status, push])

return logs
}

0 comments on commit 827b467

Please sign in to comment.