stacksapi

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Feb 12, 2026 License: MIT Imports: 15 Imported by: 1

README

stacksapi

Go client library for the Buildkite Stacks API. This package enables custom stack implementations to communicate with Buildkite's agent infrastructure, handling job scheduling, lifecycle management, and stack registration.

Installation

go get github.com/buildkite/stacksapi

Authentication

Requires a Buildkite Cluster Token (not a REST or GraphQL API token, or an unclustered Agent Registration Token). The token is passed to NewClient().

Usage

import "github.com/buildkite/stacksapi"

client, err := stacksapi.NewClient(
    os.Getenv("BUILDKITE_CLUSTER_TOKEN"),
    stacksapi.WithLogger(logger),
)

Client Options

  • WithLogger(logger *slog.Logger) - Configure structured logging. To integrate with non-slog loggers, we recommend using log adapters like slog-zap, slog-zerolog and friends.
  • WithBaseURL(url *url.URL) - Override the default API endpoint
  • WithHTTPClient(client *http.Client) - Use a custom HTTP client
  • WithRetrierOptions(...roko.RetrierOpt) - Configure client-wide retry behavior. The default retry behaviour is an exponential backoff with jitter, retrying on 429 and 5xx responses. Retry behaviour can also be customized per-request using WithRetrier and WithNoRetry request options.
  • LogHTTPPayloads() - Enable request/response payload logging (may log sensitive data)
  • PrependToUserAgent(prefix string) - Customize the User-Agent header. Note that when using this library, the user agent will always end with stacksapi v$SOME_VERSION
Register a Stack
stack, _, err := client.RegisterStack(ctx, stacksapi.RegisterStackRequest{
    Key:      "my-stack",
    Type:     stacksapi.StackTypeCustom,
    QueueKey: stacksapi.DefaultQueue,
    Metadata: map[string]string{"version": "1.0"},
})
Fetch Scheduled Jobs
jobs, _, err := client.ScheduledJobs(ctx, stacksapi.ScheduledJobsRequest{
    StackKey: "my-stack",
})
Get Job Details
job, _, err := client.GetJob(ctx, stacksapi.GetJobRequest{
    StackKey: "my-stack",
    JobUUID:  jobUUID,
})
Finish a Job
_, err = client.FinishJob(ctx, stacksapi.FinishJobRequest{
    StackKey:   "my-stack",
    JobUUID:    jobUUID,
    ExitStatus: 0,
    Detail:     "Job completed successfully",
})
Deregister a Stack
_, err = client.DeregisterStack(ctx, "my-stack")

Request Options

Per-request options can be passed to any API method:

  • WithRetrier(retrier *roko.Retrier) - Override the default retry behavior
  • WithNoRetry() - Disable retries for the request

Stack Types

  • StackTypeCustom - For third-party stack implementations (recommended)
  • StackTypeKubernetes - Reserved for first-party agent-stack-k8s
  • StackTypeElastic - Reserved for first-party elastic-stack-for-aws

Examples

See example/main.go for a complete working example.

License

See LICENSE.txt.

Documentation

Overview

The stacksapi package implements an API client for the Buildkite Stacks API.

Index

Constants

View Source
const (
	DefaultBaseURL = "https://agent.buildkite.com/v3/"
	DefaultQueue   = "_default"
)
View Source
const Version = "v1.0.0"

Variables

Functions

This section is empty.

Types

type BatchReserveJobsRequest

type BatchReserveJobsRequest struct {
	StackKey                 string   `json:"-"`                                   // The key of the stack calling this endpoint. Required.
	JobUUIDs                 []string `json:"job_uuids"`                           // The UUIDs of the jobs to reserve. Required.
	ReservationExpirySeconds int      `json:"reservation_expiry_seconds,omitzero"` // The number of seconds until the reservation expires. Optional, defaults to 300 (5 minutes) if not set.
}

BatchReserveJobsRequest is the input type for [BatchReserveJobs]. The StackKey and JobUUIDs fields are required.

type BatchReserveJobsResponse

type BatchReserveJobsResponse struct {
	Reserved    []string `json:"reserved"`     // The UUIDs of the jobs that were successfully reserved
	NotReserved []string `json:"not_reserved"` // The UUIDs of the jobs that could not be reserved (e.g. because they were already reserved by another stack, or because they're no longer in a reservable state)
}

BatchReserveJobsResponse is the output type for [BatchReserveJobs]. It contains lists of successfully reserved and not reserved job UUIDs.

type Build

type Build struct {
	UUID   string `json:"uuid"`
	Number int    `json:"number"`
	Branch string `json:"branch"`
}

Build represents the build that created a job.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a Buildkite Stacks API client.

func NewClient

func NewClient(apiToken string, opts ...ClientOpt) (*Client, error)

NewClient creates a new API client with the given token and options. Note that the token must be a Buildkite Cluster Token, and that REST/GraphQL API tokens will not work.ql

func (*Client) BatchReserveJobs

func (c *Client) BatchReserveJobs(ctx context.Context, reserveReq BatchReserveJobsRequest, opts ...RequestOption) (*BatchReserveJobsResponse, http.Header, error)

BatchReserveJobs attempts to reserve a list of jobs for processing by the calling stack. The StackKey and JobUUIDs fields of the request are required. If a job cannot be reserved (for example, because it has already been reserved by another stack, or because it is no longer in a reservable state), it will be included in the NotReserved list in the response. Note that even if none of the jobs could be reserved, this method will still return a nil error, as long as the request itself was valid.

func (*Client) DeregisterStack

func (c *Client) DeregisterStack(ctx context.Context, stackKey string, opts ...RequestOption) (http.Header, error)

DeregisterStack informs the Buildkite Stacks API that a stack is exiting cleanly.

func (*Client) FinishJob

func (c *Client) FinishJob(ctx context.Context, finishJobReq FinishJobRequest, opts ...RequestOption) (http.Header, error)

func (*Client) GetJob

func (c *Client) GetJob(ctx context.Context, getJobReq GetJobRequest, opts ...RequestOption) (*GetJobResponse, http.Header, error)

GetJob return Job's runtime data (env and command) for a single job.

func (*Client) GetJobStates

func (c *Client) GetJobStates(ctx context.Context, getJobStatesReq GetJobStatesRequest, opts ...RequestOption) (*GetJobStatesResponse, http.Header, error)

GetJobStates query job states for a list of jobs

func (*Client) ListScheduledJobs

func (c *Client) ListScheduledJobs(ctx context.Context, listReq ListScheduledJobsRequest, opts ...RequestOption) (*ListScheduledJobsResponse, http.Header, error)

ListScheduledJobs lists jobs in the scheduled state from a specific cluster queue. The StackKey and ClusterQueueKey fields of the request are required. This method will only return a single page of results. To retrieve additional pages, call this method again with the EndCursor field set to the EndCursor value from the previous response's PageInfo.

func (*Client) RegisterStack

RegisterStack registers a new stack with the Buildkite Stacks API. A stack with the same key can safely be re-registered as many times as necessary.

type ClientOpt

type ClientOpt func(*Client) error

func LogHTTPPayloads

func LogHTTPPayloads() ClientOpt

LogHTTPRequestPayloads instructs the client to log all HTTP request payloads. Note that this may log sensitive information, and should be used with caution

func PrependToUserAgent

func PrependToUserAgent(prefix string) ClientOpt

PrependToUserAgent adds a prefix to the User-Agent header for the API client. Note that overriding of the user-agent is not supported (though can probably be worked around).

func WithBaseURL

func WithBaseURL(baseURL *url.URL) ClientOpt

WithBaseURL sets the base URL for the API client, overriding DefaultBaseURL

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) ClientOpt

WithHTTPClient sets the HTTP client for the API client, overriding http.DefaultClient.

func WithLogger

func WithLogger(logger *slog.Logger) ClientOpt

WithLogger sets the *slog.Logger for the API client. The default is a slog.Logger using the slog.DiscardHandler handler.

func WithRetrierOptions

func WithRetrierOptions(opts ...roko.RetrierOpt) ClientOpt

WithRetrierOptions sets the default retrier options for the API client. These can be overridden per-request by using the WithRetrier RequestOpt.

type ClusterQueue

type ClusterQueue struct {
	ID     string `json:"id"`
	Paused bool   `json:"paused"`
}

ClusterQueue represents a cluster queue in the Buildkite Stacks system.

type CreateStackNotificationsRequest

type CreateStackNotificationsRequest struct {
	StackKey      string              `json:"-"`
	Notifications []StackNotification `json:"notifications"`
}

type CreateStackNotificationsResponse

type CreateStackNotificationsResponse struct {
	Errors []StackNotificationError `json:"errors"`
}

type ErrorResponse

type ErrorResponse struct {
	Response *http.Response `json:"-"`       // HTTP response that caused this error. The Body will be closed.
	RawBody  []byte         `json:"-"`       // Raw Response Body
	Message  string         `json:"message"` // Error message from Buildkite API
}

ErrorResponse provides a message.

func (*ErrorResponse) Error

func (r *ErrorResponse) Error() string

func (*ErrorResponse) IsRetryableStatus

func (r *ErrorResponse) IsRetryableStatus() bool

type FinishJobRequest

type FinishJobRequest struct {
	StackKey   string `json:"-"`
	JobUUID    string `json:"-"`
	ExitStatus int    `json:"exit_status,omitempty"`
	Detail     string `json:"detail"`
}

type GetJobRequest

type GetJobRequest struct {
	StackKey string `json:"-"` // The key to call the stack. Required.
	JobUUID  string `json:"-"` // The uuid of a job. Required.
}

type GetJobResponse

type GetJobResponse struct {
	ID      string            `json:"id"`
	Env     map[string]string `json:"env"`
	Command string            `json:"command"`
}

type GetJobStatesRequest

type GetJobStatesRequest struct {
	StackKey string   `json:"-"`         // The key to call the stack. Required.
	JobUUIDs []string `json:"job_uuids"` // A list of job uuids
}

type GetJobStatesResponse

type GetJobStatesResponse struct {
	States map[string]string `json:"states"`
}

type ListScheduledJobsRequest

type ListScheduledJobsRequest struct {
	StackKey        string // The key of the stack calling this endpoint. Required
	ClusterQueueKey string // The key of the cluster queue to list jobs from. Required
	PageSize        int    // The number of jobs to return. Optional, defaults to a sensible value on the backend
	StartCursor     string // The cursor to start the page from. Optional, defaults to the start of the list
}

ListScheduledJobsRequest is the input type for [ListScheduledJobs]. The StackKey and ClusterQueueKey fields are required.

type ListScheduledJobsResponse

type ListScheduledJobsResponse struct {
	Jobs         []ScheduledJob `json:"jobs"`          // A list of jobs that are in the scheduled state
	ClusterQueue ClusterQueue   `json:"cluster_queue"` // The cluster queue the jobs were fetched from
	PageInfo     PageInfo       `json:"page_info"`     // Information about pagination
}

ListScheduledJobsResponse is the output type for [ListScheduledJobs]. It contains a list of jobs and pagination information.

type PageInfo

type PageInfo struct {
	HasNextPage bool   `json:"has_next_page"` // Whether there are more pages of results
	EndCursor   string `json:"end_cursor"`    // The cursor to use to fetch the next page of results
}

PageInfo contains information about pagination in a list response.

type Pipeline

type Pipeline struct {
	Slug string `json:"slug"`
	UUID string `json:"uuid"`
}

Pipeline represents the pipeline that created a job.

type RegisterStackRequest

type RegisterStackRequest struct {
	Key      string            `json:"key,omitempty"`       // The key to call the stack. Required.
	Type     StackType         `json:"type,omitempty"`      // A type for the stack. Required.
	QueueKey string            `json:"queue_key,omitempty"` // The key of a queue for the stack to listen to. Required
	Metadata map[string]string `json:"metadata"`            // Key-value metadata to associate with the queue. Required, but can be empty
}

RegisterStackRequest is the input type for [RegisterStack]. All of its fields are required.

type RegisterStackResponse

type RegisterStackResponse struct {
	ID               string            `json:"id"`
	OrganizationUUID string            `json:"organization_uuid"`
	ClusterQueueKey  string            `json:"cluster_queue_key"`
	Key              string            `json:"key"`
	Type             StackType         `json:"type"`
	Metadata         map[string]string `json:"metadata"`
	LastConnectedOn  *time.Time        `json:"last_connected_on"`
	State            StackState        `json:"state"`
}

RegisterStackResponse is the output type for [RegisterStack]. It contains all the information about a registered stack

type RequestOption

type RequestOption func(*StackAPIRequest) error

func WithNoRetry

func WithNoRetry() RequestOption

func WithRetrier

func WithRetrier(retrier *roko.Retrier) RequestOption

WithRetrier sets the retrier for the request, overriding the default retrier belonging to the Client.

type ScheduledJob

type ScheduledJob struct {
	ID              string    `json:"id"`                // The UUID of the job
	Priority        int       `json:"priority"`          // The priority of the job; higher priority jobs should be scheduled first
	AgentQueryRules []string  `json:"agent_query_rules"` // The agent tags that must be matched to run the job
	ScheduledAt     time.Time `json:"scheduled_at"`      // When the job was scheduled
	Pipeline        Pipeline  `json:"pipeline"`          // The pipeline the job belongs to
	Build           Build     `json:"build"`             // The build the job belongs to
	Step            Step      `json:"step"`              // The step the job was created by
}

ScheduledJob represents the metadata for a job that's in the scheduled state.

type StackAPIRequest

type StackAPIRequest struct {
	*http.Request
	// contains filtered or unexported fields
}

type StackNotification

type StackNotification struct {
	JobUUID   string    `json:"job_uuid"`
	Detail    string    `json:"detail"`
	Timestamp time.Time `json:"timestamp,omitzero"`
}

type StackNotificationError

type StackNotificationError struct {
	Error   string `json:"error"`
	Indexes []int  `json:"indexes"`
}

type StackState

type StackState string

StackState enumerates the connection status of a stack

const (
	StackStateConnected    StackState = "connected"
	StackStateDisconnected StackState = "disconnected"
	StackStateLost         StackState = "lost"
)

type StackType

type StackType string

StackType enumerates a few broad categories of stack. Use of StackTypeKubernetes and StackTypeElastic are discouraged for non-first-party stacks.

const (
	StackTypeKubernetes StackType = "kubernetes" // Reserved for use by the first-party agent-stack-k8s
	StackTypeElastic    StackType = "elastic"    // Reserved for use by the first-party elastic-stack-for-aws

	// For use by custom stacks. If you're reading these docs and you don't work at buildkite, this is almost certainly the
	// stack type you should be using, even if your stack is backed by Kubernetes
	StackTypeCustom StackType = "custom"
)

type Step

type Step struct {
	Key string `json:"key"`
}

Step represents the step that created a job.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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