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
43 changes: 2 additions & 41 deletions client/building_block_v2.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,50 +218,11 @@ func (status MeshBuildingBlockV2Status) RunFailed() bool {
return slices.Contains(buildingBlockActionsRunFailed, status.Action)
}

// RunChangedSince says whether meshStack has reacted to a write since before, by the rules of
// https://docs.meshcloud.io/concepts/building-block/#waiting-for-a-run. A zero before is a block that had no status yet.
func (status MeshBuildingBlockV2Status) RunChangedSince(before MeshBuildingBlockV2Status) bool {
switch {
case status.GetLatestRunUuid() != before.GetLatestRunUuid(),
status.GetLatestDryRunUuid() != before.GetLatestDryRunUuid(),
status.RunStartFailedOn != "" && status.RunStartFailedOn != before.RunStartFailedOn:
return true
case before.RunStartFailedOn != "" && status.RunStartFailedOn == "":
// A build that includes the block again only clears the old failure.
return false
default:
return !before.IsRunning() && status.actionOfRun() != before.actionOfRun()
}
}

// actionOfRun ignores UPGRADE_AVAILABLE, which a newly released definition version sets without any run.
func (status MeshBuildingBlockV2Status) actionOfRun() enum.Entry[BuildingBlockAction] {
if status.Action == BuildingBlockActionUpgradeAvailable {
return BuildingBlockActionNoAction
}
return status.Action
}

func (bb *MeshBuildingBlockV2) IsWaitingForInput() bool {
return bb.Status != nil && bb.Status.IsWaitingForInput()
}

// RunEndedSince is done on every action that is not running, a failed or an unknown one included:
// the caller judges the outcome.
func (bb *MeshBuildingBlockV2) RunEndedSince(before MeshBuildingBlockV2Status) (done bool, err error) {
switch {
case bb == nil:
err = errors.New("building block not found")
case bb.Status == nil, !bb.Status.RunChangedSince(before), bb.Status.IsRunning():
default:
done = true
}
return
}

// DeletionSuccessful takes the status the block had before the deletion, because meshStack reports the
// action of the run before until the delete run starts.
func (bb *MeshBuildingBlockV2) DeletionSuccessful(before MeshBuildingBlockV2Status) (done bool, err error) {
func (bb *MeshBuildingBlockV2) DeletionSuccessful() (done bool, err error) {
switch {
case bb == nil:
// A 404: the block is gone, for example together with its definition.
Expand All @@ -270,7 +231,7 @@ func (bb *MeshBuildingBlockV2) DeletionSuccessful(before MeshBuildingBlockV2Stat
// A soft-deleted block does not return 404: the backend keeps returning it with DELETED.
// MARKED_FOR_DELETION means the deletion still runs, so polling goes on.
done = true
case bb.Status == nil, !bb.Status.RunChangedSince(before):
case bb.Status == nil, bb.Status.IsRunning():
case bb.Status.ForcePurge:
// A force purge (definition deletion_mode PURGE, or an admin purge) deletes the block whatever
// its delete run reports, and the lifecycle still reaches DELETED.
Expand Down
110 changes: 0 additions & 110 deletions client/building_block_v2_test.go

This file was deleted.

18 changes: 9 additions & 9 deletions cmd/buildingblock/trigger_run.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func newTriggerRun() *cobra.Command {

The command waits until meshStack has started the run, and then prints the building block. Its status.latestRunUuid is the run. If the definition requires an approval of the run, status.latestDryRunUuid is the preflight run, whose plan the approver sees. 'meshstack buildingblockrun logs <run-uuid>' shows how far a run got.

With --` + waitFlagName + `, the command waits until the run has ended. This is the same as piping meshStack's response to the run request into 'meshstack buildingblock wait <uuid> --` + beforeFlagName + `=-'.
With --` + waitFlagName + `, the command waits until the run has ended. This is the same as running 'meshstack buildingblock wait <uuid>' afterwards.

'meshstack api-docs --describe buildingblock.trigger-run' shows the fields of the response.`,
Example: ` meshstack buildingblock trigger-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90
Expand Down Expand Up @@ -58,20 +58,20 @@ With --` + waitFlagName + `, the command waits until the run has ended. This is
accepted = *answer.Status
}
if wait {
return awaitRunEnd(ctx, cmd.OutOrStdout(), output.Format, meshStack.BuildingBlockV2, buildingBlockUuid, accepted)
return awaitRunEnd(ctx, cmd.OutOrStdout(), output.Format, meshStack.BuildingBlockV2, buildingBlockUuid)
}
runWait := buildingblock.NewRunWait(meshStack.BuildingBlockV2, buildingBlockUuid)
reacted, err := runWait.AwaitReaction(ctx, accepted)
started, err := runWait.AwaitStart(ctx)
if err != nil {
return err
}
if err := output.Format.WriteItem(cmd.OutOrStdout(), client.WithKindAndApiVersion(meshStack.BuildingBlockV2, *reacted)); err != nil {
if err := output.Format.WriteItem(cmd.OutOrStdout(), client.WithKindAndApiVersion(meshStack.BuildingBlockV2, *started)); err != nil {
return err
}
if err := runWait.StartFailure(reacted); err != nil {
if err := runWait.StartFailure(started); err != nil {
return err
}
slog.InfoContext(ctx, startedRunMessage(buildingBlockUuid, accepted, *reacted.Status))
slog.InfoContext(ctx, startedRunMessage(buildingBlockUuid, accepted, *started.Status))
return nil
},
}
Expand All @@ -84,15 +84,15 @@ With --` + waitFlagName + `, the command waits until the run has ended. This is

const waitFlagName = "wait"

func startedRunMessage(buildingBlockUuid string, accepted, reacted client.MeshBuildingBlockV2Status) string {
switch dryRun, run := reacted.GetLatestDryRunUuid(), reacted.GetLatestRunUuid(); {
func startedRunMessage(buildingBlockUuid string, accepted, started client.MeshBuildingBlockV2Status) string {
switch dryRun, run := started.GetLatestDryRunUuid(), started.GetLatestRunUuid(); {
case dryRun != "" && dryRun != accepted.GetLatestDryRunUuid():
return fmt.Sprintf("meshStack started the preflight run %s of building block %s. The run that makes the changes then waits for approval. "+
"Follow the preflight run with 'meshstack buildingblockrun logs %s'", dryRun, buildingBlockUuid, dryRun)
case run != "" && run != accepted.GetLatestRunUuid():
return fmt.Sprintf("meshStack started run %s of building block %s. Follow it with 'meshstack buildingblockrun logs %s'",
run, buildingBlockUuid, run)
default:
return fmt.Sprintf("Building block %s now has the action %s.", buildingBlockUuid, reacted.Action)
return fmt.Sprintf("Building block %s now has the action %s.", buildingBlockUuid, started.Action)
}
}
15 changes: 6 additions & 9 deletions cmd/buildingblock/trigger_run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"bytes"
"encoding/json/jsontext"
"fmt"
"io"
gohttp "net/http"
"testing"

Expand All @@ -23,16 +22,14 @@ func TestTriggerRunPrintsTheBuildingBlockAndFailsWithTheReasonMeshStackCouldNotS
buildingBlockUuid = "b1d2c3e4-0000-4000-8000-000000000001"
reason = "meshStack could not start a run for this Building Block.\n\nAsk your platform team to look up the details in the meshStack logs."
)
failure := func(failedOn string) string {
return fmt.Sprintf(`{"metadata": {"uuid": %q, "ownedByWorkspace": "my-workspace"}, "spec": {}, `+
`"status": {"action": "PENDING", "latestRunUuid": "a0000000-0000-4000-8000-000000000001", "runStartFailure": %q, "runStartFailedOn": %q}, `+
`"_links": {"triggerRun": {"href": "/api/meshobjects/meshbuildingblocks/%s/trigger-run"}}}`,
buildingBlockUuid, reason, failedOn, buildingBlockUuid)
}
meshStack := fakemeshstack.Start(t, fakemeshstack.Options{BuildingBlocks: []any{jsontext.Value(failure("2026-10-01T10:05:00Z"))}})
failure := fmt.Sprintf(`{"metadata": {"uuid": %q, "ownedByWorkspace": "my-workspace"}, "spec": {}, `+
`"status": {"action": "REVIEW_ERRORS", "latestRunUuid": "a0000000-0000-4000-8000-000000000001", "runStartFailure": %q, "runStartFailedOn": "2026-10-01T10:05:00Z"}, `+
`"_links": {"triggerRun": {"href": "/api/meshobjects/meshbuildingblocks/%s/trigger-run"}}}`,
buildingBlockUuid, reason, buildingBlockUuid)
meshStack := fakemeshstack.Start(t, fakemeshstack.Options{BuildingBlocks: []any{jsontext.Value(failure)}})
meshStack.Route("POST /api/meshobjects/meshbuildingblocks/{uuid}/trigger-run", func(w gohttp.ResponseWriter, _ *gohttp.Request) {
w.WriteHeader(gohttp.StatusAccepted)
_, _ = io.WriteString(w, failure("2026-10-01T10:00:00Z"))
_, _ = fmt.Fprintf(w, `{"metadata": {"uuid": %q}, "spec": {}, "status": {"action": "PENDING", "latestRunUuid": "a0000000-0000-4000-8000-000000000001"}}`, buildingBlockUuid)
})
testlogin.LoggedInTo(t, meshStack.URL)

Expand Down
45 changes: 9 additions & 36 deletions cmd/buildingblock/wait.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,65 +14,38 @@ import (
)

func newWait() *cobra.Command {
var (
output internal.OutputFlag
beforeInput internal.JsonInputFlag[client.MeshBuildingBlockV2]
)
var output internal.OutputFlag

cmd := &cobra.Command{
Use: "wait <building-block-uuid> --before <file|->",
Use: "wait <building-block-uuid>",
Short: "Wait until the run of a building block has ended",
Long: `Wait until meshStack has reacted to a write of a building block, and until the run that the write started has ended. Give the building block by its uuid.
Long: `Wait until the run of a building block has ended. Give the building block by its uuid.

meshStack responds to a write before it starts the run. So right after the write, the building block still shows the action of the previous run. Pass that response with --` + beforeFlagName + `: the response of a create (POST), an update (PUT) or a trigger-run, or a read taken before the change. The command first waits up to a minute until meshStack has reacted, following the rules of https://docs.meshcloud.io/concepts/building-block/#waiting-for-a-run. Then it waits until the run has ended. Press Ctrl-C to stop waiting.
After a write that asks for a run, such as a create (POST), an update (PUT) or a trigger-run, meshStack shows the action PENDING until it has started the run, and IN_PROGRESS while the run is going on. The command waits while the action is PENDING or IN_PROGRESS. Press Ctrl-C to stop waiting.

The command prints the building block. It fails and names the action if the run failed, was aborted or could not start, or if the run is waiting for a person or a dependency.`,
Example: ` meshstack api -X PUT /api/meshobjects/meshbuildingblocks/0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 --request-json block.json |
meshstack bb wait 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 --before=-`,
Example: ` meshstack api -X PUT /api/meshobjects/meshbuildingblocks/0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 --request-json block.json &&
meshstack bb wait 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90`,
Args: internal.UuidArg,
RunE: func(cmd *cobra.Command, args []string) error {
buildingBlockUuid := args[0]
before, err := readBefore(cmd, beforeInput, buildingBlockUuid)
if err != nil {
return err
}
meshStack, err := internal.ResolveClient(cmd.Context())
if err != nil {
return err
}
return awaitRunEnd(cmd.Context(), cmd.OutOrStdout(), output.Format, meshStack.BuildingBlockV2, buildingBlockUuid, before)
return awaitRunEnd(cmd.Context(), cmd.OutOrStdout(), output.Format, meshStack.BuildingBlockV2, args[0])
},
}

output.RegisterForItem(cmd.Flags())
beforeInput.Register(cmd.Flags(), beforeFlagName, "file with the building block from before the write, or - to read it from stdin")
_ = cmd.MarkFlagRequired(beforeFlagName)

return cmd
}

const beforeFlagName = "before"

func readBefore(cmd *cobra.Command, input internal.JsonInputFlag[client.MeshBuildingBlockV2], buildingBlockUuid string) (client.MeshBuildingBlockV2Status, error) {
source := input.Source
before, err := input.Read(cmd)
if err != nil {
return client.MeshBuildingBlockV2Status{}, err
}
switch {
case before.Metadata.Uuid != nil && *before.Metadata.Uuid != buildingBlockUuid:
return client.MeshBuildingBlockV2Status{}, fmt.Errorf("--%s %s contains building block %s, but the command waits for %s", beforeFlagName, source, *before.Metadata.Uuid, buildingBlockUuid)
case before.Status == nil:
return client.MeshBuildingBlockV2Status{}, fmt.Errorf("--%s %s contains no status of the building block", beforeFlagName, source)
}
return *before.Status, nil
}

// awaitRunEnd writes the building block once its run has ended, and fails on an outcome someone has
// to act on.
func awaitRunEnd(ctx context.Context, out io.Writer, format internal.OutputFormat, blocks client.MeshBuildingBlockV2Client, buildingBlockUuid string, before client.MeshBuildingBlockV2Status) error {
func awaitRunEnd(ctx context.Context, out io.Writer, format internal.OutputFormat, blocks client.MeshBuildingBlockV2Client, buildingBlockUuid string) error {
wait := buildingblock.NewRunWait(blocks, buildingBlockUuid)
block, err := wait.AwaitEnd(ctx, before)
block, err := wait.AwaitEnd(ctx)
if err != nil {
return err
}
Expand Down
14 changes: 3 additions & 11 deletions cmd/buildingblock/wait_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"fmt"
"io"
gohttp "net/http"
"strings"
"sync/atomic"
"testing"

Expand All @@ -26,40 +25,33 @@ func buildingBlockWithRun(action, latestRunUuid string) string {
}

func TestWaitFailsOnAnOutcomeThatNeedsSomeoneToAct(t *testing.T) {
before := buildingBlockWithRun("NO_ACTION", "run-1")
var current atomic.Pointer[string]
meshStack := fakemeshstack.Start(t, fakemeshstack.Options{})
meshStack.Route("GET /api/meshobjects/meshbuildingblocks/{uuid}", func(w gohttp.ResponseWriter, _ *gohttp.Request) {
_, _ = io.WriteString(w, *current.Load())
})
testlogin.LoggedInTo(t, meshStack.URL)

run := func(stdin string, args ...string) (string, error) {
run := func(args ...string) (string, error) {
cmd := buildingblock.New()
var stdout bytes.Buffer
cmd.SetOut(&stdout)
cmd.SetIn(strings.NewReader(stdin))
cmd.SetArgs(args)
err := cmd.ExecuteContext(t.Context())
return stdout.String(), err
}

t.Run("wait needs the building block from before the write", func(t *testing.T) {
_, err := run("", "wait", waitedBuildingBlock)
require.ErrorContains(t, err, `required flag(s) "before" not set`)
})

t.Run("a failed run fails the wait with its action and the meshPanel link", func(t *testing.T) {
current.Store(new(buildingBlockWithRun("REVIEW_ERRORS", "run-2")))
stdout, err := run(before, "wait", waitedBuildingBlock, "--before=-")
stdout, err := run("wait", waitedBuildingBlock)
require.ErrorContains(t, err, "ended with action REVIEW_ERRORS")
require.ErrorContains(t, err, "https://panel.example/#/go/buildingblock/"+waitedBuildingBlock)
assert.Contains(t, stdout, `"action": "REVIEW_ERRORS"`, "the building block still goes to stdout")
})

t.Run("a run that waits for approval fails the wait", func(t *testing.T) {
current.Store(new(buildingBlockWithRun("APPROVE_RUN", "run-2")))
_, err := run(before, "wait", waitedBuildingBlock, "--before=-")
_, err := run("wait", waitedBuildingBlock)
require.ErrorContains(t, err, "is paused at action APPROVE_RUN")
})
}
Loading
Loading