App-FileSync

 view release on metacpan or  search on metacpan

lib/App/FileSync/Client.pm  view on Meta::CPAN

#              symlink or an empty directory; a directory that still holds
#              untracked files goes to the local trash); records the new
#              entry in $after.  A mismatch removes the temporary file and
#              raises.
sub _finish_pull :Private {
	my ($self, $connection, $action, $after, $abs, $receipt) = @_;

	my ($path, $server, $got) = ($action->{p}, $receipt->{server}, $receipt->{hash});
	my $expected = $action->{h} // $server->{h};

	my ($key, %args) =
		  (defined $expected && $got ne $expected) ? ('client.hash_mismatch', expected => $expected, got => $got)
		: (defined $server->{s} && $receipt->{written} != $server->{s}) ? ('client.size_mismatch', expected => $server->{s}, got => $receipt->{written})
		: ();
	if ($key) {
		eval { unlink $receipt->{temp} };
		$self->_throw($key, { path => $path, %args });
	}
	unless (eval { $self->_assert_unchanged($path, $abs) }) {
		my $error = $@;
		eval { unlink $receipt->{temp} };
		die $error;	## no critic (ErrorHandling::RequireCarping) -- rethrow unchanged
	}

	# A directory where the file goes still holds what the sync does not list
	# (ignored files): its listed contents were deleted earlier in this plan.
	# Keep it in the local trash rather than refuse the file, which would fail
	# this and every later sync.
	if (-d $abs && !-l $abs && @{ list_dir($abs) || [$abs] }) {
		$self->_delete_local($path);
		$self->{logger}->warn($self->i18n('client.dir_replaced', { path => $path, trash => $self->_trash_root() }));
	}

	install_file($receipt->{temp}, $abs, $server->{m}, $server->{mode});

	my %entry = (h => $got, s => $receipt->{written}, m => $server->{m}, mode => $server->{mode});
	$self->_request($connection, { cmd => 'ack', p => $path, %entry }, 'client.req.ack', { path => $path });
	$after->{$path} = { t => $TYPE_FILE, %entry };
	return 1;
}

# _push
# Purpose:     send a local file (or directory) the plan says to push.
# Entry:       $action has p, t, h and, for a conflict this side won,
#              loser_name.
# Exit:        returns 1.
# Side effects: transfers the file, as a delta when that is cheaper (never
#              for a conflict, where the server must first move its version
#              aside).
sub _push :Private {
	my ($self, $connection, $action) = @_;

	my $path = $action->{p};
	my $abs  = $self->_abs($path);

	if (($action->{t} || $TYPE_FILE) eq $TYPE_DIR) {
		$self->_request($connection, { cmd => 'mkdir', p => $path }, 'client.req.mkdir', { path => $path });
		return 1;
	}

	my @stat = Time::HiRes::stat($abs);
	$self->_throw('client.cannot_stat', { path => $abs, error => os_error() }) unless @stat;
	my %file = (s => $stat[$STAT_SIZE], m => $stat[$STAT_MTIME], mode => $stat[$STAT_MODE] & $MODE_MASK);

	return 1 if !$action->{loser_name} && $self->_push_delta($connection, $path, $abs, \%file, $action->{h});

	my $in = open_file($abs, '<:raw');

	# The server acknowledges the header before any chunk is sent; reading it
	# here keeps the lock-step protocol aligned.
	$self->_request($connection, {
		cmd => 'put', p => $path, t => $TYPE_FILE, %file, h => $action->{h},
		($action->{loser_name} ? (conflict_name => $action->{loser_name}) : ()),
	}, 'client.req.put', { path => $path });

	while (read($in, my $buffer, $CHUNK)) {
		$self->_request($connection, { cmd => 'chunk', p => $path }, 'client.req.chunk', { path => $path }, $buffer);
	}
	close $in;

	$self->_request($connection, { cmd => 'chunk_end', p => $path }, 'client.req.store', { path => $path });
	return 1;
}

# _push_delta
# Purpose:     send only the blocks that changed since the master's version.
# Entry:       %{$file} has s, m, mode; $hash is the planned hash.
# Exit:        returns 1 if pushed as a delta, 0 when a whole-file put is
#              cheaper or there is nothing to reuse.
# Side effects: spools the delta to a temporary file beside $abs.
sub _push_delta :Private {
	my ($self, $connection, $path, $abs, $file, $hash) = @_;

	return 0 if $self->{opts}{no_delta} || !defined $hash || $file->{s} < $App::FileSync::Delta::MIN_SIZE;

	my $reply = $self->_request($connection, { cmd => 'sig', p => $path }, 'client.req.signature', { path => $path });
	return 0 unless $reply->{delta};

	my $blocks = App::FileSync::Delta::decode_signature($connection->read_data($reply), $reply->{n});

	my $spool = File::Temp->new(TEMPLATE => "${TEMP_PREFIX}delta-XXXXXXXX", DIR => dirname($abs), UNLINK => 1);
	binmode $spool;
	my $stats = App::FileSync::Delta::diff($abs, { size => $reply->{s}, blocklen => $reply->{b}, blocks => $blocks }, $spool);

	my $estimated = $stats->{literal} + $DELTA_OP_BYTES * $stats->{ops} + $DELTA_OVERHEAD;
	return 0 if $estimated >= $file->{s};

	$self->_request($connection, { cmd => 'delta', p => $path, %{$file}, h => $hash }, 'client.req.delta', { path => $path });

	seek($spool, 0, 0);
	while (my ($type, @rest) = App::FileSync::Delta::read_op($spool)) {
		my ($message, $bytes) = $type eq 'copy'
			? ({ cmd => 'dcopy', p => $path, off => $rest[0], len => $rest[1] })
			: ({ cmd => 'dlit', p => $path }, $rest[0]);
		$self->_request($connection, $message, 'client.req.delta_data', { path => $path }, $bytes);
	}

	$self->_request($connection, { cmd => 'delta_end', p => $path }, 'client.req.store', { path => $path });
	$self->{delta_pushed}++;
	return 1;
}

lib/App/FileSync/Client.pm  view on Meta::CPAN

		eval { rename $abs, $conflict; 1 }
			or $self->_throw('client.conflict_move', { path => $path, to => $loser, error => os_error($@) });
		$after->{$loser} = delete $after->{$path};
	}

	return $self->_pull($connection, \%winner, $after);
}

# _refuse_unreadable_deletes
# Purpose:     stop a sync whose plan would delete from the server what this
#              side merely could not read.
# Entry:       $actions is the plan; $unreadable and $skipped come from the
#              scan.  A path the scan could not read (or one below a
#              directory it could not list) is missing from the manifest, so
#              the plan takes it for a deletion.
# Exit:        returns 1 when no planned deletion is under an unreadable path.
# Side effects: raises client.unreadable_delete, naming the first such path,
#              how many there are, and the unreadable path with its reason,
#              before anything is applied.
sub _refuse_unreadable_deletes :Private {
	my ($self, $actions, $unreadable, $skipped) = @_;

	my @dark = sort keys %{ $unreadable || {} };
	return 1 unless @dark;

	my $under = sub {
		my ($path) = @_;
		return first { $_ eq '.' || $path eq $_ || index($path, "$_/") == 0 } @dark;
	};
	my @blocked = grep { defined $_->[1] }
		map { [ $_->{p}, $under->($_->{p}) ] } grep { $_->{a} eq 'delete_remote' } @{$actions};
	return 1 unless @blocked;

	my ($path, $dark) = @{ $blocked[0] };
	$self->_throw('client.unreadable_delete', {
		count  => scalar @blocked,
		path   => $path,
		dir    => $dark,
		reason => $skipped->{$dark} // '',
	});
}

# _assert_unchanged
# Purpose:     refuse to replace or delete a local path that changed after
#              the scan, so an edit made while the sync runs is never lost.
# Entry:       $path is relative, $abs its local path; {scanned} and
#              {skipped} are from this session's scan.
# Exit:        returns 1 when the path is as the scan saw it: absent, a
#              directory (a full one goes to the local trash instead), a path
#              the scan skipped, or a file with the scanned size and mtime.
#              Without a scan (a caller outside a session) there is nothing
#              to compare against, so it returns 1.
# Side effects: raises client.changed_during_sync otherwise.  The next sync
#              scans again and plans the change (as a conflict, if the master
#              changed too).  An edit that keeps both size and mtime is not
#              seen.
sub _assert_unchanged :Private {
	my ($self, $path, $abs) = @_;

	return 1 unless $self->{scanned};
	my @now = Time::HiRes::lstat($abs);
	return 1 if !@now || -d _ || exists $self->{skipped}{$path};

	my $seen = $self->{scanned}{$path};
	return 1 if $seen && ($seen->{t} || '') eq $TYPE_FILE
		&& $now[$STAT_SIZE] == $seen->{s} && $now[$STAT_MTIME] == $seen->{m};

	$self->_throw('client.changed_during_sync', { path => $path });
}

# _delete_local
# Purpose:     remove a local path the master deleted.
# Entry:       $path is relative.
# Exit:        returns 1.
# Side effects: moves the path into this repo's local trash.
sub _delete_local :Private {
	my ($self, $path) = @_;

	# A file already gone needs nothing; a dangling symlink is still moved.
	my $abs = $self->_abs($path);
	App::FileSync::Trash::move_to_trash(src => $abs, rel => $path, root => $self->_trash_root(), epoch => time)
		if -e $abs || -l $abs;

	return 1;
}

# _request
# Purpose:     one lock-step exchange: send, receive, insist on ok.
# Entry:       $key is the catalogue key for a refusal, $args its arguments;
#              $bytes, when defined, is sent as a data payload.
# Exit:        returns the reply.
# Side effects: raises $key with the server's reason.
sub _request :Private {
	my ($self, $connection, $message, $key, $args, $bytes) = @_;

	defined $bytes ? $connection->send_data($message, $bytes) : $connection->send($message);
	my $reply = $connection->recv();
	$self->_throw($key, { %{$args}, reason => $reply->{error} || $self->i18n('client.unknown_reason') })
		unless $reply->{ok};

	return $reply;
}

# _abs
# Purpose:     the local path for a relative path from the server.
# Entry:       $path came over the wire.
# Exit:        returns ROOT/path.
# Side effects: raises client.unsafe for a path that could escape the root,
#              and client.symlink when a directory on the way is a symlink.
#              Scan never lists what is under a symlink, so such a path can
#              only come from another client's tree: writing or deleting
#              through the link would reach outside the sync root.
sub _abs :Private {
	my ($self, $path) = @_;

	my ($ok, $reason) = validate_relpath($path);
	$self->_throw('client.unsafe', { path => $path // '', reason => $reason }) unless $ok;

	my @parts = split m{/}, $path;
	my $current = $self->_repo_config()->{root};
	for my $part (@parts[ 0 .. $#parts - 1 ]) {



( run in 1.811 second using v1.01-cache-2.11-cpan-eb134014566 )