tus

package
v1.6.1 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: AGPL-3.0 Imports: 16 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 tus is a thin pure-Go tus 1.0.0 client (creation, HEAD, PATCH, termination) for resumable file uploads — the internal/bws thin-stdlib-client template applied to the tus protocol: no new dependencies (the only imports beyond stdlib are the go-sdk `auth` package already in go.mod and the internal auth package, reused for IsLoopbackHost in the plain-http credential gate), sentinel errors matched with errors.Is, byte-stable wrapper messages for goldens, bounded diagnostics (maxDiagBytes body echo, maxEchoChars server strings), and redirects never followed (http.ErrUseLastResponse — no credential re-POST, no https→http downgrade).

Authentication honors the same transport contract as the go-sdk streamable transport: a nil handler sends nothing; otherwise the bearer comes from handler.TokenSource per request, and a 401/403 drives handler.Authorize followed by exactly one retry via the request factory.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrUnauthorized     = errors.New("tus: unauthorized")
	ErrMismatchedOffset = errors.New("tus: mismatched offset")
	ErrNotFound         = errors.New("tus: not found")
	ErrSizeExceeded     = errors.New("tus: size exceeds the server cap")
)

The four sentinels (D5), each with a named consumer: ErrUnauthorized (401: the auth retry boundary and the nil-handler 401 surface), ErrMismatchedOffset (409: the resync classification), ErrNotFound (404: resume/status handling — HeadOffset reports 404 as the exists bool, the sentinel only surfaces for other methods), ErrSizeExceeded (413: the chunk-cap hint). Callers match with errors.Is — never by string-matching the unioned messages, whose text is pinned by goldens and must stay verbatim.

Functions

func NormalizeEndpoint

func NormalizeEndpoint(raw string) (string, error)

NormalizeEndpoint canonicalizes a tus endpoint base URL. It mirrors bws.NormalizeURL (absolute http/https only, no userinfo/query/fragment, a non-empty host — bare or port-bearing, e.g. http://:8080 — the host lowercased, the scheme's own default port stripped, the path kept) with ONE deliberate divergence: instead of trimming trailing slashes it ENSURES a trailing slash on a non-empty path. Tus endpoints are directory-style bases ("/files/"); a slashless "/files" gets ServeMux-301'd by tus servers, which http.ErrUseLastResponse turns into a bare redirect status error instead of a created upload. There is no scheme defaulting and no hostname rewriting.

Types

type Client

type Client struct {

	// Warn is the functional security note channel, not decoration: when an
	// https endpoint's 201 Location redirects the upload to plain http, one
	// line lands here before any PATCH is sent (the credential would travel
	// unencrypted). Zero value nil stays silent — a nil-guarded write.
	Warn io.Writer
	// contains filtered or unexported fields
}

Client is a thin tus 1.0.0 client for one endpoint. It is deliberately single-goroutine per run (the bws Client posture). The handler is the mcpcli auth registry's sdkauth.OAuthHandler — nil (--auth none) means no token injection and no Authorize calls; base carries the basic-mode credential round tripper (interface{ TransportHTTPClient() *http.Client }) and serves only with insecure=false (the CLI rejects that combo, so insecure wins when both would apply).

func NewClient

func NewClient(endpoint string, handler sdkauth.OAuthHandler, base http.RoundTripper, insecure bool) *Client

NewClient builds a Client for one tus endpoint. Like bws.NewClient it normalizes defensively so a raw input still yields working request URLs — a normalization failure keeps the raw form and the request-time URL parse fails loudly. NewClient never fails. When insecure is set, the transport is http.DefaultTransport.(*http.Transport).Clone() with TLSClientConfig.InsecureSkipVerify = true — a Clone preserves the proxy environment and HTTP/2 that a bare &http.Transport{} would silently drop, and proxy + self-signed-MITM is exactly the --insecure demographic.

func (*Client) Create

func (c *Client) Create(ctx context.Context, length int64, metadata map[string]string) (string, error)

Create starts an upload via the tus creation extension: POST to the endpoint with Upload-Length and Upload-Metadata (keys validated before any network call), expecting a 201 whose Location names the upload URL. Location is resolved through resp.Location(), so relative and absolute values both yield absolute URLs; a missing or unparseable one surfaces as an error carrying only a maxEchoChars-bounded echo.

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, url string) error

Delete removes a staged upload via the tus termination extension, expecting a 204. A 404 surfaces as ErrNotFound (the CLI layer decides whether it is data or an error); 410 and everything else ride the generic wrapper.

func (*Client) HeadOffset

func (c *Client) HeadOffset(ctx context.Context, url string) (offset, length int64, exists bool, err error)

HeadOffset asks the server for an upload's progress. A 404 is data, not an error: it returns (0, 0, false, nil) so callers classify on the exists bool and never on sentinel shape (D5). On a 2xx response both Upload-Offset and Upload-Length are required and numeric; violations surface as errors carrying a bounded echo of the offending value.

func (*Client) Patch

func (c *Client) Patch(ctx context.Context, url string, offset int64, body io.Reader, size int64) (int64, error)

Patch sends one chunk at the given offset, expecting a 204 whose Upload-Offset names the new offset. Content-Type is the tus media type and req.ContentLength is set explicitly — a PATCH is never chunked TE. size must equal the body length. The body is buffered once so the authorize-retry path replays the WHOLE chunk from the request factory: a retried PATCH must never carry a consumed reader (the SDK transport buffers the same way); memory stays bounded by the caller's chunk size.

func (*Client) Upload

func (c *Client) Upload(ctx context.Context, f *os.File, size int64, metadata map[string]string, chunkSize int64, resumeURL string, retry int, onProgress func(sent, total int64)) (string, error)

Upload performs the full tus orchestration for one file (D3): Create (or HEAD-resume), then chunked PATCHes with io.NewSectionReader bodies, the offset always advancing from the PATCH RESPONSE's Upload-Offset — never from local accounting. chunkSize <= 0 means defaultChunkSize.

Failure handling:

  • a canceled/expired context aborts immediately, wrapping the context error (%w — errors.Is classifies context.Canceled vs DeadlineExceeded) with ZERO resync HEADs;
  • any other PATCH failure triggers a HEAD resync (a tusd 409 carries no Upload-Offset, so HEAD is the only recovery primitive) and the resynced offset classifies the outcome: == size → success (the server may have landed it); > offset → advance, consume one retry, continue (tusd partial-append semantics — a blind retry from a stale offset would corrupt the upload); == offset → 4xx-class sentinels abort permanently, 5xx/network consumes a retry; resync 404 → abort "no longer in staging", never fake success, never re-Create (duplicate-upload guard).

retry is the caller's retry budget for retry-classified failures (the CLI defaults it to 3; <= 0 means no retries — the resync HEAD still fires, because it classifies, it does not retry).

onProgress fires after each successful PATCH with (sent, total). Errors stay low-context: URL+offset context is added at exactly ONE site — the CLI failure line — except where the diagnosis IS the context (the staged URL in the swept/past-size aborts, both offsets in the stall abort). The staged URL is nonetheless RETURNED alongside every error once known (after Create succeeds; the resume target is the caller's input), so the CLI failure line can name the wire target without a second channel.

Jump to

Keyboard shortcuts

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