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
121 changes: 111 additions & 10 deletions client/building_block_run.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,28 @@ package client

import (
"context"
"encoding/json/jsontext"
"errors"
"fmt"
"io"
"time"

"github.com/meshcloud/meshstack-cli/client/http"
"github.com/meshcloud/meshstack-cli/client/types/enum"
"github.com/meshcloud/meshstack-cli/client/types/hal"
"github.com/meshcloud/meshstack-cli/internal/json"
)

const buildingBlockRunApiVersion = "v1"

// MeshBuildingBlockRun keeps apiVersion and kind, because a runner passes the run on as it came.
type MeshBuildingBlockRun struct {
Metadata MeshBuildingBlockRunMetadata `json:"metadata"`
Spec MeshBuildingBlockRunSpec `json:"spec"`
Status string `json:"status"`
Links hal.Links `json:"_links,omitzero"`
ApiVersion string `json:"apiVersion"`
Kind string `json:"kind"`
Metadata MeshBuildingBlockRunMetadata `json:"metadata"`
Spec MeshBuildingBlockRunSpec `json:"spec"`
Status string `json:"status"`
Links hal.Links `json:"_links,omitzero"`
}

func (run MeshBuildingBlockRun) IsRunning() bool {
Expand All @@ -27,6 +39,9 @@ type MeshBuildingBlockRunSpec struct {
RunNumber int `json:"runNumber"`
Behavior string `json:"behavior"`
BuildingBlock MeshBuildingBlockRunBuildingBlock `json:"buildingBlock"`
Definition MeshBuildingBlockRunDefinition `json:"buildingBlockDefinition"`
RunToken string `json:"runToken"`
Trigger *MeshBuildingBlockRunTrigger `json:"trigger,omitzero"`
}

type MeshBuildingBlockRunBuildingBlock struct {
Expand All @@ -35,18 +50,104 @@ type MeshBuildingBlockRunBuildingBlock struct {
}

type MeshBuildingBlockRunBuildingBlockSpec struct {
DisplayName string `json:"displayName"`
TargetRef MeshBuildingBlockV2TargetRef `json:"targetRef"`
WorkspaceIdentifier string `json:"workspaceIdentifier"`
ProjectIdentifier string `json:"projectIdentifier,omitempty"`
FullPlatformIdentifier string `json:"fullPlatformIdentifier,omitempty"`
DisplayName string `json:"displayName"`
TargetRef MeshBuildingBlockV2TargetRef `json:"targetRef"`
WorkspaceIdentifier string `json:"workspaceIdentifier"`
ProjectIdentifier string `json:"projectIdentifier,omitempty"`
FullPlatformIdentifier string `json:"fullPlatformIdentifier,omitempty"`
Inputs []MeshBuildingBlockRunInput `json:"inputs"`
ParentBuildingBlocks []MeshBuildingBlockRunParentBlock `json:"parentBuildingBlocks"`
}

type MeshBuildingBlockRunParentBlock struct {
BuildingBlockUuid string `json:"buildingBlockUuid"`
DefinitionUuid string `json:"definitionUuid"`
}

type MeshBuildingBlockRunInput struct {
Key string `json:"key"`
// Value holds an int64 for an INTEGER and a []string for a MULTI_SELECT.
Value any `json:"value"`
Type enum.Entry[MeshBuildingBlockIOType] `json:"type"`
IsSensitive bool `json:"isSensitive"`
Env bool `json:"isEnvironment"`
}

func (i *MeshBuildingBlockRunInput) UnmarshalJSONFrom(dec *jsontext.Decoder) error {
type wire MeshBuildingBlockRunInput
var target struct {
wire

Value jsontext.Value `json:"value"`
}
if err := json.UnmarshalDecode(dec, &target, dec.Options()); err != nil {
return err
}
*i = MeshBuildingBlockRunInput(target.wire)
switch i.Type {
case MeshBuildingBlockIOTypeInteger:
i.Value = int64(0)
case MeshBuildingBlockIOTypeMultiSelect:
i.Value = []string(nil)
}
if err := json.Unmarshal(target.Value, &i.Value, dec.Options()); err != nil {
return fmt.Errorf("input %s: %w", i.Key, err)
}
return nil
}

type MeshBuildingBlockRunDefinition struct {
Uuid string `json:"uuid"`
Spec MeshBuildingBlockRunDefinitionSpec `json:"spec"`
}

type MeshBuildingBlockRunDefinitionSpec struct {
WorkspaceIdentifier string `json:"workspaceIdentifier"`
Version int `json:"version"`
Implementation MeshBuildingBlockRunImplementation `json:"implementation"`
}

type MeshBuildingBlockRunTrigger struct {
Reason string `json:"reason"`
Author MeshObjectAuthor `json:"author"`
}

type MeshBuildingBlockRunFilter struct {
BuildingBlockUuid string `json:"buildingBlockUuid,omitzero"`
}

type MeshBuildingBlockRunClient = MeshObjectReadOnlyClient[MeshBuildingBlockRun, MeshBuildingBlockRunFilter]
var ErrNoRunToClaim = errors.New("no run to claim")

type MeshBuildingBlockRunClient interface {
MeshObjectReadOnlyClient[MeshBuildingBlockRun, MeshBuildingBlockRunFilter]

Claim(ctx context.Context, runnerUuid string) (MeshBuildingBlockRun, error)
// RegisterSource takes a 409 as success: the source was registered before.
RegisterSource(ctx context.Context, runUuid string, registration MeshBuildingBlockRunSourceRegistration) error
UpdateSourceSteps(ctx context.Context, runUuid, sourceId string, update MeshBuildingBlockRunStatusUpdate) (MeshBuildingBlockRunStatusUpdateResult, error)
// DownloadArtifact writes the artifact of the run that this run applies.
DownloadArtifact(ctx context.Context, runUuid string, w io.Writer) error
UploadArtifact(ctx context.Context, runUuid, path string) error
}

type meshBuildingBlockRunClient struct {
meshObjectClient[MeshBuildingBlockRun, MeshBuildingBlockRunFilter]
}

func (c meshBuildingBlockRunClient) Claim(ctx context.Context, runnerUuid string) (MeshBuildingBlockRun, error) {
run, err := c.unmarshalJsonBody[MeshBuildingBlockRun](c.do(ctx, http.MethodPost, c.collection.JoinPath("create"),
http.WithUrlQuery(map[string]string{"forRunnerUuid": runnerUuid}),
http.WithContentType(c.mediaType),
http.WithHeader("X-Meshcloud-Runner-Version", c.client.UserAgentVersion()),
http.WithRedactedJsonPointers("/spec/runToken")))
switch {
case isNotFound(err):
return run, ErrNoRunToClaim
case err == nil && run.Metadata.Uuid == "":
return run, errors.New("the claimed run has no uuid")
}
return run, err
}

// MeshBuildingBlockRunApproval names the plan, because meshStack replaces it when a waiting run is planned again.
type MeshBuildingBlockRunApproval struct {
Expand Down
77 changes: 77 additions & 0 deletions client/building_block_run_implementation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package client

import (
"github.com/meshcloud/meshstack-cli/client/types/enum"
"github.com/meshcloud/meshstack-cli/client/types/polymorph"
)

type MeshBuildingBlockRunImplementationType string

var (
MeshBuildingBlockRunImplementationTypes = enum.Enum[MeshBuildingBlockRunImplementationType]{}
MeshBuildingBlockRunImplementationTypeManual = MeshBuildingBlockRunImplementationTypes.Entry("MANUAL")
MeshBuildingBlockRunImplementationTypeTerraform = MeshBuildingBlockRunImplementationTypes.Entry("TERRAFORM")
MeshBuildingBlockRunImplementationTypeGithubWorkflow = MeshBuildingBlockRunImplementationTypes.Entry("GITHUB_WORKFLOW")
MeshBuildingBlockRunImplementationTypeGitlabCiCd = MeshBuildingBlockRunImplementationTypes.Entry("GITLAB_CICD")
MeshBuildingBlockRunImplementationTypeAzureDevops = MeshBuildingBlockRunImplementationTypes.Entry("AZURE_DEVOPS")
)

type MeshBuildingBlockRunImplementation struct {
polymorph.Polymorph[MeshBuildingBlockRunImplementation, MeshBuildingBlockRunImplementationType]

Manual *MeshBuildingBlockRunManualImplementation `polymorph:"MANUAL,inline"`
Terraform *MeshBuildingBlockRunTerraformImplementation `polymorph:"TERRAFORM,inline"`
GithubWorkflow *MeshBuildingBlockRunGithubImplementation `polymorph:"GITHUB_WORKFLOW,inline"`
GitlabCiCd *MeshBuildingBlockRunGitlabImplementation `polymorph:"GITLAB_CICD,inline"`
AzureDevops *MeshBuildingBlockRunAzureDevopsImplementation `polymorph:"AZURE_DEVOPS,inline"`
}

type MeshBuildingBlockRunManualImplementation struct{}

type MeshBuildingBlockRunTerraformImplementation struct {
TerraformVersion string `json:"terraformVersion"`
RepositoryUrl string `json:"repositoryUrl"`
RepositoryPath *string `json:"repositoryPath,omitzero"`
RefName *string `json:"refName,omitzero"`
SshPrivateKey *string `json:"sshPrivateKey,omitzero"`
KnownHost *MeshBuildingBlockRunKnownHost `json:"knownHost,omitzero"`
UseMeshHttpBackendFallback bool `json:"useMeshHttpBackendFallback"`
PreRunScript *string `json:"preRunScript,omitzero"`
Async bool `json:"async"`
}

type MeshBuildingBlockRunKnownHost struct {
Host string `json:"host"`
KeyType string `json:"keyType"`
KeyValue string `json:"keyValue"`
}

type MeshBuildingBlockRunGithubImplementation struct {
GithubBaseUrl string `json:"githubBaseUrl"`
Owner string `json:"owner"`
AppId string `json:"appId"`
AppPem string `json:"appPem"`
Repository string `json:"repository"`
Branch string `json:"branch"`
ApplyWorkflow string `json:"applyWorkflow"`
DestroyWorkflow *string `json:"destroyWorkflow,omitzero"`
Async bool `json:"async"`
OmitRunObjectInput bool `json:"omitRunObjectInput"`
}

type MeshBuildingBlockRunGitlabImplementation struct {
GitlabBaseUrl string `json:"gitlabBaseUrl"`
ProjectId string `json:"projectId"`
RefName string `json:"refName"`
PipelineTriggerToken string `json:"pipelineTriggerToken"`
}

type MeshBuildingBlockRunAzureDevopsImplementation struct {
AzureDevOpsBaseUrl string `json:"azureDevOpsBaseUrl"`
Organization string `json:"organization"`
Project string `json:"project"`
PipelineId string `json:"pipelineId"`
PersonalAccessToken string `json:"personalAccessToken"`
Async bool `json:"async"`
RefName *string `json:"refName,omitzero"`
}
103 changes: 103 additions & 0 deletions client/building_block_run_source.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package client

import (
"context"
"errors"
"fmt"
"io"
"time"

"github.com/meshcloud/meshstack-cli/client/http"
"github.com/meshcloud/meshstack-cli/client/types/enum"
)

type MeshBuildingBlockRunSourceRegistration struct {
Source MeshBuildingBlockRunSource `json:"source"`
Steps []MeshBuildingBlockRunStepRegistration `json:"steps"`
}

type MeshBuildingBlockRunSource struct {
Id string `json:"id"`
ExternalId *string `json:"externalId,omitzero"`
ExternalUrl *string `json:"externalUrl,omitzero"`
}

type MeshBuildingBlockRunStepRegistration struct {
Id string `json:"id"`
DisplayName string `json:"displayName"`
Status *string `json:"status"`
}

type MeshBuildingBlockRunStatusUpdate struct {
BlockRunId string `json:"blockRunId,omitzero"`
Source string `json:"source,omitzero"`
Type enum.Entry[MeshBuildingBlockRunImplementationType] `json:"type,omitempty"`
Status *string `json:"status"`
CreatedOn time.Time `json:"createdOn,omitzero"`
Summary *string `json:"summary"`
Steps []MeshBuildingBlockRunStepStatusUpdate `json:"steps"`
ChangesDetected *bool `json:"changesDetected,omitzero"`
}

type MeshBuildingBlockRunStepStatusUpdate struct {
Id string `json:"id"`
DisplayName string `json:"displayName"`
Status *string `json:"status,omitzero"`
UserMessage *string `json:"userMessage,omitzero"`
SystemMessage *string `json:"systemMessage,omitzero"`
Outputs map[string]MeshBuildingBlockRunOutput `json:"outputs,omitempty"`
}

type MeshBuildingBlockRunOutput struct {
Value any `json:"value"`
Type string `json:"type"`
Sensitive bool `json:"isSensitive"`
}

type MeshBuildingBlockRunStatusUpdateResult struct {
Abort bool `json:"runAborted"`
}

const maxArtifactBytes = 128 << 20

func (c meshBuildingBlockRunClient) RegisterSource(ctx context.Context, runUuid string, registration MeshBuildingBlockRunSourceRegistration) error {
err := http.IgnoreResponse(c.do(ctx, http.MethodPost, c.collection.JoinPath(runUuid, "status", "source"),
http.WithJsonRequest(registration, c.mediaType), http.Retryable(http.RetryOnTransient)))
if httpErr, ok := errors.AsType[http.Error](err); ok && httpErr.IsConflict() {
return nil
}
return err
}

func (c meshBuildingBlockRunClient) UpdateSourceSteps(ctx context.Context, runUuid, sourceId string, update MeshBuildingBlockRunStatusUpdate) (MeshBuildingBlockRunStatusUpdateResult, error) {
return http.UnmarshalJsonBody[MeshBuildingBlockRunStatusUpdateResult](c.do(ctx, http.MethodPatch, c.collection.JoinPath(runUuid, "status", "source", sourceId),
http.WithJsonRequest(update, c.mediaType), http.Retryable(http.RetryOnTransient)))
}

func (c meshBuildingBlockRunClient) DownloadArtifact(ctx context.Context, runUuid string, w io.Writer) error {
body, err := c.do(ctx, http.MethodGet, c.collection.JoinPath(runUuid, "artifact"), http.WithHeader("Accept", "application/octet-stream"))
if err != nil {
return err
}
_, err = io.Copy(&cappedWriter{w, maxArtifactBytes}, body)
return errors.Join(err, body.Close())
}

func (c meshBuildingBlockRunClient) UploadArtifact(ctx context.Context, runUuid, path string) error {
return http.IgnoreResponse(c.do(ctx, http.MethodPut, c.collection.JoinPath(runUuid, "artifact"),
http.WithFileRequest(path, ""), http.WithHeader("Accept", "*/*")))
}

type cappedWriter struct {
io.Writer

remaining int64
}

func (w *cappedWriter) Write(p []byte) (int, error) {
if int64(len(p)) > w.remaining {
return 0, fmt.Errorf("the artifact exceeds %d bytes", maxArtifactBytes)
}
w.remaining -= int64(len(p))
return w.Writer.Write(p)
}
2 changes: 1 addition & 1 deletion client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func New(ctx context.Context, endpoint xurl.URL, client http.Client, auth http.A
return Client{
ApiKey: newMeshObjectClient[MeshApiKey, NoFilter](ctx, c, endpoint, "v1-preview"),
BuildingBlockV2: newMeshObjectClient[MeshBuildingBlockV2, MeshBuildingBlockV2Filter](ctx, c, endpoint, buildingBlockV2ApiVersion),
BuildingBlockRun: newMeshObjectClient[MeshBuildingBlockRun, MeshBuildingBlockRunFilter](ctx, c, endpoint, "v1"),
BuildingBlockRun: meshBuildingBlockRunClient{newMeshObjectClient[MeshBuildingBlockRun, MeshBuildingBlockRunFilter](ctx, c, endpoint, buildingBlockRunApiVersion)},
BuildingBlockDefinition: newMeshObjectClient[MeshBuildingBlockDefinition, MeshBuildingBlockDefinitionFilter](ctx, c, endpoint, "v1"),
BuildingBlockDefinitionVersion: newMeshObjectClient[MeshBuildingBlockDefinitionVersion, MeshBuildingBlockDefinitionVersionFilter](ctx, c, endpoint, "v1"),
BuildingBlockRunner: newMeshObjectClient[MeshBuildingBlockRunner, MeshBuildingBlockRunnerFilter](ctx, c, endpoint, "v1-preview"),
Expand Down
Loading
Loading