kr8s-org / kr8s

A batteries-included Python client library for Kubernetes that feels familiar for folks who already know how to use kubectl
https://kr8s.org
BSD 3-Clause "New" or "Revised" License
799 stars 43 forks source link

Create an instance of `CustomResourceDefinition` from a dataclass #456

Open jacobtomlinson opened 1 month ago

jacobtomlinson commented 1 month ago

We could add a classmethod to the CustomResourceDefinition object classes which takes a dataclass and returns an instance of the CRD. This classmethod could follow a similar interface to new_class to set things like the name, version and the group.

Here's an example of what this could look like using the kr8s sync API.

from dataclasses import dataclass, field
from apischema import schema
from kr8s.objects import CustomResourceDefinition

@dataclass
class MyCustomResourceSpecV1:
    foo: str
    bar: str
    baz: list[str] = field(
        default_factory=list,
        metadata=schema(
            description="List of baz",
            unique=False,
        ),
    )

my_crd = CustomResourceDefinition.from_dataclass(
    "MyCustomResource.example.com", namespaced=True, v1=MyCustomResourceSpecV1
)
my_crd.create()

The from_dataclass classmethod would need to behave similarly to kubecrd.KubeResourceBase.crd_schema_dict().

The CustomResourceDefinition contains some metadata about the resource such as the name, group, etc and whether it is versioned. It then contains a list of specification versions. The implementation in kubecrd assumes only one version but it would be nice to support multiple. These could be passed as **kwargs as v1 is in the example above, or as a versions= kwarg with a list of dicts to allow configuration of which is served and stored.

This could even be CustomResourceDefinitions implementation of #142 and use the name CustomResourceDefinition.gen(...) instead of CustomResourceDefinition.from_dataclass(...).