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
- Variables
- func ContentPath(id string) string
- func EventJobID(id string) string
- func NewID() string
- type EventSink
- type FileXferRequest
- type FileXferResult
- type Limits
- type LocalRunner
- type Manager
- func (m *Manager) CommitGet(id string, size int64, sha256 string) error
- func (m *Manager) CommitPut(id string, size int64, sha256 string) error
- func (m *Manager) Deliver(ctx context.Context, id string) error
- func (m *Manager) Dispatch(ctx context.Context, id string)
- func (m *Manager) Expire(now time.Time) (int, error)
- func (m *Manager) Fail(id, reason string) error
- func (m *Manager) Get(id string) (jobstore.XferRecord, bool, error)
- func (m *Manager) Limits() Limits
- func (m *Manager) List(f jobstore.XferFilter) ([]jobstore.XferRecord, error)
- func (m *Manager) MarkDone(id string) error
- func (m *Manager) MarkFailed(id, reason string) error
- func (m *Manager) OnWorkerResult(res FileXferResult) error
- func (m *Manager) Release(id string) error
- func (m *Manager) Remove(id string) error
- func (m *Manager) SetRunner(r Runner)
- func (m *Manager) StageGet(caller, runner, projectKey, path string) (jobstore.XferRecord, error)
- func (m *Manager) StageGetForJob(jobID, runner, projectKey, path string) (jobstore.XferRecord, error)
- func (m *Manager) StagePut(caller, runner, projectKey, path string, size int64, sha256 string, force bool) (jobstore.XferRecord, error)
- func (m *Manager) StagePutFromFile(caller, runner, projectKey, srcPath, dest string) (jobstore.XferRecord, error)
- func (m *Manager) Store() *Store
- type Op
- type Options
- type Repo
- type Router
- type Runner
- type State
- type Store
- func (s *Store) Create(id string) error
- func (s *Store) Dir(id string) string
- func (s *Store) Finalize(id string, size int64) error
- func (s *Store) Path(id string) string
- func (s *Store) Reader(id string) (io.ReadCloser, error)
- func (s *Store) Remove(id string) error
- func (s *Store) Root() string
- func (s *Store) Stat(id string) (int64, error)
- func (s *Store) Sweep(now time.Time, ttl time.Duration) ([]string, error)
- func (s *Store) Writer(id string) (io.WriteCloser, error)
- type WorkerSender
Constants ¶
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 ¶
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 ContentPath ¶
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 ¶
EventJobID is the synthetic event-log owner id of one transfer.
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.
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.
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
}
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 ¶
func (r *LocalRunner) Run(ctx context.Context, rec jobstore.XferRecord) error
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").
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 ¶
NewManager builds a Manager from opts. It fails when no journal (Repo) is given: every transfer must be recorded.
func (*Manager) CommitGet ¶
CommitGet records the payload a worker uploaded for a get (its size + sha256), making it visible for the client to download.
func (*Manager) CommitPut ¶
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 ¶
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 ¶
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 ¶
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 ¶
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) Limits ¶
Limits returns the effective caps (the HTTP layer answers 413 from MaxBytes).
func (*Manager) List ¶
func (m *Manager) List(f jobstore.XferFilter) ([]jobstore.XferRecord, error)
List returns transfer rows newest-first.
func (*Manager) MarkDone ¶
MarkDone settles a transfer as done and records its audit event exactly once.
func (*Manager) MarkFailed ¶
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) Release ¶
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 ¶
Remove deletes a transfer: its staging directory first (so a half-deleted transfer can never be downloaded), then its journal row.
func (*Manager) SetRunner ¶
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) (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.
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.
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.
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
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.
type Runner ¶
type Runner interface {
Run(ctx context.Context, rec jobstore.XferRecord) error
}
Runner executes one already-staged transfer on its executing machine. The server-local implementation and the worker-hub adapter both satisfy it; returning nil 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.
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 ¶
NewStore returns a staging store rooted at root (the `xfer` directory itself — the Manager composes it from the configured storage/config root).
func (*Store) Finalize ¶
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) 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 ¶
Remove deletes a transfer's whole staging directory. It is not an error when the directory is already gone.
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".