source

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 8 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.

README

internal/source

The Source contract of architecture.md section 3.3, plus a Registry and the contract test suite every source must pass.

Sources are dumb: they list raw upstream versions and an opaque fetch state. Diffing, version parsing, filtering and cooldown belong to the core (architecture.md section 3.4).

Types

Type Purpose
Source Kind(), Validate(Target) error, List(ctx, Target, FetchState) (Result, error)
Target Kind + source-specific Coordinates (map[string]string), stored as coordinates_json
FetchState ETag, LastModified, Cursor; opaque to the core, stored as fetch_state_json
Result Versions (newest first if known), the next State, NotModified
Version Raw, PublishedAt, Prerelease *bool, Yanked, URL, NotesURL, Metadata
Canonicalizer optional: Canonical(Target) (Target, error) returns the one spelling stored and used as the coalescing key (ADR 0021); call it through source.Canonical(src, t)
Registry explicit value (no package global): NewRegistry, Register, Get, Kinds

Errors: ErrInvalidTarget (every Validate failure wraps it), ErrUnknownKind, ErrDuplicateKind.

Writing a source

  1. Create internal/source/<kind>/ and implement source.Source.
  2. Inject the HTTP client. The constructor takes a base URL and an *http.Client (pypi.New(baseURL string, c *http.Client)); never use http.DefaultClient. Production passes the netguard client (#49); tests pass the guarded client from sourcetest. The #49 client must therefore accept a base http.RoundTripper, so the test guard can sit underneath it.
  3. Validate does no I/O (the suite asserts zero requests) and wraps source.ErrInvalidTarget.
  4. List takes ctx first, wraps errors with %w (a cancelled context must surface context.Canceled), sends conditional headers from FetchState, and on a 304 returns NotModified: true, no versions and a non-zero state (keep the incoming one if the 304 carries no ETag). A target that does not exist upstream is an error, not an empty result. List must be safe for concurrent use.
  5. Fill PublishedAt whenever upstream has it; leave Prerelease nil when upstream has no flag.
  6. Return versions in a deterministic order.
  7. If one upstream object can be spelled several ways in the coordinates (case, separators), implement source.Canonicalizer: no I/O, keep Kind, idempotent, result passes Validate. Cite the registry's own naming rule, and list other spellings in Fixtures.Aliases. If the registry is case-sensitive, don't.
  8. Register it on the Registry in the composition root (registry.Register(pypi.New(...))).

The contract suite: sourcetest.Run

func TestContract(t *testing.T) {
	var rev atomic.Int64 // bumped by Change to simulate a new release
	sourcetest.Run(t, nil, sourcetest.Fixtures{
		Handler: fakeUpstream(&rev), // recorded fixtures in testdata/
		New: func(baseURL string, c *http.Client) source.Source {
			return pypi.New(baseURL, c)
		},
		Valid:          source.Target{Kind: "pypi", Coordinates: map[string]string{"name": "requests"}},
		Invalid:        []source.Target{{Kind: "pypi"}, {Kind: "pypi", Coordinates: map[string]string{"name": "a/b"}}},
		Missing:        &source.Target{Kind: "pypi", Coordinates: map[string]string{"name": "does-not-exist"}},
		WantRaw:        []string{"2.0.0", "1.0.0"},
		Conditional:    true,
		Change:         func() { rev.Add(1) },
		HasPublishedAt: true,
	})
}

Run starts the httptest server for Handler, builds the source with New(srv.URL, client) and checks:

Subtest Checks
Kind Kind() is non-empty and equals Fixtures.Valid.Kind
ValidateAccepts / ValidateRejects the valid target passes; every Invalid target fails with an error wrapping ErrInvalidTarget
ValidateNoRequests Validate sent no HTTP request (owned server only)
Canonical for a Canonicalizer: Canonical(Valid) keeps the kind, passes Validate, is idempotent, does not mutate its argument and sends no request; every Aliases entry has the same canonical target. A Canonicalizer without Aliases fails, and so do Aliases without Canonicalizer
ListDeterministic two List calls with empty state return identical results, at least one version, no empty Raw, not NotModified
ListConcurrent 8 concurrent List calls all equal the first (run with -race)
ListMatchesFixture if WantRaw is set, Raw values match it in order
ListMissing if Missing is set, List returns an error
ListHonoursContext a cancelled context makes List fail with context.Canceled
NotModified (if Conditional) the state from call 1 makes call 2 return NotModified, no versions, non-zero state
PublishedAt (if HasPublishedAt) every version has a non-zero PublishedAt
ChangeInvalidatesState (if Conditional and Change) after Change, List with the old state is not NotModified and returns versions. Runs last
Network isolation

sourcetest.Client(t, srv) returns an *http.Client whose transport fails the test, with a clear message, and sends nothing for any request whose URL.Host is not the fake server's listener address. A net.Dialer Control hook refuses any other address as defence in depth. sourcetest.Requests(c) returns the number of requests sent. Nothing global is modified, so tests calling Run may use t.Parallel(). The guard only covers clients you inject: a source that dials with its own client or http.DefaultClient is not caught, which is why injection is required.

For a source that needs no HTTP, pass it as src and leave Handler and New unset (the HTTP-specific checks are then skipped). sourcetest.Fake is an in-memory, concurrency-safe source that passes the suite; use it for tests of the scheduler and the core. Live-registry tests go behind the live build tag and never run in go test.

Design decisions for Target, FetchState and errors: ADR 0006.

Documentation

Overview

Package source defines the Source contract (architecture.md section 3.3) and a Registry of Source implementations by kind. Implementations live in subpackages, one per kind (internal/source/pypi, ...).

Sources are dumb: they list the raw upstream versions and an opaque fetch state. Diffing, version parsing and policy belong to the core.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidTarget is wrapped by Validate errors.
	ErrInvalidTarget = errors.New("source: invalid target")
	// ErrUnknownKind is returned when no source is registered for a kind.
	ErrUnknownKind = errors.New("source: unknown kind")
	// ErrDuplicateKind is returned when a kind is registered twice.
	ErrDuplicateKind = errors.New("source: kind already registered")
)

Functions

This section is empty.

Types

type Canonicalizer

type Canonicalizer interface {
	Canonical(t Target) (Target, error)
}

Canonicalizer is an optional interface a Source implements when one upstream object can be spelled several ways in its coordinates ("Requests" and "requests" on PyPI). Canonical returns the one spelling the core stores and uses as the coalescing key, so that every spelling shares one target and one fetch. See ADR 0021, which amends ADR 0006.

Canonical is called only on a target that Validate accepted. It does no I/O, keeps the Kind, is idempotent (Canonical of its result returns the result unchanged) and its result passes Validate. It must not mutate t. A Source whose coordinates are already canonical as written does not implement it.

type FetchState

type FetchState struct {
	ETag         string `json:"etag,omitempty"`
	LastModified string `json:"last_modified,omitempty"`
	Cursor       string `json:"cursor,omitempty"`
}

FetchState is the conditional-request state kept per target (target.fetch_state_json). Its content is opaque to the core: only the source that produced it interprets it. The zero value means "no state".

func (FetchState) IsZero

func (s FetchState) IsZero() bool

IsZero reports whether s carries no state.

type Registry

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

Registry maps a name to its Source. The name of a built-in is its kind; a named instance (RegisterAs) has its own name and a Source of another kind, so that one instance can watch the same kind of registry at several URLs. It is an explicit value, not a package global: the composition root builds one and passes it down.

func NewRegistry

func NewRegistry() *Registry

NewRegistry returns an empty Registry.

func (*Registry) Get

func (r *Registry) Get(name string) (Source, error)

Get returns the Source registered under name (a kind, or the name of an instance), or an error wrapping ErrUnknownKind.

func (*Registry) KindOf

func (r *Registry) KindOf(name string) string

KindOf returns the base kind of the source registered under name (the kind events, purls, schemes and policy use), or name when none is.

func (*Registry) Kinds

func (r *Registry) Kinds() []string

Kinds returns the distinct kinds of the registered sources, sorted: the values of an event's data.source, whatever the instances are called.

func (*Registry) Names

func (r *Registry) Names() []string

Names returns every registered name, kinds and instances, sorted. A watch names one of them in its source.

func (*Registry) Register

func (r *Registry) Register(src Source) error

Register adds src under src.Kind(). It fails with ErrDuplicateKind if the kind is taken, and rejects a nil source or an empty kind.

func (*Registry) RegisterAs

func (r *Registry) RegisterAs(name string, src Source) error

RegisterAs adds src under name, a named instance of src.Kind(): its targets are stored with name as their kind, and src still receives and reports the base kind. It fails with ErrDuplicateKind if the name is taken, and rejects a nil source, an empty name or an empty kind.

type Result

type Result struct {
	// Versions are the raw upstream versions, newest first if known.
	Versions []Version
	// State is the state to pass to the next List call for the same target.
	State FetchState
	// NotModified is true when the upstream confirmed nothing changed.
	NotModified bool
}

Result is the outcome of a List call.

type Source

type Source interface {
	// Kind is the registry key: "pypi", "npm", "github-release", "oci", ...
	Kind() string
	// Validate checks the target's coordinates at create time. It does no
	// network I/O and returns an error wrapping ErrInvalidTarget.
	Validate(target Target) error
	// List fetches the upstream versions. When s lets the source prove that
	// nothing changed (ETag, Last-Modified, cursor) it returns a Result with
	// NotModified set and no Versions.
	List(ctx context.Context, t Target, s FetchState) (Result, error)
}

Source detects releases on one kind of upstream.

Implementations that do HTTP receive their *http.Client through their constructor (injection) and never use http.DefaultClient, so the netguard client or a test guard can be substituted. List wraps context errors with %w. See ADR 0006.

type Target

type Target struct {
	Kind        string            `json:"kind"`
	Coordinates map[string]string `json:"coordinates"`
}

Target identifies one upstream object (target.kind and target.coordinates_json in architecture.md section 5). Coordinates are source specific, for example {"name": "requests"} for pypi.

func Canonical

func Canonical(src Source, t Target) (Target, error)

Canonical returns the canonical form of t for src: src.Canonical(t) when src implements Canonicalizer, otherwise a copy of t. The result never shares its Coordinates map with t. It rejects a Canonicalizer that changes the Kind.

type Version

type Version struct {
	Raw         string         // "v2.3.0-rc.1"
	PublishedAt time.Time      // zero if upstream does not say
	Prerelease  *bool          // upstream flag if available; nil if unknown
	Yanked      bool           // yanked, unpublished or withdrawn upstream; deprecation goes in Metadata
	URL         string         // release page
	NotesURL    string         // release notes
	Metadata    map[string]any // digest, tarball url, dist-tags, ...
}

Version is one raw upstream version.

Directories

Path Synopsis
Package crates is the Source for crates.io.
Package crates is the Source for crates.io.
Package githubrelease is the "github-release" Source: it lists the releases of a GitHub (or GitHub Enterprise) repository.
Package githubrelease is the "github-release" Source: it lists the releases of a GitHub (or GitHub Enterprise) repository.
Package githubtag is the "github-tag" Source: it lists the git tags of a GitHub (or GitHub Enterprise) repository that does not publish releases.
Package githubtag is the "github-tag" Source: it lists the git tags of a GitHub (or GitHub Enterprise) repository that does not publish releases.
Package gitlabrelease is the "gitlab-release" Source: it lists the releases of a project on gitlab.com or on a self-managed GitLab instance.
Package gitlabrelease is the "gitlab-release" Source: it lists the releases of a project on gitlab.com or on a self-managed GitLab instance.
internal
apiclient
Package apiclient holds the token and redirect plumbing shared by the sources that call an authenticated HTTP API (github-release, github-tag, gitlab-release): the redacting token type, token providers, the test for where credentials may travel, the redirect guard that never carries credentials to another host or to plain http, and the fetch helper that adds the 404 and 401 hints.
Package apiclient holds the token and redirect plumbing shared by the sources that call an authenticated HTTP API (github-release, github-tag, gitlab-release): the redacting token type, token providers, the test for where credentials may travel, the redirect guard that never carries credentials to another host or to plain http, and the fetch helper that adds the 404 and 401 hints.
ghapi
Package ghapi holds the GitHub-specific plumbing shared by the GitHub-API based sources (github-release, github-tag): the default base URL, the "owner/name" coordinate parser and the authenticated GET helper.
Package ghapi holds the GitHub-specific plumbing shared by the GitHub-API based sources (github-release, github-tag): the default base URL, the "owner/name" coordinate parser and the authenticated GET helper.
Package npm is the Source for the npm registry.
Package npm is the Source for the npm registry.
Package pypi is the Source for PyPI releases (architecture.md section 3.3).
Package pypi is the Source for PyPI releases (architecture.md section 3.3).
Package registryauth adds the credential of a private registry or mirror (PRD F16) to every request of a source's HTTP client, so the sources themselves stay credential-free.
Package registryauth adds the credential of a private registry or mirror (PRD F16) to every request of a source's HTTP client, so the sources themselves stay credential-free.
Package sourcetest is the contract test suite every source.Source must pass.
Package sourcetest is the contract test suite every source.Source must pass.

Jump to

Keyboard shortcuts

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