mirror of
https://github.com/nodejs/node.git
synced 2026-11-24 21:50:36 -05:00
deps: update undici to 8.12.2
PR-URL: https://github.com/nodejs/node/pull/66721 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com> Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
This commit is contained in:
1 parent
e5cae10148
commit
7895a5cd2d
109 files changed
+13226
-2123
No files matched your search
Vendored
+86
-4
@@ -2,6 +2,7 @@
|
||||
|
||||
* [Guides](#guides)
|
||||
* [Update `llhttp`](#update-llhttp)
|
||||
* [Update `milo`](#update-milo)
|
||||
* [Lint](#lint)
|
||||
* [Test](#test)
|
||||
* [Coverage](#coverage)
|
||||
@@ -59,7 +60,7 @@ npm i
|
||||
> This requires [docker](https://www.docker.com/) installed on your machine.
|
||||
|
||||
```bash
|
||||
npm run build:wasm
|
||||
npm run build-wasm
|
||||
```
|
||||
|
||||
#### Copy the sources to `undici`
|
||||
@@ -83,13 +84,94 @@ cp src/native/api.h build/llhttp.h <your-path-to-undici>/deps/llhttp/include/
|
||||
```bash
|
||||
cd <your-path-to-undici>
|
||||
|
||||
npm run build:wasm
|
||||
npm run build:llhttp
|
||||
```
|
||||
|
||||
#### Commit the contents of lib/llhttp
|
||||
|
||||
Create a commit which includes all of the updated files in lib/llhttp.
|
||||
|
||||
<a id="update-milo"></a>
|
||||
### Update `milo`
|
||||
|
||||
Milo is built from the upstream sources vendored in `deps/milo`, using its own
|
||||
Dockerfile rather than a prebuilt npm package. Updating it is manual, like llhttp.
|
||||
The standalone release CommonJS modules and their license are saved in `lib/milo`.
|
||||
|
||||
The current vendored release is 0.8.5 at commit
|
||||
`2ec4642184f20cd1803e30650becc54bbd575c6c`.
|
||||
|
||||
#### Clone milo and checkout a release
|
||||
|
||||
```sh
|
||||
git clone https://github.com/ShogunPanda/milo.git
|
||||
cd milo
|
||||
git checkout v0.8.5
|
||||
```
|
||||
|
||||
#### Copy the sources into Undici
|
||||
|
||||
Replace the previous contents of `deps/milo` with the following files and
|
||||
directories from the selected release, preserving their layout:
|
||||
|
||||
```sh
|
||||
cp Dockerfile Makefile.toml rust-toolchain.toml LICENSE.md README.md CODE_OF_CONDUCT.md <your-path-to-undici>/deps/milo/
|
||||
cp -R macros scripts <your-path-to-undici>/deps/milo/
|
||||
mkdir -p <your-path-to-undici>/deps/milo/parser
|
||||
cp parser/*.toml parser/*.lock parser/*.md <your-path-to-undici>/deps/milo/parser/
|
||||
cp -R parser/src <your-path-to-undici>/deps/milo/parser/
|
||||
```
|
||||
|
||||
Keep the Cargo manifests and all three lockfiles (`macros/Cargo.lock`,
|
||||
`parser/Cargo.lock` and `scripts/Cargo.lock`), Rust binding generators and JavaScript
|
||||
template. Preserve Undici's build adjustments: the Docker image digest, pinned
|
||||
cargo-make version, Binaryen checksums and `--locked` Cargo builds. Update the
|
||||
checksums for both Linux architectures whenever Binaryen is updated.
|
||||
Do not copy `parser/tests`, `parser/examples`, `.git`, upstream workflows,
|
||||
`target`, `dist`, or prebuilt npm packages. Use a clean checkout so no local build
|
||||
outputs are included. When selecting a newer release, update the version and
|
||||
full commit recorded above.
|
||||
|
||||
#### Build and copy the release artifacts
|
||||
|
||||
Docker is the only build tool required on the host. The upstream image installs
|
||||
Rust, cargo-make and Binaryen, then runs `makers wasm` in an internal copy of the
|
||||
read-only source checkout. See [milo's Docker build instructions](https://github.com/ShogunPanda/milo#building-webassembly-with-docker).
|
||||
|
||||
From Undici, build the vendored sources:
|
||||
|
||||
```sh
|
||||
cd <your-path-to-undici>
|
||||
npm run build:milo
|
||||
```
|
||||
|
||||
`build/milo.js` follows those instructions, mounts `deps/milo` read-only, and
|
||||
copies only these release artifacts:
|
||||
|
||||
```text
|
||||
release/package-cjs/src/simd/index.js -> lib/milo/simd.js
|
||||
release/package-cjs/src/no-simd/index.js -> lib/milo/no-simd.js
|
||||
release/package-cjs/LICENSE.md -> lib/milo/LICENSE.md
|
||||
```
|
||||
|
||||
Each JavaScript module already embeds its WASM binary in base64. Separate `.wasm`
|
||||
files, unbundled modules, debug packages and package metadata are not copied.
|
||||
Temporary Docker outputs are removed when the script finishes. The script does
|
||||
not download or update milo's sources; Docker still downloads the image and build
|
||||
dependencies as needed.
|
||||
|
||||
The shared-builtin CI job removes the bundled Milo modules and rebuilds them
|
||||
before compiling Node.js, so that it cannot silently reuse prebuilt artifacts.
|
||||
The npm package contains only the license and the two bundled JavaScript modules;
|
||||
`lib/milo/binary`, `lib/milo/src` and separate WASM files are excluded.
|
||||
|
||||
#### Submit the update
|
||||
|
||||
Include the updated sources in `deps/milo`, generated files in `lib/milo` and
|
||||
the documentation update in a manually prepared PR. This step prepares milo's
|
||||
build inputs; it does not modify
|
||||
the runtime parser, llhttp's build script or any workflows.
|
||||
|
||||
<a id="update-wpts"></a>
|
||||
### Update `WPTs`
|
||||
|
||||
@@ -176,9 +258,9 @@ Use the "Create release PR" github action to generate a release PR.
|
||||
If you are packaging `undici` for a distro, this might help if you would like to use
|
||||
an unbundled version instead of bundling one in `libnode.so`.
|
||||
|
||||
To enable this, pass `EXTERNAL_PATH=/path/to/global/node_modules/undici` to `build/wasm.js`.
|
||||
To enable this, pass `EXTERNAL_PATH=/path/to/global/node_modules/undici` to `build/llhttp.js`.
|
||||
Pass this path with `loader.js` appended to `--shared-builtin-undici/undici-path` in Node.js's `configure.py`.
|
||||
If building on a non-Alpine Linux distribution, you may need to also set the `WASM_CC`, `WASM_CFLAGS`, `WASM_LDFLAGS` and `WASM_LDLIBS` environment variables before running `build/wasm.js`.
|
||||
If building on a non-Alpine Linux distribution, you may need to also set the `WASM_CC`, `WASM_CFLAGS`, `WASM_LDFLAGS` and `WASM_LDLIBS` environment variables before running `build/llhttp.js`.
|
||||
Similarly, you can set the `WASM_OPT` environment variable to utilize your own `wasm-opt` optimizer.
|
||||
|
||||
<a id="benchmarks"></a>
|
||||
|
||||
Vendored
+25
-3
@@ -86,6 +86,24 @@ Using [benchmark-http2.js](https://github.com/nodejs/undici/blob/main/benchmarks
|
||||
|
||||
Node.js includes a built-in `fetch()` implementation powered by undici starting from Node.js v18. However, there are important differences between using the built-in fetch and installing undici as a separate module.
|
||||
|
||||
### WebAssembly requirement
|
||||
|
||||
Undici's HTTP/1 parser requires WebAssembly. There is no alternative parser when
|
||||
WebAssembly is unavailable, for example in Node.js configurations where
|
||||
`--jitless` disables it. The existence of `fetch` does not imply that it can make
|
||||
HTTP/1 requests in that environment.
|
||||
|
||||
When the HTTP/1 parser is needed without WebAssembly, Client and dispatcher
|
||||
requests fail with an `Error` whose code is `ERR_WEBASSEMBLY_NOT_SUPPORTED`.
|
||||
`fetch` rejects with a `TypeError` carrying that error in `error.cause`. Importing
|
||||
Undici, accessing `fetch`, and using `Headers`, `FormData`, `Request`, or `Response`
|
||||
do not themselves require the HTTP/1 parser.
|
||||
|
||||
The error is defined locally in Undici and does not depend on Node.js providing
|
||||
that error code. For built-in fetch, this behavior depends on the bundled Undici
|
||||
version. Node.js receives upstream fixes through its normal vendored Undici
|
||||
update, rather than changes to the generated bundle alone.
|
||||
|
||||
### Built-in Fetch (Node.js v18+)
|
||||
|
||||
Node.js's built-in fetch is powered by a bundled version of undici:
|
||||
@@ -773,14 +791,18 @@ and `undici.Agent`) which will enable the family autoselection algorithm when es
|
||||
|
||||
## Collaborators
|
||||
|
||||
* [__Daniele Belardi__](https://github.com/dnlup), <https://www.npmjs.com/~dnlup>
|
||||
* [__Ethan Arrowood__](https://github.com/ethan-arrowood), <https://www.npmjs.com/~ethan_arrowood>
|
||||
* [__Aras Abbasi__](https://github.com/Uzlopak)
|
||||
* [__Carlos Fuentes__](https://github.com/metcoder95), <https://www.npmjs.com/~metcoder95>
|
||||
* [__Ethan Arrowood__](https://github.com/Ethan-Arrowood), <https://www.npmjs.com/~ethan_arrowood>
|
||||
* [__Matteo Collina__](https://github.com/mcollina), <https://www.npmjs.com/~matteo.collina>
|
||||
* [__Matthew Aitken__](https://github.com/KhafraDev), <https://www.npmjs.com/~khaf>
|
||||
* [__Mert Can Altin__](https://github.com/mertcanaltin), <https://www.npmjs.com/~mertcanaltin>
|
||||
* [__Robert Nagy__](https://github.com/ronag), <https://www.npmjs.com/~ronag>
|
||||
* [__Szymon Marczak__](https://github.com/szmarczak), <https://www.npmjs.com/~szmarczak>
|
||||
* [__Trivikram Kamat__](https://github.com/trivikr), <https://www.npmjs.com/~trivikr>
|
||||
* [__tsctx__](https://github.com/tsctx)
|
||||
|
||||
## Past Collaborators
|
||||
* [__Szymon Marczak__](https://github.com/szmarczak), <https://www.npmjs.com/~szmarczak>
|
||||
* [__Tomas Della Vedova__](https://github.com/delvedor), <https://www.npmjs.com/~delvedor>
|
||||
|
||||
### Releasers
|
||||
|
||||
@@ -62,7 +62,7 @@ if (process.argv[2] === '--docker') {
|
||||
cmd += ` --mount type=bind,source=${ROOT}/lib/llhttp,target=/home/node/build/lib/llhttp \
|
||||
--mount type=bind,source=${ROOT}/build,target=/home/node/build/build \
|
||||
--mount type=bind,source=${ROOT}/deps,target=/home/node/build/deps \
|
||||
-t ${WASM_BUILDER_CONTAINER} node build/wasm.js`
|
||||
-t ${WASM_BUILDER_CONTAINER} node build/llhttp.js`
|
||||
console.log(`> ${cmd}\n\n`)
|
||||
execSync(cmd, { stdio: 'inherit' })
|
||||
process.exit(0) // eslint-disable-line n/no-process-exit
|
||||
Vendored
+53
@@ -0,0 +1,53 @@
|
||||
'use strict'
|
||||
|
||||
const { execFileSync } = require('node:child_process')
|
||||
const { chmod, mkdtemp, readFile, cp, rm, mkdir } = require('node:fs/promises')
|
||||
const { resolve } = require('node:path')
|
||||
|
||||
const artifacts = {
|
||||
'release/package-cjs/src/no-simd/index.js': 'no-simd.js',
|
||||
'release/package-cjs/src/simd/index.js': 'simd.js',
|
||||
'release/package-cjs/LICENSE.md': 'LICENSE.md'
|
||||
}
|
||||
|
||||
function docker (...args) {
|
||||
return execFileSync('docker', args, { stdio: 'inherit' })
|
||||
}
|
||||
|
||||
async function buildMilo () {
|
||||
// Setup some folders
|
||||
const source = resolve(__dirname, '../deps/milo')
|
||||
const destination = resolve(__dirname, '../lib/milo')
|
||||
const temporary = await mkdtemp(resolve(__dirname, '../deps/.build-'))
|
||||
const imageFile = resolve(temporary, 'id')
|
||||
|
||||
try {
|
||||
await chmod(temporary, 0o777)
|
||||
docker('build', '--iidfile', imageFile, source)
|
||||
|
||||
const image = (await readFile(imageFile, 'utf8')).trim()
|
||||
if (!/^sha256:[a-f0-9]{64}$/.test(image)) {
|
||||
throw new Error('Docker did not return a valid milo build image ID')
|
||||
}
|
||||
|
||||
// Follow upstream's README: sources are read-only; only results are mounted writable.
|
||||
const sourceMount = `type=bind,source=${source},target=/src,readonly`
|
||||
const outputMount = `type=bind,source=${temporary},target=/output`
|
||||
docker('run', '--rm', '--mount', sourceMount, '--mount', outputMount, image)
|
||||
|
||||
// Clean the destination directory and recreate it before copying artifacts.
|
||||
await rm(destination, { recursive: true, force: true })
|
||||
await mkdir(destination, { recursive: true })
|
||||
|
||||
// Copy artifacts from the temporary build output to the destination directory.
|
||||
for (const [from, to] of Object.entries(artifacts)) {
|
||||
await cp(resolve(temporary, from), resolve(destination, to))
|
||||
}
|
||||
|
||||
console.log(`Milo release artifacts saved in ${destination}`)
|
||||
} finally {
|
||||
await rm(temporary, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
buildMilo()
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
In the interest of fostering an open and welcoming environment, we as
|
||||
contributors and maintainers pledge to make participation in our project and
|
||||
our community a harassment-free experience for everyone, regardless of age, body
|
||||
size, disability, ethnicity, sex characteristics, gender identity and expression,
|
||||
level of experience, education, socio-economic status, nationality, personal
|
||||
appearance, race, religion, or sexual identity and orientation.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to creating a positive environment
|
||||
include:
|
||||
|
||||
- Using welcoming and inclusive language
|
||||
- Being respectful of differing viewpoints and experiences
|
||||
- Gracefully accepting constructive criticism
|
||||
- Focusing on what is best for the community
|
||||
- Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
- The use of sexualized language or imagery and unwelcome sexual attention or
|
||||
advances
|
||||
- Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
- Public or private harassment
|
||||
- Publishing others' private information, such as a physical or electronic
|
||||
address, without explicit permission
|
||||
- Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Our Responsibilities
|
||||
|
||||
Project maintainers are responsible for clarifying the standards of acceptable
|
||||
behavior and are expected to take appropriate and fair corrective action in
|
||||
response to any instances of unacceptable behavior.
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or
|
||||
reject comments, commits, code, wiki edits, issues, and other contributions
|
||||
that are not aligned to this Code of Conduct, or to ban temporarily or
|
||||
permanently any contributor for other behaviors that they deem inappropriate,
|
||||
threatening, offensive, or harmful.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies within all project spaces, and it also applies when
|
||||
an individual is representing the project or its community in public spaces.
|
||||
Examples of representing a project or community include using an official
|
||||
project e-mail address, posting via an official social media account, or acting
|
||||
as an appointed representative at an online or offline event. Representation of
|
||||
a project may be further defined and clarified by project maintainers.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported by contacting the project team at [INSERT EMAIL ADDRESS]. All
|
||||
complaints will be reviewed and investigated and will result in a response that
|
||||
is deemed necessary and appropriate to the circumstances. The project team is
|
||||
obligated to maintain confidentiality with regard to the reporter of an incident.
|
||||
Further details of specific enforcement policies may be posted separately.
|
||||
|
||||
Project maintainers who do not follow or enforce the Code of Conduct in good
|
||||
faith may face temporary or permanent repercussions as determined by other
|
||||
members of the project's leadership.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
|
||||
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
|
||||
For answers to common questions about this code of conduct, see
|
||||
https://www.contributor-covenant.org/faq
|
||||
Vendored
+36
@@ -0,0 +1,36 @@
|
||||
FROM ghcr.io/nodejs/wasm-builder@sha256:542fdbef9fa6eb003cc1eb89a9f3e6b967359471fdb29db4910c54474e70911d
|
||||
|
||||
USER root
|
||||
|
||||
ARG BINARYEN_VERSION=123
|
||||
ARG RUST_TOOLCHAIN=nightly-2026-07-29
|
||||
ARG CARGO_MAKE_VERSION=0.37.24
|
||||
|
||||
RUN set -eux; \
|
||||
case "$(uname -m)" in \
|
||||
x86_64) binaryen_arch=x86_64; binaryen_sha256=e959f2170af4c20c552e9de3a0253704d6a9d2766e8fdb88e4d6ac4bae9388fe ;; \
|
||||
aarch64) binaryen_arch=aarch64; binaryen_sha256=4b6bd61ba6cd3b18c993b4657d93426c782f9b91b74be0d38018cd8be1319376 ;; \
|
||||
*) echo "Unsupported architecture: $(uname -m)" >&2; exit 1 ;; \
|
||||
esac; \
|
||||
wget -q "https://github.com/WebAssembly/binaryen/releases/download/version_${BINARYEN_VERSION}/binaryen-version_${BINARYEN_VERSION}-${binaryen_arch}-linux.tar.gz" -O /tmp/binaryen.tar.gz; \
|
||||
echo "${binaryen_sha256} /tmp/binaryen.tar.gz" | sha256sum -c -; \
|
||||
tar -xzf /tmp/binaryen.tar.gz -C /tmp; \
|
||||
install -m 0755 "/tmp/binaryen-version_${BINARYEN_VERSION}/bin/wasm-opt" /usr/local/bin/wasm-opt; \
|
||||
rm -rf /tmp/binaryen.tar.gz "/tmp/binaryen-version_${BINARYEN_VERSION}"
|
||||
|
||||
USER node
|
||||
|
||||
RUN set -eux; \
|
||||
rustup toolchain install "${RUST_TOOLCHAIN}" --profile minimal; \
|
||||
rustup target add wasm32-unknown-unknown --toolchain "${RUST_TOOLCHAIN}"; \
|
||||
rustup component add rust-src --toolchain "${RUST_TOOLCHAIN}"; \
|
||||
cargo +"${RUST_TOOLCHAIN}" install cargo-make --version "${CARGO_MAKE_VERSION}" --locked
|
||||
|
||||
ENV PATH="/home/node/.cargo/bin:${PATH}"
|
||||
ENV RUSTUP_TOOLCHAIN=${RUST_TOOLCHAIN}
|
||||
|
||||
WORKDIR /workspace/parser
|
||||
|
||||
# Build from an internal copy so Cargo and the build tasks cannot modify the
|
||||
# read-only source mount. Only the generated WASM artifacts are written out.
|
||||
CMD ["sh", "-ec", "cp -a /src /tmp/milo && cd /tmp/milo/parser && makers wasm && mkdir -p /output && cp -a /tmp/milo/dist/wasm/. /output/"]
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
ISC License
|
||||
|
||||
Copyright (c) 2023, and above Paolo Insogna, NearForm and other contributors
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
[config]
|
||||
skip_core_tasks = true
|
||||
|
||||
[tasks.default]
|
||||
dependencies = ["build"]
|
||||
|
||||
[tasks.build]
|
||||
script = ["cd parser", "makers build"]
|
||||
|
||||
[tasks.test]
|
||||
dependencies = ["test:rust", "test:wasm"]
|
||||
|
||||
[tasks."test:rust"]
|
||||
script = ["cd parser", "cargo test"]
|
||||
|
||||
[tasks."test:wasm"]
|
||||
script = ["cd parser", "makers test:wasm"]
|
||||
|
||||
[tasks.format]
|
||||
dependencies = ["format:rust", "format:js", "format:cpp"]
|
||||
|
||||
[tasks.lint]
|
||||
dependencies = ["lint:rust", "lint:js"]
|
||||
|
||||
[tasks.clean]
|
||||
dependencies = ["clean:rust", "clean:dist", "clean:tmp"]
|
||||
|
||||
[tasks.benchmarks]
|
||||
dependencies = ["benchmarks:cpp", "benchmarks:wasm"]
|
||||
|
||||
[tasks.references]
|
||||
dependencies = ["references:rust", "references:cpp", "references:wasm"]
|
||||
|
||||
[tasks."llhttp:import"]
|
||||
script = ["cd parser", "makers scripts:build", "../scripts/target/release/import-llhttp-tests ${1} ."]
|
||||
|
||||
[tasks."llhttp:review"]
|
||||
script = ["cd parser", "cargo run --example llhttp -- --review ${1}"]
|
||||
|
||||
[tasks."llhttp:show"]
|
||||
script = ["cd parser", "cargo run --example llhttp -- --show ${1}"]
|
||||
|
||||
[tasks."llhttp:update"]
|
||||
script = ["cd parser", "cargo run --example llhttp -- --update ${1}"]
|
||||
|
||||
[tasks."clean:rust"]
|
||||
script = [
|
||||
"cd macros",
|
||||
"cargo clean",
|
||||
"cd ../parser",
|
||||
"cargo clean",
|
||||
"cd ../references/rust",
|
||||
"cargo clean",
|
||||
"cd ../../scripts",
|
||||
"cargo clean",
|
||||
]
|
||||
|
||||
[tasks."clean:dist"]
|
||||
command = "rm"
|
||||
args = ["-rf", "dist"]
|
||||
|
||||
[tasks."clean:tmp"]
|
||||
command = "rm"
|
||||
args = ["-rf", "tmp"]
|
||||
|
||||
[tasks."lint:fix"]
|
||||
dependencies = ["lint:rust:fix", "lint:js:fix"]
|
||||
|
||||
[tasks."format:rust"]
|
||||
script = [
|
||||
"cd macros",
|
||||
"cargo fmt",
|
||||
"cd ../parser",
|
||||
"cargo fmt",
|
||||
"cd ../references/rust",
|
||||
"cargo fmt",
|
||||
"cd ../../scripts",
|
||||
"cargo fmt",
|
||||
]
|
||||
|
||||
[tasks."format:cpp"]
|
||||
command = "clang-format"
|
||||
args = [
|
||||
"-style=file:clang-format.yml",
|
||||
"-i",
|
||||
"benchmarks/cpp/src/main.cc",
|
||||
"references/cpp/src/reference.cc",
|
||||
"references/cpp/src/readme.cc",
|
||||
]
|
||||
|
||||
[tasks."format:js"]
|
||||
command = "pnpm"
|
||||
args = ["run", "format"]
|
||||
|
||||
[tasks."lint:rust"]
|
||||
script = [
|
||||
"cd macros",
|
||||
"cargo clippy",
|
||||
"cd ../parser",
|
||||
"cargo clippy",
|
||||
"cd ../references/rust",
|
||||
"cargo clippy",
|
||||
"cd ../../scripts",
|
||||
"cargo clippy",
|
||||
]
|
||||
|
||||
[tasks."lint:rust:fix"]
|
||||
script = [
|
||||
"cd macros",
|
||||
"cargo clippy --fix --allow-dirty",
|
||||
"cd ../parser",
|
||||
"cargo clippy --fix --allow-dirty",
|
||||
"cd ../references/rust",
|
||||
"cargo clippy --fix --allow-dirty",
|
||||
"cd ../../scripts",
|
||||
"cargo clippy --fix --allow-dirty",
|
||||
]
|
||||
|
||||
[tasks."lint:js"]
|
||||
command = "pnpm"
|
||||
args = ["run", "lint"]
|
||||
|
||||
[tasks."lint:js:fix"]
|
||||
command = "pnpm"
|
||||
args = ["run", "lint", "--fix"]
|
||||
|
||||
[tasks."benchmarks:cpp"]
|
||||
script = ["cd benchmarks/cpp", "makers benchmarks"]
|
||||
|
||||
[tasks."benchmarks:wasm"]
|
||||
script = ["cd benchmarks/wasm", "makers benchmarks"]
|
||||
|
||||
[tasks."references:rust"]
|
||||
script = ["cd references/rust", "makers test"]
|
||||
|
||||
[tasks."references:cpp"]
|
||||
script = ["cd references/cpp", "makers test"]
|
||||
|
||||
[tasks."references:wasm"]
|
||||
script = ["cd references/wasm", "makers test"]
|
||||
Vendored
+349
@@ -0,0 +1,349 @@
|
||||
# @perseveranza-pets/milo
|
||||
|
||||
Milo is a fast and embeddable HTTP/1.1 parser written in [Rust][rust].
|
||||
|
||||
Milo can report parser activity through callbacks or through parser-owned event buffers. See the language-specific API docs for event decoding details: [JavaScript](./docs/js.md), [Rust](./docs/rust.md), and [C++](./docs/cpp.md).
|
||||
|
||||
## Support Matrix
|
||||
|
||||
Milo supports strict HTTP/1.1 message parsing for Rust, C++, and JavaScript via WebAssembly.
|
||||
|
||||
| Target | Status | Artifact |
|
||||
| ---------- | --------- | --------------------------------------------- |
|
||||
| Rust | Supported | `milo` crate |
|
||||
| C++ | Supported | `milo.h` and `libmilo.a` |
|
||||
| JavaScript | Supported | `@perseveranza-pets/milo` WebAssembly package |
|
||||
| CLI | Supported | `milo-parser` binary |
|
||||
|
||||
Milo intentionally rejects HTTP/0.9, HTTP/1.0, RTSP, obs-fold, bare LF, and bare CR. It does not parse HTTP/2 messages, except for strict `PRI * HTTP/2.0` switch-over detection.
|
||||
|
||||
For security and ambiguity reduction, Milo rejects request bodies on `GET` and `HEAD`. Responses to `HEAD` are application context: callers must use `skip_body` when they know a response has no body because it belongs to a `HEAD` request.
|
||||
|
||||
Use `max_body_payload` when an integration needs to cap body payload consumed by a single parse call. `0` means unlimited. Reaching the limit returns normally with unconsumed input left for the next parse call.
|
||||
|
||||
Use `suspend_after_headers` when an integration needs to inspect headers before body parsing starts. Parsing returns after consuming the header terminator and can continue with the next parse call.
|
||||
|
||||
For full parser scope, strictness, and protocol behavior, see [Milo Design](./docs/design.md).
|
||||
|
||||
## How to use it (JavaScript via WebAssembly)
|
||||
|
||||
Install it from npm:
|
||||
|
||||
```
|
||||
npm install @perseveranza-pets/milo
|
||||
```
|
||||
|
||||
For CommonJS projects, install the CJS-only package instead:
|
||||
|
||||
```
|
||||
npm install @perseveranza-pets/milo-cjs
|
||||
```
|
||||
|
||||
Then create a sample source file:
|
||||
|
||||
```javascript
|
||||
import { setup } from '@perseveranza-pets/milo'
|
||||
|
||||
/*
|
||||
Milo works using callbacks.
|
||||
|
||||
All callbacks have the same signature, which characterizes the payload:
|
||||
|
||||
* The current parser
|
||||
* from: The payload offset.
|
||||
* size: The payload length.
|
||||
|
||||
The payload parameters above are relative to the last data sent to the milo.parse method.
|
||||
|
||||
If the current callback has no payload, both values are set to 0.
|
||||
|
||||
The callbacks must be provided using setup and are named in snake case.
|
||||
*/
|
||||
const milo = setup({
|
||||
on_data (p, from, size) {
|
||||
console.log(`Pos=${from} Body: ${message.slice(from, from + size).toString()}`)
|
||||
}
|
||||
})
|
||||
|
||||
// Prepare a message to parse.
|
||||
const message = Buffer.from('HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\nabc')
|
||||
|
||||
// Allocate a memory in the WebAssembly space. This speeds up data copying to the WebAssembly layer.
|
||||
const ptr = milo.alloc(message.length)
|
||||
|
||||
// Create a buffer we can use normally.
|
||||
const buffer = Buffer.from(milo.memory.buffer, ptr, message.length)
|
||||
|
||||
// Create the parser.
|
||||
const parser = milo.create()
|
||||
|
||||
// Toggle on the callbacks you want to receive
|
||||
milo.setActiveCallbacks(parser, milo.CALLBACK_ACTIVE_ON_DATA)
|
||||
|
||||
// Now perform the main parsing using milo.parse. The method returns the number of consumed characters.
|
||||
buffer.set(message, 0)
|
||||
milo.parse(parser, ptr, message.length)
|
||||
|
||||
// Cleanup used resources.
|
||||
milo.destroy(parser)
|
||||
milo.dealloc(ptr, message.length)
|
||||
```
|
||||
|
||||
The default JavaScript entry point uses the SIMD WebAssembly build. Use `@perseveranza-pets/milo/no-simd` when SIMD is not available, and add `/unbundled` to either entry point to load the external `.wasm` file instead of the bundled JavaScript module.
|
||||
|
||||
The WebAssembly release build uses immediate-abort panics: panics trap without unwinding or rich panic messages. The debug build also enables the `on_state_change` callback and provides more detailed WebAssembly errors.
|
||||
|
||||
CommonJS projects can use the same entry points from `@perseveranza-pets/milo-cjs`:
|
||||
|
||||
```javascript
|
||||
const { setup } = require('@perseveranza-pets/milo-cjs')
|
||||
```
|
||||
|
||||
Finally build and execute it using `node`:
|
||||
|
||||
```bash
|
||||
node index.js
|
||||
# Pos=38 Body: abc
|
||||
```
|
||||
|
||||
## How to use it (Rust)
|
||||
|
||||
Add `milo-parser` to your `Cargo.toml`:
|
||||
|
||||
```toml
|
||||
[package]
|
||||
name = "milo-example"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
milo-parser = "0.4.0"
|
||||
```
|
||||
|
||||
Create a sample source file:
|
||||
|
||||
```rust
|
||||
use core::ffi::c_void;
|
||||
use core::slice;
|
||||
|
||||
use milo_parser::{Parser, CALLBACK_ACTIVE_ON_DATA};
|
||||
|
||||
fn main() {
|
||||
// Create the parser.
|
||||
let mut parser = Parser::new();
|
||||
|
||||
// Prepare a message to parse.
|
||||
let message = String::from("HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\nabc");
|
||||
parser.context = message.as_ptr() as *mut c_void;
|
||||
|
||||
// Milo works using callbacks.
|
||||
//
|
||||
// All callbacks have the same signature, which characterizes the payload:
|
||||
//
|
||||
// p: The current parser.
|
||||
// from: The payload offset.
|
||||
// size: The payload length.
|
||||
//
|
||||
// The payload parameters above are relative to the last data sent to the parse
|
||||
// method.
|
||||
//
|
||||
// If the current callback has no payload, both values are set to 0.
|
||||
parser.callbacks.on_data = |p: &mut Parser, from: usize, size: usize| {
|
||||
let message =
|
||||
unsafe { std::str::from_utf8_unchecked(slice::from_raw_parts(p.context.add(from) as *const u8, size)) };
|
||||
|
||||
// Use the callback data.
|
||||
println!("Pos={} Body: {}", from, message);
|
||||
};
|
||||
|
||||
// Toggle on the callbacks you want to receive
|
||||
parser.active_callbacks |= CALLBACK_ACTIVE_ON_DATA;
|
||||
|
||||
// Now perform the main parsing using milo.parse. The method returns the number
|
||||
// of consumed characters.
|
||||
parser.parse(message.as_ptr(), message.len());
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Finally build and execute it using `cargo`:
|
||||
|
||||
```bash
|
||||
cargo run
|
||||
# Pos=38 Body: abc
|
||||
```
|
||||
|
||||
## How to use it (C++)
|
||||
|
||||
First, let's download Milo release from GitHub.
|
||||
|
||||
You will need a static library file (for Linux/Unix/MacOS is `libmilo.a`) and a header file (`milo.h`).
|
||||
|
||||
Create a sample source file:
|
||||
|
||||
```cpp
|
||||
#include "milo.h"
|
||||
#include <cinttypes>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
int main() {
|
||||
// Create the parser.
|
||||
milo_parser::Parser* parser = milo_parser::milo_create();
|
||||
|
||||
// Prepare a message to parse.
|
||||
const char* message = "HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\nabc";
|
||||
|
||||
parser->context = (char*) message;
|
||||
|
||||
/*
|
||||
Milo works using callbacks.
|
||||
|
||||
All callbacks have the same signature, which characterizes the payload:
|
||||
|
||||
* p: The current parser.
|
||||
* from: The payload offset.
|
||||
* size: The payload length.
|
||||
|
||||
The payload parameters above are relative to the last data sent to the milo_parse method.
|
||||
|
||||
If the current callback has no payload, both values are set to 0.
|
||||
*/
|
||||
parser->callbacks.on_data = [](milo_parser::Parser* p, uintptr_t from, uintptr_t size) {
|
||||
const char* payload = reinterpret_cast<const char*>(p->context) + from;
|
||||
|
||||
printf("Pos=%" PRIuPTR " Body: %.*s\n", from, static_cast<int>(size), payload);
|
||||
};
|
||||
|
||||
// Toggle on the callbacks you want to receive
|
||||
parser->active_callbacks |= milo_parser::CALLBACK_ACTIVE_ON_DATA;
|
||||
|
||||
// Now perform the main parsing using milo.parse. The method returns the number of consumed characters.
|
||||
milo_parser::milo_parse(parser, reinterpret_cast<const unsigned char*>(message), strlen(message));
|
||||
|
||||
// Cleanup used resources.
|
||||
milo_parser::milo_destroy(parser);
|
||||
}
|
||||
```
|
||||
|
||||
And then you can compile using your preferred build system. For instance, let's try with [Clang]:
|
||||
|
||||
```bash
|
||||
clang++ -std=c++11 -o example main.cc libmilo.a
|
||||
./example
|
||||
# Pos=38 Body: abc
|
||||
```
|
||||
|
||||
## How to use it (CLI)
|
||||
|
||||
Install it from crates.io:
|
||||
|
||||
```bash
|
||||
cargo install milo-parser
|
||||
```
|
||||
|
||||
The `milo-parser` binary reads an HTTP/1.1 message from standard input by default and prints the callbacks emitted by Milo:
|
||||
|
||||
```bash
|
||||
printf 'GET / HTTP/1.1\r\nHost: example.com\r\n\r\n' | milo-parser
|
||||
# offset=0 size=0 event=request
|
||||
# offset=0 size=0 event=message_start
|
||||
# offset=0 size=0 event=state_change
|
||||
# offset=0 size=3 event=method
|
||||
```
|
||||
|
||||
Each output line uses this format:
|
||||
|
||||
```text
|
||||
offset=$OFFSET size=$SIZE event=$EVENT
|
||||
```
|
||||
|
||||
Parser errors are emitted as callback lines too:
|
||||
|
||||
```text
|
||||
offset=$OFFSET size=$SIZE event=error error=$ERROR description="$DESCRIPTION"
|
||||
```
|
||||
|
||||
Use `-f` or `--file` to parse a file:
|
||||
|
||||
```bash
|
||||
milo-parser --file request.http
|
||||
```
|
||||
|
||||
By default Milo autodetects request or response input. Use `-o` or `--request` to force request parsing, and `-i` or `--response` to force response parsing:
|
||||
|
||||
```bash
|
||||
milo-parser --request --file request.http
|
||||
milo-parser --response --file response.http
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
See the following files, according to the language you are using:
|
||||
|
||||
- [JavaScript via WebAssembly API](./docs/js.md)
|
||||
- [Rust API](./docs/rust.md)
|
||||
- [C++ API](./docs/cpp.md)
|
||||
|
||||
## Strictness Differences From llhttp
|
||||
|
||||
Milo does not aim for byte-for-byte llhttp compatibility when lenient behavior would conflict with Milo's strict parser policy.
|
||||
|
||||
- Milo rejects HTTP/0.9, HTTP/1.0, RTSP, obs-fold, bare LF, and bare CR.
|
||||
- Milo rejects normal HTTP/2 request and response messages.
|
||||
- Milo rejects request bodies on `GET` and `HEAD`.
|
||||
- Milo requires `skip_body` for application-known no-body response contexts such as responses to `HEAD`.
|
||||
- Milo validates protocol framing and syntax, but leaves application semantics to callers.
|
||||
|
||||
## Security Boundaries
|
||||
|
||||
Milo validates HTTP/1.1 syntax, message framing, protocol switching, connection management, and data-after-close behavior. Milo does not validate routing, authorization, representation semantics, URI normalization, `Host` policy, method-specific request-target forms, CONNECT authority-form, or full header field semantics unless they affect safe framing.
|
||||
|
||||
## How it works?
|
||||
|
||||
Milo is a simple state machine which copies data in only one optional case: automatically handling the unconsumed portion of the input data.
|
||||
|
||||
In all other cases, no data is copied and the memory footprint is very small as only a few dozen `bool`, `uintptr_t`, or `uint64_t` fields can represent the entire parser state.
|
||||
|
||||
## Why?
|
||||
|
||||
The scope of Milo is to replace [llhttp] as [Node.js] main HTTP parser.
|
||||
|
||||
This project aims to:
|
||||
|
||||
- Make it maintainable and verifiable using easy to read Rust code.
|
||||
- Be performant by avoiding any unnecessary data copy.
|
||||
- Be self-contained and dependency-free.
|
||||
|
||||
To see the rationale behind the replacement of llhttp, check Paolo's talk at [Vancouver's Node Collab Summit][vancouver-talk] in January 2023 ([slides][vancouver-slides]).
|
||||
|
||||
To see the initial disclosure of milo, check Paolo's talk at [NodeConf EU 2023][nodeconf-talk] in November 2023 ([slides][slides]).
|
||||
|
||||
## Sponsored by
|
||||
|
||||
[][nearform]
|
||||
|
||||
## Contributing to milo
|
||||
|
||||
See [AGENTS.md](./AGENTS.md) for development setup, local and Docker builds, tests, and contribution guidelines.
|
||||
|
||||
## Copyright
|
||||
|
||||
Copyright (C) 2023 and above Paolo Insogna (paolo@cowtech.it) and NearForm (https://nearform.com).
|
||||
|
||||
Licensed under the ISC license, which can be found at https://choosealicense.com/licenses/isc or in the [LICENSE.md](./LICENSE.md) file.
|
||||
|
||||
[rust]: https://www.rust-lang.org/
|
||||
[webassembly]: https://webassembly.org/
|
||||
[nearform]: https://nearform.com
|
||||
[llhttp]: https://github.com/nodejs/llhttp
|
||||
[Node.js]: https://nodejs.org
|
||||
[vancouver-talk]: https://youtube.com/watch?v=L-VONzXQ944
|
||||
[vancouver-slides]: https://talks.cowtech.it/http-parser
|
||||
[nodeconf-talk]: https://youtube.com/watch?v=dcHbAeO_ccY
|
||||
[slides]: https://talks.paoloinsogna.dev/milo
|
||||
[isc]: https://choosealicense.com/licenses/isc
|
||||
[match]: https://doc.rust-lang.org/rust-by-example/flow_control/match.html
|
||||
[match-slice]: https://doc.rust-lang.org/rust-by-example/flow_control/match/destructuring/destructure_slice.html
|
||||
[Clang]: https://clang.llvm.org/
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
[package]
|
||||
name = "milo-macros"
|
||||
version = "0.9.0"
|
||||
edition = "2024"
|
||||
description = "Macros for milo-parser, a fast and embeddable HTTP/1.1 parser."
|
||||
homepage = "https://sw.cowtech.it/milo"
|
||||
repository = "https://github.com/ShogunPanda/milo"
|
||||
license = "ISC"
|
||||
keywords = ["http", "parser", "http-parser"]
|
||||
categories = ["network-programming", "parser-implementations"]
|
||||
include = ["Cargo.toml", "src/**/*.rs", "constants/*.yml"]
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[[bin]]
|
||||
name = "milo-parser-fields"
|
||||
path = "src/parser_fields.rs"
|
||||
|
||||
[dependencies]
|
||||
indexmap = { version = "2.13.0", features = ["serde"] }
|
||||
proc-macro2 = "1.0.106"
|
||||
quote = "1.0.45"
|
||||
regex = "1.12.3"
|
||||
semver = "1.0.27"
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_json = "1.0.149"
|
||||
serde_yaml = "0.9.34"
|
||||
syn = { version = "2.0.117", features = ["full", "extra-traits"] }
|
||||
toml = "1.0.7"
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
# milo-macros
|
||||
|
||||
milo-macros is an internal crate which represents the core of Milo.
|
||||
|
||||
It leverages Rust's [procedural macro], [syn] and [quote] crates to allow an easy definition of states and matchers for the parser.
|
||||
|
||||
To define a new macro, you have to define a new method which the following signature:
|
||||
|
||||
```rust
|
||||
#[proc_macro]
|
||||
pub fn new_macro(input: TokenStream) -> TokenStream {
|
||||
TokenStream::new( /* ... */)
|
||||
}
|
||||
```
|
||||
|
||||
Everything that is not included **within** the return value will not be present in the executed code. Macro performance is not important for runtime because macros are only evaluated at compile time.
|
||||
|
||||
The `generate!` macro also emits parser constants and internal byte lookup tables used by syntax validators. These tables are generated at compile time and are not public API.
|
||||
|
||||
To return a new code, leverage the `quote!` macro, while for parsing use the `parse_macro_input!` macro. Here's an example:
|
||||
|
||||
```rust
|
||||
#[proc_macro]
|
||||
pub fn char(input: TokenStream) -> TokenStream {
|
||||
let character = parse_macro_input!(input as LitChar);
|
||||
let byte = LitByte::new(c_uchar::try_from(character.value()).unwrap(), character.span());
|
||||
|
||||
TokenStream::from(quote! { #byte })
|
||||
}
|
||||
```
|
||||
|
||||
[procedural macro]: https://doc.rust-lang.org/reference/procedural-macros.html
|
||||
[syn]: https://crates.io/crates/syn
|
||||
[quote]: https://crates.io/crates/quote
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
- on_error
|
||||
- on_finish
|
||||
- on_message_start
|
||||
- on_message_complete
|
||||
- on_request
|
||||
- on_response
|
||||
- on_reset
|
||||
- on_method
|
||||
- on_url
|
||||
- on_protocol
|
||||
- on_version
|
||||
- on_status
|
||||
- on_reason
|
||||
- on_header_name
|
||||
- on_header_value
|
||||
- on_headers
|
||||
- on_connect
|
||||
- on_upgrade
|
||||
- on_chunk_length
|
||||
- on_chunk_extension_name
|
||||
- on_chunk_extension_value
|
||||
- on_chunk
|
||||
- on_body
|
||||
- on_data
|
||||
- on_trailer_name
|
||||
- on_trailer_value
|
||||
- on_trailers
|
||||
- on_state_change
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
- NONE
|
||||
- USER
|
||||
- CALLBACK_ERROR
|
||||
- UNEXPECTED_STATE
|
||||
- UNEXPECTED_DATA
|
||||
- UNEXPECTED_EOF
|
||||
- UNEXPECTED_CHARACTER
|
||||
- UNEXPECTED_CONTENT_LENGTH
|
||||
- UNEXPECTED_TRANSFER_ENCODING
|
||||
- UNEXPECTED_CONTENT
|
||||
- UNEXPECTED_TRAILERS
|
||||
- INVALID_VERSION
|
||||
- INVALID_STATUS
|
||||
- INVALID_CONTENT_LENGTH
|
||||
- INVALID_TRANSFER_ENCODING
|
||||
- INVALID_CHUNK_SIZE
|
||||
- MISSING_CONNECTION_UPGRADE
|
||||
- UNSUPPORTED_HTTP_VERSION
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
# Milo doesn't validate the method, that is left to the application
|
||||
- OTHER
|
||||
|
||||
# RFC 9110 section 9 (HTTP Semantics — Methods)
|
||||
- GET
|
||||
- HEAD
|
||||
- POST
|
||||
- PUT
|
||||
- DELETE
|
||||
- CONNECT
|
||||
- OPTIONS
|
||||
- TRACE
|
||||
|
||||
# RFC 5789 section 2 (PATCH Method) - This is included as widely used
|
||||
- PATCH
|
||||
|
||||
# RFC 7540 section 3.5 (HTTP/2 connection preface)
|
||||
- PRI
|
||||
@@ -0,0 +1,16 @@
|
||||
---
|
||||
- start
|
||||
- finish
|
||||
- error
|
||||
- request_line
|
||||
- status_line
|
||||
- http2_preface
|
||||
- header
|
||||
- body_decision
|
||||
- body_via_content_length
|
||||
- body_with_no_length
|
||||
- chunk_header
|
||||
- chunk_extensions
|
||||
- chunk_data
|
||||
- trailer
|
||||
- tunnel
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
use proc_macro::TokenStream;
|
||||
use quote::{format_ident, quote};
|
||||
use syn::{Expr, Ident, parse_macro_input};
|
||||
|
||||
use crate::structs::{EventRequest, FailureRequest};
|
||||
|
||||
/// Emits an event carrying an input range.
|
||||
pub fn event_with_range(input: TokenStream) -> TokenStream {
|
||||
let definition = parse_macro_input!(input as EventRequest);
|
||||
let callback = &definition.identifier;
|
||||
let callback_const = format_ident!("CALLBACK_{}", callback.to_string().to_uppercase());
|
||||
let event_type = quote! { #callback_const + 1 };
|
||||
let bitmask = format_ident!("EVENT_ACTIVE_{}", definition.identifier.to_string().to_uppercase());
|
||||
let offset = definition.offset.as_ref().expect("event_with_range requires offset");
|
||||
let length = definition.length.as_ref().expect("event_with_range requires length");
|
||||
let needed = quote! { EVENT_RANGE_SIZE };
|
||||
let emit = quote! {
|
||||
let at = (self.position + #offset) as u32;
|
||||
let len = (#length) as u32;
|
||||
unsafe {
|
||||
*self.events.add(event_cursor) = #event_type;
|
||||
core::ptr::write_unaligned(
|
||||
self.events.add(event_cursor + 1) as *mut u32,
|
||||
at.to_le(),
|
||||
);
|
||||
core::ptr::write_unaligned(
|
||||
self.events.add(event_cursor + 5) as *mut u32,
|
||||
len.to_le(),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
TokenStream::from(quote! {
|
||||
if active_events & #bitmask != 0 {
|
||||
// Reserve space for a later error event and the batch terminator.
|
||||
if event_cursor + #needed + EVENT_ERROR_RESERVE <= EVENTS_BUFFER_SIZE {
|
||||
#emit
|
||||
event_cursor += #needed;
|
||||
} else {
|
||||
suspend!();
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Emits an error event.
|
||||
pub fn event_with_error(input: TokenStream) -> TokenStream {
|
||||
let definition = parse_macro_input!(input as EventRequest);
|
||||
let callback = &definition.identifier;
|
||||
let callback_const = format_ident!("CALLBACK_{}", callback.to_string().to_uppercase());
|
||||
let event_type = quote! { #callback_const + 1 };
|
||||
let bitmask = format_ident!("EVENT_ACTIVE_{}", definition.identifier.to_string().to_uppercase());
|
||||
let needed = quote! { EVENT_ERROR_SIZE };
|
||||
let emit = quote! {
|
||||
let at = self.position as u32;
|
||||
unsafe {
|
||||
*self.events.add(event_cursor) = #event_type;
|
||||
core::ptr::write_unaligned(
|
||||
self.events.add(event_cursor + 1) as *mut u32,
|
||||
at.to_le(),
|
||||
);
|
||||
*self.events.add(event_cursor + 5) = self.error_code;
|
||||
}
|
||||
};
|
||||
|
||||
TokenStream::from(quote! {
|
||||
if active_events & #bitmask != 0 {
|
||||
if event_cursor + #needed + EVENT_END_SIZE <= EVENTS_BUFFER_SIZE {
|
||||
#emit
|
||||
event_cursor += #needed;
|
||||
} else {
|
||||
suspend!();
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Emits an event carrying parsed metadata.
|
||||
pub fn event_with_metadata(input: TokenStream) -> TokenStream {
|
||||
let definition = parse_macro_input!(input as EventRequest);
|
||||
let callback = &definition.identifier;
|
||||
let callback_const = format_ident!("CALLBACK_{}", callback.to_string().to_uppercase());
|
||||
let event_type = quote! { #callback_const + 1 };
|
||||
let bitmask = format_ident!("EVENT_ACTIVE_{}", definition.identifier.to_string().to_uppercase());
|
||||
let offset = definition.offset.unwrap_or_else(|| syn::parse_quote! { 0 });
|
||||
let needed = quote! { EVENT_METADATA_SIZE };
|
||||
let emit = quote! {
|
||||
let at = (self.position + #offset) as u32;
|
||||
let status_or_method = if self.is_request { self.method as u16 } else { self.status as u16 };
|
||||
let body_kind = if self.has_content_length { 0u8 } else if self.has_chunked_transfer_encoding { 1u8 } else { 2u8 };
|
||||
let should_keep_alive = (!self.has_connection_close) as u8;
|
||||
// Responses switch protocols only with status 101; requests can propose an upgrade.
|
||||
let should_upgrade = (self.has_upgrade && self.has_connection_upgrade && (self.is_request || self.status == 101)) as u8;
|
||||
let has_trailers = self.has_trailers as u8;
|
||||
let content_length = if self.has_content_length { self.content_length } else { 0 };
|
||||
|
||||
unsafe {
|
||||
*self.events.add(event_cursor) = #event_type;
|
||||
core::ptr::write_unaligned(
|
||||
self.events.add(event_cursor + 1) as *mut u32,
|
||||
at.to_le(),
|
||||
);
|
||||
core::ptr::write_unaligned(
|
||||
self.events.add(event_cursor + 5) as *mut u16,
|
||||
status_or_method.to_le(),
|
||||
);
|
||||
*self.events.add(event_cursor + 7) = should_keep_alive;
|
||||
*self.events.add(event_cursor + 8) = should_upgrade;
|
||||
*self.events.add(event_cursor + 9) = has_trailers;
|
||||
*self.events.add(event_cursor + 10) = body_kind;
|
||||
core::ptr::write_unaligned(
|
||||
self.events.add(event_cursor + 11) as *mut u64,
|
||||
content_length.to_le(),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
TokenStream::from(quote! {
|
||||
if active_events & #bitmask != 0 {
|
||||
// Reserve space for a later error event and the batch terminator.
|
||||
if event_cursor + #needed + EVENT_ERROR_RESERVE <= EVENTS_BUFFER_SIZE {
|
||||
#emit
|
||||
event_cursor += #needed;
|
||||
} else {
|
||||
suspend!();
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Marks a certain number of characters as used.
|
||||
pub fn advance(input: TokenStream) -> TokenStream {
|
||||
let len = parse_macro_input!(input as Expr);
|
||||
|
||||
TokenStream::from(quote! { advanced += #len; })
|
||||
}
|
||||
|
||||
/// Moves the parser to a new state.
|
||||
pub fn move_to(input: TokenStream) -> TokenStream {
|
||||
let definition = parse_macro_input!(input as Ident);
|
||||
let state = format_ident!("STATE_{}", definition.to_string().to_uppercase());
|
||||
|
||||
TokenStream::from(quote! {
|
||||
if self.state != STATE_ERROR {
|
||||
self.state = #state;
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Go to the next iteration of the parser
|
||||
pub fn next() -> TokenStream { TokenStream::from(quote! { break 'state; }) }
|
||||
|
||||
/// Marks the parser as suspended, waiting for more data.
|
||||
pub fn suspend() -> TokenStream {
|
||||
TokenStream::from(quote! {
|
||||
parsing = false;
|
||||
break 'state;
|
||||
})
|
||||
}
|
||||
|
||||
/// Marks the parsing a failed, setting a error code and and error message.
|
||||
pub fn fail(input: TokenStream) -> TokenStream {
|
||||
let definition = parse_macro_input!(input as FailureRequest);
|
||||
let error = format_ident!("ERROR_{}", definition.error);
|
||||
let message = definition.message;
|
||||
|
||||
TokenStream::from(quote! {
|
||||
self.set_error(#error, #message);
|
||||
failed = true;
|
||||
break 'parser;
|
||||
})
|
||||
}
|
||||
+443
@@ -0,0 +1,443 @@
|
||||
use proc_macro::TokenStream;
|
||||
use quote::{format_ident, quote};
|
||||
use regex::{Captures, Regex};
|
||||
use syn::{Arm, ItemConst, parse_str};
|
||||
|
||||
use crate::{native, parser_fields, wasm};
|
||||
|
||||
fn init_constants() -> (Vec<String>, Vec<String>, Vec<String>, Vec<String>) {
|
||||
let methods = serde_yaml::from_str(include_str!("../constants/methods.yml")).unwrap();
|
||||
let errors = serde_yaml::from_str(include_str!("../constants/errors.yml")).unwrap();
|
||||
let callbacks = serde_yaml::from_str(include_str!("../constants/callbacks.yml")).unwrap();
|
||||
let states = serde_yaml::from_str(include_str!("../constants/states.yml")).unwrap();
|
||||
|
||||
(methods, errors, callbacks, states)
|
||||
}
|
||||
|
||||
fn generate_constants_internal(
|
||||
items: &[String],
|
||||
prefix: &str,
|
||||
start: usize,
|
||||
strip_prefix: Option<&str>,
|
||||
) -> Vec<ItemConst> {
|
||||
let mut consts: Vec<ItemConst> = Vec::new();
|
||||
let mut bytes: Vec<&[u8]> = vec![];
|
||||
|
||||
for (i, x) in items.iter().enumerate() {
|
||||
let value = strip_prefix.and_then(|prefix| x.strip_prefix(prefix)).unwrap_or(x);
|
||||
let uppercased = value.to_uppercase();
|
||||
let name = uppercased.replace('-', "_");
|
||||
bytes.push(x.as_bytes());
|
||||
|
||||
consts.push(parse_str::<ItemConst>(&format!("pub const {}_{}: u8 = {};", prefix, name, i + start)).unwrap());
|
||||
}
|
||||
|
||||
consts
|
||||
}
|
||||
|
||||
fn generate_bitmask(items: &[String], prefix: &str) -> Vec<ItemConst> {
|
||||
let mut consts: Vec<ItemConst> = Vec::new();
|
||||
let mut all = 0u64;
|
||||
|
||||
consts.push(parse_str::<ItemConst>(&format!("pub const {}_NONE: u64 = 0;", prefix)).unwrap());
|
||||
|
||||
for (i, x) in items.iter().enumerate() {
|
||||
let uppercased = x.to_uppercase();
|
||||
let name = uppercased.replace('-', "_");
|
||||
let bit = 1 << i;
|
||||
all |= bit;
|
||||
|
||||
consts.push(parse_str::<ItemConst>(&format!("pub const {}_{}: u64 = {};", prefix, name, bit)).unwrap());
|
||||
}
|
||||
|
||||
consts.push(parse_str::<ItemConst>(&format!("pub const {}_ALL: u64 = {};", prefix, all)).unwrap());
|
||||
|
||||
consts
|
||||
}
|
||||
|
||||
fn generate_table<F>(validator: F) -> Vec<bool>
|
||||
where
|
||||
F: Fn(u16) -> bool,
|
||||
{
|
||||
// Precompute byte validators so the parser can use table lookups in hot paths.
|
||||
(0..=255).map(validator).collect()
|
||||
}
|
||||
|
||||
/// Generates all parser constants.
|
||||
fn generate_constants(methods: &[String], errors: &[String], callbacks: &[String], states: &[String]) -> TokenStream {
|
||||
let methods_consts = generate_constants_internal(methods, "METHOD", 0, None);
|
||||
let states_consts = generate_constants_internal(states, "STATE", 0, None);
|
||||
let errors_consts = generate_constants_internal(errors, "ERROR", 0, None);
|
||||
let callbacks_consts = generate_constants_internal(callbacks, "CALLBACK", 0, None);
|
||||
let callbacks_bitmask = generate_bitmask(callbacks, "CALLBACK_ACTIVE");
|
||||
let event_bitmask = generate_bitmask(callbacks, "EVENT_ACTIVE");
|
||||
let event_consts = generate_constants_internal(callbacks, "EVENT", 1, Some("on_"));
|
||||
let parser_field_offsets = parser_fields::generate_constants();
|
||||
let token_table = generate_table(|byte| {
|
||||
(0x30..=0x39).contains(&byte)
|
||||
|| (0x41..=0x5a).contains(&byte)
|
||||
|| (0x61..=0x7a).contains(&byte)
|
||||
|| matches!(
|
||||
byte as u8,
|
||||
b'!' | b'#' | b'$' | b'%' | b'&' | b'\'' | b'*' | b'+' | b'-' | b'.' | b'^' | b'_' | b'`' | b'|' | b'~'
|
||||
)
|
||||
});
|
||||
let url_table = generate_table(|byte| {
|
||||
(0x30..=0x39).contains(&byte)
|
||||
|| (0x41..=0x5a).contains(&byte)
|
||||
|| (0x61..=0x7a).contains(&byte)
|
||||
|| matches!(
|
||||
byte as u8,
|
||||
b'-'
|
||||
| b'.'
|
||||
| b'_'
|
||||
| b'~'
|
||||
| b':'
|
||||
| b'/'
|
||||
| b'?'
|
||||
| b'['
|
||||
| b']'
|
||||
| b'@'
|
||||
| b'!'
|
||||
| b'$'
|
||||
| b'&'
|
||||
| b'\''
|
||||
| b'('
|
||||
| b')'
|
||||
| b'*'
|
||||
| b'+'
|
||||
| b','
|
||||
| b';'
|
||||
| b'='
|
||||
| b'%'
|
||||
)
|
||||
});
|
||||
let quoted_string_table = generate_table(|byte| {
|
||||
byte == 0x09
|
||||
|| byte == 0x20
|
||||
|| byte == 0x21
|
||||
|| (0x23..=0x5b).contains(&byte)
|
||||
|| (0x5d..=0x7e).contains(&byte)
|
||||
|| byte >= 0x80
|
||||
});
|
||||
let quoted_pair_table =
|
||||
generate_table(|byte| byte == 0x09 || byte == 0x20 || (0x21..=0x7e).contains(&byte) || byte >= 0x80);
|
||||
|
||||
TokenStream::from(quote! {
|
||||
pub type StateHandler = fn (parser: &mut Parser, data: &[c_uchar], available: usize);
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub type Callback = fn (&mut Parser, usize, usize);
|
||||
|
||||
#(#methods_consts)*
|
||||
#(#errors_consts)*
|
||||
#(#callbacks_consts)*
|
||||
pub const EVENT_END: u8 = 0;
|
||||
#(#event_consts)*
|
||||
#(#callbacks_bitmask)*
|
||||
#(#event_bitmask)*
|
||||
#(#states_consts)*
|
||||
#parser_field_offsets
|
||||
|
||||
const EVENTS_BUFFER_SIZE: usize = 64 * 1024;
|
||||
const EVENT_RANGE_SIZE: usize = 9;
|
||||
const EVENT_METADATA_SIZE: usize = 19;
|
||||
const EVENT_ERROR_SIZE: usize = 6;
|
||||
const EVENT_END_SIZE: usize = 1;
|
||||
const EVENT_ERROR_RESERVE: usize = EVENT_ERROR_SIZE + EVENT_END_SIZE;
|
||||
// Reserve MESSAGE_COMPLETE, RESET and FINISH, regardless of which events are enabled.
|
||||
const EVENT_COMPLETION_SIZE: usize = 3 * EVENT_RANGE_SIZE;
|
||||
// Include DATA and BODY before the completion group.
|
||||
const EVENT_BODY_COMPLETION_SIZE: usize = 2 * EVENT_RANGE_SIZE + EVENT_COMPLETION_SIZE;
|
||||
// Include TRAILERS before the completion group.
|
||||
const EVENT_TRAILER_COMPLETION_SIZE: usize = EVENT_RANGE_SIZE + EVENT_COMPLETION_SIZE;
|
||||
|
||||
/// cbindgen:ignore
|
||||
static TOKEN_TABLE: [bool; 256] = [#(#token_table),*];
|
||||
|
||||
/// cbindgen:ignore
|
||||
static URL_TABLE: [bool; 256] = [#(#url_table),*];
|
||||
|
||||
/// cbindgen:ignore
|
||||
static QUOTED_STRING_TABLE: [bool; 256] = [#(#quoted_string_table),*];
|
||||
|
||||
/// cbindgen:ignore
|
||||
static QUOTED_PAIR_TABLE: [bool; 256] = [#(#quoted_pair_table),*];
|
||||
})
|
||||
}
|
||||
|
||||
/// Generates all parser enums.
|
||||
fn generate_enums(methods: &[String], errors: &[String], callbacks: &[String], states: &[String]) -> TokenStream {
|
||||
let snake_matcher = Regex::new(r"_([a-z])").unwrap();
|
||||
|
||||
let methods_ref = methods;
|
||||
let errors_ref = errors;
|
||||
let callbacks_ref = callbacks;
|
||||
let events_ref: Vec<String> = core::iter::once("END".to_string())
|
||||
.chain(
|
||||
callbacks_ref
|
||||
.iter()
|
||||
.map(|x| x.strip_prefix("on_").unwrap_or(x).to_string()),
|
||||
)
|
||||
.collect();
|
||||
let states_ref = states;
|
||||
|
||||
let methods: Vec<_> = methods_ref
|
||||
.iter()
|
||||
.map(|x| format_ident!("{}", x.replace('-', "_")))
|
||||
.collect();
|
||||
|
||||
let errors: Vec<_> = errors_ref.iter().map(|x| format_ident!("{}", x)).collect();
|
||||
|
||||
let callbacks: Vec<_> = callbacks_ref
|
||||
.iter()
|
||||
.map(|x| {
|
||||
let lowercase = x.to_lowercase();
|
||||
|
||||
format_ident!(
|
||||
"{}",
|
||||
snake_matcher.replace_all(lowercase.as_str(), |captures: &Captures| captures[1].to_uppercase())
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let events: Vec<_> = events_ref
|
||||
.iter()
|
||||
.map(|x| format_ident!("{}", x.to_uppercase()))
|
||||
.collect();
|
||||
|
||||
let states: Vec<_> = states_ref
|
||||
.iter()
|
||||
.map(|x| format_ident!("{}", x.to_uppercase()))
|
||||
.collect();
|
||||
|
||||
let methods_from: Vec<_> = methods_ref
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(x, i)| parse_str::<Arm>(&format!("{} => Ok(Methods::{})", x, i.replace('-', "_"))).unwrap())
|
||||
.collect();
|
||||
|
||||
let errors_from: Vec<_> = errors_ref
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(x, i)| parse_str::<Arm>(&format!("{} => Ok(Errors::{})", x, i)).unwrap())
|
||||
.collect();
|
||||
|
||||
let callbacks_from: Vec<_> = callbacks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(x, i)| parse_str::<Arm>(&format!("{} => Ok(Callbacks::{})", x, i)).unwrap())
|
||||
.collect();
|
||||
|
||||
let events_from: Vec<_> = events
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(x, i)| parse_str::<Arm>(&format!("{} => Ok(Events::{})", x, i)).unwrap())
|
||||
.collect();
|
||||
|
||||
let states_from: Vec<_> = states
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(x, i)| parse_str::<Arm>(&format!("{} => Ok(States::{})", x, i)).unwrap())
|
||||
.collect();
|
||||
|
||||
let methods_into: Vec<_> = methods_ref
|
||||
.iter()
|
||||
.map(|x| parse_str::<Arm>(&format!("Methods::{} => \"{}\"", x.replace('-', "_"), x)).unwrap())
|
||||
.collect();
|
||||
|
||||
let errors_into: Vec<_> = errors_ref
|
||||
.iter()
|
||||
.map(|x| parse_str::<Arm>(&format!("Errors::{} => \"{}\"", x, x)).unwrap())
|
||||
.collect();
|
||||
|
||||
let callbacks_into: Vec<_> = callbacks
|
||||
.iter()
|
||||
.map(|x| parse_str::<Arm>(&format!("Callbacks::{} => \"{}\"", x, x)).unwrap())
|
||||
.collect();
|
||||
|
||||
let events_into: Vec<_> = events_ref
|
||||
.iter()
|
||||
.map(|x| parse_str::<Arm>(&format!("Events::{} => \"{}\"", x.to_uppercase(), x.to_uppercase())).unwrap())
|
||||
.collect();
|
||||
|
||||
let states_into: Vec<_> = states
|
||||
.iter()
|
||||
.map(|x| parse_str::<Arm>(&format!("States::{} => \"{}\"", x, x)).unwrap())
|
||||
.collect();
|
||||
|
||||
TokenStream::from(quote! {
|
||||
#[repr(u8)]
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub enum Methods {
|
||||
#(#methods),*
|
||||
}
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub enum Errors {
|
||||
#(#errors),*
|
||||
}
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub enum Callbacks {
|
||||
#(#callbacks),*
|
||||
}
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub enum Events {
|
||||
#(#events),*
|
||||
}
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub enum States {
|
||||
#(#states),*
|
||||
}
|
||||
|
||||
impl TryFrom<u8> for Methods {
|
||||
type Error = ();
|
||||
|
||||
fn try_from(value: u8) -> Result<Self, ()> {
|
||||
match value {
|
||||
#(#methods_from),*,
|
||||
_ => Err(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<u8> for Errors {
|
||||
type Error = ();
|
||||
|
||||
fn try_from(value: u8) -> Result<Self, ()> {
|
||||
match value {
|
||||
#(#errors_from),*,
|
||||
_ => Err(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<u8> for Callbacks {
|
||||
type Error = ();
|
||||
|
||||
fn try_from(value: u8) -> Result<Self, ()> {
|
||||
match value {
|
||||
#(#callbacks_from),*,
|
||||
_ => Err(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<u8> for Events {
|
||||
type Error = ();
|
||||
|
||||
fn try_from(value: u8) -> Result<Self, ()> {
|
||||
match value {
|
||||
#(#events_from),*,
|
||||
_ => Err(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<u8> for States {
|
||||
type Error = ();
|
||||
|
||||
fn try_from(value: u8) -> Result<Self, ()> {
|
||||
match value {
|
||||
#(#states_from),*,
|
||||
_ => Err(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Methods> for &str {
|
||||
fn from(value: Methods) -> Self {
|
||||
match value {
|
||||
#(#methods_into),*
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Errors> for &str {
|
||||
fn from(value: Errors) -> Self {
|
||||
match value {
|
||||
#(#errors_into),*
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Callbacks> for &str {
|
||||
fn from(value: Callbacks) -> Self {
|
||||
match value {
|
||||
#(#callbacks_into),*
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Events> for &str {
|
||||
fn from(value: Events) -> Self {
|
||||
match value {
|
||||
#(#events_into),*
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<States> for &str {
|
||||
fn from(value: States) -> Self {
|
||||
match value {
|
||||
#(#states_into),*
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Methods {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
self.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl Errors {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
self.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl Callbacks {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
self.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl Events {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
self.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl States {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
self.into()
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn generate_callbacks(callbacks: &[String]) -> TokenStream {
|
||||
let native = native::generate_callbacks(callbacks);
|
||||
let wasm = wasm::generate_callbacks(callbacks);
|
||||
|
||||
TokenStream::from_iter([native, wasm])
|
||||
}
|
||||
|
||||
/// Generates the complete parser.
|
||||
pub fn generate() -> TokenStream {
|
||||
let (methods, errors, callbacks, states) = init_constants();
|
||||
|
||||
let constants_code = generate_constants(&methods, &errors, &callbacks, &states);
|
||||
let enums_code = generate_enums(&methods, &errors, &callbacks, &states);
|
||||
let callbacks_code = generate_callbacks(&callbacks);
|
||||
|
||||
TokenStream::from_iter([constants_code, enums_code, callbacks_code])
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
use proc_macro::TokenStream;
|
||||
|
||||
mod actions;
|
||||
mod generators;
|
||||
mod matchers;
|
||||
mod native;
|
||||
mod parser_fields;
|
||||
mod structs;
|
||||
mod wasm;
|
||||
|
||||
#[proc_macro]
|
||||
pub fn generate(_: TokenStream) -> TokenStream { generators::generate() }
|
||||
|
||||
#[proc_macro]
|
||||
pub fn case_insensitive_string(input: TokenStream) -> TokenStream { matchers::case_insensitive_string(input) }
|
||||
|
||||
#[proc_macro]
|
||||
pub fn event_with_range(input: TokenStream) -> TokenStream { actions::event_with_range(input) }
|
||||
|
||||
#[proc_macro]
|
||||
pub fn event_with_error(input: TokenStream) -> TokenStream { actions::event_with_error(input) }
|
||||
|
||||
#[proc_macro]
|
||||
pub fn event_with_metadata(input: TokenStream) -> TokenStream { actions::event_with_metadata(input) }
|
||||
|
||||
#[proc_macro]
|
||||
pub fn advance(input: TokenStream) -> TokenStream { actions::advance(input) }
|
||||
|
||||
#[proc_macro]
|
||||
pub fn move_to(input: TokenStream) -> TokenStream { actions::move_to(input) }
|
||||
|
||||
#[proc_macro]
|
||||
pub fn next(_: TokenStream) -> TokenStream { actions::next() }
|
||||
|
||||
#[proc_macro]
|
||||
pub fn suspend(_: TokenStream) -> TokenStream { actions::suspend() }
|
||||
|
||||
#[proc_macro]
|
||||
pub fn fail(input: TokenStream) -> TokenStream { actions::fail(input) }
|
||||
@@ -0,0 +1,16 @@
|
||||
use proc_macro::TokenStream;
|
||||
use quote::quote;
|
||||
use syn::{Expr, LitStr, parse_macro_input, parse_str};
|
||||
|
||||
/// Matches a string in case insensitive way.
|
||||
pub fn case_insensitive_string(input: TokenStream) -> TokenStream {
|
||||
let definition = parse_macro_input!(input as LitStr);
|
||||
|
||||
let bytes: Vec<_> = definition
|
||||
.value()
|
||||
.bytes()
|
||||
.map(|b| parse_str::<Expr>(&format!("{} | {}", b.to_ascii_uppercase(), b.to_ascii_lowercase())).unwrap())
|
||||
.collect();
|
||||
|
||||
TokenStream::from(quote! { [#(#bytes),*] })
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
use proc_macro::TokenStream;
|
||||
use quote::{format_ident, quote};
|
||||
|
||||
/// Generates all parser callbacks.
|
||||
pub fn generate_callbacks(callbacks: &[String]) -> TokenStream {
|
||||
let callbacks: Vec<_> = callbacks.iter().map(|x| format_ident!("{}", x)).collect();
|
||||
let replay_arms = callbacks.iter().map(|callback| {
|
||||
let callback_name = callback.to_string();
|
||||
let event_const = format_ident!(
|
||||
"EVENT_{}",
|
||||
callback_name
|
||||
.strip_prefix("on_")
|
||||
.unwrap_or(&callback_name)
|
||||
.to_uppercase()
|
||||
);
|
||||
let active_const = format_ident!("CALLBACK_ACTIVE_{}", callback_name.to_uppercase());
|
||||
|
||||
if callback_name == "on_error" {
|
||||
quote! {
|
||||
#event_const => {
|
||||
let at = unsafe { core::ptr::read_unaligned(self.events.add(cursor + 1) as *const u32) }.to_le() as usize;
|
||||
if self.active_callbacks & #active_const != 0 {
|
||||
(self.callbacks.#callback)(self, at, 0);
|
||||
}
|
||||
cursor += EVENT_ERROR_SIZE;
|
||||
}
|
||||
}
|
||||
} else if callback_name == "on_headers" {
|
||||
quote! {
|
||||
#event_const => {
|
||||
let at = unsafe { core::ptr::read_unaligned(self.events.add(cursor + 1) as *const u32) }.to_le() as usize;
|
||||
if self.active_callbacks & #active_const != 0 {
|
||||
(self.callbacks.#callback)(self, at, 0);
|
||||
}
|
||||
cursor += EVENT_METADATA_SIZE;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
quote! {
|
||||
#event_const => {
|
||||
let at = unsafe { core::ptr::read_unaligned(self.events.add(cursor + 1) as *const u32) }.to_le() as usize;
|
||||
let len = unsafe { core::ptr::read_unaligned(self.events.add(cursor + 5) as *const u32) }.to_le() as usize;
|
||||
if self.active_callbacks & #active_const != 0 {
|
||||
(self.callbacks.#callback)(self, at, len);
|
||||
}
|
||||
cursor += EVENT_RANGE_SIZE;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
TokenStream::from(quote! {
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
fn noop_internal(_parser: &mut Parser, _at: usize, _len: usize) {}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ParserCallbacks {
|
||||
#( pub #callbacks: Callback),*
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl ParserCallbacks {
|
||||
fn new() -> ParserCallbacks {
|
||||
ParserCallbacks {
|
||||
#( #callbacks: noop_internal ),*
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl Parser {
|
||||
#[inline]
|
||||
fn invoke_callbacks(&mut self) {
|
||||
let mut cursor = 0usize;
|
||||
|
||||
loop {
|
||||
let event_type = unsafe { *self.events.add(cursor) };
|
||||
|
||||
match event_type {
|
||||
EVENT_END => break,
|
||||
#(#replay_arms)*
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
use core::mem::offset_of;
|
||||
|
||||
use proc_macro2::TokenStream;
|
||||
use quote::{format_ident, quote};
|
||||
|
||||
type WasmPointer = u32;
|
||||
type WasmUsize = u32;
|
||||
|
||||
// Keep this in sync with parser::Parser when compiled with target_family =
|
||||
// "wasm".
|
||||
#[repr(C)]
|
||||
struct ParserStub {
|
||||
max_start_line_length: WasmUsize,
|
||||
max_header_length: WasmUsize,
|
||||
max_body_payload: u64,
|
||||
autodetect: bool,
|
||||
is_request: bool,
|
||||
suspend_after_headers: bool,
|
||||
manage_unconsumed: bool,
|
||||
continue_without_data: bool,
|
||||
is_connect: bool,
|
||||
skip_body: bool,
|
||||
debug: bool,
|
||||
parsed: u64,
|
||||
position: WasmUsize,
|
||||
state: u8,
|
||||
paused: bool,
|
||||
error_code: u8,
|
||||
content_length: u64,
|
||||
chunk_size: u64,
|
||||
remaining_content_length: u64,
|
||||
remaining_chunk_size: u64,
|
||||
status: u32,
|
||||
method: u8,
|
||||
has_content_length: bool,
|
||||
has_transfer_encoding: bool,
|
||||
has_chunked_transfer_encoding: bool,
|
||||
has_connection_close: bool,
|
||||
has_connection_upgrade: bool,
|
||||
has_upgrade: bool,
|
||||
has_trailers: bool,
|
||||
active_callbacks: u64,
|
||||
active_events: u64,
|
||||
ptr: WasmPointer,
|
||||
error_description: [u8; 255],
|
||||
unconsumed: WasmPointer,
|
||||
unconsumed_len: WasmUsize,
|
||||
error_description_len: u8,
|
||||
events: WasmPointer,
|
||||
}
|
||||
|
||||
pub const FIELDS: &[(&str, usize)] = &[
|
||||
("MAX_START_LINE_LENGTH", offset_of!(ParserStub, max_start_line_length)),
|
||||
("MAX_HEADER_LENGTH", offset_of!(ParserStub, max_header_length)),
|
||||
("MAX_BODY_PAYLOAD", offset_of!(ParserStub, max_body_payload)),
|
||||
("AUTODETECT", offset_of!(ParserStub, autodetect)),
|
||||
("IS_REQUEST", offset_of!(ParserStub, is_request)),
|
||||
("SUSPEND_AFTER_HEADERS", offset_of!(ParserStub, suspend_after_headers)),
|
||||
("MANAGE_UNCONSUMED", offset_of!(ParserStub, manage_unconsumed)),
|
||||
("CONTINUE_WITHOUT_DATA", offset_of!(ParserStub, continue_without_data)),
|
||||
("IS_CONNECT", offset_of!(ParserStub, is_connect)),
|
||||
("SKIP_BODY", offset_of!(ParserStub, skip_body)),
|
||||
("DEBUG", offset_of!(ParserStub, debug)),
|
||||
("PARSED", offset_of!(ParserStub, parsed)),
|
||||
("POSITION", offset_of!(ParserStub, position)),
|
||||
("STATE", offset_of!(ParserStub, state)),
|
||||
("PAUSED", offset_of!(ParserStub, paused)),
|
||||
("ERROR_CODE", offset_of!(ParserStub, error_code)),
|
||||
("CONTENT_LENGTH", offset_of!(ParserStub, content_length)),
|
||||
("CHUNK_SIZE", offset_of!(ParserStub, chunk_size)),
|
||||
(
|
||||
"REMAINING_CONTENT_LENGTH",
|
||||
offset_of!(ParserStub, remaining_content_length),
|
||||
),
|
||||
("REMAINING_CHUNK_SIZE", offset_of!(ParserStub, remaining_chunk_size)),
|
||||
("STATUS", offset_of!(ParserStub, status)),
|
||||
("METHOD", offset_of!(ParserStub, method)),
|
||||
("HAS_CONTENT_LENGTH", offset_of!(ParserStub, has_content_length)),
|
||||
("HAS_TRANSFER_ENCODING", offset_of!(ParserStub, has_transfer_encoding)),
|
||||
(
|
||||
"HAS_CHUNKED_TRANSFER_ENCODING",
|
||||
offset_of!(ParserStub, has_chunked_transfer_encoding),
|
||||
),
|
||||
("HAS_CONNECTION_CLOSE", offset_of!(ParserStub, has_connection_close)),
|
||||
("HAS_CONNECTION_UPGRADE", offset_of!(ParserStub, has_connection_upgrade)),
|
||||
("HAS_UPGRADE", offset_of!(ParserStub, has_upgrade)),
|
||||
("HAS_TRAILERS", offset_of!(ParserStub, has_trailers)),
|
||||
("ACTIVE_CALLBACKS", offset_of!(ParserStub, active_callbacks)),
|
||||
("ACTIVE_EVENTS", offset_of!(ParserStub, active_events)),
|
||||
("PTR", offset_of!(ParserStub, ptr)),
|
||||
("ERROR_DESCRIPTION", offset_of!(ParserStub, error_description)),
|
||||
("UNCONSUMED", offset_of!(ParserStub, unconsumed)),
|
||||
("UNCONSUMED_LEN", offset_of!(ParserStub, unconsumed_len)),
|
||||
("ERROR_DESCRIPTION_LEN", offset_of!(ParserStub, error_description_len)),
|
||||
("EVENTS", offset_of!(ParserStub, events)),
|
||||
];
|
||||
|
||||
pub fn generate_constants() -> TokenStream {
|
||||
let constants = FIELDS.iter().map(|(name, offset)| {
|
||||
let ident = format_ident!("PARSER_FIELD_{}", name);
|
||||
|
||||
quote! {
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub const #ident: usize = #offset;
|
||||
}
|
||||
});
|
||||
|
||||
quote! {
|
||||
#(#constants)*
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn main() {
|
||||
let constants = FIELDS
|
||||
.iter()
|
||||
.map(|(name, offset)| format!("\"PARSER_FIELD_{name}\":{offset}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
|
||||
println!("{{{}}}", constants);
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
use syn::parse::{Parse, ParseStream};
|
||||
use syn::{Expr, Ident, Result, Token};
|
||||
|
||||
/// An identifier associated to a message, typically a string - An example of
|
||||
/// this is used in `fail!`.
|
||||
pub struct FailureRequest {
|
||||
pub error: Ident,
|
||||
pub message: Expr,
|
||||
}
|
||||
|
||||
/// An identifier associated to an expression - An example of this is used in
|
||||
/// `event_with_range!`.
|
||||
pub struct EventRequest {
|
||||
pub identifier: Ident,
|
||||
pub offset: Option<Expr>,
|
||||
pub length: Option<Expr>,
|
||||
}
|
||||
|
||||
impl Parse for FailureRequest {
|
||||
// Parses a failure definition
|
||||
fn parse(input: ParseStream) -> Result<Self> {
|
||||
// Get the code
|
||||
let error = input.parse()?;
|
||||
|
||||
// Discard the comma
|
||||
input.parse::<Token![,]>()?;
|
||||
|
||||
// Get the message
|
||||
let message = input.parse()?;
|
||||
|
||||
Ok(FailureRequest { error, message })
|
||||
}
|
||||
}
|
||||
|
||||
impl Parse for EventRequest {
|
||||
// Parses a identifier and its optional expression
|
||||
fn parse(input: ParseStream) -> Result<Self> {
|
||||
let identifier = input.parse()?;
|
||||
let mut offset = None;
|
||||
let mut length = None;
|
||||
|
||||
// If there is more input
|
||||
if !input.is_empty() {
|
||||
// Discard the comma
|
||||
input.parse::<Token![,]>()?;
|
||||
|
||||
// Parse the expression
|
||||
offset = Some(input.parse::<Expr>()?);
|
||||
|
||||
if !input.is_empty() {
|
||||
// Discard the comma
|
||||
input.parse::<Token![,]>()?;
|
||||
|
||||
// Parse the expression
|
||||
length = Some(input.parse::<Expr>()?);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(EventRequest {
|
||||
identifier,
|
||||
offset,
|
||||
length,
|
||||
})
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
use proc_macro::TokenStream;
|
||||
use quote::{format_ident, quote};
|
||||
|
||||
/// Generates all parser callbacks.
|
||||
pub fn generate_callbacks(callbacks: &[String]) -> TokenStream {
|
||||
let callbacks: Vec<_> = callbacks
|
||||
.iter()
|
||||
.filter(|x| x.as_str() != "on_headers")
|
||||
.map(|x| format_ident!("{}", x))
|
||||
.collect();
|
||||
let replay_arms = callbacks
|
||||
.iter()
|
||||
.filter(|callback| callback.to_string() != "on_error")
|
||||
.map(|callback| {
|
||||
let callback_name = callback.to_string();
|
||||
let event_const = format_ident!(
|
||||
"EVENT_{}",
|
||||
callback_name
|
||||
.strip_prefix("on_")
|
||||
.unwrap_or(&callback_name)
|
||||
.to_uppercase()
|
||||
);
|
||||
let active_const = format_ident!("CALLBACK_ACTIVE_{}", callback_name.to_uppercase());
|
||||
|
||||
quote! {
|
||||
#event_const => {
|
||||
let at = unsafe { core::ptr::read_unaligned(self.events.add(cursor + 1) as *const u32) }.to_le() as usize;
|
||||
let len = unsafe { core::ptr::read_unaligned(self.events.add(cursor + 5) as *const u32) }.to_le() as usize;
|
||||
if self.active_callbacks & #active_const != 0 {
|
||||
unsafe { #callback(self.ptr, at, len); }
|
||||
}
|
||||
cursor += EVENT_RANGE_SIZE;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
TokenStream::from(quote! {
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[link(wasm_import_module = "env")]
|
||||
unsafe extern "C" {
|
||||
#(fn #callbacks(parser: *mut c_void, _at: usize, _len: usize);)*
|
||||
fn on_headers(
|
||||
parser: *mut c_void,
|
||||
at: usize,
|
||||
method_or_status: u32,
|
||||
should_keep_alive: bool,
|
||||
should_upgrade: bool,
|
||||
has_trailers: bool,
|
||||
body_kind: u8,
|
||||
content_length: f64,
|
||||
);
|
||||
|
||||
#[cfg(any(debug_assertions, feature = "debug"))]
|
||||
fn logger(message: u64);
|
||||
}
|
||||
|
||||
#[cfg(all(any(debug_assertions, feature = "debug"), target_family = "wasm"))]
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn __start() {
|
||||
std::panic::set_hook(Box::new(|panic_info| {
|
||||
debug(format!("WebAssembly panicked: {:#?}", panic_info));
|
||||
}));
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
impl Parser {
|
||||
#[inline]
|
||||
fn invoke_callbacks(&mut self) {
|
||||
let mut cursor = 0usize;
|
||||
|
||||
loop {
|
||||
let event_type = unsafe { *self.events.add(cursor) };
|
||||
|
||||
match event_type {
|
||||
EVENT_END => break,
|
||||
EVENT_ERROR => {
|
||||
let at = unsafe { core::ptr::read_unaligned(self.events.add(cursor + 1) as *const u32) }.to_le() as usize;
|
||||
if self.active_callbacks & CALLBACK_ACTIVE_ON_ERROR != 0 {
|
||||
unsafe { on_error(self.ptr, at, 0); }
|
||||
}
|
||||
cursor += EVENT_ERROR_SIZE;
|
||||
}
|
||||
EVENT_HEADERS => {
|
||||
let at = unsafe { core::ptr::read_unaligned(self.events.add(cursor + 1) as *const u32) }.to_le() as usize;
|
||||
let method_or_status = unsafe { core::ptr::read_unaligned(self.events.add(cursor + 5) as *const u16) }.to_le() as u32;
|
||||
let should_keep_alive = unsafe { *self.events.add(cursor + 7) } != 0;
|
||||
let should_upgrade = unsafe { *self.events.add(cursor + 8) } != 0;
|
||||
let has_trailers = unsafe { *self.events.add(cursor + 9) } != 0;
|
||||
let body_kind = unsafe { *self.events.add(cursor + 10) };
|
||||
let content_length = unsafe { core::ptr::read_unaligned(self.events.add(cursor + 11) as *const u64) }.to_le() as f64;
|
||||
|
||||
if self.active_callbacks & CALLBACK_ACTIVE_ON_HEADERS != 0 {
|
||||
unsafe {
|
||||
on_headers(
|
||||
self.ptr,
|
||||
at,
|
||||
method_or_status,
|
||||
should_keep_alive,
|
||||
should_upgrade,
|
||||
has_trailers,
|
||||
body_kind,
|
||||
content_length,
|
||||
);
|
||||
}
|
||||
}
|
||||
cursor += EVENT_METADATA_SIZE;
|
||||
}
|
||||
#(#replay_arms)*
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
[package]
|
||||
name = "milo-parser"
|
||||
version = "0.9.0"
|
||||
edition = "2024"
|
||||
description = "A fast and embeddable HTTP/1.1 parser."
|
||||
homepage = "https://sw.cowtech.it/milo"
|
||||
repository = "https://github.com/ShogunPanda/milo"
|
||||
license = "ISC"
|
||||
keywords = ["http", "parser", "http-parser"]
|
||||
categories = ["network-programming", "parser-implementations"]
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "staticlib", "lib"]
|
||||
|
||||
[[bin]]
|
||||
name = "milo-parser"
|
||||
path = "src/main.rs"
|
||||
|
||||
[features]
|
||||
debug = []
|
||||
|
||||
[dependencies]
|
||||
milo-macros = { version = "0.9.0", path = "../macros" }
|
||||
memchr = "2.8.0"
|
||||
|
||||
[dev-dependencies]
|
||||
comfy-table = { version = "7.2.2" }
|
||||
libc = "0.2"
|
||||
regex = "1.12.3"
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_json = "1.0.145"
|
||||
serde_yaml = "0.9.34"
|
||||
similar = "3.0.0"
|
||||
|
||||
[profile.release]
|
||||
opt-level = 3
|
||||
debug = false
|
||||
debug-assertions = false
|
||||
overflow-checks = false
|
||||
lto = true
|
||||
panic = 'abort'
|
||||
incremental = false
|
||||
codegen-units = 1
|
||||
rpath = false
|
||||
strip = true
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
[config]
|
||||
skip_core_tasks = true
|
||||
|
||||
[env]
|
||||
TARGET = { script = ["rustc -vV | sed -n 's|host: ||p'"] }
|
||||
|
||||
[tasks.default]
|
||||
dependencies = ["build"]
|
||||
|
||||
[tasks.build]
|
||||
dependencies = ["cpp", "wasm"]
|
||||
|
||||
[tasks.test]
|
||||
dependencies = ["build", "test:rust", "test:wasm"]
|
||||
|
||||
[tasks."test:rust"]
|
||||
command = "cargo"
|
||||
args = ["test"]
|
||||
|
||||
[tasks."test:wasm"]
|
||||
dependencies = ["wasm:release"]
|
||||
command = "node"
|
||||
args = ["--test", "--test-reporter=cleaner-spec-reporter", "wasm/test/*.test.js"]
|
||||
|
||||
[tasks.cpp]
|
||||
dependencies = ["cpp:headers", "cpp:libs"]
|
||||
|
||||
[tasks.wasm]
|
||||
dependencies = ["wasm:release", "wasm:debug"]
|
||||
|
||||
[tasks."cpp:libs"]
|
||||
dependencies = ["cpp:release", "cpp:debug"]
|
||||
|
||||
[tasks."cpp:release"]
|
||||
env = { CONFIGURATION = "release", "CARGO_OPTIONS" = "--release" }
|
||||
run_task = "cpp:lib"
|
||||
|
||||
[tasks."cpp:debug"]
|
||||
env = { CONFIGURATION = "debug", "CARGO_OPTIONS" = "--release --features debug" }
|
||||
run_task = "cpp:lib"
|
||||
|
||||
[tasks."cpp:lib"]
|
||||
dependencies = ["scripts:build"]
|
||||
script = ["mkdir -p ../dist/cpp/${CONFIGURATION}", "rm -rf ../dist/cpp/${CONFIGURATION}/*", "cargo build --locked -Z unstable-options --target ${TARGET} ${CARGO_OPTIONS} --artifact-dir target/cpp/${CONFIGURATION}", "cp target/cpp/${CONFIGURATION}/libmilo_parser.a ../dist/cpp/${CONFIGURATION}/libmilo.a", "cp target/headers/milo.h ../dist/cpp/${CONFIGURATION}", "../scripts/target/release/postbuild-cpp ${CONFIGURATION}"]
|
||||
|
||||
[tasks."scripts:build"]
|
||||
command = "cargo"
|
||||
args = ["build", "--locked", "--release", "--manifest-path", "../scripts/Cargo.toml", "--target-dir", "../scripts/target", "--bins"]
|
||||
|
||||
[tasks."cpp:headers"]
|
||||
command = "cbindgen"
|
||||
args = ["--quiet", "--output", "target/headers/milo.h"]
|
||||
|
||||
[tasks."wasm:release"]
|
||||
env = { CONFIGURATION = "release", CARGO_BUILD_OPTIONS = "-Z unstable-options -Z build-std=std,panic_abort", CARGO_OPTIONS = "--release", RUSTFLAGS_BASE = "-Z unstable-options -C panic=immediate-abort", WASMPACK_OPTIONS = "--release" }
|
||||
run_task = "wasm:module"
|
||||
|
||||
[tasks."wasm:debug"]
|
||||
env = { CONFIGURATION = "debug", CARGO_BUILD_OPTIONS = "-Z unstable-options", CARGO_OPTIONS = "--release --features debug", RUSTFLAGS_BASE = "", WASMPACK_OPTIONS = "--release" }
|
||||
run_task = "wasm:module"
|
||||
|
||||
[tasks."wasm:module"]
|
||||
dependencies = ["scripts:build"]
|
||||
script = ["mkdir -p ../dist/wasm", "rm -rf ../dist/wasm/${CONFIGURATION}", "mkdir -p ../dist/wasm/${CONFIGURATION}/binary", "RUSTFLAGS=\"${RUSTFLAGS_BASE} -C target-feature=+simd128\" cargo build --locked --lib ${CARGO_BUILD_OPTIONS} --target wasm32-unknown-unknown ${CARGO_OPTIONS}", "cp -a target/wasm32-unknown-unknown/release/milo_parser.wasm ../dist/wasm/${CONFIGURATION}/binary/simd.wasm", "wasm-opt -O3 --enable-bulk-memory-opt --enable-simd -o ../dist/wasm/${CONFIGURATION}/binary/simd.wasm ../dist/wasm/${CONFIGURATION}/binary/simd.wasm", "RUSTFLAGS=\"${RUSTFLAGS_BASE}\" cargo build --locked --lib ${CARGO_BUILD_OPTIONS} --target wasm32-unknown-unknown ${CARGO_OPTIONS}", "cp -a target/wasm32-unknown-unknown/release/milo_parser.wasm ../dist/wasm/${CONFIGURATION}/binary/no-simd.wasm", "wasm-opt -O3 --enable-bulk-memory-opt -o ../dist/wasm/${CONFIGURATION}/binary/no-simd.wasm ../dist/wasm/${CONFIGURATION}/binary/no-simd.wasm", "../scripts/target/release/postbuild-wasm ${CONFIGURATION}"]
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
# Milo Parser
|
||||
|
||||
This folder contains the milo main parser.
|
||||
|
||||
To build milo, simply run:
|
||||
|
||||
```bash
|
||||
makers
|
||||
```
|
||||
|
||||
this will generate `cpp` and `wasm` build in `dist` folder.
|
||||
These files can be copied in the source code to embed milo.
|
||||
|
||||
## How to use the API
|
||||
|
||||
See the main [README.md](../README.md) in the parent folder.
|
||||
|
||||
## Verify compiled code and macro substitution
|
||||
|
||||
Once [cargo-expand](https://github.com/dtolnay/cargo-expand), is installed, run:
|
||||
|
||||
```bash
|
||||
cargo expand > compiled.rs
|
||||
```
|
||||
|
||||
This will generate a file which can be analyzed to see what is the final compiled code after all macros have been evaluated.
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
language = "C++"
|
||||
include_guard = "MILO_H"
|
||||
namespace = "milo_parser"
|
||||
|
||||
[parse.expand]
|
||||
crates = ["milo-parser"]
|
||||
|
||||
[export]
|
||||
include = [
|
||||
"Parser",
|
||||
"ParserCallbacks",
|
||||
"CStringWithLength",
|
||||
"Callback",
|
||||
"MessageTypes",
|
||||
"Connections",
|
||||
"Methods",
|
||||
"States",
|
||||
"Errors",
|
||||
"Callbacks",
|
||||
"Events",
|
||||
]
|
||||
+359
@@ -0,0 +1,359 @@
|
||||
#![allow(unused_imports)]
|
||||
|
||||
extern crate alloc;
|
||||
|
||||
use alloc::ffi::CString;
|
||||
use alloc::vec::Vec;
|
||||
use alloc::{boxed::Box, format};
|
||||
use core::cell::{Cell, RefCell};
|
||||
use core::ffi::{c_char, c_uchar, c_void};
|
||||
use core::fmt::Debug;
|
||||
use core::str;
|
||||
use core::{mem, ptr};
|
||||
use core::{slice, slice::from_raw_parts};
|
||||
|
||||
use milo_macros::generate;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug)]
|
||||
pub struct Parser {
|
||||
// User writable
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub context: *mut c_void,
|
||||
pub max_start_line_length: usize,
|
||||
pub max_header_length: usize,
|
||||
pub max_body_payload: u64,
|
||||
pub autodetect: bool,
|
||||
pub is_request: bool,
|
||||
pub suspend_after_headers: bool,
|
||||
pub manage_unconsumed: bool,
|
||||
pub continue_without_data: bool,
|
||||
pub is_connect: bool,
|
||||
pub skip_body: bool,
|
||||
pub debug: bool,
|
||||
|
||||
// Generic state
|
||||
pub parsed: u64,
|
||||
pub position: usize,
|
||||
pub state: u8,
|
||||
pub paused: bool,
|
||||
pub error_code: u8,
|
||||
|
||||
// Current message flags
|
||||
pub content_length: u64,
|
||||
pub chunk_size: u64,
|
||||
pub remaining_content_length: u64,
|
||||
pub remaining_chunk_size: u64,
|
||||
pub status: u32,
|
||||
pub method: u8,
|
||||
pub has_content_length: bool,
|
||||
pub has_transfer_encoding: bool,
|
||||
pub has_chunked_transfer_encoding: bool,
|
||||
pub has_connection_close: bool,
|
||||
pub has_connection_upgrade: bool,
|
||||
pub has_upgrade: bool,
|
||||
pub has_trailers: bool,
|
||||
|
||||
// Callback handling
|
||||
pub active_callbacks: u64,
|
||||
pub active_events: u64,
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub callbacks: ParserCallbacks,
|
||||
|
||||
// WASM Specific
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub ptr: *mut c_void,
|
||||
|
||||
// Complex data types - We need to split them in order to be exportable to C++
|
||||
pub error_description: [u8; 255],
|
||||
pub unconsumed: *const c_uchar,
|
||||
pub unconsumed_len: usize,
|
||||
pub error_description_len: u8,
|
||||
|
||||
// Event buffer. Keep this at the end of the struct for external readers.
|
||||
pub events: *mut c_uchar,
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
mod native;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub use crate::native::*;
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
mod wasm;
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub use crate::wasm::*;
|
||||
|
||||
generate!();
|
||||
|
||||
impl Parser {
|
||||
/// Creates a new parser
|
||||
pub fn new() -> Parser {
|
||||
let mut events = Box::new([0u8; 65536]);
|
||||
let events_ptr = events.as_mut_ptr();
|
||||
mem::forget(events);
|
||||
|
||||
Parser {
|
||||
// User writable
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
context: ptr::null_mut(),
|
||||
max_start_line_length: 8192,
|
||||
max_header_length: 8192,
|
||||
max_body_payload: 0,
|
||||
autodetect: true,
|
||||
is_request: false,
|
||||
suspend_after_headers: false,
|
||||
manage_unconsumed: false,
|
||||
continue_without_data: false,
|
||||
is_connect: false,
|
||||
skip_body: false,
|
||||
debug: false,
|
||||
// Generic state
|
||||
parsed: 0,
|
||||
position: 0,
|
||||
state: STATE_START,
|
||||
paused: false,
|
||||
error_code: ERROR_NONE,
|
||||
// Current message flags
|
||||
content_length: 0,
|
||||
chunk_size: 0,
|
||||
remaining_content_length: 0,
|
||||
remaining_chunk_size: 0,
|
||||
status: 0,
|
||||
method: 0,
|
||||
has_content_length: false,
|
||||
has_transfer_encoding: false,
|
||||
has_chunked_transfer_encoding: false,
|
||||
has_connection_close: false,
|
||||
has_connection_upgrade: false,
|
||||
has_upgrade: false,
|
||||
has_trailers: false,
|
||||
// Callbacks handling
|
||||
active_callbacks: 0,
|
||||
active_events: 0,
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
callbacks: ParserCallbacks::new(),
|
||||
// WASM Specific
|
||||
#[cfg(target_family = "wasm")]
|
||||
ptr: ptr::null_mut(),
|
||||
// Complex data types
|
||||
error_description: [0; 255],
|
||||
unconsumed: ptr::null(),
|
||||
unconsumed_len: 0,
|
||||
error_description_len: 0,
|
||||
events: events_ptr,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resets a parser. The second parameters specifies if to also reset the
|
||||
/// parsed counter.
|
||||
///
|
||||
/// The following fields are not modified:
|
||||
/// * position
|
||||
/// * context
|
||||
/// * autodetect
|
||||
/// * is_request
|
||||
/// * suspend_after_headers
|
||||
/// * manage_unconsumed
|
||||
/// * continue_without_data
|
||||
/// * debug
|
||||
/// * context
|
||||
pub fn reset(&mut self, keep_parsed: bool) {
|
||||
self.state = STATE_START;
|
||||
self.paused = false;
|
||||
|
||||
if !keep_parsed {
|
||||
self.parsed = 0;
|
||||
}
|
||||
|
||||
self.error_code = ERROR_NONE;
|
||||
|
||||
self.error_description[0] = 0;
|
||||
self.error_description_len = 0;
|
||||
|
||||
self.clear_unconsumed();
|
||||
|
||||
self.clear();
|
||||
self.skip_body = false;
|
||||
unsafe {
|
||||
*self.events = EVENT_END;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn clear_unconsumed(&mut self) {
|
||||
if self.unconsumed_len > 0 {
|
||||
// SAFETY: Retained input is allocated as a boxed slice with exactly this
|
||||
// length, and the parser owns it until replacement, reset, or destruction.
|
||||
unsafe {
|
||||
drop(Box::from_raw(ptr::slice_from_raw_parts_mut(
|
||||
self.unconsumed as *mut c_uchar,
|
||||
self.unconsumed_len,
|
||||
)));
|
||||
}
|
||||
}
|
||||
self.unconsumed = ptr::null();
|
||||
self.unconsumed_len = 0;
|
||||
}
|
||||
|
||||
/// Clears all values about the message in the parser.
|
||||
pub fn clear(&mut self) {
|
||||
self.is_connect = false;
|
||||
self.method = 0;
|
||||
self.status = 0;
|
||||
self.has_content_length = false;
|
||||
self.has_transfer_encoding = false;
|
||||
self.has_chunked_transfer_encoding = false;
|
||||
self.has_connection_close = false;
|
||||
self.has_connection_upgrade = false;
|
||||
self.has_upgrade = false;
|
||||
self.has_trailers = false;
|
||||
self.content_length = 0;
|
||||
self.chunk_size = 0;
|
||||
self.remaining_content_length = 0;
|
||||
self.remaining_chunk_size = 0;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn try_emit_event_range(
|
||||
&mut self,
|
||||
event_cursor: &mut usize,
|
||||
event_type: u8,
|
||||
at: usize,
|
||||
len: usize,
|
||||
) -> bool {
|
||||
// Reserve six bytes for a later error event and one for the terminator.
|
||||
if *event_cursor + EVENT_RANGE_SIZE + EVENT_ERROR_RESERVE > EVENTS_BUFFER_SIZE {
|
||||
return false;
|
||||
}
|
||||
|
||||
unsafe {
|
||||
*self.events.add(*event_cursor) = event_type;
|
||||
core::ptr::write_unaligned(self.events.add(*event_cursor + 1) as *mut u32, (at as u32).to_le());
|
||||
core::ptr::write_unaligned(self.events.add(*event_cursor + 5) as *mut u32, (len as u32).to_le());
|
||||
}
|
||||
*event_cursor += EVENT_RANGE_SIZE;
|
||||
true
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn try_emit_event_error(&mut self, event_cursor: &mut usize) -> bool {
|
||||
if *event_cursor + EVENT_ERROR_SIZE + EVENT_END_SIZE > EVENTS_BUFFER_SIZE {
|
||||
return false;
|
||||
}
|
||||
|
||||
unsafe {
|
||||
*self.events.add(*event_cursor) = EVENT_ERROR;
|
||||
core::ptr::write_unaligned(
|
||||
self.events.add(*event_cursor + 1) as *mut u32,
|
||||
(self.position as u32).to_le(),
|
||||
);
|
||||
*self.events.add(*event_cursor + 5) = self.error_code;
|
||||
}
|
||||
*event_cursor += EVENT_ERROR_SIZE;
|
||||
true
|
||||
}
|
||||
|
||||
/// Pauses the parser. It will have to be resumed via `resume`.
|
||||
pub fn pause(&mut self) { self.paused = true; }
|
||||
|
||||
/// Resumes the parser.
|
||||
pub fn resume(&mut self) { self.paused = false; }
|
||||
|
||||
/// Marks the parser as finished. Any new data received via `parse` will
|
||||
/// put the parser in the error state.
|
||||
pub fn finish(&mut self) {
|
||||
match self.state {
|
||||
// If the parser is one of the initial states, simply jump to finish
|
||||
STATE_START | STATE_REQUEST_LINE | STATE_STATUS_LINE | STATE_FINISH => {
|
||||
self.state = STATE_FINISH;
|
||||
}
|
||||
STATE_BODY_WITH_NO_LENGTH => {
|
||||
// Notify that the message has been completed
|
||||
let active_events = self.active_events | self.active_callbacks;
|
||||
let mut event_cursor = 0usize;
|
||||
if active_events & EVENT_ACTIVE_ON_MESSAGE_COMPLETE != 0 {
|
||||
self.try_emit_event_range(&mut event_cursor, EVENT_MESSAGE_COMPLETE, self.position, 0);
|
||||
}
|
||||
unsafe {
|
||||
*self.events.add(event_cursor) = EVENT_END;
|
||||
}
|
||||
|
||||
// Set the state to be finished
|
||||
self.state = STATE_FINISH;
|
||||
}
|
||||
STATE_ERROR => (),
|
||||
// In another other state, this is an error
|
||||
_ => {
|
||||
self.fail(ERROR_UNEXPECTED_EOF, "Unexpected end of data");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Marks parsing as failed and starts a standalone error event batch.
|
||||
#[inline(always)]
|
||||
pub fn fail(&mut self, code: u8, description: &str) {
|
||||
self.set_error(code, description);
|
||||
let mut event_cursor = 0usize;
|
||||
if (self.active_events | self.active_callbacks) & EVENT_ACTIVE_ON_ERROR != 0 {
|
||||
self.try_emit_event_error(&mut event_cursor);
|
||||
}
|
||||
// SAFETY: The cursor follows at most one error event in the owned event buffer.
|
||||
unsafe {
|
||||
*self.events.add(event_cursor) = EVENT_END;
|
||||
}
|
||||
}
|
||||
|
||||
/// Records an error without changing the current event batch.
|
||||
#[inline(always)]
|
||||
pub(crate) fn set_error(&mut self, code: u8, description: &str) {
|
||||
let bytes = description.as_bytes();
|
||||
let len = bytes.len().min(254);
|
||||
|
||||
self.state = STATE_ERROR;
|
||||
self.error_code = code;
|
||||
self.error_description[..len].copy_from_slice(&bytes[..len]);
|
||||
self.error_description[len] = 0;
|
||||
self.error_description_len = len as u8;
|
||||
}
|
||||
|
||||
/// Returns the current parser's state as string.
|
||||
pub fn state_str(&self) -> &str { States::try_from(self.state).unwrap().as_str() }
|
||||
|
||||
/// Returns the current parser's error state as string.
|
||||
pub fn error_code_str(&self) -> &str { Errors::try_from(self.error_code).unwrap().as_str() }
|
||||
|
||||
/// Returns the current parser's error description as string.
|
||||
pub fn error_description_str(&self) -> &str {
|
||||
unsafe {
|
||||
if self.error_description_len > 0 {
|
||||
str::from_utf8_unchecked(from_raw_parts(
|
||||
self.error_description.as_ptr(),
|
||||
self.error_description_len as usize,
|
||||
))
|
||||
} else {
|
||||
""
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Parser {
|
||||
fn drop(&mut self) {
|
||||
self.clear_unconsumed();
|
||||
if !self.events.is_null() {
|
||||
unsafe {
|
||||
let _ = Box::from_raw(self.events as *mut [u8; 65536]);
|
||||
}
|
||||
self.events = ptr::null_mut();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Parser {
|
||||
fn default() -> Self { Self::new() }
|
||||
}
|
||||
|
||||
mod matchers;
|
||||
mod parse;
|
||||
+271
@@ -0,0 +1,271 @@
|
||||
use std::env;
|
||||
use std::ffi::c_void;
|
||||
use std::fs;
|
||||
use std::io::{self, Read};
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use milo_parser::{CALLBACK_ACTIVE_ALL, Parser, STATE_ERROR};
|
||||
|
||||
struct Options {
|
||||
file: Option<PathBuf>,
|
||||
mode: Mode,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Mode {
|
||||
Autodetect,
|
||||
Request,
|
||||
Response,
|
||||
}
|
||||
|
||||
struct Context {
|
||||
output: Vec<String>,
|
||||
}
|
||||
|
||||
enum RunError {
|
||||
Usage(String),
|
||||
Io(String),
|
||||
}
|
||||
|
||||
fn print_usage() {
|
||||
eprintln!("Usage: milo-parser [-f|--file PATH] [-o|--request | -i|--response]");
|
||||
}
|
||||
|
||||
fn parse_args() -> Result<Options, String> {
|
||||
let mut args = env::args().skip(1);
|
||||
let mut options = Options {
|
||||
file: None,
|
||||
mode: Mode::Autodetect,
|
||||
};
|
||||
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
"-f" | "--file" => {
|
||||
let path = args.next().ok_or_else(|| format!("Missing value for {arg}"))?;
|
||||
options.file = Some(PathBuf::from(path));
|
||||
}
|
||||
"-o" | "--request" => {
|
||||
if options.mode != Mode::Autodetect {
|
||||
return Err("Cannot use both request and response mode".into());
|
||||
}
|
||||
|
||||
options.mode = Mode::Request;
|
||||
}
|
||||
"-i" | "--response" => {
|
||||
if options.mode != Mode::Autodetect {
|
||||
return Err("Cannot use both request and response mode".into());
|
||||
}
|
||||
|
||||
options.mode = Mode::Response;
|
||||
}
|
||||
"-h" | "--help" => {
|
||||
print_usage();
|
||||
std::process::exit(0);
|
||||
}
|
||||
_ => return Err(format!("Unknown argument: {arg}")),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
fn read_input(options: &Options) -> io::Result<Vec<u8>> {
|
||||
match &options.file {
|
||||
Some(path) => fs::read(path),
|
||||
None => {
|
||||
let mut input = Vec::new();
|
||||
io::stdin().read_to_end(&mut input)?;
|
||||
Ok(input)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn quote(value: &str) -> String {
|
||||
let mut quoted = String::with_capacity(value.len() + 2);
|
||||
quoted.push('"');
|
||||
|
||||
for c in value.chars() {
|
||||
match c {
|
||||
'"' => quoted.push_str("\\\""),
|
||||
'\\' => quoted.push_str("\\\\"),
|
||||
'\n' => quoted.push_str("\\n"),
|
||||
'\r' => quoted.push_str("\\r"),
|
||||
'\t' => quoted.push_str("\\t"),
|
||||
_ => quoted.push(c),
|
||||
}
|
||||
}
|
||||
|
||||
quoted.push('"');
|
||||
quoted
|
||||
}
|
||||
|
||||
fn append_output(parser: &mut Parser, line: String) {
|
||||
let mut context = unsafe { Box::from_raw(parser.context as *mut Context) };
|
||||
context.output.push(line);
|
||||
let _ = Box::into_raw(context);
|
||||
}
|
||||
|
||||
fn event(parser: &mut Parser, offset: usize, size: usize, name: &str) {
|
||||
append_output(parser, format!("offset={offset} size={size} event={name}"));
|
||||
}
|
||||
|
||||
fn on_error(parser: &mut Parser, offset: usize, size: usize) {
|
||||
append_output(
|
||||
parser,
|
||||
format!(
|
||||
"offset={offset} size={size} event=error error={} description={}",
|
||||
parser.error_code_str(),
|
||||
quote(parser.error_description_str())
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
fn on_finish(parser: &mut Parser, offset: usize, size: usize) { event(parser, offset, size, "finish"); }
|
||||
|
||||
fn on_message_start(parser: &mut Parser, offset: usize, size: usize) { event(parser, offset, size, "message_start"); }
|
||||
|
||||
fn on_message_complete(parser: &mut Parser, offset: usize, size: usize) {
|
||||
event(parser, offset, size, "message_complete");
|
||||
}
|
||||
|
||||
fn on_request(parser: &mut Parser, offset: usize, size: usize) { event(parser, offset, size, "request"); }
|
||||
|
||||
fn on_response(parser: &mut Parser, offset: usize, size: usize) { event(parser, offset, size, "response"); }
|
||||
|
||||
fn on_reset(parser: &mut Parser, offset: usize, size: usize) { event(parser, offset, size, "reset"); }
|
||||
|
||||
fn on_method(parser: &mut Parser, offset: usize, size: usize) { event(parser, offset, size, "method"); }
|
||||
|
||||
fn on_url(parser: &mut Parser, offset: usize, size: usize) { event(parser, offset, size, "url"); }
|
||||
|
||||
fn on_protocol(parser: &mut Parser, offset: usize, size: usize) { event(parser, offset, size, "protocol"); }
|
||||
|
||||
fn on_version(parser: &mut Parser, offset: usize, size: usize) { event(parser, offset, size, "version"); }
|
||||
|
||||
fn on_status(parser: &mut Parser, offset: usize, size: usize) { event(parser, offset, size, "status"); }
|
||||
|
||||
fn on_reason(parser: &mut Parser, offset: usize, size: usize) { event(parser, offset, size, "reason"); }
|
||||
|
||||
fn on_header_name(parser: &mut Parser, offset: usize, size: usize) { event(parser, offset, size, "header_name"); }
|
||||
|
||||
fn on_header_value(parser: &mut Parser, offset: usize, size: usize) { event(parser, offset, size, "header_value"); }
|
||||
|
||||
fn on_headers(parser: &mut Parser, offset: usize, size: usize) { event(parser, offset, size, "headers"); }
|
||||
|
||||
fn on_connect(parser: &mut Parser, offset: usize, size: usize) { event(parser, offset, size, "connect"); }
|
||||
|
||||
fn on_upgrade(parser: &mut Parser, offset: usize, size: usize) { event(parser, offset, size, "upgrade"); }
|
||||
|
||||
fn on_chunk_length(parser: &mut Parser, offset: usize, size: usize) { event(parser, offset, size, "chunk_length"); }
|
||||
|
||||
fn on_chunk_extension_name(parser: &mut Parser, offset: usize, size: usize) {
|
||||
event(parser, offset, size, "chunk_extension_name");
|
||||
}
|
||||
|
||||
fn on_chunk_extension_value(parser: &mut Parser, offset: usize, size: usize) {
|
||||
event(parser, offset, size, "chunk_extension_value");
|
||||
}
|
||||
|
||||
fn on_chunk(parser: &mut Parser, offset: usize, size: usize) { event(parser, offset, size, "chunk"); }
|
||||
|
||||
fn on_body(parser: &mut Parser, offset: usize, size: usize) { event(parser, offset, size, "body"); }
|
||||
|
||||
fn on_data(parser: &mut Parser, offset: usize, size: usize) { event(parser, offset, size, "data"); }
|
||||
|
||||
fn on_trailer_name(parser: &mut Parser, offset: usize, size: usize) { event(parser, offset, size, "trailer_name"); }
|
||||
|
||||
fn on_trailer_value(parser: &mut Parser, offset: usize, size: usize) { event(parser, offset, size, "trailer_value"); }
|
||||
|
||||
fn on_trailers(parser: &mut Parser, offset: usize, size: usize) { event(parser, offset, size, "trailers"); }
|
||||
|
||||
fn on_state_change(parser: &mut Parser, offset: usize, size: usize) { event(parser, offset, size, "state_change"); }
|
||||
|
||||
fn create_parser(mode: Mode) -> Parser {
|
||||
let mut parser = Parser::new();
|
||||
let context = Box::new(Context { output: Vec::new() });
|
||||
parser.context = Box::into_raw(context) as *mut c_void;
|
||||
parser.active_callbacks = CALLBACK_ACTIVE_ALL;
|
||||
|
||||
match mode {
|
||||
Mode::Autodetect => {
|
||||
parser.autodetect = true;
|
||||
}
|
||||
Mode::Request => {
|
||||
parser.autodetect = false;
|
||||
parser.is_request = true;
|
||||
}
|
||||
Mode::Response => {
|
||||
parser.autodetect = false;
|
||||
parser.is_request = false;
|
||||
}
|
||||
}
|
||||
|
||||
parser.callbacks.on_error = on_error;
|
||||
parser.callbacks.on_finish = on_finish;
|
||||
parser.callbacks.on_message_start = on_message_start;
|
||||
parser.callbacks.on_message_complete = on_message_complete;
|
||||
parser.callbacks.on_request = on_request;
|
||||
parser.callbacks.on_response = on_response;
|
||||
parser.callbacks.on_reset = on_reset;
|
||||
parser.callbacks.on_method = on_method;
|
||||
parser.callbacks.on_url = on_url;
|
||||
parser.callbacks.on_protocol = on_protocol;
|
||||
parser.callbacks.on_version = on_version;
|
||||
parser.callbacks.on_status = on_status;
|
||||
parser.callbacks.on_reason = on_reason;
|
||||
parser.callbacks.on_header_name = on_header_name;
|
||||
parser.callbacks.on_header_value = on_header_value;
|
||||
parser.callbacks.on_headers = on_headers;
|
||||
parser.callbacks.on_connect = on_connect;
|
||||
parser.callbacks.on_upgrade = on_upgrade;
|
||||
parser.callbacks.on_chunk_length = on_chunk_length;
|
||||
parser.callbacks.on_chunk_extension_name = on_chunk_extension_name;
|
||||
parser.callbacks.on_chunk_extension_value = on_chunk_extension_value;
|
||||
parser.callbacks.on_chunk = on_chunk;
|
||||
parser.callbacks.on_body = on_body;
|
||||
parser.callbacks.on_data = on_data;
|
||||
parser.callbacks.on_trailer_name = on_trailer_name;
|
||||
parser.callbacks.on_trailer_value = on_trailer_value;
|
||||
parser.callbacks.on_trailers = on_trailers;
|
||||
parser.callbacks.on_state_change = on_state_change;
|
||||
|
||||
parser
|
||||
}
|
||||
|
||||
fn run() -> Result<bool, RunError> {
|
||||
let options = parse_args().map_err(RunError::Usage)?;
|
||||
let input = read_input(&options).map_err(|e| RunError::Io(e.to_string()))?;
|
||||
let mut parser = create_parser(options.mode);
|
||||
|
||||
parser.parse(input.as_ptr(), input.len());
|
||||
|
||||
if parser.state != STATE_ERROR {
|
||||
parser.finish();
|
||||
}
|
||||
|
||||
let failed = parser.state == STATE_ERROR;
|
||||
let context = unsafe { Box::from_raw(parser.context as *mut Context) };
|
||||
|
||||
for line in &context.output {
|
||||
println!("{line}");
|
||||
}
|
||||
|
||||
Ok(failed)
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
match run() {
|
||||
Ok(false) => ExitCode::SUCCESS,
|
||||
Ok(true) => ExitCode::from(1),
|
||||
Err(RunError::Usage(error)) => {
|
||||
eprintln!("{error}");
|
||||
print_usage();
|
||||
ExitCode::from(2)
|
||||
}
|
||||
Err(RunError::Io(error)) => {
|
||||
eprintln!("{error}");
|
||||
ExitCode::from(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
+489
@@ -0,0 +1,489 @@
|
||||
use crate::{QUOTED_PAIR_TABLE, QUOTED_STRING_TABLE, TOKEN_TABLE, URL_TABLE};
|
||||
|
||||
pub enum MatchResult {
|
||||
Continue,
|
||||
Suspend,
|
||||
Stop,
|
||||
}
|
||||
|
||||
pub enum HeaderLineScanResult {
|
||||
Cr(usize),
|
||||
Invalid(usize),
|
||||
Incomplete,
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn ensure_valid_line(data: &[u8], cr: usize, available: usize) -> MatchResult {
|
||||
if cr + 1 == available {
|
||||
MatchResult::Suspend
|
||||
} else if data[cr + 1] != b'\n' {
|
||||
MatchResult::Stop
|
||||
} else {
|
||||
MatchResult::Continue
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn find_cr(data: &[u8], available: usize) -> Option<usize> {
|
||||
if available == 0 {
|
||||
None
|
||||
} else {
|
||||
find_char(data, 0, available - 1, b'\r')
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn find_char(buf: &[u8], start: usize, end: usize, needle: u8) -> Option<usize> {
|
||||
if start > end || end >= buf.len() {
|
||||
return None;
|
||||
}
|
||||
|
||||
memchr::memchr(needle, &buf[start..=end]).map(|i| start + i)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn find_char2(buf: &[u8], start: usize, end: usize, needle1: u8, needle2: u8) -> Option<usize> {
|
||||
if start > end || end >= buf.len() {
|
||||
return None;
|
||||
}
|
||||
|
||||
memchr::memchr2(needle1, needle2, &buf[start..=end]).map(|i| start + i)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn is_digit(byte: u8) -> bool { byte.wrapping_sub(b'0') <= 9 }
|
||||
|
||||
#[inline(always)]
|
||||
pub fn is_ws(byte: u8) -> bool { byte == b' ' || byte == b'\t' }
|
||||
|
||||
#[inline(always)]
|
||||
pub fn validate_token(data: &[u8], start: usize, end: usize) -> bool {
|
||||
if start == end {
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut i = start;
|
||||
while i < end {
|
||||
if !TOKEN_TABLE[data[i] as usize] {
|
||||
return false;
|
||||
}
|
||||
|
||||
i += 1;
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn validate_quoted_string(data: &[u8], start: usize, end: usize) -> bool {
|
||||
let mut i = start;
|
||||
while i < end {
|
||||
let byte = data[i];
|
||||
if byte == b'\\' {
|
||||
i += 1;
|
||||
if i == end || !QUOTED_PAIR_TABLE[data[i] as usize] {
|
||||
return false;
|
||||
}
|
||||
} else if !QUOTED_STRING_TABLE[byte as usize] {
|
||||
return false;
|
||||
}
|
||||
|
||||
i += 1;
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn validate_url(data: &[u8], start: usize, end: usize) -> bool {
|
||||
if start == end {
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut i = start;
|
||||
while i < end {
|
||||
if !URL_TABLE[data[i] as usize] {
|
||||
return false;
|
||||
}
|
||||
|
||||
i += 1;
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn strip_ows_fast(data: &[u8], start_ref: &mut usize, end_ref: &mut usize, allow_empty: bool) -> bool {
|
||||
let start = *start_ref;
|
||||
let end = *end_ref;
|
||||
|
||||
// The single-space shortcut is valid only when no further leading OWS follows.
|
||||
if start + 1 < end && data[start] == b' ' && !is_ws(data[start + 1]) && !is_ws(data[end - 1]) {
|
||||
*start_ref = start + 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
strip_ows(data, start_ref, end_ref, allow_empty)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn strip_ows(data: &[u8], start_ref: &mut usize, end_ref: &mut usize, allow_empty: bool) -> bool {
|
||||
let mut start = *start_ref;
|
||||
let mut end = *end_ref;
|
||||
|
||||
while start < end && is_ws(data[start]) {
|
||||
start += 1;
|
||||
}
|
||||
|
||||
while end > start && is_ws(data[end - 1]) {
|
||||
end -= 1;
|
||||
}
|
||||
|
||||
if start == end && !allow_empty {
|
||||
return false;
|
||||
}
|
||||
|
||||
*start_ref = start;
|
||||
*end_ref = end;
|
||||
true
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn scan_header_line_scalar(ptr: *const u8, mut i: usize, end: usize) -> HeaderLineScanResult {
|
||||
while i < end {
|
||||
let byte = unsafe { *ptr.add(i) };
|
||||
|
||||
if byte == b'\r' {
|
||||
return HeaderLineScanResult::Cr(i);
|
||||
}
|
||||
|
||||
if (byte < 0x20 && byte != b'\t') || byte == 0x7f {
|
||||
return HeaderLineScanResult::Invalid(i);
|
||||
}
|
||||
|
||||
i += 1;
|
||||
}
|
||||
|
||||
HeaderLineScanResult::Incomplete
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
#[inline(always)]
|
||||
pub fn find_header_line_end(ptr: *const u8, len: usize) -> HeaderLineScanResult {
|
||||
use core::arch::aarch64::*;
|
||||
|
||||
if len < 16 {
|
||||
return scan_header_line_scalar(ptr, 0, len);
|
||||
}
|
||||
|
||||
let mut i = 0;
|
||||
let v_20 = unsafe { vdupq_n_u8(0x20) };
|
||||
let v_7f = unsafe { vdupq_n_u8(0x7f) };
|
||||
let v_tab = unsafe { vdupq_n_u8(b'\t') };
|
||||
let v_cr = unsafe { vdupq_n_u8(b'\r') };
|
||||
|
||||
while i + 16 <= len {
|
||||
let x = unsafe { vld1q_u8(ptr.add(i)) };
|
||||
let lt_20 = unsafe { vcltq_u8(x, v_20) };
|
||||
let eq_tab = unsafe { vceqq_u8(x, v_tab) };
|
||||
let eq_cr = unsafe { vceqq_u8(x, v_cr) };
|
||||
let eq_7f = unsafe { vceqq_u8(x, v_7f) };
|
||||
|
||||
// Header lines stop at CR; other control bytes are invalid except HTAB.
|
||||
let ctrl = unsafe { vbicq_u8(lt_20, eq_tab) };
|
||||
let invalid = unsafe { vbicq_u8(vorrq_u8(ctrl, eq_7f), eq_cr) };
|
||||
let found = unsafe { vorrq_u8(eq_cr, invalid) };
|
||||
|
||||
if unsafe { vmaxvq_u8(found) } != 0 {
|
||||
return scan_header_line_scalar(ptr, i, i + 16);
|
||||
}
|
||||
|
||||
i += 16;
|
||||
}
|
||||
|
||||
scan_header_line_scalar(ptr, i, len)
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
#[inline(always)]
|
||||
pub fn find_header_line_end(ptr: *const u8, len: usize) -> HeaderLineScanResult {
|
||||
use core::arch::x86_64::*;
|
||||
|
||||
if len < 16 {
|
||||
return scan_header_line_scalar(ptr, 0, len);
|
||||
}
|
||||
|
||||
let mut i = 0;
|
||||
let v_20 = unsafe { _mm_set1_epi8(0x20u8 as i8) };
|
||||
let v_7f = unsafe { _mm_set1_epi8(0x7fu8 as i8) };
|
||||
let v_tab = unsafe { _mm_set1_epi8(b'\t' as i8) };
|
||||
let v_cr = unsafe { _mm_set1_epi8(b'\r' as i8) };
|
||||
let v_zero = unsafe { _mm_setzero_si128() };
|
||||
let v_ones = unsafe { _mm_cmpeq_epi8(v_zero, v_zero) };
|
||||
|
||||
while i + 32 <= len {
|
||||
let x = unsafe { _mm_loadu_si128(ptr.add(i) as *const __m128i) };
|
||||
let lt_20 = unsafe { _mm_andnot_si128(_mm_cmpeq_epi8(_mm_subs_epu8(v_20, x), v_zero), v_ones) };
|
||||
let eq_tab = unsafe { _mm_cmpeq_epi8(x, v_tab) };
|
||||
let eq_cr = unsafe { _mm_cmpeq_epi8(x, v_cr) };
|
||||
let eq_7f = unsafe { _mm_cmpeq_epi8(x, v_7f) };
|
||||
|
||||
// Header lines stop at CR; other control bytes are invalid except HTAB.
|
||||
let ctrl = unsafe { _mm_andnot_si128(eq_tab, lt_20) };
|
||||
let invalid = unsafe { _mm_andnot_si128(eq_cr, _mm_or_si128(ctrl, eq_7f)) };
|
||||
let cr_mask = unsafe { _mm_movemask_epi8(eq_cr) };
|
||||
let invalid_mask = unsafe { _mm_movemask_epi8(invalid) };
|
||||
let found_mask = cr_mask | invalid_mask;
|
||||
|
||||
if found_mask != 0 {
|
||||
let index = i + found_mask.trailing_zeros() as usize;
|
||||
return if cr_mask & (1 << (index - i)) != 0 {
|
||||
HeaderLineScanResult::Cr(index)
|
||||
} else {
|
||||
HeaderLineScanResult::Invalid(index)
|
||||
};
|
||||
}
|
||||
|
||||
let x = unsafe { _mm_loadu_si128(ptr.add(i + 16) as *const __m128i) };
|
||||
let lt_20 = unsafe { _mm_andnot_si128(_mm_cmpeq_epi8(_mm_subs_epu8(v_20, x), v_zero), v_ones) };
|
||||
let eq_tab = unsafe { _mm_cmpeq_epi8(x, v_tab) };
|
||||
let eq_cr = unsafe { _mm_cmpeq_epi8(x, v_cr) };
|
||||
let eq_7f = unsafe { _mm_cmpeq_epi8(x, v_7f) };
|
||||
let ctrl = unsafe { _mm_andnot_si128(eq_tab, lt_20) };
|
||||
let invalid = unsafe { _mm_andnot_si128(eq_cr, _mm_or_si128(ctrl, eq_7f)) };
|
||||
let cr_mask = unsafe { _mm_movemask_epi8(eq_cr) };
|
||||
let invalid_mask = unsafe { _mm_movemask_epi8(invalid) };
|
||||
let found_mask = cr_mask | invalid_mask;
|
||||
|
||||
if found_mask != 0 {
|
||||
let lane = found_mask.trailing_zeros() as usize;
|
||||
let index = i + 16 + lane;
|
||||
return if cr_mask & (1 << lane) != 0 {
|
||||
HeaderLineScanResult::Cr(index)
|
||||
} else {
|
||||
HeaderLineScanResult::Invalid(index)
|
||||
};
|
||||
}
|
||||
|
||||
i += 32;
|
||||
}
|
||||
|
||||
while i + 16 <= len {
|
||||
let x = unsafe { _mm_loadu_si128(ptr.add(i) as *const __m128i) };
|
||||
let lt_20 = unsafe { _mm_andnot_si128(_mm_cmpeq_epi8(_mm_subs_epu8(v_20, x), v_zero), v_ones) };
|
||||
let eq_tab = unsafe { _mm_cmpeq_epi8(x, v_tab) };
|
||||
let eq_cr = unsafe { _mm_cmpeq_epi8(x, v_cr) };
|
||||
let eq_7f = unsafe { _mm_cmpeq_epi8(x, v_7f) };
|
||||
let ctrl = unsafe { _mm_andnot_si128(eq_tab, lt_20) };
|
||||
let invalid = unsafe { _mm_andnot_si128(eq_cr, _mm_or_si128(ctrl, eq_7f)) };
|
||||
let cr_mask = unsafe { _mm_movemask_epi8(eq_cr) };
|
||||
let invalid_mask = unsafe { _mm_movemask_epi8(invalid) };
|
||||
let found_mask = cr_mask | invalid_mask;
|
||||
|
||||
if found_mask != 0 {
|
||||
let lane = found_mask.trailing_zeros() as usize;
|
||||
let index = i + lane;
|
||||
return if cr_mask & (1 << lane) != 0 {
|
||||
HeaderLineScanResult::Cr(index)
|
||||
} else {
|
||||
HeaderLineScanResult::Invalid(index)
|
||||
};
|
||||
}
|
||||
|
||||
i += 16;
|
||||
}
|
||||
|
||||
scan_header_line_scalar(ptr, i, len)
|
||||
}
|
||||
|
||||
#[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
|
||||
#[target_feature(enable = "simd128")]
|
||||
pub fn find_header_line_end(ptr: *const u8, len: usize) -> HeaderLineScanResult {
|
||||
use core::arch::wasm32::*;
|
||||
|
||||
if len < 16 {
|
||||
return scan_header_line_scalar(ptr, 0, len);
|
||||
}
|
||||
|
||||
let mut i = 0;
|
||||
let v_20 = u8x16_splat(0x20);
|
||||
let v_7f = u8x16_splat(0x7f);
|
||||
let v_tab = u8x16_splat(b'\t');
|
||||
let v_cr = u8x16_splat(b'\r');
|
||||
|
||||
while i + 16 <= len {
|
||||
let x = unsafe { v128_load(ptr.add(i) as *const v128) };
|
||||
let lt_20 = u8x16_lt(x, v_20);
|
||||
let eq_tab = u8x16_eq(x, v_tab);
|
||||
let eq_cr = u8x16_eq(x, v_cr);
|
||||
let eq_7f = u8x16_eq(x, v_7f);
|
||||
|
||||
// Header lines stop at CR; other control bytes are invalid except HTAB.
|
||||
// WASM andnot(a, b) computes a & !b, unlike the x86 intrinsic.
|
||||
let ctrl = v128_andnot(lt_20, eq_tab);
|
||||
let invalid = v128_andnot(v128_or(ctrl, eq_7f), eq_cr);
|
||||
let found = v128_or(eq_cr, invalid);
|
||||
|
||||
if v128_any_true(found) {
|
||||
return scan_header_line_scalar(ptr, i, i + 16);
|
||||
}
|
||||
|
||||
i += 16;
|
||||
}
|
||||
|
||||
scan_header_line_scalar(ptr, i, len)
|
||||
}
|
||||
|
||||
#[cfg(not(any(
|
||||
target_arch = "aarch64",
|
||||
target_arch = "x86_64",
|
||||
all(target_arch = "wasm32", target_feature = "simd128")
|
||||
)))]
|
||||
#[inline(always)]
|
||||
pub fn find_header_line_end(ptr: *const u8, len: usize) -> HeaderLineScanResult { scan_header_line_scalar(ptr, 0, len) }
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
#[target_feature(enable = "neon")]
|
||||
pub fn validate_token_value(ptr: *const u8, len: usize) -> bool {
|
||||
use core::arch::aarch64::*;
|
||||
|
||||
let mut i = 0;
|
||||
|
||||
let v_20 = vdupq_n_u8(0x20);
|
||||
let v_7f = vdupq_n_u8(0x7f);
|
||||
let v_tab = vdupq_n_u8(9);
|
||||
|
||||
while i + 16 <= len {
|
||||
let x = unsafe { vld1q_u8(ptr.add(i)) };
|
||||
let lt_20 = vcltq_u8(x, v_20);
|
||||
let eq_tab = vceqq_u8(x, v_tab);
|
||||
let eq_7f = vceqq_u8(x, v_7f);
|
||||
|
||||
// Field values allow HTAB but reject the remaining C0 controls and DEL.
|
||||
let ctrl = vbicq_u8(lt_20, eq_tab); // lt_20 & !eq_tab
|
||||
let invalid = vorrq_u8(ctrl, eq_7f);
|
||||
|
||||
if vmaxvq_u8(invalid) != 0 {
|
||||
return false;
|
||||
}
|
||||
|
||||
i += 16;
|
||||
}
|
||||
|
||||
while i < len {
|
||||
let b = unsafe { *ptr.add(i) };
|
||||
|
||||
if (b < 0x20 && b != b'\t') || b == 0x7f {
|
||||
return false;
|
||||
}
|
||||
|
||||
i += 1;
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
#[target_feature(enable = "sse2")]
|
||||
pub fn validate_token_value(ptr: *const u8, len: usize) -> bool {
|
||||
use core::arch::x86_64::*;
|
||||
|
||||
let mut i = 0;
|
||||
let v_20 = _mm_set1_epi8(0x20u8 as i8);
|
||||
let v_7f = _mm_set1_epi8(0x7fu8 as i8);
|
||||
let v_tab = _mm_set1_epi8(b'\t' as i8);
|
||||
let v_zero = _mm_setzero_si128();
|
||||
let v_ones = _mm_cmpeq_epi8(v_zero, v_zero);
|
||||
|
||||
while i + 16 <= len {
|
||||
let x = unsafe { _mm_loadu_si128(ptr.add(i) as *const __m128i) };
|
||||
let lt_20 = _mm_andnot_si128(_mm_cmpeq_epi8(_mm_subs_epu8(v_20, x), v_zero), v_ones);
|
||||
let eq_tab = _mm_cmpeq_epi8(x, v_tab);
|
||||
let eq_7f = _mm_cmpeq_epi8(x, v_7f);
|
||||
|
||||
// Field values allow HTAB but reject the remaining C0 controls and DEL.
|
||||
let ctrl = _mm_andnot_si128(eq_tab, lt_20);
|
||||
let invalid = _mm_or_si128(ctrl, eq_7f);
|
||||
|
||||
if _mm_movemask_epi8(invalid) != 0 {
|
||||
return false;
|
||||
}
|
||||
|
||||
i += 16;
|
||||
}
|
||||
|
||||
while i < len {
|
||||
let b = unsafe { *ptr.add(i) };
|
||||
|
||||
if (b < 0x20 && b != b'\t') || b == 0x7f {
|
||||
return false;
|
||||
}
|
||||
|
||||
i += 1;
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
|
||||
#[target_feature(enable = "simd128")]
|
||||
pub fn validate_token_value(ptr: *const u8, len: usize) -> bool {
|
||||
use core::arch::wasm32::*;
|
||||
|
||||
let mut i = 0;
|
||||
let v_20 = u8x16_splat(0x20);
|
||||
let v_7f = u8x16_splat(0x7f);
|
||||
let v_tab = u8x16_splat(b'\t');
|
||||
|
||||
while i + 16 <= len {
|
||||
let x = unsafe { v128_load(ptr.add(i) as *const v128) };
|
||||
let lt_20 = u8x16_lt(x, v_20);
|
||||
let eq_tab = u8x16_eq(x, v_tab);
|
||||
let eq_7f = u8x16_eq(x, v_7f);
|
||||
|
||||
// Field values allow HTAB but reject the remaining C0 controls and DEL.
|
||||
// WASM andnot(a, b) computes a & !b, unlike the x86 intrinsic.
|
||||
let ctrl = v128_andnot(lt_20, eq_tab);
|
||||
let invalid = v128_or(ctrl, eq_7f);
|
||||
|
||||
if v128_any_true(invalid) {
|
||||
return false;
|
||||
}
|
||||
|
||||
i += 16;
|
||||
}
|
||||
|
||||
while i < len {
|
||||
let b = unsafe { *ptr.add(i) };
|
||||
|
||||
if (b < 0x20 && b != b'\t') || b == 0x7f {
|
||||
return false;
|
||||
}
|
||||
|
||||
i += 1;
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(not(any(
|
||||
target_arch = "aarch64",
|
||||
target_arch = "x86_64",
|
||||
all(target_arch = "wasm32", target_feature = "simd128")
|
||||
)))]
|
||||
#[inline(always)]
|
||||
pub fn validate_token_value(ptr: *const u8, len: usize) -> bool {
|
||||
let mut i = 0;
|
||||
|
||||
while i < len {
|
||||
let b = unsafe { *ptr.add(i) };
|
||||
|
||||
if (b < 0x20 && b != b'\t') || b == 0x7f {
|
||||
return false;
|
||||
}
|
||||
|
||||
i += 1;
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use core::ptr;
|
||||
use core::str;
|
||||
use core::{slice, slice::from_raw_parts};
|
||||
use std::ffi::{CString, c_char, c_uchar};
|
||||
|
||||
use crate::parse;
|
||||
use crate::{Callbacks, Errors, Events, Methods, Parser, States};
|
||||
|
||||
#[repr(C)]
|
||||
pub struct CStringWithLength {
|
||||
pub ptr: *const c_uchar,
|
||||
pub len: usize,
|
||||
}
|
||||
|
||||
impl CStringWithLength {
|
||||
fn new(value: &str) -> CStringWithLength {
|
||||
let cstring = CString::new(value).unwrap();
|
||||
|
||||
CStringWithLength {
|
||||
ptr: cstring.into_raw() as *const c_uchar,
|
||||
len: value.len(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for CStringWithLength {
|
||||
fn from(value: &str) -> Self { CStringWithLength::new(value) }
|
||||
}
|
||||
|
||||
impl From<CStringWithLength> for &str {
|
||||
fn from(value: CStringWithLength) -> Self {
|
||||
unsafe { str::from_utf8_unchecked(slice::from_raw_parts(value.ptr, value.len)) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns if debug informations are available in this build.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn milo_has_debug() -> bool { cfg!(any(debug_assertions, feature = "debug")) }
|
||||
|
||||
/// Returns if debug tracing is enabled for this parser.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn milo_is_debug(parser: *const Parser) -> bool { unsafe { (*parser).debug } }
|
||||
|
||||
/// A callback that simply returns `0`.
|
||||
///
|
||||
/// Use this callback as pointer when you want to remove a callback from the
|
||||
/// parser.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn milo_noop(_parser: &mut Parser, _at: usize, _len: usize) {}
|
||||
|
||||
/// Cleans up memory used by a string previously returned by one of the milo's C
|
||||
/// public interface.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn milo_free_string(s: CStringWithLength) {
|
||||
unsafe {
|
||||
let _ = CString::from_raw(s.ptr as *mut c_char);
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a new parser.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn milo_create() -> *mut Parser { Box::into_raw(Box::new(Parser::new())) }
|
||||
|
||||
/// Destroys a parser.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn milo_destroy(parser: *mut Parser) {
|
||||
if parser.is_null() {
|
||||
return;
|
||||
}
|
||||
|
||||
unsafe {
|
||||
let _ = Box::from_raw(parser);
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a slice of characters. It returns the number of consumed characters.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn milo_parse(parser: *mut Parser, data: *const c_uchar, limit: usize) -> usize {
|
||||
unsafe { (*parser).parse(data, limit) }
|
||||
}
|
||||
|
||||
/// Sets the parser event bitmask.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn milo_set_active_events(parser: *mut Parser, value: u64) {
|
||||
unsafe {
|
||||
(*parser).active_events = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the maximum body payload consumed by a single parse invocation.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn milo_set_max_body_payload(parser: *mut Parser, value: u64) {
|
||||
unsafe {
|
||||
(*parser).max_body_payload = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets whether parsing should stop after headers have completed.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn milo_set_suspend_after_headers(parser: *mut Parser, value: bool) {
|
||||
unsafe {
|
||||
(*parser).suspend_after_headers = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// Resets a parser. The second parameters specifies if to also reset the
|
||||
/// parsed counter.
|
||||
///
|
||||
/// The following fields are not modified:
|
||||
/// * position
|
||||
/// * context
|
||||
/// * autodetect
|
||||
/// * is_request
|
||||
/// * suspend_after_headers
|
||||
/// * max_body_payload
|
||||
/// * manage_unconsumed
|
||||
/// * continue_without_data
|
||||
/// * debug
|
||||
/// * context
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn milo_reset(parser: *mut Parser, keep_parsed: bool) { unsafe { (*parser).reset(keep_parsed) } }
|
||||
|
||||
/// Clears all values about the message in the parser.
|
||||
///
|
||||
/// The autodetect and is_request fields are not cleared.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn milo_clear(parser: *mut Parser) { unsafe { (*parser).clear() } }
|
||||
|
||||
/// Pauses the parser. It will have to be resumed via `milo_resume`.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn milo_pause(parser: *mut Parser) { unsafe { (*parser).pause() } }
|
||||
|
||||
/// Resumes the parser.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn milo_resume(parser: *mut Parser) { unsafe { (*parser).resume() } }
|
||||
|
||||
/// Completes the current message without consuming more input.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn milo_complete(parser: *mut Parser) { unsafe { (*parser).complete() } }
|
||||
|
||||
/// Marks the parser as finished. Any new data received via `milo_parse` will
|
||||
/// put the parser in the error state.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn milo_finish(parser: *mut Parser) { unsafe { (*parser).finish() } }
|
||||
|
||||
/// Marks the parsing a failed, setting a error code and and error message.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn milo_fail(parser: *mut Parser, code: u8, description: CStringWithLength) {
|
||||
unsafe { (*parser).fail(code, description.into()) };
|
||||
}
|
||||
|
||||
/// Returns the current parser's state as string.
|
||||
///
|
||||
/// The returned value must be freed using `free_string`.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn milo_state_string(parser: *mut Parser) -> CStringWithLength {
|
||||
unsafe { (*parser).state_str().into() }
|
||||
}
|
||||
|
||||
/// Returns a parser method as string.
|
||||
///
|
||||
/// The returned value must be freed using `free_string`.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn milo_method_to_string(method: u8) -> CStringWithLength {
|
||||
Methods::try_from(method)
|
||||
.map_or("UNKNOWN", |method| method.as_str())
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Returns a parser error as string.
|
||||
///
|
||||
/// The returned value must be freed using `free_string`.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn milo_error_to_string(error: u8) -> CStringWithLength {
|
||||
Errors::try_from(error).map_or("UNKNOWN", |error| error.as_str()).into()
|
||||
}
|
||||
|
||||
/// Returns a parser callback as string.
|
||||
///
|
||||
/// The returned value must be freed using `free_string`.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn milo_callback_to_string(callback: u8) -> CStringWithLength {
|
||||
Callbacks::try_from(callback)
|
||||
.map_or("UNKNOWN", |callback| callback.as_str())
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Returns a parser state as string.
|
||||
///
|
||||
/// The returned value must be freed using `free_string`.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn milo_state_to_string(state: u8) -> CStringWithLength {
|
||||
States::try_from(state).map_or("UNKNOWN", |state| state.as_str()).into()
|
||||
}
|
||||
|
||||
/// Returns a parser event as string.
|
||||
///
|
||||
/// The returned value must be freed using `free_string`.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn milo_event_to_string(event: u8) -> CStringWithLength {
|
||||
Events::try_from(event).map_or("UNKNOWN", |event| event.as_str()).into()
|
||||
}
|
||||
|
||||
/// Returns the current parser's error state as string.
|
||||
///
|
||||
/// The returned value must be freed using `free_string`.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn milo_error_code_string(parser: *mut Parser) -> CStringWithLength {
|
||||
unsafe { (*parser).error_code_str().into() }
|
||||
}
|
||||
|
||||
/// Returns the current parser's error descrition.
|
||||
///
|
||||
/// The returned value must be freed using `free_string`.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn milo_error_description_string(parser: *mut Parser) -> CStringWithLength {
|
||||
unsafe { (*parser).error_description_str().into() }
|
||||
}
|
||||
+1578
File diff suppressed because it is too large.
Load diff
+363
@@ -0,0 +1,363 @@
|
||||
use core::ffi::{c_uchar, c_void};
|
||||
use std::slice;
|
||||
|
||||
use crate::Parser;
|
||||
|
||||
#[cfg(any(debug_assertions, feature = "debug"))]
|
||||
pub fn debug(message: String) { unsafe { crate::logger(((message.as_ptr() as u64) << 32) + message.len() as u64) } }
|
||||
|
||||
/// Returns if debug informations are available in this build.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn milo_has_debug() -> bool { cfg!(any(debug_assertions, feature = "debug")) }
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn alloc(len: usize) -> *mut c_void {
|
||||
let buffer = Vec::with_capacity(len);
|
||||
let (ptr, _, _) = { buffer.into_raw_parts() };
|
||||
ptr as *mut c_void
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn dealloc(ptr: *mut c_void, len: usize) {
|
||||
if ptr.is_null() {
|
||||
return;
|
||||
}
|
||||
|
||||
unsafe {
|
||||
let _ = Vec::from_raw_parts(ptr, len, len);
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a new parser.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn create() -> *mut c_void {
|
||||
let ptr = Box::into_raw(Box::new(Parser::new())) as *mut c_void;
|
||||
|
||||
// Recreate the parser from the box to assign the reference to itself
|
||||
let mut parser = unsafe { Box::from_raw(ptr as *mut Parser) };
|
||||
parser.ptr = ptr;
|
||||
let _ = Box::into_raw(parser);
|
||||
|
||||
ptr
|
||||
}
|
||||
|
||||
/// Destroys a parser.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn destroy(parser: *mut c_void) {
|
||||
if parser.is_null() {
|
||||
return;
|
||||
}
|
||||
|
||||
unsafe {
|
||||
let _ = Box::from_raw(parser as *mut Parser);
|
||||
}
|
||||
}
|
||||
|
||||
/// Resets a parser. The second parameters specifies if to also reset the
|
||||
/// parsed counter.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn reset(parser: *mut c_void, keep_parsed: bool) { unsafe { (*(parser as *mut Parser)).reset(keep_parsed) } }
|
||||
|
||||
/// Clears all values in the parser.
|
||||
///
|
||||
/// Persisted fields, unconsumed data and the position are not cleared.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn clear(parser: *mut c_void) { unsafe { (*(parser as *mut Parser)).clear() } }
|
||||
|
||||
// Parses a slice of characters. It returns the number of consumed characters.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn parse(parser: *mut c_void, data: *const c_uchar, limit: usize) -> usize {
|
||||
unsafe { (*(parser as *mut Parser)).parse(data, limit) }
|
||||
}
|
||||
|
||||
/// Pauses the parser. It will have to be resumed via `resume`.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn pause(parser: *mut c_void) { unsafe { (*(parser as *mut Parser)).pause() } }
|
||||
|
||||
/// Resumes the parser.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn resume(parser: *mut c_void) { unsafe { (*(parser as *mut Parser)).resume() } }
|
||||
|
||||
/// Completes the current message without consuming more input.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn complete(parser: *mut c_void) { unsafe { (*(parser as *mut Parser)).complete() } }
|
||||
|
||||
/// Marks the parser as finished. Any new data received via `parse` will
|
||||
/// put the parser in the error state.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn finish(parser: *mut c_void) { unsafe { (*(parser as *mut Parser)).finish() } }
|
||||
|
||||
/// Marks the parser as failed.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn fail(parser: *mut c_void, code: u8, description_ptr: *const c_uchar, description_len: usize) {
|
||||
unsafe {
|
||||
(*(parser as *mut Parser)).fail(
|
||||
code,
|
||||
std::str::from_utf8_unchecked(slice::from_raw_parts(description_ptr, description_len)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Generates a getter.
|
||||
// pub fn wasm_getter(input: TokenStream) -> TokenStream {
|
||||
// let snake_matcher = Regex::new(r"([A-Z])").unwrap();
|
||||
//
|
||||
// let definition = parse_macro_input!(input as Property);
|
||||
// let property = definition.property;
|
||||
// let fn_name = format_ident!(
|
||||
// "{}",
|
||||
// snake_matcher.replace_all(&definition.getter.to_string().as_str(), |captures:
|
||||
// &Captures| { format!("_{}", captures[1].to_lowercase())
|
||||
// })
|
||||
// );
|
||||
//
|
||||
// let return_type = definition.r#type;
|
||||
//
|
||||
// TokenStream::from(quote! {
|
||||
// Gets the parser #property.
|
||||
// #[unsafe(no_mangle)]
|
||||
// pub fn #fn_name(parser: *const c_void) -> #return_type { unsafe { (*(parser
|
||||
// as *const Parser)).#property } } })
|
||||
// }
|
||||
|
||||
// Getters
|
||||
// Get the parser autodetect property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn is_autodetect(parser: *const c_void) -> bool { unsafe { (*(parser as *const Parser)).autodetect } }
|
||||
|
||||
// Get the parser is_request property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn is_request(parser: *const c_void) -> bool { unsafe { (*(parser as *const Parser)).is_request } }
|
||||
|
||||
// Get the parser debug property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn is_debug(parser: *const c_void) -> bool { unsafe { (*(parser as *const Parser)).debug } }
|
||||
|
||||
// Get the parser paused property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn is_paused(parser: *const c_void) -> bool { unsafe { (*(parser as *const Parser)).paused } }
|
||||
|
||||
// Get the parser manage_unconsumed property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn should_manage_unconsumed(parser: *const c_void) -> bool {
|
||||
unsafe { (*(parser as *const Parser)).manage_unconsumed }
|
||||
}
|
||||
|
||||
// Get the parser suspend_after_headers property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn should_suspend_after_headers(parser: *const c_void) -> bool {
|
||||
unsafe { (*(parser as *const Parser)).suspend_after_headers }
|
||||
}
|
||||
|
||||
// Get the parser max_start_line_length property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn get_max_start_line_length(parser: *const c_void) -> usize {
|
||||
unsafe { (*(parser as *const Parser)).max_start_line_length }
|
||||
}
|
||||
|
||||
// Get the parser max_header_length property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn get_max_header_length(parser: *const c_void) -> usize {
|
||||
unsafe { (*(parser as *const Parser)).max_header_length }
|
||||
}
|
||||
|
||||
// Get the parser max_body_payload property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn get_max_body_payload(parser: *const c_void) -> u64 { unsafe { (*(parser as *const Parser)).max_body_payload } }
|
||||
|
||||
// Get the parser continue_without_data property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn should_continue_without_data(parser: *const c_void) -> bool {
|
||||
unsafe { (*(parser as *const Parser)).continue_without_data }
|
||||
}
|
||||
|
||||
// Get the parser is_connect property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn is_connect(parser: *const c_void) -> bool { unsafe { (*(parser as *const Parser)).is_connect } }
|
||||
|
||||
// Get the parser skip_body property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn should_skip_body(parser: *const c_void) -> bool { unsafe { (*(parser as *const Parser)).skip_body } }
|
||||
|
||||
// Get the parser state property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn get_state(parser: *const c_void) -> u8 { unsafe { (*(parser as *const Parser)).state } }
|
||||
|
||||
// Get the parser position property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn get_position(parser: *const c_void) -> usize { unsafe { (*(parser as *const Parser)).position } }
|
||||
|
||||
// Get the parser parsed property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn get_parsed(parser: *const c_void) -> u64 { unsafe { (*(parser as *const Parser)).parsed } }
|
||||
|
||||
// Get the parser error_code property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn get_error_code(parser: *const c_void) -> u8 { unsafe { (*(parser as *const Parser)).error_code } }
|
||||
|
||||
// Get the parser method property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn get_method(parser: *const c_void) -> u8 { unsafe { (*(parser as *const Parser)).method } }
|
||||
|
||||
// Get the parser status property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn get_status(parser: *const c_void) -> u32 { unsafe { (*(parser as *const Parser)).status } }
|
||||
|
||||
// Get the parser has_connection_close property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn has_connection_close(parser: *const c_void) -> bool {
|
||||
unsafe { (*(parser as *const Parser)).has_connection_close }
|
||||
}
|
||||
|
||||
// Get the parser has_connection_upgrade property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn has_connection_upgrade(parser: *const c_void) -> bool {
|
||||
unsafe { (*(parser as *const Parser)).has_connection_upgrade }
|
||||
}
|
||||
|
||||
// Get the parser content_length property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn get_content_length(parser: *const c_void) -> u64 { unsafe { (*(parser as *const Parser)).content_length } }
|
||||
|
||||
// Get the parser chunk_size property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn get_chunk_size(parser: *const c_void) -> u64 { unsafe { (*(parser as *const Parser)).chunk_size } }
|
||||
|
||||
// Get the parser remaining_content_length property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn get_remaining_content_length(parser: *const c_void) -> u64 {
|
||||
unsafe { (*(parser as *const Parser)).remaining_content_length }
|
||||
}
|
||||
|
||||
// Get the parser remaining_chunk_size property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn get_remaining_chunk_size(parser: *const c_void) -> u64 {
|
||||
unsafe { (*(parser as *const Parser)).remaining_chunk_size }
|
||||
}
|
||||
|
||||
// Get the parser has_content_length property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn has_content_length(parser: *const c_void) -> bool { unsafe { (*(parser as *const Parser)).has_content_length } }
|
||||
|
||||
// Get the parser has_transfer_encoding property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn has_transfer_encoding(parser: *const c_void) -> bool {
|
||||
unsafe { (*(parser as *const Parser)).has_transfer_encoding }
|
||||
}
|
||||
|
||||
// Get the parser has_chunked_transfer_encoding property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn has_chunked_transfer_encoding(parser: *const c_void) -> bool {
|
||||
unsafe { (*(parser as *const Parser)).has_chunked_transfer_encoding }
|
||||
}
|
||||
|
||||
// Get the parser has_upgrade property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn has_upgrade(parser: *const c_void) -> bool { unsafe { (*(parser as *const Parser)).has_upgrade } }
|
||||
|
||||
// Get the parser has_trailers property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn has_trailers(parser: *const c_void) -> bool { unsafe { (*(parser as *const Parser)).has_trailers } }
|
||||
|
||||
/// Gets the parser callback error description, if any. This is meant for
|
||||
/// internal use.
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn get_error_description_raw(parser: *mut c_void) -> u64 {
|
||||
let parser = unsafe { &(*(parser as *const Parser)) };
|
||||
|
||||
let ptr = parser.error_description.as_ptr() as u64;
|
||||
let len = parser.error_description_len as u64;
|
||||
|
||||
(ptr << 32) + len
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn set_should_autodetect(parser: *mut c_void, value: bool) {
|
||||
unsafe {
|
||||
(*(parser as *mut Parser)).autodetect = value;
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn set_is_request(parser: *mut c_void, value: bool) {
|
||||
unsafe {
|
||||
(*(parser as *mut Parser)).is_request = value;
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn set_should_manage_unconsumed(parser: *mut c_void, value: bool) {
|
||||
unsafe {
|
||||
(*(parser as *mut Parser)).manage_unconsumed = value;
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn set_should_suspend_after_headers(parser: *mut c_void, value: bool) {
|
||||
unsafe {
|
||||
(*(parser as *mut Parser)).suspend_after_headers = value;
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn set_max_start_line_length(parser: *mut c_void, value: usize) {
|
||||
unsafe {
|
||||
(*(parser as *mut Parser)).max_start_line_length = value;
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn set_max_header_length(parser: *mut c_void, value: usize) {
|
||||
unsafe {
|
||||
(*(parser as *mut Parser)).max_header_length = value;
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn set_max_body_payload(parser: *mut c_void, value: u64) {
|
||||
unsafe {
|
||||
(*(parser as *mut Parser)).max_body_payload = value;
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn set_should_continue_without_data(parser: *mut c_void, value: bool) {
|
||||
unsafe {
|
||||
(*(parser as *mut Parser)).continue_without_data = value;
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn set_should_skip_body(parser: *mut c_void, value: bool) {
|
||||
unsafe {
|
||||
(*(parser as *mut Parser)).skip_body = value;
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn set_is_connect(parser: *mut c_void, value: bool) {
|
||||
unsafe {
|
||||
(*(parser as *mut Parser)).is_connect = value;
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn set_debug(parser: *mut c_void, value: bool) {
|
||||
unsafe {
|
||||
(*(parser as *mut Parser)).debug = value;
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn set_active_callbacks(parser: *mut c_void, value: u64) {
|
||||
unsafe {
|
||||
(*(parser as *mut Parser)).active_callbacks = value;
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn set_active_events(parser: *mut c_void, value: u64) {
|
||||
unsafe {
|
||||
(*(parser as *mut Parser)).active_events = value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"name": "@perseveranza-pets/milo",
|
||||
"version": "0.9.0",
|
||||
"description": "A fast and embeddable HTTP/1.1 parser.",
|
||||
"homepage": "https://sw.cowtech.it/milo",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/ShogunPanda/milo.git"
|
||||
},
|
||||
"keywords": [
|
||||
"http",
|
||||
"parser"
|
||||
],
|
||||
"bugs": {
|
||||
"url": "https://github.com/ShogunPanda/milo/issues"
|
||||
},
|
||||
"author": "Shogun <shogun@cowtech.it>",
|
||||
"license": "ISC",
|
||||
"private": false,
|
||||
"type": "module",
|
||||
"files": [
|
||||
"binary",
|
||||
"src",
|
||||
"CODE_OF_CONDUCT.md",
|
||||
"LICENSE.md",
|
||||
"README.md"
|
||||
],
|
||||
"main": "src/simd/index.js",
|
||||
"exports": {
|
||||
".": "./src/simd/index.js",
|
||||
"./unbundled": "./src/simd/unbundled.js",
|
||||
"./no-simd": "./src/no-simd/index.js",
|
||||
"./no-simd/unbundled": "./src/no-simd/unbundled.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 22.21.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
/* REPLACE: module */
|
||||
|
||||
const textEncoder = new TextEncoder()
|
||||
const textDecoder = new TextDecoder()
|
||||
|
||||
function log (logger, raw) {
|
||||
const len = Number(BigInt.asUintN(32, raw))
|
||||
const ptr = Number(raw >> 32n)
|
||||
|
||||
logger(textDecoder.decode(new Uint8Array(this.memory.buffer, ptr, len)))
|
||||
}
|
||||
|
||||
function alloc (len) {
|
||||
return this.alloc(len) >>> 0
|
||||
}
|
||||
|
||||
function dealloc (ptr, len) {
|
||||
return this.dealloc(ptr, len)
|
||||
}
|
||||
|
||||
function create () {
|
||||
return this.create() >>> 0
|
||||
}
|
||||
|
||||
function destroy (parser) {
|
||||
this.destroy(parser)
|
||||
}
|
||||
|
||||
function parse (parser, data, limit) {
|
||||
return this.parse(parser, data, limit) >>> 0
|
||||
}
|
||||
|
||||
function fail (parser, code, description) {
|
||||
const len = description.length
|
||||
const ptr = this.alloc(len)
|
||||
const buffer = new Uint8Array(this.memory.buffer, ptr, len)
|
||||
textEncoder.encodeInto(description, buffer)
|
||||
|
||||
this.fail(parser, code, ptr, len)
|
||||
this.dealloc(ptr, len)
|
||||
}
|
||||
|
||||
function hasDebug () {
|
||||
return this.milo_has_debug() !== 0
|
||||
}
|
||||
|
||||
/* REPLACE: enums */
|
||||
|
||||
/* REPLACE: getters */
|
||||
|
||||
/* REPLACE: setters */
|
||||
|
||||
function simpleCreate (spans, create) {
|
||||
const parser = create()
|
||||
spans[parser] = []
|
||||
this.setActiveCallbacks(parser, this.CALLBACK_ACTIVE_ALL)
|
||||
return parser
|
||||
}
|
||||
|
||||
function simpleDestroy (spans, destroy, parser) {
|
||||
spans[parser] = undefined
|
||||
destroy(parser)
|
||||
}
|
||||
|
||||
export function noop () {}
|
||||
|
||||
export function setup (env = {}) {
|
||||
let { logger: logOption, ...instanceEnvironment } = env
|
||||
let logger = noop
|
||||
const context = {}
|
||||
|
||||
if (logOption) {
|
||||
if (typeof logOption !== 'function') {
|
||||
logOption = console.log
|
||||
}
|
||||
|
||||
logger = log.bind(context, logOption)
|
||||
}
|
||||
|
||||
// Create the WASM instance
|
||||
/* eslint-disable-next-line no-undef */
|
||||
const instance = new WebAssembly.Instance(wasmModule, {
|
||||
env: {
|
||||
logger,
|
||||
/* REPLACE: callbacks:noop */
|
||||
...instanceEnvironment
|
||||
}
|
||||
})
|
||||
|
||||
const wasm = instance.exports
|
||||
context.memory = wasm.memory
|
||||
|
||||
const milo = {
|
||||
/* REPLACE: version */
|
||||
/* REPLACE: constants */
|
||||
/* REPLACE: enums:list */
|
||||
/* REPLACE: getters:list */
|
||||
/* REPLACE: setters:list */
|
||||
memory: wasm.memory,
|
||||
alloc: alloc.bind(wasm),
|
||||
dealloc: dealloc.bind(wasm),
|
||||
create: create.bind(wasm),
|
||||
destroy: destroy.bind(wasm),
|
||||
parse: parse.bind(wasm),
|
||||
fail: fail.bind(wasm),
|
||||
hasDebug: hasDebug.bind(wasm),
|
||||
clear: wasm.clear,
|
||||
complete: wasm.complete,
|
||||
finish: wasm.finish,
|
||||
pause: wasm.pause,
|
||||
reset: wasm.reset,
|
||||
resume: wasm.resume
|
||||
}
|
||||
|
||||
/* REPLACE: start */
|
||||
return milo
|
||||
}
|
||||
|
||||
export function simple () {
|
||||
const spans = {}
|
||||
|
||||
const milo = setup({/* REPLACE: callbacks:simple */})
|
||||
|
||||
milo.spans = spans
|
||||
milo.create = simpleCreate.bind(milo, spans, milo.create)
|
||||
milo.destroy = simpleDestroy.bind(milo, spans, milo.destroy)
|
||||
|
||||
return milo
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
[toolchain]
|
||||
channel = "nightly-2026-07-29"
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "milo-build-scripts"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
base64 = "0.22.1"
|
||||
icu_collator = "2.1"
|
||||
icu_normalizer = "2.1"
|
||||
markdown = "1.0.0"
|
||||
proc-macro2 = "1.0.106"
|
||||
quote = "1.0.45"
|
||||
regex = "1.12.3"
|
||||
semver = "1.0.27"
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_json = { version = "1.0.149", features = ["preserve_order"] }
|
||||
serde_yaml = "0.9.34"
|
||||
toml = "1.0.7"
|
||||
@@ -0,0 +1,8 @@
|
||||
use std::error::Error;
|
||||
|
||||
use milo_build_scripts::get_build_info;
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
println!("{}", serde_json::to_string_pretty(&get_build_info()?)?);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,549 @@
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
env,
|
||||
error::Error,
|
||||
fs,
|
||||
io::ErrorKind,
|
||||
path::{Path, PathBuf},
|
||||
process::{self, Command},
|
||||
sync::LazyLock,
|
||||
};
|
||||
|
||||
use icu_collator::{Collator, options::CollatorOptions};
|
||||
use icu_normalizer::DecomposingNormalizer;
|
||||
use markdown::{ParseOptions, mdast::Node, to_mdast};
|
||||
use regex::Regex;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
const FIXTURE_PREFIX: &str = "tests/fixtures/llhttp";
|
||||
|
||||
struct Case {
|
||||
titles: Vec<String>,
|
||||
source: Value,
|
||||
meta: Value,
|
||||
http: Option<String>,
|
||||
log: Option<String>,
|
||||
}
|
||||
|
||||
fn fail(message: &str) -> ! {
|
||||
eprintln!("{message}");
|
||||
process::exit(1);
|
||||
}
|
||||
|
||||
fn clean_heading(title: &str) -> String { title.replace('`', "").trim().to_owned() }
|
||||
|
||||
fn decode_html_entities(value: &str) -> Result<String, Box<dyn Error>> {
|
||||
static ENTITIES: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"&(?:quot|apos|amp|lt|gt|#(\d+)|#x([0-9a-fA-F]+));").unwrap());
|
||||
let mut decoded = String::new();
|
||||
let mut end = 0;
|
||||
for captures in ENTITIES.captures_iter(value) {
|
||||
let matched = captures.get(0).unwrap();
|
||||
decoded.push_str(&value[end..matched.start()]);
|
||||
let character = match matched.as_str() {
|
||||
""" => '"',
|
||||
"'" => '\'',
|
||||
"&" => '&',
|
||||
"<" => '<',
|
||||
">" => '>',
|
||||
_ => {
|
||||
let code = if let Some(decimal) = captures.get(1) {
|
||||
decimal.as_str().parse::<u32>()?
|
||||
} else {
|
||||
u32::from_str_radix(captures.get(2).unwrap().as_str(), 16)?
|
||||
};
|
||||
char::from_u32(code).ok_or("Invalid HTML character reference")?
|
||||
}
|
||||
};
|
||||
decoded.push(character);
|
||||
end = matched.end();
|
||||
}
|
||||
decoded.push_str(&value[end..]);
|
||||
Ok(decoded)
|
||||
}
|
||||
|
||||
fn parse_html_meta(value: &str) -> Result<Option<Value>, Box<dyn Error>> {
|
||||
static COMMENT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?s)<!--\s*meta=(.*?)\s*-->").unwrap());
|
||||
static BARE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?s)^\s*meta=(.*?)\s*$").unwrap());
|
||||
let Some(captures) = COMMENT.captures(value).or_else(|| BARE.captures(value)) else {
|
||||
return Ok(None);
|
||||
};
|
||||
// llhttp stores JSON metadata in markdown HTML nodes, sometimes entity-escaped
|
||||
// by the parser.
|
||||
let meta: Value = serde_json::from_str(&decode_html_entities(captures[1].trim())?)?;
|
||||
if !has_meta(&meta) {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(meta))
|
||||
}
|
||||
|
||||
fn has_meta(value: &Value) -> bool { value.as_object().is_some_and(|object| !object.is_empty()) }
|
||||
|
||||
fn stringify_fixture(fixture: &Value) -> String {
|
||||
// Match yaml's QUOTE_SINGLE values, PLAIN keys, and unlimited line width.
|
||||
// serde_yaml has no option for choosing the scalar style, so emit this JSON
|
||||
// subset explicitly while retaining the insertion order of object keys.
|
||||
fn quote(value: &str, indent: usize, key: bool) -> String {
|
||||
let double = value
|
||||
.chars()
|
||||
.any(|c| matches!(c, '\0'..='\u{8}' | '\u{b}'..='\u{1f}' | '\u{7f}'..='\u{9f}'))
|
||||
|| (key && value.contains('\n'))
|
||||
|| value
|
||||
.as_bytes()
|
||||
.windows(2)
|
||||
.any(|pair| matches!(pair, [b' ' | b'\t', b'\n'] | [b'\n', b' ' | b'\t']));
|
||||
if double {
|
||||
let json = serde_json::to_string(value).unwrap();
|
||||
let characters = json.chars().collect::<Vec<_>>();
|
||||
let mut result = String::new();
|
||||
let mut i = 0;
|
||||
while i < characters.len() {
|
||||
if characters[i] == ' ' && characters.get(i + 1..i + 3) == Some(&['\\', 'n']) {
|
||||
result.push_str("\\ ");
|
||||
i += 1;
|
||||
}
|
||||
if characters[i] == '\\' {
|
||||
match characters[i + 1] {
|
||||
'u' => {
|
||||
let code = characters[i + 2..i + 6].iter().collect::<String>();
|
||||
match code.as_str() {
|
||||
"0000" => result.push_str("\\0"),
|
||||
"0007" => result.push_str("\\a"),
|
||||
"000b" => result.push_str("\\v"),
|
||||
"001b" => result.push_str("\\e"),
|
||||
_ if code.starts_with("00") => result.push_str(&format!("\\x{}", &code[2..])),
|
||||
_ => result.push_str(&format!("\\u{code}")),
|
||||
}
|
||||
i += 6;
|
||||
continue;
|
||||
}
|
||||
'n' if !key && characters.get(i + 2) != Some(&'"') && json.encode_utf16().count() >= 40 => {
|
||||
result.push_str("\n\n");
|
||||
while characters.get(i + 2..i + 4) == Some(&['\\', 'n']) && characters.get(i + 4) != Some(&'"') {
|
||||
result.push('\n');
|
||||
i += 2;
|
||||
}
|
||||
result.push_str(&" ".repeat(indent));
|
||||
if characters.get(i + 2) == Some(&' ') {
|
||||
result.push('\\');
|
||||
}
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
_ => {
|
||||
result.push(characters[i]);
|
||||
result.push(characters[i + 1]);
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
result.push(characters[i]);
|
||||
i += 1;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
let mut result = String::from("'");
|
||||
let mut characters = value.chars().peekable();
|
||||
while let Some(character) = characters.next() {
|
||||
result.push(character);
|
||||
if character == '\'' {
|
||||
result.push('\'');
|
||||
} else if character == '\n' && characters.peek() != Some(&'\n') {
|
||||
result.push('\n');
|
||||
result.push_str(&" ".repeat(indent));
|
||||
}
|
||||
}
|
||||
result.push('\'');
|
||||
result
|
||||
}
|
||||
|
||||
fn key(value: &str, indent: usize) -> String {
|
||||
static SPECIAL: LazyLock<Regex> = LazyLock::new(|| {
|
||||
Regex::new(r#"^[\n\t ,\[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$"#).unwrap()
|
||||
});
|
||||
if value.is_empty()
|
||||
|| SPECIAL.is_match(value)
|
||||
|| !matches!(serde_yaml::from_str::<Value>(value), Ok(Value::String(_)))
|
||||
{
|
||||
return quote(value, indent, true);
|
||||
}
|
||||
value.to_owned()
|
||||
}
|
||||
|
||||
fn scalar(value: &Value, indent: usize) -> Option<String> {
|
||||
match value {
|
||||
Value::String(value) => Some(quote(value, indent, false)),
|
||||
Value::Array(value) if value.is_empty() => Some("[]".into()),
|
||||
Value::Object(value) if value.is_empty() => Some("{}".into()),
|
||||
Value::Array(_) | Value::Object(_) => None,
|
||||
_ => Some(value.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn emit(value: &Value, indent: usize) -> String {
|
||||
let padding = " ".repeat(indent);
|
||||
let mut output = String::new();
|
||||
match value {
|
||||
Value::Object(object) => {
|
||||
for (name, value) in object {
|
||||
output.push_str(&format!("{padding}{}:", key(name, indent)));
|
||||
if let Some(value) = scalar(value, indent + 2) {
|
||||
output.push_str(&format!(" {value}\n"));
|
||||
} else {
|
||||
output.push('\n');
|
||||
output.push_str(&emit(value, indent + 2));
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Array(array) => {
|
||||
for value in array {
|
||||
output.push_str(&format!("{padding}- "));
|
||||
if let Some(value) = scalar(value, indent + 2) {
|
||||
output.push_str(&value);
|
||||
output.push('\n');
|
||||
} else {
|
||||
let nested = emit(value, indent + 2);
|
||||
output.push_str(&nested[indent + 2..]);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
output.push_str(&format!("{padding}{}\n", scalar(value, indent).unwrap()));
|
||||
}
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
format!("---\n{}", emit(fixture, 0))
|
||||
}
|
||||
|
||||
fn normalize_fixture_for_comparison(value: &Value) -> Value {
|
||||
match value {
|
||||
Value::Array(values) => values.iter().map(normalize_fixture_for_comparison).collect(),
|
||||
Value::Object(object) => {
|
||||
// Compare semantic fixture data only; checked is local review state and key
|
||||
// order is irrelevant.
|
||||
let mut keys = object.keys().filter(|key| *key != "checked").collect::<Vec<_>>();
|
||||
keys.sort();
|
||||
keys
|
||||
.into_iter()
|
||||
.map(|key| (key.clone(), normalize_fixture_for_comparison(&object[key])))
|
||||
.collect()
|
||||
}
|
||||
_ => value.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
// Node's glob excludes dotfiles and does not descend into symlinked
|
||||
// directories.
|
||||
fn glob_files(root: &Path, extension: &str) -> Result<Vec<PathBuf>, Box<dyn Error>> {
|
||||
let entries = match fs::read_dir(root) {
|
||||
Ok(entries) => entries,
|
||||
Err(error) if error.kind() == ErrorKind::NotFound => return Ok(Vec::new()),
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
let mut entries = entries.collect::<Result<Vec<_>, _>>()?;
|
||||
entries.sort_by_key(|entry| entry.file_name());
|
||||
let mut files = Vec::new();
|
||||
for entry in entries {
|
||||
if entry.file_name().to_string_lossy().starts_with('.') {
|
||||
continue;
|
||||
}
|
||||
if entry.file_type()?.is_dir() {
|
||||
files.extend(glob_files(&entry.path(), extension)?);
|
||||
} else if entry.path().extension().is_some_and(|value| value == extension) {
|
||||
files.push(entry.path());
|
||||
}
|
||||
}
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
fn process_section(
|
||||
llhttp_root: &Path,
|
||||
output_root: &Path,
|
||||
fixture_root: &Path,
|
||||
section: &str,
|
||||
seen_files: &mut HashSet<String>,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
let source = llhttp_root.join("test").join(section);
|
||||
let mut cases = Vec::new();
|
||||
let mut used_names = HashSet::new();
|
||||
|
||||
// Find markdown files.
|
||||
let mut files = glob_files(&source, "md")?;
|
||||
// Use Unicode collation, as localeCompare does, rather than byte ordering.
|
||||
let collator = Collator::try_new(Default::default(), CollatorOptions::default())?;
|
||||
files.sort_by(|a, b| collator.compare(&a.to_string_lossy(), &b.to_string_lossy()));
|
||||
|
||||
// Process each file.
|
||||
for file in files {
|
||||
let raw = fs::read_to_string(&file)?;
|
||||
let source_path = file.strip_prefix(llhttp_root)?.to_string_lossy().replace('\\', "/");
|
||||
// Parse llhttp markdown sections into test cases.
|
||||
// markdown-rs exposes the same mdast node types used by remark-parse.
|
||||
let tree = to_mdast(&raw, &ParseOptions::default()).map_err(|error| error.to_string())?;
|
||||
let mut parsed = Vec::new();
|
||||
let mut current_section: Option<String> = None;
|
||||
let mut current_case: Option<Case> = None;
|
||||
|
||||
let flush_case = |current_case: &mut Option<Case>, parsed: &mut Vec<Case>| {
|
||||
// A valid llhttp markdown case is complete only after both input and expected
|
||||
// log blocks are seen.
|
||||
if let Some(case) = current_case.take()
|
||||
&& case.http.is_some()
|
||||
&& case.log.is_some()
|
||||
{
|
||||
parsed.push(case);
|
||||
}
|
||||
};
|
||||
|
||||
for node in tree.children().into_iter().flatten() {
|
||||
if let Node::Heading(heading) = node
|
||||
&& (heading.depth == 2 || heading.depth == 3)
|
||||
{
|
||||
flush_case(&mut current_case, &mut parsed);
|
||||
let heading_text = heading
|
||||
.children
|
||||
.iter()
|
||||
.filter_map(|child| {
|
||||
match child {
|
||||
Node::Text(text) => Some(text.value.as_str()),
|
||||
Node::InlineCode(code) => Some(code.value.as_str()),
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
.collect::<String>();
|
||||
let cleaned_heading = clean_heading(&heading_text);
|
||||
let titles = if heading.depth == 2 {
|
||||
current_section = Some(cleaned_heading.clone());
|
||||
vec![cleaned_heading]
|
||||
} else if let Some(section) = current_section.as_ref().filter(|section| !section.is_empty()) {
|
||||
vec![section.clone(), cleaned_heading]
|
||||
} else {
|
||||
vec![cleaned_heading]
|
||||
};
|
||||
current_case = Some(Case {
|
||||
titles,
|
||||
source: json!({ "path": source_path, "line": heading.position.as_ref().map_or(1, |position| position.start.line) }),
|
||||
meta: Value::Null,
|
||||
http: None,
|
||||
log: None,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Node::Html(html) = node
|
||||
&& let Some(case) = current_case.as_mut().filter(|case| case.http.is_none())
|
||||
{
|
||||
if let Some(Value::Object(meta)) = parse_html_meta(&html.value)? {
|
||||
if !case.meta.is_object() {
|
||||
case.meta = Value::Object(Map::new());
|
||||
}
|
||||
case.meta.as_object_mut().unwrap().extend(meta);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Node::Code(code) = node
|
||||
&& let Some(case) = current_case.as_mut()
|
||||
{
|
||||
let code_lang = code.lang.as_deref().unwrap_or("").to_lowercase();
|
||||
if code_lang == "http" {
|
||||
case.http = Some(code.value.clone());
|
||||
} else if code_lang == "log" {
|
||||
case.log = Some(code.value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
flush_case(&mut current_case, &mut parsed);
|
||||
|
||||
for item in parsed {
|
||||
let input = item.http.unwrap();
|
||||
let log = item.log.unwrap();
|
||||
if input.is_empty() || log.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Build deterministic fixture file name from titles.
|
||||
// Keep the original normalization and collision suffixes for fixture names.
|
||||
static NON_NAME: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[^a-z0-9\s-]").unwrap());
|
||||
static SPACES: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[\s_]+").unwrap());
|
||||
static HYPHENS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"-+").unwrap());
|
||||
let name = item
|
||||
.titles
|
||||
.iter()
|
||||
.map(|part| {
|
||||
let normalized = DecomposingNormalizer::new_nfkd()
|
||||
.normalize(&clean_heading(part))
|
||||
.to_lowercase();
|
||||
let normalized = NON_NAME.replace_all(&normalized, " ");
|
||||
let normalized = SPACES.replace_all(normalized.trim(), "-");
|
||||
HYPHENS.replace_all(&normalized, "-").trim_matches('-').to_owned()
|
||||
})
|
||||
.filter(|part| !part.is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join("-");
|
||||
let mut file_name = format!("{}.yml", if name.is_empty() { "test" } else { &name });
|
||||
if !used_names.contains(&file_name) {
|
||||
used_names.insert(file_name.clone());
|
||||
} else {
|
||||
let mut counter = 2;
|
||||
while used_names.contains(&format!("{name}-{counter}.yml")) {
|
||||
counter += 1;
|
||||
}
|
||||
file_name = format!("{name}-{counter}.yml");
|
||||
used_names.insert(file_name.clone());
|
||||
}
|
||||
|
||||
let prefix = &item.titles[0];
|
||||
let child = item.titles.get(1).filter(|child| !child.is_empty());
|
||||
// Keep display names aligned with existing fixture format.
|
||||
let title_case = |value: &str| {
|
||||
value
|
||||
.split_whitespace()
|
||||
.map(|part| {
|
||||
let mut characters = part.chars();
|
||||
format!("{}{}", characters.next().unwrap().to_uppercase(), characters.as_str())
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
};
|
||||
let mut fixture = json!({
|
||||
"path": format!("{FIXTURE_PREFIX}/{section}/{file_name}"),
|
||||
"name": if let Some(child) = child {
|
||||
format!("{} / {}", clean_heading(prefix), title_case(&clean_heading(child)))
|
||||
} else {
|
||||
title_case(&clean_heading(prefix))
|
||||
},
|
||||
"checked": false,
|
||||
"source": item.source,
|
||||
});
|
||||
if has_meta(&item.meta) {
|
||||
fixture["meta"] = item.meta;
|
||||
}
|
||||
fixture["input"] = input.split('\n').map(|line| Value::String(line.into())).collect();
|
||||
fixture["llhttp"] = log.split('\n').map(|line| Value::String(line.into())).collect();
|
||||
cases.push((file_name, fixture));
|
||||
}
|
||||
}
|
||||
|
||||
let target_dir = fixture_root.join(format!("{section}s"));
|
||||
fs::create_dir_all(&target_dir)?;
|
||||
let temp_fixture_path = target_dir.join(format!(".import-llhttp-{section}-temp.yml"));
|
||||
for (i, (path, fixture)) in cases.iter().enumerate() {
|
||||
println!("Processing {section} case {}/{}: {path}", i + 1, cases.len());
|
||||
let file_path = target_dir.join(path);
|
||||
seen_files.insert(format!("{section}s/{path}"));
|
||||
let mut initial_fixture = fixture.clone();
|
||||
initial_fixture["output"] = json!([]);
|
||||
let initial_content = stringify_fixture(&initial_fixture);
|
||||
fs::write(&temp_fixture_path, initial_content)?;
|
||||
|
||||
// Run generator using a temporary fixture to compute output.
|
||||
let file_arg = temp_fixture_path
|
||||
.strip_prefix(output_root)?
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
let result = Command::new("cargo")
|
||||
.args(["run", "--example", "llhttp", "--", "--generate", &file_arg])
|
||||
.current_dir(output_root)
|
||||
.output();
|
||||
let stdout = match result {
|
||||
Ok(result)
|
||||
if result.status.success()
|
||||
&& result.stdout.len() <= 10 * 1024 * 1024
|
||||
&& result.stderr.len() <= 10 * 1024 * 1024 =>
|
||||
{
|
||||
String::from_utf8_lossy(&result.stdout).into_owned()
|
||||
}
|
||||
result => {
|
||||
let details = result
|
||||
.map(|result| String::from_utf8_lossy(&result.stderr).trim().to_owned())
|
||||
.unwrap_or_default();
|
||||
let details = if details.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("\n{details}")
|
||||
};
|
||||
fail(&format!("Failed to run cargo generator for {file_arg}{details}"));
|
||||
}
|
||||
};
|
||||
let Some(marker_index) = stdout.find("---") else {
|
||||
fail(&format!(
|
||||
"Failed to parse cargo output for {file_arg}: missing YAML marker"
|
||||
));
|
||||
};
|
||||
let yaml_snippet = stdout[marker_index + 3..].trim();
|
||||
if yaml_snippet.is_empty() {
|
||||
fail(&format!(
|
||||
"Failed to parse cargo output for {file_arg}: empty YAML snippet"
|
||||
));
|
||||
}
|
||||
let output: Value = serde_yaml::from_str(yaml_snippet)?;
|
||||
let mut final_fixture = fixture.clone();
|
||||
final_fixture["output"] = output;
|
||||
|
||||
// Skip writes when only comments/checked differ semantically.
|
||||
let skip_overwrite = match fs::read_to_string(&file_path) {
|
||||
Ok(raw) => {
|
||||
serde_yaml::from_str::<Value>(&raw).is_ok_and(|existing_fixture| {
|
||||
normalize_fixture_for_comparison(&existing_fixture) == normalize_fixture_for_comparison(&final_fixture)
|
||||
})
|
||||
}
|
||||
Err(error) if error.kind() == ErrorKind::NotFound => false,
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
if skip_overwrite {
|
||||
continue;
|
||||
}
|
||||
let final_content = stringify_fixture(&final_fixture);
|
||||
fs::write(file_path, final_content)?;
|
||||
}
|
||||
match fs::remove_file(temp_fixture_path) {
|
||||
Ok(()) => {}
|
||||
Err(error) if error.kind() == ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let args = env::args().collect::<Vec<_>>();
|
||||
if args.len() < 3 || args[1].is_empty() || args[2].is_empty() {
|
||||
println!("Usage: import-llhttp-tests <llhttp-root> <output-root>");
|
||||
return Ok(());
|
||||
}
|
||||
let llhttp_root = std::path::absolute(&args[1])?;
|
||||
let output_root = std::path::absolute(&args[2])?;
|
||||
let fixture_root = output_root.join(FIXTURE_PREFIX);
|
||||
fs::create_dir_all(&fixture_root)?;
|
||||
|
||||
// Snapshot fixtures that existed before import starts.
|
||||
// Keep discovery order for stale-file messages, as JavaScript's Set does.
|
||||
let mut existing_files = Vec::new();
|
||||
for section in ["requests", "responses"] {
|
||||
let section_root = fixture_root.join(section);
|
||||
// Section folder may not exist yet.
|
||||
if let Ok(files) = glob_files(§ion_root, "yml") {
|
||||
for file in files {
|
||||
existing_files.push(file.strip_prefix(&fixture_root)?.to_string_lossy().replace('\\', "/"));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut seen_files = HashSet::new();
|
||||
process_section(&llhttp_root, &output_root, &fixture_root, "request", &mut seen_files)?;
|
||||
process_section(&llhttp_root, &output_root, &fixture_root, "response", &mut seen_files)?;
|
||||
for file in existing_files {
|
||||
if seen_files.contains(&file) {
|
||||
continue;
|
||||
}
|
||||
match fs::remove_file(fixture_root.join(&file)) {
|
||||
Ok(()) => {}
|
||||
Err(error) if error.kind() == ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
println!("Removed stale fixture: {file}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
use std::{env, error::Error, fs, path::Path};
|
||||
|
||||
use milo_build_scripts::get_build_info;
|
||||
|
||||
fn prepend_version_and_method_map(header: &str) -> Result<String, Box<dyn Error>> {
|
||||
let header_matcher = "namespace milo_parser {";
|
||||
let info = get_build_info()?;
|
||||
let version = info.version;
|
||||
// Create the method map, required by Node.js.
|
||||
let methods = info
|
||||
.constants
|
||||
.iter()
|
||||
.filter_map(|(key, value)| {
|
||||
key
|
||||
.strip_prefix("METHOD_")
|
||||
.map(|method| format!(" EACH({value}, {method}, {method}) \\"))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let updated_header = format!(
|
||||
r#"#define MILO_VERSION "{}"
|
||||
#define MILO_VERSION_MAJOR {}
|
||||
#define MILO_VERSION_MINOR {}
|
||||
#define MILO_VERSION_PATCH {}
|
||||
#define MILO_VERSION_PRERELEASE "{}"
|
||||
|
||||
#define MILO_METHODS_MAP(EACH) \
|
||||
{methods}
|
||||
|
||||
namespace milo_parser {{
|
||||
|
||||
struct Parser;"#,
|
||||
version.raw, version.major, version.minor, version.patch, version.prerelease
|
||||
);
|
||||
|
||||
// Replace the header with the new code.
|
||||
// Match the JavaScript normalization without changing other whitespace.
|
||||
let mut normalized = String::with_capacity(header.len());
|
||||
let mut newlines = 0;
|
||||
for character in header.chars() {
|
||||
if character == '\n' {
|
||||
newlines += 1;
|
||||
} else {
|
||||
newlines = 0;
|
||||
}
|
||||
if newlines <= 2 {
|
||||
normalized.push(character);
|
||||
}
|
||||
}
|
||||
Ok(normalized.replacen(header_matcher, &updated_header, 1))
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let profile = env::args().nth(1).ok_or("Usage: postbuild-cpp <profile>")?;
|
||||
// Read the file.
|
||||
let header_path = Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../dist/cpp")
|
||||
.join(profile)
|
||||
.join("milo.h");
|
||||
let header = fs::read_to_string(&header_path)?;
|
||||
// Apply modifications.
|
||||
let header = prepend_version_and_method_map(&header)?;
|
||||
// Write the updated file.
|
||||
fs::write(header_path, header)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
use std::{env, error::Error, fs, io::ErrorKind, path::Path};
|
||||
|
||||
use base64::{Engine, engine::general_purpose::STANDARD};
|
||||
use milo_build_scripts::{BuildInfo, get_build_info};
|
||||
use serde_json::Value;
|
||||
|
||||
const ENUMS: &[(&str, &str)] = &[
|
||||
("ERROR_", "Errors"),
|
||||
("METHOD_", "Methods"),
|
||||
("CALLBACK_", "Callbacks"),
|
||||
("CALLBACK_ACTIVE_", "CallbackActives"),
|
||||
("EVENT_", "Events"),
|
||||
("EVENT_ACTIVE_", "EventActives"),
|
||||
("STATE_", "States"),
|
||||
("PARSER_FIELD_", "ParserFields"),
|
||||
];
|
||||
|
||||
enum GetterType {
|
||||
Bool,
|
||||
Number,
|
||||
BigInt,
|
||||
String,
|
||||
}
|
||||
|
||||
const GETTERS: &[(&str, GetterType, &str)] = &[
|
||||
("isAutodetect", GetterType::Bool, "is_autodetect"),
|
||||
("isRequest", GetterType::Bool, "is_request"),
|
||||
("isPaused", GetterType::Bool, "is_paused"),
|
||||
("shouldManageUnconsumed", GetterType::Bool, "should_manage_unconsumed"),
|
||||
(
|
||||
"shouldSuspendAfterHeaders",
|
||||
GetterType::Bool,
|
||||
"should_suspend_after_headers",
|
||||
),
|
||||
("getMaxStartLineLength", GetterType::Number, "get_max_start_line_length"),
|
||||
("getMaxHeaderLength", GetterType::Number, "get_max_header_length"),
|
||||
("getMaxBodyPayload", GetterType::BigInt, "get_max_body_payload"),
|
||||
(
|
||||
"shouldContinueWithoutData",
|
||||
GetterType::Bool,
|
||||
"should_continue_without_data",
|
||||
),
|
||||
("isConnect", GetterType::Bool, "is_connect"),
|
||||
("isDebug", GetterType::Bool, "is_debug"),
|
||||
("shouldSkipBody", GetterType::Bool, "should_skip_body"),
|
||||
("getState", GetterType::Number, "get_state"),
|
||||
("getPosition", GetterType::Number, "get_position"),
|
||||
("getParsed", GetterType::BigInt, "get_parsed"),
|
||||
("getErrorCode", GetterType::Number, "get_error_code"),
|
||||
("getMethod", GetterType::Number, "get_method"),
|
||||
("getStatus", GetterType::Number, "get_status"),
|
||||
("hasConnectionClose", GetterType::Bool, "has_connection_close"),
|
||||
("hasConnectionUpgrade", GetterType::Bool, "has_connection_upgrade"),
|
||||
("getContentLength", GetterType::BigInt, "get_content_length"),
|
||||
("getChunkSize", GetterType::BigInt, "get_chunk_size"),
|
||||
(
|
||||
"getRemainingContentLength",
|
||||
GetterType::BigInt,
|
||||
"get_remaining_content_length",
|
||||
),
|
||||
("getRemainingChunkSize", GetterType::BigInt, "get_remaining_chunk_size"),
|
||||
("hasContentLength", GetterType::Bool, "has_content_length"),
|
||||
("hasTransferEncoding", GetterType::Bool, "has_transfer_encoding"),
|
||||
(
|
||||
"hasChunkedTransferEncoding",
|
||||
GetterType::Bool,
|
||||
"has_chunked_transfer_encoding",
|
||||
),
|
||||
("hasUpgrade", GetterType::Bool, "has_upgrade"),
|
||||
("hasTrailers", GetterType::Bool, "has_trailers"),
|
||||
("getErrorDescription", GetterType::String, "get_error_description_raw"),
|
||||
];
|
||||
|
||||
const SETTERS: &[(&str, &str)] = &[
|
||||
("setShouldAutodetect", "set_should_autodetect"),
|
||||
("setShouldContinueWithoutData", "set_should_continue_without_data"),
|
||||
("setIsRequest", "set_is_request"),
|
||||
("setIsConnect", "set_is_connect"),
|
||||
("setDebug", "set_debug"),
|
||||
("setShouldManageUnconsumed", "set_should_manage_unconsumed"),
|
||||
("setShouldSuspendAfterHeaders", "set_should_suspend_after_headers"),
|
||||
("setMaxStartLineLength", "set_max_start_line_length"),
|
||||
("setMaxHeaderLength", "set_max_header_length"),
|
||||
("setMaxBodyPayload", "set_max_body_payload"),
|
||||
("setShouldSkipBody", "set_should_skip_body"),
|
||||
("setActiveCallbacks", "set_active_callbacks"),
|
||||
("setActiveEvents", "set_active_events"),
|
||||
];
|
||||
|
||||
fn get_callbacks(info: &BuildInfo) -> Vec<(&str, &Value)> {
|
||||
info
|
||||
.constants
|
||||
.iter()
|
||||
.filter(|(key, _)| key.starts_with("CALLBACK_") && !key.starts_with("CALLBACK_ACTIVE"))
|
||||
.map(|(key, value)| (key.as_str(), value))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn generate_enums(info: &BuildInfo) -> String {
|
||||
let mut replacement = String::new();
|
||||
for &(selector, name) in ENUMS {
|
||||
let mut matching = info
|
||||
.constants
|
||||
.iter()
|
||||
.filter(|(key, _)| key.starts_with(selector))
|
||||
.collect::<Vec<_>>();
|
||||
let mut suffix = "";
|
||||
if selector == "CALLBACK_" {
|
||||
matching.retain(|(key, _)| !key.starts_with("CALLBACK_ACTIVE"));
|
||||
} else if selector == "EVENT_" {
|
||||
matching.retain(|(key, _)| !key.starts_with("EVENT_ACTIVE_"));
|
||||
} else if selector == "CALLBACK_ACTIVE_" || selector == "EVENT_ACTIVE_" {
|
||||
suffix = "n";
|
||||
}
|
||||
let entries = matching
|
||||
.iter()
|
||||
.map(|(key, value)| format!(" {}: {value}{suffix}", &key[selector.len()..]))
|
||||
.chain(
|
||||
matching
|
||||
.iter()
|
||||
.map(|(key, value)| format!(" {value}{suffix}: '{}'", &key[selector.len()..])),
|
||||
)
|
||||
.collect::<Vec<_>>()
|
||||
.join(",\n");
|
||||
replacement.push_str(&format!("const {name} = Object.freeze({{\n{entries}\n}})\n\n"));
|
||||
}
|
||||
replacement.trim_end().to_owned()
|
||||
}
|
||||
|
||||
fn generate_enums_lists() -> String {
|
||||
ENUMS
|
||||
.iter()
|
||||
.map(|(_, name)| format!("{name},"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
fn generate_constants(info: &BuildInfo) -> String {
|
||||
info
|
||||
.constants
|
||||
.iter()
|
||||
.map(|(key, value)| {
|
||||
let mut value = value.to_string();
|
||||
if key.starts_with("CALLBACK_ACTIVE_") || key.starts_with("EVENT_ACTIVE_") {
|
||||
value.push('n');
|
||||
}
|
||||
format!("{key}: {value},")
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
fn generate_getters() -> String {
|
||||
let mut replacement = String::new();
|
||||
for (getter, kind, raw_getter) in GETTERS {
|
||||
let call = format!("this.{raw_getter}(parser)");
|
||||
let body = match kind {
|
||||
GetterType::Bool => format!(" return {call} !== 0"),
|
||||
GetterType::Number => format!(" return {call} >>> 0"),
|
||||
GetterType::BigInt => format!(" return BigInt.asUintN(64, {call})"),
|
||||
GetterType::String => {
|
||||
format!(
|
||||
" const raw = {call}\n const len = Number(BigInt.asUintN(32, raw))\n const ptr = Number(raw >> 32n)\n \
|
||||
return textDecoder.decode(new Uint8Array(this.memory.buffer, ptr, len))"
|
||||
)
|
||||
}
|
||||
};
|
||||
replacement.push_str(&format!("function {getter} (parser) {{\n{body}\n}}\n\n"));
|
||||
}
|
||||
replacement.trim_end().to_owned()
|
||||
}
|
||||
|
||||
fn generate_setters() -> String {
|
||||
let mut replacement = String::new();
|
||||
for (setter, raw_setter) in SETTERS {
|
||||
replacement.push_str(&format!(
|
||||
"function {setter} (parser, value) {{\n this.{raw_setter}(parser, value)\n}}\n\n"
|
||||
));
|
||||
}
|
||||
replacement.trim_end().to_owned()
|
||||
}
|
||||
|
||||
fn generate_getters_list() -> String {
|
||||
GETTERS
|
||||
.iter()
|
||||
.map(|(name, _, _)| format!("{name}: {name}.bind(wasm),"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
fn generate_setters_list() -> String {
|
||||
SETTERS
|
||||
.iter()
|
||||
.map(|(name, _)| format!("{name}: {name}.bind(wasm),"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
fn generate_noop_callbacks(info: &BuildInfo) -> String {
|
||||
get_callbacks(info)
|
||||
.iter()
|
||||
.map(|(key, _)| format!("{}: noop,", key.replacen("CALLBACK_", "", 1).to_lowercase()))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
fn generate_simple_callbacks(info: &BuildInfo) -> String {
|
||||
get_callbacks(info)
|
||||
.iter()
|
||||
.map(|(key, value)| {
|
||||
let name = key.replacen("CALLBACK_", "", 1).to_lowercase();
|
||||
format!("{name} (parser, at, len) {{\n spans[parser].push([{value}, at, len])\n}}")
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(",\n")
|
||||
}
|
||||
|
||||
fn generate_module(profile: &str, info: &BuildInfo, loader: &str, commonjs: bool) -> Result<String, Box<dyn Error>> {
|
||||
let template = fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../parser/wasm/src/template.js"))?;
|
||||
let version = &info.version;
|
||||
let mut output = String::new();
|
||||
|
||||
// The template is shared by bundled/unbundled and ESM/CJS outputs;
|
||||
// placeholders keep the runtime code identical.
|
||||
// Placeholders occupy complete lines. Emit already formatted fragments using
|
||||
// the template's indentation, so packaging needs no JavaScript formatter.
|
||||
for line in template.lines() {
|
||||
let trimmed = line.trim_start();
|
||||
if let Some(id) = trimmed.strip_prefix("/* REPLACE: ").and_then(|s| s.strip_suffix(" */")) {
|
||||
let replacement = match id {
|
||||
"module" => loader.to_owned(),
|
||||
"version" => {
|
||||
format!(
|
||||
"version: {{\n raw: '{}',\n major: {},\n minor: {},\n patch: {},\n prerelease: '{}'\n}},",
|
||||
version.raw, version.major, version.minor, version.patch, version.prerelease
|
||||
)
|
||||
}
|
||||
"enums" => generate_enums(info),
|
||||
"enums:list" => generate_enums_lists(),
|
||||
"constants" => generate_constants(info),
|
||||
"getters" => generate_getters(),
|
||||
"setters" => generate_setters(),
|
||||
"getters:list" => generate_getters_list(),
|
||||
"setters:list" => generate_setters_list(),
|
||||
"callbacks:noop" => generate_noop_callbacks(info),
|
||||
"callbacks:simple" => generate_simple_callbacks(info),
|
||||
"start" => {
|
||||
if profile == "debug" {
|
||||
"wasm.__start()".to_owned()
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
eprintln!("Unsupported placeholder type {id}");
|
||||
trimmed.to_owned()
|
||||
}
|
||||
};
|
||||
let indent = &line[..line.len() - trimmed.len()];
|
||||
for fragment in replacement.lines() {
|
||||
if !fragment.is_empty() {
|
||||
output.push_str(indent);
|
||||
output.push_str(fragment);
|
||||
}
|
||||
output.push('\n');
|
||||
}
|
||||
} else {
|
||||
output.push_str(line);
|
||||
output.push('\n');
|
||||
}
|
||||
}
|
||||
if commonjs {
|
||||
output = output
|
||||
.lines()
|
||||
.map(|line| {
|
||||
if line.starts_with("export function ") {
|
||||
&line["export ".len()..]
|
||||
} else {
|
||||
line
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
output.push('\n');
|
||||
output.push_str("\nmodule.exports = { wasmModule, noop, setup, simple }\n");
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
fn generate_commonjs_package_json(package_json: &Value) -> Value {
|
||||
let mut cjs_package_json = package_json.clone();
|
||||
cjs_package_json["name"] = "@perseveranza-pets/milo-cjs".into();
|
||||
cjs_package_json["type"] = "commonjs".into();
|
||||
cjs_package_json
|
||||
}
|
||||
|
||||
fn generate_variant(
|
||||
profile: &str,
|
||||
info: &BuildInfo,
|
||||
root_folder: &Path,
|
||||
variant: &str,
|
||||
commonjs: bool,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
let wasm_file = format!("{variant}.wasm");
|
||||
let source_folder = root_folder.join("src").join(variant);
|
||||
let profile_root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../dist/wasm").join(profile);
|
||||
let wasm = STANDARD.encode(fs::read(profile_root.join("binary").join(&wasm_file))?);
|
||||
let unbundled_loader = if commonjs {
|
||||
format!(
|
||||
"const {{ readFileSync }} = require('node:fs')\nconst {{ join }} = require('node:path')\n\nconst wasmModule = \
|
||||
new WebAssembly.Module(readFileSync(join(__dirname, '../../binary/{wasm_file}')))"
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"import {{ readFileSync }} from 'node:fs'\n\nexport const wasmModule = new WebAssembly.Module(readFileSync(new \
|
||||
URL('../../binary/{wasm_file}', import.meta.url)))"
|
||||
)
|
||||
};
|
||||
let bundled_loader = if commonjs {
|
||||
format!("const wasmModule = new WebAssembly.Module(\n Buffer.from(\n '{wasm}',\n 'base64'\n )\n)")
|
||||
} else {
|
||||
format!(
|
||||
"export const wasmModule = new WebAssembly.Module(\n Uint8Array.from(\n globalThis.atob(\n '{wasm}'\n ),\n c => c.codePointAt(0)\n )\n)"
|
||||
)
|
||||
};
|
||||
let unbundled = generate_module(profile, info, &unbundled_loader, commonjs)?;
|
||||
let bundled = generate_module(profile, info, &bundled_loader, commonjs)?;
|
||||
fs::create_dir_all(&source_folder)?;
|
||||
fs::write(source_folder.join("unbundled.js"), unbundled)?;
|
||||
fs::write(source_folder.join("index.js"), bundled)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn copy_directory(source: &Path, destination: &Path) -> Result<(), Box<dyn Error>> {
|
||||
fs::create_dir_all(destination)?;
|
||||
for entry in fs::read_dir(source)? {
|
||||
let entry = entry?;
|
||||
let target = destination.join(entry.file_name());
|
||||
if entry.file_type()?.is_dir() {
|
||||
copy_directory(&entry.path(), &target)?;
|
||||
} else {
|
||||
fs::copy(entry.path(), target)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// TODO@PI: Generate TypeScript declarations.
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let info = get_build_info()?;
|
||||
let profile = env::args().nth(1).ok_or("Usage: postbuild-wasm <profile>")?;
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
|
||||
// Open the package.json and update the version.
|
||||
let mut package_json: Value = serde_json::from_str(&fs::read_to_string(root.join("parser/wasm/src/package.json"))?)?;
|
||||
let profile_root = root.join("dist/wasm").join(&profile);
|
||||
let root_folder = profile_root.join("package");
|
||||
let cjs_root_folder = profile_root.join("package-cjs");
|
||||
package_json["version"] = info.version.raw.clone().into();
|
||||
let cjs_package_json = generate_commonjs_package_json(&package_json);
|
||||
|
||||
// Write files.
|
||||
for folder in [&root_folder, &cjs_root_folder] {
|
||||
match fs::remove_dir_all(folder) {
|
||||
Ok(()) => {}
|
||||
Err(error) if error.kind() == ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
}
|
||||
fs::create_dir_all(&root_folder)?;
|
||||
fs::create_dir_all(&cjs_root_folder)?;
|
||||
copy_directory(&profile_root.join("binary"), &root_folder.join("binary"))?;
|
||||
copy_directory(&profile_root.join("binary"), &cjs_root_folder.join("binary"))?;
|
||||
generate_variant(&profile, &info, &root_folder, "simd", false)?;
|
||||
generate_variant(&profile, &info, &root_folder, "no-simd", false)?;
|
||||
generate_variant(&profile, &info, &cjs_root_folder, "simd", true)?;
|
||||
generate_variant(&profile, &info, &cjs_root_folder, "no-simd", true)?;
|
||||
fs::write(
|
||||
root_folder.join("package.json"),
|
||||
serde_json::to_string_pretty(&package_json)?,
|
||||
)?;
|
||||
fs::write(
|
||||
cjs_root_folder.join("package.json"),
|
||||
serde_json::to_string_pretty(&cjs_package_json)?,
|
||||
)?;
|
||||
// Copy other Markdown files from root.
|
||||
for name in ["CODE_OF_CONDUCT.md", "LICENSE.md", "README.md"] {
|
||||
fs::copy(root.join(name), root_folder.join(name))?;
|
||||
fs::copy(root.join(name), cjs_root_folder.join(name))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
use std::{
|
||||
env,
|
||||
error::Error,
|
||||
fs,
|
||||
path::Path,
|
||||
process::{Command, Stdio},
|
||||
};
|
||||
|
||||
use regex::{Captures, Regex};
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let folders = ["macros", "parser", "references/rust", "parser/wasm/src"];
|
||||
let version = env::args().nth(1).ok_or("Usage: sync-versions <version>")?;
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
|
||||
|
||||
for folder in folders {
|
||||
let path = root.join(folder);
|
||||
env::set_current_dir(path)?;
|
||||
// Like execFileSync, wait for each update and discard its stdout.
|
||||
let output = Command::new("cambi")
|
||||
.args(["update", &version])
|
||||
.stderr(Stdio::inherit())
|
||||
.output()?;
|
||||
if !output.status.success() {
|
||||
return Err(format!("cambi update failed in {folder}: {}", output.status).into());
|
||||
}
|
||||
}
|
||||
|
||||
// Dependency of milo-macros.
|
||||
// Update it without reformatting the manifest.
|
||||
let main_cargo = root.join("parser/Cargo.toml");
|
||||
let main_cargo_content = fs::read_to_string(&main_cargo)?;
|
||||
let matcher = Regex::new(r#"(?m)^(\s+milo-macros = \{ version = ")([^"]+)(")"#)?;
|
||||
let main_cargo_content = matcher.replace(&main_cargo_content, |captures: &Captures<'_>| {
|
||||
format!("{}{version}{}", &captures[1], &captures[3])
|
||||
});
|
||||
fs::write(main_cargo, main_cargo_content.as_bytes())?;
|
||||
Ok(())
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
use std::{error::Error, fs, path::Path};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
// Reuse the layout used by the macros without spawning Cargo at runtime.
|
||||
// The macro generator and CLI entry point are unused in this crate.
|
||||
#[allow(dead_code)]
|
||||
#[path = "../../macros/src/parser_fields.rs"]
|
||||
mod parser_fields;
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct Version {
|
||||
pub raw: String,
|
||||
pub major: u64,
|
||||
pub minor: u64,
|
||||
pub patch: u64,
|
||||
pub prerelease: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct BuildInfo {
|
||||
pub version: Version,
|
||||
pub constants: Map<String, Value>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Package {
|
||||
version: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Manifest {
|
||||
package: Package,
|
||||
}
|
||||
|
||||
fn read_yaml_list(name: &str) -> Result<Vec<String>, Box<dyn Error>> {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
|
||||
let raw = fs::read_to_string(root.join(format!("macros/constants/{name}.yml")))?;
|
||||
Ok(serde_yaml::from_str(&raw)?)
|
||||
}
|
||||
|
||||
fn read_version() -> Result<Version, Box<dyn Error>> {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
|
||||
let manifest: Manifest = toml::from_str(&fs::read_to_string(root.join("parser/Cargo.toml"))?)?;
|
||||
let parsed = semver::Version::parse(&manifest.package.version)?;
|
||||
Ok(Version {
|
||||
raw: manifest.package.version,
|
||||
major: parsed.major,
|
||||
minor: parsed.minor,
|
||||
patch: parsed.patch,
|
||||
prerelease: parsed.pre.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
fn read_parser_fields() -> Map<String, Value> {
|
||||
// The JavaScript helper spawned Cargo; Rust can reuse the same offsets
|
||||
// directly.
|
||||
parser_fields::FIELDS
|
||||
.iter()
|
||||
.map(|&(name, offset)| (format!("PARSER_FIELD_{name}"), offset.into()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Reads the current repository inputs, independently of the working directory.
|
||||
pub fn get_build_info() -> Result<BuildInfo, Box<dyn Error>> {
|
||||
let version = read_version()?;
|
||||
let methods = read_yaml_list("methods")?;
|
||||
let errors = read_yaml_list("errors")?;
|
||||
let callbacks = read_yaml_list("callbacks")?;
|
||||
let states = read_yaml_list("states")?;
|
||||
let parser_fields = read_parser_fields();
|
||||
|
||||
// Insertion order is part of the generated JSON and downstream bindings.
|
||||
let mut constants = Map::new();
|
||||
for (i, method) in methods.iter().enumerate() {
|
||||
constants.insert(format!("METHOD_{}", method.replace('-', "_")), i.into());
|
||||
}
|
||||
for (i, callback) in callbacks.iter().enumerate() {
|
||||
constants.insert(format!("CALLBACK_{}", callback.to_uppercase()), i.into());
|
||||
}
|
||||
constants.insert("EVENT_END".into(), 0.into());
|
||||
for (i, callback) in callbacks.iter().enumerate() {
|
||||
let name = callback.strip_prefix("on_").unwrap_or(callback).to_uppercase();
|
||||
constants.insert(format!("EVENT_{name}"), (i + 1).into());
|
||||
}
|
||||
|
||||
let mut all = 0;
|
||||
constants.insert("CALLBACK_ACTIVE_NONE".into(), 0.into());
|
||||
constants.insert("EVENT_ACTIVE_NONE".into(), 0.into());
|
||||
for (i, callback) in callbacks.iter().enumerate() {
|
||||
// Match JavaScript's signed 32-bit shifts, including the masked shift count.
|
||||
let bit = 1_i32.wrapping_shl((i % 32) as u32);
|
||||
constants.insert(format!("CALLBACK_ACTIVE_{}", callback.to_uppercase()), bit.into());
|
||||
constants.insert(format!("EVENT_ACTIVE_{}", callback.to_uppercase()), bit.into());
|
||||
all |= bit;
|
||||
}
|
||||
constants.insert("CALLBACK_ACTIVE_ALL".into(), all.into());
|
||||
constants.insert("EVENT_ACTIVE_ALL".into(), all.into());
|
||||
for (i, error) in errors.iter().enumerate() {
|
||||
constants.insert(format!("ERROR_{error}"), i.into());
|
||||
}
|
||||
for (i, state) in states.iter().enumerate() {
|
||||
constants.insert(format!("STATE_{}", state.to_uppercase()), i.into());
|
||||
}
|
||||
constants.extend(parser_fields);
|
||||
|
||||
Ok(BuildInfo { version, constants })
|
||||
}
|
||||
+24
-9
@@ -42,7 +42,8 @@ added: v7.0.0
|
||||
Stores cached responses in memory. The store enforces upper bounds on the total
|
||||
number of responses, the total size of all responses, and the size of any single
|
||||
response. When a limit is exceeded, the store evicts approximately half of its
|
||||
entries and emits a [`'maxSizeExceeded'`](#event-maxsizeexceeded) event.
|
||||
entries, least recently used first, and emits a
|
||||
[`'maxSizeExceeded'`](#event-maxsizeexceeded) event.
|
||||
|
||||
```mjs
|
||||
import { interceptors, cacheStores, Agent, setGlobalDispatcher } from 'undici'
|
||||
@@ -163,7 +164,9 @@ added: v7.0.0
|
||||
-->
|
||||
|
||||
Stores cached responses in a SQLite database using the [`node:sqlite`][] API.
|
||||
The constructor throws when [`node:sqlite`][] is not available.
|
||||
The constructor throws when [`node:sqlite`][] is not available. Response bodies
|
||||
larger than `compressThreshold` are stored compressed with zstd and
|
||||
decompressed when read back, saving database space.
|
||||
|
||||
```mjs
|
||||
import { interceptors, cacheStores, Agent, setGlobalDispatcher } from 'undici'
|
||||
@@ -189,9 +192,16 @@ added: v7.0.0
|
||||
* `maxEntrySize` {number} The maximum size, in bytes, of a single response
|
||||
body. Responses whose body exceeds this value are not cached. Must not
|
||||
exceed `2000000000` (2 GB). **Default:** `2000000000` (2 GB).
|
||||
* `compressThreshold` {number} The size, in bytes, above which a response
|
||||
body is stored compressed with zstd. Responses with an easily compressible
|
||||
Content-Type (e.g. json, xml, plain text) are compressed regardless of
|
||||
size. Requires a Node version with zstd
|
||||
support (22.19+); when unavailable, bodies are stored uncompressed.
|
||||
**Default:** `1048576` (1 MiB).
|
||||
|
||||
`maxCount` and `maxEntrySize` must be non-negative integers; a `TypeError` is
|
||||
thrown otherwise, or if `maxEntrySize` is greater than 2 GB.
|
||||
`maxCount`, `maxEntrySize`, and `compressThreshold` must be non-negative
|
||||
integers; a `TypeError` is thrown otherwise, or if `maxEntrySize` is greater
|
||||
than 2 GB.
|
||||
|
||||
### `sqliteCacheStore.close()`
|
||||
|
||||
@@ -225,7 +235,8 @@ added: v7.0.0
|
||||
See [`GetResult`](#getresult).
|
||||
|
||||
Looks up a cached response for `key`, comparing the request method and every
|
||||
header named in the stored `vary` map.
|
||||
header named in the stored `vary` map. A body that was stored compressed is
|
||||
decompressed before being returned.
|
||||
|
||||
### `sqliteCacheStore.set(key, value)`
|
||||
|
||||
@@ -240,9 +251,11 @@ added: v7.0.0
|
||||
* Returns: {undefined}
|
||||
|
||||
Writes a response into the database directly, without going through a stream. If
|
||||
the body exceeds `maxEntrySize`, nothing is stored. When an entry already exists
|
||||
for `key` it is overwritten; otherwise a new row is inserted and old entries are
|
||||
pruned to honour `maxCount`. This method is used internally by
|
||||
the body exceeds `maxEntrySize`, nothing is stored. A body larger than
|
||||
`compressThreshold`, or with an easily compressible Content-Type (e.g. json,
|
||||
xml, plain text), is compressed with zstd before being written. When an entry
|
||||
already exists for `key` it is overwritten; otherwise a new row is inserted and
|
||||
old entries are pruned to honour `maxCount`. This method is used internally by
|
||||
[`sqliteCacheStore.createWriteStream()`](#sqlitecachestorecreatewritestreamkey-value).
|
||||
|
||||
### `sqliteCacheStore.createWriteStream(key, value)`
|
||||
@@ -260,7 +273,9 @@ added: v7.0.0
|
||||
|
||||
Returns a {Writable} stream used to write the response body into the store. When
|
||||
the stream finishes, the buffered body is committed via
|
||||
[`sqliteCacheStore.set()`](#sqlitecachestoresetkey-value). If the body exceeds
|
||||
[`sqliteCacheStore.set()`](#sqlitecachestoresetkey-value), where bodies larger
|
||||
than `compressThreshold` or with an easily compressible Content-Type are
|
||||
compressed with zstd. If the body exceeds
|
||||
`maxEntrySize`, the stream is destroyed and nothing is stored.
|
||||
|
||||
### `sqliteCacheStore.delete(key)`
|
||||
|
||||
+11
-6
@@ -116,8 +116,8 @@ added: v1.0.0
|
||||
* `maxConcurrentStreams` {number} _Deprecated: use h2Options.useH2c instead_ The maximum number of concurrent HTTP/2
|
||||
streams for a single session. Once h2 is negotiated this — not `pipelining`,
|
||||
which is HTTP/1.1 only — is the ceiling used to dispatch in-flight requests.
|
||||
It may be overridden by the server's `SETTINGS_MAX_CONCURRENT_STREAMS`
|
||||
frame. **Default:** `100`.
|
||||
The server's `SETTINGS_MAX_CONCURRENT_STREAMS` can lower this limit, but
|
||||
not raise it. **Default:** `100`.
|
||||
* `connectionWindowSize` {number} _Deprecated: use h2Options.connectionWindowSize instead_ The HTTP/2 connection-level flow-control
|
||||
window size set via `ClientHttp2Session.setLocalWindowSize()`. Must be a
|
||||
positive integer. **Default:** `524288`.
|
||||
@@ -130,8 +130,8 @@ added: v1.0.0
|
||||
* `maxConcurrentStreams` {number} The maximum number of concurrent HTTP/2
|
||||
streams for a single session. Once h2 is negotiated this — not `pipelining`,
|
||||
which is HTTP/1.1 only — is the ceiling used to dispatch in-flight requests.
|
||||
It may be overridden by the server's `SETTINGS_MAX_CONCURRENT_STREAMS`
|
||||
frame. **Default:** `100`.
|
||||
The server's `SETTINGS_MAX_CONCURRENT_STREAMS` can lower this limit, but
|
||||
not raise it. **Default:** `100`.
|
||||
* `connectionWindowSize` {number} The HTTP/2 connection-level flow-control
|
||||
window size set via `ClientHttp2Session.setLocalWindowSize()`. Must be a
|
||||
positive integer. **Default:** `524288`.
|
||||
@@ -148,8 +148,13 @@ added: v1.0.0
|
||||
payloads, and decompressed (`permessage-deflate`) messages. Set to `0` to
|
||||
disable the limit. **Default:** `134217728`.
|
||||
* `eventSource` {Object} (optional) EventSource-specific configuration.
|
||||
* `maxEventSize` {number} The maximum allowed event size, in bytes, for
|
||||
EventSource messages. Set to `0` to disable the limit.
|
||||
* `maxEventSize` {number} The maximum total bytes of data and metadata
|
||||
field values retained for a pending EventSource event. Each unfinished
|
||||
line is separately limited to this value plus seven syntax bytes, before
|
||||
its line ending arrives. The number of `data:` lines per event and input
|
||||
chunks buffered for an unfinished line are each limited to
|
||||
`min(131072, max(1024, floor(maxEventSize / 128)))` to bound object overhead.
|
||||
Set to `0` to disable these limits.
|
||||
**Default:** `buffer.kStringMaxLength`.
|
||||
* Returns: {Client}
|
||||
|
||||
|
||||
+3
@@ -209,6 +209,9 @@ added: v4.0.0
|
||||
* `path` {string} The request path.
|
||||
* `method` {string} The HTTP method, e.g. `'GET'` or `'POST'`.
|
||||
* `body` {string|Buffer|Uint8Array|Readable|FormData|null} The request body.
|
||||
Undici's network clients require a `FormData` body created by the same
|
||||
undici package instance. A body from another source, including Node.js's
|
||||
built-in `FormData`, is rejected with an `InvalidArgumentError`.
|
||||
**Default:** `null`.
|
||||
* `headers` {UndiciHeaders} Request headers. **Default:** `null`.
|
||||
* `query` {Object} Query string parameters embedded into the request URL. Both
|
||||
|
||||
+76
-1
@@ -18,7 +18,7 @@ if (err instanceof errors.ConnectTimeoutError) {
|
||||
}
|
||||
```
|
||||
|
||||
All errors, except [`HTTPParserError`][], extend [`UndiciError`][]. Each error
|
||||
All errors, except [`HTTPParserError`][] and `WebAssemblyNotSupportedError`, extend [`UndiciError`][]. Each error
|
||||
carries a stable `code` string (for example `UND_ERR_CONNECT_TIMEOUT`) and a
|
||||
`name`.
|
||||
|
||||
@@ -32,6 +32,37 @@ if (err.code === 'UND_ERR_CONNECT_TIMEOUT') {
|
||||
}
|
||||
```
|
||||
|
||||
## Timeout-related errors
|
||||
|
||||
The timeout errors below are controlled by dispatcher/client options:
|
||||
|
||||
| Error code | When it is thrown | Related option |
|
||||
| ---------- | ----------------- | -------------- |
|
||||
| `UND_ERR_CONNECT_TIMEOUT` | A connection could not be established before the connection timeout elapsed. | [`connect.timeout`](Client.md) |
|
||||
| `UND_ERR_HEADERS_TIMEOUT` | The full response headers were not received before the headers timeout elapsed. | [`headersTimeout`](Client.md) |
|
||||
| `UND_ERR_BODY_TIMEOUT` | While reading the response body, no new data arrived before the body timeout elapsed. | [`bodyTimeout`](Client.md) |
|
||||
| `UND_ERR_SOCKET` | A generic socket-level failure happened. | Inspect `error.socket` for connection details. |
|
||||
|
||||
### Configuring timeouts for `fetch`
|
||||
|
||||
If you are using `fetch` (including Node.js built-in `fetch`), configure timeouts
|
||||
through the global dispatcher:
|
||||
|
||||
```js
|
||||
import { Agent, setGlobalDispatcher, fetch } from 'undici'
|
||||
|
||||
setGlobalDispatcher(new Agent({
|
||||
connect: { timeout: 10_000 }, // connection phase
|
||||
headersTimeout: 15_000, // wait for response headers
|
||||
bodyTimeout: 30_000 // wait between response body chunks
|
||||
}))
|
||||
|
||||
await fetch('https://example.com/data')
|
||||
```
|
||||
|
||||
You can inspect timeout error codes from `error.code` or (for wrapped fetch
|
||||
errors) from `error.cause?.code`.
|
||||
|
||||
## Class: `UndiciError`
|
||||
|
||||
<!-- YAML
|
||||
@@ -52,6 +83,35 @@ on a well-known symbol rather than the prototype chain.
|
||||
* `name` {string} Always `'UndiciError'`.
|
||||
* `code` {string} Always `'UND_ERR'`.
|
||||
|
||||
## Class: `WebAssemblyNotSupportedError`
|
||||
|
||||
* Extends: {Error}
|
||||
|
||||
WebAssembly is unavailable when Undici initializes its HTTP/1 parser. Undici does
|
||||
not provide an alternative parser for environments without WebAssembly, including
|
||||
Node.js configurations where `--jitless` disables it. The check is performed when
|
||||
the parser is needed, not when importing Undici or accessing `fetch`.
|
||||
|
||||
* `name` {string} Always `'Error'`.
|
||||
* `code` {string} Always `'ERR_WEBASSEMBLY_NOT_SUPPORTED'`.
|
||||
* `message` {string} By default `'WebAssembly is not supported in this environment, but is required for HTTP/1 parsing'`.
|
||||
|
||||
Client and dispatcher requests report this error directly. `fetch` rejects with
|
||||
a `TypeError` whose `cause` is this error:
|
||||
|
||||
```js
|
||||
try {
|
||||
await fetch('http://localhost:3000')
|
||||
} catch (error) {
|
||||
if (error.cause?.code === 'ERR_WEBASSEMBLY_NOT_SUPPORTED') {
|
||||
// HTTP/1 parsing requires WebAssembly in this environment.
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`Headers`, `FormData`, `Request`, `Response`, and other operations that do not need
|
||||
the HTTP/1 parser remain usable without WebAssembly.
|
||||
|
||||
## Class: `ConnectTimeoutError`
|
||||
|
||||
<!-- YAML
|
||||
@@ -436,6 +496,7 @@ The response returned an error status code. This is raised, for example, when th
|
||||
* `code` {string} Always `'UND_ERR_RESPONSE'`.
|
||||
* `statusCode` {number} The HTTP status code of the response.
|
||||
* `body` {Object|string|null} The response body.
|
||||
* `bodyTruncated` {boolean} Whether `body` was truncated by a configured limit.
|
||||
* `headers` {Object|string[]|null} The response headers.
|
||||
|
||||
### `new ResponseError(message, code, options)`
|
||||
@@ -445,6 +506,7 @@ The response returned an error status code. This is raised, for example, when th
|
||||
* `options` {Object}
|
||||
* `headers` {Object|string[]|null} The response headers. (optional)
|
||||
* `body` {Object|string|null} The response body. (optional)
|
||||
* `bodyTruncated` {boolean} Whether `body` was truncated. **Default:** `false`.
|
||||
|
||||
## Class: `ProxyConnectionError`
|
||||
|
||||
@@ -512,6 +574,19 @@ The maximum number of allowed origins has been reached.
|
||||
* `name` {string} Always `'MaxOriginsReachedError'`.
|
||||
* `code` {string} Always `'UND_ERR_MAX_ORIGINS_REACHED'`.
|
||||
|
||||
## Class: `MaxRedirectsError`
|
||||
|
||||
<!-- YAML
|
||||
added: v8.12.0
|
||||
-->
|
||||
|
||||
* Extends: {UndiciError}
|
||||
|
||||
The maximum number of redirects has been reached.
|
||||
|
||||
* `name` {string} Always `'MaxRedirectsError'`.
|
||||
* `code` {string} Always `'UND_ERR_REDIRECT_MAX'`.
|
||||
|
||||
## Class: `Socks5ProxyError`
|
||||
|
||||
<!-- YAML
|
||||
|
||||
+3
-2
@@ -55,8 +55,9 @@ added: v7.7.0
|
||||
hostname, and port. Only the `http:` protocol is supported.
|
||||
* `options` {H2CClientOptions} (optional)
|
||||
* `maxConcurrentStreams` {number} The maximum number of concurrent HTTP/2
|
||||
streams for the session. It is advertised to the server and may be overridden
|
||||
by a remote `SETTINGS` frame. Must be a positive integer. **Default:** `100`.
|
||||
streams for the session. The server's `SETTINGS_MAX_CONCURRENT_STREAMS` can
|
||||
lower this limit, but not raise it. Must be a positive integer.
|
||||
**Default:** `100`.
|
||||
* `pipelining` {number} The number of concurrent requests multiplexed over the
|
||||
single connection. For an `H2CClient` this is aliased to
|
||||
`maxConcurrentStreams` and may not exceed it. Must be a positive integer.
|
||||
|
||||
+13
-6
@@ -163,9 +163,10 @@ Follows HTTP redirects (3xx responses) automatically.
|
||||
* `maxRedirections` {number} Maximum number of redirects to follow. Passing
|
||||
`0` disables redirect following entirely. **Default:** `undefined`
|
||||
(inherits from the per-request `maxRedirections` option).
|
||||
* `throwOnMaxRedirect` {boolean} When `true`, throws an error once the
|
||||
redirect limit is reached instead of returning the final redirect response.
|
||||
**Default:** `false`.
|
||||
* `throwOnMaxRedirect` {boolean} When `true`, throws an error when a
|
||||
redirect would be followed but the redirect limit has been reached, instead
|
||||
of returning that redirect response. A non-redirect response after exactly
|
||||
`maxRedirections` redirects is returned normally. **Default:** `false`.
|
||||
* `stripHeadersOnRedirect` {string[]} List of header names to remove from
|
||||
the request when following any redirect. **Default:** `[]`.
|
||||
* `stripHeadersOnCrossOriginRedirect` {string[]} List of header names to
|
||||
@@ -198,7 +199,10 @@ const agent = new Agent().compose(
|
||||
## `interceptors.decompress([opts])`
|
||||
|
||||
Automatically decompresses response bodies encoded with `gzip`, `x-gzip`,
|
||||
`br` (Brotli), `deflate`, `compress`, `x-compress`, or `zstd`.
|
||||
`br` (Brotli), `deflate`, or `zstd`. Any other coding, including `compress`
|
||||
and `x-compress`, is left untouched, matching `fetch()`. As required by
|
||||
[RFC 9659](https://www.rfc-editor.org/rfc/rfc9659.html), a `zstd` frame that
|
||||
requires a window size larger than 8 MB fails to decode.
|
||||
|
||||
> **Experimental:** This interceptor is experimental and subject to change.
|
||||
> A one-time `ExperimentalWarning` is emitted on first use.
|
||||
@@ -244,8 +248,11 @@ The error body is automatically decoded for `application/json` and
|
||||
|
||||
**Parameters**
|
||||
|
||||
* `opts` {Object} (optional) — currently reserved for future use; may be
|
||||
omitted.
|
||||
* `opts` {Object} (optional)
|
||||
* `maxSize` {number} Maximum number of response body bytes to include in the
|
||||
error. If the body exceeds this limit, the resulting `ResponseError`
|
||||
contains the retained prefix with `bodyTruncated` set to `true`. Set to `0`
|
||||
to disable the limit. **Default:** `1048576` (1 MiB).
|
||||
|
||||
**Returns:** {Dispatcher.DispatcherComposeInterceptor}
|
||||
|
||||
|
||||
+12
-9
@@ -57,9 +57,10 @@ added: v4.0.0
|
||||
* `opts` {DispatchOptions} The dispatch options for the request. In addition to
|
||||
the standard dispatch options, the following redirect-specific fields are
|
||||
recognized:
|
||||
* `throwOnMaxRedirect` {boolean} When `true`, an error is thrown once
|
||||
`maxRedirections` is reached instead of returning the last redirect response.
|
||||
**Default:** `false`.
|
||||
* `throwOnMaxRedirect` {boolean} When `true`, an error is thrown when a
|
||||
redirect would be followed but `maxRedirections` has been reached, instead of
|
||||
returning that redirect response. A non-redirect response after exactly
|
||||
`maxRedirections` redirects is returned normally. **Default:** `false`.
|
||||
* `stripHeadersOnRedirect` {string[]} Header names to remove from the request on
|
||||
every redirect hop. **Default:** `null`.
|
||||
* `stripHeadersOnCrossOriginRedirect` {string[]} Additional header names to
|
||||
@@ -165,13 +166,15 @@ added: v7.0.0
|
||||
* `statusMessage` {string} The HTTP status message.
|
||||
|
||||
Inspects the response headers to decide whether to follow a redirect. When the
|
||||
status code is redirectable, the `maxRedirections` limit has not been reached, and
|
||||
the request body has not been consumed, the `location` property is set, the method
|
||||
and headers are adjusted for the next hop, and the response is not forwarded.
|
||||
Otherwise the event is forwarded to the wrapped `handler`.
|
||||
status code is redirectable, the response has a `Location` header, the
|
||||
`maxRedirections` limit has not been reached, and the request body has not been
|
||||
consumed, the `location` property is set, the method and headers are adjusted
|
||||
for the next hop, and the response is not forwarded. Otherwise the event is
|
||||
forwarded to the wrapped `handler`.
|
||||
|
||||
Throws when `throwOnMaxRedirect` is `true` and the number of recorded redirects
|
||||
has reached `maxRedirections`, and throws an [`InvalidArgumentError`][] if a
|
||||
Throws when `throwOnMaxRedirect` is `true` and a redirect that would otherwise be
|
||||
followed arrives after `maxRedirections` redirects have already been followed,
|
||||
and throws an [`InvalidArgumentError`][] if a
|
||||
redirect loop is detected (for example when a [`Client`][] or [`Pool`][] is used
|
||||
for a cross-origin redirect; use an [`Agent`][] instead).
|
||||
|
||||
|
||||
Vendored
+12
-12
@@ -13,7 +13,7 @@ It is also a Stranger Things reference.
|
||||
|
||||
Have a question about using Undici? Open a [Q&A Discussion](https://github.com/nodejs/undici/discussions/new) or join our official OpenJS [Slack](https://openjs-foundation.slack.com/archives/C01QF9Q31QD) channel.
|
||||
|
||||
Looking to contribute? Start by reading the [contributing guide](./CONTRIBUTING.md)
|
||||
Looking to contribute? Start by reading the [contributing guide](https://github.com/nodejs/undici/blob/main/CONTRIBUTING.md)
|
||||
|
||||
## Install
|
||||
|
||||
@@ -417,7 +417,7 @@ For more information about their behavior, please reference the body mixin from
|
||||
|
||||
## Common API Methods
|
||||
|
||||
This section documents our most commonly used API methods. Additional APIs are documented in their own files within the [docs](./docs/) folder and are accessible via the navigation list on the left side of the docs site.
|
||||
This section documents our most commonly used API methods. Additional APIs are documented in their own files within the [`api`](./api/) folder and are accessible via the navigation list on the left side of the docs site.
|
||||
|
||||
For the top-level APIs below, the `url` argument supplies the request origin and
|
||||
path. Do not pass `origin` or `path` in the second `options` argument. The linked
|
||||
@@ -427,19 +427,19 @@ lower-level APIs that do not receive a separate `url` argument.
|
||||
### `undici.request([url, options])`
|
||||
|
||||
* `url` {string|URL|UrlObject}
|
||||
* `options` {RequestOptions} See [`RequestOptions`](./docs/docs/api/Dispatcher.md#parameter-requestoptions).
|
||||
* `options` {RequestOptions} See [`RequestOptions`](./api/Dispatcher.md#parameter-requestoptions).
|
||||
* `dispatcher` {Dispatcher} **Default:** [getGlobalDispatcher](#undicigetglobaldispatcher).
|
||||
* `method` {string} **Default:** `PUT` if `options.body`, otherwise `GET`.
|
||||
* Returns: {Promise} A promise with the result of the `Dispatcher.request` method.
|
||||
|
||||
Calls `options.dispatcher.request(options)`.
|
||||
|
||||
See [Dispatcher.request](./docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback) for more details, and [request examples](./docs/examples/README.md) for examples.
|
||||
See [Dispatcher.request](./api/Dispatcher.md#dispatcherrequestoptions-callback) for more details, and [request examples](https://github.com/nodejs/undici/blob/main/docs/examples/README.md) for examples.
|
||||
|
||||
### `undici.stream([url, options, ]factory)`
|
||||
|
||||
* `url` {string|URL|UrlObject}
|
||||
* `options` {StreamOptions} See [`StreamOptions`](./docs/docs/api/Dispatcher.md#parameter-streamoptions).
|
||||
* `options` {StreamOptions} See [`StreamOptions`](./api/Dispatcher.md#parameter-streamoptions).
|
||||
* `dispatcher` {Dispatcher} **Default:** [getGlobalDispatcher](#undicigetglobaldispatcher).
|
||||
* `method` {string} **Default:** `PUT` if `options.body`, otherwise `GET`.
|
||||
* `factory` {Function} `Dispatcher.stream.factory`.
|
||||
@@ -447,12 +447,12 @@ See [Dispatcher.request](./docs/docs/api/Dispatcher.md#dispatcherrequestoptions-
|
||||
|
||||
Calls `options.dispatcher.stream(options, factory)`.
|
||||
|
||||
See [Dispatcher.stream](./docs/docs/api/Dispatcher.md#dispatcherstreamoptions-factory-callback) for more details.
|
||||
See [Dispatcher.stream](./api/Dispatcher.md#dispatcherstreamoptions-factory-callback) for more details.
|
||||
|
||||
### `undici.pipeline([url, options, ]handler)`
|
||||
|
||||
* `url` {string|URL|UrlObject}
|
||||
* `options` {PipelineOptions} See [`PipelineOptions`](./docs/docs/api/Dispatcher.md#parameter-pipelineoptions).
|
||||
* `options` {PipelineOptions} See [`PipelineOptions`](./api/Dispatcher.md#parameter-pipelineoptions).
|
||||
* `dispatcher` {Dispatcher} **Default:** [getGlobalDispatcher](#undicigetglobaldispatcher).
|
||||
* `method` {string} **Default:** `PUT` if `options.body`, otherwise `GET`.
|
||||
* `handler` {Function} `Dispatcher.pipeline.handler`.
|
||||
@@ -460,21 +460,21 @@ See [Dispatcher.stream](./docs/docs/api/Dispatcher.md#dispatcherstreamoptions-fa
|
||||
|
||||
Calls `options.dispatch.pipeline(options, handler)`.
|
||||
|
||||
See [Dispatcher.pipeline](./docs/docs/api/Dispatcher.md#dispatcherpipelineoptions-handler) for more details.
|
||||
See [Dispatcher.pipeline](./api/Dispatcher.md#dispatcherpipelineoptions-handler) for more details.
|
||||
|
||||
### `undici.connect([url, options])`
|
||||
|
||||
Starts two-way communications with the requested resource using [HTTP CONNECT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT).
|
||||
|
||||
* `url` {string|URL|UrlObject}
|
||||
* `options` {ConnectOptions} See [`ConnectOptions`](./docs/docs/api/Dispatcher.md#parameter-connectoptions).
|
||||
* `options` {ConnectOptions} See [`ConnectOptions`](./api/Dispatcher.md#parameter-connectoptions).
|
||||
* `dispatcher` {Dispatcher} **Default:** [getGlobalDispatcher](#undicigetglobaldispatcher).
|
||||
* `callback` {Function} (optional) — `(err, data) => void`.
|
||||
* Returns: {Promise} A promise with the result of the `Dispatcher.connect` method.
|
||||
|
||||
Calls `options.dispatch.connect(options)`.
|
||||
|
||||
See [Dispatcher.connect](./docs/docs/api/Dispatcher.md#dispatcherconnectoptions-callback) for more details.
|
||||
See [Dispatcher.connect](./api/Dispatcher.md#dispatcherconnectoptions-callback) for more details.
|
||||
|
||||
### `undici.fetch(input[, init])`
|
||||
|
||||
@@ -647,14 +647,14 @@ Undici limits the number of `Content-Encoding` layers in a response to **5** to
|
||||
Upgrade to a different protocol. See [MDN - HTTP - Protocol upgrade mechanism](https://developer.mozilla.org/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism) for more details.
|
||||
|
||||
* `url` {string|URL|UrlObject}
|
||||
* `options` {UpgradeOptions} See [`UpgradeOptions`](./docs/docs/api/Dispatcher.md#parameter-upgradeoptions).
|
||||
* `options` {UpgradeOptions} See [`UpgradeOptions`](./api/Dispatcher.md#parameter-upgradeoptions).
|
||||
* `dispatcher` {Dispatcher} **Default:** [getGlobalDispatcher](#undicigetglobaldispatcher).
|
||||
* `callback` {Function} (optional) — `(error, data) => void`.
|
||||
* Returns: {Promise} A promise with the result of the `Dispatcher.upgrade` method.
|
||||
|
||||
Calls `options.dispatcher.upgrade(options)`.
|
||||
|
||||
See [Dispatcher.upgrade](./docs/docs/api/Dispatcher.md#dispatcherupgradeoptions-callback) for more details.
|
||||
See [Dispatcher.upgrade](./api/Dispatcher.md#dispatcherupgradeoptions-callback) for more details.
|
||||
|
||||
### `undici.setGlobalDispatcher(dispatcher)`
|
||||
|
||||
|
||||
+66
-66
@@ -1,79 +1,79 @@
|
||||
{
|
||||
"AbortError": "/api/Errors.md#class-aborterror",
|
||||
"Agent": "/api/Agent.md#class-agent",
|
||||
"AgentDispatchOptions": "/api/Agent.md#agentdispatchoptions-handler",
|
||||
"AgentOptions": "/api/Agent.md#new-agentoptions",
|
||||
"BalancedPool": "/api/BalancedPool.md#class-balancedpool",
|
||||
"BalancedPoolOptions": "/api/BalancedPool.md#parameter-balancedpooloptions",
|
||||
"BodyMixin": "/api/Fetch.md#new-formdata",
|
||||
"AbortError": "/api/Errors.html#class-aborterror",
|
||||
"Agent": "/api/Agent.html#class-agent",
|
||||
"AgentDispatchOptions": "/api/Agent.html#agentdispatchoptions-handler",
|
||||
"AgentOptions": "/api/Agent.html#new-agentoptions",
|
||||
"BalancedPool": "/api/BalancedPool.html#class-balancedpool",
|
||||
"BalancedPoolOptions": "/api/BalancedPool.html#parameter-balancedpooloptions",
|
||||
"BodyMixin": "/api/Fetch.html#new-formdata",
|
||||
"Buffer": "https://nodejs.org/api/buffer.html#class-buffer",
|
||||
"BuildOptions": "/api/Connector.md#buildconnectoroptions",
|
||||
"CacheKey": "/api/CacheStore.md#cachekey",
|
||||
"CacheStore": "/api/CacheStore.md#new-memorycachestoreoptions",
|
||||
"CacheValue": "/api/CacheStore.md#cachevalue",
|
||||
"ClientDestroyedError": "/api/Errors.md#class-clientdestroyederror",
|
||||
"ClientOptions": "/api/Client.md#new-clienturl-options",
|
||||
"ClientStats": "/api/ClientStats.md#class-clientstats",
|
||||
"ConnectOptions": "/api/Dispatcher.md#class-dispatcher",
|
||||
"Cookie": "/api/Cookies.md#cookie",
|
||||
"DispatchController": "/api/Dispatcher.md#class-dispatcher",
|
||||
"DispatchHandler": "/api/Dispatcher.md#class-dispatcher",
|
||||
"DispatchOptions": "/api/Dispatcher.md#class-dispatcher",
|
||||
"Dispatcher": "/api/Dispatcher.md#class-dispatcher",
|
||||
"BuildOptions": "/api/Connector.html#buildconnectoroptions",
|
||||
"CacheKey": "/api/CacheStore.html#cachekey",
|
||||
"CacheStore": "/api/CacheStore.html#new-memorycachestoreoptions",
|
||||
"CacheValue": "/api/CacheStore.html#cachevalue",
|
||||
"ClientDestroyedError": "/api/Errors.html#class-clientdestroyederror",
|
||||
"ClientOptions": "/api/Client.html#new-clienturl-options",
|
||||
"ClientStats": "/api/ClientStats.html#class-clientstats",
|
||||
"ConnectOptions": "/api/Dispatcher.html#class-dispatcher",
|
||||
"Cookie": "/api/Cookies.html#cookie",
|
||||
"DispatchController": "/api/Dispatcher.html#class-dispatcher",
|
||||
"DispatchHandler": "/api/Dispatcher.html#class-dispatcher",
|
||||
"DispatchOptions": "/api/Dispatcher.html#class-dispatcher",
|
||||
"Dispatcher": "/api/Dispatcher.html#class-dispatcher",
|
||||
"Duplex": "https://nodejs.org/api/stream.html#class-streamduplex",
|
||||
"EnvHttpProxyAgent": "/api/EnvHttpProxyAgent.md#class-envhttpproxyagent",
|
||||
"EnvHttpProxyAgentOptions": "/api/EnvHttpProxyAgent.md#new-envhttpproxyagentoptions",
|
||||
"EnvHttpProxyAgent": "/api/EnvHttpProxyAgent.html#class-envhttpproxyagent",
|
||||
"EnvHttpProxyAgentOptions": "/api/EnvHttpProxyAgent.html#new-envhttpproxyagentoptions",
|
||||
"EventEmitter": "https://nodejs.org/api/events.html#class-eventemitter",
|
||||
"GetResult": "/api/CacheStore.md#getresult",
|
||||
"H2CClientOptions": "/api/H2CClient.md#new-h2cclienturl-options",
|
||||
"GetResult": "/api/CacheStore.html#getresult",
|
||||
"H2CClientOptions": "/api/H2CClient.html#new-h2cclienturl-options",
|
||||
"HeadersInit": "https://developer.mozilla.org/docs/Web/API/Headers/Headers",
|
||||
"InvalidArgumentError": "/api/Errors.md#class-invalidargumenterror",
|
||||
"InvalidArgumentError": "/api/Errors.html#class-invalidargumenterror",
|
||||
"Iterable": "https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols",
|
||||
"MaxOriginsReachedError": "/api/Errors.md#class-maxoriginsreachederror",
|
||||
"MockAgent": "/api/MockAgent.md#class-mockagent",
|
||||
"MockAgentOptions": "/api/MockAgent.md#parameter-mockagentoptions",
|
||||
"MockCallHistory": "/api/MockCallHistory.md#class-mockcallhistory",
|
||||
"MockCallHistoryLog": "/api/MockCallHistoryLog.md#class-mockcallhistorylog",
|
||||
"MockClient": "/api/MockClient.md#class-mockclient",
|
||||
"MockClientOptions": "/api/MockClient.md#parameter-mockclientoptions",
|
||||
"MockInterceptor": "/api/MockPool.md#return-mockinterceptor",
|
||||
"MockInterceptor.Options": "/api/MockPool.md#parameter-mockpoolinterceptoptions",
|
||||
"MockPool": "/api/MockPool.md#class-mockpool",
|
||||
"MockPoolInterceptOptions": "/api/MockPool.md#parameter-mockpoolinterceptoptions",
|
||||
"MockPoolOptions": "/api/MockPool.md#parameter-mockpooloptions",
|
||||
"MockResponseOptions": "/api/MockPool.md#parameter-mockresponseoptions",
|
||||
"MockScope": "/api/MockPool.md#return-mockscope",
|
||||
"PendingInterceptor": "/api/MockAgent.md#new-mockagentoptions",
|
||||
"PipelineOptions": "/api/Dispatcher.md#class-dispatcher",
|
||||
"Pool": "/api/Pool.md#class-pool",
|
||||
"PoolOptions": "/api/Pool.md#new-poolurl-options",
|
||||
"PoolStats": "/api/PoolStats.md#class-poolstats",
|
||||
"ProxyAgent": "/api/ProxyAgent.md#class-proxyagent",
|
||||
"ProxyAgentOptions": "/api/ProxyAgent.md#new-proxyagentoptions",
|
||||
"MaxOriginsReachedError": "/api/Errors.html#class-maxoriginsreachederror",
|
||||
"MockAgent": "/api/MockAgent.html#class-mockagent",
|
||||
"MockAgentOptions": "/api/MockAgent.html#parameter-mockagentoptions",
|
||||
"MockCallHistory": "/api/MockCallHistory.html#class-mockcallhistory",
|
||||
"MockCallHistoryLog": "/api/MockCallHistoryLog.html#class-mockcallhistorylog",
|
||||
"MockClient": "/api/MockClient.html#class-mockclient",
|
||||
"MockClientOptions": "/api/MockClient.html#parameter-mockclientoptions",
|
||||
"MockInterceptor": "/api/MockPool.html#return-mockinterceptor",
|
||||
"MockInterceptor.Options": "/api/MockPool.html#parameter-mockpoolinterceptoptions",
|
||||
"MockPool": "/api/MockPool.html#class-mockpool",
|
||||
"MockPoolInterceptOptions": "/api/MockPool.html#parameter-mockpoolinterceptoptions",
|
||||
"MockPoolOptions": "/api/MockPool.html#parameter-mockpooloptions",
|
||||
"MockResponseOptions": "/api/MockPool.html#parameter-mockresponseoptions",
|
||||
"MockScope": "/api/MockPool.html#return-mockscope",
|
||||
"PendingInterceptor": "/api/MockAgent.html#new-mockagentoptions",
|
||||
"PipelineOptions": "/api/Dispatcher.html#class-dispatcher",
|
||||
"Pool": "/api/Pool.html#class-pool",
|
||||
"PoolOptions": "/api/Pool.html#new-poolurl-options",
|
||||
"PoolStats": "/api/PoolStats.html#class-poolstats",
|
||||
"ProxyAgent": "/api/ProxyAgent.html#class-proxyagent",
|
||||
"ProxyAgentOptions": "/api/ProxyAgent.html#new-proxyagentoptions",
|
||||
"Readable": "https://nodejs.org/api/stream.html#class-streamreadable",
|
||||
"Record": "https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type",
|
||||
"RequestInit": "/api/Fetch.md#new-formdata",
|
||||
"RequestOptions": "/api/Dispatcher.md#class-dispatcher",
|
||||
"ResponseInit": "/api/Fetch.md#new-formdata",
|
||||
"RetryContext": "/api/RetryHandler.md#retrycontext",
|
||||
"RetryHandler": "/api/RetryHandler.md#class-retryhandler",
|
||||
"RetryHandlers": "/api/RetryHandler.md#parameter-retryhandlers",
|
||||
"RetryOptions": "/api/RetryHandler.md#retryoptions",
|
||||
"RetryState": "/api/RetryHandler.md#retrystate",
|
||||
"RoundRobinPoolOptions": "/api/RoundRobinPool.md#parameter-roundrobinpooloptions",
|
||||
"SnapshotRecorder": "/api/SnapshotAgent.md#new-snapshotagentoptions",
|
||||
"RequestInit": "/api/Fetch.html#new-formdata",
|
||||
"RequestOptions": "/api/Dispatcher.html#class-dispatcher",
|
||||
"ResponseInit": "/api/Fetch.html#new-formdata",
|
||||
"RetryContext": "/api/RetryHandler.html#retrycontext",
|
||||
"RetryHandler": "/api/RetryHandler.html#class-retryhandler",
|
||||
"RetryHandlers": "/api/RetryHandler.html#parameter-retryhandlers",
|
||||
"RetryOptions": "/api/RetryHandler.html#retryoptions",
|
||||
"RetryState": "/api/RetryHandler.html#retrystate",
|
||||
"RoundRobinPoolOptions": "/api/RoundRobinPool.html#parameter-roundrobinpooloptions",
|
||||
"SnapshotRecorder": "/api/SnapshotAgent.html#new-snapshotagentoptions",
|
||||
"Socket": "https://nodejs.org/api/net.html#class-netsocket",
|
||||
"SocketInfo": "/api/Errors.md#new-requestretryerrormessage-code-options",
|
||||
"StreamOptions": "/api/Dispatcher.md#class-dispatcher",
|
||||
"SocketInfo": "/api/Errors.html#new-requestretryerrormessage-code-options",
|
||||
"StreamOptions": "/api/Dispatcher.html#class-dispatcher",
|
||||
"TLSSocket": "https://nodejs.org/api/tls.html#class-tlstlssocket",
|
||||
"UndiciError": "/api/Errors.md#class-undicierror",
|
||||
"UndiciHeaders": "/api/Dispatcher.md#class-dispatcher",
|
||||
"UpgradeOptions": "/api/Dispatcher.md#class-dispatcher",
|
||||
"UrlObject": "/index.md#urlobject",
|
||||
"WebSocketInit": "/api/WebSocket.md#new-websocketurl-protocols",
|
||||
"WebSocketStreamOptions": "/api/WebSocket.md#new-websocketurl-protocols",
|
||||
"UndiciError": "/api/Errors.html#class-undicierror",
|
||||
"UndiciHeaders": "/api/Dispatcher.html#class-dispatcher",
|
||||
"UpgradeOptions": "/api/Dispatcher.html#class-dispatcher",
|
||||
"UrlObject": "/index.html#urlobject",
|
||||
"WebSocketInit": "/api/WebSocket.html#new-websocketurl-protocols",
|
||||
"WebSocketStreamOptions": "/api/WebSocket.html#new-websocketurl-protocols",
|
||||
"Writable": "https://nodejs.org/api/stream.html#class-streamwritable",
|
||||
"buildConnector.BuildOptions": "/api/Connector.md#buildconnectoroptions",
|
||||
"buildConnector.BuildOptions": "/api/Connector.html#buildconnectoroptions",
|
||||
"net.Socket": "https://nodejs.org/api/net.html#class-netsocket",
|
||||
"stream.Readable": "https://nodejs.org/api/stream.html#class-streamreadable"
|
||||
}
|
||||
}
|
||||
Vendored
+2
@@ -6,6 +6,8 @@ const { installedExports } = require('./lib/global')
|
||||
module.exports = [
|
||||
...neo({
|
||||
ignores: [
|
||||
'deps/milo',
|
||||
'lib/milo',
|
||||
'lib/llhttp',
|
||||
'test/fixtures/cache-tests',
|
||||
'undici-fetch.js',
|
||||
|
||||
+48
-13
@@ -100,6 +100,11 @@ class MemoryCacheStore extends EventEmitter {
|
||||
|
||||
const entry = entries ? findEntry(key, entries, now) : null
|
||||
|
||||
if (entry != null) {
|
||||
this.#entries.delete(topLevelKey)
|
||||
this.#entries.set(topLevelKey, entries)
|
||||
}
|
||||
|
||||
return entry == null
|
||||
? undefined
|
||||
: {
|
||||
@@ -148,11 +153,13 @@ class MemoryCacheStore extends EventEmitter {
|
||||
},
|
||||
final (callback) {
|
||||
let entries = store.#entries.get(topLevelKey)
|
||||
if (!entries) {
|
||||
if (entries) {
|
||||
store.#entries.delete(topLevelKey)
|
||||
} else {
|
||||
entries = []
|
||||
store.#entries.set(topLevelKey, entries)
|
||||
}
|
||||
const previousEntry = findEntry(key, entries, Date.now())
|
||||
store.#entries.set(topLevelKey, entries)
|
||||
const previousEntry = findEntry(key, entries, -Infinity)
|
||||
if (previousEntry) {
|
||||
const index = entries.indexOf(previousEntry)
|
||||
entries.splice(index, 1, entry)
|
||||
@@ -177,16 +184,7 @@ class MemoryCacheStore extends EventEmitter {
|
||||
store.#hasEmittedMaxSizeEvent = true
|
||||
}
|
||||
|
||||
// Perform eviction
|
||||
for (const [key, entries] of store.#entries) {
|
||||
for (const entry of entries.splice(0, Math.ceil(entries.length / 2))) {
|
||||
store.#size -= entry.size
|
||||
store.#count -= 1
|
||||
}
|
||||
if (entries.length === 0) {
|
||||
store.#entries.delete(key)
|
||||
}
|
||||
}
|
||||
store.#evict(entry)
|
||||
|
||||
// Reset the event flag after eviction
|
||||
if (store.#size < store.#maxSize && store.#count < store.#maxCount) {
|
||||
@@ -199,6 +197,43 @@ class MemoryCacheStore extends EventEmitter {
|
||||
})
|
||||
}
|
||||
|
||||
#evict (keep) {
|
||||
const targetSize = this.#maxSize / 2
|
||||
const targetCount = this.#maxCount / 2
|
||||
|
||||
for (const [key, entries] of this.#entries) {
|
||||
for (let i = 0; i < entries.length && (this.#size > targetSize || this.#count > targetCount);) {
|
||||
const entry = entries[i]
|
||||
if (entry === keep) {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
entries.splice(i, 1)
|
||||
this.#size -= entry.size
|
||||
this.#count -= 1
|
||||
}
|
||||
|
||||
if (entries.length === 0) {
|
||||
this.#entries.delete(key)
|
||||
}
|
||||
|
||||
if (this.#size <= targetSize && this.#count <= targetCount) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if (this.#size > this.#maxSize || this.#count > this.#maxCount) {
|
||||
const topLevelKey = `${keep.origin}:${keep.path}`
|
||||
const entries = this.#entries.get(topLevelKey)
|
||||
entries.splice(entries.indexOf(keep), 1)
|
||||
this.#size -= keep.size
|
||||
this.#count -= 1
|
||||
if (entries.length === 0) {
|
||||
this.#entries.delete(topLevelKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {CacheKey} key
|
||||
*/
|
||||
|
||||
+83
-5
@@ -2,14 +2,22 @@
|
||||
|
||||
const { Writable } = require('node:stream')
|
||||
const { assertCacheKey, assertCacheValue } = require('../util/cache.js')
|
||||
const { zstdCompressSync, zstdDecompressSync } = require('node:zlib')
|
||||
|
||||
let DatabaseSync
|
||||
|
||||
const VERSION = 3
|
||||
const VERSION = 4
|
||||
|
||||
// 2gb
|
||||
const MAX_ENTRY_SIZE = 2 * 1000 * 1000 * 1000
|
||||
|
||||
// 1MiB
|
||||
const COMPRESS_THRESHOLD = 1024 * 1024
|
||||
|
||||
// zstd support landed in Node 22.19.0/23.4.0, so it may be missing even when
|
||||
// node:sqlite is available.
|
||||
const hasZstd = typeof zstdCompressSync === 'function' && typeof zstdDecompressSync === 'function'
|
||||
|
||||
/**
|
||||
* @typedef {import('../../types/cache-interceptor.d.ts').default.CacheStore} CacheStore
|
||||
* @implements {CacheStore}
|
||||
@@ -17,6 +25,7 @@ const MAX_ENTRY_SIZE = 2 * 1000 * 1000 * 1000
|
||||
* @typedef {{
|
||||
* id: Readonly<number>,
|
||||
* body?: Uint8Array
|
||||
* compressed?: string
|
||||
* statusCode: number
|
||||
* statusMessage: string
|
||||
* headers?: string
|
||||
@@ -31,6 +40,7 @@ const MAX_ENTRY_SIZE = 2 * 1000 * 1000 * 1000
|
||||
module.exports = class SqliteCacheStore {
|
||||
#maxEntrySize = MAX_ENTRY_SIZE
|
||||
#maxCount = Infinity
|
||||
#compressThreshold = COMPRESS_THRESHOLD
|
||||
|
||||
/**
|
||||
* @type {import('node:sqlite').DatabaseSync}
|
||||
@@ -107,6 +117,17 @@ module.exports = class SqliteCacheStore {
|
||||
}
|
||||
this.#maxCount = opts.maxCount
|
||||
}
|
||||
|
||||
if (opts.compressThreshold !== undefined) {
|
||||
if (
|
||||
typeof opts.compressThreshold !== 'number' ||
|
||||
!Number.isInteger(opts.compressThreshold) ||
|
||||
opts.compressThreshold < 0
|
||||
) {
|
||||
throw new TypeError('SqliteCacheStore options.compressThreshold must be a non-negative integer')
|
||||
}
|
||||
this.#compressThreshold = opts.compressThreshold
|
||||
}
|
||||
}
|
||||
|
||||
if (!DatabaseSync) {
|
||||
@@ -128,6 +149,7 @@ module.exports = class SqliteCacheStore {
|
||||
|
||||
-- Data returned to the interceptor
|
||||
body BUF NULL,
|
||||
compressed TEXT NULL,
|
||||
deleteAt INTEGER NOT NULL,
|
||||
statusCode INTEGER NOT NULL,
|
||||
statusMessage TEXT NOT NULL,
|
||||
@@ -147,6 +169,7 @@ module.exports = class SqliteCacheStore {
|
||||
SELECT
|
||||
id,
|
||||
body,
|
||||
compressed,
|
||||
deleteAt,
|
||||
statusCode,
|
||||
statusMessage,
|
||||
@@ -167,6 +190,7 @@ module.exports = class SqliteCacheStore {
|
||||
this.#updateValueQuery = this.#db.prepare(`
|
||||
UPDATE cacheInterceptorV${VERSION} SET
|
||||
body = ?,
|
||||
compressed = ?,
|
||||
deleteAt = ?,
|
||||
statusCode = ?,
|
||||
statusMessage = ?,
|
||||
@@ -185,6 +209,7 @@ module.exports = class SqliteCacheStore {
|
||||
url,
|
||||
method,
|
||||
body,
|
||||
compressed,
|
||||
deleteAt,
|
||||
statusCode,
|
||||
statusMessage,
|
||||
@@ -194,7 +219,7 @@ module.exports = class SqliteCacheStore {
|
||||
vary,
|
||||
cachedAt,
|
||||
staleAt
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`)
|
||||
|
||||
this.#deleteByUrlQuery = this.#db.prepare(
|
||||
@@ -237,7 +262,11 @@ module.exports = class SqliteCacheStore {
|
||||
const value = this.#findValue(key)
|
||||
return value
|
||||
? {
|
||||
body: value.body ? Buffer.from(value.body.buffer, value.body.byteOffset, value.body.byteLength) : undefined,
|
||||
body: value.body
|
||||
? value.compressed === 'zstd'
|
||||
? zstdDecompressSync(Buffer.from(value.body.buffer, value.body.byteOffset, value.body.byteLength))
|
||||
: Buffer.from(value.body.buffer, value.body.byteOffset, value.body.byteLength)
|
||||
: undefined,
|
||||
statusCode: value.statusCode,
|
||||
statusMessage: value.statusMessage,
|
||||
headers: value.headers ? JSON.parse(value.headers) : undefined,
|
||||
@@ -268,11 +297,22 @@ module.exports = class SqliteCacheStore {
|
||||
return
|
||||
}
|
||||
|
||||
let compressed = null
|
||||
let storedBody = body
|
||||
if (body && hasZstd && (size > this.#compressThreshold || isCompressibleContentType(getContentType(value.headers)))) {
|
||||
const candidate = zstdCompressSync(body)
|
||||
if (candidate.byteLength < body.byteLength) {
|
||||
storedBody = candidate
|
||||
compressed = 'zstd'
|
||||
}
|
||||
}
|
||||
|
||||
const existingValue = this.#findValue(key, true)
|
||||
if (existingValue) {
|
||||
// Updating an existing response, let's overwrite it
|
||||
this.#updateValueQuery.run(
|
||||
body,
|
||||
storedBody,
|
||||
compressed,
|
||||
value.deleteAt,
|
||||
value.statusCode,
|
||||
value.statusMessage,
|
||||
@@ -289,7 +329,8 @@ module.exports = class SqliteCacheStore {
|
||||
this.#insertValueQuery.run(
|
||||
url,
|
||||
key.method,
|
||||
body,
|
||||
storedBody,
|
||||
compressed,
|
||||
value.deleteAt,
|
||||
value.statusCode,
|
||||
value.statusMessage,
|
||||
@@ -467,3 +508,40 @@ function headerValueEquals (lhs, rhs) {
|
||||
|
||||
return lhs === rhs
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Record<string, string|string[]>|null|undefined} headers
|
||||
* @returns {string|undefined}
|
||||
*/
|
||||
function getContentType (headers) {
|
||||
if (headers == null) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
for (const key in headers) {
|
||||
if (key.toLowerCase() === 'content-type') {
|
||||
const value = headers[key]
|
||||
return Array.isArray(value) ? value[0] : value
|
||||
}
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string|undefined} contentType
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isCompressibleContentType (contentType) {
|
||||
if (contentType == null) {
|
||||
return false
|
||||
}
|
||||
|
||||
const type = contentType.toLowerCase()
|
||||
|
||||
// text/* and application/json, xml, javascript, ... are easily compressible
|
||||
// even at smaller sizes, so ignore the compressThreshold for them.
|
||||
return /^text\//.test(type) ||
|
||||
/^application\/(json|xml|javascript|x-www-form-urlencoded|graphql)(\s|;|$)/.test(type) ||
|
||||
/\+(json|xml)(\s|;|$)/.test(type)
|
||||
}
|
||||
Vendored
+10
-4
@@ -41,16 +41,22 @@ const SessionCache = class WeakSessionCache {
|
||||
if (this._sessionCache.has(sessionKey)) {
|
||||
this._sessionCache.delete(sessionKey)
|
||||
} else if (this._sessionCache.size >= this._maxCachedSessions) {
|
||||
// Make room for the new session: prefer an entry whose session has
|
||||
// already been collected, otherwise evict the oldest one.
|
||||
let evicted = false
|
||||
for (const [key, ref] of this._sessionCache) {
|
||||
if (ref.deref() === undefined) {
|
||||
this._sessionCache.delete(key)
|
||||
return
|
||||
evicted = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
const oldest = this._sessionCache.keys().next()
|
||||
if (!oldest.done) {
|
||||
this._sessionCache.delete(oldest.value)
|
||||
if (!evicted) {
|
||||
const oldest = this._sessionCache.keys().next()
|
||||
if (!oldest.done) {
|
||||
this._sessionCache.delete(oldest.value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+12
-1
@@ -114,7 +114,18 @@ for (let i = 0; i < wellknownHeaderNames.length; ++i) {
|
||||
lowerCasedKey
|
||||
}
|
||||
|
||||
/**
|
||||
* Default WebSocket receive limits (see `webSocket` in Client.md). Used by
|
||||
* DispatcherBase#webSocketOptions and by the WebSocket parser when the
|
||||
* dispatcher doesn't provide a value, so a dispatcher without
|
||||
* `webSocketOptions` (a custom one, or a wrapper) doesn't remove the limits.
|
||||
*/
|
||||
const defaultWebSocketMaxFragments = 131072
|
||||
const defaultWebSocketMaxPayloadSize = 128 * 1024 * 1024 // 128 MB
|
||||
|
||||
module.exports = {
|
||||
wellknownHeaderNames,
|
||||
headerNameLowerCasedRecord
|
||||
headerNameLowerCasedRecord,
|
||||
defaultWebSocketMaxFragments,
|
||||
defaultWebSocketMaxPayloadSize
|
||||
}
|
||||
Vendored
+38
-1
@@ -306,6 +306,22 @@ class BalancedPoolMissingUpstreamError extends UndiciError {
|
||||
}
|
||||
}
|
||||
|
||||
const kWebAssemblyNotSupportedError = Symbol.for('undici.error.ERR_WEBASSEMBLY_NOT_SUPPORTED')
|
||||
class WebAssemblyNotSupportedError extends Error {
|
||||
constructor (message) {
|
||||
super(message || 'WebAssembly is not supported in this environment, but is required for HTTP/1 parsing')
|
||||
this.code = 'ERR_WEBASSEMBLY_NOT_SUPPORTED'
|
||||
}
|
||||
|
||||
static [Symbol.hasInstance] (instance) {
|
||||
return instance && instance[kWebAssemblyNotSupportedError] === true
|
||||
}
|
||||
|
||||
get [kWebAssemblyNotSupportedError] () {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
const kHTTPParserError = Symbol.for('undici.error.UND_ERR_HTTP_PARSER')
|
||||
class HTTPParserError extends Error {
|
||||
constructor (message, code, data) {
|
||||
@@ -365,13 +381,14 @@ class RequestRetryError extends UndiciError {
|
||||
|
||||
const kResponseError = Symbol.for('undici.error.UND_ERR_RESPONSE')
|
||||
class ResponseError extends UndiciError {
|
||||
constructor (message, code, { headers, body }) {
|
||||
constructor (message, code, { headers, body, bodyTruncated = false }) {
|
||||
super(message)
|
||||
this.name = 'ResponseError'
|
||||
this.message = message || 'Response error'
|
||||
this.code = 'UND_ERR_RESPONSE'
|
||||
this.statusCode = code
|
||||
this.body = body
|
||||
this.bodyTruncated = bodyTruncated
|
||||
this.headers = headers
|
||||
}
|
||||
|
||||
@@ -422,6 +439,24 @@ class ProxyConnectionError extends UndiciError {
|
||||
}
|
||||
}
|
||||
|
||||
const kMaxRedirectsError = Symbol.for('undici.error.UND_ERR_REDIRECT_MAX')
|
||||
class MaxRedirectsError extends UndiciError {
|
||||
constructor (message) {
|
||||
super(message)
|
||||
this.name = 'MaxRedirectsError'
|
||||
this.message = message || 'max redirects'
|
||||
this.code = 'UND_ERR_REDIRECT_MAX'
|
||||
}
|
||||
|
||||
static [Symbol.hasInstance] (instance) {
|
||||
return instance && instance[kMaxRedirectsError] === true
|
||||
}
|
||||
|
||||
get [kMaxRedirectsError] () {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
const kMaxOriginsReachedError = Symbol.for('undici.error.UND_ERR_MAX_ORIGINS_REACHED')
|
||||
class MaxOriginsReachedError extends UndiciError {
|
||||
constructor (message) {
|
||||
@@ -469,6 +504,7 @@ class MessageSizeExceededError extends UndiciError {
|
||||
|
||||
module.exports = {
|
||||
AbortError,
|
||||
WebAssemblyNotSupportedError,
|
||||
HTTPParserError,
|
||||
UndiciError,
|
||||
HeadersTimeoutError,
|
||||
@@ -492,6 +528,7 @@ module.exports = {
|
||||
SecureProxyConnectionError,
|
||||
ProxyConnectionError,
|
||||
MaxOriginsReachedError,
|
||||
MaxRedirectsError,
|
||||
Socks5ProxyError,
|
||||
MessageSizeExceededError
|
||||
}
|
||||
Vendored
+16
-1
@@ -206,7 +206,12 @@ class Request {
|
||||
this.body = body.byteLength ? Buffer.from(body) : null
|
||||
} else if (typeof body === 'string') {
|
||||
this.body = body.length ? Buffer.from(body) : null
|
||||
} else if (isFormDataLike(body) || isIterable(body) || isBlobLike(body)) {
|
||||
} else if (isFormDataLike(body)) {
|
||||
if (!isUndiciFormData(body)) {
|
||||
throw new InvalidArgumentError('body must be a FormData created by this undici package instance; FormData from other sources, such as the built-in FormData provided by Node.js, is not supported')
|
||||
}
|
||||
this.body = body
|
||||
} else if (isIterable(body) || isBlobLike(body)) {
|
||||
this.body = body
|
||||
} else {
|
||||
throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable')
|
||||
@@ -564,4 +569,14 @@ function processHeader (request, key, val) {
|
||||
}
|
||||
}
|
||||
|
||||
let isFormData
|
||||
|
||||
function isUndiciFormData (body) {
|
||||
if (isFormData === undefined) {
|
||||
require('../web/fetch/formdata')
|
||||
isFormData = require('../web/webidl').webidl.is.FormData
|
||||
}
|
||||
return isFormData(body)
|
||||
}
|
||||
|
||||
module.exports = Request
|
||||
Vendored
+2
@@ -6,6 +6,7 @@ module.exports = {
|
||||
kDispatch: Symbol('dispatch'),
|
||||
kUrl: Symbol('url'),
|
||||
kRequestOrigin: Symbol('request origin'),
|
||||
kRedirectCacheControl: Symbol('redirect cache control'),
|
||||
kOriginless: Symbol('originless'),
|
||||
kWriting: Symbol('writing'),
|
||||
kResuming: Symbol('resuming'),
|
||||
@@ -72,6 +73,7 @@ module.exports = {
|
||||
kRemoteSettings: Symbol('http2session remote settings'),
|
||||
kHTTP2Stream: Symbol('http2session client stream'),
|
||||
kPingInterval: Symbol('ping interval'),
|
||||
kUseMilo: Symbol('use milo'),
|
||||
kNoProxyAgent: Symbol('no proxy agent'),
|
||||
kHttpProxyAgent: Symbol('http proxy agent'),
|
||||
kHttpsProxyAgent: Symbol('https proxy agent'),
|
||||
|
||||
Vendored
+26
-1
@@ -387,7 +387,7 @@ function destroy (stream, err) {
|
||||
}
|
||||
}
|
||||
|
||||
const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/
|
||||
const KEEPALIVE_TIMEOUT_EXPR = /(?:^|,)[\t ]*timeout=(\d+)/i
|
||||
/**
|
||||
* @param {string} val
|
||||
* @returns {number | null}
|
||||
@@ -417,6 +417,30 @@ function bufferToLowerCasedHeaderName (value) {
|
||||
return tree.lookup(value) ?? value.toString('latin1').toLowerCase()
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a header onto a plain object without going through the
|
||||
* `Object.prototype` `__proto__` setter. Plain assignment there drops a string
|
||||
* value and, when the value is an array, replaces the object's prototype
|
||||
* instead of storing anything. Every other name is a normal assignment.
|
||||
*
|
||||
* @param {Record<string, string | string[]>} obj Accumulator to write onto
|
||||
* @param {string} key Header name
|
||||
* @param {string | string[]} value Header value
|
||||
* @returns {void}
|
||||
*/
|
||||
function setHeader (obj, key, value) {
|
||||
if (key === '__proto__') {
|
||||
Object.defineProperty(obj, key, {
|
||||
value,
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true
|
||||
})
|
||||
} else {
|
||||
obj[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {(Buffer | string)[]} headers
|
||||
* @param {Record<string, string | string[]>} [obj]
|
||||
@@ -984,6 +1008,7 @@ module.exports = {
|
||||
toRawHeaders,
|
||||
encodeRawHeaders,
|
||||
parseHeaders,
|
||||
setHeader,
|
||||
parseKeepAliveTimeout,
|
||||
destroy,
|
||||
bodyLength,
|
||||
|
||||
+6
-2
@@ -22,7 +22,7 @@ function defaultFactory (origin, opts) {
|
||||
}
|
||||
|
||||
class Agent extends DispatcherBase {
|
||||
constructor ({ factory = defaultFactory, maxOrigins = Infinity, connect, ...options } = {}) {
|
||||
constructor ({ factory = defaultFactory, maxOrigins = Infinity, connect, tls, ...options } = {}) {
|
||||
if (typeof factory !== 'function') {
|
||||
throw new InvalidArgumentError('factory must be a function.')
|
||||
}
|
||||
@@ -41,7 +41,11 @@ class Agent extends DispatcherBase {
|
||||
connect = { ...connect }
|
||||
}
|
||||
|
||||
this[kOptions] = { ...util.deepClone(options), maxOrigins, connect }
|
||||
if (tls && typeof tls !== 'function') {
|
||||
tls = { ...tls }
|
||||
}
|
||||
|
||||
this[kOptions] = { ...util.deepClone(options), maxOrigins, connect, tls }
|
||||
this[kFactory] = factory
|
||||
this[kClients] = new Map()
|
||||
this[kOrigins] = new Set()
|
||||
|
||||
+116
-80
@@ -17,6 +17,7 @@ const {
|
||||
InformationalError,
|
||||
BodyTimeoutError,
|
||||
HTTPParserError,
|
||||
WebAssemblyNotSupportedError,
|
||||
ResponseExceededMaxSizeError
|
||||
} = require('../core/errors.js')
|
||||
const {
|
||||
@@ -51,10 +52,15 @@ const {
|
||||
kOnError,
|
||||
kResume,
|
||||
kHTTPContext,
|
||||
kClosed
|
||||
kClosed,
|
||||
kUseMilo
|
||||
} = require('../core/symbols.js')
|
||||
|
||||
const constants = require('../llhttp/constants.js')
|
||||
// Node.js core bundles only llhttp; experimental Milo remains available in npm builds.
|
||||
const { H1Parser, getMiloEnabled } = typeof esbuildDetection === 'undefined'
|
||||
? require('./parser-h1.js')
|
||||
: {}
|
||||
const EMPTY_BUF = Buffer.alloc(0)
|
||||
const FastBuffer = Buffer[Symbol.species]
|
||||
const removeAllListeners = util.removeAllListeners
|
||||
@@ -66,6 +72,11 @@ const kTypeOfService = Symbol('kTypeOfService')
|
||||
let extractBody
|
||||
|
||||
function lazyllhttp () {
|
||||
// Check only when HTTP/1 needs the parser, so other APIs remain usable without WASM.
|
||||
if (typeof WebAssembly === 'undefined') {
|
||||
throw new WebAssemblyNotSupportedError()
|
||||
}
|
||||
|
||||
const llhttpWasmData = process.env.JEST_WORKER_ID ? require('../llhttp/llhttp-wasm.js') : undefined
|
||||
|
||||
let mod
|
||||
@@ -88,8 +99,7 @@ function lazyllhttp () {
|
||||
if (useWasmSIMD) {
|
||||
try {
|
||||
mod = new WebAssembly.Module(require('../llhttp/llhttp_simd-wasm.js'))
|
||||
} catch {
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
if (!mod) {
|
||||
@@ -126,7 +136,7 @@ function lazyllhttp () {
|
||||
* @param {number} p
|
||||
* @returns {number}
|
||||
*/
|
||||
wasm_on_message_begin: (p) => {
|
||||
wasm_on_message_begin: p => {
|
||||
assert(currentParser.ptr === p)
|
||||
return currentParser.onMessageBegin()
|
||||
},
|
||||
@@ -178,11 +188,10 @@ function lazyllhttp () {
|
||||
* @param {number} p
|
||||
* @returns {number}
|
||||
*/
|
||||
wasm_on_message_complete: (p) => {
|
||||
wasm_on_message_complete: p => {
|
||||
assert(currentParser.ptr === p)
|
||||
return currentParser.onMessageComplete()
|
||||
}
|
||||
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -215,10 +224,10 @@ const TIMEOUT_KEEP_ALIVE = 8 | USE_NATIVE_TIMER
|
||||
|
||||
class Parser {
|
||||
/**
|
||||
* @param {import('./client.js')} client
|
||||
* @param {import('net').Socket} socket
|
||||
* @param {*} llhttp
|
||||
*/
|
||||
* @param {import('./client.js')} client
|
||||
* @param {import('net').Socket} socket
|
||||
* @param {*} llhttp
|
||||
*/
|
||||
constructor (client, socket, { exports }) {
|
||||
this.llhttp = exports
|
||||
this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE)
|
||||
@@ -245,7 +254,8 @@ class Parser {
|
||||
|
||||
this.keepAlive = ''
|
||||
this.contentLength = -1
|
||||
this.connectionKeepAlive = false
|
||||
this.hasTransferEncoding = false
|
||||
this.connection = ''
|
||||
this.maxResponseSize = client[kMaxResponseSize]
|
||||
}
|
||||
|
||||
@@ -253,10 +263,7 @@ class Parser {
|
||||
// If the existing timer and the new timer are of different timer type
|
||||
// (fast or native) or have different delay, we need to clear the existing
|
||||
// timer and set a new one.
|
||||
if (
|
||||
delay !== this.timeoutValue ||
|
||||
(type & USE_FAST_TIMER) ^ (this.timeoutType & USE_FAST_TIMER)
|
||||
) {
|
||||
if (delay !== this.timeoutValue || (type & USE_FAST_TIMER) ^ (this.timeoutType & USE_FAST_TIMER)) {
|
||||
// If a timeout is already set, clear it with clearTimeout of the fast
|
||||
// timer implementation, as it can clear fast and native timers.
|
||||
if (this.timeout) {
|
||||
@@ -441,9 +448,7 @@ class Parser {
|
||||
if (ptr) {
|
||||
const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0)
|
||||
message =
|
||||
'Response does not match the HTTP/1.1 protocol (' +
|
||||
Buffer.from(llhttp.memory.buffer, ptr, len).toString() +
|
||||
')'
|
||||
'Response does not match the HTTP/1.1 protocol (' + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ')'
|
||||
}
|
||||
|
||||
return new HTTPParserError(message, constants.ERROR[ret], data)
|
||||
@@ -521,6 +526,7 @@ class Parser {
|
||||
*/
|
||||
onHeaderValue (buf) {
|
||||
let len = this.headers.length
|
||||
const isContinuation = (len & 1) === 0
|
||||
|
||||
if ((len & 1) === 1) {
|
||||
this.headers.push(buf)
|
||||
@@ -533,19 +539,19 @@ class Parser {
|
||||
if (key.length === 10) {
|
||||
const headerName = util.bufferToLowerCasedHeaderName(key)
|
||||
if (headerName === 'keep-alive') {
|
||||
this.keepAlive += buf.toString()
|
||||
this.keepAlive += (isContinuation || this.keepAlive.length === 0 ? '' : ',') + buf.toString()
|
||||
} else if (headerName === 'connection') {
|
||||
this.connectionKeepAlive =
|
||||
this.headers[len - 1].length === 10 &&
|
||||
util.bufferToLowerCasedHeaderName(this.headers[len - 1]) === 'keep-alive'
|
||||
this.connection += (isContinuation || this.connection.length === 0 ? '' : ',') + buf.toString()
|
||||
}
|
||||
} else if (key.length === 14 && util.bufferToLowerCasedHeaderName(key) === 'content-length') {
|
||||
if (this.contentLength === -1) {
|
||||
this.contentLength = 0
|
||||
}
|
||||
for (let i = 0; i < buf.length; i++) {
|
||||
this.contentLength = (this.contentLength * 10) + (buf[i] - 0x30)
|
||||
this.contentLength = this.contentLength * 10 + (buf[i] - 0x30)
|
||||
}
|
||||
} else if (key.length === 17 && util.bufferToLowerCasedHeaderName(key) === 'transfer-encoding') {
|
||||
this.hasTransferEncoding = true
|
||||
}
|
||||
|
||||
this.trackHeader(buf.length)
|
||||
@@ -652,16 +658,27 @@ class Parser {
|
||||
assert(this.timeoutType === TIMEOUT_HEADERS)
|
||||
|
||||
this.statusCode = statusCode
|
||||
this.shouldKeepAlive = (
|
||||
this.shouldKeepAlive =
|
||||
shouldKeepAlive ||
|
||||
// Override llhttp value which does not allow keepAlive for HEAD.
|
||||
(request.method === 'HEAD' && !socket[kReset] && this.connectionKeepAlive)
|
||||
)
|
||||
(request.method === 'HEAD' && !socket[kReset] &&
|
||||
/(?:^|,)[\t ]*keep-alive[\t ]*(?:,|$)/i.test(this.connection) &&
|
||||
!/(?:^|,)[\t ]*close[\t ]*(?:,|$)/i.test(this.connection))
|
||||
|
||||
// Responses to HEAD and 204/304 responses never carry content
|
||||
if (request.method === 'HEAD' || statusCode === 204 || statusCode === 304) {
|
||||
// A non-zero Content-Length or Transfer-Encoding on a 204/304 means the
|
||||
// server may also have sent content inappropriately, which would then be
|
||||
// parsed as the next response on this connection. Accept it, but do not
|
||||
// reuse the connection. HEAD requests are fine tho.
|
||||
if (request.method !== 'HEAD' && (this.contentLength > 0 || this.hasTransferEncoding)) {
|
||||
this.shouldKeepAlive = false
|
||||
}
|
||||
this.contentLength = -1
|
||||
}
|
||||
|
||||
if (this.statusCode >= 200) {
|
||||
const bodyTimeout = request.bodyTimeout != null
|
||||
? request.bodyTimeout
|
||||
: client[kBodyTimeout]
|
||||
const bodyTimeout = request.bodyTimeout != null ? request.bodyTimeout : client[kBodyTimeout]
|
||||
this.setTimeout(bodyTimeout, TIMEOUT_BODY)
|
||||
} else if (this.timeout) {
|
||||
if (this.timeout.refresh) {
|
||||
@@ -689,10 +706,7 @@ class Parser {
|
||||
const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null
|
||||
|
||||
if (keepAliveTimeout != null) {
|
||||
const timeout = Math.min(
|
||||
keepAliveTimeout - client[kKeepAliveTimeoutThreshold],
|
||||
client[kKeepAliveMaxTimeout]
|
||||
)
|
||||
const timeout = Math.min(keepAliveTimeout - client[kKeepAliveTimeoutThreshold], client[kKeepAliveMaxTimeout])
|
||||
if (timeout <= 0) {
|
||||
socket[kReset] = true
|
||||
} else {
|
||||
@@ -789,8 +803,9 @@ class Parser {
|
||||
this.statusText = ''
|
||||
this.bytesRead = 0
|
||||
this.contentLength = -1
|
||||
this.hasTransferEncoding = false
|
||||
this.keepAlive = ''
|
||||
this.connectionKeepAlive = false
|
||||
this.connection = ''
|
||||
|
||||
this.headers = []
|
||||
this.headersSize = 0
|
||||
@@ -799,7 +814,7 @@ class Parser {
|
||||
return 0
|
||||
}
|
||||
|
||||
if (request.method !== 'HEAD' && contentLength !== -1 && bytesRead !== contentLength) {
|
||||
if (contentLength !== -1 && bytesRead !== contentLength) {
|
||||
util.destroy(socket, new ResponseContentLengthMismatchError())
|
||||
return -1
|
||||
}
|
||||
@@ -887,7 +902,9 @@ function connectH1 (client, socket) {
|
||||
socket[kIdleSocketValidation] = 0
|
||||
socket[kIdleSocketValidationTimeout] = null
|
||||
socket[kSocketUsed] = false
|
||||
socket[kParser] = new Parser(client, socket, llhttpInstance)
|
||||
socket[kParser] = typeof esbuildDetection === 'undefined' && (client[kUseMilo] ?? getMiloEnabled())
|
||||
? new H1Parser(client, socket)
|
||||
: new Parser(client, socket, llhttpInstance)
|
||||
|
||||
util.addListener(socket, 'error', onHttpSocketError)
|
||||
util.addListener(socket, 'readable', onHttpSocketReadable)
|
||||
@@ -948,8 +965,11 @@ function connectH1 (client, socket) {
|
||||
return true
|
||||
}
|
||||
|
||||
if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 &&
|
||||
(util.isStream(request.body) || util.isAsyncIterable(request.body) || util.isFormDataLike(request.body))) {
|
||||
if (
|
||||
client[kRunning] > 0 &&
|
||||
util.bodyLength(request.body) !== 0 &&
|
||||
(util.isStream(request.body) || util.isAsyncIterable(request.body) || util.isFormDataLike(request.body))
|
||||
) {
|
||||
// Request with stream or iterator body can error while other requests
|
||||
// are inflight and indirectly error those as well.
|
||||
// Ensure this doesn't happen by waiting for inflight
|
||||
@@ -968,8 +988,6 @@ function connectH1 (client, socket) {
|
||||
}
|
||||
|
||||
function onHttpSocketError (err) {
|
||||
assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
|
||||
|
||||
const parser = this[kParser]
|
||||
|
||||
// On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded
|
||||
@@ -1137,9 +1155,7 @@ function resumeH1 (client) {
|
||||
} else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {
|
||||
if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) {
|
||||
const request = client[kQueue][client[kRunningIdx]]
|
||||
const headersTimeout = request.headersTimeout != null
|
||||
? request.headersTimeout
|
||||
: client[kHeadersTimeout]
|
||||
const headersTimeout = request.headersTimeout != null ? request.headersTimeout : client[kHeadersTimeout]
|
||||
socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS)
|
||||
}
|
||||
}
|
||||
@@ -1196,14 +1212,13 @@ function writeH1 (client, request) {
|
||||
// servers and corrupt connection state. Do not
|
||||
// re-use the connection for further requests.
|
||||
|
||||
const expectsPayload = (
|
||||
const expectsPayload =
|
||||
method === 'PUT' ||
|
||||
method === 'POST' ||
|
||||
method === 'PATCH' ||
|
||||
method === 'QUERY' ||
|
||||
method === 'PROPFIND' ||
|
||||
method === 'PROPPATCH'
|
||||
)
|
||||
|
||||
if (util.isFormDataLike(body)) {
|
||||
if (!extractBody) {
|
||||
@@ -1252,7 +1267,12 @@ function writeH1 (client, request) {
|
||||
|
||||
// https://github.com/nodejs/undici/issues/2046
|
||||
// A user agent may send a Content-Length header with 0 value, this should be allowed.
|
||||
if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) {
|
||||
if (
|
||||
shouldSendContentLength(method) &&
|
||||
contentLength > 0 &&
|
||||
request.contentLength !== null &&
|
||||
request.contentLength !== contentLength
|
||||
) {
|
||||
if (client[kStrictContentLength]) {
|
||||
util.errorRequest(client, request, new RequestContentLengthMismatchError())
|
||||
return false
|
||||
@@ -1268,7 +1288,7 @@ function writeH1 (client, request) {
|
||||
* @param {Error} [err]
|
||||
* @returns {void}
|
||||
*/
|
||||
const abort = (err) => {
|
||||
const abort = err => {
|
||||
if (request.aborted || request.completed) {
|
||||
return
|
||||
}
|
||||
@@ -1453,14 +1473,9 @@ function writeStream (abort, body, client, request, socket, contentLength, heade
|
||||
|
||||
assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1))
|
||||
|
||||
socket
|
||||
.off('drain', onDrain)
|
||||
.off('error', onFinished)
|
||||
socket.off('drain', onDrain).off('error', onFinished)
|
||||
|
||||
body
|
||||
.removeListener('data', onData)
|
||||
.removeListener('end', onFinished)
|
||||
.removeListener('close', onClose)
|
||||
body.removeListener('data', onData).removeListener('end', onFinished).removeListener('close', onClose)
|
||||
|
||||
if (!err) {
|
||||
try {
|
||||
@@ -1479,19 +1494,13 @@ function writeStream (abort, body, client, request, socket, contentLength, heade
|
||||
}
|
||||
}
|
||||
|
||||
body
|
||||
.on('data', onData)
|
||||
.on('end', onFinished)
|
||||
.on('error', onFinished)
|
||||
.on('close', onClose)
|
||||
body.on('data', onData).on('end', onFinished).on('error', onFinished).on('close', onClose)
|
||||
|
||||
if (body.resume) {
|
||||
body.resume()
|
||||
}
|
||||
|
||||
socket
|
||||
.on('drain', onDrain)
|
||||
.on('error', onFinished)
|
||||
socket.on('drain', onDrain).on('error', onFinished)
|
||||
|
||||
if (body.errorEmitted ?? body.errored) {
|
||||
setImmediate(onFinished, body.errored)
|
||||
@@ -1612,19 +1621,18 @@ async function writeIterable (abort, body, client, request, socket, contentLengt
|
||||
}
|
||||
}
|
||||
|
||||
const waitForDrain = () => new Promise((resolve, reject) => {
|
||||
assert(callback === null)
|
||||
const waitForDrain = () =>
|
||||
new Promise((resolve, reject) => {
|
||||
assert(callback === null)
|
||||
|
||||
if (socket[kError]) {
|
||||
reject(socket[kError])
|
||||
} else {
|
||||
callback = resolve
|
||||
}
|
||||
})
|
||||
if (socket[kError]) {
|
||||
reject(socket[kError])
|
||||
} else {
|
||||
callback = resolve
|
||||
}
|
||||
})
|
||||
|
||||
socket
|
||||
.on('close', onDrain)
|
||||
.on('drain', onDrain)
|
||||
socket.on('close', onDrain).on('drain', onDrain)
|
||||
|
||||
const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header })
|
||||
try {
|
||||
@@ -1643,9 +1651,7 @@ async function writeIterable (abort, body, client, request, socket, contentLengt
|
||||
} catch (err) {
|
||||
writer.destroy(err)
|
||||
} finally {
|
||||
socket
|
||||
.off('close', onDrain)
|
||||
.off('drain', onDrain)
|
||||
socket.off('close', onDrain).off('drain', onDrain)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1670,10 +1676,27 @@ class AsyncWriter {
|
||||
this.expectsPayload = expectsPayload
|
||||
this.header = header
|
||||
this.abort = abort
|
||||
this.lengthMismatch = false
|
||||
|
||||
socket[kWriting] = true
|
||||
}
|
||||
|
||||
/**
|
||||
* The body doesn't match the declared content-length and strictContentLength
|
||||
* is off. Warn once, and mark the socket so it isn't reused: on the wire this
|
||||
* request's body no longer ends where the server expects, so anything sent
|
||||
* after it on the same connection would be misread.
|
||||
* @returns {void}
|
||||
*/
|
||||
onLengthMismatch () {
|
||||
this.socket[kReset] = true
|
||||
|
||||
if (!this.lengthMismatch) {
|
||||
this.lengthMismatch = true
|
||||
process.emitWarning(new RequestContentLengthMismatchError())
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string|Uint8Array} chunk
|
||||
* @returns
|
||||
@@ -1689,7 +1712,7 @@ class AsyncWriter {
|
||||
return false
|
||||
}
|
||||
|
||||
const len = chunk instanceof Uint8Array ? chunk.byteLength : Buffer.byteLength(chunk)
|
||||
let len = chunk instanceof Uint8Array ? chunk.byteLength : Buffer.byteLength(chunk)
|
||||
if (!len) {
|
||||
return true
|
||||
}
|
||||
@@ -1700,7 +1723,17 @@ class AsyncWriter {
|
||||
throw new RequestContentLengthMismatchError()
|
||||
}
|
||||
|
||||
process.emitWarning(new RequestContentLengthMismatchError())
|
||||
this.onLengthMismatch()
|
||||
|
||||
// Never write past the declared content-length. The server treats any
|
||||
// extra bytes as the start of the next request, so a body could inject
|
||||
// a request of its own (request smuggling).
|
||||
const remaining = contentLength - bytesWritten
|
||||
if (remaining === 0) {
|
||||
return true
|
||||
}
|
||||
chunk = (typeof chunk === 'string' ? Buffer.from(chunk) : chunk).subarray(0, remaining)
|
||||
len = remaining
|
||||
}
|
||||
|
||||
socket.cork()
|
||||
@@ -1775,9 +1808,12 @@ class AsyncWriter {
|
||||
if (contentLength !== null && bytesWritten !== contentLength) {
|
||||
if (client[kStrictContentLength]) {
|
||||
throw new RequestContentLengthMismatchError()
|
||||
} else {
|
||||
process.emitWarning(new RequestContentLengthMismatchError())
|
||||
}
|
||||
|
||||
// The body is shorter than declared, so the server is still waiting for
|
||||
// the rest. Don't let the next request's bytes on this connection be
|
||||
// read as the missing part of this body.
|
||||
this.onLengthMismatch()
|
||||
}
|
||||
|
||||
if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
|
||||
|
||||
+46
-14
@@ -548,8 +548,14 @@ function applyConnectionWindowSize (connectionWindowSize) {
|
||||
}
|
||||
|
||||
function onHttp2RemoteSettings (settings) {
|
||||
// Fallbacks are a safe bet, remote setting will always override
|
||||
this[kClient][kMaxConcurrentStreams] = settings.maxConcurrentStreams ?? this[kClient][kMaxConcurrentStreams]
|
||||
const client = this[kClient]
|
||||
|
||||
// The configured maxConcurrentStreams (default 100) is the client's own
|
||||
// ceiling. The server's SETTINGS_MAX_CONCURRENT_STREAMS can lower it, but
|
||||
// must not raise it: a default Node.js server advertises 2^32-1.
|
||||
const localMaxConcurrentStreams = client[kHTTP2Options].maxConcurrentStreams
|
||||
const remoteMaxConcurrentStreams = settings.maxConcurrentStreams ?? client[kMaxConcurrentStreams] ?? localMaxConcurrentStreams
|
||||
client[kMaxConcurrentStreams] = Math.min(remoteMaxConcurrentStreams, localMaxConcurrentStreams)
|
||||
/**
|
||||
* From RFC-8441
|
||||
* A sender MUST NOT send a SETTINGS_ENABLE_CONNECT_PROTOCOL parameter
|
||||
@@ -594,8 +600,6 @@ function onHttp2SendPing (session) {
|
||||
}
|
||||
|
||||
function onHttp2SessionError (err) {
|
||||
assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
|
||||
|
||||
this[kSocket][kError] = err
|
||||
|
||||
if (this[kReceivedGoAway]) {
|
||||
@@ -676,6 +680,10 @@ function onHttp2SessionGoAway (errorCode, lastStreamID) {
|
||||
client[kHTTP2Session] = null
|
||||
}
|
||||
|
||||
if (this[kOpenStreams] === 0) {
|
||||
unrefH2Session(this)
|
||||
}
|
||||
|
||||
clearHttp2IdleTimeout(this)
|
||||
clearNoStreamsTimeout(this)
|
||||
|
||||
@@ -757,8 +765,6 @@ function onHttp2SocketClose () {
|
||||
}
|
||||
|
||||
function onHttp2SocketError (err) {
|
||||
assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
|
||||
|
||||
this[kError] = err
|
||||
|
||||
if (this[kHTTP2Session]?.[kReceivedGoAway]) {
|
||||
@@ -844,25 +850,27 @@ function buildRequestHeaders (reqHeaders) {
|
||||
for (let n = 0; n < reqHeaders.length; n += 2) {
|
||||
const key = reqHeaders[n + 0]
|
||||
const val = reqHeaders[n + 1]
|
||||
const current = headers[key]
|
||||
// Reading headers[key] directly resolves `__proto__` through the prototype
|
||||
// chain instead of reporting the header as absent.
|
||||
const current = Object.hasOwn(headers, key) ? headers[key] : undefined
|
||||
|
||||
if (key === 'cookie') {
|
||||
if (current != null) {
|
||||
headers[key] = Array.isArray(current) ? (current.push(val), current) : [current, val]
|
||||
util.setHeader(headers, key, Array.isArray(current) ? (current.push(val), current) : [current, val])
|
||||
} else {
|
||||
headers[key] = val
|
||||
util.setHeader(headers, key, val)
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if (typeof val === 'string') {
|
||||
headers[key] = current ? `${current}, ${val}` : val
|
||||
util.setHeader(headers, key, current ? `${current}, ${val}` : val)
|
||||
continue
|
||||
}
|
||||
|
||||
for (let i = 0; i < val.length; i++) {
|
||||
headers[key] = headers[key] ? `${headers[key]}, ${val[i]}` : val[i]
|
||||
util.setHeader(headers, key, Object.hasOwn(headers, key) ? `${headers[key]}, ${val[i]}` : val[i])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1368,10 +1376,34 @@ function onData (chunk) {
|
||||
state.bytesRead += chunk.length
|
||||
|
||||
if (request.onResponseData(chunk) === false) {
|
||||
stream.pause()
|
||||
pauseResponseStream(stream, state)
|
||||
}
|
||||
}
|
||||
|
||||
// The body timeout measures how long the peer takes to send data. While the
|
||||
// consumer applies backpressure the peer can't send (it's out of flow-control
|
||||
// window), and Http2Stream's timer, which counts stream activity, would fire.
|
||||
// Stop it while paused and start a fresh one on resume, like HTTP/1.1, which
|
||||
// ignores the body timeout while its parser is paused.
|
||||
function pauseResponseStream (stream, state) {
|
||||
stream.pause()
|
||||
if (state.bodyTimeout) {
|
||||
stream.setTimeout(0)
|
||||
}
|
||||
}
|
||||
|
||||
// Passed to the handler as its resume callback, bound to the stream.
|
||||
function resumeResponseStream () {
|
||||
const stream = this
|
||||
const state = stream[kRequestStreamState]
|
||||
|
||||
if (state != null && state.bodyTimeout && stream.isPaused()) {
|
||||
stream.setTimeout(state.bodyTimeout)
|
||||
}
|
||||
|
||||
stream.resume()
|
||||
}
|
||||
|
||||
function onInterimResponse (headers) {
|
||||
const stream = this
|
||||
const state = stream[kRequestStreamState]
|
||||
@@ -1446,8 +1478,8 @@ function onResponse (headers) {
|
||||
return
|
||||
}
|
||||
|
||||
if (request.onResponseStart(statusCode, headers, stream.resume.bind(stream), '') === false) {
|
||||
stream.pause()
|
||||
if (request.onResponseStart(statusCode, headers, resumeResponseStream.bind(stream), '') === false) {
|
||||
pauseResponseStream(stream, state)
|
||||
}
|
||||
|
||||
stream.on('data', onData)
|
||||
|
||||
+4
-1
@@ -54,7 +54,8 @@ const {
|
||||
kMaxConcurrentStreams,
|
||||
kHostAuthority,
|
||||
kResume,
|
||||
kHTTP2Options
|
||||
kHTTP2Options,
|
||||
kUseMilo
|
||||
} = require('../core/symbols.js')
|
||||
const connectH1 = require('./client-h1.js')
|
||||
const connectH2 = require('./client-h2.js')
|
||||
@@ -136,6 +137,7 @@ class Client extends DispatcherBase {
|
||||
initialWindowSize,
|
||||
connectionWindowSize,
|
||||
pingInterval,
|
||||
useMilo,
|
||||
webSocket,
|
||||
h2Options,
|
||||
eventSource
|
||||
@@ -335,6 +337,7 @@ class Client extends DispatcherBase {
|
||||
initialWindowSize: h2Options?.initialWindowSize ?? initialWindowSize ?? 262144
|
||||
}
|
||||
}
|
||||
this[kUseMilo] = useMilo
|
||||
|
||||
// kQueue is built up of 3 sections separated by
|
||||
// the kRunningIdx and kPendingIdx indices.
|
||||
|
||||
+3
-2
@@ -8,6 +8,7 @@ const {
|
||||
InvalidArgumentError
|
||||
} = require('../core/errors')
|
||||
const { kDestroy, kClose, kClosed, kDestroyed, kDispatch } = require('../core/symbols')
|
||||
const { defaultWebSocketMaxFragments, defaultWebSocketMaxPayloadSize } = require('../core/constants')
|
||||
|
||||
const kOnDestroyed = Symbol('onDestroyed')
|
||||
const kOnClosed = Symbol('onClosed')
|
||||
@@ -41,8 +42,8 @@ class DispatcherBase extends Dispatcher {
|
||||
*/
|
||||
get webSocketOptions () {
|
||||
return {
|
||||
maxFragments: this[kWebSocketOptions].maxFragments ?? 131072,
|
||||
maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 // 128 MB default
|
||||
maxFragments: this[kWebSocketOptions].maxFragments ?? defaultWebSocketMaxFragments,
|
||||
maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? defaultWebSocketMaxPayloadSize
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+20
-3
@@ -17,12 +17,16 @@ class LegacyHandlerWrapper {
|
||||
}
|
||||
|
||||
onRequestUpgrade (controller, statusCode, headers, socket) {
|
||||
const rawHeaders = controller?.rawHeaders ?? toRawHeaders(headers ?? {})
|
||||
const rawHeaders = Array.isArray(controller?.rawHeaders)
|
||||
? controller.rawHeaders
|
||||
: toRawHeaders(controller?.rawHeaders ?? headers ?? {})
|
||||
this.#handler.onUpgrade?.(statusCode, rawHeaders, socket)
|
||||
}
|
||||
|
||||
onResponseStart (controller, statusCode, headers, statusMessage) {
|
||||
const rawHeaders = controller?.rawHeaders ?? toRawHeaders(headers ?? {})
|
||||
const rawHeaders = Array.isArray(controller?.rawHeaders)
|
||||
? controller.rawHeaders
|
||||
: toRawHeaders(controller?.rawHeaders ?? headers ?? {})
|
||||
|
||||
if (this.#handler.onHeaders?.(statusCode, rawHeaders, () => controller.resume(), statusMessage) === false) {
|
||||
controller.pause()
|
||||
@@ -36,7 +40,9 @@ class LegacyHandlerWrapper {
|
||||
}
|
||||
|
||||
onResponseEnd (controller, trailers) {
|
||||
const rawTrailers = controller?.rawTrailers ?? toRawHeaders(trailers ?? {})
|
||||
const rawTrailers = Array.isArray(controller?.rawTrailers)
|
||||
? controller.rawTrailers
|
||||
: toRawHeaders(controller?.rawTrailers ?? trailers ?? {})
|
||||
this.#handler.onComplete?.(rawTrailers)
|
||||
}
|
||||
|
||||
@@ -98,6 +104,17 @@ class Dispatcher1Wrapper extends Dispatcher {
|
||||
return this.#dispatcher.dispatch(opts, Dispatcher1Wrapper.wrapHandler(handler))
|
||||
}
|
||||
|
||||
// Older undici versions read WebSocket and EventSource receive limits from
|
||||
// the (legacy) global dispatcher, which is this wrapper, so report the
|
||||
// wrapped dispatcher's settings.
|
||||
get webSocketOptions () {
|
||||
return this.#dispatcher.webSocketOptions
|
||||
}
|
||||
|
||||
get eventSourceOptions () {
|
||||
return this.#dispatcher.eventSourceOptions
|
||||
}
|
||||
|
||||
close (...args) {
|
||||
return this.#dispatcher.close(...args)
|
||||
}
|
||||
|
||||
+1064
File diff suppressed because it is too large.
Load diff
+65
-28
@@ -20,6 +20,25 @@ const kGetDispatcher = Symbol('get dispatcher')
|
||||
const kHasDispatcher = Symbol('has dispatcher')
|
||||
const kAddClient = Symbol('add client')
|
||||
const kRemoveClient = Symbol('remove client')
|
||||
const kRetireClient = Symbol('retire client')
|
||||
const kRetiring = Symbol('retiring clients')
|
||||
|
||||
// Closes every live client, including clients that have been
|
||||
// taken out of rotation but are still finishing their own
|
||||
// requests.
|
||||
function closeClients (pool) {
|
||||
const closeAll = []
|
||||
for (let i = 0; i < pool[kClients].length; i++) {
|
||||
const client = pool[kClients][i]
|
||||
if (!client.destroyed) {
|
||||
closeAll.push(client.close())
|
||||
}
|
||||
}
|
||||
for (const closed of pool[kRetiring].values()) {
|
||||
closeAll.push(closed)
|
||||
}
|
||||
return Promise.all(closeAll)
|
||||
}
|
||||
|
||||
class PoolBase extends DispatcherBase {
|
||||
[kQueue] = new FixedQueue();
|
||||
@@ -28,6 +47,10 @@ class PoolBase extends DispatcherBase {
|
||||
|
||||
[kClients] = [];
|
||||
|
||||
// Clients removed from kClients that have not finished closing,
|
||||
// mapped to a promise that settles once they have.
|
||||
[kRetiring] = new Map();
|
||||
|
||||
[kNeedDrain] = false;
|
||||
|
||||
[kOnDrain] (client, origin, targets) {
|
||||
@@ -52,6 +75,15 @@ class PoolBase extends DispatcherBase {
|
||||
client[kNeedDrain] = needDrain
|
||||
if (needDrain) {
|
||||
this[kOnClientBusy](client)
|
||||
|
||||
// This client is full but requests are still queued, e.g. an h2
|
||||
// client that has just released everything queued while ALPN was
|
||||
// negotiated and hit maxConcurrentStreams. Hand the rest to other
|
||||
// clients, creating new ones up to the connection limit, instead of
|
||||
// leaving them for this client to drain one batch at a time.
|
||||
if (!queue.isEmpty()) {
|
||||
return this[kDrainQueue](origin, targets)
|
||||
}
|
||||
}
|
||||
|
||||
if (!needDrain && this[kNeedDrain]) {
|
||||
@@ -60,15 +92,7 @@ class PoolBase extends DispatcherBase {
|
||||
}
|
||||
|
||||
if (this[kClosedResolve] && queue.isEmpty()) {
|
||||
const closeAll = []
|
||||
for (let i = 0; i < this[kClients].length; i++) {
|
||||
const client = this[kClients][i]
|
||||
if (!client.destroyed) {
|
||||
closeAll.push(client.close())
|
||||
}
|
||||
}
|
||||
return Promise.all(closeAll)
|
||||
.then(this[kClosedResolve])
|
||||
return closeClients(this).then(this[kClosedResolve])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,15 +130,7 @@ class PoolBase extends DispatcherBase {
|
||||
}
|
||||
|
||||
if (this[kClosedResolve] && queue.isEmpty()) {
|
||||
const closeAll = []
|
||||
for (let i = 0; i < this[kClients].length; i++) {
|
||||
const client = this[kClients][i]
|
||||
if (!client.destroyed) {
|
||||
closeAll.push(client.close())
|
||||
}
|
||||
}
|
||||
return Promise.all(closeAll)
|
||||
.then(this[kClosedResolve])
|
||||
return closeClients(this).then(this[kClosedResolve])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,14 +196,7 @@ class PoolBase extends DispatcherBase {
|
||||
|
||||
[kClose] () {
|
||||
if (this[kQueue].isEmpty()) {
|
||||
const closeAll = []
|
||||
for (let i = 0; i < this[kClients].length; i++) {
|
||||
const client = this[kClients][i]
|
||||
if (!client.destroyed) {
|
||||
closeAll.push(client.close())
|
||||
}
|
||||
}
|
||||
return Promise.all(closeAll)
|
||||
return closeClients(this)
|
||||
} else {
|
||||
return new Promise((resolve) => {
|
||||
this[kClosedResolve] = resolve
|
||||
@@ -208,6 +217,9 @@ class PoolBase extends DispatcherBase {
|
||||
for (let i = 0; i < this[kClients].length; i++) {
|
||||
destroyAll[i] = this[kClients][i].destroy(err)
|
||||
}
|
||||
for (const client of this[kRetiring].keys()) {
|
||||
destroyAll.push(client.destroy(err))
|
||||
}
|
||||
return Promise.all(destroyAll)
|
||||
}
|
||||
|
||||
@@ -263,13 +275,37 @@ class PoolBase extends DispatcherBase {
|
||||
return this
|
||||
}
|
||||
|
||||
[kRemoveClient] (client) {
|
||||
// Takes a client out of rotation. A closed client no longer takes requests
|
||||
// from the pool queue (see kOnDrain), but it finishes the requests it
|
||||
// already has. Until it has, pool.close() waits for it and pool.destroy()
|
||||
// destroys it.
|
||||
[kRetireClient] (client) {
|
||||
const idx = this[kClients].indexOf(client)
|
||||
if (idx !== -1) {
|
||||
this[kClients].splice(idx, 1)
|
||||
}
|
||||
|
||||
client.close(() => {})
|
||||
if (client.destroyed || this[kRetiring].has(client)) {
|
||||
return
|
||||
}
|
||||
|
||||
// Use the callback form: custom dispatchers from `factory` are not
|
||||
// required to return a promise, and may call back synchronously.
|
||||
let done = false
|
||||
let resolveClosed
|
||||
const closed = new Promise((resolve) => { resolveClosed = resolve })
|
||||
this[kRetiring].set(client, closed)
|
||||
client.close(() => {
|
||||
if (!done) {
|
||||
done = true
|
||||
this[kRetiring].delete(client)
|
||||
resolveClosed()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
[kRemoveClient] (client) {
|
||||
this[kRetireClient](client)
|
||||
|
||||
this[kNeedDrain] = !this[kClients].some(dispatcher => (
|
||||
!dispatcher[kNeedDrain] &&
|
||||
@@ -285,6 +321,7 @@ module.exports = {
|
||||
kNeedDrain,
|
||||
kAddClient,
|
||||
kRemoveClient,
|
||||
kRetireClient,
|
||||
kDrainQueue,
|
||||
kOnClientBusy,
|
||||
kOnClientDrain,
|
||||
|
||||
+11
-8
@@ -10,14 +10,15 @@ const {
|
||||
kOnClientDrain,
|
||||
kGetDispatcher,
|
||||
kHasDispatcher,
|
||||
kRemoveClient
|
||||
kRemoveClient,
|
||||
kRetireClient
|
||||
} = require('./pool-base')
|
||||
const Client = require('./client')
|
||||
const {
|
||||
InvalidArgumentError
|
||||
} = require('../core/errors')
|
||||
const util = require('../core/util')
|
||||
const { kConnecting, kHTTPContext, kUrl } = require('../core/symbols')
|
||||
const { kConnecting, kHTTPContext, kUrl, kQueued } = require('../core/symbols')
|
||||
const buildConnector = require('../core/connect')
|
||||
|
||||
const kOptions = Symbol('options')
|
||||
@@ -144,15 +145,17 @@ class Pool extends PoolBase {
|
||||
resumeQueued = true
|
||||
}
|
||||
|
||||
// Do not use kRemoveClient here, as it will close the client,
|
||||
// but the client cannot be closed in this state.
|
||||
const idx = this[kClients].indexOf(target)
|
||||
if (idx !== -1) {
|
||||
this[kClients].splice(idx, 1)
|
||||
// Retire (close) the client rather than only dropping it from
|
||||
// kClients: otherwise its drain listener keeps pulling requests from
|
||||
// the pool queue onto a client that pool.destroy() can't reach.
|
||||
if (this[kClients].includes(target)) {
|
||||
this[kRetireClient](target)
|
||||
}
|
||||
}
|
||||
|
||||
if (resumeQueued) {
|
||||
// The retired client no longer drains the pool queue, so hand any
|
||||
// queued requests to another (possibly new) client.
|
||||
if (resumeQueued || this[kQueued] > 0) {
|
||||
this[kDrainQueue](origin, targets.slice(1))
|
||||
}
|
||||
})
|
||||
|
||||
+18
-8
@@ -83,11 +83,10 @@ class Http1ProxyWrapper extends DispatcherBase {
|
||||
|
||||
opts.path = origin + path
|
||||
|
||||
if (!('host' in headers) && !('Host' in headers)) {
|
||||
const { host } = new URL(origin)
|
||||
headers.host = host
|
||||
}
|
||||
opts.headers = { ...this[kProxyHeaders], ...headers }
|
||||
if (!hasHostHeader(headers)) {
|
||||
opts.headers.host = new URL(origin).host
|
||||
}
|
||||
|
||||
// Pin the SNI/cert hostname to the proxy. Without this the underlying
|
||||
// Client would derive it from the (rewritten) Host header, which points
|
||||
@@ -276,12 +275,14 @@ class ProxyAgent extends DispatcherBase {
|
||||
}
|
||||
|
||||
dispatch (opts, handler) {
|
||||
const headers = buildHeaders(opts.headers)
|
||||
let headers = buildHeaders(opts.headers)
|
||||
throwIfProxyAuthIsSent(headers)
|
||||
|
||||
if (headers && !('host' in headers) && !('Host' in headers)) {
|
||||
const { host } = new URL(opts.origin)
|
||||
headers.host = host
|
||||
if (headers && !hasHostHeader(headers)) {
|
||||
if (headers === opts.headers) {
|
||||
headers = { ...headers }
|
||||
}
|
||||
headers.host = new URL(opts.origin).host
|
||||
}
|
||||
|
||||
return this[kAgent].dispatch(
|
||||
@@ -401,6 +402,15 @@ function isProxyAuthorizationHeader (key) {
|
||||
return key.length === proxyAuthorization.length && key.toLowerCase() === proxyAuthorization
|
||||
}
|
||||
|
||||
function hasHostHeader (headers) {
|
||||
for (const key in headers) {
|
||||
if (key.length === 4 && key.toLowerCase() === 'host') {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function throwProxyAuthError () {
|
||||
throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor')
|
||||
}
|
||||
|
||||
+10
@@ -26,6 +26,16 @@ class RetryAgent extends Dispatcher {
|
||||
return this.#agent.dispatch(opts, retry)
|
||||
}
|
||||
|
||||
// WebSocket and EventSource read their receive limits from the dispatcher
|
||||
// they are given, so report the wrapped agent's settings rather than none.
|
||||
get webSocketOptions () {
|
||||
return this.#agent.webSocketOptions
|
||||
}
|
||||
|
||||
get eventSourceOptions () {
|
||||
return this.#agent.eventSourceOptions
|
||||
}
|
||||
|
||||
close () {
|
||||
return this.#agent.close()
|
||||
}
|
||||
|
||||
+15
-5
@@ -7,14 +7,16 @@ const {
|
||||
kAddClient,
|
||||
kGetDispatcher,
|
||||
kHasDispatcher,
|
||||
kRemoveClient
|
||||
kRemoveClient,
|
||||
kRetireClient,
|
||||
kDrainQueue
|
||||
} = require('./pool-base')
|
||||
const Client = require('./client')
|
||||
const {
|
||||
InvalidArgumentError
|
||||
} = require('../core/errors')
|
||||
const util = require('../core/util')
|
||||
const { kUrl } = require('../core/symbols')
|
||||
const { kUrl, kQueued } = require('../core/symbols')
|
||||
const buildConnector = require('../core/connect')
|
||||
|
||||
const kOptions = Symbol('options')
|
||||
@@ -82,12 +84,20 @@ class RoundRobinPool extends PoolBase {
|
||||
})
|
||||
|
||||
this.on('connectionError', (origin, targets, error) => {
|
||||
// Retire (close) the client rather than only dropping it from
|
||||
// kClients: otherwise its drain listener keeps pulling requests from
|
||||
// the pool queue onto a client that pool.destroy() can't reach.
|
||||
for (const target of targets) {
|
||||
const idx = this[kClients].indexOf(target)
|
||||
if (idx !== -1) {
|
||||
this[kClients].splice(idx, 1)
|
||||
if (this[kClients].includes(target)) {
|
||||
this[kRetireClient](target)
|
||||
}
|
||||
}
|
||||
|
||||
// The retired client no longer drains the pool queue, so hand any
|
||||
// queued requests to another (possibly new) client.
|
||||
if (this[kQueued] > 0) {
|
||||
this[kDrainQueue](origin, targets.slice(1))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+153
-15
@@ -1,6 +1,7 @@
|
||||
'use strict'
|
||||
|
||||
const util = require('../core/util')
|
||||
const { kRedirectCacheControl } = require('../core/symbols')
|
||||
const {
|
||||
parseCacheControlHeader,
|
||||
hasInvalidCacheControlDirective,
|
||||
@@ -13,6 +14,63 @@ const { parseHttpDate } = require('../util/date.js')
|
||||
|
||||
function noop () {}
|
||||
|
||||
class CacheController {
|
||||
#blocked = false
|
||||
#downstreamPaused = false
|
||||
|
||||
constructor (target) {
|
||||
this.target = target
|
||||
}
|
||||
|
||||
block () {
|
||||
this.#blocked = true
|
||||
}
|
||||
|
||||
release () {
|
||||
this.#blocked = false
|
||||
if (!this.#downstreamPaused) {
|
||||
this.target.resume()
|
||||
}
|
||||
}
|
||||
|
||||
pause () {
|
||||
this.#downstreamPaused = true
|
||||
this.target.pause()
|
||||
}
|
||||
|
||||
resume () {
|
||||
this.#downstreamPaused = false
|
||||
if (!this.#blocked) {
|
||||
this.target.resume()
|
||||
}
|
||||
}
|
||||
|
||||
abort (reason) {
|
||||
this.target.abort(reason)
|
||||
}
|
||||
|
||||
get paused () { return this.#downstreamPaused }
|
||||
get aborted () { return this.target.aborted }
|
||||
get reason () { return this.target.reason }
|
||||
get rawHeaders () { return this.target.rawHeaders }
|
||||
set rawHeaders (value) { this.target.rawHeaders = value }
|
||||
get rawTrailers () { return this.target.rawTrailers }
|
||||
set rawTrailers (value) { this.target.rawTrailers = value }
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string | URL} a
|
||||
* @param {string | URL} b
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function sameOrigin (a, b) {
|
||||
try {
|
||||
return new URL(String(a)).origin === new URL(String(b)).origin
|
||||
} catch {
|
||||
return String(a) === String(b)
|
||||
}
|
||||
}
|
||||
|
||||
// Status codes that we can use some heuristics on to cache
|
||||
const HEURISTICALLY_CACHEABLE_STATUS_CODES = [
|
||||
200, 203, 204, 206, 300, 301, 308, 404, 405, 410, 414, 501
|
||||
@@ -149,11 +207,24 @@ class CacheHandler {
|
||||
*/
|
||||
#handler
|
||||
|
||||
/**
|
||||
* @type {CacheController | undefined}
|
||||
*/
|
||||
#downstreamController
|
||||
|
||||
/**
|
||||
* @type {import('node:stream').Writable | undefined}
|
||||
*/
|
||||
#writeStream
|
||||
|
||||
/**
|
||||
* The URLs visited while following redirects, shared by reference from the
|
||||
* redirect handler through the request context. Carries the suppressed hops'
|
||||
* cache-control under {@link kRedirectCacheControl}.
|
||||
* @type {URL[] | undefined}
|
||||
*/
|
||||
#history
|
||||
|
||||
/**
|
||||
* @param {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions} opts
|
||||
* @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} cacheKey
|
||||
@@ -170,7 +241,15 @@ class CacheHandler {
|
||||
onRequestStart (controller, context) {
|
||||
this.#writeStream?.destroy()
|
||||
this.#writeStream = undefined
|
||||
this.#handler.onRequestStart?.(controller, context)
|
||||
this.#downstreamController = new CacheController(controller)
|
||||
// The redirect handler threads the list of visited URLs through the
|
||||
// handler-chain context. Keep a reference to it (it is mutated as redirects
|
||||
// are followed) so onResponseStart can tell which request actually produced
|
||||
// the response. Unlike the request options object, this reference is not
|
||||
// broken by an interceptor that copies the options between the cache and
|
||||
// the redirect.
|
||||
this.#history = context?.history
|
||||
this.#handler.onRequestStart?.(this.#downstreamController, context)
|
||||
}
|
||||
|
||||
onBodySent (chunk) {
|
||||
@@ -181,8 +260,8 @@ class CacheHandler {
|
||||
this.#handler.onRequestSent?.()
|
||||
}
|
||||
|
||||
onRequestUpgrade (controller, statusCode, headers, socket) {
|
||||
this.#handler.onRequestUpgrade?.(controller, statusCode, headers, socket)
|
||||
onRequestUpgrade (_controller, statusCode, headers, socket) {
|
||||
this.#handler.onRequestUpgrade?.(this.#downstreamController, statusCode, headers, socket)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -199,7 +278,7 @@ class CacheHandler {
|
||||
) {
|
||||
const downstreamOnHeaders = () =>
|
||||
this.#handler.onResponseStart?.(
|
||||
controller,
|
||||
this.#downstreamController,
|
||||
statusCode,
|
||||
resHeaders,
|
||||
statusMessage
|
||||
@@ -217,6 +296,35 @@ class CacheHandler {
|
||||
return downstreamOnHeaders()
|
||||
}
|
||||
|
||||
// A cross-origin redirect can change the origin that actually produced the
|
||||
// final response. Keying that response on the original (trusted) origin
|
||||
// would let a redirect target control an entry for a URL the application
|
||||
// trusts. The final request is the last URL in the redirect history; only
|
||||
// cache when its origin still matches the cache key origin.
|
||||
if (this.#history && this.#history.length > 0) {
|
||||
const finalUrl = this.#history[this.#history.length - 1]
|
||||
if (!sameOrigin(finalUrl.origin, this.#cacheKey.origin)) {
|
||||
return downstreamOnHeaders()
|
||||
}
|
||||
}
|
||||
|
||||
// A redirect hop that is not forwarded can still carry a restrictive
|
||||
// storage policy (for example `no-store`, or `private` for a shared cache).
|
||||
// Honor it, otherwise a redirect that must not be stored could be laundered
|
||||
// into a cacheable final response under the original key.
|
||||
const redirectCacheControl = this.#history?.[kRedirectCacheControl]
|
||||
if (redirectCacheControl) {
|
||||
for (const hopCacheControl of redirectCacheControl) {
|
||||
const hopDirectives = hopCacheControl ? parseCacheControlHeader(hopCacheControl) : {}
|
||||
if (
|
||||
hopDirectives['no-store'] === true ||
|
||||
(this.#cacheType === 'shared' && hopDirectives.private === true)
|
||||
) {
|
||||
return downstreamOnHeaders()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const cacheControlHeader = resHeaders['cache-control']
|
||||
const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {}
|
||||
|
||||
@@ -323,10 +431,21 @@ class CacheHandler {
|
||||
// Not modified, re-use the cached value
|
||||
// https://www.rfc-editor.org/rfc/rfc9111.html#name-handling-304-not-modified
|
||||
if (statusCode === 304) {
|
||||
let done = false
|
||||
const finish304 = () => {
|
||||
if (done) {
|
||||
return
|
||||
}
|
||||
done = true
|
||||
this.#downstreamController.release()
|
||||
}
|
||||
|
||||
const handle304 = (cachedValue) => {
|
||||
if (!cachedValue) {
|
||||
// Do not create a new cache entry, as a 304 won't have a body - so cannot be cached.
|
||||
return downstreamOnHeaders()
|
||||
downstreamOnHeaders()
|
||||
finish304()
|
||||
return
|
||||
}
|
||||
|
||||
// Re-use the cached value: statuscode, statusmessage, headers and body
|
||||
@@ -341,6 +460,7 @@ class CacheHandler {
|
||||
this.#writeStream = this.#store.createWriteStream(this.#cacheKey, value)
|
||||
|
||||
if (!this.#writeStream || !cachedValue?.body) {
|
||||
finish304()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -348,20 +468,26 @@ class CacheHandler {
|
||||
const bodyIterator = cachedValue.body.values()
|
||||
|
||||
const streamCachedBody = () => {
|
||||
if (done) {
|
||||
return
|
||||
}
|
||||
for (const chunk of bodyIterator) {
|
||||
const full = this.#writeStream.write(chunk) === false
|
||||
this.#handler.onResponseData?.(controller, chunk)
|
||||
const full = this.#writeStream?.write(chunk) === false
|
||||
this.#handler.onResponseData?.(this.#downstreamController, chunk)
|
||||
// when stream is full stop writing until we get a 'drain' event
|
||||
if (full) {
|
||||
break
|
||||
return
|
||||
}
|
||||
}
|
||||
finish304()
|
||||
}
|
||||
|
||||
this.#writeStream
|
||||
.on('error', function () {
|
||||
handler.#writeStream = undefined
|
||||
handler.#store.delete(handler.#cacheKey)
|
||||
// Keep replaying downstream without the store
|
||||
streamCachedBody()
|
||||
})
|
||||
.on('drain', () => {
|
||||
streamCachedBody()
|
||||
@@ -369,6 +495,8 @@ class CacheHandler {
|
||||
.on('close', function () {
|
||||
if (handler.#writeStream === this) {
|
||||
handler.#writeStream = undefined
|
||||
// Keep replaying downstream without the store
|
||||
streamCachedBody()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -377,15 +505,17 @@ class CacheHandler {
|
||||
// Readable stream body (e.g. from async/remote cache stores)
|
||||
cachedValue.body
|
||||
.on('data', (chunk) => {
|
||||
this.#writeStream.write(chunk)
|
||||
this.#handler.onResponseData?.(controller, chunk)
|
||||
this.#writeStream?.write(chunk)
|
||||
this.#handler.onResponseData?.(this.#downstreamController, chunk)
|
||||
})
|
||||
.on('end', () => {
|
||||
this.#writeStream.end()
|
||||
this.#writeStream?.end()
|
||||
finish304()
|
||||
})
|
||||
.on('error', () => {
|
||||
this.#writeStream = undefined
|
||||
this.#store.delete(this.#cacheKey)
|
||||
finish304()
|
||||
})
|
||||
|
||||
this.#writeStream
|
||||
@@ -398,6 +528,8 @@ class CacheHandler {
|
||||
handler.#writeStream = undefined
|
||||
}
|
||||
})
|
||||
} else {
|
||||
finish304()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -405,8 +537,14 @@ class CacheHandler {
|
||||
* @type {import('../../types/cache-interceptor.d.ts').default.CacheValue}
|
||||
*/
|
||||
const result = this.#store.get(this.#cacheKey)
|
||||
// A 304 ends before the cached body is replayed. Keep the origin
|
||||
// response paused until replay is complete.
|
||||
this.#downstreamController.block()
|
||||
controller.pause()
|
||||
if (result && typeof result.then === 'function') {
|
||||
result.then(handle304)
|
||||
result.then(handle304, () => handle304(undefined)).catch((err) => {
|
||||
controller.abort(err)
|
||||
})
|
||||
} else {
|
||||
handle304(result)
|
||||
}
|
||||
@@ -449,18 +587,18 @@ class CacheHandler {
|
||||
controller.pause()
|
||||
}
|
||||
|
||||
this.#handler.onResponseData?.(controller, chunk)
|
||||
this.#handler.onResponseData?.(this.#downstreamController, chunk)
|
||||
}
|
||||
|
||||
onResponseEnd (controller, trailers) {
|
||||
this.#writeStream?.end()
|
||||
this.#handler.onResponseEnd?.(controller, trailers)
|
||||
this.#handler.onResponseEnd?.(this.#downstreamController, trailers)
|
||||
}
|
||||
|
||||
onResponseError (controller, err) {
|
||||
this.#writeStream?.destroy(err)
|
||||
this.#writeStream = undefined
|
||||
this.#handler.onResponseError?.(controller, err)
|
||||
this.#handler.onResponseError?.(this.#downstreamController, err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+116
-55
@@ -16,6 +16,7 @@ const DEFAULT_MAX_BUFFER_SIZE = 5 * 1024 * 1024
|
||||
* @property {number} bufferedBytes
|
||||
* @property {object | null} pendingTrailers
|
||||
* @property {boolean} done
|
||||
* @property {boolean} [pendingStart] onRequestStart deferred until the primary request's context is known
|
||||
*/
|
||||
|
||||
/**
|
||||
@@ -30,6 +31,20 @@ class DeduplicationHandler {
|
||||
*/
|
||||
#primaryHandler
|
||||
|
||||
/**
|
||||
* Whether the primary request has started (onRequestStart received). Until
|
||||
* then the request context is unknown and cannot be given to waiting handlers.
|
||||
* @type {boolean}
|
||||
*/
|
||||
#requestStarted = false
|
||||
|
||||
/**
|
||||
* The primary request context, replayed to waiting handlers so they observe
|
||||
* the same redirect history as the primary.
|
||||
* @type {any}
|
||||
*/
|
||||
#context = null
|
||||
|
||||
/**
|
||||
* @type {WaitingHandler[]}
|
||||
*/
|
||||
@@ -112,20 +127,30 @@ class DeduplicationHandler {
|
||||
const waitingController = waitingHandler.controller
|
||||
|
||||
try {
|
||||
handler.onRequestStart?.(waitingController, null)
|
||||
if (this.#requestStarted) {
|
||||
// The primary request has started, so its context (including the
|
||||
// redirect history) is known and can be delivered immediately.
|
||||
handler.onRequestStart?.(waitingController, this.#context)
|
||||
|
||||
if (waitingController.aborted) {
|
||||
waitingHandler.done = true
|
||||
return true
|
||||
}
|
||||
if (waitingController.aborted) {
|
||||
waitingHandler.done = true
|
||||
return true
|
||||
}
|
||||
|
||||
if (this.#responseStarted) {
|
||||
handler.onResponseStart?.(
|
||||
waitingController,
|
||||
this.#statusCode,
|
||||
this.#headers,
|
||||
this.#statusMessage
|
||||
)
|
||||
if (this.#responseStarted) {
|
||||
handler.onResponseStart?.(
|
||||
waitingController,
|
||||
this.#statusCode,
|
||||
this.#headers,
|
||||
this.#statusMessage
|
||||
)
|
||||
}
|
||||
} else {
|
||||
// The primary request has not started yet. Defer onRequestStart until
|
||||
// its context is known, so the waiting handler observes the same
|
||||
// redirect history as the primary (a cache handler relies on it to
|
||||
// reject cross-origin redirect responses).
|
||||
waitingHandler.pendingStart = true
|
||||
}
|
||||
} catch {
|
||||
// Ignore errors from waiting handlers
|
||||
@@ -146,6 +171,24 @@ class DeduplicationHandler {
|
||||
*/
|
||||
onRequestStart (controller, context) {
|
||||
this.#controller = controller
|
||||
if (!this.#requestStarted) {
|
||||
this.#requestStarted = true
|
||||
this.#context = context
|
||||
// Deliver the now-known context to handlers that joined before the
|
||||
// primary request started.
|
||||
for (const waitingHandler of this.#waitingHandlers) {
|
||||
if (waitingHandler.pendingStart && !waitingHandler.done && !waitingHandler.controller.aborted) {
|
||||
waitingHandler.pendingStart = false
|
||||
try {
|
||||
waitingHandler.handler.onRequestStart?.(waitingHandler.controller, context)
|
||||
} catch {
|
||||
// Ignore errors from waiting handlers
|
||||
waitingHandler.done = true
|
||||
}
|
||||
}
|
||||
}
|
||||
this.#pruneDoneWaitingHandlers()
|
||||
}
|
||||
this.#primaryHandler.onRequestStart?.(controller, context)
|
||||
}
|
||||
|
||||
@@ -251,40 +294,41 @@ class DeduplicationHandler {
|
||||
return
|
||||
}
|
||||
|
||||
// Remove the entry before callbacks can synchronously dispatch a retry.
|
||||
this.#cleanup()
|
||||
this.#primaryHandler.onResponseEnd?.(controller, trailers)
|
||||
// A throwing end callback must still be handled by onResponseError.
|
||||
this.#completed = true
|
||||
// Remove the completed request before callbacks can redispatch into this
|
||||
// interceptor. Cleanup must not depend on downstream handlers succeeding.
|
||||
this.#cleanup()
|
||||
|
||||
for (const waitingHandler of this.#waitingHandlers) {
|
||||
if (waitingHandler.done || waitingHandler.controller.aborted) {
|
||||
waitingHandler.done = true
|
||||
continue
|
||||
try {
|
||||
this.#primaryHandler.onResponseEnd?.(controller, trailers)
|
||||
} catch (err) {
|
||||
// Completion callbacks may throw to initiate a retry. The transport's
|
||||
// error callback would be ignored now that this handler is completed.
|
||||
this.#primaryHandler.onResponseError?.(controller, err)
|
||||
} finally {
|
||||
for (const waitingHandler of this.#waitingHandlers) {
|
||||
if (waitingHandler.done || waitingHandler.controller.aborted) {
|
||||
waitingHandler.done = true
|
||||
continue
|
||||
}
|
||||
|
||||
this.#flushWaitingHandler(waitingHandler)
|
||||
|
||||
if (waitingHandler.done || waitingHandler.controller.aborted) {
|
||||
waitingHandler.done = true
|
||||
continue
|
||||
}
|
||||
|
||||
if (waitingHandler.controller.paused) {
|
||||
waitingHandler.pendingTrailers = trailers
|
||||
continue
|
||||
}
|
||||
|
||||
this.#endWaitingHandler(waitingHandler, trailers)
|
||||
}
|
||||
|
||||
this.#flushWaitingHandler(waitingHandler)
|
||||
|
||||
if (waitingHandler.done || waitingHandler.controller.aborted) {
|
||||
waitingHandler.done = true
|
||||
continue
|
||||
}
|
||||
|
||||
if (waitingHandler.controller.paused) {
|
||||
waitingHandler.pendingTrailers = trailers
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
waitingHandler.handler.onResponseEnd?.(waitingHandler.controller, trailers)
|
||||
} catch (err) {
|
||||
this.#errorWaitingHandler(waitingHandler, err)
|
||||
}
|
||||
|
||||
waitingHandler.done = true
|
||||
this.#pruneDoneWaitingHandlers()
|
||||
}
|
||||
|
||||
this.#pruneDoneWaitingHandlers()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -300,13 +344,15 @@ class DeduplicationHandler {
|
||||
this.#completed = true
|
||||
this.#cleanup()
|
||||
|
||||
this.#primaryHandler.onResponseError?.(controller, err)
|
||||
try {
|
||||
this.#primaryHandler.onResponseError?.(controller, err)
|
||||
} finally {
|
||||
for (const waitingHandler of this.#waitingHandlers) {
|
||||
this.#errorWaitingHandler(waitingHandler, err)
|
||||
}
|
||||
|
||||
for (const waitingHandler of this.#waitingHandlers) {
|
||||
this.#errorWaitingHandler(waitingHandler, err)
|
||||
this.#waitingHandlers = []
|
||||
}
|
||||
|
||||
this.#waitingHandlers = []
|
||||
}
|
||||
|
||||
#cleanup () {
|
||||
@@ -327,7 +373,8 @@ class DeduplicationHandler {
|
||||
bufferedChunks: [],
|
||||
bufferedBytes: 0,
|
||||
pendingTrailers: null,
|
||||
done: false
|
||||
done: false,
|
||||
pendingStart: false
|
||||
}
|
||||
|
||||
const state = {
|
||||
@@ -352,14 +399,7 @@ class DeduplicationHandler {
|
||||
!state.paused &&
|
||||
!state.aborted
|
||||
) {
|
||||
try {
|
||||
waitingHandler.handler.onResponseEnd?.(waitingHandler.controller, waitingHandler.pendingTrailers)
|
||||
} catch (err) {
|
||||
this.#errorWaitingHandler(waitingHandler, err)
|
||||
}
|
||||
|
||||
waitingHandler.pendingTrailers = null
|
||||
waitingHandler.done = true
|
||||
this.#endWaitingHandler(waitingHandler, waitingHandler.pendingTrailers)
|
||||
}
|
||||
|
||||
this.#pruneDoneWaitingHandlers()
|
||||
@@ -448,6 +488,27 @@ class DeduplicationHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {WaitingHandler} waitingHandler
|
||||
* @param {object} trailers
|
||||
*/
|
||||
#endWaitingHandler (waitingHandler, trailers) {
|
||||
waitingHandler.done = true
|
||||
waitingHandler.pendingTrailers = null
|
||||
|
||||
try {
|
||||
waitingHandler.handler.onResponseEnd?.(waitingHandler.controller, trailers)
|
||||
} catch (err) {
|
||||
// This is a response failure, not a consumer abort. Aborting the waiting
|
||||
// controller here would prevent downstream handlers from retrying.
|
||||
try {
|
||||
waitingHandler.handler.onResponseError?.(waitingHandler.controller, err)
|
||||
} catch {
|
||||
// An error callback must not prevent other waiting handlers completing.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {WaitingHandler} waitingHandler
|
||||
* @param {Error} err
|
||||
|
||||
+28
-8
@@ -2,8 +2,8 @@
|
||||
|
||||
const util = require('../core/util')
|
||||
const assert = require('node:assert')
|
||||
const { InvalidArgumentError } = require('../core/errors')
|
||||
const { kRequestOrigin } = require('../core/symbols')
|
||||
const { InvalidArgumentError, MaxRedirectsError } = require('../core/errors')
|
||||
const { kRequestOrigin, kRedirectCacheControl } = require('../core/symbols')
|
||||
|
||||
const redirectableStatusCodes = [300, 301, 302, 303, 307, 308]
|
||||
|
||||
@@ -38,6 +38,15 @@ class RedirectHandler {
|
||||
this.maxRedirections = maxRedirections
|
||||
this.handler = handler
|
||||
this.history = []
|
||||
// `cache-control` of each intermediate (suppressed) redirect hop. An outer
|
||||
// cache uses it to preserve a hop's storage policy (e.g. `no-store`) that
|
||||
// would otherwise be lost because the hop's response is not forwarded. It
|
||||
// travels as a non-enumerable property of the history array so it reaches
|
||||
// the cache without becoming part of the public request/response context.
|
||||
Object.defineProperty(this.history, kRedirectCacheControl, {
|
||||
value: [],
|
||||
enumerable: false
|
||||
})
|
||||
}
|
||||
|
||||
onRequestStart (controller, context) {
|
||||
@@ -62,10 +71,6 @@ class RedirectHandler {
|
||||
return
|
||||
}
|
||||
|
||||
if (this.opts.throwOnMaxRedirect && this.history.length >= this.maxRedirections) {
|
||||
throw new Error('max redirects')
|
||||
}
|
||||
|
||||
let removeContentHeaders = statusCode === 303
|
||||
|
||||
// https://tools.ietf.org/html/rfc7231#section-6.4.2
|
||||
@@ -91,9 +96,19 @@ class RedirectHandler {
|
||||
this.opts.body = null
|
||||
}
|
||||
|
||||
this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body) || redirectableStatusCodes.indexOf(statusCode) === -1
|
||||
this.location = util.isDisturbed(this.opts.body) || redirectableStatusCodes.indexOf(statusCode) === -1
|
||||
? null
|
||||
: headers.location
|
||||
: headers.location || null
|
||||
|
||||
// Only a redirect that would otherwise be followed counts against the
|
||||
// limit. The final response after exactly maxRedirections redirects, or a
|
||||
// 3xx without a Location header, is delivered as usual.
|
||||
if (this.location && this.history.length >= this.maxRedirections) {
|
||||
if (this.opts.throwOnMaxRedirect) {
|
||||
throw new MaxRedirectsError()
|
||||
}
|
||||
this.location = null
|
||||
}
|
||||
|
||||
const requestOrigin = this.opts[kRequestOrigin] === undefined
|
||||
? this.opts.origin
|
||||
@@ -108,6 +123,11 @@ class RedirectHandler {
|
||||
return
|
||||
}
|
||||
|
||||
// This hop's response is suppressed (only its Location is used). Record its
|
||||
// cache-control so an outer cache can honor a restrictive policy that would
|
||||
// otherwise be lost when the final response is stored.
|
||||
this.history[kRedirectCacheControl].push(headers['cache-control'])
|
||||
|
||||
const baseUrl = requestOrigin
|
||||
? new URL(this.opts.path, requestOrigin)
|
||||
: undefined
|
||||
|
||||
+44
-11
@@ -4,6 +4,7 @@ const assert = require('node:assert')
|
||||
const { kRetryHandlerDefaultRetry } = require('../core/symbols')
|
||||
const { RequestRetryError, RequestAbortedError } = require('../core/errors')
|
||||
const {
|
||||
hasSafeIterator,
|
||||
isDisturbed,
|
||||
parseRangeHeader,
|
||||
wrapRequestBody
|
||||
@@ -554,19 +555,9 @@ class RetryHandler {
|
||||
|
||||
retry () {
|
||||
if (this.start !== 0) {
|
||||
const headers = { range: `bytes=${this.start}-${this.end ?? ''}` }
|
||||
|
||||
// Weak etag check - weak etags will make comparison algorithms never match
|
||||
if (this.etag != null) {
|
||||
headers['if-match'] = this.etag
|
||||
}
|
||||
|
||||
this.opts = {
|
||||
...this.opts,
|
||||
headers: {
|
||||
...this.opts.headers,
|
||||
...headers
|
||||
}
|
||||
headers: buildResumeHeaders(this.opts.headers, `bytes=${this.start}-${this.end ?? ''}`, this.etag)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -650,4 +641,46 @@ class RetryHandler {
|
||||
}
|
||||
}
|
||||
|
||||
function isReplacedHeader (key, etag) {
|
||||
const name = key.toLowerCase()
|
||||
return name === 'range' || (etag != null && name === 'if-match')
|
||||
}
|
||||
|
||||
function buildResumeHeaders (headers, range, etag) {
|
||||
if (Array.isArray(headers) || (headers && typeof headers === 'object' && hasSafeIterator(headers))) {
|
||||
const ret = []
|
||||
if (Array.isArray(headers)) {
|
||||
for (let i = 0; i < headers.length; i += 2) {
|
||||
if (!isReplacedHeader(headers[i], etag)) {
|
||||
ret.push(headers[i], headers[i + 1])
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (const [key, value] of headers) {
|
||||
if (!isReplacedHeader(key, etag)) {
|
||||
ret.push(key, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
ret.push('range', range)
|
||||
// Weak etag check - weak etags will make comparison algorithms never match
|
||||
if (etag != null) {
|
||||
ret.push('if-match', etag)
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
const ret = {}
|
||||
for (const key in headers) {
|
||||
if (Object.hasOwn(headers, key) && !isReplacedHeader(key, etag)) {
|
||||
ret[key] = headers[key]
|
||||
}
|
||||
}
|
||||
ret.range = range
|
||||
if (etag != null) {
|
||||
ret['if-match'] = etag
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
module.exports = RetryHandler
|
||||
+11
-3
@@ -210,7 +210,10 @@ function makeRevalidationHeaders (opts, result) {
|
||||
*/
|
||||
function isStale (result, cacheControlDirectives, cacheType) {
|
||||
const now = Date.now()
|
||||
if (now > result.staleAt) {
|
||||
// A zero freshness lifetime (e.g. max-age=0 with a validator) is never fresh,
|
||||
// even when reused within the same millisecond or after a clock step back.
|
||||
// https://www.rfc-editor.org/rfc/rfc9111.html#section-4.2
|
||||
if (now > result.staleAt || result.staleAt <= result.cachedAt) {
|
||||
// Response is stale
|
||||
if (!staleResponseRequiresRevalidation(result, cacheType) && cacheControlDirectives?.['max-stale']) {
|
||||
// There's a threshold where we can serve stale responses, let's see if
|
||||
@@ -331,6 +334,7 @@ function sendCachedValue (handler, opts, result, age, context, isStale) {
|
||||
assert(!stream.readableDidRead, 'stream should not be readableDidRead')
|
||||
|
||||
let aborted = false
|
||||
let abortReason = null
|
||||
|
||||
const controller = {
|
||||
rawHeaders: [],
|
||||
@@ -348,11 +352,15 @@ function sendCachedValue (handler, opts, result, age, context, isStale) {
|
||||
return aborted
|
||||
},
|
||||
get reason () {
|
||||
return stream.errored
|
||||
return abortReason
|
||||
},
|
||||
abort (reason) {
|
||||
if (aborted) {
|
||||
return
|
||||
}
|
||||
aborted = true
|
||||
stream.destroy(reason ?? new AbortError())
|
||||
abortReason = reason ?? new AbortError()
|
||||
stream.destroy(abortReason)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+22
-9
@@ -1,6 +1,6 @@
|
||||
'use strict'
|
||||
|
||||
const { createInflate, createGunzip, createBrotliDecompress, createZstdDecompress } = require('node:zlib')
|
||||
const { createInflate, createGunzip, createBrotliDecompress, createZstdDecompress, constants } = require('node:zlib')
|
||||
const { pipeline, Transform: TransformStream } = require('node:stream')
|
||||
const { InvalidArgumentError, ResponseExceededMaxSizeError } = require('../core/errors')
|
||||
const DecoratorHandler = require('../handler/decorator-handler')
|
||||
@@ -63,6 +63,10 @@ class DecompressController {
|
||||
}
|
||||
}
|
||||
|
||||
// `compress` and `x-compress` are deliberately absent. RFC 9110 section
|
||||
// 8.4.1.1 defines them as the UNIX compress (LZW) format, which zlib cannot
|
||||
// read, so inflating them turns a readable response into a Z_DATA_ERROR.
|
||||
// fetch() leaves them alone, and so does this interceptor.
|
||||
/** @type {Record<string, () => DecompressorStream>} */
|
||||
const supportedEncodings = {
|
||||
__proto__: null,
|
||||
@@ -70,9 +74,8 @@ const supportedEncodings = {
|
||||
'x-gzip': createGunzip,
|
||||
br: createBrotliDecompress,
|
||||
deflate: createInflate,
|
||||
compress: createInflate,
|
||||
'x-compress': createInflate,
|
||||
zstd: createZstdDecompress
|
||||
// https://www.rfc-editor.org/rfc/rfc9659.html#section-3
|
||||
zstd: createZstdDecompress.bind(null, { params: { [constants.ZSTD_d_windowLogMax]: 23 } })
|
||||
}
|
||||
|
||||
const defaultSkipStatusCodes = /** @type {const} */ ([204, 304])
|
||||
@@ -220,9 +223,14 @@ class DecompressHandler extends DecoratorHandler {
|
||||
this.#decompressedSize = decompressedSize
|
||||
}
|
||||
|
||||
const result = super.onResponseData(this.#controller, chunk)
|
||||
if (result === false && !this.#controller.paused) {
|
||||
this.#controller.pause()
|
||||
try {
|
||||
const result = super.onResponseData(this.#controller, chunk)
|
||||
if (result === false && !this.#controller.paused) {
|
||||
this.#controller.pause()
|
||||
}
|
||||
} catch (err) {
|
||||
this.#fail(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
} while (this.#drainRequested && !this.#terminated && !this.#controller.paused)
|
||||
@@ -239,9 +247,14 @@ class DecompressHandler extends DecoratorHandler {
|
||||
return
|
||||
}
|
||||
|
||||
this.#terminated = true
|
||||
this.#cleanupDecompressors()
|
||||
super.onResponseEnd(this.#controller, this.#trailers)
|
||||
try {
|
||||
super.onResponseEnd(this.#controller, this.#trailers)
|
||||
} catch (err) {
|
||||
this.#fail(err)
|
||||
return
|
||||
}
|
||||
this.#terminated = true
|
||||
}
|
||||
|
||||
#onDecompressionEnd () {
|
||||
|
||||
+11
@@ -190,6 +190,16 @@ class DNSInstance {
|
||||
newOpts.affinity
|
||||
)
|
||||
|
||||
// The lookup succeeded, but nothing it returned is usable here: with
|
||||
// dualStack disabled and an affinity set, records of the other family
|
||||
// cannot be picked. Running the lookup again would return the same
|
||||
// records, so report it the way an empty result is reported.
|
||||
if (ip == null) {
|
||||
this.storage.delete(origin.hostname)
|
||||
cb(new InformationalError('No DNS entries found'))
|
||||
return
|
||||
}
|
||||
|
||||
let port
|
||||
if (typeof ip.port === 'number') {
|
||||
port = `:${ip.port}`
|
||||
@@ -346,6 +356,7 @@ class DNSInstance {
|
||||
// We delete expired records
|
||||
// It is possible that they have different TTL, so we manage them individually
|
||||
family.ips.splice(position, 1)
|
||||
return this.pickFamily(origin, ipFamily)
|
||||
}
|
||||
|
||||
return ip
|
||||
|
||||
+72
-28
@@ -2,7 +2,9 @@
|
||||
|
||||
// const { parseHeaders } = require('../core/util')
|
||||
const DecoratorHandler = require('../handler/decorator-handler')
|
||||
const { ResponseError } = require('../core/errors')
|
||||
const { InvalidArgumentError, ResponseError } = require('../core/errors')
|
||||
|
||||
const defaultMaxSize = 1024 * 1024
|
||||
|
||||
class ResponseErrorHandler extends DecoratorHandler {
|
||||
#statusCode
|
||||
@@ -10,9 +12,13 @@ class ResponseErrorHandler extends DecoratorHandler {
|
||||
#decoder
|
||||
#headers
|
||||
#body
|
||||
#bodySize
|
||||
#bodyTruncated
|
||||
#maxSize
|
||||
|
||||
constructor (_opts, { handler }) {
|
||||
constructor ({ maxSize }, { handler }) {
|
||||
super(handler)
|
||||
this.#maxSize = maxSize
|
||||
}
|
||||
|
||||
#checkContentType (contentType) {
|
||||
@@ -25,6 +31,8 @@ class ResponseErrorHandler extends DecoratorHandler {
|
||||
this.#decoder = null
|
||||
this.#headers = null
|
||||
this.#body = ''
|
||||
this.#bodySize = 0
|
||||
this.#bodyTruncated = false
|
||||
|
||||
return super.onRequestStart(controller, context)
|
||||
}
|
||||
@@ -43,39 +51,69 @@ class ResponseErrorHandler extends DecoratorHandler {
|
||||
}
|
||||
}
|
||||
|
||||
#createResponseError () {
|
||||
this.#body += this.#decoder?.decode(undefined, { stream: false }) ?? ''
|
||||
this.#decoder = null
|
||||
|
||||
if (!this.#bodyTruncated && this.#checkContentType('application/json')) {
|
||||
try {
|
||||
this.#body = JSON.parse(this.#body)
|
||||
} catch {
|
||||
// Do nothing...
|
||||
}
|
||||
}
|
||||
|
||||
let err
|
||||
const stackTraceLimit = Error.stackTraceLimit
|
||||
Error.stackTraceLimit = 0
|
||||
try {
|
||||
err = new ResponseError('Response Error', this.#statusCode, {
|
||||
body: this.#body,
|
||||
bodyTruncated: this.#bodyTruncated,
|
||||
headers: this.#headers
|
||||
})
|
||||
} finally {
|
||||
Error.stackTraceLimit = stackTraceLimit
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
onResponseData (controller, chunk) {
|
||||
if (this.#statusCode < 400) {
|
||||
return super.onResponseData(controller, chunk)
|
||||
}
|
||||
|
||||
this.#body += this.#decoder?.decode(chunk, { stream: true }) ?? ''
|
||||
if (this.#decoder == null) {
|
||||
return
|
||||
}
|
||||
|
||||
if (this.#maxSize === 0) {
|
||||
this.#body += this.#decoder.decode(chunk, { stream: true })
|
||||
return
|
||||
}
|
||||
|
||||
const remaining = this.#maxSize - this.#bodySize
|
||||
|
||||
if (chunk.length <= remaining) {
|
||||
this.#bodySize += chunk.length
|
||||
this.#body += this.#decoder.decode(chunk, { stream: true })
|
||||
return
|
||||
}
|
||||
|
||||
if (remaining > 0) {
|
||||
this.#body += this.#decoder.decode(chunk.subarray(0, remaining), { stream: true })
|
||||
this.#bodySize = this.#maxSize
|
||||
}
|
||||
|
||||
this.#bodyTruncated = true
|
||||
this.#body += this.#decoder.decode(undefined, { stream: false })
|
||||
this.#decoder = null
|
||||
}
|
||||
|
||||
onResponseEnd (controller, trailers) {
|
||||
if (this.#statusCode >= 400) {
|
||||
this.#body += this.#decoder?.decode(undefined, { stream: false }) ?? ''
|
||||
|
||||
if (this.#checkContentType('application/json')) {
|
||||
try {
|
||||
this.#body = JSON.parse(this.#body)
|
||||
} catch {
|
||||
// Do nothing...
|
||||
}
|
||||
}
|
||||
|
||||
let err
|
||||
const stackTraceLimit = Error.stackTraceLimit
|
||||
Error.stackTraceLimit = 0
|
||||
try {
|
||||
err = new ResponseError('Response Error', this.#statusCode, {
|
||||
body: this.#body,
|
||||
headers: this.#headers
|
||||
})
|
||||
} finally {
|
||||
Error.stackTraceLimit = stackTraceLimit
|
||||
}
|
||||
|
||||
super.onResponseError(controller, err)
|
||||
super.onResponseError(controller, this.#createResponseError())
|
||||
} else {
|
||||
super.onResponseEnd(controller, trailers)
|
||||
}
|
||||
@@ -86,10 +124,16 @@ class ResponseErrorHandler extends DecoratorHandler {
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = () => {
|
||||
module.exports = (opts = {}) => {
|
||||
const { maxSize = defaultMaxSize } = opts
|
||||
|
||||
if (!Number.isSafeInteger(maxSize) || maxSize < 0) {
|
||||
throw new InvalidArgumentError('maxSize must be a non-negative integer')
|
||||
}
|
||||
|
||||
return (dispatch) => {
|
||||
return function Intercept (opts, handler) {
|
||||
return dispatch(opts, new ResponseErrorHandler(opts, { handler }))
|
||||
return dispatch(opts, new ResponseErrorHandler({ maxSize }, { handler }))
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
> docker run --rm --platform=linux/x86_64 --user 1001:1001 --mount type=bind,source=/home/runner/work/node/node/deps/undici/src/lib/llhttp,target=/home/node/build/lib/llhttp --mount type=bind,source=/home/runner/work/node/node/deps/undici/src/build,target=/home/node/build/build --mount type=bind,source=/home/runner/work/node/node/deps/undici/src/deps,target=/home/node/build/deps -t ghcr.io/nodejs/wasm-builder@sha256:975f391d907e42a75b8c72eb77c782181e941608687d4d8694c3e9df415a0970 node build/wasm.js
|
||||
> docker run --rm --platform=linux/x86_64 --user 1001:1001 --mount type=bind,source=/home/runner/work/node/node/deps/undici/src/lib/llhttp,target=/home/node/build/lib/llhttp --mount type=bind,source=/home/runner/work/node/node/deps/undici/src/build,target=/home/node/build/build --mount type=bind,source=/home/runner/work/node/node/deps/undici/src/deps,target=/home/node/build/deps -t ghcr.io/nodejs/wasm-builder@sha256:975f391d907e42a75b8c72eb77c782181e941608687d4d8694c3e9df415a0970 node build/llhttp.js
|
||||
|
||||
|
||||
alpine-baselayout-3.6.5-r0
|
||||
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
ISC License
|
||||
|
||||
Copyright (c) 2023, and above Paolo Insogna, NearForm and other contributors
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
Vendored
+1002
File diff suppressed because it is too large.
Load diff
Vendored
+1002
File diff suppressed because it is too large.
Load diff
+11
@@ -55,6 +55,17 @@ class MockAgent extends Dispatcher {
|
||||
}
|
||||
}
|
||||
|
||||
// WebSocket and EventSource read their receive limits from the dispatcher
|
||||
// they are given, so report the settings of the agent that makes real
|
||||
// connections.
|
||||
get webSocketOptions () {
|
||||
return this[kAgent].webSocketOptions
|
||||
}
|
||||
|
||||
get eventSourceOptions () {
|
||||
return this[kAgent].eventSourceOptions
|
||||
}
|
||||
|
||||
get (origin) {
|
||||
// Normalize origin to handle URL objects and case-insensitive hostnames
|
||||
const normalizedOrigin = normalizeOrigin(origin)
|
||||
|
||||
+3
-2
@@ -4,6 +4,7 @@ const { writeFile, readFile, mkdir } = require('node:fs/promises')
|
||||
const { dirname, resolve } = require('node:path')
|
||||
const { setTimeout, clearTimeout } = require('node:timers')
|
||||
const { InvalidArgumentError, UndiciError } = require('../core/errors')
|
||||
const { setHeader } = require('../core/util')
|
||||
const { hashId, isUrlExcludedFactory, normalizeHeaders, createHeaderFilters } = require('./snapshot-utils')
|
||||
|
||||
/**
|
||||
@@ -169,7 +170,7 @@ function filterHeadersForMatching (headers, headerFilters, matchOptions = {}) {
|
||||
if (!match.has(headerKey)) continue
|
||||
}
|
||||
|
||||
filtered[headerKey] = value
|
||||
setHeader(filtered, headerKey, value)
|
||||
}
|
||||
|
||||
return filtered
|
||||
@@ -198,7 +199,7 @@ function filterHeadersForStorage (headers, headerFilters, matchOptions = {}) {
|
||||
// Skip if in exclude list (for security)
|
||||
if (excludeSet.has(headerKey)) continue
|
||||
|
||||
filtered[headerKey] = value
|
||||
setHeader(filtered, headerKey, value)
|
||||
}
|
||||
|
||||
return filtered
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
'use strict'
|
||||
|
||||
const { InvalidArgumentError } = require('../core/errors')
|
||||
const { setHeader } = require('../core/util')
|
||||
const { runtimeFeatures } = require('../util/runtime-features.js')
|
||||
|
||||
/**
|
||||
@@ -116,7 +117,7 @@ function normalizeHeaders (headers) {
|
||||
// Convert Buffers to strings if needed
|
||||
const keyStr = Buffer.isBuffer(key) ? key.toString() : key
|
||||
const valueStr = Buffer.isBuffer(value) ? value.toString() : value
|
||||
normalizedHeaders[keyStr.toLowerCase()] = valueStr
|
||||
setHeader(normalizedHeaders, keyStr.toLowerCase(), valueStr)
|
||||
}
|
||||
}
|
||||
return normalizedHeaders
|
||||
@@ -126,7 +127,7 @@ function normalizeHeaders (headers) {
|
||||
if (headers && typeof headers === 'object') {
|
||||
for (const [key, value] of Object.entries(headers)) {
|
||||
if (key && typeof key === 'string') {
|
||||
normalizedHeaders[key.toLowerCase()] = Array.isArray(value) ? value.join(', ') : String(value)
|
||||
setHeader(normalizedHeaders, key.toLowerCase(), Array.isArray(value) ? value.join(', ') : String(value))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+11
-5
@@ -4,7 +4,8 @@ const {
|
||||
safeHTTPMethods,
|
||||
pathHasQueryOrFragment,
|
||||
hasSafeIterator,
|
||||
isValidHTTPToken
|
||||
isValidHTTPToken,
|
||||
setHeader
|
||||
} = require('../core/util')
|
||||
|
||||
const { serializePathWithQuery } = require('../core/util')
|
||||
@@ -206,15 +207,20 @@ function makeCacheKey (opts, origin = getRequestOrigin(opts)) {
|
||||
|
||||
function appendHeader (headers, key, val) {
|
||||
const headerName = key.toLowerCase()
|
||||
const current = headers[headerName]
|
||||
// Reading `headers[headerName]` directly would resolve `__proto__` (and any
|
||||
// other inherited name) through the prototype chain rather than report the
|
||||
// header as absent.
|
||||
const current = Object.hasOwn(headers, headerName)
|
||||
? headers[headerName]
|
||||
: undefined
|
||||
const values = Array.isArray(val) ? val : [val]
|
||||
|
||||
if (current === undefined) {
|
||||
headers[headerName] = Array.isArray(val) ? val.slice() : val
|
||||
setHeader(headers, headerName, Array.isArray(val) ? val.slice() : val)
|
||||
} else if (Array.isArray(current)) {
|
||||
current.push(...values)
|
||||
} else {
|
||||
headers[headerName] = [current, ...values]
|
||||
setHeader(headers, headerName, [current, ...values])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -732,7 +738,7 @@ function makeDeduplicationKey (cacheKey, excludeHeaders) {
|
||||
if (excludeHeaders?.has(header.toLowerCase())) {
|
||||
continue
|
||||
}
|
||||
headers[header] = cacheKey.headers[header]
|
||||
setHeader(headers, header, cacheKey.headers[header])
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+19
-2
@@ -317,8 +317,25 @@ function stringify (cookie) {
|
||||
|
||||
// A numeric 0 is the Unix epoch, not an absent value -- the same reason the
|
||||
// Max-Age check above tests the type rather than truthiness.
|
||||
if (cookie.expires != null && cookie.expires.toString() !== 'Invalid Date') {
|
||||
out.push(`Expires=${toIMFDate(cookie.expires)}`)
|
||||
//
|
||||
// expires is Date | number, so the "Invalid Date" check only guards the Date
|
||||
// form. A number that is not a valid time value (NaN, +/-Infinity, or outside
|
||||
// the Date range) would otherwise reach toIMFDate, which splices undefined and
|
||||
// NaN into the header value instead of failing.
|
||||
if (cookie.expires != null) {
|
||||
const expiresMs = cookie.expires instanceof Date
|
||||
? cookie.expires.getTime()
|
||||
: cookie.expires
|
||||
|
||||
// The largest time value a Date can represent, in milliseconds, i.e.
|
||||
// 100,000,000 days either side of the epoch (ECMA-262 Date Time Values).
|
||||
// Anything within it is safe for toIMFDate to format; anything beyond it
|
||||
// produces an invalid Date and must be ignored instead.
|
||||
const maxTimeValue = 8640000000000000
|
||||
|
||||
if (typeof expiresMs === 'number' && Number.isFinite(expiresMs) && Math.abs(expiresMs) <= maxTimeValue) {
|
||||
out.push(`Expires=${toIMFDate(cookie.expires)}`)
|
||||
}
|
||||
}
|
||||
|
||||
if (cookie.sameSite) {
|
||||
|
||||
+69
-15
@@ -31,6 +31,12 @@ const EVENT = Buffer.from('event')
|
||||
const ID = Buffer.from('id')
|
||||
const RETRY = Buffer.from('retry')
|
||||
|
||||
// Each data field creates a string node, and each unconsumed input chunk keeps
|
||||
// a Buffer wrapper. The absolute ceiling protects the large default byte limit.
|
||||
const minParserItems = 1024
|
||||
const maxParserItems = 131072
|
||||
const bytesPerParserItem = 128
|
||||
|
||||
function isASCIINumberBytes (buffer, start) {
|
||||
if (start >= buffer.length) {
|
||||
return false
|
||||
@@ -123,8 +129,13 @@ class EventSourceStream extends Transform {
|
||||
pos = 0
|
||||
lineChunkIndex = 0
|
||||
linePos = 0
|
||||
eventDataSize = 0
|
||||
lineLength = 0
|
||||
eventSize = 0
|
||||
eventFieldSizes = { data: 0, event: 0, id: 0, retry: 0 }
|
||||
dataLineCount = 0
|
||||
maxEventSize
|
||||
maxDataLines
|
||||
maxBufferedChunks
|
||||
|
||||
event = {
|
||||
data: undefined,
|
||||
@@ -149,6 +160,11 @@ class EventSourceStream extends Transform {
|
||||
|
||||
this.state = options.eventSourceSettings || {}
|
||||
this.maxEventSize = options.maxEventSize ?? defaultMaxEventSize
|
||||
const parserItemLimit = this.maxEventSize > 0
|
||||
? Math.min(maxParserItems, Math.max(minParserItems, Math.floor(this.maxEventSize / bytesPerParserItem)))
|
||||
: 0
|
||||
this.maxDataLines = parserItemLimit
|
||||
this.maxBufferedChunks = parserItemLimit
|
||||
if (options.push) {
|
||||
this.push = options.push
|
||||
}
|
||||
@@ -166,6 +182,14 @@ class EventSourceStream extends Transform {
|
||||
return
|
||||
}
|
||||
|
||||
// A leading line ending can immediately release the currently buffered
|
||||
// line, even when it uses the final allowed chunk slot.
|
||||
if (this.maxEventSize > 0 &&
|
||||
this.chunks.length >= this.maxBufferedChunks &&
|
||||
chunk[0] !== LF && chunk[0] !== CR) {
|
||||
callback(createMaxEventSizeExceededError())
|
||||
return
|
||||
}
|
||||
this.chunks.push(chunk)
|
||||
|
||||
// Strip leading byte-order-mark if we opened the stream and started
|
||||
@@ -258,12 +282,25 @@ class EventSourceStream extends Transform {
|
||||
continue
|
||||
}
|
||||
|
||||
// readLine() is only called after CR or LF. Reject an unfinished line
|
||||
// before it can retain an unbounded number of decoded chunks. The seven
|
||||
// extra bytes allow the longest field prefix ("event: " or "retry: ").
|
||||
if (this.maxEventSize > 0 && ++this.lineLength > this.maxEventSize + 7) {
|
||||
callback(createMaxEventSizeExceededError())
|
||||
return
|
||||
}
|
||||
this.advanceCursor()
|
||||
}
|
||||
|
||||
callback()
|
||||
}
|
||||
|
||||
_destroy (error, callback) {
|
||||
this.chunks.length = 0
|
||||
this.clearEvent()
|
||||
super._destroy(error, callback)
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Buffer} line
|
||||
* @param {EventSourceStreamEvent} event
|
||||
@@ -300,12 +337,12 @@ class EventSourceStream extends Transform {
|
||||
}
|
||||
|
||||
if (isFieldName(line, fieldLength, DATA)) {
|
||||
const valueBytes = line.length - valueStart
|
||||
const eventDataSize = this.eventDataSize + (event.data === undefined ? 0 : 1) + valueBytes
|
||||
|
||||
if (this.maxEventSize > 0 && eventDataSize > this.maxEventSize) {
|
||||
if (this.maxEventSize > 0 && this.dataLineCount >= this.maxDataLines) {
|
||||
throw createMaxEventSizeExceededError()
|
||||
}
|
||||
const valueBytes = line.length - valueStart
|
||||
const dataSize = this.eventFieldSizes.data + (event.data === undefined ? 0 : 1) + valueBytes
|
||||
this.setEventFieldSize('data', dataSize)
|
||||
|
||||
const value = line.toString('utf8', valueStart)
|
||||
|
||||
@@ -314,12 +351,13 @@ class EventSourceStream extends Transform {
|
||||
} else {
|
||||
event.data += `\n${value}`
|
||||
}
|
||||
this.eventDataSize = eventDataSize
|
||||
this.dataLineCount++
|
||||
return
|
||||
}
|
||||
|
||||
if (isFieldName(line, fieldLength, RETRY)) {
|
||||
if (isASCIINumberBytes(line, valueStart)) {
|
||||
this.setEventFieldSize('retry', line.length - valueStart)
|
||||
event.retry = line.toString('utf8', valueStart)
|
||||
}
|
||||
return
|
||||
@@ -327,20 +365,29 @@ class EventSourceStream extends Transform {
|
||||
|
||||
if (isFieldName(line, fieldLength, ID)) {
|
||||
if (isValidLastEventIdBytes(line, valueStart)) {
|
||||
this.setEventFieldSize('id', line.length - valueStart)
|
||||
event.id = line.toString('utf8', valueStart)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (isFieldName(line, fieldLength, EVENT)) {
|
||||
const value = line.toString('utf8', valueStart)
|
||||
|
||||
if (value.length > 0) {
|
||||
event.event = value
|
||||
if (valueStart < line.length) {
|
||||
this.setEventFieldSize('event', line.length - valueStart)
|
||||
event.event = line.toString('utf8', valueStart)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setEventFieldSize (field, size) {
|
||||
const eventSize = this.eventSize - this.eventFieldSizes[field] + size
|
||||
if (this.maxEventSize > 0 && eventSize > this.maxEventSize) {
|
||||
throw createMaxEventSizeExceededError()
|
||||
}
|
||||
this.eventSize = eventSize
|
||||
this.eventFieldSizes[field] = size
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {EventSourceStreamEvent} event
|
||||
*/
|
||||
@@ -371,7 +418,12 @@ class EventSourceStream extends Transform {
|
||||
this.event.event = undefined
|
||||
this.event.id = undefined
|
||||
this.event.retry = undefined
|
||||
this.eventDataSize = 0
|
||||
this.eventSize = 0
|
||||
this.dataLineCount = 0
|
||||
this.eventFieldSizes.data = 0
|
||||
this.eventFieldSizes.event = 0
|
||||
this.eventFieldSizes.id = 0
|
||||
this.eventFieldSizes.retry = 0
|
||||
}
|
||||
|
||||
hasPendingEvent () {
|
||||
@@ -407,14 +459,16 @@ class EventSourceStream extends Transform {
|
||||
syncLineStartToCursor () {
|
||||
this.lineChunkIndex = this.chunkIndex
|
||||
this.linePos = this.pos
|
||||
this.lineLength = 0
|
||||
this.dropConsumedChunks()
|
||||
}
|
||||
|
||||
dropConsumedChunks () {
|
||||
while (this.lineChunkIndex > 0) {
|
||||
this.chunks.shift()
|
||||
this.lineChunkIndex--
|
||||
this.chunkIndex--
|
||||
if (this.lineChunkIndex > 0) {
|
||||
const consumed = this.lineChunkIndex
|
||||
this.chunks.splice(0, consumed)
|
||||
this.lineChunkIndex = 0
|
||||
this.chunkIndex -= consumed
|
||||
}
|
||||
|
||||
if (this.chunkIndex === this.chunks.length) {
|
||||
|
||||
+25
-2
@@ -7,6 +7,7 @@ const { EventSourceStream } = require('./eventsource-stream')
|
||||
const { parseMIMEType } = require('../fetch/data-url')
|
||||
const { createFastMessageEvent } = require('../websocket/events')
|
||||
const { isNetworkError } = require('../fetch/response')
|
||||
const { cloneRequest } = require('../fetch/request')
|
||||
const { isValidHeaderValue, kEnumerableProperty } = require('../../core/util')
|
||||
const { environmentSettingsObject } = require('../fetch/util')
|
||||
const { createPotentialCORSRequest } = require('./util')
|
||||
@@ -29,6 +30,14 @@ let experimentalWarned = false
|
||||
*/
|
||||
const defaultReconnectionTime = 3000
|
||||
|
||||
/**
|
||||
* The largest delay setTimeout supports. Larger values (including Infinity)
|
||||
* make Node.js fire the timer after 1 ms instead, which would turn a large
|
||||
* reconnection time into a reconnect storm.
|
||||
* @type {number}
|
||||
*/
|
||||
const maxReconnectionTime = 2 ** 31 - 1
|
||||
|
||||
/**
|
||||
* The readyState attribute represents the state of the connection.
|
||||
* @typedef ReadyState
|
||||
@@ -222,8 +231,22 @@ class EventSource extends EventTarget {
|
||||
|
||||
this.#readyState = CONNECTING
|
||||
|
||||
// Fetch a copy of the request so that every connection starts from the
|
||||
// original request. Fetch mutates the request it is given (URL list,
|
||||
// redirect count, response tainting and, on cross-origin redirects,
|
||||
// headers), so reusing it makes reconnects go to the last redirect
|
||||
// target and, after 20 redirects in total, fail forever.
|
||||
// cloneRequest() shares the URL list, so copy it as well.
|
||||
// 301/308 permanent redirects are handled the same as 302/307 temporary
|
||||
// redirects. While the original EventSource spec required that permanent
|
||||
// redirects be handled, WHATWG removed that requirement and has not
|
||||
// yet opted to restore it... therefore all redirects gets handled the
|
||||
// same.
|
||||
const request = cloneRequest(this.#request)
|
||||
request.urlList = [...this.#request.urlList]
|
||||
|
||||
const fetchParams = {
|
||||
request: this.#request,
|
||||
request,
|
||||
dispatcher: this.#dispatcher
|
||||
}
|
||||
|
||||
@@ -361,7 +384,7 @@ class EventSource extends EventTarget {
|
||||
|
||||
// 4. Fetch request and process the response obtained in this fashion, if any, as described earlier in this section.
|
||||
this.#connect()
|
||||
}, this.#state.reconnectionTime)?.unref()
|
||||
}, Math.min(this.#state.reconnectionTime, maxReconnectionTime))?.unref()
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+47
-38
@@ -39,7 +39,6 @@ const streamRegistry = new FinalizationRegistry((weakRef) => {
|
||||
function extractBody (object, keepalive = false) {
|
||||
// 1. Let stream be null.
|
||||
let stream = null
|
||||
let controller = null
|
||||
|
||||
// 2. If object is a ReadableStream object, then set stream to object.
|
||||
if (webidl.is.ReadableStream(object)) {
|
||||
@@ -52,11 +51,44 @@ function extractBody (object, keepalive = false) {
|
||||
// 4. Otherwise, set stream to a new ReadableStream object, and set
|
||||
// up stream with byte reading support.
|
||||
stream = new ReadableStream({
|
||||
pull () {},
|
||||
start (c) {
|
||||
controller = c
|
||||
start () {},
|
||||
async pull (controller) {
|
||||
// 19.1. Run action.
|
||||
const result = action()
|
||||
|
||||
const iterator = result?.[Symbol.asyncIterator]?.()
|
||||
if (iterator == null) {
|
||||
// 19.2. Whenever one or more bytes are available and stream is not errored,
|
||||
// enqueue the result of creating a Uint8Array from the available bytes into stream.
|
||||
if (result?.length && !isErrored(stream)) {
|
||||
controller.enqueue(typeof result === 'string' ? textEncoder.encode(result) : new Uint8Array(result))
|
||||
}
|
||||
|
||||
// 19.3. When running action is done, close stream.
|
||||
queueMicrotask(() => readableStreamClose(controller))
|
||||
return
|
||||
}
|
||||
|
||||
while (true) {
|
||||
const { value, done } = await iterator.next()
|
||||
|
||||
// 19.3. When running action is done, close stream.
|
||||
if (done) {
|
||||
queueMicrotask(() => readableStreamClose(controller))
|
||||
return
|
||||
}
|
||||
|
||||
// 19.2. Whenever one or more bytes are available and stream is not errored,
|
||||
// enqueue the result of creating a Uint8Array from the available bytes into stream.
|
||||
if (value.length && !isErrored(stream)) {
|
||||
controller.enqueue(new Uint8Array(value))
|
||||
return
|
||||
}
|
||||
}
|
||||
},
|
||||
cancel (reason) {
|
||||
return action()[Symbol.asyncIterator]?.().return(reason)
|
||||
},
|
||||
cancel () {},
|
||||
type: 'bytes'
|
||||
})
|
||||
}
|
||||
@@ -155,7 +187,7 @@ function extractBody (object, keepalive = false) {
|
||||
// Set source to object.
|
||||
source = object
|
||||
|
||||
action = async function * () {
|
||||
const parts = (async function * () {
|
||||
for (const part of blobParts) {
|
||||
if (part.stream) {
|
||||
yield * part.stream()
|
||||
@@ -163,7 +195,8 @@ function extractBody (object, keepalive = false) {
|
||||
yield part
|
||||
}
|
||||
}
|
||||
}
|
||||
})()
|
||||
action = () => parts
|
||||
|
||||
// Set type to `multipart/form-data; boundary=`,
|
||||
// followed by the multipart/form-data boundary string generated
|
||||
@@ -208,45 +241,21 @@ function extractBody (object, keepalive = false) {
|
||||
}))
|
||||
}
|
||||
|
||||
// 11. If source is a byte sequence, then set action to a
|
||||
// 18. If source is a byte sequence, then set action to a
|
||||
// step that returns source and length to source’s length.
|
||||
if (typeof source === 'string' || isUint8Array(source)) {
|
||||
action = () => {
|
||||
length = typeof source === 'string' ? Buffer.byteLength(source) : source.length
|
||||
return source
|
||||
}
|
||||
action = () => source
|
||||
length = typeof source === 'string' ? Buffer.byteLength(source) : source.length
|
||||
}
|
||||
|
||||
// 12. If action is non-null, then run these steps in parallel:
|
||||
if (action != null) {
|
||||
;(async () => {
|
||||
// 1. Run action.
|
||||
const result = action()
|
||||
// 19. If action is non-null, then run these steps in parallel:
|
||||
// Note: this is done in the pull method of the stream created above
|
||||
|
||||
// 2. Whenever one or more bytes are available and stream is not errored,
|
||||
// enqueue the result of creating a Uint8Array from the available bytes into stream.
|
||||
const iterator = result?.[Symbol.asyncIterator]?.()
|
||||
if (iterator) {
|
||||
for await (const bytes of iterator) {
|
||||
if (isErrored(stream)) break
|
||||
if (bytes.length) {
|
||||
controller.enqueue(new Uint8Array(bytes))
|
||||
}
|
||||
}
|
||||
} else if (result?.length && !isErrored(stream)) {
|
||||
controller.enqueue(typeof result === 'string' ? textEncoder.encode(result) : new Uint8Array(result))
|
||||
}
|
||||
|
||||
// 3. When running action is done, close stream.
|
||||
queueMicrotask(() => readableStreamClose(controller))
|
||||
})()
|
||||
}
|
||||
|
||||
// 13. Let body be a body whose stream is stream, source is source,
|
||||
// 20. Let body be a body whose stream is stream, source is source,
|
||||
// and length is length.
|
||||
const body = { stream, source, length }
|
||||
|
||||
// 14. Return (body, type).
|
||||
// 21. Return (body, type).
|
||||
return [body, type]
|
||||
}
|
||||
|
||||
|
||||
+12
-4
@@ -261,19 +261,27 @@ function parseContentDispositionAttribute (input, position) {
|
||||
position
|
||||
)
|
||||
|
||||
// Check for utf-8'' prefix (case insensitive)
|
||||
const charsetSeparator = headerValue.indexOf(0x27)
|
||||
const languageSeparator = charsetSeparator === -1
|
||||
? -1
|
||||
: headerValue.indexOf(0x27, charsetSeparator + 1)
|
||||
|
||||
if (charsetSeparator === -1 || languageSeparator === -1) {
|
||||
throw parsingError('expected charset and language separators in extended value')
|
||||
}
|
||||
|
||||
if (
|
||||
charsetSeparator !== 5 ||
|
||||
(headerValue[0] !== 0x75 && headerValue[0] !== 0x55) || // u or U
|
||||
(headerValue[1] !== 0x74 && headerValue[1] !== 0x54) || // t or T
|
||||
(headerValue[2] !== 0x66 && headerValue[2] !== 0x46) || // f or F
|
||||
headerValue[3] !== 0x2d || // -
|
||||
headerValue[4] !== 0x38 // 8
|
||||
) {
|
||||
throw parsingError('unknown encoding, expected utf-8\'\'')
|
||||
throw parsingError('unknown charset, expected utf-8')
|
||||
}
|
||||
|
||||
// Skip utf-8'' and decode the rest
|
||||
value = decodeURIComponent(decoder.decode(headerValue.subarray(7)))
|
||||
value = decodeURIComponent(decoder.decode(headerValue.subarray(languageSeparator + 1)))
|
||||
} else if (input[position.position] === 0x22 /* " */) {
|
||||
// Quoted string
|
||||
position.position++ // skip opening quote
|
||||
|
||||
+2
-2
@@ -3,7 +3,7 @@
|
||||
'use strict'
|
||||
|
||||
const { kConstruct } = require('../../core/symbols')
|
||||
const { kEnumerableProperty } = require('../../core/util')
|
||||
const { kEnumerableProperty, setHeader } = require('../../core/util')
|
||||
const {
|
||||
iteratorMixin,
|
||||
isValidHeaderName,
|
||||
@@ -320,7 +320,7 @@ class HeadersList {
|
||||
|
||||
if (this.headersMap.size !== 0) {
|
||||
for (const { name, value } of this.headersMap.values()) {
|
||||
headers[name] = value
|
||||
setHeader(headers, name, value)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+8
-4
@@ -2280,8 +2280,6 @@ async function httpNetworkFetch (
|
||||
appendHeadersListFromResponseHeaders(headersList, headers, rawHeaders)
|
||||
const location = headersList.get('location', true)
|
||||
|
||||
this.body = new Readable({ read: () => controller.resume() })
|
||||
|
||||
const willFollow = location && request.redirect === 'follow' &&
|
||||
redirectStatusSet.has(status)
|
||||
|
||||
@@ -2299,7 +2297,7 @@ async function httpNetworkFetch (
|
||||
// CVE fix similar to urllib3 (GHSA-gm62-xv2j-4w53) and curl (CVE-2022-32206).
|
||||
const maxContentEncodings = 5
|
||||
if (codings.length > maxContentEncodings) {
|
||||
reject(new Error(`too many content-encodings in response: ${codings.length}, maximum allowed is ${maxContentEncodings}`))
|
||||
controller.abort(new Error(`too many content-encodings in response: ${codings.length}, maximum allowed is ${maxContentEncodings}`))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -2328,7 +2326,11 @@ async function httpNetworkFetch (
|
||||
} else if (coding === 'zstd') {
|
||||
decoders.push(zlib.createZstdDecompress({
|
||||
flush: zlib.constants.ZSTD_e_continue,
|
||||
finishFlush: zlib.constants.ZSTD_e_end
|
||||
finishFlush: zlib.constants.ZSTD_e_end,
|
||||
params: {
|
||||
// https://www.rfc-editor.org/rfc/rfc9659.html#section-3
|
||||
[zlib.constants.ZSTD_d_windowLogMax]: 23
|
||||
}
|
||||
}))
|
||||
} else {
|
||||
decoders.length = 0
|
||||
@@ -2337,6 +2339,8 @@ async function httpNetworkFetch (
|
||||
}
|
||||
}
|
||||
|
||||
this.body = new Readable({ read: () => controller.resume() })
|
||||
|
||||
const onError = (err) => this.onResponseError(controller, err)
|
||||
|
||||
resolve({
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
const assert = require('node:assert')
|
||||
const { runtimeFeatures } = require('../../util/runtime-features.js')
|
||||
const { asciiLowercase } = require('../infra/index.js')
|
||||
|
||||
/**
|
||||
* @typedef {object} Metadata
|
||||
@@ -66,14 +67,12 @@ const getSRIHashAlgorithmIndex = /** @type {GetSRIHashAlgorithmIndex} */ (Map.pr
|
||||
|
||||
/**
|
||||
* @typedef IsValidSRIHashAlgorithm
|
||||
* @see https://w3c.github.io/webappsec-subresource-integrity/#valid-sri-hash-algorithm-token
|
||||
* @type {(algorithm: string) => algorithm is SRIHashAlgorithm}
|
||||
* @param {*} algorithm
|
||||
* @returns {algorithm is SRIHashAlgorithm}
|
||||
*/
|
||||
|
||||
const isValidSRIHashAlgorithm = /** @type {IsValidSRIHashAlgorithm} */ (
|
||||
Map.prototype.has.bind(validSRIHashAlgorithmTokenSet)
|
||||
)
|
||||
const isValidSRIHashAlgorithm = (algorithm) => validSRIHashAlgorithmTokenSet.has(asciiLowercase(algorithm))
|
||||
|
||||
/**
|
||||
* @param {Uint8Array} bytes
|
||||
@@ -229,7 +228,8 @@ function parseMetadata (metadata) {
|
||||
// 8. Let metadata be the ordered map
|
||||
// «["alg" → algorithm, "val" → base64-value]».
|
||||
const metadata = {
|
||||
alg: algorithm,
|
||||
// Possible spec bug?
|
||||
alg: asciiLowercase(algorithm),
|
||||
val: base64Value
|
||||
}
|
||||
|
||||
|
||||
+25
-4
@@ -16,6 +16,7 @@ const { failWebsocketConnection } = require('./connection')
|
||||
const { WebsocketFrameSend } = require('./frame')
|
||||
const { PerMessageDeflate } = require('./permessage-deflate')
|
||||
const { MessageSizeExceededError } = require('../../core/errors')
|
||||
const { defaultWebSocketMaxFragments, defaultWebSocketMaxPayloadSize } = require('../../core/constants')
|
||||
|
||||
// This code was influenced by ws released under the MIT license.
|
||||
// Copyright (c) 2011 Einar Otto Stangvik <einaros@gmail.com>
|
||||
@@ -48,18 +49,25 @@ class ByteParser extends Writable {
|
||||
/**
|
||||
* @param {import('./websocket').Handler} handler
|
||||
* @param {Map<string, string>|null} extensions
|
||||
* @param {{ maxPayloadSize?: number }} [options]
|
||||
* @param {{ maxFragments?: number, maxPayloadSize?: number }} [options]
|
||||
* A missing value uses the default limit; `0` disables the limit.
|
||||
*/
|
||||
constructor (handler, extensions, options = {}) {
|
||||
super()
|
||||
|
||||
this.#handler = handler
|
||||
this.#extensions = extensions == null ? new Map() : extensions
|
||||
this.#maxFragments = options.maxFragments ?? 0
|
||||
this.#maxPayloadSize = options.maxPayloadSize ?? 0
|
||||
// Options come from the dispatcher's `webSocketOptions`, which only
|
||||
// DispatcherBase provides. Fall back to the defaults rather than to no
|
||||
// limit, so RetryAgent, MockAgent or a custom dispatcher can't turn off
|
||||
// the payload and decompression limits by accident.
|
||||
this.#maxFragments = options.maxFragments ?? defaultWebSocketMaxFragments
|
||||
this.#maxPayloadSize = options.maxPayloadSize ?? defaultWebSocketMaxPayloadSize
|
||||
|
||||
if (this.#extensions.has('permessage-deflate')) {
|
||||
this.#extensions.set('permessage-deflate', new PerMessageDeflate(extensions, options))
|
||||
this.#extensions.set('permessage-deflate', new PerMessageDeflate(extensions, {
|
||||
maxPayloadSize: this.#maxPayloadSize
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -244,6 +252,19 @@ class ByteParser extends Writable {
|
||||
if (isControlFrame(this.#info.opcode)) {
|
||||
this.#loop = this.parseControlFrame(body)
|
||||
this.#state = parserStates.INFO
|
||||
|
||||
// If the automatic PONG/CLOSE reply filled the socket's write buffer,
|
||||
// stop parsing and resume on drain so a PING flood cannot grow the
|
||||
// outbound queue without bound.
|
||||
if (this.#loop && this.#handler.socket.writableNeedDrain) {
|
||||
this.#loop = false
|
||||
this.#handler.socket.once('drain', () => {
|
||||
if (this.destroyed) return
|
||||
this.#loop = true
|
||||
this.run(callback)
|
||||
})
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if (!this.#info.compressed) {
|
||||
if (!this.writeFragments(body)) {
|
||||
|
||||
+43
-33
@@ -1,15 +1,15 @@
|
||||
{
|
||||
"name": "undici",
|
||||
"version": "8.11.2",
|
||||
"version": "8.12.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "undici",
|
||||
"version": "8.11.2",
|
||||
"version": "8.12.2",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@fastify/busboy": "3.2.2",
|
||||
"@fastify/busboy": "3.2.3",
|
||||
"@matteo.collina/tspl": "^0.2.0",
|
||||
"@metcoder95/https-pem": "^1.0.0",
|
||||
"@sinonjs/fake-timers": "^12.0.0",
|
||||
@@ -1209,9 +1209,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@fastify/busboy": {
|
||||
"version": "3.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-3.2.2.tgz",
|
||||
"integrity": "sha512-yXSS27qPExaXeuLvMRMXOLtpipzfQYNjG3FkunDWKGfMYjKuhFXko9CVzqxm8jcF+lmtS9Fd89QNdh9XDjnbNg==",
|
||||
"version": "3.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-3.2.3.tgz",
|
||||
"integrity": "sha512-fmo/IKgkenPzz3qTKG+sIUXdF/Kv83AkvvOXJHPTHJeKJbat8SsL1ihUaFaDotqoEl4UZ1Lf8Eb/3vK6eaWX2A==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
@@ -2806,9 +2806,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": {
|
||||
"version": "5.0.9",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz",
|
||||
"integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==",
|
||||
"version": "5.0.12",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz",
|
||||
"integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -3887,9 +3887,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/borp/node_modules/brace-expansion": {
|
||||
"version": "5.0.9",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz",
|
||||
"integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==",
|
||||
"version": "5.0.12",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz",
|
||||
"integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -4024,9 +4024,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/brace-expansion": {
|
||||
"version": "1.1.18",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz",
|
||||
"integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==",
|
||||
"version": "1.1.21",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz",
|
||||
"integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -5697,9 +5697,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/fast-check": {
|
||||
"version": "4.10.1",
|
||||
"resolved": "https://registry.npmjs.org/fast-check/-/fast-check-4.10.1.tgz",
|
||||
"integrity": "sha512-sB5Vghiu8MyCyToHoBVGsT0baZg3sZWNIY+a6Ct2EDrQJlT4YdH6MC1BSLNe3kX1k5i5g0q1O52XFgcKK/rGHg==",
|
||||
"version": "4.10.2",
|
||||
"resolved": "https://registry.npmjs.org/fast-check/-/fast-check-4.10.2.tgz",
|
||||
"integrity": "sha512-iK2f+YrcmoeGqk6fA0ea2bptcu/itMIm4NfEozq6N25+aG6h7s5HZbB/k1aV7b5w5sFLMCbbtRUsTVR+BgC3xw==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
@@ -6139,9 +6139,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/glob/node_modules/brace-expansion": {
|
||||
"version": "2.1.4",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz",
|
||||
"integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==",
|
||||
"version": "2.1.7",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz",
|
||||
"integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -7962,10 +7962,20 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/js-yaml": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
|
||||
"integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
|
||||
"version": "4.3.2",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz",
|
||||
"integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/puzrin"
|
||||
},
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/nodeca"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"argparse": "^2.0.1"
|
||||
@@ -10363,9 +10373,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/test-exclude/node_modules/brace-expansion": {
|
||||
"version": "5.0.9",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz",
|
||||
"integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==",
|
||||
"version": "5.0.12",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz",
|
||||
"integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -10798,9 +10808,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/undici": {
|
||||
"version": "6.28.0",
|
||||
"resolved": "https://registry.npmjs.org/undici/-/undici-6.28.0.tgz",
|
||||
"integrity": "sha512-LIY910g9TI13YS95lrMFrs8Rm/u/irgHeTWoKCoteeJ04CUJ92eEfj0rVn+7VKMPBpUPiUoBKfhNyLI23EE/KA==",
|
||||
"version": "6.29.0",
|
||||
"resolved": "https://registry.npmjs.org/undici/-/undici-6.29.0.tgz",
|
||||
"integrity": "sha512-R+RODBqp6i2pPflGdq+xIOUkl+RNfGgHwoinecKu/JCuf2uO06cOKoDbI2P7Dn6KcswdKwrczbU6IYJ6K8X+wg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
@@ -11157,9 +11167,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/ws": {
|
||||
"version": "8.21.3",
|
||||
"resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz",
|
||||
"integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==",
|
||||
"version": "8.22.0",
|
||||
"resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",
|
||||
"integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
|
||||
Vendored
+7
-5
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "undici",
|
||||
"version": "8.11.2",
|
||||
"version": "8.12.2",
|
||||
"description": "An HTTP/1.1 client, written from scratch for Node.js",
|
||||
"homepage": "https://undici.nodejs.org",
|
||||
"bugs": {
|
||||
@@ -63,13 +63,15 @@
|
||||
"types": "index.d.ts",
|
||||
"scripts": {
|
||||
"build:node": "esbuild index-fetch.js --bundle --platform=node --outfile=undici-fetch.js --define:esbuildDetection=1 --keep-names && node scripts/strip-comments.js",
|
||||
"build:wasm": "node build/wasm.js --docker",
|
||||
"build:milo": "node build/milo.js",
|
||||
"build:llhttp": "node build/llhttp.js --docker",
|
||||
"build:wasm": "node build/llhttp.js --docker",
|
||||
"generate-pem": "node scripts/generate-pem.js",
|
||||
"lint": "eslint --cache",
|
||||
"lint:fix": "eslint --fix --cache",
|
||||
"test": "npm run test:javascript && cross-env NODE_V8_COVERAGE= npm run test:typescript",
|
||||
"test:javascript": "npm run test:javascript:no-jest && npm run test:jest",
|
||||
"test:javascript:no-jest": "npm run generate-pem && npm run test:unit && npm run test:fetch && npm run test:node-fetch && npm run test:infra && npm run test:cache && npm run test:cache-interceptor && npm run test:interceptors && npm run test:cookies && npm run test:eventsource && npm run test:subresource-integrity && npm run test:wpt && npm run test:websocket && npm run test:node-test && npm run test:cache-tests",
|
||||
"test:javascript:no-jest": "npm run generate-pem && npm run test:unit && npm run test:fetch && npm run test:node-fetch && npm run test:infra && npm run test:cache && npm run test:cache-interceptor && npm run test:interceptors && npm run test:cookies && npm run test:eventsource && npm run test:subresource-integrity && npm run test:websocket && npm run test:node-test && npm run test:cache-tests",
|
||||
"test:javascript:without-intl": "npm run test:javascript:no-jest",
|
||||
"test:busboy": "borp --timeout 180000 -p \"test/busboy/*.js\"",
|
||||
"test:cache": "borp --timeout 180000 -p \"test/cache/*.js\"",
|
||||
@@ -97,7 +99,7 @@
|
||||
"test:websocket:autobahn": "node test/autobahn/client.js",
|
||||
"test:websocket:autobahn:report": "node test/autobahn/report.js",
|
||||
"test:wpt:setup": "node test/web-platform-tests/wpt-runner.mjs setup",
|
||||
"test:wpt": "npm run test:wpt:setup && node test/web-platform-tests/wpt-runner.mjs run /fetch /mimesniff /xhr /websockets /eventsource",
|
||||
"test:wpt": "npm run test:wpt:setup && node test/web-platform-tests/wpt-runner.mjs run /fetch /mimesniff /xhr /websockets /eventsource /service-workers",
|
||||
"test:cache-tests": "node test/cache-interceptor/cache-tests.mjs --ci",
|
||||
"coverage": "npm run coverage:clean && cross-env NODE_V8_COVERAGE=./coverage/tmp npm run test:javascript && npm run coverage:report",
|
||||
"coverage:ci": "npm run coverage:clean && cross-env NODE_V8_COVERAGE=./coverage/tmp npm run test:javascript && npm run coverage:report:ci",
|
||||
@@ -109,7 +111,7 @@
|
||||
"prepare": "husky && node ./scripts/platform-shell.js"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@fastify/busboy": "3.2.2",
|
||||
"@fastify/busboy": "3.2.3",
|
||||
"@matteo.collina/tspl": "^0.2.0",
|
||||
"@metcoder95/https-pem": "^1.0.0",
|
||||
"@sinonjs/fake-timers": "^12.0.0",
|
||||
|
||||
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user