Blog


Dec

A Christmas tree formatter for RSpec!


It's December, a time of glögg and gingerbread cookies with blue cheese… and Christmas trees!

Me and Anders figured we'd bring some Christmas spirit into our test suite, so we created an RSpec formatter very much like the regular progress formatter with green dots… except it's a tree!

Source code is on GitHub, v0.1, and a nasty piece of code, but it's December so it's very much time to ship it! It's named christmas_tree_formatter.

Here's a GIF of it in action:

Imgur

Nov

Retrieving the last N ordered records with ActiveRecord


Here's a database of chat messages.

|  id  | created_at |
|——————|————————————|
|   1  |   13:20    |
|   2  |   13:21    |
|   3  |   13:22    |
|   …  |   ……………    |
|  121 |   14:27    |
|  122 |   14:29    |
|  123 |   14:32    |
|——————|————————————|

So, we're building a chat, and what we'd like to see is the 10 most recent messages, with the oldest of the bunch at the top, and the newest message at the bottom, something like: [<Message 113>, <Message 114>, <Message 115>, …, <Message 123>].

At first, you might think "I'll just sort all messages by created_at in ascending order, and take the last 10". OK, here's what that looks like.

Message.order(created_at: :asc).last(10) # => [<Message 113>, <Message 114>, …, <Message 123>]

Looks good? Yes? No. Have a look at the SQL:

 SELECT "messages".* FROM "messages"  ORDER BY "messages"."created_at" ASC

   |  id  | created_at |
   |——————|————————————|
-> |   1  |   13:20    |
-> |   2  |   13:21    |
-> |   3  |   13:22    |
-> |   …  |   ……………    |
-> |  121 |   14:27    |
-> |  122 |   14:29    |
-> |  123 |   14:32    |
   |——————|————————————|

What, no mention of 10 in our SQL query?! .last is not so clever. We end up loading all messages in our database to Ruby, maybe a few hundred thousand, and then we throw away all messages except for the last 10, what a waste.

Okay, how about using OFFSET? Let's try.

Message.order(created_at: :asc).offset(Message.count - 10).limit(10) # => [<Message 113>, <Message 114>, …, <Message 123>]        

Looks good? Yes? No. Let's look at the SQL:

 SELECT "messages".* FROM "messages"  ORDER BY "messages"."created_at" ASC OFFSET 112 LIMIT 10

     |  id  | created_at |
     |——————|————————————|
SKIP |   1  |   13:20    |
SKIP |   2  |   13:21    |
SKIP |   …  |   ……………    |
  -> |  113 |   14:13    |
  -> |   …  |   ……………    |
  -> |  123 |   14:32    |
     |——————|————————————|

A few important notes about this.

  1. OFFSET in SQL must be a positive number so we can't simply use -10 as our offset.
  2. ActiveRecord will try to coerce our offset to an integer using #to_i, so we can't pass a subquery as our offset, which leaves us with precomputed positive numbers only.
  3. What is our offset? It must be calculated ahead of time using Message.count, this is slow, and prone to race conditions if we get more messages in between our count and select.

Even if we disregard all the above points, have a look at the documentation for LIMIT/OFFSET in PostgreSQL: "The rows skipped by an OFFSET clause still have to be computed inside the server; therefore a large OFFSET might be inefficient."

Oh, OK, so offset is off.

One more try. Let's sort this out with a new mindset. We change the order of our SQL, and reverse the thing in Ruby. That must work!

Message.order(created_at: :asc).reverse_order.limit(10).reverse # => [<Message 113>, <Message 114>, …, <Message 123>]

Looks good? Yes? Let's look at the SQL.

 SELECT "messages".* FROM "messages"  ORDER BY "messages"."created_at" DESC LIMIT 10

   |  id  | created_at |
   |——————|————————————|
-> |  123 |   14:32    |
-> |   …  |   ……………    |
-> |  113 |   14:13    |
   |——————|————————————|

Well, this is actually quite OK. We only retrieve 10 records from the database, which is what we want. Sure, the order of the messages is wrong which is kind of sad, but we can fix that later. Let's make a scope of this and call it a good day!

class << Message
  def in_order
    order(created_at: :asc)
  end

  def recent(n)
    in_order.reverse_order.limit(n).reverse
  end
end

There's a few downsides with this, can you spot it?

  1. We have to reverse it in Ruby.
  2. The return value is an Array, and not an ActiveRecord::Relation, since we force it with reverse.
  3. We can't merge an Array with other scopes.
  4. We can't chain additional SQL conditions to the end of our array to further filter the 10 results, e.g. Message.recent(5).where(…).

We can still do better!

What if I told you there is a way to reverse the result in SQL, and that there's also an OK way to do so with ActiveRecord? I'm sure you'd believe me after all of this, anything else would be cruel.

class Message
  class << self
    def in_order
      order(created_at: :asc)
    end

    def recent(n)
      in_order.endmost(n)
    end

    def endmost(n)
      all.only(:order).from(all.reverse_order.limit(n), table_name)
    end
  end
end

Looks good? Yes! Let's use this and have a look at the SQL, Message.recent(10):

SELECT "messages".* FROM (
  SELECT  "messages".* FROM "messages"  ORDER BY "messages"."created_at" DESC LIMIT 10
) messages  ORDER BY "messages"."created_at" ASC

   |  id  | created_at |
   |——————|————————————|
-> |  113 |   14:13    |
-> |   …  |   ……………    |
-> |  123 |   14:32    |
   |——————|————————————|

This is exactly what we want, and it has none of the downsides of reversing the results in Ruby. The final .recent method is our final implementation, and it works as expected.

The keen eye will notice that I extracted part of the logic into a general-purpose .endmost method. .endmost is what you want when you call .last: the last N records in the result set without having to retrieve all records from the database, and it works with any ordering. You can impose filtering before, Message.where(…).in_order.endmost(10), and afterwards to filter your final results as well Message.in_order.endmost(10).where(…).

Thanks for reading! I hope you found it as useful as I did!

Sep

Introducing Serial, a light-weight no-magic serialization library (for Ruby, and Rails)


Jonas and I created a serialization library recently while working on ProjectPuzzle, it's named Serial.

Serial will generate a Hash or an Array of hashes from an object of your choosing. It has a very small API surface, and is designed to be easy to reason about. It's suitable for where you'd use YourModel#as_json, ActiveModel::Serializers, or JBuilder. It could look something like this:

# app/serializers/person_serializer.rb
PersonSerializer = Serial::Serializer.new do |h, person|
  h.attribute(:id, person.id)
  h.attribute(:name, person.name)
  h.attribute(:url, account_person_path(person.account, person))
  h.attribute(:assignable, policy(person).assignable?)
  h.attribute(:skills, person.skills.map(&:name))
  h.map(:groups, person.groups, &GroupSerializer)
end

# app/controllers/api/people_controller.rb
include Serial::RailsHelpers
def index
  people = People.all
  render json: { people: serialize(people) }
end

You're very welcome to have a look, you can find it at github.com/elabs/serial, we'd love to hear what you think!

Mar

Advanced topics in Ruby FFI


Short primer: what is FFI?

This article is not a tutorial on the basics of FFI. However, if you’ve never heard of FFI before, I’d like to wet your appetite before continuing on.

FFI is an alternative to writing C to use functionality locked within native libraries from Ruby. It allows you to explain, with an intuitive Ruby DSL, which functions your native library contain, and how they should be used. Once the functionality of your native library is mapped out, you can call the functions directly from Ruby.

Furthermore, gems using ffi do not need to be compiled, and will run without modifications on CRuby, JRuby and Rubinius! In practice there could be small differences between the platforms in the behaviour and usage of FFI, and if you find any you should report them to the Ruby FFI issue tracker so it can be dealt with.

As far as basic tutorials on using FFI, your best resource is the FFI wiki. It also has a list of projects using FFI, which is your second best resource on learning how to use FFI.

Aliasing with typedef

If we look at the header for a function from libspotify:

SP_LIBEXPORT(sp_error) sp_session_player_prefetch(sp_session *session, sp_track *track);

Naively mapping this to FFI we’ll need:

enum :error, [ … ]
attach_function :sp_session_player_prefetch, [ :pointer, :pointer ], :error

Unfortunately, we lost two pieces of valuable information here. Both sp_session and sp_track are types that occur many times in the library. When we look at the ruby implementation, there is no hint whatsoever of what type the two pointers should be of.

It does not need to be like this. Using typedef we can name our parameters, and bring back the information that we lost in our translation.

typedef :pointer, :session
typedef :pointer, :track
enum :error, [ … ]
attach_function :sp_session_player_prefetch, [ :session, :track ], :error

Functionality of our method does not change, but implementation is now slightly more clear and maintainable.

Specializing in attach_function

C libraries do not follow Ruby naming conventions, which makes sense since they’re not written in Ruby. However, bindings written with Ruby FFI are in Ruby and will be called from Ruby, so they should have the look and feel of Ruby.

Attach function allow you to call it in two ways:

attach_function :c_name, [ :params ], :returns, { :options => values } # 1
attach_function :ruby_name, :c_name, [ :params ], :returns, { :options => values } # 2

Using the first form will create your Ruby methods with the same name as your native library’s functions. Using the second form allows you to rename the bound method, giving it a more expected final name.

Native libraries you bind with FFI will have naming conventions of their own. For example, OpenAL will prefix it’s functions with al or alc, and camel case. libspotify will prefix it’s functions with sp_. Apart from removing the suffix, and snake_casing the function name, we want the Ruby method to be named similarly. We could repeat ourselves for every method:

attach_function :open_device, :alcOpenDevice, [ :string ], :device
attach_function :close_device, :alcCloseDevice, [ :device ], :bool

But remember! When you use FFI, you extend the FFI::Library inside a module of your own. This also means you can override the attach_function call, without your specialized version leaking to the outside world. By overriding attach_function we can avoid unnecessary noise in our FFI bindings.

def self.attach_function(c_name, args, returns)
    ruby_name = c_name.to_s.sub(/\Aalc?/, "").gsub(/(?\<\!\A)\p{Lu}/u, '_\0').downcase
    super(ruby_name, c_name, args, returns)
end

attach_function :alcOpenDevice, [ :string ], :device # gets bound to open_device
attach_function :alcCloseDevice, [ :device ], :bool # gets bound to close_device

This does not end here. After calling super inside attach_function you have the option of further specializing the newly bound method. You could implement automatic error checking for every API call, or alter the parameters based on native library conventions, and more. Just remember that the added complexity should be worth the savings.

FFI::Structs as parameters

Structs in FFI can be used as parameters, and is by default equivalent to specifying a type of :pointer.

class SomeStruct < FFI::Struct
end

attach_function :some_function, [ SomeStruct ], :void
# equivalent to:
attach_function :some_function, [ :pointer ], :void

callback :some_callback, [ SomeStruct ], :void
# equivalent to:
callback :some_callback, [ :pointer ], :void

I’d like to bring forth an alternative for your referenced struct parameters, namely FFI::Struct.by_ref. It behaves very similarly to the above, with the important difference in that it type-safety built-in!

attach_function :some_function, [ SomeStruct ], :void
some_function FFI::Pointer.new(0xADDE55) # this is possibly unsafe, but allowed

attach_function :some_function, [ SomeStruct.by_ref ], :void
some_function FFI::Pointer.new(0xADDE55) # BOOM, wrong argument type FFI::Pointer (expected SomeStruct) (TypeError)
some_function SomeOtherStruct.new # BOOM, wrong argument type SomeOtherStruct (expected SomeStruct) (TypeError)

Further more, if you use FFI::Struct.by_ref for your callback parameters or function return values, FFI will automatically cast the pointer to an instance of your struct for you!

callback :some_callback, [ SomeStruct.by_ref ], :void
attach_function :some_function, [ :some_callback ], :void

returned_struct = some_function(proc do |struct|
  # struct is an instance of SomeStruct, instead of an FFI::Pointer
end)

attach_function :some_other_function, [ ], SomeStruct.by_ref
some_other_function.is_a?(SomeStruct) # true, instead of being an FFI::Pointer

Keep in mind, that on JRuby 1.7.3, FFI::Struct.by_ref type accepts any descendant of FFI::Struct, and not only instances of YourStruct. See https://github.com/jruby/jruby/issues/612 for updates.

Piggy-back on Ruby’s garbage collection with regular FFI::Structs

If we take a look again at the above code with SomeStruct as return value.

attach_function :some_other_function, [ ], SomeStruct.by_ref

In some libraries, the memory for the pointer to SomeStruct returned from some_other_function is expected to be managed by us. This means we’ll most likely need to call some function free_some_struct to specifically free the memory used by SomeStruct when the object is no longer needed. Here’s how it would be used:

begin
  some_struct = some_other_function
  # do something with some_struct
ensure
  free_some_struct(some_struct)
end

Unfortunately, if we pass some_struct somewhere else beyond our control, we must be able to trust that the new guardian of some_struct calls free_some_struct in the future, or we will have a memory leak! Oh no!

Fear not, for FFI::Struct has a trick up it’s sleeve for us. Have a look at this.

class SomeStruct < FFI::Struct
  def self.release(pointer)
    MyFFIBinding.free_some_struct(pointer) unless pointer.null?
  end
end

attach_function :some_other_function, [], SomeStruct.auto_ptr

With the above binding code, some_other_function still returns an instance of SomeStruct. However, when our object is garbage collected FFI will call upon SomeStruct.release to free the native memory used by our struct. We can safely pass our instance of SomeStruct around everywhere and to everyone, and safely remember that when the object goes out of scope and Ruby garbage collects it, FFI will call upon us to free the underlying memory!

Related to this, you should look into FFI::ManagedStruct and FFI::AutoPointer if you have not already.

Writing our own data types

class Device < FFI::Pointer
end
attach_function :some_function, [ ], Device

Subclassing FFI::Pointers is a convenient way of working with pointers from native libraries less generic. Using the above code, when we call some_function we’ll receive an instance of Device, instead of the FFI::Pointer we would get if we specified the return value as a :pointer.

If objects in our native library are not pointers we can’t do what we’ve done above. For example, in OpenAL there’s a concept of audio sources, but they are represented by an integer, and not a pointer. Passing arbitrary integers around is not a nice practice, so what you could do is wrap the source in an object for further use.

class Source
  def initialize(id)
    @id = id
  end
  attr_reader :id
end

typedef :int, :source
attach_function :create_source, [], :source
attach_function :destroy_source, [ :source ], :void

# Usage
source = Source.new(create_source)
destroy_source(source.id)

While the code above is not bad, we could do much better by utilizing something in FFI called DataConverters. DataConverters are a way of writing code that tells FFI how to convert a native value to a ruby value and back. By doing this, we could have FFI automatically wrap source above in an object, making it completely transparent to the developer using the library.

class Source
  extend FFI::DataConverter
  native_type FFI::Type::INT

  class << self
    # `value` is a ruby object that we want to convert to a native object
    # this method should return a type of the native_type we specified above
    def to_native(value, context)
      if value
        value.id # in our case, we convert a Source to an int
      else
        -1 # if value is nil, we represent a `no source` value as -1
      end
    end

    # `value` is a type of the native_type specified above, we should return
    # a ruby object we wish to pass around in our application
    def from_native(value, context)
      new(value)
    end

    # this is needed when FFI needs to figure out the native size of your native type
    # for example, if you want to generate a pointer to hold something of this type
    # e.g. FFI::MemoryPointer.new(Source) # <= requires size to be defined and correct
    def size
      FFI.type_size(FFI::Type::INT)
    end

    # this method is a hint to FFI that the object returned from to_native needs to
    # be kept alive for the native value in the object to remain valid, so that if we
    # return an object that automatically frees itself on garbage collection, ffi will
    # prevent it from being garbage collected while it’s still needed, mainly useful
    # for to_native methods that allocate memory
    def reference_required?
      false
    end
  end

  def initialize(id)
    @id = id
  end

  attr_reader :id
end

attach_function :create_source, [], Source
attach_function :destroy_source, [ Source ], :void

source = create_source # an instance of Source, created through Source.from_native!
source.id # => the native value
destroy_source(source) # converts source to native value through Source.to_native!

You could do this to all types, even pointers. Even more, you are not constrained to only doing type conversion in to_native and from_native — you could perform validation, making sure your values have the correct type, length, or what ever you may need!

If you’d like some more example of custom types, I’ve written down a few in this gist: https://gist.github.com/elabs-dev/41c27fdb0a007ad4cac6

Implementing type safety

Do you remember what I mentioned earlier about FFI::Struct.by_ref automatically giving us some kind of type safety, preventing us from shenanigans where somebody sends invalid values to native functions? We can implement the very same kind of type safety ourselves for all types, by overriding to_native in our DataConverters.

# A to_native DataConverter method that raises an error if the value is not of the same type.
module TypeSafety
  def to_native(value, ctx)
    if value.kind_of?(self)
      super
    else
      raise TypeError, "expected a kind of #{name}, was #{value.class}"
    end
  end
end

We could now mix the above module into our own custom data types from the previous chapters.

# Even if we have another object that happens to look like a Source from our previous chapter,
# by having a #value method, we now won’t allow sending it down to C unless it’s an instance of
# Source or any of it’s subclasses.
Source.extend(TypeSafety)

# Remember Device from earlier? It’s a descendant of FFI::Pointer. Now all parameters of type Device
# will only accept instances of Device or any of it’s subclasses. All else results in a type error.
Device.extend(TypeSafety)

Duck-typing is very useful in Ruby, where raising an exception is the worst thing that can happen when we try to call a method on an object that does not respond to such a method. However, when interfacing with C libraries, passing in the wrong type will segfault your application with little information on what went wrong. Using this TypeSafety module, we can catch errors early, with a useful error message as a result.

Final words

Personally I really like using FFI. It’s a low-pain way of writing gems that use native libraries, and if you set your types up properly, not having a compiler that type-checks your code won’t be so bad. If you can work with native libraries through the means of FFI instead of writing a C extension, by all means do. Even if you intend on writing a C extension, using FFI can be a quick way of exploring a native API without wiring up C functions and data structures together with the Ruby C API.

Something that FFI excells at, in comparison to writing a C extension, is handling asynchronous callbacks from non-ruby threads in C. FFI can save you a lot of headache in that area.

Thank you.

References

Mar

Handle secret credentials in Ruby On Rails


This blog post aims to lay out a simple and concrete strategy for handling sensitive data in your Ruby On Rails applications, and to explain the importance of such a strategy.

Never, ever check them into source control

Even if your project is closed source and your trusted colleagues are the only ones with access, you never know when a freelancer or consultant might be joining the project. Even if that never occurs, how do you keep track of all the locations where that repository is checked out? Who knows on how many hard drives your company's credit card transaction secret API key might be stored. What happens when someone with a weak login password forgets their laptop on the bus or at the airport?

Also note that it's not always as simple as removing secrets after the fact, especially with version control. It's usually impossible to do this without drastically changing your entire project's history!

Do it right

For a long time, we've been using YAML files to store our application configuration. It's easy to manage and can be configured for different Rails environments. These YAML files could look like the following:

config/app.yml:

development: &defaults
  awesomeness_score: 3
  host: "localhost:3000"
  s3_bucket: "example-development-us"

production:
  <<: *defaults
  host: "example.com"
  s3_bucket: "example-production-us"

test:
  <<: *defaults

config/app_secret.yml.example:

  development: &defaults
  aws_access_key_id: ""
  aws_secret_access_key_id: ""

production:
  <<: *defaults

test:
  <<: *defaults

config/app_secret.yml:

development: &defaults
  aws_access_key_id: "ACTUAL-ID-WOULD-GO-HERE"
  aws_secret_access_key_id: "ACTUAL-SECRET-WOULD-GO-HERE"

production:
  <<: *defaults

test:
  <<: *defaults

Only the first two files would be checked in to source control, and the application's README would instruct developers to cp config/app_secret.yml.example config/app_secret.yml and fill in the gaps from the company keychain.

To make sure we never check in the secrets by mistake, we ignore the app_secret.yml file:

.gitignore:

# ...
/config/app_secret.yml

We then use the econfig gem written by Jonas Nicklas to easily merge them together:

Gemfile

# ...
gem "econfig", require: "econfig/rails"

config/application.rb

# ...
module YourApp
  extend Econfig::Shortcut
  # ...
end

Now we can access any configuration variable and secret credential:

YourApp.host # => "localhost:3000"
YourApp.aws_secret_access_key_id # => "ACTUAL-SECRET-WOULD-GO-HERE"

Deploy

When you deploy the application, you must manually manage the secrets on the server(s).

Capistrano

If you deploy with Capistrano, you'll want to place the app_secret.yml in your /shared folder. Once that's done, it can be copied to each release with symlink task:

deploy.rb

# ...
namespace :config do
  desc "Symlink application config files."
  task :symlink do
    run "ln -s {#{shared_path},#{release_path}}/config/app_secret.yml"  
  end
end

after "deploy", "config:symlink"

Heroku

If you're deploying your application where you don't have file access, such as Heroku, you're better off storing this kind of information in ENV. The econfig gem has built in support for this and a few other storage backends, but that's another blog post.

Conclusion

With this method, we now have a clear separation of sensitive and non-sensitive data. There's no risk of checking in any sensitive data, since we have only one place to put it all and it's hidden from source control. Data access within the application hasn't changed, and we no longer have to concern ourselves with how sensitive it is.

We can now be sure that giving access to a repository does not imply giving access to other systems.

Epilogue

If you have any feedback on how the blog post can be improved, or if you spot any errors, please let me know by posting a comment below!