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: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ require (
github.com/cenkalti/backoff/v4 v4.3.0
github.com/golang-jwt/jwt/v4 v4.5.2
github.com/google/uuid v1.6.0
github.com/hashicorp/go-retryablehttp v0.7.8
github.com/hashicorp/go-version v1.6.0
github.com/joho/godotenv v1.5.1
github.com/onsi/ginkgo/v2 v2.15.0
Expand All @@ -27,6 +26,7 @@ require (
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1 // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/hashicorp/go-retryablehttp v0.7.8 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.66.1 // indirect
Expand Down
47 changes: 0 additions & 47 deletions pkg/github/actions/api.go

This file was deleted.

133 changes: 0 additions & 133 deletions pkg/github/actions/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,29 +6,9 @@ package actions

import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"sync"
"time"

"github.com/google/uuid"
"github.com/macstadium/orka-github-actions-integration/pkg/env"
"github.com/macstadium/orka-github-actions-integration/pkg/github"
"github.com/macstadium/orka-github-actions-integration/pkg/github/app"
"github.com/macstadium/orka-github-actions-integration/pkg/github/auth"
"github.com/macstadium/orka-github-actions-integration/pkg/github/types"
retryablehttp "github.com/macstadium/orka-github-actions-integration/pkg/http"
"github.com/macstadium/orka-github-actions-integration/pkg/logging"
"github.com/macstadium/orka-github-actions-integration/pkg/utils"
"go.uber.org/zap"
)

const (
scaleSetEndpoint = "_apis/runtime/runnerscalesets"
apiVersion = "6.0-preview"
)

type ActionsService interface {
Expand All @@ -42,123 +22,10 @@ type ActionsService interface {

CreateMessageSession(ctx context.Context, runnerScaleSetId int, owner string) (*types.RunnerScaleSetSession, error)
DeleteMessageSession(ctx context.Context, runnerScaleSetId int, sessionId *uuid.UUID) error
RefreshMessageSession(ctx context.Context, runnerScaleSetId int, sessionId *uuid.UUID) (*types.RunnerScaleSetSession, error)

AcquireJobs(ctx context.Context, runnerScaleSetId int, messageQueueAccessToken string, requestIds []int64) ([]int64, error)
GetAcquirableJobs(ctx context.Context, runnerScaleSetId int) (*types.AcquirableJobList, error)

GetMessage(ctx context.Context, messageQueueUrl, messageQueueAccessToken string, lastMessageId int64) (*types.RunnerScaleSetMessage, error)
DeleteMessage(ctx context.Context, messageQueueUrl, messageQueueAccessToken string, messageId int64) error
}

type ActionsClient struct {
*retryablehttp.Client

actionsServiceUrl string
adminToken string
adminTokenExpiresAt time.Time

logger *zap.SugaredLogger

envData *env.Data

gitHubConfig *github.GitHubConfig

// lock for refreshing the adminToken and adminTokenExpiresAt
mu sync.Mutex
}

func (client *ActionsClient) newActionsServiceRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) {
if err := client.updateTokenIfNeeded(ctx); err != nil {
return nil, err
}

targetURL, err := client.buildURL(path, apiVersion)
if err != nil {
return nil, err
}

return http.NewRequestWithContext(ctx, method, targetURL.String(), body)
}

func (client *ActionsClient) updateTokenIfNeeded(ctx context.Context) error {
client.mu.Lock()
defer client.mu.Unlock()

aboutToExpire := time.Now().Add(60 * time.Second).After(client.adminTokenExpiresAt)
if !aboutToExpire && !client.adminTokenExpiresAt.IsZero() {
return nil
}

client.logger.Infof("refreshing token for githubConfigUrl %s", client.gitHubConfig.URL)

accessToken, err := app.FetchAccessToken(ctx, client.envData)
if err != nil {
return fmt.Errorf("failed to get app access token on refresh: %w", err)
}

authInfo, err := auth.GetAuthorizationInfo(ctx, accessToken, client.envData.GitHubAPIUrl, client.gitHubConfig)
if err != nil {
return fmt.Errorf("failed to get actions service admin authentication info on refresh: %w", err)
}

client.actionsServiceUrl = authInfo.ActionsServiceUrl
client.adminToken = authInfo.AdminToken
client.adminTokenExpiresAt, err = utils.GetTokenExpirationTime(authInfo.AdminToken)
if err != nil {
return fmt.Errorf("failed to get admin token expire at on refresh: %w", err)
}

client.Client.Transport = &retryablehttp.ClientTransport{
ContentType: "application/json",
Token: client.adminToken,
}

return nil
}

func (client *ActionsClient) buildURL(path, apiVersion string) (*url.URL, error) {
urlString := fmt.Sprintf("%s/%s", strings.TrimRight(client.actionsServiceUrl, "/"), strings.TrimLeft(path, "/"))

targetURL, err := url.Parse(urlString)
if err != nil {
return nil, err
}

query := targetURL.Query()
if query.Get("api-version") == "" {
query.Set("api-version", apiVersion)
}
targetURL.RawQuery = query.Encode()

return targetURL, nil
}

func NewActionsClient(ctx context.Context, envData *env.Data, config *github.GitHubConfig) (*ActionsClient, error) {
accessToken, err := app.FetchAccessToken(ctx, envData)
if err != nil {
return nil, fmt.Errorf("failed to get access token from app: %w", err)
}

authInfo, err := auth.GetAuthorizationInfo(ctx, accessToken, envData.GitHubAPIUrl, config)
if err != nil {
return nil, fmt.Errorf("failed to get actions service auth info: %w", err)
}

retryableClient, err := retryablehttp.NewClient(&retryablehttp.ClientTransport{
Token: authInfo.AdminToken,
ContentType: "application/json",
})
if err != nil {
return nil, err
}

return &ActionsClient{
actionsServiceUrl: authInfo.ActionsServiceUrl,
adminToken: authInfo.AdminToken,
Client: retryableClient,
logger: logging.Logger.Named("actions-service"),
envData: envData,
gitHubConfig: config,
}, nil
}
43 changes: 0 additions & 43 deletions pkg/github/actions/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,7 @@
package actions

import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
)

type ActionsError struct {
Expand All @@ -22,41 +17,3 @@ type ActionsError struct {
func (e *ActionsError) Error() string {
return fmt.Sprintf("%v - had issue communicating with Actions backend: %v", e.StatusCode, e.Message)
}

func ParseActionsErrorFromResponse(response *http.Response) error {
if response.ContentLength == 0 {
message := "Request returned status: " + response.Status
return &ActionsError{
ExceptionName: "unknown",
Message: message,
StatusCode: response.StatusCode,
}
}

body, err := io.ReadAll(response.Body)
if err != nil {
return err
}

body = trimByteOrderMark(body)
contentType, ok := response.Header["Content-Type"]
if ok && len(contentType) > 0 && strings.Contains(contentType[0], "text/plain") {
message := string(body)
statusCode := response.StatusCode
return &ActionsError{
Message: message,
StatusCode: statusCode,
}
}

actionsError := &ActionsError{StatusCode: response.StatusCode}
if err := json.Unmarshal(body, &actionsError); err != nil {
return err
}

return actionsError
}

func trimByteOrderMark(body []byte) []byte {
return bytes.TrimPrefix(body, []byte("\xef\xbb\xbf"))
}
60 changes: 0 additions & 60 deletions pkg/github/actions/job.go

This file was deleted.

Loading
Loading