Skip to content

Proposed new API #85

Closed
Closed

Description

@pgjones

In an effort to solve #27, #61, #83 I propose changing the WSConnection API following aspects from h11 and h2. In summary I propose a initiate_upgrade_connection method and a send method with the latter being a switch to event driven.

Initiating upgrades

Currently I think most implementations that support websockets and HTTP simply recreate the raw bytes for the upgrade request and call receive_bytes, as I do in Hypercorn for example.

I propose the following method,

class WSConnection:
    def initiate_upgrade_connection(
        self, 
        headers: List[Tuple[bytes, bytes]], 
        path: str,
) -> None:
        ...

which would setup the connection as if it had received that request, thereby emitting a ConnectionRequested instance as the first event from the events method.

This should satisfy use cases that don't use h11 as easily as those that do.

Controlling the handshake & being event driven

Currently to accept a connection the accept method is called, to reject a connection requires some effort, such as using the private h11 _upgrade_connection. (As the _upgrade_connection is required it is clear wsproto can handle the full HTTP request/response cycle.)

I propose wsproto follows the h11 practice and infact accepts h11 event objects via a send method like,

class WSConnection:
    def send(self, Union[h11.Event, wsproto.Event]):
        ...

this would deprecate the existing accept, close, and send_data methods initially replacing them as so,

class WSConnection:
    def accept(self):
        return self.send(AcceptConnection())

    def close(self, code):
        return self.send(CloseConnection(code))

    def send_data(self, data):
        return self.send(Data(data))

with the send method also accepting the h11.Response, h11.Data and h11.EndOfMessage events thereby allowing complete control over the HTTP acceptance/rejection responses.

As for the AcceptConnection, CloseConnection and Data events I'd follow the existing wsproto event structure.

A Note on h11 dependence

This would further tie wsproto to h11, which could be considered problematic. However I think h11 is great and also maintained by the same group (python-hyper) and hence cooperation would be expected and beneficial to both.

Next steps

Assuming @Kriechi, @mehaase are in some sought of agreement with me I'll make the changes, update the documentation and prepare a new release :). (Would be good to know what @njsmith thinks as well).

Activity

  1. mehaase commented on Oct 25, 2018

    @mehaase
    Member

    Thank you @pgjones for putting in the effort to think through this and to write it up. I'm not very familiar with h11, but I do generally like the approach you have described here. I am also not concerned about the increased dependency on h11.

    I think it might be nice to include a reject(status_code, headers, body=None) method to provide symmetry with accept(…). This would be a convenience method that sends the corresponding h11 events for you.

    The proposed send(…) method also deprecates the current ping() and pong() methods, right? Do you propose to update those methods or drop them?

    Regarding initiate_upgrade_connection()…

    class WSConnection:
        def initiate_upgrade_connection(
            self, 
            headers: List[Tuple[bytes, bytes]], 
            path: str,
    ) -> None:
            ...

    The headers argument is extra headers to send, right? And wsproto will still take care of handshake headers like Sec-Websocket-Accept? I think this would also be the right place to put subprotocols and extensions arguments, since those can both be negotiated as part of the handshake. (It wouldn't make sense to set those values in the constructor anymore, because the caller can negotiate the handshake separately from wsproto.)

  2. pgjones commented on Oct 25, 2018

    @pgjones
    MemberAuthor

    I would rather deprecate and remove accept(..) so I don't think adding a reject(status_code, headers, body=None) would make sense, however I think it would look like (to better illustrate my thoughts),

    class WSConnection:
        def reject(self, status_code, headers, body):
            self.send(h11.Response(status_code=status_code, headers=headers))
            self.send(h11.Data(data=body))
            self.send(h11.EndOfMessage())

    You are right, I had forgotten about ping and pong, which could be replaced by send(Ping()). (Do we need a pong? It seems like something that should be dealt with automatically by the connection, as h2 does).

    Regarding initiate_upgrade_connection(), the headers argument is in fact the full set of headers received by the server. This is only for a server side connection and would allow another HTTP parser to receive the initial HTTP request and then pass over to wsproto to handle thereafter (by passing the headers).

    Regarding the extra headers, I think the initiate_connection method should gain a extra_headers argument.

  3. mehaase commented on Oct 25, 2018

    @mehaase
    Member

    Oh okay, I misunderstood the part about deprecation when I first read it. Now I understand that accept() et. al. would be deprecated (and could eventually be removed). As @Kriechi points out, there is value in having a pong feature.

    It also seems like the events need to be renamed if they can be both sent and received. I.e. conn.send(PingReceived(…)) is a bit confusing and should probably be conn.send(PingEvent(…)) or just conn.send(Ping(…)).

  4. pgjones commented on Oct 25, 2018

    @pgjones
    MemberAuthor

    I agree with the naming suggestion, on this as well we could have a subclass with the old name initially (to help with the migration). I'm also happy to keep an ability to force send a pong.

    Should I start work? I think we seem in agreement.

  5. mehaase commented on Oct 26, 2018

    @mehaase
    Member

    👍 from me. Let me know how I can help: code, docs, review, whatever you need.

  6. pgjones commented on Nov 15, 2018

    @pgjones
    MemberAuthor

    For those following, I'm pushing the work in parts to https://github.com/pgjones/wsproto and then I'll open a pull request here.

  7. njsmith commented on Dec 3, 2018

    @njsmith
    Member

    I haven't had time to look into this in any detail, but just to raise a flag: if we're rethinking the handshake API we should also think about RFC 8441 handshakes (#90)

  8. pgjones commented on Dec 30, 2018

    @pgjones
    MemberAuthor

    Looking at #92 and following on from the work on this I would like to propose removing the Fail event and instead replacing it with raised LocalProtocol and RemoteProtocol errors (the former is roughly the same as #92). This would follow how h11 works, and I think be clearer as I'd expect an exception rather than having to check for a certain error type (more pythonic).

    Note that the Fail event isn't really an event if #93 is merged as it is effectively replaced by RejectConnection.

    Note also that the equivalent of raising LocalProtocol currently happens via a select few ValueError exceptions.

  9. pgjones commented on Dec 30, 2018

    @pgjones
    MemberAuthor

    I should add that regarding #91 I think the API would become:

    try:
        events = connection.receive_bytes(data):
    except RemoteProtocolError:
        if connection._state == CONNECTING:
            connection.send(RejectConnection())
        elif connection._state == OPEN:
            connection.send(CloseConnection())
    else:
        for event in events:
            ...

    With LocalProtocolErrors up to the user to decide how to deal with programming errors.
    (Maybe also _state should be state to encourage usage?)

  10. Kriechi commented on Dec 30, 2018

    @Kriechi
    Member

    Regarding _state:
    yes, if we make it a public API, it should become state, but I don't like exposing it directly.

    We already have a closed property, I would like to see an opened property, as was recently proposed in https://github.com/python-hyper/wsproto/pull/92/files#diff-76076ffd5b77a8b4cfe658823ea73be1R193 by @touilleMan.

  11. pgjones commented on Dec 30, 2018

    @pgjones
    MemberAuthor

    I think you'd want to know if you were in the REJECTING state to know whether you could send Rejection data, and the CONNECTING state to know if you can reject etc... as in you'd want to know about all the states. I prefer not to have a property for each possible state, as it is less helpful than exposing the attribute.

  12. Kriechi commented on Dec 30, 2018

    @Kriechi
    Member

    Fine with me - but currently we have a mix. If you want to expose state as public API (read-only, if possible?), I would suggest removing the closed property. Either is fine with me.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions