Skip to content

Commit 987365d

Browse files
Aaron Seigoaseigo
authored andcommitted
Refactor: grpcweb trailer sending in its own function
Reads cleaner, perhaps a bit more idiomatic as well.
1 parent f4a753c commit 987365d

File tree

1 file changed

+31
-26
lines changed
  • grpc_server/lib/grpc/server/adapters/cowboy

1 file changed

+31
-26
lines changed

grpc_server/lib/grpc/server/adapters/cowboy/handler.ex

Lines changed: 31 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -481,34 +481,15 @@ defmodule GRPC.Server.Adapters.Cowboy.Handler do
481481
end
482482

483483
def info({:stream_trailers, trailers}, req, state) do
484-
metadata = Map.get(state, :resp_trailers, %{})
485-
metadata = GRPC.Transport.HTTP2.encode_metadata(metadata)
486-
all_trailers = Map.merge(metadata, trailers)
484+
metadata =
485+
state
486+
|> Map.get(:resp_trailers, %{})
487+
|> GRPC.Transport.HTTP2.encode_metadata()
487488

488-
req = check_sent_resp(req)
489-
490-
if state.access_mode === :grpcweb do
491-
# grpc_web requires trailers be sent as the last
492-
# message block rather than in the HTTP trailers
493-
# as javascript runtimes do not propagate trailers
494-
#
495-
# trailers are instead denoted with the "trailer flag"
496-
# which has the MSB set to 1.
497-
{:ok, data, _length} =
498-
all_trailers
499-
|> Enum.map_join("\r\n", fn {k, v} -> "#{k}: #{v}" end)
500-
|> GRPC.Message.to_data(message_flag: @trailers_flag)
501-
502-
packed =
503-
if function_exported?(state.codec, :pack_for_channel, 1) do
504-
state.codec.pack_for_channel(data)
505-
else
506-
data
507-
end
508-
509-
:cowboy_req.stream_body(packed, :nofin, req)
510-
end
489+
all_trailers = Map.merge(trailers, metadata)
511490

491+
req = check_sent_resp(req)
492+
stream_grpcweb_trailers(req, all_trailers, state)
512493
:cowboy_req.stream_trailers(all_trailers, req)
513494

514495
{:ok, req, state}
@@ -781,4 +762,28 @@ defmodule GRPC.Server.Adapters.Cowboy.Handler do
781762

782763
:ok
783764
end
765+
766+
defp stream_grpcweb_trailers(req, trailers, %{access_mode: :grpcweb} = state) do
767+
# grpc_web requires trailers be sent as the last
768+
# message block rather than in the HTTP trailers
769+
# as javascript runtimes do not propagate trailers
770+
#
771+
# trailers are instead denoted with the "trailer flag"
772+
# which has the MSB set to 1.
773+
{:ok, data, _length} =
774+
trailers
775+
|> Enum.map_join("\r\n", fn {k, v} -> "#{k}: #{v}" end)
776+
|> GRPC.Message.to_data(message_flag: @trailers_flag)
777+
778+
packed =
779+
if function_exported?(state.codec, :pack_for_channel, 1) do
780+
state.codec.pack_for_channel(data)
781+
else
782+
data
783+
end
784+
785+
:cowboy_req.stream_body(packed, :nofin, req)
786+
end
787+
788+
defp stream_grpcweb_trailers(req, _trailers, _not_grpcweb), do: req
784789
end

0 commit comments

Comments
 (0)