rage-rb 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: 213f5a221d8e6cac6f5fde63e3ffaf17ea9258b8e62b22e101669efac42b3e03
4
+ data.tar.gz: 8a2ff71ae4ade7ac77b4734557b345e93794a2a7559d7ca2f65186e102bfad75
5
+ SHA512:
6
+ metadata.gz: 2389af124774b3c65aab25b88082df641af660a047d050ec0ac494f64a0d01054bd649b95e91cce0dacf98a685a749002e0fcebbf10bf6660f85b5b06faf0c2f
7
+ data.tar.gz: 20d7122017e6fdb1084a762e6326cc5e140b814014353dcb88ea525f38cfe9a23cb8fc2a64e8a27e4b772231b8cb5b10cb74b2e000846f14316404ea79b7b6b9
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/CHANGELOG.md ADDED
@@ -0,0 +1,15 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2023-09-15
4
+
5
+ - Initial release
6
+ - Add console utility to generate new apps and start up the server.
7
+ - Implement base API controller:
8
+ - support `before_action` with the `only` and `except` options;
9
+ - support `render` with the `json`, `plain` and `status` options;
10
+ - support the `head` method;
11
+ - Implement router:
12
+ - support the `root`, `get`, `post`, `patch`, `put`, `delete` methods;
13
+ - support the `scope` method with the `path` and `module` options;
14
+ - support `host` constraint;
15
+
@@ -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 roman.samoilov@wework.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/Gemfile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in rage.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 Roman Samoilov
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,96 @@
1
+ # Rage
2
+
3
+ Inspired by [Deno](https://deno.com) and built on top of [Iodine](https://github.com/rage-rb/iodine), this is a Ruby web framework that is based on the following design principles:
4
+
5
+ * **Rails compatible API** - Rails' API is clean, straightforward, and simply makes sense. I believe it was one of the reasons why Rails was so successful in the past.
6
+
7
+ * **High performance** - some think performance is not a major metric for a framework, but I don't believe it's true. Poor performance is a risk, and in today's world, companies refuse to use risky technologies.
8
+
9
+ * **API-only** - the only technology we should use to create web UI is JavaScript. I recommend checking out [Vite](https://vitejs.dev) if you don't know where to start.
10
+
11
+ * **Acceptance of modern Ruby** - the framework includes a fiber scheduler, which means your code never blocks while waiting on IO.
12
+
13
+ This framework results from reflecting on [Ruby's declining popularity](https://survey.stackoverflow.co/2023/#most-popular-technologies-language) and attempting to answer why this is happening and what we, as a community, could be doing differently.
14
+
15
+ ## Installation
16
+
17
+ Install the gem:
18
+ ```
19
+ $ gem install rage
20
+ ```
21
+
22
+ Create a new app:
23
+ ```
24
+ $ rage new my_app
25
+ ```
26
+
27
+ Switch to your new application and install dependencies:
28
+ ```
29
+ $ cd my_app
30
+ $ bundle
31
+ ```
32
+
33
+ Start up the server and visit http://localhost:3000.
34
+ ```
35
+ $ rage s
36
+ ```
37
+
38
+ Start coding!
39
+
40
+ ## Benchmarks
41
+
42
+ #### hello world
43
+
44
+ ```ruby
45
+ class ArticlesController < ApplicationController
46
+ def index
47
+ render json: { hello: "world" }
48
+ end
49
+ end
50
+ ```
51
+ ![Requests per second](https://github.com/rage-rb/rage/assets/2270393/7d9f408c-7cec-4cc0-a509-66c9dedc1d0a)
52
+
53
+ #### waiting on IO
54
+
55
+ ```ruby
56
+ require "net/http"
57
+
58
+ class ArticlesController < ApplicationController
59
+ def index
60
+ Net::HTTP.get(URI("<endpoint-that-responds-in-one-second>"))
61
+ head :ok
62
+ end
63
+ end
64
+ ```
65
+ ![Time to complete 100 requests](https://github.com/rage-rb/rage/assets/2270393/007044e9-efe0-4675-9cab-8a4868154118)
66
+
67
+ ## Milestones
68
+
69
+ Version | Changes
70
+ ------- |------------
71
+ 0.2 | Gem configuration by env.<br>Add `skip_before_action`.<br>Add `rescue_from`.<br>Router updates:<br>&emsp;• make the `root` helper work correctly with `scope`;<br>&emsp;• support the `defaults` option;
72
+ 0.3 | CLI updates:<br>&emsp;• `routes` task;<br>&emsp;• `console` task;<br>Support the `:if` and `:unless` options in `before_action`.<br>Allow to set response headers.
73
+ 0.4 | Expose the `params` object.<br>Support header authentication with `authenticate_with_http_token`.<br>Router updates:<br>&emsp;• add the `resources` route helper;<br>&emsp;• add the `namespace` route helper;<br>&emsp;• support regexp constraints;
74
+ 0.5 | Implement Iodine-based equivalent of `ActionController::Live`.<br>Use `ActionDispatch::RemoteIp`.
75
+ 0.6 | Expose the `cookies` object.<br>Expose the `send_data` and `send_file` methods.<br>Support conditional get with `etag` and `last_modified`.
76
+ 0.7 | Add request logging.
77
+ 0.8 | Collect app metrics.
78
+ 0.9 | Automatic code reloading in development.
79
+
80
+ ## Development
81
+
82
+ 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.
83
+
84
+ 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).
85
+
86
+ ## Contributing
87
+
88
+ Bug reports and pull requests are welcome on GitHub at https://github.com/rage-rb/rage. 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/rage-rb/rage/blob/master/CODE_OF_CONDUCT.md).
89
+
90
+ ## License
91
+
92
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
93
+
94
+ ## Code of Conduct
95
+
96
+ Everyone interacting in the Rage project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/rage-rb/rage/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
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
+ task default: :spec
data/exe/rage ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require_relative "../lib/rage/cli"
4
+ Rage::CLI.start
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Rage::Application
4
+ def initialize(router)
5
+ Fiber.set_scheduler(Rage::FiberScheduler.new)
6
+ @router = router
7
+ end
8
+
9
+ def call(env)
10
+ fiber = Fiber.schedule do
11
+ handler = @router.lookup(env)
12
+
13
+ if handler
14
+ handler[:handler].call(env, handler[:params])
15
+ else
16
+ [404, {}, ["Not Found"]]
17
+ end
18
+
19
+ rescue => e
20
+ [500, {}, ["#{e.class}:#{e.message}\n\n#{e.backtrace.join("\n")}"]]
21
+
22
+ ensure
23
+ # notify Iodine the request can now be served
24
+ Iodine.publish(env["IODINE_REQUEST_ID"], "")
25
+ end
26
+
27
+ # the fiber encountered blocking IO and yielded; instruct Iodine to pause the request;
28
+ if fiber.alive?
29
+ [:__http_defer__, fiber]
30
+ else
31
+ fiber.__get_result
32
+ end
33
+ end
34
+ end
data/lib/rage/cli.rb ADDED
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "thor"
4
+ require "iodine"
5
+ require "rack"
6
+
7
+ module Rage
8
+ class CLI < Thor
9
+ def self.exit_on_failure?
10
+ true
11
+ end
12
+
13
+ desc "new PATH", "Create a new application."
14
+ def new(path)
15
+ NewAppGenerator.start([path])
16
+ end
17
+
18
+ desc "s", "Start the app server."
19
+ def server
20
+ app = ::Rack::Builder.parse_file("config.ru")
21
+ app = app[0] if app.is_a?(Array)
22
+
23
+ ::Iodine.listen service: :http, handler: app
24
+ ::Iodine.threads = 1
25
+ ::Iodine.start
26
+ end
27
+ end
28
+
29
+ class NewAppGenerator < Thor::Group
30
+ include Thor::Actions
31
+
32
+ argument :path, type: :string
33
+
34
+ def self.source_root
35
+ File.expand_path("templates", __dir__)
36
+ end
37
+
38
+ def create_directory
39
+ empty_directory(path)
40
+ end
41
+
42
+ def copy_files
43
+ Dir.glob("*", base: self.class.source_root).each do |template|
44
+ *template_path_parts, template_name = template.split("-")
45
+ template(template, "#{path}/#{template_path_parts.join("/")}/#{template_name}")
46
+ end
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,123 @@
1
+ # frozen_string_literal: true
2
+
3
+ class RageController::API
4
+ class << self
5
+ def __register_action(action)
6
+ raise "The action '#{action}' could not be found for #{self}" unless method_defined?(action)
7
+
8
+ before_actions_chunk = if @__before_actions
9
+ filtered_before_actions = @__before_actions.select do |h|
10
+ (h[:only].nil? || h[:only].include?(action)) &&
11
+ (h[:except].nil? || !h[:except].include?(action))
12
+ end
13
+
14
+ lines = filtered_before_actions.map do |h|
15
+ <<-RUBY
16
+ #{h[:name]}
17
+ return [@__status, @__headers, @__body] if @__rendered
18
+ RUBY
19
+ end
20
+
21
+ lines.join("\n")
22
+ else
23
+ ""
24
+ end
25
+
26
+ class_eval <<-RUBY
27
+ def __run_#{action}
28
+ #{before_actions_chunk}
29
+ #{action}
30
+
31
+ [@__status, @__headers, @__body]
32
+ end
33
+ RUBY
34
+ end
35
+
36
+ # Register a new `before_action` hook.
37
+ #
38
+ # @param action_name [String] the name of the callback to add
39
+ # @param only [Symbol, Array<Symbol>] restrict the callback to run only for specific actions
40
+ # @param except [Symbol, Array<Symbol>] restrict the callback to run for all actions except specified
41
+ # @example
42
+ # before_action :find_photo, only: :show
43
+ # def find_photo
44
+ # ...
45
+ # end
46
+ def before_action(action_name, only: nil, except: nil)
47
+ (@__before_actions ||= []) << {
48
+ name: action_name,
49
+ only: only && Array(only),
50
+ except: except && Array(except)
51
+ }
52
+ end
53
+ end # class << self
54
+
55
+ DEFAULT_HEADERS = { "content-type" => "application/json; charset=utf-8" }.freeze
56
+
57
+ def initialize(env, params)
58
+ @__env = env
59
+ @__params = params
60
+ @__status, @__headers, @__body = 204, DEFAULT_HEADERS, []
61
+ @__rendered = false
62
+ end
63
+
64
+ # Send a response to the client.
65
+ #
66
+ # @param json [String, Object] send a json response to the client; objects like arrays will be serialized automatically
67
+ # @param plain [String] send a text response to the client
68
+ # @param status [Integer, Symbol] set a response status
69
+ # @example
70
+ # render json: { hello: "world" }
71
+ # @example
72
+ # render status: :ok
73
+ # @example
74
+ # render plain: "hello world", status: 201
75
+ # @note `render` doesn't terminate execution of the action, so if you want to exit an action after rendering, you need to do something like 'render(...) and return'
76
+ def render(json: nil, plain: nil, status: nil)
77
+ raise "Render was called multiple times in this action" if @__rendered
78
+ @__rendered = true
79
+
80
+ if json || plain
81
+ @__body << if json
82
+ json.is_a?(String) ? json : json.to_json
83
+ else
84
+ set_header("content-type", "text/plain; charset=utf-8")
85
+ plain
86
+ end
87
+
88
+ @__status = 200
89
+ end
90
+
91
+ if status
92
+ @__status = if status.is_a?(Symbol)
93
+ ::Rack::Utils::SYMBOL_TO_STATUS_CODE[status]
94
+ else
95
+ status
96
+ end
97
+ end
98
+ end
99
+
100
+ # Send a response with no body.
101
+ #
102
+ # @param status [Integer, Symbol] set a response status
103
+ # @example
104
+ # head :unauthorized
105
+ # @example
106
+ # head 429
107
+ def head(status)
108
+ @__rendered = true
109
+
110
+ @__status = if status.is_a?(Symbol)
111
+ ::Rack::Utils::SYMBOL_TO_STATUS_CODE[status]
112
+ else
113
+ status
114
+ end
115
+ end
116
+
117
+ private
118
+
119
+ def set_header(key, value)
120
+ @__headers = @__headers.dup if DEFAULT_HEADERS.equal?(@__headers)
121
+ @__headers[key] = value
122
+ end
123
+ end
data/lib/rage/fiber.rb ADDED
@@ -0,0 +1,9 @@
1
+ class Fiber
2
+ def __set_result(result)
3
+ @__result = result
4
+ end
5
+
6
+ def __get_result
7
+ @__result
8
+ end
9
+ end
@@ -0,0 +1,98 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Rage::FiberScheduler
4
+ def io_wait(io, events, timeout = nil)
5
+ f = Fiber.current
6
+ ::Iodine::Scheduler.attach(io.fileno, events, timeout&.ceil || 0) { f.resume }
7
+ Fiber.yield
8
+
9
+ events
10
+ end
11
+
12
+ # TODO: this is more synchronous than asynchronous right now
13
+ def io_read(io, buffer, length, offset = 0)
14
+ loop do
15
+ string = ::Iodine::Scheduler.read(io.fileno, length, offset)
16
+
17
+ if string.nil?
18
+ return offset
19
+ end
20
+
21
+ if string.empty?
22
+ io_wait(io, IO::READABLE)
23
+ next
24
+ end
25
+
26
+ buffer.set_string(string, offset)
27
+ offset += string.bytesize
28
+
29
+ size = string.bytesize
30
+ break if size >= length
31
+ length -= size
32
+ end
33
+
34
+ offset
35
+ end
36
+
37
+ def io_write(io, buffer, length, offset = 0)
38
+ bytes_to_write = length
39
+ bytes_to_write = buffer.size if length == 0
40
+
41
+ ::Iodine::Scheduler.write(io.fileno, buffer.get_string, bytes_to_write, offset)
42
+
43
+ buffer.size - offset
44
+ end
45
+
46
+ def kernel_sleep(duration = nil)
47
+ if duration
48
+ f = Fiber.current
49
+ ::Iodine.run_after((duration * 1000).to_i) { f.resume }
50
+ Fiber.yield
51
+ end
52
+ end
53
+
54
+ # TODO: GC works a little strange with this closure;
55
+ #
56
+ # def timeout_after(duration, exception_class = Timeout::Error, *exception_arguments, &block)
57
+ # fiber, block_status = Fiber.current, :running
58
+ # ::Iodine.run_after((duration * 1000).to_i) do
59
+ # fiber.raise(exception_class, exception_arguments) if block_status == :running
60
+ # end
61
+
62
+ # result = block.call
63
+ # block_status = :finished
64
+
65
+ # result
66
+ # end
67
+
68
+ def address_resolve(hostname)
69
+ Resolv.getaddresses(hostname)
70
+ end
71
+
72
+ def block(blocker, timeout = nil)
73
+ f = Fiber.current
74
+ ::Iodine.subscribe("unblock:#{f.object_id}") do
75
+ ::Iodine.defer { ::Iodine.unsubscribe("unblock:#{f.object_id}") }
76
+ f.resume
77
+ end
78
+ # TODO support timeout
79
+ Fiber.yield
80
+ end
81
+
82
+ def unblock(_blocker, fiber)
83
+ ::Iodine.publish("unblock:#{fiber.object_id}", "")
84
+ end
85
+
86
+ def fiber(&block)
87
+ fiber = Fiber.new(blocking: false) do
88
+ Fiber.current.__set_result(block.call)
89
+ end
90
+ fiber.resume
91
+
92
+ fiber
93
+ end
94
+
95
+ def close
96
+ ::Iodine::Scheduler.close
97
+ end
98
+ end
@@ -0,0 +1,19 @@
1
+ This is an almost complete rewrite of https://github.com/delvedor/find-my-way.
2
+
3
+ Currrently, the only constraint supported is the `host` constraint. Regexp constraints are likely to be added. Custom/lambda constraints are unlikely to be added.
4
+
5
+ Compared to the Rails router, the most notable difference except constraints is that a wildcard segment can only be in the last section of the path and cannot be named.
6
+
7
+ ```ruby
8
+ Rage.routes.draw do
9
+ get "photos/:id", to: "photos#show", constraints: { host: /myhost/ }
10
+
11
+ scope path: "api/v1", module: "api/v1" do
12
+ get "photos/:id", to: "photos#show"
13
+ end
14
+
15
+ root to: "photos#index"
16
+
17
+ get "*", to: ->(env) { [404, {}, [{ message: "Not Found" }.to_json]] }
18
+ end
19
+ ```