api

package
v0.9.4 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2023 License: MIT Imports: 42 Imported by: 0

README

API Versioning

We now make the commitment to users that existing endpoints will not change, either in schema/format or in content (for example, silently changing a branch name field to a SHA).

Any changed endpoints must be put into a separate API version.

This API package allows a developer to create a new API version by defining a new struct in a new file in this package (api_vX.go) supporting the new routes it defines.

The API version struct is required to have a single method: register(m *mux.Router) which accepts a Gorilla Mux router. It must define the various routes it implements along with their respective handler methods.

DO NOT serialize or deserialize fundamental data structures in handlers (anything in models.go).

Fundamental data types are subject to change at any time and in that event will break your API, often silently.

Instead, define endpoint input/output structs as private types (ex: apiV2_Environment) and then provide methods to convert to and from the fundamental types. If anyone changes the fundamental types that break your API it will likely become a compile time error. Please create unit tests that verify endpoint conformance to your API contracts for better protection against silent breakage.

HOWTO

  1. Create a new files in this package (api_v9.go, api_v9_test.go).
  2. Implement a non-exported struct and constructor. The constructor should take all required dependencies as parameters.
  3. Implement the struct method register() and register all relevant endpoint routes using the Mux API.
  4. Implement all handler methods.
  5. Write tests
  6. Wire in your structs creation and registration in Dispatcher.RegisterVersions()
  7. Add a line to CHANGELOG describing the API changes and the new version number.

Documentation

Index

Constants

View Source
const (
	DefaultPodContainerLogLines = 100
	MinAPIKeyPermissionLevel    = models.ReadOnlyPermission
	MaxAPIKeyPermissionLevel    = models.WritePermission
	MaxAPIKeysLimit             = 10
)

Variables

View Source
var MaxAsyncActionTimeout = 32 * time.Minute

MaxAsyncActionTimeout is the maximum amount of time an asynchronous action can take before it's forcibly cancelled This is mainly a failsafe against leaking goroutines, additional more strict timeout logic is implemented by environment operations code. If this timeout occurs, no notifications will be sent to the user.

Functions

This section is empty.

Types

type BaseTemplateData added in v0.7.6

type BaseTemplateData struct {
	APIBaseURL, GitHubUser              string
	Branding                            uiBranding
	RenderEventLink, RenderUserSettings bool
}

type Dependencies

type Dependencies struct {
	DataLayer          persistence.DataLayer
	GitHubEventWebhook *ghevent.GitHubEventWebhook
	EnvironmentSpawner spawner.EnvironmentSpawner
	RepoClient         ghclient.RepoClient
	ServerConfig       config.ServerConfig
	DatadogServiceName string
	Logger             *log.Logger
	KubernetesReporter metahelm.KubernetesReporter
	Furan2Client       Furan2Client
}

Dependencies are the dependencies required for the API

type Dispatcher

type Dispatcher struct {
	AppGHClientFactoryFunc func(tkn string) ghclient.GitHubAppInstallationClient
	// contains filtered or unexported fields
}

Dispatcher is the concrete implementation of Manager

func NewDispatcher

func NewDispatcher(s *http.Server) *Dispatcher

NewDispatcher returns an initialized Dispatcher. s should be preconfigured to be able to run ListenAndServeTLS()

func (*Dispatcher) RegisterVersions

func (d *Dispatcher) RegisterVersions(deps *Dependencies, ro ...RegisterOption) error

RegisterVersions registers all API versions with the supplied http.Server

func (*Dispatcher) Stop added in v0.7.6

func (d *Dispatcher) Stop()

Stop stops any async processes such as UI sessions cleanup

func (*Dispatcher) WaitForAsync

func (d *Dispatcher) WaitForAsync()

WaitAsync waits for any async goroutines to finish

func (*Dispatcher) WaitForHandlers

func (d *Dispatcher) WaitForHandlers()

WaitHandlers waits for any handlers that have used waitMiddleware to finish

type Furan2Client added in v0.9.3

type Furan2Client interface {
	GetBuildEvents(ctx context.Context, id guuid.UUID) (*furanrpc.BuildEventsResponse, error)
	GetBuildStatus(ctx context.Context, id guuid.UUID) (*furanrpc.BuildStatusResponse, error)
	Close()
}

type Manager

type Manager interface {
	RegisterVersions(deps *Dependencies)
	Wait()
}

Manager describes an object capable of registering API versions and waiting on requests

type OAuthConfig added in v0.7.6

type OAuthConfig struct {
	Enforce                     bool                                                    // Enforce OAuth authn/authz for protected routes
	DummySessionUser            string                                                  // Create a new authenticated dummy session with username if no session exists (for testing)
	AppInstallationID           int64                                                   // GitHub App installation ID
	ClientID, ClientSecret      string                                                  // GitHub App ClientID/secret
	ValidateURL                 url.URL                                                 // URL to validate callback code and exchange for bearer token
	AuthURL                     url.URL                                                 // URL to initiate OAuth flow
	AppGHClientFactoryFunc      func(token string) ghclient.GitHubAppInstallationClient // Function that produces a token-scoped GitHubAppInstallationClient
	CookieAuthKey, CookieEncKey [32]byte                                                // Cookie authentication & encryption keys (AES-256)
	UserTokenEncKey             [32]byte                                                // Secretbox encryption key for user token
	// contains filtered or unexported fields
}

OAuthConfig models the configuration needed to support a GitHub OAuth authn/authz flow

func (*OAuthConfig) SetAuthURL added in v0.7.6

func (oac *OAuthConfig) SetAuthURL(aurl string) error

func (*OAuthConfig) SetValidateURL added in v0.7.6

func (oac *OAuthConfig) SetValidateURL(vurl string) error

type RegisterOption

type RegisterOption func(*registerOptions)

RegisterOption is an option for RegisterVersions()

func WithAPIKeys

func WithAPIKeys(keys []string) RegisterOption

WithAPIKeys supplies API keys for protected endpoints

func WithDebugEndpoints

func WithDebugEndpoints() RegisterOption

WithDebugEndpoints causes RegisterVersions to register debug pprof endpoints

func WithGitHubConfig added in v0.7.6

func WithGitHubConfig(ghconfig config.GithubConfig) RegisterOption

func WithIPWhitelist

func WithIPWhitelist(ips []string) RegisterOption

WithIPWhitelist supplies IP CIDRs for whitelisted endpoints. Invalid CIDRs are ignored.

func WithUIAssetsPath added in v0.7.5

func WithUIAssetsPath(assetsPath string) RegisterOption

func WithUIBaseURL added in v0.7.5

func WithUIBaseURL(baseURL string) RegisterOption

func WithUIBranding added in v0.7.5

func WithUIBranding(branding config.UIBrandingConfig) RegisterOption

func WithUIDummySessionUser added in v0.7.6

func WithUIDummySessionUser(user string) RegisterOption

func WithUIReload added in v0.7.5

func WithUIReload() RegisterOption

func WithUIRoutePrefix added in v0.7.5

func WithUIRoutePrefix(routePrefix string) RegisterOption

type StatusTemplateData added in v0.7.5

type StatusTemplateData struct {
	BaseTemplateData
	LogKey string
}

type V2EnvDetail added in v0.7.6

type V2EnvDetail struct {
	V2UserEnv
	GitHubUser   string           `json:"github_user"`
	PRHeadBranch string           `json:"pr_head_branch"`
	K8sNamespace string           `json:"k8s_namespace"`
	Events       []V2EventSummary `json:"events"`
}

func V2EnvDetailFromQAEnvAndK8sEnv added in v0.7.6

func V2EnvDetailFromQAEnvAndK8sEnv(qae models.QAEnvironment, k8senv models.KubernetesEnvironment) V2EnvDetail

type V2EnvNamePodContainers added in v0.8.0

type V2EnvNamePodContainers struct {
	Name       string   `json:"name"`
	Containers []string `json:"containers"`
}

type V2EnvNamePods added in v0.8.0

type V2EnvNamePods struct {
	Name     string `json:"name"`
	Ready    string `json:"ready"`
	Status   string `json:"status"`
	Restarts string `json:"restarts"`
	Age      string `json:"age"`
}

type V2EventStatusSummary added in v0.7.5

type V2EventStatusSummary struct {
	Config V2EventStatusSummaryConfig       `json:"config"`
	Tree   map[string]V2EventStatusTreeNode `json:"tree"`
}

func V2EventStatusSummaryFromEventStatusSummary added in v0.7.5

func V2EventStatusSummaryFromEventStatusSummary(sum *models.EventStatusSummary) *V2EventStatusSummary

type V2EventStatusSummaryConfig added in v0.7.5

type V2EventStatusSummaryConfig struct {
	Type           string                `json:"type"`
	Status         string                `json:"status"`
	RenderedStatus V2RenderedEventStatus `json:"rendered_status"`
	EnvName        string                `json:"env_name"`
	K8sNamespace   string                `json:"k8s_ns"`
	TriggeringRepo string                `json:"triggering_repo"`
	PullRequest    uint                  `json:"pull_request"`
	GitHubUser     string                `json:"github_user"`
	Branch         string                `json:"branch"`
	Revision       string                `json:"revision"`
	ProcessingTime string                `json:"processing_time"`
	Started        *time.Time            `json:"started"`
	Completed      *time.Time            `json:"completed"`
	RefMap         map[string]string     `json:"ref_map"`
}

type V2EventStatusTreeNode added in v0.7.5

type V2EventStatusTreeNode struct {
	Parent string                      `json:"parent"`
	Image  *V2EventStatusTreeNodeImage `json:"image"`
	Chart  V2EventStatusTreeNodeChart  `json:"chart"`
}

type V2EventStatusTreeNodeChart added in v0.7.5

type V2EventStatusTreeNodeChart struct {
	Status    string     `json:"status"`
	Started   *time.Time `json:"started"`
	Completed *time.Time `json:"completed"`
}

type V2EventStatusTreeNodeImage added in v0.7.5

type V2EventStatusTreeNodeImage struct {
	Name      string     `json:"name"`
	BuildID   string     `json:"build_id"`
	Error     bool       `json:"error"`
	Completed *time.Time `json:"completed"`
	Started   *time.Time `json:"started"`
}

type V2EventSummary added in v0.7.6

type V2EventSummary struct {
	EventID  string                           `json:"event_id"`
	Started  time.Time                        `json:"started"`
	Duration *models.ConfigProcessingDuration `json:"duration"`
	Type     string                           `json:"type"`
	Status   string                           `json:"status"`
}

func V2EventSummariesFromEventLogs added in v0.7.6

func V2EventSummariesFromEventLogs(elogs []models.EventLog) []V2EventSummary

type V2ImageBuildEvents added in v0.9.3

type V2ImageBuildEvents struct {
	BuildID   uuid.UUID `json:"build_id"`
	Started   time.Time `json:"started"`
	Completed time.Time `json:"completed"`
	Elapsed   string    `json:"elapsed"`
	Status    string    `json:"status"`
	Events    []string  `json:"events"`
}

type V2RenderedEventStatus added in v0.7.5

type V2RenderedEventStatus struct {
	Description   string `json:"description"`
	LinkTargetURL string `json:"link_target_url"`
}

func V2RenderedStatusFromRenderedStatus added in v0.7.5

func V2RenderedStatusFromRenderedStatus(rs models.RenderedEventStatus) V2RenderedEventStatus

type V2UserAPIKeyData added in v0.9.2

type V2UserAPIKeyData struct {
	ID          uuid.UUID              `json:"id"`
	Created     time.Time              `json:"created"`
	LastUsed    pq.NullTime            `json:"last_used"`
	Permission  models.PermissionLevel `json:"permission"`
	Description string                 `json:"description"`
	User        string                 `json:"user"`
}

type V2UserAPIKeyResponse added in v0.9.2

type V2UserAPIKeyResponse struct {
	User  string    `json:"user"`
	Token uuid.UUID `json:"token"`
}

type V2UserEnv added in v0.7.6

type V2UserEnv struct {
	Repo        string    `json:"repo"`
	PullRequest uint      `json:"pull_request"`
	EnvName     string    `json:"env_name"`
	LastEvent   time.Time `json:"last_event"`
	Status      string    `json:"status"`
}

Jump to

Keyboard shortcuts

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