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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,10 +140,10 @@ A project name is 3 to 20 lowercase letters or digits and starts with a letter.
#### Delete a project

```bash
valar projects delete [--yes] [project-name]
valar projects delete [--yes] [--cascade] [project-name]
```

Only empty projects can be deleted: a project with services, domains or key-value storage is refused. The command asks you to type the project name to confirm; `--yes` skips that.
Without `--cascade`, only empty projects can be deleted: a project with services, domains or key-value storage is refused. With `--cascade`, the project's services are deleted first, then its domain claims. The command asks you to type the project name to confirm; `--yes` skips that. With `--cascade` and no terminal to ask on, it refuses unless `--yes` is given.

> [!CAUTION]
> Deleting a project retires its name for good. No one can create a project with that name again, not even you.
Expand Down Expand Up @@ -207,6 +207,14 @@ valar service enable [--service service]
valar service disable [--service service]
```

#### Delete a service

```bash
valar service delete [--yes] [service]
```

Deletes the service with its builds, deployments, batch executions, environment, secrets, schedules and permission rules. Its linked domains are unlinked; the project keeps their claims. The service defaults to the one in `.valar.yml`. The command asks you to type the service name to confirm; `--yes` skips that, and without a terminal it refuses unless `--yes` is given. If a deletion fails, the service stays disabled and running the command again finishes it.

#### Listing all deployments of a service

```bash
Expand Down
6 changes: 6 additions & 0 deletions api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,12 @@ func (client *Client) AbortBuild(project, service, id string) error {
return nil
}

// DeleteService deletes a service with everything it holds. A failed deletion
// leaves the service disabled; deleting again finishes it.
func (client *Client) DeleteService(project, service string) error {
return client.request(http.MethodDelete, fmt.Sprintf("/projects/%s/services/%s", project, service), nil, nil)
}

// Sets a service' status. A disabled service cannot receive any requests.
func (client *Client) ChangeServiceStatus(project, service string, disabled bool) error {
var (
Expand Down
12 changes: 9 additions & 3 deletions api/projects.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,13 @@ func (client *Client) CreateProject(name string, public bool) (*Project, error)
return &project, nil
}

// DeleteProject deletes an empty project. The platform retires its name for good.
func (client *Client) DeleteProject(name string) error {
return client.request(http.MethodDelete, "/projects/"+name, nil, nil)
// DeleteProject deletes a project and retires its name for good. Without
// cascade the project must be empty; with it, its services and domain claims
// are deleted first.
func (client *Client) DeleteProject(name string, cascade bool) error {
path := "/projects/" + name
if cascade {
path += "?cascade=true"
}
return client.request(http.MethodDelete, path, nil, nil)
}
32 changes: 25 additions & 7 deletions api/projects_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,24 +41,32 @@ func TestCreateProject_SurfacesServerError(t *testing.T) {

func TestDeleteProject(t *testing.T) {
for _, tc := range []struct {
Name string
Status int
Body string
WantErr string
Name string
Cascade bool
Status int
Body string
WantQuery string
WantErr string
}{
{"Deleted", http.StatusOK, `{"status":"ok"}`, ""},
{"NotEmpty", http.StatusConflict, `{"error":"only empty projects can be deleted, and this one has services"}`,
{"Deleted", false, http.StatusOK, `{"status":"ok"}`, "", ""},
{"NotEmpty", false, http.StatusConflict, `{"error":"only empty projects can be deleted, and this one has services"}`, "",
"Conflict: only empty projects can be deleted, and this one has services"},
{"Cascade", true, http.StatusOK, `{"status":"ok"}`, "cascade=true", ""},
} {
t.Run(tc.Name, func(t *testing.T) {
var query string
client, requests := newEnvTestServer(t, func(w http.ResponseWriter, r *http.Request) {
query = r.URL.RawQuery
w.WriteHeader(tc.Status)
w.Write([]byte(tc.Body))
})
err := client.DeleteProject("demo")
err := client.DeleteProject("demo", tc.Cascade)
if want := (recordedRequest{http.MethodDelete, "/projects/demo", ""}); (*requests)[0] != want {
t.Errorf("request %+v, want %+v", (*requests)[0], want)
}
if query != tc.WantQuery {
t.Errorf("query = %q, want %q", query, tc.WantQuery)
}
switch {
case tc.WantErr == "" && err != nil:
t.Errorf("unexpected error: %v", err)
Expand All @@ -68,3 +76,13 @@ func TestDeleteProject(t *testing.T) {
})
}
}

func TestDeleteService(t *testing.T) {
client, requests := newEnvTestServer(t, func(w http.ResponseWriter, r *http.Request) {})
if err := client.DeleteService("demo", "web"); err != nil {
t.Fatalf("DeleteService: %v", err)
}
if want := (recordedRequest{http.MethodDelete, "/projects/demo/services/web", ""}); (*requests)[0] != want {
t.Errorf("request %+v, want %+v", (*requests)[0], want)
}
}
87 changes: 87 additions & 0 deletions cmd/delete.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package cmd

import (
"bufio"
"errors"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"

"github.com/valar/cli/api"
"golang.org/x/term"
)

// confirmation reads a name to confirm a deletion. A nil confirmation skips
// the question, as --yes does.
type confirmation struct {
in io.Reader
terminal bool
}

func stdinConfirmation(yes bool) *confirmation {
if yes {
return nil
}
return &confirmation{in: os.Stdin, terminal: term.IsTerminal(int(os.Stdin.Fd()))}
}

// ask prints warning and asks for the name of the subject being deleted.
// Without a terminal it refuses, so a script never blocks on the question.
func (c *confirmation) ask(w io.Writer, subject, name, warning string) error {
if c == nil {
return nil
}
if !c.terminal {
return newError(kindInvalid, "refusing to delete %s %s without confirmation: standard input is not a terminal, pass --yes", subject, name)
}
fmt.Fprintln(w, warning)
fmt.Fprintf(w, "Type the %s name to confirm: ", subject)
line, _ := bufio.NewReader(c.in).ReadString('\n')
if strings.TrimSpace(line) != name {
return newError(kindInvalid, "aborted: the input does not match %s, pass --yes to skip the confirmation", name)
}
return nil
}

// deleteRetryDelays are the waits before each retry of a deletion.
var deleteRetryDelays = []time.Duration{time.Second, 2 * time.Second, 4 * time.Second}

// retryDeletion calls del until it succeeds, retrying a 409 or 5xx answer.
// A 404 on a retry means an earlier attempt finished the deletion.
func retryDeletion(w io.Writer, del func() error) error {
for attempt := 0; ; attempt++ {
err := del()
var apiErr api.Error
if err == nil || !errors.As(err, &apiErr) {
return err
}
if attempt > 0 && apiErr.StatusCode == http.StatusNotFound {
return nil
}
retryable := apiErr.StatusCode == http.StatusConflict || apiErr.StatusCode >= 500
if !retryable || attempt == len(deleteRetryDelays) {
return err
}
delay := deleteRetryDelays[attempt]
fmt.Fprintf(w, "Deletion not finished (%v), retrying in %s ...\n", err, delay)
time.Sleep(delay)
}
}

func deleteService(client *api.Client, project, service string, confirm *confirmation, w io.Writer) error {
if err := api.VerifyNames(project, service); err != nil {
return withKind(kindInvalid, err)
}
warning := fmt.Sprintf("Deleting service %s in project %s removes its builds, deployments, batch executions, environment, secrets and schedules.", service, project)
if err := confirm.ask(w, "service", service, warning); err != nil {
return err
}
if err := retryDeletion(w, func() error { return client.DeleteService(project, service) }); err != nil {
return fmt.Errorf("delete service %s: %w", service, err)
}
fmt.Fprintf(w, "Deleted service %s.\n", service)
return nil
}
175 changes: 175 additions & 0 deletions cmd/delete_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
package cmd

import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"

"github.com/valar/cli/api"
)

// newScriptedAPI answers the nth request with the nth status, and with the
// last status once they run out. It records each request as "METHOD uri".
func newScriptedAPI(t *testing.T, statuses ...int) (*api.Client, *[]string) {
t.Helper()
var (
mu sync.Mutex
requests []string
)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
w.Write([]byte(`{"version":"v2"}`))
return
}
mu.Lock()
defer mu.Unlock()
status := statuses[min(len(requests), len(statuses)-1)]
requests = append(requests, r.Method+" "+r.URL.RequestURI())
w.WriteHeader(status)
if status == http.StatusOK {
w.Write([]byte(`{"status":"ok"}`))
} else {
fmt.Fprintf(w, `{"error":%q}`, http.StatusText(status))
}
}))
t.Cleanup(srv.Close)
client, err := api.NewClient(srv.URL, "token")
if err != nil {
t.Fatalf("new client: %v", err)
}
return client, &requests
}

func fastDeleteRetries(t *testing.T) {
t.Helper()
prev := deleteRetryDelays
deleteRetryDelays = []time.Duration{time.Millisecond, time.Millisecond, time.Millisecond}
t.Cleanup(func() { deleteRetryDelays = prev })
}

func terminalInput(s string) *confirmation {
return &confirmation{in: strings.NewReader(s), terminal: true}
}

func TestDeleteService(t *testing.T) {
const route = "DELETE /projects/demo/services/web"
for _, tc := range []struct {
Name string
Confirm *confirmation
Statuses []int
WantRequests int
WantKind errorKind
WantErr string
}{
{"Confirmed", terminalInput("web\n"), []int{200}, 1, 0, ""},
{"Yes", nil, []int{200}, 1, 0, ""},
{"Mismatch", terminalInput("api\n"), []int{200}, 0, kindInvalid, "aborted"},
{"NotATerminal", &confirmation{in: strings.NewReader("web\n")}, []int{200}, 0, kindInvalid, "pass --yes"},
{"NotFound", nil, []int{404}, 1, kindNotFound, "Not Found"},
{"RetryThenNotFound", nil, []int{503, 404}, 2, 0, ""},
{"ConflictRetried", nil, []int{409, 409, 200}, 3, 0, ""},
{"ConflictPersists", nil, []int{409}, 4, kindConflict, "Conflict"},
{"ServerErrorPersists", nil, []int{500}, 4, kindUnavailable, "Internal Server Error"},
{"ForbiddenNotRetried", nil, []int{403}, 1, kindNotAllowed, "Forbidden"},
} {
t.Run(tc.Name, func(t *testing.T) {
fastDeleteRetries(t)
client, requests := newScriptedAPI(t, tc.Statuses...)
var out bytes.Buffer
err := deleteService(client, "demo", "web", tc.Confirm, &out)
if len(*requests) != tc.WantRequests {
t.Errorf("requests %v, want %d", *requests, tc.WantRequests)
}
for _, r := range *requests {
if r != route {
t.Errorf("request %q, want %q", r, route)
}
}
if tc.WantErr != "" {
if err == nil || !strings.Contains(err.Error(), tc.WantErr) {
t.Fatalf("error = %v, want one containing %q", err, tc.WantErr)
}
if got := classify(err, kindFailed); got != tc.WantKind {
t.Errorf("kind = %v, want %v", got, tc.WantKind)
}
return
}
if err != nil {
t.Fatalf("deleteService: %v", err)
}
if !strings.Contains(out.String(), "Deleted service web.") {
t.Errorf("output %q does not report the deletion", out.String())
}
})
}
}

func TestDeleteService_PromptNamesService(t *testing.T) {
client, _ := newScriptedAPI(t, 200)
var out bytes.Buffer
deleteService(client, "demo", "web", terminalInput("no\n"), &out)
if !strings.Contains(out.String(), "Deleting service web in project demo") || !strings.Contains(out.String(), "Type the service name") {
t.Errorf("prompt %q does not name the service", out.String())
}
}

// runCLI runs the root command against endpoint with JSON output and returns
// what it printed on stdout.
func runCLI(t *testing.T, endpoint string, args ...string) string {
t.Helper()
cfgPath := filepath.Join(t.TempDir(), "config")
if err := os.WriteFile(cfgPath, nil, 0o600); err != nil {
t.Fatal(err)
}
t.Setenv("VALARCONFIG", cfgPath)
t.Setenv("VALAR_ENDPOINT", endpoint)
t.Setenv("VALAR_TOKEN", "token")
out := setJSON(t, false)
t.Cleanup(func() {
serviceDeleteYes, projectsDeleteYes, projectsDeleteCascade = false, false, false
rootCmd.SetArgs(nil)
})
rootCmd.SetArgs(append(args, "--json"))
if err := rootCmd.Execute(); err != nil {
t.Fatalf("valar %s: %v", strings.Join(args, " "), err)
}
return out.String()
}

func TestDeleteCommands_JSON(t *testing.T) {
for _, tc := range []struct {
Name string
Args []string
WantRequest string
Want string
}{
{"ServiceFromConfig", []string{"service", "delete", "--yes"}, "DELETE /projects/p/services/s", `{"service":"s","deleted":true}`},
{"NamedService", []string{"service", "delete", "--yes", "api"}, "DELETE /projects/p/services/api", `{"service":"api","deleted":true}`},
{"Project", []string{"project", "delete", "--yes", "demo"}, "DELETE /projects/demo", `{"project":"demo","deleted":true}`},
{"ProjectCascade", []string{"project", "delete", "--yes", "--cascade", "demo"}, "DELETE /projects/demo?cascade=true", `{"project":"demo","deleted":true}`},
} {
t.Run(tc.Name, func(t *testing.T) {
writeServiceConfig(t, deployConfig)
client, requests := newScriptedAPI(t, 200)
out := runCLI(t, client.Endpoint, tc.Args...)
if len(*requests) != 1 || (*requests)[0] != tc.WantRequest {
t.Errorf("requests %v, want [%s]", *requests, tc.WantRequest)
}
if got := strings.Join(strings.Fields(out), ""); got != tc.Want {
t.Errorf("printed %s, want %s", got, tc.Want)
}
var doc map[string]any
if err := json.Unmarshal([]byte(out), &doc); err != nil {
t.Errorf("output is not JSON: %v", err)
}
})
}
}
Loading