Class: Prdigest::DeliveryCheckpointStore

Inherits:
Object
  • Object
show all
Defined in:
lib/prdigest/delivery_checkpoint_store.rb

Defined Under Namespace

Classes: Session

Constant Summary collapse

SCHEMA =
"prdigest-delivery-checkpoint"
SCHEMA_VERSION =
1

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root:) ⇒ DeliveryCheckpointStore

Returns a new instance of DeliveryCheckpointStore.



101
102
103
# File 'lib/prdigest/delivery_checkpoint_store.rb', line 101

def initialize(root:)
  @root = File.expand_path(root)
end

Class Method Details

.atomic_write(path, content) ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/prdigest/delivery_checkpoint_store.rb', line 140

def self.atomic_write(path, content)
  directory = File.dirname(path)
  temporary = "#{path}.tmp-#{Process.pid}-#{Thread.current.object_id}"
  File.open(temporary, File::WRONLY | File::CREAT | File::EXCL, 0o600) do |file|
    file.write(content)
    file.flush
    file.fsync
  end
  File.rename(temporary, path)
  File.chmod(0o600, path)
  File.open(directory, File::RDONLY, &:fsync)
ensure
  File.unlink(temporary) if temporary && File.exist?(temporary)
end

Instance Method Details

#with_checkpoint(date:, chat_id:, scope:, chunks: nil, chunk_factory: nil) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/prdigest/delivery_checkpoint_store.rb', line 105

def with_checkpoint(date:, chat_id:, scope:, chunks: nil, chunk_factory: nil)
  normalized_date = Date.iso8601(date.to_s)
  ensure_root!
  path = File.join(@root, "#{normalized_date}.json")
  lock_path = File.join(@root, "#{normalized_date}.lock")

  File.open(lock_path, File::RDWR | File::CREAT, 0o600) do |lock|
    File.chmod(0o600, lock_path)
    unless lock.flock(File::LOCK_EX | File::LOCK_NB)
      raise SendError.new(
        "delivery checkpoint is already active",
        kind: "delivery_checkpoint",
        delivery: { accepted_chunks: 0, total_chunks: Array(chunks).length, status: "pending" }
      )
    end

    data = load_or_create(
      path,
      date: normalized_date,
      chat_id: Integer(chat_id),
      scope: Array(scope).map(&:to_s),
      chunks: chunks,
      chunk_factory: chunk_factory
    )
    fail_if_unavailable!(data)
    yield Session.new(path: path, data: data)
  ensure
    lock.flock(File::LOCK_UN)
  end
rescue Error
  raise
rescue StandardError => e
  raise StateError, "cannot access delivery checkpoint (#{e.class})"
end