package Catalyst::Plugin::Scheduler;

use strict;
use warnings;
use NEXT;
use base qw/Class::Accessor::Fast Class::Data::Inheritable Catalyst::Base/;
use Catalyst::Plugin::Scheduler::Base;

our $VERSION = '0.07_01';


=pod

=head1 NAME

Catalyst::Plugin::Scheduler - Schedule events to run in a cron-like fashion

=head1 SYNOPSIS

    use Catalyst qw/Scheduler/;
    
    # run remove_sessions in the Cron controller every hour
    __PACKAGE__->schedule(
        at    => '0 * * * *',
        event => '/cron/remove_sessions'
    );
    
    # Run a subroutine at 4:05am every Sunday
    __PACKAGE__->schedule(
        at    => '5 4 * * sun',
        event => \&do_stuff,
    );
    
    # A long-running scheduled event that must be triggered 
    # manually by an authorized user
    __PACKAGE__->schedule(
        trigger => 'rebuild_search_index',
        event   => '/cron/rebuild_search_index',
    );
    
    $ wget -q http://www.myapp.com/?schedule_trigger=rebuild_search_index
    
    
=head1 DESCRIPTION

This plugin allows you to schedule events to run at recurring intervals.
Events will run during the first request which meets or exceeds the specified
time.  Depending on the level of traffic to the application, events may or may
not run at exactly the correct time, but it should be enough to satisfy many
basic scheduling needs.


=head1 CONFIGURATION

Configuration is optional and is specified in MyApp->config->{scheduler}.

=head2 logging

Set to 1 to enable logging of events as they are executed.  This option is
enabled by default when running under -Debug mode.  Errors are always logged
regardless of the value of this option.

=head2 time_zone

The time zone of your system.  This will be autodetected where possible, or
will default to UTC (GMT).  You can override the detection by providing a
valid L<DateTime> time zone string, such as 'America/New_York'.

=head2 state_file

The current state of every event is stored in a file.  By default this is
$APP_HOME/scheduler.state.  This file is created on the first request if it
does not already exist.

=head2 yaml_file

The location of the optional YAML event configuration file.  By default this
is $APP_HOME/scheduler.yml.

=head2 hosts_allow

This option specifies IP addresses for trusted users.  This option defaults
to 127.0.0.1.  Multiple addresses can be specified by using an array
reference.  This option is used for both events where auto_run is set to 0
and for manually-triggered events.

    __PACKAGE__->config->{scheduler}->{hosts_allow} = '192.168.1.1';
    __PACKAGE__->config->{scheduler}->{hosts_allow} = [ 
        '127.0.0.1',
        '192.168.1.1'
    ];

=head2 check_every

This option allows you to configure how often the scheduler should check
for pending events. By default this is set to C<60> which means C<no more>
than once per 60 seconds. 

=cut

### set some defaults at start up time
sub setup {
    my $c = shift;

    # store the app, for usage in the base class
    $c->scheduler->_app( $c );

    # initial configuration
    $c->config->{scheduler}->{logging}     ||= ( $c->debug ) ? 1 : 0;
    $c->config->{scheduler}->{time_zone}   ||= $c->scheduler->_detect_timezone;
    $c->config->{scheduler}->{state_file}  ||= $c->path_to('scheduler.state');
    $c->config->{scheduler}->{yaml_file}   ||= $c->path_to('scheduler.yml');
    $c->config->{scheduler}->{hosts_allow} ||= '127.0.0.1';
    $c->config->{scheduler}->{check_every} ||= 60;

    ### make sure we run our own setup FIRST, so other plugins /could/
    ### schedule things in /their/ setup
    $c->NEXT::setup(@_);
}

### for debugging purposes
sub dump_these {
    my $c = shift;
    
    return ( $c->NEXT::dump_these(@_) ) unless @{ $c->scheduler->_events };
    
    # for debugging, we dump out a list of all events with their next
    # scheduled run time
    return ( 
        $c->NEXT::dump_these(@_),
        [ 'Scheduled Events', $c->scheduler_state ], 
    );
}

=head1 METHODS

=head2 $scheduler = MyApp->scheduler;

This the actual C<Scheduler> object that you can query for a lot of
information. See C<Catalyst::Plugin::Scheduler::Base> for usage information.

The below methods are shorthand methods on this object.

=head2 $aref = MyApp->scheduler_state

The current state of all scheduled events is available in an easy-to-use
format by calling $c->scheduler_state.  You can use this data to build an
admin view into the scheduling engine, for example.  This same data is also
displayed on the Catalyst debug screen.

This method returns an array reference containing a hash reference for each
event.

    [
        {
            'last_run'    => '2005-12-29 16:29:33 EST',
            'auto_run'    => 1,
            'last_output' => 1,
            'at'          => '0 0 * * *',
            'next_run'    => '2005-12-30 00:00:00 EST',
            'event'       => '/cron/session_cleanup'
        },
        {
            'auto_run'    => 1,
            'at'          => '0 0 * * *',
            'next_run'    => '2005-12-30 00:00:00 EST',
            'event'       => '/cron/build_rss'
        },
    ]

=head2 MyApp->schedule( event => CODE|/path, (at => CRONTIME, auto_run => BOOL) | (trigger => GET_PARAMETER) )

Schedule is a class method for adding scheduled events.  You can schedule
both automated and manual events, which are discussed below. For extended
options to C<shedule>, consult the C<Catalyst::Plugin::Scheduler::Event>
documentation on the C<new> method.

=head3 SCHEDULING AUTOMATED EVENTS

Events are scheduled by calling the class method C<schedule>.
    
    MyApp->schedule(
        at       => '0 * * * *',
        event    => '/cron/remove_sessions',
    );
    
    package MyApp::Controller::Cron;
    
    sub remove_sessions : Private {
        my ( $self, $c ) = @_;
        
        $c->delete_expired_sessions;
    }

=head4 at

The time to run an event is specified using L<crontab(5)>-style syntax.

    5 0 * * *      # 5 minutes after midnight, every day
    15 14 1 * *    # run at 2:15pm on the first of every month
    0 22 * * 1-5   # run at 10 pm on weekdays
    5 4 * * sun    # run at 4:05am every Sunday

From crontab(5):

    field          allowed values
    -----          --------------
    minute         0-59
    hour           0-23
    day of month   1-31
    month          0-12 (or names, see below)
    day of week    0-7 (0 or 7 is Sun, or use names)
    
Instead of the first five fields, one of the following special strings 
may appear:

    string         meaning
    ------         -------
    @yearly        Run once a year, "0 0 1 1 *".
    @annually      (same as @yearly)
    @monthly       Run once a month, "0 0 1 * *".
    @weekly        Run once a week, "0 0 * * 0".
    @daily         Run once a day, "0 0 * * *".
    @midnight      (same as @daily)
    @hourly        Run once an hour, "0 * * * *".
    @always        Run every minute, "* * * * *".

=head4 event

The event to run at the specified time can be either a Catalyst private
action path or a coderef.  Both types of event methods will receive the $c
object from the current request, but you must not rely on any request-specific
information present in $c as it will be from a random user request at or near
the event's specified run time.

Important: Methods used for events should be marked C<Private> so that
they can not be executed via the browser.

=head4 auto_run

The auto_run parameter specifies when the event is allowed to be executed.
By default this option is set to 1, so the event will be executed during the
first request that matches the specified time in C<at>.

If set to 0, the event will only run when a request is made by a user from
an authorized address.  The purpose of this option is to allow long-running
tasks to execute only for certain users.

    MyApp->schedule(
        at       => '0 0 * * *',
        event    => '/cron/rebuild_search_index',
        auto_run => 0,
    );
    
    package MyApp::Controller::Cron;
    
    sub rebuild_search_index : Private {
        my ( $self, $c ) = @_;
        
        # rebuild the search index, this may take a long time
    }
    
Now, the search index will only be rebuilt when a request is made from a user
whose IP address matches the list in the C<hosts_allow> config option.  To
run this event, you probably want to ping the app from a cron job.

    0 0 * * * wget -q http://www.myapp.com/

=head3 SCHEDULING MANUAL EVENTS

To create an event that does not run on a set schedule and must be manually
triggered, you can specify the C<trigger> option instead of C<at>.

    __PACKAGE__->schedule(
        trigger => 'send_email',
        event   => '/events/send_email',
    );
    
The event may then be triggered by a standard web request from an authorized
user.  The trigger to run is specified by using a special GET parameter,
'schedule_trigger'; the path requested does not matter.

    http://www.myapp.com/?schedule_trigger=send_email
    
By default, manual events may only be triggered by requests made from
localhost (127.0.0.1).  To allow other addresses to run events, use the
configuration option L</hosts_allow>.


=cut

__PACKAGE__->mk_classdata( scheduler => do { bless {}, __PACKAGE__ .'::Base'} );

{   ### convenience wrapper
    sub schedule { 
        my $c = shift;
        return $c->scheduler->schedule( 
                    scheduled_by => $c->scheduler->_caller_string, @_ );
    }    
    
    sub scheduler_state {
        my $c = shift;
        return $c->scheduler->state( @_ );
    }
}

=head1 INTERNAL METHODS

The following methods are extended by this plugin.

=over 4

=item dispatch

The main scheduling logic takes place during the dispatch phase.

=item dump_these

On the Catalyst debug screen, all scheduled events are displayed along with
the next time they will be executed.

=item setup

Configuration is initialized during setup time.

=back

=cut

### run stuff at dispatch time
sub dispatch {
    my $c = shift;

    $c->NEXT::dispatch(@_);

    $c->scheduler->_run_events;
}

### store the BLESSED $c for us to work with, at the begining of every
### request... otherwise, we just have a class name, and no request info.
sub prepare_action {
    my $c = shift;

    $c->scheduler->_app( $c );
    
    $c->NEXT::prepare_action( @_ );
}    

1;

__END__

=head1 SCHEDULING USING A YAML FILE

As an alternative to using the schedule() method, you may define scheduled
events in an external YAML file.  By default, the plugin looks for the
existence of a file called C<schedule.yml> in your application's home
directory.  You can change the filename using the configuration option
L</yaml_file>.

Modifications to this file will be re-read during the normal event checking
process, which occurs once per minute (or whatever you set C<check_every>
to in your configuration).

Here's an example YAML configuration file with 4 events.  Each event is
denoted with a '-' character, followed by the same parameters used by the
C<schedule> method.  Note that coderef events are not supported by the YAML
file.

    ---
    - at: '* * * * *'
      event: /cron/delete_sessions
    - event: /cron/send_email
      trigger: send_email
    - at: '@hourly'
      event: /cron/hourly
    - at: 0 0 * * *
      auto_run: 0
      event: /cron/rebuild_search_index
    
=head1 SECURITY

All events are run inside of an eval container.  This protects the user from
receiving any error messages or page crashes if an event fails to run
properly.  All event errors are logged, even if logging is disabled.

=head1 PLUGIN SUPPORT

Other plugins may register scheduled events if they need to perform periodic
maintenance.  Plugin authors, B<be sure to inform your users> if you do this!
Events should be registered from a plugin's C<setup> method.

    sub setup {
        my $c = shift;
        $c->NEXT::setup(@_);
        
        if ( $c->can('schedule') ) {
            $c->schedule(
                at    => '0 * * * *',
                event => \&cleanup,
            );
        }
    }



=head1 CAVEATS

The time at which an event will run is determined completely by the requests
made to the application.  Apps with heavy traffic may have events run at very
close to the correct time, whereas apps with low levels of traffic may see
events running much later than scheduled.  If this is a problem, you can use
a real cron entry that simply hits your application at the desired time.

    0 * * * * wget -q http://www.myapp.com/

Events which consume a lot of time will slow the request processing for the
user who triggers the event.  For these types of events, you should use
auto_run => 0 or manual event triggering.

=head1 PERFORMANCE

The plugin only checks once per minute (or whatever you set C<check_every>
to in your configuration) if any events need to be run, so the overhead on 
each request is minimal.  On my test server, the difference between running 
with Scheduler and without was only around 0.02% (0.004 seconds).

Of course, when a scheduled event runs, performance will depend on what's
being run in the event.
    
=head1 SEE ALSO

L<Catalyst::Plugin::Scheduler::Base>, L<Catalyst::Plugin::Scheduler::Event>, L<crontab(5)>

=head1 AUTHORS

Andy Grundman, <andy@hybridized.org>
Jos I. Boumans, <kane@cpan.org>

=head1 COPYRIGHT

This program is free software, you can redistribute it and/or modify it
under the same terms as Perl itself.

=cut

Changes:
* split out C::P::Scheduler to ::Base and ::Event
* Implement all core functionality in ::Base
    * C::P::Scheduler provides convenience functions to ::Base
      and the hooks into catalyst to do the scheduling
    * Pollute $c less
* Introduce event objects
    * No longer hash based
    * ->next_run and ->last_run are now accessors
    * running events goes via $event->run, called from the dispatch hook
* Use $self->_config to retrieve config, rather than accessing $c directly
* Add tests for schedule_state();
* Add '@always' as a cron shorcut
* made _event_state class data rather than instance data, so it is
  accessible from the ::Event objects
* made 'once every 60 seconds' check configurable using 'check_every'
  XXX add to docs
* made tests no longer need to hack the state file, but provide
  $BASE->_last_check_time( 0 ) to reset the last checked time
* Moved _event_state toe ::Event from ::Base, as it's the _event_ state
* All tested & documented

TODO:  
* fix t/09long.t to use time::warp or somesuch


