iopromise-dalli 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: 506d6c0d703b3ba413265cf71236b40904e3dc816a2d3b3dc5df92c25a07f5f7
4
+ data.tar.gz: beffa392adba71f9c498708915c7a9a962f25732f07d00b85651d32655130425
5
+ SHA512:
6
+ metadata.gz: bdd6d517e8daa20e3e4c080af085156260e1ba0d13c11d58adb551e232758ddedc42d430fe448408cca0c23b947a4b2b6b85701c9cd12bfc2eba10e513c848f9
7
+ data.tar.gz: ae2004a6c2abd85631aad564d90c3549fa528422944bfae69fbc1edf376b900dd903c11eda929558ad0f130b8bdab07584d72d546e58e7e5d9f5f4061877a360
@@ -0,0 +1,19 @@
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
+ - uses: niden/actions-memcached@v7
11
+ - name: Set up Ruby
12
+ uses: ruby/setup-ruby@v1
13
+ with:
14
+ ruby-version: 2.7.2
15
+ - name: Run the default task
16
+ run: |
17
+ gem install bundler -v 2.2.9
18
+ bundle install
19
+ bundle exec rake
data/.gitignore ADDED
@@ -0,0 +1,57 @@
1
+ *.gem
2
+ *.rbc
3
+ /.config
4
+ /coverage/
5
+ /InstalledFiles
6
+ /pkg/
7
+ /spec/reports/
8
+ /spec/examples.txt
9
+ /test/tmp/
10
+ /test/version_tmp/
11
+ /tmp/
12
+
13
+ # Used by dotenv library to load environment variables.
14
+ # .env
15
+
16
+ # Ignore Byebug command history file.
17
+ .byebug_history
18
+
19
+ ## Specific to RubyMotion:
20
+ .dat*
21
+ .repl_history
22
+ build/
23
+ *.bridgesupport
24
+ build-iPhoneOS/
25
+ build-iPhoneSimulator/
26
+
27
+ ## Specific to RubyMotion (use of CocoaPods):
28
+ #
29
+ # We recommend against adding the Pods directory to your .gitignore. However
30
+ # you should judge for yourself, the pros and cons are mentioned at:
31
+ # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
32
+ #
33
+ # vendor/Pods/
34
+
35
+ ## Documentation cache and generated files:
36
+ /.yardoc/
37
+ /_yardoc/
38
+ /doc/
39
+ /rdoc/
40
+
41
+ ## Environment normalization:
42
+ /.bundle/
43
+ /vendor/bundle
44
+ /lib/bundler/man/
45
+
46
+ # for a library or gem, you might want to ignore these files since the code is
47
+ # intended to run in multiple environments; otherwise, check them in:
48
+ # Gemfile.lock
49
+ # .ruby-version
50
+ # .ruby-gemset
51
+
52
+ # unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
53
+ .rvmrc
54
+
55
+ # Used by RuboCop. Remote config files pulled in from inherit_from directive.
56
+ # .rubocop-https?--*
57
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -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 theojulienne@github.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,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in iopromise.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
11
+
12
+ group :development, :test do
13
+ # benchmarking
14
+ gem "benchmark-ips"
15
+ gem "stackprof"
16
+ end
data/Gemfile.lock ADDED
@@ -0,0 +1,46 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ iopromise-dalli (0.1.0)
5
+ dalli (= 2.7.11)
6
+ iopromise (~> 0.1.3)
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ benchmark-ips (2.9.1)
12
+ dalli (2.7.11)
13
+ diff-lcs (1.4.4)
14
+ iopromise (0.1.3)
15
+ nio4r
16
+ promise.rb (~> 0.7.4)
17
+ nio4r (2.5.7)
18
+ promise.rb (0.7.4)
19
+ rake (13.0.3)
20
+ rspec (3.10.0)
21
+ rspec-core (~> 3.10.0)
22
+ rspec-expectations (~> 3.10.0)
23
+ rspec-mocks (~> 3.10.0)
24
+ rspec-core (3.10.1)
25
+ rspec-support (~> 3.10.0)
26
+ rspec-expectations (3.10.1)
27
+ diff-lcs (>= 1.2.0, < 2.0)
28
+ rspec-support (~> 3.10.0)
29
+ rspec-mocks (3.10.2)
30
+ diff-lcs (>= 1.2.0, < 2.0)
31
+ rspec-support (~> 3.10.0)
32
+ rspec-support (3.10.2)
33
+ stackprof (0.2.17)
34
+
35
+ PLATFORMS
36
+ x86_64-linux
37
+
38
+ DEPENDENCIES
39
+ benchmark-ips
40
+ iopromise-dalli!
41
+ rake (~> 13.0)
42
+ rspec (~> 3.0)
43
+ stackprof
44
+
45
+ BUNDLED WITH
46
+ 2.2.17
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 iopromise-ruby
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 all
13
+ 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 THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,65 @@
1
+ # iopromise-dalli
2
+
3
+ This gem provides a promise-based parallel interface to [dalli](https://github.com/petergoldstein/dalli) (memcached), based on [IOPromise](https://github.com/iopromise-ruby/iopromise).
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'iopromise-dalli'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle install
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install iopromise-dalli
20
+
21
+ ## Usage
22
+
23
+ The pattern for using `IOPromise::Dalli` is very similar to regular Dalli, except that everything returns promises, and the promises resolve to response objects that contain the `value` and `exist?` as separate control and data information.
24
+
25
+ ```ruby
26
+ require 'iopromise/dalli'
27
+
28
+ client = IOPromise::Dalli.new('localhost:11211')
29
+
30
+ promises = [
31
+ client.get('some_key'),
32
+ client.set('another_key', 'something'),
33
+ ]
34
+
35
+ promises << client.get('next_key').then do |response|
36
+ # note that control (exist?) and data (value) are not mixed
37
+ if response.exist?
38
+ puts "#{response.key} exists with value #{response.value}"
39
+ else
40
+ puts "#{response.key} does not exist"
41
+ end
42
+ end
43
+
44
+ # this will execute all 3 operations at the same time, similarly to an "mget",
45
+ # but not dependent on an explicit API, nor limited to just gets.
46
+ Promise.all(promises).sync
47
+ ```
48
+
49
+ ## Development
50
+
51
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `bundle exec rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
52
+
53
+ 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).
54
+
55
+ ## Contributing
56
+
57
+ Bug reports and pull requests are welcome on GitHub at https://github.com/iopromise-ruby/iopromise-dalli. 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/iopromise-ruby/iopromise-dalli/blob/main/CODE_OF_CONDUCT.md).
58
+
59
+ ## License
60
+
61
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
62
+
63
+ ## Code of Conduct
64
+
65
+ Everyone interacting in the iopromise project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/iopromise-ruby/iopromise-dalli/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "iopromise/dalli"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # bring up a memcached for testing
9
+ docker run -d -p 11211:11211 memcached:alpine
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/iopromise/dalli/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "iopromise-dalli"
7
+ spec.version = IOPromise::Dalli::VERSION
8
+ spec.authors = ["Theo Julienne"]
9
+ spec.email = ["theo.julienne@gmail.com"]
10
+
11
+ spec.summary = "Parallel Dalli support via IOPromise"
12
+ spec.description = "This gem provides a promise-based interface to Dalli (memcached) using IOPromise"
13
+ spec.homepage = "https://github.com/iopromise-ruby/iopromise-dalli"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.4.0")
16
+
17
+ spec.metadata["homepage_uri"] = spec.homepage
18
+ spec.metadata["source_code_uri"] = spec.homepage
19
+
20
+ # Specify which files should be added to the gem when it is released.
21
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
22
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
23
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
24
+ end
25
+ spec.bindir = "exe"
26
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
27
+ spec.require_paths = ["lib"]
28
+
29
+ spec.add_dependency 'iopromise', '~> 0.1.3'
30
+
31
+ # we pin this very specifically while we are monkey patching support
32
+ spec.add_dependency 'dalli', '2.7.11'
33
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'dalli/client'
4
+
5
+ module IOPromise
6
+ module Dalli
7
+ class << self
8
+ def new(*args, **kwargs)
9
+ ::IOPromise::Dalli::Client.new(*args, **kwargs)
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,142 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'dalli'
4
+ require_relative 'promise'
5
+ require_relative 'patch_dalli'
6
+
7
+ module IOPromise
8
+ module Dalli
9
+ class Client
10
+ # General note:
11
+ # There is no need for explicit get_multi or batching, as requests
12
+ # are sent as soon as the IOPromise is created, multiple can be
13
+ # awaiting response at any time, and responses are automatically demuxed.
14
+ def initialize(servers = nil, options = {})
15
+ @cache_nils = !!options[:cache_nils]
16
+ options[:iopromise_async] = true
17
+ @options = options
18
+ @client = ::Dalli::Client.new(servers, options)
19
+ end
20
+
21
+ # Returns a promise that resolves to a IOPromise::Dalli::Response with the
22
+ # value for the given key, or +nil+ if the key is not found.
23
+ def get(key, options = nil)
24
+ @client.perform(:get, key, options)
25
+ end
26
+
27
+ # Convenience function that attempts to fetch the given key, or set
28
+ # the key with a dynamically generated value if it does not exist.
29
+ # Either way, the returned promise will resolve to the cached or computed
30
+ # value.
31
+ #
32
+ # If the value does not exist then the provided block is run to generate
33
+ # the value (which can also be a promise), after which the value is set
34
+ # if it still doesn't exist.
35
+ def fetch(key, ttl = nil, options = nil, &block)
36
+ # match the Dalli behaviour exactly
37
+ options = options.nil? ? ::Dalli::Client::CACHE_NILS : options.merge(::Dalli::Client::CACHE_NILS) if @cache_nils
38
+ get(key, options).then do |response|
39
+ not_found = @options[:cache_nils] ?
40
+ !response.exist? :
41
+ response.value.nil?
42
+ if not_found && !block.nil?
43
+ block.call.then do |new_val|
44
+ # delay the final resolution here until after the add succeeds,
45
+ # to guarantee errors are caught. we could potentially allow
46
+ # the add to resolve once it's sent (without confirmation), but
47
+ # we do need to wait on the add promise to ensure it's sent.
48
+ add(key, new_val, ttl, options).then { new_val }
49
+ end
50
+ else
51
+ response.value
52
+ end
53
+ end
54
+ end
55
+
56
+ # Unconditionally sets the +key+ to the +value+ specified.
57
+ # Returns a promise that resolves to a IOPromise::Dalli::Response.
58
+ def set(key, value, ttl = nil, options = nil)
59
+ @client.perform(:set, key, value, ttl_or_default(ttl), 0, options)
60
+ end
61
+
62
+ # Conditionally sets the +key+ to the +value+ specified.
63
+ # Returns a promise that resolves to a IOPromise::Dalli::Response.
64
+ def add(key, value, ttl = nil, options = nil)
65
+ @client.perform(:add, key, value, ttl_or_default(ttl), options)
66
+ end
67
+
68
+ # Conditionally sets the +key+ to the +value+ specified only
69
+ # if the key already exists.
70
+ # Returns a promise that resolves to a IOPromise::Dalli::Response.
71
+ def replace(key, value, ttl = nil, options = nil)
72
+ @client.perform(:replace, key, value, ttl_or_default(ttl), 0, options)
73
+ end
74
+
75
+ # Deletes the specified key, resolving the promise when complete.
76
+ def delete(key)
77
+ @client.perform(:delete, key, 0)
78
+ end
79
+
80
+ # Appends a value to the specified key, resolving the promise when complete.
81
+ # Appending only works for values stored with :raw => true.
82
+ def append(key, value)
83
+ value.then do |resolved_value|
84
+ @client.perform(:append, key, resolved_value.to_s)
85
+ end
86
+ end
87
+
88
+ # Prepend a value to the specified key, resolving the promise when complete.
89
+ # Prepending only works for values stored with :raw => true.
90
+ def prepend(key, value)
91
+ value.then do |resolved_value|
92
+ @client.perform(:prepend, key, resolved_value.to_s)
93
+ end
94
+ end
95
+
96
+ ##
97
+ # Incr adds the given amount to the counter on the memcached server.
98
+ # Amt must be a positive integer value.
99
+ #
100
+ # If default is nil, the counter must already exist or the operation
101
+ # will fail and will return nil. Otherwise this method will return
102
+ # the new value for the counter.
103
+ #
104
+ # Note that the ttl will only apply if the counter does not already
105
+ # exist. To increase an existing counter and update its TTL, use
106
+ # #cas.
107
+ def incr(key, amt = 1, ttl = nil, default = nil)
108
+ raise ArgumentError, "Positive values only: #{amt}" if amt < 0
109
+ @client.perform(:incr, key, amt.to_i, ttl_or_default(ttl), default)
110
+ end
111
+
112
+ ##
113
+ # Decr subtracts the given amount from the counter on the memcached server.
114
+ # Amt must be a positive integer value.
115
+ #
116
+ # memcached counters are unsigned and cannot hold negative values. Calling
117
+ # decr on a counter which is 0 will just return 0.
118
+ #
119
+ # If default is nil, the counter must already exist or the operation
120
+ # will fail and will return nil. Otherwise this method will return
121
+ # the new value for the counter.
122
+ #
123
+ # Note that the ttl will only apply if the counter does not already
124
+ # exist. To decrease an existing counter and update its TTL, use
125
+ # #cas.
126
+ def decr(key, amt = 1, ttl = nil, default = nil)
127
+ raise ArgumentError, "Positive values only: #{amt}" if amt < 0
128
+ @client.perform(:decr, key, amt.to_i, ttl_or_default(ttl), default)
129
+ end
130
+
131
+ # TODO: touch, gat, CAS operations
132
+
133
+ private
134
+
135
+ def ttl_or_default(ttl)
136
+ (ttl || @options[:expires_in]).to_i
137
+ rescue NoMethodError
138
+ raise ArgumentError, "Cannot convert ttl (#{ttl}) to an integer"
139
+ end
140
+ end
141
+ end
142
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'iopromise'
4
+
5
+ module IOPromise
6
+ module Dalli
7
+ class DalliExecutorPool < IOPromise::ExecutorPool::Base
8
+ def initialize(*)
9
+ super
10
+
11
+ @iop_monitor = nil
12
+ end
13
+
14
+ def dalli_server
15
+ @connection_pool
16
+ end
17
+
18
+ def execute_continue
19
+ dalli_server.execute_continue
20
+ end
21
+
22
+ def connected_socket(sock)
23
+ close_socket
24
+
25
+ @iop_monitor = ::IOPromise::ExecutorContext.current.register_observer_io(self, sock, :r)
26
+ end
27
+
28
+ def close_socket
29
+ unless @iop_monitor.nil?
30
+ @iop_monitor.close
31
+ @iop_monitor = nil
32
+ end
33
+ end
34
+
35
+ def monitor_ready(monitor, readiness)
36
+ dalli_server.async_io_ready(monitor.readable?, monitor.writable?)
37
+ end
38
+
39
+ def set_interest(direction, interested)
40
+ if interested
41
+ @iop_monitor.add_interest(direction)
42
+ else
43
+ @iop_monitor.remove_interest(direction)
44
+ end
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,353 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'dalli'
4
+ require_relative 'response'
5
+
6
+ module IOPromise
7
+ module Dalli
8
+ module AsyncClient
9
+ def initialize(servers = nil, options = {})
10
+ @async = options[:iopromise_async] == true
11
+
12
+ super
13
+ end
14
+
15
+ def perform(*)
16
+ return super unless @async
17
+
18
+ begin
19
+ super
20
+ rescue => ex
21
+ # Wrap any connection errors into a promise, this is more forwards-compatible
22
+ # if we ever attempt to make connecting/server fallback nonblocking too.
23
+ Promise.new.tap { |p| p.reject(ex) }
24
+ end
25
+ end
26
+ end
27
+
28
+ module AsyncServer
29
+ def initialize(attribs, options = {})
30
+ @async = options.delete(:iopromise_async) == true
31
+
32
+ if @async
33
+ @write_buffer = +""
34
+ @read_buffer = +""
35
+ async_reset
36
+
37
+ @next_opaque_id = 0
38
+ @pending_ops = {}
39
+
40
+ @executor_pool = DalliExecutorPool.for(self)
41
+ end
42
+
43
+ super
44
+ end
45
+
46
+ def async?
47
+ @async
48
+ end
49
+
50
+ def close
51
+ if async?
52
+ async_reset
53
+ end
54
+
55
+ super
56
+ end
57
+
58
+ def connect
59
+ super
60
+
61
+ if async?
62
+ @executor_pool.connected_socket(@sock)
63
+ end
64
+ end
65
+
66
+ def async_reset
67
+ @write_buffer.clear
68
+ @write_offset = 0
69
+
70
+ @read_buffer.clear
71
+ @read_offset = 0
72
+
73
+ @executor_pool.close_socket if defined? @executor_pool
74
+ end
75
+
76
+ def async_io_ready(readable, writable)
77
+ async_sock_write_nonblock if writable
78
+ async_sock_read_nonblock if readable
79
+ end
80
+
81
+ # called by ExecutorPool to continue processing for this server
82
+ def execute_continue
83
+ timeout = @options[:socket_timeout]
84
+ @pending_ops.select! do |key, op|
85
+ if op.timeout?
86
+ op.reject(Timeout::Error.new)
87
+ next false # this op is done
88
+ end
89
+
90
+ # let all pending operations know that they are seeing the
91
+ # select loop. this starts the timer for the operation, because
92
+ # it guarantees we're now working on it.
93
+ # this is more accurate than starting the timer when we buffer
94
+ # the write.
95
+ op.in_select_loop
96
+
97
+ remaining = op.timeout_remaining
98
+ timeout = remaining if remaining < timeout
99
+
100
+ true # keep
101
+ end
102
+
103
+ @executor_pool.select_timeout = timeout
104
+ @executor_pool.set_interest(:r, !@pending_ops.empty?)
105
+ end
106
+
107
+ private
108
+
109
+ REQUEST = ::Dalli::Server::REQUEST
110
+ OPCODES = ::Dalli::Server::OPCODES
111
+ FORMAT = ::Dalli::Server::FORMAT
112
+
113
+
114
+ def promised_request(key, &block)
115
+ promise = ::IOPromise::Dalli::DalliPromise.new(self, key)
116
+
117
+ new_id = @next_opaque_id
118
+ @pending_ops[new_id] = promise
119
+ @next_opaque_id = (@next_opaque_id + 1) & 0xffff_ffff
120
+
121
+ async_buffered_write(block.call(new_id))
122
+
123
+ promise
124
+ end
125
+
126
+ def get(key, options = nil)
127
+ return super unless async?
128
+
129
+ promised_request(key) do |opaque|
130
+ [REQUEST, OPCODES[:get], key.bytesize, 0, 0, 0, key.bytesize, opaque, 0, key].pack(FORMAT[:get])
131
+ end
132
+ end
133
+
134
+ def async_generic_write_op(op, key, value, ttl, cas, options)
135
+ value.then do |value|
136
+ (value, flags) = serialize(key, value, options)
137
+ ttl = sanitize_ttl(ttl)
138
+
139
+ guard_max_value_with_raise(key, value)
140
+
141
+ promised_request(key) do |opaque|
142
+ [REQUEST, OPCODES[op], key.bytesize, 8, 0, 0, value.bytesize + key.bytesize + 8, opaque, cas, flags, ttl, key, value].pack(FORMAT[op])
143
+ end
144
+ end
145
+ end
146
+
147
+ def set(key, value, ttl, cas, options)
148
+ return super unless async?
149
+ async_generic_write_op(:set, key, value, ttl, cas, options)
150
+ end
151
+
152
+ def add(key, value, ttl, options)
153
+ return super unless async?
154
+
155
+ async_generic_write_op(:add, key, value, ttl, 0, options)
156
+ end
157
+
158
+ def replace(key, value, ttl, cas, options)
159
+ return super unless async?
160
+
161
+ async_generic_write_op(:replace, key, value, ttl, cas, options)
162
+ end
163
+
164
+ def delete(key, cas)
165
+ return super unless async?
166
+
167
+ promised_request(key) do |opaque|
168
+ [REQUEST, OPCODES[:delete], key.bytesize, 0, 0, 0, key.bytesize, opaque, cas, key].pack(FORMAT[:delete])
169
+ end
170
+ end
171
+
172
+ def async_append_prepend_op(op, key, value)
173
+ promised_request(key) do |opaque|
174
+ [REQUEST, OPCODES[op], key.bytesize, 0, 0, 0, value.bytesize + key.bytesize, opaque, 0, key, value].pack(FORMAT[op])
175
+ end
176
+ end
177
+
178
+ def append(key, value)
179
+ return super unless async?
180
+
181
+ async_append_prepend_op(:append, key, value)
182
+ end
183
+
184
+ def prepend(key, value)
185
+ return super unless async?
186
+
187
+ async_append_prepend_op(:prepend, key, value)
188
+ end
189
+
190
+ def flush
191
+ return super unless async?
192
+
193
+ promised_request(nil) do |opaque|
194
+ [REQUEST, OPCODES[:flush], 0, 4, 0, 0, 4, opaque, 0, 0].pack(FORMAT[:flush])
195
+ end
196
+ end
197
+
198
+ def async_decr_incr(opcode, key, count, ttl, default)
199
+ expiry = default ? sanitize_ttl(ttl) : 0xFFFFFFFF
200
+ default ||= 0
201
+ (h, l) = split(count)
202
+ (dh, dl) = split(default)
203
+ promised_request(key) do |opaque|
204
+ req = [REQUEST, OPCODES[opcode], key.bytesize, 20, 0, 0, key.bytesize + 20, opaque, 0, h, l, dh, dl, expiry, key].pack(FORMAT[opcode])
205
+ end
206
+ end
207
+
208
+ def decr(key, count, ttl, default)
209
+ return super unless async?
210
+
211
+ async_decr_incr :decr, key, count, ttl, default
212
+ end
213
+
214
+ def incr(key, count, ttl, default)
215
+ return super unless async?
216
+
217
+ async_decr_incr :incr, key, count, ttl, default
218
+ end
219
+
220
+ def async_buffered_write(data)
221
+ @write_buffer << data
222
+ async_sock_write_nonblock
223
+ end
224
+
225
+ def async_sock_write_nonblock
226
+ remaining = @write_buffer.byteslice(@write_offset, @write_buffer.length)
227
+ begin
228
+ bytes_written = @sock.write_nonblock(remaining, exception: false)
229
+ rescue Errno::EINTR
230
+ retry
231
+ end
232
+
233
+ return if bytes_written == :wait_writable
234
+
235
+ @write_offset += bytes_written
236
+ completed = (@write_offset == @write_buffer.length)
237
+ if completed
238
+ @write_buffer.clear
239
+ @write_offset = 0
240
+ end
241
+ @executor_pool.set_interest(:w, !completed)
242
+ rescue SystemCallError, Timeout::Error => e
243
+ failure!(e)
244
+ end
245
+
246
+ FULL_HEADER = 'CCnCCnNNQ'
247
+
248
+ def read_available
249
+ loop do
250
+ result = @sock.read_nonblock(8196, exception: false)
251
+ if result == :wait_readable
252
+ break
253
+ elsif result == :wait_writable
254
+ break
255
+ elsif result
256
+ @read_buffer << result
257
+ else
258
+ raise Errno::ECONNRESET, "Connection reset: #{safe_options.inspect}"
259
+ end
260
+ end
261
+ end
262
+
263
+ def async_sock_read_nonblock
264
+ read_available
265
+
266
+ buf = @read_buffer
267
+ pos = @read_offset
268
+
269
+ while buf.bytesize - pos >= 24
270
+ header = buf.byteslice(pos, 24)
271
+ (magic, opcode, key_length, extra_length, data_type, status, body_length, opaque, cas) = header.unpack(FULL_HEADER)
272
+
273
+ if buf.bytesize - pos >= 24 + body_length
274
+ exists = (status != 1) # Key not found
275
+ this_pos = pos
276
+
277
+ # key = buf.byteslice(this_pos + 24 + extra_length, key_length)
278
+ value = buf.byteslice(this_pos + 24 + extra_length + key_length, body_length - key_length - extra_length) if exists
279
+
280
+ pos = pos + 24 + body_length
281
+
282
+ promise = @pending_ops.delete(opaque)
283
+ next if promise.nil?
284
+
285
+ begin
286
+ raise Dalli::DalliError, "Response error #{status}: #{Dalli::RESPONSE_CODES[status]}" unless status == 0 || status == 1 || status == 2 || status == 5
287
+
288
+ final_value = nil
289
+ if opcode == OPCODES[:incr] || opcode == OPCODES[:decr]
290
+ final_value = value.unpack1("Q>")
291
+ elsif exists
292
+ flags = if extra_length >= 4
293
+ buf.byteslice(this_pos + 24, 4).unpack1("N")
294
+ else
295
+ 0
296
+ end
297
+ final_value = deserialize(value, flags)
298
+ end
299
+
300
+ response = ::IOPromise::Dalli::Response.new(
301
+ key: promise.key,
302
+ value: final_value,
303
+ exists: exists,
304
+ stored: !(status == 2 || status == 5), # Key exists or Item not stored
305
+ cas: cas,
306
+ )
307
+
308
+ promise.fulfill(response)
309
+ rescue => ex
310
+ promise.reject(ex)
311
+ end
312
+ else
313
+ # not enough data yet, wait for more
314
+ break
315
+ end
316
+ end
317
+
318
+ if pos == @read_buffer.length
319
+ @read_buffer.clear
320
+ @read_offset = 0
321
+ else
322
+ @read_offset = pos
323
+ end
324
+
325
+ rescue SystemCallError, Timeout::Error, EOFError => e
326
+ failure!(e)
327
+ end
328
+
329
+ def failure!(ex)
330
+ if async?
331
+ # all pending operations need to be rejected when a failure occurs
332
+ @pending_ops.each do |op|
333
+ op.reject(ex)
334
+ end
335
+ @pending_ops = {}
336
+ end
337
+
338
+ super
339
+ end
340
+
341
+ # this is guard_max_value from the master version, rather than using the yield block.
342
+ def guard_max_value_with_raise(key, value)
343
+ return if value.bytesize <= @options[:value_max_bytes]
344
+
345
+ message = "Value for #{key} over max size: #{@options[:value_max_bytes]} <= #{value.bytesize}"
346
+ raise Dalli::ValueOverMaxSize, message
347
+ end
348
+ end
349
+ end
350
+ end
351
+
352
+ ::Dalli::Server.prepend(IOPromise::Dalli::AsyncServer)
353
+ ::Dalli::Client.prepend(IOPromise::Dalli::AsyncClient)
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'executor_pool'
4
+
5
+ module IOPromise
6
+ module Dalli
7
+ class DalliPromise < ::IOPromise::Base
8
+ attr_reader :key
9
+
10
+ def initialize(server = nil, key = nil)
11
+ super()
12
+
13
+ # when created from a 'then' call, initialize nothing
14
+ return if server.nil? || key.nil?
15
+
16
+ @server = server
17
+ @key = key
18
+ @start_time = nil
19
+
20
+ ::IOPromise::ExecutorContext.current.register(self)
21
+ end
22
+
23
+ def wait
24
+ unless defined?(@server)
25
+ super
26
+ else
27
+ ::IOPromise::ExecutorContext.current.wait_for_all_data(end_when_complete: self)
28
+ end
29
+ end
30
+
31
+ def execute_pool
32
+ return @pool if defined?(@pool)
33
+ if defined?(@server)
34
+ @pool = DalliExecutorPool.for(@server)
35
+ else
36
+ @pool = nil
37
+ end
38
+ end
39
+
40
+ def in_select_loop
41
+ if @start_time.nil?
42
+ @start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
43
+ end
44
+ end
45
+
46
+ def timeout_remaining
47
+ now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
48
+ elapsed = now - @start_time
49
+ remaining = @server.options[:socket_timeout] - elapsed
50
+ return 0 if remaining < 0
51
+ remaining
52
+ end
53
+
54
+ def timeout?
55
+ return false if @start_time.nil?
56
+ timeout_remaining <= 0
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module IOPromise
4
+ module Dalli
5
+ class Response
6
+ attr_reader :key, :value, :cas
7
+
8
+ def initialize(key:, value:, exists: false, stored: false, cas: nil)
9
+ @key = key
10
+ @value = value
11
+ @exists = exists
12
+ @stored = stored
13
+ @cas = cas
14
+ end
15
+
16
+ def exist?
17
+ @exists
18
+ end
19
+
20
+ def stored?
21
+ @stored
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module IOPromise
4
+ module Dalli
5
+ VERSION = '0.1.0'
6
+ end
7
+ end
metadata ADDED
@@ -0,0 +1,93 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: iopromise-dalli
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Theo Julienne
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-06-18 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: iopromise
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 0.1.3
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 0.1.3
27
+ - !ruby/object:Gem::Dependency
28
+ name: dalli
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - '='
32
+ - !ruby/object:Gem::Version
33
+ version: 2.7.11
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - '='
39
+ - !ruby/object:Gem::Version
40
+ version: 2.7.11
41
+ description: This gem provides a promise-based interface to Dalli (memcached) using
42
+ IOPromise
43
+ email:
44
+ - theo.julienne@gmail.com
45
+ executables: []
46
+ extensions: []
47
+ extra_rdoc_files: []
48
+ files:
49
+ - ".github/workflows/main.yml"
50
+ - ".gitignore"
51
+ - ".rspec"
52
+ - CODE_OF_CONDUCT.md
53
+ - Gemfile
54
+ - Gemfile.lock
55
+ - LICENSE
56
+ - README.md
57
+ - Rakefile
58
+ - bin/console
59
+ - bin/setup
60
+ - iopromise-dalli.gemspec
61
+ - lib/iopromise/dalli.rb
62
+ - lib/iopromise/dalli/client.rb
63
+ - lib/iopromise/dalli/executor_pool.rb
64
+ - lib/iopromise/dalli/patch_dalli.rb
65
+ - lib/iopromise/dalli/promise.rb
66
+ - lib/iopromise/dalli/response.rb
67
+ - lib/iopromise/dalli/version.rb
68
+ homepage: https://github.com/iopromise-ruby/iopromise-dalli
69
+ licenses:
70
+ - MIT
71
+ metadata:
72
+ homepage_uri: https://github.com/iopromise-ruby/iopromise-dalli
73
+ source_code_uri: https://github.com/iopromise-ruby/iopromise-dalli
74
+ post_install_message:
75
+ rdoc_options: []
76
+ require_paths:
77
+ - lib
78
+ required_ruby_version: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: 2.4.0
83
+ required_rubygems_version: !ruby/object:Gem::Requirement
84
+ requirements:
85
+ - - ">="
86
+ - !ruby/object:Gem::Version
87
+ version: '0'
88
+ requirements: []
89
+ rubygems_version: 3.2.9
90
+ signing_key:
91
+ specification_version: 4
92
+ summary: Parallel Dalli support via IOPromise
93
+ test_files: []