• Stars
    star
    307
  • Rank 136,109 (Top 3 %)
  • Language
    Elixir
  • License
    Apache License 2.0
  • Created about 9 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Provides idiomatic Elixir bindings for Apache Thrift

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, ...]

More Repositories

1

ktlint

An anti-bikeshedding Kotlin linter with built-in formatter
Kotlin
6,192
star
2

gestalt

A set of React UI components that supports Pinterest’s design language
TypeScript
4,240
star
3

PINRemoteImage

A thread safe, performant, feature rich image fetcher
Objective-C
4,009
star
4

PINCache

Fast, non-deadlocking parallel object cache for iOS, tvOS and OS X
Objective-C
2,660
star
5

querybook

Querybook is a Big Data Querying UI, combining collocated table metadata and a simple notebook interface.
TypeScript
1,923
star
6

secor

Secor is a service implementing Kafka log persistence
Java
1,845
star
7

teletraan

Teletraan is Pinterest's deploy system.
Java
1,807
star
8

knox

Knox is a secret management service
Go
1,229
star
9

pinball

Pinball is a scalable workflow manager
JavaScript
1,048
star
10

mysql_utils

Pinterest MySQL Management Tools
Python
883
star
11

snappass

Share passwords securely
Python
837
star
12

elixometer

A light Elixir wrapper around exometer.
Elixir
827
star
13

pymemcache

A comprehensive, fast, pure-Python memcached client.
Python
771
star
14

bonsai

Understand the tree of dependencies inside your webpack bundles, and trim away the excess.
JavaScript
738
star
15

rocksplicator

RocksDB Replication
C++
662
star
16

esprint

Fast eslint runner
JavaScript
661
star
17

bender

An easy-to-use library for creating load testing applications
Go
658
star
18

DoctorK

DoctorK is a service for Kafka cluster auto healing and workload balancing
Java
633
star
19

plank

A tool for generating immutable model objects
Swift
469
star
20

thrift-tools

thrift-tools is a library and a set of tools to introspect Apache Thrift traffic.
Python
233
star
21

elixir-thrift

A Pure Elixir Thrift Implementation
Elixir
214
star
22

widgets

JavaScript widgets, including the Pin It button.
JavaScript
210
star
23

singer

A high-performance, reliable and extensible logging agent for uploading data to Kafka, Pulsar, etc.
Java
178
star
24

terrapin

Serving system for batch generated data sets
Java
176
star
25

git-stacktrace

Easily figure out which git commit caused a given stacktrace
Python
158
star
26

jbender

An easy-to-use library for creating load testing applications.
Java
156
star
27

ptracer

A library for ptrace-based tracing of Python programs
Python
155
star
28

react-pinterest

JavaScript
151
star
29

pinlater

PinLater is a Thrift service to manage scheduling and execution of asynchronous jobs.
Java
135
star
30

memq

MemQ is an efficient, scalable cloud native PubSub system
Java
129
star
31

api-quickstart

Code that makes it easy to get started with the Pinterest API.
Python
122
star
32

it-cpe-cookbooks

A suite of Chef cookbooks that we use to manage our fleet of client devices
Ruby
118
star
33

psc

PubSubClient (PSC)
Java
117
star
34

pinterest-api-demo

JavaScript
106
star
35

PINOperation

Objective-C
104
star
36

orion

Management and automation platform for Stateful Distributed Systems
Java
101
star
37

soundwave

A searchable EC2 Inventory store
Java
96
star
38

PINFuture

An Objective-C future implementation that aims to provide maximal type safety
Objective-C
83
star
39

kingpin

KingPin is the toolset used at Pinterest for service discovery and application configuration.
Python
69
star
40

arcanist-linters

A collection of custom Arcanist linters
PHP
63
star
41

pagerduty-monit

Wrapper scripts to integrate monit and PagerDuty.
Shell
60
star
42

pinrepo

Pinrepo is a highly scalable solution for storing and serving build artifacts such as debian packages, maven jars and pypi packages.
Python
58
star
43

transformer_user_action

Transformer-based Realtime User Action Model for Recommendation at Pinterest
Python
49
star
44

quasar-thrift

A Thrift server that uses Quasar's lightweight threads to handle connections.
Java
47
star
45

pinterest-python-sdk

An SDK that makes it quick and easy to build applications with Pinterest API.
Python
47
star
46

yuvi

Yuvi is an in-memory storage engine for recent time series metrics data.
Java
45
star
47

atg-research

Python
41
star
48

slackminion

A python bot framework for slack
Python
22
star
49

api-description

OpenAPI descriptions for Pinterest's REST API
18
star
50

l10nmessages

L10nMessages is a library that makes internationalization (i18n) and localization (l10n) of Java applications easy and safe.
Java
17
star
51

thriftcheck

A linter for Thrift IDL files
Go
16
star
52

arcanist-owners

An Arcanist extension for displaying file ownership information
PHP
16
star
53

tiered-storage

Pinterest's simplified and efficient Tiered Storage implementation for Kafka
Java
13
star
54

.github

Pinterest's Open Source Project Template
12
star
55

homebrew-tap

macOS Homebrew formulas to install Pinterest open source software
Ruby
12
star
56

pinterest-python-generated-api-client

This is the auto-generated code using OpenAPI generator. Generated code comprises HTTP requests to various v5 API endpoints.
Python
12
star
57

vscode-gestalt

Visual Studio Code extension for Gestalt, Pinterest's design system
TypeScript
9
star
58

wheeljack

Work with interdependent python repositories seemlessly.
Python
8
star
59

ffffound

FFFFOUND Import tool for Pinterest
HTML
8
star
60

vscode-package-watcher

Watch package lock files and suggest to re-run npm or yarn.
TypeScript
6
star
61

graphql-lint-rules

Pinterest GraphQL Lint Rules
TypeScript
6
star
62

ss-gtm-template

This is a repository to implement the Google Tag Manager server-side tag template for Pinterest Conversions API to be deployed into Google Community Template Gallery.
Smarty
5
star
63

pinterest-magento2-extension

PHP
4
star
64

Pinterest-Salesforce-Commerce-Cartridge

JavaScript
4
star
65

figma-calculations

TypeScript
2
star
66

slate

Resource Lifecycle Management framework
Java
1
star