Module: Legion::Data::Archiver
- Defined in:
- lib/legion/data/archiver.rb
Defined Under Namespace
Classes: UploadError
Class Method Summary collapse
- .archive_table(table:, retention_days: 90, batch_size: 1000, storage_backend: nil) ⇒ Object
- .manifest_stats ⇒ Object
- .upload_batch(data:, table:, year:, month:, batch_n:, backend:) ⇒ Object
Class Method Details
.archive_table(table:, retention_days: 90, batch_size: 1000, storage_backend: nil) ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/legion/data/archiver.rb', line 16 def archive_table(table:, retention_days: 90, batch_size: 1000, storage_backend: nil) return { skipped: true, reason: 'not_postgres' } unless postgres? conn = Legion::Data.connection cutoff = Time.now - (retention_days * 86_400) now = Time.now.utc batches = 0 total_rows = 0 paths = [] batch_n = 0 loop do batch_n += 1 rows = conn[table].where { created_at < cutoff }.limit(batch_size).all break if rows.empty? ids = rows.map { |r| r[:id] } jsonl = serialize_rows(rows) compressed = gzip_compress(jsonl) checksum = Digest::SHA256.hexdigest(compressed) batch_id = SecureRandom.uuid path = upload_batch( data: compressed, table: table.to_s, year: now.year, month: now.month, batch_n: batch_n, backend: storage_backend ) conn.transaction do conn[:archive_manifest].insert( batch_id: batch_id, source_table: table.to_s, row_count: rows.size, checksum: checksum, storage_path: path, archived_at: now ) conn[table].where(id: ids).delete end batches += 1 total_rows += rows.size paths << path end { batches: batches, total_rows: total_rows, paths: paths } end |
.manifest_stats ⇒ Object
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
# File 'lib/legion/data/archiver.rb', line 79 def manifest_stats return {} unless postgres? return {} unless Legion::Data.connection.table_exists?(:archive_manifest) Legion::Data.connection[:archive_manifest] .group_and_count(:source_table) .select_append( Sequel.function(:sum, :row_count).as(:total_rows), Sequel.function(:min, :archived_at).as(:earliest), Sequel.function(:max, :archived_at).as(:latest) ) .all .to_h do |row| [row[:source_table], { batches: row[:count], total_rows: row[:total_rows].to_i, earliest: row[:earliest], latest: row[:latest] }] end end |
.upload_batch(data:, table:, year:, month:, batch_n:, backend:) ⇒ Object
68 69 70 71 72 73 74 75 76 77 |
# File 'lib/legion/data/archiver.rb', line 68 def upload_batch(data:, table:, year:, month:, batch_n:, backend:) case backend when :s3 upload_s3(data: data, table: table, year: year, month: month, batch_n: batch_n) when :azure upload_azure(data: data, table: table, year: year, month: month, batch_n: batch_n) else upload_tmpdir(data: data, table: table, year: year, month: month, batch_n: batch_n) end end |