Skip to content
Kward Search API index

Class: Kward::Transport::Store

Inherits:
Object
  • Object
show all
Defined in:
lib/kward/transport/store.rb

Overview

Small private JSON store scoped to one transport plugin.

Constant Summary collapse

KEY_PATTERN =
/\A[A-Za-z0-9][A-Za-z0-9:._-]*\z/.freeze
DEFAULT_MAX_PROCESSED_KEYS =
10_000

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(transport_id, root: ConfigFiles.config_dir) ⇒ Store

Returns a new instance of Store.



18
19
20
21
22
23
# File 'lib/kward/transport/store.rb', line 18

def initialize(transport_id, root: ConfigFiles.config_dir)
  @transport_id = validate_key(transport_id, "transport id")
  @path = File.join(File.expand_path(root), "transports", @transport_id, "state.json")
  @mutex = Mutex.new
  @values, @processed = load_state
end

Instance Attribute Details

#transport_idObject (readonly)

Returns the value of attribute transport_id.



16
17
18
# File 'lib/kward/transport/store.rb', line 16

def transport_id
  @transport_id
end

Instance Method Details

#claim(key, max_keys: DEFAULT_MAX_PROCESSED_KEYS) ⇒ Object

Claims an external event key. Returns false when the key was already claimed, making duplicate webhook and polling deliveries harmless.

Raises:

  • (ArgumentError)


51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/kward/transport/store.rb', line 51

def claim(key, max_keys: DEFAULT_MAX_PROCESSED_KEYS)
  key = validate_key(key, "idempotency key")
  max_keys = Integer(max_keys)
  raise ArgumentError, "max_keys must be positive" unless max_keys.positive?

  @mutex.synchronize do
    return false if @processed.key?(key)

    @processed[key] = Time.now.utc.iso8601
    @processed.shift while @processed.length > max_keys
    persist
    true
  end
end

#delete(key) ⇒ Object



39
40
41
42
43
44
45
46
47
# File 'lib/kward/transport/store.rb', line 39

def delete(key)
  key = validate_key(key, "storage key")
  @mutex.synchronize do
    present = @values.key?(key)
    value = @values.delete(key)
    persist if present
    copy(value)
  end
end

#get(key) ⇒ Object



25
26
27
28
# File 'lib/kward/transport/store.rb', line 25

def get(key)
  key = validate_key(key, "storage key")
  @mutex.synchronize { copy(@values[key]) }
end

#put(key, value) ⇒ Object



30
31
32
33
34
35
36
37
# File 'lib/kward/transport/store.rb', line 30

def put(key, value)
  key = validate_key(key, "storage key")
  @mutex.synchronize do
    @values[key] = copy(value)
    persist
  end
  value
end