App-FileSync

 view release on metacpan or  search on metacpan

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

		$action->{loser_name} = $name;
	}

	return 1;
}

# _expect
# Purpose:     the one gate every path-bearing request passes.
# Entry:       $kind is a key of %MAY; $path is from the client.
# Exit:        returns the planned action for $path.
# Side effects: raises server.unplanned when the plan has no such path and
#              server.not_planned when it does not allow this request.
sub _expect :Private {
	my ($self, $kind, $path) = @_;

	my $what = $self->i18n("server.op.$kind");
	my $action = defined $path ? $self->{plan}{$path} : undef;
	$self->_throw('server.unplanned', { what => $what, path => $path // '' }) unless $action;

	my $label = $action->{a} eq 'conflict' ? "conflict:" . ($action->{winner} // '') : $action->{a};
	$self->_throw('server.not_planned', { what => $what, path => $path })
		unless any { $_ eq $label } @{ $MAY{$kind} };

	return $action;
}

# _assert_unapplied
# Purpose:     let each planned path change once per session.
# Entry:       $path passed _expect.
# Exit:        returns 1 when nothing has yet been applied to $path.
# Side effects: raises server.applied otherwise.  A second put of a conflict
#              the client won would move the client's own winning version
#              aside, and a second ack would journal the conflict twice.
#              Reads (get, sig, dsig, dop) change nothing and stay allowed.
sub _assert_unapplied :Private {
	my ($self, $path) = @_;

	$self->_throw('server.applied', { path => $path }) if $self->{applied}{$path};
	return 1;
}

# _get
# Purpose:     send one chunk of a master file the client is pulling.
# Entry:       $message has p, optional off and max.
# Exit:        returns 1 after sending the chunk.
# Side effects: reads the master; raises server.bad_field for a malformed
#              offset or size, server.not_file and io.* errors.  max is
#              clamped to MAX_CHUNK_BYTES so a client cannot ask the server to
#              buffer an entire large file.
sub _get :Private {
	my ($self, $message) = @_;

	my $path = $message->{p};
	$self->_expect('read', $path);

	my $offset = $self->_uint($message, 'off', 0);
	my $max    = $self->_uint($message, 'max', $CHUNK);
	$max = $MAX_CHUNK_BYTES if $max > $MAX_CHUNK_BYTES;

	my $abs = $self->{store}->abs_path($path);
	my $file = $self->_file_stat($abs, $path);
	$self->_throw('server.bad_field', { field => 'off', path => $path }) if $offset > $file->{s};

	my $length = $file->{s} - $offset;
	$length = $max if $length > $max;

	my $bytes = '';
	if ($length > 0) {
		my $fh = App::FileSync::IO::open_file($abs, '<:raw');
		seek($fh, $offset, 0);
		$bytes = App::FileSync::Delta::read_exact($fh, $length, $abs);
		close $fh;
	}

	$self->{conn}->send_data({ ok => 1, eof => ($offset + $length >= $file->{s}) ? 1 : 0, %{$file} }, $bytes);
	return 1;
}

# _put
# Purpose:     start receiving a whole file the client is pushing.
# Entry:       $message has p, s, h, m, mode; conflict_name is optional and,
#              when sent, must equal the plan's loser_name.
# Exit:        returns 1 after replying ok with off 0.
# Side effects: for a conflict the client won, moves the master's version
#              aside under the plan's name first - whatever the client
#              sends, so a client that omits the name cannot overwrite the
#              master's losing version.  Opens a temporary file.
sub _put :Private {
	my ($self, $message) = @_;

	my $path = $message->{p};
	my $action = $self->_expect('write', $path);
	$self->_assert_unapplied($path);

	if ($action->{a} eq 'conflict' && defined $action->{loser_name}) {
		$self->_throw('server.conflict_name', { path => $path, expected => $action->{loser_name} })
			if defined $message->{conflict_name} && $message->{conflict_name} ne $action->{loser_name};
		$self->_preserve_loser($path, $action->{loser_name}, { sha256 => $message->{h}, mtime => $message->{m} });
	}

	$self->_open_upload($path, $message);
	$self->{conn}->send({ ok => 1, off => 0 });
	return 1;
}

# _chunk
# Purpose:     receive one chunk of a whole-file upload.
# Entry:       a put for $message->{p} is open; len gives the payload size.
# Exit:        returns 1 after replying with the new offset.
# Side effects: appends to the temporary file and the running hash.
sub _chunk :Private {
	my ($self, $message) = @_;

	my $path = $message->{p} // '';
	my $upload = $self->{uploads}{$path};
	$self->_throw('server.no_put', { path => $path }) unless $upload && !$upload->{delta};

	my $length = $self->_uint($message, 'len', 0);
	$self->_throw('server.too_large', { path => $path }) if $length > $MAX_CHUNK_BYTES;

	$self->_append_upload($path, $upload, $length ? $self->{conn}->read_data($message) : '');

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


	$self->_throw('server.bad_copy', { path => $path })
		unless $length > 0 && $upload->{old_fh} && $offset + $length <= $upload->{old_size};

	seek($upload->{old_fh}, $offset, 0);
	$self->_append_upload($path, $upload, App::FileSync::Delta::read_exact($upload->{old_fh}, $length, $upload->{old}));
	$self->{conn}->send({ ok => 1, off => $upload->{got} });
	return 1;
}

# _delta_literal
# Purpose:     apply a literal record: bytes sent by the client.
# Entry:       a delta for p is open.
# Exit:        returns 1 after replying with the new offset.
# Side effects: appends to the upload.
sub _delta_literal :Private {
	my ($self, $message) = @_;

	my ($path, $upload) = $self->_open_delta($message);
	$self->_append_upload($path, $upload, $self->{conn}->read_data($message));
	$self->{conn}->send({ ok => 1, off => $upload->{got} });
	return 1;
}

# _delta_end
# Purpose:     finish a delta upload.
# Entry:       a delta for p is open.
# Exit:        returns 1 after replying ok.
# Side effects: verifies and installs the file; journals it as a delta push.
sub _delta_end :Private {
	my ($self, $message) = @_;

	my ($path, $upload) = $self->_open_delta($message);
	delete $self->{uploads}{$path};

	$self->_commit_upload($path, $upload, delta => 1);
	$self->{conn}->send({ ok => 1, delta => 1 });
	return 1;
}

# _pull_signature
# Purpose:     take the client's description of its old version and spool a
#              delta from the master's current one.
# Entry:       $message->{p} is a planned pull; n and b describe the blocks.
# Exit:        returns 1 after replying; delta 0 when a delta is not worth it.
# Side effects: reads the master file; keeps the spool for _pull_op.
sub _pull_signature :Private {
	my ($self, $message) = @_;

	my $path = $message->{p};
	$self->_expect('pull', $path);

	my $count = $self->_uint($message, 'n');
	my $block = $self->_uint($message, 'b');
	$self->_throw('server.bad_signature', { path => $path })
		unless $count <= $MAX_SIGNATURE_BLOCKS && $block >= $MIN_SIGNATURE_BLOCK && $block <= $MAX_SIGNATURE_BLOCK;

	my $blocks = App::FileSync::Delta::decode_signature($self->{conn}->read_data($message), $count);

	my $abs = $self->{store}->abs_path($path);
	my $file = $self->_file_stat($abs, $path);
	return $self->_reply({ ok => 1, delta => 0 }) if $file->{s} < $App::FileSync::Delta::MIN_SIZE;

	my $spool = File::Temp->new(UNLINK => 1);
	binmode $spool;
	my $stats = App::FileSync::Delta::diff($abs, { blocklen => $block, blocks => $blocks }, $spool);
	$spool->flush();

	# Only the literal bytes and record headers go on the wire; compression can
	# shrink them further, so this is a conservative estimate.
	my $estimated = $stats->{literal} + $DELTA_OP_BYTES * $stats->{ops} + $DELTA_OVERHEAD;
	return $self->_reply({ ok => 1, delta => 0 }) if $estimated >= $file->{s};

	seek($spool, 0, 0);
	$self->{pull_deltas}{$path} = { spool => $spool, %{$file} };
	$self->{conn}->send({ ok => 1, delta => 1, %{$file}, b => $block });
	return 1;
}

# _pull_op
# Purpose:     serve the next record of a spooled pull delta.
# Entry:       _pull_signature spooled a delta for p.
# Exit:        returns 1 after sending a copy, a literal, or done.
# Side effects: advances the spool; forgets it at the end.
sub _pull_op :Private {
	my ($self, $message) = @_;

	my $path = $message->{p} // '';
	my $state = $self->{pull_deltas}{$path} or $self->_throw('server.no_signature', { path => $path });

	my ($type, @rest) = App::FileSync::Delta::read_op($state->{spool});
	unless ($type) {
		delete $self->{pull_deltas}{$path};
		return $self->_reply({ ok => 1, done => 1 });
	}

	return $self->_reply({ ok => 1, op => 'copy', off => $rest[0], len => $rest[1] }) if $type eq 'copy';

	$self->{conn}->send_data({ ok => 1, op => 'lit' }, $rest[0]);
	return 1;
}

# _mkdir
# Purpose:     create a directory the client pushed.
# Entry:       $message->{p} is a planned push of a directory.
# Exit:        returns 1 after replying ok.
# Side effects: creates the directory in the master; records it.
sub _mkdir :Private {
	my ($self, $message) = @_;

	my $path = $message->{p};
	$self->_expect('mkdir', $path);
	$self->_assert_unapplied($path);

	App::FileSync::IO::ensure_dir($self->{store}->abs_path($path));
	$self->{index}{$path} = { t => $TYPE_DIR };
	$self->{base_after}{$path} = { t => $TYPE_DIR };
	$self->_journal({ action => 'mkdir', path => $path, result => 'ok' });

	$self->{applied}{$path} = 1;
	return $self->_reply({ ok => 1 });

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

		1;
	};
	unless ($installed) {
		my $failure = $@;
		eval { unlink $upload->{temp} } if -e $upload->{temp};
		die $failure;
	}

	my $entry = {
		t    => $TYPE_FILE,
		s    => $upload->{got},
		m    => $upload->{mtime} // time,
		h    => $hash,
		mode => $upload->{mode} // $DEFAULT_FILE_MODE,
	};
	$self->{index}{$path}      = $entry;
	$self->{base_after}{$path} = { %{$entry} };

	$self->_journal({ action => 'push', path => $path, size => $upload->{got}, sha256 => $hash, result => 'ok', %extra });
	$self->{applied}{$path} = 1;
	return $entry;
}

# _discard_upload / _discard_uploads
# Purpose:     abandon one, or every, partial upload.
# Entry:       none.
# Exit:        returns 1.
# Side effects: closes handles and removes temporary files, so a failed
#              session leaves nothing for clean_stale_temps to find an hour
#              later.
sub _discard_upload :Private {
	my ($self, $path) = @_;

	# Best effort: the session is ending or the upload was refused, so a
	# handle that will not close or a temp that will not go is not an error.
	if (my $upload = delete $self->{uploads}{$path}) {
		eval { close $_ } for grep { defined } @{$upload}{qw(fh old_fh)};
		eval { unlink $upload->{temp} };
	}

	return 1;
}

sub _discard_uploads :Private {
	my ($self) = @_;

	$self->_discard_upload($_) for keys %{ $self->{uploads} };
	return 1;
}

# _file_stat
# Purpose:     size, mtime and mode of a master file the client is reading.
# Entry:       $abs is inside the master.
# Exit:        returns { s, m, mode }.
# Side effects: raises server.cannot_stat or server.not_file.
sub _file_stat :Private {
	my ($self, $abs, $path) = @_;

	# lstat: Scan never lists a symlink, but one can appear between the plan
	# and the read, and following it would send a file outside the master.
	my @stat = Time::HiRes::lstat($abs);
	$self->_throw('server.cannot_stat', { path => $path, error => os_error() }) unless @stat;
	$self->_throw('server.not_file', { path => $path }) unless -f _;
	return { s => $stat[$STAT_SIZE], m => $stat[$STAT_MTIME], mode => $stat[$STAT_MODE] & $MODE_MASK };
}

# _uint
# Purpose:     read an unsigned integer field from a client message.
# Entry:       $default is used when the field is absent; without one the
#              field is required.
# Exit:        returns the number.
# Side effects: raises server.bad_field for anything else (a negative or
#              fractional offset, a string, a missing required field).
sub _uint :Private {
	my ($self, $message, $field, $default) = @_;

	my $value = $message->{$field} // $default;
	$self->_throw('server.bad_field', { field => $field, path => $message->{p} // '' })
		unless defined $value && $value =~ $UINT;
	return $value + 0;
}

# _journal
# Purpose:     append an event for this client.
# Entry:       $event is a hashref without client.
# Exit:        returns 1.
# Side effects: appends to the journal.
sub _journal :Private {
	my ($self, $event) = @_;

	$self->{store}->journal({ client => $self->{client}, %{$event} });
	return 1;
}

# _reply
# Purpose:     send a reply and end the handler.
# Entry:       $reply is a hashref.
# Exit:        returns 1.
# Side effects: writes to the connection.
sub _reply :Private {
	my ($self, $reply) = @_;

	$self->{conn}->send($reply);
	return 1;
}

1;

__END__

=head1 LIMITATIONS

=over 4

=item * The plan is computed once, from a scan taken while the lock is held.
Something other than filesync writing into the master during a session (an
admin's C<cp>, say) is not seen until the next session, and a file it
replaces may be overwritten.

=item * The whole client manifest is held in memory, as is the plan; a repo
with millions of paths needs memory in proportion.



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