SD/ForeignReplica.pm untested

filter: Statementstmt 0.0% 0 / 156 Branchbran 0.0% 0 / 42 Conditioncond 0.0% 0 / 13 MC/DCmcdc 0.0% 0 / 8 Subroutinesub 0.0% 0 / 28 Podpod 0.0% 0 / 21 totaltotal 0.0% 0 / 268 CC 22 SCAR 30.5
CC
22
Cov
0%
traverse_changesets
56.0
login_loop
56.0
record_pushed_transactions
30.0
CRAP 21.1
1 package App::SD::ForeignReplica;
2 use Any::Moose;
3 use Params::Validate qw/:all/;
4  
5 use Try::Tiny;
6 use URI;
7  
8 extends 'Prophet::ForeignReplica';
9  
10  
11 has uuid => (
12 lazy => 1,
13 isa => 'Str',
14 is => 'ro',
15 default => sub {
16 my $self = shift;
17 $self->uuid_for_url( $self->_uuid_url );
18 }
19 );
20  
21 =head2 save_username_and_token( $username, $token )
22  
23 Saves the given username and token to the replica-specific config file,
24 so the user doesn't have to enter it every time.
25  
26 =cut
27  
28 sub save_username_and_token {
29 my ($self, $username, $password) = @_;
30  
31 # make sure replica is initialized, since this method is generally called
32 # in the BUILD method of an object, which makes it end up being called
33 # before the initialize call in clone
34 $self->app_handle->handle->after_initialize( sub { shift->app_handle->set_db_defaults } );
35 $self->app_handle->handle->initialize;
36  
37 my $replica_username_key = 'replica.' . $self->scheme . ":" . $self->{url} . '.username';
38 my $replica_token_key = 'replica.' . $self->scheme . ":" . $self->{url} . '.secret_token';
39  
40 if ( !$self->app_handle->config->get( key => $replica_username_key ) ) {
41 print "Setting replica's username and token in the config file";
42 $self->app_handle->config->group_set(
43 $self->app_handle->config->replica_config_file,
44 [ {
45 key => $replica_username_key,
46 value => $username,
47 }, {
48 key => $replica_token_key,
49 value => $password,
50 } ],
51 );
52 }
53 }
54  
55  
56 sub integrate_changeset {
57 my $self = shift;
58 my %args = validate(
59 @_,
60 { changeset => { isa => 'Prophet::ChangeSet' },
61 resolver => { optional => 1 },
62 resolver_class => { optional => 1 },
63 resdb => { optional => 1 },
64 conflict_callback => { optional => 1 },
65 reporting_callback => { optional => 1 }
66 }
67 );
68  
69 my $changeset = $args{'changeset'};
70 return if $self->last_changeset_from_source(
71 $changeset->original_source_uuid) >= $changeset->original_sequence_no;
72 $self->SUPER::integrate_changeset(%args);
73 }
74  
75 =head2 integrate_change $change $changeset
76  
77 Given a change (and the changeset it's part of), this routine will load
78 the push encoder for the foreign replica's type and call integrate_change
79 on it.
80  
81 To avoid publishing prophet-private data, It skips any change with a record type
82 that record_type starts with '__'.
83  
84 This is probably a bug.
85  
86 =cut
87  
88 sub integrate_change {
89 my $self = shift;
90 my ( $change, $changeset ) = validate_pos(
91 @_,
92 { isa => 'Prophet::Change' },
93 { isa => 'Prophet::ChangeSet' },
94 );
95  
96 # don't push internal records
97 return if $change->record_type =~ /^__/;
98  
99  
100 Prophet::App->require( $self->push_encoder());
101 my $recoder = $self->push_encoder->new( { sync_source => $self } );
102 $recoder->integrate_change($change,$changeset);
103 }
104  
105 =head2 record_pushed_transactions
106  
107 Walk the set of transactions on the ticket whose id you've passed in, looking
108 for updates by the 'current user' which happened after start_time and before
109 now. Then mark those transactions as ones that originated in SD, so we don't
110 accidentally push them later.
111  
112 =over
113  
114 =item ticket
115  
116 =item changeset
117  
118 =item start_time
119  
120 =back
121  
122 =cut
123  
124 sub record_pushed_transactions {
125 my $self = shift;
126 my %args = validate( @_,
127 { ticket => 1,
128 changeset => { isa => 'Prophet::ChangeSet' }, start_time => 1} );
129  
130 my $earliest_valid_txn_date;
131  
132 # walk through every transaction on the ticket, starting with the latest
133  
134 for my $txn ( $self->get_txn_list_by_date($args{ticket}) ) {
135 # walk backwards through all transactions on the ticket we just updated
136 # Skip any transaction where the remote user isn't me, this might
137 # include any transaction RT created with a scrip on your behalf
138  
139 next unless $txn->{creator} eq $self->foreign_username;
140  
141 # get the completion time _after_ we do our next round trip to rt to
142 # try to make sure a bit of lag doesn't skew us to the wrong side of a
143 # 1s boundary
144 if (!$earliest_valid_txn_date){
145 my $change_window = time() - $args{start_time};
146 # skip any transaction created more than 5 seconds before the push
147 # started. I can't think of any reason that number shouldn't be 1,
148 # but clocks are fickle
149 $earliest_valid_txn_date = $txn->{created} - ($change_window + 5);
150 }
151  
152 last if $txn->{created} < $earliest_valid_txn_date;
153  
154 # if the transaction id is older than the id of the last changeset
155 # we got from the original source of this changeset, we're done
156 last if $txn->{id} <= $self->app_handle->handle->last_changeset_from_source(
157 $args{changeset}->original_source_uuid);
158  
159 # if the transaction from RT is more recent than the most recent
160 # transaction we got from the original source of the changeset
161 # then we should record that we sent that transaction upstream
162  
163 $self->record_pushed_transaction(
164 transaction => $txn->{id},
165 changeset => $args{'changeset'},
166 record => $args{'ticket'}
167 );
168 }
169 }
170  
171  
172 =head2 record_pushed_transaction $foreign_transaction_id, $changeset
173  
174 Record that this replica was the original source of $foreign_transaction_id
175 (with changeset $changeset)
176  
177 =cut
178  
179 sub record_pushed_transaction {
180 my $self = shift;
181 my %args = validate( @_,
182 { transaction => 1, changeset => { isa => 'Prophet::ChangeSet' },
183 record => 1 } );
184  
185 my $key = join('-', "foreign-txn-from" , $self->uuid ,
186 'record' , $args{record} , 'txn' , $args{transaction} );
187 my $value = join(':', $args{changeset}->original_source_uuid,
188 $args{changeset}->original_sequence_no );
189  
190 $self->store_local_metadata($key => $value);
191  
192 }
193  
194 =head2 foreign_transaction_originated_locally $transaction_id $foreign_record_id
195  
196 Given a transaction id, will return true if this transaction
197 originated in Prophet and was pushed to the foreign replica or
198 originated in the foreign replica and has already been pulled to
199 the Prophet replica.
200  
201  
202 This is a mapping of all the transactions we have pushed to the
203 remote replica we'll only ever care about remote sequence #s greater
204 than the last transaction # we've pulled from the remote replica
205 once we've done a pull from the remote replica, we can safely expire
206 all records of this type for the remote replica (they'll be
207 obsolete)
208  
209 We use this cache to avoid integrating changesets we've pushed to the
210 remote replica when doing a subsequent pull
211  
212 =cut
213  
214 sub foreign_transaction_originated_locally {
215 my $self = shift;
216 my ( $id, $record ) = validate_pos( @_, 1, 1 );
217 return $self->fetch_local_metadata(
218 "foreign-txn-from-" . $self->uuid . '-record-' . $record . '-txn-' . $id );
219 }
220  
221 sub traverse_changesets {
222 my $self = shift;
223 my %args = validate( @_,
224 { after => 1,
225 callback => 1,
226 before_load_changeset_callback => { type => CODEREF, optional => 1},
227 reporting_callback => { type => CODEREF, optional => 1 },
228 }
229 );
230  
231 Prophet::App->require( $self->pull_encoder());
232 my $recoder = $self->pull_encoder->new( { sync_source => $self } );
233 my ( $changesets ) = $recoder->run( after => $args{'after'} );
234 for my $changeset (@$changesets) {
235 if ( $args{'before_load_changeset_callback'} ) {
236 my $continue = $args{'before_load_changeset_callback'}->(
237 changeset_metadata => $self->_construct_changeset_index_entry($changeset)
238 );
239  
240 next unless $continue;
241 }
242  
243 $args{callback}->(
244 changeset => $changeset,
245 after_integrate_changeset => sub {
246 $self->record_last_changeset_from_replica(
247 $changeset->original_source_uuid => $changeset->original_sequence_no );
248  
249 # We're treating each individual ticket in the foreign system
250 # as its own 'replica' because of that, we need to hint to the
251 # push side of the system what the most recent txn on each
252 # ticket it has.
253 my $previously_modified
254 = App::SD::Util::string_to_datetime(
255 $self->upstream_last_modified_date || '');
256 my $created_datetime = App::SD::Util::string_to_datetime(
257 $changeset->created );
258 $self->record_upstream_last_modified_date( $changeset->created )
259 if ( ( $created_datetime ? $created_datetime->epoch : 0 )
260 > ( $previously_modified ? $previously_modified->epoch : 0 ) );
261 }
262 );
263 $args{reporting_callback}->($changeset) if ($args{reporting_callback});
264 }
265 }
266  
267 sub _construct_changeset_index_entry {
268 my $self = shift;
269 my $changeset = shift;
270  
271 return [ $changeset->sequence_no, $changeset->original_source_uuid,
272 $changeset->original_sequence_no, $changeset->calculate_sha1 ];
273 }
274  
275 sub remote_uri_path_for_id {
276 die "your subclass needs to implement this to be able to ".
277 "map a remote id to /ticket/id or soemthing";
278 }
279  
280 =head2 uuid_for_remote_id $id
281  
282 lookup the uuid for the remote record id. If we don't find it,
283 construct it out of the remote url and the remote uri path for the record id;
284  
285 =cut
286  
287 sub uuid_for_remote_id {
288 my ( $self, $id ) = @_;
289  
290 return $self->_lookup_uuid_for_remote_id($id)
291 ||$self->_url_based_uuid_for_remote_ticket_id( $id);
292 }
293  
294 sub _lookup_uuid_for_remote_id {
295 my $self = shift;
296 my ($id) = validate_pos( @_, 1 );
297  
298 return $self->fetch_local_metadata(
299 'local_uuid_for_'. $self->_url_based_uuid_for_remote_ticket_id($id));
300 }
301  
302 sub _set_uuid_for_remote_id {
303 my $self = shift;
304 my %args = validate( @_, { uuid => 1, remote_id => 1 } );
305 return $self->store_local_metadata('local_uuid_for_'.
306 $self->_url_based_uuid_for_remote_ticket_id( $args{'remote_id'} ),
307 $args{uuid}
308 );
309 }
310  
311 sub _url_based_uuid_for_remote_ticket_id {
312 my $self = shift;
313 my $id = shift;
314  
315 return $self->uuid_for_url(
316 $self->remote_url
317 . $self->remote_uri_path_for_id( $id )
318 );
319 }
320  
321 # This mapping table stores uuids for tickets we've synced from a remote
322 # database Basically, if we created the ticket to begin with, then we'll know
323 # its uuid if we pulled the ticket from the foreign replica then its uuid will
324 # be generated based on a UUID-from-ticket-url scheme
325  
326 sub remote_id_for_uuid {
327 my ( $self, $uuid_or_luid ) = @_;
328  
329 require App::SD::Model::Ticket;
330 my $ticket = App::SD::Model::Ticket->new(
331 app_handle => $self->app_handle,
332 type => 'ticket'
333 );
334 $ticket->load( $uuid_or_luid =~ /^\d+$/? 'luid': 'uuid', $uuid_or_luid )
335 or do {
336 warn "couldn't load ticket #$uuid_or_luid";
337 return undef;
338 };
339  
340 my $prop = $self->uuid . '-id';
341 my $id = $ticket->prop( $prop )
342 or warn "ticket #$uuid_or_luid has no property '$prop'";
343 return $id;
344 }
345  
346 sub _set_remote_id_for_uuid {
347 my $self = shift;
348 my %args = validate(
349 @_,
350 { uuid => 1,
351 remote_id => 1
352 }
353 );
354  
355 require App::SD::Model::Ticket;
356 my $ticket = App::SD::Model::Ticket->new(
357 app_handle => $self->app_handle,
358 type => 'ticket'
359 );
360 $ticket->load( uuid => $args{'uuid'} );
361 $ticket->set_props( props => { $self->uuid.'-id' => $args{'remote_id'} } );
362 }
363  
364 =head2 record_remote_id_for_pushed_record
365  
366 When pushing a record created within the prophet cloud to a foreign replica, we
367 need to do bookkeeping to record the prophet uuid to remote id mapping.
368  
369 =cut
370  
371 sub record_remote_id_for_pushed_record {
372 my $self = shift;
373 my %args = validate(
374 @_,
375 { uuid => 1,
376 remote_id => 1
377 }
378 );
379 $self->_set_uuid_for_remote_id(%args);
380 $self->_set_remote_id_for_uuid(%args);
381 }
382  
383 sub record_upstream_last_modified_date {
384 my $self = shift;
385 my $date = shift;
386 return $self->store_local_metadata('last_modified_date' => $date);
387 }
388  
389 sub upstream_last_modified_date {
390 my $self = shift;
391 return $self->fetch_local_metadata('last_modified_date');
392 }
393  
394 =head2 login_loop
395  
396 Loop on prompting for username/password until login is successful; user can
397 abort with ^C.
398  
399 Saves username and password to the replica's configuration file
400 upon successful login.
401  
402 params:
403 - uri # login url
404 - username # optional; a pre-seeded username
405 - password # optional; a pre-seeded password
406 - username_prompt # optional; custom username prompt
407 - secret_prompt # optional; custom secret prompt
408 - login_callback # coderef of code that attempts login; should throw exception
409 # on error
410 - catch_callback # optional; process thrown exception message (e.g. munge
411 # in some way and then print to STDERR)
412  
413 returns: ($username, $password)
414  
415 =cut
416  
417 sub login_loop {
418 my $self = shift;
419 my %args = @_;
420  
421 my $login_successful = 0;
422 my ($username, $password);
423  
424 my %login_args = ( uri => $args{uri}, username => $username );
425 $login_args{username_prompt} = $args{username_prompt}
426 if $args{username_prompt};
427 $login_args{secret_prompt} = $args{secret_prompt}
428 if $args{secret_prompt};
429 # allow prompting for just password if username already specified
430 # and vice-versa for password
431 # if both are specified, we still want to loop in case the
432 # credentials are wrong
433 $login_args{username} = $args{username} if $args{username};
434 $login_args{password} = $args{password} if $args{password};
435  
436 while (!$login_successful) {
437 ( $username, $password ) = $self->prompt_for_login(%login_args);
438  
439 try {
440 $args{login_callback}->($self, $username, $password);
441 $login_successful = 1;
442 } catch {
443 if ($args{catch_callback}) {
444 $args{catch_callback}->($_);
445 }
446 else {
447 warn "\n$_\n\n";
448 }
449 # in the case of a failed login, reset username/password
450 # to nothing so we re-prompt for both in the case of
451 # having used saved values
452 ($login_args{username}, $login_args{password}) = (undef, undef);
453 };
454 $self->foreign_username($username) if ($username);
455 }
456 # only save username/password if login was successful
457 $self->save_username_and_token( $username, $password );
458  
459 return ($username, $password);
460 }
461  
462 =head2 extract_auth_from_uri( $uri_string )
463  
464 Given a server URI string, possibly containing auth info, extract the
465 auth info if it exists.
466  
467 Also sets the remote_url and url attribute to the server URI with the auth
468 information removed.
469  
470 returns: ($username, $password)
471  
472 =cut
473  
474 sub extract_auth_from_uri {
475 my ($self, $uri_string) = @_;
476  
477 my $uri = URI->new($uri_string);
478 my ($username, $password);
479  
480 if ( $uri->can('userinfo') && ( my $auth = $uri->userinfo ) ) {
481 ( $username, $password ) = split /:/, $auth, 2;
482 $uri->userinfo(undef);
483 }
484 $self->remote_url("$uri");
485 $self->url("$uri");
486  
487 return ($username, $password);
488 }
489  
490 sub foreign_username {
491 die "replica class must implement foreign_username";
492 }
493  
494 __PACKAGE__->meta->make_immutable;
495 no Any::Moose;
496  
497 1;