aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorLoïc Hoguin <[email protected]>2025-08-21 18:09:42 +0200
committerLoïc Hoguin <[email protected]>2025-09-15 13:09:23 +0200
commit8da6ca11e8ea4e93def78bd0299decd6f409bc43 (patch)
treee897bf997175a113e02acb2b7f4c179c7528aeb4 /src
parenta8c717718a3f4dd7b4bc67fe7bebe3a4e7a7ed74 (diff)
downloadcowboy-8da6ca11e8ea4e93def78bd0299decd6f409bc43.tar.gz
cowboy-8da6ca11e8ea4e93def78bd0299decd6f409bc43.tar.bz2
cowboy-8da6ca11e8ea4e93def78bd0299decd6f409bc43.zip
New data delivery mechanism for HTTP/2+ Websocketdirect-data_delivery-for-h2-websocket
A new data_delivery mechanism called 'relay' has been added. It bypasses stream handlers (and the buffering in cowboy_stream_h) and sends the data directly to the process implementing Websocket (and should work for other similar protocols like HTTP/2 WebTransport). Flow control in HTTP/2 is maintained in a simpler way, via a configured flow value that is used to maintain the window to a reasonable value when data is received. The 'relay' data_delivery has been implemented for both HTTP/2 and HTTP/3. It has not been implemented for HTTP/1.1 since switching protocol there overrides the connection process. HTTP/2 Websocket is now better tested. A bug was fixed with the 'stream_handlers' data_delivery where active mode would not be reenabled if it was disabled at some point. The Websocket performance suite has been updated to include tests that do not use Gun. Websocket modules used by the performance suite use the 'relay' data_delivery now. Performance is improved significantly with 'relay', between 10% and 20% faster. HTTP/2 Websocket performance is not on par with HTTP/1.1 still, but the remaining difference is thought to be from the HTTP/2 overhead and flow control.
Diffstat (limited to 'src')
-rw-r--r--src/cowboy_http2.erl59
-rw-r--r--src/cowboy_http3.erl54
-rw-r--r--src/cowboy_quicer.erl13
-rw-r--r--src/cowboy_websocket.erl62
-rw-r--r--src/cowboy_webtransport.erl1
5 files changed, 172 insertions, 17 deletions
diff --git a/src/cowboy_http2.erl b/src/cowboy_http2.erl
index 0d22fa1..5cb0585 100644
--- a/src/cowboy_http2.erl
+++ b/src/cowboy_http2.erl
@@ -82,8 +82,13 @@
-export_type([opts/0]).
-record(stream, {
- %% Whether the stream is currently stopping.
- status = running :: running | stopping,
+ %% Whether the stream is currently in a special state.
+ %%
+ %% - The running state is the normal state of a stream.
+ %% - The relaying state is used by extended CONNECT protocols to
+ %% use a 'relay' data_delivery method.
+ %% - The stopping state indicates the stream used the 'stop' command.
+ status = running :: running | {relaying, non_neg_integer(), pid()} | stopping,
%% Flow requested for this stream.
flow = 0 :: non_neg_integer(),
@@ -327,6 +332,8 @@ loop(State=#state{parent=Parent, socket=Socket, transport=Transport,
%% Messages pertaining to a stream.
{{Pid, StreamID}, Msg} when Pid =:= self() ->
before_loop(info(State, StreamID, Msg), Buffer);
+ {'$cowboy_relay_command', {Pid, StreamID}, RelayCommand} when Pid =:= self() ->
+ before_loop(relay_command(State, StreamID, RelayCommand), Buffer);
%% Exit signal from children.
Msg = {'EXIT', Pid, _} ->
before_loop(down(State, Pid, Msg), Buffer);
@@ -520,6 +527,14 @@ data_frame(State0=#state{opts=Opts, flow=Flow0, streams=Streams}, StreamID, IsFi
reset_stream(State0, StreamID, {internal_error, {Class, Exception},
'Unhandled exception in cowboy_stream:data/4.'})
end;
+ %% Stream handlers are not used for the data when relaying.
+ #{StreamID := #stream{status={relaying, _, RelayPid}}} ->
+ RelayPid ! {'$cowboy_relay_data', {self(), StreamID}, IsFin, Data},
+ %% We keep a steady flow using the configured flow value.
+ %% Because we do not change the 'flow' value the update_window/2
+ %% function will always maintain this value (of course with
+ %% thresholds applying).
+ update_window(State0, StreamID);
%% We ignore DATA frames for streams that are stopping.
#{} ->
State0
@@ -866,6 +881,26 @@ commands(State=#state{socket=Socket, transport=Transport, http2_status=upgrade},
commands(State, StreamID, Tail);
%% Use a different protocol within the stream (CONNECT :protocol).
%% @todo Make sure we error out when the feature is disabled.
+%% There are two data_delivery: stream_handlers and relay.
+%% The former just has the data go through stream handlers
+%% like normal requests. The latter relays data directly.
+%%
+%% @todo When relaying there might be some data that is
+%% in stream handlers and that need to be received,
+%% depending on whether the protocol sends data
+%% before processing the response.
+commands(State0=#state{flow=Flow, streams=Streams}, StreamID,
+ [{switch_protocol, Headers, _Mod, ModState=#{data_delivery := relay}}|Tail]) ->
+ State1 = info(State0, StreamID, {headers, 200, Headers}),
+ #{StreamID := Stream} = Streams,
+ #{data_delivery_pid := RelayPid} = ModState,
+ %% WINDOW_UPDATE frames updating the window will be sent after
+ %% the first DATA frame has been received.
+ RelayFlow = maps:get(data_delivery_flow, ModState, 131072),
+ State = State1#state{flow=Flow + RelayFlow, streams=Streams#{StreamID => Stream#stream{
+ status={relaying, RelayFlow, RelayPid},
+ flow=RelayFlow}}},
+ commands(State, StreamID, Tail);
commands(State0, StreamID, [{switch_protocol, Headers, _Mod, _ModState}|Tail]) ->
State = info(State0, StreamID, {headers, 200, Headers}),
commands(State, StreamID, Tail);
@@ -881,6 +916,26 @@ commands(State=#state{opts=Opts}, StreamID, [Log={log, _, _, _}|Tail]) ->
cowboy:log(Log, Opts),
commands(State, StreamID, Tail).
+%% Relay data delivery commands.
+
+relay_command(State, StreamID, DataCmd = {data, _, _}) ->
+ commands(State, StreamID, [DataCmd]);
+%% When going active mode again we set the RelayFlow again
+%% and update the window if necessary.
+relay_command(State=#state{flow=Flow, streams=Streams}, StreamID, active) ->
+ #{StreamID := Stream} = Streams,
+ #stream{status={relaying, RelayFlow, _}} = Stream,
+ update_window(State#state{flow=Flow + RelayFlow,
+ streams=Streams#{StreamID => Stream#stream{flow=RelayFlow}}},
+ StreamID);
+%% When going passive mode we don't update the window
+%% since we have not incremented it.
+relay_command(State=#state{flow=Flow, streams=Streams}, StreamID, passive) ->
+ #{StreamID := Stream} = Streams,
+ #stream{flow=StreamFlow} = Stream,
+ State#state{flow=Flow - StreamFlow,
+ streams=Streams#{StreamID => Stream#stream{flow=0}}}.
+
%% Tentatively update the window after the flow was updated.
update_window(State0=#state{socket=Socket, transport=Transport,
diff --git a/src/cowboy_http3.erl b/src/cowboy_http3.erl
index 9aa6be5..740b9e3 100644
--- a/src/cowboy_http3.erl
+++ b/src/cowboy_http3.erl
@@ -67,6 +67,7 @@
%% Whether the stream is currently in a special state.
status :: header | {unidi, control | encoder | decoder}
| normal | {data | ignore, non_neg_integer()} | stopping
+ | {relaying, normal | {data, non_neg_integer()}, pid()}
| {webtransport_session, normal | {ignore, non_neg_integer()}}
| {webtransport_stream, cow_http3:stream_id()},
@@ -164,6 +165,8 @@ loop(State0=#state{opts=Opts, children=Children}) ->
%% Messages pertaining to a stream.
{{Pid, StreamID}, Msg} when Pid =:= self() ->
loop(info(State0, StreamID, Msg));
+ {'$cowboy_relay_command', {Pid, StreamID}, RelayCommand} when Pid =:= self() ->
+ loop(relay_command(State0, StreamID, RelayCommand));
%% WebTransport commands.
{'$webtransport_commands', SessionID, Commands} ->
loop(webtransport_commands(State0, SessionID, Commands));
@@ -299,6 +302,22 @@ parse1(State, Stream=#stream{status={data, Len}, id=StreamID}, Data, IsFin) ->
parse(frame(State, Stream#stream{status=normal}, {data, Data1}, FrameIsFin),
StreamID, Rest, IsFin)
end;
+%% This clause mirrors the {data, Len} clause.
+parse1(State, Stream=#stream{status={relaying, {data, Len}, RelayPid}, id=StreamID},
+ Data, IsFin) ->
+ DataLen = byte_size(Data),
+ if
+ DataLen < Len ->
+ %% We don't have the full frame but this is the end of the
+ %% data we have. So FrameIsFin is equivalent to IsFin here.
+ loop(frame(State, Stream#stream{status={relaying, {data, Len - DataLen}, RelayPid}},
+ {data, Data}, IsFin));
+ true ->
+ <<Data1:Len/binary, Rest/bits>> = Data,
+ FrameIsFin = is_fin(IsFin, Rest),
+ parse(frame(State, Stream#stream{status={relaying, normal, RelayPid}},
+ {data, Data1}, FrameIsFin), StreamID, Rest, IsFin)
+ end;
parse1(State, Stream=#stream{status={ignore, Len}, id=StreamID}, Data, IsFin) ->
DataLen = byte_size(Data),
if
@@ -311,7 +330,7 @@ parse1(State, Stream=#stream{status={ignore, Len}, id=StreamID}, Data, IsFin) ->
end;
%% @todo Clause that discards receiving data for stopping streams.
%% We may receive a few more frames after we abort receiving.
-parse1(State=#state{opts=Opts}, Stream=#stream{id=StreamID}, Data, IsFin) ->
+parse1(State=#state{opts=Opts}, Stream=#stream{status=Status0, id=StreamID}, Data, IsFin) ->
case cow_http3:parse(Data) of
{ok, Frame, Rest} ->
FrameIsFin = is_fin(IsFin, Rest),
@@ -322,6 +341,10 @@ parse1(State=#state{opts=Opts}, Stream=#stream{id=StreamID}, Data, IsFin) ->
{more, Frame = {data, _}, Len} ->
%% We're at the end of the data so FrameIsFin is equivalent to IsFin.
case IsFin of
+ nofin when element(1, Status0) =:= relaying ->
+ %% The stream will be stored at the end of processing commands.
+ Status = setelement(2, Status0, {data, Len}),
+ loop(frame(State, Stream#stream{status=Status}, Frame, nofin));
nofin ->
%% The stream will be stored at the end of processing commands.
loop(frame(State, Stream#stream{status={data, Len}}, Frame, nofin));
@@ -432,6 +455,9 @@ frame(State=#state{http3_machine=HTTP3Machine0},
terminate(State#state{http3_machine=HTTP3Machine}, Error)
end.
+data_frame(State, Stream=#stream{status={relaying, _, RelayPid}, id=StreamID}, IsFin, Data) ->
+ RelayPid ! {'$cowboy_relay_data', {self(), StreamID}, IsFin, Data},
+ stream_store(State, Stream);
data_frame(State=#state{opts=Opts},
Stream=#stream{id=StreamID, state=StreamState0}, IsFin, Data) ->
try cowboy_stream:data(StreamID, IsFin, Data, StreamState0) of
@@ -767,6 +793,18 @@ commands(State0, Stream0=#stream{id=StreamID},
},
%% @todo We must propagate the buffer to capsule handling if any.
commands(State#state{http3_machine=HTTP3Machine}, Stream, Tail);
+%% There are two data_delivery: stream_handlers and relay.
+%% The former just has the data go through stream handlers
+%% like normal requests. The latter relays data directly.
+commands(State0, Stream0=#stream{id=StreamID},
+ [{switch_protocol, Headers, _Mod, ModState=#{data_delivery := relay}}|Tail]) ->
+ State = info(stream_store(State0, Stream0), StreamID, {headers, 200, Headers}),
+ Stream1 = #stream{status=normal} = stream_get(State, StreamID),
+ #{data_delivery_pid := RelayPid} = ModState,
+ %% We do not set data_delivery_flow because it is managed by quicer
+ %% and we do not have an easy way to modify it.
+ Stream = Stream1#stream{status={relaying, normal, RelayPid}},
+ commands(State, Stream, Tail);
commands(State0, Stream0=#stream{id=StreamID},
[{switch_protocol, Headers, _Mod, _ModState}|Tail]) ->
State = info(stream_store(State0, Stream0), StreamID, {headers, 200, Headers}),
@@ -872,6 +910,20 @@ send_instructions(State=#state{conn=Conn, local_encoder_id=EncoderID},
cowboy_quicer:send(Conn, EncoderID, EncData)),
State.
+%% Relay data delivery commands.
+
+relay_command(State, StreamID, DataCmd = {data, _, _}) ->
+ Stream = stream_get(State, StreamID),
+ commands(State, Stream, [DataCmd]);
+relay_command(State=#state{conn=Conn}, StreamID, active) ->
+ ok = maybe_socket_error(State,
+ cowboy_quicer:setopt(Conn, StreamID, active, true)),
+ State;
+relay_command(State=#state{conn=Conn}, StreamID, passive) ->
+ ok = maybe_socket_error(State,
+ cowboy_quicer:setopt(Conn, StreamID, active, false)),
+ State.
+
%% We mark the stream as being a WebTransport stream
%% and then continue parsing the data as a WebTransport
%% stream. This function is common for incoming unidi
diff --git a/src/cowboy_quicer.erl b/src/cowboy_quicer.erl
index aa52fae..d2f5433 100644
--- a/src/cowboy_quicer.erl
+++ b/src/cowboy_quicer.erl
@@ -25,6 +25,7 @@
%% Streams.
-export([start_bidi_stream/2]).
-export([start_unidi_stream/2]).
+-export([setopt/4]).
-export([send/3]).
-export([send/4]).
-export([send_datagram/2]).
@@ -54,6 +55,9 @@ start_bidi_stream(_, _) -> no_quicer().
-spec start_unidi_stream(_, _) -> no_return().
start_unidi_stream(_, _) -> no_quicer().
+-spec setopt(_, _, _, _) -> no_return().
+setopt(_, _, _, _) -> no_quicer().
+
-spec send(_, _, _) -> no_return().
send(_, _, _) -> no_quicer().
@@ -109,7 +113,7 @@ sockname(Conn) ->
| {error, any()}.
peercert(Conn) ->
- quicer_nif:peercert(Conn).
+ quicer_nif:peercert(Conn).
-spec shutdown(quicer_connection_handle(), quicer_app_errno())
-> ok | {error, any()}.
@@ -154,6 +158,13 @@ start_stream(Conn, InitialData, OpenFlag) ->
Error
end.
+-spec setopt(quicer_connection_handle(), cow_http3:stream_id(), active, boolean())
+ -> ok | {error, any()}.
+
+setopt(_Conn, StreamID, active, Value) ->
+ StreamRef = get({quicer_stream, StreamID}),
+ quicer:setopt(StreamRef, active, Value).
+
-spec send(quicer_connection_handle(), cow_http3:stream_id(), iodata())
-> ok | {error, any()}.
diff --git a/src/cowboy_websocket.erl b/src/cowboy_websocket.erl
index cb30c3f..65289cd 100644
--- a/src/cowboy_websocket.erl
+++ b/src/cowboy_websocket.erl
@@ -68,6 +68,8 @@
-type opts() :: #{
active_n => pos_integer(),
compress => boolean(),
+ data_delivery => stream_handlers | relay,
+ data_delivery_flow => pos_integer(),
deflate_opts => cow_ws:deflate_opts(),
dynamic_buffer => false | {pos_integer(), pos_integer()},
dynamic_buffer_initial_average => non_neg_integer(),
@@ -91,7 +93,7 @@
parent :: undefined | pid(),
ref :: ranch:ref(),
socket = undefined :: inet:socket() | {pid(), cowboy_stream:streamid()} | undefined,
- transport = undefined :: module() | undefined,
+ transport :: module() | {data_delivery, stream_handlers | relay},
opts = #{} :: opts(),
active = true :: boolean(),
handler :: module(),
@@ -149,7 +151,7 @@ upgrade(Req, Env, Handler, HandlerState) ->
%% @todo Immediately crash if a response has already been sent.
upgrade(Req0=#{version := Version}, Env, Handler, HandlerState, Opts) ->
FilteredReq = case maps:get(req_filter, Opts, undefined) of
- undefined -> maps:with([method, version, scheme, host, port, path, qs, peer], Req0);
+ undefined -> maps:with([method, version, scheme, host, port, path, qs, peer, streamid], Req0);
FilterFun -> FilterFun(Req0)
end,
Utf8State = case maps:get(validate_utf8, Opts, true) of
@@ -273,12 +275,27 @@ websocket_handshake(State=#state{key=Key},
%% For HTTP/2 we do not let the process die, we instead keep it
%% for the Websocket stream. This is because in HTTP/2 we only
%% have a stream, it doesn't take over the whole connection.
-websocket_handshake(State, Req=#{ref := Ref, pid := Pid, streamid := StreamID},
+%%
+%% There are two methods of delivering data to the Websocket session:
+%% - 'stream_handlers' is the default and makes the data go
+%% through stream handlers just like when reading a request body;
+%% - 'relay' is a new method where data is sent as a message as
+%% soon as it is received from the socket in a DATA frame.
+websocket_handshake(State=#state{opts=Opts},
+ Req=#{ref := Ref, pid := Pid, streamid := StreamID},
HandlerState, _Env) ->
%% @todo We don't want date and server headers.
Headers = cowboy_req:response_headers(#{}, Req),
- Pid ! {{Pid, StreamID}, {switch_protocol, Headers, ?MODULE, {State, HandlerState}}},
- takeover(Pid, Ref, {Pid, StreamID}, undefined, #{}, <<>>,
+ DataDelivery = maps:get(data_delivery, Opts, stream_handlers),
+ ModState = #{
+ data_delivery => DataDelivery,
+ %% For relay data_delivery. The flow is a hint and may
+ %% not be used by the underlying protocol.
+ data_delivery_pid => self(),
+ data_delivery_flow => maps:get(data_delivery_flow, Opts, 131072)
+ },
+ Pid ! {{Pid, StreamID}, {switch_protocol, Headers, ?MODULE, ModState}},
+ takeover(Pid, Ref, {Pid, StreamID}, {data_delivery, DataDelivery}, #{}, <<>>,
{State, HandlerState}).
%% Connection process.
@@ -301,7 +318,7 @@ websocket_handshake(State, Req=#{ref := Ref, pid := Pid, streamid := StreamID},
-type parse_state() :: #ps_header{} | #ps_payload{}.
-spec takeover(pid(), ranch:ref(), inet:socket() | {pid(), cowboy_stream:streamid()},
- module() | undefined, any(), binary(),
+ module() | {data_delivery, stream_handlers | relay}, any(), binary(),
{#state{}, any()}) -> no_return().
takeover(Parent, Ref, Socket, Transport, Opts, Buffer,
{State0=#state{opts=WsOpts, handler=Handler, req=Req}, HandlerState}) ->
@@ -311,7 +328,7 @@ takeover(Parent, Ref, Socket, Transport, Opts, Buffer,
_ -> ranch:remove_connection(Ref)
end,
Messages = case Transport of
- undefined -> undefined;
+ {data_delivery, _} -> undefined;
_ -> Transport:messages()
end,
State = set_idle_timeout(State0#state{parent=Parent,
@@ -355,13 +372,14 @@ after_init(State, HandlerState, ParseState) ->
%% immediately but there might still be data to be processed in
%% the message queue.
-setopts_active(#state{transport=undefined}) ->
+setopts_active(#state{transport={data_delivery, _}}) ->
ok;
setopts_active(#state{socket=Socket, transport=Transport, opts=Opts}) ->
N = maps:get(active_n, Opts, 1),
Transport:setopts(Socket, [{active, N}]).
-maybe_read_body(#state{socket=Stream={Pid, _}, transport=undefined, active=true}) ->
+maybe_read_body(#state{transport={data_delivery, stream_handlers},
+ socket=Stream={Pid, _}, active=true}) ->
%% @todo Keep Ref around.
ReadBodyRef = make_ref(),
Pid ! {Stream, {read_body, self(), ReadBodyRef, auto, infinity}},
@@ -369,16 +387,25 @@ maybe_read_body(#state{socket=Stream={Pid, _}, transport=undefined, active=true}
maybe_read_body(_) ->
ok.
-active(State) ->
+active(State=#state{transport={data_delivery, relay},
+ socket=Stream={Pid, _}}) ->
+ Pid ! {'$cowboy_relay_command', Stream, active},
+ State#state{active=true};
+active(State0) ->
+ State = State0#state{active=true},
setopts_active(State),
maybe_read_body(State),
- State#state{active=true}.
+ State.
-passive(State=#state{transport=undefined}) ->
+passive(State=#state{transport={data_delivery, stream_handlers}}) ->
%% Unfortunately we cannot currently cancel read_body.
%% But that's OK, we will just stop reading the body
%% after the next message.
State#state{active=false};
+passive(State=#state{transport={data_delivery, relay},
+ socket=Stream={Pid, _}}) ->
+ Pid ! {'$cowboy_relay_command', Stream, passive},
+ State#state{active=false};
passive(State=#state{socket=Socket, transport=Transport, messages=Messages}) ->
Transport:setopts(Socket, [{active, false}]),
flush_passive(Socket, Messages),
@@ -454,6 +481,10 @@ loop(State=#state{parent=Parent, socket=Socket, messages=Messages,
{request_body, _Ref, fin, _, Data} ->
maybe_read_body(State),
parse(?reset_idle_timeout(State), HandlerState, ParseState, Data);
+ %% @todo It would be better to check StreamID.
+ %% @todo We must ensure that IsFin=fin is handled like a socket close?
+ {'$cowboy_relay_data', {Pid, _StreamID}, _IsFin, Data} when Pid =:= Parent ->
+ parse(?reset_idle_timeout(State), HandlerState, ParseState, Data);
%% Timeouts.
{timeout, TRef, ?MODULE} ->
tick_idle_timeout(State, HandlerState, ParseState);
@@ -662,9 +693,14 @@ commands([Frame|Tail], State, Data0) ->
commands(Tail, State, Data)
end.
-transport_send(#state{socket=Stream={Pid, _}, transport=undefined}, IsFin, Data) ->
+transport_send(#state{transport={data_delivery, stream_handlers},
+ socket=Stream={Pid, _}}, IsFin, Data) ->
Pid ! {Stream, {data, IsFin, Data}},
ok;
+transport_send(#state{transport={data_delivery, relay},
+ socket=Stream={Pid, _}}, IsFin, Data) ->
+ Pid ! {'$cowboy_relay_command', Stream, {data, IsFin, Data}},
+ ok;
transport_send(#state{socket=Socket, transport=Transport}, _, Data) ->
Transport:send(Socket, Data).
diff --git a/src/cowboy_webtransport.erl b/src/cowboy_webtransport.erl
index 8c8ca39..7bcac55 100644
--- a/src/cowboy_webtransport.erl
+++ b/src/cowboy_webtransport.erl
@@ -277,6 +277,7 @@ handler_terminate(#state{handler=Handler, req=Req}, HandlerState, Reason) ->
%% callback is not implemented.
%%
%% @todo Better type than map() for the cowboy_stream state.
+%% @todo Is this really useful?
-spec info(cowboy_stream:streamid(), any(), State)
-> {cowboy_stream:commands(), State} when State::map().