| 1 | package Eixo::Rest::RequestAsync; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | |||
| 5 | use threads; | ||
| 6 | use Thread::Queue; | ||
| 7 | |||
| 8 | use JSON -convert_blessed_universally; | ||
| 9 | |||
| 10 | # use Eixo::Base::Clase; | ||
| 11 | use Eixo::Base::Clase 'Eixo::Rest::Request'; | ||
| 12 | |||
| 13 | use Attribute::Handlers; | ||
| 14 | use Eixo::Rest::Client; | ||
| 15 | use Carp; | ||
| 16 | |||
| 17 | use Eixo::Rest::RequestAsyncThread; | ||
| 18 | |||
| 19 | has ( | ||
| 20 | |||
| 21 | job_id=>undef, | ||
| 22 | api=>undef, | ||
| 23 | |||
| 24 | # callback=>undef, | ||
| 25 | |||
| 26 | # onProgress => undef, | ||
| 27 | # onSuccess => undef, | ||
| 28 | # onError => undef, | ||
| 29 | # onStart => undef, | ||
| 30 | |||
| 31 | thread=>undef, | ||
| 32 | queue=>undef, | ||
| 33 | |||
| 34 | ); | ||
| 35 | |||
| 36 | sub process{ | ||
| 37 | my ($self) = @_; | ||
| 38 | |||
| 39 | while(my $task = $self->queue->dequeue_nb()){ | ||
| 40 | |||
| 41 | # use Data::Dumper; print Dumper($task); | ||
| 42 | |||
| 43 | if($task->{type} eq 'PROGRESS'){ | ||
| 44 | $self->progress($task->{chunk}, $task->{req}); | ||
| 45 | } | ||
| 46 | elsif($task->{type} eq 'END'){ | ||
| 47 | $self->api->jobFinished($self); | ||
| 48 | $self->end($task->{res}); | ||
| 49 | } | ||
| 50 | else{ | ||
| 51 | $self->api->jobFinished($self); | ||
| 52 | $self->error($task->{res}); | ||
| 53 | } | ||
| 54 | } | ||
| 55 | } | ||
| 56 | |||
| 57 | sub send{ | ||
| 58 | my ($self, $ua, $req) = @_; | ||
| 59 | |||
| 60 | $self->api->newJob($self); | ||
| 61 | |||
| 62 | $self->start(); | ||
| 63 | |||
| 64 | $self->queue(Thread::Queue->new); | ||
| 65 | |||
| 66 | my $with_progress = ($self->onProgress) ? 1 : undef; | ||
| 67 | |||
| 68 | $self->thread( | ||
| 69 | |||
| 70 | threads->create( | ||
| 71 | |||
| 72 | sub { | ||
| 73 | |||
| 74 | my ($ua, $req, $queue, $with_progress) = @_; | ||
| 75 | |||
| 76 | Eixo::Rest::RequestAsyncThread->new( | ||
| 77 | |||
| 78 | |||
| 79 | ua=>$ua, | ||
| 80 | req=>$req, | ||
| 81 | queue=>$queue | ||
| 82 | |||
| 83 | )->process($with_progress); | ||
| 84 | |||
| 85 | |||
| 86 | }, $ua, $req, $self->queue, $with_progress | ||
| 87 | |||
| 88 | ) | ||
| 89 | ); | ||
| 90 | |||
| 91 | $self->thread->detach(); | ||
| 92 | |||
| 93 | $self; | ||
| 94 | } |