From d4b9524ed43eef5cb6c38fc8d57a5077087d9156 Mon Sep 17 00:00:00 2001 From: Lennart Espe <3391295+lnsp@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:51:50 +0100 Subject: [PATCH] Add service settings and roll back only to deployments that served .valar.yml accepts deployment.cpu (millicores), deployment.memory (MiB), deployment.http and deployment.minRunning. A push that deploys sends the declared keys in one PATCH settings after the upload and before the build, so the build's deployment pins them; nothing is sent without keys, with --no-deploy or with deployment.skip, which the push now honours as documented. Refusals keep their exit codes: 403 is notAllowed with a hint that raising needs a token with full access, 400 is invalid. valar service settings [service] shows the settings, which were set, their bounds and the project's budget, and passes the response through with --json. settings set name=value and settings reset name wrap PATCH. deployment rollback now targets the newest deployment below the live one that served (done or expired, without a failure or error) instead of counting versions, which could pick a failed deployment. --delta counts only those. --settings pinned|current is passed through. --- README.md | 28 +++- api/client.go | 6 + api/settings.go | 111 ++++++++++++++ cmd/builds.go | 52 ++++--- cmd/deployments.go | 88 +++++++++--- cmd/deployments_test.go | 71 ++++++++- cmd/env_test.go | 10 ++ cmd/root.go | 1 + cmd/settings.go | 215 ++++++++++++++++++++++++++++ cmd/settings_test.go | 310 ++++++++++++++++++++++++++++++++++++++++ config/schema.go | 2 + config/schema_test.go | 36 +++++ config/service.go | 30 +++- schema/valar.yml.json | 28 ++++ skills/valar/SKILL.md | 6 +- 15 files changed, 946 insertions(+), 48 deletions(-) create mode 100644 api/settings.go create mode 100644 cmd/settings.go create mode 100644 cmd/settings_test.go diff --git a/README.md b/README.md index 772dd04..5c6d59a 100644 --- a/README.md +++ b/README.md @@ -219,6 +219,26 @@ 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. +#### Show and change a service's settings + +```bash +valar service settings [service] +valar service settings set cpu=500 memory=2048 [--service service] +valar service settings reset memory [--service service] +``` + +`cpu` is in millicores (100 to 2000, in steps of 100) and `memory` in MiB (128 to 4096). `settings` shows each value, whether it was set or is the platform's default, its bounds, and the project's budget; with `--json` it prints the API's response. `reset` returns a setting to its default. A change takes effect with the next deployment, which pins the settings it runs with. Raising `cpu`, `memory` or `minRunning` needs a token with full access (scope `all`), within the project's budget; otherwise the command exits with code 4. A value out of its bounds exits with code 2. + +A push applies the settings declared in `.valar.yml`, next to `skip`: + +```yaml +deployment: + cpu: 500 + memory: 512 +``` + +Before a push that deploys, the declared keys are sent as one change, so the push's deployment runs with them; undeclared settings and settings removed from the file keep their value. With `--no-deploy` or `skip: true` nothing is sent. `http` and `minRunning` are accepted too, but the platform refuses values other than `true` and `0` for now. + #### Listing all deployments of a service ```bash @@ -238,10 +258,12 @@ Without a build ID, the build of the latest active deployment is redeployed with #### Reverse service to the previous deployment ```bash -valar deployment rollback [--delta 1] [--env pinned|current] +valar deployment rollback [--delta 1] [--env pinned|current] [--settings pinned|current] ``` -With `--env pinned` (the default) the new deployment gets the environment the earlier deployment ran with, and the command names the variables whose values differ from the current ones. With `--env current` it gets the current variables. +The target is the newest deployment below the live one (the newest `done` deployment) that served: `done` or `expired`, without a failure. Failed deployments, and deployments above the live one, are skipped, and `--delta n` picks the n-th such deployment. Earlier versions of the CLI picked by version number alone, so they could roll back to a failed deployment. + +With `--env pinned` (the default) the new deployment gets the environment the earlier deployment ran with, and the command names the variables whose values differ from the current ones. With `--env current` it gets the current variables. `--settings` works the same way for the service's settings; without it, the platform pins them. ### Environment variables @@ -331,7 +353,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. 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. +`push` prints the build ID. Unless it skips the deployment, it first applies the settings declared in `.valar.yml` (see [the service's settings](#show-and-change-a-services-settings)). 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 diff --git a/api/client.go b/api/client.go index f1c67ae..afcda98 100644 --- a/api/client.go +++ b/api/client.go @@ -17,6 +17,8 @@ type JSONError struct { Err string `json:"error"` // Names lists the variables an environment error concerns. Names []string `json:"names,omitempty"` + // Field names the setting a settings error concerns. + Field string `json:"field,omitempty"` } func (err JSONError) Error() string { @@ -772,6 +774,8 @@ const ( type RollbackRequest struct { Version int64 `json:"version"` Environment string `json:"environment,omitempty"` + // Settings is pinned or current; empty leaves the choice to the server. + Settings string `json:"settings,omitempty"` } type RollbackResult struct { @@ -907,6 +911,8 @@ type Deployment struct { Build string `json:"build"` // Failure is set on a failed deployment by servers that classify failures. Failure *DeploymentFailure `json:"failure,omitempty"` + // Settings are the settings the deployment runs with, on servers that pin them. + Settings *ServiceSettings `json:"settings,omitempty"` } // DeploymentFailure says why a deployment failed. Kind is build, schedule, diff --git a/api/settings.go b/api/settings.go new file mode 100644 index 0000000..bf2e283 --- /dev/null +++ b/api/settings.go @@ -0,0 +1,111 @@ +package api + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" +) + +// ErrNoSettingsAPI is returned when the server predates service settings. +var ErrNoSettingsAPI = errors.New("the server has no service settings API; it needs a newer Valar platform") + +// Setting names, as the API and .valar.yml spell them. +const ( + SettingCPU = "cpu" + SettingMemory = "memory" + SettingHTTP = "http" + SettingMinRunning = "minRunning" +) + +// ServiceSettings is a full set of settings with defaults filled in. CPU is in +// millicores, Memory in MiB. +type ServiceSettings struct { + CPU int `json:"cpu"` + Memory int `json:"memory"` + HTTP bool `json:"http"` + MinRunning int `json:"minRunning"` +} + +// SettingsPatch maps setting names to new values; a nil value resets the +// setting to its default. Names left out keep their value. +type SettingsPatch map[string]any + +type SettingsBound struct { + Min int `json:"min"` + Max int `json:"max"` + Step int `json:"step,omitempty"` +} + +type Allowance struct { + Used int `json:"used"` + Allowed int `json:"allowed"` +} + +type SettingsLimits struct { + CPU SettingsBound `json:"cpu"` + Memory SettingsBound `json:"memory"` + MinRunning SettingsBound `json:"minRunning"` + // Budget and RunningInstances are nil on a single-user installation. + Budget *struct { + Memory Allowance `json:"memory"` + CPU Allowance `json:"cpu"` + } `json:"budget,omitempty"` + RunningInstances *Allowance `json:"runningInstances,omitempty"` +} + +// SettingsView is a service's settings, the ones that were set explicitly, +// and their limits. Raw is the response as the server sent it. +type SettingsView struct { + Settings ServiceSettings `json:"settings"` + Explicit []string `json:"explicit"` + Limits SettingsLimits `json:"limits"` + Raw json.RawMessage `json:"-"` +} + +func settingsPath(project, service string) string { + return fmt.Sprintf("/projects/%s/services/%s/settings", project, service) +} + +// settingsError maps a route the server does not know to ErrNoSettingsAPI. +func settingsError(err error) error { + var apiErr Error + if !errors.As(err, &apiErr) { + return err + } + var jsonErr JSONError + missing := apiErr.StatusCode == http.StatusNotFound || apiErr.StatusCode == http.StatusMethodNotAllowed + if missing && !errors.As(apiErr.ServerError, &jsonErr) { + return ErrNoSettingsAPI + } + return err +} + +func (client *Client) settingsRequest(method, project, service string, body io.Reader) (*SettingsView, error) { + var raw json.RawMessage + if err := client.request(method, settingsPath(project, service), &raw, body); err != nil { + return nil, settingsError(err) + } + view := SettingsView{Raw: raw} + if err := json.Unmarshal(raw, &view); err != nil { + return nil, fmt.Errorf("unmarshalling settings: %w", err) + } + return &view, nil +} + +// ServiceSettings returns the service's current settings and their limits. +func (client *Client) ServiceSettings(project, service string) (*SettingsView, error) { + return client.settingsRequest(http.MethodGet, project, service, nil) +} + +// PatchSettings merges patch into the service's settings, which the next +// deployment pins. +func (client *Client) PatchSettings(project, service string, patch SettingsPatch) (*SettingsView, error) { + payload, err := json.Marshal(patch) + if err != nil { + return nil, err + } + return client.settingsRequest(http.MethodPatch, project, service, bytes.NewReader(payload)) +} diff --git a/cmd/builds.go b/cmd/builds.go index ccc9d25..b133560 100644 --- a/cmd/builds.go +++ b/cmd/builds.go @@ -529,22 +529,8 @@ var buildPushCmd = &cobra.Command{ return err } } - hasEnvAPI, err := client.HasEnvAPI(serviceCfg.Project(), serviceCfg.Service()) - if err != nil { - return err - } - if hasEnvAPI { - warnInlineEnvironment(serviceCfg.Unwrap()) - } - artifact, err := client.SubmitArtifact(serviceCfg.Project(), serviceCfg.Service(), buildPushKind, targzFile) - if err != nil { - return err - } - // The kind is repeated here because the server reads an absent kind as - // "function" and rejects a mismatch with 409. - buildReq := newBuildRequest(serviceCfg, artifact.Artifact, buildPushKind, buildPushNoDeploy, !hasEnvAPI) - buildReq.Build.Constructor = constructor - build, err := client.SubmitBuild(serviceCfg.Project(), serviceCfg.Service(), buildReq) + deploy := !buildPushNoDeploy && !skipsDeploy(serviceCfg) + build, err := submitPush(client, serviceCfg, targzFile, buildPushKind, constructor, deploy) if err != nil { return err } @@ -557,10 +543,42 @@ var buildPushCmd = &cobra.Command{ if !buildPushWait { return nil } - return waitForPush(client, serviceCfg.Project(), serviceCfg.Service(), build.ID, !buildPushNoDeploy, buildPushTimeout, os.Stderr) + return waitForPush(client, serviceCfg.Project(), serviceCfg.Service(), build.ID, deploy, buildPushTimeout, os.Stderr) }), } +func skipsDeploy(cfg *config.ValidatedServiceConfig) bool { + d := cfg.Unwrap().Deployment + return d != nil && d.Skip +} + +// submitPush uploads the archive and submits its build. A deploying push +// first applies the settings .valar.yml declares, after the upload, which +// creates a new service, and before the build, whose deployment pins them. +func submitPush(client *api.Client, cfg *config.ValidatedServiceConfig, archive io.ReadCloser, kind, constructor string, deploy bool) (*api.Build, error) { + hasEnvAPI, err := client.HasEnvAPI(cfg.Project(), cfg.Service()) + if err != nil { + return nil, err + } + if hasEnvAPI { + warnInlineEnvironment(cfg.Unwrap()) + } + artifact, err := client.SubmitArtifact(cfg.Project(), cfg.Service(), kind, archive) + if err != nil { + return nil, err + } + if deploy { + if err := applyDeclaredSettings(client, cfg); err != nil { + return nil, err + } + } + // The kind is repeated here because the server reads an absent kind as + // "function" and rejects a mismatch with 409. + buildReq := newBuildRequest(cfg, artifact.Artifact, kind, !deploy, !hasEnvAPI) + buildReq.Build.Constructor = constructor + return client.SubmitBuild(cfg.Project(), cfg.Service(), buildReq) +} + func initBuildsCmd() { buildCmd.PersistentFlags().StringVarP(&buildService, "service", "s", "", "The service to act on, instead of the one in .valar.yml") buildLogsCmd.PersistentFlags().BoolVarP(&logsFollow, "follow", "f", false, "Follow the logs") diff --git a/cmd/deployments.go b/cmd/deployments.go index 4b2dd6a..06e7b71 100644 --- a/cmd/deployments.go +++ b/cmd/deployments.go @@ -4,6 +4,7 @@ import ( "fmt" "io" "os" + "slices" "sort" "strconv" "strings" @@ -67,18 +68,27 @@ service's current runtime variables, for example after 'valar env set'.`, } var ( - rollbackDelta int - rollbackEnv string + rollbackDelta int + rollbackEnv string + rollbackSettings string ) var deploymentRollbackCmd = &cobra.Command{ Use: "rollback", - Short: "Reverse service to the previous deployment.", - Long: `Reverse service to the previous deployment. + Short: "Reverse service to the previous deployment that served.", + Long: `Reverse service to the previous deployment that served. + +The target is the newest deployment below the live one that is done or +expired and has no failure; failed deployments are skipped. With --delta n it +is the n-th such deployment. The live deployment is the newest done one. With --env pinned, the default, the new deployment gets the environment the earlier one ran with; the command then names the variables whose values differ -from the current ones. With --env current, it gets the current variables.`, +from the current ones. With --env current, it gets the current variables. + +With --settings pinned, the platform's default, the new deployment gets the +settings the earlier one ran with; with --settings current, the service's +current settings.`, Args: cobra.NoArgs, Run: runAndHandle(func(cmd *cobra.Command, args []string) error { cfg, err := config.NewServiceConfigWithFallback(functionConfiguration, &deploymentService, globalConfiguration) @@ -89,13 +99,50 @@ from the current ones. With --env current, it gets the current variables.`, if err != nil { return err } - return rollbackLatestDeployment(client, cfg, rollbackDelta, rollbackEnv, stdout, os.Stderr) + return rollbackLatestDeployment(client, cfg, rollbackOptions{rollbackDelta, rollbackEnv, rollbackSettings}, stdout, os.Stderr) }), } +type rollbackOptions struct { + Delta int + Env string + Settings string +} + +// served reports whether a deployment went live and did not fail. The API +// does not tell an expired deployment that served from one replaced before it +// went live, so both count. +func served(d api.Deployment) bool { + return (d.Status == "done" || d.Status == "expired") && d.Failure == nil && d.Error == "" +} + +// rollbackTarget returns the delta-th deployment below the newest done one +// that served. +func rollbackTarget(deployments []api.Deployment, delta int) (int64, error) { + if delta < 1 { + return 0, newError(kindInvalid, "--delta must be at least 1") + } + sorted := slices.Clone(deployments) + sort.Slice(sorted, func(i, j int) bool { return sorted[i].Version > sorted[j].Version }) + live := slices.IndexFunc(sorted, func(d api.Deployment) bool { return d.Status == "done" }) + if live < 0 { + return 0, newError(kindNotFound, "no deployment is live to roll back from") + } + found := 0 + for _, d := range sorted[live+1:] { + if served(d) { + found++ + if found == delta { + return d.Version, nil + } + } + } + return 0, newError(kindNotFound, "found %d earlier deployments that served below version %d, --delta %d needs more", found, sorted[live].Version, delta) +} + // rollbackLatestDeployment prints the new version to stdout and notes to stderr. -func rollbackLatestDeployment(client *api.Client, cfg config.ServiceConfig, delta int, env string, stdout, stderr io.Writer) error { - switch env { +func rollbackLatestDeployment(client *api.Client, cfg config.ServiceConfig, opts rollbackOptions, stdout, stderr io.Writer) error { + switch opts.Env { case api.RollbackEnvPinned: case api.RollbackEnvCurrent: // A server without the environment API ignores the field and rolls @@ -108,26 +155,28 @@ func rollbackLatestDeployment(client *api.Client, cfg config.ServiceConfig, delt return fmt.Errorf("--env current needs Valar platform %s or newer with the environment API enabled", api.EnvMinPlatform) } default: - return newError(kindInvalid, "unknown --env %q, want %q or %q", env, api.RollbackEnvPinned, api.RollbackEnvCurrent) + return newError(kindInvalid, "unknown --env %q, want %q or %q", opts.Env, api.RollbackEnvPinned, api.RollbackEnvCurrent) + } + switch opts.Settings { + case "", api.RollbackEnvPinned, api.RollbackEnvCurrent: + default: + return newError(kindInvalid, "unknown --settings %q, want %q or %q", opts.Settings, api.RollbackEnvPinned, api.RollbackEnvCurrent) } deployments, err := client.ListDeployments(cfg.Project(), cfg.Service()) if err != nil { return err } - if len(deployments) < delta+1 { - return newError(kindNotFound, "not enough deployments available") + target, err := rollbackTarget(deployments, opts.Delta) + if err != nil { + return err } - // Sort by version (desc) - sort.Slice(deployments, func(i, j int) bool { - return deployments[i].Version > deployments[j].Version - }) - target := deployments[delta].Version result, err := client.RollbackDeploy(cfg.Project(), cfg.Service(), &api.RollbackRequest{ Version: target, - Environment: env, + Environment: opts.Env, + Settings: opts.Settings, }) if err != nil { - return err + return settingsRefusal(err) } if err := emit(stdout, result, func(w io.Writer) error { _, err := fmt.Fprintln(w, result.Version) @@ -173,8 +222,9 @@ func listDeployments(client *api.Client, cfg config.ServiceConfig) error { } func initDeploymentsCmd() { - deploymentRollbackCmd.Flags().IntVarP(&rollbackDelta, "delta", "d", 1, "Number of deployments to roll back") + deploymentRollbackCmd.Flags().IntVarP(&rollbackDelta, "delta", "d", 1, "Roll back to the n-th earlier deployment that served") deploymentRollbackCmd.Flags().StringVar(&rollbackEnv, "env", api.RollbackEnvPinned, "Environment of the new deployment (pinned|current)") + deploymentRollbackCmd.Flags().StringVar(&rollbackSettings, "settings", "", "Settings of the new deployment (pinned|current); pinned unless given") deploymentCmd.PersistentFlags().StringVarP(&deploymentService, "service", "s", "", "The service to manage") deploymentCmd.AddCommand(deploymentListCmd, deploymentRollbackCmd, deploymentCreateCmd) rootCmd.AddCommand(deploymentCmd) diff --git a/cmd/deployments_test.go b/cmd/deployments_test.go index 59a77ff..f190413 100644 --- a/cmd/deployments_test.go +++ b/cmd/deployments_test.go @@ -111,20 +111,24 @@ func TestRollback(t *testing.T) { Name string EnvAPI bool Env string + Settings string WantBody string WantErr string }{ - {"Pinned", true, "pinned", `{"version":2,"environment":"pinned"}`, ""}, - {"Current", true, "current", `{"version":2,"environment":"current"}`, ""}, + {"Pinned", true, "pinned", "", `{"version":2,"environment":"pinned"}`, ""}, + {"Current", true, "current", "", `{"version":2,"environment":"current"}`, ""}, // An old server ignores the field and rolls back pinned, as it always has. - {"PinnedOldServer", false, "pinned", `{"version":2,"environment":"pinned"}`, ""}, - {"CurrentOldServer", false, "current", "", api.EnvMinPlatform}, - {"Unknown", true, "latest", "", "unknown --env"}, + {"PinnedOldServer", false, "pinned", "", `{"version":2,"environment":"pinned"}`, ""}, + {"CurrentOldServer", false, "current", "", "", api.EnvMinPlatform}, + {"Unknown", true, "latest", "", "", "unknown --env"}, + {"SettingsPinned", true, "pinned", "pinned", `{"version":2,"environment":"pinned","settings":"pinned"}`, ""}, + {"SettingsCurrent", true, "pinned", "current", `{"version":2,"environment":"pinned","settings":"current"}`, ""}, + {"SettingsUnknown", true, "pinned", "latest", "", "unknown --settings"}, } { t.Run(tc.Name, func(t *testing.T) { cfg, _ := writeServiceConfig(t, deployConfig) routes := map[string]string{ - listRoute: `[{"version":1},{"version":3},{"version":2}]`, + listRoute: `[{"version":1,"status":"expired"},{"version":3,"status":"done"},{"version":2,"status":"expired"}]`, "POST " + rollbackPath: `{"version":4,"changed":["A"]}`, } if tc.EnvAPI { @@ -132,7 +136,7 @@ func TestRollback(t *testing.T) { } client, requests := newFakeAPI(t, routes) var out, notes bytes.Buffer - err := rollbackLatestDeployment(client, cfg, 1, tc.Env, &out, ¬es) + err := rollbackLatestDeployment(client, cfg, rollbackOptions{1, tc.Env, tc.Settings}, &out, ¬es) rollbacks := requestsTo(*requests, http.MethodPost, rollbackPath) if tc.WantErr != "" { if err == nil || !strings.Contains(err.Error(), tc.WantErr) { @@ -159,6 +163,59 @@ func TestRollback(t *testing.T) { } } +func TestRollbackTarget(t *testing.T) { + failed := api.Deployment{Status: "failed", Failure: &api.DeploymentFailure{Kind: "health", Message: "not ready within 300s"}} + d := func(version int64, status string) api.Deployment { + return api.Deployment{Version: version, Status: status} + } + withVersion := func(d api.Deployment, version int64) api.Deployment { + d.Version = version + return d + } + for _, tc := range []struct { + Name string + Deployments []api.Deployment + Delta int + Want int64 + WantErr string + }{ + {"Previous", []api.Deployment{d(1, "expired"), d(2, "done")}, 1, 1, ""}, + {"SkipsFailed", []api.Deployment{d(1, "expired"), withVersion(failed, 2), d(3, "done")}, 1, 1, ""}, + // A failed deploy above the live one is not the live one. + {"FailedAboveLive", []api.Deployment{d(1, "expired"), d(2, "done"), withVersion(failed, 3)}, 1, 1, ""}, + {"InFlightAboveLive", []api.Deployment{d(1, "expired"), d(2, "done"), d(3, "scheduled"), d(4, "waiting")}, 1, 1, ""}, + // An old server's failure without a kind, and a deployment that never left scheduled. + {"SkipsErrors", []api.Deployment{ + d(1, "expired"), + {Version: 2, Status: "failed", Error: "crashed"}, + {Version: 3, Status: "expired", Error: "failedToSchedule"}, + d(4, "done"), + }, 1, 1, ""}, + {"DeltaCountsEligible", []api.Deployment{d(1, "expired"), withVersion(failed, 2), d(3, "expired"), withVersion(failed, 4), d(5, "done")}, 2, 1, ""}, + {"Unsorted", []api.Deployment{d(5, "done"), d(3, "expired"), d(4, "expired")}, 2, 3, ""}, + {"NothingEarlier", []api.Deployment{withVersion(failed, 1), d(2, "done")}, 1, 0, "found 0 earlier deployments"}, + {"DeltaTooLarge", []api.Deployment{d(1, "expired"), d(2, "done")}, 2, 0, "--delta 2 needs more"}, + {"NothingLive", []api.Deployment{d(1, "expired"), withVersion(failed, 2)}, 1, 0, "no deployment is live"}, + {"DeltaZero", []api.Deployment{d(1, "expired"), d(2, "done")}, 0, 0, "--delta must be at least 1"}, + } { + t.Run(tc.Name, func(t *testing.T) { + got, err := rollbackTarget(tc.Deployments, tc.Delta) + if tc.WantErr != "" { + if err == nil || !strings.Contains(err.Error(), tc.WantErr) { + t.Fatalf("got %d, %v, want an error containing %q", got, err, tc.WantErr) + } + return + } + if err != nil { + t.Fatalf("rollbackTarget: %v", err) + } + if got != tc.Want { + t.Errorf("target = %d, want %d", got, tc.Want) + } + }) + } +} + func TestListDeployments_Failure(t *testing.T) { const deploys = `[ {"version":5,"status":"failed","error":"crashed on start","build":"b5","createdAt":"2026-11-20T10:00:00Z"}, diff --git a/cmd/env_test.go b/cmd/env_test.go index a9e8dfd..6545dd1 100644 --- a/cmd/env_test.go +++ b/cmd/env_test.go @@ -23,6 +23,13 @@ type recordedRequest struct { // the way the platform's router answers an unknown route. It records every // request except the client's version check. func newFakeAPI(t *testing.T, routes map[string]string) (*api.Client, *[]recordedRequest) { + t.Helper() + return newFakeAPIWithStatus(t, routes, nil) +} + +// newFakeAPIWithStatus is newFakeAPI answering the routes in statuses with +// that status code. +func newFakeAPIWithStatus(t *testing.T, routes map[string]string, statuses map[string]int) (*api.Client, *[]recordedRequest) { t.Helper() var requests []recordedRequest srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -37,6 +44,9 @@ func newFakeAPI(t *testing.T, routes map[string]string) (*api.Client, *[]recorde http.NotFound(w, r) return } + if status, ok := statuses[r.Method+" "+r.URL.Path]; ok { + w.WriteHeader(status) + } w.Write([]byte(resp)) })) t.Cleanup(srv.Close) diff --git a/cmd/root.go b/cmd/root.go index bb541a0..f7ad9ea 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -55,6 +55,7 @@ func init() { initBuildsCmd() // Configure services.go initServicesCmd() + initSettingsCmd() // Configure env.go initEnvCmd() // Configure domains.go diff --git a/cmd/settings.go b/cmd/settings.go new file mode 100644 index 0000000..85f3efa --- /dev/null +++ b/cmd/settings.go @@ -0,0 +1,215 @@ +package cmd + +import ( + "errors" + "fmt" + "io" + "net/http" + "slices" + "strconv" + "strings" + "text/tabwriter" + + "github.com/spf13/cobra" + "github.com/valar/cli/api" + "github.com/valar/cli/config" +) + +var settingNames = []string{api.SettingCPU, api.SettingMemory, api.SettingHTTP, api.SettingMinRunning} + +const raiseHint = "Raising cpu, memory or minRunning needs a token with full access (scope all), and the project's budget caps what its services request; 'valar service settings' shows the budget." + +// settingsRefusal adds a hint to a settings change the server refused for +// scope or budget. Its exit code stays that of the response. +func settingsRefusal(err error) error { + var apiErr api.Error + var jsonErr api.JSONError + if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusForbidden && + errors.As(apiErr.ServerError, &jsonErr) && jsonErr.Field != "" { + return fmt.Errorf("%w\n%s", err, raiseHint) + } + return err +} + +// applyDeclaredSettings sends the settings .valar.yml declares, so that the +// deployment a push creates pins them. It sends nothing if none are declared. +func applyDeclaredSettings(client *api.Client, cfg *config.ValidatedServiceConfig) error { + declared := cfg.Unwrap().Deployment.Settings() + if declared == nil { + return nil + } + if _, err := client.PatchSettings(cfg.Project(), cfg.Service(), declared); err != nil { + return settingsRefusal(fmt.Errorf("applying the settings in %s: %w", functionConfiguration, err)) + } + return nil +} + +var settingsService string + +var serviceSettingsCmd = &cobra.Command{ + Use: "settings [service]", + Short: "Show the service's settings, which of them were set, and their limits.", + Long: `Show the service's settings, which of them were set, and their limits. + +cpu is in millicores and memory in MiB. Settings that were not set have the +platform's default. A change takes effect with the next deployment, which pins +the settings it runs with. Raising cpu, memory or minRunning needs a token with +full access, within the project's budget.`, + Args: cobra.MaximumNArgs(1), + Run: runAndHandle(func(cmd *cobra.Command, args []string) error { + if len(args) == 1 { + settingsService = args[0] + } + client, cfg, err := settingsTarget() + if err != nil { + return err + } + view, err := client.ServiceSettings(cfg.Project(), cfg.Service()) + if err != nil { + return err + } + return printSettings(stdout, view) + }), +} + +var serviceSettingsSetCmd = &cobra.Command{ + Use: "set name=value...", + Short: "Change settings, such as cpu=500 memory=2048.", + Args: cobra.MinimumNArgs(1), + Run: runAndHandle(func(cmd *cobra.Command, args []string) error { + patch, err := parseSettingAssignments(args) + if err != nil { + return err + } + return patchSettings(patch) + }), +} + +var serviceSettingsResetCmd = &cobra.Command{ + Use: "reset name...", + Short: "Reset settings to the platform's defaults.", + Args: cobra.MinimumNArgs(1), + Run: runAndHandle(func(cmd *cobra.Command, args []string) error { + patch := api.SettingsPatch{} + for _, name := range args { + if !slices.Contains(settingNames, name) { + return unknownSetting(name) + } + patch[name] = nil + } + return patchSettings(patch) + }), +} + +func settingsTarget() (*api.Client, *config.ValidatedServiceConfig, error) { + cfg, err := config.NewServiceConfigWithFallback(functionConfiguration, &settingsService, globalConfiguration) + if err != nil { + return nil, nil, err + } + client, err := globalConfiguration.APIClient() + if err != nil { + return nil, nil, err + } + return client, cfg, nil +} + +func patchSettings(patch api.SettingsPatch) error { + client, cfg, err := settingsTarget() + if err != nil { + return err + } + view, err := client.PatchSettings(cfg.Project(), cfg.Service(), patch) + if err != nil { + return settingsRefusal(err) + } + return printSettings(stdout, view) +} + +func unknownSetting(name string) error { + return newError(kindInvalid, "unknown setting %q, known settings are %s", name, strings.Join(settingNames, ", ")) +} + +// parseSettingAssignments reads name=value arguments: integers, and true or +// false for http. +func parseSettingAssignments(args []string) (api.SettingsPatch, error) { + patch := api.SettingsPatch{} + for _, arg := range args { + name, value, ok := strings.Cut(arg, "=") + if !ok { + return nil, newError(kindInvalid, "%q is not name=value", arg) + } + if !slices.Contains(settingNames, name) { + return nil, unknownSetting(name) + } + if _, dup := patch[name]; dup { + return nil, newError(kindInvalid, "%s is given twice", name) + } + if name == api.SettingHTTP { + b, err := strconv.ParseBool(value) + if err != nil { + return nil, newError(kindInvalid, "http must be true or false") + } + patch[name] = b + continue + } + n, err := strconv.Atoi(value) + if err != nil { + return nil, newError(kindInvalid, "%s must be an integer", name) + } + patch[name] = n + } + return patch, nil +} + +// printSettings prints the settings as a table, or the server's response with +// --json. +func printSettings(w io.Writer, view *api.SettingsView) error { + return emit(w, view.Raw, func(w io.Writer) error { + s, l := view.Settings, view.Limits + tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0) + fmt.Fprintln(tw, "SETTING\tVALUE\tSOURCE\tBOUNDS") + for _, row := range []struct { + name, value, bound string + }{ + {api.SettingCPU, strconv.Itoa(s.CPU), boundText(l.CPU, "millicores")}, + {api.SettingMemory, strconv.Itoa(s.Memory), boundText(l.Memory, "MiB")}, + {api.SettingHTTP, strconv.FormatBool(s.HTTP), ""}, + {api.SettingMinRunning, strconv.Itoa(s.MinRunning), boundText(l.MinRunning, "")}, + } { + source := "default" + if slices.Contains(view.Explicit, row.name) { + source = "set" + } + fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n", row.name, row.value, source, row.bound) + } + tw.Flush() + if b := l.Budget; b != nil { + fmt.Fprintf(w, "Project budget: %d of %d MiB memory, %d of %d millicores CPU.\n", + b.Memory.Used, b.Memory.Allowed, b.CPU.Used, b.CPU.Allowed) + } + if r := l.RunningInstances; r != nil { + fmt.Fprintf(w, "Instances that always run: %d of %d.\n", r.Used, r.Allowed) + } + return nil + }) +} + +func boundText(b api.SettingsBound, unit string) string { + if b.Max == 0 { + return "" + } + text := fmt.Sprintf("%d-%d", b.Min, b.Max) + if unit != "" { + text += " " + unit + } + if b.Step > 1 { + text += fmt.Sprintf(", steps of %d", b.Step) + } + return text +} + +func initSettingsCmd() { + serviceSettingsCmd.PersistentFlags().StringVarP(&settingsService, "service", "s", "", "The service to target") + serviceSettingsCmd.AddCommand(serviceSettingsSetCmd, serviceSettingsResetCmd) + serviceCmd.AddCommand(serviceSettingsCmd) +} diff --git a/cmd/settings_test.go b/cmd/settings_test.go new file mode 100644 index 0000000..026bcbd --- /dev/null +++ b/cmd/settings_test.go @@ -0,0 +1,310 @@ +package cmd + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "net/http" + "strings" + "testing" + + "github.com/valar/cli/api" +) + +const ( + artifactRoute = "POST /projects/p/services/s/artifacts" + buildRoute = "POST /projects/p/services/s/builds" + settingsRoute = "PATCH /projects/p/services/s/settings" + settingsPath = "/projects/p/services/s/settings" + settingsView = `{"settings":{"cpu":500,"memory":512,"http":true,"minRunning":0},"explicit":["cpu","memory"],` + + `"limits":{"cpu":{"min":100,"max":2000,"step":100},"memory":{"min":128,"max":4096},"minRunning":{"min":0,"max":16},` + + `"budget":{"memory":{"used":1536,"allowed":51200},"cpu":{"used":1500,"allowed":50000}},"runningInstances":{"used":0,"allowed":0}}}` +) + +const settingsConfig = `project: p +service: s +build: + constructor: go +deployment: + cpu: 500 + memory: 512 +` + +// routeOrder returns the "METHOD /path" of each request. +func routeOrder(requests []recordedRequest) []string { + order := make([]string, len(requests)) + for i, r := range requests { + order[i] = r.Method + " " + r.Path + } + return order +} + +func TestSubmitPush_Settings(t *testing.T) { + const noSettings = "project: p\nservice: s\nbuild:\n constructor: go\ndeployment:\n skip: false\n" + for _, tc := range []struct { + Name string + Config string + Deploy bool + Status int + Response string + WantPatch string + WantKind errorKind + WantErr []string + }{ + {Name: "PatchBeforeBuild", Config: settingsConfig, Deploy: true, WantPatch: `{"cpu":500,"memory":512}`}, + {Name: "OnlyDeclared", Config: "project: p\nservice: s\nbuild:\n constructor: go\ndeployment:\n memory: 2048\n", Deploy: true, WantPatch: `{"memory":2048}`}, + {Name: "NothingDeclared", Config: noSettings, Deploy: true}, + {Name: "NoDeploymentSection", Config: "project: p\nservice: s\nbuild:\n constructor: go\n", Deploy: true}, + {Name: "NoDeploy", Config: settingsConfig, Deploy: false}, + { + Name: "Forbidden", Config: settingsConfig, Deploy: true, WantPatch: `{"cpu":500,"memory":512}`, + Status: http.StatusForbidden, Response: `{"error":"raising memory needs a token with scope all","field":"memory"}`, + WantKind: kindNotAllowed, WantErr: []string{"raising memory needs a token with scope all", "full access"}, + }, + { + Name: "Budget", Config: settingsConfig, Deploy: true, WantPatch: `{"cpu":500,"memory":512}`, + Status: http.StatusForbidden, Response: `{"error":"the project's services would request 52000 MiB of memory, above its budget of 51200 MiB","field":"memory"}`, + WantKind: kindNotAllowed, WantErr: []string{"above its budget", "budget"}, + }, + { + Name: "Invalid", Config: settingsConfig, Deploy: true, WantPatch: `{"cpu":500,"memory":512}`, + Status: http.StatusBadRequest, Response: `{"error":"memory must be between 128 and 4096 MiB","field":"memory"}`, + WantKind: kindInvalid, WantErr: []string{"memory must be between 128 and 4096 MiB"}, + }, + } { + t.Run(tc.Name, func(t *testing.T) { + cfg, _ := writeServiceConfig(t, tc.Config) + response := settingsView + if tc.Response != "" { + response = tc.Response + } + routes := map[string]string{ + envRoute: `[]`, + artifactRoute: `{"artifact":"art"}`, + settingsRoute: response, + buildRoute: `{"id":"b1","status":"scheduled"}`, + } + statuses := map[string]int{} + if tc.Status != 0 { + statuses[settingsRoute] = tc.Status + } + client, requests := newFakeAPIWithStatus(t, routes, statuses) + build, err := submitPush(client, cfg, io.NopCloser(strings.NewReader("archive")), "", "go", tc.Deploy) + + patches := requestsTo(*requests, http.MethodPatch, settingsPath) + switch { + case tc.WantPatch == "" && len(patches) != 0: + t.Errorf("sent settings %+v, want none", patches) + case tc.WantPatch != "" && (len(patches) != 1 || patches[0].Body != tc.WantPatch): + t.Errorf("settings requests %+v, want one with body %s", patches, tc.WantPatch) + } + builds := requestsTo(*requests, http.MethodPost, "/projects/p/services/s/builds") + if tc.WantErr != nil { + if err == nil { + t.Fatalf("pushed build %+v, want an error", build) + } + for _, want := range tc.WantErr { + if !strings.Contains(err.Error(), want) { + t.Errorf("error %q lacks %q", err, want) + } + } + if got := classify(err, kindFailed); got != tc.WantKind { + t.Errorf("kind = %v, want %v", got, tc.WantKind) + } + if len(builds) != 0 { + t.Errorf("submitted a build after a refusal: %+v", builds) + } + return + } + if err != nil { + t.Fatalf("submitPush: %v", err) + } + order := strings.Join(routeOrder(*requests), ", ") + want := envRoute + ", " + artifactRoute + ", " + buildRoute + if tc.WantPatch != "" { + want = envRoute + ", " + artifactRoute + ", " + settingsRoute + ", " + buildRoute + } + if order != want { + t.Errorf("requests %s, want %s", order, want) + } + var req api.BuildRequest + if err := json.Unmarshal([]byte(builds[0].Body), &req); err != nil { + t.Fatal(err) + } + if req.Deployment.Skip == tc.Deploy { + t.Errorf("build request skip = %v, want %v", req.Deployment.Skip, !tc.Deploy) + } + }) + } +} + +func TestSubmitPush_OldServer(t *testing.T) { + cfg, _ := writeServiceConfig(t, settingsConfig) + client, requests := newFakeAPI(t, map[string]string{ + envRoute: `[]`, + artifactRoute: `{"artifact":"art"}`, + buildRoute: `{"id":"b1"}`, + }) + _, err := submitPush(client, cfg, io.NopCloser(strings.NewReader("archive")), "", "go", true) + if !errors.Is(err, api.ErrNoSettingsAPI) { + t.Fatalf("got %v, want ErrNoSettingsAPI", err) + } + if builds := requestsTo(*requests, http.MethodPost, "/projects/p/services/s/builds"); len(builds) != 0 { + t.Errorf("submitted a build without its settings: %+v", builds) + } +} + +func TestSkipsDeploy(t *testing.T) { + for _, tc := range []struct { + Name string + Config string + Want bool + }{ + {"Skip", "project: p\nservice: s\ndeployment:\n skip: true\n", true}, + {"NoSkip", "project: p\nservice: s\ndeployment:\n skip: false\n", false}, + {"NoSection", "project: p\nservice: s\n", false}, + } { + t.Run(tc.Name, func(t *testing.T) { + cfg, _ := writeServiceConfig(t, tc.Config) + if got := skipsDeploy(cfg); got != tc.Want { + t.Errorf("skipsDeploy = %v, want %v", got, tc.Want) + } + }) + } +} + +func TestParseSettingAssignments(t *testing.T) { + for _, tc := range []struct { + Name string + Args []string + Want string + WantErr string + }{ + {"CPUAndMemory", []string{"cpu=500", "memory=2048"}, `{"cpu":500,"memory":2048}`, ""}, + {"HTTPAndMinRunning", []string{"http=false", "minRunning=1"}, `{"http":false,"minRunning":1}`, ""}, + {"Unknown", []string{"disk=10"}, "", `unknown setting "disk"`}, + {"NotInteger", []string{"cpu=0.5"}, "", "cpu must be an integer"}, + {"NotBool", []string{"http=maybe"}, "", "http must be true or false"}, + {"NoValue", []string{"cpu"}, "", "not name=value"}, + {"Twice", []string{"cpu=500", "cpu=600"}, "", "given twice"}, + } { + t.Run(tc.Name, func(t *testing.T) { + patch, err := parseSettingAssignments(tc.Args) + if tc.WantErr != "" { + if err == nil || !strings.Contains(err.Error(), tc.WantErr) { + t.Fatalf("got %v, want an error containing %q", err, tc.WantErr) + } + if classify(err, kindFailed) != kindInvalid { + t.Errorf("kind = %v, want invalid", classify(err, kindFailed)) + } + return + } + if err != nil { + t.Fatal(err) + } + got, _ := json.Marshal(patch) + if string(got) != tc.Want { + t.Errorf("patch = %s, want %s", got, tc.Want) + } + }) + } +} + +func TestPrintSettings(t *testing.T) { + // A field the CLI does not know yet passes through with --json. + const response = `{"settings":{"cpu":500,"memory":512,"http":true,"minRunning":0},"explicit":["cpu"],"limits":{"cpu":{"min":100,"max":2000,"step":100},"memory":{"min":128,"max":4096},"minRunning":{"min":0,"max":16}},"future":1}` + client, requests := newFakeAPI(t, map[string]string{ + "GET " + settingsPath: response, + settingsRoute: response, + }) + view, err := client.ServiceSettings("p", "s") + if err != nil { + t.Fatal(err) + } + + t.Run("Human", func(t *testing.T) { + out := setJSON(t, false) + if err := printSettings(stdout, view); err != nil { + t.Fatal(err) + } + lines := strings.Split(out.String(), "\n") + for i, want := range map[int][]string{ + 1: {"cpu", "500", "set", "100-2000 millicores, steps of 100"}, + 2: {"memory", "512", "default", "128-4096 MiB"}, + 3: {"http", "true", "default"}, + 4: {"minRunning", "0", "default", "0-16"}, + } { + for _, field := range want { + if !strings.Contains(lines[i], field) { + t.Errorf("line %q lacks %q", lines[i], field) + } + } + } + if strings.Contains(out.String(), "budget") { + t.Errorf("printed a budget the server did not send:\n%s", out) + } + }) + + t.Run("HumanBudget", func(t *testing.T) { + var budgeted api.SettingsView + if err := json.Unmarshal([]byte(settingsView), &budgeted); err != nil { + t.Fatal(err) + } + out := setJSON(t, false) + if err := printSettings(stdout, &budgeted); err != nil { + t.Fatal(err) + } + for _, want := range []string{"Project budget: 1536 of 51200 MiB memory, 1500 of 50000 millicores CPU.", "Instances that always run: 0 of 0."} { + if !strings.Contains(out.String(), want) { + t.Errorf("output lacks %q:\n%s", want, out) + } + } + }) + + t.Run("JSON", func(t *testing.T) { + out := setJSON(t, true) + if err := printSettings(stdout, view); err != nil { + t.Fatal(err) + } + var got, want bytes.Buffer + json.Compact(&got, out.Bytes()) + json.Compact(&want, []byte(response)) + if got.String() != want.String() { + t.Errorf("printed %s, want the response %s", got.String(), want.String()) + } + }) + + t.Run("Reset", func(t *testing.T) { + if _, err := client.PatchSettings("p", "s", api.SettingsPatch{"memory": nil}); err != nil { + t.Fatal(err) + } + patches := requestsTo(*requests, http.MethodPatch, settingsPath) + if len(patches) != 1 || patches[0].Body != `{"memory":null}` { + t.Errorf("settings requests %+v, want one resetting memory", patches) + } + }) +} + +func TestSettingsRefusal_HintOnlyForSettings(t *testing.T) { + for _, tc := range []struct { + Name string + Status int + Server api.JSONError + WantHint bool + }{ + {"Scope", http.StatusForbidden, api.JSONError{Err: "raising cpu needs a token with scope all", Field: "cpu"}, true}, + {"PlainForbidden", http.StatusForbidden, api.JSONError{Err: "forbidden"}, false}, + {"Invalid", http.StatusBadRequest, api.JSONError{Err: "cpu must be between", Field: "cpu"}, false}, + } { + t.Run(tc.Name, func(t *testing.T) { + err := settingsRefusal(api.Error{StatusCode: tc.Status, ServerError: tc.Server}) + if got := strings.Contains(err.Error(), "full access"); got != tc.WantHint { + t.Errorf("hint in %q = %v, want %v", err, got, tc.WantHint) + } + if classify(err, kindFailed) != statusKind(tc.Status) { + t.Errorf("kind = %v, want %v", classify(err, kindFailed), statusKind(tc.Status)) + } + }) + } +} diff --git a/config/schema.go b/config/schema.go index 4cf2953..943f483 100644 --- a/config/schema.go +++ b/config/schema.go @@ -64,6 +64,8 @@ func schemaOf(t reflect.Type) map[string]any { return map[string]any{"type": "string"} case reflect.Bool: return map[string]any{"type": "boolean"} + case reflect.Int: + return map[string]any{"type": "integer"} case reflect.Struct: props := map[string]any{} for i := 0; i < t.NumField(); i++ { diff --git a/config/schema_test.go b/config/schema_test.go index 4030caa..6b43b2c 100644 --- a/config/schema_test.go +++ b/config/schema_test.go @@ -65,6 +65,9 @@ deployment: {"NullSections", "project: p\nservice: s\nbuild:\ndeployment:\n", ""}, {"UnknownTopLevel", "project: p\nservice: s\nregion: eu\n", `line 3: unknown key "region" at the top level`}, {"UnknownInBuild", "project: p\nbuild:\n constructr: go\n", `line 3: unknown key "constructr" in build`}, + {"Settings", "project: p\nservice: s\ndeployment:\n cpu: 500\n memory: 512\n http: true\n minRunning: 0\n", ""}, + {"SettingNotInteger", "project: p\ndeployment:\n cpu: 500m\n", "cannot unmarshal"}, + {"UnknownSetting", "project: p\ndeployment:\n disk: 10\n", `line 3: unknown key "disk" in deployment`}, {"UnknownInEnvEntry", "build:\n environment:\n - key: A\n val: x\n", `line 4: unknown key "val" in build.environment[0]`}, } { t.Run(tc.Name, func(t *testing.T) { @@ -94,3 +97,36 @@ deployment: }) } } + +func TestDeploymentConfig_Settings(t *testing.T) { + for _, tc := range []struct { + Name string + Config string + Want string + }{ + {"None", "project: p\ndeployment:\n skip: false\n", "null"}, + {"NoSection", "project: p\n", "null"}, + {"NullKey", "project: p\ndeployment:\n cpu:\n", "null"}, + {"Some", "project: p\ndeployment:\n memory: 2048\n", `{"memory":2048}`}, + {"All", "project: p\ndeployment:\n cpu: 500\n memory: 512\n http: true\n minRunning: 0\n", `{"cpu":500,"http":true,"memory":512,"minRunning":0}`}, + } { + t.Run(tc.Name, func(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, ".valar.yml"), []byte(tc.Config), 0o644); err != nil { + t.Fatal(err) + } + t.Chdir(dir) + var cfg ServiceConfigYAML + if err := cfg.ReadFromFile(".valar.yml"); err != nil { + t.Fatal(err) + } + got, err := json.Marshal(cfg.Deployment.Settings()) + if err != nil { + t.Fatal(err) + } + if string(got) != tc.Want { + t.Errorf("Settings() = %s, want %s", got, tc.Want) + } + }) + } +} diff --git a/config/service.go b/config/service.go index c0cf2de..2ec6c40 100644 --- a/config/service.go +++ b/config/service.go @@ -67,6 +67,34 @@ type BuildConfig struct { type DeploymentConfig struct { Skip bool `yaml:"skip" json:"skip" doc:"Build without deploying."` Environment []EnvironmentConfig `yaml:"environment" json:"environment" doc:"Deprecated: runtime variables are stored by the platform, see 'valar env'. Move them with 'valar env import'."` + CPU *int `yaml:"cpu,omitempty" json:"cpu,omitempty" doc:"Requested CPU in millicores, 100 to 2000 in steps of 100; the platform's default is 1000. Applied before each deploying push."` + Memory *int `yaml:"memory,omitempty" json:"memory,omitempty" doc:"Requested memory in MiB, 128 to 4096; the platform's default is 1024. Applied before each deploying push."` + HTTP *bool `yaml:"http,omitempty" json:"http,omitempty" doc:"Whether the service serves HTTP; the platform's default is true. Applied before each deploying push."` + MinRunning *int `yaml:"minRunning,omitempty" json:"minRunning,omitempty" doc:"Instances that are never paused; the platform's default is 0. Applied before each deploying push."` +} + +// Settings returns the service settings the file declares, or nil. +func (d *DeploymentConfig) Settings() map[string]any { + if d == nil { + return nil + } + settings := map[string]any{} + if d.CPU != nil { + settings["cpu"] = *d.CPU + } + if d.Memory != nil { + settings["memory"] = *d.Memory + } + if d.HTTP != nil { + settings["http"] = *d.HTTP + } + if d.MinRunning != nil { + settings["minRunning"] = *d.MinRunning + } + if len(settings) == 0 { + return nil + } + return settings } // Abort reports a missing setting and ends the process. The CLI replaces it to @@ -179,7 +207,7 @@ func (config *ServiceConfigYAML) ReadFromFile(name string) error { return &Error{Path: path, Err: fmt.Errorf("%s: %w", path, err)} } if err := doc.Decode(config); err != nil { - return &Error{Path: path, Err: fmt.Errorf("config read: %w", err)} + return &Error{Path: path, Err: fmt.Errorf("%s: %w", path, err)} } config.filePath = path return nil diff --git a/schema/valar.yml.json b/schema/valar.yml.json index fe017c4..34c47fd 100644 --- a/schema/valar.yml.json +++ b/schema/valar.yml.json @@ -62,6 +62,13 @@ "additionalProperties": false, "description": "How builds are deployed.", "properties": { + "cpu": { + "description": "Requested CPU in millicores, 100 to 2000 in steps of 100; the platform's default is 1000. Applied before each deploying push.", + "type": [ + "integer", + "null" + ] + }, "environment": { "deprecated": true, "description": "Deprecated: runtime variables are stored by the platform, see 'valar env'. Move them with 'valar env import'.", @@ -94,6 +101,27 @@ "null" ] }, + "http": { + "description": "Whether the service serves HTTP; the platform's default is true. Applied before each deploying push.", + "type": [ + "boolean", + "null" + ] + }, + "memory": { + "description": "Requested memory in MiB, 128 to 4096; the platform's default is 1024. Applied before each deploying push.", + "type": [ + "integer", + "null" + ] + }, + "minRunning": { + "description": "Instances that are never paused; the platform's default is 0. Applied before each deploying push.", + "type": [ + "integer", + "null" + ] + }, "skip": { "description": "Build without deploying.", "type": "boolean" diff --git a/skills/valar/SKILL.md b/skills/valar/SKILL.md index adc7b21..96599d7 100644 --- a/skills/valar/SKILL.md +++ b/skills/valar/SKILL.md @@ -55,7 +55,11 @@ 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 `. 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 `. 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 `. 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 `. If the build passes but requests fail, read `valar service logs --json`. `valar deployment rollback` deploys the newest earlier version that served, skipping failed ones. + +## Size + +`cpu` (millicores, 100 to 2000 in steps of 100, default 1000) and `memory` (MiB, 128 to 4096, default 1024) size each deployment. Declare them in `.valar.yml` under `deployment:`; a deploying push applies them before the build. `valar service settings --json` shows the current values, their bounds and the project's budget; `valar service settings set memory=2048` and `reset memory` change them for the next deployment. Raising a value needs a token with full access and room in the budget: exit code 4 means ask the user, not retry. ## The app's contract