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
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,8 @@ Deletes the service with its builds, deployments, batch executions, environment,
valar deployment list
```

A failed deployment's status names the kind of failure, such as `failed (health)`, on platforms that report it. With `--json`, the API's `failure` object is passed through.

#### Roll out a specific build

```bash
Expand Down Expand Up @@ -329,7 +331,7 @@ valar domains delete [domain]
valar builds push [--no-deploy] [--service service] [--wait [--timeout 30m]]
```

`push` prints the build ID. With `--wait` it also streams the build log to stderr, waits for the build and its deployment, and exits non-zero if either fails. `--service` pushes to another service than the one in `.valar.yml`, with the same build settings.
`push` prints the build ID. With `--wait` it also streams the build log to stderr, waits for the build and its deployment, and exits non-zero if either fails. A failed deployment is reported with its kind (`build`, `schedule`, `capacity`, `start` or `health`), the reason, the version that keeps serving and the command that reads its log; on a terminal outside CI (`CI` unset), the last 20 lines of that log are printed too. `--service` pushes to another service than the one in `.valar.yml`, with the same build settings.

#### Listing all builds

Expand Down
9 changes: 9 additions & 0 deletions api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -905,6 +905,15 @@ type Deployment struct {
Error string `json:"error"`
Status string `json:"status"`
Build string `json:"build"`
// Failure is set on a failed deployment by servers that classify failures.
Failure *DeploymentFailure `json:"failure,omitempty"`
}

// DeploymentFailure says why a deployment failed. Kind is build, schedule,
// capacity, start or health.
type DeploymentFailure struct {
Kind string `json:"kind"`
Message string `json:"message"`
}

// NewClient creates a new client instance.
Expand Down
9 changes: 7 additions & 2 deletions cmd/deployments.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,12 +154,17 @@ func listDeployments(client *api.Client, cfg config.ServiceConfig) error {
tw := ansiterm.NewTabWriter(w, 6, 0, 1, ' ', 0)
fmt.Fprintln(tw, "VERSION\tSTATUS\tCREATED\tBUILD\tERROR")
for _, d := range deployments {
status, msg := colorize(d.Status), d.Error
if d.Failure != nil {
status += " (" + escapeControl(d.Failure.Kind) + ")"
msg = d.Failure.Message
}
fmt.Fprintln(tw, strings.Join([]string{
strconv.FormatInt(d.Version, 10),
colorize(d.Status),
status,
humanize.Time(d.CreatedAt),
d.Build,
d.Error,
escapeControl(msg),
}, "\t"))
}
tw.Flush()
Expand Down
54 changes: 54 additions & 0 deletions cmd/deployments_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,3 +158,57 @@ func TestRollback(t *testing.T) {
})
}
}

func TestListDeployments_Failure(t *testing.T) {
const deploys = `[
{"version":5,"status":"failed","error":"crashed on start","build":"b5","createdAt":"2026-11-20T10:00:00Z"},
{"version":6,"status":"done","error":"","build":"b6","createdAt":"2026-11-20T11:00:00Z"},
{"version":7,"status":"failed","error":"not ready within 300s","build":"b7","createdAt":"2026-11-20T12:00:00Z",
"failure":{"kind":"health","message":"not ready within 300s"}}
]`
for _, tc := range []struct {
Name string
JSON bool
}{
{"Human", false},
{"JSON", true},
} {
t.Run(tc.Name, func(t *testing.T) {
cfg, _ := writeServiceConfig(t, deployConfig)
client, _ := newFakeAPI(t, map[string]string{listRoute: deploys})
out := setJSON(t, tc.JSON)
if err := listDeployments(client, cfg); err != nil {
t.Fatalf("listDeployments: %v", err)
}
if !tc.JSON {
lines := strings.Split(out.String(), "\n")
for i, want := range map[int][]string{
1: {"5", "failed ", "crashed on start"},
3: {"7", "failed (health)", "not ready within 300s"},
} {
for _, field := range want {
if !strings.Contains(lines[i], field) {
t.Errorf("line %q lacks %q", lines[i], field)
}
}
}
if strings.Contains(lines[1], "(") {
t.Errorf("a deployment without failure shows a kind: %q", lines[1])
}
return
}
var got []map[string]json.RawMessage
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
t.Fatalf("decode %q: %v", out.String(), err)
}
if _, ok := got[0]["failure"]; ok {
t.Errorf("a deployment without failure has one: %s", got[0]["failure"])
}
var failure bytes.Buffer
json.Compact(&failure, got[2]["failure"])
if want := `{"kind":"health","message":"not ready within 300s"}`; failure.String() != want {
t.Errorf("failure = %s, want %s", failure.String(), want)
}
})
}
}
82 changes: 81 additions & 1 deletion cmd/wait.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,14 @@ package cmd
import (
"fmt"
"io"
"os"
"strconv"
"strings"
"time"
"unicode"

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

// pollInterval is how often waitForPush asks for build and deployment status.
Expand Down Expand Up @@ -89,7 +94,7 @@ func waitForDeployment(client *api.Client, project, service, buildID string, dea
fmt.Fprintf(w, "Version %d was replaced by a newer deployment.\n", deployment.Version)
return nil
case "failed":
return fmt.Errorf("deployment of version %d failed%s", deployment.Version, detail(deployment.Error))
return deploymentFailed(client, project, service, deployment, deployments, w)
}
if time.Now().After(deadline) {
return fmt.Errorf("timed out waiting for version %d, which is %s", deployment.Version, deployment.Status)
Expand Down Expand Up @@ -117,3 +122,78 @@ func detail(msg string) string {
}
return ": " + msg
}

// failureLogLines is how many lines of a failed deployment's log a terminal
// shows.
const failureLogLines = 20

// stderrIsTerminal reports whether stderr is a terminal; tests replace it.
var stderrIsTerminal = func() bool { return term.IsTerminal(int(os.Stderr.Fd())) }

// deploymentFailed prints the end of a failed deployment's log on an
// interactive terminal and returns why it failed with a hint to its log.
func deploymentFailed(client *api.Client, project, service string, failed *api.Deployment, deployments []api.Deployment, w io.Writer) error {
ci := os.Getenv("CI")
if !outputJSON && (ci == "" || ci == "false") && stderrIsTerminal() {
printLogTail(client, project, service, failed.Version, w)
}
return newError(kindFailed, "%s\nRead its log with: valar service logs --deployment %d", failureMessage(failed, deployments), failed.Version)
}

// failureMessage describes a failed deployment, with its failure kind and the
// version still serving when the server classifies failures.
func failureMessage(failed *api.Deployment, deployments []api.Deployment) string {
msg := fmt.Sprintf("deployment of version %d failed", failed.Version)
if failed.Failure == nil {
return msg + detail(escapeControl(failed.Error))
}
msg += fmt.Sprintf(" (%s)%s", escapeControl(failed.Failure.Kind), detail(escapeControl(failed.Failure.Message)))
var serving int64
for _, d := range deployments {
if d.Status == "done" && d.Version > serving {
serving = d.Version
}
}
if serving > 0 {
msg += fmt.Sprintf("; version %d keeps serving", serving)
}
return msg
}

// printLogTail prints the last lines of a deployment's log. It is best
// effort: the log may be missing or unreadable.
func printLogTail(client *api.Client, project, service string, version int64, w io.Writer) {
var lines []string
opts := api.LogOptions{Deployment: int(version), Tail: true, Skip: failureLogLines}
err := client.StreamServiceLogRecords(project, service, opts, func(record api.LogRecord) error {
lines = append(lines, escapeControl(record.Line))
return nil
})
if err != nil || len(lines) == 0 {
return
}
fmt.Fprintf(w, "Last lines of version %d:\n", version)
for _, line := range lines[max(0, len(lines)-failureLogLines):] {
fmt.Fprintln(w, " "+line)
}
}

// escapeControl escapes control characters other than tabs, such as terminal
// escape sequences, so that server text cannot drive the terminal.
func escapeControl(s string) string {
if strings.IndexFunc(s, isEscaped) < 0 {
return s
}
var b strings.Builder
for _, r := range s {
if isEscaped(r) {
q := strconv.QuoteRune(r)
b.WriteString(q[1 : len(q)-1])
} else {
b.WriteRune(r)
}
}
return b.String()
}

func isEscaped(r rune) bool { return r != '\t' && unicode.IsControl(r) }
95 changes: 94 additions & 1 deletion cmd/wait_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ type fakeRollout struct {
deployLists [][]api.Deployment
services []api.Service
deployCalls int
// serviceLog is the NDJSON body of the service log; logQuery records the
// query it was read with.
serviceLog string
logQuery string
}

func next[T any](items *[]T) T {
Expand All @@ -40,6 +44,10 @@ func (f *fakeRollout) client(t *testing.T) *api.Client {
switch path := r.URL.Path; {
case path == "/":
body = map[string]string{"version": "v2"}
case path == "/projects/p/services/s/logs":
f.logQuery = r.URL.RawQuery
w.Write([]byte(f.serviceLog))
return
case strings.HasSuffix(path, "/logs"):
return
case strings.HasSuffix(path, "/inspect"):
Expand Down Expand Up @@ -99,7 +107,7 @@ func TestWaitForPush(t *testing.T) {
Name: "deployment fails",
Fake: &fakeRollout{buildStates: []api.Build{done}, deployLists: [][]api.Deployment{deploy("failed", "crashed on start")}},
Deploy: true,
Error: "deployment of version 3 failed: crashed on start",
Error: "deployment of version 3 failed: crashed on start\nRead its log with: valar service logs --deployment 3",
},
{
Name: "deployment replaced by a newer one",
Expand Down Expand Up @@ -215,3 +223,88 @@ func TestEnableService_RetriesWhileStopping(t *testing.T) {
t.Error("a conflict past the retry window was not reported")
}
}

func TestWaitForPush_DeploymentFailure(t *testing.T) {
defer func(d time.Duration) { pollInterval = d }(pollInterval)
pollInterval = time.Millisecond
defer func(f func() bool) { stderrIsTerminal = f }(stderrIsTerminal)

const hint = "\nRead its log with: valar service logs --deployment 3"
health := &api.DeploymentFailure{Kind: "health", Message: "not ready within 300s"}
deploys := func(failure *api.DeploymentFailure) []api.Deployment {
return []api.Deployment{
{Version: 1, Build: "b0", Status: "expired"},
{Version: 2, Build: "b0", Status: "done"},
{Version: 3, Build: "b1", Status: "failed", Error: "not ready within 300s", Failure: failure},
}
}
log := `{"stream":"stdout","line":"listening on :8080"}` + "\n" + `{"stream":"stderr","line":"\u001b[31mpanic: no database\u001b[0m"}` + "\n"
for _, tc := range []struct {
Name string
Failure *api.DeploymentFailure
CI string
Terminal bool
Error string
LogShown bool
}{
{
Name: "failure kind and serving version",
Failure: health,
Error: "deployment of version 3 failed (health): not ready within 300s; version 2 keeps serving" + hint,
},
{
Name: "server without failure kinds",
Error: "deployment of version 3 failed: not ready within 300s" + hint,
},
{
Name: "terminal shows the end of the log",
Failure: health,
Terminal: true,
Error: "deployment of version 3 failed (health): not ready within 300s; version 2 keeps serving" + hint,
LogShown: true,
},
{
Name: "CI prints no log lines",
Failure: health,
CI: "true",
Terminal: true,
Error: "deployment of version 3 failed (health): not ready within 300s; version 2 keeps serving" + hint,
},
} {
t.Run(tc.Name, func(t *testing.T) {
t.Setenv("CI", tc.CI)
stderrIsTerminal = func() bool { return tc.Terminal }
fake := &fakeRollout{
buildStates: []api.Build{{ID: "b1", Status: "done"}},
deployLists: [][]api.Deployment{deploys(tc.Failure)},
serviceLog: log,
}
var out strings.Builder
err := waitForPush(fake.client(t), "p", "s", "b1", true, time.Minute, &out)
if err == nil || err.Error() != tc.Error {
t.Fatalf("error = %v, want %q", err, tc.Error)
}
if kind := classify(err, kindUnavailable); kind != kindFailed {
t.Errorf("kind = %v, want failed", kind)
}
shown := strings.Contains(out.String(), "Last lines of version 3:")
if shown != tc.LogShown {
t.Fatalf("log shown = %v, want %v; output %q", shown, tc.LogShown, out.String())
}
if !tc.LogShown {
if fake.logQuery != "" {
t.Errorf("read the service log with %q", fake.logQuery)
}
return
}
if want := " \\x1b[31mpanic: no database\\x1b[0m\n"; !strings.HasSuffix(out.String(), want) {
t.Errorf("output %q does not end with the escaped line %q", out.String(), want)
}
for _, param := range []string{"deployment=3", "seek=end", "skip=20"} {
if !strings.Contains(fake.logQuery, param) {
t.Errorf("log query %q lacks %s", fake.logQuery, param)
}
}
})
}
}
2 changes: 1 addition & 1 deletion skills/valar/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ Branch on the exit code, not on text:
2. `valar build push --wait --json` uploads the folder (ignoring `.git`, `node_modules` and `.valar.yml`), builds it, deploys the build, and exits non-zero if either fails. The build log streams to stderr.
3. `valar service url --json` gives the service's URLs.

If the build fails, read its log with `valar build logs <build-id>`. If the build passes but requests fail, read `valar service logs --json`. `valar deployment rollback` deploys the previous version again.
If the build fails, read its log with `valar build logs <build-id>`. If the deployment fails, the error names the failure kind (`health` and `start` mean the app did not come up; the previous version keeps serving) and the command that reads its log, `valar service logs --deployment <version>`. If the build passes but requests fail, read `valar service logs --json`. `valar deployment rollback` deploys the previous version again.

## The app's contract

Expand Down