| 1 | package WebSource::Queue; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use Carp; | ||
| 5 | use File::Spec; | ||
| 6 | use File::Copy; | ||
| 7 | use LockFile::Simple qw(lock trylock unlock); | ||
| 8 | use WebSource::Envelope; | ||
| 9 | use DateTime; | ||
| 10 | |||
| 11 | =head1 NAME | ||
| 12 | |||
| 13 | WebSource::Queue - Object encapusalting a filesystem based queue | ||
| 14 | |||
| 15 | =head1 DESCRIPTION | ||
| 16 | |||
| 17 | A WebSource::Queue is used to access objects saved in a filesystem based queue. | ||
| 18 | |||
| 19 | =head1 SYNOPSIS | ||
| 20 | |||
| 21 | use WebSource::Queue; | ||
| 22 | ... | ||
| 23 | my $queue = WebSource::Queue->new( | ||
| 24 | directory => $path | ||
| 25 | ... | ||
| 26 | ); | ||
| 27 | ... | ||
| 28 | $queue->enqueue($env); | ||
| 29 | ... | ||
| 30 | $queue->dequeue($env); | ||
| 31 | |||
| 32 | =head1 METHODS | ||
| 33 | |||
| 34 | =cut | ||
| 35 | |||
| 36 | sub new { | ||
| 37 | my $class = shift; | ||
| 38 | my %params = @_; | ||
| 39 | $params{directory} or croak("No directory specified for queue"); | ||
| 40 | my $self = bless \%params, $class; | ||
| 41 | return $self; | ||
| 42 | } | ||
| 43 | |||
| 44 | sub _lockfilepath { | ||
| 45 | my $self = shift; | ||
| 46 | return File::Spec->catfile($self->{directory},".lock"); | ||
| 47 | } | ||
| 48 | |||
| 49 | sub enqueue { | ||
| 50 | my ($self,$env) = @_; | ||
| 51 | lock($self->_lockfilepath); | ||
| 52 | my $dt = DateTime->now(); | ||
| 53 | my $itemname = $dt->ymd('') . $dt->hms(''); | ||
| 54 | my $itembase = File::Spec->catfile($self->{directory},$itemname); | ||
| 55 | my $itemcand = $itembase . '.itm'; | ||
| 56 | my $ext = ""; | ||
| 57 | while(-f $itemcand) { | ||
| 58 | $ext++; | ||
| 59 | $itemcand = $itembase . $ext . '.itm'; | ||
| 60 | } | ||
| 61 | $env->to_file($itemcand); | ||
| 62 | unlock($self->_lockfilepath); | ||
| 63 | } | ||
| 64 | |||
| 65 | sub dequeue { | ||
| 66 | my ($self,$env) = @_; | ||
| 67 | lock($self->_lockfilepath); | ||
| 68 | my $dir = $self->{directory}; | ||
| 69 | my $itemfile; | ||
| 70 | foreach my $cand (<${dir}*.itm>) { | ||
| 71 | if(-f $cand) { | ||
| 72 | $itemfile = $cand; | ||
| 73 | last; | ||
| 74 | } | ||
| 75 | } | ||
| 76 | if($itemfile) { | ||
| 77 | move($itemfile, $itemfile . '.process'); | ||
| 78 | $itemfile = $itemfile . '.process'; | ||
| 79 | } | ||
| 80 | unlock($self->_lockfilepath); | ||
| 81 | if($itemfile) { | ||
| 82 | return WebSource::Envelope->new_from_file($itemfile); | ||
| 83 | } else { | ||
| 84 | return undef; | ||
| 85 | } | ||
| 86 | } | ||
| 87 | |||
| 88 | =head1 SEE ALSO | ||
| 89 | |||
| 90 | WebSource | ||
| 91 | |||
| 92 | =cut | ||
| 93 | |||
| 94 | 1; |