Skip to content

feat: add types, mappers and fuzzer for SpeechCustomClass #4277

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 117 additions & 0 deletions apis/speech/v1alpha1/customclass_identity.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package v1alpha1

import (
"context"
"fmt"
"strings"

"github.com/GoogleCloudPlatform/k8s-config-connector/apis/common"
refsv1beta1 "github.com/GoogleCloudPlatform/k8s-config-connector/apis/refs/v1beta1"
"sigs.k8s.io/controller-runtime/pkg/client"
)

// CustomClassIdentity defines the resource reference to SpeechCustomClass, which "External" field
// holds the GCP identifier for the KRM object.
type CustomClassIdentity struct {
parent *CustomClassParent
id string
}

func (i *CustomClassIdentity) String() string {
return i.parent.String() + "/customClasses/" + i.id
}

func (i *CustomClassIdentity) ID() string {
return i.id
}

func (i *CustomClassIdentity) Parent() *CustomClassParent {
return i.parent
}

type CustomClassParent struct {
ProjectID string
Location string
}

func (p *CustomClassParent) String() string {
return "projects/" + p.ProjectID + "/locations/" + p.Location
}

// New builds a CustomClassIdentity from the Config Connector CustomClass object.
func NewCustomClassIdentity(ctx context.Context, reader client.Reader, obj *SpeechCustomClass) (*CustomClassIdentity, error) {

// Get Parent
projectRef, err := refsv1beta1.ResolveProject(ctx, reader, obj.GetNamespace(), obj.Spec.ProjectRef)
if err != nil {
return nil, err
}
projectID := projectRef.ProjectID
if projectID == "" {
return nil, fmt.Errorf("cannot resolve project")
}
location := obj.Spec.Location

// Get desired ID
resourceID := common.ValueOf(obj.Spec.ResourceID)
if resourceID == "" {
resourceID = obj.GetName()
}
if resourceID == "" {
return nil, fmt.Errorf("cannot resolve resource ID")
}

// Use approved External
externalRef := common.ValueOf(obj.Status.ExternalRef)
if externalRef != "" {
// Validate desired with actual
actualParent, actualResourceID, err := ParseCustomClassExternal(externalRef)
if err != nil {
return nil, err
}
if actualParent.ProjectID != projectID {
return nil, fmt.Errorf("spec.projectRef changed, expect %s, got %s", actualParent.ProjectID, projectID)
}
if actualParent.Location != location {
return nil, fmt.Errorf("spec.location changed, expect %s, got %s", actualParent.Location, location)
}
if actualResourceID != resourceID {
return nil, fmt.Errorf("cannot reset `metadata.name` or `spec.resourceID` to %s, since it has already assigned to %s",
resourceID, actualResourceID)
}
}
return &CustomClassIdentity{
parent: &CustomClassParent{
ProjectID: projectID,
Location: location,
},
id: resourceID,
}, nil
}

func ParseCustomClassExternal(external string) (parent *CustomClassParent, resourceID string, err error) {
tokens := strings.Split(external, "/")
if len(tokens) != 6 || tokens[0] != "projects" || tokens[2] != "locations" || tokens[4] != "customClasses" {
return nil, "", fmt.Errorf("format of SpeechCustomClass external=%q was not known (use projects/{{projectID}}/locations/{{location}}/customClasses/{{customclassID}})", external)
}
parent = &CustomClassParent{
ProjectID: tokens[1],
Location: tokens[3],
}
resourceID = tokens[5]
return parent, resourceID, nil
}
83 changes: 83 additions & 0 deletions apis/speech/v1alpha1/customclass_reference.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package v1alpha1

import (
"context"
"fmt"

refsv1beta1 "github.com/GoogleCloudPlatform/k8s-config-connector/apis/refs/v1beta1"
"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/k8s"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
)

var _ refsv1beta1.ExternalNormalizer = &CustomClassRef{}

// CustomClassRef defines the resource reference to SpeechCustomClass, which "External" field
// holds the GCP identifier for the KRM object.
type CustomClassRef struct {
// A reference to an externally managed SpeechCustomClass resource.
// Should be in the format "projects/{{projectID}}/locations/{{location}}/customClasses/{{customclassID}}".
External string `json:"external,omitempty"`

// The name of a SpeechCustomClass resource.
Name string `json:"name,omitempty"`

// The namespace of a SpeechCustomClass resource.
Namespace string `json:"namespace,omitempty"`
}

// NormalizedExternal provision the "External" value for other resource that depends on SpeechCustomClass.
// If the "External" is given in the other resource's spec.SpeechCustomClassRef, the given value will be used.
// Otherwise, the "Name" and "Namespace" will be used to query the actual SpeechCustomClass object from the cluster.
func (r *CustomClassRef) NormalizedExternal(ctx context.Context, reader client.Reader, otherNamespace string) (string, error) {
if r.External != "" && r.Name != "" {
return "", fmt.Errorf("cannot specify both name and external on %s reference", SpeechCustomClassGVK.Kind)
}
// From given External
if r.External != "" {
if _, _, err := ParseCustomClassExternal(r.External); err != nil {
return "", err
}
return r.External, nil
}

// From the Config Connector object
if r.Namespace == "" {
r.Namespace = otherNamespace
}
key := types.NamespacedName{Name: r.Name, Namespace: r.Namespace}
u := &unstructured.Unstructured{}
u.SetGroupVersionKind(SpeechCustomClassGVK)
if err := reader.Get(ctx, key, u); err != nil {
if apierrors.IsNotFound(err) {
return "", k8s.NewReferenceNotFoundError(u.GroupVersionKind(), key)
}
return "", fmt.Errorf("reading referenced %s %s: %w", SpeechCustomClassGVK, key, err)
}
// Get external from status.externalRef. This is the most trustworthy place.
actualExternalRef, _, err := unstructured.NestedString(u.Object, "status", "externalRef")
if err != nil {
return "", fmt.Errorf("reading status.externalRef: %w", err)
}
if actualExternalRef == "" {
return "", k8s.NewReferenceNotReadyError(u.GroupVersionKind(), key)
}
r.External = actualExternalRef
return r.External, nil
}
155 changes: 155 additions & 0 deletions apis/speech/v1alpha1/customclass_types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package v1alpha1

import (
"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/apis/k8s/v1alpha1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

var SpeechCustomClassGVK = GroupVersion.WithKind("SpeechCustomClass")

// SpeechCustomClassSpec defines the desired state of SpeechCustomClass
// +kcc:proto=google.cloud.speech.v2.CustomClass
type SpeechCustomClassSpec struct {
// The SpeechCustomClass name. If not given, the metadata.name will be used.
ResourceID *string `json:"resourceID,omitempty"`

Parent `json:",inline"`

// Optional. User-settable, human-readable name for the CustomClass. Must be
// 63 characters or less.
// +kcc:proto:field=google.cloud.speech.v2.CustomClass.display_name
DisplayName *string `json:"displayName,omitempty"`

// A collection of class items.
// +kcc:proto:field=google.cloud.speech.v2.CustomClass.items
Items []CustomClass_ClassItem `json:"items,omitempty"`

// Optional. Allows users to store small amounts of arbitrary data.
// Both the key and the value must be 63 characters or less each.
// At most 100 annotations.
// +kcc:proto:field=google.cloud.speech.v2.CustomClass.annotations
Annotations map[string]string `json:"annotations,omitempty"`
}

// SpeechCustomClassStatus defines the config connector machine state of SpeechCustomClass
type SpeechCustomClassStatus struct {
/* Conditions represent the latest available observations of the
object's current state. */
Conditions []v1alpha1.Condition `json:"conditions,omitempty"`

// ObservedGeneration is the generation of the resource that was most recently observed by the Config Connector controller. If this is equal to metadata.generation, then that means that the current reported status reflects the most recent desired state of the resource.
ObservedGeneration *int64 `json:"observedGeneration,omitempty"`

// A unique specifier for the SpeechCustomClass resource in GCP.
ExternalRef *string `json:"externalRef,omitempty"`

// ObservedState is the state of the resource as most recently observed in GCP.
ObservedState *SpeechCustomClassObservedState `json:"observedState,omitempty"`
}

// SpeechCustomClassObservedState is the state of the SpeechCustomClass resource as most recently observed in GCP.
// +kcc:proto=google.cloud.speech.v2.CustomClass
type SpeechCustomClassObservedState struct {
// Output only. Identifier. The resource name of the CustomClass.
// Format:
// `projects/{project}/locations/{location}/customClasses/{custom_class}`.
// +kcc:proto:field=google.cloud.speech.v2.CustomClass.name
// NOTYET: this field serves the same purpose as externalRef
// Name *string `json:"name,omitempty"`

// Output only. System-assigned unique identifier for the CustomClass.
// +kcc:proto:field=google.cloud.speech.v2.CustomClass.uid
UID *string `json:"uid,omitempty"`

// Output only. The CustomClass lifecycle state.
// +kcc:proto:field=google.cloud.speech.v2.CustomClass.state
State *string `json:"state,omitempty"`

// Output only. Creation time.
// +kcc:proto:field=google.cloud.speech.v2.CustomClass.create_time
CreateTime *string `json:"createTime,omitempty"`

// Output only. The most recent time this resource was modified.
// +kcc:proto:field=google.cloud.speech.v2.CustomClass.update_time
UpdateTime *string `json:"updateTime,omitempty"`

// Output only. The time at which this resource was requested for deletion.
// +kcc:proto:field=google.cloud.speech.v2.CustomClass.delete_time
DeleteTime *string `json:"deleteTime,omitempty"`

// Output only. The time at which this resource will be purged.
// +kcc:proto:field=google.cloud.speech.v2.CustomClass.expire_time
ExpireTime *string `json:"expireTime,omitempty"`

// Output only. This checksum is computed by the server based on the value of
// other fields. This may be sent on update, undelete, and delete requests to
// ensure the client has an up-to-date value before proceeding.
// +kcc:proto:field=google.cloud.speech.v2.CustomClass.etag
Etag *string `json:"etag,omitempty"`

// Output only. Whether or not this CustomClass is in the process of being
// updated.
// +kcc:proto:field=google.cloud.speech.v2.CustomClass.reconciling
Reconciling *bool `json:"reconciling,omitempty"`

// Output only. The [KMS key
// name](https://cloud.google.com/kms/docs/resource-hierarchy#keys) with which
// the CustomClass is encrypted. The expected format is
// `projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}`.
// +kcc:proto:field=google.cloud.speech.v2.CustomClass.kms_key_name
KMSKeyName *string `json:"kmsKeyName,omitempty"`

// Output only. The [KMS key version
// name](https://cloud.google.com/kms/docs/resource-hierarchy#key_versions)
// with which the CustomClass is encrypted. The expected format is
// `projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}`.
// +kcc:proto:field=google.cloud.speech.v2.CustomClass.kms_key_version_name
KMSKeyVersionName *string `json:"kmsKeyVersionName,omitempty"`
}

// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +kubebuilder:resource:categories=gcp,shortName=gcpspeechcustomclass;gcpspeechcustomclasses
// +kubebuilder:subresource:status
// +kubebuilder:metadata:labels="cnrm.cloud.google.com/managed-by-kcc=true";"cnrm.cloud.google.com/system=true"
// +kubebuilder:printcolumn:name="Age",JSONPath=".metadata.creationTimestamp",type="date"
// +kubebuilder:printcolumn:name="Ready",JSONPath=".status.conditions[?(@.type=='Ready')].status",type="string",description="When 'True', the most recent reconcile of the resource succeeded"
// +kubebuilder:printcolumn:name="Status",JSONPath=".status.conditions[?(@.type=='Ready')].reason",type="string",description="The reason for the value in 'Ready'"
// +kubebuilder:printcolumn:name="Status Age",JSONPath=".status.conditions[?(@.type=='Ready')].lastTransitionTime",type="date",description="The last transition time for the value in 'Status'"

// SpeechCustomClass is the Schema for the SpeechCustomClass API
// +k8s:openapi-gen=true
type SpeechCustomClass struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`

// +required
Spec SpeechCustomClassSpec `json:"spec,omitempty"`
Status SpeechCustomClassStatus `json:"status,omitempty"`
}

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// SpeechCustomClassList contains a list of SpeechCustomClass
type SpeechCustomClassList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []SpeechCustomClass `json:"items"`
}

func init() {
SchemeBuilder.Register(&SpeechCustomClass{}, &SpeechCustomClassList{})
}
39 changes: 39 additions & 0 deletions apis/speech/v1alpha1/generate.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#!/bin/bash
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


set -o errexit
set -o nounset
set -o pipefail

REPO_ROOT="$(git rev-parse --show-toplevel)"
cd ${REPO_ROOT}/dev/tools/controllerbuilder

go run . generate-types \
--service google.cloud.speech.v2 \
--api-version speech.cnrm.cloud.google.com/v1alpha1 \
--resource SpeechRecognizer:Recognizer \
--resource SpeechCustomClass:CustomClass

go run . generate-mapper \
--service google.cloud.speech.v2 \
--api-version speech.cnrm.cloud.google.com/v1alpha1


cd ${REPO_ROOT}
dev/tasks/generate-crds

go run -mod=readonly golang.org/x/tools/cmd/goimports@latest -w pkg/controller/direct/speech/

Loading
Loading