diff --git a/.claude/skills/development/SKILL.md b/.claude/skills/development/SKILL.md index 4f75fb0a..baefa3eb 100644 --- a/.claude/skills/development/SKILL.md +++ b/.claude/skills/development/SKILL.md @@ -123,12 +123,18 @@ there, later, and not in this repository's CI. `develop` but not released. The source is the controllers and meshObjects of `../meshfed-release` (*meshcloud-internal*). -**The provider implements the client's interfaces.** Its tests plug the mocks of its -`internal/clientmock` into `client.Client`, so a method added to a `Mesh…Client` interface stops -the provider compiling at its next bump. Put a method only the CLI calls on a new `client.Client` -field instead: an interface of its own, or a concrete type such as `*client.RawClient` when nothing -mocks it. `client.New` sets the field for every caller, while the provider's mock client fills the -struct by field name and leaves a new field unset. +**The provider implements the client's interfaces.** Every kind's client is a type alias named +after the kind for one of three generic interfaces, each of which adds to the one before: +`client.MeshObjectReadOnlyClient[M, Filter]` with Read, List and ListSeq, +`client.MeshObjectImmutableClient[M, Filter]` with Create and Delete, and +`client.MeshObjectClient[M, Filter]` with Update. The alias takes the level that the API docs offer +for the kind. The tests of the provider plug the mocks of its `internal/clientmock` into +`client.Client`, so a method added to a `Mesh…Client` interface stops the provider compiling at +its next bump. An action of a kind is a method of the object, such as `run.Abort(ctx)`, which +follows a link of the object's `_links` through `hal.Links` and states the link's rel, method, +payload and result type once. Put anything else only the CLI +calls on a new `client.Client` field, which the provider's mock client leaves unset, or in a +function of `client`, such as `client.WithKindAndApiVersion`. Reading the pre-import history takes both paths, since the import merge re-roots the files under `client/`: @@ -138,7 +144,7 @@ git log -- client/client.go client.go # a path-limited log from client/ alone git blame client/client.go # traverses the merge on its own ``` -**`client/` does not log in.** `client.Authorization` produces a bearer token and replaces one that +**`client/` does not log in.** `http.Authorization` produces a bearer token and replaces one that came back 401; resolving a credential, minting a token, caching it and refreshing it is `pkg/auth`. Both front ends build their client through `auth.ResolveClient`, so the endpoint and the authorization always agree with what was resolved. Do **not** add a login exchange anywhere else: a diff --git a/.claude/skills/meshobject-command/SKILL.md b/.claude/skills/meshobject-command/SKILL.md index 87650d06..74908a4a 100644 --- a/.claude/skills/meshobject-command/SKILL.md +++ b/.claude/skills/meshobject-command/SKILL.md @@ -44,8 +44,8 @@ the `help-text` rule of the `development` skill. ## Leaf -- `list` lists the kind with `flags.Run[M](cmd, filter)` of `internal.ListFlags`, which pages through - `client.Raw.List[M]`. +- `list` lists the kind with `flags.Run(cmd, meshStack., filter)` of `internal.ListFlags`, + which pages through the kind's `List`. - `show` shows one object. - A sub-resource or an action is named after its path element in the API: `buildingblockrun logs` for `…/logs`, `buildingblock trigger-run` for `…/trigger-run`. @@ -65,11 +65,10 @@ and a `cmd/internal/markdown` template next to the command. - A command gets its client from `internal.ResolveClient`, or for the session itself from `auth.ResolveSession(ctx, internal.ResolveClientOptions(...))` and `Session.Client`. A `ResolveClientOptionsModifier` such as `internal.SkipVersionCheck` adapts the resolution. -- What the CLI writes as meshStack sent it goes through `client.Raw`: `List[M]` with the kind's - list filter struct, `Get[M]` for one object or a sub-resource below it, and `DoRequest` for any - other path. `M` is the Go type of the kind's typed client, which `client.New` registers with - `Raw`; register a kind there before a command reads it. -- A list filter struct holds every query parameter the API docs give its endpoint, a repeated one +- The CLI writes an object as meshStack sent it through `client.WithKindAndApiVersion`. A + sub-resource or an action is a method of the typed object, such as `run.Logs`, which follows a + link of its `Links`. Add such a method in `client/` for a new one. Any other path goes through `client.Client.HttpClient`, joined onto `client.Client.Endpoint`. +- A filter struct holds every query parameter the API docs give its endpoint, a repeated one as a slice. A parameter the command always sends, such as `includeAllPublished`, is a field the command sets. Any other client method only the CLI calls goes on a new `client.Client` field, so the Terraform provider's mocks keep compiling. diff --git a/.golangci.yml b/.golangci.yml index 198db5d2..29169942 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -183,7 +183,7 @@ linters: checks: - all - -ST1000 - # SA4023 crashes on a type with a generic method, as client.RawClient has: go1.27.0 loses + # SA4023 crashes on a type with a generic method, as hal.Link has: go1.27.0 loses # the order of methods in the export data (golang/go#81188). Enable it again with go1.27.2. - -SA4023 # Replaces the default list, so that ClientId, BaseUrl and Uuid stand as the meshObject diff --git a/client/api_key.go b/client/api_key.go index 6605a449..78463d37 100644 --- a/client/api_key.go +++ b/client/api_key.go @@ -1,22 +1,21 @@ package client import ( - "context" "time" - "github.com/meshcloud/meshstack-cli/client/internal" "github.com/meshcloud/meshstack-cli/client/types" ) +type MeshApiKeyMetadata = MeshObjectByUuidMetadata + type MeshApiKey struct { Metadata MeshApiKeyMetadata `json:"metadata" tfsdk:"metadata"` Spec MeshApiKeySpec `json:"spec" tfsdk:"spec"` Status *MeshApiKeyStatus `json:"status,omitzero" tfsdk:"status"` } -type MeshApiKeyMetadata struct { - Uuid *string `json:"uuid,omitzero" tfsdk:"uuid"` - OwnedByWorkspace string `json:"ownedByWorkspace" tfsdk:"owned_by_workspace"` +func (k MeshApiKey) meshObjectId() string { + return k.Metadata.meshObjectId() } type MeshApiKeySpec struct { @@ -33,33 +32,4 @@ type MeshApiKeyStatus struct { ExpiresAt time.Time `json:"expiresAt,omitzero" tfsdk:"-"` } -type MeshApiKeyClient interface { - Create(ctx context.Context, apiKey *MeshApiKey) (*MeshApiKey, error) - Read(ctx context.Context, uuid string) (*MeshApiKey, error) - Update(ctx context.Context, uuid string, apiKey *MeshApiKey) (*MeshApiKey, error) - Delete(ctx context.Context, uuid string) error -} - -type meshApiKeyClient struct { - meshObject internal.MeshObjectClient[MeshApiKey] -} - -func newApiKeyClient(ctx context.Context, httpClient internal.HttpClient) MeshApiKeyClient { - return meshApiKeyClient{internal.NewMeshObjectClient[MeshApiKey](ctx, httpClient, "v1-preview")} -} - -func (c meshApiKeyClient) Create(ctx context.Context, apiKey *MeshApiKey) (*MeshApiKey, error) { - return c.meshObject.Post(ctx, apiKey) -} - -func (c meshApiKeyClient) Read(ctx context.Context, uuid string) (*MeshApiKey, error) { - return c.meshObject.Get(ctx, uuid) -} - -func (c meshApiKeyClient) Update(ctx context.Context, uuid string, apiKey *MeshApiKey) (*MeshApiKey, error) { - return c.meshObject.Put(ctx, uuid, apiKey) -} - -func (c meshApiKeyClient) Delete(ctx context.Context, uuid string) error { - return c.meshObject.Delete(ctx, uuid) -} +type MeshApiKeyClient = MeshObjectClient[MeshApiKey, NoFilter] diff --git a/client/building_block_definition.go b/client/building_block_definition.go index 246dbbf4..237fad9b 100644 --- a/client/building_block_definition.go +++ b/client/building_block_definition.go @@ -1,12 +1,9 @@ package client import ( - "context" - - "github.com/meshcloud/meshstack-cli/client/http" - "github.com/meshcloud/meshstack-cli/client/internal" "github.com/meshcloud/meshstack-cli/client/types" "github.com/meshcloud/meshstack-cli/client/types/enum" + "github.com/meshcloud/meshstack-cli/client/types/hal" ) type MeshBuildingBlockType string @@ -129,58 +126,24 @@ type MeshBuildingBlockDefinitionStatus struct { LatestReleasedVersion *int64 `json:"latestReleasedVersion"` LatestReleasedVersionUuid *string `json:"latestReleasedVersionUuid"` RedactedForNonOwnerAccess bool `json:"redactedForNonOwnerAccess"` + Lifecycle MeshLifecycle `json:"lifecycle"` } type MeshBuildingBlockDefinition struct { Metadata MeshBuildingBlockDefinitionMetadata `json:"metadata"` Spec MeshBuildingBlockDefinitionSpec `json:"spec"` Status *MeshBuildingBlockDefinitionStatus `json:"status,omitzero"` + Links hal.Links `json:"_links,omitzero"` } -type MeshBuildingBlockDefinitionClient interface { - List(ctx context.Context, workspaceIdentifier *string) ([]MeshBuildingBlockDefinition, error) - Read(ctx context.Context, uuid string) (*MeshBuildingBlockDefinition, error) - Create(ctx context.Context, definition MeshBuildingBlockDefinition) (*MeshBuildingBlockDefinition, error) - Update(ctx context.Context, uuid string, definition MeshBuildingBlockDefinition) (*MeshBuildingBlockDefinition, error) - Delete(ctx context.Context, uuid string) error -} - -type meshBuildingBlockDefinitionClient struct { - meshObject internal.MeshObjectClient[MeshBuildingBlockDefinition] -} - -func newBuildingBlockDefinitionClient(ctx context.Context, httpClient internal.HttpClient) meshBuildingBlockDefinitionClient { - return meshBuildingBlockDefinitionClient{ - meshObject: internal.NewMeshObjectClient[MeshBuildingBlockDefinition](ctx, httpClient, "v1"), - } -} +type MeshBuildingBlockDefinitionClient = MeshObjectClient[MeshBuildingBlockDefinition, MeshBuildingBlockDefinitionFilter] -type MeshBuildingBlockDefinitionListFilter struct { +type MeshBuildingBlockDefinitionFilter struct { OwnedByWorkspace *string `json:"ownedByWorkspace"` // IncludeAllPublished adds the definitions published to the whole platform to the workspace's own. - IncludeAllPublished bool `json:"includeAllPublished"` - Sort SortCriteria `json:"sort"` -} - -func (c meshBuildingBlockDefinitionClient) List(ctx context.Context, workspaceIdentifier *string) ([]MeshBuildingBlockDefinition, error) { - return c.meshObject.List(ctx, http.WithUrlQuery(MeshBuildingBlockDefinitionListFilter{ - OwnedByWorkspace: workspaceIdentifier, - IncludeAllPublished: true, - })) -} - -func (c meshBuildingBlockDefinitionClient) Read(ctx context.Context, uuid string) (*MeshBuildingBlockDefinition, error) { - return c.meshObject.Get(ctx, uuid) -} - -func (c meshBuildingBlockDefinitionClient) Create(ctx context.Context, definition MeshBuildingBlockDefinition) (*MeshBuildingBlockDefinition, error) { - return c.meshObject.Post(ctx, definition) -} - -func (c meshBuildingBlockDefinitionClient) Update(ctx context.Context, uuid string, definition MeshBuildingBlockDefinition) (*MeshBuildingBlockDefinition, error) { - return c.meshObject.Put(ctx, uuid, definition) + IncludeAllPublished bool `json:"includeAllPublished"` } -func (c meshBuildingBlockDefinitionClient) Delete(ctx context.Context, uuid string) error { - return c.meshObject.Delete(ctx, uuid) +func (d MeshBuildingBlockDefinition) meshObjectId() string { + return *d.Metadata.Uuid } diff --git a/client/building_block_definition_version.go b/client/building_block_definition_version.go index e684a09c..a0d8d1f5 100644 --- a/client/building_block_definition_version.go +++ b/client/building_block_definition_version.go @@ -1,16 +1,12 @@ package client import ( - "context" "encoding/json/jsontext" "errors" - "fmt" - "uuid" - "github.com/meshcloud/meshstack-cli/client/http" - "github.com/meshcloud/meshstack-cli/client/internal" "github.com/meshcloud/meshstack-cli/client/types" "github.com/meshcloud/meshstack-cli/client/types/enum" + "github.com/meshcloud/meshstack-cli/client/types/hal" "github.com/meshcloud/meshstack-cli/internal/json" ) @@ -181,9 +177,9 @@ type MeshBuildingBlockDefinitionOutput struct { } type MeshBuildingBlockDefinitionVersionMetadata struct { - Uuid string `json:"uuid"` - OwnedByWorkspace string `json:"ownedByWorkspace"` - CreatedOn string `json:"createdOn"` + Uuid *string `json:"uuid,omitzero"` + OwnedByWorkspace string `json:"ownedByWorkspace"` + CreatedOn string `json:"createdOn,omitzero"` } type MeshBuildingBlockDefinitionVersionSpec struct { @@ -201,63 +197,27 @@ type MeshBuildingBlockDefinitionVersionSpec struct { } type MeshBuildingBlockDefinitionVersionStatus struct { - State MeshBuildingBlockDefinitionVersionState `json:"state" tfsdk:"state"` - UsageCount *int64 `json:"usageCount,omitzero" tfsdk:"usage_count"` + State MeshBuildingBlockDefinitionVersionState `json:"state" tfsdk:"state"` + UsageCount *int64 `json:"usageCount,omitzero" tfsdk:"usage_count"` + RedactedForNonOwnerAccess bool `json:"redactedForNonOwnerAccess" tfsdk:"-"` + Lifecycle MeshLifecycle `json:"lifecycle" tfsdk:"-"` } type MeshBuildingBlockDefinitionVersion struct { Metadata MeshBuildingBlockDefinitionVersionMetadata `json:"metadata" tfsdk:"metadata"` Spec MeshBuildingBlockDefinitionVersionSpec `json:"spec" tfsdk:"spec"` Status *MeshBuildingBlockDefinitionVersionStatus `json:"status,omitzero" tfsdk:"status"` + Links hal.Links `json:"_links,omitzero" tfsdk:"-"` } -// MeshBuildingBlockDefinitionVersionClient has no Get and no Delete: a caller always reads all -// versions of a definition with List, and the versions are deleted together with their definition. -type MeshBuildingBlockDefinitionVersionClient interface { - List(ctx context.Context, buildingBlockDefinitionUuid string) ([]MeshBuildingBlockDefinitionVersion, error) - Create(ctx context.Context, ownedByWorkspace string, versionSpec MeshBuildingBlockDefinitionVersionSpec) (*MeshBuildingBlockDefinitionVersion, error) - Update(ctx context.Context, uuid, ownedByWorkspace string, versionSpec MeshBuildingBlockDefinitionVersionSpec) (*MeshBuildingBlockDefinitionVersion, error) -} - -type meshBuildingBlockDefinitionVersionClient struct { - meshObject internal.MeshObjectClient[MeshBuildingBlockDefinitionVersion] -} - -func newBuildingBlockDefinitionVersionClient(ctx context.Context, httpClient internal.HttpClient) meshBuildingBlockDefinitionVersionClient { - return meshBuildingBlockDefinitionVersionClient{ - meshObject: internal.NewMeshObjectClient[MeshBuildingBlockDefinitionVersion](ctx, httpClient, "v1"), - } -} +type MeshBuildingBlockDefinitionVersionClient = MeshObjectClient[MeshBuildingBlockDefinitionVersion, MeshBuildingBlockDefinitionVersionFilter] -type MeshBuildingBlockDefinitionVersionListFilter struct { - BuildingBlockDefinitionUuid uuid.UUID `json:"buildingBlockDefinitionUuid,omitzero"` +type MeshBuildingBlockDefinitionVersionFilter struct { + BuildingBlockDefinitionUuid string `json:"buildingBlockDefinitionUuid,omitzero"` } -func (c meshBuildingBlockDefinitionVersionClient) List(ctx context.Context, buildingBlockDefinitionUuid string) ([]MeshBuildingBlockDefinitionVersion, error) { - definitionUuid, err := uuid.Parse(buildingBlockDefinitionUuid) - if err != nil { - return nil, fmt.Errorf("building block definition %q: %w", buildingBlockDefinitionUuid, err) - } - return c.meshObject.List(ctx, http.WithUrlQuery(MeshBuildingBlockDefinitionVersionListFilter{ - BuildingBlockDefinitionUuid: definitionUuid, - })) +func (v MeshBuildingBlockDefinitionVersion) meshObjectId() string { + return *v.Metadata.Uuid } -func (c meshBuildingBlockDefinitionVersionClient) Create(ctx context.Context, ownedByWorkspace string, versionSpec MeshBuildingBlockDefinitionVersionSpec) (*MeshBuildingBlockDefinitionVersion, error) { - return c.meshObject.Post(ctx, MeshBuildingBlockDefinitionVersion{ - Metadata: MeshBuildingBlockDefinitionVersionMetadata{ - OwnedByWorkspace: ownedByWorkspace, - }, - Spec: versionSpec, - }) -} - -func (c meshBuildingBlockDefinitionVersionClient) Update(ctx context.Context, uuid, ownedByWorkspace string, versionSpec MeshBuildingBlockDefinitionVersionSpec) (*MeshBuildingBlockDefinitionVersion, error) { - return c.meshObject.Put(ctx, uuid, MeshBuildingBlockDefinitionVersion{ - Metadata: MeshBuildingBlockDefinitionVersionMetadata{ - Uuid: uuid, - OwnedByWorkspace: ownedByWorkspace, - }, - Spec: versionSpec, - }) -} +func (MeshBuildingBlockDefinitionVersion) meshObjectNoSortQuery() {} diff --git a/client/building_block_definition_version_implementation.go b/client/building_block_definition_version_implementation.go index 2700d179..714568e3 100644 --- a/client/building_block_definition_version_implementation.go +++ b/client/building_block_definition_version_implementation.go @@ -1,13 +1,9 @@ package client import ( - "encoding/json/jsontext" - "fmt" - "github.com/meshcloud/meshstack-cli/client/types" "github.com/meshcloud/meshstack-cli/client/types/enum" - "github.com/meshcloud/meshstack-cli/client/types/variant" - "github.com/meshcloud/meshstack-cli/internal/json" + "github.com/meshcloud/meshstack-cli/client/types/polymorph" ) type MeshBuildingBlockImplementationType string @@ -67,52 +63,11 @@ type MeshBuildingBlockDefinitionAzureDevOpsPipelineImplementation struct { } type MeshBuildingBlockDefinitionImplementation struct { - Type enum.Entry[MeshBuildingBlockImplementationType] `json:"type" tfsdk:"-"` - Manual *MeshBuildingBlockDefinitionManualImplementation `json:"manual,omitzero" tfsdk:"manual"` - GithubWorkflows *MeshBuildingBlockDefinitionGitHubWorkflowsImplementation `json:"githubWorkflows,omitzero" tfsdk:"github_workflows"` - AzureDevOpsPipeline *MeshBuildingBlockDefinitionAzureDevOpsPipelineImplementation `json:"azureDevOpsPipeline,omitzero" tfsdk:"azure_devops_pipeline"` - GitlabPipeline *MeshBuildingBlockDefinitionGitLabPipelineImplementation `json:"gitlabPipeline,omitzero" tfsdk:"gitlab_pipeline"` - Terraform *MeshBuildingBlockDefinitionTerraformImplementation `json:"terraform,omitzero" tfsdk:"terraform"` -} - -// InferType accepts a version without any variant: meshStack answers that way to a workspace that -// may only consume the definition. -func (m MeshBuildingBlockDefinitionImplementation) InferType() (enum.Entry[MeshBuildingBlockImplementationType], error) { - result, err := variant.InferType( - variant.NewCandidate(MeshBuildingBlockImplementationTypeManual, m.Manual != nil), - variant.NewCandidate(MeshBuildingBlockImplementationTypeTerraform, m.Terraform != nil), - variant.NewCandidate(MeshBuildingBlockImplementationTypeGithubWorkflows, m.GithubWorkflows != nil), - variant.NewCandidate(MeshBuildingBlockImplementationTypeGitlabPipeline, m.GitlabPipeline != nil), - variant.NewCandidate(MeshBuildingBlockImplementationTypeAzureDevOpsPipeline, m.AzureDevOpsPipeline != nil), - ) - if err != nil { - return "", fmt.Errorf("cannot infer implementation type: %w", err) - } - return result, nil -} - -func (m MeshBuildingBlockDefinitionImplementation) MarshalJSONTo(enc *jsontext.Encoder) error { - type wrapped MeshBuildingBlockDefinitionImplementation - w := wrapped(m) - if len(w.Type) == 0 { - inferred, err := m.InferType() - if err != nil { - return err - } - w.Type = inferred - } - return json.MarshalEncode(enc, w, enc.Options()) -} + polymorph.Polymorph[MeshBuildingBlockDefinitionImplementation, MeshBuildingBlockImplementationType] -func (m *MeshBuildingBlockDefinitionImplementation) UnmarshalJSONFrom(dec *jsontext.Decoder) error { - type wrapped MeshBuildingBlockDefinitionImplementation - var target wrapped - if err := json.UnmarshalDecode(dec, &target, dec.Options()); err != nil { - return err - } - *m = MeshBuildingBlockDefinitionImplementation(target) - if m.Type == MeshBuildingBlockImplementationTypeManual { - m.Manual = &MeshBuildingBlockDefinitionManualImplementation{} - } - return nil + Manual *MeshBuildingBlockDefinitionManualImplementation `json:"manual,omitzero" polymorph:"manual" tfsdk:"manual"` + GithubWorkflows *MeshBuildingBlockDefinitionGitHubWorkflowsImplementation `json:"githubWorkflows,omitzero" polymorph:"githubWorkflows" tfsdk:"github_workflows"` + AzureDevOpsPipeline *MeshBuildingBlockDefinitionAzureDevOpsPipelineImplementation `json:"azureDevOpsPipeline,omitzero" polymorph:"azureDevOpsPipeline" tfsdk:"azure_devops_pipeline"` + GitlabPipeline *MeshBuildingBlockDefinitionGitLabPipelineImplementation `json:"gitlabPipeline,omitzero" polymorph:"gitlabPipeline" tfsdk:"gitlab_pipeline"` + Terraform *MeshBuildingBlockDefinitionTerraformImplementation `json:"terraform,omitzero" polymorph:"terraform" tfsdk:"terraform"` } diff --git a/client/building_block_run.go b/client/building_block_run.go index 565cb7bf..d9324d13 100644 --- a/client/building_block_run.go +++ b/client/building_block_run.go @@ -3,16 +3,15 @@ package client import ( "context" "time" - "uuid" - "github.com/meshcloud/meshstack-cli/client/internal" + "github.com/meshcloud/meshstack-cli/client/types/hal" ) type MeshBuildingBlockRun struct { Metadata MeshBuildingBlockRunMetadata `json:"metadata"` Spec MeshBuildingBlockRunSpec `json:"spec"` Status string `json:"status"` - Links MeshBuildingBlockRunLinks `json:"_links,omitzero"` + Links hal.Links `json:"_links,omitzero"` } func (run MeshBuildingBlockRun) IsRunning() bool { @@ -21,18 +20,15 @@ func (run MeshBuildingBlockRun) IsRunning() bool { type MeshBuildingBlockRunMetadata struct { Uuid string `json:"uuid"` - CreatedAt time.Time `json:"createdAt"` + CreatedAt time.Time `json:"createdAt,omitzero"` } type MeshBuildingBlockRunSpec struct { - RunNumber int64 `json:"runNumber"` + RunNumber int `json:"runNumber"` Behavior string `json:"behavior"` BuildingBlock MeshBuildingBlockRunBuildingBlock `json:"buildingBlock"` } -// MeshBuildingBlockRunBuildingBlock is spec.buildingBlock of a meshBuildingBlockRun. The wire also -// carries spec.buildingBlock.spec.inputs, which holds the run's input values and is left out here -// because a sensitive one goes out encrypted for the runner alone. type MeshBuildingBlockRunBuildingBlock struct { Uuid string `json:"uuid"` Spec MeshBuildingBlockRunBuildingBlockSpec `json:"spec"` @@ -42,40 +38,55 @@ type MeshBuildingBlockRunBuildingBlockSpec struct { DisplayName string `json:"displayName"` TargetRef MeshBuildingBlockV2TargetRef `json:"targetRef"` WorkspaceIdentifier string `json:"workspaceIdentifier"` - ProjectIdentifier *string `json:"projectIdentifier"` - FullPlatformIdentifier *string `json:"fullPlatformIdentifier"` + ProjectIdentifier string `json:"projectIdentifier,omitempty"` + FullPlatformIdentifier string `json:"fullPlatformIdentifier,omitempty"` } -type MeshBuildingBlockRunListFilter struct { - BuildingBlockUuid uuid.UUID `json:"buildingBlockUuid,omitzero"` - Sort SortCriteria `json:"sort"` +type MeshBuildingBlockRunFilter struct { + BuildingBlockUuid string `json:"buildingBlockUuid,omitzero"` } -type MeshBuildingBlockRunLogs struct { - Steps []MeshBuildingBlockRunStepLog `json:"steps"` +type MeshBuildingBlockRunClient = MeshObjectReadOnlyClient[MeshBuildingBlockRun, MeshBuildingBlockRunFilter] + +// MeshBuildingBlockRunApproval names the plan, because meshStack replaces it when a waiting run is planned again. +type MeshBuildingBlockRunApproval struct { + PredecessorRunUuid string `json:"predecessorRunUuid"` } -type MeshBuildingBlockRunStepLog struct { - DisplayName string `json:"displayName"` - Status string `json:"status"` - UserMessage *string `json:"userMessage"` - SystemMessage *string `json:"systemMessage"` +func (run MeshBuildingBlockRun) Abort(ctx context.Context) error { + _, err := run.Links.Post[struct{}](ctx, "abort", nil) + return err } -type MeshBuildingBlockRunClient interface { - GetLogs(ctx context.Context, runUuid string) (MeshBuildingBlockRunLogs, error) +func (run MeshBuildingBlockRun) Approve(ctx context.Context, predecessorRunUuid string) error { + _, err := run.Links.Post[struct{}](ctx, "approve", MeshBuildingBlockRunApproval{PredecessorRunUuid: predecessorRunUuid}) + return err } -type meshBuildingBlockRunClient struct { - meshObject internal.MeshObjectClient[MeshBuildingBlockRun] +func (run MeshBuildingBlockRun) Reject(ctx context.Context) error { + _, err := run.Links.Post[struct{}](ctx, "reject", nil) + return err } -func newBuildingBlockRunClient(ctx context.Context, httpClient internal.HttpClient) meshBuildingBlockRunClient { - return meshBuildingBlockRunClient{ - meshObject: internal.NewMeshObjectClient[MeshBuildingBlockRun](ctx, httpClient, "v1"), - } +func (run MeshBuildingBlockRun) Predecessor(ctx context.Context) (MeshBuildingBlockRun, error) { + return run.Links.Get[MeshBuildingBlockRun](ctx, "predecessor") } -func (c meshBuildingBlockRunClient) GetLogs(ctx context.Context, runUuid string) (MeshBuildingBlockRunLogs, error) { - return c.meshObject.GetAtPath[MeshBuildingBlockRunLogs](ctx, runUuid, "logs") +func (run MeshBuildingBlockRun) Logs(ctx context.Context) (MeshBuildingBlockRunLogs, error) { + return run.Links.Get[MeshBuildingBlockRunLogs](ctx, "downloadLogs") +} + +func (run MeshBuildingBlockRun) meshObjectId() string { + return run.Metadata.Uuid +} + +type MeshBuildingBlockRunLogs struct { + Steps []MeshBuildingBlockRunStepLog `json:"steps"` +} + +type MeshBuildingBlockRunStepLog struct { + DisplayName string `json:"displayName"` + Status string `json:"status"` + UserMessage *string `json:"userMessage"` + SystemMessage *string `json:"systemMessage"` } diff --git a/client/building_block_run_action.go b/client/building_block_run_action.go deleted file mode 100644 index 4f11899d..00000000 --- a/client/building_block_run_action.go +++ /dev/null @@ -1,86 +0,0 @@ -package client - -import ( - "context" - "fmt" - "net/url" - - "github.com/meshcloud/meshstack-cli/client/http" - "github.com/meshcloud/meshstack-cli/client/internal" -) - -// Link is a HAL link. meshStack sends the link of an action only while the caller may take it. -type Link struct { - Href string `json:"href"` -} - -type MeshBuildingBlockRunLinks struct { - Predecessor *Link `json:"predecessor"` - DownloadLogs *Link `json:"downloadLogs"` - Approve *Link `json:"approve"` - Reject *Link `json:"reject"` - Abort *Link `json:"abort"` -} - -type MeshBuildingBlockV2Links struct { - LatestRun *Link `json:"latestRun"` - LatestDryRun *Link `json:"latestDryRun"` - MeshPanel *Link `json:"meshPanel"` -} - -type MeshBuildingBlockRunActionClient struct { - httpClient internal.HttpClient - run internal.MeshObjectApi -} - -func newBuildingBlockRunActionClient(httpClient internal.HttpClient, run meshBuildingBlockRunClient) *MeshBuildingBlockRunActionClient { - return &MeshBuildingBlockRunActionClient{httpClient: httpClient, run: run.meshObject.MeshObjectApi} -} - -func (c *MeshBuildingBlockRunActionClient) ReadRun(ctx context.Context, link Link) (MeshBuildingBlockRun, error) { - return c.doAtLink[MeshBuildingBlockRun](ctx, http.MethodGet, link) -} - -func (c *MeshBuildingBlockRunActionClient) ReadLogs(ctx context.Context, link Link) (MeshBuildingBlockRunLogs, error) { - return c.doAtLink[MeshBuildingBlockRunLogs](ctx, http.MethodGet, link) -} - -// ApproveRun takes the predecessor because meshStack replaces the plan of a run that waits for -// approval when the run is planned again. The predecessor names the plan that is approved. -func (c *MeshBuildingBlockRunActionClient) ApproveRun(ctx context.Context, approve Link, predecessorRunUuid string) error { - _, err := c.doAtLink[struct{}](ctx, http.MethodPost, approve, http.WithJsonRequest(struct { - PredecessorRunUuid string `json:"predecessorRunUuid"` - }{predecessorRunUuid}, c.run.MeshObjectMimeType())) - return err -} - -func (c *MeshBuildingBlockRunActionClient) RejectRun(ctx context.Context, reject Link) error { - return c.postWithoutBody(ctx, reject) -} - -func (c *MeshBuildingBlockRunActionClient) AbortRun(ctx context.Context, abort Link) error { - return c.postWithoutBody(ctx, abort) -} - -func (c *MeshBuildingBlockRunActionClient) postWithoutBody(ctx context.Context, link Link) error { - _, err := c.doAtLink[struct{}](ctx, http.MethodPost, link, http.WithContentType(c.run.MeshObjectMimeType())) - return err -} - -// doAtLink sends the request only below the endpoint, so that the bearer token never leaves for -// another host that a link names. -func (c *MeshBuildingBlockRunActionClient) doAtLink[R any](ctx context.Context, method string, link Link, options ...http.RequestOption) (R, error) { - var noResult R - href, err := url.Parse(link.Href) - if err != nil { - return noResult, fmt.Errorf("meshStack sent the link %q, which is no URL: %w", link.Href, err) - } - target := c.httpClient.EndpointUrl.ResolveReference(href) - path, isBelowEndpoint := c.httpClient.EndpointUrl.PathTo(target) - if !isBelowEndpoint { - return noResult, fmt.Errorf("meshStack sent the link %s, which is not below the endpoint %s", target.Redacted(), c.httpClient.EndpointUrl) - } - below := c.httpClient.EndpointUrl.JoinPath(path) - below.RawQuery = target.RawQuery - return http.UnmarshalJsonBody[R](c.httpClient.DoRequest(ctx, method, below, append(options, http.WithHeader("Accept", c.run.MeshObjectMimeType()))...)) -} diff --git a/client/building_block_run_action_test.go b/client/building_block_run_action_test.go deleted file mode 100644 index 1dfe5c56..00000000 --- a/client/building_block_run_action_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package client - -import ( - "encoding/json/jsontext" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/meshcloud/meshstack-cli/internal/testutil/fakemeshstack" -) - -func TestBuildingBlockRunActionClientSendsTheTokenOnlyBelowTheEndpoint(t *testing.T) { - const runUuid = "a0000000-0000-4000-8000-000000000001" - server := fakemeshstack.Start(t, fakemeshstack.Options{BuildingBlockRuns: []any{ - jsontext.Value(`{"metadata": {"uuid": "` + runUuid + `"}, "status": "IN_PROGRESS"}`), - }}) - httpClient := newTestHttpClient(server) - actions := newBuildingBlockRunActionClient(httpClient, newBuildingBlockRunClient(t.Context(), httpClient)) - - t.Run("a link below the endpoint is followed", func(t *testing.T) { - run, err := actions.ReadRun(t.Context(), Link{Href: server.URL + "/api/meshobjects/meshbuildingblockruns/" + runUuid}) - - require.NoError(t, err) - assert.Equal(t, runUuid, run.Metadata.Uuid) - server.TakeRequests() - }) - - t.Run("a link to another host is refused before anything is sent", func(t *testing.T) { - for _, href := range []string{"https://other.host/api/meshobjects/meshbuildingblockruns/" + runUuid, "//other.host/x"} { - err := actions.AbortRun(t.Context(), Link{Href: href}) - - require.ErrorContains(t, err, "which is not below the endpoint") - } - assert.Empty(t, server.TakeRequests()) - }) -} diff --git a/client/building_block_runner.go b/client/building_block_runner.go index d94ebac8..52e56e87 100644 --- a/client/building_block_runner.go +++ b/client/building_block_runner.go @@ -1,34 +1,19 @@ package client -import ( - "context" - "errors" - - "github.com/meshcloud/meshstack-cli/client/http" - "github.com/meshcloud/meshstack-cli/client/internal" -) +import "github.com/meshcloud/meshstack-cli/client/types/enum" type MeshBuildingBlockRunnerImplementationType string -// TODO Turn this into enum! -const ( - MeshBuildingBlockRunnerImplementationTypeTerraform MeshBuildingBlockRunnerImplementationType = "TERRAFORM" - MeshBuildingBlockRunnerImplementationTypeGithubWorkflow MeshBuildingBlockRunnerImplementationType = "GITHUB_WORKFLOW" - MeshBuildingBlockRunnerImplementationTypeGitlabPipeline MeshBuildingBlockRunnerImplementationType = "GITLAB_PIPELINE" - MeshBuildingBlockRunnerImplementationTypeAzureDevopsPipeline MeshBuildingBlockRunnerImplementationType = "AZURE_DEVOPS_PIPELINE" - MeshBuildingBlockRunnerImplementationTypeManual MeshBuildingBlockRunnerImplementationType = "MANUAL" - MeshBuildingBlockRunnerImplementationTypeAll MeshBuildingBlockRunnerImplementationType = "ALL" +var ( + MeshBuildingBlockRunnerImplementationTypes = enum.Enum[MeshBuildingBlockRunnerImplementationType]{} + MeshBuildingBlockRunnerImplementationTypeTerraform = MeshBuildingBlockRunnerImplementationTypes.Entry("TERRAFORM") + MeshBuildingBlockRunnerImplementationTypeGithubWorkflow = MeshBuildingBlockRunnerImplementationTypes.Entry("GITHUB_WORKFLOW") + MeshBuildingBlockRunnerImplementationTypeGitlabPipeline = MeshBuildingBlockRunnerImplementationTypes.Entry("GITLAB_PIPELINE") + MeshBuildingBlockRunnerImplementationTypeAzureDevopsPipeline = MeshBuildingBlockRunnerImplementationTypes.Entry("AZURE_DEVOPS_PIPELINE") + MeshBuildingBlockRunnerImplementationTypeManual = MeshBuildingBlockRunnerImplementationTypes.Entry("MANUAL") + MeshBuildingBlockRunnerImplementationTypeAll = MeshBuildingBlockRunnerImplementationTypes.Entry("ALL") ) -var MeshBuildingBlockRunnerImplementationTypes = []string{ - string(MeshBuildingBlockRunnerImplementationTypeTerraform), - string(MeshBuildingBlockRunnerImplementationTypeGithubWorkflow), - string(MeshBuildingBlockRunnerImplementationTypeGitlabPipeline), - string(MeshBuildingBlockRunnerImplementationTypeAzureDevopsPipeline), - string(MeshBuildingBlockRunnerImplementationTypeManual), - string(MeshBuildingBlockRunnerImplementationTypeAll), -} - type MeshBuildingBlockRunner struct { Metadata MeshBuildingBlockRunnerMetadata `json:"metadata" tfsdk:"metadata"` Spec MeshBuildingBlockRunnerSpec `json:"spec" tfsdk:"spec"` @@ -49,12 +34,12 @@ type MeshBuildingBlockRunnerStatus struct { } type MeshBuildingBlockRunnerSpec struct { - DisplayName string `json:"displayName" tfsdk:"display_name"` - PublicKey string `json:"publicKey" tfsdk:"public_key"` - ImplementationType string `json:"implementationType" tfsdk:"implementation_type"` - Restriction *string `json:"restriction,omitzero" tfsdk:"restriction"` - IsSelfHosted *bool `json:"isSelfHosted,omitzero" tfsdk:"is_self_hosted"` - WorkloadIdentityFederation *MeshRunnerWorkloadIdentityFed `json:"workloadIdentityFederation,omitzero" tfsdk:"workload_identity_federation"` + DisplayName string `json:"displayName" tfsdk:"display_name"` + PublicKey string `json:"publicKey" tfsdk:"public_key"` + ImplementationType enum.Entry[MeshBuildingBlockRunnerImplementationType] `json:"implementationType" tfsdk:"implementation_type"` + Restriction *string `json:"restriction,omitzero" tfsdk:"restriction"` + IsSelfHosted *bool `json:"isSelfHosted,omitzero" tfsdk:"is_self_hosted"` + WorkloadIdentityFederation *MeshRunnerWorkloadIdentityFed `json:"workloadIdentityFederation,omitzero" tfsdk:"workload_identity_federation"` } type MeshRunnerWorkloadIdentityFed struct { @@ -71,47 +56,13 @@ type MeshRunnerWifProviderConfig struct { TokenPath string `json:"tokenPath" tfsdk:"token_path"` } -type MeshBuildingBlockRunnerClient interface { - Create(ctx context.Context, runner MeshBuildingBlockRunner) (*MeshBuildingBlockRunner, error) - Read(ctx context.Context, uuid string) (*MeshBuildingBlockRunner, error) - List(ctx context.Context, filter MeshBuildingBlockRunnerFilter) ([]MeshBuildingBlockRunner, error) - Update(ctx context.Context, runner MeshBuildingBlockRunner) (*MeshBuildingBlockRunner, error) - Delete(ctx context.Context, uuid string) error -} +type MeshBuildingBlockRunnerClient = MeshObjectClient[MeshBuildingBlockRunner, MeshBuildingBlockRunnerFilter] type MeshBuildingBlockRunnerFilter struct { WorkspaceIdentifier *string `json:"workspaceIdentifier"` IsDefault *bool `json:"isDefault"` } -type meshBuildingBlockRunnerClient struct { - meshObject internal.MeshObjectClient[MeshBuildingBlockRunner] -} - -func newBuildingBlockRunnerClient(ctx context.Context, httpClient internal.HttpClient) MeshBuildingBlockRunnerClient { - return meshBuildingBlockRunnerClient{internal.NewMeshObjectClient[MeshBuildingBlockRunner](ctx, httpClient, "v1-preview")} -} - -func (c meshBuildingBlockRunnerClient) Create(ctx context.Context, runner MeshBuildingBlockRunner) (*MeshBuildingBlockRunner, error) { - return c.meshObject.Post(ctx, runner) -} - -func (c meshBuildingBlockRunnerClient) Read(ctx context.Context, uuid string) (*MeshBuildingBlockRunner, error) { - return c.meshObject.Get(ctx, uuid) -} - -func (c meshBuildingBlockRunnerClient) List(ctx context.Context, filter MeshBuildingBlockRunnerFilter) ([]MeshBuildingBlockRunner, error) { - return c.meshObject.List(ctx, http.WithUrlQuery(filter)) -} - -func (c meshBuildingBlockRunnerClient) Update(ctx context.Context, runner MeshBuildingBlockRunner) (*MeshBuildingBlockRunner, error) { - if runner.Metadata.Uuid == nil || *runner.Metadata.Uuid == "" { - return nil, errors.New("missing metadata.uuid") - } - - return c.meshObject.Put(ctx, *runner.Metadata.Uuid, runner) -} - -func (c meshBuildingBlockRunnerClient) Delete(ctx context.Context, uuid string) error { - return c.meshObject.Delete(ctx, uuid) +func (runner MeshBuildingBlockRunner) meshObjectId() string { + return *runner.Metadata.Uuid } diff --git a/client/building_block_v2.go b/client/building_block_v2.go index 77283335..acc74134 100644 --- a/client/building_block_v2.go +++ b/client/building_block_v2.go @@ -7,21 +7,13 @@ import ( "fmt" "slices" - "github.com/meshcloud/meshstack-cli/client/http" - "github.com/meshcloud/meshstack-cli/client/internal" "github.com/meshcloud/meshstack-cli/client/types" "github.com/meshcloud/meshstack-cli/client/types/enum" + "github.com/meshcloud/meshstack-cli/client/types/hal" "github.com/meshcloud/meshstack-cli/internal/json" ) -type BuildingBlockLifecycleState string - -var ( - BuildingBlockLifecycleStates = enum.Enum[BuildingBlockLifecycleState]{} - BuildingBlockLifecycleStateActive = BuildingBlockLifecycleStates.Entry("ACTIVE") - BuildingBlockLifecycleStateMarkedForDeletion = BuildingBlockLifecycleStates.Entry("MARKED_FOR_DELETION") - BuildingBlockLifecycleStateDeleted = BuildingBlockLifecycleStates.Entry("DELETED") -) +const buildingBlockV2ApiVersion = "v2" type BuildingBlockHealthStatus string @@ -49,16 +41,14 @@ var ( BuildingBlockActionNoAction = BuildingBlockActions.Entry("NO_ACTION") ) +type MeshBuildingBlockV2Metadata = MeshObjectByUuidMetadata + +//nolint:recvcheck // a nil block is one that is gone, and meshObjectId reads one that is there type MeshBuildingBlockV2 struct { Metadata MeshBuildingBlockV2Metadata `json:"metadata" tfsdk:"metadata"` Spec MeshBuildingBlockV2Spec `json:"spec" tfsdk:"spec"` Status *MeshBuildingBlockV2Status `json:"status" tfsdk:"status"` - Links MeshBuildingBlockV2Links `json:"_links,omitzero" tfsdk:"-"` -} - -type MeshBuildingBlockV2Metadata struct { - Uuid *string `json:"uuid" tfsdk:"uuid"` - OwnedByWorkspace string `json:"ownedByWorkspace" tfsdk:"owned_by_workspace"` + Links hal.Links `json:"_links,omitzero" tfsdk:"-"` } type MeshBuildingBlockV2Spec struct { @@ -75,6 +65,7 @@ type MeshBuildingBlockInput struct { Value types.SecretOrAny `json:"value" tfsdk:"value"` ValueType *enum.Entry[MeshBuildingBlockIOType] `json:"valueType,omitzero" tfsdk:"-"` AssignmentType enum.Entry[MeshBuildingBlockInputAssignmentType] `json:"assignmentType,omitempty" tfsdk:"-"` + IsOptional bool `json:"isOptional" tfsdk:"-"` UpdateableByConsumer *bool `json:"updateableByConsumer,omitzero" tfsdk:"-"` @@ -122,12 +113,8 @@ type MeshBuildingBlockV2DefinitionVersionRef struct { type MeshBuildingBlockV2TargetRef struct { Kind string `json:"kind" tfsdk:"kind"` - Uuid *string `json:"uuid" tfsdk:"uuid"` - Name *string `json:"name" tfsdk:"name"` -} - -type MeshBuildingBlockV2Lifecycle struct { - State enum.Entry[BuildingBlockLifecycleState] `json:"state" tfsdk:"state"` + Uuid *string `json:"uuid,omitzero" tfsdk:"uuid"` + Name *string `json:"name,omitzero" tfsdk:"name"` } type MeshBuildingBlockV2Status struct { @@ -135,7 +122,7 @@ type MeshBuildingBlockV2Status struct { Action enum.Entry[BuildingBlockAction] `json:"action" tfsdk:"action"` Outputs map[string]MeshBuildingBlockOutput `json:"outputs" tfsdk:"outputs"` ForcePurge bool `json:"forcePurge" tfsdk:"force_purge"` - Lifecycle MeshBuildingBlockV2Lifecycle `json:"lifecycle" tfsdk:"-"` + Lifecycle MeshLifecycle `json:"lifecycle" tfsdk:"-"` // LatestRunUuid tracks the latest *modifying* (apply/destroy) run and excludes dry runs. It is nil // only when no such run exists: run_transparency gates reading the run and its system messages, not // this identifier (MeshBuildingBlockV2RepresentationModelAssembler.resolveLatestRunUuid). @@ -173,11 +160,11 @@ type MeshBuildingBlockOutput struct { AssignmentType enum.Entry[MeshBuildingBlockDefinitionOutputAssignmentType] `json:"assignmentType" tfsdk:"assignment_type"` } -// MeshBuildingBlockV2ListFilter never matches a soft-deleted building block: the endpoint lists +// MeshBuildingBlockV2Filter never matches a soft-deleted building block: the endpoint lists // only active ones. The json tags are the query parameter names and must match the @RequestParam // names of fetchBuildingBlocksV2 in the meshStack backend, which ignores an unknown parameter, so // a typo turns the filter off without an error. -type MeshBuildingBlockV2ListFilter struct { +type MeshBuildingBlockV2Filter struct { WorkspaceIdentifier *string `json:"workspaceIdentifier"` ProjectIdentifier *string `json:"projectIdentifier"` PlatformIdentifier *string `json:"platformIdentifier"` @@ -195,59 +182,22 @@ type MeshBuildingBlockV2ListFilter struct { Action []string `json:"action"` // ManagedByWorkspaceIdentifier and ManagedByDefinitionUuid list the building blocks of the // definitions a platform operator owns, and need the MANAGED_BUILDINGBLOCK_LIST permission. - ManagedByWorkspaceIdentifier *string `json:"managedByWorkspaceIdentifier"` - ManagedByDefinitionUuid *string `json:"managedByDefinitionUuid"` - Sort SortCriteria `json:"sort"` -} - -type MeshBuildingBlockV2Client interface { - Read(ctx context.Context, uuid string) (*MeshBuildingBlockV2, error) - ReadFunc(uuid string) func(ctx context.Context) (*MeshBuildingBlockV2, error) - List(ctx context.Context, filter MeshBuildingBlockV2ListFilter) ([]MeshBuildingBlockV2, error) - Create(ctx context.Context, bb *MeshBuildingBlockV2) (*MeshBuildingBlockV2, error) - Update(ctx context.Context, bb *MeshBuildingBlockV2) (*MeshBuildingBlockV2, error) - Delete(ctx context.Context, uuid string, purge bool) error - TriggerRun(ctx context.Context, uuid string) (*MeshBuildingBlockV2, error) -} - -type meshBuildingBlockV2Client struct { - meshObject internal.MeshObjectClient[MeshBuildingBlockV2] -} - -func newBuildingBlockV2Client(ctx context.Context, httpClient internal.HttpClient) meshBuildingBlockV2Client { - return meshBuildingBlockV2Client{internal.NewMeshObjectClient[MeshBuildingBlockV2](ctx, httpClient, "v2")} + ManagedByWorkspaceIdentifier *string `json:"managedByWorkspaceIdentifier"` + ManagedByDefinitionUuid *string `json:"managedByDefinitionUuid"` } -func (c meshBuildingBlockV2Client) Read(ctx context.Context, uuid string) (*MeshBuildingBlockV2, error) { - return c.ReadFunc(uuid)(ctx) -} +type MeshBuildingBlockV2Client = MeshObjectClient[MeshBuildingBlockV2, MeshBuildingBlockV2Filter] -func (c meshBuildingBlockV2Client) ReadFunc(uuid string) func(ctx context.Context) (*MeshBuildingBlockV2, error) { - return func(ctx context.Context) (*MeshBuildingBlockV2, error) { - return c.meshObject.Get(ctx, uuid) - } +type MeshBuildingBlockV2RunTrigger struct { + DryRun bool `json:"dryRun"` } -func (c meshBuildingBlockV2Client) List(ctx context.Context, filter MeshBuildingBlockV2ListFilter) ([]MeshBuildingBlockV2, error) { - return c.meshObject.List(ctx, http.WithUrlQuery(filter)) +func (bb MeshBuildingBlockV2) TriggerRun(ctx context.Context) (MeshBuildingBlockV2, error) { + return bb.Links.Post[MeshBuildingBlockV2](ctx, "triggerRun", MeshBuildingBlockV2RunTrigger{}) } -func (c meshBuildingBlockV2Client) Create(ctx context.Context, bb *MeshBuildingBlockV2) (*MeshBuildingBlockV2, error) { - return c.meshObject.Post(ctx, bb) -} - -func (c meshBuildingBlockV2Client) Update(ctx context.Context, bb *MeshBuildingBlockV2) (*MeshBuildingBlockV2, error) { - if bb.Metadata.Uuid == nil { - return nil, errors.New("cannot update building block without UUID") - } - return c.meshObject.Put(ctx, *bb.Metadata.Uuid, bb) -} - -func (c meshBuildingBlockV2Client) Delete(ctx context.Context, uuid string, purge bool) error { - if purge { - return c.meshObject.DeleteAtPath(ctx, uuid, "purge") - } - return c.meshObject.Delete(ctx, uuid) +func (bb MeshBuildingBlockV2) Purge(ctx context.Context) error { + return bb.Links.Delete(ctx, "forcePurge") } var ( @@ -316,7 +266,7 @@ func (bb *MeshBuildingBlockV2) DeletionSuccessful(before MeshBuildingBlockV2Stat case bb == nil: // A 404: the block is gone, for example together with its definition. done = true - case bb.Status != nil && bb.Status.Lifecycle.State == BuildingBlockLifecycleStateDeleted: + case bb.Status != nil && bb.Status.Lifecycle.State == MeshLifecycleStateDeleted: // 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 @@ -332,12 +282,8 @@ func (bb *MeshBuildingBlockV2) DeletionSuccessful(before MeshBuildingBlockV2Stat return } -// MeshPanelLink is "" for a block read from a meshStack that sends no meshPanel link. -func (bb *MeshBuildingBlockV2) MeshPanelLink() string { - if bb == nil || bb.Links.MeshPanel == nil { - return "" - } - return bb.Links.MeshPanel.Href +func (bb MeshBuildingBlockV2) meshObjectId() string { + return bb.Metadata.meshObjectId() } func (bb *MeshBuildingBlockV2) uuidOrUnknown() string { @@ -346,14 +292,3 @@ func (bb *MeshBuildingBlockV2) uuidOrUnknown() string { } return "" } - -// TriggerRun answers with the building block as meshStack left it on accepting the run: Action, -// LatestRunUuid, RunStartFailure and RunStartFailedOn still report the request before, because -// meshStack starts the run, or records why it could not, only after it answered. -func (c meshBuildingBlockV2Client) TriggerRun(ctx context.Context, bbUuid string) (*MeshBuildingBlockV2, error) { - // dryRun is not optional to the endpoint once a body is sent, so it goes out as false rather - // than being omitted. - return c.meshObject.PostAtPath[*MeshBuildingBlockV2](ctx, struct { - DryRun bool `json:"dryRun"` - }{}, bbUuid, "trigger-run") -} diff --git a/client/building_block_v2_test.go b/client/building_block_v2_test.go index 96663228..49eba793 100644 --- a/client/building_block_v2_test.go +++ b/client/building_block_v2_test.go @@ -108,65 +108,3 @@ func TestMeshBuildingBlockV2_RunEndedSince(t *testing.T) { require.Error(t, err) }) } - -func TestMeshBuildingBlockV2_DeletionSuccessful(t *testing.T) { - before := MeshBuildingBlockV2Status{Action: BuildingBlockActionReviewErrors, LatestRunUuid: new("apply-run")} - deleteRun := func(action enum.Entry[BuildingBlockAction]) *MeshBuildingBlockV2 { - return &MeshBuildingBlockV2{ - Metadata: MeshBuildingBlockV2Metadata{Uuid: new("test-uuid")}, - Status: &MeshBuildingBlockV2Status{Action: action, LatestRunUuid: new("delete-run")}, - } - } - tests := []struct { - name string - bb *MeshBuildingBlockV2 - wantDone bool - wantErr string - }{ - {name: "a block that is gone (404, hard deletion or purge) is deleted", bb: nil, wantDone: true}, - { - name: "a soft-deleted block is deleted", - bb: &MeshBuildingBlockV2{Status: &MeshBuildingBlockV2Status{Lifecycle: MeshBuildingBlockV2Lifecycle{State: BuildingBlockLifecycleStateDeleted}}}, - wantDone: true, - }, - { - name: "REVIEW_ERRORS of the run before the deletion goes on", - bb: &MeshBuildingBlockV2{Status: &MeshBuildingBlockV2Status{Action: BuildingBlockActionReviewErrors, LatestRunUuid: new("apply-run")}}, - }, - {name: "a delete run in progress goes on", bb: deleteRun(BuildingBlockActionInProgress)}, - {name: "a failed delete run fails", bb: deleteRun(BuildingBlockActionReviewErrors), wantErr: "the delete run of building block test-uuid ended with action REVIEW_ERRORS"}, - {name: "an aborted delete run fails", bb: deleteRun(BuildingBlockActionReviewAbortedRun), wantErr: "ended with action REVIEW_ABORTED_RUN"}, - { - name: "a delete run that could not start fails", - bb: &MeshBuildingBlockV2{Status: &MeshBuildingBlockV2Status{ - Action: BuildingBlockActionReviewErrors, LatestRunUuid: new("apply-run"), RunStartFailedOn: "2026-10-28T12:00:00Z", - }}, - wantErr: "ended with action REVIEW_ERRORS", - }, - {name: "a delete run that waits for approval fails at once", bb: deleteRun(BuildingBlockActionApproveRun), wantErr: "waits with action APPROVE_RUN"}, - {name: "a delete run that waits for a dependency fails at once", bb: deleteRun(BuildingBlockActionWaitingForDependency), wantErr: "waits with action WAITING_FOR_DEPENDENCY"}, - { - name: "a failed delete run of a force-purged block goes on, as the purge still reaches DELETED", - bb: &MeshBuildingBlockV2{Status: &MeshBuildingBlockV2Status{ - Action: BuildingBlockActionReviewErrors, LatestRunUuid: new("delete-run"), ForcePurge: true, - }}, - }, - { - name: "a failed delete run of a block without a uuid names it unknown", - bb: &MeshBuildingBlockV2{Status: &MeshBuildingBlockV2Status{Action: BuildingBlockActionReviewErrors, LatestRunUuid: new("delete-run")}}, - wantErr: "", - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - done, err := tt.bb.DeletionSuccessful(before) - assert.Equal(t, tt.wantDone, done) - if tt.wantErr == "" { - assert.NoError(t, err) - } else { - require.Error(t, err) - assert.Contains(t, err.Error(), tt.wantErr) - } - }) - } -} diff --git a/client/client.go b/client/client.go index 8a265544..1e31bde2 100644 --- a/client/client.go +++ b/client/client.go @@ -4,7 +4,6 @@ import ( "context" "github.com/meshcloud/meshstack-cli/client/http" - "github.com/meshcloud/meshstack-cli/client/internal" "github.com/meshcloud/meshstack-cli/client/types/version" "github.com/meshcloud/meshstack-cli/client/types/xurl" ) @@ -15,16 +14,14 @@ type Version = version.Version type HttpError = http.Error -type Authorization = http.Authorization - type Client struct { ApiKey MeshApiKeyClient BuildingBlockV2 MeshBuildingBlockV2Client BuildingBlockRun MeshBuildingBlockRunClient - BuildingBlockRunAction *MeshBuildingBlockRunActionClient BuildingBlockDefinition MeshBuildingBlockDefinitionClient BuildingBlockDefinitionVersion MeshBuildingBlockDefinitionVersionClient BuildingBlockRunner MeshBuildingBlockRunnerClient + EventLog MeshEventLogClient Integration MeshIntegrationClient LandingZone MeshLandingZoneClient Location MeshLocationClient @@ -43,56 +40,43 @@ type Client struct { WorkspaceGroupBinding MeshWorkspaceGroupBindingClient WorkspaceUserBinding MeshWorkspaceUserBindingClient WorkspaceUserGroup MeshWorkspaceUserGroupClient - Raw *RawClient // Endpoint is read by the Terraform provider's meshstack_instance data source. Endpoint xurl.URL + // HttpClient sends the bearer token to any host, so join its path onto Endpoint. + HttpClient http.AuthorizedClient } -func New(ctx context.Context, endpoint xurl.URL, client http.Client, auth Authorization) Client { - authorizedClient := internal.HttpClient{ - AuthorizedClient: client.WithAuthorization(auth), - EndpointUrl: endpoint, - } - buildingBlockV2 := newBuildingBlockV2Client(ctx, authorizedClient) - buildingBlockDefinition := newBuildingBlockDefinitionClient(ctx, authorizedClient) - buildingBlockDefinitionVersion := newBuildingBlockDefinitionVersionClient(ctx, authorizedClient) - buildingBlockRun := newBuildingBlockRunClient(ctx, authorizedClient) - workspace := newWorkspaceClient(ctx, authorizedClient) +func New(ctx context.Context, endpoint xurl.URL, client http.Client, auth http.Authorization) Client { + c := client.WithAuthorization(auth) return Client{ - ApiKey: newApiKeyClient(ctx, authorizedClient), - BuildingBlockV2: buildingBlockV2, - BuildingBlockRun: buildingBlockRun, - BuildingBlockRunAction: newBuildingBlockRunActionClient(authorizedClient, buildingBlockRun), - BuildingBlockDefinition: buildingBlockDefinition, - BuildingBlockDefinitionVersion: buildingBlockDefinitionVersion, - BuildingBlockRunner: newBuildingBlockRunnerClient(ctx, authorizedClient), - Integration: newIntegrationClient(ctx, authorizedClient), - LandingZone: newLandingZoneClient(ctx, authorizedClient), - Location: newLocationClient(ctx, authorizedClient), + 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"), + 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"), + EventLog: newMeshObjectClient[MeshEventLog, MeshEventLogFilter](ctx, c, endpoint, "v1"), + Integration: newMeshObjectClient[MeshIntegration, NoFilter](ctx, c, endpoint, "v1"), + LandingZone: newMeshObjectClient[MeshLandingZone, MeshLandingZoneFilter](ctx, c, endpoint, "v1"), + Location: newMeshObjectClient[MeshLocation, NoFilter](ctx, c, endpoint, "v1"), MeshInfo: NewMeshInfoClient(client, endpoint), - PaymentMethod: newPaymentMethodClient(ctx, authorizedClient), - Platform: newPlatformClient(ctx, authorizedClient), - PlatformType: newPlatformTypeClient(ctx, authorizedClient), - Project: newProjectClient(ctx, authorizedClient), - ProjectGroupBinding: newProjectGroupBindingClient(ctx, authorizedClient), - ProjectUserBinding: newProjectUserBindingClient(ctx, authorizedClient), - ServiceInstance: newServiceInstanceClient(ctx, authorizedClient), - TagDefinition: newTagDefinitionClient(ctx, authorizedClient), - Tenant: newTenantClient(ctx, authorizedClient), - User: newUserClient(ctx, authorizedClient), - Workspace: workspace, - WorkspaceGroupBinding: newWorkspaceGroupBindingClient(ctx, authorizedClient), - WorkspaceUserBinding: newWorkspaceUserBindingClient(ctx, authorizedClient), - WorkspaceUserGroup: newWorkspaceUserGroupClient(ctx, authorizedClient), - Raw: newRawClient(authorizedClient). - with(workspace.meshObject). - with(buildingBlockV2.meshObject). - with(buildingBlockRun.meshObject). - with(buildingBlockDefinition.meshObject). - withOwnOrder(buildingBlockDefinitionVersion.meshObject). - with(newEventLogMeshObject(ctx, authorizedClient)), + PaymentMethod: newMeshObjectClient[MeshPaymentMethod, NoFilter](ctx, c, endpoint, "v2"), + Platform: newMeshObjectClient[MeshPlatform, MeshPlatformFilter](ctx, c, endpoint, "v2"), + PlatformType: newMeshObjectClient[MeshPlatformType, MeshPlatformTypeFilter](ctx, c, endpoint, "v1"), + Project: newMeshObjectClient[MeshProject, MeshProjectFilter](ctx, c, endpoint, "v2"), + ProjectGroupBinding: newMeshObjectClient[MeshProjectGroupBinding, MeshProjectBindingFilter](ctx, c, endpoint, "v3"), + ProjectUserBinding: newMeshObjectClient[MeshProjectUserBinding, MeshProjectBindingFilter](ctx, c, endpoint, "v3"), + ServiceInstance: newMeshObjectClient[MeshServiceInstance, MeshServiceInstanceFilter](ctx, c, endpoint, "v2"), + TagDefinition: newMeshObjectClient[MeshTagDefinition, NoFilter](ctx, c, endpoint, "v1"), + Tenant: newMeshObjectClient[MeshTenant, MeshTenantFilter](ctx, c, endpoint, "v4"), + User: newMeshObjectClient[MeshUser, MeshUserFilter](ctx, c, endpoint, "v2"), + Workspace: newMeshObjectClient[MeshWorkspace, NoFilter](ctx, c, endpoint, "v2"), + WorkspaceGroupBinding: newMeshObjectClient[MeshWorkspaceGroupBinding, MeshWorkspaceBindingFilter](ctx, c, endpoint, "v2"), + WorkspaceUserBinding: newMeshObjectClient[MeshWorkspaceUserBinding, MeshWorkspaceBindingFilter](ctx, c, endpoint, "v2"), + WorkspaceUserGroup: newMeshObjectClient[MeshWorkspaceUserGroup, MeshWorkspaceUserGroupFilter](ctx, c, endpoint, "v1"), - Endpoint: endpoint, + Endpoint: endpoint, + HttpClient: c, } } diff --git a/client/client_kind_test.go b/client/client_kind_test.go index ef1ea4db..cb6f7f23 100644 --- a/client/client_kind_test.go +++ b/client/client_kind_test.go @@ -4,31 +4,29 @@ import ( "testing" "github.com/stretchr/testify/assert" - - "github.com/meshcloud/meshstack-cli/client/internal" ) func TestKind(t *testing.T) { - assert.Equal(t, internal.InferKind[MeshApiKey](), MeshObjectKind.ApiKey) - assert.Equal(t, internal.InferKind[MeshBuildingBlockV2](), MeshObjectKind.BuildingBlock) - assert.Equal(t, internal.InferKind[MeshBuildingBlockDefinition](), MeshObjectKind.BuildingBlockDefinition) - assert.Equal(t, internal.InferKind[MeshBuildingBlockDefinitionVersion](), MeshObjectKind.BuildingBlockDefinitionVersion) - assert.Equal(t, internal.InferKind[MeshEventLog](), MeshObjectKind.EventLog) - assert.Equal(t, internal.InferKind[MeshIntegration](), MeshObjectKind.Integration) - assert.Equal(t, internal.InferKind[MeshLandingZone](), MeshObjectKind.LandingZone) - assert.Equal(t, internal.InferKind[MeshLocation](), MeshObjectKind.Location) - assert.Equal(t, internal.InferKind[MeshPaymentMethod](), MeshObjectKind.PaymentMethod) - assert.Equal(t, internal.InferKind[MeshPlatform](), MeshObjectKind.Platform) - assert.Equal(t, internal.InferKind[MeshPlatformType](), MeshObjectKind.PlatformType) - assert.Equal(t, internal.InferKind[MeshProject](), MeshObjectKind.Project) - assert.Equal(t, internal.InferKind[MeshProjectGroupBinding](), MeshObjectKind.ProjectGroupBinding) - assert.Equal(t, internal.InferKind[MeshProjectUserBinding](), MeshObjectKind.ProjectUserBinding) - assert.Equal(t, internal.InferKind[MeshServiceInstance](), MeshObjectKind.ServiceInstance) - assert.Equal(t, internal.InferKind[MeshTagDefinition](), MeshObjectKind.TagDefinition) - assert.Equal(t, internal.InferKind[MeshTenant](), MeshObjectKind.Tenant) - assert.Equal(t, internal.InferKind[MeshUser](), MeshObjectKind.User) - assert.Equal(t, internal.InferKind[MeshWorkspace](), MeshObjectKind.Workspace) - assert.Equal(t, internal.InferKind[MeshWorkspaceGroupBinding](), MeshObjectKind.WorkspaceGroupBinding) - assert.Equal(t, internal.InferKind[MeshWorkspaceUserBinding](), MeshObjectKind.WorkspaceUserBinding) - assert.Equal(t, internal.InferKind[MeshWorkspaceUserGroup](), MeshObjectKind.WorkspaceUserGroup) + assert.Equal(t, inferKind[MeshApiKey](), MeshObjectKind.ApiKey) + assert.Equal(t, inferKind[MeshBuildingBlockV2](), MeshObjectKind.BuildingBlock) + assert.Equal(t, inferKind[MeshBuildingBlockDefinition](), MeshObjectKind.BuildingBlockDefinition) + assert.Equal(t, inferKind[MeshBuildingBlockDefinitionVersion](), MeshObjectKind.BuildingBlockDefinitionVersion) + assert.Equal(t, inferKind[MeshEventLog](), MeshObjectKind.EventLog) + assert.Equal(t, inferKind[MeshIntegration](), MeshObjectKind.Integration) + assert.Equal(t, inferKind[MeshLandingZone](), MeshObjectKind.LandingZone) + assert.Equal(t, inferKind[MeshLocation](), MeshObjectKind.Location) + assert.Equal(t, inferKind[MeshPaymentMethod](), MeshObjectKind.PaymentMethod) + assert.Equal(t, inferKind[MeshPlatform](), MeshObjectKind.Platform) + assert.Equal(t, inferKind[MeshPlatformType](), MeshObjectKind.PlatformType) + assert.Equal(t, inferKind[MeshProject](), MeshObjectKind.Project) + assert.Equal(t, inferKind[MeshProjectGroupBinding](), MeshObjectKind.ProjectGroupBinding) + assert.Equal(t, inferKind[MeshProjectUserBinding](), MeshObjectKind.ProjectUserBinding) + assert.Equal(t, inferKind[MeshServiceInstance](), MeshObjectKind.ServiceInstance) + assert.Equal(t, inferKind[MeshTagDefinition](), MeshObjectKind.TagDefinition) + assert.Equal(t, inferKind[MeshTenant](), MeshObjectKind.Tenant) + assert.Equal(t, inferKind[MeshUser](), MeshObjectKind.User) + assert.Equal(t, inferKind[MeshWorkspace](), MeshObjectKind.Workspace) + assert.Equal(t, inferKind[MeshWorkspaceGroupBinding](), MeshObjectKind.WorkspaceGroupBinding) + assert.Equal(t, inferKind[MeshWorkspaceUserBinding](), MeshObjectKind.WorkspaceUserBinding) + assert.Equal(t, inferKind[MeshWorkspaceUserGroup](), MeshObjectKind.WorkspaceUserGroup) } diff --git a/client/event_log.go b/client/event_log.go index 038635e2..6478d469 100644 --- a/client/event_log.go +++ b/client/event_log.go @@ -1,21 +1,21 @@ package client import ( - "context" "encoding/json/jsontext" "time" - "github.com/meshcloud/meshstack-cli/client/internal" + "github.com/meshcloud/meshstack-cli/client/types/hal" ) type MeshEventLog struct { Metadata MeshEventLogMetadata `json:"metadata"` Spec MeshEventLogSpec `json:"spec"` Status MeshEventLogStatus `json:"status"` + Links hal.Links `json:"_links,omitzero"` } type MeshEventLogMetadata struct { - Uuid string `json:"uuid"` + Uuid *string `json:"uuid"` } type MeshEventLogSpec struct { @@ -42,22 +42,11 @@ type MeshEventLogStatus struct { } type MeshEventLogCreated struct { - Timestamp time.Time `json:"timestamp"` - Author *MeshEventLogAuthor `json:"author"` + Timestamp time.Time `json:"timestamp"` + Author *MeshObjectAuthor `json:"author"` } -type MeshEventLogAuthor struct { - // Type is one of ApiKey, ApiUser, System and User, and decides what Identifier is: the uuid of - // the meshApiKey, the name of the API user, "system", or the uuid of the meshUser. - Type string `json:"type"` - Identifier string `json:"identifier"` - DisplayName *string `json:"displayName"` - Username *string `json:"username"` - Email *string `json:"email"` - Euid *string `json:"euid"` -} - -type MeshEventLogListFilter struct { +type MeshEventLogFilter struct { From time.Time `json:"from,omitzero"` Until time.Time `json:"until,omitzero"` Title string `json:"title"` @@ -69,11 +58,12 @@ type MeshEventLogListFilter struct { AuthorIdentifier string `json:"authorIdentifier"` // WorkspaceIdentifier and WorkspaceName, which matches part of the display name, exclude // each other. - WorkspaceIdentifier string `json:"workspaceIdentifier"` - WorkspaceName string `json:"workspaceName"` - Sort SortCriteria `json:"sort"` + WorkspaceIdentifier string `json:"workspaceIdentifier"` + WorkspaceName string `json:"workspaceName"` } -func newEventLogMeshObject(ctx context.Context, httpClient internal.HttpClient) internal.MeshObjectClient[MeshEventLog] { - return internal.NewMeshObjectClient[MeshEventLog](ctx, httpClient, "v1") +type MeshEventLogClient = MeshObjectReadOnlyClient[MeshEventLog, MeshEventLogFilter] + +func (log MeshEventLog) meshObjectId() string { + return *log.Metadata.Uuid } diff --git a/client/integration.go b/client/integration.go index 582a224f..685bd7c8 100644 --- a/client/integration.go +++ b/client/integration.go @@ -1,20 +1,15 @@ package client -import ( - "context" - - "github.com/meshcloud/meshstack-cli/client/internal" -) +type MeshIntegrationMetadata = MeshObjectByUuidMetadata type MeshIntegration struct { Metadata MeshIntegrationMetadata `json:"metadata" tfsdk:"metadata"` Spec MeshIntegrationSpec `json:"spec" tfsdk:"spec"` - Status *MeshIntegrationStatus `json:"status" tfsdk:"status"` + Status *MeshIntegrationStatus `json:"status,omitzero" tfsdk:"status"` } -type MeshIntegrationMetadata struct { - Uuid *string `json:"uuid,omitzero" tfsdk:"uuid"` - OwnedByWorkspace string `json:"ownedByWorkspace" tfsdk:"owned_by_workspace"` +func (i MeshIntegration) meshObjectId() string { + return i.Metadata.meshObjectId() } type MeshIntegrationSpec struct { @@ -44,38 +39,4 @@ type MeshAwsWifProvider struct { Thumbprint string `json:"thumbprint" tfsdk:"thumbprint"` } -type MeshIntegrationClient interface { - Create(ctx context.Context, integration MeshIntegration) (*MeshIntegration, error) - Read(ctx context.Context, uuid string) (*MeshIntegration, error) - Update(ctx context.Context, integration MeshIntegration) (*MeshIntegration, error) - Delete(ctx context.Context, uuid string) error - List(ctx context.Context) ([]MeshIntegration, error) -} - -type meshIntegrationClientImpl struct { - meshObject internal.MeshObjectClient[MeshIntegration] -} - -func newIntegrationClient(ctx context.Context, httpClient internal.HttpClient) MeshIntegrationClient { - return meshIntegrationClientImpl{internal.NewMeshObjectClient[MeshIntegration](ctx, httpClient, "v1")} -} - -func (c meshIntegrationClientImpl) Create(ctx context.Context, integration MeshIntegration) (*MeshIntegration, error) { - return c.meshObject.Post(ctx, integration) -} - -func (c meshIntegrationClientImpl) Read(ctx context.Context, uuid string) (*MeshIntegration, error) { - return c.meshObject.Get(ctx, uuid) -} - -func (c meshIntegrationClientImpl) Update(ctx context.Context, integration MeshIntegration) (*MeshIntegration, error) { - return c.meshObject.Put(ctx, *integration.Metadata.Uuid, integration) -} - -func (c meshIntegrationClientImpl) Delete(ctx context.Context, uuid string) error { - return c.meshObject.Delete(ctx, uuid) -} - -func (c meshIntegrationClientImpl) List(ctx context.Context) ([]MeshIntegration, error) { - return c.meshObject.List(ctx) -} +type MeshIntegrationClient = MeshObjectClient[MeshIntegration, NoFilter] diff --git a/client/integration_config.go b/client/integration_config.go index 16120199..14cebde9 100644 --- a/client/integration_config.go +++ b/client/integration_config.go @@ -1,13 +1,9 @@ package client import ( - "encoding/json/jsontext" - "fmt" - "github.com/meshcloud/meshstack-cli/client/types" "github.com/meshcloud/meshstack-cli/client/types/enum" - "github.com/meshcloud/meshstack-cli/client/types/variant" - "github.com/meshcloud/meshstack-cli/internal/json" + "github.com/meshcloud/meshstack-cli/client/types/polymorph" ) type MeshIntegrationConfigType string @@ -51,47 +47,10 @@ type MeshIntegrationEntraIdConfig struct { } type MeshIntegrationConfig struct { - Type enum.Entry[MeshIntegrationConfigType] `json:"type" tfsdk:"-"` - Github *MeshIntegrationGithubConfig `json:"github,omitzero" tfsdk:"github"` - Gitlab *MeshIntegrationGitlabConfig `json:"gitlab,omitzero" tfsdk:"gitlab"` - AzureDevops *MeshIntegrationAzureDevopsConfig `json:"azuredevops,omitzero" tfsdk:"azuredevops"` - EntraId *MeshIntegrationEntraIdConfig `json:"entraid,omitzero" tfsdk:"entraid"` -} - -func (m MeshIntegrationConfig) InferType() (enum.Entry[MeshIntegrationConfigType], error) { - result, err := variant.InferType( - variant.NewCandidate(MeshIntegrationConfigTypeGithub, m.Github != nil), - variant.NewCandidate(MeshIntegrationConfigTypeGitlab, m.Gitlab != nil), - variant.NewCandidate(MeshIntegrationConfigTypeAzureDevops, m.AzureDevops != nil), - variant.NewCandidate(MeshIntegrationConfigTypeEntraId, m.EntraId != nil), - ) - if err != nil { - return "", fmt.Errorf("cannot infer integration config type: %w", err) - } - return result, nil -} - -func (m MeshIntegrationConfig) MarshalJSONTo(enc *jsontext.Encoder) error { - type wrapped MeshIntegrationConfig - w := wrapped(m) - // Built-in integrations (replicator, metering) come with a type but no variant, so the type is only - // inferred when it is missing. - if len(w.Type) == 0 { - inferred, err := m.InferType() - if err != nil { - return err - } - w.Type = inferred - } - return json.MarshalEncode(enc, w, enc.Options()) -} + polymorph.Polymorph[MeshIntegrationConfig, MeshIntegrationConfigType] -func (m *MeshIntegrationConfig) UnmarshalJSONFrom(dec *jsontext.Decoder) error { - type wrapped MeshIntegrationConfig - var target wrapped - if err := json.UnmarshalDecode(dec, &target, dec.Options()); err != nil { - return err - } - *m = MeshIntegrationConfig(target) - return nil + Github *MeshIntegrationGithubConfig `json:"github,omitzero" polymorph:"github" tfsdk:"github"` + Gitlab *MeshIntegrationGitlabConfig `json:"gitlab,omitzero" polymorph:"gitlab" tfsdk:"gitlab"` + AzureDevops *MeshIntegrationAzureDevopsConfig `json:"azuredevops,omitzero" polymorph:"azuredevops" tfsdk:"azuredevops"` + EntraId *MeshIntegrationEntraIdConfig `json:"entraid,omitzero" polymorph:"entraid" tfsdk:"entraid"` } diff --git a/client/internal/mesh_object.go b/client/internal/mesh_object.go deleted file mode 100644 index 1991ecb8..00000000 --- a/client/internal/mesh_object.go +++ /dev/null @@ -1,207 +0,0 @@ -package internal - -import ( - "context" - "errors" - "fmt" - "iter" - "log/slog" - "net/url" - "reflect" - "regexp" - "slices" - "strings" - "unicode" - - "github.com/meshcloud/meshstack-cli/client/http" - "github.com/meshcloud/meshstack-cli/client/types/xurl" -) - -type HttpClient struct { - http.AuthorizedClient - - EndpointUrl xurl.URL -} - -// MeshObjectApi is the API of one meshObject kind, in one version, with no Go type for its objects: -// the requests and the paging they share, for a caller that decodes the answers itself. -type MeshObjectApi struct { - http.AuthorizedClient - - Kind string - ApiVersion string - ApiUrl *url.URL -} - -// MeshObjectClient decodes the API's objects into M, whose type name gives the kind. -type MeshObjectClient[M any] struct { - MeshObjectApi -} - -// NewMeshObjectClient takes the API path from the kind of M, in plural and lower case, unless -// explicitApiPathElems is given. Only the user and group binding APIs of workspaces and projects -// break that convention. -func NewMeshObjectClient[M any](ctx context.Context, httpClient HttpClient, apiVersion string, explicitApiPathElems ...string) MeshObjectClient[M] { - kind := InferKind[M]() - - if len(explicitApiPathElems) == 0 { - explicitApiPathElems = []string{strings.ToLower(pluralizeKind(kind))} - } - explicitApiPathElems = slices.Insert(explicitApiPathElems, 0, "/api/meshobjects") - apiUrl := httpClient.EndpointUrl.JoinPath(explicitApiPathElems...) - slog.DebugContext(ctx, fmt.Sprintf("initialized %s client", reflect.TypeFor[M]().Name()), "url", apiUrl.String(), "kind", kind, "version", apiVersion) - return MeshObjectClient[M]{MeshObjectApi{httpClient.AuthorizedClient, kind, apiVersion, apiUrl}} -} - -var versionSuffixRe = regexp.MustCompile(`V\d+$`) - -// InferKind follows the naming of the meshObject API: MeshWorkspace gives meshWorkspace, and -// MeshBuildingBlockV2 gives meshBuildingBlock. -func InferKind[M any]() string { - typeName := reflect.TypeFor[M]().Name() - - runes := []rune(typeName) - runes[0] = unicode.ToLower(runes[0]) - kind := string(runes) - - return versionSuffixRe.ReplaceAllString(kind, "") -} - -var pluralExceptions = map[string]string{} - -func pluralizeKind(kind string) string { - if plural, ok := pluralExceptions[kind]; ok { - return plural - } - return kind + "s" -} - -func (c MeshObjectApi) MeshObjectMimeType() string { - return fmt.Sprintf("application/vnd.meshcloud.api.%s.%s.hal+json", c.Kind, c.ApiVersion) -} - -func (c MeshObjectClient[M]) Get(ctx context.Context, id string) (resp *M, err error) { - resp, err = c.GetAtPath[*M](ctx, id) - if httpErr, ok := errors.AsType[http.Error](err); ok && httpErr.IsNotFound() { - //nolint:nilnil // MeshObject clients return nil on 404, which is how Terraform handles a resource that does not exist - return nil, nil - } - return -} - -func (c MeshObjectApi) GetAtPath[R any](ctx context.Context, id string, extraPath ...string) (R, error) { - return http.UnmarshalJsonBody[R](c.DoRequest(ctx, http.MethodGet, c.ApiUrl.JoinPath(id).JoinPath(extraPath...), http.WithHeader("Accept", c.MeshObjectMimeType()))) -} - -func (c MeshObjectClient[M]) Post[P any](ctx context.Context, payload P) (*M, error) { - return c.PostAtPath[*M](ctx, payload) -} - -func (c MeshObjectApi) PostAtPath[R, P any](ctx context.Context, payload P, extraPath ...string) (R, error) { - return http.UnmarshalJsonBody[R](c.DoRequest(ctx, http.MethodPost, c.ApiUrl.JoinPath(extraPath...), c.withMeshObjectPayload(payload))) -} - -func (c MeshObjectClient[M]) Put[P any](ctx context.Context, id string, payload P) (*M, error) { - return http.UnmarshalJsonBody[*M](c.DoRequest(ctx, http.MethodPut, c.ApiUrl.JoinPath(id), c.withMeshObjectPayload(payload), http.Retryable(http.RetryOnTransient))) -} - -func (c MeshObjectClient[M]) Delete(ctx context.Context, id string) (err error) { - return c.DeleteAtPath(ctx, id) -} - -func (c MeshObjectApi) DeleteAtPath(ctx context.Context, id string, extraPath ...string) (err error) { - return http.IgnoreResponse(c.DoRequest(ctx, http.MethodDelete, c.ApiUrl.JoinPath(id).JoinPath(extraPath...), http.WithHeader("Accept", c.MeshObjectMimeType()))) -} - -func (c MeshObjectClient[M]) ListSeq(ctx context.Context, options ...http.RequestOption) iter.Seq2[M, error] { - return c.ListSeqAs[M](ctx, ListOptions{}, options...) -} - -func (c MeshObjectApi) ListSeqAs[T any](ctx context.Context, listOptions ListOptions, options ...http.RequestOption) iter.Seq2[T, error] { - return func(yield func(T, error) bool) { - var noItem T - embeddedKey := pluralizeKind(c.Kind) - - for pageNumber := 0; ; pageNumber++ { - response, err := c.getPage[T](ctx, listOptions, pageNumber, options) - if err != nil { - yield(noItem, err) - return - } - items, ok := response.Embedded[embeddedKey] - if !ok { - yield(noItem, fmt.Errorf("embedded key %s not found in paginated response", embeddedKey)) - return - } - if listOptions.OnPage != nil { - listOptions.OnPage(response.Page) - } - for _, item := range items { - if !yield(item, nil) { - return - } - } - if response.Page.Number >= response.Page.TotalPages-1 { - return - } - } - } -} - -type Page struct { - Size int `json:"size"` - TotalElements int `json:"totalElements"` - TotalPages int `json:"totalPages"` - Number int `json:"number"` -} - -type paginatedResponse[T any] struct { - Embedded map[string][]T `json:"_embedded"` - Page Page `json:"page"` -} - -// withMeshObjectPayload takes P rather than an any because the `,embed` tag takes a struct, a -// string-keyed map or a jsontext.Value, never an any. -func (c MeshObjectApi) withMeshObjectPayload[P any](payload P) http.RequestOption { - return http.WithJsonRequest(struct { - ApiVersion string `json:"apiVersion"` - Kind string `json:"kind"` - Payload P `json:",embed"` - }{c.ApiVersion, c.Kind, payload}, c.MeshObjectMimeType()) -} - -func (c MeshObjectApi) getPage[T any](ctx context.Context, listOptions ListOptions, pageNumber int, options []http.RequestOption) (paginatedResponse[T], error) { - query := map[string]any{"page": pageNumber} - if listOptions.PageSize > 0 { - query["size"] = listOptions.PageSize - } - response, err := http.UnmarshalJsonBody[paginatedResponse[T]](c.DoRequest(ctx, http.MethodGet, c.ApiUrl, append(options, - http.WithHeader("Accept", c.MeshObjectMimeType()), - http.WithUrlQuery(query), - )...)) - if err != nil && pageNumber > 0 { - // The first page fails for what fails the whole list, such as a missing role, and a page - // number would only distract from it. - return response, fmt.Errorf("cannot read page %d of the list: %w", pageNumber, err) - } - if err != nil { - return response, err - } - return response, nil -} - -type ListOptions struct { - PageSize int - OnPage func(Page) -} - -func (c MeshObjectClient[M]) List(ctx context.Context, options ...http.RequestOption) ([]M, error) { - var result []M - for item, err := range c.ListSeq(ctx, options...) { - if err != nil { - return result, err - } - result = append(result, item) - } - return result, nil -} diff --git a/client/landingzone.go b/client/landingzone.go index 1f3b3f3b..6d7ac187 100644 --- a/client/landingzone.go +++ b/client/landingzone.go @@ -1,16 +1,9 @@ package client -import ( - "context" - - "github.com/meshcloud/meshstack-cli/client/http" - "github.com/meshcloud/meshstack-cli/client/internal" -) - type MeshLandingZone struct { Metadata MeshLandingZoneMetadata `json:"metadata" tfsdk:"metadata"` Spec MeshLandingZoneSpec `json:"spec" tfsdk:"spec"` - Status MeshLandingZoneStatus `json:"status" tfsdk:"status"` + Status MeshLandingZoneStatus `json:"status,omitzero" tfsdk:"status"` } type MeshLandingZoneMetadata struct { @@ -58,12 +51,7 @@ type MeshLandingZoneQuota struct { Value int64 `json:"value" tfsdk:"value"` } -type MeshLandingZoneCreate struct { - Metadata MeshLandingZoneMetadata `json:"metadata" tfsdk:"metadata"` - Spec MeshLandingZoneSpec `json:"spec" tfsdk:"spec"` -} - -type MeshLandingZoneListQuery struct { +type MeshLandingZoneFilter struct { PlatformUuid *string `json:"platformUuid"` Identifier *string `json:"identifier"` DisplayName *string `json:"displayName"` @@ -71,38 +59,8 @@ type MeshLandingZoneListQuery struct { OwnedByWorkspace *string `json:"ownedByWorkspace"` } -type MeshLandingZoneClient interface { - Read(ctx context.Context, name string) (*MeshLandingZone, error) - List(ctx context.Context, query MeshLandingZoneListQuery) ([]MeshLandingZone, error) - Create(ctx context.Context, landingZone *MeshLandingZoneCreate) (*MeshLandingZone, error) - Update(ctx context.Context, name string, landingZone *MeshLandingZoneCreate) (*MeshLandingZone, error) - Delete(ctx context.Context, name string) error -} - -type meshLandingZoneClient struct { - meshObject internal.MeshObjectClient[MeshLandingZone] -} - -func newLandingZoneClient(ctx context.Context, httpClient internal.HttpClient) MeshLandingZoneClient { - return meshLandingZoneClient{internal.NewMeshObjectClient[MeshLandingZone](ctx, httpClient, "v1")} -} - -func (c meshLandingZoneClient) Read(ctx context.Context, name string) (*MeshLandingZone, error) { - return c.meshObject.Get(ctx, name) -} - -func (c meshLandingZoneClient) List(ctx context.Context, query MeshLandingZoneListQuery) ([]MeshLandingZone, error) { - return c.meshObject.List(ctx, http.WithUrlQuery(query)) -} - -func (c meshLandingZoneClient) Create(ctx context.Context, landingZone *MeshLandingZoneCreate) (*MeshLandingZone, error) { - return c.meshObject.Post(ctx, landingZone) -} - -func (c meshLandingZoneClient) Update(ctx context.Context, name string, landingZone *MeshLandingZoneCreate) (*MeshLandingZone, error) { - return c.meshObject.Put(ctx, name, landingZone) -} +type MeshLandingZoneClient = MeshObjectClient[MeshLandingZone, MeshLandingZoneFilter] -func (c meshLandingZoneClient) Delete(ctx context.Context, name string) error { - return c.meshObject.Delete(ctx, name) +func (lz MeshLandingZone) meshObjectId() string { + return lz.Metadata.Name } diff --git a/client/lifecycle.go b/client/lifecycle.go new file mode 100644 index 00000000..2e9bf493 --- /dev/null +++ b/client/lifecycle.go @@ -0,0 +1,41 @@ +package client + +import ( + "time" + + "github.com/meshcloud/meshstack-cli/client/types/enum" +) + +type MeshLifecycleState string + +var ( + MeshLifecycleStates = enum.Enum[MeshLifecycleState]{} + MeshLifecycleStateActive = MeshLifecycleStates.Entry("ACTIVE") + MeshLifecycleStateDeactivated = MeshLifecycleStates.Entry("DEACTIVATED") + MeshLifecycleStateMarkedForDeletion = MeshLifecycleStates.Entry("MARKED_FOR_DELETION") + MeshLifecycleStateDeleted = MeshLifecycleStates.Entry("DELETED") +) + +type MeshLifecycle struct { + State enum.Entry[MeshLifecycleState] `json:"state"` + Created MeshLifecycleTransition `json:"created"` + Deactivated *MeshLifecycleTransition `json:"deactivated,omitzero"` + MarkedForDeletion *MeshLifecycleTransition `json:"markedForDeletion,omitzero"` + Deleted *MeshLifecycleTransition `json:"deleted,omitzero"` +} + +type MeshLifecycleTransition struct { + Timestamp time.Time `json:"timestamp"` + Author *MeshObjectAuthor `json:"author,omitzero"` +} + +type MeshObjectAuthor struct { + // Type is one of ApiKey, ApiUser, System and User, and decides what Identifier is: the uuid of + // the meshApiKey, the name of the API user, "system", or the uuid of the meshUser. + Type string `json:"type"` + Identifier string `json:"identifier"` + DisplayName *string `json:"displayName,omitzero"` + Username *string `json:"username,omitzero"` + Email *string `json:"email,omitzero"` + Euid *string `json:"euid,omitzero"` +} diff --git a/client/location.go b/client/location.go index c2935caf..752e3073 100644 --- a/client/location.go +++ b/client/location.go @@ -1,21 +1,15 @@ package client -import ( - "context" - - "github.com/meshcloud/meshstack-cli/client/internal" -) - type MeshLocation struct { Metadata MeshLocationMetadata `json:"metadata" tfsdk:"metadata"` Spec MeshLocationSpec `json:"spec" tfsdk:"spec"` - Status MeshLocationStatus `json:"status" tfsdk:"status"` + Status MeshLocationStatus `json:"status,omitzero" tfsdk:"status"` } type MeshLocationMetadata struct { - Name string `json:"name" tfsdk:"name"` - OwnedByWorkspace string `json:"ownedByWorkspace" tfsdk:"owned_by_workspace"` - Uuid string `json:"uuid" tfsdk:"uuid"` + Name string `json:"name" tfsdk:"name"` + OwnedByWorkspace string `json:"ownedByWorkspace" tfsdk:"owned_by_workspace"` + Uuid *string `json:"uuid,omitzero" tfsdk:"uuid"` } type MeshLocationSpec struct { @@ -27,43 +21,8 @@ type MeshLocationStatus struct { IsPublic bool `json:"isPublic" tfsdk:"is_public"` } -type MeshLocationCreate struct { - Metadata MeshLocationCreateMetadata `json:"metadata" tfsdk:"metadata"` - Spec MeshLocationSpec `json:"spec" tfsdk:"spec"` -} - -type MeshLocationCreateMetadata struct { - Name string `json:"name" tfsdk:"name"` - OwnedByWorkspace string `json:"ownedByWorkspace" tfsdk:"owned_by_workspace"` -} - -type MeshLocationClient interface { - Read(ctx context.Context, name string) (*MeshLocation, error) - Create(ctx context.Context, location *MeshLocationCreate) (*MeshLocation, error) - Update(ctx context.Context, name string, location *MeshLocationCreate) (*MeshLocation, error) - Delete(ctx context.Context, name string) error -} - -type meshLocationClient struct { - meshObject internal.MeshObjectClient[MeshLocation] -} - -func newLocationClient(ctx context.Context, httpClient internal.HttpClient) MeshLocationClient { - return meshLocationClient{internal.NewMeshObjectClient[MeshLocation](ctx, httpClient, "v1")} -} - -func (c meshLocationClient) Read(ctx context.Context, name string) (*MeshLocation, error) { - return c.meshObject.Get(ctx, name) -} - -func (c meshLocationClient) Create(ctx context.Context, location *MeshLocationCreate) (*MeshLocation, error) { - return c.meshObject.Post(ctx, location) -} - -func (c meshLocationClient) Update(ctx context.Context, name string, location *MeshLocationCreate) (*MeshLocation, error) { - return c.meshObject.Put(ctx, name, location) -} +type MeshLocationClient = MeshObjectClient[MeshLocation, NoFilter] -func (c meshLocationClient) Delete(ctx context.Context, name string) error { - return c.meshObject.Delete(ctx, name) +func (location MeshLocation) meshObjectId() string { + return location.Metadata.Name } diff --git a/client/meshobject.go b/client/meshobject.go new file mode 100644 index 00000000..acdf8935 --- /dev/null +++ b/client/meshobject.go @@ -0,0 +1,276 @@ +package client + +import ( + "context" + "errors" + "fmt" + "io" + "iter" + "log/slog" + "net/url" + "reflect" + "regexp" + "slices" + "strings" + "time" + "unicode" + + "github.com/meshcloud/meshstack-cli/client/http" + "github.com/meshcloud/meshstack-cli/client/types" + "github.com/meshcloud/meshstack-cli/client/types/hal" + "github.com/meshcloud/meshstack-cli/client/types/xurl" +) + +type MeshObjectReadOnlyClient[M, Filter any] interface { + // Read returns nil and no error where meshStack has no object with the id. + Read(ctx context.Context, id string) (*M, error) + List(ctx context.Context, filter Filter, options ...ListOption) ([]M, error) + ListSeq(ctx context.Context, filter Filter, options ...ListOption) iter.Seq2[M, error] +} + +type MeshObjectImmutableClient[M, Filter any] interface { + MeshObjectReadOnlyClient[M, Filter] + Create(ctx context.Context, object M) (M, error) + // Delete takes a 404 as success, which a retried delete gets. + Delete(ctx context.Context, id string) error +} + +type MeshObjectClient[M, Filter any] interface { + MeshObjectImmutableClient[M, Filter] + Update(ctx context.Context, object M) (M, error) +} + +type NoFilter struct{} + +type ListOption func(request *listOptions) + +type listOptions struct { + pageSize int + until time.Time + page *types.Page +} + +func WithPageSize(size int) ListOption { + return func(request *listOptions) { + request.pageSize = size + } +} + +// WithNewestFirst yields to a filter's own sort and until. +func WithNewestFirst(until time.Time) ListOption { + return func(request *listOptions) { + request.until = until + } +} + +func WithCapturedPage(page *types.Page) ListOption { + return func(request *listOptions) { + request.page = page + } +} + +type meshObject interface { + meshObjectId() string +} + +type meshObjectAtPath interface { + meshObjectPath() string +} + +type meshObjectNoSortQuery interface { + meshObjectNoSortQuery() +} + +type meshObjectClient[M meshObject, Filter any] struct { + client http.AuthorizedClient + collection *url.URL + mediaType string + kind string + apiVersion string +} + +func newMeshObjectClient[M meshObject, Filter any](ctx context.Context, client http.AuthorizedClient, endpoint xurl.URL, apiVersion string) meshObjectClient[M, Filter] { + kind := inferKind[M]() + path := strings.ToLower(pluralizeKind(kind)) + if atPath, ok := any(*new(M)).(meshObjectAtPath); ok { + path = atPath.meshObjectPath() + } + c := meshObjectClient[M, Filter]{ + client: client, + collection: endpoint.JoinPath("api", "meshobjects", path), + mediaType: fmt.Sprintf("application/vnd.meshcloud.api.%s.%s.hal+json", kind, apiVersion), + kind: kind, + apiVersion: apiVersion, + } + slog.DebugContext(ctx, fmt.Sprintf("initialized %s client", reflect.TypeFor[M]().Name()), "url", c.collection.String(), "kind", kind, "version", apiVersion) + return c +} + +func WithKindAndApiVersion[M, Filter any](c MeshObjectReadOnlyClient[M, Filter], object M) any { + enveloper, ok := c.(interface{ envelope(object M) any }) + if !ok { + panic(fmt.Sprintf("%T is no client that client.New built", c)) + } + return enveloper.envelope(object) +} + +var versionSuffixRe = regexp.MustCompile(`V\d+$`) + +func inferKind[M any]() string { + runes := []rune(reflect.TypeFor[M]().Name()) + runes[0] = unicode.ToLower(runes[0]) + return versionSuffixRe.ReplaceAllString(string(runes), "") +} + +func pluralizeKind(kind string) string { + return kind + "s" +} + +func (c meshObjectClient[M, Filter]) do(ctx context.Context, method string, target *url.URL, options ...http.RequestOption) (io.ReadCloser, error) { + return c.client.DoRequest(ctx, method, target, slices.Insert(options, 0, http.WithHeader("Accept", c.mediaType))...) +} + +// followLink sends the bearer token only to the origin of the endpoint. +func (c meshObjectClient[M, Filter]) followLink(ctx context.Context, method, href string, options ...http.RequestOption) (io.ReadCloser, error) { + target, err := c.collection.Parse(href) + if err != nil { + return nil, fmt.Errorf("meshStack sent the link %q, which is no URL: %w", href, err) + } + if target.Scheme != c.collection.Scheme || target.Host != c.collection.Host { + return nil, fmt.Errorf("meshStack sent the link %s, which leaves the endpoint %s://%s", target.Redacted(), c.collection.Scheme, c.collection.Host) + } + return c.do(ctx, method, target, slices.Insert(options, 0, http.WithContentType(c.mediaType))...) +} + +func (c meshObjectClient[M, Filter]) Read(ctx context.Context, id string) (*M, error) { + object, err := c.unmarshalJsonBody[*M](c.do(ctx, http.MethodGet, c.collection.JoinPath(id))) + if isNotFound(err) { + //nolint:nilnil // a meshObject client returns nil on 404, which is how Terraform handles a resource that does not exist + return nil, nil + } + return object, err +} + +func (c meshObjectClient[M, Filter]) Create(ctx context.Context, object M) (M, error) { + return c.unmarshalJsonBody[M](c.do(ctx, http.MethodPost, c.collection, http.WithJsonRequest(c.envelope(object), c.mediaType))) +} + +func (c meshObjectClient[M, Filter]) Update(ctx context.Context, object M) (M, error) { + return c.unmarshalJsonBody[M](c.do(ctx, http.MethodPut, c.collection.JoinPath(object.meshObjectId()), + http.WithJsonRequest(c.envelope(object), c.mediaType), http.Retryable(http.RetryOnTransient))) +} + +func (c meshObjectClient[M, Filter]) Delete(ctx context.Context, id string) error { + err := http.IgnoreResponse(c.do(ctx, http.MethodDelete, c.collection.JoinPath(id))) + if isNotFound(err) { + return nil + } + return err +} + +func (c meshObjectClient[M, Filter]) envelope(object M) any { + return struct { + ApiVersion string `json:"apiVersion"` + Kind string `json:"kind"` + Object M `json:",embed"` + }{c.apiVersion, c.kind, object} +} + +func (c meshObjectClient[M, Filter]) List(ctx context.Context, filter Filter, options ...ListOption) ([]M, error) { + var result []M + for item, err := range c.ListSeq(ctx, filter, options...) { + if err != nil { + return result, err + } + result = append(result, item) + } + return result, nil +} + +func (c meshObjectClient[M, Filter]) ListSeq(ctx context.Context, filter Filter, options ...ListOption) iter.Seq2[M, error] { + var opts listOptions + for _, option := range options { + option(&opts) + } + query := []http.RequestOption{http.WithUrlQuery(filter)} + if !opts.until.IsZero() { + // Without a fixed until, an object created during the listing pushes a read one onto the next page. + newestFirst := url.Values{"until": {opts.until.UTC().Format(time.RFC3339Nano)}} + if _, noSortQuery := any(*new(M)).(meshObjectNoSortQuery); !noSortQuery { + newestFirst.Set("sort", "createdAt,desc") + } + query = []http.RequestOption{http.WithUrlQuery(newestFirst), http.WithUrlQuery(filter)} + } + return func(yield func(M, error) bool) { + var noObject M + embeddedKey := pluralizeKind(c.kind) + for pageNumber := 0; ; pageNumber++ { + page, err := c.page(ctx, pageNumber, opts.pageSize, query) + if err != nil { + yield(noObject, err) + return + } + objects, ok := page.Embedded[embeddedKey] + if !ok { + yield(noObject, fmt.Errorf("embedded key %s not found in paginated response", embeddedKey)) + return + } + if opts.page != nil { + *opts.page = page.Page + } + for _, object := range objects { + if !yield(object, nil) { + return + } + } + if page.Page.Number >= page.Page.TotalPages-1 { + return + } + } + } +} + +type paginatedResponse[M any] struct { + Embedded map[string][]M `json:"_embedded"` + Page types.Page `json:"page"` +} + +func (c meshObjectClient[M, Filter]) page(ctx context.Context, pageNumber, pageSize int, query []http.RequestOption) (paginatedResponse[M], error) { + pageQuery := map[string]any{"page": pageNumber} + if pageSize > 0 { + pageQuery["size"] = pageSize + } + page, err := c.unmarshalJsonBody[paginatedResponse[M]](c.do(ctx, http.MethodGet, c.collection, append(query, http.WithUrlQuery(pageQuery))...)) + if err != nil && pageNumber > 0 { + // The first page fails for what fails the whole list, such as a missing role, and a page + // number would only distract from it. + return page, fmt.Errorf("cannot read page %d of the list: %w", pageNumber, err) + } + return page, err +} + +func (c meshObjectClient[M, Filter]) unmarshalJsonBody[R any](body io.ReadCloser, err error) (R, error) { + return http.UnmarshalJsonBody[R](body, err, hal.LinkUnmarshalers(c.followLink)) +} + +func isNotFound(err error) bool { + httpErr, ok := errors.AsType[http.Error](err) + return ok && httpErr.IsNotFound() +} + +type MeshObjectByUuidMetadata struct { + Uuid *string `json:"uuid,omitzero" tfsdk:"uuid"` + OwnedByWorkspace string `json:"ownedByWorkspace" tfsdk:"owned_by_workspace"` +} + +func (m MeshObjectByUuidMetadata) meshObjectId() string { + return *m.Uuid +} + +type MeshObjectByNameMetadata struct { + Name string `json:"name" tfsdk:"name"` +} + +func (m MeshObjectByNameMetadata) meshObjectId() string { + return m.Name +} diff --git a/client/meshobject_test.go b/client/meshobject_test.go new file mode 100644 index 00000000..196a3b6a --- /dev/null +++ b/client/meshobject_test.go @@ -0,0 +1,20 @@ +package client + +import ( + "net/url" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/meshcloud/meshstack-cli/client/http" +) + +func TestALinkToAnotherOriginIsNotFollowed(t *testing.T) { + c := meshObjectClient[MeshWorkspace, NoFilter]{ + collection: &url.URL{Scheme: "https", Host: "meshstack.example", Path: "/api/meshobjects/meshworkspaces"}, + } + for _, href := range []string{"https://other.host/api/x", "//other.host/x", "http://meshstack.example/x"} { + _, err := c.followLink(t.Context(), http.MethodGet, href) + require.ErrorContains(t, err, "which leaves the endpoint", href) + } +} diff --git a/client/payment_method.go b/client/payment_method.go index 05f9f3ab..f28489c2 100644 --- a/client/payment_method.go +++ b/client/payment_method.go @@ -1,11 +1,5 @@ package client -import ( - "context" - - "github.com/meshcloud/meshstack-cli/client/internal" -) - type MeshPaymentMethod struct { Metadata MeshPaymentMethodMetadata `json:"metadata" tfsdk:"metadata"` Spec MeshPaymentMethodSpec `json:"spec" tfsdk:"spec"` @@ -14,8 +8,8 @@ type MeshPaymentMethod struct { type MeshPaymentMethodMetadata struct { Name string `json:"name" tfsdk:"name"` OwnedByWorkspace string `json:"ownedByWorkspace" tfsdk:"owned_by_workspace"` - CreatedOn string `json:"createdOn" tfsdk:"created_on"` - DeletedOn *string `json:"deletedOn" tfsdk:"deleted_on"` + CreatedOn string `json:"createdOn,omitzero" tfsdk:"created_on"` + DeletedOn *string `json:"deletedOn,omitzero" tfsdk:"deleted_on"` } type MeshPaymentMethodSpec struct { @@ -25,43 +19,8 @@ type MeshPaymentMethodSpec struct { Tags map[string][]string `json:"tags,omitempty" tfsdk:"tags"` } -type MeshPaymentMethodCreate struct { - Metadata MeshPaymentMethodCreateMetadata `json:"metadata" tfsdk:"metadata"` - Spec MeshPaymentMethodSpec `json:"spec" tfsdk:"spec"` -} - -type MeshPaymentMethodCreateMetadata struct { - Name string `json:"name" tfsdk:"name"` - OwnedByWorkspace string `json:"ownedByWorkspace" tfsdk:"owned_by_workspace"` -} - -type MeshPaymentMethodClient interface { - Read(ctx context.Context, identifier string) (*MeshPaymentMethod, error) - Create(ctx context.Context, paymentMethod *MeshPaymentMethodCreate) (*MeshPaymentMethod, error) - Update(ctx context.Context, identifier string, paymentMethod *MeshPaymentMethodCreate) (*MeshPaymentMethod, error) - Delete(ctx context.Context, identifier string) error -} - -type meshPaymentMethodClient struct { - meshObject internal.MeshObjectClient[MeshPaymentMethod] -} - -func newPaymentMethodClient(ctx context.Context, httpClient internal.HttpClient) MeshPaymentMethodClient { - return meshPaymentMethodClient{internal.NewMeshObjectClient[MeshPaymentMethod](ctx, httpClient, "v2")} -} - -func (c meshPaymentMethodClient) Read(ctx context.Context, identifier string) (*MeshPaymentMethod, error) { - return c.meshObject.Get(ctx, identifier) -} - -func (c meshPaymentMethodClient) Create(ctx context.Context, paymentMethod *MeshPaymentMethodCreate) (*MeshPaymentMethod, error) { - return c.meshObject.Post(ctx, paymentMethod) -} - -func (c meshPaymentMethodClient) Update(ctx context.Context, identifier string, paymentMethod *MeshPaymentMethodCreate) (*MeshPaymentMethod, error) { - return c.meshObject.Put(ctx, identifier, paymentMethod) -} +type MeshPaymentMethodClient = MeshObjectClient[MeshPaymentMethod, NoFilter] -func (c meshPaymentMethodClient) Delete(ctx context.Context, identifier string) error { - return c.meshObject.Delete(ctx, identifier) +func (paymentMethod MeshPaymentMethod) meshObjectId() string { + return paymentMethod.Metadata.Name } diff --git a/client/platform.go b/client/platform.go index f20e8983..bea356ab 100644 --- a/client/platform.go +++ b/client/platform.go @@ -1,10 +1,6 @@ package client import ( - "context" - - "github.com/meshcloud/meshstack-cli/client/http" - "github.com/meshcloud/meshstack-cli/client/internal" "github.com/meshcloud/meshstack-cli/client/types" ) @@ -78,7 +74,7 @@ type TagMapper struct { ValuePattern string `json:"valuePattern" tfsdk:"value_pattern"` } -type MeshPlatformListQuery struct { +type MeshPlatformFilter struct { OwnedByWorkspace *string `json:"ownedByWorkspace"` Identifier *string `json:"identifier"` LocationIdentifier *string `json:"locationIdentifier"` @@ -91,38 +87,8 @@ type MeshPlatformListQuery struct { PlatformTypeIdentifier *string `json:"platformTypeIdentifier"` } -type MeshPlatformClient interface { - Read(ctx context.Context, uuid string) (*MeshPlatform, error) - List(ctx context.Context, query MeshPlatformListQuery) ([]MeshPlatform, error) - Create(ctx context.Context, platform MeshPlatform) (*MeshPlatform, error) - Update(ctx context.Context, uuid string, platform MeshPlatform) (*MeshPlatform, error) - Delete(ctx context.Context, uuid string) error -} - -type meshPlatformClient struct { - meshObject internal.MeshObjectClient[MeshPlatform] -} - -func newPlatformClient(ctx context.Context, httpClient internal.HttpClient) MeshPlatformClient { - return meshPlatformClient{internal.NewMeshObjectClient[MeshPlatform](ctx, httpClient, "v2")} -} - -func (c meshPlatformClient) Read(ctx context.Context, uuid string) (*MeshPlatform, error) { - return c.meshObject.Get(ctx, uuid) -} - -func (c meshPlatformClient) List(ctx context.Context, query MeshPlatformListQuery) ([]MeshPlatform, error) { - return c.meshObject.List(ctx, http.WithUrlQuery(query)) -} - -func (c meshPlatformClient) Create(ctx context.Context, platform MeshPlatform) (*MeshPlatform, error) { - return c.meshObject.Post(ctx, platform) -} - -func (c meshPlatformClient) Update(ctx context.Context, uuid string, platform MeshPlatform) (*MeshPlatform, error) { - return c.meshObject.Put(ctx, uuid, platform) -} +type MeshPlatformClient = MeshObjectClient[MeshPlatform, MeshPlatformFilter] -func (c meshPlatformClient) Delete(ctx context.Context, uuid string) error { - return c.meshObject.Delete(ctx, uuid) +func (platform MeshPlatform) meshObjectId() string { + return *platform.Metadata.Uuid } diff --git a/client/platform_type.go b/client/platform_type.go index 37ea81f4..638ffb4a 100644 --- a/client/platform_type.go +++ b/client/platform_type.go @@ -1,16 +1,9 @@ package client -import ( - "context" - - "github.com/meshcloud/meshstack-cli/client/http" - "github.com/meshcloud/meshstack-cli/client/internal" -) - type MeshPlatformType struct { Metadata MeshPlatformTypeMetadata `json:"metadata" tfsdk:"metadata"` Spec MeshPlatformTypeSpec `json:"spec" tfsdk:"spec"` - Status MeshPlatformTypeStatus `json:"status" tfsdk:"status"` + Status MeshPlatformTypeStatus `json:"status,omitzero" tfsdk:"status"` } type MeshPlatformTypeStatus struct { @@ -34,56 +27,13 @@ type MeshPlatformTypeSpec struct { Icon string `json:"icon" tfsdk:"icon"` } -type MeshPlatformTypeCreate struct { - Metadata MeshPlatformTypeCreateMetadata `json:"metadata" tfsdk:"metadata"` - Spec MeshPlatformTypeSpec `json:"spec" tfsdk:"spec"` -} - -type MeshPlatformTypeCreateMetadata struct { - Name string `json:"name" tfsdk:"name"` - OwnedByWorkspace string `json:"ownedByWorkspace" tfsdk:"owned_by_workspace"` -} - -type MeshPlatformTypeClient interface { - Create(ctx context.Context, platformType *MeshPlatformTypeCreate) (*MeshPlatformType, error) - Read(ctx context.Context, identifier string) (*MeshPlatformType, error) - Update(ctx context.Context, name string, platformType *MeshPlatformTypeCreate) (*MeshPlatformType, error) - Delete(ctx context.Context, name string) error - List(ctx context.Context, category *string, lifecycleStatus *string) ([]MeshPlatformType, error) -} - -type meshPlatformTypeClient struct { - meshObject internal.MeshObjectClient[MeshPlatformType] -} - -func newPlatformTypeClient(ctx context.Context, httpClient internal.HttpClient) MeshPlatformTypeClient { - return meshPlatformTypeClient{internal.NewMeshObjectClient[MeshPlatformType](ctx, httpClient, "v1")} -} - -func (c meshPlatformTypeClient) Create(ctx context.Context, platformType *MeshPlatformTypeCreate) (*MeshPlatformType, error) { - return c.meshObject.Post(ctx, platformType) -} - -func (c meshPlatformTypeClient) Read(ctx context.Context, identifier string) (*MeshPlatformType, error) { - return c.meshObject.Get(ctx, identifier) -} - -func (c meshPlatformTypeClient) Update(ctx context.Context, name string, platformType *MeshPlatformTypeCreate) (*MeshPlatformType, error) { - return c.meshObject.Put(ctx, name, platformType) -} - -func (c meshPlatformTypeClient) Delete(ctx context.Context, name string) error { - return c.meshObject.Delete(ctx, name) -} - -type meshPlatformTypeListQuery struct { +type MeshPlatformTypeFilter struct { Category *string `json:"category"` LifecycleStatus *string `json:"lifecycleStatus"` } -func (c meshPlatformTypeClient) List(ctx context.Context, category *string, lifecycleStatus *string) ([]MeshPlatformType, error) { - return c.meshObject.List(ctx, http.WithUrlQuery(meshPlatformTypeListQuery{ - Category: category, - LifecycleStatus: lifecycleStatus, - })) +type MeshPlatformTypeClient = MeshObjectClient[MeshPlatformType, MeshPlatformTypeFilter] + +func (platformType MeshPlatformType) meshObjectId() string { + return platformType.Metadata.Name } diff --git a/client/project.go b/client/project.go index c8e06165..63f0b5fd 100644 --- a/client/project.go +++ b/client/project.go @@ -1,12 +1,5 @@ package client -import ( - "context" - - "github.com/meshcloud/meshstack-cli/client/http" - "github.com/meshcloud/meshstack-cli/client/internal" -) - type MeshProject struct { Metadata MeshProjectMetadata `json:"metadata" tfsdk:"metadata"` Spec MeshProjectSpec `json:"spec" tfsdk:"spec"` @@ -15,8 +8,8 @@ type MeshProject struct { type MeshProjectMetadata struct { Name string `json:"name" tfsdk:"name"` OwnedByWorkspace string `json:"ownedByWorkspace" tfsdk:"owned_by_workspace"` - CreatedOn string `json:"createdOn" tfsdk:"created_on"` - DeletedOn *string `json:"deletedOn" tfsdk:"deleted_on"` + CreatedOn string `json:"createdOn,omitzero" tfsdk:"created_on"` + DeletedOn *string `json:"deletedOn,omitzero" tfsdk:"deleted_on"` } type MeshProjectSpec struct { @@ -26,60 +19,17 @@ type MeshProjectSpec struct { SubstitutePaymentMethodIdentifier *string `json:"substitutePaymentMethodIdentifier" tfsdk:"substitute_payment_method_identifier"` } -type MeshProjectCreate struct { - Metadata MeshProjectCreateMetadata `json:"metadata" tfsdk:"metadata"` - Spec MeshProjectSpec `json:"spec" tfsdk:"spec"` -} - -type MeshProjectCreateMetadata struct { - Name string `json:"name" tfsdk:"name"` - OwnedByWorkspace string `json:"ownedByWorkspace" tfsdk:"owned_by_workspace"` -} - -type MeshProjectClient interface { - Read(ctx context.Context, workspace string, name string) (*MeshProject, error) - List(ctx context.Context, workspaceIdentifier string, paymentMethodIdentifier *string) ([]MeshProject, error) - Create(ctx context.Context, project *MeshProjectCreate) (*MeshProject, error) - Update(ctx context.Context, project *MeshProjectCreate) (*MeshProject, error) - Delete(ctx context.Context, workspace string, name string) error -} - -type meshProjectClient struct { - meshObject internal.MeshObjectClient[MeshProject] -} - -func newProjectClient(ctx context.Context, httpClient internal.HttpClient) MeshProjectClient { - return meshProjectClient{internal.NewMeshObjectClient[MeshProject](ctx, httpClient, "v2")} -} - -func (c meshProjectClient) Read(ctx context.Context, workspace string, name string) (*MeshProject, error) { - return c.meshObject.Get(ctx, c.projectId(workspace, name)) +func NewMeshProjectId(workspace, name string) string { + return workspace + "." + name } -type meshProjectListQuery struct { +type MeshProjectFilter struct { WorkspaceIdentifier string `json:"workspaceIdentifier"` PaymentIdentifier *string `json:"paymentIdentifier"` } -func (c meshProjectClient) List(ctx context.Context, workspaceIdentifier string, paymentMethodIdentifier *string) ([]MeshProject, error) { - return c.meshObject.List(ctx, http.WithUrlQuery(meshProjectListQuery{ - WorkspaceIdentifier: workspaceIdentifier, - PaymentIdentifier: paymentMethodIdentifier, - })) -} - -func (c meshProjectClient) Create(ctx context.Context, project *MeshProjectCreate) (*MeshProject, error) { - return c.meshObject.Post(ctx, project) -} - -func (c meshProjectClient) Update(ctx context.Context, project *MeshProjectCreate) (*MeshProject, error) { - return c.meshObject.Put(ctx, c.projectId(project.Metadata.OwnedByWorkspace, project.Metadata.Name), project) -} +type MeshProjectClient = MeshObjectClient[MeshProject, MeshProjectFilter] -func (c meshProjectClient) Delete(ctx context.Context, workspace string, name string) error { - return c.meshObject.Delete(ctx, c.projectId(workspace, name)) -} - -func (c meshProjectClient) projectId(workspace string, name string) string { - return workspace + "." + name +func (project MeshProject) meshObjectId() string { + return NewMeshProjectId(project.Metadata.OwnedByWorkspace, project.Metadata.Name) } diff --git a/client/project_binding.go b/client/project_binding.go index 57f91d39..08a98b31 100644 --- a/client/project_binding.go +++ b/client/project_binding.go @@ -1,15 +1,11 @@ package client type MeshProjectBinding struct { - Metadata MeshProjectBindingMetadata `json:"metadata" tfsdk:"metadata"` - RoleRef MeshProjectRoleRef `json:"roleRef" tfsdk:"role_ref"` - TargetRef MeshProjectTargetRef `json:"targetRef" tfsdk:"target_ref"` - Subject MeshSubject `json:"subject" tfsdk:"subject"` - ExpiryDate *string `json:"expiryDate,omitzero" tfsdk:"expiry_date"` -} - -type MeshProjectBindingMetadata struct { - Name string `json:"name" tfsdk:"name"` + Metadata MeshObjectByNameMetadata `json:"metadata" tfsdk:"metadata"` + RoleRef MeshProjectRoleRef `json:"roleRef" tfsdk:"role_ref"` + TargetRef MeshProjectTargetRef `json:"targetRef" tfsdk:"target_ref"` + Subject MeshSubject `json:"subject" tfsdk:"subject"` + ExpiryDate *string `json:"expiryDate,omitzero" tfsdk:"expiry_date"` } // MeshProjectRoleRef names a role by its name alone. @@ -29,7 +25,11 @@ type MeshSubject struct { Name string `json:"name" tfsdk:"name"` } -type MeshProjectBindingListFilter struct { +type MeshProjectBindingFilter struct { WorkspaceIdentifier *string `json:"workspaceIdentifier"` ProjectIdentifier *string `json:"projectIdentifier"` } + +func (binding MeshProjectBinding) meshObjectId() string { + return binding.Metadata.meshObjectId() +} diff --git a/client/project_group_binding.go b/client/project_group_binding.go index 4aa3bc91..549507af 100644 --- a/client/project_group_binding.go +++ b/client/project_group_binding.go @@ -1,45 +1,13 @@ package client -import ( - "context" - - "github.com/meshcloud/meshstack-cli/client/http" - "github.com/meshcloud/meshstack-cli/client/internal" -) - type MeshProjectGroupBinding struct { MeshProjectBinding Status *MeshGroupBindingStatus `json:"status,omitempty" tfsdk:"status"` } -type MeshProjectGroupBindingClient interface { - Read(ctx context.Context, name string) (*MeshProjectGroupBinding, error) - List(ctx context.Context, filter MeshProjectBindingListFilter) ([]MeshProjectGroupBinding, error) - Create(ctx context.Context, binding *MeshProjectGroupBinding) (*MeshProjectGroupBinding, error) - Delete(ctx context.Context, name string) error -} - -type meshProjectGroupBindingClient struct { - meshObject internal.MeshObjectClient[MeshProjectGroupBinding] -} - -func newProjectGroupBindingClient(ctx context.Context, httpClient internal.HttpClient) MeshProjectGroupBindingClient { - return meshProjectGroupBindingClient{internal.NewMeshObjectClient[MeshProjectGroupBinding](ctx, httpClient, "v3", "meshprojectbindings", "groupbindings")} -} - -func (c meshProjectGroupBindingClient) Read(ctx context.Context, name string) (*MeshProjectGroupBinding, error) { - return c.meshObject.Get(ctx, name) -} - -func (c meshProjectGroupBindingClient) List(ctx context.Context, filter MeshProjectBindingListFilter) ([]MeshProjectGroupBinding, error) { - return c.meshObject.List(ctx, http.WithUrlQuery(filter)) -} - -func (c meshProjectGroupBindingClient) Create(ctx context.Context, binding *MeshProjectGroupBinding) (*MeshProjectGroupBinding, error) { - return c.meshObject.Post(ctx, binding) -} +type MeshProjectGroupBindingClient = MeshObjectImmutableClient[MeshProjectGroupBinding, MeshProjectBindingFilter] -func (c meshProjectGroupBindingClient) Delete(ctx context.Context, name string) error { - return c.meshObject.Delete(ctx, name) +func (MeshProjectGroupBinding) meshObjectPath() string { + return "meshprojectbindings/groupbindings" } diff --git a/client/project_user_binding.go b/client/project_user_binding.go index 086d8375..3dfda010 100644 --- a/client/project_user_binding.go +++ b/client/project_user_binding.go @@ -1,12 +1,6 @@ package client -import ( - "context" - - "github.com/meshcloud/meshstack-cli/client/http" - "github.com/meshcloud/meshstack-cli/client/internal" - "github.com/meshcloud/meshstack-cli/client/types/enum" -) +import "github.com/meshcloud/meshstack-cli/client/types/enum" type MeshProjectUserBinding struct { MeshProjectBinding @@ -19,33 +13,8 @@ type MeshUserBindingStatus struct { Approval enum.Entry[MeshBindingApproval] `json:"approval,omitempty" tfsdk:"approval"` } -type MeshProjectUserBindingClient interface { - Read(ctx context.Context, name string) (*MeshProjectUserBinding, error) - List(ctx context.Context, filter MeshProjectBindingListFilter) ([]MeshProjectUserBinding, error) - Create(ctx context.Context, binding *MeshProjectUserBinding) (*MeshProjectUserBinding, error) - Delete(ctx context.Context, name string) error -} - -type meshProjectUserBindingClient struct { - meshObject internal.MeshObjectClient[MeshProjectUserBinding] -} - -func newProjectUserBindingClient(ctx context.Context, httpClient internal.HttpClient) MeshProjectUserBindingClient { - return meshProjectUserBindingClient{internal.NewMeshObjectClient[MeshProjectUserBinding](ctx, httpClient, "v3", "meshprojectbindings", "userbindings")} -} - -func (c meshProjectUserBindingClient) Read(ctx context.Context, name string) (*MeshProjectUserBinding, error) { - return c.meshObject.Get(ctx, name) -} - -func (c meshProjectUserBindingClient) List(ctx context.Context, filter MeshProjectBindingListFilter) ([]MeshProjectUserBinding, error) { - return c.meshObject.List(ctx, http.WithUrlQuery(filter)) -} - -func (c meshProjectUserBindingClient) Create(ctx context.Context, binding *MeshProjectUserBinding) (*MeshProjectUserBinding, error) { - return c.meshObject.Post(ctx, binding) -} +type MeshProjectUserBindingClient = MeshObjectImmutableClient[MeshProjectUserBinding, MeshProjectBindingFilter] -func (c meshProjectUserBindingClient) Delete(ctx context.Context, name string) error { - return c.meshObject.Delete(ctx, name) +func (MeshProjectUserBinding) meshObjectPath() string { + return "meshprojectbindings/userbindings" } diff --git a/client/raw.go b/client/raw.go deleted file mode 100644 index 3931a6fe..00000000 --- a/client/raw.go +++ /dev/null @@ -1,96 +0,0 @@ -package client - -import ( - "context" - "encoding/json/jsontext" - "fmt" - "iter" - "net/url" - "reflect" - "time" - "uuid" - - "github.com/meshcloud/meshstack-cli/client/http" - "github.com/meshcloud/meshstack-cli/client/internal" -) - -type ListOptions = internal.ListOptions - -type Page = internal.Page - -// SortCriteria holds one `property,(asc|desc)` criterion per element, such as createdAt,desc. -type SortCriteria []string - -// RawClient answers with the JSON meshStack sent, for the CLI, which writes it out as it came. -type RawClient struct { - httpClient internal.HttpClient - apis map[reflect.Type]rawApi -} - -type rawApi struct { - internal.MeshObjectApi - - sortsByCreatedAt bool -} - -func newRawClient(httpClient internal.HttpClient) *RawClient { - return &RawClient{httpClient: httpClient, apis: map[reflect.Type]rawApi{}} -} - -// List pages through the objects of M, narrowed by filter, a struct whose fields are the query -// parameters of the listing. -func (r *RawClient) List[M any](ctx context.Context, filter any, options ListOptions) iter.Seq2[jsontext.Value, error] { - api, err := r.api[M]() - if err != nil { - return func(yield func(jsontext.Value, error) bool) { - yield(nil, err) - } - } - // Newest first, an object created while the pages are read would land on a page already read - // and push another one onto the next page, to be listed twice. The fixed until leaves it out; an - // endpoint without until ignores the parameter. The filter's own sort and until win. - newestFirst := url.Values{"until": {time.Now().UTC().Format(time.RFC3339Nano)}} - if api.sortsByCreatedAt { - newestFirst.Set("sort", "createdAt,desc") - } - return api.ListSeqAs[jsontext.Value](ctx, options, http.WithUrlQuery(newestFirst), http.WithUrlQuery(filter)) -} - -// Get reads the object of M with the uuid, or the sub-resource that pathElems name below it. -func (r *RawClient) Get[M any](ctx context.Context, uuid uuid.UUID, pathElems ...string) (jsontext.Value, error) { - api, err := r.api[M]() - if err != nil { - return nil, err - } - return http.UnmarshalJsonBody[jsontext.Value](api.DoRequest(ctx, http.MethodGet, api.ApiUrl.JoinPath(uuid.String()).JoinPath(pathElems...), - http.WithHeader("Accept", api.MeshObjectMimeType()))) -} - -// 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. -func (r *RawClient) DoRequest(ctx context.Context, method, path string, opts ...http.RequestOption) ([]byte, error) { - return http.ReadAllBody(r.httpClient.DoRequest(ctx, method, r.httpClient.EndpointUrl.JoinPath(path), opts...)) -} - -// with makes List and Get reach the objects of M through the API version of meshObject, so that -// the version stays declared once, in the constructor of M's typed client. -func (r *RawClient) with[M any](meshObject internal.MeshObjectClient[M]) *RawClient { - r.apis[reflect.TypeFor[M]()] = rawApi{MeshObjectApi: meshObject.MeshObjectApi, sortsByCreatedAt: true} - return r -} - -// withOwnOrder is with for a listing that answers 400 to any sort key, as that of building block -// definition versions does, which orders by version number. -func (r *RawClient) withOwnOrder[M any](meshObject internal.MeshObjectClient[M]) *RawClient { - r.apis[reflect.TypeFor[M]()] = rawApi{MeshObjectApi: meshObject.MeshObjectApi} - return r -} - -func (r *RawClient) api[M any]() (rawApi, error) { - api, ok := r.apis[reflect.TypeFor[M]()] - if !ok { - return api, fmt.Errorf("the raw client has no API for %s: add its typed client in client.New", reflect.TypeFor[M]()) - } - return api, nil -} diff --git a/client/raw_test.go b/client/raw_test.go deleted file mode 100644 index 4f1a1922..00000000 --- a/client/raw_test.go +++ /dev/null @@ -1,116 +0,0 @@ -package client - -import ( - "encoding/json/jsontext" - "fmt" - "io" - gohttp "net/http" - "slices" - "strings" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/meshcloud/meshstack-cli/client/http" - "github.com/meshcloud/meshstack-cli/client/internal" - "github.com/meshcloud/meshstack-cli/client/types/xurl" - "github.com/meshcloud/meshstack-cli/internal/testutil/fakemeshstack" -) - -func newTestHttpClient(server *fakemeshstack.Server) internal.HttpClient { - return internal.HttpClient{ - AuthorizedClient: http.NewClient(fakemeshstack.UserAgent).WithAuthorization(http.BearerToken(fakemeshstack.Token)), - EndpointUrl: xurl.MustParsef("%s", server.URL), - } -} - -func TestRawClient(t *testing.T) { - const serverPageSize = 2 - var workspaces []string - for i := range 5 { - workspaces = append(workspaces, fmt.Sprintf(`{"kind":"meshWorkspace","apiVersion":"v2","metadata":{"name":"workspace-%d"},`+ - `"_links":{"self":{"href":"http://localhost:8080/api/meshobjects/meshworkspaces/workspace-%d"}}}`, i, i)) - } - var items []any - for _, workspace := range workspaces { - items = append(items, jsontext.Value(workspace)) - } - server := fakemeshstack.Start(t, fakemeshstack.Options{Workspaces: items, PageSize: serverPageSize}) - httpClient := newTestHttpClient(server) - raw := newRawClient(httpClient).with(newWorkspaceClient(t.Context(), httpClient).meshObject) - var requests []fakemeshstack.Request - list := func(t *testing.T, filter MeshWorkspaceListFilter, options ListOptions) (listed []string) { - t.Helper() - server.TakeRequests() - for item, err := range raw.List[MeshWorkspace](t.Context(), filter, options) { - require.NoError(t, err) - listed = append(listed, string(item)) - } - requests = server.TakeRequests() - return listed - } - asked := func(parameter string) (values []string) { - for _, r := range requests { - values = append(values, strings.Join(r.URL.Query()[parameter], " ")) - } - return values - } - - before := time.Now() - // Decoding into MeshWorkspace and encoding again would drop what the model lacks: apiVersion and - // kind, which a POST of the edited object needs, and _links, which shows an LLM agent how - // meshObjects relate. - t.Run("a list yields every item of every page as meshStack sent it", func(t *testing.T) { - assert.Equal(t, workspaces, list(t, MeshWorkspaceListFilter{}, ListOptions{})) - }) - - t.Run("the list asks for newest first, and every page ends at the instant the list started", func(t *testing.T) { - assert.Equal(t, slices.Repeat([]string{"createdAt,desc"}, 3), asked("sort")) - untils := asked("until") - assert.Equal(t, slices.Repeat(untils[:1], 3), untils) - until, err := time.Parse(time.RFC3339Nano, untils[0]) - require.NoError(t, err) - assert.WithinRange(t, until, before, time.Now()) - }) - - // The Terraform provider sets no list options, and must get no page size it did not ask for. - t.Run("without list options a page carries no size", func(t *testing.T) { - assert.Equal(t, []string{"", "", ""}, asked("size")) - }) - - t.Run("a page size asks for pages of that size, and takes the smaller ones meshStack caps it to", func(t *testing.T) { - assert.Equal(t, workspaces, list(t, MeshWorkspaceListFilter{}, ListOptions{PageSize: 3})) - assert.Equal(t, []string{"3", "3", "3"}, asked("size")) - }) - - t.Run("the sort of a filter replaces newest first", func(t *testing.T) { - list(t, MeshWorkspaceListFilter{Sort: []string{"createdAt,desc", "name,asc"}}, ListOptions{}) - assert.Equal(t, slices.Repeat([]string{"createdAt,desc name,asc"}, 3), asked("sort")) - }) - - t.Run("a kind without a typed client fails before it asks meshStack", func(t *testing.T) { - server.TakeRequests() - var failed error - for _, err := range raw.List[MeshTenant](t.Context(), nil, ListOptions{}) { - failed = err - } - require.ErrorContains(t, failed, "client.MeshTenant") - assert.Empty(t, server.TakeRequests()) - }) - - t.Run("DoRequest joins any path onto the endpoint, so the token goes nowhere else", func(t *testing.T) { - server.Route("/", func(w gohttp.ResponseWriter, _ *gohttp.Request) { _, _ = io.WriteString(w, `{}`) }) - server.TakeRequests() - for _, path := range []string{"https://other.host/api/x", "//other.host/api/x"} { - _, err := raw.DoRequest(t.Context(), gohttp.MethodGet, path) - require.NoError(t, err) - } - requests := server.TakeRequests() - require.Len(t, requests, 2) - for _, r := range requests { - assert.Equal(t, httpClient.EndpointUrl.Host, r.Host) - } - }) -} diff --git a/client/service_instance.go b/client/service_instance.go index f62ab334..d43c5f26 100644 --- a/client/service_instance.go +++ b/client/service_instance.go @@ -1,10 +1,6 @@ package client import ( - "context" - - "github.com/meshcloud/meshstack-cli/client/http" - "github.com/meshcloud/meshstack-cli/client/internal" "github.com/meshcloud/meshstack-cli/client/types" ) @@ -28,13 +24,10 @@ type MeshServiceInstanceSpec struct { Parameters map[string]types.Any `json:"parameters" tfsdk:"parameters"` } -type MeshServiceInstanceClient interface { - Read(ctx context.Context, instanceId string) (*MeshServiceInstance, error) - List(ctx context.Context, filter MeshServiceInstanceFilter) ([]MeshServiceInstance, error) -} +type MeshServiceInstanceClient = MeshObjectClient[MeshServiceInstance, MeshServiceInstanceFilter] -type meshServiceInstanceClient struct { - meshObject internal.MeshObjectClient[MeshServiceInstance] +func (instance MeshServiceInstance) meshObjectId() string { + return instance.Metadata.InstanceId } type MeshServiceInstanceFilter struct { @@ -44,15 +37,3 @@ type MeshServiceInstanceFilter struct { ServiceIdentifier *string `json:"serviceIdentifier"` PlanIdentifier *string `json:"planIdentifier"` } - -func newServiceInstanceClient(ctx context.Context, httpClient internal.HttpClient) MeshServiceInstanceClient { - return meshServiceInstanceClient{internal.NewMeshObjectClient[MeshServiceInstance](ctx, httpClient, "v2")} -} - -func (c meshServiceInstanceClient) Read(ctx context.Context, instanceId string) (*MeshServiceInstance, error) { - return c.meshObject.Get(ctx, instanceId) -} - -func (c meshServiceInstanceClient) List(ctx context.Context, filter MeshServiceInstanceFilter) ([]MeshServiceInstance, error) { - return c.meshObject.List(ctx, http.WithUrlQuery(filter)) -} diff --git a/client/tag_definition.go b/client/tag_definition.go index 0e002266..b4ce300d 100644 --- a/client/tag_definition.go +++ b/client/tag_definition.go @@ -1,18 +1,14 @@ package client -import ( - "context" - - "github.com/meshcloud/meshstack-cli/client/internal" -) +type MeshTagDefinitionMetadata = MeshObjectByNameMetadata type MeshTagDefinition struct { Metadata MeshTagDefinitionMetadata `json:"metadata" tfsdk:"metadata"` Spec MeshTagDefinitionSpec `json:"spec" tfsdk:"spec"` } -type MeshTagDefinitionMetadata struct { - Name string `json:"name" tfsdk:"name"` +func (d MeshTagDefinition) meshObjectId() string { + return d.Metadata.meshObjectId() } type MeshTagDefinitionSpec struct { @@ -65,38 +61,4 @@ type TagValueMultiSelect struct { DefaultValue *[]string `json:"defaultValue,omitzero" tfsdk:"default_value"` } -type MeshTagDefinitionClient interface { - List(ctx context.Context) ([]MeshTagDefinition, error) - Read(ctx context.Context, name string) (*MeshTagDefinition, error) - Create(ctx context.Context, tagDefinition *MeshTagDefinition) (*MeshTagDefinition, error) - Update(ctx context.Context, tagDefinition *MeshTagDefinition) (*MeshTagDefinition, error) - Delete(ctx context.Context, name string) error -} - -type meshTagDefinitionClient struct { - meshObject internal.MeshObjectClient[MeshTagDefinition] -} - -func newTagDefinitionClient(ctx context.Context, httpClient internal.HttpClient) MeshTagDefinitionClient { - return meshTagDefinitionClient{internal.NewMeshObjectClient[MeshTagDefinition](ctx, httpClient, "v1")} -} - -func (c meshTagDefinitionClient) List(ctx context.Context) ([]MeshTagDefinition, error) { - return c.meshObject.List(ctx) -} - -func (c meshTagDefinitionClient) Read(ctx context.Context, name string) (*MeshTagDefinition, error) { - return c.meshObject.Get(ctx, name) -} - -func (c meshTagDefinitionClient) Create(ctx context.Context, tagDefinition *MeshTagDefinition) (*MeshTagDefinition, error) { - return c.meshObject.Post(ctx, tagDefinition) -} - -func (c meshTagDefinitionClient) Update(ctx context.Context, tagDefinition *MeshTagDefinition) (*MeshTagDefinition, error) { - return c.meshObject.Put(ctx, tagDefinition.Metadata.Name, tagDefinition) -} - -func (c meshTagDefinitionClient) Delete(ctx context.Context, name string) error { - return c.meshObject.Delete(ctx, name) -} +type MeshTagDefinitionClient = MeshObjectClient[MeshTagDefinition, NoFilter] diff --git a/client/tenant_v4.go b/client/tenant_v4.go index 43a2427f..8a0c118a 100644 --- a/client/tenant_v4.go +++ b/client/tenant_v4.go @@ -1,12 +1,9 @@ package client import ( - "context" "errors" "fmt" - "github.com/meshcloud/meshstack-cli/client/http" - "github.com/meshcloud/meshstack-cli/client/internal" "github.com/meshcloud/meshstack-cli/client/types/enum" ) @@ -28,16 +25,17 @@ type MeshTenantLifecycleAction struct { Timestamp string `json:"timestamp" tfsdk:"-"` } +//nolint:recvcheck // a nil tenant is one that is gone, and meshObjectId reads one that is there type MeshTenant struct { Metadata MeshTenantMetadata `json:"metadata" tfsdk:"metadata"` Spec MeshTenantSpec `json:"spec" tfsdk:"spec"` - Status MeshTenantStatus `json:"status" tfsdk:"status"` + Status MeshTenantStatus `json:"status,omitzero" tfsdk:"status"` } type MeshTenantMetadata struct { - Uuid string `json:"uuid" tfsdk:"uuid"` - OwnedByProject string `json:"ownedByProject" tfsdk:"owned_by_project"` - OwnedByWorkspace string `json:"ownedByWorkspace" tfsdk:"owned_by_workspace"` + Uuid *string `json:"uuid,omitzero" tfsdk:"uuid"` + OwnedByProject string `json:"ownedByProject" tfsdk:"owned_by_project"` + OwnedByWorkspace string `json:"ownedByWorkspace" tfsdk:"owned_by_workspace"` } type MeshTenantSpec struct { @@ -46,7 +44,7 @@ type MeshTenantSpec struct { LandingZoneRef *NamedRef `json:"landingZoneRef" tfsdk:"landing_zone_ref"` // RequestedQuotas is an input at creation only: the backend does not return it on read, so the // Terraform resource keeps the configured value from its state. - RequestedQuotas map[string]RequestQuotaValue `json:"requestedQuotas" tfsdk:"requested_quotas"` + RequestedQuotas map[string]RequestQuotaValue `json:"requestedQuotas,omitempty" tfsdk:"requested_quotas"` } type MeshTenantStatus struct { @@ -82,24 +80,7 @@ type AppliedQuotaValue struct { Value int64 `json:"value" tfsdk:"value"` } -type MeshTenantCreate struct { - Metadata MeshTenantCreateMetadata `json:"metadata" tfsdk:"metadata"` - Spec MeshTenantCreateSpec `json:"spec" tfsdk:"spec"` -} - -type MeshTenantCreateMetadata struct { - OwnedByProject string `json:"ownedByProject" tfsdk:"owned_by_project"` - OwnedByWorkspace string `json:"ownedByWorkspace" tfsdk:"owned_by_workspace"` -} - -type MeshTenantCreateSpec struct { - PlatformRef UuidRef `json:"platformRef" tfsdk:"platform_ref"` - LandingZoneRef *NamedRef `json:"landingZoneRef" tfsdk:"landing_zone_ref"` - PlatformTenantId *string `json:"platformTenantId" tfsdk:"platform_tenant_id"` - RequestedQuotas map[string]RequestQuotaValue `json:"requestedQuotas,omitempty" tfsdk:"requested_quotas"` -} - -type MeshTenantQuery struct { +type MeshTenantFilter struct { Workspace string `json:"workspaceIdentifier"` Project *string `json:"projectIdentifier"` Platform *string `json:"platformIdentifier"` @@ -108,43 +89,7 @@ type MeshTenantQuery struct { PlatformTenant *string `json:"platformTenantId"` } -type MeshTenantClient interface { - Read(ctx context.Context, uuid string) (*MeshTenant, error) - ReadFunc(uuid string) func(ctx context.Context) (*MeshTenant, error) - List(ctx context.Context, query MeshTenantQuery) ([]MeshTenant, error) - Create(ctx context.Context, tenant *MeshTenantCreate) (*MeshTenant, error) - Delete(ctx context.Context, uuid string) error -} - -type meshTenantClient struct { - meshObject internal.MeshObjectClient[MeshTenant] -} - -func newTenantClient(ctx context.Context, httpClient internal.HttpClient) MeshTenantClient { - return meshTenantClient{internal.NewMeshObjectClient[MeshTenant](ctx, httpClient, "v4")} -} - -func (c meshTenantClient) Read(ctx context.Context, uuid string) (*MeshTenant, error) { - return c.ReadFunc(uuid)(ctx) -} - -func (c meshTenantClient) ReadFunc(uuid string) func(ctx context.Context) (*MeshTenant, error) { - return func(ctx context.Context) (*MeshTenant, error) { - return c.meshObject.Get(ctx, uuid) - } -} - -func (c meshTenantClient) Create(ctx context.Context, tenant *MeshTenantCreate) (*MeshTenant, error) { - return c.meshObject.Post(ctx, tenant) -} - -func (c meshTenantClient) List(ctx context.Context, query MeshTenantQuery) ([]MeshTenant, error) { - return c.meshObject.List(ctx, http.WithUrlQuery(query)) -} - -func (c meshTenantClient) Delete(ctx context.Context, uuid string) error { - return c.meshObject.Delete(ctx, uuid) -} +type MeshTenantClient = MeshObjectImmutableClient[MeshTenant, MeshTenantFilter] func (tenant *MeshTenant) CreationSuccessful() (done bool, err error) { switch { @@ -167,6 +112,10 @@ func (tenant *MeshTenant) DeletionState() string { return tenant.Status.Lifecycle.deletionState() } +func (tenant MeshTenant) meshObjectId() string { + return *tenant.Metadata.Uuid +} + const tenantNotObserved = "no successful read after the delete request" func (lifecycle MeshTenantLifecycle) deletionState() string { diff --git a/client/tenant_v4_deletion_test.go b/client/tenant_v4_deletion_test.go index 0bbd0907..173adde8 100644 --- a/client/tenant_v4_deletion_test.go +++ b/client/tenant_v4_deletion_test.go @@ -23,7 +23,6 @@ func TestMeshTenantDeletion(t *testing.T) { {"a tenant marked for deletion is not deleted yet, and says since when", &MeshTenant{Status: MeshTenantStatus{Lifecycle: markedForDeletion}}, false, "MARKED_FOR_DELETION since 2026-07-30T16:14:14Z"}, {"a tenant marked for deletion at no time is not deleted yet, and says what it awaits", &MeshTenant{Status: MeshTenantStatus{Lifecycle: MeshTenantLifecycle{State: TenantLifecycleStateMarkedForDeletion}}}, false, "MARKED_FOR_DELETION, awaiting"}, {"an active tenant is not deleted, as meshStack has not acted on it", &MeshTenant{Status: MeshTenantStatus{Lifecycle: MeshTenantLifecycle{State: TenantLifecycleStateActive}}}, false, "has not acted on it"}, - {"a tenant without a lifecycle is not deleted, as meshStack has not acted on it", &MeshTenant{Metadata: MeshTenantMetadata{Uuid: "test-uuid"}}, false, "has not acted on it"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/client/types/clienttypes.go b/client/types/clienttypes.go index 43331ec7..508ace65 100644 --- a/client/types/clienttypes.go +++ b/client/types/clienttypes.go @@ -4,7 +4,7 @@ import ( "reflect" "strings" - "github.com/meshcloud/meshstack-cli/client/types/variant" + "github.com/meshcloud/meshstack-cli/client/types/polymorph" ) type ( @@ -17,7 +17,7 @@ type ( Hash *string `json:"hash,omitzero" tfsdk:"-"` } - SecretOrAny = variant.Variant[Secret, any] + SecretOrAny = polymorph.Variant[Secret, any] Any any ) diff --git a/client/types/hal/link.go b/client/types/hal/link.go new file mode 100644 index 00000000..4136cc97 --- /dev/null +++ b/client/types/hal/link.go @@ -0,0 +1,57 @@ +package hal + +import ( + "context" + "encoding/json/jsontext" + "errors" + "fmt" + "io" + + "github.com/meshcloud/meshstack-cli/client/http" + "github.com/meshcloud/meshstack-cli/internal/json" +) + +var ErrNoLink = errors.New("meshStack sent no link") + +type Links map[string]Link + +type Link struct { + Href string `json:"href"` + + action LinkAction +} + +type LinkAction func(ctx context.Context, method, href string, options ...http.RequestOption) (io.ReadCloser, error) + +func NewLink(href string, action LinkAction) Link { + return Link{Href: href, action: action} +} + +func LinkUnmarshalers(action LinkAction) *json.Unmarshalers { + return json.UnmarshalFromFunc(func(_ *jsontext.Decoder, l *Link) error { + l.action = action + return errors.ErrUnsupported + }) +} + +func (ls Links) Get[R any](ctx context.Context, rel string, options ...http.RequestOption) (R, error) { + return follow[R](ctx, ls, http.MethodGet, rel, options) +} + +func (ls Links) Post[R any](ctx context.Context, rel string, payload any, options ...http.RequestOption) (R, error) { + return follow[R](ctx, ls, http.MethodPost, rel, append(options, http.WithJsonBody(payload))) +} + +func (ls Links) Delete(ctx context.Context, rel string, options ...http.RequestOption) error { + _, err := follow[struct{}](ctx, ls, http.MethodDelete, rel, options) + return err +} + +func follow[R any](ctx context.Context, ls Links, method, rel string, options []http.RequestOption) (result R, _ error) { + link, found := ls[rel] + if !found || link.action == nil { + return result, fmt.Errorf("%w %q", ErrNoLink, rel) + } + body, err := link.action(ctx, method, link.Href, options...) + return http.UnmarshalJsonBody[R](body, err, LinkUnmarshalers(link.action)) +} diff --git a/client/types/hal/link_test.go b/client/types/hal/link_test.go new file mode 100644 index 00000000..3ec18199 --- /dev/null +++ b/client/types/hal/link_test.go @@ -0,0 +1,34 @@ +package hal_test + +import ( + "context" + "io" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/meshcloud/meshstack-cli/client/http" + "github.com/meshcloud/meshstack-cli/client/types/hal" +) + +func TestLinksFollowALinkAndGiveTheLinksOfTheAnswerTheSameAction(t *testing.T) { + var followed []string + action := func(_ context.Context, method, href string, _ ...http.RequestOption) (io.ReadCloser, error) { + followed = append(followed, method+" "+href) + return io.NopCloser(strings.NewReader(`{"_links": {"next": {"href": "/second"}}}`)), nil + } + type page struct { + Links hal.Links `json:"_links"` + } + links := hal.Links{"first": hal.NewLink("/first", action)} + + answer, err := links.Get[page](t.Context(), "first") + require.NoError(t, err) + _, err = answer.Links.Post[page](t.Context(), "next", nil) + require.NoError(t, err) + assert.Equal(t, []string{"GET /first", "POST /second"}, followed) + + require.ErrorIs(t, links.Delete(t.Context(), "missing"), hal.ErrNoLink) +} diff --git a/client/types/page.go b/client/types/page.go new file mode 100644 index 00000000..51ea8d98 --- /dev/null +++ b/client/types/page.go @@ -0,0 +1,8 @@ +package types + +type Page struct { + Size int `json:"size"` + TotalElements int `json:"totalElements"` + TotalPages int `json:"totalPages"` + Number int `json:"number"` +} diff --git a/client/types/polymorph/polymorph.go b/client/types/polymorph/polymorph.go new file mode 100644 index 00000000..331923eb --- /dev/null +++ b/client/types/polymorph/polymorph.go @@ -0,0 +1,195 @@ +// Package polymorph reads and writes a struct as Jackson's +// @JsonTypeInfo(use = NAME, include = PROPERTY, property = "type") does. The struct embeds Polymorph +// first and tags one pointer per subtype polymorph:"", with ,inline for fields next to "type". +package polymorph + +import ( + "bytes" + "encoding/json/jsontext" + "errors" + "fmt" + "reflect" + "strings" + "unsafe" + + "github.com/meshcloud/meshstack-cli/client/types/enum" + "github.com/meshcloud/meshstack-cli/internal/json" +) + +type Polymorph[T any, E ~string] struct { + Type enum.Entry[E] `tfsdk:"-"` +} + +func (p *Polymorph[T, E]) MarshalJSONTo(enc *jsontext.Encoder) error { + typeName := p.Type + if typeName == "" { + var err error + if typeName, err = p.InferType(); err != nil { + return err + } + } + return p.outer().marshal(enc, string(typeName)) +} + +func (p *Polymorph[T, E]) UnmarshalJSONFrom(dec *jsontext.Decoder) error { + typeName, err := p.outer().unmarshal(dec) + p.Type = enum.Entry[E](typeName) + return err +} + +func (p *Polymorph[T, E]) InferType() (enum.Entry[E], error) { + typeName, err := p.outer().inferType() + return enum.Entry[E](typeName), err +} + +// outer is the T that embeds p. As the first field, p has the address of T. +func (p *Polymorph[T, E]) outer() polymorphic { + t := reflect.TypeFor[T]() + if t.Kind() != reflect.Struct || t.NumField() == 0 || t.Field(0).Type != reflect.TypeFor[Polymorph[T, E]]() { + panic(fmt.Sprintf("%s needs polymorph.Polymorph as its first field", t)) + } + return newPolymorphic(reflect.ValueOf((*T)(unsafe.Pointer(p))).Elem()) //nolint:gosec // the check above makes p the address of T +} + +type polymorphic struct { + value reflect.Value + subtypes []subtype +} + +type subtype struct { + index int + name string + member string +} + +func newPolymorphic(value reflect.Value) polymorphic { + p := polymorphic{value: value} + for i := range value.NumField() { + field := value.Type().Field(i) + tag, tagged := field.Tag.Lookup("polymorph") + if !tagged { + continue + } + name, inline := strings.CutSuffix(tag, ",inline") + s := subtype{index: i, name: name} + if !inline { + s.member, _, _ = strings.Cut(field.Tag.Get("json"), ",") + } + p.subtypes = append(p.subtypes, s) + } + if len(p.subtypes) == 0 { + panic(fmt.Sprintf("%s needs a field tagged polymorph", value.Type())) + } + return p +} + +func (p polymorphic) marshal(enc *jsontext.Encoder, typeName string) error { + if err := enc.WriteToken(jsontext.BeginObject); err != nil { + return err + } + if err := errors.Join(enc.WriteToken(jsontext.String("type")), enc.WriteToken(jsontext.String(typeName))); err != nil { + return err + } + for _, s := range p.subtypes { + subtype := p.value.Field(s.index) + if subtype.IsNil() { + continue + } + if err := s.marshal(enc, subtype.Interface()); err != nil { + return err + } + } + return enc.WriteToken(jsontext.EndObject) +} + +func (p polymorphic) unmarshal(dec *jsontext.Decoder) (typeName string, _ error) { + raw, err := dec.ReadValue() + if err != nil { + return "", err + } + p.value.SetZero() + if raw.Kind() == jsontext.KindNull { + return "", nil + } + var members map[string]jsontext.Value + if err = json.Unmarshal(raw, &members, dec.Options()); err != nil { + return "", err + } + if encodedType, ok := members["type"]; ok { + if err = json.Unmarshal(encodedType, &typeName); err != nil { + return "", err + } + } + for _, s := range p.subtypes { + if s.name != typeName { + continue + } + field := p.value.Field(s.index) + subtype := reflect.New(field.Type().Elem()) + encoded := raw + if s.member != "" { + var sent bool + if encoded, sent = members[s.member]; !sent && subtype.Elem().NumField() > 0 { + return typeName, nil + } + } + if len(encoded) > 0 { + if err = json.Unmarshal(encoded, subtype.Interface(), dec.Options()); err != nil { + return typeName, fmt.Errorf("%s: %w", typeName, err) + } + } + field.Set(subtype) + } + return typeName, nil +} + +func (p polymorphic) inferType() (string, error) { + var result string + for _, s := range p.subtypes { + if p.value.Field(s.index).IsNil() { + continue + } + if result != "" { + return "", fmt.Errorf("%s: more than one subtype is set: %s and %s", p.value.Type(), result, s.name) + } + result = s.name + } + if result == "" { + return "", fmt.Errorf("%s: no subtype is set", p.value.Type()) + } + return result, nil +} + +func (s subtype) marshal(enc *jsontext.Encoder, subtype any) error { + if s.member != "" { + if err := enc.WriteToken(jsontext.String(s.member)); err != nil { + return err + } + return json.MarshalEncode(enc, subtype, enc.Options()) + } + encoded, err := json.Marshal(subtype, enc.Options()) + if err != nil { + return err + } + fields := jsontext.NewDecoder(bytes.NewReader(encoded)) + if _, err = fields.ReadToken(); err != nil { + return err + } + for fields.PeekKind() != jsontext.KindEndObject { + name, err := fields.ReadToken() + if err != nil { + return err + } + if err = enc.WriteToken(name); err != nil { + return err + } + fieldValue, err := fields.ReadValue() + if err != nil { + return err + } + if err = enc.WriteValue(fieldValue); err != nil { + return err + } + } + return nil +} diff --git a/client/types/polymorph/polymorph_test.go b/client/types/polymorph/polymorph_test.go new file mode 100644 index 00000000..fe109199 --- /dev/null +++ b/client/types/polymorph/polymorph_test.go @@ -0,0 +1,61 @@ +package polymorph_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/meshcloud/meshstack-cli/client/types/polymorph" + "github.com/meshcloud/meshstack-cli/internal/json" +) + +type circle struct{} + +type square struct { + Side int `json:"side"` +} + +type flat struct { + polymorph.Polymorph[flat, string] + + Circle *circle `polymorph:"circle,inline"` + Square *square `polymorph:"square,inline"` +} + +type nested struct { + polymorph.Polymorph[nested, string] + + Circle *circle `json:"circle" polymorph:"circle"` + Square *square `json:"square" polymorph:"square"` +} + +func TestPolymorph(t *testing.T) { + t.Run("an inline subtype sits next to the type", func(t *testing.T) { + encoded, err := json.Marshal(flat{Square: &square{Side: 2}}) + require.NoError(t, err) + assert.JSONEq(t, `{"type":"square","side":2}`, string(encoded)) + + var decoded flat + require.NoError(t, json.Unmarshal(encoded, &decoded)) + assert.Equal(t, flat{Type: "square", Square: &square{Side: 2}}, decoded) + }) + + t.Run("a nested subtype sits in its member, and one without fields needs none", func(t *testing.T) { + encoded, err := json.Marshal(nested{Square: &square{Side: 2}}) + require.NoError(t, err) + assert.JSONEq(t, `{"type":"square","square":{"side":2}}`, string(encoded)) + + var decoded nested + require.NoError(t, json.Unmarshal([]byte(`{"type":"circle"}`), &decoded)) + assert.Equal(t, nested{Type: "circle", Circle: &circle{}}, decoded) + require.NoError(t, json.Unmarshal([]byte(`{"type":"square"}`), &decoded)) + assert.Equal(t, nested{Type: "square"}, decoded, "meshStack leaves out the subtype for a reader that may not see it") + }) + + t.Run("an unknown type decodes to the type alone", func(t *testing.T) { + var decoded flat + require.NoError(t, json.Unmarshal([]byte(`{"type":"triangle","corners":3}`), &decoded)) + assert.Equal(t, flat{Type: "triangle"}, decoded) + }) +} diff --git a/client/types/variant/variant.go b/client/types/polymorph/variant.go similarity index 89% rename from client/types/variant/variant.go rename to client/types/polymorph/variant.go index e138694a..4c85c091 100644 --- a/client/types/variant/variant.go +++ b/client/types/polymorph/variant.go @@ -1,4 +1,4 @@ -package variant +package polymorph import ( "encoding/json/jsontext" @@ -49,22 +49,6 @@ func (v Variant[X, Y]) HasY() bool { return has[Y](v.Y) } -func (v Variant[X, Y]) WithX(action func(x *X)) { - if v.HasX() { - action(&v.X) - } else { - action(nil) - } -} - -func (v Variant[X, Y]) WithY(action func(y *Y)) { - if v.HasY() { - action(&v.Y) - } else { - action(nil) - } -} - func (v *Variant[X, Y]) UnmarshalJSONFrom(dec *jsontext.Decoder) error { bytes, err := dec.ReadValue() if err != nil { diff --git a/client/types/variant/infer.go b/client/types/variant/infer.go deleted file mode 100644 index cf20c631..00000000 --- a/client/types/variant/infer.go +++ /dev/null @@ -1,35 +0,0 @@ -package variant - -import ( - "errors" - "fmt" - - "github.com/meshcloud/meshstack-cli/client/types/enum" -) - -type Candidate[T ~string] struct { - Type enum.Entry[T] - IsSet bool -} - -func NewCandidate[T ~string](typ enum.Entry[T], isSet bool) Candidate[T] { - return Candidate[T]{Type: typ, IsSet: isSet} -} - -// InferType returns the type of the one candidate that is set. -func InferType[T ~string](candidates ...Candidate[T]) (enum.Entry[T], error) { - var result enum.Entry[T] - for _, candidate := range candidates { - if !candidate.IsSet { - continue - } - if len(result) > 0 { - return "", fmt.Errorf("more than one variant is set: %s and %s", result, candidate.Type) - } - result = candidate.Type - } - if len(result) == 0 { - return "", errors.New("no variant is set") - } - return result, nil -} diff --git a/client/types/variant/infer_test.go b/client/types/variant/infer_test.go deleted file mode 100644 index 8a937419..00000000 --- a/client/types/variant/infer_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package variant - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/meshcloud/meshstack-cli/client/types/enum" -) - -type shape string - -const ( - circle enum.Entry[shape] = "circle" - square enum.Entry[shape] = "square" -) - -type shapeHolder struct { - Circle *struct{} - Square *struct{ Side int } -} - -func (s shapeHolder) inferType() (enum.Entry[shape], error) { - return InferType( - NewCandidate(circle, s.Circle != nil), - NewCandidate(square, s.Square != nil), - ) -} - -func TestInferType(t *testing.T) { - t.Run("an empty struct counts as set", func(t *testing.T) { - got, err := shapeHolder{Circle: &struct{}{}}.inferType() - require.NoError(t, err) - assert.Equal(t, circle, got) - }) - - t.Run("one variant", func(t *testing.T) { - got, err := shapeHolder{Square: &struct{ Side int }{Side: 2}}.inferType() - require.NoError(t, err) - assert.Equal(t, square, got) - }) - - t.Run("no variant", func(t *testing.T) { - _, err := shapeHolder{}.inferType() - require.EqualError(t, err, "no variant is set") - }) - - t.Run("several variants", func(t *testing.T) { - _, err := shapeHolder{Circle: &struct{}{}, Square: &struct{ Side int }{}}.inferType() - require.EqualError(t, err, "more than one variant is set: circle and square") - }) -} diff --git a/client/types/xurl/url.go b/client/types/xurl/url.go index a1cc1a52..b890cb2b 100644 --- a/client/types/xurl/url.go +++ b/client/types/xurl/url.go @@ -62,20 +62,6 @@ func (u URL) Clone() URL { return URL{u.URL.Clone()} } -// PathTo is the path of target below u, and false where u does not hold target. A near match, such -// as https://x.io/ab for https://x.io/a, is false as well, because a caller sends u's credential to -// target. -func (u URL) PathTo(target *url.URL) (string, bool) { - if u.URL == nil || target == nil || !strings.EqualFold(target.Scheme, u.Scheme) || !strings.EqualFold(target.Host, u.Host) { - return "", false - } - path, found := strings.CutPrefix(target.Path, strings.TrimSuffix(u.Path, "/")) - if !found || path != "" && !strings.HasPrefix(path, "/") { - return "", false - } - return path, true -} - func (u URL) isLoopback() bool { hostname := u.Hostname() if hostname == "localhost" { diff --git a/client/user.go b/client/user.go index f0b433f0..979bdf10 100644 --- a/client/user.go +++ b/client/user.go @@ -1,12 +1,5 @@ package client -import ( - "context" - - "github.com/meshcloud/meshstack-cli/client/http" - "github.com/meshcloud/meshstack-cli/client/internal" -) - type MeshUser struct { Metadata MeshUserMetadata `json:"metadata" tfsdk:"metadata"` Spec MeshUserSpec `json:"spec" tfsdk:"spec"` @@ -35,7 +28,7 @@ type MeshUserLifecycle struct { State string `json:"state" tfsdk:"state"` } -type MeshUserListFilter struct { +type MeshUserFilter struct { Uuid string `json:"uuid"` Username string `json:"username"` Email string `json:"email"` @@ -45,23 +38,8 @@ type MeshUserListFilter struct { ProjectIdentifier string `json:"projectIdentifier"` } -type MeshUserClient interface { - List(ctx context.Context, filter MeshUserListFilter) ([]MeshUser, error) - Read(ctx context.Context, username string) (*MeshUser, error) -} - -type meshUserClient struct { - meshObject internal.MeshObjectClient[MeshUser] -} - -func newUserClient(ctx context.Context, httpClient internal.HttpClient) meshUserClient { - return meshUserClient{internal.NewMeshObjectClient[MeshUser](ctx, httpClient, "v2")} -} - -func (c meshUserClient) List(ctx context.Context, filter MeshUserListFilter) ([]MeshUser, error) { - return c.meshObject.List(ctx, http.WithUrlQuery(filter)) -} +type MeshUserClient = MeshObjectClient[MeshUser, MeshUserFilter] -func (c meshUserClient) Read(ctx context.Context, username string) (*MeshUser, error) { - return c.meshObject.Get(ctx, username) +func (user MeshUser) meshObjectId() string { + return user.Metadata.Name } diff --git a/client/uuid_filter_test.go b/client/uuid_filter_test.go deleted file mode 100644 index 806c7680..00000000 --- a/client/uuid_filter_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package client - -import ( - "testing" - "uuid" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/meshcloud/meshstack-cli/internal/testutil/fakemeshstack" -) - -func TestAUuidOfAFilterGoesAsItsTextAndAZeroOneNotAtAll(t *testing.T) { - server := fakemeshstack.Start(t, fakemeshstack.Options{}) - httpClient := newTestHttpClient(server) - raw := newRawClient(httpClient).with(newBuildingBlockRunClient(t.Context(), httpClient).meshObject) - - for _, filter := range []MeshBuildingBlockRunListFilter{ - {BuildingBlockUuid: uuid.MustParse("0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90")}, - {}, - } { - for _, err := range raw.List[MeshBuildingBlockRun](t.Context(), filter, ListOptions{}) { - require.NoError(t, err) - } - } - - requests := server.TakeRequests() - require.Len(t, requests, 2) - assert.Equal(t, []string{"0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90"}, requests[0].URL.Query()["buildingBlockUuid"]) - assert.NotContains(t, requests[1].URL.Query(), "buildingBlockUuid") -} - -func TestListingTheVersionsOfADefinitionRejectsAnIdOfNoUuidBeforeItAsksMeshStack(t *testing.T) { - server := fakemeshstack.Start(t, fakemeshstack.Options{}) - versions := newBuildingBlockDefinitionVersionClient(t.Context(), newTestHttpClient(server)) - - _, err := versions.List(t.Context(), "my-definition") - - require.EqualError(t, err, `building block definition "my-definition": invalid uuid`) - assert.Empty(t, server.TakeRequests()) -} diff --git a/client/workspace.go b/client/workspace.go index 85830420..6504da03 100644 --- a/client/workspace.go +++ b/client/workspace.go @@ -1,20 +1,17 @@ package client -import ( - "context" - - "github.com/meshcloud/meshstack-cli/client/internal" -) +import "github.com/meshcloud/meshstack-cli/client/types/hal" type MeshWorkspace struct { Metadata MeshWorkspaceMetadata `json:"metadata" tfsdk:"metadata"` Spec MeshWorkspaceSpec `json:"spec" tfsdk:"spec"` + Links hal.Links `json:"_links,omitzero" tfsdk:"-"` } type MeshWorkspaceMetadata struct { Name string `json:"name" tfsdk:"name"` - CreatedOn string `json:"createdOn" tfsdk:"created_on"` - DeletedOn *string `json:"deletedOn" tfsdk:"deleted_on"` + CreatedOn string `json:"createdOn,omitzero" tfsdk:"created_on"` + DeletedOn *string `json:"deletedOn,omitzero" tfsdk:"deleted_on"` Tags map[string][]string `json:"tags" tfsdk:"tags"` } @@ -23,53 +20,8 @@ type MeshWorkspaceSpec struct { PlatformBuilderAccessEnabled *bool `json:"platformBuilderAccessEnabled,omitzero" tfsdk:"platform_builder_access_enabled"` } -type MeshWorkspaceCreate struct { - Metadata MeshWorkspaceCreateMetadata `json:"metadata" tfsdk:"metadata"` - Spec MeshWorkspaceSpec `json:"spec" tfsdk:"spec"` -} -type MeshWorkspaceCreateMetadata struct { - Name string `json:"name" tfsdk:"name"` - Tags map[string][]string `json:"tags" tfsdk:"tags"` -} - -type MeshWorkspaceListFilter struct { - Sort SortCriteria `json:"sort"` -} - -type MeshWorkspaceClient interface { - // List returns every workspace the credential can see. An unscoped user token reaches this and - // almost nothing else, which is why `meshstack login` prompts for a workspace from it. - List(ctx context.Context) ([]MeshWorkspace, error) - Read(ctx context.Context, name string) (*MeshWorkspace, error) - Create(ctx context.Context, workspace *MeshWorkspaceCreate) (*MeshWorkspace, error) - Update(ctx context.Context, name string, workspace *MeshWorkspaceCreate) (*MeshWorkspace, error) - Delete(ctx context.Context, name string) error -} - -type meshWorkspaceClient struct { - meshObject internal.MeshObjectClient[MeshWorkspace] -} - -func newWorkspaceClient(ctx context.Context, httpClient internal.HttpClient) meshWorkspaceClient { - return meshWorkspaceClient{internal.NewMeshObjectClient[MeshWorkspace](ctx, httpClient, "v2")} -} - -func (c meshWorkspaceClient) List(ctx context.Context) ([]MeshWorkspace, error) { - return c.meshObject.List(ctx) -} - -func (c meshWorkspaceClient) Read(ctx context.Context, name string) (*MeshWorkspace, error) { - return c.meshObject.Get(ctx, name) -} - -func (c meshWorkspaceClient) Create(ctx context.Context, workspace *MeshWorkspaceCreate) (*MeshWorkspace, error) { - return c.meshObject.Post(ctx, workspace) -} - -func (c meshWorkspaceClient) Update(ctx context.Context, name string, workspace *MeshWorkspaceCreate) (*MeshWorkspace, error) { - return c.meshObject.Put(ctx, name, workspace) -} +type MeshWorkspaceClient = MeshObjectClient[MeshWorkspace, NoFilter] -func (c meshWorkspaceClient) Delete(ctx context.Context, name string) error { - return c.meshObject.Delete(ctx, name) +func (workspace MeshWorkspace) meshObjectId() string { + return workspace.Metadata.Name } diff --git a/client/workspace_binding.go b/client/workspace_binding.go index 8d2892be..e187cbd9 100644 --- a/client/workspace_binding.go +++ b/client/workspace_binding.go @@ -1,15 +1,11 @@ package client type MeshWorkspaceBinding struct { - Metadata MeshWorkspaceBindingMetadata `json:"metadata" tfsdk:"metadata"` - RoleRef MeshWorkspaceRoleRef `json:"roleRef" tfsdk:"role_ref"` - TargetRef MeshWorkspaceTargetRef `json:"targetRef" tfsdk:"target_ref"` - Subject MeshWorkspaceSubject `json:"subject" tfsdk:"subject"` - ExpiryDate *string `json:"expiryDate,omitzero" tfsdk:"expiry_date"` -} - -type MeshWorkspaceBindingMetadata struct { - Name string `json:"name" tfsdk:"name"` + Metadata MeshObjectByNameMetadata `json:"metadata" tfsdk:"metadata"` + RoleRef MeshWorkspaceRoleRef `json:"roleRef" tfsdk:"role_ref"` + TargetRef MeshWorkspaceTargetRef `json:"targetRef" tfsdk:"target_ref"` + Subject MeshWorkspaceSubject `json:"subject" tfsdk:"subject"` + ExpiryDate *string `json:"expiryDate,omitzero" tfsdk:"expiry_date"` } type MeshWorkspaceRoleRef struct { @@ -24,9 +20,13 @@ type MeshWorkspaceSubject struct { Name string `json:"name" tfsdk:"name"` } -type MeshWorkspaceBindingListFilter struct { +type MeshWorkspaceBindingFilter struct { WorkspaceIdentifier *string `json:"workspaceIdentifier"` WorkspaceRole *string `json:"workspaceRole"` // Username matches a user binding of that user, or a group binding of a group the user is in. Username *string `json:"username"` } + +func (binding MeshWorkspaceBinding) meshObjectId() string { + return binding.Metadata.meshObjectId() +} diff --git a/client/workspace_group_binding.go b/client/workspace_group_binding.go index 187da981..3c668330 100644 --- a/client/workspace_group_binding.go +++ b/client/workspace_group_binding.go @@ -1,45 +1,13 @@ package client -import ( - "context" - - "github.com/meshcloud/meshstack-cli/client/http" - "github.com/meshcloud/meshstack-cli/client/internal" -) - type MeshWorkspaceGroupBinding struct { MeshWorkspaceBinding Status *MeshGroupBindingStatus `json:"status,omitempty" tfsdk:"status"` } -type MeshWorkspaceGroupBindingClient interface { - Read(ctx context.Context, name string) (*MeshWorkspaceGroupBinding, error) - List(ctx context.Context, filter MeshWorkspaceBindingListFilter) ([]MeshWorkspaceGroupBinding, error) - Create(ctx context.Context, binding *MeshWorkspaceGroupBinding) (*MeshWorkspaceGroupBinding, error) - Delete(ctx context.Context, name string) error -} - -type meshWorkspaceGroupBindingClient struct { - meshObject internal.MeshObjectClient[MeshWorkspaceGroupBinding] -} - -func newWorkspaceGroupBindingClient(ctx context.Context, httpClient internal.HttpClient) MeshWorkspaceGroupBindingClient { - return meshWorkspaceGroupBindingClient{internal.NewMeshObjectClient[MeshWorkspaceGroupBinding](ctx, httpClient, "v2", "meshworkspacebindings", "groupbindings")} -} - -func (c meshWorkspaceGroupBindingClient) Read(ctx context.Context, name string) (*MeshWorkspaceGroupBinding, error) { - return c.meshObject.Get(ctx, name) -} - -func (c meshWorkspaceGroupBindingClient) List(ctx context.Context, filter MeshWorkspaceBindingListFilter) ([]MeshWorkspaceGroupBinding, error) { - return c.meshObject.List(ctx, http.WithUrlQuery(filter)) -} - -func (c meshWorkspaceGroupBindingClient) Create(ctx context.Context, binding *MeshWorkspaceGroupBinding) (*MeshWorkspaceGroupBinding, error) { - return c.meshObject.Post(ctx, binding) -} +type MeshWorkspaceGroupBindingClient = MeshObjectClient[MeshWorkspaceGroupBinding, MeshWorkspaceBindingFilter] -func (c meshWorkspaceGroupBindingClient) Delete(ctx context.Context, name string) error { - return c.meshObject.Delete(ctx, name) +func (MeshWorkspaceGroupBinding) meshObjectPath() string { + return "meshworkspacebindings/groupbindings" } diff --git a/client/workspace_user_binding.go b/client/workspace_user_binding.go index 3575eae8..781cb40d 100644 --- a/client/workspace_user_binding.go +++ b/client/workspace_user_binding.go @@ -1,45 +1,13 @@ package client -import ( - "context" - - "github.com/meshcloud/meshstack-cli/client/http" - "github.com/meshcloud/meshstack-cli/client/internal" -) - type MeshWorkspaceUserBinding struct { MeshWorkspaceBinding Status *MeshUserBindingStatus `json:"status,omitempty" tfsdk:"status"` } -type MeshWorkspaceUserBindingClient interface { - Read(ctx context.Context, name string) (*MeshWorkspaceUserBinding, error) - List(ctx context.Context, filter MeshWorkspaceBindingListFilter) ([]MeshWorkspaceUserBinding, error) - Create(ctx context.Context, binding *MeshWorkspaceUserBinding) (*MeshWorkspaceUserBinding, error) - Delete(ctx context.Context, name string) error -} - -type meshWorkspaceUserBindingClient struct { - meshObject internal.MeshObjectClient[MeshWorkspaceUserBinding] -} - -func newWorkspaceUserBindingClient(ctx context.Context, httpClient internal.HttpClient) MeshWorkspaceUserBindingClient { - return meshWorkspaceUserBindingClient{internal.NewMeshObjectClient[MeshWorkspaceUserBinding](ctx, httpClient, "v2", "meshworkspacebindings", "userbindings")} -} - -func (c meshWorkspaceUserBindingClient) Read(ctx context.Context, name string) (*MeshWorkspaceUserBinding, error) { - return c.meshObject.Get(ctx, name) -} - -func (c meshWorkspaceUserBindingClient) List(ctx context.Context, filter MeshWorkspaceBindingListFilter) ([]MeshWorkspaceUserBinding, error) { - return c.meshObject.List(ctx, http.WithUrlQuery(filter)) -} - -func (c meshWorkspaceUserBindingClient) Create(ctx context.Context, binding *MeshWorkspaceUserBinding) (*MeshWorkspaceUserBinding, error) { - return c.meshObject.Post(ctx, binding) -} +type MeshWorkspaceUserBindingClient = MeshObjectImmutableClient[MeshWorkspaceUserBinding, MeshWorkspaceBindingFilter] -func (c meshWorkspaceUserBindingClient) Delete(ctx context.Context, name string) error { - return c.meshObject.Delete(ctx, name) +func (MeshWorkspaceUserBinding) meshObjectPath() string { + return "meshworkspacebindings/userbindings" } diff --git a/client/workspace_user_group.go b/client/workspace_user_group.go index e6a74478..6a9a2b26 100644 --- a/client/workspace_user_group.go +++ b/client/workspace_user_group.go @@ -1,12 +1,5 @@ package client -import ( - "context" - - "github.com/meshcloud/meshstack-cli/client/http" - "github.com/meshcloud/meshstack-cli/client/internal" -) - type MeshWorkspaceUserGroup struct { Metadata MeshWorkspaceUserGroupMetadata `json:"metadata" tfsdk:"metadata"` Spec MeshWorkspaceUserGroupSpec `json:"spec" tfsdk:"spec"` @@ -19,12 +12,8 @@ type MeshWorkspaceUserGroupMetadata struct { SourceSystem *string `json:"sourceSystem,omitzero" tfsdk:"source_system"` } -func (m MeshWorkspaceUserGroupMetadata) Identifier() string { - return MeshWorkspaceUserGroupIdentifier(m.OwnedByWorkspace, m.Name) -} - -func MeshWorkspaceUserGroupIdentifier(ownedByWorkspace, name string) string { - return ownedByWorkspace + "." + name +func NewMeshWorkspaceUserGroupId(workspace, name string) string { + return workspace + "." + name } type MeshWorkspaceUserGroupSpec struct { @@ -38,44 +27,14 @@ type MeshWorkspaceUserGroupStatus struct { DisabledUsernames []string `json:"disabledUsernames" tfsdk:"disabled_usernames"` } -type MeshWorkspaceUserGroupListFilter struct { +type MeshWorkspaceUserGroupFilter struct { WorkspaceIdentifier string `json:"workspaceIdentifier"` Username string `json:"username"` SourceSystem string `json:"sourceSystem"` } -type MeshWorkspaceUserGroupClient interface { - List(ctx context.Context, filter MeshWorkspaceUserGroupListFilter) ([]MeshWorkspaceUserGroup, error) - Read(ctx context.Context, ownedByWorkspace, name string) (*MeshWorkspaceUserGroup, error) - Create(ctx context.Context, group *MeshWorkspaceUserGroup) (*MeshWorkspaceUserGroup, error) - Update(ctx context.Context, group *MeshWorkspaceUserGroup) (*MeshWorkspaceUserGroup, error) - Delete(ctx context.Context, ownedByWorkspace, name string) error -} - -type meshWorkspaceUserGroupClient struct { - meshObject internal.MeshObjectClient[MeshWorkspaceUserGroup] -} - -func newWorkspaceUserGroupClient(ctx context.Context, httpClient internal.HttpClient) meshWorkspaceUserGroupClient { - return meshWorkspaceUserGroupClient{internal.NewMeshObjectClient[MeshWorkspaceUserGroup](ctx, httpClient, "v1")} -} - -func (c meshWorkspaceUserGroupClient) List(ctx context.Context, filter MeshWorkspaceUserGroupListFilter) ([]MeshWorkspaceUserGroup, error) { - return c.meshObject.List(ctx, http.WithUrlQuery(filter)) -} - -func (c meshWorkspaceUserGroupClient) Read(ctx context.Context, ownedByWorkspace, name string) (*MeshWorkspaceUserGroup, error) { - return c.meshObject.Get(ctx, MeshWorkspaceUserGroupIdentifier(ownedByWorkspace, name)) -} - -func (c meshWorkspaceUserGroupClient) Create(ctx context.Context, group *MeshWorkspaceUserGroup) (*MeshWorkspaceUserGroup, error) { - return c.meshObject.Post(ctx, group) -} - -func (c meshWorkspaceUserGroupClient) Update(ctx context.Context, group *MeshWorkspaceUserGroup) (*MeshWorkspaceUserGroup, error) { - return c.meshObject.Put(ctx, group.Metadata.Identifier(), group) -} +type MeshWorkspaceUserGroupClient = MeshObjectClient[MeshWorkspaceUserGroup, MeshWorkspaceUserGroupFilter] -func (c meshWorkspaceUserGroupClient) Delete(ctx context.Context, ownedByWorkspace, name string) error { - return c.meshObject.Delete(ctx, MeshWorkspaceUserGroupIdentifier(ownedByWorkspace, name)) +func (group MeshWorkspaceUserGroup) meshObjectId() string { + return NewMeshWorkspaceUserGroupId(group.Metadata.OwnedByWorkspace, group.Metadata.Name) } diff --git a/cmd/api/api.go b/cmd/api/api.go index e8a7c339..d204d5e9 100644 --- a/cmd/api/api.go +++ b/cmd/api/api.go @@ -77,7 +77,7 @@ To see what the API docs say about the request, run the same command line with ' for key, values := range r.header { options = append(options, http.WithHeader(key, values...)) } - answer, err := meshStack.Raw.DoRequest(ctx, r.method, r.target.Path, options...) + answer, err := http.ReadAllBody(meshStack.HttpClient.DoRequest(ctx, r.method, meshStack.Endpoint.JoinPath(r.target.Path), options...)) if httpErr, ok := errors.AsType[client.HttpError](err); ok { if writeErr := writeAnswer(cmd.OutOrStdout(), httpErr.ResponseBody); writeErr != nil { return writeErr diff --git a/cmd/auth/login.go b/cmd/auth/login.go index 7fa0a2a1..62d6f868 100644 --- a/cmd/auth/login.go +++ b/cmd/auth/login.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "slices" - "uuid" "github.com/spf13/cobra" "github.com/spf13/pflag" @@ -33,7 +32,7 @@ func NewLoginTo(name profile.Name) *cobra.Command { func newLogin(profileSources setting.Sources) *cobra.Command { var ( openStdinFlag = newStdinFlag() - apiKeyFlag = internal.NewFlagForSetting[uuid.UUID](apiKeyFlagName, setting.ApiKeyClientId) + apiKeyFlag = internal.NewFlagForSetting[string](apiKeyFlagName, setting.ApiKeyClientId) apiTokenFlag = internal.NewFlagForSetting[bool]("apitoken", setting.ApiToken) output internal.ShowFlag ) @@ -66,8 +65,8 @@ Afterwards, the command prints the same output as 'meshstack auth status' for th case cmd.Flags().Changed(apiKeyFlag.Name.String()): authWith = credential.ApiKeyName opts.SettingSources = append(opts.SettingSources, - apiKeyFlag.AsSourceUnless(func(id uuid.UUID) bool { - return id == uuid.Nil() + apiKeyFlag.AsSourceUnless(func(id string) bool { + return id == "" }), newPromptingSource(setting.ApiKeyClientSecret.EnvKey(), &openStdinFlag, promptedFrom, "API Client Secret"), ) diff --git a/cmd/auth/login_apikey_test.go b/cmd/auth/login_apikey_test.go index 9f811509..e7b3d19a 100644 --- a/cmd/auth/login_apikey_test.go +++ b/cmd/auth/login_apikey_test.go @@ -10,14 +10,13 @@ import ( "github.com/meshcloud/meshstack-cli/internal/meshstack" ) -func TestLoginRejectsAnApiKeyIdOfNoUuidWhileItParsesTheFlags(t *testing.T) { +func TestLoginRejectsAnEmptyApiKeyIdWhileItParsesTheFlags(t *testing.T) { configDir := withEmptyConfigDir(t) tests := []struct { arg string wantErr string }{ - {arg: "--apikey=my-key", wantErr: `invalid argument "my-key" for "--apikey" flag: invalid uuid`}, {arg: "--apikey=", wantErr: `invalid argument "" for "--apikey" flag: the API key id is empty; give a bare --apikey to read it from the environment`}, } for _, tt := range tests { @@ -38,5 +37,5 @@ func TestABareApiKeyFlagLeavesTheIdToTheEnvironment(t *testing.T) { _, err := execute(t, "login", "--apikey") - assert.EqualError(t, err, "value from source 'env MESHSTACK_API_KEY' could not be parsed: invalid uuid\ntry setting flag --apikey") + assert.ErrorContains(t, err, "cannot login with api key my-key at https://meshstack.example.io/api/login") } diff --git a/cmd/buildingblock/abort_run.go b/cmd/buildingblock/abort_run.go index 056b9a7f..3b73b79d 100644 --- a/cmd/buildingblock/abort_run.go +++ b/cmd/buildingblock/abort_run.go @@ -7,7 +7,6 @@ import ( "fmt" "log/slog" gohttp "net/http" - "uuid" "github.com/spf13/cobra" @@ -16,10 +15,7 @@ import ( ) func newAbortRun() *cobra.Command { - var ( - output internal.OutputFlag - buildingBlockUuid uuid.UUID - ) + var output internal.OutputFlag cmd := &cobra.Command{ Use: "abort-run ", @@ -31,8 +27,9 @@ To reject a run that is waiting for approval, use 'meshstack buildingblock rejec The command shows the run and asks you to confirm, so it needs a terminal. After the abort, it prints the building block.`, Example: ` meshstack buildingblock abort-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 meshstack bb abort-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90`, - Args: internal.UuidArg(&buildingBlockUuid), - RunE: func(cmd *cobra.Command, _ []string) error { + Args: internal.UuidArg, + RunE: func(cmd *cobra.Command, args []string) error { + buildingBlockUuid := args[0] ctx := cmd.Context() action, err := newRunAction(cmd, buildingBlockUuid, output.Format) if err != nil { @@ -48,23 +45,23 @@ The command shows the run and asks you to confirm, so it needs a terminal. After } func (a runAction) abort(ctx context.Context) error { - _, block, err := a.readBuildingBlock(ctx) + block, err := a.readBuildingBlock(ctx) if err != nil { return err } - latest := cmp.Or(block.Links.LatestDryRun, block.Links.LatestRun) - if latest == nil { + latest := cmp.Or(block.Status.GetLatestDryRunUuid(), block.Status.GetLatestRunUuid()) + if latest == "" { return fmt.Errorf("building block %s has no run to abort", a.buildingBlockUuid) } - run, err := a.meshStack.BuildingBlockRunAction.ReadRun(ctx, *latest) + run, err := a.readRun(ctx, latest) if err != nil { return err } - if run.Links.Abort == nil && run.Links.Reject != nil { - return fmt.Errorf("run %s of building block %s is waiting for approval, and you may reject it but not abort it. Reject it with 'meshstack buildingblock reject-run %s'", - run.Metadata.Uuid, a.buildingBlockUuid, a.buildingBlockUuid) - } - if run.Links.Abort == nil { + if _, found := run.Links["abort"]; !found { + if _, found := run.Links["reject"]; found { + return fmt.Errorf("run %s of building block %s is waiting for approval, and you may reject it but not abort it. Reject it with 'meshstack buildingblock reject-run %s'", + run.Metadata.Uuid, a.buildingBlockUuid, a.buildingBlockUuid) + } return fmt.Errorf("run %s of building block %s (action %s) has the status %s and cannot be aborted, or you are not allowed to abort it", run.Metadata.Uuid, a.buildingBlockUuid, block.Status.Action, run.Status) } @@ -80,7 +77,7 @@ func (a runAction) abort(ctx context.Context) error { slog.InfoContext(ctx, fmt.Sprintf("Did not abort run %s.", run.Metadata.Uuid)) return nil } - err = a.meshStack.BuildingBlockRunAction.AbortRun(ctx, *run.Links.Abort) + err = run.Abort(ctx) if httpErr, ok := errors.AsType[client.HttpError](err); ok && httpErr.StatusCode == gohttp.StatusConflict { return fmt.Errorf("run %s can no longer be aborted", run.Metadata.Uuid) } diff --git a/cmd/buildingblock/approve_run.go b/cmd/buildingblock/approve_run.go index 27fe7385..98e21363 100644 --- a/cmd/buildingblock/approve_run.go +++ b/cmd/buildingblock/approve_run.go @@ -7,7 +7,6 @@ import ( "fmt" "log/slog" gohttp "net/http" - "uuid" "github.com/spf13/cobra" @@ -17,10 +16,7 @@ import ( ) func newApproveRun() *cobra.Command { - var ( - output internal.OutputFlag - buildingBlockUuid uuid.UUID - ) + var output internal.OutputFlag cmd := &cobra.Command{ Use: "approve-run ", @@ -32,8 +28,9 @@ The command shows the plan and asks you to approve it, so it needs a terminal. I A building block whose status.action is APPROVE_RUN in 'meshstack buildingblock list' has a run that is waiting for approval. After the approval, the command prints the building block.`, Example: ` meshstack buildingblock approve-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 meshstack bb approve-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90`, - Args: internal.UuidArg(&buildingBlockUuid), - RunE: func(cmd *cobra.Command, _ []string) error { + Args: internal.UuidArg, + RunE: func(cmd *cobra.Command, args []string) error { + buildingBlockUuid := args[0] ctx := cmd.Context() action, err := newRunAction(cmd, buildingBlockUuid, output.Format) if err != nil { @@ -49,32 +46,32 @@ A building block whose status.action is APPROVE_RUN in 'meshstack buildingblock } func (a runAction) approve(ctx context.Context) error { - _, block, err := a.readBuildingBlock(ctx) + block, err := a.readBuildingBlock(ctx) if err != nil { return err } - if block.Links.LatestRun == nil { + if block.Status.GetLatestRunUuid() == "" { return fmt.Errorf("building block %s has no run to approve", a.buildingBlockUuid) } - run, err := a.meshStack.BuildingBlockRunAction.ReadRun(ctx, *block.Links.LatestRun) + run, err := a.readRun(ctx, block.Status.GetLatestRunUuid()) if err != nil { return err } - if run.Links.Approve == nil { + if _, found := run.Links["approve"]; !found { return fmt.Errorf("the latest run %s of building block %s (action %s) is not waiting for approval, or you are not allowed to approve it", run.Metadata.Uuid, a.buildingBlockUuid, block.Status.Action) } - if run.Links.Predecessor == nil { + if _, found := run.Links["predecessor"]; !found { return fmt.Errorf("run %s is waiting for approval, but meshStack does not say which run created its plan", run.Metadata.Uuid) } - plan, err := a.meshStack.BuildingBlockRunAction.ReadRun(ctx, *run.Links.Predecessor) + plan, err := run.Predecessor(ctx) if err != nil { return err } - if plan.Links.DownloadLogs == nil { + if _, found := plan.Links["downloadLogs"]; !found { return fmt.Errorf("cannot read the logs of run %s, which created the plan for run %s", plan.Metadata.Uuid, run.Metadata.Uuid) } - logs, err := a.meshStack.BuildingBlockRunAction.ReadLogs(ctx, *plan.Links.DownloadLogs) + logs, err := plan.Logs(ctx) if err != nil { return err } @@ -94,7 +91,7 @@ func (a runAction) approve(ctx context.Context) error { slog.InfoContext(ctx, fmt.Sprintf("Did not approve run %s.", run.Metadata.Uuid)) return nil } - err = a.meshStack.BuildingBlockRunAction.ApproveRun(ctx, *run.Links.Approve, plan.Metadata.Uuid) + err = run.Approve(ctx, plan.Metadata.Uuid) if httpErr, ok := errors.AsType[client.HttpError](err); ok { switch httpErr.StatusCode { case gohttp.StatusConflict: diff --git a/cmd/buildingblock/approve_run_internal_test.go b/cmd/buildingblock/approve_run_internal_test.go index 7f1e27fa..920fdf73 100644 --- a/cmd/buildingblock/approve_run_internal_test.go +++ b/cmd/buildingblock/approve_run_internal_test.go @@ -6,7 +6,6 @@ import ( gohttp "net/http" "strings" "testing" - "uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -38,7 +37,7 @@ func newTestRunAction(t *testing.T, server *fakemeshstack.Server, answers string require.NoError(t, err) var asked bytes.Buffer return runAction{ - meshStack: meshStack, prompt: prompt.New(strings.NewReader(answers), &asked), buildingBlockUuid: uuid.MustParse(buildingBlockUuid), + meshStack: meshStack, prompt: prompt.New(strings.NewReader(answers), &asked), buildingBlockUuid: buildingBlockUuid, out: io.Discard, format: internal.OutputJson, }, &asked } @@ -52,7 +51,7 @@ func TestApproveRunApprovesOnlyThePlanItShowed(t *testing.T) { `"spec": {"runNumber": 2, "behavior": "APPLY", "buildingBlock": {"uuid": "`+buildingBlockUuid+`", "spec": {"displayName": "my-block"}}}, `+ `"_links": {"predecessor": {"href": "`+runsPath+planRun+`"}, "approve": {"href": "`+runsPath+waitingRun+`/approve"}}}`) server := fakemeshstack.Start(t, fakemeshstack.Options{ - BuildingBlocks: []any{meshObject(t, `{"metadata": {"uuid": "`+buildingBlockUuid+`"}, "status": {"action": "APPROVE_RUN"}, `+ + BuildingBlocks: []any{meshObject(t, `{"metadata": {"uuid": "`+buildingBlockUuid+`"}, "status": {"action": "APPROVE_RUN", "latestRunUuid": "`+waitingRun+`"}, `+ `"_links": {"latestRun": {"href": "`+runsPath+waitingRun+`"}}}`)}, BuildingBlockRuns: []any{run, meshObject(t, `{"metadata": {"uuid": "`+planRun+`"}, "status": "SUCCEEDED", `+ `"_links": {"downloadLogs": {"href": "`+runsPath+planRun+`/logs"}}}`)}, diff --git a/cmd/buildingblock/buildingblock.go b/cmd/buildingblock/buildingblock.go index eaebce90..bf65170f 100644 --- a/cmd/buildingblock/buildingblock.go +++ b/cmd/buildingblock/buildingblock.go @@ -2,11 +2,9 @@ package buildingblock import ( "context" - "encoding/json/jsontext" "fmt" "io" "log/slog" - "uuid" "github.com/spf13/cobra" @@ -14,7 +12,6 @@ import ( "github.com/meshcloud/meshstack-cli/cmd/buildingblock/tfstate" "github.com/meshcloud/meshstack-cli/cmd/internal" "github.com/meshcloud/meshstack-cli/cmd/internal/prompt" - "github.com/meshcloud/meshstack-cli/internal/json" ) func New() *cobra.Command { @@ -45,12 +42,12 @@ func New() *cobra.Command { type runAction struct { meshStack client.Client prompt prompt.Prompt - buildingBlockUuid uuid.UUID + buildingBlockUuid string out io.Writer format internal.OutputFormat } -func newRunAction(cmd *cobra.Command, buildingBlockUuid uuid.UUID, format internal.OutputFormat) (runAction, error) { +func newRunAction(cmd *cobra.Command, buildingBlockUuid string, format internal.OutputFormat) (runAction, error) { p := prompt.New(cmd.InOrStdin(), cmd.ErrOrStderr()) // A script cannot approve, reject or abort: the decision belongs to a person who saw the run. if !p.UsesTerminal() { @@ -63,28 +60,36 @@ func newRunAction(cmd *cobra.Command, buildingBlockUuid uuid.UUID, format intern return runAction{meshStack: meshStack, prompt: p, buildingBlockUuid: buildingBlockUuid, out: cmd.OutOrStdout(), format: format}, nil } -type linkedBuildingBlock struct { - Status client.MeshBuildingBlockV2Status `json:"status"` - Links client.MeshBuildingBlockV2Links `json:"_links"` +func (a runAction) readBuildingBlock(ctx context.Context) (client.MeshBuildingBlockV2, error) { + block, err := a.meshStack.BuildingBlockV2.Read(ctx, a.buildingBlockUuid) + switch { + case err != nil: + return client.MeshBuildingBlockV2{}, err + case block == nil: + return client.MeshBuildingBlockV2{}, fmt.Errorf("building block %s not found", a.buildingBlockUuid) + } + return *block, nil } -func (a runAction) readBuildingBlock(ctx context.Context) (jsontext.Value, linkedBuildingBlock, error) { - var block linkedBuildingBlock - raw, err := a.meshStack.Raw.Get[client.MeshBuildingBlockV2](ctx, a.buildingBlockUuid) - if err != nil { - return nil, block, err +func (a runAction) readRun(ctx context.Context, runUuid string) (client.MeshBuildingBlockRun, error) { + run, err := a.meshStack.BuildingBlockRun.Read(ctx, runUuid) + switch { + case err != nil: + return client.MeshBuildingBlockRun{}, err + case run == nil: + return client.MeshBuildingBlockRun{}, fmt.Errorf("run %s of building block %s not found", runUuid, a.buildingBlockUuid) } - return raw, block, json.Unmarshal(raw, &block) + return *run, nil } // report reads the building block again and writes it, because a run hides the actions // APPROVE_RUN and REVIEW_ABORTED_RUN that only the building block shows. func (a runAction) report(ctx context.Context, done string) error { - raw, block, err := a.readBuildingBlock(ctx) + block, err := a.readBuildingBlock(ctx) if err != nil { return err } - if err := a.format.WriteItem(a.out, raw); err != nil { + if err := a.format.WriteItem(a.out, client.WithKindAndApiVersion(a.meshStack.BuildingBlockV2, block)); err != nil { return err } slog.InfoContext(ctx, fmt.Sprintf("%s Building block %s now has the action %s.", done, a.buildingBlockUuid, block.Status.Action)) diff --git a/cmd/buildingblock/list.go b/cmd/buildingblock/list.go index 8f8973e4..2d85fb68 100644 --- a/cmd/buildingblock/list.go +++ b/cmd/buildingblock/list.go @@ -19,13 +19,17 @@ func newList() *cobra.Command { Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { var ( - filter client.MeshBuildingBlockV2ListFilter + filter client.MeshBuildingBlockV2Filter err error ) if filter.WorkspaceIdentifier, err = internal.ListWorkspace(cmd.Context()); err != nil { return err } - return flags.Run[client.MeshBuildingBlockV2](cmd, filter) + meshStack, err := internal.ResolveClient(cmd.Context()) + if err != nil { + return err + } + return flags.Run(cmd, meshStack.BuildingBlockV2, filter) }, } diff --git a/cmd/buildingblock/reject_run.go b/cmd/buildingblock/reject_run.go index bb0c656b..c21f6155 100644 --- a/cmd/buildingblock/reject_run.go +++ b/cmd/buildingblock/reject_run.go @@ -5,8 +5,6 @@ import ( "errors" "fmt" "log/slog" - gohttp "net/http" - "uuid" "github.com/spf13/cobra" @@ -15,10 +13,7 @@ import ( ) func newRejectRun() *cobra.Command { - var ( - output internal.OutputFlag - buildingBlockUuid uuid.UUID - ) + var output internal.OutputFlag cmd := &cobra.Command{ Use: "reject-run ", @@ -30,8 +25,9 @@ The run ends at once without applying its plan, and meshStack does not plan the A building block whose status.action is APPROVE_RUN in 'meshstack buildingblock list' has a run that is waiting for approval. After the rejection, the command prints the building block.`, Example: ` meshstack buildingblock reject-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 meshstack bb reject-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90`, - Args: internal.UuidArg(&buildingBlockUuid), - RunE: func(cmd *cobra.Command, _ []string) error { + Args: internal.UuidArg, + RunE: func(cmd *cobra.Command, args []string) error { + buildingBlockUuid := args[0] ctx := cmd.Context() action, err := newRunAction(cmd, buildingBlockUuid, output.Format) if err != nil { @@ -47,18 +43,18 @@ A building block whose status.action is APPROVE_RUN in 'meshstack buildingblock } func (a runAction) reject(ctx context.Context) error { - _, block, err := a.readBuildingBlock(ctx) + block, err := a.readBuildingBlock(ctx) if err != nil { return err } - if block.Links.LatestRun == nil { + if block.Status.GetLatestRunUuid() == "" { return fmt.Errorf("building block %s has no run to reject", a.buildingBlockUuid) } - run, err := a.meshStack.BuildingBlockRunAction.ReadRun(ctx, *block.Links.LatestRun) + run, err := a.readRun(ctx, block.Status.GetLatestRunUuid()) if err != nil { return err } - if run.Links.Reject == nil { + if _, found := run.Links["reject"]; !found { return fmt.Errorf("the latest run %s of building block %s (action %s) is not waiting for approval, or you are not allowed to reject it", run.Metadata.Uuid, a.buildingBlockUuid, block.Status.Action) } @@ -74,8 +70,8 @@ func (a runAction) reject(ctx context.Context) error { slog.InfoContext(ctx, fmt.Sprintf("Did not reject run %s.", run.Metadata.Uuid)) return nil } - err = a.meshStack.BuildingBlockRunAction.RejectRun(ctx, *run.Links.Reject) - if httpErr, ok := errors.AsType[client.HttpError](err); ok && httpErr.StatusCode == gohttp.StatusConflict { + err = run.Reject(ctx) + if httpErr, ok := errors.AsType[client.HttpError](err); ok && httpErr.IsConflict() { return fmt.Errorf("run %s is no longer waiting for approval", run.Metadata.Uuid) } if err != nil { diff --git a/cmd/buildingblock/reject_run_internal_test.go b/cmd/buildingblock/reject_run_internal_test.go index 0bcd60f9..beb41ebd 100644 --- a/cmd/buildingblock/reject_run_internal_test.go +++ b/cmd/buildingblock/reject_run_internal_test.go @@ -14,7 +14,7 @@ import ( func TestRejectRunRejectsOnlyAfterConfirmation(t *testing.T) { const waitingRun = "a0000000-0000-4000-8000-000000000003" server := fakemeshstack.Start(t, fakemeshstack.Options{ - BuildingBlocks: []any{meshObject(t, `{"metadata": {"uuid": "`+buildingBlockUuid+`"}, "status": {"action": "APPROVE_RUN"}, `+ + BuildingBlocks: []any{meshObject(t, `{"metadata": {"uuid": "`+buildingBlockUuid+`"}, "status": {"action": "APPROVE_RUN", "latestRunUuid": "`+waitingRun+`"}, `+ `"_links": {"latestRun": {"href": "`+runsPath+waitingRun+`"}}}`)}, BuildingBlockRuns: []any{meshObject(t, `{"metadata": {"uuid": "`+waitingRun+`"}, "status": "IN_PROGRESS", `+ `"spec": {"runNumber": 2, "behavior": "APPLY", "buildingBlock": {"uuid": "`+buildingBlockUuid+`", "spec": {"displayName": "my-block"}}}, `+ diff --git a/cmd/buildingblock/tfstate/exec.go b/cmd/buildingblock/tfstate/exec.go index 161c5527..570094e4 100644 --- a/cmd/buildingblock/tfstate/exec.go +++ b/cmd/buildingblock/tfstate/exec.go @@ -12,7 +12,6 @@ import ( "slices" "syscall" "time" - "uuid" "github.com/charmbracelet/x/term" "github.com/spf13/cobra" @@ -21,7 +20,7 @@ import ( "github.com/meshcloud/meshstack-cli/internal/tfstate" ) -// runLockTimeout must match stateLockTimeout in ../building-block-runner/tf-block-runner/tfrun/tfcmd.go. +// runLockTimeout must match stateLockTimeout in ../building-block-runner/internal/executor/tf/tfcmd.go. const runLockTimeout = 5 * time.Minute type mode string @@ -59,7 +58,7 @@ func (m *mode) Type() string { func newExec() *cobra.Command { var ( - buildingBlockUuid uuid.UUID + buildingBlockUuid string command []string access = modeRead force bool @@ -94,8 +93,8 @@ With --%[8]s, exec copies the stored state into that directory before it replace return fmt.Errorf("%s needs the building block uuid, then --, then the command to run, such as '%s -- tofu plan'", cmd.CommandPath(), cmd.CommandPath()) } - command = args[1:] - return internal.UuidArg(&buildingBlockUuid)(cmd, args[:1]) + command, buildingBlockUuid = args[1:], args[0] + return internal.UuidArg(cmd, args[:1]) }, RunE: func(cmd *cobra.Command, _ []string) error { ctx := cmd.Context() @@ -136,7 +135,7 @@ With --%[8]s, exec copies the stored state into that directory before it replace proxy.LockWarning = runLockTimeout if !force { proxy.BeforeWrite = func(ctx context.Context) error { - if running := tfstate.NoRunOf(ctx, meshStack.Raw, buildingBlockUuid); running != nil { + if running := tfstate.NoRunOf(ctx, meshStack.BuildingBlockV2, buildingBlockUuid); running != nil { return fmt.Errorf("%w: wait for it to finish, or run again with --%s", running, forceFlagName) } return nil diff --git a/cmd/buildingblock/tfstate/force_unlock.go b/cmd/buildingblock/tfstate/force_unlock.go index a4869407..87c02076 100644 --- a/cmd/buildingblock/tfstate/force_unlock.go +++ b/cmd/buildingblock/tfstate/force_unlock.go @@ -4,7 +4,6 @@ import ( "errors" "fmt" "log/slog" - "uuid" "github.com/spf13/cobra" @@ -14,10 +13,7 @@ import ( ) func newForceUnlock() *cobra.Command { - var ( - buildingBlockUuid uuid.UUID - force bool - ) + var force bool cmd := &cobra.Command{ Use: "force-unlock ", @@ -29,8 +25,9 @@ If the lock belongs to a run of the building block that is pending or in progres By default, the command uses the state stored in the building block's own workspace, metadata.ownedByWorkspace. Use --` + internal.WorkspaceFlag.Name.String() + ` to choose another workspace.`, Example: ` meshstack bb tfstate force-unlock 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 echo yes | meshstack bb tfstate force-unlock 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 --force`, - Args: internal.UuidArg(&buildingBlockUuid), - RunE: func(cmd *cobra.Command, _ []string) error { + Args: internal.UuidArg, + RunE: func(cmd *cobra.Command, args []string) error { + buildingBlockUuid := args[0] ctx := cmd.Context() meshStack, err := internal.ResolveClient(ctx) if err != nil { @@ -42,15 +39,15 @@ By default, the command uses the state stored in the building block's own worksp } lock, err := store.ReadLock(ctx) if errors.Is(err, tfstate.ErrNoLock) { - slog.InfoContext(ctx, "The state of building block "+buildingBlockUuid.String()+" in workspace "+store.Workspace+" has no lock") + slog.InfoContext(ctx, "The state of building block "+buildingBlockUuid+" in workspace "+store.Workspace+" has no lock") return nil } else if err != nil { return withRightsHint(err) } - slog.InfoContext(ctx, "The state of building block "+buildingBlockUuid.String()+" is locked by "+lock.String()) + slog.InfoContext(ctx, "The state of building block "+buildingBlockUuid+" is locked by "+lock.String()) if !force { - if running := lock.NoUnfinishedRun(ctx, meshStack.Raw); running != nil { + if running := lock.NoUnfinishedRun(ctx, meshStack.BuildingBlockRun); running != nil { return fmt.Errorf("%w: wait for it to finish, or run again with --%s", running, forceFlagName) } } @@ -69,7 +66,7 @@ By default, the command uses the state stored in the building block's own worksp } else if err != nil { return withRightsHint(err) } - slog.InfoContext(ctx, "Released the lock "+lock.Info.ID+" on the state of building block "+buildingBlockUuid.String()) + slog.InfoContext(ctx, "Released the lock "+lock.Info.ID+" on the state of building block "+buildingBlockUuid) return nil }, } diff --git a/cmd/buildingblock/tfstate/show.go b/cmd/buildingblock/tfstate/show.go index 998dd29a..8e270592 100644 --- a/cmd/buildingblock/tfstate/show.go +++ b/cmd/buildingblock/tfstate/show.go @@ -3,7 +3,6 @@ package tfstate import ( "errors" "log/slog" - "uuid" "github.com/spf13/cobra" @@ -12,8 +11,6 @@ import ( ) func newShow() *cobra.Command { - var buildingBlockUuid uuid.UUID - return &cobra.Command{ Use: "show ", Short: "Show the state of a building block", @@ -21,8 +18,9 @@ func newShow() *cobra.Command { By default, the command uses the state stored in the building block's own workspace, metadata.ownedByWorkspace. Use --` + internal.WorkspaceFlag.Name.String() + ` to choose another workspace.`, Example: ` meshstack bb tfstate show 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 | jq .resources`, - Args: internal.UuidArg(&buildingBlockUuid), - RunE: func(cmd *cobra.Command, _ []string) error { + Args: internal.UuidArg, + RunE: func(cmd *cobra.Command, args []string) error { + buildingBlockUuid := args[0] ctx := cmd.Context() meshStack, err := internal.ResolveClient(ctx) if err != nil { @@ -34,7 +32,7 @@ By default, the command uses the state stored in the building block's own worksp } state, err := store.Get(ctx) if errors.Is(err, tfstate.ErrNoState) { - slog.InfoContext(ctx, "Building block "+buildingBlockUuid.String()+" has no state in workspace "+store.Workspace+" yet") + slog.InfoContext(ctx, "Building block "+buildingBlockUuid+" has no state in workspace "+store.Workspace+" yet") return nil } else if err != nil { return withRightsHint(err) diff --git a/cmd/buildingblock/tfstate/tfstate.go b/cmd/buildingblock/tfstate/tfstate.go index 5db7a8b3..8b5bf01f 100644 --- a/cmd/buildingblock/tfstate/tfstate.go +++ b/cmd/buildingblock/tfstate/tfstate.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "uuid" "github.com/spf13/cobra" @@ -53,12 +52,12 @@ func New() *cobra.Command { // openStore ignores the profile's default workspace. Otherwise that workspace would replace the // building block's own workspace, which the runner stores the state under, for every user who has a // default. -func openStore(ctx context.Context, meshStack client.Client, buildingBlockUuid uuid.UUID) (tfstate.Store, error) { +func openStore(ctx context.Context, meshStack client.Client, buildingBlockUuid string) (tfstate.Store, error) { workspace, err := internal.ResolveWorkspace(ctx, internal.IgnoreDefaultWorkspace) if err != nil { return tfstate.Store{}, err } - return tfstate.OpenStore(ctx, meshStack.Raw, workspace, buildingBlockUuid) + return tfstate.OpenStore(ctx, meshStack, workspace, buildingBlockUuid) } func withRightsHint(err error) error { diff --git a/cmd/buildingblock/tfstate/tfstate_test.go b/cmd/buildingblock/tfstate/tfstate_test.go index 20e98e98..8084af15 100644 --- a/cmd/buildingblock/tfstate/tfstate_test.go +++ b/cmd/buildingblock/tfstate/tfstate_test.go @@ -87,7 +87,7 @@ func readAsTheProvider() error { if err != nil { return err } - block, err := meshStack.Raw.DoRequest(ctx, http.MethodGet, "/api/meshobjects/meshbuildingblocks/"+buildingBlockUuid) + block, err := http.ReadAllBody(meshStack.HttpClient.DoRequest(ctx, http.MethodGet, meshStack.Endpoint.JoinPath("/api/meshobjects/meshbuildingblocks/"+buildingBlockUuid))) fmt.Print(string(block)) return err } diff --git a/cmd/buildingblock/trigger_run.go b/cmd/buildingblock/trigger_run.go index bf48d674..315543f2 100644 --- a/cmd/buildingblock/trigger_run.go +++ b/cmd/buildingblock/trigger_run.go @@ -1,22 +1,22 @@ package buildingblock import ( + "errors" "fmt" "log/slog" - "uuid" "github.com/spf13/cobra" "github.com/meshcloud/meshstack-cli/client" + "github.com/meshcloud/meshstack-cli/client/types/hal" "github.com/meshcloud/meshstack-cli/cmd/internal" "github.com/meshcloud/meshstack-cli/cmd/internal/buildingblock" ) func newTriggerRun() *cobra.Command { var ( - output internal.OutputFlag - buildingBlockUuid uuid.UUID - wait bool + output internal.OutputFlag + wait bool ) cmd := &cobra.Command{ @@ -31,14 +31,25 @@ With --` + waitFlagName + `, the command waits until the run has ended. This is 'meshstack api-docs --describe buildingblock.trigger-run' shows the fields of the response.`, Example: ` meshstack buildingblock trigger-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 meshstack bb trigger-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 -o ndjson | jq -r .status.latestRunUuid`, - Args: internal.UuidArg(&buildingBlockUuid), - RunE: func(cmd *cobra.Command, _ []string) error { + Args: internal.UuidArg, + RunE: func(cmd *cobra.Command, args []string) error { + buildingBlockUuid := args[0] ctx := cmd.Context() meshStack, err := internal.ResolveClient(ctx) if err != nil { return err } - answer, err := meshStack.BuildingBlockV2.TriggerRun(ctx, buildingBlockUuid.String()) + block, err := meshStack.BuildingBlockV2.Read(ctx, buildingBlockUuid) + switch { + case err != nil: + return err + case block == nil: + return fmt.Errorf("building block %s not found", buildingBlockUuid) + } + answer, err := block.TriggerRun(ctx) + if errors.Is(err, hal.ErrNoLink) { + return fmt.Errorf("meshStack lets you trigger no run of building block %s", buildingBlockUuid) + } if err != nil { return err } @@ -47,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.Raw, buildingBlockUuid, accepted) + return awaitRunEnd(ctx, cmd.OutOrStdout(), output.Format, meshStack.BuildingBlockV2, buildingBlockUuid, accepted) } - runWait := buildingblock.NewRunWait(meshStack.Raw, buildingBlockUuid) - reacted, block, err := runWait.AwaitReaction(ctx, accepted) + runWait := buildingblock.NewRunWait(meshStack.BuildingBlockV2, buildingBlockUuid) + reacted, err := runWait.AwaitReaction(ctx, accepted) if err != nil { return err } - if err := output.Format.WriteItem(cmd.OutOrStdout(), reacted); err != nil { + if err := output.Format.WriteItem(cmd.OutOrStdout(), client.WithKindAndApiVersion(meshStack.BuildingBlockV2, *reacted)); err != nil { return err } - if err := runWait.StartFailure(block); err != nil { + if err := runWait.StartFailure(reacted); err != nil { return err } - slog.InfoContext(ctx, startedRunMessage(buildingBlockUuid, accepted, *block.Status)) + slog.InfoContext(ctx, startedRunMessage(buildingBlockUuid, accepted, *reacted.Status)) return nil }, } @@ -73,7 +84,7 @@ With --` + waitFlagName + `, the command waits until the run has ended. This is const waitFlagName = "wait" -func startedRunMessage(buildingBlockUuid uuid.UUID, accepted, reacted client.MeshBuildingBlockV2Status) string { +func startedRunMessage(buildingBlockUuid string, accepted, reacted client.MeshBuildingBlockV2Status) string { switch dryRun, run := reacted.GetLatestDryRunUuid(), reacted.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. "+ diff --git a/cmd/buildingblock/trigger_run_test.go b/cmd/buildingblock/trigger_run_test.go index 90ea4577..e656efea 100644 --- a/cmd/buildingblock/trigger_run_test.go +++ b/cmd/buildingblock/trigger_run_test.go @@ -25,8 +25,9 @@ func TestTriggerRunPrintsTheBuildingBlockAndFailsWithTheReasonMeshStackCouldNotS ) 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}}`, - buildingBlockUuid, reason, failedOn) + `"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"))}}) meshStack.Route("POST /api/meshobjects/meshbuildingblocks/{uuid}/trigger-run", func(w gohttp.ResponseWriter, _ *gohttp.Request) { diff --git a/cmd/buildingblock/wait.go b/cmd/buildingblock/wait.go index c420e28f..dc924c4b 100644 --- a/cmd/buildingblock/wait.go +++ b/cmd/buildingblock/wait.go @@ -5,7 +5,6 @@ import ( "fmt" "io" "log/slog" - "uuid" "github.com/spf13/cobra" @@ -16,9 +15,8 @@ import ( func newWait() *cobra.Command { var ( - output internal.OutputFlag - buildingBlockUuid uuid.UUID - beforeInput internal.JsonInputFlag[client.MeshBuildingBlockV2] + output internal.OutputFlag + beforeInput internal.JsonInputFlag[client.MeshBuildingBlockV2] ) cmd := &cobra.Command{ @@ -31,8 +29,9 @@ meshStack responds to a write before it starts the run. So right after the write 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=-`, - Args: internal.UuidArg(&buildingBlockUuid), - RunE: func(cmd *cobra.Command, _ []string) error { + 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 @@ -41,7 +40,7 @@ The command prints the building block. It fails and names the action if the run if err != nil { return err } - return awaitRunEnd(cmd.Context(), cmd.OutOrStdout(), output.Format, meshStack.Raw, buildingBlockUuid, before) + return awaitRunEnd(cmd.Context(), cmd.OutOrStdout(), output.Format, meshStack.BuildingBlockV2, buildingBlockUuid, before) }, } @@ -54,14 +53,14 @@ The command prints the building block. It fails and names the action if the run const beforeFlagName = "before" -func readBefore(cmd *cobra.Command, input internal.JsonInputFlag[client.MeshBuildingBlockV2], buildingBlockUuid uuid.UUID) (client.MeshBuildingBlockV2Status, error) { +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.String(): + 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) @@ -71,13 +70,13 @@ func readBefore(cmd *cobra.Command, input internal.JsonInputFlag[client.MeshBuil // 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, raw *client.RawClient, buildingBlockUuid uuid.UUID, before client.MeshBuildingBlockV2Status) error { - wait := buildingblock.NewRunWait(raw, buildingBlockUuid) - ended, block, err := wait.AwaitEnd(ctx, before) +func awaitRunEnd(ctx context.Context, out io.Writer, format internal.OutputFormat, blocks client.MeshBuildingBlockV2Client, buildingBlockUuid string, before client.MeshBuildingBlockV2Status) error { + wait := buildingblock.NewRunWait(blocks, buildingBlockUuid) + block, err := wait.AwaitEnd(ctx, before) if err != nil { return err } - if err = format.WriteItem(out, ended); err != nil { + if err = format.WriteItem(out, client.WithKindAndApiVersion(blocks, *block)); err != nil { return err } if err = wait.Outcome(block); err != nil { diff --git a/cmd/buildingblockdefinition/list.go b/cmd/buildingblockdefinition/list.go index aa7c02f9..1e1f361b 100644 --- a/cmd/buildingblockdefinition/list.go +++ b/cmd/buildingblockdefinition/list.go @@ -37,7 +37,11 @@ func list(cmd *cobra.Command, flags *internal.ListFlags, includeAllPublished boo if cmd.Flags().Changed(internal.WorkspaceFlag.Name.String()) { ownedByWorkspace = new(internal.WorkspaceFlag.Value) } - return flags.Run[client.MeshBuildingBlockDefinition](cmd, client.MeshBuildingBlockDefinitionListFilter{ + meshStack, err := internal.ResolveClient(cmd.Context()) + if err != nil { + return err + } + return flags.Run(cmd, meshStack.BuildingBlockDefinition, client.MeshBuildingBlockDefinitionFilter{ OwnedByWorkspace: ownedByWorkspace, IncludeAllPublished: includeAllPublished, }) diff --git a/cmd/buildingblockdefinitionversion/list.go b/cmd/buildingblockdefinitionversion/list.go index f649218d..05152e0a 100644 --- a/cmd/buildingblockdefinitionversion/list.go +++ b/cmd/buildingblockdefinitionversion/list.go @@ -1,8 +1,6 @@ package buildingblockdefinitionversion import ( - "uuid" - "github.com/spf13/cobra" "github.com/meshcloud/meshstack-cli/client" @@ -14,7 +12,7 @@ const definitionFlagName = "definition" func newList() *cobra.Command { var ( flags internal.ListFlags - definitionUuid uuid.UUID + definitionUuid string ) cmd := &cobra.Command{ @@ -27,7 +25,11 @@ Give the definition by its uuid; 'meshstack buildingblockdefinition list' shows meshstack bbdv list --definition 3c9e1f7a-2b4d-4e6f-8a1c-5d7b9e2f4a6c --limit 1`, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { - return flags.Run[client.MeshBuildingBlockDefinitionVersion](cmd, client.MeshBuildingBlockDefinitionVersionListFilter{ + meshStack, err := internal.ResolveClient(cmd.Context()) + if err != nil { + return err + } + return flags.Run(cmd, meshStack.BuildingBlockDefinitionVersion, client.MeshBuildingBlockDefinitionVersionFilter{ BuildingBlockDefinitionUuid: definitionUuid, }) }, diff --git a/cmd/buildingblockrun/list.go b/cmd/buildingblockrun/list.go index 95d62fd0..f6ebbeca 100644 --- a/cmd/buildingblockrun/list.go +++ b/cmd/buildingblockrun/list.go @@ -2,19 +2,15 @@ package buildingblockrun import ( "context" - "encoding/json/jsontext" "errors" "fmt" "iter" "slices" - "time" - "uuid" "github.com/spf13/cobra" "github.com/meshcloud/meshstack-cli/client" "github.com/meshcloud/meshstack-cli/cmd/internal" - "github.com/meshcloud/meshstack-cli/internal/json" ) const buildingBlockFlagName = "building-block" @@ -22,7 +18,7 @@ const buildingBlockFlagName = "building-block" func newList() *cobra.Command { var ( flags internal.ListFlags - buildingBlockUuid uuid.UUID + buildingBlockUuid string ) cmd := &cobra.Command{ @@ -35,18 +31,26 @@ With --` + buildingBlockFlagName + `, the command lists only the runs of that bu meshstack bbrun list --workspace my-workspace --limit 20`, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { - if buildingBlockUuid != uuid.Nil() { - return flags.Run[client.MeshBuildingBlockRun](cmd, client.MeshBuildingBlockRunListFilter{BuildingBlockUuid: buildingBlockUuid}) + if buildingBlockUuid != "" { + meshStack, err := internal.ResolveClient(cmd.Context()) + if err != nil { + return err + } + return flags.Run(cmd, meshStack.BuildingBlockRun, client.MeshBuildingBlockRunFilter{BuildingBlockUuid: buildingBlockUuid}) } var ( - blockFilter client.MeshBuildingBlockV2ListFilter + blockFilter client.MeshBuildingBlockV2Filter err error ) if blockFilter.WorkspaceIdentifier, err = internal.ListWorkspace(cmd.Context()); err != nil { return err } - return flags.RunSeq(cmd, func(ctx context.Context, meshStack client.Client, options client.ListOptions) iter.Seq2[jsontext.Value, error] { - return allRuns(ctx, meshStack, blockFilter, options.PageSize) + meshStack, err := internal.ResolveClient(cmd.Context()) + if err != nil { + return err + } + return flags.RunSeq(cmd, func(ctx context.Context, options ...client.ListOption) iter.Seq2[any, error] { + return internal.WithKindAndApiVersion(meshStack.BuildingBlockRun, allRuns(ctx, meshStack, blockFilter, options)) }) }, } @@ -57,50 +61,35 @@ With --` + buildingBlockFlagName + `, the command lists only the runs of that bu return cmd } -// runsPageSizeOfEachBlock caps the page size a limited listing asks for, which is its limit, for the -// runs of each building block: a listing of every building block reads the first page of each one -// before it lists a single run. An unlimited listing reads every page anyway, and takes meshStack's -// default page size. +// runsPageSizeOfEachBlock is small, because a listing reads the first page of every block's runs. const runsPageSizeOfEachBlock = 10 // allRuns merges the runs of every building block, because the run list endpoint takes one building // block at a time and has no list of every run. -func allRuns(ctx context.Context, meshStack client.Client, blockFilter client.MeshBuildingBlockV2ListFilter, pageSize int) iter.Seq2[jsontext.Value, error] { - if pageSize > 0 { - pageSize = min(pageSize, runsPageSizeOfEachBlock) - } - return func(yield func(jsontext.Value, error) bool) { - var runsOfEachBlock []iter.Seq2[jsontext.Value, error] - // The blocks are read raw because only their uuid is needed, and a block the client cannot - // fully decode still has runs to list. - for rawBlock, err := range meshStack.Raw.List[client.MeshBuildingBlockV2](ctx, blockFilter, client.ListOptions{}) { - if err != nil { - yield(nil, err) - return - } - var buildingBlock struct { - Metadata struct { - Uuid uuid.UUID `json:"uuid"` - } `json:"metadata"` - } - if err := json.Unmarshal(rawBlock, &buildingBlock); err != nil { - yield(nil, err) - return - } - if buildingBlock.Metadata.Uuid == uuid.Nil() { - yield(nil, errors.New("building block has no metadata.uuid: this must be a bug in the meshStack CLI or meshStack")) +func allRuns(ctx context.Context, meshStack client.Client, blockFilter client.MeshBuildingBlockV2Filter, options []client.ListOption) iter.Seq2[client.MeshBuildingBlockRun, error] { + options = append(options, client.WithPageSize(runsPageSizeOfEachBlock)) + return func(yield func(client.MeshBuildingBlockRun, error) bool) { + var runsOfEachBlock []iter.Seq2[client.MeshBuildingBlockRun, error] + blocks, err := meshStack.BuildingBlockV2.List(ctx, blockFilter) + if err != nil { + yield(client.MeshBuildingBlockRun{}, err) + return + } + for _, block := range blocks { + if block.Metadata.Uuid == nil { + yield(client.MeshBuildingBlockRun{}, errors.New("building block has no metadata.uuid: this must be a bug in the meshStack CLI or meshStack")) return } - runsOfEachBlock = append(runsOfEachBlock, runsOf(ctx, meshStack, buildingBlock.Metadata.Uuid, pageSize)) + runsOfEachBlock = append(runsOfEachBlock, runsOf(ctx, meshStack, *block.Metadata.Uuid, options)) } mergeNewestFirst(runsOfEachBlock)(yield) } } -func runsOf(ctx context.Context, meshStack client.Client, buildingBlockUuid uuid.UUID, pageSize int) iter.Seq2[jsontext.Value, error] { - return func(yield func(jsontext.Value, error) bool) { - filter := client.MeshBuildingBlockRunListFilter{BuildingBlockUuid: buildingBlockUuid} - for run, err := range meshStack.Raw.List[client.MeshBuildingBlockRun](ctx, filter, client.ListOptions{PageSize: pageSize}) { +func runsOf(ctx context.Context, meshStack client.Client, buildingBlockUuid string, options []client.ListOption) iter.Seq2[client.MeshBuildingBlockRun, error] { + return func(yield func(client.MeshBuildingBlockRun, error) bool) { + filter := client.MeshBuildingBlockRunFilter{BuildingBlockUuid: buildingBlockUuid} + for run, err := range meshStack.BuildingBlockRun.ListSeq(ctx, filter, options...) { if err != nil { err = fmt.Errorf("listing the runs of building block %s: %w", buildingBlockUuid, err) } @@ -114,8 +103,8 @@ func runsOf(ctx context.Context, meshStack client.Client, buildingBlockUuid uuid // mergeNewestFirst merges runs that each come newest first. It reads the first run of every one // before it yields any, and after that reads on only in the runs it yielded the head of. Runs created // at the same time keep the order of the sequences they come from. -func mergeNewestFirst(runs []iter.Seq2[jsontext.Value, error]) iter.Seq2[jsontext.Value, error] { - return func(yield func(jsontext.Value, error) bool) { +func mergeNewestFirst(runs []iter.Seq2[client.MeshBuildingBlockRun, error]) iter.Seq2[client.MeshBuildingBlockRun, error] { + return func(yield func(client.MeshBuildingBlockRun, error) bool) { heads := make([]*runHead, 0, len(runs)) stops := make([]func(), 0, len(runs)) defer func() { @@ -128,7 +117,7 @@ func mergeNewestFirst(runs []iter.Seq2[jsontext.Value, error]) iter.Seq2[jsontex stops = append(stops, stop) head := &runHead{next: next} if ok, err := head.advance(); err != nil { - yield(nil, err) + yield(client.MeshBuildingBlockRun{}, err) return } else if ok { heads = append(heads, head) @@ -137,7 +126,7 @@ func mergeNewestFirst(runs []iter.Seq2[jsontext.Value, error]) iter.Seq2[jsontex for len(heads) > 0 { newest := 0 for i, head := range heads { - if head.createdAt.After(heads[newest].createdAt) { + if head.run.Metadata.CreatedAt.After(heads[newest].run.Metadata.CreatedAt) { newest = i } } @@ -145,7 +134,7 @@ func mergeNewestFirst(runs []iter.Seq2[jsontext.Value, error]) iter.Seq2[jsontex return } if ok, err := heads[newest].advance(); err != nil { - yield(nil, err) + yield(client.MeshBuildingBlockRun{}, err) return } else if !ok { heads = slices.Delete(heads, newest, newest+1) @@ -155,9 +144,8 @@ func mergeNewestFirst(runs []iter.Seq2[jsontext.Value, error]) iter.Seq2[jsontex } type runHead struct { - next func() (jsontext.Value, error, bool) - run jsontext.Value - createdAt time.Time + next func() (client.MeshBuildingBlockRun, error, bool) + run client.MeshBuildingBlockRun } func (h *runHead) advance() (bool, error) { @@ -165,12 +153,6 @@ func (h *runHead) advance() (bool, error) { if !ok || err != nil { return false, err } - var created struct { - Metadata client.MeshBuildingBlockRunMetadata `json:"metadata"` - } - if err := json.Unmarshal(run, &created); err != nil { - return false, fmt.Errorf("reading the metadata.createdAt of a building block run: %w", err) - } - h.run, h.createdAt = run, created.Metadata.CreatedAt + h.run = run return true, nil } diff --git a/cmd/buildingblockrun/list_internal_test.go b/cmd/buildingblockrun/list_internal_test.go index e1b28c17..c2228a15 100644 --- a/cmd/buildingblockrun/list_internal_test.go +++ b/cmd/buildingblockrun/list_internal_test.go @@ -1,73 +1,70 @@ package buildingblockrun import ( - "encoding/json/jsontext" "errors" "fmt" "iter" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/meshcloud/meshstack-cli/internal/json" + "github.com/meshcloud/meshstack-cli/client" ) // blockRuns yields a run named block/i, created at the i-th of createdAts, and counts into pulled the -// runs a reader took from it. -func blockRuns(block string, pulled *int, createdAts ...string) iter.Seq2[jsontext.Value, error] { - return func(yield func(jsontext.Value, error) bool) { +// runs a reader took from it. The name goes into the first two bytes of the run's uuid. +func blockRuns(t *testing.T, block string, pulled *int, createdAts ...string) iter.Seq2[client.MeshBuildingBlockRun, error] { + t.Helper() + return func(yield func(client.MeshBuildingBlockRun, error) bool) { for i, createdAt := range createdAts { *pulled++ - run := fmt.Sprintf(`{"metadata": {"uuid": "%s/%d", "createdAt": %q}}`, block, i, createdAt) - if !yield(jsontext.Value(run), nil) { + created, err := time.Parse(time.RFC3339Nano, createdAt) + require.NoError(t, err) + id := string([]byte{block[0], byte(i)}) + if !yield(client.MeshBuildingBlockRun{Metadata: client.MeshBuildingBlockRunMetadata{Uuid: id, CreatedAt: created}}, nil) { return } } } } -func uuidsOf(t *testing.T, runs iter.Seq2[jsontext.Value, error], n int) []string { +func namesOf(t *testing.T, runs iter.Seq2[client.MeshBuildingBlockRun, error], n int) []string { t.Helper() - var uuids []string + var names []string for run, err := range runs { require.NoError(t, err) - var listed struct { - Metadata struct { - Uuid string `json:"uuid"` - } `json:"metadata"` - } - require.NoError(t, json.Unmarshal(run, &listed)) - if uuids = append(uuids, listed.Metadata.Uuid); len(uuids) == n { + if names = append(names, fmt.Sprintf("%c/%d", run.Metadata.Uuid[0], run.Metadata.Uuid[1])); len(names) == n { break } } - return uuids + return names } func TestMergeNewestFirst(t *testing.T) { t.Run("lists the runs of every block newest first", func(t *testing.T) { var pulled int - merged := mergeNewestFirst([]iter.Seq2[jsontext.Value, error]{ - blockRuns("a", &pulled, "2026-10-01T05:00:00Z", "2026-10-01T03:00:00Z", "2026-10-01T01:00:00Z"), - blockRuns("empty", &pulled), - blockRuns("c", &pulled, "2026-10-01T04:00:00Z", "2026-10-01T03:00:00Z", "2026-10-01T00:00:00Z"), - blockRuns("d", &pulled, "2026-10-01T03:00:00.000Z"), + merged := mergeNewestFirst([]iter.Seq2[client.MeshBuildingBlockRun, error]{ + blockRuns(t, "a", &pulled, "2026-10-01T05:00:00Z", "2026-10-01T03:00:00Z", "2026-10-01T01:00:00Z"), + blockRuns(t, "empty", &pulled), + blockRuns(t, "c", &pulled, "2026-10-01T04:00:00Z", "2026-10-01T03:00:00Z", "2026-10-01T00:00:00Z"), + blockRuns(t, "d", &pulled, "2026-10-01T03:00:00.000Z"), }) - assert.Equal(t, []string{"a/0", "c/0", "a/1", "c/1", "d/0", "a/2", "c/2"}, uuidsOf(t, merged, 0), + assert.Equal(t, []string{"a/0", "c/0", "a/1", "c/1", "d/0", "a/2", "c/2"}, namesOf(t, merged, 0), "runs created at the same time keep the order of their blocks") }) t.Run("reads no block further than its first run or the last run it listed", func(t *testing.T) { var pulledA, pulledB, pulledC int - merged := mergeNewestFirst([]iter.Seq2[jsontext.Value, error]{ - blockRuns("a", &pulledA, "2026-10-01T05:00:00Z", "2026-10-01T04:00:00Z", "2026-10-01T03:00:00Z"), - blockRuns("b", &pulledB, "2026-10-01T02:00:00Z", "2026-10-01T01:00:00Z"), - blockRuns("c", &pulledC, "2026-10-01T01:00:00Z"), + merged := mergeNewestFirst([]iter.Seq2[client.MeshBuildingBlockRun, error]{ + blockRuns(t, "a", &pulledA, "2026-10-01T05:00:00Z", "2026-10-01T04:00:00Z", "2026-10-01T03:00:00Z"), + blockRuns(t, "b", &pulledB, "2026-10-01T02:00:00Z", "2026-10-01T01:00:00Z"), + blockRuns(t, "c", &pulledC, "2026-10-01T01:00:00Z"), }) - assert.Equal(t, []string{"a/0", "a/1"}, uuidsOf(t, merged, 2)) + assert.Equal(t, []string{"a/0", "a/1"}, namesOf(t, merged, 2)) assert.Equal(t, 2, pulledA, "no further than the last listed run of a") assert.Equal(t, 1, pulledB, "only the first run of b, before the merge listed any") assert.Equal(t, 1, pulledC, "only the first run of c, before the merge listed any") @@ -76,9 +73,11 @@ func TestMergeNewestFirst(t *testing.T) { t.Run("yields only the error of a block that fails before every block answered", func(t *testing.T) { var pulled int failure := errors.New("listing the runs of building block b failed") - merged := mergeNewestFirst([]iter.Seq2[jsontext.Value, error]{ - blockRuns("a", &pulled, "2026-10-01T05:00:00Z"), - func(yield func(jsontext.Value, error) bool) { yield(nil, failure) }, + merged := mergeNewestFirst([]iter.Seq2[client.MeshBuildingBlockRun, error]{ + blockRuns(t, "a", &pulled, "2026-10-01T05:00:00Z"), + func(yield func(client.MeshBuildingBlockRun, error) bool) { + yield(client.MeshBuildingBlockRun{}, failure) + }, }) var errs []error diff --git a/cmd/buildingblockrun/logs.go b/cmd/buildingblockrun/logs.go index dd9df62c..d5658697 100644 --- a/cmd/buildingblockrun/logs.go +++ b/cmd/buildingblockrun/logs.go @@ -8,22 +8,19 @@ import ( "log/slog" "strings" "time" - "uuid" "github.com/spf13/cobra" "github.com/meshcloud/meshstack-cli/client" "github.com/meshcloud/meshstack-cli/cmd/internal" - "github.com/meshcloud/meshstack-cli/internal/json" ) const followFlagName = "follow" func newLogs() *cobra.Command { var ( - output internal.OutputFlag - follow bool - runUuid uuid.UUID + output internal.OutputFlag + follow bool ) cmd := &cobra.Command{ @@ -37,8 +34,9 @@ With --` + followFlagName + `, the command prints new log lines as text until th Example: ` meshstack buildingblockrun logs 7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c meshstack bbrun logs 7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c -o ndjson meshstack bbrun logs 7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c --follow`, - Args: internal.UuidArg(&runUuid), - RunE: func(cmd *cobra.Command, _ []string) error { + Args: internal.UuidArg, + RunE: func(cmd *cobra.Command, args []string) error { + runUuid := args[0] ctx := cmd.Context() meshStack, err := internal.ResolveClient(ctx) if err != nil { @@ -46,10 +44,14 @@ With --` + followFlagName + `, the command prints new log lines as text until th } if follow { return followRun(ctx, cmd.OutOrStdout(), runUuid, func(ctx context.Context) (runSnapshot, error) { - return readRun(ctx, meshStack, runUuid) + return readSnapshot(ctx, meshStack, runUuid) }) } - logs, err := meshStack.Raw.Get[client.MeshBuildingBlockRun](ctx, runUuid, "logs") + run, err := readRun(ctx, meshStack, runUuid) + if err != nil { + return err + } + logs, err := run.Logs(ctx) if err != nil { return err } @@ -87,27 +89,33 @@ type runSnapshot struct { steps []client.MeshBuildingBlockRunStepLog } -// readRun reads the run's status before its logs, so that the logs of a finished run are its -// last ones. -func readRun(ctx context.Context, meshStack client.Client, runUuid uuid.UUID) (runSnapshot, error) { - rawRun, err := meshStack.Raw.Get[client.MeshBuildingBlockRun](ctx, runUuid) - if err != nil { - return runSnapshot{}, err - } - var run struct { - Status string `json:"status"` +var errRunNotFound = errors.New("building block run not found") + +func readRun(ctx context.Context, meshStack client.Client, runUuid string) (client.MeshBuildingBlockRun, error) { + run, err := meshStack.BuildingBlockRun.Read(ctx, runUuid) + switch { + case err != nil: + return client.MeshBuildingBlockRun{}, err + case run == nil: + return client.MeshBuildingBlockRun{}, fmt.Errorf("%w: %s", errRunNotFound, runUuid) } - if err = json.Unmarshal(rawRun, &run); err != nil { + return *run, nil +} + +// readSnapshot reads the status before the logs, so that a finished run's logs are its last ones. +func readSnapshot(ctx context.Context, meshStack client.Client, runUuid string) (runSnapshot, error) { + run, err := readRun(ctx, meshStack, runUuid) + if err != nil { return runSnapshot{}, err } - logs, err := meshStack.BuildingBlockRun.GetLogs(ctx, runUuid.String()) + logs, err := run.Logs(ctx) if err != nil { return runSnapshot{}, err } return runSnapshot{status: run.Status, steps: logs.Steps}, nil } -func followRun(ctx context.Context, w io.Writer, runUuid uuid.UUID, read func(context.Context) (runSnapshot, error)) error { +func followRun(ctx context.Context, w io.Writer, runUuid string, read func(context.Context) (runSnapshot, error)) error { var ( written writtenLogs readOnce bool @@ -153,7 +161,7 @@ func followRun(ctx context.Context, w io.Writer, runUuid uuid.UUID, read func(co } } -func stoppedFollowing(runUuid uuid.UUID) error { +func stoppedFollowing(runUuid string) error { return fmt.Errorf("stopped following building block run %s before it finished", runUuid) } @@ -161,10 +169,10 @@ func stoppedFollowing(runUuid uuid.UUID) error { // deleted, from a failure that can clear. func isClientError(err error) bool { httpErr, ok := errors.AsType[client.HttpError](err) - return ok && httpErr.IsClientError() + return ok && httpErr.IsClientError() || errors.Is(err, errRunNotFound) } -func (run runSnapshot) failure(runUuid uuid.UUID) error { +func (run runSnapshot) failure(runUuid string) error { var abortedStep string for _, step := range run.steps { switch step.Status { diff --git a/cmd/buildingblockrun/logs_test.go b/cmd/buildingblockrun/logs_test.go index e063f63c..6d73beb7 100644 --- a/cmd/buildingblockrun/logs_test.go +++ b/cmd/buildingblockrun/logs_test.go @@ -9,7 +9,6 @@ import ( "testing" "testing/synctest" "time" - "uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -17,7 +16,7 @@ import ( "github.com/meshcloud/meshstack-cli/client" ) -var runUuid = uuid.MustParse("7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c") +var runUuid = "7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c" func step(displayName, status string, userMessage, systemMessage *string) client.MeshBuildingBlockRunStepLog { return client.MeshBuildingBlockRunStepLog{DisplayName: displayName, Status: status, UserMessage: userMessage, SystemMessage: systemMessage} diff --git a/cmd/eventlog/list.go b/cmd/eventlog/list.go index c979a853..9f0f76a7 100644 --- a/cmd/eventlog/list.go +++ b/cmd/eventlog/list.go @@ -43,7 +43,7 @@ The command lists the event logs of the workspace. With an admin credential and if err != nil { return err } - filter := client.MeshEventLogListFilter{ + filter := client.MeshEventLogFilter{ From: from.instant, Until: until.instant, Title: title, @@ -52,7 +52,11 @@ The command lists the event logs of the workspace. With an admin credential and if workspace != nil { filter.WorkspaceIdentifier = *workspace } - return flags.Run[client.MeshEventLog](cmd, filter) + meshStack, err := internal.ResolveClient(cmd.Context()) + if err != nil { + return err + } + return flags.Run(cmd, meshStack.EventLog, filter) }, } diff --git a/cmd/internal/buildingblock/run_wait.go b/cmd/internal/buildingblock/run_wait.go index 5563db7e..49f22319 100644 --- a/cmd/internal/buildingblock/run_wait.go +++ b/cmd/internal/buildingblock/run_wait.go @@ -4,13 +4,10 @@ package buildingblock import ( "context" - "encoding/json/jsontext" "fmt" "time" - "uuid" "github.com/meshcloud/meshstack-cli/client" - "github.com/meshcloud/meshstack-cli/internal/json" ) const ( @@ -23,39 +20,39 @@ const ( ) type RunWait struct { - raw *client.RawClient - buildingBlockUuid uuid.UUID + blocks client.MeshBuildingBlockV2Client + buildingBlockUuid string startEvery time.Duration startWithin time.Duration endEvery time.Duration } -func NewRunWait(raw *client.RawClient, buildingBlockUuid uuid.UUID) RunWait { - return RunWait{raw, buildingBlockUuid, runStartPollInterval, runStartTimeout, runEndPollInterval} +func NewRunWait(blocks client.MeshBuildingBlockV2Client, buildingBlockUuid string) RunWait { + return RunWait{blocks, buildingBlockUuid, runStartPollInterval, runStartTimeout, runEndPollInterval} } // AwaitReaction returns the building block once meshStack has reacted to a write since before. -func (w RunWait) AwaitReaction(ctx context.Context, before client.MeshBuildingBlockV2Status) (jsontext.Value, *client.MeshBuildingBlockV2, error) { +func (w RunWait) AwaitReaction(ctx context.Context, before client.MeshBuildingBlockV2Status) (*client.MeshBuildingBlockV2, error) { ctx, cancel := context.WithTimeoutCause(ctx, w.startWithin, fmt.Errorf( "meshStack did not react to the write of building block %s within %s: it started no run and reported no failure to start one", w.buildingBlockUuid, w.startWithin)) defer cancel() - reacted, block, err := w.poll(ctx, w.startEvery, func(block *client.MeshBuildingBlockV2) (bool, error) { + block, err := w.poll(ctx, w.startEvery, func(block *client.MeshBuildingBlockV2) (bool, error) { return block.Status != nil && block.Status.RunChangedSince(before), nil }) - return reacted, block, withMeshPanelLink(err, block) + return block, withMeshPanelLink(err, block) } // AwaitEnd returns the building block once meshStack has reacted to a write since before, and the run // is no longer running. -func (w RunWait) AwaitEnd(ctx context.Context, before client.MeshBuildingBlockV2Status) (jsontext.Value, *client.MeshBuildingBlockV2, error) { - if _, _, err := w.AwaitReaction(ctx, before); err != nil { - return nil, nil, err +func (w RunWait) AwaitEnd(ctx context.Context, before client.MeshBuildingBlockV2Status) (*client.MeshBuildingBlockV2, error) { + if _, err := w.AwaitReaction(ctx, before); err != nil { + return nil, err } - ended, block, err := w.poll(ctx, w.endEvery, func(block *client.MeshBuildingBlockV2) (bool, error) { + block, err := w.poll(ctx, w.endEvery, func(block *client.MeshBuildingBlockV2) (bool, error) { return block.RunEndedSince(client.MeshBuildingBlockV2Status{}) }) - return ended, block, withMeshPanelLink(err, block) + return block, withMeshPanelLink(err, block) } func (w RunWait) StartFailure(block *client.MeshBuildingBlockV2) error { @@ -81,34 +78,36 @@ func (w RunWait) Outcome(block *client.MeshBuildingBlockV2) error { } func withMeshPanelLink(err error, block *client.MeshBuildingBlockV2) error { - if link := block.MeshPanelLink(); err != nil && link != "" { - return fmt.Errorf("%w. Open it in meshPanel: %s", err, link) + if err == nil || block == nil { + return err + } + if meshPanel, found := block.Links["meshPanel"]; found { + return fmt.Errorf("%w. Open it in meshPanel: %s", err, meshPanel.Href) } return err } // poll reads the building block every interval until done says so, and returns the last read, also // when ctx ends the poll. -func (w RunWait) poll(ctx context.Context, every time.Duration, done func(*client.MeshBuildingBlockV2) (bool, error)) (jsontext.Value, *client.MeshBuildingBlockV2, error) { +func (w RunWait) poll(ctx context.Context, every time.Duration, done func(*client.MeshBuildingBlockV2) (bool, error)) (*client.MeshBuildingBlockV2, error) { var last *client.MeshBuildingBlockV2 for { - current, err := w.raw.Get[client.MeshBuildingBlockV2](ctx, w.buildingBlockUuid) - if err != nil && ctx.Err() != nil { - return nil, last, context.Cause(ctx) - } else if err != nil { - return nil, last, err - } - var block client.MeshBuildingBlockV2 - if err := json.Unmarshal(current, &block); err != nil { - return nil, last, err + current, err := w.blocks.Read(ctx, w.buildingBlockUuid) + switch { + case err != nil && ctx.Err() != nil: + return last, context.Cause(ctx) + case err != nil: + return last, err + case current == nil: + return last, fmt.Errorf("building block %s not found", w.buildingBlockUuid) } - last = &block + last = current if ended, err := done(last); ended || err != nil { - return current, last, err + return last, err } select { case <-ctx.Done(): - return nil, last, context.Cause(ctx) + return last, context.Cause(ctx) case <-time.After(every): } } diff --git a/cmd/internal/buildingblock/run_wait_test.go b/cmd/internal/buildingblock/run_wait_test.go index 91ab5aaf..9c53ed52 100644 --- a/cmd/internal/buildingblock/run_wait_test.go +++ b/cmd/internal/buildingblock/run_wait_test.go @@ -6,7 +6,6 @@ import ( "sync/atomic" "testing" "time" - "uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -18,7 +17,7 @@ import ( ) func TestRunWait(t *testing.T) { - buildingBlockUuid := uuid.MustParse("b1d2c3e4-0000-4000-8000-000000000003") + buildingBlockUuid := "b1d2c3e4-0000-4000-8000-000000000003" before := client.MeshBuildingBlockV2Status{Action: client.BuildingBlockActionNoAction, LatestRunUuid: new("run-1")} var status atomic.Pointer[string] meshStack := fakemeshstack.Start(t, fakemeshstack.Options{}) @@ -26,13 +25,14 @@ func TestRunWait(t *testing.T) { _, _ = fmt.Fprintf(w, `{"metadata": {"uuid": %q}, "spec": {}, "status": {%s}, "_links": {"meshPanel": {"href": "https://panel.example/block"}}}`, buildingBlockUuid, *status.Load()) }) - raw := client.New(t.Context(), xurl.MustParsef("%s", meshStack.URL), http.NewClient(fakemeshstack.UserAgent), http.BearerToken(fakemeshstack.Token)).Raw - wait := RunWait{raw: raw, buildingBlockUuid: buildingBlockUuid, startEvery: time.Millisecond, startWithin: 50 * time.Millisecond} + blocks := client.New(t.Context(), xurl.MustParsef("%s", meshStack.URL), http.NewClient(fakemeshstack.UserAgent), http.BearerToken(fakemeshstack.Token)).BuildingBlockV2 + wait := NewRunWait(blocks, buildingBlockUuid) + wait.startEvery, wait.startWithin = time.Millisecond, 50*time.Millisecond t.Run("a preflight run that a trigger with an approval policy starts is a reaction", func(t *testing.T) { status.Store(new(`"action": "IN_PROGRESS", "latestRunUuid": "run-1", "latestDryRunUuid": "preflight-1"`)) - _, block, err := wait.AwaitReaction(t.Context(), before) + block, err := wait.AwaitReaction(t.Context(), before) require.NoError(t, err) assert.Equal(t, "preflight-1", block.Status.GetLatestDryRunUuid()) @@ -41,18 +41,18 @@ func TestRunWait(t *testing.T) { t.Run("fails when meshStack does not react within the start window", func(t *testing.T) { status.Store(new(`"action": "NO_ACTION", "latestRunUuid": "run-1"`)) - _, _, err := wait.AwaitReaction(t.Context(), before) + _, err := wait.AwaitReaction(t.Context(), before) - require.ErrorContains(t, err, "meshStack did not react to the write of building block "+buildingBlockUuid.String()+" within 50ms") + require.ErrorContains(t, err, "meshStack did not react to the write of building block "+buildingBlockUuid+" within 50ms") require.ErrorContains(t, err, "https://panel.example/block") }) t.Run("fails with the reason meshStack could not start the run", func(t *testing.T) { status.Store(new(`"action": "REVIEW_ERRORS", "latestRunUuid": "run-1", "runStartFailure": "no runner", "runStartFailedOn": "2026-10-29T10:00:00Z"`)) - _, block, err := wait.AwaitReaction(t.Context(), before) + block, err := wait.AwaitReaction(t.Context(), before) require.NoError(t, err) - require.ErrorContains(t, wait.StartFailure(block), "meshStack could not start the run of building block "+buildingBlockUuid.String()+": no runner") + require.ErrorContains(t, wait.StartFailure(block), "meshStack could not start the run of building block "+buildingBlockUuid+": no runner") }) } diff --git a/cmd/internal/color/color.go b/cmd/internal/color/color.go index 6e32039c..a8d923ad 100644 --- a/cmd/internal/color/color.go +++ b/cmd/internal/color/color.go @@ -87,7 +87,7 @@ func (e env) isOff(name string) bool { // evidence, and a log viewer outside the list, such as Jenkins without its AnsiColor plugin, shows // the escape codes as text. So does the system log of a building block run in meshPanel. Its // runner starts a script or tofu with neither CI nor TERM set, which keeps a run plain: see -// cleanSystemEnv in tf-block-runner/tfrun of ../building-block-runner. +// cleanSystemEnv in ../building-block-runner/internal/executor/tf/tfcmd.go. func (e env) ciProfile() colorprofile.Profile { has := func(name string) bool { _, found := e[name]; return found } switch { diff --git a/cmd/internal/flags.go b/cmd/internal/flags.go index 9ee4a753..de69a2ac 100644 --- a/cmd/internal/flags.go +++ b/cmd/internal/flags.go @@ -3,7 +3,6 @@ package internal import ( "context" "fmt" - "uuid" "github.com/spf13/pflag" @@ -38,7 +37,7 @@ func (n FlagName) String() string { return string(n) } -type Flag[T string | bool | uuid.UUID] struct { +type Flag[T string | bool] struct { Name FlagName Shorthand string Help string @@ -46,7 +45,7 @@ type Flag[T string | bool | uuid.UUID] struct { SettingEnvKey string } -func NewFlagForSetting[T string | bool | uuid.UUID](name FlagName, s setting.Setting) Flag[T] { +func NewFlagForSetting[T string | bool](name FlagName, s setting.Setting) Flag[T] { return Flag[T]{Name: name, Help: s.Help(), SettingEnvKey: s.EnvKey()} } @@ -61,8 +60,6 @@ func (flag *Flag[T]) Register(flags *pflag.FlagSet) (flagName string) { flags.StringVarP(v, flag.Name.String(), flag.Shorthand, *v, flag.Help) case *bool: flags.BoolVarP(v, flag.Name.String(), flag.Shorthand, *v, flag.Help) - case *uuid.UUID: - flags.VarP((*UuidFlag)(v), flag.Name.String(), flag.Shorthand, flag.Help) default: panic(fmt.Sprintf("cannot register flag with value type %T", flag.Value)) } diff --git a/cmd/internal/list.go b/cmd/internal/list.go index e3bb9b33..fcd58b9c 100644 --- a/cmd/internal/list.go +++ b/cmd/internal/list.go @@ -2,16 +2,17 @@ package internal import ( "context" - "encoding/json/jsontext" "fmt" "iter" "log/slog" "strconv" + "time" "github.com/spf13/cobra" "github.com/spf13/pflag" "github.com/meshcloud/meshstack-cli/client" + "github.com/meshcloud/meshstack-cli/client/types" ) type ListFlags struct { @@ -38,33 +39,42 @@ func ListWorkspace(ctx context.Context) (*string, error) { return &workspace, nil } -// Run lists the objects of M that filter narrows. -func (f *ListFlags) Run[M any](cmd *cobra.Command, filter any) error { - return f.RunSeq(cmd, func(ctx context.Context, meshStack client.Client, options client.ListOptions) iter.Seq2[jsontext.Value, error] { - return meshStack.Raw.List[M](ctx, filter, options) +func (f *ListFlags) Run[M, Filter any](cmd *cobra.Command, kind client.MeshObjectReadOnlyClient[M, Filter], filter Filter) error { + var page types.Page + return f.run(cmd, &page, func(ctx context.Context, options ...client.ListOption) iter.Seq2[any, error] { + return WithKindAndApiVersion(kind, kind.ListSeq(ctx, filter, append(options, client.WithCapturedPage(&page))...)) }) } +func WithKindAndApiVersion[M, Filter any](kind client.MeshObjectReadOnlyClient[M, Filter], objects iter.Seq2[M, error]) iter.Seq2[any, error] { + return func(yield func(any, error) bool) { + for object, err := range objects { + if err != nil { + yield(nil, err) + return + } + if !yield(client.WithKindAndApiVersion(kind, object), nil) { + return + } + } + } +} + // RunSeq is Run for a listing that is not one kind's, such as the runs of every building block. -func (f *ListFlags) RunSeq(cmd *cobra.Command, list func(ctx context.Context, meshStack client.Client, options client.ListOptions) iter.Seq2[jsontext.Value, error]) error { +func (f *ListFlags) RunSeq(cmd *cobra.Command, list func(ctx context.Context, options ...client.ListOption) iter.Seq2[any, error]) error { + return f.run(cmd, nil, list) +} + +func (f *ListFlags) run(cmd *cobra.Command, page *types.Page, list func(ctx context.Context, options ...client.ListOption) iter.Seq2[any, error]) error { ctx := cmd.Context() - meshStack, err := ResolveClient(ctx) - if err != nil { - return err - } result := ListResult{Limit: int(f.limit), Defaulted: !cmd.Flags().Changed(limitFlagName)} - listOptions := client.ListOptions{ - PageSize: result.Limit, - OnPage: func(page client.Page) { - if result.Total == nil { - result.Total = &page.TotalElements - } - }, - } - items := counted(First(list(ctx, meshStack, listOptions), result.Limit), &result.Listed) + items := counted(First(list(ctx, client.WithNewestFirst(time.Now()), client.WithPageSize(result.Limit)), result.Limit), &result.Listed) if err := f.output.Format.WriteList(cmd.OutOrStdout(), items); err != nil { return err } + if page != nil { + result.Total = &page.TotalElements + } if note := result.CutShortNote(); note != "" { slog.InfoContext(ctx, note) } diff --git a/cmd/internal/markdown/markdown_test.go b/cmd/internal/markdown/markdown_test.go index 95f31097..0516c3a1 100644 --- a/cmd/internal/markdown/markdown_test.go +++ b/cmd/internal/markdown/markdown_test.go @@ -6,7 +6,6 @@ import ( "testing" "testing/synctest" "time" - "uuid" "github.com/charmbracelet/x/ansi" "github.com/stretchr/testify/assert" @@ -48,7 +47,7 @@ func TestABrowserLoginShowsItsUserAccessAndSessionEnd(t *testing.T) { func TestAnApiKeyShowsItsClientIdAndNoCachedTokenYet(t *testing.T) { synctest.Test(t, func(t *testing.T) { - clientId := uuid.MustParse("11111111-45bf-42ba-a965-2097b9d0d181") + clientId := "11111111-45bf-42ba-a965-2097b9d0d181" status := auth.CredentialStatus{ Profile: "ci", Endpoint: xurl.MustParsef("https://meshstack.example.com"), Kind: credential.ApiKeyName, Sources: []string{"env MESHSTACK_API_KEY", "env MESHSTACK_API_SECRET"}, diff --git a/cmd/internal/output.go b/cmd/internal/output.go index 101dba7a..d8da742c 100644 --- a/cmd/internal/output.go +++ b/cmd/internal/output.go @@ -60,7 +60,7 @@ func (f *OutputFlag) Type() string { // WriteList leaves a listing that fails part way through unterminated, so that json output which // stopped early does not parse as a complete array. ndjson has no end to leave out, so there only // the exit status tells a cut listing from a complete one. -func (format OutputFormat) WriteList(w io.Writer, items iter.Seq2[jsontext.Value, error]) error { +func (format OutputFormat) WriteList(w io.Writer, items iter.Seq2[any, error]) error { list, err := format.listing() if err != nil { return err @@ -70,14 +70,19 @@ func (format OutputFormat) WriteList(w io.Writer, items iter.Seq2[jsontext.Value if itemErr != nil { return itemErr } + encoded, marshalErr := json.Marshal(item) + if marshalErr != nil { + return marshalErr + } separator := list.between if written == 0 { separator = list.begin } - if err = list.format(&item); err != nil { + value := jsontext.Value(encoded) + if err = list.format(&value); err != nil { return err } - if _, err = fmt.Fprintf(w, "%s%s%s", separator, item, list.after); err != nil { + if _, err = fmt.Fprintf(w, "%s%s%s", separator, value, list.after); err != nil { return err } written++ @@ -90,8 +95,12 @@ func (format OutputFormat) WriteList(w io.Writer, items iter.Seq2[jsontext.Value return err } -func (format OutputFormat) WriteItem(w io.Writer, item jsontext.Value) error { - var err error +func (format OutputFormat) WriteItem(w io.Writer, object any) error { + encoded, err := json.Marshal(object) + if err != nil { + return err + } + item := jsontext.Value(encoded) switch format { case OutputNdjson: err = item.Compact() diff --git a/cmd/internal/output_test.go b/cmd/internal/output_test.go index 6a338da0..4702daae 100644 --- a/cmd/internal/output_test.go +++ b/cmd/internal/output_test.go @@ -13,8 +13,8 @@ import ( "github.com/meshcloud/meshstack-cli/cmd/internal" ) -func items(values ...string) iter.Seq2[jsontext.Value, error] { - return func(yield func(jsontext.Value, error) bool) { +func items(values ...string) iter.Seq2[any, error] { + return func(yield func(any, error) bool) { for _, value := range values { if !yield(jsontext.Value(value), nil) { return @@ -118,7 +118,7 @@ func TestAnEmptyListing(t *testing.T) { func TestAFailingPageStopsTheListing(t *testing.T) { pageErr := errors.New("page 1 failed") - failing := func(yield func(jsontext.Value, error) bool) { + failing := func(yield func(any, error) bool) { if yield(jsontext.Value(`{"kind":"meshWorkspace"}`), nil) { yield(nil, pageErr) } diff --git a/cmd/internal/testacc/api_get_test.go b/cmd/internal/testacc/api_get_test.go index 5e76392c..5e03738e 100644 --- a/cmd/internal/testacc/api_get_test.go +++ b/cmd/internal/testacc/api_get_test.go @@ -165,7 +165,7 @@ func (o *firstObjects) get(ctx context.Context, r getRequest, operation openapi. if mediaType, ok := operation.LatestMediaType(); ok { options = append(options, http.WithHeader("Accept", mediaType.Name)) } - body, err := o.meshStack.Raw.DoRequest(ctx, gohttp.MethodGet, r.path, options...) + body, err := http.ReadAllBody(o.meshStack.HttpClient.DoRequest(ctx, gohttp.MethodGet, o.meshStack.Endpoint.JoinPath(r.path), options...)) if httpErr, ok := errors.AsType[client.HttpError](err); ok { return httpErr.StatusCode, string(httpErr.ResponseBody), nil } diff --git a/cmd/internal/testacc/api_test.go b/cmd/internal/testacc/api_test.go index b3b77575..f80d9e66 100644 --- a/cmd/internal/testacc/api_test.go +++ b/cmd/internal/testacc/api_test.go @@ -7,7 +7,6 @@ import ( "github.com/stretchr/testify/require" "github.com/meshcloud/meshstack-cli/client" - "github.com/meshcloud/meshstack-cli/internal/json" ) // apiAsksForJson checks the answers of meshStack that request.negotiate in cmd/api relies on where @@ -39,17 +38,9 @@ func apiDeletesWithNoMediaType(c *cli) func(*testing.T) { func apiFollowsASelfLink(c *cli) func(*testing.T) { return func(t *testing.T) { var href string - for item, err := range c.client(t).Raw.List[client.MeshWorkspace](t.Context(), nil, client.ListOptions{PageSize: 1}) { + for workspace, err := range c.client(t).Workspace.ListSeq(t.Context(), client.NoFilter{}, client.WithPageSize(1)) { require.NoError(t, err) - var links struct { - Links struct { - Self struct { - Href string `json:"href"` - } `json:"self"` - } `json:"_links"` - } - require.NoError(t, json.Unmarshal(item, &links)) - href = links.Links.Self.Href + href = workspace.Links["self"].Href break } require.NotEmpty(t, href, "the workspace list answers no workspace with a self link") diff --git a/cmd/internal/uuid.go b/cmd/internal/uuid.go index 63168f7b..46cb46a7 100644 --- a/cmd/internal/uuid.go +++ b/cmd/internal/uuid.go @@ -9,21 +9,17 @@ import ( // UuidFlag and [UuidArg] reject a malformed uuid while cobra parses the command line. meshStack // answers one with an empty list or a 404, which says nothing about a typo. -type UuidFlag uuid.UUID +type UuidFlag string func (f *UuidFlag) String() string { - if *f == (UuidFlag{}) { - return "" - } - return uuid.UUID(*f).String() + return string(*f) } func (f *UuidFlag) Set(value string) error { - parsed, err := uuid.Parse(value) - if err != nil { + if _, err := uuid.Parse(value); err != nil { return err } - *f = UuidFlag(parsed) + *f = UuidFlag(value) return nil } @@ -31,16 +27,12 @@ func (f *UuidFlag) Type() string { return "uuid" } -func UuidArg(id *uuid.UUID) cobra.PositionalArgs { - return func(cmd *cobra.Command, args []string) error { - if err := cobra.ExactArgs(1)(cmd, args); err != nil { - return err - } - parsed, err := uuid.Parse(args[0]) - if err != nil { - return fmt.Errorf("invalid argument %q: %w", args[0], err) - } - *id = parsed - return nil +func UuidArg(cmd *cobra.Command, args []string) error { + if err := cobra.ExactArgs(1)(cmd, args); err != nil { + return err } + if _, err := uuid.Parse(args[0]); err != nil { + return fmt.Errorf("invalid argument %q: %w", args[0], err) + } + return nil } diff --git a/cmd/internal/uuid_test.go b/cmd/internal/uuid_test.go index 038cdbdd..bdb17e54 100644 --- a/cmd/internal/uuid_test.go +++ b/cmd/internal/uuid_test.go @@ -2,7 +2,6 @@ package internal_test import ( "testing" - "uuid" "github.com/spf13/cobra" "github.com/spf13/pflag" @@ -13,14 +12,14 @@ import ( ) func TestAUuidFlagFailsWhileTheFlagsAreParsed(t *testing.T) { - var id uuid.UUID + var id string flags := pflag.NewFlagSet("test", pflag.ContinueOnError) flags.Var((*internal.UuidFlag)(&id), "definition", "") require.EqualError(t, flags.Parse([]string{"--definition", "my-definition"}), `invalid argument "my-definition" for "--definition" flag: invalid uuid`) require.NoError(t, flags.Parse([]string{"--definition", "3c9e1f7a-2b4d-4e6f-8a1c-5d7b9e2f4a6c"})) - assert.Equal(t, uuid.MustParse("3c9e1f7a-2b4d-4e6f-8a1c-5d7b9e2f4a6c"), id) + assert.Equal(t, "3c9e1f7a-2b4d-4e6f-8a1c-5d7b9e2f4a6c", id) } func TestAnUnsetUuidFlagShowsNoDefault(t *testing.T) { @@ -30,27 +29,24 @@ func TestAnUnsetUuidFlagShowsNoDefault(t *testing.T) { assert.Equal(t, " --definition uuid the definition\n", flags.FlagUsages()) } -func TestUuidArgParsesTheOnlyArgument(t *testing.T) { +func TestUuidArgChecksTheOnlyArgument(t *testing.T) { tests := []struct { name string args []string - want uuid.UUID wantErr string }{ - {name: "a uuid", args: []string{"7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c"}, want: uuid.MustParse("7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c")}, + {name: "a uuid", args: []string{"7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c"}}, {name: "no uuid", args: []string{"my-run"}, wantErr: `invalid argument "my-run": invalid uuid`}, {name: "two arguments", args: []string{"7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c", "more"}, wantErr: "accepts 1 arg(s), received 2"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - var id uuid.UUID - err := internal.UuidArg(&id)(&cobra.Command{}, tt.args) + err := internal.UuidArg(&cobra.Command{}, tt.args) if tt.wantErr != "" { assert.EqualError(t, err, tt.wantErr) return } require.NoError(t, err) - assert.Equal(t, tt.want, id) }) } } diff --git a/cmd/profile/form.go b/cmd/profile/form.go index ecf824dc..3e63e41a 100644 --- a/cmd/profile/form.go +++ b/cmd/profile/form.go @@ -335,5 +335,5 @@ func listWorkspaces(ctx context.Context, p *profile.Profile) ([]client.MeshWorks if err != nil { return nil, err } - return c.Workspace.List(ctx) + return c.Workspace.List(ctx, client.NoFilter{}) } diff --git a/cmd/profile/form_test.go b/cmd/profile/form_test.go index 2c96db74..52e8da33 100644 --- a/cmd/profile/form_test.go +++ b/cmd/profile/form_test.go @@ -2,7 +2,6 @@ package profile import ( "testing" - "uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -53,7 +52,7 @@ func TestTheWorkspacesThatTheProfilesAtTheEndpointReachAreSuggested(t *testing.T ) credentials, err := profiles.Profiles["ci"].Credentials(t.Context()) require.NoError(t, err) - credentials.Set(&credential.ApiKey{Endpoint: endpoint, ClientId: uuid.MustParse(apiKey.ClientId), ClientSecret: apiKey.ClientSecret}) + credentials.Set(&credential.ApiKey{Endpoint: endpoint, ClientId: apiKey.ClientId, ClientSecret: apiKey.ClientSecret}) require.NoError(t, credentials.Store(t.Context())) // The logged-out profile is asked as well, and fails without a call. diff --git a/cmd/workspace/list.go b/cmd/workspace/list.go index 99546fce..927dd5ee 100644 --- a/cmd/workspace/list.go +++ b/cmd/workspace/list.go @@ -20,7 +20,11 @@ If you work in the admin workspace and have a role that can list all workspaces, meshstack ws list --workspace admin-workspace --limit unlimited -o ndjson`, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { - return flags.Run[client.MeshWorkspace](cmd, client.MeshWorkspaceListFilter{}) + meshStack, err := internal.ResolveClient(cmd.Context()) + if err != nil { + return err + } + return flags.Run(cmd, meshStack.Workspace, client.NoFilter{}) }, } diff --git a/cmd/workspace/list_test.go b/cmd/workspace/list_test.go index e7df607e..94649830 100644 --- a/cmd/workspace/list_test.go +++ b/cmd/workspace/list_test.go @@ -29,7 +29,7 @@ func TestAListCutShortByTheLimitSaysHowManyThereAre(t *testing.T) { require.NoError(t, cmd.ExecuteContext(t.Context())) - assert.JSONEq(t, `[{"metadata":{"name":"workspace-0"}}]`, stdout.String()) + assert.JSONEq(t, `[{"apiVersion":"v2","kind":"meshWorkspace","metadata":{"name":"workspace-0","tags":{}},"spec":{"displayName":""}}]`, stdout.String()) assert.Contains(t, captured.String(), "listed the first 1 of 6") assert.Len(t, server.TakeRequests(), 1) } diff --git a/internal/auth/cache_test.go b/internal/auth/cache_test.go index 956cb9eb..6be8430d 100644 --- a/internal/auth/cache_test.go +++ b/internal/auth/cache_test.go @@ -5,7 +5,6 @@ import ( "os" "path/filepath" "testing" - "uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -32,7 +31,7 @@ func TestCache(t *testing.T) { } token := jsontest.MustUnmarshal[jwt.JWT](t, jwtJson) apiKey := func(clientId string) *credential.ApiKey { - return &credential.ApiKey{Endpoint: p.Endpoint, ClientId: uuid.MustParse(clientId), ClientSecret: "super-test-secret"} + return &credential.ApiKey{Endpoint: p.Endpoint, ClientId: clientId, ClientSecret: "super-test-secret"} } const stored, fromEnvironment = "11111111-45bf-42ba-a965-2097b9d0d181", "22222222-45bf-42ba-a965-2097b9d0d181" reloadedToken := func(t *testing.T) jwt.JWT { diff --git a/internal/auth/credential/apikey.go b/internal/auth/credential/apikey.go index 2a31c0a2..8e9c91d7 100644 --- a/internal/auth/credential/apikey.go +++ b/internal/auth/credential/apikey.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "uuid" "github.com/meshcloud/meshstack-cli/client/http" "github.com/meshcloud/meshstack-cli/client/types/xurl" @@ -15,8 +14,8 @@ var _ Credential = &ApiKey{} type ApiKey struct { Endpoint xurl.URL - ClientId uuid.UUID `json:"client_id"` - ClientSecret string `json:"client_secret"` + ClientId string `json:"client_id"` + ClientSecret string `json:"client_secret"` Cache *struct { Token jwt.JWT `json:"token,omitzero"` @@ -42,8 +41,8 @@ func (apiKey *ApiKey) RefreshCachedToken(ctx context.Context, client http.Client loginEndpoint := apiKey.Endpoint.JoinPath("api", "login") payload := struct { - ClientId uuid.UUID `json:"clientId"` - ClientSecret string `json:"clientSecret"` + ClientId string `json:"clientId"` + ClientSecret string `json:"clientSecret"` }{apiKey.ClientId, apiKey.ClientSecret} answer, err := http.UnmarshalJsonBody[struct { diff --git a/internal/auth/credential_apikey.go b/internal/auth/credential_apikey.go index 616a6d69..a3b738c2 100644 --- a/internal/auth/credential_apikey.go +++ b/internal/auth/credential_apikey.go @@ -5,13 +5,12 @@ import ( "errors" "fmt" "log/slog" - "uuid" "github.com/meshcloud/meshstack-cli/internal/auth/credential" "github.com/meshcloud/meshstack-cli/internal/setting" ) -var ApiKeyClientIdSetting = setting.Setting[uuid.UUID]{ +var ApiKeyClientIdSetting = setting.Setting[string]{ Env: "MESHSTACK_API_KEY", Short: func(envKey string) string { return fmt.Sprintf("The client id of a meshStack API key to authenticate with, together with its secret from %s. Also read from %s.", ApiKeyClientSecretSetting.EnvKey(), envKey) @@ -19,7 +18,7 @@ var ApiKeyClientIdSetting = setting.Setting[uuid.UUID]{ Long: func(envKey string) string { return fmt.Sprintf("The client id of a meshStack API key to authenticate with, together with its secret, also read from `%s`.", envKey) }, - Parse: setting.ParseTextUnmarshaler[uuid.UUID], + Parse: setting.ParseText[string], } var ApiKeyClientSecretSetting = setting.Setting[string]{ diff --git a/internal/auth/login.go b/internal/auth/login.go index 1adf567b..0c765e14 100644 --- a/internal/auth/login.go +++ b/internal/auth/login.go @@ -125,7 +125,7 @@ func (s Session) resolveWorkspaceForLogin(ctx context.Context, opts ResolveSessi if err != nil { return r, err } - r.Items, err = c.Workspace.List(ctx) + r.Items, err = c.Workspace.List(ctx, client.NoFilter{}) if httpError, ok := errors.AsType[http.Error](err); ok && httpError.IsForbidden() { slog.DebugContext(ctx, "meshStack refused the workspace list: "+httpError.Error()) err = meshstack.NoWorkspaceToWorkInError{MayNotList: true} diff --git a/internal/auth/session_test.go b/internal/auth/session_test.go index 185cf449..897e926b 100644 --- a/internal/auth/session_test.go +++ b/internal/auth/session_test.go @@ -8,11 +8,11 @@ import ( "net/url" "testing" "time" - "uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/meshcloud/meshstack-cli/client" "github.com/meshcloud/meshstack-cli/client/http" "github.com/meshcloud/meshstack-cli/client/types/xurl" "github.com/meshcloud/meshstack-cli/internal/auth" @@ -223,7 +223,7 @@ func TestARefreshFinishesAndIsCachedThoughItsContextIsCancelledMidway(t *testing Name: "slow", Endpoint: xurl.MustParsef("%s", server.URL), Credential: credential.ApiKeyName, ConfigDir: config.Directory(t.TempDir()), } - apiKey := &credential.ApiKey{Endpoint: p.Endpoint, ClientId: uuid.MustParse(testApiKey1.ClientId), ClientSecret: testApiKey1.ClientSecret} + apiKey := &credential.ApiKey{Endpoint: p.Endpoint, ClientId: testApiKey1.ClientId, ClientSecret: testApiKey1.ClientSecret} creds, err := p.Credentials(t.Context()) require.NoError(t, err) creds.Set(apiKey) @@ -238,7 +238,7 @@ func TestARefreshFinishesAndIsCachedThoughItsContextIsCancelledMidway(t *testing require.NoError(t, err) listed := make(chan error, 1) go func() { - _, err := c.Workspace.List(ctx) + _, err := c.Workspace.List(ctx, client.NoFilter{}) listed <- err }() <-requested diff --git a/internal/auth/status.go b/internal/auth/status.go index fa5641b1..5ad7854f 100644 --- a/internal/auth/status.go +++ b/internal/auth/status.go @@ -9,7 +9,6 @@ import ( "maps" "slices" "time" - "uuid" "github.com/meshcloud/meshstack-cli/client/types/xurl" "github.com/meshcloud/meshstack-cli/internal/auth/credential" @@ -92,7 +91,7 @@ func BrowserLoginEnded(ctx context.Context, p *profile.Profile) bool { } type ApiKeyStatus struct { - ClientId uuid.UUID `json:"clientId"` + ClientId string `json:"clientId"` } // Status reads only the stored credential and its cached token, and calls no meshStack. It never @@ -150,7 +149,7 @@ func (s Session) unusedCredentials(ctx context.Context, workspace meshstack.Work entry := UnusedCredential{Kind: name, Selected: name == s.CurrentProfile.Credential} switch cred := cred.(type) { case *credential.ApiKey: - entry.ClientId = cred.ClientId.String() + entry.ClientId = cred.ClientId case *credential.OidcLogin: if token, found := oidcTokenFor(cred, workspace); found { entry.Token = tokenStatusOf(token) diff --git a/internal/auth/status_test.go b/internal/auth/status_test.go index 764a39ae..2aefc3c9 100644 --- a/internal/auth/status_test.go +++ b/internal/auth/status_test.go @@ -5,7 +5,6 @@ import ( "log/slog" "testing" "time" - "uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -68,7 +67,7 @@ func TestStatusOfABrowserLogin(t *testing.T) { t.Run("lists the stored credentials besides the one in use", func(t *testing.T) { creds, err := p.Credentials(t.Context()) require.NoError(t, err) - creds.Set(&credential.ApiKey{Endpoint: p.Endpoint, ClientId: uuid.MustParse(testApiKey2.ClientId), ClientSecret: testApiKey2.ClientSecret}) + creds.Set(&credential.ApiKey{Endpoint: p.Endpoint, ClientId: testApiKey2.ClientId, ClientSecret: testApiKey2.ClientSecret}) require.NoError(t, creds.Store(t.Context())) assert.Equal(t, []auth.UnusedCredential{{Kind: credential.ApiKeyName, ClientId: testApiKey2.ClientId}}, status(t).Unused) @@ -86,7 +85,7 @@ func TestStatusOfAnApiKeyIsReadFromFilesAndTheEnvironment(t *testing.T) { assert.Equal(t, []string{"env MESHSTACK_API_KEY", "env MESHSTACK_API_SECRET"}, status.Sources) require.NotNil(t, status.ApiKey) - assert.Equal(t, testApiKey1.ClientId, status.ApiKey.ClientId.String()) + assert.Equal(t, testApiKey1.ClientId, status.ApiKey.ClientId) assert.Nil(t, status.Token, "no token is cached before the key is first used") assert.Empty(t, captured.Records(slog.LevelWarn)) } diff --git a/internal/profile/resolve_test.go b/internal/profile/resolve_test.go index 3a3b5fb4..5d5e8806 100644 --- a/internal/profile/resolve_test.go +++ b/internal/profile/resolve_test.go @@ -213,7 +213,7 @@ func assertApiKey(t *testing.T, p *Profile, clientId, clientSecret string) { creds, err := p.Credentials(t.Context()) require.NoError(t, err) require.NotNil(t, creds.ApiKey) - assert.Equal(t, clientId, creds.ApiKey.ClientId.String()) + assert.Equal(t, clientId, creds.ApiKey.ClientId) assert.Equal(t, clientSecret, creds.ApiKey.ClientSecret) } diff --git a/internal/tfstate/backups.go b/internal/tfstate/backups.go index 2098fcb6..efc0b89b 100644 --- a/internal/tfstate/backups.go +++ b/internal/tfstate/backups.go @@ -5,14 +5,13 @@ import ( "os" "path/filepath" "time" - "uuid" ) type Backups string // save names the file by the time down to the nanosecond, so that two writes within one second keep // a backup each. -func (b Backups) save(buildingBlock uuid.UUID, state []byte, at time.Time) (path string, err error) { +func (b Backups) save(buildingBlock string, state []byte, at time.Time) (path string, err error) { if err = os.MkdirAll(string(b), 0o700); err != nil { return "", err } diff --git a/internal/tfstate/buildingblock.go b/internal/tfstate/buildingblock.go index d555ab49..ae021b9c 100644 --- a/internal/tfstate/buildingblock.go +++ b/internal/tfstate/buildingblock.go @@ -3,40 +3,36 @@ package tfstate import ( "context" "fmt" - "uuid" "github.com/meshcloud/meshstack-cli/client" - "github.com/meshcloud/meshstack-cli/internal/json" ) -type buildingBlock struct { - Metadata client.MeshBuildingBlockV2Metadata `json:"metadata"` - Status *client.MeshBuildingBlockV2Status `json:"status"` -} - -func readBuildingBlock(ctx context.Context, raw *client.RawClient, buildingBlockUuid uuid.UUID) (block buildingBlock, err error) { - read, err := raw.Get[client.MeshBuildingBlockV2](ctx, buildingBlockUuid) - if err != nil { - return block, err +func readBuildingBlock(ctx context.Context, blocks client.MeshBuildingBlockV2Client, buildingBlockUuid string) (client.MeshBuildingBlockV2, error) { + block, err := blocks.Read(ctx, buildingBlockUuid) + switch { + case err != nil: + return client.MeshBuildingBlockV2{}, err + case block == nil: + return client.MeshBuildingBlockV2{}, fmt.Errorf("building block %s not found", buildingBlockUuid) } - return block, json.Unmarshal(read, &block) + return *block, nil } // OpenStore opens the state under the building block's own workspace where workspace is empty, // because that is where the runner stores it. -func OpenStore(ctx context.Context, raw *client.RawClient, workspace string, buildingBlockUuid uuid.UUID) (Store, error) { +func OpenStore(ctx context.Context, meshStack client.Client, workspace string, buildingBlockUuid string) (Store, error) { if workspace == "" { - block, err := readBuildingBlock(ctx, raw, buildingBlockUuid) + block, err := readBuildingBlock(ctx, meshStack.BuildingBlockV2, buildingBlockUuid) if err != nil { return Store{}, err } workspace = block.Metadata.OwnedByWorkspace } - return NewStore(raw, workspace, buildingBlockUuid), nil + return NewStore(meshStack.HttpClient, meshStack.Endpoint, workspace, buildingBlockUuid), nil } -func NoRunOf(ctx context.Context, raw *client.RawClient, buildingBlockUuid uuid.UUID) error { - block, err := readBuildingBlock(ctx, raw, buildingBlockUuid) +func NoRunOf(ctx context.Context, blocks client.MeshBuildingBlockV2Client, buildingBlockUuid string) error { + block, err := readBuildingBlock(ctx, blocks, buildingBlockUuid) if err != nil { return err } diff --git a/internal/tfstate/lock.go b/internal/tfstate/lock.go index 7f25f203..3aa8a97b 100644 --- a/internal/tfstate/lock.go +++ b/internal/tfstate/lock.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "time" - "uuid" "github.com/meshcloud/meshstack-cli/client" "github.com/meshcloud/meshstack-cli/client/http" @@ -41,23 +40,18 @@ func (l Lock) String() string { } // NoUnfinishedRun passes a lock that a person holds. -func (l Lock) NoUnfinishedRun(ctx context.Context, raw *client.RawClient) error { +func (l Lock) NoUnfinishedRun(ctx context.Context, runs client.MeshBuildingBlockRunClient) error { if l.Holder.RunUuid == "" { return nil } - runUuid, err := uuid.Parse(l.Holder.RunUuid) - if err != nil { - return fmt.Errorf("the lock belongs to run %q, which is not a valid uuid: %w", l.Holder.RunUuid, err) - } - read, err := raw.Get[client.MeshBuildingBlockRun](ctx, runUuid) - if err != nil { + runUuid := l.Holder.RunUuid + run, err := runs.Read(ctx, runUuid) + switch { + case err != nil: return err - } - var run client.MeshBuildingBlockRun - if err = json.Unmarshal(read, &run); err != nil { - return err - } - if run.IsRunning() { + case run == nil: + return fmt.Errorf("building block run %s holds the lock, but meshStack does not know it", runUuid) + case run.IsRunning(): return fmt.Errorf("building block run %s holds the lock, is %s and is still writing the state", runUuid, run.Status) } return nil diff --git a/internal/tfstate/proxy.go b/internal/tfstate/proxy.go index 5a77f150..09b172f5 100644 --- a/internal/tfstate/proxy.go +++ b/internal/tfstate/proxy.go @@ -284,7 +284,7 @@ func (p *Proxy) write(w gohttp.ResponseWriter, r *gohttp.Request) { p.refuse(w, r, gohttp.StatusInternalServerError, fmt.Errorf("cannot back up the stored state, so it stays as it is: %w", err)) return } - slog.InfoContext(ctx, "Saved the stored state of building block "+p.Store.BuildingBlock.String()+" to "+path) + slog.InfoContext(ctx, "Saved the stored state of building block "+p.Store.BuildingBlock+" to "+path) } lockId := r.URL.Query().Get("ID") diff --git a/internal/tfstate/proxy_test.go b/internal/tfstate/proxy_test.go index 9537d652..f60fc153 100644 --- a/internal/tfstate/proxy_test.go +++ b/internal/tfstate/proxy_test.go @@ -15,12 +15,12 @@ import ( "sync" "testing" "time" - "uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/meshcloud/meshstack-cli/client/http" + "github.com/meshcloud/meshstack-cli/client/types/xurl" "github.com/meshcloud/meshstack-cli/internal/oidc/jwt" "github.com/meshcloud/meshstack-cli/internal/testutil/fakemeshstack" ) @@ -32,16 +32,7 @@ const ( nextState = `{"version":4,"serial":2,"lineage":"lineage-1"}` ) -var buildingBlockUuid = uuid.MustParse("b1d2c3e4-0000-4000-8000-000000000001") - -type requester struct { - endpoint *url.URL -} - -func (r requester) DoRequest(ctx context.Context, method, path string, opts ...http.RequestOption) ([]byte, error) { - return http.ReadAllBody(http.NewClient(fakemeshstack.UserAgent).WithAuthorization(http.BearerToken(fakemeshstack.Token)). - DoRequest(ctx, method, r.endpoint.JoinPath(path), opts...)) -} +var buildingBlockUuid = "b1d2c3e4-0000-4000-8000-000000000001" type proxyUnderTest struct { *Proxy @@ -50,7 +41,7 @@ type proxyUnderTest struct { problems []error } -var storedState = fakemeshstack.TfState{Workspace: "my-workspace", BuildingBlockUuid: buildingBlockUuid.String()} +var storedState = fakemeshstack.TfState{Workspace: "my-workspace", BuildingBlockUuid: buildingBlockUuid} func newProxy(t *testing.T, stored string, writable bool) *proxyUnderTest { t.Helper() @@ -63,7 +54,7 @@ func newProxy(t *testing.T, stored string, writable bool) *proxyUnderTest { require.NoError(t, err) p := &proxyUnderTest{meshStack: meshStack} p.Proxy = &Proxy{ - Store: NewStore(requester{endpoint}, "my-workspace", buildingBlockUuid), + Store: NewStore(http.NewClient(fakemeshstack.UserAgent).WithAuthorization(http.BearerToken(fakemeshstack.Token)), xurl.URL{URL: endpoint}, "my-workspace", buildingBlockUuid), Writable: writable, Backups: Backups(filepath.Join(t.TempDir(), "not", "yet", "there")), OnProblem: func(_ context.Context, err error) { p.problems = append(p.problems, err) }, @@ -118,7 +109,7 @@ func (p *proxyUnderTest) backups(t *testing.T) []string { require.NoError(t, err) var contents []string for _, file := range files { - assert.True(t, strings.HasPrefix(file, buildingBlockUuid.String()+"-"), file) + assert.True(t, strings.HasPrefix(file, buildingBlockUuid+"-"), file) info, err := fs.Stat(backups, file) require.NoError(t, err) assert.Equal(t, os.FileMode(0o600), info.Mode().Perm()) @@ -286,7 +277,7 @@ func TestAReadOnlyProxy(t *testing.T) { assert.Equal(t, gohttp.StatusOK, w.Code) assert.JSONEq(t, firstState, w.Body.String()) - assert.Equal(t, []string{"GET /api/terraform/state/workspace/my-workspace/buildingBlock/" + buildingBlockUuid.String()}, p.requests()) + assert.Equal(t, []string{"GET /api/terraform/state/workspace/my-workspace/buildingBlock/" + buildingBlockUuid}, p.requests()) }) t.Run("answers tofu's lock calls itself, so that a plan never makes a run wait", func(t *testing.T) { @@ -416,7 +407,7 @@ func (l *lockOf) serve(w gohttp.ResponseWriter, r *gohttp.Request) { func TestAWritableProxyPassesTheLockOn(t *testing.T) { p := newProxy(t, firstState, true) lock := &lockOf{} - p.meshStack.Route("/api/terraform/state/workspace/my-workspace/buildingBlock/"+buildingBlockUuid.String()+"/lock", lock.serve) + p.meshStack.Route("/api/terraform/state/workspace/my-workspace/buildingBlock/"+buildingBlockUuid+"/lock", lock.serve) var log lockedLog previous := slog.Default() t.Cleanup(func() { slog.SetDefault(previous) }) @@ -451,7 +442,7 @@ func TestAWritableProxyPassesTheLockOn(t *testing.T) { }) t.Run("passes a write that meshStack refuses for another's lock back as 423, and logs the holder rather than a problem", func(t *testing.T) { - writeInMeshStack := "POST /api/terraform/state/workspace/my-workspace/buildingBlock/" + buildingBlockUuid.String() + writeInMeshStack := "POST /api/terraform/state/workspace/my-workspace/buildingBlock/" + buildingBlockUuid p.meshStack.Route(writeInMeshStack, func(w gohttp.ResponseWriter, _ *gohttp.Request) { w.WriteHeader(gohttp.StatusLocked) _, _ = w.Write([]byte(lockInfo("theirs"))) @@ -477,7 +468,7 @@ func TestAWritableProxyPassesTheLockOn(t *testing.T) { }) t.Run("passes a 5xx of meshStack on for tofu to retry, and logs it rather than a problem", func(t *testing.T) { - lockInMeshStack := "POST /api/terraform/state/workspace/my-workspace/buildingBlock/" + buildingBlockUuid.String() + "/lock" + lockInMeshStack := "POST /api/terraform/state/workspace/my-workspace/buildingBlock/" + buildingBlockUuid + "/lock" p.meshStack.Route(lockInMeshStack, func(w gohttp.ResponseWriter, _ *gohttp.Request) { w.WriteHeader(gohttp.StatusInternalServerError) }) @@ -485,7 +476,7 @@ func TestAWritableProxyPassesTheLockOn(t *testing.T) { assert.Equal(t, gohttp.StatusInternalServerError, p.sendTo(gohttp.MethodPost, lockPath, lockInfo("mine")).Code) assert.Empty(t, p.problems, "tofu fails the command itself where its retries fail as well") - assert.Contains(t, log.String(), "cannot lock the state of building block "+buildingBlockUuid.String()) + assert.Contains(t, log.String(), "cannot lock the state of building block "+buildingBlockUuid) }) t.Run("releases the lock in meshStack", func(t *testing.T) { diff --git a/internal/tfstate/store.go b/internal/tfstate/store.go index 91ba679f..1660e835 100644 --- a/internal/tfstate/store.go +++ b/internal/tfstate/store.go @@ -7,9 +7,10 @@ import ( "encoding/json/jsontext" "errors" "fmt" - "uuid" + "net/url" "github.com/meshcloud/meshstack-cli/client/http" + "github.com/meshcloud/meshstack-cli/client/types/xurl" "github.com/meshcloud/meshstack-cli/internal/json" ) @@ -18,24 +19,25 @@ var ErrNoState = errors.New("no state") var ErrNoLock = errors.New("no lock") -// Requester is implemented by client.RawClient. -type Requester interface { - DoRequest(ctx context.Context, method, path string, opts ...http.RequestOption) ([]byte, error) -} - type Store struct { - BuildingBlock uuid.UUID + BuildingBlock string Workspace string - raw Requester + client http.AuthorizedClient + state *url.URL } -func NewStore(raw Requester, workspace string, buildingBlock uuid.UUID) Store { - return Store{BuildingBlock: buildingBlock, Workspace: workspace, raw: raw} +// NewStore must address the state as stateEndpointFormat in +// ../building-block-runner/internal/executor/tf/tfcmd.go does. +func NewStore(client http.AuthorizedClient, endpoint xurl.URL, workspace string, buildingBlock string) Store { + return Store{ + BuildingBlock: buildingBlock, Workspace: workspace, client: client, + state: endpoint.JoinPath("api", "terraform", "state", "workspace", workspace, "buildingBlock", buildingBlock), + } } func (s Store) Get(ctx context.Context) ([]byte, error) { - state, err := s.do(ctx, http.MethodGet, s.path()) + state, err := s.do(ctx, http.MethodGet, s.state) if httpErr, ok := errors.AsType[http.Error](err); ok && httpErr.IsNotFound() { return nil, ErrNoState } @@ -45,12 +47,12 @@ func (s Store) Get(ctx context.Context) ([]byte, error) { // Put and Delete send the ID of tofu's lock as tofu's http backend does, because meshStack refuses // a write without the ID of the lock it holds. func (s Store) Put(ctx context.Context, state []byte, lockId string) error { - _, err := s.do(ctx, http.MethodPost, s.path(), withLockId(lockId, jsonBody(state)...)...) + _, err := s.do(ctx, http.MethodPost, s.state, withLockId(lockId, jsonBody(state)...)...) return s.wrap("store", err) } func (s Store) Delete(ctx context.Context, lockId string) error { - _, err := s.do(ctx, http.MethodDelete, s.path(), withLockId(lockId)...) + _, err := s.do(ctx, http.MethodDelete, s.state, withLockId(lockId)...) return s.wrap("delete", err) } @@ -64,19 +66,19 @@ func withLockId(lockId string, opts ...http.RequestOption) []http.RequestOption // Lock and Unlock take tofu's lock info as tofu sends it. A Lock that meshStack refuses with 423 // is an [http.Error] that carries the lock info of the holder. func (s Store) Lock(ctx context.Context, info []byte) error { - _, err := s.do(ctx, http.MethodPost, s.lockPath(), jsonBody(info)...) + _, err := s.do(ctx, http.MethodPost, s.state.JoinPath("lock"), jsonBody(info)...) return s.wrap("lock", err) } // Unlock fails with a 423 of meshStack where meshStack holds a lock of another ID than the one in // info. func (s Store) Unlock(ctx context.Context, info []byte) error { - _, err := s.do(ctx, http.MethodDelete, s.lockPath(), jsonBody(info)...) + _, err := s.do(ctx, http.MethodDelete, s.state.JoinPath("lock"), jsonBody(info)...) return s.wrap("unlock", err) } func (s Store) ReadLock(ctx context.Context) (lock Lock, err error) { - read, err := s.do(ctx, http.MethodGet, s.lockPath()) + read, err := s.do(ctx, http.MethodGet, s.state.JoinPath("lock")) if httpErr, ok := errors.AsType[http.Error](err); ok && httpErr.IsNotFound() { return lock, ErrNoLock } else if err != nil { @@ -85,12 +87,12 @@ func (s Store) ReadLock(ctx context.Context) (lock Lock, err error) { return lock, json.Unmarshal(read, &lock) } -func (s Store) do(ctx context.Context, method, path string, opts ...http.RequestOption) ([]byte, error) { +func (s Store) do(ctx context.Context, method string, target *url.URL, opts ...http.RequestOption) ([]byte, error) { if method != http.MethodGet { // A 423 goes back to tofu at once, which names the holder of the lock and waits itself. opts = append(opts, http.Retryable(http.RetryOnBusy)) } - return s.raw.DoRequest(ctx, method, path, opts...) + return http.ReadAllBody(s.client.DoRequest(ctx, method, target, opts...)) } func (s Store) wrap(action string, err error) error { @@ -100,16 +102,6 @@ func (s Store) wrap(action string, err error) error { return fmt.Errorf("cannot %s the state of building block %s in workspace %s: %w", action, s.BuildingBlock, s.Workspace, err) } -// path must match EP_State in ../building-block-runner/tf-block-runner/tfrun/runapi.go, the address -// that the runner's backend uses. meshfed's TfHttpStateController serves it. -func (s Store) path() string { - return fmt.Sprintf("/api/terraform/state/workspace/%s/buildingBlock/%s", s.Workspace, s.BuildingBlock) -} - -func (s Store) lockPath() string { - return s.path() + "/lock" -} - // jsonBody sends no body for an empty one, as tofu's force-unlock sends it. func jsonBody(body []byte) []http.RequestOption { if len(body) == 0 {