chore: add preflight check to tryFetch

This commit is contained in:
Ben Allfree
2023-06-14 12:00:18 +00:00
parent b962b4b54b
commit a438dc293c
3 changed files with 31 additions and 17 deletions

View File

@@ -34,3 +34,4 @@ This is a maintenance release.
- Fix: Increased release page limit to 100 because some old PocketBase releases were getting dropped from the github API query
- Chore: adjust logfile destination on live server
- Chore: remove platform reference when launching instance
- Chore: add preflight check to tryFetch

View File

@@ -173,6 +173,9 @@ export const createPocketbaseService = async (
args.push(`--http`)
args.push(mkInternalAddress(port))
}
let isRunning = true
dbg(`Spawning ${slug}`, { bin, args, cli: [bin, ...args].join(' ') })
const ls = spawn(bin, args)
cm.add(() => ls.kill())
@@ -192,6 +195,7 @@ export const createPocketbaseService = async (
const exited = new Promise<number | null>((resolve) => {
ls.on('exit', (code) => {
dbg(`${slug} exited with code ${code}`)
isRunning = false
if (code) onUnexpectedStop?.(code)
resolve(code)
})
@@ -203,7 +207,7 @@ export const createPocketbaseService = async (
const url = mkInternalUrl(port)
if (command === 'serve') {
await tryFetch(url)
await tryFetch(url, async () => isRunning)
}
const api: PocketbaseProcess = {
url,

View File

@@ -1,20 +1,29 @@
import { logger, safeCatch } from '@pockethost/common'
export const tryFetch = safeCatch(`tryFetch`, (url: string) => {
const { dbg } = logger().create('tryFetch')
return new Promise<void>((resolve, reject) => {
const tryFetch = () => {
dbg(`Trying to connect to instance ${url} `)
fetch(url)
.then(() => {
dbg(`Connection to ${url} successful`)
export const tryFetch = safeCatch(
`tryFetch`,
(url: string, preflight?: () => Promise<boolean>) => {
const { dbg } = logger().create('tryFetch')
return new Promise<void>((resolve, reject) => {
const tryFetch = async () => {
if (preflight) {
dbg(`Checking preflight`)
const shouldFetch = await preflight()
if (!shouldFetch) {
throw new Error(`tryFetch failed preflight, aborting`)
}
}
try {
dbg(`Trying to fetch ${url} `)
const res = await fetch(url)
dbg(`Fetch ${url} successful`)
resolve()
})
.catch((e) => {
dbg(`Could not connect to ${url}`)
} catch (e) {
dbg(`Could not fetch ${url}, trying again in 1s`)
setTimeout(tryFetch, 1000)
})
}
tryFetch()
})
})
}
}
tryFetch()
})
}
)