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

add dispatcher option to Request #2831

Merged
merged 1 commit into from
Feb 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 0 additions & 2 deletions lib/web/cache/cache.js
Expand Up @@ -10,7 +10,6 @@ const { kState } = require('../fetch/symbols')
const { fetching } = require('../fetch/index')
const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = require('../fetch/util')
const assert = require('node:assert')
const { getGlobalDispatcher } = require('../../global')

/**
* @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation
Expand Down Expand Up @@ -150,7 +149,6 @@ class Cache {
// 5.7
fetchControllers.push(fetching({
request: r,
dispatcher: getGlobalDispatcher(),
processResponse (response) {
// 1.
if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) {
Expand Down
6 changes: 1 addition & 5 deletions lib/web/eventsource/eventsource.js
Expand Up @@ -9,7 +9,6 @@ const { EventSourceStream } = require('./eventsource-stream')
const { parseMIMEType } = require('../fetch/dataURL')
const { MessageEvent } = require('../websocket/events')
const { isNetworkError } = require('../fetch/response')
const { getGlobalDispatcher } = require('../../global')
const { delay } = require('./util')

let experimentalWarned = false
Expand Down Expand Up @@ -316,10 +315,7 @@ class EventSource extends EventTarget {
})
}

this.#controller = fetching({
...fetchParam,
dispatcher: getGlobalDispatcher()
})
this.#controller = fetching(fetchParam)
}

/**
Expand Down
6 changes: 3 additions & 3 deletions lib/web/fetch/index.js
Expand Up @@ -47,7 +47,7 @@ const {
createInflate,
extractMimeType
} = require('./util')
const { kState } = require('./symbols')
const { kState, kDispatcher } = require('./symbols')
const assert = require('node:assert')
const { safelyExtractBody, extractBody } = require('./body')
const {
Expand Down Expand Up @@ -239,7 +239,7 @@ function fetch (input, init = undefined) {
request,
processResponseEndOfBody: handleFetchDone,
processResponse,
dispatcher: init?.dispatcher ?? getGlobalDispatcher() // undici
dispatcher: requestObject[kDispatcher] // undici
})

// 14. Return p.
Expand Down Expand Up @@ -361,7 +361,7 @@ function fetching ({
processResponseEndOfBody,
processResponseConsumeBody,
useParallelQueue = false,
dispatcher // undici
dispatcher = getGlobalDispatcher() // undici
}) {
// Ensure that the dispatcher is set accordingly
assert(dispatcher)
Expand Down
10 changes: 9 additions & 1 deletion lib/web/fetch/request.js
Expand Up @@ -24,7 +24,7 @@ const {
requestDuplex
} = require('./constants')
const { kEnumerableProperty } = util
const { kHeaders, kSignal, kState, kGuard, kRealm } = require('./symbols')
const { kHeaders, kSignal, kState, kGuard, kRealm, kDispatcher } = require('./symbols')
const { webidl } = require('./webidl')
const { getGlobalOrigin } = require('./global')
const { URLSerializer } = require('./dataURL')
Expand Down Expand Up @@ -78,6 +78,8 @@ class Request {

// 5. If input is a string, then:
if (typeof input === 'string') {
this[kDispatcher] = init.dispatcher

// 1. Let parsedURL be the result of parsing input with baseURL.
// 2. If parsedURL is failure, then throw a TypeError.
let parsedURL
Expand All @@ -101,6 +103,8 @@ class Request {
// 5. Set fallbackMode to "cors".
fallbackMode = 'cors'
} else {
this[kDispatcher] = input[kDispatcher]
Copy link
Contributor

Choose a reason for hiding this comment

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

Shouldn't this like look like this? Allowing to override the dispatcher when creating a new request from an existing one.

Suggested change
this[kDispatcher] = input[kDispatcher]
this[kDispatcher] = init.dispatcher || input[kDispatcher]

Copy link
Contributor

Choose a reason for hiding this comment

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

Can you Provide a Pr and test?

Copy link
Contributor

Choose a reason for hiding this comment

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


// 6. Otherwise:

// 7. Assert: input is a Request object.
Expand Down Expand Up @@ -979,6 +983,10 @@ webidl.converters.RequestInit = webidl.dictionaryConverter([
key: 'duplex',
converter: webidl.converters.DOMString,
allowedValues: requestDuplex
},
{
key: 'dispatcher', // undici specific option
converter: webidl.converters.any
}
])

Expand Down
3 changes: 2 additions & 1 deletion lib/web/fetch/symbols.js
Expand Up @@ -6,5 +6,6 @@ module.exports = {
kSignal: Symbol('signal'),
kState: Symbol('state'),
kGuard: Symbol('guard'),
kRealm: Symbol('realm')
kRealm: Symbol('realm'),
kDispatcher: Symbol('dispatcher')
}
2 changes: 1 addition & 1 deletion lib/web/fetch/webidl.js
Expand Up @@ -3,7 +3,7 @@
const { types } = require('node:util')
const { toUSVString } = require('../../core/util')

/** @type {import('../../types/webidl').Webidl} */
/** @type {import('../../../types/webidl').Webidl} */
const webidl = {}
webidl.converters = {}
webidl.util = {}
Expand Down
3 changes: 1 addition & 2 deletions lib/web/websocket/connection.js
Expand Up @@ -13,7 +13,6 @@ const { CloseEvent } = require('./events')
const { makeRequest } = require('../fetch/request')
const { fetching } = require('../fetch/index')
const { Headers } = require('../fetch/headers')
const { getGlobalDispatcher } = require('../../global')
const { kHeadersList } = require('../../core/symbols')

/** @type {import('crypto')} */
Expand Down Expand Up @@ -100,7 +99,7 @@ function establishWebSocketConnection (url, protocols, ws, onEstablish, options)
const controller = fetching({
request,
useParallelQueue: true,
dispatcher: options.dispatcher ?? getGlobalDispatcher(),
dispatcher: options.dispatcher,
processResponse (response) {
// 1. If response is a network error or its status is not 101,
// fail the WebSocket connection.
Expand Down
32 changes: 32 additions & 0 deletions test/fetch/issue-2828.js
@@ -0,0 +1,32 @@
'use strict'

const { once } = require('node:events')
const { createServer } = require('node:http')
const { test } = require('node:test')
const { Agent, Request, fetch } = require('../..')
const { tspl } = require('@matteo.collina/tspl')

test('issue #2828, dispatcher is allowed in RequestInit options', async (t) => {
const { deepStrictEqual } = tspl(t, { plan: 1 })

class CustomAgent extends Agent {
dispatch (options, handler) {
options.headers['x-my-header'] = 'hello'
return super.dispatch(...arguments)
}
}

const server = createServer((req, res) => {
deepStrictEqual(req.headers['x-my-header'], 'hello')
res.end()
}).listen(0)

t.after(server.close.bind(server))
await once(server, 'listening')

const request = new Request(`http://localhost:${server.address().port}`, {
dispatcher: new CustomAgent()
})

await fetch(request)
})