Skip to content

WIP: Defer HTTP parsing to Hyper (h11 project) - #262

Draft
ian-otto wants to merge 36 commits into
cherrypy:mainfrom
ian-otto:h11-migrate
Draft

ian-otto wants to merge 36 commits into
cherrypy:mainfrom
ian-otto:h11-migrate

Conversation

@ian-otto

@ian-otto ian-otto commented Jan 22, 2020 •

Copy link
Copy Markdown
Contributor

❓ What kind of change does this PR introduce?

  • 🐞 bug fix
  • 🐣 feature
  • 📋 docs update
  • 📋 tests/coverage improvement
  • 📋 refactoring
  • 💥 other

📋 What is the related issue number (starting with #)

Resolves #201

❓ What is the current behavior? (You can also link to an open issue here)

Currently, the Cheroot project has its own HTTP parser and logic.

❓ What is the new behavior (if this is a feature change)?

This PR will defer the primary HTTP parser to the h11 project's implementation.

📋 Other information:

Depends on: python-hyper/h11#99

📋 Checklist:

  • I think the code is well written
  • I wrote good commit messages
  • I have squashed related commits together after the changes have been approved
  • Unit tests for the changes exist
  • Integration tests for the changes exist (if applicable)
  • I used the same coding conventions as the rest of the project
  • The new code doesn't generate linter offenses
  • Documentation reflects the changes
  • The PR relates to only one subject with a clear title
    and description in grammatically correct, complete sentences

This change is Reviewable

@ian-otto

Copy link
Copy Markdown
Contributor Author

Something of note, is I'm not sure whether I should anticipate supporting Python 2.7 specifically in this PR as it appears there is a discussion of its deprecation (#252)

@lgtm-com

This comment has been minimized.

Comment thread cheroot/server.py Resolved
Comment thread cheroot/server.py Resolved
Comment thread cheroot/server.py Resolved
Comment thread cheroot/server.py Resolved
Comment thread cheroot/server.py Resolved
Comment thread cheroot/server.py Resolved
Comment thread cheroot/server.py Resolved
Comment thread cheroot/server.py Outdated
line = self.rfile.readline()
while line:
event = self.conn.next_event()
if event is h11.NEED_DATA:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

plz reverse this check in order to reduce the following block indentation

Suggested change
if event is h11.NEED_DATA:
if event is not h11.NEED_DATA:
continue

Comment thread cheroot/server.py Resolved
Comment thread cheroot/server.py Outdated
if event is h11.NEED_DATA:
self.conn.receive_data(self.rfile.read(size))
event = self.conn.next_event()
assert isinstance(event, h11.Data)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Is this some sort of an exit-check for ensuring contracts?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Anything other than h11.Data here should be undefined behavior. Currently, I believe the only possible way we don't is if we get an EndOfMessage, but I'm pretty sure that were that to happen, h11 would raise an exception. I believe I saw this in the example code that they provide, so I kept it in for fun.

I can't really think of any other way it would be anything else, so I kept it in as a general catch-all.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Alright. This is a practice people follow when doing contract programming just as a sanity-check. asserts are stripped off in optimized mode. But it's useful to keep this as an exit-check.

@webknjaz

webknjaz commented Jan 22, 2020 •

Copy link
Copy Markdown
Member

I'm not sure whether I should anticipate supporting Python 2.7 specifically in this PR as it appears there is a discussion of its deprecation

@ian-otto I wanted to deprecate Python 2.7 after the HTTP parser replacement so that the last py2-compatible release would get the changes and then we'd start dropping support for this. Will probably merge #243 too before that. And maybe even #256 if we agree on it. That said, this PR should also be tested against CherryPy 17 which is the last major version to support Python 2.

@njsmith thanks a lot for your comments here!

Comment thread cheroot/server.py Resolved
Comment thread cheroot/server.py Resolved
Comment thread cheroot/server.py Resolved
Comment thread cheroot/server.py Resolved
Comment thread cheroot/server.py Resolved
Comment thread cheroot/server.py Resolved
Comment thread cheroot/server.py Outdated
if isinstance(req_line, h11.Request):
self.started_request = True
self.uri = req_line.target
scheme, netloc, path, query, fragment = urllib.parse.urlsplit(self.uri)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think you could save a few lines by doing the assignments directly

Suggested change
scheme, netloc, path, query, fragment = urllib.parse.urlsplit(self.uri)
_scheme, _netloc, self.path, self.qs, _fragment = urllib.parse.urlsplit(self.uri)

Comment thread cheroot/server.py Resolved
Comment thread cheroot/server.py Outdated
"""The HTTPConnection object on which this request connected."""

inheaders = {}
"""A dict of request headers."""

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Should this be a dict, though? I seem to recall that there could be header duplicates...

Comment thread cheroot/server.py Resolved
Comment thread cheroot/server.py Resolved
Comment thread cheroot/server.py Resolved
Comment thread cheroot/server.py Outdated
))

res = h11.Response(status_code=status, headers=self.outheaders,
http_version=self.response_protocol, reason=self.status[3:])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Maybe?

Suggested change
http_version=self.response_protocol, reason=self.status[3:])
http_version=self.response_protocol, reason=self.status[4:])

Comment thread cheroot/server.py Resolved
@ian-otto

Copy link
Copy Markdown
Contributor Author

So I've been peeking over the code reviews and I agree with most, if not all of them. I do have a few questions in regards to a few of them however.

There are a few instances where I'm attempting to take things from h11 (a lot of byte-strings), and shim them into the format that the old HTTPRequest class used, which increases the complexity and I believe a few of the errors I've made throughout.

@webknjaz Would you like me to attempt to make this change backwards compatible with the existing class, or throw that out in favor of increasing interoperability with h11? Note that some of the expectations (such as sending an HTTP 1.0 request and expecting an HTTP 1.0 response) are already going to be violated.

@webknjaz

webknjaz commented Jan 23, 2020 •

Copy link
Copy Markdown
Member

@duper51 I think I'm okay with not keeping compat. But just make sure that it doesn't affect CherryPy (it shouldn't but still). I think it may break WSGI adapter on CherryPy's side so it's worth confirming. We may need to think about edge-cases that we need to test manually or implement in automatic tests when this PR is closer to being ready.

ian-otto and others added 26 commits December 4, 2026 22:27
- Remove Transfer-Encoding check in `test_streaming_11` (I'm not sure if this is needed to follow spec)

- Marking invalid_terminators as expected fail (h11 treats this differently now)

- Ensure that we send a 100-Continue when it actually would be expected :P
h11 doesn't give us specific messaging for malformed data, disable messaging for the timebeing

Host header must be provided in HTTP/1.1 requests
Paths should be properly decoded as they were before.

Paths without a leading slash should be ignored and deleted
In order to get debugging to work nicely, test multithreading must be disabled, as well as a number of modules. I accidentally included this in one of my commits
- Reconfigure test_100_Continue to check specifically for a 200, not an unspecific != 100
- Reconfigure RFile base class to include the h11 functions
- Reconfigure KnownLength and ChunkedRFile to read including the h11 functions
- moved h11 as per request
- removed the HyperRFile implementation.
The invalid version `GET / HTTP/2.15` should be reported as an invalid version, rather than "Cannot fufill request" `https://tools.ietf.org/html/rfc2616#section-3.1`. Test has been modified to be more realistic.
- Remove the specifics of why a request-line is invalid, this would be difficult to support on h11's side due to the usage of regex
- There are scenarios (mainly with Chunked encoding) where h11 does not return an event, return something to prevent crash
- Copy specifics with CONNECT and OPTIONS requests to improve tests
- cherrypy#69 is solved by migrating to h11. We now handle this properly.
- Force removal of unintentional pytest.ini change
- We now properly empty the unreceived data from a client buffer, which should allow other tests to work better
- path should always start with forward slash, even if it's technically allowed to not (see OPTIONS)
- Read out trailers, but don't do anything with them
- Ensure EndOfMessage is sent with simple_response's
- Only send EndOfMessage if the client (or us) could actually handle sending that.
- Mark abstract as ABC, and mark unimplemented methods as abstractmethod
- Modify _send_100_if_needed to be a guard-like function
- Also add a docstring, since the method has differences in function
- Also correctly handle error string parsing
Co-Authored-By: Sviatoslav Sydorenko <wk.cvs.github@sydorenko.org.ua>
Co-authored-by: Sviatoslav Sydorenko <wk.cvs.github@sydorenko.org.ua>
Comment thread cheroot/test/test_core.py
assert response.status == HTTP_BAD_REQUEST
assert response.read(21) == b'Malformed Request-URI'
# TODO: h11 doesn't have this specific of messaging. See python-hyper/h11#98
# assert response.read(21) == b'Malformed Request-URI'

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

TODO: check if python-hyper/h11#99 gives us details for the request line

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement Improvement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Defer HTTP/1.1 parsing to Hyper (h11 project) Make HTTP server correctly read trailers (Trailer HTTP headers, which come after body)

4 participants