supermarket

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 21 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

cinc-supermarket-api

A Go client for the Chef Supermarket API.

Install

go get github.com/cinc-project/cinc-supermarket-api

Usage

Read endpoints are anonymous:

c, err := supermarket.NewClient(supermarket.Config{})
if err != nil {
    return err
}
cb, _, err := c.Cookbooks.Get(ctx, "apache2")
if err != nil {
    return err
}

Write endpoints (share, delete) use the Chef mixlib-authentication signed-header protocol (version 1.1, SHA-1 — the version the public Supermarket accepts). The credentials are the Supermarket username and the RSA private key registered on that user's Supermarket profile:

key, err := supermarket.LoadKeyFile("/home/me/.chef/me.pem")
if err != nil {
    return err
}
c, err := supermarket.NewClient(supermarket.Config{Username: "me", Key: key})
if err != nil {
    return err
}
if _, _, err := c.Cookbooks.Share(ctx, "apache2", "Web Servers", tarball); err != nil {
    return err
}

A Client with no credentials refuses write calls with ErrUnauthenticatedWrite without contacting the server.

A private Supermarket whose certificate comes from an internal CA is reached by trusting that CA, which keeps certificate verification on:

pem, err := os.ReadFile("/etc/ssl/internal-ca.pem")
if err != nil {
    return err
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(pem) {
    return errors.New("no certificates in internal-ca.pem")
}
c, err := supermarket.NewClient(
    supermarket.Config{BaseURL: "https://supermarket.example.internal"},
    supermarket.WithRootCAs(pool))
if err != nil {
    return err
}

WithSkipTLSVerify(true) turns verification off entirely. It is off by default and meant for local testing only.

The universe (every version of every cookbook with its dependencies) is tens of megabytes. Universe.Entries decodes it incrementally and yields one version at a time, so memory stays flat:

for e, err := range c.Universe.Entries(ctx) {
    if err != nil {
        return err // request, HTTP, decode or ctx error; iteration has stopped
    }
    fmt.Println(e.Cookbook, e.Version, e.Dependencies)
}

Breaking out of the loop early closes the response body. There is no total request timeout on this path; bound it with ctx.

Version helpers work on the version strings cookbooks return, without a full semver dependency: CompareVersions(a, b) orders two versions, LatestVersion(versions) picks the newest, and VersionFromURL(u) pulls the dotted version out of a /versions/<v> URL (Supermarket encodes the dots as underscores).

Runnable examples, including pagination, ErrNotFound handling and streaming /universe, are on pkg.go.dev.

Coverage

Resource Endpoint Method
Cookbook GET /api/v1/cookbooks List
Cookbook GET /api/v1/cookbooks/:name Get
Cookbook GET /api/v1/cookbooks/:name/contingent Contingent
Cookbook GET /api/v1/cookbooks/:name/versions/:v GetVersion
Cookbook GET /api/v1/cookbooks/:name/versions/:v/download Download
Cookbook POST /api/v1/cookbooks (signed, multipart) Share
Cookbook DELETE /api/v1/cookbooks/:name (signed) Delete
Cookbook DELETE /api/v1/cookbooks/:name/versions/:v (signed) DeleteVersion
Search GET /api/v1/search Cookbooks
Tools GET /api/v1/tools List
Tools GET /api/v1/tools/:slug Get
Tools GET /api/v1/tools-search Search
Users GET /api/v1/users/:username Get
Universe GET /universe Get
Universe GET /universe (streaming) GetStream
Universe GET /universe (one entry per version) Entries
Health GET /api/v1/health Status
Health GET /api/v1/metrics Metrics

Errors

Non-2xx responses are wrapped in an *ErrorResponse that decodes Supermarket's {error_messages, error_code} envelope. Use errors.Is(err, supermarket.ErrNotFound) (and friends) to check the class of failure rather than the HTTP status. The sentinel is derived from error_code first (production returns 404 with error_code=NOT_FOUND for a missing resource) and falls back to the status code.

Testing

go test ./... runs the unit suite: it's fast, deterministic, and needs neither network nor Ruby. It includes:

  • An always-on signing-version guard (internal/signing) asserting we sign with 1.0 or 1.1. Signing with 1.3 got a 401 on every share against supermarket.chef.io in production; the cause is unknown, so the guard pins the versions observed to work.
  • A contract replay suite that decodes recorded production responses under testdata/contract/ through the public types, so a decoder regression fails CI deterministically.

Two extra layers reach for outside resources and are gated so the default run stays fast:

  • Gem-backed verifier test (internal/signing): runs our signed headers through mixlib-authentication's real server-side SignatureVerification (the gold standard). Its 1.3 case only exercises the test harness's own version gate, not mixlib or Supermarket. It needs Ruby plus the mixlib-authentication gem (gem install mixlib-authentication); without them it skips cleanly rather than failing.

  • Live contract suite — the drift alarm against the real API:

    go test -tags contract ./...
    

    It needs network access to https://supermarket.chef.io and hits the anonymous read endpoints (list + pagination, search, cookbook show, a specific version, /universe, tools, and a user record) through the actual client. It asserts on shape, types, and required fields — not volatile values — and fails (naming the field) if production drifts from what the client depends on. It is intentionally excluded from the default suite.

    Coverage boundary: the live suite covers anonymous reads; the signed write path (share/delete) is guarded deterministically by the version guard and the mixlib verifier test. A true live signed upload still needs a Supermarket account or a local instance — future work.

License

Copyright 2026 The Cinc Project and Tim Smith.

Licensed under the Apache License 2.0. See NOTICE.

Documentation

Overview

Package supermarket is a Go client for the Chef Supermarket API.

Read endpoints (cookbooks, search, tools, users, /universe, health) are anonymous; build a Client with no credentials:

c, err := supermarket.NewClient(supermarket.Config{})
if err != nil {
	return err
}
cb, _, err := c.Cookbooks.Get(ctx, "apache2")
if err != nil {
	return err // errors.Is(err, supermarket.ErrNotFound) for a missing cookbook
}

Write endpoints (share, delete) use the Chef mixlib-authentication signed-header protocol (version 1.1, SHA-1 — the version the public Supermarket accepts). The credentials are the Supermarket username and the RSA private key whose public half is registered on that user's Supermarket profile:

key, err := supermarket.LoadKeyFile("/home/me/.chef/me.pem")
if err != nil {
	return err
}
c, err := supermarket.NewClient(supermarket.Config{Username: "me", Key: key})
if err != nil {
	return err
}
if _, _, err := c.Cookbooks.Share(ctx, "apache2", "Web Servers", tarball); err != nil {
	return err
}

All list and search endpoints share a paginated envelope; the generic Page[T] type carries the items along with Start/Items/Total for cursoring. Loop while Page.HasMore, passing Page.NextStart as the next Start.

The examples in this package show each of these in full.

Example (NotFound)

Supermarket reports a missing resource as 400 with error_code NOT_FOUND rather than 404. Match on the sentinel, not the status code.

package main

import (
	"context"
	"errors"
	"fmt"
	"log"

	supermarket "github.com/cinc-project/cinc-supermarket-api"
)

func main() {
	c, err := supermarket.NewClient(supermarket.Config{})
	if err != nil {
		log.Fatal(err)
	}

	_, _, err = c.Cookbooks.Get(context.Background(), "no-such-cookbook")
	switch {
	case errors.Is(err, supermarket.ErrNotFound):
		fmt.Println("cookbook does not exist")
	case err != nil:
		log.Fatal(err)
	}
}
Example (Pagination)

List returns one page at a time. Page.HasMore reports whether another page exists and Page.NextStart is the offset to request it with; a page with no items always ends the loop, even if Total claims more.

package main

import (
	"context"
	"fmt"
	"log"

	supermarket "github.com/cinc-project/cinc-supermarket-api"
)

func main() {
	c, err := supermarket.NewClient(supermarket.Config{})
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	opts := supermarket.ListOptions{Items: 100, Order: "most_downloaded"}
	for {
		page, _, err := c.Cookbooks.List(ctx, opts)
		if err != nil {
			log.Fatal(err)
		}
		for _, cb := range page.Items {
			fmt.Println(cb.Name)
		}
		if !page.HasMore() {
			break
		}
		opts.Start = page.NextStart()
	}
}

Index

Examples

Constants

View Source
const (
	OrderByName          = "by_name"
	OrderRecentlyUpdated = "recently_updated"
	OrderRecentlyAdded   = "recently_added"
	OrderMostDownloaded  = "most_downloaded"
	OrderMostFollowed    = "most_followed"
)

Cookbook list orderings for ListOptions.Order.

View Source
const (
	ToolTypeKnifePlugin       = "knife_plugin"
	ToolTypeOhaiPlugin        = "ohai_plugin"
	ToolTypeChefInfraTool     = "chef_infra_tool"
	ToolTypeChefInfraHandler  = "chef_infra_handler"
	ToolTypeKitchenDriver     = "kitchen_driver"
	ToolTypePowerShellModule  = "powershell_module"
	ToolTypeDSCResource       = "dsc_resource"
	ToolTypeComplianceProfile = "compliance_profile"
)

Tool types, for ToolSearchOptions.Type. These are the values Supermarket accepts; it ignores any other.

View Source
const DefaultBaseURL = "https://supermarket.chef.io"

DefaultBaseURL is the public Supermarket instance hosted by Progress.

View Source
const ToolOrderRecentlyAdded = "recently_added"

ToolOrderRecentlyAdded is the only tool ordering Supermarket supports besides the default (by name).

Variables

View Source
var (
	ErrNotFound             = errors.New("supermarket: not found")
	ErrUnauthorized         = errors.New("supermarket: unauthorized")
	ErrForbidden            = errors.New("supermarket: forbidden")
	ErrInvalidData          = errors.New("supermarket: invalid data")
	ErrUnauthenticatedWrite = errors.New("supermarket: write requires Username and Key")
	// ErrInvalidArgument is returned locally, without contacting the server,
	// when a caller passes a blank value for a required path segment such as
	// a cookbook name or version.
	ErrInvalidArgument = errors.New("supermarket: invalid argument")
	// ErrConflict matches a 409, which Supermarket returns when deleting the
	// only remaining version of a cookbook.
	ErrConflict = errors.New("supermarket: conflict")
	// ErrRateLimited matches a 429 that outlasted the client's retries.
	ErrRateLimited = errors.New("supermarket: rate limited")
)

Sentinel errors for use with errors.Is. Supermarket reports a missing resource as 404 with error_code NOT_FOUND; Unwrap maps the error_code (and, failing that, the status) to ErrNotFound, so match on the sentinel rather than the status code.

Functions

func CompareVersions

func CompareVersions(a, b string) int

CompareVersions compares two cookbook version strings using a relaxed semver ordering and returns -1, 0, or 1 in the usual sense (a<b, a==b, a>b).

Numeric base segments are compared numerically (so 1.10.0 > 1.2.0), missing trailing segments are treated as zero (1.0 == 1.0.0), and an empty string sorts below everything. A base segment that is not numeric is compared lexically and ranks above a numeric one, so a malformed version such as 1.0.x is ordered consistently rather than collapsing onto 1.0.0. A clean release outranks any pre-release of the same base; pre-release identifiers are compared per semver §11 (dot-separated, all-numeric identifiers compared numerically and ranking below alphanumeric ones, with a larger set of fields winning when all earlier ones are equal). Build metadata (everything after '+') is ignored. Supermarket versions are overwhelmingly plain "X.Y.Z", so this avoids pulling in a full semver dependency while still ordering the occasional pre-release sensibly.

Example
package main

import (
	"fmt"

	supermarket "github.com/cinc-project/cinc-supermarket-api"
)

func main() {
	fmt.Println(supermarket.CompareVersions("1.10.0", "1.2.0"))
	fmt.Println(supermarket.CompareVersions("1.0", "1.0.0"))
	fmt.Println(supermarket.CompareVersions("2.0.0-rc.1", "2.0.0"))
}
Output:
1
0
-1

func LatestVersion

func LatestVersion(versions []string) string

LatestVersion returns the highest version in versions per CompareVersions, or "" when versions is empty.

Example
package main

import (
	"fmt"

	supermarket "github.com/cinc-project/cinc-supermarket-api"
)

func main() {
	fmt.Println(supermarket.LatestVersion([]string{"1.2.0", "1.10.0", "1.9.3", "2.0.0-beta"}))
}
Output:
2.0.0-beta

func LoadKeyFile

func LoadKeyFile(path string) (*rsa.PrivateKey, error)

LoadKeyFile reads and parses an RSA private key from a file path.

Example

Write endpoints are signed with the RSA key registered on the user's Supermarket profile. A client without Username and Key returns ErrUnauthenticatedWrite from them without contacting the server.

package main

import (
	"context"
	"log"

	supermarket "github.com/cinc-project/cinc-supermarket-api"
)

func main() {
	key, err := supermarket.LoadKeyFile("/home/me/.chef/me.pem")
	if err != nil {
		log.Fatal(err)
	}
	c, err := supermarket.NewClient(supermarket.Config{
		Username: "me",
		Key:      key,
	})
	if err != nil {
		log.Fatal(err)
	}

	if _, _, err := c.Cookbooks.DeleteVersion(context.Background(), "my-cookbook", "0.1.0"); err != nil {
		log.Fatal(err)
	}
}

func ParseKey

func ParseKey(pemBytes []byte) (*rsa.PrivateKey, error)

ParseKey parses a PEM-encoded RSA private key (PKCS#1 or PKCS#8).

func VersionFromURL

func VersionFromURL(s string) string

VersionFromURL extracts the version segment from a Supermarket version URL like https://supermarket.chef.io/api/v1/cookbooks/nginx/versions/12_0_4 (optionally followed by /download or a query), returning "12.0.4". Supermarket encodes dots as underscores in these paths; either form is tolerated, so a bare "12.0.4" or "12_0_4" passes through unchanged.

Input that is not a version returns "". Previously the underscore-to-dot rewrite was applied unconditionally to whatever was left after trimming, which turned "my_cookbook" into "my.cookbook" and a URL with no /versions/ segment into "https:" — plausible-looking values that were never versions.

Example
package main

import (
	"fmt"

	supermarket "github.com/cinc-project/cinc-supermarket-api"
)

func main() {
	fmt.Println(supermarket.VersionFromURL("https://supermarket.chef.io/api/v1/cookbooks/nginx/versions/12_0_4"))
	fmt.Println(supermarket.VersionFromURL("https://supermarket.chef.io/api/v1/cookbooks/nginx/versions/12_0_4/download"))
	fmt.Printf("%q\n", supermarket.VersionFromURL("https://supermarket.chef.io/api/v1/cookbooks/nginx"))
}
Output:
12.0.4
12.0.4
""

Types

type Client

type Client struct {

	// Services.
	Cookbooks *CookbooksService
	Search    *SearchService
	Tools     *ToolsService
	Users     *UsersService
	Universe  *UniverseService
	Health    *HealthService
	// contains filtered or unexported fields
}

Client is a Chef Supermarket API client. It is safe for concurrent use.

A Client with no Username/Key may call only the anonymous read endpoints; write endpoints (share, delete) return ErrUnauthenticatedWrite without contacting the server.

func NewClient

func NewClient(cfg Config, opts ...Option) (*Client, error)

NewClient builds a Client from cfg and optional Options.

type Config

type Config struct {
	BaseURL  string          // http or https URL; defaults to DefaultBaseURL
	Username string          // Supermarket username (write endpoints only)
	Key      *rsa.PrivateKey // RSA private key registered on the user's profile (write endpoints only)
}

Config holds the parameters for constructing a Client. Username and Key are only needed for the write endpoints (share / delete); read endpoints work with an empty Config.

type Contingent added in v1.0.0

type Contingent struct {
	Name    string `json:"name"`    // name of the dependent cookbook
	Version string `json:"version"` // version of the dependent cookbook
	URL     string `json:"url"`     // API URL of that cookbook version
}

Contingent is one cookbook version that depends on the cookbook passed to Cookbooks.Contingent.

type Cookbook

type Cookbook struct {
	Name          string    `json:"name"`
	Maintainer    string    `json:"maintainer"`
	Description   string    `json:"description"`
	Category      string    `json:"category"`
	LatestVersion string    `json:"latest_version"`
	ExternalURL   string    `json:"external_url"`
	SourceURL     string    `json:"source_url"`
	IssuesURL     string    `json:"issues_url"`
	AverageRating *float64  `json:"average_rating"`
	CreatedAt     time.Time `json:"created_at"`
	UpdatedAt     time.Time `json:"updated_at"`
	Deprecated    bool      `json:"deprecated"`
	// Replacement is the API URL of the cookbook suggested in place of a
	// deprecated one. Supermarket sends it only when Deprecated is true and
	// a replacement was named; otherwise it is empty.
	Replacement   string          `json:"replacement"`
	UpForAdoption bool            `json:"up_for_adoption"`
	Versions      []string        `json:"versions"`
	Metrics       CookbookMetrics `json:"metrics"`
}

Cookbook is the full cookbook representation returned by GET /cookbooks/:name.

type CookbookMetrics

type CookbookMetrics struct {
	Downloads     Downloads `json:"downloads"`
	Followers     int       `json:"followers"`
	Collaborators int       `json:"collaborators"`
}

CookbookMetrics is the metrics sub-object of a Cookbook.

type CookbookSummary

type CookbookSummary struct {
	Name        string `json:"cookbook_name"`
	Description string `json:"cookbook_description"`
	URL         string `json:"cookbook"`
	Maintainer  string `json:"cookbook_maintainer"`
}

CookbookSummary is the lighter shape returned by list and search.

type CookbookVersion

type CookbookVersion struct {
	Version       string            `json:"version"`
	License       string            `json:"license"`
	TarballSize   int64             `json:"tarball_file_size"`
	AverageRating *float64          `json:"average_rating"`
	PublishedAt   time.Time         `json:"published_at"`
	Cookbook      string            `json:"cookbook"` // URL of the cookbook
	File          string            `json:"file"`     // URL of the tarball
	Dependencies  map[string]string `json:"dependencies"`
	// Supports maps platform name to a version constraint. The API
	// returns this under the "supports" key (mirroring metadata.rb).
	Supports       map[string]string `json:"supports"`
	QualityMetrics []QualityMetric   `json:"quality_metrics"`
}

CookbookVersion is the full version representation returned by GET /cookbooks/:name/versions/:version.

type CookbooksService

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

CookbooksService accesses the /cookbooks endpoints.

func (*CookbooksService) Contingent

func (s *CookbooksService) Contingent(ctx context.Context, name string) ([]Contingent, *Response, error)

Contingent returns the cookbook versions that depend on the named cookbook. A cookbook nothing depends on yields an empty slice.

func (*CookbooksService) Delete

func (s *CookbooksService) Delete(ctx context.Context, name string) (*Cookbook, *Response, error)

Delete removes an entire cookbook from Supermarket. The caller must own the cookbook (or be a Supermarket admin).

func (*CookbooksService) DeleteVersion

func (s *CookbooksService) DeleteVersion(ctx context.Context, name, version string) (*CookbookVersion, *Response, error)

DeleteVersion removes a single version of a cookbook.

func (*CookbooksService) Download

func (s *CookbooksService) Download(ctx context.Context, name, version string) (io.ReadCloser, *Response, error)

Download fetches the gzipped tarball for a cookbook version. The caller owns closing the returned body. Like GetVersion the version may be "latest" or any Semver form.

The download is not subject to the client's total-transaction timeout, which would otherwise truncate a large tarball mid-read. Bound it with ctx.

func (*CookbooksService) Get

func (s *CookbooksService) Get(ctx context.Context, name string) (*Cookbook, *Response, error)

Get returns the full record for a single cookbook by name.

Example

Read endpoints are anonymous, so a zero Config talks to the public Supermarket without credentials.

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	supermarket "github.com/cinc-project/cinc-supermarket-api"
)

func main() {
	c, err := supermarket.NewClient(supermarket.Config{})
	if err != nil {
		log.Fatal(err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	cb, _, err := c.Cookbooks.Get(ctx, "apache2")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(cb.Name, cb.LatestVersion)
}

func (*CookbooksService) GetVersion

func (s *CookbooksService) GetVersion(ctx context.Context, name, version string) (*CookbookVersion, *Response, error)

GetVersion returns a single cookbook version. The version may be "latest" or a Semver string in either dotted ("1.2.3") or underscore ("1_2_3") form; the dotted form is converted automatically.

func (*CookbooksService) List

List paginates the cookbook index.

func (*CookbooksService) Share

func (s *CookbooksService) Share(ctx context.Context, name, category string, tarball io.Reader) (*ShareResult, *Response, error)

Share uploads a new cookbook version. tarball is the gzipped tar of the cookbook directory (must contain metadata.json at its root); category is the Supermarket category string (e.g. "Web Servers"). Requires Username and Key on the Client.

Supermarket answers a successful share with only the cookbook's API URL, returned as ShareResult.URI; fetch the cookbook with Get for its details.

type Downloads

type Downloads struct {
	Total    int            `json:"total"`
	Versions map[string]int `json:"versions"`
}

Downloads splits a cookbook's download counter into the all-time total and a per-version breakdown.

type ErrorResponse

type ErrorResponse struct {
	Method     string   // request method
	Path       string   // request path
	StatusCode int      // HTTP status code
	Code       string   // server-supplied error_code (e.g. NOT_FOUND)
	Messages   []string // server-supplied error_messages
}

ErrorResponse describes a non-2xx response from Supermarket.

func (*ErrorResponse) Error

func (e *ErrorResponse) Error() string

func (*ErrorResponse) Unwrap

func (e *ErrorResponse) Unwrap() error

Unwrap maps the error_code (preferred) or HTTP status to a sentinel error for errors.Is.

type Health

type Health struct {
	Status      string            `json:"status"`
	Supermarket HealthSupermarket `json:"supermarket"`
	PostgreSQL  HealthPostgreSQL  `json:"postgresql"`
	Sidekiq     HealthSidekiq     `json:"sidekiq"`
	Redis       HealthRedis       `json:"redis"`
	// Features maps each feature flag (tools, fieri, announcement, github,
	// no_crawl) to whether it is enabled.
	Features map[string]bool `json:"features"`
}

Health is the status object returned by /health (and the /status alias). Status is "ok" when PostgreSQL, Redis and Sidekiq are all reachable. A subsystem that could not be reached reports only its Status ("unreachable" or "unknown"), leaving its metrics zero.

type HealthPostgreSQL added in v1.0.0

type HealthPostgreSQL struct {
	Status        string `json:"status"`
	WaitingOnLock int    `json:"waiting_on_lock"`
	Connections   int    `json:"connections"`
}

HealthPostgreSQL describes the database connection.

type HealthRedis added in v1.0.0

type HealthRedis struct {
	Status           string `json:"status"`
	UptimeInSeconds  int64  `json:"uptime_in_seconds"`
	ConnectedClients int    `json:"connected_clients"`
	UsedMemory       int64  `json:"used_memory"`
	UsedMemoryPeak   int64  `json:"used_memory_peak"`
}

HealthRedis describes the Redis server.

type HealthService

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

HealthService accesses the health / metrics endpoints.

func (*HealthService) Metrics

func (s *HealthService) Metrics(ctx context.Context) (map[string]any, *Response, error)

Metrics hits /api/v1/metrics and returns the raw decoded JSON. The shape is server-version-specific so callers receive map[string]any.

func (*HealthService) Status

func (s *HealthService) Status(ctx context.Context) (*Health, *Response, error)

Status hits /api/v1/health and returns the parsed status object.

type HealthSidekiq added in v1.0.0

type HealthSidekiq struct {
	Status         string  `json:"status"`
	Latency        float64 `json:"latency"` // seconds the oldest queued job has waited
	QueuedJobs     int     `json:"queued_jobs"`
	ScheduledJobs  int     `json:"scheduled_jobs"`
	RetryableJobs  int     `json:"retryable_jobs"`
	DeadJobs       int     `json:"dead_jobs"`
	TotalProcessed int64   `json:"total_processed"`
	TotalFailed    int64   `json:"total_failed"`
	ActiveWorkers  int     `json:"active_workers"`
}

HealthSidekiq describes the background job queue.

type HealthSupermarket added in v1.0.0

type HealthSupermarket struct {
	ExpiredOCIDTokens int `json:"expired_ocid_tokens"`
}

HealthSupermarket holds application-level health figures.

type ListOptions

type ListOptions struct {
	Start int
	Items int
	// Order, when set, is one of the Order* constants. The server sorts
	// by name when it is empty or unrecognized, and always lists
	// deprecated cookbooks after the rest.
	Order string
	// User, when set, restricts the result set to cookbooks owned by
	// that Supermarket username.
	User string
	// Platforms, when set, restricts the result set to cookbooks whose
	// versions declare support for any of these platforms (e.g. "debian").
	Platforms []string
}

ListOptions configures GET /cookbooks.

type Option

type Option func(*options)

Option customizes a Client.

func WithHTTPClient

func WithHTTPClient(c *http.Client) Option

WithHTTPClient sets a custom *http.Client. A nil client is ignored.

func WithMaxRetries

func WithMaxRetries(n int) Option

WithMaxRetries sets the retry count for idempotent (GET) requests.

func WithRetryBackoff added in v1.0.0

func WithRetryBackoff(d time.Duration) Option

WithRetryBackoff sets the base delay between retries of an idempotent (GET) request. Waits grow exponentially from this value and are jittered. Zero disables waiting entirely; a negative value is ignored.

func WithRootCAs added in v1.0.0

func WithRootCAs(pool *x509.CertPool) Option

WithRootCAs sets the certificate authorities the client trusts when verifying the server, replacing the system pool. Use it to reach a Supermarket whose certificate is issued by a private or internal CA without disabling verification. A nil pool is ignored.

Like WithSkipTLSVerify it requires the client's transport to be an *http.Transport; combining it with a custom RoundTripper is a NewClient error.

Example

A private Supermarket whose certificate is issued by an internal CA is reached by trusting that CA, which keeps certificate verification on.

package main

import (
	"context"
	"crypto/x509"
	"fmt"
	"log"
	"os"

	supermarket "github.com/cinc-project/cinc-supermarket-api"
)

func main() {
	pem, err := os.ReadFile("/etc/ssl/internal-ca.pem")
	if err != nil {
		log.Fatal(err)
	}
	pool := x509.NewCertPool()
	if !pool.AppendCertsFromPEM(pem) {
		log.Fatal("no certificates found in internal-ca.pem")
	}

	c, err := supermarket.NewClient(
		supermarket.Config{BaseURL: "https://supermarket.example.internal"},
		supermarket.WithRootCAs(pool),
	)
	if err != nil {
		log.Fatal(err)
	}

	cb, _, err := c.Cookbooks.Get(context.Background(), "apache2")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(cb.Name, cb.LatestVersion)
}

func WithSkipTLSVerify

func WithSkipTLSVerify(skip bool) Option

WithSkipTLSVerify disables TLS certificate verification, leaving the connection open to interception. It is off by default and meant for local testing only; to reach a Supermarket whose certificate comes from a private CA, use WithRootCAs, which keeps verification on.

It requires the client's transport to be an *http.Transport, since that is where the TLS config lives. Combining it with a custom RoundTripper is a NewClient error rather than a silent downgrade to http.DefaultTransport.

func WithUserAgent

func WithUserAgent(ua string) Option

WithUserAgent sets the User-Agent header.

type Page

type Page[T any] struct {
	Start int `json:"start"`
	Total int `json:"total"`
	Items []T `json:"items"`
}

Page is the envelope every Supermarket list/search response uses. Items carries the actual result rows; Start is the offset of the first.

Total is only as good as the server makes it. Supermarket reports the number of cookbooks on the whole server for Search.Cookbooks and for a Cookbooks.List filtered by User or Platforms, and the size of the returned page for Tools.Search. Only an unfiltered Cookbooks.List or Tools.List reports a true total. A page with no items is the reliable end-of-results signal.

func (Page[T]) HasMore

func (p Page[T]) HasMore() bool

HasMore reports whether the server has more results past this page. A page that carries no items is always terminal, even if Total claims otherwise — otherwise NextStart would not advance and a caller's pagination loop would spin forever.

func (Page[T]) NextStart

func (p Page[T]) NextStart() int

NextStart returns the Start offset a caller should pass to fetch the page that immediately follows p. Returns 0 when HasMore is false.

type QualityMetric

type QualityMetric struct {
	Name     string `json:"name"`
	Failed   bool   `json:"failed"`
	Feedback string `json:"feedback"`
}

QualityMetric is one entry in a cookbook version's quality_metrics array: the Fieri/cookstyle evaluation results shown on the version page (collaborator count, version tag, cookstyle, no-binaries, etc.).

type Response

type Response struct {
	*http.Response
}

Response wraps the raw HTTP response returned by an API call. It embeds *http.Response, so StatusCode, Header and Body are read directly off it.

For the decoding calls (everything returning a parsed type) the body has already been consumed and closed by the time the caller sees the Response, so it is useful only for its status and headers.

The streaming calls — Universe.GetStream and Cookbooks.Download — are the exception: they hand back the still-open body as their first return value, and Response.Body is that same ReadCloser. Closing it is the caller's job either way.

type SearchOptions

type SearchOptions struct {
	Q     string
	Start int
	Items int
}

SearchOptions configures a search query. Q is required; Start and Items follow the same convention as ListOptions.

type SearchService

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

SearchService accesses the fuzzy-search endpoints.

func (*SearchService) Cookbooks

Cookbooks runs a fuzzy search over cookbook name, description, and maintainer.

type ShareResult added in v1.0.0

type ShareResult struct {
	// URI is the API URL of the shared cookbook, e.g.
	// https://supermarket.chef.io/api/v1/cookbooks/apache2.
	URI string `json:"uri"`
}

ShareResult is the response to a successful Cookbooks.Share.

type Tool

type Tool struct {
	Name          string `json:"name"`
	Slug          string `json:"slug"`
	Type          string `json:"type"`
	SourceURL     string `json:"source_url"`
	Description   string `json:"description"`
	Instructions  string `json:"instructions"` // markdown
	Owner         string `json:"owner"`
	UpForAdoption bool   `json:"up_for_adoption"`
}

Tool is the full record returned by GET /tools/:slug.

type ToolSearchOptions added in v1.0.0

type ToolSearchOptions struct {
	Q     string // query; empty matches every tool
	Start int
	Items int
	Type  string // one of the ToolType* constants; empty means any type
	Order string // ToolOrderRecentlyAdded, or empty for by name
}

ToolSearchOptions configures GET /tools-search.

type ToolSummary

type ToolSummary struct {
	Name        string `json:"tool_name"`
	Type        string `json:"tool_type"`
	SourceURL   string `json:"tool_source_url"`
	Description string `json:"tool_description"`
	Owner       string `json:"tool_owner"`
	URL         string `json:"tool"`
}

ToolSummary is the lighter shape returned by list and search.

type ToolsListOptions

type ToolsListOptions struct {
	Start int
	Items int
	// Order, when set, is ToolOrderRecentlyAdded.
	Order string
}

ToolsListOptions configures GET /tools.

type ToolsService

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

ToolsService accesses the /tools endpoints.

func (*ToolsService) Get

func (s *ToolsService) Get(ctx context.Context, slug string) (*Tool, *Response, error)

Get returns a single tool by slug.

func (*ToolsService) List

List paginates the tools index.

func (*ToolsService) Search

Search runs a fuzzy search over the tools index.

Supermarket reports Total for this endpoint as the number of items in the returned page, not the number of matches, so Page.HasMore cannot tell whether more pages exist. Request the next Start until a page comes back empty.

type Universe

type Universe map[string]map[string]UniverseVersion

Universe is the full dependency graph of every cookbook version on the server. It is keyed by cookbook name then by version string.

type UniverseEntry added in v1.0.0

type UniverseEntry struct {
	Cookbook string
	Version  string
	UniverseVersion
}

UniverseEntry is one cookbook version from the universe.

type UniverseService

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

UniverseService accesses the /universe endpoint.

func (*UniverseService) Entries added in v1.0.0

Entries decodes the universe incrementally and yields one entry per cookbook version, so memory stays flat however large the document is. The request is sent when iteration starts, not when Entries is called.

It is built on GetStream: there is no total-transaction timeout, so bound the download with ctx. A request error, an error response, a malformed or truncated document, or ctx being cancelled mid-stream yields a single (zero, err) and ends the iteration; a clean end means the whole document was read. The response body is closed when iteration ends, including when the caller breaks out of the loop early.

func (*UniverseService) Get

Get returns the entire universe in one shot. The payload can be tens of megabytes; prefer Entries when memory pressure matters.

func (*UniverseService) GetStream

func (s *UniverseService) GetStream(ctx context.Context) (io.ReadCloser, *Response, error)

GetStream returns the universe body as a raw io.ReadCloser so the caller can decode it incrementally with json.Decoder. The caller owns closing the body. Most callers want Entries, which does that decoding and yields one UniverseEntry per cookbook version.

Streaming responses are not subject to the client's total-transaction timeout — a multi-megabyte universe would otherwise be truncated mid-read. Bound the download with ctx.

Example

GetStream hands back the raw /universe body so it can be decoded one cookbook at a time instead of holding the whole graph in memory. Bound the download with ctx: the client's total-transaction timeout does not apply to streams.

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"time"

	supermarket "github.com/cinc-project/cinc-supermarket-api"
)

func main() {
	c, err := supermarket.NewClient(supermarket.Config{})
	if err != nil {
		log.Fatal(err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
	defer cancel()

	body, _, err := c.Universe.GetStream(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer body.Close()

	dec := json.NewDecoder(body)
	if _, err := dec.Token(); err != nil { // opening '{'
		log.Fatal(err)
	}
	for dec.More() {
		tok, err := dec.Token() // cookbook name
		if err != nil {
			log.Fatal(err)
		}
		var versions map[string]supermarket.UniverseVersion
		if err := dec.Decode(&versions); err != nil {
			log.Fatal(err)
		}
		fmt.Println(tok.(string), len(versions))
	}
	if _, err := dec.Token(); err != nil { // closing '}'
		log.Fatal(err)
	}
}

type UniverseVersion

type UniverseVersion struct {
	// LocationType is "opscode": Supermarket keeps the legacy value because
	// Berkshelf matches on it.
	LocationType string `json:"location_type"`
	// LocationPath is the API base URL the version is served from.
	LocationPath string `json:"location_path"`
	// DownloadURL is the URL of this version's tarball.
	DownloadURL  string            `json:"download_url"`
	Dependencies map[string]string `json:"dependencies"`
}

UniverseVersion is one entry in the universe graph.

type User

type User struct {
	Username  string        `json:"username"`
	Name      string        `json:"name"`
	Company   string        `json:"company"`
	GitHub    []string      `json:"github"`
	Twitter   string        `json:"twitter"`
	Slack     string        `json:"slack"`
	Cookbooks UserCookbooks `json:"cookbooks"`
	Tools     UserTools     `json:"tools"`
}

User is the profile representation returned by GET /users/:username.

type UserCookbooks

type UserCookbooks struct {
	Owns         map[string]string `json:"owns"`
	Collaborates map[string]string `json:"collaborates"`
	Follows      map[string]string `json:"follows"`
}

UserCookbooks groups the cookbook relationships on a user profile.

Supermarket serializes each relationship as a JSON object mapping the cookbook name to its API URL (e.g. {"apache2": ".../cookbooks/apache2"}), NOT as an array of cookbook records — and it omits a relationship key entirely when it's empty, so an absent group decodes to a nil map. The contract suite (contract_live_test.go) is what pins this shape against the live API.

type UserTools

type UserTools struct {
	Owns         map[string]string `json:"owns"`
	Collaborates map[string]string `json:"collaborates"`
}

UserTools groups the tool relationships on a user profile. Like UserCookbooks, Supermarket maps each tool name to its API URL and omits the key when there are none.

type UsersService

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

UsersService accesses the /users endpoints.

func (*UsersService) Get

func (s *UsersService) Get(ctx context.Context, username string) (*User, *Response, error)

Get returns a user profile by username.

Directories

Path Synopsis
internal
signing
Package signing implements the Chef mixlib-authentication signed-header protocol used by Supermarket's write endpoints.
Package signing implements the Chef mixlib-authentication signed-header protocol used by Supermarket's write endpoints.

Jump to

Keyboard shortcuts

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