Class: Cosmo::API::Counter
- Inherits:
-
Object
- Object
- Cosmo::API::Counter
- Defined in:
- lib/cosmo/api/counter.rb,
sig/cosmo/api/counter.rbs
Constant Summary collapse
- STREAM_NAME =
"_cosmostats"
Class Method Summary collapse
Instance Method Summary collapse
- #client ⇒ Client
- #decrement(key, by: 1) ⇒ ::Integer (also: #decr)
- #get(key) ⇒ ::Integer
- #increment(key, by: 1) ⇒ ::Integer (also: #incr)
-
#initialize(namespace) ⇒ Counter
constructor
A new instance of Counter.
- #publish(key, value) ⇒ ::Integer
- #reset(key) ⇒ Object
- #subject(key) ⇒ ::String
- #with { ... } ⇒ void
Constructor Details
#initialize(namespace) ⇒ Counter
Returns a new instance of Counter.
12 13 14 |
# File 'lib/cosmo/api/counter.rb', line 12 def initialize(namespace) @namespace = namespace end |
Class Method Details
.instance ⇒ Counter
8 9 10 |
# File 'lib/cosmo/api/counter.rb', line 8 def self.instance @instance ||= new("jobs") end |
Instance Method Details
#client ⇒ Client
65 66 67 |
# File 'lib/cosmo/api/counter.rb', line 65 def client @client ||= Client.instance end |
#decrement(key, by: 1) ⇒ ::Integer Also known as: decr
29 30 31 |
# File 'lib/cosmo/api/counter.rb', line 29 def decrement(key, by: 1) publish(key, "-#{by}") end |
#get(key) ⇒ ::Integer
38 39 40 41 42 43 |
# File 'lib/cosmo/api/counter.rb', line 38 def get(key) raw = client.(STREAM_NAME, direct: true, subject: subject(key)) Utils::Json.parse(raw.data, default: { "val" => 0 })[:val].to_i rescue NATS::JetStream::Error::NotFound, NATS::JetStream::Error::ServiceUnavailable, NATS::IO::Timeout 0 end |
#increment(key, by: 1) ⇒ ::Integer Also known as: incr
24 25 26 |
# File 'lib/cosmo/api/counter.rb', line 24 def increment(key, by: 1) publish(key, "+#{by}") end |
#publish(key, value) ⇒ ::Integer
47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/cosmo/api/counter.rb', line 47 def publish(key, value) rescued = nil begin client.publish(subject(key), "", header: { "Nats-Incr" => value }).val.to_i rescue NATS::JetStream::Error::NoStreamResponse raise if rescued rescued = true client.create_stream(STREAM_NAME, subjects: ["#{STREAM_NAME}.>"], allow_msg_counter: true, allow_direct: true, description: "Cosmo statistics") retry end end |
#reset(key) ⇒ Object
34 35 36 |
# File 'lib/cosmo/api/counter.rb', line 34 def reset(key) client.purge(STREAM_NAME, subject(key)) end |
#subject(key) ⇒ ::String
61 62 63 |
# File 'lib/cosmo/api/counter.rb', line 61 def subject(key) "#{STREAM_NAME}.#{@namespace}.#{key}" end |
#with { ... } ⇒ void
This method returns an undefined value.
16 17 18 19 20 21 22 |
# File 'lib/cosmo/api/counter.rb', line 16 def with result = yield increment(:processed) if result == true increment(:failed) if result == false rescue Exception # rubocop:disable Lint/RescueException increment(:failed) end |