Shopify/GraphQL.pm untested

filter: Statementstmt 0.0% 0 / 150 Branchbran 0.0% 0 / 66 Conditioncond 0.0% 0 / 59 MC/DCmcdc 0.0% 0 / 32 Subroutinesub 0.0% 0 / 18 Podpod 0.0% 0 / 8 totaltotal 0.0% 0 / 333 CC 34 SCAR 46.5
CC
34
Cov
0%
internal_query
240.0
bulk_operation_query
132.0
encode_hash
30.0
CRAP 104.5
1 package WWW::Shopify::GraphQL;
2  
3 use strict;
4 use warnings;
5  
6 use JSON qw(from_json decode_json encode_json);
7 use Encode;
8 use Scalar::Util qw(blessed);
9 use Data::Dumper;
10  
11 sub new {
12 my ($package, $sa) = @_;
13 return bless {
14 _sa => $sa
15 }, $package;
16 }
17  
18 sub sa { return $_[0]->{_sa}; }
19  
20 sub encode_hash {
21 my ($self, $object) = @_;
22 return $object if !ref($object);
23 return join(" ", map { $self->encode_hash($_) } @$object) if ref($object) eq 'ARRAY';
24 return "" if int(keys(%$object)) == 0;
25 die new WWW::Shopify::Exception("Invalid GraphQL hash: " . int(keys(%$object)) . " keys present.") unless int(keys(%$object)) == 1;
26 my ($key) = keys(%$object);
27 return "$key { " . $self->encode_hash($object->{$key}) . " }";
28 }
29  
30 sub internal_query {
31 my ($self, $hash, $json) = @_;
32 my $request = HTTP::Request->new(POST => $self->sa->encode_url('/admin/api/' . $self->sa->api_version . '/graphql.json'));
33 my $content = ref($hash) ? encode("UTF-8", $self->encode_hash({ query => $hash })) : encode("UTF-8", $hash);
34 my $body = encode_json({ "query" => $content, "variables" => ($json || {}) });
35 $request->content($body);
36 $request->header('Content-Length' => length($body));
37 $request->header('Accept' => 'application/json');
38 $request->header('Content-Type' => 'application/json; charset=UTF-8');
39 my $response = $self->sa->ua->request($request);
40 print STDERR "POST " . $response->request->uri . "\n" if $ENV{'SHOPIFY_LOG'} && $ENV{'SHOPIFY_LOG'} == 1;
41 print STDERR Dumper($response) if $ENV{'SHOPIFY_LOG'} && $ENV{'SHOPIFY_LOG'} > 1;
42 # This is explicitly decode_json here. If not, the thing doesn't decode properly.
43 $content = eval { decode_json($response->decoded_content) };
44 if (!$response->is_success) {
45 print STDERR Dumper($response) if $ENV{'SHOPIFY_LOG'} && $ENV{'SHOPIFY_LOG'} > 1;
46 die WWW::Shopify::Exception::CallLimit->new($response) if $response->code() == 429;
47 die WWW::Shopify::Exception::InvalidKey->new($response) if $response->code() == 401;
48 die WWW::Shopify::Exception::NotFound->new($response) if $response->code() == 404;
49 # I honestly can't believe this.
50 die WWW::Shopify::Exception::QueryParamTooLong->new($response) if $content->{errors} && $content->{errors} =~ m/query param length is too/i;
51 die WWW::Shopify::Exception->new($response);
52 }
53 if ($content && $content->{errors}) {
54 die WWW::Shopify::Exception::CallLimit->new($response) if int(grep { $_->{message} eq "Throttled" } @{$content->{errors}}) > 0;
55 die WWW::Shopify::Exception::ExceededCost->new($response) if int(grep { $_->{extensions} && $_->{extensions}->{code} && $_->{extensions}->{code} eq 'MAX_COST_EXCEEDED' } @{$content->{errors}}) > 0;
56 # Adding this in the hope tht they have reasonable error handling someday.
57 die WWW::Shopify::Exception::QueryParamTooLong->new($response) if int(grep { $_->{message} =~ m/query param length is too/i } @{$content->{errors}}) > 0;
58 die WWW::Shopify::Exception->new($response);
59 }
60 return $content->{data} unless wantarray;
61 return ($response, $content->{data});
62 }
63  
64 sub query {
65 my ($self, $hash, $variables) = @_;
66
67 my @result;
68 while (int(@result) == 0) {
69 eval {
70 @result = $self->internal_query($hash, $variables);
71 };
72 if (my $exp = $@) {
73 if ($self->sa->sleep_for_limit && blessed($exp) && $exp->isa('WWW::Shopify::Exception::CallLimit')) {
74 sleep(1);
75 next;
76 }
77 die $exp;
78 }
79 };
80 return $result[1] unless wantarray;
81 return @result;
82 }
83  
84 use File::Temp qw(tempfile);
85 use List::Util qw(min max);
86 use IO::Handle;
87 use Fcntl qw(SEEK_SET SEEK_END SEEK_CUR);
88  
89 sub cancel_bulk_operation {
90 my ($self, $id) = @_;
91 my ($response, $result) = $self->query('mutation bulkOperationCancel($id: ID!) { bulkOperationCancel(id: $id) { bulkOperation { status } userErrors { field message } } }', { id => $id });
92 die WWW::Shopify::Exception->new($response) if int(@{$result->{bulkOperationCancel}->{userErrors}}) > 0;
93 return 1;
94 }
95  
96 sub current_bulk_operation {
97 my ($self) = @_;
98 my ($response, $result) = $self->query('query { currentBulkOperation { id status errorCode createdAt completedAt objectCount fileSize url partialDataUrl } }');
99 return undef if !$result->{currentBulkOperation} || !$result->{currentBulkOperation}->{id};
100 return $result->{currentBulkOperation};
101 }
102  
103 sub bulk_operation_query {
104 my ($self, $hash, $callback, $properties) = @_;
105 my $content = ref($hash) ? $self->encode_hash({ query => $hash }) : $hash;
106 my $query = "mutation { bulkOperationRunQuery(query: \"\"\"$content\"\"\") { bulkOperation { id status } userErrors { field message } } }";
107 my ($response, $result) = $self->query($query);
108
109 if ($properties && $properties->{cancel_running_operation} && $result->{bulkOperationRunQuery} && $result->{bulkOperationRunQuery}->{userErrors} && int(@{$result->{bulkOperationRunQuery}->{userErrors}}) > 0 &&
110 $result->{bulkOperationRunQuery}->{userErrors}->[0]->{message} =~ m/already in progress/) {
111 my $bulk_operation = $self->current_bulk_operation;
112 die WWW::Shopify::Exception->new($response) unless $bulk_operation && $bulk_operation->{status} eq "RUNNING";
113 $self->cancel_bulk_operation($bulk_operation->{id});
114 my $max_wait = 10*60;
115 my $start = DateTime->now;
116 while ($bulk_operation->{status} ne "CANCELED" && DateTime->now->epoch - $start->epoch < $max_wait) {
117 $bulk_operation = $self->current_bulk_operation;
118 sleep(5);
119 }
120 ($response, $result) = $self->query($query);
121 }
122 die WWW::Shopify::Exception->new($response) if !$result->{bulkOperationRunQuery} || !$result->{bulkOperationRunQuery}->{bulkOperation}->{status} || $result->{bulkOperationRunQuery}->{bulkOperation}->{status} ne "CREATED";
123 while (1) {
124 my ($response, $result) = $self->query('query { currentBulkOperation { id status errorCode createdAt completedAt objectCount fileSize url partialDataUrl } }');
125 die WWW::Shopify::Exception->new($response) if $result->{currentBulkOperation}->{errorCode};
126 if ($result->{currentBulkOperation}->{status} eq "COMPLETED") {
127 my $fh = tempfile();
128 $self->sa->ua->set_my_handler(response_data => sub {
129 my($response, $ua, $handler, $data) = @_;
130 print $fh $data;
131 });
132 my $response = $self->sa->ua->request(HTTP::Request->new(GET => $result->{currentBulkOperation}->{url}));
133 $fh->flush;
134 $self->sa->ua->set_my_handler(reponse_data => undef);
135 my $chunk_size = 10*1024;
136 my $buffer = "";
137 my $chunk;
138 seek($fh, -1, SEEK_END);
139 my $cursor_position = tell($fh);
140 while ($cursor_position > 0) {
141 my $to_read = $chunk_size;
142 if ($cursor_position >= $chunk_size) {
143 $cursor_position -= $chunk_size;
144 } else {
145 $to_read = $cursor_position;
146 $cursor_position = 0;
147 }
148 seek($fh, $cursor_position, SEEK_SET);
149 my $size_read = read($fh, $chunk, $to_read);
150 $buffer = $chunk . $buffer;
151 while ((my $index = rindex($buffer, "\n")) != -1) {
152 my $line = substr($buffer, $index, length($buffer) - $index + 1, "");
153 $callback->(substr($line, 1)) if length($line) > 1;
154 }
155 }
156 $callback->($buffer) if length($buffer) > 0;
157 last;
158 } else {
159 die WWW::Shopify::Exception->new($response) if $result->{currentBulkOperation}->{status} !~ /(RUNNING|CREATED)/;
160 sleep(1);
161 }
162 }
163 }
164  
165 1;