Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ commands and PR conventions).
`cleanup`, and runs in parallel.
- `integration/cincserverng` boots one in-memory cinc-server-ng and
runs the suite against it. A test that cinc-server-ng cannot pass is
listed in its `Target.Gaps` with the upstream issue URL, never
listed in its `Target.Gaps` with a reason (the upstream issue URL when
it is a server bug), never
deleted or special-cased; `suite.Run` fails on a gap that names no
test or gives no reason. Remove the gap once the issue is fixed.
- `integration/cincservererlang` runs the same suite against the CINC
Expand Down Expand Up @@ -123,14 +124,21 @@ down.
`transferClient` is copied before that and keeps the caller's policy, so
bookshelf/S3 transfers still follow redirects.
- Retries: GETs are retried on 5xx and on genuine wire failures, up to
`WithMaxRetries(n)` (default 2), with exponential backoff from 100ms.
`WithMaxRetries(n)` (default 2), with backoff doubling from 100ms up to
`maxBackoff` (10s), jittered over its upper half. 501 and 505 are not
retried. An `http.Client` timeout on a GET is retried, as chef-client
retries one.
Non-GET requests are retried only on a `503` (`retryable`): the server
refused them unprocessed (erchef does this when its key-generation pool
runs dry under parallel user/client creation), while a 500/502/504 or a
wire failure may follow a request that was applied. A 503's `Retry-After`
lengthens the wait, capped at `maxRetryAfter`. Every retry goes back
through `doOnce`, so it resends the same body and is re-signed with a
fresh timestamp. Context cancellation/deadline never retries. Only errors wrapped in `transportErr` are retriable — if you add
fresh timestamp. The caller's context ending never retries: `backoff`
checks `ctx.Err()`, which is how a caller's deadline is told apart from an
`http.Client` timeout (both match `context.DeadlineExceeded`); `giveUp`
then returns an error matching both `ctx.Err()` and the last failure.
Only errors wrapped in `transportErr` are retriable — if you add
a new failure point in `doOnce` that happens on the wire, mark it, or it
will never be retried; if it is client-side, do not, or it will be
retried pointlessly. A `transportErr` that is a failed certificate
Expand All @@ -139,7 +147,9 @@ down.
- Bookshelf transfers (`uploadFile`, `downloadFile`) are the exception to
"non-GET never retried": they go through `doTransfer`, which applies
the same `shouldRetry`/`backoff` policy to the pre-signed PUT as well,
because it is idempotent (content-addressed by checksum). They use
because it is idempotent (content-addressed by checksum), except that a
transfer timeout is not retried (a file too big for the limit would only
time out again). They use
`transferClient` (timeout `WithTransferTimeout`, default 10m), not
the API client's 30s timeout.

Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@ standard library.
node, _, err := c.Nodes.Get(ctx, "web01")
if errors.Is(err, cinc.ErrNotFound) {
// no such node
} else if err != nil {
return err
}
fmt.Println(node.Environment)

## Status

Expand Down
10 changes: 8 additions & 2 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,14 @@ func NewClient(cfg Config, opts ...Option) (*Client, error) {
// from the server root, so a path here (most often a pasted
// .../organizations/<org> URL) would be prefixed onto every request.
if base.Path != "" || base.RawQuery != "" || base.ForceQuery || base.Fragment != "" {
return nil, fmt.Errorf("cinc: ServerURL %q must be scheme://host[:port] with no path, query or fragment; "+
"use ParseServerURL to split an https://host/organizations/<org> URL into ServerURL and Org", cfg.ServerURL)
if strings.HasPrefix(base.Path, "/organizations/") {
return nil, fmt.Errorf("cinc: ServerURL %q includes the organization; "+
"use ParseServerURL to split an https://host/organizations/<org> URL into ServerURL and Org", cfg.ServerURL)
}
// A request is signed over the path the server sees; a proxy that
// strips a prefix would make every signature cover the wrong path.
return nil, fmt.Errorf("cinc: ServerURL %q must be scheme://host[:port], with no path, query or fragment "+
"(a server behind a path prefix is not supported)", cfg.ServerURL)
}
o := defaultOptions()
for _, opt := range opts {
Expand Down
4 changes: 2 additions & 2 deletions cookbook_metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import (
// package never does. ParseMetadataRb returns it, wrapped with the line,
// alongside the rest of the metadata, whose Version is left empty; without
// the check the cookbook would silently take Chef's default of 0.0.0.
var ErrMetadataVersionNotLiteral = errors.New("version is not a string literal, so it can't be read without running Ruby")
var ErrMetadataVersionNotLiteral = errors.New("cinc: version is not a string literal, so it can't be read without running Ruby")

// LoadCookbookMetadata reads the cookbook metadata in dir. Like Chef's
// CookbookVersionLoader, metadata.json takes precedence over metadata.rb; see
Expand Down Expand Up @@ -111,7 +111,7 @@ var metadataRbAssignment = regexp.MustCompile(`^[ \t]*[a-z_]+[ \t]*=[^=~]`)
// double-quoted without interpolation or escapes other than \" and \\; a
// symbol (:apt, :"apt") reads as its name; a # comment may end any line.
// A call may continue onto following lines after a trailing comma or an open
// parenthesis or bracket, as Ruby reads it (see metadataRbStatements).
// parenthesis or bracket, as Ruby reads it.
//
// A statement whose arguments are not all literals (a computed value,
// interpolation, a trailing conditional) is skipped, as is any other method,
Expand Down
8 changes: 4 additions & 4 deletions cookbooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -299,8 +299,8 @@ func (s *CookbooksService) Download(ctx context.Context, name, version, destDir
// DownloadFiles writes every file of an already-fetched cookbook manifest (a
// Cookbooks.Get or CookbookArtifacts.Get result) to destDir, recreating the
// path hierarchy. File content is fetched from the manifest's pre-signed
// bookshelf URLs using a plain (unsigned) HTTP GET, matching the upload path
// in sandboxes.go; no API request is made. Each file is verified against the
// bookshelf URLs using a plain (unsigned) HTTP GET, as uploads are sent; no
// API request is made. Each file is verified against the
// manifest's MD5 checksum and written atomically; files already in destDir
// with a matching checksum are skipped.
//
Expand Down Expand Up @@ -615,8 +615,8 @@ func SkipChefignore() LocalCookbookOption {
// - files excluded by the applicable chefignore (see LoadChefignore, which
// also searches parent directories) are skipped;
// - a symlink to a regular file inside the cookbook is kept under its own
// path; any other symlink, and any special file, is skipped (see
// cookbookSymlinkTarget).
// path; any other symlink (to a directory, to anything outside the
// cookbook, or to nothing), and any special file, is skipped.
//
// Metadata comes from LoadCookbookMetadata: metadata.json when present
// (complete, as compiled by knife or Berkshelf), and otherwise a static parse
Expand Down
10 changes: 10 additions & 0 deletions doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,17 @@
// node, _, err := c.Nodes.Get(ctx, "web01")
// if errors.Is(err, cinc.ErrNotFound) {
// // no such node
// } else if err != nil {
// return err
// }
// fmt.Println(node.Environment)
//
// Every non-2xx response is an *ErrorResponse that also matches a sentinel
// error (ErrNotFound, ErrConflict, ErrForbidden, ...). GETs, and any request
// the server refused with a 503, are retried with backoff (WithMaxRetries).
// Client.Do sends a signed request to any path and returns the body
// unchanged, for what the typed services do not model. The package's
// examples show the common tasks.
//
// Requests are authenticated with the Chef v1.3 signed-header protocol.
package cinc
13 changes: 10 additions & 3 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,16 @@ import (

// Sentinel errors for use with errors.Is.
var (
ErrNotFound = errors.New("cinc: not found")
ErrConflict = errors.New("cinc: conflict")
ErrForbidden = errors.New("cinc: forbidden")
// ErrNotFound is a 404: the object, or the organization, does not exist.
ErrNotFound = errors.New("cinc: not found")
// ErrConflict is a 409: an object of that name already exists, or (for a
// cookbook version) it is frozen; see ErrCookbookFrozen.
ErrConflict = errors.New("cinc: conflict")
// ErrForbidden is a 403: the requestor lacks the permission, or the
// server refused the change outright (see ErrAdminsRequiredOnGrant).
ErrForbidden = errors.New("cinc: forbidden")
// ErrUnauthorized is a 401: the signature did not verify, which is
// nearly always the wrong key or a skewed clock.
ErrUnauthorized = errors.New("cinc: unauthorized")
// ErrBadRequest is a 400: the server refused the request as malformed or
// naming something that does not exist, such as an unknown actor or group
Expand Down
6 changes: 5 additions & 1 deletion options.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,11 @@ func WithRootCAs(pool *x509.CertPool) Option {
}

// WithMaxRetries sets how many times a failed request is retried: a GET after
// a 5xx or a network error, any other method after a 503. The default is 2.
// a 5xx other than 501 and 505, a network error or a client timeout; any
// other method only after a 503; a bookshelf transfer as a GET, except after
// a timeout. Waits double from 100ms up to 10s, jittered, or follow a 503's
// Retry-After (at most 10s). The caller's context ending stops retrying. The
// default is 2.
func WithMaxRetries(n int) Option {
return func(o *options) {
if n >= 0 {
Expand Down
2 changes: 1 addition & 1 deletion required_recipe.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import "context"

// RequiredRecipeService accesses the /required_recipe endpoint. Unlike the
// rest of the API this endpoint returns a Ruby recipe as text/plain rather
// than JSON, so it bypasses the generic do[T] helper.
// than JSON.
type RequiredRecipeService struct{ client *Client }

// Get returns the configured required recipe (Ruby text). The endpoint
Expand Down
3 changes: 2 additions & 1 deletion search.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,8 @@ func decodeRows[T any](rows iter.Seq2[json.RawMessage, error], decode func(json.

// Collect pages through every result, returning all rows.
// WithStart(n) is respected as the absolute offset of the first row to fetch;
// subsequent pages advance the offset by the number of rows received per page.
// subsequent pages advance it by the page size requested (WithRows), so a page
// shortened by objects deleted since they were indexed does not end paging.
//
// Collect holds the whole result set in memory; use All to process rows
// page by page instead.
Expand Down
4 changes: 2 additions & 2 deletions search_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ func TestSearch_All_CapsPrealloc(t *testing.T) {
// Total far exceeds maxPrealloc (100_000); only one row is actually
// returned. The next page reports the index's real size, which
// ends paging (an empty page alone does not: see
// TestSearchAll_PagesPastDeletedObjects).
// TestCollect_PagesPastDeletedObjects).
w.Write([]byte(`{"total":5000000,"start":0,"rows":[{"name":"a"}]}`))
return
}
Expand Down Expand Up @@ -650,7 +650,7 @@ func TestSearch_DataBagItemsDecodeError(t *testing.T) {
// counts them. Paging must advance by the page size it asked for, as
// chef-client's Search::Query does, or a short page repeats rows of the next
// one and an all-deleted page ends the search early.
func TestSearchAll_PagesPastDeletedObjects(t *testing.T) {
func TestCollect_PagesPastDeletedObjects(t *testing.T) {
index := []string{"a", "b", "c", "d", "e"}
for _, tc := range []struct {
name string
Expand Down
8 changes: 6 additions & 2 deletions transport_wire_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,12 @@ func TestNewClient_RejectsServerURLWithPath(t *testing.T) {
"https://chef.example.com#frag",
} {
_, err := NewClient(Config{ServerURL: u, Org: "o", ClientName: "c", Key: testRSAKey(t)})
if err == nil || !strings.Contains(err.Error(), "ParseServerURL") {
t.Errorf("ServerURL %q: err = %v, want a rejection pointing at ParseServerURL", u, err)
want := "scheme://host[:port]"
if strings.Contains(u, "/organizations/") {
want = "ParseServerURL"
}
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("ServerURL %q: err = %v, want a rejection mentioning %s", u, err, want)
}
}
for _, u := range []string{"https://chef.example.com", "https://chef.example.com/", "http://127.0.0.1:8889"} {
Expand Down