{"owner":"kubernetes","repo":"client-go","hasSkills":true,"totalSkillsCount":1,"totalTokensCount":1861,"categories":["project-spec"],"hasMcp":false,"mcpConfig":null,"found":["ARCHITECTURE.md"],"skills":{"ARCHITECTURE.md":"# `client-go` Architecture\n\nThis document explains the internal architecture of `client-go` for contributors. It describes the\nmajor components, how they interact, and the key design decisions that shape the library.\n\n## Client Configuration\n\nThere is an architectural separation between loading client configuration and using it. The\n`rest.Config` object is the in-memory representation of this configuration. The\n`tools/clientcmd` package is the standard factory for producing it. `clientcmd` handles the\ncomplex logic of parsing `kubeconfig` files, merging contexts, and handling external\nauthentication providers (e.g., OIDC).\n\n## REST Client\n\nThe `rest.Client` is the foundational HTTP client that underpins all other clients. It separates\nthe low-level concerns of HTTP transport, serialization, and error handling from higher-level,\nKubernetes-specific object logic.\n\nThe `rest.Config` object is used to build the underlying HTTP transport, which is typically a\nchain of `http.RoundTripper` objects. Each element in the chain is responsible for a specific\ntask, such as adding an `Authorization` header. This is the mechanism by which all authentication\nis injected into requests.\n\nThe client uses a builder pattern for requests (e.g., `.Verb()`, `.Resource()`), deferring\nresponse processing until a method like `.Into(&pod)` is called. This separation is key to\nsupporting different client models from a common base.\n\n### Endpoint Interactions\n\n*   **Content Negotiation:** The client uses HTTP `Accept` headers to negotiate the wire format\n    (JSON or Protobuf). A key performance optimization using this mechanism is the ability to\n    request metadata-only objects via the `as=PartialObjectMetadata;g=meta.k8s.io;v=v1` Accept custom parameter.\n    Also the `as=Table;g=meta.k8s.io;v=v1` Accept custom parameters may be used to request lists as tables. \n*   **Subresources:** The client can target standard subresources like `/status` or `/scale` for\n    object mutations, and it can also handle action-oriented subresources like `/logs` or\n    `/exec`, which often involve streaming data.\n*   **List Pagination:** For `LIST` requests, the client can specify a `limit`. The server will\n    return up to that many items and, if more exist, a `continue` token. The client is\n    responsible for passing this token in a subsequent request to retrieve the next page.\n    Higher-level tools like the `Reflector`'s `ListerWatcher` handle this logic automatically.\n*   **Streaming Watches:** A `WATCH` request returns a `watch.Interface` (from\n    `k8s.io/apimachinery/pkg/watch`), which provides a channel of structured `watch.Event`\n    objects (`ADDED`, `MODIFIED`, `DELETED`, `BOOKMARK`). This decouples the watch consumer from\n    the underlying streaming protocol.\n\n### Errors, Warnings, and Rate Limiting\n\n*   **Structured Errors:** The client deserializes non-2xx responses into a structured\n    `errors.StatusError`, enabling programmatic error handling (e.g., `errors.IsNotFound(err)`).\n*   **Warnings:** It processes non-fatal `Warning` headers from the API server via a\n    `WarningHandler`.\n*   **Client-Side Rate Limiting:** The `QPS` and `Burst` settings in `rest.Config` are the\n    client's half of the contract with the server's API Priority and Fairness system.\n*   **Server-Side Throttling:** The client's default transport automatically handles HTTP `429`\n    responses by reading the `Retry-After` header, waiting, and retrying the request.\n\n## Typed and Dynamic Clients\n\nTo handle the extensible nature of the Kubernetes API, `client-go` provides two primary client\nmodels.\n\nThe **`kubernetes.Clientset`** provides compile-time, type-safe access to core, built-in APIs.\n\nThe **`dynamic.DynamicClient`** represents all objects as `unstructured.Unstructured`, allowing it\nto interact with any API resource, including CRDs. It relies on two discovery mechanisms:\n1.  The **`discovery.DiscoveryClient`** determines *what* resources exist. The\n    **`CachedDiscoveryClient`** is an optimization that caches this data on disk to solve.\n2.  The **OpenAPI schema** (fetched from `/openapi/v3`) describes the *structure* of those\n    resources, providing the schema awareness needed by the dynamic client.\n\n## Code Generation\n\nA core architectural principle of `client-go` is the use of code generation to provide a\nstrongly-typed, compile-time-safe interface for specific API GroupVersions. This makes\ncontroller code more robust and easier to maintain. The tools in `k8s.io/code-generator` produce\nseveral key components:\n\n*   **Typed Clientsets:** The primary interface for interacting with a specific GroupVersion.\n*   **Typed Listers:** The read-only, cached accessors used by controllers.\n*   **Typed Informers:** The machinery for populating the cache for a specific type.\n*   **Apply Configurations:** The type-safe builders for Server-Side Apply.\n\nA contributor modifying a built-in API type **must** run the code generation scripts to update all\nof these dependent components. For the Kubernetes project, `hack/update-codegen.sh` runs code generation.\n\n`sample-controller` shows how code generate can be configured to build custom controllers.\n\n## Controller Infrastructure\n\nThe `tools/cache` package provides the core infrastructure for controllers, replacing a high-load,\nrequest-based pattern with a low-load, event-driven, cached model.\n\nThe data flow is as follows:\n\n```mermaid\ngraph TD\n    subgraph \"Kubernetes API\"\n        API_Server[API Server]\n    end\n\n    subgraph \"client-go: Informer Mechanism\"\n        Reflector(\"1. Reflector\")\n        DeltaFIFO(\"2. DeltaFIFO\")\n        Indexer[\"3. Indexer (Cache)\"]\n        EventHandlers(\"4. Event Handlers\")\n    end\n\n    subgraph \"User Code\"\n        WorkQueue[\"5. Work Queue\"]\n        Controller(\"6. Controller\")\n    end\n\n    API_Server -- LIST/WATCH --> Reflector\n    Reflector -- Puts changes into --> DeltaFIFO\n    DeltaFIFO -- Is popped by internal loop, which updates --> Indexer\n    Indexer -- Update triggers --> EventHandlers\n    EventHandlers -- Adds key to --> WorkQueue\n    WorkQueue -- Is processed by --> Controller\n    Controller -- Reads from cache via Lister --> Indexer\n```\n\nA **`Reflector`** performs a `LIST` to get a consistent snapshot of a resource, identified by a\n`resourceVersion`. It then starts a `WATCH` from that `resourceVersion` to receive a continuous\nstream of subsequent changes. The `Reflector`'s relist/rewatch loop is designed to solve the\n**\"too old\" `resourceVersion` error** by re-listing. To make this recovery more efficient, the\n`Reflector` consumes **watch bookmarks** from the server, which provide a more recent\n`resourceVersion` to restart from.\n\nThe **`Lister`** is the primary, read-only, thread-safe interface for a controller's business\nlogic to access the `Indexer`'s cache.\n\n## Controller Patterns\n\nThe controller infrastructure is architecturally decoupled from the controller's business logic to\nensure resiliency.\n\nThe **`util/workqueue`** creates a critical boundary between event detection (the informer's job)\nand reconciliation (the controller's job). Informer event handlers only add an object's key to the\nwork queue. This allows the controller to retry failed operations with exponential backoff without\nblocking the informer's watch stream.\n\nFor high availability, the **`tools/leaderelection`** package provides the standard architectural\nsolution to ensure single-writer semantics by having replicas compete to acquire a lock on a\nshared `Lease` object.\n\n## Server-Side Apply\n\n`client-go` provides a distinct architectural pattern for object mutation that aligns with the\nserver's declarative model. This is a separate workflow from the traditional `get-modify-update`\nmodel that allows multiple controllers to safely co-manage the same object. The\n**`applyconfigurations`** package provides the generated, type-safe builder API used to\nconstruct the declarative patch.\n\n## Versioning and Compatibility\n\n`client-go` has a strict versioning relationship with the main Kubernetes repository. A `client-go`\nversion `v0.X.Y` corresponds to the Kubernetes version `v1.X.Y`.\n\nThe Kubernetes API has strong backward compatibility guarantees: a client built with an older\nversion of `client-go` will work with a newer API server. However, the reverse is not guaranteed.\nA contributor must not break compatibility with supported versions of the Kubernetes API server.\n"},"files":{"ARCHITECTURE.md":"# `client-go` Architecture\n\nThis document explains the internal architecture of `client-go` for contributors. It describes the\nmajor components, how they interact, and the key design decisions that shape the library.\n\n## Client Configuration\n\nThere is an architectural separation between loading client configuration and using it. The\n`rest.Config` object is the in-memory representation of this configuration. The\n`tools/clientcmd` package is the standard factory for producing it. `clientcmd` handles the\ncomplex logic of parsing `kubeconfig` files, merging contexts, and handling external\nauthentication providers (e.g., OIDC).\n\n## REST Client\n\nThe `rest.Client` is the foundational HTTP client that underpins all other clients. It separates\nthe low-level concerns of HTTP transport, serialization, and error handling from higher-level,\nKubernetes-specific object logic.\n\nThe `rest.Config` object is used to build the underlying HTTP transport, which is typically a\nchain of `http.RoundTripper` objects. Each element in the chain is responsible for a specific\ntask, such as adding an `Authorization` header. This is the mechanism by which all authentication\nis injected into requests.\n\nThe client uses a builder pattern for requests (e.g., `.Verb()`, `.Resource()`), deferring\nresponse processing until a method like `.Into(&pod)` is called. This separation is key to\nsupporting different client models from a common base.\n\n### Endpoint Interactions\n\n*   **Content Negotiation:** The client uses HTTP `Accept` headers to negotiate the wire format\n    (JSON or Protobuf). A key performance optimization using this mechanism is the ability to\n    request metadata-only objects via the `as=PartialObjectMetadata;g=meta.k8s.io;v=v1` Accept custom parameter.\n    Also the `as=Table;g=meta.k8s.io;v=v1` Accept custom parameters may be used to request lists as tables. \n*   **Subresources:** The client can target standard subresources like `/status` or `/scale` for\n    object mutations, and it can also handle action-oriented subresources like `/logs` or\n    `/exec`, which often involve streaming data.\n*   **List Pagination:** For `LIST` requests, the client can specify a `limit`. The server will\n    return up to that many items and, if more exist, a `continue` token. The client is\n    responsible for passing this token in a subsequent request to retrieve the next page.\n    Higher-level tools like the `Reflector`'s `ListerWatcher` handle this logic automatically.\n*   **Streaming Watches:** A `WATCH` request returns a `watch.Interface` (from\n    `k8s.io/apimachinery/pkg/watch`), which provides a channel of structured `watch.Event`\n    objects (`ADDED`, `MODIFIED`, `DELETED`, `BOOKMARK`). This decouples the watch consumer from\n    the underlying streaming protocol.\n\n### Errors, Warnings, and Rate Limiting\n\n*   **Structured Errors:** The client deserializes non-2xx responses into a structured\n    `errors.StatusError`, enabling programmatic error handling (e.g., `errors.IsNotFound(err)`).\n*   **Warnings:** It processes non-fatal `Warning` headers from the API server via a\n    `WarningHandler`.\n*   **Client-Side Rate Limiting:** The `QPS` and `Burst` settings in `rest.Config` are the\n    client's half of the contract with the server's API Priority and Fairness system.\n*   **Server-Side Throttling:** The client's default transport automatically handles HTTP `429`\n    responses by reading the `Retry-After` header, waiting, and retrying the request.\n\n## Typed and Dynamic Clients\n\nTo handle the extensible nature of the Kubernetes API, `client-go` provides two primary client\nmodels.\n\nThe **`kubernetes.Clientset`** provides compile-time, type-safe access to core, built-in APIs.\n\nThe **`dynamic.DynamicClient`** represents all objects as `unstructured.Unstructured`, allowing it\nto interact with any API resource, including CRDs. It relies on two discovery mechanisms:\n1.  The **`discovery.DiscoveryClient`** determines *what* resources exist. The\n    **`CachedDiscoveryClient`** is an optimization that caches this data on disk to solve.\n2.  The **OpenAPI schema** (fetched from `/openapi/v3`) describes the *structure* of those\n    resources, providing the schema awareness needed by the dynamic client.\n\n## Code Generation\n\nA core architectural principle of `client-go` is the use of code generation to provide a\nstrongly-typed, compile-time-safe interface for specific API GroupVersions. This makes\ncontroller code more robust and easier to maintain. The tools in `k8s.io/code-generator` produce\nseveral key components:\n\n*   **Typed Clientsets:** The primary interface for interacting with a specific GroupVersion.\n*   **Typed Listers:** The read-only, cached accessors used by controllers.\n*   **Typed Informers:** The machinery for populating the cache for a specific type.\n*   **Apply Configurations:** The type-safe builders for Server-Side Apply.\n\nA contributor modifying a built-in API type **must** run the code generation scripts to update all\nof these dependent components. For the Kubernetes project, `hack/update-codegen.sh` runs code generation.\n\n`sample-controller` shows how code generate can be configured to build custom controllers.\n\n## Controller Infrastructure\n\nThe `tools/cache` package provides the core infrastructure for controllers, replacing a high-load,\nrequest-based pattern with a low-load, event-driven, cached model.\n\nThe data flow is as follows:\n\n```mermaid\ngraph TD\n    subgraph \"Kubernetes API\"\n        API_Server[API Server]\n    end\n\n    subgraph \"client-go: Informer Mechanism\"\n        Reflector(\"1. Reflector\")\n        DeltaFIFO(\"2. DeltaFIFO\")\n        Indexer[\"3. Indexer (Cache)\"]\n        EventHandlers(\"4. Event Handlers\")\n    end\n\n    subgraph \"User Code\"\n        WorkQueue[\"5. Work Queue\"]\n        Controller(\"6. Controller\")\n    end\n\n    API_Server -- LIST/WATCH --> Reflector\n    Reflector -- Puts changes into --> DeltaFIFO\n    DeltaFIFO -- Is popped by internal loop, which updates --> Indexer\n    Indexer -- Update triggers --> EventHandlers\n    EventHandlers -- Adds key to --> WorkQueue\n    WorkQueue -- Is processed by --> Controller\n    Controller -- Reads from cache via Lister --> Indexer\n```\n\nA **`Reflector`** performs a `LIST` to get a consistent snapshot of a resource, identified by a\n`resourceVersion`. It then starts a `WATCH` from that `resourceVersion` to receive a continuous\nstream of subsequent changes. The `Reflector`'s relist/rewatch loop is designed to solve the\n**\"too old\" `resourceVersion` error** by re-listing. To make this recovery more efficient, the\n`Reflector` consumes **watch bookmarks** from the server, which provide a more recent\n`resourceVersion` to restart from.\n\nThe **`Lister`** is the primary, read-only, thread-safe interface for a controller's business\nlogic to access the `Indexer`'s cache.\n\n## Controller Patterns\n\nThe controller infrastructure is architecturally decoupled from the controller's business logic to\nensure resiliency.\n\nThe **`util/workqueue`** creates a critical boundary between event detection (the informer's job)\nand reconciliation (the controller's job). Informer event handlers only add an object's key to the\nwork queue. This allows the controller to retry failed operations with exponential backoff without\nblocking the informer's watch stream.\n\nFor high availability, the **`tools/leaderelection`** package provides the standard architectural\nsolution to ensure single-writer semantics by having replicas compete to acquire a lock on a\nshared `Lease` object.\n\n## Server-Side Apply\n\n`client-go` provides a distinct architectural pattern for object mutation that aligns with the\nserver's declarative model. This is a separate workflow from the traditional `get-modify-update`\nmodel that allows multiple controllers to safely co-manage the same object. The\n**`applyconfigurations`** package provides the generated, type-safe builder API used to\nconstruct the declarative patch.\n\n## Versioning and Compatibility\n\n`client-go` has a strict versioning relationship with the main Kubernetes repository. A `client-go`\nversion `v0.X.Y` corresponds to the Kubernetes version `v1.X.Y`.\n\nThe Kubernetes API has strong backward compatibility guarantees: a client built with an older\nversion of `client-go` will work with a newer API server. However, the reverse is not guaranteed.\nA contributor must not break compatibility with supported versions of the Kubernetes API server.\n"},"items":[{"name":"ARCHITECTURE.md","path":"ARCHITECTURE.md","rawUrl":"https://raw.githubusercontent.com/kubernetes/client-go/HEAD/ARCHITECTURE.md","title":"System Architecture & Module Boundaries","category":"project-spec","format":"markdown","content":"# `client-go` Architecture\n\nThis document explains the internal architecture of `client-go` for contributors. It describes the\nmajor components, how they interact, and the key design decisions that shape the library.\n\n## Client Configuration\n\nThere is an architectural separation between loading client configuration and using it. The\n`rest.Config` object is the in-memory representation of this configuration. The\n`tools/clientcmd` package is the standard factory for producing it. `clientcmd` handles the\ncomplex logic of parsing `kubeconfig` files, merging contexts, and handling external\nauthentication providers (e.g., OIDC).\n\n## REST Client\n\nThe `rest.Client` is the foundational HTTP client that underpins all other clients. It separates\nthe low-level concerns of HTTP transport, serialization, and error handling from higher-level,\nKubernetes-specific object logic.\n\nThe `rest.Config` object is used to build the underlying HTTP transport, which is typically a\nchain of `http.RoundTripper` objects. Each element in the chain is responsible for a specific\ntask, such as adding an `Authorization` header. This is the mechanism by which all authentication\nis injected into requests.\n\nThe client uses a builder pattern for requests (e.g., `.Verb()`, `.Resource()`), deferring\nresponse processing until a method like `.Into(&pod)` is called. This separation is key to\nsupporting different client models from a common base.\n\n### Endpoint Interactions\n\n*   **Content Negotiation:** The client uses HTTP `Accept` headers to negotiate the wire format\n    (JSON or Protobuf). A key performance optimization using this mechanism is the ability to\n    request metadata-only objects via the `as=PartialObjectMetadata;g=meta.k8s.io;v=v1` Accept custom parameter.\n    Also the `as=Table;g=meta.k8s.io;v=v1` Accept custom parameters may be used to request lists as tables. \n*   **Subresources:** The client can target standard subresources like `/status` or `/scale` for\n    object mutations, and it can also handle action-oriented subresources like `/logs` or\n    `/exec`, which often involve streaming data.\n*   **List Pagination:** For `LIST` requests, the client can specify a `limit`. The server will\n    return up to that many items and, if more exist, a `continue` token. The client is\n    responsible for passing this token in a subsequent request to retrieve the next page.\n    Higher-level tools like the `Reflector`'s `ListerWatcher` handle this logic automatically.\n*   **Streaming Watches:** A `WATCH` request returns a `watch.Interface` (from\n    `k8s.io/apimachinery/pkg/watch`), which provides a channel of structured `watch.Event`\n    objects (`ADDED`, `MODIFIED`, `DELETED`, `BOOKMARK`). This decouples the watch consumer from\n    the underlying streaming protocol.\n\n### Errors, Warnings, and Rate Limiting\n\n*   **Structured Errors:** The client deserializes non-2xx responses into a structured\n    `errors.StatusError`, enabling programmatic error handling (e.g., `errors.IsNotFound(err)`).\n*   **Warnings:** It processes non-fatal `Warning` headers from the API server via a\n    `WarningHandler`.\n*   **Client-Side Rate Limiting:** The `QPS` and `Burst` settings in `rest.Config` are the\n    client's half of the contract with the server's API Priority and Fairness system.\n*   **Server-Side Throttling:** The client's default transport automatically handles HTTP `429`\n    responses by reading the `Retry-After` header, waiting, and retrying the request.\n\n## Typed and Dynamic Clients\n\nTo handle the extensible nature of the Kubernetes API, `client-go` provides two primary client\nmodels.\n\nThe **`kubernetes.Clientset`** provides compile-time, type-safe access to core, built-in APIs.\n\nThe **`dynamic.DynamicClient`** represents all objects as `unstructured.Unstructured`, allowing it\nto interact with any API resource, including CRDs. It relies on two discovery mechanisms:\n1.  The **`discovery.DiscoveryClient`** determines *what* resources exist. The\n    **`CachedDiscoveryClient`** is an optimization that caches this data on disk to solve.\n2.  The **OpenAPI schema** (fetched from `/openapi/v3`) describes the *structure* of those\n    resources, providing the schema awareness needed by the dynamic client.\n\n## Code Generation\n\nA core architectural principle of `client-go` is the use of code generation to provide a\nstrongly-typed, compile-time-safe interface for specific API GroupVersions. This makes\ncontroller code more robust and easier to maintain. The tools in `k8s.io/code-generator` produce\nseveral key components:\n\n*   **Typed Clientsets:** The primary interface for interacting with a specific GroupVersion.\n*   **Typed Listers:** The read-only, cached accessors used by controllers.\n*   **Typed Informers:** The machinery for populating the cache for a specific type.\n*   **Apply Configurations:** The type-safe builders for Server-Side Apply.\n\nA contributor modifying a built-in API type **must** run the code generation scripts to update all\nof these dependent components. For the Kubernetes project, `hack/update-codegen.sh` runs code generation.\n\n`sample-controller` shows how code generate can be configured to build custom controllers.\n\n## Controller Infrastructure\n\nThe `tools/cache` package provides the core infrastructure for controllers, replacing a high-load,\nrequest-based pattern with a low-load, event-driven, cached model.\n\nThe data flow is as follows:\n\n```mermaid\ngraph TD\n    subgraph \"Kubernetes API\"\n        API_Server[API Server]\n    end\n\n    subgraph \"client-go: Informer Mechanism\"\n        Reflector(\"1. Reflector\")\n        DeltaFIFO(\"2. DeltaFIFO\")\n        Indexer[\"3. Indexer (Cache)\"]\n        EventHandlers(\"4. Event Handlers\")\n    end\n\n    subgraph \"User Code\"\n        WorkQueue[\"5. Work Queue\"]\n        Controller(\"6. Controller\")\n    end\n\n    API_Server -- LIST/WATCH --> Reflector\n    Reflector -- Puts changes into --> DeltaFIFO\n    DeltaFIFO -- Is popped by internal loop, which updates --> Indexer\n    Indexer -- Update triggers --> EventHandlers\n    EventHandlers -- Adds key to --> WorkQueue\n    WorkQueue -- Is processed by --> Controller\n    Controller -- Reads from cache via Lister --> Indexer\n```\n\nA **`Reflector`** performs a `LIST` to get a consistent snapshot of a resource, identified by a\n`resourceVersion`. It then starts a `WATCH` from that `resourceVersion` to receive a continuous\nstream of subsequent changes. The `Reflector`'s relist/rewatch loop is designed to solve the\n**\"too old\" `resourceVersion` error** by re-listing. To make this recovery more efficient, the\n`Reflector` consumes **watch bookmarks** from the server, which provide a more recent\n`resourceVersion` to restart from.\n\nThe **`Lister`** is the primary, read-only, thread-safe interface for a controller's business\nlogic to access the `Indexer`'s cache.\n\n## Controller Patterns\n\nThe controller infrastructure is architecturally decoupled from the controller's business logic to\nensure resiliency.\n\nThe **`util/workqueue`** creates a critical boundary between event detection (the informer's job)\nand reconciliation (the controller's job). Informer event handlers only add an object's key to the\nwork queue. This allows the controller to retry failed operations with exponential backoff without\nblocking the informer's watch stream.\n\nFor high availability, the **`tools/leaderelection`** package provides the standard architectural\nsolution to ensure single-writer semantics by having replicas compete to acquire a lock on a\nshared `Lease` object.\n\n## Server-Side Apply\n\n`client-go` provides a distinct architectural pattern for object mutation that aligns with the\nserver's declarative model. This is a separate workflow from the traditional `get-modify-update`\nmodel that allows multiple controllers to safely co-manage the same object. The\n**`applyconfigurations`** package provides the generated, type-safe builder API used to\nconstruct the declarative patch.\n\n## Versioning and Compatibility\n\n`client-go` has a strict versioning relationship with the main Kubernetes repository. A `client-go`\nversion `v0.X.Y` corresponds to the Kubernetes version `v1.X.Y`.\n\nThe Kubernetes API has strong backward compatibility guarantees: a client built with an older\nversion of `client-go` will work with a newer API server. However, the reverse is not guaranteed.\nA contributor must not break compatibility with supported versions of the Kubernetes API server.\n","isInternal":false,"tokens":1861,"sizeBytes":8402}],"systemPromptSnippet":"<yakaai_skills repo=\"kubernetes/client-go\">\n<!-- File: ARCHITECTURE.md (Tokens: ~1861 | Category: project-spec) -->\n# `client-go` Architecture\n\nThis document explains the internal architecture of `client-go` for contributors. It describes the\nmajor components, how they interact, and the key design decisions that shape the library.\n\n## Client Configuration\n\nThere is an architectural separation between loading client configuration and using it. The\n`rest.Config` object is the in-memory representation of this configuration. The\n`tools/clientcmd` package is the standard factory for producing it. `clientcmd` handles the\ncomplex logic of parsing `kubeconfig` files, merging contexts, and handling external\nauthentication providers (e.g., OIDC).\n\n## REST Client\n\nThe `rest.Client` is the foundational HTTP client that underpins all other clients. It separates\nthe low-level concerns of HTTP transport, serialization, and error handling from higher-level,\nKubernetes-specific object logic.\n\nThe `rest.Config` object is used to build the underlying HTTP transport, which is typically a\nchain of `http.RoundTripper` objects. Each element in the chain is responsible for a specific\ntask, such as adding an `Authorization` header. This is the mechanism by which all authentication\nis injected into requests.\n\nThe client uses a builder pattern for requests (e.g., `.Verb()`, `.Resource()`), deferring\nresponse processing until a method like `.Into(&pod)` is called. This separation is key to\nsupporting different client models from a common base.\n\n### Endpoint Interactions\n\n*   **Content Negotiation:** The client uses HTTP `Accept` headers to negotiate the wire format\n    (JSON or Protobuf). A key performance optimization using this mechanism is the ability to\n    request metadata-only objects via the `as=PartialObjectMetadata;g=meta.k8s.io;v=v1` Accept custom parameter.\n    Also the `as=Table;g=meta.k8s.io;v=v1` Accept custom parameters may be used to request lists as tables. \n*   **Subresources:** The client can target standard subresources like `/status` or `/scale` for\n    object mutations, and it can also handle action-oriented subresources like `/logs` or\n    `/exec`, which often involve streaming data.\n*   **List Pagination:** For `LIST` requests, the client can specify a `limit`. The server will\n    return up to that many items and, if more exist, a `continue` token. The client is\n    responsible for passing this token in a subsequent request to retrieve the next page.\n    Higher-level tools like the `Reflector`'s `ListerWatcher` handle this logic automatically.\n*   **Streaming Watches:** A `WATCH` request returns a `watch.Interface` (from\n    `k8s.io/apimachinery/pkg/watch`), which provides a channel of structured `watch.Event`\n    objects (`ADDED`, `MODIFIED`, `DELETED`, `BOOKMARK`). This decouples the watch consumer from\n    the underlying streaming protocol.\n\n### Errors, Warnings, and Rate Limiting\n\n*   **Structured Errors:** The client deserializes non-2xx responses into a structured\n    `errors.StatusError`, enabling programmatic error handling (e.g., `errors.IsNotFound(err)`).\n*   **Warnings:** It processes non-fatal `Warning` headers from the API server via a\n    `WarningHandler`.\n*   **Client-Side Rate Limiting:** The `QPS` and `Burst` settings in `rest.Config` are the\n    client's half of the contract with the server's API Priority and Fairness system.\n*   **Server-Side Throttling:** The client's default transport automatically handles HTTP `429`\n    responses by reading the `Retry-After` header, waiting, and retrying the request.\n\n## Typed and Dynamic Clients\n\nTo handle the extensible nature of the Kubernetes API, `client-go` provides two primary client\nmodels.\n\nThe **`kubernetes.Clientset`** provides compile-time, type-safe access to core, built-in APIs.\n\nThe **`dynamic.DynamicClient`** represents all objects as `unstructured.Unstructured`, allowing it\nto interact with any API resource, including CRDs. It relies on two discovery mechanisms:\n1.  The **`discovery.DiscoveryClient`** determines *what* resources exist. The\n    **`CachedDiscoveryClient`** is an optimization that caches this data on disk to solve.\n2.  The **OpenAPI schema** (fetched from `/openapi/v3`) describes the *structure* of those\n    resources, providing the schema awareness needed by the dynamic client.\n\n## Code Generation\n\nA core architectural principle of `client-go` is the use of code generation to provide a\nstrongly-typed, compile-time-safe interface for specific API GroupVersions. This makes\ncontroller code more robust and easier to maintain. The tools in `k8s.io/code-generator` produce\nseveral key components:\n\n*   **Typed Clientsets:** The primary interface for interacting with a specific GroupVersion.\n*   **Typed Listers:** The read-only, cached accessors used by controllers.\n*   **Typed Informers:** The machinery for populating the cache for a specific type.\n*   **Apply Configurations:** The type-safe builders for Server-Side Apply.\n\nA contributor modifying a built-in API type **must** run the code generation scripts to update all\nof these dependent components. For the Kubernetes project, `hack/update-codegen.sh` runs code generation.\n\n`sample-controller` shows how code generate can be configured to build custom controllers.\n\n## Controller Infrastructure\n\nThe `tools/cache` package provides the core infrastructure for controllers, replacing a high-load,\nrequest-based pattern with a low-load, event-driven, cached model.\n\nThe data flow is as follows:\n\n```mermaid\ngraph TD\n    subgraph \"Kubernetes API\"\n        API_Server[API Server]\n    end\n\n    subgraph \"client-go: Informer Mechanism\"\n        Reflector(\"1. Reflector\")\n        DeltaFIFO(\"2. DeltaFIFO\")\n        Indexer[\"3. Indexer (Cache)\"]\n        EventHandlers(\"4. Event Handlers\")\n    end\n\n    subgraph \"User Code\"\n        WorkQueue[\"5. Work Queue\"]\n        Controller(\"6. Controller\")\n    end\n\n    API_Server -- LIST/WATCH --> Reflector\n    Reflector -- Puts changes into --> DeltaFIFO\n    DeltaFIFO -- Is popped by internal loop, which updates --> Indexer\n    Indexer -- Update triggers --> EventHandlers\n    EventHandlers -- Adds key to --> WorkQueue\n    WorkQueue -- Is processed by --> Controller\n    Controller -- Reads from cache via Lister --> Indexer\n```\n\nA **`Reflector`** performs a `LIST` to get a consistent snapshot of a resource, identified by a\n`resourceVersion`. It then starts a `WATCH` from that `resourceVersion` to receive a continuous\nstream of subsequent changes. The `Reflector`'s relist/rewatch loop is designed to solve the\n**\"too old\" `resourceVersion` error** by re-listing. To make this recovery more efficient, the\n`Reflector` consumes **watch bookmarks** from the server, which provide a more recent\n`resourceVersion` to restart from.\n\nThe **`Lister`** is the primary, read-only, thread-safe interface for a controller's business\nlogic to access the `Indexer`'s cache.\n\n## Controller Patterns\n\nThe controller infrastructure is architecturally decoupled from the controller's business logic to\nensure resiliency.\n\nThe **`util/workqueue`** creates a critical boundary between event detection (the informer's job)\nand reconciliation (the controller's job). Informer event handlers only add an object's key to the\nwork queue. This allows the controller to retry failed operations with exponential backoff without\nblocking the informer's watch stream.\n\nFor high availability, the **`tools/leaderelection`** package provides the standard architectural\nsolution to ensure single-writer semantics by having replicas compete to acquire a lock on a\nshared `Lease` object.\n\n## Server-Side Apply\n\n`client-go` provides a distinct architectural pattern for object mutation that aligns with the\nserver's declarative model. This is a separate workflow from the traditional `get-modify-update`\nmodel that allows multiple controllers to safely co-manage the same object. The\n**`applyconfigurations`** package provides the generated, type-safe builder API used to\nconstruct the declarative patch.\n\n## Versioning and Compatibility\n\n`client-go` has a strict versioning relationship with the main Kubernetes repository. A `client-go`\nversion `v0.X.Y` corresponds to the Kubernetes version `v1.X.Y`.\n\nThe Kubernetes API has strong backward compatibility guarantees: a client built with an older\nversion of `client-go` will work with a newer API server. However, the reverse is not guaranteed.\nA contributor must not break compatibility with supported versions of the Kubernetes API server.\n</yakaai_skills>"}