cosmonauts 0.1.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 54700678b007fd3f607a4572749a5d9bac998b0f4d5ace9f2a72f5e19dbe41c4
4
+ data.tar.gz: a9f158bdcec30f9e01a8296b4b6c26f4030b51ebc0e330b1a6db18495ce8ed8f
5
+ SHA512:
6
+ metadata.gz: 25811708dd72f75f930dafad246a9242ba3208b03cf28ff6abb49830b6ce529a7439dc05440c744a43ac04938690599bdf5b87ca3a8b664f12bf3b5fef41028d
7
+ data.tar.gz: 4f1385fe59157d28c1e4fc420ca61ef51a2811395d92b828b26dc8ea569ce23d87c57ceb8b808df9e1897360b1aa2bd17fb825dfb7398b649d21a03680d373b2
data/LICENSE.txt ADDED
@@ -0,0 +1,169 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
166
+
167
+ Copyright (c) BitsBeam LLC
168
+
169
+ https://www.gnu.org/licenses/lgpl-3.0.txt
data/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # Cosmo
2
+
3
+ Background jobs processing for Ruby
data/lib/cosmo/cli.rb ADDED
@@ -0,0 +1,121 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "yaml"
4
+ require "optparse"
5
+
6
+ module Cosmo
7
+ class CLI
8
+ def self.run
9
+ new.run
10
+ end
11
+
12
+ def run
13
+ options = parse
14
+ load_config(options)
15
+ puts self.class.banner
16
+ create_streams
17
+ run_processor
18
+ end
19
+
20
+ private
21
+
22
+ def parse
23
+ options = {}
24
+ parser = option_parser(options)
25
+ parser.parse!(ARGV.dup)
26
+ options
27
+ end
28
+
29
+ def load_config(options)
30
+ Config.load_config(options[:config_file])
31
+ end
32
+
33
+ def create_streams
34
+ Config.instance[:streams].each do |name, config|
35
+ Client.instance.maybe_create_stream(name, config)
36
+ end
37
+ end
38
+
39
+ def run_processor
40
+ Processor.run
41
+ end
42
+
43
+ def option_parser(options)
44
+ parser = OptionParser.new do |o|
45
+ o.on "-c", "--concurrency INT", "Threads to use" do |arg|
46
+ options[:concurrency] = Integer(arg)
47
+ end
48
+
49
+ o.on "-t", "--timeout NUM", "Shutdown timeout" do |arg|
50
+ options[:timeout] = Integer(arg)
51
+ end
52
+
53
+ o.on "-C", "--config PATH", "Path to config file" do |arg|
54
+ options[:config_file] = arg
55
+ end
56
+
57
+ o.on "-s", "--setup", "Load config, create streams and exit" do
58
+ load_config(options)
59
+ create_streams
60
+ puts "Cosmo streams were created/updated"
61
+ exit(0)
62
+ end
63
+
64
+ o.on "-v", "--version", "Print version and exit" do
65
+ puts "Cosmo #{VERSION}"
66
+ exit(0)
67
+ end
68
+ end
69
+
70
+ parser.banner = "cosmo [options]"
71
+ parser.on_tail "-h", "--help", "Show help" do
72
+ puts parser
73
+ exit(1)
74
+ end
75
+
76
+ parser
77
+ end
78
+
79
+ # rubocop:disable Layout/TrailingWhitespace,Lint/IneffectiveAccessModifier
80
+ def self.banner
81
+ <<-TEXT
82
+ .#%+:
83
+ ==-. +.
84
+ +: .::::. :*-
85
+ .=%%%%%%%%%%%%%#-
86
+ .#%%%%%%%%##*+===+*#%%:
87
+ :##%%%%#: :-::...::::. -%.
88
+ +%%%** :. :+. -=.%: -
89
+ *%%%%: .-%%%# ++ ---%. -= :==-
90
+ :%%%- *%%%% *- %:#+ =%%%. .====:
91
+ .%@%+.##. #%%: -+ =-=- *%%: . :=
92
+ =*%%%=-#. :: =-: *%-%%%%%#
93
+ .%=##* #- %. :%%-+++%%%:
94
+ +=*+= +%. .*. .=+.%%-#%%#*+:
95
+ ===: =*%= .*+ *%+%%% -%*:%%%%%: .
96
+ =***%*. .:#*: .%%*+%%%#.+%+. . =
97
+ -%#-: -*########+ .: +%%%=%%%*++:
98
+ .##:---. :%%- *: +%%%%%%%%%%%##. -#%%*= =-
99
+ *#:-: :%%%%+%%= --%%#. -#%%%%+=#- =: .::::::::::::::
100
+ :#- =%%%%%%%+++. +*%=-%%%%#-.. ..:::::::::::::..
101
+ +***+:=***:: ==:. ....::..
102
+ -%%%%%+%%- .... . +##%%= .#%%%%%%%#.
103
+ .%%%%##=%%- :+#%%%#. *%%%%+ -%%%%%= .%%%%%%%%%%%
104
+ -+-- -=#%#+: +%%%%%%%#. *%%%%%+ #%%%%%= =%%%* %%%%.
105
+ .-+###. *%%%%%%%%+ -%%%%+. *%%%%%%:*%%%%%%+ -%%%* %%%%.
106
+ .*%%%%%%% %%%%+.=%%%# =%%%%- *%%%%%%%%%%*%%%+ -%%%* %%%%.
107
+ =%%%%%#=:. :%%%# .%%%# #%%%%%%%: +%%%-*%%%%:=%%%+ -%%%* %%%%.
108
+ -%%%%- .%%%# %%%% .#%%%%%= +%%%- #%%= -%%%+ -%%%* .%%%%.
109
+ *%%%# .%%%#. %%%% +%%%* +%%%- -%%%+ #%%%###%%%*
110
+ %%%%* %%%#. #%%%..****#####- =###- -###+ =######*.
111
+ #%%%# #%%%*+*#%%* .########: =#*=:
112
+ +%%%%- .=+ .########= :----. .:::--====++++********###
113
+ .#%#########: :==-: ..:--=====---::::..
114
+ .########+. .:--=--::.
115
+ :--. .---:.
116
+ :.
117
+ TEXT
118
+ end
119
+ # rubocop:enable Layout/TrailingWhitespace,Lint/IneffectiveAccessModifier
120
+ end
121
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "nats/client"
4
+
5
+ module Cosmo
6
+ class Client
7
+ NATS_URL = ENV.fetch("NATS_URL", "nats://localhost:4222")
8
+
9
+ def self.instance
10
+ @instance ||= Client.new
11
+ end
12
+
13
+ attr_reader :client, :stream
14
+
15
+ def initialize(nats_url: NATS_URL)
16
+ @client = NATS.connect(nats_url)
17
+ @stream = @client.jetstream
18
+ end
19
+
20
+ def publish_message(message)
21
+ subject, payload, params = message.to_args
22
+ publish(subject, payload, **params)
23
+ message.jid
24
+ end
25
+
26
+ def publish(subject, payload, **params)
27
+ @stream.publish(subject, payload, **params)
28
+ end
29
+
30
+ def maybe_create_stream(name, config)
31
+ @stream.stream_info(name)
32
+ rescue NATS::JetStream::Error::NotFound
33
+ @stream.add_stream(name: name, **config)
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "yaml"
4
+ require "forwardable"
5
+
6
+ module Cosmo
7
+ class Config
8
+ extend Forwardable
9
+
10
+ class << self
11
+ extend Forwardable
12
+
13
+ delegate %i[[] fetch key? dig] => :instance
14
+ end
15
+
16
+ def self.load_config(path = nil)
17
+ raise ConfigNotFoundError, path if path && !File.exist?(path)
18
+
19
+ unless path
20
+ default_path = File.expand_path("config/cosmo.yml")
21
+ path = default_path if File.exist?(default_path)
22
+ end
23
+ return unless path
24
+
25
+ config = parse_file(path)
26
+ instance.merge!(config)
27
+ end
28
+
29
+ def self.parse_file(path)
30
+ YAML.load_file(path, aliases: true).tap { normalize!(_1) }
31
+ end
32
+
33
+ def self.normalize!(config)
34
+ Utils::Hash.symbolize_keys!(config)
35
+ config[:streams].each_key do |name|
36
+ c = config[:streams][name]
37
+ c[:max_age] = c[:max_age].to_i * 1_000_000_000 if c[:max_age]
38
+ c[:duplicate_window] = c[:duplicate_window].to_i * 1_000_000_000 if c[:duplicate_window]
39
+ c[:subjects] = c[:subjects].map { |s| format(s, name: name) } if c[:subjects]
40
+ c[:consumer] = c[:consumer].dup if c[:consumer]
41
+ c[:consumer][:name] = format(c.dig(:consumer, :name), name: name) if c.dig(:consumer, :name)
42
+ end
43
+ end
44
+
45
+ def self.instance
46
+ @instance ||= new
47
+ end
48
+
49
+ delegate %i[[] []= fetch key? merge! dig] => :@config
50
+
51
+ def initialize
52
+ @config = self.class.parse_file(File.expand_path("defaults.yml", __dir__)).tap { _1.delete(:default) }
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,48 @@
1
+ timeout: 5
2
+ max_retries: 3
3
+
4
+ default: &default
5
+ storage: file
6
+ retention: workqueue
7
+ duplicate_window: 120 # 2m
8
+ discard: old
9
+ allow_direct: true
10
+ subjects:
11
+ - jobs.%{name}.>
12
+ consumer:
13
+ ack_policy: "explicit"
14
+ max_deliver: 10
15
+ ack_wait: 30
16
+ name: consumer-%{name}
17
+
18
+ streams:
19
+ critical:
20
+ <<: *default
21
+ priority: 50
22
+ high:
23
+ <<: *default
24
+ priority: 30
25
+ default:
26
+ <<: *default
27
+ priority: 15
28
+ low:
29
+ <<: *default
30
+ priority: 5
31
+ scheduled:
32
+ <<: *default
33
+ dead:
34
+ <<: *default
35
+ retention: limits
36
+ max_msgs: 10000
37
+ max_age: 604800 # 7d
38
+
39
+ development:
40
+ verbose: false
41
+ concurrency: 1
42
+
43
+ staging:
44
+ verbose: true
45
+ concurrency: 3
46
+
47
+ production:
48
+ concurrency: 3
data/lib/cosmo/job.rb ADDED
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cosmo
4
+ module Job
5
+ def self.included(base)
6
+ base.extend(ClassMethods)
7
+ end
8
+
9
+ module ClassMethods
10
+ def options(stream: nil, retry: nil, backtrace: nil, dead: nil)
11
+ default_options.merge!({ stream:, retry:, backtrace:, dead: }.compact)
12
+ end
13
+
14
+ def perform(*args, async: true, **options)
15
+ message = Message.new(name, args, default_options.merge(options))
16
+ unless async
17
+ payload = Utils::Json.parse(message.to_args[1])
18
+ raise ArgumentError, "Cannot parse message payload" unless payload
19
+
20
+ new.perform(*payload[:args])
21
+ return
22
+ end
23
+
24
+ client.publish_message(message)
25
+ end
26
+
27
+ def perform_async(*args)
28
+ perform(*args)
29
+ end
30
+
31
+ def perform_at(timestamp, *args)
32
+ perform(*args, at: timestamp)
33
+ end
34
+
35
+ def perform_in(interval, *args)
36
+ perform(*args, in: interval)
37
+ end
38
+
39
+ def perform_sync(*args)
40
+ perform(*args, async: false)
41
+ end
42
+
43
+ def default_options
44
+ @default_options ||= (superclass.respond_to?(:default_options) ? superclass.default_options : Message::DEFAULTS).dup
45
+ end
46
+
47
+ private
48
+
49
+ def client
50
+ @client ||= Cosmo::Client.instance
51
+ end
52
+ end
53
+
54
+ def perform(...)
55
+ raise NotImplementedError, "#{self.class}#perform must be implemented"
56
+ end
57
+
58
+ def jid
59
+ Thread.current[:cosmo_jid]
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Cosmo
6
+ class Message
7
+ DEFAULTS = { stream: :default, retry: 3, backtrace: false, dead: true }.freeze
8
+
9
+ attr_reader :jid
10
+
11
+ def initialize(class_name, args, options = nil)
12
+ @class_name = class_name
13
+ @args = args
14
+ @options = Hash(options)
15
+ validate!
16
+
17
+ @at = @options[:at].to_i if @options[:at]
18
+ @at ||= Time.now.to_i + @options[:in].to_i if @options[:in]
19
+
20
+ @jid = SecureRandom.hex(12)
21
+ end
22
+
23
+ def stream(target: false)
24
+ return @options[:stream] if target
25
+
26
+ @at ? :scheduled : @options[:stream]
27
+ end
28
+
29
+ def subject(target: false)
30
+ ["jobs", stream(target:), Utils::String.underscore(@class_name)]
31
+ end
32
+
33
+ def as_json
34
+ {
35
+ jid: jid,
36
+ class: @class_name,
37
+ args: @args,
38
+ retry: @options[:retry] || DEFAULTS[:retry]
39
+ }
40
+ end
41
+
42
+ def to_json(*_args)
43
+ Utils::Json.dump(as_json)
44
+ end
45
+
46
+ def to_args
47
+ headers = { "Nats-Msg-Id" => jid }
48
+ if @at
49
+ headers.merge!("X-Execute-At" => @at.to_i,
50
+ "X-Stream" => stream(target: true),
51
+ "X-Subject" => subject(target: true).join("."))
52
+ end
53
+ [subject.join("."), to_json, { stream: stream, header: headers }]
54
+ end
55
+
56
+ private
57
+
58
+ def validate!
59
+ raise ArgumentError, ":stream is not provided" unless @options[:stream]
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,128 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "concurrent-ruby"
4
+
5
+ module Cosmo
6
+ class Processor
7
+ FETCH_TIMEOUT = ENV.fetch("COSMO_FETCH_TIMEOUT", 0.1).to_f
8
+
9
+ def self.run
10
+ new.run
11
+ end
12
+
13
+ def initialize(streams: ["default"])
14
+ @concurrency = Config.fetch(:concurrency, 1)
15
+ @pool = Utils::ThreadPool.new(@concurrency)
16
+ @running = false
17
+ @consumers = {}
18
+ end
19
+
20
+ def run
21
+ setup_consumers
22
+
23
+ @running = true
24
+ Thread.new { work_loop }
25
+ Thread.new { schedule_loop }
26
+ sleep
27
+ end
28
+
29
+ private
30
+
31
+ def setup_consumers
32
+ Config[:streams].each_key do |name|
33
+ config = Config.dig(:streams, name, :consumer)
34
+ subject = Config.dig(:streams, name, :subjects, 0)
35
+ @consumers[name] = Client.instance.stream.pull_subscribe(subject, config[:name], config: config)
36
+ end
37
+ end
38
+
39
+ def work_loop
40
+ weighted = Config[:streams].filter_map { |n, c| [n, c[:priority]] if c[:priority] }
41
+ .to_h.flat_map { |p, w| [p] * w }
42
+
43
+ while @running
44
+ weighted.shuffle.each do |name|
45
+ break unless @running
46
+
47
+ begin
48
+ message = @consumers[name].fetch(1, timeout: FETCH_TIMEOUT)
49
+ @pool.post { process_job(message.first) }
50
+ rescue NATS::Timeout
51
+ # No messages, continue
52
+ rescue StandardError => e
53
+ puts "#{e.class}: #{e.message}\n#{e.backtrace.join("\n")}"
54
+ rescue Exception => e # rubocop:disable Lint/RescueException, Lint/DuplicateBranch
55
+ # Unexpected error!
56
+ puts "#{e.class}: #{e.message}\n#{e.backtrace.join("\n")}"
57
+ end
58
+
59
+ break unless @running
60
+ end
61
+ end
62
+ end
63
+
64
+ def schedule_loop
65
+ while @running
66
+ break unless @running
67
+
68
+ begin
69
+ now = Time.now.to_i
70
+ messages = @consumers[:scheduled].fetch(1, timeout: FETCH_TIMEOUT)
71
+ messages.each do |message|
72
+ headers = message.header.except("X-Stream", "X-Subject", "X-Execute-At", "Nats-Expected-Stream")
73
+ stream, subject, execute_at = message.header.values_at("X-Stream", "X-Subject", "X-Execute-At")
74
+ headers["Nats-Expected-Stream"] = stream
75
+ execute_at = execute_at.to_i
76
+
77
+ if now >= execute_at
78
+ Client.instance.publish(subject, message.data, headers: headers)
79
+ message.ack
80
+ else
81
+ delay_ns = (execute_at - now) * 1_000_000_000
82
+ message.nak(delay: delay_ns)
83
+ end
84
+ end
85
+ rescue NATS::Timeout
86
+ # No messages, continue
87
+ end
88
+
89
+ break unless @running
90
+ end
91
+ end
92
+
93
+ def process_job(message)
94
+ puts "#perform start #{message.inspect}"
95
+ job = Utils::Json.parse(message.data)
96
+ raise ArgumentError, "malformed payload" unless job
97
+
98
+ worker_class = Utils::String.safe_constantize(job[:class])
99
+ raise ArgumentError, "#{job[:class]} class not found" unless job
100
+
101
+ Thread.current[:cosmo_jid] = job[:jid]
102
+ worker_class.new.perform(*job[:args])
103
+ message.ack
104
+ rescue StandardError => e
105
+ handle_failure(message, job, e)
106
+ ensure
107
+ Thread.current[:cosmo_jid] = nil
108
+ end
109
+
110
+ def handle_failure(message, job, error)
111
+ puts "Error happened for #{job.inspect} with #{error.class}: #{error.message}"
112
+ attempts = message.metadata.num_delivered
113
+ max_attempts = job[:retry] + 1
114
+
115
+ if attempts >= max_attempts
116
+ # Dead letter - ack and move on
117
+ # Could publish to jobs.dead for DLQ # msg.ack
118
+ message.term
119
+ puts "Job #{job[:jid]} failed permanently with #{error.class}: #{error.message}"
120
+ else
121
+ # NATS will auto-retry based on max_deliver
122
+ # NATS handles retry automatically with exponential backoff
123
+ delay_ns = ((attempts**4) + 15) * 1_000_000_000
124
+ message.nak(delay: delay_ns)
125
+ end
126
+ end
127
+ end
128
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cosmo
4
+ module Utils
5
+ module Hash
6
+ module_function
7
+
8
+ def symbolize_keys!(hash)
9
+ hash.keys.each do |key|
10
+ raise ArgumentError, "key cannot be converted to symbol" unless key.respond_to?(:to_sym)
11
+
12
+ sym = key.to_sym
13
+ hash[sym] = hash.delete(key)
14
+ symbolize_keys!(hash[sym]) if hash[sym].is_a?(::Hash)
15
+ end
16
+
17
+ hash
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Cosmo
6
+ module Utils
7
+ module Json
8
+ module_function
9
+
10
+ def parse(value, default: nil, symbolize_names: true, **options)
11
+ JSON.parse(value, options.merge(symbolize_names:))
12
+ rescue TypeError, JSON::ParserError
13
+ default
14
+ end
15
+
16
+ def dump(value, default: nil)
17
+ ::JSON.generate(value)
18
+ rescue TypeError, JSON::NestingError
19
+ default
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cosmo
4
+ module Utils
5
+ module String
6
+ module_function
7
+
8
+ def underscore(value)
9
+ value
10
+ .to_s
11
+ .gsub("::", "/")
12
+ .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
13
+ .gsub(/([a-z\d])([A-Z])/, '\1_\2')
14
+ .tr("-", "_")
15
+ .downcase
16
+ end
17
+
18
+ def safe_constantize(class_name)
19
+ Object.const_get(class_name)
20
+ rescue NameError
21
+ # nop
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cosmo
4
+ module Utils
5
+ # A thread pool that reuses a fixed number of threads operating off a fixed size queue.
6
+ # At any point, at most `num_threads` will be active processing tasks. When all threads are busy new
7
+ # tasks posted to the thread pool are blocked until a thread becomes available.
8
+ # Should a thread crash for any reason the thread will immediately be removed
9
+ # from the pool and replaced.
10
+ class ThreadPool
11
+ def initialize(concurrency)
12
+ @mutex = Mutex.new
13
+ @available = concurrency
14
+ @cond = ConditionVariable.new
15
+ @pool = Concurrent::FixedThreadPool.new(concurrency)
16
+ end
17
+
18
+ def post
19
+ @mutex.synchronize do
20
+ @cond.wait(@mutex) while @available <= 0
21
+ @available -= 1
22
+ end
23
+
24
+ @pool.post do
25
+ yield
26
+ ensure
27
+ @mutex.synchronize do
28
+ @available += 1
29
+ @cond.signal
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cosmo
4
+ VERSION = "0.1.0"
5
+ end
data/lib/cosmo.rb ADDED
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "cosmo/utils/hash"
4
+ require "cosmo/utils/json"
5
+ require "cosmo/utils/string"
6
+ require "cosmo/utils/thread_pool"
7
+
8
+ require "cosmo/client"
9
+ require "cosmo/processor"
10
+ require "cosmo/message"
11
+ require "cosmo/version"
12
+ require "cosmo/config"
13
+ require "cosmo/job"
14
+ require "cosmo/cli"
15
+
16
+ module Cosmo
17
+ class Error < StandardError; end
18
+
19
+ class ArgumentError < Error; end
20
+
21
+ class ConfigNotFoundError < Error
22
+ def initialize(config_file)
23
+ super("No such file #{config_file}")
24
+ end
25
+ end
26
+ end
data/lib/cosmonauts.rb ADDED
@@ -0,0 +1,3 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "cosmo"
metadata ADDED
@@ -0,0 +1,76 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: cosmonauts
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Dmitry Vorotilin
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: nats-pure
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '2.5'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '2.5'
26
+ description: Background processing at warp speed for Ruby
27
+ email:
28
+ - d.vorotilin@gmail.com
29
+ executables: []
30
+ extensions: []
31
+ extra_rdoc_files: []
32
+ files:
33
+ - LICENSE.txt
34
+ - README.md
35
+ - lib/cosmo.rb
36
+ - lib/cosmo/cli.rb
37
+ - lib/cosmo/client.rb
38
+ - lib/cosmo/config.rb
39
+ - lib/cosmo/defaults.yml
40
+ - lib/cosmo/job.rb
41
+ - lib/cosmo/message.rb
42
+ - lib/cosmo/processor.rb
43
+ - lib/cosmo/utils/hash.rb
44
+ - lib/cosmo/utils/json.rb
45
+ - lib/cosmo/utils/string.rb
46
+ - lib/cosmo/utils/thread_pool.rb
47
+ - lib/cosmo/version.rb
48
+ - lib/cosmonauts.rb
49
+ homepage: https://github.com/bitsbeam/cosmonauts
50
+ licenses:
51
+ - LGPL-3.0
52
+ metadata:
53
+ homepage_uri: https://github.com/bitsbeam/cosmonauts
54
+ bug_tracker_uri: https://github.com/bitsbeam/cosmonauts/issues
55
+ documentation_uri: https://github.com/bitsbeam/cosmonauts/blob/main/README.md
56
+ changelog_uri: https://github.com/bitsbeam/cosmonauts/blob/main/CHANGELOG.md
57
+ source_code_uri: https://github.com/bitsbeam/cosmonauts
58
+ rubygems_mfa_required: 'true'
59
+ rdoc_options: []
60
+ require_paths:
61
+ - lib
62
+ required_ruby_version: !ruby/object:Gem::Requirement
63
+ requirements:
64
+ - - ">="
65
+ - !ruby/object:Gem::Version
66
+ version: 3.1.0
67
+ required_rubygems_version: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - ">="
70
+ - !ruby/object:Gem::Version
71
+ version: '0'
72
+ requirements: []
73
+ rubygems_version: 3.6.9
74
+ specification_version: 4
75
+ summary: Lightning-fast background processing
76
+ test_files: []