cougar 0.0.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 75a7f4d6fc2810c3756efc0ff5510798ebc6d28078f51b59e568ebcee09afa8d
4
- data.tar.gz: dae5536d6035f67546136f12ffe1fc52d602bdffc8dd5eeba120fec2313c4cd7
3
+ metadata.gz: aa97730346dd063a023c0548de1ed8d1f5dccfe190db84ba3dc523c035062af0
4
+ data.tar.gz: edef3d4edeb4463324b7be7732093082e037c65f57eb1f41936ca76f446ef75d
5
5
  SHA512:
6
- metadata.gz: e81456be6eae99b5c9fef7c15034b4b18cfa44e35ac54520e82341314298d54f0b9d3b6c709a7052c28b94e0193575a47427dd2a09be94818d7eaac1c7b61229
7
- data.tar.gz: 8cf8d948c812075b068479e25737a0d43999831f2dea87a018d6d62fe8c1049d96bb27076f88173ed91d4bd4ae1939669d768402ee9e8ce8e5c215c14014d909
6
+ metadata.gz: 3de9b433b0f9b462585aea42743b5e601792e0b127526fa2d12b549e91d689736fa473e9d108ab0488402a4a009417203246efa8742e766e9c59e747eef57f8b
7
+ data.tar.gz: 99242b473d36d29940882637b38bc5c8c7944b77bc113fdb6fdaee8974d3736ba4ab4d66879c7fce744089e953de6cfd6555b1cebaf81bc5bae71634a34a2275
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 John Hawthorn
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,42 @@
1
+ # Cougar
2
+
3
+ > [!CAUTION]
4
+ > Do not use this. It's just an experiment I'm using for benchmarking
5
+
6
+ ## Installation
7
+
8
+ TODO: Replace `cougar` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
9
+
10
+ Install the gem and add to the application's Gemfile by executing:
11
+
12
+ ```bash
13
+ bundle add cougar
14
+ ```
15
+
16
+ If bundler is not being used to manage dependencies, install the gem by executing:
17
+
18
+ ```bash
19
+ gem install cougar
20
+ ```
21
+
22
+ ## Usage
23
+
24
+ TODO: Write usage instructions here
25
+
26
+ ## Development
27
+
28
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
29
+
30
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
31
+
32
+ ## Contributing
33
+
34
+ Bug reports and pull requests are welcome on GitHub at https://github.com/jhawthorn/cougar. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/jhawthorn/cougar/blob/main/CODE_OF_CONDUCT.md).
35
+
36
+ ## License
37
+
38
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
39
+
40
+ ## Code of Conduct
41
+
42
+ Everyone interacting in the Cougar project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/jhawthorn/cougar/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "minitest/test_task"
5
+
6
+ Minitest::TestTask.create
7
+
8
+ task default: :test
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+
5
+ class MyApp
6
+ def self.call(env)
7
+ path = env["PATH_INFO"]
8
+
9
+ case path
10
+ when "/"
11
+ [200, {"Content-Type" => "text/plain"}, ["Hello from Cougar!\n"]]
12
+ when "/json"
13
+ response = JSON.generate(message: "Hello, World!")
14
+ [200, {"Content-Type" => "application/json"}, [response]]
15
+ when "/headers"
16
+ headers_info = env.select { |k, v| k.start_with?("HTTP_") }
17
+ .map { |k, v| "#{k}: #{v}" }
18
+ .join("\n")
19
+ [200, {"Content-Type" => "text/plain"}, ["Request Headers:\n#{headers_info}\n"]]
20
+ when "/env"
21
+ [200, {"Content-Type" => "text/plain"}, [env.inspect]]
22
+ when "/echo"
23
+ body = env["rack.input"].read
24
+ [200, {"Content-Type" => "text/plain"}, ["Method: #{env["REQUEST_METHOD"]}\nBody: #{body}\nContent-Length: #{env["CONTENT_LENGTH"]}\n"]]
25
+ else
26
+ [404, {"Content-Type" => "text/plain"}, ["Not Found\n"]]
27
+ end
28
+ end
29
+ end
30
+
31
+ app = MyApp
32
+
33
+ run app
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "cougar"
6
+ require "rack"
7
+
8
+ # Load the Rack app from config.ru
9
+ app, _options = Rack::Builder.parse_file("examples/config.ru")
10
+
11
+ # Start the server (uses RUBY_MAX_CPU env var or defaults to 8 workers)
12
+ server = Cougar::Server.new(app, host: "0.0.0.0", port: 9292)
13
+
14
+ trap("INT") do
15
+ puts "\nShutting down..."
16
+ server.stop
17
+ exit
18
+ end
19
+
20
+ server.run
data/exe/cougar ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require_relative '../lib/cougar/cli'
4
+
5
+ Cougar::CLI.new(ARGV).run
data/lib/cougar/cli.rb ADDED
@@ -0,0 +1,104 @@
1
+ require 'optparse'
2
+ require 'cougar'
3
+ require 'rack'
4
+
5
+ module Cougar
6
+ class CLI
7
+ def initialize(argv)
8
+ @argv = argv
9
+ @options = {
10
+ host: "localhost",
11
+ port: 9292,
12
+ config: "config.ru",
13
+ environment: ENV["RACK_ENV"] || "development"
14
+ }
15
+ end
16
+
17
+ def run
18
+ parse_options!
19
+
20
+ if @options[:version]
21
+ puts "Cougar version #{Cougar::VERSION}"
22
+ return
23
+ end
24
+
25
+ if @options[:help]
26
+ puts @parser
27
+ return
28
+ end
29
+
30
+ start_server
31
+ end
32
+
33
+ private
34
+
35
+ def parse_options!
36
+ @parser = OptionParser.new do |opts|
37
+ opts.banner = "Usage: cougar [options] [config.ru]"
38
+
39
+ opts.on("-p", "--port PORT", Integer, "Port to bind to (default: 9292)") do |port|
40
+ @options[:port] = port
41
+ end
42
+
43
+ opts.on("-b", "--bind HOST", "Host to bind to (default: localhost)") do |host|
44
+ @options[:host] = host
45
+ end
46
+
47
+ opts.on("-e", "--environment ENVIRONMENT", "Rack environment (default: development)") do |env|
48
+ @options[:environment] = env
49
+ end
50
+
51
+ opts.on("-w", "--workers NUM", Integer, "Number of worker processes") do |workers|
52
+ @options[:workers] = workers
53
+ end
54
+
55
+ opts.on("-v", "--version", "Print version and exit") do
56
+ @options[:version] = true
57
+ end
58
+
59
+ opts.on("-h", "--help", "Show this help message") do
60
+ @options[:help] = true
61
+ end
62
+ end
63
+
64
+ @parser.parse!(@argv)
65
+
66
+ # After parse!, @argv contains only non-option arguments
67
+ if @argv.first
68
+ @options[:config] = @argv.first
69
+ end
70
+ end
71
+
72
+ def start_server
73
+ _, max_file_limit = Process.getrlimit(Process::RLIMIT_NOFILE)
74
+ Process.setrlimit(Process::RLIMIT_NOFILE, max_file_limit)
75
+
76
+ ENV["RACK_ENV"] = @options[:environment]
77
+
78
+ # Load the Rack app
79
+ app, _options = ::Rack::Builder.parse_file(@options[:config])
80
+
81
+ # Create server options
82
+ server_options = {
83
+ host: @options[:host],
84
+ port: @options[:port]
85
+ }
86
+
87
+ server_options[:workers] = @options[:workers] if @options[:workers]
88
+
89
+ # Start the server
90
+ server = Cougar::Server.new(app, **server_options)
91
+
92
+ puts "Starting Cougar server on http://#{@options[:host]}:#{@options[:port]}"
93
+ puts "* Workers: #{server_options[:workers] || ENV.fetch("RUBY_MAX_CPU", 8)}"
94
+ puts "* Loading app from: #{@options[:config]}"
95
+
96
+ trap("INT") do
97
+ puts "\nShutting down..."
98
+ server.stop
99
+ end
100
+
101
+ server.run
102
+ end
103
+ end
104
+ end
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cougar
4
+ module HttpStatuses
5
+ STATUSES = {
6
+ 100 => 'Continue',
7
+ 101 => 'Switching Protocols',
8
+ 200 => 'OK',
9
+ 201 => 'Created',
10
+ 202 => 'Accepted',
11
+ 203 => 'Non-Authoritative Information',
12
+ 204 => 'No Content',
13
+ 205 => 'Reset Content',
14
+ 206 => 'Partial Content',
15
+ 207 => 'Multi-Status',
16
+ 300 => 'Multiple Choices',
17
+ 301 => 'Moved Permanently',
18
+ 302 => 'Found',
19
+ 303 => 'See Other',
20
+ 304 => 'Not Modified',
21
+ 305 => 'Use Proxy',
22
+ 307 => 'Temporary Redirect',
23
+ 400 => 'Bad Request',
24
+ 401 => 'Unauthorized',
25
+ 402 => 'Payment Required',
26
+ 403 => 'Forbidden',
27
+ 404 => 'Not Found',
28
+ 405 => 'Method Not Allowed',
29
+ 406 => 'Not Acceptable',
30
+ 407 => 'Proxy Authentication Required',
31
+ 408 => 'Request Timeout',
32
+ 409 => 'Conflict',
33
+ 410 => 'Gone',
34
+ 411 => 'Length Required',
35
+ 412 => 'Precondition Failed',
36
+ 413 => 'Request Entity Too Large',
37
+ 414 => 'Request-URI Too Large',
38
+ 415 => 'Unsupported Media Type',
39
+ 416 => 'Request Range Not Satisfiable',
40
+ 417 => 'Expectation Failed',
41
+ 422 => 'Unprocessable Entity',
42
+ 423 => 'Locked',
43
+ 424 => 'Failed Dependency',
44
+ 426 => 'Upgrade Required',
45
+ 428 => 'Precondition Required',
46
+ 429 => 'Too Many Requests',
47
+ 431 => 'Request Header Fields Too Large',
48
+ 451 => 'Unavailable For Legal Reasons',
49
+ 500 => 'Internal Server Error',
50
+ 501 => 'Not Implemented',
51
+ 502 => 'Bad Gateway',
52
+ 503 => 'Service Unavailable',
53
+ 504 => 'Gateway Timeout',
54
+ 505 => 'HTTP Version Not Supported',
55
+ 507 => 'Insufficient Storage',
56
+ 511 => 'Network Authentication Required',
57
+ }.freeze
58
+
59
+ STATUS_LINES_11 = STATUSES.to_h do |code, text|
60
+ [code, -"HTTP/1.1 #{code} #{text}\r\n"]
61
+ end.freeze
62
+
63
+ STATUS_LINES_10 = STATUSES.to_h do |code, text|
64
+ [code, -"HTTP/1.0 #{code} #{text}\r\n"]
65
+ end.freeze
66
+
67
+ def self.text_for(code)
68
+ STATUSES[code] || "Unknown"
69
+ end
70
+
71
+ def self.status_line_11(code)
72
+ STATUS_LINES_11[code]
73
+ end
74
+
75
+ def self.status_line_10(code)
76
+ STATUS_LINES_10[code]
77
+ end
78
+ end
79
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cougar
4
+ module Rack
5
+ class EmptyInput
6
+ def gets
7
+ nil
8
+ end
9
+
10
+ def read(length = nil, buffer = nil)
11
+ buffer&.clear
12
+ if length
13
+ nil
14
+ else
15
+ buffer || ""
16
+ end
17
+ end
18
+
19
+ def each
20
+ end
21
+
22
+ def close
23
+ end
24
+ end
25
+
26
+ EMPTY_INPUT = EmptyInput.new.freeze
27
+ end
28
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cougar
4
+ module Rack
5
+ class ErrorStream
6
+ def puts(*args)
7
+ $stderr.puts(*args)
8
+ end
9
+
10
+ def write(*args)
11
+ $stderr.write(*args)
12
+ end
13
+
14
+ def flush
15
+ $stderr.flush
16
+ end
17
+ end
18
+
19
+ ERROR_STREAM = ErrorStream.new.freeze
20
+ end
21
+ end
@@ -0,0 +1,97 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cougar
4
+ class RactorWorker
5
+ attr_reader :worker_id, :ractor
6
+
7
+ def initialize(worker_id, server, app)
8
+ @worker_id = worker_id
9
+ control_port_port = Ractor::Port.new
10
+
11
+ @ractor = Ractor.new(server, app, worker_id, control_port_port) do |server, app, worker_id, control_port_port|
12
+ control_port = Ractor::Port.new
13
+ worker_thread = Thread.current
14
+ control_thread = Thread.new do |th|
15
+ loop do
16
+ case control_port.receive
17
+ in :stop
18
+ server.close
19
+ break
20
+ in [:status, response_port]
21
+ response_port.send({
22
+ worker_id: worker_id,
23
+ thread_status: worker_thread.status,
24
+ alive: worker_thread.alive?
25
+ })
26
+ end
27
+ end
28
+ end
29
+ control_port_port.send(control_port)
30
+
31
+ loop do
32
+ begin
33
+ client = server.accept
34
+ client.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
35
+ rescue IOError, Errno::EBADF => e
36
+ # Server socket was closed, exit gracefully
37
+ break
38
+ end
39
+
40
+ keepalive = true
41
+ request = Cougar::Request.new(client)
42
+ first_request = true
43
+ while keepalive
44
+ begin
45
+ unless first_request || request.has_buffered_data?
46
+ unless client.wait_readable(0.1)
47
+ break
48
+ end
49
+ end
50
+ first_request = false
51
+
52
+ # Parse the HTTP request
53
+ if !request.parse
54
+ break
55
+ end
56
+
57
+ # Call the Rack app
58
+ status, headers, body = app.call(request.env)
59
+
60
+ # Send the response
61
+ keepalive = request.respond(status, headers, body)
62
+
63
+ client.flush
64
+
65
+ break unless keepalive
66
+
67
+ request.reset_for_next_request
68
+ rescue => e
69
+ $stderr.puts "[Worker #{worker_id}] #{e.class}: #{e.message}"
70
+ $stderr.puts e.backtrace
71
+ keepalive = false
72
+ end
73
+ end
74
+ ensure
75
+ client&.close
76
+ end
77
+
78
+ control_thread.join
79
+ end
80
+
81
+ @control_port = control_port_port.receive
82
+ control_port_port.close
83
+ end
84
+
85
+ def stop
86
+ @control_port.send(:stop)
87
+ end
88
+
89
+ def send_status_request(response_port)
90
+ @control_port.send([:status, response_port])
91
+ end
92
+
93
+ def join
94
+ @ractor.join
95
+ end
96
+ end
97
+ end
@@ -0,0 +1,196 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "stringio"
4
+ require "picohttp"
5
+ require_relative "http_statuses"
6
+ require_relative "rack/error_stream"
7
+ require_relative "rack/empty_input"
8
+
9
+ module Cougar
10
+ SERVER_SOFTWARE = "Cougar/#{VERSION}".freeze
11
+
12
+
13
+ class Request
14
+ def initialize(client)
15
+ @client = client
16
+ @buffer = String.new
17
+ @read_buf = String.new(capacity: 16384)
18
+ @remote_addr = client.respond_to?(:remote_address) ? client.remote_address.ip_address : "127.0.0.1"
19
+ reset_for_next_request
20
+ end
21
+
22
+ def reset_for_next_request
23
+ if @body_offset
24
+ content_length = @env&.fetch("CONTENT_LENGTH", "0").to_i
25
+ consumed = @body_offset + content_length
26
+ if consumed >= @buffer.bytesize
27
+ @buffer.clear
28
+ else
29
+ @buffer = @buffer.byteslice(consumed, @buffer.bytesize - consumed)
30
+ end
31
+ end
32
+ @env = nil
33
+ @body_offset = nil
34
+ end
35
+
36
+ def has_buffered_data?
37
+ !@buffer.empty?
38
+ end
39
+
40
+ def parse
41
+ # Read data until we have a complete HTTP request
42
+ while @env.nil?
43
+ # Try to parse the accumulated buffer
44
+ unless @buffer.empty?
45
+ @env = Picohttp.parse_request_env(@buffer)
46
+
47
+ if @env
48
+ # Find where headers end and body begins
49
+ @body_offset = @buffer.index("\r\n\r\n")
50
+ @body_offset += 4 if @body_offset
51
+ break
52
+ end
53
+ end
54
+
55
+ # Need more data
56
+ break unless fast_read(16384, @read_buf)
57
+
58
+ @buffer << @read_buf
59
+ end
60
+
61
+ return false unless @env
62
+
63
+ # Add additional Rack environment variables
64
+ setup_rack_env
65
+
66
+ # Handle request body if present
67
+ setup_request_body
68
+
69
+ true
70
+ rescue EOFError
71
+ false
72
+ end
73
+
74
+ def env
75
+ @env
76
+ end
77
+
78
+ WRITE_TIMEOUT = 10
79
+ READ_TIMEOUT = 10
80
+ SOCKET_WRITE_ERR_MSG = "Socket timeout writing data"
81
+ SOCKET_READ_ERR_MSG = "Socket timeout reading data"
82
+
83
+ def fast_read(size, buf)
84
+ while true
85
+ ret = @client.read_nonblock(size, buf, exception: false)
86
+ if :wait_readable == ret
87
+ unless @client.wait_readable(READ_TIMEOUT)
88
+ raise SOCKET_READ_ERR_MSG
89
+ end
90
+ else
91
+ return ret
92
+ end
93
+ end
94
+ end
95
+
96
+ def fast_write(str)
97
+ n = 0
98
+ byte_size = str.bytesize
99
+ while n < byte_size
100
+ ret = @client.write_nonblock(n.zero? ? str : str.byteslice(n..-1), exception: false)
101
+ if :wait_writable == ret
102
+ unless @client.wait_writable(WRITE_TIMEOUT)
103
+ raise SOCKET_WRITE_ERR_MSG
104
+ end
105
+ else
106
+ n += ret
107
+ end
108
+ end
109
+ end
110
+
111
+ def respond(status, headers, body)
112
+ if @env["SERVER_PROTOCOL"] == "HTTP/1.0"
113
+ status_line = HttpStatuses.status_line_10(status)
114
+ should_keepalive = false
115
+ else
116
+ status_line = HttpStatuses.status_line_11(status)
117
+ should_keepalive = !@env["HTTP_CONNECTION"]&.casecmp?("close")
118
+ end
119
+
120
+ headers["connection"] = should_keepalive ? "keep-alive" : "close"
121
+
122
+ if !headers["content-length"] && status >= 200 && status != 204 && status != 304
123
+ old_body = body
124
+ body = []
125
+ length = 0
126
+ old_body.each do |chunk|
127
+ body << chunk
128
+ length += chunk.bytesize
129
+ end
130
+ headers["content-length"] = length.to_s
131
+ end
132
+
133
+ buf = +""
134
+ buf << status_line
135
+ headers.each do |name, value|
136
+ case value
137
+ when Array
138
+ value.each do |v|
139
+ buf << name << ": " << v << "\r\n"
140
+ end
141
+ else
142
+ buf << name << ": " << value << "\r\n"
143
+ end
144
+ end
145
+ buf << "\r\n"
146
+
147
+ body.each do |chunk|
148
+ buf << chunk
149
+ end
150
+ fast_write(buf)
151
+
152
+ body.close if body.respond_to?(:close)
153
+
154
+ should_keepalive
155
+ end
156
+
157
+ RACK_ENV_CONST = {
158
+ "rack.version" => [1, 3].freeze,
159
+ "rack.url_scheme" => "http",
160
+ "rack.errors" => Cougar::Rack::ERROR_STREAM,
161
+ "rack.multithread" => false,
162
+ "rack.multiprocess" => true,
163
+ "rack.run_once" => false,
164
+ "SERVER_SOFTWARE" => SERVER_SOFTWARE,
165
+ }.freeze
166
+
167
+ private
168
+
169
+ def setup_rack_env
170
+ @env["REMOTE_ADDR"] = @remote_addr
171
+ @env.update(RACK_ENV_CONST)
172
+ end
173
+
174
+ def setup_request_body
175
+ content_length = @env["CONTENT_LENGTH"]&.to_i || 0
176
+
177
+ if content_length == 0
178
+ @env["rack.input"] = Cougar::Rack::EMPTY_INPUT
179
+ return
180
+ end
181
+
182
+ body_data = @buffer.byteslice(@body_offset, @buffer.bytesize - @body_offset) || ""
183
+
184
+ while body_data.bytesize < content_length
185
+ break unless fast_read(16384, @read_buf)
186
+ body_data << @read_buf
187
+ end
188
+
189
+ @env["rack.input"] = StringIO.new(body_data)
190
+ end
191
+
192
+ def status_text(code)
193
+ HttpStatuses.text_for(code)
194
+ end
195
+ end
196
+ end
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "socket"
4
+ require_relative "ractor_worker"
5
+
6
+ module Cougar
7
+ class Server
8
+ attr_reader :host, :port, :app, :workers
9
+
10
+ def initialize(app, host: "localhost", port: 9292, workers: ENV.fetch("RUBY_MAX_CPU", 8).to_i)
11
+ @app = app
12
+ @host = host
13
+ @port = port
14
+ @workers = workers
15
+ @server = nil
16
+ @workers_list = []
17
+ end
18
+
19
+ def start
20
+ silence_ractor_warning!
21
+
22
+ @server = TCPServer.new(@host, @port)
23
+ @port = @server.addr[1] # Get the actual port if it was 0
24
+ puts "Cougar listening on #{@host}:#{@port} with #{@workers} workers"
25
+
26
+ # Freeze the app so it can be shared across Ractors
27
+ @app.freeze
28
+
29
+ # Create worker Ractors
30
+ @workers.times do |i|
31
+ worker = RactorWorker.new(i, @server, @app)
32
+ @workers_list << worker
33
+ end
34
+ end
35
+
36
+ def run
37
+ start
38
+
39
+ # Wait for workers to finish
40
+ @workers_list.each(&:join)
41
+ end
42
+
43
+ def stop
44
+ @server.close
45
+
46
+ @workers_list.each(&:stop)
47
+ end
48
+
49
+ def status
50
+ response_port = Ractor::Port.new
51
+ workers = @workers_list
52
+ workers.each { |worker| worker.send_status_request(response_port) }
53
+ statuses = workers.size.times.map { response_port.receive }
54
+ response_port.close
55
+ statuses
56
+ end
57
+
58
+ def inspect
59
+ worker_statuses = status
60
+ "#<#{self.class.name}:0x#{object_id.to_s(16)} @host=#{@host.inspect} @port=#{@port} @workers=#{@workers} workers=#{worker_statuses.inspect}>"
61
+ end
62
+
63
+ private
64
+
65
+ def silence_ractor_warning!
66
+ warning_was = Warning[:experimental]
67
+ Warning[:experimental] = false
68
+ Ractor.new{}.join
69
+ Warning[:experimental] = warning_was
70
+ end
71
+ end
72
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cougar
4
+ VERSION = "0.2.0"
5
+ end
data/lib/cougar.rb ADDED
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "cougar/version"
4
+ require_relative "cougar/request"
5
+ require_relative "cougar/server"
6
+
7
+ module Cougar
8
+ class Error < StandardError; end
9
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "cougar"
4
+
5
+ module Rackup
6
+ module Handler
7
+ module Cougar
8
+ def self.run(app, **options)
9
+ host = options[:Host] || "localhost"
10
+ port = Integer(options[:Port] || 9292)
11
+
12
+ server = ::Cougar::Server.new(app, host: host, port: port)
13
+ yield server if block_given?
14
+ server.run
15
+ end
16
+
17
+ def self.valid_options
18
+ {
19
+ "Host=HOST" => "Hostname to listen on (default: localhost)",
20
+ "Port=PORT" => "Port to listen on (default: 9292)"
21
+ }
22
+ end
23
+ end
24
+
25
+ register :cougar, Cougar
26
+ end
27
+ end
data/sig/cougar.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module Cougar
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata CHANGED
@@ -1,28 +1,76 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: cougar
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.0
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - John Hawthorn
8
- bindir: bin
8
+ bindir: exe
9
9
  cert_chain: []
10
10
  date: 1980-01-02 00:00:00.000000000 Z
11
- dependencies: []
12
- description: placeholder
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: picohttp
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: 0.3.0
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: 0.3.0
26
+ - !ruby/object:Gem::Dependency
27
+ name: rack
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '0'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '0'
40
+ description: Cougar is a high-performance web server built from the ground up with
41
+ Ruby's Ractors for true parallelism
13
42
  email:
14
43
  - john@hawthorn.email
15
- executables: []
44
+ executables:
45
+ - cougar
16
46
  extensions: []
17
47
  extra_rdoc_files: []
18
- files: []
19
- homepage: https://jhawthorn.com
48
+ files:
49
+ - CODE_OF_CONDUCT.md
50
+ - LICENSE.txt
51
+ - README.md
52
+ - Rakefile
53
+ - examples/config.ru
54
+ - examples/server.rb
55
+ - exe/cougar
56
+ - lib/cougar.rb
57
+ - lib/cougar/cli.rb
58
+ - lib/cougar/http_statuses.rb
59
+ - lib/cougar/rack/empty_input.rb
60
+ - lib/cougar/rack/error_stream.rb
61
+ - lib/cougar/ractor_worker.rb
62
+ - lib/cougar/request.rb
63
+ - lib/cougar/server.rb
64
+ - lib/cougar/version.rb
65
+ - lib/rackup/handler/cougar.rb
66
+ - sig/cougar.rbs
67
+ homepage: https://github.com/jhawthorn/cougar
20
68
  licenses:
21
69
  - MIT
22
70
  metadata:
23
- homepage_uri: https://jhawthorn.com
24
- source_code_uri: https://jhawthorn.com
25
- changelog_uri: https://jhawthorn.com
71
+ homepage_uri: https://github.com/jhawthorn/cougar
72
+ source_code_uri: https://github.com/jhawthorn/cougar
73
+ changelog_uri: https://github.com/jhawthorn/cougar/blob/main/CHANGELOG.md
26
74
  rdoc_options: []
27
75
  require_paths:
28
76
  - lib
@@ -30,14 +78,14 @@ required_ruby_version: !ruby/object:Gem::Requirement
30
78
  requirements:
31
79
  - - ">="
32
80
  - !ruby/object:Gem::Version
33
- version: 3.0.0
81
+ version: 3.5.a
34
82
  required_rubygems_version: !ruby/object:Gem::Requirement
35
83
  requirements:
36
84
  - - ">="
37
85
  - !ruby/object:Gem::Version
38
86
  version: '0'
39
87
  requirements: []
40
- rubygems_version: 3.6.7
88
+ rubygems_version: 4.0.10
41
89
  specification_version: 4
42
- summary: placeholder
90
+ summary: A fast, Ractor-first web server for Ruby
43
91
  test_files: []