maybe_later 0.0.1

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: 97eeed3e9c54c6fc50761b564b2931efb9095256dd204713202f661fd3bae530
4
+ data.tar.gz: c970f7ce158383f37d37e889b2e7eebc6709fb99a2c62fb70aab7f7ea8f6894f
5
+ SHA512:
6
+ metadata.gz: d85dd59825388991863f20945f8ee5b1ee8f9ce133657c0910b0e5adffd61eee9eebb185d33f714f1cb33bf9c04bd70eb02be68ae059fba3ef31480244e3c183
7
+ data.tar.gz: ee4340c11eb2f7da34ea743947ca6f9649a3bf2e44923dd371990e7efc3c092e6dcc84943eb498080bad88f830f26a66c5b84de796f217c458056c1c88c1a9fa
data/.standard.yml ADDED
@@ -0,0 +1,2 @@
1
+ # For available configuration options, see:
2
+ # https://github.com/testdouble/standard
data/CHANGELOG.md ADDED
@@ -0,0 +1,3 @@
1
+ ## [0.0.1] - 2022-01-19
2
+
3
+ - Initial release
data/Gemfile ADDED
@@ -0,0 +1,11 @@
1
+ source "https://rubygems.org"
2
+
3
+ gemspec
4
+
5
+ gem "rake"
6
+ gem "minitest"
7
+ gem "standard"
8
+
9
+ gem "rack"
10
+
11
+ gem "pry"
data/Gemfile.lock ADDED
@@ -0,0 +1,106 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ maybe_later (0.0.1)
5
+ concurrent-ruby (~> 1.1.9)
6
+ railties (>= 6.0.0)
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ actionpack (7.0.1)
12
+ actionview (= 7.0.1)
13
+ activesupport (= 7.0.1)
14
+ rack (~> 2.0, >= 2.2.0)
15
+ rack-test (>= 0.6.3)
16
+ rails-dom-testing (~> 2.0)
17
+ rails-html-sanitizer (~> 1.0, >= 1.2.0)
18
+ actionview (7.0.1)
19
+ activesupport (= 7.0.1)
20
+ builder (~> 3.1)
21
+ erubi (~> 1.4)
22
+ rails-dom-testing (~> 2.0)
23
+ rails-html-sanitizer (~> 1.1, >= 1.2.0)
24
+ activesupport (7.0.1)
25
+ concurrent-ruby (~> 1.0, >= 1.0.2)
26
+ i18n (>= 1.6, < 2)
27
+ minitest (>= 5.1)
28
+ tzinfo (~> 2.0)
29
+ ast (2.4.2)
30
+ builder (3.2.4)
31
+ coderay (1.1.3)
32
+ concurrent-ruby (1.1.9)
33
+ crass (1.0.6)
34
+ erubi (1.10.0)
35
+ i18n (1.8.11)
36
+ concurrent-ruby (~> 1.0)
37
+ loofah (2.13.0)
38
+ crass (~> 1.0.2)
39
+ nokogiri (>= 1.5.9)
40
+ method_source (1.0.0)
41
+ minitest (5.15.0)
42
+ nokogiri (1.13.1-arm64-darwin)
43
+ racc (~> 1.4)
44
+ parallel (1.21.0)
45
+ parser (3.1.0.0)
46
+ ast (~> 2.4.1)
47
+ pry (0.14.1)
48
+ coderay (~> 1.1)
49
+ method_source (~> 1.0)
50
+ racc (1.6.0)
51
+ rack (2.2.3)
52
+ rack-test (1.1.0)
53
+ rack (>= 1.0, < 3)
54
+ rails-dom-testing (2.0.3)
55
+ activesupport (>= 4.2.0)
56
+ nokogiri (>= 1.6)
57
+ rails-html-sanitizer (1.4.2)
58
+ loofah (~> 2.3)
59
+ railties (7.0.1)
60
+ actionpack (= 7.0.1)
61
+ activesupport (= 7.0.1)
62
+ method_source
63
+ rake (>= 12.2)
64
+ thor (~> 1.0)
65
+ zeitwerk (~> 2.5)
66
+ rainbow (3.1.1)
67
+ rake (13.0.6)
68
+ regexp_parser (2.2.0)
69
+ rexml (3.2.5)
70
+ rubocop (1.25.0)
71
+ parallel (~> 1.10)
72
+ parser (>= 3.1.0.0)
73
+ rainbow (>= 2.2.2, < 4.0)
74
+ regexp_parser (>= 1.8, < 3.0)
75
+ rexml
76
+ rubocop-ast (>= 1.15.1, < 2.0)
77
+ ruby-progressbar (~> 1.7)
78
+ unicode-display_width (>= 1.4.0, < 3.0)
79
+ rubocop-ast (1.15.1)
80
+ parser (>= 3.0.1.1)
81
+ rubocop-performance (1.13.2)
82
+ rubocop (>= 1.7.0, < 2.0)
83
+ rubocop-ast (>= 0.4.0)
84
+ ruby-progressbar (1.11.0)
85
+ standard (1.7.0)
86
+ rubocop (= 1.25.0)
87
+ rubocop-performance (= 1.13.2)
88
+ thor (1.2.1)
89
+ tzinfo (2.0.4)
90
+ concurrent-ruby (~> 1.0)
91
+ unicode-display_width (2.1.0)
92
+ zeitwerk (2.5.3)
93
+
94
+ PLATFORMS
95
+ arm64-darwin-21
96
+
97
+ DEPENDENCIES
98
+ maybe_later!
99
+ minitest
100
+ pry
101
+ rack
102
+ rake
103
+ standard
104
+
105
+ BUNDLED WITH
106
+ 2.3.3
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Justin Searls
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,120 @@
1
+ # maybe_later - get slow code out of your users' way
2
+
3
+ Maybe you've been in this situation: you want to call some Ruby while responding
4
+ to an HTTP request, but it's a time-consuming operation, its outcome won't
5
+ impact the response you send, and naively invoking it will result in a slower
6
+ page load or API response for your users.
7
+
8
+ In almost all cases like this, Rubyists will reach for a [job
9
+ queue](https://edgeguides.rubyonrails.org/active_job_basics.html). And that's
10
+ usually the right answer! But for relatively trivial tasks—cases where the
11
+ _only_ reason you want to defer execution is a faster page load—creating a new
12
+ job class and scheduling the work onto a queuing system can feel like overkill.
13
+
14
+ If this resonates with you, the `maybe_later` gem might be the best way to run
15
+ that code for you (eventually).
16
+
17
+ ## Bold Font Disclaimer
18
+
19
+ ⚠️ **If the name `maybe_later` didn't make it clear, this gem does nothing to
20
+ ensure that your after-action callbacks actually run. If the code you're calling
21
+ is very important, use [sidekiq](https://github.com/mperham/sidekiq) or
22
+ something!** ⚠️
23
+
24
+ ## Setup
25
+
26
+ Add the gem to your Gemfile:
27
+
28
+ ```ruby
29
+ gem "maybe_later"
30
+ ```
31
+
32
+ If you're using Rails, the gem's middleware will be registered automatically. If
33
+ you're not using Rails but _are_ using a rack-based server that supports
34
+ [env["rack.after_reply"]](https://github.com/rack/rack/issues/1060) (which
35
+ includes
36
+ [puma](https://github.com/puma/puma/commit/be4a8336c0b4fc911b99d1ffddc4733b6f38d81d)
37
+ and
38
+ [unicorn](https://github.com/defunkt/unicorn/commit/673c15e3f020bccc0336838617875b26c9a45f4e)),
39
+ just add `use MaybeLater::Middleware` to your `config.ru` file.
40
+
41
+ ## Usage
42
+
43
+ Using the gem is pretty straightforward, just pass the code you want to run to
44
+ `MaybeLater.run` as a block:
45
+
46
+ ```ruby
47
+ MaybeLater.run {
48
+ AnalyticsService.send_telemetry!
49
+ }
50
+ ```
51
+
52
+ Each block passed to `MaybeLater.run` will be run after the HTTP response is
53
+ sent and the response will include a `"Connection: close` header.
54
+
55
+ If the code you're calling needs to be executed in the same thread that's
56
+ handling the HTTP request, you can pass `inline: true`:
57
+
58
+ ```ruby
59
+ MaybeLater.run(inline: true) {
60
+ # Thread un-safe code here
61
+ }
62
+ ```
63
+
64
+ And your code will be run right after the HTTP response is sent (note: this can
65
+ potentially saturate the server's available threads and effectively block
66
+ subsequent HTTP requests!)
67
+
68
+
69
+ ## Configuration
70
+
71
+ The gem offers a few configuration options:
72
+
73
+ ```ruby
74
+ MaybeLater.config do |config|
75
+ # Will be called if a `MaybeLater.run {}` callback errors, e.g.:
76
+ config.on_error = ->(error) {
77
+ # e.g. Honeybadger.notify(error)
78
+ }
79
+
80
+ # Will run after each `MaybeLater.run {}` block, even if it errors
81
+ config.after_each = -> {}
82
+
83
+ # By default, tasks will run in a fixed thread pool. To run them in the
84
+ # thread dispatching the HTTP response, set this to true
85
+ config.inline_by_default = false
86
+
87
+ # How many threads to allocate to the fixed thread pool (default: 5)
88
+ config.max_threads = 5
89
+ end
90
+ ```
91
+
92
+ ## Help! Why isn't my code running?
93
+
94
+ If the blocks you pass to `MaybeLater.run` aren't running, possible
95
+ explanations:
96
+
97
+ * Because the blocks passed to `MaybeLater.run` are themselves stored in a
98
+ thread-local array, if you invoke `MaybeLater.run` from a thread that isn't
99
+ handling with a Rack request, the block will never run
100
+ * If your Rack server doesn't support `rack.after_reply`, the blocks will never
101
+ run
102
+ * If the block _is_ running and raising an error, you'll only know about it if
103
+ you register a `MaybeLater.config.on_error` handler
104
+
105
+ ## Acknowledgement
106
+
107
+ The idea for this gem was triggered by [this
108
+ tweet](https://twitter.com/julikt/status/1483585327277223939) in reply to [this
109
+ question](https://twitter.com/searls/status/1483572597686259714). Also, many
110
+ thanks to [Matthew Draper](https://github.com/matthewd) for answering a bunch of
111
+ questions I had while implementing this.
112
+
113
+ ## Code of Conduct
114
+
115
+ This project follows Test Double's [code of
116
+ conduct](https://testdouble.com/code-of-conduct) for all community interactions,
117
+ including (but not limited to) one-on-one communications, public posts/comments,
118
+ code reviews, pull requests, and GitHub issues. If violations occur, Test Double
119
+ will take any action they deem appropriate for the infraction, up to and
120
+ including blocking a user from the organization's repositories.
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << "test"
6
+ t.libs << "lib"
7
+ t.test_files = FileList["test/**/*_test.rb"]
8
+ end
9
+
10
+ require "standard/rake"
11
+
12
+ task default: %i[test standard]
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 "maybe_later"
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,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
@@ -0,0 +1,12 @@
1
+ module MaybeLater
2
+ class Config
3
+ attr_accessor :after_each, :on_error, :inline_by_default, :max_threads
4
+
5
+ def initialize
6
+ @after_each = nil
7
+ @on_error = nil
8
+ @inline_by_default = false
9
+ @max_threads = 5
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,21 @@
1
+ module MaybeLater
2
+ class Middleware
3
+ RACK_AFTER_REPLY = "rack.after_reply"
4
+
5
+ def initialize(app)
6
+ @app = app
7
+ end
8
+
9
+ def call(env)
10
+ status, headers, body = @app.call(env)
11
+ if Store.instance.any_callbacks?
12
+ env[RACK_AFTER_REPLY] ||= []
13
+ env[RACK_AFTER_REPLY] << -> {
14
+ RunsCallbacks.new.call
15
+ }
16
+ headers["Connection"] = "close"
17
+ end
18
+ [status, headers, body]
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,15 @@
1
+ module MaybeLater
2
+ Callback = Struct.new(:inline, :callable, keyword_init: true)
3
+
4
+ class QueuesCallback
5
+ def call(callable:, inline:)
6
+ raise Error.new("No block was passed to MaybeLater.run") if callable.nil?
7
+
8
+ inline = MaybeLater.config.inline_by_default if inline.nil?
9
+ Store.instance.add_callback(Callback.new(
10
+ inline: inline,
11
+ callable: callable
12
+ ))
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,7 @@
1
+ module MaybeLater
2
+ class Railtie < ::Rails::Railtie
3
+ initializer "maybe_later.middleware" do
4
+ config.app_middleware.use Middleware
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,22 @@
1
+ module MaybeLater
2
+ class RunsCallbacks
3
+ def call
4
+ store = Store.instance
5
+ config = MaybeLater.config
6
+
7
+ store.callbacks.each do |callback|
8
+ if callback.inline
9
+ callback.callable.call
10
+ else
11
+ ThreadPool.instance.run(callback.callable)
12
+ end
13
+ rescue => e
14
+ config.on_error&.call(e)
15
+ ensure
16
+ config.after_each&.call
17
+ end
18
+
19
+ store.clear_callbacks!
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,24 @@
1
+ module MaybeLater
2
+ class Store
3
+ def self.instance
4
+ Thread.current[:maybe_later_store] ||= new
5
+ end
6
+
7
+ attr_reader :callbacks
8
+ def initialize
9
+ @callbacks = []
10
+ end
11
+
12
+ def any_callbacks?
13
+ !@callbacks.empty?
14
+ end
15
+
16
+ def add_callback(callable)
17
+ @callbacks << callable
18
+ end
19
+
20
+ def clear_callbacks!
21
+ @callbacks = []
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,22 @@
1
+ module MaybeLater
2
+ class ThreadPool
3
+ def self.instance
4
+ @instance ||= new
5
+ end
6
+
7
+ # The only time this is invoked by the gem will be when an Async task runs
8
+ # As a result, the max thread config will be locked after responding to the
9
+ # first relevant request, since the pool will have been created
10
+ def initialize
11
+ @pool = Concurrent::FixedThreadPool.new(MaybeLater.config.max_threads)
12
+ end
13
+
14
+ def run(callable)
15
+ @pool.post do
16
+ callable.call
17
+ rescue => e
18
+ MaybeLater.config.on_error&.call(e)
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,3 @@
1
+ module MaybeLater
2
+ VERSION = "0.0.1"
3
+ end
@@ -0,0 +1,22 @@
1
+ require_relative "maybe_later/version"
2
+ require_relative "maybe_later/config"
3
+ require_relative "maybe_later/middleware"
4
+ require_relative "maybe_later/queues_callback"
5
+ require_relative "maybe_later/runs_callbacks"
6
+ require_relative "maybe_later/store"
7
+ require_relative "maybe_later/thread_pool"
8
+ require_relative "maybe_later/railtie" if defined?(Rails)
9
+
10
+ module MaybeLater
11
+ class Error < StandardError; end
12
+
13
+ def self.run(inline: nil, &blk)
14
+ QueuesCallback.new.call(callable: blk, inline: inline)
15
+ end
16
+
17
+ def self.config(&blk)
18
+ (@config ||= Config.new).tap { |config|
19
+ blk&.call(config)
20
+ }
21
+ end
22
+ end
@@ -0,0 +1,32 @@
1
+ require_relative "lib/maybe_later/version"
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = "maybe_later"
5
+ spec.version = MaybeLater::VERSION
6
+ spec.authors = ["Justin Searls"]
7
+ spec.email = ["searls@gmail.com"]
8
+
9
+ spec.summary = "Run code after the current Rack response or Rails action completes"
10
+ spec.homepage = "https://github.com/testdouble/maybe_later"
11
+ spec.license = "MIT"
12
+ spec.required_ruby_version = ">= 3.0.0"
13
+
14
+ spec.metadata["homepage_uri"] = spec.homepage
15
+ spec.metadata["source_code_uri"] = spec.homepage
16
+ spec.metadata["changelog_uri"] = "#{spec.homepage}/blob/main/CHANGELOG.md"
17
+
18
+ # Specify which files should be added to the gem when it is released.
19
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
20
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
21
+ `git ls-files -z`.split("\x0").reject do |f|
22
+ (f == __FILE__) || f.match(%r{\A(?:(?:test|spec|features)/|\.(?:git|travis|circleci)|appveyor)})
23
+ end
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
+ # Uncomment to register a new dependency of your gem
30
+ spec.add_dependency "railties", ">= 6.0.0"
31
+ spec.add_dependency "concurrent-ruby", "~> 1.1.9"
32
+ end
@@ -0,0 +1,4 @@
1
+ module MaybeLater
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,94 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: maybe_later
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Justin Searls
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2022-01-20 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: railties
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: 6.0.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: 6.0.0
27
+ - !ruby/object:Gem::Dependency
28
+ name: concurrent-ruby
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: 1.1.9
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: 1.1.9
41
+ description:
42
+ email:
43
+ - searls@gmail.com
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files: []
47
+ files:
48
+ - ".standard.yml"
49
+ - CHANGELOG.md
50
+ - Gemfile
51
+ - Gemfile.lock
52
+ - LICENSE.txt
53
+ - README.md
54
+ - Rakefile
55
+ - bin/console
56
+ - bin/setup
57
+ - lib/maybe_later.rb
58
+ - lib/maybe_later/config.rb
59
+ - lib/maybe_later/middleware.rb
60
+ - lib/maybe_later/queues_callback.rb
61
+ - lib/maybe_later/railtie.rb
62
+ - lib/maybe_later/runs_callbacks.rb
63
+ - lib/maybe_later/store.rb
64
+ - lib/maybe_later/thread_pool.rb
65
+ - lib/maybe_later/version.rb
66
+ - maybe_later.gemspec
67
+ - sig/maybe_later.rbs
68
+ homepage: https://github.com/testdouble/maybe_later
69
+ licenses:
70
+ - MIT
71
+ metadata:
72
+ homepage_uri: https://github.com/testdouble/maybe_later
73
+ source_code_uri: https://github.com/testdouble/maybe_later
74
+ changelog_uri: https://github.com/testdouble/maybe_later/blob/main/CHANGELOG.md
75
+ post_install_message:
76
+ rdoc_options: []
77
+ require_paths:
78
+ - lib
79
+ required_ruby_version: !ruby/object:Gem::Requirement
80
+ requirements:
81
+ - - ">="
82
+ - !ruby/object:Gem::Version
83
+ version: 3.0.0
84
+ required_rubygems_version: !ruby/object:Gem::Requirement
85
+ requirements:
86
+ - - ">="
87
+ - !ruby/object:Gem::Version
88
+ version: '0'
89
+ requirements: []
90
+ rubygems_version: 3.3.3
91
+ signing_key:
92
+ specification_version: 4
93
+ summary: Run code after the current Rack response or Rails action completes
94
+ test_files: []