GithubHelp home page GithubHelp logo

riffed's Introduction

Riffed

Version Build Status Coverage Status Issues License

Healing the rift between Elixir and Thrift.

Thrift's Erlang implementation isn't very pleasant to use in Elixir. It prefers records to structs, littering your code with tuples. It swallows enumerations you've defined, banishing them to the realm of wind and ghosts. It requires that you write a bunch of boilerplate handler code, and client code that's not very Elixir-y. Riffed fixes this.

Getting Started

For a detailed guide on how to get started with Riffed, and creating your first Riffed server and client, see the Getting Started Guide. For a general summary of some of the features Riffed provides, continue reading.

You can also generate Riffed documentation by running mix docs.

Riffed Provides three modules, Riffed.Struct, Riffed.Client, and Riffed.Server which will help you manage this impedence mismatch.

Elixir-style structs with Riffed.Struct

Riffed.Struct provides functionality for converting Thrift types into Elixir structs.

You tell Riffed.Struct about your Erlang Thrift modules and which structs you would like to import. It then looks at the thrift files, parses their metadata and builds Elixir structs for you. It also creates to_elixir and to_erlang functions that will handle converting Erlang records into Elixir structs and vice versa.

Assuming you have a Thrift module called pinterest_types in your src directory:

defmodule Structs do
  use Riffed.Struct, pinterest_types: [:User, :Pin, :Board]
end

Then you can do the following:

iex> user = Structs.User.new(firstName: "Stinky", lastName: "Stinkman")
iex> user_tuple = Structs.to_erlang(user, {:pinterest_types, :User}
{:User, "Stinky", "Stinkman"}

iex> Structs.to_elixir(user_tuple)
%Structs.User{firstName: "Stinky", lastName: "Stinkman"}

...but you'll rarely use the Struct module directly. Instead, you'll use the Riffed.Client or Riffed.Server modules.

If your Thrift structs define default values for fields, these will be preserved in Elixir structs, using appropiate types. The only exception is that Riffed cannot handle default values that reference other structs; the default value for these fields will always be :undefined.

Generating Servers with Riffed.Server

Riffed.Server assumes you have a module that has a bunch of handler functions in it. When a thrift RPC is called, your parameters will be converted into Elixir structs and then passed in to one of your handler functions. Let's assume you have the following thrift defined:

enum UserState {
  ACTIVE,
  INACTIVE,
  BANNED;
}

struct User {
  1: string username,
  2: string firstName,
  3: string lastName;
  4: UserState state;
}

service PinterestRegister {
  User register(1: string firstName, 2: string lastName);
  bool isRegistered(1: User user);
  UserState getState(1: string username);
  void setState(1: User user, 2: UserState state);
  void setStatesForUser(1: map<i64, UserState> stateMap);
}

You can set it up like this:

defmodule Server do
  use Riffed.Server,
  service: :pinterest_thrift,
  structs: Data,
  functions: [register: &ThriftHandlers.register/3,
              isRegistered: &ThriftHandlers.is_registered/1,
              getState: &ThriftHandlers.get_state/1,
              setState: &ThriftHandlers.set_state/2
              setStatesForUser: &ThriftHandlers.set_states_for_user/1
  ],
  server: {:thrift_socket_server,
           port: 2112,
           framed: true,
           max: 10_000,
           socket_opts: [
                   recv_timeout: 3000,
                   keepalive: true]
          }

  defenum UserState do
    :active -> 1
    :inactive -> 2
    :banned -> 3
  end

  enumerize_struct User, state: UserState
  enumerize_function setUserState(_, UserState)
  enumerize_function getState(_), returns: UserState
end

defmodule ThriftHandlers do

  def register(username, first_name, last_name) do
    # registration logic. Return a new user
    Data.User.new(username: username, firstName: "Stinky", lastName: "Stinkman")
  end

  def is_registered(user=%Data.User{}) do
    true
  end

  def get_state(username) do
    user = Models.User.fetch(username)
    case user.state do
      :active -> Data.UserState.active
      :banned -> Data.UserState.banned
      _ -> Data.UserState.inactive
    end
  end

  def set_state(user=%Data.User{}, state=%Data.UserState{}) do
    ...
  end

end

Riffed.Server is doing a bunch of work for you. It's investigating your thrift files and figuring out which structs need to be imported by looking at the parameters, exceptions and return values. It then makes a module that imports your structs (Data in this case) and builds code for the thrift server that takes an incoming thrift request, converts its parameters into Elixir representations and then calls your handler. Notice how the handlers in ThriftHandlers take structs as arguments and return structs. That's what Riffed gets you.

These handler functions also process the values your code returns and hands them back to thrift.

The above example also shows how to handle Thrift enums. Due to the way thrift enums are handled by the erlang generator, there's no way for Riffed to convert them into a friendly structure for you, so they need to be defined and pointed out to Riffed.

The thrift server is configured in the server block. The first element of the tuple is the module of the server you wish to instantiate. In this case, we're using thrift_socket_server. The second element is a Keyword list of configuration options for the server. You cannot set the :name, :handler or :service params. The name and handler are set to the current module. The service is given as the thrift_module option.

Generating a client with Riffed.Client

Generating a client is similarly simple. Riffed.Client just asks that you point it at the erlang module that was generated by thrift, tell it what the client's configuration is and tell it what functions you'd like to import. When that's done, it examines the thrift module, figures out what types you need, creates structs for them and generates helper functions for calling your thrift RPC calls.

Assuming the same configuration above, the following block will generate a client:

defmodule RegisterClient do
  use Riffed.Client,
  structs: Models,
  client_opts: [host: "localhost", port: 1234, framed: true],
  service: :pinterest_thrift,
  import: [:register,
         :isRegistered,
         :getState]

  defenum UserState do
    :active -> 1
    :inactive -> 2
    :banned -> 3
  end

  enumerize_struct User, state: UserState
  enumerize_function getState(_), returns: UserState
end

You start the client by calling start_link:

RegisterClient.start_link

You can then issue calls against the client:

iex> user = RegisterClient.register("Stinky", "Stinkman")
%Models.User{firstName: "Stinky", lastName: "Stinkman")

iex> is_registered = RegisterClient.isRegistered(user)
true

iex> state = RegisterClient.getState(user)
%Models.UserState{ordinal: :active, value: 1}

Clients support the same callbacks and enumeration transformations that the server suports, and they're configured identically.

Sharing Structs

Sometimes, you have common structs that are shared between services. Due to Riffed auto-importing structs based on the server definition, Riffed will duplicate shared structs. This auto-import feature can be disabled by specifying auto_import_structs: false when creating a client or server. You can then use Riffed.Struct to build a struct module:

defmodule SharedStructs do
  use Riffed.Struct, shared_types: [:User, :Account, :Profile]
end

defmodule UserService do
  use Riffed.Server, service: :user_thrift,
  auto_import_structs: false,
  structs: SharedStructs
  ...
end

defmodule ProfileService do
  use Riffed.Server, service: :profile_thrift,
  auto_import_structs: false,
  structs: SharedStructs
  ...
end

Advanced Struct Packaging

Often, thrift files will make use of include statements to share structs. This can present a namespacing problem if you're running several thrift servers or clients that all make use of a common thrift file. This is because each server or client will import the struct separately and produce incompatible structs.

This can be mitigated by using shared structs in a common module and controlling how they're imported. To control the destination module, use the dest_modules keyword dict:

defmodule Models do
  use Riffed.Struct, dest_modules: [common_types: Common,
                                    server_types: Server,
                                    client_types: Client],
                    common_types: [:RequestContext, :User],
                    server_types: [:AccessControlList],
                    client_types: [:UserList]

  defenum Common.UserState do
    :inactive -> 1
    :active -> 2
    :core -> 3
  end

  enumerize_struct Common.User, state: Common.UserState
end

defmodule Server do
  use Riffed.Server, service: :server_thrift,
  auto_import_structs: false,
  structs: Models
  ...
end

defmodule Client do
  use Riffed.Client,
  auto_import_structs: false,
  structs: Models
  ...
end

The above configuration will produce three different modules, Models.Common, Models.Server and Models.Client. The Models module is capable of serializing and deserializing all the types defined in the three submodules, and should be used as your :structs module in your client and servers.

As you can see above, you can also namespace enumerations.

Handling Thrift Enumerations

Unfortunately, enumeration support in Erlang thrift code is lossy and because of this Riffed can't tell where the enumerations you worked so tirelessly to define appear in the generated code. Unfortunately, you have to re-define them and tell Riffed where they are; otherwise, all you'll see are integers.

To do this, Riffed supports a syntax to re-define enumerations, and this syntax is available when you use Riffed.Server and Riffed.Client.

The following examples assume these RPC calls and enumeration:

enum DayOfTheWeek {
  SUNDAY,
  MONDAY,
  TUESDAY,
  WEDNESDAY,
  THURSDAY,
  FRIDAY
}

void setCreatedDay(1: User user, 2: DayOfTheWeek day);
DayOfTheWeek getCreatedDay(1: User user);

First off, you'll need to re-define your enumeration. To do that, use the defenum macro inside of your Riffed.Server or Riffed.Client module:

defenum DayOfTheWeek do
  :sunday -> 1
  :monday -> 2
  :tuesday -> 3
  :wednesday -> 4
  :thursday -> 5
  :friday -> 6
  :saturday -> 7
end
Converting enumerations in structs

Now you'll need to tell Riffed where this enum appears in your other data structures. To do that, use the enumerize_struct macro:

enumerize_struct User, sign_up_day: DayOfTheWeek, last_login_day: DayOfTheWeek

Now all Users will have their sign_up_day and last_login_day fields automatically converted to enumerations.

Converting enumerations in functions

If the enumeration is the argument or return value of a RPC call, you'll need to identify it there too. Use the enumerize_function macro:

enumerize_function setCreatedDay(_, DayOfTheWeek)
enumerize_function getCreatedDay(_) returns: DayOfTheWeek

The enumerize_function macro allows you to mark function arguments and return values with the enumeration you would like to use. Unconverted arguments are signaled by using the _ character. In the example above, setCreatedDay's second argument will be converted to a DayOfTheWeek enumeration and its first argument will be left alone.

Similarly, the function getCreatedDay will have its argument left alone and its return value converted into a DayOfTheWeek enumeration

Complex types are also handled in both arguments and return types:

enumerize_function setStatesForUser({:map, {:i64, UserState}})
Using enumerations in code

Enumerations are elixir structs whose modules support converting between the struct and integer representation. This shows how to convert integers to enumerations and vice-versa

iex> x = DayOfWeek.monday
%DayOfWeek{ordinal: :monday, value: 2}

iex> x.value
1

iex> x = DayOfWeek.value(4)
%DayOfWeek{ordinal: :thursday, value: 4}

iex> x.ordinal
:thursday

Since they're just maps, enumerations support pattern matching.

def handle_user(user=%User{sign_up_day: DayOfTheWeek.monday}) do
  # code for users that signed up on monday
end

def handle_user(user=%User{})
  # code for everyone else
end

You can also retrieve the ordinals, values, or mappings from an enumeration.

iex> DayOfWeek.ordinals
[:sunday, :monday, :tuesday, ...]

iex> DayOfWeek.values
[1, 2, 3, ...]

iex> DayOfWeek.mappings
[sunday: 1, monday: 2, tuesday: 3, ...]

riffed's People

Contributors

aawilson avatar austinmontoya avatar binaryseed avatar edwardt avatar jparise avatar letusfly85 avatar nickzh avatar scohen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

riffed's Issues

Please consider making riffed available as a package on hex.pm

Please consider making riffed available as a package on hex.pm, so other hex packages can refer to this project as a dependency :)

On another topic, please also consider removing exlager from the lib dependencies, so using this library does not force you to use it.

Thanks!

Using riffed for deserialization of binary data

Hello! I'm currently using riffed to try and deserialize messages coming in from a kafka stream. I've created a models.ex with:

defmodule Models do
  use Riffed.Struct, common_types: [:Location, ...],
    event_types:[:Event, ...]
end

My thrift files are compiled from the instructions provided on this github.

My function for converting binary -> Thrift struct (is copied from @scohen here

def to_thrift(record_binary, struct_definition) do

    try do
      with({:ok, memory_buffer_transport} <- :thrift_memory_buffer.new(record_binary),
           {:ok, binary_protocol} <- :thrift_binary_protocol.new(memory_buffer_transport),
           {_, {:ok, record}} <- :thrift_protocol.read(binary_protocol, struct_definition)) do

        {:ok, Models.to_elixir(record, struct_definition)}
      end

    rescue e ->
      IO.inspect e
        {:error, :cant_decode}
    end
  end

I'm looking at my logs and I keep seeing something like:

%FunctionClauseError{args: nil, arity: 2, clauses: nil, function: :skip,
 kind: nil, module: :thrift_protocol}

Has anyone run into this kind of error and if so what is the workaround? Thanks!

[Question] In server.ex there is a reference to ZkRegister .

In server.ex
after_start: fn(server_pid, server_opts) ->
ZKRegister.death_pact(server_pid, server_opts[:port]) <----??? Some zookeeper thing?
end,

I am guessing it is some zookeeper elixir wrapper, but not seeing it from any deps pulled it; and so far not, in code.

retries off by one error

<fishcakez> https://github.com/pinterest/riffed/blob/master/lib/riffed/client.ex#L199 this also seems to have an off by 1 error
<fishcakez> so maybe try setting retries: 1
<fishcakez> as if retries: 0 then it will never try :/

Small confusion in Getting Starting Guide

In the beginning you state:
'We'll assume you already have a Mix project to work with called rift_tutorial. Feel free to go create one if you don't, using mix new rift_tutorial --sup.'

Should it not be 'mix new riffed_tutorial --sup' ?

Support thrift master?

Since the server I'm using requires the definition of:

Type "i8" has not been defined.

Can you check if Riffed works with thrift master?

Is there any other option I can take?

Undefined function Logger.notice/1

An UndefinedFunctionError is raised in this function:

def handle_error(_, :timeout) do
  Logger.notice("Connection to client timed out.")
  {:ok, :timeout}
end

notice/1 is part of Lager. Maybe use Logger.warn/2 or Logger.info/2 ?

This occurred after #47.

Unstable build runs due to unclean server shutdown

Some logs are showing server startup error out complaining address in use from
lingering server process
e.g. address ** (EXIT from #PID<0.1690.0>) :eaddrinuse
Examples of failed build runs:
https://travis-ci.org/pinterest/riffed/builds/100428104
https://travis-ci.org/pinterest/riffed/builds/100394694
https://travis-ci.org/pinterest/riffed/builds/97888684

There are projects that use underlying Erlang library (which is also used in common test in Erlang) to deal with more reliable server shutdown/startup:

There are tests in gen_rpc, that spawned a few Erlang nodes sending messages to each other, for their tests (also on travisci). So there may be something useful there. Those projects are also on travisci so have to deal with travisci build VM performance variance.

Potential unnecessary libraries for mix prod environment

Both meck and mock are mocking libraries, for prod environment, there is no need to distribute as such. Add only:[:dev, :test] as constraint ??? This applies to other elixir projects.

i mix.exs
{:meck, "~> 0.8.2"},
{:mock, github: "jjh42/mock"},

Compile error in examples/tutorial/

With a fresh clone of the repo, if I cd into examples/tutorial and run mix deps.get followed by mix compile I get the following error:

== Compilation error on file lib/riffed_tutorial/models.ex ==
** (FunctionClauseError) no function clause matching in :tutorial_types.struct_info_ext/1
    src/tutorial_types.erl:21: :tutorial_types.struct_info_ext(:User)
    lib/riffed/struct.ex:157: Riffed.Struct.build_struct_and_conversion_function/5
    (elixir) lib/enum.ex:1623: Enum."-reduce/3-lists^foldl/2-0-"/3
    expanding macro: Riffed.Struct.__before_compile__/1
    lib/riffed_tutorial/models.ex:1: RiffedTutorial.Models (module)

I'm getting the same error in my own project trying to use riffed so wondering if you have any ideas?

Running Elixir 1.3.4

Use Riffed to serialize/deserialize messages

Hello,

Thanks for making our lives easier with Riffed! :) It's really nice to work with it.

In some parts of our service we would like to just serialize models and transport them to other parts of the system over RabbitMQ. Ruby and Elixir will talk to each other over RabbitMQ. For Ruby side we are covered with https://wiki.apache.org/thrift/ThriftUsageRuby. Is there something as easy to use on the Riffed side?

Thanks,
Darko

Difference with pinterest/elixir-thrift

Hello :)
Really great work for the Thrift implementation in Elixir.
But I'm stuck to know which repo and implementation is better or the most up to date between
this one and the pinterest/elixir-thrift.

Why 2 repositories for the same implementation ? Because this one as the advantage to prevent code generation.

Thanks

Problems of deserializing nils and enums

I've been playing with Riffed and I encountered a problem when writing tests.

My service is a simple CRUD service that allows clients to create, get, update, and delete animals. (think of the service as a zoo service)

In the test where I try to get an animal that doesn't exist, the assertion fails because of:

  1) test get animal that doesn't exist (ZooServerTest)
     test/zoo_server_test.exs:26
     Assertion with == failed
     code: response.error() == error
     lhs:  %ZooServer.Models.Error{errors: [%ZooServer.Models.ErrorEntry{message: "animal not found", location: nil, reason: 7}]}
     rhs:  %ZooServer.Models.Error{errors: [%ZooServer.Models.ErrorEntry{message: "animal not found", location: :undefined, reason: %ZooServer.Models.ErrorReason{ordinal: :resource_not_found, value: 7}}]}
     stacktrace:
       test/zoo_server_test.exs:32: (test)

So there are two problems:

  1. The service doesn't specify a location so the client deserializes location as "nil". However, when I create an ErrorEntry manually on the client side, the location would default to ":undefined". The Riffed doc clearly says so but I wonder why struct fields won't default to nil?
  2. The 2nd problem relates to enums. When the client deserializes the reason, it sets it to 7. However, when I create an ErrorEntry manually, I use "Models.ErrorReason.resource_not_found" and I get a struct with ordinal and value. Obviously, you can't compare 7 with a struct object. So why won't Riffed or elixir-thrift deserializes 7 into a nice struct object? They should be able to do so based on number 7 I think.

Use of binary_protocol

How do I deserialize a binary_message, like a simple function call? (e.g. add(1,1))
I can't seem to find the right usage of the :thrift_protocol.read function

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.