Skip to content

Instantly share code, notes, and snippets.

@bigcurl
Created May 18, 2011 06:10
Show Gist options
  • Save bigcurl/978061 to your computer and use it in GitHub Desktop.
Save bigcurl/978061 to your computer and use it in GitHub Desktop.
CPU spikes while copying data to a socket.
#!/usr/bin/env ruby
# encoding: utf-8
require 'goliath'
require 'digest/sha1'
class ShaStream < Goliath::API
def on_headers(env, headers)
env['async-digest'] = Digest::SHA1.new # SHA1 or MD5
str = env['CONTENT_TYPE'].match(/multipart\/form-data.*boundary\=?([^"\;,]+)?/)
env['request-boundary'] = str[1] if str
end
def on_body(env, data)
data.gsub!(/.*#{env['request-boundary']}.*\r\n\r\n/m, '')
data.gsub!(/\r\n.*#{env['request-boundary']}--\r\n/m, '')
env['async-digest'] << data
end
def response(env)
digest = env['async-digest'].hexdigest
env['async-digest'] = nil
[200, {}, ["#{digest}\n"]]
end
end
# run with ruby sha_stream.rb -sv -p 9001
#!/usr/bin/env ruby
# encoding: utf-8
require 'goliath'
class Connector < EM::Connection
def post_init
@data = ""
end
def receive_data(data)
@data << data
end
def data
@data
end
def unbind
@fiber.resume
end
def fiber=(fiber)
@fiber = fiber
end
end
class UploadStreamEm < Goliath::API
def on_headers(env, headers)
str = env['CONTENT_TYPE'].match(/multipart\/form-data.*boundary\=?([^"\;,]+)?/)
env['request-boundary'] = str[1] if str
env['request-header'] = headers
url = "http://localhost:9001/"
env['async-socket'] = EM.connect('127.0.0.1', 9001, Connector)
env['async-socket'].send_data "POST "+ url + " HTTP/1.0\n"
env['async-socket'].send_data "Content-Type: multipart/form-data\; boundary=#{env['request-boundary']}\n"
env['async-socket'].send_data "Content-Length:" + headers["Content-Length"] + "\n\n"
end
def on_body(env, data)
env['async-socket'].send_data(data)
end
def response(env)
env['async-socket'].fiber = Fiber.current
Fiber.yield
body = env['async-socket'].data
[200, {}, ["#{body}\n"]]
end
end
# run with ruby upload_stream.rb -sv -p 9000
# call with curl -F "file=@goliath/github.rb" "localhost:9000/"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment