Class: Legion::Data::Spool::ScopedSpool

Inherits:
Object
  • Object
show all
Includes:
Logging::Helper
Defined in:
lib/legion/data/spool.rb

Instance Method Summary collapse

Methods included from Logging::Helper

#handle_exception

Constructor Details

#initialize(extension_module, spool_root) ⇒ ScopedSpool

Returns a new instance of ScopedSpool.



37
38
39
# File 'lib/legion/data/spool.rb', line 37

def initialize(extension_module, spool_root)
  @extension_dir = File.join(spool_root, Spool.send(:extension_path, extension_module))
end

Instance Method Details

#clear(sub_namespace) ⇒ Object



89
90
91
92
93
94
95
96
97
98
# File 'lib/legion/data/spool.rb', line 89

def clear(sub_namespace)
  dir = sub_dir(sub_namespace)
  return unless Dir.exist?(dir)

  Dir[File.join(dir, '*.json')].each { |f| File.delete(f) }
  log.info "Spool cleared #{sub_namespace}"
rescue StandardError => e
  handle_exception(e, level: :error, handled: false, operation: :spool_clear, sub_namespace: sub_namespace)
  raise
end

#count(sub_namespace) ⇒ Object



85
86
87
# File 'lib/legion/data/spool.rb', line 85

def count(sub_namespace)
  sorted_files(sub_namespace).size
end

#flush(sub_namespace) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/legion/data/spool.rb', line 67

def flush(sub_namespace)
  count = 0
  path = nil
  sorted_files(sub_namespace).each do |path|
    event = load_event_file(path, sub_namespace)
    next unless event

    yield event
    File.delete(path)
    count += 1
  end
  log.info "Spool drained #{count} item(s) from #{sub_namespace}" if count.positive?
  count
rescue StandardError => e
  handle_exception(e, level: :error, handled: false, operation: :spool_flush, sub_namespace: sub_namespace, path: path)
  raise
end

#read(sub_namespace) ⇒ Object



57
58
59
60
61
62
63
64
65
# File 'lib/legion/data/spool.rb', line 57

def read(sub_namespace)
  sorted_files(sub_namespace).each_with_object([]) do |path, events|
    event = load_event_file(path, sub_namespace)
    events << event if event
  end
rescue StandardError => e
  handle_exception(e, level: :error, handled: false, operation: :spool_read, sub_namespace: sub_namespace)
  raise
end

#write(sub_namespace, payload) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/legion/data/spool.rb', line 41

def write(sub_namespace, payload)
  dir = sub_dir(sub_namespace)
  FileUtils.mkdir_p(dir)
  filename = "#{Time.now.strftime('%s%9N')}-#{SecureRandom.uuid}.json"
  path = File.join(dir, filename)
  temp_path = temp_path_for(dir, filename)
  File.binwrite(temp_path, ::JSON.generate(payload))
  File.rename(temp_path, path)
  log.info "Spool write: #{sub_namespace} -> #{filename}"
  path
rescue StandardError => e
  File.delete(temp_path) if defined?(temp_path) && temp_path && File.exist?(temp_path)
  handle_exception(e, level: :error, handled: false, operation: :spool_write, sub_namespace: sub_namespace)
  raise
end