### Install the example with go install Source: https://github.com/actions/scaleset/blob/main/examples/dockerscaleset/README.md Installs the example binary from the latest version of the module. Requires Go and network access to the module. ```bash go install github.com/actions/scaleset/examples/dockerscaleset@latest ``` -------------------------------- ### Install scaleset with go get Source: https://github.com/actions/scaleset/blob/main/README.md Install the scaleset Go module using the go get command. ```bash go get github.com/actions/scaleset@latest ``` -------------------------------- ### NewClientWithGitHubApp error handling example Source: https://github.com/actions/scaleset Shows error handling for NewClientWithGitHubApp. Checks for "invalid credentials: app installation ID is required" and distinguishes malformed GitHubConfigURL via *url.Error. ```go client, err := scaleset.NewClientWithGitHubApp(cfg) if err != nil { // "invalid credentials: app installation ID is required" var invalidErr *url.Error if errors.As(err, &invalidErr) { // malformed GitHubConfigURL instead of a credential problem } return err } ``` -------------------------------- ### Install with GONOSUMDB and GOPRIVATE Source: https://github.com/actions/scaleset/blob/main/examples/dockerscaleset/README.md Alternative installation command that sets GONOSUMDB and GOPRIVATE environment variables to bypass checksum database and private module access issues. ```bash GONOSUMDB=github.com/actions/scaleset GOPRIVATE=github.com/actions/scaleset go install github.com/actions/scaleset/examples/dockerscaleset@latest ``` -------------------------------- ### New function usage example Source: https://github.com/actions/scaleset Example of creating a Listener with a session client and configuration. Returns an error if creation fails. ```go l, err := listener.New(sessionClient, listener.Config{ ScaleSetID: scaleSet.ID, MaxRunners: c.MaxRunners, Logger: logger.WithGroup("listener"), }) if err != nil { return err } ``` -------------------------------- ### Session usage example Source: https://github.com/actions/scaleset Example call to Session, logging the session ID and message queue URL. ```go sess := session.Session() log.Printf("session %s on queue %s", sess.SessionID, sess.MessageQueueURL) ``` -------------------------------- ### SetMaxRunners example Source: https://github.com/actions/scaleset Example usage of SetMaxRunners to raise capacity while running. ```go l.SetMaxRunners(20) // raise capacity while running ``` -------------------------------- ### Listener.Run method signature Source: https://github.com/actions/scaleset Starts the listener and processes messages with the given scaler. Validates the session, calls Scale with the initial message, then loops to get, scale, and delete messages. Returns ctx.Err() on cancellation or wraps failures. ```go // listener/listener.go:126 func (l *Listener) Run(ctx context.Context, scaler Scaler) error ``` -------------------------------- ### Scaler implementation example Source: https://github.com/actions/scaleset Example implementation of the Scaler interface from examples/dockerscaleset/scaler.go. Handles nil messages, acquires jobs, marks runners busy, and scales based on statistics. ```go type Scaler struct { /* ... */ } func (s *Scaler) Scale(ctx context.Context, msg *scaleset.RunnerScaleSetMessage) error { if msg == nil { return nil } if len(msg.JobAvailableMessages) > 0 { if _, err := s.sessionClient.AcquireJobs(ctx, runnerRequestIDs(msg)); err != nil { return err } } for _, started := range msg.JobStartedMessages { s.runners.markBusy(started.RunnerName) } for _, done := range msg.JobCompletedMessages { // remove the runner's container, release resources } if msg.Statistics != nil { s.scaleTo(msg.Statistics.TotalAssignedJobs) } return nil } ``` -------------------------------- ### MessageSessionClient usage example Source: https://github.com/actions/scaleset Example of creating a message session client and closing it after use. The session is created eagerly and must be closed to release resources. ```go session, err := client.MessageSessionClient(ctx, scaleSetID, hostname) if err != nil { return err } defer session.Close(context.Background()) ``` -------------------------------- ### Customize retry policy with WithRetry Source: https://github.com/actions/scaleset/blob/main/README.md WithRetry replaces the retry policy wholesale, so start from DefaultRetryConfig when tweaking. This example sets Max to 8. RetryConfig{} or Max: 0 disables retries entirely. ```go retry := scaleset.DefaultRetryConfig() retry.Max = 8 client, err := scaleset.NewClientWithPersonalAccessToken(config, scaleset.WithRetry(retry), ) ``` -------------------------------- ### GitHubAppAuth.Validate usage example Source: https://github.com/actions/scaleset Example of calling Validate on a GitHubAppAuth instance and handling the error. Used by NewClientWithGitHubApp and examples/dockerscaleset to choose between App and PAT auth. ```go auth := scaleset.GitHubAppAuth{ClientID: "Iv1.abc", InstallationID: 123, PrivateKey: pem} if err := auth.Validate(); err != nil { return err } ``` -------------------------------- ### NewClientWithPersonalAccessToken example Source: https://github.com/actions/scaleset Creates a client authenticating with a PAT. Requires GitHubConfigURL and PersonalAccessToken. Shows usage with WithHTTPClient and WithRetry options. ```go client, err := scaleset.NewClientWithPersonalAccessToken( scaleset.NewClientWithPersonalAccessTokenConfig{ GitHubConfigURL: "https://github.com/org/repo", PersonalAccessToken: os.Getenv("GITHUB_PAT"), }, scaleset.WithHTTPClient(scaleset.NewHTTPClient(scaleset.HTTPClientConfig{})), scaleset.WithRetry(scaleset.DefaultRetryConfig()), ) if err != nil { return err } ``` -------------------------------- ### GetRunner example Source: https://github.com/actions/scaleset Example usage of GetRunner to check if a runner exists before removing it. Logs a message if the runner does not exist. ```go r, err := client.GetRunner(ctx, 123) if err != nil { return err } if r == nil { log.Println("runner 123 does not exist") } ``` -------------------------------- ### Config.Validate usage example Source: https://github.com/actions/scaleset Shows how to create a Config and call Validate, returning the error if validation fails. ```go cfg := listener.Config{ScaleSetID: 7, MaxRunners: 10, Logger: logger} if err := cfg.Validate(); err != nil { return err } ``` -------------------------------- ### GetRunnerByName example Source: https://github.com/actions/scaleset Example usage of GetRunnerByName to look up a runner by name and log its ID if found. ```go r, err := client.GetRunnerByName(ctx, "runner-abc12345") if err != nil { return err } if r != nil { log.Printf("runner %d is registered", r.ID) } ``` -------------------------------- ### CreateRunnerScaleSet example Source: https://github.com/actions/scaleset Example from README. Creates a scale set with name, runner group ID, labels, and runner settings. On error, errors.As can give the response snapshot. The scale set is deleted with context.WithoutCancel. ```go scaleSet, err := client.CreateRunnerScaleSet(ctx, &scaleset.RunnerScaleSet{ Name: "my-scale-set", RunnerGroupID: 1, Labels: []scaleset.Label{{Name: "gpu"}}, RunnerSetting: scaleset.RunnerSetting{DisableUpdate: true}, }) if err != nil { // e.g. scale set already exists -> *RequestResponseError wrapping // a 4xx; errors.As gives the response snapshot return err } defer client.DeleteRunnerScaleSet(context.WithoutCancel(ctx), scaleSet.ID) ``` -------------------------------- ### WithLogger usage example Source: https://github.com/actions/scaleset Shows how to configure the SDK to use a JSON logger writing to stdout when creating a client. ```go client, err := scaleset.NewClientWithPersonalAccessToken(config, scaleset.WithLogger(slog.New(slog.NewJSONHandler(os.Stdout, nil))), ) ``` -------------------------------- ### NewClientWithJWTProvider with KMS signer Source: https://github.com/actions/scaleset Creates a client using a custom JWTProvider (e.g., KMS/HSM-backed signing). Fails with "JWT provider is required" when provider is nil and "installation ID is required" when config.InstallationID is 0. The example uses a SignerJWTProvider with a crypto.Signer. ```go provider := &scaleset.SignerJWTProvider{ ClientID: "Iv1.abc123", Signer: myKMSSigner, // any crypto.Signer with an RSA key } client, err := scaleset.NewClientWithJWTProvider( scaleset.ClientWithJWTProviderConfig{ GitHubConfigURL: "https://github.com/my-org", InstallationID: 12345, }, provider, ) if err != nil { return err } ``` -------------------------------- ### Example: handling Listener.Run error Source: https://github.com/actions/scaleset Shows how to call Run and handle the expected context.Canceled error on shutdown, wrapping other failures. ```go if err := l.Run(ctx, scaler); !errors.Is(err, context.Canceled) { return fmt.Errorf("listener run failed: %w", err) } return nil ``` -------------------------------- ### UpdateRunnerScaleSet example Source: https://github.com/actions/scaleset Example usage: fetches an existing scale set, appends a label, then updates it. Requires a valid client and context; returns error on failure. ```go ss, err := client.GetRunnerScaleSet(ctx, groupID, "web") if err != nil { return err } ss.Labels = append(ss.Labels, scaleset.Label{Name: "large"}) updated, err := client.UpdateRunnerScaleSet(ctx, ss.ID, ss) if err != nil { return err } ``` -------------------------------- ### Example: Using JWTProviderFunc with NewClientWithJWTProvider Source: https://github.com/actions/scaleset Shows how to wrap a function that fetches a JWT from an external service and pass it to NewClientWithJWTProvider. ```go provider := scaleset.JWTProviderFunc(func(ctx context.Context) (string, error) { return getJWTFromExternalService(ctx) }) client, err := scaleset.NewClientWithJWTProvider(cfg, provider) if err != nil { return err } ``` -------------------------------- ### DebugInfo usage example Source: https://github.com/actions/scaleset Shows how to call DebugInfo on a client created with NewClientWithPersonalAccessToken and log the result. The returned JSON includes fields like has_proxy and has_root_ca. ```go client, _ := scaleset.NewClientWithPersonalAccessToken(cfg) log.Println(client.DebugInfo()) ``` -------------------------------- ### NewClientWithGitHubApp example Source: https://github.com/actions/scaleset Creates a client authenticating as a GitHub App. Requires GitHubConfigURL and GitHubAppAuth with all fields. PEM private key parsed into internal pemJWTProvider. Validation errors wrapped as "invalid credentials: ...". ```go client, err := scaleset.NewClientWithGitHubApp(scaleset.ClientWithGitHubAppConfig{ GitHubConfigURL: "https://github.com/my-org", GitHubAppAuth: scaleset.GitHubAppAuth{ ClientID: "Iv1.abc", InstallationID: 12345, PrivateKey: string(pemBytes), }, SystemInfo: scaleset.SystemInfo{System: "my-autoscaler", Version: "1.0.0"}, }) ``` -------------------------------- ### Example: defer session.Close Source: https://github.com/actions/scaleset Shows how to close the message session after creating it. The example creates a session client and defers Close to ensure the session is deleted when the surrounding function returns. ```go session, err := client.MessageSessionClient(ctx, scaleSetID, owner) if err != nil { return err } defer session.Close(context.Background()) ``` -------------------------------- ### RemoveRunner example Source: https://github.com/actions/scaleset Example usage of RemoveRunner: first checks if the runner exists with GetRunner, then removes it if present. ```go if r, err := client.GetRunner(context.Background(), id); err == nil && r != nil { if err := client.RemoveRunner(context.Background(), int64(r.ID)); err != nil { return err } } ``` -------------------------------- ### SetSystemInfo usage example (from examples/dockerscaleset/main.go) Source: https://github.com/actions/scaleset Informs GitHub of the scale set ID once it is created. The systemInfo function returns a SystemInfo value with System set to "dockerscaleset" and the scale set ID. ```go scalesetClient.SetSystemInfo(systemInfo(scaleSet.ID)) // {System:"dockerscaleset", ScaleSetID: scaleSet.ID, ...} ``` -------------------------------- ### GenerateJitRunnerConfig example from examples/dockerscaleset/scaler.go Source: https://github.com/actions/scaleset Example usage of GenerateJitRunnerConfig from examples/dockerscaleset/scaler.go. Generates a JIT config with a unique runner name and handles errors. The encoded config is then passed to a runner via environment variable ACTIONS_RUNNER_INPUT_JITCONFIG. ```go jit, err := s.scalesetClient.GenerateJitRunnerConfig( ctx, &scaleset.RunnerScaleSetJitRunnerSetting{ Name: fmt.Sprintf("runner-%s", uuid.NewString()[:8]), }, s.scaleSetID, ) if err != nil { return "", fmt.Errorf("failed to generate JIT config: %w", err) } // Hand the encoded config to a runner (container/VM/process): // Cmd: ["/home/runner/run.sh"] // Env: ["ACTIONS_RUNNER_INPUT_JITCONFIG=" + jit.EncodedJITConfig] ``` -------------------------------- ### ListRunnerScaleSets usage example Source: https://github.com/actions/scaleset Example usage of ListRunnerScaleSets. Iterates over returned scale sets and logs their ID, name, and total assigned jobs. ```go scaleSets, err := client.ListRunnerScaleSets(ctx, runnerGroupID) if err != nil { return err } for _, ss := range scaleSets { log.Printf("scale set %d (%s): %d jobs assigned", ss.ID, ss.Name, ss.Statistics.TotalAssignedJobs) } ``` -------------------------------- ### Example: Using SignerJWTProvider with NewClientWithJWTProvider Source: https://github.com/actions/scaleset Shows how to create a SignerJWTProvider with a KMS-backed signer and pass it to NewClientWithJWTProvider. The signer must have an RSA key. ```go provider := &scaleset.SignerJWTProvider{ ClientID: "Iv1.abc123", Signer: myKMSSigner, // any crypto.Signer with an RSA key } client, err := scaleset.NewClientWithJWTProvider( scaleset.ClientWithJWTProviderConfig{ GitHubConfigURL: "https://github.com/my-org", InstallationID: 12345, }, provider, ) ``` -------------------------------- ### GetRunnerScaleSet usage example Source: https://github.com/actions/scaleset Shows how to call GetRunnerScaleSet and handle the nil result when the scale set does not exist. The example logs a message and returns nil if scaleSet is nil. ```go scaleSet, err := client.GetRunnerScaleSet(ctx, runnerGroupID, "my-scale-set") if err != nil { return err } if scaleSet == nil { log.Println("scale set does not exist yet") return nil } ``` -------------------------------- ### GetRunnerScaleSetByID usage example Source: https://github.com/actions/scaleset Example usage of GetRunnerScaleSetByID. Checks for nil result to handle not-found case. ```go ss, err := client.GetRunnerScaleSetByID(ctx, 42) if err != nil { return err } if ss == nil { log.Println("scale set 42 not found") } ``` -------------------------------- ### WithRequestRetry usage example Source: https://github.com/actions/scaleset Shows a per-call rate-limit policy using WithRequestRetry, setting a custom OnRateLimit and MaxElapsed. The example also demonstrates handling a RateLimitError by requeueing after the retry-after duration. ```go ctx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() ctx = scaleset.WithRequestRetry(ctx, func(c *scaleset.RetryConfig) { c.OnRateLimit = scaleset.RateLimitRetries( scaleset.RateLimitRule{}, // primary: return immediately scaleset.RateLimitRule{MaxRetries: 2, MaxWait: 5 * time.Second}, // secondary: short retry ) c.MaxElapsed = 20 * time.Second }) jit, err := client.GenerateJitRunnerConfig(ctx, setting, scaleSetID) var rl *scaleset.RateLimitError if errors.As(err, &rl) { return ctrl.Result{RequeueAfter: max(rl.RetryAfter, minBackoff)}, nil } ``` -------------------------------- ### Error handling example with RateLimitError Source: https://github.com/actions/scaleset Example error handling for GetMessage: checks for RateLimitError to requeue after RetryAfter, otherwise returns the error. Notes that 401 is handled internally. ```go msg, err := session.GetMessage(ctx, lastMessageID, maxCapacity) if err != nil { var rl *scaleset.RateLimitError if errors.As(err, &rl) { // requeue after rl.RetryAfter } return err } // A 401 during polling is handled internally: the session is refreshed // and the poll retried once before any error reaches the caller. ``` -------------------------------- ### GetRunnerGroupByName example Source: https://github.com/actions/scaleset Example usage of GetRunnerGroupByName. The runnerGroup parameter can be a specific name or scaleset.DefaultRunnerGroup ("default"). ```go group, err := client.GetRunnerGroupByName(ctx, "linux-arm64") if err != nil { return err } runnerGroupID := group.ID ``` -------------------------------- ### Client.DebugInfo Source: https://github.com/actions/scaleset Returns a JSON string with diagnostics about the HTTP client configuration, including proxy and root CA usage, and system info. Useful for debugging client setup. ```APIDOC ## Client.DebugInfo ### Description Returns a JSON string with diagnostics: whether the HTTP client uses a proxy and/or a custom root CA, and the current system info (user-agent string). Proxy/CA settings are reported as `false`/unknown when the supplied HTTP client does not expose an `*http.Transport`; environment-proxy detection evaluates the transport's `Proxy` function for the GitHub config URL on each call. ### Method Function ### Signature `func (c *Client) DebugInfo() string` ### Parameters - (receiver) `*Client` - The client to inspect ### Return `string` - JSON like `{"has_proxy":false,"has_root_ca":false,"system_info":"{...}"}` (marshal errors are ignored and produce empty fields). ### Example ```go client, _ := scaleset.NewClientWithPersonalAccessToken(cfg) log.Println(client.DebugInfo()) ``` ``` -------------------------------- ### Polling loop example Source: https://github.com/actions/scaleset Example polling loop from README: calls GetMessage, handles nil (202) by continuing, updates lastMessageID, scales based on statistics, and deletes the message. ```go var lastMessageID int for { msg, err := session.GetMessage(ctx, lastMessageID, maxCapacity) if err != nil { return err } if msg == nil { continue // 202: no messages, poll again } lastMessageID = msg.MessageID // Scale on statistics, not message counts: desired := msg.Statistics.TotalAssignedJobs scaleToDesired(desired) if err := session.DeleteMessage(ctx, msg.MessageID); err != nil { return err } } ``` -------------------------------- ### Build HTTP client with NewHTTPClient Source: https://github.com/actions/scaleset/blob/main/README.md NewHTTPClient builds a sensible *http.Client for common cases. Leaving Timeout unset applies DefaultTimeout (5 minutes). The example shows configuring RootCAs and client certificates for mTLS. ```go httpClient := scaleset.NewHTTPClient(scaleset.HTTPClientConfig{ RootCAs: myCertPool, Certificates: []tls.Certificate{myClientCert}, // mTLS }) ``` -------------------------------- ### CreateRunnerScaleSet error example Source: https://github.com/actions/scaleset Error example showing validation failure when Name and Labels are empty. The error message is "validating runner scale set: runner scale set must have a name or at least one label". errors.Is with scaleset.ConflictError indicates a 409 from the server. ```go _, err := client.CreateRunnerScaleSet(ctx, &scaleset.RunnerScaleSet{}) // "validating runner scale set: runner scale set must have a name or at least one label" if errors.Is(err, scaleset.ConflictError) { // 409 from the server } ``` -------------------------------- ### WithRetry usage example Source: https://github.com/actions/scaleset Shows how to set the maximum retry count to 8 using WithRetry when creating a client with a personal access token. ```go retry := scaleset.DefaultRetryConfig() retry.Max = 8 client, err := scaleset.NewClientWithPersonalAccessToken(config, scaleset.WithRetry(retry), ) ``` -------------------------------- ### Checking ErrInvalidGitHubConfigURL with errors.Is Source: https://github.com/actions/scaleset Example of wrapping constructor failure and checking the sentinel error to fix the GitHubConfigURL. ```go client, err := scaleset.NewClientWithPersonalAccessToken(cfg) if errors.Is(err, scaleset.ErrInvalidGitHubConfigURL) { // fix GitHubConfigURL } ``` -------------------------------- ### Listener.Run Source: https://github.com/actions/scaleset Starts the listener and processes messages with the given scaler. It validates the session, calls the scaler with a synthetic initial message, then polls for messages and scales until the context is canceled. ```APIDOC ## Listener.Run ### Description Starts the listener and processes messages with the given scaler. It validates the session, calls the scaler with a synthetic initial message, then polls for messages and scales until the context is canceled. ### Method `func (l *Listener) Run(ctx context.Context, scaler Scaler) error` ### Parameters - `ctx` (context.Context) - Required - Canceling it stops the loop and returns `ctx.Err()` (typically `context.Canceled`) - `scaler` (Scaler) - Required - Message handler ### Return `error` — `context.Canceled` (or other ctx error) on shutdown, else a wrapped failure. ### Flow 1. Validates the current session from `client.Session()`: fails with `"initial session is nil"` if `SessionID == uuid.Nil`, and `"session statistics is nil"` if `Statistics == nil`. 2. Calls `scaler.Scale` once with the synthetic initial message (`InitialMessageID`); 3. Loops: `client.GetMessage(ctx, lastMessageID, maxCapacity)` → `scaler.Scale(ctx, msg)` → if `msg != nil`, update `lastMessageID` and `client.DeleteMessage(context.WithoutCancel(ctx), msg.MessageID)` — the ack is not canceled by ctx shutdown. A nil message leaves `lastMessageID` unchanged. 4. Returns `ctx.Err()` on cancellation; otherwise wraps failures as `"failed to get message: ..."`, `"failed to scale: ..."`, or `"failed to delete the message %d: ..."`. ### Request Example ```go if err := l.Run(ctx, scaler); !errors.Is(err, context.Canceled) { return fmt.Errorf("listener run failed: %w", err) } return nil ``` ``` -------------------------------- ### NewClientWithJWTProvider Source: https://github.com/actions/scaleset Creates a client using a custom JWTProvider (e.g. KMS/HSM-backed signing). Fails with "JWT provider is required" when provider == nil and "installation ID is required" when config.InstallationID == 0. ```APIDOC ## NewClientWithJWTProvider ### Description Creates a client using a custom [`JWTProvider`](./jwt-provider.md) (e.g. KMS/HSM-backed signing). Fails with `"JWT provider is required"` when `provider == nil` and `"installation ID is required"` when `config.InstallationID == 0`. ### Parameters #### Request Body - `config.GitHubConfigURL` (string) - Required - Registration URL - `config.InstallationID` (int64) - Required - GitHub App installation ID - `config.SystemInfo` ([`SystemInfo`](#type-systeminfo)) - Optional - System identification - `provider` ([`JWTProvider`](./jwt-provider.md)) - Required - Supplies RS256 app JWTs - `options` (`...HTTPOption`) - Optional - See [http-client.md](./http-client.md) ### Request Example ```go provider := &scaleset.SignerJWTProvider{ ClientID: "Iv1.abc123", Signer: myKMSSigner, // any crypto.Signer with an RSA key } client, err := scaleset.NewClientWithJWTProvider( scaleset.ClientWithJWTProviderConfig{ GitHubConfigURL: "https://github.com/my-org", InstallationID: 12345, }, provider, ) if err != nil { return err } ``` ``` -------------------------------- ### AcquireJobs usage example from scaler.go Source: https://github.com/actions/scaleset Shows how to call AcquireJobs with request IDs extracted from JobAvailable messages. The call is safe to repeat on redelivery because acquiring an already-acquired job is a no-op. ```go if len(msg.JobAvailableMessages) > 0 { requestIDs := make([]int64, 0, len(msg.JobAvailableMessages)) for _, job := range msg.JobAvailableMessages { requestIDs = append(requestIDs, job.RunnerRequestID) } if _, err := s.sessionClient.AcquireJobs(ctx, requestIDs); err != nil { return fmt.Errorf("failed to acquire jobs: %w", err) } } // Acquiring an already-acquired job is a no-op, so this is safe to // repeat when a message is redelivered after an error. ``` -------------------------------- ### GenerateJitRunnerConfig error handling for rate limit Source: https://github.com/actions/scaleset Error handling example for GenerateJitRunnerConfig when rate limited. Uses errors.As to detect RateLimitError and requeues after the server's hint instead of blocking. ```go jit, err := client.GenerateJitRunnerConfig(ctx, setting, scaleSetID) var rl *scaleset.RateLimitError if errors.As(err, &rl) { // Requeue after the server's hint instead of blocking: return ctrl.Result{RequeueAfter: max(rl.RetryAfter, minBackoff)}, nil } if err != nil { return err } ``` -------------------------------- ### GetRunnerScaleSet error inspection example Source: https://github.com/actions/scaleset Demonstrates inspecting the response snapshot when GetRunnerScaleSet returns an error. Uses errors.As to check for *scaleset.RequestResponseError and logs the status code and X-GitHub-Request-Id header from the response. ```go _, err := client.GetRunnerScaleSet(ctx, 1, "missing") var rerr *scaleset.RequestResponseError if errors.As(err, &rerr) && rerr.Response != nil { log.Printf("status=%d request_id=%s", rerr.Response.StatusCode, rerr.Response.Header.Get("X-GitHub-Request-Id")) } ``` -------------------------------- ### RateLimitRetries usage example Source: https://github.com/actions/scaleset Shows how to configure a retry policy with RateLimitRetries, setting primary to return immediately and secondary to retry up to 2 times with a max wait of 5 seconds. The retry configuration is passed to NewClientWithPersonalAccessToken via WithRetry. ```go retry := scaleset.DefaultRetryConfig() retry.OnRateLimit = scaleset.RateLimitRetries( scaleset.RateLimitRule{}, // primary: return immediately scaleset.RateLimitRule{MaxRetries: 2, MaxWait: 5 * time.Second}, // secondary: short retry ) client, err := scaleset.NewClientWithPersonalAccessToken(config, scaleset.WithRetry(retry), ) ``` -------------------------------- ### Inspect HTTP failures with errors.As Source: https://github.com/actions/scaleset/blob/main/README.md Demonstrates how to inspect a *scaleset.RequestResponseError returned by any client method when a request fails, an unexpected HTTP status is received, or a required response body is missing or malformed. The example shows how to access response metadata such as status code and headers for logging. ```APIDOC ## Inspect HTTP failures with errors.As ### Description Use `errors.As` to unwrap a `*scaleset.RequestResponseError` from any outer error wrapping and inspect the final HTTP response metadata. This is useful for logging status codes, request IDs, and activity IDs when a client call fails. ### Method N/A (Go error handling pattern) ### Endpoint N/A (applies to all client methods) ### Parameters N/A ### Response #### Error Type - **`*scaleset.RequestResponseError`** - Returned for request failures, unexpected HTTP statuses, and missing or malformed required response bodies. Contains a `Response` field with response metadata. #### Response Fields (on `Response`) - **`StatusCode`** (int) - HTTP status code of the final response. - **`Header`** (http.Header) - Response headers, including `X-GitHub-Request-Id` and `ActivityId`. - **`Body`** (io.Reader) - Independent in-memory reader of the response body, even after decoding. - **`Request`** (sensitive) - The original request, may contain tokens or JIT configuration. ### Request Example ```go _, err := client.GetRunner(ctx, runnerID) if err != nil { var responseErr *scaleset.RequestResponseError if errors.As(err, &responseErr) && responseErr.Response != nil { resp := responseErr.Response log.Printf("GitHub response: status=%d request_id=%q activity_id=%q", resp.StatusCode, resp.Header.Get("X-GitHub-Request-Id"), resp.Header.Get("ActivityId"), ) } return err } ``` ### Notes - `Response` is nil when no response was received (e.g., transport-only failure). - `Response.Body` is an independent reader; closing it is a no-op. - `Unwrap()` returns `Err`, preserving the original cause and recognized status/domain errors. - Rate-limited failures support both `errors.As` to `*RateLimitError` and `*RequestResponseError`. - Treat `Response.Body` and `Response.Request` as sensitive; they may contain tokens or JIT configuration. ``` -------------------------------- ### DeleteMessage usage example Source: https://github.com/actions/scaleset Example call to DeleteMessage. If it returns an error, the message stays queued and will be redelivered. ```go if err := session.DeleteMessage(ctx, msg.MessageID); err != nil { return err // message stays queued and will be redelivered } ``` -------------------------------- ### GetRunnerByName method signature Source: https://github.com/actions/scaleset Method signature for fetching a runner by name. Issues GET _apis/distributedtask/pools/0/agents?agentName={runnerName}. Returns (nil, nil) when no match; fails with specific errors for multiple or null results. ```go // client.go:842 func (c *Client) GetRunnerByName(ctx context.Context, runnerName string) (*RunnerReference, error) ``` -------------------------------- ### DeleteRunnerScaleSet example Source: https://github.com/actions/scaleset Example usage: deletes the scale set with ID 42. Returns error on failure. ```go if err := client.DeleteRunnerScaleSet(ctx, 42); err != nil { return err } ``` -------------------------------- ### Client constructors signatures Source: https://github.com/actions/scaleset Three exported constructors returning (*Client, error). Common behavior: GitHubConfigURL parsed and validated, exactly one credential mode required, options applied before SDK defaults, nil HTTPOption safe. ```go // client.go:201 func NewClientWithGitHubApp(config ClientWithGitHubAppConfig, options ...HTTPOption) (*Client, error) // client.go:230 func NewClientWithPersonalAccessToken(config NewClientWithPersonalAccessTokenConfig, options ...HTTPOption) (*Client, error) // client.go:252 func NewClientWithJWTProvider(config ClientWithJWTProviderConfig, provider JWTProvider, options ...HTTPOption) (*Client, error) ``` -------------------------------- ### NewClientWithPersonalAccessToken Source: https://github.com/actions/scaleset Creates a client authenticating with a Personal Access Token (PAT). ```APIDOC ## NewClientWithPersonalAccessToken ### Description Creates a client authenticating with a Personal Access Token (PAT). ### Signature ```go func NewClientWithPersonalAccessToken(config NewClientWithPersonalAccessTokenConfig, options ...HTTPOption) (*Client, error) ``` ### Parameters - `config.GitHubConfigURL` (string) - Required - Registration URL (enterprise/org/repo) - `config.PersonalAccessToken` (string) - Required - GitHub PAT - `config.SystemInfo` (SystemInfo) - Optional - System identification (default: zero value) - `options` (...HTTPOption) - Optional - See http-client.md ### Response Returns `(*Client, error)`. ### Request Example ```go client, err := scaleset.NewClientWithPersonalAccessToken( scaleset.NewClientWithPersonalAccessTokenConfig{ GitHubConfigURL: "https://github.com/org/repo", PersonalAccessToken: os.Getenv("GITHUB_PAT"), }, scaleset.WithHTTPClient(scaleset.NewHTTPClient(scaleset.HTTPClientConfig{})), scaleset.WithRetry(scaleset.DefaultRetryConfig()), ) if err != nil { return err } ``` ``` -------------------------------- ### MessageSessionClient method signature Source: https://github.com/actions/scaleset Creates a MessageSessionClient for the given scale set and owner, creating the session eagerly. Returns (*MessageSessionClient, error) and wraps any session-creation failure as "failed to create message session: ...". ```go // client.go:750 func (c *Client) MessageSessionClient(ctx context.Context, runnerScaleSetID int, owner string, options ...HTTPOption) (*MessageSessionClient, error) ``` -------------------------------- ### NewHTTPClient Source: https://github.com/actions/scaleset Builds an HTTP client with the given configuration. All fields are optional. ```APIDOC ## NewHTTPClient ### Description Builds an HTTP client with the given configuration. All fields are optional. ### Signature `func NewHTTPClient(config HTTPClientConfig) HTTPClient` ### Parameters - **config** (HTTPClientConfig) - Required - The configuration for the HTTP client. ### HTTPClientConfig Fields - **RootCAs** (*x509.CertPool) - Optional - CA set for server verification. Default: host trust store. - **Certificates** ([]tls.Certificate) - Optional - mTLS client certificates presented on every connection. Default: nil. - **InsecureSkipVerify** (bool) - Optional - Disables server certificate verification (testing only). Default: false. - **Proxy** (ProxyFunc) - Optional - Proxy selector. Default: `http.ProxyFromEnvironment`. - **Timeout** (time.Duration) - Optional - Per-attempt timeout; retries excluded. Default: `DefaultTimeout` (5 min). ``` -------------------------------- ### Client.DebugInfo method signature (client.go:78) Source: https://github.com/actions/scaleset Returns a JSON string with diagnostics about the HTTP client's proxy and root CA settings, and the current system info. Proxy/CA settings are reported as false/unknown when the HTTP client does not expose an *http.Transport. Environment-proxy detection evaluates the transport's Proxy function for the GitHub config URL on each call. ```go // client.go:78 func (c *Client) DebugInfo() string ``` -------------------------------- ### SetSystemInfo and SystemInfo method signatures (client.go:305, 313) Source: https://github.com/actions/scaleset SetSystemInfo atomically updates the system metadata embedded in the User-Agent header of every request. SystemInfo returns the currently configured value. ```go // client.go:305 func (c *Client) SetSystemInfo(info SystemInfo) // client.go:313 func (c *Client) SystemInfo() SystemInfo ``` -------------------------------- ### NewClientWithGitHubApp Source: https://github.com/actions/scaleset Creates a client that authenticates as a GitHub App. The PEM private key is parsed into an internal pemJWTProvider. Validation errors are wrapped as "invalid credentials: ...". ```APIDOC ## NewClientWithGitHubApp ### Description Creates a client that authenticates as a GitHub App. The PEM private key is parsed into an internal pemJWTProvider. Validation errors are wrapped as "invalid credentials: ...". ### Signature ```go func NewClientWithGitHubApp(config ClientWithGitHubAppConfig, options ...HTTPOption) (*Client, error) ``` ### Parameters - `config.GitHubConfigURL` (string) - Required - URL of the enterprise, org, or repo to register against - `config.GitHubAppAuth` (GitHubAppAuth) - Required - App credentials (all fields required) - `config.SystemInfo` (SystemInfo) - Optional - System identification (default: zero value) - `options` (...HTTPOption) - Optional - See http-client.md ### Response Returns `(*Client, error)`. ### Request Example ```go client, err := scaleset.NewClientWithGitHubApp(scaleset.ClientWithGitHubAppConfig{ GitHubConfigURL: "https://github.com/my-org", GitHubAppAuth: scaleset.GitHubAppAuth{ ClientID: "Iv1.abc", InstallationID: 12345, PrivateKey: string(pemBytes), }, SystemInfo: scaleset.SystemInfo{System: "my-autoscaler", Version: "1.0.0"}, }) ``` ### Error Example ```go client, err := scaleset.NewClientWithGitHubApp(cfg) if err != nil { // "invalid credentials: app installation ID is required" var invalidErr *url.Error if errors.As(err, &invalidErr) { // malformed GitHubConfigURL instead of a credential problem } return err } ``` ``` -------------------------------- ### GET _apis/distributedtask/pools/0/agents/{id} Source: https://github.com/actions/scaleset Retrieves a runner by its ID. Returns a RunnerReference object, or null if the runner does not exist. ```APIDOC ## [GET] _apis/distributedtask/pools/0/agents/{id} ### Description Retrieves a runner by its ID. Returns a RunnerReference object, or null if the runner does not exist. ### Method GET ### Endpoint _apis/distributedtask/pools/0/agents/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the runner to retrieve. ### Response #### Success Response (200) - **RunnerReference** (object) - The runner details. If the response body is JSON `null`, the method returns `(nil, nil)`. ``` -------------------------------- ### New(client Client, config Config) (*Listener, error) Source: https://github.com/actions/scaleset Creates a Listener instance. Fails with 'client is required' for a nil client and 'invalid config: ...' when config.Validate() errors. ```APIDOC ## New(client Client, config Config) (*Listener, error) ### Description Creates a `Listener`. Fails with `"client is required"` for a nil client and `"invalid config: ..."` when `config.Validate()` errors. ### Parameters - `client` (Client) - Required - Message session client (e.g. `*scaleset.MessageSessionClient`) - `config` (Config) - Required - Scale set ID, max runners, logger ### Return `(*Listener, error)` ### Request Example ```go l, err := listener.New(sessionClient, listener.Config{ ScaleSetID: scaleSet.ID, MaxRunners: c.MaxRunners, Logger: logger.WithGroup("listener"), }) if err != nil { return err } ``` ``` -------------------------------- ### GET _apis/runtime/runnerscalesets/{id} Source: https://github.com/actions/scaleset Retrieves a single runner scale set by its ID. Returns null if the JSON response is null. ```APIDOC ## GET _apis/runtime/runnerscalesets/{id} ### Description Retrieves a single runner scale set by its ID. Returns null if the JSON response is null. ### Method GET ### Endpoint _apis/runtime/runnerscalesets/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the runner scale set. ### Response #### Success Response (200) - **RunnerScaleSet** - The runner scale set object. If the JSON response is null, returns null. ``` -------------------------------- ### New function signature Source: https://github.com/actions/scaleset Creates a Listener. Fails with "client is required" for a nil client and "invalid config: ..." when config.Validate() errors. ```go // listener/listener.go:77 func New(client Client, config Config) (*Listener, error) ``` -------------------------------- ### GET {MessageQueueURL}?lastMessageId={id} Source: https://github.com/actions/scaleset Retrieves a message from the message queue. Returns a RunnerScaleSetMessage on success, or null if the long poll times out. ```APIDOC ## [GET] {MessageQueueURL}?lastMessageId={id} ### Description Retrieves a message from the message queue. Returns a RunnerScaleSetMessage on success, or null if the long poll times out. ### Method GET ### Endpoint {MessageQueueURL}?lastMessageId={id} ### Parameters #### Query Parameters - **lastMessageId** (integer) - Optional - The ID of the last message received. Only included when `id > 0`. #### Headers - **Accept** (string) - Required - Must be `application/json; api-version=6.0-preview`. - **X-ScaleSetMaxCapacity** (integer) - Required - The maximum capacity of the scale set. - **Authorization** (string) - Required - Must be `Bearer `. ### Response #### Success Response (200) - **RunnerScaleSetMessage** (object) - The parsed message. The response envelope includes `messageId`, `messageType`, `body`, and `statistics`. #### Success Response (202) - Returns `(nil, nil)` when the long poll times out. #### Error Response (401) - Returns `MessageQueueTokenExpiredError`; the session is refreshed and the request is retried once. #### Error Response (other) - Returns `*RequestResponseError`. ``` -------------------------------- ### GET _apis/runtime/runnergroups/?groupName={name} Source: https://github.com/actions/scaleset Retrieves a runner group by its name. Returns the runner group if exactly one is found, otherwise an error. ```APIDOC ## GET _apis/runtime/runnergroups/?groupName={name} ### Description Retrieves a runner group by its name. Returns the runner group if exactly one is found, otherwise an error. ### Method GET ### Endpoint _apis/runtime/runnergroups/?groupName={name} ### Parameters #### Query Parameters - **groupName** (string) - Required - The name of the runner group. ### Response #### Success Response (200) - **count** (integer) - Number of runner groups found. - **value** (array of RunnerGroup) - List of runner groups. If count is 0, an error is returned. If count is 1, returns the RunnerGroup object. ``` -------------------------------- ### Import scaleset package Source: https://github.com/actions/scaleset/blob/main/README.md Import the scaleset package in Go code. ```go import "github.com/actions/scaleset" ``` -------------------------------- ### NewClientWithJWTProvider Source: https://github.com/actions/scaleset Creates a client that authenticates using a custom JWT provider. ```APIDOC ## NewClientWithJWTProvider ### Description Creates a client that authenticates using a custom JWT provider. ### Signature ```go func NewClientWithJWTProvider(config ClientWithJWTProviderConfig, provider JWTProvider, options ...HTTPOption) (*Client, error) ``` ### Parameters - `config` (ClientWithJWTProviderConfig) - Required - Configuration for the client - `provider` (JWTProvider) - Required - JWT provider implementation - `options` (...HTTPOption) - Optional - See http-client.md ### Response Returns `(*Client, error)`. ``` -------------------------------- ### GET _apis/distributedtask/pools/0/agents?agentName={name} Source: https://github.com/actions/scaleset Retrieves a runner by its name. Returns a RunnerReference object if exactly one runner matches, or null if none match. ```APIDOC ## [GET] _apis/distributedtask/pools/0/agents?agentName={name} ### Description Retrieves a runner by its name. Returns a RunnerReference object if exactly one runner matches, or null if none match. ### Method GET ### Endpoint _apis/distributedtask/pools/0/agents?agentName={name} ### Parameters #### Query Parameters - **agentName** (string) - Required - The name of the runner to retrieve. ### Response #### Success Response (200) - **RunnerReferenceList** (array) - The list of matching runners. If the response is `null`, an error is returned. If the count is 0, the method returns `(nil, nil)`. If the count is 1, the method returns `*RunnerReference`. ``` -------------------------------- ### GET _apis/runtime/runnerscalesets?runnerGroupId={id} Source: https://github.com/actions/scaleset Retrieves a list of runner scale sets for a specific runner group. Returns an error if the response object is null. ```APIDOC ## GET _apis/runtime/runnerscalesets?runnerGroupId={id} ### Description Retrieves a list of runner scale sets for a specific runner group. Returns an error if the response object is null. ### Method GET ### Endpoint _apis/runtime/runnerscalesets?runnerGroupId={id} ### Parameters #### Query Parameters - **runnerGroupId** (string) - Required - The ID of the runner group. ### Response #### Success Response (200) - **count** (integer) - Number of runner scale sets returned. - **value** (array of RunnerScaleSet) - List of runner scale sets. If the response object is null, an error is returned: "runner scale set list is null". ``` -------------------------------- ### Configure client-wide rate limit retries with WithRetry Source: https://github.com/actions/scaleset/blob/main/README.md Sets a custom OnRateLimit hook using RateLimitRetries with rules for primary and secondary limits. Apply via WithRetry when creating a client. ```go retry := scaleset.DefaultRetryConfig() retry.OnRateLimit = scaleset.RateLimitRetries( scaleset.RateLimitRule{}, // primary: return immediately scaleset.RateLimitRule{MaxRetries: 2, MaxWait: 5 * time.Second}, // secondary: short retry ) client, err := scaleset.NewClientWithPersonalAccessToken(config, scaleset.WithRetry(retry), ) ```