Thrift + Thinの組み合わせでS/C

Binary RPCの実験。環境によってはインストールが結構面倒かも。

ThriftをWindows/MinGW/MSYS環境でビルドするには、MSYSに以下のものが必要だった。全部mingwsourceforgeサイトにあるので、ちまちま落として展開する。lzmaとかいう変態アーカイブなのが腹立つ。MSYSのコンソール上でtar --lzma -xvf hoge.tar.lzma とかやると展開できる。

  • flex
  • bison
  • autoconf
  • automake
  • libregex
  • mktemp

さらに http://www.gtk.org/download-windows.html から、以下を落としてきて、MSYS/1.0以下に展開する。

  • pkg-config
  • glib

他にも何かあったかも。

Thrift

time.thrift

typedef i64 TimeStamp
service TimeServer {
	TimeStamp time()
}
$ thrift --gen rb time.thrift
$ ls gen-rb
time_constants.rb  time_server.rb  time_types.rb

Ruby Client

client.rb

#!/opt/local/bin/ruby

require 'thrift'
require 'thrift/transport/http_client_transport'
require 'thrift/protocol/binary_protocol'
require 'time_server'

transport = Thrift::HTTPClientTransport.new('http://localhost:9090/')
protocol = Thrift::BinaryProtocol.new(transport)
client = TimeServer::Client.new(protocol)

transport.open()
tdata = client.time()
now = Time.at(tdata >> 32, tdata & 0xffffffff)
puts now.strftime('%c ') + now.usec.to_s

Ruby Server

server.ru

require 'thrift'
require 'thrift/protocol/binary_protocol'
require 'thrift/transport/memory_buffer_transport'
require 'time_server'

use Rack::ContentLength

class TimeServiceHandler
  def time()
    now = Time.now
    puts now.strftime('%c ') + now.usec.to_s
    return now.to_i << 32 | now.usec
  end
end

handler = TimeServiceHandler.new()
transport = Thrift::MemoryBufferTransport.new()
protocol = Thrift::BinaryProtocol.new(transport)
processor = TimeServer::Processor.new(handler)

app = proc do |env|
  result = ''
  if env['rack.input']
    # p env['rack.input'].string
    transport.reset_buffer
    transport.write(env['rack.input'].string)
    processor.process(protocol, protocol)
    result = transport.read(transport.available)
  end
  [ 200, { 'Content-Type' => 'text/html' }, [result] ]
end

run app
$ thin -p 9090 -R server.ru start
>> Thin web server (v1.2.5 codename This Is Not A Web Server)
>> Maximum connections set to 1024
>> Listening on 0.0.0.0:9090, CTRL+C to stop

test

$ ruby client.rb
Tue Jan  5 19:00:55 2010 721615
$

server sideでは

>> Listening on 0.0.0.0:9090, CTRL+C to stop
Tue Jan  5 19:00:55 2010 721615

初期化の時にいちいちにゅーにゅー言うのが間抜けだけど、取りあえず便利だ!