diff --git a/internal/handler/cooldown_supported_test.go b/internal/handler/cooldown_supported_test.go index 7187edeb..372d78d3 100644 --- a/internal/handler/cooldown_supported_test.go +++ b/internal/handler/cooldown_supported_test.go @@ -10,10 +10,17 @@ import ( func TestCooldownSupportedCoversHandlers(t *testing.T) { calls := regexp.MustCompile(`(?:IsAllowed|Evaluate)\("([a-z]+)"|withheld\(h\.proxy, "([a-z]+)"|IsAllowed\((helmMetadataEcosystem)`) + // Metadata rewrites moved out of the handlers (#501) check cooldown in + // internal/metadata. files, err := filepath.Glob("*.go") if err != nil { t.Fatal(err) } + extracted, err := filepath.Glob("../metadata/*/*.go") + if err != nil { + t.Fatal(err) + } + files = append(files, extracted...) found := map[string]bool{} for _, f := range files { if strings.HasSuffix(f, "_test.go") { diff --git a/internal/handler/nuget.go b/internal/handler/nuget.go index 12f0c435..891282df 100644 --- a/internal/handler/nuget.go +++ b/internal/handler/nuget.go @@ -1,12 +1,12 @@ package handler import ( - "encoding/json" "errors" "fmt" "net/http" "strings" + "github.com/git-pkgs/proxy/internal/metadata/nuget" "github.com/git-pkgs/proxy/internal/retention" "github.com/git-pkgs/purl" ) @@ -122,56 +122,16 @@ func (h *NuGetHandler) handleServiceIndex(w http.ResponseWriter, r *http.Request _, _ = w.Write(rewritten) } -// rewriteServiceIndex rewrites service URLs in the index to point at this proxy. +// rewriteServiceIndex rewrites service URLs in the index to point at this +// proxy (see nuget.RewriteServiceIndex). func (h *NuGetHandler) rewriteServiceIndex(body []byte) ([]byte, error) { - var index map[string]any - if err := json.Unmarshal(body, &index); err != nil { - return nil, err - } - - resources, ok := index["resources"].([]any) - if !ok { - return body, nil - } - - for _, res := range resources { - rmap, ok := res.(map[string]any) - if !ok { - continue - } - - id, _ := rmap["@id"].(string) - rtype, _ := rmap["@type"].(string) - - // Rewrite URLs for services we proxy. The service type determines the - // local route because an upstream index may advertise a different host. - if id != "" { - rmap["@id"] = h.rewriteNuGetURL(id, rtype) - } - } - - return json.Marshal(index) + return nuget.RewriteServiceIndex(body, h.proxyURL) } -// rewriteNuGetURL rewrites a NuGet service URL based on its advertised type. -// Service types the proxy does not handle are returned unchanged. +// rewriteNuGetURL rewrites a NuGet service URL based on its advertised type +// (see nuget.ServiceURL). func (h *NuGetHandler) rewriteNuGetURL(origURL, serviceType string) string { - switch serviceType { - case "PackageBaseAddress/3.0.0": - return h.proxyURL + "/nuget/v3-flatcontainer/" - case "RegistrationsBaseUrl", "RegistrationsBaseUrl/3.0.0-beta", "RegistrationsBaseUrl/3.0.0-rc": - return h.proxyURL + "/nuget/v3/registration5-semver1/" - case "RegistrationsBaseUrl/3.4.0": - return h.proxyURL + "/nuget/v3/registration5-gz-semver1/" - case "RegistrationsBaseUrl/3.6.0", "RegistrationsBaseUrl/Versioned": - return h.proxyURL + "/nuget/v3/registration5-gz-semver2/" - case "SearchQueryService", "SearchQueryService/3.0.0-rc", "SearchQueryService/3.5.0": - return h.proxyURL + "/nuget/query" - case "SearchAutocompleteService", "SearchAutocompleteService/3.5.0": - return h.proxyURL + "/nuget/autocomplete" - default: - return origURL - } + return nuget.ServiceURL(h.proxyURL, origURL, serviceType) } // handleDownload serves a package file, fetching and caching from upstream if needed. diff --git a/internal/handler/nuget_cooldown.go b/internal/handler/nuget_cooldown.go index cdf0bc60..27e5b394 100644 --- a/internal/handler/nuget_cooldown.go +++ b/internal/handler/nuget_cooldown.go @@ -7,7 +7,6 @@ import ( "context" "crypto/sha256" "encoding/json" - "encoding/json/jsontext" "errors" "fmt" "io" @@ -16,17 +15,34 @@ import ( "slices" "strings" "time" + + "github.com/git-pkgs/proxy/internal/metadata/nuget" ) -var nugetRegistrationPrefixes = []string{ - "/v3/registration5-semver1/", - "/v3/registration5-gz-semver1/", - "/v3/registration5-gz-semver2/", -} +var nugetRegistrationPrefixes = nuget.RegistrationPrefixes + +const nugetRegistrationPath = nuget.RegistrationPath + +// nugetTimes is what decides which versions of a registration are in +// cooldown (see nuget.Times). +type nugetTimes = nuget.Times -var nugetArtifactPrefixes = append([]string{"/v3-flatcontainer/"}, nugetRegistrationPrefixes...) +// nugetFlushSize is how much of a registration that isn't filtered is +// collected before it is written out. +const nugetFlushSize = nuget.FlushSize -const nugetRegistrationPath = "/v3/registration5-gz-semver2/" +// metadataOptions returns the inputs of the nuget transformations, with +// cooldown evaluated now. +func (h *NuGetHandler) metadataOptions() nuget.Options { + o := nuget.Options{UpstreamURL: h.upstreamURL, ProxyURL: h.proxyURL, EvaluatedAt: time.Now()} + if h.proxy != nil { + o.Cooldown = h.proxy.cooldown() + o.OnWithheld = func(id, version string, publishedAt time.Time) { + h.proxy.recordWithheld("nuget", id, version, publishedAt) + } + } + return o +} func (h *NuGetHandler) cooldownEnabled() bool { return h.proxy.Cooldown != nil && h.proxy.Cooldown.Enabled() @@ -41,7 +57,7 @@ func (h *NuGetHandler) nugetCooldownApplies(id string) bool { func (h *NuGetHandler) nugetMetadata(ctx context.Context, path string) (map[string]any, error) { var document map[string]any err := h.readNuGetMetadata(ctx, path, func(body []byte) (err error) { - document, err = decodeNuGetDocument(body) + document, err = nuget.DecodeDocument(body) return err }) if err != nil { @@ -77,49 +93,6 @@ func (h *NuGetHandler) readNuGetMetadata(ctx context.Context, path string, decod return err } -func decodeNuGetDocument(body []byte) (map[string]any, error) { - var document map[string]any - if err := json.Unmarshal(body, &document); err != nil { - return nil, fmt.Errorf("parsing NuGet metadata: %w", err) - } - if document == nil { - return nil, fmt.Errorf("empty NuGet metadata") - } - return document, nil -} - -// nugetTimes holds the members of a registration index, page or leaf that -// decide which versions are in cooldown. Reading only them skips nearly all of -// a registration. -type nugetTimes struct { - // ID is the node's link. It is kept for the pages of an index only. - ID string - Version string - Published string - CatalogEntry nugetCatalogTimes - // CatalogLink is the catalogEntry of a standalone leaf, a link. - CatalogLink string - // Items is nil unless the node has an items array. - Items []nugetTimes -} - -// nugetCatalogTimes is the catalogEntry of a registration leaf. It stays unset -// unless the entry is an object: standalone leaves carry a link there. -type nugetCatalogTimes struct { - set bool - version string - published string -} - -// release returns the version and publish time of a leaf. A leaf embedded in a -// page carries them in catalogEntry, a standalone leaf at its root. -func (t *nugetTimes) release() (version, published string) { - if t.CatalogEntry.set { - return t.CatalogEntry.version, t.CatalogEntry.published - } - return t.Version, t.Published -} - func (h *NuGetHandler) nugetTimesMetadata(ctx context.Context, path string) (*nugetTimes, error) { document, _, err := h.nugetTimesDocument(ctx, path) return document, err @@ -143,148 +116,10 @@ func (h *NuGetHandler) nugetTimesDocument(ctx context.Context, path string) (*nu return document, body, nil } -// decodeNuGetTimes reads a registration document the way writeNuGetRegistration -// copies it, so that what is decided here holds for what is written there: -// with the same decoder, members by their exact names, and a member of an -// unexpected type left empty. A node that has one of these members twice is -// refused, as which of the two counts would be the reader's choice. +// decodeNuGetTimes reads a registration document the way +// writeNuGetRegistration copies it (see nuget.DecodeTimes). func decodeNuGetTimes(body []byte) (*nugetTimes, error) { - dec := newNuGetDecoder(body) - if dec.PeekKind() == 'n' { - return nil, fmt.Errorf("empty NuGet metadata") - } - document := &nugetTimes{} - var scratch []byte - var err error - if dec.PeekKind() == '{' { - err = document.decode(dec, 0, &scratch) - } else if _, err = dec.ReadValue(); err == nil { - err = errors.New("not an object") - } - if err == nil { - // Nothing may follow the document. - if _, err = dec.ReadToken(); errors.Is(err, io.EOF) { - return document, nil - } else if err == nil { - err = errors.New("data after the document") - } - } - return nil, fmt.Errorf("parsing NuGet metadata: %w", err) -} - -// decode reads the node dec is at, which is depth levels below the document. -func (t *nugetTimes) decode(dec *jsontext.Decoder, depth int, scratch *[]byte) error { - if _, err := dec.ReadToken(); err != nil { - return err - } - seen := 0 - for dec.PeekKind() != '}' { - kind, err := readNuGetMember(dec, &seen, scratch) - if err != nil { - return err - } - switch value := dec.PeekKind(); { - case kind == nugetMemberItems && value == '[': - err = t.decodeItems(dec, depth, scratch) - case kind == nugetMemberCatalogEntry && value == '{': - err = t.CatalogEntry.decode(dec, scratch) - case kind == nugetMemberCatalogEntry && value == '"' && depth == 0: - t.CatalogLink, err = readNuGetString(dec, scratch) - case kind == nugetMemberID && value == '"' && depth == 1: - t.ID, err = readNuGetString(dec, scratch) - case kind == nugetMemberVersion && value == '"': - t.Version, err = readNuGetString(dec, scratch) - case kind == nugetMemberPublished && value == '"': - t.Published, err = readNuGetString(dec, scratch) - default: - err = dec.SkipValue() - } - if err != nil { - return err - } - } - _, err := dec.ReadToken() - return err -} - -// decodeItems reads the items array dec is at. A child that is not an object -// is an empty node. -func (t *nugetTimes) decodeItems(dec *jsontext.Decoder, depth int, scratch *[]byte) error { - if _, err := dec.ReadToken(); err != nil { - return err - } - t.Items = []nugetTimes{} - for dec.PeekKind() != ']' { - t.Items = append(t.Items, nugetTimes{}) - var err error - if dec.PeekKind() == '{' { - err = t.Items[len(t.Items)-1].decode(dec, depth+1, scratch) - } else { - err = dec.SkipValue() - } - if err != nil { - return err - } - } - _, err := dec.ReadToken() - return err -} - -func (e *nugetCatalogTimes) decode(dec *jsontext.Decoder, scratch *[]byte) error { - if _, err := dec.ReadToken(); err != nil { - return err - } - e.set = true - seen := 0 - for dec.PeekKind() != '}' { - kind, err := readNuGetMember(dec, &seen, scratch) - if err != nil { - return err - } - switch value := dec.PeekKind(); { - case kind == nugetMemberVersion && value == '"': - e.version, err = readNuGetString(dec, scratch) - case kind == nugetMemberPublished && value == '"': - e.published, err = readNuGetString(dec, scratch) - default: - err = dec.SkipValue() - } - if err != nil { - return err - } - } - _, err := dec.ReadToken() - return err -} - -// nugetDecidingMembers are the members that decide what a node is and whether -// its release is in cooldown. -const nugetDecidingMembers = 1<= 24*time.Hour} +} + +var evaluatedAt = time.Date(2026, 3, 10, 12, 0, 0, 0, time.UTC) + +const ( + upstream = "https://api.nuget.example" + proxy = "https://proxy.example" +) + +type withheldVersion struct { + id, version string + at time.Time +} + +func testOptions(policy CooldownPolicy, withheld *[]withheldVersion) Options { + o := Options{UpstreamURL: upstream, ProxyURL: proxy, Cooldown: policy, EvaluatedAt: evaluatedAt} + if withheld != nil { + o.OnWithheld = func(id, version string, at time.Time) { + *withheld = append(*withheld, withheldVersion{id, version, at}) + } + } + return o +} + +func TestServiceURL(t *testing.T) { + tests := map[string]string{ + "PackageBaseAddress/3.0.0": proxy + "/nuget/v3-flatcontainer/", + "RegistrationsBaseUrl": proxy + "/nuget/v3/registration5-semver1/", + "RegistrationsBaseUrl/3.0.0-rc": proxy + "/nuget/v3/registration5-semver1/", + "RegistrationsBaseUrl/3.4.0": proxy + "/nuget/v3/registration5-gz-semver1/", + "RegistrationsBaseUrl/3.6.0": proxy + "/nuget/v3/registration5-gz-semver2/", + "RegistrationsBaseUrl/Versioned": proxy + "/nuget/v3/registration5-gz-semver2/", + "SearchQueryService/3.5.0": proxy + "/nuget/query", + "SearchAutocompleteService/3.5.0": proxy + "/nuget/autocomplete", + "PackagePublish/2.0.0": "https://other.example/publish", + "": "https://other.example/publish", + } + for serviceType, want := range tests { + if got := ServiceURL(proxy, "https://other.example/publish", serviceType); got != want { + t.Errorf("ServiceURL(%q) = %q, want %q", serviceType, got, want) + } + } +} + +func TestRewriteServiceIndex(t *testing.T) { + body := []byte(`{"version":"3.0.0","resources":[ + {"@id":"https://api.nuget.example/v3-flatcontainer/","@type":"PackageBaseAddress/3.0.0"}, + {"@id":"https://publish.example/","@type":"PackagePublish/2.0.0"}, + {"@type":"SearchQueryService"}, + "not an object"]}`) + out, err := RewriteServiceIndex(body, proxy) + if err != nil { + t.Fatal(err) + } + var index struct { + Version string `json:"version"` + Resources []any `json:"resources"` + } + if err := json.Unmarshal(out, &index); err != nil { + t.Fatal(err) + } + if index.Version != "3.0.0" || len(index.Resources) != 4 { + t.Fatalf("index = %s", out) + } + ids := []string{} + for _, r := range index.Resources[:3] { + id, _ := r.(map[string]any)["@id"].(string) + ids = append(ids, id) + } + want := []string{proxy + "/nuget/v3-flatcontainer/", "https://publish.example/", ""} + for i := range want { + if ids[i] != want[i] { + t.Errorf("resource %d @id = %q, want %q", i, ids[i], want[i]) + } + } + + noResources := []byte(`{"version": "3.0.0"}`) + if out, err := RewriteServiceIndex(noResources, proxy); err != nil || !bytes.Equal(out, noResources) { + t.Errorf("index without resources = %s, %v; want it unchanged", out, err) + } + if _, err := RewriteServiceIndex([]byte(`{`), proxy); err == nil { + t.Error("invalid index: no error") + } +} + +func TestDecodeDocument(t *testing.T) { + if _, err := DecodeDocument([]byte(`null`)); err == nil { + t.Error("null document: no error") + } + if _, err := DecodeDocument([]byte(`[`)); err == nil { + t.Error("invalid document: no error") + } + if doc, err := DecodeDocument([]byte(`{"versions":[]}`)); err != nil || doc["versions"] == nil { + t.Errorf("DecodeDocument = %v, %v", doc, err) + } +} + +func TestVersionKeyAndUnlistedTime(t *testing.T) { + if got := VersionKey("1.0.0-Beta+build.5"); got != "1.0.0-beta" { + t.Errorf("VersionKey = %q", got) + } + if !UnlistedTime("1900-01-01T00:00:00+00:00") { + t.Error("1900 is not unlisted") + } + if UnlistedTime("2026-01-01T00:00:00Z") || UnlistedTime("not a time") { + t.Error("a listed or invalid time is unlisted") + } +} + +func TestPublishedAllowed(t *testing.T) { + policy := &dayPolicy{} + var withheld []withheldVersion + o := testOptions(policy, &withheld) + + recent := evaluatedAt.Add(-time.Hour).Format(time.RFC3339) + old := evaluatedAt.Add(-48 * time.Hour).Format(time.RFC3339) + if o.PublishedAllowed("Acme.Tool", "2.0.0-RC+meta", recent) { + t.Error("recent version allowed") + } + if !o.PublishedAllowed("Acme.Tool", "1.0.0", old) { + t.Error("old version held back") + } + if !o.PublishedAllowed("Acme.Tool", "3.0.0", "") || !o.PublishedAllowed("Acme.Tool", "3.0.0", "yesterday") { + t.Error("version without a valid time held back") + } + want := []withheldVersion{{"acme.tool", "2.0.0-rc", evaluatedAt.Add(-time.Hour)}} + if len(withheld) != 1 || withheld[0] != want[0] { + t.Errorf("withheld = %v, want %v", withheld, want) + } + for i, at := range policy.evaluatedAt { + if !at.Equal(evaluatedAt) { + t.Errorf("evaluation %d at %v, want %v", i, at, evaluatedAt) + } + } + if len(policy.purls) == 0 || policy.purls[0] != "nuget pkg:nuget/acme.tool" { + t.Errorf("evaluated %v", policy.purls) + } + + // Without a policy and without a callback, everything is let through + // and nothing reported. + if !testOptions(nil, nil).PublishedAllowed("Acme.Tool", "2.0.0", recent) { + t.Error("no policy: version held back") + } + if testOptions(policy, nil).PublishedAllowed("Acme.Tool", "2.0.0", recent) { + t.Error("no callback: recent version allowed") + } +} + +func TestCollectBlocked(t *testing.T) { + recent := evaluatedAt.Add(-time.Hour).Format(time.RFC3339) + old := evaluatedAt.Add(-48 * time.Hour).Format(time.RFC3339) + document := &Times{Items: []Times{ + {Items: []Times{ + {CatalogEntry: CatalogTimes{set: true, version: "1.0.0", published: old}}, + {CatalogEntry: CatalogTimes{set: true, version: "2.0.0+Build", published: recent}}, + }}, + {Version: "3.0.0-Beta", Published: recent}, + // A node without a version blocks nothing. + {Published: recent}, + }} + blocked := map[string]bool{} + testOptions(&dayPolicy{}, nil).CollectBlocked(document, "Acme", blocked) + if len(blocked) != 2 || !blocked["2.0.0"] || !blocked["3.0.0-beta"] { + t.Errorf("blocked = %v", blocked) + } +} + +func TestFilterVersions(t *testing.T) { + document := map[string]any{"versions": []any{"1.0.0", "2.0.0-Beta", "3.0.0+build"}} + if err := FilterVersions(document, map[string]bool{"2.0.0-beta": true, "3.0.0": true}); err != nil { + t.Fatal(err) + } + if got := document["versions"].([]any); len(got) != 1 || got[0] != "1.0.0" { + t.Errorf("versions = %v", got) + } + if err := FilterVersions(map[string]any{}, nil); err == nil { + t.Error("no versions: no error") + } + if err := FilterVersions(map[string]any{"versions": []any{1}}, nil); err == nil { + t.Error("non-string version: no error") + } +} + +func TestRegistrationPaths(t *testing.T) { + ids := map[string]string{ + "/v3/registration5-gz-semver2/acme.tool/index.json": "acme.tool", + "/v3/registration5-semver1/acme.tool/1.0.0.json": "acme.tool", + "/v3-flatcontainer/acme.tool/index.json": "", + } + for path, want := range ids { + if got := RegistrationID(path); got != want { + t.Errorf("RegistrationID(%q) = %q, want %q", path, got, want) + } + } + versions := map[string]string{ + "/v3/registration5-gz-semver2/acme.tool/1.0.0.json": "1.0.0", + "/v3/registration5-gz-semver2/acme.tool/index.json": "", + "/v3/registration5-gz-semver2/acme.tool/page/1.json": "", + "/v3/registration5-gz-semver2/acme.tool/.json": "", + "/v3/registration5-gz-semver2/acme.tool/1.0.0": "", + "/v3-flatcontainer/acme.tool/1.0.0.json": "", + } + for path, want := range versions { + if got := RegistrationLeafVersion(path); got != want { + t.Errorf("RegistrationLeafVersion(%q) = %q, want %q", path, got, want) + } + } +} + +func TestLinks(t *testing.T) { + o := Options{UpstreamURL: upstream + "/base", ProxyURL: proxy} + links := map[string]string{ + upstream + "/base/v3-flatcontainer/a/1.0.0/a.1.0.0.nupkg": proxy + "/nuget/v3-flatcontainer/a/1.0.0/a.1.0.0.nupkg", + upstream + "/base/v3/registration5-semver1/a/index.json?x=1#f": proxy + "/nuget/v3/registration5-semver1/a/index.json?x=1#f", + "https://elsewhere.example/v3-flatcontainer/a/index.json": proxy + "/nuget/v3-flatcontainer/a/index.json", + // The upstream's base path is only taken off links to its host. + "https://elsewhere.example/base/v3-flatcontainer/a/index.json": "https://elsewhere.example/base/v3-flatcontainer/a/index.json", + upstream + "/base/v3/catalog0/data/a.json": upstream + "/base/v3/catalog0/data/a.json", + "://bad": "://bad", + } + for link, want := range links { + if got := o.ProxyLink(link); got != want { + t.Errorf("ProxyLink(%q) = %q, want %q", link, got, want) + } + } + if got := (Options{UpstreamURL: "://bad", ProxyURL: proxy}).ProxyLink(upstream + "/v3-flatcontainer/a"); got != upstream+"/v3-flatcontainer/a" { + t.Errorf("ProxyLink with a bad upstream = %q", got) + } + + catalog := map[string]string{ + upstream + "/base/v3/catalog0/data/a.json": "/v3/catalog0/data/a.json", + "http://api.nuget.example/base/v3/catalog0/a": "", + "https://other.example/base/v3/catalog0/a": "", + upstream + "/elsewhere/v3/catalog0/a": "", + upstream + "/base/v3/../../secret": "", + upstream + "/base/v3/%2e%2e/secret": "", + upstream + "/base/v3/%252e%252e/secret": "", + upstream + "/base/v3/..%5Csecret": "", + upstream + "/base/v3/catalog0/a?x=1": "", + upstream + "/base/v3/catalog0/a#f": "", + } + for link, want := range catalog { + got, ok := o.CatalogPath(link) + if got != want || ok != (want != "") { + t.Errorf("CatalogPath(%q) = %q, %v; want %q", link, got, ok, want) + } + } + + index := "/v3/registration5-gz-semver2/a/index.json" + if got, err := o.RegistrationPagePath(index, upstream+"/base/v3/registration5-gz-semver2/a/page/1.0.0/2.0.0.json"); err != nil || got != "/v3/registration5-gz-semver2/a/page/1.0.0/2.0.0.json" { + t.Errorf("RegistrationPagePath = %q, %v", got, err) + } + if got, err := o.RegistrationPagePath(index, "page/1.json"); err != nil || got != "/v3/registration5-gz-semver2/a/page/1.json" { + t.Errorf("relative RegistrationPagePath = %q, %v", got, err) + } + for _, link := range []string{"page/../index.json", "index.json", "page/1.json?x=1", "page/1.json#x", + "https://other.example/base/v3/registration5-gz-semver2/a/page/1.json", "../b/page/1.json"} { + if got, err := o.RegistrationPagePath(index, link); err == nil { + t.Errorf("RegistrationPagePath(%q) = %q, want an error", link, got) + } + } +} + +func TestDecodeTimes(t *testing.T) { + doc, err := DecodeTimes([]byte(`{"@id":"x","items":[{"@id":"` + upstream + `/v3/registration5-gz-semver2/a/page/1.json","items":[ + {"catalogEntry":{"version":"1.0.0","published":"2026-01-01T00:00:00Z"}}]}]}`)) + if err != nil { + t.Fatal(err) + } + if doc.ID != "" || len(doc.Items) != 1 || doc.Items[0].ID == "" { + t.Errorf("only page links are kept: %+v", doc) + } + if v, p := doc.Items[0].Items[0].Release(); v != "1.0.0" || p != "2026-01-01T00:00:00Z" { + t.Errorf("Release = %q, %q", v, p) + } + leaf, err := DecodeTimes([]byte(`{"catalogEntry":"` + upstream + `/v3/catalog0/a.json","published":"1900-01-01T00:00:00Z"}`)) + if err != nil || leaf.CatalogLink == "" { + t.Errorf("standalone leaf = %+v, %v", leaf, err) + } + if v, p := leaf.Release(); v != "" || p != "1900-01-01T00:00:00Z" { + t.Errorf("leaf Release = %q, %q", v, p) + } + for _, body := range []string{`null`, `[]`, `{"version":"1","version":"2"}`, `{} {}`, `{`} { + if _, err := DecodeTimes([]byte(body)); err == nil { + t.Errorf("DecodeTimes(%s): no error", body) + } + } +} + +// registration is an index with one inlined page of three leaves, the +// newest published an hour before evaluatedAt. +func registration() string { + leaf := func(version, published string) string { + return `{"@id":"` + upstream + `/v3/registration5-gz-semver2/acme/` + version + `.json", + "catalogEntry":{"version":"` + version + `","published":"` + published + `"}, + "packageContent":"` + upstream + `/v3-flatcontainer/acme/` + version + `/acme.` + version + `.nupkg"}` + } + old := evaluatedAt.Add(-72 * time.Hour).Format(time.RFC3339) + recent := evaluatedAt.Add(-time.Hour).Format(time.RFC3339) + return `{"@id":"` + upstream + `/v3/registration5-gz-semver2/acme/index.json","count":1,"items":[ + {"@id":"` + upstream + `/v3/registration5-gz-semver2/acme/index.json#page/1.0.0/3.0.0", + "count":3,"lower":"1.0.0","upper":"3.0.0","items":[` + + leaf("1.0.0", old) + `,` + leaf("2.0.0", old) + `,` + leaf("3.0.0", recent) + `]}]}` +} + +func TestWriteRegistrationFilters(t *testing.T) { + var withheld []withheldVersion + var out bytes.Buffer + if err := WriteRegistration(&out, []byte(registration()), "Acme", true, nil, testOptions(&dayPolicy{}, &withheld)); err != nil { + t.Fatal(err) + } + var doc struct { + ID string `json:"@id"` + Count int `json:"count"` + Items []struct { + Count int `json:"count"` + Lower string `json:"lower"` + Upper string `json:"upper"` + Items []struct { + PackageContent string `json:"packageContent"` + } `json:"items"` + } `json:"items"` + } + if err := json.Unmarshal(out.Bytes(), &doc); err != nil { + t.Fatalf("%v: %s", err, out.Bytes()) + } + if !strings.HasPrefix(doc.ID, proxy+"/nuget/v3/") { + t.Errorf("@id = %q", doc.ID) + } + page := doc.Items[0] + if doc.Count != 1 || page.Count != 2 || page.Lower != "1.0.0" || page.Upper != "2.0.0" || len(page.Items) != 2 { + t.Errorf("filtered registration = %s", out.Bytes()) + } + if want := proxy + "/nuget/v3-flatcontainer/acme/2.0.0/acme.2.0.0.nupkg"; page.Items[1].PackageContent != want { + t.Errorf("packageContent = %q, want %q", page.Items[1].PackageContent, want) + } + if len(withheld) != 1 || withheld[0].version != "3.0.0" || withheld[0].id != "acme" { + t.Errorf("withheld = %v", withheld) + } +} + +func TestWriteRegistrationWithoutFilter(t *testing.T) { + var out bytes.Buffer + if err := WriteRegistration(&out, []byte(registration()), "Acme", false, nil, testOptions(&dayPolicy{}, nil)); err != nil { + t.Fatal(err) + } + if strings.Contains(out.String(), upstream+"/v3") { + t.Errorf("upstream link left: %s", out.Bytes()) + } + if n := strings.Count(out.String(), `"catalogEntry"`); n != 3 { + t.Errorf("%d leaves copied, want 3", n) + } +} + +func TestWriteRegistrationInlinesLinkedPages(t *testing.T) { + pageLink := upstream + "/v3/registration5-gz-semver2/acme/page/1.0.0/3.0.0.json" + index := `{"count":1,"items":[{"@id":"` + pageLink + `","count":3,"lower":"1.0.0","upper":"3.0.0"}]}` + full := registration() + page := full[strings.Index(full, `{"@id":"`+upstream+`/v3/registration5-gz-semver2/acme/index.json#page`):strings.LastIndex(full, "]}")] + var out bytes.Buffer + err := WriteRegistration(&out, []byte(index), "acme", true, map[string][]byte{pageLink: []byte(page)}, testOptions(&dayPolicy{}, nil)) + if err != nil { + t.Fatal(err) + } + if n := strings.Count(out.String(), `"catalogEntry"`); n != 2 || !strings.Contains(out.String(), `"count":2`) { + t.Errorf("inlined page = %s", out.Bytes()) + } + if err := WriteRegistration(&bytes.Buffer{}, []byte(index), "acme", true, map[string][]byte{}, testOptions(&dayPolicy{}, nil)); err == nil { + t.Error("page not loaded: no error") + } +} diff --git a/internal/handler/nuget_registration.go b/internal/metadata/nuget/registration.go similarity index 68% rename from internal/handler/nuget_registration.go rename to internal/metadata/nuget/registration.go index e32273ff..f98d5b1d 100644 --- a/internal/handler/nuget_registration.go +++ b/internal/metadata/nuget/registration.go @@ -1,4 +1,4 @@ -package handler +package nuget import ( "bytes" @@ -10,49 +10,49 @@ import ( "strings" ) -// nugetFlushSize is how much of a document that isn't filtered is collected +// FlushSize is how much of a document that isn't filtered is collected // before it is written out. -const nugetFlushSize = 32 << 10 +const FlushSize = 32 << 10 // The members of a registration document that are read or rewritten. const ( - nugetMemberOther = iota - nugetMemberID - nugetMemberLink - nugetMemberItems - nugetMemberCount - nugetMemberLower - nugetMemberUpper - nugetMemberCatalogEntry - nugetMemberVersion - nugetMemberPublished + memberOther = iota + memberID + memberLink + memberItems + memberCount + memberLower + memberUpper + memberCatalogEntry + memberVersion + memberPublished ) -func nugetMemberKind(name []byte) int { +func memberKind(name []byte) int { switch string(name) { case "@id": - return nugetMemberID + return memberID case "parent", "registration", "packageContent": - return nugetMemberLink + return memberLink case "items": - return nugetMemberItems + return memberItems case "count": - return nugetMemberCount + return memberCount case "lower": - return nugetMemberLower + return memberLower case "upper": - return nugetMemberUpper + return memberUpper case "catalogEntry": - return nugetMemberCatalogEntry + return memberCatalogEntry case "version": - return nugetMemberVersion + return memberVersion case "published": - return nugetMemberPublished + return memberPublished } - return nugetMemberOther + return memberOther } -// nugetRegistrationWriter copies a registration index, page or leaf with its +// registrationWriter copies a registration index, page or leaf with its // links pointing at the proxy. With filter set it leaves out the leaves in // cooldown and the pages that end up empty, and corrects the counts and // bounds of the rest, as it goes: the document is never held as a tree. @@ -60,8 +60,8 @@ func nugetMemberKind(name []byte) int { // A document is made of nodes. A node with an items array is the index or a // page, and the objects in that array are its nodes in turn; any other node // is a leaf. Everything else is copied with its upstream bytes. -type nugetRegistrationWriter struct { - h *NuGetHandler +type registrationWriter struct { + o Options id string filter bool // pages holds the pages an index links to, by link. It is nil unless the @@ -81,18 +81,18 @@ type nugetRegistrationWriter struct { proxyPrefix []byte } -// nugetLinkProbe is a path that nugetProxyLink rewrites. -const nugetLinkProbe = "/v3-flatcontainer/" +// linkProbe is a path that ProxyLink rewrites. +const linkProbe = "/v3-flatcontainer/" // setLinkPrefixes prepares rewriting plain links without parsing them. Nearly // every link of a registration is one, and parsing each as a URL allocates // more than the rest of the copy does. -func (rw *nugetRegistrationWriter) setLinkPrefixes() { - upstream := rw.h.upstreamURL +func (rw *registrationWriter) setLinkPrefixes() { + upstream := rw.o.UpstreamURL if strings.ContainsAny(upstream, "?#") { return } - proxied, ok := strings.CutSuffix(rw.h.nugetProxyLink(upstream+nugetLinkProbe), nugetLinkProbe) + proxied, ok := strings.CutSuffix(rw.o.ProxyLink(upstream+linkProbe), linkProbe) if !ok { return } @@ -104,23 +104,23 @@ func (rw *nugetRegistrationWriter) setLinkPrefixes() { rw.proxyPrefix = quoted[:len(quoted)-1] } -// nugetArtifactPrefixBytes is nugetArtifactPrefixes for matching in a document. -var nugetArtifactPrefixBytes = func() [][]byte { - prefixes := make([][]byte, len(nugetArtifactPrefixes)) - for i, prefix := range nugetArtifactPrefixes { +// artifactPrefixBytes is ArtifactPrefixes for matching in a document. +var artifactPrefixBytes = func() [][]byte { + prefixes := make([][]byte, len(ArtifactPrefixes)) + for i, prefix := range ArtifactPrefixes { prefixes[i] = []byte(prefix) } return prefixes }() -// nugetLinkIsForeign reports whether a link can't be to a NuGet resource, so -// that nugetProxyLink leaves it alone: its path names none, however the link +// linkIsForeign reports whether a link can't be to a NuGet resource, so +// that ProxyLink leaves it alone: its path names none, however the link // parses. An escaped link is not judged here. -func nugetLinkIsForeign(link []byte) bool { +func linkIsForeign(link []byte) bool { if bytes.IndexByte(link, '%') >= 0 { return false } - for _, prefix := range nugetArtifactPrefixBytes { + for _, prefix := range artifactPrefixBytes { if bytes.Contains(link, prefix) { return false } @@ -128,15 +128,15 @@ func nugetLinkIsForeign(link []byte) bool { return true } -// plainLinkPath returns the path of a link that nugetProxyLink rewrites to +// plainLinkPath returns the path of a link that ProxyLink rewrites to // the same path below the proxy: one on the upstream, to a NuGet resource, // with nothing in it that a URL or JSON would encode. -func (rw *nugetRegistrationWriter) plainLinkPath(link []byte) ([]byte, bool) { +func (rw *registrationWriter) plainLinkPath(link []byte) ([]byte, bool) { if rw.proxyPrefix == nil { return nil, false } path, ok := bytes.CutPrefix(link, rw.upstreamPrefix) - if !ok || !slices.ContainsFunc(nugetArtifactPrefixBytes, func(prefix []byte) bool { return bytes.HasPrefix(path, prefix) }) { + if !ok || !slices.ContainsFunc(artifactPrefixBytes, func(prefix []byte) bool { return bytes.HasPrefix(path, prefix) }) { return nil, false } for _, c := range path { @@ -149,9 +149,9 @@ func (rw *nugetRegistrationWriter) plainLinkPath(link []byte) ([]byte, bool) { } // writeLink writes a link, given as a JSON string, pointing at the proxy. -func (rw *nugetRegistrationWriter) writeLink(raw []byte) { +func (rw *registrationWriter) writeLink(raw []byte) { link := rw.unquote(raw) - if nugetLinkIsForeign(link) { + if linkIsForeign(link) { rw.buf.Write(raw) return } @@ -162,26 +162,26 @@ func (rw *nugetRegistrationWriter) writeLink(raw []byte) { return } original := string(link) - if proxied := rw.h.nugetProxyLink(original); proxied != original { + if proxied := rw.o.ProxyLink(original); proxied != original { rw.text, _ = jsontext.AppendQuote(rw.text[:0], proxied) raw = rw.text } rw.buf.Write(raw) } -// nugetRelease is what an object says about the release it describes. -type nugetRelease struct { +// releaseInfo is what an object says about the release it describes. +type releaseInfo struct { link string version []byte // as JSON, nil when there is none published string } -// nugetNode is the state of the node being copied. -type nugetNode struct { +// nodeState is the state of the node being copied. +type nodeState struct { depth int wrote bool // a member has been written - own nugetRelease - entry nugetRelease + own releaseInfo + entry releaseInfo hasEntry bool container bool kept int @@ -192,19 +192,25 @@ type nugetNode struct { count, lower, upper []byte } -func newNuGetDecoder(document []byte) *jsontext.Decoder { +func newDecoder(document []byte) *jsontext.Decoder { // A bytes.Buffer is parsed in place. Duplicate names and invalid UTF-8 // are accepted as encoding/json accepts them. return jsontext.NewDecoder(bytes.NewBuffer(document), jsontext.AllowDuplicateNames(true), jsontext.AllowInvalidUTF8(true)) } -// writeNuGetRegistration writes the registration document to w. The document -// and pages must have been decoded before, so that it only fails once the -// response has started if writing does. -func (h *NuGetHandler) writeNuGetRegistration(w io.Writer, document []byte, id string, filter bool, pages map[string][]byte) error { - rw := &nugetRegistrationWriter{h: h, id: id, filter: filter, pages: pages, out: w} +// WriteRegistration copies the registration index, page or leaf document to +// w with its links pointing at the proxy (Options.ProxyLink). With filter +// set it leaves out the leaves cooldown holds back, by +// Options.PublishedAllowed, and the pages that end up empty, and corrects +// the counts and bounds of the rest. pages holds the pages an index links +// to, by link, for an index whose linked pages are to be inlined, and is +// nil otherwise. The document and pages must have been read with +// DecodeTimes before, so that it only fails once w has been written to if +// writing does. +func WriteRegistration(w io.Writer, document []byte, id string, filter bool, pages map[string][]byte, o Options) error { + rw := ®istrationWriter{o: o, id: id, filter: filter, pages: pages, out: w} rw.setLinkPrefixes() - dec := newNuGetDecoder(document) + dec := newDecoder(document) var err error if filter { _, _, err = rw.node(dec, 0) @@ -217,19 +223,19 @@ func (h *NuGetHandler) writeNuGetRegistration(w io.Writer, document []byte, id s return rw.flush() } -func (rw *nugetRegistrationWriter) flush() error { +func (rw *registrationWriter) flush() error { _, err := rw.out.Write(rw.buf.Bytes()) rw.buf.Reset() return err } // unquote returns the text of a JSON string. It is valid until the next call. -func (rw *nugetRegistrationWriter) unquote(raw []byte) []byte { - return nugetUnquote(&rw.text, raw) +func (rw *registrationWriter) unquote(raw []byte) []byte { + return unquote(&rw.text, raw) } -// nugetUnquote returns the text of a JSON string, in raw or in scratch. -func nugetUnquote(scratch *[]byte, raw []byte) []byte { +// unquote returns the text of a JSON string, in raw or in scratch. +func unquote(scratch *[]byte, raw []byte) []byte { if bytes.IndexByte(raw, '\\') < 0 { return raw[1 : len(raw)-1] } @@ -240,17 +246,17 @@ func nugetUnquote(scratch *[]byte, raw []byte) []byte { } // readName reads the name of the next member and keeps it for writeName. -func (rw *nugetRegistrationWriter) readName(dec *jsontext.Decoder) (int, error) { +func (rw *registrationWriter) readName(dec *jsontext.Decoder) (int, error) { raw, err := dec.ReadValue() if err != nil { - return nugetMemberOther, err + return memberOther, err } rw.name = append(rw.name[:0], raw...) - return nugetMemberKind(rw.unquote(raw)), nil + return memberKind(rw.unquote(raw)), nil } // writeName writes the name read last, or name when it is not empty. -func (rw *nugetRegistrationWriter) writeName(wrote *bool, name string) { +func (rw *registrationWriter) writeName(wrote *bool, name string) { if *wrote { rw.buf.WriteByte(',') } @@ -264,7 +270,7 @@ func (rw *nugetRegistrationWriter) writeName(wrote *bool, name string) { } // value copies the value dec is at, rewriting the links in it. -func (rw *nugetRegistrationWriter) value(dec *jsontext.Decoder) error { +func (rw *registrationWriter) value(dec *jsontext.Decoder) error { switch dec.PeekKind() { case '{': return rw.object(dec, nil) @@ -279,7 +285,7 @@ func (rw *nugetRegistrationWriter) value(dec *jsontext.Decoder) error { return nil } -func (rw *nugetRegistrationWriter) array(dec *jsontext.Decoder) error { +func (rw *registrationWriter) array(dec *jsontext.Decoder) error { if _, err := dec.ReadToken(); err != nil { return err } @@ -299,7 +305,7 @@ func (rw *nugetRegistrationWriter) array(dec *jsontext.Decoder) error { // object copies the object dec is at, rewriting the links in it. release, // when not nil, receives what the object says about its release. -func (rw *nugetRegistrationWriter) object(dec *jsontext.Decoder, release *nugetRelease) error { +func (rw *registrationWriter) object(dec *jsontext.Decoder, release *releaseInfo) error { if _, err := dec.ReadToken(); err != nil { return err } @@ -316,7 +322,7 @@ func (rw *nugetRegistrationWriter) object(dec *jsontext.Decoder, release *nugetR } // Nothing written so far can be cut off again unless nodes are // filtered, so only then does the output wait for the node to end. - if !rw.filter && rw.buf.Len() >= nugetFlushSize { + if !rw.filter && rw.buf.Len() >= FlushSize { if err := rw.flush(); err != nil { return err } @@ -328,8 +334,8 @@ func (rw *nugetRegistrationWriter) object(dec *jsontext.Decoder, release *nugetR } // member copies the value of a member of the given kind. -func (rw *nugetRegistrationWriter) member(dec *jsontext.Decoder, kind int, release *nugetRelease) error { - if kind == nugetMemberOther || dec.PeekKind() != '"' { +func (rw *registrationWriter) member(dec *jsontext.Decoder, kind int, release *releaseInfo) error { + if kind == memberOther || dec.PeekKind() != '"' { return rw.value(dec) } raw, err := dec.ReadValue() @@ -337,17 +343,17 @@ func (rw *nugetRegistrationWriter) member(dec *jsontext.Decoder, kind int, relea return err } switch kind { - case nugetMemberID, nugetMemberLink: - if kind == nugetMemberID && release != nil && rw.pages != nil { + case memberID, memberLink: + if kind == memberID && release != nil && rw.pages != nil { release.link = string(rw.unquote(raw)) } rw.writeLink(raw) return nil - case nugetMemberVersion: + case memberVersion: if release != nil { release.version = append(release.version[:0], raw...) } - case nugetMemberPublished: + case memberPublished: if release != nil { release.published = string(rw.unquote(raw)) } @@ -358,7 +364,7 @@ func (rw *nugetRegistrationWriter) member(dec *jsontext.Decoder, kind int, relea // node copies the index, page or leaf dec is at. It reports whether the node // is to be kept, and the version of its release as JSON. -func (rw *nugetRegistrationWriter) node(dec *jsontext.Decoder, depth int) (bool, []byte, error) { +func (rw *registrationWriter) node(dec *jsontext.Decoder, depth int) (bool, []byte, error) { if dec.PeekKind() != '{' { return false, nil, rw.value(dec) } @@ -366,7 +372,7 @@ func (rw *nugetRegistrationWriter) node(dec *jsontext.Decoder, depth int) (bool, return false, nil, err } rw.buf.WriteByte('{') - n := &nugetNode{depth: depth} + n := &nodeState{depth: depth} for dec.PeekKind() != '}' { kind, err := rw.readName(dec) if err != nil { @@ -393,19 +399,19 @@ func (rw *nugetRegistrationWriter) node(dec *jsontext.Decoder, depth int) (bool, if len(release.version) >= 2 && release.version[0] == '"' { version = string(rw.unquote(release.version)) } - return rw.h.nugetPublishedAllowed(rw.id, version, release.published), release.version, nil + return rw.o.PublishedAllowed(rw.id, version, release.published), release.version, nil } // linksPage reports whether a node at depth is a page of an index whose // linked pages are inlined. -func (rw *nugetRegistrationWriter) linksPage(depth int) bool { +func (rw *registrationWriter) linksPage(depth int) bool { return rw.pages != nil && depth == 1 } -func (rw *nugetRegistrationWriter) nodeMember(dec *jsontext.Decoder, kind int, n *nugetNode) error { +func (rw *registrationWriter) nodeMember(dec *jsontext.Decoder, kind int, n *nodeState) error { var held *[]byte switch kind { - case nugetMemberItems: + case memberItems: if dec.PeekKind() == '[' { rw.writeName(&n.wrote, "") return rw.items(dec, n) @@ -414,19 +420,19 @@ func (rw *nugetRegistrationWriter) nodeMember(dec *jsontext.Decoder, kind int, n // The leaves of the linked page take its place. return dec.SkipValue() } - case nugetMemberCatalogEntry: + case memberCatalogEntry: // A standalone leaf has a link here and its release in the leaf. if dec.PeekKind() == '{' { rw.writeName(&n.wrote, "") n.hasEntry = true - n.entry = nugetRelease{} + n.entry = releaseInfo{} return rw.object(dec, &n.entry) } - case nugetMemberCount: + case memberCount: held = &n.count - case nugetMemberLower: + case memberLower: held = &n.lower - case nugetMemberUpper: + case memberUpper: held = &n.upper } if held != nil { @@ -443,7 +449,7 @@ func (rw *nugetRegistrationWriter) nodeMember(dec *jsontext.Decoder, kind int, n // items copies the array dec is at, the children of n, without those that // are not kept. -func (rw *nugetRegistrationWriter) items(dec *jsontext.Decoder, n *nugetNode) error { +func (rw *registrationWriter) items(dec *jsontext.Decoder, n *nodeState) error { if _, err := dec.ReadToken(); err != nil { return err } @@ -490,7 +496,7 @@ func (rw *nugetRegistrationWriter) items(dec *jsontext.Decoder, n *nugetNode) er } // endNode writes what is left of a node once its members have been read. -func (rw *nugetRegistrationWriter) endNode(n *nugetNode) error { +func (rw *registrationWriter) endNode(n *nodeState) error { if rw.linksPage(n.depth) && !n.container { if err := rw.linkedItems(n); err != nil { return err @@ -500,7 +506,7 @@ func (rw *nugetRegistrationWriter) endNode(n *nugetNode) error { n.count = append(n.count[:0], strconv.Itoa(n.kept)...) // Page bounds describe the retained leaves, not versions hidden by cooldown. if n.lower != nil && n.kept > 0 { - n.lower, n.upper = nugetVersionJSON(n.first), nugetVersionJSON(n.last) + n.lower, n.upper = versionJSON(n.first), versionJSON(n.last) } } for _, held := range []struct { @@ -516,7 +522,7 @@ func (rw *nugetRegistrationWriter) endNode(n *nugetNode) error { continue } // Links are rewritten at any depth, so in here too. - if err := rw.value(newNuGetDecoder(held.value)); err != nil { + if err := rw.value(newDecoder(held.value)); err != nil { return err } } @@ -524,9 +530,9 @@ func (rw *nugetRegistrationWriter) endNode(n *nugetNode) error { return nil } -// nugetVersionJSON returns the version of a leaf as JSON. A leaf without one +// versionJSON returns the version of a leaf as JSON. A leaf without one // leaves an empty version behind, which is not always nil. -func nugetVersionJSON(version []byte) []byte { +func versionJSON(version []byte) []byte { if len(version) == 0 { return []byte("null") } @@ -535,12 +541,12 @@ func nugetVersionJSON(version []byte) []byte { // linkedItems writes the leaves of the page that n, a page of the index // without leaves of its own, links to. -func (rw *nugetRegistrationWriter) linkedItems(n *nugetNode) error { +func (rw *registrationWriter) linkedItems(n *nodeState) error { page, ok := rw.pages[n.own.link] if !ok { return fmt.Errorf("registration page %q was not loaded", n.own.link) } - dec := newNuGetDecoder(page) + dec := newDecoder(page) if _, err := dec.ReadToken(); err != nil { return err } @@ -549,7 +555,7 @@ func (rw *nugetRegistrationWriter) linkedItems(n *nugetNode) error { if err != nil { return err } - if kind != nugetMemberItems || dec.PeekKind() != '[' { + if kind != memberItems || dec.PeekKind() != '[' { err = dec.SkipValue() } else { rw.writeName(&n.wrote, "") diff --git a/internal/metadata/nuget/times.go b/internal/metadata/nuget/times.go new file mode 100644 index 00000000..1efecee1 --- /dev/null +++ b/internal/metadata/nuget/times.go @@ -0,0 +1,184 @@ +package nuget + +import ( + "encoding/json/jsontext" + "errors" + "fmt" + "io" +) + +// Times holds the members of a registration index, page or leaf that +// decide which versions are in cooldown. Reading only them skips nearly all of +// a registration. +type Times struct { + // ID is the node's link. It is kept for the pages of an index only. + ID string + Version string + Published string + CatalogEntry CatalogTimes + // CatalogLink is the catalogEntry of a standalone leaf, a link. + CatalogLink string + // Items is nil unless the node has an items array. + Items []Times +} + +// CatalogTimes is the catalogEntry of a registration leaf. It stays unset +// unless the entry is an object: standalone leaves carry a link there. +type CatalogTimes struct { + set bool + version string + published string +} + +// Release returns the version and publish time of a leaf. A leaf embedded in a +// page carries them in catalogEntry, a standalone leaf at its root. +func (t *Times) Release() (version, published string) { + if t.CatalogEntry.set { + return t.CatalogEntry.version, t.CatalogEntry.published + } + return t.Version, t.Published +} + +// DecodeTimes reads a registration document the way WriteRegistration +// copies it, so that what is decided here holds for what is written there: +// with the same decoder, members by their exact names, and a member of an +// unexpected type left empty. A node that has one of these members twice is +// refused, as which of the two counts would be the reader's choice. +func DecodeTimes(body []byte) (*Times, error) { + dec := newDecoder(body) + if dec.PeekKind() == 'n' { + return nil, fmt.Errorf("empty NuGet metadata") + } + document := &Times{} + var scratch []byte + var err error + if dec.PeekKind() == '{' { + err = document.decode(dec, 0, &scratch) + } else if _, err = dec.ReadValue(); err == nil { + err = errors.New("not an object") + } + if err == nil { + // Nothing may follow the document. + if _, err = dec.ReadToken(); errors.Is(err, io.EOF) { + return document, nil + } else if err == nil { + err = errors.New("data after the document") + } + } + return nil, fmt.Errorf("parsing NuGet metadata: %w", err) +} + +// decode reads the node dec is at, which is depth levels below the document. +func (t *Times) decode(dec *jsontext.Decoder, depth int, scratch *[]byte) error { + if _, err := dec.ReadToken(); err != nil { + return err + } + seen := 0 + for dec.PeekKind() != '}' { + kind, err := readMember(dec, &seen, scratch) + if err != nil { + return err + } + switch value := dec.PeekKind(); { + case kind == memberItems && value == '[': + err = t.decodeItems(dec, depth, scratch) + case kind == memberCatalogEntry && value == '{': + err = t.CatalogEntry.decode(dec, scratch) + case kind == memberCatalogEntry && value == '"' && depth == 0: + t.CatalogLink, err = readString(dec, scratch) + case kind == memberID && value == '"' && depth == 1: + t.ID, err = readString(dec, scratch) + case kind == memberVersion && value == '"': + t.Version, err = readString(dec, scratch) + case kind == memberPublished && value == '"': + t.Published, err = readString(dec, scratch) + default: + err = dec.SkipValue() + } + if err != nil { + return err + } + } + _, err := dec.ReadToken() + return err +} + +// decodeItems reads the items array dec is at. A child that is not an object +// is an empty node. +func (t *Times) decodeItems(dec *jsontext.Decoder, depth int, scratch *[]byte) error { + if _, err := dec.ReadToken(); err != nil { + return err + } + t.Items = []Times{} + for dec.PeekKind() != ']' { + t.Items = append(t.Items, Times{}) + var err error + if dec.PeekKind() == '{' { + err = t.Items[len(t.Items)-1].decode(dec, depth+1, scratch) + } else { + err = dec.SkipValue() + } + if err != nil { + return err + } + } + _, err := dec.ReadToken() + return err +} + +func (e *CatalogTimes) decode(dec *jsontext.Decoder, scratch *[]byte) error { + if _, err := dec.ReadToken(); err != nil { + return err + } + e.set = true + seen := 0 + for dec.PeekKind() != '}' { + kind, err := readMember(dec, &seen, scratch) + if err != nil { + return err + } + switch value := dec.PeekKind(); { + case kind == memberVersion && value == '"': + e.version, err = readString(dec, scratch) + case kind == memberPublished && value == '"': + e.published, err = readString(dec, scratch) + default: + err = dec.SkipValue() + } + if err != nil { + return err + } + } + _, err := dec.ReadToken() + return err +} + +// decidingMembers are the members that decide what a node is and whether +// its release is in cooldown. +const decidingMembers = 1<