From 974bdc45a6810e68fc2a37ca428fa44e3984b311 Mon Sep 17 00:00:00 2001 From: Nic Cope Date: Tue, 8 Oct 2024 17:15:25 -0700 Subject: [PATCH 1/3] Add a resource.update convenience function This function can be used to add or update a resource. For example, to add a desired composed bucket (assuming the "bucket" resource doesn't yet exist): ```python resource.update(rsp.desired.resources["bucket"], bucket) ``` Or to update the desired XR: ```python resource.update(rsp.desired.composite.resource, partial_xr) ``` The source resource can be a dictionary, a protobuf struct, or a Pydantic model. Signed-off-by: Nic Cope --- crossplane/function/resource.py | 29 + pyproject.toml | 8 +- tests/test_resource.py | 80 ++ .../io/k8s/apimachinery/pkg/apis/__init__.py | 3 + .../apimachinery/pkg/apis/meta/__init__.py | 3 + .../io/k8s/apimachinery/pkg/apis/meta/v1.py | 301 +++++++ .../models/io/upbound/aws/s3/__init__.py | 3 + .../models/io/upbound/aws/s3/v1beta2.py | 800 ++++++++++++++++++ 8 files changed, 1226 insertions(+), 1 deletion(-) create mode 100644 tests/testdata/models/io/k8s/apimachinery/pkg/apis/__init__.py create mode 100644 tests/testdata/models/io/k8s/apimachinery/pkg/apis/meta/__init__.py create mode 100644 tests/testdata/models/io/k8s/apimachinery/pkg/apis/meta/v1.py create mode 100644 tests/testdata/models/io/upbound/aws/s3/__init__.py create mode 100644 tests/testdata/models/io/upbound/aws/s3/v1beta2.py diff --git a/crossplane/function/resource.py b/crossplane/function/resource.py index 11626f1..51483e3 100644 --- a/crossplane/function/resource.py +++ b/crossplane/function/resource.py @@ -17,12 +17,41 @@ import dataclasses import datetime +import pydantic from google.protobuf import struct_pb2 as structpb +import crossplane.function.proto.v1.run_function_pb2 as fnv1 + # TODO(negz): Do we really need dict_to_struct and struct_to_dict? They don't do # much, but are perhaps useful for discoverability/"documentation" purposes. +def update(r: fnv1.Resource, source: dict | structpb.Struct | pydantic.BaseModel): + """Update a composite or composed resource. + + Use update to add or update the supplied resource. If the resource doesn't + exist, it'll be added. If the resource does exist, it'll be updated. The + update method semantics are the same as a dictionary's update method. Fields + that don't exist will be added. Fields that exist will be overwritten. + + The source can be a dictionary, a protobuf Struct, or a Pydantic model. + """ + # If the resource has a model_dump attribute it's a Pydantic BaseModel. + if hasattr(source, "model_dump"): + r.resource.update(source.model_dump(exclude_defaults=True, warnings=False)) + return + + # If the resource has a get_or_create_struct attribute it's a Struct. + if hasattr(source, "get_or_create_struct"): + # TODO(negz): Use struct_to_dict and update to match other semantics? + r.resource.MergeFrom(source) + return + + # If it has neither, it must be a dictionary. + r.resource.update(source) + return + + def dict_to_struct(d: dict) -> structpb.Struct: """Create a Struct well-known type from the supplied dict. diff --git a/pyproject.toml b/pyproject.toml index b2f96dc..bb5a19e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -16,7 +16,13 @@ classifiers = [ "Programming Language :: Python :: 3.11", ] -dependencies = ["grpcio==1.*", "grpcio-reflection==1.*", "protobuf==5.27.2", "structlog==24.*"] +dependencies = [ + "grpcio==1.*", + "grpcio-reflection==1.*", + "protobuf==5.27.2", + "pydantic==2.*", + "structlog==24.*", +] dynamic = ["version"] diff --git a/tests/test_resource.py b/tests/test_resource.py index a7c4796..47fb18b 100644 --- a/tests/test_resource.py +++ b/tests/test_resource.py @@ -16,15 +16,95 @@ import datetime import unittest +import pydantic +from google.protobuf import json_format from google.protobuf import struct_pb2 as structpb +import crossplane.function.proto.v1.run_function_pb2 as fnv1 from crossplane.function import logging, resource +from .testdata.models.io.upbound.aws.s3 import v1beta2 + class TestResource(unittest.TestCase): def setUp(self) -> None: logging.configure(level=logging.Level.DISABLED) + def test_add(self) -> None: + @dataclasses.dataclass + class TestCase: + reason: str + r: fnv1.Resource + source: dict | structpb.Struct | pydantic.BaseModel + want: fnv1.Resource + + cases = [ + TestCase( + reason="Updating from a dict should work.", + r=fnv1.Resource(), + source={"apiVersion": "example.org", "kind": "Resource"}, + want=fnv1.Resource( + resource=resource.dict_to_struct( + {"apiVersion": "example.org", "kind": "Resource"} + ), + ), + ), + TestCase( + reason="Updating an existing resource from a dict should work.", + r=fnv1.Resource( + resource=resource.dict_to_struct( + {"apiVersion": "example.org", "kind": "Resource"} + ), + ), + source={ + "metadata": {"name": "cool"}, + }, + want=fnv1.Resource( + resource=resource.dict_to_struct( + { + "apiVersion": "example.org", + "kind": "Resource", + "metadata": {"name": "cool"}, + } + ), + ), + ), + TestCase( + reason="Updating from a struct should work.", + r=fnv1.Resource(), + source=resource.dict_to_struct( + {"apiVersion": "example.org", "kind": "Resource"} + ), + want=fnv1.Resource( + resource=resource.dict_to_struct( + {"apiVersion": "example.org", "kind": "Resource"} + ), + ), + ), + TestCase( + reason="Updating from a Pydantic model should work.", + r=fnv1.Resource(), + source=v1beta2.Bucket( + spec=v1beta2.Spec( + forProvider=v1beta2.ForProvider(region="us-west-2"), + ), + ), + want=fnv1.Resource( + resource=resource.dict_to_struct( + {"spec": {"forProvider": {"region": "us-west-2"}}} + ), + ), + ), + ] + + for case in cases: + resource.update(case.r, case.source) + self.assertEqual( + json_format.MessageToDict(case.want), + json_format.MessageToDict(case.r), + "-want, +got", + ) + def test_get_condition(self) -> None: @dataclasses.dataclass class TestCase: diff --git a/tests/testdata/models/io/k8s/apimachinery/pkg/apis/__init__.py b/tests/testdata/models/io/k8s/apimachinery/pkg/apis/__init__.py new file mode 100644 index 0000000..92eaf2e --- /dev/null +++ b/tests/testdata/models/io/k8s/apimachinery/pkg/apis/__init__.py @@ -0,0 +1,3 @@ +# generated by datamodel-codegen: +# filename: +# timestamp: 2024-10-04T21:01:52+00:00 diff --git a/tests/testdata/models/io/k8s/apimachinery/pkg/apis/meta/__init__.py b/tests/testdata/models/io/k8s/apimachinery/pkg/apis/meta/__init__.py new file mode 100644 index 0000000..92eaf2e --- /dev/null +++ b/tests/testdata/models/io/k8s/apimachinery/pkg/apis/meta/__init__.py @@ -0,0 +1,3 @@ +# generated by datamodel-codegen: +# filename: +# timestamp: 2024-10-04T21:01:52+00:00 diff --git a/tests/testdata/models/io/k8s/apimachinery/pkg/apis/meta/v1.py b/tests/testdata/models/io/k8s/apimachinery/pkg/apis/meta/v1.py new file mode 100644 index 0000000..6362ede --- /dev/null +++ b/tests/testdata/models/io/k8s/apimachinery/pkg/apis/meta/v1.py @@ -0,0 +1,301 @@ +# generated by datamodel-codegen: +# filename: +# timestamp: 2024-10-04T21:01:52+00:00 + +from __future__ import annotations + +from typing import Dict, List, Optional + +from pydantic import AwareDatetime, BaseModel, Field, RootModel + + +class FieldsV1(BaseModel): + pass + + +class ListMeta(BaseModel): + continue_: Optional[str] = Field(None, alias='continue') + """ + continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message. + """ + remainingItemCount: Optional[int] = None + """ + remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact. + """ + resourceVersion: Optional[str] = None + """ + String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency + """ + selfLink: Optional[str] = None + """ + Deprecated: selfLink is a legacy read-only field that is no longer populated by the system. + """ + + +class OwnerReference(BaseModel): + apiVersion: str + """ + API version of the referent. + """ + blockOwnerDeletion: Optional[bool] = None + """ + If true, AND if the owner has the "foregroundDeletion" finalizer, then the owner cannot be deleted from the key-value store until this reference is removed. See https://kubernetes.io/docs/concepts/architecture/garbage-collection/#foreground-deletion for how the garbage collector interacts with this field and enforces the foreground deletion. Defaults to false. To set this field, a user needs "delete" permission of the owner, otherwise 422 (Unprocessable Entity) will be returned. + """ + controller: Optional[bool] = None + """ + If true, this reference points to the managing controller. + """ + kind: str + """ + Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + """ + name: str + """ + Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names + """ + uid: str + """ + UID of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids + """ + + +class Patch(BaseModel): + pass + + +class Preconditions(BaseModel): + resourceVersion: Optional[str] = None + """ + Specifies the target ResourceVersion + """ + uid: Optional[str] = None + """ + Specifies the target UID. + """ + + +class StatusCause(BaseModel): + field: Optional[str] = None + """ + The field of the resource that has caused this error, as named by its JSON serialization. May include dot and postfix notation for nested attributes. Arrays are zero-indexed. Fields may appear more than once in an array of causes due to fields having multiple errors. Optional. + + Examples: + "name" - the field "name" on the current resource + "items[0].name" - the field "name" on the first array entry in "items" + """ + message: Optional[str] = None + """ + A human-readable description of the cause of the error. This field may be presented as-is to a reader. + """ + reason: Optional[str] = None + """ + A machine-readable description of the cause of the error. If this value is empty there is no information available. + """ + + +class StatusDetails(BaseModel): + causes: Optional[List[StatusCause]] = None + """ + The Causes array includes more details associated with the StatusReason failure. Not all StatusReasons may provide detailed causes. + """ + group: Optional[str] = None + """ + The group attribute of the resource associated with the status StatusReason. + """ + kind: Optional[str] = None + """ + The kind attribute of the resource associated with the status StatusReason. On some operations may differ from the requested resource Kind. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + """ + name: Optional[str] = None + """ + The name attribute of the resource associated with the status StatusReason (when there is a single name which can be described). + """ + retryAfterSeconds: Optional[int] = None + """ + If specified, the time in seconds before the operation should be retried. Some errors may indicate the client must take an alternate action - for those errors this field may indicate how long to wait before taking the alternate action. + """ + uid: Optional[str] = None + """ + UID of the resource. (when there is a single resource which can be described). More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids + """ + + +class Time(RootModel[AwareDatetime]): + root: AwareDatetime + """ + Time is a wrapper around time.Time which supports correct marshaling to YAML and JSON. Wrappers are provided for many of the factory methods that the time package offers. + """ + + +class DeleteOptions(BaseModel): + apiVersion: Optional[str] = None + """ + APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + """ + dryRun: Optional[List[str]] = None + """ + When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed + """ + gracePeriodSeconds: Optional[int] = None + """ + The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. + """ + kind: Optional[str] = None + """ + Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + """ + orphanDependents: Optional[bool] = None + """ + Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. + """ + preconditions: Optional[Preconditions] = None + """ + Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. + """ + propagationPolicy: Optional[str] = None + """ + Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. + """ + + +class ManagedFieldsEntry(BaseModel): + apiVersion: Optional[str] = None + """ + APIVersion defines the version of this resource that this field set applies to. The format is "group/version" just like the top-level APIVersion field. It is necessary to track the version of a field set because it cannot be automatically converted. + """ + fieldsType: Optional[str] = None + """ + FieldsType is the discriminator for the different fields format and version. There is currently only one possible value: "FieldsV1" + """ + fieldsV1: Optional[FieldsV1] = None + """ + FieldsV1 holds the first JSON version format as described in the "FieldsV1" type. + """ + manager: Optional[str] = None + """ + Manager is an identifier of the workflow managing these fields. + """ + operation: Optional[str] = None + """ + Operation is the type of operation which lead to this ManagedFieldsEntry being created. The only valid values for this field are 'Apply' and 'Update'. + """ + subresource: Optional[str] = None + """ + Subresource is the name of the subresource used to update that object, or empty string if the object was updated through the main resource. The value of this field is used to distinguish between managers, even if they share the same name. For example, a status update will be distinct from a regular update using the same manager name. Note that the APIVersion field is not related to the Subresource field and it always corresponds to the version of the main resource. + """ + time: Optional[Time] = None + """ + Time is the timestamp of when the ManagedFields entry was added. The timestamp will also be updated if a field is added, the manager changes any of the owned fields value or removes a field. The timestamp does not update when a field is removed from the entry because another manager took it over. + """ + + +class ObjectMeta(BaseModel): + annotations: Optional[Dict[str, str]] = None + """ + Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations + """ + creationTimestamp: Optional[Time] = None + """ + CreationTimestamp is a timestamp representing the server time when this object was created. It is not guaranteed to be set in happens-before order across separate operations. Clients may not set this value. It is represented in RFC3339 form and is in UTC. + + Populated by the system. Read-only. Null for lists. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + """ + deletionGracePeriodSeconds: Optional[int] = None + """ + Number of seconds allowed for this object to gracefully terminate before it will be removed from the system. Only set when deletionTimestamp is also set. May only be shortened. Read-only. + """ + deletionTimestamp: Optional[Time] = None + """ + DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This field is set by the server when a graceful deletion is requested by the user, and is not directly settable by a client. The resource is expected to be deleted (no longer visible from resource lists, and not reachable by name) after the time in this field, once the finalizers list is empty. As long as the finalizers list contains items, deletion is blocked. Once the deletionTimestamp is set, this value may not be unset or be set further into the future, although it may be shortened or the resource may be deleted prior to this time. For example, a user may request that a pod is deleted in 30 seconds. The Kubelet will react by sending a graceful termination signal to the containers in the pod. After that 30 seconds, the Kubelet will send a hard termination signal (SIGKILL) to the container and after cleanup, remove the pod from the API. In the presence of network partitions, this object may still exist after this timestamp, until an administrator or automated process can determine the resource is fully terminated. If not set, graceful deletion of the object has not been requested. + + Populated by the system when a graceful deletion is requested. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + """ + finalizers: Optional[List[str]] = None + """ + Must be empty before the object is deleted from the registry. Each entry is an identifier for the responsible component that will remove the entry from the list. If the deletionTimestamp of the object is non-nil, entries in this list can only be removed. Finalizers may be processed and removed in any order. Order is NOT enforced because it introduces significant risk of stuck finalizers. finalizers is a shared field, any actor with permission can reorder it. If the finalizer list is processed in order, then this can lead to a situation in which the component responsible for the first finalizer in the list is waiting for a signal (field value, external system, or other) produced by a component responsible for a finalizer later in the list, resulting in a deadlock. Without enforced ordering finalizers are free to order amongst themselves and are not vulnerable to ordering changes in the list. + """ + generateName: Optional[str] = None + """ + GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the Name field has not been provided. If this field is used, the name returned to the client will be different than the name passed. This value will also be combined with a unique suffix. The provided value has the same validation rules as the Name field, and may be truncated by the length of the suffix required to make the value unique on the server. + + If this field is specified and the generated name exists, the server will return a 409. + + Applied only if Name is not specified. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency + """ + generation: Optional[int] = None + """ + A sequence number representing a specific generation of the desired state. Populated by the system. Read-only. + """ + labels: Optional[Dict[str, str]] = None + """ + Map of string keys and values that can be used to organize and categorize (scope and select) objects. May match selectors of replication controllers and services. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels + """ + managedFields: Optional[List[ManagedFieldsEntry]] = None + """ + ManagedFields maps workflow-id and version to the set of fields that are managed by that workflow. This is mostly for internal housekeeping, and users typically shouldn't need to set or understand this field. A workflow can be the user's name, a controller's name, or the name of a specific apply path like "ci-cd". The set of fields is always in the version that the workflow used when modifying the object. + """ + name: Optional[str] = None + """ + Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names + """ + namespace: Optional[str] = None + """ + Namespace defines the space within which each name must be unique. An empty namespace is equivalent to the "default" namespace, but "default" is the canonical representation. Not all objects are required to be scoped to a namespace - the value of this field for those objects will be empty. + + Must be a DNS_LABEL. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces + """ + ownerReferences: Optional[List[OwnerReference]] = None + """ + List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller. + """ + resourceVersion: Optional[str] = None + """ + An opaque value that represents the internal version of this object that can be used by clients to determine when objects have changed. May be used for optimistic concurrency, change detection, and the watch operation on a resource or set of resources. Clients must treat these values as opaque and passed unmodified back to the server. They may only be valid for a particular resource or set of resources. + + Populated by the system. Read-only. Value must be treated as opaque by clients and . More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency + """ + selfLink: Optional[str] = None + """ + Deprecated: selfLink is a legacy read-only field that is no longer populated by the system. + """ + uid: Optional[str] = None + """ + UID is the unique in time and space value for this object. It is typically generated by the server on successful creation of a resource and is not allowed to change on PUT operations. + + Populated by the system. Read-only. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids + """ + + +class Status(BaseModel): + apiVersion: Optional[str] = None + """ + APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + """ + code: Optional[int] = None + """ + Suggested HTTP return code for this status, 0 if not set. + """ + details: Optional[StatusDetails] = None + """ + Extended data associated with the reason. Each reason may define its own extended details. This field is optional and the data returned is not guaranteed to conform to any schema except that defined by the reason type. + """ + kind: Optional[str] = None + """ + Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + """ + message: Optional[str] = None + """ + A human-readable description of the status of this operation. + """ + metadata: Optional[ListMeta] = {} + """ + Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + """ + reason: Optional[str] = None + """ + A machine-readable description of why this operation is in the "Failure" status. If this value is empty there is no information available. A Reason clarifies an HTTP status code but does not override it. + """ + status: Optional[str] = None + """ + Status of the operation. One of: "Success" or "Failure". More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + """ diff --git a/tests/testdata/models/io/upbound/aws/s3/__init__.py b/tests/testdata/models/io/upbound/aws/s3/__init__.py new file mode 100644 index 0000000..92eaf2e --- /dev/null +++ b/tests/testdata/models/io/upbound/aws/s3/__init__.py @@ -0,0 +1,3 @@ +# generated by datamodel-codegen: +# filename: +# timestamp: 2024-10-04T21:01:52+00:00 diff --git a/tests/testdata/models/io/upbound/aws/s3/v1beta2.py b/tests/testdata/models/io/upbound/aws/s3/v1beta2.py new file mode 100644 index 0000000..0a678e0 --- /dev/null +++ b/tests/testdata/models/io/upbound/aws/s3/v1beta2.py @@ -0,0 +1,800 @@ +# generated by datamodel-codegen: +# filename: +# timestamp: 2024-10-04T21:01:52+00:00 + +from __future__ import annotations + +from enum import Enum +from typing import Dict, List, Optional + +from pydantic import AwareDatetime, BaseModel, Field + +from ....k8s.apimachinery.pkg.apis.meta import v1 + + +class DeletionPolicy(Enum): + Orphan = 'Orphan' + Delete = 'Delete' + + +class ForProvider(BaseModel): + forceDestroy: Optional[bool] = None + """ + Boolean that indicates all objects (including any locked objects) should be deleted from the bucket when the bucket is destroyed so that the bucket can be destroyed without error. These objects are not recoverable. This only deletes objects when the bucket is destroyed, not when setting this parameter to true. If setting this field in the same operation that would require replacing the bucket or destroying the bucket, this flag will not work. + """ + objectLockEnabled: Optional[bool] = None + """ + Indicates whether this bucket has an Object Lock configuration enabled. Valid values are true or false. This argument is not supported in all regions or partitions. + """ + region: str + """ + AWS region this bucket resides in. + Region is the region you'd like your resource to be created in. + """ + tags: Optional[Dict[str, str]] = None + """ + Key-value map of resource tags. + """ + + +class InitProvider(BaseModel): + forceDestroy: Optional[bool] = None + """ + Boolean that indicates all objects (including any locked objects) should be deleted from the bucket when the bucket is destroyed so that the bucket can be destroyed without error. These objects are not recoverable. This only deletes objects when the bucket is destroyed, not when setting this parameter to true. If setting this field in the same operation that would require replacing the bucket or destroying the bucket, this flag will not work. + """ + objectLockEnabled: Optional[bool] = None + """ + Indicates whether this bucket has an Object Lock configuration enabled. Valid values are true or false. This argument is not supported in all regions or partitions. + """ + tags: Optional[Dict[str, str]] = None + """ + Key-value map of resource tags. + """ + + +class ManagementPolicy(Enum): + Observe = 'Observe' + Create = 'Create' + Update = 'Update' + Delete = 'Delete' + LateInitialize = 'LateInitialize' + field_ = '*' + + +class Resolution(Enum): + Required = 'Required' + Optional = 'Optional' + + +class Resolve(Enum): + Always = 'Always' + IfNotPresent = 'IfNotPresent' + + +class Policy(BaseModel): + resolution: Optional[Resolution] = 'Required' + """ + Resolution specifies whether resolution of this reference is required. + The default is 'Required', which means the reconcile will fail if the + reference cannot be resolved. 'Optional' means this reference will be + a no-op if it cannot be resolved. + """ + resolve: Optional[Resolve] = None + """ + Resolve specifies when this reference should be resolved. The default + is 'IfNotPresent', which will attempt to resolve the reference only when + the corresponding field is not present. Use 'Always' to resolve the + reference on every reconcile. + """ + + +class ProviderConfigRef(BaseModel): + name: str + """ + Name of the referenced object. + """ + policy: Optional[Policy] = None + """ + Policies for referencing. + """ + + +class ConfigRef(BaseModel): + name: str + """ + Name of the referenced object. + """ + policy: Optional[Policy] = None + """ + Policies for referencing. + """ + + +class Metadata(BaseModel): + annotations: Optional[Dict[str, str]] = None + """ + Annotations are the annotations to be added to connection secret. + - For Kubernetes secrets, this will be used as "metadata.annotations". + - It is up to Secret Store implementation for others store types. + """ + labels: Optional[Dict[str, str]] = None + """ + Labels are the labels/tags to be added to connection secret. + - For Kubernetes secrets, this will be used as "metadata.labels". + - It is up to Secret Store implementation for others store types. + """ + type: Optional[str] = None + """ + Type is the SecretType for the connection secret. + - Only valid for Kubernetes Secret Stores. + """ + + +class PublishConnectionDetailsTo(BaseModel): + configRef: Optional[ConfigRef] = Field( + default_factory=lambda: ConfigRef.model_validate({'name': 'default'}) + ) + """ + SecretStoreConfigRef specifies which secret store config should be used + for this ConnectionSecret. + """ + metadata: Optional[Metadata] = None + """ + Metadata is the metadata for connection secret. + """ + name: str + """ + Name is the name of the connection secret. + """ + + +class WriteConnectionSecretToRef(BaseModel): + name: str + """ + Name of the secret. + """ + namespace: str + """ + Namespace of the secret. + """ + + +class Spec(BaseModel): + deletionPolicy: Optional[DeletionPolicy] = 'Delete' + """ + DeletionPolicy specifies what will happen to the underlying external + when this managed resource is deleted - either "Delete" or "Orphan" the + external resource. + This field is planned to be deprecated in favor of the ManagementPolicies + field in a future release. Currently, both could be set independently and + non-default values would be honored if the feature flag is enabled. + See the design doc for more information: https://github.com/crossplane/crossplane/blob/499895a25d1a1a0ba1604944ef98ac7a1a71f197/design/design-doc-observe-only-resources.md?plain=1#L223 + """ + forProvider: ForProvider + initProvider: Optional[InitProvider] = None + """ + THIS IS A BETA FIELD. It will be honored + unless the Management Policies feature flag is disabled. + InitProvider holds the same fields as ForProvider, with the exception + of Identifier and other resource reference fields. The fields that are + in InitProvider are merged into ForProvider when the resource is created. + The same fields are also added to the terraform ignore_changes hook, to + avoid updating them after creation. This is useful for fields that are + required on creation, but we do not desire to update them after creation, + for example because of an external controller is managing them, like an + autoscaler. + """ + managementPolicies: Optional[List[ManagementPolicy]] = ['*'] + """ + THIS IS A BETA FIELD. It is on by default but can be opted out + through a Crossplane feature flag. + ManagementPolicies specify the array of actions Crossplane is allowed to + take on the managed and external resources. + This field is planned to replace the DeletionPolicy field in a future + release. Currently, both could be set independently and non-default + values would be honored if the feature flag is enabled. If both are + custom, the DeletionPolicy field will be ignored. + See the design doc for more information: https://github.com/crossplane/crossplane/blob/499895a25d1a1a0ba1604944ef98ac7a1a71f197/design/design-doc-observe-only-resources.md?plain=1#L223 + and this one: https://github.com/crossplane/crossplane/blob/444267e84783136daa93568b364a5f01228cacbe/design/one-pager-ignore-changes.md + """ + providerConfigRef: Optional[ProviderConfigRef] = Field( + default_factory=lambda: ProviderConfigRef.model_validate({'name': 'default'}) + ) + """ + ProviderConfigReference specifies how the provider that will be used to + create, observe, update, and delete this managed resource should be + configured. + """ + publishConnectionDetailsTo: Optional[PublishConnectionDetailsTo] = None + """ + PublishConnectionDetailsTo specifies the connection secret config which + contains a name, metadata and a reference to secret store config to + which any connection details for this managed resource should be written. + Connection details frequently include the endpoint, username, + and password required to connect to the managed resource. + """ + writeConnectionSecretToRef: Optional[WriteConnectionSecretToRef] = None + """ + WriteConnectionSecretToReference specifies the namespace and name of a + Secret to which any connection details for this managed resource should + be written. Connection details frequently include the endpoint, username, + and password required to connect to the managed resource. + This field is planned to be replaced in a future release in favor of + PublishConnectionDetailsTo. Currently, both could be set independently + and connection details would be published to both without affecting + each other. + """ + + +class CorsRuleItem(BaseModel): + allowedHeaders: Optional[List[str]] = None + """ + List of headers allowed. + """ + allowedMethods: Optional[List[str]] = None + """ + One or more HTTP methods that you allow the origin to execute. Can be GET, PUT, POST, DELETE or HEAD. + """ + allowedOrigins: Optional[List[str]] = None + """ + One or more origins you want customers to be able to access the bucket from. + """ + exposeHeaders: Optional[List[str]] = None + """ + One or more headers in the response that you want customers to be able to access from their applications (for example, from a JavaScript XMLHttpRequest object). + """ + maxAgeSeconds: Optional[float] = None + """ + Specifies time in seconds that browser can cache the response for a preflight request. + """ + + +class GrantItem(BaseModel): + id: Optional[str] = None + """ + Canonical user id to grant for. Used only when type is CanonicalUser. + """ + permissions: Optional[List[str]] = None + """ + List of permissions to apply for grantee. Valid values are READ, WRITE, READ_ACP, WRITE_ACP, FULL_CONTROL. + """ + type: Optional[str] = None + """ + Type of grantee to apply for. Valid values are CanonicalUser and Group. AmazonCustomerByEmail is not supported. + """ + uri: Optional[str] = None + """ + Uri address to grant for. Used only when type is Group. + """ + + +class Expiration(BaseModel): + date: Optional[str] = None + """ + Specifies the date after which you want the corresponding action to take effect. + """ + days: Optional[float] = None + """ + Specifies the number of days after object creation when the specific rule action takes effect. + """ + expiredObjectDeleteMarker: Optional[bool] = None + """ + On a versioned bucket (versioning-enabled or versioning-suspended bucket), you can add this element in the lifecycle configuration to direct Amazon S3 to delete expired object delete markers. This cannot be specified with Days or Date in a Lifecycle Expiration Policy. + """ + + +class NoncurrentVersionExpiration(BaseModel): + days: Optional[float] = None + """ + Specifies the number of days after object creation when the specific rule action takes effect. + """ + + +class NoncurrentVersionTransitionItem(BaseModel): + days: Optional[float] = None + """ + Specifies the number of days after object creation when the specific rule action takes effect. + """ + storageClass: Optional[str] = None + """ + Specifies the Amazon S3 storage class to which you want the object to transition. + """ + + +class TransitionItem(BaseModel): + date: Optional[str] = None + """ + Specifies the date after which you want the corresponding action to take effect. + """ + days: Optional[float] = None + """ + Specifies the number of days after object creation when the specific rule action takes effect. + """ + storageClass: Optional[str] = None + """ + Specifies the Amazon S3 storage class to which you want the object to transition. + """ + + +class LifecycleRuleItem(BaseModel): + abortIncompleteMultipartUploadDays: Optional[float] = None + """ + Specifies the number of days after initiating a multipart upload when the multipart upload must be completed. + """ + enabled: Optional[bool] = None + """ + Specifies lifecycle rule status. + """ + expiration: Optional[Expiration] = None + """ + Specifies a period in the object's expire. See Expiration below for details. + """ + id: Optional[str] = None + """ + Unique identifier for the rule. Must be less than or equal to 255 characters in length. + """ + noncurrentVersionExpiration: Optional[NoncurrentVersionExpiration] = None + """ + Specifies when noncurrent object versions expire. See Noncurrent Version Expiration below for details. + """ + noncurrentVersionTransition: Optional[List[NoncurrentVersionTransitionItem]] = None + """ + Specifies when noncurrent object versions transitions. See Noncurrent Version Transition below for details. + """ + prefix: Optional[str] = None + """ + Object key prefix identifying one or more objects to which the rule applies. + """ + tags: Optional[Dict[str, str]] = None + """ + Specifies object tags key and value. + """ + transition: Optional[List[TransitionItem]] = None + """ + Specifies a period in the object's transitions. See Transition below for details. + """ + + +class Logging(BaseModel): + targetBucket: Optional[str] = None + """ + Name of the bucket that will receive the log objects. + """ + targetPrefix: Optional[str] = None + """ + To specify a key prefix for log objects. + """ + + +class DefaultRetention(BaseModel): + days: Optional[float] = None + """ + Number of days that you want to specify for the default retention period. + """ + mode: Optional[str] = None + """ + Default Object Lock retention mode you want to apply to new objects placed in this bucket. Valid values are GOVERNANCE and COMPLIANCE. + """ + years: Optional[float] = None + """ + Number of years that you want to specify for the default retention period. + """ + + +class Rule(BaseModel): + defaultRetention: Optional[DefaultRetention] = None + """ + Default retention period that you want to apply to new objects placed in this bucket (documented below). + """ + + +class ObjectLockConfiguration(BaseModel): + objectLockEnabled: Optional[str] = None + """ + Indicates whether this bucket has an Object Lock configuration enabled. Valid value is Enabled. Use the top-level argument object_lock_enabled instead. + """ + rule: Optional[Rule] = None + """ + Object Lock rule in place for this bucket (documented below). + """ + + +class AccessControlTranslation(BaseModel): + owner: Optional[str] = None + """ + Specifies the replica ownership. For default and valid values, see PUT bucket replication in the Amazon S3 API Reference. The only valid value is Destination. + """ + + +class Metrics(BaseModel): + minutes: Optional[float] = None + """ + Threshold within which objects are to be replicated. The only valid value is 15. + """ + status: Optional[str] = None + """ + Status of RTC. Either Enabled or Disabled. + """ + + +class ReplicationTime(BaseModel): + minutes: Optional[float] = None + """ + Threshold within which objects are to be replicated. The only valid value is 15. + """ + status: Optional[str] = None + """ + Status of RTC. Either Enabled or Disabled. + """ + + +class Destination(BaseModel): + accessControlTranslation: Optional[AccessControlTranslation] = None + """ + Specifies the overrides to use for object owners on replication (documented below). Must be used in conjunction with account_id owner override configuration. + """ + accountId: Optional[str] = None + """ + Account ID to use for overriding the object owner on replication. Must be used in conjunction with access_control_translation override configuration. + """ + bucket: Optional[str] = None + """ + ARN of the S3 bucket where you want Amazon S3 to store replicas of the object identified by the rule. + """ + metrics: Optional[Metrics] = None + """ + Enables replication metrics (documented below). + """ + replicaKmsKeyId: Optional[str] = None + """ + Destination KMS encryption key ARN for SSE-KMS replication. Must be used in conjunction with + sse_kms_encrypted_objects source selection criteria. + """ + replicationTime: Optional[ReplicationTime] = None + """ + Enables S3 Replication Time Control (S3 RTC) (documented below). + """ + storageClass: Optional[str] = None + """ + Specifies the Amazon S3 storage class to which you want the object to transition. + """ + + +class Filter(BaseModel): + prefix: Optional[str] = None + """ + Object keyname prefix that identifies subset of objects to which the rule applies. Must be less than or equal to 1024 characters in length. + """ + tags: Optional[Dict[str, str]] = None + """ + A map of tags that identifies subset of objects to which the rule applies. + The rule applies only to objects having all the tags in its tagset. + """ + + +class SseKmsEncryptedObjects(BaseModel): + enabled: Optional[bool] = None + """ + Enable versioning. Once you version-enable a bucket, it can never return to an unversioned state. You can, however, suspend versioning on that bucket. + """ + + +class SourceSelectionCriteria(BaseModel): + sseKmsEncryptedObjects: Optional[SseKmsEncryptedObjects] = None + """ + Match SSE-KMS encrypted objects (documented below). If specified, replica_kms_key_id + in destination must be specified as well. + """ + + +class RuleModel(BaseModel): + deleteMarkerReplicationStatus: Optional[str] = None + """ + Whether delete markers are replicated. The only valid value is Enabled. To disable, omit this argument. This argument is only valid with V2 replication configurations (i.e., when filter is used). + """ + destination: Optional[Destination] = None + """ + Specifies the destination for the rule (documented below). + """ + filter: Optional[Filter] = None + """ + Filter that identifies subset of objects to which the replication rule applies (documented below). + """ + id: Optional[str] = None + """ + Unique identifier for the rule. Must be less than or equal to 255 characters in length. + """ + prefix: Optional[str] = None + """ + Object keyname prefix identifying one or more objects to which the rule applies. Must be less than or equal to 1024 characters in length. + """ + priority: Optional[float] = None + """ + Priority associated with the rule. Priority should only be set if filter is configured. If not provided, defaults to 0. Priority must be unique between multiple rules. + """ + sourceSelectionCriteria: Optional[SourceSelectionCriteria] = None + """ + Specifies special object selection criteria (documented below). + """ + status: Optional[str] = None + """ + Status of the rule. Either Enabled or Disabled. The rule is ignored if status is not Enabled. + """ + + +class ReplicationConfiguration(BaseModel): + role: Optional[str] = None + """ + ARN of the IAM role for Amazon S3 to assume when replicating the objects. + """ + rules: Optional[List[RuleModel]] = None + """ + Specifies the rules managing the replication (documented below). + """ + + +class ApplyServerSideEncryptionByDefault(BaseModel): + kmsMasterKeyId: Optional[str] = None + """ + AWS KMS master key ID used for the SSE-KMS encryption. This can only be used when you set the value of sse_algorithm as aws:kms. The default aws/s3 AWS KMS master key is used if this element is absent while the sse_algorithm is aws:kms. + """ + sseAlgorithm: Optional[str] = None + """ + Server-side encryption algorithm to use. Valid values are AES256 and aws:kms + """ + + +class RuleModel1(BaseModel): + applyServerSideEncryptionByDefault: Optional[ApplyServerSideEncryptionByDefault] = ( + None + ) + """ + Single object for setting server-side encryption by default. (documented below) + """ + bucketKeyEnabled: Optional[bool] = None + """ + Whether or not to use Amazon S3 Bucket Keys for SSE-KMS. + """ + + +class ServerSideEncryptionConfiguration(BaseModel): + rule: Optional[RuleModel1] = None + """ + Single object for server-side encryption by default configuration. (documented below) + """ + + +class Versioning(BaseModel): + enabled: Optional[bool] = None + """ + Enable versioning. Once you version-enable a bucket, it can never return to an unversioned state. You can, however, suspend versioning on that bucket. + """ + mfaDelete: Optional[bool] = None + """ + Enable MFA delete for either Change the versioning state of your bucket or Permanently delete an object version. Default is false. This cannot be used to toggle this setting but is available to allow managed buckets to reflect the state in AWS + """ + + +class Website(BaseModel): + errorDocument: Optional[str] = None + """ + Absolute path to the document to return in case of a 4XX error. + """ + indexDocument: Optional[str] = None + """ + Amazon S3 returns this index document when requests are made to the root domain or any of the subfolders. + """ + redirectAllRequestsTo: Optional[str] = None + """ + Hostname to redirect all website requests for this bucket to. Hostname can optionally be prefixed with a protocol (http:// or https://) to use when redirecting requests. The default is the protocol that is used in the original request. + """ + routingRules: Optional[str] = None + """ + JSON array containing routing rules + describing redirect behavior and when redirects are applied. + """ + + +class AtProvider(BaseModel): + accelerationStatus: Optional[str] = None + """ + Sets the accelerate configuration of an existing bucket. Can be Enabled or Suspended. Cannot be used in cn-north-1 or us-gov-west-1. + Use the resource aws_s3_bucket_accelerate_configuration instead. + """ + acl: Optional[str] = None + """ + The canned ACL to apply. Valid values are private, public-read, public-read-write, aws-exec-read, authenticated-read, and log-delivery-write. Defaults to private. Conflicts with grant. Use the resource aws_s3_bucket_acl instead. + """ + arn: Optional[str] = None + """ + ARN of the bucket. Will be of format arn:aws:s3:::bucketname. + """ + bucketDomainName: Optional[str] = None + """ + Bucket domain name. Will be of format bucketname.s3.amazonaws.com. + """ + bucketRegionalDomainName: Optional[str] = None + """ + The bucket region-specific domain name. The bucket domain name including the region name. Please refer to the S3 endpoints reference for format. Note: AWS CloudFront allows specifying an S3 region-specific endpoint when creating an S3 origin. This will prevent redirect issues from CloudFront to the S3 Origin URL. For more information, see the Virtual Hosted-Style Requests for Other Regions section in the AWS S3 User Guide. + """ + corsRule: Optional[List[CorsRuleItem]] = None + """ + Rule of Cross-Origin Resource Sharing. See CORS rule below for details. Use the resource aws_s3_bucket_cors_configuration instead. + """ + forceDestroy: Optional[bool] = None + """ + Boolean that indicates all objects (including any locked objects) should be deleted from the bucket when the bucket is destroyed so that the bucket can be destroyed without error. These objects are not recoverable. This only deletes objects when the bucket is destroyed, not when setting this parameter to true. If setting this field in the same operation that would require replacing the bucket or destroying the bucket, this flag will not work. + """ + grant: Optional[List[GrantItem]] = None + """ + An ACL policy grant. See Grant below for details. Conflicts with acl. Use the resource aws_s3_bucket_acl instead. + """ + hostedZoneId: Optional[str] = None + """ + Route 53 Hosted Zone ID for this bucket's region. + """ + id: Optional[str] = None + """ + Name of the bucket. + """ + lifecycleRule: Optional[List[LifecycleRuleItem]] = None + """ + Configuration of object lifecycle management. See Lifecycle Rule below for details. + Use the resource aws_s3_bucket_lifecycle_configuration instead. + """ + logging: Optional[Logging] = None + """ + Configuration of S3 bucket logging parameters. See Logging below for details. + Use the resource aws_s3_bucket_logging instead. + """ + objectLockConfiguration: Optional[ObjectLockConfiguration] = None + """ + Configuration of S3 object locking. See Object Lock Configuration below for details. + Use the object_lock_enabled parameter and the resource aws_s3_bucket_object_lock_configuration instead. + """ + objectLockEnabled: Optional[bool] = None + """ + Indicates whether this bucket has an Object Lock configuration enabled. Valid values are true or false. This argument is not supported in all regions or partitions. + """ + policy: Optional[str] = None + """ + Valid bucket policy JSON document. In this case, please make sure you use the verbose/specific version of the policy. + Use the resource aws_s3_bucket_policy instead. + """ + region: Optional[str] = None + """ + AWS region this bucket resides in. + Region is the region you'd like your resource to be created in. + """ + replicationConfiguration: Optional[ReplicationConfiguration] = None + """ + Configuration of replication configuration. See Replication Configuration below for details. + Use the resource aws_s3_bucket_replication_configuration instead. + """ + requestPayer: Optional[str] = None + """ + Specifies who should bear the cost of Amazon S3 data transfer. + Can be either BucketOwner or Requester. By default, the owner of the S3 bucket would incur the costs of any data transfer. + See Requester Pays Buckets developer guide for more information. + Use the resource aws_s3_bucket_request_payment_configuration instead. + """ + serverSideEncryptionConfiguration: Optional[ServerSideEncryptionConfiguration] = ( + None + ) + """ + Configuration of server-side encryption configuration. See Server Side Encryption Configuration below for details. + Use the resource aws_s3_bucket_server_side_encryption_configuration instead. + """ + tags: Optional[Dict[str, str]] = None + """ + Key-value map of resource tags. + """ + tagsAll: Optional[Dict[str, str]] = None + """ + Map of tags assigned to the resource, including those inherited from the provider default_tags configuration block. + """ + versioning: Optional[Versioning] = None + """ + Configuration of the S3 bucket versioning state. See Versioning below for details. Use the resource aws_s3_bucket_versioning instead. + """ + website: Optional[Website] = None + """ + Configuration of the S3 bucket website. See Website below for details. + Use the resource aws_s3_bucket_website_configuration instead. + """ + websiteDomain: Optional[str] = None + """ + (Deprecated) Domain of the website endpoint, if the bucket is configured with a website. If not, this will be an empty string. This is used to create Route 53 alias records. Use the resource aws_s3_bucket_website_configuration instead. + """ + websiteEndpoint: Optional[str] = None + """ + (Deprecated) Website endpoint, if the bucket is configured with a website. If not, this will be an empty string. Use the resource aws_s3_bucket_website_configuration instead. + """ + + +class Condition(BaseModel): + lastTransitionTime: AwareDatetime + """ + LastTransitionTime is the last time this condition transitioned from one + status to another. + """ + message: Optional[str] = None + """ + A Message containing details about this condition's last transition from + one status to another, if any. + """ + observedGeneration: Optional[int] = None + """ + ObservedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + """ + reason: str + """ + A Reason for this condition's last transition from one status to another. + """ + status: str + """ + Status of this condition; is it currently True, False, or Unknown? + """ + type: str + """ + Type of this condition. At most one of each condition type may apply to + a resource at any point in time. + """ + + +class Status(BaseModel): + atProvider: Optional[AtProvider] = None + conditions: Optional[List[Condition]] = None + """ + Conditions of the resource. + """ + observedGeneration: Optional[int] = None + """ + ObservedGeneration is the latest metadata.generation + which resulted in either a ready state, or stalled due to error + it can not recover from without human intervention. + """ + + +class Bucket(BaseModel): + apiVersion: Optional[str] = None + """ + APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + """ + kind: Optional[str] = None + """ + Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + """ + metadata: Optional[v1.ObjectMeta] = None + """ + Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + """ + spec: Spec + """ + BucketSpec defines the desired state of Bucket + """ + status: Optional[Status] = None + """ + BucketStatus defines the observed state of Bucket. + """ + + +class BucketList(BaseModel): + apiVersion: Optional[str] = None + """ + APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + """ + items: List[Bucket] + """ + List of buckets. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md + """ + kind: Optional[str] = None + """ + Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + """ + metadata: Optional[v1.ListMeta] = None + """ + Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + """ From 5fe3b5c9e0cb4b020ece3e188ef1a95858af049e Mon Sep 17 00:00:00 2001 From: Nic Cope Date: Wed, 9 Oct 2024 10:37:28 -0700 Subject: [PATCH 2/3] Don't lint (generated) testdata Signed-off-by: Nic Cope --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index bb5a19e..08a6eb3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -79,7 +79,7 @@ packages = ["crossplane"] [tool.ruff] target-version = "py311" -exclude = ["crossplane/function/proto/*"] +exclude = ["crossplane/function/proto/*", "tests/testdata/*"] lint.select = [ "A", "ARG", From df655cabecd33a335668ffdc337d397e0b70fc36 Mon Sep 17 00:00:00 2001 From: Nic Cope Date: Wed, 9 Oct 2024 17:51:26 -0700 Subject: [PATCH 3/3] Use class matches in resource.update() This was introduced in 3.10, and seems like a much better way to handle matching a type. Signed-off-by: Nic Cope --- crossplane/function/resource.py | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/crossplane/function/resource.py b/crossplane/function/resource.py index 51483e3..322a482 100644 --- a/crossplane/function/resource.py +++ b/crossplane/function/resource.py @@ -36,20 +36,18 @@ def update(r: fnv1.Resource, source: dict | structpb.Struct | pydantic.BaseModel The source can be a dictionary, a protobuf Struct, or a Pydantic model. """ - # If the resource has a model_dump attribute it's a Pydantic BaseModel. - if hasattr(source, "model_dump"): - r.resource.update(source.model_dump(exclude_defaults=True, warnings=False)) - return - - # If the resource has a get_or_create_struct attribute it's a Struct. - if hasattr(source, "get_or_create_struct"): - # TODO(negz): Use struct_to_dict and update to match other semantics? - r.resource.MergeFrom(source) - return - - # If it has neither, it must be a dictionary. - r.resource.update(source) - return + match source: + case pydantic.BaseModel(): + r.resource.update(source.model_dump(exclude_defaults=True, warnings=False)) + case structpb.Struct(): + # TODO(negz): Use struct_to_dict and update to match other semantics? + r.resource.MergeFrom(source) + case dict(): + r.resource.update(source) + case _: + t = type(source) + msg = f"Unsupported type: {t}" + raise TypeError(msg) def dict_to_struct(d: dict) -> structpb.Struct: