Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement GitHubClientFactory #3203

Merged
merged 1 commit into from
Apr 30, 2024
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
4 changes: 3 additions & 1 deletion internal/controlplane/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ import (
"github.com/stacklok/minder/internal/profiles"
"github.com/stacklok/minder/internal/providers"
ghprov "github.com/stacklok/minder/internal/providers/github"
"github.com/stacklok/minder/internal/providers/github/clients"
ghmanager "github.com/stacklok/minder/internal/providers/github/manager"
"github.com/stacklok/minder/internal/providers/github/service"
"github.com/stacklok/minder/internal/providers/manager"
Expand Down Expand Up @@ -175,6 +176,7 @@ func NewServer(
profileSvc := profiles.NewProfileService(evt)
mt := metrics.NewNoopMetrics()
provMt := provtelemetry.NewNoopMetrics()
ghClientFactory := clients.NewGitHubClientFactory(provMt)
ruleSvc := ruletypes.NewRuleTypeService()
marketplace, err := marketplaces.NewMarketplaceFromServiceConfig(cfg.Marketplace, profileSvc, ruleSvc)
if err != nil {
Expand Down Expand Up @@ -217,7 +219,7 @@ func NewServer(

githubProviderManager := ghmanager.NewGitHubProviderClassManager(
s.restClientCache,
provMt,
ghClientFactory,
&cfg.Provider,
fallbackTokenClient,
eng,
Expand Down
62 changes: 5 additions & 57 deletions internal/providers/github/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,21 +19,15 @@ import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"

gogithub "github.com/google/go-github/v61/github"
"github.com/motemen/go-loghttp"
"github.com/rs/zerolog"
"golang.org/x/oauth2"

"github.com/stacklok/minder/internal/config/server"
"github.com/stacklok/minder/internal/db"
"github.com/stacklok/minder/internal/providers/github"
"github.com/stacklok/minder/internal/providers/github/clients"
ghcommon "github.com/stacklok/minder/internal/providers/github/common"
"github.com/stacklok/minder/internal/providers/ratecache"
"github.com/stacklok/minder/internal/providers/telemetry"
minderv1 "github.com/stacklok/minder/pkg/api/protobuf/go/minder/v1"
provifv1 "github.com/stacklok/minder/pkg/providers/v1"
)
Expand Down Expand Up @@ -68,63 +62,17 @@ type GitHubAppDelegate struct {
// endpoint (as is the case with GitHub Enterprise), set the Endpoint field in
// the GitHubConfig struct
func NewGitHubAppProvider(
providerConfig *minderv1.GitHubAppProviderConfig,
cfg *minderv1.GitHubAppProviderConfig,
appConfig *server.GitHubAppConfig,
metrics telemetry.HttpClientMetrics,
restClientCache ratecache.RestClientCache,
credential provifv1.GitHubCredential,
packageListingClient *gogithub.Client,
ghClientFactory clients.GitHubClientFactory,
isOrg bool,
) (*github.GitHub, error) {
var err error

tc := &http.Client{
Transport: &oauth2.Transport{
Base: http.DefaultClient.Transport,
Source: credential.GetAsOAuth2TokenSource(),
},
}

transport, err := metrics.NewDurationRoundTripper(tc.Transport, db.ProviderTypeGithub)
ghClient, err := ghClientFactory.Build(cfg.Endpoint, credential)
if err != nil {
return nil, fmt.Errorf("error creating duration round tripper: %w", err)
}

// If $MINDER_LOG_GITHUB_REQUESTS is set, wrap the transport in a logger
// to record all calls and responses to from GitHub:
if os.Getenv("MINDER_LOG_GITHUB_REQUESTS") != "" {
transport = &loghttp.Transport{
Transport: transport,
LogRequest: func(req *http.Request) {
zerolog.Ctx(req.Context()).Debug().
Str("type", "REQ").
Str("method", req.Method).
Msg(req.URL.String())
},
LogResponse: func(resp *http.Response) {
zerolog.Ctx(resp.Request.Context()).Debug().
Str("type", "RESP").
Str("method", resp.Request.Method).
Str("status", fmt.Sprintf("%d", resp.StatusCode)).
Str("rate-limit", fmt.Sprintf("%s/%s",
resp.Request.Header.Get("x-ratelimit-used"),
resp.Request.Header.Get("x-ratelimit-remaining"),
)).
Msg(resp.Request.URL.String())

},
}
}

tc.Transport = transport
ghClient := gogithub.NewClient(tc)

if providerConfig.Endpoint != "" {
parsedURL, err := url.Parse(providerConfig.Endpoint)
if err != nil {
return nil, err
}
ghClient.BaseURL = parsedURL
return nil, err
}

appName := appConfig.AppName
Expand Down
40 changes: 21 additions & 19 deletions internal/providers/github/app/app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import (
"github.com/stacklok/minder/internal/db"
"github.com/stacklok/minder/internal/providers/credentials"
github2 "github.com/stacklok/minder/internal/providers/github"
"github.com/stacklok/minder/internal/providers/github/clients"
"github.com/stacklok/minder/internal/providers/ratecache"
provtelemetry "github.com/stacklok/minder/internal/providers/telemetry"
minderv1 "github.com/stacklok/minder/pkg/api/protobuf/go/minder/v1"
Expand All @@ -42,13 +43,13 @@ import (
func TestNewGitHubAppProvider(t *testing.T) {
t.Parallel()

client, err := NewGitHubAppProvider(&minderv1.GitHubAppProviderConfig{
Endpoint: "https://api.github.com",
},
client, err := NewGitHubAppProvider(
&minderv1.GitHubAppProviderConfig{Endpoint: "https://api.github.com"},
&config.GitHubAppConfig{},
provtelemetry.NewNoopMetrics(),
nil, credentials.NewGitHubTokenCredential("token"),
nil,
credentials.NewGitHubTokenCredential("token"),
github.NewClient(http.DefaultClient),
clients.NewGitHubClientFactory(provtelemetry.NewNoopMetrics()),
false,
)

Expand All @@ -64,17 +65,17 @@ func TestUserInfo(t *testing.T) {

ctx := context.Background()

client, err := NewGitHubAppProvider(&minderv1.GitHubAppProviderConfig{
Endpoint: "https://api.github.com",
},
client, err := NewGitHubAppProvider(
&minderv1.GitHubAppProviderConfig{Endpoint: "https://api.github.com"},
&config.GitHubAppConfig{
AppName: appName,
AppID: appId,
UserID: expectedUserId,
},
provtelemetry.NewNoopMetrics(),
nil, credentials.NewGitHubTokenCredential("token"),
ratecache.NewRestClientCache(context.Background()),
credentials.NewGitHubTokenCredential("token"),
github.NewClient(http.DefaultClient),
clients.NewGitHubClientFactory(provtelemetry.NewNoopMetrics()),
false,
)
assert.NoError(t, err)
Expand Down Expand Up @@ -165,15 +166,16 @@ func TestArtifactAPIEscapes(t *testing.T) {
assert.NoError(t, err)
packageListingClient.BaseURL = testServerUrl

client, err := NewGitHubAppProvider(&minderv1.GitHubAppProviderConfig{
Endpoint: testServer.URL + "/",
},
client, err := NewGitHubAppProvider(
&minderv1.GitHubAppProviderConfig{Endpoint: testServer.URL + "/"},
&config.GitHubAppConfig{},
provtelemetry.NewNoopMetrics(),
nil, credentials.NewGitHubTokenCredential("token"),
ratecache.NewRestClientCache(context.Background()),
credentials.NewGitHubTokenCredential("token"),
packageListingClient,
clients.NewGitHubClientFactory(provtelemetry.NewNoopMetrics()),
true,
)

assert.NoError(t, err)
assert.NotNil(t, client)

Expand Down Expand Up @@ -256,10 +258,10 @@ func TestListPackagesByRepository(t *testing.T) {
&config.GitHubAppConfig{
FallbackToken: accessToken,
},
provtelemetry.NewNoopMetrics(),
nil,
ratecache.NewRestClientCache(context.Background()),
credentials.NewGitHubTokenCredential(accessToken),
packageListingClient,
clients.NewGitHubClientFactory(provtelemetry.NewNoopMetrics()),
true,
)
assert.NoError(t, err)
Expand Down Expand Up @@ -304,10 +306,10 @@ func TestWaitForRateLimitReset(t *testing.T) {
client, err := NewGitHubAppProvider(
&minderv1.GitHubAppProviderConfig{Endpoint: server.URL + "/"},
&config.GitHubAppConfig{},
provtelemetry.NewNoopMetrics(),
ratecache.NewRestClientCache(context.Background()),
credentials.NewGitHubTokenCredential(token),
packageListingClient,
clients.NewGitHubClientFactory(provtelemetry.NewNoopMetrics()),
false,
)
require.NoError(t, err)
Expand Down Expand Up @@ -361,10 +363,10 @@ func TestConcurrentWaitForRateLimitReset(t *testing.T) {
client, err := NewGitHubAppProvider(
&minderv1.GitHubAppProviderConfig{Endpoint: server.URL + "/"},
&config.GitHubAppConfig{},
provtelemetry.NewNoopMetrics(),
restClientCache,
credentials.NewGitHubTokenCredential(token),
packageListingClient,
clients.NewGitHubClientFactory(provtelemetry.NewNoopMetrics()),
false,
)
require.NoError(t, err)
Expand Down
102 changes: 102 additions & 0 deletions internal/providers/github/clients/factory.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// Copyright 2024 Stacklok, Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package clients contains the GitHub client factory
package clients

import (
"fmt"
"net/http"
"net/url"
"os"

gogithub "github.com/google/go-github/v61/github"
"github.com/motemen/go-loghttp"
"github.com/rs/zerolog"
"golang.org/x/oauth2"

"github.com/stacklok/minder/internal/db"
"github.com/stacklok/minder/internal/providers/telemetry"
provifv1 "github.com/stacklok/minder/pkg/providers/v1"
)

// GitHubClientFactory creates instances of the GitHub API client
type GitHubClientFactory interface {
// Build creates an instance of the GitHub Client
// `baseURL` should be set to the empty string if there is no need to
// override the default GitHub URL
Build(baseURL string, credential provifv1.GitHubCredential) (*gogithub.Client, error)
}

type githubClientFactory struct {
metrics telemetry.HttpClientMetrics
}

// NewGitHubClientFactory creates a new instance of GitHubClientFactory
func NewGitHubClientFactory(metrics telemetry.HttpClientMetrics) GitHubClientFactory {
return &githubClientFactory{metrics: metrics}
}

func (g *githubClientFactory) Build(baseURL string, credential provifv1.GitHubCredential) (*gogithub.Client, error) {
tc := &http.Client{
Transport: &oauth2.Transport{
Base: http.DefaultClient.Transport,
Source: credential.GetAsOAuth2TokenSource(),
},
}

transport, err := g.metrics.NewDurationRoundTripper(tc.Transport, db.ProviderTypeGithub)
if err != nil {
return nil, fmt.Errorf("error creating duration round tripper: %w", err)
}

// If $MINDER_LOG_GITHUB_REQUESTS is set, wrap the transport in a logger
// to record all calls and responses to from GitHub:
if os.Getenv("MINDER_LOG_GITHUB_REQUESTS") != "" {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should move this to some actual configuration at some point, or remove this hook.

(Doesn't need to be part of this PR)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not for this PR, but it would be nice to keep a histogram of the values of x-ratelimit-remaining across our GitHub clients.

transport = &loghttp.Transport{
Transport: transport,
LogRequest: func(req *http.Request) {
zerolog.Ctx(req.Context()).Debug().
Str("type", "REQ").
Str("method", req.Method).
Msg(req.URL.String())
},
LogResponse: func(resp *http.Response) {
zerolog.Ctx(resp.Request.Context()).Debug().
Str("type", "RESP").
Str("method", resp.Request.Method).
Str("status", fmt.Sprintf("%d", resp.StatusCode)).
Str("rate-limit", fmt.Sprintf("%s/%s",
resp.Request.Header.Get("x-ratelimit-used"),
resp.Request.Header.Get("x-ratelimit-remaining"),
)).
Msg(resp.Request.URL.String())

},
}
}

tc.Transport = transport
ghClient := gogithub.NewClient(tc)

if baseURL != "" {
parsedURL, err := url.Parse(baseURL)
if err != nil {
return nil, err
}
ghClient.BaseURL = parsedURL
}

return ghClient, nil
}
Loading