diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..37a9318 --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,27 @@ +name: Ruby + +on: + push: + branches: + - main + + pull_request: + +jobs: + build: + runs-on: ubuntu-latest + name: Ruby ${{ matrix.ruby }} + strategy: + matrix: + ruby: + - '3.3.0' + + steps: + - uses: actions/checkout@v4 + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby }} + bundler-cache: true + - name: Run the default task + run: bundle exec rake diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9106b2a --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +/.bundle/ +/.yardoc +/_yardoc/ +/coverage/ +/doc/ +/pkg/ +/spec/reports/ +/tmp/ diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000..aab46ed --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,18 @@ +AllCops: + NewCops: enable + TargetRubyVersion: 3.0 + +Metrics/MethodLength: + Enabled: false + +Style/Documentation: + Enabled: false + +Style/MultilineBlockChain: + Enabled: false + +Style/StringLiterals: + EnforcedStyle: double_quotes + +Style/StringLiteralsInInterpolation: + EnforcedStyle: double_quotes diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..92fabcd --- /dev/null +++ b/Gemfile @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +source "https://rubygems.org" + +# Specify your gem's dependencies in clamo.gemspec +gemspec + +gem "rake", "~> 13.0" + +gem "minitest", "~> 5.16" + +gem "rubocop", "~> 1.21" diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..7a060b0 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,50 @@ +PATH + remote: . + specs: + clamo (0.1.0) + parallel (~> 1.24.0) + +GEM + remote: https://rubygems.org/ + specs: + ast (2.4.2) + json (2.7.2) + language_server-protocol (3.17.0.3) + minitest (5.22.3) + parallel (1.24.0) + parser (3.3.1.0) + ast (~> 2.4.1) + racc + racc (1.7.3) + rainbow (3.1.1) + rake (13.2.1) + regexp_parser (2.9.0) + rexml (3.2.6) + rubocop (1.63.4) + json (~> 2.3) + language_server-protocol (>= 3.17.0) + parallel (~> 1.10) + parser (>= 3.3.0.2) + rainbow (>= 2.2.2, < 4.0) + regexp_parser (>= 1.8, < 3.0) + rexml (>= 3.2.5, < 4.0) + rubocop-ast (>= 1.31.1, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 3.0) + rubocop-ast (1.31.3) + parser (>= 3.3.1.0) + ruby-progressbar (1.13.0) + unicode-display_width (2.5.0) + +PLATFORMS + arm64-darwin-23 + ruby + +DEPENDENCIES + clamo! + minitest (~> 5.16) + rake (~> 13.0) + rubocop (~> 1.21) + +BUNDLED WITH + 2.5.9 diff --git a/README.md b/README.md new file mode 100644 index 0000000..36bdf62 --- /dev/null +++ b/README.md @@ -0,0 +1,31 @@ +# Clamo + +JSON-RPC protocol toolkit for Ruby. + +Consume, Serve or test JSON-RPC endpoints with Clamo. + +## Installation + +TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG` 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. + +Install the gem and add to the application's Gemfile by executing: + + $ bundle add clamo + +If bundler is not being used to manage dependencies, install the gem by executing: + + $ gem install clamo + +## Usage + +TODO: Write usage instructions here + +## Development + +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. + +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). + +## Contributing + +Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/clamo. diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..2bf771f --- /dev/null +++ b/Rakefile @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +require "bundler/gem_tasks" +require "minitest/test_task" + +Minitest::TestTask.create + +require "rubocop/rake_task" + +RuboCop::RakeTask.new + +task default: %i[test rubocop] diff --git a/bin/console b/bin/console new file mode 100755 index 0000000..c1dd50d --- /dev/null +++ b/bin/console @@ -0,0 +1,11 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +require "bundler/setup" +require "clamo" + +# You can add fixtures and/or initialization code here to make experimenting +# with your gem easier. You can also use a different console, if you like. + +require "irb" +IRB.start(__FILE__) diff --git a/bin/setup b/bin/setup new file mode 100755 index 0000000..dce67d8 --- /dev/null +++ b/bin/setup @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' +set -vx + +bundle install + +# Do any other automated setup that you need to do here diff --git a/clamo.gemspec b/clamo.gemspec new file mode 100644 index 0000000..99f9fcb --- /dev/null +++ b/clamo.gemspec @@ -0,0 +1,43 @@ +# frozen_string_literal: true + +require_relative "lib/clamo/version" + +Gem::Specification.new do |spec| + spec.name = "clamo" + spec.version = Clamo::VERSION + spec.authors = ["Andriy Tyurnikov"] + spec.email = ["Andriy.Tyurnikov@gmail.com"] + + spec.summary = "JSON-RPC Client/Server tooling for Ruby" + spec.description = "JSON-RPC Client/Server tooling for Ruby" + spec.homepage = "https://github.com/andriytyurnikov/clamo" + spec.required_ruby_version = ">= 3.0.0" + + # spec.metadata["allowed_push_host"] = "TODO: Set to your gem server 'https://example.com'" + + spec.metadata["homepage_uri"] = spec.homepage + spec.metadata["source_code_uri"] = spec.homepage + spec.metadata["changelog_uri"] = spec.homepage + + # Specify which files should be added to the gem when it is released. + # The `git ls-files -z` loads the files in the RubyGem that have been added into git. + gemspec = File.basename(__FILE__) + spec.files = IO.popen(%w[git ls-files -z], chdir: __dir__, err: IO::NULL) do |ls| + ls.readlines("\x0", chomp: true).reject do |f| + (f == gemspec) || + f.start_with?(*%w[bin/ test/ spec/ features/ .git .github appveyor Gemfile]) + end + end + spec.bindir = "exe" + spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) } + spec.require_paths = ["lib"] + + spec.add_dependency "parallel", "~> 1.24.0" + # Uncomment to register a new dependency of your gem + # spec.add_dependency "example-gem", "~> 1.0" + # + + # For more information and examples about making a new gem, check out our + # guide at: https://bundler.io/guides/creating_gem.html + spec.metadata["rubygems_mfa_required"] = "true" +end diff --git a/lib/clamo.rb b/lib/clamo.rb new file mode 100644 index 0000000..85edd2d --- /dev/null +++ b/lib/clamo.rb @@ -0,0 +1,9 @@ +# frozen_string_literal: true + +require_relative "clamo/version" +require_relative "clamo/jsonrpc" +require_relative "clamo/server" + +module Clamo + # class Error < StandardError; end +end diff --git a/lib/clamo/client.rb b/lib/clamo/client.rb new file mode 100644 index 0000000..7383e7e --- /dev/null +++ b/lib/clamo/client.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +class Client + ANSWER = 42 +end diff --git a/lib/clamo/jsonrpc.rb b/lib/clamo/jsonrpc.rb new file mode 100644 index 0000000..0dd5ae1 --- /dev/null +++ b/lib/clamo/jsonrpc.rb @@ -0,0 +1,101 @@ +# frozen_string_literal: true + +module Clamo + module JSONRPC + PROTOCOL_VERSION_PRAGMA = { jsonrpc: "2.0" }.freeze + + module ProtocolErrors + ErrorDescriptor = Data.define(:code, :message) + SERVER_ERROR_CODE_RANGE = ((-32_099)..(-32_000)) + + PARSE_ERROR = ErrorDescriptor.new(code: -32_700, message: "Parse error") + INVALID_REQUEST = ErrorDescriptor.new(code: -32_600, message: "Invalid request") + METHOD_NOT_FOUND = ErrorDescriptor.new(code: -32_601, message: "Method not found") + INVALID_PARAMS = ErrorDescriptor.new(code: -32_602, message: "Invalid params") + INTERNAL_ERROR = ErrorDescriptor.new(code: -32_603, message: "Internal error") + SERVER_ERROR = ErrorDescriptor.new(code: -32_000, message: "Server error") + end + + class << self + def proper_pragma?(request) + request["jsonrpc"] == "2.0" + end + + def proper_method?(request) + request["method"].is_a?(String) + end + + def proper_id_if_any?(request) + if request.key?("id") + request["id"].is_a?(String) || + request["id"].is_a?(Integer) || + request["id"].is_a?(NilClass) + else + true + end + end + + def proper_params_if_any?(request) + if request.key?("params") + request["params"].is_a?(Array) + else + true + end + end + + def valid_request?(request) + request.is_a?(Hash) && + proper_pragma?(request) && + proper_method?(request) && + proper_id_if_any?(request) && + proper_params_if_any?(request) + end + + def build_request **opts + # raise if no method present + # raise if params present, but not an array + { jsonrpc: "2.0", + method: opts[:method] } + .merge({ params: opts[:params] }) + .merge(opts.key?(:id) ? { id: opts[:id] } : {}) + end + + def build_result_response(id:, result:) + {}.merge(PROTOCOL_VERSION_PRAGMA) + .merge({ result: result }) + .merge({ id: id }) + end + + def build_error_response **opts + # raise if no error code present + # raise if no error message present + { jsonrpc: "2.0", + id: opts[:id], + error: { + code: opts.dig(:error, :code), + message: opts.dig(:error, :message), + data: opts.dig(:error, :data) + }.reject { |k, _| k == :data && !opts[:error].key?(:data) } } + end + + def build_error_response_from **opts + # raise unless opts[:descriptor] + opts.merge( + { error: + { code: opts[:descriptor].code, + message: opts[:descriptor].message } } + ) + .then { |hash| build_error_response(**hash) } + end + + def build_error_response_parse_error **opts + opts.merge( + { error: + { code: ProtocolErrors::PARSE_ERROR.code, + message: ProtocolErrors::PARSE_ERROR.message } } + ) + .then { |hash| build_error_response(**hash) } + end + end + end +end diff --git a/lib/clamo/server.rb b/lib/clamo/server.rb new file mode 100644 index 0000000..57ec58b --- /dev/null +++ b/lib/clamo/server.rb @@ -0,0 +1,123 @@ +# frozen_string_literal: true + +require "json" + +module Clamo + module Server + class << self + # Clamo::Server.unparsed_dispatch_to_object( + # request: request_body, + # object: MyModule + # ) + def unparsed_dispatch_to_object(request:, object:, **opts) + # TODO: raise unless object is present? + begin + parsed = JSON.parse(request) + rescue JSON::JSONError # TODO: any error + return JSONRPC.build_error_response_parse_error + end + + parsed_dispatch_to_object(request: parsed, object: object, **opts) + end + + def parsed_dispatch_to_object(request:, object:, **opts) + response_for(request: request, object: object, **opts) do |method, params| + dispatch_to_ruby( + object: object, + method: method, + params: params # consider splating + ) + end + end + + def method_known?(object:, method:) + (object.public_methods - Object.methods) + .map(&:to_sym) + .include?(method.to_sym) + end + + def dispatch_to_ruby(object:, method:, params:) + case params + when Array + object.send method.to_sym, *params + when Hash + object.send method.to_sym, **params + when NilClass + object.send method.to_sym + else + # TODO: raise + raise "WTF" + end + end + + def response_for(request:, object:, **opts, &block) + case request + when Array # batch request + Parallel.map(request, **opts) do |item| + response_for_single_request( + request: item, + object: object, + block: block + ) + end.compact + when Hash # single request + response_for_single_request( + request: request, + object: object, + block: block + ) + else + JSONRPC.build_error_response_from( + id: nil, + descriptor: JSONRPC::ProtocolErrors::INVALID_REQUEST + ) + end + end + + def yield_to_execution(block:, method:, params:) + block.yield method, params + end + + def response_for_single_request(request:, object:, block:) + unless JSONRPC.valid_request?(request) + return JSONRPC.build_error_response_from( + id: request["id"], + descriptor: JSONRPC::ProtocolErrors::INVALID_REQUEST + ) + end + + unless request.key?("id") # notification - no result needed + # TODO: block.call off the current thread + Thread.new do + yield_to_execution( + block: block, + method: request["method"], + params: request["params"] + ) + rescue StandardError + # TODO: add exception handler + nil + end + + return nil + end + + unless method_known?(object: object, method: request["method"]) + return JSONRPC.build_error_response_from( + id: request["id"], + descriptor: JSONRPC::ProtocolErrors::METHOD_NOT_FOUND + ) + end + + JSONRPC.build_result_response( + id: request["id"], + result: yield_to_execution( + block: block, + method: request["method"], + params: request["params"] + ) + ) + end + end + end +end diff --git a/lib/clamo/version.rb b/lib/clamo/version.rb new file mode 100644 index 0000000..218bad0 --- /dev/null +++ b/lib/clamo/version.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +module Clamo + VERSION = "0.1.0" +end diff --git a/sig/clamo.rbs b/sig/clamo.rbs new file mode 100644 index 0000000..b0607b8 --- /dev/null +++ b/sig/clamo.rbs @@ -0,0 +1,4 @@ +module Clamo + VERSION: String + # See the writing guide of rbs: https://github.com/ruby/rbs#guides +end diff --git a/test/clamo/test_server.rb b/test/clamo/test_server.rb new file mode 100644 index 0000000..b1678d0 --- /dev/null +++ b/test/clamo/test_server.rb @@ -0,0 +1,148 @@ +# frozen_string_literal: true + +require "test_helper" + +class TestServer < Minitest::Test + module ExampleModule + class << self + def method_no_params_nil + nil + end + + def method_no_params_number + 42 + end + + def method_no_params_string + "Hello world" + end + + def method_no_params_array + [] + end + + def method_no_params_object + {} + end + + def method_one_params_echo(arg) + arg + end + + def method_one_params_array_echo(arg) + [arg] + end + + def method_one_params_object_echo(arg) + { value: arg } + end + end + end + + PARSE_ERROR_RESPONSE = { jsonrpc: "2.0", + id: nil, + error: { code: -32_700, + message: "Parse error" } }.freeze + INVALID_REQUEST_ERROR_RESPONSE = { jsonrpc: "2.0", + id: nil, + error: { code: -32_600, + message: "Invalid request" } }.freeze + + def with_request(req) + @response = Clamo::Server.parsed_dispatch_to_object( + object: ExampleModule, + request: req + ) + end + + def test_blank_request + with_request({}) + assert_equal INVALID_REQUEST_ERROR_RESPONSE, @response + end + + def test_number_request + with_request(1) + assert_equal INVALID_REQUEST_ERROR_RESPONSE, @response + end + + def test_string_request + with_request("") + assert_equal INVALID_REQUEST_ERROR_RESPONSE, @response + end + + def test_unknown_method_request + with_request({ "jsonrpc" => "2.0", "method" => "unknown_method", "id" => 1 }) + method_not_found_response = { jsonrpc: "2.0", id: 1, error: { code: -32_601, message: "Method not found" } } + assert_equal method_not_found_response, @response + end + + def test_unknown_method_notification + with_request({ "jsonrpc" => "2.0", "method" => "unknown_method" }) + assert_nil @response + end + + def test_no_params_result_nil + with_request({ "jsonrpc" => "2.0", "method" => "method_no_params_nil", "id" => 1 }) + assert_equal({ jsonrpc: "2.0", result: nil, id: 1 }, @response) + end + + def test_no_params_result_number + with_request({ "jsonrpc" => "2.0", "method" => "method_no_params_number", "id" => 1 }) + assert_equal({ jsonrpc: "2.0", result: 42, id: 1 }, @response) + end + + def test_no_params_result_string + with_request({ "jsonrpc" => "2.0", "method" => "method_no_params_string", "id" => 1 }) + assert_equal({ jsonrpc: "2.0", result: "Hello world", id: 1 }, @response) + end + + def test_no_params_result_array + with_request({ "jsonrpc" => "2.0", "method" => "method_no_params_array", "id" => 1 }) + assert_equal({ jsonrpc: "2.0", result: [], id: 1 }, @response) + end + + def test_no_params_result_object + with_request({ "jsonrpc" => "2.0", "method" => "method_no_params_object", "id" => 1 }) + assert_equal({ jsonrpc: "2.0", result: {}, id: 1 }, @response) + end + + def test_one_params_result_nil + with_request({ "jsonrpc" => "2.0", "method" => "method_one_params_echo", "params" => [nil], "id" => 1 }) + assert_equal({ jsonrpc: "2.0", result: nil, id: 1 }, @response) + end + + def test_one_params_result_number + with_request({ "jsonrpc" => "2.0", "method" => "method_one_params_echo", "params" => [42], "id" => 1 }) + assert_equal({ jsonrpc: "2.0", result: 42, id: 1 }, @response) + end + + def test_one_params_result_string + with_request({ "jsonrpc" => "2.0", "method" => "method_one_params_echo", "params" => ["hello"], "id" => 1 }) + assert_equal({ jsonrpc: "2.0", result: "hello", id: 1 }, @response) + end + + def test_one_params_result_array + with_request({ "jsonrpc" => "2.0", "method" => "method_one_params_echo", "params" => [[]], "id" => 1 }) + assert_equal({ jsonrpc: "2.0", result: [], id: 1 }, @response) + end + + def test_one_params_result_object + with_request({ "jsonrpc" => "2.0", "method" => "method_one_params_echo", "params" => [{}], "id" => 1 }) + assert_equal({ jsonrpc: "2.0", result: {}, id: 1 }, @response) + end + + def test_one_params_result_nil_in_array + with_request({ "jsonrpc" => "2.0", "method" => "method_one_params_array_echo", "params" => [nil], "id" => 1 }) + assert_equal({ jsonrpc: "2.0", result: [nil], id: 1 }, @response) + end + + def test_one_params_result_nil_in_object + with_request({ "jsonrpc" => "2.0", "method" => "method_one_params_object_echo", "params" => [nil], "id" => 1 }) + assert_equal({ jsonrpc: "2.0", result: { value: nil }, id: 1 }, @response) + end + + def test_one_params_result_object_in_object + with_request({ "jsonrpc" => "2.0", "method" => "method_one_params_object_echo", "params" => [{}], "id" => 1 }) + assert_equal({ jsonrpc: "2.0", result: { value: {} }, id: 1 }, @response) + end +end diff --git a/test/test_clamo.rb b/test/test_clamo.rb new file mode 100644 index 0000000..db0a830 --- /dev/null +++ b/test/test_clamo.rb @@ -0,0 +1,13 @@ +# frozen_string_literal: true + +require "test_helper" + +class TestClamo < Minitest::Test + def test_that_it_has_a_version_number + refute_nil ::Clamo::VERSION + end + + def test_it_does_something_useful + assert true + end +end diff --git a/test/test_helper.rb b/test/test_helper.rb new file mode 100644 index 0000000..d0c884c --- /dev/null +++ b/test/test_helper.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +$LOAD_PATH.unshift File.expand_path("../lib", __dir__) +require "clamo" + +require "minitest/autorun" +require "minitest/pride"