Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions desktop/internal/core/github.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ type GitHubRequest struct {
Assignees []string `json:"assignees,omitempty"`
// Commit is the commit a check read names, as a hexadecimal SHA of at least four digits.
Commit string `json:"commit,omitempty"`
// Ref is the branch, tag or HEAD whose newest commit latestCommit looks up.
Ref string `json:"ref,omitempty"`
}

// GitHubPlan is the HTTP request Core planned: the host it goes to, the method, the path and the
Expand Down
38 changes: 35 additions & 3 deletions desktop/internal/core/marketplace.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,33 @@ func (o marketplaceOutcome) failure(command string) error {
return nil
}

// MarketplaceSource is Core's canonical index location and its optional repository.
// MarketplaceSource is Core's canonical index location and its optional repository. IndexURL is
// the source's identity; Pinned only says where the same files are at one commit.
type MarketplaceSource struct {
IndexURL string `json:"indexURL"`
RecommendationsURL string `json:"recommendationsURL"`
Repository *string `json:"repository"`
DisplayName string `json:"displayName"`
// Revision is the GitHub repository and ref a GitHub-hosted index follows; nil for any
// other source and for an index URL already at a commit.
Revision *MarketplaceRevision `json:"revision"`
// Pinned is the index and recommendations at the commit PinMarketplaceSource passed; nil
// when nothing could be pinned.
Pinned *MarketplacePinned `json:"pinned"`
}

// MarketplaceRevision is the repository and ref whose newest commit pins a source.
type MarketplaceRevision struct {
Repository GitHubRepo `json:"repository"`
Ref string `json:"ref"`
}

// MarketplacePinned is a source's files at one commit. Branch URLs on raw.githubusercontent.com
// are cached for minutes; a commit URL is not served stale.
type MarketplacePinned struct {
Commit string `json:"commit"`
IndexURL string `json:"indexURL"`
RecommendationsURL string `json:"recommendationsURL"`
}

// MarketplaceAvailability is Core's platform and capability decision.
Expand Down Expand Up @@ -115,11 +136,22 @@ type MarketplaceReview struct {

// ResolveMarketplaceSource delegates URL validation and canonicalization to Core.
func (c *Client) ResolveMarketplaceSource(ctx context.Context, url string) (MarketplaceSource, error) {
return c.resolveMarketplaceSource(ctx, url, "")
}

// PinMarketplaceSource resolves url like ResolveMarketplaceSource and adds Pinned, its files at
// commit, the newest commit of the source's Revision.
func (c *Client) PinMarketplaceSource(ctx context.Context, url, commit string) (MarketplaceSource, error) {
return c.resolveMarketplaceSource(ctx, url, commit)
}

func (c *Client) resolveMarketplaceSource(ctx context.Context, url, commit string) (MarketplaceSource, error) {
const command = "plugins.marketplace.resolveSource"
var result marketplaceOutcome
if err := c.Execute(ctx, command, struct {
URL string `json:"url"`
}{url}, &result); err != nil {
URL string `json:"url"`
Commit string `json:"commit,omitempty"`
}{url, commit}, &result); err != nil {
return MarketplaceSource{}, err
}
if err := result.failure(command); err != nil {
Expand Down
24 changes: 18 additions & 6 deletions desktop/internal/core/marketplace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"os"
"path/filepath"
"reflect"
"slices"
"testing"

Expand All @@ -26,19 +27,28 @@ func TestMarketplaceSourceFixture(t *testing.T) {
var fixture struct {
Cases []struct {
Input string `json:"input"`
Commit string `json:"commit"`
Expected struct {
IndexURL string `json:"indexURL"`
RecommendationsURL string `json:"recommendationsURL"`
DisplayName string `json:"displayName"`
IndexURL string `json:"indexURL"`
RecommendationsURL string `json:"recommendationsURL"`
DisplayName string `json:"displayName"`
Revision *MarketplaceRevision `json:"revision"`
Pinned *MarketplacePinned `json:"pinned"`
} `json:"expected"`
ExpectedCode string `json:"expectedCode"`
} `json:"cases"`
}
readMarketFixture(t, "marketplace/source-urls.json", &fixture)
client := NewClient()
for _, item := range fixture.Cases {
t.Run(item.Input, func(t *testing.T) {
source, err := client.ResolveMarketplaceSource(testContext(t), item.Input)
t.Run(item.Input+"@"+item.Commit, func(t *testing.T) {
var source MarketplaceSource
var err error
if item.Commit != "" {
source, err = client.PinMarketplaceSource(testContext(t), item.Input, item.Commit)
} else {
source, err = client.ResolveMarketplaceSource(testContext(t), item.Input)
}
if item.ExpectedCode != "" {
rejection, ok := err.(*MarketplaceRejection)
if !ok || rejection.Code != item.ExpectedCode {
Expand All @@ -49,7 +59,9 @@ func TestMarketplaceSourceFixture(t *testing.T) {
if err != nil ||
source.IndexURL != item.Expected.IndexURL ||
source.RecommendationsURL != item.Expected.RecommendationsURL ||
source.DisplayName != item.Expected.DisplayName {
source.DisplayName != item.Expected.DisplayName ||
!reflect.DeepEqual(source.Revision, item.Expected.Revision) ||
!reflect.DeepEqual(source.Pinned, item.Expected.Pinned) {
t.Fatalf("source = %#v, error = %v", source, err)
}
})
Expand Down
27 changes: 27 additions & 0 deletions desktop/internal/githubapi/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,33 @@ func DecodeBranches(raw json.RawMessage) ([]Branch, error) {
return items, err
}

// DecodeReleases reads the normalized listReleases result, newest first.
func DecodeReleases(raw json.RawMessage) ([]Release, error) {
var items []Release
err := json.Unmarshal(raw, &items)
return items, err
}

// DecodeLatestCommit reads the normalized latestCommit result: the full lowercase SHA.
func DecodeLatestCommit(raw json.RawMessage) (string, error) {
var commit struct {
SHA string `json:"sha"`
}
err := json.Unmarshal(raw, &commit)
return commit.SHA, err
}

// Release is one published release. Name is empty when the author left the title empty; Body is
// the release notes in Markdown, possibly empty; PublishedAt is RFC 3339 or empty.
type Release struct {
TagName string `json:"tagName"`
Name string `json:"name"`
Body string `json:"body"`
PublishedAt string `json:"publishedAt"`
Prerelease bool `json:"prerelease"`
URL string `json:"url"`
}

// DecodeComparison reads the normalized comparison of two branches.
func DecodeComparison(raw json.RawMessage) (Comparison, error) {
var comparison Comparison
Expand Down
24 changes: 24 additions & 0 deletions desktop/internal/i18n/shared.generated.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

89 changes: 86 additions & 3 deletions desktop/internal/marketplace/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ const (
MaxIndexBytes = 5 << 20
fetchTimeout = 20 * time.Second
maxRedirects = 10
// commitLookupTimeout bounds the newest-commit lookup, so an unreachable GitHub API costs
// a few seconds before the canonical index is read instead of the whole fetch budget.
commitLookupTimeout = 5 * time.Second
)

var (
Expand All @@ -36,13 +39,21 @@ var (
// Evaluator is the shared Core marketplace contract, supplied by core.Client.
type Evaluator interface {
ResolveMarketplaceSource(context.Context, string) (core.MarketplaceSource, error)
PinMarketplaceSource(ctx context.Context, url, commit string) (core.MarketplaceSource, error)
ValidateMarketplaceIndex(context.Context, json.RawMessage, core.MarketplaceSourceKind, string, map[string][]int) (core.MarketplaceIndex, error)
}

// CommitLookup returns the newest commit of ref in repository as a full SHA.
type CommitLookup func(ctx context.Context, repository core.GitHubRepo, ref string) (string, error)

// Service holds a reusable HTTP client. It stores no index inside application resources.
type Service struct {
core Evaluator
http *http.Client
// latest and fallback are set by PinToLatestCommit; with latest nil every file is read
// from its canonical URL.
latest CommitLookup
fallback func(context.Context, error)
}

// New creates a marketplace service. A nil client uses Go's default transport;
Expand All @@ -51,6 +62,16 @@ func New(evaluator Evaluator, client *http.Client) *Service {
return &Service{core: evaluator, http: marketplaceHTTPClient(client, fetchTimeout)}
}

// PinToLatestCommit makes s read a GitHub-hosted source at the newest commit latest reports
// rather than at its branch URL, which raw.githubusercontent.com serves from a cache for up to
// five minutes after a push. When the lookup or the pinned read fails, s reads the canonical URL
// and hands the failure to fallback with the fetch's context; fallback must be safe to call from
// any goroutine.
func (s *Service) PinToLatestCommit(latest CommitLookup, fallback func(context.Context, error)) *Service {
s.latest, s.fallback = latest, fallback
return s
}

// marketplaceHTTPClient preserves the supplied transport and redirect policy,
// while refusing redirects that would downgrade or embed credentials. A
// positive timeout bounds each request as a whole, keeping a shorter one the
Expand Down Expand Up @@ -103,7 +124,8 @@ func (s *Service) Fetch(ctx context.Context, input string, kind core.Marketplace
if err != nil {
return Snapshot{}, err
}
data, _, err := s.fetchJSON(ctx, source.IndexURL)
pinned := s.pin(ctx, input, source)
data, err := s.fetchPinned(ctx, source.IndexURL, pinnedIndex(pinned))
if err != nil {
return Snapshot{}, err
}
Expand All @@ -127,14 +149,15 @@ func (s *Service) FetchRecommendationBundle(ctx context.Context, input string, k
if source.RecommendationsURL == "" {
return RecommendationBundle{}, false, nil
}
recBody, _, err := s.fetchJSON(ctx, source.RecommendationsURL)
pinned := s.pin(ctx, input, source)
recBody, err := s.fetchPinned(ctx, source.RecommendationsURL, pinnedRecommendations(pinned))
if err != nil {
if err == httpStatusError(http.StatusNotFound) {
return RecommendationBundle{}, false, nil
}
return RecommendationBundle{}, false, err
}
indexBody, _, err := s.fetchJSON(ctx, source.IndexURL)
indexBody, err := s.fetchPinned(ctx, source.IndexURL, pinnedIndex(pinned))
if err != nil {
return RecommendationBundle{}, false, err
}
Expand All @@ -146,6 +169,66 @@ func (s *Service) FetchRecommendationBundle(ctx context.Context, input string, k
}, true, nil
}

// pin asks for the newest commit of a GitHub-hosted source and has Core place the source's files
// at it. It returns nil, after reporting why, when the lookup or Core fails, and nil without a
// report when s does not pin or the source follows no GitHub branch.
func (s *Service) pin(ctx context.Context, input string, source core.MarketplaceSource) *core.MarketplacePinned {
if s.latest == nil || source.Revision == nil {
return nil
}
lookupCtx, cancel := context.WithTimeout(ctx, commitLookupTimeout)
commit, err := s.latest(lookupCtx, source.Revision.Repository, source.Revision.Ref)
cancel()
if err != nil {
s.reportFallback(ctx, fmt.Errorf("look up the newest commit of %s/%s %s: %w", source.Revision.Repository.Owner, source.Revision.Repository.Name, source.Revision.Ref, err))
return nil
}
pinned, err := s.core.PinMarketplaceSource(ctx, input, commit)
if err == nil && pinned.Pinned == nil {
err = errors.New("Core placed no file at the commit")
}
if err != nil {
s.reportFallback(ctx, fmt.Errorf("pin %s at %s: %w", source.IndexURL, commit, err))
return nil
}
return pinned.Pinned
}

// fetchPinned reads the file at pinnedURL when there is one and at canonical otherwise. A pinned
// read that fails is reported and retried at canonical, except a 404: the commit is the
// repository's newest, so the file is absent from it.
func (s *Service) fetchPinned(ctx context.Context, canonical, pinnedURL string) ([]byte, error) {
if pinnedURL != "" {
data, _, err := s.fetchJSON(ctx, pinnedURL)
if err == nil || err == httpStatusError(http.StatusNotFound) || ctx.Err() != nil {
return data, err
}
s.reportFallback(ctx, fmt.Errorf("read %s: %w", pinnedURL, err))
}
data, _, err := s.fetchJSON(ctx, canonical)
return data, err
}

func (s *Service) reportFallback(ctx context.Context, err error) {
if s.fallback != nil {
s.fallback(ctx, err)
}
}

func pinnedIndex(pinned *core.MarketplacePinned) string {
if pinned == nil {
return ""
}
return pinned.IndexURL
}

func pinnedRecommendations(pinned *core.MarketplacePinned) string {
if pinned == nil {
return ""
}
return pinned.RecommendationsURL
}

func (s *Service) fetchJSON(ctx context.Context, rawURL string) (data []byte, status int, err error) {
request, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
Expand Down
Loading
Loading