Skip to content
Open
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
19 changes: 19 additions & 0 deletions client/raw.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,25 @@ func (r *RawClient) Get[M any](ctx context.Context, uuid uuid.UUID, pathElems ..
http.WithAccept(api.MeshObjectMimeType()))
}

// Post creates an object of M from payload, its JSON as meshStack takes it.
func (r *RawClient) Post[M any](ctx context.Context, payload jsontext.Value) (jsontext.Value, error) {
api, err := r.api[M]()
if err != nil {
return nil, err
}
return api.DoRequest[jsontext.Value](ctx, http.MethodPost, api.ApiUrl, http.WithJsonPayload(payload, api.MeshObjectMimeType()))
}

// Put replaces the object of M with the uuid by payload, its JSON as meshStack takes it.
func (r *RawClient) Put[M any](ctx context.Context, uuid uuid.UUID, payload jsontext.Value) (jsontext.Value, error) {
api, err := r.api[M]()
if err != nil {
return nil, err
}
return api.DoRequest[jsontext.Value](ctx, http.MethodPut, api.ApiUrl.JoinPath(uuid.String()),
http.WithJsonPayload(payload, api.MeshObjectMimeType()), http.Retryable())
}

// DoRequest joins path onto the endpoint, even one that names a host, so that the bearer token
// never leaves for another host. The answer is of any content type, such as a plan artifact's
// application/octet-stream, so it is returned unparsed.
Expand Down
2 changes: 2 additions & 0 deletions cmd/buildingblock/buildingblock.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,10 @@ func New() *cobra.Command {
}

cmd.AddCommand(newList())
cmd.AddCommand(newCreate())
cmd.AddCommand(newTriggerRun())
cmd.AddCommand(newWait())
cmd.AddCommand(newUpgrade())
cmd.AddCommand(newApproveRun())
cmd.AddCommand(newAbortRun())
cmd.AddCommand(tfstate.New())
Expand Down
77 changes: 77 additions & 0 deletions cmd/buildingblock/create.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package buildingblock

import (
"encoding/json/jsontext"
"encoding/json/v2"
"errors"
"fmt"
"log/slog"
"uuid"

"github.com/spf13/cobra"

"github.com/meshcloud/meshstack-cli/client"
"github.com/meshcloud/meshstack-cli/cmd/internal"
)

const fileFlagName = "file"

func newCreate() *cobra.Command {
var (
output internal.OutputFlag
file internal.JsonInputFlag[jsontext.Value]
wait bool
)

cmd := &cobra.Command{
Use: "create -f <file|->",
Short: "Create a building block from a file",
Long: `Create a building block from a JSON file, or from stdin with -f -. The file holds the building block as the meshStack API takes it; 'meshstack api-docs --describe buildingblock' shows its fields.

The command prints meshStack's response, the building block before its first run has started. With --` + waitFlagName + `, it waits until that run has ended.`,
Example: ` meshstack buildingblock create -f block.json --wait
jq -n '{kind: "meshBuildingBlock", spec: {...}}' | meshstack bb create -f - -o ndjson | jq -r .metadata.uuid`,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
ctx := cmd.Context()
payload, err := file.Read(cmd)
if err != nil {
return err
}
meshStack, err := internal.ResolveClient(ctx)
if err != nil {
return err
}
answer, err := meshStack.Raw.Post[client.MeshBuildingBlockV2](ctx, payload)
if err != nil {
return err
}
var created struct {
Metadata client.MeshBuildingBlockV2Metadata `json:"metadata"`
Status client.MeshBuildingBlockV2Status `json:"status"`
}
if err = json.Unmarshal(answer, &created); err != nil {
return err
}
if created.Metadata.Uuid == nil {
return errors.New("meshStack created the building block, but its response names no uuid")
}
buildingBlockUuid, err := uuid.Parse(*created.Metadata.Uuid)
if err != nil {
return err
}
slog.InfoContext(ctx, fmt.Sprintf("Created building block %s.", buildingBlockUuid))
if wait {
return awaitRunEnd(ctx, cmd.OutOrStdout(), output.Format, meshStack.Raw, buildingBlockUuid, &created.Status)
}
return output.Format.WriteItem(cmd.OutOrStdout(), answer)
},
}

output.RegisterForItem(cmd.Flags())
file.RegisterP(cmd.Flags(), fileFlagName, "f", "file with the building block, or - to read it from stdin")
_ = cmd.MarkFlagRequired(fileFlagName)
cmd.Flags().BoolVar(&wait, waitFlagName, false, "wait until the run has ended, and fail if the run failed or is waiting for a person or a dependency")

return cmd
}
180 changes: 180 additions & 0 deletions cmd/buildingblock/upgrade.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
package buildingblock

import (
"context"
"encoding/json/jsontext"
"encoding/json/v2"
"fmt"
"log/slog"
"strings"
"uuid"

"github.com/spf13/cobra"

"github.com/meshcloud/meshstack-cli/client"
"github.com/meshcloud/meshstack-cli/cmd/internal"
)

const (
versionFlagName = "version"
inputFlagName = "input"
)

func newUpgrade() *cobra.Command {
var (
output internal.OutputFlag
buildingBlockUuid uuid.UUID
versionUuid uuid.UUID
inputs []string
wait bool
)

cmd := &cobra.Command{
Use: "upgrade <building-block-uuid>",
Short: "Upgrade a building block to another version of its definition",
Long: `Upgrade a building block to another version of its definition, by default to the latest released version. Give the building block by its uuid.

The building block keeps the values of its inputs. Give a value for an input that the new version adds, such as a payment method, or for an input that you want to change, with --` + inputFlagName + ` <name>=<value>. The command sends a value that is valid JSON as that JSON, and any other value as a string. A payment method input takes the payment method's reference, such as {"kind": "meshPaymentMethod", "name": "<identifier>"}, and a sensitive input takes {"plaintext": "<value>"}.

meshStack upgrades a building block only to the latest released version of its definition. Only for a building block in the workspace that owns the definition, --` + versionFlagName + ` can name a draft version, to test it. Changing the version needs admin rights or the right of the workspace that owns the definition to manage its building blocks.

The command prints meshStack's response, the building block before the run that the upgrade starts. With --` + waitFlagName + `, it waits until that run has ended. This is the same as piping the response into 'meshstack buildingblock wait <uuid> --` + beforeFlagName + `=-'.`,
Example: ` meshstack buildingblock upgrade 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 --wait
meshstack bb upgrade 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 --input 'payment_method={"kind": "meshPaymentMethod", "name": "my-payment-method"}'`,
Args: internal.UuidArg(&buildingBlockUuid),
RunE: func(cmd *cobra.Command, _ []string) error {
ctx := cmd.Context()
values, err := parseInputs(inputs)
if err != nil {
return err
}
meshStack, err := internal.ResolveClient(ctx)
if err != nil {
return err
}
read, err := meshStack.Raw.Get[client.MeshBuildingBlockV2](ctx, buildingBlockUuid)
if err != nil {
return err
}
var upgrade upgradeRequest
if err = json.Unmarshal(read, &upgrade); err != nil {
return err
}
current := upgrade.Spec.BuildingBlockDefinitionVersionRef.Uuid
if versionUuid == uuid.Nil() {
if versionUuid, err = latestReleasedVersion(ctx, meshStack.Raw, current); err != nil {
return err
}
}
if versionUuid.String() == current {
return fmt.Errorf("building block %s already uses version %s", buildingBlockUuid, current)
}
upgrade.Spec.BuildingBlockDefinitionVersionRef.Uuid = versionUuid.String()
upgrade.Spec.Inputs = values
payload, err := json.Marshal(upgrade)
if err != nil {
return err
}
answer, err := meshStack.Raw.Put[client.MeshBuildingBlockV2](ctx, buildingBlockUuid, payload)
if err != nil {
return err
}
slog.InfoContext(ctx, fmt.Sprintf("Asked meshStack to upgrade building block %s from version %s to version %s.", buildingBlockUuid, current, versionUuid))
if wait {
var accepted struct {
Status client.MeshBuildingBlockV2Status `json:"status"`
}
if err = json.Unmarshal(answer, &accepted); err != nil {
return err
}
return awaitRunEnd(ctx, cmd.OutOrStdout(), output.Format, meshStack.Raw, buildingBlockUuid, &accepted.Status)
}
return output.Format.WriteItem(cmd.OutOrStdout(), answer)
},
}

output.RegisterForItem(cmd.Flags())
cmd.Flags().Var((*internal.UuidFlag)(&versionUuid), versionFlagName, "upgrade to the version with this uuid instead of the latest released version")
cmd.Flags().StringArrayVar(&inputs, inputFlagName, nil, "set the input to the value, given as <name>=<value>; repeat it for each input")
cmd.Flags().BoolVar(&wait, waitFlagName, false, "wait until the run has ended, and fail if the run failed or is waiting for a person or a dependency")

return cmd
}

// upgradeRequest is what an upgrade sends back of the building block it read. It sends only the
// inputs to set, because meshStack keeps the value of every input that a version change leaves out,
// and rejects one that the building block's owner may not set.
type upgradeRequest struct {
ApiVersion string `json:"apiVersion"`
Kind string `json:"kind"`
Metadata jsontext.Value `json:"metadata"`
Spec struct {
BuildingBlockDefinitionVersionRef client.UuidRef `json:"buildingBlockDefinitionVersionRef"`
TargetRef jsontext.Value `json:"targetRef,omitzero"`
DisplayName string `json:"displayName"`
ParentBuildingBlockRefs jsontext.Value `json:"parentBuildingBlockRefs,omitzero"`
Inputs map[string]upgradeInput `json:"inputs"`
} `json:"spec"`
}

type upgradeInput struct {
Value jsontext.Value `json:"value"`
}

func parseInputs(given []string) (map[string]upgradeInput, error) {
values := map[string]upgradeInput{}
for _, input := range given {
name, value, ok := strings.Cut(input, "=")
if !ok || name == "" {
return nil, fmt.Errorf("--%s %q is not of the form <name>=<value>", inputFlagName, input)
}
raw := jsontext.Value(value)
if !raw.IsValid() {
var err error
if raw, err = json.Marshal(value); err != nil {
return nil, err
}
}
values[name] = upgradeInput{Value: raw}
}
return values, nil
}

func latestReleasedVersion(ctx context.Context, raw *client.RawClient, currentVersion string) (uuid.UUID, error) {
versionUuid, err := uuid.Parse(currentVersion)
if err != nil {
return uuid.Nil(), fmt.Errorf("the building block names its version as %q, which is no uuid", currentVersion)
}
read, err := raw.Get[client.MeshBuildingBlockDefinitionVersion](ctx, versionUuid)
if err != nil {
return uuid.Nil(), err
}
var version struct {
Spec struct {
BuildingBlockDefinitionRef *client.UuidRef `json:"buildingBlockDefinitionRef"`
} `json:"spec"`
}
if err = json.Unmarshal(read, &version); err != nil {
return uuid.Nil(), err
}
if version.Spec.BuildingBlockDefinitionRef == nil {
return uuid.Nil(), fmt.Errorf("version %s names no building block definition", currentVersion)
}
definitionUuid, err := uuid.Parse(version.Spec.BuildingBlockDefinitionRef.Uuid)
if err != nil {
return uuid.Nil(), err
}
if read, err = raw.Get[client.MeshBuildingBlockDefinition](ctx, definitionUuid); err != nil {
return uuid.Nil(), err
}
var definition struct {
Status client.MeshBuildingBlockDefinitionStatus `json:"status"`
}
if err = json.Unmarshal(read, &definition); err != nil {
return uuid.Nil(), err
}
if definition.Status.LatestReleasedVersionUuid == nil {
return uuid.Nil(), fmt.Errorf("building block definition %s has no released version. Use --%s to name a draft version", definitionUuid, versionFlagName)
}
return uuid.Parse(*definition.Status.LatestReleasedVersionUuid)
}
52 changes: 52 additions & 0 deletions cmd/buildingblock/upgrade_internal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package buildingblock

import (
"io"
gohttp "net/http"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/meshcloud/meshstack-cli/internal/testutil/fakemeshstack"
"github.com/meshcloud/meshstack-cli/internal/testutil/testlogin"
)

func TestUpgradeSendsOnlyTheNewVersionAndTheGivenInputs(t *testing.T) {
const (
currentVersion = "c0000000-0000-4000-8000-000000000001"
latestRelease = "c0000000-0000-4000-8000-000000000002"
definition = "d0000000-0000-4000-8000-000000000001"
)
server := fakemeshstack.Start(t, fakemeshstack.Options{
BuildingBlocks: []any{meshObject(t, `{"apiVersion": "v2-preview", "kind": "meshBuildingBlock", `+
`"metadata": {"uuid": "`+buildingBlockUuid+`", "ownedByWorkspace": "app"}, `+
`"spec": {"displayName": "my-block", "buildingBlockDefinitionVersionRef": {"kind": "meshBuildingBlockDefinitionVersion", "uuid": "`+currentVersion+`"}, `+
`"targetRef": {"kind": "meshWorkspace", "name": "app"}, "parentBuildingBlockRefs": [], `+
`"inputs": {"name": {"value": "web", "assignmentType": "USER_INPUT"}, "hub": {"value": "eu", "assignmentType": "STATIC"}}}, `+
`"status": {"action": "UPGRADE_AVAILABLE"}}`)},
})
server.Route("GET /api/meshobjects/meshbuildingblockdefinitionversions/"+currentVersion, func(w gohttp.ResponseWriter, _ *gohttp.Request) {
_, _ = io.WriteString(w, `{"metadata": {"uuid": "`+currentVersion+`"}, "spec": {"buildingBlockDefinitionRef": {"kind": "meshBuildingBlockDefinition", "uuid": "`+definition+`"}}}`)
})
server.Route("GET /api/meshobjects/meshbuildingblockdefinitions/"+definition, func(w gohttp.ResponseWriter, _ *gohttp.Request) {
_, _ = io.WriteString(w, `{"metadata": {"uuid": "`+definition+`"}, "status": {"latestReleasedVersionUuid": "`+latestRelease+`"}}`)
})
var sent string
server.Route("PUT /api/meshobjects/meshbuildingblocks/"+buildingBlockUuid, func(w gohttp.ResponseWriter, r *gohttp.Request) {
body, _ := io.ReadAll(r.Body)
sent = string(body)
_, _ = w.Write(body)
})
testlogin.LoggedInTo(t, server.URL)

cmd := New()
cmd.SetOut(io.Discard)
cmd.SetArgs([]string{"upgrade", buildingBlockUuid, "--input", `payment_method={"kind": "meshPaymentMethod", "name": "pm"}`, "--input", "size=small"})

require.NoError(t, cmd.ExecuteContext(t.Context()))
assert.JSONEq(t, `{"apiVersion": "v2-preview", "kind": "meshBuildingBlock", "metadata": {"uuid": "`+buildingBlockUuid+`", "ownedByWorkspace": "app"}, `+
`"spec": {"displayName": "my-block", "buildingBlockDefinitionVersionRef": {"kind": "meshBuildingBlockDefinitionVersion", "uuid": "`+latestRelease+`"}, `+
`"targetRef": {"kind": "meshWorkspace", "name": "app"}, "parentBuildingBlockRefs": [], `+
`"inputs": {"payment_method": {"value": {"kind": "meshPaymentMethod", "name": "pm"}}, "size": {"value": "small"}}}}`, sent)
}
6 changes: 5 additions & 1 deletion cmd/internal/read.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,12 @@ type JsonInputFlag[T any] struct {
}

func (f *JsonInputFlag[T]) Register(flags *pflag.FlagSet, name, usage string) {
f.RegisterP(flags, name, "", usage)
}

func (f *JsonInputFlag[T]) RegisterP(flags *pflag.FlagSet, name, shorthand, usage string) {
f.name = name
flags.Var(f, name, usage)
flags.VarP(f, name, shorthand, usage)
}

func (f *JsonInputFlag[T]) String() string {
Expand Down
Loading
Loading