Slide 1

Slide 1 text

From Rails to the web server to the browser David Padilla @dabit

Slide 2

Slide 2 text

David Padilla @dabit

Slide 3

Slide 3 text

www.crowdint.com

Slide 4

Slide 4 text

Image from: http://www.vectorworldmap.com/vectormaps/vector-world-map-v2.2.jpg

Slide 5

Slide 5 text

Image from: http://www.vectorworldmap.com/vectormaps/vector-world-map-v2.2.jpg

Slide 6

Slide 6 text

No content

Slide 7

Slide 7 text

Image from: http://www.vectorworldmap.com/vectormaps/vector-world-map-v2.2.jpg

Slide 8

Slide 8 text

From Rails to the web server to the browser

Slide 9

Slide 9 text

Life of a Request

Slide 10

Slide 10 text

www.app.com/hello HTTP Request

Slide 11

Slide 11 text

HTTP Request

Slide 12

Slide 12 text

HTTP Request

Slide 13

Slide 13 text

Railsconf LOL

Slide 14

Slide 14 text

Railsconf LOL

Slide 15

Slide 15 text

No content

Slide 16

Slide 16 text

Rack

Slide 17

Slide 17 text

Rack

Slide 18

Slide 18 text

Rack

Slide 19

Slide 19 text

class App def call(env) # ... return [http_code, headers, body] end end

Slide 20

Slide 20 text

[http_code, headers, body] Integer Hash Responds to :each

Slide 21

Slide 21 text

Somewhere on the web server...

Slide 22

Slide 22 text

# ... # ... # ... @app.call(env) # ... # ... # ...

Slide 23

Slide 23 text

Somewhere on the Application...

Slide 24

Slide 24 text

class App def call(env) # ... return [http_code, headers, body] end end

Slide 25

Slide 25 text

config.ru

Slide 26

Slide 26 text

require 'rack/app' run Rack::App.new config.ru

Slide 27

Slide 27 text

No content

Slide 28

Slide 28 text

No content

Slide 29

Slide 29 text

rackup

Slide 30

Slide 30 text

No content

Slide 31

Slide 31 text

No content

Slide 32

Slide 32 text

No content

Slide 33

Slide 33 text

No content

Slide 34

Slide 34 text

No content

Slide 35

Slide 35 text

All Rails apps are Rack apps

Slide 36

Slide 36 text

No content

Slide 37

Slide 37 text

No content

Slide 38

Slide 38 text

class HelloController def show render text: "Hello World" end end app/controllers/hello_controller.rb

Slide 39

Slide 39 text

No content

Slide 40

Slide 40 text

App::Application.routes.draw do root to: "hello#show" end config/routes.rb

Slide 41

Slide 41 text

No content

Slide 42

Slide 42 text

No content

Slide 43

Slide 43 text

class TestServer < Test::Unit::TestCase def test_the_request uri = URI('http://127.0.0.1:9292') assert "Hello World", Net::HTTP.get(uri) end end test/test.rb

Slide 44

Slide 44 text

No content

Slide 45

Slide 45 text

No content

Slide 46

Slide 46 text

No content

Slide 47

Slide 47 text

No content

Slide 48

Slide 48 text

No content

Slide 49

Slide 49 text

No content

Slide 50

Slide 50 text

No content

Slide 51

Slide 51 text

@app.call({ "REQUEST_METHOD" => "GET", "PATH_INFO" => "/", "rack.input" => "" })

Slide 52

Slide 52 text

[status, headers, body] Rack

Slide 53

Slide 53 text

No content

Slide 54

Slide 54 text

No content

Slide 55

Slide 55 text

No content

Slide 56

Slide 56 text

No content

Slide 57

Slide 57 text

No content

Slide 58

Slide 58 text

No content

Slide 59

Slide 59 text

No content

Slide 60

Slide 60 text

No content

Slide 61

Slide 61 text

No content

Slide 62

Slide 62 text

No content

Slide 63

Slide 63 text

No content

Slide 64

Slide 64 text

No content

Slide 65

Slide 65 text

No content

Slide 66

Slide 66 text

StringIO.new(“Hello World”)

Slide 67

Slide 67 text

No content

Slide 68

Slide 68 text

class App def call(env) content = "Hello World" status_code = 200 headers = { "Content-Length" => content.length.to_s } [status_code, headers, [content]] end end rack/app.rb

Slide 69

Slide 69 text

No content

Slide 70

Slide 70 text

Webservers

Slide 71

Slide 71 text

# ... # ... # ... @app.call(env) # ... # ... # ...

Slide 72

Slide 72 text

Thin

Slide 73

Slide 73 text

thin start

Slide 74

Slide 74 text

module Thin # The uterly famous Thin HTTP server. # It listen for incoming request through # a given +backend+ # and forward all request to +app+. # # == TCP server # Create a new TCP server on bound # to host:port by specifiying +host+ # and +port+ as the first 2 arguments. # # Thin::Server.start('0.0.0.0', 3000, app) lib/thin/server.rb

Slide 75

Slide 75 text

Thin::Server.start('0.0.0.0', 3000, app) thin start

Slide 76

Slide 76 text

# Start the server and listen for connections. def start raise ArgumentError, 'app required' unless @app log ">> Thin web server (v#{VERSION::STRING} codename #{VERSION::C debug ">> Debugging ON" trace ">> Tracing ON" log ">> Maximum connections set to #{@backend.maximum_connections}" log ">> Listening on #{@backend}, CTRL+C to stop" @backend.start end lib/thin/server.rb

Slide 77

Slide 77 text

# Start the server and listen for connections. def start raise ArgumentError, 'app required' unless @app log ">> Thin web server (v#{VERSION::STRING} codename #{VERSION::C debug ">> Debugging ON" trace ">> Tracing ON" log ">> Maximum connections set to #{@backend.maximum_connections}" log ">> Listening on #{@backend}, CTRL+C to stop" @backend.start end lib/thin/server.rb

Slide 78

Slide 78 text

@backend.start lib/thin/server.rb

Slide 79

Slide 79 text

def select_backend(host, port, options) case when options.has_key?(:backend) raise ArgumentError, ":backend must be options[:backend].new(host, port, optio when options.has_key?(:swiftiply) Backends::SwiftiplyClient.new(host, por when host.include?('/') Backends::UnixServer.new(host) else Backends::TcpServer.new(host, port) end end lib/thin/server.rb

Slide 80

Slide 80 text

def select_backend(host, port, options) case when options.has_key?(:backend) raise ArgumentError, ":backend must be options[:backend].new(host, port, optio when options.has_key?(:swiftiply) Backends::SwiftiplyClient.new(host, por when host.include?('/') Backends::UnixServer.new(host) else Backends::TcpServer.new(host, port) end end lib/thin/server.rb

Slide 81

Slide 81 text

def select_backend(host, port, options) case when options.has_key?(:backend) raise ArgumentError, ":backend must be options[:backend].new(host, port, optio when options.has_key?(:swiftiply) Backends::SwiftiplyClient.new(host, por when host.include?('/') Backends::UnixServer.new(host) else Backends::TcpServer.new(host, port) end end lib/thin/server.rb

Slide 82

Slide 82 text

lib/thin/backends/tcp_server.rb

Slide 83

Slide 83 text

module Thin module Backends # Backend to act as a TCP socket server. class TcpServer < Base # Address and port on which the server is listening for connections. attr_accessor :host, :port def initialize(host, port) @host = host @port = port super() end # Connect the server def connect @signature = EventMachine.start_server(@host, @port, Connection, &method(:initializ end # Stops the server def disconnect EventMachine.stop_server(@signature) end def to_s "#{@host}:#{@port}" end end end end lib/thin/backends/tcp_server.rb

Slide 84

Slide 84 text

# Connect the server def connect @signature = EventMachine.start_server(@ end lib/thin/backends/tcp_server.rb

Slide 85

Slide 85 text

EventMachine

Slide 86

Slide 86 text

module Connection def post_init # A client connected end def receive_data data # Data received end def unbind # Client disconnected end end EventMachine.start_server("0.0.0.0", 8081, Connection) EventMachine

Slide 87

Slide 87 text

# Connect the server def connect @signature = EventMachine.start_server(@ end lib/thin/backends/tcp_server.rb

Slide 88

Slide 88 text

ne.start_server(@host, @port, Connection, &metho lib/thin/backends/tcp_server.rb

Slide 89

Slide 89 text

ne.start_server(@host, @port, Connection, &metho lib/thin/backends/tcp_server.rb

Slide 90

Slide 90 text

lib/thin/connection.rb

Slide 91

Slide 91 text

lib/thin/connection.rb

Slide 92

Slide 92 text

# Called when data is received from the client. def receive_data(data) @idle = false trace { data } process if @request.parse(data) rescue InvalidRequest => e log "!! Invalid request" log_error e post_process Response::BAD_REQUEST end lib/thin/connection.rb

Slide 93

Slide 93 text

# Called when data is received from the client. def receive_data(data) @idle = false trace { data } process if @request.parse(data) rescue InvalidRequest => e log "!! Invalid request" log_error e post_process Response::BAD_REQUEST end lib/thin/connection.rb

Slide 94

Slide 94 text

Thin::Request

Slide 95

Slide 95 text

lib/thin/request.rb

Slide 96

Slide 96 text

# Parse a chunk of data into the request environment # Raises a +InvalidRequest+ if invalid. # Returns +true+ if the parsing is complete. def parse(data) if @parser.finished? # Header finished, can only be some more body @body << data else # Parse more header using the super parser @data << data raise InvalidRequest, 'Header longer than allowed' if @data.size > MAX_HEADER @nparsed = @parser.execute(@env, @data, @nparsed) # Transfert to a tempfile if body is very big move_body_to_tempfile if @parser.finished? && content_length > MAX_BODY end if finished? # Check if header and body are complete @data = nil @body.rewind true # Request is fully parsed else false # Not finished, need more data end end lib/thin/request.rb

Slide 97

Slide 97 text

Mongrel Parser

Slide 98

Slide 98 text

/** * Copyright (c) 2005 Zed A. Shaw * You can redistribute it and/or modify * it under the same terms as Ruby. */ #ifndef http11_parser_h #define http11_parser_h #include #if defined(_WIN32) #include #endif

Slide 99

Slide 99 text

GET /index.html HTTP/1.1 Host:localhost HTTP Request

Slide 100

Slide 100 text

No content

Slide 101

Slide 101 text

GET /index.html HTTP/1.1\r\n Host:localhost\r\n\r\n HTTP Request

Slide 102

Slide 102 text

No content

Slide 103

Slide 103 text

No content

Slide 104

Slide 104 text

No content

Slide 105

Slide 105 text

No content

Slide 106

Slide 106 text

# Called when data is received from the client def receive_data(data) @idle = false trace { data } process if @request.parse(data) rescue InvalidRequest => e log "!! Invalid request" log_error e post_process Response::BAD_REQUEST end lib/thin/connection.rb

Slide 107

Slide 107 text

# Called when data is received from the client def receive_data(data) @idle = false trace { data } process if @request.parse(data) rescue InvalidRequest => e log "!! Invalid request" log_error e post_process Response::BAD_REQUEST end lib/thin/connection.rb

Slide 108

Slide 108 text

# Called when all data was received and # the request is ready to be processed. def process if threaded? @request.threaded = true EventMachine.defer(method(:pre_process), me else @request.threaded = false post_process(pre_process) end end lib/thin/connection.rb

Slide 109

Slide 109 text

# Called when all data was received and # the request is ready to be processed. def process if threaded? @request.threaded = true EventMachine.defer(method(:pre_process), else @request.threaded = false post_process(pre_process) end end lib/thin/connection.rb

Slide 110

Slide 110 text

def pre_process # Add client info to the request env @request.remote_address = remote_address # Connection may be closed unless the App# # It should be noted that connection objec # callback is no longer referenced, so be @request.async_callback = method(:post_pro if @backend.ssl? @request.env["rack.url_scheme"] = "https if cert = get_peer_cert @request.env['rack.peer_cert'] = cert end end

Slide 111

Slide 111 text

end # When we're under a non-async framework l # off async responses using the callback i # in removing this. response = AsyncResponse catch(:async) do # Process the request calling the Rack a response = @app.call(@request.env) end response rescue Exception handle_error # Pass through error response can_persist? && @request.persistent? ? Res end

Slide 112

Slide 112 text

end # When we're under a non-async framework l # off async responses using the callback i # in removing this. response = AsyncResponse catch(:async) do # Process the request calling the Rack a response = @app.call(@request.env) end response rescue Exception handle_error # Pass through error response can_persist? && @request.persistent? ? Res end lib/thin/connection.rb

Slide 113

Slide 113 text

# Called when all data was received and # the request is ready to be processed. def process if threaded? @request.threaded = true EventMachine.defer(method(:pre_process), else @request.threaded = false post_process(pre_process) end end lib/thin/connection.rb

Slide 114

Slide 114 text

# Called when all data was received and # the request is ready to be processed. def process if threaded? @request.threaded = true EventMachine.defer(method(:pre_process), else @request.threaded = false post_process(pre_process) end end

Slide 115

Slide 115 text

HTTP/1.1 200 OK Content-Length: 11 Hello World HTTP Response

Slide 116

Slide 116 text

Unicorn

Slide 117

Slide 117 text

EventMachine No

Slide 118

Slide 118 text

@app.call(env) YES

Slide 119

Slide 119 text

lib/unicorn/http_server.rb def process_client(client)

Slide 120

Slide 120 text

Uses the mongrel parser Kinda

Slide 121

Slide 121 text

PUMA

Slide 122

Slide 122 text

What we’ve learned so far

Slide 123

Slide 123 text

EventMachine.start_server("0.0.0.0", 8081, Connection)

Slide 124

Slide 124 text

GET /index.html HTTP/1.1 Host:localhost

Slide 125

Slide 125 text

GET /index.html HTTP/1.1 Host:localhost { "REQUEST_METHOD" => "GET", "PATH_INFO" => "/", "rack.input" => "" }

Slide 126

Slide 126 text

@app.call({ "REQUEST_METHOD" => "GET", "PATH_INFO" => "/", "rack.input" => "" })

Slide 127

Slide 127 text

[http_code, headers, body]

Slide 128

Slide 128 text

[http_code, headers, body] HTTP/1.1 200 OK Content-Length: 11 Hello World

Slide 129

Slide 129 text

HTTP/1.1 200 OK Content-Length: 11 Hello World

Slide 130

Slide 130 text

Our own Webserver

Slide 131

Slide 131 text

No content

Slide 132

Slide 132 text

module Server def receive_data(data) puts data end end rack/server.rb

Slide 133

Slide 133 text

No content

Slide 134

Slide 134 text

No content

Slide 135

Slide 135 text

module Server def receive_data(data) request = Thin::Request.new request.parse(data) puts request.env end end rack/server.rb

Slide 136

Slide 136 text

No content

Slide 137

Slide 137 text

No content

Slide 138

Slide 138 text

def receive_data(data) request = Thin::Request.new request.parse(data) app = App.new response = app.call(request.env) end rack/server.rb

Slide 139

Slide 139 text

No content

Slide 140

Slide 140 text

HTTP/1.1 200 OK Content-Length: 11 Hello World HTTP Response

Slide 141

Slide 141 text

No content

Slide 142

Slide 142 text

No content

Slide 143

Slide 143 text

No content

Slide 144

Slide 144 text

No content

Slide 145

Slide 145 text

No content

Slide 146

Slide 146 text

No content

Slide 147

Slide 147 text

No content

Slide 148

Slide 148 text

Do not try this at home

Slide 149

Slide 149 text

Do not try this in production

Slide 150

Slide 150 text

Be curious

Slide 151

Slide 151 text

dabit/rails-server-browser

Slide 152

Slide 152 text

El fin

Slide 153

Slide 153 text

Thank you! David Padilla @dabit [email protected]