| 1 | package Backblaze::B2::v1::Synchronous; | ||
| 2 | use strict; | ||
| 3 | use vars qw($AUTOLOAD $VERSION); | ||
| 4 | use Carp qw(croak); | ||
| 5 | |||
| 6 | $VERSION = '0.02'; | ||
| 7 | |||
| 8 | sub isAsync { 0 } | ||
| 9 | sub api { $_[0]->{api} } | ||
| 10 | sub asyncApi { $_[0]->api } | ||
| 11 | |||
| 12 | =head1 METHODS | ||
| 13 | |||
| 14 | =head2 C<< ->new >> | ||
| 15 | |||
| 16 | Creates a new synchronous instance. | ||
| 17 | |||
| 18 | =cut | ||
| 19 | |||
| 20 | sub new { | ||
| 21 | my( $class, %options ) = @_; | ||
| 22 | |||
| 23 | require Backblaze::B2; | ||
| 24 | |||
| 25 | $options{ api_base } //= $Backblaze::B2::v1::API_BASE | ||
| 26 | = $Backblaze::B2::v1::API_BASE; | ||
| 27 | |||
| 28 | $options{ api } ||= do { | ||
| 29 | require Backblaze::B2::v1::AnyEvent; | ||
| 30 | Backblaze::B2::v1::AnyEvent->new( | ||
| 31 | api_base => $Backblaze::B2::v1::API_BASE, | ||
| 32 | %options | ||
| 33 | ); | ||
| 34 | }; | ||
| 35 | |||
| 36 | bless \%options => $class; | ||
| 37 | } | ||
| 38 | |||
| 39 | sub read_credentials { | ||
| 40 | my( $self, @args ) = @_; | ||
| 41 | $self->api->read_credentials(@args) | ||
| 42 | } | ||
| 43 | |||
| 44 | sub downloadUrl { $_[0]->api->downloadUrl }; | ||
| 45 | sub apiUrl { $_[0]->api->apiUrl }; | ||
| 46 | |||
| 47 | sub await($) { | ||
| 48 | my $promise = $_[0]; | ||
| 49 | my @res; | ||
| 50 | if( $promise->is_unfulfilled ) { | ||
| 51 | require AnyEvent; | ||
| 52 | my $await = AnyEvent->condvar; | ||
| 53 | $promise->then(sub{ $await->send(@_)}); | ||
| 54 | @res = $await->recv; | ||
| 55 | } else { | ||
| 56 | @res = @{ $promise->result } | ||
| 57 | } | ||
| 58 | @res | ||
| 59 | }; | ||
| 60 | |||
| 61 | sub AUTOLOAD { | ||
| 62 | my( $self, @arguments ) = @_; | ||
| 63 | $AUTOLOAD =~ /::([^:]+)$/ | ||
| 64 | or croak "Invalid method name '$AUTOLOAD' called"; | ||
| 65 | my $method = $1; | ||
| 66 | $self->api->can( $method ) | ||
| 67 | or croak "Unknown method '$method' called on $self"; | ||
| 68 | |||
| 69 | # Install the subroutine for caching | ||
| 70 | my $namespace = ref $self; | ||
| 71 | no strict 'refs'; | ||
| 72 | my $new_method = *{"$namespace\::$method"} = sub { | ||
| 73 | my $self = shift; | ||
| 74 | warn "In <$namespace\::$method>"; | ||
| 75 | my( $ok, $msg, @results) = await $self->api->$method( @_ ); | ||
| 76 | if( ! $ok ) { | ||
| 77 | croak $msg; | ||
| 78 | } else { | ||
| 79 | return wantarray ? @results : $results[0] | ||
| 80 | }; | ||
| 81 | }; | ||
| 82 | |||
| 83 | # Invoke the newly installed method | ||
| 84 | goto &$new_method; | ||
| 85 | }; | ||
| 86 | |||
| 87 | 1; |