Skip to content

feat!: v1 #1

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

Merged
merged 19 commits into from
May 16, 2022
Merged
Show file tree
Hide file tree
Changes from 8 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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,6 @@ dist

# TernJS port file
.tern-port

# Not necessary for libs
package-lock.json
151 changes: 151 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1 +1,152 @@
'use strict'
const fp = require('fastify-plugin')

const { Errors } = require('./lib/index')

module.exports = fp(
function fastifyRacePlugin (fastify, globalOpts, next) {
const controllers = new Map()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks very leak-prone. Maybe use a WeakMap instead?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking about that at the first iteration, but I wasn't sure under which circumstances the onResponse cannot be called so the Map is not cleaned properly. But I think for avoiding unexpected issues would be better to go with a WeakMap as you suggested

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Btw, here is what do you recommend to use the key for the WeakMap? My initial thought is to take advantage of the request, as is ready to be gc'ed once the request is done. wdyt?

let error

if (globalOpts != null && typeof globalOpts !== 'object') {
return next(new Errors.BAD_PARAMS('object', typeof globalOpts))
}

globalOpts = Object.assign(
{},
{ handleOnError: true, onRequestClosed: null },
globalOpts
)

if (typeof globalOpts.handleOnError !== 'boolean') {
error = new Errors.BAD_PARAMS('boolean', typeof globalOpts.handleOnError)
} else if (
globalOpts.onRequestClosed != null &&
typeof globalOpts.onRequestClosed !== 'function'
) {
error = new Errors.BAD_PARAMS(
'function',
typeof globalOpts.onRequestClosed
)
}

fastify.decorateRequest('race', race)
fastify.addHook('onResponse', onResponseCleaner)

return next(error)

function onResponseCleaner (request, _reply, done) {
if (controllers.has(request.id)) {
const { controller, cbs } = controllers.get(request.id)

if (controller.signal.aborted === false) {
for (const cb of cbs) {
controller.signal.removeEventListener('abort', cb, {
once: true
})
}
}

controllers.delete(request.id)
}

done()
}

function race (opts = globalOpts) {
const { raw, id: reqId } = this
const handleError = typeof opts === 'function' ? true : opts.handleOnError
const cb = typeof opts === 'function' ? opts : opts.onRequestClosed

if (controllers.has(reqId)) {
const { controller: ctrl, cbs } = controllers.get(reqId)

if (cb != null) {
// TODO: handle when socket is destroyed already
ctrl.signal.addEventListener('abort', cb, {
once: true
})

raw.once('error', err => {
if (controllers.has(reqId)) {
const internalCtrl = controllers.get(reqId)
if (internalCtrl.signal.aborted === false) internalCtrl.abort(err)
}
})

controllers.set(reqId, { controller: ctrl, cbs: cbs.concat(cb) })
}

if (raw.socket.destroyed === true) {
process.nextTick(() => ctrl.abort(Errors.SOCKET_CLOSED(reqId)))
}

return ctrl.signal
} else {
// eslint-disable-next-line no-undef
const controller = new AbortController()

if (cb != null) {
controller.signal.addEventListener('abort', cb, {
once: true
})
}

if (cb == null) controller.signal.then = theneable.bind(this)

if (raw.socket.destroyed) {
process.nextTick(() => controller.abort(Errors.SOCKET_CLOSED(reqId)))
} else {
raw.once('close', () => {
if (controllers.has(reqId)) {
const { controller: ctrl } = controllers.get(reqId)
if (ctrl.signal.aborted === false) controller.abort()
}
})

if (handleError === true || cb != null) {
raw.once('error', err => {
if (controllers.has(reqId)) {
const { controller: ctrl } = controllers.get(reqId)
if (ctrl.signal.aborted === false) controller.abort(err)
}
})
}
}

controllers.set(reqId, { controller, cbs: cb != null ? [cb] : [] })

return controller.signal
}

function theneable (resolve, reject) {
const { controller, cbs } = controllers.get(reqId)

if (controller.signal.aborted === true) {
return reject(Errors.ALREADY_ABORTED(reqId))
}

try {
controller.signal.addEventListener('abort', theneableHandler, {
once: true
})

controllers.set(reqId, {
controller,
cbs: cbs.concat(theneableHandler)
})
} catch (err) {
reject(err)
}

function theneableHandler (evt) {
resolve(evt)
}
}
}
},
{
fastify: '>=3.24.1',
name: 'fastify-racing'
}
)
18 changes: 18 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const Errors = require('fastify-error')

module.exports = {
Errors: {
BAD_PARAMS: Errors(
'FST_PLUGIN_RACE_BAD_PARAM',
'Invalid param, expected %s but received %s'
),
ALREADY_ABORTED: Errors(
'FST_PLUGIN_RACE_ALREADY_ABORTED',
"Request with ID '%s' already aborted"
),
SOCKET_CLOSED: Errors(
'FST_PLUGIN_RACE_SOCKET_CLOSED',
"Socket for request with ID '%s' already closed"
)
}
}
19 changes: 12 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "<lib_name>",
"name": "fastify-racing",
"version": "0.0.0",
"description": "<description>",
"description": "Cancel any running operation at the right time on your request handler",
"main": "index.js",
"types": "index.d.ts",
"scripts": {
Expand All @@ -16,24 +16,29 @@
"keywords": [],
"repository": {
"type": "git",
"url": "git+https://github.com/metcoder95/<lib_name>.git"
"url": "git+https://github.com/metcoder95/fastify-racing.git"
},
"readme": "https://github.com/metcoder95/<lib_name>/blob/main/README.md",
"readme": "https://github.com/metcoder95/fastify-racing/blob/main/README.md",
"bugs": {
"url": "https://github.com/metcoder95/<lib_name>/issues"
"url": "https://github.com/metcoder95/fastify-racing/issues"
},
"author": "metcoder95 <[email protected]>",
"license": "MIT",
"devDependencies": {
"@types/node": "^14.17.6",
"@types/node": "^14.18.13",
"fastify": "^3.28.0",
"husky": "^7.0.2",
"nodemon": "^2.0.15",
"snazzy": "^9.0.0",
"standard": "^16.0.3",
"tap": "^15.0.10",
"tsd": "^0.17.0",
"typescript": "^4.4"
"typescript": "^4.4",
"undici": "^5.0.0"
},
"dependencies": {
"fastify-error": "^1.1.0",
"fastify-plugin": "^3.0.1"
},
"tsd": {
"directory": "test"
Expand Down
Loading