Skip to content
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

Introduce middleware for Tesla HTTP Client #18

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,5 @@ erl_crash.dump

/bench/snapshots
/bench/graphs

.devcontainer
82 changes: 62 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@ the risk that a malicious client can exhaust out atom space and crash the vm.

Add XML-RPC to your mix dependencies

def deps do
[{:xmlrpc, "~> 1.0"}]
end
```elixir
def deps do
[{:xmlrpc, "~> 1.0"}]
end
```

Then run `mix deps.get` and `mix deps.compile`.

Expand Down Expand Up @@ -62,48 +64,88 @@ If you want a <nil/> input to be treated as an error then pass
The XML-RPC api consists of a call to a remote url, passing a "method_name"
and a number of parameters.

%XMLRPC.MethodCall{method_name: "test.sumprod", params: [2,3]}
```elixir
%XMLRPC.MethodCall{method_name: "test.sumprod", params: [2,3]}
```

The response is either "failure" and a `fault_code` and `fault_string`, or a
response which consists of a single parameter (use a struct/array to pass back
multiple values)

%XMLRPC.Fault{fault_code: 4, fault_string: "Too many parameters."}
```elixir
%XMLRPC.Fault{fault_code: 4, fault_string: "Too many parameters."}
```

%XMLRPC.MethodResponse{param: 30}
```elixir
%XMLRPC.MethodResponse{param: 30}
```

To encode/decode to xml use `XMLRPC.encode/2` or `XMLRPC.decode/2`

## Examples

### Client using Tesla

[Tesla](https://github.com/teamon/tesla) can be used to talk to the remote API.

There is dedicated Middleware available [here](lib/xml_rpc/tesla/middleware.ex).

```elixir
defmodule Client do
use Tesla

plug XMLRPC.Tesla.Middleware

def sumprod(a, b) do
post("http://www.advogato.org/XMLRPC", %XMLRPC.MethodCall(method_name: "test.sumprod", params: [a, b]))
end
end
```

Your request body will be automatically converted to `%XMLRPC.MethodCall` struct and your response will be
automatically marshalled to `%XMLRPC.MethodResponse`.

You can use `XMLRPC.Tesla.Middleware.Encode` or `XMLRPC.Tesla.Middleware.Decode` middlewares if you only
need encode/decode option. By default only 2xx responses are parsed but that is configurable.

```elixir
plug XMLRPC.Tesla.Middleware, decodable_status: fn status -> status in 200..299
```

You can see all options available in the moduledoc [here](lib/xml_rpc/tesla/middleware.ex).

### Client using HTTPoison

[HTTPoison](https://github.com/edgurgel/httpoison) can be used to talk to the remote API. To encode the body we can
simply call `XMLRPC.encode/2`, and then decode the response with `XMLRPC.decode/2`

request_body = %XMLRPC.MethodCall{method_name: "test.sumprod", params: [2,3]}
|> XMLRPC.encode!
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodCall><methodName>test.sumprod</methodName><params><param><value><int>2</int></value></param><param><value><int>3</int></value></param></params></methodCall>"
```elixir
request_body = %XMLRPC.MethodCall{method_name: "test.sumprod", params: [2,3]}
|> XMLRPC.encode!
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodCall><methodName>test.sumprod</methodName><params><param><value><int>2</int></value></param><param><value><int>3</int></value></param></params></methodCall>"

# Now use HTTPoison to call your RPC
response = HTTPoison.post!("http://www.advogato.org/XMLRPC", request_body).body
# Now use HTTPoison to call your RPC
response = HTTPoison.post!("http://www.advogato.org/XMLRPC", request_body).body

# eg
response = "<?xml version=\"1.0\"?><methodResponse><params><param><value><array><data><value><int>5</int></value><value><int>6</int></value></data></array></value></param></params></methodResponse>"
|> XMLRPC.decode
{:ok, %XMLRPC.MethodResponse{param: [5, 6]}}
# eg
response = "<?xml version=\"1.0\"?><methodResponse><params><param><value><array><data><value><int>5</int></value><value><int>6</int></value></data></array></value></param></params></methodResponse>"
|> XMLRPC.decode
{:ok, %XMLRPC.MethodResponse{param: [5, 6]}}
```

See the [HTTPoison docs](https://github.com/edgurgel/httpoison#wrapping-httpoisonbase)
for more details, but you can also wrap the base API and have HTTPoison
automatically do your encoding and decoding. In this way its very simple to build
higher level APIs

defmodule XMLRPC do
use HTTPoison.Base
```elixir
defmodule XMLRPC do
use HTTPoison.Base

def process_request_body(body), do: XMLRPC.encode(body)
def process_response_body(body), do: XMLRPC.decode(body)
end
def process_request_body(body), do: XMLRPC.encode(body)
def process_response_body(body), do: XMLRPC.decode(body)
end
```

iex> request = %XMLRPC.MethodCall{method_name: "test.sumprod", params: [2,3]}
iex> response = HTTPoison.post!("http://www.advogato.org/XMLRPC", request).body
Expand Down
34 changes: 17 additions & 17 deletions lib/xml_rpc.ex
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ defmodule XMLRPC do
alias XMLRPC.Decoder
alias XMLRPC.Encoder


@moduledoc ~S"""
Encode and decode elixir terms to [XML-RPC](http://wikipedia.org/wiki/XML-RPC) parameters.
All XML-RPC parameter types are supported, including arrays, structs and Nil (optional).
Expand Down Expand Up @@ -90,7 +89,7 @@ defmodule XMLRPC do
@moduledoc """
struct defining an xml-rpc 'fault' response
"""
@type t :: %__MODULE__{fault_code: Integer, fault_string: String.t}
@type t :: %__MODULE__{fault_code: Integer, fault_string: String.t()}

defstruct fault_code: 0, fault_string: ""
end
Expand All @@ -99,7 +98,7 @@ defmodule XMLRPC do
@moduledoc """
struct defining an xml-rpc call (note array of params)
"""
@type t :: %__MODULE__{method_name: String.t, params: [ XMLRPC.t ]}
@type t :: %__MODULE__{method_name: String.t(), params: [XMLRPC.t()]}

defstruct method_name: "", params: nil
end
Expand All @@ -108,29 +107,27 @@ defmodule XMLRPC do
@moduledoc """
struct defining an xml-rpc response (note single param)
"""
@type t :: %__MODULE__{param: XMLRPC.t}
@type t :: %__MODULE__{param: XMLRPC.t()}

defstruct param: nil
end


@type t :: nil | number | boolean | String.t | map() | [nil | number | boolean | String.t]

@type t :: nil | number | boolean | String.t() | map() | [nil | number | boolean | String.t()]

@doc """
Encode an XMLRPC call or response elixir structure into XML as iodata

Raises an exception on error.
"""
@spec encode_to_iodata!(XMLRPC.t, Keyword.t) :: {:ok, iodata} | {:error, {any, String.t}}
@spec encode_to_iodata!(XMLRPC.t(), Keyword.t()) :: {:ok, iodata} | {:error, {any, String.t()}}
def encode_to_iodata!(value, options \\ []) do
encode!(value, [iodata: true] ++ options)
end

@doc """
Encode an XMLRPC call or response elixir structure into XML as iodata
"""
@spec encode_to_iodata(XMLRPC.t, Keyword.t) :: {:ok, iodata} | {:error, {any, String.t}}
@spec encode_to_iodata(XMLRPC.t(), Keyword.t()) :: {:ok, iodata} | {:error, {any, String.t()}}
def encode_to_iodata(value, options \\ []) do
encode(value, [iodata: true] ++ options)
end
Expand All @@ -143,12 +140,12 @@ defmodule XMLRPC do
iex> %XMLRPC.MethodCall{method_name: "test.sumprod", params: [2,3]} |> XMLRPC.encode!
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodCall><methodName>test.sumprod</methodName><params><param><value><int>2</int></value></param><param><value><int>3</int></value></param></params></methodCall>"
"""
@spec encode!(XMLRPC.t, Keyword.t) :: iodata | no_return
@spec encode!(XMLRPC.t(), Keyword.t()) :: iodata | no_return
def encode!(value, options \\ []) do
iodata = Encoder.encode!(value, options)

unless options[:iodata] do
iodata |> IO.iodata_to_binary
iodata |> IO.iodata_to_binary()
else
iodata
end
Expand All @@ -160,26 +157,28 @@ defmodule XMLRPC do
iex> %XMLRPC.MethodCall{method_name: "test.sumprod", params: [2,3]} |> XMLRPC.encode
{:ok, "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodCall><methodName>test.sumprod</methodName><params><param><value><int>2</int></value></param><param><value><int>3</int></value></param></params></methodCall>"}
"""
@spec encode(XMLRPC.t, Keyword.t) :: {:ok, iodata} | {:ok, String.t} | {:error, {any, String.t}}
@spec encode(XMLRPC.t(), Keyword.t()) ::
{:ok, iodata} | {:ok, String.t()} | {:error, {any, String.t()}}
def encode(value, options \\ []) do
{:ok, encode!(value, options)}

rescue
exception in [EncodeError] ->
{:error, {exception.value, exception.message}}
end


@doc ~S"""
Decode XMLRPC call or response XML into an Elixir structure

iex> XMLRPC.decode("<?xml version=\"1.0\"?><methodResponse><params><param><value><array><data><value><int>5</int></value><value><int>6</int></value></data></array></value></param></params></methodResponse>")
{:ok, %XMLRPC.MethodResponse{param: [5, 6]}}
"""
@spec decode(iodata, Keyword.t) :: {:ok, Fault.t} | {:ok, MethodCall.t} | {:ok, MethodResponse.t} | {:error, String.t}
@spec decode(iodata, Keyword.t()) ::
{:ok, Fault.t()}
| {:ok, MethodCall.t()}
| {:ok, MethodResponse.t()}
| {:error, String.t()}
def decode(value, options \\ []) do
{:ok, decode!(value, options)}

rescue
exception in [DecodeError] ->
{:error, exception.message}
Expand All @@ -193,7 +192,8 @@ defmodule XMLRPC do
iex> XMLRPC.decode!("<?xml version=\"1.0\"?><methodResponse><params><param><value><array><data><value><int>5</int></value><value><int>6</int></value></data></array></value></param></params></methodResponse>")
%XMLRPC.MethodResponse{param: [5, 6]}
"""
@spec decode!(iodata, Keyword.t) :: Fault.t | MethodCall.t | MethodResponse.t | no_return
@spec decode!(iodata, Keyword.t()) ::
Fault.t() | MethodCall.t() | MethodResponse.t() | no_return
def decode!(value, options \\ []) do
Decoder.decode!(value, options)
end
Expand Down
13 changes: 8 additions & 5 deletions lib/xml_rpc/base64.ex
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ defmodule XMLRPC.Base64 do

Note: See the `Base` module for other conversions in Elixir stdlib
"""
@type t :: %__MODULE__{raw: String.t}
@type t :: %__MODULE__{raw: String.t()}
defstruct raw: ""

@doc """
Expand All @@ -24,12 +24,15 @@ defmodule XMLRPC.Base64 do
# The <1.2.0 version of elixir won't correctly parse it.
# We manually remove whitespace on older versions of elixir
case encoded do
[] -> {:ok, encoded}
[] ->
{:ok, encoded}

_ ->
if Version.compare(System.version, "1.2.3") == :lt do
if Version.compare(System.version(), "1.2.3") == :lt do
encoded
|> String.replace(~r/\s/, "") # remove any whitespace
|> Base.decode64
# remove any whitespace
|> String.replace(~r/\s/, "")
|> Base.decode64()
else
Base.decode64(encoded, ignore: :whitespace)
end
Expand Down
34 changes: 22 additions & 12 deletions lib/xml_rpc/date_time.ex
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ defmodule XMLRPC.DateTime do
(and perhaps encoder) to speak to non standard end-points...
"""

@type t :: %__MODULE__{raw: String.t}
@type t :: %__MODULE__{raw: String.t()}
defstruct raw: ""

@doc """
Expand All @@ -17,10 +17,14 @@ defmodule XMLRPC.DateTime do
iex> XMLRPC.DateTime.new({{2015,6,9},{9,7,2}})
%XMLRPC.DateTime{raw: "20150609T09:07:02"}
"""
def new({{year, month, day},{hour, min, sec}}) do
date = :io_lib.format("~4.10.0B~2.10.0B~2.10.0BT~2.10.0B:~2.10.0B:~2.10.0B",
[year, month, day, hour, min, sec])
|> IO.iodata_to_binary
def new({{year, month, day}, {hour, min, sec}}) do
date =
:io_lib.format(
"~4.10.0B~2.10.0B~2.10.0BT~2.10.0B:~2.10.0B:~2.10.0B",
[year, month, day, hour, min, sec]
)
|> IO.iodata_to_binary()

%__MODULE__{raw: date}
end

Expand All @@ -37,14 +41,20 @@ defmodule XMLRPC.DateTime do
{:ok, {{2015, 6, 9}, {9, 7, 2}}}
"""
def to_erlang_date(%__MODULE__{raw: date}) do
case Regex.run(~r/(\d{4})-?(\d{2})-?(\d{2})T(\d{2}):(\d{2}):(\d{2})/, date, capture: :all_but_first) do
nil -> {:error, "Unable to parse date"}
date -> [year, mon, day, hour, min, sec] =
date
|> Enum.map(&to_int/1)
{:ok, {{year, mon, day}, {hour, min, sec}}}
case Regex.run(~r/(\d{4})-?(\d{2})-?(\d{2})T(\d{2}):(\d{2}):(\d{2})/, date,
capture: :all_but_first
) do
nil ->
{:error, "Unable to parse date"}

date ->
[year, mon, day, hour, min, sec] =
date
|> Enum.map(&to_int/1)

{:ok, {{year, mon, day}, {hour, min, sec}}}
end
end

defp to_int(str), do: str |> Integer.parse |> elem(0)
defp to_int(str), do: str |> Integer.parse() |> elem(0)
end
Loading