Mining/pkg/mining/version.go
Claude ee69484f5f
ax(mining): replace prose comments with usage examples in version.go
Comments on GitHubRelease and fetchGitHubVersionDirect restated what
the type names already said. Replaced with concrete call examples
per AX Principle 2 (comments as usage examples).

Co-Authored-By: Charon <charon@lethean.io>
2026-04-02 12:43:09 +01:00

87 lines
2.2 KiB
Go

package mining
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
var (
version = "dev"
commit = "none"
date = "unknown"
)
// v := mining.GetVersion() // "1.2.3" or "dev" when unset
func GetVersion() string {
return version
}
// c := mining.GetCommit() // "a1b2c3d" or "none" when unset
func GetCommit() string {
return commit
}
// d := mining.GetBuildDate() // "2026-04-02T00:00:00Z" or "unknown" when unset
func GetBuildDate() string {
return date
}
// release := &GitHubRelease{TagName: "v6.21.0", Name: "XMRig v6.21.0"}
type GitHubRelease struct {
TagName string `json:"tag_name"`
Name string `json:"name"`
}
// tag, err := FetchLatestGitHubVersion("xmrig", "xmrig") // "v6.21.0"
func FetchLatestGitHubVersion(owner, repo string) (string, error) {
cb := getGitHubCircuitBreaker()
result, err := cb.Execute(func() (interface{}, error) {
return fetchGitHubVersionDirect(owner, repo)
})
if err != nil {
// If circuit is open, try to return cached value with warning
if err == ErrCircuitOpen {
if cached, ok := cb.GetCached(); ok {
if tagName, ok := cached.(string); ok {
return tagName, nil
}
}
return "", fmt.Errorf("github API unavailable (circuit breaker open): %w", err)
}
return "", err
}
tagName, ok := result.(string)
if !ok {
return "", fmt.Errorf("unexpected result type from circuit breaker")
}
return tagName, nil
}
// tag, err := fetchGitHubVersionDirect("xmrig", "xmrig") // "v6.21.0"; called via circuit breaker
func fetchGitHubVersionDirect(owner, repo string) (string, error) {
url := fmt.Sprintf("https://api.github.com/repos/%s/%s/releases/latest", owner, repo)
resp, err := getHTTPClient().Get(url)
if err != nil {
return "", fmt.Errorf("failed to fetch version: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
io.Copy(io.Discard, resp.Body) // Drain body to allow connection reuse
return "", fmt.Errorf("failed to get latest release: unexpected status code %d", resp.StatusCode)
}
var release GitHubRelease
if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
return "", fmt.Errorf("failed to decode release: %w", err)
}
return release.TagName, nil
}