source

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: 24 Imported by: 0

Documentation

Overview

Package source is the read boundary shared by remote package adapters. It is below HTTP routing and outside format write hooks: neither a resolver nor a body reader may run inside the transaction that publishes a cached item.

Role

artifacts module, core layer: the authorised read boundary shared by adapters. Service.Read checks a request's path, permission and repository restrictions before any backend work, resolves the durable source identity, hands the read to a Backend under a Permit, and fences what comes back against a changed source or withdrawn authority.

Inputs

  • Driving: the routes and format slices that read a remote repository (artifacts/adapters/http, pkgroute and the ecosystem slices), and core remote's discovery and listings, through Service.Read with the Request and Resource they build.
  • Driven: the Backends the application installs for the HTTP and cache-only reads (core remote's Policy, or a format backend over it such as Maven's or Docker's), Resolve for the source identity, Revalidate for the caller's current authority, and access/api's Decider, which answers each Request's permission questions.
  • The generic download policy (generic.CheckDownload), which every authorised read also passes: at its permission path, or at the Resource's PolicyPath, the path Artifactory 7.x caches the document or file at, when the adapter names one, and only the repository's blackout when the Resource is BlackoutOnly (Resource.CheckPolicy).

Outputs

  • Service and its Read; Backend; Request, Resource, Permit, RetrievalIntent and ResourceKind; Result, Stream, Representation and MetadataResponse.
  • The closed adapter contracts: CocoaPodsGitSource and ValidGitLFSActionHeaders.
  • The safe failures (ErrDenied, ErrInvalidRequest, ErrUnsupported, ErrUnavailable, ErrSuperseded, ErrInvalidResult) and HTTPError with its FailureKind, which routers map to their own error envelopes.
  • The cache fill check: AuthorizeFill, which a backend asks before it keeps what it fetches, and its refusal CacheFillDenied, with MetadataPath, the paths it asks Annotate for; and ErrAssumedOffline, a remote's miss while its upstream is assumed offline. Both are kernel.ErrNotFound, which the item route words as 7.x does (#1587, #1601).
  • Resource.CheckPolicy, the policy rule Service.Read applies, which the application's Revalidate fences a result with too.
  • A Result's descendant checks: CheckRead and CheckFolder, which apply the download policy as Read does, and CheckPermission, which checks Read permission alone, for a listing that keeps a release whose file the repository's patterns reject, as Artifactory's listings do.

Invariants

  • Path, permission and repository restrictions run before any source lookup or backend call; a Request without a decider is refused.
  • A Permit only narrows: no hop borrows a more privileged flight's result, and a cache-only read never reaches the network.
  • A backend failure leaves as a safe failure, kernel.ErrNotFound, the context's error or an HTTPError with a bounded status and Retry-After; upstream bodies, URLs, headers and credentials are never error messages. The download policy's refusal leaves as its own *format.RejectionError, from Read and from CheckRead and CheckFolder alike, since artifactweave writes its message: a listing that checks each disclosed release can keep one whose file is refused, and a read answers the policy's 404 (#1237). A failure of the server's own storage (format.ErrStorageFault) leaves as it is too, in the store's words, so a router answers it as a server fault rather than as ErrUnavailable (#1269). A *CacheFillDenied and ErrAssumedOffline leave as they are, for the item route's reasons.
  • The package opens no store transaction and propagates none.

References

Status

Implemented P9. Moved here in P9d.

Testing

  • source_test.go, source_boundary_test.go, root_test.go, smart_test.go, policy_test.go and storage_fault_test.go are an external test package (source_test) over fake backends: read intents and representations, refusals before lookup, result validation and safe errors, a storage fault passed on as it is, stream ownership and late fences, root metadata grants, the Smart and Git LFS contracts, and the policy path, blackout-only reads, policy refusals from CheckRead and CheckPermission's permission-only check; fill_test.go, the cache fill check and its refusal and the assumed-offline miss passed on.
  • authorize_test.go and cocoapods_test.go are in-package unit tests of the path authorisation and the CocoaPods Git descriptor.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrDenied         = errors.New("source: source read denied")
	ErrInvalidRequest = errors.New("source: invalid source request")
	ErrUnsupported    = errors.New("source: source kind or operation is not implemented")
	ErrUnavailable    = errors.New("source: source unavailable")
	ErrSuperseded     = errors.New("source: source configuration changed during retrieval")
	ErrInvalidResult  = errors.New("source: invalid source result")
)

Safe failures are protocol-independent. Routers map them to their own error envelopes; upstream response bodies, URLs and credentials are never messages.

View Source
var ErrAssumedOffline = fmt.Errorf("source: remote assumed offline: %w", kernel.ErrNotFound)

ErrAssumedOffline is a remote's answer for a path it cannot serve while its upstream is assumed offline: nothing complete cached, and no upstream asked. 7.161.26's RemoteRepoBase.internalGetInfo asks isOffline, which is true while the repository is assumed offline, before it asks the upstream anything, and answers such a path with an UnfoundRepoResource, which the download answers 404 (DownloadServiceImpl.respondResourceNotFound). It is kernel.ErrNotFound, so a route that answers its own miss answers this one too, and a virtual repository passes over the member, as over an offline one (decision 0008, R3); the item route names the repository's state in its reason.

Functions

func AuthorizeFill

func AuthorizeFill(q Request) error

AuthorizeFill checks that q's caller may fill the remote's cache with q's resource: Deploy/Cache (accessapi.ActionWrite) on the path 7.x keeps it at, the resource's PolicyPath when it names one and its Path otherwise, or Annotate on a metadata path. Permissions on a remote are always those of its cache ("permissions are always on the cache repo key", RemoteRepoBase.checkDownloadIsAllowed), which the decider judges as the remote. It returns a *CacheFillDenied, or nil.

Only the checks of assertValidDeployPathAndPermissions that a fill can meet are made. Delete/Overwrite is checked there only to replace a file the cache repository does not treat as expirable, without a forced expiry check (DbStoringRepoMixin.assertOverride), and 7.x refreshes only expirable files (ZapServiceImpl.zapFile zaps nothing else), as the remote policy refreshes only metadata and mutable files; Maven metadata and checksums are never protected. The storage quota has no counterpart.

func ChecksumSubject

func ChecksumSubject(path string) (string, bool)

ChecksumSubject returns the file a ChecksumOnly resource's path names, less its .sha256, .sha512, .sha1 or .md5, and false for any other path.

func MetadataPath

func MetadataPath(p string) bool

MetadataPath reports whether p is what 7.161.26's NamingUtils.isMetadata calls metadata, which assertValidDeployPathAndPermissions asks Annotate for: a file name holding ":" that ends in ":properties", ":statistics" or ":maven-metadata.xml", the "<resource>:<metadata>" form. A plain maven-metadata.xml is a file like any other, needing Deploy ("Maven metadata is treated as regular file").

func ValidGitLFSActionHeaders

func ValidGitLFSActionHeaders(headers http.Header) bool

ValidGitLFSActionHeaders limits upstream-selected basic-transfer headers to bounded end-to-end fields. The transport applies them only to the exact validated action URL and removes them before following any redirect.

Types

type Backend

type Backend interface {
	Read(context.Context, Request, Permit) (Result, error)
}

Backend resolves one already-authorized request. It owns freshness, fetching and optional publication, but cannot expand Permit. Network and body reads precede short conditional publication transactions. Any body returned with an error is closed by Service, so failed admission cannot leak a connection.

type CacheFillDenied

type CacheFillDenied struct {
	// User is the caller's name, "anonymous" for an anonymous one.
	User string
	// Repo is the remote repository's key.
	Repo string
	// Path is the cache path checked: where 7.x keeps the file.
	Path string
	// Annotate is set for a metadata path, which needs Annotate.
	Annotate bool
}

CacheFillDenied refuses a read that would fill a remote repository's cache from its upstream for a caller who may read the remote but not fill its cache: who lacks Deploy/Cache on the cache path, or Annotate on a metadata path. JFrog's Permissions page: on a remote, Read "only allows downloading from the remote cache", and new files need "the Deploy/Cache permission". 7.161.26's RemoteRepoBase.downloadAndSave calls RepositoryServiceImpl.assertValidDeployPathAndPermissions on the cache path before it downloads.

It is kernel.ErrNotFound for every route but the item route, which answers Message as 7.x's download does (403 "Rejected artifact download request: ..."). JFrog's KB article "Why Am I Getting Random 404 Errors When Downloading From a Remote Repository" says installing packages without Deploy "will result in a 404 error - even if the artifact exists in the upstream repository", and RTFACT-30824 shows a PyPI page answered 404 for a read-only user; which body each native route sends is closed code, inferred to be its own miss [I].

func (*CacheFillDenied) Error

func (e *CacheFillDenied) Error() string

Error returns Message.

func (*CacheFillDenied) Message

func (e *CacheFillDenied) Message() string

Message is assertValidDeployPathAndPermissions' reason, for the cache path: "User <user> is not permitted to deploy '<path>' into '<remote>-cache:<path>'.", or "... to annotate '<path>' on ..." for a metadata path (RepositoryServiceImpl 2817-2870, 7.161.26).

func (*CacheFillDenied) Unwrap

func (e *CacheFillDenied) Unwrap() error

Unwrap is kernel.ErrNotFound, the answer of every route but the item route.

type ClientMIME

type ClientMIME struct {
	Accept []string
}

ClientMIME is what 7.x's MIME check reads from the client's request: its Accept values, none when it sent no Accept.

type CocoaPodsGitSource

type CocoaPodsGitSource struct {
	URL        string `json:"git"`
	Tag        string `json:"tag,omitempty"`
	Branch     string `json:"branch,omitempty"`
	Commit     string `json:"commit,omitempty"`
	Submodules bool   `json:"submodules,omitempty"`
}

CocoaPodsGitSource is the closed source contract for a pod's Git checkout. The remote backend reads Git objects without executing Git, checking out a filesystem, or handing upstream destinations to the downstream client.

func (CocoaPodsGitSource) Validate

func (g CocoaPodsGitSource) Validate() error

Validate checks g against the closed contract before any Git exchange. URL must be an absolute http or https URL of at most 2,048 bytes with a host and a path of plain segments, and no user information, query, fragment, percent escape, backslash, NUL or line break. Tag and Branch, when set, must be safe Git reference names, and Commit, when set, a 40-character hexadecimal object ID other than all zeros. Anything else answers ErrInvalidRequest.

func (CocoaPodsGitSource) Variant

func (g CocoaPodsGitSource) Variant() string

Variant binds the cached archive to every checkout option, including the requested revision and whether Git submodules are materialized.

type FailureKind

type FailureKind int

FailureKind distinguishes status-bearing faults for freshness policy.

const (
	FailureKindHTTP FailureKind = iota + 1
	FailureKindConnectivity
	FailureKindTimeout
	FailureKindSecurity
	FailureKindIntegrity
	FailureKindProtocol
)

The failure kinds an HTTPError carries, which say what failed rather than which status to answer: an upstream HTTP status, an unreachable upstream, a timeout, a refused destination or TLS check, bytes that failed validation, or a response the protocol does not allow. The remote policy reads them to decide whether a stale entry may be served and whether the assumed-offline circuit counts the failure; adapters map the error to their own status and envelope.

type HTTPError

type HTTPError struct {
	Kind       FailureKind
	Status     int
	RetryAfter time.Duration
}

HTTPError preserves an approved status without its upstream body, URL or authentication challenge. Confirmed 404 uses kernel.ErrNotFound; other failures must never be recorded as negative cache entries.

func (*HTTPError) Error

func (f *HTTPError) Error() string

Error returns "source: " and the standard text of f's Status, never the upstream's body, URL or challenge, so the error is safe to log.

type MIMERefusal

type MIMERefusal struct {
	*format.RejectionError
}

MIMERefusal is a remote's refusal of an upstream file for its label on a resource with ClientMIME: the 409 and message its RejectionError carries, which a client is answered with as any rejection.

func (*MIMERefusal) Unwrap

func (e *MIMERefusal) Unwrap() error

Unwrap is the rejection, which pkgroute.SourceError answers.

type MetadataResponse

type MetadataResponse struct {
	BaseURL string
}

MetadataResponse is trusted adapter-only response context, never an HTTP header or log field. BaseURL contains only scheme, host and path after redirects. Adapters opting into this context must change Variant when upgrading old cache entries that did not retain their response base.

type Permit

type Permit struct {
	Identity               model.SourceIdentity
	Intent                 RetrievalIntent
	UpstreamNetworkAllowed bool
}

Permit is request-scoped authority. A future project backend may narrow UpstreamNetworkAllowed while retaining MayFetch to consult a producer's stored bytes. Each hop must narrow this permit; it cannot borrow a more privileged flight's newly fetched result. It is not a persisted credential.

type Representation

type Representation struct {
	// OriginalChecksums retain upstream declarations for Maven pass-through;
	// Checksums always describe the computed bytes.
	OriginalChecksums kernel.Checksums
	// MediaType is the upstream's label on a stream the remote policy
	// returns, which the MIME check and the registry's manifest
	// negotiation read; a route serving a remote file answers the type of
	// Path instead (pkgroute.ServeStream).
	MediaType string
	Size      int64
	// ETag is a validator the route chose for what it serves, such as the
	// registry's manifest digest or a document it builds per request. The
	// remote policy leaves it empty and keeps the upstream's ETag in its
	// entry for its own conditional request, so a remote file answers with
	// its SHA-1, as 7.161.26's RequestResponseHelper.setBasicHeaders sets
	// every downloaded resource's ETag (pkgroute.ServeStream, #1484).
	ETag         string
	Modified     time.Time
	Checksums    kernel.Checksums
	ContentRange string
	// Path, when set, is the repository path of the remote file these bytes
	// are, the upstream's or its cached copy: the item route sets it on
	// every stream it serves, and the package route kit on an artifact read
	// (pkgroute.Kit.Read). The stream is then answered with the type of its
	// path, as 7.161.26's RemoteRepoResource.getMimeType types a remote file
	// and a kept copy is typed (#1477). Empty for a document a protocol
	// builds per request and for raw metadata a protocol serves under its
	// own type.
	Path string
}

Representation describes bytes safely, without arbitrary upstream headers or an upstream URL. Size is -1 when unknown. Validators describe these exact bytes; an adapter that rewrites metadata must replace them.

type Request

type Request struct {
	Repo         repo.Config
	Subject      accessapi.Subject
	Access       accessapi.Decider
	Matrix       model.Matrix
	MatrixParams string
	Resource     Resource
	CacheOnly    bool
	Project      string
	Visited      []model.RepositoryIncarnation
}

Request carries the resolved repository and caller's permission snapshot: Subject is who the caller acts as, and Access the decider that answers its permission questions. A nil Access refuses every path with ErrDenied. A caller without a decider leaves Access a nil interface, as accessapi.DeciderFrom answers for an absent one, never an interface holding a nil pointer, which would pass that check and fail on its first question. Adapters resolve repository existence before constructing it. Project and Visited retain the original consumer context for P11 and future P10 sources; neither is taken from caller-supplied headers.

Matrix is the request's matrix parameters as a download matches them. MatrixParams is the same parameters as the upstream URL carries them after its last segment: ";key=value" per value in request order, ";key+=" for a mandatory key, ";key" for a blank value, escaped, with "+" as %2B. It is kept out of Resource on purpose: Resource's terms are the cache key and the escaped path is checked against Path, while 7.x caches the file at its bare path whatever properties a request asks for (HttpRepo appends them to the URL only).

type Resource

type Resource struct {
	// CocoaPodsGit requests a bounded Git-object archive through the normal
	// remote cache and current-authority publication fences.
	CocoaPodsGit *CocoaPodsGitSource
	// RequireSmart requests authenticated peer discovery before this prepared
	// metadata request. Only adapters set it; it conveys no network permission.
	RequireSmart bool
	// SmartAQL is a closed read-only items.find operation. It uses transient
	// metadata and the discovered peer search endpoint, never a generic POST.
	SmartAQL string
	// Adapter targets never change Path, which remains the authorization and
	// cache identity. UpstreamPath is escaped and repository-relative;
	// ExternalURL is a metadata-selected absolute URL subject to the transport's
	// DNS, redirect and credential-origin checks. They are mutually exclusive.
	UpstreamPath string
	ExternalURL  string
	// CheckURL narrows an adapter-selected destination and every redirect hop.
	// It never replaces transport DNS/credential policy and requires a Variant.
	CheckURL func(context.Context, *url.URL) error
	// NoCrossOriginAuth prevents a format-selected URL from borrowing remote
	// repository credentials, client certificates or cookies on another origin.
	NoCrossOriginAuth bool
	// GitLFSActionHeaders are bounded, validated headers supplied by an upstream
	// Git LFS download action. They apply only to that exact action URL, never
	// redirects or cached representations.
	GitLFSActionHeaders http.Header
	// Checksums pin the selected representation independently of the repository's
	// policy for optional upstream checksum headers. Variant identifies the
	// adapter validation schema; it must change if validation semantics change.
	Checksums           kernel.Checksums
	ExpectedContentType string
	// ExpectedContentTypes is an exact metadata MIME allowlist for negotiated APIs.
	// It requires complete body validation and cannot accompany the singular hint.
	ExpectedContentTypes []string
	// ClientMIME, when set, holds a download to 7.x's MIME check as its
	// item route makes it: the client's Accept values are the requested
	// types, and a refused label answers 409 with 7.x's message, which
	// Service.Read then answers for the path until the repository's
	// missedRetrievalCachePeriodSecs pass. Without Accept the requested
	// type is the type of the URL asked for. A format route's read through
	// pkgroute sets it with no Accept unless the resource has a format
	// hint (#1392); nil keeps the check and answers its 502. Accept here
	// never reaches the upstream or the cache identity.
	ClientMIME *ClientMIME
	Validate   func(context.Context, io.ReadSeeker, int64) error
	// ValidateMetadata validates complete metadata against the actual response
	// base after redirects. It is exclusive with Validate and requires Variant.
	ValidateMetadata func(context.Context, io.ReadSeeker, int64, MetadataResponse) error
	// PermissionFolder authorizes metadata against the folder it describes; the
	// adapter must filter its response to the readable descendants. Artifact
	// requests always authorize their exact cache path.
	PermissionFolder bool
	PermissionPath   string
	// PermissionRoot is a trusted metadata-discovery scope when a layout cannot
	// represent the query as a canonical folder. It requires actual root Read,
	// not a grant on any descendant, and disclosed files still need CheckRead.
	PermissionRoot bool
	// PolicyPath, when set, is the path the repository's download policy is
	// checked at instead of the permission path, as a file: the path
	// Artifactory 7.x caches the document or file at, such as npm's
	// .npm/<name>/package.json, so a pattern written for 7.x's layout
	// refuses what it names there, while Read permission is still checked
	// at the permission path (CheckPolicy).
	PolicyPath string
	// BlackoutOnly checks only the repository's blackout, not its include
	// and exclude patterns: for a lookup a download makes on its way to the
	// file it serves, such as the metadata a remote tarball's URL is read
	// from, which the patterns of the lookup's own path do not refuse.
	BlackoutOnly bool

	// GoneIsMissing is a trusted protocol opt-in: GOPROXY permits member fallback
	// for both 404 and 410. Other protocols retain their existing error semantics.
	GoneIsMissing bool
	// ModuleDownloadLocation is a closed metadata projection for Terraform's
	// 204/X-Terraform-Get response. The backend retains the exact header in a
	// private JSON control representation; the adapter must validate its source
	// against the actual response base before admission and rewrite it on delivery.
	ModuleDownloadLocation bool
	// NuGetEmptyFeed projects a bodyless NuGet v2 204 into a fixed empty Atom
	// feed. Only trusted feed/query metadata adapters may opt in; complete
	// metadata validation, an Atom MIME expectation and a versioned schema remain required.
	NuGetEmptyFeed bool
	// ChecksumOnly is a checksum file (a .sha256, .sha512, .sha1 or .md5
	// path, ChecksumSubject) the item route reads from the upstream itself,
	// once the upstream found the file it names: the checksum request of a
	// Maven-family remote that stores nothing (7.161.26's
	// RemoteRepoBase.getRemoteChecksum), and of a generic remote with
	// retrieveSha256FromServer whose file's info held no value
	// (getChecksumByExternalSha256). It must remain transient and
	// authorize the artifact it describes.
	ChecksumOnly bool
	// ChecksumRequest marks a read of the file a checksum request (a
	// .sha1, .md5, .sha256 or .sha512 path) names. Its HEAD is answered
	// from the upstream's info and keeps no body, where any other HEAD on
	// a remote that stores artifacts locally downloads the file, as 7.x
	// leaves checksum requests out of that download.
	ChecksumRequest bool
	// Mutable marks a refreshable artifact name, such as a non-unique Maven
	// snapshot. It does not turn a binary into metadata for zap semantics.
	Mutable     bool
	Kind        ResourceKind
	Path        string
	EscapedPath string
	Method      string
	// PostBody is a canonical, bounded format-owned metadata query. Only the
	// closed AI editor and Git LFS contracts below may use it. No caller
	// supplied headers or credentials are forwarded with it.
	PostBody []byte
	// Transient forbids persistent caching of a Git LFS batch response, whose
	// upstream transfer actions may carry expiring URLs or credentials.
	Transient bool
	// NoCacheFile marks a read whose document 7.x keeps in the remote's
	// memory rather than as a file of its cache, such as a folder listing
	// (RemoteRepoBase.remoteResourceCache), so the remote policy fills it
	// for a caller with Read alone (AuthorizeFill is not asked).
	NoCacheFile bool
	Query       string
	Variant     string
	// Accept is the adapter's own Accept for the upstream request, such as
	// the registry's manifest types or npm's abbreviated packument, and part
	// of the cache identity. It is never the client's header: 7.161.26's
	// HttpRepo.whiteListHeaders sends upstream no header of a client's
	// request, and keeps one cached file per path (#1390).
	Accept          string
	Range           string
	IfRange         string
	IfNoneMatch     string
	IfModifiedSince string
	// contains filtered or unexported fields
}

Resource contains only downstream fields a source may use. There is no caller-supplied header bag: credentials, cookies and forwarding headers cannot accidentally reach an upstream. Path is decoded and repository-relative; Query and Variant are opaque and must never be included in logs.

func (Resource) CheckPolicy

func (r Resource) CheckPolicy(c repo.Config, path string) error

CheckPolicy applies c's download policy to a read of r whose Read permission is checked at path, a folder when r.PermissionFolder or r.PermissionRoot says so: at r.PolicyPath instead, as a file, when the adapter set one, and only c's blackout when r.BlackoutOnly is set (generic.CheckDownload, generic.CheckBlackedOut). Service.Read and the application's Revalidate both check it, so a read is refused, and a result fenced, by the same rule. A descendant Result.CheckPermission checks has no policy to apply.

type ResourceKind

type ResourceKind int

ResourceKind distinguishes protocol metadata and version queries from bytes. Version lists remain authoritative upstream representations, not a listing of the subset of artifacts present in the local cache.

const (
	ResourceKindArtifact ResourceKind = iota + 1
	ResourceKindMetadata
	ResourceKindVersions
)

The kinds of resource an adapter reads. An artifact is the bytes cached and authorised at their exact path; metadata and versions are protocol documents, read under the repository's metadata retrieval timeout. The adapter chooses the kind, and the kind selects the remote policy's cache rules, not a status.

type Result

type Result struct {
	Metadata MetadataResponse `json:"-"`

	// CheckRead checks a disclosed descendant against current authority. It is
	// bounded by the originally authorized metadata folder and never fetches.
	CheckRead func(context.Context, string) error
	// CheckFolder checks whether a disclosed descendant folder can contain
	// readable items. It preserves narrow grants without granting file access.
	CheckFolder func(context.Context, string) error
	// CheckPermission is CheckRead without the download policy: it checks
	// only a disclosed descendant's Read permission, for a listing that
	// keeps a release whose file the repository's include and exclude
	// patterns reject, as Artifactory's listings and indexes do, while the
	// file's own read is refused (#1237).
	CheckPermission func(context.Context, string) error
	// Revalidate fences backend-specific credentials immediately before delivery.
	Revalidate func(context.Context) error
	Item       *model.Item
	Stream     *Stream
	Identity   model.SourceIdentity
	// Used records successful content delivery using the backend's opaque cache
	// token. The delivery adapter calls it after a successful GET/range or signed
	// URL issuance, never on lookup, HEAD, 304 or a failed body. Nil for no-store.
	Used func(context.Context) error
	// Refused is set on a result served from an expired cached file
	// because the upstream's label was refused, as 7.x's
	// RemoteRepoBase.internalGetInfo serves it: the refusal, which Read
	// remembers for the requests after this one.
	Refused *MIMERefusal
}

Result holds exactly one of Item and Stream. A persisted Item belongs to the consumer's cache; a stream must not be presented as a fake persisted item. Identity allows consumers and publication code to retain the source revision.

type RetrievalIntent

type RetrievalIntent int

RetrievalIntent is computed from the authorized entry point, never from an HTTP header or query parameter. CacheOnly cannot traverse a source or join a MayFetch flight, even if another request is already filling the same path.

const (
	RetrievalIntentCacheOnly RetrievalIntent = iota + 1
	RetrievalIntentMayFetch
)

The retrieval intents Service.Read puts in a Permit: CacheOnly when the Request is CacheOnly, which serves only what the cache already holds, and MayFetch otherwise, which may fill from the upstream. A backend never widens a CacheOnly permit.

type Service

type Service struct {
	Resolve    func(context.Context, repo.Config) (model.SourceIdentity, error)
	Revalidate func(context.Context, Request, Permit) error
	HTTP       Backend
	Cache      Backend
}

Service registers only the implemented HTTP source kind. Resolve obtains the durable identity matching the supplied configuration snapshot (#619), without network I/O. Revalidate, when supplied, rechecks current caller/repository authority before lookup and before returning bytes (P11 adds share revisions). The application must not install this service in production routes until the relevant adapter is ready. Nil Cache is a cache miss, never a network fallback.

func (*Service) ForgetRefusals

func (s *Service) ForgetRefusals(repoKey, path string)

ForgetRefusals drops the remembered MIME refusals of repoKey at path and below it, everywhere for an empty path, as 7.x's zap clears its missed-retrieval cache (ZapServiceImpl, RemoteRepoBase.removeFromCaches).

func (*Service) Read

func (s *Service) Read(ctx context.Context, q Request) (Result, error)

Read applies path, permission and repository restrictions before any backend work, then fences the returned representation against a changed source. No store transaction is opened here or propagated by this package.

type Stream

type Stream struct {
	Body   io.ReadCloser
	Status int
	Representation
}

Stream is an unpersisted representation (including storeArtifactsLocally=false). Status is 200, 206 or 304. Body ownership transfers to the caller on success; the caller closes it on every path, including HEAD and downstream disconnect. Service also closes it when the request context is canceled.

Jump to

Keyboard shortcuts

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