Skip to content

New API - #89

Merged
pgjones merged 7 commits into
python-hyper:masterfrom
pgjones:master
Dec 22, 2018
Merged

pgjones merged 7 commits into
python-hyper:masterfrom
pgjones:master

Conversation

@pgjones

@pgjones pgjones commented Dec 2, 2018

Copy link
Copy Markdown
Member

As per #85 I think this is a good point for me to stop and ask for feedback. This implements the same functionality as currently exists in wsproto in the form of the new API proposed in #85. If this is merged I have a simple follow up to add the new functionality discussed (e.g. the rejection response).

This removes any need to figure out how to style the code for wsproto,
instead allowing these two commands to do it instead,

    black wsproto/ test/
    isort --dont-skip __init__.py --apply --settings-path setup.cfg --recursive wsproto test

In addition a format stage has been added to the tox setup to enforce
this styling.
This is useful if the connection is being used as a server, but
something else has parsed the initial request. This is quite common
for dual protocol (HTTP & Websocket) servers whereby the HTTP part
parses first.

The implementation reverses the parsing, which is a little unpleasent,
however it is more unpleasent to put the h11 upgrade_connection into a
specific state.
This allows the packaging (restructured text format, setup structure,
and manifest) to be continually checked in travis.
@pgjones
pgjones requested review from Kriechi and mehaase December 2, 2018 16:49
@Kriechi

Kriechi commented Dec 2, 2018

Copy link
Copy Markdown
Member

Great progress!
This looks like a fresh approach - I'm not yet used to this "type" of API... but I don't have any major problems with it 😄

Just a clarification question: The events are now usable in both directions, if we create a new event object and pass it to WSConnection.send, or if we receive one, the event data is the same object. This would make proxying (I'm again thinking with my mitmproxy hat) very easy and straightforward!

Since h11 uses a very similar API design, why does our WSConnection.send function not return bytes that can be directly passed into a socket?

Now that we first have to send(Request(...) to initiate a connection, do we still need ConnectionType .CLIENT and ConnectionType .SERVER? Maybe we can auto-detect the first event and configure the connection accordingly - if it makes a differences?

I feel like the event class names could be a bit more descriptive, how about something like:
AcceptConnection, BytesMessage, TextMessage, CloseConnection?

Do we actually want to bother with a proper deprecation process? We are still on a 0.x.y release - so I guess we could just break things?

Also, I think we don't support py34 with the latest release anyway, so this can be removed / ignored.

Overall, this looks pretty good already!

Comment thread README.rst Outdated
elif isinstance(event, Text):
print('We got a text!', event.data)
elif isinstance(event, TextReceived):
elif isinstance(event, Text):

@mehaase mehaase Dec 3, 2018 •

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 a bug in the original README? I assume this should be:

elif isinstance(event, Bytes):
    print('We got bytes!', event.data)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Looks like it, good spot.

@mehaase

mehaase commented Dec 3, 2018

Copy link
Copy Markdown
Member

Do we actually want to bother with a proper deprecation process? We are still on a 0.x.y release - so I guess we could just break things?

I am content not to have an official deprecation process until 1.0. The deprecation warnings in this PR are sufficient.

@pgjones

pgjones commented Dec 3, 2018

Copy link
Copy Markdown
Member Author

Not having a deprecation process makes this so much easier :) I spent a good few days agonizing over the event structure in this regard. I'll change with that in mind.

Since h11 uses a very similar API design, why does our WSConnection.send function not return bytes that can be directly passed into a socket?

I think this would work nicely, I'll update.

Now that we first have to send(Request(...) to initiate a connection, do we still need ConnectionType .CLIENT and ConnectionType .SERVER?

I would prefer too, we still need to configure the h11.Connection object before we pass it any bytes. It also allows us to helpfully error if a Request is sent by a server.

I feel like the event class names could be a bit more descriptive, how about something like:
AcceptConnection, BytesMessage, TextMessage, CloseConnection?

I'm happy with those names, @mehaase do they look good to you?

@njsmith

njsmith commented Dec 3, 2018

Copy link
Copy Markdown
Member

Since h11 uses a very similar API design, why does our WSConnection.send function not return bytes that can be directly passed into a socket?

This is a difference between h11 and h2. h11's send returns bytes directly; h2's equivalent adds bytes to a buffer (so wsproto is currently like h2).

The reason for the difference between h11 and h2 is that in h11, the only time we ever send bytes are in response to an explicit call to send. In h2, bytes can also magically appear in the send buffer when certain data is received. Specifically, this happens when h2 receives a PING frame – it automatically encodes a reply frame without any intervention from the library user.

WebSocket has PING frames, which I guess is why wsproto copied h2 in the first place, but I think wsproto has ended up not sending PONG automatically, and instead relies on the library user to manually send PONG replies? If that's right then it makes sense to switch to the h11-style no-send-buffer API.

@Kriechi

Kriechi commented Dec 4, 2018

Copy link
Copy Markdown
Member

wsproto currently DOES send a pong by itself:

wsproto automatically emits a PONG frame with the same payload.

But I think this is still a valid point - if we have any other parts that need a send-buffer, or if everything can return the bytes-to-send.

Any thought on a hybrid approach? return bytes for API calls + send-buffer for non-user triggered actions?

@mehaase

mehaase commented Dec 4, 2018

Copy link
Copy Markdown
Member

I'm happy with those names, @mehaase do they look good to you?

👍

@njsmith

njsmith commented Dec 4, 2018

Copy link
Copy Markdown
Member

Ah ha. Then I guess the actual first question is whether wsproto should auto-send PONGs or not. I'm a bit dubious about it being a net win.

On the one hand, auto-sending is kind of convenient, and sending PONGs is a mandatory part of the protocol. On the other hand, at a higher level, it's also very convenient and maybe easier to reason about if send only sends, and receive only receives, and we don't have to just magically know when to check the send buffer in case new data has materialized.

Figuring out how to arrange sends and receives in trio-websocket was quite tricky once you take onto account backpressure and so forth. I'm honestly a bit daunted by the idea of going back and trying to figure out whether it handles auto-pong correctly.

@Kriechi

Kriechi commented Dec 4, 2018 •

Copy link
Copy Markdown
Member

@njsmith wsproto auto-replied to PING messages since forever (as far as git-blame would take me).

h2 also auto-replies ping messages: https://github.com/python-hyper/hyper-h2/blob/master/h2/connection.py#L1734

IMO this makes sense and should stay part of the promises we offer!

wsproto should make it easy to use websocket connections. If every user has to re-implement the same three lines of code to be RFC-compliant, what good is a library at that point? You wouldn't want to use a Linux TCP/IP stack where you have to manually deal with re-transmissions - I want it already taken care of!

Your other concern about "magically knowing when to check the output buffer" is of course valid. That's why I raised the question. I don't have strong feelings at the moment either way.

Using h2 as an example again, I usually check & send data from the output buffer whenever I'm receiving data, in case a ping/pong or setting-changes need to be handled. I feel this could be a valid usage pattern for wsproto as well. Having the auto-return-data on API calls is for user-triggered data.

@pgjones thoughts?

This changes the event naming so that they are all verb baseds and
hence can either be used to represent something that has happened (as
before) or to represent something that should happen. The latter
enables a ``send(event: Event)`` API similar to h11 and h2 to be
created.

Structure wise the h11 EventBundle system (and in places some of the
code) is adopted. This structure is roughly a stripped down
``dataclass``, and when wsproto supports 3.7 or greater I recommend
switching to a dataclass implementation. This restructure standardises
the reprs.

When migrating to this commit be sure to change names as follows,

    ConnectionRequested -> Request
    ConnectionEstablished -> AcceptConnection
    ConnectionClosed -> CloseConnection
    ConnectionFailed -> Fail
    DataReceived -> Data
    TextReceived -> TextMessage
    BytesReceived -> BytesMessage
    PingReceived -> Ping
    PongReceived -> Pong

Note the attributes (fields) may have to change in a subsequent
commit, so this should not be considered a reference commit.
@pgjones

pgjones commented Dec 4, 2018

Copy link
Copy Markdown
Member Author

I think we should keep the auto-pong as it matches h2 and what I think would be a user's expectations. I also think we should keep the bytes_to_send method and have send return None, as it is clearer to retrieve the bytes to send from a single place, especially as the buffer is consumed.

I've updated the changes to match the discussions so far.

@njsmith

njsmith commented Dec 4, 2018

Copy link
Copy Markdown
Member

If every user has to re-implement the same three lines of code to be RFC-compliant, what good is a library at that point?

Every user is going to have to re-implement some code to be RFC-compliant, the question is just which lines of code. Either they need to know that after receiving a PING they have to send a PONG, and then use a few lines to do that, or else they need to know that after receiving any data they have to check the send buffer for data to send, and then use a few lines to do that.

If auto-PONG actually reduced what users needed to know or needed to do, then it would be a no brainer, but I'm not convinced that's true. And then the other factors I'm thinking about, it seems easier to explain/document "if you get a PING you have to send a PONG" than to explain "under certain conditions, the send buffer might have automatically updated, ...", plus it might let us simplify the API overall (by getting rid of the send buffer concept entirely).

@Kriechi

Kriechi commented Dec 5, 2018

Copy link
Copy Markdown
Member

I also think we should keep the bytes_to_send method and have send return None, as it is clearer to retrieve the bytes to send from a single place, especially as the buffer is consumed.

👍

@pgjones
pgjones force-pushed the master branch 2 times, most recently from 88c7ee3 to b9a5897 Compare December 5, 2018 21:33
This allows a new event based API to be used in preference to the
previous method based API. The basic concept being that callingg
``connection.foo()`` becomes ``connection.send(Foo())``. This follows
the h11 convention.

This requires the following changes to be made to existing code,
(assuming connection is a Connection instance),

    connection.accept(subprotocol=subprotocol) -> connection.send(AcceptConnection(subprotocol=subprotocol))
    connection.send_data(data) -> connection.send(Data(payload=payload))
    connection.close(code) -> connection.send(CloseConnection(code=code))
    connection.ping() -> connection.send(Ping())
    connection.pong() -> connection.send(Pong())
This is required till prospector is fixed, See
prospector-dev/prospector#309.
@pgjones

pgjones commented Dec 6, 2018

Copy link
Copy Markdown
Member Author

@njsmith your argument is very strong, and I'm quite conflicted. I see it (as an illustration) as the difference between,

connection.receive_bytes(data)
for event in connection.events():
    ...
send(connection.bytes_to_send())

and

for event in connection.receive_bytes(data):
    if isinstance(event, Ping):
        send(connection.send(Pong())
   ...

with the right documentation the latter is quite clear, and it also makes the Sans-IO API very clear (in that you get events when you pass data and you get data when you send events).

I've written this in the hope it attracts more thoughts...

@mehaase

mehaase commented Dec 6, 2018

Copy link
Copy Markdown
Member

Side note: Pong isn't the only automatic event. If wsproto receives a close frame, it also puts a close frame in the outgoing buffer. The caller has to know to call bytes_to_send when they get a close event.

I lean towards the @njsmith style:

  1. I don't think it's any more or less complicated. In both cases, the user will need to read the docs to implement RFC-compliant behavior.
  2. Some user may appreciate the flexibility to do something unusual or non-compliant.
  3. The caller's code is a bit more explicit and readable.
  4. The biggest win is getting rid of the [unbounded] send buffer.

@Kriechi

Kriechi commented Dec 6, 2018

Copy link
Copy Markdown
Member

I'm not a big fan of making the user responsible to read the RFC and write RFC-compliant code. At this point the only point of wsproto would be parsing and serializing frames. My vision for a (sans-io) protocol library is "to be RFC-compliant", not "you can build something that might be RFC-compliant if you read the RFC yourself and implement it yourself". Sure, there are various gray areas and degrees of how-much-code the user needs to write, but essential protocol things, such as the closing handshake or ping+pong, should be provided by wsproto out-of-the-box.

In mitmproxy we currently use this pattern to auto-send protocol-level frames without requiring custom code or reading the RFC:

frame = websockets.Frame.from_file(source_socket.rfile)
source_conn.receive_bytes(bytes(frame))
source_socket.send(source_conn.bytes_to_send()) # exchange protocol maintenance data

for event in self.connections[source_conn].events():
    # handle events here

@pgjones

pgjones commented Dec 21, 2018

Copy link
Copy Markdown
Member Author

So I'd like to move the discussion about how to manage the bytes to send to #91 and instead ask that this be merged in this state (unless there are new issues). I can then continue to implement the rejection API and then possibly #91 if we decide it is right.

@Kriechi Kriechi left a comment

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.

Let's get this merged and continue the work in newer issues & PRs.

@pgjones
pgjones merged commit 7ef9200 into python-hyper:master Dec 22, 2018
@pgjones

pgjones commented Dec 22, 2018

Copy link
Copy Markdown
Member Author

Thanks :)

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants