remote

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 35 Imported by: 0

Documentation

Overview

Package remote decides how a remote repository read is served: from cache, by revalidation, by an upstream fetch or from a negative entry. It holds the shared retrieval and cache policy, upstream discovery and folder listings, and the vocabulary that the upstream transport, Smart Remote and the format slices' upstream rules share with it.

Role

artifacts module, core layer: the remote retrieval decision, with no HTTP client code. The transport (artifacts/adapters/upstream) implements the Upstream and Registries ports declared here; Smart Remote (artifacts/core/remote/smart) reaches the policy through Interceptor and the WithSmart mark; the format slices plug their upstream rules into the policy's hooks. None of them is imported back (decision 0044).

Inputs

  • Driving: the source service (artifacts/core/remote/source), which reads a remote repository through Policy.Read once it has authorised the request; the listing and discovery callers; Smart Remote; and the format slices' upstream rules, which call the policy's exported checks.
  • Driven: the Upstream and Registries ports, for every upstream exchange; source.Request and source.Permit, the authorised request and its source identity; the store, through Store (transactions, the remote cache, repositories, items, the work queue and leases), which Policy.Store holds, CheckCurrent is handed and Smart's and the Maven slice's companion queues are built on, while a Discovery keeps only the remote cache's reader; the item service and its format registry, which publish what a fetch admits; and the policy hooks the application installs (Fetch, GitFetch, PrepareUpload, ProjectResponse, Options, CheckCurrent and Smart).

Outputs

  • Store, the store Policy.Store holds. It names no access store.
  • Policy, its Read and the exported checks the slices and Smart call (Check, CacheKey, FlightKey, ReadEntry, Acquire, State, Cooldown, RecordFailure, RecordResponse), with PolicyError, ResponseError, TransportRequest, MetadataContext, MustNotStore and EagerKey.
  • Discovery, NewDiscovery and DiscoveryScope; the folder listings (FolderListing, MappedFolderListing, ListFolder, ListMappedFolder, ListingEntry, ListingBudget); SmartPeer and ParseSmartPeer.
  • The ports and hooks: Upstream, Connection, Options and Request; Registries, RegistryClient and ErrRegistryDenied; Outbound, WithOutbound and OutboundFrom; Interceptor, WithSmart and SmartActive.
  • The shared vocabulary: the remote: sentinels (ErrURL, ErrRequest, ErrRedirect, ErrConfiguration, ErrClosed, ErrConnection, ErrSecurity and ErrBusy), BaseURL, CheckedURL, Origin, Port, RetryAfter, Admission and FlightGroup.

Invariants

  • Callers authorise the repository and path before consulting either cache or upstream; the policy only rechecks that authority (CheckCurrent) before it publishes.
  • Core imports neither the transport (artifacts/adapters/upstream) nor Smart Remote; both import it.
  • Cache aliases and explicit offline mode make no upstream call, and nor does a read while the upstream is assumed offline, which serves the copy the cache holds, however old, or misses with source.ErrAssumedOffline (https://github.com/weaveplatform/artifactweave/issues/1601).
  • Only a caller with Deploy/Cache on the cache path fills the cache (source.AuthorizeFill); one with Read alone is answered from the upstream's info, and nothing the upstream sends it is kept (https://github.com/weaveplatform/artifactweave/issues/1587).
  • A HEAD on a resource the cache keeps fills it as a GET does, in the GET's flight, and is answered from the kept copy; only a read that keeps nothing and a checksum request's HEAD send the upstream a HEAD, and nothing is published from an upstream HEAD alone (https://github.com/weaveplatform/artifactweave/issues/1391).
  • The sentinel texts, cache key terms and remote. log names stay byte-identical.
  • A failure of the server's own storage while the cache keeps a file (item.StorageFault: a failed open or read of the copy under check, the 304 re-admission's read of cached metadata included, or a failed write of the copy or store call that publishes it) is no upstream failure: PolicyError passes it on where the error it brought about would answer a 502 that serves no stale copy and that the assumed-offline circuit does not count, and otherwise maps that error as before (https://github.com/weaveplatform/artifactweave/issues/1269).

References

Status

Implemented P9. Moved here in P9d, which narrowed Policy.Store to Store (https://github.com/weaveplatform/artifactweave/issues/1091).

Testing

  • Most tests are an external test package (remote_test) over a fake upstream (fakeupstream) and a pool from upstreamtest: policy_test.go holds the policy fixture, with policy_fault_test.go, policy_format_test.go, cache_maintenance_test.go, metadata_response_test.go, module_location_test.go, cold_head_test.go, a HEAD that fills the cache, fill_test.go, a caller who may not fill the cache and an upstream assumed offline, storage_fault_test.go, a failed read, write or publication of the cache's own copy, a Hex tarball's Deployed hook among them, state_fault_test.go, a failed read or write of the availability state the circuit keeps; and discovery_test.go, discovery_contract_test.go, listing_test.go and listing_smart_test.go cover discovery and listings. helpers_test.go holds their small helpers, and export_test.go opens the policy's unexported parts to them.
  • flight_test.go, rules_test.go, rules_nostore_test.go, listing_parse_test.go, protocol_test.go and smart_peer_test.go are in-package unit tests of the flight group and the admission, the cache rules and the upstream no-store the cache keeps, the listing parsers, the protocol paths and the Smart peer parser.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrURL is returned when a configured repository URL fails BaseURL, or
	// when a request path or query cannot be placed below it: a leading
	// slash, a dot segment, or an escaped or control character that would
	// change what the URL addresses.
	ErrURL = errors.New("remote: invalid url or path")
	// ErrRequest is returned when the transport or a format rule refuses a
	// request it will not send, such as a method, body, header or target
	// the exchange does not allow. When a sent exchange fails, the transport
	// returns it wrapping the cause: ErrRedirect, ErrSecurity, ErrConnection
	// or the context's error.
	ErrRequest = errors.New("remote: request failed")
	// ErrRedirect is returned when a redirect is refused: one the redirect
	// rules forbid (more than ten hops, user information, a scheme other
	// than http or https, or https to http), a redirect of a POST, or any
	// redirect on a connection that follows none, such as Send's.
	ErrRedirect = errors.New("remote: redirect refused")
	// ErrConfiguration is returned when a remote's transport settings cannot
	// be applied: an unusable proxy, local address, certificate or stored
	// credential, or a registry client for an identity that is not a
	// complete external HTTP source.
	ErrConfiguration = errors.New("remote: invalid transport configuration")
	// ErrClosed is returned by the transport's and the registry clients'
	// pools after Close, at application shutdown.
	ErrClosed = errors.New("remote: transport pool closed")
	// ErrConnection is returned when the upstream cannot be reached: its
	// name resolves to no address, the proxy tunnel fails, or the connection
	// fails or ends early.
	ErrConnection = errors.New("remote: connection unavailable")
	// ErrSecurity is returned when a target fails the destination or TLS
	// checks: CheckedURL refuses it, it resolves to a cloud metadata address
	// or to a private one the operator did not allow, an Outbound hook
	// refuses it, an unguarded connection is asked to vouch for it, its
	// certificate does not verify, or the proxy refuses its credentials.
	ErrSecurity = errors.New("remote: transport security validation failed")
)

The transport's error vocabulary is declared in core so that the policy, Smart Remote and the format rules can match an upstream failure with errors.Is without importing the transport (decision 0044).

View Source
var ErrBusy = errors.New("remote: remote retrieval capacity exhausted")

ErrBusy reports that upstream capacity is exhausted: Admission.Acquire, and so Policy.Acquire, returns it when a repository already has its maximum of callers queued, and Smart Remote when its work queue is full. PolicyError answers it with a 503.

View Source
var ErrRegistryDenied = errors.New("remote: upstream registry authentication denied")

ErrRegistryDenied is what a registry client returns when the upstream registry still refuses a request after the one authentication retry Do allows, or answers it with a challenge the client may not follow: one from another origin, or Basic after the configured credentials were sent. The Docker remote rules answer it as an upstream 401.

Functions

func BaseURL

func BaseURL(raw string) (*url.URL, error)

BaseURL parses a remote repository's configured URL: absolute http or https with a host, and no user information, fragment or opaque part. Anything else answers ErrURL. Unlike CheckedURL it does not judge the host, port or path; the transport does that when it connects.

func CheckedMatrix

func CheckedMatrix(matrix string) error

CheckedMatrix refuses with ErrSecurity a matrix string, as it follows an upstream path, that is not ";"-led and escaped throughout (RFC 3986 segment bytes and %XX escapes, nothing else), or whose decoded form holds a piece between "/", "\" or NUL that reads as a dot segment: "." or "..", alone or before a ";", "?" or "#".

7.x sends a remote request's matrix parameters as HttpRepo.encodeIfNeeded leaves them (7.161.26): ArtifactoryRequestBase.processMatrixParams URL-decodes each key and value, RemoteRepoBase.buildRequestMatrixParams appends them as they are, and HttpUtils.encodeUrl escapes the path with URIUtil.encodeQuery, whose allowed_query set is RFC 2396's uric without "%". A backslash, NUL, CR and LF fall outside it and travel as %5C, %00, %0D and %0A, which this check accepts where CheckedURL refuses them in the rest of the path. As escapes they are printable octets of the request line, and HTTP/1.1 frames a message on raw CR LF before any decoding, so they split neither our request nor its headers. An upstream that decodes the path and copies it into a request or header of its own carries the line break on; that is the upstream's fault, and 7.x sends it the same bytes.

encodeQuery keeps "/" and ".", so 7.x sends a value "a/../b" as it is and the upstream resolves another file than the one asked for: a 7.x fault, not followed. Escaped as %2F the value would stay in one segment only for an upstream that resolves dot segments before it decodes; one that decodes first, as nginx does, would step out of the path. So a string whose decoded form holds a dot piece is refused, and TransportRequest leaves it off. Pieces are cut at "\" too, which some upstreams read as a separator, and at NUL, which a C upstream reads as the end of the path or drops, so that neither escape can be decoded into a step. A piece is read up to its first ";", "?" or "#" as well: an upstream that decodes first and then strips each segment's path parameters, or splits off the query or fragment, would read "..;k=v" or "..?q" as a dot segment. 7.x sends such a value with its "/" and ";" as they are, the same fault.

func CheckedRequestURL

func CheckedRequestURL(raw, matrix string) (*url.URL, error)

CheckedRequestURL is CheckedURL for a request whose escaped path ends with matrix, the matrix string TransportRequest appended after the path (Request.Matrix). The URL without matrix, which holds the repository URL and the item path, must pass CheckedURL as any URL must, and matrix must pass CheckedMatrix. With an empty matrix, or a URL whose escaped path does not end with it, such as a redirect elsewhere, the whole URL is checked by CheckedURL.

func CheckedURL

func CheckedURL(raw string) (*url.URL, error)

CheckedURL parses raw as an absolute http or https URL with a host and no user information, fragment or opaque part, and refuses with ErrSecurity one that could address something other than what it shows: an escaped or control character in the host, a port outside 1 to 65535, a backslash, NUL or line break in the decoded path, a dot segment, or a '#' or line break in the query. It looks nothing up; the destination policy checks the addresses before a request is sent. The only path it does not judge this way is the matrix string a request appends, which CheckedRequestURL checks by its own rule.

func MetadataContext

func MetadataContext(ctx context.Context, q source.Request) (context.Context, context.CancelFunc)

MetadataContext bounds a metadata exchange by the repository's metadata retrieval timeout, 60 seconds when unset; an artifact request, or a timeout of zero or less, keeps ctx as it is. The caller calls the cancel function in every case.

func MustNotStore

func MustNotStore(h http.Header) bool

MustNotStore reports whether a response with header h may not be kept: its Cache-Control says no-store, or its Vary names anything but Accept and Accept-Encoding, so it could differ by request state that the cache identity leaves out. The remote cache does not use it for what it stores (mustNotPersist); the smart remote's discovery documents still do.

func Origin

func Origin(u *url.URL) string

Origin is u's scheme and host in lower case, without a trailing dot, with the port the scheme implies when u names none: two URLs with the same Origin reach the same server, which credential, redirect and pagination checks compare.

func PolicyError

func PolicyError(err error) error

PolicyError classifies a failure of the policy's own work for the source service: an error that already carries a *source.HTTPError keeps it; the sentinels a caller tests (source.ErrDenied, source.ErrSuperseded, kernel.ErrNotFound and context.Canceled) pass through, a store conflict reading as superseded; a timeout becomes a 504, a busy pool a 503, a security, connection or integrity failure a 502 of that kind, and anything else a 502 protocol failure. Format rules in the ecosystem slices return it unwrapped, as the policy does, so that the source service maps their failures as it maps the policy's own.

A failure of the server's own storage while it keeps a remote file (*item.StorageFault: a failed read of the copy under check, a failed write of the copy, a failed call of the store that publishes it) passes through as it is, a server fault, where the error it brought about maps on its own to a 502 that serves no stale copy and that the assumed-offline circuit does not count (storageFault). Elsewhere, as for a read or write that timed out or ended short, that error maps as before, so the stale copy and the circuit are as they were.

func Port

func Port(u *url.URL) string

Port is u's port, or the one its scheme implies when it names none: 443 for https and 80 otherwise, so that Origin, CheckedURL and the transport's dialer compare and connect to the same port.

func ResponseError

func ResponseError(res *http.Response, now time.Time) error

ResponseError is the error of an upstream answer that is neither content nor a protocol-declared absence: a *source.HTTPError carrying 401, 403, 429 (with the Retry-After it gives, read against now) or a 5xx status as an HTTP failure, and any other status as a 502 protocol failure. Format rules that make their own upstream exchanges return it unwrapped, so the source service maps the failure as it does for the policy's own reads.

func RetryAfter

func RetryAfter(raw string, now time.Time) time.Duration

RetryAfter reads a Retry-After header value, in seconds or as an HTTP date measured from now, and bounds the pause to between 1 and 300 seconds; an empty or unreadable value means 1 second. The circuit, the policy's 429 answers and the registry token exchange share it, so every upstream pause is bounded alike.

func SmartActive

func SmartActive(ctx context.Context) bool

SmartActive reports whether ctx was marked active by WithSmart; an inactive mark and no mark both answer false.

func WithOutbound

func WithOutbound(ctx context.Context, o Outbound) context.Context

WithOutbound returns a copy of ctx whose upstream requests apply o. It replaces any hooks ctx carries rather than combining with them.

func WithSmart

func WithSmart(ctx context.Context, active bool) context.Context

WithSmart marks ctx as inside Smart Remote; active enables Smart headers. Policy.Read tests whether the mark is present, not whether it is active: Smart's Read marks its context inactive on entry, before it knows whether Smart applies, and calls Policy.Read under that mark for the reads it leaves to the policy. A test of activity would hand those reads back to the interceptor, which would enter itself again without end.

Types

type Admission

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

Admission bounds active work and queued callers without creating a goroutine for each blocked request. A single notification wakes contenders to recheck under the mutex; no repository reserves a global slot while it is full. Its zero value is ready to use, with at most 8 active callers per key, 64 in all and 256 queued per key; it must not be copied after first use.

func (*Admission) Acquire

func (a *Admission) Acquire(ctx context.Context, repoKey string) (func(), error)

Acquire waits for a slot for repoKey and returns its release, which is safe to call more than once. It answers ErrBusy at once when repoKey's queue is full, and the context's error, wrapped, when ctx ends first.

type Connection

type Connection interface {
	// Fetch reads r, probing with HEAD first unless the repository bypasses
	// HEAD requests or r must be sent once as it is. A probe answered with 304
	// or a definitive error status is the result; otherwise the GET is, and
	// nothing of the probe's response is reused.
	Fetch(ctx context.Context, r Request) (*http.Response, error)
	// Do sends r once as it is. Both Fetch and Do keep the transport's
	// destination, redirect and credential rules and apply the hooks that
	// WithOutbound installed in ctx.
	Do(ctx context.Context, r Request) (*http.Response, error)
	// Guarded reports whether the connection checks absolute destinations
	// that metadata names (Options.CheckURL). An unguarded connection sends
	// no ExternalURL request.
	Guarded() bool
	// CheckURL applies that destination check to u, and returns ErrSecurity
	// when the connection is unguarded.
	CheckURL(ctx context.Context, u *url.URL) error
	// Prepare applies the connection's request preparation (Options.Prepare),
	// which adds the configured credentials, to a request its caller built;
	// without one it leaves req as it is and returns nil.
	Prepare(req *http.Request) error
	// Send sends a request its caller built, checked and prepared, over the
	// connection's transport, and refuses every redirect with ErrRedirect.
	// None of Do's checks or hooks apply, and the error is the HTTP client's
	// own, not one of this package's classifications.
	Send(req *http.Request) (*http.Response, error)
}

Connection sends requests to one remote origin. Every successful Fetch, Do or Send transfers response-body ownership to the caller, including non-2xx responses. It is safe for concurrent use.

type Discovery

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

Discovery retains an atomic layout/source snapshot. Upstream paths are traversal inputs only; consumers receive canonical paths after lossless translation and current authorization.

func NewDiscovery

func NewDiscovery(ctx context.Context, items *item.Service, c repo.Config) (*Discovery, error)

NewDiscovery prepares upstream discovery for remote repository c. In one transaction it pins the repository's source identity and loads the canonical layout and the upstream one (RemoteRepoLayoutRef, or RepoLayoutRef when that is empty). Its errors match source.ErrInvalidRequest when items has no store, c is not a remote or a layout cannot be read, and source.ErrSuperseded when the stored repository is gone or its remote policy changed since c was read; a failed read of the source identity is wrapped.

func (*Discovery) Canonical

func (d *Discovery) Canonical() *layout.Layout

Canonical returns the repository's own layout, in which discovery reports paths and checks authority.

func (*Discovery) MapFile

func (d *Discovery) MapFile(upstream string) (string, bool, error)

MapFile refuses lossy or ambiguous coordinates instead of keeping the raw upstream path. Non-artifact metadata/auxiliary names are not file results.

func (*Discovery) MetadataResource

func (d *Discovery) MetadataResource(
	scope DiscoveryScope,
	upstream, variant string,
) (source.Resource, error)

MetadataResource separates the private cache/authority location from the upstream document. Callers must supply complete body validation before Read.

func (*Discovery) Read

func (d *Discovery) Read(
	ctx context.Context,
	service *source.Service,
	q source.Request,
) (source.Result, error)

Read pins the identity before Service acquires the source. A layout edit between preparing the mapping and Service.Resolve cannot adopt a new source generation with old mapping rules, even before the first network request.

func (*Discovery) Revalidate

func (d *Discovery) Revalidate(ctx context.Context) error

Revalidate reports whether the source identity NewDiscovery pinned is still the repository's, so a caller discloses nothing discovered under a replaced source. It answers source.ErrSuperseded when the identity changed or cannot be read.

func (*Discovery) Scopes

func (d *Discovery) Scopes(values layout.Values) []DiscoveryScope

Scopes derives authority from complete canonical directory components. A constraint present only in a filename cannot borrow a sibling file's grant.

func (*Discovery) Upstream

func (d *Discovery) Upstream() *layout.Layout

Upstream returns the layout of the remote origin, which discovery traverses; it is the canonical layout when the repository names no remote layout.

func (*Discovery) VersionScope

func (d *Discovery) VersionScope(group, module, version string) (DiscoveryScope, bool)

VersionScope proves a version-specific artifact directory without guessing an extension, classifier or POM. Filename-only versions need actual files.

type DiscoveryScope

type DiscoveryScope struct {
	Path string
	Root bool
}

DiscoveryScope is a canonical query folder. Root requires actual root Read when the layout cannot encode the query's coordinates in a directory; a grant on an unrelated descendant cannot initiate that scan.

func (DiscoveryScope) Allows

func (s DiscoveryScope) Allows(q source.Request) bool

Allows reports whether q's caller may scan the scope: it must be well formed, the repository's include and exclude patterns must admit its folder, and the caller must hold Read on it. A folder scope counts a grant on a path below it; a Root scope needs Read on the repository root itself. A request without an access decision is refused.

type EagerKey

type EagerKey struct{}

EagerKey marks the context of a Maven companion job; its value is the credential revision the job was queued under. A policy read or Check in that context answers source.ErrSuperseded when the revision it would use differs, so a job never fetches with credentials other than those of the read that queued it. The Maven slice sets it when a job runs, and reads it so that a companion's own read queues no further companion.

type FlightGroup

type FlightGroup[T any] struct {
	// contains filtered or unexported fields
}

FlightGroup lets concurrent callers with one key share one run of an operation; its zero value is ready to use, and it must not be copied after first use. The shared operation gets its own context. A departing waiter cannot cancel its peers; the last departure cancels otherwise abandoned I/O. Only persisted results may be shared: an owned stream is never multicast.

func (*FlightGroup[T]) Do

func (g *FlightGroup[T]) Do(
	ctx context.Context,
	key string,
	work func(context.Context) (T, error),
) (T, error)

Do runs work for key, or joins the run already in flight for it, and returns that run's result to every caller still waiting. work runs on a context that keeps the values of the caller who started the run but none of its cancellation, and that ends when the last waiter leaves. A caller whose ctx ends first leaves at once with the context's error, wrapped, and the run goes on for the others.

func (*FlightGroup[T]) Pending

func (g *FlightGroup[T]) Pending() int

Pending reports how many callers wait on the group's active flights. Tests poll it to know every caller has joined before the shared work ends.

type FolderListing

type FolderListing struct {
	Entries []ListingEntry
	// contains filtered or unexported fields
}

FolderListing retains current authority for every page and visible child. Call Revalidate immediately before disclosing the result, including HEAD.

func ListFolder

func ListFolder(ctx context.Context, service *source.Service, q source.Request,
	folder string, budget *ListingBudget,
) (FolderListing, error)

ListFolder performs an explicit, nonrecursive source lookup. The entry point owns the documented listRemoteFolderItems policy; this source primitive does not infer an entry point from a caller-controlled parameter. CacheOnly is carried unchanged to every page.

func (FolderListing) Revalidate

func (l FolderListing) Revalidate(ctx context.Context) error

Revalidate reruns, in order, the checks the listing gathered: each page's source revalidation and each listed child's current read authority. It returns the first failure as the check reported it, so a caller discloses nothing once a source changed or a grant was revoked.

type Interceptor

type Interceptor interface {
	Read(ctx context.Context, q source.Request, permit source.Permit) (source.Result, error)
}

Interceptor reads a remote resource in place of the shared policy. Once installed as Policy.Smart, it receives every Policy.Read whose context carries no WithSmart mark, and answers with the source service's errors as the policy does. Smart Remote (artifacts/core/remote/smart) is the one implementation, and core never imports it (decision 0044): this interface and the context mark are all the policy knows of Smart.

type ListingBudget

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

ListingBudget bounds an entire browsing/search operation, including multiple folders. A zero value is ready to use; the caller must not share it concurrently.

type ListingEntry

type ListingEntry struct {
	Path   string
	Folder bool
}

ListingEntry describes an upstream child, not a cached item. Listing never creates an item row or fetches the child's payload.

type MappedFolderListing

type MappedFolderListing struct {
	Files     []ListingEntry
	Folders   []string `json:"-"`
	Documents []string `json:"-"`
	// contains filtered or unexported fields
}

MappedFolderListing exposes only authorized canonical files. Folders are private upstream traversal cursors, never public paths or permission grants. Documents contains non-artifact control-document cursors. Consumers must validate their identities and read them under a derived canonical scope.

func ListMappedFolder

func ListMappedFolder(ctx context.Context, service *source.Service, q source.Request,
	discovery *Discovery, scope DiscoveryScope, upstreamFolder string, budget *ListingBudget,
) (MappedFolderListing, error)

ListMappedFolder uses one fixed canonical query scope for each bounded upstream page. It must never authorize an upstream lexical path, including subdirectories that the caller later traverses under that same query scope.

func (MappedFolderListing) Revalidate

func (l MappedFolderListing) Revalidate(ctx context.Context) error

Revalidate reruns, in order, the checks the listing gathered: each page's source revalidation and each listed file's current read authority at its canonical path; Folders and Documents carry none. It returns the first failure as the check reported it.

type Options

type Options struct {
	ProxyURL  *url.URL
	TLSConfig *tls.Config
	Revision  string
	Jar       http.CookieJar
	// CheckURL authorizes metadata-provided absolute destinations.
	CheckURL      func(context.Context, *url.URL) error
	WrapTransport func(*http.Transport) (http.RoundTripper, func())
	Prepare       func(*http.Request) error
	CheckRedirect func(*http.Request, []*http.Request) error
	// MaxResponseHeaderBytes defaults to 1 MiB; tests can lower it.
	MaxResponseHeaderBytes int64
}

Options contains resolved connection settings. Revision must change whenever externally resolved settings (proxy, trust, credentials) change. Prepare runs for initial requests and redirects, after the transport removes credentials from requests crossing origins. It must not forward downstream credentials.

type Outbound

type Outbound struct {
	// Header edits each request before sending and each same-origin redirect.
	Header func(*http.Request)
	// Allow reports whether target may be requested; nil allows every target.
	Allow func(target string) bool
}

Outbound holds request-scoped hooks that every upstream connection applies. Smart Remote installs them to mark its requests and narrow their targets, so the transport knows nothing of Smart sessions. They only add to the transport's rules: Do applies Header after the credential preparation and then asks Allow; on a redirect it asks Allow after the request's own CheckURL and before the redirect policy, and once that policy passes it, applies Header only when the redirect stays on the first request's origin, since a change of origin keeps only the transport's own headers (decision 0007). A refused target fails with ErrSecurity and is never sent. Hooks travel with one request's context, so requests sharing a pooled connection never see each other's.

func OutboundFrom

func OutboundFrom(ctx context.Context) Outbound

OutboundFrom returns the hooks installed by WithOutbound, or the zero value.

type Policy

type Policy struct {
	// Smart reads, in place of the policy, every request whose context
	// carries no WithSmart mark; NewSmart in artifacts/core/remote/smart
	// installs itself here. Nil leaves every read to the policy.
	Smart Interceptor
	// Fetch overrides only the protocol exchange. Authentication adapters retain
	// the source identity and credential revision used by this cache operation.
	Fetch func(context.Context, source.Request, source.Permit, Options, Request) (*http.Response, error)
	// GitFetch answers a request for a CocoaPods Git checkout (q.Resource.CocoaPodsGit
	// set). The application installs cocoapods.FetchCocoaPodsGit; nil answers
	// source.ErrUnsupported, as a policy without a pool does.
	GitFetch func(ctx context.Context, p *Policy, q source.Request, permit source.Permit, opts Options) (*http.Response, error)
	// PrepareUpload performs bounded adapter work outside SQL, after the main
	// response succeeds and before validation/publication. It uses the same
	// transport security and cannot replace the final CheckCurrent fence.
	PrepareUpload func(context.Context, source.Request, source.Permit, Options, *item.CacheUpload) error
	// ProjectResponse may rewrite an upstream response before admission, for a
	// format whose protocol gives a status a meaning of its own (NuGet v2 reads a
	// bodyless 204 as an empty feed). It runs after the module-location projection
	// and before missing-status normalisation; nil leaves every response as sent.
	// The application installs nuget.ProjectEmptyFeed. A hook that replaces
	// res.Body closes the body it replaces; the policy closes whichever body res
	// holds when the fetch ends. An error it returns ends the fetch as it is, with
	// no fallback to a cached copy, so it is one of the source service's errors.
	ProjectResponse func(q source.Request, res *http.Response) error
	Store           Store
	Blobs           blob.Store
	Items           *item.Service
	// Pool opens the upstream connections. Left nil, with Fetch nil too, every
	// read that needs the network answers source.ErrUnavailable. Assign a
	// *Pool only when it is not nil: a nil *Pool is a non-nil Upstream, which
	// passes that check and the format rules' own.
	Pool         Upstream
	Options      func(context.Context, repo.Config) (Options, error)
	CheckCurrent func(context.Context, Store, source.Request, source.Permit, string) error
	// Key is a stable keyring-derived HMAC key, never a logged cache identifier.
	Key           []byte
	Now           func() time.Time
	MetadataLimit int64
	// contains filtered or unexported fields
}

Policy implements the shared remote retrieval table. Authorization belongs to source.Service; CheckCurrent repeats it inside the short publication transaction and verifies the effective credential revision without network access.

func (*Policy) Acquire

func (p *Policy) Acquire(ctx context.Context, repoKey string) (func(), error)

Acquire waits for a slot of the policy's upstream capacity for repoKey, which Smart Remote's own peer requests share with the policy's fills: at most 8 active exchanges per repository and 64 in all, with up to 256 callers queued per repository. It returns the release, which is safe to call more than once, or ErrBusy when the repository's queue is full, or the context's error, wrapped, when ctx ends first.

func (*Policy) AssumedOffline

func (p *Policy) AssumedOffline(ctx context.Context, q source.Request) bool

AssumedOffline reports whether the upstream of q's repository is assumed offline now, under the repository's current credential revision. A read of the options or of the state that fails reports false, leaving the read that follows to meet the same failure.

func (*Policy) CacheKey

func (p *Policy) CacheKey(q source.Request, revision string) model.RemoteCacheKey

CacheKey is the remote cache key of q under the credential revision: the repository key and resource path, revision as SettingsRevision, and as Variant a keyed HMAC-SHA256 (Key) of every term that changes the representation. The terms are the resource's kind, mutability, escaped path, variant and Accept (the adapter's own, never the client's, so a file is cached once whatever clients accept, #1390), its query when the repository propagates query parameters, its upstream path, external URL (not for a Git LFS object, which its SHA-256 names), checksums and expected content type when any is set, and each opt-in rule set on it, the NuGet empty feed ("nuget-empty-feed-v1") and the accepted media types among them. The keyed fingerprint keeps sensitive query values out of an observable key. Cached entries are stored under the key, so each term's encoding must stay as it is, and a new opt-in term is added only when its option is set, which leaves every existing key unchanged. It reads neither the store nor the network.

func (*Policy) Check

func (p *Policy) Check(
	ctx context.Context,
	q source.Request,
	permit source.Permit,
	revision string,
) error

Check is the authority fence of a read under revision, the credential revision the read's options carried. Inside a Maven companion job (EagerKey) it answers source.ErrSuperseded when revision is not the one the job was queued under. CheckCurrent then decides when it is set (the application's repeats the read's authorisation and compares the repository's current credential revision); otherwise Check answers source.ErrSuperseded unless the repository's source identity is still permit's, or the error of reading it. It reads the store, never the network, so it can run inside a publication transaction; format rules call it after their own upstream exchanges, before anything they fetched is used.

func (*Policy) Cooldown

func (p *Policy) Cooldown(state model.RemoteSourceState) error

Cooldown refuses an upstream exchange while state holds one off, by the policy's clock: a 429 *source.HTTPError carrying the rest of a Retry-After pause, or a 502 connectivity failure while the upstream is assumed offline. It returns nil when the exchange may go ahead. The policy's reads of a file answer an assumed-offline upstream before they ask it (offline); the 502 is what a folder listing, a search's metadata read, a POST query and Smart Remote's own exchanges, its discovery and its property and statistics requests, are refused with.

func (*Policy) FlightKey

func (p *Policy) FlightKey(key model.RemoteCacheKey, identity model.SourceIdentity) string

FlightKey returns the key under which concurrent fills of key for one source identity share a single upstream exchange: the hex SHA-256 of both, so that callers with different credentials never share a response. Smart Remote keys its discovery flights the same way.

func (*Policy) Read

func (p *Policy) Read(
	ctx context.Context,
	q source.Request,
	permit source.Permit,
) (out source.Result, retErr error)

Read is the source.Backend that the source service's HTTP kind calls once it has authorised q. It serves a fresh cached entry, otherwise revalidates or fetches from the upstream (one shared fill per cache key and source identity, within Acquire's capacity), and falls back to a stale entry on the failures decision 0007 allows. A cache-only intent, a permit without upstream network access, an offline repository and a derived resource read the cache alone. A HEAD fills the cache as a GET does and is answered from the copy kept; a read that keeps nothing (storeArtifactsLocally false, a checksum-only or transient resource) and a checksum request's HEAD have an upstream exchange of their own, a HEAD for a HEAD. A caller who may not fill the cache (source.AuthorizeFill) is answered from the upstream's info alone (withoutFill), and while the upstream is assumed offline a read asks it nothing (offline). With an Interceptor installed, a read that WithSmart has not marked goes to it first. Errors: source.ErrUnavailable when the hooks a fetch needs are not installed, a *source.CacheFillDenied for a file such a caller would fill, source.ErrAssumedOffline for a miss while the upstream is assumed offline, kernel.ErrNotFound for a fresh negative entry, source.ErrSuperseded when the credential revision moved on, and PolicyError's mapping of upstream and capacity failures. A successful result's Revalidate repeats Check before disclosure.

func (*Policy) ReadEntry

func (p *Policy) ReadEntry(
	ctx context.Context,
	key model.RemoteCacheKey,
	permit source.Permit,
) (model.RemoteCacheEntry, error)

ReadEntry returns the remote cache entry stored under key for the permit's source identity: an entry recorded under another identity answers kernel.ErrNotFound, as a missing one does, so a source that changed never reads its predecessor's state. A store error comes back wrapped.

func (*Policy) RecordFailure

func (p *Policy) RecordFailure(
	ctx context.Context,
	q source.Request,
	permit source.Permit,
	revision string,
	err error,
) error

RecordFailure counts err against the repository's circuit when it is a connectivity or timeout *source.HTTPError, and ignores any other error. The tenth failure in a row marks the upstream offline for the assumed-offline period, 300 seconds when unset, and each failure after that starts the period again; a period of zero or less clears the count instead. The write is its own short transaction, bounded even when ctx has ended, and its error is classified by PolicyError: source.ErrSuperseded when the permit's source identity is no longer current.

func (*Policy) RecordResponse

func (p *Policy) RecordResponse(
	ctx context.Context,
	q source.Request,
	permit source.Permit,
	revision string,
	res *http.Response,
) error

RecordResponse records that the upstream answered: any status clears the connection failures and cooldowns, and a 429 starts a Retry-After pause (from 1 to 300 seconds) that Cooldown then enforces. It writes as RecordFailure does, with the same errors.

func (*Policy) State

func (p *Policy) State(
	ctx context.Context,
	q source.Request,
	revision string,
) (model.RemoteSourceState, error)

State returns the repository's upstream availability state as the circuit judges it under the credential revision, without writing it back: a state recorded under another revision loses its Smart negotiation, connection failures and cooldowns, and a repository whose assumed-offline period is zero or less is never offline. A store error comes back wrapped.

type Registries

type Registries interface {
	// Open returns the pooled client, or source.ErrSuperseded when the resolved
	// credential revision differs from revision. On any error the client is
	// a nil interface.
	Open(
		ctx context.Context,
		c repo.Config,
		id model.SourceIdentity,
		revision string,
	) (RegistryClient, error)
	// Foreign sends r once through an unpooled client built from opts, for
	// a foreign layer, which a manifest names outside the registry.
	Foreign(ctx context.Context, c repo.Config, opts Options, r Request) (*http.Response, error)
}

Registries opens registry clients for the Docker remote rules, so that the rules hold neither the client pool nor the credential resolver, which live as long as the application. RegistryClients implements it.

type RegistryClient

type RegistryClient interface {
	// Image returns the name the upstream knows the image name by, with the
	// repository's project prefix and Docker Hub's library namespace, or
	// ErrRequest for a name outside the Distribution grammar or over 255
	// characters.
	Image(name string) (string, error)
	// Do sends r for image; r.Path is relative to the image, such as
	// "manifests/latest". The caller owns the response body.
	// ErrRegistryDenied reports a request the registry refused.
	Do(ctx context.Context, image string, r Request) (*http.Response, error)
	// Base returns a copy of the registry's base URL, under which a
	// listing's next-page link must stay.
	Base() *url.URL
}

RegistryClient sends Distribution requests to one upstream registry for one resolved repository revision, and authenticates them itself (decision 0007, docs/implementation/remote-registry-authentication.md). *Registry implements it.

type Request

type Request struct {
	// GitUploadPack is set only by the closed CocoaPods Git-object adapter
	// (cocoapods.FetchCocoaPodsGit), to mark its upload-pack POST. It is
	// exported only so that the adapter, outside this package, can mark the
	// request: Do still admits the POST only when the whole Git guard holds
	// (a CocoaPods repository, a metadata request without cross-origin
	// credentials, an external URL with no path or query, a body of 1 to
	// 4096 bytes, the upload-pack Accept header and a destination check).
	GitUploadPack bool
	// ExternalURL is a metadata/token-realm URL, never combined with Path/Query.
	// It requires a resolved destination policy.
	ExternalURL string
	// CheckURL is a request-scoped restriction, never retained by the pooled client.
	// It applies before the initial request and each redirected request is sent.
	CheckURL          func(context.Context, *url.URL) error
	NoCrossOriginAuth bool
	// GitLFSActionHeaders belong only to the exact, validated download action.
	// They are never copied to a redirected request.
	GitLFSActionHeaders http.Header
	Method              string
	Path                string
	// Matrix is the matrix string TransportRequest appended to Path, which
	// still ends with it. The transport checks Path without it as it checks
	// any path, and it by CheckedMatrix, so that the escapes 7.x sends in a
	// matrix value pass while the same bytes in the item path are refused.
	// A Path that no longer ends with Matrix is checked whole.
	Matrix   string
	Query    string
	Header   http.Header
	Metadata bool
	// Body is admitted only for closed format-owned metadata POST contracts.
	Body []byte
}

Request is one upstream exchange for Connection.Do and Connection.Fetch. Path and Query resolve against the repository URL; ExternalURL instead names an absolute destination, which only a guarded connection sends (ErrSecurity otherwise). Only GET and HEAD without a body are sent, apart from the closed format-owned POSTs marked below; anything else is ErrRequest. Metadata bounds the whole exchange, body included, by the repository's metadata retrieval timeout.

func TransportRequest

func TransportRequest(q source.Request, e model.RemoteCacheEntry) Request

TransportRequest is the upstream request for q: the resource's escaped path, or the path mapped to the upstream's layout, or its external URL, with its query, the adapter's Accept header and body. Given e, the cached complete representation of the same resource, it adds e's validator (If-None-Match, else If-Modified-Since) so that the upstream can answer 304; the caller's own validators never reach the upstream. Format rules build their extra exchanges, such as Maven's checksum sidecars, from it so that they go out as the policy's own requests do.

The request's matrix parameters follow the path, after its last segment, as 7.x's HttpRepo.downloadResource (GET) and assembleRetrieveInfoUrl (HEAD) append buildRequestMatrixParams to the remote request URL. They are not part of the cache key, so the copy they fetch is cached at its bare path. An external URL names its own resource and takes none. Request.Matrix names them, so that the transport checks them by their own rule (CheckedMatrix) and the path before them as any path.

type SmartPeer

type SmartPeer struct {
	BaseURL    string
	Repository string
	Class      repo.Class
	Version    string
	// contains filtered or unexported fields
}

SmartPeer identifies only the configured peer. Parsing it does not negotiate capabilities or grant network authority; callers use source.Service.Read. Class and Version are filled only by authenticated discovery.

func ParseSmartPeer

func ParseSmartPeer(c repo.Config) (SmartPeer, error)

ParseSmartPeer accepts repository endpoints, including the documented api/<package>/<repository> forms. Query-bearing and ambiguous endpoint paths cannot safely identify a different management API and are refused.

func (SmartPeer) Revision

func (p SmartPeer) Revision() string

Revision returns the credential revision the peer was discovered under, empty for a peer that ParseSmartPeer returned. Smart Remote refuses a peer whose revision is not the repository's current one with source.ErrSuperseded, so a credential change cannot reuse a discovery made with the old credentials.

func (SmartPeer) StorageURL

func (p SmartPeer) StorageURL(path string, query url.Values) (string, error)

StorageURL constructs a peer storage endpoint without accepting another authority, repository, or a preescaped traversal. It never performs I/O.

func (SmartPeer) WithRevision

func (p SmartPeer) WithRevision(r string) SmartPeer

WithRevision returns a copy of p marked as discovered under the credential revision r, which Smart's discovery calls. The revision is no field, so neither a SmartPeer literal nor ParseSmartPeer carries one.

type Store

type Store interface {
	tx.Runner
	RemoteCache() port.RemoteCacheStore
	Repos() port.RepoStore
	Items() port.ItemStore
	WorkQueue() work.WorkQueue
	Leases() work.LeaseStore
}

Store is the persistence that the policy, Smart Remote and the ecosystem remote rules reach through Policy.Store: the remote cache, repositories and items, the work queue and the lease table, in transactions. Every call made inside a policy transaction joins it, and work.New builds the Smart and Maven companion queues on it, so work they enqueue exists exactly when the change that needs it commits (decision 0033). CheckCurrent is handed it. It names no access store: credentials reach the policy through Options. Each composite store in app is a Store.

type Upstream

type Upstream interface {
	// Connection returns the connection for c configured by opts. A repository
	// whose configuration or opts.Revision changed gets a new one. On error
	// the Connection is a nil interface, never a nil pointer inside one, so
	// that a caller can compare it with nil.
	Connection(c repo.Config, opts Options) (Connection, error)
}

Upstream opens pooled connections to remote origins. It is the port through which the policy, Smart Remote and the format rules reach an upstream, so that none of them holds the transport; *Pool implements it, and it is safe for concurrent use. It sits beside Options, Request and the transport errors that its callers share, not in a separate ports package (decision 0044, "Artifacts and remote").

Directories

Path Synopsis
Package smart is Smart Remote: a remote repository that discovers the Artifactory repository behind its URL, copies and refreshes the user properties of what it caches, reports its downloads to the peer, records when an item is confirmed gone from the origin, and answers transitive AQL against the peer.
Package smart is Smart Remote: a remote repository that discovers the Artifactory repository behind its URL, copies and refreshes the user properties of what it caches, reports its downloads to the peer, records when an item is confirmed gone from the origin, and answers transitive AQL against the peer.
Package source is the read boundary shared by remote package adapters.
Package source is the read boundary shared by remote package adapters.

Jump to

Keyboard shortcuts

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