acp

package module
v0.2.10 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: BSD-2-Clause Imports: 36 Imported by: 2 modules, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

acp

ACP is a file copy tool and Go library with concurrent workers, ordered access for linear media, buffered or mapped reads, multiple targets from one content read, metadata preservation, progress events and JSON reports. An optional xattr cache stores SHA-256 content hashes.

Requirements

Build with Go 1.26.8 or newer, as declared in go.mod.

Operating model and stages

For the duration of a run, source contents and path relationships stay stable. The caller does not submit one item's output as another item's source in the same run, or edit files, directories, symlinks or hardlinks during copying. ACP owns its output changes; the rewrite command intentionally replaces its own source after reading it. ACP does not detect or recover from unsupported input changes. Files may change between runs.

Stage Responsibility
index Evaluate each needed Item method once, collect source facts (reusing available enumeration metadata), and resolve target paths and devices. Validate source/target aliases and overwrite rules before any target mutation. Pass the source facts unchanged to later stages.
prepare Open the source once when content or a cached hash is needed. Read the stored signature as required by the hash policy through that descriptor. Reserve a bounded file lifetime before dequeue; preparation does not read content ahead itself.
copy Read content once and, when enabled, compute one hash while fanning out to the targets. Complete ordinary-file metadata, cache work, synchronization and closure before final replacement; device nodes use direct output.
results Form one Result per accepted item and deliver it through one callback goroutine. Fatal pipeline failures are the exception to per-item completion; see delivery and lifecycle.

Indexed source facts are immutable; content-byte progress is tracked separately.

Content streams through shared immutable chunks. Hashing and writing consume independent references in parallel; each source is read once and each enabled digest is computed once. Random targets have independent bounded consumers of the same bytes. Linear source data reads remain ordered through EOF, then source Close runs independently of the next read. A linear target has one application Write lane: the next file may start after the previous file's last Write, while target Close, hash completion and metadata/publication settle asynchronously. This permits application overlap; the filesystem and device still decide physical scheduling.

The per-run pool allocates lazily, with at most 512 backing buffers of 1 MiB (512 MiB of content backing, not a total RSS limit). After all consumers and completion workers exit, backing returns to the shared reusable pool with no reference to the completed stream. Eight credits are reserved for the ordered foreground file. For linear targets, reads stay within the next 512 MiB from the writer's consumed frontier; this is an upper bound, not a guarantee that the window fills. Each tiny file still occupies a 1 MiB backing, and the 256 full file lifetimes also include pending completion and result delivery. Hash queues and each random-target queue hold four chunk references; file write queues hold references sized to the file prefix, at most 512. References share the global backing budget.

Configured source threads bound actual Read calls; configured target threads bound concurrent file data writers. Linear devices force their corresponding thread count to one. Preparation uses min(max(source threads, 8), 256) workers. Ordered reads reserve an opportunity for the earliest unfinished source; that reservation advances at source EOF independently of Write and Close, including with one source thread. Workers release Read permits before waiting on queues. Random-target files reserve their writer permit in dispatch order before reading, so future files cannot consume all backing while the active writers need it. File-lifetime admission is reserved before job dequeue, so later preparation cannot take the required head's slot. Open descriptors scale with admitted files and their target counts, rather than with Read permits alone. WithReadBuffer continues to count input items, independently of these content limits.

Target completion

Random ordinary outputs complete metadata, Sync and Close before rename. Linear outputs omit per-file Sync and Close independently after data writing; metadata/cache work on their owned temporary paths follows closure. Linear sources, linear targets and single-writer targets preserve publication order for the same resolved path, including equivalent relative and absolute names. Their completion keys also group case-folded, canonically equivalent Unicode names conservatively, so case or normalization aliases keep the same winner. On a case-sensitive filesystem this may order otherwise distinct outputs; their actual names and contents remain distinct. This key is not a filesystem identity test for every vendor-specific naming rule. Other keys publish independently; the copy data flow does not wait for these ordinary-file completion dependencies. Results keep the caller's original target names, and the exclusive-rename fallback remains in force. A late linear Close or metadata error stops future admission once observed; it cannot retract already started writes. Results retain each started item's actual outcome, and completion waits for all source/target Close, hash, cache and publication dependencies.

Ordinary targets use an exclusively created .tmp_* file beside the resolved final path. The old target remains in place while ACP writes the new file; the rename happens only after that file's content, hash, metadata and required closure complete. Success is reported after replacement, using the final target path. A failed copy cleans up only its owned temporary file and retains cleanup errors alongside the primary error. ACP never deletes the original to work around a rename failure.

An existing valid destination symlink is resolved once during indexing: ACP replaces its referent and retains the symlink. A dangling destination symlink is refused. Directory symlinks are also resolved once per parent during the run, including when child directories do not yet exist. For missing directories, ACP finds the existing ancestor first and resolves its symlinks once. Replacement creates a new inode at the final path; other hardlinks to the old inode keep their old content. It requires write permission on the destination directory and space for the complete new file while the old file still exists. A source alias, including a hardlink or symlink alias, fails that target while independent targets continue.

Overwrite(false) and acp -n reject targets found during indexing. For an initially missing target, Linux and macOS use the filesystem's exclusive rename: another item's completed output cannot be replaced, and independent targets finish concurrently. Other platforms, and filesystems that do not support exclusive rename, serialize only the final existence check and rename. Copying, sync and close stay outside that fallback lock. This preserves ACP's own output without a per-file lock registry; external writers remain outside the supported operating model.

Device nodes are written directly, without rename or metadata/cache changes, and may contain partial output after failure. Linear writers retain request order and perform neither preallocation nor per-file sync. Ordinary non-linear files retain the allocation and sync policy described under platform behavior, with no free-space estimate. Linear targets check an advisory cached free-space estimate before output creation. Each mount gets an independent goroutine that samples immediately and refreshes every five seconds, with at most one query in flight. Writing never waits for a capacity query, including the first one: unknown capacity permits writing and relies on actual filesystem errors. Each positive-size admission debits its logical size; admissions overlapping a query are also deducted from the new observation. Empty targets skip the check, and equality permits the write. A completed observation failure fails subsequent positive-size targets until a successful refresh; the worker also logs that failure. Cleanup does not refund the estimate. This estimate reserves nothing and cannot account for ongoing writes, filesystem allocation, media buffering or overhead, so a passing estimate does not guarantee that the write will fit. Close/Wait stop and join the polling workers after copying drains. An in-flight filesystem capacity call cannot be cancelled and can delay shutdown, but never holds the cache lock. Actual no-space and read-only errors stop the affected device and retain ErrTargetNoSpace and ErrTargetDropToReadonly; ErrTargetIO remains an individual target failure. Outputs already created on that device when the error is observed, by concurrent files or overlapped stream members, are not refused in advance; they succeed or fail on their own operations, and any device error they hit is classified the same way.

Same-directory rename does not promise atomic replacement on every platform, including Windows, or durability through power failure. ACP's existing sync policy is not a filesystem transaction.

The internal fileio.Output owns the temporary descriptor and path. The rewrite command supplies its scanned source facts and preallocated output through internal RewriteItem, so source replacement reuses the same completion path without a second temporary allocation, open or source stat. Before replacement, rewrite closes its source descriptor and mapping, as required by Windows file sharing. Rewrite retains its own state, hardlink and report responsibilities.

Library API

The caller submits items to a push engine and consumes their results:

func NewStream(ctx context.Context, onResults func([]Result) error, opts ...Option) (*StreamCopyer, error)
func (c *StreamCopyer) Submit(items ...Item) error
func (c *StreamCopyer) Close() error
func (c *StreamCopyer) Wait() error
func (c *StreamCopyer) HardStopped() <-chan struct{}
stream, err := acp.NewStream(ctx, func(results []acp.Result) error {
	for _, result := range results {
		job := result.Job.(*acp.SimpleJob) // the exact instance that was submitted
		if result.Err != nil {
			recordFailure(job, result.Err)
			continue
		}
		recordFacts(job, result)
	}
	return nil
}, acp.WithHashPolicy(acp.HashRead))
if err != nil {
	return err // creation or validation error
}

if err := stream.Submit(&acp.SimpleJob{Path: "/data/a.bin", Dsts: []string{"/tape/a.bin"}}); err != nil {
	// the run accepts no more work
}
if err := stream.Close(); err != nil {
	// the final flush failed
}
return stream.Wait() // the run's terminal error

An item is pure data. It has no callback, so the caller finds its own state by asserting Result.Job back to the instance it submitted:

type Item interface {
	Source() string
	Targets() []string // an empty slice writes nothing: it reads and hashes only when the
	                   // hash policy produces a hash, so the default HashOff records no hash
}

// Optional: override the source device mode for this item.
type ReadModeItem interface {
	ReadMode() ReadMode
}

type SimpleJob struct {
	Path string
	Dsts []string
}

A result reports the content facts of one finished item, one outcome per requested target in request order, and the item's own error:

type Result struct {
	Job  Item  // the exact instance that was submitted
	Err  error // nil = the item completed, even when every target failed

	Size      int64
	Mode      fs.FileMode
	ModTime   time.Time
	WriteTime time.Time

	SHA256            []byte // nil when the hash policy produces no hash
	SignatureCacheHit bool

	Targets []TargetResult
}

type TargetResult struct {
	Path       string
	Size       int64
	StoredSize int64 // bytes written to a written native target; zero for a failed or content target
	WriteTime  time.Time
	Err        error // nil when this target was written
}

A failure of the item's source while its transfer runs wraps ErrSourceRead: opening or observing a content source, reading or decoding a source, a content size mismatch, and closing the source. It is wrapped wherever ACP reports that failure, in Result.Err or inside a TargetResult.Err, so a caller can tell a source failure from a target's own failure. A failure to open a native source before its transfer starts, a stop (including a context error a source returns after the run was cancelled) and a panic are not tagged; a source's own deadline while the run continues is tagged.

var ErrSourceRead error    // wrapped by every source failure during a transfer
var ErrMemberSettled error // wrapped by an endpoint failure that ends only its own member
Encoded native content

An item can store a caller-owned encoding, such as a compression format, in its native targets, and read one back from its native source. ACP has no codec of its own; hashing, Result.Size, TargetResult.Size and progress always describe the plaintext:

// Optional: encode every native target of this item; a nil encode writes plaintext.
// encoding names the codec and is required, non-empty and at most 64 bytes, when encode is set.
type TargetEncoderItem interface {
	TargetEncoder() (encoding string, encode func(dst io.Writer) (io.WriteCloser, error))
}

// Optional: decode this item's native source; a nil decode reads plaintext.
type SourceDecoderItem interface {
	SourceDecoder() (encoding string, decode func(src io.Reader) (io.ReadCloser, error), size int64)
}

var ErrEncodedContent error // wrapped by every decoder failure

ACP calls TargetEncoder once while indexing; a non-nil encode without a valid encoding fails the item. For each native output it calls the encoder with that output's file writer and writes the item's plaintext into the returned writer. After the last write ACP calls Close exactly once, including after a failed write. Close flushes the encoded tail into dst and returns only after every write into dst has finished. It belongs to that output's data writing, so a linear writer starts the next file only after it returns. Content targets are not encoded.

TargetResult.StoredSize counts the bytes written into dst. An encoded output keeps ordinary target completion: its exclusive temporary file, the overwrite rules and the rename after completion, with the item's mode, times and ordinary xattrs restored onto the stored file. It is never preallocated, because its size is unknown. Linear capacity admission still debits the plaintext size. It always receives a managed signature entry that marks it as encoded; see the content signature cache.

An encoder error, a nil writer, a Close error, a failure to write the managed entry, or a panic in either call fails that target and discards its temporary output; other targets and items continue. A panic in the returned writer's Write remains a fatal pipeline failure, as for a content writer. An encoder that returns an error keeps ownership of any writer it created. Wrap dst errors to keep their identity, so device errors such as ErrTargetNoSpace stay classified.

ACP calls SourceDecoder once while indexing; a non-nil decode without a valid encoding fails the item. size is the declared plaintext size: it replaces the stored file's size in results, progress, read-ahead and target preallocation, while opening and mapping still use the stored file's own facts. A negative size fails the item. A decoded source requires native targets and no content source, since an endpoint would receive the stored file's size. Preparation opens the native source as usual; the decoder starts only when that source's read begins, so prepared items hold no decoder state. ACP reads plaintext from the returned reader until io.EOF and closes it exactly once, before the native descriptor; native targets publish only after that Close. The item's mode, times and ordinary xattrs come from the stored file.

Every failure the decoder reports wraps ErrEncodedContent: an error from the decoder function, any Read error other than io.EOF (including the decoder's own io.ErrUnexpectedEOF), a Close error, and plaintext longer or shorter than the declared size. Reading stops once the plaintext passes the declared size. An error from the native source's own Read keeps its identity instead, even when the decoder returns a different error for it. A decode failure is reported where a read failure is: in Result.Err for a targetless item, and in each TargetResult.Err otherwise, whose temporary outputs are discarded; a decoder Close error also sets Result.Err, as a source Close error does. It never stops the run. A panic or nil reader from the decoder function fails the item without ErrEncodedContent; panics in the reader's Read and Close remain fatal pipeline failures, as for a content source. A decoder that returns an error keeps ownership of any reader it created.

A decoded source reuses and refreshes only the decoded part of the managed signature entry, and a plaintext target written from it receives an entry as usual; see the content signature cache.

Content endpoints

An Item can optionally implement ContentItem to copy a member of an ordered stream:

type ContentMetadata struct {
	Info   fs.FileInfo
	Xattrs map[string][]byte
}
type ContentSource interface {
	Open(context.Context) (fs.File, error)
}
// Optional capability of the opened source file.
type XattrReader interface {
	Xattrs() (map[string][]byte, error)
}
func SourceFromFS(fsys fs.FS, name string) ContentSource

type ContentTarget interface {
	Open(context.Context, ContentMetadata) (ContentWriter, error)
}
type ContentWriter interface {
	io.Writer
	Finish(cause error) error
}
type ContentItem interface {
	Item
	ContentSource() ContentSource
	ContentTargets() []ContentTarget
}

A nil content source selects the native Source path. ContentTargets is nil or aligned with Targets; a nil entry selects that native target path. For an endpoint, the matching Item string is an exact display/result identifier: ACP never cleans, stats, caches or deletes it as a path. Each actual endpoint side requires LinearDevice(true); content sources require buffered reads. At most one non-nil content target is supported per item. Native sides retain their options, including mapped source reads, ordinary output staging, metadata, cache and no-overwrite behavior. These combinations are validated while indexing, before endpoint Open or native source observation.

Endpoint items run through one ordered lane of the existing bounded transfer engine. A member with a content target or a linear target holds the lane for its complete lifecycle, as does every member unless the source is linear or the target has one thread, the configurations that order same-path publication. Otherwise, a member whose outputs are all random-target native paths releases the lane once its source has reached EOF and closed and all its data has been written to the outputs; its metadata, Sync, rename, publication and result then complete while the next member opens and reads. At most three such members complete behind the reading one; they hold output descriptors and owned temporary files but no content backing. Their results therefore arrive in completion order. A content source opens lazily in that lane. ACP calls the opened file's Stat once, then optional Xattrs once, and takes its own portable metadata snapshot before any output is created. Stat must supply regular-file metadata with a nonnegative size. Expected metadata belongs to the caller and cannot substitute for that observation. Open, Stat or Xattrs failure creates no output. Any file returned alongside an Open error still receives one Close attempt; observation and cleanup errors retain their causes. A provider normalizes missing or unsupported xattr facilities to an empty map; other Xattrs errors fail the item.

Panics in custom source Open, Stat, Xattrs or file-info accessors retain their cause as an item failure before target creation, and any acquired file still receives one Close attempt. Panics in the Read or Close worker remain fatal pipeline failures. Empty observed members skip payload Read while retaining metadata observation, hashing when enabled, source Close and target Finish.

Source Close settles before the next source Open, before target Finish, and before any native target publication. A Close error discards the owned native temporary output and retains the existing final file. Endpoint failure stops future member admission; accepted unstarted items still receive the original stopping error. A content source that wraps ErrMemberSettled in its Open, Read or Close error has left its stream at a usable boundary: that item fails and later members are still admitted. A native source's failure on an item with a content target is decided by that target's Finish instead. Source reads stop on cancellation without draining remaining payload. Context-aware endpoint implementations receive the run context and must make their blocking Open, Read and Write operations respond to cancellation. ACP also checks cancellation during source observation and closes any acquired file before reporting the outcome.

SourceFromFS binds an existing fs.FS and an fs.ValidPath name without opening it. It opens only in that same ordered lane and returns the filesystem's actual fs.File, retaining optional XattrReader. It never calls fs.Stat separately. Invalid names and a nil filesystem fail before target creation. The name is relative, UTF-8 and slash-delimited; Item.Source remains the caller's display identifier:

source := acp.SourceFromFS(fsys, "docs/readme.txt")
// Return source from the existing caller-owned Item's ContentSource method.

The adapter checks context before and after Open, retaining any acquired file and joining an Open error with cancellation for ACP's common cleanup. Standard filesystem methods that ignore context are not made interruptible. An injected os.DirFS stays an opaque filesystem: ACP does not infer a native root, mmap, ownership or cache access. The caller keeps its storage disjoint from native outputs under the stable-input operating model. Native-path entrypoints retain their native name, symlink, alias, mapped-read and rewrite behavior.

ACP calls each returned writer's Finish exactly once after writes stop, passing any read, write, hash or source Close error as its cause. A Finish error also fails that target and stops the lane, unless the writer wraps ErrMemberSettled itself: a writer that has completed the member's framing, for example by padding it to its declared size, fails only that target and later members are still admitted. Only a marker the writer adds counts. The cause reaches Finish as its own node, and a marker inside it, such as a content source's settlement, never settles the target stream, so a Finish that returns, wraps or joins its cause stops the lane as usual. A panicking Finish always stops it. A content writer's own Write error always stops the lane when it happens, before Finish runs: ErrMemberSettled settles a failed source or a refused member, never a failed write to the stream. A content target's Open error that wraps ErrMemberSettled and returns no writer likewise fails only that target, while the item's other targets continue; the target refused the member before emitting anything, such as a name its format cannot represent. A content source is always read to the end of its member, even when no target or hash consumes it, so its stream keeps its boundary. Finish must settle a failed member without acknowledging missing bytes as successful. Completion proves one member's transfer only; finalization of the enclosing stream belongs to the caller after Close/Wait settle handles and result callbacks. Endpoint operations perform no native mmap, cache, capacity query, rename or per-file sync. Content-requiring hash policies hash actual bytes; HashCachedOnly on a targetless content source opens nothing and reports no hash or cache hit.

Metadata is copied into a portable immutable snapshot of size, mode, mtime and ordinary xattrs; endpoint Info.Sys never supplies native ownership. Native sources reuse their already-captured platform-selected attrs. Native outputs restore ordinary attrs before restrictive permissions, retain ACP's existing best-effort destination xattr error policy, and regenerate managed cache entries through the selected hash policy. Both managed keys (acp.signature and user.acp.signature) are excluded from endpoint snapshots. Empty and binary attribute values are preserved. Attribute names and values remain opaque to generic snapshots; each codec owns its representation checks, including PAX key grammar. ACP applies these exported envelope limits:

Limit Value
ContentMaxXattrCount 256 ordinary attributes
ContentMaxXattrNameBytes 1 KiB per name
ContentMaxXattrValueBytes 1 MiB per value
ContentMaxMetadataBytes 4 MiB aggregate xattr names/values, including 64 bytes framing allowance per attribute

Native endpoint capture validates the name-list and each name/value/count/aggregate limit before the corresponding buffer allocation or snapshot growth. Managed keys are excluded before ordinary count/value/aggregate checks. ACP bounds its own snapshot allocations; a custom XattrReader must bound any earlier decoding itself. Ordinary native-to-native capture retains its current behavior. A codec must also bound its own other metadata and encoded header chain. Optional XattrReader does not opt a custom source into native signature-cache reuse or refresh.

Terminology
Term Meaning
Item One caller-owned unit submitted to the push engine through Item.
Job The compatibility Job report row; SimpleJob is the existing convenience implementation of Item, and internal job types carry pipeline state. These roles retain their names.
Target One path requested by Item.Targets or the shell's target options; “destination” describes the same path.
Result One item's terminal facts, error and target outcomes. Result.Job retains the submitted item.
Result buffer The bounded queue of results waiting for delivery.
Result batch The slice passed to one invocation of the results callback.
Content hash / cached signature SHA-256 identifies content; a cached signature stores that hash together with size and mtime.
Stream / compatibility shell The stream accepts items; the shell enumerates job options and produces report rows over that stream.

Copyer, StreamCopyer, AccurateJob, WildcardJob, Result.Job and the report's existing field names are public API names. Their spelling and type roles are preserved for compatibility. A rewrite entry describes persisted rewrite work; it is separate from the stream's submitted item and the report row.

Delivery and lifecycle

Use one submitter, then call Close and Wait. Submit blocks when the read buffer is full and rejects nil items. Close ends the feed and drains accepted work; it returns wrap-up or flush errors. NewStream returns creation and option-validation errors; Wait returns the terminal run error.

Result.Err describes an item ACP could not process, including a source description/open failure, a failed targetless read or an item abandoned by a graceful stop. TargetResult.Err describes one failed target. A nil Result.Err can accompany failed targets, so callers must inspect both. Any result carrying an error is delivered immediately as its own batch. Successful results wait for WithResultBatch, WithResultFlushInterval, or the final Close flush. WithResultBuffer bounds the queue; slow callbacks apply backpressure. ACP owns batching; persistence belongs to the caller. Copy a callback's result slice if retaining it beyond that call.

Result order is unspecified; target outcomes within a result retain request order. Never call Submit, Close or Wait from inside onResults, since delivery must return before the run can finish.

Cancellation of the caller's context, a callback error or an exhausted linear target stops new submissions. Accepted items that cannot start receive the stopping error; work already past the read stage finishes and is reported. A callback error does not retract the submission already in progress. Closing the feed alone is not a stopping error. A fatal pipeline failure ends the run without a per-item completion guarantee.

HardStopped closes when that fatal boundary is crossed, so a caller waiting for per-item source completion can escape without first closing the feed. It stays open for normal completion and graceful stops. The signal does not prove that sources or device commands have settled; Close and Wait still settle resources, and Wait supplies the authoritative terminal error.

Caller methods, the results callback and event handlers run under panic protection. A panic in an item method fails that item; a callback or event-handler panic becomes a run error. A panic escaping pipeline code is a fatal run error, preserving the panic value.

Options

Option Scope Meaning
SetFromDevice(...) run Source device options
SetToDevice(...) run Target device options
LinearDevice(bool) device Enable linear device behavior
DeviceThreads(int) device Worker count, default 8, forced to 1 for a linear device
WithReadMode(ReadBuffered|ReadMapped) source device Read sources buffered or through a memory mapping
RefreshSignatureCache(bool) device Let a refreshing hash policy write signatures onto this side's files, default true
Overwrite(bool) run Replace an existing target instead of refusing it; applies to every target
WithReadBuffer(items) run Backpressure limit of the feed, default 4096 items
WithResultBuffer(items) run Depth of the result queue, default 256 items
WithResultBatch(items) run Results one delivery carries, default 256 items
WithResultFlushInterval(d) run How long a successful result may wait for its batch, default 1s
WithHashPolicy(HashPolicy) run Content hash and stored hash policy, default HashOff
WithLogger(*logrus.Logger) run Logger for pipeline diagnostics
WithEventHandler(EventHandler) run Progress, count, and error events
WithProgressBar() run Terminal progress bar handler

Validation happens in NewStream/New, which reject: a negative DeviceThreads; any ReadMode other than ReadBuffered or ReadMapped; WithReadMode applied to the target device; an unknown HashPolicy; WithReadBuffer(0) or less; WithResultBuffer(0) or less; WithResultBatch(0) or less; and a WithResultFlushInterval below 100ms. A job option (AccurateJob, WildcardJob) is valid only for New, which is the shell that enumerates it; NewStream rejects it instead of running an empty stream.

Repeated value options are last-wins, WithEventHandler included: the handler registered last is the only one that receives events, and WithEventHandler(nil) clears the registration. WithProgressBar() installs its handler through the same option, so a later WithEventHandler replaces the bar. The job options and SetFromDevice/SetToDevice accumulate by design: a second WildcardJob adds another walk, and a second device option adjusts the same device description.

WithReadMode applies to the source device only. An item implementing ReadModeItem overrides that choice for its own source; an invalid mode or panic fails that item without stopping the run. Buffered reads are the default; platform differences are listed below.

Events

WithEventHandler receives Event values serially on one goroutine. A command needing both a progress bar and another consumer composes them into that handler. EventFinished is sent once, last; Close and Wait wait for the handler, so a handler that never returns holds the run open.

Event What it reports
EventUpdateCount Accepted totals (Bytes, Files), with Finished on the last update
EventUpdateProgress Completed totals (Bytes, Files), with Finished on the last update
EventUpdateJob One terminal Job report row, emitted by the compatibility shell
EventReportError A pipeline error (Error: source, target, cause)
EventSignatureCacheSummary Aggregate cache activity when a policy manages the cache
EventFinished The run ended

Content hash policy

HashPolicy selects both how an item's content hash is produced and how the stored hash is used, because refreshing the cache requires a computed hash. A targetless item records content facts; a transfer reads its source to write it somewhere:

Policy Targetless item Transfer
HashOff no hash or cache use no hash or cache use
HashCachedOnly stored hash reused; a miss leaves the item without one rejected: a copy always reads its source
HashCachedOrRead stored hash reused; a miss reads and hashes rejected: a copy always reads its source
HashCachedOrReadRefresh stored hash reused; a miss reads, hashes and refreshes always reads, hashes and refreshes
HashRead always reads and hashes; no cache use always reads and hashes; no cache use
HashReadRefresh always reads and hashes, and refreshes the cache always reads, hashes and refreshes the cache

Transfers read source content and compute a hash only when the policy enables hashing. The two reuse-only policies fail the item with Result.Err when it requests targets; they do not fail stream creation. HashCachedOrReadRefresh transfers as HashReadRefresh.

Content signature cache

The managed xattr (user.acp.signature on Linux, acp.signature on Darwin and FreeBSD) holds a Protobuf SignatureEntry of at most 512 bytes (internal/signaturepb/signature.proto, generated by go generate ./internal/signaturepb). size and mtime_ns describe the file on disk and decide freshness against the stored file's own size and mtime, never a decoded size; sha256 is the hash of the bytes on disk. An encoded file also carries decoded: the item's encoding, the decoded size and the decoded content's sha256. Every hash is empty when unknown; an entry with a bad hash length, a negative size, a decoded without an encoding or a value over 512 bytes is invalid, which is a cache warning and a miss. The 56-byte ACPS layout of earlier releases is still read, as an entry without decoded; every write uses the Protobuf form, which never begins with ACPS.

A lookup compares the stored metadata with the indexed facts to detect a cache made stale between runs. A plain read reuses only a fresh entry's sha256. A decoding read reuses only a fresh entry's decoded.sha256, and only when decoded.encoding equals the item's encoding and decoded.size equals the declared size; targetless decoding items reuse under the same policies as plain ones. Neither read ever trusts the other hash. The source entry is read at most once when needed. A refresh writes the hash its read computed (sha256, or decoded for a decoding read), keeps the other half of a fresh entry unchanged, writes only what it computed over a stale or missing entry, and skips an unchanged write. A fresh staged plaintext target receives a new entry directly only when refresh is enabled, without reading or invalidating an old one. RefreshSignatureCache(false) on the source or target device keeps a refreshing policy from writing that side's entries; hashing, reuse and the other side are unchanged. A rewrite's replacement file is a written target.

An encoded target always receives an entry, whatever the hash policy: size is the stored size (TargetResult.StoredSize), mtime_ns the source mtime the metadata restore applies, and decoded the encoding, plaintext size and, when the policy refreshes, the target side has not opted out and a hash was computed, plaintext hash. This entry is the durable marker that the file is encoded, so a failure to write it, including a file system without the attribute, fails that target and discards its temporary output, unlike the warning-only plaintext writes. For a written target, only an encoding write produces the marker. A plain copy of an encoded file, including an acp-rewrite replacement, does not carry decoded: the managed key is never copied as an ordinary attribute, and the copy writes at most a plaintext entry for the stored bytes. The target entry is written before restoring restrictive permissions; all metadata is complete before replacement.

Source cache lookup uses its content descriptor. Source refresh runs after hash and a successful source Close through the stable source path, so a decoder that rejects its plaintext in Close, or a plain source whose Close fails, leaves its entry unchanged; a closed linear output uses its owned temporary path. Random output cache work uses its still-open descriptor before Sync and Close. Platforms may reopen these paths for metadata operations without rereading content. Rewrite waits for source cache and closure before replacing its source. The managed key is excluded from ordinary xattr copying. Cache diagnostics are aggregated in EventSignatureCacheSummary; they never become copy or Wait errors. A filesystem without the managed attribute namespace stores nothing: reads miss and writes are silent no-ops.

Platform behavior

Platform Buffered source access time Managed signature attribute Non-linear file allocation Metadata restore Mapped read
Linux O_NOATIME, falling back when refused user.acp.signature fallocate xattrs, mode, owner as root, times syscall.Mmap; sequential/prefetch advice for files up to 16 MiB
Darwin not suppressed acp.signature Truncate xattrs, mode, owner as root, times syscall.Mmap
FreeBSD not suppressed acp.signature in the user namespace Truncate mode and times descriptor-backed ReadAt
Windows not suppressed none Truncate mode and times CreateFileMapping and MapViewOfFile
other not suppressed none Truncate mode and times descriptor-backed ReadAt

Zero-length files need no preallocation. Non-linear writers sync content before closing. Mapped reads do not suppress access time. See platform verification limits for checks requiring a native runtime.

af05f05c compatibility shell

The af05f05c surface delegates to the push engine and retains its exported names, field types and report format. v0.1.0 and v0.2.0 are withdrawn and are not compatibility baselines.

c, err := acp.New(ctx, acp.WildcardJob(acp.Source("example"), acp.Target("target")), acp.WithHash(true))
if err != nil {
	return err
}
c.Wait()
  • New(ctx, opts...) (*Copyer, error), (*Copyer).Wait(), (*Copyer).WaitErr() error. Wait/WaitErr close the stream and report how the run ended.
  • AccurateJob(src, dsts) copies one exact source to exact target paths; WildcardJob(Source(...), Target(...)), AccurateSource(base, paths...), WildcardJobOption walk sources, keep regular files, map each source-relative path onto every target directory, and sort them in the platform's path order.
  • A repeated relative path inside one WildcardJob is an enumeration error: WaitErr returns it and nothing is copied.
  • Overwrite(bool) Option, SetFromDevice, SetToDevice, LinearDevice, DeviceThreads, WithReadMode, RefreshSignatureCache, WithReadBuffer, WithResultBuffer, WithResultBatch, WithResultFlushInterval, WithHashPolicy, WithLogger, WithEventHandler, WithProgressBar, WithHash(bool), Event*, EventHandler, Error, Job, Report, ReportGetter, NewReportGetter, NewProgressBar, Cache[K,V], DeviceOption, WildcardJobOption, Option, ReadCachedSignature, CachedSignature, DecodeCachedSignature, SignatureEntry, DecodedSignature, SignatureStatus (SignatureMissing, SignatureStale, SignatureFresh), ReadSignatureEntry, DecodeSignatureEntry, ErrTargetNoSpace, ErrTargetDropToReadonly, ErrTargetIO, CopyAttrs, UnexpectFileMode.
  • WithHash(true) maps to HashReadRefresh; WithHash(false) maps to HashOff.
  • Pipeline errors are returned by WaitErr and cause the command to fail. The shell produces reports from final results, including failed items.
  • Cache[K,V] initializes a key once while allowing different keys to initialize concurrently.

Memory reader

The mmap package includes code derived from golang.org/x/exp/mmap; its upstream notice and license are retained in mmap/LICENSE.

The mmap package retains its source descriptor. Explicit Close releases a mapping before closing the descriptor and is idempotent on every platform. An open empty file is readable as empty, not closed; a failed mapping setup releases its resources. Slice bounds are checked before allocation. Read returns io.EOF at the end; ReadAt rejects an offset past the end. File returns the owned descriptor, so keep the reader reachable while using it. The finalizer is a fallback, not a substitute for Close.

Install

go install github.com/samuelncui/acp/cmd/acp@latest
go install github.com/samuelncui/acp/cmd/acp-rewrite@latest

Usage

Usage of acp:
  -cpu.arm
    	allow ARM features to be detected; can potentially crash
  -cpu.disable string
    	disable cpu features; comma separated list
  -cpu.features
    	lists cpu features and exits
  -from-linear
    	copy from linear device, such like tape drive
  -n	not overwrite exist file
  -notarget
    	do not have target, use as dir index tool
  -p	display progress bar (default true)
  -report string
    	json report storage path
  -report-indent
    	json report with indent
  -target value
    	use target flag to give multi target path
  -to-linear
    	copy to linear device, such like tape drive

The command exits 0 only when every selected item was copied to every requested target. Any item failure, any target that was not written, cancellation, and any pipeline failure make it exit 1, and the requested report is attempted before exit. Failure to write that report also exits 1; invalid flags or missing positional arguments exit 2. Independent items and targets continue after individual failures. -notarget selects an index operation with no destinations, including when -target flags were supplied.

Examples

Place flags before positional source and target paths; Go flag parsing stops at the first positional argument.

# copy `example` dir to `target` dir
acp example target/

# copy `example` dir to `target` dir, and output a report to `report.json`
acp -report report.json example target/

# the same report, indented with two spaces
acp -report report.json -report-indent example target/

# copy one file to one exact path
acp example/a.bin target-b.bin

# copy `example` dir to `target1` and `target2` dir
acp -target target1 -target target2 example

# do not copy, just get a dir index, write to `report.json`
acp -notarget -report report.json example

# copy from a tape-like source to a tape-like target
acp -from-linear -to-linear example target/

Report

The compatibility shell owns report rows; the push engine returns Result values. Each terminal item, including a failed item, produces one Job row. Base is the source base directory and Path is its relative segment slice, encoded as a JSON array. Their joined path is the additive FullPath (full_path); SignatureCacheHit (signature_cache_hit) is also additive. NewReportGetter keys and sorts rows by the joined relative path. Overlapping job options that produce the same relative key share a row.

-report writes these rows under files. Per-target failures use the final target path in fail_target; item-level failures use the empty key. Pipeline errors appear only in the top-level errors array. Empty files and errors arrays are omitted, so an empty report is {}. Nil errors remain absent. -report-indent and Report.ToJSONString(true) use two-space indentation. Standard encoding/json handles reports without a custom decoder.

JSON report paths require valid UTF-8. Invalid filename bytes cause an encoding error instead of a lossy path; native copies and in-memory results retain host filename semantics. Individual rows and errors use *Job and *Error because their JSON methods have pointer receivers. json.Marshal and json.Encoder return encoding errors; Report.ToJSONString returns an empty string on encoding failure. Commands preserve the previous report and exit 1 if the requested report cannot be saved.

Rewrite command

acp-rewrite -state state.json -report report.json ROOT replaces regular files under the target completion contract, preserves each scanned hardlink group, and accumulates report rows across runs. It reports final paths and duplicate content by size and SHA-256. -dryrun saves the selected work without rewriting it; repeated -ignore PATH excludes a file or subtree. Busy entries remain in the state's busy queue; missing and failed entries remain pending for an explicit later invocation. Missing paths are also recorded in the state's missing list. As with acp, exit codes are 0 for success, 1 for execution or partial failure, and 2 for usage errors.

The persisted pending queue includes the current entry, its hardlinks and the unprocessed tail. An entry leaves pending only after its copy, replacement, relinks, report and progress writes succeed. An interrupted current entry may be rewritten again. Individual failures retain that entry and allow independent entries to continue; a state or report persistence failure stops new entries. State and report files must both decode before any source or saved temporary file is changed.

Rewrite requires valid UTF-8 paths for its root, selected regular files and hardlinks, and the directories holding its state/report documents and their temporary files. The document basenames themselves retain host filename semantics. Scanning rejects an unsupported selected filename before any file is rewritten; no lossy queue is saved. -ignore can exclude an unsupported file or subtree. Whitespace, control characters, backslashes and the literal Unicode replacement character are preserved wherever the host filesystem supports them.

State and report writes use the shared temporary-file allocation and JSON writer: encode, sync, close, then rename. Temporary hardlinks use exclusive allocation with collision retry. Cleanup removes only allocated paths or ownership recorded in state; a cleanup failure keeps that ownership for a later run and is reported alongside the primary failure.

Testing

See TESTING.md for unit, race, end-to-end, and cross-platform test instructions and the release SOP.

Documentation

Index

Constants

View Source
const (
	ContentMaxXattrCount      = 256
	ContentMaxXattrNameBytes  = 1 << 10
	ContentMaxXattrValueBytes = 1 << 20
	ContentMaxMetadataBytes   = 4 << 20
)

Content endpoint metadata limits also bound native capture before allocating xattr buffers. The aggregate includes a conservative 64-byte framing allowance per attribute.

View Source
const (
	JobStatusPending   = "pending"
	JobStatusPreparing = "preparing"
	JobStatusCopying   = "copying"
	JobStatusFinishing = "finishing"
	JobStatusFinished  = "finished"
)

Report row status vocabulary. A row is published once, when the item's data and metadata lifecycle has finished, so a completed and a failed item both read JobStatusFinished.

View Source
const UnexpectFileMode = os.ModeType &^ os.ModeDir

UnexpectFileMode is the file-mode mask a walk refuses to descend into.

Variables

View Source
var (
	ErrTargetNoSpace        = fmt.Errorf("acp: target have no space")
	ErrTargetDropToReadonly = fmt.Errorf("acp: target droped into readonly")
	// ErrTargetIO reports an I/O failure of one target. Unlike ErrTargetDropToReadonly it does
	// not describe the whole device, so it must not abort a target that is still writable.
	ErrTargetIO = fmt.Errorf("acp: target have io error")
)
View Source
var ErrEncodedContent = errors.New("acp: encoded content cannot be decoded")

ErrEncodedContent identifies a native source whose item decoder failed: an error from the decoder function or its reader, or plaintext that differs from the declared size. The native source's own read errors keep their identity instead.

View Source
var ErrMemberSettled = errors.New("acp: endpoint member failure is settled")

ErrMemberSettled marks an endpoint failure that ends only its own member. A content source that wraps it in an Open, Read or Close error, a content target that wraps it in an Open error and returns no writer, or a content writer that wraps it in its own Finish error has left its ordered stream at a usable boundary: that member fails, but later members are still admitted instead of the endpoint failure stopping the run. A writer settles only with a marker it adds itself: one it merely passes on from the cause Finish received, by returning, wrapping or joining that cause, does not count. A refused content target fails alone; the item's other targets continue. A content writer's own Write error always stops the run.

View Source
var ErrSourceRead = errors.New("read source failed")

ErrSourceRead identifies a failure of an item's source while its transfer runs: opening or observing a content source, reading or decoding a source, a content size mismatch, or closing the source. ACP wraps it wherever it reports that failure, in Result.Err or inside a TargetResult.Err, so a caller can tell a source failure from a target's own failure.

Functions

func Cache

func Cache[K comparable, V any](f func(in K) V) func(in K) V

func CopyAttrs

func CopyAttrs(dst, src string) error

func NewReportGetter

func NewReportGetter() (EventHandler, ReportGetter)

NewReportGetter returns the event handler that collects one run's report and the getter that renders it. A row is keyed by the joined relative path of its item, and the getter emits the rows in that key's order, so the same items always produce the same document; the pipeline errors keep their arrival order.

func ReadSignatureEntry added in v0.2.10

func ReadSignatureEntry(path string) (SignatureEntry, SignatureStatus, error)

ReadSignatureEntry returns a regular file's managed entry and whether it is fresh. A stale entry is still returned, so a caller can see its Decoded marker when only the mtime changed. Missing and unsupported xattrs report SignatureMissing.

Types

type CachedSignature added in v0.2.0

type CachedSignature struct {
	Size    int64
	MtimeNS int64
	SHA256  [32]byte
}

CachedSignature is a SHA-256 content signature of the bytes on disk, bound to file metadata.

func DecodeCachedSignature added in v0.2.0

func DecodeCachedSignature(encoded []byte) (CachedSignature, error)

DecodeCachedSignature decodes the plain view of a managed xattr value, in either encoding. It fails for an entry without a SHA-256 of the bytes on disk.

func ReadCachedSignature added in v0.2.0

func ReadCachedSignature(path string) (CachedSignature, bool, error)

ReadCachedSignature returns the plain signature of the bytes on disk only when the entry's size and mtime still match the regular file and the entry has that hash. Missing, stale, decoded-only and unsupported xattrs are cache misses.

type ContentItem added in v0.2.7

type ContentItem interface {
	Item
	ContentSource() ContentSource
	ContentTargets() []ContentTarget
}

ContentItem optionally supplies stream endpoints. A nil source selects the native Source path. ContentTargets is either nil or aligned with Targets; nil entries select native target paths. Each endpoint side requires LinearDevice(true); content sources require buffered reads. At most one target endpoint is supported per item. Native sides retain their device options.

type ContentMetadata added in v0.2.7

type ContentMetadata struct {
	Info   fs.FileInfo
	Xattrs map[string][]byte
}

ContentMetadata is an immutable snapshot observed when a source opens. Endpoint implementations retain ownership of their input; ACP copies the snapshot before forwarding it to targets.

type ContentSource added in v0.2.7

type ContentSource interface {
	Open(context.Context) (fs.File, error)
}

ContentSource opens one member in an ordered content stream. ACP observes Stat and optional Xattrs once before opening targets. ACP owns any returned file, even alongside an error, and closes it once before another member opens or its native outputs can be committed.

func SourceFromFS added in v0.2.7

func SourceFromFS(fsys fs.FS, name string) ContentSource

SourceFromFS binds a filesystem and its relative, slash-delimited name without opening it. ACP opens the file in the ordered source lane, observes Stat and optional Xattrs, and owns Close. Invalid names and a nil filesystem fail that item before target creation. The filesystem must remain disjoint from native outputs; ACP cannot identify aliases hidden behind an fs.FS.

type ContentTarget added in v0.2.7

type ContentTarget interface {
	Open(context.Context, ContentMetadata) (ContentWriter, error)
}

ContentTarget opens one member using observed source metadata. Its matching target string is a display identifier, never a filesystem path.

type ContentWriter added in v0.2.7

type ContentWriter interface {
	io.Writer
	Finish(cause error) error
}

ContentWriter receives member bytes. ACP calls Finish exactly once after writes stop, passing the transfer failure, if any; Finish must not publish a truncated member as successful.

type Copyer

type Copyer struct {
	// contains filtered or unexported fields
}

Copyer is the af05f05c compatibility shell: the same job options, events and JSON report as the commit that predates the streaming API, built on the push engine.

New enumerates the requested jobs, submits every selected file to a StreamCopyer, and translates each result into the terminal report row event the CLI, Report and NewReportGetter machinery reads. Wait/WaitErr close that stream and report how the run ended.

func New

func New(ctx context.Context, opts ...Option) (*Copyer, error)

New builds a shell run. Creation and validation errors, such as a target that is not a directory or a source that does not exist, come back from New; an enumeration error, such as two sources mapping to the same relative path, ends the run and comes back from WaitErr.

func (*Copyer) Wait

func (c *Copyer) Wait()

Wait blocks until the run finished. Use WaitErr to learn how it ended.

func (*Copyer) WaitErr

func (c *Copyer) WaitErr() error

WaitErr closes the run, drains the pipeline and returns its terminal error. An item-level failure is not a run error: it travels in that item's report row.

type DecodedSignature added in v0.2.10

type DecodedSignature struct {
	// Encoding is the caller-defined, non-empty encoding name.
	Encoding string
	// Size is the decoded size.
	Size int64
	// SHA256 is the SHA-256 of the decoded content; empty when unknown.
	SHA256 []byte
}

DecodedSignature describes the decoded content of an encoded file.

type DeviceOption

type DeviceOption func(*deviceOption) *deviceOption

func DeviceThreads

func DeviceThreads(threads int) DeviceOption

func LinearDevice

func LinearDevice(b bool) DeviceOption

func RefreshSignatureCache added in v0.2.9

func RefreshSignatureCache(b bool) DeviceOption

RefreshSignatureCache selects whether a refreshing hash policy writes computed signatures onto this device's files: sources on the source device, written targets on the target device. It defaults to true and never changes hashing or reuse of stored signatures.

func WithReadMode added in v0.2.1

func WithReadMode(mode ReadMode) DeviceOption

WithReadMode selects how a source device reads its content. It applies to the source device only and defaults to buffered reads.

type Error

type Error struct {
	Src string `json:"src,omitempty"`
	Dst string `json:"dst,omitempty"`
	Err error  `json:"error,omitempty"`
}

Error is one pipeline-level failure. Its JSON form stores the message, so a report stays readable with encoding/json and an absent error stays absent.

func (*Error) Error

func (e *Error) Error() string

func (*Error) MarshalJSON

func (e *Error) MarshalJSON() ([]byte, error)

MarshalJSON encodes the message of an error. A missing error stays missing: it is omitted instead of being rendered from a nil value, so marshalling cannot panic on the nil errors UnmarshalJSON can produce.

func (*Error) UnmarshalJSON

func (e *Error) UnmarshalJSON(buf []byte) error

UnmarshalJSON decodes the object form or null. An absent or empty message leaves Err nil, so a round trip neither loses an error nor invents one.

type Event

type Event interface {
	// contains filtered or unexported methods
}

type EventFinished

type EventFinished struct{}

type EventHandler

type EventHandler func(Event)

EventHandler observes the events of one run. ACP calls it from one goroutine per registration and never concurrently, so a handler may keep unguarded state between events. WithEventHandler is last-wins, so a run has at most one handler.

func NewProgressBar

func NewProgressBar() EventHandler

type EventReportError

type EventReportError struct {
	Error *Error
}

type EventSignatureCacheSummary added in v0.2.0

type EventSignatureCacheSummary struct {
	Summary SignatureCacheSummary
}

EventSignatureCacheSummary reports aggregate cache behavior for one Copyer.

type EventUpdateCount

type EventUpdateCount struct {
	Bytes, Files int64
	Finished     bool
}

type EventUpdateJob

type EventUpdateJob struct {
	Job *Job
}

type EventUpdateProgress

type EventUpdateProgress struct {
	Bytes, Files int64
	Finished     bool
}

type HashPolicy added in v0.2.1

type HashPolicy uint8

HashPolicy selects how an item's content hash is produced and how the stored hash cache is used. Hashing and the cache are one policy, because refreshing the cache requires a computed hash: a miss under a refresh-enabled value must read.

A targetless item may reuse a stored hash, because it records content facts without writing the content anywhere. A transfer always reads its source and produces a computed hash, so the two reuse-only values are rejected for an item that requests targets.

const (
	// HashOff produces no hash and leaves the cache untouched.
	HashOff HashPolicy = iota
	// HashCachedOnly reuses a stored hash for a targetless item; a miss leaves the item
	// without a hash. Rejected for an item with targets.
	HashCachedOnly
	// HashCachedOrRead reuses a stored hash for a targetless item; a miss reads and hashes
	// without refreshing. Rejected for an item with targets, because a copy always reads and
	// a reused hash would then describe content the transfer never computed.
	HashCachedOrRead
	// HashCachedOrReadRefresh reuses a stored hash for a targetless item; a miss reads,
	// hashes and refreshes. A transfer always reads, hashes and refreshes.
	HashCachedOrReadRefresh
	// HashRead always reads and hashes; the cache is not refreshed. A targetless item
	// ignores its stored hash, and a transfer hashes the content it copies.
	HashRead
	// HashReadRefresh always reads and hashes, and refreshes the cache.
	HashReadRefresh
)

func (HashPolicy) String added in v0.2.1

func (p HashPolicy) String() string

type Item added in v0.2.1

type Item interface {
	// Source returns the exact native path to read, or the content source display identifier.
	Source() string

	// Targets returns native paths or content target display identifiers. An empty slice writes nothing: the source is
	// read and hashed only when the hash policy produces a hash, so the default HashOff reports
	// neither a copy nor a hash.
	Targets() []string
}

Item is one unit of work owned by the caller.

The caller implements Item over whatever state it owns, so the item is the handle that ties a result back to that state: Result.Job is the exact instance that was submitted, and no id lookup or payload plumbing is needed. ACP calls Source and Targets under panic protection: the first call describes the item, and an item whose description failed is asked for its Source once more when it is reported, so a failure path may read Source twice. ACP never keeps the item afterwards.

type Job

type Job struct {
	Base string   `json:"base"`
	Path []string `json:"path"`

	Status         string           `json:"status"`
	SuccessTargets []string         `json:"success_target,omitempty"`
	FailTargets    map[string]error `json:"fail_target,omitempty"`

	Size      int64       `json:"size"`
	Mode      fs.FileMode `json:"mode"`
	ModTime   time.Time   `json:"mod_time"`
	WriteTime time.Time   `json:"write_time"`
	SHA256    string      `json:"sha256"`

	FullPath          string `json:"full_path,omitempty"`
	SignatureCacheHit bool   `json:"signature_cache_hit,omitempty"`
}

Job is one report row in the af05f05c shape: Base is the directory the source-relative Path is resolved against, and Path holds the source-relative path segments that also map onto a target directory, so the row's JSON carries path as an array. It is part of the public report contract, so it is a plain data structure that a report reader can decode with encoding/json alone.

FullPath and SignatureCacheHit are additive fields. FullPath names the source file as one whole path, which a consumer that does not join Base and Path needs, and SignatureCacheHit reports where the content hash came from; both stay empty on a row that does not record them.

func (*Job) MarshalJSON added in v0.2.1

func (j *Job) MarshalJSON() ([]byte, error)

MarshalJSON renders one report row with encoding/json. A row is part of the public report contract, so it must be readable and writable without ACP's own JSON coders.

func (*Job) UnmarshalJSON added in v0.2.1

func (j *Job) UnmarshalJSON(buf []byte) error

UnmarshalJSON reads one report row back. A null or empty failure message leaves the target out of the map instead of turning it into an error that was never recorded.

type Option

type Option func(*option) *option

Option configures one run. A repeated value option is last-wins, so a later value replaces an earlier one instead of combining with it; the job options and SetFromDevice/SetToDevice accumulate, so a second WildcardJob adds another walk and a second device option adjusts the same device description.

func AccurateJob

func AccurateJob(src string, dsts []string) Option

AccurateJob copies one exact source to the given destination paths, without mapping a relative path onto a target directory.

func Overwrite

func Overwrite(b bool) Option

Overwrite selects whether an existing target file is replaced or refused. It is a run-level option and applies to every requested target.

func SetFromDevice

func SetFromDevice(opts ...DeviceOption) Option

func SetToDevice

func SetToDevice(opts ...DeviceOption) Option

func WildcardJob

func WildcardJob(opts ...WildcardJobOption) Option

WildcardJob copies every regular file below the given sources into every target directory, keeping each file's source-relative path.

func WithEventHandler

func WithEventHandler(h EventHandler) Option

WithEventHandler registers the run's event handler. Repeated options are last-wins, so this replaces every handler registered before it, and a nil handler clears the registration instead of leaving a handler that fails the run when it is called.

func WithHash

func WithHash(b bool) Option

WithHash selects whether the run computes a content hash and refreshes the stored hash cache. It is the af05f05c form of WithHashPolicy: true maps to HashReadRefresh and false to HashOff, and a repeated hash option is last-wins.

func WithHashPolicy added in v0.2.1

func WithHashPolicy(policy HashPolicy) Option

WithHashPolicy sets the content hash policy, which also decides how the stored hash cache is read and refreshed. It defaults to HashOff.

func WithLogger

func WithLogger(logger *logrus.Logger) Option

func WithProgressBar

func WithProgressBar() Option

func WithReadBuffer added in v0.2.1

func WithReadBuffer(items int) Option

WithReadBuffer sets how many items ACP may hold in its read buffer, which is also the feed's backpressure limit: Submit blocks while the buffer is full. It defaults to 4096 items.

func WithResultBatch added in v0.2.1

func WithResultBatch(items int) Option

WithResultBatch sets how many results one delivery carries: ACP hands the caller's results callback at most this many results at a time. It defaults to 256 items.

func WithResultBuffer added in v0.2.1

func WithResultBuffer(items int) Option

WithResultBuffer sets how many finished results ACP may hold for delivery, which is the backpressure limit of the result path: a pipeline stage that produces a result blocks while the result buffer is full. A result that carries an error is delivered as soon as it is read, so it does not wait for room in a batch. It defaults to 256 items.

func WithResultFlushInterval added in v0.2.1

func WithResultFlushInterval(d time.Duration) Option

WithResultFlushInterval sets how long a successful result may wait for the rest of its batch. It defaults to one second and accepts no value below 100ms.

type ReadMode added in v0.2.1

type ReadMode uint8

ReadMode selects how a source device reads its content.

const (
	// ReadBuffered reads through the kernel's buffered path, which is the default.
	ReadBuffered ReadMode = iota
	// ReadMapped reads through a memory mapping.
	ReadMapped
)

func (ReadMode) String added in v0.2.1

func (m ReadMode) String() string

type ReadModeItem added in v0.2.2

type ReadModeItem interface {
	ReadMode() ReadMode
}

ReadModeItem optionally selects how one item's source content is read. Items that do not implement it use the source device mode set by WithReadMode, which defaults to ReadBuffered. ACP calls ReadMode once while indexing a describable item. A panic or invalid mode fails only that item; it does not stop the run.

type Report

type Report struct {
	Jobs   []*Job   `json:"files,omitempty"`
	Errors []*Error `json:"errors,omitempty"`
}

Report is the JSON document of one run: one row per accepted item plus the pipeline-level errors. The standard library encodes and decodes it as-is, so a consumer needs no ACP coder to read what ACP wrote.

func (*Report) ToJSONString

func (r *Report) ToJSONString(indent bool) string

ToJSONString renders the report. Indentation is two spaces, because a JSON encoder accepts nothing else and a report writer must never panic while it is producing a document. It returns an empty string on encoding failure; use json.Marshal to inspect the error.

type ReportGetter

type ReportGetter func() *Report

type Result added in v0.2.1

type Result struct {
	// Job is the exact Item instance that was submitted.
	Job Item

	// Err is the item-level error. A nil Err means the item completed, even when every
	// requested target failed: an item that could not be processed at all is what fails,
	// and its target outcomes are still reported.
	Err error

	// Size, Mode and ModTime describe the source facts the item observed, and WriteTime is
	// when its copy stage started. A decoded source reports its declared plaintext Size.
	Size      int64
	Mode      fs.FileMode
	ModTime   time.Time
	WriteTime time.Time

	// SHA256 is the hash of the bytes actually read; it is nil when the hash policy produces
	// no hash. SignatureCacheHit reports that a stored hash was reused instead of computed.
	SHA256            []byte
	SignatureCacheHit bool

	// Targets holds one outcome per requested target, in request order. A target that was
	// not written still has an outcome.
	Targets []TargetResult
}

Result reports the content facts of one finished item, one outcome per requested target, and the item's own error.

A result that carries an error is delivered as soon as it is produced; results without an error are buffered. Result order is unspecified: results arrive in completion order, and a failure may therefore arrive before a success of the same submission batch. A linear target still writes in request order, because one writer consumes items in that order.

type SignatureCacheSummary added in v0.2.0

type SignatureCacheSummary struct {
	Hits       int64    `json:"hits"`
	Misses     int64    `json:"misses"`
	Stale      int64    `json:"stale"`
	Writes     int64    `json:"writes"`
	Failures   int64    `json:"failures"`
	FirstError string   `json:"first_error,omitempty"`
	Samples    []string `json:"samples,omitempty"`
}

SignatureCacheSummary describes cache activity for one Copyer run.

type SignatureEntry added in v0.2.10

type SignatureEntry struct {
	Size    int64
	MtimeNS int64
	SHA256  []byte
	Decoded *DecodedSignature
}

SignatureEntry is the managed signature xattr of a file. Size and MtimeNS describe the file on disk and decide freshness; SHA256 is the hash of the bytes on disk and is empty when unknown. Decoded is present only for an encoded file, where the entry is also the marker that the file is encoded.

func DecodeSignatureEntry added in v0.2.10

func DecodeSignatureEntry(encoded []byte) (SignatureEntry, error)

DecodeSignatureEntry decodes the managed xattr value: the Protobuf form, or the legacy fixed-size layout that begins with the legacy magic.

type SignatureStatus added in v0.2.10

type SignatureStatus uint8

SignatureStatus tells whether a file's managed signature entry describes its current version.

const (
	// SignatureMissing means the file has no entry, or its file system has no managed attribute.
	SignatureMissing SignatureStatus = iota
	// SignatureStale means the entry's size or mtime no longer match the file.
	SignatureStale
	// SignatureFresh means the entry's size and mtime match the file.
	SignatureFresh
)

type SimpleJob added in v0.2.1

type SimpleJob struct {
	Path string
	Dsts []string
}

SimpleJob is an Item that carries no state of its own: Path is the source and Dsts are the destinations. A caller that submits a SimpleJob finds its result by matching Result.Job against the pointer it submitted, because SimpleJob has no callback of its own.

func (*SimpleJob) Source added in v0.2.1

func (j *SimpleJob) Source() string

Source returns the path to read.

func (*SimpleJob) Targets added in v0.2.1

func (j *SimpleJob) Targets() []string

Targets returns the destinations; an empty slice reads without writing, and it produces a hash only when the run's hash policy does.

type SourceDecoderItem added in v0.2.10

type SourceDecoderItem interface {
	SourceDecoder() (encoding string, decode func(src io.Reader) (io.ReadCloser, error), size int64)
}

SourceDecoderItem optionally decodes one item's native source. ACP calls SourceDecoder once while indexing; a nil decode reads plaintext, and a non-nil one requires a non-empty encoding name of at most 64 bytes. size is the plaintext size: it replaces the stored file's size in results, progress, read-ahead and target allocation, and the decoded bytes must match it. When the source starts reading, ACP calls decode with the opened native reader and reads plaintext from the returned reader until io.EOF; it closes that reader once before the native descriptor. A decoded source reuses and refreshes only the decoded part of the managed signature entry, for its encoding and size, and requires native targets.

type StreamCopyer added in v0.2.1

type StreamCopyer struct {
	// contains filtered or unexported fields
}

StreamCopyer is the push engine. The caller submits items, ACP reports every accepted item through one results callback, and Wait returns the run's terminal error.

A run has exactly one cancellation checkpoint: Submit consults the context, the results callback error and an exhausted linear target before it accepts a batch. Every later stage runs on a context that never cancels, so it only drains and forwards what it holds; a stage that pulls an item it can no longer start marks it with the stopping reason, and the results stage is the only goroutine that invokes the caller's callback. A graceful stop therefore gives every accepted item exactly one result.

func NewStream added in v0.2.1

func NewStream(ctx context.Context, onResults func([]Result) error, opts ...Option) (*StreamCopyer, error)

NewStream builds a push engine. It returns creation and validation errors: a nil results callback, an invalid option combination, or a job option that only the New shell can honour.

onResults is called from one goroutine, never concurrently. An error it returns is handled as a cancellation: already accepted items finish and are delivered normally, items still inside the read pipeline are delivered as failures with that error, the batch in hand is still submitted, the next Submit returns an error, and Wait returns it. A result that carries any error is delivered immediately as its own batch; results without an error are buffered until the delivery reaches WithResultBatch results, the result flush interval elapses, or Close flushes them.

func (*StreamCopyer) Close added in v0.2.1

func (c *StreamCopyer) Close() error

Close ends the feed and drains the run: every item already submitted finishes and all dependent cache and Close work settle, the remaining results are flushed, and the run's cache summary is reported. It returns the flush error, and it is safe to call more than once.

func (*StreamCopyer) HardStopped added in v0.2.7

func (c *StreamCopyer) HardStopped() <-chan struct{}

HardStopped returns a channel closed when a fatal pipeline failure ends per-item accounting. It does not signal normal completion, graceful stopping or physical source settlement. Call Close and Wait to settle resources and obtain the run's authoritative terminal error.

func (*StreamCopyer) Submit added in v0.2.1

func (c *StreamCopyer) Submit(items ...Item) error

Submit accepts items. It blocks while the read buffer is full, so a caller that produces work faster than the pipeline reads it is slowed down instead of growing memory, and it returns an error once the run accepts no more work: after Close, after the context ended, after the results callback returned an error, or after a fatal pipeline failure.

A single submitter is required, and Items must be submitted before Close. A nil item is a submission error that does not end the feed: it is recorded as the run's error, so Wait reports it, and the items submitted after it are still accepted.

func (*StreamCopyer) Wait added in v0.2.1

func (c *StreamCopyer) Wait() error

Wait drains the run and returns its terminal error: a pipeline failure, a submission error, an error the results callback returned, or a flush failure. It is the authoritative outlet for run-time errors, and a caller that stopped the run gracefully reads the stopping error here.

type TargetEncoderItem added in v0.2.10

type TargetEncoderItem interface {
	TargetEncoder() (encoding string, encode func(dst io.Writer) (io.WriteCloser, error))
}

TargetEncoderItem optionally encodes every native target of one item. ACP calls TargetEncoder once while indexing; a nil encode writes plaintext, and a non-nil one requires a non-empty encoding name of at most 64 bytes. For each native output ACP calls the encoder with that output's file writer, writes the item's plaintext into the returned writer and closes it once after the last write. Close flushes the encoded tail into dst and returns only after every write into dst has finished. An encoded target is never preallocated and always receives a managed signature entry that names the encoding and describes the plaintext; the entry marks the file as encoded, so a failure to write it fails that target. Content targets are not encoded.

type TargetResult added in v0.2.1

type TargetResult struct {
	Path string
	// Size is the item's size as read, so a failed or partially written target reports that
	// size rather than a count of the bytes that landed there.
	Size int64
	// StoredSize counts the bytes ACP wrote to a written native target: Size, or the encoded
	// size when the item encodes its targets. It is zero for a failed or content target.
	StoredSize int64
	WriteTime  time.Time

	// Err is nil when the target was written. Target failures keep their error identity, so
	// errors.Is(err, ErrTargetNoSpace) identifies an exhausted medium.
	Err error
}

TargetResult is the outcome of one requested target.

type WildcardJobOption

type WildcardJobOption func(*wildcardJob) *wildcardJob

WildcardJobOption configures one WildcardJob.

func AccurateSource

func AccurateSource(base string, paths ...[]string) WildcardJobOption

AccurateSource adds sources as base plus relative path segments to a WildcardJob.

func Source

func Source(paths ...string) WildcardJobOption

Source adds source paths to a WildcardJob. A source may be a directory or a regular file.

func Target

func Target(paths ...string) WildcardJobOption

Target adds target directories to a WildcardJob. Every one of them must exist.

type XattrReader added in v0.2.7

type XattrReader interface {
	Xattrs() (map[string][]byte, error)
}

XattrReader optionally supplies ordinary attributes from an opened content source. Values are opaque bytes. Providers normalize missing or unsupported attribute facilities to an empty map.

Directories

Path Synopsis
cmd
acp command
acp-rewrite command
internal
fileio
Package fileio owns temporary command files and atomic JSON replacement.
Package fileio owns temporary command files and atomic JSON replacement.
signaturepb
Package signaturepb holds the Protobuf form of the managed signature xattr entry.
Package signaturepb holds the Protobuf form of the managed signature xattr entry.
Package mmap provides a way to memory-map a file.
Package mmap provides a way to memory-map a file.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL