package Proc::tored::Role::Running;
# ABSTRACT: add running state and signal handling to services
$Proc::tored::Role::Running::VERSION = '0.07';
use strict;
use warnings;
use Moo::Role;
use Carp;
use Path::Tiny 'path';
use Types::Standard -types;


has term_file => (
  is  => 'ro',
  isa => Maybe[Str],
  required => 1,
);

has _path => (
  is  => 'lazy',
  isa => InstanceOf['Path::Tiny'],
);

sub _build__path { path(shift->term_file) }

has is_started => (
  is  => 'ro',
  isa => Bool,
  default => 0,
);


sub is_running {
  my $self = shift;

  if ($self->_path->exists) {
    $self->{is_started} = 0;
    $self->_path->remove;
  }

  return $self->is_started;
}


sub start {
  my $self = shift;
  return if $self->is_running;
  $self->_path->remove;
  $self->{is_started} = 1;
  return 1;
}


sub stop { $_[0]->{is_started} = 0; return 1 }


sub signal { $_[0]->_path->touch->assert(sub { $_->exists }) }

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

Proc::tored::Role::Running - add running state and signal handling to services

=head1 VERSION

version 0.07

=head1 SYNOPSIS

  package Some::Thing;
  use Moo;

  with 'Proc::tored::Running';

  sub run {
    my $self = shift;

    $self->start;

    while ($self->is_running) {
      do_stuff(...);
    }
  }

=head1 DESCRIPTION

Classes consuming this role are provided with controls to L</start> and
L</stop> voluntarily through the use of a touch file to signal the process to
self-terminate.

=head1 ATTRIBUTES

=head2 term_file

Specifies a file path that will be used as a touch file to signal the process
to self-terminate.

=head1 METHODS

=head2 is_running

Returns true while the service is running in the current process.

=head2 start

Flags the current process as I<running>. After calling this method,
L</is_running> will return true.

=head2 stop

Flags the current process as I<not running> and restores any previously
configured signal handlers. Once this method has been called, L</is_running>
will return false.

=head2 signal

Signals the process to stop running by creating a touch file.

=head1 AUTHOR

Jeff Ober <jeffober@gmail.com>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2017 by Jeff Ober.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut
