add tcp timeout, fix worker stuck

This commit is contained in:
lyc8503 committed 2023-10-28 16:02:22 +08:00
1 parent 4817fef547
commit 6157bc0879
4 files changed
+15 -6

No files matched your search

+2 -2
View File
@@ -1,6 +1,6 @@
import { connect } from 'cloudflare:sockets'
import config from '../../uptime.config'
import { fetchTimeout, getWorkerLocation } from './util'
import { fetchTimeout, getWorkerLocation, withTimeout } from './util'
import { MonitorState, MonitorTarget } from "../../uptime.types"
export interface Env {
@@ -30,7 +30,7 @@ async function getStatus(monitor: MonitorTarget): Promise<{ ping: number; up: bo
// Can't do this: await socket.close()
// https://github.com/cloudflare/workerd/issues/1305
await socket.closed
await withTimeout(monitor.timeout || 10000, socket.closed)
console.log(`${monitor.name} connected to ${monitor.target}`)
+11 -1
View File
@@ -14,4 +14,14 @@ const fetchTimeout = (url: string, ms: number, { signal, ...options }: RequestIn
return promise.finally(() => clearTimeout(timeout))
}
export { getWorkerLocation, fetchTimeout }
function withTimeout<T> (millis: number, promise: Promise<T>): Promise<T> {
const timeout = new Promise<T>((resolve, reject) =>
setTimeout(() => reject(new Error(`Promise timed out after ${millis}ms`)), millis))
return Promise.race([
promise,
timeout
])
}
export { getWorkerLocation, fetchTimeout, withTimeout }