KOPRS - Kubernetes Operators Rust
A reusable, ergonomic library that streamlines Kubernetes operator development. By providing generic implementations for the most common operator patterns, it eliminates widespread boilerplate across your codebase. It integrates tightly with the kube-rs ecosystem to handle repetitive operational scaffolding, allowing developers to build reliable controllers with significantly less code.
Architecture Overview
koprs is an opinionated, high-level orchestration framework built directly on top of kube and kube-runtime. While kube provides type-safe Kubernetes API bindings and kube-runtime delivers the controller primitives, koprs abstracts away the repetitive boilerplate required to build production ready controllers.
It encapsulates complex infrastructure orchestration loops, robust Server-Side Apply (SSA) patterns, and automated background garbage collection/cleanup processes out of your controller's core codebase. Additionally, it streamlines state synchronization with ready to use watcher logic and provides a strongly typed error handling model that removes the friction of building custom Kubernetes error variants from scratch. Every generic operation comes out of the box with structured, built-in tracing instrumentation, giving you deep visibility into your controller's execution paths without additional setup.
By lifting these structural requirements off your shoulders, koprs leaves you free to focus purely on your custom business logic.
| |
| () |
|
| |
| () |
|
| |
| () |
Features
- Apply & delete — cluster-scoped and namespaced resources via Server-Side Apply (SSA)
- Get — fetch a single resource by name, returning
Option<T>(Noneon 404) - Status patching — patch the
/statussubresource of any CRD, cluster-scoped or namespaced - Finalizers — add and remove finalizers on cluster-scoped and namespaced resources
- Garbage collection — diff-based GC for orphaned cluster and namespaced resources, with stuck-termination recovery
- Watchers — watch any resource type with optional label filtering, signal-based via
mpsc - Listing — list resources across namespaces or within a namespace, with or without label selectors
- Ownership & controller wiring — build
OwnerReferences, set owner refs on children, generateObjectRefsets, and create mapper closures for cross-resource reconcile triggers - Status conditions —
make_conditionbuilds aConditionwith the current timestamp;upsert_conditionmerges it withlastTransitionTimepreservation. Include conditions in your status struct and patch them withpatch_status_* - Patch labels / annotations — merge labels or annotations onto any resource without replacing existing ones
- Persist to disk — fetch a resource list and write it as JSON to a file
- Typed errors —
KubeGenericErrorenum viathiserror, pattern-matchable by callers
Installation
[]
= { = "../koprs" }
# or once published:
# koprs = "<version>"
Module overview
| Module | Description |
|---|---|
resources |
Apply, delete, get, list, poll, patch labels/annotations, and fetch resources |
status |
Patch /status subresource via SSA; make_condition and upsert_condition helpers |
finalizers |
Add and remove finalizers |
gc |
Garbage collect orphaned resources |
watcher |
Watch resources for changes via mpsc signals |
owners |
Owner references, child wiring, ObjectRef sets, and mapper closures |
scope |
Cluster and Namespaced scope markers for compile-time API selection |
traits |
KubeResource, NamespacedResource, ClusterResource trait aliases |
error |
KubeGenericError enum |
Usage
Most operations come in three forms: _namespaced (most common), _cluster, and a generic scope form that accepts Namespaced("ns") or Cluster. The examples below show the namespaced form; the others follow the same signature.
Apply and delete
use ;
.await?;
// Returns Ok(false) if the resource was already gone
let deleted = .await?;
Finalizers
use ;
// No-op if the finalizer is already present — safe to call on every reconcile.
.await?;
.await?;
Status
Include all status fields — scalars and conditions — in a single patch_status_namespaced call. Using separate patches with the same field manager causes each one to drop the fields from the other on every reconcile, producing an endless watch-event loop.
Preserve lastTransitionTime when the condition status has not changed so the patch is idempotent and does not bump resourceVersion.
use patch_status_namespaced;
use Serialize;
let last_transition_time = cr.status.as_ref
.and_then
.map
.unwrap_or_else;
.await?;
make_condition and upsert_condition from koprs::status are available as pure helpers when you need to build or merge k8s_openapi::Condition values before converting to your CRD's own condition type.
Garbage collection
Accepts a keep-predicate: any resource matching the label selector for which the predicate returns false is deleted.
use gc_namespaced_resources;
.await?;
Watcher
use watch_namespaced_by_label;
use mpsc;
let = channel;
let _handle = .await?;
while let Some = rx.recv.await
List and poll
use ;
use Duration;
let items = .await?;
let names = .await?;
let items = .await?;
Ownership and controller wiring
use ;
use Arc;
let oref = controller_ref?;
set_owner_refs;
let refs = .await?;
let mapper = ;
Labels, annotations, and namespaces
use ;
.await?;
.await?;
ensure_namespace.await?;
Error handling
All functions return Result<T, KubeGenericError>:
KubeGenericError implements std::error::Error via thiserror and composes with the ? operator. Variants are pattern-matchable for cases where you need to handle specific failures — for example, distinguishing a missing resource from a permission error:
use KubeGenericError;
match .await
Testing
Unit tests
Unit tests use tower_test::mock to intercept HTTP requests and inject
hand-crafted JSON responses — no cluster or kubeconfig needed:
Enable log output:
RUST_LOG=koprs=debug
Tests are organised one file per module under src/tests/:
src/tests/
├── mod.rs
├── resources.rs
├── status.rs
├── finalizers.rs
├── gc.rs
├── owners.rs
├── watcher.rs
├── scope.rs
├── traits.rs
└── error.rs
To write your own tests, create a mock (Client, Handle) pair with
tower_test::mock::pair and serve responses from a background task:
use ;
use Body;
use Client;
use json;
use mock;
type MockHandle = Handle;
async
The mock handle serves requests in FIFO order. Functions that make multiple
API calls (such as the GC loop: list → delete → patch) require one
handle.next_request() call per request in the correct sequence.
Integration tests
Integration tests run against a real cluster and are gated behind the
integration feature flag. The test functions are always compiled so type
errors are caught by cargo check, but they only execute when the feature
is enabled:
# Verify the integration tests compile without a cluster
# Create a local cluster
# Run
# Tear down
Each test creates resources with a unique name suffix and cleans up after
itself, so the suite is safe to run with --test-threads greater than one.
License
MIT