-
Notifications
You must be signed in to change notification settings - Fork 352
Request/Response streaming for Finch adapter, SSE middleware #540
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,102 @@ | ||
defmodule Tesla.Middleware.SSE do | ||
@moduledoc """ | ||
Decode Server Sent Events. | ||
This middleware is mostly useful when streaming response body. | ||
## Examples | ||
``` | ||
plug Tesla.Middleware.SSE, only: :data | ||
``` | ||
## Options | ||
- `:only` - keep only specified keys in event (necessary for using with `JSON` middleware) | ||
- `:decode_content_types` - list of additional decodable content-types | ||
""" | ||
|
||
@behaviour Tesla.Middleware | ||
|
||
@default_content_types ["text/event-stream"] | ||
|
||
@impl Tesla.Middleware | ||
def call(env, next, opts) do | ||
opts = opts || [] | ||
|
||
with {:ok, env} <- Tesla.run(env, next) do | ||
decode(env, opts) | ||
end | ||
end | ||
|
||
def decode(env, opts) do | ||
if decodable_content_type?(env, opts) do | ||
{:ok, %{env | body: decode_body(env.body, opts)}} | ||
else | ||
{:ok, env} | ||
end | ||
end | ||
|
||
defp decode_body(body, opts) when is_struct(body, Stream) or is_function(body) do | ||
body | ||
|> Stream.chunk_while( | ||
"", | ||
fn elem, acc -> | ||
{lines, [rest]} = (acc <> elem) |> String.split("\n\n") |> Enum.split(-1) | ||
{:cont, lines, rest} | ||
end, | ||
fn | ||
"" -> {:cont, ""} | ||
acc -> {:cont, acc, ""} | ||
end | ||
) | ||
|> Stream.flat_map(& &1) | ||
|> Stream.map(&decode_message/1) | ||
|> Stream.flat_map(&only(&1, opts[:only])) | ||
end | ||
|
||
defp decode_body(binary, opts) when is_binary(binary) do | ||
binary | ||
|> String.split("\n\n") | ||
|> Enum.map(&decode_message/1) | ||
|> Enum.flat_map(&only(&1, opts[:only])) | ||
end | ||
|
||
defp decode_message(message) do | ||
message | ||
|> String.split("\n") | ||
|> Enum.map(&decode_body/1) | ||
|> Enum.reduce(%{}, fn | ||
:empty, acc -> acc | ||
{:data, data}, acc -> Map.update(acc, :data, data, &(&1 <> "\n" <> data)) | ||
{key, value}, acc -> Map.put_new(acc, key, value) | ||
end) | ||
end | ||
|
||
defp decode_body(": " <> comment), do: {:comment, comment} | ||
defp decode_body("data: " <> data), do: {:data, data} | ||
defp decode_body("event: " <> event), do: {:event, event} | ||
defp decode_body("id: " <> id), do: {:id, id} | ||
defp decode_body("retry: " <> retry), do: {:retry, retry} | ||
defp decode_body(""), do: :empty | ||
|
||
defp decodable_content_type?(env, opts) do | ||
case Tesla.get_header(env, "content-type") do | ||
nil -> false | ||
content_type -> Enum.any?(content_types(opts), &String.starts_with?(content_type, &1)) | ||
end | ||
end | ||
|
||
defp content_types(opts), | ||
do: @default_content_types ++ Keyword.get(opts, :decode_content_types, []) | ||
|
||
defp only(message, nil), do: [message] | ||
|
||
defp only(message, key) do | ||
case Map.get(message, key) do | ||
nil -> [] | ||
val -> [val] | ||
end | ||
end | ||
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
defmodule Tesla.AdapterCase.StreamResponseBody do | ||
defmacro __using__(_) do | ||
quote do | ||
alias Tesla.Env | ||
|
||
describe "Stream Response" do | ||
test "stream response body" do | ||
request = %Env{ | ||
method: :get, | ||
url: "#{@http}/stream/20" | ||
} | ||
|
||
assert {:ok, %Env{} = response} = call(request, response: :stream) | ||
assert response.status == 200 | ||
assert is_function(response.body) || response.body.__struct__ == Stream | ||
|
||
body = Enum.to_list(response.body) | ||
assert Enum.count(body) == 20 | ||
end | ||
end | ||
end | ||
end | ||
end |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.