Class: Cosmo::API::Counter

Inherits:
Object
  • Object
show all
Defined in:
lib/cosmo/api/counter.rb

Constant Summary collapse

STREAM_NAME =
"cosmostats"

Class Method Summary collapse

Instance Method Summary collapse

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

.instanceObject



8
9
10
# File 'lib/cosmo/api/counter.rb', line 8

def self.instance
  @instance ||= new("jobs")
end

Instance Method Details

#decrement(key, by: 1) ⇒ Object 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) ⇒ Object



38
39
40
41
42
43
# File 'lib/cosmo/api/counter.rb', line 38

def get(key)
  raw = client.get_message(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
  0
end

#increment(key, by: 1) ⇒ Object Also known as: incr



24
25
26
# File 'lib/cosmo/api/counter.rb', line 24

def increment(key, by: 1)
  publish(key, "+#{by}")
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

#withObject



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