anway 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/lib/anway/testing.rb CHANGED
@@ -5,15 +5,17 @@ require 'anway'
5
5
  module Anway
6
6
  # Test modes for apps. No server is necessary.
7
7
  #
8
- # Anway::Testing.fake! keeps pushed jobs in a list
9
- # Anway::Testing.inline! runs each job at push
8
+ # Anway::Testing.fake! keeps pushed jobs and published events in lists
9
+ # Anway::Testing.inline! runs each job at push, and each event in the
10
+ # subscribed classes of the app at publish
10
11
  # Anway::Testing.disable! uses the real client
11
12
  module Testing
12
13
  @mode = nil
13
14
  @jobs = []
15
+ @events = []
14
16
 
15
17
  class << self
16
- attr_reader :jobs, :mode
18
+ attr_reader :jobs, :events, :mode
17
19
 
18
20
  def fake!
19
21
  @mode = :fake
@@ -29,6 +31,7 @@ module Anway
29
31
 
30
32
  def clear
31
33
  @jobs.clear
34
+ @events.clear
32
35
  end
33
36
 
34
37
  def enqueue(job)
@@ -39,10 +42,36 @@ module Anway
39
42
  job.jid
40
43
  end
41
44
 
45
+ # Keeps the event as the PUBLISH payload, with string keys. jobs is the
46
+ # number of subscriptions in the job classes of the app. There is no
47
+ # duplicate check.
48
+ def publish(topic, args = [], id: nil, unique_for: nil, custom: nil)
49
+ event = { 'topic' => topic, 'args' => args, 'id' => id, 'unique_for' => unique_for, 'custom' => custom }
50
+ copy = JSON.parse(JSON.generate(event.compact))
51
+
52
+ event_id = id || "evt-#{SecureRandom.hex(12)}"
53
+ subscriptions = Worker.subscriptions.select { |subscription| subscription.topic == topic.to_s }
54
+
55
+ @events << copy
56
+
57
+ subscriptions.each { |subscription| Executor.call(event_job(subscription, copy, event_id)) } if @mode == :inline
58
+
59
+ Client::Published.new(event: event_id, jobs: subscriptions.size, duplicate: false)
60
+ end
61
+
42
62
  # Runs and removes all fake jobs. Jobs that they push also run.
43
63
  def drain
44
64
  Executor.call(@jobs.shift) until @jobs.empty?
45
65
  end
66
+
67
+ private
68
+
69
+ # The copy that the server makes for one subscription.
70
+ def event_job(subscription, event, event_id)
71
+ custom = (event['custom'] || {}).merge('topic' => subscription.topic, 'event' => event_id)
72
+
73
+ Job.new(subscription.jobtype, event['args'], queue: subscription.queue, custom: custom)
74
+ end
46
75
  end
47
76
  end
48
77
  end
data/lib/anway/version.rb CHANGED
@@ -1,5 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Anway
4
- VERSION = '0.1.1'
4
+ VERSION = '0.3.0'
5
+
6
+ # The anway server that the platform gems carry, and that CI tests against.
7
+ SERVER_VERSION = '0.3.1'
5
8
  end
data/lib/anway/web.rb ADDED
@@ -0,0 +1,104 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'net/http'
4
+ require 'uri'
5
+
6
+ module Anway
7
+ # Web serves the Anway console inside a Rack app, such as Rails:
8
+ #
9
+ # authenticate :user, ->(user) { user.admin? } do
10
+ # mount Anway::Web => '/anway'
11
+ # end
12
+ #
13
+ # It proxies to the console process, which bin/anway starts when
14
+ # config/anway.yml sets console.path. The console gets the mount path in
15
+ # X-Forwarded-Prefix, and the browser host, so its links, redirects, and
16
+ # CSRF check work under the path. Cookies and Authorization stay in the app.
17
+ class Web
18
+ METHODS = %w[GET HEAD POST].freeze
19
+ DROPPED = %w[connection keep-alive proxy-authenticate proxy-authorization te trailer transfer-encoding upgrade content-length].freeze
20
+ PRIVATE = %w[HTTP_COOKIE HTTP_AUTHORIZATION HTTP_HOST HTTP_VERSION HTTP_CONNECTION].freeze
21
+
22
+ def self.call(env)
23
+ new.call(env)
24
+ end
25
+
26
+ def initialize(target = nil)
27
+ @target = target
28
+ end
29
+
30
+ def call(env)
31
+ return [405, { 'content-type' => 'text/plain', 'allow' => METHODS.join(', ') }, ['Method not allowed']] unless METHODS.include?(env['REQUEST_METHOD'])
32
+
33
+ response = forward(env)
34
+ headers = {}
35
+
36
+ response.each_header { |name, value| headers[name] = value unless DROPPED.include?(name) }
37
+
38
+ [response.code.to_i, headers, [response.body.to_s]]
39
+ rescue SystemCallError, IOError, Net::OpenTimeout, Net::ReadTimeout, SocketError
40
+ [502, { 'content-type' => 'text/html; charset=utf-8' }, [unavailable]]
41
+ end
42
+
43
+ private
44
+
45
+ def target
46
+ URI(@target || Anway.config.console_url || Settings.load.console_url)
47
+ end
48
+
49
+ def forward(env)
50
+ base = target
51
+ path = env['PATH_INFO'].to_s
52
+ path = '/' if path.empty?
53
+ query = env['QUERY_STRING'].to_s
54
+ request = Net::HTTPGenericRequest.new(env['REQUEST_METHOD'], env['REQUEST_METHOD'] == 'POST', env['REQUEST_METHOD'] != 'HEAD', query.empty? ? path : "#{path}?#{query}")
55
+
56
+ copy_headers(env, request)
57
+
58
+ if env['REQUEST_METHOD'] == 'POST'
59
+ request.body = body_of(env)
60
+ request['content-type'] = env['CONTENT_TYPE'] if env['CONTENT_TYPE']
61
+ end
62
+
63
+ Net::HTTP.start(base.host, base.port, open_timeout: 2, read_timeout: 30) { |http| http.request(request) }
64
+ end
65
+
66
+ # Rails reads a form post before the mount, in Rack::MethodOverride, so
67
+ # the input is at its end. It rewinds the input, and uses the raw form that
68
+ # Rack keeps when the input cannot rewind.
69
+ def body_of(env)
70
+ input = env['rack.input']
71
+
72
+ input.rewind if input.respond_to?(:rewind)
73
+
74
+ body = input&.read.to_s
75
+
76
+ body.empty? ? env['rack.request.form_vars'].to_s : body
77
+ end
78
+
79
+ def copy_headers(env, request)
80
+ env.each do |key, value|
81
+ next unless key.start_with?('HTTP_') && !PRIVATE.include?(key)
82
+
83
+ request[key.delete_prefix('HTTP_').split('_').map(&:capitalize).join('-')] = value
84
+ end
85
+
86
+ request['host'] = env['HTTP_HOST'] || "#{env['SERVER_NAME']}:#{env['SERVER_PORT']}"
87
+ request['x-forwarded-prefix'] = env['SCRIPT_NAME'].to_s
88
+ request['x-forwarded-proto'] = env['rack.url_scheme'].to_s
89
+ request['accept-encoding'] = 'identity'
90
+ end
91
+
92
+ def unavailable
93
+ <<~HTML
94
+ <!doctype html>
95
+ <title>Anway console</title>
96
+ <div style="font-family:system-ui,sans-serif;max-width:560px;margin:15vh auto;padding:0 16px;line-height:1.5">
97
+ <h1 style="font-size:20px">The Anway console is not running</h1>
98
+ <p>Set <code>console.path</code> in <code>config/anway.yml</code> to the console binary. Then <code>bin/anway</code>, or Puma with <code>plugin :anway</code>, starts it next to the server.</p>
99
+ <p>To run it apart, use <code>bin/anway console</code>, and set <code>console.bind</code> to its address.</p>
100
+ </div>
101
+ HTML
102
+ end
103
+ end
104
+ end
data/lib/anway/worker.rb CHANGED
@@ -12,8 +12,23 @@ module Anway
12
12
  # end
13
13
  #
14
14
  # WelcomeJob.perform_async(42)
15
+ #
16
+ # A class can also run the events of a topic:
17
+ #
18
+ # class BroadcastMessage
19
+ # include Anway::Worker
20
+ #
21
+ # subscribe 'chat.message', queue: 'realtime'
22
+ #
23
+ # def perform(message); end
24
+ # end
15
25
  module Worker
16
26
  DEFAULT_BACKTRACE = 30
27
+ SUBSCRIBE_OPTIONS = %i[retry reserve_for].freeze
28
+
29
+ # One topic, queue, and job type. retry and reserve_for are the options of
30
+ # each copy.
31
+ Subscription = Data.define(:topic, :queue, :jobtype, :retry, :reserve_for)
17
32
 
18
33
  @registry = {}
19
34
  @lock = Mutex.new
@@ -36,6 +51,12 @@ module Anway
36
51
  @lock.synchronize { @registry.values }
37
52
  end
38
53
 
54
+ # The subscriptions of all registered classes. A worker sends them with
55
+ # SUBSCRIBE when it starts.
56
+ def subscriptions
57
+ classes.flat_map(&:subscriptions).uniq
58
+ end
59
+
39
60
  # Only registered classes run. The job type comes from the network, so it
40
61
  # never becomes a constant lookup. The lookup by the class name below
41
62
  # uses a registered name, and returns the newest class after a reload.
@@ -83,6 +104,35 @@ module Anway
83
104
  inherited_options.merge(@job_options || {})
84
105
  end
85
106
 
107
+ # Runs each event of the topic in this class. The job type is the job
108
+ # type of the class. queue, retry, and reserve_for have the job_options
109
+ # of the class as defaults, read when the worker starts. A subclass does
110
+ # not get the subscriptions of its parent.
111
+ def subscribe(topic, queue: nil, **options)
112
+ unknown = options.keys - SUBSCRIBE_OPTIONS
113
+
114
+ raise ArgumentError, "unknown subscribe options: #{unknown.join(', ')}" if unknown.any?
115
+
116
+ entry = { topic: topic.to_s, queue: queue&.to_s, **options }
117
+
118
+ @subscriptions ||= []
119
+ @subscriptions << entry unless @subscriptions.include?(entry)
120
+ end
121
+
122
+ def subscriptions
123
+ defaults = job_options
124
+
125
+ (@subscriptions || []).map do |entry|
126
+ Subscription.new(
127
+ topic: entry[:topic],
128
+ queue: entry[:queue] || defaults[:queue]&.to_s || 'default',
129
+ jobtype: job_type,
130
+ retry: entry.fetch(:retry, defaults[:retry]),
131
+ reserve_for: entry.fetch(:reserve_for, defaults[:reserve_for])
132
+ )
133
+ end
134
+ end
135
+
86
136
  def perform_async(*args)
87
137
  enqueue_with(args, {})
88
138
  end
data/lib/anway.rb CHANGED
@@ -11,6 +11,12 @@ require_relative 'anway/worker'
11
11
  require_relative 'anway/executor'
12
12
  require_relative 'anway/queues'
13
13
  require_relative 'anway/runner'
14
+ require_relative 'anway/settings'
15
+ require_relative 'anway/daemon'
16
+ require_relative 'anway/server'
17
+ require_relative 'anway/console'
18
+ require_relative 'anway/web'
19
+ require_relative 'anway/puma/plugin'
14
20
  require_relative 'anway/railtie' if defined?(Rails::Railtie)
15
21
 
16
22
  module Anway
@@ -49,6 +55,23 @@ module Anway
49
55
  job.jid
50
56
  end
51
57
 
58
+ # Sends one event to each subscription of the topic. Returns a
59
+ # Client::Published. Inside a database transaction, the publish waits for
60
+ # the commit and returns nil.
61
+ def publish(topic, args = [], **options)
62
+ Job.validate_args!(args)
63
+
64
+ testing = const_defined?(:Testing) ? Testing : nil
65
+
66
+ return testing.publish(topic, args, **options) if testing&.mode
67
+
68
+ published = nil
69
+
70
+ config.push_wrapper.call { published = client.publish(topic, args, **options) }
71
+
72
+ published
73
+ end
74
+
52
75
  def reset!
53
76
  @lock.synchronize do
54
77
  @client&.close
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rails/generators'
4
+
5
+ module Anway
6
+ module Generators
7
+ # bin/rails generate anway:install [--active-job]
8
+ class InstallGenerator < Rails::Generators::Base
9
+ PUMA_LINE = 'plugin :anway'
10
+
11
+ source_root File.expand_path('templates', __dir__)
12
+
13
+ class_option :active_job, type: :boolean, default: false, desc: 'Use Anway as the Active Job adapter'
14
+
15
+ def create_settings
16
+ copy_file 'anway.yml', 'config/anway.yml'
17
+ end
18
+
19
+ def create_binstub
20
+ copy_file 'anway', 'bin/anway'
21
+ chmod 'bin/anway', 0o755
22
+ end
23
+
24
+ def add_puma_plugin
25
+ path = File.join(destination_root, 'config/puma.rb')
26
+
27
+ return unless File.exist?(path)
28
+ return if File.read(path).include?(PUMA_LINE)
29
+
30
+ append_to_file 'config/puma.rb', <<~RUBY
31
+
32
+ # Runs Anway next to Puma: the embedded server and the workers. ANWAY_IN_PUMA
33
+ # turns it on or off. Without it, it runs only in development.
34
+ #{PUMA_LINE}
35
+ RUBY
36
+ end
37
+
38
+ # The mount stays a comment: it needs a console binary, and the app must
39
+ # choose who can open it.
40
+ def add_console_route
41
+ path = File.join(destination_root, 'config/routes.rb')
42
+
43
+ return unless File.exist?(path)
44
+ return if File.read(path).include?('Anway::Web')
45
+
46
+ route <<~RUBY.chomp
47
+ # The Anway console. It needs console.path in config/anway.yml. Limit it to admins:
48
+ # authenticate :user, ->(user) { user.admin? } do
49
+ # mount Anway::Web => "/anway"
50
+ # end
51
+ RUBY
52
+ end
53
+
54
+ def set_active_job_adapter
55
+ return unless options[:active_job]
56
+
57
+ application 'config.active_job.queue_adapter = :anway'
58
+ end
59
+
60
+ def show_next_steps
61
+ say <<~TEXT
62
+
63
+ Anway is installed.
64
+
65
+ bin/dev Puma starts the Anway server and workers in development
66
+ bin/anway the server and workers, without Puma
67
+ bin/anway worker only workers, for a server that runs apart
68
+
69
+ Jobs: include Anway::Worker in a class#{options[:active_job] ? ', or use Active Job' : ', or run the generator with --active-job'}.
70
+ TEXT
71
+ end
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ # bin/anway the embedded server, when config/anway.yml has no url, and workers
5
+ # bin/anway server only the server
6
+ # bin/anway worker only workers
7
+ Dir.chdir(File.expand_path('..', __dir__))
8
+
9
+ require_relative '../config/boot'
10
+ require 'anway/cli'
11
+
12
+ exit Anway::CLI.new(ARGV).run
@@ -0,0 +1,32 @@
1
+ # Anway settings. Keys at the top apply to every environment, and an
2
+ # environment section overrides them.
3
+ #
4
+ # Without url, this app runs the Anway server itself (embedded), with its
5
+ # data in storage/anway. Set url, or ANWAY_URL, to use a server that runs
6
+ # apart. On more than one host, run one server and set ANWAY_URL everywhere.
7
+
8
+ queues: [default]
9
+ concurrency: 10
10
+
11
+ # The console shows each worker as hostname:pid with a tag. The tag is the
12
+ # app folder by default. ANWAY_HOSTNAME and ANWAY_TAG override these.
13
+ # hostname: worker.1
14
+ # tag: my_app
15
+
16
+ # Autoscale adds threads while jobs wait, up to max, and removes them when
17
+ # the load drops. Keep max at or below the database pool of the worker.
18
+ # autoscale:
19
+ # max: 20
20
+
21
+ # The web console. bin/anway starts it next to the server, and
22
+ # `mount Anway::Web` in config/routes.rb serves it in the app.
23
+ # console:
24
+ # path: /path/to/anway-webui
25
+
26
+ production:
27
+ # url: <%= ENV["ANWAY_URL"] %>
28
+ #
29
+ # To accept workers from other hosts on the embedded server:
30
+ # server:
31
+ # bind: 0.0.0.0:7419
32
+ # password: <%= ENV["ANWAY_PASSWORD"] %>
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'puma/plugin'
4
+ require 'anway'
5
+ require 'anway/puma/plugin'
6
+
7
+ # `plugin :anway` in config/puma.rb runs bin/anway next to Puma, as
8
+ # config/anway.yml says: the embedded server and the workers, or only the
9
+ # workers. ANWAY_IN_PUMA turns it on or off. Without it, it runs only in
10
+ # development. When anway stops by itself, Puma stops too, so a broken worker
11
+ # is not hidden.
12
+ Puma::Plugin.create do
13
+ def start(launcher)
14
+ @launcher = launcher
15
+
16
+ return unless Anway::Puma::Plugin.enabled?
17
+
18
+ events = launcher.events
19
+
20
+ if events.respond_to?(:after_booted)
21
+ events.after_booted { start_anway }
22
+ events.after_stopped { stop_anway }
23
+ events.before_restart { stop_anway }
24
+ else
25
+ events.on_booted { start_anway }
26
+ events.on_stopped { stop_anway }
27
+ events.on_restart { stop_anway }
28
+ end
29
+ end
30
+
31
+ private
32
+
33
+ def start_anway
34
+ @stopping = false
35
+ @pid = Process.spawn(*Anway::Puma::Plugin.command)
36
+
37
+ @monitor = Thread.new(@pid) do |pid|
38
+ _, status = Process.wait2(pid)
39
+
40
+ unless @stopping
41
+ log("anway stopped with #{status}, so Puma stops")
42
+ @launcher.stop
43
+ end
44
+ end
45
+
46
+ log("anway started with pid #{@pid}")
47
+ end
48
+
49
+ def stop_anway
50
+ return unless @pid
51
+
52
+ @stopping = true
53
+
54
+ Process.kill('TERM', @pid)
55
+
56
+ Process.kill('KILL', @pid) unless @monitor.join(Anway::Server::STOP_TIMEOUT + 5)
57
+ @monitor.join(5)
58
+ rescue Errno::ESRCH
59
+ nil
60
+ ensure
61
+ @pid = nil
62
+ end
63
+
64
+ def log(message)
65
+ writer = @launcher.respond_to?(:log_writer) ? @launcher.log_writer : @launcher.events
66
+
67
+ writer.log("* #{message}")
68
+ end
69
+ end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: anway
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.1
4
+ version: 0.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Thadeu
@@ -37,16 +37,26 @@ files:
37
37
  - lib/anway/client.rb
38
38
  - lib/anway/configuration.rb
39
39
  - lib/anway/connection.rb
40
+ - lib/anway/console.rb
41
+ - lib/anway/daemon.rb
40
42
  - lib/anway/errors.rb
41
43
  - lib/anway/executor.rb
42
44
  - lib/anway/job.rb
43
45
  - lib/anway/pool.rb
46
+ - lib/anway/puma/plugin.rb
44
47
  - lib/anway/queues.rb
45
48
  - lib/anway/railtie.rb
46
49
  - lib/anway/runner.rb
50
+ - lib/anway/server.rb
51
+ - lib/anway/settings.rb
47
52
  - lib/anway/testing.rb
48
53
  - lib/anway/version.rb
54
+ - lib/anway/web.rb
49
55
  - lib/anway/worker.rb
56
+ - lib/generators/anway/install/install_generator.rb
57
+ - lib/generators/anway/install/templates/anway
58
+ - lib/generators/anway/install/templates/anway.yml
59
+ - lib/puma/plugin/anway.rb
50
60
  homepage: https://github.com/thadeu/anway-ruby
51
61
  licenses:
52
62
  - MIT