diff --git a/internal/api/serverless/environment_test.go b/internal/api/serverless/environment_test.go index 3206959..06580c6 100644 --- a/internal/api/serverless/environment_test.go +++ b/internal/api/serverless/environment_test.go @@ -17,7 +17,10 @@ import ( "github.com/google/uuid" ) -const testEnvironment = "staging" +const ( + testEnvironment = "staging" + testVolume = "model-weights" +) // environmentCall is one client call, named by the generated operation it sends. type environmentCall struct { @@ -28,6 +31,56 @@ type environmentCall struct { func environmentScopedCalls() []environmentCall { id := uuid.MustParse("11111111-1111-1111-1111-111111111111") return []environmentCall{ + { + operation: "ListVolumes", + call: func(ctx context.Context, c *Client) error { + _, err := c.ListVolumes(ctx, ListVolumesParams{}) + return err + }, + }, + { + operation: "CreateVolume", + call: func(ctx context.Context, c *Client) error { + _, err := c.CreateVolume(ctx, VolumeCreate{ + Name: testVolume, + }) + return err + }, + }, + { + operation: "GetVolume", + call: func(ctx context.Context, c *Client) error { + _, err := c.GetVolume(ctx, testVolume) + return err + }, + }, + { + operation: "UpdateVolume", + call: func(ctx context.Context, c *Client) error { + _, err := c.UpdateVolume(ctx, testVolume, VolumeUpdate{}) + return err + }, + }, + { + operation: "DeleteVolume", + call: func(ctx context.Context, c *Client) error { + return c.DeleteVolume(ctx, testVolume, id, false) + }, + }, + { + operation: "GetVolumeReferences", + call: func(ctx context.Context, c *Client) error { + _, err := c.GetVolumeReferences(ctx, testVolume, GetVolumeReferencesParams{}) + return err + }, + }, + { + operation: "ListVolumeFiles", + call: func(ctx context.Context, c *Client) error { + _, err := c.ListVolumeFiles(ctx, testVolume, ListVolumeFilesParams{}) + return err + }, + }, { operation: "CreateApp", call: func(ctx context.Context, c *Client) error { @@ -362,6 +415,13 @@ func environmentScopedCalls() []environmentCall { func orgScopedCalls() []environmentCall { return []environmentCall{ + { + operation: "GetVolumeSettings", + call: func(ctx context.Context, c *Client) error { + _, err := c.GetVolumeSettings(ctx) + return err + }, + }, { operation: "ListGpuTypes", call: func(ctx context.Context, c *Client) error { @@ -559,23 +619,16 @@ var unwrappedOperations = []string{ "CompleteVolumeUploadFile", "CopySecret", "CreateSecretBatch", - "CreateVolume", "CreateVolumeUpload", "DeclareVolumeUploadFiles", - "DeleteVolume", "FavoriteApp", "GetAppSummary", "GetMetricSeries", - "GetVolume", - "GetVolumeReferences", "GetVolumeUpload", - "ListVolumeFiles", - "ListVolumes", "RenewVolumeUploadFileParts", "StartDefaultAsyncTask", "StartDefaultSyncTask", "UnfavoriteApp", - "UpdateVolume", } // environmentOperations are the generated operations whose params carry an diff --git a/internal/api/serverless/errors.go b/internal/api/serverless/errors.go index 665a733..127c10b 100644 --- a/internal/api/serverless/errors.go +++ b/internal/api/serverless/errors.go @@ -36,6 +36,11 @@ func problemToError(p *gen.ProblemDetails, statusCode int) error { case p.Title != "": msg = p.Title } + // The limit belongs to the headline: it is the organization's, not + // one of the fields the errors lines point at. + if limit := formatVolumeLimit(p); limit != "" { + msg = msg + ": " + limit + } if extra := formatProblemErrors(p.Errors); extra != "" { msg = msg + "\n" + extra } @@ -77,6 +82,30 @@ func formatProblemErrors(errors *[]gen.ProblemError) string { return strings.Join(lines, "\n") } +// formatVolumeLimit names the Shared Volume limit a volume-limit-exceeded +// conflict reports, with its cap and the requested value, or "" when the +// problem names none. +func formatVolumeLimit(p *gen.ProblemDetails) string { + if p.Limit == nil || *p.Limit == "" { + return "" + } + out := "limit " + *p.Limit + if p.Cap != nil { + out += fmt.Sprintf(", cap %d", *p.Cap) + } + if p.Current != nil { + out += fmt.Sprintf(", current %d", *p.Current) + } + if p.Requested != nil { + label := "requested" + if p.RequestedIsIncrement != nil && *p.RequestedIsIncrement { + label = "requested increase" + } + out += fmt.Sprintf(", %s %d", label, *p.Requested) + } + return out +} + func formatShortfall(amount *gen.MoneyAmount) string { if amount == nil || amount.Amount == "" { return "" diff --git a/internal/api/serverless/errors_test.go b/internal/api/serverless/errors_test.go index 9b62028..f9d95f0 100644 --- a/internal/api/serverless/errors_test.go +++ b/internal/api/serverless/errors_test.go @@ -146,3 +146,42 @@ func TestProblemToError_ProblemTypes(t *testing.T) { }) } } + +func TestProblemToError_VolumeLimitStaysOnTheHeadline(t *testing.T) { + detail := "maxStoredBytes exceeds its limit" + pointer := "/files/0/size" + limit := "maxStoredBytes" + limitCap, current, requested := int64(1099511627776), int64(1095000000000), int64(10270000000) + increment := true + p := &gen.ProblemDetails{ + Type: "https://docs.runware.ai/serverless/errors#volume-limit-exceeded", + Title: "Conflict", + Status: http.StatusConflict, + Detail: &detail, + Errors: &[]gen.ProblemError{ + { + Detail: detail, + Pointer: &pointer, + }, + }, + Limit: &limit, + Cap: &limitCap, + Current: ¤t, + Requested: &requested, + RequestedIsIncrement: &increment, + } + + err := problemToError(p, http.StatusConflict) + re, ok := errors.AsType[*transport.RunwareError](err) + if !ok { + t.Fatalf("expected *transport.RunwareError, got %T: %v", err, err) + } + headline, rest, _ := strings.Cut(re.Message, "\n") + want := detail + ": limit maxStoredBytes, cap 1099511627776, current 1095000000000, requested increase 10270000000" + if headline != want { + t.Errorf("headline = %q, want %q", headline, want) + } + if rest != " "+pointer+": "+detail { + t.Errorf("errors lines = %q, want the pointer line alone", rest) + } +} diff --git a/internal/api/serverless/volume_uploads.go b/internal/api/serverless/volume_uploads.go index 9f554a2..1713b60 100644 --- a/internal/api/serverless/volume_uploads.go +++ b/internal/api/serverless/volume_uploads.go @@ -81,31 +81,9 @@ type volumeFilePage struct { } // LatestFiles reads every page of the Volume's latest files, starting again -// when the list changes between two pages. When the attempts run out on a -// later page's 400, the error keeps that problem, since the 400 may be about -// something other than a stale cursor. +// when the list changes between two pages (see latestFiles). func (v *VolumeUploads) LatestFiles(ctx context.Context, volume put.VolumeRef) (put.FileList, error) { - var last error - for range volumeFileListAttempts { - list, changed, err := v.readFiles(ctx, volume) - if !changed { - if err != nil { - return put.FileList{}, err - } - return list, nil - } - last = err - } - return put.FileList{}, errors.Join(errVolumeFilesKeptChanging, last) -} - -// readFiles reads the pages once; changed reports that the list may have -// changed under it, with the later page's 400 problem as err when that is why. -func (v *VolumeUploads) readFiles(ctx context.Context, volume put.VolumeRef) (put.FileList, bool, error) { - var list put.FileList - seen := make(map[string]struct{}) - cursor := "" - for first := true; ; first = false { + digest, files, err := latestFiles(ctx, func(ctx context.Context, cursor string) (volumeFilesPage[put.VolumeFile], error) { query := url.Values{} query.Set("limit", strconv.Itoa(volumeFilesPageSize)) if cursor != "" { @@ -113,29 +91,22 @@ func (v *VolumeUploads) readFiles(ctx context.Context, volume put.VolumeRef) (pu } var page volumeFilePage err := v.do(ctx, http.MethodGet, volumePath(volume.Name, "files"), volume.Environment, query, nil, http.StatusOK, &page) - if err != nil { - // A cursor issued before an upload completed answers 400: the - // list changed, so start again from the first page. - if p, ok := errors.AsType[*put.ProblemError](err); ok && !first && p.Status == http.StatusBadRequest { - return put.FileList{}, true, err - } - return put.FileList{}, false, err - } - if first { - list.ManifestSHA256 = page.ManifestSHA256 - } else if page.ManifestSHA256 != list.ManifestSHA256 { - return put.FileList{}, true, nil - } - list.Files = append(list.Files, page.Data...) - if page.NextCursor == nil || *page.NextCursor == "" { - return list, false, nil - } - cursor = *page.NextCursor - if _, dup := seen[cursor]; dup { - return put.FileList{}, false, errRepeatedVolumeCursor - } - seen[cursor] = struct{}{} + return volumeFilesPage[put.VolumeFile]{ + digest: page.ManifestSHA256, + data: page.Data, + next: page.NextCursor, + }, err + }, func(err error) bool { + p, ok := errors.AsType[*put.ProblemError](err) + return ok && p.Status == http.StatusBadRequest + }) + if err != nil { + return put.FileList{}, err } + return put.FileList{ + ManifestSHA256: digest, + Files: files, + }, nil } // KeyPairStatement reads the organization's signed key-pair statement. diff --git a/internal/api/serverless/volumes.go b/internal/api/serverless/volumes.go new file mode 100644 index 0000000..a557805 --- /dev/null +++ b/internal/api/serverless/volumes.go @@ -0,0 +1,477 @@ +package serverless + +import ( + "context" + "errors" + "fmt" + "net/http" + + "github.com/runware/runware-cli/internal/api/serverless/gen" + "github.com/runware/runware-cli/internal/api/transport" +) + +// Volume is a Shared Volume: a named set of files, its latest file set, that +// apps in its environment mount. +type Volume = gen.Volume + +// VolumeCreate is the request body for createVolume. +type VolumeCreate = gen.VolumeCreate + +// VolumeUpdate is the request body for updateVolume. An omitted description +// is left unchanged; a null one is cleared. +type VolumeUpdate = gen.VolumeUpdate + +// VolumeDescription is a Volume's free-text description. +type VolumeDescription = gen.VolumeDescription + +// VolumeID is a Volume's immutable id. A new Volume that reuses a deleted +// one's name gets a new id. +type VolumeID = gen.VolumeId + +// VolumeReferences are the uses of a Volume: the ones that block a delete and +// the older app versions a confirmed delete takes the rollback from. +type VolumeReferences = gen.VolumeReferences + +// VolumeReference is one app version that uses a Volume. +type VolumeReference = gen.VolumeReference + +// VolumeReferenceKind is how an app version uses a Volume. +type VolumeReferenceKind = gen.VolumeReferenceKind + +// The kinds of VolumeReference. Every kind but rollback-target blocks a delete. +const ( + VolumeReferenceCurrentAppVersion = gen.CurrentAppVersion + VolumeReferenceDeployInProgress = gen.DeployInProgress + VolumeReferenceRunningWorker = gen.RunningWorker + VolumeReferenceRollbackTarget = gen.RollbackTarget +) + +// VolumeFile is one of a Volume's latest files. +type VolumeFile = gen.VolumeFile + +// VolumeFilePage is a page of a Volume's latest files and the digest of the +// file list it was read from. +type VolumeFilePage = gen.VolumeFilePage + +// VolumeSettings are the organization's Shared Volume access and effective +// limits. +type VolumeSettings = gen.VolumeSettings + +// GetVolumeReferencesParams are the query parameters for getVolumeReferences. +type GetVolumeReferencesParams = gen.GetVolumeReferencesParams + +// ListVolumesParams are the query parameters for listVolumes. +type ListVolumesParams = gen.ListVolumesParams + +// ListVolumeFilesParams are the query parameters for listVolumeFiles. +type ListVolumeFilesParams = gen.ListVolumeFilesParams + +// The problem types of the Shared Volume refusals a client tells apart. +const ( + ProblemVolumeInUse = "https://docs.runware.ai/serverless/errors#volume-in-use" + ProblemVolumeRollbackConfirmationRequired = "https://docs.runware.ai/serverless/errors#volume-rollback-confirmation-required" + ProblemVolumeNameTaken = "https://docs.runware.ai/serverless/errors#volume-name-taken" +) + +// ListVolumes returns a page of the Volumes in the client's environment. +func (c *Client) ListVolumes(ctx context.Context, params ListVolumesParams) (Page[Volume], error) { + if c.apiKey == "" { + return Page[Volume]{}, transport.ErrNoAPIKey + } + + params.Environment = c.environmentParam() + resp, err := c.inner.ListVolumesWithResponse(ctx, ¶ms) + if err != nil { + return Page[Volume]{}, fmt.Errorf("list volumes: %w", err) + } + + c.logResponse(ctx, resp.HTTPResponse, resp.Body) + + if resp.StatusCode() != http.StatusOK { + return Page[Volume]{}, problemFromBody(resp.Body, resp.StatusCode()) + } + if resp.JSON200 == nil { + return Page[Volume]{}, errors.New("list volumes: empty 200 response") + } + return pageOf(&resp.JSON200.Data, resp.JSON200.NextCursor), nil +} + +// CreateVolume creates an empty Volume in the client's environment. +func (c *Client) CreateVolume(ctx context.Context, body VolumeCreate) (*Volume, error) { + if c.apiKey == "" { + return nil, transport.ErrNoAPIKey + } + + params := gen.CreateVolumeParams{ + Environment: c.environmentParam(), + } + resp, err := c.inner.CreateVolumeWithResponse(ctx, ¶ms, body) + if err != nil { + return nil, fmt.Errorf("create volume: %w", err) + } + + c.logResponse(ctx, resp.HTTPResponse, resp.Body) + + if resp.StatusCode() != http.StatusCreated { + return nil, problemFromBody(resp.Body, resp.StatusCode()) + } + if resp.JSON201 == nil { + return nil, errors.New("create volume: empty 201 response") + } + return resp.JSON201, nil +} + +// GetVolume returns one Volume of the client's environment. +func (c *Client) GetVolume(ctx context.Context, name string) (*Volume, error) { + if c.apiKey == "" { + return nil, transport.ErrNoAPIKey + } + + params := gen.GetVolumeParams{ + Environment: c.environmentParam(), + } + resp, err := c.inner.GetVolumeWithResponse(ctx, name, ¶ms) + if err != nil { + return nil, fmt.Errorf("get volume: %w", err) + } + + c.logResponse(ctx, resp.HTTPResponse, resp.Body) + + if resp.StatusCode() != http.StatusOK { + return nil, problemFromBody(resp.Body, resp.StatusCode()) + } + if resp.JSON200 == nil { + return nil, errors.New("get volume: empty 200 response") + } + return resp.JSON200, nil +} + +// UpdateVolume changes the description of one Volume of the client's +// environment. +func (c *Client) UpdateVolume(ctx context.Context, name string, body VolumeUpdate) (*Volume, error) { + if c.apiKey == "" { + return nil, transport.ErrNoAPIKey + } + + params := gen.UpdateVolumeParams{ + Environment: c.environmentParam(), + } + resp, err := c.inner.UpdateVolumeWithResponse(ctx, name, ¶ms, body) + if err != nil { + return nil, fmt.Errorf("update volume: %w", err) + } + + c.logResponse(ctx, resp.HTTPResponse, resp.Body) + + if resp.StatusCode() != http.StatusOK { + return nil, problemFromBody(resp.Body, resp.StatusCode()) + } + if resp.JSON200 == nil { + return nil, errors.New("update volume: empty 200 response") + } + return resp.JSON200, nil +} + +// DeleteVolume logically deletes one Volume of the client's environment. id is +// the Volume's immutable id from a read, so a retry cannot delete a new Volume +// that took the name. confirmRollbackLoss accepts that older app versions +// using it lose their rollback; it never overrides a blocking use, which the +// API answers with a 409 typed ProblemVolumeInUse. +func (c *Client) DeleteVolume(ctx context.Context, name string, id VolumeID, confirmRollbackLoss bool) error { + if c.apiKey == "" { + return transport.ErrNoAPIKey + } + + params := gen.DeleteVolumeParams{ + Environment: c.environmentParam(), + VolumeId: id, + } + if confirmRollbackLoss { + params.ConfirmRollbackLoss = &confirmRollbackLoss + } + resp, err := c.inner.DeleteVolumeWithResponse(ctx, name, ¶ms) + if err != nil { + return fmt.Errorf("delete volume: %w", err) + } + + c.logResponse(ctx, resp.HTTPResponse, resp.Body) + + if resp.StatusCode() != http.StatusNoContent { + return problemFromBody(resp.Body, resp.StatusCode()) + } + return nil +} + +// GetVolumeReferences returns a page of the uses of one Volume of the +// client's environment, blocking uses before rollback targets. The answer is a +// snapshot: it does not authorize a delete. +func (c *Client) GetVolumeReferences(ctx context.Context, name string, params GetVolumeReferencesParams) (*VolumeReferences, error) { + if c.apiKey == "" { + return nil, transport.ErrNoAPIKey + } + + params.Environment = c.environmentParam() + resp, err := c.inner.GetVolumeReferencesWithResponse(ctx, name, ¶ms) + if err != nil { + return nil, fmt.Errorf("get volume references: %w", err) + } + + c.logResponse(ctx, resp.HTTPResponse, resp.Body) + + if resp.StatusCode() != http.StatusOK { + return nil, problemFromBody(resp.Body, resp.StatusCode()) + } + if resp.JSON200 == nil { + return nil, errors.New("get volume references: empty 200 response") + } + return resp.JSON200, nil +} + +// ListVolumeFiles returns a page of the latest files of one Volume of the +// client's environment. +func (c *Client) ListVolumeFiles(ctx context.Context, name string, params ListVolumeFilesParams) (*VolumeFilePage, error) { + if c.apiKey == "" { + return nil, transport.ErrNoAPIKey + } + + params.Environment = c.environmentParam() + resp, err := c.inner.ListVolumeFilesWithResponse(ctx, name, ¶ms) + if err != nil { + return nil, fmt.Errorf("list volume files: %w", err) + } + + c.logResponse(ctx, resp.HTTPResponse, resp.Body) + + if resp.StatusCode() != http.StatusOK { + return nil, problemFromBody(resp.Body, resp.StatusCode()) + } + if resp.JSON200 == nil { + return nil, errors.New("list volume files: empty 200 response") + } + return resp.JSON200, nil +} + +// GetVolumeSettings returns the organization's Shared Volume access and +// effective limits. Settings belong to the organization, so the request +// carries no environment. +func (c *Client) GetVolumeSettings(ctx context.Context) (*VolumeSettings, error) { + if c.apiKey == "" { + return nil, transport.ErrNoAPIKey + } + + resp, err := c.inner.GetVolumeSettingsWithResponse(ctx) + if err != nil { + return nil, fmt.Errorf("get volume settings: %w", err) + } + + c.logResponse(ctx, resp.HTTPResponse, resp.Body) + + if resp.StatusCode() != http.StatusOK { + return nil, problemFromBody(resp.Body, resp.StatusCode()) + } + if resp.JSON200 == nil { + return nil, errors.New("get volume settings: empty 200 response") + } + return resp.JSON200, nil +} + +// volumePageSize is the page size AllVolumes and AllVolumeReferences ask +// for, the largest their routes serve. +const volumePageSize Limit = 100 + +// AllVolumes follows every page of the Volumes in the client's environment. +// On an error it returns no Volumes, never the pages read before it. +func (c *Client) AllVolumes(ctx context.Context) ([]Volume, error) { + volumes := []Volume{} + limit := volumePageSize + var cursor *Cursor + seen := make(map[string]struct{}) + for { + page, err := c.ListVolumes(ctx, ListVolumesParams{ + Limit: &limit, + Cursor: cursor, + }) + if err != nil { + return nil, err + } + volumes = append(volumes, page.Data...) + next, err := nextVolumeCursor(page.NextCursor, seen) + if err != nil { + return nil, err + } + if next == nil { + return volumes, nil + } + cursor = next + } +} + +// AllVolumeReferences follows every page of the uses of one Volume of the +// client's environment. The result has no next cursor. On an error it returns +// no uses, never the pages read before it, which would omit some. +func (c *Client) AllVolumeReferences(ctx context.Context, name string) (*VolumeReferences, error) { + all := &VolumeReferences{ + Blocking: []VolumeReference{}, + RollbackTargets: []VolumeReference{}, + } + limit := volumePageSize + var cursor *Cursor + seen := make(map[string]struct{}) + for { + page, err := c.GetVolumeReferences(ctx, name, GetVolumeReferencesParams{ + Limit: &limit, + Cursor: cursor, + }) + if err != nil { + return nil, err + } + all.Blocking = append(all.Blocking, page.Blocking...) + all.RollbackTargets = append(all.RollbackTargets, page.RollbackTargets...) + next, err := nextVolumeCursor(page.NextCursor, seen) + if err != nil { + return nil, err + } + if next == nil { + return all, nil + } + cursor = next + } +} + +// LatestVolumeFiles reads every page of the latest files of one Volume of the +// client's environment, starting again when the list changes between two +// pages (see latestFiles). The result has no next cursor. +func (c *Client) LatestVolumeFiles(ctx context.Context, name string) (VolumeFilePage, error) { + limit := gen.VolumeFileLimit(volumeFilesPageSize) + digest, files, err := latestFiles(ctx, func(ctx context.Context, cursor string) (volumeFilesPage[VolumeFile], error) { + params := ListVolumeFilesParams{ + Limit: &limit, + } + if cursor != "" { + params.Cursor = &cursor + } + page, err := c.ListVolumeFiles(ctx, name, params) + if err != nil { + return volumeFilesPage[VolumeFile]{}, err + } + var digest string + if page.ManifestSha256 != nil { + digest = *page.ManifestSha256 + } + return volumeFilesPage[VolumeFile]{ + digest: digest, + data: page.Data, + next: page.NextCursor, + }, nil + }, func(err error) bool { + re, ok := errors.AsType[*transport.RunwareError](err) + return ok && re.StatusCode == http.StatusBadRequest + }) + if err != nil { + return VolumeFilePage{}, keepRetryAdvice(err) + } + out := VolumeFilePage{ + Data: files, + } + if out.Data == nil { + out.Data = []VolumeFile{} + } + if digest != "" { + out.ManifestSha256 = &digest + } + return out, nil +} + +// keepRetryAdvice puts the advice of a listing that kept changing into the +// API answer it ended on: the CLI prints that answer's message, which alone +// would read as an unexplained 400. Any other error is returned as it is. +func keepRetryAdvice(err error) error { + if !errors.Is(err, errVolumeFilesKeptChanging) { + return err + } + re, ok := errors.AsType[*transport.RunwareError](err) + if !ok { + return err + } + api := *re + api.Message = fmt.Sprintf("%v (the last answer: %s)", errVolumeFilesKeptChanging, re.Message) + return &filesKeptChangingError{ + api: &api, + } +} + +// filesKeptChangingError is a listing that ran out of attempts on a later +// page's 400, whose message carries the advice to retry. +type filesKeptChangingError struct { + api *transport.RunwareError +} + +func (e *filesKeptChangingError) Error() string { return e.api.Message } + +func (e *filesKeptChangingError) Unwrap() []error { + return []error{errVolumeFilesKeptChanging, e.api} +} + +// volumeFilesPage is one page of a Volume's latest files, as latestFiles +// reads it. digest is "" for a Volume with no files. +type volumeFilesPage[T any] struct { + digest string + data []T + next *string +} + +// latestFiles reads every page of a Volume's latest files with fetch, which +// takes a cursor ("" for the first page). The listing starts again, a bounded +// number of times, when the list changes between two pages: a later page +// comes from another file list, or answers the 400 a cursor issued before an +// upload completed gets, which staleCursor recognizes. When the attempts run +// out on such a 400, the error keeps it, since a 400 may be about something +// other than a stale cursor. A first page's 400 is returned as it is. +func latestFiles[T any](ctx context.Context, fetch func(context.Context, string) (volumeFilesPage[T], error), staleCursor func(error) bool) (string, []T, error) { + var last error + for range volumeFileListAttempts { + digest, files, changed, err := readFilesOnce(ctx, fetch, staleCursor) + if !changed { + return digest, files, err + } + last = err + } + return "", nil, errors.Join(errVolumeFilesKeptChanging, last) +} + +// readFilesOnce reads the pages once; changed reports that the list may have +// changed under it, with the later page's 400 as err when that is why. +func readFilesOnce[T any](ctx context.Context, fetch func(context.Context, string) (volumeFilesPage[T], error), staleCursor func(error) bool) (digest string, files []T, changed bool, err error) { + seen := make(map[string]struct{}) + cursor := "" + for first := true; ; first = false { + page, err := fetch(ctx, cursor) + if err != nil { + return "", nil, !first && staleCursor(err), err + } + if first { + digest = page.digest + } else if page.digest != digest { + return "", nil, true, nil + } + files = append(files, page.data...) + next, err := nextVolumeCursor(page.next, seen) + if err != nil || next == nil { + return digest, files, false, err + } + cursor = *next + } +} + +// nextVolumeCursor is the cursor of the next page, or nil after the last +// page. A cursor the API repeats would loop forever, so it is an error. +func nextVolumeCursor(next *string, seen map[string]struct{}) (*string, error) { + if next == nil || *next == "" { + return nil, nil + } + if _, dup := seen[*next]; dup { + return nil, errRepeatedVolumeCursor + } + seen[*next] = struct{}{} + return next, nil +} diff --git a/internal/api/serverless/volumes_test.go b/internal/api/serverless/volumes_test.go new file mode 100644 index 0000000..6c18b24 --- /dev/null +++ b/internal/api/serverless/volumes_test.go @@ -0,0 +1,48 @@ +package serverless + +import ( + "context" + "errors" + "log/slog" + "net/http" + "net/http/httptest" + "testing" +) + +// repeatedCursorServer answers every request with body, whose nextCursor +// never changes, so the second page repeats the first page's cursor. +func repeatedCursorServer(t *testing.T, body string) *Client { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(body)) + })) + t.Cleanup(srv.Close) + return newClient("test-key", srv.URL, slog.Default(), srv.Client()) +} + +func TestAllVolumesReturnsNothingWhenPagingFails(t *testing.T) { + c := repeatedCursorServer(t, `{"data":[{"id":"6a1f0d6e-5c1b-4f69-9a39-0f4c1c8b2d11","name":"model-weights","environment":"production","status":"live","logicalBytes":0,"fileCount":0,"createdAt":"2026-11-02T10:00:00Z","updatedAt":"2026-11-02T10:00:00Z"}],"nextCursor":"c1"}`) + + volumes, err := c.AllVolumes(context.Background()) + + if !errors.Is(err, errRepeatedVolumeCursor) { + t.Fatalf("err = %v, want errRepeatedVolumeCursor", err) + } + if volumes != nil { + t.Fatalf("volumes = %v, want none: the pages read before the error are incomplete", volumes) + } +} + +func TestAllVolumeReferencesReturnsNothingWhenPagingFails(t *testing.T) { + c := repeatedCursorServer(t, `{"blocking":[{"appId":"img-gen","appVersionNumber":7,"kind":"current-app-version"}],"rollbackTargets":[],"nextCursor":"r1"}`) + + refs, err := c.AllVolumeReferences(context.Background(), "model-weights") + + if !errors.Is(err, errRepeatedVolumeCursor) { + t.Fatalf("err = %v, want errRepeatedVolumeCursor", err) + } + if refs != nil { + t.Fatalf("refs = %+v, want none: the pages read before the error are incomplete", refs) + } +} diff --git a/internal/cmd/serverless/pack.go b/internal/cmd/serverless/pack.go index 143ba6d..0f277dc 100644 --- a/internal/cmd/serverless/pack.go +++ b/internal/cmd/serverless/pack.go @@ -460,6 +460,10 @@ func largestFilesSummary(files []packedFile) string { func humanBytes(n int64) string { switch { + case n >= 1<<40: + return fmt.Sprintf("%.1f TiB", float64(n)/(1<<40)) + case n >= 1<<30: + return fmt.Sprintf("%.1f GiB", float64(n)/(1<<30)) case n >= 1<<20: return fmt.Sprintf("%.1f MiB", float64(n)/(1<<20)) case n >= 1<<10: diff --git a/internal/cmd/serverless/volume.go b/internal/cmd/serverless/volume.go index e5eb9ad..8a8eaac 100644 --- a/internal/cmd/serverless/volume.go +++ b/internal/cmd/serverless/volume.go @@ -1,6 +1,7 @@ package serverless import ( + "errors" "fmt" "path" "regexp" @@ -33,6 +34,9 @@ const ( // volumeNamePattern is the server's VolumeName rule. var volumeNamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,62}$`) +// errVolumeName rejects a name volumeNamePattern does not match. +var errVolumeName = errors.New("volume name must be 1-63 lowercase letters, digits, hyphens, underscores or periods, starting with a letter or digit") + // sandboxPath is one requested path inside the sandbox, with the flag that asked // for it, so an error can name the flag the person has to change. type sandboxPath struct { diff --git a/internal/cmd/serverless/volumes.go b/internal/cmd/serverless/volumes.go index 442872d..ddc774c 100644 --- a/internal/cmd/serverless/volumes.go +++ b/internal/cmd/serverless/volumes.go @@ -73,9 +73,20 @@ func newVerifiedVolumeKeys(serverlessBaseURL, stateDir string) (put.Keys, error) // hidden until the production verification keys ship (see // newVerifiedVolumeKeys). func newVolumesCmd(logger *log.Logger) *cobra.Command { - cmd := stubGroup("volumes", "Manage Shared Volumes") + cmd := stubGroup("volumes", "Manage Shared Volumes (beta)") cmd.Hidden = true - cmd.AddCommand(newVolumesPutCmd(logger)) + cmd.Long = volumesHelpLong + cmd.AddCommand( + newVolumesListCmd(logger), + newVolumesCreateCmd(logger), + newVolumesShowCmd(logger), + newVolumesUpdateCmd(logger), + newVolumesDeleteCmd(logger), + newVolumesReferencesCmd(logger), + newVolumesFilesCmd(logger), + newVolumesPutCmd(logger), + newVolumesSettingsCmd(logger), + ) return cmd } @@ -139,7 +150,7 @@ func newVolumesPutCmd(logger *log.Logger) *cobra.Command { cmd.Flags().StringVar(&to, toFlag, "", "Directory in the Volume the paths land under (default the Volume root)") cmd.Flags().IntVar(&concurrency, concurrencyFlag, put.DefaultParallelism, fmt.Sprintf("Parts to upload at once (1-%d); each part in flight holds about 1 MiB of memory", put.MaxParallelism)) - addEnvironmentFlag(cmd, cmd.Flags(), logger, "Environment the Volume belongs to "+environmentFlagDefault) + addVolumeEnvironmentFlag(cmd, logger) return cmd } diff --git a/internal/cmd/serverless/volumes_display.go b/internal/cmd/serverless/volumes_display.go new file mode 100644 index 0000000..8569e9f --- /dev/null +++ b/internal/cmd/serverless/volumes_display.go @@ -0,0 +1,242 @@ +package serverless + +import ( + "encoding/json" + "fmt" + "strconv" + "time" + + serverlessapi "github.com/runware/runware-cli/internal/api/serverless" +) + +const ( + colDescription = "Description" + colSize = "Size" + colFiles = "Files" + colFilesDigest = "Files digest" + colUsedBy = "Used by" + colRollbackFor = "Rollback of" + colEffect = "On delete" + colPath = "Path" + colMode = "Mode" + colSHA256 = "SHA-256" + colVolume = "Volume" + colDeleted = "Deleted" + colLostRollback = "Lost rollback" + colAvailable = "Enabled" + colMaxStored = "Max stored" + colMaxFileSize = "Max file size" + colMaxFiles = "Max files per Volume" + colMaxMounted = "Max mounted per app version" + colUploadDeadline = "Upload session lifetime" + + // shortIDLength is how much of an id or digest a list table shows. + shortIDLength = 8 + // effectBlocks and effectLosesRollback say what a reference does to a + // delete. + effectBlocks = "blocks it" + effectLosesRollback = "loses rollback" + // deletedLogically is what a deleted Volume's table says about its bytes. + deletedLogically = "yes; stored bytes may be reclaimed later" +) + +// shortID is the start of an id or digest, for a table. +func shortID(s string) string { + if len(s) <= shortIDLength { + return s + } + return s[:shortIDLength] +} + +// volumeResult is one Volume. Its table adds the uses of the Volume when show +// read them; JSON and YAML print the API's Volume object only. +type volumeResult struct { + volume serverlessapi.Volume + // withUses adds the uses to the table. + withUses bool + // references are the Volume's uses, or nil when they could not be read. + references *serverlessapi.VolumeReferences + // referencesErr says why the uses could not be read. + referencesErr string +} + +func (r volumeResult) Headers() []string { + return []string{colField, colValue} +} + +func (r volumeResult) Rows() [][]any { + v := r.volume + digest := noValue + if v.ManifestSha256 != nil { + digest = *v.ManifestSha256 + } + rows := [][]any{ + {colID, v.Id.String()}, + {colName, v.Name}, + {colEnvironment, v.Environment}, + {colDescription, formatOptionalString(v.Description)}, + {colStatus, string(v.Status)}, + {colSize, humanBytes(v.LogicalBytes)}, + {colFiles, v.FileCount}, + {colFilesDigest, digest}, + {colCreated, v.CreatedAt.Format(time.RFC3339)}, + {colUpdated, v.UpdatedAt.Format(time.RFC3339)}, + } + if !r.withUses { + return rows + } + usedBy, rollbackOf := r.referencesErr, r.referencesErr + if r.references != nil { + usedBy = describeOrNone(r.references.Blocking) + rollbackOf = describeOrNone(r.references.RollbackTargets) + } + return append(rows, + []any{colUsedBy, usedBy}, + []any{colRollbackFor, rollbackOf}, + ) +} + +func (r volumeResult) MarshalJSON() ([]byte, error) { + return json.Marshal(r.volume) +} + +func describeOrNone(refs []serverlessapi.VolumeReference) string { + if len(refs) == 0 { + return noValue + } + return describeVolumeReferences(refs) +} + +// volumesResult is every Volume of an environment. JSON and YAML print it as +// the API's page, holding every Volume and no next cursor. +type volumesResult []serverlessapi.Volume + +func (r volumesResult) Headers() []string { + return []string{colID, colName, colSize, colFiles, colDescription, colUpdated} +} + +func (r volumesResult) Rows() [][]any { + rows := make([][]any, len(r)) + for i := range r { + v := &r[i] + rows[i] = []any{ + shortID(v.Id.String()), + v.Name, + humanBytes(v.LogicalBytes), + v.FileCount, + formatOptionalString(v.Description), + v.UpdatedAt.Format(time.RFC3339), + } + } + return rows +} + +func (r volumesResult) page() serverlessapi.Page[serverlessapi.Volume] { + return serverlessapi.Page[serverlessapi.Volume]{ + Data: r, + } +} + +func (r volumesResult) MarshalJSON() ([]byte, error) { + return json.Marshal(r.page()) +} + +// volumeReferencesResult is the uses of a Volume: one row per app version. +type volumeReferencesResult serverlessapi.VolumeReferences + +func (r volumeReferencesResult) Headers() []string { + return []string{colApp, colVersion, colKind, colEffect} +} + +func (r volumeReferencesResult) Rows() [][]any { + rows := make([][]any, 0, len(r.Blocking)+len(r.RollbackTargets)) + for _, ref := range r.Blocking { + rows = append(rows, []any{referenceApp(ref), ref.AppVersionNumber, volumeReferenceKind(ref.Kind), effectBlocks}) + } + for _, ref := range r.RollbackTargets { + rows = append(rows, []any{referenceApp(ref), ref.AppVersionNumber, volumeReferenceKind(ref.Kind), effectLosesRollback}) + } + return rows +} + +func (r volumeReferencesResult) api() serverlessapi.VolumeReferences { + return serverlessapi.VolumeReferences{ + Blocking: nonNilReferences(r.Blocking), + RollbackTargets: nonNilReferences(r.RollbackTargets), + } +} + +func (r volumeReferencesResult) MarshalJSON() ([]byte, error) { + return json.Marshal(r.api()) +} + +// volumeFilesResult is every one of a Volume's latest files. JSON and YAML +// print it as the API's page, with the digest of the file list it came from. +type volumeFilesResult serverlessapi.VolumeFilePage + +func (r volumeFilesResult) Headers() []string { + return []string{colPath, colSize, colMode, colSHA256} +} + +func (r volumeFilesResult) Rows() [][]any { + rows := make([][]any, len(r.Data)) + for i, f := range r.Data { + rows[i] = []any{ + f.Path, + humanBytes(f.Size), + fmt.Sprintf("%#o", f.Mode), + shortID(f.Sha256), + } + } + return rows +} + +func (r volumeFilesResult) MarshalJSON() ([]byte, error) { + return json.Marshal(serverlessapi.VolumeFilePage(r)) +} + +// volumeDeletedResult reports a deleted Volume and the app versions that lost +// their rollback with it. +type volumeDeletedResult struct { + ID string `json:"id"` + Name string `json:"name"` + Environment string `json:"environment"` + LostRollback []serverlessapi.VolumeReference `json:"lostRollback"` +} + +func (r volumeDeletedResult) Headers() []string { + return []string{colField, colValue} +} + +func (r volumeDeletedResult) Rows() [][]any { + return [][]any{ + {colID, r.ID}, + {colVolume, r.Name}, + {colEnvironment, r.Environment}, + {colDeleted, deletedLogically}, + {colLostRollback, describeOrNone(r.LostRollback)}, + } +} + +// volumeSettingsResult is the organization's Shared Volume access and limits. +type volumeSettingsResult serverlessapi.VolumeSettings + +func (r volumeSettingsResult) Headers() []string { + return []string{colField, colValue} +} + +func (r volumeSettingsResult) Rows() [][]any { + l := r.Limits + return [][]any{ + {colAvailable, formatYesNo(r.Available)}, + {colMaxStored, humanBytes(l.MaxStoredBytes)}, + {colMaxFileSize, humanBytes(l.MaxFileBytes)}, + {colMaxFiles, strconv.FormatInt(l.MaxFilesPerVolume, 10)}, + {colMaxMounted, humanBytes(l.MaxMountedBytesPerAppVersion)}, + {colUploadDeadline, (time.Duration(l.UploadSessionTtlSeconds) * time.Second).String()}, + } +} + +func (r volumeSettingsResult) MarshalJSON() ([]byte, error) { + return json.Marshal(serverlessapi.VolumeSettings(r)) +} diff --git a/internal/cmd/serverless/volumes_manage.go b/internal/cmd/serverless/volumes_manage.go new file mode 100644 index 0000000..2b96122 --- /dev/null +++ b/internal/cmd/serverless/volumes_manage.go @@ -0,0 +1,695 @@ +package serverless + +import ( + "cmp" + "errors" + "fmt" + "net/http" + "strings" + + "github.com/charmbracelet/log" + "github.com/oapi-codegen/nullable" + serverlessapi "github.com/runware/runware-cli/internal/api/serverless" + "github.com/runware/runware-cli/internal/api/transport" + "github.com/runware/runware-cli/internal/cmdutil" + "github.com/runware/runware-cli/internal/config" + "github.com/runware/runware-cli/internal/output" + "github.com/spf13/cobra" +) + +const ( + descriptionFlag = "description" + descriptionField = "description" + // volumeSettingsCommand is the command that shows the organization's + // access and limits. + volumeSettingsCommand = "runware serverless volumes settings" +) + +var errNothingToUpdateOnVolume = errors.New("nothing to update; pass --description or --clear description") + +// volumesHelpLong is the help of the volumes group. +const volumesHelpLong = `Manage Shared Volumes: named, durable sets of files that apps mount. + +Shared Volumes are in beta. These commands need Shared Volumes enabled for the +organization, which 'volumes settings' shows, and they may change before general +availability. + +A Volume belongs to one environment, and only apps in that environment mount +it. Every command here except 'settings' takes --env to select that +environment, else the default environment (RUNWARE_ENV, else the config's) or +production. + +The lifecycle: + + 1. 'volumes create' makes an empty Volume. No app is needed. + 2. 'volumes put' uploads files into it. Uploads are additive: they add or + replace the paths they name and keep every other file. + 3. 'deploy --mount' mounts it into an app. + +A Volume has one set of files, its latest files. Workers mount the latest +files when they start; running workers keep theirs until they stop. Rolling an +app back does not bring back older files. To start clean, create a new Volume. + +A Shared Volume is not the node-local folder 'deploy --volume' declares: that +folder lives on one machine, while a Volume is stored by the platform and +mounted wherever the app's workers run. + +Deleting a Volume is logical: it stops new mounts at once, and the platform +may reclaim the stored bytes later.` + +// addVolumeEnvironmentFlag registers --env on a Volume command that addresses +// one environment. +func addVolumeEnvironmentFlag(cmd *cobra.Command, logger *log.Logger) { + addEnvironmentFlag(cmd, cmd.Flags(), logger, "Environment the Volume belongs to "+environmentFlagDefault) +} + +func newVolumesListCmd(logger *log.Logger) *cobra.Command { + cmd := &cobra.Command{ + Use: connectorsListUse, + Short: "List Volumes", + Long: `List every Volume in one environment, newest first, following every page. + +The table shows sizes in binary units and short ids; --format json or yaml +prints the API objects with sizes in bytes and full ids.`, + Example: ` # list the Volumes of the default environment (production unless set) + runware serverless volumes list + + # list the staging Volumes as JSON + runware serverless volumes list --env staging --format json`, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + spin := cmdutil.NewSpinner("Fetching Volumes...") + spin.Start() + + client := newServerlessClient(cmd, logger) + volumes, err := client.AllVolumes(cmd.Context()) + spin.Stop() + if err != nil { + return volumeError(cmd, client, err, volumeOperation{ + action: "Listing Volumes", + }) + } + + return output.Print(cmdutil.FormatFor(cmd), volumesResult(volumes)) + }, + } + addVolumeEnvironmentFlag(cmd, logger) + return cmd +} + +func newVolumesCreateCmd(logger *log.Logger) *cobra.Command { + var description string + + cmd := &cobra.Command{ + Use: "create ", + Short: "Create a Volume", + Long: `Create an empty Volume in one environment. + +The name is unique among the environment's Volumes and never changes. Fill the +Volume with 'volumes put', then mount it with 'deploy --mount'.`, + Example: ` # create a Volume in the default environment (production unless set) + runware serverless volumes create model-weights + + # create one in staging with a description + runware serverless volumes create model-weights --env staging --description "SDXL base and refiner weights"`, + Args: volumeNameArg, + RunE: func(cmd *cobra.Command, args []string) error { + body := serverlessapi.VolumeCreate{ + Name: args[0], + } + if cmd.Flags().Changed(descriptionFlag) { + body.Description = &description + } + + spin := cmdutil.NewSpinner(fmt.Sprintf("Creating Volume %s...", body.Name)) + spin.Start() + + client := newServerlessClient(cmd, logger) + volume, err := client.CreateVolume(cmd.Context(), body) + spin.Stop() + if err != nil { + return volumeError(cmd, client, err, volumeOperation{ + action: "Creating a Volume", + name: body.Name, + creates: true, + unchanged: "nothing was created", + }) + } + + return output.Print(cmdutil.FormatFor(cmd), volumeResult{ + volume: *volume, + }) + }, + } + cmd.Flags().StringVar(&description, descriptionFlag, "", "Free-text description, at most 1024 characters") + addVolumeEnvironmentFlag(cmd, logger) + return cmd +} + +func newVolumesShowCmd(logger *log.Logger) *cobra.Command { + cmd := &cobra.Command{ + Use: "show ", + Short: "Show a Volume", + Long: `Show a Volume: its size, file count, the digest of its latest file list, +and the app versions that use it. + +The digest changes exactly when the latest files change, so comparing it tells +whether they did. It is not an id: nothing accepts it. + +--format json or yaml prints the API's Volume object; 'volumes references' +prints the uses on their own.`, + Example: ` runware serverless volumes show model-weights + + # the staging Volume as JSON + runware serverless volumes show model-weights --env staging --format json`, + Args: volumeNameArg, + RunE: func(cmd *cobra.Command, args []string) error { + name := args[0] + + spin := cmdutil.NewSpinner(fmt.Sprintf("Fetching Volume %s...", name)) + spin.Start() + + client := newServerlessClient(cmd, logger) + volume, err := client.GetVolume(cmd.Context(), name) + if err != nil { + spin.Stop() + return volumeError(cmd, client, err, volumeOperation{ + action: "Reading a Volume", + name: name, + }) + } + result := volumeResult{ + volume: *volume, + } + if cmdutil.FormatFor(cmd) == output.FormatTable { + result.withUses = true + // A failed read shows the uses as unavailable, never as + // the pages read before it failed. + refs, err := client.AllVolumeReferences(cmd.Context(), name) + if err != nil { + result.referencesErr = referencesUnavailable(err) + } else { + result.references = refs + } + } + spin.Stop() + + return output.Print(cmdutil.FormatFor(cmd), result) + }, + } + addVolumeEnvironmentFlag(cmd, logger) + return cmd +} + +func newVolumesUpdateCmd(logger *log.Logger) *cobra.Command { + var ( + description string + clears []string + ) + + cmd := &cobra.Command{ + Use: "update ", + Short: "Update a Volume's description", + Long: `Change a Volume's description, the only thing about a Volume that changes +here. Its name and environment never change, and its files change only through +'volumes put'. + +--clear description removes the description.`, + Example: ` # replace the description + runware serverless volumes update model-weights --description "SDXL weights, fp16" + + # remove it + runware serverless volumes update model-weights --clear description`, + Args: volumeNameArg, + RunE: func(cmd *cobra.Command, args []string) error { + name := args[0] + body, err := volumeUpdateBody(cmd, description, clears) + if err != nil { + return err + } + + spin := cmdutil.NewSpinner(fmt.Sprintf("Updating Volume %s...", name)) + spin.Start() + + client := newServerlessClient(cmd, logger) + volume, err := client.UpdateVolume(cmd.Context(), name, body) + spin.Stop() + if err != nil { + return volumeError(cmd, client, err, volumeOperation{ + action: "Updating a Volume", + name: name, + unchanged: "nothing was changed", + }) + } + + return output.Print(cmdutil.FormatFor(cmd), volumeResult{ + volume: *volume, + }) + }, + } + cmd.Flags().StringVar(&description, descriptionFlag, "", "New free-text description, at most 1024 characters") + addClearFlag(cmd, &clears, []string{descriptionField}) + addVolumeEnvironmentFlag(cmd, logger) + return cmd +} + +// volumeUpdateBody is the patch the update flags ask for: a description that +// replaces the current one, or null to clear it. +func volumeUpdateBody(cmd *cobra.Command, description string, clears []string) (serverlessapi.VolumeUpdate, error) { + cleared, err := clearedFields(cmd.Flags(), clears, []string{descriptionField}) + if err != nil { + return serverlessapi.VolumeUpdate{}, err + } + var body serverlessapi.VolumeUpdate + switch { + case len(cleared) > 0: + body.Description = nullable.NewNullNullable[serverlessapi.VolumeDescription]() + case cmd.Flags().Changed(descriptionFlag): + body.Description = nullable.NewNullableWithValue(description) + default: + return serverlessapi.VolumeUpdate{}, errNothingToUpdateOnVolume + } + return body, nil +} + +func newVolumesDeleteCmd(logger *log.Logger) *cobra.Command { + var ( + yes bool + force bool + ) + + cmd := &cobra.Command{ + Use: "delete ", + Short: "Delete a Volume", + Long: `Delete a whole Volume: its latest files and any upload still open on it. +Individual files cannot be deleted. + +The API currently deletes only a Volume that has never had files published +and that no app version uses. For any other Volume that passes the checks +below, including one that only older app versions use once that is confirmed, +it answers 501 Not Implemented and nothing is deleted. + +The command reads the Volume and its references first. A Volume that a +current app version, a deploy in progress or a running worker uses is not +deleted: the command prints those uses and fails. When only older app +versions use it, a deletion takes their rollback, so the command names them +and asks before it goes ahead, and asks again if they change while it waits. +The API checks the uses again when the delete commits, and confirming never +overrides a current use. The delete names the Volume by the id it read, so it +never deletes a new Volume that took the name meanwhile. + +The deletion is logical. New mounts of the Volume stop at once, and the +platform may reclaim its stored bytes later. A new Volume with the same name +is a different Volume, and never satisfies a mount of this one. + +Confirmation is required unless --yes or --force is passed.`, + Example: ` # delete a Volume (prompts for confirmation) + runware serverless volumes delete model-weights + + # delete the staging Volume without a prompt + runware serverless volumes delete model-weights --env staging --yes`, + Args: volumeNameArg, + RunE: func(cmd *cobra.Command, args []string) error { + return deleteVolume(cmd, logger, args[0], yes || force) + }, + } + addDeleteConfirmFlags(cmd, &yes, &force) + addVolumeEnvironmentFlag(cmd, logger) + return cmd +} + +// deleteVolume deletes a Volume after reading it and its references: it +// refuses a Volume in use, and names the app versions a confirmed delete takes +// the rollback from before it asks, and again when they change while it asks. +// The references come first even without a terminal, so a script that forgot +// --yes still learns what uses the Volume. The delete sends the id read +// first, which the API requires, so a Volume that takes the name between the +// read and the delete is never deleted. +func deleteVolume(cmd *cobra.Command, logger *log.Logger, name string, skipConfirm bool) error { + if config.GetAPIKey() == "" { + return transport.ErrNoAPIKey + } + in, errOut := cmd.InOrStdin(), cmd.ErrOrStderr() + isTTY := stdinIsTerminal(in) + + client := newServerlessClient(cmd, logger) + spin := cmdutil.NewSpinner(fmt.Sprintf("Reading Volume %s...", name)) + spin.Start() + volume, err := client.GetVolume(cmd.Context(), name) + spin.Stop() + if err != nil { + return volumeError(cmd, client, err, volumeOperation{ + action: "Reading the Volume to delete", + name: name, + unchanged: "nothing was deleted", + }) + } + refs, err := readDeletableReferences(cmd, client, name) + if err != nil { + return err + } + + var confirmRollbackLoss bool + for { + confirmRollbackLoss = len(refs.RollbackTargets) > 0 + if confirmRollbackLoss { + _, _ = fmt.Fprintf(errOut, "Deleting Volume %s removes the rollback of %s.\n", name, describeVolumeReferences(refs.RollbackTargets)) + } + if err := confirmDelete(deleteSubject(cmd, "Volume "+name), skipConfirm, in, errOut, isTTY, config.GetAPIKey()); err != nil { + return err + } + if skipConfirm { + break + } + // The prompt waits without a time limit, so the confirmed rollback + // targets may be stale: read them again, and ask again on a change. + var fresh *serverlessapi.VolumeReferences + fresh, err = readDeletableReferences(cmd, client, name) + if err != nil { + return err + } + if sameVolumeReferences(fresh.RollbackTargets, refs.RollbackTargets) { + break + } + refs = fresh + _, _ = fmt.Fprintf(errOut, "What uses Volume %s changed while the prompt waited.\n", name) + } + + spin = cmdutil.NewSpinner(fmt.Sprintf("Deleting Volume %s...", name)) + spin.Start() + err = client.DeleteVolume(cmd.Context(), name, volume.Id, confirmRollbackLoss) + spin.Stop() + if err != nil { + return volumeDeleteError(cmd, client, err, name) + } + + return output.Print(cmdutil.FormatFor(cmd), volumeDeletedResult{ + ID: volume.Id.String(), + Name: name, + Environment: volumeEnvironment(cmd), + LostRollback: nonNilReferences(refs.RollbackTargets), + }) +} + +// readDeletableReferences reads what uses Volume name for a delete. A use +// that blocks the delete is printed and refused. +func readDeletableReferences(cmd *cobra.Command, client *serverlessapi.Client, name string) (*serverlessapi.VolumeReferences, error) { + spin := cmdutil.NewSpinner(fmt.Sprintf("Reading what uses Volume %s...", name)) + spin.Start() + refs, err := client.AllVolumeReferences(cmd.Context(), name) + spin.Stop() + if err != nil { + return nil, volumeError(cmd, client, err, volumeOperation{ + action: "Listing what uses a Volume, which a delete reads first,", + name: name, + unchanged: "nothing was deleted", + }) + } + if len(refs.Blocking) > 0 { + if err := output.Print(cmdutil.FormatFor(cmd), volumeReferencesResult(*refs)); err != nil { + return nil, err + } + return nil, fmt.Errorf("volume %s is in use by %s, so nothing was deleted; remove it from those apps, wait for their deploys and workers to finish, and retry", name, describeVolumeReferences(refs.Blocking)) + } + return refs, nil +} + +// sameVolumeReferences reports whether a and b name the same app versions, +// in any order. +func sameVolumeReferences(a, b []serverlessapi.VolumeReference) bool { + if len(a) != len(b) { + return false + } + seen := make(map[serverlessapi.VolumeReference]struct{}, len(a)) + for _, r := range a { + seen[r] = struct{}{} + } + for _, r := range b { + if _, ok := seen[r]; !ok { + return false + } + } + return true +} + +// volumeDeleteError explains a refused delete. The references were read +// before the delete, so a conflict means a use appeared in between. A 501 is +// the API's answer to a delete it does not perform, so it says which Volumes +// the API deletes rather than suggesting a retry. +func volumeDeleteError(cmd *cobra.Command, client *serverlessapi.Client, err error, name string) error { + re, ok := errors.AsType[*transport.RunwareError](err) + if ok && re.StatusCode == http.StatusNotImplemented { + return withMessage(re, fmt.Sprintf("the API answered 501 Not Implemented, so Volume %s was not deleted: it currently deletes only a Volume that has never had files published and that no app version uses", name)) + } + if ok && re.StatusCode == http.StatusConflict { + refsCommand := serverlessCommand(volumeEnvironment(cmd), defaultEnvironment(cmd), "volumes", "references", name) + switch re.ProblemType { + case serverlessapi.ProblemVolumeInUse: + return withMessage(re, fmt.Sprintf("Volume %s came into use after its references were read, so nothing was deleted; see '%s'", name, refsCommand)) + case serverlessapi.ProblemVolumeRollbackConfirmationRequired: + return withMessage(re, fmt.Sprintf("an older app version started using Volume %s after its references were read, so nothing was deleted; retry to review it", name)) + } + } + return volumeError(cmd, client, err, volumeOperation{ + action: "Deleting a Volume", + name: name, + unchanged: "the Volume was not deleted", + }) +} + +func newVolumesReferencesCmd(logger *log.Logger) *cobra.Command { + cmd := &cobra.Command{ + Use: "references ", + Short: "List what uses a Volume", + Long: `List the app versions that use a Volume, following every page. + +Current app versions, deploys in progress and running workers block a delete. +Older app versions do not, but a delete takes their rollback. The list is a +snapshot: 'volumes delete' reads it again, and the API checks again when the +delete commits.`, + Example: ` runware serverless volumes references model-weights + + # as JSON, for a script + runware serverless volumes references model-weights --format json`, + Args: volumeNameArg, + RunE: func(cmd *cobra.Command, args []string) error { + name := args[0] + + spin := cmdutil.NewSpinner(fmt.Sprintf("Reading what uses Volume %s...", name)) + spin.Start() + + client := newServerlessClient(cmd, logger) + refs, err := client.AllVolumeReferences(cmd.Context(), name) + spin.Stop() + if err != nil { + return volumeError(cmd, client, err, volumeOperation{ + action: "Listing what uses a Volume", + name: name, + }) + } + if len(refs.Blocking) == 0 && len(refs.RollbackTargets) == 0 && cmdutil.FormatFor(cmd) == output.FormatTable { + _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "No app version uses Volume %s.\n", name) + } + + return output.Print(cmdutil.FormatFor(cmd), volumeReferencesResult(*refs)) + }, + } + addVolumeEnvironmentFlag(cmd, logger) + return cmd +} + +func newVolumesFilesCmd(logger *log.Logger) *cobra.Command { + cmd := &cobra.Command{ + Use: "files ", + Short: "List a Volume's latest files", + Long: `List every one of a Volume's latest files, ordered by path, following every +page. + +The listing reads file metadata only: paths, sizes, modes and digests. There is +no download. When an upload changes the files between two pages, the command +starts again, so the list always comes from one file set.`, + Example: ` runware serverless volumes files model-weights + + # every path, size in bytes and digest as JSON + runware serverless volumes files model-weights --format json`, + Args: volumeNameArg, + RunE: func(cmd *cobra.Command, args []string) error { + name := args[0] + + spin := cmdutil.NewSpinner(fmt.Sprintf("Fetching the files of Volume %s...", name)) + spin.Start() + + client := newServerlessClient(cmd, logger) + files, err := client.LatestVolumeFiles(cmd.Context(), name) + spin.Stop() + if err != nil { + return volumeError(cmd, client, err, volumeOperation{ + action: "Listing a Volume's files", + name: name, + }) + } + if len(files.Data) == 0 && cmdutil.FormatFor(cmd) == output.FormatTable { + _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Volume %s has no files yet.\n", name) + } + + return output.Print(cmdutil.FormatFor(cmd), volumeFilesResult(files)) + }, + } + addVolumeEnvironmentFlag(cmd, logger) + return cmd +} + +func newVolumesSettingsCmd(logger *log.Logger) *cobra.Command { + return &cobra.Command{ + Use: "settings", + Short: "Show the organization's Shared Volume access and limits", + Long: `Show whether Shared Volumes are enabled for the organization, and the +effective limits that apply to every environment. + +Settings belong to the organization, so this command takes no --env.`, + Example: ` runware serverless volumes settings + + # limits in bytes, for a script + runware serverless volumes settings --format json`, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + spin := cmdutil.NewSpinner("Fetching Shared Volume settings...") + spin.Start() + + settings, err := newServerlessClient(cmd, logger).GetVolumeSettings(cmd.Context()) + spin.Stop() + if err != nil { + return err + } + + return output.Print(cmdutil.FormatFor(cmd), volumeSettingsResult(*settings)) + }, + } +} + +// volumeNameArg takes one argument, a Volume name the API accepts. +func volumeNameArg(cmd *cobra.Command, args []string) error { + if err := cobra.ExactArgs(1)(cmd, args); err != nil { + return err + } + if !volumeNamePattern.MatchString(args[0]) { + return errVolumeName + } + return nil +} + +// referencesUnavailable is the short reason show gives when it cannot read a +// Volume's references. +func referencesUnavailable(err error) string { + if re, ok := errors.AsType[*transport.RunwareError](err); ok && re.StatusCode == http.StatusNotImplemented { + return "unavailable: not implemented by the API yet" + } + msg, _, _ := strings.Cut(err.Error(), "\n") + return "unavailable: " + msg +} + +// volumeEnvironment is the environment a Volume command addresses. +func volumeEnvironment(cmd *cobra.Command) string { + return cmp.Or(commandEnvironment(cmd), serverlessapi.ProductionEnvironment) +} + +// volumeOperation describes the command a Shared Volume refusal stopped. +type volumeOperation struct { + // action names the operation as the start of a sentence. + action string + // name is the Volume the command addresses, or "" for list. + name string + // creates marks an operation whose 404 cannot mean an unknown Volume. + creates bool + // unchanged says what did not happen, for an operation that would change + // something, or "". + unchanged string +} + +// volumeError turns a Shared Volume refusal into one line that says what to +// do next. Any other error passes through unchanged. +func volumeError(cmd *cobra.Command, client *serverlessapi.Client, err error, op volumeOperation) error { + re, ok := errors.AsType[*transport.RunwareError](err) + if !ok { + return err + } + unchanged := "" + if op.unchanged != "" { + unchanged = "; " + op.unchanged + } + env := volumeEnvironment(cmd) + switch re.StatusCode { + case http.StatusNotFound: + // An organization without beta access gets the 404 of an unknown + // path on every Volume route but the settings, so the settings tell + // the two apart. An unknown environment is a 404 too, so a missing + // Volume is named only once its environment is known to exist. + // Otherwise the 404 stays as the API said it. + settings, settingsErr := client.GetVolumeSettings(cmd.Context()) + switch { + case settingsErr == nil && !settings.Available: + return withMessage(re, "Shared Volumes are not enabled for this organization"+unchanged+"; ask Runware for beta access, and check it with '"+volumeSettingsCommand+"'") + case settingsErr == nil && op.name != "" && !op.creates && environmentExists(cmd, client, env): + return withMessage(re, fmt.Sprintf("no Volume named %s in environment %s%s; list them with '%s'", op.name, env, unchanged, serverlessCommand(env, defaultEnvironment(cmd), "volumes", "list"))) + } + case http.StatusNotImplemented: + return withMessage(re, op.action+" is not available yet: the API answered 501 Not Implemented"+unchanged+"; retry after the API release that adds it") + case http.StatusConflict: + if re.ProblemType == serverlessapi.ProblemVolumeNameTaken { + return withMessage(re, fmt.Sprintf("a Volume named %s already exists in environment %s, or one by that name is still being deleted%s; choose another name", op.name, env, unchanged)) + } + } + return err +} + +// environmentExists reports whether the API knows environment env. Every +// organization has production; any other environment is read, and a failed +// read counts as unknown, so the caller keeps the API's own answer. +func environmentExists(cmd *cobra.Command, client *serverlessapi.Client, env string) bool { + if isProductionEnvironment(env) { + return true + } + _, err := client.GetEnvironment(cmd.Context(), env) + return err == nil +} + +// withMessage is a copy of re that says message instead. +func withMessage(re *transport.RunwareError, message string) error { + out := *re + out.Message = message + return &out +} + +// describeVolumeReferences names app versions as "img-gen v7 (current app +// version), img-gen v3". +func describeVolumeReferences(refs []serverlessapi.VolumeReference) string { + parts := make([]string, len(refs)) + for i, r := range refs { + parts[i] = fmt.Sprintf("%s v%d", referenceApp(r), r.AppVersionNumber) + if r.Kind != serverlessapi.VolumeReferenceRollbackTarget { + parts[i] += " (" + volumeReferenceKind(r.Kind) + ")" + } + } + return strings.Join(parts, ", ") +} + +// referenceApp names the app of a use, marking a deleted app, whose id a new +// app may have taken since. +func referenceApp(r serverlessapi.VolumeReference) string { + if r.AppDeleted { + return r.AppId + " (deleted app)" + } + return r.AppId +} + +// volumeReferenceKind is a reference kind in words. +func volumeReferenceKind(kind serverlessapi.VolumeReferenceKind) string { + return strings.ReplaceAll(string(kind), "-", " ") +} + +func nonNilReferences(refs []serverlessapi.VolumeReference) []serverlessapi.VolumeReference { + if refs == nil { + return []serverlessapi.VolumeReference{} + } + return refs +} diff --git a/internal/cmd/serverless/volumes_manage_test.go b/internal/cmd/serverless/volumes_manage_test.go new file mode 100644 index 0000000..4177685 --- /dev/null +++ b/internal/cmd/serverless/volumes_manage_test.go @@ -0,0 +1,1436 @@ +package serverless + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "net/url" + "os" + "slices" + "strings" + "sync" + "testing" + "testing/iotest" + + "github.com/charmbracelet/log" + serverlessapi "github.com/runware/runware-cli/internal/api/serverless" + "github.com/runware/runware-cli/internal/api/transport" + "github.com/runware/runware-cli/internal/cmdutil" + "github.com/runware/runware-cli/internal/output" + "gopkg.in/yaml.v3" +) + +const ( + testVolumesGroup = "volumes" + testVolumesPath = "/v1/volumes" + testSharedVolumePath = testVolumesPath + "/" + testVolume + testVolumeRefsPath = testSharedVolumePath + "/references" + testVolumeFilesPath = testSharedVolumePath + "/files" + testVolumeSettings = "/v1/volumes-settings" + testVolumeDigest = "9f2c4e1a7b3d5f8e0c6a2b4d1e3f5a7c9b0d2e4f6a8c1b3d5e7f9a0c2e4b6d8f" + testOtherDigest = "0e1d2c3b4a5f6e7d8c9b0a1f2e3d4c5b6a7f8e9d0c1b2a3f4e5d6c7b8a9f0e1d" + testFormatJSON = "json" + testFormatYAML = "yaml" + testConfirmParam = "confirmRollbackLoss" + testEnvironmentParam = "environment" + testReferencesCommand = "references" + testFilesCommand = "files" + testCreateCommand = "create" + testVolumeID = "6a1f0d6e-5c1b-4f69-9a39-0f4c1c8b2d11" + testVolumeIDParam = "volumeId" + // testVolumeFileListAttempts is how often the client reads a Volume's + // files before it gives up on a list that keeps changing. + testVolumeFileListAttempts = 3 + + testVolumeBody = `{ + "id":"` + testVolumeID + `", + "name":"model-weights", + "environment":"production", + "description":"SDXL weights", + "status":"live", + "logicalBytes":10604643268, + "fileCount":2, + "manifestSha256":"` + testVolumeDigest + `", + "createdAt":"2026-11-02T10:00:00Z", + "updatedAt":"2026-11-02T12:30:00Z" + }` + testSecondVolumeBody = `{ + "id":"0b7e4c2a-9d3f-4e51-8c6a-2f1d0e9b7a44", + "name":"reference-data", + "environment":"production", + "status":"live", + "logicalBytes":0, + "fileCount":0, + "createdAt":"2026-11-01T09:00:00Z", + "updatedAt":"2026-11-01T09:00:00Z" + }` + testNoReferences = `{"blocking":[],"rollbackTargets":[]}` + testTwoRollbackReferences = `{"blocking":[],"rollbackTargets":[{"appId":"img-gen","appVersionNumber":3,"kind":"rollback-target"},{"appId":"img-gen","appVersionNumber":4,"kind":"rollback-target"}]}` + testRetryAfterRelease = "retry after the API release that adds it" + testBlockingReferences = `{"blocking":[{"appId":"img-gen","appVersionNumber":7,"kind":"current-app-version"}],"rollbackTargets":[{"appId":"img-gen","appVersionNumber":3,"kind":"rollback-target"}]}` + testRollbackReferences = `{"blocking":[],"rollbackTargets":[{"appId":"img-gen","appVersionNumber":3,"kind":"rollback-target"}]}` + testSettingsEnabled = `{"available":true,"limits":{"maxStoredBytes":1099511627776,"maxFileBytes":268435456000,"maxFilesPerVolume":100000,"maxMountedBytesPerAppVersion":536870912000,"uploadSessionTtlSeconds":86400}}` + testSettingsDisabled = `{"available":false,"limits":{"maxStoredBytes":1099511627776,"maxFileBytes":268435456000,"maxFilesPerVolume":100000,"maxMountedBytesPerAppVersion":268435456000,"uploadSessionTtlSeconds":86400}}` + testNotImplemented = `{"type":"https://docs.runware.ai/serverless/errors#not-implemented","title":"Not Implemented","status":501,"detail":"Not Implemented"}` + testNoRoute = `{"type":"https://docs.runware.ai/serverless/errors#not-found","title":"Not Found","status":404,"detail":"no route matches the request path"}` + testEnvironmentNotFound = `{"type":"https://docs.runware.ai/serverless/errors#not-found","title":"Not Found","status":404,"detail":"environment not found"}` + testVolumeNotFound = `{"type":"https://docs.runware.ai/serverless/errors#not-found","title":"Not Found","status":404,"detail":"volume not found"}` + testVolumeInUse = `{"type":"https://docs.runware.ai/serverless/errors#volume-in-use","title":"Conflict","status":409,"detail":"the Volume is in use; list its references to see where"}` + testNameTaken = `{"type":"https://docs.runware.ai/serverless/errors#volume-name-taken","title":"Conflict","status":409,"detail":"a Volume named 'model-weights' already exists in this environment"}` + testRollbackConfirmationRequired = `{"type":"https://docs.runware.ai/serverless/errors#volume-rollback-confirmation-required","title":"Conflict","status":409,"detail":"older app versions would lose their rollback; retry with confirmRollbackLoss=true"}` +) + +// volumeRequest is one request the Volume stub received. +type volumeRequest struct { + method string + path string + query url.Values + body string +} + +// volumeAPI answers each "METHOD /path" with the next of its responses, +// repeating the last, and records every request. +type volumeAPI struct { + t *testing.T + mu sync.Mutex + responses map[string][]stubResponse + requests []volumeRequest +} + +// newVolumeAPI copies responses, so a table case can serve several runs. +func newVolumeAPI(t *testing.T, responses map[string][]stubResponse) *volumeAPI { + queues := make(map[string][]stubResponse, len(responses)) + for key, queue := range responses { + queues[key] = slices.Clone(queue) + } + return &volumeAPI{ + t: t, + responses: queues, + } +} + +func (a *volumeAPI) ServeHTTP(w http.ResponseWriter, r *http.Request) { + raw, err := io.ReadAll(r.Body) + if err != nil { + a.t.Error(err) + } + key := r.Method + " " + r.URL.Path + a.mu.Lock() + a.requests = append(a.requests, volumeRequest{ + method: r.Method, + path: r.URL.Path, + query: r.URL.Query(), + body: string(raw), + }) + queue, ok := a.responses[key] + var resp stubResponse + if ok && len(queue) > 0 { + resp = queue[0] + if len(queue) > 1 { + a.responses[key] = queue[1:] + } + } + a.mu.Unlock() + if !ok { + a.t.Errorf("unexpected %s", key) + writeNotFound(w) + return + } + contentType := "application/json" + if resp.status >= http.StatusBadRequest { + contentType = "application/problem+json" + } + w.Header().Set("Content-Type", contentType) + w.WriteHeader(resp.status) + _, _ = io.WriteString(w, resp.body) +} + +// sent returns the requests to method and path. +func (a *volumeAPI) sent(method, path string) []volumeRequest { + a.mu.Lock() + defer a.mu.Unlock() + var out []volumeRequest + for _, r := range a.requests { + if r.method == method && r.path == path { + out = append(out, r) + } + } + return out +} + +func ok(body string) []stubResponse { + return answer(http.StatusOK, body) +} + +func answer(status int, body string) []stubResponse { + return []stubResponse{ + { + status: status, + body: body, + }, + } +} + +// volumesRun is what one volumes command did. +type volumesRun struct { + stdout string + stderr string + err error +} + +// runVolumes runs `serverless volumes ` in format against api, with +// stdin answering prompts, and no default environment. +func runVolumes(t *testing.T, api *volumeAPI, format string, stdin io.Reader, args ...string) volumesRun { + t.Helper() + withoutDefaultEnvironment(t) + srv := httptest.NewServer(api) + defer srv.Close() + t.Setenv("RUNWARE_API_KEY", "test-key") + t.Setenv("RUNWARE_SERVERLESS_BASE_URL", srv.URL) + + cmd := NewCmd(log.New(io.Discard)) + cmd.PersistentFlags().String("format", format, "") + var stderr bytes.Buffer + cmd.SetOut(&stderr) + cmd.SetErr(&stderr) + cmd.SetIn(stdin) + cmd.SetArgs(append([]string{testVolumesGroup}, args...)) + + f, err := os.CreateTemp(t.TempDir(), "stdout") + if err != nil { + t.Fatal(err) + } + old := os.Stdout + os.Stdout = f + execErr := cmd.Execute() + os.Stdout = old + _ = f.Close() + out, err := os.ReadFile(f.Name()) + if err != nil { + t.Fatal(err) + } + return volumesRun{ + stdout: string(out), + stderr: stderr.String(), + err: execErr, + } +} + +func runVolumesTable(t *testing.T, api *volumeAPI, args ...string) volumesRun { + t.Helper() + return runVolumes(t, api, "", strings.NewReader(""), args...) +} + +func requireOutput(t *testing.T, out string, want ...string) { + t.Helper() + for _, w := range want { + if !strings.Contains(out, w) { + t.Errorf("output missing %q:\n%s", w, out) + } + } +} + +// requireRow fails unless one line of out has every string of want, so a +// label cannot pass with another row's value. +func requireRow(t *testing.T, out string, want ...string) { + t.Helper() + for line := range strings.SplitSeq(out, "\n") { + if containsAll(line, want) { + return + } + } + t.Errorf("no line has all of %q:\n%s", want, out) +} + +func containsAll(s string, want []string) bool { + for _, w := range want { + if !strings.Contains(s, w) { + return false + } + } + return true +} + +func requireErr(t *testing.T, run volumesRun, want ...string) { + t.Helper() + if run.err == nil { + t.Fatalf("err = nil, want %q; stdout:\n%s", want, run.stdout) + } + if strings.Contains(run.err.Error(), "\n") { + t.Errorf("err spans several lines: %q", run.err) + } + for _, w := range want { + if !strings.Contains(run.err.Error(), w) { + t.Errorf("err = %q, want %q", run.err, w) + } + } +} + +func TestVolumesGroupIsHiddenAndExplainsTheLifecycle(t *testing.T) { + cmd := newVolumesCmd(log.New(io.Discard)) + if !cmd.Hidden { + t.Fatal("volumes is visible before release") + } + for _, want := range []string{"beta", "Shared Volumes enabled", "volumes create", "volumes put", "deploy --mount", "additive", "latest files", "does not bring back older files", "create a new Volume", "deploy --volume"} { + if !strings.Contains(cmd.Long, want) { + t.Errorf("group help missing %q", want) + } + } + lower := strings.ToLower(cmd.Long) + for _, promise := range []string{"download", "version history", "delete a file", "delete files"} { + if strings.Contains(lower, promise) { + t.Errorf("group help promises %q", promise) + } + } + for _, sub := range cmd.Commands() { + if sub.Short == "" || sub.Long == "" || sub.Example == "" { + t.Errorf("%s lacks help or an example", sub.Name()) + } + } +} + +func TestVolumesListFollowsEveryPage(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testVolumesPath: { + { + status: http.StatusOK, + body: `{"data":[` + testVolumeBody + `],"nextCursor":"c1"}`, + }, + { + status: http.StatusOK, + body: `{"data":[` + testSecondVolumeBody + `],"nextCursor":null}`, + }, + }, + }) + + run := runVolumesTable(t, api, appHealthListCommand) + + if run.err != nil { + t.Fatal(run.err) + } + requireOutput(t, run.stdout, testVolume, "reference-data", "9.9 GiB", "6a1f0d6e ") + if strings.Contains(run.stdout, "6a1f0d6e-5c1b") { + t.Errorf("table shows a full id:\n%s", run.stdout) + } + sent := api.sent(http.MethodGet, testVolumesPath) + if len(sent) != 2 || sent[1].query["cursor"][0] != "c1" || sent[0].query["limit"][0] != "100" { + t.Fatalf("requests = %+v, want two pages of 100", sent) + } +} + +func TestVolumesListStopsOnARepeatedCursor(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testVolumesPath: ok(`{"data":[],"nextCursor":"c1"}`), + }) + + run := runVolumesTable(t, api, appHealthListCommand) + + if run.err == nil || !strings.Contains(run.err.Error(), "same page cursor twice") { + t.Fatalf("err = %v, want a repeated cursor error", run.err) + } +} + +func TestVolumesStructuredOutputIsTheAPIObject(t *testing.T) { + cases := []struct { + name string + args []string + responses map[string][]stubResponse + key string + // items is how many entries data must hold, or 0 to skip the check. + items int + }{ + { + name: appHealthListCommand, + args: []string{appHealthListCommand}, + responses: map[string][]stubResponse{ + "GET " + testVolumesPath: { + { + status: http.StatusOK, + body: `{"data":[` + testVolumeBody + `],"nextCursor":"c1"}`, + }, + { + status: http.StatusOK, + body: `{"data":[` + testSecondVolumeBody + `]}`, + }, + }, + }, + key: "data", + items: 2, + }, + { + name: appHealthShowCommand, + args: []string{appHealthShowCommand, testVolume}, + responses: map[string][]stubResponse{ + "GET " + testSharedVolumePath: ok(testVolumeBody), + }, + key: "logicalBytes", + }, + { + name: "references", + args: []string{testReferencesCommand, testVolume}, + responses: map[string][]stubResponse{ + "GET " + testVolumeRefsPath: ok(testBlockingReferences), + }, + key: "rollbackTargets", + }, + { + name: "files", + args: []string{testFilesCommand, testVolume}, + responses: map[string][]stubResponse{ + "GET " + testVolumeFilesPath: ok(`{"manifestSha256":"` + testVolumeDigest + `","data":[{"path":"a.bin","mode":292,"size":10,"sha256":"` + testOtherDigest + `"}]}`), + }, + key: "manifestSha256", + }, + { + name: "settings", + args: []string{"settings"}, + responses: map[string][]stubResponse{ + "GET " + testVolumeSettings: ok(testSettingsEnabled), + }, + key: "limits", + }, + } + for _, tc := range cases { + for _, format := range []string{testFormatJSON, testFormatYAML} { + t.Run(tc.name+"/"+format, func(t *testing.T) { + api := newVolumeAPI(t, tc.responses) + + run := runVolumes(t, api, format, strings.NewReader(""), tc.args...) + + if run.err != nil { + t.Fatal(run.err) + } + var got map[string]any + var err error + if format == testFormatJSON { + err = json.Unmarshal([]byte(run.stdout), &got) + } else { + err = yaml.Unmarshal([]byte(run.stdout), &got) + } + if err != nil { + t.Fatalf("decode: %v\n%s", err, run.stdout) + } + if _, ok := got[tc.key]; !ok { + t.Fatalf("%s output lacks the API field %q:\n%s", format, tc.key, run.stdout) + } + if tc.items > 0 { + data, isList := got["data"].([]any) + if !isList || len(data) != tc.items { + t.Fatalf("%s output data = %v, want %d items:\n%s", format, got["data"], tc.items, run.stdout) + } + } + if _, ok := got["nextCursor"]; ok { + t.Fatalf("output keeps a next cursor after following every page:\n%s", run.stdout) + } + }) + } + } +} + +func TestVolumesShowJSONKeepsBytesAndFullIDs(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testSharedVolumePath: ok(testVolumeBody), + }) + + run := runVolumes(t, api, testFormatJSON, strings.NewReader(""), appHealthShowCommand, testVolume) + + if run.err != nil { + t.Fatal(run.err) + } + got := decodeJSONObject(t, run.stdout) + want := decodeJSONObject(t, testVolumeBody) + if !jsonEqual(got, want) { + t.Fatalf("json = %v\nwant %v", got, want) + } + if len(api.sent(http.MethodGet, testVolumeRefsPath)) != 0 { + t.Fatal("show --format json read the references it does not print") + } +} + +func jsonEqual(a, b map[string]any) bool { + ra, _ := json.Marshal(a) + rb, _ := json.Marshal(b) + return bytes.Equal(ra, rb) +} + +func TestVolumesShowTableAddsTheUses(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testSharedVolumePath: ok(testVolumeBody), + "GET " + testVolumeRefsPath: ok(testBlockingReferences), + }) + + run := runVolumesTable(t, api, appHealthShowCommand, testVolume) + + if run.err != nil { + t.Fatal(run.err) + } + requireOutput(t, run.stdout, testVolumeDigest, "9.9 GiB") + requireRow(t, run.stdout, colUsedBy, "img-gen v7 (current app version)") + requireRow(t, run.stdout, colRollbackFor, "img-gen v3") +} + +func TestVolumesShowSurvivesUnimplementedReferences(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testSharedVolumePath: ok(testVolumeBody), + "GET " + testVolumeRefsPath: answer(http.StatusNotImplemented, testNotImplemented), + }) + + run := runVolumesTable(t, api, appHealthShowCommand, testVolume) + + if run.err != nil { + t.Fatal(run.err) + } + requireOutput(t, run.stdout, testVolumeDigest, "not implemented by the API yet") +} + +func TestVolumesShowMarksTheUsesUnavailableWhenPagingFails(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testSharedVolumePath: ok(testVolumeBody), + "GET " + testVolumeRefsPath: { + { + status: http.StatusOK, + body: `{"blocking":[{"appId":"img-gen","appVersionNumber":7,"kind":"current-app-version"}],"rollbackTargets":[],"nextCursor":"r1"}`, + }, + { + status: http.StatusOK, + body: `{"blocking":[],"rollbackTargets":[{"appId":"img-gen","appVersionNumber":3,"kind":"rollback-target"}],"nextCursor":"r1"}`, + }, + }, + }) + + run := runVolumesTable(t, api, appHealthShowCommand, testVolume) + + if run.err != nil { + t.Fatal(run.err) + } + requireRow(t, run.stdout, colUsedBy, "unavailable", "same page cursor twice") + requireRow(t, run.stdout, colRollbackFor, "unavailable", "same page cursor twice") + if strings.Contains(run.stdout, "img-gen") { + t.Fatalf("show printed some uses of an incomplete read:\n%s", run.stdout) + } +} + +func TestVolumesCreateSendsNameAndDescription(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "POST " + testVolumesPath: answer(http.StatusCreated, testVolumeBody), + }) + + run := runVolumesTable(t, api, testCreateCommand, testVolume, "--description", "SDXL weights", testEnvFlag, testEnvironment) + + if run.err != nil { + t.Fatal(run.err) + } + sent := api.sent(http.MethodPost, testVolumesPath) + if len(sent) != 1 { + t.Fatalf("requests = %+v", sent) + } + body := decodeJSONObject(t, sent[0].body) + if body["name"] != testVolume || body["description"] != "SDXL weights" { + t.Fatalf("body = %v", body) + } + if sent[0].query.Get(testEnvironmentParam) != testEnvironment { + t.Fatalf("query = %v, want environment=%s", sent[0].query, testEnvironment) + } + requireOutput(t, run.stdout, testVolume) +} + +func TestVolumesCreateLeavesOutAnUnsetDescription(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "POST " + testVolumesPath: answer(http.StatusCreated, testSecondVolumeBody), + }) + + run := runVolumesTable(t, api, testCreateCommand, "reference-data") + + if run.err != nil { + t.Fatal(run.err) + } + body := decodeJSONObject(t, api.sent(http.MethodPost, testVolumesPath)[0].body) + if _, ok := body["description"]; ok { + t.Fatalf("body = %v, want no description", body) + } +} + +func TestVolumesRefuseANameTheAPIRejects(t *testing.T) { + api := newVolumeAPI(t, nil) + + run := runVolumesTable(t, api, appHealthShowCommand, "Model_Weights") + + if run.err == nil || !strings.Contains(run.err.Error(), "volume name") { + t.Fatalf("err = %v, want a name error", run.err) + } + if len(api.requests) != 0 { + t.Fatalf("requests = %+v, want none", api.requests) + } +} + +func TestVolumeNamesFollowTheAPIPattern(t *testing.T) { + longest := "a" + strings.Repeat("b", 62) + for name, valid := range map[string]bool{ + longest: true, + longest + "c": false, + "a.b_c-1": true, + ".weights": false, + "-weights": false, + "_weights": false, + "": false, + } { + err := volumeNameArg(nil, []string{name}) + if (err == nil) != valid { + t.Errorf("%q: err = %v, want valid %v", name, err, valid) + } + } +} + +func TestVolumesUpdateSetsOrClearsTheDescription(t *testing.T) { + cases := []struct { + name string + args []string + want string + }{ + { + name: "set", + args: []string{"--description", "fp16"}, + want: `{"description":"fp16"}`, + }, + { + name: "clear", + args: []string{testClearFlag, "description"}, + want: `{"description":null}`, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "PATCH " + testSharedVolumePath: ok(testVolumeBody), + }) + + run := runVolumesTable(t, api, append([]string{testUpdateCommand, testVolume}, tc.args...)...) + + if run.err != nil { + t.Fatal(run.err) + } + sent := api.sent(http.MethodPatch, testSharedVolumePath) + if len(sent) != 1 || sent[0].body != tc.want { + t.Fatalf("requests = %+v, want body %s", sent, tc.want) + } + }) + } +} + +func TestVolumesUpdateNeedsOneChange(t *testing.T) { + cases := map[string][]string{ + "nothing": nil, + "both": {"--description", "x", testClearFlag, "description"}, + "unknown": {testClearFlag, "name"}, + } + for name, args := range cases { + t.Run(name, func(t *testing.T) { + api := newVolumeAPI(t, nil) + + run := runVolumesTable(t, api, append([]string{testUpdateCommand, testVolume}, args...)...) + + if run.err == nil { + t.Fatal("err = nil") + } + if len(api.requests) != 0 { + t.Fatalf("requests = %+v, want none", api.requests) + } + }) + } +} + +func TestVolumesDeleteRefusesAVolumeInUse(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testSharedVolumePath: ok(testVolumeBody), + "GET " + testVolumeRefsPath: ok(testBlockingReferences), + }) + + run := runVolumesTable(t, api, testDeleteCommand, testVolume, testYesFlag) + + requireErr(t, run, "in use", "img-gen v7 (current app version)", "nothing was deleted") + requireRow(t, run.stdout, "current app version", effectBlocks) + requireRow(t, run.stdout, "rollback target", effectLosesRollback) + if len(api.sent(http.MethodDelete, testSharedVolumePath)) != 0 { + t.Fatal("a Volume in use was deleted") + } +} + +func TestVolumesDeleteConfirmsTheRollbackLoss(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testSharedVolumePath: ok(testVolumeBody), + "GET " + testVolumeRefsPath: ok(testRollbackReferences), + "DELETE " + testSharedVolumePath: answer(http.StatusNoContent, ""), + }) + + run := runVolumes(t, api, "", terminalInput{strings.NewReader("y\n")}, testDeleteCommand, testVolume) + + if run.err != nil { + t.Fatal(run.err) + } + requireOutput(t, run.stderr, "removes the rollback of img-gen v3", "Delete Volume model-weights in production?") + requireRow(t, run.stdout, colLostRollback, "img-gen v3") + sent := api.sent(http.MethodDelete, testSharedVolumePath) + if len(sent) != 1 || sent[0].query.Get(testConfirmParam) != "true" { + t.Fatalf("requests = %+v, want one confirmed delete", sent) + } + if reads := len(api.sent(http.MethodGet, testVolumeRefsPath)); reads != 2 { + t.Fatalf("references read %d times, want before and after the prompt", reads) + } +} + +func TestVolumesDeleteAsksAgainWhenTheRollbackTargetsChange(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testSharedVolumePath: ok(testVolumeBody), + "GET " + testVolumeRefsPath: append(ok(testRollbackReferences), ok(testTwoRollbackReferences)...), + "DELETE " + testSharedVolumePath: answer(http.StatusNoContent, ""), + }) + + // One byte per read, as a terminal hands over one line per answer. + stdin := terminalInput{iotest.OneByteReader(strings.NewReader("y\ny\n"))} + run := runVolumes(t, api, "", stdin, testDeleteCommand, testVolume) + + if run.err != nil { + t.Fatal(run.err) + } + requireOutput(t, run.stderr, "changed while the prompt waited", "removes the rollback of img-gen v3, img-gen v4") + if prompts := strings.Count(run.stderr, "Delete Volume model-weights"); prompts != 2 { + t.Fatalf("prompts = %d, want 2:\n%s", prompts, run.stderr) + } + requireRow(t, run.stdout, colLostRollback, "img-gen v3, img-gen v4") + if reads := len(api.sent(http.MethodGet, testVolumeRefsPath)); reads != 3 { + t.Fatalf("references read %d times, want 3", reads) + } + if len(api.sent(http.MethodDelete, testSharedVolumePath)) != 1 { + t.Fatal("want one delete after the second confirmation") + } +} + +func TestVolumesDeleteRefusesAUseThatAppearedDuringThePrompt(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testSharedVolumePath: ok(testVolumeBody), + "GET " + testVolumeRefsPath: append(ok(testRollbackReferences), ok(testBlockingReferences)...), + }) + + run := runVolumes(t, api, "", terminalInput{strings.NewReader("y\n")}, testDeleteCommand, testVolume) + + requireErr(t, run, "in use", "img-gen v7 (current app version)", "nothing was deleted") + if len(api.sent(http.MethodDelete, testSharedVolumePath)) != 0 { + t.Fatal("a Volume that came into use during the prompt was deleted") + } +} + +func TestVolumesDeleteYesSkipsThePrompt(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testSharedVolumePath: ok(testVolumeBody), + "GET " + testVolumeRefsPath: ok(testRollbackReferences), + "DELETE " + testSharedVolumePath: answer(http.StatusNoContent, ""), + }) + + run := runVolumes(t, api, testFormatJSON, strings.NewReader(""), testDeleteCommand, testVolume, "-y") + + if run.err != nil { + t.Fatal(run.err) + } + got := decodeJSONObject(t, run.stdout) + lost, _ := got["lostRollback"].([]any) + if got["name"] != testVolume || got["id"] != testVolumeID || len(lost) != 1 { + t.Fatalf("json = %v, want the version that lost its rollback", got) + } + if reads := len(api.sent(http.MethodGet, testVolumeRefsPath)); reads != 1 { + t.Fatalf("references read %d times, want once without a prompt", reads) + } + if sent := api.sent(http.MethodDelete, testSharedVolumePath); len(sent) != 1 || sent[0].query.Get(testConfirmParam) != "true" { + t.Fatalf("requests = %+v, want one delete that confirms the rollback loss", sent) + } +} + +func TestVolumesDeleteDeclinedDeletesNothing(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testSharedVolumePath: ok(testVolumeBody), + "GET " + testVolumeRefsPath: ok(testRollbackReferences), + }) + + run := runVolumes(t, api, "", terminalInput{strings.NewReader("n\n")}, testDeleteCommand, testVolume) + + if !errors.Is(run.err, errDeleteCancelled) { + t.Fatalf("err = %v, want %v", run.err, errDeleteCancelled) + } + if len(api.sent(http.MethodDelete, testSharedVolumePath)) != 0 { + t.Fatal("a declined delete was sent") + } +} + +func TestVolumesDeleteWithoutATerminalNeedsYes(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testSharedVolumePath: ok(testVolumeBody), + "GET " + testVolumeRefsPath: ok(testRollbackReferences), + }) + + run := runVolumesTable(t, api, testDeleteCommand, testVolume) + + if !errors.Is(run.err, errDeleteNeedsConfirm) { + t.Fatalf("err = %v, want %v", run.err, errDeleteNeedsConfirm) + } + requireOutput(t, run.stderr, "removes the rollback of img-gen v3") + if len(api.sent(http.MethodDelete, testSharedVolumePath)) != 0 { + t.Fatal("an unconfirmed delete was sent") + } +} + +func TestVolumesDeleteWithoutATerminalStillPrintsTheUses(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testSharedVolumePath: ok(testVolumeBody), + "GET " + testVolumeRefsPath: ok(testBlockingReferences), + }) + + run := runVolumesTable(t, api, testDeleteCommand, testVolume) + + requireErr(t, run, "in use", "nothing was deleted") + requireRow(t, run.stdout, "current app version", effectBlocks) + if len(api.sent(http.MethodDelete, testSharedVolumePath)) != 0 { + t.Fatal("a Volume in use was deleted") + } +} + +func TestVolumesDeleteUnusedSendsNoConfirmation(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testSharedVolumePath: ok(testVolumeBody), + "GET " + testVolumeRefsPath: ok(testNoReferences), + "DELETE " + testSharedVolumePath: answer(http.StatusNoContent, ""), + }) + + run := runVolumesTable(t, api, testDeleteCommand, testVolume, testYesFlag) + + if run.err != nil { + t.Fatal(run.err) + } + sent := api.sent(http.MethodDelete, testSharedVolumePath) + if len(sent) != 1 || sent[0].query.Has(testConfirmParam) { + t.Fatalf("requests = %+v, want one unconfirmed delete", sent) + } + if got := sent[0].query.Get(testVolumeIDParam); got != testVolumeID { + t.Fatalf("volumeId = %q, want the id the Volume read returned, %s", got, testVolumeID) + } + requireOutput(t, run.stdout, deletedLogically) +} + +func TestVolumesDeleteNeverReportsARefusalAsDeleted(t *testing.T) { + cases := []struct { + name string + refs []stubResponse + delete []stubResponse + want []string + }{ + { + name: "delete not implemented", + refs: ok(testNoReferences), + delete: answer(http.StatusNotImplemented, testNotImplemented), + want: []string{"501 Not Implemented", "Volume model-weights was not deleted", "never had files published", "no app version uses"}, + }, + { + name: "confirmed rollback loss not implemented", + refs: ok(testRollbackReferences), + delete: answer(http.StatusNotImplemented, testNotImplemented), + want: []string{"501 Not Implemented", "Volume model-weights was not deleted", "never had files published"}, + }, + { + name: "references not implemented", + refs: answer(http.StatusNotImplemented, testNotImplemented), + want: []string{"not available yet", "nothing was deleted"}, + }, + { + name: "an older version started using it after the references were read", + refs: ok(testNoReferences), + delete: answer(http.StatusConflict, testRollbackConfirmationRequired), + want: []string{"older app version started using", "nothing was deleted"}, + }, + { + name: "in use after the references were read", + refs: ok(testNoReferences), + delete: answer(http.StatusConflict, testVolumeInUse), + want: []string{"came into use", "nothing was deleted", "volumes references model-weights"}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + responses := map[string][]stubResponse{ + "GET " + testSharedVolumePath: ok(testVolumeBody), + "GET " + testVolumeRefsPath: tc.refs, + } + if tc.delete != nil { + responses["DELETE "+testSharedVolumePath] = tc.delete + } + api := newVolumeAPI(t, responses) + + run := runVolumesTable(t, api, testDeleteCommand, testVolume, testYesFlag) + + requireErr(t, run, tc.want...) + if run.stdout != "" { + t.Fatalf("stdout = %q, want nothing reported as deleted", run.stdout) + } + }) + } +} + +func TestVolumesReferencesListsEachUse(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testSharedVolumePath: ok(testVolumeBody), + "GET " + testVolumeRefsPath: ok(testBlockingReferences), + }) + + run := runVolumesTable(t, api, testReferencesCommand, testVolume) + + if run.err != nil { + t.Fatal(run.err) + } + requireRow(t, run.stdout, "current app version", effectBlocks) + requireRow(t, run.stdout, "rollback target", effectLosesRollback) +} + +func TestVolumesFilesFollowsEveryPageOfOneFileList(t *testing.T) { + page := func(digest, path, next string) stubResponse { + return stubResponse{ + status: http.StatusOK, + body: `{"manifestSha256":"` + digest + `","data":[{"path":"` + path + `","mode":365,"size":2048,"sha256":"` + testOtherDigest + `"}],"nextCursor":` + next + `}`, + } + } + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testVolumeFilesPath: { + page(testVolumeDigest, "a.bin", `"c1"`), + // an upload completed: the listing starts again + page(testOtherDigest, "b.bin", `null`), + page(testOtherDigest, "a.bin", `"c1"`), + page(testOtherDigest, "c.bin", `null`), + }, + }) + + run := runVolumes(t, api, testFormatJSON, strings.NewReader(""), testFilesCommand, testVolume) + + if run.err != nil { + t.Fatal(run.err) + } + got := decodeJSONObject(t, run.stdout) + data, _ := got["data"].([]any) + if got["manifestSha256"] != testOtherDigest || len(data) != 2 { + t.Fatalf("json = %v, want the two files of the newer list", got) + } + if sent := api.sent(http.MethodGet, testVolumeFilesPath); sent[0].query.Get("limit") != "1000" { + t.Fatalf("limit = %v, want 1000", sent[0].query) + } +} + +func TestVolumesFilesGivesUpWhenTheFilesKeepChanging(t *testing.T) { + var responses []stubResponse + for i := range testVolumeFileListAttempts { + digest := testVolumeDigest + if i%2 == 1 { + digest = testOtherDigest + } + responses = append(responses, + stubResponse{ + status: http.StatusOK, + body: `{"manifestSha256":"` + digest + `","data":[],"nextCursor":"c1"}`, + }, + stubResponse{ + status: http.StatusOK, + body: `{"manifestSha256":"changed","data":[],"nextCursor":null}`, + }, + ) + } + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testVolumeFilesPath: responses, + }) + + run := runVolumesTable(t, api, testFilesCommand, testVolume) + + if run.err == nil || !strings.Contains(run.err.Error(), "kept changing") { + t.Fatalf("err = %v, want the files kept changing", run.err) + } +} + +func TestVolumesFilesKeepsTheRetryAdviceAfterStaleCursors(t *testing.T) { + var responses []stubResponse + for range testVolumeFileListAttempts { + responses = append(responses, + stubResponse{ + status: http.StatusOK, + body: `{"manifestSha256":"` + testVolumeDigest + `","data":[],"nextCursor":"c1"}`, + }, + stubResponse{ + status: http.StatusBadRequest, + body: `{"type":"https://docs.runware.ai/serverless/errors#bad-request","title":"Bad Request","status":400,"detail":"stale cursor"}`, + }, + ) + } + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testVolumeFilesPath: responses, + }) + + run := runVolumesTable(t, api, testFilesCommand, testVolume) + + requireErr(t, run, "kept changing", "retry once uploads to it finish", "stale cursor") + var text bytes.Buffer + cmdutil.PrintErrorTo(log.New(&text), io.Discard, output.FormatTable, run.err) + requireOutput(t, text.String(), "kept changing", "retry once uploads to it finish", "stale cursor") + re, ok := errors.AsType[*transport.RunwareError](run.err) + if !ok || re.StatusCode != http.StatusBadRequest { + t.Fatalf("err = %v, want the API's 400 kept for structured output", run.err) + } +} + +func TestVolumesDeleteHelpSaysWhichVolumesTheAPIDeletes(t *testing.T) { + long := newVolumesDeleteCmd(log.New(io.Discard)).Long + requireOutput(t, long, "never had files published", "no app version uses", "501 Not Implemented") + if strings.Contains(long, "can be deleted") { + t.Fatalf("help still says a Volume older versions use can be deleted:\n%s", long) + } +} + +func TestVolumesFilesSaysAnEmptyVolumeHasNoFiles(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testVolumeFilesPath: ok(`{"data":[],"nextCursor":null}`), + }) + + run := runVolumesTable(t, api, testFilesCommand, testVolume) + + if run.err != nil { + t.Fatal(run.err) + } + requireOutput(t, run.stderr, "has no files yet") +} + +func TestVolumesFilesTableShowsHumanSizesAndModes(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testVolumeFilesPath: ok(`{"manifestSha256":"` + testVolumeDigest + `","data":[{"path":"unet/model.safetensors","mode":292,"size":10270000000,"sha256":"` + testOtherDigest + `"}]}`), + }) + + run := runVolumesTable(t, api, testFilesCommand, testVolume) + + if run.err != nil { + t.Fatal(run.err) + } + requireOutput(t, run.stdout, "unet/model.safetensors", "9.6 GiB", "0444", "0e1d2c3b") +} + +func TestVolumesSettingsShowsAccessAndLimits(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testVolumeSettings: ok(testSettingsEnabled), + }) + + run := runVolumesTable(t, api, "settings") + + if run.err != nil { + t.Fatal(run.err) + } + requireRow(t, run.stdout, colAvailable, "yes") + requireRow(t, run.stdout, colMaxStored, "1.0 TiB") + requireRow(t, run.stdout, colMaxFileSize, "250.0 GiB") + requireRow(t, run.stdout, colMaxFiles, "100000") + requireRow(t, run.stdout, colMaxMounted, "500.0 GiB") + requireRow(t, run.stdout, colUploadDeadline, "24h0m0s") +} + +func TestVolumesSettingsTakesNoEnvironment(t *testing.T) { + withDefaultEnvironment(t, testEnvironment) + cmd := newVolumesSettingsCmd(log.New(io.Discard)) + if cmd.Flags().Lookup(environmentFlag) != nil { + t.Fatal("settings takes --env, but settings belong to the organization") + } +} + +// volumeEnvironmentCommands are the Volume commands that address one +// environment, with the requests they send. +func volumeEnvironmentCommands() map[string][]string { + return map[string][]string{ + appHealthListCommand: {appHealthListCommand}, + testCreateCommand: {testCreateCommand, testVolume}, + appHealthShowCommand: {appHealthShowCommand, testVolume}, + testUpdateCommand: {testUpdateCommand, testVolume, "--description", "x"}, + testDeleteCommand: {testDeleteCommand, testVolume, testYesFlag}, + testReferencesCommand: {testReferencesCommand, testVolume}, + testFilesCommand: {testFilesCommand, testVolume}, + } +} + +func volumeHappyAPI(t *testing.T) *volumeAPI { + return newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testVolumesPath: ok(`{"data":[]}`), + "POST " + testVolumesPath: answer(http.StatusCreated, testVolumeBody), + "GET " + testSharedVolumePath: ok(testVolumeBody), + "PATCH " + testSharedVolumePath: ok(testVolumeBody), + "DELETE " + testSharedVolumePath: answer(http.StatusNoContent, ""), + "GET " + testVolumeRefsPath: ok(testNoReferences), + "GET " + testVolumeFilesPath: ok(`{"data":[]}`), + }) +} + +func TestVolumesSendTheEnvironmentEveryCommandAddresses(t *testing.T) { + for name, args := range volumeEnvironmentCommands() { + t.Run(name+"/flag", func(t *testing.T) { + api := volumeHappyAPI(t) + + run := runVolumesTable(t, api, append(args, testEnvFlag, testEnvironment)...) + + if run.err != nil { + t.Fatal(run.err) + } + requireEveryRequestIn(t, api, testEnvironment) + }) + t.Run(name+"/production by default", func(t *testing.T) { + api := volumeHappyAPI(t) + + run := runVolumesTable(t, api, args...) + + if run.err != nil { + t.Fatal(run.err) + } + requireEveryRequestIn(t, api, "") + }) + } +} + +func requireEveryRequestIn(t *testing.T, api *volumeAPI, environment string) { + t.Helper() + if len(api.requests) == 0 { + t.Fatal("no request sent") + } + for _, r := range api.requests { + got := "" + if v := r.query[testEnvironmentParam]; len(v) > 0 { + got = v[0] + } + if got != environment { + t.Errorf("%s %s environment = %q, want %q", r.method, r.path, got, environment) + } + } +} + +func TestVolumesUseTheDefaultEnvironment(t *testing.T) { + api := volumeHappyAPI(t) + srv := httptest.NewServer(api) + defer srv.Close() + withDefaultEnvironment(t, testEnvironment) + t.Setenv("RUNWARE_API_KEY", "test-key") + t.Setenv("RUNWARE_SERVERLESS_BASE_URL", srv.URL) + cmd := NewCmd(log.New(io.Discard)) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + cmd.SetArgs([]string{testVolumesGroup, appHealthListCommand}) + _ = captureServerlessCommandOutput(t, cmd) + + requireEveryRequestIn(t, api, testEnvironment) +} + +func decodeVolume(t *testing.T, body string) serverlessapi.Volume { + t.Helper() + var v serverlessapi.Volume + if err := json.Unmarshal([]byte(body), &v); err != nil { + t.Fatal(err) + } + return v +} + +func TestVolumesErrorsSayWhatToDoNext(t *testing.T) { + cases := []struct { + name string + args []string + responses map[string][]stubResponse + want []string + }{ + { + name: "beta switch off", + args: []string{appHealthListCommand}, + responses: map[string][]stubResponse{ + "GET " + testVolumesPath: answer(http.StatusNotFound, testNoRoute), + "GET " + testVolumeSettings: ok(testSettingsDisabled), + }, + want: []string{"not enabled for this organization", "volumes settings"}, + }, + { + name: "beta switch off on create", + args: []string{testCreateCommand, testVolume}, + responses: map[string][]stubResponse{ + "POST " + testVolumesPath: answer(http.StatusNotFound, testNoRoute), + "GET " + testVolumeSettings: ok(testSettingsDisabled), + }, + want: []string{"not enabled for this organization", "nothing was created"}, + }, + { + name: "not found", + args: []string{appHealthShowCommand, testVolume, testEnvFlag, testEnvironment}, + responses: map[string][]stubResponse{ + "GET " + testSharedVolumePath: answer(http.StatusNotFound, testVolumeNotFound), + "GET " + testVolumeSettings: ok(testSettingsEnabled), + "GET " + testEnvironmentsPath + "/" + testEnvironment: ok(testEnvironmentBody), + }, + want: []string{"no Volume named model-weights in environment staging", "volumes list --env staging"}, + }, + { + name: "unknown environment", + args: []string{appHealthShowCommand, testVolume, testEnvFlag, testEnvironment}, + responses: map[string][]stubResponse{ + "GET " + testSharedVolumePath: answer(http.StatusNotFound, testEnvironmentNotFound), + "GET " + testVolumeSettings: ok(testSettingsEnabled), + "GET " + testEnvironmentsPath + "/" + testEnvironment: answer(http.StatusNotFound, testEnvironmentNotFound), + }, + want: []string{"environment not found"}, + }, + { + name: "create refused with 404 while enabled", + args: []string{testCreateCommand, testVolume}, + responses: map[string][]stubResponse{ + "POST " + testVolumesPath: answer(http.StatusNotFound, testNoRoute), + "GET " + testVolumeSettings: ok(testSettingsEnabled), + }, + want: []string{"no route matches the request path"}, + }, + { + name: "settings unreadable on a 404", + args: []string{appHealthShowCommand, testVolume}, + responses: map[string][]stubResponse{ + "GET " + testSharedVolumePath: answer(http.StatusNotFound, testVolumeNotFound), + "GET " + testVolumeSettings: answer(http.StatusInternalServerError, `{"title":"Internal Server Error","status":500}`), + }, + want: []string{"volume not found"}, + }, + { + name: "beta switch off with settings unreadable", + args: []string{appHealthShowCommand, testVolume}, + responses: map[string][]stubResponse{ + "GET " + testSharedVolumePath: answer(http.StatusNotFound, testNoRoute), + "GET " + testVolumeSettings: answer(http.StatusInternalServerError, `{"title":"Internal Server Error","status":500}`), + }, + want: []string{"no route matches the request path"}, + }, + { + name: "not implemented", + args: []string{testFilesCommand, testVolume}, + responses: map[string][]stubResponse{ + "GET " + testVolumeFilesPath: answer(http.StatusNotImplemented, testNotImplemented), + }, + want: []string{"Listing a Volume's files is not available yet", "501", testRetryAfterRelease}, + }, + { + name: "name taken", + args: []string{testCreateCommand, testVolume}, + responses: map[string][]stubResponse{ + "POST " + testVolumesPath: answer(http.StatusConflict, testNameTaken), + }, + want: []string{"already exists in environment production", "choose another name"}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + api := newVolumeAPI(t, tc.responses) + + run := runVolumesTable(t, api, tc.args...) + + requireErr(t, run, tc.want...) + if run.stdout != "" { + t.Fatalf("stdout = %q, want nothing printed on a refusal", run.stdout) + } + }) + } +} + +func TestVolumesYAMLUsesTheAPIFieldNames(t *testing.T) { + var buf bytes.Buffer + if err := output.PrintTo(&buf, output.FormatYAML, volumeResult{ + volume: decodeVolume(t, testVolumeBody), + }); err != nil { + t.Fatal(err) + } + out := buf.String() + for _, key := range []string{"logicalBytes:", "fileCount:", "manifestSha256:", "createdAt:"} { + if !strings.Contains(out, key) { + t.Errorf("yaml lacks %q:\n%s", key, out) + } + } + if slices.Contains(strings.Fields(out), "logicalbytes:") { + t.Errorf("yaml lowercased a field name:\n%s", out) + } +} + +func TestVolumesReferencesFollowEveryPage(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testVolumeRefsPath: { + { + status: http.StatusOK, + body: `{"blocking":[{"appId":"img-gen","appVersionNumber":7,"kind":"current-app-version"}],"rollbackTargets":[],"nextCursor":"r1"}`, + }, + { + status: http.StatusOK, + body: `{"blocking":[],"rollbackTargets":[{"appId":"img-gen","appVersionNumber":3,"kind":"rollback-target"}]}`, + }, + }, + }) + + run := runVolumes(t, api, testFormatJSON, strings.NewReader(""), testReferencesCommand, testVolume) + + if run.err != nil { + t.Fatal(run.err) + } + got := decodeJSONObject(t, run.stdout) + blocking, _ := got["blocking"].([]any) + rollback, _ := got["rollbackTargets"].([]any) + if len(blocking) != 1 || len(rollback) != 1 { + t.Fatalf("json = %v, want the uses of both pages", got) + } + sent := api.sent(http.MethodGet, testVolumeRefsPath) + if len(sent) != 2 || sent[0].query.Get("limit") != "100" || sent[1].query.Get("cursor") != "r1" { + t.Fatalf("requests = %+v, want two pages of 100", sent) + } +} + +func TestVolumesDeleteRefusesABlockingUseOnALaterPage(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testSharedVolumePath: ok(testVolumeBody), + "GET " + testVolumeRefsPath: { + { + status: http.StatusOK, + body: `{"blocking":[],"rollbackTargets":[{"appId":"img-gen","appVersionNumber":3,"kind":"rollback-target"}],"nextCursor":"r1"}`, + }, + { + status: http.StatusOK, + body: `{"blocking":[{"appId":"img-gen","appVersionNumber":7,"kind":"running-worker"}],"rollbackTargets":[]}`, + }, + }, + }) + + run := runVolumesTable(t, api, testDeleteCommand, testVolume, testYesFlag) + + requireErr(t, run, "in use", "img-gen v7 (running worker)", "nothing was deleted") + if len(api.sent(http.MethodDelete, testSharedVolumePath)) != 0 { + t.Fatal("a Volume in use was deleted") + } +} + +func TestVolumesDeleteOfAnUnknownVolumeReadsNothingElse(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testSharedVolumePath: answer(http.StatusNotFound, testVolumeNotFound), + "GET " + testVolumeSettings: ok(testSettingsEnabled), + }) + + run := runVolumesTable(t, api, testDeleteCommand, testVolume, testYesFlag) + + requireErr(t, run, "no Volume named model-weights in environment production", "nothing was deleted") + if len(api.sent(http.MethodGet, testVolumeRefsPath)) != 0 || len(api.sent(http.MethodDelete, testSharedVolumePath)) != 0 { + t.Fatalf("requests = %+v, want only the Volume and settings reads", api.requests) + } +} + +func TestVolumesFilesStartAgainOnAStaleCursor(t *testing.T) { + page := func(digest, path, next string) stubResponse { + return stubResponse{ + status: http.StatusOK, + body: `{"manifestSha256":"` + digest + `","data":[{"path":"` + path + `","mode":292,"size":1,"sha256":"` + testOtherDigest + `"}],"nextCursor":` + next + `}`, + } + } + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testVolumeFilesPath: { + page(testVolumeDigest, "a.bin", `"c1"`), + // an upload completed, so the cursor of the old list is refused + { + status: http.StatusBadRequest, + body: `{"type":"https://docs.runware.ai/serverless/errors#bad-request","title":"Bad Request","status":400,"detail":"stale cursor"}`, + }, + page(testOtherDigest, "a.bin", `"c2"`), + page(testOtherDigest, "b.bin", `null`), + }, + }) + + run := runVolumes(t, api, testFormatJSON, strings.NewReader(""), testFilesCommand, testVolume) + + if run.err != nil { + t.Fatal(run.err) + } + got := decodeJSONObject(t, run.stdout) + data, _ := got["data"].([]any) + if got["manifestSha256"] != testOtherDigest || len(data) != 2 { + t.Fatalf("json = %v, want the two files of the newer list", got) + } + sent := api.sent(http.MethodGet, testVolumeFilesPath) + if len(sent) != 4 || sent[2].query.Has("cursor") { + t.Fatalf("requests = %+v, want the listing to start again from the first page", sent) + } +} + +func TestVolumesFilesKeepsAFirstPageBadRequest(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testVolumeFilesPath: answer(http.StatusBadRequest, `{"title":"Bad Request","status":400,"detail":"bad limit"}`), + }) + + run := runVolumesTable(t, api, testFilesCommand, testVolume) + + requireErr(t, run, "bad limit") + if sent := api.sent(http.MethodGet, testVolumeFilesPath); len(sent) != 1 { + t.Fatalf("requests = %d, want one: a first page's 400 is not a changed list", len(sent)) + } +} + +func TestVolumesGroupHoldsPutAndTheManagementCommands(t *testing.T) { + cmd := newVolumesCmd(log.New(io.Discard)) + var names []string + for _, sub := range cmd.Commands() { + names = append(names, sub.Name()) + } + want := []string{createCommand, testDeleteCommand, testFilesCommand, appHealthListCommand, "put", testReferencesCommand, "settings", appHealthShowCommand, testUpdateCommand} + if !slices.Equal(names, want) { + t.Fatalf("commands = %v, want %v", names, want) + } +} + +func TestVolumesReferencesMarkADeletedApp(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testVolumeRefsPath: ok(`{"blocking":[],"rollbackTargets":[{"appId":"img-gen","appVersionNumber":3,"appDeleted":true,"kind":"rollback-target"}]}`), + }) + + run := runVolumesTable(t, api, testReferencesCommand, testVolume) + + if run.err != nil { + t.Fatal(run.err) + } + requireRow(t, run.stdout, "img-gen (deleted app)", "3", effectLosesRollback) +} + +func TestVolumesDeleteForceSkipsThePrompt(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testSharedVolumePath: ok(testVolumeBody), + "GET " + testVolumeRefsPath: ok(testRollbackReferences), + "DELETE " + testSharedVolumePath: answer(http.StatusNoContent, ""), + }) + + run := runVolumesTable(t, api, testDeleteCommand, testVolume, "--force") + + if run.err != nil { + t.Fatal(run.err) + } + if sent := api.sent(http.MethodDelete, testSharedVolumePath); len(sent) != 1 || sent[0].query.Get(testConfirmParam) != "true" { + t.Fatalf("requests = %+v, want one confirmed delete", sent) + } +} + +func TestVolumesDeleteAsksAgainWhenARollbackTargetIsReplaced(t *testing.T) { + api := newVolumeAPI(t, map[string][]stubResponse{ + "GET " + testSharedVolumePath: ok(testVolumeBody), + "GET " + testVolumeRefsPath: append(ok(testRollbackReferences), + ok(`{"blocking":[],"rollbackTargets":[{"appId":"img-gen","appVersionNumber":4,"kind":"rollback-target"}]}`)...), + "DELETE " + testSharedVolumePath: answer(http.StatusNoContent, ""), + }) + + // One byte per read, as a terminal hands over one line per answer. + stdin := terminalInput{iotest.OneByteReader(strings.NewReader("y\ny\n"))} + run := runVolumes(t, api, "", stdin, testDeleteCommand, testVolume) + + if run.err != nil { + t.Fatal(run.err) + } + requireOutput(t, run.stderr, "changed while the prompt waited", "removes the rollback of img-gen v4") + if prompts := strings.Count(run.stderr, "Delete Volume model-weights"); prompts != 2 { + t.Fatalf("prompts = %d, want 2:\n%s", prompts, run.stderr) + } + requireRow(t, run.stdout, colLostRollback, "img-gen v4") +}