mooro 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 01db74ca33a9fcb1326925c3efbba7f48214dbd20da9c604982a083bb67d47d7
4
+ data.tar.gz: ee9b4e8919d8ddc5a89f2fa8462a661c26a13b5745d0d7f94e6937e13d414d8d
5
+ SHA512:
6
+ metadata.gz: 5a57ab35cc2fd087b18b161c9108477912bf3dd4e9e08cdb3c8429877ef7fe66d0fd809a54da1454ef98b0f7f5f4837b0ff2d05dee9857b107130690575d683c
7
+ data.tar.gz: f3d57b298e737f929bc432af070600c21bc5ce2e08a436041065628533edd1d345226fc50b7d1d98e1f1b1b16c2ecda8c63bbe17c4780c708c000b725c1930d4
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,8 @@
1
+ inherit_gem:
2
+ rubocop-shopify: rubocop.yml
3
+
4
+ require: rubocop-rspec
5
+
6
+ AllCops:
7
+ TargetRubyVersion: 3.3
8
+ NewCops: enable
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2023-12-03
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at castlehoneyjung@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 Forthoney
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,88 @@
1
+ # Mooro: A truly parallel server for CRuby
2
+ Mooro is a Ractor-based, compact, parallel TCP server targeting CRuby. It is built to be extended - you can only do so much with raw TCP sockets - and offers straigtforward ways (and examples) of doing so.
3
+
4
+ ## Uncompromising Minimalism
5
+ Mooro aims to deliver all essential features expected from a modern Ruby web server such as
6
+ * **Parallelism**. Mooro utilizes true parallelism with CRuby through `Ractor`s.
7
+ * **Logging**. Supervisor start/stop, worker errors, and other notable events are logged by default, and adding additional logging points is as straightforward as adding `logger.send("message")`.
8
+ * **Stopping**. Capable of gracefully stopping (or forcefully, if you prefer that).
9
+
10
+ At the same time, it abstracts virtually nothing away from TCPServer, enabling maximum extensibility.
11
+ Anything at the TCP level and higher is fair game for Mooro.
12
+ Extending Mooro is quite simple because it is
13
+ * **Compact**. The base server has 0 dependencies and fits in less than 150 lines of code. Yes, this number _includes_ comments!
14
+ * **Pure Ruby**. No C extensions, so you don't need to dive into the shadow realm to figure out the internals of Mooro.
15
+ * **Almost GServer compatible**. Most of the server interface is identical to [GServer](https://github.com/ruby/gserver), an ex-stdlib Generic Server, for familiarity's sake.
16
+
17
+ ## Usage
18
+
19
+ If you want to create a basic server that outputs the time,
20
+ ```ruby
21
+ class TimeServer < Mooro::Server
22
+ def serve(io)
23
+ io.puts(Time.now.to_i)
24
+ end
25
+ end
26
+
27
+ server = TimeServer.new(max_connections = 4)
28
+ server.start
29
+ sleep(15)
30
+ server.stop
31
+ ```
32
+
33
+ Mooro ships with an implementation of an HTTP Server.
34
+ A [healthcheck server](https://www.mikeperham.com/2023/09/11/ruby-http-server-from-scratch/) can be built with
35
+ ```ruby
36
+ HTTP = Mooro::Plugin::HTTP
37
+
38
+ class HealthCheck < Mooro::Server
39
+ include HTTP
40
+
41
+ def handle_request(req)
42
+ req.path == "/" ? HTTP::Response[200] : HTTP::Response[404]
43
+ end
44
+ end
45
+ ```
46
+
47
+ ## Installation
48
+
49
+ Install the gem and add to the application's Gemfile by executing:
50
+
51
+ $ bundle add UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG
52
+
53
+ If bundler is not being used to manage dependencies, install the gem by executing:
54
+
55
+ $ gem install UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG
56
+
57
+
58
+
59
+ ## Development
60
+
61
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
62
+
63
+ 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).
64
+
65
+ ## Contributing
66
+
67
+ Mooro is in desperate need of Tests (both Unit and Integration) and Benchmarks.
68
+ I unfortunately lack the expertise needed for either of these, so any contribution in these areas are greatly appreciated.
69
+ Contributions outside these areas are, of course, also welcome.
70
+
71
+ Bug reports and pull requests are welcome on GitHub at https://github.com/Forthoney/mooro. 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/Forthoney/mooro/blob/main/CODE_OF_CONDUCT.md).
72
+
73
+ ## Caveats
74
+
75
+ * `Ractor`s are still experimental as of `3.2.2`. Subsequently, Mooro should be treated as experimental.
76
+
77
+ * Mooro is quite incompatible with older versions of Ruby. Anything pre-`Ractor` (i.e. pre 3.0) obviously does not work.
78
+ The builtin HTTP Server requires Ruby 3.2 or later, although this can easily be circumvented if need be.
79
+
80
+ * Mooro's interface is not exactly like `gserver`. Read more about the differences [here](docs/gserver_differences.md).
81
+
82
+ ## License
83
+
84
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
85
+
86
+ ## Code of Conduct
87
+
88
+ Everyone interacting in the Mooro project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/Forthoney/mooro/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: [:spec, :rubocop]
data/Steepfile ADDED
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ D = Steep::Diagnostic
4
+
5
+ target :lib do
6
+ signature "sig"
7
+
8
+ check "lib" # Directory name
9
+ check "app/models/**/*.rb" # Glob
10
+ # ignore "lib/templates/*.rb"
11
+
12
+ library "socket"
13
+ # library "strong_json" # Gems
14
+
15
+ configure_code_diagnostics(D::Ruby.default) # `default` diagnostics setting (applies by default)
16
+ # configure_code_diagnostics(D::Ruby.strict) # `strict` diagnostics setting
17
+ # configure_code_diagnostics(D::Ruby.lenient) # `lenient` diagnostics setting
18
+ # configure_code_diagnostics(D::Ruby.silent) # `silent` diagnostics setting
19
+ # configure_code_diagnostics do |hash| # You can setup everything yourself
20
+ # hash[D::Ruby::NoMethod] = :information
21
+ # end
22
+ end
23
+
24
+ target :test do
25
+ signature "sig", "sig-private"
26
+
27
+ check "test"
28
+
29
+ library "socket" # Standard libraries
30
+ end
@@ -0,0 +1,20 @@
1
+ # Differences with GServer
2
+ Although Mooro is based off of the GServer interface, there exists some differences.
3
+ Most are ergonomic differences (at least for the end user) but there are small functionality differences as well.
4
+
5
+ ## Logging
6
+ Logging is turned on in Mooro, whereas you need to turn it on for GServer.
7
+ The default Server does not allow for turning it off, but there is nothing technically stopping anyone from turning it off.
8
+ This is more of a "I got a bit lazy" portion - I would appreciate contributions that enable this easily!
9
+
10
+ ## Multiserver Management
11
+ GServer comes built with multiserver management.
12
+ Mooro does not, and does not intend to, at least in the base Server.
13
+ There is, of course, the question of how. This is nontrivial but also not impossible.
14
+ More importantly, I feel multiserver management disregards Mooro's leanness principle.
15
+ My unsubstantiated opinion is that if you really have need for that multiserver management, Mooro is too light for you.
16
+ I am very very open to being proven wrong, and when proven wrong, will write a `Plugin::Multiserver`.
17
+
18
+ ## Tests and Benchmarks
19
+ One of the [reasons](https://bugs.ruby-lang.org/issues/5480) why `gserver` was removed from stdlib was due to a lack of tests.
20
+ Mooro would _like_ to be different from GServer by having adequate tests and benchmarks.
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "mooro"
4
+ require "mooro/server"
5
+
6
+ module Mooro
7
+ module Plugin
8
+ module InterruptableServer
9
+ def make_worker(supervisor, logger, ractor_name: "interruptable_worker")
10
+ block = Ractor.make_shareable(method(:serve).to_proc)
11
+ Ractor.new(supervisor, logger, block, name: ractor_name) do |supervisor, logger, serve|
12
+ clients = Thread::Queue.new
13
+ runner = Thread.new do
14
+ while (current_client = clients.pop)
15
+ begin
16
+ serve.call(current_client)
17
+ rescue TerminateServer
18
+ break
19
+ rescue => err
20
+ logger.send(err.to_s)
21
+ ensure
22
+ current_client&.close
23
+ end
24
+ end
25
+ end
26
+ begin
27
+ until (client = supervisor.take) == :terminate
28
+ clients.push(client)
29
+ end
30
+ rescue Ractor::ClosedError => closed_err
31
+ logger.send("#{closed_err}: Supervisor's outgoing port is closed")
32
+ ensure
33
+ runner.raise(TerminateServer)
34
+ runner.join
35
+ end
36
+ end
37
+ end
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,98 @@
1
+ # frozen_string_literal: true
2
+ # shareable_constant_value: literal
3
+
4
+ require "uri"
5
+
6
+ require "mooro"
7
+
8
+ module Mooro
9
+ module Plugin
10
+ module HTTP
11
+ CRLF = "\r\n"
12
+ VERSION = "HTTP/1.1"
13
+ SERVER_NAME = "Mooro HttpServer (Ruby #{RUBY_VERSION})"
14
+
15
+ protected
16
+
17
+ def handle_request(request)
18
+ Response[200]
19
+ end
20
+
21
+ def serve(socket)
22
+ # parse first line
23
+ socket.gets&.scan(/^(\S+)\s+(\S+)\s+(\S+)/) do |method, path, version|
24
+ header = parse_header(socket)
25
+ return socket << Response[400] if header.nil?
26
+
27
+ socket.binmode
28
+ request = Request[socket, header, method, path, version]
29
+ response = handle_request(request)
30
+ return socket << response
31
+ end
32
+
33
+ socket << Response[400]
34
+ end
35
+
36
+ private
37
+
38
+ def parse_header(socket)
39
+ # parse HTTP headers
40
+ header = Header.new { |h, k| h[k] = [] }
41
+ field = nil
42
+ while /^(\n|\r)/.match?(line = socket.gets)
43
+ # Use WEBrick parsing
44
+ case line
45
+ when /^([A-Za-z0-9!\#$%&'*+\-.^_`|~]+):(.*?)\z/om
46
+ field = Regexp.last_match(1).downcase
47
+ header[field] << Regexp.last_match(2).strip
48
+ when /^\s+(.*?)/om && field
49
+ header[field][-1] << " " << line.strip
50
+ else
51
+ return
52
+ end
53
+ end
54
+ header
55
+ end
56
+
57
+ class Header < Hash
58
+ def to_s
59
+ export.map { |k, v| "#{k}: #{v.join(", ")}" + CRLF }.join
60
+ end
61
+
62
+ private
63
+
64
+ def export
65
+ new_header = Header.new { |h, k| h[k] = [] }
66
+ new_header.update(self)
67
+ new_header["server"] << SERVER_NAME
68
+ new_header["connection"] << "close"
69
+ new_header["date"] << http_time(Time.now)
70
+ new_header
71
+ end
72
+
73
+ def http_time(time)
74
+ time.gmtime.strftime("%a, %d %b %Y %H:%M:%S GMT")
75
+ end
76
+ end
77
+
78
+ Request = Data.define(:data, :header, :method, :path, :proto)
79
+
80
+ Response = Data.define(:status_code, :status_message, :header, :body) do
81
+ def initialize(status_code:, status_message: CODE_MSG[status_code], header: Header.new, body: "") = super
82
+
83
+ def to_s
84
+ "#{VERSION} #{status_code} #{status_message}#{CRLF}#{header}#{body}"
85
+ end
86
+
87
+ CODE_MSG = {
88
+ 200 => "OK",
89
+ 400 => "Bad Request",
90
+ 403 => "Forbidden",
91
+ 405 => "Method Not Allowed",
92
+ 411 => "Length Required",
93
+ 500 => "Internal Server Error",
94
+ }
95
+ end
96
+ end
97
+ end
98
+ end
@@ -0,0 +1,154 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "socket"
4
+
5
+ module Mooro
6
+ class TerminateServer < StandardError; end
7
+
8
+ class Server
9
+ def initialize(max_connections,
10
+ host = "127.0.0.1",
11
+ port = 10001,
12
+ stdlog = $stderr)
13
+
14
+ @host = host
15
+ @port = port
16
+ @max_connections = max_connections
17
+ @stdlog = stdlog
18
+ @shutdown = true
19
+ end
20
+
21
+ def start
22
+ raise "server is already running" unless @shutdown
23
+
24
+ @logger = make_logger
25
+ @workers = @max_connections.times.map do |i|
26
+ make_worker(Ractor.current, @logger, ractor_name: "worker-#{i}")
27
+ end
28
+ @supervisor = make_supervisor(@logger, @workers)
29
+ @shutdown = false
30
+ end
31
+
32
+ def stop
33
+ raise "server is not yet running" if @shutdown
34
+
35
+ @supervisor.raise(Mooro::TerminateServer.new) if @supervisor.alive?
36
+ @supervisor.join
37
+
38
+ raise "orphaned ractor" unless Ractor.count == 1
39
+
40
+ @shutdown = true
41
+ end
42
+
43
+ def running?
44
+ !@shutdown
45
+ end
46
+
47
+ protected
48
+
49
+ def serve(socket)
50
+ socket.puts("Hello, World!")
51
+ end
52
+
53
+ # Create a logger Ractor
54
+ # workers & supervisor ----> logger
55
+ #
56
+ # The logger logs messages to @stdlog with the timestamp of when the
57
+ # message was processed
58
+ # Workers and the supervisor will send messages to logger (push based)
59
+ #
60
+ # Termination:
61
+ # Logger only yields once when it terminates. Do not take from it unless
62
+ # joining - the taking thread will hang otherwise
63
+ def make_logger(ractor_name: "logger")
64
+ Ractor.new(@stdlog, name: ractor_name) do |out_stream|
65
+ until (msg = Ractor.receive) == :terminate
66
+ out_stream.puts("[#{Time.new.ctime}] #{msg}")
67
+ out_stream.flush
68
+ end
69
+ end
70
+ end
71
+
72
+ # Create a worker Ractor
73
+ # supervisor >---- worker ----> logger
74
+ #
75
+ # The worker actually serves the client
76
+ # Workers take a client from the supervisor (pull based)
77
+ # and send messages to logger when non-ractor exceptions are raised (push based)
78
+ #
79
+ # Termination:
80
+ # Workers do not stop while the supervisor is alive unless explicitly told to
81
+ def make_worker(supervisor, logger, ractor_name: "worker")
82
+ block = Ractor.make_shareable(method(:serve).to_proc)
83
+ Ractor.new(supervisor, logger, block, name: ractor_name) do |supervisor, logger, serve|
84
+ # Failure point 1: supervisor.take
85
+ # - ClosedError: supervisor is already dead
86
+ # - RemoteError: supervisor raised some unhandled error
87
+ # Neither are really recoverable...
88
+ until (client = supervisor.take) == :terminate
89
+ # Failure point 2: server.serve
90
+ # Rescue any error and move on to next client
91
+ begin
92
+ addr = client.peeraddr
93
+ logger.send("client: #{addr[1]} #{addr[2]}<#{addr[3]}> connect")
94
+ serve.call(client)
95
+ rescue => err
96
+ logger.send([err.to_s, err.backtrace])
97
+ ensure
98
+ logger.send("client: #{client.peeraddr[1]} disconnect")
99
+ client&.close
100
+ end
101
+ end
102
+ rescue Ractor::ClosedError => closed_err
103
+ logger.send("#{closed_err}: Supervisor's outgoing port is closed")
104
+ end
105
+ end
106
+
107
+ # Create a supervisor Ractor
108
+ #
109
+ # supervisor >---- worker
110
+ # |-----> logger
111
+ #
112
+ # The supervisor dispatches clients for the workers to take on
113
+ # Supervisor safely terminates on receiving TerminateServer error.
114
+ # This will be triggered remotely by the main thread on the main ractor.
115
+ # Graceful termination will safely join with workers and logger.
116
+ # Assuming no workers or the logger is blocking, graceful termination guarantees
117
+ # joining with all child ractors. This is becausee workers are guaranteed to
118
+ # survive as long as the supervisor too is alive and well.
119
+ #
120
+ # Termination
121
+ # Any other error will trigger a "non-graceful" termination.
122
+ # We do not know if any child ractors are in a blocking state, so we cannot
123
+ # yield or take from any of them without risk of blocking the supervisor.
124
+ # So, the supervisor does not attempt to join.
125
+ def make_supervisor(logger, workers)
126
+ # Dupe workers array because we mutate it when stopping
127
+ Thread.new(workers.dup) do |workers|
128
+ logger.send("supervisor start")
129
+ TCPServer.open(@host, @port) do |socket|
130
+ @port = socket.addr[1]
131
+ logger.send("supervisor socket opened at #{@host}:#{@port}")
132
+
133
+ loop do
134
+ client = socket.accept
135
+ Ractor.yield(client, move: true)
136
+ rescue TerminateServer
137
+ logger.send("supervisor at #{@host}:#{@port} gracefully stopping...")
138
+ # Consider changing to push-only once round-robin scheduling is implemented in Ractor.select
139
+ until workers.empty?
140
+ Ractor.yield(:terminate)
141
+ r, _ = Ractor.select(*workers)
142
+ workers.delete(r)
143
+ end
144
+ break
145
+ end
146
+ rescue => unexpected_err
147
+ logger.send("supervisor at #{@host}:#{@port} crashed with #{unexpected_err}")
148
+ end
149
+ logger.send(:terminate)
150
+ logger.take
151
+ end
152
+ end
153
+ end
154
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mooro
4
+ VERSION = "0.1.0"
5
+ end
data/lib/mooro.rb ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "mooro/version"
4
+ require "mooro/server"
5
+ require "mooro/plugin/http"
6
+ require "mooro/plugin/fault_tolerance"
7
+
8
+ module Mooro
9
+ # Your code goes here...
10
+ end
@@ -0,0 +1,64 @@
1
+ module Mooro
2
+ module Plugin
3
+ # A rudimentary HTTP server based off of gserver/xmlrpc.rb with
4
+ # bits of WEBRICK sprinkled in where xmlrpc is incorrect
5
+ # It serves more of a demonstration purpose although it can suit
6
+ # small internal applications.
7
+ module HTTP
8
+ CRLF: ::String
9
+
10
+ HTTP_PROTO: ::String
11
+
12
+ SERVER_NAME: ::String
13
+
14
+ DEFAULT_HEADER: Hash[String, String]
15
+
16
+ STATUS_CODE_MAPPING: ::Hash[Integer, String]
17
+
18
+ def serve: (TCPSocket io) -> void
19
+
20
+ def request_handler: (Request request) -> Response
21
+
22
+ private
23
+
24
+ def parse_header: (TCPSocket io) -> Header?
25
+
26
+ class Header < Hash[String, String]
27
+ DEFAULT_HEADER: Hash[String, String]
28
+
29
+ def to_s: () -> String
30
+
31
+ private
32
+
33
+ def export: () -> Header
34
+
35
+ def http_time: (untyped time) -> String
36
+ end
37
+
38
+ class Request
39
+ attr_reader data: IO
40
+ attr_reader header: Header
41
+ attr_reader method: String
42
+ attr_reader path: String
43
+ attr_reader proto: String
44
+
45
+ def initialize: (IO data, Header header, String method, String path, String proto) -> void
46
+ def self.[]: (IO data, Header header, String method, String path, String proto) -> Request
47
+ def content_length: () -> Integer?
48
+ end
49
+
50
+ class Response
51
+ attr_reader status_code: Integer
52
+ attr_reader status_message: String
53
+ attr_reader header: Header
54
+ attr_reader body: String
55
+
56
+ def initialize: (Integer status_code, ?String status_message, ?Header header, ?String body) -> void
57
+
58
+ def self.[]: (Integer status_code, ?String status_message, ?Header header, ?String body) -> Response
59
+
60
+ def to_s: () -> String
61
+ end
62
+ end
63
+ end
64
+ end
@@ -0,0 +1,57 @@
1
+ module Mooro
2
+ class TerminateServer < StandardError end
3
+ class Server
4
+ @host: String
5
+
6
+ @port: Integer
7
+
8
+ @max_connections: Integer
9
+
10
+ @stdlog: IO
11
+
12
+ @shutdown: bool
13
+
14
+ @logger: Ractor
15
+
16
+ @supervisor: Thread
17
+
18
+ @workers: Array[Ractor]
19
+
20
+ # Logic on how to serve each client
21
+ # Server.serve must be a pure function, and any variables must be passed explicitly
22
+ # The only means of passing a Method or Proc as a nested proc are currently hacky
23
+ # Mooro's workaround is to define a class method, which is able to be called
24
+ # This comes with the caveat that no shared object can live in the function body
25
+ def self.serve: (TCPSocket io) -> untyped
26
+
27
+ def initialize: (Integer max_connections, ?::String host, ?::Integer port, ?IO stdlog) -> void
28
+
29
+ def start: () -> void
30
+
31
+ def stop: () -> void
32
+
33
+ # Create a logger Ractor
34
+ # The logger logs messages to @stdlog with the timestamp of when the
35
+ # message was processed
36
+ # workers & listener ----> logger
37
+ # Workers and the listener will send messages to logger (push based)
38
+ # Logger only yields one value
39
+ # Logger terminates on receiving :terminate
40
+ def make_logger: (?ractor_name: ::String) -> Ractor
41
+
42
+ # Create a worker Ractor
43
+ # The worker actually serves the client
44
+ # listener --->> worker ----> logger
45
+ # Workers take a client from the listener (pull based)
46
+ # and send messages to logger when non-standard behavior occurs (push based)
47
+ # Worker terminates when the listener closes its outgoing port
48
+ def make_worker: (Ractor listener, Ractor logger, ?ractor_name: ::String) -> Ractor
49
+
50
+ # Create a supervisor thread on the main Ractor
51
+ # The listener dispatches clients for the workers to take on
52
+ # listener --->> worker
53
+ # listener ----> logger
54
+ # Listener terminates on receiving :terminate
55
+ def make_supervisor: (Ractor logger, Array[Ractor] workers) -> Thread
56
+ end
57
+ end
data/sig/mooro.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module Mooro
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,63 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: mooro
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Forthoney
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-12-22 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Write a longer description or delete this line.
14
+ email:
15
+ - castlehoneyjung@gmail.com
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - ".rspec"
21
+ - ".rubocop.yml"
22
+ - CHANGELOG.md
23
+ - CODE_OF_CONDUCT.md
24
+ - LICENSE.txt
25
+ - README.md
26
+ - Rakefile
27
+ - Steepfile
28
+ - docs/gserver_differences.md
29
+ - lib/mooro.rb
30
+ - lib/mooro/plugin/fault_tolerance.rb
31
+ - lib/mooro/plugin/http.rb
32
+ - lib/mooro/server.rb
33
+ - lib/mooro/version.rb
34
+ - sig/mooro.rbs
35
+ - sig/mooro/http.rbs
36
+ - sig/mooro/server.rbs
37
+ homepage: https://github.com/Forthoney/mooro
38
+ licenses:
39
+ - MIT
40
+ metadata:
41
+ homepage_uri: https://github.com/Forthoney/mooro
42
+ source_code_uri: https://github.com/Forthoney/mooro
43
+ changelog_uri: https://github.com/Forthoney/mooro/blob/main/CHANGELOG.md
44
+ post_install_message:
45
+ rdoc_options: []
46
+ require_paths:
47
+ - lib
48
+ required_ruby_version: !ruby/object:Gem::Requirement
49
+ requirements:
50
+ - - ">="
51
+ - !ruby/object:Gem::Version
52
+ version: 3.2.0
53
+ required_rubygems_version: !ruby/object:Gem::Requirement
54
+ requirements:
55
+ - - ">="
56
+ - !ruby/object:Gem::Version
57
+ version: '0'
58
+ requirements: []
59
+ rubygems_version: 3.5.1
60
+ signing_key:
61
+ specification_version: 4
62
+ summary: Truly parallel server powered by Ractors
63
+ test_files: []