From fdaa92cfde5dfeaa0dd99e0e88d262e51cc748b4 Mon Sep 17 00:00:00 2001 From: Tim Smith Date: Thu, 26 Nov 2026 18:05:45 -0800 Subject: [PATCH] docs: bring the package doc, AGENTS.md and comments up to date for 1.0 - Collect, WithMaxRetries and AGENTS.md described the retry and paging rules from before this release: paging advances by the rows requested, backoff is capped and jittered, 501/505 are not retried, an http.Client timeout on a GET is, a transfer timeout is not, and the caller's context is what ends retrying. - The package doc says how errors and retries work and points at Do and the examples; its usage snippet, like the README's, now uses node. - Exported docs no longer name unexported helpers or source files (metadataRbStatements, cookbookSymlinkTarget, sandboxes.go, do[T]). - ErrNotFound, ErrConflict, ErrForbidden and ErrUnauthorized have doc comments, and ErrMetadataVersionNotLiteral has the cinc: prefix every other error has. - NewClient's error for a ServerURL with a path says why: a path /organizations/ points at ParseServerURL, any other prefix is refused because the signature must cover the path the server sees. - AGENTS.md: a cinc-server-ng gap needs a reason, an issue URL only when it is a server bug, as integration/README.md already says. Signed-off-by: Tim Smith --- AGENTS.md | 18 ++++++++++++++---- README.md | 3 +++ client.go | 10 ++++++++-- cookbook_metadata.go | 4 ++-- cookbooks.go | 8 ++++---- doc.go | 10 ++++++++++ errors.go | 13 ++++++++++--- options.go | 6 +++++- required_recipe.go | 2 +- search.go | 3 ++- search_test.go | 4 ++-- transport_wire_test.go | 8 ++++++-- 12 files changed, 67 insertions(+), 22 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0cb1697..8d1d103 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 @@ -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 @@ -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. diff --git a/README.md b/README.md index 6d66665..532a330 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/client.go b/client.go index 42fcbda..0f6d0dd 100644 --- a/client.go +++ b/client.go @@ -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/ 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/ 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/ 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 { diff --git a/cookbook_metadata.go b/cookbook_metadata.go index 961402b..a672182 100644 --- a/cookbook_metadata.go +++ b/cookbook_metadata.go @@ -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 @@ -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, diff --git a/cookbooks.go b/cookbooks.go index aef525f..9ef69c5 100644 --- a/cookbooks.go +++ b/cookbooks.go @@ -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. // @@ -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 diff --git a/doc.go b/doc.go index a3944c5..01c3c2a 100644 --- a/doc.go +++ b/doc.go @@ -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 diff --git a/errors.go b/errors.go index c6d5e22..6d3f430 100644 --- a/errors.go +++ b/errors.go @@ -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 diff --git a/options.go b/options.go index e723d99..821198b 100644 --- a/options.go +++ b/options.go @@ -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 { diff --git a/required_recipe.go b/required_recipe.go index 1a27fbb..26f0dac 100644 --- a/required_recipe.go +++ b/required_recipe.go @@ -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 diff --git a/search.go b/search.go index 6d44371..cb90974 100644 --- a/search.go +++ b/search.go @@ -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. diff --git a/search_test.go b/search_test.go index d8aeecd..915d83e 100644 --- a/search_test.go +++ b/search_test.go @@ -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 } @@ -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 diff --git a/transport_wire_test.go b/transport_wire_test.go index 47415cb..8a62e29 100644 --- a/transport_wire_test.go +++ b/transport_wire_test.go @@ -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"} {