Skip to content

Commit

Permalink
Merge branch 'main' into patch-1
Browse files Browse the repository at this point in the history
  • Loading branch information
Nytelife26 authored Mar 23, 2021
2 parents 95b0595 + b3dd69f commit 943d425
Show file tree
Hide file tree
Showing 19 changed files with 220 additions and 128 deletions.
34 changes: 34 additions & 0 deletions .github/ISSUE_TEMPLATE/bug-report.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
---
name: Bug Report
about: Report an issue
title: ''
labels: bug
assignees: ''

---

## Bug Description

<!-- A clear and concise description of what the bug is. -->

## Reproducible By

<!-- A step by step list on how the bug can be reproduced for examination. -->

## Expected Behavior

<!-- A clear and concise description of what you expected to happen. -->

## Logs & Screenshots

<!-- If applicable, add screenshots to help explain your problem, or
alternatively add your console logs here. -->

## Environment

<!-- This is just your OS and environment information [e.g. Ubuntu 18.04 LTS,
Node v14.14.0] -->

### Additional context

<!-- Add any other context about the problem here. -->
28 changes: 28 additions & 0 deletions .github/ISSUE_TEMPLATE/feature-request.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
---
name: Feature Request
about: Make a suggestion on a feature or improvement for the project
title: ''
labels: enhancement
assignees: ''

---

## This would solve...

<!-- A clear and concise description of the problem this feature request relates
to, if applicable. -->

## The implementation should look like...

<!-- A clear and concise description of how you expect this to be resolved or
implemented. -->

## I have also considered...

<!-- A clear and concise description of any alternative solutions or features
you have considered. -->

## Additional context

<!-- Add any other context, screenshots or ideas about the feature request
here. -->
52 changes: 52 additions & 0 deletions .github/PULL_REQUEST_TEMPLATE/template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<!--
Before submitting a Pull Request, please read our contribution guidelines, which
can be found at CONTRIBUTING.md in the repository root.
For code changes:
1. Include tests for any bug fixes or new features.
2. Update documentation if relevant.
3. Ensure that tests and linting pass.
You will also need to ensure that your contribution complies with the
Developer's Certificate of Origin, outlined in CONTRIBUTING.md
-->

## This relates to...

<!-- List the issues this resolves or relates to here (if applicable) -->

## Rationale

<!-- Briefly explain the purpose of this pull request, if not already
justifiable with the above section. If it is, you may omit this section. -->

## Changes

<!-- Write a summary or list of changes here -->

### Features

<!-- List the new features here (if applicable), or write N/A if not -->

### Bug Fixes

<!-- List the fixed bugs here (if applicable), or write N/A if not -->

### Breaking Changes and Deprecations

<!-- List the breaking changes (changes that modify the existing API) and
deprecations (removed features) here -->

## Status

KEY: S = Skipped, x = complete

- [ ] I have read and agreed to the [Developer's Certificate of Origin][cert]
- [ ] Tested
- [ ] Benchmarked (**optional**)
- [ ] Documented
- [ ] Review ready
- [ ] In review
- [ ] Merge ready

[cert]: https://github.com/nodejs/undici/blob/main/CONTRIBUTING.md
1 change: 1 addition & 0 deletions .husky/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
_
4 changes: 4 additions & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npm run coverage
43 changes: 33 additions & 10 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@

const Client = require('./lib/core/client')
const errors = require('./lib/core/errors')
const Pool = require('./lib/pool')
const { Agent, request, stream, pipeline, setGlobalAgent } = require('./lib/agent')
const Pool = require('./lib/client-pool')
const { Agent, getGlobalAgent, setGlobalAgent } = require('./lib/agent')
const util = require('./lib/core/util')
const { InvalidArgumentError, InvalidReturnValueError } = require('./lib/core/errors')
const api = require('./lib/api')

Client.prototype.request = require('./lib/client-request')
Client.prototype.stream = require('./lib/client-stream')
Client.prototype.pipeline = require('./lib/client-pipeline')
Client.prototype.upgrade = require('./lib/client-upgrade')
Client.prototype.connect = require('./lib/client-connect')
Object.assign(Client.prototype, api)
Object.assign(Pool.prototype, api)

function undici (url, opts) {
return new Pool(url, opts)
Expand All @@ -22,7 +22,30 @@ module.exports.Client = Client
module.exports.errors = errors

module.exports.Agent = Agent
module.exports.request = request
module.exports.stream = stream
module.exports.pipeline = pipeline
module.exports.setGlobalAgent = setGlobalAgent
module.exports.getGlobalAgent = getGlobalAgent

function dispatchFromAgent (requestType) {
return (url, { agent = getGlobalAgent(), method = 'GET', ...opts } = {}, ...additionalArgs) => {
if (opts.path != null) {
throw new InvalidArgumentError('unsupported opts.path')
}

const { origin, pathname, search } = util.parseURL(url)
const path = `${pathname || '/'}${search || ''}`

const client = agent.get(origin)

if (client && typeof client[requestType] !== 'function') {
throw new InvalidReturnValueError(`Client returned from Agent.get() does not implement method ${requestType}`)
}

return client[requestType]({ ...opts, method, path }, ...additionalArgs)
}
}

module.exports.request = dispatchFromAgent('request')
module.exports.stream = dispatchFromAgent('stream')
module.exports.pipeline = dispatchFromAgent('pipeline')
module.exports.connect = dispatchFromAgent('connect')
module.exports.upgrade = dispatchFromAgent('upgrade')
67 changes: 26 additions & 41 deletions lib/agent.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,30 @@
'use strict'
const { InvalidArgumentError, InvalidReturnValueError } = require('./core/errors')
const Pool = require('./pool')
const { InvalidArgumentError } = require('./core/errors')
const Pool = require('./client-pool')
const Client = require('./core/client')
const util = require('./core/util')
const { kAgentOpts, kAgentCache } = require('./core/symbols')
const EventEmitter = require('events')

const kOnConnect = Symbol('onConnect')
const kOnDisconnect = Symbol('onDisconnect')
const kCache = Symbol('cache')
const kFactory = Symbol('factory')

function defaultFactory (origin, opts) {
return opts && opts.connections === 1
? new Client(origin, opts)
: new Pool(origin, opts)
}

class Agent extends EventEmitter {
constructor (opts) {
constructor ({ factory = defaultFactory, ...opts } = {}) {
super()

this[kAgentOpts] = opts
this[kAgentCache] = new Map()
if (typeof factory !== 'function') {
throw new InvalidArgumentError('factory must be a function.')
}

this[kFactory] = (origin) => factory(origin, opts)
this[kCache] = new Map()

const agent = this

Expand All @@ -25,7 +35,7 @@ class Agent extends EventEmitter {
this[kOnDisconnect] = function onDestroy (client, err) {
if (this.connected === 0 && this.size === 0) {
this.off('disconnect', agent[kOnDisconnect])
agent[kAgentCache].delete(this.origin)
agent[kCache].delete(this.origin)
}

agent.emit('disconnect', client, err)
Expand All @@ -37,35 +47,30 @@ class Agent extends EventEmitter {
throw new InvalidArgumentError('Origin must be a non-empty string.')
}

const self = this
let pool = self[kAgentCache].get(origin)
let pool = this[kCache].get(origin)

if (!pool) {
pool = self[kAgentOpts] && self[kAgentOpts].connections === 1
? new Client(origin, self[kAgentOpts])
: new Pool(origin, self[kAgentOpts])

pool
pool = this[kFactory](origin)
.on('connect', this[kOnConnect])
.on('disconnect', this[kOnDisconnect])

self[kAgentCache].set(origin, pool)
this[kCache].set(origin, pool)
}

return pool
}

close () {
const closePromises = []
for (const pool of this[kAgentCache].values()) {
for (const pool of this[kCache].values()) {
closePromises.push(pool.close())
}
return Promise.all(closePromises)
}

destroy () {
const destroyPromises = []
for (const pool of this[kAgentCache].values()) {
for (const pool of this[kCache].values()) {
destroyPromises.push(pool.destroy())
}
return Promise.all(destroyPromises)
Expand All @@ -81,32 +86,12 @@ function setGlobalAgent (agent) {
globalAgent = agent
}

function dispatchFromAgent (requestType) {
return (url, { agent = globalAgent, method = 'GET', ...opts } = {}, ...additionalArgs) => {
if (opts.path != null) {
throw new InvalidArgumentError('unsupported opts.path')
}

const { origin, pathname, search } = util.parseURL(url)

const path = `${pathname || '/'}${search || ''}`

const client = agent.get(origin)

if (client && typeof client[requestType] !== 'function') {
throw new InvalidReturnValueError(`Client returned from Agent.get() does not implement method ${requestType}`)
}

return client[requestType]({ ...opts, method, path }, ...additionalArgs)
}
function getGlobalAgent () {
return globalAgent
}

module.exports = {
request: dispatchFromAgent('request'),
stream: dispatchFromAgent('stream'),
pipeline: dispatchFromAgent('pipeline'),
connect: dispatchFromAgent('connect'),
upgrade: dispatchFromAgent('upgrade'),
setGlobalAgent,
getGlobalAgent,
Agent
}
2 changes: 1 addition & 1 deletion lib/abort-signal.js → lib/api/abort-signal.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { RequestAbortedError } = require('./core/errors')
const { RequestAbortedError } = require('../core/errors')

const kListener = Symbol('kListener')
const kSignal = Symbol('kSignal')
Expand Down
16 changes: 3 additions & 13 deletions lib/client-connect.js → lib/api/api-connect.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
'use strict'

const { InvalidArgumentError, RequestAbortedError } = require('./core/errors')
const { InvalidArgumentError, RequestAbortedError } = require('../core/errors')
const { AsyncResource } = require('async_hooks')
const util = require('./core/util')
const util = require('../core/util')
const { addSignal, removeSignal } = require('./abort-signal')

class ConnectHandler extends AsyncResource {
Expand Down Expand Up @@ -77,17 +77,7 @@ function connect (opts, callback) {

try {
const connectHandler = new ConnectHandler(opts, callback)
const {
path,
headers,
signal
} = opts
this.dispatch({
path,
method: 'CONNECT',
headers,
signal
}, connectHandler)
this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler)
} catch (err) {
process.nextTick(callback, err, { opaque: opts && opts.opaque })
}
Expand Down
20 changes: 3 additions & 17 deletions lib/client-pipeline.js → lib/api/api-pipeline.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ const {
InvalidArgumentError,
InvalidReturnValueError,
RequestAbortedError
} = require('./core/errors')
const util = require('./core/util')
} = require('../core/errors')
const util = require('../core/util')
const { AsyncResource } = require('async_hooks')
const { assert } = require('console')
const { addSignal, removeSignal } = require('./abort-signal')
Expand Down Expand Up @@ -225,21 +225,7 @@ class PipelineHandler extends AsyncResource {
function pipeline (opts, handler) {
try {
const pipelineHandler = new PipelineHandler(opts, handler)
const {
path,
method,
headers,
idempotent,
signal
} = opts
this.dispatch({
path,
method,
body: pipelineHandler.req,
headers,
idempotent,
signal
}, pipelineHandler)
this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler)
return pipelineHandler.ret
} catch (err) {
return new PassThrough().destroy(err)
Expand Down
4 changes: 2 additions & 2 deletions lib/client-request.js → lib/api/api-request.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ const { Readable } = require('stream')
const {
InvalidArgumentError,
RequestAbortedError
} = require('./core/errors')
const util = require('./core/util')
} = require('../core/errors')
const util = require('../core/util')
const { AsyncResource } = require('async_hooks')
const { addSignal, removeSignal } = require('./abort-signal')

Expand Down
4 changes: 2 additions & 2 deletions lib/client-stream.js → lib/api/api-stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ const {
InvalidArgumentError,
InvalidReturnValueError,
RequestAbortedError
} = require('./core/errors')
const util = require('./core/util')
} = require('../core/errors')
const util = require('../core/util')
const { AsyncResource } = require('async_hooks')
const { addSignal, removeSignal } = require('./abort-signal')

Expand Down
Loading

0 comments on commit 943d425

Please sign in to comment.