Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: rewrite #199

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
542 changes: 258 additions & 284 deletions boot.js

Large diffs are not rendered by default.

8 changes: 8 additions & 0 deletions lib/debug.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
'use strict'

// debug is the same name as deprecated API, we use alias instead
const { debuglog } = require('util')

module.exports = {
debug: debuglog('avvio')
}
1 change: 1 addition & 0 deletions lib/errors.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
'use strict'

// Code inherited from fastify-error
const { inherits, format } = require('util')

Expand Down
5 changes: 5 additions & 0 deletions lib/noop.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
'use strict'

function noop () {}

module.exports = { noop }
128 changes: 66 additions & 62 deletions plugin.js → lib/plugin.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
'use strict'

const fastq = require('fastq')
const EE = require('events').EventEmitter
const inherits = require('util').inherits
const debug = require('debug')('avvio')
const { AVV_ERR_READY_TIMEOUT } = require('./lib/errors')

// this symbol is assigned by fastify-plugin
const kPluginMeta = Symbol.for('plugin-meta')

function getName (func, optsOrFunc) {
const FastQ = require('fastq')
const { EventEmitter } = require('events')
const { inherits } = require('util')
const { AVV_ERR_READY_TIMEOUT, AVV_ERR_PLUGIN_NOT_VALID } = require('./errors')
const { debug } = require('./debug')
const { kPluginMeta } = require('./symbols')
const { createPromise } = require('./promise')
const { noop } = require('./noop')

function getName (func, optionsOrFunc) {
// use explicit function metadata if set
if (func[kPluginMeta] && func[kPluginMeta].name) {
return func[kPluginMeta].name
}

if (typeof optsOrFunc !== 'undefined' && typeof optsOrFunc !== 'function' && optsOrFunc.name) {
return optsOrFunc.name
if (typeof optionsOrFunc !== 'undefined' && typeof optionsOrFunc !== 'function' && optionsOrFunc.name) {
return optionsOrFunc.name
}

// use the function name if it exists
Expand All @@ -28,27 +28,16 @@ function getName (func, optsOrFunc) {
return func.toString().split('\n').slice(0, 2).map(s => s.trim()).join(' -- ')
}

function promise () {
const obj = {}

obj.promise = new Promise((resolve, reject) => {
obj.resolve = resolve
obj.reject = reject
})

return obj
}

function Plugin (parent, func, optsOrFunc, isAfter, timeout) {
function Plugin (parent, func, optionsOrFunc, isAfter, timeout) {
this.started = false
this.func = func
this.opts = optsOrFunc
this.options = optionsOrFunc
this.onFinish = null
this.parent = parent
this.timeout = timeout === undefined ? parent._timeout : timeout
this.name = getName(func, optsOrFunc)
this.name = getName(func, optionsOrFunc)
this.isAfter = isAfter
this.q = fastq(parent, loadPluginNextTick, 1)
this.q = FastQ(parent, loadPluginNextTick, 1)
this.q.pause()
this._error = null
this.loaded = false
Expand All @@ -60,32 +49,32 @@ function Plugin (parent, func, optsOrFunc, isAfter, timeout) {
// or they will end up at the top of _current
}

inherits(Plugin, EE)
inherits(Plugin, EventEmitter)

Plugin.prototype.exec = function (server, cb) {
Plugin.prototype.exec = function (server, callback) {
const func = this.func
let completed = false
const name = this.name

if (this.parent._error && !this.isAfter) {
debug('skipping loading of plugin as parent errored and it is not an after', name)
process.nextTick(cb)
process.nextTick(callback)
return
}

if (!this.isAfter) {
// Skip override for after
try {
this.server = this.parent.override(server, func, this.opts)
this.server = this.parent.override(server, func, this.options)
} catch (err) {
debug('override errored', name)
return cb(err)
return callback(err)
}
} else {
this.server = server
}

this.opts = typeof this.opts === 'function' ? this.opts(this.server) : this.opts
this.options = typeof this.options === 'function' ? this.options(this.server) : this.options

debug('exec', name)

Expand All @@ -111,7 +100,7 @@ Plugin.prototype.exec = function (server, cb) {
clearTimeout(timer)
}

cb(err)
callback(err)
}

if (this.timeout > 0) {
Expand All @@ -127,7 +116,7 @@ Plugin.prototype.exec = function (server, cb) {

this.started = true
this.emit('start', this.server ? this.server.name : null, this.name, Date.now())
const promise = func(this.server, this.opts, done)
const promise = func(this.server, this.options, done)

if (promise && typeof promise.then === 'function') {
debug('exec: resolving promise', name)
Expand All @@ -144,7 +133,7 @@ Plugin.prototype.loadedSoFar = function () {
}

const setup = () => {
this.server.after((err, cb) => {
this.server.after((err, callback) => {
this._error = err
this.q.pause()

Expand All @@ -157,36 +146,36 @@ Plugin.prototype.loadedSoFar = function () {
}
this._promise = null

process.nextTick(cb, err)
process.nextTick(callback, err)
})
this.q.resume()
}

let res
let result

if (!this._promise) {
this._promise = promise()
res = this._promise.promise
this._promise = createPromise()
result = this._promise.promise

if (!this.server) {
this.on('start', setup)
} else {
setup()
}
} else {
res = Promise.resolve()
result = Promise.resolve()
}

return res
return result
}

Plugin.prototype.enqueue = function (obj, cb) {
Plugin.prototype.enqueue = function (obj, callback) {
debug('enqueue', this.name, obj.name)
this.emit('enqueue', this.server ? this.server.name : null, this.name, Date.now())
this.q.push(obj, cb)
this.q.push(obj, callback)
}

Plugin.prototype.finish = function (err, cb) {
Plugin.prototype.finish = function (err, callback) {
debug('finish', this.name, err)
const done = () => {
if (this.loaded) {
Expand All @@ -197,7 +186,7 @@ Plugin.prototype.finish = function (err, cb) {
this.emit('loaded', this.server ? this.server.name : null, this.name, Date.now())
this.loaded = true

cb(err)
callback(err)
}

if (err) {
Expand Down Expand Up @@ -246,38 +235,53 @@ Plugin.prototype.finish = function (err, cb) {

// delays plugin loading until the next tick to ensure any bound `_after` callbacks have a chance
// to run prior to executing the next plugin
function loadPluginNextTick (toLoad, cb) {
function loadPluginNextTick (plugin, callback) {
const parent = this
process.nextTick(loadPlugin.bind(parent), toLoad, cb)
process.nextTick(loadPlugin.bind(parent), plugin, callback)
}

function validatePluginFunction (plugin) {
// bundler or TypeScript support
if (plugin && typeof plugin === 'object' && typeof plugin.default === 'function') {
plugin = plugin.default
}

// validate if plugin is a function or Promise
if (!(plugin && (typeof plugin === 'function' || typeof plugin.then === 'function'))) {
throw new AVV_ERR_PLUGIN_NOT_VALID(typeof plugin)
}

return plugin
}

// loads a plugin
function loadPlugin (toLoad, cb) {
if (typeof toLoad.func.then === 'function') {
toLoad.func.then((fn) => {
function loadPlugin (plugin, callback) {
if (typeof plugin.func.then === 'function') {
plugin.func.then((fn) => {
if (typeof fn.default === 'function') {
fn = fn.default
}
toLoad.func = fn
loadPlugin.call(this, toLoad, cb)
}, cb)
plugin.func = fn
loadPlugin.call(this, plugin, callback)
}, callback)
return
}

const last = this._current[0]

// place the plugin at the top of _current
this._current.unshift(toLoad)
this._current.unshift(plugin)

toLoad.exec((last && last.server) || this._server, (err) => {
toLoad.finish(err, (err) => {
plugin.exec((last && last.server) || this._instance, (err) => {
plugin.finish(err, (err) => {
this._current.shift()
cb(err)
callback(err)
})
})
}

function noop () {}

module.exports = Plugin
module.exports.loadPlugin = loadPlugin
module.exports = {
Plugin,
validatePluginFunction,
loadPlugin
}
14 changes: 14 additions & 0 deletions lib/promise.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
'use strict'

function createPromise () {
const result = {}

result.promise = new Promise((resolve, reject) => {
result.resolve = resolve
result.reject = reject
})

return result
}

module.exports = { createPromise }
21 changes: 21 additions & 0 deletions lib/queue.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'use strict'

const FastQ = require('fastq')
const { noop } = require('./noop')

/**
* Initialize a paused queue with context
* @param {*} context
* @param {*} worker
* @param {*} drain
*/
function createQueue (context, worker, drain) {
const q = FastQ(context, worker, 1)
q.pause()
q.drain = drain ?? noop
return q
}

module.exports = {
createQueue
}
24 changes: 24 additions & 0 deletions lib/symbols.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
'use strict'

// Internal Symbols
const kAvvio = Symbol('avvio.Boot')
const kThenifyDoNotWrap = Symbol('avvio.ThenifyDoNotWrap')
const kUntrackNode = Symbol('avvio.TimeTree.untrackNode')
const kTrackNode = Symbol('avvio.TimeTree.trackNode')
const kGetParent = Symbol('avvio.TimeTree.getParent')
const kGetNode = Symbol('avvio.TimeTree.getNode')
const kAddNode = Symbol('avvio.TimeTree.addNode')

// Public Symbols
const kPluginMeta = Symbol.for('plugin-meta')

module.exports = {
kAvvio,
kThenifyDoNotWrap,
kUntrackNode,
kTrackNode,
kGetParent,
kGetNode,
kAddNode,
kPluginMeta
}
49 changes: 49 additions & 0 deletions lib/thenable.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
'use strict'

const { kAvvio, kThenifyDoNotWrap } = require('./symbols')
const { debug } = require('./debug')

function executeWithThenable (func, args, callback) {
const result = func(...args)
if (result && !result[kAvvio] && typeof result.then === 'function') {
// process promise but not avvio mock thenable
result.then(() => process.nextTick(callback), (error) => process.nextTick(callback, error))
} else if (callback) {
process.nextTick(callback)
}
}

function thenify () {
// If the instance is ready, then there is
// nothing to await. This is true during
// await server.ready() as ready() resolves
// with the server, end we will end up here
// because of automatic promise chaining.
if (this.booted) {
debug('thenify returning null because we are already booted')
return
}

// Calling resolve(this._instance) would fetch the then
// property on the server, which will lead it here.
// If we do not break the recursion, we will loop
// forever.
if (this[kThenifyDoNotWrap]) {
this[kThenifyDoNotWrap] = false
return
}

debug('thenify')
return (resolve, reject) => {
const p = this._loadRegistered()
return p.then(() => {
this[kThenifyDoNotWrap] = true
return resolve(this._instance)
}, reject)
}
}

module.exports = {
thenify,
executeWithThenable
}
Loading