xfer

package
v0.187.0 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 17 Imported by: 0 modules, 0 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.

Documentation

Overview

Package xfer implements XFER-01's transfer staging area and journal: the on-disk staging directory a transfer's payload passes through (<root>/xfer/<id>/data) and the business operations recorded against it (stage a put/get, dispatch it to the executing machine, settle it done/failed, expire it). It is a data/business layer package: it never imports httpapi/commands (G022) — the CLI, the HTTP handlers and the worker hub all consume it through the seams declared here.

The payload bytes NEVER travel through the journal: the HTTP layer streams them into Store (a temporary file renamed into place only after the sha256 and size have been verified), so an aborted or corrupted upload can never be handed to an executing machine.

Index

Constants

View Source
const AttachmentRetention = 7 * 24 * time.Hour

AttachmentRetention is how long a placed attachment's date directory survives on the executing machine: a placement prunes the ones older than this (the design's 7 days). There is no separate timer — the cleanup rides on the next placement.

View Source
const AttachmentsDirName = "gofer-attachments"

AttachmentsDirName is the directory placed attachments live in, under a project's EXCHANGE directory (the same base a job's result dir is built from): the default location is therefore <project root>/tmp/gofer-attachments, and a project that moved its exchange_subdir keeps its attachments next to its transfer exchange dir.

View Source
const DefaultPutWaitTimeout = 60 * time.Second

DefaultPutWaitTimeout bounds PutAndWait. The far side is bounded by its own worker.xfer_timeout_sec (10 minutes by default), so a SHORTER wait is a caller-side budget, not a transfer deadline: it is what keeps one slow machine from stalling a message the user is waiting on.

View Source
const DefaultWorkerTimeout = 10 * time.Minute

DefaultWorkerTimeout bounds one transfer on a worker (worker.xfer_timeout_sec overrides it). A transfer that cannot finish in the window is failed rather than left dispatched forever: nothing here is resumable, so a stalled worker (or a worker that died mid-file) must not hold a record open.

Variables

View Source
var (
	// ErrTooLarge is returned when a transfer exceeds the configured byte cap.
	ErrTooLarge = errors.New("too large")
	// ErrNotFound is returned when no journal row matches an id.
	ErrNotFound = errors.New("xfer not found")
	// ErrExists is the worker-side refusal to overwrite an existing destination
	// without --force (mapped to a failed transfer with error "exists").
	ErrExists = errors.New("exists")
	// ErrNotStaged is returned when an operation requires a staged record.
	ErrNotStaged = errors.New("xfer is not staged")
)

Sentinel errors. ErrTooLarge and ErrExists are surfaced to the caller's wire error text verbatim (the CLI prints them as-is), so their messages are part of the contract.

Functions

func AttachmentsDir added in v0.177.0

func AttachmentsDir(cfg *config.Config, proj config.ProjectConfig) (string, error)

AttachmentsDir returns the absolute attachment directory of a project: <exchange dir>/gofer-attachments.

The result is re-checked to be INSIDE the project's execution root, because its caller DELETES directories in it: project.ExchangeDir already resolves the exchange subdir with project.SafeJoin (so an escaping `exchange_subdir` is refused), and the extra relative check keeps that guarantee explicit here instead of one import away.

func ContentPath

func ContentPath(id string) string

ContentPath is the server-relative URL of a transfer's payload: the endpoint a worker downloads a put's source from and uploads a get's result to.

func EventJobID

func EventJobID(id string) string

EventJobID is the synthetic event-log owner id of one transfer.

func IsAttachmentPath added in v0.177.0

func IsAttachmentPath(dir, path string) bool

IsAttachmentPath reports whether path lies strictly inside dir (the directory itself is not "inside" it: a prune must never act on the base).

func NewID

func NewID() string

NewID mints a transfer id: `xf-` + 8 random hex chars (XFER-02 decision 5 — every new short id is `<2 letters>-<8hex>`, like the wakeups' `wk-`).

The old form was 32 hex chars; the short form is what a human reads in `tool xfer ls` / an event scope. 2^-32 per row is not a security boundary on its own and is not meant to be one: fetching a transfer's content is gated by the CALLER (a worker may only fetch its own put, and only a user caller sees a get's result), so a guessed id buys nothing. Collisions are absorbed by the unique id column plus the staging retry (see Manager.stage), and rows written with the old 32-hex ids stay readable — nothing parses an id's shape.

func PruneAttachments added in v0.177.0

func PruneAttachments(dir string, now time.Time) ([]string, error)

PruneAttachments deletes the DATE subdirectories of dir older than AttachmentRetention and returns their names. It only ever looks one level deep, only at directories whose name parses as YYYYMMDD, and never follows an entry out of dir — so a file the operator dropped in there, or a differently named directory, survives.

A missing dir is not an error: nothing was ever placed on this machine.

func PruneAttachmentsAfterPut added in v0.177.0

func PruneAttachmentsAfterPut(cfg *config.Config, proj config.ProjectConfig, dst, component string)

PruneAttachmentsAfterPut is the post-placement step both executing sides run: when dst landed under the project's attachment directory, the date subdirectories older than AttachmentRetention are deleted.

It is BEST EFFORT by contract: the file is already in place, so a prune failure (or a project whose paths do not resolve) must never turn a successful placement into a failed transfer. The only report is a log line; component names the side doing it ("server" / "worker") so an operator can tell the two machines apart.

Types

type EventSink

type EventSink interface {
	RecordScopedEvent(scope, eventType, projectKey string, detail map[string]any)
}

EventSink records one transfer audit event. A transfer is not a job, so its events are recorded under the synthetic scope id `xfer:<id>` (EventJobID): the durable log, the SSE/poll cursor and the audit trail are shared with job events, while the id keeps them out of every real job's stream.

The production sink is *job.Service (RecordScopedEvent): it persists the event AND runs it through the notification pipeline (E14 webhook enqueue), so an operator can subscribe to xfer.put|xfer.get like any other event. StoreSink is the bare audit-only sink for a deployment or test with no job service wired.

func StoreSink

func StoreSink(st *jobstore.Store) EventSink

StoreSink adapts the metadata store into an audit-only EventSink: the event lands in the shared log and nothing is notified. It is what a transfer manager built without a job service (a focused test, a standalone tool) gets.

type FileXferRequest

type FileXferRequest struct {
	XferID     string
	Op         string
	ProjectKey string
	Path       string
	Size       int64
	SHA256     string
	Force      bool
	// URLPath is the server-relative content URL the worker fetches (put) or
	// uploads to (get).
	URLPath string
}

FileXferRequest is one transfer instruction for a worker. It deliberately mirrors the wire frame instead of sharing it, so this package stays free of the wire protocol (wsproto is imported only by the hub/worker and the assembly adapter that converts one into the other).

type FileXferResult

type FileXferResult struct {
	XferID     string
	OK         bool
	Size       int64
	SHA256     string
	Error      string
	DurationMS int64
	// AbsPath is the absolute destination the worker reports for a put (empty for a
	// get, and for a worker below wsproto.XferAbsPathMinProtocolVersion).
	AbsPath string
}

FileXferResult is a worker's report for one transfer.

type Limits

type Limits struct {
	MaxBytes int64
	TTL      time.Duration
	// CollectMaxBytes caps the sum of one job's collected files. Per-file is still
	// MaxBytes; this is what stops a job from filling the disk with many files that
	// are each under the cap.
	CollectMaxBytes int64
}

Limits are the operator-tunable caps (server.xfer): the per-transfer byte ceiling, how long a staged/finished transfer survives in the staging area, and how much one JOB's `--collect` may bring back in total (XFER-01 X2).

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits are the documented XFER-01 defaults (design §一.1/§一.3): 256MB per transfer, 24h in the staging area, 1GB per job's collect.

type LocalRunner

type LocalRunner struct {
	// Config returns the config in force NOW (nil means "not assembled").
	Config func() *config.Config
	// Store is the staging area the payload passes through: the source of a put, the
	// destination of a get.
	Store *Store
	// OnGetContent is called with the size + sha256 of the payload a get just staged,
	// and its error FAILS the transfer. The assembly points it at the manager's
	// CommitGet (which makes the staged payload visible and records the digest); a
	// failure there must not be swallowed, or the transfer would be reported done with
	// nothing to download.
	OnGetContent func(id string, size int64, sha256 string) error
}

LocalRunner is the `runner=local` half of XFER-01: it moves the payload on the SERVER's own machine (the canonical `local` spelling, also written `server`), with no worker and no wire involved.

It is a thin Runner over the staging Store, deliberately narrow: it knows how to resolve a project root and how to copy bytes, and nothing about the journal. The journal is settled by Manager.Deliver from Run's outcome — and, for a get, from the digest this runner reports through OnGetContent (Run cannot return the size/sha a get produced, and the alternative — handing this type the journal — would put the transfer's state machine in two places).

Every path decision is re-read from Config() PER CALL: the server hot-reloads its config (SIGHUP / a web edit), so a cached ProjectConfig would let a transfer land in a project root the operator has already moved.

func (*LocalRunner) Run

Run implements Runner: it resolves the record's target on this machine and moves the bytes. ErrExists and ErrNotFound are the two sentinel outcomes Manager.Deliver maps onto the operator-facing reason ("exists" / "source not found").

A put reports the absolute destination it just wrote: on this machine that path is known here, so no round trip is needed to name the file the receiving agent must read.

type Manager

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

Manager carries out the transfer business operations over a Store and a Repo.

func NewManager

func NewManager(opts Options) (*Manager, error)

NewManager builds a Manager from opts. It fails when no journal (Repo) is given: every transfer must be recorded.

func (*Manager) CommitGet

func (m *Manager) CommitGet(id string, size int64, sha256 string) error

CommitGet records the payload a worker uploaded for a get (its size + sha256), making it visible for the client to download.

func (*Manager) CommitPut

func (m *Manager) CommitPut(id string, size int64, sha256 string) error

CommitPut makes a verified upload visible: the temporary payload is renamed into place and the journal records the confirmed size + sha256. The caller has already compared the streamed digest against the value the client declared, so a mismatch never reaches here.

func (*Manager) Deliver

func (m *Manager) Deliver(ctx context.Context, id string) error

Deliver drives one staged transfer to a terminal state: it marks the record dispatched, runs it through the configured Router and settles it done/failed from the outcome. A record that is not staged is left untouched, so a duplicate dispatch (a retried HTTP call, a re-delivered result) is a no-op.

func (*Manager) Dispatch

func (m *Manager) Dispatch(ctx context.Context, id string)

Dispatch runs Deliver in the background so the HTTP request that created the transfer returns as soon as the payload is staged; the client follows progress through GET /v1/xfer/{id}. Without a runner wired (mcp, tests) it is a no-op: the record stays staged rather than being failed for a deployment that simply does not execute transfers.

func (*Manager) Expire

func (m *Manager) Expire(now time.Time) (int, error)

Expire applies the TTL: every journal row past expires_at is marked expired and its staging directory removed, then orphan directories (a Create with no row, or a row the journal lost) older than the TTL are swept. It returns how many journal rows were expired.

func (*Manager) Fail

func (m *Manager) Fail(id, reason string) error

Fail settles a transfer as failed and drops its staging directory (a failed transfer's partial bytes must never be served). Use it for a rejection detected before dispatch; MarkFailed handles the post-dispatch path.

func (*Manager) Get

func (m *Manager) Get(id string) (jobstore.XferRecord, bool, error)

Get returns one transfer row.

func (*Manager) Limits

func (m *Manager) Limits() Limits

Limits returns the effective caps (the HTTP layer answers 413 from MaxBytes).

func (*Manager) List

List returns transfer rows newest-first.

func (*Manager) MarkDone

func (m *Manager) MarkDone(id string) error

MarkDone settles a transfer as done and records its audit event exactly once.

func (*Manager) MarkFailed

func (m *Manager) MarkFailed(id, reason string) error

MarkFailed settles a transfer as failed with reason, dropping its staging directory. A transfer already in a terminal state is left alone (idempotent), so a late worker result cannot overwrite a settled outcome.

func (*Manager) OnWorkerResult

func (m *Manager) OnWorkerResult(res FileXferResult) error

OnWorkerResult applies a worker result that arrived with no waiter (a frame for a transfer whose dispatch already gave up, or a duplicate). It only settles a record that is still dispatched — a settled transfer is never reopened.

func (*Manager) PutAndWait added in v0.177.0

func (m *Manager) PutAndWait(ctx context.Context, caller, runner, projectKey, srcPath, dest string, timeout time.Duration) (string, error)

PutAndWait stages srcPath as a put to <runner>:<project>/<dest>, executes it and waits for it to settle. It returns the ABSOLUTE path the executing machine reported for the destination — empty when that machine cannot report one (a worker below wsproto.XferAbsPathMinProtocolVersion) — or the transfer's own failure reason (worker offline, path escapes project, exists, too large…).

The staging overwrites an existing destination: a re-delivery of the same attachment is then idempotent instead of failing on the copy the previous attempt left. timeout <= 0 means DefaultPutWaitTimeout; on a timeout the record is settled FAILED, so a stalled far side can never leave it dispatched forever.

func (*Manager) Release

func (m *Manager) Release(id string) error

Release drops a SETTLED transfer's staged payload without touching its journal row: the bytes were copied where they belong (XFER-01 X2 hands a collected file to the job's artifact directory), so keeping a second copy would only spend disk. The row stays for audit and is expired by the TTL sweep like any other.

func (*Manager) Remove

func (m *Manager) Remove(id string) error

Remove deletes a transfer: its staging directory first (so a half-deleted transfer can never be downloaded), then its journal row.

func (*Manager) SetAbsPath added in v0.177.0

func (m *Manager) SetAbsPath(id, absPath string) error

SetAbsPath records the absolute destination an executing machine reported for a completed put. An empty path records nothing (a get, a failed transfer, or a worker below the protocol floor that cannot report one), so callers never have to guard.

func (*Manager) SetRunner

func (m *Manager) SetRunner(r Runner)

SetRunner installs the executor for staged transfers. It is wired at assembly time (serve); without one a staged transfer stays staged.

func (*Manager) StageGet

func (m *Manager) StageGet(caller, runner, projectKey, path string) (jobstore.XferRecord, error)

StageGet records a transfer that fetches <runner>:<project>/<path> back to the server. The staging directory is created up front so the executing worker can upload the result into it.

func (*Manager) StageGetForJob

func (m *Manager) StageGetForJob(jobID, runner, projectKey, path string) (jobstore.XferRecord, error)

StageGetForJob records a pull that belongs to a job. caller and job id are the same value: the audit trail then names the job, which is what the collect step acted for (there is no human behind it to name).

func (*Manager) StagePut

func (m *Manager) StagePut(caller, runner, projectKey, path string, size int64, sha256 string, force bool) (jobstore.XferRecord, error)

StagePut records a pending upload of size bytes towards <runner>:<project>/<path>. The payload is streamed into the staging area by the caller (Store().Writer) and made visible with CommitPut. force allows overwriting an existing destination.

func (*Manager) StagePutFromFile

func (m *Manager) StagePutFromFile(caller, runner, projectKey, srcPath, dest string, overwrite bool) (jobstore.XferRecord, error)

StagePutFromFile stages ONE local file as a put transfer and returns its record: the bytes are copied from srcPath into the staging area in one step, with the size and sha256 computed HERE (the caller cannot under-declare them). It is what lets a caller that already holds the file on this machine — the JOB-10 skills mount — reuse the transfer channel without an HTTP round trip through its own server.

overwrite allows the placement to replace an existing destination (a re-delivery of the SAME payload is then idempotent instead of failing with "exists"); false keeps the refusing default the CLI's `--force` flips.

A staging failure leaves no journal row: the record is created first (that is where the id comes from) and removed again if the copy or the commit fails, exactly like the HTTP path's cleanup.

func (*Manager) Store

func (m *Manager) Store() *Store

Store exposes the staging area (the HTTP layer streams payloads through it).

func (*Manager) Wait added in v0.157.0

func (m *Manager) Wait(ctx context.Context) error

Wait blocks until every delivery started by Dispatch has returned, or ctx ends.

type Op

type Op string

Op is a transfer's direction. put = a local file travels TO the executing machine; get = a file is fetched FROM it.

const (
	OpPut Op = "put"
	OpGet Op = "get"
)

type Options

type Options struct {
	// Root is the base directory the staging area is created under: the Manager
	// owns <Root>/xfer. serve passes storage.root when set, else the config dir.
	Root string
	// Limits are the byte/TTL caps; zero fields fall back to DefaultLimits.
	Limits Limits
	// Repo is the journal (required).
	Repo Repo
	// Events is the optional audit sink; nil disables event recording.
	Events EventSink
	// Now is the clock seam (tests); nil = time.Now.
	Now func() time.Time
}

Options configures a Manager.

type Repo

type Repo interface {
	InsertXfer(jobstore.XferRecord) error
	GetXfer(id string) (jobstore.XferRecord, bool, error)
	ListXfers(jobstore.XferFilter) ([]jobstore.XferRecord, error)
	UpdateXferState(id, state, errMsg string, finishedAt int64) error
	SetXferContent(id string, size int64, sha256 string) error
	SetXferAbsPath(id string, absPath string) error
	DeleteXfer(id string) error
	ExpiredXfers(now int64) ([]jobstore.XferRecord, error)
}

Repo is the journal persistence seam, satisfied by *jobstore.Store. It is declared here (rather than the Manager holding a concrete store) so the xfer business logic is testable without SQLite and so the HTTP layer can build a Manager over a stub.

type Router

type Router struct {
	// Local executes a transfer against the server's own project roots. nil means
	// the local runner is not wired (a `server:` target then fails cleanly).
	Local Runner
	// Sender reaches workers. nil means no worker can be reached.
	Sender WorkerSender
	// Timeout bounds one worker transfer; 0 = DefaultWorkerTimeout.
	Timeout time.Duration
}

Router picks the executor for a staged transfer from its runner name: the server's own machine (`local`, the canonical spelling of `server`) is executed in-process, anything else is a worker.

func (*Router) Run

func (r *Router) Run(ctx context.Context, rec jobstore.XferRecord) (RunResult, error)

Run implements Runner.

type RunResult added in v0.177.0

type RunResult struct {
	AbsPath string
}

RunResult is what one executed transfer reports back to the journal. AbsPath is the absolute path the payload ended up at on the EXECUTING machine (a put's destination, as that machine's own filesystem sees it); it is empty for a get and for a worker that cannot report one (protocol below wsproto.XferAbsPathMinProtocolVersion).

type Runner

type Runner interface {
	Run(ctx context.Context, rec jobstore.XferRecord) (RunResult, error)
}

Runner executes one already-staged transfer on its executing machine. The server-local implementation and the worker-hub adapter both satisfy it; returning a nil error means the bytes are in place, and any other error is the terminal failure reason (ErrExists is surfaced as the literal "exists").

type State

type State string

State is a transfer's position in the state machine (design §一.2). staged = the payload is complete on the server (put) or the record is ready to dispatch (get); dispatched = handed to the executing machine, awaiting its result; done = the bytes are where they belong; failed/expired are terminal.

const (
	StateStaged     State = "staged"
	StateDispatched State = "dispatched"
	StateDone       State = "done"
	StateFailed     State = "failed"
	StateExpired    State = "expired"
)

func (State) Terminal

func (s State) Terminal() bool

Terminal reports whether a state can no longer change.

type Store

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

Store owns the staging area: one directory per transfer id under root, containing the payload as `data` plus `data.tmp` while a transfer is being written. All payload I/O goes through here so the temp-then-rename discipline (and the TTL sweep) lives in exactly one place.

func NewStore

func NewStore(root string) *Store

NewStore returns a staging store rooted at root (the `xfer` directory itself — the Manager composes it from the configured storage/config root).

func (*Store) Create

func (s *Store) Create(id string) error

Create makes (idempotently) a transfer's staging directory.

func (*Store) Dir

func (s *Store) Dir(id string) string

Dir is a transfer's staging directory.

func (*Store) Finalize

func (s *Store) Finalize(id string, size int64) error

Finalize moves the verified payload into place. size < 0 skips the size check. The caller has already verified the sha256 against the expected value while streaming (that is what makes an aborted upload impossible to serve); Finalize only guards against a truncated/oversized temp file and makes the payload visible atomically.

func (*Store) Path

func (s *Store) Path(id string) string

Path is the absolute path of a transfer's payload.

func (*Store) Reader

func (s *Store) Reader(id string) (io.ReadCloser, error)

Reader opens a transfer's payload for reading (downloading to a client, or to an executing machine).

func (*Store) Remove

func (s *Store) Remove(id string) error

Remove deletes a transfer's whole staging directory. It is not an error when the directory is already gone.

func (*Store) Root

func (s *Store) Root() string

Root is the directory every transfer directory lives under.

func (*Store) Stat

func (s *Store) Stat(id string) (int64, error)

Stat reports the payload's size (an error when it is not present).

func (*Store) Sweep

func (s *Store) Sweep(now time.Time, ttl time.Duration) ([]string, error)

Sweep removes staging directories whose last modification is older than ttl — the disk-side half of expiry, covering the orphans the journal no longer knows about (a crash between Create and Insert). It returns the ids it removed, so a caller can log them.

func (*Store) Writer

func (s *Store) Writer(id string) (io.WriteCloser, error)

Writer opens the temporary payload file for a transfer. The caller MUST close it and then call Finalize (or Remove) — an un-finalized temporary file is never served.

type WorkerSender

type WorkerSender interface {
	SendFileXfer(ctx context.Context, workerID string, req FileXferRequest) (FileXferResult, error)
}

WorkerSender sends one transfer instruction to a worker and waits for its result. It is the seam the hub satisfies (through an adapter) and the one tests stub; a nil sender means "this deployment cannot reach workers".

Jump to

Keyboard shortcuts

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