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
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,11 @@ model, so callers don't re-encode server conventions:
cookbook upload --freeze` does; replacing a frozen version then fails with
`ErrCookbookFrozen` (also `ErrConflict`) unless the upload is `WithForce()`.
`Cookbook.Frozen` reports the flag, which the server never clears.
- `WithUploadProgress(fn)` (for `Cookbooks.Upload` and
`CookbookArtifacts.Upload`) and `WithDownloadProgress(fn)` (for
`Cookbooks.Download` and `DownloadFiles`) report each file's
cookbook-relative path as it is uploaded or put in place, for progress
output. Transfers run in parallel, so `fn` may be called concurrently.
- `LocalCookbookFromDir(dir, version)` — load a cookbook for
`Cookbooks.Upload` / `CookbookArtifacts.Upload`. `LocalCookbook.Metadata`
(a `CookbookMetadata`: name, version, description, maintainer, license,
Expand All @@ -229,7 +234,7 @@ model, so callers don't re-encode server conventions:
needs a `metadata.json` or an edit to `Metadata`. An empty `version` uses
the metadata's version (an error if `metadata.rb` computes it); one that
disagrees with it is an error. `LocalCookbookFromDir(dir, version,
SkipChefignore())` keeps the files chefignore would drop (every other
WithSkipChefignore())` keeps the files chefignore would drop (every other
selection rule still applies), for packaging a cookbook as-is; chef-cli
always applies chefignore, so such a cookbook's `Identifiers()` are not the
ones a `Policyfile.lock.json` should carry.
Expand Down
1 change: 0 additions & 1 deletion associations.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ type OrgUser struct {
DisplayName string `json:"display_name,omitempty"`
FirstName string `json:"first_name,omitempty"`
LastName string `json:"last_name,omitempty"`
PublicKey string `json:"public_key,omitempty"`
}

// Invitation is a pending organization invitation (association request). The
Expand Down
16 changes: 14 additions & 2 deletions cookbook_artifacts.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package cinc

import (
"context"
"errors"
"fmt"
)

Expand Down Expand Up @@ -72,11 +73,22 @@ func (s *CookbookArtifactsService) Delete(ctx context.Context, name, identifier
// Upload uploads a LocalCookbook as a cookbook artifact using the
// sandbox/checksum protocol, then PUTs the artifact manifest at
// PUT /organizations/NAME/cookbook_artifacts/NAME/IDENTIFIER.
func (s *CookbookArtifactsService) Upload(ctx context.Context, cb *LocalCookbook, identifier string) error {
//
// WithUploadProgress applies. WithFreeze and WithForce do not, and are an
// error: an artifact's identifier is a hash of its content, and the server
// never replaces one.
func (s *CookbookArtifactsService) Upload(ctx context.Context, cb *LocalCookbook, identifier string, opts ...CookbookUploadOption) error {
var o uploadOptions
for _, opt := range opts {
opt(&o)
}
if o.freeze || o.force {
return errors.New("cinc: a cookbook artifact cannot be uploaded WithFreeze or WithForce")
}
// Work on a shallow copy so the caller's struct is not mutated.
artifact := *cb
artifact.identifier = identifier
if err := uploadCookbook(ctx, s.client, "/cookbook_artifacts", &artifact, uploadOptions{}); err != nil {
if err := uploadCookbook(ctx, s.client, "/cookbook_artifacts", &artifact, o); err != nil {
return fmt.Errorf("cinc: upload cookbook artifact: %w", err)
}
return nil
Expand Down
6 changes: 3 additions & 3 deletions cookbook_identifier_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ func TestLocalCookbook_IdentifiersCountInCookbookSymlinks(t *testing.T) {
}
}

// SkipChefignore keeps the files chefignore would drop, including a broken
// WithSkipChefignore keeps the files chefignore would drop, including a broken
// or unreadable chefignore's cookbook, and changes nothing else: root
// dot-directories, the chef-zero sentinel and out-of-cookbook symlinks are
// still skipped.
Expand Down Expand Up @@ -172,13 +172,13 @@ func TestLocalCookbookFromDir_SkipChefignore(t *testing.T) {
t.Fatalf("default: got %v, want %v", got, want)
}

skipped, err := LocalCookbookFromDir(root, "", SkipChefignore())
skipped, err := LocalCookbookFromDir(root, "", WithSkipChefignore())
if err != nil {
t.Fatal(err)
}
want := []string{"chefignore", "files/.hidden/keep", "metadata.rb", "recipes/default.rb.bak", "tmp/scratch"}
if got := paths(skipped); !reflect.DeepEqual(got, want) {
t.Fatalf("SkipChefignore: got %v, want %v", got, want)
t.Fatalf("WithSkipChefignore: got %v, want %v", got, want)
}
idHonored, _ := honored.Identifiers()
idSkipped, _ := skipped.Identifiers()
Expand Down
130 changes: 130 additions & 0 deletions cookbook_progress_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
package cinc

import (
"context"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
)

// progressRecorder collects the paths a progress callback reports. The
// callback may run on several goroutines at once.
type progressRecorder struct {
mu sync.Mutex
paths []string
}

func (r *progressRecorder) record(path string) {
r.mu.Lock()
defer r.mu.Unlock()
r.paths = append(r.paths, path)
}

func (r *progressRecorder) sorted() []string {
r.mu.Lock()
defer r.mu.Unlock()
return slices.Sorted(slices.Values(r.paths))
}

// WithUploadProgress reports each file the upload sends, by cookbook path:
// only the files the server lacked, since the others are never sent.
func TestUpload_WithUploadProgress(t *testing.T) {
root := filepath.Join(t.TempDir(), "web")
writeTree(t, root, map[string]string{
"metadata.rb": "name 'web'\nversion '1.0.0'\n",
"recipes/default.rb": "package 'nginx'\n",
"recipes/other.rb": "package 'curl'\n",
})
cb, err := LocalCookbookFromDir(root, "")
if err != nil {
t.Fatal(err)
}
present := md5Hex([]byte("package 'curl'\n")) // the server already holds recipes/other.rb
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == "POST" && r.URL.Path == "/organizations/o/sandboxes":
var entries []string
for _, f := range cb.files {
needs := f.checksum != present
entries = append(entries, `"`+f.checksum+`":{"needs_upload":`+map[bool]string{true: "true", false: "false"}[needs]+
`,"url":"http://`+r.Host+`/shelf/`+f.checksum+`"}`)
}
w.WriteHeader(201)
io.WriteString(w, `{"sandbox_id":"sb","checksums":{`+strings.Join(entries, ",")+`}}`)
case strings.HasPrefix(r.URL.Path, "/shelf/"):
case r.Method == "PUT":
io.WriteString(w, `{}`)
default:
t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
}
}))
defer srv.Close()
c := newTestClient(t, srv)

var cookbook, artifact progressRecorder
if err := c.Cookbooks.Upload(context.Background(), cb, WithUploadProgress(cookbook.record)); err != nil {
t.Fatal(err)
}
if err := c.CookbookArtifacts.Upload(context.Background(), cb, "abc", WithUploadProgress(artifact.record)); err != nil {
t.Fatal(err)
}
want := []string{"metadata.rb", "recipes/default.rb"}
for name, got := range map[string][]string{"cookbook": cookbook.sorted(), "artifact": artifact.sorted()} {
if !slices.Equal(got, want) {
t.Errorf("%s progress = %v, want %v", name, got, want)
}
}
}

// A cookbook artifact cannot be frozen or forced: its identifier is a content
// hash and the server never replaces one. Those options are refused before
// anything is sent.
func TestCookbookArtifacts_Upload_RefusesFreezeAndForce(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
}))
defer srv.Close()
c := newTestClient(t, srv)
cb := &LocalCookbook{Name: "web", Version: "1.0.0"}
for _, opt := range []CookbookUploadOption{WithFreeze(), WithForce()} {
err := c.CookbookArtifacts.Upload(context.Background(), cb, "abc", opt)
if err == nil || !strings.Contains(err.Error(), "artifact") {
t.Errorf("err = %v, want a refusal", err)
}
}
}

// WithDownloadProgress reports every file once it is in place, whether it was
// fetched or already on disk with the right checksum, so the reports add up to
// the manifest.
func TestDownloadFiles_WithDownloadProgress(t *testing.T) {
content := map[string]string{"metadata.rb": "name 'web'\n", "recipes/default.rb": "package 'nginx'\n"}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, content[strings.TrimPrefix(r.URL.Path, "/shelf/")])
}))
defer srv.Close()
var refs []CookbookFileRef
for p, body := range content {
refs = append(refs, CookbookFileRef{Path: p, URL: srv.URL + "/shelf/" + p, Checksum: md5Hex([]byte(body))})
}
dest := t.TempDir()
if err := os.WriteFile(filepath.Join(dest, "metadata.rb"), []byte(content["metadata.rb"]), 0o644); err != nil {
t.Fatal(err)
}

var progress progressRecorder
c := newTestClient(t, srv)
if err := c.Cookbooks.DownloadFiles(context.Background(), &Cookbook{AllFilesManifest: refs}, dest,
WithDownloadProgress(progress.record)); err != nil {
t.Fatal(err)
}
if got, want := progress.sorted(), []string{"metadata.rb", "recipes/default.rb"}; !slices.Equal(got, want) {
t.Errorf("progress = %v, want %v", got, want)
}
}
57 changes: 46 additions & 11 deletions cookbooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,27 +249,52 @@ func (s *CookbooksService) Delete(ctx context.Context, name, version string) (*R
return resp, err
}

// UploadOption configures Cookbooks.Upload.
type UploadOption func(*uploadOptions)
// CookbookUploadOption configures Cookbooks.Upload and
// CookbookArtifacts.Upload.
type CookbookUploadOption func(*uploadOptions)

type uploadOptions struct {
freeze, force bool
progress func(path string)
}

// WithUploadProgress calls fn with each file's cookbook-relative path once
// it is uploaded. Files the server already holds are not sent and not
// reported. Files upload in parallel, so fn may be called from several
// goroutines at once.
func WithUploadProgress(fn func(path string)) CookbookUploadOption {
return func(o *uploadOptions) { o.progress = fn }
}

// CookbookDownloadOption configures Cookbooks.Download and DownloadFiles.
type CookbookDownloadOption func(*downloadOptions)

type downloadOptions struct {
progress func(path string)
}

// WithDownloadProgress calls fn with each file's cookbook-relative path once
// it is in place under the destination, whether it was fetched or was already
// there with the right checksum, so the calls add up to the manifest. Files
// download in parallel, so fn may be called from several goroutines at once.
func WithDownloadProgress(fn func(path string)) CookbookDownloadOption {
return func(o *downloadOptions) { o.progress = fn }
}

// WithFreeze uploads the cookbook version frozen, as knife cookbook upload
// --freeze does: the server then refuses to replace it unless an upload is
// WithForce. Freezing cannot be undone.
func WithFreeze() UploadOption { return func(o *uploadOptions) { o.freeze = true } }
func WithFreeze() CookbookUploadOption { return func(o *uploadOptions) { o.freeze = true } }

// WithForce replaces the version even if it is frozen, as knife cookbook
// upload --force does. It does not unfreeze it.
func WithForce() UploadOption { return func(o *uploadOptions) { o.force = true } }
func WithForce() CookbookUploadOption { return func(o *uploadOptions) { o.force = true } }

// Upload uploads a LocalCookbook: sandbox -> file PUTs -> version manifest PUT.
//
// Replacing a frozen version without WithForce fails with an error matching
// ErrCookbookFrozen (and ErrConflict).
func (s *CookbooksService) Upload(ctx context.Context, cb *LocalCookbook, opts ...UploadOption) error {
func (s *CookbooksService) Upload(ctx context.Context, cb *LocalCookbook, opts ...CookbookUploadOption) error {
var o uploadOptions
for _, opt := range opts {
opt(&o)
Expand All @@ -288,12 +313,12 @@ func (s *CookbooksService) Upload(ctx context.Context, cb *LocalCookbook, opts .
// destDir (see DownloadFiles). version may be LatestVersion. To learn the
// resolved version before choosing destDir, Get the manifest and pass it to
// DownloadFiles instead, which saves fetching it twice.
func (s *CookbooksService) Download(ctx context.Context, name, version, destDir string) error {
func (s *CookbooksService) Download(ctx context.Context, name, version, destDir string, opts ...CookbookDownloadOption) error {
cb, _, err := s.Get(ctx, name, version)
if err != nil {
return fmt.Errorf("cinc: get cookbook manifest: %w", err)
}
return s.DownloadFiles(ctx, cb, destDir)
return s.DownloadFiles(ctx, cb, destDir, opts...)
}

// DownloadFiles writes every file of an already-fetched cookbook manifest (a
Expand All @@ -308,7 +333,11 @@ func (s *CookbooksService) Download(ctx context.Context, name, version, destDir
// leave it, writes go through an os.Root on destDir: a symlink already under
// destDir may point elsewhere inside it, but one pointing out of it fails the
// download (a directory) or is replaced by the downloaded file (a file).
func (s *CookbooksService) DownloadFiles(ctx context.Context, cb *Cookbook, destDir string) error {
func (s *CookbooksService) DownloadFiles(ctx context.Context, cb *Cookbook, destDir string, opts ...CookbookDownloadOption) error {
var o downloadOptions
for _, opt := range opts {
opt(&o)
}
if cb == nil {
return fmt.Errorf("cinc: DownloadFiles: nil cookbook manifest")
}
Expand Down Expand Up @@ -340,6 +369,9 @@ func (s *CookbooksService) DownloadFiles(ctx context.Context, cb *Cookbook, dest
if err := s.client.downloadFile(ctx, root, j.url, j.rel, j.checksum); err != nil {
return fmt.Errorf("cinc: download %s: %w", j.path, err)
}
if o.progress != nil {
o.progress(j.path)
}
return nil
})
}
Expand Down Expand Up @@ -482,6 +514,9 @@ func uploadCookbook(ctx context.Context, c *Client, base string, cb *LocalCookbo
if err := c.uploadFile(ctx, j.url, j.file); err != nil {
return fmt.Errorf("cinc: upload %s: %w", j.file.name, err)
}
if o.progress != nil {
o.progress(j.file.name)
}
return nil
}); err != nil {
return err
Expand Down Expand Up @@ -589,7 +624,7 @@ type localCookbookOptions struct {
skipChefignore bool
}

// SkipChefignore makes LocalCookbookFromDir ignore chefignore: no chefignore
// WithSkipChefignore makes LocalCookbookFromDir ignore chefignore: no chefignore
// is read, and files it would exclude are kept. Every other selection rule
// (root dot-directories, the chef-zero sentinel, symlinks, special files)
// still applies.
Expand All @@ -599,7 +634,7 @@ type localCookbookOptions struct {
// Policyfile identifiers chef-cli would compute for it whenever chefignore
// excludes anything; do not write them into a Policyfile.lock.json. The
// option is for packaging a cookbook as-is, such as a Supermarket tarball.
func SkipChefignore() LocalCookbookOption {
func WithSkipChefignore() LocalCookbookOption {
return func(o *localCookbookOptions) { o.skipChefignore = true }
}

Expand Down Expand Up @@ -636,7 +671,7 @@ func SkipChefignore() LocalCookbookOption {
// it is read; its content is not kept, but streamed from disk again by the
// upload. An empty directory is an error. The selected files are available
// from Files, and the Policyfile identifier over them from Identifiers. The
// SkipChefignore option keeps the files chefignore would drop.
// WithSkipChefignore option keeps the files chefignore would drop.
func LocalCookbookFromDir(dir, version string, opts ...LocalCookbookOption) (*LocalCookbook, error) {
var o localCookbookOptions
for _, opt := range opts {
Expand Down
2 changes: 1 addition & 1 deletion cookbooks_freeze_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
// manifestPUT runs an upload of a small cookbook against a fake server and
// returns the manifest PUT's query string and decoded body. The manifest PUT
// answers with status and body.
func manifestPUT(t *testing.T, status int, body string, opts ...UploadOption) (query string, manifest map[string]any, err error) {
func manifestPUT(t *testing.T, status int, body string, opts ...CookbookUploadOption) (query string, manifest map[string]any, err error) {
t.Helper()
root := filepath.Join(t.TempDir(), "web")
writeTree(t, root, manifestFixture)
Expand Down
6 changes: 3 additions & 3 deletions cookbooks_unix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func TestLocalCookbookFromDir_SkipsSpecialFiles(t *testing.T) {
}
}

// With SkipChefignore the chefignore is never read, so one that cannot be
// With WithSkipChefignore the chefignore is never read, so one that cannot be
// read does not fail the load.
func TestLocalCookbookFromDir_SkipChefignoreDoesNotReadIt(t *testing.T) {
if os.Geteuid() == 0 {
Expand All @@ -49,8 +49,8 @@ func TestLocalCookbookFromDir_SkipChefignoreDoesNotReadIt(t *testing.T) {
if _, err := LocalCookbookFromDir(root, ""); err == nil {
t.Fatal("expected the default load to fail reading chefignore")
}
if _, err := LocalCookbookFromDir(root, "", SkipChefignore()); err != nil {
t.Fatalf("SkipChefignore: %v", err)
if _, err := LocalCookbookFromDir(root, "", WithSkipChefignore()); err != nil {
t.Fatalf("WithSkipChefignore: %v", err)
}
}

Expand Down