Skip to content

Commit

Permalink
bacalhau: refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
juliangruber committed Aug 21, 2023
1 parent d467583 commit 30bd68b
Showing 1 changed file with 37 additions and 33 deletions.
70 changes: 37 additions & 33 deletions lib/bacalhau.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,41 @@ export async function install () {
})
}

const getApiUrl = childProcess => new Promise((resolve, reject) => {
let output = ''

const readyHandler = data => {
output += data.toString()

const apiMatch = output.match(/^API: (http.*)$/m)
if (apiMatch) {
childProcess.stdout.off('data', readyHandler)
const apiUrl = apiMatch[1]
resolve(apiUrl)
}
}
childProcess.stdout.on('data', readyHandler)
childProcess.catch(reject)
})

const runMetricsLoop = async ({ childProcess, apiUrl, onMetrics }) => {
while (true) {
if (
childProcess.exitCode !== null ||
childProcess.signalCode !== null
) {
break
}
try {
await updateStats({ apiUrl, onMetrics })
} catch (err) {
const errString = err.stack || err.message || err
console.error(`Cannot fetch Bacalhau module stats. ${errString}`)
}
await timers.setTimeout(1000)
}
}

export async function run ({
FIL_WALLET_ADDRESS,
storagePath,
Expand Down Expand Up @@ -68,23 +103,6 @@ export async function run ({
})
childProcess.stderr.pipe(process.stderr, { end: false })

const readyPromise = new Promise((resolve, reject) => {
let output = ''

const readyHandler = data => {
output += data.toString()

const apiMatch = output.match(/^API: (http.*)$/m)
if (apiMatch) {
childProcess.stdout.off('data', readyHandler)
const apiUrl = apiMatch[1]
resolve(apiUrl)
}
}
childProcess.stdout.on('data', readyHandler)
childProcess.catch(reject)
})

childProcess.on('exit', (code, signal) => {
const reason = signal ? `via signal ${signal}` : `with code: ${code}`
const msg = `Bacalhau exited ${reason}`
Expand All @@ -95,7 +113,7 @@ export async function run ({
(async () => {
let apiUrl
try {
apiUrl = await readyPromise
apiUrl = await getApiUrl(childProcess)
} catch (err) {
const errorMsg = err instanceof Error ? err.message : '' + err
const message = `Cannot start Bacalhau: ${errorMsg}`
Expand All @@ -104,21 +122,7 @@ export async function run ({
}

onActivity({ type: 'info', message: 'Bacalhau module started.' })
while (true) {
if (
childProcess.exitCode !== null ||
childProcess.signalCode !== null
) {
break
}
try {
await updateStats({ apiUrl, onMetrics })
} catch (err) {
const errString = err.stack || err.message || err
console.error(`Cannot fetch Bacalhau module stats. ${errString}`)
}
await timers.setTimeout(1000)
}
await runMetricsLoop({ childProcess, apiUrl, onMetrics })
})(),
(async () => {
const [code] = await once(childProcess, 'close')
Expand Down

0 comments on commit 30bd68b

Please sign in to comment.