Documentation
¶
Overview ¶
Package sync plans and executes transfers between a local library and a device.
The planner in plan.go is a pure function over (local set, device listing, manifest). It performs no I/O and reads no clock, which is what makes the decision table in the spec directly testable.
Index ¶
- Constants
- func ApplyDrops(m *Manifest, drops []string)
- func NewUUIDv7() string
- func WriteDeviceState(ctx context.Context, t Transport, m *Manifest) error
- type Candidate
- type DeviceMarker
- type Entry
- type Event
- type EventKind
- type ExecOptions
- type Input
- type LocalBook
- type Manifest
- func (m *Manifest) ByDevicePath() map[device.Path]*Entry
- func (m *Manifest) ByLocalPath() map[string]*Entry
- func (m *Manifest) Bytes() ([]byte, error)
- func (m *Manifest) Put(e Entry)
- func (m *Manifest) RemoveDevice(p device.Path) bool
- func (m *Manifest) RemoveLocal(localPath string) bool
- func (m *Manifest) Save(path string) error
- func (m *Manifest) Touch(now time.Time)
- type Op
- type OpKind
- type Options
- type Plan
- type Prepared
- type Preparer
- type PreparerConfig
- type Result
- type Transport
Constants ¶
const ( ShelfDir = "/shelf" MarkerPath = "/shelf/device.json" ManifestPath = "/shelf/manifest.json" )
Device-side paths for shelf's own state.
const ManifestVersion = 1
ManifestVersion is the schema version of the per-device state file.
Variables ¶
This section is empty.
Functions ¶
func ApplyDrops ¶
ApplyDrops removes manifest entries the planner decided to forget.
Types ¶
type Candidate ¶
type Candidate struct {
// Path is the file in the library.
Path string
// Format is the lowercase source format, without a dot ("epub", "pdf").
Format string
// SHA256 and Size describe the source file, as recorded in the index.
SHA256 string
Size int64
// RelPath is the device-relative destination without an extension.
RelPath string
}
Candidate is a library book offered for syncing.
RelPath carries no extension: the destination's extension depends on what conversion produces, which is not known until it runs.
type DeviceMarker ¶
type DeviceMarker struct {
Version int `json:"version"`
DeviceUUID string `json:"device_uuid"`
Nickname string `json:"nickname"`
Created int64 `json:"created_unix"`
}
DeviceMarker is the file shelf writes to identify a device.
It lives in a visible /shelf directory rather than a dotfile: the firmware hides dotfiles from listings unless showHiddenFiles is enabled and refuses to serve some of them, and one extra folder in the device's browser is a small price for avoiding that whole class of failure.
type Entry ¶
type Entry struct {
// SHA256 is the hash of the bytes actually sent, which after optimization
// is not the hash of the local source file. Recording what was sent means
// an unchanged optimizer profile produces no churn.
SHA256 string `json:"sha256"`
// DevicePath is pinned. Once a book occupies a path it keeps that path,
// because every rename, move, and re-upload clears the firmware's
// .crosspoint cache for it, destroying the reading position.
DevicePath string `json:"device_path"`
DeviceSize int64 `json:"device_size"`
LocalPath string `json:"local_path"`
UploadedUnix int64 `json:"uploaded_unix"`
Optimized bool `json:"optimized,omitempty"`
OptimizeProfile string `json:"optimize_profile,omitempty"`
}
Entry records one book's placement on the device.
type Event ¶
type Event struct {
Kind EventKind
Op Op
Index int // 1-based position in the plan
Total int // number of operations
Sent int64
Size int64
Attempt int
Err error
}
Event reports execution progress. The CLI prints these; the TUI will feed them to tea.Program.Send.
type ExecOptions ¶
type ExecOptions struct {
// InterOpDelay gives the ESP32 time to flush its SD writes between
// operations. The device is slow to commit and a tight loop provokes
// write failures.
InterOpDelay time.Duration
// MaxRetries bounds attempts per operation. There is no resume, so every
// retry restarts the file from byte zero.
MaxRetries int
// ChunkSize is passed through to the uploader.
ChunkSize int
// Events, when set, receives progress.
Events func(Event)
// DryRun reports what would happen without touching the device.
DryRun bool
}
ExecOptions tunes execution.
type Input ¶
type Input struct {
// Root is the device directory the shelf syncs into.
Root device.Path
// Local is the set of books that should be on the device.
Local []LocalBook
// Device is the current device listing, keyed by full path.
Device map[device.Path]device.FileEntry
// Manifest records what shelf placed previously.
Manifest *Manifest
Options Options
}
Input is everything the planner needs.
type LocalBook ¶
type LocalBook struct {
// Path is the local file, and the book's identity in the manifest.
//
// For a converted or optimized book this stays the library source — the
// PDF on disk, not the derived artifact. The manifest is keyed by it, so
// it has to be stable across everything that can change the bytes: a
// decant upgrade or a profile bump moves the artifact to a new cache path,
// and if that path were the identity the planner would see a brand new
// book, upload it beside the old one, and orphan a pinned file.
Path string
// UploadPath is the file whose bytes are sent. Empty means Path.
//
// This is what splits identity from content: the derived artifact supplies
// the bytes, while Path continues to say which book they belong to.
UploadPath string
// SHA256 is the hash of the bytes that will be sent, and Size their size.
// After conversion or optimization neither describes the source file.
SHA256 string
Size int64
// RelPath is the device-relative destination rendered from the naming
// template. It is used only for books that are not already pinned.
RelPath string
// Optimized records that the bytes were built for a device profile, and
// which one, so the manifest can say what produced them.
Optimized bool
OptimizeProfile string
}
LocalBook is one candidate for syncing.
type Manifest ¶
type Manifest struct {
Version int `json:"version"`
DeviceUUID string `json:"device_uuid"`
Nickname string `json:"nickname"`
Model string `json:"model"`
Firmware string `json:"firmware"`
Root string `json:"root"`
LastSyncUnix int64 `json:"last_sync_unix"`
Entries []Entry `json:"entries"`
}
Manifest is shelf's record of what it has placed on one device.
It is stored locally and mirrored to /shelf/manifest.json on the device, so that a second machine can reconstruct the same state rather than treating every book as new.
func LoadManifest ¶
LoadManifest reads a manifest from disk. A missing file yields a new, empty manifest rather than an error, since that is the state before a first sync.
func NewManifest ¶
NewManifest creates an empty manifest with a fresh device identity.
func (*Manifest) ByDevicePath ¶
ByDevicePath indexes entries by their pinned device path.
func (*Manifest) ByLocalPath ¶
ByLocalPath indexes entries by their local file path.
func (*Manifest) RemoveDevice ¶
RemoveDevice drops the entry occupying a device path.
func (*Manifest) RemoveLocal ¶
RemoveLocal drops the entry for a local path, reporting whether it existed.
type Op ¶
type Op struct {
Kind OpKind
DevicePath device.Path
// From is the source path for a move.
From device.Path
// LocalPath is the file to read for an upload.
LocalPath string
// SourcePath is the library file this book came from, which is what the
// manifest is keyed by. It differs from LocalPath only when the bytes
// being sent are a derived artifact. Empty means LocalPath.
SourcePath string
Size int64
SHA256 string
// Optimized and OptimizeProfile are carried through to the manifest entry.
Optimized bool
OptimizeProfile string
// Reason is shown in dry-run output.
Reason string
}
Op is one planned operation.
type Options ¶
type Options struct {
// Prune deletes device files that shelf placed but the shelf no longer
// contains, and orphans that shelf did not place.
Prune bool
// RespectDeviceDeletes treats a book deleted on the device as intentional
// and drops it from the manifest rather than re-uploading it.
RespectDeviceDeletes bool
// Repath allows moving already-pinned books to the path the current
// template renders. This destroys reading positions and is never implied.
Repath bool
}
Options control planning policy.
type Plan ¶
type Plan struct {
Ops []Op
// Orphans are device files shelf did not place. They are reported but only
// deleted under --prune.
Orphans []device.Path
// Warnings describe situations the user should know about but that do not
// stop the sync.
Warnings []string
// RepathWarnings lists books that would lose their reading position. A
// caller must show these and get confirmation before executing.
RepathWarnings []string
// Drops are manifest entries to forget without touching the device.
Drops []string
Unchanged int
TotalBytes int64
}
Plan is the result of planning.
func Build ¶
Build computes the operations needed to bring the device into agreement with the local shelf.
The decision table, from the spec:
manifest device size action present present match no-op present present differ re-upload in place present absent - re-upload, or drop under --respect-device-deletes absent present - orphan: report, delete only under --prune present local gone delete under --prune, else warn
type Prepared ¶
type Prepared struct {
Books []LocalBook
// Notes describe what happened to individual books: conversions, skips,
// and failures. A failure here is not fatal to the run — one unconvertible
// PDF should not stop a hundred good books from syncing — so the caller
// shows these and continues.
Notes []string
// Failed counts books that could not be prepared.
Failed int
}
Prepared is the result of preparing a shelf.
type Preparer ¶
type Preparer struct {
// Convert supplies converted EPUBs. Nil disables conversion, which makes
// any format the device cannot render a skip.
Convert *convert.Cache
// Resolve picks a converter for a source file. Nil disables conversion.
Resolve func(src string) (*convert.Converter, error)
// Optimize supplies device-targeted EPUBs. Nil disables optimization.
Optimize *convert.OptimizeCache
// Profile is the optimization target. Ignored when Optimize is nil.
Profile convert.Profile
// Syncable reports whether the device can render a format directly. A
// format that is neither syncable nor convertible is skipped.
Syncable func(format string) bool
}
Preparer turns candidates into planner input.
func NewPreparer ¶
func NewPreparer(c PreparerConfig) *Preparer
NewPreparer assembles the standard conversion and optimization pipeline.
type PreparerConfig ¶
type PreparerConfig struct {
// ConvertCacheDir and OptimizedDir are the two derived-artifact caches.
ConvertCacheDir string
OptimizedDir string
// ConverterName is the configured converter, used for the formats it
// accepts and fallen back from for the ones it does not.
ConverterName string
Timeout time.Duration
// Optimize enables device-targeted optimization, and Profile is its
// target.
Optimize bool
Profile convert.Profile
// Syncable reports whether the device renders a format directly. Supplied
// by the caller so this package does not need to know the library's
// format vocabulary.
Syncable func(format string) bool
}
PreparerConfig is the settings NewPreparer needs.
It exists so the CLI and the TUI build an identical pipeline rather than each assembling one and drifting apart.
type Result ¶
type Result struct {
Completed int
Failed int
Skipped int
BytesSent int64
Errors []error
Aborted bool
AbortedFor error
}
Result summarizes an execution.
func Execute ¶
func Execute(ctx context.Context, t Transport, plan Plan, m *Manifest, opts ExecOptions) (*Result, error)
Execute runs a plan against a device, serially.
Serial by design, not by omission: the firmware accepts one upload at a time, and the device is a microcontroller whose SD writes need breathing room.
type Transport ¶
type Transport interface {
Mkdir(ctx context.Context, p device.Path) error
Upload(ctx context.Context, dest device.Path, r io.Reader, size int64, opts device.UploadOptions) error
Delete(ctx context.Context, p device.Path) error
Move(ctx context.Context, from, to device.Path) error
Status(ctx context.Context) (*device.Status, error)
}
Transport is the subset of the device client the executor needs. Keeping it an interface lets the SD-card transport drop in later without touching the executor, and lets tests run the full engine without a network.