Skip to content
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

fix: enhance websocket stability and error handling #39

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions packages/jstack/src/client/hooks/use-web-socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,19 @@ export function useWebSocket<
eventsRef.current = events

useEffect(() => {
if (opts?.enabled === false) {
if (opts?.enabled === false || !socket) {
return
}

const defaultHandlers = {
onConnect: () => {},
onError: () => {},
onError: (error: Error) => console.error("WebSocket error:", error),
onDisconnect: () => socket.reconnect(),
}

const mergedEvents = {
...defaultHandlers,
...events,
...eventsRef.current, // Use ref to avoid stale closures
}

const eventNames = Object.keys(mergedEvents) as Array<
Expand All @@ -36,7 +37,6 @@ export function useWebSocket<

eventNames.forEach((eventName) => {
const handler = mergedEvents[eventName]

if (handler) {
socket.on(eventName, handler)
}
Expand All @@ -45,8 +45,11 @@ export function useWebSocket<
return () => {
eventNames.forEach((eventName) => {
const handler = mergedEvents[eventName]
socket.off(eventName, handler)
if (handler) {
socket.off(eventName, handler)
}
})
socket.close()
}
}, [opts?.enabled])
}, [socket, opts?.enabled])
}
34 changes: 23 additions & 11 deletions packages/jstack/src/server/io.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,41 @@ import { logger } from "jstack-shared"
export class IO<IncomingEvents, OutgoingEvents> {
private targetRoom: string | null = null
private redis: Redis
private readonly timeout = 5000 // 5 seconds timeout

constructor(redisUrl: string, redisToken: string) {
this.redis = new Redis({ token: redisToken, url: redisUrl })
}

/**
* Sends to all connected clients (broadcast)
*/
async emit<K extends keyof OutgoingEvents>(event: K, data: OutgoingEvents[K]) {
if (this.targetRoom) {
await this.redis.publish(this.targetRoom, [event, data])
if (!this.targetRoom) {
throw new Error("No target room specified. Call .to(room) before .emit()")
}

logger.success(`IO emitted to room "${this.targetRoom}":`, [event, data])
try {
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => reject(new Error("Redis publish timeout")), this.timeout)
})

// Reset target room after emitting
this.targetRoom = null
await Promise.race([
this.redis.publish(this.targetRoom, [event, data]),
timeoutPromise
])

logger.success(`IO emitted to room "${this.targetRoom}":`, [event, data])
} catch (error) {
logger.error(`Failed to emit to room "${this.targetRoom}":`, error)
throw error
} finally {
// Reset target room after emitting
this.targetRoom = null
}
}

/**
* Sends to all in a room
*/
to(room: string): this {
if (!room) {
throw new Error("Room name cannot be empty")
}
this.targetRoom = room
return this
}
Expand Down
47 changes: 33 additions & 14 deletions www/src/actions/stargazers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const fetchStargazers = async ({ GITHUB_TOKEN }: { GITHUB_TOKEN: string }
throw new Error("GitHub token is required but was not provided. Set the GITHUB_TOKEN environment variable.")
}

const makeRequest = async (url: string, useToken = true) => {
const makeRequest = async (url: string, useToken = true, retries = 3) => {
const headers: Record<string, string> = {
Accept: "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
Expand All @@ -27,23 +27,42 @@ export const fetchStargazers = async ({ GITHUB_TOKEN }: { GITHUB_TOKEN: string }
headers.Authorization = `Bearer ${GITHUB_TOKEN}`
}

const res = await fetch(url, { headers })

if (res.status === 403) {
// rate limit reached, retry without token
if (useToken) {
return makeRequest(url, false)
try {
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), 10000)

const res = await fetch(url, {
headers,
signal: controller.signal
})
clearTimeout(timeout)

if (res.status === 403) {
if (useToken) {
return makeRequest(url, false, retries)
}
throw new Error("Rate limit reached for both authenticated and unauthenticated requests")
}

throw new Error("Rate limit reached for both authenticated and unauthenticated requests")
}
if (!res.ok) {
if (retries > 0) {
await new Promise(resolve => setTimeout(resolve, 1000))
return makeRequest(url, useToken, retries - 1)
}
const errorText = await res.text()
throw new Error(`GitHub API failed: ${res.status} ${res.statusText} - ${errorText}`)
}

if (!res.ok) {
const errorText = await res.text()
throw new Error(`GitHub API failed: ${res.status} ${res.statusText} - ${errorText}`)
return res
} catch (error) {
if (error instanceof Error && error.name === 'AbortError') {
if (retries > 0) {
return makeRequest(url, useToken, retries - 1)
}
throw new Error('Request timeout')
}
throw error
}

return res
}

try {
Expand Down
5 changes: 2 additions & 3 deletions www/src/ctx/use-table-of-contents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,8 @@ interface State {
export const useTableOfContents = create<State>()((set) => ({
allHeadings: [],
activeHeadingIds: [],
setAllHeadings: (allHeadings) => set((state) => ({ allHeadings })),
sections: [],
visibleSections: [],
setAllHeadings: (allHeadings) => set(() => ({ allHeadings })),
setVisibleSections: (visibleSections) =>
set((state) => (state.visibleSections.join() === visibleSections.join() ? {} : { visibleSections })),
set((state) => (state.visibleSections.join() === visibleSections.join() ? state : { ...state, visibleSections })),
}))