Python streams and mappings
Use byte streams for generated data or incremental reads, and mappings to choose each entry’s source and destination. See the Python guide for examples and the operations reference for client configuration and shared arguments. Results and exceptions apply across these interfaces.
Byte streams
Use a byte stream to write one destination or read one source from your own code, without a temporary file. Streams follow the CLI’s descriptor-copy rules for permissions, metadata, and which endpoints work. They are sequential and not seekable, and start over if interrupted.
client.open_writer(*, as_=None, as_new=None, as_existing=None, to=None, follow_dst=False, ...) returns a StreamWriter. Give exactly one of as_,
as_new, or as_existing.
client.open_reader(src, *, from_=None, cwd=None, root=None, follow_src=False, ...)
returns a StreamReader. cwd and root work as in cp; give at most one.
Both also accept these cp arguments: rsh, syq_path, pscope,
no_bootstrap, no_compress, no_tcp, no_tcp_encryption, tcp_ports,
tcp_congestion, auth_from, s3_endpoint, s3_region, s3_profile,
s3_header, s3_retries, performance_tuning, resource_limits,
integrity_checking, if_exists, dry_run, stats, verbose, quiet,
progress, no_progress, and timeout. open_writer also accepts
s3_write_header. Only some tuning settings apply; see
descriptor copy limits.
A stream always raises on a transfer failure; it has no check argument.
| Object | Operations |
|---|---|
StreamWriter | write(bytes) writes the whole buffer and returns its length; flush() does nothing; close() ends the input without publishing; commit() publishes and waits for success; abort() cancels |
StreamReader | read(size=-1) and readinto(buffer), where read() with no size reads everything left into memory and returns once the transfer succeeds; close() reads the rest and waits for success; abort() cancels |
Writer completion
Use a with block: the writer publishes when the block exits without an
exception. An exception inside either block cancels the transfer and propagates
unchanged; a cancelled writer leaves its destination as it was. Calling
close() in the block does not stop publication; only abort() does. If you
wrap the writer in io.BufferedWriter or io.TextIOWrapper, close the wrapper
before the writer commits, so its buffered data is written.
Without a with block, finish with commit() or abort(); after close()
alone, the transfer stays pending, and an uncommitted writer is aborted only
when it is garbage-collected, which can block. commit() publishes at once, so
a later error in your program cannot undo it. If a timeout or lost connection
interrupts it, commit() raises without knowing whether the file was published.
Skips and previews
open_writer returns before the destination is ready, so setup errors can
appear at write() or commit(). With if_exists="keep" or dry_run=True,
it waits for syq’s decision instead; check output.skipped before producing
data:
with client.open_writer(to="server", as_="archive.tar", if_exists="keep") as output:
if not output.skipped:
produce_archive(output)
A skipped writer rejects write(), and its block exits without publishing. A
skipped reader returns no data, and its skipped is set once it completes.
With dry_run=True, entering and leaving the block checks placement without
transferring data: writers reject write(), readers return nothing, and the
result has the planned totals.
Results and failures
After completion, stream.result holds a CpResult, or None if syq never
reported one, as after a forced kill.
read(size) can return data before a later transfer error, so treat the data
as complete only when the reader’s block exits without an exception.
timeout covers the stream’s whole life, including time blocked in reads and
writes, and raises subprocess.TimeoutExpired unless the transfer already
succeeded. A failed transfer raises SyqProcessError, whose result holds the
exit status and the last 8 KiB of diagnostics. The stream’s stderr holds the
same bytes, also after success; for example, pass stats=True and read
output.stderr.decode() after the writer’s block.
Async streams
Async streams use async with and await reads, writes, and closing:
client = syq.AsyncClient()
async with client.open_writer(to="server", as_="generated.bin") as output:
await output.write(b"generated bytes")
async with client.open_reader("generated.bin", from_="server") as source:
while chunk := await source.read(65536):
await consume(chunk)
An async stream starts when its block is entered, and cancellation stops the
transfer. Their read or write, close, abort, and (on writers) commit
methods are coroutines.
map
map(*sources, **options) → MapStream lists source entries without copying,
locally or from from_="server" or from_="s3://bucket". Besides the shared
arguments, it accepts as_ to rename one selected object, and include, an
iterable of the extra fields to add to each entry: kind, size, mtime, or
s3_last_modified. where, srcs_in, and these fields work as for
syq map.
The connection options are auth_from, rsh, syq_path, no_bootstrap,
pscope, s3_endpoint, s3_region, s3_profile, and s3_header. The
mapping keeps the ones you pass and uses them when you copy it, so here the
copy reaches the same service as the listing:
with client.map(from_="s3://photos", srcs_in="originals",
s3_endpoint="https://objects.example.com",
s3_region="us-east-1") as mapping:
client.cp(mapping=mapping, into="restored")
s3_retries applies only to the listing; pass it to cp too if the copy needs
it.
Use a MapStream in a with block and an AsyncMapStream in async with,
and consume it inside the block; it cannot be reused afterwards. Reading it to
the end checks that the listing succeeded, and leaving the block early stops
the listing.
Mapping and AsyncMapping
A Mapping holds entries together with their source machine, base
directory, and the connection options you passed, so cp(mapping=...) reads
the same sources on any client, even one with another process_cwd.
Mapping(entries, *, from_=None, cwd=None, root=None, follow_src=False, **connection_options) takes an iterable of MappingEntry, and
AsyncMapping(...) an async iterable, with the connection options listed for
map. Give at most one of cwd and root. A local base is resolved when you
create the mapping, against the Python process’s directory rather than
process_cwd; a remote base is left for the source machine to interpret.
| Member | Type | Meaning |
|---|---|---|
from_ | str or None | Source endpoint; None means local |
cwd | pathlib.Path or str | Absolute local base, or the remote base as given |
root | pathlib.Path, str, or None | Confining base, when created with root |
follow_src | bool | Whether the copy follows source symlinks |
transform(function) | Mapping or AsyncMapping | A new mapping with the same sources that applies function to each entry as it is read |
function receives each MappingEntry and returns a replacement, or None
to drop it; transforms can be chained, and an async mapping’s function can be
async. Mappings do not store entries, so whether you can read one twice depends
on the iterable you supplied.
When you copy a mapping that knows its sources, do not pass from_, cwd,
root, or a conflicting connection option. Settings the mapping does not carry
come from the copy’s environment and configuration, so pass s3_endpoint
explicitly if the copy must reach the same service as the listing. The mapping
holds no credentials or data; cp reads the sources again.
cp(mapping=...) reads the whole mapping before copying, so if iterating,
transforming, or encoding entries fails, nothing is copied. A plain iterable or
a manifest path does not know its sources; pass cwd, root, or from_ with
it. See mapping rules.
Callback mappings
Use callbacks to produce or consume an entry’s bytes in your own code.
StreamSource(produce, *, size=None) produces one entry’s bytes, and
StreamDestination(consume) receives them; use either or both as the src and
dst of a MappingEntry whose kind is None or "file". Callbacks work
only in a cp(mapping=...) call, not in a saved manifest.
Entries with paths copy first; then up to stream_concurrency callback
entries run at once. A failed entry does not undo the others.
A producer gets a writable binary file object. Its entry is published only if
it returns normally, and cancelled if it raises, even after closing the file
object. A consumer gets a readable one. Reading to the end checks that the
transfer succeeded; if the consumer returns early, the SDK reads and checks the
rest, and if it raises, the remaining work is cancelled. Syq cannot undo what a
consumer did, so write extracted files to a staging directory and publish it
after cp succeeds.
Client runs callbacks on worker threads. AsyncClient also accepts
async def callbacks, which await read, write, and close on your event
loop. Cancellation interrupts blocked reads and writes, but code that computes
without I/O must check for cancellation itself.
StreamSource(size=...) promises the exact byte count, and a mismatch fails
the entry before publication; MappingEntry.size stays informational.
expected_hash is checked as the bytes transfer, and metadata sets a named
destination’s attributes without copy_metadata.
A skip policy or dry run never calls the callbacks of entries it excludes,
but a selected callback always transfers. Callback mappings cannot use hash,
content comparison, in_place, pruning, or ignore rules; leave unwanted
entries out instead. Callbacks run on this machine, so a mapping that also
copies paths between two SSH servers needs coordinate_at="local".
Each callback entry is reported as a MappingStreamResult event, using
automation schema version 5:
entry: int # zero-based index in your mapping
source: PathValue | None # None for a callback
destination: PathValue | None # None for a callback
disposition: str # "succeeded", "failed", "skipped", or "planned"
dry_run: bool
bytes: int | None
message: str | None # on failure
Callbacks are never rerun automatically; to retry, build a new mapping from the indices of the failed entries.
Hash and HashAlgorithm
To require known contents for a mapped file, give its entry an expected_hash.
Hash(algorithm, value) is the expected hash of a whole regular file.
algorithm is a HashAlgorithm or its string: "blake3", "sha256", "md5",
or "xxh3-128". value is hexadecimal: 64 digits for BLAKE3 and SHA-256, 32
for MD5 and XXH3-128.
A file fails if its complete contents do not match; see expected hashes for when syq checks. MD5 and XXH3-128 catch accidental errors, not deliberate collisions.
MappingEntry
A frozen dataclass for one source-to-destination pair. Pass an iterable of
them to cp(mapping=...), and use dataclasses.replace to change one.
| Attribute | Type | Meaning |
|---|---|---|
src | RelativePath or StreamSource | Path relative to the source base, or a producer callback |
dst | RelativePath or StreamDestination | Path relative to the destination directory, or a consumer callback |
kind | EntryKind or None | Object kind, when known; default None |
size | int or None | Informational size in bytes; default None |
mtime | int or None | Informational filesystem modification time in Unix seconds; default None |
s3_last_modified | int or None | Informational S3 object modification time in Unix seconds; default None |
expected_hash | Hash or None | Expected whole-file hash; requires a regular file; default None |
metadata | DestinationMetadata or None | Explicit destination attributes; default None |
MappingEntry(src, dst, kind=None, size=None, mtime=None, expected_hash=None, metadata=None, s3_last_modified=None) also accepts text or byte paths and
converts them to RelativePath. For example, a DVC adapter can require the MD5
that DVC recorded:
entry = syq.MappingEntry(
"cache/object", "data.bin", kind="file",
expected_hash=syq.Hash("md5", "900150983cd24fb0d6963f7d28e17f72"),
)
client.cp(mapping=[entry], cwd="source", into="download")
DestinationMetadata
Give a destination attributes that differ from its source:
entry = syq.MappingEntry(
"source.bin", "payload.bin",
metadata=syq.DestinationMetadata(mode=0o640, mtime=1700000000),
)
client.cp(mapping=[entry], cwd="source", into="output")
The optional keyword-only fields are mode (permission bits), numeric uid
and gid, mtime in Unix seconds, and mtime_nsec (zero when omitted).
Attributes you set apply without copy_metadata, and the others follow normal
copy behavior. The
mapping format
says how S3 handles them.
RelativePath and PathValue
RelativePath(value) takes text, bytes, or os.PathLike, and refuses empty or
absolute paths, NUL bytes, and empty, ., or .. components. Join paths with
/, as in syq.RelativePath("archive") / entry.dst. It is also
os.PathLike, returning bytes.
PathValue(raw: bytes) holds a path from an event, which can be absolute. Both
types are immutable and provide:
| Member | Type | Meaning |
|---|---|---|
raw | bytes | Original filename bytes; also returned by bytes(path) |
text | str | UTF-8 decoding; raises UnicodeDecodeError for invalid UTF-8 |
str(path) | str | Filesystem decoding with os.fsdecode |
PathValue.display | str | Same as str(path) |