FileSync¶
FileSync uses the same transports as other rmote tools, including SSH, Docker/Kubernetes exec, local Python and prepared byte streams.
- class rmote.tools.file_sync.FileSync[source]¶
Bases:
ToolSynchronize regular files through an open asynchronous Protocol.
Call
await FileSync.upload(protocol, local_path, remote_path)orawait FileSync.download(protocol, remote_path, local_path)directly. These methods coordinate both machines locally; do not pass them as the tool argument toprotocol(...). The target needs Python but no rmote installation. Paths are interpreted on their respective sides; parent directories must already exist and symlinks/special files are rejected.The sender hashes a block with SHA-256; the receiver compares its own block at that offset and requests content only on mismatch. The final check is a hash over those signatures, so neither side reads the content twice. Blocks default to 4 MiB.
Signatures and content travel in batches, so one message serves many blocks and a long round trip is paid few times: 128 MiB of new content costs 18 calls with the default block, and 4 calls when the destination already holds it. Memory is bounded by
Session.WINDOW, not by the size of the file: a sender holds the content of one message and the blocks it signed ahead. Insertions can shift later block boundaries and cause large retransfers.Files smaller than one hashing block allow compression. For larger files, a MIME guess from the source name allows text, JSON and XML; encoded, binary and unknown formats use
protocol.uncompressedwhen available. This is a tool policy, not content inspection or a transport guarantee.The receiver assembles a temporary file beside the destination, verifies the signatures, flushes and fsyncs, then atomically replaces it. Existing destination mode/uid/gid are preserved, new files use 0600. Source timestamps, ACLs and extended attributes are not copied. Other hard links still point to the old file. Identical files retain inode and timestamps, and nothing is written for them: the temporary file appears at the first block that differs, and the blocks before it are copied from the destination. Allow free space for the complete result, even if only one block differs.
Keep both files stable: version checks detect ordinary concurrent changes but do not provide locking. Errors before replacement preserve the target. Cancellation waits for the current RPC before cleanup and can therefore wait on a stalled connection. An in-flight final replacement cannot be undone. Lost connections or abrupt process termination may leave a
.<filename>.rmote-*temporary file; retry after an ambiguous final RPC failure to establish the resulting state. There is no resume or directory synchronization, and no guarantee of durability across power loss.Example using a real local subprocess (no SSH server required):
>>> import asyncio >>> import sys >>> from pathlib import Path >>> from tempfile import TemporaryDirectory >>> from rmote.protocol import Protocol >>> async def example(): ... with TemporaryDirectory() as directory: ... root = Path(directory) ... source, target, copy = (root / n for n in ("source", "target", "copy")) ... source.write_bytes(b"hello") ... process = await asyncio.create_subprocess_exec( ... sys.executable, "-qui", stdin=asyncio.subprocess.PIPE, ... stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL, ... ) ... try: ... protocol = await Protocol.from_subprocess(process) ... async with protocol: ... first = await FileSync.upload(protocol, source, target) ... again = await FileSync.upload(protocol, source, target) ... await FileSync.download(protocol, target, copy) ... return first.changed, again.changed, copy.read_bytes() ... finally: ... if process.returncode is None: ... process.terminate() ... await process.wait() >>> asyncio.run(example()) (True, False, b'hello')
With SSH, enter
async with await Protocol.from_ssh("user@host") as protocoland use the same upload/download calls. The SSH protocol owns its process; the local subprocess example explicitly owns and reaps its child.- async static download(protocol, remote_path, local_path, *, block_size=4194304)[source]¶
Synchronize remote source content into a local destination.
- Parameters:
protocol (
Callable[...,Awaitable[Any]]) – An open async Protocol, already entered with async with.remote_path (
Text|Path) – Existing remote source file; relative to target cwd.local_path (
Text|Path) – Local destination file; relative to local cwd. Its parent must exist. A missing file is created with mode 0600.block_size (
getint) – Bytes per block, 1 through 16 MiB; defaults to 4 MiB.
- Return type:
- Returns:
SyncResult with changed status and transferred/reused byte counts.
- Raises:
ValueError – Invalid block size, special file, or failed integrity check.
RuntimeError – A file changed while being synchronized.
OSError – File access, temporary-file creation or installation fails.
ConnectionError – Closed connection; other transport errors propagate.
asyncio.CancelledError – Cancelled after the in-flight RPC and cleanup.
Uses the same exchange and atomic replacement as upload, with the remote side as sender. Call directly:
await FileSync.download(protocol, src, dst).
- async static transfer(protocol, local_path, remote_path, uploading, block_size)[source]¶
- Return type:
- async static upload(protocol, local_path, remote_path, *, block_size=4194304)[source]¶
Synchronize local source content into a remote destination.
- Parameters:
protocol (
Callable[...,Awaitable[Any]]) – An open async Protocol, already entered with async with.local_path (
Text|Path) – Existing local source file; relative to local cwd.remote_path (
Text|Path) – Remote destination file; relative to the target cwd. Its parent must exist. A missing file is created with mode 0600.block_size (
getint) – Bytes per block, 1 through 16 MiB; defaults to 4 MiB.
- Return type:
- Returns:
SyncResult with changed status and transferred/reused byte counts. Repeating the call with identical content returns changed=False.
- Raises:
ValueError – Invalid block size, special file, or failed integrity check.
RuntimeError – A file changed while being synchronized.
OSError – File access, temporary-file creation or installation fails.
ConnectionError – The connection is closed. Transport failures may also propagate their original exception.
asyncio.CancelledError – Cancelled after the in-flight RPC and cleanup.
Uses the atomic replacement and metadata policy documented on FileSync.
Strict receive decoding¶
Built-in Batch, Planned and SyncResult models are explicitly registered,
so default strict receivers need no extra configuration. A rejected reply does
not roll back an installed file. See Protocol and Tool Support for permissions.
Types¶
- class rmote.tools.file_sync.SyncResult(changed, size, transferred, reused)[source]¶
Bases:
objectSummary of a completed file synchronization.
- changed¶
Whether the destination was created or replaced. False leaves its inode and timestamps unchanged; source metadata is not copied.
- size¶
Final file size in bytes.
- transferred¶
File-content bytes sent across the connection, before compression. Excludes signatures, RPC framing and transferred code.
- reused¶
Bytes taken from the existing destination instead of the connection.
transferred + reused == sizeeven when only truncating. They are written to the temporary file only when some other block differs.
What a transfer costs¶
Measured by python -m benchmarks.file_sync on one quiet machine, with a local
subprocess as the target and a file of 128 MiB of random bytes. Every call
through the protocol is counted, so the calls are the round trips the exchange
needs. A link with a long round trip pays that time once per call.
block |
first transfer |
calls |
repeat |
calls |
|---|---|---|---|---|
1 MiB |
610 MiB/s |
18 |
1 332 MiB/s |
5 |
4 MiB |
605 MiB/s |
18 |
1 327 MiB/s |
4 |
8 MiB |
601 MiB/s |
18 |
1 292 MiB/s |
4 |
16 MiB |
482 MiB/s |
10 |
1 233 MiB/s |
4 |
One block per call cost 258, 66, 34 and 18 calls for the same four rows, and the alternating comparison at the default block gives 614 against 585 MiB/s on the first transfer and 1 320 against 1 190 MiB/s on the repeat. The block size no longer decides the number of round trips, so the default of 4 MiB fits a link with a long round trip as well.
Low-level API¶
- class rmote.tools.file_sync.Session(path, receiving, block_size, size=0)[source]¶
Bases:
objectOne sender or receiver in the block exchange used by
FileSync.Opens a regular file and keeps at most WINDOW bytes of content in memory: a sender holds the blocks it signed ahead, and gives one message of them at a time. A receiver opens a temporary file beside the destination at the first block that differs, and not at all while every block matches. Always call
close()in afinallyblock, including after successful completion. Calls on one session must be sequential. Thelockattribute keeps that order for a caller that steps the session from more than one thread; separate sessions never wait for each other.- Parameters:
path (
Text) – Source or destination path in this process’s filesystem.receiving (
bool) – True to assemble a destination, False to read a source.block_size (
getint) – Block size in bytes, from 1 through 16 MiB inclusive.size (
getint) – Expected final size for a receiver; ignored by a sender, whose size is read from the open source file.
- Raises:
ValueError – Invalid block size, negative size, or a special file.
OSError – Opening the file fails, including missing source or parent, insufficient permissions, or a symlink at the supplied path.
step()advances the exchange and returns the message for the other session. A receiver returnsSyncResultafter verifying the complete file and committing it. Application code normally usesFileSync.- ahead()[source]¶
Report how many blocks to sign in one message.
While every answered block matched, the signatures run far ahead: one costs 32 bytes and no content is expected for it. As soon as a block differs, the batch shrinks to what the window holds, so every signed block stays in memory and its content needs no second read.
- Return type:
getint
- append(data, signature=None)[source]¶
Append already verified bytes to a receiver’s temporary file.
Starts the copy if it has not started, and updates the position and the chain of signatures. Use step for normal exchange: this helper does not check a block against its signature or count it as transferred.
- Return type:
- block(offset, length)[source]¶
Read one block of the destination, which can be shorter than asked.
- Return type:
- check()[source]¶
Raise RuntimeError if the file’s identity, size or timestamps changed.
These checks detect ordinary concurrent writes; they do not lock the file or make a snapshot. Keep both files stable throughout the transfer.
- Return type:
- close()[source]¶
Close file descriptors and remove any remaining temporary file.
Does not install incomplete output or undo a completed replacement. Repeated calls are safe. Filesystem errors during cleanup propagate.
- Return type:
- commit()[source]¶
Take the planned blocks the destination already holds, in order.
A block that matched waits for the blocks before it, because the output is written in order. Only the blocks at the front of the plan can go.
- Return type:
- content()[source]¶
Read the blocks the receiver asked for, up to WINDOW bytes.
A requested block is read from the source again, because the signatures run ahead of the content and keeping that many blocks would not bound the memory. The receiver checks every block against its signature, so a source that changes between the two reads is still found.
- decide(length, signature)[source]¶
Compare one signature with the block of the destination at its place.
- Return type:
- finish(digest)[source]¶
Verify the hash over the block signatures and install the output.
All bytes must have arrived and no requested block may be outstanding. An identical destination is left untouched, and nothing was written for it. Otherwise flush and fsync the temporary file, preserve existing mode/uid/gid, and use os.replace. New files have mode 0600. The containing directory is not fsynced, so this is atomic replacement, not a power-loss durability guarantee.
- Raises:
ValueError – Incomplete transfer, wrong digest or a sender session.
RuntimeError – The destination changed during transfer.
OSError – Flushing, metadata preservation or replacement fails.
Call close afterwards to release descriptors and any temporary file.
- Return type:
- keep(length, signature)[source]¶
Account for a block the destination already holds.
Nothing is written while every block has matched: the destination already contains those bytes. Once a copy has started, the block is read from the destination and written into the copy.
- Return type:
- read(offset, length)[source]¶
Read one block of the source, or report that the source changed.
- Return type:
- receive(message)[source]¶
Write the content that arrived, then decide on the new signatures.
- Return type:
- send(decisions)[source]¶
Answer the decisions of the receiver with content and signatures.
The content of the requested blocks goes first, so the receiver can write and the memory of both sides stays inside WINDOW. New signatures travel in the same message, which keeps one round trip per message.
- Return type:
- start()[source]¶
Open the temporary file and copy the part that already matched.
A receiver whose blocks all match writes nothing, so the copy begins at the first block that differs. The bytes before it are read from the destination, whose read position is restored afterwards.
- Return type:
- step(message=None)[source]¶
Exchange a batch of signatures, the decisions on it, and content.
Start the sender with None. It returns a
Batch: the signatures of its next blocks, the content of the blocks asked for earlier, and the final hash when nothing is left. Feed the batch to the receiver. It returns one decision per signature: True means its own block matched, and False asks for the content. Pass that list back to the sender.A batch with a digest ends the stream, and the receiver then returns SyncResult. Stop exchanging messages at that point and close both sessions.
- Raises:
ValueError – Invalid signature, unexpected or corrupt content, unexpected decisions, incomplete transfer, or a final hash that does not match.
RuntimeError – Either this file or its open descriptor changed.
OSError – A read, write, fsync, metadata update or replacement fails.
- Return type:
- class rmote.tools.file_sync.Batch(signatures, blocks, digest=None)[source]¶
Bases:
objectOne message of a sender: new signatures, requested content, final hash.
- signatures¶
(length, sha256_digest)of the next blocks of the source, in block order. The receiver answers one decision for each.
- blocks¶
Content of the blocks the receiver asked for, in the order it asked for them. Its size is bounded by
Session.WINDOW.
- digest¶
The hash over every block signature, present only in the last message. The receiver then verifies and installs the file.