Skip to content

Commit

Permalink
refactor: drop unnecessary logic
Browse files Browse the repository at this point in the history
  • Loading branch information
Kikobeats committed Sep 12, 2024
1 parent 3767dcc commit 6c2a047
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 49 deletions.
3 changes: 0 additions & 3 deletions packages/function/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,8 @@
"serverless"
],
"dependencies": {
"@browserless/errors": "^10.5.2",
"debug-logfmt": "~1.2.1",
"isolated-function": "~0.1.4",
"p-retry": "~4.6.1",
"p-timeout": "~4.1.0",
"require-one-of": "~1.0.19"
},
"devDependencies": {
Expand Down
61 changes: 15 additions & 46 deletions packages/function/src/index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
'use strict'

const { isBrowserlessError, ensureError, browserTimeout } = require('@browserless/errors')
const debug = require('debug-logfmt')('browserless:function')
const { isBrowserlessError, ensureError } = require('@browserless/errors')
const requireOneOf = require('require-one-of')
const pTimeout = require('p-timeout')
const pRetry = require('p-retry')

const { AbortError } = pRetry

const runFunction = require('./function')

const stringify = fn => fn.toString().trim().replace(/;$/, '')
Expand All @@ -25,48 +19,23 @@ module.exports =
) =>
async (url, fnOpts = {}) => {
const browserlessPromise = getBrowserless()
let isRejected = false

async function run () {
const browser = await browserlessPromise
const browserless = await browser.createContext()

const withVM = browserless.withPage((page, goto) => async () => {
const { device } = await goto(page, { url, ...gotoOpts })
return runFunction({
url,
code: stringify(fn),
browserWSEndpoint: (await browserless.browser()).wsEndpoint(),
device,
...opts,
...fnOpts
})
const browser = await browserlessPromise
const browserless = await browser.createContext()

return browserless.withPage((page, goto) => async () => {
const { device } = await goto(page, { url, ...gotoOpts })
const result = await runFunction({
url,
code: stringify(fn),
browserWSEndpoint: (await browserless.browser()).wsEndpoint(),
device,
...opts,
...fnOpts
})

const result = await withVM()
if (result.isFulfilled) return result
const error = ensureError(result.value)
if (isBrowserlessError(error)) throw ensureError(error)
if (isBrowserlessError(error)) throw error
return result
}

const task = () =>
pRetry(run, {
retries: retry,
onFailedAttempt: async error => {
if (error.name === 'AbortError') throw error
if (isRejected) throw new AbortError()
await (await browserlessPromise).respawn()
const { message, attemptNumber, retriesLeft } = error
debug('retry', { attemptNumber, retriesLeft, message })
}
})

// main
const result = await pTimeout(task(), timeout, () => {
isRejected = true
throw browserTimeout({ timeout })
})

return result
})()
}

0 comments on commit 6c2a047

Please sign in to comment.