<commit_before>package Minion::Backend::Pg;
use Mojo::Base 'Minion::Backend';

use Carp 'croak';
use Mojo::IOLoop;
use Mojo::Pg;
use Sys::Hostname 'hostname';

has 'pg';

sub dequeue {
  my ($self, $id, $wait, $options) = @_;

  if ((my $job = $self->_try($id, $options))) { return $job }
  return undef if Mojo::IOLoop->is_running;

  my $db = $self->pg->db;
  $db->listen('minion.job')->on(notification => sub { Mojo::IOLoop->stop });
  my $timer = Mojo::IOLoop->timer($wait => sub { Mojo::IOLoop->stop });
  Mojo::IOLoop->start;
  $db->unlisten('*') and Mojo::IOLoop->remove($timer);
  undef $db;

  return $self->_try($id, $options);
}

sub enqueue {
  my ($self, $task, $args, $options) = (shift, shift, shift || [], shift || {});

  my $db = $self->pg->db;
  return $db->query(
    "insert into minion_jobs (args, attempts, delayed, priority, queue, task)
     values (?, ?, (now() + (interval '1 second' * ?)), ?, ?, ?)
     returning id", {json => $args}, $options->{attempts} // 1,
    $options->{delay} // 0, $options->{priority} // 0,
    $options->{queue} // 'default', $task
  )->hash->{id};
}

sub fail_job   { shift->_update(1, @_) }
sub finish_job { shift->_update(0, @_) }

sub job_info {
  shift->pg->db->query(
    'select id, args, attempts, extract(epoch from created) as created,
       extract(epoch from delayed) as delayed,
       extract(epoch from finished) as finished, priority, queue, result,
       extract(epoch from retried) as retried, retries,
       extract(epoch from started) as started, state, task, worker
     from minion_jobs where id = ?', shift
  )->expand->hash;
}

sub list_jobs {
  my ($self, $offset, $limit, $options) = @_;

  return $self->pg->db->query(
    'select id from minion_jobs
     where (state = $1 or $1 is null) and (task = $2 or $2 is null)
     order by id desc
     limit $3
     offset $4', @$options{qw(state task)}, $limit, $offset
  )->arrays->map(sub { $self->job_info($_->[0]) })->to_array;
}

sub list_workers {
  my ($self, $offset, $limit) = @_;

  my $sql = 'select id from minion_workers order by id desc limit ? offset ?';
  return $self->pg->db->query($sql, $limit, $offset)
    ->arrays->map(sub { $self->worker_info($_->[0]) })->to_array;
}

sub new {
  my $self = shift->SUPER::new(pg => Mojo::Pg->new(@_));

  croak 'PostgreSQL 9.5 or later is required'
    if Mojo::Pg->new(@_)->db->dbh->{pg_server_version} < 90500;
  my $pg = $self->pg->auto_migrate(1)->max_connections(1);
  $pg->migrations->name('minion')->from_data;

  return $self;
}

sub register_worker {
  my ($self, $id) = @_;

  my $sql
    = 'update minion_workers set notified = now() where id = ? returning 1';
  return $id if $id && $self->pg->db->query($sql, $id)->rows;

  $sql = 'insert into minion_workers (host, pid) values (?, ?) returning id';
  return $self->pg->db->query($sql, hostname, $$)->hash->{id};
}

sub remove_job {
  !!shift->pg->db->query(
    "delete from minion_jobs
     where id = ? and state in ('inactive', 'failed', 'finished')
     returning 1", shift
  )->rows;
}

sub repair {
  my $self = shift;

  # Check worker registry
  my $db     = $self->pg->db;
  my $minion = $self->minion;
  $db->query(
    "delete from minion_workers
     where notified < now() - interval '1 second' * ?", $minion->missing_after
  );

  # Abandoned jobs
  my $fail = $db->query(
    "select id, retries from minion_jobs as j
     where state = 'active'
       and not exists(select 1 from minion_workers where id = j.worker)"
  )->hashes;
  $fail->each(sub { $self->fail_job(@$_{qw(id retries)}, 'Worker went away') });

  # Old jobs
  $db->query(
    "delete from minion_jobs
     where state = 'finished' and finished < now() - interval '1 second' * ?",
    $minion->remove_after
  );
}

sub reset { shift->pg->db->query('truncate minion_jobs, minion_workers') }

sub retry_job {
  my ($self, $id, $retries, $options) = (shift, shift, shift, shift || {});

  return !!$self->pg->db->query(
    "update minion_jobs
     set priority = coalesce(?, priority), queue = coalesce(?, queue),
       retried = now(), retries = retries + 1, state = 'inactive',
       delayed = (now() + (interval '1 second' * ?))
     where id = ? and retries = ?
       and state in ('inactive', 'failed', 'finished')
     returning 1", @$options{qw(priority queue)}, $options->{delay} // 0, $id,
    $retries
  )->rows;
}

sub stats {
  my $self = shift;

  my $stats = $self->pg->db->query(
    "select state::text, count(state) from minion_jobs group by state
     union all
     select 'workers', count(*) from minion_workers
     union all
     select 'active_workers', count(distinct worker) from minion_jobs
     where state = 'active'"
  );
  $stats = $stats->arrays->reduce(sub { $a->{$b->[0]} = $b->[1]; $a }, {});

  return {
    active_jobs => $stats->{active} || 0,
    active_workers   => $stats->{active_workers},
    failed_jobs      => $stats->{failed} || 0,
    finished_jobs    => $stats->{finished} || 0,
    inactive_jobs    => $stats->{inactive} || 0,
    inactive_workers => $stats->{workers} - $stats->{active_workers}
  };
}

sub unregister_worker {
  shift->pg->db->query('delete from minion_workers where id = ?', shift);
}

sub worker_info {
  shift->pg->db->query(
    "select id, extract(epoch from notified) as notified, array(
       select id from minion_jobs<commit_msg>no need to create a new hash<commit_after>package Minion::Backend::Pg;
use Mojo::Base 'Minion::Backend';

use Carp 'croak';
use Mojo::IOLoop;
use Mojo::Pg;
use Sys::Hostname 'hostname';

has 'pg';

sub dequeue {
  my ($self, $id, $wait, $options) = @_;

  if ((my $job = $self->_try($id, $options))) { return $job }
  return undef if Mojo::IOLoop->is_running;

  my $db = $self->pg->db;
  $db->listen('minion.job')->on(notification => sub { Mojo::IOLoop->stop });
  my $timer = Mojo::IOLoop->timer($wait => sub { Mojo::IOLoop->stop });
  Mojo::IOLoop->start;
  $db->unlisten('*') and Mojo::IOLoop->remove($timer);
  undef $db;

  return $self->_try($id, $options);
}

sub enqueue {
  my ($self, $task, $args, $options) = (shift, shift, shift || [], shift || {});

  my $db = $self->pg->db;
  return $db->query(
    "insert into minion_jobs (args, attempts, delayed, priority, queue, task)
     values (?, ?, (now() + (interval '1 second' * ?)), ?, ?, ?)
     returning id", {json => $args}, $options->{attempts} // 1,
    $options->{delay} // 0, $options->{priority} // 0,
    $options->{queue} // 'default', $task
  )->hash->{id};
}

sub fail_job   { shift->_update(1, @_) }
sub finish_job { shift->_update(0, @_) }

sub job_info {
  shift->pg->db->query(
    'select id, args, attempts, extract(epoch from created) as created,
       extract(epoch from delayed) as delayed,
       extract(epoch from finished) as finished, priority, queue, result,
       extract(epoch from retried) as retried, retries,
       extract(epoch from started) as started, state, task, worker
     from minion_jobs where id = ?', shift
  )->expand->hash;
}

sub list_jobs {
  my ($self, $offset, $limit, $options) = @_;

  return $self->pg->db->query(
    'select id from minion_jobs
     where (state = $1 or $1 is null) and (task = $2 or $2 is null)
     order by id desc
     limit $3
     offset $4', @$options{qw(state task)}, $limit, $offset
  )->arrays->map(sub { $self->job_info($_->[0]) })->to_array;
}

sub list_workers {
  my ($self, $offset, $limit) = @_;

  my $sql = 'select id from minion_workers order by id desc limit ? offset ?';
  return $self->pg->db->query($sql, $limit, $offset)
    ->arrays->map(sub { $self->worker_info($_->[0]) })->to_array;
}

sub new {
  my $self = shift->SUPER::new(pg => Mojo::Pg->new(@_));

  croak 'PostgreSQL 9.5 or later is required'
    if Mojo::Pg->new(@_)->db->dbh->{pg_server_version} < 90500;
  my $pg = $self->pg->auto_migrate(1)->max_connections(1);
  $pg->migrations->name('minion')->from_data;

  return $self;
}

sub register_worker {
  my ($self, $id) = @_;

  my $sql
    = 'update minion_workers set notified = now() where id = ? returning 1';
  return $id if $id && $self->pg->db->query($sql, $id)->rows;

  $sql = 'insert into minion_workers (host, pid) values (?, ?) returning id';
  return $self->pg->db->query($sql, hostname, $$)->hash->{id};
}

sub remove_job {
  !!shift->pg->db->query(
    "delete from minion_jobs
     where id = ? and state in ('inactive', 'failed', 'finished')
     returning 1", shift
  )->rows;
}

sub repair {
  my $self = shift;

  # Check worker registry
  my $db     = $self->pg->db;
  my $minion = $self->minion;
  $db->query(
    "delete from minion_workers
     where notified < now() - interval '1 second' * ?", $minion->missing_after
  );

  # Abandoned jobs
  my $fail = $db->query(
    "select id, retries from minion_jobs as j
     where state = 'active'
       and not exists(select 1 from minion_workers where id = j.worker)"
  )->hashes;
  $fail->each(sub { $self->fail_job(@$_{qw(id retries)}, 'Worker went away') });

  # Old jobs
  $db->query(
    "delete from minion_jobs
     where state = 'finished' and finished < now() - interval '1 second' * ?",
    $minion->remove_after
  );
}

sub reset { shift->pg->db->query('truncate minion_jobs, minion_workers') }

sub retry_job {
  my ($self, $id, $retries, $options) = (shift, shift, shift, shift || {});

  return !!$self->pg->db->query(
    "update minion_jobs
     set priority = coalesce(?, priority), queue = coalesce(?, queue),
       retried = now(), retries = retries + 1, state = 'inactive',
       delayed = (now() + (interval '1 second' * ?))
     where id = ? and retries = ?
       and state in ('inactive', 'failed', 'finished')
     returning 1", @$options{qw(priority queue)}, $options->{delay} // 0, $id,
    $retries
  )->rows;
}

sub stats {
  my $self = shift;

  my $stats = $self->pg->db->query(
    "select state::text || '_jobs', count(state) from minion_jobs group by state
     union all
     select 'inactive_workers', count(*) from minion_workers
     union all
     select 'active_workers', count(distinct worker) from minion_jobs
     where state = 'active'"
  );
  $stats = $stats->arrays->reduce(sub { $a->{$b->[0]} = $b->[1]; $a }, {});
  $stats->{inactive_workers} -= $stats->{active_workers};
  $stats->{"${_}_jobs"} ||= 0 for qw(inactive active failed finished);

  return $stats;
}

sub unregister_worker {
  shift->pg->db->query('delete from minion_workers where id = ?', shift);
}

sub worker_info {
  shift->pg->db->query(
    "select id, extract(epoch from notified) as notified, array(
       select id from minion_jobs
{'fraction_non_alphanumeric': 0.1892250782509722, 'fraction_numerical': 0.00692402541970976, 'mean_word_length': 3.4527027027027026, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 233, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2725737', 'n_tokens_mistral': 3833, 'n_tokens_neox': 3725, 'n_words': 1003}