-
Notifications
You must be signed in to change notification settings - Fork 5
Add streaming support #57
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
Open
bglusman
wants to merge
3
commits into
HGInsights:main
Choose a base branch
from
bglusman:add_streaming_support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 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 |
|---|---|---|
|
|
@@ -47,7 +47,7 @@ defmodule Avalanche.Steps.DecodeData do | |
|
|
||
| def decode_data(request_response), do: request_response | ||
|
|
||
| defp decode_data_rows(types, data, downcase_column_names) do | ||
| defp decode_data_rows(types, data, downcase_column_names) when is_list(data) do | ||
| Enum.map(data, fn row -> | ||
| Enum.zip_reduce(types, row, %{}, fn type, value, result -> | ||
| column_name = maybe_downcased_column_name(type, downcase_column_names) | ||
|
|
@@ -57,6 +57,20 @@ defmodule Avalanche.Steps.DecodeData do | |
| end) | ||
| end | ||
|
|
||
| defp decode_data_rows(types, %Stream{} = data, downcase_column_names) do | ||
| Stream.map(data, fn row -> | ||
| Enum.zip_reduce(types, row, %{}, fn type, value, result -> | ||
| column_name = maybe_downcased_column_name(type, downcase_column_names) | ||
| column_value = decode(type, value) | ||
| Map.put(result, column_name, column_value) | ||
| end) | ||
|
Comment on lines
+62
to
+66
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. we could DRY this up with the above function head of |
||
| end) | ||
| end | ||
|
|
||
| defp decode_data_rows(types, data, downcase_column_names) do | ||
| decode_data_rows(types, Stream.map(data, & &1), downcase_column_names) | ||
| end | ||
|
|
||
| defp maybe_downcased_column_name(type, true), do: type |> Map.fetch!("name") |> String.downcase() | ||
| defp maybe_downcased_column_name(type, false), do: Map.fetch!(type, "name") | ||
|
|
||
|
|
||
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,137 @@ | ||
| defmodule Avalanche.Steps.StreamPartitions do | ||
| @moduledoc """ | ||
| A custom `Req` pipeline step to stream partitions of data from a statement execution. | ||
|
|
||
| This module implements streaming of partitioned data responses from Snowflake using the SQL API. | ||
| It ensures partitions are retrieved and processed in the correct order. | ||
|
|
||
| See: https://docs.snowflake.com/en/developer-guide/sql-api/handling-responses | ||
| """ | ||
|
|
||
| require Logger | ||
|
|
||
| @doc """ | ||
| Attach the streaming step to a Req pipeline. | ||
|
|
||
| ## Options | ||
|
|
||
| * `:max_concurrency` - sets the maximum number of tasks to run at the same time. | ||
| Defaults to `System.schedulers_online/0`. | ||
|
|
||
| * `:timeout` - the maximum amount of time to wait (in milliseconds) for each partition. | ||
| Defaults to 2 minutes. | ||
| """ | ||
| def attach(%Req.Request{} = request, options \\ []) do | ||
| request | ||
| |> Req.Request.register_options([:max_concurrency, :timeout, :params]) | ||
| |> Req.Request.merge_options(options) | ||
| |> Req.Request.append_response_steps(stream_partitions: &stream_partitions/1) | ||
| end | ||
|
|
||
| def stream_partitions(request_response) | ||
|
|
||
| def stream_partitions({request, %{status: 200, body: %{"resultSetMetaData" => metadata} = body} = response}) do | ||
| options = request.options || %{} | ||
| max_concurrency = Map.get(options, :max_concurrency, System.schedulers_online()) | ||
| timeout = Map.get(options, :timeout, 120_000) # Default to 2 minutes | ||
|
|
||
| path = Map.get(body, "statementStatusUrl") | ||
| data = Map.get(body, "data", []) | ||
|
|
||
| row_types = Map.get(metadata, "rowType", []) | ||
| partitions = Map.get(metadata, "partitionInfo", []) | ||
|
|
||
| partition_stream = | ||
| case {path, partitions} do | ||
| {nil, _} -> | ||
| [] | ||
|
|
||
| {_, []} -> | ||
| [] | ||
|
|
||
| {_, "0"} -> | ||
| [] | ||
|
|
||
| {path, [_head | rest]} when is_binary(path) -> | ||
| rest | ||
| |> Stream.with_index(1) | ||
| |> Stream.map(fn {_info, partition} -> | ||
| build_status_request(request, path, partition, row_types) | ||
| end) | ||
| |> Task.async_stream( | ||
| fn req -> | ||
| Req.Request.run_request(req) | ||
| end, | ||
| ordered: true, | ||
| max_concurrency: max_concurrency, | ||
| timeout: timeout, | ||
| on_timeout: :kill_task | ||
| ) | ||
| |> Stream.map(fn | ||
| {:ok, {:ok, value}} -> value | ||
| {:ok, error} -> error_response(error) | ||
| {:exit, reason} -> error_response(reason) | ||
| end) | ||
| |> Stream.map(&handle_partition_response/1) | ||
| |> Stream.filter(&(&1.status == 200)) | ||
| |> Stream.flat_map(&Map.get(&1.body, "data", [])) | ||
| end | ||
|
|
||
| # Create a stream of the initial data and partition data | ||
| stream = Stream.concat(Stream.map([data], & &1), partition_stream) | ||
| {request, %{response | body: Map.put(body, "data", stream)}} | ||
| end | ||
|
|
||
| def stream_partitions({request, %{status: 200, body: ""} = response}) do | ||
| {request, response} | ||
| end | ||
|
|
||
| def stream_partitions({request, %{status: 202} = response}) do | ||
| {request, response} | ||
| end | ||
|
|
||
| def stream_partitions({request, %{status: status} = response}) when status >= 400 do | ||
| {request, response} | ||
| end | ||
|
|
||
| def stream_partitions(request_response), do: request_response | ||
|
|
||
| # Private helpers | ||
|
|
||
| defp build_status_request(request, path, partition, row_types) do | ||
| # Start with a new request but copy over the relevant options from the original | ||
| # Handle cases where headers might be nil | ||
| headers = request.headers || %{} | ||
| options = request.options || %{} | ||
|
|
||
| Req.new( | ||
| method: :get, | ||
| url: path, | ||
| params: [partition: partition], | ||
| auth: options[:auth], # Get auth from options | ||
| headers: headers, | ||
| receive_timeout: options[:timeout] # Map our timeout to Req's receive_timeout | ||
| ) | ||
| |> Req.Request.put_private(:avalanche_row_types, row_types) | ||
| end | ||
|
|
||
| defp handle_partition_response(response) do | ||
| case response do | ||
| {:ok, {_request, %Req.Response{} = response}} -> | ||
| response | ||
|
|
||
| {:ok, {_request, exception}} -> | ||
| error_response(exception) | ||
|
|
||
| {:exit, reason} -> | ||
| error_response(reason) | ||
|
|
||
| other -> | ||
| error_response(other) | ||
| end | ||
| end | ||
|
|
||
| defp error_response(reason) do | ||
| %{status: 500, body: %{"message" => inspect(reason)}} | ||
| 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| defmodule Avalanche.Steps.StreamPartitionsTest do | ||
| use ExUnit.Case, async: true | ||
| alias Avalanche.Steps.StreamPartitions | ||
|
|
||
| setup do | ||
| # Set up Task.Supervisor for async streaming | ||
| start_supervised({Task.Supervisor, name: Avalanche.TaskSupervisor}) | ||
|
|
||
| # Mock response data | ||
| base_response = %Req.Response{ | ||
| status: 200, | ||
| body: %{ | ||
| "resultSetMetaData" => %{ | ||
| "rowType" => [ | ||
| %{"name" => "col1", "type" => "text"} | ||
| ], | ||
| "partitionInfo" => [ | ||
| %{"rowCount" => 2}, | ||
| %{"rowCount" => 3} | ||
| ] | ||
| }, | ||
| "statementStatusUrl" => "https://example.snowflakecomputing.com/status", | ||
| "data" => [["first"]] | ||
| } | ||
| } | ||
|
|
||
| # Mock request with all necessary fields | ||
| request = | ||
| Req.new( | ||
| url: "https://example.snowflakecomputing.com", | ||
| auth: {:bearer, "test-token"}, | ||
| headers: %{"Content-Type" => "application/json"}, | ||
| receive_timeout: 120_000 | ||
| ) | ||
| |> Req.Request.register_options([:max_concurrency, :timeout]) # Register our custom options | ||
| |> Req.Request.merge_options( | ||
| timeout: 120_000, | ||
| max_concurrency: System.schedulers_online() | ||
| ) | ||
|
|
||
| {:ok, request: request, base_response: base_response} | ||
| end | ||
|
|
||
| describe "attach/2" do | ||
| test "attaches streaming step to request pipeline" do | ||
| request = %Req.Request{} | ||
| result = StreamPartitions.attach(request) | ||
|
|
||
| assert Keyword.has_key?(result.response_steps, :stream_partitions) | ||
| end | ||
| end | ||
|
|
||
| describe "stream_partitions/1" do | ||
| test "handles empty response body", %{request: request} do | ||
| empty_response = %Req.Response{body: Stream.into([], []), status: 200} | ||
| assert {^request, ^empty_response} = StreamPartitions.stream_partitions({request, empty_response}) | ||
| end | ||
|
|
||
| test "handles response with no partitions", %{request: request} do | ||
| response = %Req.Response{ | ||
| status: 200, | ||
| body: %{ | ||
| "resultSetMetaData" => %{ | ||
| "rowType" => [], | ||
| "partitionInfo" => [] | ||
| }, | ||
| "data" => "" | ||
| } | ||
| } | ||
|
|
||
| {_req, result} = StreamPartitions.stream_partitions({request, response}) | ||
| assert Enum.to_list(result.body["data"]) == [""] | ||
| end | ||
|
|
||
| test "handles response with missing fields", %{request: request} do | ||
| response = %Req.Response{ | ||
| status: 200, | ||
| body: %{ | ||
| "resultSetMetaData" => %{}, | ||
| "data" => [] | ||
| } | ||
| } | ||
|
|
||
| {_req, result} = StreamPartitions.stream_partitions({request, response}) | ||
| assert Enum.to_list(result.body["data"]) == [[]] | ||
| end | ||
|
|
||
| test "processes partitioned response", %{request: request, base_response: response} do | ||
| {_req, result} = StreamPartitions.stream_partitions({request, response}) | ||
|
|
||
| assert is_function(result.body["data"]) | ||
| assert length(Enum.to_list(result.body["data"])) >= 1 | ||
| end | ||
| end | ||
| end |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
hmm should this ALSO be
fetch!because of howNimbleOptionswill build opts and take care of the default value I guess?