96 lines
2.3 KiB
TypeScript
96 lines
2.3 KiB
TypeScript
import { useLogger } from './useLogger'
|
|
|
|
export const isServerAvailable = ref(true)
|
|
export const isChecking = ref(false)
|
|
export const lastCheckTime = ref<Date | null>(null)
|
|
|
|
export function useServerHealth() {
|
|
const logger = useLogger().withTag('serverHealth')
|
|
const checkInterval = ref<ReturnType<typeof setInterval> | null>(null)
|
|
const healthCheckUrl = '/api/actuator/health'
|
|
|
|
async function checkServerHealth(): Promise<boolean> {
|
|
if (isChecking.value) return isServerAvailable.value
|
|
|
|
isChecking.value = true
|
|
lastCheckTime.value = new Date()
|
|
|
|
try {
|
|
const controller = new AbortController()
|
|
const timeoutId = setTimeout(() => controller.abort(), 5000)
|
|
|
|
const response = await fetch(healthCheckUrl, {
|
|
method: 'GET',
|
|
signal: controller.signal,
|
|
headers: {
|
|
'Content-Type': 'application/json'
|
|
}
|
|
})
|
|
|
|
clearTimeout(timeoutId)
|
|
|
|
const wasAvailable = isServerAvailable.value
|
|
isServerAvailable.value = response.ok
|
|
|
|
if (!wasAvailable && isServerAvailable.value) {
|
|
logger.info('Server is back online')
|
|
}
|
|
|
|
if (wasAvailable && !isServerAvailable.value) {
|
|
logger.warn('Server is no longer available')
|
|
}
|
|
|
|
return isServerAvailable.value
|
|
} catch (error) {
|
|
const wasAvailable = isServerAvailable.value
|
|
isServerAvailable.value = false
|
|
|
|
if (wasAvailable) {
|
|
logger.warn('Server health check failed:', error)
|
|
}
|
|
|
|
return false
|
|
} finally {
|
|
isChecking.value = false
|
|
}
|
|
}
|
|
|
|
async function startPeriodicHealthCheck(intervalMs: number = 60000) {
|
|
if (checkInterval.value) {
|
|
clearInterval(checkInterval.value)
|
|
}
|
|
|
|
checkServerHealth()
|
|
|
|
checkInterval.value = setInterval(() => {
|
|
checkServerHealth()
|
|
}, intervalMs)
|
|
|
|
onUnmounted(() => {
|
|
if (checkInterval.value) {
|
|
clearInterval(checkInterval.value)
|
|
checkInterval.value = null
|
|
}
|
|
})
|
|
|
|
return checkInterval.value
|
|
}
|
|
|
|
const stopHealthCheck = () => {
|
|
if (checkInterval.value) {
|
|
clearInterval(checkInterval.value)
|
|
checkInterval.value = null
|
|
}
|
|
}
|
|
|
|
return {
|
|
isServerAvailable,
|
|
isChecking,
|
|
lastCheckTime,
|
|
healthCheckUrl,
|
|
checkServerHealth,
|
|
startPeriodicHealthCheck,
|
|
stopHealthCheck
|
|
}
|
|
}
|