Skip to content
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
38 changes: 38 additions & 0 deletions packages/ui/src/lib/retry-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
interface RetryOptions {
maxAttempts?: number
initialDelayMs?: number
maxDelayMs?: number
backoffMultiplier?: number
}

export async function retryWithBackoff<T>(
fn: () => Promise<T>,
options: RetryOptions = {},
): Promise<T> {
const {
maxAttempts = 3,
initialDelayMs = 100,
maxDelayMs = 5000,
backoffMultiplier = 2,
} = options

let lastError: Error | null = null
let delayMs = initialDelayMs

for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await fn()
} catch (error) {
lastError = error instanceof Error ? error : new Error(String(error))

if (attempt < maxAttempts) {
await new Promise((resolve) => setTimeout(resolve, delayMs))
delayMs = Math.min(delayMs * backoffMultiplier, maxDelayMs)
}
}
}

throw new Error(
`Failed after ${maxAttempts} attempts: ${lastError?.message || "Unknown error"}`,
)
}
22 changes: 14 additions & 8 deletions packages/ui/src/lib/server-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { WorkspaceEventPayload, WorkspaceEventType } from "../../../server/
import { serverApi } from "./api-client"
import { getClientIdentity } from "./client-identity"
import { getLogger } from "./logger"
import { retryWithBackoff } from "./retry-utils"

const RETRY_BASE_DELAY = 1000
const RETRY_MAX_DELAY = 10000
Expand Down Expand Up @@ -39,14 +40,19 @@ class ServerEvents {
(event) => this.dispatch(event),
() => this.scheduleReconnect(),
(payload) => {
void serverApi
.sendClientConnectionPong({
...getClientIdentity(),
pingTs: payload.ts,
})
.catch((error) => {
log.error("Failed to send client connection pong", error)
})
const identity = getClientIdentity()
const pongPayload = { ...identity, pingTs: payload.ts }

void retryWithBackoff(
() => serverApi.sendClientConnectionPong(pongPayload),
{
maxAttempts: 3,
initialDelayMs: 100,
maxDelayMs: 2000,
},
).catch((error) => {
log.error("Failed to send client connection pong after retries", error)
})
},
)
this.source.onopen = () => {
Expand Down
Loading