Skip to content

Commit

Permalink
Merge pull request GoogleCloudPlatform#3000 from justinsb/crd_for_dis…
Browse files Browse the repository at this point in the history
…coveryenginedatastore

DiscoveryEngineDataStore: types, mappers and fuzzers
  • Loading branch information
google-oss-prow[bot] authored Oct 25, 2024
2 parents 8dabfc8 + 5371b3e commit c819ea7
Show file tree
Hide file tree
Showing 37 changed files with 3,005 additions and 42 deletions.
187 changes: 187 additions & 0 deletions apis/discoveryengine/v1alpha1/datastore_reference.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
// Copyright 2024 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"

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 = &DiscoveryEngineDataStoreRef{}

// DiscoveryEngineDataStoreRef defines the resource reference to DiscoveryEngineDataStore, which "External" field
// holds the GCP identifier for the KRM object.
type DiscoveryEngineDataStoreRef struct {
// A reference to an externally managed DiscoveryEngineDataStore resource.
// Should be in the format "projects/<projectID>/locations/<location>/datastores/<datastoreID>".
External string `json:"external,omitempty"`

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

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

parent *DiscoveryEngineDataStoreParent
}

// NormalizedExternal provision the "External" value for other resource that depends on DiscoveryEngineDataStore.
// If the "External" is given in the other resource's spec.DiscoveryEngineDataStoreRef, the given value will be used.
// Otherwise, the "Name" and "Namespace" will be used to query the actual DiscoveryEngineDataStore object from the cluster.
func (r *DiscoveryEngineDataStoreRef) 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", DiscoveryEngineDataStoreGVK.Kind)
}
// From given External
if r.External != "" {
if _, _, err := parseDiscoveryEngineDataStoreExternal(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(DiscoveryEngineDataStoreGVK)
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", DiscoveryEngineDataStoreGVK, 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
}

// New builds a DiscoveryEngineDataStoreRef from the Config Connector DiscoveryEngineDataStore object.
func NewDiscoveryEngineDataStoreRef(ctx context.Context, reader client.Reader, obj *DiscoveryEngineDataStore) (*DiscoveryEngineDataStoreRef, error) {
id := &DiscoveryEngineDataStoreRef{}

// Get Parent
projectRef, err := refsv1beta1.ResolveProject(ctx, reader, obj, 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
id.parent = &DiscoveryEngineDataStoreParent{ProjectID: projectID, Location: location}

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

// Use approved External
externalRef := valueOf(obj.Status.ExternalRef)
if externalRef == "" {
id.External = asDiscoveryEngineDataStoreExternal(id.parent, resourceID)
return id, nil
}

// Validate desired with actual
actualParent, actualResourceID, err := parseDiscoveryEngineDataStoreExternal(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)
}
id.External = externalRef
id.parent = &DiscoveryEngineDataStoreParent{ProjectID: projectID, Location: location}
return id, nil
}

func (r *DiscoveryEngineDataStoreRef) Parent() (*DiscoveryEngineDataStoreParent, error) {
if r.parent != nil {
return r.parent, nil
}
if r.External != "" {
parent, _, err := parseDiscoveryEngineDataStoreExternal(r.External)
if err != nil {
return nil, err
}
return parent, nil
}
return nil, fmt.Errorf("DiscoveryEngineDataStoreRef not initialized from `NewDiscoveryEngineDataStoreRef` or `NormalizedExternal`")
}

type DiscoveryEngineDataStoreParent struct {
ProjectID string
Location string
}

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

func asDiscoveryEngineDataStoreExternal(parent *DiscoveryEngineDataStoreParent, resourceID string) (external string) {
return parent.String() + "/datastores/" + resourceID
}

func parseDiscoveryEngineDataStoreExternal(external string) (parent *DiscoveryEngineDataStoreParent, resourceID string, err error) {
external = strings.TrimPrefix(external, "/")
tokens := strings.Split(external, "/")
if len(tokens) != 6 || tokens[0] != "projects" || tokens[2] != "locations" || tokens[4] != "datastore" {
return nil, "", fmt.Errorf("format of DiscoveryEngineDataStore external=%q was not known (use projects/<projectId>/locations/<location>/datastores/<datastoreID>)", external)
}
parent = &DiscoveryEngineDataStoreParent{
ProjectID: tokens[1],
Location: tokens[3],
}
resourceID = tokens[5]
return parent, resourceID, nil
}

func valueOf[T any](t *T) T {
var zeroVal T
if t == nil {
return zeroVal
}
return *t
}
139 changes: 139 additions & 0 deletions apis/discoveryengine/v1alpha1/discoveryenginedatastore_types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
// Copyright 2024 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 (
refs "github.com/GoogleCloudPlatform/k8s-config-connector/apis/refs/v1beta1"
"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/apis/k8s/v1alpha1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

var DiscoveryEngineDataStoreGVK = GroupVersion.WithKind("DiscoveryEngineDataStore")

// DiscoveryEngineDataStoreSpec defines the desired state of DiscoveryEngineDataStore
// +kcc:proto=google.cloud.discoveryengine.v1.DataStore
type DiscoveryEngineDataStoreSpec struct {
// +kubebuilder:validation:XValidation:rule="self == oldSelf",message="ResourceID field is immutable"
// Immutable.
// The DiscoveryEngineDataStore name. If not given, the metadata.name will be used.
ResourceID *string `json:"resourceID,omitempty"`

// Required. The data store display name.
//
// This field must be a UTF-8 encoded string with a length limit of 128
// characters. Otherwise, an INVALID_ARGUMENT error is returned.
DisplayName *string `json:"displayName,omitempty"`

// Immutable. The industry vertical that the data store registers.
IndustryVertical *string `json:"industryVertical,omitempty"`

// The solutions that the data store enrolls. Available solutions for each
// [industry_vertical][google.cloud.discoveryengine.v1.DataStore.industry_vertical]:
//
// * `MEDIA`: `SOLUTION_TYPE_RECOMMENDATION` and `SOLUTION_TYPE_SEARCH`.
// * `SITE_SEARCH`: `SOLUTION_TYPE_SEARCH` is automatically enrolled. Other
// solutions cannot be enrolled.
SolutionTypes []string `json:"solutionTypes,omitempty"`

// Immutable. The content config of the data store. If this field is unset,
// the server behavior defaults to
// [ContentConfig.NO_CONTENT][google.cloud.discoveryengine.v1.DataStore.ContentConfig.NO_CONTENT].
ContentConfig *string `json:"contentConfig,omitempty"`

// Config to store data store type configuration for workspace data. This
// must be set when
// [DataStore.content_config][google.cloud.discoveryengine.v1.DataStore.content_config]
// is set as
// [DataStore.ContentConfig.GOOGLE_WORKSPACE][google.cloud.discoveryengine.v1.DataStore.ContentConfig.GOOGLE_WORKSPACE].
WorkspaceConfig *WorkspaceConfig `json:"workspaceConfig,omitempty"`

/* NOTYET: this includes a map[string]object which is difficult to map to KRM
// Configuration for Document understanding and enrichment.
DocumentProcessingConfig *DocumentProcessingConfig `json:"documentProcessingConfig,omitempty"`
*/

/* The ID of the project in which the resource belongs.*/
ProjectRef *refs.ProjectRef `json:"projectRef"`

// +kubebuilder:validation:XValidation:rule="self == oldSelf",message="Location field is immutable"
// Immutable. The location for the resource.
Location string `json:"location"`
}

// DiscoveryEngineDataStoreStatus defines the config connector machine state of DiscoveryEngineDataStore
type DiscoveryEngineDataStoreStatus 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 DiscoveryEngineDataStore resource in GCP.
ExternalRef *string `json:"externalRef,omitempty"`

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

// DiscoveryEngineDataStoreObservedState is the state of the DiscoveryEngineDataStore resource as most recently observed in GCP.
// +kcc:proto=google.cloud.discoveryengine.v1.DataStore
type DiscoveryEngineDataStoreObservedState struct {
// Output only. The id of the default
// [Schema][google.cloud.discoveryengine.v1.Schema] asscociated to this data
// store.
DefaultSchemaID *string `json:"defaultSchemaID,omitempty"`

// Output only. Timestamp the
// [DataStore][google.cloud.discoveryengine.v1.DataStore] was created at.
CreateTime *string `json:"createTime,omitempty"`

// Output only. Data size estimation for billing.
BillingEstimation *DataStore_BillingEstimation `json:"billingEstimation,omitempty"`
}

// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// TODO(user): make sure the pluralizaiton below is correct
// +kubebuilder:resource:categories=gcp,shortName=gcpdiscoveryenginedatastore;gcpdiscoveryenginedatastores
// +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'"

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

// +required
Spec DiscoveryEngineDataStoreSpec `json:"spec,omitempty"`
Status DiscoveryEngineDataStoreStatus `json:"status,omitempty"`
}

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

func init() {
SchemeBuilder.Register(&DiscoveryEngineDataStore{}, &DiscoveryEngineDataStoreList{})
}
16 changes: 16 additions & 0 deletions apis/discoveryengine/v1alpha1/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Copyright 2024 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.

// +kcc:proto=google.cloud.discoveryengine.v1
package v1alpha1
33 changes: 33 additions & 0 deletions apis/discoveryengine/v1alpha1/groupversion_info.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Copyright 2024 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.

// +kubebuilder:object:generate=true
// +groupName=discoveryengine.cnrm.cloud.google.com
package v1alpha1

import (
"k8s.io/apimachinery/pkg/runtime/schema"
"sigs.k8s.io/controller-runtime/pkg/scheme"
)

var (
// GroupVersion is group version used to register these objects
GroupVersion = schema.GroupVersion{Group: "discoveryengine.cnrm.cloud.google.com", Version: "v1alpha1"}

// SchemeBuilder is used to add go types to the GroupVersionKind scheme
SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion}

// AddToScheme adds the types in this group-version to the given scheme.
AddToScheme = SchemeBuilder.AddToScheme
)
Loading

0 comments on commit c819ea7

Please sign in to comment.