grumlin 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: 49bd6724ef81d1ac81e11d07d353b1f474ffaa60616dfab291d3f43ae81f95aa
4
+ data.tar.gz: 8023ce32bede0aadaed1c0495654b5d2bec8e244deb007b766561254b7c9b69e
5
+ SHA512:
6
+ metadata.gz: 434d14086ce4814684de2f414ba9eb9e5dd24f5a96b4acb0861b526f1515ad13dff96d5460d871e8373335f38baae013c248815d08e0ff2616a6ace873e1316a
7
+ data.tar.gz: e5fd01d1b8743d263097449f1f17ae515073e6253c7d7cfc11e65e923870b695c5d0a482105a41c20cea2a401f4cd2ffab3282defa74d0e9ed739e60fd850ead
@@ -0,0 +1,18 @@
1
+ name: Ruby
2
+
3
+ on: [push,pull_request]
4
+
5
+ jobs:
6
+ build:
7
+ runs-on: ubuntu-latest
8
+ steps:
9
+ - uses: actions/checkout@v2
10
+ - name: Set up Ruby
11
+ uses: ruby/setup-ruby@v1
12
+ with:
13
+ ruby-version: 3.0.1
14
+ - name: Run the default task
15
+ run: |
16
+ gem install bundler -v 2.2.15
17
+ bundle install
18
+ bundle exec rake
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,35 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.6
3
+ NewCops: enable
4
+ SuggestExtensions: false
5
+
6
+ require:
7
+ - rubocop-performance
8
+ - rubocop-rspec
9
+
10
+ Style/StringLiterals:
11
+ Enabled: true
12
+ EnforcedStyle: double_quotes
13
+
14
+ Style/StringLiteralsInInterpolation:
15
+ Enabled: true
16
+ EnforcedStyle: double_quotes
17
+
18
+ Style/Documentation:
19
+ Enabled: false
20
+
21
+ Layout/LineLength:
22
+ Max: 120
23
+
24
+ Metrics/BlockLength:
25
+ Exclude:
26
+ - spec/**/*_spec.rb
27
+
28
+ RSpec/NamedSubject:
29
+ Enabled: false
30
+
31
+ RSpec/NestedGroups:
32
+ Enabled: false
33
+
34
+ RSpec/ExampleLength:
35
+ Enabled: false
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2021-05-25
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 zhulik.gleb@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/Gemfile ADDED
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ gemspec
6
+
7
+ gem "rake"
8
+
9
+ gem "rubocop"
10
+ gem "rubocop-performance"
11
+ gem "rubocop-rspec"
12
+
13
+ gem "solargraph"
14
+
15
+ gem "async-rspec"
16
+ gem "factory_bot"
17
+ gem "rspec"
18
+ gem "simplecov"
data/Gemfile.lock ADDED
@@ -0,0 +1,162 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ grumlin (0.1.0)
5
+ async-websocket (~> 0.18)
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ activesupport (6.1.3.2)
11
+ concurrent-ruby (~> 1.0, >= 1.0.2)
12
+ i18n (>= 1.6, < 2)
13
+ minitest (>= 5.1)
14
+ tzinfo (~> 2.0)
15
+ zeitwerk (~> 2.3)
16
+ ast (2.4.2)
17
+ async (1.29.0)
18
+ console (~> 1.10)
19
+ nio4r (~> 2.3)
20
+ timers (~> 4.1)
21
+ async-http (0.56.2)
22
+ async (~> 1.25)
23
+ async-io (~> 1.28)
24
+ async-pool (~> 0.2)
25
+ protocol-http (~> 0.22.0)
26
+ protocol-http1 (~> 0.14.0)
27
+ protocol-http2 (~> 0.14.0)
28
+ async-io (1.31.0)
29
+ async (~> 1.14)
30
+ async-pool (0.3.6)
31
+ async (~> 1.25)
32
+ async-rspec (1.16.0)
33
+ rspec (~> 3.0)
34
+ rspec-files (~> 1.0)
35
+ rspec-memory (~> 1.0)
36
+ async-websocket (0.18.0)
37
+ async-http (~> 0.54)
38
+ async-io (~> 1.23)
39
+ protocol-websocket (~> 0.7.0)
40
+ backport (1.1.2)
41
+ benchmark (0.1.1)
42
+ concurrent-ruby (1.1.8)
43
+ console (1.12.0)
44
+ fiber-local
45
+ diff-lcs (1.4.4)
46
+ docile (1.4.0)
47
+ e2mmap (0.1.0)
48
+ factory_bot (6.2.0)
49
+ activesupport (>= 5.0.0)
50
+ fiber-local (1.0.0)
51
+ i18n (1.8.10)
52
+ concurrent-ruby (~> 1.0)
53
+ jaro_winkler (1.5.4)
54
+ kramdown (2.3.1)
55
+ rexml
56
+ kramdown-parser-gfm (1.1.0)
57
+ kramdown (~> 2.0)
58
+ minitest (5.14.4)
59
+ nio4r (2.5.7)
60
+ nokogiri (1.11.5-x86_64-linux)
61
+ racc (~> 1.4)
62
+ parallel (1.20.1)
63
+ parser (3.0.1.1)
64
+ ast (~> 2.4.1)
65
+ protocol-hpack (1.4.2)
66
+ protocol-http (0.22.0)
67
+ protocol-http1 (0.14.1)
68
+ protocol-http (~> 0.22)
69
+ protocol-http2 (0.14.2)
70
+ protocol-hpack (~> 1.4)
71
+ protocol-http (~> 0.18)
72
+ protocol-websocket (0.7.5)
73
+ protocol-http (~> 0.2)
74
+ protocol-http1 (~> 0.2)
75
+ racc (1.5.2)
76
+ rainbow (3.0.0)
77
+ rake (13.0.3)
78
+ regexp_parser (2.1.1)
79
+ reverse_markdown (2.0.0)
80
+ nokogiri
81
+ rexml (3.2.5)
82
+ rspec (3.10.0)
83
+ rspec-core (~> 3.10.0)
84
+ rspec-expectations (~> 3.10.0)
85
+ rspec-mocks (~> 3.10.0)
86
+ rspec-core (3.10.1)
87
+ rspec-support (~> 3.10.0)
88
+ rspec-expectations (3.10.1)
89
+ diff-lcs (>= 1.2.0, < 2.0)
90
+ rspec-support (~> 3.10.0)
91
+ rspec-files (1.1.1)
92
+ rspec (~> 3.0)
93
+ rspec-memory (1.0.2)
94
+ rspec (~> 3.0)
95
+ rspec-mocks (3.10.2)
96
+ diff-lcs (>= 1.2.0, < 2.0)
97
+ rspec-support (~> 3.10.0)
98
+ rspec-support (3.10.2)
99
+ rubocop (1.15.0)
100
+ parallel (~> 1.10)
101
+ parser (>= 3.0.0.0)
102
+ rainbow (>= 2.2.2, < 4.0)
103
+ regexp_parser (>= 1.8, < 3.0)
104
+ rexml
105
+ rubocop-ast (>= 1.5.0, < 2.0)
106
+ ruby-progressbar (~> 1.7)
107
+ unicode-display_width (>= 1.4.0, < 3.0)
108
+ rubocop-ast (1.5.0)
109
+ parser (>= 3.0.1.1)
110
+ rubocop-performance (1.11.3)
111
+ rubocop (>= 1.7.0, < 2.0)
112
+ rubocop-ast (>= 0.4.0)
113
+ rubocop-rspec (2.3.0)
114
+ rubocop (~> 1.0)
115
+ rubocop-ast (>= 1.1.0)
116
+ ruby-progressbar (1.11.0)
117
+ simplecov (0.21.2)
118
+ docile (~> 1.1)
119
+ simplecov-html (~> 0.11)
120
+ simplecov_json_formatter (~> 0.1)
121
+ simplecov-html (0.12.3)
122
+ simplecov_json_formatter (0.1.3)
123
+ solargraph (0.40.4)
124
+ backport (~> 1.1)
125
+ benchmark
126
+ bundler (>= 1.17.2)
127
+ e2mmap
128
+ jaro_winkler (~> 1.5)
129
+ kramdown (~> 2.3)
130
+ kramdown-parser-gfm (~> 1.1)
131
+ parser (~> 3.0)
132
+ reverse_markdown (>= 1.0.5, < 3)
133
+ rubocop (>= 0.52)
134
+ thor (~> 1.0)
135
+ tilt (~> 2.0)
136
+ yard (~> 0.9, >= 0.9.24)
137
+ thor (1.1.0)
138
+ tilt (2.0.10)
139
+ timers (4.3.3)
140
+ tzinfo (2.0.4)
141
+ concurrent-ruby (~> 1.0)
142
+ unicode-display_width (2.0.0)
143
+ yard (0.9.26)
144
+ zeitwerk (2.4.2)
145
+
146
+ PLATFORMS
147
+ x86_64-linux
148
+
149
+ DEPENDENCIES
150
+ async-rspec
151
+ factory_bot
152
+ grumlin!
153
+ rake
154
+ rspec
155
+ rubocop
156
+ rubocop-performance
157
+ rubocop-rspec
158
+ simplecov
159
+ solargraph
160
+
161
+ BUNDLED WITH
162
+ 2.2.15
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Gleb Sinyavskiy
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,43 @@
1
+ # Grumlin
2
+
3
+ [Gremlin](https://tinkerpop.apache.org/gremlin.html) query language DSL for Ruby
4
+
5
+ **In development. Nothing to write here yet. If you are really interested, check out the source code and the specs.**
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'grumlin'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle install
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install grumlin
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ 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.
30
+
31
+ 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).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/grumlin. 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/[USERNAME]/grumlin/blob/master/CODE_OF_CONDUCT.md).
36
+
37
+ ## License
38
+
39
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
40
+
41
+ ## Code of Conduct
42
+
43
+ Everyone interacting in the Grumlin project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/grumlin/blob/master/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: %i[spec rubocop]
data/bin/console ADDED
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "grumlin"
6
+ require "irb"
7
+
8
+ Async do
9
+ client = Grumlin::Client.new("ws://localhost:8182/gremlin", mode: :bytecode)
10
+ g = Grumlin::Traversal.new(client)
11
+
12
+ IRB.setup(nil)
13
+ workspace = IRB::WorkSpace.new(binding)
14
+ irb = IRB::Irb.new(workspace)
15
+ irb.eval_input
16
+ rescue StandardError
17
+ raise
18
+ ensure
19
+ client.disconnect
20
+ end
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/bin/stress ADDED
@@ -0,0 +1,51 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "grumlin"
6
+ require "irb"
7
+
8
+ def queries(client, uuids)
9
+ total = 0
10
+ g = Grumlin::Traversal.new(client)
11
+
12
+ loop do
13
+ uuid = uuids.sample
14
+ result = g.V(uuid).toList[0]
15
+ raise "!!!" if result.id != uuid
16
+
17
+ total += 1
18
+ end
19
+ rescue Async::Stop
20
+ total
21
+ end
22
+
23
+ def prepare_dataset(client)
24
+ uuids = Array.new(1000) { SecureRandom.uuid }
25
+
26
+ Grumlin::Traversal.new(client) do
27
+ g.V().drop
28
+
29
+ uuids.each do |uuid|
30
+ g.addV("test_vertex").property(id, uuid).toList
31
+ end
32
+ end
33
+
34
+ uuids
35
+ end
36
+
37
+ Async do |task|
38
+ client = Grumlin::Client.new("ws://localhost:8182/gremlin", mode: :bytecode)
39
+
40
+ uuids = prepare_dataset(client)
41
+ tasks = Array.new(20) { task.async { queries(client, uuids) } }
42
+
43
+ task.sleep(60)
44
+
45
+ tasks.each(&:stop)
46
+ total = tasks.sum(&:wait)
47
+
48
+ p("#{total} requests performed")
49
+ ensure
50
+ client.disconnect
51
+ end
data/grumlin.gemspec ADDED
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/grumlin/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "grumlin"
7
+ spec.version = Grumlin::VERSION
8
+ spec.authors = ["Gleb Sinyavskiy"]
9
+ spec.email = ["zhulik.gleb@gmail.com"]
10
+
11
+ spec.summary = "A ruby client for Gremlin query language."
12
+ spec.description = "A ruby client for Gremlin query language."
13
+ spec.homepage = "https://github.com/zhulik/grumlin"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.6.0")
16
+
17
+ spec.metadata["homepage_uri"] = spec.homepage
18
+ spec.metadata["source_code_uri"] = "https://github.com/zhulik/grumlin"
19
+ spec.metadata["changelog_uri"] = "https://github.com/zhulik/grumlin/blob/master/CHANGELOG.md"
20
+
21
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
22
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
23
+ end
24
+ spec.require_paths = ["lib"]
25
+
26
+ spec.add_dependency "async-websocket", "~> 0.18"
27
+ end
data/lib/grumlin.rb ADDED
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+ require "json"
5
+
6
+ require "async"
7
+ require "async/queue"
8
+ require "async/http/endpoint"
9
+ require "async/websocket/client"
10
+
11
+ require_relative "grumlin/version"
12
+ require_relative "grumlin/exceptions"
13
+
14
+ require_relative "grumlin/vertex"
15
+ require_relative "grumlin/edge"
16
+ require_relative "grumlin/typing"
17
+ require_relative "grumlin/client"
18
+ require_relative "grumlin/traversal"
19
+ require_relative "grumlin/step"
20
+ require_relative "grumlin/translator"
21
+ require_relative "grumlin/traversing_context"
22
+
23
+ module Grumlin
24
+ end
@@ -0,0 +1,172 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grumlin
4
+ class Client # rubocop:disable Metrics/ClassLength
5
+ SUCCESS_STATUS = 200
6
+ NO_CONTENT_STATUS = 204
7
+ PARTIAL_CONTENT_STATUS = 206
8
+
9
+ ERRORS = {
10
+ 499 => InvalidRequestArgumentsError,
11
+ 500 => ServerError,
12
+ 597 => ScriptEvaluationError,
13
+ 599 => ServerSerializationError,
14
+ 598 => ServerTimeoutError,
15
+
16
+ 401 => ClientSideError,
17
+ 407 => ClientSideError,
18
+ 498 => ClientSideError
19
+ }.freeze
20
+
21
+ def initialize(url, task: Async::Task.current, autoconnect: true, mode: :bytecode)
22
+ @task = task
23
+ @endpoint = Async::HTTP::Endpoint.parse(url)
24
+ @mode = mode
25
+
26
+ @requests = {}
27
+ @query_queue = Async::Queue.new
28
+
29
+ connect if autoconnect
30
+ end
31
+
32
+ def connect # rubocop:disable Metrics/MethodLength
33
+ raise AlreadyConnectedError unless @connection_task.nil?
34
+
35
+ @connection_task = @task.async do |subtask|
36
+ Async::WebSocket::Client.connect(@endpoint) do |connection|
37
+ subtask.async { query_task(connection) }
38
+ response_task(connection)
39
+ end
40
+ rescue StandardError => e
41
+ @requests.each_value do |queue|
42
+ queue << [:error, e]
43
+ end
44
+ disconnect
45
+ end
46
+ end
47
+
48
+ def disconnect
49
+ raise NotConnectedError if @connection_task.nil?
50
+
51
+ @connection_task&.stop
52
+ @connection_task&.wait
53
+ @connection_task = nil
54
+ @requests = {}
55
+ end
56
+
57
+ def query(*args) # rubocop:disable Metrics/MethodLength
58
+ response_queue, request_id = schedule_query(args)
59
+ result = []
60
+
61
+ response_queue.each do |status, response|
62
+ reraise_error!(response) if status == :error
63
+
64
+ status = response[:status]
65
+
66
+ if status[:code] == NO_CONTENT_STATUS
67
+ close_request(request_id)
68
+ return []
69
+ end
70
+
71
+ check_errors!(status, request_id)
72
+
73
+ page = Typing.cast(response.dig(:result, :data))
74
+
75
+ case status[:code]
76
+ when SUCCESS_STATUS
77
+ close_request(request_id)
78
+ return result + page
79
+ when PARTIAL_CONTENT_STATUS
80
+ result += page
81
+ else
82
+ raise UnknownResponseStatus, status
83
+ end
84
+ end
85
+ end
86
+
87
+ private
88
+
89
+ def schedule_query(args)
90
+ uuid = SecureRandom.uuid
91
+ queue = Async::Queue.new
92
+ @requests[uuid] = queue
93
+ @query_queue << to_query(uuid, args)
94
+
95
+ [queue, uuid]
96
+ end
97
+
98
+ def to_query(uuid, message)
99
+ case message.first
100
+ when String
101
+ string_query_message(uuid, *message)
102
+ when Grumlin::Step
103
+ build_query(uuid, message)
104
+ end
105
+ end
106
+
107
+ def check_errors!(status, request_id)
108
+ error = ERRORS[status[:code]]
109
+ close_request(request_id)
110
+ raise(error, status) if error
111
+ end
112
+
113
+ def close_request(request_id)
114
+ @requests.delete(request_id)
115
+ end
116
+
117
+ def reraise_error!(error)
118
+ raise error
119
+ rescue StandardError
120
+ raise ConnectionError
121
+ end
122
+
123
+ def query_task(connection)
124
+ loop do
125
+ connection.write @query_queue.dequeue
126
+ connection.flush
127
+ end
128
+ end
129
+
130
+ def response_task(connection)
131
+ loop do
132
+ response = connection.read
133
+ response_queue = @requests[response[:requestId]]
134
+ response_queue << [:response, response]
135
+ end
136
+ end
137
+
138
+ def string_query_message(uuid, query, bindings)
139
+ {
140
+ requestId: uuid,
141
+ op: "eval",
142
+ processor: "",
143
+ args: {
144
+ gremlin: query,
145
+ bindings: bindings,
146
+ language: "gremlin-groovy"
147
+ }
148
+ }
149
+ end
150
+
151
+ def bytecode_query_message(uuid, bytecode)
152
+ {
153
+ requestId: uuid,
154
+ op: "bytecode",
155
+ processor: "traversal",
156
+ args: {
157
+ gremlin: { "@type": "g:Bytecode", "@value": { step: bytecode } },
158
+ aliases: { g: :g }
159
+ }
160
+ }
161
+ end
162
+
163
+ def build_query(uuid, steps)
164
+ case @mode
165
+ when :string
166
+ string_query_message(uuid, *Translator.to_string_query(steps))
167
+ else
168
+ bytecode_query_message(uuid, Translator.to_bytecode_query(steps))
169
+ end
170
+ end
171
+ end
172
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ # rubocop:disable Naming/VariableName,Naming/MethodParameterName,Naming/MethodName
4
+ module Grumlin
5
+ class Edge
6
+ attr_reader :label, :id, :inVLabel, :outVLabel, :inV, :outV
7
+
8
+ def initialize(label:, id:, inVLabel:, outVLabel:, inV:, outV:) # rubocop:disable Metrics/ParameterLists
9
+ @label = label
10
+ @id = Typing.cast(id)
11
+ @inVLabel = inVLabel
12
+ @outVLabel = outVLabel
13
+ @inV = Typing.cast(inV)
14
+ @outV = Typing.cast(outV)
15
+ end
16
+
17
+ def ==(other)
18
+ @label == other.label && @id == other.id
19
+ end
20
+
21
+ def inspect
22
+ "<E #{@label}(#{@id})>"
23
+ end
24
+ alias to_s inspect
25
+ end
26
+ end
27
+ # rubocop:enable Naming/MethodParameterName,Naming/VariableName,Naming/MethodName
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grumlin
4
+ class Error < StandardError; end
5
+
6
+ class ConnectionError < Error; end
7
+
8
+ class ConnectionStatusError < Error; end
9
+
10
+ class NotConnectedError < ConnectionStatusError; end
11
+
12
+ class AlreadyConnectedError < ConnectionStatusError; end
13
+
14
+ class ProtocolError < Error; end
15
+
16
+ class UnknownResponseStatus < ProtocolError
17
+ attr_reader :status
18
+
19
+ def initialize(status)
20
+ super("unknown response status code #{status[:code]}")
21
+ @status = status
22
+ end
23
+ end
24
+
25
+ class UnknownTypeError < ProtocolError; end
26
+
27
+ class ConnectionClosedError < Error; end
28
+
29
+ class StatusError < Error
30
+ attr_reader :status
31
+
32
+ def initialize(status)
33
+ super(status[:message])
34
+ @status = status
35
+ end
36
+ end
37
+
38
+ class ClientSideError < StatusError; end
39
+
40
+ class ServerSideError < StatusError; end
41
+
42
+ class ScriptEvaluationError < ServerSideError; end
43
+
44
+ class InvalidRequestArgumentsError < ServerSideError; end
45
+
46
+ class ServerError < ServerSideError; end
47
+
48
+ class ServerSerializationError < ServerSideError; end
49
+
50
+ class ServerTimeoutError < ServerSideError; end
51
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grumlin
4
+ class Step
5
+ attr_reader :client, :name, :args
6
+
7
+ # TODO: add support for bytecode
8
+ def initialize(client, name, *args, previous_steps: [])
9
+ @client = client
10
+ @name = name
11
+ @previous_steps = previous_steps
12
+ @args = args
13
+ end
14
+
15
+ %w[addV addE V E limit count drop property valueMap select from to as].each do |step|
16
+ define_method step do |*args|
17
+ Step.new(@client, step, *args, previous_steps: steps)
18
+ end
19
+ end
20
+
21
+ alias addVertex addV
22
+ alias addEdge addE
23
+
24
+ # TODO: add support for next
25
+ # TODO: add support for iterate
26
+ # TODO: memoization
27
+ def toList # rubocop:disable Naming/MethodName
28
+ @client.query(*steps)
29
+ end
30
+
31
+ def inspect
32
+ "<Step #{self}>" # TODO: substitute bindings
33
+ end
34
+
35
+ # TODO: memoization
36
+ def to_s(*)
37
+ Translator.to_string(steps)
38
+ end
39
+
40
+ alias to_gremlin to_s
41
+
42
+ def steps
43
+ (@previous_steps + [self])
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grumlin
4
+ module Translator
5
+ class << self
6
+ def to_string_query(steps) # rubocop:disable Metrics/MethodLength
7
+ counter = 0
8
+ string_steps, bindings = steps.each_with_object([[], {}]) do |step, (acc_g, acc_b)|
9
+ args = step.args.map do |arg|
10
+ binding_name(counter).tap do |b|
11
+ acc_b[b] = arg
12
+ counter += 1
13
+ end
14
+ end.join(", ")
15
+
16
+ acc_g << "#{step.name}(#{args})"
17
+ end
18
+
19
+ ["g.#{string_steps.join(".")}", bindings]
20
+ end
21
+
22
+ def to_bytecode_query(steps)
23
+ steps.map do |step|
24
+ [step.name, *step.args.flatten]
25
+ end
26
+ end
27
+
28
+ def to_string(steps)
29
+ "g." + steps.map do |step| # rubocop:disable Style/StringConcatenation
30
+ "#{step.name}(#{step.args.map(&:inspect).join(", ")})"
31
+ end.join(".")
32
+ end
33
+
34
+ private
35
+
36
+ def binding_name(num)
37
+ "b_#{num.to_s(16)}"
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grumlin
4
+ class Traversal
5
+ attr_reader :connection
6
+
7
+ def initialize(client_or_url, &block)
8
+ @client = if client_or_url.is_a?(String)
9
+ Grumlin::Client.new(client_or_url)
10
+ else
11
+ client_or_url
12
+ end
13
+
14
+ return if block.nil?
15
+
16
+ TraversingContext.new(self).instance_exec(&block)
17
+ end
18
+
19
+ %w[addV addE V E].each do |step|
20
+ define_method step do |*args|
21
+ Step.new(@client, step, *args)
22
+ end
23
+ end
24
+
25
+ alias addVertex addV
26
+ alias addEdge addE
27
+ end
28
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grumlin
4
+ class TraversingContext
5
+ ID = { :@type => "g:T", :@value => "id" }.freeze
6
+
7
+ attr_reader :g
8
+
9
+ def initialize(traversal)
10
+ @g = traversal
11
+ end
12
+
13
+ def id
14
+ ID
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grumlin
4
+ module Typing
5
+ TYPES = {
6
+ "g:List" => ->(value) { value.map { |item| cast(item) } },
7
+ "g:Map" => ->(value) { cast_map(value) },
8
+ "g:Vertex" => ->(value) { cast_entity(Grumlin::Vertex, value) },
9
+ "g:Edge" => ->(value) { cast_entity(Grumlin::Edge, value) },
10
+ "g:Int64" => ->(value) { cast_int(value) },
11
+ "g:Int32" => ->(value) { cast_int(value) },
12
+ "g:Traverser" => ->(value) { cast(value[:value]) } # TODO: wtf is bulk?
13
+ }.freeze
14
+
15
+ CASTABLE_TYPES = [Hash, String, Integer].freeze
16
+
17
+ class << self
18
+ def cast(value)
19
+ verify_type!(value)
20
+
21
+ return value unless value.is_a?(Hash)
22
+
23
+ type = TYPES[value[:@type]]
24
+
25
+ verify_castable_hash!(value, type)
26
+
27
+ type.call(value[:@value])
28
+ end
29
+
30
+ private
31
+
32
+ def castable_type?(value); end
33
+
34
+ def verify_type!(value)
35
+ raise TypeError, "#{value.inspect} cannot be casted" unless CASTABLE_TYPES.any? { |t| value.is_a?(t) }
36
+ end
37
+
38
+ def verify_castable_hash!(value, type)
39
+ raise TypeError, "#{value} cannot be casted, @type is missing" if value[:@type].nil?
40
+ raise(UnknownTypeError, value[:@type]) if type.nil?
41
+ raise TypeError, "#{value} cannot be casted, @value is missing" if value[:@value].nil?
42
+ end
43
+
44
+ def cast_int(value)
45
+ raise TypeError, "#{value} is not an Integer" unless value.is_a?(Integer)
46
+
47
+ value
48
+ end
49
+
50
+ def cast_entity(entity, value)
51
+ entity.new(**value)
52
+ rescue ArgumentError, TypeError
53
+ raise TypeError, "#{value} cannot be casted to #{entity.name}"
54
+ end
55
+
56
+ def cast_map(value)
57
+ Hash[*value].transform_keys(&:to_sym).transform_values { |v| cast(v) }
58
+ rescue ArgumentError
59
+ raise TypeError, "#{value} cannot be casted to Hash"
60
+ end
61
+
62
+ def cast_traverser(value); end
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grumlin
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grumlin
4
+ class Vertex
5
+ attr_reader :label, :id
6
+
7
+ def initialize(label:, id:)
8
+ @label = label
9
+ @id = Typing.cast(id)
10
+ end
11
+
12
+ def ==(other)
13
+ @label == other.label && @id == other.id
14
+ end
15
+
16
+ def inspect
17
+ "<V #{@label}(#{@id})>"
18
+ end
19
+ alias to_s inspect
20
+ end
21
+ end
metadata ADDED
@@ -0,0 +1,86 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: grumlin
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Gleb Sinyavskiy
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2021-05-27 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: async-websocket
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '0.18'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '0.18'
27
+ description: A ruby client for Gremlin query language.
28
+ email:
29
+ - zhulik.gleb@gmail.com
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - ".github/workflows/main.yml"
35
+ - ".gitignore"
36
+ - ".rspec"
37
+ - ".rubocop.yml"
38
+ - CHANGELOG.md
39
+ - CODE_OF_CONDUCT.md
40
+ - Gemfile
41
+ - Gemfile.lock
42
+ - LICENSE.txt
43
+ - README.md
44
+ - Rakefile
45
+ - bin/console
46
+ - bin/setup
47
+ - bin/stress
48
+ - grumlin.gemspec
49
+ - lib/grumlin.rb
50
+ - lib/grumlin/client.rb
51
+ - lib/grumlin/edge.rb
52
+ - lib/grumlin/exceptions.rb
53
+ - lib/grumlin/step.rb
54
+ - lib/grumlin/translator.rb
55
+ - lib/grumlin/traversal.rb
56
+ - lib/grumlin/traversing_context.rb
57
+ - lib/grumlin/typing.rb
58
+ - lib/grumlin/version.rb
59
+ - lib/grumlin/vertex.rb
60
+ homepage: https://github.com/zhulik/grumlin
61
+ licenses:
62
+ - MIT
63
+ metadata:
64
+ homepage_uri: https://github.com/zhulik/grumlin
65
+ source_code_uri: https://github.com/zhulik/grumlin
66
+ changelog_uri: https://github.com/zhulik/grumlin/blob/master/CHANGELOG.md
67
+ post_install_message:
68
+ rdoc_options: []
69
+ require_paths:
70
+ - lib
71
+ required_ruby_version: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: 2.6.0
76
+ required_rubygems_version: !ruby/object:Gem::Requirement
77
+ requirements:
78
+ - - ">="
79
+ - !ruby/object:Gem::Version
80
+ version: '0'
81
+ requirements: []
82
+ rubygems_version: 3.2.15
83
+ signing_key:
84
+ specification_version: 4
85
+ summary: A ruby client for Gremlin query language.
86
+ test_files: []